Datasets:
AI4M
/

text
stringlengths
0
3.34M
import data.real.sqrt tactic.fin_cases /-! # IMO 2020 A3 -/ namespace IMOSL namespace IMO2020A3 open real private lemma AM_GM_sqrt {a b : ℝ} (h : 0 ≤ a) (h0 : 0 ≤ b) : 2 * sqrt (a * b) ≤ a + b := begin have h1 := two_mul_le_add_sq (sqrt a) (sqrt b), rwa [sq_sqrt h, sq_sqrt h0, mul_assoc, ← sqrt_mul h] at h1 end /-- Final solution -/ theorem final_solution : is_least ((λ x : fin 4 → ℝ, x 0 / x 1 + x 1 / x 2 + x 2 / x 3 + x 3 / x 0) '' {x | (∀ i : fin 4, 0 < x i) ∧ (x 0 + x 2) * (x 1 + x 3) = x 0 * x 2 + x 1 * x 3}) 8 := begin refine ⟨_, λ a h, _⟩, { obtain ⟨c, h, h0⟩ : ∃ c : ℝ, 0 < c ∧ c + 1 / c = 4 := begin have X : 0 < 2 + sqrt 3 := add_pos_of_pos_of_nonneg two_pos (sqrt_nonneg 3), refine ⟨2 + sqrt 3, X, _⟩, rw [add_div' _ _ _ (ne_of_gt X), div_eq_iff (ne_of_gt X), ← sq, add_sq, sq_sqrt, add_assoc, sq, two_mul], change (4 + 4 * sqrt 3 + (2 + 1 + 1) = _), rw [add_assoc (2 : ℝ), add_right_comm, ← bit0, ← bit0, ← mul_two, ← mul_add], norm_num end, have h1 : c ≠ 0 := ne_of_gt h, refine ⟨![c, 1, c, 1], ⟨λ i, _, _⟩, _⟩, fin_cases i; simp; assumption, simp; rw [← mul_two, ← bit0, mul_assoc, ← div_left_inj' h1, add_div, mul_div_cancel_left _ h1, mul_div_cancel_left _ h1, h0, two_mul, ← bit0], simp; rw [inv_eq_one_div, add_assoc, h0, ← bit0] }, { rcases h with ⟨x, ⟨h, h0⟩, rfl⟩; simp only [], rw [add_assoc, add_add_add_comm], have Y : ∀ i j, 0 ≤ x i / x j := λ i j, le_of_lt (div_pos (h i) (h j)), refine le_trans _ (add_le_add (AM_GM_sqrt (Y 0 1) (Y 2 3)) (AM_GM_sqrt (Y 1 2) (Y 3 0))), rw [← mul_add, bit0, ← two_mul, mul_le_mul_left, div_mul_div_comm, div_mul_div_comm], replace Y : ∀ i j, 0 ≤ x i * x j := λ i j, le_of_lt (mul_pos (h i) (h j)), have Z : ∀ i j, sqrt (x i * x j) ≠ 0 := λ i j, sqrt_ne_zero'.mpr (mul_pos (h i) (h j)), rw [sqrt_div (Y 0 2), sqrt_div (Y 1 3), mul_comm (x 2), div_add_div _ _ (Z 1 3) (Z 0 2), ← sq, sq_sqrt (Y 0 2), ← sq, sq_sqrt (Y 1 3), ← h0, mul_comm, le_div_iff, bit0, ← two_mul, mul_mul_mul_comm], clear Y Z; have Y : ∀ i, 0 ≤ x i := λ i, le_of_lt (h i), refine mul_le_mul _ _ (mul_nonneg zero_le_two (sqrt_nonneg _)) (add_nonneg (Y _) (Y _)); exact AM_GM_sqrt (Y _) (Y _), apply mul_pos; rw sqrt_pos; apply mul_pos; exact h _, exact two_pos } end end IMO2020A3 end IMOSL
#include <iostream> #include <boost/date_time.hpp> int main() { std::cout << boost::posix_time::second_clock::universal_time() << " UTC\n"; return 0; }
My first memory of Eero Saarinen‘s work was going to the top of St. Louis’ Gateway Arch in June 1970, when I was 10 years old. Having grown up in suburban Detroit, I later remember gazing at the futuristic looking Design Dome and Watertower at the General Motors Technical Center in Warren, Michigan. The Design Dome at the General Motors Technical Center in Warren, Michigan opened in 1955. The TWA Flight Center opened in 1962 as the original terminal designed by Eero Saarinen for Trans World Airlines at New York City’s John F. Kennedy International Airport.
SUBROUTINE MPYQ (Z ) C C MPYQ IS CALLED ONCE PER EXECUTION OF MPYAD. IT PERFORMS GENERAL C INITIALIZATION FOR EACH OF THE ENTRY POINTS C I.E. SETTING UP MPYAD GO-TO-BRANCHES, ARITH AND BPICK FOR METHOD C 1, AND ARITH2, APICK2 AND BPICK2 FOR METHOD 2 C C ENTRY POINTS - C MPY1V (PERFORMS THE INNER LOOP FOR MPYAD, METHOD 1, C TRANSPOSE AND NON-TRANSPOSE. IT IS CALLED ONCE FOR C EACH COLUMNN OF THE A MATRIX) C MPY2NV (PERFORMS THE INNER LOOP FOR THE NON-TRANSPOSE CASE C OF METHOD 2. IT IS CALLED ONCE FOR EACH COUMN OF C THE B MATRIX) C MPY2TV (SAME AS MPY2NV, EXECPT IT IS FOR THE TRANSPOSE C CASE) C MPY3T (PERFORMS THE INNER LOOP FOR THE TRANSPOSE CASE OF C METHOD 3. IT IS CALLED ONCE FOR EACH COLUMN OF THE C B MATRIX) C (WHERE V STANDS FOR VAX VERSION, AND T IS THE TRANSPOSE FLAG) C C THE MPYi ROUTINES PERFORM THE MATRIX MULTIPLICATION AND ADDITION C FOR THE MPYAD INNER LOOPS C C (+/-)A * B (+/-)C = D OR (+/-)A(T) * B (+/-)C = D C C C LAST REVISED BY G.CHAN/UNISYS 1/91 C (1) MPY3T WAS PREVIOUSLY A .MDS SUBROUTINE. IT IS NOW AN ENTRY C POINT IN THIS MPYQ ROUTINE C (MPY3T IS AN ENTRY POINT IN MPYQ, IN IBM AND CDC VERSIONS) C (2) TO IMPROVE MPYAD INNER LOOP LOGIC FOR THE COMMON CASES C C IMPLICIT INTEGER (A-Z) REAL A(4) ,B(4) ,D(4) ,Z(1) ,AA(4) ,AAA , 1 BSR ,AAS(1) ,DDS(1) ,BBB ,BSI ,BBS DOUBLE PRECISION AD(2) ,BD(2) ,DD(2) ,ZD(1) ,ADD(2),BDR , 1 BDI ,AAD(1) ,DDD(1) ,BBD(1) DIMENSION ZZ(1) COMMON /MPYADX/ FILEA(7),FILEB(7),FILEC(7),FILED(7),NZ ,T , 1 SIGNAB ,SIGNC ,PREC1 ,SCRTCH ,TIME 2 /SYSTEM/ KSYSTM(65) 3 /TYPE / PRC(2) ,NWDS(4) ,RC(4) 4 /NAMES / RD ,RDREW ,WRT ,WRTREW ,CLSREW,CLS 5 /ZBLPKX/ D ,DROW 6 /ZNTPKX/ A ,I ,EOL ,EOR 7 /PACKX / TYPED ,TYPD1 ,ONE1 ,PP1 ,INCR1 8 /UNPAKX/ TYPEBD ,ONE2 ,PP2 ,INCR2 COMMON /MPYADZ/ RCB ,RCD ,LL ,LLL ,JB ,NBX , 1 NDX ,JMAX1X ,ACOL ,ACOL1 ,ACOLN ,ACORE, 2 APOINT ,BCOL ,CROW ,FIRSTL ,NA ,NB , 3 ND ,NWDA ,NWDB ,NWDD ,PREC ,JMAX , 4 INCRA ,BLOCK(20) COMMON /MPYQT4/ RCA ,PRCA ,ALL4 ,JUMP4 ,PREC4 COMMON /ZZZZZZ/ BBS(17000) EQUIVALENCE (KSYSTM( 1),SYSBUF) ,(KSYSTM( 2),MOUT ) , 1 (KSYSTM(58),IPASS ) EQUIVALENCE (A(1) ,AD(1) ) ,(B(1) ,BD(1)) , 1 (D(1) ,DD(1) ) ,(FILEA(2),M ) , 2 (FILEA(3),N ) ,(FILEA(5),TYPEA ) , 3 (FILEB(2),Q ) ,(FILEB(3),R ) , 4 (FILEB(5),TYPEB ) ,(FILEC(5),TYPEC ) , 5 (FILED(5),TYPD ) ,(NZZ ,BUF1 ) , 6 (ACOLN ,AROWN ) ,(AA(1) ,ADD(1) ) , 7 (ACOL1 ,AROW1 ) ,(ACOL ,AROW ) , 8 (BBS(1) ,BBD(1) ) EQUIVALENCE (BLOCK(2),TYPE ) ,(BLOCK(3),FORM ) , 1 (BLOCK(4),ROW, J3 ) ,(BLOCK(5),POINT ) , 2 (BLOCK(6),NBRSTR ) ,(BLOCK(8),FLAG ) EQUIVALENCE (BLOCK(5),JB31 ) ,(BLOCK(6),NTERM3 ) , 1 (BLOCK(7),JB3N ) ,(BLOCK(8),B3FLAG ) C DATA MASK6F / X'00FFFFFF' / DATA MASK6F / 16777215 / C C MASK6F= '00FFFFFF'X (OR X'00FFFFFF') = 16777215 C RCB = 1 IF B IS REAL,2 IF B IS COMPLEX C NWDB = NUMBER OF WORDS PER ELEMENT OF B C NBX = NUMBER OF ELEMENTS PER COLUMN OF B C NB = NUMBER OF WORDS PER COLUMN OF B C NDX = NUMBER OF ELEMENTS PER COLUMN OF C AND D C ND = NUMBER OF WORDS PER COLUMN OF C AND D C NZZ = BUF1 = POINTER TO FIRST GINO BUFFER C BUF2 = POINTER TO SECOND GINO BUFFER C BUF3 = POINTER TO THIRD GINO BUFFER C JJ = MAX. NO. OF COLUMNS OF B AND D THAT MAY BE HELD IN CORE C MPASS1= NUMBER OF PASSES REQUIRED FOR METHOD ONE C JZB = POINTER TO FIRST ELEMENT OF B FOR SP REFERENCE C JZDB = POINTER TO FIRST ELEMENT OF B FOR DP REFERENCE C JB = POINTER TO FIRST ELEMENT OF B FOR PRECISION OF PROBLEM C NWDA = NUMBER OF WORDS PER ELEMENT OF A C NWDD = NUMBER OF WORDS PER ELEMENT OF D C ACORE = POINTER TO FIRST WORD FOR STORAGE OF PACKED COLUMNS C OF A MATRIX FOR METHOD TWO C***** RCA = RC(TYPEA) MODB = MOD(TYPEB,2) MODA = MOD(TYPEA,2) PRCA = PRC(TYPEA) FA3 = FILEA(3) C C IF DIAG 43 IS ON, SKIP ALL (1991) SPEED IMPROVEMENT LOGIC C (THIS IS ONLY TEMPORARY) C ALL = 0 IF (TYPEA.EQ.TYPEB .AND. TYPEA.EQ.TYPED) ALL = TYPEA ALL4 = ALL IF (ALL4 .EQ. 0) ALL4 = 5 IF (TYPED.GE.3 .AND. TYPEA.LE.2 .AND. TYPEB.LE.2) ALL4 = 6 CALL SSWTCH (43,J) IF (J .EQ. 1) ALL = 0 JUMP4 = TYPEB + (TYPEA-1)*4 PREC4 = PREC1 - 1 C C RCA, PRCA, ALL4 AND JUMP4 ARE USED IN MPY4T C GO TO (20,40,100,300), TYPED C C REAL SINGLE PRECISION C 20 ASSIGN 840 TO ARITH ASSIGN 750 TO BPICK IF (T .NE. 0) GO TO 30 C ASSIGN 1210 TO ARITH2 ASSIGN 1010 TO BPICK2 ASSIGN 1100 TO APICK2 GO TO 600 C 30 ASSIGN 1600 TO ARITH2 ASSIGN 1400 TO BPICK2 ASSIGN 1500 TO APICK2 GO TO 600 C C REAL DOUBLE PRECISION C 40 ASSIGN 850 TO ARITH ASSIGN 770 TO BPICK IF (MODB .EQ. 1) ASSIGN 790 TO BPICK IF (T .NE. 0) GO TO 60 C ASSIGN 1220 TO ARITH2 ASSIGN 1030 TO BPICK2 IF (MODB .EQ. 1) ASSIGN 1050 TO BPICK2 ASSIGN 1120 TO APICK2 50 IF (MODA .EQ. 1) ASSIGN 1140 TO APICK2 GO TO 600 C 60 ASSIGN 1610 TO ARITH2 ASSIGN 1420 TO BPICK2 IF (MODB .EQ. 1) ASSIGN 1440 TO BPICK2 ASSIGN 1520 TO APICK2 70 IF (MODA .EQ. 1) ASSIGN 1540 TO APICK2 GO TO 600 C C COMPLEX SINGLE PRECISION C 100 ASSIGN 860 TO ARITH GO TO (110,110,120,130), TYPEB 110 ASSIGN 750 TO BPICK GO TO 140 120 ASSIGN 760 TO BPICK GO TO 140 130 ASSIGN 810 TO BPICK 140 IF (T .NE. 0) GO TO 220 C ASSIGN 1230 TO ARITH2 GO TO (150,150,160,170), TYPEB 150 ASSIGN 1010 TO BPICK2 GO TO 180 160 ASSIGN 1020 TO BPICK2 GO TO 180 170 ASSIGN 1070 TO BPICK2 180 GO TO (190,190,200,210), TYPEA 190 ASSIGN 1100 TO APICK2 GO TO 600 200 ASSIGN 1110 TO APICK2 GO TO 600 210 ASSIGN 1160 TO APICK2 GO TO 600 220 ASSIGN 1620 TO ARITH2 C GO TO (230,230,240,250), TYPEB 230 ASSIGN 1400 TO BPICK2 GO TO 260 240 ASSIGN 1410 TO BPICK2 GO TO 260 250 ASSIGN 1460 TO BPICK2 260 GO TO (270,270,280,290), TYPEA 270 ASSIGN 1500 TO APICK2 GO TO 600 280 ASSIGN 1510 TO APICK2 GO TO 600 290 ASSIGN 1560 TO APICK2 GO TO 600 C C COMPLEX DOUBLE PRECISION C 300 ASSIGN 870 TO ARITH GO TO (310,320,330,340), TYPEB 310 ASSIGN 790 TO BPICK GO TO 350 320 ASSIGN 770 TO BPICK GO TO 350 330 ASSIGN 800 TO BPICK GO TO 350 340 ASSIGN 780 TO BPICK 350 IF (T .NE. 0) GO TO 440 C ASSIGN 1240 TO ARITH2 GO TO (360,370,380,390), TYPEB 360 ASSIGN 1050 TO BPICK2 GO TO 400 370 ASSIGN 1030 TO BPICK2 GO TO 400 380 ASSIGN 1060 TO BPICK2 GO TO 400 390 ASSIGN 1040 TO BPICK2 400 GO TO (50,410,420,430), TYPEA 410 ASSIGN 1120 TO APICK2 GO TO 600 420 ASSIGN 1150 TO APICK2 GO TO 600 430 ASSIGN 1130 TO APICK2 GO TO 600 C 440 ASSIGN 1630 TO ARITH2 GO TO (450,460,470,480), TYPEB 450 ASSIGN 1440 TO BPICK2 GO TO 490 460 ASSIGN 1420 TO BPICK2 GO TO 490 470 ASSIGN 1450 TO BPICK2 GO TO 490 480 ASSIGN 1430 TO BPICK2 490 GO TO (70,500,510,520), TYPEA 500 ASSIGN 1520 TO APICK2 GO TO 600 510 ASSIGN 1550 TO APICK2 GO TO 600 520 ASSIGN 1530 TO APICK2 C C MPYQ INITIALIZATION DONE C 600 RETURN C C ENTRY MPY1V (ZZ ,Z ,ZD ) C ===================== C C METHOD 1 (TRANSPOSE AND NON-TRANSPOSE) C 700 B (2) = 0. BD(2) = 0.D0 710 CALL ZNTPKI I1 = I - 1 IF (T) 730,720,730 720 K1 = LL K2 = I1*RCD + 1 GO TO 740 730 K1 = I1*RCB + JB K2 = LLL 740 K3 = K2 + JMAX1X IF (ALL .NE. 0) GO TO (900,920,940,960), ALL DO 880 K = K2,K3,NDX J = K1 GO TO BPICK, (750,760,770,780,790,800,810) 750 IF (Z(J) .EQ. 0.0) GO TO 880 B(1) = Z(J) GO TO 830 760 IF (Z(J).EQ.0.0 .AND. Z(J+1).EQ.0.0) GO TO 880 B(1) = Z(J ) B(2) = Z(J+1) GO TO 830 770 IF (ZD(J) .EQ. 0.D0) GO TO 880 BD(1) = ZD(J) GO TO 830 780 IF (ZD(J).EQ.0.D0 .AND. ZD(J+1).EQ.0.D0) GO TO 880 BD(1) = ZD(J ) BD(2) = ZD(J+1) GO TO 830 790 IF (Z(J) .EQ. 0.0) GO TO 880 BD(1) = Z(J) GO TO 830 800 IF (Z(J).EQ.0.0 .AND. Z(J+1).EQ.0.0) GO TO 880 BD(1) = Z(J ) BD(2) = Z(J+1) GO TO 830 810 IF (ZD(J).EQ.0.D0 .AND. ZD(J+1).EQ.0.D0) GO TO 880 B(1) = ZD(J ) B(2) = ZD(J+1) C 830 GO TO ARITH, (840,850,860,870) 840 Z(K) = Z(K) + A(1)*B(1) GO TO 880 850 ZD(K) = ZD(K) + AD(1)*BD(1) GO TO 880 860 Z(K ) = Z(K ) + A(1)*B(1) - A(2)*B(2) Z(K+1) = Z(K+1) + A(1)*B(2) + A(2)*B(1) GO TO 880 870 ZD(K ) = ZD(K ) + AD(1)*BD(1) - AD(2)*BD(2) ZD(K+1) = ZD(K+1) + AD(1)*BD(2) + AD(2)*BD(1) 880 K1 = K1 + NBX IF (EOL) 980,710,980 C C COMMON CASES (TYPEA=TYPEB=TYPED=PREC) C C PREC=1, ARITH(840) AND BPICK(750) C PREC=2, ARITH(850) AND BPICK(770) C PREC=3, ARITH(860) AND BPICK(760) C PREC=4, ARITH(870) AND BPICK(780) C 900 DO 910 K = K2,K3,NDX Z(K) = Z(K) + A(1)*Z(K1) 910 K1 = K1 + NBX IF (EOL) 980,710,980 920 DO 930 K = K2,K3,NDX ZD(K) = ZD(K) + AD(1)*ZD(K1) 930 K1 = K1 + NBX IF (EOL) 980,710,980 940 DO 950 K = K2,K3,NDX Z(K ) = Z(K ) + A(1)*Z(K1 ) - A(2)*Z(K1+1) Z(K+1) = Z(K+1) + A(1)*Z(K1+1) + A(2)*Z(K1 ) 950 K1 = K1 + NBX IF (EOL) 980,710,980 960 DO 970 K = K2,K3,NDX ZD(K ) = ZD(K ) + AD(1)*ZD(K1 ) - AD(2)*ZD(K1+1) ZD(K+1) = ZD(K+1) + AD(1)*ZD(K1+1) + AD(2)*ZD(K1 ) 970 K1 = K1 + NBX IF (EOL) 980,710,980 980 RETURN C C ENTRY MPY2NV (ZZ ,Z ,ZD ) C ====================== C C METHOD 2 NON-TRANSPOSE CASE C B(2) = 0. BD(2) = 0.D0 AA(2) = 0. ADD(2)= 0.D0 L = FIRSTL ACOL = ACOL1 1000 CALL ZNTPKI IF (I.LT.ACOL1 .OR. I.GT.ACOLN .OR. I.LT.ACOL) GO TO 1290 L = L - 2*(I-ACOL) ACOL = I APOINT= ZZ(L) IF (APOINT .EQ. 0) GO TO 1280 NBR = ZZ(L-1) IF (ALL .NE. 0) GO TO (1260,1265,1270,1275), ALL GO TO BPICK2, (1010,1020,1030,1040,1050,1060,1070) 1010 B(1) = A(1) GO TO 1090 1020 B(1) = A(1) B(2) = A(2) GO TO 1090 1030 BD(1) = AD(1) GO TO 1090 1040 BD(1) = AD(1) BD(2) = AD(2) GO TO 1090 1050 BD(1) = A(1) GO TO 1090 1060 BD(1) = A(1) BD(2) = A(2) GO TO 1090 1070 B(1) = AD(1) B(2) = AD(2) C 1090 NBRSTR = ZZ( APOINT+1 ) INIT = ZZ( APOINT ) APOINT = APOINT + 2 J = APOINT IF ( PRCA .EQ. 2 ) J = J/2 + 1 APOINT = APOINT+ NBRSTR*NWDA IROW = INIT*RCD - RCD + 1 NROW = IROW + NBRSTR*RCD - 1 DO 1250 K = IROW,NROW,RCD GO TO APICK2, (1100,1110,1120,1130,1140,1150,1160) 1100 AA(1) = Z(J) GO TO 1200 1110 AA(1) = Z(J ) AA(2) = Z(J+1) GO TO 1200 1120 ADD(1)= ZD(J) GO TO 1200 1130 ADD(1)= ZD(J ) ADD(2)= ZD(J+1) GO TO 1200 1140 ADD(1)= Z(J) GO TO 1200 1150 ADD(1)= Z(J ) ADD(2)= Z(J+1) GO TO 1200 1160 AA(1) = ZD(J ) AA(2) = ZD(J+1) C 1200 GO TO ARITH2, (1210,1220,1230,1240) 1210 Z(K) = Z(K) + AA(1)*B(1) GO TO 1250 1220 ZD(K) = ZD(K) + ADD(1)*BD(1) GO TO 1250 1230 Z(K )= Z(K ) + AA(1)*B(1) - AA(2)*B(2) Z(K+1)= Z(K+1) + AA(1)*B(2) + AA(2)*B(1) GO TO 1250 1240 ZD(K ) = ZD(K ) + ADD(1)*BD(1) - ADD(2)*BD(2) ZD(K+1) = ZD(K+1) + ADD(1)*BD(2) + ADD(2)*BD(1) 1250 J = J + RCA NBR = NBR - 1 IF (NBR) 1280,1280,1090 C C COMMON CASES (TYPEA=TYPEB=TYPED=PREC) C C PREC=1, ARITH2(1210), APICK2(1100) AND BPICK2(1010) C PREC=2, ARITH2(1220), APICK2(1120) AND BPICK2(1030) C PREC=3, ARITH2(1230), APICK2(1110) AND BPICK2(1020) C PREC=4, ARITH2(1620), APICK2(1510) AND BPICK2(1410) C 1260 NBRSTR = ZZ( APOINT+1 ) INIT = ZZ( APOINT ) APOINT = APOINT + 2 J = APOINT IF ( PRCA .EQ. 2 ) J = J/2 + 1 APOINT = APOINT+ NBRSTR*NWDA IROW = INIT*RCD - RCD + 1 NROW = IROW + NBRSTR*RCD - 1 DO 1262 K = IROW,NROW,RCD Z(K) = Z(K) + Z(J)*A(1) 1262 J = J + RCA NBR = NBR - 1 IF (NBR) 1280,1280,1260 C 1265 NBRSTR = ZZ( APOINT+1 ) INIT = ZZ( APOINT ) APOINT = APOINT + 2 J = APOINT IF ( PRCA .EQ. 2 ) J = J/2 + 1 APOINT = APOINT+ NBRSTR*NWDA IROW = INIT*RCD - RCD + 1 NROW = IROW + NBRSTR*RCD - 1 DO 1267 K = IROW,NROW,RCD ZD(K) = ZD(K) + ZD(J)*AD(1) 1267 J = J + RCA NBR = NBR - 1 IF (NBR) 1280,1280,1265 C 1270 NBRSTR = ZZ( APOINT+1 ) INIT = ZZ( APOINT ) APOINT = APOINT + 2 J = APOINT IF ( PRCA .EQ. 2 ) J = J/2 + 1 APOINT = APOINT+ NBRSTR*NWDA IROW = INIT*RCD - RCD + 1 NROW = IROW + NBRSTR*RCD - 1 DO 1272 K = IROW,NROW,RCD Z(K ) = Z(K ) + Z(J)*A(1) - Z(J+1)*A(2) Z(K+1) = Z(K+1) + Z(J)*A(2) + Z(J+1)*A(1) 1272 J = J + RCA NBR = NBR - 1 IF (NBR) 1280,1280,1270 C 1275 NBRSTR = ZZ( APOINT+1 ) INIT = ZZ( APOINT ) APOINT = APOINT + 2 J = APOINT IF ( PRCA .EQ. 2 ) J = J/2 + 1 APOINT = APOINT+ NBRSTR*NWDA IROW = INIT*RCD - RCD + 1 NROW = IROW + NBRSTR*RCD - 1 DO 1277 K = IROW,NROW,RCD ZD(K ) = ZD(K ) + ZD(J)*AD(1) - ZD(J+1)*AD(2) ZD(K+1) = ZD(K+1) + ZD(J)*AD(2) + ZD(J+1)*AD(1) 1277 J = J + RCA NBR = NBR - 1 IF (NBR) 1280,1280,1275 C 1280 L = L - 2 ACOL = ACOL + 1 1290 IF (EOL .EQ. 0) GO TO 1000 RETURN C C ENTRY MPY2TV (ZZ ,Z ,ZD ) C ====================== C C METHOD 2 - TRANSPOSE CASE C C COMMENTS FROM G.CHAN/UNISYS 1/91 C OBSERVE THAT THERE IS NO DO-LOOP IN THIS MPY2TV LOGIC. IT IS C THEREFORE CONCLUDED THAT THE TRANSPOSE CASE WOULD TAKE MUCH MORE C TIME THAN THE NON-TRANSPOSE CASE C B(2) = 0. BD(2) = 0.D0 AA(2) = 0. ADD(2)= 0.D0 DD(1) = 0.D0 DD(2) = 0.D0 L = FIRSTL APOINT= ZZ(L) AROW = AROW1 IF (CROW .EQ. MASK6F) GO TO 1350 GO TO 1330 1300 APOINT = ZZ(L) IF (CROW-AROW) 1320,1340,1350 1310 DROW = CROW CALL ZBLPKI 1320 IF (EOL .NE. 0) GO TO 1350 1330 CALL ZNTPKI CROW = I 1340 DD(1) = AD(1) DD(2) = AD(2) IF (CROW-AROW) 1310,1360,1350 1350 DD(1) = 0.D0 DD(2) = 0.D0 IF (APOINT .EQ. 0) GO TO 1690 1360 DROW = AROW IF (APOINT .EQ. 0) GO TO 1680 NBRSTR= ZZ(L-1) 1370 NBR = ZZ( APOINT+1 ) NBR1 = NBR INIT = ZZ( APOINT ) APOINT = APOINT + 2 J = APOINT IF ( PRCA .GT. 1 ) J = J/2 + 1 APOINT = APOINT + NBR*NWDA K = (INIT-1)*RCB + 1 1380 IF (ALL .NE. 0) GO TO (1640,1645,1650,1655), ALL GO TO BPICK2, (1400,1410,1420,1430,1440,1450,1460) 1400 B(1) = Z(K) GO TO 1470 1410 B(1) = Z(K ) B(2) = Z(K+1) GO TO 1470 1420 BD(1) = ZD(K) GO TO 1470 1430 BD(1) = ZD(K ) BD(2) = ZD(K+1) GO TO 1470 1440 BD(1) = Z(K) GO TO 1470 1450 BD(1) = Z(K ) BD(2) = Z(K+1) GO TO 1470 1460 B(1) = ZD(K ) B(2) = ZD(K+1) C 1470 GO TO APICK2, (1500,1510,1520,1530,1540,1550,1560) 1500 AA(1) = Z(J) GO TO 1570 1510 AA(1) = Z(J ) AA(2) = Z(J+1) GO TO 1570 1520 ADD(1)= ZD(J) GO TO 1570 1530 ADD(1)= ZD(J ) ADD(2)= ZD(J+1) GO TO 1570 1540 ADD(1)= Z(J) GO TO 1570 1550 ADD(1)= Z(J ) ADD(2)= Z(J+1) GO TO 1570 1560 AA(1) = Z(J ) AA(2) = Z(J+2) C 1570 GO TO ARITH2, (1600,1610,1620,1630) 1600 D(1) = D(1) + AA(1)*B(1) GO TO 1660 1610 DD(1) = DD(1) + ADD(1)*BD(1) GO TO 1660 1620 D(1) = D(1) + AA(1)*B(1) - AA(2)*B(2) D(2) = D(2) + AA(1)*B(2) + AA(2)*B(1) GO TO 1660 1630 DD(1) = DD(1) + ADD(1)*BD(1) - ADD(2)*BD(2) DD(2) = DD(2) + ADD(1)*BD(2) + ADD(2)*BD(1) GO TO 1660 C C COMMON CASES (TYPEA=TYPEB=TYPED=PREC) C C PREC=1, ARITH2(1600), APICK2(1500) AND BPICK2(1400) C PREC=2, ARITH2(1610), APICK2(1520) AND BPICK2(1420) C PREC=3, ARITH2(1620), APICK2(1510) AND BPICK2(1410) C PREC=4, ARITH2(1630), APICK2(1530) AND BPICK2(1430) C 1640 D(1) = D(1) + Z(J)*Z(K) J = J + RCA K = K + RCB NBR = NBR - 1 IF (NBR) 1670,1670,1640 C 1645 DD(1) = DD(1) + ZD(J)*ZD(K) J = J + RCA K = K + RCB NBR = NBR - 1 IF (NBR) 1670,1670,1645 C 1650 D(1) = D(1) + Z(J)*Z(K ) - Z(J+1)*Z(K+1) D(2) = D(2) + Z(J)*Z(K+1) + Z(J+1)*Z(K ) J = J + RCA K = K + RCB NBR = NBR - 1 IF (NBR) 1670,1670,1650 C 1655 DD(1) = DD(1) + ZD(J)*ZD(K ) - ZD(J+1)*ZD(K+1) DD(2) = DD(2) + ZD(J)*ZD(K+1) + ZD(J+1)*ZD(K ) J = J + RCA K = K + RCB NBR = NBR - 1 IF (NBR) 1670,1670,1655 C 1660 J = J + RCA K = K + RCB NBR = NBR - 1 IF (NBR .GT. 0) GO TO 1380 1670 NBRSTR = NBRSTR - 1 IF (NBRSTR .GT. 0) GO TO 1370 1680 CALL ZBLPKI 1690 L = L - 2 AROW = AROW + 1 IF (AROW .LE. AROWN) GO TO 1300 RETURN C C ENTRY MPY3T (*,AAS ,AAD ,DDS ,DDD ) C =============================== C C METHOD 3 (TRANSPOSE ONLY) C B3FLAG = -1 CALL GETSTR (*2400,BLOCK) CIBMNB 6/93 IF ( BLOCK( 2 ) .EQ. TYPEB ) GO TO 1699 TYPEB = BLOCK( 2 ) RCB = RC( TYPEB ) ALL = 0 1699 CONTINUE CIBMNE 6/93 IF (ALL .NE. 0) GO TO (1760,1920,2060,2270), ALL GO TO (1700,1800,2000,2100), TYPED C C PERFORM ARITHMETIC IN REAL SINGLE PRECISION C 1700 JB3N = JB31 + NTERM3 - 1 DO 1740 JB3 = JB31,JB3N K = J3 BBB = BBS(JB3) IF (BLOCK(2) .EQ. 2) BBB = BBD(JB3) IF (TYPEA .NE. 2) GO TO 1720 DO 1710 I = AROW1,AROWN AAA = AAD(K) DDS(I) = DDS(I) + AAA*BBB 1710 K = K + NA GO TO 1740 1720 DO 1730 I = AROW1,AROWN DDS(I) = DDS(I) + AAS(K)*BBB 1730 K = K + NA 1740 J3 = J3 + 1 CALL ENDGET (BLOCK) CALL GETSTR (*2500,BLOCK) GO TO 1700 C C COMMON CASE (TYPEA=TYPEB=TYPED=PREC=1) C 1760 JB3N = JB31 + NTERM3 - 1 DO 1780 JB3 = JB31,JB3N K = J3 DO 1770 I = AROW1,AROWN DDS(I) = DDS(I) + AAS(K)*BBS(JB3) 1770 K = K + NA 1780 J3 = J3 + 1 CALL ENDGET (BLOCK) CALL GETSTR (*2500,BLOCK) GO TO 1760 C C PERFORM ARITHMETIC IN REAL DOUBLE PRECISION C 1800 K1 = 2*(PRCA-1) + PRC(TYPEB) 1810 JB3N = JB31 + NTERM3 - 1 DO 1900 JB3 = JB31,JB3N K = J3 GO TO (1820,1840,1860,1880), K1 1820 DO 1830 I = AROW1,AROWN DDD(I) = DDD(I) + AAS(K)*BBS(JB3) 1830 K = K + FA3 GO TO 1900 1840 DO 1850 I = AROW1,AROWN DDD(I) = DDD(I) + AAS(K)*BBD(JB3) 1850 K = K + FA3 GO TO 1900 1860 DO 1870 I = AROW1,AROWN DDD(I) = DDD(I) + AAD(K)*BBS(JB3) 1870 K = K + FA3 GO TO 1900 1880 DO 1890 I = AROW1,AROWN DDD(I) = DDD(I) + AAD(K)*BBD(JB3) 1890 K = K + FA3 1900 J3 = J3 + 1 CALL ENDGET (BLOCK) CALL GETSTR (*2500,BLOCK) GO TO 1810 C C COMMON CASE (TYPEA=TYPEB=TYPED=PREC=2) C 1920 JB3N = JB31 + NTERM3 - 1 DO 1940 JB3 = JB31,JB3N K = J3 DO 1930 I = AROW1,AROWN DDD(I) = DDD(I) + AAD(K)*BBD(JB3) 1930 K = K + FA3 1940 J3 = J3 + 1 CALL ENDGET (BLOCK) CALL GETSTR (*2500,BLOCK) GO TO 1920 C C PERFORM ARITHMETIC IN COMPLEX SINGLE PRECISION C 2000 BSI = 0. I1 = 2*AROW1 - 1 IN = 2*AROWN - 1 2010 IF (RCA .EQ. 2) J3 = 2*J3 - 1 JB3N = JB31 + RCB*NTERM3 - RCB DO 2050 JB3 = JB31,JB3N,RCB BSR = BBS(JB3) IF (RCB .EQ. 2) BSI = BBS(JB3+1) K = J3 IF (RCA .EQ. 2) GO TO 2030 DO 2020 I = I1,IN,2 DDS(I ) = DDS(I ) + AAS(K)*BSR DDS(I+1) = DDS(I+1) + AAS(K)*BSI 2020 K = K + NA GO TO 2050 2030 DO 2040 I = I1,IN,2 DDS(I ) = DDS(I ) + AAS(K)*BSR - AAS(K+1)*BSI DDS(I+1) = DDS(I+1) + AAS(K)*BSI + AAS(K+1)*BSR 2040 K = K + NA 2050 J3 = J3 + RCA CALL ENDGET (BLOCK) CALL GETSTR (*2500,BLOCK) GO TO 2010 C C COMMON CASE (TYPEA=TYPEB=TYPED=PREC=3) C 2060 I1 = 2*AROW1 - 1 IN = 2*AROWN - 1 2070 J3 = 2*J3 - 1 JB3N = JB31 + RCB*NTERM3 - RCB DO 2090 JB3 = JB31,JB3N,RCB K = J3 DO 2080 I = I1,IN,2 DDS(I ) = DDS(I ) + AAS(K)*BBS(JB3 ) - AAS(K+1)*BBS(JB3+1) DDS(I+1) = DDS(I+1) + AAS(K)*BBS(JB3+1) + AAS(K+1)*BBS(JB3 ) 2080 K = K + NA 2090 J3 = J3 + RCA CALL ENDGET (BLOCK) CALL GETSTR (*2500,BLOCK) GO TO 2070 C C PERFORM ARITHMETIC IN COMPLEX DOUBLE PRECISION C 2100 BDI = 0. INCA= RCA*FA3 I1 = 2*AROW1 - 1 IN = 2*AROWN - 1 2110 IF (RCA .EQ. 2) J3 = 2*J3 - 1 JB3N = JB31 + RCB*NTERM3 - RCB DO 2260 JB3 = JB31,JB3N,RCB K = J3 GO TO (2120,2130,2140,2150), TYPEB 2120 BDR = BBS(JB3) GO TO 2160 2130 BDR = BBD(JB3) GO TO 2160 2140 BDR = BBS(JB3 ) BDI = BBS(JB3+1) GO TO 2160 2150 BDR = BBD(JB3 ) BDI = BBD(JB3+1) 2160 GO TO (2170,2190,2210,2230), TYPEA 2170 DO 2180 I = I1,IN,2 DDD(I ) = DDD(I ) + AAS(K)*BDR DDD(I+1) = DDD(I+1) + AAS(K)*BDI 2180 K = K + INCA GO TO 2250 2190 DO 2200 I = I1,IN,2 DDD(I ) = DDD(I ) + AAD(K)*BDR DDD(I+1) = DDD(I+1) + AAD(K)*BDI 2200 K = K + INCA GO TO 2250 2210 DO 2220 I = I1,IN,2 DDD(I ) = DDD(I ) + AAS(K)*BDR - AAS(K+1)*BDI DDD(I+1) = DDD(I+1) + AAS(K)*BDI + AAS(K+1)*BDR 2220 K = K + INCA GO TO 2250 2230 DO 2240 I = I1,IN,2 DDD(I ) = DDD(I ) + AAD(K)*BDR - AAD(K+1)*BDI DDD(I+1) = DDD(I+1) + AAD(K)*BDI + AAD(K+1)*BDR 2240 K = K + INCA 2250 J3 = J3 + RCA 2260 CONTINUE CALL ENDGET (BLOCK) CALL GETSTR (*2500,BLOCK) GO TO 2110 C C COMMON CASE (TYPEA=TYPEB=TYPED=PREC=4) C 2270 INCA= RCA*FA3 I1 = 2*AROW1 - 1 IN = 2*AROWN - 1 2280 J3 = 2*J3 - 1 JB3N = JB31 + RCB*NTERM3 - RCB DO 2300 JB3 = JB31,JB3N,RCB K = J3 DO 2290 I = I1,IN,2 DDD(I ) = DDD(I ) + AAD(K)*BBD(JB3 ) - AAD(K+1)*BBD(JB3+1) DDD(I+1) = DDD(I+1) + AAD(K)*BBD(JB3+1) + AAD(K+1)*BBD(JB3 ) 2290 K = K + INCA 2300 J3 = J3 + RCA CALL ENDGET (BLOCK) CALL GETSTR (*2500,BLOCK) GO TO 2280 C 2400 RETURN 1 2500 RETURN END
utc_time <- strptime(utc_time_str, "%b. %d, %H:%M:%S UTC") strftime(utc_time, "%A, %d %B %Y, %H:%M:%S")
(* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) (* Error monad *) Require Import Ascii. Require Import String. Require Import List. Require Import ZArith. Require Import ErgoSpec.Utils.Misc. Require Import ErgoSpec.Backend.QLib. Require Import ErgoSpec.Common.Provenance. Require Import ErgoSpec.Common.Names. Require Import ErgoSpec.Common.Ast. Section Result. Inductive eerror : Set := | ESystemError : provenance -> string -> eerror | EParseError : provenance -> string -> eerror | ECompilationError : provenance -> string -> eerror | ETypeError : provenance -> string -> eerror | ERuntimeError : provenance -> string -> eerror. Inductive ewarning : Set := | EWarning : provenance -> string -> ewarning. Definition eresult (A:Set) := Result (A * list ewarning) eerror. Definition esuccess {A:Set} (a:A) (l:list ewarning) : eresult A := Success (A * list ewarning) eerror (a,l). Definition efailure {A:Set} (e:eerror) : eresult A := Failure (A * list ewarning) eerror e. Section Lift. Definition eolift {A B:Set} (f:A -> eresult B) (a:eresult A) : eresult B := lift_failure (fun xw : (A * list ewarning) => let (x,w) := xw in lift_failure_in (fun xw' : (B * list ewarning) => let (x',w') := xw' in (x',w ++ w')) (f x)) a. Definition eolift_warning {A B:Set} (f:A * list ewarning -> eresult B) (a:eresult A) : eresult B := lift_failure f a. Definition elift {A B:Set} (f:A -> B) (a:eresult A) : eresult B := lift_failure_in (fun xw : (A * list ewarning) => let (x,w) := xw in (f x, w)) a. Definition elift_warning {A B:Set} (f:A * list ewarning -> B) (a:eresult A) : eresult B := lift_failure_in (fun xw : (A * list ewarning) => (f xw, snd xw)) a. Definition elift2 {A B C:Set} (f:A -> B -> C) (a:eresult A) (b:eresult B) : eresult C := eolift (fun x => elift (fun y => f x y) b) a. Definition elift3 {A B C D:Set} (f:A -> B -> C -> D) (a:eresult A) (b:eresult B) (c:eresult C) : eresult D := eolift (fun x => elift2 (fun y z => f x y z) b c) a. Definition elift4 {A B C D E:Set} (f:A -> B -> C -> D -> E) (a:eresult A) (b:eresult B) (c:eresult C) (d:eresult D) : eresult E := eolift (fun x => elift3 (fun y z xx => f x y z xx) b c d) a. Definition elift5 {A B C D E F:Set} (f:A -> B -> C -> D -> E -> F) (a:eresult A) (b:eresult B) (c:eresult C) (d:eresult D) (e:eresult E) : eresult F := eolift (fun x => elift4 (fun y z xx yy => f x y z xx yy) b c d e) a. (* Fold-left over functions returning eresults *) Definition elift_fold_left {A:Set} {B:Set} (f : A -> B -> eresult A) (l:list B) (a:A) : eresult A := let proc_one (acc:eresult A) (x:B) : eresult A := eolift (fun acc => f acc x) acc in fold_left proc_one l (esuccess a nil). (* Map over functions returning eresults *) Definition emaplift {A B:Set} (f:A -> eresult B) (al:list A) : eresult (list B) := let init_bl := Success (list B * list ewarning) _ (nil, nil) in let proc_one := fun (acc : eresult (list B)) (a : A) => elift2 (fun acc x => app acc (x::nil)) acc (f a) in fold_left proc_one al init_bl. (* Variant of Fold-left for functions passing eresults with a context *) Definition elift_context_fold_left {A:Set} {B:Set} {C:Set} (f : C -> A -> eresult (B * C)) (l:list A) (c:C) : eresult (list B * C) := elift_fold_left (fun acc c => elift (fun mc => ((fst acc)++((fst mc)::nil), snd mc)) (f (snd acc) c)) l (nil, c). Definition eflatmaplift {A B:Set} (f:A -> eresult (list B)) (al:list A) : eresult (list B) := elift_fold_left (fun acc c => elift (fun mc => acc ++ mc) (f c)) al nil. Definition eresult_of_option {A:Set} (a:option A) (e:eerror) (warnings:list ewarning) : eresult A := result_of_option (lift (fun x => (x,warnings)) a) e. Definition eolift2 {A B C:Set} (f : A -> B -> eresult C) (a : eresult A) (b : eresult B) : eresult C := eolift id (elift2 f a b). Definition elift_maybe {A:Set} (f: A -> option (eresult A)) (a:eresult A) : eresult A := eolift (fun x => match x with | None => a | Some s => s end) (elift f a). (* XXX Those lose warnings *) Definition elift_fail {A:Set} (g:eerror -> eresult A) (a:eresult A) : eresult A := match a with | Success _ _ (s,_) => a | Failure _ _ e => g e end. Definition elift_both {A B:Set} (f: A -> B) (g:eerror -> B) (a:eresult A) : B := match a with | Success _ _ (s,_) => f s | Failure _ _ e => g e end. Definition elift2_both {A B C:Set} (f: A -> B -> C) (g:eerror -> C) (a:eresult A) (b:eresult B) : C := match a with | Success _ _ (s1,_) => match b with | Success _ _ (s2,_) => f s1 s2 | Failure _ _ e => g e end | Failure _ _ e => g e end. Section qcert. Definition eerror_of_qerror (prov:provenance) (qe:qerror) := match qe with | DataResult.CompilationError msg => ECompilationError prov msg | DataResult.TypeError msg => ETypeError prov msg | DataResult.UserError msg => ESystemError prov "User error occured in backend" end. Definition eresult_of_qresult {A:Set} (prov:provenance) (a:qresult A) : eresult A := match a with | Result.Success _ _ s => esuccess s nil | Result.Failure _ _ e => efailure (eerror_of_qerror prov e) end. Definition option_of_eresult {A:Set} (a:eresult A) : option A := lift fst (option_of_result a). End qcert. End Lift. Section Fmt. Definition format_error (name : string) (prov : provenance) (msg : string) : string := let loc := loc_of_provenance prov in (name ++ " at " ++ (string_of_location_no_file loc) ++ " '" ++ msg ++ "'")%string. End Fmt. (** Built-in errors *) Section Builtin. Definition clause_call_not_on_contract_error {A} prov : eresult A := efailure (ECompilationError prov "Cannot call a clause except on 'contract'"). Definition use_contract_not_in_contract_error {A} prov : eresult A := efailure (ECompilationError prov "Cannot use 'contract' variable outside of a contract"). Definition call_clause_not_in_contract_error {A} prov clname : eresult A := efailure (ECompilationError prov ("Cannot call clause " ++ clname ++ " outside of a contract")). Definition not_in_clause_error {A} prov : eresult A := efailure (ECompilationError prov "Cannot use 'clause' variable outside of a clause"). Definition case_option_not_on_either_error {A} prov : eresult A := efailure (ECompilationError prov "Cannot match unless against an option type"). Definition set_state_on_non_brand_error {A} prov name : eresult A := efailure (ECompilationError prov ("Cannot use 'set state." ++ name ++ " on non-objet state")). (* CTO errors *) Definition import_not_found_error {A} prov (import:string) : eresult A := efailure (ECompilationError prov ("Import not found: " ++ import)). Definition type_name_not_found_error {A} prov (ln:string) : eresult A := efailure (ECompilationError prov ("Cannot find type with name '" ++ ln ++ "'")). Definition namespace_not_found_error {A} prov (ns:string) : eresult A := efailure (ECompilationError prov ("Cannot find namespace '" ++ ns ++ "'")). Definition variable_name_not_found_error {A} prov (ln:string) : eresult A := efailure (ECompilationError prov ("Cannot find variable with name '" ++ ln ++ "'")). Definition enum_name_not_found_error {A} prov (ln:string) : eresult A := efailure (ECompilationError prov ("Cannot find enum with name '" ++ ln ++ "'")). Definition function_name_not_found_error {A} prov (ln:string) : eresult A := efailure (ECompilationError prov ("Cannot find function with name '" ++ ln ++ "'")). Definition contract_name_not_found_error {A} prov (ln:string) : eresult A := efailure (ECompilationError prov ("Cannot find contract with name '" ++ ln ++ "'")). Definition import_name_not_found_error {A} prov (namespace:string) (name_ref:string) : eresult A := efailure (ECompilationError prov ("Cannot import name '" ++ name_ref++ "' in CTO with namespace " ++ namespace)). (** Main clause creation errors *) Definition main_parameter_mismatch_error {A} prov : eresult A := efailure (ECompilationError prov "Parameter mismatch during main creation"). Definition main_at_least_one_parameter_error {A} prov : eresult A := efailure (ECompilationError prov "Cannot create main if not at least one parameter"). Definition main_not_a_class_error {A} prov (cname:string) : eresult A := efailure (ECompilationError prov ("Cannot create main for non-class type "++cname)). (** Call errors *) Definition function_not_found_error {A} prov (fname:string) : eresult A := efailure (ECompilationError prov ("Function '" ++ fname ++ "' not found")). Definition clause_not_found_error {A} prov (fname:string) : eresult A := efailure (ECompilationError prov ("Clause '" ++ fname ++ "' not found")). Definition call_params_error {A} prov (fname:string) : eresult A := efailure (ECompilationError prov ("Parameter mismatch when calling function '" ++ fname ++ "'")). (** Other runtime errors *) Definition eval_unary_operator_error {A} prov (op:ergo_unary_operator) : eresult A := let op_name := toString op in efailure (ESystemError prov ("Unexpected operator [" ++ op_name ++ "] during eval (should have been resolved).")). Definition eval_binary_operator_error {A} prov (op:ergo_binary_operator) : eresult A := let op_name := toString op in efailure (ESystemError prov ("Unexpected operator [" ++ op_name ++ "] during eval (should have been resolved).")). Definition eval_unary_builtin_error {A} prov (op:QcertOps.Unary.op) : eresult A := let op_name := toString op in efailure (ERuntimeError prov ("Evaluation for builtin unary operator [" ++ op_name ++ "] failed.")). Definition eval_binary_builtin_error {A} prov (op:QcertOps.Binary.op) : eresult A := let op_name := toString op in efailure (ERuntimeError prov ("Evaluation for builtin binary operator [" ++ op_name ++ "] failed.")). Definition eval_if_not_boolean_error {A} prov : eresult A := efailure (ERuntimeError prov "'If' condition not boolean."). Definition eval_match_let_optional_not_on_option_error {A} prov : eresult A := efailure (ERuntimeError prov "Matched LetOption without an option."). Definition eval_match_enum_error {A} prov : eresult A := efailure (ERuntimeError prov "Enum case not resolved in match."). Definition eval_foreach_not_on_array_error {A} prov : eresult A := efailure (ERuntimeError prov "Foreach needs to be called on an array"). Definition template_type_not_found_error {A} prov : eresult A := efailure (ERuntimeError prov ("Cannot find template type (one declared type should extend either AcccordContract or AccordClause)")). Definition more_than_one_template_type_error {A} prov msg : eresult A := efailure (ERuntimeError prov ("Multiple template type (at most one of " ++ msg ++ " should extend either AcccordContract or AccordClause)")). (** System errors *) Definition no_ergo_module_error {A} prov : eresult A := efailure (ESystemError prov ("No input ergo found")). Definition built_in_function_not_found_error {A} prov (fname:string) : eresult A := efailure (ESystemError prov ("Built in function " ++ fname ++ " not found")). Definition built_in_function_without_body_error {A} prov (fname:string) : eresult A := efailure (ESystemError prov ("Built in function " ++ fname ++ " does not have a body")). Definition enforce_error_content (prov:provenance) (msg:string) : QcertData.data := let message := format_error "Enforce Error" prov msg in dbrand (default_error_absolute_name::nil) (drec (("message"%string, dstring message)::nil)). Definition default_match_error_content (prov:provenance) : data := let message := "Dispatch Error: no clause in the contract matches the request"%string in dbrand (default_error_absolute_name::nil) (drec (("message"%string, dstring message)::nil)). Definition unresolved_name_error {A} prov : eresult A := efailure (ECompilationError prov "Unresolved name"). Definition should_have_one_contract_error {A} prov : eresult A := efailure (ECompilationError prov "Should have exactly one contract"). Definition this_in_calculus_error {A} prov : eresult A := efailure (ESystemError prov "Should not find 'this' in Ergo Calculus"). Definition contract_in_calculus_error {A} prov : eresult A := efailure (ESystemError prov "Should not find 'contract' in Ergo Calculus"). Definition clause_in_calculus_error {A} prov : eresult A := efailure (ESystemError prov "Should not find 'clause' in Ergo Calculus"). Definition operator_in_calculus_error {A} prov : eresult A := efailure (ESystemError prov "Should not find an overloaded operator in Ergo Calculus"). Definition state_in_calculus_error {A} prov : eresult A := efailure (ESystemError prov "Should not find 'state' in Ergo Calculus"). Definition text_in_calculus_error {A} prov : eresult A := efailure (ESystemError prov "Should not find '{{ text }}' in Ergo Calculus"). Definition complex_foreach_in_calculus_error {A} prov : eresult A := efailure (ESystemError prov "Should only have single loop foreach in Ergo Calculus"). Definition print_in_calculus_error {A} prov : eresult A := efailure (ESystemError prov "Should not find 'print' in Ergo Calculus"). Definition function_not_inlined_error {A} prov msg fname : eresult A := efailure (ESystemError prov ("[" ++ msg ++ "] " ++ "Function " ++ fname ++ " did not get inlined")). Definition function_in_group_not_inlined_error {A} prov gname fname : eresult A := efailure (ESystemError prov ("Clause " ++ fname ++ " in contract " ++ gname ++ " did not get inlined")). Definition as_in_calculus_error {A} prov : eresult A := efailure (ESystemError prov "Should not find 'as' in Ergo Calculus"). End Builtin. Section Duplicates. Context {A:Set}. Definition no_duplicates_with_err (l:list string) (succ:A) (err:option string -> eerror) : eresult A := if (@NoDup_dec string string_dec l) then esuccess succ nil else let s := find_duplicate l in efailure (err s). Definition duplicate_function_params_error prov (fname:string) (vname:option string) : eerror := match vname with | None => ECompilationError prov ("Same variable bound multiple times in '" ++ fname ++ "'") | Some vname => ECompilationError prov ("Variable '" ++ vname ++ "' is bound multiple times in '" ++ fname ++ "'") end. Definition duplicate_function_params_check prov (fname:string) (l:list string) (succ:A) : eresult A := no_duplicates_with_err l succ (duplicate_function_params_error prov fname). Definition duplicate_clause_for_request_error prov (rname:option string) : eerror := match rname with | None => ECompilationError prov ("Multiple clauses can process the same request") | Some rname => ECompilationError prov ("Multiple clauses can process the request '" ++ rname ++ "'") end. Definition duplicate_clause_for_request_check prov (l:list string) (succ:A) : eresult A := no_duplicates_with_err l succ (duplicate_clause_for_request_error prov). End Duplicates. Section warnings. Definition string_of_warning (w:ewarning) : string := match w with | EWarning prov msg => msg end. Definition print_warnings {A:Set} (prefix:string) (x:eresult A) : eresult A := elift_warning (fun xy => coq_print_warnings prefix (List.map string_of_warning (snd xy)) (fst xy)) x. Definition warning_no_else prov : ewarning := EWarning prov "No else in enforce". Definition warning_global_shadowing prov (name:string) := EWarning prov ("Constant " ++ name ++ " hides an existing constant with the same name"). End warnings. End Result.
Suppose $f$ is a complex-valued function defined on a line segment $[w, z]$ and $f$ is differentiable at every point of $[w, z]$. Then there exists a point $u$ in $[w, z]$ such that $f(z) - f(w) = f'(u) (z - w)$.
if we all of our time spend attacking democrats are going to lose. “So weird to watch Crazy Bernie on @FoxNews. Not surprisingly, @BretBaier and the ‘audience’ was so smiley and nice. Very strange, and now we have @donnabrazile?” the president tweeted on Tuesday, the morning after 2020 Democratic presidential contender and democratic socialist Bernie Sanders appeared at a Fox-hosted town hall event. Bernie Sanders spent more than 2 minutes of his Fox News town hall to defend Medicare for All and attack Trump’s Medicare plans ― uninterrupted. Not sure I’ve seen that happen on Fox News before. Also notable: How the audience largely applauds the idea of a government-run health system and how Sanders wrests the conversation back to tout Medicare for All. Some politicians still say a $15 minimum wage is "too radical." Here's what's radical: in the wealthiest country in the world 40 million people live in poverty and 40% of our people can't afford basic needs. That's unacceptable, and it's why we must guarantee a living wage.
Formal statement is: lemma order_1: "[:-a, 1:] ^ order a p dvd p" Informal statement is: If $p$ is a polynomial with $p(a) = 0$, then $p$ is divisible by $(x - a)$ to the power of the order of $a$ in $p$.
[STATEMENT] theorem LS_parametric_solution: assumes y_le_x: "\<^bold>|y\<^bold>| \<le> \<^bold>|x\<^bold>|" and j_min: "1 \<le> j" and k_min: "1 \<le> k" and l_min: "2 \<le> l" shows "x\<^sup>@j \<cdot> y\<^sup>@k = z\<^sup>@l \<longleftrightarrow> ( (\<exists>r m n t. x = r\<^sup>@m \<and> y = r\<^sup>@n \<and> z = r\<^sup>@t \<and> m*j+n*k=t*l) \<comment>\<open>{x,y} is not a code\<close> \<or> ((j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r\<cdot>q)\<^sup>@m\<cdot>r \<and> y = q\<cdot>(r\<cdot>q)\<^sup>@n \<and> z = r\<cdot>q \<and> Suc(m+n) = l \<and> r\<cdot>q \<noteq> q\<cdot>r)) \<or> ((j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2)\<cdot>(((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r\<cdot>q \<noteq> q\<cdot>r)) \<or> ((j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q\<cdot>r\<^sup>@k)\<^sup>@(l-1)\<cdot>q \<and> y = r \<and> z = q\<cdot>r\<^sup>@k \<and> r\<cdot>q \<noteq> q\<cdot>r)) \<or> ((j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ (Suc (Suc t)) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ (Suc (Suc t)) \<cdot> r \<cdot> r \<cdot> q \<and> r\<cdot>q \<noteq> q\<cdot>r )) ) " (is "?eq = (?sol_per \<or> (?cond_j1k1 \<and> ?sol_j1k1) \<or> (?cond_j1k2 \<and> ?sol_j1k2_a) \<or> (?cond_j1k2 \<and> ?sol_j1k2_b) \<or> (?cond_j2k1l2 \<and> ?sol_j2k1l2))") [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l) = ((\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r)) [PROOF STEP] proof(rule iffI) [PROOF STATE] proof (state) goal (2 subgoals): 1. x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] assume eq: "x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l" [PROOF STATE] proof (state) this: x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l goal (2 subgoals): 1. x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] show "(?sol_per \<or> (?cond_j1k1 \<and> ?sol_j1k1) \<or> (?cond_j1k2 \<and> ?sol_j1k2_a) \<or> (?cond_j1k2 \<and> ?sol_j1k2_b) \<or> (?cond_j2k1l2 \<and> ?sol_j2k1l2))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] proof(cases) [PROOF STATE] proof (state) goal (2 subgoals): 1. ?P \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<not> ?P \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] assume "x\<cdot>y = y\<cdot>x" [PROOF STATE] proof (state) this: x \<cdot> y = y \<cdot> x goal (2 subgoals): 1. ?P \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<not> ?P \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] from comm_primrootE[OF this] [PROOF STATE] proof (chain) picking this: (\<And>t. \<lbrakk>x \<in> t*; y \<in> t*; primitive t\<rbrakk> \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis [PROOF STEP] obtain r m n where "x = r \<^sup>@ m" "y = r \<^sup>@ n" "primitive r" [PROOF STATE] proof (prove) using this: (\<And>t. \<lbrakk>x \<in> t*; y \<in> t*; primitive t\<rbrakk> \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis goal (1 subgoal): 1. (\<And>r m n. \<lbrakk>x = r \<^sup>@ m; y = r \<^sup>@ n; primitive r\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] using rootE [PROOF STATE] proof (prove) using this: (\<And>t. \<lbrakk>x \<in> t*; y \<in> t*; primitive t\<rbrakk> \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis \<lbrakk>?u \<in> ?r*; \<And>k. ?r \<^sup>@ k = ?u \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis goal (1 subgoal): 1. (\<And>r m n. \<lbrakk>x = r \<^sup>@ m; y = r \<^sup>@ n; primitive r\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by metis [PROOF STATE] proof (state) this: x = r \<^sup>@ m y = r \<^sup>@ n primitive r goal (2 subgoals): 1. ?P \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<not> ?P \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] note eqs = eq[unfolded this, folded pow_mult add_exps, symmetric] [PROOF STATE] proof (state) this: z \<^sup>@ l = r \<^sup>@ (m * j + n * k) goal (2 subgoals): 1. ?P \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<not> ?P \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] obtain t where "z = r \<^sup>@ t" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>t. z = r \<^sup>@ t \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] using l_min pow_comm_comm[OF eqs, THEN prim_comm_exp[OF \<open>primitive r\<close>]] [PROOF STATE] proof (prove) using this: 2 \<le> l \<lbrakk>l \<noteq> 0; \<And>k. r \<^sup>@ k = z \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis goal (1 subgoal): 1. (\<And>t. z = r \<^sup>@ t \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: z = r \<^sup>@ t goal (2 subgoals): 1. ?P \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<not> ?P \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] from eqs[unfolded this, folded pow_mult, symmetric] [PROOF STATE] proof (chain) picking this: r \<^sup>@ (m * j + n * k) = r \<^sup>@ (t * l) [PROOF STEP] have "m * j + n * k = t * l" [PROOF STATE] proof (prove) using this: r \<^sup>@ (m * j + n * k) = r \<^sup>@ (t * l) goal (1 subgoal): 1. m * j + n * k = t * l [PROOF STEP] unfolding prim_nemp[OF \<open>primitive r\<close>, THEN eq_pow_exp] [PROOF STATE] proof (prove) using this: m * j + n * k = t * l goal (1 subgoal): 1. m * j + n * k = t * l [PROOF STEP] . [PROOF STATE] proof (state) this: m * j + n * k = t * l goal (2 subgoals): 1. ?P \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<not> ?P \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] hence ?sol_per [PROOF STATE] proof (prove) using this: m * j + n * k = t * l goal (1 subgoal): 1. \<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l [PROOF STEP] using \<open>x = r \<^sup>@ m\<close> \<open>y = r \<^sup>@ n\<close> \<open>z = r \<^sup>@ t\<close> [PROOF STATE] proof (prove) using this: m * j + n * k = t * l x = r \<^sup>@ m y = r \<^sup>@ n z = r \<^sup>@ t goal (1 subgoal): 1. \<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l [PROOF STEP] by blast [PROOF STATE] proof (state) this: \<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l goal (2 subgoals): 1. ?P \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<not> ?P \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: \<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] by blast [PROOF STATE] proof (state) this: (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) goal (1 subgoal): 1. x \<cdot> y \<noteq> y \<cdot> x \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. x \<cdot> y \<noteq> y \<cdot> x \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] assume "x\<cdot>y \<noteq> y\<cdot>x" [PROOF STATE] proof (state) this: x \<cdot> y \<noteq> y \<cdot> x goal (1 subgoal): 1. x \<cdot> y \<noteq> y \<cdot> x \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] interpret LS_len_le x y j k l z [PROOF STATE] proof (prove) goal (1 subgoal): 1. LS_len_le x y j k l z [PROOF STEP] using \<open>x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l\<close> \<open>x\<cdot>y \<noteq> y\<cdot>x\<close> j_min k_min l_min y_le_x [PROOF STATE] proof (prove) using this: x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l x \<cdot> y \<noteq> y \<cdot> x 1 \<le> j 1 \<le> k 2 \<le> l \<^bold>|y\<^bold>| \<le> \<^bold>|x\<^bold>| goal (1 subgoal): 1. LS_len_le x y j k l z [PROOF STEP] by(unfold_locales) [PROOF STATE] proof (state) goal (1 subgoal): 1. x \<cdot> y \<noteq> y \<cdot> x \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] using solution_cases [PROOF STATE] proof (prove) using this: \<lbrakk>\<lbrakk>j = 2; k = 1\<rbrakk> \<Longrightarrow> ?thesis; \<lbrakk>j = 1; 2 \<le> k; z <s y \<^sup>@ k\<rbrakk> \<Longrightarrow> ?thesis; \<lbrakk>j = 1; 2 \<le> k; y \<^sup>@ k <s z\<rbrakk> \<Longrightarrow> ?thesis; \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] proof(cases) [PROOF STATE] proof (state) goal (4 subgoals): 1. \<lbrakk>j = 2; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<lbrakk>j = 1; 2 \<le> k; z <s y \<^sup>@ k\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 3. \<lbrakk>j = 1; 2 \<le> k; y \<^sup>@ k <s z\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 4. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] case 1 [PROOF STATE] proof (state) this: j = 2 k = 1 goal (4 subgoals): 1. \<lbrakk>j = 2; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<lbrakk>j = 1; 2 \<le> k; z <s y \<^sup>@ k\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 3. \<lbrakk>j = 1; 2 \<le> k; y \<^sup>@ k <s z\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 4. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] from case_j2k1[OF less_or_eq_imp_le[of 2 j] \<open>k = 1\<close>, OF disjI2, OF \<open>j = 2\<close>[symmetric], of "?sol_j2k1l2 \<and> l = 2"] [PROOF STATE] proof (chain) picking this: (\<And>r q t. \<lbrakk>(r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r = x; q \<cdot> r \<cdot> r \<cdot> q = y; (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q = z; j = 2; l = 2; r \<cdot> q \<noteq> q \<cdot> r; primitive x; primitive y\<rbrakk> \<Longrightarrow> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) \<and> l = 2) \<Longrightarrow> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) \<and> l = 2 [PROOF STEP] have "?sol_j2k1l2" and "l = 2" [PROOF STATE] proof (prove) using this: (\<And>r q t. \<lbrakk>(r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r = x; q \<cdot> r \<cdot> r \<cdot> q = y; (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q = z; j = 2; l = 2; r \<cdot> q \<noteq> q \<cdot> r; primitive x; primitive y\<rbrakk> \<Longrightarrow> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) \<and> l = 2) \<Longrightarrow> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) \<and> l = 2 goal (1 subgoal): 1. \<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r &&& l = 2 [PROOF STEP] by blast+ [PROOF STATE] proof (state) this: \<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r l = 2 goal (4 subgoals): 1. \<lbrakk>j = 2; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<lbrakk>j = 1; 2 \<le> k; z <s y \<^sup>@ k\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 3. \<lbrakk>j = 1; 2 \<le> k; y \<^sup>@ k <s z\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 4. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: \<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r l = 2 goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] using \<open>k = 1\<close> \<open>j = 2\<close> [PROOF STATE] proof (prove) using this: \<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r l = 2 k = 1 j = 2 goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] by blast [PROOF STATE] proof (state) this: (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) goal (3 subgoals): 1. \<lbrakk>j = 1; 2 \<le> k; z <s y \<^sup>@ k\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<lbrakk>j = 1; 2 \<le> k; y \<^sup>@ k <s z\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 3. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] next [PROOF STATE] proof (state) goal (3 subgoals): 1. \<lbrakk>j = 1; 2 \<le> k; z <s y \<^sup>@ k\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<lbrakk>j = 1; 2 \<le> k; y \<^sup>@ k <s z\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 3. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] case 2 [PROOF STATE] proof (state) this: j = 1 2 \<le> k z <s y \<^sup>@ k goal (3 subgoals): 1. \<lbrakk>j = 1; 2 \<le> k; z <s y \<^sup>@ k\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<lbrakk>j = 1; 2 \<le> k; y \<^sup>@ k <s z\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 3. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] have "?sol_j1k2_a" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r [PROOF STEP] using case_j1k2_a[OF \<open>j = 1\<close> \<open>2 \<le> k\<close> ssufD1[OF \<open>z <s y \<^sup>@ k\<close>], of ?sol_j1k2_a] [PROOF STATE] proof (prove) using this: (\<And>r q t. \<lbrakk>x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> \<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<Longrightarrow> \<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r goal (1 subgoal): 1. \<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r [PROOF STEP] by blast [PROOF STATE] proof (state) this: \<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r goal (3 subgoals): 1. \<lbrakk>j = 1; 2 \<le> k; z <s y \<^sup>@ k\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<lbrakk>j = 1; 2 \<le> k; y \<^sup>@ k <s z\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 3. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: \<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] using \<open>j = 1\<close> \<open>2 \<le> k\<close> [PROOF STATE] proof (prove) using this: \<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r j = 1 2 \<le> k goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] by blast [PROOF STATE] proof (state) this: (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) goal (2 subgoals): 1. \<lbrakk>j = 1; 2 \<le> k; y \<^sup>@ k <s z\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] next [PROOF STATE] proof (state) goal (2 subgoals): 1. \<lbrakk>j = 1; 2 \<le> k; y \<^sup>@ k <s z\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] case 3 [PROOF STATE] proof (state) this: j = 1 2 \<le> k y \<^sup>@ k <s z goal (2 subgoals): 1. \<lbrakk>j = 1; 2 \<le> k; y \<^sup>@ k <s z\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] with case_j1k2_b[OF this, of "?sol_j1k2_b"] [PROOF STATE] proof (chain) picking this: (\<And>q. \<lbrakk>x = (q \<cdot> y \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; z = q \<cdot> y \<^sup>@ k; q \<cdot> y \<noteq> y \<cdot> q\<rbrakk> \<Longrightarrow> \<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<Longrightarrow> \<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r j = 1 2 \<le> k y \<^sup>@ k <s z [PROOF STEP] have "?sol_j1k2_b" [PROOF STATE] proof (prove) using this: (\<And>q. \<lbrakk>x = (q \<cdot> y \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; z = q \<cdot> y \<^sup>@ k; q \<cdot> y \<noteq> y \<cdot> q\<rbrakk> \<Longrightarrow> \<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<Longrightarrow> \<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r j = 1 2 \<le> k y \<^sup>@ k <s z goal (1 subgoal): 1. \<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r [PROOF STEP] by auto [PROOF STATE] proof (state) this: \<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r goal (2 subgoals): 1. \<lbrakk>j = 1; 2 \<le> k; y \<^sup>@ k <s z\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) 2. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: \<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] using \<open>j = 1\<close> \<open>2 \<le> k\<close> [PROOF STATE] proof (prove) using this: \<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r j = 1 2 \<le> k goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] by blast [PROOF STATE] proof (state) this: (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) goal (1 subgoal): 1. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] case 4 [PROOF STATE] proof (state) this: j = 1 k = 1 goal (1 subgoal): 1. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] with case_j1k1[OF this, of ?sol_j1k1] [PROOF STATE] proof (chain) picking this: (\<And>r q m n. \<lbrakk>x = (r \<cdot> q) \<^sup>@ m \<cdot> r; y = q \<cdot> (r \<cdot> q) \<^sup>@ n; z = r \<cdot> q; Suc (m + n) = l; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> \<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<Longrightarrow> \<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r j = 1 k = 1 [PROOF STEP] have"?sol_j1k1" [PROOF STATE] proof (prove) using this: (\<And>r q m n. \<lbrakk>x = (r \<cdot> q) \<^sup>@ m \<cdot> r; y = q \<cdot> (r \<cdot> q) \<^sup>@ n; z = r \<cdot> q; Suc (m + n) = l; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> \<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<Longrightarrow> \<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r j = 1 k = 1 goal (1 subgoal): 1. \<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r [PROOF STEP] by blast [PROOF STATE] proof (state) this: \<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r goal (1 subgoal): 1. \<lbrakk>j = 1; k = 1\<rbrakk> \<Longrightarrow> (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: \<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] using \<open>j = 1\<close> \<open>k = 1\<close> [PROOF STATE] proof (prove) using this: \<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r j = 1 k = 1 goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] by blast [PROOF STATE] proof (state) this: (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] have "l \<noteq> 0" "l - 1 \<noteq> 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. l \<noteq> 0 &&& l - 1 \<noteq> 0 [PROOF STEP] using l_min [PROOF STATE] proof (prove) using this: 2 \<le> l goal (1 subgoal): 1. l \<noteq> 0 &&& l - 1 \<noteq> 0 [PROOF STEP] by auto [PROOF STATE] proof (state) this: l \<noteq> 0 l - 1 \<noteq> 0 goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] have "k \<noteq> 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. k \<noteq> 0 [PROOF STEP] using k_min [PROOF STATE] proof (prove) using this: 1 \<le> k goal (1 subgoal): 1. k \<noteq> 0 [PROOF STEP] by auto [PROOF STATE] proof (state) this: k \<noteq> 0 goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] have "j \<noteq> 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. j \<noteq> 0 [PROOF STEP] using j_min [PROOF STATE] proof (prove) using this: 1 \<le> j goal (1 subgoal): 1. j \<noteq> 0 [PROOF STEP] by auto [PROOF STATE] proof (state) this: j \<noteq> 0 goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] assume "(?sol_per \<or> (?cond_j1k1 \<and> ?sol_j1k1) \<or> (?cond_j1k2 \<and> ?sol_j1k2_a) \<or> (?cond_j1k2 \<and> ?sol_j1k2_b) \<or> (?cond_j2k1l2 \<and> ?sol_j2k1l2))" [PROOF STATE] proof (state) this: (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) goal (1 subgoal): 1. (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] then [PROOF STATE] proof (chain) picking this: (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) [PROOF STEP] show ?eq [PROOF STATE] proof (prove) using this: (\<exists>r m n t. x = r \<^sup>@ m \<and> y = r \<^sup>@ n \<and> z = r \<^sup>@ t \<and> m * j + n * k = t * l) \<or> (j = 1 \<and> k = 1) \<and> (\<exists>r q m n. x = (r \<cdot> q) \<^sup>@ m \<cdot> r \<and> y = q \<cdot> (r \<cdot> q) \<^sup>@ n \<and> z = r \<cdot> q \<and> Suc (m + n) = l \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q t. x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q \<and> y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t \<and> z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 1 \<and> 2 \<le> k) \<and> (\<exists>r q. x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<and> y = r \<and> z = q \<cdot> r \<^sup>@ k \<and> r \<cdot> q \<noteq> q \<cdot> r) \<or> (j = 2 \<and> k = 1 \<and> l = 2) \<and> (\<exists>r q t. x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<and> y = q \<cdot> r \<cdot> r \<cdot> q \<and> z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q \<and> r \<cdot> q \<noteq> q \<cdot> r) goal (1 subgoal): 1. x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] proof(elim disjE conjE exE) [PROOF STATE] proof (state) goal (5 subgoals): 1. \<And>r m n t. \<lbrakk>x = r \<^sup>@ m; y = r \<^sup>@ n; z = r \<^sup>@ t; m * j + n * k = t * l\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q m n. \<lbrakk>j = 1; k = 1; x = (r \<cdot> q) \<^sup>@ m \<cdot> r; y = q \<cdot> (r \<cdot> q) \<^sup>@ n; z = r \<cdot> q; Suc (m + n) = l; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 4. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 5. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] fix r m n t [PROOF STATE] proof (state) goal (5 subgoals): 1. \<And>r m n t. \<lbrakk>x = r \<^sup>@ m; y = r \<^sup>@ n; z = r \<^sup>@ t; m * j + n * k = t * l\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q m n. \<lbrakk>j = 1; k = 1; x = (r \<cdot> q) \<^sup>@ m \<cdot> r; y = q \<cdot> (r \<cdot> q) \<^sup>@ n; z = r \<cdot> q; Suc (m + n) = l; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 4. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 5. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] assume sol: "x = r \<^sup>@ m" "y = r \<^sup>@ n" "z = r \<^sup>@ t" and "m * j + n * k = t * l" [PROOF STATE] proof (state) this: x = r \<^sup>@ m y = r \<^sup>@ n z = r \<^sup>@ t m * j + n * k = t * l goal (5 subgoals): 1. \<And>r m n t. \<lbrakk>x = r \<^sup>@ m; y = r \<^sup>@ n; z = r \<^sup>@ t; m * j + n * k = t * l\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q m n. \<lbrakk>j = 1; k = 1; x = (r \<cdot> q) \<^sup>@ m \<cdot> r; y = q \<cdot> (r \<cdot> q) \<^sup>@ n; z = r \<cdot> q; Suc (m + n) = l; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 4. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 5. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] unfolding sol [PROOF STATE] proof (prove) goal (1 subgoal): 1. (r \<^sup>@ m) \<^sup>@ j \<cdot> (r \<^sup>@ n) \<^sup>@ k = (r \<^sup>@ t) \<^sup>@ l [PROOF STEP] unfolding power_mult[symmetric] power_add[symmetric] [PROOF STATE] proof (prove) goal (1 subgoal): 1. r \<^sup>@ (m * j + n * k) = r \<^sup>@ (t * l) [PROOF STEP] unfolding \<open>m * j + n * k = t * l\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. r \<^sup>@ (t * l) = r \<^sup>@ (t * l) [PROOF STEP] .. [PROOF STATE] proof (state) this: x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l goal (4 subgoals): 1. \<And>r q m n. \<lbrakk>j = 1; k = 1; x = (r \<cdot> q) \<^sup>@ m \<cdot> r; y = q \<cdot> (r \<cdot> q) \<^sup>@ n; z = r \<cdot> q; Suc (m + n) = l; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 4. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] next [PROOF STATE] proof (state) goal (4 subgoals): 1. \<And>r q m n. \<lbrakk>j = 1; k = 1; x = (r \<cdot> q) \<^sup>@ m \<cdot> r; y = q \<cdot> (r \<cdot> q) \<^sup>@ n; z = r \<cdot> q; Suc (m + n) = l; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 4. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] fix r q m n [PROOF STATE] proof (state) goal (4 subgoals): 1. \<And>r q m n. \<lbrakk>j = 1; k = 1; x = (r \<cdot> q) \<^sup>@ m \<cdot> r; y = q \<cdot> (r \<cdot> q) \<^sup>@ n; z = r \<cdot> q; Suc (m + n) = l; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 4. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] assume "j = 1" "k = 1" and sol: "x = (r\<cdot>q)\<^sup>@m\<cdot>r" "y = q\<cdot>(r\<cdot>q)\<^sup>@n" "z = r\<cdot>q" and "Suc(m+n) = l" [PROOF STATE] proof (state) this: j = 1 k = 1 x = (r \<cdot> q) \<^sup>@ m \<cdot> r y = q \<cdot> (r \<cdot> q) \<^sup>@ n z = r \<cdot> q Suc (m + n) = l goal (4 subgoals): 1. \<And>r q m n. \<lbrakk>j = 1; k = 1; x = (r \<cdot> q) \<^sup>@ m \<cdot> r; y = q \<cdot> (r \<cdot> q) \<^sup>@ n; z = r \<cdot> q; Suc (m + n) = l; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 4. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] unfolding sol [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((r \<cdot> q) \<^sup>@ m \<cdot> r) \<^sup>@ j \<cdot> (q \<cdot> (r \<cdot> q) \<^sup>@ n) \<^sup>@ k = (r \<cdot> q) \<^sup>@ l [PROOF STEP] unfolding \<open>j = 1\<close> \<open>k = 1\<close> \<open>Suc(m+n) = l\<close>[symmetric] pow_one' [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((r \<cdot> q) \<^sup>@ m \<cdot> r) \<cdot> q \<cdot> (r \<cdot> q) \<^sup>@ n = (r \<cdot> q) \<^sup>@ Suc (m + n) [PROOF STEP] unfolding lassoc pow_Suc add_exps [PROOF STATE] proof (prove) goal (1 subgoal): 1. (((r \<cdot> q) \<^sup>@ m \<cdot> r) \<cdot> q) \<cdot> (r \<cdot> q) \<^sup>@ n = ((r \<cdot> q) \<cdot> (r \<cdot> q) \<^sup>@ m) \<cdot> (r \<cdot> q) \<^sup>@ n [PROOF STEP] unfolding power_commutes[of _ m, symmetric] lassoc [PROOF STATE] proof (prove) goal (1 subgoal): 1. (((r \<cdot> q) \<^sup>@ m \<cdot> r) \<cdot> q) \<cdot> (r \<cdot> q) \<^sup>@ n = (((r \<cdot> q) \<^sup>@ m \<cdot> r) \<cdot> q) \<cdot> (r \<cdot> q) \<^sup>@ n [PROOF STEP] .. [PROOF STATE] proof (state) this: x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l goal (3 subgoals): 1. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] next [PROOF STATE] proof (state) goal (3 subgoals): 1. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] fix r q t [PROOF STATE] proof (state) goal (3 subgoals): 1. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] assume "j = 1" "2 \<le> k" and sol: "x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q" "y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t" "z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)" [PROOF STATE] proof (state) this: j = 1 2 \<le> k x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1) goal (3 subgoals): 1. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] obtain k' where "Suc (Suc k') = k" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>k'. Suc (Suc k') = k \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] using Suc_minus2[OF \<open>2 \<le> k\<close>] [PROOF STATE] proof (prove) using this: Suc (Suc (k - 2)) = k goal (1 subgoal): 1. (\<And>k'. Suc (Suc k') = k \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: Suc (Suc k') = k goal (3 subgoals): 1. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] hence k1: "k - 1 = Suc k'" and k2: "k - 2 = k'" and k: "k = k'+ 2" [PROOF STATE] proof (prove) using this: Suc (Suc k') = k goal (1 subgoal): 1. k - 1 = Suc k' &&& k - 2 = k' &&& k = k' + 2 [PROOF STEP] by fastforce+ [PROOF STATE] proof (state) this: k - 1 = Suc k' k - 2 = k' k = k' + 2 goal (3 subgoals): 1. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] obtain l' where "Suc (Suc l') = l" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>l'. Suc (Suc l') = l \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] using Suc_minus2[OF \<open>2 \<le> l\<close>] [PROOF STATE] proof (prove) using this: Suc (Suc (l - 2)) = l goal (1 subgoal): 1. (\<And>l'. Suc (Suc l') = l \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: Suc (Suc l') = l goal (3 subgoals): 1. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] hence l2: "l - 2 = l'" and l: "l = l' + 2" [PROOF STATE] proof (prove) using this: Suc (Suc l') = l goal (1 subgoal): 1. l - 2 = l' &&& l = l' + 2 [PROOF STEP] by fastforce+ [PROOF STATE] proof (state) this: l - 2 = l' l = l' + 2 goal (3 subgoals): 1. \<And>r q t. \<lbrakk>j = 1; 2 \<le> k; x = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1)) \<^sup>@ (l - 2) \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 2)) \<cdot> r) \<cdot> q; y = r \<cdot> (q \<cdot> r) \<^sup>@ Suc t; z = (q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k - 1); r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 3. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] show "x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l" [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] unfolding sol \<open>j = 1\<close> k1 k2 l2 [PROOF STATE] proof (prove) goal (1 subgoal): 1. (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ Suc k') \<^sup>@ l' \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ k') \<cdot> r) \<cdot> q) \<^sup>@ 1 \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ k = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ Suc k') \<^sup>@ l [PROOF STEP] unfolding k l [PROOF STATE] proof (prove) goal (1 subgoal): 1. (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ Suc k') \<^sup>@ l' \<cdot> (((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ k') \<cdot> r) \<cdot> q) \<^sup>@ 1 \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ (k' + 2) = ((q \<cdot> r) \<cdot> (r \<cdot> (q \<cdot> r) \<^sup>@ Suc t) \<^sup>@ Suc k') \<^sup>@ (l' + 2) [PROOF STEP] by comparison [PROOF STATE] proof (state) this: x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l goal (2 subgoals): 1. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] next [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] fix r q [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] assume "j = 1" "2 \<le> k" and sol: "x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q" "y = r" "z = q \<cdot> r \<^sup>@ k" [PROOF STATE] proof (state) this: j = 1 2 \<le> k x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q y = r z = q \<cdot> r \<^sup>@ k goal (2 subgoals): 1. \<And>r q. \<lbrakk>j = 1; 2 \<le> k; x = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q; y = r; z = q \<cdot> r \<^sup>@ k; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l 2. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] unfolding sol \<open>j = 1\<close> pow_one' [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q) \<cdot> r \<^sup>@ k = (q \<cdot> r \<^sup>@ k) \<^sup>@ l [PROOF STEP] unfolding pop_pow_one'[OF \<open>l \<noteq> 0\<close>] rassoc [PROOF STATE] proof (prove) goal (1 subgoal): 1. (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<cdot> r \<^sup>@ k = (q \<cdot> r \<^sup>@ k) \<^sup>@ (l - 1) \<cdot> q \<cdot> r \<^sup>@ k [PROOF STEP] .. [PROOF STATE] proof (state) this: x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l goal (1 subgoal): 1. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] fix r q t [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] assume "j = 2" "k = 1" "l = 2" and sol: "x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r" "y = q \<cdot> r \<cdot> r \<cdot> q" "z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q" [PROOF STATE] proof (state) this: j = 2 k = 1 l = 2 x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r y = q \<cdot> r \<cdot> r \<cdot> q z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q goal (1 subgoal): 1. \<And>r q t. \<lbrakk>j = 2; k = 1; l = 2; x = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r; y = q \<cdot> r \<cdot> r \<cdot> q; z = (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q; r \<cdot> q \<noteq> q \<cdot> r\<rbrakk> \<Longrightarrow> x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] show "x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l" [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l [PROOF STEP] unfolding \<open>j = 2\<close> \<open>k = 1\<close> \<open>l = 2\<close> sol pow_one' pow_two [PROOF STATE] proof (prove) goal (1 subgoal): 1. (((r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r) \<cdot> (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r) \<cdot> q \<cdot> r \<cdot> r \<cdot> q = ((r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q) \<cdot> (r \<cdot> q) \<^sup>@ Suc (Suc t) \<cdot> r \<cdot> r \<cdot> q [PROOF STEP] by comparison [PROOF STATE] proof (state) this: x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: x \<^sup>@ j \<cdot> y \<^sup>@ k = z \<^sup>@ l goal: No subgoals! [PROOF STEP] qed
State Before: case nil V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ : V ⊢ length (bypass nil) ≤ length nil State After: no goals Tactic: rfl State Before: case cons V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ ⊢ length (bypass (cons h✝ p✝)) ≤ length (cons h✝ p✝) State After: case cons V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ ⊢ length (if hs : u✝ ∈ support (bypass p✝) then dropUntil (bypass p✝) u✝ hs else cons h✝ (bypass p✝)) ≤ length (cons h✝ p✝) Tactic: simp only [bypass] State Before: case cons V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ ⊢ length (if hs : u✝ ∈ support (bypass p✝) then dropUntil (bypass p✝) u✝ hs else cons h✝ (bypass p✝)) ≤ length (cons h✝ p✝) State After: case cons.inl V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : u✝ ∈ support (bypass p✝) ⊢ length (dropUntil (bypass p✝) u✝ h✝) ≤ length (cons h✝¹ p✝) case cons.inr V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : ¬u✝ ∈ support (bypass p✝) ⊢ length (cons h✝¹ (bypass p✝)) ≤ length (cons h✝¹ p✝) Tactic: split_ifs State Before: case cons.inl V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : u✝ ∈ support (bypass p✝) ⊢ length (dropUntil (bypass p✝) u✝ h✝) ≤ length (cons h✝¹ p✝) State After: V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : u✝ ∈ support (bypass p✝) ⊢ length (dropUntil (bypass p✝) u✝ h✝) ≤ ?m.279260 V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : u✝ ∈ support (bypass p✝) ⊢ ?m.279260 ≤ length (cons h✝¹ p✝) V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : u✝ ∈ support (bypass p✝) ⊢ ℕ Tactic: trans State Before: V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : u✝ ∈ support (bypass p✝) ⊢ length (dropUntil (bypass p✝) u✝ h✝) ≤ ?m.279260 V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : u✝ ∈ support (bypass p✝) ⊢ ?m.279260 ≤ length (cons h✝¹ p✝) V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : u✝ ∈ support (bypass p✝) ⊢ ℕ State After: V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : u✝ ∈ support (bypass p✝) ⊢ length (bypass p✝) ≤ length (cons h✝¹ p✝) Tactic: apply length_dropUntil_le State Before: V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : u✝ ∈ support (bypass p✝) ⊢ length (bypass p✝) ≤ length (cons h✝¹ p✝) State After: V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : u✝ ∈ support (bypass p✝) ⊢ length (bypass p✝) ≤ length p✝ + 1 Tactic: rw [length_cons] State Before: V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : u✝ ∈ support (bypass p✝) ⊢ length (bypass p✝) ≤ length p✝ + 1 State After: no goals Tactic: exact le_add_right ih State Before: case cons.inr V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : ¬u✝ ∈ support (bypass p✝) ⊢ length (cons h✝¹ (bypass p✝)) ≤ length (cons h✝¹ p✝) State After: case cons.inr V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : ¬u✝ ∈ support (bypass p✝) ⊢ length (bypass p✝) + 1 ≤ length p✝ + 1 Tactic: rw [length_cons, length_cons] State Before: case cons.inr V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' inst✝ : DecidableEq V u v u✝ v✝ w✝ : V h✝¹ : Adj G u✝ v✝ p✝ : Walk G v✝ w✝ ih : length (bypass p✝) ≤ length p✝ h✝ : ¬u✝ ∈ support (bypass p✝) ⊢ length (bypass p✝) + 1 ≤ length p✝ + 1 State After: no goals Tactic: exact add_le_add_right ih 1
#!/usr/bin/Rscript # Bhishan Poudel # Jan 16, 2016 # set up a device driver to plot #postscript(file='~/Copy/Programming/R/rprograms/plotting/legends/legend2.eps') ## Using 'ncol' : x <- 0:64/64 matplot(x, outer(x, 1:7, function(x, k) sin(k * pi * x)), type = "o", col = 1:7, ylim = c(-1, 1.5), pch = "*") op <- par(bg = "antiquewhite1") legend(0, 1.5, paste("sin(", 1:7, "pi * x)"), col = 1:7, lty = 1:7, pch = "*", ncol = 4, cex = 0.8) # legend(.8,1.2, paste("sin(", 1:7, "pi * x)"), col = 1:7, lty = 1:7, # pch = "*", cex = 0.8) # legend(0, -.1, paste("sin(", 1:4, "pi * x)"), col = 1:4, lty = 1:4, # ncol = 2, cex = 0.8) # legend(0, -.4, paste("sin(", 5:7, "pi * x)"), col = 4:6, pch = 24, # ncol = 2, cex = 1.5, lwd = 2, pt.bg = "pink", pt.cex = 1:3) par(op) # turn off device driver #dev.off()
{-# LANGUAGE ForeignFunctionInterface #-} {-| Module : Grenade.Layers.Internal.Add Description : Fast addition functions that call efficient C function Maintainer : Theo Charalambous License : BSD2 Stability : experimental -} module Grenade.Layers.Internal.Add ( addPerChannel ) where import qualified Data.Vector.Storable as U (unsafeFromForeignPtr0, unsafeToForeignPtr0) import Foreign (mallocForeignPtrArray, withForeignPtr) import Foreign.Ptr (Ptr) import Numeric.LinearAlgebra (Matrix, Vector, flatten) import qualified Numeric.LinearAlgebra.Devel as U import System.IO.Unsafe (unsafePerformIO) import Grenade.Types -- | Add the nth element to a vector to every pixel in the nth channel of a matrix. -- It assumes that the size of the vector and the number of channels in the matrix -- are both equal to channels. addPerChannel :: Int -> Int -> Int -> Matrix RealNum -> Vector RealNum -> Matrix RealNum addPerChannel channels rows cols m b = let outMatSize = rows * cols * channels vec = flatten m in unsafePerformIO $ do outPtr <- mallocForeignPtrArray outMatSize let (inPtr, _) = U.unsafeToForeignPtr0 vec (bPtr, _) = U.unsafeToForeignPtr0 b withForeignPtr inPtr $ \inPtr' -> withForeignPtr bPtr $ \bPtr' -> withForeignPtr outPtr $ \outPtr' -> add_per_channel_cpu inPtr' channels rows cols bPtr' outPtr' let matVec = U.unsafeFromForeignPtr0 outPtr outMatSize return (U.matrixFromVector U.RowMajor (rows * channels) cols matVec) {-# INLINE addPerChannel #-} foreign import ccall unsafe add_per_channel_cpu :: Ptr RealNum -> Int -> Int -> Int -> Ptr RealNum -> Ptr RealNum -> IO ()
New York : Crowell, ©1954. Pioneers > United States > Juvenile literature. United States > Biography > Juvenile literature.
#' The length of a string #' #' Compute the number of characters in a string. Technically, this returns the #' number of "code points", in a string. One code point usually corresponds to #' one character, but not always. For example, an u with a umlaut might be #' represented as a single code point or as "u" code point and an umlaut #' code point. #' #' @inheritParams str_detect #' @return A numeric vector giving number of characters (code points) in each #' element of the character vector. Missing string have missing length. #' @seealso [stringi::stri_length()] which this function wraps. #' @export #' @examples #' str_length(letters) #' str_length(NA) #' str_length(factor("abc")) #' str_length(c("i", "like", "programming", NA)) #' #' # Two ways of representing a u with an umlaut #' u1 <- "\u00fc" #' u2 <- stringi::stri_trans_nfd(u1) #' # The print the same: #' u1 #' u2 #' # But have a different length #' str_length(u1) #' str_length(u2) #' # Even though they have the same number of characters #' str_count(u1) #' str_count(u2) str_length <- function(string) { stri_length(string) }
/- Copyright (c) 2022 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import algebra.associated import data.int.units /-! # Associated elements and the integers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains some results on equality up to units in the integers. ## Main results * `int.nat_abs_eq_iff_associated`: the absolute value is equal iff integers are associated -/ lemma int.nat_abs_eq_iff_associated {a b : ℤ} : a.nat_abs = b.nat_abs ↔ associated a b := begin refine int.nat_abs_eq_nat_abs_iff.trans _, split, { rintro (rfl | rfl), { refl }, { exact ⟨-1, by simp⟩ } }, { rintro ⟨u, rfl⟩, obtain (rfl | rfl) := int.units_eq_one_or u, { exact or.inl (by simp) }, { exact or.inr (by simp) } } end
[STATEMENT] lemma finite_reach_af_G_opt: "finite (reach \<Sigma> \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. finite (reach \<Sigma> \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>)) [PROOF STEP] proof (cases "\<Sigma> \<noteq> {}") [PROOF STATE] proof (state) goal (2 subgoals): 1. \<Sigma> \<noteq> {} \<Longrightarrow> finite (reach \<Sigma> \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>)) 2. \<not> \<Sigma> \<noteq> {} \<Longrightarrow> finite (reach \<Sigma> \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>)) [PROOF STEP] case True [PROOF STATE] proof (state) this: \<Sigma> \<noteq> {} goal (2 subgoals): 1. \<Sigma> \<noteq> {} \<Longrightarrow> finite (reach \<Sigma> \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>)) 2. \<not> \<Sigma> \<noteq> {} \<Longrightarrow> finite (reach \<Sigma> \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>)) [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: \<Sigma> \<noteq> {} goal (1 subgoal): 1. finite (reach \<Sigma> \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>)) [PROOF STEP] using af_G_abs_opt.finite_abs_reach [PROOF STATE] proof (prove) using this: \<Sigma> \<noteq> {} finite (af_G_abs_opt.abs_reach (Abs ?\<phi>)) goal (1 subgoal): 1. finite (reach \<Sigma> \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>)) [PROOF STEP] unfolding af_G_abs_opt.abs_reach_def reach_foldl_def[OF True] [PROOF STATE] proof (prove) using this: \<Sigma> \<noteq> {} finite {foldl af_G_abs_opt.f_abs (Abs ?\<phi>) w |w. True} goal (1 subgoal): 1. finite {foldl \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>) w |w. set w \<subseteq> \<Sigma>} [PROOF STEP] using finite_subset[of "{foldl \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>) w |w. set w \<subseteq> \<Sigma>}" "{foldl \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>) w |w. True}"] [PROOF STATE] proof (prove) using this: \<Sigma> \<noteq> {} finite {foldl af_G_abs_opt.f_abs (Abs ?\<phi>) w |w. True} \<lbrakk>{foldl \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>) w |w. set w \<subseteq> \<Sigma>} \<subseteq> {foldl \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>) w |w. True}; finite {foldl \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>) w |w. True}\<rbrakk> \<Longrightarrow> finite {foldl \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>) w |w. set w \<subseteq> \<Sigma>} goal (1 subgoal): 1. finite {foldl \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>) w |w. set w \<subseteq> \<Sigma>} [PROOF STEP] unfolding af_G_letter_abs_opt_def [PROOF STATE] proof (prove) using this: \<Sigma> \<noteq> {} finite {foldl af_G_abs_opt.f_abs (Abs ?\<phi>) w |w. True} \<lbrakk>{foldl af_G_abs_opt.f_abs (Abs \<phi>) w |w. set w \<subseteq> \<Sigma>} \<subseteq> {foldl af_G_abs_opt.f_abs (Abs \<phi>) w |w. True}; finite {foldl af_G_abs_opt.f_abs (Abs \<phi>) w |w. True}\<rbrakk> \<Longrightarrow> finite {foldl af_G_abs_opt.f_abs (Abs \<phi>) w |w. set w \<subseteq> \<Sigma>} goal (1 subgoal): 1. finite {foldl af_G_abs_opt.f_abs (Abs \<phi>) w |w. set w \<subseteq> \<Sigma>} [PROOF STEP] by blast [PROOF STATE] proof (state) this: finite (reach \<Sigma> \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>)) goal (1 subgoal): 1. \<not> \<Sigma> \<noteq> {} \<Longrightarrow> finite (reach \<Sigma> \<up>af\<^sub>G\<^sub>\<UU> (Abs \<phi>)) [PROOF STEP] qed (simp add: reach_def)
using TikzGraphs using TikzPictures using GraphRecipes using LightGraphs using Plots default(size=(1000, 1000)) f = :(x * y + sin(x)) vertices = Dict([ 1 => (name = "x", x = 1, y = 0, color = :lightblue, ), 2 => (name = "y", x = 0, y = 1, color = :lightblue, ), 3 => (name = "h₁ = sin", x = 1, y = 2, color = :lightblue, ), 4 => (name = "h₂ = *", x = 0, y = 3, color = :lightblue, ), 5 => (name = "h₃ = +", x = 1, y = 4, color = :lightblue, ), 6 => (name = "z", x = 1, y = 5, color = :lightblue, ), 7 => (name = "∂z/∂h₃", x = 2.5, y = 4, color = :orange, ), 8 => (name = "∂h₃/∂h₂", x = 2.5, y = 3, color = :orange, ), 9 => (name = "∂z/∂h₂", x = 3.5, y = 3, color = :orange, ), 10 => (name = "∂h₃/∂h₁", x = 2.5, y = 2, color = :orange, ), 11 => (name = "∂z/∂h₁", x = 3.5, y = 2, color = :orange, ), 12 => (name = "∂h₂/∂y", x = 4.5, y = 1, color = :orange, ), 13 => (name = "∂h₂/∂x + ∂h₁/∂x", x = 4.5, y = 0, color = :orange, ), 14 => (name = "∂z/∂x", x = 6, y = 0, color = :orange, ), ]) n = length(vertices) g = LightGraphs.DiGraph(n) add_edge!(g, 1, 3) # x -> sin add_edge!(g, 1, 4) # x -> * add_edge!(g, 2, 4) # y -> * add_edge!(g, 3, 5) # sin(x) -> sin(x) + x*y add_edge!(g, 4, 5) # x*y -> sin(x) + x*y add_edge!(g, 5, 6) # sin(x) + x*y -> z #add_edge!(g, 5, 7,) # ∂z/∂h₃ -> z #add_edge!(g, 4, 8,) # ∂h₃/∂h₂ -> h₂ = * #add_edge!(g, 8, 9,) # ∂z/∂h₂ -> ∂h₃/∂h₂ #add_edge!(g, 7, 9,) # ∂z/∂h₂ -> ∂h₃/∂h₂ #add_edge!(g, 3, 10,) # ∂h₃/∂h₁ -> h₁ #add_edge!(g, 10, 11,)# ∂z/∂h₁ -> ∂h₃/∂h₁ #add_edge!(g, 7, 11,) # ∂z/∂h₁ -> ∂z/∂h₃ #add_edge!(g, 2, 12,) # ∂h₂/∂y -> y #add_edge!(g, 9, 12,) # ∂h₂/∂y -> y #add_edge!(g, 1, 13,) # ∂h₂/∂x + ∂h₁/∂x -> y #add_edge!(g, 9, 14,) # "∂z/∂x" -> ∂z/∂h₂ #add_edge!(g, 11, 14,) # "∂z/∂x" -> ∂z/∂h₁ #add_edge!(g, 13, 14,) # "∂z/∂x" -> ∂h₂/∂x + ∂h₁/∂x # graphplot(adjacency_matrix(g), # names = [vertices[i].name for i in 1:n], # x = 0.25 .* [vertices[i].x for i in 1:n], # y = 0.25 .* [vertices[i].y falseor i in 1:n], # curves=false, # markercolor = [vertices[i].color for i in 1:n], # ) for n in [6, 7, 9, 11, 13, 14] #graphplot(adjacency_matrix(g)[1:n, 1:n], # names = [vertices[i].name for i in 1:n], # x = 0.25 .* [vertices[i].x for i in 1:n], # y = 0.25 .* [vertices[i].y for i in 1:n], # curves=false, # markercolor = [vertices[i].color for i in 1:n], #) names = [vertices[i].name for i in 1:length(vertices)] t = TikzGraphs.plot(g, names) TikzPictures.save(SVG("graphdiff_$(n).svg"),t) end
(* Title: Code_Rational.thy Author: Jose Divasón <jose.divasonm at unirioja.es> Author: Jesús Aransay <jesus-maria.aransay at unirioja.es> *) section\<open>Code Generation for rational numbers in Haskell\<close> theory Code_Rational imports (*VERY IMPORTANT! When code is exported, the order of the imports is very important. In this case, I have to import here the following three theories. They allow the computation of the Gauss-Jordan algorithm in Haskell*) "HOL-Library.Code_Real_Approx_By_Float" Code_Generation_IArrays (*These theories are necessary for the serialisation:*) "HOL-Library.Code_Target_Int" begin subsection\<open>Serializations\<close> text\<open>The following \<open>code_printing code_module\<close> module is the usual way to import libraries in Haskell. In this case, we rebind some functions from Data.Ratio. See @{url "https://lists.cam.ac.uk/pipermail/cl-isabelle-users/2013-June/msg00007.html"}\<close> code_printing code_module Rational \<rightharpoonup> (Haskell) \<open>module Rational(fract, numerator, denominator) where import qualified Data.Ratio import Data.Ratio(numerator, denominator) fract (a, b) = a Data.Ratio.% b\<close> context includes integer.lifting begin lift_definition Frct_integer :: "integer \<times> integer => rat" is "Frct :: int \<times> int => rat" . end consts Foo::rat code_datatype Foo context includes integer.lifting begin lemma [code]: "Rat.of_int a = Frct_integer (of_int a, 1)" by transfer (auto simp: Fract_of_int_eq Rat.of_int_def) definition numerator :: "rat => int" where "numerator x = fst (quotient_of x)" definition denominator :: "rat => int" where "denominator x = snd (quotient_of x)" lift_definition numerator_integer :: "rat => integer" is "numerator" . lift_definition denominator_integer :: "rat => integer" is "denominator" . lemma [code]: "inverse x = Frct_integer (denominator_integer x, numerator_integer x)" apply (cases x) apply transfer apply (auto simp: inverse_eq_divide numerator_def denominator_def quotient_of_Fract One_rat_def) done lemma quotient_of_num_den: "quotient_of x = ((numerator x), (denominator x))" unfolding numerator_def denominator_def by simp lemma [code]: "quotient_of x = (int_of_integer (numerator_integer x), int_of_integer(denominator_integer x))" by (transfer, simp add: quotient_of_num_den) end code_printing type_constructor rat \<rightharpoonup> (Haskell) "Prelude.Rational" | class_instance rat :: "HOL.equal" => (Haskell) - | constant "0 :: rat" \<rightharpoonup> (Haskell) "(Prelude.toRational (0::Integer))" | constant "1 :: rat" \<rightharpoonup> (Haskell) "(Prelude.toRational (1::Integer))" | constant "Frct_integer" \<rightharpoonup> (Haskell) "Rational.fract (_)" | constant "numerator_integer" \<rightharpoonup> (Haskell) "Rational.numerator (_)" | constant "denominator_integer" \<rightharpoonup> (Haskell) "Rational.denominator (_)" | constant "HOL.equal :: rat \<Rightarrow> rat \<Rightarrow> bool" \<rightharpoonup> (Haskell) "(_) == (_)" | constant "(<) :: rat => rat => bool" \<rightharpoonup> (Haskell) "_ < _" | constant "(\<le>) :: rat => rat => bool" \<rightharpoonup> (Haskell) "_ <= _" | constant "(+) :: rat \<Rightarrow> rat \<Rightarrow> rat" \<rightharpoonup> (Haskell) "(_) + (_)" | constant "(-) :: rat \<Rightarrow> rat \<Rightarrow> rat" \<rightharpoonup> (Haskell) "(_) - (_)" | constant "(*) :: rat \<Rightarrow> rat \<Rightarrow> rat" \<rightharpoonup> (Haskell) "(_) * (_)" | constant "(/) :: rat \<Rightarrow> rat \<Rightarrow> rat" \<rightharpoonup> (Haskell) " (_) '/ (_)" | constant "uminus :: rat => rat" \<rightharpoonup> (Haskell) "Prelude.negate" (* definition "test1 = (3::rat)" definition "test2 = (3/9::rat)" definition "test3 = (3/8 + 8/7::rat)" definition "test4 = (3/8 - 8/7::rat)" definition "test5 = (3/8 * 8/7::rat)" definition "test6 = (3/8 / 8/7::rat)" definition "test7 = (34 < (53 :: rat))" definition "test8 = (34 <= (53 :: rat))" definition "test9 = (inverse (8/5::rat))" definition "test10 = quotient_of (8/3::rat)" export_code test1 test2 test3 test4 test5 test6 test7 test8 test9 test10 in Haskell module_name "Rational_Haskell" file "haskell" *) end
[STATEMENT] lemma split_at_conv_split_at_it': assumes "(ts, ds) = split_at n xs" "(ts', ds') = split_at_it' acc n xs" shows "rev acc @ ts = ts'" and "ds = ds'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. rev acc @ ts = ts' &&& ds = ds' [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: (ts, ds) = split_at n xs (ts', ds') = split_at_it' acc n xs goal (1 subgoal): 1. rev acc @ ts = ts' &&& ds = ds' [PROOF STEP] by (induction acc n xs arbitrary: ts rule: split_at_it'.induct) (auto simp: split: prod.splits nat.splits)
= = Players = =
export PolyVar, @polyvar, @ncpolyvar export polyvecvar function polyarrayvar(::Type{PV}, prefix, indices...) where {PV} map(i -> PV("$(prefix)[$(join(i, ","))]"), Iterators.product(indices...)) end function buildpolyvar(::Type{PV}, var) where {PV} if isa(var, Symbol) var, :($(esc(var)) = $PV($"$var")) else isa(var, Expr) || error("Expected $var to be a variable name") Base.Meta.isexpr(var, :ref) || error("Expected $var to be of the form varname[idxset]") (2 ≤ length(var.args)) || error("Expected $var to have at least one index set") varname = var.args[1] prefix = string(varname) varname, :($(esc(varname)) = polyarrayvar($PV, $prefix, $(esc.(var.args[2:end])...))) end end function buildpolyvars(::Type{PV}, args) where {PV} vars = Symbol[] exprs = [] for arg in args var, expr = buildpolyvar(PV, arg) push!(vars, var) push!(exprs, expr) end vars, exprs end # Variable vector x returned garanteed to be sorted so that if p is built with x then vars(p) == x macro polyvar(args...) vars, exprs = buildpolyvars(PolyVar{true}, args) :($(foldl((x,y) -> :($x; $y), exprs, init=:())); $(Expr(:tuple, esc.(vars)...))) end macro ncpolyvar(args...) vars, exprs = buildpolyvars(PolyVar{false}, args) :($(foldl((x,y) -> :($x; $y), exprs, init=:())); $(Expr(:tuple, esc.(vars)...))) end struct PolyVar{C} <: AbstractVariable id::Int name::String function PolyVar{C}(name::AbstractString) where {C} # gensym returns something like Symbol("##42") # we first remove "##" and then parse it into an Int id = parse(Int, string(gensym())[3:end]) new(id, convert(String, name)) end end Base.hash(x::PolyVar, u::UInt) = hash(x.id, u) Base.broadcastable(x::PolyVar) = Ref(x) MP.name(v::PolyVar) = v.name function MP.name_base_indices(v::PolyVar) splits = split(v.name, r"[\[,\]]\s*", keepempty=false) if length(splits) == 1 return v.name, Int[] else return splits[1], parse.(Int, splits[2:end]) end end MP.monomial(v::PolyVar) = Monomial(v) _vars(v::PolyVar) = [v] iscomm(::Type{PolyVar{C}}) where {C} = C function mergevars(varsvec::Vector{Vector{PV}}) where {PV<:PolyVar} n = length(varsvec) is = ones(Int, n) maps = zeros.(Int, length.(varsvec)) nonempty = BitSet(findall(!isempty, varsvec)) vars = Vector{PV}() while !isempty(nonempty) imin = 0 for i in nonempty if imin == 0 || varsvec[i][is[i]] > varsvec[imin][is[imin]] imin = i end end var = varsvec[imin][is[imin]] push!(vars, var) for i in nonempty if var == varsvec[i][is[i]] maps[i][is[i]] = length(vars) if is[i] == length(varsvec[i]) pop!(nonempty, i) else is[i] += 1 end end end end vars, maps end
The Dill Stake is intended to be cut from metal using a CNC cutting system. Once fabricated, this stake can be used to show where you are growing dill in your garden. This artwork depicts a garden stake with dill written on it. The Dill Stake has been reviewed and tested by a machinist for compatibility with various CNC systems. This design can be easily modified with CAD software. Review the tables below for more detailed specifications.
(* Title: HOL/Induct/Common_Patterns.thy Author: Makarius *) section \<open>Common patterns of induction\<close> theory Common_Patterns imports MainRLT begin text \<open> The subsequent Isar proof schemes illustrate common proof patterns supported by the generic \<open>induct\<close> method. To demonstrate variations on statement (goal) structure we refer to the induction rule of Peano natural numbers: @{thm nat.induct [no_vars]}, which is the simplest case of datatype induction. We shall also see more complex (mutual) datatype inductions involving several rules. Working with inductive predicates is similar, but involves explicit facts about membership, instead of implicit syntactic typing. \<close> subsection \<open>Variations on statement structure\<close> subsubsection \<open>Local facts and parameters\<close> text \<open> Augmenting a problem by additional facts and locally fixed variables is a bread-and-butter method in many applications. This is where unwieldy object-level \<open>\<forall>\<close> and \<open>\<longrightarrow>\<close> used to occur in the past. The \<open>induct\<close> method works with primary means of the proof language instead. \<close> lemma fixes n :: nat and x :: 'a assumes "A n x" shows "P n x" using \<open>A n x\<close> proof (induct n arbitrary: x) case 0 note prem = \<open>A 0 x\<close> show "P 0 x" \<proof> next case (Suc n) note hyp = \<open>\<And>x. A n x \<Longrightarrow> P n x\<close> and prem = \<open>A (Suc n) x\<close> show "P (Suc n) x" \<proof> qed subsubsection \<open>Local definitions\<close> text \<open> Here the idea is to turn sub-expressions of the problem into a defined induction variable. This is often accompanied with fixing of auxiliary parameters in the original expression, otherwise the induction step would refer invariably to particular entities. This combination essentially expresses a partially abstracted representation of inductive expressions. \<close> lemma fixes a :: "'a \<Rightarrow> nat" assumes "A (a x)" shows "P (a x)" using \<open>A (a x)\<close> proof (induct n \<equiv> "a x" arbitrary: x) case 0 note prem = \<open>A (a x)\<close> and defn = \<open>0 = a x\<close> show "P (a x)" \<proof> next case (Suc n) note hyp = \<open>\<And>x. n = a x \<Longrightarrow> A (a x) \<Longrightarrow> P (a x)\<close> and prem = \<open>A (a x)\<close> and defn = \<open>Suc n = a x\<close> show "P (a x)" \<proof> qed text \<open> Observe how the local definition \<open>n = a x\<close> recurs in the inductive cases as \<open>0 = a x\<close> and \<open>Suc n = a x\<close>, according to underlying induction rule. \<close> subsubsection \<open>Simple simultaneous goals\<close> text \<open> The most basic simultaneous induction operates on several goals one-by-one, where each case refers to induction hypotheses that are duplicated according to the number of conclusions. \<close> lemma fixes n :: nat shows "P n" and "Q n" proof (induct n) case 0 case 1 show "P 0" \<proof> next case 0 case 2 show "Q 0" \<proof> next case (Suc n) case 1 note hyps = \<open>P n\<close> \<open>Q n\<close> show "P (Suc n)" \<proof> next case (Suc n) case 2 note hyps = \<open>P n\<close> \<open>Q n\<close> show "Q (Suc n)" \<proof> qed text \<open> The split into subcases may be deferred as follows -- this is particularly relevant for goal statements with local premises. \<close> lemma fixes n :: nat shows "A n \<Longrightarrow> P n" and "B n \<Longrightarrow> Q n" proof (induct n) case 0 { case 1 note \<open>A 0\<close> show "P 0" \<proof> next case 2 note \<open>B 0\<close> show "Q 0" \<proof> } next case (Suc n) note \<open>A n \<Longrightarrow> P n\<close> and \<open>B n \<Longrightarrow> Q n\<close> { case 1 note \<open>A (Suc n)\<close> show "P (Suc n)" \<proof> next case 2 note \<open>B (Suc n)\<close> show "Q (Suc n)" \<proof> } qed subsubsection \<open>Compound simultaneous goals\<close> text \<open> The following pattern illustrates the slightly more complex situation of simultaneous goals with individual local assumptions. In compound simultaneous statements like this, local assumptions need to be included into each goal, using \<open>\<Longrightarrow>\<close> of the Pure framework. In contrast, local parameters do not require separate \<open>\<And>\<close> prefixes here, but may be moved into the common context of the whole statement. \<close> lemma fixes n :: nat and x :: 'a and y :: 'b shows "A n x \<Longrightarrow> P n x" and "B n y \<Longrightarrow> Q n y" proof (induct n arbitrary: x y) case 0 { case 1 note prem = \<open>A 0 x\<close> show "P 0 x" \<proof> } { case 2 note prem = \<open>B 0 y\<close> show "Q 0 y" \<proof> } next case (Suc n) note hyps = \<open>\<And>x. A n x \<Longrightarrow> P n x\<close> \<open>\<And>y. B n y \<Longrightarrow> Q n y\<close> then have some_intermediate_result \<proof> { case 1 note prem = \<open>A (Suc n) x\<close> show "P (Suc n) x" \<proof> } { case 2 note prem = \<open>B (Suc n) y\<close> show "Q (Suc n) y" \<proof> } qed text \<open> Here \<open>induct\<close> provides again nested cases with numbered sub-cases, which allows to share common parts of the body context. In typical applications, there could be a long intermediate proof of general consequences of the induction hypotheses, before finishing each conclusion separately. \<close> subsection \<open>Multiple rules\<close> text \<open> Multiple induction rules emerge from mutual definitions of datatypes, inductive predicates, functions etc. The \<open>induct\<close> method accepts replicated arguments (with \<open>and\<close> separator), corresponding to each projection of the induction principle. The goal statement essentially follows the same arrangement, although it might be subdivided into simultaneous sub-problems as before! \<close> datatype foo = Foo1 nat | Foo2 bar and bar = Bar1 bool | Bar2 bazar and bazar = Bazar foo text \<open> The pack of induction rules for this datatype is: @{thm [display] foo.induct [no_vars] bar.induct [no_vars] bazar.induct [no_vars]} This corresponds to the following basic proof pattern: \<close> lemma fixes foo :: foo and bar :: bar and bazar :: bazar shows "P foo" and "Q bar" and "R bazar" proof (induct foo and bar and bazar) case (Foo1 n) show "P (Foo1 n)" \<proof> next case (Foo2 bar) note \<open>Q bar\<close> show "P (Foo2 bar)" \<proof> next case (Bar1 b) show "Q (Bar1 b)" \<proof> next case (Bar2 bazar) note \<open>R bazar\<close> show "Q (Bar2 bazar)" \<proof> next case (Bazar foo) note \<open>P foo\<close> show "R (Bazar foo)" \<proof> qed text \<open> This can be combined with the previous techniques for compound statements, e.g.\ like this. \<close> lemma fixes x :: 'a and y :: 'b and z :: 'c and foo :: foo and bar :: bar and bazar :: bazar shows "A x foo \<Longrightarrow> P x foo" and "B1 y bar \<Longrightarrow> Q1 y bar" "B2 y bar \<Longrightarrow> Q2 y bar" and "C1 z bazar \<Longrightarrow> R1 z bazar" "C2 z bazar \<Longrightarrow> R2 z bazar" "C3 z bazar \<Longrightarrow> R3 z bazar" proof (induct foo and bar and bazar arbitrary: x and y and z) oops subsection \<open>Inductive predicates\<close> text \<open> The most basic form of induction involving predicates (or sets) essentially eliminates a given membership fact. \<close> inductive Even :: "nat \<Rightarrow> bool" where zero: "Even 0" | double: "Even (2 * n)" if "Even n" for n lemma assumes "Even n" shows "P n" using assms proof induct case zero show "P 0" \<proof> next case (double n) note \<open>Even n\<close> and \<open>P n\<close> show "P (2 * n)" \<proof> qed text \<open> Alternatively, an initial rule statement may be proven as follows, performing ``in-situ'' elimination with explicit rule specification. \<close> lemma "Even n \<Longrightarrow> P n" proof (induct rule: Even.induct) oops text \<open> Simultaneous goals do not introduce anything new. \<close> lemma assumes "Even n" shows "P1 n" and "P2 n" using assms proof induct case zero { case 1 show "P1 0" \<proof> next case 2 show "P2 0" \<proof> } next case (double n) note \<open>Even n\<close> and \<open>P1 n\<close> and \<open>P2 n\<close> { case 1 show "P1 (2 * n)" \<proof> next case 2 show "P2 (2 * n)" \<proof> } qed text \<open> Working with mutual rules requires special care in composing the statement as a two-level conjunction, using lists of propositions separated by \<open>and\<close>. For example: \<close> inductive Evn :: "nat \<Rightarrow> bool" and Odd :: "nat \<Rightarrow> bool" where zero: "Evn 0" | succ_Evn: "Odd (Suc n)" if "Evn n" for n | succ_Odd: "Evn (Suc n)" if "Odd n" for n lemma "Evn n \<Longrightarrow> P1 n" "Evn n \<Longrightarrow> P2 n" "Evn n \<Longrightarrow> P3 n" and "Odd n \<Longrightarrow> Q1 n" "Odd n \<Longrightarrow> Q2 n" proof (induct rule: Evn_Odd.inducts) case zero { case 1 show "P1 0" \<proof> } { case 2 show "P2 0" \<proof> } { case 3 show "P3 0" \<proof> } next case (succ_Evn n) note \<open>Evn n\<close> and \<open>P1 n\<close> \<open>P2 n\<close> \<open>P3 n\<close> { case 1 show "Q1 (Suc n)" \<proof> } { case 2 show "Q2 (Suc n)" \<proof> } next case (succ_Odd n) note \<open>Odd n\<close> and \<open>Q1 n\<close> \<open>Q2 n\<close> { case 1 show "P1 (Suc n)" \<proof> } { case 2 show "P2 (Suc n)" \<proof> } { case 3 show "P3 (Suc n)" \<proof> } qed text \<open> Cases and hypotheses in each case can be named explicitly. \<close> inductive star :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool" for r where refl: "star r x x" for x | step: "star r x z" if "r x y" and "star r y z" for x y z text \<open>Underscores are replaced by the default name hyps:\<close> lemmas star_induct = star.induct [case_names base step[r _ IH]] lemma "star r x y \<Longrightarrow> star r y z \<Longrightarrow> star r x z" proof (induct rule: star_induct) print_cases case base then show ?case . next case (step a b c) print_facts from step.prems have "star r b z" by (rule step.IH) with step.r show ?case by (rule star.step) qed end
function c = phaseunlockreal(c,a,M,varargin) %PHASEUNLOCKREAL Undo phase lock of Gabor coefficients % Usage: c=phaseunlockreal(c,a,M); % % `phaseunlockreal(c,a,M)` removes phase locking from the Gabor coefficients *c*. % The coefficient must have been obtained from a |dgtreal| with parameter *a* % and using the 'timeinv' flag. % % Phase locking the coefficients modifies them so as if they were obtained % from a frequency-invariant Gabor system. A filter bank produces phase locked % coefficients. % % See also: dgt, phaselockreal % % References: puc95 % AUTHOR: Peter Balazs, Peter L. Søndergaard, Zdenek Prusa % TESTING: OK % REFERENCE: OK if nargin<3 error('%s: Too few input parameters.',upper(mfilename)); end; if ~isscalar(a) || ~isnumeric(a) || rem(a,1)~=0 error('a must be integer'); end; if ~isscalar(M) || ~isnumeric(M) || rem(M,1)~=0 error('M must be integer'); end; definput.flags.accuracy={'normal', 'precise'}; flags=ltfatarghelper({},definput,varargin); M2=size(c,1); M2user = floor(M/2) + 1; if M2~=M2user error('%s: Size of s does not comply with M.',upper(mfilename)); end N=size(c,2); if flags.do_normal TimeInd = (0:(N-1))*a; FreqInd = (0:(M2-1)); phase = FreqInd'*TimeInd; phase = mod(phase,M); phase = exp(-2*1i*pi*phase/M); % Handle multisignals c=bsxfun(@times,c,phase); elseif flags.do_precise frames = ifftreal(c,M); for n=0:N-1 frames(:,n+1,:) = circshift(frames(:,n+1,:),n*a); end c = fftreal(frames); end
This single level home in a quiet court delivers an exceptional opportunity to enter the market or add to your portfolio. In a floor plan laid out to ensure no wasted space, it offers formal lounge and casual living overlooked by a kitchen featuring stainless steel cooker and plenty of storage options, complemented by an enclosed veranda perfect for year round living and entertaining. Three bedrooms, all with robes, are served by a large bathroom with the convenience of a separate toilet. Currently comfortable with scope for a contemporary update, it&#x2019;s a short walk from Andrew Place shops, cafe and supermarket, Warrawee Park, Concord and Loyola College. The tram on Plenty Road is an easy stroll away.
theory subspace imports topological_space begin definition (in topological_space) subspace_topology :: "'a set \<Rightarrow>'a set set" where (* "subspace_topology S \<equiv> { \<forall>t \<in> T. S \<inter> t } "*) "subspace_topology S = {a .\<exists>u\<in>T. a = S \<inter> u }" thm topological_space.subspace_topology_def lemma (in topological_space) subspace_inter[simp ,intro]: assumes a1 : "S \<subseteq> X" and a2 : "x \<in> {a. \<exists>u\<in>T. a = S \<inter> u}" and a3 : "y \<in> {a. \<exists>u\<in>T. a = S \<inter> u}" shows "x \<inter> y \<in> {a. \<exists>u\<in>T. a = S \<inter> u}" proof- from a2 have b : "\<exists>u1\<in>T. x = S \<inter> u1 " apply simp done from a3 have c : "\<exists>u2\<in>T. y = S \<inter> u2 " apply simp done from b c have d : "\<exists>u1\<in>T. \<exists>u2\<in> T. x \<inter> y = S \<inter> (u1 \<inter> u2)" apply blast done from d have e : "\<exists>u1\<in>T. \<exists>u2\<in> T. x \<inter> y = S \<inter> (u1 \<inter> u2) \<and> (u1 \<inter> u2 \<in> T)" apply (simp add:topological_space_def) done from e have f : "\<exists>u3\<in>T. x \<inter> y = S \<inter> u3 " apply blast done from a1 a2 a3 f show ?thesis apply blast done qed definition (in topological_space) map_B :: "['a set , 'a set ]\<Rightarrow> 'a set " where " map_B S a = \<Union>{u. a = S \<inter> u \<and> u \<in> T}" lemma (in topological_space) subspace_in_T[simp,intro]: "{u. a=S \<inter> u \<and> u \<in> T} \<subseteq> T " apply blast done lemma (in topological_space)subspace_union[simp,intro]: assumes a1: "S \<subseteq> X" and a2: " A \<subseteq> {a. \<exists>u\<in>T. a = S \<inter> u}" (* and a3: "\<And>a. \<lbrakk>a\<in>A\<rbrakk> \<Longrightarrow> B a \<in> T " and a4: "\<And>a. \<lbrakk>a\<in>A\<rbrakk> \<Longrightarrow> ( a = (S \<inter> (B a)))"*) shows "\<exists>u\<in>T. \<Union>A = S \<inter> u" proof- from a2 have s1: "\<Union>A = \<Union>{a. a\<in>A}" apply (simp) done from a2 have s2 : "\<Union>{a. a\<in>A}= \<Union>{c. \<exists>a\<in>A. c =a }" apply (simp) done from a1 a2 have s3: "\<And>a. \<lbrakk> a\<in>A \<rbrakk> \<Longrightarrow> (map_B S a ) \<in> T" apply(simp add:map_B_def subspace_in_T) done (*apply blast done*) from a2 s3 have s4: "\<And>a. \<lbrakk>a\<in>A\<rbrakk> \<Longrightarrow> ( a = (S \<inter> (map_B S a)))" apply (simp add:map_B_def) apply blast done from s4 have s5 : "{c. \<exists>a\<in>A. c=a}={c. \<exists>a\<in>A. c= S \<inter> map_B S a } " apply simp done from s1 s2 s5 have s6 : "\<Union>A = \<Union>{c. \<exists>a\<in>A. c=S \<inter> map_B S a } " apply simp done from s3 s4 have s7 : "\<Union>{c. \<exists>a\<in>A. c= S \<inter> (map_B S a)} = \<Union>{u. \<exists>a\<in>A. u =(map_B S a) } \<inter> S " apply blast done from a2 s3 s4 have s8: "\<And>t. \<lbrakk>t\<in>{u. \<exists>a\<in>A. u =map_B S a}\<rbrakk> \<Longrightarrow> t \<in> T" apply (simp add :Pi_def) apply blast done from s8 have s9 : "{u. \<exists>a\<in>A. u =map_B S a} \<subseteq> T " apply blast done from s9 have s10 : "\<Union>{u. \<exists>a\<in>A. u =map_B S a} \<in> T " apply(simp add:map_B_def subspace_in_T) done from s10 have s11 : "\<exists>u\<in>T. u=\<Union>{u. \<exists>a\<in>A. u =map_B S a}" apply simp done from s1 s2 s6 s7 have s12: "\<Union>A = \<Union>{u. \<exists>a\<in>A. u =map_B S a } \<inter> S " apply simp done from s11 s12 have s13 : "\<exists>u\<in>T. \<Union>A= u \<inter> S" apply blast done have s14 : "\<forall>u\<in>T. u \<inter> S = S \<inter> u" apply blast done (*from m n have o: "\<exists>u\<in>T. \<Union>A = S \<inter> u" apply simp done*) from s13 s14 show ?thesis apply simp done qed lemma (in topological_space)subspace_union_1[simp,intro]: "\<lbrakk> S \<subseteq> X ; A \<subseteq> {a. \<exists>u\<in>T. a = S \<inter> u}\<rbrakk> \<Longrightarrow> \<exists>u\<in>T. \<Union>A = S \<inter> u" apply (blast intro: subspace_union) done lemma (in topological_space) empty_in_subspace: "{} \<in> {a. \<exists>u\<in>T. a = S \<inter> u}" apply simp apply auto done lemma (in topological_space)S_in_subspace: " S \<subseteq> X \<Longrightarrow> S \<in> {a. \<exists>u\<in>T. a = S \<inter> u}" apply auto done thm topological_space.subspace_topology_def lemma (in topological_space) subspace_is_top: "\<lbrakk>S \<subseteq> X\<rbrakk> \<Longrightarrow> topological_space S (subspace_topology S)" apply (simp add:subspace_topology_def) apply (rule topological_space.intro) apply blast apply (rule empty_in_subspace) apply (rule S_in_subspace,assumption+) apply (erule subspace_inter,assumption+) apply (simp add: subspace_union_1) done end
clusters <- hclust(dist(iris[, -5])) plot(clusters)
config = MOI.Test.TestConfig() optimize!(mock) = MOIU.mock_optimize!(mock, [0.0, 0.0], (MOI.VectorAffineFunction{Float64}, MOI.Nonnegatives) => [[1.0]], (MOI.VectorAffineFunction{Float64}, MOI.Zeros) => [[1.0]]) for mock in mocks(optimize!) Tests.sos_term_test(mock, config) Tests.sdsos_term_test(mock, config) Tests.dsos_term_test(mock, config) end
#include <string.h> #include <stdlib.h> #include <arpa/inet.h> #include <boost/thread/mutex.hpp> #include "./../Game/cmdtypes.h" #include "./../Game/log.h" #include "./../utils/stringbuilder.hpp" #include "./../Game/getdefinevalue.h" #include "./../server.h" #include "./../Monster/monster.h" #include "diskdbmanager.h" using namespace std; DiskDBManager::DiskDBManager() { } DiskDBManager::~DiskDBManager() { } bool DiskDBManager::Connect(Configuration con) { m_PGconn = PQsetdbLogin(con.ip, con.port, NULL, NULL,con.dbName, con.user, con.password); if(PQstatus(m_PGconn) != CONNECTION_OK) { printf("PQconnectdb error\n"); return false; } else return true; } bool DiskDBManager::Connect() { // m_PGconn = PQconnectdb("hostaddr = 127.0.0.1 port = 5432 dbname = my_database user = postgres password = postgres connect_timeout = 1"); m_PGconn = PQconnectdb("hostaddr = 139.196.165.107 port = 5433 dbname = game user = game password = houfang2015 connect_timeout = 1"); // m_PGconn = PQconnectdb("host = localhost dbname = my_database user = postgres password = postgres"); if(PQstatus(m_PGconn) != CONNECTION_OK) { printf("PQconnectdb error\n"); return false; } else return true; } bool DiskDBManager::Disconnect() { PQfinish(m_PGconn); return true; } //从数据库中得到查询的数据 void* DiskDBManager::Get(const char* str) { return NULL; } //执行不返回数据的命令 update insert delete move hf_int32 DiskDBManager::Set(const char *str,...) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_ExecStatusType = PQresultStatus(t_PGresult); if(t_ExecStatusType != PGRES_COMMAND_OK) //成功完成一个不返回数据的命令 { printf("%d\n", t_ExecStatusType); printf("PQexec error\n"); return -1; } else { return atoi(PQcmdTuples(t_PGresult)); } } //执行返回数据的命令 select hf_int32 DiskDBManager::GetSqlResult(const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) //执行一个返回数据的操作 { return -1; } else { return PQntuples(t_PGresult); } } //得到玩家的登录信息 hf_int32 DiskDBManager::GetPlayerUserId(STR_PlayerLoginUserId* user,const char *str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_ExecStatusType = PQresultStatus((t_PGresult)); StringBuilder sbd; sbd<<"Function GetPlayerUserID :" << str; Logger::GetLogger()->Debug(sbd.str()); if(t_ExecStatusType != PGRES_TUPLES_OK) // PGRES_TUPLES_OK表示成功执行一个返回数据的查询查询 { printf("PQexec error:%d\n", t_ExecStatusType); return -1; } else { int t_row = PQntuples(t_PGresult); //行数 for(int i = 0; i < t_row; i++) { memcpy(user->userName, PQgetvalue(t_PGresult, i, 0), PQgetlength(t_PGresult, i, 0)); memcpy(user->password, PQgetvalue(t_PGresult, i, 1), PQgetlength(t_PGresult, i, 1)); } return t_row; } } hf_int32 DiskDBManager::GetPlayerRoleList(ResRoleList* RoleList, const char *str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_ExecStatusType = PQresultStatus((t_PGresult)); StringBuilder sbd; // sbd<<"Function GetPlayerRoleList :" << str; // Logger::GetLogger()->Debug(sbd.str()); if(t_ExecStatusType != PGRES_TUPLES_OK) // PGRES_TUPLES_OK表示成功执行一个返回数据的查询查询 { printf("PQexec error\n"); return -1; } else { int t_row = PQntuples(t_PGresult); //行数 STR_RoleBasicInfo t_RoleInfo; //打包数据 for(int i = 0; i < t_row; i++) { memset(&t_RoleInfo, 0, sizeof(t_RoleInfo)); memcpy(t_RoleInfo.Nick, PQgetvalue(t_PGresult, i, 0), PQgetlength(t_PGresult, i, 0)); t_RoleInfo.RoleID = atoi(PQgetvalue(t_PGresult, i, 1)); t_RoleInfo.Profession = atoi(PQgetvalue(t_PGresult, i, 2)); t_RoleInfo.Level = atoi(PQgetvalue(t_PGresult, i, 3)); t_RoleInfo.Sex = atoi(PQgetvalue(t_PGresult, i, 4)); t_RoleInfo.Figure = atoi(PQgetvalue(t_PGresult, i, 5)); t_RoleInfo.FigureColor = atoi(PQgetvalue(t_PGresult, i, 6)); t_RoleInfo.Face = atoi(PQgetvalue(t_PGresult, i, 7)); t_RoleInfo.Eye = atoi(PQgetvalue(t_PGresult, i, 8)); t_RoleInfo.Hair = atoi(PQgetvalue(t_PGresult, i, 9)); t_RoleInfo.HairColor = atoi(PQgetvalue(t_PGresult, i, 10)); t_RoleInfo.ModeID = atoi(PQgetvalue(t_PGresult, i, 11)); t_RoleInfo.SkirtID = atoi(PQgetvalue(t_PGresult, i, 12)); RoleList->m_Role.push_back(t_RoleInfo); } return t_row; } } hf_int32 DiskDBManager::GetPlayerRegisterRoleInfo(STR_RoleBasicInfo* t_RoleInfo, const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_ExecStatusType = PQresultStatus((t_PGresult)); if(t_ExecStatusType != PGRES_TUPLES_OK) // PGRES_TUPLES_OK表示成功执行一个返回数据的查询查询 { printf("PQexec error\n"); return -1; } else { int t_row = PQntuples(t_PGresult); //行数 //打包数据 if(t_row == 1) { memcpy(t_RoleInfo->Nick, PQgetvalue(t_PGresult, 0, 0), PQgetlength(t_PGresult, 0, 0)); t_RoleInfo->RoleID = atoi(PQgetvalue(t_PGresult, 0, 1)); t_RoleInfo->Profession = atoi(PQgetvalue(t_PGresult, 0, 2)); t_RoleInfo->Level = atoi(PQgetvalue(t_PGresult, 0, 3)); t_RoleInfo->Sex = atoi(PQgetvalue(t_PGresult, 0, 4)); t_RoleInfo->Figure = atoi(PQgetvalue(t_PGresult, 0, 5)); t_RoleInfo->FigureColor = atoi(PQgetvalue(t_PGresult, 0, 6)); t_RoleInfo->Face = atoi(PQgetvalue(t_PGresult, 0, 7)); t_RoleInfo->Eye = atoi(PQgetvalue(t_PGresult, 0, 8)); t_RoleInfo->Hair = atoi(PQgetvalue(t_PGresult, 0, 9)); t_RoleInfo->HairColor = atoi(PQgetvalue(t_PGresult, 0, 10)); t_RoleInfo->ModeID = atoi(PQgetvalue(t_PGresult, 0, 11)); t_RoleInfo->SkirtID = atoi(PQgetvalue(t_PGresult, 0, 12)); } return t_row; } } bool DiskDBManager::IsConnected() { if ( PQstatus(m_PGconn) != CONNECTION_OK ) return false; else return true; } hf_int32 DiskDBManager::GetPlayerInitPos(STR_PackPlayerPosition *pos, const char *sql) { if ( ! IsConnected()) return -1; m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, sql); m_mtx.unlock(); ExecStatusType t_ExecStatusType = PQresultStatus((t_PGresult)); if(t_ExecStatusType != PGRES_TUPLES_OK) // PGRES_TUPLES_OK表示成功执行一个返回数据的查询查询 { std::ostringstream os; os<<"SQL:"<<sql<<" Execute error"; Logger::GetLogger()->Error(os.str().c_str()); return -1; } else { int t_row = PQntuples(t_PGresult); //行数 //打包数据 if(t_row == 1) { istringstream( PQgetvalue(t_PGresult,0,0) ) >> pos->Pos_x; istringstream( PQgetvalue(t_PGresult,0,1) ) >> pos->Pos_y; istringstream( PQgetvalue(t_PGresult,0,2) ) >> pos->Pos_z; istringstream( PQgetvalue(t_PGresult,0,3) ) >> pos->Direct; istringstream( PQgetvalue(t_PGresult,0,4) ) >> pos->MapID; pos->ActID = atoi(PQgetvalue(t_PGresult, 0, 5)); // istringstream( PQgetvalue(t_PGresult,0,5) ) >> pos->ActID; } return t_row; } } //从数据库中查询怪物条目 hf_int32 DiskDBManager:: GetMonsterSpawns(umap_monsterSpawns* monsterSpawns) { const hf_char* str = "select * from T_MonsterSpawns;"; m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_ExecStatusType = PQresultStatus(t_PGresult); if(t_ExecStatusType != PGRES_TUPLES_OK) //成功执行一个返回数据的查询查询 { std::ostringstream os; os<<"Function : GetMonsterSpawns SQL: '"<<str<<"'' Execute Error"; // Logger::GetLogger()->Error(os.str()); return -1; } else { int t_row = PQntuples(t_PGresult); //行数 //为结果分配内存 STR_MonsterSpawns t_monsterSpawns; //打包数据 for(int i = 0; i < t_row; i++) { t_monsterSpawns.MonsterTypeID = atoi(PQgetvalue(t_PGresult, i, 0)); t_monsterSpawns.SpawnsPosID = atoi(PQgetvalue(t_PGresult, i,1)); t_monsterSpawns.Pos_x = atof(PQgetvalue(t_PGresult, i,2)); t_monsterSpawns.Pos_y = atof(PQgetvalue(t_PGresult, i, 3)); t_monsterSpawns.Pos_z = atof(PQgetvalue(t_PGresult, i, 4)); t_monsterSpawns.Boundary = atof(PQgetvalue(t_PGresult, i,5)); t_monsterSpawns.MapID = atoi(PQgetvalue(t_PGresult, i, 6)); t_monsterSpawns.Amount = atoi(PQgetvalue(t_PGresult, i, 7)); (*monsterSpawns)[t_monsterSpawns.SpawnsPosID] = t_monsterSpawns; } return t_row; } } //从数据库中查询怪物属性 hf_int32 DiskDBManager::GetMonsterType(umap_monsterType* monsterType) { const hf_char* str = "select * from T_MonsterType;"; m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { Logger::GetLogger()->Error("select MosnterType error"); return -1; } else { int t_row = PQntuples(t_PGresult); STR_MonsterType t_monsterType; // 打包数据 for(int i = 0; i < t_row; i++) { memset(&t_monsterType, 0, sizeof(STR_MonsterType)); t_monsterType.MonsterTypeID = atoi(PQgetvalue(t_PGresult, i, 0)); memcpy(t_monsterType.MonsterName, PQgetvalue(t_PGresult, i, 1), PQgetlength(t_PGresult, i, 1)); t_monsterType.HP = atoi(PQgetvalue(t_PGresult, i, 2)); t_monsterType.PhysicalAttack = atoi(PQgetvalue(t_PGresult, i, 3)); t_monsterType.MagicAttack = atoi(PQgetvalue(t_PGresult, i, 4)); t_monsterType.PhysicalDefense = atoi(PQgetvalue(t_PGresult, i, 5)); t_monsterType.MagicDefense = atoi(PQgetvalue(t_PGresult, i, 6)); t_monsterType.Attackrate = atoi(PQgetvalue(t_PGresult, i, 7)); t_monsterType.MoveRate = atoi(PQgetvalue(t_PGresult, i, 8)); t_monsterType.Crit_Rate = atof(PQgetvalue(t_PGresult, i, 9)); t_monsterType.Dodge_Rate = atof(PQgetvalue(t_PGresult, i, 10)); t_monsterType.Hit_Rate = atof(PQgetvalue(t_PGresult, i, 11)); t_monsterType.RankID = atoi(PQgetvalue(t_PGresult, i, 12)); t_monsterType.Level = atoi(PQgetvalue(t_PGresult, i, 13)); t_monsterType.AttackTypeID = atoi(PQgetvalue(t_PGresult, i, 14)); // t_monsterType.AttackRange = atoi(PQgetvalue(t_PGresult, i, 15)); (*monsterType)[t_monsterType.MonsterTypeID] = t_monsterType; } return t_row; } } hf_int32 DiskDBManager::GetTaskProfile(umap_taskProfile TaskProfile) { const hf_char* str = "select * from t_taskprofile;"; m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { Logger::GetLogger()->Error("select t_taskprofile error"); return -1; } else { int t_row = PQntuples(t_PGresult); STR_TaskProfile t_profile; for(int i = 0; i < t_row; i++) { memset(&t_profile, 0, sizeof(STR_TaskProfile)); t_profile.TaskID = atoi(PQgetvalue(t_PGresult, i, 0)); memcpy(t_profile.TaskName, PQgetvalue(t_PGresult, i, 1), PQgetlength(t_PGresult, i, 1)); t_profile.StartNPCID = atoi(PQgetvalue(t_PGresult, i, 2)); t_profile.FinishNPCID = atoi(PQgetvalue(t_PGresult, i, 3)); t_profile.AcceptModeID = atoi(PQgetvalue(t_PGresult, i, 4)); t_profile.FinishModeID = atoi(PQgetvalue(t_PGresult, i, 5)); t_profile.Status = 1; //未接取 (*TaskProfile)[t_profile.TaskID] = t_profile; } return t_row; } } hf_int32 DiskDBManager::GetTaskDialogue(umap_dialogue* TaskDialogue) { const hf_char* str = "select * from t_taskdialogue;"; m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { Logger::GetLogger()->Error("select t_taskDialogue error"); return -1; } else { int t_row = PQntuples(t_PGresult); STR_TaskDlg t_dialogue; for(int i = 0; i < t_row; i++) { memset(&t_dialogue, 0, sizeof(STR_TaskDlg)); t_dialogue.TaskID = atoi(PQgetvalue(t_PGresult, i, 0)); t_dialogue.StartLen = PQgetlength(t_PGresult, i, 1) + 1; // t_dialogue.ExeLen = PQgetlength(t_PGresult, i, 2) + 1; t_dialogue.FinishLen = PQgetlength(t_PGresult, i, 2) + 1; memcpy(t_dialogue.StartDialogue, PQgetvalue(t_PGresult, i,1), t_dialogue.StartLen - 1); // memcpy(t_dialogue.ExeDialogue, PQgetvalue(t_PGresult, i, 2), t_dialogue.ExeLen - 1); memcpy(t_dialogue.FinishDialogue, PQgetvalue(t_PGresult, i, 2), t_dialogue.FinishLen - 1); (*TaskDialogue).insert(make_pair(t_dialogue.TaskID,t_dialogue)); } return t_row; } } hf_int32 DiskDBManager::GetTaskExeDialogue(umap_exeDialogue* TaskExeDialogue) { const hf_char* str = "select * from t_taskexedialogue;"; m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { Logger::GetLogger()->Error("select t_taskDialogue error"); return -1; } else { int t_row = PQntuples(t_PGresult); if(t_row == 0) { return 0; } STR_TaskExeDlg t_dialogue; for(int i = 0; i < t_row; i++) { memset(&t_dialogue, 0, sizeof(STR_TaskExeDlg)); t_dialogue.TaskID = atoi(PQgetvalue(t_PGresult, i, 0)); t_dialogue.AimID = atoi(PQgetvalue(t_PGresult, i, 1)); t_dialogue.ExeLen = PQgetlength(t_PGresult, i, 2) + 1; memcpy(t_dialogue.ExeDialogue, PQgetvalue(t_PGresult, i, 2), t_dialogue.ExeLen - 1); umap_exeDialogue::iterator it = TaskExeDialogue->find(t_dialogue.TaskID); if(it == TaskExeDialogue->end()) { vector<STR_TaskExeDlg> t_exeDlg; t_exeDlg.push_back(t_dialogue); (*TaskExeDialogue)[t_dialogue.TaskID] = t_exeDlg; } else { it->second.push_back(t_dialogue); } } return t_row; } } hf_int32 DiskDBManager::GetTaskDescription(umap_taskDescription* TaskDesc) { const hf_char* str = "select * from t_taskdescription;"; m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { Logger::GetLogger()->Error("select t_taskdescrition error"); return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_PackTaskDescription t_desc; for(int i = 0; i < t_row; i++) { memset(t_desc.Description, 0, sizeof(t_desc.Description)); t_desc.TaskID = atoi(PQgetvalue(t_PGresult, i, 0)); t_desc.TaskPropsID = atoi(PQgetvalue(t_PGresult, i, 1)); t_desc.Time = atoi(PQgetvalue(t_PGresult, i, 2)); memcpy(t_desc.Description, PQgetvalue(t_PGresult, i, 3), PQgetlength(t_PGresult, i, 3)); (*TaskDesc).insert(make_pair(t_desc.TaskID,t_desc)); } return t_row; } } hf_int32 DiskDBManager::GetTaskAim(umap_taskAim* TaskAim) { const hf_char* str = "select * from t_taskaim;"; m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { Logger::GetLogger()->Error("select t_taskaim error"); return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_TaskAim t_Aim; for(int i = 0; i < t_row; i++) { t_Aim.TaskID = atoi(PQgetvalue(t_PGresult, i, 0)); t_Aim.AimID = atoi(PQgetvalue(t_PGresult, i, 1)); t_Aim.Amount = atoi(PQgetvalue(t_PGresult, i, 2)); t_Aim.ExeModeID = atoi(PQgetvalue(t_PGresult, i, 3)); umap_taskAim::iterator it = TaskAim->find(t_Aim.TaskID); if(it == TaskAim->end()) { vector<STR_TaskAim> vecAim; vecAim.push_back(t_Aim); (*TaskAim)[t_Aim.TaskID] = vecAim; } else { it->second.push_back(t_Aim); } } return t_row; } } hf_int32 DiskDBManager::GetTaskReward(umap_taskReward* TaskReward) { const char* str = "select * from t_taskreward;"; m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { Logger::GetLogger()->Error("select t_taskaim error"); return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_TaskReward t_reward; for(int i = 0; i < t_row; i++) { t_reward.TaskID = atoi(PQgetvalue(t_PGresult, i, 0)); t_reward.Experience = atoi(PQgetvalue(t_PGresult, i, 1)); t_reward.Money = atoi(PQgetvalue(t_PGresult, i, 2)); t_reward.SkillID = atoi(PQgetvalue(t_PGresult, i, 3)); t_reward.TitleID = atoi(PQgetvalue(t_PGresult, i, 4)); t_reward.Attribute = atoi(PQgetvalue(t_PGresult, i, 5)); (*TaskReward).insert(make_pair(t_reward.TaskID,t_reward)); } return t_row; } } hf_int32 DiskDBManager::GetGoodsReward(umap_goodsReward* GoodsReward) { const char* str = "select * from t_GoodsReward;"; m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { Logger::GetLogger()->Error("select t_GoodsReward error"); return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_GoodsReward t_good; vector<STR_GoodsReward> v_goodReward; for(int i = 0; i < t_row; i++) { v_goodReward.clear(); hf_uint32 TaskID = atoi(PQgetvalue(t_PGresult, i, 0)); t_good.GoodsID = atoi(PQgetvalue(t_PGresult, i, 1)); t_good.Count = atoi(PQgetvalue(t_PGresult, i, 2)); t_good.Type = atoi(PQgetvalue(t_PGresult, i, 3)); v_goodReward.push_back(t_good); umap_goodsReward::iterator it = GoodsReward->find(TaskID); if(it != GoodsReward->end()) { it->second.push_back(t_good); } else { (*GoodsReward)[TaskID] = v_goodReward; } } return t_row; } } //查询任务条件 hf_int32 DiskDBManager::GetTaskPremise(umap_taskPremise* t_TaskPremise) { const char* str = "select * from t_taskPremise;"; m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_TaskPremise t_taskPremise; for(int i = 0; i < t_row; i++) { t_taskPremise.TaskID = atoi(PQgetvalue(t_PGresult, i, 0)); t_taskPremise.PreTaskID = atoi(PQgetvalue(t_PGresult, i, 1)); t_taskPremise.CrmtTaskID = atoi(PQgetvalue(t_PGresult, i, 2)); t_taskPremise.GoodsID = atoi(PQgetvalue(t_PGresult, i, 3)); t_taskPremise.TitleID = atoi(PQgetvalue(t_PGresult, i, 4)); t_taskPremise.DungeonID = atoi(PQgetvalue(t_PGresult, i, 5)); t_taskPremise.GenderID = atoi(PQgetvalue(t_PGresult, i, 6)); t_taskPremise.Level = atoi(PQgetvalue(t_PGresult, i, 7)); t_taskPremise.JobID = atoi(PQgetvalue(t_PGresult, i, 8)); (*t_TaskPremise).insert(make_pair(t_taskPremise.TaskID, t_taskPremise)); } return t_row; } } //查询任务进度 hf_int32 DiskDBManager::GetPlayerTaskProcess(umap_taskProcess TaskProcess, const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_TaskProcess t_taskProcess; for(int i = 0; i < t_row; i++) { memset(&t_taskProcess, 0, sizeof(STR_TaskProcess)); t_taskProcess.TaskID = atoi(PQgetvalue(t_PGresult, i, 1)); t_taskProcess.AimID = atoi(PQgetvalue(t_PGresult, i, 2)); t_taskProcess.FinishCount = atoi(PQgetvalue(t_PGresult, i, 3)); t_taskProcess.AimAmount = atoi(PQgetvalue(t_PGresult, i, 4)); t_taskProcess.ExeModeID = atoi(PQgetvalue(t_PGresult, i, 5)); _umap_taskProcess::iterator it = TaskProcess->find(t_taskProcess.TaskID); if(it != TaskProcess->end()) { it->second.push_back(t_taskProcess); } else { vector<STR_TaskProcess> vec_process; vec_process.push_back(t_taskProcess); (*TaskProcess)[t_taskProcess.TaskID] = vec_process; } } return t_row; } } //查询角色信息 hf_int32 DiskDBManager::GetRoleInfo(STR_RoleInfo* roleinfo, const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); if(t_row == 1) { roleinfo->MaxHP = atoi(PQgetvalue(t_PGresult, 0, 1)); roleinfo->HP = atoi(PQgetvalue(t_PGresult, 0, 2)); roleinfo->MaxMagic = atoi(PQgetvalue(t_PGresult, 0, 3)); roleinfo->Magic = atoi(PQgetvalue(t_PGresult, 0, 4)); roleinfo->PhysicalDefense = atoi(PQgetvalue(t_PGresult, 0, 5)); roleinfo->MagicDefense = atoi(PQgetvalue(t_PGresult, 0, 6)); roleinfo->PhysicalAttack = atoi(PQgetvalue(t_PGresult, 0, 7)); roleinfo->MagicAttack = atoi(PQgetvalue(t_PGresult, 0, 8)); roleinfo->Crit_Rate = atof(PQgetvalue(t_PGresult, 0, 9)); roleinfo->Dodge_Rate = atof(PQgetvalue(t_PGresult, 0, 10)); roleinfo->Hit_Rate = atof(PQgetvalue(t_PGresult, 0, 11)); roleinfo->Resist_Rate = atof(PQgetvalue(t_PGresult, 0, 12)); roleinfo->Caster_Speed = atoi(PQgetvalue(t_PGresult, 0, 13)); roleinfo->Move_Speed = atoi(PQgetvalue(t_PGresult, 0, 14)); roleinfo->Hurt_Speed = atoi(PQgetvalue(t_PGresult, 0, 15)); roleinfo->Small_Universe = atoi(PQgetvalue(t_PGresult, 0, 16)); roleinfo->maxSmall_Universe = atoi(PQgetvalue(t_PGresult, 0, 17)); roleinfo->RecoveryLife_Percentage = atof(PQgetvalue(t_PGresult, 0, 18)); roleinfo->RecoveryLife_value = atoi(PQgetvalue(t_PGresult, 0, 19)); roleinfo->RecoveryMagic_Percentage = atof(PQgetvalue(t_PGresult, 0, 20)); roleinfo->RecoveryMagic_value = atoi(PQgetvalue(t_PGresult, 0, 21)); roleinfo->MagicHurt_Reduction = atof(PQgetvalue(t_PGresult, 0, 22)); roleinfo->PhysicalHurt_Reduction = atof(PQgetvalue(t_PGresult, 0, 23)); roleinfo->CritHurt = atof(PQgetvalue(t_PGresult, 0, 24)); roleinfo->CritHurt_Reduction = atof(PQgetvalue(t_PGresult, 0, 25)); roleinfo->Magic_Pass = atof(PQgetvalue(t_PGresult, 0, 26)); roleinfo->Physical_Pass = atof(PQgetvalue(t_PGresult, 0, 27)); roleinfo->Rigorous = atoi(PQgetvalue(t_PGresult, 0, 28)); roleinfo->Will = atoi(PQgetvalue(t_PGresult, 0, 29)); roleinfo->Wise = atoi(PQgetvalue(t_PGresult, 0, 30)); roleinfo->Mentality = atoi(PQgetvalue(t_PGresult, 0, 21)); roleinfo->Physical_fitness = atoi(PQgetvalue(t_PGresult, 0, 32)); } return t_row; } } //查询玩家经验 hf_int32 DiskDBManager::GetRoleExperience(STR_PackRoleExperience* RoleExp, const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); if(t_row == 1) { RoleExp->Level = atoi(PQgetvalue(t_PGresult, 0, 0)); RoleExp->CurrentExp = atoi(PQgetvalue(t_PGresult, 0, 1)); RoleExp->UpgradeExp = GetUpgradeExprience(RoleExp->Level); } return t_row; } } //查询好友列表 hf_int32 DiskDBManager::GetFriendList(umap_friendList t_friendList, const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_FriendInfo t_friendInfo; for(hf_int32 i = 0; i < t_row; i++) { memset(&t_friendInfo, 0, sizeof(STR_FriendInfo)); t_friendInfo.RoleID = atoi(PQgetvalue(t_PGresult, i, 0)); memcpy(t_friendInfo.Nick, PQgetvalue(t_PGresult, i, 1), PQgetlength(t_PGresult, i, 1)); t_friendInfo.Status = 2; //默认不在线 (*t_friendList)[t_friendInfo.RoleID] = t_friendInfo; } return t_row; } } //查询某个昵称的roleid hf_int32 DiskDBManager::GetNickRoleid(hf_uint32* roleid, const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); if(t_row == 1) { *roleid = atoi(PQgetvalue(t_PGresult, 0, 0)); } return t_row; } } //查询添加好友请求 hf_int32 DiskDBManager::GetAskAddFriend(vector<STR_AddFriend>& addFriend, const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_AddFriend t_addFriend; for(hf_int32 i = 0; i < t_row; i++) { memset(&t_addFriend, 0, sizeof(STR_AddFriend)); t_addFriend.RoleID = atoi(PQgetvalue(t_PGresult, i, 0)); memcpy(t_addFriend.Nick,PQgetvalue(t_PGresult, i, 1), PQgetlength(t_PGresult, i, 1)); addFriend.push_back(t_addFriend); } return t_row; } } //查询NPC信息 hf_int32 DiskDBManager::GetNPCInfo(umap_npcInfo* npcInfo) { const hf_char* str = "select * from t_npcinfo;"; m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); NPCInfo t_NPCInfo; for(hf_int32 i = 0; i < t_row; i++) { t_NPCInfo.NpcID = atoi(PQgetvalue(t_PGresult, i, 0)); t_NPCInfo.Mapid = atoi(PQgetvalue(t_PGresult, i, 1)); t_NPCInfo.Pos_x = atof(PQgetvalue(t_PGresult, i, 2)); t_NPCInfo.Pos_y = atof(PQgetvalue(t_PGresult, i, 3)); t_NPCInfo.Pos_z = atof(PQgetvalue(t_PGresult, i, 4)); (*npcInfo)[t_NPCInfo.NpcID] = t_NPCInfo; } return t_row; } } //查询怪物掉落物品 hf_int32 DiskDBManager::GetMonsterLoot(umap_monsterLoot* monsterLoot) { const hf_char* str = "select * from t_monsterloot;"; m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_MonsterLoot t_monsterLoot; vector<STR_MonsterLoot> v_monsterLoot; for(hf_int32 i = 0; i < t_row; i++) { v_monsterLoot.clear(); t_monsterLoot.MonsterTypeID = atoi(PQgetvalue(t_PGresult, i, 0)); t_monsterLoot.PreCondition = atoi(PQgetvalue(t_PGresult, i, 1)); t_monsterLoot.LootGoodsID = atoi(PQgetvalue(t_PGresult, i, 2)); t_monsterLoot.LootProbability = atof(PQgetvalue(t_PGresult, i, 3)); t_monsterLoot.Count = atoi(PQgetvalue(t_PGresult, i, 4)); v_monsterLoot.push_back(t_monsterLoot); umap_monsterLoot::iterator it = monsterLoot->find(t_monsterLoot.MonsterTypeID); if(it != monsterLoot->end()) { it->second.push_back(t_monsterLoot); } else { (*monsterLoot)[t_monsterLoot.MonsterTypeID] = v_monsterLoot; } } return t_row; } } //查询技能信息 hf_int32 DiskDBManager::GetSkillInfo(umap_skillInfo* skillInfo) { const hf_char* str = "select * from t_skillinfo;"; m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_PackSkillInfo t_skill; for(hf_int32 i = 0; i < t_row; i++) { t_skill.SkillID = atoi(PQgetvalue(t_PGresult, i, 0)); t_skill.UseGoodsID = atoi(PQgetvalue(t_PGresult, i, 1)); t_skill.UseMagic = atoi(PQgetvalue(t_PGresult, i, 2)); t_skill.CoolTime = atof(PQgetvalue(t_PGresult, i, 3)); t_skill.LeadTime = atof(PQgetvalue(t_PGresult, i, 4)); t_skill.PhysicalHurt = atoi(PQgetvalue(t_PGresult, i, 5)); t_skill.PhyPlus = atof(PQgetvalue(t_PGresult, i, 6)); t_skill.MagicHurt = atoi(PQgetvalue(t_PGresult, i, 7)); t_skill.MagPlus = atof(PQgetvalue(t_PGresult, i, 8)); t_skill.UseGoodsCount = atoi(PQgetvalue(t_PGresult, i, 9)); t_skill.FarDistance = atoi(PQgetvalue(t_PGresult, i, 10)); t_skill.NearlyDistance = atoi(PQgetvalue(t_PGresult, i, 11)); t_skill.TriggerID = atoi(PQgetvalue(t_PGresult, i, 12)); t_skill.SkillRangeID = atoi(PQgetvalue(t_PGresult, i, 13)); t_skill.UseAnger = atoi(PQgetvalue(t_PGresult, i, 14)); t_skill.CastingTime = atoi(PQgetvalue(t_PGresult, i, 15)); t_skill.CasterNumber = atoi(PQgetvalue(t_PGresult, i, 16)); (*skillInfo)[t_skill.SkillID] = t_skill; } return t_row; } } //查询玩家金币 hf_int32 DiskDBManager::GetPlayerMoney(umap_roleMoney playerMoney, const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_PlayerMoney t_money; for(hf_int32 i = 0; i < t_row; i++) { t_money.Count = atoi(PQgetvalue(t_PGresult, i, 0)); t_money.TypeID = atoi(PQgetvalue(t_PGresult, i, 1)); (*playerMoney)[t_money.TypeID] = t_money; } return t_row; } } //查询玩家物品 hf_int32 DiskDBManager::GetPlayerGoods(umap_roleGoods playerGoods, umap_roleEqu playerEqu, const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_Goods t_goods; STR_PlayerEqu t_equ; t_goods.Source = Source_Bag; vector<STR_Goods> t_vec; for(hf_int32 i = 0; i < t_row; i++) { t_goods.GoodsID = atoi(PQgetvalue(t_PGresult, i, 0)); t_goods.TypeID = atoi(PQgetvalue(t_PGresult, i, 1)); t_goods.Count = atoi(PQgetvalue(t_PGresult, i, 2)); t_goods.Position = atoi(PQgetvalue(t_PGresult, i, 3)); if(EquTypeMinValue <= t_goods.TypeID && t_goods.TypeID <= EquTypeMaxValue) //装备 { memcpy(&t_equ.goods, &t_goods, sizeof(STR_Goods)); (*playerEqu)[t_goods.GoodsID] = t_equ; continue; } _umap_roleGoods::iterator it = playerGoods->find(t_goods.GoodsID); if(it != playerGoods->end()) { it->second.push_back(t_goods); } else { t_vec.clear(); t_vec.push_back(t_goods); (*playerGoods)[t_goods.GoodsID] = t_vec; } } return t_row; } } //查询玩家装备属性 hf_int32 DiskDBManager::GetPlayerEqu(umap_roleEqu playerEqu, const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_EquipmentAttr t_equAttr; for(hf_int32 i = 0; i < t_row; i++) { t_equAttr.EquID = atoi(PQgetvalue(t_PGresult, i, 1)); t_equAttr.TypeID = atoi(PQgetvalue(t_PGresult, i, 2)); t_equAttr.Crit_Rate = atof(PQgetvalue(t_PGresult, i, 3)); t_equAttr.Dodge_Rate = atof(PQgetvalue(t_PGresult, i, 4)); t_equAttr.Hit_Rate = atof(PQgetvalue(t_PGresult, i, 5)); t_equAttr.Resist_Rate = atof(PQgetvalue(t_PGresult, i, 6)); t_equAttr.Caster_Speed = atof(PQgetvalue(t_PGresult, i, 7)); t_equAttr.Move_Speed = atof(PQgetvalue(t_PGresult, i, 8)); t_equAttr.Hurt_Speed = atof(PQgetvalue(t_PGresult, i, 9)); t_equAttr.RecoveryLife_Percentage = atof(PQgetvalue(t_PGresult, i, 10)); t_equAttr.RecoveryLife_value = atoi(PQgetvalue(t_PGresult, i, 11)); t_equAttr.RecoveryMagic_Percentage = atof(PQgetvalue(t_PGresult, i, 12)); t_equAttr.RecoveryMagic_value = atoi(PQgetvalue(t_PGresult, i, 13)); t_equAttr.MagicHurt_Reduction = atof(PQgetvalue(t_PGresult, i, 14)); t_equAttr.PhysicalHurt_Reduction = atof(PQgetvalue(t_PGresult, i, 15)); t_equAttr.CritHurt = atof(PQgetvalue(t_PGresult, i, 16)); t_equAttr.CritHurt_Reduction = atof(PQgetvalue(t_PGresult, i, 17)); t_equAttr.Magic_Pass = atof(PQgetvalue(t_PGresult, i, 18)); t_equAttr.Physical_Pass = atof(PQgetvalue(t_PGresult, i, 19)); t_equAttr.SuitSkillID = atoi(PQgetvalue(t_PGresult, i, 20)); t_equAttr.HP = atoi(PQgetvalue(t_PGresult, i, 21)); t_equAttr.Magic = atoi(PQgetvalue(t_PGresult, i, 22)); t_equAttr.PhysicalDefense = atoi(PQgetvalue(t_PGresult, i, 23)); t_equAttr.MagicDefense = atoi(PQgetvalue(t_PGresult, i, 24)); t_equAttr.PhysicalAttack = atoi(PQgetvalue(t_PGresult, i, 25)); t_equAttr.MagicAttack = atoi(PQgetvalue(t_PGresult, i, 26)); t_equAttr.Rigorous = atoi(PQgetvalue(t_PGresult, i, 27)); t_equAttr.Will = atoi(PQgetvalue(t_PGresult, i, 28)); t_equAttr.Wise = atoi(PQgetvalue(t_PGresult, i, 29)); t_equAttr.Mentality = atoi(PQgetvalue(t_PGresult, i, 30)); t_equAttr.Physical_fitness = atoi(PQgetvalue(t_PGresult, i, 31)); t_equAttr.JobID = atoi(PQgetvalue(t_PGresult, i, 32)); t_equAttr.BodyPos = atoi(PQgetvalue(t_PGresult, i, 33)); t_equAttr.Grade = atoi(PQgetvalue(t_PGresult, i, 34)); t_equAttr.Level = atoi(PQgetvalue(t_PGresult, i, 35)); t_equAttr.StrengthenLevel = atoi(PQgetvalue(t_PGresult, i, 36)); t_equAttr.MaxDurability = atoi(PQgetvalue(t_PGresult, i, 37)); t_equAttr.Durability = atoi(PQgetvalue(t_PGresult, i, 38)); memcpy(&((*playerEqu)[t_equAttr.EquID].equAttr), &t_equAttr, sizeof(STR_EquipmentAttr)); } return t_row; } } //查询玩家未捡取的物品位置 hf_int32 DiskDBManager::GetNotPickGoodsPosition(umap_lootPosition lootPosition, const hf_char* str) { time_t timep; time(&timep); m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); LootPositionTime t_loot; for(hf_int32 i = 0; i < t_row; i++) { t_loot.timep = (hf_uint32)timep; t_loot.continueTime = atoi(PQgetvalue(t_PGresult, i, 0)); t_loot.goodsPos.GoodsFlag = atoi(PQgetvalue(t_PGresult, i, 1)); t_loot.goodsPos.Pos_x = atoi(PQgetvalue(t_PGresult, i, 2)); t_loot.goodsPos.Pos_y = atoi(PQgetvalue(t_PGresult, i, 3)); t_loot.goodsPos.Pos_z = atoi(PQgetvalue(t_PGresult, i, 4)); t_loot.goodsPos.MapID = atoi(PQgetvalue(t_PGresult, i, 5)); (*lootPosition)[t_loot.goodsPos.GoodsFlag] = t_loot; } return t_row; } } //查询玩家未捡取的物品 hf_int32 DiskDBManager::GetNotPickGoods(umap_lootGoods lootGoods, const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_LootGoods t_goods; vector<STR_LootGoods> vec; for(hf_int32 i = 0; i < t_row; i++) { hf_uint32 lootID = atoi(PQgetvalue(t_PGresult, i, 0)); t_goods.LootGoodsID = atoi(PQgetvalue(t_PGresult, i, 1)); t_goods.Count = atoi(PQgetvalue(t_PGresult, i, 2)); _umap_lootGoods::iterator it = lootGoods->find(lootID); if(it != lootGoods->end()) { it->second.push_back(t_goods); } else { vec.clear(); vec.push_back(t_goods); (*lootGoods)[lootID] = vec; } } return t_row; } } //查询物品价格 hf_int32 DiskDBManager::GetGoodsPrice(umap_goodsPrice* goodsPrice, const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_GoodsPrice t_goodsPrice; for(hf_int32 i = 0; i < t_row; i++) { t_goodsPrice.GoodsID = atoi(PQgetvalue(t_PGresult, i, 0)); t_goodsPrice.BuyPrice = atoi(PQgetvalue(t_PGresult, i, 1)); t_goodsPrice.SellPrice = atoi(PQgetvalue(t_PGresult, i, 2)); (*goodsPrice)[t_goodsPrice.GoodsID] = t_goodsPrice; } return t_row; } } //查询消耗品价格 hf_int32 DiskDBManager::GetConsumableAttr(umap_consumable* consumable, const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_Consumable t_consumable; for(hf_int32 i = 0; i < t_row; i++) { t_consumable.GoodsID = atoi(PQgetvalue(t_PGresult, i, 0)); t_consumable.HP = atoi(PQgetvalue(t_PGresult, i, 1)); t_consumable.Magic = atoi(PQgetvalue(t_PGresult, i, 2)); t_consumable.ColdTime = atoi(PQgetvalue(t_PGresult, i, 3)); t_consumable.StackNumber = atoi(PQgetvalue(t_PGresult, i, 4)); t_consumable.PersecondHP = atoi(PQgetvalue(t_PGresult, i, 5)); t_consumable.PersecondMagic = atoi(PQgetvalue(t_PGresult, i, 6)); t_consumable.UserLevel = atoi(PQgetvalue(t_PGresult, i, 7)); t_consumable.ContinueTime = atoi(PQgetvalue(t_PGresult, i, 8)); t_consumable.Type = atoi(PQgetvalue(t_PGresult, i, 9)); (*consumable)[t_consumable.GoodsID] = t_consumable; } return t_row; } } //查询装备属性 hf_int32 DiskDBManager::GetEquAttr(umap_equAttr* equAttr, const hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); STR_EquipmentAttr t_equAttr; for(hf_int32 i = 0; i < t_row; i++) { t_equAttr.TypeID = atoi(PQgetvalue(t_PGresult, i, 0)); t_equAttr.Crit_Rate = atof(PQgetvalue(t_PGresult, i, 2)); t_equAttr.Dodge_Rate = atof(PQgetvalue(t_PGresult, i, 3)); t_equAttr.Hit_Rate = atof(PQgetvalue(t_PGresult, i, 4)); t_equAttr.Resist_Rate = atof(PQgetvalue(t_PGresult, i, 5)); t_equAttr.Caster_Speed = atof(PQgetvalue(t_PGresult, i, 6)); t_equAttr.Move_Speed = atof(PQgetvalue(t_PGresult, i, 7)); t_equAttr.Hurt_Speed = atof(PQgetvalue(t_PGresult, i, 8)); t_equAttr.RecoveryLife_Percentage = atof(PQgetvalue(t_PGresult, i, 9)); t_equAttr.RecoveryLife_value = atoi(PQgetvalue(t_PGresult, i, 10)); t_equAttr.RecoveryMagic_Percentage = atof(PQgetvalue(t_PGresult, i, 11)); t_equAttr.RecoveryMagic_value = atoi(PQgetvalue(t_PGresult, i, 12)); t_equAttr.MagicHurt_Reduction = atof(PQgetvalue(t_PGresult, i, 13)); t_equAttr.PhysicalHurt_Reduction = atof(PQgetvalue(t_PGresult, i, 14)); t_equAttr.CritHurt = atof(PQgetvalue(t_PGresult, i, 15)); t_equAttr.CritHurt_Reduction = atof(PQgetvalue(t_PGresult, i, 16)); t_equAttr.Magic_Pass = atof(PQgetvalue(t_PGresult,i, 17)); t_equAttr.Physical_Pass = atof(PQgetvalue(t_PGresult,i, 18)); t_equAttr.SuitSkillID = atoi(PQgetvalue(t_PGresult,i, 19)); t_equAttr.HP = atoi(PQgetvalue(t_PGresult, i, 20)); t_equAttr.Magic = atoi(PQgetvalue(t_PGresult, i, 21)); t_equAttr.PhysicalDefense = atoi(PQgetvalue(t_PGresult, i, 22)); t_equAttr.MagicDefense = atoi(PQgetvalue(t_PGresult, i, 23)); t_equAttr.PhysicalAttack = atoi(PQgetvalue(t_PGresult, i, 24)); t_equAttr.MagicAttack = atoi(PQgetvalue(t_PGresult, i, 25)); t_equAttr.Rigorous = atoi(PQgetvalue(t_PGresult, i, 26)); t_equAttr.Will = atoi(PQgetvalue(t_PGresult, i, 27)); t_equAttr.Wise = atoi(PQgetvalue(t_PGresult, i, 28)); t_equAttr.Mentality = atoi(PQgetvalue(t_PGresult, i, 29)); t_equAttr.Physical_fitness = atoi(PQgetvalue(t_PGresult, i, 30)); t_equAttr.JobID = atoi(PQgetvalue(t_PGresult, i ,31)); t_equAttr.BodyPos = atoi(PQgetvalue(t_PGresult, i, 32)); t_equAttr.Grade = atoi(PQgetvalue(t_PGresult, i, 33)); t_equAttr.Level = atoi(PQgetvalue(t_PGresult, i, 34)); t_equAttr.StrengthenLevel = atoi(PQgetvalue(t_PGresult, i, 35)); t_equAttr.MaxDurability = atoi(PQgetvalue(t_PGresult, i, 36)); t_equAttr.Durability = t_equAttr.MaxDurability; (*equAttr)[t_equAttr.TypeID] = t_equAttr; } return t_row; } } //查询数据库中装备现在的最大值 hf_int32 DiskDBManager::GetEquIDMaxValue() { const hf_char* str = "select max(equid) from t_playerequattr;"; Logger::GetLogger()->Debug(str); m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } hf_int32 t_row = PQntuples(t_PGresult); if(t_row == 0) { return EquipMentID; } else { hf_uint32 equid = atoi(PQgetvalue(t_PGresult, 0, 0)); if(equid < EquipMentID) { return EquipMentID; } else { return equid; } } } //查询用户身上穿戴的装备 hf_int32 DiskDBManager::GetUserBodyEqu(hf_char* buff, hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { STR_BodyEquipment bodyEqu; hf_int32 t_row = PQntuples(t_PGresult); for(hf_int32 i = 0; i < t_row; i++) { bodyEqu.roleid = atoi(PQgetvalue(t_PGresult, 0, 0)); bodyEqu.Head = atoi(PQgetvalue(t_PGresult, 0, 1)); bodyEqu.HeadType = atoi(PQgetvalue(t_PGresult, 0, 2)); bodyEqu.UpperBody = atoi(PQgetvalue(t_PGresult, 0, 3)); bodyEqu.UpperBodyType = atoi(PQgetvalue(t_PGresult, 0, 4)); bodyEqu.Pants = atoi(PQgetvalue(t_PGresult, 0, 5)); bodyEqu.PantsType = atoi(PQgetvalue(t_PGresult, 0, 6)); bodyEqu.Shoes = atoi(PQgetvalue(t_PGresult, 0, 7)); bodyEqu.ShoesType = atoi(PQgetvalue(t_PGresult, 0, 8)); bodyEqu.Belt = atoi(PQgetvalue(t_PGresult, 0, 9)); bodyEqu.BeltType = atoi(PQgetvalue(t_PGresult, 0, 10)); bodyEqu.Neaklace = atoi(PQgetvalue(t_PGresult, 0, 11)); bodyEqu.NeaklaceType = atoi(PQgetvalue(t_PGresult, 0, 12)); bodyEqu.Bracelet = atoi(PQgetvalue(t_PGresult, 0, 13)); bodyEqu.BraceletType = atoi(PQgetvalue(t_PGresult, 0, 14)); bodyEqu.LeftRing = atoi(PQgetvalue(t_PGresult, 0, 15)); bodyEqu.LeftRingType = atoi(PQgetvalue(t_PGresult, 0, 16)); bodyEqu.RightRing = atoi(PQgetvalue(t_PGresult, 0, 17)); bodyEqu.RightRingType = atoi(PQgetvalue(t_PGresult, 0, 18)); bodyEqu.Phone = atoi(PQgetvalue(t_PGresult, 0, 19)); bodyEqu.PhoneType = atoi(PQgetvalue(t_PGresult, 0, 20)); bodyEqu.Weapon = atoi(PQgetvalue(t_PGresult, 0, 21)); bodyEqu.WeaponType = atoi(PQgetvalue(t_PGresult, 0, 22)); memcpy(buff + sizeof(STR_PackHead) + i*sizeof(STR_BodyEquipment), &bodyEqu, sizeof(STR_BodyEquipment)); } return t_row; } } //查询玩家身上穿戴的装备 hf_int32 DiskDBManager::GetRoleBodyEqu(STR_BodyEquipment* bodyEqu, hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); if(t_row == 1) { bodyEqu->roleid = atoi(PQgetvalue(t_PGresult, 0, 0)); bodyEqu->Head = atoi(PQgetvalue(t_PGresult, 0, 1)); bodyEqu->HeadType = atoi(PQgetvalue(t_PGresult, 0, 2)); bodyEqu->UpperBody = atoi(PQgetvalue(t_PGresult, 0, 3)); bodyEqu->UpperBodyType = atoi(PQgetvalue(t_PGresult, 0, 4)); bodyEqu->Pants = atoi(PQgetvalue(t_PGresult, 0, 5)); bodyEqu->PantsType = atoi(PQgetvalue(t_PGresult, 0, 6)); bodyEqu->Shoes = atoi(PQgetvalue(t_PGresult, 0, 7)); bodyEqu->ShoesType = atoi(PQgetvalue(t_PGresult, 0, 8)); bodyEqu->Belt = atoi(PQgetvalue(t_PGresult, 0, 9)); bodyEqu->BeltType = atoi(PQgetvalue(t_PGresult, 0, 10)); bodyEqu->Neaklace = atoi(PQgetvalue(t_PGresult, 0, 11)); bodyEqu->NeaklaceType = atoi(PQgetvalue(t_PGresult, 0, 12)); bodyEqu->Bracelet = atoi(PQgetvalue(t_PGresult, 0, 13)); bodyEqu->BraceletType = atoi(PQgetvalue(t_PGresult, 0, 14)); bodyEqu->LeftRing = atoi(PQgetvalue(t_PGresult, 0, 15)); bodyEqu->LeftRingType = atoi(PQgetvalue(t_PGresult, 0, 16)); bodyEqu->RightRing = atoi(PQgetvalue(t_PGresult, 0, 17)); bodyEqu->RightRingType = atoi(PQgetvalue(t_PGresult, 0, 18)); bodyEqu->Phone = atoi(PQgetvalue(t_PGresult, 0, 19)); bodyEqu->PhoneType = atoi(PQgetvalue(t_PGresult, 0, 20)); bodyEqu->Weapon = atoi(PQgetvalue(t_PGresult, 0, 21)); bodyEqu->WeaponType = atoi(PQgetvalue(t_PGresult, 0, 22)); } return t_row; } } //查询职业属性 hf_int32 DiskDBManager::GetJobAttribute(STR_RoleJobAttribute* jobAttr, hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_status = PQresultStatus(t_PGresult); if(t_status != PGRES_TUPLES_OK) { return -1; } else { jobAttr++; hf_int32 t_row = PQntuples(t_PGresult); for(hf_int32 i = 0; i < t_row; i++) { jobAttr->MaxHP = atoi(PQgetvalue(t_PGresult, i, 0));; jobAttr->MaxMagic = atoi(PQgetvalue(t_PGresult, i, 1));; jobAttr->PhysicalDefense = atoi(PQgetvalue(t_PGresult, i, 2));; jobAttr->MagicDefense = atoi(PQgetvalue(t_PGresult, i, 3));; jobAttr->PhysicalAttack = atoi(PQgetvalue(t_PGresult, i, 4)); jobAttr->PhysicalDefense = atoi(PQgetvalue(t_PGresult, i, 5)); jobAttr->Rigorous = atoi(PQgetvalue(t_PGresult, i, 6)); jobAttr->Will = atoi(PQgetvalue(t_PGresult, i, 7)); jobAttr->Wise = atoi(PQgetvalue(t_PGresult, i, 8)); jobAttr->Mentality = atoi(PQgetvalue(t_PGresult, i, 9)); jobAttr->Physical_fitness = atoi(PQgetvalue(t_PGresult, i, 10)); jobAttr++; } return t_row; } } //查询玩家基本信息 hf_int32 DiskDBManager::GetRoleBasicInfo(STR_RoleBasicInfo* roleInfo, hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_ExecStatusType = PQresultStatus((t_PGresult)); if(t_ExecStatusType != PGRES_TUPLES_OK) { printf("PQexec error\n"); return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); //行数 if(t_row == 1) { memcpy(roleInfo->Nick, PQgetvalue(t_PGresult, 0, 1), PQgetlength(t_PGresult, 0, 1)); roleInfo->RoleID = atoi(PQgetvalue(t_PGresult, 0, 2)); roleInfo->Profession = atoi(PQgetvalue(t_PGresult, 0, 3)); roleInfo->Level = atoi(PQgetvalue(t_PGresult, 0, 4)); roleInfo->Sex = atoi(PQgetvalue(t_PGresult, 0, 5)); roleInfo->Figure = atoi(PQgetvalue(t_PGresult, 0, 6)); roleInfo->FigureColor = atoi(PQgetvalue(t_PGresult, 0, 7)); roleInfo->Face = atoi(PQgetvalue(t_PGresult, 0, 8)); roleInfo->Eye = atoi(PQgetvalue(t_PGresult, 0, 9)); roleInfo->Hair = atoi(PQgetvalue(t_PGresult, 0, 10)); roleInfo->HairColor = atoi(PQgetvalue(t_PGresult, 0, 11)); roleInfo->ModeID = atoi(PQgetvalue(t_PGresult, 0, 13)); roleInfo->SkirtID = atoi(PQgetvalue(t_PGresult, 0, 14)); } return t_row; } } //查询玩家已经完成的任务 hf_int32 DiskDBManager::GetPlayerCompleteTask(umap_completeTask completeTask, hf_char* str) { m_mtx.lock(); PGresult* t_PGresult = PQexec(m_PGconn, str); m_mtx.unlock(); ExecStatusType t_ExecStatusType = PQresultStatus((t_PGresult)); if(t_ExecStatusType != PGRES_TUPLES_OK) { printf("PQexec error\n"); return -1; } else { hf_int32 t_row = PQntuples(t_PGresult); //行数 hf_uint32 taskid = 0; for(hf_int32 i = 0; i < t_row; i++) { taskid = atoi(PQgetvalue(t_PGresult, i, 0)); (*completeTask)[taskid] = taskid; } return t_row; } }
/* -*- c++ -*- */ /* * Copyright 2015 Free Software Foundation, Inc. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3, or (at your * option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_fec_mtrx_impl_H #define INCLUDED_fec_mtrx_impl_H #include <string> #include <gsl/gsl_matrix.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <gnuradio/fec/fec_mtrx.h> namespace gr { namespace fec { namespace code { class fec_mtrx_impl : public fec_mtrx { protected: //! Constructor fec_mtrx_impl(); //! Codeword length n unsigned int d_n; //! Information word length k unsigned int d_k; //! Number of rows in the matrix read in from alist file unsigned int d_num_rows; //! Number of columns in the matrix read in from alist file unsigned int d_num_cols; //! GSL matrix structure for the parity check matrix matrix_sptr d_H_sptr; //! Flag for whether or not the parity bits come first or last bool d_par_bits_last; public: //! Returns the parity check matrix H (needed by decoder) const gsl_matrix *H() const; //!Get the codeword length n unsigned int n() const; //! Get the information word length k unsigned int k() const; //! Subtract matrices using mod2 operations void add_matrices_mod2(gsl_matrix *result, const gsl_matrix *, const gsl_matrix *) const; //! Multiply matrices using mod2 operations void mult_matrices_mod2(gsl_matrix *result, const gsl_matrix *, const gsl_matrix *) const; //! Invert a square matrix using mod2 operations gsl_matrix *calc_inverse_mod2(const gsl_matrix *) const; /*! * \brief Get Boolean for whether or not parity bits come first or last * \details * The decoder will need to know if the parity bits are * coming first or last */ bool parity_bits_come_last() const; virtual ~fec_mtrx_impl(); }; } } } #endif /* INCLUDED_fec_mtrx_impl_H */
[STATEMENT] lemma yun_factorization_induct: assumes base: "\<And> bn cn. bn = 1 \<Longrightarrow> P bn cn" and step: "\<And> bn cn. bn \<noteq> 1 \<Longrightarrow> P (bn div (gcd bn (cn - pderiv bn))) ((cn - pderiv bn) div (gcd bn (cn - pderiv bn))) \<Longrightarrow> P bn cn" and id: "bn = p div gcd p (pderiv p)" "cn = pderiv p div gcd p (pderiv p)" shows "P bn cn" [PROOF STATE] proof (prove) goal (1 subgoal): 1. P bn cn [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. P bn cn [PROOF STEP] define n where "n = (0 :: nat)" [PROOF STATE] proof (state) this: n = 0 goal (1 subgoal): 1. P bn cn [PROOF STEP] let ?m = "\<lambda> n. bound - n" [PROOF STATE] proof (state) goal (1 subgoal): 1. P bn cn [PROOF STEP] have "P (B n) (C n)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. P (B n) (C n) [PROOF STEP] proof (induct n rule: wf_induct[OF wf_measure[of ?m]]) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x. \<forall>y. (y, x) \<in> measure ((-) bound) \<longrightarrow> P (B y) (C y) \<Longrightarrow> P (B x) (C x) [PROOF STEP] case (1 n) [PROOF STATE] proof (state) this: \<forall>y. (y, n) \<in> measure ((-) bound) \<longrightarrow> P (B y) (C y) goal (1 subgoal): 1. \<And>x. \<forall>y. (y, x) \<in> measure ((-) bound) \<longrightarrow> P (B y) (C y) \<Longrightarrow> P (B x) (C x) [PROOF STEP] note IH = 1(1)[rule_format] [PROOF STATE] proof (state) this: (?y, n) \<in> measure ((-) bound) \<Longrightarrow> P (B ?y) (C ?y) goal (1 subgoal): 1. \<And>x. \<forall>y. (y, x) \<in> measure ((-) bound) \<longrightarrow> P (B y) (C y) \<Longrightarrow> P (B x) (C x) [PROOF STEP] show ?case [PROOF STATE] proof (prove) goal (1 subgoal): 1. P (B n) (C n) [PROOF STEP] proof (cases "B n = 1") [PROOF STATE] proof (state) goal (2 subgoals): 1. B n = 1 \<Longrightarrow> P (B n) (C n) 2. B n \<noteq> 1 \<Longrightarrow> P (B n) (C n) [PROOF STEP] case True [PROOF STATE] proof (state) this: B n = 1 goal (2 subgoals): 1. B n = 1 \<Longrightarrow> P (B n) (C n) 2. B n \<noteq> 1 \<Longrightarrow> P (B n) (C n) [PROOF STEP] with base [PROOF STATE] proof (chain) picking this: ?bn1 = 1 \<Longrightarrow> P ?bn1 ?cn1 B n = 1 [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: ?bn1 = 1 \<Longrightarrow> P ?bn1 ?cn1 B n = 1 goal (1 subgoal): 1. P (B n) (C n) [PROOF STEP] by auto [PROOF STATE] proof (state) this: P (B n) (C n) goal (1 subgoal): 1. B n \<noteq> 1 \<Longrightarrow> P (B n) (C n) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. B n \<noteq> 1 \<Longrightarrow> P (B n) (C n) [PROOF STEP] case False [PROOF STATE] proof (state) this: B n \<noteq> 1 goal (1 subgoal): 1. B n \<noteq> 1 \<Longrightarrow> P (B n) (C n) [PROOF STEP] note Bn = this [PROOF STATE] proof (state) this: B n \<noteq> 1 goal (1 subgoal): 1. B n \<noteq> 1 \<Longrightarrow> P (B n) (C n) [PROOF STEP] with bound[of n] [PROOF STATE] proof (chain) picking this: bound \<le> n \<Longrightarrow> B n = 1 B n \<noteq> 1 [PROOF STEP] have "\<not> bound \<le> n" [PROOF STATE] proof (prove) using this: bound \<le> n \<Longrightarrow> B n = 1 B n \<noteq> 1 goal (1 subgoal): 1. \<not> bound \<le> n [PROOF STEP] by auto [PROOF STATE] proof (state) this: \<not> bound \<le> n goal (1 subgoal): 1. B n \<noteq> 1 \<Longrightarrow> P (B n) (C n) [PROOF STEP] hence "(Suc n, n) \<in> measure ?m" [PROOF STATE] proof (prove) using this: \<not> bound \<le> n goal (1 subgoal): 1. (Suc n, n) \<in> measure ((-) bound) [PROOF STEP] by auto [PROOF STATE] proof (state) this: (Suc n, n) \<in> measure ((-) bound) goal (1 subgoal): 1. B n \<noteq> 1 \<Longrightarrow> P (B n) (C n) [PROOF STEP] note IH = IH[OF this] [PROOF STATE] proof (state) this: P (B (Suc n)) (C (Suc n)) goal (1 subgoal): 1. B n \<noteq> 1 \<Longrightarrow> P (B n) (C n) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. P (B n) (C n) [PROOF STEP] by (rule step[OF Bn], insert IH, simp add: D.simps C.simps B.simps A.simps) [PROOF STATE] proof (state) this: P (B n) (C n) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: P (B n) (C n) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: P (B n) (C n) goal (1 subgoal): 1. P bn cn [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: P (B n) (C n) goal (1 subgoal): 1. P bn cn [PROOF STEP] unfolding id n_def B.simps C.simps [PROOF STATE] proof (prove) using this: P (p div gcd p (pderiv p)) (pderiv p div gcd p (pderiv p)) goal (1 subgoal): 1. P (p div gcd p (pderiv p)) (pderiv p div gcd p (pderiv p)) [PROOF STEP] . [PROOF STATE] proof (state) this: P bn cn goal: No subgoals! [PROOF STEP] qed
function [X,data] = kamada_kawai_spring_layout(A,varargin) % KAMADA_KAWAI_SPRING_LAYOUT Use springs to compute a graph layout % % X = kamada_kawai_spring_layout(A) computes a layout for an undirected % graph, connected graph by simulating a system of springs. % [X,data] = kamada_kawai_spring_layout(A) returns extra data, such as the % spring matrix and matrix of distances between vertices, i.e. % data.spring_strength % returns the spring stremgth % data.distances % returns the distance between all points % % See % http://www.boost.org/doc/libs/1_36_0/libs/graph/doc/kamada_kawai_spring_layout.html % for information about the layout function and the parameters % % ... = kamada_kawai_spring_layout(A,...) takes a set of % key-value pairs or an options structure. See set_matlab_bgl_options % for the standard options. % options.tol: stopping tolerance of layout change [double | {1e-6}] % options.maxiter: the maximum number of layout iterations [500] % options.spring_constant: energy of the system [double | {1}] % options.progressive: if you want to start from an existing layout, % provide the coordinates of the layout [{0} | position matrix X] % options.edge_length: default length of an edge [double | {1}] % options.edge_weight: a double array over the edges with an edge % weight for each edge, see EDGE_INDEX and EXAMPLES/REWEIGHTED_GRAPHS % for information on how to use this option correctly % [{'matrix'} | 'none' | length(nnz(A)) double vector] % % Example: % G = grid_graph(6,5); % X = kamada_kawai_spring_layout(G); % gplot(G,X); % % See also FRUCHTERMAN_REINGOLD_FORCE_DIRECTED_LAYOUT, GURSOY_ATUN_LAYOUT % David F. Gleich % Copyright, Stanford University, 2008 %% History % 2008-09-25: Initial coding %% [trans check full2sparse] = get_matlab_bgl_options(varargin{:}); if full2sparse && ~issparse(A), A = sparse(A); end n = num_vertices(A); options = struct('tol',1e-6,'maxiter',500,'spring_constant',1,... 'progressive',0,'edge_length',1,'edge_weight','matrix'); options = merge_options(options,varargin{:}); % edge_weights is an indicator that is 1 if we are using edge_weights % passed on the command line or 0 if we are using the matrix, or -1 to use % nothing edge_weights = 0; edge_weight_opt = 'matrix'; if strcmp(options.edge_weight, 'matrix'), % do nothing to use the matrix weights elseif strcmp(options.edge_weight,'none'), edge_weights = -1; % don't use weights else edge_weights = 1; edge_weight_opt = options.edge_weight; end if check % make sure the matrix is symmetric if ~edge_weights==1 check_matlab_bgl(A,struct('sym',1,'values',edge_weights==0,'noneg',1)); else if nnz(A) ~= length(edge_weight_opt) error('matlab_bgl:invalidParameter', ... 'the vector of edge weights must have length nnz(A)'); end if any(edge_weight_opt)<0, error('matlab_bgl:invalidParameter',... 'the edge_weight array must be non-negative'); end [i j] = find(A); Av = sparse(i,j,edge_weight_opt,size(A,1),size(A,2)); check_matlab_bgl(Av,struct('sym',1,'noneg',1)); end end progressive_opt = []; if ~isscalar(options.progressive), progressive_opt = options.progressive; end [X,spring,distance]=kamada_kawai_spring_layout_mex(... A, options.tol, options.maxiter, options.spring_constant, ... progressive_opt, options.edge_length, edge_weights, edge_weight_opt); if nargout>1, data.spring_strength = spring; data.distances = distance; end
Local Unset Elimination Schemes. Inductive P : Type := a | b. Inductive W : P -> Type :=. Fail Axiom b : W a.
import data.matrix data.rat.basic .misc tactic.fin_cases import .matrix_pequiv open matrix fintype finset function variables {m n : ℕ} local notation `rvec`:2000 n := matrix (fin 1) (fin n) ℚ local notation `cvec`:2000 m := matrix (fin m) (fin 1) ℚ def list.to_matrix (m :ℕ) (n : ℕ) (l : list (list ℚ)) : matrix (fin m) (fin n) ℚ := λ i j, (l.nth_le i sorry).nth_le j sorry local attribute [instance] matrix.ordered_comm_group matrix.decidable_le open pequiv lemma cvec_one_lt_iff {a b : cvec 1} : a < b ↔ a 0 0 < b 0 0 := begin simp only [lt_iff_le_not_le], show (∀ i j, a i j ≤ b i j) ∧ (¬ ∀ i j, b i j ≤ a i j) ↔ _, simp [unique.forall_iff], refl, end instance : discrete_linear_ordered_field (cvec 1) := { mul_nonneg := λ a b ha0 hb0 i j, by simp [matrix.mul]; exact mul_nonneg (ha0 _ _) (hb0 _ _), mul_pos := λ a b ha0 hb0, begin rw [cvec_one_lt_iff] at *, simp [matrix.mul], exact mul_pos ha0 hb0 end, le_total := λ a b, (le_total (a 0 0) (b 0 0)).elim (λ hab, or.inl $ λ i j, by fin_cases i; fin_cases j; exact hab) (λ hba, or.inr $ λ i j, by fin_cases i; fin_cases j; exact hba), zero_lt_one := dec_trivial, decidable_le := matrix.decidable_le, ..matrix.discrete_field, ..matrix.ordered_comm_group } instance : decidable_linear_order (cvec 1) := { ..matrix.discrete_linear_ordered_field } local infix ` ⬝ `:70 := matrix.mul local postfix `ᵀ` : 1500 := transpose lemma cvec_le_iff (a b : cvec n) : a ≤ b ↔ (∀ i : fin n, (single (0 : fin 1) i).to_matrix ⬝ a ≤ (single 0 i).to_matrix ⬝ b) := show (∀ i j, a i j ≤ b i j) ↔ (∀ i j k, ((single (0 : fin 1) i).to_matrix ⬝ a) j k ≤ ((single 0 i).to_matrix ⬝ b) j k), begin simp only [mul_matrix_apply], split, { intros h i j k, fin_cases j, fin_cases k, exact h _ _ }, { intros h i j, fin_cases j, exact h i 0 0 } end lemma rvec_le_iff (a b : rvec n) : a ≤ b ↔ (∀ j : fin n, a ⬝ (single j (0 : fin 1)).to_matrix ≤ b ⬝ (single j 0).to_matrix) := show (∀ i k, a i k ≤ b i k) ↔ (∀ j i k, (a ⬝ (single j (0 : fin 1)).to_matrix) i k ≤ (b ⬝ (single j 0).to_matrix) i k), begin simp only [matrix_mul_apply], split, { intros h i j k, fin_cases j, fin_cases k, exact h _ _ }, { intros h i j, fin_cases i, exact h _ 0 0 } end def rvec.to_list {n : ℕ} (x : rvec n) : list ℚ := (vector.of_fn (x 0)).1 instance has_repr_fin_fun {n : ℕ} {α : Type*} [has_repr α] : has_repr (fin n → α) := ⟨λ f, repr (vector.of_fn f).to_list⟩ instance {m n} : has_repr (matrix (fin m) (fin n) ℚ) := has_repr_fin_fun namespace simplex open list def pequiv_of_vector (v : vector (fin n) m) (hv : v.1.nodup) : fin m ≃. fin n := { to_fun := λ i, some $ v.nth i, inv_fun := λ j, fin.find (λ i, v.nth i = j), inv := λ i j, ⟨λ h, by rw ← fin.find_spec _ h; exact rfl, λ h, fin.mem_find_of_unique (begin rintros ⟨i, him⟩ ⟨j, hjm⟩ h₁ h₂, cases v, refine fin.eq_of_veq (list.nodup_iff_nth_le_inj.1 hv i j _ _ (h₁.trans h₂.symm)); simpa [v.2] end) (option.some_inj.1 h)⟩ } def nonbasis_vector_of_vector (v : vector (fin n) m) (hv : v.to_list.nodup) : {v : vector (fin n) (n - m) // v.to_list.nodup} := ⟨⟨(fin_range n).diff v.to_list, have h : m ≤ n, by rw [← list.length_fin_range n, ← v.2]; exact list.length_le_of_subperm (subperm_of_subset_nodup hv (λ _ _, list.mem_fin_range _)), begin rw [← add_right_inj m, nat.sub_add_cancel h], conv in m { rw [← vector.to_list_length v] }, rw ← length_append, conv_rhs { rw ← length_fin_range n }, exact list.perm_length ((perm_ext (nodup_append.2 ⟨nodup_diff (nodup_fin_range _), hv, by simp [list.disjoint, mem_diff_iff_of_nodup (nodup_fin_range n), imp_false]⟩) (nodup_fin_range _)).2 (by simp only [list.mem_diff_iff_of_nodup (nodup_fin_range n), list.mem_append, mem_fin_range, true_and, iff_true]; exact λ _, or.symm (decidable.em _))), end⟩, nodup_diff (nodup_fin_range _)⟩ def pre_nonbasis_of_vector (v : vector (fin n) m) (hv : v.1.nodup) : fin (n - m) ≃. fin n := pequiv_of_vector (nonbasis_vector_of_vector v hv).1 (nonbasis_vector_of_vector v hv).2 structure prebasis (m n : ℕ) : Type := ( basis : fin m ≃. fin n ) ( nonbasis : fin (n - m) ≃. fin n ) ( basis_trans_basis_symm : basis.trans basis.symm = pequiv.refl (fin m) ) ( nonbasis_trans_nonbasis_symm : nonbasis.trans nonbasis.symm = pequiv.refl (fin (n - m)) ) ( basis_trans_nonbasis_symm : basis.trans nonbasis.symm = ⊥ ) namespace prebasis open pequiv attribute [simp] basis_trans_basis_symm nonbasis_trans_nonbasis_symm basis_trans_nonbasis_symm lemma is_some_basis (B : prebasis m n) : ∀ (i : fin m), (B.basis i).is_some := by rw [← trans_symm_eq_iff_forall_is_some, basis_trans_basis_symm] lemma is_some_nonbasis (B : prebasis m n) : ∀ (k : fin (n - m)), (B.nonbasis k).is_some := by rw [← trans_symm_eq_iff_forall_is_some, nonbasis_trans_nonbasis_symm] lemma injective_basis (B : prebasis m n) : injective B.basis := injective_of_forall_is_some (is_some_basis B) lemma injective_nonbasis (B : prebasis m n) : injective B.nonbasis := injective_of_forall_is_some (is_some_nonbasis B) def basisg (B : prebasis m n) (r : fin m) : fin n := option.get (B.is_some_basis r) def nonbasisg (B : prebasis m n) (s : fin (n - m)) : fin n := option.get (B.is_some_nonbasis s) lemma injective_basisg (B : prebasis m n) : injective B.basisg := λ x y h, by rw [basisg, basisg, ← option.some_inj, option.some_get, option.some_get] at h; exact injective_basis B h lemma injective_nonbasisg (B : prebasis m n) : injective B.nonbasisg := λ x y h, by rw [nonbasisg, nonbasisg, ← option.some_inj, option.some_get, option.some_get] at h; exact injective_nonbasis B h local infix ` ♣ `: 70 := pequiv.trans def swap (B : prebasis m n) (r : fin m) (s : fin (n - m)) : prebasis m n := { basis := B.basis.trans (equiv.swap (B.basisg r) (B.nonbasisg s)).to_pequiv, nonbasis := B.nonbasis.trans (equiv.swap (B.basisg r) (B.nonbasisg s)).to_pequiv, basis_trans_basis_symm := by rw [symm_trans_rev, ← trans_assoc, trans_assoc B.basis, ← equiv.to_pequiv_symm, ← equiv.to_pequiv_trans]; simp, nonbasis_trans_nonbasis_symm := by rw [symm_trans_rev, ← trans_assoc, trans_assoc B.nonbasis, ← equiv.to_pequiv_symm, ← equiv.to_pequiv_trans]; simp, basis_trans_nonbasis_symm := by rw [symm_trans_rev, ← trans_assoc, trans_assoc B.basis, ← equiv.to_pequiv_symm, ← equiv.to_pequiv_trans]; simp } lemma not_is_some_nonbasis_of_is_some_basis (B : prebasis m n) (j : fin n) : (B.basis.symm j).is_some → (B.nonbasis.symm j).is_some → false := begin rw [option.is_some_iff_exists, option.is_some_iff_exists], rintros ⟨i, hi⟩ ⟨k, hk⟩, have : B.basis.trans B.nonbasis.symm i = none, { rw [B.basis_trans_nonbasis_symm, pequiv.bot_apply] }, rw [pequiv.trans_eq_none] at this, rw [pequiv.eq_some_iff] at hi, exact (this j k).resolve_left (not_not.2 hi) hk end lemma nonbasis_ne_none_of_basis_eq_none (B : prebasis m n) (j : fin n) (hb : B.basis.symm j = none) (hnb : B.nonbasis.symm j = none) : false := have hs : card (univ.image B.basis) = m, by rw [card_image_of_injective _ (B.injective_basis), card_univ, card_fin], have ht : card (univ.image B.nonbasis) = (n - m), by rw [card_image_of_injective _ (B.injective_nonbasis), card_univ, card_fin], have hst : disjoint (univ.image B.basis) (univ.image B.nonbasis), from finset.disjoint_left.2 begin simp only [mem_image, exists_imp_distrib, not_exists], assume j i _ hbasis k _ hnonbasis, cases option.is_some_iff_exists.1 (is_some_basis B i) with x hi, cases option.is_some_iff_exists.1 (is_some_nonbasis B k) with y hk, have hxy : x = y, { rw [← option.some_inj, ← hk, ← hi, hbasis, hnonbasis] }, subst hxy, rw [← eq_some_iff] at hi hk, refine not_is_some_nonbasis_of_is_some_basis B x _ _; simp [hi, hk] end, have (univ.image B.basis) ∪ (univ.image B.nonbasis) = univ.image (@some (fin n)), from eq_of_subset_of_card_le begin assume i h, simp only [finset.mem_image, finset.mem_union] at h, rcases h with ⟨j, _, hj⟩ | ⟨k, _, hk⟩, { simpa [hj.symm, option.is_some_iff_exists, eq_comm] using is_some_basis B j }, { simpa [hk.symm, option.is_some_iff_exists, eq_comm] using is_some_nonbasis B k } end (begin rw [card_image_of_injective, card_univ, card_fin, card_disjoint_union hst, hs, ht], { rw add_comm, exact nat.le_sub_add _ _ }, { intros _ _ h, injection h } end), begin simp only [option.eq_none_iff_forall_not_mem, mem_iff_mem B.basis, mem_iff_mem B.nonbasis] at hb hnb, have := (finset.ext.1 this (some j)).2 (mem_image_of_mem _ (mem_univ _)), simp only [hb, hnb, mem_image, finset.mem_union, option.mem_def.symm] at this, tauto end lemma is_some_basis_iff (B : prebasis m n) (j : fin n) : (B.basis.symm j).is_some ↔ ¬(B.nonbasis.symm j).is_some := ⟨not_is_some_nonbasis_of_is_some_basis B j, by erw [option.not_is_some_iff_eq_none, ← option.ne_none_iff_is_some, forall_swap]; exact nonbasis_ne_none_of_basis_eq_none B j⟩ @[simp] lemma nonbasis_basisg_eq_none (B : prebasis m n) (r : fin m) : B.nonbasis.symm (B.basisg r) = none := option.not_is_some_iff_eq_none.1 ((B.is_some_basis_iff _).1 (is_some_symm_get _ _)) @[simp] lemma basis_nonbasisg_eq_none (B : prebasis m n) (s : fin (n - m)) : B.basis.symm (B.nonbasisg s) = none := option.not_is_some_iff_eq_none.1 (mt (B.is_some_basis_iff _).1 $ not_not.2 (is_some_symm_get _ _)) @[simp] lemma basisg_mem (B : prebasis m n) (r : fin m) : (B.basisg r) ∈ B.basis r := option.get_mem _ @[simp] lemma nonbasisg_mem (B : prebasis m n) (s : fin (n - m)) : (B.nonbasisg s) ∈ B.nonbasis s := option.get_mem _ @[simp] lemma basis_basisg (B : prebasis m n) (r : fin m) : B.basis.symm (B.basisg r) = some r:= B.basis.mem_iff_mem.2 (basisg_mem _ _) @[simp] lemma nonbasis_nonbasisg (B : prebasis m n) (s : fin (n - m)) : B.nonbasis.symm (B.nonbasisg s) = some s := B.nonbasis.mem_iff_mem.2 (nonbasisg_mem _ _) lemma eq_basisg_or_nonbasisg (B : prebasis m n) (i : fin n) : (∃ j, i = B.basisg j) ∨ (∃ j, i = B.nonbasisg j) := begin dsimp only [basisg, nonbasisg], by_cases h : ↥(B.basis.symm i).is_some, { cases option.is_some_iff_exists.1 h with j hj, exact or.inl ⟨j, by rw [B.basis.eq_some_iff] at hj; rw [← option.some_inj, ← hj, option.some_get]⟩ }, { rw [(@not_iff_comm _ _ (classical.dec _) (classical.dec _)).1 (B.is_some_basis_iff _).symm] at h, cases option.is_some_iff_exists.1 h with j hj, exact or.inr ⟨j, by rw [B.nonbasis.eq_some_iff] at hj; rw [← option.some_inj, ← hj, option.some_get]⟩ } end lemma basisg_ne_nonbasisg (B : prebasis m n) (i : fin m) (j : fin (n - m)): B.basisg i ≠ B.nonbasisg j := λ h, by simpa using congr_arg B.basis.symm h lemma single_basisg_mul_basis (B : prebasis m n) (i : fin m) : ((single (0 : fin 1) (B.basisg i)).to_matrix : matrix _ _ ℚ) ⬝ B.basis.to_matrixᵀ = (single (0 : fin 1) i).to_matrix := by rw [← to_matrix_symm, ← to_matrix_trans, single_trans_of_mem _ (basis_basisg _ _)] lemma single_basisg_mul_nonbasis (B : prebasis m n) (i : fin m) : ((single (0 : fin 1) (B.basisg i)).to_matrix : matrix _ _ ℚ) ⬝ B.nonbasis.to_matrixᵀ = 0 := by rw [← to_matrix_symm, ← to_matrix_trans, single_trans_of_eq_none _ (nonbasis_basisg_eq_none _ _), to_matrix_bot]; apply_instance lemma single_nonbasisg_mul_nonbasis (B : prebasis m n) (k : fin (n - m)) : ((single (0 : fin 1) (B.nonbasisg k)).to_matrix : matrix _ _ ℚ) ⬝ B.nonbasis.to_matrixᵀ = (single (0 : fin 1) k).to_matrix := by rw [← to_matrix_symm, ← to_matrix_trans, single_trans_of_mem _ (nonbasis_nonbasisg _ _)] lemma single_nonbasisg_mul_basis (B : prebasis m n) (k : fin (n - m)) : ((single (0 : fin 1) (B.nonbasisg k)).to_matrix : matrix _ _ ℚ) ⬝ B.basis.to_matrixᵀ = 0 := by rw [← to_matrix_symm, ← to_matrix_trans, single_trans_of_eq_none _ (basis_nonbasisg_eq_none _ _), to_matrix_bot]; apply_instance lemma nonbasis_trans_basis_symm (B : prebasis m n) : B.nonbasis.trans B.basis.symm = ⊥ := symm_injective $ by rw [symm_trans_rev, symm_symm, basis_trans_nonbasis_symm, symm_bot] @[simp] lemma nonbasis_mul_basis_transpose (B : prebasis m n) : (B.nonbasis.to_matrix : matrix _ _ ℚ) ⬝ B.basis.to_matrixᵀ = 0 := by rw [← to_matrix_bot, ← B.nonbasis_trans_basis_symm, to_matrix_trans, to_matrix_symm] @[simp] lemma basis_mul_nonbasis_transpose (B : prebasis m n) : (B.basis.to_matrix : matrix _ _ ℚ) ⬝ B.nonbasis.to_matrixᵀ = 0 := by rw [← to_matrix_bot, ← B.basis_trans_nonbasis_symm, to_matrix_trans, to_matrix_symm] @[simp] lemma nonbasis_mul_nonbasis_transpose (B : prebasis m n) : (B.nonbasis.to_matrix : matrix _ _ ℚ) ⬝ B.nonbasis.to_matrixᵀ = 1 := by rw [← to_matrix_refl, ← B.nonbasis_trans_nonbasis_symm, to_matrix_trans, to_matrix_symm] @[simp] lemma basis_mul_basis_transpose (B : prebasis m n) : (B.basis.to_matrix : matrix _ _ ℚ) ⬝ B.basis.to_matrixᵀ = 1 := by rw [← to_matrix_refl, ← B.basis_trans_basis_symm, to_matrix_trans, to_matrix_symm] lemma transpose_mul_add_tranpose_mul (B : prebasis m n) : (B.basis.to_matrixᵀ ⬝ B.basis.to_matrix : matrix (fin n) (fin n) ℚ) + B.nonbasis.to_matrixᵀ ⬝ B.nonbasis.to_matrix = 1 := begin ext, repeat {rw [← to_matrix_symm, ← to_matrix_trans] }, simp only [add_val, pequiv.symm_trans, pequiv.to_matrix, one_val, pequiv.mem_of_set_iff, set.mem_set_of_eq], have := is_some_basis_iff B j, split_ifs; tauto end lemma swap_basis_eq (B : prebasis m n) (r : fin m) (s : fin (n - m)) : (B.swap r s).basis.to_matrix = (B.basis.to_matrix : matrix _ _ ℚ) - (single r (B.basisg r)).to_matrix + (single r (B.nonbasisg s)).to_matrix := begin dsimp [swap], rw [to_matrix_trans, to_matrix_swap], simp only [matrix.mul_add, sub_eq_add_neg, matrix.mul_one, matrix.mul_neg, (to_matrix_trans _ _).symm, trans_single_of_mem _ (basisg_mem B r), trans_single_of_eq_none _ (basis_nonbasisg_eq_none B s), to_matrix_bot, neg_zero, add_zero] end lemma nonbasis_trans_swap_basis_symm (B : prebasis m n) (r : fin m) (s : fin (n - m)) : B.nonbasis.trans (B.swap r s).basis.symm = single s r := begin rw [swap, symm_trans_rev, ← equiv.to_pequiv_symm, ← equiv.perm.inv_def, equiv.swap_inv], ext i j, rw [mem_single_iff], dsimp [pequiv.trans, equiv.to_pequiv, equiv.swap_apply_def], simp only [coe, coe_mk_apply, option.mem_def, option.bind_eq_some'], rw [option.mem_def.1 (nonbasisg_mem B i)], simp [B.injective_nonbasisg.eq_iff, (B.basisg_ne_nonbasisg _ _).symm], split_ifs; simp [*, eq_comm] end lemma nonbasis_mul_swap_basis_tranpose (B : prebasis m n) (r : fin m) (s : fin (n - m)) : (B.nonbasis.to_matrix : matrix _ _ ℚ) ⬝ (B.swap r s).basis.to_matrixᵀ = (single s r).to_matrix := by rw [← nonbasis_trans_swap_basis_symm, to_matrix_trans, to_matrix_symm] lemma basis_trans_swap_basis_transpose (B : prebasis m n) (r : fin m) (s : fin (n - m)) : B.basis.trans (B.swap r s).basis.symm = of_set {i | i ≠ r} := begin rw [swap, symm_trans_rev, ← equiv.to_pequiv_symm, ← equiv.perm.inv_def, equiv.swap_inv], ext i j, dsimp [pequiv.trans, equiv.to_pequiv, equiv.swap_apply_def], simp only [coe, coe_mk_apply, option.mem_def, option.bind_eq_some'], rw [option.mem_def.1 (basisg_mem B i)], simp [B.injective_basisg.eq_iff, B.basisg_ne_nonbasisg], split_ifs, { simp * }, { simp *; split; intros; simp * at * } end lemma swap_basis_transpose_apply_single_of_ne (B : prebasis m n) {r : fin m} (s : fin (n - m)) {i : fin m} (hir : i ≠ r) : ((B.swap r s).basis.to_matrixᵀ : matrix (fin n) (fin m) ℚ) ⬝ (single i (0 : fin 1)).to_matrix = B.basis.to_matrixᵀ ⬝ (single i 0).to_matrix := begin simp only [swap_basis_eq, sub_eq_add_neg, matrix.mul_add, matrix.mul_neg, matrix.mul_one, matrix.add_mul, (to_matrix_trans _ _).symm, (to_matrix_symm _).symm, transpose_add, transpose_neg, matrix.neg_mul, symm_trans_rev, trans_assoc], rw [trans_single_of_mem _ (basis_basisg _ _), trans_single_of_eq_none, trans_single_of_eq_none, to_matrix_bot, neg_zero, add_zero, add_zero]; {dsimp [single]; simp [*, B.injective_basisg.eq_iff]} <|> apply_instance end lemma swap_basis_transpose_apply_single (B : prebasis m n) (r : fin m) (s : fin (n - m)) : ((B.swap r s).basis.to_matrixᵀ : matrix (fin n) (fin m) ℚ) ⬝ (single r (0 : fin 1)).to_matrix = B.nonbasis.to_matrixᵀ ⬝ (single s (0 : fin 1)).to_matrix := begin simp only [swap_basis_eq, sub_eq_add_neg, matrix.mul_add, matrix.mul_neg, matrix.mul_one, matrix.add_mul, (to_matrix_trans _ _).symm, (to_matrix_symm _).symm, transpose_add, transpose_neg, matrix.neg_mul, symm_trans_rev, trans_assoc, symm_single], rw [trans_single_of_mem _ (basis_basisg _ _), trans_single_of_mem _ (mem_single _ _), trans_single_of_mem _ (mem_single _ _), trans_single_of_mem _ (nonbasis_nonbasisg _ _)], simp, all_goals {apply_instance} end def equiv_aux : prebasis m n ≃ Σ' (basis : fin m ≃. fin n) (nonbasis : fin (n - m) ≃. fin n) ( basis_trans_basis_symm : basis.trans basis.symm = pequiv.refl (fin m) ) ( nonbasis_trans_nonbasis_symm : nonbasis.trans nonbasis.symm = pequiv.refl (fin (n - m)) ), basis.trans nonbasis.symm = ⊥ := { to_fun := λ ⟨a, b, c, d, e⟩, ⟨a, b, c, d, e⟩, inv_fun := λ ⟨a, b, c, d, e⟩, ⟨a, b, c, d, e⟩, left_inv := λ ⟨_, _, _, _, _⟩, rfl, right_inv := λ ⟨_, _, _, _, _⟩, rfl } --instance : fintype (prebasis m n) := sorry end prebasis open prebasis /- By convention `A_bar` and `b_bar` are in tableau form, so definitions may only be correct assuming `A ⬝ B.basis.to_matrixᵀ = 1` and `b_bar = 0` -/ def pivot_element (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (r : fin m) (s : fin (n - m)) : cvec 1 := (single 0 r).to_matrix ⬝ A_bar ⬝ B.nonbasis.to_matrixᵀ ⬝ (single s 0).to_matrix def swap_inverse (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (r : fin m) (s : fin (n - m)) : matrix (fin m) (fin m) ℚ := (1 + (1 - A_bar ⬝ B.nonbasis.to_matrixᵀ ⬝ (single s (0 : fin 1)).to_matrix ⬝ (single (0 : fin 1) r).to_matrix) ⬝ (single r (0 : fin 1)).to_matrix ⬝ (pivot_element B A_bar r s)⁻¹ ⬝ (single (0 : fin 1) r).to_matrix) def ratio (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (r : fin m) (s : fin (n - m)) : cvec 1 := (pivot_element B A_bar r s)⁻¹ ⬝ ((single 0 r).to_matrix ⬝ b_bar) lemma swap_mul_swap_inverse {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : pivot_element B A_bar r s ≠ 0) : swap_inverse B A_bar r s ⬝ (A_bar ⬝ (B.swap r s).basis.to_matrixᵀ) = 1 := have ((single (0 : fin 1) r).to_matrix ⬝ (single r 0).to_matrix : cvec 1) = 1, by rw [← to_matrix_trans]; simp, begin refine mul_single_ext (λ i, _), simp only [swap_inverse, matrix.mul_add, matrix.add_mul, sub_eq_add_neg, matrix.neg_mul, matrix.mul_neg, matrix.one_mul, matrix.mul_one, matrix.mul_assoc, transpose_add, transpose_neg, mul_right_eq_of_mul_eq this, pivot_element], rw [pivot_element, matrix.mul_assoc, matrix.mul_assoc] at hpivot, by_cases h : i = r, { simp only [h, swap_basis_transpose_apply_single, mul_right_eq_of_mul_eq hA_bar, one_by_one_inv_mul_cancel hpivot, inv_eq_inverse], simp }, { have : ((single (0 : fin 1) r).to_matrix ⬝ (single i 0).to_matrix : cvec 1) = 0, { rw [← to_matrix_trans, single_trans_single_of_ne (ne.symm h), to_matrix_bot] }, simp [swap_basis_transpose_apply_single_of_ne _ _ h, mul_right_eq_of_mul_eq hA_bar, this] } end lemma has_left_inverse_swap {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : pivot_element B A_bar r s ≠ 0) : (A_bar ⬝ (B.swap r s).basis.to_matrixᵀ).has_left_inverse := ⟨_, swap_mul_swap_inverse hA_bar hpivot⟩ lemma has_left_inverse_swap_inverse {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : pivot_element B A_bar r s ≠ 0) : (swap_inverse B A_bar r s).has_left_inverse := has_right_inverse_iff_has_left_inverse.1 ⟨_, swap_mul_swap_inverse hA_bar hpivot⟩ lemma inverse_swap_eq {A_bar : matrix (fin m) (fin n) ℚ} {B : prebasis m n} {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : pivot_element B A_bar r s ≠ 0) : inverse (A_bar ⬝ (B.swap r s).basis.to_matrixᵀ) = swap_inverse B A_bar r s := eq.symm $ eq_inverse_of_mul_eq_one $ by rw [swap_mul_swap_inverse hA_bar hpivot] def adjust (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (s : fin (n - m)) (a : cvec 1) : cvec n := B.basis.to_matrixᵀ ⬝ b_bar + (B.nonbasis.to_matrixᵀ - B.basis.to_matrixᵀ ⬝ A_bar ⬝ B.nonbasis.to_matrixᵀ) ⬝ (single s 0).to_matrix ⬝ a lemma adjust_is_solution {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (b_bar : cvec m) (s : fin (n - m)) (a : cvec 1) (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) : A_bar ⬝ adjust B A_bar b_bar s a = b_bar := by simp [matrix.mul_assoc, matrix.mul_add, adjust, matrix.add_mul, mul_right_eq_of_mul_eq hA_bar] lemma single_pivot_mul_adjust (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (s : fin (n - m)) (a : cvec 1) : (single 0 s).to_matrix ⬝ B.nonbasis.to_matrix ⬝ adjust B A_bar b_bar s a = a := by simp [matrix.mul_assoc, matrix.add_mul, matrix.mul_add, adjust, mul_right_eq_of_mul_eq (nonbasis_mul_basis_transpose B), mul_right_eq_of_mul_eq (nonbasis_mul_nonbasis_transpose B)] lemma basis_mul_adjust (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (s : fin (n - m)) (a : cvec 1) : B.basis.to_matrix ⬝ adjust B A_bar b_bar s a = b_bar - A_bar ⬝ B.nonbasis.to_matrixᵀ ⬝ (single s 0).to_matrix ⬝ a := by simp [matrix.mul_assoc, matrix.add_mul, matrix.mul_add, adjust, mul_right_eq_of_mul_eq (basis_mul_basis_transpose B), mul_right_eq_of_mul_eq (basis_mul_nonbasis_transpose B)] lemma nonbasis_mul_adjust (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (s : fin (n - m)) (a : cvec 1) : B.nonbasis.to_matrix ⬝ adjust B A_bar b_bar s a = to_matrix (single s 0) ⬝ a := by simp [matrix.mul_assoc, matrix.add_mul, matrix.mul_add, adjust, mul_right_eq_of_mul_eq (nonbasis_mul_basis_transpose B), mul_right_eq_of_mul_eq (nonbasis_mul_nonbasis_transpose B)] lemma adjust_nonneg_iff {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} {b_bar : cvec m} {s : fin (n - m)} {a : cvec 1} (ha : 0 ≤ a) (hb : 0 ≤ b_bar) : 0 ≤ adjust B A_bar b_bar s a ↔ ∀ (i : fin m), 0 < pivot_element B A_bar i s → a ≤ ratio B A_bar b_bar i s := have ∀ i : fin m, (single (0 : fin 1) (B.basisg i)).to_matrix ⬝ 0 ≤ (single 0 (B.basisg i)).to_matrix ⬝ (B.basis.to_matrixᵀ ⬝ b_bar + (B.nonbasis.to_matrixᵀ - B.basis.to_matrixᵀ ⬝ A_bar ⬝ B.nonbasis.to_matrixᵀ) ⬝ to_matrix (single s 0) ⬝ a) ↔ 0 < pivot_element B A_bar i s → a ≤ ratio B A_bar b_bar i s, begin assume i, simp only [matrix.mul_zero, ratio, matrix.mul_add, matrix.add_mul, matrix.mul_assoc, sub_eq_add_neg, matrix.mul_neg, matrix.neg_mul, matrix.mul_assoc, mul_right_eq_of_mul_eq (single_basisg_mul_basis B i), mul_right_eq_of_mul_eq (single_basisg_mul_nonbasis B i), matrix.zero_mul, zero_add], rw [← sub_eq_add_neg, sub_nonneg], simp only [pivot_element, matrix.mul_assoc], cases classical.em (0 < (single (0 : fin 1) i).to_matrix ⬝ (A_bar ⬝ (B.nonbasis.to_matrixᵀ ⬝ (single s (0 : fin 1)).to_matrix))) with hpos hpos, { rw [← matrix.mul_eq_mul, ← mul_comm, ← div_eq_mul_inv, le_div_iff hpos, mul_comm, matrix.mul_eq_mul], simp [matrix.mul_assoc, hpos] }, { simp only [hpos, forall_prop_of_false, iff_true, not_false_iff], simp only [(matrix.mul_assoc _ _ _).symm, (matrix.mul_eq_mul _ _).symm] at *, intros, refine le_trans (mul_nonpos_of_nonpos_of_nonneg (le_of_not_gt hpos) ha) _, rw [cvec_le_iff] at hb, simpa using hb i }, end, begin rw [adjust, cvec_le_iff], split, { assume h i, rw [← this], exact h (B.basisg i) }, { assume h j, rcases eq_basisg_or_nonbasisg B j with ⟨i, hi⟩ | ⟨k, hk⟩, { rw [hi, this], exact h _ }, { simp only [hk, matrix.mul_assoc, mul_right_eq_of_mul_eq (single_nonbasisg_mul_basis _ _), matrix.mul_add, matrix.add_mul, matrix.mul_neg, mul_right_eq_of_mul_eq (single_nonbasisg_mul_nonbasis _ _), add_zero, matrix.neg_mul, matrix.zero_mul, zero_add, matrix.mul_zero, sub_eq_add_neg, neg_zero], by_cases hks : k = s, { simpa [hks] }, { rw [mul_right_eq_of_mul_eq (single_mul_single_of_ne hks _ _), matrix.zero_mul], exact le_refl _ } } } end def reduced_cost (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (c : rvec n) : rvec (n - m) := c ⬝ (B.nonbasis.to_matrixᵀ - B.basis.to_matrixᵀ ⬝ A_bar ⬝ B.nonbasis.to_matrixᵀ) noncomputable def solution_of_basis (B : prebasis m n) (A : matrix (fin m) (fin n) ℚ) (b : cvec m) : cvec n := B.basis.to_matrixᵀ ⬝ inverse (A ⬝ B.basis.to_matrixᵀ) ⬝ b lemma solution_of_basis_is_solution {A : matrix (fin m) (fin n) ℚ} {B : prebasis m n} (b : cvec m) (hA : (A ⬝ B.basis.to_matrixᵀ).has_left_inverse) : A ⬝ solution_of_basis B A b = b := by rw [solution_of_basis, ← matrix.mul_assoc, ← matrix.mul_assoc, mul_inverse (has_right_inverse_iff_has_left_inverse.2 hA), matrix.one_mul] noncomputable def objective_function_of_basis (A : matrix (fin m) (fin n) ℚ) (B : prebasis m n) (b : cvec m) (c : rvec n) : cvec 1 := c ⬝ solution_of_basis B A b /-- For proving `solution_of_basis_eq_adjust`, it suffices to prove they are equal after left multiplication by `A_bar` and after left multiplication by `B.nonbasis.to_matrix`. This lemma helps prove that. -/ lemma basis_transpose_add_nonbasis_transpose_mul_nonbasis {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) : (B.basis.to_matrixᵀ ⬝ A_bar + B.nonbasis.to_matrixᵀ ⬝ B.nonbasis.to_matrix) ⬝ (1 - B.basis.to_matrixᵀ ⬝ A_bar ⬝ B.nonbasis.to_matrixᵀ ⬝ B.nonbasis.to_matrix) = 1 := by rw [← transpose_mul_add_tranpose_mul B]; simp [matrix.mul_add, matrix.add_mul, matrix.mul_neg, matrix.mul_assoc, mul_right_eq_of_mul_eq hA_bar, mul_right_eq_of_mul_eq (nonbasis_mul_basis_transpose _), mul_right_eq_of_mul_eq (nonbasis_mul_nonbasis_transpose _)] lemma solution_of_basis_eq_adjust {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (b_bar : cvec m) {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : pivot_element B A_bar r s ≠ 0) : solution_of_basis (B.swap r s) A_bar b_bar = adjust B A_bar b_bar s (ratio B A_bar b_bar r s) := /- It suffices to prove they are equal after left multiplication by `A_bar` and by `B.nonbasis.to_matrix` -/ suffices A_bar ⬝ (B.swap r s).basis.to_matrixᵀ ⬝ inverse (A_bar ⬝ (B.swap r s).basis.to_matrixᵀ) ⬝ b_bar = A_bar ⬝ adjust B A_bar b_bar s (ratio B A_bar b_bar r s) ∧ B.nonbasis.to_matrix ⬝ (B.swap r s).basis.to_matrixᵀ ⬝ inverse (A_bar ⬝ (B.swap r s).basis.to_matrixᵀ) ⬝ b_bar = B.nonbasis.to_matrix ⬝ adjust B A_bar b_bar s (ratio B A_bar b_bar r s), begin rw [solution_of_basis, ← matrix.mul_left_inj ⟨_, mul_eq_one_comm.1 (basis_transpose_add_nonbasis_transpose_mul_nonbasis hA_bar)⟩, matrix.add_mul, matrix.add_mul], simp only [matrix.mul_assoc] at *, rw [this.1, this.2] end, { left := by rw [adjust_is_solution _ _ _ hA_bar, matrix.mul_inverse (has_right_inverse_iff_has_left_inverse.2 (has_left_inverse_swap hA_bar hpivot)), matrix.one_mul], right := /- This `have` would be unnecessary with a powerful `assoc_rw` tactic -/ have (single s r).to_matrix ⬝ (A_bar ⬝ (B.nonbasis.to_matrixᵀ ⬝ ((single s (0 : fin 1)).to_matrix ⬝ ((single 0 r).to_matrix ⬝ ((single r 0).to_matrix ⬝ (inverse (pivot_element B A_bar r s) ⬝ ((single 0 r).to_matrix ⬝ b_bar))))))) = (single s (0 : fin 1)).to_matrix ⬝ (single 0 r).to_matrix ⬝ b_bar, begin rw [pivot_element, mul_right_eq_of_mul_eq (single_mul_single (0 : fin 1) r (0 : fin 1)), single_subsingleton_eq_refl, to_matrix_refl, matrix.one_mul, ← single_mul_single s (0 : fin 1) r], simp only [(matrix.mul_assoc _ _ _).symm], simp only [(single s (0 : fin 1)).to_matrix.mul_assoc], rw [one_by_one_mul_inv_cancel, matrix.one_mul], { simpa [pivot.matrix.mul_assoc] using hpivot } end, begin simp only [adjust, matrix.mul_add, zero_add, sub_eq_add_neg, matrix.neg_mul, mul_right_eq_of_mul_eq (nonbasis_mul_basis_transpose _), matrix.zero_mul, nonbasis_mul_swap_basis_tranpose, matrix.mul_assoc, matrix.add_mul, matrix.mul_neg, mul_right_eq_of_mul_eq (nonbasis_mul_nonbasis_transpose _), matrix.one_mul, neg_zero, add_zero, inverse_swap_eq hA_bar hpivot, swap_inverse, ratio, this, inv_eq_inverse], simp end } lemma cvec_eq_basis_add_nonbasis (B : prebasis m n) (x : cvec n) : x = B.basis.to_matrixᵀ ⬝ B.basis.to_matrix ⬝ x + B.nonbasis.to_matrixᵀ ⬝ B.nonbasis.to_matrix ⬝ x := by simp only [(matrix.mul_assoc _ _ _).symm, (matrix.add_mul _ _ _).symm, B.transpose_mul_add_tranpose_mul, matrix.one_mul] lemma objective_function_eq {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} {b_bar : cvec m} {c : rvec n} {x : cvec n} (hAx : A_bar ⬝ x = b_bar) (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) : c ⬝ x = c ⬝ B.basis.to_matrixᵀ ⬝ b_bar + reduced_cost B A_bar c ⬝ B.nonbasis.to_matrix ⬝ x := have B.basis.to_matrix ⬝ x = b_bar - A_bar ⬝ B.nonbasis.to_matrixᵀ ⬝ B.nonbasis.to_matrix ⬝ x, by rw [eq_sub_iff_add_eq, ← (B.basis.to_matrix).one_mul, ← hA_bar, matrix.mul_assoc, matrix.mul_assoc, matrix.mul_assoc, matrix.mul_assoc, ← matrix.mul_add, ← matrix.mul_assoc, ← matrix.mul_assoc, ← matrix.add_mul, transpose_mul_add_tranpose_mul, matrix.one_mul, hAx], begin conv_lhs {rw [cvec_eq_basis_add_nonbasis B x, matrix.mul_assoc, this]}, simp [matrix.mul_add, matrix.mul_assoc, matrix.add_mul, reduced_cost] end lemma objective_function_swap_eq {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (b_bar : cvec m) (c : rvec n) {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : pivot_element B A_bar r s ≠ 0) : objective_function_of_basis A_bar (B.swap r s) b_bar c = objective_function_of_basis A_bar B b_bar c + reduced_cost B A_bar c ⬝ (single s (0 : fin 1)).to_matrix ⬝ ratio B A_bar b_bar r s := have h₁ : A_bar ⬝ (B.basis.to_matrixᵀ ⬝ b_bar) = b_bar, by rw [← matrix.mul_assoc, hA_bar, matrix.one_mul], have h₂ : (A_bar ⬝ (to_matrix ((swap B r s).basis))ᵀ).has_left_inverse, from has_left_inverse_swap hA_bar hpivot, begin rw [objective_function_of_basis, objective_function_eq (solution_of_basis_is_solution _ h₂) hA_bar, solution_of_basis_eq_adjust _ hA_bar hpivot, objective_function_of_basis, solution_of_basis, hA_bar, inverse_one, matrix.mul_one, c.mul_assoc, matrix.mul_assoc, matrix.mul_assoc], congr' 2, rw [adjust], simp only [matrix.mul_add, matrix.mul_assoc, sub_eq_add_neg, matrix.add_mul, matrix.neg_mul, matrix.mul_neg, mul_right_eq_of_mul_eq (nonbasis_mul_basis_transpose _), mul_right_eq_of_mul_eq (nonbasis_mul_nonbasis_transpose _)], simp end lemma swap_nonneg_iff {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (b_bar : cvec m) {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : 0 < pivot_element B A_bar r s) (h0b : 0 ≤ b_bar) : 0 ≤ solution_of_basis (B.swap r s) A_bar b_bar ↔ (∀ i : fin m, 0 < pivot_element B A_bar i s → ratio B A_bar b_bar r s ≤ ratio B A_bar b_bar i s) := begin rw [solution_of_basis_eq_adjust _ hA_bar (ne_of_lt hpivot).symm, adjust_nonneg_iff _ h0b, ratio], rw cvec_le_iff at h0b, exact mul_nonneg (inv_nonneg.2 (le_of_lt hpivot)) (by simpa using h0b r) end lemma swap_inverse_mul_nonneg {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (b_bar : cvec m) {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : 0 < pivot_element B A_bar r s) (h0b : 0 ≤ b_bar) : (∀ i : fin m, 0 < pivot_element B A_bar i s → ratio B A_bar b_bar r s ≤ ratio B A_bar b_bar i s) → 0 ≤ swap_inverse B A_bar r s ⬝ b_bar:= begin rw [← swap_nonneg_iff b_bar hA_bar hpivot h0b, solution_of_basis, inverse_swap_eq hA_bar (ne_of_lt hpivot).symm], assume hratio, rw [cvec_le_iff] at *, assume i, simpa [mul_right_eq_of_mul_eq (single_basisg_mul_basis _ _), matrix.mul_assoc] using hratio ((B.swap r s).basisg i) end def is_unbounded (A : matrix (fin m) (fin n) ℚ) (b : cvec m) (c : rvec n) : Prop := ∀ q : cvec 1, ∃ x, 0 ≤ x ∧ A ⬝ x = b ∧ q ≤ c ⬝ x def is_optimal (A : matrix (fin m) (fin n) ℚ) (b : cvec m) (c : rvec n) (x : cvec n) : Prop := 0 ≤ x ∧ A ⬝ x = b ∧ ∀ y, 0 ≤ y → A ⬝ y = b → c ⬝ y ≤ c ⬝ x def is_optimal_basis (B : prebasis m n) (A : matrix (fin m) (fin n) ℚ) (b : cvec m) (c : rvec n) : Prop := (A ⬝ B.basis.to_matrixᵀ).has_left_inverse ∧ is_optimal A b c (B.basis.to_matrixᵀ ⬝ inverse (A ⬝ B.basis.to_matrixᵀ) ⬝ b) lemma is_unbounded_of_pivot_element_nonpos {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (b_bar : cvec m) (c : rvec n) {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (h0b : 0 ≤ b_bar) (hs : reduced_cost B A_bar c ⬝ (single s (0 : fin 1)).to_matrix > 0) (h : ∀ r, pivot_element B A_bar r s ≤ 0) : is_unbounded A_bar b_bar c := begin assume q, let a := (reduced_cost B A_bar c ⬝ (single s (0 : fin 1)).to_matrix)⁻¹ ⬝ (q - c ⬝ ((to_matrix (B.basis))ᵀ ⬝ b_bar)), use adjust B A_bar b_bar s (max 0 a), simp only [adjust_is_solution b_bar _ _ hA_bar, true_and, eq_self_iff_true], simp only [objective_function_eq (adjust_is_solution b_bar _ _ hA_bar) hA_bar] {single_pass := tt}, simp only [nonbasis_mul_adjust, matrix.mul_assoc], split, { rw adjust_nonneg_iff (le_max_left _ _) h0b, assume i hi, exact absurd hi (not_lt_of_ge (h _)), }, { cases le_total a 0 with ha0 ha0, { rw [max_eq_left ha0], simp only [a, (mul_eq_mul _ _).symm] at ha0, rw [mul_comm, ← div_eq_mul_inv, div_le_iff hs, _root_.zero_mul, sub_nonpos] at ha0, simpa }, { simp only [max_eq_right ha0], rw [← (reduced_cost _ _ _).mul_assoc], dsimp only [a], rw [← matrix.mul_assoc (reduced_cost _ _ _ ⬝ _ ), ← mul_eq_mul, ← mul_eq_mul, mul_inv_cancel (ne_of_lt hs).symm, one_mul], simp [le_refl] } } end lemma is_optimal_basis_of_reduced_cost_nonpos {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (b_bar : cvec m) (c : rvec n) (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (h0b : 0 ≤ b_bar) (hs : reduced_cost B A_bar c ≤ 0) : is_optimal_basis B A_bar b_bar c := begin rw [is_optimal_basis, hA_bar, inverse_one, matrix.mul_one], refine ⟨⟨1, matrix.one_mul _⟩, matrix.mul_nonneg (by rw [← to_matrix_symm]; exact pequiv_nonneg _) h0b, by rw [← matrix.mul_assoc, hA_bar, matrix.one_mul], _⟩, assume x h0x hAx, rw [objective_function_eq hAx hA_bar, ← le_sub_iff_add_le', ← matrix.mul_assoc, sub_self], exact matrix.mul_nonpos_of_nonpos_of_nonneg (matrix.mul_nonpos_of_nonpos_of_nonneg hs (pequiv_nonneg _)) h0x end def choose_pivot_column (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) : option (fin (n - m)) := (fin.find (λ j : fin n, ∃ h : (B.nonbasis.symm j).is_some, 0 < reduced_cost B A_bar c ⬝ (single (option.get h) (0 : fin 1)).to_matrix)).bind B.nonbasis.symm lemma choose_pivot_column_eq_none (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (h0b : 0 ≤ b_bar) (h : choose_pivot_column B A_bar b_bar c = none) : is_optimal_basis B A_bar b_bar c := is_optimal_basis_of_reduced_cost_nonpos _ _ hA_bar h0b $ begin rw [choose_pivot_column, option.bind_eq_none] at h, have : ∀ j, j ∉ fin.find (λ j : fin n, ∃ h : (B.nonbasis.symm j).is_some, 0 < reduced_cost B A_bar c ⬝ (single (option.get h) (0 : fin 1)).to_matrix), { assume j hj, cases option.is_some_iff_exists.1 (fin.find_spec _ hj).fst with s hs, exact h s j hj hs }, rw [← option.eq_none_iff_forall_not_mem, fin.find_eq_none_iff] at this, rw [rvec_le_iff], assume j, refine le_of_not_gt (λ h0j, _), have hj : ↥(B.nonbasis.symm (B.nonbasisg j)).is_some, from option.is_some_iff_exists.2 ⟨j, nonbasis_nonbasisg _ _⟩, have hjg : j = option.get hj, { rw [← option.some_inj, option.some_get, nonbasis_nonbasisg] }, exact this (B.nonbasisg j) ⟨hj, by { rw ← hjg, rwa [matrix.zero_mul] at h0j} ⟩ end lemma choose_pivot_column_spec (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) (s : fin (n - m)) (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (h0b : 0 ≤ b_bar) (h : choose_pivot_column B A_bar b_bar c = some s) : 0 < reduced_cost B A_bar c ⬝ (single s (0 : fin 1)).to_matrix := begin rw [choose_pivot_column, option.bind_eq_some'] at h, cases h with j hj, have := fin.find_spec _ hj.1, have hs : s = option.get this.fst, { rw [← option.some_inj, option.some_get, hj.2] }, exact hs.symm ▸ this.snd end set_option class.instance_max_depth 60 def choose_pivot_row (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) (s : fin (n - m)) : option (fin m) := (fin.find (λ j : fin n, ∃ h : (B.basis.symm j).is_some, 0 < pivot_element B A_bar (option.get h) s ∧ ∀ i : fin m, ((0 : cvec 1) < pivot_element B A_bar i s) → ratio B A_bar b_bar (option.get h) s ≤ ratio B A_bar b_bar i s)).bind B.basis.symm lemma choose_pivot_row_spec (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) (r : fin m) (s : fin (n - m)) (hr : r ∈ choose_pivot_row B A_bar b_bar c s) : 0 < pivot_element B A_bar r s ∧ ∀ i : fin m, 0 < pivot_element B A_bar i s → ratio B A_bar b_bar r s ≤ ratio B A_bar b_bar i s := begin rw [choose_pivot_row, option.mem_def, option.bind_eq_some'] at hr, cases hr with j hj, have hrj : r = option.get (fin.find_spec _ hj.1).fst, { rw [← option.some_inj, option.some_get, ← hj.2] }, rw hrj, exact (fin.find_spec _ hj.1).snd end lemma choose_pivot_row_eq_none (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) (r : fin m) (s : fin (n - m)) (hn : choose_pivot_row B A_bar b_bar c s = none) : pivot_element B A_bar r s ≤ 0 := le_of_not_gt $ λ hpivot, begin rw [choose_pivot_row, option.bind_eq_none] at hn, cases @finset.min_of_mem _ _ ((univ.filter (λ j, 0 < pivot_element B A_bar j s)).image (λ i, ratio B A_bar b_bar i s)) (ratio B A_bar b_bar r s) (mem_image_of_mem _ (finset.mem_filter.2 ⟨mem_univ _, hpivot⟩)) with q hq, rcases mem_image.1 (mem_of_min hq) with ⟨i, hip, hiq⟩, subst hiq, have : ∀ j : fin n, j ∉ fin.find (λ j : fin n, ∃ h : (B.basis.symm j).is_some, 0 < pivot_element B A_bar (option.get h) s ∧ ∀ i : fin m, 0 < pivot_element B A_bar i s → ratio B A_bar b_bar (option.get h) s ≤ ratio B A_bar b_bar i s), { assume j hj, cases option.is_some_iff_exists.1 (fin.find_spec _ hj).fst with r hr, exact hn _ _ hj hr }, rw [← option.eq_none_iff_forall_not_mem, fin.find_eq_none_iff] at this, have hi : ↥(B.basis.symm (B.basisg i)).is_some, from option.is_some_iff_exists.2 ⟨i, basis_basisg _ _⟩, have hig : i = option.get hi, { rw [← option.some_inj, option.some_get, basis_basisg] }, exact this (B.basisg i) ⟨(option.is_some_iff_exists.2 ⟨i, basis_basisg _ _⟩), begin rw [← hig], clear_aux_decl, refine ⟨by simpa using hip, _⟩, assume j hj, refine min_le_of_mem (mem_image.2 ⟨j, _⟩) hq, simp [hj] end⟩ end lemma is_unbounded_of_choose_pivot_row_eq_none (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) (s : fin (n - m)) (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (h0b : 0 ≤ b_bar) (hs : 0 < reduced_cost B A_bar c ⬝ (single s (0 : fin 1)).to_matrix) (hn : choose_pivot_row B A_bar b_bar c s = none) : is_unbounded A_bar b_bar c := is_unbounded_of_pivot_element_nonpos _ _ hA_bar h0b hs (λ _, choose_pivot_row_eq_none _ _ _ _ _ _ hn) lemma is_unbounded_swap {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} {b_bar : cvec m} {c : rvec n} {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : pivot_element B A_bar r s ≠ 0) : is_unbounded (swap_inverse B A_bar r s ⬝ A_bar) (swap_inverse B A_bar r s ⬝ b_bar) c → is_unbounded A_bar b_bar c := by simp only [is_unbounded, matrix.mul_assoc, matrix.mul_left_inj (has_left_inverse_swap_inverse hA_bar hpivot), imp_self] lemma is_optimal_basis_swap {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} {b_bar : cvec m} {c : rvec n} (S : matrix (fin m) (fin m) ℚ) (hS : S.has_left_inverse) (h : is_optimal_basis B (S ⬝ A_bar) (S ⬝ b_bar) c) : is_optimal_basis B A_bar b_bar c := begin rw [is_optimal_basis, matrix.mul_assoc, ← has_left_inverse_mul hS] at h, simp only [is_optimal_basis, is_optimal, matrix.mul_assoc, matrix.mul_left_inj hS, h.1, inverse_one, matrix.one_mul, matrix.mul_one, matrix.mul_left_inj (inverse_has_left_inverse (has_right_inverse_iff_has_left_inverse.2 hS)), inverse_mul hS, inverse_one, mul_right_eq_of_mul_eq (inverse_mul hS), matrix.one_mul, matrix.mul_one, mul_inverse_rev hS h.1, *] at *, tauto, end axiom wf (p : Prop) : p def simplex : Π (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (h0b : 0 ≤ b_bar), { o : option (Σ (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ), cvec m) // option.cases_on o (is_unbounded A_bar b_bar c) (λ P, is_optimal_basis P.1 A_bar b_bar c) } | B A_bar b_bar c hA_bar h0b := match choose_pivot_column B A_bar b_bar c, (λ s, choose_pivot_column_spec B A_bar b_bar c s hA_bar h0b), choose_pivot_column_eq_none B A_bar b_bar c hA_bar h0b with | none, _, hn := ⟨some ⟨B, A_bar, b_bar⟩, hn rfl⟩ | some s, hs, _ := match choose_pivot_row B A_bar b_bar c s, (λ r, choose_pivot_row_spec B A_bar b_bar c r s), is_unbounded_of_choose_pivot_row_eq_none B A_bar b_bar c s hA_bar h0b (hs _ rfl) with | none, _, hnone := ⟨none, hnone rfl⟩ | (some r), hr, _ := let S := swap_inverse B A_bar r s in have wf : prebasis.sizeof m n (swap B r s) < prebasis.sizeof m n B, from wf _, let o := simplex (B.swap r s) (S ⬝ A_bar) (S ⬝ b_bar) c (by rw [matrix.mul_assoc, swap_mul_swap_inverse hA_bar (ne_of_lt (hr r rfl).1).symm]) (swap_inverse_mul_nonneg b_bar hA_bar (hr _ rfl).1 h0b (hr _ rfl).2) in ⟨o.1, option.cases_on o.1 (is_unbounded_swap hA_bar (ne_of_lt (hr r rfl).1).symm) (λ P, is_optimal_basis_swap S (has_left_inverse_swap_inverse hA_bar (ne_of_lt (hr r rfl).1).symm)) o.2⟩ end end #print axioms simplex.simplex def rel (A : matrix (fin m) (fin n) ℚ) (b : cvec m) (c : rvec n) : prebasis m n → prebasis m n → Prop := tc (λ B C, ∃ hs : (choose_pivot_column B (inverse (A ⬝ B.basis.to_matrixᵀ) ⬝ A) (inverse (A ⬝ B.basis.to_matrixᵀ) ⬝ b) c).is_some, ∃ hr : (choose_pivot_row B (inverse (A ⬝ B.basis.to_matrixᵀ) ⬝ A) (inverse (A ⬝ B.basis.to_matrixᵀ) ⬝ b) c (option.get hs)).is_some, C = B.swap (option.get hr) (option.get hs)) #eval inverse (list.to_matrix 3 3 [[1,2,3],[0,1,5],[0,0,1]]) -- def ex.A := list.to_matrix 2 5 [[1,1,0,1,0], -- [0,1,-1,0,1]] -- def ex.b : cvec 2 := (λ i _, (list.nth_le [8,0] i sorry)) -- def ex.c : rvec 5 := λ _ i, (list.nth_le [1, 1, 1, 0, 0] i sorry) -- def ex.B : prebasis 2 5 := -- ⟨pequiv_of_vector ⟨[3, 4], rfl⟩ dec_trivial, -- pre_nonbasis_of_vector ⟨[3, 4], rfl⟩ dec_trivial, sorry, sorry, sorry⟩ -- #eval ex.A ⬝ ex.B.basis.to_matrixᵀ -- #eval (simplex ex.B ex.A ex.b ex.c dec_trivial dec_trivial).1.is_some def ex.A := list.to_matrix 3 7 [[1/4, - 8, - 1, 9, 1, 0, 0], [1/2, -12, -1/2, 3, 0, 1, 0], [ 0, 0, 1, 0, 0, 0, 1]] def ex.b : cvec 3 := (λ i _, list.nth_le [0,0,1] i sorry) --#eval ex.b def ex.c : rvec 7 := λ _ i, (list.nth_le [3/4, -20, 1/2, -6, 0, 0, 0] i sorry) --#eval ex.c def ex.B : prebasis 3 7 := ⟨pequiv_of_vector ⟨[4, 5, 6], rfl⟩ dec_trivial, pre_nonbasis_of_vector ⟨[4,5,6], rfl⟩ dec_trivial, sorry, sorry, sorry⟩ --#eval (simplex ex.B ex.A ex.b ex.c dec_trivial dec_trivial).1.is_some #eval (find_optimal_solution_from_starting_basis ex.A ex.c ex.b ex.B) --set_option trace.fun_info true #eval (is_optimal_bool ex.A ex.c ex.b ex.B) -- (some [[2064/445]]) -- (some [[6401/1895]]) #eval (is_feasible_basis ex.A ex.c ex.b ex.B : bool) -- #eval (show matrix _ _ ℚ, from minor ex.A id ex.B.read) * -- _root_.inverse (show matrix _ _ ℚ, from minor ex.A id ex.B.read ) -- #eval ((1 : cvec 1) - (minor ex.c id ex.B.read) ⬝ -- _root_.inverse (minor ex.A id ex.B.read) ⬝ -- (minor ex.A id ex.NB.read)) #eval finishing_basis ex.A ex.c ex.b ex.B #eval test ex.A ex.c ex.b ex.B #eval (let x : cvec 4 := λ i _, list.nth_le [0, 80/89, 62/89, 196/89] i sorry in let A := list.to_matrix 3 4 [[12, -1, 1, 1], [1, 1.45, 1, 0], [1, 2, 0, 1]] in A ⬝ x )
\section{Secure Coding : EXP04-A. Do not perform byte-by-byte comparisons between structures} Structures may be padded with data to ensure that they are properly aligned in memory. The contents of the padding, and the amount of padding added is implementation defined. This can can lead to incorrect results when attempting a byte-by-byte comparison between structures. \subsection{Non-Compliant Code Example} This example uses {\tt memcmp()} to compare two structures. If the structures are determined to be equal, {\tt buf\_compare()} should return 1 otherwise, 0 should be returned. However, structure padding may cause {\tt memcmp()} to evaluate the structures to be unequal regardless of the contents of their fields. \code{ \noindent \ttfamily \hlstd{}\hlline{\ \ \ \ 1\ }\hlstd{}\hltyp{struct\ }\hlstd{my\textunderscore buf\ }\hlsym{\{\\ }\hlline{\ \ \ \ 2\ }\hlsym{\hlstd{\ \ }}\hlstd{}\hltyp{size\textunderscore t\ }\hlstd{size;\\ }\hlline{\ \ \ \ 3\ }\hlstd{\hlstd{\ \ }}\hltyp{char\ }\hlstd{buffer}\hlsym{[}\hlstd{}\hlnum{50}\hlstd{}\hlsym{]}\hlstd{;\\ }\hlline{\ \ \ \ 4\ }\hlstd{}\hlsym{\}}\hlstd{;\\ }\hlline{\ \ \ \ 5\ }\hlstd{\\ }\hlline{\ \ \ \ 6\ }\hlstd{}\hltyp{unsigned\ int\ }\hlstd{buf\textunderscore compare}\hlsym{(}\hlstd{}\hltyp{struct\ }\hlstd{my\textunderscore buf\ *s1,\ }\hltyp{struct\ }\hlstd{my\textunderscore buf\ *s2}\hlsym{)\ \{\\ }\hlline{\ \ \ \ 7\ }\hlsym{\hlstd{\ \ }}\hlstd{}\hlkey{if\ }\hlstd{}\hlsym{(}\hlstd{!memcmp}\hlsym{(}\hlstd{s1,\ s2,\ }\hlkey{sizeof}\hlstd{}\hlsym{(}\hlstd{}\hltyp{struct\ }\hlstd{my\textunderscore struct}\hlsym{)))\ \{\\ }\hlline{\ \ \ \ 8\ }\hlsym{\hlstd{\ \ \ \ }}\hlstd{}\hlkey{return\ }\hlstd{}\hlnum{1}\hlstd{;\\ }\hlline{\ \ \ \ 9\ }\hlstd{\hlstd{\ \ }}\hlsym{\}\\ }\hlline{\ \ \ 10\ }\hlsym{\hlstd{\ \ }}\hlstd{}\hlkey{return\ }\hlstd{}\hlnum{0}\hlstd{;\\ }\hlline{\ \ \ 11\ }\hlstd{}\hlsym{\}\\ }\hlline{\ \ \ 12\ }\hlsym{}\hlstd{}\\ \mbox{}\\ \normalfont } \subsection{Compliant Solution} To accurately compare structures it is necessary to perform a field-by-field comparison [ \htmladdnormallink{Summit 95}{https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References} ]. The {\tt buf\_compare()} function has been rewritten to do this. \code{ \noindent \ttfamily \hlstd{}\hlline{\ \ \ \ 1\ }\hlstd{}\hltyp{struct\ }\hlstd{my\textunderscore buf\ }\hlsym{\{\\ }\hlline{\ \ \ \ 2\ }\hlsym{\hlstd{\ \ }}\hlstd{}\hltyp{size\textunderscore t\ }\hlstd{size;\\ }\hlline{\ \ \ \ 3\ }\hlstd{\hlstd{\ \ }}\hltyp{char\ }\hlstd{buffer}\hlsym{[}\hlstd{}\hlnum{50}\hlstd{}\hlsym{]}\hlstd{;\\ }\hlline{\ \ \ \ 4\ }\hlstd{}\hlsym{\}}\hlstd{;\\ }\hlline{\ \ \ \ 5\ }\hlstd{\\ }\hlline{\ \ \ \ 6\ }\hlstd{}\hltyp{unsigned\ int\ }\hlstd{buf\textunderscore compare}\hlsym{(}\hlstd{}\hltyp{struct\ }\hlstd{buffer\ *s1,\ }\hltyp{struct\ }\hlstd{buffer\ *s2}\hlsym{)\ \{\\ }\hlline{\ \ \ \ 7\ }\hlsym{\hlstd{\ \ }}\hlstd{}\hlkey{if\ }\hlstd{}\hlsym{(}\hlstd{s1-$>$size\ !=\ s2-$>$size}\hlsym{)\ }\hlstd{}\hlkey{return\ }\hlstd{}\hlnum{0}\hlstd{;\\ }\hlline{\ \ \ \ 8\ }\hlstd{\hlstd{\ \ }}\hlkey{if\ }\hlstd{}\hlsym{(}\hlstd{strcmp}\hlsym{(}\hlstd{s1-$>$buffer,\ s2-$>$buffer}\hlsym{)\ }\hlstd{!=\ }\hlnum{0}\hlstd{}\hlsym{)\ }\hlstd{}\hlkey{return\ }\hlstd{}\hlnum{0}\hlstd{;\\ }\hlline{\ \ \ \ 9\ }\hlstd{\hlstd{\ \ }}\hlkey{return\ }\hlstd{}\hlnum{1}\hlstd{;\\ }\hlline{\ \ \ 10\ }\hlstd{}\hlsym{\}\\ }\hlline{\ \ \ 11\ }\hlsym{}\hlstd{}\\ \mbox{}\\ \normalfont } \subsection{Risk Assessment} Failure to correctly compare structure can lead to unexpected program behavior. \begin{tabular}[c]{| c| c| c| c| c| c|} \hline {\bf Rule} & {\bf Severity} & {\bf Likelihood} & {\bf Remediation Cost} & {\bf Priority} & {\bf Level} \\ \hline EXP04-A & {\bf 2} (medium) & {\bf 1} (unlikely) & {\bf 1} (high) & {\bf P2} & {\bf L3} \\ \hline \end{tabular} \subsubsection{Related Vulnerabilities} Search for vulnerabilities resulting from the violation of this rule on the \htmladdnormallink{CERT website}{https://www.kb.cert.org/vulnotes/bymetric?searchview\&query=FIELD+contains+EXP04-A} . \subsection{References} [ \htmladdnormallink{Dowd 06}{https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References} ] Chapter 6, "C Language Issues" (Structure Padding 284-287) [ \\* \htmladdnormallink{ISO/IEC 9899-1999}{https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References} ] Section 6.7.2.1, "Structure and union specifiers" [ \\* \htmladdnormallink{Kerrighan 88}{https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References} ] Chapter 6, "Structures" (Structures and Functions 129) [ \\* \htmladdnormallink{Summit 95}{https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References} ] comp.lang.c FAQ list - Question 2.8
import unittest import numpy as np
# Looker API 4.0 (Beta) Reference # # Welcome to the future! API 4.0 co-exists with APIs 3.1 and 3.0. (3.0 should no longer be used.) The \"beta\" tag means updates for API 4.0 may include breaking changes, but as always we will work to minimize them. ### Authorization The classic method of API authorization uses Looker **API3** credentials for authorization and access control. Looker admins can create API3 credentials on Looker's **Admin/Users** page. API 4.0 adds additional ways to authenticate API requests, including OAuth and CORS requests. For details, see [Looker API Authorization](https://looker.com/docs/r/api/authorization). ### API Explorer The API Explorer is a Looker-provided utility with many new and unique features for learning and using the Looker API and SDKs. It is a replacement for the 'api-docs' page currently provided on Looker instances. For details, see the [API Explorer documentation](https://looker.com/docs/r/api/explorer). ### Looker Language SDKs The Looker API is a RESTful system that should be usable by any programming language capable of making HTTPS requests. SDKs for a variety of programming languages are also provided to streamline using the API. Looker has an OpenSource [sdk-codegen project](https://github.com/looker-open-source/sdk-codegen) that provides several language SDKs. Language SDKs generated by `sdk-codegen` have an Authentication manager that can automatically authenticate API requests when needed. For details on available Looker SDKs, see [Looker API Client SDKs](https://looker.com/docs/r/api/client_sdks). ### API Versioning Future releases of Looker expand the latest API version release-by-release to securely expose more and more of the core power of the Looker platform to API client applications. API endpoints marked as \"beta\" may receive breaking changes without warning (but we will try to avoid doing that). Stable (non-beta) API endpoints should not receive breaking changes in future releases. For details, see [Looker API Versioning](https://looker.com/docs/r/api/versioning). ### In This Release API 4.0 version was introduced so we can make adjustments to API functions, parameters, and response types to fix bugs and inconsistencies. These changes fall outside the bounds of non-breaking additive changes we can make to our stable API 3.1. One benefit of these type adjustments in API 4.0 is dramatically better support for strongly typed languages like TypeScript, Kotlin, Swift, Go, C#, and more. While API 3.1 is still the de-facto Looker API (\"current\", \"stable\", \"default\", etc), the bulk of our development activity has shifted to API 4.0, where all new features are added. The API Explorer can be used to [interactively compare](https://looker.com/docs/r/api/explorer#comparing_api_versions) the differences between API 3.1 and 4.0. ### API and SDK Support Policies Looker API versions and language SDKs have varying support levels. Please read the API and SDK [support policies](https://looker.com/docs/r/api/support-policy) for more information. # # OpenAPI spec version: 4.0.21.18 # # Generated by: https://github.com/swagger-api/swagger-codegen.git #' FolderBase Class #' #' @field name #' @field parent_id #' @field id #' @field content_metadata_id #' @field created_at #' @field creator_id #' @field child_count #' @field external_id #' @field is_embed #' @field is_embed_shared_root #' @field is_embed_users_root #' @field is_personal #' @field is_personal_descendant #' @field is_shared_root #' @field is_users_root #' @field can #' #' @importFrom R6 R6Class #' @importFrom jsonlite parse_json toJSON #' @export FolderBase <- R6::R6Class( 'FolderBase', public = list( `name` = NULL, `parent_id` = NULL, `id` = NULL, `content_metadata_id` = NULL, `created_at` = NULL, `creator_id` = NULL, `child_count` = NULL, `external_id` = NULL, `is_embed` = NULL, `is_embed_shared_root` = NULL, `is_embed_users_root` = NULL, `is_personal` = NULL, `is_personal_descendant` = NULL, `is_shared_root` = NULL, `is_users_root` = NULL, `can` = NULL, initialize = function(`name`, `parent_id`, `id`, `content_metadata_id`, `created_at`, `creator_id`, `child_count`, `external_id`, `is_embed`, `is_embed_shared_root`, `is_embed_users_root`, `is_personal`, `is_personal_descendant`, `is_shared_root`, `is_users_root`, `can`){ if (!missing(`name`)) { stopifnot(is.character(`name`), length(`name`) == 1) self$`name` <- `name` } if (!missing(`parent_id`)) { stopifnot(is.character(`parent_id`), length(`parent_id`) == 1) self$`parent_id` <- `parent_id` } if (!missing(`id`)) { stopifnot(is.character(`id`), length(`id`) == 1) self$`id` <- `id` } if (!missing(`content_metadata_id`)) { stopifnot(is.numeric(`content_metadata_id`), length(`content_metadata_id`) == 1) self$`content_metadata_id` <- `content_metadata_id` } if (!missing(`created_at`)) { stopifnot(is.character(`created_at`), length(`created_at`) == 1) self$`created_at` <- `created_at` } if (!missing(`creator_id`)) { stopifnot(is.numeric(`creator_id`), length(`creator_id`) == 1) self$`creator_id` <- `creator_id` } if (!missing(`child_count`)) { stopifnot(is.numeric(`child_count`), length(`child_count`) == 1) self$`child_count` <- `child_count` } if (!missing(`external_id`)) { stopifnot(is.character(`external_id`), length(`external_id`) == 1) self$`external_id` <- `external_id` } if (!missing(`is_embed`)) { self$`is_embed` <- `is_embed` } if (!missing(`is_embed_shared_root`)) { self$`is_embed_shared_root` <- `is_embed_shared_root` } if (!missing(`is_embed_users_root`)) { self$`is_embed_users_root` <- `is_embed_users_root` } if (!missing(`is_personal`)) { self$`is_personal` <- `is_personal` } if (!missing(`is_personal_descendant`)) { self$`is_personal_descendant` <- `is_personal_descendant` } if (!missing(`is_shared_root`)) { self$`is_shared_root` <- `is_shared_root` } if (!missing(`is_users_root`)) { self$`is_users_root` <- `is_users_root` } if (!missing(`can`)) { self$`can` <- `can` } }, toJSON = function() { FolderBaseObject <- list() if (!is.null(self$`name`)) { FolderBaseObject[['name']] <- self$`name` } if (!is.null(self$`parent_id`)) { FolderBaseObject[['parent_id']] <- self$`parent_id` } if (!is.null(self$`id`)) { FolderBaseObject[['id']] <- self$`id` } if (!is.null(self$`content_metadata_id`)) { FolderBaseObject[['content_metadata_id']] <- self$`content_metadata_id` } if (!is.null(self$`created_at`)) { FolderBaseObject[['created_at']] <- self$`created_at` } if (!is.null(self$`creator_id`)) { FolderBaseObject[['creator_id']] <- self$`creator_id` } if (!is.null(self$`child_count`)) { FolderBaseObject[['child_count']] <- self$`child_count` } if (!is.null(self$`external_id`)) { FolderBaseObject[['external_id']] <- self$`external_id` } if (!is.null(self$`is_embed`)) { FolderBaseObject[['is_embed']] <- self$`is_embed` } if (!is.null(self$`is_embed_shared_root`)) { FolderBaseObject[['is_embed_shared_root']] <- self$`is_embed_shared_root` } if (!is.null(self$`is_embed_users_root`)) { FolderBaseObject[['is_embed_users_root']] <- self$`is_embed_users_root` } if (!is.null(self$`is_personal`)) { FolderBaseObject[['is_personal']] <- self$`is_personal` } if (!is.null(self$`is_personal_descendant`)) { FolderBaseObject[['is_personal_descendant']] <- self$`is_personal_descendant` } if (!is.null(self$`is_shared_root`)) { FolderBaseObject[['is_shared_root']] <- self$`is_shared_root` } if (!is.null(self$`is_users_root`)) { FolderBaseObject[['is_users_root']] <- self$`is_users_root` } if (!is.null(self$`can`)) { FolderBaseObject[['can']] <- self$`can` } FolderBaseObject }, fromJSONObject = function(FolderBaseJsonObject) { FolderBaseObject <- FolderBaseJsonObject #jsonlite::fromJSON(FolderBaseJson, simplifyVector = FALSE) if (!is.null(FolderBaseObject$`name`)) { self$`name` <- FolderBaseObject$`name` } if (!is.null(FolderBaseObject$`parent_id`)) { self$`parent_id` <- FolderBaseObject$`parent_id` } if (!is.null(FolderBaseObject$`id`)) { self$`id` <- FolderBaseObject$`id` } if (!is.null(FolderBaseObject$`content_metadata_id`)) { self$`content_metadata_id` <- FolderBaseObject$`content_metadata_id` } if (!is.null(FolderBaseObject$`created_at`)) { self$`created_at` <- FolderBaseObject$`created_at` } if (!is.null(FolderBaseObject$`creator_id`)) { self$`creator_id` <- FolderBaseObject$`creator_id` } if (!is.null(FolderBaseObject$`child_count`)) { self$`child_count` <- FolderBaseObject$`child_count` } if (!is.null(FolderBaseObject$`external_id`)) { self$`external_id` <- FolderBaseObject$`external_id` } if (!is.null(FolderBaseObject$`is_embed`)) { self$`is_embed` <- FolderBaseObject$`is_embed` } if (!is.null(FolderBaseObject$`is_embed_shared_root`)) { self$`is_embed_shared_root` <- FolderBaseObject$`is_embed_shared_root` } if (!is.null(FolderBaseObject$`is_embed_users_root`)) { self$`is_embed_users_root` <- FolderBaseObject$`is_embed_users_root` } if (!is.null(FolderBaseObject$`is_personal`)) { self$`is_personal` <- FolderBaseObject$`is_personal` } if (!is.null(FolderBaseObject$`is_personal_descendant`)) { self$`is_personal_descendant` <- FolderBaseObject$`is_personal_descendant` } if (!is.null(FolderBaseObject$`is_shared_root`)) { self$`is_shared_root` <- FolderBaseObject$`is_shared_root` } if (!is.null(FolderBaseObject$`is_users_root`)) { self$`is_users_root` <- FolderBaseObject$`is_users_root` } if (!is.null(FolderBaseObject$`can`)) { self$`can` <- FolderBaseObject$`can` } }, fromJSON = function(FolderBaseJson) { FolderBaseObject <- jsonlite::fromJSON(FolderBaseJson, simplifyVector = FALSE) self$fromJSONObject(FolderBaseObject) }, toJSONString = function() { sprintf( '{ "name": %s, "parent_id": %s, "id": %s, "content_metadata_id": %d, "created_at": %s, "creator_id": %d, "child_count": %d, "external_id": %s, "is_embed": %s, "is_embed_shared_root": %s, "is_embed_users_root": %s, "is_personal": %s, "is_personal_descendant": %s, "is_shared_root": %s, "is_users_root": %s, "can": %s }', self$`name`, self$`parent_id`, self$`id`, self$`content_metadata_id`, self$`created_at`, self$`creator_id`, self$`child_count`, self$`external_id`, self$`is_embed`, self$`is_embed_shared_root`, self$`is_embed_users_root`, self$`is_personal`, self$`is_personal_descendant`, self$`is_shared_root`, self$`is_users_root`, self$`can` ) }, fromJSONString = function(FolderBaseJson) { FolderBaseObject <- jsonlite::fromJSON(FolderBaseJson, simplifyVector = FALSE) self$`name` <- FolderBaseObject$`name` self$`parent_id` <- FolderBaseObject$`parent_id` self$`id` <- FolderBaseObject$`id` self$`content_metadata_id` <- FolderBaseObject$`content_metadata_id` self$`created_at` <- FolderBaseObject$`created_at` self$`creator_id` <- FolderBaseObject$`creator_id` self$`child_count` <- FolderBaseObject$`child_count` self$`external_id` <- FolderBaseObject$`external_id` self$`is_embed` <- FolderBaseObject$`is_embed` self$`is_embed_shared_root` <- FolderBaseObject$`is_embed_shared_root` self$`is_embed_users_root` <- FolderBaseObject$`is_embed_users_root` self$`is_personal` <- FolderBaseObject$`is_personal` self$`is_personal_descendant` <- FolderBaseObject$`is_personal_descendant` self$`is_shared_root` <- FolderBaseObject$`is_shared_root` self$`is_users_root` <- FolderBaseObject$`is_users_root` self$`can` <- FolderBaseObject$`can` } ) )
theory "Value" imports HOLCF begin subsubsection \<open>The semantic domain for values and environments\<close> domain Value = Fn (lazy "Value \<rightarrow> Value") | B (lazy "bool discr") fixrec Fn_project :: "Value \<rightarrow> Value \<rightarrow> Value" where "Fn_project\<cdot>(Fn\<cdot>f) = f" abbreviation Fn_project_abbr (infix "\<down>Fn" 55) where "f \<down>Fn v \<equiv> Fn_project\<cdot>f\<cdot>v" fixrec B_project :: "Value \<rightarrow> Value \<rightarrow> Value \<rightarrow> Value" where "B_project\<cdot>(B\<cdot>db)\<cdot>v\<^sub>1\<cdot>v\<^sub>2 = (if undiscr db then v\<^sub>1 else v\<^sub>2)" lemma [simp]: "B_project\<cdot>(B\<cdot>(Discr b))\<cdot>v\<^sub>1\<cdot>v\<^sub>2 = (if b then v\<^sub>1 else v\<^sub>2)" "B_project\<cdot>\<bottom>\<cdot>v\<^sub>1\<cdot>v\<^sub>2 = \<bottom>" "B_project\<cdot>(Fn\<cdot>f)\<cdot>v\<^sub>1\<cdot>v\<^sub>2 = \<bottom>" by fixrec_simp+ text \<open> A chain in the domain @{typ Value} is either always bottom, or eventually @{term "Fn"} of another chain \<close> lemma Value_chainE[consumes 1, case_names bot B Fn]: assumes "chain Y" obtains "Y = (\<lambda> _ . \<bottom>)" | n b where "Y = (\<lambda> m. (if m < n then \<bottom> else B\<cdot>b))" | n Y' where "Y = (\<lambda> m. (if m < n then \<bottom> else Fn\<cdot>(Y' (m-n))))" "chain Y'" proof(cases "Y = (\<lambda> _ . \<bottom>)") case True thus ?thesis by (rule that(1)) next case False hence "\<exists> i. Y i \<noteq> \<bottom>" by auto hence "\<exists> n. Y n \<noteq> \<bottom> \<and> (\<forall>m. Y m \<noteq> \<bottom> \<longrightarrow> m \<ge> n)" by (rule exE)(rule ex_has_least_nat) then obtain n where "Y n \<noteq> \<bottom>" and "\<forall>m. m < n \<longrightarrow> Y m = \<bottom>" by fastforce hence "(\<exists> f. Y n = Fn\<cdot>f) \<or> (\<exists> b. Y n = B\<cdot>b)" by (metis Value.exhaust) thus ?thesis proof assume "(\<exists> f. Y n = Fn\<cdot>f)" then obtain f where "Y n = Fn \<cdot> f" by blast { fix i from \<open>chain Y\<close> have "Y n \<sqsubseteq> Y (i+n)" by (metis chain_mono le_add2) with \<open>Y n = _\<close> have "\<exists> g. (Y (i+n) = Fn \<cdot> g)" by (metis Value.dist_les(1) Value.exhaust below_bottom_iff) } then obtain Y' where Y': "\<And> i. Y (i + n) = Fn \<cdot> (Y' i)" by metis have "Y = (\<lambda>m. if m < n then \<bottom> else Fn\<cdot>(Y' (m - n)))" using \<open>\<forall>m. _\<close> Y' by (metis add_diff_inverse add.commute) moreover have"chain Y'" using \<open>chain Y\<close> by (auto intro!:chainI elim: chainE simp add: Value.inverts[symmetric] Y'[symmetric] simp del: Value.inverts) ultimately show ?thesis by (rule that(3)) next assume "(\<exists> b. Y n = B\<cdot>b)" then obtain b where "Y n = B\<cdot>b" by blast { fix i from \<open>chain Y\<close> have "Y n \<sqsubseteq> Y (i+n)" by (metis chain_mono le_add2) with \<open>Y n = _\<close> have "Y (i+n) = B\<cdot>b" by (metis Value.dist_les(2) Value.exhaust Value.inverts(2) below_bottom_iff discrete_cpo) } hence Y': "\<And> i. Y (i + n) = B\<cdot>b" by metis have "Y = (\<lambda>m. if m < n then \<bottom> else B\<cdot>b)" using \<open>\<forall>m. _\<close> Y' by (metis add_diff_inverse add.commute) thus ?thesis by (rule that(2)) qed qed end
/- Copyright (c) 2020 Heather Macbeth, Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Patrick Massot -/ import group_theory.subgroup import algebra.archimedean /-! # Archimedean groups This file proves a few facts about ordered groups which satisfy the `archimedean` property, that is: `class archimedean (α) [ordered_add_comm_monoid α] : Prop :=` `(arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y)` They are placed here in a separate file (rather than incorporated as a continuation of `algebra.archimedean`) because they rely on some imports from `group_theory` -- bundled subgroups in particular. The main result is `add_subgroup.cyclic_of_min`: a subgroup of a decidable archimedean abelian group is cyclic, if its set of positive elements has a minimal element. This result is used in this file to deduce `int.subgroup_cyclic`, proving that every subgroup of `ℤ` is cyclic. (There are several other methods one could use to prove this fact, including more purely algebraic methods, but none seem to exist in mathlib as of writing. The closest is `subgroup.is_cyclic`, but that has not been transferred to `add_subgroup`.) The result is also used in `topology.instances.real` as an ingredient in the classification of subgroups of `ℝ`. -/ variables {G : Type*} [linear_ordered_add_comm_group G] [archimedean G] open linear_ordered_add_comm_group /-- Given a subgroup `H` of a decidable linearly ordered archimedean abelian group `G`, if there exists a minimal element `a` of `H ∩ G_{>0}` then `H` is generated by `a`. -/ lemma add_subgroup.cyclic_of_min {H : add_subgroup G} {a : G} (ha : is_least {g : G | g ∈ H ∧ 0 < g} a) : H = add_subgroup.closure {a} := begin obtain ⟨⟨a_in, a_pos⟩, a_min⟩ := ha, refine le_antisymm _ (H.closure_le.mpr $ by simp [a_in]), intros g g_in, obtain ⟨k, nonneg, lt⟩ : ∃ k, 0 ≤ g - k • a ∧ g - k • a < a := exists_int_smul_near_of_pos' a_pos g, have h_zero : g - k • a = 0, { by_contra h, have h : a ≤ g - k • a, { refine a_min ⟨_, _⟩, { exact add_subgroup.sub_mem H g_in (add_subgroup.gsmul_mem H a_in k) }, { exact lt_of_le_of_ne nonneg (ne.symm h) } }, have h' : ¬ (a ≤ g - k • a) := not_le.mpr lt, contradiction }, simp [sub_eq_zero.mp h_zero, add_subgroup.mem_closure_singleton], end /-- Every subgroup of `ℤ` is cyclic. -/ lemma int.subgroup_cyclic (H : add_subgroup ℤ) : ∃ a, H = add_subgroup.closure {a} := begin cases add_subgroup.bot_or_exists_ne_zero H with h h, { use 0, rw h, exact add_subgroup.closure_singleton_zero.symm }, let s := {g : ℤ | g ∈ H ∧ 0 < g}, have h_bdd : ∀ g ∈ s, (0 : ℤ) ≤ g := λ _ h, le_of_lt h.2, obtain ⟨g₀, g₀_in, g₀_ne⟩ := h, obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℤ, g₁ ∈ H ∧ 0 < g₁, { cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀, { exact ⟨-g₀, H.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ }, { exact ⟨g₀, g₀_in, Hg₀⟩ } }, obtain ⟨a, ha, ha'⟩ := int.exists_least_of_bdd ⟨(0 : ℤ), h_bdd⟩ ⟨g₁, g₁_in, g₁_pos⟩, exact ⟨a, add_subgroup.cyclic_of_min ⟨ha, ha'⟩⟩, end
------------------------------------------------------------------------------ -- Distributive laws on a binary operation: Task B ------------------------------------------------------------------------------ {-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} module DistributiveLaws.TaskB-TopDownATP where open import DistributiveLaws.Base open import Common.FOL.Relation.Binary.EqReasoning ------------------------------------------------------------------------------ -- We found the longest chains of equalities from -- DistributiveLaws.TaskB-I which are prove by the ATPs, following a -- top-down approach. prop₂ : ∀ u x y z → (x · y · (z · u)) · (( x · y · ( z · u)) · (x · z · (y · u))) ≡ x · z · (y · u) prop₂ u x y z = -- The numbering of the proof step justifications are associated with -- the numbers used in DistributiveLaws.TaskB-I. xy·zu · (xy·zu · xz·yu) ≡⟨ j₁₋₅ ⟩ xy·zu · (xz · xu·yu · (y·zu · xz·yu)) ≡⟨ j₅₋₉ ⟩ xy·zu · (xz · xyu · (yxz · yu)) ≡⟨ j₉₋₁₄ ⟩ xz · xyu · (yz · xyu) · (xz · xyu · (y·xu · z·yu)) ≡⟨ j₁₄₋₂₀ ⟩ xz · xyu · (y·xu · (y·yu · z·yu) · (z · xu·yu · (y·xu · z·yu))) ≡⟨ j₂₀₋₂₃ ⟩ xz · xyu · (y · xu·zu · (z · xu·yu · (y·xu · z·yu))) ≡⟨ j₂₃₋₂₅ ⟩ (xz · xyu) · (y · xu·zu · (z·xu · y·xu · z·yu)) ≡⟨ j₂₅₋₃₀ ⟩ xz · xyu · (y·zy · xzu) ≡⟨ j₃₀₋₃₅ ⟩ xz·yu ∎ where -- Two variables abbreviations xz = x · z yu = y · u yz = y · z {-# ATP definitions xz yu yz #-} -- Three variables abbreviations xyu = x · y · u xyz = x · y · z xzu = x · z · u yxz = y · x · z {-# ATP definitions xyu xyz xzu yxz #-} y·xu = y · (x · u) y·yu = y · (y · u) y·zu = y · (z · u) y·zy = y · (z · y) {-# ATP definitions y·xu y·yu y·zu y·zy #-} z·xu = z · (x · u) z·yu = z · (y · u) {-# ATP definitions z·xu z·yu #-} -- Four variables abbreviations xu·yu = x · u · (y · u) xu·zu = x · u · (z · u) {-# ATP definitions xu·yu xu·zu #-} xy·zu = x · y · (z · u) {-# ATP definition xy·zu #-} xz·yu = x · z · (y · u) {-# ATP definition xz·yu #-} -- Steps justifications postulate j₁₋₅ : xy·zu · (xy·zu · xz·yu) ≡ xy·zu · (xz · xu·yu · (y·zu · xz·yu)) {-# ATP prove j₁₋₅ #-} postulate j₅₋₉ : xy·zu · (xz · xu·yu · (y·zu · xz·yu)) ≡ xy·zu · (xz · xyu · (yxz · yu)) {-# ATP prove j₅₋₉ #-} postulate j₉₋₁₄ : xy·zu · (xz · xyu · (yxz · yu)) ≡ xz · xyu · (yz · xyu) · (xz · xyu · (y·xu · z·yu)) {-# ATP prove j₉₋₁₄ #-} postulate j₁₄₋₂₀ : xz · xyu · (yz · xyu) · (xz · xyu · (y·xu · z·yu)) ≡ xz · xyu · (y·xu · (y·yu · z·yu) · (z · xu·yu · (y·xu · z·yu))) {-# ATP prove j₁₄₋₂₀ #-} postulate j₂₀₋₂₃ : xz · xyu · (y·xu · (y·yu · z·yu) · (z · xu·yu · (y·xu · z·yu))) ≡ xz · xyu · (y · xu·zu · (z · xu·yu · (y·xu · z·yu))) {-# ATP prove j₂₀₋₂₃ #-} postulate j₂₃₋₂₅ : xz · xyu · (y · xu·zu · (z · xu·yu · (y·xu · z·yu))) ≡ (xz · xyu) · (y · xu·zu · (z·xu · y·xu · z·yu)) {-# ATP prove j₂₃₋₂₅ #-} postulate j₂₅₋₃₀ : (xz · xyu) · (y · xu·zu · (z·xu · y·xu · z·yu)) ≡ xz · xyu · (y·zy · xzu) {-# ATP prove j₂₅₋₃₀ #-} postulate j₃₀₋₃₅ : xz · xyu · (y·zy · xzu) ≡ xz·yu {-# ATP prove j₃₀₋₃₅ #-}
# 5 Filters To filter signals on graphs, we need to define filters. They are represented in the toolbox by the [`pygsp.filters.Filter` class](https://pygsp.readthedocs.io/en/stable/reference/filters.html). Filters are usually defined in the spectral domain. Given the transfer function ```python import numpy as np import matplotlib.pyplot as plt from pygsp import graphs, filters, utils from additional_utils import get_approx_filter import time ``` ## 5.1 Heat diffusion The heat kernel $h(\lambda)$ is defined as: $$h_\tau(\lambda)=\exp^{-\tau\lambda}.$$ In fact, the graph heat equation reads (see section 2.5.5. of *Discrete Calculus* (by Grady and Polimeni)): $$\frac{d\mathbf{x}}{dt}+\mathbf{Lx} = \mathbf{0}.$$ In the Fourier space, this translates in: $$\frac{d\hat{\mathbf{x}}}{dt}+\mathbf{\Lambda}\hat{\mathbf{x}} = \mathbf{0},$$ where $\hat{\mathbf{x}}=\mathbf{U}^\top\mathbf{x}$ is the Fourier transform of $\mathbf{x}$. This equation is easily solved in each dimension by the exponential with: $$\hat{\mathbf{x}} = \exp^{-t\mathbf{\Lambda}}\hat{\mathbf{x}_0}$$ where $\hat{x_0}$ is the initial signal at time $t=0$. Such that: $$\mathbf{x}(t) =\mathbf{U} \exp^{-t\mathbf{\Lambda}}\mathbf{U}^\top \mathbf{x}_0=\mathbf{U} h_t(\mathbf{\Lambda})\mathbf{U}^\top \mathbf{x}_0.$$ ```python G1 = graphs.Sensor(seed=42) G1.compute_fourier_basis() G2 = graphs.Ring(N=100) G2.compute_fourier_basis() G2.set_coordinates('line1D') TAUS = [0, 5, 100] DELTA = 10 fig, axes = plt.subplots(len(TAUS), 3, figsize=(15, 6)) for i, tau in enumerate(TAUS): g1 = filters.Heat(G1, tau) g2 = filters.Heat(G2, tau) y = g1.localize(DELTA).squeeze() G1.plot_signal(y, ax=axes[i, 0]) axes[i, 0].set_axis_off() axes[i, 0].text(0, -0.2, '$y^T L y = {:.2f}$'.format(y.T @ G1.L @ y)) G2.plot_signal(g2.localize(G2.N//2), ax=axes[i, 2]) g1.plot(ax=axes[i, 1]) axes[i, 1].set_xlabel('') axes[i, 1].set_ylabel('') text = r'$\hat{{g}}(\lambda) = \exp \left( \frac{{-{{{}}} \lambda}}{{\lambda_{{max}}}} \right)$'.format(tau) axes[i, 1].text(6, 0.5, text, fontsize=15) axes[0, 0].set_title('$y = \hat{{g}}(L) \delta_{{{}}}$: localized on sensor'.format(DELTA)) axes[0, 1].set_title('$\hat{g}(\lambda)$: filter defined in the spectral domain') axes[0, 2].set_title('$y = \hat{{g}}(L) \delta_{{{}}}$: localized on ring graph'.format(G2.N//2)) axes[-1, 1].set_xlabel("$\lambda$: laplacian's eigenvalues / graph frequencies") ``` ## 5.2 Exercise Solve the following problem using a graph filter: $$\mathbf{x}^* = \operatorname*{arg\,min}_{\mathbf{x} \in \mathbb{R}^N} \|\mathbf{y} - \mathbf{x}\|_2^2 + \alpha \mathbf{x}^\intercal \mathbf{L} \mathbf{x},$$ where $y$ is the observed signal, $\alpha$ is an hyper-parameter which controls the trade-off between the data fidelity term and the smoothness prior. ```python # your code here ``` ## 5.3 Example of denoising Let's define a low-pass filter $$g(\lambda) = \frac{1}{1+\tau\lambda}$$ Given a noisy version of a smooth signal $x_\text{noisy}$, one can denoise it with the low-pass filter $g$: $$ x_\text{denoised} = \mathbf{U}g(\mathbf{\Lambda})\mathbf{U}^\top x_{\text{noisy}}$$ ```python # the graph: G = graphs.Logo() G.compute_fourier_basis() # the filter: tau = 1 def g(x): return 1. / (1. + tau * x) g = filters.Filter(G, g) # the noisy signal: x = np.zeros(G.N) x[G.info['idx_g']-1] = -1 x[G.info['idx_s']-1] = 0 x[G.info['idx_p']-1] = 1 rs = np.random.RandomState(42) x_noisy = x + rs.uniform(-1, 1, size=G.N) # the denoised signal: x_denoised = g.filter(x_noisy, method='exact') # and... plot: fig, axes = plt.subplots(1, 2, figsize=(10, 3)) G.plot_signal(x_noisy, vertex_size=30, ax=axes[0]) _ = axes[0].set_title('Noisy signal') axes[0].set_axis_off() G.plot_signal(x_denoised, vertex_size=30, ax=axes[1]) _ = axes[1].set_title('Cleaned signal') axes[1].set_axis_off() fig.tight_layout() ``` ## 5.4 Polynomial approximation Let us approximate the filter $$g(x) = \frac{1}{1+x}$$ on the interval $[0,\lambda_N]$ by a Chebychev polynomial of order $m$: $$g(x) \simeq \sum_{k=0}^m \alpha_k x^k=p(x),$$ such that the exact filtering can be approximated by a polynomial in $\mathbf{L}$: \begin{align} x_{\text{filtered}}&=\mathbf{U}g(\mathbf{\Lambda})\mathbf{U}^\top x\\ &\simeq \mathbf{U}p(\mathbf{\Lambda})\mathbf{U}^\top x\\ &=\mathbf{U}\sum_{k=0}^m \alpha_k \mathbf{\Lambda}^k\mathbf{U}^\top x\\ &=\sum_{k=0}^m \alpha_k \mathbf{L}^k x \end{align} Note that computing $\sum_{k=0}^m \alpha_k \mathbf{L}^k x$ takes only $m$ matrix-vector multiplication and costs thus $\mathcal{O}(m|E|)$ with $|E|$ the number of edges of the graph (compared to the $\mathcal{O}(N^3)$ necessary operations just to diagonalize $\mathbf{L}$ for the exact computation!) ```python m=2 ``` ```python g = lambda x: 1 / (1 + x) filt_g = filters.Filter(G, g) c = filters.approximations.compute_cheby_coeff(filt_g, m=m) ``` ```python filt_approx = get_approx_filter(c) x = np.arange(0, G.lmax, (G.lmax) / 1000) plt.figure() plt.plot(x, g(x)) plt.hold plt.plot(x, np.squeeze(filt_approx((x-(G.lmax/2)) / (G.lmax/2)))) plt.legend(['original filter', 'polynomial approximation']) ``` ```python start_time = time.time() G.compute_fourier_basis(recompute = True) #just to measure time x_denoised_exact = filt_g.filter(x_noisy, method='exact') time_exact_filter = time.time() - start_time start_time = time.time() G.estimate_lmax(recompute = True) #just to measure time x_denoised_cheby = filt_g.filter(x_noisy, method='chebyshev', order=m) time_cheby_filter = time.time() - start_time ``` ```python fig, axes = plt.subplots(1, 2, figsize=(10, 3)) G.plot_signal(x_denoised_exact, vertex_size=30, ax=axes[0]) _ = axes[0].set_title('Exact denoising') axes[0].set_axis_off() G.plot_signal(x_denoised_cheby, vertex_size=30, ax=axes[1]) _ = axes[1].set_title('Chebyshev approx') axes[1].set_axis_off() fig.tight_layout() ``` ```python print('The max error is ' + str(np.max(np.abs(x_denoised_exact-x_denoised_cheby)))) print('The mean energy of the error is ' + str((np.sum((x_denoised_exact - x_denoised_cheby)**2)/G.N))) print('The computation time for exact filtering was ' + str(time_exact_filter)) print('The computation time for approx filtering was ' + str(time_cheby_filter)) ``` ### Exercise: Precision-Efficiency trade-off of the polynomial approximation Illustrate the precision vs computation time trade-off of the Chebyshev polynomial approximation, as the order of the polynomial changes. How about with the ideal low-pass```g = lambda x: x <= cut_off_freq```? ## 5.5 Spectral Graph Wavelets Given a (smooth-enough) bandpass filter $g(u)$, a wavelet centered on node $i$ at scale $s\geq0$ reads: $$\mathbf{\psi}_{s,i} = \mathbf{U}g(s\mathbf{\Lambda})\mathbf{U}^\top \mathbf{\delta}_i\in\mathbb{R}^{N},$$ where $\mathbf{\delta}_i\in\mathbb{R}^N$ is the Dirac centered on node $i$: $\mathbf{\delta}_i(i)=1$ and $0$ elsewhere. See the [seminal paper](https://hal.inria.fr/file/index/docid/541855/filename/hammond-vandergheynst-gribonval-acha-2009r.pdf) by Hammond et al. for details on spectral graph wavelets. Given a graph signal $\mathbf{x}$, the wavelet coefficient at node $i$ and scale $s$, denoted by $W_{s,i}(\mathbf{x})$, is the projection of the signal on $\mathbf{\psi}_{s,i}$: $$W_{s,i}(\mathbf{x}) = \mathbf{\psi}_{s,i}^\top\mathbf{x}\in\mathbb{R}.$$ Let us consider $\mathcal{S}=(s_1, s_2, \ldots, s_m)$ a set of $m$ scales. The collection of $m$ filters $\{g(s_1 u), g(s_2 u), \ldots, g(s_m u)\}$ is called a *filterbank*. Consider all wavelet coefficients $\{W_{s,i}\}_{s\in\mathcal{S},~i\in\mathcal{V}}$ of a graph signal $\mathbf{x}$. Can we recover perfectly $\mathbf{x}$ from its wavelet coefficients? The answer is "no" because wavelet filters are necessarily bandpass (thus $g(0)=0$) and constant signals are in the null space of the transform! Let us add a low-pass $h(u)$ to the filterbank for instance (the exact form does not have a huge importance): $$h(u)=\exp^{-u^4}.$$ Do the coefficients extracted from the combination of filters $(h(u), g(s_1 u), g(s_2 u), \ldots, g(s_m u))$ enough for perfect reconstruction of any $\mathbb{R}^N$ signal? **Theorem.** (see Theorem 5.6 of [Hammond et al.](https://hal.inria.fr/file/index/docid/541855/filename/hammond-vandergheynst-gribonval-acha-2009r.pdf)) Perfect recovery is possible iff $$\text{min}_{u\in\{\lambda_0, \ldots, \lambda_{N-1}\}} \quad h(u)^2 + \sum_{s\in\mathcal{S}} g(su)^2 > 0.$$ ```python G = graphs.Sensor(seed=42) G.compute_fourier_basis() ``` ```python # The mexican hat bandpass example mex_hat = lambda x: x * np.exp(-x) plt.plot(np.arange(0,10,0.01), mex_hat(np.arange(0,10,0.01))) ``` ```python m=5 g = filters.MexicanHat(G, Nf = m + 1, lpfactor = 50) ``` ```python eval_x = np.arange(0, G.lmax, G.lmax/1000) y = g.evaluate(eval_x) ``` ```python plt.plot(eval_x, y.T) plt.plot(G.e, g.evaluate(G.e).T, '+') plt.xlabel('$\lambda$') plt.ylabel('filters') plt.figure() plt.plot(G.e, np.sum(np.power(g.evaluate(G.e).T,2),1), '+') plt.ylim([0, 1]) ``` As we see on the last graph, we have : $$\text{min}_{u\in\{\lambda_0, \ldots, \lambda_{N-1}\}} \quad h(u)^2 + \sum_{s\in\mathcal{S}} g(su)^2 > 0.$$ Perfect reconstruction of all $\mathbb{R}^N$ signals is thus possible! The frame is not tight though. **Plot a few wavelets** ```python node = 10 delta_node = np.zeros((G.N,)) delta_node[node] = 1 wavelet_at_node = g.filter(delta_node) wavelet_at_node.shape ``` ```python G.plot_signal(delta_node) # the delta signal centered on 'node' G.plot_signal(wavelet_at_node[:,5]) # the wavelet centered on 'node' at very small scale (large value of s) G.plot_signal(wavelet_at_node[:,4]) # the wavelet at the same node but at slightly larger scale (smaller value of s) G.plot_signal(wavelet_at_node[:,3]) # etc. G.plot_signal(wavelet_at_node[:,2]) G.plot_signal(wavelet_at_node[:,1]) ``` **Example** Plot some wavelets in the SBM model. Observe how wavelets first "diffuse" within the blocks before exploring the whole network **Filterbanks for compression :** We are going to use the filterbanks 'Itersine' (which forms a tight frame). Some methods exist to 'tighten' the frame formed by the 'MexicanHat' for instance, but we will not look into this here. ```python m=5 g = filters.Itersine(G, Nf = m + 1) eval_x = np.arange(0, G.lmax, G.lmax/1000) y = g.evaluate(eval_x) plt.plot(eval_x, y.T) plt.plot(G.e, g.evaluate(G.e).T, '+') plt.xlabel('$\lambda$') plt.ylabel('filters') plt.figure() plt.plot(G.e, np.sum(np.power(g.evaluate(G.e).T,2),1), '+') plt.ylim([0, 1]) ``` ```python comp_level = 0.9 #a scalar between 0 and 1, 0 meaning no compression ``` ```python x_toy_orig = - np.ones((G.N,)) ind_left = G.coords[:,0] < 0.5 x_toy_orig[ind_left] = 1 x_toy_noisy = x_toy_orig + 0.2 * np.random.randn(G.N) G.plot_signal(x_toy_noisy) ``` ```python W_coeffs = g.filter(x_toy_noisy, method='exact') n_coef = np.prod(W_coeffs.shape) # total number of scalars encoding the signal in the wavelet space n_coef_comp = np.ceil((1 - comp_level) * n_coef).astype(int) # authorized number of scalars at specified compression level # find the threshold under which we will set entries to 0: sorted_coefs = np.sort(np.abs(W_coeffs), axis=None) threshold = sorted_coefs[-n_coef_comp] # the thresholded wavelet transform: W_coeffs_th = W_coeffs.copy() W_coeffs_th[np.abs(W_coeffs) < threshold] = 0 ``` ```python x_toy_recovered = g.synthesize(W_coeffs_th, method='exact') G.plot_signal(x_toy_recovered) print(str(np.linalg.norm(x_toy_recovered-x_toy_noisy))) ``` **Exercise** Plot the error of reconstruction vs the compression rate. This is only one quick example of compression. Denoising may be done as well, etc. ```python ```
% works on TeX-Live 2015 \documentclass{beamer} \usepackage{tgheros} \usepackage[varqu, scaled]{inconsolata} %\usepackage{mylistings} \usepackage{csquotes} \usepackage{hyperref} \usepackage{xcolor} \usepackage{graphicx} \usepackage{siunitx} \usepackage{booktabs} %\usepackage{tikz} %\usepackage{tikz-uml} % \lstset{ % style=colored, % %belowskip=0pt % basicstyle=\ttfamily\small\color{darkgray}, % columns=[c]fixed, % gobble=4 % } % colors \providecolor{textgreen}{RGB}{59, 158, 72} \providecolor{textblue}{RGB}{15, 100, 255} \providecolor{textred}{RGB}{255, 51, 66} \usetheme[compress]{Singapore} \useinnertheme{circles} \setbeamercolor{structure}{fg=textblue} %\setbeamercolor{block body alerted}{bg=normal text.bg!90!black} \setbeamercolor{block body}{bg=normal text.bg!90!black} %\setbeamercolor{block body example}{bg=normal text.bg!90!black} %\setbeamercolor{block title alerted}{use={normal text,alerted text},fg=alerted text.fg!75!normal text.fg,bg=normal text.bg!75!black} \setbeamercolor{block title}{fg=black, bg=textblue!90} %\setbeamercolor{block title example}{use={normal text,example text},fg=example text.fg!75!normal text.fg,bg=normal text.bg!75!black} % smaller footnotes; see: http://tex.stackexchange.com/a/192652/46356 \setbeamertemplate{footnote}{% \tiny% \parindent 1em\noindent% \raggedright \hbox to 1.8em{\hfil\insertfootnotemark}\insertfootnotetext\par% }% \setlength\footnotesep{0pt} \author{Philipp Gabler} \title{Geometry} \date{18.\,11.\,2016} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{document} \beamertemplatenavigationsymbolsempty \section{Dataset} \begin{frame} \begin{columns} \begin{column}{0.7\textwidth} \small \begin{tabular}{lrr} \toprule & Facebook\footnotemark & TX roads\footnotemark \\ \midrule Vertices & 63731 & 1393383 \\ Edges (both undir.) & 817035 & 1921660 \\ Triangles & 3500542 & 82869 \\ Triangles per node & 164.780 & 0.178 \\ Mean degree & 25.640 & 2.758 \\ Density & 0.0004023 & 0.0000002 \\ Conn. components & 144 & 13890 \\ Mean component size & 442.576 & 100.315 \\ Global clustering coeff. & 0.1477 & 0.0602 \\ \bottomrule \end{tabular} \end{column} \begin{column}{0.3\textwidth} \includegraphics[width=\textwidth]{fig/texas-image} \end{column} \end{columns} \footnotetext[1]{\protect\url{http://konect.uni-koblenz.de/networks/facebook-wosn-links}} \footnotetext[2]{\protect\url{http://konect.uni-koblenz.de/networks/roadNet-TX}} \begin{block}{Question} A road network is topologically fundamentally different from a social one. How do different sampling strategies react to these differences? \end{block} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Experimental Setup} \begin{frame} Comparison of \textit{random walk} and \textit{forest fire} (see here\footnote{\protect\href{https://cs.stanford.edu/people/jure/pubs/sampling-kdd06.pdf}{Leskovec, J; Faloutsos, C. \enquote{Sampling from Large Graphs.} In: Proceedings of the 12th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, 631--636. ACM, 2006.}}), by analysing some graph measures on samples. \vspace{-0.5cm} \begin{columns} \begin{column}[t]{0.5\textwidth} \begin{block}{Texas} \centering \includegraphics[scale=0.3]{fig/texas_rw}\\ \includegraphics[scale=0.3]{fig/texas_ff} \end{block} \end{column} \begin{column}[t]{0.5\textwidth} \begin{block}{Facebook} \centering \includegraphics[scale=0.3]{fig/facebook_rw}\\ \includegraphics[scale=0.3]{fig/facebook_ff} \end{block} \end{column} \end{columns} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Results} \begin{frame} Some meaningful measures by sampling 100 times from both data sets, using 10~\% of the network\footnote{Code, data, and statistics: \protect\url{https://github.com/phipsgabler/netsci-01}}. \vspace{1ex} \begin{columns} \begin{column}[t]{0.4\textwidth} \includegraphics[width=\textwidth]{fig/sampled-ok}\\ Magnitude mostly preserved \end{column} \begin{column}[t]{0.6\textwidth} \includegraphics[width=\textwidth]{fig/sampled-off}\\ Magnitudes far off, but order still mostly preserved \end{column} \end{columns} \end{frame} % @misc{snapnets, % author = {Jure Leskovec and Andrej Krevl}, % title = {{SNAP Datasets}: {Stanford} Large Network Dataset Collection}, % howpublished = {\url{http://snap.stanford.edu/data}}, % month = jun, % year = 2014 % } \end{document}
lemma Im_complex_of_real [simp]: "Im (complex_of_real z) = 0"
From sflib Require Import sflib. From Paco Require Import paco. Require Import Coq.Classes.RelationClasses. Require Import Program. From Fairness Require Import Axioms. From Fairness Require Export ITreeLib FairBeh FairSim NatStructsLarge. From Fairness Require Import pind PCMLarge World WFLibLarge ThreadsURA. From Fairness Require Import Mod ModSimYOrd ModSimStid. Set Implicit Arguments. Section PROOF. Context `{M: URA.t}. Variable state_src: Type. Variable state_tgt: Type. Variable ident_src: ID. Variable _ident_tgt: ID. Let ident_tgt := sum_tid _ident_tgt. Variable wf_src: WF. Variable wf_tgt: WF. Hypothesis wf_tgt_inhabited: inhabited wf_tgt.(T). Hypothesis wf_tgt_open: forall (o0: wf_tgt.(T)), exists o1, wf_tgt.(lt) o0 o1. Let srcE := ((@eventE ident_src +' cE) +' sE state_src). Let tgtE := ((@eventE _ident_tgt +' cE) +' sE state_tgt). Let shared := (TIdSet.t * (@imap ident_src wf_src) * (@imap ident_tgt wf_tgt) * state_src * state_tgt)%type. Let shared_rel: Type := shared -> Prop. Variable I: shared -> URA.car -> Prop. Variable wf_stt: Type -> Type -> WF. Variable wf_stt0: forall R0 R1, (wf_stt R0 R1).(T). Let ident_src2 := sum_tid ident_src. Let wf_src_th {R0 R1}: WF := clos_trans_WF (prod_WF (prod_WF (wf_stt R0 R1) wf_tgt) (nmo_wf (wf_stt R0 R1))). Let wf_src2 {R0 R1}: WF := sum_WF (@wf_src_th R0 R1) wf_src. Let srcE2 := ((@eventE ident_src2 +' cE) +' sE state_src). Let shared2 {R0 R1} := (TIdSet.t * (@imap ident_src2 (@wf_src2 R0 R1)) * (@imap ident_tgt wf_tgt) * state_src * state_tgt)%type. Let shared2_rel {R0 R1}: Type := (@shared2 R0 R1) -> Prop. Let M2 {R0 R1}: URA.t := URA.prod (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)) M. Definition shared_thsRA {R0 R1} (ost: NatMap.t (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)) : @thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T) := (fun tid => match NatMap.find tid ost with | Some osot => ae_black osot | None => ae_black (wf_stt0 R0 R1, wf_stt0 R0 R1) ⋅ ae_white (wf_stt0 R0 R1, wf_stt0 R0 R1) end). Definition Is {R0 R1}: (TIdSet.t * (@imap thread_id (@wf_src_th R0 R1)) * (@imap ident_tgt wf_tgt))%type -> (@URA.car (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T))) -> Prop := fun '(ths, im_src, im_tgt) ths_r => exists (ost: NatMap.t (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)), (<<WFOST: nm_wf_pair ths ost>>) /\ (<<TRES: ths_r = shared_thsRA ost>>) /\ (<<IMSRC: forall tid (IN: NatMap.In tid ths) os ot (FIND: NatMap.find tid ost = Some (os, ot)), wf_src_th.(lt) ((ot, im_tgt (inl tid)), nm_proj_v1 ost) (im_src tid)>>). Definition I2 {R0 R1}: (@shared2 R0 R1) -> (@URA.car (@M2 R0 R1)) -> Prop := fun '(ths, im_src, im_tgt, st_src, st_tgt) '(ths_r, r) => exists im_src_th im_src_us, (<<ICOMB: im_src = imap_comb im_src_th im_src_us>>) /\ (<<INV: I (ths, im_src_us, im_tgt, st_src, st_tgt) r>>) /\ (<<INVS: Is (ths, im_src_th, im_tgt) ths_r>>). Lemma shared_thsRA_th_has_wf_find tid R0 R1 ost os ot (ctx_r: (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T))) (VALS: URA.wf ((shared_thsRA ost) ⋅ (th_has tid (os, ot)) ⋅ ctx_r)) : NatMap.find tid ost = Some (os, ot). Proof. ur in VALS. specialize (VALS tid). eapply URA.wf_mon in VALS. unfold shared_thsRA in VALS. rewrite th_has_hit in VALS. des_ifs. - ur in VALS. des. rewrite URA.unit_idl in VALS. unfold URA.extends in VALS. des. ur in VALS. des_ifs. - rewrite <- URA.add_assoc in VALS. rewrite URA.add_comm in VALS. eapply URA.wf_mon in VALS. ur in VALS. ur in VALS. ss. Qed. Lemma shared_thsRA_th_has_wf_update tid R0 R1 ost os ot (ctx_r: (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T))) (VALS: URA.wf ((shared_thsRA ost) ⋅ (th_has tid (os, ot)) ⋅ ctx_r)) os1 ot1 : URA.wf ((shared_thsRA (NatMap.add tid (os1, ot1) ost)) ⋅ (th_has tid (os1, ot1)) ⋅ ctx_r). Proof. hexploit shared_thsRA_th_has_wf_find; eauto. intro FIND. ur. ur in VALS. i. specialize (VALS k). destruct (tid_dec k tid); clarify. - rewrite th_has_hit in *. unfold shared_thsRA in *. rewrite nm_find_add_eq. rewrite FIND in VALS. ur. ur in VALS. des_ifs. des. split. + rewrite URA.unit_idl in VALS. unfold URA.extends in *. des. r_solve. ss. exists ctx. ur in VALS. ur. des_ifs. + ur. ss. - rewrite th_has_miss in *; auto. rewrite URA.unit_id in VALS. r_solve. unfold shared_thsRA in *. rewrite nm_find_add_neq; auto. Qed. Lemma shared_thsRA_th_has_wf_wf_pair tid R0 R1 (ths: TIdSet.t) ost os ot (ctx_r: (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T))) (VALS: URA.wf ((shared_thsRA ost) ⋅ (th_has tid (os, ot)) ⋅ ctx_r)) (WFP: nm_wf_pair ths ost) os1 ot1 : nm_wf_pair ths (NatMap.add tid (os1, ot1) ost). Proof. replace ths with (NatMap.add tid tt ths). apply nm_wf_pair_add; auto. apply nm_eq_is_equal. ii. destruct (tid_dec y tid); clarify. 2:{ rewrite nm_find_add_neq; auto. } rewrite nm_find_add_eq. symmetry. destruct (NatMap.find tid ths) eqn:FIND; ss. destruct u; auto. hexploit shared_thsRA_th_has_wf_find. eapply VALS. i. hexploit nm_wf_pair_find_cases; eauto. i; des. eapply H0 in FIND. ss. clarify. Qed. Lemma local_RR_impl tid R0 R1 (RR: R0 -> R1 -> Prop) ths (im_src: @imap ident_src2 (@wf_src2 R0 R1)) im_src_th im_src_us (ICOMB: im_src = imap_comb im_src_th im_src_us) (im_tgt: @imap ident_tgt wf_tgt) st_src st_tgt r_ctx r0 r1 (LRR: ModSimYOrd.local_RR I RR tid r0 r1 r_ctx (ths, im_src_us, im_tgt, st_src, st_tgt)) (ths_r ctx_r: (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T))) os ot (INVS: Is (ths, im_src_th, im_tgt) ths_r) (VALS: URA.wf (ths_r ⋅ (th_has tid (os, ot)) ⋅ ctx_r)) : ModSimStid.local_RR I2 RR tid r0 r1 (ctx_r, r_ctx) (ths, im_src, im_tgt, st_src, st_tgt). Proof. unfold ModSimYOrd.local_RR in LRR. des. unfold local_RR. unfold Is in INVS. des. set (ost':=NatMap.remove tid ost). clarify. esplits; eauto. - instantiate (1:=(ε, r_own)). instantiate (1:=(shared_thsRA ost', r_shared)). ur. split; auto. hexploit shared_thsRA_th_has_wf_find; eauto. intro FIND. r_solve. ur. ur in VALS. i. specialize (VALS k). destruct (tid_dec k tid); clarify. + rewrite th_has_hit in VALS. unfold shared_thsRA in *. subst ost'. rewrite nm_find_rm_eq. rewrite FIND in VALS. ur. ur in VALS. des_ifs. des. split. * rewrite URA.unit_idl in VALS. unfold URA.extends in *. des. r_solve. ss. exists ctx. ur in VALS. ur. des_ifs. * ur. ss. + rewrite th_has_miss in VALS; auto. rewrite URA.unit_id in VALS. unfold shared_thsRA in *. subst ost'. rewrite nm_find_rm_neq; auto. - unfold I2. esplits; eauto. unfold Is. exists ost'. splits; auto. { subst ost'. eapply nm_wf_pair_rm; auto. } i. specialize (IMSRC tid0). destruct (tid_dec tid0 tid); clarify. { exfalso. apply NatMap.remove_1 in IN; auto. } hexploit IMSRC; clear IMSRC. { eapply NatMapP.F.remove_neq_in_iff; eauto. } { subst ost'. rewrite nm_find_rm_neq in FIND; eauto. } i. ss. eapply clos_trans_n1_trans. 2: eapply H. econs 1. econs 2. auto. subst ost'. econs. instantiate (1:=tid). { unfold nm_proj_v1. rewrite <- nm_map_rm_comm_eq. rewrite nm_find_rm_eq. assert (FINDOST: NatMap.find tid ost = Some (os, ot)). { eapply shared_thsRA_th_has_wf_find. eapply VALS. } rewrite NatMapP.F.map_o. rewrite FINDOST. ss. econs. } { i. unfold nm_proj_v1. rewrite <- nm_map_rm_comm_eq. rewrite nm_find_rm_neq; auto. } Qed. Let St: wf_tgt.(T) -> wf_tgt.(T) := fun o0 => @epsilon _ wf_tgt_inhabited (fun o1 => wf_tgt.(lt) o0 o1). Let lt_succ_diag_r_tgt: forall (t: wf_tgt.(T)), wf_tgt.(lt) t (St t). Proof. i. unfold St. hexploit (@epsilon_spec _ wf_tgt_inhabited (fun o1 => wf_tgt.(lt) t o1)); eauto. Qed. Lemma yord_implies_stid tid R0 R1 (RR: R0 -> R1 -> Prop) ths (im_src: @imap ident_src2 (@wf_src2 R0 R1)) im_src_th im_src_us (ICOMB: im_src = imap_comb im_src_th im_src_us) (im_tgt: @imap ident_tgt wf_tgt) st_src st_tgt ps pt r_ctx src tgt os ot (LSIM: ModSimYOrd.lsim I wf_stt tid (ModSimYOrd.local_RR I RR tid) ps pt r_ctx (os, src) (ot, tgt) (ths, im_src_us, im_tgt, st_src, st_tgt)) (ths_r ctx_r: (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T))) (INVS: Is (ths, im_src_th, im_tgt) ths_r) (VALS: URA.wf (ths_r ⋅ (th_has tid (os, ot)) ⋅ ctx_r)) : ModSimStid.lsim I2 tid (ModSimStid.local_RR I2 RR tid) ps pt (ctx_r, r_ctx) src tgt (ths, im_src, im_tgt, st_src, st_tgt). Proof. revert_until R1. pcofix CIH; i. match type of LSIM with ModSimYOrd.lsim _ _ _ ?_LRR0 _ _ _ ?_osrc ?_otgt ?_shr => remember _LRR0 as LRR0 in LSIM; remember _osrc as osrc; remember _otgt as otgt; remember _shr as shr end. move LSIM before CIH. punfold LSIM. revert_until LSIM. revert LRR0 ps pt r_ctx osrc otgt shr LSIM. pinduction 7. i. clear LE. clarify. rename x1 into ps, x2 into pt, x3 into r_ctx, PR into LSIM. eapply pind9_unfold in LSIM; eauto with paco. rename INVS into INVS0; assert (INVS:Is (ths, im_src_th, im_tgt) ths_r). { auto. } clear INVS0. inv LSIM. { pfold. eapply pind9_fold. econs 1. eapply local_RR_impl; eauto. } { pfold. eapply pind9_fold. econs 2; eauto. split; [|ss]. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND. { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. } all: eauto. } { pfold. eapply pind9_fold. econs 3; eauto. des. exists x. split; [|ss]. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND. { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. } all: eauto. } { pfold. eapply pind9_fold. econs 4; eauto. split; [|ss]. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND. { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. } all: eauto. } { pfold. eapply pind9_fold. econs 5; eauto. split; [|ss]. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND. { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. } all: eauto. } { pfold. eapply pind9_fold. econs 6; eauto. } { pfold. eapply pind9_fold. econs 7; eauto. des. exists (fun idx => match idx with | inl t => inl (im_src_th t) | inr i => inr (im_src1 i) end). esplits. { clear - FAIR. ii. destruct i; ss. specialize (FAIR i). unfold prism_fmap in *; ss. des_ifs. - econs 2. auto. - rewrite FAIR. auto. } split; [|ss]. destruct LSIM as [LSIM IND]. eapply IH in IND. punfold IND. { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. } all: ss; eauto. } { pfold. eapply pind9_fold. econs 8; eauto. split; [|ss]. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND. { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. } all: eauto. } { pfold. eapply pind9_fold. econs 9; eauto. i. specialize (LSIM0 x). split; [|ss]. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND. { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. } all: eauto. } { pfold. eapply pind9_fold. econs 10; eauto. split; [|ss]. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND. { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. } all: eauto. } { pfold. eapply pind9_fold. econs 11; eauto. split; [|ss]. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND. { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. } all: eauto. } { pfold. eapply pind9_fold. econs 12; eauto. i. specialize (LSIM0 _ FAIR). split; [|ss]. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND. { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. } all: eauto. clear - FAIR INVS. unfold Is in INVS. des. esplits; eauto. i. hexploit IMSRC; eauto; i. replace (im_tgt1 (inl tid)) with (im_tgt (inl tid)); auto. clear - FAIR. specialize (FAIR (inl tid)). ss. } { pfold. eapply pind9_fold. econs 13; eauto. i. specialize (LSIM0 ret). pclearbot. right. eapply CIH; eauto. } { pfold. eapply pind9_fold. econs 14. } { pfold. eapply pind9_fold. econs 15; eauto. des. unfold Is in INVS. des. subst. set (ost':= NatMap.add tid (os1, ot1) ost). assert (WFOST': nm_wf_pair ths ost'). { eapply shared_thsRA_th_has_wf_wf_pair; eauto. } exists (fun idx => match idx with | inl t => if (NatMapP.F.In_dec ths t) then match (NatMap.find t ost') with | None => inl (im_src_th t) | Some (_, ot) => inl ((ot, im_tgt (inl t)), nm_proj_v1 ost) end else inl (im_src_th t) | inr i => inr (im_src_us i) end). splits. { clear - LT IMSRC VALS WFOST WFOST'. ii. unfold prism_fmap in *; ss. destruct i; ss. destruct (tids_fmap tid ths n) eqn:FM; auto. - unfold tids_fmap in FM. destruct (Nat.eq_dec n tid) eqn:EQ; ss. destruct (NatMapP.F.In_dec ths n) eqn:INDEC; ss. des_ifs. 2:{ exfalso. eapply NatMapP.F.in_find_iff; eauto. apply nm_wf_pair_sym in WFOST'. eapply nm_wf_pair_find_cases in WFOST'. des. eapply WFOST' in Heq. auto. } hexploit IMSRC; clear IMSRC. 3:{ instantiate (1:=n). instantiate (1:=t0). i. econs 1. auto. } auto. subst ost'. rewrite nm_find_add_neq in Heq; eauto. - unfold tids_fmap in FM. destruct (Nat.eq_dec n tid) eqn:EQ; ss. destruct (NatMapP.F.In_dec ths n) eqn:INDEC; ss. } split; [|ss]. destruct LSIM as [LSIM IND]. eapply IH in IND. punfold IND. { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. } 6: instantiate (2:=shared_thsRA ost'). all: eauto. - instantiate (1:= fun t => if NatMapP.F.In_dec ths t then match NatMap.find t ost' with | Some (_, ot0) => (ot0, im_tgt (inl t), nm_proj_v1 ost) | None => (im_src_th t) end else (im_src_th t)). unfold imap_comb. clear. extensionality idx. des_ifs. - exists ost'; splits; auto. clear - LT IMSRC VALS WFOST WFOST'. i. econs 1. des_ifs. ss. econs 2; auto. econs. instantiate (1:=tid). + unfold nm_proj_v1. rewrite !NatMapP.F.map_o. replace (NatMap.find tid ost) with (Some (os, ot)). subst ost'. rewrite nm_find_add_eq. ss. econs. auto. symmetry. eapply shared_thsRA_th_has_wf_find; eauto. + i. unfold nm_proj_v1. rewrite !NatMapP.F.map_o. subst ost'. rewrite nm_find_add_neq; auto. - eapply shared_thsRA_th_has_wf_update; eauto. } { pfold. eapply pind9_fold. econs 16; eauto. instantiate (1:=(ths_r, r_shared)). { unfold I2. esplits; eauto. } instantiate (1:=(tid |-> (os, ot) , r_own)). { ur. auto. } clear - LSIM0 IH; i. unfold I2 in INV. destruct r_shared1 as [shared_r r_shared], r_ctx1 as [ctx_r r_ctx]. ur in VALID. des. specialize (LSIM0 _ _ _ _ _ _ _ INV VALID0 _ TGT). des. unfold Is in INVS. des. subst. set (ost':= NatMap.add tid (os1, ot1) ost). clarify. assert (WFOST': nm_wf_pair ths1 ost'). { eapply shared_thsRA_th_has_wf_wf_pair; eauto. } split; [|ss]. destruct LSIM as [LSIM IND]. eapply IH in IND. punfold IND. { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. } all: eauto. instantiate (1:=shared_thsRA ost'). - exists ost'. splits; auto. i. specialize (IMSRC _ IN). unfold prism_fmap in *; ss. destruct (tid_dec tid0 tid); clarify. + hexploit IMSRC. eapply shared_thsRA_th_has_wf_find; eauto. i. subst ost'. rewrite nm_find_add_eq in FIND. clarify. eapply clos_trans_n1_trans. 2: eapply H. econs 1. econs 1. econs 1. auto. + subst ost'. rewrite nm_find_add_neq in FIND; auto. hexploit IMSRC. eauto. i. eapply clos_trans_n1_trans. 2: eapply H. econs 1. econs 1. econs 2; auto. clear - n IN TGT. specialize (TGT (inl tid0)). ss. unfold tids_fmap in TGT. des_ifs. - eapply shared_thsRA_th_has_wf_update; eauto. } { pfold. eapply pind9_fold. econs 17; eauto. instantiate (1:=(ths_r, r_shared)). { unfold I2. esplits; eauto. } instantiate (1:=(tid |-> (os, ot) , r_own)). { ur. auto. } revert LSIM0. clear_upto IH. i. unfold I2 in INV. destruct r_shared1 as [shared_r r_shared], r_ctx1 as [ctx_r r_ctx]. ur in VALID. des. specialize (LSIM0 _ _ _ _ _ _ _ INV VALID0 _ TGT). des. unfold Is in INVS. des. subst. set (ost':= NatMap.add tid (os1, ot1) ost). assert (WFOST': nm_wf_pair ths1 ost'). { eapply shared_thsRA_th_has_wf_wf_pair; eauto. } exists (fun idx => match idx with | inl t => if (tid_dec t tid) then inl ((ot1, St (im_tgt2 (inl t))), nm_proj_v1 ost) else if (NatMapP.F.In_dec ths1 t) then match (NatMap.find t ost') with | None => inl (im_src_th t) | Some (_, ot) => inl ((ot, im_tgt1 (inl t)), nm_proj_v1 ost) end else inl (im_src_th t) | inr i => inr (im_src_us i) end). splits. { clear - IMSRC VALID TGT WFOST WFOST'. ii. unfold prism_fmap in *; ss. destruct i; ss. destruct (tids_fmap tid ths1 n) eqn:FM; auto. - unfold tids_fmap in FM. destruct (Nat.eq_dec n tid) eqn:EQ; ss. destruct (NatMapP.F.In_dec ths1 n) eqn:INDEC; ss. des_ifs. 2:{ exfalso. eapply NatMapP.F.in_find_iff; eauto. apply nm_wf_pair_sym in WFOST'. eapply nm_wf_pair_find_cases in WFOST'. des. eapply WFOST' in Heq. auto. } hexploit IMSRC; clear IMSRC. 3:{ instantiate (1:=n). instantiate (1:=t0). i. econs 1. auto. } auto. subst ost'. rewrite nm_find_add_neq in Heq; eauto. - unfold tids_fmap in FM. destruct (Nat.eq_dec n tid) eqn:EQ; ss. destruct (NatMapP.F.In_dec ths1 n) eqn:INDEC; ss. des_ifs. } pclearbot. right. eapply CIH. 2:eauto. 3: instantiate (1:=shared_thsRA ost'). - instantiate (1:= fun t => if tid_dec t tid then (ot1, St (im_tgt2 (inl t)), nm_proj_v1 ost) else if NatMapP.F.In_dec ths1 t then match NatMap.find t ost' with | Some (_, ot0) => (ot0, im_tgt1 (inl t), nm_proj_v1 ost) | None => (im_src_th t) end else (im_src_th t)). unfold imap_comb. extensionality idx. des_ifs. - exists ost'; splits; auto. revert IMSRC VALID TGT WFOST WFOST'. clear_upto tid. i. subst. i. econs 1. des_ifs; ss. + subst ost'. rewrite nm_find_add_eq in FIND. clarify. econs 1. econs 2; auto. + unfold prism_fmap in *; ss. rewrite FIND in Heq. clarify. econs 1. econs 2; auto. clear - n IN TGT. specialize (TGT (inl tid0)). ss. unfold tids_fmap in TGT. des_ifs. + rewrite FIND in Heq. ss. - eapply shared_thsRA_th_has_wf_update; eauto. } { pfold. eapply pind9_fold. econs 18; eauto. pclearbot. right. eapply CIH; eauto. } Qed. Lemma init_src_inv tid R0 R1 ths (im_src1: @imap ident_src2 (@wf_src2 R0 R1)) im_src_th1 im_src_us (ICOMB: im_src1 = imap_comb im_src_th1 im_src_us) (im_tgt1 im_tgt2: @imap ident_tgt wf_tgt) (ths_r ctx_r: (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T))) os ot (INVS: Is (ths, im_src_th1, im_tgt1) ths_r) (VALS: URA.wf (ths_r ⋅ (th_has tid (os, ot)) ⋅ ctx_r)) (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths))) : exists im_src_th2, (<<SRC: fair_update im_src1 (imap_comb im_src_th2 im_src_us) (prism_fmap inlp (tids_fmap tid ths))>>) /\ (<<INVS: Is (ths, im_src_th2, im_tgt2) ths_r>>). Proof. unfold Is in INVS. des. clarify. exists (fun t => if (tid_dec t tid) then ((ot, St (im_tgt2 (inl t))), nm_proj_v1 ost) else if (NatMapP.F.In_dec ths t) then match (NatMap.find t ost) with | None => (im_src_th1 t) | Some (_, ot) => ((ot, im_tgt1 (inl t)), nm_proj_v1 ost) end else (im_src_th1 t)). splits. - ii. destruct i; ss. unfold tids_fmap, prism_fmap in *; ss. destruct (Nat.eq_dec n tid) eqn:EQT; clarify. destruct (NatMapP.F.In_dec ths n) eqn:INT; ss; clarify. 2:{ des_ifs; ss. } clear EQT INT. destruct (NatMap.find n ost) eqn:FIND. 2:{ exfalso. eapply NatMapP.F.in_find_iff in i. eapply nm_wf_pair_sym in WFOST. hexploit nm_wf_pair_find_cases; eauto. i. des. eapply H in FIND; clarify. } des_ifs. specialize (IMSRC _ i _ _ FIND). econs 1. eapply IMSRC. - exists ost. splits; auto. i. unfold prism_fmap in *; ss. des_ifs. + ss. hexploit shared_thsRA_th_has_wf_find. eapply VALS. intro FIND2. ss; rewrite FIND in FIND2; clarify. econs 1. econs 1. econs 2; auto. + ss. econs 1. econs 1. econs 2; auto. clear - n i TGT. specialize (TGT (inl tid0)). ss. unfold tids_fmap in TGT. des_ifs. Qed. End PROOF. Section MODSIM. Lemma yord_implies_stid_mod md_src md_tgt (MDSIM: ModSimYOrd.ModSim.mod_sim md_src md_tgt) : ModSimStid.ModSim.mod_sim md_src md_tgt. Proof. inv MDSIM. set (ident_src := Mod.ident md_src). set (_ident_tgt := Mod.ident md_tgt). set (state_src := Mod.state md_src). set (state_tgt := Mod.state md_tgt). set (srcE := ((@eventE ident_src +' cE) +' sE state_src)). set (tgtE := ((@eventE _ident_tgt +' cE) +' sE state_tgt)). set (ident_tgt := @ident_tgt _ident_tgt). set (shared := (TIdSet.t * (@imap ident_src wf_src) * (@imap ident_tgt wf_tgt) * state_src * state_tgt)%type). set (ident_src2 := sum_tid ident_src). set (wf_src_th := fun R0 R1 => clos_trans_WF (prod_WF (prod_WF (wf_stt R0 R1) wf_tgt) (nmo_wf (wf_stt R0 R1)))). set (wf_src2 := fun R0 R1 => sum_WF (@wf_src_th R0 R1) wf_src). (* set (I2 := fun R0 R1 => (I2 I wf_stt wf_stt0 (R0:=R0) (R1:=R1))). *) set (M2 := fun R0 R1 => URA.prod (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)) world). set (St := fun o0 => @epsilon _ wf_tgt_inhabited (fun o1 => wf_tgt.(lt) o0 o1)). assert (lt_succ_diag_r_tgt: forall (t: wf_tgt.(T)), wf_tgt.(lt) t (St t)). { i. unfold St. hexploit (@epsilon_spec _ wf_tgt_inhabited (fun o1 => wf_tgt.(lt) t o1)); eauto. } ss. (* eapply (@ModSim.mk _ _ (wf_src2 Any.t Any.t) _ wf_tgt_inhabited wf_tgt_open (M2 Any.t Any.t) (I2 Any.t Any.t)). *) eapply (@ModSim.mk _ _ (wf_src2 Any.t Any.t) _ wf_tgt_inhabited wf_tgt_open (M2 Any.t Any.t)). i. specialize (init im_tgt). des. rename init0 into funs. set (I2 := fun R0 R1 => (I2 I wf_stt wf_stt0 (R0:=R0) (R1:=R1))). exists (I2 Any.t Any.t). split. (* assert (im_src_th: imap thread_id (@wf_src_th Any.t Any.t)). *) (* { exact (fun t => ((wf_stt0 Any.t Any.t, im_tgt (inl t)), nm_proj_v1 ost)). } *) (* exists (imap_comb im_src_th im_src). exists (shared_thsRA wf_stt wf_stt0 ost, r_shared). *) { i. (* move init after im_tgt. specialize (init im_tgt). des. *) set (ost:= @NatMap.empty (prod (wf_stt Any.t Any.t).(T) (wf_stt Any.t Any.t).(T))). assert (im_src_th: imap thread_id (@wf_src_th Any.t Any.t)). { exact (fun t => ((wf_stt0 Any.t Any.t, im_tgt (inl t)), nm_proj_v1 ost)). } exists (imap_comb im_src_th im_src). exists (shared_thsRA wf_stt wf_stt0 ost, r_shared). unfold I2. unfold YOrd2Stid.I2. esplits; eauto. - unfold Is. exists ost. splits; auto. { subst ost. eapply nm_wf_pair_empty_empty_eq. } i. eapply NatMapP.F.empty_in_iff in IN. ss. - ur. split; auto. subst ost. ur. i. ur. split; ur; ss. des_ifs. unfold URA.extends. exists ε. r_solve. } i. specialize (funs fn args). des_ifs. unfold ModSimYOrd.local_sim in funs. ii. unfold I2 in INV. unfold YOrd2Stid.I2 in INV. rename r_shared into r_shared1. destruct r_shared0 as [shared_r r_shared], r_ctx0 as [ctx_r r_ctx]. ur in VALID. des. specialize (funs _ _ _ _ _ _ _ INV tid _ THS VALID0 _ UPD). move funs after UPD. des. rename funs1 into LSIM. move LSIM before M2. unfold Is in INVS. des. clarify. set (ost':= NatMap.add tid (os, ot) ost). exists (shared_thsRA wf_stt wf_stt0 ost', r_shared0), (tid |-> (os, ot), r_own). set (im_src_th':= fun t => match (NatMap.find t ost') with | None => (im_src_th t) | Some (_, ot) => ((ot, St (im_tgt0' (inl t))), nm_proj_v1 ost') end). remember (fun ti => match ti with | inl t => inl (im_src_th' t) | inr i => inr (im_src_us i) end) as im_src_tot. exists im_src_tot. splits. - unfold I2, YOrd2Stid.I2. exists im_src_th', im_src_us. splits; auto. exists ost'. splits; auto. { subst ost'. clear - THS WFOST. inv THS. eapply nm_wf_pair_add. auto. } i. inv THS. subst im_src_th'. ss. rewrite FIND. econs 1. econs 1. econs 2; auto. - ur; split; auto. subst ost'. ur. ur in VALID. i. unfold shared_thsRA in *. specialize (VALID k1). destruct (tid_dec k1 tid); clarify. + rewrite nm_find_add_eq. assert (NatMap.find tid ost = None). { inv THS. eapply nm_wf_pair_find_cases in WFOST. des. eapply WFOST in NEW. auto. } rewrite H in VALID. clear - VALID. rewrite th_has_hit. ur. ur in VALID. des_ifs. des; split. 2: ur; ss. unfold URA.extends in *. des. exists ctx. rewrite URA.unit_idl in VALID. ur in VALID. r_solve. des_ifs; ur; auto. + rewrite nm_find_add_neq; auto. rewrite th_has_miss. r_solve. des_ifs; auto. ii. clarify. - subst. i. destruct r_shared2 as [shared_r2 r_shared2], r_ctx2 as [ctx_r2 r_ctx2]. unfold I2, YOrd2Stid.I2 in INV1. ur in VALID2. des. move LSIM after TGT. specialize (LSIM _ _ _ _ _ _ _ INV1 VALID3 _ TGT). des. hexploit init_src_inv. 1,2: eauto. 2: eapply INVS. 2: eapply VALID2. 2: eapply TGT. instantiate (1:=im_src_us0). reflexivity. i. des. subst im_src1. esplits. eapply SRC. i. eapply yord_implies_stid; eauto. Qed. End MODSIM. Require Import List. Section AUX. Import NatMap. Import NatMapP. Lemma nm_fold_prod_res (world: URA.t) X pw rsost : NatMap.fold (fun (_ : NatMap.key) (r s : URA.prod (@thsRA (prod X X)) world) => r ⋅ s) (NatMap.mapi (fun (t : NatMap.key) (rst : world * (X * X)) => (t |-> snd rst, fst rst)) rsost) pw = (NatMap.fold (fun (_ : NatMap.key) (r s : _) => r ⋅ s) (NatMap.mapi (fun (t : NatMap.key) (rst : world * (X * X)) => (t |-> snd rst)) rsost) (fst pw), NatMap.fold (fun (_ : NatMap.key) (r s : _) => r ⋅ s) (NatMap.mapi (fun (t : NatMap.key) (rst : world * (X * X)) => (fst rst)) rsost) (snd pw)). Proof. rewrite ! NatMap.fold_1. ss. remember (NatMap.this rsost) as l. clear Heql rsost. revert pw. induction l; ss. { i. destruct pw. ss. } i. des_ifs. ss. destruct p as [r [xs xt]]. ss. rewrite IHl. destruct pw as [p w]. ss. f_equal. - f_equal. repeat ur. des_ifs; ss. - f_equal. repeat ur. des_ifs; ss. Qed. Lemma list_map_elements_nm_mapi : forall (elt : Type) (m : NatMap.t elt) (elt1 : Type) (f: NatMap.key -> elt -> elt1), List.map (fun '(k, e) => (k, f k e)) (NatMap.elements m) = NatMap.elements (NatMap.mapi f m). Proof. i. ss. unfold NatMap.elements. unfold NatMap.Raw.elements. destruct m. ss. clear sorted0. rename this0 into l. induction l; ss. des_ifs. f_equal; auto. Qed. Lemma list_fold_left_resource_aux2 (world : URA.t) c X l : fold_left (fun (a : world) (p : NatMap.key * (world * X)) => (let '(r, _) := snd p in fun s : world => r ⋅ s) a) l ε ⋅ c = fold_left (fun (a : world) (p : NatMap.key * (world * X)) => (let '(r, _) := snd p in fun s : world => r ⋅ s) a) l c. Proof. revert c. induction l; i; ss. r_solve. des_ifs. destruct a; ss. clarify; ss. rewrite <- (IHl (c0 ⋅ ε)). r_solve. rewrite <- (IHl (c0 ⋅ c)). r_solve. Qed. Lemma nm_map_empty e0 e1 (f: e0 -> e1) : NatMap.map f (NatMap.empty e0) = (NatMap.empty e1). Proof. eapply nm_empty_eq. eapply nm_map_empty1. apply NatMap.empty_1. Qed. Lemma nm_mapi_empty1 : forall (elt1 : Type) (m : NatMap.t elt1) (elt2 : Type) (f: NatMap.key -> elt1 -> elt2), NatMap.Empty m -> NatMap.Empty (NatMap.mapi f m). Proof. i. rewrite elements_Empty in *. ss. unfold elements, Raw.elements in *. rewrite H. ss. Qed. Lemma nm_mapi_empty e0 e1 f : NatMap.mapi f (NatMap.empty e0) = (NatMap.empty e1). Proof. eapply nm_empty_eq. eapply nm_mapi_empty1. apply NatMap.empty_1. Qed. Lemma nm_mapi_add_comm_equal elt (m: t elt) elt' (f: key -> elt -> elt') k e : Equal (add k (f k e) (mapi f m)) (mapi f (add k e m)). Proof. eapply F.Equal_mapsto_iff. i. split; i. - eapply F.add_mapsto_iff in H. des; clarify. + assert (H: MapsTo k0 e (add k0 e m)). { eapply add_1; auto. } eapply mapi_1 in H. des; clarify; eauto. + eapply F.mapi_mapsto_iff in H0. 2: i; clarify; eauto. des; clarify. assert (H2: MapsTo k0 a (add k e m)). { eapply add_2; auto. } eapply mapi_1 in H2. des; clarify; eauto. - eapply F.mapi_mapsto_iff in H. 2: i; clarify; eauto. des; clarify. eapply F.add_mapsto_iff in H0. des; clarify. + eapply add_1; auto. + eapply add_2; auto. eapply mapi_1 in H1. des; clarify; eauto. Qed. Lemma nm_mapi_add_comm_eq elt (m: t elt) elt' (f: key -> elt -> elt') k e : (add k (f k e) (mapi f m)) = (mapi f (add k e m)). Proof. eapply nm_eq_is_equal, nm_mapi_add_comm_equal. Qed. Lemma nm_map_mapi_equal elt (m: t elt) elt1 (f: key -> elt -> elt1) elt2 (g: elt1 -> elt2) : Equal (map g (mapi f m)) (mapi (fun k e => (g (f k e))) m). Proof. eapply F.Equal_mapsto_iff. i. split; i. - rewrite F.map_mapsto_iff in H. des; clarify. rewrite F.mapi_mapsto_iff in H0. 2: i; clarify. des; clarify. eapply mapi_1 in H1. des; clarify. instantiate (1:= (fun k e => g (f k e))) in H0. ss. - rewrite F.mapi_mapsto_iff in H. 2: i; clarify. des; clarify. eapply map_1. eapply mapi_1 in H0. des; clarify. eauto. Qed. Lemma nm_map_mapi_eq elt (m: t elt) elt1 (f: key -> elt -> elt1) elt2 (g: elt1 -> elt2) : (map g (mapi f m)) = (mapi (fun k e => (g (f k e))) m). Proof. eapply nm_eq_is_equal, nm_map_mapi_equal. Qed. Lemma mapi_unit1_map_equal elt (m: t elt) elt1 (f: key -> elt -> elt1) : Equal (mapi (fun k e => unit1 (f k e)) m) (map unit1 m). Proof. rewrite <- nm_map_mapi_eq. eapply F.Equal_mapsto_iff. i. split; i. - rewrite F.map_mapsto_iff in H. des; clarify. rewrite F.mapi_mapsto_iff in H0. 2: i; clarify. des; clarify. unfold unit1. eapply map_1 in H1. instantiate (1:= (fun _ => tt)) in H1. ss. - rewrite F.map_mapsto_iff in H. des; clarify. rewrite nm_map_mapi_eq. eapply mapi_1 in H0. des; clarify. instantiate (1:=fun k a => tt) in H1. ss. Qed. Lemma mapi_unit1_map_eq elt (m: t elt) elt1 (f: key -> elt -> elt1) : (mapi (fun k e => unit1 (f k e)) m) = (map unit1 m). Proof. eapply nm_eq_is_equal, mapi_unit1_map_equal. Qed. Lemma nm_mapi_unit1_map_equal elt (m: t elt) elt' (f: key -> elt -> elt') : Equal (map unit1 (mapi f m)) (map unit1 m). Proof. rewrite nm_map_mapi_equal. rewrite mapi_unit1_map_equal. ss. Qed. Lemma nm_mapi_unit1_map_eq elt (m: t elt) elt' (f: key -> elt -> elt') : (map unit1 (mapi f m)) = (map unit1 m). Proof. eapply nm_eq_is_equal, nm_mapi_unit1_map_equal. Qed. Lemma fold_left_pointwise_none X l k e (NONE : SetoidList.findA (NatMapP.F.eqb k) l = None) : fold_left (fun (a : @thsRA X) (p : NatMap.key * X) (k0 : nat) => (fst p |-> snd p) k0 ⋅ a k0) l e k = (e k). Proof. revert_until l. induction l; i; ss. des_ifs. ss. rewrite IHl; auto. rewrite th_has_miss; auto. r_solve. ii. clarify. unfold F.eqb in Heq. des_ifs. Qed. End AUX. Section USERSIM. Lemma yord_implies_stid_user md_src md_tgt p_src p_tgt (MDSIM: ModSimYOrd.UserSim.sim md_src md_tgt p_src p_tgt) : ModSimStid.UserSim.sim md_src md_tgt p_src p_tgt. Proof. inv MDSIM. set (ident_src := Mod.ident md_src). set (_ident_tgt := Mod.ident md_tgt). set (state_src := Mod.state md_src). set (state_tgt := Mod.state md_tgt). set (srcE := ((@eventE ident_src +' cE) +' sE state_src)). set (tgtE := ((@eventE _ident_tgt +' cE) +' sE state_tgt)). set (ident_tgt := @ident_tgt _ident_tgt). set (shared := (TIdSet.t * (@imap ident_src wf_src) * (@imap ident_tgt wf_tgt) * state_src * state_tgt)%type). set (ident_src2 := sum_tid ident_src). set (wf_src_th := fun R0 R1 => clos_trans_WF (prod_WF (prod_WF (wf_stt R0 R1) wf_tgt) (nmo_wf (wf_stt R0 R1)))). set (wf_src2 := fun R0 R1 => sum_WF (@wf_src_th R0 R1) wf_src). set (M2 := fun R0 R1 => URA.prod (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)) world). set (St := fun o0 => @epsilon _ wf_tgt_inhabited (fun o1 => wf_tgt.(lt) o0 o1)). assert (lt_succ_diag_r_tgt: forall (t: wf_tgt.(T)), wf_tgt.(lt) t (St t)). { i. unfold St. hexploit (@epsilon_spec _ wf_tgt_inhabited (fun o1 => wf_tgt.(lt) t o1)); eauto. } eapply (@UserSim.mk _ _ _ _ (wf_src2 Any.t Any.t) _ wf_tgt_inhabited wf_tgt_open (M2 Any.t Any.t)). i. specialize (funs im_tgt). des. set (ost:= NatMap.map snd rsost). set (rs:= NatMap.map fst rsost). set (im_src_th:= fun t => match (NatMap.find t ost) with | None => ((wf_stt0 Any.t Any.t, St (im_tgt (inl t))), nm_proj_v1 ost) | Some (_, ot) => ((ot, St (im_tgt (inl t))), nm_proj_v1 ost) end). exists (@I2 _ _ _ _ _ _ _ I wf_stt wf_stt0 Any.t Any.t). exists (@imap_comb _ _ (wf_src_th Any.t Any.t) _ im_src_th im_src). set (rowns:= NatMap.mapi (fun t rst => (t |-> (snd rst), fst rst)) rsost). exists rowns. exists (shared_thsRA wf_stt wf_stt0 ost, r_shared). (* instantiate (1:=@I2 _ _ _ _ _ _ _ I wf_stt wf_stt0 Any.t Any.t). *) esplits. { unfold I2. esplits; eauto. unfold Is. exists ost. splits; auto. { subst ost. unfold nm_wf_pair. unfold key_set. rewrite ! nm_map_unit1_map_eq. eapply nm_forall2_wf_pair. eapply list_forall3_implies_forall2_3 in SIM; eauto. i. des_ifs; des; clarify. } i. subst im_src_th. econs 1. ss. rewrite FIND. econs 1. econs 2; auto. } { eapply nm_find_some_implies_forall3. { eapply nm_forall2_wf_pair. eapply list_forall3_implies_forall2_2 in SIM; eauto. i. des_ifs; des; clarify. } { subst rowns. unfold nm_wf_pair. unfold key_set. rewrite ! nm_mapi_unit1_map_eq. eapply nm_forall2_wf_pair. eapply list_forall3_implies_forall2_3 in SIM; eauto. i. des_ifs; des; clarify. } i. subst rowns. rewrite NatMapP.F.mapi_o in FIND3. unfold option_map in FIND3. des_ifs. 2:{ i; clarify. } destruct p. ss. eapply nm_forall3_implies_find_some in SIM; eauto. unfold ModSimYOrd.local_sim_init in SIM. des_ifs. ii. unfold I2 in INV. des_ifs. des. destruct p as [os ot]. ur in VALID. des_ifs. des. hexploit init_src_inv. 1,2: eauto. 2: eapply INVS. 2: eapply VALID. 2: eapply FAIR. instantiate (1:=im_src_us). reflexivity. i. des. esplits. eapply SRC. i. simpl in Heq0. clarify. eapply yord_implies_stid; eauto. } { subst rowns. subst ost. clear - WF. subst M2. ss. setoid_rewrite (@nm_fold_prod_res world (wf_stt Any.t Any.t).(T) (ε, ε) rsost). try rewrite ! URA.unfold_wf; try rewrite ! URA.unfold_add. ss. split. { clear. assert (RW: (NatMap.mapi (fun (t : NatMap.key) (rst : world * (T (wf_stt Any.t Any.t) * T (wf_stt Any.t Any.t))) => t |-> snd rst) rsost) = (NatMap.mapi (fun t st => t |-> st) (NatMap.map snd rsost))). { induction rsost using nm_ind. { rewrite nm_map_empty. rewrite ! nm_mapi_empty. auto. } rewrite <- nm_map_add_comm_eq. rewrite <- ! nm_mapi_add_comm_eq. f_equal. auto. } setoid_rewrite RW. clear RW. remember (NatMap.map snd rsost) as ost. clear Heqost. clear. replace (@NatMap.fold (forall _ : nat, @Auth.car (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))) (forall _ : nat, @Auth.car (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))) (fun (_ : NatMap.key) (f0 f1 : forall _ : nat, @Auth.car (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))) (k : nat) => @URA.add (Auth.t (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))) (f0 k) (f1 k)) (@NatMap.mapi (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))) (@URA.car (@thsRA (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))) (fun (t : NatMap.key) (st : prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))) => @th_has (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))) t st) ost) (@URA.unit (@thsRA (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t)))))) with (fun n => match NatMap.find n ost with | Some st => ae_white st | None => ε end ). { unfold shared_thsRA. ur. i. des_ifs. { repeat ur. des_ifs. split; r_solve. ss. } { r_solve. ur. split; r_solve. ur. ss. } } replace (@NatMap.fold (forall _ : nat, @Auth.car (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))) (forall _ : nat, @Auth.car (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))) (fun (_ : NatMap.key) (f0 f1 : forall _ : nat, @Auth.car (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))) (k : nat) => @URA.add (Auth.t (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))) (f0 k) (f1 k)) (@NatMap.mapi (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))) (@URA.car (@thsRA (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))) (fun (t : NatMap.key) (st : prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))) => @th_has (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))) t st) ost) (@URA.unit (@thsRA (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t)))))) with (NatMap.fold (fun t st r => (t |-> st) ⋅ r) ost ε). 2:{ rewrite ! NatMap.fold_1. rewrite <- list_map_elements_nm_mapi. remember (NatMap.elements ost) as l. clear. remember ε as r. clear. revert r. induction l; ss. i. rewrite IHl. f_equal. extensionality x. des_ifs. ss. repeat ur. des_ifs; ss. } induction ost using nm_ind; ss. rewrite NatMapP.fold_add; try typeclasses eauto; ss. 2:{ ii. r_solve. } 2:{ ii. apply NatMapP.F.in_find_iff in H. clarify. } extensionality x. destruct (tid_dec x k) eqn:DEC. - clarify. rewrite nm_find_add_eq. rewrite NatMap.fold_1. rewrite NatMapP.F.elements_o in NONE. remember (NatMap.elements ost) as l. ur. setoid_rewrite fold_left_pointwise_none; auto. rewrite th_has_hit. repeat ur; ss. - rewrite nm_find_add_neq; auto. eapply equal_f in IHost. erewrite IHost. ur. rewrite th_has_miss; auto. r_solve. } { replace (NatMap.fold (fun _ : NatMap.key => URA._add) (NatMap.mapi (fun (_ : NatMap.key) (rst : world * (T (wf_stt Any.t Any.t) * T (wf_stt Any.t Any.t))) => fst rst) rsost) ε) with (NatMap.fold (fun (_ : NatMap.key) '(r, _) (s : world) => r ⋅ s) rsost ε); auto. rewrite ! NatMap.fold_1. rewrite <- list_map_elements_nm_mapi. remember (NatMap.elements rsost) as l. clear. replace (fold_left (fun (a : world) (p : NatMap.key * world) => URA._add (snd p) a) (map (fun '(k, e) => (k, fst e)) l) ε) with (fold_left (fun (a : world) (p : NatMap.key * world) => (snd p) ⋅ a) (map (fun '(k, e) => (k, fst e)) l) ε). 2:{ ur. auto. } induction l; ss. des_ifs. ss. clarify. ss. r_solve. rewrite resources_fold_left_base. rewrite <- IHl. symmetry. eapply list_fold_left_resource_aux2. } } Qed. End USERSIM.
#include <stdio.h> #include <gsl/gsl_math.h> #include <gsl/gsl_multimin.h> void calcmatriceswrapper(int *Omega, int *NumTerms, int *qmax, int *pmax, int *IsTriplet, int *Ordering, int *Method, double *Alpha, double *Beta, double *Gamma, double *Energy); void testfortran(int *x) { printf("%d\n", *x); } double test(const gsl_vector *v, void *params) { double a1, b1, g1, Energy; int *p = (int*)params; int Omega = p[0], NumTerms = p[1], qmax = p[2], pmax = p[3], IsTriplet = p[4], Ordering = p[5], Method = p[6]; a1 = gsl_vector_get(v, 0); b1 = gsl_vector_get(v, 1); g1 = gsl_vector_get(v, 2); calcmatriceswrapper(&Omega, &NumTerms, &qmax, &pmax, &IsTriplet, &Ordering, &Method, &a1, &b1, &g1, &Energy); printf("Energy: %f\n", Energy); return Energy; } int optimizewavefn(int MaxIter, int Omega, int NumTerms, int qmax, int pmax, int IsTriplet, int Ordering, int Method, double alpha, double beta, double gamma) { int par[7] = { Omega, NumTerms, qmax, pmax, IsTriplet, Ordering, Method }; //printf("Test: %f %f %f\n", alpha, beta, gamma); const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex; //gsl_multimin_fminimizer_nmsimplex2; gsl_multimin_fminimizer *s = NULL; gsl_vector *ss, *x; gsl_multimin_function minex_func; int iter = 0, status; double size; x = gsl_vector_alloc(3); gsl_vector_set(x, 0, alpha); gsl_vector_set(x, 1, beta); gsl_vector_set(x, 2, gamma); /* Set initial step sizes to 1 */ //ss = gsl_vector_alloc (2); ss = gsl_vector_alloc(3); gsl_vector_set_all(ss, 0.05); /* Initialize method and iterate */ //minex_func.n = 2; minex_func.n = 3; minex_func.f = (void*)test; minex_func.params = par; //s = gsl_multimin_fminimizer_alloc (T, 2); s = gsl_multimin_fminimizer_alloc(T, 3); gsl_multimin_fminimizer_set(s, &minex_func, x, ss); do { iter++; status = gsl_multimin_fminimizer_iterate(s); if (status) break; size = gsl_multimin_fminimizer_size(s); status = gsl_multimin_test_size(size, 1e-5); if (status == GSL_SUCCESS) { printf ("converged to minimum at\n"); } printf ("%5d %10.5e f() = %12.7f size = %.5f\n", iter, gsl_vector_get (s->x, 0), gsl_vector_get (s->x, 1), gsl_vector_get (s->x, 2), s->fval, size); } while (status == GSL_CONTINUE && iter < MaxIter); gsl_vector_free(x); gsl_vector_free(ss); gsl_multimin_fminimizer_free(s); return 0; //@TODO: How do I make this into a void subroutine? }
If $p$ and $q$ are natural numbers such that $pq$ is prime, then $p = 1$ or $q = 1$.
from dsmpy.utils import cmtcatalog from pytomo.dataset.sourceselection import SourceSelection import numpy as np from datetime import datetime import glob import sys if __name__ == '__main__': catalog = cmtcatalog.read_catalog() dep_min = 150 dep_max = 800 dist_min = 15 dist_max = 25 Mw_min = 5.3 Mw_max = 7. start_date = datetime(2000,1,1) sac_files = glob.glob( '/mnt/doremi/anpan/inversion/MTZ_JAPAN/DATA/20*/*T') selector = SourceSelection( sac_files, dep_min=dep_min, dep_max=dep_max, Mw_min=Mw_min, Mw_max=Mw_max, dist_min=dist_min, dist_max=dist_max, start_date=start_date) catalog_filt = np.array( [event for event in selector.dataset.events if selector.select(event)]) print('len(catalog)={}'.format(catalog_filt.shape)) # exclude Philippines and Aleutians eqs catalog_filt = [e for e in catalog_filt if not (e.longitude < 140 and e.latitude < 18) and e.longitude < 165] cluster_labels, cluster_centers = selector.cluster( catalog_filt, max_clusters=50, max_dist=220) _, counts = np.unique(cluster_labels, return_counts=True) cluster_centers_keep = cluster_centers[counts >= 2] catalog_keep = [e for i,e in enumerate(catalog_filt) if counts[cluster_labels[i]] >= 2] cluster_labels_keep = [label for i,label in enumerate(cluster_labels) if counts[cluster_labels[i]] >= 2] print("n_events={}\nn_clusters={}" .format(len(catalog_keep), len(cluster_centers_keep))) df = selector.get_dataframe( catalog_keep, cluster_centers, cluster_labels_keep) selector.plot( catalog_keep, projection='cyl', lon_min=120, lon_max=160, lat_min=10, lat_max=60, cluster_labels=cluster_labels_keep) df.index = list(range(len(df))) df.to_csv('clusters.txt', sep=' ') selector.plot_cartesian(df)
State Before: m n : Nat ⊢ ofNat m % -[n+1] + -[n+1] * (ofNat m / -[n+1]) = ofNat m State After: m n : Nat ⊢ ↑m % ↑(succ n) + -↑(succ n) * -↑(m / succ n) = ↑m Tactic: show (m % succ n + -↑(succ n) * -↑(m / succ n) : Int) = m State Before: m n : Nat ⊢ ↑m % ↑(succ n) + -↑(succ n) * -↑(m / succ n) = ↑m State After: m n : Nat ⊢ ↑m % ↑(succ n) + ↑(succ n) * ↑(m / succ n) = ↑m Tactic: rw [Int.neg_mul_neg] State Before: m n : Nat ⊢ ↑m % ↑(succ n) + ↑(succ n) * ↑(m / succ n) = ↑m State After: no goals Tactic: exact congrArg ofNat <| Nat.mod_add_div .. State Before: a✝ : Nat ⊢ -[a✝+1] % 0 + 0 * (-[a✝+1] / 0) = -[a✝+1] State After: a✝ : Nat ⊢ -[a✝+1] + 0 * (-[a✝+1] / 0) = -[a✝+1] Tactic: rw [emod_zero] State Before: a✝ : Nat ⊢ -[a✝+1] + 0 * (-[a✝+1] / 0) = -[a✝+1] State After: no goals Tactic: rfl State Before: x✝¹ x✝ : Int m n : Nat ⊢ ↑n - (↑m % ↑n + 1) - (↑n * (↑m / ↑n) + ↑n) = -[m+1] State After: x✝¹ x✝ : Int m n : Nat ⊢ -(↑(m % n) + ↑n * ↑(m / n) + 1) = -(↑m + 1) Tactic: rw [← ofNat_emod, ← ofNat_ediv, ← Int.sub_sub, negSucc_eq, Int.sub_sub n, ← Int.neg_neg (_-_), Int.neg_sub, Int.sub_sub_self, Int.add_right_comm] State Before: x✝¹ x✝ : Int m n : Nat ⊢ -(↑(m % n) + ↑n * ↑(m / n) + 1) = -(↑m + 1) State After: no goals Tactic: exact congrArg (fun x => -(ofNat x + 1)) (Nat.mod_add_div ..)
import numpy as np from sklearn.base import BaseEstimator, clone from sklearn.preprocessing import KBinsDiscretizer from .utils import my_fit class ClfBinningRegressor(BaseEstimator): def __init__(self, classifier=None, n_bins=None): self.classifier = classifier self.n_bins = n_bins def fit(self, X, y, sample_weight=None, fit_context=None): self.n_features_in_ = X.shape[1] self.classifier_ = clone(self.classifier) self.transformer_ = KBinsDiscretizer(n_bins=self.n_bins, encode='ordinal', strategy='quantile') y = self.transformer_.fit_transform(y.reshape(-1, 1)).flatten().astype('int') if fit_context is not None: fit_context = fit_context.copy() fit_context['y_val'] = self.transformer_.transform(fit_context['y_val'].reshape(-1, 1)).flatten().astype('int') my_fit( self.classifier_, X, y, sample_weight=sample_weight, fit_context=fit_context, ) self.class_values_ = self.transformer_.inverse_transform(np.array(self.classifier_.classes_).reshape(-1, 1)).flatten() return self def predict(self, X): proba = self.classifier_.predict_proba(X) return np.sum(proba * self.class_values_, axis=1)
import Pkg if VERSION < v"1.4" if get(Pkg.installed(), "Tables", v"0.0") < v"1.0" include("./dummy_tables.jl") @eval import .Tables else @eval import Tables end else # no check for correct version of Tables in Julia 1.4 since # Pkg.dependencies() is "experimental" and Pkg.installed is deprecated try @eval import Tables catch ex include("./dummy_tables.jl") @eval import .Tables end end include("./RConnector.jl") RConnector.serve(parse(Int, ARGS[1]), portfile = ARGS[2], multiclient = (ARGS[3] == "t"))
# GetAuditFreqData.r # RBLandau 20171230 # where to run? # setwd("C:/cygwin64/home/landau/working/PreservationSimulation/audit/frequency") # # For copies 3,4,5, what is the impact of more frequent total audits? # source("../common/DataUtil.r") source("../common/PlotUtil.r") # G E T D A T A if (exists("results")) {rm(results)} results <- fndfGetGiantData("./") # Get fewer columns to work with, easier to see. dat.auditallcopies <- as.data.frame(fndfGetAuditData(results)) dat.auditall <- dat.auditallcopies[dat.auditallcopies$copies>=3 & dat.auditallcopies$copies<=5,] fnPlotAuditFreq1 <- function(trows, nCopies){ p <- ggplot(data=trows , mapping=aes(x=lifem, y=safe(mdmlosspct) # , color=factor(auditfrequency) ) ) p <- p + geom_line(data=trows, size=2 , mapping=aes(color=factor(auditfrequency)) ) p <- p + geom_point(data=trows, shape=(point.DOT), size=4 # , mapping=aes(color=factor(auditfrequency)) ) p <- p + theme(legend.position=c(1,0.8) , legend.justification=c(1,0.5) ) p <- p + labs(color="Audit frequency") p <- p + scale_color_manual( labels=c("month","quarter","half-year","1 year", "2 years") , values = c("black","purple","green","blue","red") ) p <- fnPlotLogScales(p, x='yes', y='yes') p <- fnPlotPercentLine(p) sParams <- sprintf("copies=%s", nCopies) p <- fnPlotTitles(p, title=("Audit frequency comparisons, " %+% sParams %+% "\nIncreasing auditing frequency beyond annually " %+% "yields small benefits " %+% "\nbut at greatly increased cost in bandwidth" ) ,titlesize=16 ,xlabel="1MB sector half-life (megahours)" %+% " (lower error rate \u2192)" ,ylabel="permanent document losses (%)" ,labelsize=14 ) } # S U B S E T S if (nrow(dat.auditall) > 0) { # source("./AuditFreqPlots.r") dat.audit3 <- subset(dat.auditall, copies==3) gp <- fnPlotAuditFreq1(trows=dat.audit3, nCopies=3) plot(gp) fnPlotMakeFile(gp, "Audit_FrequencyComparisons_copies3_MonthToBiennial.png") dat.audit4 <- subset(dat.auditall, copies==4) gp <- fnPlotAuditFreq1(trows=dat.audit4, nCopies=4) plot(gp) fnPlotMakeFile(gp, "Audit_FrequencyComparisons_copies4_MonthToBiennial.png") dat.audit5 <- subset(dat.auditall, copies==5) gp <- fnPlotAuditFreq1(trows=dat.audit5, nCopies=5) plot(gp) fnPlotMakeFile(gp, "Audit_FrequencyComparisons_copies5_MonthToBiennial.png") } # Unwind any remaining sink()s to close output files. while (sink.number() > 0) {sink()} # Edit history: # longago RBL Original version. # 20180326 RBL Put in unbelievably obscure and horrible syntax to control # legend title, colors, labels. Who would guess that # "scale_color_manual()" would be the function to control # the line colors and the legend labels for the variable # factor(auditfrequency)? # Move fnPlotAuditFreq1() function into here from the # subsidiary file. # # #END
(* -*- mode: coq; coq-prog-args: ("-nois") -*- *) (* in Coq 8.8.0 *) (** * Pre 事前に定義すべきもの。 第一に、表記法を事前に定義する。 これらは実際に何を意味するか定義されていないが 優先順位や結合性は定義されている。 最初から [_ + _] を自然数同士の足し算を意味すると決めたりすると それを整数同士の足し算と解釈したいときに困ってしまうし、 それぞれの単塊 (Module) で表記法を定義すると [2 + 3 + 4 * 0] という式が どの単塊に書かれているかによって [(2 + 3) + (4 * 0)] と解釈されたり [((2 + 3) + 4) * 0] と解釈されたりして 読みづらくなってしまうことがあり得るため、 両方の間を取っている。 ちなみに書かれている場所によってどの解釈を選ぶかは 視野 (scope) の仕組みによる。 第二に、視野 (scope) を定義する。 例えば [(Empty + Unit)%type] という式があったとする。 このとき、百分率記号は右側の式が解釈されるときに その式の内部の表記法の意味が [type] という視野の中から探されることを示す。 どの表記法がどの視野に入るかは表記法の意味を定義するときに一緒に定義できる。 同じ表記法でも視野によって意味が異なることがある。 式を読み取る何某から見える「視野」をイメージしてほしい。 百分率記号で直接的に指定しなくとも型によって視野が選ばれることもある。 第三に、戦略 (tactic) を使用するための設定をする。 戦略 (tactic) は一気に定義を書き上げることが出来ない場合に有用な道具である。 この部分の記述は Stack Overflow で Tej Chajed 氏に教えていただいた。 さらに、 Coq の標準文庫 (library) の内部にある Coq.Init.Notations の記述も参考にした。 第四に、設定旗 (flag) を操作する。 HoTT の内部にある HoTT.Basics.Overture の記述に依った。 *) Module Pre. (** ** 述語論理の記号 これらのいずれも Coq.Init.Notations を参考にした。 含意記号は右側のみ優先順位が低いため、 [P -> _] と書かれた時に [_] の部分が分けられて認識されることはない。 *) Reserved Notation "x -> y" (at level 99, right associativity, y at level 200). Reserved Notation "x <-> y" (at level 95, no associativity). Reserved Notation "x /\ y" (at level 80, right associativity). Reserved Notation "x \/ y" (at level 85, right associativity). Reserved Notation "~ x" (at level 75, right associativity). (** ** 等号及び不等号、大小関係 *) Reserved Notation "x = y :> T" (at level 70, y at next level, no associativity). Reserved Notation "x = y" (at level 70, no associativity). Reserved Notation "x <> y :> T"(at level 70, y at next level, no associativity). Reserved Notation "x <> y" (at level 70, no associativity). Reserved Notation "x <= y" (at level 70, no associativity). Reserved Notation "x < y" (at level 70, no associativity). Reserved Notation "x >= y" (at level 70, no associativity). Reserved Notation "x > y" (at level 70, no associativity). (** ** 算術演算子 *) Reserved Notation "x + y" (at level 50, left associativity). Reserved Notation "x - y" (at level 50, left associativity). Reserved Notation "x * y" (at level 40, left associativity). Reserved Notation "x / y" (at level 40, left associativity). Reserved Notation "x ^ y" (at level 30, right associativity). Reserved Notation "- x" (at level 35, right associativity). Reserved Notation "/ x" (at level 35, right associativity). (** ** 視野 (scope) *) Delimit Scope type_scope with type. Delimit Scope function_scope with function. Delimit Scope core_scope with core. Bind Scope type_scope with Sortclass. Bind Scope function_scope with Funclass. Open Scope core_scope. Open Scope function_scope. Open Scope type_scope. (** ** 戦略 (tactic) の設定 *) Declare ML Module "ltac_plugin". Export Set Default Proof Mode "Classic". (** ** 設定旗 (flag) の操作 *) Export Unset Bracketing Last Introduction Pattern. Export Set Typeclasses Strict Resolution. Export Unset Elimination Schemes. Export Set Keyed Unification. Export Unset Refine Instance Mode. Export Unset Strict Universe Declaration. Export Unset Universe Minimization ToSet. End Pre. (** * Predicate 命題論理、述語論理についての定義。 論理式はカリー・ハワード対応に従って型へ翻訳される。 この小単位はそれらを定義するものである。 ただ、これらは命題 (Prop) ではなく 型 (Type) であることに注意すること。 *) Module Predicate. Export Pre. (** ** 関数 *) Definition arrow (A B : Type) : Type := forall (_ : A), B. Notation "A -> B" := (forall (_ : A), B) : type_scope. (** 汎用関数 *) Definition id {A : Type} : A -> A := fun x => x. Definition const {A B : Type} : A -> B -> A := fun x _ => x. Definition compose {A B C : Type} : (A -> B) -> (C -> A) -> C -> B := fun f g x => f (g x). Definition flip {A B C : Type} : (A -> B -> C) -> B -> A -> C := fun f x y => f y x. Definition apply {A B : Type} : (A -> B) -> A -> B := id. (** ** Empty *) (** 偽、矛盾、空の型、空の空間。 *) Inductive Empty : Type := . Scheme Empty_ind := Induction for Empty Sort Type. Scheme Empty_rec := Minimality for Empty Sort Type. Definition Empty_rect := Empty_ind. Arguments Empty_rec {P} _. Definition not (A : Type) : Type := A -> Empty. Notation "~ x" := (not x) : type_scope. (** ** Unit *) (** 真、点の空間、ユニット。 *) Inductive Unit : Type := | tt : Unit . Scheme Unit_ind := Induction for Unit Sort Type. Scheme Unit_rec := Minimality for Unit Sort Type. Definition Unit_rect := Unit_ind. Arguments Unit_rec {P} _ _. (** ** and *) (** 論理積、二つ組、対、ダブル、2-タプル、ペア。 *) Inductive and (A B : Type) : Type := | pair : A -> B -> A /\ B where "A /\ B" := (and A B) : type_scope . Arguments pair {A B} _ _. Scheme and_ind := Induction for and Sort Type. Scheme and_rec := Minimality for and Sort Type. Definition and_rect := and_ind. Arguments and_ind {A B} _ _ _. Arguments and_rec {A B P} _ _. Arguments and_rect {A B} _ _ _. Definition first {A B : Type} : A /\ B -> A := fun x => match x with pair xL _ => xL end . Definition second {A B : Type} : A /\ B -> B := fun x => match x with pair _ xR => xR end . Definition and_proj1 {A B : Type} := @first A B. Definition and_proj2 {A B : Type} := @second A B. (** ** or *) (** 論理和。 *) Inductive or (A B : Type) : Type := | left : A -> A \/ B | right : B -> A \/ B where "A \/ B" := (or A B) : type_scope . Arguments left {A B} _. Arguments right {A B} _. Scheme or_ind := Induction for or Sort Type. Scheme or_rec := Minimality for or Sort Type. Definition or_rect := or_ind. Arguments or_ind {A B} _ _ _ _. Arguments or_rec {A B P} _ _ _. Arguments or_rect {A B} _ _ _ _. (** 写像。 *) Theorem and_map_l {A B C : Type} : (A -> B) -> A /\ C -> B /\ C. Proof. intros f [xl xr]; refine (pair (f xl) xr). Defined. Theorem and_map_r {A B C : Type} : (A -> B) -> C /\ A -> C /\ B. Proof. intros f [xl xr]; refine (pair xl (f xr)). Defined. Theorem or_map_l {A B C : Type} : (A -> B) -> A \/ C -> B \/ C. Proof. intros f [xl | xr]; [> refine (left (f xl)) | refine (right xr) ]. Defined. Theorem or_map_r {A B C : Type} : (A -> B) -> C \/ A -> C \/ B. Proof. intros f [xl | xr]; [> refine (left xl) | refine (right (f xr)) ]. Defined. Theorem imp_map_l {A B C : Type} : (A -> B) -> (B -> C) -> (A -> C). Proof. intros f g; refine (compose g f). Defined. Theorem imp_map_r {A B C : Type} : (A -> B) -> (C -> A) -> (C -> B). Proof. intros f g; refine (compose f g). Defined. Theorem not_map {A B : Type} : (A -> B) -> ~ B -> ~ A. Proof. intros f x; refine (compose x f). Defined. (** ** 命題論理の定理 *) Definition exfalso {A : Type} : Empty -> A := Empty_rec. Definition unit_const {A : Type} : A -> Unit := const tt. Theorem and_fanout {A B C : Type} : (A -> B) -> (A -> C) -> A -> B /\ C. Proof. intros f g x; refine (pair (f x) (g x)). Defined. Theorem or_fanin {A B C : Type} : (A -> B) -> (C -> B) -> A \/ C -> B. Proof. intros f g [xl | xr]; [> refine (f xl) | refine (g xr) ]. Defined. Theorem double_not {A : Type} : A -> ~ ~ A. Proof. intros a na. apply na. apply a. Defined. (** ** iff *) (** 同値。 *) Definition iff (A B : Type) : Type := (A -> B) /\ (B -> A). Notation "A <-> B" := (iff A B) : type_scope. (** iffの基本性質 *) Theorem iff_refl {A : Type} : A <-> A. Proof. refine (pair id id). Defined. Theorem iff_sym {A B : Type} : (A <-> B) -> (B <-> A). Proof. intros x. refine (pair (second x) (first x)). Defined. Theorem iff_trans {A B C : Type} : (A <-> B) -> (C <-> A) -> (C <-> B). Proof. intros x y. apply pair. - refine (compose (first x) (first y)). - refine (compose (second y) (second x)). Defined. (** 双方向の写像 *) Theorem and_iff_map_l {A B C : Type} : (A <-> B) -> (A /\ C <-> B /\ C). Proof. intros [xl xr]; refine (pair (and_map_l xl) (and_map_l xr)). Defined. Theorem and_iff_map_r {A B C : Type} : (A <-> B) -> (C /\ A <-> C /\ B). Proof. intros [xl xr]; refine (pair (and_map_r xl) (and_map_r xr)). Defined. Theorem or_iff_map_l {A B C : Type} : (A <-> B) -> (A \/ C <-> B \/ C). Proof. intros [xl xr]; refine (pair (or_map_l xl) (or_map_l xr)). Defined. Theorem or_iff_map_r {A B C : Type} : (A <-> B) -> (C \/ A <-> C \/ B). Proof. intros [xl xr]; refine (pair (or_map_r xl) (or_map_r xr)). Defined. Theorem imp_iff_map_l {A B C : Type} : (A <-> B) -> ((A -> C) <-> (B -> C)). Proof. intros [xl xr]; refine (pair (imp_map_l xr) (imp_map_l xl)). Defined. Theorem imp_iff_map_r {A B C : Type} : (A <-> B) -> ((C -> A) <-> (C -> B)). Proof. intros [xl xr]; refine (pair (imp_map_r xl) (imp_map_r xr)). Defined. Theorem not_iff_map {A B C : Type} : (A <-> B) -> (~ A <-> ~B). Proof. intros [xl xr]; refine (pair (not_map xr) (not_map xl)). Defined. (** ** 重要な同値関係 *) Theorem neg_false {A : Type} : ~ A <-> (A <-> Empty). Proof. apply pair. - intros nx. refine (pair nx exfalso). - apply first. Defined. Theorem and_comm {A B : Type} : A /\ B <-> B /\ A. Proof. assert (comm : forall A B, A /\ B -> B /\ A). - intros gA gB [xl xr]; refine (pair xr xl). - apply pair. + apply comm. + apply comm. Defined. Theorem and_assoc {A B C : Type} : (A /\ B) /\ C <-> A /\ B /\ C. Proof. apply pair. - refine (and_fanout _ _). + refine (compose first first). + refine (and_fanout _ _). * refine (compose second first). * refine second. - refine (and_fanout _ _). + refine (and_fanout _ _). * refine first. * refine (compose first second). + refine (compose second second). Defined. Theorem and_unit_l {A : Type} : A /\ Unit <-> A. Proof. apply pair. - apply first. - refine (and_fanout id unit_const). Defined. Theorem and_unit_r {A : Type} : Unit /\ A <-> A. Proof. apply pair. - apply second. - refine (and_fanout unit_const id). Defined. Theorem or_comm {A B : Type} : (A \/ B) <-> (B \/ A). Proof. assert (comm : forall A B, A \/ B -> B \/ A). - intros gA gB [xl | xr]; [> refine (right xl) | refine (left xr) ]. - apply pair. + apply comm. + apply comm. Defined. Theorem or_assoc {A B C : Type} : (A \/ B) \/ C <-> A \/ B \/ C. Proof. apply pair. - refine (or_fanin _ _). + refine (or_fanin _ _). * refine left. * refine (compose right left). + refine (compose right right). - refine (or_fanin _ _). + refine (compose left left). + refine (or_fanin _ _). * refine (compose left right). * refine right. Defined. Theorem or_empty_l {A : Type} : A \/ Empty <-> A. Proof. apply pair. - apply or_fanin. + apply id. + apply exfalso. - apply left. Defined. Theorem or_empty_r {A : Type} : Empty \/ A <-> A. Proof. apply pair. - apply or_fanin. + apply exfalso. + apply id. - apply right. Defined. Theorem iff_double_not {A : Type} : ~ ~ ~ A <-> ~ A. Proof. apply pair. - apply not_map. apply double_not. - apply double_not. Defined. Theorem de_morgan {A B : Type} : ~ (A \/ B) <-> ~ A /\ ~ B. Proof. apply pair. - apply and_fanout. + apply not_map. apply left. + apply not_map. apply right. - intros [xl xr]. refine (or_rec xl xr). Defined. (** ** 量化子 *) Inductive ex (A : Type) (P : A -> Type) : Type := | ex_pair : forall x : A, P x -> ex A P . Notation "'exists' x .. y , p" := (ex _ (fun x => .. (ex _ (fun y => p)) ..)) ( at level 200, x binder, right associativity, format "'[' 'exists' '/ ' x .. y , '/ ' p ']'") : type_scope. Arguments ex {A} _. Arguments ex_pair {A} _ _ _. Scheme ex_ind := Induction for ex Sort Type. Scheme ex_rec := Minimality for ex Sort Type. Definition ex_rect := ex_ind. Arguments ex_ind {A P} _ _ _. Arguments ex_rec {A P P0} _ _. Arguments ex_rect {A P} _ _ _. Definition ex_proj1 {A : Type} {P : A -> Type} : ex P -> A. Proof. intros x. case x. intros x1 x2. apply x1. Defined. Definition ex_proj2 {A : Type} {P : A -> Type} : forall (x : ex P), P (ex_proj1 x). Proof. intros x. case x. intros x1 x2. apply x2. Defined. Definition all {A : Type} (P : A -> Type) : Type := forall x, P x. (** 量化子に関する重要な同値関係 *) Theorem quant_de_morgan {A : Type} {P : A -> Type} : ~ (exists x, P x) <-> forall x, ~ P x. Proof. apply pair. - intros H x xH. apply H. apply ex_pair with x. apply xH. - intros H [x xH]. apply H with x. apply xH. Defined. End Predicate. (** * Equality *) (** 等号について。 *) Module Equality. Export Predicate. (** ** eq *) Inductive eq (A : Type) (x : A) : A -> Type := | eq_refl : x = x :> A where "x = y :> A" := (eq A x y) : type_scope . Notation "x = y" := (x = y :> _) : type_scope. Notation "x <> y :> T" := (~ x = y :> T) : type_scope. Notation "x <> y" := (x <> y :> _) : type_scope. Arguments eq {A} _ _. Arguments eq_refl {A x}, [A] x. Scheme eq_ind := Induction for eq Sort Type. Scheme eq_rec := Minimality for eq Sort Type. Definition eq_rect := eq_ind. Arguments eq_ind [A] _ _ _ _ _. Arguments eq_rec [A] _ _ _ _ _. Arguments eq_rect [A] _ _ _ _ _. (** eqの基本性質 *) Definition eq_sym {A : Type} {x y : A} : x = y -> y = x. Proof. intros []. apply eq_refl. Defined. Definition eq_trans {A : Type} {x y z : A} : x = y -> z = x -> y = z. Proof. intros [] []. apply eq_refl. Defined. (** eqの汎用関数 *) Definition eq_ind' : forall (A : Type) (P : forall a b : A, a = b -> Type), (forall a : A, P a a eq_refl) -> forall (a b : A) (p : a = b), P a b p. Proof. intros A P H a b []. apply H. Defined. Definition eq_rec' : forall (A : Type) (P : A -> A -> Type), (forall a : A, P a a) -> forall a b : A, a = b -> P a b. Proof. intros A P H a b []. apply H. Defined. Definition eq_rect' := eq_ind'. Definition eq_rec_r : forall (A : Type) (x : A) (P : A -> Type), P x -> forall (y : A), y = x -> P y. Proof. intros A x P H y p. apply (eq_rec x P H y). apply eq_sym. apply p. Defined. Arguments eq_ind' [A] _ _ _ _ _. Arguments eq_rec' [A] _ _ _ _ _. Arguments eq_rect' [A] _ _ _ _ _. Arguments eq_rec_r [A] _ _ _ _ _. Definition f_equal {A B : Type} (f : A -> B) {x y : A} : x = y -> f x = f y. Proof. intros []. apply eq_refl. Defined. Definition rew {A : Type} (P : A -> Type) {x y : A} : x = y -> P x -> P y. Proof. intros []. apply id. Defined. End Equality. Module Peano. Export Predicate Equality. Inductive nat : Type := | O : nat | S : nat -> nat . Scheme nat_ind := Induction for nat Sort Type. Scheme nat_rec := Minimality for nat Sort Type. Definition nat_rect := nat_ind. Definition not_eq_O_S : forall n, O <> S n. Proof. intros n p. refine ( match p in _ = x' return (match x' with O => Unit | S xp => Empty end) with | eq_refl _ _ => _ end ). apply tt. Defined. Definition pred : nat -> nat := fun x => match x with | O => O | S xp => xp end . Inductive le (m : nat) : nat -> Type := | le_n : le m m | le_S : forall n, le m n -> le m (S n) . Definition le_rect_simple : forall (m : nat) (P : nat -> Type), P m -> (forall n, le m n -> P n -> P (S n)) -> forall n, le m n -> P n. Proof. intros m P cN cS. apply le_rect. - apply cN. - apply cS. Defined. Definition le_ind_simple : forall (m : nat) (P : nat -> Prop), P m -> (forall n, le m n -> P n -> P (S n)) -> forall n, le m n -> P n. Proof. intros m P cN cS. apply le_rect. - apply cN. - apply cS. Defined. Definition le_rec_simple : forall (m : nat) (P : nat -> Set), P m -> (forall n, le m n -> P n -> P (S n)) -> forall n, le m n -> P n. Proof. intros m P. apply le_rect_simple. Defined. Definition le_0_n : forall n : nat, le O n. Proof. intros n. induction n as [ | n IHn ]. - apply le_n. - apply le_S. apply IHn. Defined. Definition le_n_S : forall m n : nat, le m n -> le (S m) (S n). Proof. intros m. apply le_rect_simple. - apply le_n. - intros n nH H. apply le_S. apply H. Defined. Definition le_pred : forall m n : nat, le m n -> le (pred m) (pred n). Proof. intros m. apply le_rect_simple. - apply le_n. - intros [ | np ] nH H. + apply H. + cut (forall k, S (pred (S k)) = pred (S (S k))). * intros Lem. case (Lem np). apply le_S. apply H. * intros k. apply eq_refl. Defined. Definition le_S_n : forall m n : nat, le (S m) (S n) -> le m n. Proof. intros m n H. apply (le_pred (S m) (S n)). apply H. Defined. Definition le_trans : forall m n o, le m n -> le n o -> le m o. Proof. intros m n o H. revert o. apply le_rect_simple. - apply H. - intros o oH IH. apply le_S. apply IH. Defined. Definition lt m n := le (S m) n. Definition not_lt_n_0 : forall n, ~ lt n O. Proof. intros n nH. cut (O = O). - refine ( match nH in le _ o' return O <> o' with | le_n _ => _ | le_S _ o pH => _ end ). + apply not_eq_O_S. + apply not_eq_O_S. - apply eq_refl. Defined. End Peano. Export Peano. *) Module Path. Export Equality. Definition paths := @eq. Definition idpath := @eq_refl. Definition inverse := eq_sym. Definition concat := fun (A : Type) (x y z : A) => flip (@eq_trans A y z x). Definition transport := rew. Definition ap := f_equal. (** apKN << ap00 := fun (f : A -> B) (x : A) => (_ : B) ap01 := fun (f : A -> B) (x y : A) (p : eq A x y) => (_ : eq B (f x) (f y)) ap10 := fun (f g : A -> B) (p : eq (A -> B) f g) (x : A) => (_ : eq B (f x) (g x)) ap11 := fun (f g : A -> B) (p : eq (A -> B) f g) (x y : A) (q : eq A x y) => (_ : eq B (f x) (g y)) >> *) Definition ap00 := apply. Definition ap01 := ap. Definition ap10 : forall (A B : Type) (f g : A -> B), f = g -> forall (x : A), f x = g x. Proof. intros A B f g p x. case p. apply idpath. Defined. Definition ap11 : forall (A B : Type) (f g : A -> B), f = g -> forall (x y : A), x = y -> f x = g y. Proof. intros A B f g p x y q. case p. case q. apply idpath. Defined. Definition pw_paths (A : Type) (P : A -> Type) (f g : forall x, P x) := forall x, f x = g x. Definition pw_idpath : forall (A : Type) (P : A -> Type) (f : forall x, P x), pw_paths P f f. Proof. intros A P f x. apply idpath. Defined. Definition pw_whiskerL (A B C : Type) (f : A -> B) (g h : B -> C) : pw_paths (fun _ => C) g h -> pw_paths (fun _ => C) (compose g f) (compose h f). Proof. intros p x. apply p. Defined. Definition pw_whiskerR (A B C : Type) (f g : A -> B) (h : B -> C) : pw_paths (fun _ => B) f g -> pw_paths (fun _ => C) (compose h f) (compose h g). Proof. intros p x. apply ap with (f := h). apply p. Defined. Definition pw_pw_paths (A : Type) (P : A -> Type) (f g : forall x, P x) (pw_p pw_q : pw_paths P f g) := forall x, pw_p x = pw_q x. Definition sect (A B : Type) (s : A -> B) (r : B -> A) := pw_paths (fun _ => A) (compose r s) id. Definition equiv (A B : Type) := exists (f : A -> B) (g : B -> A) (es : sect g f) (er : sect f g), pw_pw_paths (fun _ => B) (compose f (compose g f)) f (pw_whiskerL f (compose f g) id es) (pw_whiskerR (compose g f) id f er). End Path. Module Relation. Export Predicate. Definition relation (A : Type) := A -> A -> Type. Definition mere (A : Type) (R : relation A) := forall x y : A, forall p q : R x y, p = q. Section Classes. Variable A : Type. Variable R : relation A. Class Reflexive : Type := reflexivity : forall x, R x x. Class Irreflexive := irreflexivity : forall x, ~ R x x. Class Symmetric := symmetry : forall x y, R x y -> R y x. Class Asymmetric := asymmetry : forall x y, R x y -> ~ R y x. Class Antisymmetric := antisymmetry : forall x y, R x y -> R y x -> x = y. Class Transitive := transitivity : forall x y z, R x y -> R y z -> R x z. Class Well_Founded := well_foundness : forall P, (forall x, (forall y, R y x -> P y) -> P x) -> (forall x, P x). Class Trichotomous := trichotomy : forall x y, x = y \/ R x y \/ R y x. Class Extensional := extensionality : forall x y, (forall a, R a x <-> R a y) -> x = y. Theorem th_0 `{WF : Well_Founded} : Irreflexive. Proof. unfold Irreflexive. apply well_foundness. intros x IH H. apply IH with x. - apply H. - apply H. Defined. Theorem th_1 `{WF : Well_Founded} : Asymmetric. Proof. unfold Asymmetric. apply (@well_foundness _ (fun x => forall y, R x y -> ~ R y x)). intros x IH y Hl Hr. apply IH with y x. - apply Hr. - apply Hr. - apply Hl. Defined. Theorem th_2 `{IR : Irreflexive} `{T : Trichotomous} : Extensional. Proof. unfold Extensional. intros x y H. destruct (@trichotomy _ x y) as [both | [left | right]]. - apply both. - apply exfalso. apply irreflexivity with x. apply (second (H _)). apply left. - apply exfalso. apply irreflexivity with y. apply (first (H _)). apply right. Defined. Theorem th_3 `{WF : Well_Founded} `{T : Trichotomous} : Transitive. Proof. unfold Transitive. intros x y z Hl Hr. destruct (@trichotomy _ x z) as [both | [left | right]]. - apply exfalso. assert (AS : Asymmetric). + apply th_1. + apply asymmetry with y z. * apply Hr. * case both. apply Hl. - apply left. - assert (tri_loop : forall x y z, R x y -> R y z -> R z x -> Empty). + clear x y z Hl Hr right. apply (@well_foundness _ (fun x => forall y z, R x y -> R y z -> R z x -> Empty)). intros x IH y z Hx Hy Hz. apply IH with z x y. * apply Hz. * apply Hz. * apply Hx. * apply Hy. + apply exfalso. apply tri_loop with x y z. * apply Hl. * apply Hr. * apply right. Defined. End Classes. Module Type Ord. Parameter ord : Type. Parameter lt : ord -> ord -> Type. End Ord. Module Ord_Defs (Export Model : Ord). Definition le : ord -> ord -> Type := fun a b => lt a b \/ a = b. Definition le_lt : forall a b, lt a b -> le a b. Proof. intros a b H. apply left. apply H. Defined. Definition le_eq : forall a b, a = b -> le a b. Proof. intros a b H. apply right. apply H. Defined. Definition le_refl : forall a, le a a. Proof. intros a. apply le_eq. apply eq_refl. Defined. End Ord_Defs. Module Type Induction (Export Model : Ord). Axiom ind : forall p : ord -> Type, (forall a, (forall x, lt x a -> p x) -> p a) -> forall a, p a. End Induction. Module Induction_Defs (Model : Ord) (Export IndModel : Induction Model). Module Model_Ord_Defs := Ord_Defs Model. Export Model_Ord_Defs. Definition not_lt_refl : forall a, ~ lt a a. Proof. apply (ind (fun a => ~ lt a a)). intros a IHa H. apply IHa with a. - apply H. - apply H. Defined. Definition not_lt_sym : forall a b, lt a b -> ~ lt b a. Proof. apply (ind (fun a => forall b, lt a b -> ~ lt b a)). intros a IHa b Ha Hb. apply IHa with b a. - apply Hb. - apply Hb. - apply Ha. Defined. Definition not_lt_sym_and : forall a b, ~ (lt a b /\ lt b a). Proof. intros a b. apply not_and_then. apply not_lt_sym. Defined. Definition not_lt_inf_dec_chain : forall f, ~ (forall n, lt (f (S n)) (f n)). Proof. intros f inf_dec_chain. cut (forall a x, f x <> a). - intros H. apply H with (f O) O. apply eq_refl. - apply (ind (fun a => forall x, f x <> a)). intros a IHa x H. apply IHa with (f (S x)) (S x). + case H. apply inf_dec_chain. + apply eq_refl. Defined. Definition not_le_lt : forall a b, lt a b -> ~ le b a. Proof. intros a b H [L | R]. - apply not_lt_sym with a b. + apply H. + apply L. - revert H. case R. apply not_lt_refl. Defined. Definition not_and_lt_le : forall a b, ~ (lt a b /\ le b a). Proof. intros a b. apply not_and_then. apply not_le_lt. Defined. Definition not_lt_le : forall a b, le a b -> ~ lt b a. Proof. intros a b. apply not_then_then. apply not_le_lt. Defined. End Induction_Defs. Module Type Extensionality (Export Model : Ord). Axiom extension : forall a b, (forall x, lt x a <-> lt x b) -> a = b. End Extensionality. Module Extensionality_Defs (Model : Ord) (Export ExModel : Extensionality Model). End Extensionality_Defs. Module Type Transitivity (Export Model : Ord). Axiom transition : forall a b c, lt a b -> lt b c -> lt a c. End Transitivity. Module Transitivity_Defs (Model : Ord) (Export TransModel : Transitivity Model). End Transitivity_Defs. Module IndExTrans_Defs (Model : Ord) (Export IndModel : Induction Model) (Export ExModel : Extensionality Model) (Export TransModel : Transitivity Model). Module IndDefs := Induction_Defs Model IndModel. Export IndDefs. Module ExDefs := Extensionality_Defs Model ExModel. Export ExDefs. Module TransDefs := Transitivity_Defs Model TransModel. Export TransDefs. (* double-negation translated [forall x y, x = y \/ lt x y \/ lt y x] (Gödel–Gentzen translation) *) Definition trichotomy : forall x y, ~ (~ ~ ~ x = y /\ ~ ~ (~ ~ ~ lt x y /\ ~ ~ ~ lt y x)). Proof. intros x y H. case H. intros HL HR. apply HL. intros HL'. apply HR. intros HR'. case HR'. intros HR'L HR'R. apply HR'L. Module Nat_Ord <: Ord. Definition ord : Type := nat. Definition lt : ord -> ord -> Type := lt. End Nat_Ord. Module Nat_Induction <: Induction Nat_Ord. Export Nat_Ord. Definition ind : forall p : ord -> Type, (forall a, (forall x, lt x a -> p x) -> p a) -> forall a, p a. Proof. intros p f. cut (forall n k, lt k n -> p k). - intros Lem a. apply f. apply Lem. - apply (nat_rect (fun n => forall k, lt k n -> p k)). + intros k kH. apply Empty_rect. apply not_lt_n_0 with k. apply kH. + intros n IHn k kH. apply f. intros x xH. apply IHn. apply le_trans with k. * apply xH. * apply le_S_n. apply kH. Defined. End Nat_Induction.
(* -*- mode: coq; mode: visual-line -*- *) Require Import HoTT.Basics HoTT.Types. Require Import Modality Accessible. Local Open Scope path_scope. (** * The identity modality *) (** Everything to say here is fairly trivial. *) Inductive Identity_Modality : Type1 := purely : Identity_Modality. Module Identity_Modalities <: Modalities. Definition Modality : Type2@{u a} := Identity_Modality@{a}. Definition O_reflector : forall (O : Modality@{u a}), Type@{i} -> Type@{i} := fun O X => X. Definition In : forall (O : Modality@{u a}), Type@{i} -> Type@{i} := fun O X => Unit. Definition O_inO : forall (O : Modality@{u a}) (T : Type@{i}), In@{u a i} O (O_reflector@{u a i} O T) := fun O X => tt. Definition to : forall (O : Modality@{u a}) (T : Type@{i}), T -> O_reflector@{u a i} O T := fun O X x => x. Definition inO_equiv_inO : forall (O : Modality@{u a}) (T : Type@{i}) (U : Type@{j}) (T_inO : In@{u a i} O T) (f : T -> U) (feq : IsEquiv f), let gei := ((fun x => x) : Type@{i} -> Type@{k}) in let gej := ((fun x => x) : Type@{j} -> Type@{k}) in In@{u a j} O U := fun O T U _ _ _ => tt. Definition hprop_inO@{u a i} : Funext -> forall (O : Modality@{u a}) (T : Type@{i}), IsHProp (In@{u a i} O T) := fun _ O T => trunc_contr@{i}. Definition O_ind_internal : forall (O : Modality@{u a}) (A : Type@{i}) (B : O_reflector O A -> Type@{j}) (B_inO : forall oa, In@{u a j} O (B oa)), let gei := ((fun x => x) : Type@{i} -> Type@{k}) in let gej := ((fun x => x) : Type@{j} -> Type@{k}) in (forall a, B (to O A a)) -> forall a, B a := fun O A B _ f a => f a. Definition O_ind_beta_internal : forall (O : Modality@{u a}) (A : Type@{i}) (B : O_reflector O A -> Type@{j}) (B_inO : forall oa, In@{u a j} O (B oa)) (f : forall a : A, B (to O A a)) (a:A), O_ind_internal O A B B_inO f (to O A a) = f a := fun _ _ _ _ _ _ => 1. Definition minO_paths : forall (O : Modality@{u a}) (A : Type@{i}) (A_inO : In@{u a i} O A) (z z' : A), In@{u a i} O (z = z') := fun _ _ _ _ _ => tt. Definition IsSepFor@{u a} : forall (O' O : Modality@{u a}), Type@{u} := fun _ _ => Unit. Definition inO_paths_from_inSepO@{u a i iplus} : forall (O' O : Modality@{u a}) (sep : IsSepFor O' O) (A : Type@{i}) (A_inO : In@{u a i} O' A) (x y : A), In@{u a i} O (x = y) := fun _ _ _ _ _ _ _ => tt. Definition inSepO_from_inO_paths@{u a i iplus} : forall (O' O : Modality@{u a}) (sep : IsSepFor O' O) (A : Type@{i}), (forall (x y : A), In@{u a i} O (x = y)) -> In@{u a i} O' A := fun _ _ _ _ _ => tt. End Identity_Modalities. Module purelyM := Modalities_Theory Identity_Modalities. Export purelyM.Coercions. Export purelyM.RSU.Coercions. Coercion Identity_Modalities_to_Modalities := idmap : Identity_Modality -> Identity_Modalities.Modality. Module Accessible_Identity <: Accessible_Modalities Identity_Modalities. Module Import Os_Theory := Modalities_Theory Identity_Modalities. Definition acc_gen : Modality@{u a} -> NullGenerators@{a} := fun _ => Build_NullGenerators Empty (fun _ => Empty). Definition inO_iff_isnull@{u a i} : forall (O : Modality@{u a}) (X : Type@{i}), iff@{i i i} (In@{u a i} O X) (IsNull_Internal.IsNull@{a i} (acc_gen O) X) := fun O X => @pair _ (_ -> Unit) (fun _ => Empty_ind _) (fun _ => tt). End Accessible_Identity.
export MultiHomTotalDegreeSystem """ MultiHomogeneousTotalDegreeSystem(polynomials, vars) <: AbstractSystem Create a multi-homogeneous total degree system as described in An efficient start system for multi-homogeneous polynomial continuation, Wampler, C.W. Numer. Math. (1993) 66: 517. https://doi.org/10.1007/BF01385710 """ struct MultiHomTotalDegreeSystem{T} <: AbstractSystem D::Matrix{Int} C::Matrix{Float64} scaling_factors::Vector{T} end function MultiHomTotalDegreeSystem(D, C) MultiHomTotalDegreeSystem(D, C, ones(size(D, 2))) end struct MultiHomTotalDegreeSystemCache{M,T} <: AbstractSystemCache B::Matrix{T} Ĝ::Matrix{T} R::Matrix{T} S::Matrix{T} ranges::NTuple{M,UnitRange{Int}} homvars::NTuple{M,Int} end Base.size(F::MultiHomTotalDegreeSystem) = (size(F.D, 2), sum(size(F.D))) Base.length(F::MultiHomTotalDegreeSystem) = size(F.D, 2) function cache(F::MultiHomTotalDegreeSystem, x::PVector{TX,M}) where {TX,M} T = typeof(F.C[1, 1] * x[1] + F.C[1, 1] * x[1]) n = length(F) B, Ĝ = zeros(T, M, n), zeros(T, M, n) R, S = zeros(T, M, n), zeros(T, M, n) ranges_homvars = ProjectiveVectors.dimension_indices_homvars(x) ranges = first.(ranges_homvars) homvars = last.(ranges_homvars) MultiHomTotalDegreeSystemCache(B, Ĝ, R, S, ranges, homvars) end function evaluate!( u, F::MultiHomTotalDegreeSystem, z::ProjectiveVectors.PVector, cache::MultiHomTotalDegreeSystemCache{M}, ) where {M} D, C = F.D, F.C B, ranges, homvars = cache.B, cache.ranges, cache.homvars n = size(B, 2) @boundscheck checkbounds(u, 1:n) # Compute all bᵢⱼ and store in B # Since B is column major we store bᵢⱼ in B[j, i] @inbounds for i = 1:n for j = 1:M if D[j, i] != 0 bᵢⱼ = -zero(B[j, i]) for k in ranges[j] bᵢⱼ += C[k, i] * z[k] end B[j, i] = bᵢⱼ end end end @inbounds for i = 1:n gᵢ = one(eltype(u)) for j = 1:M dᵢⱼ, bᵢⱼ = D[j, i], B[j, i] if dᵢⱼ != 0 gᵢ *= bᵢⱼ^dᵢⱼ - z[homvars[j]]^dᵢⱼ end end u[i] = gᵢ * F.scaling_factors[i] end u end function evaluate(F::MultiHomTotalDegreeSystem, x, cache::MultiHomTotalDegreeSystemCache) evaluate!(similar(x, size(F, 1)), F, x, cache) end function jacobian!( U, F::MultiHomTotalDegreeSystem, z, cache::MultiHomTotalDegreeSystemCache{M}, ) where {M} evaluate_and_jacobian!(nothing, U, F, z, cache) U end function jacobian(F::MultiHomTotalDegreeSystem, x, cache::MultiHomTotalDegreeSystemCache) jacobian!(similar(x, size(F)), F, x, cache) end function evaluate_and_jacobian!( u, U, F::MultiHomTotalDegreeSystem, z, cache::MultiHomTotalDegreeSystemCache{M}, ) where {M} n, N = size(F) @boundscheck checkbounds(U, 1:n, 1:N) if u !== nothing @boundscheck checkbounds(u, 1:n) end D, C = F.D, F.C B, Ĝ, R, S, ranges, homvars = cache.B, cache.Ĝ, cache.R, cache.S, cache.ranges, cache.homvars n = size(B, 2) @inbounds for i = 1:n # Compute all bᵢⱼ and store in B # Since B is column major we store bᵢⱼ in B[j, i] for j = 1:M if D[j, i] != 0 bᵢⱼ = -zero(B[j, i]) for k in ranges[j] bᵢⱼ += C[k, i] * z[k] end B[j, i] = bᵢⱼ end end # Compute all ĝᵢⱼ and store in Ĝ # Since Ĝ is column major we store ĝᵢⱼ in Ĝ[j, i] for j = 1:M dᵢⱼ, bᵢⱼ = D[j, i], B[j, i] if dᵢⱼ == 0 Ĝ[j, i] = one(eltype(Ĝ)) else Ĝ[j, i] = bᵢⱼ^dᵢⱼ - z[homvars[j]]^dᵢⱼ end end # Accumulate subproducts forward R[1, i] = rᵢⱼ_prev = Ĝ[1, i] for j = 2:M if D[j, i] != 0 # otherwise Ĝ[j, i] = 1 R[j, i] = rᵢⱼ_prev = rᵢⱼ_prev * Ĝ[j, i] else R[j, i] = rᵢⱼ_prev end if u !== nothing u[i] = rᵢⱼ_prev * F.scaling_factors[i] end end # Accumulate subproducts backward S[M, i] = sᵢⱼ_prev = Ĝ[M, i] for j = M-1:-1:1 if D[j, i] != 0 # otherwise Ĝ[j, i] = 1 S[j, i] = sᵢⱼ_prev = sᵢⱼ_prev * Ĝ[j, i] else S[j, i] = sᵢⱼ_prev end end # Compute partial derivatives for j = 1:M dᵢⱼ = D[j, i] for k in ranges[j] c = C[k, i] if iszero(c) || iszero(dᵢⱼ) U[i, k] = zero(eltype(U)) else if dᵢⱼ == 1 u_ik = c else u_ik = dᵢⱼ * B[j, i]^(dᵢⱼ - 1) * c end if j > 1 u_ik *= R[j-1, i] end if j < M u_ik *= S[j+1, i] end U[i, k] = u_ik * F.scaling_factors[i] end end k = homvars[j] if iszero(dᵢⱼ) U[i, k] = zero(eltype(U)) else if dᵢⱼ == 1 u_ik = -dᵢⱼ else u_ik = -dᵢⱼ * z[k]^(dᵢⱼ - 1) end if j > 1 u_ik *= R[j-1, i] end if j < M u_ik *= S[j+1, i] end U[i, k] = u_ik * F.scaling_factors[i] end end end nothing end
using POMDPs using POMDPPolicies using POMDPModels using BeliefUpdaters using Random using Test using POMDPSimulators import POMDPLinter @testset "rollout" begin include("test_rollout.jl") end @testset "sim" begin include("test_sim.jl") end @testset "stepthrough" begin include("test_stepthrough.jl") end @testset "history_recorder" begin include("test_history_recorder.jl") end @testset "parallel" begin include("test_parallel.jl") end @testset "display" begin include("test_display.jl") end
[STATEMENT] lemma wnf_lemma_2: "(n(p * L) * n(q * L) \<squnion> an(r * L) * an(q * L)) * n(q * L) = n(p * L) * n(q * L)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (n (p * L) * n (q * L) \<squnion> an (r * L) * an (q * L)) * n (q * L) = n (p * L) * n (q * L) [PROOF STEP] by (metis an_mult_commutative n_mult_commutative wnf_lemma_1)
# generate sample data files for development library(detourr) set.seed(1) p <- animate_tour( tourr::flea, display = display_scatter(tour_aes(color = species, label = species)), tour_path = tourr::grand_tour(2) ) writeLines( jsonlite::toJSON(p$x, auto_unbox = TRUE, null = "null"), "../dev/display_scatter_2d/static/sample_data.json" ) set.seed(1) p <- animate_tour( tourr::flea, display = display_scatter(tour_aes(color = species, label = species)), tour_path = tourr::grand_tour(3) ) writeLines( jsonlite::toJSON(p$x, auto_unbox = TRUE, null = "null"), "../dev/display_scatter_3d/static/sample_data.json" )
State Before: ι : Type ?u.6042 X : Type u_2 E : Type u_1 inst✝⁷ : TopologicalSpace X inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : NormalSpace X inst✝³ : ParacompactSpace X inst✝² : TopologicalSpace E inst✝¹ : ContinuousAdd E inst✝ : ContinuousSMul ℝ E t : X → Set E ht : ∀ (x : X), Convex ℝ (t x) H : ∀ (x : X), ∃ U, U ∈ 𝓝 x ∧ ∃ g, ContinuousOn g U ∧ ∀ (y : X), y ∈ U → g y ∈ t y ⊢ ∃ g, ∀ (x : X), ↑g x ∈ t x State After: ι : Type ?u.6042 X : Type u_2 E : Type u_1 inst✝⁷ : TopologicalSpace X inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : NormalSpace X inst✝³ : ParacompactSpace X inst✝² : TopologicalSpace E inst✝¹ : ContinuousAdd E inst✝ : ContinuousSMul ℝ E t : X → Set E ht : ∀ (x : X), Convex ℝ (t x) U : X → Set X hU : ∀ (x : X), U x ∈ 𝓝 x g : X → X → E hgc : ∀ (x : X), ContinuousOn (g x) (U x) hgt : ∀ (x y : X), y ∈ U x → g x y ∈ t y ⊢ ∃ g, ∀ (x : X), ↑g x ∈ t x Tactic: choose U hU g hgc hgt using H State Before: ι : Type ?u.6042 X : Type u_2 E : Type u_1 inst✝⁷ : TopologicalSpace X inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : NormalSpace X inst✝³ : ParacompactSpace X inst✝² : TopologicalSpace E inst✝¹ : ContinuousAdd E inst✝ : ContinuousSMul ℝ E t : X → Set E ht : ∀ (x : X), Convex ℝ (t x) U : X → Set X hU : ∀ (x : X), U x ∈ 𝓝 x g : X → X → E hgc : ∀ (x : X), ContinuousOn (g x) (U x) hgt : ∀ (x y : X), y ∈ U x → g x y ∈ t y ⊢ ∃ g, ∀ (x : X), ↑g x ∈ t x State After: case intro ι : Type ?u.6042 X : Type u_2 E : Type u_1 inst✝⁷ : TopologicalSpace X inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : NormalSpace X inst✝³ : ParacompactSpace X inst✝² : TopologicalSpace E inst✝¹ : ContinuousAdd E inst✝ : ContinuousSMul ℝ E t : X → Set E ht : ∀ (x : X), Convex ℝ (t x) U : X → Set X hU : ∀ (x : X), U x ∈ 𝓝 x g : X → X → E hgc : ∀ (x : X), ContinuousOn (g x) (U x) hgt : ∀ (x y : X), y ∈ U x → g x y ∈ t y f : PartitionOfUnity X X univ hf : PartitionOfUnity.IsSubordinate f fun x => interior (U x) ⊢ ∃ g, ∀ (x : X), ↑g x ∈ t x Tactic: obtain ⟨f, hf⟩ := PartitionOfUnity.exists_isSubordinate isClosed_univ (fun x => interior (U x)) (fun x => isOpen_interior) fun x _ => mem_iUnion.2 ⟨x, mem_interior_iff_mem_nhds.2 (hU x)⟩ State Before: case intro ι : Type ?u.6042 X : Type u_2 E : Type u_1 inst✝⁷ : TopologicalSpace X inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : NormalSpace X inst✝³ : ParacompactSpace X inst✝² : TopologicalSpace E inst✝¹ : ContinuousAdd E inst✝ : ContinuousSMul ℝ E t : X → Set E ht : ∀ (x : X), Convex ℝ (t x) U : X → Set X hU : ∀ (x : X), U x ∈ 𝓝 x g : X → X → E hgc : ∀ (x : X), ContinuousOn (g x) (U x) hgt : ∀ (x y : X), y ∈ U x → g x y ∈ t y f : PartitionOfUnity X X univ hf : PartitionOfUnity.IsSubordinate f fun x => interior (U x) ⊢ ∃ g, ∀ (x : X), ↑g x ∈ t x State After: case intro ι : Type ?u.6042 X : Type u_2 E : Type u_1 inst✝⁷ : TopologicalSpace X inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : NormalSpace X inst✝³ : ParacompactSpace X inst✝² : TopologicalSpace E inst✝¹ : ContinuousAdd E inst✝ : ContinuousSMul ℝ E t : X → Set E ht : ∀ (x : X), Convex ℝ (t x) U : X → Set X hU : ∀ (x : X), U x ∈ 𝓝 x g : X → X → E hgc : ∀ (x : X), ContinuousOn (g x) (U x) hgt : ∀ (x y : X), y ∈ U x → g x y ∈ t y f : PartitionOfUnity X X univ hf : PartitionOfUnity.IsSubordinate f fun x => interior (U x) x i : X hi : ↑(PartitionOfUnity.toFun univ f i) x ≠ 0 ⊢ x ∈ U i Tactic: refine' ⟨⟨fun x => ∑ᶠ i, f i x • g i x, hf.continuous_finsum_smul (fun i => isOpen_interior) fun i => (hgc i).mono interior_subset⟩, fun x => f.finsum_smul_mem_convex (mem_univ x) (fun i hi => hgt _ _ _) (ht _)⟩ State Before: case intro ι : Type ?u.6042 X : Type u_2 E : Type u_1 inst✝⁷ : TopologicalSpace X inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : NormalSpace X inst✝³ : ParacompactSpace X inst✝² : TopologicalSpace E inst✝¹ : ContinuousAdd E inst✝ : ContinuousSMul ℝ E t : X → Set E ht : ∀ (x : X), Convex ℝ (t x) U : X → Set X hU : ∀ (x : X), U x ∈ 𝓝 x g : X → X → E hgc : ∀ (x : X), ContinuousOn (g x) (U x) hgt : ∀ (x y : X), y ∈ U x → g x y ∈ t y f : PartitionOfUnity X X univ hf : PartitionOfUnity.IsSubordinate f fun x => interior (U x) x i : X hi : ↑(PartitionOfUnity.toFun univ f i) x ≠ 0 ⊢ x ∈ U i State After: no goals Tactic: exact interior_subset (hf _ <| subset_closure hi)
/* * TargetPhrases.cpp * * Created on: 23 Oct 2015 * Author: hieu */ #include <cassert> #include <boost/foreach.hpp> #include "TargetPhrases.h" #include "TargetPhraseImpl.h" #include "../Phrase.h" #include "../TargetPhrase.h" using namespace std; namespace Moses2 { TargetPhrases::TargetPhrases(MemPool &pool, size_t size) : m_coll(pool, size), m_currInd(0) { } /* TargetPhrases::TargetPhrases(MemPool &pool, const System &system, const TargetPhrases &copy) :m_coll(pool, copy.m_coll.size()) { for (size_t i = 0; i < copy.m_coll.size(); ++i) { const TargetPhrase *tpOrig = copy.m_coll[i]; assert(tpOrig); const TargetPhrase *tpClone = new (pool.Allocate<TargetPhrase>()) TargetPhrase(pool, system, *tpOrig); m_coll[i] = tpClone; } } */ TargetPhrases::~TargetPhrases() { // TODO Auto-generated destructor stub } std::string TargetPhrases::Debug(const System &system) const { stringstream out; BOOST_FOREACH(const TargetPhraseImpl *tp, *this) { out << tp->Debug(system); out << endl; } return out.str(); } void TargetPhrases::SortAndPrune(size_t tableLimit) { iterator iterMiddle; iterMiddle = (tableLimit == 0 || m_coll.size() < tableLimit) ? m_coll.end() : m_coll.begin() + tableLimit; std::partial_sort(m_coll.begin(), iterMiddle, m_coll.end(), CompareScoreForPruning<TP>()); if (tableLimit && m_coll.size() > tableLimit) { m_coll.resize(tableLimit); } //cerr << "TargetPhrases=" << GetSize() << endl; } /* const TargetPhrases *TargetPhrases::Clone(MemPool &pool, const System &system) const { const TargetPhrases *ret = new (pool.Allocate<TargetPhrases>()) TargetPhrases(pool, system, *this); return ret; } */ }
If $A_1, A_2, \ldots$ are measurable sets with finite measure, and $\sum_{n=1}^\infty \mu(A_n) < \infty$, then $\mu(\bigcup_{n=1}^\infty A_n) < \infty$ and $\mu(\bigcup_{n=1}^\infty A_n) \leq \sum_{n=1}^\infty \mu(A_n)$.
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_SWAR_FUNCTIONS_CONTAINER_SPLIT_HPP_INCLUDED #define NT2_SWAR_FUNCTIONS_CONTAINER_SPLIT_HPP_INCLUDED #include <nt2/swar/functions/split.hpp> #include <nt2/include/functions/splat.hpp> #include <nt2/include/functions/run.hpp> #include <nt2/sdk/meta/downgrade.hpp> #include <nt2/sdk/meta/cardinal_of.hpp> #include <boost/mpl/comparison.hpp> #if 0 #include <nt2/include/functions/if_else.hpp> #include <nt2/include/functions/bitwise_and.hpp> #endif namespace nt2 { namespace ext { // can't statically know we have enough data for split #if 0 // split BOOST_DISPATCH_IMPLEMENT_IF ( run_, tag::cpu_ , (A0)(State)(Data)(X) , (boost::mpl::greater< boost::mpl::sizeof_<typename A0::value_type> , boost::mpl::sizeof_<typename boost::proto::result_of::child_c<A0&, 0>::value_type::value_type> > ) , ((node_<A0, nt2::tag::split_, boost::mpl::long_<1> , nt2::container::domain>)) (generic_< integer_<State> >) ((target_< simd_< unspecified_<Data>, X > >)) ) { typedef typename Data::type rvec; typedef typename meta::downgrade<rvec>::type vec; typedef rvec result_type; result_type operator()(A0& a0, State const& p, Data const& data) const { rvec r0, r1; nt2::split(nt2::run(boost::proto::child_c<0>(a0), p, meta::as_<vec>()), r0, r1); return if_else(p & meta::cardinal_of<vec>::value-1, r1, r0); } }; #endif BOOST_DISPATCH_IMPLEMENT ( run_, tag::cpu_ , (A0)(State)(Data) , ((node_<A0, nt2::tag::split_, boost::mpl::long_<1> , nt2::container::domain>)) (generic_< integer_<State> >) (target_< unspecified_<Data> >) ) { typedef typename Data::type result_type; result_type operator()(A0& a0, State const& p, Data const& data) const { typedef typename boost::proto::result_of::child_c<A0&, 0>::value_type child0; return nt2::splat<result_type>(nt2::run(boost::proto::child_c<0>(a0), p, boost::simd::ext::adapt_data<child0, Data>::call(data))); } }; } } #endif
[STATEMENT] lemma graph_plan_lemma_17: fixes as_1 as_2 as s assumes "(as_1 @ as_2 = as)" "(sat_precond_as s as)" shows "((sat_precond_as s as_1) \<and> sat_precond_as (exec_plan s as_1) as_2)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: as_1 @ as_2 = as sat_precond_as s as goal (1 subgoal): 1. sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] proof (induction as arbitrary: as_1 as_2 s) [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>as_1 as_2 s. \<lbrakk>as_1 @ as_2 = []; sat_precond_as s []\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 2. \<And>a as as_1 as_2 s. \<lbrakk>\<And>as_1 as_2 s. \<lbrakk>as_1 @ as_2 = as; sat_precond_as s as\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2; as_1 @ as_2 = a # as; sat_precond_as s (a # as)\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] case (Cons a as) [PROOF STATE] proof (state) this: \<lbrakk>?as_1.0 @ ?as_2.0 = as; sat_precond_as ?s as\<rbrakk> \<Longrightarrow> sat_precond_as ?s ?as_1.0 \<and> sat_precond_as (exec_plan ?s ?as_1.0) ?as_2.0 as_1 @ as_2 = a # as sat_precond_as s (a # as) goal (2 subgoals): 1. \<And>as_1 as_2 s. \<lbrakk>as_1 @ as_2 = []; sat_precond_as s []\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 2. \<And>a as as_1 as_2 s. \<lbrakk>\<And>as_1 as_2 s. \<lbrakk>as_1 @ as_2 = as; sat_precond_as s as\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2; as_1 @ as_2 = a # as; sat_precond_as s (a # as)\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<lbrakk>?as_1.0 @ ?as_2.0 = as; sat_precond_as ?s as\<rbrakk> \<Longrightarrow> sat_precond_as ?s ?as_1.0 \<and> sat_precond_as (exec_plan ?s ?as_1.0) ?as_2.0 as_1 @ as_2 = a # as sat_precond_as s (a # as) [PROOF STEP] show ?case [PROOF STATE] proof (prove) using this: \<lbrakk>?as_1.0 @ ?as_2.0 = as; sat_precond_as ?s as\<rbrakk> \<Longrightarrow> sat_precond_as ?s ?as_1.0 \<and> sat_precond_as (exec_plan ?s ?as_1.0) ?as_2.0 as_1 @ as_2 = a # as sat_precond_as s (a # as) goal (1 subgoal): 1. sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] proof(cases "as_1") [PROOF STATE] proof (state) goal (2 subgoals): 1. \<lbrakk>\<And>as_1 as_2 s. \<lbrakk>as_1 @ as_2 = as; sat_precond_as s as\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2; as_1 @ as_2 = a # as; sat_precond_as s (a # as); as_1 = []\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 2. \<And>aa list. \<lbrakk>\<And>as_1 as_2 s. \<lbrakk>as_1 @ as_2 = as; sat_precond_as s as\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2; as_1 @ as_2 = a # as; sat_precond_as s (a # as); as_1 = aa # list\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] case Nil [PROOF STATE] proof (state) this: as_1 = [] goal (2 subgoals): 1. \<lbrakk>\<And>as_1 as_2 s. \<lbrakk>as_1 @ as_2 = as; sat_precond_as s as\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2; as_1 @ as_2 = a # as; sat_precond_as s (a # as); as_1 = []\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 2. \<And>aa list. \<lbrakk>\<And>as_1 as_2 s. \<lbrakk>as_1 @ as_2 = as; sat_precond_as s as\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2; as_1 @ as_2 = a # as; sat_precond_as s (a # as); as_1 = aa # list\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] then [PROOF STATE] proof (chain) picking this: as_1 = [] [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: as_1 = [] goal (1 subgoal): 1. sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] using Cons.prems(1, 2) [PROOF STATE] proof (prove) using this: as_1 = [] as_1 @ as_2 = a # as sat_precond_as s (a # as) goal (1 subgoal): 1. sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] by auto [PROOF STATE] proof (state) this: sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 goal (1 subgoal): 1. \<And>aa list. \<lbrakk>\<And>as_1 as_2 s. \<lbrakk>as_1 @ as_2 = as; sat_precond_as s as\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2; as_1 @ as_2 = a # as; sat_precond_as s (a # as); as_1 = aa # list\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>aa list. \<lbrakk>\<And>as_1 as_2 s. \<lbrakk>as_1 @ as_2 = as; sat_precond_as s as\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2; as_1 @ as_2 = a # as; sat_precond_as s (a # as); as_1 = aa # list\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] case (Cons a list) [PROOF STATE] proof (state) this: as_1 = a # list goal (1 subgoal): 1. \<And>aa list. \<lbrakk>\<And>as_1 as_2 s. \<lbrakk>as_1 @ as_2 = as; sat_precond_as s as\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2; as_1 @ as_2 = a__ # as; sat_precond_as s (a__ # as); as_1 = aa # list\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] then [PROOF STATE] proof (chain) picking this: as_1 = a # list [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: as_1 = a # list goal (1 subgoal): 1. sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] using Cons.prems(1, 2) Cons.IH hd_append2 list.distinct(1) list.sel(1, 3) tl_append2 [PROOF STATE] proof (prove) using this: as_1 = a # list as_1 @ as_2 = a__ # as sat_precond_as s (a__ # as) \<lbrakk>?as_1.0 @ ?as_2.0 = as; sat_precond_as ?s as\<rbrakk> \<Longrightarrow> sat_precond_as ?s ?as_1.0 \<and> sat_precond_as (exec_plan ?s ?as_1.0) ?as_2.0 ?xs \<noteq> [] \<Longrightarrow> hd (?xs @ ?ys) = hd ?xs [] \<noteq> ?x21.0 # ?x22.0 hd (?x21.0 # ?x22.0) = ?x21.0 tl (?x21.0 # ?x22.0) = ?x22.0 ?xs \<noteq> [] \<Longrightarrow> tl (?xs @ ?ys) = tl ?xs @ ?ys goal (1 subgoal): 1. sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] by auto [PROOF STATE] proof (state) this: sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 goal (1 subgoal): 1. \<And>as_1 as_2 s. \<lbrakk>as_1 @ as_2 = []; sat_precond_as s []\<rbrakk> \<Longrightarrow> sat_precond_as s as_1 \<and> sat_precond_as (exec_plan s as_1) as_2 [PROOF STEP] qed auto
From MetaCoq.Template Require Import All Pretty. Require Import List String. Import ListNotations MonadNotation. Fixpoint tm_sequence {A: Type} (mvals: list (TemplateMonad A)) : TemplateMonad (list A) := match mvals with | [] => tmReturn [] | mval :: mvals => val <- mval;; vals <- tm_sequence mvals;; tmReturn (val :: vals) end. Fixpoint tm_mapM {A B: Type} (f: A -> TemplateMonad B) (l: list A) : TemplateMonad (list B) := match l with | [] => tmReturn [] | a :: l => b <- f a;; bs <- tm_mapM f l;; tmReturn (b :: bs) end. Fixpoint tm_foldM {A B: Type} (f: A -> B -> TemplateMonad A) (l: list B) (init: A) : TemplateMonad A := match l with | [] => tmReturn init | b :: l => init <- f init b;; tm_foldM f l init end. (** * Register a definition in the Coq environment given the quoted representation of its type and term. ** * This works with terms that contain holes (but the types must not, else Coq cannot infer all holes) *) Definition tmTypedDefinition (lem: string * term * term) : TemplateMonad unit := let '(name, typ_q, t_q) := lem in typ <- tmUnquoteTyped Type typ_q;; t <- tmUnquoteTyped typ t_q;; @tmDefinitionRed name (Some TemplateMonad.Common.hnf) typ t;; tmReturn tt. (* MetaCoq Run (tmTypedDefinition "mynatnil" <% list nat %> (tApp <% @nil %> [hole])). *) Definition locate_name (name: string) : TemplateMonad (string * term) := loc <- tmLocate1 name;; match loc with | IndRef ind => tmReturn (name, tInd ind []) | ConstructRef ind n => tmReturn (name, tConstruct ind n []) | ConstRef kn => tmReturn (name, tConst kn []) | _ => tmFail (String.append "unknown name or name is not an inductive/constructor/constant: " name) end. (* kind of works but it's not completely evaluated *) Definition my_print_term (t: term) : TemplateMonad unit := let s := print_term ([], Monomorphic_ctx (LevelSet.Mkt [], ConstraintSet.Mkt [])) [] false t in tmEval TemplateMonad.Common.all s >>= tmPrint.
A set $S$ has dimension $n-1$ if and only if there exists a nonzero vector $a$ such that $S$ is the set of all vectors $x$ such that $a \cdot x = 0$.
[GOAL] t : ℝ ⊢ t ∈ I ↔ 1 - t ∈ I [PROOFSTEP] rw [mem_Icc, mem_Icc] [GOAL] t : ℝ ⊢ 0 ≤ t ∧ t ≤ 1 ↔ 0 ≤ 1 - t ∧ 1 - t ≤ 1 [PROOFSTEP] constructor [GOAL] case mp t : ℝ ⊢ 0 ≤ t ∧ t ≤ 1 → 0 ≤ 1 - t ∧ 1 - t ≤ 1 [PROOFSTEP] intro [GOAL] case mpr t : ℝ ⊢ 0 ≤ 1 - t ∧ 1 - t ≤ 1 → 0 ≤ t ∧ t ≤ 1 [PROOFSTEP] intro [GOAL] case mp t : ℝ a✝ : 0 ≤ t ∧ t ≤ 1 ⊢ 0 ≤ 1 - t ∧ 1 - t ≤ 1 [PROOFSTEP] constructor [GOAL] case mpr t : ℝ a✝ : 0 ≤ 1 - t ∧ 1 - t ≤ 1 ⊢ 0 ≤ t ∧ t ≤ 1 [PROOFSTEP] constructor [GOAL] case mp.left t : ℝ a✝ : 0 ≤ t ∧ t ≤ 1 ⊢ 0 ≤ 1 - t [PROOFSTEP] linarith [GOAL] case mp.right t : ℝ a✝ : 0 ≤ t ∧ t ≤ 1 ⊢ 1 - t ≤ 1 [PROOFSTEP] linarith [GOAL] case mpr.left t : ℝ a✝ : 0 ≤ 1 - t ∧ 1 - t ≤ 1 ⊢ 0 ≤ t [PROOFSTEP] linarith [GOAL] case mpr.right t : ℝ a✝ : 0 ≤ 1 - t ∧ 1 - t ≤ 1 ⊢ t ≤ 1 [PROOFSTEP] linarith [GOAL] ⊢ 1 ∈ I [PROOFSTEP] constructor [GOAL] case left ⊢ 0 ≤ 1 [PROOFSTEP] norm_num [GOAL] case right ⊢ 1 ≤ 1 [PROOFSTEP] norm_num [GOAL] ⊢ ↑(σ 0) = ↑1 [PROOFSTEP] simp [symm] [GOAL] ⊢ ↑(σ 1) = ↑0 [PROOFSTEP] simp [symm] [GOAL] x : ↑I ⊢ ↑(σ (σ x)) = ↑x [PROOFSTEP] simp [symm] [GOAL] ⊢ CompactSpace ↑I [PROOFSTEP] infer_instance [GOAL] x : ↑I ⊢ 0 ≤ 1 - ↑x [PROOFSTEP] simpa using x.2.2 [GOAL] x : ↑I ⊢ 1 - ↑x ≤ 1 [PROOFSTEP] simpa using x.2.1 [GOAL] a t : ℝ ha : 0 < a ⊢ a * t ∈ I ↔ t ∈ Icc 0 (1 / a) [PROOFSTEP] constructor [GOAL] case mp a t : ℝ ha : 0 < a ⊢ a * t ∈ I → t ∈ Icc 0 (1 / a) [PROOFSTEP] rintro ⟨h₁, h₂⟩ [GOAL] case mpr a t : ℝ ha : 0 < a ⊢ t ∈ Icc 0 (1 / a) → a * t ∈ I [PROOFSTEP] rintro ⟨h₁, h₂⟩ [GOAL] case mp.intro a t : ℝ ha : 0 < a h₁ : 0 ≤ a * t h₂ : a * t ≤ 1 ⊢ t ∈ Icc 0 (1 / a) [PROOFSTEP] constructor [GOAL] case mpr.intro a t : ℝ ha : 0 < a h₁ : 0 ≤ t h₂ : t ≤ 1 / a ⊢ a * t ∈ I [PROOFSTEP] constructor [GOAL] case mp.intro.left a t : ℝ ha : 0 < a h₁ : 0 ≤ a * t h₂ : a * t ≤ 1 ⊢ 0 ≤ t [PROOFSTEP] exact nonneg_of_mul_nonneg_right h₁ ha [GOAL] case mp.intro.right a t : ℝ ha : 0 < a h₁ : 0 ≤ a * t h₂ : a * t ≤ 1 ⊢ t ≤ 1 / a [PROOFSTEP] rwa [le_div_iff ha, mul_comm] [GOAL] case mpr.intro.left a t : ℝ ha : 0 < a h₁ : 0 ≤ t h₂ : t ≤ 1 / a ⊢ 0 ≤ a * t [PROOFSTEP] exact mul_nonneg ha.le h₁ [GOAL] case mpr.intro.right a t : ℝ ha : 0 < a h₁ : 0 ≤ t h₂ : t ≤ 1 / a ⊢ a * t ≤ 1 [PROOFSTEP] rwa [le_div_iff ha, mul_comm] at h₂ [GOAL] t : ℝ ⊢ 2 * t - 1 ∈ I ↔ t ∈ Icc (1 / 2) 1 [PROOFSTEP] constructor [GOAL] case mp t : ℝ ⊢ 2 * t - 1 ∈ I → t ∈ Icc (1 / 2) 1 [PROOFSTEP] rintro ⟨h₁, h₂⟩ [GOAL] case mpr t : ℝ ⊢ t ∈ Icc (1 / 2) 1 → 2 * t - 1 ∈ I [PROOFSTEP] rintro ⟨h₁, h₂⟩ [GOAL] case mp.intro t : ℝ h₁ : 0 ≤ 2 * t - 1 h₂ : 2 * t - 1 ≤ 1 ⊢ t ∈ Icc (1 / 2) 1 [PROOFSTEP] constructor [GOAL] case mpr.intro t : ℝ h₁ : 1 / 2 ≤ t h₂ : t ≤ 1 ⊢ 2 * t - 1 ∈ I [PROOFSTEP] constructor [GOAL] case mp.intro.left t : ℝ h₁ : 0 ≤ 2 * t - 1 h₂ : 2 * t - 1 ≤ 1 ⊢ 1 / 2 ≤ t [PROOFSTEP] linarith [GOAL] case mp.intro.right t : ℝ h₁ : 0 ≤ 2 * t - 1 h₂ : 2 * t - 1 ≤ 1 ⊢ t ≤ 1 [PROOFSTEP] linarith [GOAL] case mpr.intro.left t : ℝ h₁ : 1 / 2 ≤ t h₂ : t ≤ 1 ⊢ 0 ≤ 2 * t - 1 [PROOFSTEP] linarith [GOAL] case mpr.intro.right t : ℝ h₁ : 1 / 2 ≤ t h₂ : t ≤ 1 ⊢ 2 * t - 1 ≤ 1 [PROOFSTEP] linarith [GOAL] x : ↑unitInterval ⊢ 0 ≤ ↑x [PROOFSTEP] unit_interval [GOAL] 𝕜 : Type u_1 inst✝² : LinearOrderedField 𝕜 inst✝¹ : TopologicalSpace 𝕜 inst✝ : TopologicalRing 𝕜 a b : 𝕜 h : 0 < a ⊢ ↑(affineHomeomorph a b (_ : a ≠ 0)) '' Icc 0 1 = Icc b (a + b) [PROOFSTEP] simp [h] [GOAL] 𝕜 : Type u_1 inst✝² : LinearOrderedField 𝕜 inst✝¹ : TopologicalSpace 𝕜 inst✝ : TopologicalRing 𝕜 a b : 𝕜 h : a < b ⊢ ↑(Icc a b) ≃ₜ ↑(Icc 0 1) [PROOFSTEP] let e := Homeomorph.image (affineHomeomorph (b - a) a (sub_pos.mpr h).ne.symm) (Set.Icc 0 1) [GOAL] 𝕜 : Type u_1 inst✝² : LinearOrderedField 𝕜 inst✝¹ : TopologicalSpace 𝕜 inst✝ : TopologicalRing 𝕜 a b : 𝕜 h : a < b e : ↑(Icc 0 1) ≃ₜ ↑(↑(affineHomeomorph (b - a) a (_ : b - a ≠ 0)) '' Icc 0 1) := Homeomorph.image (affineHomeomorph (b - a) a (_ : b - a ≠ 0)) (Icc 0 1) ⊢ ↑(Icc a b) ≃ₜ ↑(Icc 0 1) [PROOFSTEP] refine' (e.trans _).symm [GOAL] 𝕜 : Type u_1 inst✝² : LinearOrderedField 𝕜 inst✝¹ : TopologicalSpace 𝕜 inst✝ : TopologicalRing 𝕜 a b : 𝕜 h : a < b e : ↑(Icc 0 1) ≃ₜ ↑(↑(affineHomeomorph (b - a) a (_ : b - a ≠ 0)) '' Icc 0 1) := Homeomorph.image (affineHomeomorph (b - a) a (_ : b - a ≠ 0)) (Icc 0 1) ⊢ ↑(↑(affineHomeomorph (b - a) a (_ : b - a ≠ 0)) '' Icc 0 1) ≃ₜ ↑(Icc a b) [PROOFSTEP] apply Homeomorph.setCongr [GOAL] case h 𝕜 : Type u_1 inst✝² : LinearOrderedField 𝕜 inst✝¹ : TopologicalSpace 𝕜 inst✝ : TopologicalRing 𝕜 a b : 𝕜 h : a < b e : ↑(Icc 0 1) ≃ₜ ↑(↑(affineHomeomorph (b - a) a (_ : b - a ≠ 0)) '' Icc 0 1) := Homeomorph.image (affineHomeomorph (b - a) a (_ : b - a ≠ 0)) (Icc 0 1) ⊢ ↑(affineHomeomorph (b - a) a (_ : b - a ≠ 0)) '' Icc 0 1 = Icc a b [PROOFSTEP] rw [affineHomeomorph_image_I _ _ (sub_pos.2 h)] [GOAL] case h 𝕜 : Type u_1 inst✝² : LinearOrderedField 𝕜 inst✝¹ : TopologicalSpace 𝕜 inst✝ : TopologicalRing 𝕜 a b : 𝕜 h : a < b e : ↑(Icc 0 1) ≃ₜ ↑(↑(affineHomeomorph (b - a) a (_ : b - a ≠ 0)) '' Icc 0 1) := Homeomorph.image (affineHomeomorph (b - a) a (_ : b - a ≠ 0)) (Icc 0 1) ⊢ Icc a (b - a + a) = Icc a b [PROOFSTEP] simp
[STATEMENT] lemma rel_interior_UNIV [simp]: "rel_interior (UNIV :: ('n::euclidean_space) set) = UNIV" [PROOF STATE] proof (prove) goal (1 subgoal): 1. rel_interior UNIV = UNIV [PROOF STEP] by (metis open_UNIV rel_interior_open)
# This file is a part of Julia. License is MIT: https://julialang.org/license "TOML Table" struct Table values::Dict{String,Any} defined::Bool end Table(defined::Bool) = Table(Dict{String,Any}(), defined) function Base.show(io::IO, tbl::Table, level::Int=1) Base.print(io, "T($(tbl.defined)){\n") for (k,v) in tbl.values Base.print(io, "\t"^level, k, " => ") if isa(v, Table) Base.show(io, v, level+1) Base.print(io, "\n") elseif isa(v, Vector{Table}) Base.print(io, "[\n") for i in 1:length(v) Base.print(io, "\t"^level, " ") Base.show(io, v[i], level+1) i != length(v) && Base.print(io, ",\n") end Base.print("\t"^level, "]\n") else Base.print(io, " $v\n") end end Base.print(io, "\t"^(level-1), "}\n") end Base.getindex(tbl::Table, key::AbstractString) = tbl.values[key] Base.haskey(tbl::Table, key::AbstractString) = haskey(tbl.values ,key) "Parser error exception" struct ParserError <: Exception lo::Int hi::Int msg::String end "TOML Parser" mutable struct Parser{IO_T <: IO} input::IO_T errors::Vector{ParserError} charbuffer::Base.GenericIOBuffer{Array{UInt8,1}} currentchar::Char Parser(input::IO_T) where {IO_T <: IO} = new{IO_T}(input, ParserError[], IOBuffer(), ' ') end Parser(input::String) = Parser(IOBuffer(input)) Base.error(p::Parser, l, h, msg) = push!(p.errors, ParserError(l, h, msg)) Base.eof(p::Parser) = eof(p.input) Base.position(p::Parser) = Int(position(p.input))+1 Base.write(p::Parser, x) = write(p.charbuffer, x) Base.read(p::Parser) = p.currentchar = read(p.input, Char) NONE() = nothing NONE(::Type{T}) where {T} = nothing SOME(v::T) where {T} = v NONE(::Type{String}, p::Parser) = (take!(p.charbuffer); nothing) SOME(::Type{String}, p::Parser) = String(take!(p.charbuffer)) isnull(x) = x === nothing get(x) = (@assert !isnull(x); x) "Rewind parser input on `n` characters." function rewind(p::Parser, n=1) pos = position(p.input) pos == 0 && return 0 skip(p.input, -n) return Int(position(p.input)) end "Converts an offset to a line and a column in the original source." function linecol(p::Parser, offset::Int) pos = position(p) seekstart(p.input) line = 0 cur = 1 for (i,l) in enumerate(eachline(p.input, chomp=false)) if cur + length(l) > offset return (i, offset - cur + 1) end cur += length(l) line+=1 end seek(p.input, pos) return (line, 0) end "Determine next position in parser input" function nextpos(p::Parser) pos = position(p) return pos + 1 end "Peeks ahead `n` characters" function peek(p::Parser) #, i::Int=0 eof(p) && return nothing res = Base.peek(p.input) res == -1 && return nothing return Char(res) end "Returns `true` and consumes the next character if it matches `ch`, otherwise do nothing and return `false`" function consume(p::Parser, ch::AbstractChar) eof(p) && return false c = peek(p) if get(c) == ch read(p) return true else return false end end function expect(p::Parser, ch::AbstractChar) consume(p, ch) && return true lo = position(p) if eof(p) error(p, lo, lo, "expected `$ch`, but found EOF") else v = peek(p) mark(p.input) c = read(p) error(p, lo, lo+1, "expected `$ch`, but found `$c`") reset(p.input) end return false end "Consumes whitespace ('\t' and ' ') until another character (or EOF) is reached. Returns `true` if any whitespace was consumed" function whitespace(p::Parser) ret = false while !eof(p) c = read(p) if c == '\t' || c == ' ' ret = true else rewind(p) break end end return ret end "Consumes the rest of the line after a comment character" function comment(p::Parser) !consume(p, '#') && return false while !eof(p) ch = read(p) ch == '\n' && break end return true end "Consumes a newline if one is next" function newline(p::Parser) if !eof(p) n = 1 ch = read(p.input, UInt8) ch == 0x0a && return true if ch == 0x0d if !eof(p) nch = read(p.input, UInt8) nch == 0x0a && return true n+=1 end end rewind(p, n) end return false end "Consume ignored symbols" function ignore(p::Parser) while true whitespace(p) !newline(p) && !comment(p) && break end end "Parse a single key name starting at next position" function keyname(p) s = nextpos(p) key = if consume(p, '"') basicstring(p, s, false) elseif consume(p, '\'') literalstring(p, s, false) else while !eof(p) ch = read(p) if 'a' <= ch <= 'z' || 'A' <= ch <= 'Z' || isdigit(ch) || ch == '_' || ch == '-' write(p, ch) else rewind(p) break end end SOME(String, p) end if !isnull(key) && isempty(get(key)) error(p, s, s, "expected a key but found an empty string") key = NONE(String, p) end return key end "Parse a path into a vector of paths" function lookup(p::Parser) ks = String[] eof(p) && return SOME(ks) while true whitespace(p) s = keyname(p) if !isnull(s) push!(ks, get(s)) else s = integer(p, 0) if !isnull(s) push!(ks, get(s)) else return NONE() end end whitespace(p) !expect(p, '.') && return SOME(ks) end end "Parses a key-value separator" function separator(p::Parser) whitespace(p) !expect(p, '=') && return false whitespace(p) return true end "Insert key-value pair to table, if duplicate key found reports error" function insertpair(p::Parser, tbl::Table, k, v, st) if haskey(tbl, k) error(p, st, st+length(k), "duplicate key `$k`") else tbl.values[k] = v end end "Parses integer with leading zeros and sign" function integer(p::Parser, st::Int, allow_leading_zeros::Bool=false, allow_sign::Bool=false) if allow_sign if consume(p, '-') write(p, '-') elseif consume(p, '+') write(p, '+') end end nch = peek(p) if isnull(nch) pos = nextpos(p) error(p, pos, pos, "expected start of a numeric literal") return NONE(String, p) else ch = get(nch) if isdigit(ch) c = read(p) if c == '0' && !allow_leading_zeros write(p, '0') nch = peek(p) if !isnull(nch) ch = get(nch) if isdigit(ch) error(p, st, position(p), "leading zeroes are not allowed") return NONE(String, p) end end elseif isdigit(c) write(p, c) end else # non-digit error(p, st, position(p), "expected a digit, found `$ch`") return NONE(String, p) end end underscore = false while !eof(p) ch = read(p) if isdigit(ch) write(p, ch) underscore = false elseif ch == '_' && !underscore underscore = true else rewind(p) break end end if underscore pos = nextpos(p) error(p, pos, pos, "numeral cannot end with an underscore") NONE(String, p) else p.charbuffer.ptr == 1 ? NONE(String, p) : SOME(String, p) end end "Parses boolean" function boolean(p::Parser, st::Int) ch = '\x00' i = 0 word = "true" while !eof(p) && i<length(word) ch = read(p) i+=1 ch != word[i] && break end if i == length(word) return SOME(true) else rewind(p, i) end ti = i tch = ch i = 0 word = "false" while !eof(p) && i<length(word) ch = read(p) i+=1 ch != word[i] && break end if i == length(word) return SOME(false) else rewind(p, i) if i < ti i = ti ch = tch end error(p, st, st+i-1, "unexpected character: `$ch`") end return NONE(Bool) end "Parse number or datetime" function numdatetime(p::Parser, st::Int) isfloat = false nprefix = integer(p, st, false, true) isnull(nprefix) && return NONE() prefix = get(nprefix) decimal = if consume(p, '.') isfloat = true ndecimal = integer(p, st, true, false) isnull(ndecimal) && return NONE() SOME(get(ndecimal)) else NONE(String, p) end exponent = if consume(p,'e') || consume(p,'E') isfloat = true; nexponent = integer(p, st, false, true) isnull(nexponent) && return NONE() SOME(get(nexponent)) else NONE(String, p) end pend = nextpos(p) nch = peek(p) ret = if isnull(decimal) && isnull(exponent) && nch != '+' && nch != '+' && st + 4 == pend && consume(p, '-') datetime(p, prefix, st) else input = if isnull(decimal) && isnull(exponent) #!isfloat prefix elseif !isnull(decimal) && isnull(exponent) "$(prefix)."*get(decimal,"") elseif isnull(decimal) && !isnull(exponent) "$(prefix)E"*get(exponent,"") elseif !isnull(decimal) && !isnull(exponent) "$(prefix)."*get(decimal,"")*"E"*get(exponent,"") end input = lstrip(input, '+') try SOME(Base.parse(isfloat ? Float64 : Int, input)) catch NONE() end end isnull(ret) && error(p, st, pend, "invalid numeric literal") return ret end "Parses a datetime value" function datetime(p::Parser, syear::String, st::Int) valid = true function parsetwodigits(p, valid) eof(p) && return 0, false ch1 = read(p) valid = valid && isdigit(ch1) eof(p) && return 0, false ch2 = read(p) valid = valid && isdigit(ch2) (valid ? Base.parse(Int, String([ch1, ch2])) : 0), valid end year = Base.parse(Int, syear) month, valid = parsetwodigits(p, valid) valid = valid && consume(p, '-') day, valid = parsetwodigits(p, valid) valid = valid && consume(p, 'T') hour, valid = parsetwodigits(p, valid) valid = valid && consume(p, ':') minute, valid = parsetwodigits(p, valid) valid = valid && consume(p, ':') second, valid = parsetwodigits(p, valid) # fractional seconds msec = 0 if consume(p, '.') fsec = Char[] ch = peek(p) valid = valid && !isnull(ch) && isdigit(get(ch)) while true ch = peek(p) if !isnull(ch) && isdigit(get(ch)) push!(fsec, read(p)) else break end end if length(fsec)>0 msec = Base.parse(Int, String(fsec)) end end # time zone tzhour=0 tzminute=0 tzplus = true tzminus = false tzsign = true if valid && !consume(p, 'Z') tzplus = consume(p, '+') if !tzplus tzminus = consume(p, '-') end valid = valid && (tzplus || tzminus) tzhour, valid = parsetwodigits(p, valid) valid = valid && consume(p, ':') tzminute, valid = parsetwodigits(p, valid) tzsign = tzplus end if valid dt = DateTime(year, month, day, hour + (tzsign ? tzhour : -tzhour), minute + (tzsign ? tzminute : -tzminute), second, msec) return SOME(dt) else error(p, st, position(p), "malformed date literal") return NONE() end end "Parses a single or multi-line string" function basicstring(p::Parser, st::Int) !expect(p, '"') && return NONE(String, p) multiline = false if consume(p, '"') if consume(p, '"') multiline = true newline(p) else return SOME("") end end basicstring(p, st, multiline) end "Finish parsing a basic string after the opening quote has been seen" function basicstring(p::Parser, st::Int, multiline::Bool) while true while multiline && newline(p) write(p, '\n') end if eof(p) pos = position(p) error(p, st, pos, "unterminated string literal") return NONE(String, p) else ch = read(p) if ch == '"' if multiline if !consume(p, '"') write(p, '"') continue end if !consume(p, '"') write(p, '"') write(p, '"') continue end end return SOME(String, p) elseif ch == '\\' pos = position(p) ec = escape(p, pos, multiline) !isnull(ec) && write(p, get(ec)) elseif ch < '\x1f' pos = position(p) error(p, st, pos, "control character `$ch` must be escaped") else write(p, ch) end end end end "Reads character(s) after `\\` and transforms them into proper character" function escape(p::Parser, st::Int, multiline::Bool) if multiline && newline(p) while whitespace(p) || newline(p) end return NONE() end pos = position(p) if eof(p) error(p, st, pos, "unterminated escape sequence") return NONE() else ch = read(p) if ch == 'b' SOME('\b') elseif ch == 't' SOME('\t') elseif ch == 'n' SOME('\n') elseif ch == 'f' SOME('\f') elseif ch == 'r' SOME('\r') elseif ch == '"' SOME('\"') elseif ch == '\\' SOME('\\') elseif ch == 'u' || ch == 'U' len = ch == 'u' ? 4 : 8 ucstr = ch == 'u' ? "\\u" : "\\U" snum = String(read(p.input, len)) try if length(snum) < len error(p, st, st+len, "expected $len hex digits after a `$ch` escape") NONE() end if !all(isxdigit, snum) error(p, st, st+len, "unknown string escape: `$snum`") NONE() end c = unescape_string(ucstr * snum)[1] SOME(c) catch error(p, st, st+len, "codepoint `$snum` is not a valid unicode codepoint") rewind(p, len) NONE() end else error(p, st, position(p), "unknown string escape: `$("\\x"*hex(ch,2))`") NONE() end end end "Parses a single or multi-line literal string" function literalstring(p::Parser, st::Int) !expect(p, '\'') && return NONE(String, p) multiline = false if consume(p, '\'') if consume(p, '\'') multiline = true newline(p) else return SOME("") end end literalstring(p, st, multiline) end function literalstring(p::Parser, st::Int, multiline::Bool) while true if !multiline && newline(p) npos = nextpos(p) error(p, st, npos, "literal strings cannot contain newlines") return NONE(String, p) end if eof(p) error(p, st, position(p), "unterminated string literal") return NONE(String, p) else ch = read(p.input, UInt8) if ch == 0x27 if multiline if !consume(p, '\'') write(p, 0x27) continue end if !consume(p, '\'') write(p, 0x27) write(p, 0x27) continue end end return SOME(String, p) else write(p, ch) end end end end function array(p::Parser, st::Int) !expect(p, '[') && return NONE() ret = Any[] rettype = Any expected = Any while true # Break out early if we see the closing bracket ignore(p) consume(p, ']') && return SOME(ret) # Attempt to parse a value, triggering an error if it's the wrong type. pstart = nextpos(p) npvalue = value(p) isnull(npvalue) && return NONE() pvalue = get(npvalue) pend = nextpos(p) valtype = isa(pvalue, Array) ? Array : typeof(pvalue) expected = rettype === Any ? valtype : expected if valtype != expected error(p, pstart, pend, "expected type `$expected`, found type `$valtype`") else rettype = expected push!(ret, pvalue) end # Look for a comma. If we don't find one we're done ignore(p) !consume(p, ',') && break end ignore(p) !expect(p, ']') && return NONE() return SOME(convert(Vector{rettype}, ret)) end function inlinetable(p::Parser, st::Int) !expect(p, '{') && return NONE() whitespace(p) ret = Table(true) consume(p, '}') && return SOME(ret) while true npos = nextpos(p) k = keyname(p) isnull(k) && return NONE() !separator(p) && return NONE() v = value(p) isnull(v) && return NONE() insertpair(p, ret, get(k), get(v), npos) whitespace(p) consume(p, '}') && break !expect(p, ',') && return NONE() whitespace(p) end return SOME(ret) end "Parses a value" function value(p::Parser) whitespace(p) c = peek(p) isnull(c) && return NONE() ch = get(c) pos = position(p)+1 if ch == '"' return basicstring(p, pos) elseif ch == '\'' return literalstring(p, pos) elseif ch == 't' || ch == 'f' return boolean(p, pos) elseif ch == '[' return array(p, pos) elseif ch == '{' return inlinetable(p, pos) elseif ch == '-' || ch == '+' || isdigit(ch) return numdatetime(p, pos) else error(p, pos, pos+1, "expected a value") return NONE() end end "Parses the key-values and fills the given dictionary. Returns true in case of success and false in case of error." function keyvalues(p::Parser, tbl::Table) while true whitespace(p) newline(p) && continue comment(p) && continue nc = peek(p) isnull(nc) && break get(nc) == '[' && break # get key klo = nextpos(p) k = keyname(p) isnull(k) && return false # skip kv separator !separator(p) && return false # get value v = value(p) isnull(v) && return false vend = nextpos(p) # insert kv into result table insertpair(p, tbl, get(k), get(v), klo) whitespace(p) if !comment(p) && !newline(p) pc = peek(p) isnull(pc) && return true error(p, klo, vend, "expected a newline after a key") return false end end return true end "Construct nested structures from keys" function nested(p, into, ks, kstart) cnode = into kend = 0 for k in ks[1:end-1] kend += length(k)+1 if !haskey(cnode, k) cnode.values[k] = Table(false) cnode = cnode[k] else tmp = cnode[k] if isa(tmp, Table) cnode = tmp elseif isa(tmp, Array) if length(tmp)>0 && typeof(tmp[end]) === Table cnode = tmp[end] else error(p, kstart, kstart+kend, "array `$k` does not contain tables") return NONE(), kend end else error(p, kstart, kstart+kend, "key `$k` was not previously a table") return NONE(), kend end end end return SOME(cnode), kend end function addtable(p::Parser, into::Table, ks::Vector{String}, tbl::Table, kstart) cnode, kend = nested(p, into, ks, kstart) isnull(cnode) && return cur = get(cnode) # fill last level with values tkey = ks[end] if haskey(cur, tkey) ctbl = cur[tkey] if isa(ctbl, Table) ctbl.defined && error(p, kstart, kstart+kend+length(tkey), "redefinition of table `$tkey`") for (k,v) in tbl.values insertpair(p, ctbl, k, v, kstart) end else error(p, kstart, kstart+kend+length(tkey), "key `$tkey` was not previously a table") end else cur.values[tkey] = tbl end end function addarray(p::Parser, into::Table, ks::Vector{String}, val, kstart) cnode, kend = nested(p, into, ks, kstart) isnull(cnode) && return cur = get(cnode) akey = ks[end] if haskey(cur, akey) vec = cur[akey] if isa(vec, Array) if isa(val, eltype(vec)) push!(vec, val) else error(p, kstart, kstart+kend+length(akey), "expected type `$(typeof(val))`, found type `$(eltype(vec))`") end else error(p, kstart, kstart+kend+length(akey), "key `$akey` was previously not an array") end else cur.values[akey] = Any[val] end end """Executes the parser, parsing the string contained within. This function will return the `Table` instance if parsing is successful, or it will return `nothing` if any parse error or invalid TOML error occurs. If an error occurs, the `errors` field of this parser can be consulted to determine the cause of the parse failure. """ function parse(p::Parser) ret = Table(false) while !eof(p) whitespace(p) newline(p) && continue comment(p) && continue # parse section if consume(p, '[') arr = consume(p, '[') npos = nextpos(p) # parse the name of the section ks = String[] while true whitespace(p) s = keyname(p) !isnull(s) && push!(ks, get(s)) whitespace(p) if consume(p, ']') arr && !expect(p, ']') && return NONE(Table) break end !expect(p, '.') && return NONE() end isempty(ks) && return NONE(Table) # build the section section = Table(true) !keyvalues(p, section) && return NONE(Table) if arr addarray(p, ret, ks, section, npos) else addtable(p, ret, ks, section, npos) end else !keyvalues(p, ret) && return NONE(Table) end end length(p.errors) != 0 && return NONE(Table) return SOME(ret) end
# using CytofResearch # using Distributions # using Flux, Flux.Tracker include(joinpath(@__DIR__, "util.jl")) include(joinpath(@__DIR__, "logprob_lam.jl")) function sample_lam(state::CytofResearch.VB.StateMP, y::Vector{Matrix{Float64}}, c::CytofResearch.VB.Constants) _, s, ys, _ = CytofResearch.VB.rsample(state, y, c) lp_lam= logprob_lam(data(s), Tracker.data.(ys), c) lam = [[CytofResearch.MCMC.wsample_logprob(lp_lam[i][n, :]) for n in 1:c.N[i]] for i in 1:c.I] # Relabel noisy class as 0 for i in 1:c.I for n in 1:c.N[i] if lam[i][n] > c.K lam[i][n] = 0 end end end return Vector{Int8}.(lam) end VV = Vector{Vector{I}} where I VVV = Vector{VV{I}} where I function lam_f(lam_samps::VVV{T}, i::Integer, n::Integer, f::Function) where {T <: Integer} B = length(lam_samps) return f(lam_samps[b][i][n] for b in 1:B) end function lam_f(lam_samps::VVV{T}, f::Function) where {T <: Integer} I = length(lam_samps[1]) N = length.(lam_samps[1]) B = length(lam_samps) return [[lam_f(lam_samps, i, n, f) for n in 1:N[i]] for i in 1:I] end
Victor (Eric Braeden) takes a page from Fred Sanford in faking a sick spell to try to get out of trouble this week on The Young and the Restless. Too bad his loved ones — not to mention the police — aren&apos;t buying what the mogul is selling. Nikki (Melody Thomas Scott) is the first Newman to call b.s. following Victor&apos;s "dizzy spell". However, it&apos;s doctor son-in-law Stitch (Sean Carrigan) who confirms the patriarch is perfectly healthy. Will Victor once again weasel out of paying for his crimes against the Abbotts? Watch the video below then sound off in the comments!
import ..prooflab import lectures.lec6_proposition import data.real.basic import data.complex.exponential /-! # Homework 4: ... Homework must be done individually. Replace the placeholders (e.g., `:= sorry`) with your solutions. You are allowed to use all the tactics we have learned so far. Pro Tip: Don't forget you know the tactics `linarith` and `ring`! -/ namespace PROOFS variables {P Q R : Prop} /-! ## Question 1 (20 points): Give a proof of the proposition `(P ∧ R) → (R → P → Q) → Q`. -/ example : (P ∧ R) → (R → P → Q) → Q := begin sorry, end /-! ## Question 2 (20 points): Prove the implication `m * n - m - n + 1 = 1 → (m = 2) ∧ (n = 2)` for natural numbers `m` and `n` by filling in `sorry` placeholders below. You need to use the lemma `mul_eq_one_of_pos_of_pos` in below which says if the multiplication of two positive integers is `1` then both of them must be `1`. Notice that we did not provide the proof of this lemma here, and __you don't need to provide it either__. We will construct a proof of this lemma in the next lecture. -/ -- no need to solve the following, just use it in the next proof lemma mul_eq_one_of_pos_of_pos (m n : ℤ) (h : m * n = 1) : (0 < m ∧ 0 < n) → (m = 1 ∧ n = 1) := begin sorry, end -- give a proof of this one using the lemma above. example (m n : ℤ) : m * n - m - n + 1 = 1 → (1 < m ∧ 1 < n) → (m = 2) ∧ (n = 2) := begin sorry, end /-! ## Question 3 (20 points): Construct a proof of the proposition `abs (2 * x - 1) < 5 → -2 < x `. You are allowed to use the lemma `abs_lt`. -/ section variables a b : ℝ #check (abs_lt : |a| < b ↔ -b < a ∧ a < b) end example (x y : ℝ) : abs (2 * x - 1) < 5 → -2 < x := begin sorry, end /-! ## Question 4 (20 points): For `x : ℝ`, the term `real.exp x` encodes the exponential e^x. -/ section variables a b c : ℝ #check (real.exp_le_exp.mpr : a ≤ b → real.exp a ≤ real.exp b) end example (a b c : ℝ) (h : 1 ≤ a ∧ b ≤ c) : 2 + a + real.exp b ≤ 3 * a + real.exp c := begin sorry, end /-! ## Question 5 (20 points): Prove the following statement. You might like to use any of the following lemmas (most likely you need only some of them not all.): - `abs_mul` - `abs_lt`. - `abs_nonneg` - `abs_pos` - `real_le_of_mul_nonneg_left` - `real_lt_of_mul_pos_right` - `real_le_mul_right` -/ section variables a b : ℝ #check (abs_mul a b : |a * b| = |a| * |b|) #check (abs_lt : |a| < b ↔ -b < a ∧ a < b) end lemma real_le_of_mul_nonneg_left {a b c : ℝ} (h₀ : a < b) (h₁ : 0 ≤ c): c * a ≤ c * b := begin apply mul_le_mul_of_nonneg_left, { apply le_of_lt, apply h₀, }, { apply h₁, }, end lemma real_lt_of_mul_pos_right {a b c : ℝ} (h₀ : a < b) (h₁ : 0 < c): a * c < b * c := begin rw mul_comm a c, rw mul_comm b c, apply mul_lt_mul_of_pos_left, assumption', end lemma real_le_mul_right {a b c : ℝ} (h₀ : a ≤ b) (h₁ : 0 < c): a * c ≤ b * c := begin apply (mul_le_mul_right h₁).mpr, assumption, end #check abs_nonneg example (x y ε : ℝ) : (0 < ε ∧ ε ≤ 1) → (abs x < ε ∧ abs y < ε) → abs (x * y) < ε := begin sorry, end end PROOFS
(* Title: Jive Data and Store Model Author: Norbert Schirmer <schirmer at informatik.tu-muenchen.de>, 2003 Maintainer: Nicole Rauch <rauch at informatik.uni-kl.de> License: LGPL *) section \<open>Attributes\<close> theory Attributes imports "../Isabelle/Subtype" begin text \<open>This theory has to be generated as well for each program under verification. It defines the attributes of the classes and various functions on them. \<close> datatype AttId = CounterImpl'value | UndoCounter'save | Dummy'dummy | Counter'dummy text \<open>The last two entries are only added to demonstrate what is to happen with attributes of abstract classes and interfaces.\<close> text \<open>It would be nice if attribute names were generated in a way that keeps them short, so that the proof state does not get unreadable because of fancy long names. The generation of attribute names that is performed by the Jive tool should only add the definition class if necessary, i.e.~if there would be a name clash otherwise. For the example above, the class names are not necessary. One must be careful, though, not to generate names that might clash with names of free variables that are used subsequently. \<close> text \<open>The domain type of an attribute is the definition class (or interface) of the attribute.\<close> definition dtype:: "AttId \<Rightarrow> Javatype" where "dtype f = (case f of CounterImpl'value \<Rightarrow> CClassT CounterImpl | UndoCounter'save \<Rightarrow> CClassT UndoCounter | Dummy'dummy \<Rightarrow> AClassT Dummy | Counter'dummy \<Rightarrow> InterfaceT Counter)" lemma dtype_simps [simp]: "dtype CounterImpl'value = CClassT CounterImpl" "dtype UndoCounter'save = CClassT UndoCounter" "dtype Dummy'dummy = AClassT Dummy" "dtype Counter'dummy = InterfaceT Counter" by (simp_all add: dtype_def dtype_def dtype_def) text \<open>For convenience, we add some functions that directly apply the selectors of the datatype @{typ Javatype}. \<close> definition cDTypeId :: "AttId \<Rightarrow> CTypeId" where "cDTypeId f = (case f of CounterImpl'value \<Rightarrow> CounterImpl | UndoCounter'save \<Rightarrow> UndoCounter | Dummy'dummy \<Rightarrow> undefined | Counter'dummy \<Rightarrow> undefined )" definition aDTypeId:: "AttId \<Rightarrow> ATypeId" where "aDTypeId f = (case f of CounterImpl'value \<Rightarrow> undefined | UndoCounter'save \<Rightarrow> undefined | Dummy'dummy \<Rightarrow> Dummy | Counter'dummy \<Rightarrow> undefined )" definition iDTypeId:: "AttId \<Rightarrow> ITypeId" where "iDTypeId f = (case f of CounterImpl'value \<Rightarrow> undefined | UndoCounter'save \<Rightarrow> undefined | Dummy'dummy \<Rightarrow> undefined | Counter'dummy \<Rightarrow> Counter )" lemma DTypeId_simps [simp]: "cDTypeId CounterImpl'value = CounterImpl" "cDTypeId UndoCounter'save = UndoCounter" "aDTypeId Dummy'dummy = Dummy" "iDTypeId Counter'dummy = Counter" by (simp_all add: cDTypeId_def aDTypeId_def iDTypeId_def) text \<open>The range type of an attribute is the type of the value stored in that attribute. \<close> definition rtype:: "AttId \<Rightarrow> Javatype" where "rtype f = (case f of CounterImpl'value \<Rightarrow> IntgT | UndoCounter'save \<Rightarrow> IntgT | Dummy'dummy \<Rightarrow> NullT | Counter'dummy \<Rightarrow> NullT)" lemma rtype_simps [simp]: "rtype CounterImpl'value = IntgT" "rtype UndoCounter'save = IntgT" "rtype Dummy'dummy = NullT" "rtype Counter'dummy = NullT" by (simp_all add: rtype_def rtype_def rtype_def) text \<open>With the datatype \<open>CAttId\<close> we describe the possible locations in memory for instance fields. We rule out the impossible combinations of class names and field names. For example, a \<open>CounterImpl\<close> cannot have a \<open>save\<close> field. A store model which provides locations for all possible combinations of the Cartesian product of class name and field name works out fine as well, because we cannot express modification of such ``wrong'' locations in a Java program. So we can only prove useful properties about reasonable combinations. The only drawback in such a model is that we cannot prove a property like \<open>not_treach_ref_impl_not_reach\<close> in theory StoreProperties. If the store provides locations for every combination of class name and field name, we cannot rule out reachability of certain pointer chains that go through ``wrong'' locations. That is why we decided to introduce the new type \<open>CAttId\<close>. While \<open>AttId\<close> describes which fields are declared in which classes and interfaces, \<open>CAttId\<close> describes which objects of which classes may contain which fields at run-time. Thus, \<open>CAttId\<close> makes the inheritance of fields visible in the formalization. There is only one such datatype because only objects of concrete classes can be created at run-time, thus only instance fields of concrete classes can occupy memory.\<close> datatype CAttId = CounterImpl'CounterImpl'value | UndoCounter'CounterImpl'value | UndoCounter'UndoCounter'save | CounterImpl'Counter'dummy | UndoCounter'Counter'dummy text \<open>Function \<open>catt\<close> builds a \<open>CAttId\<close> from a class name and a field name. In case of the illegal combinations we just return \<open>undefined\<close>. We can also filter out static fields in \<open>catt\<close>.\<close> definition catt:: "CTypeId \<Rightarrow> AttId \<Rightarrow> CAttId" where "catt C f = (case C of CounterImpl \<Rightarrow> (case f of CounterImpl'value \<Rightarrow> CounterImpl'CounterImpl'value | UndoCounter'save \<Rightarrow> undefined | Dummy'dummy \<Rightarrow> undefined | Counter'dummy \<Rightarrow> CounterImpl'Counter'dummy) | UndoCounter \<Rightarrow> (case f of CounterImpl'value \<Rightarrow> UndoCounter'CounterImpl'value | UndoCounter'save \<Rightarrow> UndoCounter'UndoCounter'save | Dummy'dummy \<Rightarrow> undefined | Counter'dummy \<Rightarrow> UndoCounter'Counter'dummy) | Object \<Rightarrow> undefined | Exception \<Rightarrow> undefined | ClassCastException \<Rightarrow> undefined | NullPointerException \<Rightarrow> undefined )" lemma catt_simps [simp]: "catt CounterImpl CounterImpl'value = CounterImpl'CounterImpl'value" "catt UndoCounter CounterImpl'value = UndoCounter'CounterImpl'value" "catt UndoCounter UndoCounter'save = UndoCounter'UndoCounter'save" "catt CounterImpl Counter'dummy = CounterImpl'Counter'dummy" "catt UndoCounter Counter'dummy = UndoCounter'Counter'dummy" by (simp_all add: catt_def) text \<open>Selection of the class name of the type of the object in which the field lives. The field can only be located in a concrete class.\<close> definition cls:: "CAttId \<Rightarrow> CTypeId" where "cls cf = (case cf of CounterImpl'CounterImpl'value \<Rightarrow> CounterImpl | UndoCounter'CounterImpl'value \<Rightarrow> UndoCounter | UndoCounter'UndoCounter'save \<Rightarrow> UndoCounter | CounterImpl'Counter'dummy \<Rightarrow> CounterImpl | UndoCounter'Counter'dummy \<Rightarrow> UndoCounter )" lemma cls_simps [simp]: "cls CounterImpl'CounterImpl'value = CounterImpl" "cls UndoCounter'CounterImpl'value = UndoCounter" "cls UndoCounter'UndoCounter'save = UndoCounter" "cls CounterImpl'Counter'dummy = CounterImpl" "cls UndoCounter'Counter'dummy = UndoCounter" by (simp_all add: cls_def) text \<open>Selection of the field name.\<close> definition att:: "CAttId \<Rightarrow> AttId" where "att cf = (case cf of CounterImpl'CounterImpl'value \<Rightarrow> CounterImpl'value | UndoCounter'CounterImpl'value \<Rightarrow> CounterImpl'value | UndoCounter'UndoCounter'save \<Rightarrow> UndoCounter'save | CounterImpl'Counter'dummy \<Rightarrow> Counter'dummy | UndoCounter'Counter'dummy \<Rightarrow> Counter'dummy )" end
type $SS <struct { @real f32, @imag f32}> var $sconst1 <struct { @f11 i32, @f22 <$SS>, @f33 i32, @f44 i32, @f55 f32, @f66 f32}> = [ 6=1007.0f, 2= [1=11.11f, 2=22.22f], 3=-273, 4=75, 1=1425926, 5=6023.0f ] func $printf (var %p1 <* i8>)void func $main ( ) i32 { call &printf (addrof a32 $sconst1) return (constval i32 0) } # EXEC: %irbuild Main.mpl # EXEC: %irbuild Main.irb.mpl # EXEC: %cmp Main.irb.mpl Main.irb.irb.mpl
\documentclass[a4paper]{article} \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} \usepackage{newcent} \usepackage{helvet} \usepackage{graphicx} \usepackage[pdftex, pdfborder={0 0 0}]{hyperref} \frenchspacing \include{bml} \title{BML 5542} \author{Erik Sjöstrand} \begin{document} \maketitle \tableofcontents \section{Introduction} Welcome to BML! This is a normal paragraph, and above we can see the \texttt{\#+TITLE}, the \texttt{\#+AUTHOR} and the \texttt{\#+DESCRIPTION} of the file. \texttt{\#+TITLE} is the name of the system and \texttt{\#+DESCRIPTION} is a \emph{short summary of} how the system works. \texttt{\#+AUTHOR} is self explanatory. \texttt{Introduction} above, ``headed by an asterisk'', sets a section at the first level (the second level would have two asterisks etc). In the paragraph above I encapsulated some words between equal signs. This means that they will show up as a monospaced font when exported to HTML or LaTeX. It is also possible to make words (or sentences) \textbf{strong or bold} or \emph{in italics}. The system presented in this example file is meant to showcase many of the current features in BML. Let's start with the basic opening structure of the system: \begin{bidtable} 1\c \> 2+\c . Natural or balanced\\ 1\d \> 4+ suit, unbalanced\\ 1M \> 5+ suit\\ 2\c \> 20--21 bal / Any game force\\ 2\d \> 6+\h\ or 6+\s , 5--9 hcp\\ 2\h\s \> 6+ suit, 10--13 hcp\\ 2NT \> 22--24\\ 3X \> Preemptive\\ 3NT \> Gambling \end{bidtable} The above is an example of a bidding table; the reason why BML is more suited for bridge system notes than other markup languages. You start by writing the bid, then a number of whitespaces, and then the description of the bid. Simple! C is for clubs, D for diamonds, H for hearts, S for spades and N for no trump. There's also some special cases which you could use, above we use 1M (1H and 1S), 2HS (2H and 2S) and 3X (3C, 3D, 3H and 3S). We'll see more of these later. The reason why the 1NT opening is left out above is a secret for now! \section{The 1\pdfc\ opening} You might have noticed the \c\ in the title of this section? This will be replaced by a club suit symbol when exported. The same is true for \d , \h\ and \s\ (but these will be converted to diamonds, hearts and spades, ofcourse). In this example we use transfer responses to the 1\c\ opening: \begin{bidtable} 1\c---\\ 1red \> Transfer. 4+ major, 0+ hcp\\ 1\s \> INV+ with 5+\d\ / Negative NT\\ 1NT \> Game forcing, 5+\c\ or balanced\\ 2\c \> 5+\c , 5--9 hcp\\ 2X \> 6+ suit, 4--8 hcp\\ 2NT \> Invitational \end{bidtable} By writing 1C--- we define that the following bids should be continuations to the sequence 1C. We could write 1C- or 1C-- too, the number of dashes only matters to the way the output looks. Also note the 1red response, this defines both 1D and 1H. \subsection{After a transfer} This section has two asterisks, meaning it will be at level two (so its a subsection). You might also have noticed that the paragraphs, the sections and the bidtables are separated by a blank line? This is important in BML, as the blankline are used to separate elements. \begin{bidtable} 1\c-1\d;\\ 1\h \> Minimum with 2--3\h \+\\ 1\s \> 4+\h , 4\s , at most invitational\\ 1NT \> Sign off\\ 2\c \> Puppet to 2\d \+\\ 2\d \> Forced\+\\ 2\h \> Mildly invitational with 5\h \\ 2\s \> Invitational, 5+\h\ and 4\s \\ 2NT \> Strongly invitational with 5\h \\ 3m \> Invitational with 4\h\ and 5+ minor\\ 3\h \> 6\h , about 11--12 hcp\-\-\\ 2\d \> Artificial game force\\ 2\h \> 6+\h , about 9--10 hcp\-\\ 1\s \> 5+\c , 4+\s , unlimited\\ 1NT \> 17--19 bal, 2--3\h \\ 2\c \> 5+\c , unbal, 0--2\h , 0--3\s \\ 2\d \> Reverse\\ 2\h \> Minimum, 4\h \\ 2\s \> 16+ hcp, 5+\c\ and 4+\h \+\\ 3\d \> Retransfer\+\\ 3\h\+\\ 3\s \> Cue bid, slam interest\\ 4\c\d \> Cue bid, slam interest\\ 4\h \> To play\-\-\\ 3\h \> Invitational\\ 3\s \> Splinter\\ 4\c\d \> Splinter\\ 4\h \> To play\-\\ 2NT \> 16+ hcp, 6+\c . 18+ if 3\h \+\\ 3\c \> Suggestion to play\\ 3\d \> Relay\+\\ 3\h \> 3\h , 18+ hcp\-\\ 3\h \> Game forcing with 6+\h \-\\ 3\c \> 15--17 hcp, 6+\c\ and 3\h \+\\ 3\d \> Retransfer\\ 3\h \> Invitational\-\\ 3\d \> 17--19 bal, 4\h \+\\ 3\h \> To play\-\\ 3\h \> 13--15 hcp, good hand, 5+\c\ and 4\h \+\\ 3NT \> Asking for singleton\- \end{bidtable} This bidding table shows a couple of new features. The most prominent is the ability to add continuations directly in the table, by using whitespaces. We also see another example of appending bids to an existing sequence, by using 1C-1D; in the beginning. There's also the use of 3m, meaning both 3C and 3D. \section{Defense to 1NT} Defining bidding when both sides bid is a little bit more tricky, since you have to write all the bids (even passes). The opponents' bid are indicated by encapsulating them in parentheses. P is used for Pass, D for Double and R for Redouble. \begin{bidtable} (1NT)---\\ Dbl \> Strength, ca 15+\\ 2\c \> At least 5-4 majors\+\\ (D)\+\\ Pass \> 5+\c , suggestion to play\\ Rdbl \> Asking for better/longer major\\ 2\d \> 5+\d , suggestion to play\-\\ (P)\+\\ 2\d \> Asking for better/longer major\-\-\\ 2\d \> A weak major or a strong minor\+\\ (P)\+\\ 2\h \> Pass/correct\\ 2\s \> Pass/correct\\ 2NT \> Asking\-\-\\ 2\h\s \> Constructive\\ 2NT \> 5-5 minors\\ 3X \> Preemptive \end{bidtable} Note that the above is only for a direct overcall over 1NT. To define the above also when balancing. We've used BML's copy/cut/paste functionality in order to showcase that you do not have to write it all over again. Take a look below (only visible in the \emph{example.txt} file, not in HTML, LaTeX or .pdf): First we used the \texttt{\#COPY} command; the text between \texttt{\#COPY} and \texttt{\#ENDCOPY} got put into a sort of clipboard, with the tag nt\_defense which we specified. To paste it into the bidding table above we used the \texttt{\#PASTE} command. We also used the \texttt{\#HIDE} option. When this is present in a bidding table the table will be exported to Full Disclosure, but not to HTML or LaTeX. You could also include other BML-files into your main file by using the \texttt{\#INCLUDE} command. Just type \texttt{\#INCLUDE <filename>} and the entire file will be inserted at the point where you wrote the command. This is a useful way to separate your system into modules, or perhaps just to make it more manageable. It is also possible to add continuations when the opponents interfere: \begin{bidtable} 1\c-(1\d)---\\ Dbl \> 4+\h \\ 1\h \> 4+\s \\ 1\s \> INV+ with 5+\d\ / Negative NT\\ 1NT \> Game forcing, 5+\c\ or balanced\\ 2\c \> 5+\c , 5--9 hcp\\ 2X \> 6+ suit, 4--8 hcp\\ 2NT \> Invitational \end{bidtable} \section{The 1NT opening} Here's the reason why I left out the 1NT opening earlier: I will showcase how to make sequences dependant on vulnerability and seat. This will be a bit messy, so hold tight! We start by cutting our NT-module, since this will be used on all NT-openings. \texttt{\#CUT} is similar to the \texttt{\#COPY} command, but using \texttt{\#CUT} means that it isn't parsed as a bidding table until it is pasted. The \texttt{\#VUL} command is used to set the vulnerability. It takes an argument of two characters, each can be Y, N or 0. The first character asks if we are vulnerable and the second asks if our opponents are vulnerable. Y is for Yes, N is for No and 0 means that it doesn't matter. The \texttt{\#SEAT} command sets the seat in which the bid should be valid. 0 means that the seat doesn't matter (all seats), 12 means first or second and 34 means third or fourth. 1--4 could also be used. So when we're not vulnerable we open 1NT 12--14 in 1st and 2nd seat. But in third and fourth seat it is 14--16. When we're vulnerable we always open 1NT 14--16. \begin{bidtable} 1NT---\\ 2\c \> Stayman\+\\ 2\d \> No major\\ 2NT \> 4-4 majors, minimum\\ 3\c \> 4-4 majors, maximum\-\\ 2red \> Transfer\\ 2\s \> Minor suit stayman\\ 2NT \> Invitational \end{bidtable} We've been using the \texttt{\#HIDE} command, so we don't have to see our NT-system over and over again. This time tough we paste it normally, so that we see it at least once. \section{Lists} I'd like to show you how to make lists in BML. It is pretty simple: \begin{itemize} \item Here's a list! \item With a couple of \item Items in it \end{itemize} You could also make ordered lists: \begin{enumerate} \item This is ordered \item Just add numbers \item To each item \end{enumerate} \end{document}
# Offset between 0-based indexing and 1-based indexing const OFFSET = 1 mutable struct Grid{T} w::Int h::Int data::Vector{T} function Grid{T}() where T w = 0 h = 0 data = [] new{T}( w, h, data, ) end end function resize(grid::Grid{T}, width::Int, height::Int) where T grid.w = width grid.h = height empty!(grid.data) resize!(grid.data, width * height) fill!(grid.data, zero(T)) return nothing end function contains(grid::Grid{T}, x::Int, y::Int) where T return 0 <= y && y < grid.h && 0 <= x && x < grid.w end function get(grid::Grid{T}, x::Int, y::Int) where T return grid.data[y * grid.w + x + OFFSET] end function set(grid::Grid{T}, x::Int, y::Int, v::T) where T grid.data[y * grid.w + x + OFFSET] = v return nothing end
\documentclass[british,titlepage]{ntnuthesis} \title{Title of Your Report} \shorttitle{Title of Your Report} \author{Student Name} \shortauthor{Student Name} \date{2021-12-15} \addbibresource{thesis.bib} \input{glossary.tex} % add glossary and acronym lists before document \begin{document} \input{chapters/0a-abstract.tex} \tableofcontents \listoffigures \listoftables \lstlistoflistings \printglossary[type=\acronymtype] % Print acronyms \printglossary % Print glossary \input{chapters/1-introduction} \input{chapters/2-usage.tex} \input{chapters/3-structure.tex} \input{chapters/4-conclusion.tex} \chapter*{\bibname} \printbibliography[heading=none] \input{chapters/papers.tex} \appendix \input{appendices/a-appendix.tex} \end{document}
-- this is to test that changes introduced for #2032 do not ruin other things -- (#2032 itself is a performance issue, I don't know how to properly test for that) import Data.Fin ex0 : {n : Nat} -> Fin (S n) ex0 = fromInteger 0 ex1 : {n : Nat} -> Fin (S (S (S n))) ex1 = fromInteger 2 eq0 : (===) {a=Fin 3} (fromInteger 2) (FS (FS FZ)) eq0 = Refl eq1 : (===) {a=Fin (S (S (S k)))} (fromInteger 2) (FS (FS FZ)) eq1 = Refl -- this will probably show up if issue #2032 is present -- and anybody measures the time it takes this test to run... addFourMillion : Int -> Int addFourMillion x = 4000000 + x
/- Copyright (c) 2018 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.module.pi import Mathlib.algebra.big_operators.basic import Mathlib.PostPort universes u u_1 namespace Mathlib /-! # Basic properties of holors Holors are indexed collections of tensor coefficients. Confusingly, they are often called tensors in physics and in the neural network community. A holor is simply a multidimensional array of values. The size of a holor is specified by a `list ℕ`, whose length is called the dimension of the holor. The tensor product of `x₁ : holor α ds₁` and `x₂ : holor α ds₂` is the holor given by `(x₁ ⊗ x₂) (i₁ ++ i₂) = x₁ i₁ * x₂ i₂`. A holor is "of rank at most 1" if it is a tensor product of one-dimensional holors. The CP rank of a holor `x` is the smallest N such that `x` is the sum of N holors of rank at most 1. Based on the tensor library found in <https://www.isa-afp.org/entries/Deep_Learning.html> ## References * <https://en.wikipedia.org/wiki/Tensor_rank_decomposition> -/ /-- `holor_index ds` is the type of valid index tuples to identify an entry of a holor of dimensions `ds` -/ def holor_index (ds : List ℕ) := Subtype fun (is : List ℕ) => list.forall₂ Less is ds namespace holor_index def take {ds₂ : List ℕ} {ds₁ : List ℕ} : holor_index (ds₁ ++ ds₂) → holor_index ds₁ := sorry def drop {ds₂ : List ℕ} {ds₁ : List ℕ} : holor_index (ds₁ ++ ds₂) → holor_index ds₂ := sorry theorem cast_type {ds₁ : List ℕ} {ds₂ : List ℕ} (is : List ℕ) (eq : ds₁ = ds₂) (h : list.forall₂ Less is ds₁) : subtype.val (cast (congr_arg holor_index eq) { val := is, property := h }) = is := eq.drec (Eq.refl (subtype.val (cast (congr_arg holor_index (Eq.refl ds₁)) { val := is, property := h }))) eq def assoc_right {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} : holor_index (ds₁ ++ ds₂ ++ ds₃) → holor_index (ds₁ ++ (ds₂ ++ ds₃)) := cast sorry def assoc_left {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} : holor_index (ds₁ ++ (ds₂ ++ ds₃)) → holor_index (ds₁ ++ ds₂ ++ ds₃) := cast sorry theorem take_take {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} (t : holor_index (ds₁ ++ ds₂ ++ ds₃)) : take (assoc_right t) = take (take t) := sorry theorem drop_take {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} (t : holor_index (ds₁ ++ ds₂ ++ ds₃)) : take (drop (assoc_right t)) = drop (take t) := sorry theorem drop_drop {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} (t : holor_index (ds₁ ++ ds₂ ++ ds₃)) : drop (drop (assoc_right t)) = drop t := sorry end holor_index /-- Holor (indexed collections of tensor coefficients) -/ def holor (α : Type u) (ds : List ℕ) := holor_index ds → α namespace holor protected instance inhabited {α : Type} {ds : List ℕ} [Inhabited α] : Inhabited (holor α ds) := { default := fun (t : holor_index ds) => Inhabited.default } protected instance has_zero {α : Type} {ds : List ℕ} [HasZero α] : HasZero (holor α ds) := { zero := fun (t : holor_index ds) => 0 } protected instance has_add {α : Type} {ds : List ℕ} [Add α] : Add (holor α ds) := { add := fun (x y : holor α ds) (t : holor_index ds) => x t + y t } protected instance has_neg {α : Type} {ds : List ℕ} [Neg α] : Neg (holor α ds) := { neg := fun (a : holor α ds) (t : holor_index ds) => -a t } protected instance add_semigroup {α : Type} {ds : List ℕ} [add_semigroup α] : add_semigroup (holor α ds) := add_semigroup.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_semigroup.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry protected instance add_comm_semigroup {α : Type} {ds : List ℕ} [add_comm_semigroup α] : add_comm_semigroup (holor α ds) := add_comm_semigroup.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_comm_semigroup.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry sorry protected instance add_monoid {α : Type} {ds : List ℕ} [add_monoid α] : add_monoid (holor α ds) := add_monoid.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_monoid.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry (id fun (ᾰ : holor_index ds) => add_monoid.zero) sorry sorry protected instance add_comm_monoid {α : Type} {ds : List ℕ} [add_comm_monoid α] : add_comm_monoid (holor α ds) := add_comm_monoid.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_comm_monoid.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry (id fun (ᾰ : holor_index ds) => add_comm_monoid.zero) sorry sorry sorry protected instance add_group {α : Type} {ds : List ℕ} [add_group α] : add_group (holor α ds) := add_group.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_group.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry (id fun (ᾰ : holor_index ds) => add_group.zero) sorry sorry (fun (ᾰ : holor α ds) => id fun (ᾰ_1 : holor_index ds) => add_group.neg (ᾰ ᾰ_1)) (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_group.sub (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry protected instance add_comm_group {α : Type} {ds : List ℕ} [add_comm_group α] : add_comm_group (holor α ds) := add_comm_group.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_comm_group.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry (id fun (ᾰ : holor_index ds) => add_comm_group.zero) sorry sorry (fun (ᾰ : holor α ds) => id fun (ᾰ_1 : holor_index ds) => add_comm_group.neg (ᾰ ᾰ_1)) (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_comm_group.sub (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry sorry /- scalar product -/ protected instance has_scalar {α : Type} {ds : List ℕ} [Mul α] : has_scalar α (holor α ds) := has_scalar.mk fun (a : α) (x : holor α ds) (t : holor_index ds) => a * x t protected instance semimodule {α : Type} {ds : List ℕ} [semiring α] : semimodule α (holor α ds) := pi.semimodule (holor_index ds) (fun (ᾰ : holor_index ds) => α) α /-- The tensor product of two holors. -/ def mul {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} [s : Mul α] (x : holor α ds₁) (y : holor α ds₂) : holor α (ds₁ ++ ds₂) := fun (t : holor_index (ds₁ ++ ds₂)) => x (holor_index.take t) * y (holor_index.drop t) theorem cast_type {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} (eq : ds₁ = ds₂) (a : holor α ds₁) : cast (congr_arg (holor α) eq) a = fun (t : holor_index ds₂) => a (cast (congr_arg holor_index (Eq.symm eq)) t) := eq.drec (Eq.refl (cast (congr_arg (holor α) (Eq.refl ds₁)) a)) eq def assoc_right {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} : holor α (ds₁ ++ ds₂ ++ ds₃) → holor α (ds₁ ++ (ds₂ ++ ds₃)) := cast sorry def assoc_left {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} : holor α (ds₁ ++ (ds₂ ++ ds₃)) → holor α (ds₁ ++ ds₂ ++ ds₃) := cast sorry theorem mul_assoc0 {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : mul (mul x y) z = assoc_left (mul x (mul y z)) := sorry theorem mul_assoc {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : mul (mul x y) z == mul x (mul y z) := sorry theorem mul_left_distrib {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} [distrib α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₂) : mul x (y + z) = mul x y + mul x z := funext fun (t : holor_index (ds₁ ++ ds₂)) => left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t)) theorem mul_right_distrib {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} [distrib α] (x : holor α ds₁) (y : holor α ds₁) (z : holor α ds₂) : mul (x + y) z = mul x z + mul y z := funext fun (t : holor_index (ds₁ ++ ds₂)) => right_distrib (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t)) @[simp] theorem zero_mul {ds₁ : List ℕ} {ds₂ : List ℕ} {α : Type} [ring α] (x : holor α ds₂) : mul 0 x = 0 := funext fun (t : holor_index (ds₁ ++ ds₂)) => zero_mul (x (holor_index.drop t)) @[simp] theorem mul_zero {ds₁ : List ℕ} {ds₂ : List ℕ} {α : Type} [ring α] (x : holor α ds₁) : mul x 0 = 0 := funext fun (t : holor_index (ds₁ ++ ds₂)) => mul_zero (x (holor_index.take t)) theorem mul_scalar_mul {α : Type} {ds : List ℕ} [monoid α] (x : holor α []) (y : holor α ds) : mul x y = x { val := [], property := list.forall₂.nil } • y := sorry /- holor slices -/ /-- A slice is a subholor consisting of all entries with initial index i. -/ def slice {α : Type} {d : ℕ} {ds : List ℕ} (x : holor α (d :: ds)) (i : ℕ) (h : i < d) : holor α ds := fun (is : holor_index ds) => x { val := i :: subtype.val is, property := sorry } /-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/ def unit_vec {α : Type} [monoid α] [add_monoid α] (d : ℕ) (j : ℕ) : holor α [d] := fun (ti : holor_index [d]) => ite (subtype.val ti = [j]) 1 0 theorem holor_index_cons_decomp {d : ℕ} {ds : List ℕ} (p : holor_index (d :: ds) → Prop) (t : holor_index (d :: ds)) : (∀ (i : ℕ) (is : List ℕ) (h : subtype.val t = i :: is), p { val := i :: is, property := eq.mpr (id (Eq._oldrec (Eq.refl (list.forall₂ Less (i :: is) (d :: ds))) (Eq.symm h))) (subtype.property t) }) → p t := sorry /-- Two holors are equal if all their slices are equal. -/ theorem slice_eq {α : Type} {d : ℕ} {ds : List ℕ} (x : holor α (d :: ds)) (y : holor α (d :: ds)) (h : slice x = slice y) : x = y := sorry theorem slice_unit_vec_mul {α : Type} {d : ℕ} {ds : List ℕ} [ring α] {i : ℕ} {j : ℕ} (hid : i < d) (x : holor α ds) : slice (mul (unit_vec d j) x) i hid = ite (i = j) x 0 := sorry theorem slice_add {α : Type} {d : ℕ} {ds : List ℕ} [Add α] (i : ℕ) (hid : i < d) (x : holor α (d :: ds)) (y : holor α (d :: ds)) : slice x i hid + slice y i hid = slice (x + y) i hid := sorry theorem slice_zero {α : Type} {d : ℕ} {ds : List ℕ} [HasZero α] (i : ℕ) (hid : i < d) : slice 0 i hid = 0 := rfl theorem slice_sum {α : Type} {d : ℕ} {ds : List ℕ} [add_comm_monoid α] {β : Type} (i : ℕ) (hid : i < d) (s : finset β) (f : β → holor α (d :: ds)) : (finset.sum s fun (x : β) => slice (f x) i hid) = slice (finset.sum s fun (x : β) => f x) i hid := sorry /-- The original holor can be recovered from its slices by multiplying with unit vectors and summing up. -/ @[simp] theorem sum_unit_vec_mul_slice {α : Type} {d : ℕ} {ds : List ℕ} [ring α] (x : holor α (d :: ds)) : (finset.sum (finset.attach (finset.range d)) fun (i : Subtype fun (x : ℕ) => x ∈ finset.range d) => mul (unit_vec d ↑i) (slice x (↑i) (nat.succ_le_of_lt (iff.mp finset.mem_range (subtype.prop i))))) = x := sorry /- CP rank -/ /-- `cprank_max1 x` means `x` has CP rank at most 1, that is, it is the tensor product of 1-dimensional holors. -/ inductive cprank_max1 {α : Type} [Mul α] : {ds : List ℕ} → holor α ds → Prop where | nil : ∀ (x : holor α []), cprank_max1 x | cons : ∀ {d : ℕ} {ds : List ℕ} (x : holor α [d]) (y : holor α ds), cprank_max1 y → cprank_max1 (mul x y) /-- `cprank_max N x` means `x` has CP rank at most `N`, that is, it can be written as the sum of N holors of rank at most 1. -/ inductive cprank_max {α : Type} [Mul α] [add_monoid α] : ℕ → {ds : List ℕ} → holor α ds → Prop where | zero : ∀ {ds : List ℕ}, cprank_max 0 0 | succ : ∀ (n : ℕ) {ds : List ℕ} (x y : holor α ds), cprank_max1 x → cprank_max n y → cprank_max (n + 1) (x + y) theorem cprank_max_nil {α : Type} [monoid α] [add_monoid α] (x : holor α []) : cprank_max 1 x := sorry theorem cprank_max_1 {α : Type} {ds : List ℕ} [monoid α] [add_monoid α] {x : holor α ds} (h : cprank_max1 x) : cprank_max 1 x := sorry theorem cprank_max_add {α : Type} {ds : List ℕ} [monoid α] [add_monoid α] {m : ℕ} {n : ℕ} {x : holor α ds} {y : holor α ds} : cprank_max m x → cprank_max n y → cprank_max (m + n) (x + y) := sorry theorem cprank_max_mul {α : Type} {d : ℕ} {ds : List ℕ} [ring α] (n : ℕ) (x : holor α [d]) (y : holor α ds) : cprank_max n y → cprank_max n (mul x y) := sorry theorem cprank_max_sum {α : Type} {ds : List ℕ} [ring α] {β : Type u_1} {n : ℕ} (s : finset β) (f : β → holor α ds) : (∀ (x : β), x ∈ s → cprank_max n (f x)) → cprank_max (finset.card s * n) (finset.sum s fun (x : β) => f x) := sorry theorem cprank_max_upper_bound {α : Type} [ring α] {ds : List ℕ} (x : holor α ds) : cprank_max (list.prod ds) x := sorry /-- The CP rank of a holor `x`: the smallest N such that `x` can be written as the sum of N holors of rank at most 1. -/ def cprank {α : Type} {ds : List ℕ} [ring α] (x : holor α ds) : ℕ := nat.find sorry theorem cprank_upper_bound {α : Type} [ring α] {ds : List ℕ} (x : holor α ds) : cprank x ≤ list.prod ds := nat.find_min' (Exists.intro (list.prod ds) ((fun (this : cprank_max (list.prod ds) x) => this) (cprank_max_upper_bound x))) (cprank_max_upper_bound x)
Require Import List. Require Import Nat. Require Import Bool. Require Export Coq.Arith.Compare_dec. Require Import Coq.Arith.Lt. Require Import Coq.Arith.PeanoNat. Require Import Lia. Import ListNotations. Lemma eqb_reflect : forall x y, reflect (x = y) (x =? y). Proof. intros x y. apply iff_reflect. symmetry. apply Nat.eqb_eq. Qed. Lemma ltb_reflect : forall x y, reflect (x < y) (x <? y). Proof. intros x y. apply iff_reflect. symmetry. apply Nat.ltb_lt. Qed. Lemma leb_reflect : forall x y, reflect (x <= y) (x <=? y). Proof. intros x y. apply iff_reflect. symmetry. apply Nat.leb_le. Qed. Ltac bdestruct X := let H := fresh in let e := fresh "e" in evar (e: Prop); assert (H: reflect e X); subst e; [eauto with bdestruct | destruct H as [H|H]; [ | try first [apply not_lt in H | apply not_le in H]]]. #[export] Hint Resolve ltb_reflect leb_reflect eqb_reflect : bdestruct. Lemma eq_list {A} : forall (a : A) (l1 l2 : list A), a :: l1 = a :: l2 -> l1 = l2. Proof. intros. inversion H. reflexivity. Qed. (** * Insertion Inserting a number into a list will guarantee the number appears exactly once. *) Fixpoint insert (i : nat) (l : list nat) := match l with | [] => [i] | h :: t => if i <? h then i :: h :: t else if i =? h then l else h :: insert i t end. Lemma insert_lt : forall (n h : nat) (t : list nat), n < h -> insert n (h :: t) = n :: h :: t. Proof. intros. apply Nat.ltb_lt in H as H1. unfold insert. rewrite H1. reflexivity. Qed. Lemma insert_eq : forall (n h : nat) (t : list nat), n = h -> insert n (h :: t) = h :: t. Proof. intros. apply Nat.eqb_eq in H as H1. unfold insert. destruct (ltb_reflect n h). contradict l. Nat.order. rewrite H1. reflexivity. Qed. Lemma insert_gt : forall (n h : nat) (t : list nat), n > h -> insert n (h :: t) = h :: (insert n t). Proof. intros. apply Nat.ltb_lt in H as H1. unfold insert. destruct (ltb_reflect n h). contradict l. apply le_not_lt. lia. destruct (eqb_reflect n h). contradict e. lia. reflexivity. Qed. Theorem insert_inv : forall (n : nat) (l : list nat), In n (insert n l). Proof. intros. induction l. - (* Base case: l = [] *) unfold insert; unfold In. auto. - (* Inductive case: l = a::l *) assert (n = a \/ n > a \/ n < a). lia. inversion H. -- (* Subcase: n = a *) rewrite <- H0. apply Nat.eqb_eq in H0 as H1. unfold insert. destruct (ltb_reflect n n). apply (in_eq n (n :: l)). rewrite <- H0 in H1. rewrite H1. apply (in_eq n l). -- inversion H0. --- (* Subcase: n > a *) apply (insert_gt n a l) in H1 as H2. rewrite H2. apply (in_cons a n (insert n l)). assumption. --- (* Subcase: n < a *) apply (insert_lt n a l) in H1 as H2. rewrite H2. apply (in_eq n (a :: l)). Qed. Theorem insert_preserves_elts : forall (e n : nat) (l : list nat), In e l -> In e (insert n l). Proof. intros. induction l. - contradict H. - (* Inductive case: l = a :: l *) assert (e = a \/ e <> a). lia. inversion H0. + (* Case: e = a *) assert (n = a \/ n < a \/ n > a). lia. inversion H2. ++ apply (insert_eq n a l) in H3. rewrite H3. assumption. ++ inversion H3. +++ (* Subcase: n = a *) apply (insert_lt n a l) in H4 as H5. rewrite H5. rewrite <- H1. unfold In. auto. +++ (* Subcase n < a *) apply (insert_gt n a l) in H4 as H5. rewrite H5. rewrite <- H1. apply (in_eq e (insert n l)). + (* Case: e <> a *) assert (n = a \/ n < a \/ n > a). lia. inversion H2. ++ (* Subcase: a = n *) apply (insert_eq n a l) in H3 as H4. rewrite H4. assumption. ++ inversion H3. +++ (* Subcase: n < a *) apply (insert_lt n a l) in H4 as H5. rewrite H5. assert (e = n \/ e <> n). lia. inversion H6. rewrite H7. apply (in_eq n (a::l)). unfold In. simpl; auto. +++ (* Subcase: n > a *) apply (insert_gt n a l) in H4 as H5. rewrite H5. assert (e = n \/ e <> n). lia. inversion H6. rewrite H7. apply (in_cons a n (insert n l)). apply (insert_inv n l). apply (in_cons a e (insert n l)). inversion H. apply eq_sym in H8. contradict H8. assumption. apply IHl. assumption. Qed. Theorem insert_nonempty : forall (n : nat) (l : list nat), [] <> (insert n l). Proof. intros. induction l. - unfold insert. apply nil_cons. - assert (n < a \/ n = a \/ n > a). lia. inversion H. + apply (insert_lt n a l) in H0 as H1. rewrite H1. discriminate. + inversion H0. ++ apply (insert_eq n a l) in H1 as H2. rewrite H2. discriminate. ++ apply (insert_gt n a l) in H1 as H2. rewrite H2. discriminate. Qed. (** Now we have an inductive way to specify if our set of [nat] is sorted or not. *) Inductive sorted : list nat -> Prop := | sorted_nil : sorted [] | sorted_1 : forall x, sorted [x] | sorted_cons : forall x y l, x < y -> sorted (y :: l) -> sorted (x :: y :: l). Theorem sorted_tl : forall (n : nat) (l : list nat), sorted (n :: l) -> sorted l. Proof. intros. induction l. - apply sorted_nil. - inversion H. assumption. Qed. Lemma sorted_head : forall (n a : nat) (l : list nat), sorted (a :: l) -> Some a = hd_error (insert n (a :: l)) \/ Some n = hd_error (insert n (a :: l)). Proof. intros. assert (a < n \/ n = a \/ a > n). lia. inversion H0. - (* Case 1: a < n *) apply (insert_gt n a l) in H1. left. rewrite H1. unfold hd_error. reflexivity. - inversion H1. + (* Case 2: a = n *) apply (insert_eq n a l) in H2. left. rewrite H2. unfold hd_error. reflexivity. + (* Case 3: a > n *) apply (insert_lt n a l) in H2. right. rewrite H2. unfold hd_error. reflexivity. Qed. Lemma sorted_head_ge : forall (n a : nat) (l : list nat), sorted (a :: l) -> n >= a -> Some a = hd_error (insert n (a :: l)). Proof. intros. assert (n = a \/ n > a). lia. inversion H1. - (* Case: a = n *) apply (insert_eq n a l) in H2. rewrite H2. unfold hd_error; reflexivity. - (* Case: n > a *) apply (insert_gt n a l) in H2. rewrite H2. unfold hd_error; reflexivity. Qed. (* Lemma sorted_tail : forall (n : nat) (l l0 : list nat), sorted l -> n :: l0 = insert n l -> (~(In n l) -> l0 = l). Proof. intros. inversion H. destruct l as [|a tl]. - (* Case: l = [] *) unfold insert in H0; injection H0; auto. - (* Case: l = a::tl *) (* Goal: l0 = a :: tl *) inversion H as [|b|b tl']. (* sorted (a :: tl) can be considerd in two subcases: tl=[] and sorted_cons : a < b -> sorted (b::tl') -> sorted(a::b::tl'). The sorted_nil case isn't possible. *) + (* Subcase: l = a::[] *) rewrite <- H3 in H; rewrite <- H3 in H0; rewrite <- H3 in H1. - (* Subcase: l = a::b::tl' *) apply sorted_tl in H as IH. apply IHtl in IH. inversion H. + (* Subcase: tl = []; goal becomes l0 = [a] *) rewrite <- H4 in H0. inversion H0. assert (sorted []) as IH. apply sorted_nil. apply IHtl in IH. apply IHtl in H1. assert(In n (insert n tl)). assert (a < n \/ n = a \/ a > n). lia. inversion H1. - apply (insert_gt n a l) in H2 as H3. assert (n :: l0 = a :: insert n l). { rewrite <- H3; rewrite <- H0; reflexivity. } Admitted. Lemma sorted_insert_sorted_tl : forall (n : nat) (l : list nat), sorted (insert n l) -> sorted l. Proof. intros. induction l. - apply sorted_nil. - (* Inductive case: l = a :: l *) assert (n < a \/ n = a \/ n > a). lia. inversion H0. + (* Subcase: n < a *) apply (insert_lt n a l) in H1 as H2. rewrite H2 in H. apply (sorted_cons n a l) in H1. apply sorted_tl in H1 as H3. assumption. apply sorted_tl in H. assumption. + inversion H1. ++ (* Subcase: n = a *) apply (insert_eq n a l) in H2 as H3. rewrite H3 in H. assumption. ++ (* Subcase: n > a *) apply (insert_gt n a l) in H2 as H3. rewrite H3 in H. apply sorted_tl in H as IH. apply IHl in IH. inversion IH. apply sorted_1. rewrite <- H4 in H. assert (x < n \/ x = n \/ x > n). lia. inversion H5. (* Sub-subcases [sorted [a; x]]. *) * (* Sub-subcase: x < n *) apply (insert_gt n x []) in H6 as H7. rewrite H7 in H. unfold insert in H. inversion H. apply (sorted_cons a x []) in H10 as H13. assumption. apply sorted_1. * inversion H6. ** (* Sub-subcase: x = n *) apply eq_sym in H7. apply (insert_eq n x []) in H7 as H8. rewrite H8 in H. assumption. ** (* Sub-subcase: x > n *) assert (a < x). lia. apply (sorted_cons a x []) in H8. assumption. apply sorted_1. (* Subcases to prove [sorted (a :: x :: y :: l0)] *) * apply (sorted_cons x y l0) in H4 as H4a. inversion H. contradict H9. apply (insert_nonempty n l). assert (Some y0 = hd_error (insert n l)). { rewrite <- H8. unfold hd_error; reflexivity. } assert (x = y0 \/ n = y0). { apply (sorted_head n x (y :: l0)) in H4a as H4b. rewrite H6 in H4b. rewrite <- H11 in H4b. inversion H4b. left. injection H12. auto. right. injection H12. auto. } inversion H12. ** (* insert n l = x :: (stuff) *) rewrite <- H13 in H8; rewrite <- H13 in H10; rewrite <- H13 in H9. apply (sorted_cons a x (y :: l0)) in H9. apply H9. apply H4a. ** (* insert n l = n :: l *) rewrite <- H13 in H8; rewrite <- H13 in H10; rewrite <- H13 in H9. inversion H8. unfold insert in H15. rewrite <- H6 in H15. apply (sorted_cons a n (y :: l0)) in H9. apply H9. sorted (a :: n :: y :: l0) rewrite H6 in H4b. apply (insert_lt n x []) in H7 as H8. rewrite H8 in H. unfold insert in H. induction l. apply sorted_1. inversion IH. rewrite <- H6 in IH. Admitted. *) Lemma sorted_split : forall (l1 l2 : list nat), sorted (l1 ++ l2) -> sorted l1 /\ sorted l2. Proof. intros. induction l1. - rewrite (app_nil_l l2) in H; split. apply sorted_nil. apply H. - rewrite <- (app_comm_cons l1 l2 a) in H. apply sorted_tl in H as H1. apply IHl1 in H1. split. destruct l1. -- apply sorted_1. -- inversion H. assert (sorted (n :: l1)). apply H1. apply sorted_tl in H6 as H7. apply (sorted_cons a n l1). assumption. assumption. -- apply H1. Qed. Lemma sorted_head_min : forall (n k : nat) (l : list nat), sorted (n :: l) -> In k l -> n < k. Proof. intros. induction l. - contradict H0. - apply (sorted_tl n (a::l)) in H as IH. destruct l. -- unfold In in H0. inversion H. destruct H0. apply eq_sym in H0. rewrite H0. assumption. contradict H0. -- inversion H. inversion H5. clear H6 H7 H9 H1 H2 H4. assert (n < n0). { rewrite <- H8. assumption. } inversion H0. apply eq_sym in H2. rewrite H2. assumption. apply (sorted_cons n n0 l) in H1. apply IHl in H1 as IH1. assumption. assumption. assumption. Qed. (* Lemma sorted_split_ends : forall (l1 l2 : list nat), sorted (l1 ++ l2) -> (forall (a b : nat), In a l1 /\ In b l2 -> a < b). Admitted. Proof. intros. induction l1. - apply proj1 in H0. contradict H0. - apply proj1 in H0 as H1; apply proj2 in H0 as H2. destruct l1. -- (* Subcase: l1 = [] *) apply sorted_tl in H as IH. unfold app in IHl1; unfold app in H. assert (a0 = a). { unfold In in H1. intuition. } rewrite H3 in H; rewrite H3 in H1; rewrite H3 in H0. apply (sorted_head b a l2) in H. apply IHl1 in IH. assumption. assumption. -- (* Subcase: l1 = n :: l1 *) rewrite <- (app_comm_cons (n :: l1) l2 a0) in H. apply sorted_tl in H as IH. assert (a = a0 \/ a <> a0). { lia. } inversion H3. + (* a = a0 *) rewrite <- H4 in H; rewrite <- H4 in H1. apply (sorted_head a b ((n :: l1) ++ l2)) in H. assumption. apply (in_or_app (n :: l1) l2 b). auto. + (* a <> a0 *) assert (In a (n :: l1)). { inversion H1. apply eq_sym in H5. contradict H5. assumption. assumption. } apply IHl1 in IH. assumption. split. assumption. assumption. Qed. Lemma insert_split : forall (n : nat) (l1 l2 : list nat), sorted (l1 ++ n::l2) -> (l1 ++ n::l2) = insert n (l1 ++ n::l2). Admitted. *) (* Theorem insert_existing_sorted : forall (n : nat) (l : list nat), sorted l -> In n l -> l = insert n l. Proof. intros. apply in_split in H0 as H1. destruct H1. destruct H1. rewrite H1 in H. apply insert_split in H. rewrite <- H1 in H. apply H. Qed. *) Lemma sorted_in_inv : forall (n h : nat) (tl : list nat), sorted(h :: tl) -> In n (h::tl) -> h=n \/ (In n tl). Proof. intros. apply in_inv in H0. trivial. Qed. Lemma sorted_surgery : forall ( a b : nat) (tl : list nat), sorted (a :: b :: tl) -> sorted (a :: tl). Proof. intros. inversion H. apply sorted_tl in H4 as H5. destruct tl. - apply sorted_1. - inversion H4. assert (a < n). { Nat.order. } apply (sorted_cons a n tl) in H11. assumption. assumption. Qed. Lemma sorted_in_tl : forall (n h : nat) (tl : list nat), sorted (h :: tl) -> In n tl -> h < n. Proof. intros. induction tl. - (* Base case: tl = [] *) contradict H0. - (* Inductive case: tl = a::tl *) inversion H. (* -- (* Case: sorted_1 *) contradict H0. rewrite <- H3. apply in_nil. *) -- (* Case: sorted_cons where [h < y] and [tl = y::l] *) rewrite <- H2 in H0. apply in_inv in H0 as H6. case H6. + (* Subcase: [n = y] *) intro. rewrite H7 in H2. rewrite <- H2 in H3. assumption. + (* Subcase: [In n l] *) intro. apply sorted_surgery in H as IH. apply IHtl in IH. apply IH. assumption. Qed. Theorem insert_existing_sorted : forall (n : nat) (l : list nat), sorted l -> In n l -> l = insert n l. Proof. intros. induction l as [|h tl]. - contradict H0. - inversion H. + rewrite <- H3 in H0; rewrite <- H3 in H. assert (h = n). { unfold In in H0. intuition. } rewrite H1; rewrite H1 in H0; rewrite H1 in H. assert (n = n). reflexivity. apply (insert_eq n n []) in H4. symmetry. assumption. + (* Subcase sorted_cons : tl=y::l, h < y, sorted(y :: l) *) apply in_inv in H0. case H0. ++ (* Case of [In h n::tl] when [h = n] *) intro. rewrite H5. rewrite (insert_eq n n (y::l)). reflexivity. reflexivity. ++ (* Case of [In h n::tl] when [In h tl] *) intro. (* apply sorted_tl in H as IH. apply IHtl in IH. *) rewrite <- H2 in H5. apply in_inv in H5. case H5. (* Since [tl = y::l], we do this again! *) +++ intro. rewrite H6; rewrite H6 in H5; rewrite H6 in H2; rewrite H6 in H3; rewrite H6 in H4. rewrite (insert_gt n h (n :: l)). rewrite (insert_eq n n l). reflexivity. reflexivity. assumption. +++ (* Last case: In n l -> h :: y :: l = insert n (h :: y :: l) *) intro. (* INDUCTION SAVES US, AT LONG LAST! *) apply sorted_tl in H as IH. apply IHtl in IH. rewrite H2. apply (sorted_in_tl n h tl) in H as IH1. apply (insert_gt n h tl) in IH1. rewrite <- IH in IH1. auto. rewrite <- H2. simpl; auto. rewrite <- H2. simpl; auto. Qed. Lemma eq_lists_eq_len {A} : forall (l1 l2 : list A), l1 = l2 -> length l1 = length l2. Proof. intros. rewrite H. reflexivity. Qed. (* Theorem insert_nondecreasing : forall (n : nat) (l : list nat), sorted l -> length l <= length (insert n l). Proof. intros. assert (In n l \/ ~In n l). 2: { inversion H0. - apply (insert_existing_sorted n l) in H as H2. apply eq_lists_eq_len in H2 as H3. Nat.order. assumption. - assumption. Admitted. *) Lemma in_singleton_eq : forall {A} (a x : A), In a [x] -> a = x. Proof. intros. unfold In in H. intuition. Qed. Theorem insert_singleton_invert : forall (n x : nat) (l : list nat), [x] = (insert n l) -> l = [] \/ l = [n]. Proof. intros. assert (sorted [x]). apply sorted_1. rewrite H in H0. assert (In n [x]). { rewrite H. apply (insert_inv n l). } apply (in_singleton_eq n x) in H1. rewrite <- H1 in H. clear H1. induction l as [|n0 l0]. - (* Case: l = [] *) left; reflexivity. - (* Case: l = n0::l0 *) assert (n < n0 \/ n = n0 \/ n > n0). lia. -- destruct H1. + (* Subcase: n < n0 *) apply (insert_lt n n0 l0) in H1. rewrite H1 in H; rewrite H1 in H0. inversion H0; right; discriminate. + destruct H1. ++ (* Subcase: n = n0 *) apply (insert_eq n n0 l0) in H1. rewrite H1 in H; rewrite H1 in H0. right; symmetry. apply H. ++ (* Subcase: n > n0 *) apply (insert_gt n n0 l0) in H1 as H2. rewrite H2 in H; rewrite H2 in H0. inversion H0. +++ (* Sub-subcase (sorted_1) : l0 = [] *) right. rewrite <- H5 in H. contradict H5. apply (insert_nonempty n l0). +++ (* Sub-subcase (sorted_cons) [sorted (insert n (n0 :: l0))] becomes : n0 < y -> sorted( y :: l) -> sorted(n0 :: y :: l)*) rewrite <- H4 in H; rewrite <- H4 in H2. left. discriminate. Qed. Require Import Coq.Classes.RelationClasses. Theorem nat_comparison : forall (a b : nat), a < b \/ a = b \/ a > b. Proof. intros. lia. Qed. Lemma gt_to_not_ltb : forall (n a : nat), n > a -> Nat.ltb n a = false. Proof. intros. bdestruct (n <? a); simpl. contradict H0. lia. reflexivity. Qed. Lemma gt_to_not_eqb : forall (n a : nat), n > a -> Nat.eqb n a = false. Proof. intros. bdestruct (n =? a); simpl. contradict H0. lia. reflexivity. Qed. Lemma invert_insert_sorted : forall (n a n0 : nat) (l l0 : list nat), sorted (a :: l) -> insert n (a :: l) = a :: n0 :: l0 -> a < n0. Proof. intros. assert (a > n \/ a = n \/ a < n). lia. generalize dependent l0. induction l. - intros. destruct H1. -- (* Subcase: a > n *) apply (insert_lt n a []) in H1 as H2. rewrite H2 in H0. contradict H0. injection. intros. lia. -- destruct H1. --- (* Subcase: a = n *) apply eq_sym in H1. apply (insert_eq n a []) in H1 as H2. rewrite H2 in H0. contradict H0. injection. discriminate. --- (* Subcase: a < n *) apply (insert_gt n a []) in H1 as H2. rewrite H2 in H0. unfold insert in H0. injection H0. intros. rewrite H4 in H1. assumption. - (* Inductive case: l = a0::l *) destruct H1. -- intros. apply Nat.ltb_lt in H0 as H2. unfold insert in H1. rewrite H2 in H1. contradict H1. injection. intros. rewrite <- H3 in H1. injection H1. intro. lia. -- destruct H0. + (* Subcase: a = n *) intros. apply eq_sym in H0. apply (insert_eq n a (a0::l)) in H0 as H3. rewrite H3 in H1. injection H1. intros. rewrite H4 in H. inversion H. assumption. + (* Subase: a < n *) intros. apply (sorted_surgery a a0 l) in H as IH. apply (insert_gt n a (a0 :: l)) in H0 as H2. assert (a0 < n \/ a0 = n \/ a0 > n). lia. destruct H3. ++ (* a0 < n *) apply (insert_gt n a0 l) in H3 as H4. apply (insert_gt n a (a0 :: l)) in H0 as H5. rewrite H4 in H2. rewrite H2 in H1. injection H1. intros. rewrite H7 in H. inversion H. assumption. ++ destruct H3. * (* Case a0 = n *) apply eq_sym in H3. apply (insert_eq n a0 l) in H3 as H4. rewrite H4 in H2. rewrite H2 in H1. injection H1. intros. inversion H. rewrite H6 in H9. assumption. * (* Case a0 > n *) apply (insert_lt n a0 l) in H3 as H4. assert (insert n (a :: a0 :: l) = a :: insert n (a0 :: l)). assumption. rewrite H4 in H2. rewrite H4 in H5. rewrite H1 in H5. injection H5. intros. rewrite H7. assumption. Qed. Theorem insert_preserves_sorted : forall (n : nat) (l : list nat), sorted l -> sorted (insert n l). Proof. intros. induction l. - unfold insert. apply sorted_1. - apply sorted_tl in H as H1. apply IHl in H1. assert (n < a \/ n = a \/ n > a). lia. inversion H0. -- (* Case: n < a *) apply (insert_lt n a l) in H2 as H3. rewrite H3. apply sorted_cons. assumption. assumption. -- (* Case: n = a *) inversion H2. apply (insert_eq n a l) in H3 as H4. rewrite H4. assumption. (* Case: n > a *) apply (insert_gt n a l) in H3 as H4. rewrite H4. destruct (insert n l). + apply sorted_1. + clear H0; clear H2. apply sorted_tl in H1 as H5. assert (n < n0 \/ n = n0 \/ n > n0). lia. inversion H0. (* case: n < n0 *) ++ apply sorted_cons. rewrite <- H2. assumption. assumption. ++ (* case: n = n0 *) inversion H2. apply sorted_cons. rewrite <- H6. assumption. assumption. (* case: n > n0 *) clear H2 H0. inversion H4. apply gt_to_not_ltb in H3 as H8. rewrite H8. rewrite H8 in H2. clear H8; apply gt_to_not_eqb in H3 as H8. rewrite H8; rewrite H8 in H2. apply (invert_insert_sorted n a n0 l l0) in H4 as H7. apply eq_list in H2. rewrite H2. apply sorted_cons. assumption. assumption. assumption. Qed. (* Theorem insert_preserves_sorted2 : forall (n : nat) (l : list nat), sorted l -> sorted (insert n l). Proof. intros. induction l. - unfold insert. apply sorted_1. - apply sorted_tl in H as H1. apply IHl in H1. assert (n < a \/ n = a \/ n > a). lia. inversion H0. -- apply (insert_lt n a l) in H2 as H3. rewrite H3. apply sorted_cons. assumption. assumption. -- inversion H2. --- apply (insert_eq n a l) in H3 as H4. rewrite H4. assumption. --- apply (insert_gt n a l) in H3 as H4. rewrite H4. destruct (insert n l). apply sorted_1. set (ln := insert n l). inversion H4. auto; simpl. + apply sorted_1. + assert (n = n0 \/ n <> n0). lia. inversion H5. ++ apply sorted_cons. rewrite <- H6. assumption. rewrite <- H6. + unfold insert in ln. unfold ln. apply sorted_cons. assumption. apply sorted_1. + destruct l. + unfold insert. apply sorted_cons. assumption. apply sorted_1. + set (ln := insert n l). destruct l. auto. apply (sorted_cons a n l) in H3. apply (sorted_tl a (insert n l)) in H1 as H5. apply sorted_tl with (n := a) (l := insert n l) in H1 as H5. apply (sorted_cons a n l) in H3. Admitted. *) (* Theorem insert_preserves_sorted : forall (n : nat) (l : list nat), sorted l -> sorted (insert n l). Proof. intros. induction l. - unfold insert. apply sorted_1. - apply sorted_tl in H as H1. apply IHl in H1. assert (n < a \/ n = a \/ n > a). lia. inversion H0. -- apply (insert_lt n a l) in H2 as H3. rewrite H3. apply sorted_cons. assumption. assumption. -- inversion H2. --- apply (insert_eq n a l) in H3 as H4. rewrite H4. assumption. --- apply (insert_gt n a l) in H3 as H4. rewrite H4. apply (sorted_cons a n l) in H3. -- contradict H2. apply insert_nonempty. -- apply (insert_singleton_invert n x l) in H2. rewrite H2. assert (n < a \/ n = a \/ n > a). lia. inversion H0. --- apply (insert_lt n a []) in H3 as H4. rewrite H4. apply sorted_cons. assumption. apply sorted_1. --- inversion H3. apply (insert_eq n a []) in H4 as H5. rewrite H5. apply sorted_1. apply (insert_gt n a []) in H4 as H5. rewrite H5. unfold insert. apply sorted_cons. assumption. apply sorted_1. -- auto. --- auto. *) Lemma insert_different : forall (a n : nat) (l : list nat), sorted (a :: l) -> a <> n -> (n < a -> sorted (n :: a :: l)) /\ (a < n -> sorted (a :: insert n l)). (* Proof. intros. split. - intro H1. apply sorted_cons. assumption. assumption. - intro H1. apply (insert_gt n a l) in H1 as H2. rewrite <- H2. apply sorted_tl in H as H2. destruct l. -- unfold insert. apply sorted_cons. assumption. apply sorted_1. -- apply (sorted_cons a n (n0 :: l)) in H1. inversion H1. unfold insert. assert (a < n \/ n > a). 2: { split. } *) Admitted. (* Theorem insert_if_present : forall (n : nat) (l : list nat), sorted l -> In n l -> insert n l = l. Proof. intros. induction l. - unfold In in H. contradiction. - bdestruct (n =? a). -- unfold insert. assert (~ n < a). { lia. } (* intuition. *) assert (Nat.ltb n a = false). { apply Nat.nlt_ge in H2 as H3. unfold Nat.ltb. apply leb_correct_conv. intuition. } rewrite H3. apply (Nat.eqb_eq n a) in H1. rewrite H1. reflexivity. -- apply List.in_inv in H0 as H2. assert (List.In n l). { firstorder. contradict H0. auto. } apply sorted_tl in H as H4. apply IHl in H3 as IHl2. discriminate. intuition. --- symmetry in H5. contradict H5. auto. --- auto. assert (a < n). 2: { intuition. apply Nat.ltb_lt in H5 as H6. unfold insert. apply H6. --- unfold insert. apply Nat.eqb_eq in H5. simpl. auto. apply (ltb_reflect n a) in H1. auto. rewrite H0. rewrite <- H0. Lemma insert_different : forall (a n : nat) (l : list nat), sorted (a :: l) -> a <> n -> sorted (n :: a :: l) \/ sorted (a :: insert n l). *) Fixpoint insert_merge (l1 l2 : list nat) := match l1 with | [] => l2 | a::tl => insert_merge tl (insert a l2) end. Theorem insert_merge_sorted : forall (l1 l2 : list nat), sorted l1 -> sorted l2 -> sorted (insert_merge l1 l2). Proof. intros. generalize dependent l2. induction l1. - (* Base case: l1 = nil *) intros. unfold insert_merge; auto. - (* Inductive case: l1 = a::l1 *) intros. assert (forall l2 : list nat, sorted l2 -> sorted (insert_merge l1 l2)). { apply IHl1. apply sorted_tl in H. assumption. } assert (sorted (insert a l2)). { apply insert_preserves_sorted. assumption. } assert (insert_merge (a :: l1) l2 = insert_merge l1 (insert a l2)). { unfold insert. simpl; auto. } rewrite H3. apply H1 in H2. assumption. Qed. Theorem insert_merge_sorted2 : forall (l1 l2 : list nat), sorted l2 -> sorted (insert_merge l1 l2). Proof. intros. generalize dependent l2. induction l1. - (* Base case: l1 = nil *) intros. unfold insert_merge; auto. - (* Inductive case: l1 = a::l1 *) intros. assert (forall l2 : list nat, sorted l2 -> sorted (insert_merge l1 l2)). { apply IHl1. } assert (sorted (insert a l2)). { apply insert_preserves_sorted. assumption. } assert (insert_merge (a :: l1) l2 = insert_merge l1 (insert a l2)). { unfold insert. simpl; auto. } rewrite H2. apply H0. apply insert_preserves_sorted. assumption. Qed. Theorem insert_merge_idempotent : forall (l1 l2 : list nat), sorted l2 -> incl l1 l2 -> l2 = insert_merge l1 l2. Proof. intros. induction l1. - simpl; auto. - apply incl_cons_inv in H0 as H1. destruct H1. assert (insert_merge (a :: l1) l2 = insert_merge l1 (insert a l2)). { simpl; auto. } assert(l2 = insert a l2). { apply insert_existing_sorted. assumption. assumption. } rewrite H3. rewrite <- H4. apply IHl1. assumption. Qed. Lemma insert_merge_idem_right : forall l, insert_merge l [] = l. Admitted. (** * Fresh Number The other important function we want to implement concerns, given a list [l : list nat], find the first natural number *not* in the list. *) Fixpoint first_new (n : nat) (l : list nat) : nat := match l with | (h::tl)%list => if Nat.eqb h n then first_new (S n) tl else first_new n tl | []%list => n end. Lemma first_new_eq {l n} : first_new n (n::l) = first_new (S n) l. Proof. intros. assert (Nat.eqb n n = true). apply Nat.eqb_eq; reflexivity. unfold first_new; rewrite H. reflexivity. Qed. Require Import Coq.Arith.EqNat. Lemma neq_is_neqb {a b} : a <> b -> Nat.eqb a b = false. Admitted. Lemma first_new_not_eq {l a n} : a <> n -> first_new n (a::l) = first_new n l. Proof. intros. assert (Nat.eqb a n = false). apply neq_is_neqb; assumption. unfold first_new. rewrite H0. simpl; auto. Qed. Require Import Coq.Lists.ListDec. Theorem first_new_nondecreasing {l n} : n <= first_new n l. Proof. generalize dependent n. induction l. - simpl; auto. - intros. assert({a = n} + {a <> n}). decide equality. destruct H. + (* Case: a = n *) rewrite e. assert (first_new n (n::l) = first_new (S n) l). apply first_new_eq. rewrite H. assert (n < S n). lia. assert (S n <= first_new (S n) l). apply IHl. lia. + (* Case: a <> n *) apply (@first_new_not_eq l a n) in n0. rewrite n0. apply IHl. Qed. Theorem first_new_lt {l x n} : sorted (x :: l) -> n < x -> first_new n (x::l) = n. Proof. intros. induction l. - assert (x <> n). lia. apply (@first_new_not_eq [] x n) in H1. rewrite H1. unfold first_new. reflexivity. - assert (sorted (x :: l)). { apply sorted_surgery in H. assumption. } apply IHl in H1 as H2. assert (x <> n). lia. apply (@first_new_not_eq l x n) in H3 as H4. inversion H. clear H5 H8 H6. assert (a <> n). lia. apply (@first_new_not_eq l a n) in H5 as H6. assert (first_new n (x :: a :: l) = first_new n (a :: l)). { apply (@first_new_not_eq (a::l) x n). assumption. } rewrite H8. rewrite H6. rewrite <- H4. assumption. Qed. Lemma first_new_not_in_lt {l l0 a n} : l = a::l0 -> sorted (l) -> n < a -> ~In (first_new n l) l. Proof. intros. assert (first_new n (a::l0) = n). { apply (@first_new_lt l0 a n). rewrite <- H. assumption. assumption. } rewrite H. rewrite H2. rewrite <- H. generalize dependent a. generalize dependent l0. induction H0. - intros; apply in_nil. - intros; apply not_in_cons. split. inversion H. lia. apply in_nil. - intros. assert (sorted (x :: y :: l)). { apply (sorted_cons x y l). assumption. assumption. } apply not_in_cons. split. + inversion H1. lia. + apply (IHsorted l y). reflexivity. inversion H1. lia. apply first_new_lt. assumption. inversion H1. lia. Qed. Lemma first_new_not_in_gt {l x y n} : forall (IHsorted : forall n : nat, ~ In (first_new n (y :: l)) (y :: l)), sorted (y :: l) -> x < n -> x < y -> ~ In (first_new n (x :: y :: l)) (x :: y :: l). Proof. intros. apply not_in_cons. split. - assert(n <= first_new n (x :: y :: l)). { apply first_new_nondecreasing. } lia. - assert(x <> n). lia. apply (@first_new_not_eq (y::l) x n) in H2. rewrite H2. apply IHsorted. Qed. Theorem first_new_not_in {l n} : sorted l -> ~ In (first_new n l) l. Proof. intros. generalize dependent n. induction H. - (* Base case: sorted_nil. *) simpl; auto. - (* Base case: sorted_1. *) intros. assert ({x = n} + {x <> n}). decide equality. destruct H. + (* If x = n *) rewrite e. assert (first_new n [n] = first_new (S n) []). apply first_new_eq. rewrite H. unfold first_new. apply not_in_cons. simpl; auto. + (* If x <> n *) apply (@first_new_not_eq [] x n) in n0 as H. rewrite H. unfold first_new. apply not_in_cons. simpl; auto. - (* Inductive case (sorted_cons): x < y && sorted (y::l0) && l = x::y::l0 *) intros. assert ({x < n} + {x = n} + {n < x}). apply lt_eq_lt_dec. destruct H1. destruct s. -- (* x < n *) apply (@first_new_not_in_gt l x y n IHsorted). assumption. assert (x <> n). lia. assumption. assumption. -- (* x = n *) rewrite e. assert (first_new n (n :: y :: l) = first_new (S n) (y :: l)). apply first_new_eq. rewrite H1. apply not_in_cons. assert (S n <> n). lia. assert (S n <= first_new (S n) (y :: l)). apply first_new_nondecreasing. split. lia. apply IHsorted. -- (* x > n *) apply (@first_new_not_in_lt (x :: y :: l) (y :: l) x n). reflexivity. apply sorted_cons. assumption. assumption. assumption. Qed. Theorem insert_merge_list_fold_sorted : forall (A : Type) (f : A -> list nat) (l : list A) (init : list nat), sorted init -> sorted (List.fold_left (fun l' => fun (a : A) => insert_merge (f a) l') l init%list). Proof. intros. generalize dependent init. induction l. - simpl; auto. - intros. assert((fold_left (fun (l' : list nat) (a0 : A) => insert_merge (f a0) l') (a :: l) init) = (fold_left (fun (l' : list nat) (a0 : A) => insert_merge (f a0) l') l (insert_merge (f a) init))). { simpl; auto. } rewrite H0. assert (sorted (insert_merge (f a) init)). { apply insert_merge_sorted2. assumption. } apply IHl in H1 as IH. apply IH. Qed. Theorem insert_merge_list_fold_sorted2 : forall (A : Type) (f : A -> list nat -> list nat) (l : list A) (init : list nat), sorted init -> sorted (List.fold_left (fun l' => fun (a : A) => insert_merge (f a l') l') l init%list). Proof. intros. generalize dependent init. induction l. - simpl; auto. - intros. assert((fold_left (fun (l' : list nat) (a0 : A) => insert_merge (f a0 l') l') (a :: l) init) = (fold_left (fun (l' : list nat) (a0 : A) => insert_merge (f a0 l') l') l (insert_merge (f a init) init))). { simpl; auto. } rewrite H0. assert (sorted (insert_merge (f a init) init)). { apply insert_merge_sorted2. assumption. } apply IHl in H1 as IH. apply IH. Qed. Require Export Coq.Vectors.VectorSpec. Theorem insert_merge_vector_fold_sorted {n} : forall (A : Type) (f : A -> list nat) (v : Vector.t A n) (init : list nat), sorted init -> sorted (Vector.fold_left (fun l' => fun (a : A) => insert_merge (f a) l') init v). Proof. intros. assert(Vector.fold_left (fun l' => fun (a : A) => insert_merge (f a) l') init v = List.fold_left (fun l' => fun (a : A) => insert_merge (f a) l') (Vector.to_list v) init). { apply to_list_fold_left. } rewrite H0. apply insert_merge_list_fold_sorted. assumption. Qed. Theorem insert_merge_vector_fold_sorted2 {n} : forall (A : Type) (f : A -> list nat -> list nat) (v : Vector.t A n) (init : list nat), sorted init -> sorted (Vector.fold_left (fun l' => fun (a : A) => insert_merge (f a l') l') init v). Proof. intros. assert(Vector.fold_left (fun l' => fun (a : A) => insert_merge (f a l') l') init v = List.fold_left (fun l' => fun (a : A) => insert_merge (f a l') l') (Vector.to_list v) init). { apply to_list_fold_left. } rewrite H0. apply insert_merge_list_fold_sorted2. assumption. Qed. Require Import Nat. Require Import Coq.Arith.PeanoNat. Lemma first_new_cons {l n} : first_new n (n :: l) = first_new (S n) l. Proof. assert(n = n). reflexivity. apply Nat.eqb_eq in H as H1. simpl; auto. rewrite H1. reflexivity. Qed. Lemma neq_neqb : forall (n k : nat), n <> k <-> Nat.eqb n k = false. Proof. intros. revert n. induction k as [|k IHk]; intro n; destruct n; simpl; rewrite ?IHk; split; try easy. - intros. assert (n <> k). red; auto. apply IHk in H0. assumption. - intros. apply IHk in H. red; auto. Qed. Lemma first_new_distinct {l a n} : a <> n -> first_new n (a :: l) = first_new n l. Proof. intros. apply neq_neqb in H as H1. simpl; auto. rewrite H1. reflexivity. Qed. Lemma fresh_new_step {l n k} : first_new n l = first_new n (k::l) \/ first_new (S n) l = first_new n (k::l). Proof. assert({k = n} + {k <> n}). decide equality. destruct H. - right. rewrite e. symmetry. apply first_new_cons. - left. apply (@first_new_distinct l k n) in n0. symmetry; assumption. Qed. (* Lemma first_new_nondecreasing {l n} : n <= first_new n l. Proof. generalize dependent n. induction l. - simpl; auto. - intros. assert ({a = n} + {a <> n}). decide equality. destruct H. -- rewrite e. assert (first_new n (n :: l) = first_new (S n) l). apply first_new_cons. rewrite H. assert (S n <= first_new (S n) l). apply (@IHl (S n)). intuition. -- assert(first_new n l = first_new n (a :: l)). symmetry. apply (@first_new_distinct l a n). assumption. rewrite <- H. apply IHl. Qed. *) Lemma fresh_succ_nonzero {l n} : 0 < first_new (S n) l. Proof. intros. generalize dependent n. induction l. - simpl; auto. apply Nat.lt_0_succ. - intros. destruct (@fresh_new_step l (S n) a). + rewrite <- H. apply IHl. + rewrite <- H. apply (IHl (S n)). Qed. (* Lemma first_new_cons_inv {l n a} : a = n <-> first_new n (a :: l) = first_new (S n) l. Proof. assert ({a = n} + {a <> n}). decide equality. destruct H. - split. -- rewrite e. intros. apply first_new_cons. -- intros; assumption. - split. contradiction. intros. inversion H. assert (Nat.eqb a n = false). { apply neq_neqb. assumption. } rewrite H0 in H1. split. - intros. rewrite H. apply first_new_cons. - intros. inversion H. assert(n = n). reflexivity. apply Nat.eqb_eq in H as H1. simpl; auto. rewrite H1. reflexivity. Qed. *) Require Import Coq.Arith.Compare. Lemma first_new_on_different_args {l m n} : m <= n -> first_new m l <= first_new n l. Proof. intros. generalize dependent m. generalize dependent n. induction l. - simpl; auto. - intros. assert ({n = a} + {n <> a}). decide equality. destruct H0. + assert (first_new n (n :: l) = first_new (S n) l). apply first_new_cons. assert ({m = a} + {m <> a}). decide equality. destruct H1. ++ rewrite e0; rewrite <- e. reflexivity. ++ (* m <> a && n = a *) assert (first_new m (a :: l) = first_new m l). { apply (@first_new_distinct l a m); intuition. } rewrite H1. assert (n <= first_new n (a :: l)). { apply first_new_nondecreasing. } rewrite <- e; rewrite H0. apply IHl. intuition. + (* n <> a *) assert (first_new n (a :: l) = first_new n l). { apply (@first_new_distinct l a n); intuition. } assert ({m = a} + {m <> a}). decide equality. destruct H1. ++ (* n <> a && m = a *) assert (first_new m (a :: l) = first_new (S m) l). { rewrite <- e; apply first_new_cons. } assert (S m <= n \/ m = n). { apply le_le_S_eq in H. assumption. } destruct H2. +++ (* S m <= n *) rewrite H0. rewrite H1. apply IHl. intuition. +++ rewrite H2. reflexivity. ++ assert (first_new m (a :: l) = first_new m l). { apply (@first_new_distinct l a m); intuition. } rewrite H1; rewrite H0. apply IHl. assumption. Qed. (** * Segments -- range of integers At present, it seems like I will need to use a consecutive, finite sequence of natural numbers. I defined it as a fixpoint, then proved a number of useful theorems about it. *) Fixpoint nat_range_list (n : nat) : list nat := match n with | 0 => []%list | S n' => ((nat_range_list n') ++ [n'])%list end. Lemma test_works2 : [0;1;2]%list = nat_range_list 3. Proof. unfold nat_range_list. simpl; auto. Qed. Lemma nat_range_list_ind : forall (n : nat), nat_range_list (S n) = ((nat_range_list n) ++ [n])%list. Proof. intros. induction n. - unfold nat_range_list; simpl; auto. - unfold nat_range_list; simpl; auto. Qed. Require Import Lia. Theorem nat_range_list_length : forall (n : nat), length (nat_range_list n) = n. Proof. intros. induction n. - unfold nat_range_list; simpl; auto. - assert (nat_range_list (S n) = ((nat_range_list n) ++ [n])%list). { apply nat_range_list_ind. } rewrite H. assert (length (nat_range_list n ++ [n]) = (length (nat_range_list n)) + (length [n]%list)). { apply List.app_length. } rewrite H0. rewrite IHn. unfold length. lia. Qed. Lemma nth_cons : forall {A} (n : nat) (l : list A) (a default : A), nth (S n) (a::l) default = nth n l default. Proof. intros. induction l. - unfold nth; simpl; auto. - unfold nth; simpl; auto. Qed. Lemma last_nth : forall {A} (n n' : nat) (l : list A) (default : A), S n' = n -> n = length l -> List.nth n' l default = List.last l default. Proof. intros. generalize dependent n'. generalize dependent n. induction l. - intros. unfold length in H0. rewrite H0 in H. contradict H. unfold length; simpl; auto. - intros. destruct l. + unfold length in H0. rewrite H0 in H. assert (n' = 0). lia. rewrite H1. unfold nth; unfold last; simpl; auto. + set (n'' := length l). assert (S n'' = length (a0 :: l)). { unfold length; simpl; auto; lia. } assert (S (S n'') = length (a :: a0 :: l)). { unfold length; simpl; auto; lia. } assert (S (S n'') = n). { lia. } assert (S n'' = n'). { lia. } assert (n' = length (a0 :: l)). lia. rewrite <- H4. assert(last (a :: a0 :: l) default = last (a0 :: l) default). { simpl; auto. } rewrite H6. assert (nth (S n'') (a :: a0 :: l) default = nth n'' (a0 :: l) default). { simpl; auto. } rewrite H7. apply (IHl n'). assumption. assumption. Qed. Lemma nat_range_list_incl_end : forall (n : nat), List.incl (nat_range_list n) (nat_range_list (S n)). Proof. intros. induction n. - unfold nat_range_list; simpl; auto. unfold incl; simpl; auto. - set (m := S n). assert (nat_range_list m = (nat_range_list n ++ [n])%list). { unfold nat_range_list; unfold m; simpl; auto. } assert (nat_range_list (S m) = (nat_range_list m ++ [m])%list). { unfold nat_range_list; unfold m; simpl; auto. } assert (nat_range_list (S m) = (nat_range_list n ++ [n; m])%list). { rewrite H0. rewrite H. symmetry. apply (List.app_assoc (nat_range_list n) ([n]%list) ([m]%list)). } rewrite H1. rewrite H. assert (incl [n]%list [n; m]%list). { unfold incl; simpl; auto. intros. destruct H2. left; simpl; auto. simpl; auto. } apply List.incl_app_app; simpl; auto. apply List.incl_refl. Qed. Theorem nat_range_list_incl : forall (m n : nat), m < n -> List.incl (nat_range_list m) (nat_range_list n). Proof. intros. generalize dependent m. induction n. - intros. contradict H; lia. - intros. assert (incl (nat_range_list n) (nat_range_list (S n))). { apply nat_range_list_incl_end. } assert ({m = n} + {m <> n}). decide equality. destruct H1. + rewrite e. assumption. + assert (m < n). { lia. } assert (incl (nat_range_list m) (nat_range_list n)). { apply IHn. assumption. } apply (@incl_tran nat (nat_range_list m) (nat_range_list n) (nat_range_list (S n))). assumption. assumption. Qed. Theorem nat_range_list_firstn : forall (m n : nat), m < n -> List.firstn m (nat_range_list n) = nat_range_list m. Proof. intros. generalize dependent m. induction n. - intros. contradict H; lia. - intros. assert({m = n} + {m <> n}). decide equality. assert(nat_range_list (S n) = (nat_range_list n ++ [n])%list). { unfold nat_range_list; simpl; auto. } destruct H0. + rewrite e. rewrite H1. set (l := nat_range_list n). assert (n = length l). { symmetry. apply nat_range_list_length. } assert (firstn (length l + 0) (l ++ [n])%list = l). { assert (firstn 0 [n]%list = List.nil). { simpl; auto. } assert (l = (l ++ (firstn 0 [n]%list))%list). { simpl; auto. symmetry. apply app_nil_r. } set (l2 := firstn (length l + 0) (l ++ [n])%list). rewrite H3. unfold l2. apply (@firstn_app_2 nat 0 l ([n])%list). } assert (length l + 0 = length l). { simpl; auto. } rewrite H3 in H2. rewrite <- H0 in H2. assumption. + assert (m < n) as IH. lia. apply IHn in IH. destruct m as [| m']. ++ (* m = 0 *) apply firstn_O. ++ (* m = S m' *) set (l := skipn (S m') (nat_range_list n)). assert (nat_range_list n = (nat_range_list (S m') ++ l)%list). { symmetry. rewrite <- IH. unfold l. apply (@firstn_skipn nat (S m') (nat_range_list n)). } assert (nat_range_list (S n) = ((nat_range_list (S m') ++ l) ++ [n])%list). { rewrite <- H0. rewrite H1. reflexivity. } rewrite H2. assert (((nat_range_list (S m') ++ l) ++ [n])%list = (nat_range_list (S m') ++ (l ++ [n]))%list). { symmetry. apply app_assoc. } rewrite H3. set (l' := (l ++ [n])%list). assert (length (nat_range_list (S m')) = S m'). { apply nat_range_list_length. } assert (firstn (length (nat_range_list (S m')) + 0) (nat_range_list (S m') ++ l')%list = ((nat_range_list (S m')) ++ firstn 0 l')%list). { apply (@firstn_app_2 nat 0). } rewrite H4 in H5. assert ((nat_range_list (S m') ++ firstn 0 l')%list = nat_range_list (S m')). { assert (firstn 0 l' = []%list). simpl; auto. rewrite H6. apply app_nil_r. } rewrite H6 in H5. assert (firstn (S m' + 0) (nat_range_list (S m') ++ l') = firstn (S m') (nat_range_list (S m') ++ l')). { assert(S m' + 0 = S m'). simpl; auto. rewrite H7. reflexivity. } rewrite H7 in H5. assumption. Qed. Theorem nat_range_list_entry : forall (k n : nat), k < n -> nth k (nat_range_list n) (S n) = k. Proof. intros. generalize dependent k. induction n as [|n']. - intros. contradict H. lia. - intros. set (n := S n'). assert (nat_range_list n = (nat_range_list n' ++ [n'])%list). { simpl; auto. } assert ({k = n'} + {k <> n'}). decide equality. destruct H1. + (* Case: k = n' *) assert (nth k (nat_range_list (S k)) (S (S k)) = last (nat_range_list (S k)) (S (S k))). { apply (@last_nth nat n k). lia. rewrite e. unfold n. symmetry. apply nat_range_list_length. } unfold n. rewrite <- e. rewrite H1. unfold n in H0. rewrite <- e in H0. rewrite H0. apply last_last. + assert (k < n'). lia. assert (length (nat_range_list n') = n'). { apply nat_range_list_length. } apply IHn' in H1 as IH. rewrite H0. assert (nth k (nat_range_list n' ++ [n'])%list (S n') = nth k (nat_range_list n') (S n')). { apply app_nth1 with (d := (S n')). rewrite H2. assumption. } assert (nth k (nat_range_list n' ++ [n']) (S n) = nth k (nat_range_list n' ++ [n']) (S n')). { apply nth_indep. assert (length (nat_range_list n') + 1 = length (nat_range_list n' ++ [n'])). { symmetry. apply app_length. } lia. } rewrite H4. rewrite H3. rewrite IH. reflexivity. Qed. Definition rev_nat_range_list (n : nat) : list nat := List.rev (nat_range_list n). Example ex_rev_nat_range_list_4 : rev_nat_range_list 4 = [3;2;1;0]%list. Proof. simpl; auto. Qed. Theorem rev_nat_range_list_length : forall (n : nat), length (rev_nat_range_list n) = n. Proof. intros. unfold rev_nat_range_list. assert (length (rev (nat_range_list n)) = length (nat_range_list n)). { apply (rev_length (nat_range_list n)). } rewrite H. apply nat_range_list_length. Qed. (* Lemma rev_nth : forall l d n, n < length l -> nth n (rev l) d = nth (length l - S n) l d. nat_range_list_entry : forall k n : nat, k < n -> nth k (nat_range_list n) (S n) = k nth k (rev_nat_range_list n) d = nth (n - k) (nat_range_list n) d = (n - k) *) Theorem rev_nat_range_list_entry : forall (k n : nat), k < n -> nth k (rev_nat_range_list n) (S n) = (n - S k). Proof. intros. unfold rev_nat_range_list. assert (length (nat_range_list n) = n). { apply nat_range_list_length. } assert (nth k (rev (nat_range_list n)) (S n) = nth (length (nat_range_list n) - S k) (nat_range_list n) (S n)). { apply (@rev_nth nat (nat_range_list n) (S n) k). rewrite H0. assumption. } rewrite H0 in H1. assert (nth (n - S k) (nat_range_list n) (S n) = (n - S k)). { apply nat_range_list_entry. lia. } rewrite H1. rewrite H2. reflexivity. Qed. (* Coq thinks [Vector.of_list (rev_nat_range_list n)] is a [Vector] of size [length (rev_nat_range_list n)]. So we have to explicitly spell it out for Coq. *) Require Fin List. Require Import VectorDef PeanoNat Eqdep_dec. Import VectorNotations EqNotations. Fixpoint rev_nat_range_vector (n : nat) : Vector.t nat n := match n with | 0 => [] | S n' => (n') :: (rev_nat_range_vector n') end. Lemma rev_nat_range_vector_last : forall (n' : nat), Vector.last (rev_nat_range_vector (S n')) = 0. Proof. intros. induction n'. - unfold rev_nat_range_vector. simpl; auto. - assert((rev_nat_range_vector (S (S n'))) = Vector.cons nat (S n') (S n') (rev_nat_range_vector (S n'))). { simpl; auto. } rewrite H. assert (Vector.last (Vector.cons nat (S n') (S n') (rev_nat_range_vector (S n'))) = Vector.last (rev_nat_range_vector (S n'))). { simpl; auto. } rewrite H0. apply IHn'. Qed. Example rev_nat_range_vector_0 : rev_nat_range_vector 0 = []. Proof. simpl; auto. Qed. Example rev_nat_range_vector_1 : rev_nat_range_vector 1 = [0]. Proof. simpl; auto. Qed. Example rev_nat_range_vector_2 : rev_nat_range_vector 2 = [1;0]. Proof. simpl; auto. Qed. Lemma rev_nat_range_vector_hd : forall (n' : nat), Vector.hd (rev_nat_range_vector (S n')) = n'. Proof. intros. unfold rev_nat_range_vector. simpl; auto. Qed. Lemma rev_nat_range_vector_tl : forall (n' : nat), Vector.tl (rev_nat_range_vector (S (S n'))) = rev_nat_range_vector (S n'). Proof. intros. unfold rev_nat_range_vector. simpl; auto. Qed. (* These next two lemmas are true, but I am too stupid to understand Coq's inner workings to prove them. *) Lemma rev_nat_range_vector_entry_base_case : forall (k : nat) (H : k < 1), nth_order (rev_nat_range_vector 1) H = 1 - S k. Admitted. Lemma rev_nat_range_vector_entry_inductive_case_subtlety : forall (k n : nat) (H : k < S (S n)) (e : k = S n) (H0 : S n < S (S n)), nth_order (rev_nat_range_vector (S (S n))) H = nth_order (rev_nat_range_vector (S (S n))) H0. Admitted. Theorem rev_nat_range_vector_entry : forall (k n : nat) (H : k < S n), nth_order (rev_nat_range_vector (S n)) H = (S n - S k). Proof. intros. generalize dependent k. induction n. - intros. apply rev_nat_range_vector_entry_base_case. - intros. assert({k = S n} + {k <> S n}). decide equality. destruct H0. + assert (S n < S (S n)) as H0. lia. assert (nth_order (rev_nat_range_vector (S (S n))) H = nth_order (rev_nat_range_vector (S (S n))) H0). { apply rev_nat_range_vector_entry_inductive_case_subtlety. assumption. } rewrite H1. rewrite e. assert (last (rev_nat_range_vector (S (S n))) = 0). { apply rev_nat_range_vector_last. } assert (nth_order (rev_nat_range_vector (S (S n))) H0 = last (rev_nat_range_vector (S (S n)))). { apply (@nth_order_last nat (S n) (rev_nat_range_vector (S (S n)))). } rewrite H3; rewrite H2; lia. + destruct k as [|k']. ++ (* k = 0 *) apply nth_order_hd. ++ (* k = S k' *) set (k := S k'). assert (k' < S n). lia. assert (nth_order (rev_nat_range_vector (S n)) H0 = S n - S k') as IH. { apply (IHn k' H0). } assert (S (S n) - S k = S n - S k'). lia. rewrite H1. rewrite <- IH. symmetry. assert (Vector.tl (rev_nat_range_vector (S (S n))) = rev_nat_range_vector (S n)). { apply rev_nat_range_vector_tl. } rewrite <- H2. apply (@nth_order_tl nat (S n) k' (rev_nat_range_vector (S (S n)))). Qed.
module TestPackage # Write your package code here. function testFunction(number) return 2*number end export testFunction end
#pragma once #include <eosio/chain/webassembly/eos-vm-oc/config.hpp> #include <boost/asio/local/datagram_protocol.hpp> #include <eosio/chain/webassembly/eos-vm-oc/ipc_helpers.hpp> namespace eosio { namespace chain { namespace eosvmoc { wrapped_fd get_connection_to_compile_monitor(int cache_fd); }}}
import data.matrix.basic import data.real.basic import analysis.normed_space.basic variables {n : ℕ} {d : ℕ} /-- This is a fake eigenvalue function on matrices... It likely _will_ be set up this way, and likely return meaningless values for non-self-adjoint matrices-/ -- Maybe not a finset, though? not sure... def eigs (A : matrix (fin d) (fin d) ℝ) : finset ℝ := sorry lemma eigs_smul_ext {x : ℝ} (c : ℝ) (A : matrix (fin d) (fin d) ℝ) (h : x ≠ 0): x ∈ eigs (A) ↔ (c * x) ∈ (eigs (c • A)) := sorry -- lemma eigs_smul (c : ℝ) (A : matrix (fin d) (fin d) ℝ) : eigs (c • A) = c • (eigs (A)) := sorry lemma eigs_zero (d : ℕ) : eigs (0 : matrix (fin d) (fin d) ℝ) = {(0 : ℝ)} := begin ext, have h0 : (0 : matrix (fin d) (fin d) ℝ) = (0 : ℝ) • (0 : matrix (fin d) (fin d) ℝ) := (smul_zero 0).symm, split, intro h1, -- rw h0 at h1, rw finset.mem_singleton, by_contra, have : ∀ b : ℝ, b ∈ eigs 0 := begin intro b, rw eigs_smul_ext (b / a) 0 h at h1, rw smul_zero at h1, field_simp at h1, exact h1, end, sorry, rw finset.mem_singleton, sorry, -- change a ≠ 0 at h, -- rw eigs_smul_ext 0 0 a at h, -- rw h0, -- rw eigs_smul_ext 0 0 a, end def is_psd (U : matrix (fin d) (fin d) ℝ) : Prop := ∀ (x : ℝ), x ∈ eigs U → 0 ≤ x def is_pd (U : matrix (fin d) (fin d) ℝ) : Prop := ∀ x : ℝ, x ∈ eigs U → 0 < x lemma psd_zero (d : ℕ) : is_psd (0 : matrix (fin d) (fin d) ℝ) := begin intros x hx, rw eigs_zero at hx, rw finset.mem_singleton at hx, rw hx, end lemma not_pd_zero (d : ℕ) : ¬ is_pd (0 : matrix (fin d) (fin d) ℝ) := begin change ¬ (∀ x : ℝ, x ∈ eigs 0 → 0 < x), rw not_forall, simp_rw [not_imp, not_lt], use 0, rw eigs_zero, rw finset.mem_singleton, simp only [le_refl, eq_self_iff_true, and_self], end lemma psd_add_of_psd_of_psd {A B : matrix (fin d) (fin d) ℝ} (hA : is_psd A) (hB : is_psd B) : is_psd (A + B) := sorry lemma not_psd_of_neg_pd {A : matrix (fin d) (fin d) ℝ} (hA : is_pd (-A)) : ¬(is_psd A) := sorry lemma psd_of_pd {A : matrix (fin d) (fin d) ℝ} (hA : is_pd A) : is_psd A := sorry lemma pd_of_psd_of_not_neg_psd {A : matrix (fin d) (fin d) ℝ} (hA : is_psd A) (hA' : ¬(is_psd (-A))) : is_pd A := sorry lemma eq_zero_of_psd_of_neg_psd {A : matrix (fin d) (fin d) ℝ} (hA : is_psd A) (hA' : is_psd (-A)) : A = 0 := sorry instance : partial_order (matrix (fin d) (fin d) ℝ) := { le := λ a b, is_psd (b - a), lt := λ a b, is_pd (b - a), le_refl := begin intro a, change is_psd (a - a), rw sub_self, exact psd_zero _, end, le_trans := begin intros a b c hab hbc, change is_psd (c - a), have : c - a = (c - b) + (b - a) := by simp only [sub_add_sub_cancel, sub_left_inj], rw this, exact psd_add_of_psd_of_psd hbc hab, end, lt_iff_le_not_le := begin intros a b, split, intro hab, change is_pd (b - a) at hab, split, exact psd_of_pd hab, change ¬(is_psd (a - b)), exact not_psd_of_neg_pd hab, intro h, have fact₁ := h.1, have fact₂ : ¬ (is_psd (-(b - a))) := h.2, exact pd_of_psd_of_not_neg_psd fact₁ fact₂, end, le_antisymm := begin intros a b hab hba, have : a - b = 0 := eq_zero_of_psd_of_neg_psd hab hba, rw sub_eq_zero at this, exact this, end,}
[GOAL] n : ℕ ⊢ ∀ (a b c : QuaternionGroup n), a * b * c = a * (b * c) [PROOFSTEP] rintro (i | i) (j | j) (k | k) [GOAL] case a.a.a n : ℕ i j k : ZMod (2 * n) ⊢ a i * a j * a k = a i * (a j * a k) [PROOFSTEP] simp only [(· * ·), mul] [GOAL] case a.a.xa n : ℕ i j k : ZMod (2 * n) ⊢ a i * a j * xa k = a i * (a j * xa k) [PROOFSTEP] simp only [(· * ·), mul] [GOAL] case a.xa.a n : ℕ i j k : ZMod (2 * n) ⊢ a i * xa j * a k = a i * (xa j * a k) [PROOFSTEP] simp only [(· * ·), mul] [GOAL] case a.xa.xa n : ℕ i j k : ZMod (2 * n) ⊢ a i * xa j * xa k = a i * (xa j * xa k) [PROOFSTEP] simp only [(· * ·), mul] [GOAL] case xa.a.a n : ℕ i j k : ZMod (2 * n) ⊢ xa i * a j * a k = xa i * (a j * a k) [PROOFSTEP] simp only [(· * ·), mul] [GOAL] case xa.a.xa n : ℕ i j k : ZMod (2 * n) ⊢ xa i * a j * xa k = xa i * (a j * xa k) [PROOFSTEP] simp only [(· * ·), mul] [GOAL] case xa.xa.a n : ℕ i j k : ZMod (2 * n) ⊢ xa i * xa j * a k = xa i * (xa j * a k) [PROOFSTEP] simp only [(· * ·), mul] [GOAL] case xa.xa.xa n : ℕ i j k : ZMod (2 * n) ⊢ xa i * xa j * xa k = xa i * (xa j * xa k) [PROOFSTEP] simp only [(· * ·), mul] [GOAL] case a.a.a n : ℕ i j k : ZMod (2 * n) ⊢ a (i + j + k) = a (i + (j + k)) [PROOFSTEP] ring_nf [GOAL] case a.a.xa n : ℕ i j k : ZMod (2 * n) ⊢ xa (k - (i + j)) = xa (k - j - i) [PROOFSTEP] ring_nf [GOAL] case a.xa.a n : ℕ i j k : ZMod (2 * n) ⊢ xa (j - i + k) = xa (j + k - i) [PROOFSTEP] ring_nf [GOAL] case a.xa.xa n : ℕ i j k : ZMod (2 * n) ⊢ a (↑n + k - (j - i)) = a (i + (↑n + k - j)) [PROOFSTEP] ring_nf [GOAL] case xa.a.a n : ℕ i j k : ZMod (2 * n) ⊢ xa (i + j + k) = xa (i + (j + k)) [PROOFSTEP] ring_nf [GOAL] case xa.a.xa n : ℕ i j k : ZMod (2 * n) ⊢ a (↑n + k - (i + j)) = a (↑n + (k - j) - i) [PROOFSTEP] ring_nf [GOAL] case xa.xa.a n : ℕ i j k : ZMod (2 * n) ⊢ a (↑n + j - i + k) = a (↑n + (j + k) - i) [PROOFSTEP] ring_nf [GOAL] case xa.xa.xa n : ℕ i j k : ZMod (2 * n) ⊢ xa (k - (↑n + j - i)) = xa (i + (↑n + k - j)) [PROOFSTEP] ring_nf [GOAL] case xa.xa.xa n : ℕ i j k : ZMod (2 * n) ⊢ xa (k + (-↑n - j) + i) = xa (k + (↑n - j) + i) [PROOFSTEP] congr [GOAL] case xa.xa.xa.e_a.e_a.e_a.e_a n : ℕ i j k : ZMod (2 * n) ⊢ -↑n = ↑n [PROOFSTEP] calc -(n : ZMod (2 * n)) = 0 - n := by rw [zero_sub] _ = 2 * n - n := by norm_cast; simp _ = n := by ring [GOAL] n : ℕ i j k : ZMod (2 * n) ⊢ -↑n = 0 - ↑n [PROOFSTEP] rw [zero_sub] [GOAL] n : ℕ i j k : ZMod (2 * n) ⊢ 0 - ↑n = 2 * ↑n - ↑n [PROOFSTEP] norm_cast [GOAL] n : ℕ i j k : ZMod (2 * n) ⊢ ↑(Int.subNatNat 0 n) = ↑(Int.subNatNat (2 * n) n) [PROOFSTEP] simp [GOAL] n : ℕ i j k : ZMod (2 * n) ⊢ 2 * ↑n - ↑n = ↑n [PROOFSTEP] ring [GOAL] n : ℕ ⊢ ∀ (a : QuaternionGroup n), 1 * a = a [PROOFSTEP] rintro (i | i) [GOAL] case a n : ℕ i : ZMod (2 * n) ⊢ 1 * a i = a i [PROOFSTEP] exact congr_arg a (zero_add i) [GOAL] case xa n : ℕ i : ZMod (2 * n) ⊢ 1 * xa i = xa i [PROOFSTEP] exact congr_arg xa (sub_zero i) [GOAL] n : ℕ ⊢ ∀ (a : QuaternionGroup n), a * 1 = a [PROOFSTEP] rintro (i | i) [GOAL] case a n : ℕ i : ZMod (2 * n) ⊢ a i * 1 = a i [PROOFSTEP] exact congr_arg a (add_zero i) [GOAL] case xa n : ℕ i : ZMod (2 * n) ⊢ xa i * 1 = xa i [PROOFSTEP] exact congr_arg xa (add_zero i) [GOAL] n : ℕ ⊢ ∀ (a : QuaternionGroup n), a⁻¹ * a = 1 [PROOFSTEP] rintro (i | i) [GOAL] case a n : ℕ i : ZMod (2 * n) ⊢ (a i)⁻¹ * a i = 1 [PROOFSTEP] exact congr_arg a (neg_add_self i) [GOAL] case xa n : ℕ i : ZMod (2 * n) ⊢ (xa i)⁻¹ * xa i = 1 [PROOFSTEP] exact congr_arg a (sub_self (n + i)) [GOAL] n : ℕ ⊢ Function.LeftInverse (fun i => match i with | a j => Sum.inl j | xa j => Sum.inr j) fun i => match i with | Sum.inl j => a j | Sum.inr j => xa j [PROOFSTEP] rintro (x | x) [GOAL] case inl n : ℕ x : ZMod (2 * n) ⊢ (fun i => match i with | a j => Sum.inl j | xa j => Sum.inr j) ((fun i => match i with | Sum.inl j => a j | Sum.inr j => xa j) (Sum.inl x)) = Sum.inl x [PROOFSTEP] rfl [GOAL] case inr n : ℕ x : ZMod (2 * n) ⊢ (fun i => match i with | a j => Sum.inl j | xa j => Sum.inr j) ((fun i => match i with | Sum.inl j => a j | Sum.inr j => xa j) (Sum.inr x)) = Sum.inr x [PROOFSTEP] rfl [GOAL] n : ℕ ⊢ Function.RightInverse (fun i => match i with | a j => Sum.inl j | xa j => Sum.inr j) fun i => match i with | Sum.inl j => a j | Sum.inr j => xa j [PROOFSTEP] rintro (x | x) [GOAL] case a n : ℕ x : ZMod (2 * n) ⊢ (fun i => match i with | Sum.inl j => a j | Sum.inr j => xa j) ((fun i => match i with | a j => Sum.inl j | xa j => Sum.inr j) (a x)) = a x [PROOFSTEP] rfl [GOAL] case xa n : ℕ x : ZMod (2 * n) ⊢ (fun i => match i with | Sum.inl j => a j | Sum.inr j => xa j) ((fun i => match i with | a j => Sum.inl j | xa j => Sum.inr j) (xa x)) = xa x [PROOFSTEP] rfl [GOAL] n : ℕ ⊢ Function.LeftInverse (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j [PROOFSTEP] rintro (k | k) [GOAL] case a n : ℕ k : ZMod (2 * 0) ⊢ (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) (a k)) = a k [PROOFSTEP] rfl [GOAL] case xa n : ℕ k : ZMod (2 * 0) ⊢ (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) (xa k)) = xa k [PROOFSTEP] rfl [GOAL] n : ℕ ⊢ Function.RightInverse (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j [PROOFSTEP] rintro (k | k) [GOAL] case r n : ℕ k : ZMod 0 ⊢ (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) (DihedralGroup.r k)) = DihedralGroup.r k [PROOFSTEP] rfl [GOAL] case sr n : ℕ k : ZMod 0 ⊢ (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) (DihedralGroup.sr k)) = DihedralGroup.sr k [PROOFSTEP] rfl [GOAL] n : ℕ ⊢ ∀ (x y : QuaternionGroup 0), Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } (x * y) = Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } x * Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } y [PROOFSTEP] rintro (k | k) (l | l) [GOAL] case a.a n : ℕ k l : ZMod (2 * 0) ⊢ Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } (a k * a l) = Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } (a k) * Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } (a l) [PROOFSTEP] simp [GOAL] case a.xa n : ℕ k l : ZMod (2 * 0) ⊢ Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } (a k * xa l) = Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } (a k) * Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } (xa l) [PROOFSTEP] simp [GOAL] case xa.a n : ℕ k l : ZMod (2 * 0) ⊢ Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } (xa k * a l) = Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } (xa k) * Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } (a l) [PROOFSTEP] simp [GOAL] case xa.xa n : ℕ k l : ZMod (2 * 0) ⊢ Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } (xa k * xa l) = Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } (xa k) * Equiv.toFun { toFun := fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j, invFun := fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j, left_inv := (_ : ∀ (x : QuaternionGroup 0), (fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) ((fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) x) = x), right_inv := (_ : ∀ (x : DihedralGroup 0), (fun i => match i with | a j => DihedralGroup.r j | xa j => DihedralGroup.sr j) ((fun i => match i with | DihedralGroup.r j => a j | DihedralGroup.sr j => xa j) x) = x) } (xa l) [PROOFSTEP] simp [GOAL] n : ℕ ⊢ a 0 ≠ xa 0 [PROOFSTEP] revert n [GOAL] ⊢ ∀ {n : ℕ}, a 0 ≠ xa 0 [PROOFSTEP] simp [GOAL] n : ℕ inst✝ : NeZero n ⊢ Fintype.card (QuaternionGroup n) = 4 * n [PROOFSTEP] rw [← Fintype.card_eq.mpr ⟨fintypeHelper⟩, Fintype.card_sum, ZMod.card, two_mul] [GOAL] n : ℕ inst✝ : NeZero n ⊢ n + n + (n + n) = 4 * n [PROOFSTEP] ring [GOAL] n k : ℕ ⊢ a 1 ^ k = a ↑k [PROOFSTEP] induction' k with k IH [GOAL] case zero n : ℕ ⊢ a 1 ^ Nat.zero = a ↑Nat.zero [PROOFSTEP] rw [Nat.cast_zero] [GOAL] case zero n : ℕ ⊢ a 1 ^ Nat.zero = a 0 [PROOFSTEP] rfl [GOAL] case succ n k : ℕ IH : a 1 ^ k = a ↑k ⊢ a 1 ^ Nat.succ k = a ↑(Nat.succ k) [PROOFSTEP] rw [pow_succ, IH, a_mul_a] [GOAL] case succ n k : ℕ IH : a 1 ^ k = a ↑k ⊢ a (1 + ↑k) = a ↑(Nat.succ k) [PROOFSTEP] congr 1 [GOAL] case succ.e_a n k : ℕ IH : a 1 ^ k = a ↑k ⊢ 1 + ↑k = ↑(Nat.succ k) [PROOFSTEP] norm_cast [GOAL] case succ.e_a n k : ℕ IH : a 1 ^ k = a ↑k ⊢ ↑(1 + k) = ↑(Nat.succ k) [PROOFSTEP] rw [Nat.one_add] [GOAL] n : ℕ ⊢ a 1 ^ (2 * n) = 1 [PROOFSTEP] rw [a_one_pow, one_def] [GOAL] n : ℕ ⊢ a ↑(2 * n) = a 0 [PROOFSTEP] congr 1 [GOAL] case e_a n : ℕ ⊢ ↑(2 * n) = 0 [PROOFSTEP] exact ZMod.nat_cast_self _ [GOAL] n : ℕ i : ZMod (2 * n) ⊢ xa i ^ 2 = a ↑n [PROOFSTEP] simp [sq] [GOAL] n : ℕ i : ZMod (2 * n) ⊢ xa i ^ 4 = 1 [PROOFSTEP] rw [pow_succ, pow_succ, sq, xa_mul_xa, xa_mul_a, xa_mul_xa, add_sub_cancel, add_sub_assoc, add_sub_cancel'] [GOAL] n : ℕ i : ZMod (2 * n) ⊢ a (↑n + ↑n) = 1 [PROOFSTEP] norm_cast [GOAL] n : ℕ i : ZMod (2 * n) ⊢ a ↑(n + n) = 1 [PROOFSTEP] rw [← two_mul] [GOAL] n : ℕ i : ZMod (2 * n) ⊢ a ↑(2 * n) = 1 [PROOFSTEP] simp [one_def] [GOAL] n : ℕ inst✝ : NeZero n i : ZMod (2 * n) ⊢ orderOf (xa i) = 4 [PROOFSTEP] change _ = 2 ^ 2 [GOAL] n : ℕ inst✝ : NeZero n i : ZMod (2 * n) ⊢ orderOf (xa i) = 2 ^ 2 [PROOFSTEP] haveI : Fact (Nat.Prime 2) := Fact.mk Nat.prime_two [GOAL] n : ℕ inst✝ : NeZero n i : ZMod (2 * n) this : Fact (Nat.Prime 2) ⊢ orderOf (xa i) = 2 ^ 2 [PROOFSTEP] apply orderOf_eq_prime_pow [GOAL] case hnot n : ℕ inst✝ : NeZero n i : ZMod (2 * n) this : Fact (Nat.Prime 2) ⊢ ¬xa i ^ 2 ^ 1 = 1 [PROOFSTEP] intro h [GOAL] case hnot n : ℕ inst✝ : NeZero n i : ZMod (2 * n) this : Fact (Nat.Prime 2) h : xa i ^ 2 ^ 1 = 1 ⊢ False [PROOFSTEP] simp only [pow_one, xa_sq] at h [GOAL] case hnot n : ℕ inst✝ : NeZero n i : ZMod (2 * n) this : Fact (Nat.Prime 2) h : a ↑n = 1 ⊢ False [PROOFSTEP] injection h with h' [GOAL] case hnot n : ℕ inst✝ : NeZero n i : ZMod (2 * n) this : Fact (Nat.Prime 2) h' : ↑n = 0 ⊢ False [PROOFSTEP] apply_fun ZMod.val at h' [GOAL] case hnot n : ℕ inst✝ : NeZero n i : ZMod (2 * n) this : Fact (Nat.Prime 2) h' : ZMod.val ↑n = ZMod.val 0 ⊢ False [PROOFSTEP] apply_fun (· / n) at h' [GOAL] case hnot n : ℕ inst✝ : NeZero n i : ZMod (2 * n) this : Fact (Nat.Prime 2) h' : ZMod.val ↑n / n = ZMod.val 0 / n ⊢ False [PROOFSTEP] simp only [ZMod.val_nat_cast, ZMod.val_zero, Nat.zero_div, Nat.mod_mul_left_div_self, Nat.div_self (NeZero.pos n)] at h' [GOAL] case hfin n : ℕ inst✝ : NeZero n i : ZMod (2 * n) this : Fact (Nat.Prime 2) ⊢ xa i ^ 2 ^ (1 + 1) = 1 [PROOFSTEP] norm_num [GOAL] n : ℕ ⊢ IsCyclic (QuaternionGroup 1) [PROOFSTEP] apply isCyclic_of_orderOf_eq_card [GOAL] case hx n : ℕ ⊢ orderOf ?x = Fintype.card (QuaternionGroup 1) case x n : ℕ ⊢ QuaternionGroup 1 [PROOFSTEP] rw [card, mul_one] [GOAL] case hx n : ℕ ⊢ orderOf ?x = 4 case x n : ℕ ⊢ QuaternionGroup 1 case x n : ℕ ⊢ QuaternionGroup 1 case x n : ℕ ⊢ QuaternionGroup 1 [PROOFSTEP] exact orderOf_xa 0 [GOAL] n : ℕ ⊢ orderOf (a 1) = 2 * n [PROOFSTEP] cases' eq_zero_or_neZero n with hn hn [GOAL] case inl n : ℕ hn : n = 0 ⊢ orderOf (a 1) = 2 * n [PROOFSTEP] subst hn [GOAL] case inl ⊢ orderOf (a 1) = 2 * 0 [PROOFSTEP] simp_rw [mul_zero, orderOf_eq_zero_iff'] [GOAL] case inl ⊢ ∀ (n : ℕ), 0 < n → QuaternionGroup.a 1 ^ n ≠ 1 [PROOFSTEP] intro n h [GOAL] case inl n : ℕ h : 0 < n ⊢ a 1 ^ n ≠ 1 [PROOFSTEP] rw [one_def, a_one_pow] [GOAL] case inl n : ℕ h : 0 < n ⊢ a ↑n ≠ a 0 [PROOFSTEP] apply mt a.inj [GOAL] case inl n : ℕ h : 0 < n ⊢ ¬↑n = 0 [PROOFSTEP] haveI : CharZero (ZMod (2 * 0)) := ZMod.charZero [GOAL] case inl n : ℕ h : 0 < n this : CharZero (ZMod (2 * 0)) ⊢ ¬↑n = 0 [PROOFSTEP] simpa using h.ne' [GOAL] case inr n : ℕ hn : NeZero n ⊢ orderOf (a 1) = 2 * n [PROOFSTEP] apply (Nat.le_of_dvd (NeZero.pos _) (orderOf_dvd_of_pow_eq_one (@a_one_pow_n n))).lt_or_eq.resolve_left [GOAL] case inr n : ℕ hn : NeZero n ⊢ ¬orderOf (a 1) < 2 * n [PROOFSTEP] intro h [GOAL] case inr n : ℕ hn : NeZero n h : orderOf (a 1) < 2 * n ⊢ False [PROOFSTEP] have h1 : (a 1 : QuaternionGroup n) ^ orderOf (a 1) = 1 := pow_orderOf_eq_one _ [GOAL] case inr n : ℕ hn : NeZero n h : orderOf (a 1) < 2 * n h1 : a 1 ^ orderOf (a 1) = 1 ⊢ False [PROOFSTEP] rw [a_one_pow] at h1 [GOAL] case inr n : ℕ hn : NeZero n h : orderOf (a 1) < 2 * n h1 : a ↑(orderOf (a 1)) = 1 ⊢ False [PROOFSTEP] injection h1 with h2 [GOAL] case inr n : ℕ hn : NeZero n h : orderOf (a 1) < 2 * n h2 : ↑(orderOf (a 1)) = 0 ⊢ False [PROOFSTEP] rw [← ZMod.val_eq_zero, ZMod.val_nat_cast, Nat.mod_eq_of_lt h] at h2 [GOAL] case inr n : ℕ hn : NeZero n h : orderOf (a 1) < 2 * n h2 : orderOf (a 1) = 0 ⊢ False [PROOFSTEP] exact absurd h2.symm (orderOf_pos _).ne [GOAL] n : ℕ inst✝ : NeZero n i : ZMod (2 * n) ⊢ orderOf (a i) = 2 * n / Nat.gcd (2 * n) (ZMod.val i) [PROOFSTEP] conv_lhs => rw [← ZMod.nat_cast_zmod_val i] [GOAL] n : ℕ inst✝ : NeZero n i : ZMod (2 * n) | orderOf (a i) [PROOFSTEP] rw [← ZMod.nat_cast_zmod_val i] [GOAL] n : ℕ inst✝ : NeZero n i : ZMod (2 * n) | orderOf (a i) [PROOFSTEP] rw [← ZMod.nat_cast_zmod_val i] [GOAL] n : ℕ inst✝ : NeZero n i : ZMod (2 * n) | orderOf (a i) [PROOFSTEP] rw [← ZMod.nat_cast_zmod_val i] [GOAL] n : ℕ inst✝ : NeZero n i : ZMod (2 * n) ⊢ orderOf (a ↑(ZMod.val i)) = 2 * n / Nat.gcd (2 * n) (ZMod.val i) [PROOFSTEP] rw [← a_one_pow, orderOf_pow, orderOf_a_one] [GOAL] n : ℕ ⊢ Monoid.exponent (QuaternionGroup n) = 2 * lcm n 2 [PROOFSTEP] rw [← normalize_eq 2, ← lcm_mul_left, normalize_eq] [GOAL] n : ℕ ⊢ Monoid.exponent (QuaternionGroup n) = lcm (2 * n) (2 * 2) [PROOFSTEP] norm_num [GOAL] n : ℕ ⊢ Monoid.exponent (QuaternionGroup n) = lcm (2 * n) 4 [PROOFSTEP] cases' eq_zero_or_neZero n with hn hn [GOAL] case inl n : ℕ hn : n = 0 ⊢ Monoid.exponent (QuaternionGroup n) = lcm (2 * n) 4 [PROOFSTEP] subst hn [GOAL] case inl ⊢ Monoid.exponent (QuaternionGroup 0) = lcm (2 * 0) 4 [PROOFSTEP] simp only [lcm_zero_left, mul_zero] [GOAL] case inl ⊢ Monoid.exponent (QuaternionGroup 0) = 0 [PROOFSTEP] exact Monoid.exponent_eq_zero_of_order_zero orderOf_a_one [GOAL] case inr n : ℕ hn : NeZero n ⊢ Monoid.exponent (QuaternionGroup n) = lcm (2 * n) 4 [PROOFSTEP] apply Nat.dvd_antisymm [GOAL] case inr.a n : ℕ hn : NeZero n ⊢ Monoid.exponent (QuaternionGroup n) ∣ lcm (2 * n) 4 [PROOFSTEP] apply Monoid.exponent_dvd_of_forall_pow_eq_one [GOAL] case inr.a.hG n : ℕ hn : NeZero n ⊢ ∀ (g : QuaternionGroup n), g ^ lcm (2 * n) 4 = 1 [PROOFSTEP] rintro (m | m) [GOAL] case inr.a.hG.a n : ℕ hn : NeZero n m : ZMod (2 * n) ⊢ a m ^ lcm (2 * n) 4 = 1 [PROOFSTEP] rw [← orderOf_dvd_iff_pow_eq_one, orderOf_a] [GOAL] case inr.a.hG.a n : ℕ hn : NeZero n m : ZMod (2 * n) ⊢ 2 * n / Nat.gcd (2 * n) (ZMod.val m) ∣ lcm (2 * n) 4 [PROOFSTEP] refine' Nat.dvd_trans ⟨gcd (2 * n) m.val, _⟩ (dvd_lcm_left (2 * n) 4) [GOAL] case inr.a.hG.a n : ℕ hn : NeZero n m : ZMod (2 * n) ⊢ 2 * n = 2 * n / Nat.gcd (2 * n) (ZMod.val m) * gcd (2 * n) (ZMod.val m) [PROOFSTEP] exact (Nat.div_mul_cancel (Nat.gcd_dvd_left (2 * n) m.val)).symm [GOAL] case inr.a.hG.xa n : ℕ hn : NeZero n m : ZMod (2 * n) ⊢ xa m ^ lcm (2 * n) 4 = 1 [PROOFSTEP] rw [← orderOf_dvd_iff_pow_eq_one, orderOf_xa] [GOAL] case inr.a.hG.xa n : ℕ hn : NeZero n m : ZMod (2 * n) ⊢ 4 ∣ lcm (2 * n) 4 [PROOFSTEP] exact dvd_lcm_right (2 * n) 4 [GOAL] case inr.a n : ℕ hn : NeZero n ⊢ lcm (2 * n) 4 ∣ Monoid.exponent (QuaternionGroup n) [PROOFSTEP] apply lcm_dvd [GOAL] case inr.a.hab n : ℕ hn : NeZero n ⊢ 2 * n ∣ Monoid.exponent (QuaternionGroup n) [PROOFSTEP] convert Monoid.order_dvd_exponent (a 1) [GOAL] case h.e'_3 n : ℕ hn : NeZero n ⊢ 2 * n = orderOf (a 1) [PROOFSTEP] exact orderOf_a_one.symm [GOAL] case inr.a.hcb n : ℕ hn : NeZero n ⊢ 4 ∣ Monoid.exponent (QuaternionGroup n) [PROOFSTEP] convert Monoid.order_dvd_exponent (xa (0 : ZMod (2 * n))) [GOAL] case h.e'_3 n : ℕ hn : NeZero n ⊢ 4 = orderOf (xa 0) [PROOFSTEP] exact (orderOf_xa 0).symm
# -*- coding: utf-8 -*- ''' This is the Task Management Tool (TMT) ''' def write_task_summary(task_dir, task_type = 'VASP', band_gap_label = True, plot_fatband = False, band_struct_ylim = None, num_added_bands = 3): ''' write task summary band_struct_ylim: A list of length two. The limit of the y axis (i.e. the energy range around the Fermi level). This is used to check the band structure near the Fermi level. If the value is None, then the program will determine the ylim automatically. num_added_bands: This is used to automatically determine the added bands around the Fermi level. ''' args_dict = locals() import time import os import numpy as np from .. import funcs from .. import convert from .. import default_params from ..vasp import vasp_plot from ..vasp import vasp_read from ..vasp import vasp_tools from ..vasp import vasp_analyze import time import random defaults_dict = default_params.default_params() logfile = defaults_dict['logfile'] output_dir = os.path.join(os.getcwd(), defaults_dict['output_dir_name']) projects_summary_dir = os.path.join(output_dir, defaults_dict['projects_summary_dir_name']) task_summary_dir = os.path.join(output_dir, defaults_dict['task_summary_dir_name']) funcs.mkdir(output_dir) #funcs.mkdir(projects_summary_dir) funcs.mkdir(task_summary_dir) default_palette_list = ['black','red','cyan','darkviolet','magenta','gray','darkorange','darkcyan','palegreen', 'goldenrod','lightpink','tan','mediumpurple','steelblue','tomato','mediumturquoise', 'mediumslateblue','brown','darkseagreen','wheat','seagreen','maroon','deeppink','chocolate', 'bisque','plum'] task_dir = os.path.abspath(task_dir) task_dir_name = os.path.split(task_dir)[-1] #project_dir_name = os.path.split(os.path.abspath(os.path.join(task_dir, '../')))[-1] #project_summary_dir = os.path.join(projects_summary_dir, 'summary_' + project_dir_name) task_summary_dir = os.path.join(task_summary_dir, 'summary_' + task_dir_name) task_summary_fig_dir = os.path.join(task_summary_dir, 'figs') #task_summary_dir = os.path.join(project_summary_dir, task_dir_name) #funcs.mkdir(project_summary_dir) funcs.mkdir(task_summary_dir) funcs.mkdir(task_summary_fig_dir) font_size = 24 opt_dir = os.path.join(task_dir, 'opt/') scf_dir = os.path.join(task_dir, 'scf/') dos_dir = os.path.join(task_dir, 'dos/') bs_dir = os.path.join(task_dir, 'bs/') bs_soc_dir = os.path.join(task_dir, 'bs_soc/') task_summary_ctext_file_path = os.path.join(task_summary_dir, task_dir_name + '.tex') task_summary_ctex_str = '' current_time = time.time() formatted_time = time.strftime('## %Y%m%d %H:%M:%S',time.localtime(current_time)) ################# #Write header ################# task_summary_ctex_str = task_summary_ctex_str + (r'\documentclass[a4paper,12]{ctexart}' + '\n' + r'\usepackage{amsmath,bm}' + '\n' + r'\usepackage[hidelinks]{hyperref}' + '\n' + r'\usepackage{longtable}' + '\n' + r'\usepackage{graphicx}' + '\n' + r'\usepackage{tikz}' + '\n' + r'\usepackage{lscape}' + '\n' + r'\usepackage{listings}' + '\n') task_summary_ctex_str = task_summary_ctex_str + ( r'\usepackage[ ' + '\n' + r' a4paper, ' + '\n' + r' left=3.17cm,right=3.17cm,top=4cm,bottom=3cm]{geometry} ' + '\n' + r'\usepackage{fancyhdr} ' + '\n' + r' ' + '\n' + r'\renewcommand{\headrulewidth}{0.6pt}% ' + '\n' + r'\pagestyle{fancy} ' + '\n' + r'\lhead{} ' + '\n' + r'\chead{} ' + '\n' + r'\rhead{} ' + '\n' + r'\lfoot{} ' + '\n' + r'\cfoot{} ' + '\n' + r'\rfoot{} ' + '\n' + r'\fancyhead[CE,CO]{\zihao{-5}\nouppercase{\leftmark}} ' + '\n' + r'\fancyfoot[CE,CO]{\zihao{-5}\thepage} ' + '\n') task_summary_ctex_str = task_summary_ctex_str + r'\graphicspath{{' + r'./' + defaults_dict['output_dir_name'] + r'/}{' + r'../../' + r'}{./}{./' + os.path.split(task_summary_fig_dir)[-1] + r'/}}' + '\n' task_summary_ctex_str = task_summary_ctex_str + r'\renewcommand{\figurename}{Figure}' + '\n' task_summary_ctex_str = task_summary_ctex_str + r'\renewcommand{\tablename}{Table}' + '\n' task_summary_ctex_str = task_summary_ctex_str + r'\renewcommand{\contentsname}{Table of Contents}' + '\n' task_summary_ctex_str = task_summary_ctex_str +( r'\definecolor{light-gray}{gray}{0.99} ' + '\n' + r'\definecolor{lbcolor}{rgb}{0.99,0.99,0.99} ' + '\n' + r'\lstset{% ' + '\n' + r'frame=shadowbox, ' + '\n' + r'language=python, ' + '\n' + r'basicstyle=\footnotesize, %\scriptsize ' + '\n' + r'numbers=left, ' + '\n' + r'rulecolor=, ' + '\n' + r'upquote=true, ' + '\n' + r'aboveskip={1.5\baselineskip}, ' + '\n' + r'numberstyle=\footnotesize, ' + '\n' + r'stepnumber=1, ' + '\n' + r'numbersep=5pt, ' + '\n' + r'backgroundcolor=\color{lbcolor}, %\color{white}, ' + '\n' + r'showspaces=false, ' + '\n' + r'showstringspaces=false, ' + '\n' + r'showtabs=false, ' + '\n' + r'identifierstyle=\ttfamily, ' + '\n' + r'keywordstyle=\color[rgb]{0,0,1}, ' + '\n' + r'%commentstyle=\color[rgb]{0.133,0.545,0.133} ' + '\n' + r'%stringstyle=\color[rgb]{0.627,0.126,0.941} ' + '\n' + r'%frame=single, ' + '\n' + r'tabsize=2, ' + '\n' + r'captionpos=b, ' + '\n' + r'prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}, ' + '\n' + r'breaklines=true, ' + '\n' + r'extendedchars=true, ' + '\n' + r'columns=fixed, ' + '\n' + r'breakatwhitespace=false, ' + '\n' + r'xleftmargin=2em, ' + '\n' + r'xrightmargin=2em, ' + '\n' + r'aboveskip=1em ' + '\n' + r'} ' + '\n') task_summary_ctex_str = task_summary_ctex_str + r'\newcommand{\ucite}[1]{\textsuperscript{\cite{#1}}}' + '\n' task_summary_ctex_str = task_summary_ctex_str + ( r'\newcommand{\wideunderline}[2][2em]{% ' + '\n' + r' \underline{\makebox[\ifdim\width>#1\width\else#1\fi]{#2}}% ' + '\n' + r'} ' + '\n') task_summary_ctex_str = task_summary_ctex_str + '\n' task_summary_ctex_str = task_summary_ctex_str + (r'\begin{document}' + '\n') task_summary_ctex_str = task_summary_ctex_str + ( r'\zihao{4} ' + '\n' + r'\begin{titlepage} ' + '\n' + r'\begin{center} ' + '\n' + r' ' + '\n' + r'%\begin{figure} ' + '\n' + r'%\centering ' + '\n' + r'%\includegraphics[width=0.2\linewidth]{logo.png} ' + '\n' + r'%\end{figure} ' + '\n' + r'%\LARGE \textbf{MATSDP} ' + '\n' + r' ' + '\n' + r'\vspace*{2cm} ' + '\n' + r' ' + '\n' + r'\Huge\textbf{Task Summary} ' + '\n' + r' ' + '\n' + r' ' + '\n' + r'\vspace{3.5cm} ' + '\n' + r' ' + '\n' + r'\begin{table}[h] ' + '\n' + r'\Large ' + '\n' + r'\centering ' + '\n' + r'\begin{tabular}{rc} ' + '\n' + r'Generated with: &\wideunderline[10em]{MATSDP}\\[1cm] ' + '\n' + #r'Project: &\wideunderline[10em]{' + project_dir_name.replace("_", "\_") + r'}\\[1cm]' + '\n' + r'Task: &\wideunderline[10em]{' + task_dir_name.replace("_", "\_") + r'}\\[1cm]' + '\n' + r'Time: &\wideunderline[10em]{' + formatted_time.strip('#') + r'}\\[1cm] ' + '\n' + r'\end{tabular} ' + '\n' + r'\end{table} ' + '\n' + r' ' + '\n' + r'%\Large xxxx年x月 ' + '\n' + r' ' + '\n' + r'\end{center} ' + '\n' + r'\end{titlepage} ' + '\n' + r' ' + '\n' + r'\newcommand\frontmatter{% ' + '\n' + r' \cleardoublepage ' + '\n' + r' \thispagestyle{empty} ' + '\n' + r' \pagenumbering{roman}} ' + '\n' + r' ' + '\n' + r'\frontmatter ' + '\n' + r' ' + '\n' + r'\tableofcontents ' + '\n' + r'\newpage ' + '\n') task_summary_ctex_str = task_summary_ctex_str + ( r'\pagenumbering{arabic} ' + '\n' + r'\setcounter{page}{1} ' + '\n') # materials structure and input symmetry #path_recorder_list = [] path1, name1 = os.path.split(task_dir) path_recorder_list = [path1] path_level_list = [None] * 99 temp_indx = 0 ## for root, dirs, files in os.walk(task_dir): ## dirs.sort() ## temp_indx = temp_indx + 1 ## level = root.replace(task_dir, '').count(os.sep) ## path_level_list[level] = os.path.basename(root) ## if level >= 1: ## path_recorder_list = path_level_list[:level] ## ##print('****',path_recorder_list) ## path_recorder_list.append(os.path.basename(root)) ## i_dir_path = os.path.join(path1, '/'.join(path_recorder_list)) fig_format = 'pdf' for root, dirs, files in os.walk(task_dir): dirs.sort() temp_indx = temp_indx + 1 level = root.replace(task_dir, '').count(os.sep) path_level_list[level] = os.path.basename(root) if level >= 1: path_recorder_list = [path1] + path_level_list[:level] path_recorder_list.append(os.path.basename(root)) path_recorder_list_temp = path_recorder_list.copy() path_recorder_list_temp.pop(0) i_dir_path = os.path.join('', *path_recorder_list) i_task_str = '/'.join(path_recorder_list_temp) ##print(level, '/'.join(path_recorder_list)) ##print('i_dir_path=', i_dir_path) i_dir_name = os.path.basename(root).strip('\\').strip('#') i_task_tex_str = i_task_str.replace("_", "\_") i_task_tex_str_wrapped = '' wrap_length = 40 for i_char_indx in range(0, len(i_task_tex_str)): i_char = i_task_tex_str[i_char_indx] if i_char_indx % wrap_length == 0 and i_char_indx != 0: i_task_tex_str_wrapped = i_task_tex_str_wrapped + i_char + '\\\\' else: i_task_tex_str_wrapped = i_task_tex_str_wrapped + i_char if check_job_type(i_dir_path) != 'VASP': task_summary_ctex_str = task_summary_ctex_str + (r'\section{' + i_task_tex_str_wrapped + '}' + '\n') task_summary_ctex_str = task_summary_ctex_str + ('This is not a valid VASP job (one or more of the following files are missing: INCAR, POSCAR, KPOINTS, POTCAR).' + '\n') continue task_summary_ctex_str = task_summary_ctex_str + (r'\section{' + i_task_tex_str + '}' + '\n') ################################# #Basic properties ################################# task_summary_ctex_str = task_summary_ctex_str + (r'\subsection{Job Summary}' + '\n') outcar_file_path = os.path.join(i_dir_path, 'OUTCAR') kpoints_file_path = os.path.join(i_dir_path, 'KPOINTS') eigenval_file_path = os.path.join(i_dir_path, 'EIGENVAL') poscar_file_path = os.path.join(i_dir_path, 'POSCAR') contcar_file_path = os.path.join(i_dir_path, 'CONTCAR') job_finished = vasp_tools.vasp_job_finished(outcar_file_path, suppress_warning = True) if job_finished == False: job_status = 'Unfinished' #task_summary_ctex_str = task_summary_ctex_str + ('Job Status = ' + str(job_finished) + '\n') table_label = 'tab:' + i_dir_name + str(temp_indx) task_summary_ctex_str = task_summary_ctex_str + (r'The job summary is shown in Table \ref{' + table_label + '}.' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\begin{table}[!h]' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\centering' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\caption{\label{' + table_label + '}Job summary}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\begin{tabular}{ll}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\hline' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'Parameters & Value' + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + (r'\hline' + '\n') task_summary_ctex_str = task_summary_ctex_str + ('Job Status & ' + str(job_status) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + (r'\hline' + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + (r'\end{tabular}' + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + (r'\end{table}' + '\\\\\n') elif job_finished == True: job_status = 'Finished' outcar_params_dict = vasp_read.read_outcar(outcar_file_path) energy_without_entropy = '{:.4f}'.format(outcar_params_dict['energy_without_entropy']) toten = '{:.4f}'.format(outcar_params_dict['TOTEN']) energy_sigma_0 = '{:.4f}'.format(outcar_params_dict['energy(sigma->0)']) elapsed_time_hour = '{:.4f}'.format(convert.time_converter(hour = 0, minute = 0, second = outcar_params_dict['elapsed_time'], unit = 'hour')) e_fermi = outcar_params_dict['e_fermi'] e_fermi_mod = outcar_params_dict['e_fermi_mod'] kpoints_dict = vasp_read.read_kpoints(kpoints_file_path) eigenval_dict = vasp_read.read_eigenval(eigenval_file_path) band_gap_dict = vasp_analyze.get_band_gap( eigenval_or_procar_dict = eigenval_dict, outcar_params_dict = outcar_params_dict, kpoints_dict = kpoints_dict, fermi_shift_zero = True, ) band_gap = band_gap_dict['band_gap'] gap_type = band_gap_dict['gap_type'] cbm = band_gap_dict['CBM'] vbm = band_gap_dict['VBM'] band_gap_up = band_gap_dict['band_gap_up'] gap_type_up = band_gap_dict['gap_type_up'] cbm_up = band_gap_dict['CBM_up'] vbm_up = band_gap_dict['VBM_up'] band_gap_dn = band_gap_dict['band_gap_dn'] gap_type_dn = band_gap_dict['gap_type_dn'] cbm_dn = band_gap_dict['CBM_dn'] vbm_dn = band_gap_dict['VBM_dn'] if band_gap in [None, 'None', 'none']: band_gap = 'None' else: band_gap = '{:.6f}'.format(band_gap) if cbm in [None, 'None', 'none']: cbm = 'None' else: cbm = '{:.6f}'.format(cbm) if vbm in [None, 'None', 'none']: vbm = 'None' else: vbm = '{:.6f}'.format(vbm) if band_gap_up in [None, 'None', 'none']: band_gap_up = 'None' else: band_gap_up = '{:.6f}'.format(band_gap_up) if cbm_up in [None, 'None', 'none']: cbm_up = 'None' else: cbm_up = '{:.6f}'.format(cbm_up) if vbm_up in [None, 'None', 'none']: vbm_up = 'None' else: vbm_up = '{:.6f}'.format(vbm_up) if band_gap_dn in [None, 'None', 'none']: band_gap_dn = 'None' else: band_gap_dn = '{:.6f}'.format(band_gap_dn) if cbm_dn in [None, 'None', 'none']: cbm_dn = 'None' else: cbm_dn = '{:.6f}'.format(cbm_dn) if vbm_dn in [None, 'None', 'none']: vbm_dn = 'None' else: vbm_dn = '{:.6f}'.format(vbm_dn) poscar_dict = vasp_read.read_poscar(poscar_file_path) if poscar_dict['file_status'] == 1: poscar_len_vec_a = poscar_dict['len_vec_a'] poscar_len_vec_b = poscar_dict['len_vec_b'] poscar_len_vec_c = poscar_dict['len_vec_c'] poscar_angle_alpha_degree = poscar_dict['angle_alpha_degree'] poscar_angle_beta_degree = poscar_dict['angle_beta_degree'] poscar_angle_gamma_degree = poscar_dict['angle_gamma_degree'] poscar_box_volume = poscar_dict['box_volume'] poscar_len_vec_a = '{:.4f}'.format(poscar_len_vec_a) poscar_len_vec_b = '{:.4f}'.format(poscar_len_vec_b) poscar_len_vec_c = '{:.4f}'.format(poscar_len_vec_c) poscar_angle_alpha_degree = '{:.4f}'.format(poscar_angle_alpha_degree) poscar_angle_beta_degree = '{:.4f}'.format(poscar_angle_beta_degree) poscar_angle_gamma_degree = '{:.4f}'.format(poscar_angle_gamma_degree) poscar_box_volume = '{:.4f}'.format(poscar_box_volume) contcar_dict = vasp_read.read_poscar(contcar_file_path) if contcar_dict['file_status'] == 1: contcar_len_vec_a = contcar_dict['len_vec_a'] contcar_len_vec_b = contcar_dict['len_vec_b'] contcar_len_vec_c = contcar_dict['len_vec_c'] contcar_angle_alpha_degree = contcar_dict['angle_alpha_degree'] contcar_angle_beta_degree = contcar_dict['angle_beta_degree'] contcar_angle_gamma_degree = contcar_dict['angle_gamma_degree'] contcar_box_volume = contcar_dict['box_volume'] contcar_len_vec_a = '{:.4f}'.format(contcar_len_vec_a) contcar_len_vec_b = '{:.4f}'.format(contcar_len_vec_b) contcar_len_vec_c = '{:.4f}'.format(contcar_len_vec_c) contcar_angle_alpha_degree = '{:.4f}'.format(contcar_angle_alpha_degree) contcar_angle_beta_degree = '{:.4f}'.format(contcar_angle_beta_degree) contcar_angle_gamma_degree = '{:.4f}'.format(contcar_angle_gamma_degree) contcar_box_volume = '{:.4f}'.format(contcar_box_volume) table_label = 'tab:' + i_dir_name + str(temp_indx) task_summary_ctex_str = task_summary_ctex_str + (r'The job summary is shown in Table \ref{' + table_label + '}.' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\begin{table}[!h]' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\centering' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\caption{\label{' + table_label + '}Job summary}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\begin{tabular}{ll}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\hline' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'Parameters & Value' + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + (r'\hline' + '\n') task_summary_ctex_str = task_summary_ctex_str + ('Job Status & ' + str(job_status) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('elapsed time(h) & ' + str(elapsed_time_hour) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + (r'\hline' + '\n') task_summary_ctex_str = task_summary_ctex_str + ('Energy without entropy &' + str(energy_without_entropy) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('TOTEN & ' + str(toten) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('energy(sigma->0) & ' + str(energy_sigma_0) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('E-fermi & ' + str(e_fermi) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('E-fermi (corrected) & ' + str(e_fermi_mod) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + (r'\hline' + '\n') if poscar_dict['file_status'] == 1: task_summary_ctex_str = task_summary_ctex_str + ('$|\\vec{a}|$ ($\mathring{A}$) (POSCAR)& ' + str(poscar_len_vec_a) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('$|\\vec{b}|$ ($\mathring{A}$) (POSCAR)& ' + str(poscar_len_vec_b) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('$|\\vec{c}|$ ($\mathring{A}$) (POSCAR)& ' + str(poscar_len_vec_c) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('$\\alpha$ (degree) (POSCAR)& ' + str(poscar_angle_alpha_degree) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('$\\beta$ (degree) (POSCAR)& ' + str(poscar_angle_beta_degree) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('$\\gamma$ (degree) (POSCAR)& ' + str(poscar_angle_gamma_degree) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('Volume ($\mathring{A}^{3}$) (POSCAR)& ' + str(poscar_box_volume) + '\\\\\n') if contcar_dict['file_status'] == 1: task_summary_ctex_str = task_summary_ctex_str + ('$|\\vec{a}|$ ($\mathring{A}$) (CONTCAR)& ' + str(contcar_len_vec_a) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('$|\\vec{b}|$ ($\mathring{A}$) (CONTCAR)& ' + str(contcar_len_vec_b) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('$|\\vec{c}|$ ($\mathring{A}$) (CONTCAR)& ' + str(contcar_len_vec_c) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('$\\alpha$ (degree) (CONTCAR)& ' + str(contcar_angle_alpha_degree) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('$\\beta$ (degree) (CONTCAR)& ' + str(contcar_angle_beta_degree) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('$\\gamma$ (degree) (CONTCAR)& ' + str(contcar_angle_gamma_degree) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('Volume ($\mathring{A}^{3}$) (CONTCAR)& ' + str(contcar_box_volume) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + (r'\hline' + '\n') task_summary_ctex_str = task_summary_ctex_str + ('$E_{gap}$ (eV) & ' + str(band_gap) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('Gap Type & ' + str(gap_type) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('CBM (eV) & ' + str(cbm) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('VBM (eV) & ' + str(vbm) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + (r'\hline' + '\n') task_summary_ctex_str = task_summary_ctex_str + ('$E_{gap}$(up) (eV) & ' + str(band_gap_up) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('Gap Type(up) & ' + str(gap_type_up) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('CBM(up) (eV) & ' + str(cbm_up) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('VBM(up) (eV) & ' + str(vbm_up) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + (r'\hline' + '\n') task_summary_ctex_str = task_summary_ctex_str + ('$E_{gap}$(down) (eV) & ' + str(band_gap_dn) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('Gap Type(down) & ' + str(gap_type_dn) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('CBM(down) (eV) & ' + str(cbm_dn) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + ('VBM(down) (eV) & ' + str(vbm_dn) + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + (r'\hline' + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + (r'\end{tabular}' + '\\\\\n') task_summary_ctex_str = task_summary_ctex_str + (r'\end{table}' + '\\\\\n') ############################### # Model ############################### task_summary_ctex_str = task_summary_ctex_str + (r'\subsection{Model}' + '\n') poscar_file_path = os.path.join(i_dir_path, 'POSCAR') if os.path.exists(poscar_file_path) and os.path.isfile(poscar_file_path): ###front view ##fig_poscar1 = vasp_plot.plot_poscar(poscar_file_path, euler_angle_type = 'zyx', phi = -3, theta = 5, psi = 0, ## elmt_color = None, draw_mirror_atom = True, box_on = True, axis_indicator = True, ## plot_cell_basis_vector_label = False, plot_atom_label = 'atom_name', label_size = 16, fig_format = 'png', fig_dpi = 150, ## draw_colormap = False, colormap_column_indx = 1, colormap_vmin = None, colormap_vmax = None, vmin_color = 'blue', vmax_color = 'red', colorbar_alignment = 'vertical') ###side view ##fig_poscar2 = vasp_plot.plot_poscar(poscar_file_path, euler_angle_type = 'zxy', phi = -87, theta = 5, psi = 0, ## elmt_color = None, draw_mirror_atom = True, box_on = True, axis_indicator = True, ## plot_cell_basis_vector_label = False, plot_atom_label = 'atom_name', label_size = 16, fig_format = 'png', fig_dpi = 150, ## draw_colormap = False, colormap_column_indx = 1, colormap_vmin = None, colormap_vmax = None, vmin_color = 'blue', vmax_color = 'red', colorbar_alignment = 'vertical') ###top view ##fig_poscar3 = vasp_plot.plot_poscar(poscar_file_path, euler_angle_type = 'yxz', phi = 93, theta = 5, psi = 0, ## elmt_color = None, draw_mirror_atom = True, box_on = True, axis_indicator = True, ## plot_cell_basis_vector_label = False, plot_atom_label = 'atom_name', label_size = 16, fig_format = 'png', fig_dpi = 150, ## draw_colormap = False, colormap_column_indx = 1, colormap_vmin = None, colormap_vmax = None, vmin_color = 'blue', vmax_color = 'red', colorbar_alignment = 'vertical') ##fig_poscar_list = [fig_poscar1, fig_poscar2, fig_poscar3] viewing_direction_list = ['front view', 'side view', 'top view'] #for i_fig_poscar_indx in range(0, 3): euler_angle_type_phi_theta_psi_list_dict= {} euler_angle_type_phi_theta_psi_list_dict['front view'] = ['zyx',-3, 5, 0] euler_angle_type_phi_theta_psi_list_dict['side view'] = ['zxy',-87, 5, 0] euler_angle_type_phi_theta_psi_list_dict['psi view'] = ['yxz',93, 5, 0] ##for i_fig_poscar_indx in [0, 1, 2]: for i_fig_poscar_indx in [0]: viewing_direction = viewing_direction_list[i_fig_poscar_indx] formatted_time = time.strftime('%Y%m%d_%H-%M-%S',time.localtime(time.time())) i_fig_file_path = os.path.join(task_summary_fig_dir, 'fig_poscar_' + formatted_time + '_randnum' + str(random.randint(0,99)) + '.' + fig_format) plot_poscar_dict = vasp_plot.plot_poscar( poscar_file_path, euler_angle_type = euler_angle_type_phi_theta_psi_list_dict[viewing_direction][0], phi = euler_angle_type_phi_theta_psi_list_dict[viewing_direction][1], theta = euler_angle_type_phi_theta_psi_list_dict[viewing_direction][2], psi = euler_angle_type_phi_theta_psi_list_dict[viewing_direction][3], elmt_color = None, draw_mirror_atom = True, box_on = True, axis_indicator = True, plot_cell_basis_vector_label = False, plot_atom_label = 'atom_name', label_size = 16, fig_format = fig_format, fig_dpi = 150, draw_colormap = False, colormap_column_indx = 1, colormap_vmin = None, colormap_vmax = None, vmin_color = 'blue', vmax_color = 'red', colorbar_alignment = 'vertical', output_fig_file_path = i_fig_file_path) #i_fig_poscar = fig_poscar_list[i_fig_poscar_indx] if plot_poscar_dict['fig_file'] in [None, 'None', 'none']: continue parent_path, filename1 = funcs.file_path_name(plot_poscar_dict['fig_file']) tex_fig_label1 = 'fig:model' + str(i_fig_poscar_indx) +'_' + str(i_dir_name) task_summary_ctex_str = task_summary_ctex_str + (r'The model (' + viewing_direction + ') is shown in Figure ' + r'\ref{' + tex_fig_label1 + '}.' + '\n\n') task_summary_ctex_str = task_summary_ctex_str + (r'\begin{figure}[h!]' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\centering' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\includegraphics[width=0.8\linewidth, height=10cm, keepaspectratio]{' + filename1 + '}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\caption{\label{' + tex_fig_label1 + '}Model (front view)' + '}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\end{figure}' + '\n') ################################# #inputs of the calculations ################################# task_summary_ctex_str = task_summary_ctex_str + (r'\subsection{Inputs Summary}' + '\n') # materials structure ##for i_subtask in task_full_item_list: ## if i_subtask in task_subdir_list: ## i_dir_path = os.path.join(task_dir, i_subtask) ##i_task_tex_str = i_subtask.replace("_", "\_") #task_summary_ctex_str = task_summary_ctex_str + (r'\subsection{' + i_task_tex_str + '}' + '\n') ##if i_dir_path == 'opt': task_summary_ctex_str = task_summary_ctex_str + (r'\subsubsection{POSCAR}' + '\n') poscar_str = funcs.get_file_str(os.path.join(i_dir_path, 'POSCAR')) task_summary_ctex_str = task_summary_ctex_str + (r'\begin{lstlisting}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (poscar_str) + '\n' task_summary_ctex_str = task_summary_ctex_str + (r'\end{lstlisting}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\subsubsection{INCAR}' + '\n') incar_file_path = os.path.join(i_dir_path, 'INCAR') if os.path.exists(incar_file_path) and os.path.isfile(incar_file_path): incar_str = funcs.get_file_str(incar_file_path) task_summary_ctex_str = task_summary_ctex_str + (r'\begin{lstlisting}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (incar_str) + '\n' task_summary_ctex_str = task_summary_ctex_str + (r'\end{lstlisting}' + '\n') kpoints_file_path = os.path.join(i_dir_path, 'KPOINTS') if os.path.exists(kpoints_file_path) and os.path.isfile(kpoints_file_path): task_summary_ctex_str = task_summary_ctex_str + (r'\subsubsection{KPOINTS}' + '\n') kpoints_str = funcs.get_file_str(kpoints_file_path) task_summary_ctex_str = task_summary_ctex_str + (r'\begin{lstlisting}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (kpoints_str) + '\n' task_summary_ctex_str = task_summary_ctex_str + (r'\end{lstlisting}' + '\n') ################################# #Electronic structure ################################# task_summary_ctex_str = task_summary_ctex_str + (r'\subsection{Electronic Structure}' + '\n') # electronic structure - band structure #task_summary_ctex_str = task_summary_ctex_str + (r'\subsection{Band Structure}' + '\n') ##for i_bs_name in ['bs', 'bs_soc']: kpoints_dict = vasp_read.read_kpoints(kpoints_file_path) ##if kpoints_dict['file_status'] != 1: ## print('WARNING #2012032054 (from task_manager): ' + kpoints_file_path + ' does not exist or is empty!') ##else: ## print(kpoints_dict['file_status']) if 'scheme' in kpoints_dict.keys() and job_finished == True: if kpoints_dict['scheme'] in ['l', 'L']: #i_task_tex_str = funcs.logic_retn_val(i_bs_name == 'bs_soc',' (SOC)','(w/o SOC)') ##if i_bs_name not in task_subdir_list: ## task_summary_ctex_str = task_summary_ctex_str + (r'\subsection{' + 'Band Structure' + i_task_tex_str + '}' + '\n') ## task_summary_ctex_str = task_summary_ctex_str + ('None\n') ## task_summary_ctex_str = task_summary_ctex_str + (r'\subsection{Fat Band' + i_task_tex_str + '}' + '\n') ## task_summary_ctex_str = task_summary_ctex_str + ('None\n') ##if i_bs_name in task_subdir_list: ######################## #band structure ######################## task_summary_ctex_str = task_summary_ctex_str + (r'\subsection{' + 'Band Structure}' + '\n') eigenval_file_path = os.path.join(i_dir_path, 'EIGENVAL') if os.path.exists(eigenval_file_path) and os.path.isfile(eigenval_file_path): if eigenval_dict['ispin'] == 1: band_indx_max = band_gap_dict['CBM_band_indx'] + num_added_bands band_indx_min = band_gap_dict['VBM_band_indx'] - num_added_bands if band_indx_max > band_gap_dict['num_bands']: band_indx_max = band_gap_dict['num_bands'] - 1 if band_indx_min < 0: band_indx_min = 0 e_max = np.max(band_gap_dict['eigs'][:, band_indx_max]) e_min = np.min(band_gap_dict['eigs'][:, band_indx_min]) elif eigenval_dict['ispin'] == 2: band_indx_max_up = band_gap_dict['CBM_band_indx_up'] + num_added_bands band_indx_min_up = band_gap_dict['VBM_band_indx_up'] - num_added_bands if band_indx_max_up > band_gap_dict['num_bands']: band_indx_max_up = band_gap_dict['num_bands'] - 1 if band_indx_min_up < 0: band_indx_min_up = 0 band_indx_max_dn = band_gap_dict['CBM_band_indx_dn'] + num_added_bands band_indx_min_dn = band_gap_dict['VBM_band_indx_dn'] - num_added_bands if band_indx_max_dn > band_gap_dict['num_bands']: band_indx_max_dn = band_gap_dict['num_bands'] - 1 if band_indx_min_dn < 0: band_indx_min_dn = 0 e_max_up = np.max(band_gap_dict['eigs_up'][:, band_indx_max_up]) e_min_up = np.min(band_gap_dict['eigs_up'][:, band_indx_min_up]) e_max_dn = np.max(band_gap_dict['eigs_dn'][:, band_indx_max_dn]) e_min_dn = np.min(band_gap_dict['eigs_dn'][:, band_indx_min_dn]) e_max = max(e_max_up, e_max_dn) e_min = min(e_min_up, e_min_dn) if band_struct_ylim in [None, 'None', 'none']: band_struct_ylim = [e_min, e_max] formatted_time = time.strftime('%Y%m%d_%H-%M-%S',time.localtime(time.time())) i_fig_file_path = os.path.join(task_summary_fig_dir, 'fig_bs_' + formatted_time + '_randnum' + str(random.randint(0,99)) + '.' + fig_format) plot_bs_dict = vasp_plot.plot_bs(infile_path_list = [eigenval_file_path], xlim = None, ylim = band_struct_ylim, fermi_shift_zero = True, band_list = None, interp_on = False, plot_band_data_point = False, plot_line = True, band_gap_label = band_gap_label, band_palette_dict = None, band_lty_dict = None, #for single system system_color_list = None, system_lty_list = None, #multiple systems spd_and_site_projections_file_path_list = None, projections_point_size_factor = 1, legend_on = True, plot_fermi_level = True, xtick_direction = 'out', ytick_direction = 'out', line_width = 2.0, font_size = font_size, fig_format = 'pdf', fig_size = [15,10], fig_dpi = 150, output_fig_file_path = i_fig_file_path) ##fig_bs1 = vasp_plot.plot_bs(infile_path_list = [eigenval_file_path], xlim = None, ylim = band_struct_ylim, fermi_shift_zero = True, band_list = None, ## interp_on = True, plot_band_data_point = False, ## band_gap_label = band_gap_label, ## band_palette_dict = None, band_lty_dict = None, #for single system ## system_color_list = None, system_lty_list = None, #multiple systems ## spd_and_site_projections_file_path_list = None, projections_point_size_factor = 1, ## legend_on = True, plot_fermi_level = True, ## xtick_direction = 'out', ytick_direction = 'out', ## line_width = 2.0, font_size = 18, fig_format = 'png', fig_size = [15,10], fig_dpi = 150) parent_path, filename = funcs.file_path_name(plot_bs_dict['fig_file']) # band structure over the whole energy range tex_fig_label = 'fig:bs_' + i_task_str.strip('\\').strip('#') task_summary_ctex_str = task_summary_ctex_str + (r'The band structure is shown in Figure ' + r'\ref{' + tex_fig_label + '}.' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\begin{figure}[h!]' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\centering' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\includegraphics[width=0.8\linewidth]{' + filename + '}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\caption{\label{' + tex_fig_label + '}Band structure}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\end{figure}' + '\n') ##parent_path, filename1 = funcs.file_path_name(fig_bs1) ### band structure in a specific energy range (usually near the Fermi level) ##tex_fig_label1 = 'fig:bs1_' + i_task_str.strip('\\').strip('#') ##task_summary_ctex_str = task_summary_ctex_str + (r'The band structure (in a specific energy range) of is shown in Figure ' + r'\ref{' + tex_fig_label1 + '}.' + '\n') ##task_summary_ctex_str = task_summary_ctex_str + (r'\begin{figure}[h!]' + '\n') ##task_summary_ctex_str = task_summary_ctex_str + (r'\centering' + '\n') ##task_summary_ctex_str = task_summary_ctex_str + (r'\includegraphics[width=0.8\linewidth]{' + filename1 + '}' + '\n') ##task_summary_ctex_str = task_summary_ctex_str + (r'\caption{\label{' + tex_fig_label1 + '}Band structure (in a specific energy range)}' + '\n') ##task_summary_ctex_str = task_summary_ctex_str + (r'\end{figure}' + '\n') ################################ #band structure (fat band) ################################ poscar_file_path = os.path.join(i_dir_path, 'POSCAR') procar_file_path = os.path.join(i_dir_path, 'PROCAR') if plot_fatband == True and os.path.exists(poscar_file_path) and os.path.isfile(poscar_file_path) and os.path.exists(procar_file_path) and os.path.isfile(procar_file_path): task_summary_ctex_str = task_summary_ctex_str + (r'\subsection{Fat Band}' + '\n') #prepare projections file projections_txt = '' projections_txt = projections_txt +( r'spin, mag, ions_list , orbit , color , legend' + '\n' ) poscar_dict = vasp_read.read_poscar(poscar_file_path) procar_dict = vasp_read.read_procar(procar_file_path) elmt_species_arr = poscar_dict['elmt_species_arr'] ispin = procar_dict['ispin'] item_counter = 0 for i_elmt_species in elmt_species_arr: if ispin == 1: projections_txt = projections_txt +( r"None, tot, " + r"['" + i_elmt_species + r"'] , tot , " + default_palette_list[item_counter] + r" , Auto" + "\n" ) elif ispin == 2: for i_spin in range(0, ispin): spin_label = funcs.logic_retn_val(i_spin == 0,'up','dn') projections_txt = projections_txt +( spin_label + r" , tot, " + r"['" + i_elmt_species + r"'] , tot , " + default_palette_list[item_counter] + r" , Auto" + "\n" ) item_counter = item_counter + 1 #write projections text into projections file projections_file_path = os.path.join(task_summary_dir, 'projections_elements.txt') funcs.write_file(projections_txt, projections_file_path, mode = 'w') #################################################################################################### # the fatband plotting is time consuming, turn on the switch if you want to plot the fatband #################################################################################################### #plot band structure (SOC) if procar_dict['ispin'] == 1: band_indx_max = band_gap_dict['CBM_band_indx'] + num_added_bands band_indx_min = band_gap_dict['VBM_band_indx'] - num_added_bands if band_indx_max > band_gap_dict['num_bands']: band_indx_max = band_gap_dict['num_bands'] - 1 if band_indx_min < 0: band_indx_min = 0 e_max = np.max(band_gap_dict['eigs'][:, band_indx_max]) e_min = np.min(band_gap_dict['eigs'][:, band_indx_min]) elif procar_dict['ispin'] == 2: band_indx_max_up = band_gap_dict['CBM_band_indx_up'] + num_added_bands band_indx_min_up = band_gap_dict['VBM_band_indx_up'] - num_added_bands if band_indx_max_up > band_gap_dict['num_bands']: band_indx_max_up = band_gap_dict['num_bands'] - 1 if band_indx_min_up < 0: band_indx_min_up = 0 band_indx_max_dn = band_gap_dict['CBM_band_indx_dn'] + num_added_bands band_indx_min_dn = band_gap_dict['VBM_band_indx_dn'] - num_added_bands if band_indx_max_dn > band_gap_dict['num_bands']: band_indx_max_dn = band_gap_dict['num_bands'] - 1 if band_indx_min_dn < 0: band_indx_min_dn = 0 e_max_up = np.max(band_gap_dict['eigs_up'][:, band_indx_max_up]) e_min_up = np.min(band_gap_dict['eigs_up'][:, band_indx_min_up]) e_max_dn = np.max(band_gap_dict['eigs_dn'][:, band_indx_max_dn]) e_min_dn = np.min(band_gap_dict['eigs_dn'][:, band_indx_min_dn]) e_max = max(e_max_up, e_max_dn) e_min = min(e_min_up, e_min_dn) if band_struct_ylim in [None, 'None', 'none']: band_struct_ylim = [e_min, e_max] formatted_time = time.strftime('%Y%m%d_%H-%M-%S',time.localtime(time.time())) i_fig_file_path = os.path.join(task_summary_fig_dir, 'fig_bs_fatband_' + formatted_time + '_randnum' + str(random.randint(0,99)) + '.' + fig_format) plot_bs_dict_fatband = vasp_plot.plot_bs(infile_path_list = [procar_file_path], xlim = None, ylim = band_struct_ylim, fermi_shift_zero = True, band_list = None, interp_on = False, plot_band_data_point = True, plot_line = False, band_gap_label = band_gap_label, band_palette_dict = None, band_lty_dict = None, #for single system system_color_list = None, system_lty_list = None, #multiple systems spd_and_site_projections_file_path_list = [projections_file_path], projections_point_size_factor = 1, legend_on = True, plot_fermi_level = True, xtick_direction = 'out', ytick_direction = 'out', line_width = 2.0, font_size = font_size, fig_format = 'pdf', fig_size = [15,10], fig_dpi = 150, output_fig_file_path = i_fig_file_path) ##fig_bs_fatband1 = vasp_plot.plot_bs(infile_path_list = [procar_file_path], xlim = None, ylim = band_struct_ylim, fermi_shift_zero = True, band_list = None, ## interp_on = False, plot_band_data_point = False, ## band_gap_label = band_gap_label, ## band_palette_dict = None, band_lty_dict = None, #for single system ## system_color_list = None, system_lty_list = None, #multiple systems ## spd_and_site_projections_file_path_list = [projections_file_path], projections_point_size_factor = 1, ## legend_on = True, plot_fermi_level = True, ## xtick_direction = 'out', ytick_direction = 'out', ## line_width = 2.0, font_size = 18, fig_format = 'png', fig_size = [15,10], fig_dpi = 150) parent_path, filename = funcs.file_path_name(plot_bs_dict_fatband['fig_file']) # band structure over the whole energy range tex_fig_label = 'fig:fatband_' + i_task_str.strip('\\').strip('#') task_summary_ctex_str = task_summary_ctex_str + (r'The fat band is shown in Figure ' + r'\ref{' + tex_fig_label + '}.' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\begin{figure}[h!]' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\centering' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\includegraphics[width=0.8\linewidth]{' + filename + '}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\caption{\label{' + tex_fig_label + '}Fat band}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\end{figure}' + '\n') ##parent_path, filename1 = funcs.file_path_name(fig_bs_fatband1) ### band structure in a specific energy range (usually near the Fermi level) ##tex_fig_label1 = 'fig:fatband1_' + i_task_str.strip('\\').strip('#') ##task_summary_ctex_str = task_summary_ctex_str + (r'The fat band (in a specific energy range) is shown in Figure ' + r'\ref{' + tex_fig_label1 + '}.' + '\n') ##task_summary_ctex_str = task_summary_ctex_str + (r'\begin{figure}[h!]' + '\n') ##task_summary_ctex_str = task_summary_ctex_str + (r'\centering' + '\n') ##task_summary_ctex_str = task_summary_ctex_str + (r'\includegraphics[width=0.8\linewidth]{' + filename1 + '}' + '\n') ##task_summary_ctex_str = task_summary_ctex_str + (r'\caption{\label{' + tex_fig_label1 + '}Fat band (in a specific energy range)}' + '\n') ##task_summary_ctex_str = task_summary_ctex_str + (r'\end{figure}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\cleardoublepage' + '\n') else: ##task_summary_ctex_str = task_summary_ctex_str + (r'\subsection{' + 'Band Structure}' + '\n') ##task_summary_ctex_str = task_summary_ctex_str + ('None\n') ##task_summary_ctex_str = task_summary_ctex_str + (r'\subsection{Fat Band}' + '\n') ##task_summary_ctex_str = task_summary_ctex_str + ('None\n') task_summary_ctex_str = task_summary_ctex_str + (r'\cleardoublepage' + '\n') pass # job_status #dir_tree_str = funcs.dir_tree(task_dir) job_status_str = vasp_tools.job_status(job_parent_dir = task_dir) task_summary_ctex_str = task_summary_ctex_str + (r'\section{APPENDIX: Job Status Summary}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\begin{landscape}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\begin{lstlisting}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (job_status_str + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\end{lstlisting}' + '\n') task_summary_ctex_str = task_summary_ctex_str + (r'\end{landscape}' + '\n') # comparision of recommended and human input # comparision of recommended job and human input job ######################## #Write .tex file ######################## #task_summary_ctex_file_name = 'task_summary' + task_dir_name + '.tex' task_summary_ctex_file_name = task_dir_name + '.tex' task_summary_ctex_file_path = os.path.join(task_summary_dir, task_summary_ctex_file_name) task_summary_ctex_str = task_summary_ctex_str + (r'\end{document}' + '\n') funcs.write_file(task_summary_ctex_str, task_summary_ctex_file_path, mode = 'w') ######################## # compile tex file ######################## tex_debug_mode = False debug_str = funcs.logic_retn_val(tex_debug_mode, '', ' --interaction=batchmode') try: if tex_debug_mode == False: os.system('xelatex' + debug_str + ' -aux-directory=' + task_summary_dir + ' -output-directory=' + task_summary_dir + ' ' + task_summary_ctex_file_path) os.system('bibtex ' + debug_str + ' -aux-directory=' + task_summary_dir + ' -output-directory=' + task_summary_dir + ' ' + task_summary_ctex_file_path[:-4] + '.aux') os.system('xelatex' + debug_str + ' -aux-directory=' + task_summary_dir + ' -output-directory=' + task_summary_dir + ' ' + task_summary_ctex_file_path) os.system('xelatex' + debug_str + ' -aux-directory=' + task_summary_dir + ' -output-directory=' + task_summary_dir + ' ' + task_summary_ctex_file_path) except: print('WARNING #2012271610: .tex file ' + task_summary_ctex_file_path + ' compilation failed.') return task_summary_ctex_file_path def gen_kpath(fpath, kpath_scheme, kpath_params): ''' Generate KPOINTS (currently, we use pymatgen and vaspkit to generate k-path) fpath: the working directory of the job kpath_scheme: pymatgen, vaspkit kpath_params: 'echo 3;echo 303 | vaspkit' ''' args_dict = locals() import os #fpath = bs_dir fpath = fpath pwd_dir = os.getcwd() if kpath_scheme in ['pymatgen', 'PYMATGEN']: temp_file_path = os.path.join(fpath, 'gen_kpoints_line_mode_pymatgen.py') kpath_params = '''from pymatgen.io.vasp.inputs import Kpoints from pymatgen.core import Structure from pymatgen.symmetry.bandstructure import HighSymmKpath struct = Structure.from_file('POSCAR') kpath = HighSymmKpath(struct) kpts = Kpoints.automatic_linemode(divisions = 20, ibz = kpath) kpts.write_file('KPOINTS')''' with open(temp_file_path, 'w') as f: f.write(kpath_params) try: poscar_file_path_bs = os.path.join(fpath, 'POSCAR') kpoints_file_path_bs = os.path.join(fpath, 'KPOINTS') from pymatgen.io.vasp.inputs import Kpoints from pymatgen.core import Structure from pymatgen.symmetry.bandstructure import HighSymmKpath #from pymatgen import Structure from pymatgen.symmetry.analyzer import SpacegroupAnalyzer ################### # prepare KPOINTS line-mode ################### struct = Structure.from_file(poscar_file_path_bs) kpath = HighSymmKpath(struct) kpts = Kpoints.automatic_linemode(divisions = 20, ibz = kpath) kpts.write_file(kpoints_file_path_bs) ################### # prepare primitive cell for band structure calculation ################### analyzer = SpacegroupAnalyzer(struct) prim_cell = analyzer.find_primitive() #print(prim_cell) prim_cell.to(filename = poscar_file_path_bs) except: pass elif kpath_scheme in ['vaspkit', 'VASPKIT', 'VaspKit', 'vasp kit']: # the vaspkit scheme can also be used to generate k-points: temp_file_path = os.path.join(fpath, 'gen_kpoints_line_mode_vaspkit.sh') temp_str = '' temp_str = temp_str + '#!/bin/bash\n' temp_str = temp_str + 'cd ' + fpath + '\n' temp_str = temp_str + kpath_params + '\n' temp_str = temp_str + 'cd ' + pwd_dir + '\n' with open(temp_file_path, 'w') as f: f.write(temp_str) try: os.system('sh ' + temp_file_path + ' > ' + os.path.join(fpath, 'vaspkit.log')) os.system('cp -r ' + os.path.join(fpath, 'KPATH.in') + ' ' + os.path.join(fpath, 'KPOINTS')) except: pass return 0 def gen_inputs(poscar_file_path_list, project_name = None, task_type = 'VASP', elmt_potcar_dir = None, apply_to_existed_task = True, use_primitive_cell = True, kpath_scheme = 'vaspkit', kpath_params = '''echo 3 ; echo 303 | vaspkit''', ): ''' generate inputs for a specified structure. The generated inputs are used for further structural optimization. project_name: user-defined name of the project. If None is given, the project_name will be same as poscar_file_dir For a given structure, to keep the uniqueness of the task, this module should only run once. use_primitive_cell: If True, then the structure will be reduced to primitive cell. Now the "phonopy --symmetry" is used to fulfill this function. ''' args_dict = locals() import time import math import os import re import random import numpy as np from .. import funcs from .. import default_params from ..vasp import vasp_write from ..vasp import vasp_read from ..vasp import vasp_analyze from ..vasp import vasp_tools #if params_test == True: #get params from params_test_output #modify the params according to the params test results defaults_dict = default_params.default_params() logfile = defaults_dict['logfile'] output_dir = os.path.join(os.getcwd(), defaults_dict['output_dir_name']) projects_dir = os.path.join(output_dir, defaults_dict['projects_dir_name']) funcs.mkdir(output_dir) funcs.mkdir(projects_dir) elmt_potcar_dir = os.path.abspath(elmt_potcar_dir) # build project ##temp_dir, dir_name = os.path.split(poscar_file_dir) ##if project_name in [None, 'None', 'none']: ## project_name = dir_name if project_name in [None, 'None', 'none']: project_name = 'Untitled' project_dir = os.path.join(projects_dir, project_name) funcs.mkdir(project_dir) project_dir_name = os.path.split(project_dir)[-1] job_id_file_name = 'job_id.txt' ### get poscar_file_path_list from poscar_file_dir ##poscar_file_path_list = [] ##items_list = os.listdir(poscar_file_dir) ##for i_name in items_list: ## i_file = os.path.join(poscar_file_dir, i_name) ## # Should add a functions to check if the file is POSCAR or not ## if os.path.isfile(i_file): ## poscar_file_path_list.append(i_file) # loop over each task for poscar_file_path in poscar_file_path_list: poscar_file_path = os.path.abspath(poscar_file_path) temp_dir, file_name = os.path.split(poscar_file_path) middle_dir_name = os.path.split(temp_dir)[-1] poscar_dict = vasp_read.read_poscar(poscar_file_path) chem_formula_str = '' for i_elmt_indx in range(0, len(poscar_dict['elmt_species_arr'])): chem_formula_str = chem_formula_str + poscar_dict['elmt_species_arr'][i_elmt_indx] + str(poscar_dict['elmt_num_arr'][i_elmt_indx]) ##current_time = time.time() ##formatted_time = time.strftime('## %Y%m%d%H%M',time.localtime(current_time)) ##int1 = random.randint(0, 99).zfill(2) ##int2 = random.randint(0, 99).zfill(2) ##task_id = formatte_time[2:] + str(int1) + str(int2) ##task_dir_name = task_id + '_' + chem_formula_str ##task_dir = os.path.join(project_dir, task_dir_name) ##task_dir_name = chem_formula_str task_dir_name = file_name # to conform with the project_manager flow, if the POSCAR file is ***/opt/POSCAR, change the file_name # It is better for the user to name the input structure (POSCAR file) with a specific name, not to directly name it to 'POSCAR'. if task_dir_name == 'POSCAR' and middle_dir_name in ['opt']: task_dir_name = os.path.split(os.path.split(os.path.split(poscar_file_path)[0])[0])[-1] # remove the parenthesis '(', or ')' in the name, to avoid the following errors: # sh: -c: line 0: syntax error near unexpected token `(' # sh: -c: line 0: `sh a.sh' task_dir_name = re.sub('[()]', '', task_dir_name) task_dir = os.path.join(project_dir, task_dir_name) existed_task_dir_list = [os.path.join(project_dir, x) for x in os.listdir(project_dir) if os.path.isdir(os.path.join(project_dir, x))] if task_dir in existed_task_dir_list: if apply_to_existed_task == True: pass elif apply_to_existed_task == False: print('WARNING #2012271603 (from task_manager.gen_inputs): Duplicate chemical composition warning: the task for ' + poscar_file_path + ' is omitted.') continue ##continue #task_dir_name = task_dir_name + '_d1' funcs.mkdir(task_dir) opt_dir = os.path.join(task_dir, 'opt/') scf_dir = os.path.join(task_dir, 'scf/') dos_dir = os.path.join(task_dir, 'dos/') bs_dir = os.path.join(task_dir, 'bs/') bs_soc_dir = os.path.join(task_dir, 'bs_soc/') nscf_dir = os.path.join(task_dir, 'nscf/') test_encut_dir = os.path.join(task_dir, 'test_encut/') test_kpoints_dir = os.path.join(task_dir, 'test_kpoints/') funcs.mkdir(opt_dir) funcs.mkdir(scf_dir) funcs.mkdir(dos_dir) funcs.mkdir(bs_dir) funcs.mkdir(bs_soc_dir) funcs.mkdir(nscf_dir) funcs.mkdir(test_encut_dir) funcs.mkdir(test_kpoints_dir) opt_poscar_file_path = os.path.join(opt_dir, 'POSCAR') scf_poscar_file_path = os.path.join(scf_dir, 'POSCAR') dos_poscar_file_path = os.path.join(dos_dir, 'POSCAR') bs_poscar_file_path = os.path.join(bs_dir, 'POSCAR') bs_soc_poscar_file_path = os.path.join(bs_soc_dir, 'POSCAR') nscf_poscar_file_path = os.path.join(nscf_dir, 'POSCAR') task_dir_list = [opt_dir, scf_dir, dos_dir, bs_dir, bs_soc_dir, nscf_dir, test_encut_dir, test_kpoints_dir] for i_task_dir in task_dir_list: if os.path.exists(i_task_dir) and not os.path.isfile(i_task_dir): pass else: print('WARNING #2012271604 (from task_manager.gen_inputs): ' + i_task_dir + ' does not exist! Cannot be created.') # If vacuum exists in certain direction, then set the number of kpoints in that directions to num_kpt_in_vacuum_direction num_kpt_in_vacuum_direction = 1 ############################ # opt ############################ outcar_path = os.path.join(opt_dir, 'OUTCAR') # when the job is running, or it has been finished, it will be skipped job_id_file_path = os.path.join(opt_dir, job_id_file_name) if os.path.exists(job_id_file_path): with open(job_id_file_path, 'r') as f: line = f.readlines() try: job_id = int(line[0]) except: job_id = None else: job_id = None if job_id_exists(job_id) == True: # if the job is running, then pass pass elif check_job_type(opt_dir) == 'VASP' and os.path.exists(outcar_path) and os.path.isfile(outcar_path) and vasp_tools.vasp_job_finished(outcar_path, suppress_warning = True) == True: pass else: # prepare POSCAR opt_poscar_file_path = os.path.join(opt_dir, 'POSCAR') if not os.path.exists(opt_poscar_file_path) and not os.path.isfile(opt_poscar_file_path): funcs.cp(poscar_file_path, opt_poscar_file_path) # reduce the structure to primitive cell using "phonopy --symmetry" if use_primitive_cell == True: try: pwd_dir = os.getcwd() fpath, fname = os.path.split(opt_poscar_file_path) phonopy_sh_file_path = os.path.join(output_dir, 'run_phonopy.sh') funcs.touch(phonopy_sh_file_path) with open(phonopy_sh_file_path, 'w') as f: f.write('#!/bin/bash\n') f.write('cd ' + fpath + '\n') f.write('phonopy --symmetry > phonopy_symmetry.log' + '\n') f.write('cp PPOSCAR POSCAR' + '\n') f.write('cd ' + pwd_dir + '\n') os.system('sh ' + phonopy_sh_file_path) except: print('# phonopy --symmetry did not work for the file: ' + opt_poscar_file_path) ################################## # prepare INCAR ################################## incar_dict = {} incar_dict['SYSTEM'] = 'opt' incar_dict['ISTART'] = 0 incar_dict['ENCUT'] = 500 incar_dict['EDIFF'] = 1E-06 incar_dict['EDIFFG'] = -1E-02 incar_dict['PREC'] = 'Accurate' incar_dict['IBRION'] = 2 incar_dict['NSW'] = 200 incar_dict['ISIF'] = 3 incar_dict['POTIM'] = 0.5 incar_dict['ALGO'] = 'Normal' incar_dict['ISMEAR'] = 0 incar_dict['SIGMA'] = 0.05 incar_dict['LREAL'] = '.FALSE.' incar_dict['ISPIN'] = 2 incar_dict['NELM'] = 200 incar_dict['NELMIN'] = 6 incar_dict['ICHARG'] = 2 incar_dict['LWAVE'] = '.FALSE.' incar_dict['LCHARG'] = '.FALSE.' incar_dict['NPAR'] = 4 incar_dict['AMIX'] = 0.1 incar_file_path = os.path.join(opt_dir, 'INCAR') vasp_write.write_incar(incar_file_path, incar_dict = incar_dict, mode = 'w') ################################## # prepare KPOINTS ################################## vec1_len = np.linalg.norm(poscar_dict['l_arr'][0,:]) vec2_len = np.linalg.norm(poscar_dict['l_arr'][1,:]) vec3_len = np.linalg.norm(poscar_dict['l_arr'][2,:]) # k_times_x can affect the number of KPOINTS k_times_x = 60 num_k1 = int(math.ceil(k_times_x / vec1_len)) num_k2 = int(math.ceil(k_times_x / vec2_len)) num_k3 = int(math.ceil(k_times_x / vec3_len)) # odd number of kpoints if (num_k1 % 2) == 0: num_k1 = num_k1 + 1 if (num_k2 % 2) == 0: num_k2 = num_k2 + 1 if (num_k3 % 2) == 0: num_k3 = num_k3 + 1 if os.path.exists(opt_poscar_file_path): vacuum_in_xyz = vasp_tools.get_vacuum_status(opt_poscar_file_path) ##################################################################################################################################### # If vacuum exist in the model, the vector length in that direction can be kept unchanged. To that end, the user can modify VSAP src. # The usser can modify the VASP src file constr_cell_relax.F by inserting the following codes and recompile VASP software. # After recompiling VASP, the user needs OPTCELL file and set ISIF = 3 to relax the model # # # Adding the folowing codes to SUBROUTINE CONSTR_CELL_RELAX(FCELL) in constr_cell_relax.F: # LOGICAL FILFLG # INTEGER ICELL(3,3) # INQUIRE(FILE='OPTCELL',EXIST=FILFLG) # IF (FILFLG) THEN # OPEN(67,FILE='OPTCELL',FORM='FORMATTED',STATUS='OLD') # DO J=1,3 # READ(67,"(3I1)") (ICELL(I,J),I=1,3) # ENDDO # CLOSE(67) # DO J=1,3 # DO I=1,3 # IF (ICELL(I,J)==0) FCELL(I,J)=0.0 # ENDDO # ENDDO # ENDIF ##################################################################################################################################### identity_arr = np.ones((3,3)) if vacuum_in_xyz[0] == True: num_k1 = num_kpt_in_vacuum_direction identity_arr[0,:] = [0,0,0] elif vacuum_in_xyz[1] == True: num_k2 = num_kpt_in_vacuum_direction identity_arr[1,:] = [0,0,0] elif vacuum_in_xyz[2] == True: num_k3 = num_kpt_in_vacuum_direction identity_arr[2,:] = [0,0,0] optcell_file_path = os.path.join(opt_dir, 'OPTCELL') np.savetxt(optcell_file_path, identity_arr, fmt = '%i') kpoints_str = '' kpoints_str = kpoints_str + 'Gamma centered Monkhorst-Pack grids' + '\n' kpoints_str = kpoints_str + '0' + '\n' kpoints_str = kpoints_str + 'Gamma' + '\n' kpoints_str = kpoints_str + str(num_k1) + ' ' + str(num_k2) + ' ' + str(num_k3) + '\n' kpoints_str = kpoints_str + '0 0 0' + '\n' kpoints_file_path = os.path.join(opt_dir, 'KPOINTS') funcs.write_file(kpoints_str, kpoints_file_path, mode = 'w') ################################## # prepare POTCAR ################################## try: vasp_write.write_potcar(opt_poscar_file_path, elmt_potcar_dir) except: print('WARNING #2101102026 from gen_inputs: Cannot write POTCAR file') ################################## # Modify INCAR ################################## # set default ENCUT according to 1.3 * ENMAX (Value of ENMAX can be found in POTCAR) opt_potcar_file_path = os.path.join(task_dir, 'opt', 'POTCAR') enmax_val = -9999 if os.path.exists(opt_potcar_file_path) and os.path.isfile(opt_potcar_file_path): if funcs.file_status(opt_potcar_file_path, suppress_warning = True) == 1: grep_str = funcs.grep('ENMAX', opt_potcar_file_path) pot_list = grep_str.split('\n') for i_elmt in range(0, len(poscar_dict['elmt_species_arr'])): enmax_temp = float(pot_list[i_elmt].split(';')[0].split('=')[-1]) enmax_val = max(enmax_val, enmax_temp) recommended_encut_val = math.ceil(enmax_val * 1.3 / 10) * 10 encut_val = recommended_encut_val elif funcs.file_status(opt_potcar_file_path, suppress_warning = True) == 2: print('WARNING #2012271605 (from task_manager.gen_inputs): ' + opt_potcar_file_path + ' is empty. Please check your POTCAR file. This problem may caused by the absense of the elemental POTCAR file (e.g. POTCAR.Z), i.e. the designation of the elemental POTCAR directory is not correct or it actually does not exist. Due to this problem, we set ENCUT = 350 (an arbitrary value) for the INCAR of the job directory ' + opt_dir) recommended_encut_val = 350 # an arbitrary ENCUT value encut_val = recommended_encut_val elif funcs.file_status(opt_potcar_file_path, suppress_warning = True) == 0: pass vasp_write.write_incar(incar_file_path, incar_dict = {'ENCUT': recommended_encut_val}, mode = 's') # set default LREAL according to pseudo.F in the VASP source code if incar_dict['LREAL'] in ['.FALSE.', '.F.'] and poscar_dict['n_atoms'] > 16: recommended_lreal_val = 'Auto' vasp_write.write_incar(incar_file_path, incar_dict = {'LREAL': recommended_lreal_val}, mode = 's') elif incar_dict['LREAL'] in ['.TRUE.', '.T.', 'On', 'O', 'Auto', 'A'] and poscar_dict['n_atoms'] < 8: recommended_lreal_val = '.FALSE.' vasp_write.write_incar(incar_file_path, incar_dict = {'LREAL': recommended_lreal_val}, mode = 's') # modify MAGMOM incar_dict_temp = {} magmom = '' transition_metal_list = ['Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg',] if os.path.exists(opt_poscar_file_path) and os.path.isfile(opt_poscar_file_path): poscar_dict_opt = vasp_read.read_poscar(opt_poscar_file_path) magmom = '' for i_indx in range(0, len(poscar_dict_opt['elmt_species_arr'])): i_elmt = poscar_dict_opt['elmt_species_arr'][i_indx] i_elmt_num = poscar_dict_opt['elmt_num_arr'][i_indx] if i_elmt in transition_metal_list: magmom = magmom + str(i_elmt_num) + '*5.0 ' else: magmom = magmom + str(i_elmt_num) + '*0.6 ' incar_dict_temp['MAGMOM'] = magmom vasp_write.write_incar(incar_file_path, incar_dict = incar_dict_temp, mode = 's') #Currently, we don't use tested parameters, to save the computational cost, the tested parameters is recommended to be used only in the refined calculations. use_tested_parameters = False if use_tested_parameters == True: # set ENCUT and KPOINTS according to the ENCUT and KPOINT test results (if the tests has been done) if os.path.exists(test_encut_dir) and not os.path.isfile(test_encut_dir): opt_outcar_file_path = os.path.join(task_dir, 'opt', 'OUTCAR') i_job_finished = vasp_tools.vasp_job_finished(opt_outcar_file_path, suppress_warning = True) i_job_type = check_job_type(os.path.join(task_dir, 'opt')) if i_job_type == 'VASP' and i_job_finished != True: recommended_encut_test = get_recommended_test_param(test_encut_dir) funcs.touch(os.path.join(test_encut_dir, 'test.log')) if recommended_encut_test <= encut_val: recommended_encut_test = encut_val with open(os.path.join(test_encut_dir, 'test.log'), 'w') as f: f.write(str(recommended_encut_test)) vasp_write.write_incar(incar_file_path, incar_dict = {'ENCUT': recommended_encut_test}, mode = 's') if os.path.exists(test_kpoints_dir) and not os.path.isfile(test_kpoints_dir): opt_outcar_file_path = os.path.join(task_dir, 'opt', 'OUTCAR') i_job_finished = vasp_tools.vasp_job_finished(opt_outcar_file_path, suppress_warning = True) i_job_type = check_job_type(os.path.join(task_dir, 'opt')) if i_job_type == 'VASP' and i_job_finished != True: recommended_kpoints_test = int(get_recommended_test_param(test_kpoints_dir)) funcs.touch(os.path.join(test_kpoints_dir, 'test.log')) kpoints_dict_opt = vasp_read.read_kpoints(os.path.join(opt_dir, 'KPOINTS')) kpoints_val = kpoints_dict_opt['subdivisions_arr'][0] if recommended_kpoints_test <= kpoints_val: recommended_kpoints_test = kpoints_val with open(os.path.join(test_kpoints_dir, 'test.log'), 'w') as f: f.write(str(recommended_kpoints_test)) kpoints_dict = vasp_read.read_kpoints(os.path.join(opt_dir, 'KPOINTS')) if kpoints_dict['scheme'] in ['g', 'G', 'm', 'M']: subdivisions_arr = (kpoints_dict['subdivisions_arr']) subdivisions_arr[0] = recommended_kpoints_test subdivisions_arr[1] = recommended_kpoints_test subdivisions_arr[2] = recommended_kpoints_test kpoints_dict_temp = {} kpoints_dict_temp['subdivisions_arr'] = subdivisions_arr vasp_write.write_kpoints(os.path.join(opt_dir, 'KPOINTS'), kpoints_dict = kpoints_dict_temp, mode = 's') # when opt job is running, or it has been finished, the test will be skipped job_id_file_path = os.path.join(opt_dir, job_id_file_name) if os.path.exists(job_id_file_path): with open(job_id_file_path, 'r') as f: line = f.readlines() try: job_id = int(line[0]) except: job_id = None else: job_id = None if job_id_exists(job_id) == True: # if the job is running, then pass pass elif check_job_type(opt_dir) == 'VASP' and os.path.exists(outcar_path) and os.path.isfile(outcar_path) and vasp_tools.vasp_job_finished(outcar_path, suppress_warning = True) == True: pass else: ############################ # ENCUT test ############################ # copy A B src_dir = opt_dir dst_dir = test_encut_dir for i_file_name in ['INCAR', 'POSCAR', 'KPOINTS', 'POTCAR']: src_file_name = i_file_name dst_file_name = i_file_name dst_file_path = os.path.join(dst_dir, dst_file_name) if os.path.exists(src_dir) and not os.path.isfile(src_dir): src_file_path = os.path.join(opt_dir, src_file_name) if os.path.exists(src_file_path) and os.path.isfile(src_file_path): funcs.cp(src_file_path, dst_file_path) # prepare INCAR incar_dict_temp = {} incar_dict_temp['ENCUT'] = '$i' vasp_write.write_incar(os.path.join(test_encut_dir, 'INCAR'), incar_dict = incar_dict_temp, mode = 's') #generate ENCUT test list incar_dict_opt = vasp_read.read_incar(os.path.join(opt_dir, 'INCAR')) encut_val = incar_dict_opt['ENCUT'] encut_test_val_list = [encut_val] encut_val_temp = encut_val for indx in range(0, 4): encut_val_temp = encut_val_temp - 50 if encut_val_temp >= 170: encut_test_val_list.append(encut_val_temp) encut_val_temp = encut_val for indx in range(0, 5): encut_val_temp = encut_val_temp + 50 if encut_val_temp >= 170: encut_test_val_list.append(encut_val_temp) encut_test_val_list = sorted(encut_test_val_list) params_test(test_encut_dir, variant_name = '$i', variant_value_list = encut_test_val_list) # build log file #funcs.touch(os.path.join(test_encut_dir, 'test.log')) ############################ # KPOINTS test ############################ # copy A B src_dir = opt_dir dst_dir = test_kpoints_dir for i_file_name in ['INCAR', 'POSCAR', 'KPOINTS', 'POTCAR']: src_file_name = i_file_name dst_file_name = i_file_name dst_file_path = os.path.join(dst_dir, dst_file_name) if os.path.exists(src_dir) and not os.path.isfile(src_dir): src_file_path = os.path.join(src_dir, src_file_name) if os.path.exists(src_file_path) and os.path.isfile(src_file_path): funcs.cp(src_file_path, dst_file_path) # prepare INCAR: get ENCUT from the test_encut job # get ENCUT from test ENCUT task recommended_encut_test = get_recommended_test_param(test_encut_dir) funcs.touch(os.path.join(test_encut_dir, 'test.log')) if recommended_encut_test <= encut_val: recommended_encut_test = encut_val with open(os.path.join(test_encut_dir, 'test.log'), 'w') as f: f.write(str(recommended_encut_test)) test_log_path = os.path.join(test_encut_dir, 'test.log') if os.path.exists(test_log_path) and os.path.isfile(test_log_path) and os.path.getsize(test_log_path) > 0: with open(test_log_path, 'r') as f: line = f.readlines() recommended_encut = float(funcs.split_line(line = line[0], separator = '=')[-1]) incar_dict_test_encut = vasp_read.read_incar(os.path.join(test_encut_dir, 'INCAR')) incar_dict_temp = {} incar_dict_temp['ENCUT'] = recommended_encut vasp_write.write_incar(os.path.join(test_kpoints_dir, 'INCAR'), incar_dict = incar_dict_temp, mode = 's') # modify the KPOINTS poscar_dict = vasp_read.read_poscar(os.path.join(opt_dir, 'POSCAR')) vec1_len = np.linalg.norm(poscar_dict['l_arr'][0,:]) vec2_len = np.linalg.norm(poscar_dict['l_arr'][1,:]) vec3_len = np.linalg.norm(poscar_dict['l_arr'][2,:]) num_k1 = int(math.ceil(60 / vec1_len)) num_k2 = int(math.ceil(60 / vec2_len)) num_k3 = int(math.ceil(60 / vec3_len)) # odd number of kpoints if (num_k1 % 2) == 0: num_k1 = num_k1 + 1 if (num_k2 % 2) == 0: num_k2 = num_k2 + 1 if (num_k3 % 2) == 0: num_k3 = num_k3 + 1 if os.path.exists(os.path.join(opt_dir, 'POSCAR')): vacuum_in_xyz = vasp_tools.get_vacuum_status(os.path.join(opt_dir, 'POSCAR')) if vacuum_in_xyz[0] == True: num_k1 = num_kpt_in_vacuum_direction elif vacuum_in_xyz[1] == True: num_k2 = num_kpt_in_vacuum_direction elif vacuum_in_xyz[2] == True: num_k3 = num_kpt_in_vacuum_direction kpoints_dict = vasp_read.read_kpoints(os.path.join(opt_dir, 'KPOINTS')) if kpoints_dict['scheme'] in ['g', 'G', 'm', 'M']: subdivisions_arr = (kpoints_dict['subdivisions_arr']) subdivisions_arr[0] = '$i' subdivisions_arr[1] = '$i' subdivisions_arr[2] = '$i' kpoints_dict_temp = {} kpoints_dict_temp['subdivisions_arr'] = subdivisions_arr vasp_write.write_kpoints(os.path.join(test_kpoints_dir, 'KPOINTS'), kpoints_dict = kpoints_dict_temp, mode = 's') #generate test list kpoints_dict_opt = vasp_read.read_kpoints(os.path.join(opt_dir, 'KPOINTS')) #kpoints_val = kpoints_dict_opt['subdivisions_arr'][0] kpoints_val = num_k1 kpoints_test_val_list = [kpoints_val] kpoints_val_temp = kpoints_val for indx in range(0, 4): kpoints_val_temp = kpoints_val_temp - 2 if kpoints_val_temp >= 0: kpoints_test_val_list.append(kpoints_val_temp) kpoints_val_temp = kpoints_val for indx in range(0, 5): kpoints_val_temp = kpoints_val_temp + 2 if kpoints_val_temp >= 0: kpoints_test_val_list.append(kpoints_val_temp) kpoints_test_val_list = sorted(kpoints_test_val_list) params_test(test_kpoints_dir, variant_name = '$i', variant_value_list = kpoints_test_val_list) # build log file #funcs.touch(os.path.join(test_kpoints_dir, 'test.log')) ############################ # scf ############################ outcar_path = os.path.join(scf_dir, 'OUTCAR') scf_poscar_file_path = os.path.join(scf_dir, 'POSCAR') # when the job is running, or it has been finished, it will be skipped job_id_file_path = os.path.join(scf_dir, job_id_file_name) if os.path.exists(job_id_file_path): with open(job_id_file_path, 'r') as f: line = f.readlines() try: job_id = int(line[0]) except: job_id = None else: job_id = None if job_id_exists(job_id) == True: # if the job is running, then pass pass elif check_job_type(scf_dir) == 'VASP' and os.path.exists(outcar_path) and os.path.isfile(outcar_path) and vasp_tools.vasp_job_finished(outcar_path, suppress_warning = True) == True: pass else: # copy A B src_dir = opt_dir dst_dir = scf_dir for i_file_name in ['CHGCAR', 'WAVECAR', 'CONTCAR', 'KPOINTS', 'POTCAR']: src_file_name = i_file_name dst_file_name = i_file_name if i_file_name == 'CONTCAR': src_file_name = 'CONTCAR' dst_file_name = 'POSCAR' dst_file_path = os.path.join(dst_dir, dst_file_name) if os.path.exists(src_dir) and not os.path.isfile(src_dir): src_file_path = os.path.join(src_dir, src_file_name) if os.path.exists(src_file_path) and os.path.isfile(src_file_path): funcs.cp(src_file_path, dst_file_path) # prepare INCAR incar_dict = {} incar_dict['SYSTEM'] = 'scf' incar_dict['ISTART'] = 0 incar_dict['ENCUT'] = 500 incar_dict['EDIFF'] = 1E-06 incar_dict['EDIFFG'] = -1E-02 incar_dict['PREC'] = 'Accurate' incar_dict['IBRION'] = -1 incar_dict['NSW'] = 0 incar_dict['ISIF'] = 3 incar_dict['POTIM'] = 0.5 incar_dict['ALGO'] = 'Normal' incar_dict['ISMEAR'] = 0 incar_dict['SIGMA'] = 0.05 incar_dict['LREAL'] = '.FALSE.' incar_dict['ISPIN'] = 2 incar_dict['NELM'] = 200 incar_dict['NELMIN'] = 6 incar_dict['ICHARG'] = 2 incar_dict['LWAVE'] = '.FALSE.' incar_dict['LCHARG'] = '.TRUE.' incar_dict['NPAR'] = 4 incar_dict['AMIX'] = 0.1 incar_file_path = os.path.join(scf_dir, 'INCAR') vasp_write.write_incar(incar_file_path, incar_dict = incar_dict, mode = 'w') # modify ENCUT incar_dict_opt = vasp_read.read_incar(os.path.join(opt_dir, 'INCAR')) incar_dict_temp = {} incar_dict_temp['ENCUT'] = incar_dict_opt['ENCUT'] vasp_write.write_incar(incar_file_path, incar_dict = incar_dict_temp, mode = 's') # set default LREAL according to pseudo.F in the VASP source code if incar_dict['LREAL'] in ['.FALSE.', '.F.'] and poscar_dict['n_atoms'] > 16: recommended_lreal_val = 'Auto' vasp_write.write_incar(incar_file_path, incar_dict = {'LREAL': recommended_lreal_val}, mode = 's') elif incar_dict['LREAL'] in ['.TRUE.', '.T.', 'On', 'O', 'Auto', 'A'] and poscar_dict['n_atoms'] < 8: recommended_lreal_val = '.FALSE.' vasp_write.write_incar(incar_file_path, incar_dict = {'LREAL': recommended_lreal_val}, mode = 's') # modify MAGMOM incar_dict_temp = {} magmom = '' transition_metal_list = ['Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg',] if os.path.exists(scf_poscar_file_path) and os.path.isfile(scf_poscar_file_path): # in case the POSCAR in the scf folder is empty, we use the POSCAR from opt directory poscar_dict = vasp_read.read_poscar(opt_poscar_file_path) magmom = '' for i_indx in range(0, len(poscar_dict['elmt_species_arr'])): i_elmt = poscar_dict['elmt_species_arr'][i_indx] i_elmt_num = poscar_dict['elmt_num_arr'][i_indx] if i_elmt in transition_metal_list: magmom = magmom + str(i_elmt_num) + '*5.0 ' else: magmom = magmom + str(i_elmt_num) + '*0.6 ' incar_dict_temp['MAGMOM'] = magmom vasp_write.write_incar(incar_file_path, incar_dict = incar_dict_temp, mode = 's') # modify the KPOINTS kpoints_dict = vasp_read.read_kpoints(os.path.join(opt_dir, 'KPOINTS')) if kpoints_dict['scheme'] in ['g', 'G', 'm', 'M']: #subdivisions_arr = (kpoints_dict['subdivisions_arr'] * 2) - 1 subdivisions_arr = (kpoints_dict['subdivisions_arr'] + 2) if os.path.exists(scf_poscar_file_path): vacuum_in_xyz = vasp_tools.get_vacuum_status(scf_poscar_file_path) if vacuum_in_xyz[0] == True: subdivisions_arr[0] = num_kpt_in_vacuum_direction elif vacuum_in_xyz[1] == True: subdivisions_arr[1] = num_kpt_in_vacuum_direction elif vacuum_in_xyz[2] == True: subdivisions_arr[2] = num_kpt_in_vacuum_direction kpoints_dict_temp = {} kpoints_dict_temp['subdivisions_arr'] = subdivisions_arr vasp_write.write_kpoints(os.path.join(scf_dir, 'KPOINTS'), kpoints_dict = kpoints_dict_temp, mode = 's') ############################ # bs ############################ bs_poscar_file_path = os.path.join(bs_dir, 'POSCAR') # when the job is running, or it has been finished, it will be skipped job_id_file_path = os.path.join(bs_dir, job_id_file_name) if os.path.exists(job_id_file_path): with open(job_id_file_path, 'r') as f: line = f.readlines() try: job_id = int(line[0]) except: job_id = None else: job_id = None if job_id_exists(job_id) == True: # if the job is running, then pass pass elif check_job_type(bs_dir) == 'VASP' and os.path.exists(outcar_path) and os.path.isfile(outcar_path) and vasp_tools.vasp_job_finished(outcar_path, suppress_warning = True) == True: pass else: # copy A B src_dir = scf_dir dst_dir = bs_dir for i_file_name in ['CHGCAR', 'WAVECAR', 'CONTCAR', 'KPOINTS', 'POTCAR']: src_file_name = i_file_name dst_file_name = i_file_name if i_file_name == 'CONTCAR': src_file_name = 'CONTCAR' dst_file_name = 'POSCAR' dst_file_path = os.path.join(dst_dir, dst_file_name) if os.path.exists(src_dir) and not os.path.isfile(src_dir): src_file_path = os.path.join(src_dir, src_file_name) if os.path.exists(src_file_path) and os.path.isfile(src_file_path): funcs.cp(src_file_path, dst_file_path) # prepare INCAR incar_dict = {} incar_dict['SYSTEM'] = 'bs' incar_dict['ISTART'] = 0 incar_dict['ENCUT'] = 500 incar_dict['EDIFF'] = 1E-06 incar_dict['EDIFFG'] = -1E-02 incar_dict['PREC'] = 'Accurate' incar_dict['IBRION'] = -1 incar_dict['NSW'] = 0 incar_dict['ISIF'] = 3 incar_dict['POTIM'] = 0.5 incar_dict['ALGO'] = 'Normal' incar_dict['ISMEAR'] = 0 incar_dict['SIGMA'] = 0.05 incar_dict['LREAL'] = '.FALSE.' incar_dict['ISPIN'] = 2 incar_dict['NELM'] = 200 incar_dict['NELMIN'] = 6 incar_dict['ICHARG'] = 11 incar_dict['LWAVE'] = '.FALSE.' incar_dict['LCHARG'] = '.TRUE.' incar_dict['NPAR'] = 4 incar_dict['LORBIT'] = 11 incar_dict['NBANDS'] = 16 incar_dict['AMIX'] = 0.1 incar_file_path = os.path.join(bs_dir, 'INCAR') vasp_write.write_incar(incar_file_path, incar_dict = incar_dict, mode = 'w') # modify ENCUT incar_dict_opt = vasp_read.read_incar(os.path.join(opt_dir, 'INCAR')) incar_dict_temp = {} incar_dict_temp['ENCUT'] = incar_dict_opt['ENCUT'] vasp_write.write_incar(incar_file_path, incar_dict = incar_dict_temp, mode = 's') # set default LREAL according to pseudo.F in the VASP source code if incar_dict['LREAL'] in ['.FALSE.', '.F.'] and poscar_dict['n_atoms'] > 16: recommended_lreal_val = 'Auto' vasp_write.write_incar(incar_file_path, incar_dict = {'LREAL': recommended_lreal_val}, mode = 's') elif incar_dict['LREAL'] in ['.TRUE.', '.T.', 'On', 'O', 'Auto', 'A'] and poscar_dict['n_atoms'] < 8: recommended_lreal_val = '.FALSE.' vasp_write.write_incar(incar_file_path, incar_dict = {'LREAL': recommended_lreal_val}, mode = 's') # modify MAGMOM incar_dict_temp = {} magmom = '' transition_metal_list = ['Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg',] if os.path.exists(bs_poscar_file_path) and os.path.isfile(bs_poscar_file_path): # in case the POSCAR in the scf folder is empty, we use the POSCAR from opt directory poscar_dict = vasp_read.read_poscar(opt_poscar_file_path) magmom = '' for i_indx in range(0, len(poscar_dict['elmt_species_arr'])): i_elmt = poscar_dict['elmt_species_arr'][i_indx] i_elmt_num = poscar_dict['elmt_num_arr'][i_indx] if i_elmt in transition_metal_list: magmom = magmom + str(i_elmt_num) + '*5.0 ' else: magmom = magmom + str(i_elmt_num) + '*0.6 ' incar_dict_temp['MAGMOM'] = magmom vasp_write.write_incar(incar_file_path, incar_dict = incar_dict_temp, mode = 's') # modify NBANDS outcar_path_scf = os.path.join(scf_dir, 'OUTCAR') nbands_scf = None if os.path.exists(outcar_path_scf) and os.path.isfile(outcar_path_scf): outcar_params_dict_scf = vasp_read.read_outcar(outcar_path_scf) nbands_scf = outcar_params_dict_scf['NBANDS'] if nbands_scf in [None, 'None', 'none']: pass else: incar_dict_temp['NBANDS'] = nbands_scf vasp_write.write_incar(incar_file_path, incar_dict = incar_dict_temp, mode = 's') # generate KPATH if os.path.exists(bs_poscar_file_path): vacuum_in_xyz = vasp_tools.get_vacuum_status(bs_poscar_file_path) if not any(vacuum_in_xyz): # 3D kpoint gen_kpath(fpath = bs_dir, kpath_scheme = kpath_scheme, kpath_params = kpath_params) else: # 2D kpoint kpath_params = '''echo 3 ; echo 302 | vaspkit''' gen_kpath(fpath = bs_dir, kpath_scheme = kpath_scheme, kpath_params = kpath_params) ############################ # bs_soc ############################ outcar_path = os.path.join(bs_soc_dir, 'OUTCAR') bs_soc_poscar_file_path = os.path.join(bs_soc_dir, 'POSCAR') # when the job is running, or it has been finished, it will be skipped job_id_file_path = os.path.join(bs_soc_dir, job_id_file_name) if os.path.exists(job_id_file_path): with open(job_id_file_path, 'r') as f: line = f.readlines() try: job_id = int(line[0]) except: job_id = None else: job_id = None if job_id_exists(job_id) == True: # if the job is running, then pass pass elif check_job_type(bs_soc_dir) == 'VASP' and os.path.exists(outcar_path) and os.path.isfile(outcar_path) and vasp_tools.vasp_job_finished(outcar_path, suppress_warning = True) == True: pass else: # copy A B src_dir = scf_dir dst_dir = bs_soc_dir for i_file_name in ['CHGCAR', 'WAVECAR', 'CONTCAR', 'KPOINTS', 'POTCAR']: src_file_name = i_file_name dst_file_name = i_file_name if i_file_name == 'CONTCAR': src_file_name = 'CONTCAR' dst_file_name = 'POSCAR' dst_file_path = os.path.join(dst_dir, dst_file_name) if os.path.exists(src_dir) and not os.path.isfile(src_dir): src_file_path = os.path.join(src_dir, src_file_name) if os.path.exists(src_file_path) and os.path.isfile(src_file_path): funcs.cp(src_file_path, dst_file_path) # prepare INCAR incar_dict = {} incar_dict['SYSTEM'] = 'bs_soc' incar_dict['ISTART'] = 0 incar_dict['ENCUT'] = 500 incar_dict['EDIFF'] = 1E-06 incar_dict['EDIFFG'] = -1E-02 incar_dict['PREC'] = 'Accurate' incar_dict['IBRION'] = -1 incar_dict['NSW'] = 0 incar_dict['ISIF'] = 3 incar_dict['POTIM'] = 0.5 incar_dict['ALGO'] = 'Normal' incar_dict['ISMEAR'] = 0 incar_dict['SIGMA'] = 0.05 incar_dict['LREAL'] = '.FALSE.' incar_dict['ISPIN'] = 2 incar_dict['NELM'] = 200 incar_dict['NELMIN'] = 6 incar_dict['ICHARG'] = 11 incar_dict['LWAVE'] = '.FALSE.' incar_dict['LCHARG'] = '.TRUE.' incar_dict['NPAR'] = 4 incar_dict['AMIX'] = 0.1 incar_dict['LORBIT'] = 11 incar_dict['LSORBIT'] = '.TRUE.' incar_dict['LMAXMIX'] = 2 incar_dict['SAXIS'] = '0 0 1' incar_dict['NBANDS'] = 32 incar_dict['GGA_COMPAT'] = '.FALSE.' incar_file_path = os.path.join(bs_soc_dir, 'INCAR') vasp_write.write_incar(incar_file_path, incar_dict = incar_dict, mode = 'w') # modify ENCUT incar_dict_opt = vasp_read.read_incar(os.path.join(opt_dir, 'INCAR')) incar_dict_temp = {} incar_dict_temp['ENCUT'] = incar_dict_opt['ENCUT'] vasp_write.write_incar(incar_file_path, incar_dict = incar_dict_temp, mode = 's') # set default LREAL according to pseudo.F in the VASP source code if incar_dict['LREAL'] in ['.FALSE.', '.F.'] and poscar_dict['n_atoms'] > 16: recommended_lreal_val = 'Auto' vasp_write.write_incar(incar_file_path, incar_dict = {'LREAL': recommended_lreal_val}, mode = 's') elif incar_dict['LREAL'] in ['.TRUE.', '.T.', 'On', 'O', 'Auto', 'A'] and poscar_dict['n_atoms'] < 8: recommended_lreal_val = '.FALSE.' vasp_write.write_incar(incar_file_path, incar_dict = {'LREAL': recommended_lreal_val}, mode = 's') # modify MAGMOM incar_dict_temp = {} magmom = '' transition_metal_list = ['Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg',] if os.path.exists(bs_soc_poscar_file_path) and os.path.isfile(bs_soc_poscar_file_path): # in case the POSCAR in the scf folder is empty, we use the POSCAR from opt directory poscar_dict = vasp_read.read_poscar(opt_poscar_file_path) magmom = '' for i_indx in range(0, len(poscar_dict['elmt_species_arr'])): i_elmt = poscar_dict['elmt_species_arr'][i_indx] i_elmt_num = poscar_dict['elmt_num_arr'][i_indx] for j_indx in range(0, i_elmt_num): if i_elmt in transition_metal_list: magmom = magmom + '0 0 5.0 ' else: magmom = magmom + '0 0 0.6 ' incar_dict_temp['MAGMOM'] = magmom vasp_write.write_incar(incar_file_path, incar_dict = incar_dict_temp, mode = 's') # modify NBANDS outcar_path_bs = os.path.join(bs_dir, 'OUTCAR') ##nbands_bs = None ##if os.path.exists(outcar_path_bs) and os.path.isfile(outcar_path_bs): ## outcar_params_dict_bs = vasp_read.read_outcar(outcar_path_bs) ## nbands_bs = outcar_params_dict_bs['NBANDS'] ##if nbands_bs in [None, 'None', 'none']: ## pass ##else: ## incar_dict_temp['NBANDS'] = int(nbands_bs * 2) ## vasp_write.write_incar(incar_file_path, incar_dict = incar_dict_temp, mode = 's') outcar_path_scf = os.path.join(scf_dir, 'OUTCAR') nbands_scf = None if os.path.exists(outcar_path_scf) and os.path.isfile(outcar_path_scf): outcar_params_dict_scf = vasp_read.read_outcar(outcar_path_scf) nbands_scf = outcar_params_dict_scf['NBANDS'] if nbands_scf in [None, 'None', 'none']: pass else: incar_dict_temp['NBANDS'] = int(nbands_scf * 2) vasp_write.write_incar(incar_file_path, incar_dict = incar_dict_temp, mode = 's') # generate KPATH if os.path.exists(bs_soc_poscar_file_path): vacuum_in_xyz = vasp_tools.get_vacuum_status(bs_soc_poscar_file_path) if not any(vacuum_in_xyz): # 3D kpoint gen_kpath(fpath = bs_dir, kpath_scheme = kpath_scheme, kpath_params = kpath_params) else: # 2D kpoint kpath_params = '''echo 3 ; echo 302 | vaspkit''' gen_kpath(fpath = bs_dir, kpath_scheme = kpath_scheme, kpath_params = kpath_params) ############################ # dos ############################ outcar_path = os.path.join(dos_dir, 'OUTCAR') dos_poscar_file_path = os.path.join(dos_dir, 'POSCAR') # when the job is running, or it has been finished, it will be skipped job_id_file_path = os.path.join(dos_dir, job_id_file_name) if os.path.exists(job_id_file_path): with open(job_id_file_path, 'r') as f: line = f.readlines() try: job_id = int(line[0]) except: job_id = None else: job_id = None if job_id_exists(job_id) == True: # if the job is running, then pass pass elif check_job_type(dos_dir) == 'VASP' and os.path.exists(outcar_path) and os.path.isfile(outcar_path) and vasp_tools.vasp_job_finished(outcar_path, suppress_warning = True) == True: pass else: # copy A B src_dir = scf_dir dst_dir = dos_dir for i_file_name in ['CHGCAR', 'WAVECAR', 'CONTCAR', 'KPOINTS', 'POTCAR']: src_file_name = i_file_name dst_file_name = i_file_name if i_file_name == 'CONTCAR': src_file_name = 'CONTCAR' dst_file_name = 'POSCAR' dst_file_path = os.path.join(dst_dir, dst_file_name) if os.path.exists(src_dir) and not os.path.isfile(src_dir): src_file_path = os.path.join(src_dir, src_file_name) if os.path.exists(src_file_path) and os.path.isfile(src_file_path): funcs.cp(src_file_path, dst_file_path) # prepare INCAR incar_dict = {} incar_dict['SYSTEM'] = 'dos' incar_dict['ISTART'] = 1 incar_dict['ENCUT'] = 500 incar_dict['EDIFF'] = 1E-06 incar_dict['EDIFFG'] = -1E-02 incar_dict['PREC'] = 'Accurate' incar_dict['IBRION'] = -1 incar_dict['NSW'] = 0 incar_dict['ISIF'] = 3 incar_dict['POTIM'] = 0.5 incar_dict['ALGO'] = 'Normal' incar_dict['ISMEAR'] = -5 incar_dict['SIGMA'] = 0.05 incar_dict['LREAL'] = '.FALSE.' incar_dict['ISPIN'] = 2 incar_dict['NELM'] = 200 incar_dict['NELMIN'] = 6 incar_dict['ICHARG'] = 11 incar_dict['LWAVE'] = '.FALSE.' incar_dict['LCHARG'] = '.FALSE.' incar_dict['NPAR'] = 4 incar_dict['AMIX'] = 0.1 incar_dict['LORBIT'] = 11 incar_dict['NEDOS'] = 501 incar_file_path = os.path.join(dos_dir, 'INCAR') vasp_write.write_incar(incar_file_path, incar_dict = incar_dict, mode = 'w') # modify ENCUT incar_dict_opt = vasp_read.read_incar(os.path.join(opt_dir, 'INCAR')) incar_dict_temp = {} incar_dict_temp['ENCUT'] = incar_dict_opt['ENCUT'] vasp_write.write_incar(incar_file_path, incar_dict = incar_dict_temp, mode = 's') # set default LREAL according to pseudo.F in the VASP source code if incar_dict['LREAL'] in ['.FALSE.', '.F.'] and poscar_dict['n_atoms'] > 16: recommended_lreal_val = 'Auto' vasp_write.write_incar(incar_file_path, incar_dict = {'LREAL': recommended_lreal_val}, mode = 's') elif incar_dict['LREAL'] in ['.TRUE.', '.T.', 'On', 'O', 'Auto', 'A'] and poscar_dict['n_atoms'] < 8: recommended_lreal_val = '.FALSE.' vasp_write.write_incar(incar_file_path, incar_dict = {'LREAL': recommended_lreal_val}, mode = 's') # modify MAGMOM incar_dict_temp = {} magmom = '' transition_metal_list = ['Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg',] if os.path.exists(dos_poscar_file_path) and os.path.isfile(dos_poscar_file_path): # in case the POSCAR in the scf folder is empty, we use the POSCAR from opt directory poscar_dict = vasp_read.read_poscar(opt_poscar_file_path) magmom = '' for i_indx in range(0, len(poscar_dict['elmt_species_arr'])): i_elmt = poscar_dict['elmt_species_arr'][i_indx] i_elmt_num = poscar_dict['elmt_num_arr'][i_indx] if i_elmt in transition_metal_list: magmom = magmom + str(i_elmt_num) + '*5.0 ' else: magmom = magmom + str(i_elmt_num) + '*0.6 ' incar_dict_temp['MAGMOM'] = magmom vasp_write.write_incar(incar_file_path, incar_dict = incar_dict_temp, mode = 's') # modify the KPOINTS kpoints_dict = vasp_read.read_kpoints(os.path.join(opt_dir, 'KPOINTS')) if kpoints_dict['scheme'] in ['g', 'G', 'm', 'M']: #subdivisions_arr = (kpoints_dict['subdivisions_arr'] * 2) + 3 subdivisions_arr = (kpoints_dict['subdivisions_arr'] + 2) if os.path.exists(opt_poscar_file_path): vacuum_in_xyz = vasp_tools.get_vacuum_status(opt_poscar_file_path) if vacuum_in_xyz[0] == True: subdivisions_arr[0] = num_kpt_in_vacuum_direction elif vacuum_in_xyz[1] == True: subdivisions_arr[1] = num_kpt_in_vacuum_direction elif vacuum_in_xyz[2] == True: subdivisions_arr[2] = num_kpt_in_vacuum_direction kpoints_dict_temp = {} kpoints_dict_temp['subdivisions_arr'] = subdivisions_arr vasp_write.write_kpoints(os.path.join(dos_dir, 'KPOINTS'), kpoints_dict = kpoints_dict_temp, mode = 's') ############################ # nscf ############################ outcar_path = os.path.join(nscf_dir, 'OUTCAR') nscf_poscar_file_path = os.path.join(nscf_dir, 'POSCAR') # when the job is running, or it has been finished, it will be skipped job_id_file_path = os.path.join(nscf_dir, job_id_file_name) if os.path.exists(job_id_file_path): with open(job_id_file_path, 'r') as f: line = f.readlines() try: job_id = int(line[0]) except: job_id = None else: job_id = None if job_id_exists(job_id) == True: # if the job is running, then pass pass elif check_job_type(nscf_dir) == 'VASP' and os.path.exists(outcar_path) and os.path.isfile(outcar_path) and vasp_tools.vasp_job_finished(outcar_path, suppress_warning = True) == True: pass else: # copy A B src_dir = scf_dir dst_dir = nscf_dir for i_file_name in ['CHGCAR', 'WAVECAR', 'CONTCAR', 'KPOINTS', 'POTCAR']: src_file_name = i_file_name dst_file_name = i_file_name if i_file_name == 'CONTCAR': src_file_name = 'CONTCAR' dst_file_name = 'POSCAR' dst_file_path = os.path.join(dst_dir, dst_file_name) if os.path.exists(src_dir) and not os.path.isfile(src_dir): src_file_path = os.path.join(src_dir, src_file_name) if os.path.exists(src_file_path) and os.path.isfile(src_file_path): funcs.cp(src_file_path, dst_file_path) # prepare INCAR incar_dict = {} incar_dict['SYSTEM'] = 'nscf' incar_dict['ISTART'] = 1 incar_dict['ENCUT'] = 500 incar_dict['EDIFF'] = 1E-06 incar_dict['EDIFFG'] = -1E-02 incar_dict['PREC'] = 'Accurate' incar_dict['IBRION'] = -1 incar_dict['NSW'] = 0 incar_dict['ISIF'] = 3 incar_dict['POTIM'] = 0.5 incar_dict['ALGO'] = 'Normal' incar_dict['ISMEAR'] = 0 incar_dict['SIGMA'] = 0.05 incar_dict['LREAL'] = '.FALSE.' incar_dict['ISPIN'] = 2 incar_dict['NELM'] = 0 incar_dict['ICHARG'] = 12 incar_dict['LWAVE'] = '.FALSE.' incar_dict['LCHARG'] = '.TRUE.' incar_dict['NPAR'] = 4 incar_dict['AMIX'] = 0.1 incar_file_path = os.path.join(nscf_dir, 'INCAR') vasp_write.write_incar(incar_file_path, incar_dict = incar_dict, mode = 'w') # modify ENCUT incar_dict_opt = vasp_read.read_incar(os.path.join(opt_dir, 'INCAR')) incar_dict_temp = {} incar_dict_temp['ENCUT'] = incar_dict_opt['ENCUT'] vasp_write.write_incar(incar_file_path, incar_dict = incar_dict_temp, mode = 's') # set default LREAL according to pseudo.F in the VASP source code if incar_dict['LREAL'] in ['.FALSE.', '.F.'] and poscar_dict['n_atoms'] > 16: recommended_lreal_val = 'Auto' vasp_write.write_incar(incar_file_path, incar_dict = {'LREAL': recommended_lreal_val}, mode = 's') elif incar_dict['LREAL'] in ['.TRUE.', '.T.', 'On', 'O', 'Auto', 'A'] and poscar_dict['n_atoms'] < 8: recommended_lreal_val = '.FALSE.' vasp_write.write_incar(incar_file_path, incar_dict = {'LREAL': recommended_lreal_val}, mode = 's') # modify MAGMOM incar_dict_temp = {} magmom = '' transition_metal_list = ['Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg',] if os.path.exists(nscf_poscar_file_path) and os.path.isfile(nscf_poscar_file_path): # in case the POSCAR in the scf folder is empty, we use the POSCAR from opt directory poscar_dict = vasp_read.read_poscar(opt_poscar_file_path) magmom = '' for i_indx in range(0, len(poscar_dict['elmt_species_arr'])): i_elmt = poscar_dict['elmt_species_arr'][i_indx] i_elmt_num = poscar_dict['elmt_num_arr'][i_indx] if i_elmt in transition_metal_list: magmom = magmom + str(i_elmt_num) + '*5.0 ' else: magmom = magmom + str(i_elmt_num) + '*0.6 ' incar_dict_temp['MAGMOM'] = magmom vasp_write.write_incar(incar_file_path, incar_dict = incar_dict_temp, mode = 's') return 0 def params_test(job_dir, variant_name = '$i', variant_value_list = None): ''' For the files in the job_dir, this function substitute the keyword "$i" with the values of the "variant_value_list" and generate test jobs. job_dir: the directory of the calculation job. variant_value_list: a list of the variant values. ''' args_dict = locals() import os from .. import funcs from .. import default_params defaults_dict = default_params.default_params() logfile = defaults_dict['logfile'] output_dir = os.path.join(os.getcwd(), defaults_dict['output_dir_name']) ##projects_dir = os.path.join(output_dir, defaults_dict['projects_dir_name']) ##funcs.mkdir(projects_dir) funcs.mkdir(output_dir) job_dir = os.path.abspath(job_dir) flist = funcs.get_files(job_dir, extension = None) files_list = flist[0] file_name_list = flist[1] ## temp_list = [] ## for i_file in files_list: ## if i_file.split('.')[-1] in ['png', 'eps', 'pdf', 'tif', 'tiff', 'jpg', 'jpeg', 'svg', 'svgz', 'pgf', 'ps', 'raw', 'rgba']: ## # ignore the files that is not ASCII format to avoid file reading error ## pass ## else: ## temp_list.append(i_file) ## files_list = temp_list #test_dir_name = defaults_dict['test_dir_name'] #funcs.mkdir(os.path.join(output_dir,test_dir_name)) for i in range(0, len(variant_value_list)): #new_dir = os.path.join(output_dir, test_dir_name, str(variant_value_list[i])) #funcs.mkdir(new_dir) new_dir = os.path.join(job_dir, str(variant_value_list[i])) funcs.mkdir(new_dir) for j in range(0, len(files_list)): dest_file = os.path.join(new_dir, file_name_list[j]) try: funcs.cp(files_list[j], dest_file) funcs.replace_file_content(dest_file, variant_name, str(variant_value_list[i])) except: pass ################################## # Determine the args string ################################## log_str = '' func_name = 'task_manager.params_test' args_str = func_name + '(' + '\n' for i_arg in args_dict.keys(): arg_value = args_dict[i_arg] if isinstance(arg_value,str): arg_value_str = '\'' + arg_value + '\'' else: arg_value_str = str(arg_value) if i_arg == 'job_dir': arg_value_str = 'r\'' + job_dir + '\'' if i_arg == 'variant_name': arg_value_str = '\'' + variant_name + '\'' args_str += ' ' + i_arg + ' = ' + arg_value_str + ',\n' args_str += ' )\n' args_str += '################################################\n' log_str += args_str funcs.write_log(logfile, log_str) return 0 def get_recommended_test_param(test_dir, fit_order = 6, plot_fitted_curve = True, suppress_warning = True): ''' test_dir: the directory of the parameter test jobs. ''' args_dict = locals() import os from .. import funcs from .. import default_params import scipy.optimize as opt import numpy as np from ..vasp import vasp_read from ..vasp import vasp_analyze use_plt = True try: import matplotlib.pyplot as plt except: use_plt = False defaults_dict = default_params.default_params() logfile = defaults_dict['logfile'] output_dir = os.path.join(os.getcwd(), defaults_dict['output_dir_name']) ##projects_dir = os.path.join(output_dir, defaults_dict['projects_dir_name']) ##funcs.mkdir(projects_dir) funcs.mkdir(output_dir) general_params_dict = {} if use_plt == True: general_params_dict['marker_size'] = 10.0 general_params_dict['line_width'] = 2.0 general_params_dict['fig_format'] = 'png' general_params_dict['fig_dpi'] = 300 general_params_dict['fig_size'] = [15, 10] general_params_dict['font_size'] = 18 plt.rcParams['figure.figsize'] = (general_params_dict['fig_size'][0],general_params_dict['fig_size'][1]) test_dir = os.path.abspath(test_dir) dir_list = [os.path.join(test_dir, x) for x in sorted([x for x in os.listdir(test_dir) if os.path.isdir(os.path.join(test_dir, x))])] dir_name_list = sorted([x for x in os.listdir(test_dir) if os.path.isdir(os.path.join(test_dir, x))]) energy_list = [] params_list = [] for i in range(0, len(dir_list)): outcar_path = os.path.join(dir_list[i], 'OUTCAR') if funcs.file_status(outcar_path, suppress_warning = True) == 1 and vasp_tools.vasp_job_finished(outcar_path, suppress_warning = True): outcar_params_dict = vasp_read.read_outcar(outcar_path) energy_list.append(outcar_params_dict['energy(sigma->0)']) params_list.append(dir_name_list[i]) else: if suppress_warning == False: print('WARNING #2012271608 (from get_recommended_test_param): ' + outcar_path + ' dose not exist or is empty or the VASP job has not been finished!') energy_arr = np.array(energy_list, dtype = float) params_arr = np.array(params_list, dtype = float) recommended_param_val = None if len(params_arr) == 0: recommended_param_val = 0 else: ############################################################# # determine the optimum parameter # fit the data and get the point with zero second derivative ############################################################# #fit_order = 6 coeffs = np.polyfit(params_arr, energy_arr, fit_order) ffit = np.poly1d(coeffs) params_dense_arr = np.linspace(min(params_arr), max(params_arr), num = 100, endpoint = True) ffit_dense = ffit(params_dense_arr) if use_plt == True: fig_file = os.path.join(test_dir, 'E_param_relation.' + general_params_dict['fig_format']) plt.title('E-param relation', fontsize = general_params_dict['font_size']) if plot_fitted_curve == True: plt.plot(params_dense_arr, ffit_dense, linestyle = '-', color = 'black', linewidth = general_params_dict['line_width'], markersize = general_params_dict['marker_size']) plt.plot(params_arr, energy_arr, linestyle = '', marker = '.', color = 'black', linewidth = general_params_dict['line_width'], markersize = general_params_dict['marker_size']) plt.xlabel('param', fontsize = general_params_dict['font_size']) plt.ylabel('E (eV)', fontsize = general_params_dict['font_size']) plt.xticks(fontsize=general_params_dict['font_size']) plt.yticks(fontsize=general_params_dict['font_size']) ##plt.show() plt.savefig(fig_file, dpi = general_params_dict['fig_dpi']) plt.close() else: pass #derivative fderiv = ffit.deriv() #first derivative fderiv_n = ffit.deriv(1) #nth derivative, either n=1 or n=2 would give good results, I choose n=1 here fderiv_arr = fderiv(params_arr) fderiv_dense = fderiv(params_dense_arr) if use_plt == True: fig_file = os.path.join(test_dir, 'E_derivative_param_relation.' + general_params_dict['fig_format']) plt.title('dE/d(param)-param relation', fontsize = general_params_dict['font_size']) if plot_fitted_curve == True: plt.plot(params_dense_arr, fderiv_dense, linestyle = '-', color = 'black', linewidth = general_params_dict['line_width'], markersize = general_params_dict['marker_size']) plt.plot(params_arr, fderiv_arr, linestyle = '', marker = '.', color = 'black', linewidth = general_params_dict['line_width'], markersize = general_params_dict['marker_size']) plt.xlabel('param', fontsize = general_params_dict['font_size']) plt.ylabel('E\' (eV)', fontsize = general_params_dict['font_size']) plt.xticks(fontsize=general_params_dict['font_size']) plt.yticks(fontsize=general_params_dict['font_size']) ##plt.show() plt.savefig(fig_file, dpi = general_params_dict['fig_dpi']) plt.close() else: pass #https://stackoverflow.com/questions/29634217/get-minimum-points-of-numpy-poly1d-curve crit = fderiv_n.r r_crit = crit[crit.imag==0].real ##print('r_crit=', r_crit) ##fderiv_n_val = fderiv_n(r_crit) ##print('fderiv_n_val=', test) #determine the optimum paramter sorted_r_crit = sorted(r_crit) num_r_crit = len(sorted_r_crit) if num_r_crit == 0: print('WARNING #2012271609 (from get_recommended_test_param): No optimum parameter is found.') recommended_param_val = params_arr[-1] elif num_r_crit == 1: recommended_param_val = sorted_r_crit[0] elif num_r_crit > 1 and num_r_crit < 3: # Among the zero second derivative pionts, choose the second smallest piont recommended_param_val = sorted_r_crit[1] elif num_r_crit >= 3: # Among the zero second derivative pionts, choose the second smallest piont recommended_param_val = sorted_r_crit[2] # find the cloest parameter point to the critical point if len(params_arr) > 1: optimum_indx = int(np.argsort(np.abs(params_arr - recommended_param_val))[1]) recommended_param_val = params_arr[optimum_indx] elif len(params_arr) == 1: optimum_indx = int(np.argsort(np.abs(params_arr - recommended_param_val))[0]) recommended_param_val = params_arr[optimum_indx] ##print('recommended parameter = ', recommended_param_val) # write test.log funcs.touch(os.path.join(test_dir, 'test.log')) with open(os.path.join(test_dir, 'test.log'), 'w') as f: f.write(str(recommended_param_val)) return recommended_param_val def latt_const_test(job_dir, model_dimension = 2, increment = 0.005, num_points = 5, latt_const_list = None): ''' For the files in the job_dir, this function modifies the POSCAR generates test jobs. job_dir: the directory of the calculation job. model_dimension: dimension of the model. 1 for chain, 2 for slab, 3 for bulk. increment: the increment of the lattice constant, units in percentage/100. num_points: the number of scaled systems (including the original one). latt_const_list: a list of the lattice constant. If this list is provided, the increment tag is omitted. ''' args_dict = locals() import os import numpy as np from .. import funcs from .. import default_params from ..vasp import vasp_read from ..vasp import vasp_write defaults_dict = default_params.default_params() logfile = defaults_dict['logfile'] #output_dir = os.path.join(os.getcwd(), defaults_dict['output_dir_name']) ##projects_dir = os.path.join(output_dir, defaults_dict['projects_dir_name']) ##funcs.mkdir(projects_dir) #funcs.mkdir(output_dir) job_dir = os.path.abspath(job_dir) files_list, file_name_list = funcs.get_files(job_dir, extension = None) work_last_dir = os.path.join(job_dir, '..') latt_const_test_dir = os.path.join(work_last_dir, 'latt_const_test') funcs.mkdir(latt_const_test_dir) poscar_file_path = os.path.join(job_dir, 'POSCAR') poscar_dict = vasp_read.read_poscar(poscar_file_path) if model_dimension == 2: indx_list = [0] scale_fac_list = [] if (num_points % 2) != 0: up_bound = (num_points - 1) / 2 elif (num_points % 2) == 0: up_bound = num_points / 2 for i in range(0, up_bound): indx_list.append(i+1) indx_list.append(-(i+1)) for i_point in range(0, num_points): scale_fac_list.append(1 + increment * indx_list[i_point]) for i_scale_fac in scale_fac_list: box_len_arr = poscar_dict['box_len_arr'] len_vec1 = np.linalg.norm([box_len_arr[0,0], box_len_arr[0,1], box_len_arr[0,2]]) len_vec2 = np.linalg.norm([box_len_arr[1,0], box_len_arr[1,1], box_len_arr[1,2]]) len_vec3 = np.linalg.norm([box_len_arr[2,0], box_len_arr[2,1], box_len_arr[2,2]]) #find the axis with the longest length len_vec_list = [len_vec1, len_vec2, len_vec3] max_len_axis_indx = len_vec_list.index(max(len_vec_list)) if max_len_axis_indx == 0: box_len_arr[1,:] = box_len_arr[1,:] * i_scale_fac box_len_arr[2,:] = box_len_arr[2,:] * i_scale_fac elif max_len_axis_indx == 1: box_len_arr[0,:] = box_len_arr[0,:] * i_scale_fac box_len_arr[2,:] = box_len_arr[2,:] * i_scale_fac elif max_len_axis_indx == 2: box_len_arr[0,:] = box_len_arr[0,:] * i_scale_fac box_len_arr[1,:] = box_len_arr[1,:] * i_scale_fac vec1_str = ' '.join([str(x) for x in box_len_arr[0,:]]) + '\n' vec2_str = ' '.join([str(x) for x in box_len_arr[1,:]]) + '\n' vec3_str = ' '.join([str(x) for x in box_len_arr[2,:]]) + '\n' poscar_dict['header'][2] = vec1_str poscar_dict['header'][3] = vec2_str poscar_dict['header'][4] = vec3_str if max_len_axis_indx == 0: poscar_dict['coord_arr'][:,0] = poscar_dict['coord_arr'][:,0] * i_scale_fac elif max_len_axis_indx == 1: poscar_dict['coord_arr'][:,1] = poscar_dict['coord_arr'][:,1] * i_scale_fac elif max_len_axis_indx == 2: poscar_dict['coord_arr'][:,2] = poscar_dict['coord_arr'][:,2] * i_scale_fac incar_dict= {} incar_dict['ISIF'] = 4 new_dir = os.path.join(latt_const_test_dir, str(i_scale_fac)) new_poscar_file_path = os.path.join(new_dir, 'POSCAR') new_incar_file_path = os.path.join(new_dir, 'INCAR') funcs.mkdir(new_dir) for j in range(0, len(files_list)): dest_file = os.path.join(new_dir, file_name_list[j]) try: funcs.cp(files_list[j], dest_file) #funcs.replace_file_content(dest_file, variant_name, str(variant_value_list[i])) vasp_write.write_poscar(output_poscar_file_path = new_poscar_file_path, poscar_dict = poscar_dict) vasp_write.write_incar(incar_file_path = new_incar_file_path, incar_dict = incar_dict, mode = 's') except: pass elif model_dimension ==3: for i in range(0, len(latt_const_list)): #new_dir = os.path.join(output_dir, test_dir_name, str(variant_value_list[i])) #funcs.mkdir(new_dir) new_dir = os.path.join(job_dir, str(latt_const_list[i])) funcs.mkdir(new_dir) for j in range(0, len(files_list)): dest_file = os.path.join(new_dir, file_name_list[j]) try: funcs.cp(files_list[j], dest_file) #funcs.replace_file_content(dest_file, variant_name, str(variant_value_list[i])) except: pass ################################## # Determine the args string ################################## log_str = '' func_name = 'task_manager.latt_const_test' args_str = func_name + '(' + '\n' for i_arg in args_dict.keys(): arg_value = args_dict[i_arg] if isinstance(arg_value,str): arg_value_str = '\'' + arg_value + '\'' else: arg_value_str = str(arg_value) if i_arg == 'job_dir': arg_value_str = 'r\'' + job_dir + '\'' if i_arg == 'variant_name': arg_value_str = '\'' + variant_name + '\'' args_str += ' ' + i_arg + ' = ' + arg_value_str + ',\n' args_str += ' )\n' args_str += '################################################\n' log_str += args_str funcs.write_log(logfile, log_str) return 0 def gen_submit_script(task_dir, submit_script_path_dict = None, task_flow_list = None, queue_system = 'PBS'): ''' generate submit script for the specified task submit_script_path_dict: the keyword 'universal' must exist in submit_script_path_dict, if no submit files are provided for other calculations, the submit file in submit_script_path_dict['universal'] will be used. For example: submit_script_path_dict = {} submit_script_path_dict['universal'] = './submit_opt.sh' submit_script_path_dict['bs_soc'] = './submit_bs_soc.sh' ''' args_dict = locals() import os from .. import funcs from .. import default_params defaults_dict = default_params.default_params() logfile = defaults_dict['logfile'] output_dir = os.path.join(os.getcwd(), defaults_dict['output_dir_name']) projects_dir = os.path.join(output_dir, defaults_dict['projects_dir_name']) if task_flow_list in [None, 'None', 'none']: task_flow_list = ['opt', 'test_encut', 'test_kpoints', 'scf', 'bs', 'bs_soc', 'dos', 'nscf'] else: pass if submit_script_path_dict in [None, 'None', 'none']: submit_script_path_dict = {} submit_script_path_dict['universal'] = os.path.join(project_dir, 'submit.sh') if 'universal' not in submit_script_path_dict.keys(): print('ERROR (from gen_submit_script): The keyword universal must exist in the submit_script_path_dict') exit() else: universal_submit_script_path = os.path.abspath(submit_script_path_dict['universal']) for i_task in task_flow_list: if i_task not in submit_script_path_dict.keys(): submit_script_path_dict[i_task] = None elif i_task in submit_script_path_dict.keys() and submit_script_path_dict[i_task] in [None, 'None', 'none']: submit_script_path_dict[i_task] = os.path.abspath(submit_script_path_dict['universal']) line_dict = {} # read example submit script with open(submit_script_path_dict['universal'], 'r') as f: line_dict['universal'] = f.readlines() for i_task in task_flow_list: if submit_script_path_dict[i_task] in [None, 'None', 'none']: line_dict[i_task] = None else: with open(submit_script_path_dict[i_task], 'r') as f: line_dict[i_task] = f.readlines() # write submit script to each job submit_script_name = 'submit.sh' run_submit_script_name = 'run_submit.sh' i_task_dir = os.path.abspath(task_dir) for i_job_indx in range(0, len(task_flow_list)): i_job_dir = os.path.join(i_task_dir, task_flow_list[i_job_indx]) if 'test' in task_flow_list[i_job_indx]: subjob_name_list = [x for x in os.listdir(i_job_dir) if os.path.isdir(os.path.join(i_job_dir, x))] for i_subjob_indx in range(0, len(subjob_name_list)): i_subjob_dir = os.path.join(i_job_dir, subjob_name_list[i_subjob_indx]) submit_script_file_path = os.path.join(i_subjob_dir, submit_script_name) ##if os.path.exists(submit_script_file_path) == False: fpath, fname = funcs.file_path_name(submit_script_file_path) if os.path.exists(fpath) and os.path.isfile(fpath): os.remove(fpath) funcs.mkdir(fpath) with open(submit_script_file_path, 'w') as f: if line_dict[task_flow_list[i_job_indx]] in [None, 'None', 'none']: f.writelines(line_dict['universal']) else: f.writelines(line_dict[task_flow_list[i_job_indx]]) else: submit_script_file_path = os.path.join(i_job_dir, submit_script_name) ##if os.path.exists(submit_script_file_path) == False: fpath, fname = funcs.file_path_name(submit_script_file_path) if os.path.exists(fpath) and os.path.isfile(fpath): os.remove(fpat) funcs.mkdir(fpath) with open(submit_script_file_path, 'w') as f: if line_dict[task_flow_list[i_job_indx]] in [None, 'None', 'none']: f.writelines(line_dict['universal']) else: f.writelines(line_dict[task_flow_list[i_job_indx]]) return 0 def job_id_exists(job_id, queue_system = 'PBS'): '''Check whether the job ID exists or not''' args_dict = locals() import os from .. import funcs from .. import default_params defaults_dict = default_params.default_params() logfile = defaults_dict['logfile'] output_dir = os.path.join(os.getcwd(), defaults_dict['output_dir_name']) if isinstance(job_id, int) == True: job_id = int(job_id) job_id_log_file_name = 'job_id.log' job_id_log_file_path = os.path.join(output_dir, job_id_log_file_name) funcs.touch(job_id_log_file_path) if queue_system == 'PBS': os.system('qstat -r ' + ' | grep ' + str(job_id) + ' > ' + job_id_log_file_path) ##print('qstat -r ' + ' | grep ' + str(job_id) + ' > ' + job_id_log_file_path) with open(job_id_log_file_path, 'r') as f: line = f.readlines() num_lines = len(line) if num_lines == 0: id_exists = False elif num_lines == 1: id_exists = True else: id_exists = False ##print('job ' + str(job_id) + ' exists? ' + str(id_exists)) return id_exists def job_submission_status(job_dir, job_kwd = 'R', queue_system = 'PBS'): ''' Check the submission status status of a job, only consider those unfinished jobs job_dir: directory of the job job_kwd: user-defined job identifier queue_system: PBS, SLURM, LSF ''' args_dict = locals() import os from .. import funcs from .. import default_params from ..vasp import vasp_tools defaults_dict = default_params.default_params() logfile = defaults_dict['logfile'] output_dir = os.path.join(os.getcwd(), defaults_dict['output_dir_name']) ####################################################################################################### # get submitted(including running, queued, held or waiting jobs) job file paths and put them in a list ####################################################################################################### job_dir = os.path.abspath(job_dir) fpath = job_dir pwd_dir = os.getcwd() temp_file_path = os.path.join(fpath, 'temp.sh') temp_log_path = os.path.join(fpath, 'temp.log') if queue_system == 'PBS': with open(temp_file_path, 'w') as f: f.write('#!/bin/bash\n') f.write('cd ' + fpath + '\n') temp_str = '''cp /dev/null temp.log n=1 ##output_kwd1='Output_Path' ##output_kwd2='Priority' output_kwd1='PBS_O_WORKDIR' output_kwd2='PBS_O_HOST' ntot=`{ qstat -r & qstat -i; } | grep $1 | awk 'END{print NR}'` for i in `{ qstat -r & qstat -i; } | grep $1 | awk '{print $1}'` do n1=`qstat -f $i | awk "/$output_kwd1/{print NR}"` n2=`qstat -f $i | awk "/$output_kwd2/{print NR}"` a=$(($n2-$n1-1)) temp_dir=$(echo `qstat -f $i | grep -A $a "$output_kwd1"` | tr -d '[:space:]' | sed "s/$output_kwd1=//g" | sed 's/, *$//') echo $temp_dir >> temp.log n=$(($n+1)) done''' f.write(temp_str + '\n') f.write('cd ' + pwd_dir + '\n') os.system('sh ' + temp_file_path + ' ' + job_kwd) submitted_job_list = [] if os.path.exists(temp_log_path) and os.path.isfile(temp_log_path): with open(temp_log_path, 'r') as f: lines = f.readlines() num_lines = len(lines) for i in range(0, num_lines): submitted_job_list.append(lines[i].strip().strip('\n').strip('r')) os.remove(temp_file_path) os.remove(temp_log_path) ################################################### # Check whether the job has been submitted ################################################### submission_status = False outcar_file_path = os.path.join(job_dir, 'OUTCAR') #job_finished = vasp_tools.vasp_job_finished(outcar_file_path, suppress_warning = True) #if job_finished == False: # Check whether the job is submitted to job management system if job_dir in submitted_job_list: submission_status = True else: submission_status = False return submission_status def check_job_type(job_dir): ''' decide the task type of the directory. ''' args_dict = locals() import os job_type = 'VASP' job_dir = os.path.abspath(job_dir) file_list = os.listdir(job_dir) if job_type in ['VASP', 'Vasp', 'vasp']: job_input_file_name_list = ['INCAR', 'POSCAR', 'KPOINTS', 'POTCAR'] for i_file_str in job_input_file_name_list: if i_file_str in file_list: pass else: job_type = None else: job_type = None return job_type
#!/usr/bin/env python from os.path import basename import pandas as pd from granatum_sdk import Granatum #import numpy as np def main(): gn = Granatum() assay_file = gn.get_arg('pathToAssayFile') sample_meta_file = gn.get_arg('pathToSampleMetaFile') tb = pd.read_csv(assay_file, index_col=0) sample_ids = tb.columns.values.tolist() assay_export_name = '[A]{}'.format(basename(assay_file)) exported_assay = { 'matrix': tb.values.tolist(), 'sampleIds': sample_ids, 'geneIds': tb.index.values.tolist(), } gn.export(exported_assay, assay_export_name, 'assay') results_markdown = 'The assay has **{}** genes and **{}** samples.'.format(tb.shape[0], tb.shape[1]) results_markdown += '\n\n The first few rows and columns:' results_markdown += '\n\n```' results_markdown += '\n'.join([', '.join(x) for x in tb.values[:10, :10].astype(str).tolist()]) results_markdown += '\n```' if sample_meta_file is not None: results_markdown += '\n' sample_meta_tb = pd.read_csv(sample_meta_file) for meta_name in sample_meta_tb.columns: meta_output_name = '[M]{}'.format(meta_name) sample_meta_dict = dict(zip(sample_ids, sample_meta_tb[meta_name].values.tolist())) gn.export(sample_meta_dict, meta_output_name, 'sampleMeta') num_sample_values = 5 sample_values = ', '.join(sample_meta_tb[meta_name].astype(str).values[0:num_sample_values].tolist()) num_omitted_values = len(sample_meta_tb[meta_name]) - num_sample_values if num_omitted_values > 0: etc = ', ... and {} more entries'.format(num_omitted_values) else: etc = '' results_markdown += '\n * Sample meta with name **{}** is accepted ({}{}).'.format(meta_name, sample_values, etc) gn.add_result(results_markdown, 'markdown') #TODO: SAVE assay pickle gn.commit() if __name__ == '__main__': main()
Critical reception towards Rachel has remained consistently positive throughout Friends ' decade @-@ long run , with The A. V. Club attributing much of the show 's early success to the character . However , some of her storylines have been criticized , specifically her romantic relationship with her friend Joey during season ten . Rachel 's popularity established her as the show 's breakout character , who has since been named one of the greatest television characters of all @-@ time , while the character 's second season haircut spawned an international phenomenon of its own . Named the " Rachel " after her , the character 's shag continues to be imitated by millions of women around the world and remains one of the most popular hairstyles in history , in spite of Aniston 's own resentment towards it . Rachel is also regarded as a style icon due to her influence on womenswear during the 1990s . Meanwhile , the character 's relationship with Ross is often cited among television 's most beloved .
\<^marker>\<open>creator "Alexander Krauss"\<close> \<^marker>\<open>creator "Kevin Kappelmann"\<close> \<^marker>\<open>creator "Larry Paulson"\<close> section \<open>Union and Intersection\<close> theory Union_Intersection imports Comprehension begin definition "inter A \<equiv> {x \<in> \<Union>A | \<forall>y \<in> A. x \<in> y}" bundle hotg_inter_syntax begin notation inter ("\<Inter>_" [90] 90) end bundle no_hotg_inter_syntax begin no_notation inter ("\<Inter>_" [90] 90) end unbundle hotg_inter_syntax text \<open>Intersection is well-behaved only if the family is non-empty!\<close> lemma mem_inter_iff [iff]: "A \<in> \<Inter>C \<longleftrightarrow> C \<noteq> {} \<and> (\<forall>x \<in> C. A \<in> x)" unfolding inter_def by auto (*LP: A "destruct" rule: every B in C contains A as an element, but A \<in> B can hold when B \<in> C does not! This rule is analogous to "spec".*) lemma interD [dest]: "\<lbrakk>A \<in> \<Inter>C; B \<in> C\<rbrakk> \<Longrightarrow> A \<in> B" by auto lemma union_empty_eq [iff]: "\<Union>{} = {}" by auto lemma inter_empty_eq [iff]: "\<Inter>{} = {}" by auto lemma union_eq_empty_iff: "\<Union>A = {} \<longleftrightarrow> A = {} \<or> A = {{}}" proof assume "\<Union>A = {}" show "A = {} \<or> A = {{}}" proof (rule or_if_not_imp) assume "A \<noteq> {}" then obtain x where "x \<in> A" by auto from \<open>\<Union>A = {}\<close> have [simp]: "\<And>x. x \<in> A \<Longrightarrow> x = {}" by auto with \<open>x \<in> A\<close> have "x = {}" by simp with \<open>x \<in> A\<close> have [simp]: "{} \<in> A" by simp show "A = {{}}" by auto qed qed auto lemma union_eq_empty_iff': "\<Union>A = {} \<longleftrightarrow> (\<forall>B \<in> A. B = {})" by auto lemma union_singleton_eq [simp]: "\<Union>{b} = b" by auto lemma inter_singleton_eq [simp]: "\<Inter>{b} = b" by auto lemma subset_union_if_mem: "B \<in> A \<Longrightarrow> B \<subseteq> \<Union>A" by blast lemma inter_subset_if_mem: "B \<in> A \<Longrightarrow> \<Inter>A \<subseteq> B" by blast lemma union_subset_iff: "\<Union>A \<subseteq> C \<longleftrightarrow> (\<forall>x \<in> A. x \<subseteq> C)" by blast lemma subset_inter_iff_all_mem_subset_if_ne_empty: "A \<noteq> {} \<Longrightarrow> C \<subseteq> \<Inter>A \<longleftrightarrow> (\<forall>x \<in> A. C \<subseteq> x)" by blast lemma union_subset_if_all_mem_subset: "(\<And>x. x \<in> A \<Longrightarrow> x \<subseteq> C) \<Longrightarrow> \<Union>A \<subseteq> C" by blast lemma subset_inter_if_all_mem_subset_if_ne_empty: "\<lbrakk>A \<noteq> {}; \<And>x. x \<in> A \<Longrightarrow> C \<subseteq> x\<rbrakk> \<Longrightarrow> C \<subseteq> \<Inter>A" using subset_inter_iff_all_mem_subset_if_ne_empty by auto lemma mono_union: "mono union" by (intro monoI) auto lemma antimono_inter: "A \<noteq> {} \<Longrightarrow> A \<subseteq> A' \<Longrightarrow> \<Inter>A' \<subseteq> \<Inter>A" by auto subsection \<open>Indexed Union and Intersection:\<close> bundle hotg_idx_union_inter_syntax begin syntax "_idx_union" :: \<open>[pttrn, set, set \<Rightarrow> set] => set\<close> ("(3\<Union>_ \<in> _./ _)" [0, 0, 10] 10) "_idx_inter" :: \<open>[pttrn, set, set \<Rightarrow> set] => set\<close> ("(3\<Inter>_ \<in> _./ _)" [0, 0, 10] 10) end bundle no_hotg_idx_union_inter_syntax begin no_syntax "_idx_union" :: \<open>[pttrn, set, set \<Rightarrow> set] => set\<close> ("(3\<Union>_ \<in> _./ _)" [0, 0, 10] 10) "_idx_inter" :: \<open>[pttrn, set, set \<Rightarrow> set] => set\<close> ("(3\<Inter>_ \<in> _./ _)" [0, 0, 10] 10) end unbundle hotg_idx_union_inter_syntax translations "\<Union>x \<in> A. B" \<rightleftharpoons> "\<Union>{B | x \<in> A}" "\<Inter>x \<in> A. B" \<rightleftharpoons> "\<Inter>{B | x \<in> A}" lemma mem_idx_unionE [elim!]: assumes "b \<in> (\<Union>x \<in> A. B x)" obtains x where "x \<in> A" and "b \<in> B x" using assms by blast lemma mem_idx_interD: assumes "b \<in> (\<Inter>x \<in> A. B x)" and "x \<in> A" shows "b \<in> B x" using assms by blast lemma idx_union_cong [cong]: "\<lbrakk>A = B; \<And>x. x \<in> B \<Longrightarrow> C x = D x\<rbrakk> \<Longrightarrow> (\<Union>x \<in> A. C x) = (\<Union>x \<in> B. D x)" by simp lemma idx_inter_cong [cong]: "\<lbrakk>A = B; \<And>x. x \<in> B \<Longrightarrow> C x = D x\<rbrakk> \<Longrightarrow> (\<Inter>x \<in> A. C x) = (\<Inter>x \<in> B. D x)" by simp lemma idx_union_const_eq_if_ne_empty: "A \<noteq> {} \<Longrightarrow> (\<Union>x \<in> A. B) = B" by (rule eq_if_subset_if_subset) auto lemma idx_inter_const_eq_if_ne_empty: "A \<noteq> {} \<Longrightarrow> (\<Inter>x \<in> A. B) = B" by (rule eq_if_subset_if_subset) auto lemma idx_union_empty_dom_eq [simp]: "(\<Union>x \<in> {}. B x) = {}" by auto lemma idx_inter_empty_dom_eq [simp]: "(\<Inter>x \<in> {}. B x) = {}" by auto lemma idx_union_empty_eq [simp]: "(\<Union>x \<in> A. {}) = {}" by auto lemma idx_inter_empty_eq [simp]: "(\<Inter>x \<in> A. {}) = {}" by blast lemma idx_union_eq_union [simp]: "(\<Union>x \<in> A. x) = \<Union>A" by auto lemma idx_inter_eq_inter [simp]: "(\<Inter>x \<in> A. x) = \<Inter>A" by auto lemma idx_union_subset_iff: "(\<Union>x \<in> A. B x) \<subseteq> C \<longleftrightarrow> (\<forall>x \<in> A. B x \<subseteq> C)" by blast lemma subset_idx_inter_iff_if_ne_empty: "C \<noteq> {} \<Longrightarrow> C \<subseteq> (\<Inter>x \<in> A. B x) \<longleftrightarrow> (A \<noteq> {} \<and> (\<forall>x \<in> A. C \<subseteq> B x))" by auto lemma subset_idx_union_if_mem: "x \<in> A \<Longrightarrow> B x \<subseteq> (\<Union>x \<in> A. B x)" by blast lemma idx_inter_subset_if_mem: "x \<in> A \<Longrightarrow> (\<Inter>x \<in> A. B x) \<subseteq> B x" by blast lemma idx_union_subset_if_all_mem_app_subset: "(\<And>x. x \<in> A \<Longrightarrow> B x \<subseteq> C) \<Longrightarrow> (\<Union>x \<in> A. B x) \<subseteq> C" by blast lemma subset_idx_inter_if_all_mem_subset_app_if_ne_empty: "\<lbrakk>A \<noteq> {}; \<And>x. x \<in> A \<Longrightarrow> C \<subseteq> B x\<rbrakk> \<Longrightarrow> C \<subseteq> (\<Inter>x \<in> A. B x)" by blast lemma idx_union_singleton_eq [simp]: "(\<Union>x \<in> A. {x}) = A" by (rule eq_if_subset_if_subset) auto lemma idx_union_flatten [simp]: "(\<Union>x \<in> (\<Union>y \<in> A. B y). C x) = (\<Union>y \<in> A. \<Union>x \<in> B y. C x)" by (rule eq_if_subset_if_subset) auto lemma idx_union_const [simp]: "(\<Union>y \<in> A. c) = (if A = {} then {} else c)" by (rule eq_if_subset_if_subset) auto lemma idx_inter_const [simp]: "(\<Inter>y \<in> A. c) = (if A = {} then {} else c)" by (rule eq_if_subset_if_subset) auto lemma idx_union_repl [simp]: "(\<Union>y \<in> {f x | x \<in> A}. B y) = (\<Union>x \<in> A. B (f x))" by (rule eq_if_subset_if_subset) auto lemma idx_inter_repl [simp]: "(\<Inter>x \<in> {f x | x \<in> A}. B x) = (\<Inter>a \<in> A. B(f a))" by auto lemma idx_inter_union_eq_idx_inter_idx_inter: "{} \<notin> A \<Longrightarrow> (\<Inter>x \<in> \<Union>A. B x) = (\<Inter>y \<in> A. \<Inter>x \<in> y. B x)" by (auto iff: union_eq_empty_iff) lemma idx_inter_idx_union_eq_idx_inter_idx_inter: assumes "\<And>x. (x \<in> A \<Longrightarrow> B x \<noteq> {})" shows "(\<Inter>z \<in> (\<Union>x \<in> A. B x). C z) = (\<Inter>x \<in> A. \<Inter>z \<in> B x. C z)" proof (rule eqI) fix x assume "x \<in> (\<Inter>z \<in> (\<Union>x \<in> A. B x). C z)" with assms show "x \<in> (\<Inter>x \<in> A. \<Inter>z \<in> B x. C z)" by (auto 5 0) next fix x assume x_mem: "x \<in> (\<Inter>x \<in> A. \<Inter>z \<in> B x. C z)" then have "A \<noteq> {}" by auto then obtain y where "y \<in> A" by auto with assms have "B y \<noteq> {}" by auto with \<open>y \<in> A\<close> have "{B x | x \<in> A} \<noteq> {{}}" by auto with x_mem show "x \<in> (\<Inter>z \<in> (\<Union>x \<in> A. B x). C z)" by (auto simp: union_eq_empty_iff) qed lemma mono_idx_union: assumes "A \<subseteq> A'" and "\<And>x. x \<in> A \<Longrightarrow> B x \<subseteq> B' x" shows "(\<Union>x \<in> A. B x) \<subseteq> (\<Union>x \<in> A'. B' x)" using assms by auto lemma mono_antimono_idx_inter: assumes "A \<noteq> {}" and "A \<subseteq> A'" and "\<And>x. x \<in> A \<Longrightarrow> B' x \<subseteq> B x" shows "(\<Inter>x \<in> A'. B' x) \<subseteq> (\<Inter>x \<in> A. B x)" using assms by (intro subsetI) auto subsection \<open>Binary Union and Intersection\<close> definition "bin_union A B \<equiv> \<Union>{A, B}" bundle hotg_bin_union_syntax begin notation bin_union (infixl "\<union>" 70) end bundle no_hotg_bin_union_syntax begin no_notation bin_union (infixl "\<union>" 70) end unbundle hotg_bin_union_syntax definition "bin_inter A B \<equiv> \<Inter>{A, B}" bundle hotg_bin_inter_syntax begin notation bin_inter (infixl "\<inter>" 70) end bundle no_hotg_bin_inter_syntax begin no_notation bin_inter (infixl "\<inter>" 70) end unbundle hotg_bin_inter_syntax lemma mem_bin_union_iff [iff]: "x \<in> A \<union> B \<longleftrightarrow> x \<in> A \<or> x \<in> B" unfolding bin_union_def by auto lemma mem_bin_inter_iff [iff]: "x \<in> A \<inter> B \<longleftrightarrow> x \<in> A \<and> x \<in> B" unfolding bin_inter_def by auto paragraph\<open>Binary Union\<close> lemma mem_bin_union_if_mem_left [elim?]: "c \<in> A \<Longrightarrow> c \<in> A \<union> B" by simp lemma mem_bin_union_if_mem_right [elim?]: "c \<in> B \<Longrightarrow> c \<in> A \<union> B" by simp lemma bin_unionE [elim!]: assumes "c \<in> A \<union> B" obtains (mem_left) "c \<in> A" | (mem_right) "c \<in> B" using assms by auto (*stronger version of above rule*) lemma bin_unionE' [elim!]: assumes "c \<in> A \<union> B" obtains (mem_left) "c \<in> A" | (mem_right) "c \<in> B" and "c \<notin> A" using assms by auto (*LP: Classical introduction rule: no commitment to A vs B*) lemma mem_bin_union_if_mem_if_not_mem: "(c \<notin> B \<Longrightarrow> c \<in> A) \<Longrightarrow> c \<in> A \<union> B" by auto lemma bin_union_comm: "A \<union> B = B \<union> A" by (rule eq_if_subset_if_subset) auto lemma bin_union_assoc: "(A \<union> B) \<union> C = A \<union> (B \<union> C)" by (rule eq_if_subset_if_subset) auto lemma bin_union_comm_left: "A \<union> (B \<union> C) = B \<union> (A \<union> C)" by auto lemmas bin_union_AC_rules = bin_union_comm bin_union_assoc bin_union_comm_left lemma empty_bin_union_eq [iff]: "{} \<union> A = A" by (rule eq_if_subset_if_subset) auto lemma bin_union_empty_eq [iff]: "A \<union> {} = A" by (rule eq_if_subset_if_subset) auto lemma singleton_bin_union_absorb [simp]: "a \<in> A \<Longrightarrow> {a} \<union> A = A" by auto lemma singleton_bin_union_eq_insert: "{x} \<union> A = insert x A" by (rule eq_if_subset_if_subset) auto lemma bin_union_singleton_eq_insert: "A \<union> {x} = insert x A" using singleton_bin_union_eq_insert by (subst bin_union_comm) lemma mem_singleton_bin_union [iff]: "a \<in> {a} \<union> B" by auto lemma mem_bin_union_singleton [iff]: "b \<in> A \<union> {b}" by auto lemma bin_union_subset_iff [iff]: "A \<union> B \<subseteq> C \<longleftrightarrow> A \<subseteq> C \<and> B \<subseteq> C" by blast lemma bin_union_eq_left_iff [iff]: "A \<union> B = A \<longleftrightarrow> B \<subseteq> A" using mem_bin_union_if_mem_right[of _ B A] by (auto simp only: sym[of "A \<union> B"]) lemma bin_union_eq_right_iff [iff]: "A \<union> B = B \<longleftrightarrow> A \<subseteq> B" by (subst bin_union_comm) (fact bin_union_eq_left_iff) lemma subset_bin_union_left: "A \<subseteq> A \<union> B" by blast lemma subset_bin_union_right: "B \<subseteq> A \<union> B" by (subst bin_union_comm) (fact subset_bin_union_left) lemma bin_union_subset_if_subset_if_subset: "\<lbrakk>A \<subseteq> C; B \<subseteq> C\<rbrakk> \<Longrightarrow> A \<union> B \<subseteq> C" by blast lemma bin_union_self_eq_self [simp]: "A \<union> A = A" by (rule eq_if_subset_if_subset) auto lemma bin_union_absorb: "A \<union> (A \<union> B) = A \<union> B" by (rule eq_if_subset_if_subset) auto lemma bin_union_eq_right_if_subset: "A \<subseteq> B \<Longrightarrow> A \<union> B = B" by (rule eq_if_subset_if_subset) auto lemma bin_union_eq_left_if_subset: "B \<subseteq> A \<Longrightarrow> A \<union> B = A" by (rule eq_if_subset_if_subset) auto lemma bin_union_subset_bin_union_if_subset: "B \<subseteq> C \<Longrightarrow> A \<union> B \<subseteq> A \<union> C" by auto lemma bin_union_subset_bin_union_if_subset': "A \<subseteq> B \<Longrightarrow> A \<union> C \<subseteq> B \<union> C" by auto lemma bin_union_eq_empty_iff [iff]: "(A \<union> B = {}) \<longleftrightarrow> (A = {} \<and> B = {})" by auto lemma mono_bin_union_left: "mono (\<lambda>A. A \<union> B)" by (intro monoI) auto lemma mono_bin_union_right: "mono (\<lambda>B. A \<union> B)" by (intro monoI) auto paragraph \<open>Binary Intersection\<close> lemma mem_bin_inter_if_mem_if_mem [intro!]: "\<lbrakk>c \<in> A; c \<in> B\<rbrakk> \<Longrightarrow> c \<in> A \<inter> B" by simp lemma mem_bin_inter_if_mem_left: "c \<in> A \<inter> B \<Longrightarrow> c \<in> A" by simp lemma mem_bin_inter_if_mem_right: "c \<in> A \<inter> B \<Longrightarrow> c \<in> B" by simp lemma mem_bin_interE [elim!]: assumes "c \<in> A \<inter> B" obtains "c \<in> A" and "c \<in> B" using assms by simp lemma bin_inter_empty_iff [iff]: "A \<inter> B = {} \<longleftrightarrow> (\<forall>a \<in> A. a \<notin> B)" by auto lemma bin_inter_comm: "A \<inter> B = B \<inter> A" by auto lemma bin_inter_assoc: "(A \<inter> B) \<inter> C = A \<inter> (B \<inter> C)" by auto lemma bin_inter_comm_left: "A \<inter> (B \<inter> C) = B \<inter> (A \<inter> C)" by auto lemmas bin_inter_AC_rules = bin_inter_comm bin_inter_assoc bin_inter_comm_left lemma empty_bin_inter_eq_empty [iff]: "{} \<inter> B = {}" by auto lemma bin_inter_empty_eq_empty [iff]: "A \<inter> {} = {}" by auto lemma bin_inter_subset_iff [iff]: "C \<subseteq> A \<inter> B \<longleftrightarrow> C \<subseteq> A \<and> C \<subseteq> B" by blast lemma bin_inter_subset_left [iff]: "A \<inter> B \<subseteq> A" by blast lemma bin_inter_subset_right [iff]: "A \<inter> B \<subseteq> B" by blast lemma subset_bin_inter_if_subset_if_subset: "\<lbrakk>C \<subseteq> A; C \<subseteq> B\<rbrakk> \<Longrightarrow> C \<subseteq> A \<inter> B" by blast lemma bin_inter_self_eq_self [iff]: "A \<inter> A = A" by (rule eq_if_subset_if_subset) auto lemma bin_inter_absorb [iff]: "A \<inter> (A \<inter> B) = A \<inter> B" by (rule eq_if_subset_if_subset) auto lemma bin_inter_eq_right_if_subset: "B \<subseteq> A \<Longrightarrow> A \<inter> B = B" by (rule eq_if_subset_if_subset) auto lemma bin_inter_eq_left_if_subset: "A \<subseteq> B \<Longrightarrow> A \<inter> B = A" by (subst bin_inter_comm) (fact bin_inter_eq_right_if_subset) lemma bin_inter_bin_union_distrib: "(A \<inter> B) \<union> C = (A \<union> C) \<inter> (B \<union> C)" by (rule eq_if_subset_if_subset) auto lemma bin_inter_bin_union_distrib': "A \<inter> (B \<union> C) = (A \<inter> B) \<union> (A \<inter> C)" by (rule eq_if_subset_if_subset) auto lemma bin_union_bin_inter_distrib: "(A \<union> B) \<inter> C = (A \<inter> C) \<union> (B \<inter> C)" by (rule eq_if_subset_if_subset) auto lemma bin_union_bin_inter_distrib': "A \<union> (B \<inter> C) = (A \<union> B) \<inter> (A \<union> C)" by (rule eq_if_subset_if_subset) auto lemma bin_inter_eq_left_iff_subset: "A \<subseteq> B \<longleftrightarrow> A \<inter> B = A" by auto lemma bin_inter_eq_right_iff_subset: "A \<subseteq> B \<longleftrightarrow> B \<inter> A = A" by auto lemma bin_inter_bin_union_assoc_iff: "(A \<inter> B) \<union> C = A \<inter> (B \<union> C) \<longleftrightarrow> C \<subseteq> A" by auto lemma bin_inter_bin_union_swap3: "(A \<inter> B) \<union> (B \<inter> C) \<union> (C \<inter> A) = (A \<union> B) \<inter> (B \<union> C) \<inter> (C \<union> A)" by auto lemma mono_bin_inter_left: "mono (\<lambda>A. A \<inter> B)" by (intro monoI) auto lemma mono_bin_inter_right: "mono (\<lambda>B. A \<inter> B)" by (intro monoI) auto paragraph\<open>Comprehension\<close> lemma collect_eq_bin_inter [simp]: "{a \<in> A | a \<in> A'} = A \<inter> A'" by auto lemma collect_bin_union_eq: "{x \<in> A \<union> B | P x} = {x \<in> A | P x} \<union> {x \<in> B | P x}" by (rule eq_if_subset_if_subset) auto lemma collect_bin_inter_eq: "{x \<in> A \<inter> B | P x} = {x \<in> A | P x} \<inter> {x \<in> B | P x}" by (rule eq_if_subset_if_subset) auto lemma bin_inter_collect_absorb [iff]: "A \<inter> {x \<in> A | P x} = {x \<in> A | P x}" by (rule eq_if_subset_if_subset) auto lemma collect_idx_union_eq_union_collect [simp]: "{y \<in> (\<Union>x \<in> A. B x) | P y} = (\<Union>x \<in> A. {y \<in> B x | P y})" by (rule eq_if_subset_if_subset) auto lemma bin_inter_collect_left_eq_collect: "{x \<in> A | P x} \<inter> B = {x \<in> A \<inter> B | P x}" by (rule eq_if_subset_if_subset) auto lemma bin_inter_collect_right_eq_collect: "A \<inter> {x \<in> B | P x} = {x \<in> A \<inter> B | P x}" by (rule eq_if_subset_if_subset) auto lemma collect_and_eq_inter_collect: "{x \<in> A | P x \<and> Q x} = {x \<in> A | P x} \<inter> {x \<in> A | Q x}" by (rule eq_if_subset_if_subset) auto lemma collect_or_eq_union_collect: "{x \<in> A | P x \<or> Q x} = {x \<in> A | P x} \<union> {x \<in> A | Q x}" by (rule eq_if_subset_if_subset) auto lemma union_bin_union_eq_bin_union_union: "\<Union>(A \<union> B) = \<Union>A \<union> \<Union>B" by (rule eq_if_subset_if_subset) auto lemma union_bin_inter_subset_bin_inter_union: "\<Union>(A \<inter> B) \<subseteq> \<Union>A \<inter> \<Union>B" by blast lemma union__disjoint_iff: "\<Union>C \<inter> A = {} \<longleftrightarrow> (\<forall>B \<in> C. B \<inter> A = {})" by blast lemma subset_idx_union_iff_eq: "A \<subseteq> (\<Union>i \<in> I. B i) \<longleftrightarrow> A = (\<Union>i \<in> I. A \<inter> B i)" (is "A \<subseteq> ?lhs_union \<longleftrightarrow> A = ?rhs_union") proof assume A_eq: "A = ?rhs_union" show "A \<subseteq> ?lhs_union" proof (rule subsetI) fix a assume "a \<in> A" with A_eq have "a \<in> ?rhs_union" by simp then obtain x where "x \<in> I" and "a \<in> A \<inter> B x" by auto then show "a \<in> ?lhs_union" by auto qed qed (auto 5 0 intro!: eqI) lemma bin_inter_union_eq_idx_union_inter: "\<Union>B \<inter> A = (\<Union>C \<in> B. C \<inter> A)" by (rule eq_if_subset_if_subset) auto lemma bin_union_inter_subset_inter_bin_inter: "\<lbrakk>z \<in> A; z \<in> B\<rbrakk> \<Longrightarrow> \<Inter>A \<union> \<Inter>B \<subseteq> \<Inter>(A \<inter> B)" by blast lemma inter_bin_union_eq_bin_inter_inter: "\<lbrakk>A \<noteq> {}; B \<noteq> {}\<rbrakk> \<Longrightarrow> \<Inter>(A \<union> B) = \<Inter>A \<inter> \<Inter>B" by (rule eq_if_subset_if_subset) auto lemma idx_union_bin_union_dom_eq_bin_union_idx_union: "(\<Union>i \<in> A \<union> B. C i) = (\<Union>i \<in> A. C i) \<union> (\<Union>i \<in> B. C i)" by (rule eq_if_subset_if_subset) auto lemma idx_inter_bin_inter_dom_eq_bin_inter_idx_inter: "(\<Inter>i \<in> I \<union> J. A i) = ( if I = {} then \<Inter>j \<in> J. A j else if J = {} then \<Inter>i \<in> I. A i else (\<Inter>i \<in> I. A i) \<inter> (\<Inter>j \<in> J. A j) )" by (rule eq_if_subset_if_subset) auto (*Halmos, Naive Set Theory, page 35*) lemma bin_inter_idx_union_eq_union_bin_inter: "B \<inter> (\<Union>i \<in> I. A i) = (\<Union>i \<in> I. B \<inter> A i)" by (rule eq_if_subset_if_subset) auto lemma bin_union_idx_inter_eq_inter_bin_union: "I \<noteq> {} \<Longrightarrow> B \<union> (\<Inter>i \<in> I. A i) = (\<Inter>i \<in> I. B \<union> A i)" by (rule eq_if_subset_if_subset) auto lemma bin_inter_idx_union_eq_idx_union_bin_inter: "(\<Union>i \<in> I. A i) \<inter> (\<Union>j \<in> J. B j) = (\<Union>i \<in> I. \<Union>j \<in> J. A i \<inter> B j)" by (rule eq_if_subset_if_subset) auto lemma bin_union_idx_inter_eq_idx_inter_bin_union: "\<lbrakk>I \<noteq> {}; J \<noteq> {}\<rbrakk> \<Longrightarrow> (\<Inter>i \<in> I. A i) \<union> (\<Inter>j \<in> J. B j) = (\<Inter>i \<in> I. \<Inter>j \<in> J. A i \<union> B j)" by (rule eq_if_subset_if_subset) auto lemma idx_union_bin_union_eq_bin_union_idx_union: "(\<Union>i \<in> I. A i \<union> B i) = (\<Union>i \<in> I. A i) \<union> (\<Union>i \<in> I. B i)" by (rule eq_if_subset_if_subset) auto lemma idx_inter_bin_inter_eq_bin_inter_idx_inter: "I \<noteq> {} \<Longrightarrow> (\<Inter>i \<in> I. A i \<inter> B i) = (\<Inter>i \<in> I. A i) \<inter> (\<Inter>i \<in> I. B i)" by (rule eq_if_subset_if_subset) auto lemma idx_union_bin_inter_subset_bin_inter_idx_union: "(\<Union>z \<in> I \<inter> J. A z) \<subseteq> (\<Union>z \<in> I. A z) \<inter> (\<Union>z \<in> J. A z)" by blast end
Require Import Coq.Logic.Classical_Prop. Require Import SpecCert.Address. Require Import SpecCert.Cache. Require Import SpecCert.Formalism. Require Import SpecCert.Interval. Require Import SpecCert.Memory. Require Import SpecCert.Smm.Delta.Invariant. Require Import SpecCert.Smm.Delta.Preserve.Architecture. Require Import SpecCert.Smm.Software. Require Import SpecCert.x86. Lemma read_strat_uc (r: R) (pa: PhysicalAddress) (v: Value) : partial_preserve (Read r pa v) (fun a => resolve_cache_strategy (proc a) pa = Uncachable) inv. Proof. unfold partial_preserve. intros a a' Hinv Hres Hpre Hpost. unfold x86_postcondition, read_post in Hpost. rewrite Hres in Hpost. unfold read_uncachable_post in Hpost. rewrite Hpost. exact Hinv. Qed. Lemma read_strat_sh (r: R) (pa: PhysicalAddress) (v: Value) : partial_preserve (Read r pa v) (fun a => resolve_cache_strategy (proc a) pa = SmrrHit) inv. Proof. unfold partial_preserve. intros a a' Hinv Hres Hpre Hpost. unfold x86_postcondition, read_post in Hpost. rewrite Hres in Hpost. unfold read_smrrhit_post in Hpost. rewrite Hpost. exact Hinv. Qed. Lemma read_strat_smrr_wb (r: R) (pa: PhysicalAddress) (v: Value) : partial_preserve (Read r pa v) (fun a => is_inside_smrr (proc a) pa /\ smm_strategy (smrr (proc a)) = WriteBack) inv. Proof. unfold partial_preserve. intros a a' Hinv [Hsmrr Hsmm] Hpre Hpost. unfold x86_postcondition, read_post, resolve_cache_strategy in Hpost. destruct is_inside_smrr_dec; [| intuition ]. destruct is_in_smm_dec. + rewrite Hsmm in Hpost. unfold read_writeback_post in Hpost. destruct cache_hit_dec. * rewrite Hpost. exact Hinv. * assert (is_inside_smram pa -> is_in_smm (proc a)). intro H; exact i0. apply (load_in_cache_from_memory_preserves_inv a a' pa Hinv H Hpost). + unfold read_smrrhit_post in Hpost. rewrite Hpost. exact Hinv. Qed. Lemma read_strat_not_smrr (r: R) (pa: PhysicalAddress) (v: Value) : partial_preserve (Read r pa v) (fun a => ~ is_inside_smrr (proc a) pa) inv. Proof. unfold partial_preserve. intros a a' Hinv Hnot_smrr Hpre Hpost. unfold x86_postcondition, read_post in Hpost. unfold resolve_cache_strategy in Hpost. destruct is_inside_smrr_dec; [ intuition |]. case_eq (strategy (proc a)); intro Heqstrat; rewrite Heqstrat in Hpost. + unfold read_uncachable_post in Hpost. rewrite Hpost. exact Hinv. + unfold read_writeback_post in Hpost. destruct cache_hit_dec. * rewrite Hpost; exact Hinv. * assert (is_inside_smram pa -> is_in_smm (proc a)). intro H. destruct Hinv as [Hsmramc [Hsmram [Hsmrr Hclean]]]. apply Hsmrr in H. intuition. apply (load_in_cache_from_memory_preserves_inv a a' pa Hinv H Hpost). + unfold read_smrrhit_post in Hpost. rewrite Hpost. exact Hinv. Qed. Lemma read_inv (r: R) (pa: PhysicalAddress) (v: Value) : preserve (Read r pa v) inv. Proof. unfold preserve. intros a a' Hinv Hpre Hpost. case_eq (resolve_cache_strategy (proc a) pa); intro Heqstrat. + apply (read_strat_uc r pa v a a' Hinv Heqstrat Hpre Hpost). + destruct (is_inside_smrr_dec (proc a) pa). * unfold resolve_cache_strategy in Heqstrat. destruct is_inside_smrr_dec; [| intuition ]. destruct is_in_smm_dec; [| discriminate ]. assert (is_inside_smrr (proc a) pa /\ smm_strategy (smrr (proc a)) = WriteBack); [ split; trivial |]. apply (read_strat_smrr_wb r pa v a a' Hinv H Hpre Hpost). * apply (read_strat_not_smrr r pa v a a' Hinv n Hpre Hpost). + apply (read_strat_sh r pa v a a' Hinv Heqstrat Hpre Hpost). Qed.
function a = schur_block_inverse ( n, x, y ) %*****************************************************************************80 % %% SCHUR_BLOCK_INVERSE returns the inverse of the SCHUR_BLOCK matrix. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 20 October 2007 % % Author: % % John Burkardt % % Parameters: % % Input, integer N, the order of A. % % Input, real X( (N+1)/2 ), specifies the diagonal elements % of A. % % Input, real Y( N/2 ), specifies the off-diagonal elements % of the Schur blocks. % % Output, real A(N,N), the matrix. % a = zeros ( n, n ); for i = 1 : n for j = 1 : n k = floor ( ( i + 1 ) / 2 ); if ( i == j ) if ( i == n & mod ( n, 2 ) == 1 ) a(i,j) = 1.0 / x(k); else a(i,j) = x(k) / ( x(k)^2 + y(k)^2 ); end elseif ( mod ( i, 2 ) == 1 & j == i + 1 ) a(i,j) = - y(k) / ( x(k)^2 + y(k)^2 ); elseif ( mod ( i, 2 ) == 0 & j == i - 1 ) a(i,j) = y(k) / ( x(k)^2 + y(k)^2 ); else a(i,j) = 0.0; end end end return end
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov ! This file was ported from Lean 3 source module data.set.intervals.ord_connected ! leanprover-community/mathlib commit 76de8ae01554c3b37d66544866659ff174e66e1f ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Data.Set.Intervals.UnorderedInterval import Mathbin.Data.Set.Lattice import Mathbin.Order.Antichain /-! # Order-connected sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We say that a set `s : set α` is `ord_connected` if for all `x y ∈ s` it includes the interval `[x, y]`. If `α` is a `densely_ordered` `conditionally_complete_linear_order` with the `order_topology`, then this condition is equivalent to `is_preconnected s`. If `α` is a `linear_ordered_field`, then this condition is also equivalent to `convex α s`. In this file we prove that intersection of a family of `ord_connected` sets is `ord_connected` and that all standard intervals are `ord_connected`. -/ open Interval open OrderDual (toDual ofDual) namespace Set section Preorder variable {α β : Type _} [Preorder α] [Preorder β] {s t : Set α} #print Set.OrdConnected /- /-- We say that a set `s : set α` is `ord_connected` if for all `x y ∈ s` it includes the interval `[x, y]`. If `α` is a `densely_ordered` `conditionally_complete_linear_order` with the `order_topology`, then this condition is equivalent to `is_preconnected s`. If `α` is a `linear_ordered_field`, then this condition is also equivalent to `convex α s`. -/ class OrdConnected (s : Set α) : Prop where out' ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s) : Icc x y ⊆ s #align set.ord_connected Set.OrdConnected -/ #print Set.OrdConnected.out /- theorem OrdConnected.out (h : OrdConnected s) : ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), Icc x y ⊆ s := h.1 #align set.ord_connected.out Set.OrdConnected.out -/ #print Set.ordConnected_def /- theorem ordConnected_def : OrdConnected s ↔ ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), Icc x y ⊆ s := ⟨fun h => h.1, fun h => ⟨h⟩⟩ #align set.ord_connected_def Set.ordConnected_def -/ #print Set.ordConnected_iff /- /-- It suffices to prove `[x, y] ⊆ s` for `x y ∈ s`, `x ≤ y`. -/ theorem ordConnected_iff : OrdConnected s ↔ ∀ x ∈ s, ∀ y ∈ s, x ≤ y → Icc x y ⊆ s := ordConnected_def.trans ⟨fun hs x hx y hy hxy => hs hx hy, fun H x hx y hy z hz => H x hx y hy (le_trans hz.1 hz.2) hz⟩ #align set.ord_connected_iff Set.ordConnected_iff -/ #print Set.ordConnected_of_Ioo /- theorem ordConnected_of_Ioo {α : Type _} [PartialOrder α] {s : Set α} (hs : ∀ x ∈ s, ∀ y ∈ s, x < y → Ioo x y ⊆ s) : OrdConnected s := by rw [ord_connected_iff] intro x hx y hy hxy rcases eq_or_lt_of_le hxy with (rfl | hxy'); · simpa rw [← Ioc_insert_left hxy, ← Ioo_insert_right hxy'] exact insert_subset.2 ⟨hx, insert_subset.2 ⟨hy, hs x hx y hy hxy'⟩⟩ #align set.ord_connected_of_Ioo Set.ordConnected_of_Ioo -/ /- warning: set.ord_connected.preimage_mono -> Set.OrdConnected.preimage_mono is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u1} α] [_inst_2 : Preorder.{u2} β] {s : Set.{u1} α} {f : β -> α}, (Set.OrdConnected.{u1} α _inst_1 s) -> (Monotone.{u2, u1} β α _inst_2 _inst_1 f) -> (Set.OrdConnected.{u2} β _inst_2 (Set.preimage.{u2, u1} β α f s)) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : Preorder.{u2} α] [_inst_2 : Preorder.{u1} β] {s : Set.{u2} α} {f : β -> α}, (Set.OrdConnected.{u2} α _inst_1 s) -> (Monotone.{u1, u2} β α _inst_2 _inst_1 f) -> (Set.OrdConnected.{u1} β _inst_2 (Set.preimage.{u1, u2} β α f s)) Case conversion may be inaccurate. Consider using '#align set.ord_connected.preimage_mono Set.OrdConnected.preimage_monoₓ'. -/ theorem OrdConnected.preimage_mono {f : β → α} (hs : OrdConnected s) (hf : Monotone f) : OrdConnected (f ⁻¹' s) := ⟨fun x hx y hy z hz => hs.out hx hy ⟨hf hz.1, hf hz.2⟩⟩ #align set.ord_connected.preimage_mono Set.OrdConnected.preimage_mono /- warning: set.ord_connected.preimage_anti -> Set.OrdConnected.preimage_anti is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u1} α] [_inst_2 : Preorder.{u2} β] {s : Set.{u1} α} {f : β -> α}, (Set.OrdConnected.{u1} α _inst_1 s) -> (Antitone.{u2, u1} β α _inst_2 _inst_1 f) -> (Set.OrdConnected.{u2} β _inst_2 (Set.preimage.{u2, u1} β α f s)) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : Preorder.{u2} α] [_inst_2 : Preorder.{u1} β] {s : Set.{u2} α} {f : β -> α}, (Set.OrdConnected.{u2} α _inst_1 s) -> (Antitone.{u1, u2} β α _inst_2 _inst_1 f) -> (Set.OrdConnected.{u1} β _inst_2 (Set.preimage.{u1, u2} β α f s)) Case conversion may be inaccurate. Consider using '#align set.ord_connected.preimage_anti Set.OrdConnected.preimage_antiₓ'. -/ theorem OrdConnected.preimage_anti {f : β → α} (hs : OrdConnected s) (hf : Antitone f) : OrdConnected (f ⁻¹' s) := ⟨fun x hx y hy z hz => hs.out hy hx ⟨hf hz.2, hf hz.1⟩⟩ #align set.ord_connected.preimage_anti Set.OrdConnected.preimage_anti #print Set.Icc_subset /- protected theorem Icc_subset (s : Set α) [hs : OrdConnected s] {x y} (hx : x ∈ s) (hy : y ∈ s) : Icc x y ⊆ s := hs.out hx hy #align set.Icc_subset Set.Icc_subset -/ /- warning: set.ord_connected.inter -> Set.OrdConnected.inter is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : Preorder.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α}, (Set.OrdConnected.{u1} α _inst_1 s) -> (Set.OrdConnected.{u1} α _inst_1 t) -> (Set.OrdConnected.{u1} α _inst_1 (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : Preorder.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α}, (Set.OrdConnected.{u1} α _inst_1 s) -> (Set.OrdConnected.{u1} α _inst_1 t) -> (Set.OrdConnected.{u1} α _inst_1 (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)) Case conversion may be inaccurate. Consider using '#align set.ord_connected.inter Set.OrdConnected.interₓ'. -/ theorem OrdConnected.inter {s t : Set α} (hs : OrdConnected s) (ht : OrdConnected t) : OrdConnected (s ∩ t) := ⟨fun x hx y hy => subset_inter (hs.out hx.1 hy.1) (ht.out hx.2 hy.2)⟩ #align set.ord_connected.inter Set.OrdConnected.inter /- warning: set.ord_connected.inter' -> Set.OrdConnected.inter' is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : Preorder.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α} [_inst_3 : Set.OrdConnected.{u1} α _inst_1 s] [_inst_4 : Set.OrdConnected.{u1} α _inst_1 t], Set.OrdConnected.{u1} α _inst_1 (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t) but is expected to have type forall {α : Type.{u1}} [_inst_1 : Preorder.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α} [_inst_3 : Set.OrdConnected.{u1} α _inst_1 s] [_inst_4 : Set.OrdConnected.{u1} α _inst_1 t], Set.OrdConnected.{u1} α _inst_1 (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t) Case conversion may be inaccurate. Consider using '#align set.ord_connected.inter' Set.OrdConnected.inter'ₓ'. -/ instance OrdConnected.inter' {s t : Set α} [OrdConnected s] [OrdConnected t] : OrdConnected (s ∩ t) := OrdConnected.inter ‹_› ‹_› #align set.ord_connected.inter' Set.OrdConnected.inter' #print Set.OrdConnected.dual /- theorem OrdConnected.dual {s : Set α} (hs : OrdConnected s) : OrdConnected (OrderDual.ofDual ⁻¹' s) := ⟨fun x hx y hy z hz => hs.out hy hx ⟨hz.2, hz.1⟩⟩ #align set.ord_connected.dual Set.OrdConnected.dual -/ #print Set.ordConnected_dual /- theorem ordConnected_dual {s : Set α} : OrdConnected (OrderDual.ofDual ⁻¹' s) ↔ OrdConnected s := ⟨fun h => by simpa only [ord_connected_def] using h.dual, fun h => h.dual⟩ #align set.ord_connected_dual Set.ordConnected_dual -/ #print Set.ordConnected_interₛ /- theorem ordConnected_interₛ {S : Set (Set α)} (hS : ∀ s ∈ S, OrdConnected s) : OrdConnected (⋂₀ S) := ⟨fun x hx y hy => subset_interₛ fun s hs => (hS s hs).out (hx s hs) (hy s hs)⟩ #align set.ord_connected_sInter Set.ordConnected_interₛ -/ #print Set.ordConnected_interᵢ /- theorem ordConnected_interᵢ {ι : Sort _} {s : ι → Set α} (hs : ∀ i, OrdConnected (s i)) : OrdConnected (⋂ i, s i) := ordConnected_interₛ <| forall_range_iff.2 hs #align set.ord_connected_Inter Set.ordConnected_interᵢ -/ #print Set.ordConnected_interᵢ' /- instance ordConnected_interᵢ' {ι : Sort _} {s : ι → Set α} [∀ i, OrdConnected (s i)] : OrdConnected (⋂ i, s i) := ordConnected_interᵢ ‹_› #align set.ord_connected_Inter' Set.ordConnected_interᵢ' -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i hi) -/ #print Set.ordConnected_binterᵢ /- theorem ordConnected_binterᵢ {ι : Sort _} {p : ι → Prop} {s : ∀ (i : ι) (hi : p i), Set α} (hs : ∀ i hi, OrdConnected (s i hi)) : OrdConnected (⋂ (i) (hi), s i hi) := ordConnected_interᵢ fun i => ordConnected_interᵢ <| hs i #align set.ord_connected_bInter Set.ordConnected_binterᵢ -/ /- warning: set.ord_connected_pi -> Set.ordConnected_pi is a dubious translation: lean 3 declaration is forall {ι : Type.{u1}} {α : ι -> Type.{u2}} [_inst_3 : forall (i : ι), Preorder.{u2} (α i)] {s : Set.{u1} ι} {t : forall (i : ι), Set.{u2} (α i)}, (forall (i : ι), (Membership.Mem.{u1, u1} ι (Set.{u1} ι) (Set.hasMem.{u1} ι) i s) -> (Set.OrdConnected.{u2} (α i) (_inst_3 i) (t i))) -> (Set.OrdConnected.{max u1 u2} (forall (i : ι), α i) (Pi.preorder.{u1, u2} ι (fun (i : ι) => α i) (fun (i : ι) => _inst_3 i)) (Set.pi.{u1, u2} ι (fun (i : ι) => α i) s t)) but is expected to have type forall {ι : Type.{u2}} {α : ι -> Type.{u1}} [_inst_3 : forall (i : ι), Preorder.{u1} (α i)] {s : Set.{u2} ι} {t : forall (i : ι), Set.{u1} (α i)}, (forall (i : ι), (Membership.mem.{u2, u2} ι (Set.{u2} ι) (Set.instMembershipSet.{u2} ι) i s) -> (Set.OrdConnected.{u1} (α i) (_inst_3 i) (t i))) -> (Set.OrdConnected.{max u2 u1} (forall (i : ι), α i) (Pi.preorder.{u2, u1} ι (fun (i : ι) => α i) (fun (i : ι) => _inst_3 i)) (Set.pi.{u2, u1} ι (fun (i : ι) => α i) s t)) Case conversion may be inaccurate. Consider using '#align set.ord_connected_pi Set.ordConnected_piₓ'. -/ theorem ordConnected_pi {ι : Type _} {α : ι → Type _} [∀ i, Preorder (α i)] {s : Set ι} {t : ∀ i, Set (α i)} (h : ∀ i ∈ s, OrdConnected (t i)) : OrdConnected (s.pi t) := ⟨fun x hx y hy z hz i hi => (h i hi).out (hx i hi) (hy i hi) ⟨hz.1 i, hz.2 i⟩⟩ #align set.ord_connected_pi Set.ordConnected_pi #print Set.ordConnected_pi' /- instance ordConnected_pi' {ι : Type _} {α : ι → Type _} [∀ i, Preorder (α i)] {s : Set ι} {t : ∀ i, Set (α i)} [h : ∀ i, OrdConnected (t i)] : OrdConnected (s.pi t) := ordConnected_pi fun i hi => h i #align set.ord_connected_pi' Set.ordConnected_pi' -/ #print Set.ordConnected_Ici /- @[instance] theorem ordConnected_Ici {a : α} : OrdConnected (Ici a) := ⟨fun x hx y hy z hz => le_trans hx hz.1⟩ #align set.ord_connected_Ici Set.ordConnected_Ici -/ #print Set.ordConnected_Iic /- @[instance] theorem ordConnected_Iic {a : α} : OrdConnected (Iic a) := ⟨fun x hx y hy z hz => le_trans hz.2 hy⟩ #align set.ord_connected_Iic Set.ordConnected_Iic -/ #print Set.ordConnected_Ioi /- @[instance] theorem ordConnected_Ioi {a : α} : OrdConnected (Ioi a) := ⟨fun x hx y hy z hz => lt_of_lt_of_le hx hz.1⟩ #align set.ord_connected_Ioi Set.ordConnected_Ioi -/ #print Set.ordConnected_Iio /- @[instance] theorem ordConnected_Iio {a : α} : OrdConnected (Iio a) := ⟨fun x hx y hy z hz => lt_of_le_of_lt hz.2 hy⟩ #align set.ord_connected_Iio Set.ordConnected_Iio -/ #print Set.ordConnected_Icc /- @[instance] theorem ordConnected_Icc {a b : α} : OrdConnected (Icc a b) := ordConnected_Ici.inter ordConnected_Iic #align set.ord_connected_Icc Set.ordConnected_Icc -/ #print Set.ordConnected_Ico /- @[instance] theorem ordConnected_Ico {a b : α} : OrdConnected (Ico a b) := ordConnected_Ici.inter ordConnected_Iio #align set.ord_connected_Ico Set.ordConnected_Ico -/ #print Set.ordConnected_Ioc /- @[instance] theorem ordConnected_Ioc {a b : α} : OrdConnected (Ioc a b) := ordConnected_Ioi.inter ordConnected_Iic #align set.ord_connected_Ioc Set.ordConnected_Ioc -/ #print Set.ordConnected_Ioo /- @[instance] theorem ordConnected_Ioo {a b : α} : OrdConnected (Ioo a b) := ordConnected_Ioi.inter ordConnected_Iio #align set.ord_connected_Ioo Set.ordConnected_Ioo -/ #print Set.ordConnected_singleton /- @[instance] theorem ordConnected_singleton {α : Type _} [PartialOrder α] {a : α} : OrdConnected ({a} : Set α) := by rw [← Icc_self] exact ord_connected_Icc #align set.ord_connected_singleton Set.ordConnected_singleton -/ #print Set.ordConnected_empty /- @[instance] theorem ordConnected_empty : OrdConnected (∅ : Set α) := ⟨fun x => False.elim⟩ #align set.ord_connected_empty Set.ordConnected_empty -/ #print Set.ordConnected_univ /- @[instance] theorem ordConnected_univ : OrdConnected (univ : Set α) := ⟨fun _ _ _ _ => subset_univ _⟩ #align set.ord_connected_univ Set.ordConnected_univ -/ /-- In a dense order `α`, the subtype from an `ord_connected` set is also densely ordered. -/ instance [DenselyOrdered α] {s : Set α} [hs : OrdConnected s] : DenselyOrdered s := ⟨fun a b (h : (a : α) < b) => let ⟨x, H⟩ := exists_between h ⟨⟨x, (hs.out a.2 b.2) (Ioo_subset_Icc_self H)⟩, H⟩⟩ /- warning: set.ord_connected_preimage -> Set.ordConnected_preimage is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u1} α] [_inst_2 : Preorder.{u2} β] {F : Type.{u3}} [_inst_3 : OrderHomClass.{u3, u1, u2} F α β (Preorder.toLE.{u1} α _inst_1) (Preorder.toLE.{u2} β _inst_2)] (f : F) {s : Set.{u2} β} [hs : Set.OrdConnected.{u2} β _inst_2 s], Set.OrdConnected.{u1} α _inst_1 (Set.preimage.{u1, u2} α β (coeFn.{succ u3, max (succ u1) (succ u2)} F (fun (_x : F) => α -> β) (FunLike.hasCoeToFun.{succ u3, succ u1, succ u2} F α (fun (_x : α) => β) (RelHomClass.toFunLike.{u3, u1, u2} F α β (LE.le.{u1} α (Preorder.toLE.{u1} α _inst_1)) (LE.le.{u2} β (Preorder.toLE.{u2} β _inst_2)) _inst_3)) f) s) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : Preorder.{u2} α] [_inst_2 : Preorder.{u1} β] {F : Type.{u3}} [_inst_3 : OrderHomClass.{u3, u2, u1} F α β (Preorder.toLE.{u2} α _inst_1) (Preorder.toLE.{u1} β _inst_2)] (f : F) {s : Set.{u1} β} [hs : Set.OrdConnected.{u1} β _inst_2 s], Set.OrdConnected.{u2} α _inst_1 (Set.preimage.{u2, u1} α β (FunLike.coe.{succ u3, succ u2, succ u1} F α (fun (_x : α) => (fun ([email protected]._hyg.867 : α) => β) _x) (RelHomClass.toFunLike.{u3, u2, u1} F α β (fun ([email protected]._hyg.1896 : α) ([email protected]._hyg.1898 : α) => LE.le.{u2} α (Preorder.toLE.{u2} α _inst_1) [email protected]._hyg.1896 [email protected]._hyg.1898) (fun (_x : β) ([email protected]._hyg.1920 : β) => LE.le.{u1} β (Preorder.toLE.{u1} β _inst_2) _x [email protected]._hyg.1920) _inst_3) f) s) Case conversion may be inaccurate. Consider using '#align set.ord_connected_preimage Set.ordConnected_preimageₓ'. -/ @[instance] theorem ordConnected_preimage {F : Type _} [OrderHomClass F α β] (f : F) {s : Set β} [hs : OrdConnected s] : OrdConnected (f ⁻¹' s) := ⟨fun x hx y hy z hz => hs.out hx hy ⟨OrderHomClass.mono _ hz.1, OrderHomClass.mono _ hz.2⟩⟩ #align set.ord_connected_preimage Set.ordConnected_preimage /- warning: set.ord_connected_image -> Set.ordConnected_image is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u1} α] [_inst_2 : Preorder.{u2} β] {E : Type.{u3}} [_inst_3 : OrderIsoClass.{u3, u1, u2} E α β (Preorder.toLE.{u1} α _inst_1) (Preorder.toLE.{u2} β _inst_2)] (e : E) {s : Set.{u1} α} [hs : Set.OrdConnected.{u1} α _inst_1 s], Set.OrdConnected.{u2} β _inst_2 (Set.image.{u1, u2} α β (coeFn.{succ u3, max (succ u1) (succ u2)} E (fun (_x : E) => α -> β) (FunLike.hasCoeToFun.{succ u3, succ u1, succ u2} E α (fun (_x : α) => β) (RelHomClass.toFunLike.{u3, u1, u2} E α β (LE.le.{u1} α (Preorder.toLE.{u1} α _inst_1)) (LE.le.{u2} β (Preorder.toLE.{u2} β _inst_2)) (OrderIsoClass.toOrderHomClass.{u3, u1, u2} E α β (Preorder.toLE.{u1} α _inst_1) (Preorder.toLE.{u2} β _inst_2) _inst_3))) e) s) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : Preorder.{u2} α] [_inst_2 : Preorder.{u1} β] {E : Type.{u3}} [_inst_3 : OrderIsoClass.{u3, u2, u1} E α β (Preorder.toLE.{u2} α _inst_1) (Preorder.toLE.{u1} β _inst_2)] (e : E) {s : Set.{u2} α} [hs : Set.OrdConnected.{u2} α _inst_1 s], Set.OrdConnected.{u1} β _inst_2 (Set.image.{u2, u1} α β (FunLike.coe.{succ u3, succ u2, succ u1} E α (fun (_x : α) => (fun ([email protected]._hyg.867 : α) => β) _x) (RelHomClass.toFunLike.{u3, u2, u1} E α β (fun ([email protected]._hyg.1896 : α) ([email protected]._hyg.1898 : α) => LE.le.{u2} α (Preorder.toLE.{u2} α _inst_1) [email protected]._hyg.1896 [email protected]._hyg.1898) (fun (_x : β) ([email protected]._hyg.1920 : β) => LE.le.{u1} β (Preorder.toLE.{u1} β _inst_2) _x [email protected]._hyg.1920) (OrderIsoClass.toOrderHomClass.{u3, u2, u1} E α β (Preorder.toLE.{u2} α _inst_1) (Preorder.toLE.{u1} β _inst_2) _inst_3)) e) s) Case conversion may be inaccurate. Consider using '#align set.ord_connected_image Set.ordConnected_imageₓ'. -/ @[instance] theorem ordConnected_image {E : Type _} [OrderIsoClass E α β] (e : E) {s : Set α} [hs : OrdConnected s] : OrdConnected (e '' s) := by erw [(e : α ≃o β).image_eq_preimage] apply ord_connected_preimage #align set.ord_connected_image Set.ordConnected_image /- warning: set.ord_connected_range -> Set.ordConnected_range is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Preorder.{u1} α] [_inst_2 : Preorder.{u2} β] {E : Type.{u3}} [_inst_3 : OrderIsoClass.{u3, u1, u2} E α β (Preorder.toLE.{u1} α _inst_1) (Preorder.toLE.{u2} β _inst_2)] (e : E), Set.OrdConnected.{u2} β _inst_2 (Set.range.{u2, succ u1} β α (coeFn.{succ u3, max (succ u1) (succ u2)} E (fun (_x : E) => α -> β) (FunLike.hasCoeToFun.{succ u3, succ u1, succ u2} E α (fun (_x : α) => β) (RelHomClass.toFunLike.{u3, u1, u2} E α β (LE.le.{u1} α (Preorder.toLE.{u1} α _inst_1)) (LE.le.{u2} β (Preorder.toLE.{u2} β _inst_2)) (OrderIsoClass.toOrderHomClass.{u3, u1, u2} E α β (Preorder.toLE.{u1} α _inst_1) (Preorder.toLE.{u2} β _inst_2) _inst_3))) e)) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : Preorder.{u2} α] [_inst_2 : Preorder.{u1} β] {E : Type.{u3}} [_inst_3 : OrderIsoClass.{u3, u2, u1} E α β (Preorder.toLE.{u2} α _inst_1) (Preorder.toLE.{u1} β _inst_2)] (e : E), Set.OrdConnected.{u1} β _inst_2 (Set.range.{u1, succ u2} β α (FunLike.coe.{succ u3, succ u2, succ u1} E α (fun (_x : α) => (fun ([email protected]._hyg.867 : α) => β) _x) (RelHomClass.toFunLike.{u3, u2, u1} E α β (fun ([email protected]._hyg.1896 : α) ([email protected]._hyg.1898 : α) => LE.le.{u2} α (Preorder.toLE.{u2} α _inst_1) [email protected]._hyg.1896 [email protected]._hyg.1898) (fun (_x : β) ([email protected]._hyg.1920 : β) => LE.le.{u1} β (Preorder.toLE.{u1} β _inst_2) _x [email protected]._hyg.1920) (OrderIsoClass.toOrderHomClass.{u3, u2, u1} E α β (Preorder.toLE.{u2} α _inst_1) (Preorder.toLE.{u1} β _inst_2) _inst_3)) e)) Case conversion may be inaccurate. Consider using '#align set.ord_connected_range Set.ordConnected_rangeₓ'. -/ @[instance] theorem ordConnected_range {E : Type _} [OrderIsoClass E α β] (e : E) : OrdConnected (range e) := by simp_rw [← image_univ, ord_connected_image e] #align set.ord_connected_range Set.ordConnected_range #print Set.dual_ordConnected_iff /- @[simp] theorem dual_ordConnected_iff {s : Set α} : OrdConnected (ofDual ⁻¹' s) ↔ OrdConnected s := by simp_rw [ord_connected_def, to_dual.surjective.forall, dual_Icc, Subtype.forall'] exact forall_swap #align set.dual_ord_connected_iff Set.dual_ordConnected_iff -/ #print Set.dual_ordConnected /- @[instance] theorem dual_ordConnected {s : Set α} [OrdConnected s] : OrdConnected (ofDual ⁻¹' s) := dual_ordConnected_iff.2 ‹_› #align set.dual_ord_connected Set.dual_ordConnected -/ end Preorder section PartialOrder variable {α : Type _} [PartialOrder α] {s : Set α} #print IsAntichain.ordConnected /- protected theorem IsAntichain.ordConnected (hs : IsAntichain (· ≤ ·) s) : s.OrdConnected := ⟨fun x hx y hy z hz => by obtain rfl := hs.eq hx hy (hz.1.trans hz.2) rw [Icc_self, mem_singleton_iff] at hz rwa [hz]⟩ #align is_antichain.ord_connected IsAntichain.ordConnected -/ end PartialOrder section LinearOrder variable {α : Type _} [LinearOrder α] {s : Set α} {x : α} #print Set.ordConnected_uIcc /- @[instance] theorem ordConnected_uIcc {a b : α} : OrdConnected [a, b] := ordConnected_Icc #align set.ord_connected_uIcc Set.ordConnected_uIcc -/ #print Set.ordConnected_uIoc /- @[instance] theorem ordConnected_uIoc {a b : α} : OrdConnected (Ι a b) := ordConnected_Ioc #align set.ord_connected_uIoc Set.ordConnected_uIoc -/ #print Set.OrdConnected.uIcc_subset /- theorem OrdConnected.uIcc_subset (hs : OrdConnected s) ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s) : [x, y] ⊆ s := hs.out (min_rec' (· ∈ s) hx hy) (max_rec' (· ∈ s) hx hy) #align set.ord_connected.uIcc_subset Set.OrdConnected.uIcc_subset -/ #print Set.OrdConnected.uIoc_subset /- theorem OrdConnected.uIoc_subset (hs : OrdConnected s) ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s) : Ι x y ⊆ s := Ioc_subset_Icc_self.trans <| hs.uIcc_subset hx hy #align set.ord_connected.uIoc_subset Set.OrdConnected.uIoc_subset -/ #print Set.ordConnected_iff_uIcc_subset /- theorem ordConnected_iff_uIcc_subset : OrdConnected s ↔ ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), [x, y] ⊆ s := ⟨fun h => h.uIcc_subset, fun H => ⟨fun x hx y hy => Icc_subset_uIcc.trans <| H hx hy⟩⟩ #align set.ord_connected_iff_uIcc_subset Set.ordConnected_iff_uIcc_subset -/ #print Set.ordConnected_of_uIcc_subset_left /- theorem ordConnected_of_uIcc_subset_left (h : ∀ y ∈ s, [x, y] ⊆ s) : OrdConnected s := ordConnected_iff_uIcc_subset.2 fun y hy z hz => calc [y, z] ⊆ [y, x] ∪ [x, z] := uIcc_subset_uIcc_union_uIcc _ = [x, y] ∪ [x, z] := by rw [uIcc_comm] _ ⊆ s := union_subset (h y hy) (h z hz) #align set.ord_connected_of_uIcc_subset_left Set.ordConnected_of_uIcc_subset_left -/ #print Set.ordConnected_iff_uIcc_subset_left /- theorem ordConnected_iff_uIcc_subset_left (hx : x ∈ s) : OrdConnected s ↔ ∀ ⦃y⦄, y ∈ s → [x, y] ⊆ s := ⟨fun hs => hs.uIcc_subset hx, ordConnected_of_uIcc_subset_left⟩ #align set.ord_connected_iff_uIcc_subset_left Set.ordConnected_iff_uIcc_subset_left -/ #print Set.ordConnected_iff_uIcc_subset_right /- theorem ordConnected_iff_uIcc_subset_right (hx : x ∈ s) : OrdConnected s ↔ ∀ ⦃y⦄, y ∈ s → [y, x] ⊆ s := by simp_rw [ord_connected_iff_uIcc_subset_left hx, uIcc_comm] #align set.ord_connected_iff_uIcc_subset_right Set.ordConnected_iff_uIcc_subset_right -/ end LinearOrder end Set
\documentclass{article} \usepackage{amsmath,amssymb} \usepackage{hyperref} \usepackage{graphicx} \usepackage{listings} \title{\bf{Turbine Formulation}} \author{Nicholas Malaya, Roy Stogner, Robert D. Moser \\ Institute for Computational Engineering and Sciences \\ University of Texas at Austin} \date{} \begin{document} \maketitle \newpage \section{Turbine Definitions} The normal in the blade's velocity direction is, \begin{equation} n_B = \frac{u_B}{||u_B||}. \end{equation} Where $u_B$ is the blade velocity and is specified. The normal in the fan vertical direction is also set, and is typically, \begin{equation} n_v = \left(0,0,1\right) \end{equation} e.g. pointing ``up''. Then the normal in the radial direction must be, \begin{equation} n_r = n_B \times n_v. \end{equation} % The fan-wing-plane bit means that we're only looking at the projection % of velocity into the plane that's defined by the base velocity and % vertical direction. % (01:03:44 PM) Roy Stogner: The "local relative velocity" means that % we're taking the velocity not in the reference frame of the domain, but % in the reference frame of the wing. So if the base velocity is U_B and % the air velocity is U, then the local relative velocity is U - U_B. % (01:04:25 PM) Roy Stogner: Note that we simplify that equation a tiny % bit by using the fact that U_B and N_R are perpendicular. Then, the fan-wing-plane component (e.g. the plane perpendicular to the radius) of local relative velocity is \begin{equation} u_p = u - (u\cdot n_r)\cdot n_r - u_B. \end{equation} We can now define the lift and drag normals, where the direction opposing drag is, \begin{equation} n_{\text{drag}} = \frac{u_p}{||u_p||} \end{equation} and the direction opposing lift orthogonal to the drag and the radial direction, \begin{equation} n_{\text{lift}}= n_{\text{drag}} \times n_r. \end{equation} Now the ``forward velocity'' in the reference frame of the turbine is, \begin{equation} u_{\text{fwd}}= -u_p \cdot n_B \end{equation} and the ``upward'' velocity in this frame is, \begin{equation} u_{\text{up}} = u_p \cdot n_v. \end{equation} Finally, we can specify the angle with respect to the fan velocity direction as, \begin{equation} \theta_f = \text{atan2}\left(\frac{u_{\text{up}}}{u_{\text{fwd}}}\right) %\theta_f = \text{tan}^{-1}\left(\frac{u_{\text{up}}}{u_{\text{fwd}}}\right) \end{equation} while the angle with respect to the chord is this with the addition of the angle of attack of the blade, \begin{equation} \theta = \theta_f + \alpha(r). \end{equation} Now, we only need the drag polars in order to fully specify the force on the blades. \newpage \section{Drag Polars} We have been provided lift and drag as a function of angle of attack for two cases, the flat plate and semi-circle turbine blades. For the flat plate, the drag polars are specified as, \begin{lstlisting} theta := ((t+pi/2)%pi)-pi/2; lift = 'if(abs(theta)<pi/24,theta*9,sin(2*theta))' drag = 'if(abs(theta)<pi/24,0.005+theta*theta*81/25,1-0.8*cos(2*theta))' \end{lstlisting} for example. \begin{figure}[!htb] \begin{center} \includegraphics[width = 12 cm]{figs/flat} \caption{The flat plate interpolation.} \label{flat} \end{center} \end{figure} As shown in Figure \ref{flat}, the fit is largely accurate. The semi-circular plots are more complicated. Here, we use a high order polynomial fit to continuously interpolate between drag polars. This results in a \begin{figure}[!htb] \begin{center} \includegraphics[width = 12 cm]{figs/semi} \caption{The semi-circular plate interpolation.} \label{semi} \end{center} \end{figure} As shown in Figure \ref{semi}, the fit is decent, but not remarkably accurate. Then, the force on the turbine is, \begin{equation} \boxed{F = \frac{1}{2}\frac{\rho u_p^2 C}{A}\left(C_l \cdot n_\text{lift} + C_d \cdot n_\text{drag} \right)} \end{equation} Where C is the chord length (specified as input), and A is the area, which is also specified. For instance, the area swept might be, \begin{lstlisting} area_swept = '{r:=sqrt(x^2+y^2); 2*pi*r*(.6-.4)/4}' \end{lstlisting} for a 4 blade fan. The chord is specified similarly, for instance, \begin{lstlisting} chord_length = '.2*sqrt(2)' \end{lstlisting} would set a 0.28 meter chord length. % % --------------------------------------------------- % old turbine discussion: % --------------------------------------------------- % The penalty function will be added to the navier-stokes as, % % \begin{align} % % \partial_t(\rho u) = \text{NS} &+ \frac{1}{\epsilon}(u-u_t)\cdot n_p \\ % % &+ \frac{1}{\epsilon}(u-\omega u_t)\cdot n_p \\ % % \end{align} % \begin{align} % \partial_t(\rho u) = \text{NS} + \frac{1}{\epsilon}(u-\omega u_t)\cdot n_p % \end{align} % We will start by formulating a constant rotation speed % turbine. The rotor will have counter-clockwise spin with angular % velocity omega. % \begin{verbatim} % base_velocity= % '{(r<r_max)*(z<zmax) * r * -sin(theta)*omega} % {(r<r_max)*(z<zmax) * r * cos(theta)*omega} % {0}' % \end{verbatim} % There are a few problems with this formulation. One, in a turbine, the % fluid velocity is not necessarily identical to the blade velocity. % The turbine speed can take a range of values, and is often quoted as the % `tip-speed ratio'', $\lambda$, which is, % \begin{equation} % \lambda = \frac{\omega R}{v}. % \end{equation} % Here, R is the radius of the turbine blades, omega the angular velocity, % and v is the velocity of the fluid. Values for $\lambda$ generate power % in the range of 0-16, and are typically between 4 and 14. % Zmax will be the height of the vanes, which is approximately 0.84 meters in the laboratory, % and 1.0795 meters for the two-meter SoV configuration. Rmax will be the inner diameter of the vanes. % % --------------------------------------------------- % old discussion on determining the rotation speed: % --------------------------------------------------- % We now need to choose $\omega$. At the Betz limit, the velocities will be % $V_{\text{out}}/V_{\text{in}} = 1/3$. Furthermore, the control volume % analysis implies that, % \begin{equation} % V_{\text{turbine}} = \frac{1}{2}\left(V_{\text{in}} + V_{\text{out}} \right) % \end{equation} % then, % \begin{align} % V_{\text{turbine}} &= \left(\frac{1}{2}\right) \left(\frac{4}{3}\right) V_{\text{in}} \\ % &= \frac{2}{3} V_{\text{in}}. % \end{align} % Note this is not the velocity of the turbine, but the velocity of the % fluid around the turbine. We can estimate the turbine speed from the % ``tip-speed ratio'', $\lambda$, which is, % \begin{equation} % \lambda = \frac{\omega R}{v}. % \end{equation} % Here, R is the radius of the turbine blades, omega the angular velocity, % and v is the velocity of the fluid. Values for $\lambda$ generate power % in the range of 0-16, and are typically between 4 and 14. Thus, our % angular velocity of the turbine is, % \begin{equation} % \omega = \frac{ 2 V_{\text{in}}\lambda}{3 R_{\text{max}}}. % \end{equation} % --------------------------------------------------- % refs % --------------------------------------------------- % % https://github.com/grinsfem/grins/tree/master/src/physics/src % https://github.com/grinsfem/grins/blob/master/src/physics/src/averaged_fan.C % https://github.com/grinsfem/grins/blob/master/src/physics/src/averaged_fan_base.C#L120 % https://github.com/grinsfem/grins/blob/3f86653ab5ba01981193ccce142ea196d0a192de/src/physics/src/averaged_fan_base.C % https://github.com/grinsfem/grins/blob/34e2fc1e7d7143e0080f81c67bd584ce1236e2c1/src/physics/include/grins/averaged_fan.h % https://github.com/grinsfem/grins/blob/34e2fc1e7d7143e0080f81c67bd584ce1236e2c1/src/physics/include/grins/averaged_fan_base.h % \end{document}
The rebellion against the government of Porfirio Díaz broke out in late 1910 , after Díaz had his rival Francisco Madero imprisoned and had announced his own victory in a falsified election . Madero 's earlier vague promises of agrarian reforms had attracted many supporters . He himself escaped from prison and fled to Texas , from where he issued his famous Plan of San Luis Potosí . This manifesto called for an armed uprising against the <unk> and establishment of free and democratic elections . As a response to Madero 's proclamation , violent clashes began throughout Mexico in November 1910 .
module UselessAbstractAbstract where A : Set₁ abstract abstract A = Set
// Copyright (C) 2013 by Glyn Matthews // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef NETWORK_HTTP_V2_CLIENT_CONNECTION_SSL_CONNECTION_INC #define NETWORK_HTTP_V2_CLIENT_CONNECTION_SSL_CONNECTION_INC /** * \file * \brief */ #include <memory> #include <vector> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/io_service.hpp> #include <boost/asio/ssl.hpp> #include <boost/asio/placeholders.hpp> #include <network/config.hpp> #include <network/http/v2/client/connection/connection.hpp> #include <network/http/v2/client/client.hpp> namespace network { namespace http { namespace v2 { namespace client_connection { class ssl_connection : public connection, std::enable_shared_from_this<ssl_connection> { ssl_connection(const ssl_connection &) = delete; ssl_connection &operator = (const ssl_connection &) = delete; public: ssl_connection(boost::asio::io_service &io_service, const client_options &options) : io_service_(io_service) , options_(options) { } virtual ~ssl_connection() noexcept { } virtual void async_connect(const boost::asio::ip::tcp::endpoint &endpoint, connect_callback callback) { context_.reset(new boost::asio::ssl::context(boost::asio::ssl::context::sslv23)); std::vector<std::string> const& certificate_paths = options_.openssl_certificate_paths(); std::vector<std::string> const& verifier_paths = options_.openssl_verify_paths(); bool use_default_verification = certificate_paths.empty() && verifier_paths.empty(); if (!use_default_verification) { for (auto path : certificate_paths) { context_->load_verify_file(path); } for (auto path : verifier_paths) { context_->add_verify_path(path); } context_->set_verify_mode(boost::asio::ssl::context::verify_peer); //context_->set_verify_callback(boost::asio::ssl::rfc2818_verification(host)); } else { context_->set_default_verify_paths(); context_->set_verify_mode(boost::asio::ssl::context::verify_none); } socket_.reset(new boost::asio::ssl::stream< boost::asio::ip::tcp::socket>(io_service_, *context_)); using namespace std::placeholders; socket_->lowest_layer() .async_connect(endpoint, callback); } virtual void async_write(boost::asio::streambuf &command_streambuf, write_callback callback) { boost::asio::async_write(*socket_, command_streambuf, callback); } virtual void async_read_some(const boost::asio::mutable_buffers_1 &read_buffer, read_callback callback) { socket_->async_read_some(read_buffer, callback); } virtual void cancel() { //socket_->cancel(); } private: boost::asio::io_service &io_service_; client_options options_; std::unique_ptr<boost::asio::ssl::context> context_; std::unique_ptr< boost::asio::ssl::stream<boost::asio::ip::tcp::socket>> socket_; }; } // namespace client_connection } // namespace v2 } // namespace http } // namespace network #endif // NETWORK_HTTP_V2_CLIENT_CONNECTION_SSL_CONNECTION_INC
# Simulate some kind of explosion. # This program will generate two plots. # Load the only necessary library to complete this simulation: library(ggplot2) # Number of particles to simulate n=200 # Simulates a vector explosion bigbang<-data.frame("x"=rnorm(n),"y"=rnorm(n)) bigbang$dx<-bigbang$x*.1+.05*rnorm(n) bigbang$dy<-bigbang$y*.1+.05*rnorm(n) bigbang$speed=sqrt(bigbang$dx^2+bigbang$dy^2) bigbang$dist=sqrt(bigbang$x^2+bigbang$y^2) ggplot(bigbang)+ geom_point(aes(x=x,y=y),size=1)+ geom_segment(color="steelblue",aes(x=x,y=y,xend=x+dx,yend=y+dy),arrow=arrow(length=unit(.1,"cm")))+ geom_point(aes(x=0,y=0),color="red",shape=3)+ ggtitle("Particle Speeds after an Explosion") ggplot(bigbang,aes(dist,speed))+ geom_point(size=1)+ geom_smooth(method=lm,se=F,formula=y~x+0,linetype=4,size=1)+ ylab("Speed of Particle")+ xlab("Distance of Particle from Center")+ ggtitle("Particle Speeds after an Explosion")
import client.EEGLABChat; import client.VisualToolbar; import java.awt.*; import javax.swing.*; tb = VisualToolbar(); F = gcf; tb.setPreferredSize(Dimension(0, 75)); javacomponent(tb,'South',F); refresh(F);
% Copyright 2015-2016 Dan Foreman-Mackey and the co-authors listed below. \documentclass[manuscript, letterpaper]{aastex} \pdfoutput=1 \include{vc} \include{figures/abctoy} \usepackage{microtype} \usepackage{url} \usepackage{amssymb,amsmath} \usepackage{natbib} \usepackage{multirow} \bibliographystyle{aasjournal} % ----------------------------------- % % start of AASTeX mods by DWH and DFM % % ----------------------------------- % \setlength{\voffset}{0in} \setlength{\hoffset}{0in} \setlength{\textwidth}{6in} \setlength{\textheight}{9in} \setlength{\headheight}{0ex} \setlength{\headsep}{\baselinestretch\baselineskip} % this is 2 lines in ``manuscript'' \setlength{\footnotesep}{0in} \setlength{\topmargin}{-\headsep} \setlength{\oddsidemargin}{0.25in} \setlength{\evensidemargin}{0.25in} \linespread{0.54} % close to 10/13 spacing in ``manuscript'' \setlength{\parindent}{0.54\baselineskip} \hypersetup{colorlinks = false} \makeatletter % you know you are living your life wrong when you need to do this \long\def\frontmatter@title@above{ \vspace*{-\headsep}\vspace*{\headheight} \noindent\footnotesize {\noindent\footnotesize\textsc{\@journalinfo}}\par {\noindent\scriptsize Preprint typeset using \LaTeX\ style AASTeX6\\ With modifications by David W. Hogg and Daniel Foreman-Mackey }\par\vspace*{-\baselineskip}\vspace*{0.625in} }% \makeatother % Section spacing: \makeatletter \let\origsection\section \renewcommand\section{\@ifstar{\starsection}{\nostarsection}} \newcommand\nostarsection[1]{\sectionprelude\origsection{#1}} \newcommand\starsection[1]{\sectionprelude\origsection*{#1}} \newcommand\sectionprelude{\vspace{1em}} \let\origsubsection\subsection \renewcommand\subsection{\@ifstar{\starsubsection}{\nostarsubsection}} \newcommand\nostarsubsection[1]{\subsectionprelude\origsubsection{#1}} \newcommand\starsubsection[1]{\subsectionprelude\origsubsection*{#1}} \newcommand\subsectionprelude{\vspace{1em}} \makeatother \widowpenalty=10000 \clubpenalty=10000 \sloppy\sloppypar % ------------------ % % end of AASTeX mods % % ------------------ % % Projects: \newcommand{\project}[1]{\textsl{#1}} \newcommand{\kepler}{\project{Kepler}} \newcommand{\ktwo}{\project{K2}} \newcommand{\tess}{\project{TESS}} \newcommand{\plato}{\project{PLATO}} \newcommand{\gaia}{\project{Gaia}} \newcommand{\accronym}[1]{\textsc{#1}} \newcommand{\foreign}[1]{\emph{#1}} \newcommand{\etal}{\foreign{et\,al.}} \newcommand{\etc}{\foreign{etc.}} \newcommand{\dfmfigref}[1]{\ref{fig:#1}} \newcommand{\dfmFig}[1]{Figure~\dfmfigref{#1}} \newcommand{\dfmfig}[1]{\dfmFig{#1}} \newcommand{\dfmfiglabel}[1]{\label{fig:#1}} % \newcommand{\Tab}[1]{Table~\ref{tab:#1}} % \newcommand{\tab}[1]{\Tab{#1}} \newcommand{\tablabel}[1]{\label{tab:#1}} \renewcommand{\eqref}[1]{\ref{eq:#1}} \newcommand{\Eq}[1]{Equation~(\eqref{#1})} \newcommand{\eq}[1]{\Eq{#1}} \newcommand{\eqalt}[1]{Equation~\eqref{#1}} \newcommand{\eqlabel}[1]{\label{eq:#1}} \newcommand{\sectionname}{Section} \newcommand{\sectref}[1]{\ref{sect:#1}} \newcommand{\Sect}[1]{\sectionname~\sectref{#1}} \newcommand{\sect}[1]{\Sect{#1}} \newcommand{\sectalt}[1]{\sectref{#1}} \newcommand{\App}[1]{Appendix~\sectref{#1}} \newcommand{\app}[1]{\App{#1}} \newcommand{\sectlabel}[1]{\label{sect:#1}} \newcommand{\T}{\ensuremath{\mathrm{T}}} \newcommand{\dd}{\ensuremath{\,\mathrm{d}}} \newcommand{\unit}[1]{{\ensuremath{\,\mathrm{#1}}}} \newcommand{\bvec}[1]{{\ensuremath{\boldsymbol{#1}}}} \newcommand{\appropto}{\mathrel{\vcenter{ \offinterlineskip\halign{\hfil$##$\cr \propto\cr\noalign{\kern2pt}\sim\cr\noalign{\kern-2pt}}}}} \newcommand{\densityunit}{{\ensuremath{\mathrm{nat}^{-2}}}} % TO DOS \newcommand{\todo}[3]{{\color{#2}\emph{#1}: #3}} \newcommand{\dfmtodo}[1]{\todo{DFM}{red}{#1}} \newcommand{\tdmtodo}[1]{\todo{TDM}{blue}{#1}} \newcommand{\hoggtodo}[1]{\todo{HOGG}{blue}{#1}} % Response \newcommand{\response}[1]{{\color{blue}#1}} % Helpers for this paper: \newcommand{\license}{MIT License} \newcommand{\paper}{paper} % Notation for this paper: \newcommand{\obs}{{\ensuremath{\mathrm{obs}}}} \newcommand{\simu}{{\ensuremath{\mathrm{sim}}}} \def\abc{Approximate Bayesian Computation (\accronym{abc})\def\abc{\accronym{abc}}} \def\mcmc{Markov Chain Monte Carlo (\accronym{mcmc})\def\mcmc{\accronym{mcmc}}} \newcommand{\datareleaseurl}{TBD} % \shorttitle{The population of long-period transiting exoplanets} % \shortauthors{Foreman-Mackey, Morton, Hogg, \etal} % \submitted{Submitted to \textit{The Astrophysical Journal}} \begin{document} \title{% \vspace{\baselineskip} Approximate Bayesian Computation of the population of exoplanets \vspace{-2\baselineskip} % OMG AASTEX6 IS SO BROKEN } \newcounter{affilcounter} \altaffiltext{1}{\textsf{[email protected]}; Sagan Fellow} \setcounter{affilcounter}{2} \edef \uw {\arabic{affilcounter}}\stepcounter{affilcounter} \altaffiltext{\uw} {Astronomy Department, University of Washington, Seattle, WA, 98195, USA} \author{% Daniel~Foreman-Mackey\altaffilmark{1,\uw}, and friends \vspace{\baselineskip} } \begin{abstract} The \kepler\ Mission was designed to statistical questions about the population of exoplanets. So far, all occurrence rate and distribution results have required either strong modeling assumptions or heuristic (qualitative) inference methods. We present a general method of occurrence rate measurement using Approximate Bayesian Computation (ABC). ABC allows rigorous posterior inference of population parameters without computing a likelihood function. Instead, we only need to be able to simulate representative data sets. We demonstrate the importance of this method on a simple toy problem with a tractable likelihood function and then apply the method to a catalog of exoplanet discoveries from the \kepler\ Mission to simultaneously measure the occurrence rate and period, size, multiplicity, and mutual inclination distributions. \end{abstract} \keywords{% methods: data analysis --- methods: statistical --- catalogs --- planetary systems --- stars: statistics } \clearpage \section{Introduction} \begin{itemize} \item Exoplanet populations \item Why \abc? Which problems? Limitations of current methods. \end{itemize} \section{A motivating example: inference with a Poisson process} A standard problem in the astronomy literature that can~--~and has been~--~solved using \abc\ is the situation where we have a procedure for simulating a population of objects that we then want to compare to the observed population. For example, in the exoplanet literature, this is the case for most studies of the multiplicity distribution of exoplanets; it is easy to simulate and observe a population of exoplanetary systems with a given multiplicity distribution \citep[for example][]{Fang:2012, Ballard:2016} \dfmtodo{CITE Jack} but it is difficult to write down an analytic or otherwise tractable likelihood function without making strong assumptions \citep[for example]{Tremaine:2012}. It is common practice in this field to use the simulator to do inference by comparing the simulations to the observed distributions using a heuristic ``likelihood function''. For example, \citet{Ballard:2016} (\dfmtodo{Others?}) draw a realization of the observed multiplicity distribution from the model and then compare this to the data by computing the Poisson likelihood of the observations but treating the simulated number as the expected rate. In other words, for each bin $k$ in multiplicity, they compute a likelihood: \begin{eqnarray}\eqlabel{heuristic-likelihood} p(N_{\obs,k}\mid\theta) &=& \frac{N_{\simu,k}(\theta)^{N_{\obs,k}}\, \exp\left[-N_{\simu,k}(\theta)\right]}{N_{\obs,k}!} \end{eqnarray} where $N_{\simu,k} \sim p(N_{\simu,k}\mid\theta)$ is the simulated number of systems with $k$ transiting planets. This might seem intuitive but, as we will demonstrate shortly, it is not valid even if the underlying process is actually Poisson and using a model like this will lead to incorrect inferences. To demonstrate the issues with this method, let's start with the simplest toy problem: a single observation of a Poisson process. In this case, the correct posterior inference can be performed because the correct likelihood is analytically tractable. The generative model is \begin{eqnarray} N_\obs &\sim& p(N_\obs\mid\mu) = \frac{\mu^{N_\obs}\,e^{-\mu}}{N_\obs!} \end{eqnarray} with a single parameter $\mu$. Placing a uniform prior on $\log\mu$ between $\mu_\mathrm{min}$ and $\mu_\mathrm{max}$, the posterior probability becomes \begin{eqnarray}\eqlabel{exact-posterior} p(\mu\mid N_\obs) \propto \left\{\begin{array}{ll} \frac{1}{\mu}\frac{\mu^{N_\obs}\,e^{-\mu}}{N_\obs!}\quad & \quad \mathrm{if}\,\mu_\mathrm{min} \le \mu \le \mu_\mathrm{max} \\ 0 \quad & \quad \mathrm{otherwise} \end{array}\right. \quad. \end{eqnarray} To test the methods, we generated a simulated ``data set'' of $N_\obs = \abctoynobs$ from a Poisson process with $\mu_\mathrm{true} = \abctoytruth$. Using this simulated data, \dfmfig{abctoy} compares the inferences made using \eq{heuristic-likelihood} to the exact posterior inference using \eq{exact-posterior} and to inferences made using \abc\ with a pseudo-likelihood (the details will be given in the following section) \begin{eqnarray}\eqlabel{pseudo-likelihood} p(N_\obs\mid\mu) &=& \int K(N_\simu,\,N_\obs;\,\epsilon)\, p(N_\simu\mid\mu) \dd N_\simu \end{eqnarray} where \begin{eqnarray} p(N_\simu\mid\mu) &=& \frac{\mu^{N_\simu}\,e^{-\mu}}{N_\simu!} \end{eqnarray} is the generative model. For this demonstration, we use a Gaussian kernel \begin{eqnarray} K(N_\simu,\,N_\obs;\,\epsilon) \propto \exp\left( -\frac{(N_\simu - N_\obs)^2}{2\,\epsilon^2} \right) \end{eqnarray} with $\epsilon \equiv \abctoyeps$. The pseudo-likelihood is computed numerically as \begin{eqnarray} p(N_\obs\mid\mu) &\approx& \frac{1}{S}\sum_{s=1}^S K({N_\simu}^{(s)},\,N_\obs;\,\epsilon) \end{eqnarray} for ${N_\simu}^{(s)} \sim \mathrm{Pois}(\mu)$ and $S = \abctoyS$. From \dfmfig{abctoy}, it is clear that the \abc\ inference correctly recovers the exact posterior while the heuristic method underestimates the mean of the posterior and overestimates the variance. In practice, this inconsistency increases when the true underlying distribution is no longer Poisson. The main point of this demonstration is that the heuristic method commonly used to do inference with stochastic population models is not sufficient if we want to do rigorous quantitative population inference. Instead, \abc\ can be used to capture the exact posterior. \begin{figure*}[p]~\\ \begin{center} \includegraphics{figures/abctoy.pdf} \end{center} \caption{% A comparison between a commonly used heuristic method for doing inference with stochastic models and \abc. The blue histogram shows the posterior inference for the rate parameter $\mu$ using the heuristic likelihood function from \eq{heuristic-likelihood}, the orange histogram shows the \abc\ inference using the pseudo-likelihood from \eq{pseudo-likelihood}, and the black curve shows the exact posterior from \eq{exact-posterior}. The vertical gray line shows the true value of $\mu$ that was used to generate the data. \dfmfiglabel{abctoy}} \end{figure*} \section{A short introduction to Approximate Bayesian Computation} The problem statement for \abc\ is that you have a method of (stochastically) simulating representative data from the model given a set of parameters but it is computationally intractable to compute the likelihood of a given data set conditioned on these same parameters. In other words, you can sample $D_\simu \sim p(D_\simu\mid\theta)$ but you can't directly evaluate $p(D_\obs\mid\theta)$ for any values $D_\obs$ and $\theta$. This means that you can't use standard \mcmc\ methods to draw samples from the posterior probability $p(\theta\mid D_\obs) \propto p(D_\obs\mid\theta)\,p(\theta)$. To motivate \abc, let's start with an extreme method. Let's say that sample a set of parameters $\theta \sim p(\theta)$ from your prior and then simulate some data $D_\simu$ that just happens to \emph{exactly} match the observed data $D_\obs$. In this case, under your simulation model, this value of $\theta$ is a valid sample from the posterior probability density $p(\theta\mid D_\obs)$ even though you never evaluated the likelihood. Now if you had an infinite amount of computing power and could draw a huge number of samples following this procedure and rejecting all samples that don't result in an exact match for your data then you could produce a posterior sampling for $p(\theta\mid D_\obs)$ without ever evaluating the likelihood. Of course this method is absurd and intractable so \abc\ builds on this using two observations \begin{enumerate} \item This method will still be correct if sufficient statistics of the simulated data match the same sufficient statistics on the observed data. \item The comparison between the simulation and the observation can be ``softened'' without significant loss of information. \end{enumerate} The first point is correct by definition but we will return to the relevant subtleties below. The second point is less obvious. \begin{itemize} \item Qualitative justification. \item Theoretical basis. \item Methodological questions: (a) sufficient statistics, (b) distance function, (c) inference algorithm. \end{itemize} \section{The occurrence rate of small and cool exoplanets} \begin{itemize} \item Sample selection \citep{Burke:2015}. \item Generative model: power laws, discussion of Poisson process. \item Observation model: \citep{Christiansen:2013,Christiansen:2015,Burke:2015} \item Statistics, distance metric \item Inference method: PMC, MCMC, etc. \item Results: compare to \citet{Burke:2015} \end{itemize} \section{The multiplicity \& mutual inclination of exoplanetary systems} \begin{itemize} \item Sample selection: looks as a function of stellar type. \item Generative model: more flexible than power laws. \item Observation model: calibrating the completeness and caveats: CITE Christiansen note \item Inference method: PMC, MCMC, etc. \item Results \end{itemize} \section{The potential impact of Approximate Bayesian Computation} \begin{itemize} \item More general generative models means fewer and weaker assumptions. \item False positives. \item Physical models. \end{itemize} \vspace{1.5em} All of the code used in this project is available from \url{https://github.com/dfm/exoabc} under the MIT open-source software license. This code (plus some dependencies) can be run to re-generate all of the figures and results in this \paper; this version of the paper was generated with git commit \texttt{\githash} (\gitdate). % \acknowledgments \vspace{1.5em} DFM would like to thank Jessi Cisewski for introducing him and the SAMSI exoplanet populations working group to the method of \abc. It is a pleasure to also thank Eric Agol, Eric Ford, David Hogg, and Richard Wilkinson, for helpful discussions and contributions. \dfmtodo{Thank SAMSI.} This research made use of the NASA \project{Astrophysics Data System} and the NASA Exoplanet Archive. The Exoplanet Archive is operated by the California Institute of Technology, under contract with NASA under the Exoplanet Exploration Program. This \paper\ includes data collected by the \kepler\ mission. Funding for the \kepler\ mission is provided by the NASA Science Mission directorate. We are grateful to the entire \kepler\ team, past and present. Their tireless efforts were all essential to the tremendous success of the mission and the successes of \ktwo, present and future. These data were obtained from the Mikulski Archive for Space Telescopes (MAST). STScI is operated by the Association of Universities for Research in Astronomy, Inc., under NASA contract NAS5-26555. Support for MAST is provided by the NASA Office of Space Science via grant NNX13AC07G and by other grants and contracts. Computing resources were provided by High Performance Computing at New York University. \facility{Kepler} \software{% \project{corner.py} \citep{Foreman-Mackey:2016}, \project{matplotlib} \citep{Hunter:2007}, \project{numpy} \citep{Van-Der-Walt:2011}, \project{scipy} \citep{Jones:2001} } % \newpage % \appendix % \section{Appendix} \bibliography{exoabc} \end{document}
subroutine NODEAVERAGE( & coarse & ,icoarselo0,icoarselo1 & ,icoarsehi0,icoarsehi1 & ,ncoarsecomp & ,fine & ,ifinelo0,ifinelo1 & ,ifinehi0,ifinehi1 & ,nfinecomp & ,iblo0,iblo1 & ,ibhi0,ibhi1 & ,ref_ratio & ,weight & ,iweightlo0,iweightlo1 & ,iweighthi0,iweighthi1 & ,nweightcomp & ) implicit none integer*8 ch_flops COMMON/ch_timer/ ch_flops integer ncoarsecomp integer icoarselo0,icoarselo1 integer icoarsehi0,icoarsehi1 REAL*8 coarse( & icoarselo0:icoarsehi0, & icoarselo1:icoarsehi1, & 0:ncoarsecomp-1) integer nfinecomp integer ifinelo0,ifinelo1 integer ifinehi0,ifinehi1 REAL*8 fine( & ifinelo0:ifinehi0, & ifinelo1:ifinehi1, & 0:nfinecomp-1) integer iblo0,iblo1 integer ibhi0,ibhi1 integer ref_ratio integer nweightcomp integer iweightlo0,iweightlo1 integer iweighthi0,iweighthi1 REAL*8 weight( & iweightlo0:iweighthi0, & iweightlo1:iweighthi1, & 0:nweightcomp-1) integer var integer icrse0,icrse1 integer ifine0,ifine1 integer ii0,ii1 REAL*8 csum do var = 0, ncoarsecomp - 1 do icrse1 = iblo1,ibhi1 do icrse0 = iblo0,ibhi0 csum = 0 do ii1 = iweightlo1,iweighthi1 do ii0 = iweightlo0,iweighthi0 ifine0 = icrse0*ref_ratio + ii0 ifine1 = icrse1*ref_ratio + ii1 csum = csum + weight( ii0,ii1, 0) * & fine( ifine0,ifine1, var ) enddo enddo coarse( icrse0,icrse1, var ) = csum enddo enddo end do return end subroutine NODEAVERAGEPOINT( & coarse & ,icoarselo0,icoarselo1 & ,icoarsehi0,icoarsehi1 & ,ncoarsecomp & ,fine & ,ifinelo0,ifinelo1 & ,ifinehi0,ifinehi1 & ,nfinecomp & ,pcrse & ,ref_ratio & ,weight & ,iweightlo0,iweightlo1 & ,iweighthi0,iweighthi1 & ,nweightcomp & ) implicit none integer*8 ch_flops COMMON/ch_timer/ ch_flops integer ncoarsecomp integer icoarselo0,icoarselo1 integer icoarsehi0,icoarsehi1 REAL*8 coarse( & icoarselo0:icoarsehi0, & icoarselo1:icoarsehi1, & 0:ncoarsecomp-1) integer nfinecomp integer ifinelo0,ifinelo1 integer ifinehi0,ifinehi1 REAL*8 fine( & ifinelo0:ifinehi0, & ifinelo1:ifinehi1, & 0:nfinecomp-1) integer pcrse(0:1) integer ref_ratio integer nweightcomp integer iweightlo0,iweightlo1 integer iweighthi0,iweighthi1 REAL*8 weight( & iweightlo0:iweighthi0, & iweightlo1:iweighthi1, & 0:nweightcomp-1) integer var integer ifine0,ifine1 integer ii0,ii1 REAL*8 csum, weightpt, finept do var = 0, ncoarsecomp - 1 csum = 0 do ii1 = iweightlo1,iweighthi1 do ii0 = iweightlo0,iweighthi0 ifine0 = pcrse(0)*ref_ratio + ii0 ifine1 = pcrse(1)*ref_ratio + ii1 weightpt = weight( ii0,ii1, 0) finept = fine( ifine0,ifine1, var ) csum = csum + weightpt*finept enddo enddo coarse(pcrse(0),pcrse(1), var ) = csum end do return end subroutine NODEAVERAGE_GETWEIGHTS( & weight & ,iweightlo0,iweightlo1 & ,iweighthi0,iweighthi1 & ,nweightcomp & ,ref_ratio & ) implicit none integer*8 ch_flops COMMON/ch_timer/ ch_flops integer nweightcomp integer iweightlo0,iweightlo1 integer iweighthi0,iweighthi1 REAL*8 weight( & iweightlo0:iweighthi0, & iweightlo1:iweighthi1, & 0:nweightcomp-1) integer ref_ratio integer ext, nxtrm integer ii0,ii1 REAL*8 ref_scale ext = ref_ratio / 2 ref_scale = (1.0d0) / (ref_ratio**2) do ii1 = iweightlo1,iweighthi1 do ii0 = iweightlo0,iweighthi0 nxtrm = 0 if (iabs(ii0) .eq. ext) nxtrm = nxtrm + 1 if (iabs(ii1) .eq. ext) nxtrm = nxtrm + 1 weight( ii0,ii1, 0) = ref_scale * (0.500d0)**nxtrm enddo enddo return end
lemma pred_count_space_const2[measurable (raw)]: "f \<in> measurable M (count_space UNIV) \<Longrightarrow> Measurable.pred M (\<lambda>x. c = f x)"
!Crown Copyright 2012 AWE. ! ! This file is part of CloverLeaf. ! ! CloverLeaf is free software: you can redistribute it and/or modify it under ! the terms of the GNU General Public License as published by the ! Free Software Foundation, either version 3 of the License, or (at your option) ! any later version. ! ! CloverLeaf is distributed in the hope that it will be useful, but ! WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ! FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ! details. ! ! You should have received a copy of the GNU General Public License along with ! CloverLeaf. If not, see http://www.gnu.org/licenses/. !> @brief Driver for chunk initialisation. !> @author Wayne Gaudin !> @details Invokes the user specified chunk initialisation kernel. SUBROUTINE initialise_chunk(tile) USE clover_module USE initialise_chunk_kernel_module IMPLICIT NONE INTEGER :: tile REAL(KIND=8) :: xmin,ymin,dx,dy dx=(grid%xmax-grid%xmin)/float(grid%x_cells) dy=(grid%ymax-grid%ymin)/float(grid%y_cells) xmin=grid%xmin+dx*float(chunk%tiles(tile)%t_left-1) ymin=grid%ymin+dy*float(chunk%tiles(tile)%t_bottom-1) IF(use_fortran_kernels) THEN CALL initialise_chunk_kernel(chunk%tiles(tile)%t_xmin, & chunk%tiles(tile)%t_xmax, & chunk%tiles(tile)%t_ymin, & chunk%tiles(tile)%t_ymax, & xmin,ymin,dx,dy, & chunk%tiles(tile)%field%vertexx, & chunk%tiles(tile)%field%vertexdx, & chunk%tiles(tile)%field%vertexy, & chunk%tiles(tile)%field%vertexdy, & chunk%tiles(tile)%field%cellx, & chunk%tiles(tile)%field%celldx, & chunk%tiles(tile)%field%celly, & chunk%tiles(tile)%field%celldy, & chunk%tiles(tile)%field%volume, & chunk%tiles(tile)%field%xarea, & chunk%tiles(tile)%field%yarea ) ELSEIF(use_C_kernels) THEN CALL initialise_chunk_kernel_c(chunk%tiles(tile)%t_xmin, & chunk%tiles(tile)%t_xmax, & chunk%tiles(tile)%t_ymin, & chunk%tiles(tile)%t_ymax, & xmin,ymin,dx,dy, & chunk%tiles(tile)%field%vertexx, & chunk%tiles(tile)%field%vertexdx, & chunk%tiles(tile)%field%vertexy, & chunk%tiles(tile)%field%vertexdy, & chunk%tiles(tile)%field%cellx, & chunk%tiles(tile)%field%celldx, & chunk%tiles(tile)%field%celly, & chunk%tiles(tile)%field%celldy, & chunk%tiles(tile)%field%volume, & chunk%tiles(tile)%field%xarea, & chunk%tiles(tile)%field%yarea ) ENDIF END SUBROUTINE initialise_chunk