Datasets:
AI4M
/

text
stringlengths
0
3.34M
{-# OPTIONS --universe-polymorphism #-} module Categories.Functor.Diagonal where open import Data.Product open import Categories.Category open import Categories.Functor open import Categories.Product open import Categories.FunctorCategory open import Categories.Functor.Constant import Categories.Power as Power Δ : ∀ {o ℓ e} → (C : Category o ℓ e) → Functor C (Product C C) Δ C = record { F₀ = λ x → x , x ; F₁ = λ f → f , f ; identity = refl , refl ; homomorphism = refl , refl ; F-resp-≡ = λ x → x , x } where open Category C open Equiv Δ′ : ∀ {o ℓ e} → (I : Set) → (C : Category o ℓ e) → Functor C (Power.Exp C I) Δ′ I C = record { F₀ = λ x _ → x ; F₁ = λ f _ → f ; identity = λ _ → refl ; homomorphism = λ _ → refl ; F-resp-≡ = λ x _ → x } where open Power C open Category C open Equiv ΔF : ∀ {o ℓ e o₁ ℓ₁ e₁} {C : Category o ℓ e} (I : Category o₁ ℓ₁ e₁) → Functor C (Functors I C) ΔF {C = C} I = record { F₀ = λ c → Constant c ; F₁ = λ f → record { η = λ X → f; commute = λ g → trans C.identityʳ (sym C.identityˡ) } ; identity = refl ; homomorphism = refl ; F-resp-≡ = λ x → x } where module C = Category C open C.Equiv module I = Category I
function nlp_cvx_202_010( optimizer, objective_tol, primal_tol, dual_tol, termination_target = TERMINATION_TARGET_LOCAL, primal_target = PRIMAL_TARGET_LOCAL, ) # Test Goals: # - linear objective # - intersection convex quadratic constraints # Variants # 010 - one binding constraint (inflection point) # 011 - one binding constraint (inflection point) # 012 - one binding constraint (non-inflection point) # 013 - one binding constraint (non-inflection point) # 014 - intersection set model = Model(optimizer) @variable(model, x) @variable(model, y) @variable(model, z) @objective(model, Min, -z) @NLconstraint(model, x^2 + y^2 <= z) @NLconstraint(model, x^2 + y^2 <= -z + 1) optimize!(model) check_status(model, FEASIBLE_PROBLEM, termination_target, primal_target) check_objective(model, -1, tol = objective_tol) return check_solution([x, y, z], [0, 0, 1], tol = primal_tol) end
subroutine Initial_condition use variables implicit none real(8) :: kx,ky,eps,uhxx,uhyy,vhxx,vhyy,thewx,thewy,thewxy,taustar,taustarc,alphc,cainf!,ustar0 character :: dummy h=0.d0 ca=0.d0 u=0.d0 v=0.d0 iero=0.d0 Uc=0.d0 Ec=0.d0 Fc=0.d0 Cc=0.d0 Qxc=0.d0 Qyc=0.d0 Up=0.d0 Ep=0.d0 Fp=0.d0 Cp=0.d0 Qxp=0.d0 Qyp=0.d0 Zb=100.d0 select case (inittype) case(1) DO I=1,Nx+1 if(I<=Nx/2)then Zb(I,0:Ny+1)=Zb(I-1,0:Ny+1) !勾配0 else Zb(I,0:Ny+1)=Zb(I-1,0:Ny+1) !勾配0 endif ENDDO h(0:int(Nx/2),0:Ny+1)=0.5d0 h(int(Nx/2)+1:Nx+1,0:Ny+1)=0.05d0 Ca(0:Nx+1,0:Ny+1)=0.d0 case(2) DO I=1,Nx+1 if(I<=Nx/2)then Zb(I,0:Ny+1)=Zb(I-1,0:Ny+1)-sli*dx !勾配sliに設定 else Zb(I,0:Ny+1)=Zb(I-1,0:Ny+1)-sli*dx*0.01d0!*0.01d0 !勾配sliに設定 endif ENDDO h(1:Nx,1:Ny)=hup Ca(1:Nx,1:Ny)=Cup u(1:Nx,1:Ny)=Qup/Bini/hup v(1:Nx,1:Ny)=0.d0 case(3) DO I=1,Nx+1 ! Zb(I,0:Ny+1)=Zb(I-1,0:Ny+1)-sli*dx !勾配sliに設定 if(I<=Nx/2)then Zb(I,0:Ny+1)=Zb(I-1,0:Ny+1)-sli*dx !勾配sliに設定 else Zb(I,0:Ny+1)=Zb(I-1,0:Ny+1)-sli*dx*0.01d0!*0.01d0 !勾配sliに設定 endif ENDDO zbini=zb ! zb(101:105,11:20)=zb(101:105,11:20)+0.5d0 h(1:Nx,1:Ny)=hup ! h(1:int(Nx/2),1:Ny)=hup ! h(int(Nx/2)+1:Nx,1:Ny)=hdown ! h(101:105,11:20)=0.d0 Ca(0:Nx+1,0:Ny+1)=Cup u(1:Nx,1:Ny)=Qup/Bini/hup ! u(100:106,11:20)=0.d0 ! u(1:int(Nx/2),1:Ny)=Qup/Bini/hup ! u(int(Nx/2)+1:Nx,1:Ny)=Qup/Bini/hdown v(1:Nx,1:Ny)=0.d0 write(*,*) "u(200,10)=",u(200,10),qup/Bini/hup zbmin(1:Nx,1:Ny)=0.d0 case(4) DO I=1,Nx+1 if(I<=Nx/2)then Zb(I,0:Ny+1)=Zb(I-1,0:Ny+1)-sli*dx !勾配sliに設定 else Zb(I,0:Ny+1)=Zb(I-1,0:Ny+1)-slidown*dx!*0.01d0 !勾配sliに設定 endif ENDDO zbini=zb h(1:Nx,1:Ny)=0.d0 Ca(0:Nx+1,0:Ny+1)=0.d0 h(10:20,1:Ny)=hini Ca(10:20,1:Ny)=cini v(1:Nx,1:Ny)=0.d0 u(1:Nx,1:Ny)=0.d0 ! h(1:int(Nx/2),1:Ny)=hup ! h(int(Nx/2)+1:Nx,1:Ny)=hdown ! u(1:int(Nx/2),1:Ny)=Qup/Bini/hup ! u(int(Nx/2)+1:Nx,1:Ny)=Qup/Bini/hdown zbmin(1:Nx,1:Ny)=0.d0 write(*,*) "u(200,10)=",u(200,10) case(5) DO J=1,Ny read(1001,*) (Zb(I,J),I=1,Nx) ENDDO Zb(0,1:Ny)=Zb(1,1:Ny) Zb(Nx+1,1:Ny)=Zb(Nx,1:Ny) Zb(0:Nx,0)=Zb(0:Nx,1) Zb(0:Nx,Ny+1)=Zb(0:Nx,Ny) zbini=zb ! zbmin=zb zbmin(1:275,1:Ny)=Zb zbmin(276:Nx,1:Ny)=0.d0 ! zbmin(5:155,1:Ny)=zb(5:155,1:Ny)-0.1d0 h=0.d0 Ca=0.d0 v=0.d0 u=0.d0 case(6) DO J=1,Ny ! DO J=Ny,1,-1 read(1001,*) (Zb(I,J),I=1,Nx) ENDDO DO I=1,5 read(1002,*) dummy ENDDO h=0.d0 Ca=0.d0 DO J=1,Ny ! DO J=Ny,1,-1 read(1002,*) (h(I,J),I=1,Nx) DO I=1,Nx if(h(I,J)>hcr)then Ca(I,J)=Cini ! else ! h(I,J)=hcr ENDIF ENDDO ENDDO v=0.d0 u=0.d0 Zb(0,1:Ny)=Zb(1,1:Ny) Zb(Nx+1,1:Ny)=Zb(Nx,1:Ny) Zb(0:Nx,0)=Zb(0:Nx,1) Zb(0:Nx,Ny+1)=Zb(0:Nx,Ny) zbini=zb ! zbmin=zb zbmin=Zb-1.d0 end select ! call dry_or_wet(h,zb,u,v,iswet,hcr,Nx,Ny,1) call dry_or_wet_f(h,zb,u,v,iswet,hcr,Nx,Ny) ! where(h>hcr) ! iswet=1 ! elsewhere ! iswet=0 ! endwhere !calc U Uc(0:Nx+1,0:Ny+1,1)=h(0:Nx+1,0:Ny+1) Uc(0:Nx+1,0:Ny+1,2)=u(0:Nx+1,0:Ny+1)*h(0:Nx+1,0:Ny+1) Uc(0:Nx+1,0:Ny+1,3)=v(0:Nx+1,0:Ny+1)*h(0:Nx+1,0:Ny+1) Uc(0:Nx+1,0:Ny+1,4)=Ca(0:Nx+1,0:Ny+1)*h(0:Nx+1,0:Ny+1) Uc(0:Nx+1,0:Ny+1,5)=Zb(0:Nx+1,0:Ny+1) !calc E Ec(0:Nx+1,0:Ny+1,1)=u(0:Nx+1,0:Ny+1)*h(0:Nx+1,0:Ny+1) Ec(0:Nx+1,0:Ny+1,2)=u(0:Nx+1,0:Ny+1)**2*h(0:Nx+1,0:Ny+1)+0.5d0*g*h(0:Nx+1,0:Ny+1)**2 Ec(0:Nx+1,0:Ny+1,3)=u(0:Nx+1,0:Ny+1)*v(0:Nx+1,0:Ny+1)*h(0:Nx+1,0:Ny+1) Ec(0:Nx+1,0:Ny+1,4)=ca(0:Nx+1,0:Ny+1)*u(0:Nx+1,0:Ny+1)*h(0:Nx+1,0:Ny+1) Ec(0:Nx+1,0:Ny+1,5)=0.d0 !calc F Fc(0:Nx+1,0:Ny+1,1)=v(0:Nx+1,0:Ny+1)*h(0:Nx+1,0:Ny+1) Fc(0:Nx+1,0:Ny+1,2)=u(0:Nx+1,0:Ny+1)*v(0:Nx+1,0:Ny+1)*h(0:Nx+1,0:Ny+1) Fc(0:Nx+1,0:Ny+1,3)=v(0:Nx+1,0:Ny+1)**2*h(0:Nx+1,0:Ny+1)+0.5d0*g*h(0:Nx+1,0:Ny+1)**2 Fc(0:Nx+1,0:Ny+1,4)=ca(0:Nx+1,0:Ny+1)*v(0:Nx+1,0:Ny+1)*h(0:Nx+1,0:Ny+1) Fc(0:Nx+1,0:Ny+1,5)=0.d0 DO J=1,Ny !$omp parallel do default(shared),private(I,eps,uhxx,uhyy,vhxx,vhyy,thewx,thewy,thewxy,taustar,taustarc,alphc,cainf) DO I=1,Nx Ec(I,J,1)=u(I,J)*h(I,J) Ec(I,J,2)=u(I,J)**2*h(I,J)+0.5d0*g*h(I,J)**2 Ec(I,J,3)=u(I,J)*v(I,J)*h(I,J) Ec(I,J,4)=ca(I,J)*u(I,J)*h(I,J) Ec(I,J,5)=0.d0 Fc(I,J,1)=v(I,J)*h(I,J) Fc(I,J,2)=u(I,J)*v(I,J)*h(I,J) Fc(I,J,3)=v(I,J)**2*h(I,J)+0.5d0*g*h(I,J)**2 Fc(I,J,4)=ca(I,J)*v(I,J)*h(I,J) Fc(I,J,5)=0.d0 if(iswet(I,J)==1)then if(ca(I,J)>=0.4d0*cstar.and.h(I,J)/dm<30.d0)then Sfx(I,J)=u(I,J)*sqrt(v(I,J)**2+u(I,J)**2)*dm**2& /(8.d0*h(I,J)**3.d0*(ca(I,J)+(1.d0-ca(I,J))*rho/sigma)*((Cstar/ca(I,J))**(1.d0/3.d0)-1.d0)**2.d0)/g Sfy(I,J)=v(I,J)*sqrt(v(I,J)**2+u(I,J)**2)*dm**2& /(8.d0*h(I,J)**3.d0*(ca(I,J)+(1.d0-ca(I,J))*rho/sigma)*((Cstar/ca(I,J))**(1.d0/3.d0)-1.d0)**2.d0)/g elseif(ca(I,J)>0.01d0.and.h(I,J)/dm<30.d0)then Sfx(I,J)=1.d0/0.49d0*u(I,J)*sqrt(v(I,J)**2+u(I,J)**2)*dm**2/h(I,J)**3.d0/g Sfy(I,J)=1.d0/0.49d0*v(I,J)*sqrt(v(I,J)**2+u(I,J)**2)*dm**2/h(I,J)**3.d0/g else Sfx(I,J)=nm**2*u(I,J)*sqrt(v(I,J)**2+u(I,J)**2)/h(I,J)**(4.d0/3.d0) Sfy(I,J)=nm**2*v(I,J)*sqrt(v(I,J)**2+u(I,J)**2)/h(I,J)**(4.d0/3.d0) endif else Sfx(I,J)=0.d0 Sfy(I,J)=0.d0 endif if(iswet(I,J)==1.and.iswet(I+1,J)==1)then S0x(I,J)=-(Zb(I+1,J)-Zb(I,J))/Dx else S0x(I,J)=0.d0 endif if(iswet(I,J)==1.and.iswet(I,J+1)==1)then S0y(I,J)=-(Zb(I,J+1)-Zb(I,J))/Dy !collectorなので前進差分 else S0y(I,J)=0.d0 endif eps=1.d0/6.d0*karman*sqrt(g*h(I,J)*abs(S0x(I,J)+Sfx(I,J)))*h(I,J) if(iswet(I+1,J)==1.and.iswet(I-1,J)==1)then uhxx=(eps*(u(I+1,J)*h(I+1,J)-u(I,J)*h(I,J))/dx-eps*(u(I,J)*h(I,J)-u(I-1,J)*h(I-1,J))/dx)/dx else uhxx=0.d0 endif if(iswet(I,J+1)==1.and.iswet(I,J-1)==1)then uhyy=(eps*(u(I,J+1)*h(I,J+1)-u(I,J)*h(I,J))/dy-eps*(u(I,J)*h(I,J)-u(I,J-1)*h(I,J-1))/dy)/dy else uhyy=0.d0 endif eps=1.d0/6.d0*karman*sqrt(g*h(I,J)*abs(S0y(I,J)+Sfy(I,J)))*h(I,J) if(iswet(I+1,J)==1.and.iswet(I-1,J)==1)then vhyy=(eps*(v(I,J+1)*h(I,J+1)-v(I,J)*h(I,J))/dy-eps*(v(I,J)*h(I,J)-v(I,J-1)*h(I,J-1))/dy)/dy else vhyy=0.d0 endif if(iswet(I,J+1)==1.and.iswet(I,J-1)==1)then vhxx=(eps*(v(I+1,J)*h(I+1,J)-v(I,J)*h(I,J))/dy-eps*(v(I,J)*h(I,J)-v(I-1,J)*h(I-1,J))/dx)/dx else vhxx=0.d0 endif !calc water surface gradient!要検討 if(u(I,J)>0.d0)then thewx=(-Zb(I+1,J)-H(I+1,J)+Zb(I,J)+H(I,J))/dx elseif(u(I,J)<0.d0)then thewx=(-Zb(I,J)-H(I,J)+Zb(I-1,J)+H(I-1,J))/dx else thewx=0.d0 endif if(v(I,J)>0.d0)then thewy=(-Zb(I,J+1)-H(I,J+1)+Zb(I,J)+H(I,J))/dy elseif(v(I,J)<0.d0)then thewy=(-Zb(I,J)-H(I,J)+Zb(I,J-1)+H(I,J-1))/dy else thewy=0.d0 endif if(u(I,J)**2*cos(atan(thewx))**2+v(I,J)**2*cos(atan(thewy)**2)>0.d0)then thewxy=atan((sin(atan(thewx))*u(I,J)+sin(atan(thewy))*v(I,J))/& dsqrt(u(I,J)**2*cos(atan(thewx))**2+v(I,J)**2*cos(atan(thewy)**2))) !nakagawa else thewxy=0.d0 endif !calc Cainf if(abs(tan(thewxy))>=tan(phi))then cainf=0.9d0*Cstar elseif(abs(tan(thewxy))>0.138d0)then cainf=min(rho*abs(tan(thewxy))/((sigma-rho)*(tan(phi)-abs(tan(thewxy)))),0.9d0*Cstar) elseif(abs(tan(thewxy))>0.03d0)then cainf=6.7d0*(rho*abs(tan(thewxy))/((sigma-rho)*(tan(phi)-abs(tan(thewxy)))))**2 else taustar=rho/(sigma-rho)*h(I,J)*tan(thewxy)/dm taustarc=0.04d0*10.d0**(1.72*tan(thewxy)) alphc=sqrt(2.d0*(0.425d0-sigma*tan(thewxy)/(sigma-rho))/(1.d0-sigma*tan(thewxy)/(sigma-rho))) if(taustar>0.d0)then cainf=(1.d0+5.d0*tan(thewxy))*tan(thewxy)/(sigma/rho-1.d0)*& (1.d0-alphc**2*taustarc/taustar)*(1.d0-alphc*sqrt(taustarc/taustar)) else cainf=0.d0 endif ENDIF if(cainf>=Ca(I,J))then iero(I,J)=delero*(cainf-Ca(I,J))/(Cstar-cainf)*& sqrt(u(I,J)**2+v(I,J)**2)*h(I,J)/dm else iero(I,J)=deldep*(cainf-Ca(I,J))/Cstar*sqrt(u(I,J)**2+v(I,J)**2) endif if(caltype==1)then Cc(I,J,1)=iero(I,J) elseif(caltype==0)then Cc(I,J,1)=0.d0 else write(*,*) "error" endif Cc(I,J,2)=g*h(I,J)*(S0x(I,J)-Sfx(I,J))+uhxx+uhyy Cc(I,J,3)=g*h(I,J)*(S0y(I,J)-Sfy(I,J))+vhxx+vhyy Cc(I,J,4)=iero(I,J)*Cstar Cc(I,J,5)=-iero(I,J) ENDDO !$omp end parallel do enddo DO k=1,kmax DO J=1,Ny !$omp parallel do default(shared),private(I,kx,ky) DO I=1,Nx ! if(h(I-1,J)>0.d0.and.h(I+1,J)>0.d0)then if(I>=1.and.I<=Nx)then ! kx=8.d0*Kv(K)*sqrt(g*h(I,J)*abs(S0x(I,J)+Sfx(I,J)))*h(I,J)/Dx kx=8.d0*Kv(K)*sqrt(g*h(I,J)*abs(Sfx(I,J)))*h(I,J)/Dx Qxc(I,J,K)=0.125d0*kx*(Uc(I+1,J,K)-2.d0*Uc(I,J,K)+Uc(I-1,J,K)) else Qxc(I,J,K)=0.d0 endif ! if(h(I,J-1)>0.d0.and.h(I,J+1)>0.d0)then if(J>1.and.J<Ny)then ! ky=8.d0*Kv(K)*sqrt(g*h(I,J)*abs(S0y(I,J)+Sfy(I,J)))*h(I,J)/Dy ky=8.d0*Kv(K)*sqrt(g*h(I,J)*abs(Sfy(I,J)))*h(I,J)/Dy Qyc(I,J,K)=0.125d0*ky*(Uc(I,J+1,K)-2.d0*Uc(I,J,K)+Uc(I,J+1,K)) else Qxc(I,J,K)=0.d0 endif ENDDO !$omp end parallel do ENDDO ENDDO Up=Uc Ep=Ec Fp=Fc Cp=Cc Qxp=Qxc Qyp=Qyc ! !calc Sf ! DO J=0,Ny+1 ! DO I=0,nx+1 ! if(h(I,J)>Hcr)then ! if(ca(I,J)>=0.4d0*cstar.and.h(I,J)/dm<30.d0)then ! Sfx(I,J)=u(I,J)*sqrt(v(I,J)**2+u(I,J)**2)*dm**2& ! /(8.d0*h(I,J)**3.d0*(ca(I,J)+(1.d0-ca(I,J))*rho/sigma)*((Cstar/ca(I,J))**(1.d0/3.d0)-1.d0)**2.d0)/g ! Sfy(I,J)=v(I,J)*sqrt(v(I,J)**2+u(I,J)**2)*dm**2& ! /(8.d0*h(I,J)**3.d0*(ca(I,J)+(1.d0-ca(I,J))*rho/sigma)*((Cstar/ca(I,J))**(1.d0/3.d0)-1.d0)**2.d0)/g ! elseif(ca(I,J)>0.01d0.and.h(I,J)/dm<30.d0)then ! Sfx(I,J)=1.d0/0.49d0*u(I,J)*sqrt(v(I,J)**2+u(I,J)**2)*dm**2/h(I,J)**3.d0/g ! Sfy(I,J)=1.d0/0.49d0*v(I,J)*sqrt(v(I,J)**2+u(I,J)**2)*dm**2/h(I,J)**3.d0/g ! else ! Sfx(I,J)=nm**2*u(I,J)*sqrt(v(I,J)**2+u(I,J)**2)/h(I,J)**(4.d0/3.d0) ! Sfy(I,J)=nm**2*v(I,J)*sqrt(v(I,J)**2+u(I,J)**2)/h(I,J)**(4.d0/3.d0) ! endif ! else ! Sfx(I,J)=0.d0 ! Sfy(I,J)=0.d0 ! endif ! ENDDO ! ENDDO ! !calc Sf0 ! DO J=1,Ny ! DO I=1,Nx ! S0x(I,J)=-(Zb(I+1,J)-Zb(I-1,J))/2.d0/Dx ! S0y(I,J)=-(Zb(I,J+1)-Zb(I,J-1))/2.d0/Dy ! enddo ! enddo ! S0x(0,1:Ny)=S0x(1,1:Ny) ! S0x(Nx+1,1:Ny)=S0x(Nx,1:Ny) ! S0x(1:Nx,0)=S0x(1:Nx,1) ! S0x(1:Nx,Ny+1)=S0x(1:Nx,Ny) ! S0x(0,0)=0.d0 ! S0x(Nx+1,0)=0.d0 ! S0x(0,Ny+1)=0.d0 ! S0x(Nx+1,Ny+1)=0.d0 ! S0y(0,1:Ny)=S0y(1,1:Ny) ! S0y(Nx+1,1:Ny)=S0y(Nx,1:Ny) ! S0y(1:Nx,0)=S0y(1:Nx,1) ! S0y(1:Nx,Ny+1)=S0y(1:Nx,Ny) ! S0y(0,0)=0.d0 ! S0y(Nx+1,0)=0.d0 ! S0y(0,Ny+1)=0.d0 ! S0y(Nx+1,Ny+1)=0.d0 ! write(*,*) "here ok" ! !calc reynolds stress ! DO J=1,Ny ! DO I=1,Nx ! eps=1.d0/6.d0*karman*sqrt(g*h(I,J)*abs(S0x(I,J)+Sfx(I,J)))*h(I,J) ! uhxx=(eps*(u(I+1,J)*h(I+1,J)-u(I,J)*h(I,J))/dx-eps*(u(I,J)*h(I,J)-u(I-1,J)*h(I-1,J))/dx)/dx ! uhyy=(eps*(u(I,J+1)*h(I,J+1)-u(I,J)*h(I,J))/dy-eps*(u(I,J)*h(I,J)-u(I,J-1)*h(I,J-1))/dy)/dy ! eps=1.d0/6.d0*karman*sqrt(g*h(I,J)*abs(S0y(I,J)+Sfy(I,J)))*h(I,J) ! vhyy=(eps*(v(I,J+1)*h(I,J+1)-v(I,J)*h(I,J))/dy-eps*(v(I,J)*h(I,J)-v(I,J-1)*h(I,J-1))/dy)/dy ! vhxx=(eps*(v(I+1,J)*h(I+1,J)-v(I,J)*h(I,J))/dy-eps*(v(I,J)*h(I,J)-v(I-1,J)*h(I-1,J))/dx)/dx ! if(u(I,J)>0.d0)then ! thewx=(-Zb(I+1,J)-H(I+1,J)+Zb(I,J)+H(I,J))/dx ! elseif(u(I,J)<0.d0)then ! thewx=(-Zb(I,J)-H(I,J)+Zb(I-1,J)+H(I-1,J))/dx ! else ! thewx=0.d0 ! endif ! if(v(I,J)>0.d0)then ! thewy=(-Zb(I,J+1)-H(I,J+1)+Zb(I,J)+H(I,J))/dy ! elseif(v(I,J)<0.d0)then ! thewy=(-Zb(I,J)-H(I,J)+Zb(I,J-1)+H(I,J-1))/dy ! else ! thewy=0.d0 ! endif ! if(u(I,J)**2*cos(atan(thewx))**2+v(I,J)**2*cos(atan(thewy)**2)>0.d0)then ! thewxy=atan((sin(atan(thewx))*u(I,J)+sin(atan(thewy))*v(I,J))/& ! dsqrt(u(I,J)**2*cos(atan(thewx))**2+v(I,J)**2*cos(atan(thewy)**2))) !nakagawa ! else ! thewxy=0.d0 ! endif ! !calc water surface gradient ! if(abs(tan(thewxy))>=tan(phi))then ! cainf=0.9d0*Cstar ! elseif(abs(tan(thewxy))>0.138d0)then ! cainf=min(rho*abs(tan(thewxy))/((sigma-rho)*(tan(phi)-abs(tan(thewxy)))),0.9d0*Cstar) ! elseif(abs(tan(thewxy))>0.03d0)then ! cainf=6.7d0*(rho*abs(tan(thewxy))/((sigma-rho)*(tan(phi)-abs(tan(thewxy)))))**2 ! else ! taustar=rho/(sigma-rho)*h(I,J)*tan(thewxy)/dm ! taustarc=0.04d0*10.d0**(1.72*tan(thewxy)) ! alphc=sqrt(2.d0*(0.425d0-sigma*tan(thewxy)/(sigma-rho))/(1.d0-sigma*tan(thewxy)/(sigma-rho))) ! cainf=(1.d0+5.d0*tan(thewxy))*tan(thewxy)/(sigma/rho-1.d0)*& ! (1.d0-alphc**2*taustarc/taustar)*(1.d0-alphc*sqrt(taustarc/taustar)) ! ENDIF ! if(cainf>=Ca(I,J))then ! iero(I,J)=delero*(cainf-Ca(I,J))/(Cstar-cainf)*& ! sqrt(u(I,J)**2+v(I,J)**2)*h(I,J)/dm ! else ! iero(I,J)=deldep*(cainf-Ca(I,J))/Cstar*sqrt(u(I,J)**2+v(I,J)**2) ! endif ! !calc C ! if(caltype==1)then ! Cc(I,J,1)=iero(I,J) ! elseif(caltype==0)then ! Cc(I,J,1)=0 ! else ! write(*,*) "error" ! endif ! Cc(I,J,2)=g*h(I,J)*(S0x(I,J)-Sfx(I,J))+uhxx+uhyy ! Cc(I,J,3)=g*h(I,J)*(S0y(I,J)-Sfy(I,J))+vhxx+vhyy ! Cc(I,J,4)=iero(I,J)*Cstar ! Cc(I,J,5)=-iero(I,J) ! ENDDO ! ENDDO ! Cc(0,0:Ny+1,1:5)=0.d0 ! Cc(Nx+1,0:Ny+1,1:5)=0.d0 ! Cc(0:Nx+1,0,1:5)=0.d0 ! Cc(0:Nx+1,Ny+1,1:5)=0.d0 ! DO J=0,Ny+1 ! DO I=0,Nx+1 ! !calc kxky for Q ! DO k=1,kmax ! !calc Q ! if(I>1.and.I<Nx)then ! kx=8.d0*Kv(K)*sqrt(g*h(I,J)*abs(S0x(I,J)+Sfx(I,J)))*h(I,J)/Dx ! Qxc(I,J,K)=0.125d0*kx*(Uc(I+1,J,K)-2.d0*Uc(I,J,K)+Uc(I-1,J,K)) ! else ! Qxc(I,J,K)=0.d0 ! endif ! if(J>1.and.J<Ny)then ! ky=8.d0*Kv(K)*sqrt(g*h(I,J)*abs(S0y(I,J)+Sfy(I,J)))*h(I,J)/Dy ! Qyc(I,J,K)=0.125d0*ky*(Uc(I,J+1,K)-2.d0*Uc(I,J,K)+Uc(I,J+1,K)) ! else ! Qyc(I,J,K)=0.d0 ! endif ! ENDDO ! ENDDO ! ENDDO end subroutine Initial_condition
\documentclass{beamer} \usepackage{subfigure} \usepackage{graphicx} \usepackage{amsfonts} \usepackage{amsmath} \usepackage{amsthm} \usepackage{wrapfig} \usepackage{amssymb} \usepackage{nicefrac} \makeatletter \def\handoutsmode{handoutsmode} \def\notesmode{notesmode} \ifx\modetype\handoutsmode % Handouts mode: supress overlays \gdef\beamer@currentmode{handout} \else\relax\fi \ifx\modetype\notesmode % Notes mode: show notes and suppress overlays \gdef\beamer@currentmode{handout} \setbeameroption{show notes} \else\relax\fi \makeatother % -- BEAMER PACKAGES & OPTIONS -- \setbeamersize{text margin left=.5cm} % Default 1cm \setbeamersize{text margin right=.5cm} % Default 1cm \usefonttheme[onlymath]{serif} % Serif math font \setbeamertemplate{itemize items}[circle] \setbeamertemplate{section in toc}[sections numbered] \setbeamertemplate{navigation symbols}{} % No navigation symbols %\setbeamercovered{invisible} % Shadowed/invisible overlays %\setbeameroption{show notes} \setbeamercolor{frametitle}{fg=black} \setbeamerfont{frametitle}{size=\large,series=\bfseries} \setbeamertemplate{frametitle} { \begin{centering} \insertframetitle\par \end{centering} } % \setbeamertemplate{footline}[page number] % Simple n/N footer \setbeamertemplate{footline}[text line]{% \vbox{% % \tinycolouredline{black}{\color{white}\bf% \insertpart\hfill% \insertpartnumber--\insertframenumber% \smallskip }} % -- PACKAGES -- \usepackage{amsmath,amssymb,amsfonts} % \usepackage{bbding} % \usepackage{pstricks} % \usepackage[misc]{ifsym} \usepackage{braket} \usepackage{boxedminipage} \usepackage{overpic} % -- SLIDE MACROS -- \def\bc{\begin{center}} %\def\be{\begin{enumerate}} \def\bi{\begin{itemize}} \def\bs{\begin{small}} \def\ec{\end{center}} %\def\ee{\end{enumerate}} \def\ei{\end{itemize}} \def\es{\end{small}} % -- ONE-LINE SLIDES -- \newcommand{\TOPIC}[1]{ \frame{LARGE\textbf{% \begin{center} \gr{#1} \end{center}}}} % -- BOXED EQUATIONS -- %\usepackage{empheq} \newenvironment{boxedeq}% {\begin{empheq}[box=\fbox]{align}} {\end{empheq}} % -- MISC -- \newcommand{\com}[1]{\texttt{#1}} \newcommand{\DIV}{\ensuremath{\mathop{\mathbf{DIV}}}} \newcommand{\GRAD}{\ensuremath{\mathop{\mathbf{GRAD}}}} \newcommand{\CURL}{\ensuremath{\mathop{\mathbf{CURL}}}} \newcommand{\CURLt}{\ensuremath{\mathop{\overline{\mathbf{CURL}}}}} \newcommand{\nullspace}{\ensuremath{\mathop{\mathrm{null}}}} \newcommand{\BALL}{{\color{structure}$\bullet \;$}} \newcommand{\eq}{\ =} \newcommand{\plus}{\ +} \newcommand{\footbar}{\hspace*{-2.5ex}\rule{2in}{.2pt}\\} \newcommand{\topline}{\hrulefill} \newcommand{\botline}{\vspace*{-1ex}\hrulefill} \renewcommand{\emph}[1]{\textbf{#1}} \newcommand{\mcol}[3]{\multicolumn{#1}{#2}{#3}} \newcommand{\assign}{\ensuremath{\leftarrow}} \newcommand{\textbox}[2]{% % \renewcommand{}[1]{{#1}} \newcommand{\nedelec}{N\'{e}d\'{e}lec } \begin{tabular}{@{}#1@{}}% #2 \end{tabular}} \def\paper#1{\textcolor{darkyellow}{[#1]}} \newcommand{\tss}[1]{{\scriptscriptstyle #1}} \renewcommand{\Re}{\ensuremath{\mathbf{R}}} \newcommand{\squishlist}{ \begin{list}{$\bullet$} { \setlength{\itemsep}{0pt} \setlength{\parsep}{3pt} \setlength{\topsep}{3pt} \setlength{\partopsep}{0pt} \setlength{\leftmargin}{1.5em} \setlength{\labelwidth}{1em} \setlength{\labelsep}{0.5em} } } \newcommand{\barelist}{ \begin{list}{} { \setlength{\itemsep}{0pt} \setlength{\parsep}{3pt} \setlength{\topsep}{3pt} \setlength{\partopsep}{0pt} \setlength{\leftmargin}{0em} \setlength{\labelwidth}{1em} \setlength{\labelsep}{0.5em} } } \newcommand{\squishlisttwo}{ \begin{list}{$\bullet$} { \setlength{\itemsep}{0pt} \setlength{\parsep}{0pt} \setlength{\topsep}{0pt} \setlength{\partopsep}{0pt} \setlength{\leftmargin}{2em} \setlength{\labelwidth}{1.5em} \setlength{\labelsep}{0.5em} } } \newcommand{\squishend}{ \end{list} } % -- COLORS -- \definecolor{darkgreen}{rgb}{0,0.5,0} \definecolor{darkyellow}{rgb}{.8,.6,.04} \newcommand{\gr}[1]{\textcolor{darkgreen} {#1}} \newcommand{\wh}[1]{\textcolor{white} {#1}} \newcommand{\dy}[1]{\textcolor{darkyellow}{#1}} \newcommand{\yb}[1]{\colorbox {yellow} {#1}} \newcommand{\re}[1]{{\textcolor{red} {#1}}} \newcommand{\RE}[1]{{\bf\textcolor{red} {#1}}} \newcommand{\GR}[1]{{\bf\textcolor{darkgreen} {#1}}} \newcommand{\DY}[1]{{\bf\textcolor{darkyellow}{#1}}} \newcommand{\BL}[1]{{\bf\textcolor{blue}{#1}}} \newcommand{\ssec}[1]{{\bf #1}} \newcommand{\rsec}[1]{{\bf\color{red} #1}} \newcommand{\bsec}[1]{{\bf\color{blue} #1}} \newcommand{\gsec}[1]{{\bf\color{darkgreen} #1}} \newcommand{\dom}{\mbox{\sf dom}} \newcommand{\curl}{\ensuremath{\nabla\times\,}} \renewcommand{\div}{\nabla\cdot\,} \newcommand{\grad}{\ensuremath{\nabla}} % -- SPACING -- \def\TabS {\\ \hspace*{12pt}} \def\TabSS {\\ \hspace*{30pt}} \def\TabSSS{\\ \hspace*{45pt}} \def\fourth{{\textstyle{\frac{1}{4}}}} \newcommand{\rock}{\mcol{1}{l}{\bf Rock}} \renewcommand{\paper}{\mcol{1}{l}{\bf Paper}} \newcommand{\scissors}{\mcol{1}{l}{\bf Scissors}} \newcommand{\Px}{{\bf X}} \newcommand{\Py}{{\bf Y}} \renewcommand{\div}{\nabla\cdot\,} %\newcommand{Lt}{\hbox{\bf Left}} \newcommand{\Rt}{\hbox{\bf Right}} \newcommand{\iLt}{\invisible{Lt}} \newcommand{\iRt}{\invisible{\Rt}} \usetheme{CambridgeUS} \usecolortheme{whale} % \usecolortheme[named=Brown]{structure} \usefonttheme[onlylarge]{structuresmallcapsserif} \usefonttheme[onlysmall]{structurebold} %\setbeamerfont{title}{shape=\itshape,family=\rmfamily} %\setbeamercolor{title}{fg=black!80!black, bg=white!70!blue} %\useoutertheme{miniframes} %\usecolortheme{rose} \beamertemplatetransparentcovereddynamic \title{MHD} \author{Michael Wathen} \institute{MSc presentation} \date{August 2014} \begin{document} \begin{frame} \institute{MSc presentation \\ UBC Computer Science} \title{Iterative Solution of a Mixed Finite Element Discretisation of an Incompressible Magnetohydrodynamics Problem} \titlepage \institute{MSc presentation} \title{MHD} \institute{MSc presentation} \end{frame} \institute{MSc presentation} \title{MHD} % \section{Introduction} % \begin{frame} % \frametitle{Continuous and Discrete Maxwell's equations} % \begin{tabular}{lrrrr} % \hline % {} & Grid size & DoF & $\#$ iters & Soln Time \\ % \hline % 0 & $ 2^3$ & 81 & 1 & 4.25e-04 \\ % 1 & $ 4^3$ & 375 & 3 & 6.03e-04 \\ % 2 & $ 8^3$ & 2187 & 5 & 2.53e-03 \\ % 3 & $ 16^3$ & 14739 & 5 & 1.96e-02 \\ % 4 & $ 32^3$ & 107811 & 6 & 2.24e-01 \\ % 5 & $ 64^3$ & 823875 & 6 & 2.28e+00 \\ % 6 & $ 128^3$ & 6440067 & 6 & 2.09e+01 \\ % \hline % \end{tabular} % \end{frame} % \section{Overview} % \begin{frame} % \begin{center} % Overview % \end{center} % \begin{itemize} % \item Problem background: Setup, ... % \item % \end{itemize} % \end{frame} \section{Problem background} \begin{frame}{Problem background} \begin{itemize} \item MHD models electrically conductive fluids (such as liquid metals, plasma, salt water, etc) in an electic field \pause \item Applications: electromagnetic pumping, aluminium electrolysis, the Earth's molten core and solar flares \pause \item MHD models couple electromagnetism (governed by Maxwell's equations) and fluid dynamics (governed by the Navier-Stokes equations) \pause \item Movement of the conductive material that induces and modifies any existing electromagnetic field \pause \item Magnetic and electric fields generate a mechanical force on the fluid \end{itemize} \end{frame} \subsection{Navier-Stokes Equations} % (fold) \begin{frame} Incompressible Navier-Stokes Equations: \begin{subequations}\nonumber \re{\begin{alignat}2 - \nu \, \Delta{u}+({u} \cdot \nabla){u} +\nabla p &= {f} & \qquad &\mbox{in $\Omega$},\\[.1cm] \nabla\cdot{u} &= 0 & \qquad &\mbox{in $\Omega$},\\[.1cm] u &= u_D & \qquad &\mbox{on $\partial \Omega$} \end{alignat}} \end{subequations} \begin{itemize} \item $\re{u}$: fluid velocity \item $\re{p}$: fluid pressure \item $\re{f}$: body force acting on the fluid \item $\re{\nu}$: kinematic viscosity \end{itemize} \end{frame} % \begin{frame} % Discretised and linearised Incompressible Navier-Stokes system % \begin{equation} % \nonumber % \re{\begin{pmatrix} % A+O & B^T \\ % B & 0 % \end{pmatrix} % \begin{pmatrix} % u \\ % p % \end{pmatrix} % = % \begin{pmatrix} % f \\ % 0 % \end{pmatrix}}, % \end{equation} % \begin{itemize} % \item $\re{A}$: discrete Laplacian operator % \item $\re{O}$: discrete convection-diffusion operator % \item $\re{B}$: discrete divergence operator % \end{itemize} % \vspace{5mm} % For an extensive discussion of preconditioners we refer to \gr{Elman, Silvester and Wathen 2005/2014}. % \end{frame} \subsection{Maxwell's Equations} % (fold) \begin{frame} Maxwell operator in mixed form: \begin{subequations}\nonumber \re{\begin{alignat}2 \nabla\times( \nabla\times {b}) +\grad r &= {g} & \qquad &\mbox{in $\Omega$},\\[.1cm] \nabla\cdot{b} &= 0 & \qquad &\mbox{in $\Omega$},\\[.1cm] b \times n &= b_D & \qquad &\mbox{on $\partial \Omega$},\\[.1cm] r &= 0& \qquad &\mbox{on $\partial \Omega$}, \end{alignat}}\\[.1cm] \end{subequations} \begin{itemize} \item $\re{b}$: magnetic field \item $\re{r}$: scalar multiplier \item $\re{n}$: unit outward normal \end{itemize} \end{frame} % \begin{frame} % Discretised and linearised Incompressible Navier-Stokes system % \begin{equation} % \nonumber % \re{\begin{pmatrix} % M+X & D^T \\ % D & 0 % \end{pmatrix} % \begin{pmatrix} % b \\ % r % \end{pmatrix} % = % \begin{pmatrix} % g \\ % 0 % \end{pmatrix}}, % \end{equation} % \begin{itemize} % \item $\re{M}$: discrete curl-curl operator % \item $\re{X}$: discrete mass matrix % \item $\re{D}$: discrete divergence operator % \end{itemize} % \vspace{5mm} % For an extensive discussion of preconditioners we refer to \gr{Elman, Silvester and Wathen 2005/2014}. % \end{frame} \section{MHD} \begin{frame}{MHD model: coupled Navier-Stokes and Maxwell's equations} \begin{subequations} \nonumber % \label{eq:mhd} \re{\begin{alignat}2 % \label{eq:mhd1} - \nu \, \Delta{u} + ({u} \cdot \nabla) {u}+\nabla p {\only<2>{\color{blue}}- \kappa\, (\nabla\times{b})\times{b}} &= {f} & \qquad &\mbox{in $\Omega$},\\[.1cm] % \label{eq:mhd2} \nabla\cdot{u} &= 0 & \qquad &\mbox{in $\Omega$},\\[.1cm] % \label{eq:mhd3} \kappa\nu_m \, \nabla\times( \nabla\times {b}) + \nabla r {\only<2>{\color{blue}}- \kappa \, \nabla\times({u}\times {b})} &= {g} & \qquad &\mbox{in $\Omega$},\\[.1cm] % \label{eq:mhd4} \nabla\cdot{b} &= 0 & \qquad &\mbox{in $\Omega$}, \end{alignat}} \end{subequations} with appropriate boundary conditions. \pause \begin{itemize} \item ${\color{blue}(\nabla\times{b})\times{b}}$: Lorentz force accelerates the fluid particles in the direction normal to the electric and magnetic fields. \item ${\color{blue} \nabla\times({u}\times {b})}$: electromotive force modifying the magnetic field \end{itemize} \end{frame} \section{Discretisation} \begin{frame}{Discretisation} \begin{itemize} \item Finite element discretisation based on the formulation in \gr{Sch{\"o}tzau 2004} \item Fluid variables: lowest order Taylor-Hood (${\mathcal P_2}/{\mathcal P_1}$) \item Magnetic variables: mixed {N\'{e}d\'{e}lec} element approximation \item {N\'{e}d\'{e}lec} elements capture solutions correctly on non-convex domains \end{itemize} \end{frame} \subsection{Picard (fixed-point iteration)} \begin{frame}{Non-linear solver} \begin{itemize} \item MHD model is non-linear: $\re{\mathcal{K}(x) x = b}$ \item Standard Oseen iteration: $\re{\mathcal{K}(x_k) x_{k+1} = b}$ \item Re-arrange to solve for updates \item $\re{\mathcal{K}(x_k) \delta x = b - \mathcal{K}(x_k)x_k} \ $ where $ \ \re{x_{k+1} = x_k+\delta x}$ \end{itemize} \end{frame} \begin{frame} Discretised and linearised MHD model: \begin{equation} \nonumber %\mathcal{K} x \equiv \re{\left( \begin{array}{cccc} A+O(u) & B^T & C(b)^T & 0\\ B & 0 & 0 & 0 \\ -C(b) & 0 & M & D^T\\ 0 & 0 & D & 0 \end{array} \right) \, \left( \begin{array}{c} \delta u\\ \delta p\\ \delta b\\ \delta r \end{array} \right) = \begin{pmatrix} r_u \\ r_p\\ r_b\\ r_r \end{pmatrix},} \end{equation} with \begin{equation}\nonumber \re{\begin{array}{rl} r_u &= f- Au -O(u) u - C(b)^T b- B^T p,\\ r_p &=-B u,\\ r_b &=g-Mu+C(b)b-D^T r,\\ r_r &=-D b. \end{array}} \end{equation} $\re{A}$:~discrete Laplacian operator, $\re{O}$:~discrete convection operator, $\re{B}$:~discrete divergence operator, $\re{M}$:~discrete curl-curl operator, $\re{C}$:~coupling terms, $\re{D}$:~discrete divergence operator. \end{frame} \begin{frame} \begin{center} {\Large Decoupling schemes} \end{center} Magnetic Decoupling (MD): $$\re{\mathcal{K}_{\rm MD}=\left( \begin{array}{cc|cc} A+O(u) & B^T & 0 & 0\\ B & 0 & 0 & 0 \\ \hline 0 & 0 & M & D^T\\ 0 & 0 & D & 0 \end{array}\right)} $$ Complete Decoupling (CD): $$\re{\mathcal{K}_{\rm CD}=\left( \begin{array}{cc|cc} A & B^T & 0 & 0\\ B & 0 & 0 & 0 \\ \hline 0 & 0 & M & D^T\\ 0 & 0 & D & 0 \end{array} \right)} $$ \end{frame} \section{Preconditioning} \begin{frame}{Linear solver and Preconditioning} Consider $$\re{Ax=b},$$ to iteratively solve: $$\mbox{find }\re{x_k \in x_0+{\rm span}\{r_0,Ar_0, \ldots ,A^{k-1}r_0\}}$$ where $\re{r_0 = b-Ax_0}$ and $\re{x_0}$ is the initial guess. \vspace{5mm} Key for success: preconditioning \begin{itemize} \item[1.] the preconditioner $\re{P}$ approximates $\re{A}$ \item[2.] $\re{P}$ easy to solve for than $\re{A}$ \end{itemize} Want eigenvalues of $\re{P ^{-1}A}$ to be clusters \end{frame} \begin{frame}{Ideal preconditioning} Non-singular $(1,1)$ block \begin{equation}\nonumber \re{\mathcal{K} = \begin{pmatrix} F & B^T \\ B & 0 \end{pmatrix}; \quad \mathcal{P}=\begin{pmatrix} F & B^T\\ 0 & B F^{-1} B^T \end{pmatrix}} \end{equation} \gr{Murphy, Golub \& Wathen 2000} showed exactly two eigenvalues: $\pm 1$ %and $\nicefrac{1}{2}\pm \nicefrac{\sqrt{5}}{2}$ \vspace{5mm} \pause {Singular} $(1,1)$ block \begin{equation}\nonumber \re{\mathcal{K} = \begin{pmatrix} F & B^T \\ B & 0 \end{pmatrix}; \quad \mathcal{P}=\begin{pmatrix} F+B^T W^{-1} B & 0 \\ 0 & W \end{pmatrix}}, \ \mbox{where $\re{W}$ is SPD} \end{equation} \gr{Greif \& Sch{\"o}tzau 2006} showed exactly two eigenvalues: $\pm 1$ \end{frame} \begin{frame}{Navier-Stokes subproblem} $$\re{\mathcal{K}_{\rm NS}=\begin{pmatrix} F & B^T \\ B & 0 \end{pmatrix}}$$ where $\re{F=A+O}$ is the discrete convection diffusion operator. Shown in \gr{Elman, Silvester \& Wathen 2005/2014} that $$\re{\mathcal{P}_{\rm NS}=\left(\begin{array}{cc} F & B^T \\ 0 & S \end{array}\right)}, \quad \re{S =A_p F_p^{-1}Q_p}$$ is a good approximation to the Schur complement preconditioner. $\re{A_p}$:~pressure space Laplacian, $\re{F_p}$:~pressure space convection-diffusion operator, $\re{Q_p}$:~pressure space mass matrix \end{frame} \begin{frame}{Maxwell subproblem} $$\re{\mathcal{K}_{\rm NS}=\begin{pmatrix} M & B^T \\ B & 0 \end{pmatrix}}$$ {\textit Note:} M is highly rank defficient. \gr{Greif \& Sch{\"o}tzau 2007} shows that $\re{L}$ (scalar Laplacian) is the appropriate choice for $\re{W}$ $$\re{\mathcal{P}_{\rm iM}=\left(\begin{array}{cc} M+B^T L^{-1} B & 0 \\ 0 & L \end{array}\right)}$$ \pause Practical preconditioner: $$\re{\mathcal{P}_{\rm M}=\left(\begin{array}{cc} M+X & 0 \\ 0 & L \end{array}\right)}$$ where $\re{X}$ vector mass matrix is spectrally equivalent to $\re{B^T L^{-1} B}$ \end{frame} \begin{frame}{MHD problem} Combining the Navier-Stokes and Maxwell preconditioners $$\re{\mathcal{P}_{\rm MH} = \left( \begin{array}{cccc} F & B^T & C^T & 0\\ 0 & -{S} & 0 & 0 \\ -C & 0 & M+X & 0\\ 0 & 0 & 0 & L \end{array} \right)}$$ with the inner preconditioner $$\re{\mathcal{P}_{\rm innerMH} = \left( \begin{array}{cccc} F & B^T & 0 & 0\\ 0 & -{S} & 0 & 0 \\ 0 & 0 & M+X & 0\\ 0 & 0 & 0 & L \end{array} \right)}$$ \end{frame} \begin{frame}{Summary of decoupling scheme preconditioners} \begin{table}[h!] \begin{center} \begin{tabular}{|c|c|c|} \hline Iteration & Coefficient & Preconditioner \\ scheme & matrix & \\ \hline % \rule{0pt}{12pt}(P) & $ \left( % \begin{array}{cccc} % A+O & B^T & C^T & 0\\ % B & 0 & 0 & 0\\ % -C & 0 & M & D^T \\ % 0 & 0 & D & 0 % \end{array} % \right)$ & $\left( % \begin{array}{cccc} % F & B^T & C^T & 0\\ % 0 & -{S} & 0 & 0 \\ % -C & 0 & N & 0\\ % 0 & 0 & 0 & L % \end{array} % \right)$ \\[0.1cm] % \hline \rule{0pt}{20pt}(MD) & $\re{ \left( \begin{array}{cc|cc} F& B^T & 0 & 0\\ B & 0 & 0 & 0 \\ \hline 0 & 0 & M & D^T\\ 0 & 0 & D & 0 \end{array} \right)}$ & $\re{\left( \begin{array}{cc|cc} F & B^T & 0 & 0\\ 0 & -{S} & 0 & 0 \\ \hline 0 & 0 & M+X & 0\\ 0 & 0 & 0 & L \end{array} \right)}$ \\[0.1cm] \hline \rule{0pt}{20pt}(CD) & $\re{\left( \begin{array}{cc|cc} A & B^T & 0 & 0\\ B & 0 & 0 & 0 \\ \hline 0 & 0 & M & D^T\\ 0 & 0 & D & 0 \end{array} \right)}$ &$\re{\left(\begin{array}{cc|cc} A & 0 & 0 & 0\\ 0 & \mbox{\small \(\frac{1}{\nu}\)} Q_p & 0 & 0 \\ \hline 0 & 0 & M+X & 0\\ 0 & 0 & 0 & L \end{array} \right)}$ \\[0.1cm] \hline \end{tabular} \caption{Summary of coefficient matrices and corresponding preconditioners for each the decoupling scheme} \label{tab:SummaryTable} \end{center} \end{table} \end{frame} \section{Numerical results} \begin{frame}{Numerical software used} \begin{itemize} \item Finite element software \re{\tt FEniCS}: core libraries are the problem-solving interface \re{\tt DOLFIN}, the compiler for finite element variational forms \re{\tt FFC}, the finite element tabulator \re{\tt FIAT} for creating finite element function spaces, the just-in-time compiler \re{\tt Instant}, the code generator \re{\tt UFC} and the form language \re{\tt UFL}. \item Linear algebra software: \re{\tt HYPRE} as a multigrid solver and the sparse direct solvers \re{\tt UMFPACK}, \re{\tt PASTIX}, \re{\tt SuperLU} and \re{\tt MUMPS} \end{itemize} \end{frame} \begin{frame}{Navier-Stokes subproblem in isolation: 2D} \begin{table}[h!] \begin{center} \begin{tabular}{cccccc} \hline $\ell$ & Dofs & \multicolumn{4}{ c }{Average iterations}\\ & ${u}_h/p_h$ & $\nu=10$ & $\nu=1$ & $\nu=0.1$& $\nu=0.01$ \\ \hline 5 & 8,450/1,089 & 17 & 17 & 21 & 58 \\ 6 & 33,282/4,225 & 17 & 17 & 22 & 30 \\ 7 & 132,098/16,641 & 18 & 17 & 22 & 21 \\ 8 & 526,338/66,049 & 18 & 18 & 22 & 20 \\ 9 & 2,101,250/263,169 & 18 & 19 & 22 & 21 \\ \hline \end{tabular} \caption{Iteration table for a PCD preconditioned for various values of $\nu$} \label{tab:PCD_2D} \end{center} \end{table} \end{frame} \begin{frame}{Maxwell subproblem in isolation: 2D} \begin{table}[h!] \small \begin{center} \begin{tabular}{cccccc} \hline $\ell$ & Dofs ${b}_h/r_h$ & \multicolumn{4}{ c }{Number of iterations} \\ & & $\nu_m=10$ & $\nu_m=100 $& $\nu_m=1000 $& $\nu_m=10000$ \\ \hline 5 & 10,368/4,225 & 5 & 4 & 6 & 6 \\ 6 & 41,216/16,641 & 5 & 6 & 6 & 6 \\ 7 & 164,352/66,049 & 5 & 6 & 6 & 6 \\ 8 & 656,384/263,169 & 5 & 6 & 6 & 8 \\ 9 & 2,623,488/1,050,625 & 4 & 6 & 6 & 8 \\ 10 & 10,489,856/4,198,401 & 4 & 6 & 8 & 10 \\ \hline \end{tabular} \caption{Iteration count for Maxwell preconditioner} \label{tab:Maxwell_2D} \end{center} \end{table} \end{frame} % \begin{frame}{Maxwell subproblem in isolation: 3D} % \begin{table}[h!] % \begin{center} % \begin{tabular}{cccccc} % \hline % $\ell$ & Dofs ${b}_h/r_h$ & \multicolumn{4}{ c }{Number of iterations} \\ % & & $\nu_m=10$ & $\nu_m=100 $& $\nu_m=1000 $& $\nu_m=10000$ \\ % \hline % 2 & 2,936/729 & 4 & 4 & 6 & 5 \\ % 3 & 21,424/49,13 & 4 & 4 & 6 & 5 \\ % 4 & 163,424/35,937 & 4 & 6 & 6 & 5 \\ % 5 & 1,276,096/274,625 & 4 & 6 & 6 & 5 \\ % \hline % \end{tabular} % \caption{Iteration table for Maxwell preconditioner for 3D example} % \label{tab:Maxwell_3D} % \end{center} % \end{table} % \end{frame} \begin{frame}{MHD: why inner-outer?} % \begin{table}[h!] \small % \begin{center} % \begin{tabular}{ccccccc} % \hline % $\ell$ & Dofs & Av solve time & Total time & Its$_{\rm NL}$ & Its$_{\rm O}$ & Its$_{\rm I}$ \\ % \hline % 4 & 6,180 & 0.8 & 5.4 & 5 & 21.2 & 11.2 \\ % 5 & 24,132 & 3.4 & 20.4 & 5 & 22.2 & 11.0 \\ % 6 & 95,364 & 16.4 & 94.2 & 5 & 23.2 & 12.2 \\ % 7 & 379,140 & 52.1 & 309.6 & 5 & 19.4 & 10.0 \\ % 8 & 1,511,940 & 243.7 & 1695.0 & 6 & 21.2 & 10.0 \\ % 9 & 6,038,532 & 3592.6 & 26861.9 & 7 & 17.3 & 10.9 \\ % \hline % \end{tabular} % \caption{Number of non-linear and average number of preconditioning iterations with $\kappa = 1$, $\nu = 1$ and $\nu_m = 10$. Outer tol 1e-6, inner tol 1e-4.} % \label{tab:MD_large_scale} % \end{center} % \end{table} {\setlength{\tabcolsep}{.25em} \begin{table}[h!] \scriptsize \begin{center} \begin{tabular}{|cc|ccc|ccc|ccc|ccc|} \hline \multicolumn{2}{|c }{} & \multicolumn{3}{ |c| }{$\kappa=0.1$} & \multicolumn{3}{|c| }{$\kappa=1$} & \multicolumn{3}{|c| }{$\kappa=10$}& \multicolumn{3}{|c| }{$\kappa=100$} \\ $\ell$ & Dofs & Its$_{\rm NL}$ & Its$_{\rm O}$ & Its$_{\rm I}$ & Its$_{\rm NL}$ & Its$_{\rm O}$ & Its$_{\rm I}$ & Its$_{\rm NL}$ & Its$_{\rm O}$ & Its$_{\rm I}$ & Its$_{\rm NL}$ & Its$_{\rm O}$ & Its$_{\rm I}$ \\ \hline % 3 & 1,620 & 6 & 46.7 & 41.5 & 6 & 22.3 & 20.2 & 7 & 24.7 & 14.6 & 10 & 54.8 & 34.6 \\ 4 & 6,180 & 5 & 22.2 & 15.4 & 6 & 18.8 & 14.7 & 7 & 30.7 & 14.1 & 9 & 61.4 & 24.4 \\ 5 & 24,132 & 5 & 23.8 & 11.4 & 6 & 27.3 & 15.2 & 8 & 43.8 & 24.0 & 10 & 80.3 & 37.9 \\ 6 & 95,364 & 5 & 28.0 & 17.4 & 6 & 20.2 & 15.3 & 7 & 41.1 & 15.4 & 9 & 74.6 & 31.1 \\ 7 & 379,140 & 5 & 18.6 & 14.6 & 7 & 16.3 & 14.2 & 7 & 37.4 & 16.4 & 14 & 73.9 & 34.7 \\ 8 & 1,511,940 & 5 & 20.4 & 15.2 & 8 & 24.3 & 14.9 & 7 & 39.6 & 18.4 & 11 & 75.4 & 33.3 \\ \hline \end{tabular} \caption{Number of non-linear and average number of preconditioning iterations for various values of $\kappa$ with $\nu = 1$ and $\nu_m = 10$.} \label{tab:Picard_kappa_test} \end{center} \end{table}} {\setlength{\tabcolsep}{.16em} \begin{table}[h!] \scriptsize \begin{center} \begin{tabular}{|cc|ccc|ccc|ccc|ccc|} \hline \multicolumn{2}{|c }{} & \multicolumn{3}{ |c| }{$\kappa=0.1$} & \multicolumn{3}{|c| }{$\kappa=1$} & \multicolumn{3}{|c| }{$\kappa=10$}& \multicolumn{3}{|c| }{$\kappa=100$} \\ $\ell$ & Dofs & Its$_{\rm NL}$ & Its$_{\rm NS}$ & Its$_{\rm M}$ & Its$_{\rm NL}$ & Its$_{\rm NS}$ & Its$_{\rm M}$ & Its$_{\rm NL}$ & Its$_{\rm NS}$ & Its$_{\rm M}$ & Its$_{\rm NL}$ & Its$_{\rm NS}$ & Its$_{\rm M}$ \\ \hline 4 & 6,180 & 4 & 22.5 & 4.5 & 5 & 23.0 & 3.4 & 10 & 21.9 & 2.3 & - & 22.2 & 2.2 \\ 5 & 24,132 & 4 & 22.1 & 4.5 & 5& 22.0 & 3.4 & 10 & 21.4 & 2.3 &- & 21.7 & 2.2 \\ 6 & 95,364 & 4 & 21.5 & 4.5 & 5 & 21.2 & 3.4 & 10 & 21.1 & 2.3 &- & 21.5 & 2.3 \\ 7 & 379,140 & 4 & 21.5 & 4.8 & 5 & 21.2 & 3.4 & 10 & 21.1 & 2.4 &- & 21.6 & 2.2 \\ 8 & 1,511,940 & 4 & 21.5 & 4.8 & 5 & 21.4 & 3.4 & 10 & 21.1 & 2.4 &- & 21.7 & 2.2 \\ \hline \end{tabular} \caption{Number of non-linear iterations and average number of iterations to solve the Navier-Stokes and Maxwell's subproblem for the MD scheme with $\nu = 1$ and $\nu_m = 10$.} \label{tab:MD_kappa_test} \end{center} \end{table}} \end{frame} \begin{frame}{MHD: (MD) scheme 2D} \begin{table}[h!] \small \begin{center} \begin{tabular}{ccccccc} \hline $\ell$ & Dofs & Av solve time & Total time & Its$_{\rm NL}$ & Its$_{\rm NS}$ & Its$_{\rm M}$ \\ \hline 5 & 24,132 & 0.5 & 7.3 & 5 & 22.0 & 3.4 \\ 6 & 95,364 & 2.5 & 30.4 & 5 & 21.2 & 3.4 \\ 7 & 379,140 & 13.1 & 134.7 & 5 & 21.2 & 3.4 \\ 8 & 1,511,940 & 69.8 & 627.3 & 5 & 21.4 & 3.4 \\ 9 & 6,038,532 & 407.7 & 3159.7 & 5 & 21.6 & 3.2 \\ 10 & 24,135,684 & 3022.1 & 19668.3 & 5 & 21.6 & 3.4 \\ \hline \end{tabular} \caption{Number of non-linear iterations and average number of iterations to solve the Navier-Stokes and Maxwell's subproblem for the MD scheme with $\kappa = 1$, $\nu = 1$ and $\nu_m = 10$.} \label{tab:MD_large_scale} \end{center} \end{table} \end{frame} \begin{frame}{MHD: (MD) scheme 3D} \begin{table}[h!] \small \begin{center} \begin{tabular}{ccccccc} \hline l& Dofs & Av solve time & Total time & Its$_{\rm NL}$ & Its$_{\rm NS}$ & Its$_{\rm M}$ \\ \hline 1 & 963 & 0.04 & 2.7 & 5 & 23.2 & 3.4 \\ 2 & 5977 & 0.20 & 17.2 & 5 & 34.2 & 3.0 \\ 3 & 41805 & 4.86 & 151.1 & 5 & 34.2 & 3.4 \\ 4 & 312,085 & 242.1 & 2222.8 & 5 & 32.4 & 3.4 \\ 5 & 2,410,533 & 30222.3 & 159032.8 & 5 & 30.8 & 3.2 \\ \hline \end{tabular} \caption{Number of non-linear iterations and average number of iterations to solve the Navier-Stokes and Maxwell's subproblem for the MD scheme with $\kappa = 1$, $\nu = 1$ and $\nu_m = 10$ in 3D.} \label{tab:MD_3Dlarge_scale} \end{center} \end{table} \end{frame} \begin{frame}{{MHD: (CD) scheme 2D}} \begin{table}[h!] \small \begin{center} \begin{tabular}{ccccccc} \hline $\ell$ & Dofs & Av solve time & Total time & Its$_{\rm NL}$ & Its$_{\rm S}$ & Its$_{\rm M}$ \\ \hline 5 & 24,132 & 0.4 & 7.7 & 11 & 29.0 & 3.3 \\ 6 & 95,364 & 2.6 & 38.8 & 11 & 28.5 & 3.4 \\ 7 & 379,140 & 13.0 & 181.7 & 11 & 27.5 & 3.4 \\ 8 & 1,511,940 & 66.5 & 888.0 & 11 & 28.3 & 3.5 \\ 9 & 6,038,532 & 358.0 & 4565.4 & 11 & 28.3 & 3.4 \\ 10 & 24,135,684 & 2335.7 & 28337.4 & 11 & 27.4 & 3.5 \\ \hline \end{tabular} \caption{Number of non-linear iterations and average number of iterations to solve the Stokes and Maxwell's subproblem for the CD scheme with $\kappa = 1$, $\nu = 1$ and $\nu_m = 10$.} \label{tab:CD_large_scale} \end{center} \end{table} \end{frame} \begin{frame}{{MHD: (CD) scheme 3D}} \begin{table}[h!] \small \begin{center} \begin{tabular}{ccccccc} \hline $\ell$ & Dofs & Av solve time & Total time & Its$_{\rm NL}$ & Its$_{\rm S}$ & Its$_{\rm M}$\\ \hline 1 & 963 & 0.03 & 1.8 & 6 & 30.0 & 3.5 \\ 2 & 5,977 & 0.20 & 9.9 & 6 & 45.7 & 3.2 \\ 3 & 41,805 & 4.32 & 89.2 & 6 & 43.0 & 2.8 \\ 4 & 312,085 & 214.3 & 1786.5 & 6 & 42.3 & 2.8 \\ 5 & 2,410,533 & 26954.4 & 165671.1 & 6 & 41.3 & 2.8 \\ \hline \end{tabular} \caption{Number of non-linear iterations and average number of iterations to solve the Stokes and Maxwell's subproblem for the CD scheme with $\kappa = 1$, $\nu = 1$ and $\nu_m = 10$ in 3D.} \label{tab:CD3D_large_scale} \end{center} \end{table} \end{frame} % \begin{frame} % \begin{equation} \nonumber % \begin{aligned} % \re{ -\nu \Delta \vec u+ \nabla p} \ & \re{= \vec f} \\ % \re{ \div \vec u } \ & \re{= 0 }\\ % % \vec u &= \vec 0 \ \ \ \mbox{on } \partial\Omega} % \end{aligned} \ \ \ \ \ \mbox{in } \Omega \hspace{24mm} % \end{equation} % \vspace{-3mm} % \begin{equation} \nonumber % \mbox{\hspace{-1.5mm}} \re{\vec u = \vec g} \ \ \ \ \ \ \mbox{on } \partial\Omega % \end{equation} % Viscosity $ \re{\nu}$, velocity $ \re{\vec u}$ and pressure $ \re{p}$ % \end{frame} % \begin{frame} % \frametitle{Stokes} % $$ \re{\mathcal{K} = \begin{bmatrix} % A & B^{\mbox{\tiny{T}}}\\ % B & 0\\ % \end{bmatrix} \hspace{15mm} % \mathcal{M} = \begin{bmatrix} % A & 0\\ % 0& M\\ % \end{bmatrix}} % $$ % \end{frame} \section{Future work} \begin{frame} Future work: \begin{itemize} \item Scalable inner solvers \item Release code on a public repository \item Parallelisation of the code \item Robustness with respect to kinematic viscosity \item Other non-linear solvers \item Different mixed finite element discretisations \end{itemize} \end{frame} \end{document}
# Shear/Strain Parameterization <div class="alert alert-info"> This section is available as jupyter notebook in the `docs/` directory or at https://github.com/modscripps/mixsea/tree/master/docs. </div> Import `mixsea` and a few other modules: ```python import mixsea as mx import numpy as np import matplotlib.pyplot as plt import gsw ``` <div class="alert alert-info"> **Basic idea** (Unfortunately shear-strain parameterizations for internal wave-driven mixing are not basic at all; this is as clear and concise a summary as possible.) At the root of the shear-strain parameterization is the assumption of a scale separation between the production of turbulent kinetic energy $\mathcal{P}$ (extracted from a mean shear) at low wave numbers and its destruction by both viscous dissipation $\epsilon$ and vertical buoyancy flux $\overline{w'b'}$ at high wave numbers. In stationary turbulence, non-linear wave-wave interactions at some intermediate ("fine"-)scale $m_{c}$ must be responsible for this downscale energy flux $\mathcal{T}_{\text{IW}}$, i.e. \begin{equation} -\mathcal{T}_{\text{IW}}(m_{c}) = \mathcal{P} = - \epsilon + \overline{w'b'} \end{equation} Shear-strain parameterizations get their popular name based on the functional form $\mathcal{G}$ of the downscale transfer function that arises from either heuristic (<cite data-cite="Polzin2004">Polzin 2004</cite>) or ray-tracing (<cite data-cite="Henyey1986">Henyey et al. 1986</cite>) methods: \begin{equation} \mathcal{T}_{\text{IW}} = \mathcal{G}(E_{\text{KE}}, E_{\text{PE}}; \overline{N}, f), \end{equation} where: - $E_{\text{KE}}$ is the *kinetic energy spectral density*, often expressed as the shear variance $\langle S^{2} \rangle = \int_{m_{\text{low}}}^{\min\{m_{\text{high}}, m_{c}\}} m^{2}E_{\text{KE}} \; \text{d} m$ integrated over a low wavenumber band [$m_{\text{low}}$, $m_{\text{high}}$], which is possibly cutoff early at $m_{c}$ as soon the cumulative shear variance increases above $1/6$ the amount required for wave breaking by shear instability $\big(\text{i.e. }R_{f} = \langle N^{2} \rangle / \langle S^{2} \rangle = 1/4 \big)$; - $E_{\text{PE}}$ is the *potential energy spectral density*, often expressed in terms of a strain variance $\langle \xi_{z}^{2} \rangle$, where $\xi$ is the displacement of a density surface, or in terms of the ratio of shear to strain variance, $R_{\omega} = E_{\text{KE}}/E_{\text{PE}}$, which also doubles as a characteristic internal wave aspect ratio (strain variance also has a high cutoff wavenumber); - $\overline{N}$ is the mean stratification; and - $f$ is the Coriolis frequency. Strain-only parameterizations assume a characteristic constant shear to strain ratio and thus replace the shear variance with more readily available strain variance measurements, $\langle S^{2} \rangle \simeq \langle \xi_{z}^{2} \rangle R_{\omega}$. In practice, such parameterizations are conventionally formulated as scalings of the <cite data-cite="Garrett1975">Garrett-Munk (1975)</cite> empirical internal wave energy spectrum. The exact forms of the parameterization used are described in the underlying functions' docstrings– see the Methods section of <cite data-cite="Gregg2003">Gregg (2003)</cite> for a concise example or <cite data-cite="Kunze2006">Kunze (2006)</cite> for a detailed exposition of the default method implemented in `mixsea`. </div> #### Read example data ```python ctd = mx.helpers.read_ctd_testfile() ladcp = mx.helpers.read_ladcp_testfile() ``` Our example data contain some NaN values, as is common with observational datasets. Below we isolate the good data by removing NaNs. See the section [Missing Data](#Missing-Data) for using `nan_shearstrain` with input data that contains NaNs. ```python def nonan(data): notnan = [np.isfinite(v) for k, v in data.items()] notnan = np.vstack(notnan) notnan = np.all(notnan, axis=0) return notnan notnan = nonan(ctd) depth = ctd["depth"][notnan] t = ctd["t"][notnan] SP = ctd["SP"][notnan] lon = ctd["lon"][0] lat = ctd["lat"][0] notnan = nonan(ladcp) u = ladcp["u"][notnan] v = ladcp["v"][notnan] uz = ladcp["uz"][notnan] vz = ladcp["vz"][notnan] depth_sh = ladcp["depth"][notnan] ``` A quick overview plot of the data: ```python fig, ax = plt.subplots( nrows=1, ncols=3, figsize=(9, 4), constrained_layout=True, sharey=True ) ax[0].plot(t, depth) ax[0].set(ylabel="depth [m]", xlabel="temperature [°C]") ax[1].plot(u, depth_sh, label="u") ax[1].plot(v, depth_sh, label="v") ax[1].set(xlabel="velocity [m/s]") ax[1].legend() ax[2].plot(uz, depth_sh, label=r"u$_{z}$") ax[2].plot(vz, depth_sh, label=r"v$_{z}$") ax[2].set(xlabel="shear [1/s]") ax[2].legend() ax[0].invert_yaxis() ``` ## Example of the shear/strain internal wave parameterization We begin by choosing our parameters. The key parameter choices are: - `window_size`: the vertical extent of the spectral windows used to estimate shear/strain spectra; - `min_size`: the shortest vertical wavelength resolved by the data (should be a factor of `window_size`); doesn't matter much in practice because we separately constrain the spectral windows with the two following parameters. - `mi_sh`: index limits for integrating shear variance (excluding upper limit, following Python convention). Lower bound is generally just set to 0 so that the gravest mode included is the `window_size`; upper bound is generally set to 100-150 m. - `mi_st`: index limits for integrating strain variance (excluding upper limit, following Python convention). Lower bound is generally set to 100-150 m and upper bound set to 10-20 m. In practice, the integration is often cut-off well before 10 m. ```python shst_params = dict() # Center points of depth windows. Windows are half overlapping, i.e. # their size (300m) is double the spacing here (150m). window_size = 300.0 min_size = 10.0 dz = window_size / 2 shst_params["depth_bin"] = np.arange(dz, 10000.0, dz) shst_params["window_size"] = window_size # Set up wavenumber vector. shst_params["m"] = np.arange( 2 * np.pi / window_size, 2 * np.pi / min_size, 2 * np.pi / window_size ) # Set up limits for shear and strain variance integrations mi_sh = np.array([0, 3]) mii_sh = np.array(range(*mi_sh)) mi_st = np.array([2, 20]) mii_st = np.array(range(*mi_st)) shst_params["m_include_sh"] = mii_sh shst_params["m_include_st"] = mii_st # Convert indices to more intuitive length scales m_sh = 2 * np.pi / shst_params["m"][[mi_sh[0], mi_sh[1] - 1]] m_st = 2 * np.pi / shst_params["m"][[mi_st[0], mi_st[1] - 1]] print( f"Wavenumber indices for integration:\n" f"- Shear is integrated from {round(m_sh[0])}m to {round(m_sh[1])}m scales.\n" f"- Strain is integrated from {round(m_st[0])}m to {round(m_st[1])}m." ) shst_params["ladcp_is_shear"] = True shst_params["return_diagnostics"] = True ``` We now pass our input data and parameter dictionary to the `shearstrain` function and retrieve the dissipation rate of turbulent kinetic energy $\epsilon$, the diapycnal diffusivity $\kappa_{\rho}$, and an optional dictionary of detailed diagnostics. ```python eps, krho, diag = mx.shearstrain.shearstrain( depth, t, SP, lon, lat, uz, vz, depth_sh, **shst_params ) ``` Let's visualize the vertical profiles of the estimated mixing rates due to internal waves: ```python depth_bin = diag["depth_bin"] depth_bin_edges = np.concatenate( ( [np.min(depth_bin) - dz / 2], 0.5 * (depth_bin[1:] + depth_bin[:-1]), [np.max(depth_bin) - dz / 2], ) ) fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(6, 4), sharey=True, constrained_layout=True) ax[0].stairs(eps, depth_bin_edges, orientation="horizontal", baseline=None, lw=1.5) ax[0].set(xscale="log", xlabel=r"$\epsilon$ [W/kg]", ylabel="depth [m]") ax[0].invert_yaxis() ax[1].stairs(krho, depth_bin_edges, orientation="horizontal", baseline=None, lw=1.5) ax[1].set(xscale="log", xlabel=r"$\kappa$ [m$^{2}$/s]") k = -2 ax[0].fill_betweenx( np.array([-dz, dz]) + depth_bin[k], [0, 0], [eps[k], eps[k]], facecolor="C3", alpha=0.2, ) ax[1].fill_betweenx( np.array([-dz, dz]) + depth_bin[k], [0, 0], [krho[k], krho[k]], facecolor="C3", alpha=0.2, ); ``` #### Deep dive for a single high-dissipation window near the bottom Let's zoom in on the second to last window (shaded in red above), which exhibits abnormally strong strain variance and thus corresponds to a large dissipation rate, to get a better understanding of what the shear/strain variance and strain variance algorithms are doing. ```python ax = plt.subplot() plt.loglog(diag["m"][mii_sh], diag["P_shear"][k][mii_sh]) plt.loglog(diag["m"], diag["P_shear"][k], "C0--", alpha=0.25) S_shear_gm, P_shear_gm = mx.shearstrain.gm_shear_variance( diag["m"], mii_sh, diag["Nmseg"][k] ) plt.loglog(diag["m"], P_shear_gm, label="GM76 spectrum (minus rolloff)") ylims = plt.gca().get_ylim() plt.fill_between( diag["m"][[mi_sh[0], mi_sh[1] - 1]], [ylims[0], ylims[0]], [ylims[1], ylims[1]], alpha=0.1, ) plt.ylim(ylims) plt.xlim(diag["m"][0], diag["m"][-1]) plt.ylabel(r"$\langle S^{2} \rangle$", fontsize=13) plt.xlabel(r"wavenumber $m$ [rad/m]", fontsize=13) plt.legend() def same(x): return x secax = ax.secondary_xaxis("top", functions=(same, same)) secax.set_xticks([diag["m"][mii_sh[0]], diag["m"][mii_sh[-1]]], minor=False) secax.set_xticklabels([r"$m_{low}$", r"$m_{high}$"]) var_ratio = diag["Int_sh"][k] / diag["Int_sh_gm"][k] print( f"Shear variance levels are {round(var_ratio,1)} times higher than\n" f"the GM spectrum over the low wavenumber band." ) ``` ```python ax = plt.subplot() plt.loglog(diag["m"][mii_st], diag["P_strain"][k][mii_st]) plt.loglog(diag["m"], diag["P_strain"][k], "C0--", alpha=0.25) S_strain_gm, P_strain_gm = mx.shearstrain.gm_strain_variance( diag["m"], mii_st, diag["Nmseg"][k] ) plt.loglog(diag["m"], P_strain_gm, label="GM76 spectrum") mii_st_cutoff = mii_st[diag["m"][mii_st] <= diag["Mmax_st"][k]] S_strain_gm, P_strain_gm = mx.shearstrain.gm_strain_variance( diag["m"], mii_st_cutoff, diag["Nmseg"][k] ) ylims = plt.gca().get_ylim() plt.fill_between( [diag["m"][mii_st_cutoff[0]], diag["Mmax_st"][k]], [ylims[0], ylims[0]], [ylims[1], ylims[1]], alpha=0.1, ) plt.ylim(ylims) plt.xlim(diag["m"][0], diag["m"][-1]) plt.ylabel(r"$\langle \xi_{z}^{2} \rangle$", fontsize=13) plt.xlabel(r"wavenumber $m$ [rad/m]", fontsize=13) plt.legend() secax = ax.secondary_xaxis("top", functions=(same, same)) secax.set_xticks( [diag["m"][mii_st[0]], diag["m"][mii_st[-1]], diag["Mmax_st"][k]], minor=False ) secax.set_xticklabels([r"$m_{low}$", r"$m_{high}$", r"$m_{c}$"]) print( rf"Strain variance levels are {round(diag['Int_st'][k]/S_strain_gm,1)} times " f"higher than\nthe GM spectrum over the low wavenumber band." ) ``` In this example, since the strain variance is much larger than GM levels while the shear variance is only slightly large than GM levels, the shear/strain ratio drops well below the GM level of $R_{\omega}$=3. Since shear/strain ratios of less than $1$ are unphysical for internal waves (for example the aspect ratio correction terms contain a factor $\sqrt{R_{\omega} - 1}$), we set any $R_{\omega} \leq 1$ to $R_{\omega}=1.01$. ```python print( f"Raw shear/strain ratio: {round(diag['Rwtot'][k], 2)}, " f"corrected ratio: {diag['Rwcor'][k]}" ) ``` #### Decomposing the terms of the parameterization The dissipation rate for the shear/strain parameterization is given as: \begin{equation} \epsilon_{\text{fine}} = \epsilon_{0} \; \frac{\overline{N}^{2}}{N_{0}^{2}} \; \frac{\langle S^{2} \rangle}{\langle S^{2}_{\text{GM}} \rangle} \; h_{1}(R_{\omega}) \; L(f, \overline{N}) \end{equation} It is useful to plot their vertical profiles to get a sense of how their various dependencies combine to produce a typical dissipation rate profile, where the grey dashed lines denote the reference values for the GM spectrum. ```python N0 = 5.24e-3 f = np.absolute(gsw.f(ctd["lat"][0])) fig, ax = plt.subplots( nrows=1, ncols=5, figsize=(9, 4), sharey=True, constrained_layout=True ) ax[0].stairs( eps, depth_bin_edges, label=r"$\epsilon$", orientation="horizontal", baseline=None, lw=1.5, ) ax[0].set(xscale="log", xlabel=r"$\epsilon$ [W/kg]", ylabel="depth [m]") ax[0].invert_yaxis() ax[1].axvline(1.0, color="k", alpha=0.3, ls="--") ax[1].stairs( diag["Nmseg"] ** 2 / N0 ** 2, depth_bin_edges, orientation="horizontal", baseline=None, lw=1.5, ) ax[1].set(xscale="log", xlabel=r"$\overline{N}^{2}/N_{0}^{2}$") ax[2].axvline(1.0, color="k", alpha=0.3, ls="--") ax[2].stairs( diag["Int_sh"] ** 2 / diag["Int_sh_gm"] ** 2, depth_bin_edges, orientation="horizontal", baseline=None, lw=1.5, ) ax[2].set( xscale="log", xlabel=r"$\langle S^{2} \rangle^{2} / \langle S^{2}_{GM} \rangle^{2}$ [W/kg]", ) ax[3].axvline( mx.shearstrain.aspect_ratio_correction_shst(3.0), color="k", alpha=0.3, ls="--" ) ax[3].stairs( mx.shearstrain.aspect_ratio_correction_shst(diag["Rwcor"]), depth_bin_edges, orientation="horizontal", baseline=None, lw=1.5, ) ax[3].set(xscale="log", xlabel=r"$h_{1}(R_{\omega})$") ax[4].axvline(1.0, color="k", alpha=0.3, ls="--") ax[4].stairs( mx.shearstrain.latitude_correction(f, diag["Nmseg"]), depth_bin_edges, orientation="horizontal", baseline=None, lw=1.5, ) ax[4].set(xlabel=r"$L(f, N)$") eps0 = 7.8e-10 eps_verify = ( eps0 * diag["Nmseg"] ** 2 / N0 ** 2 * diag["Int_sh"] ** 2 / diag["Int_sh_gm"] ** 2 * mx.shearstrain.aspect_ratio_correction_shst(diag["Rwcor"]) * mx.shearstrain.latitude_correction(f, diag["Nmseg"]) ) ax[0].stairs( eps_verify, depth_bin_edges, label=r"$\epsilon_{verify}$", orientation="horizontal", baseline=None, lw=1.2, ls="--", alpha=1.0, ) ax[0].legend() print(f"Verification successful: {np.isclose(eps_verify, eps).all()}") ``` ## Stratification Smoothing Techniques `shearstrain` allows to select between two different techniques for obtaining a smooth profile of $N^2$. Adiabatic leveling is the default (used in the example above). **Adiabatic Leveling** finds locally stable density gradients to calculate a smooth $N^2$ profile following Bray & Fofonoff (1981), see e.g. Polzin et al. (2014), Waterman et al. (2013, 2014). **Polynomial Fitting** applies a second order polynomial fit to $N^2$ for each segment to obtain a smooth profile, compare e.g. Kunze et al. (2006), Whalen et al. (2012, 2015). Run the shear/strain parameterization for both the techniques: ```python eps_PF, krho_PF, diag_PF = mx.shearstrain.shearstrain( depth, t, SP, lon, lat, uz, vz, depth_sh, smooth="PF", **shst_params ) ``` Compare results from the two techniques: ```python fig, ax = plt.subplots( nrows=1, ncols=2, figsize=(6, 4), constrained_layout=True, sharey=True ) opts = dict(orientation="horizontal", baseline=None) # shear/strain ax[0].stairs(eps, depth_bin_edges, label="AL", **opts) ax[0].stairs(eps_PF, depth_bin_edges, label="PF", **opts) ax[0].legend(loc="upper left") ax[0].set( xscale="log", xlabel=r"$\epsilon$ [W/kg]", ylabel="depth [m]", title="shear/strain" ) ax[0].invert_yaxis() # strain only ax[1].stairs(diag["eps_st"], depth_bin_edges, label="AL", **opts) ax[1].stairs(diag_PF["eps_st"], depth_bin_edges, label="PF", **opts) ax[1].set(xscale="log", xlabel=r"$\epsilon$ [W/kg]", title="strain only"); ``` Results differ mostly for the upper ocean and the bottom layer. Note that we do not filter out parts of the profile where the shear/strain parameterization may not apply as underlying assumptions are violated, i.e. near the surface mixed layer and in the lowly stratified layer of the abyssal flow through the Samoan Passage. <a id='Missing-Data'></a> ## Missing Data Here we pass the data as is, containing NaNs, to `nan_shearstrain`. ```python eps_nan, krho_nan, diag_nan = mx.shearstrain.nan_shearstrain( ctd["depth"], ctd["t"], ctd["SP"], ctd["lon"], ctd["lat"], ladcp["uz"], ladcp["vz"], ladcp["depth"], **shst_params ) ``` Compare with result of `shearstrain` from above - the results should be the same. Here we apply only the polynomial fit method for obtaining strain. ```python depth_bin_nan = diag_nan["depth_bin"] depth_bin_nan_edges = np.concatenate( ( [np.min(depth_bin_nan) - dz / 2], 0.5 * (depth_bin_nan[1:] + depth_bin_nan[:-1]), [np.max(depth_bin_nan) - dz / 2], ) ) fig, ax = plt.subplots( nrows=1, ncols=2, figsize=(6, 4), constrained_layout=True, sharey=True ) # shear/strain ax[0].stairs(eps, depth_bin_edges, label="without NaNs", **opts) ax[0].stairs(eps_nan, depth_bin_nan_edges, label="with NaNs", linestyle="--", **opts) ax[0].legend() ax[0].set( xscale="log", xlabel=r"$\epsilon$ [W/kg]", ylabel="depth [m]", title="shear/strain" ) ax[0].invert_yaxis() # strain only ax[1].stairs(diag["eps_st"], depth_bin_edges, label="without NaNs", **opts) ax[1].stairs( diag_nan["eps_st"], depth_bin_nan_edges, label="with NaNs", linestyle="--", **opts ) ax[1].legend() ax[1].set( xscale="log", xlabel=r"$\epsilon$ [W/kg]", title="strain only", ); ``` Note that there may be cases where simply removing all missing data from the input, as is happening in `nan_shearstrain`, will lead to unphysical results!
import category_theory.adjunction.limits import category_theory.closed.cartesian import category_theory.conj universes v u₁ u₂ namespace category_theory open category limits variables {C : Type u₁} [category.{v} C] [has_finite_products C] [cartesian_closed C] variables {D : Type u₂} [category.{v} D] [has_finite_products D] [cartesian_closed D] variables (F : C ⥤ D) class cartesian_closed_functor := [preserves_bin_prods : preserves_limits_of_shape (discrete walking_pair) F] (comparison_iso : ∀ A B, is_iso (exp_comparison F A B)) attribute [instance] cartesian_closed_functor.comparison_iso variables {F} {L : D ⥤ C} noncomputable def frobenius_map (A : C) (B : D) (adj : L ⊣ F) : L.obj (F.obj A ⨯ B) ⟶ A ⨯ L.obj B := prod_comparison _ _ _ ≫ limits.prod.map (adj.counit.app A) (𝟙 _) @[reassoc] lemma frob_naturality {A A' : C} {B B' : D} (adj : L ⊣ F) (f : A ⟶ A') (g : B ⟶ B') : frobenius_map A B adj ≫ limits.prod.map f (L.map g) = L.map (limits.prod.map (F.map f) g) ≫ frobenius_map A' B' adj := begin rw [frobenius_map, frobenius_map, assoc, prod_comparison_natural_assoc], apply prod.hom_ext, simp only [assoc, limits.prod.map_fst, limits.prod.map_fst_assoc, adjunction.counit_naturality], simp only [assoc, limits.prod.map_snd, limits.prod.map_snd_assoc, comp_id, id_comp], end -- @[reassoc] -- lemma frob_inv_naturality_left {A A' : C} {B : D} (adj : L ⊣ F) (f : A ⟶ A') -- [is_iso (frobenius_map A B adj)] -- [is_iso (frobenius_map A' B adj)] : -- inv (frobenius_map A B adj) ≫ L.map (limits.prod.map (F.map f) (𝟙 _)) = -- limits.prod.map f (𝟙 _) ≫ inv (frobenius_map A' B adj) := -- begin -- erw [(as_iso] -- -- erw [(as_iso (frobenius_map A B adj)).inv_comp_eq, assoc, ← prod_map_comp_id_assoc, ← assoc, -- -- (as_iso (frobenius_map A' B adj)).eq_comp_inv, prod_comparison_natural_assoc, L.map_id, -- -- ← prod_map_comp_id, adj.counit.naturality], refl, -- end @[reassoc] lemma frob_inv_naturality {A A' : C} {B B' : D} (adj : L ⊣ F) (f : A ⟶ A') (g : B ⟶ B') [is_iso (frobenius_map A B adj)] [is_iso (frobenius_map A' B' adj)] : inv (frobenius_map A B adj) ≫ L.map (limits.prod.map (F.map f) g) = limits.prod.map f (L.map g) ≫ inv (frobenius_map A' B' adj) := begin erw [(as_iso (frobenius_map A B adj)).inv_comp_eq], rw ← assoc, erw [(as_iso (frobenius_map A' B' adj)).eq_comp_inv], symmetry, apply frob_naturality, end variables (adj : L ⊣ F) [∀ A B, is_iso (frobenius_map A B adj)] noncomputable def biject (adj : L ⊣ F) [∀ A B, is_iso (frobenius_map A B adj)] {A B : C} {c : D} : (c ⟶ F.obj (B ^^ A)) ≃ (c ⟶ F.obj B ^^ F.obj A) := calc (c ⟶ F.obj (B ^^ A)) ≃ (L.obj c ⟶ B ^^ A) : (adj.hom_equiv _ _).symm ... ≃ (A ⨯ L.obj c ⟶ B) : ((exp.adjunction A).hom_equiv _ _).symm ... ≃ (L.obj (F.obj A ⨯ c) ⟶ B) : iso.hom_congr (as_iso (frobenius_map _ _ adj)).symm (iso.refl _) ... ≃ (F.obj A ⨯ c ⟶ F.obj B) : adj.hom_equiv _ _ ... ≃ (c ⟶ F.obj B ^^ F.obj A) : ((exp.adjunction _).hom_equiv _ _) -- tidy this up lemma biject_id {A B : C} [preserves_limits_of_shape (discrete walking_pair) F] : biject adj (𝟙 _) = exp_comparison F A B := begin dsimp [biject, iso.hom_congr, frobenius_map, exp_comparison], rw [comp_id], change cartesian_closed.curry _ = _, congr' 1, erw (as_iso (prod_comparison F A ((exp A).obj B))).eq_inv_comp, rw adj.hom_equiv_unit, erw adj.unit.naturality_assoc, dsimp [prod_comparison], erw ← F.map_comp, rw adjunction.hom_equiv_counit, rw adjunction.hom_equiv_counit, rw L.map_id, rw id_comp, dsimp, rw prod.lift_map, rw prod.lift_map_assoc, rw comp_id, rw comp_id, simp only [functor.map_comp], rw ← F.map_comp, rw ← F.map_comp, rw ← adj.hom_equiv_unit, rw adj.hom_equiv_apply_eq, rw adj.hom_equiv_counit, erw adj.counit.naturality, rw ← assoc, congr' 1, apply prod.hom_ext; simp [← functor.map_comp_assoc], end lemma biject_id' {A B : C} [preserves_limits_of_shape (discrete walking_pair) F] : 𝟙 (F.obj ((exp A).obj B)) = (biject adj).symm (exp_comparison F A B) := begin rw equiv.eq_symm_apply, rw biject_id, end lemma biject_natural {A B B' : C} {c c' : D} (f : c' ⟶ c) (g : B ⟶ B') (q : c ⟶ F.obj (B ^^ A)) : f ≫ biject adj q ≫ (exp _).map (F.map g) = biject adj (f ≫ q ≫ F.map ((exp _).map g)) := begin dsimp [biject, iso.hom_congr], rw [comp_id, comp_id], rw ← adjunction.hom_equiv_naturality_right, rw ← adjunction.hom_equiv_naturality_left, erw ← adjunction.hom_equiv_naturality_right, rw ← adjunction.hom_equiv_naturality_left, rw assoc, rw adj.hom_equiv_naturality_left_symm, rw adjunction.hom_equiv_naturality_left_symm, erw frob_naturality_assoc, rw adj.hom_equiv_naturality_right_symm, rw adjunction.hom_equiv_naturality_right_symm, congr' 4, dsimp, simp, end lemma biject_natural_left {A B : C} {c c' : D} (f : c' ⟶ c) (q : c ⟶ F.obj (B ^^ A)) : f ≫ biject adj q = biject adj (f ≫ q) := by simpa using biject_natural adj f (𝟙 _) q lemma biject_natural_right {A B B' : C} {c : D} (g : B ⟶ B') (q : c ⟶ F.obj (B ^^ A)) : biject adj q ≫ (exp _).map (F.map g) = biject adj (q ≫ F.map ((exp _).map g)) := by simpa using biject_natural adj (𝟙 _) g q noncomputable def cartesian_closed_of_frobenius_iso : cartesian_closed_functor F := { preserves_bin_prods := begin letI := adj.right_adjoint_preserves_limits, apply_instance, end, comparison_iso := λ A B, { inv := (biject adj).symm (𝟙 _), hom_inv_id' := begin rw ← (biject adj).apply_eq_iff_eq, rw biject_id _, rw ← biject_natural_left, rw equiv.apply_symm_apply, rw comp_id, end, inv_hom_id' := begin letI := adj.right_adjoint_preserves_limits, rw ← biject_id adj, rw biject_natural_left, rw comp_id, rw equiv.apply_symm_apply, end } } -- /-- -- The exponential comparison map. -- `F` is a cartesian closed functor if this is an iso for all `A,B`. -- -/ -- def exp_comparison (A B : C) : -- F.obj (A ⟹ B) ⟶ F.obj A ⟹ F.obj B := -- curry (inv (prod_comparison F A _) ≫ F.map ((ev _).app _)) -- /-- The exponential comparison map is natural in its left argument. -/ -- lemma exp_comparison_natural_left (A A' B : C) (f : A' ⟶ A) : -- exp_comparison F A B ≫ pre (F.obj B) (F.map f) = F.map (pre B f) ≫ exp_comparison F A' B := -- begin -- rw [exp_comparison, exp_comparison, ← curry_natural_left, eq_curry_iff, uncurry_natural_left, -- pre, uncurry_curry, prod_map_map_assoc, curry_eq, prod_map_id_comp, assoc], -- erw [(ev _).naturality, ev_coev_assoc, ← F.map_id, ← prod_comparison_inv_natural_assoc, -- ← F.map_id, ← prod_comparison_inv_natural_assoc, ← F.map_comp, ← F.map_comp, pre, curry_eq, -- prod_map_id_comp, assoc, (ev _).naturality, ev_coev_assoc], refl, -- end -- /-- The exponential comparison map is natural in its right argument. -/ -- lemma exp_comparison_natural_right (A B B' : C) (f : B ⟶ B') : -- exp_comparison F A B ≫ (exp (F.obj A)).map (F.map f) = -- F.map ((exp A).map f) ≫ exp_comparison F A B' := -- by -- erw [exp_comparison, ← curry_natural_right, curry_eq_iff, exp_comparison, uncurry_natural_left, -- uncurry_curry, assoc, ← F.map_comp, ← (ev _).naturality, F.map_comp, -- prod_comparison_inv_natural_assoc, F.map_id] -- -- TODO: If F has a left adjoint L, then F is cartesian closed if and only if -- -- L (B ⨯ F A) ⟶ L B ⨯ L F A ⟶ L B ⨯ A -- -- is an iso for all A ∈ D, B ∈ C. -- -- Corollary: If F has a left adjoint L which preserves finite products, F is cartesian closed iff -- -- F is full and faithful. end category_theory
example : Id Nat := do let x ← if true then pure 1 else pure 2 pure x
\<^marker>\<open>creator "Kevin Kappelmann"\<close> subsubsection \<open>Generic Compositions\<close> theory Transport_Compositions_Generic imports Transport_Compositions_Generic_Galois_Equivalence Transport_Compositions_Generic_Galois_Relator Transport_Compositions_Generic_Order_Base Transport_Compositions_Generic_Order_Equivalence begin paragraph \<open>Summary of Main Results\<close> subparagraph \<open>Closure of Order and Galois Concepts\<close> context transport_comp begin interpretation flip : transport_comp R2 L2 r2 l2 R1 L1 r1 l1 . lemma preorder_galois_connection_if_galois_equivalenceI: assumes "((\<le>\<^bsub>L1\<^esub>) \<equiv>\<^sub>G (\<le>\<^bsub>R1\<^esub>)) l1 r1" and "reflexive_on (in_field (\<le>\<^bsub>L1\<^esub>)) (\<le>\<^bsub>L1\<^esub>)" and "preorder_on (in_field (\<le>\<^bsub>R1\<^esub>)) (\<le>\<^bsub>R1\<^esub>)" and "((\<le>\<^bsub>L2\<^esub>) \<equiv>\<^sub>G (\<le>\<^bsub>R2\<^esub>)) l2 r2" and "preorder_on (in_field (\<le>\<^bsub>L2\<^esub>)) (\<le>\<^bsub>L2\<^esub>)" and "reflexive_on (in_field (\<le>\<^bsub>R2\<^esub>)) (\<le>\<^bsub>R2\<^esub>)" and "middle_compatible_codom" shows "((\<le>\<^bsub>L\<^esub>) \<stileturn>\<^bsub>pre\<^esub> (\<le>\<^bsub>R\<^esub>)) l r" using assms by (intro preorder_galois_connectionI) (auto elim!: t1.galois_equivalenceE t2.galois_equivalenceE intro!: galois_connection_left_right_if_galois_equivalenceI preorder_on_in_field_leftI flip.preorder_on_in_field_leftI mono_in_codom_left_rel_left1_if_in_codom_rel_comp_le flip.mono_in_codom_left_rel_left1_if_in_codom_rel_comp_le in_codom_eq_in_dom_if_reflexive_on_in_field) theorem preorder_galois_connection_if_preorder_equivalenceI: assumes "((\<le>\<^bsub>L1\<^esub>) \<equiv>\<^bsub>pre\<^esub> (\<le>\<^bsub>R1\<^esub>)) l1 r1" and "((\<le>\<^bsub>L2\<^esub>) \<equiv>\<^bsub>pre\<^esub> (\<le>\<^bsub>R2\<^esub>)) l2 r2" and "middle_compatible_codom" shows "((\<le>\<^bsub>L\<^esub>) \<stileturn>\<^bsub>pre\<^esub> (\<le>\<^bsub>R\<^esub>)) l r" using assms by (intro preorder_galois_connection_if_galois_equivalenceI) auto lemma preorder_equivalence_if_galois_equivalenceI: assumes "((\<le>\<^bsub>L1\<^esub>) \<equiv>\<^sub>G (\<le>\<^bsub>R1\<^esub>)) l1 r1" and "reflexive_on (in_field (\<le>\<^bsub>L1\<^esub>)) (\<le>\<^bsub>L1\<^esub>)" and "preorder_on (in_field (\<le>\<^bsub>R1\<^esub>)) (\<le>\<^bsub>R1\<^esub>)" and "((\<le>\<^bsub>L2\<^esub>) \<equiv>\<^sub>G (\<le>\<^bsub>R2\<^esub>)) l2 r2" and "preorder_on (in_field (\<le>\<^bsub>L2\<^esub>)) (\<le>\<^bsub>L2\<^esub>)" and "reflexive_on (in_field (\<le>\<^bsub>R2\<^esub>)) (\<le>\<^bsub>R2\<^esub>)" and "middle_compatible_codom" shows "((\<le>\<^bsub>L\<^esub>) \<equiv>\<^bsub>pre\<^esub> (\<le>\<^bsub>R\<^esub>)) l r" proof - from assms have "((\<le>\<^bsub>L\<^esub>) \<stileturn>\<^bsub>pre\<^esub> (\<le>\<^bsub>R\<^esub>)) l r" by (intro preorder_galois_connection_if_galois_equivalenceI) auto with assms show ?thesis by (intro preorder_equivalence_if_galois_equivalenceI) (auto intro!: galois_equivalence_if_galois_equivalenceI preorder_galois_connection_if_galois_equivalenceI) qed theorem preorder_equivalenceI: assumes "((\<le>\<^bsub>L1\<^esub>) \<equiv>\<^bsub>pre\<^esub> (\<le>\<^bsub>R1\<^esub>)) l1 r1" and "((\<le>\<^bsub>L2\<^esub>) \<equiv>\<^bsub>pre\<^esub> (\<le>\<^bsub>R2\<^esub>)) l2 r2" and "middle_compatible_codom" shows "((\<le>\<^bsub>L\<^esub>) \<equiv>\<^bsub>pre\<^esub> (\<le>\<^bsub>R\<^esub>)) l r" using assms by (intro preorder_equivalence_if_galois_equivalenceI) auto theorem partial_equivalence_rel_equivalenceI: assumes "((\<le>\<^bsub>L1\<^esub>) \<equiv>\<^bsub>PER\<^esub> (\<le>\<^bsub>R1\<^esub>)) l1 r1" and "((\<le>\<^bsub>L2\<^esub>) \<equiv>\<^bsub>PER\<^esub> (\<le>\<^bsub>R2\<^esub>)) l2 r2" and "middle_compatible_codom" shows "((\<le>\<^bsub>L\<^esub>) \<equiv>\<^bsub>PER\<^esub> (\<le>\<^bsub>R\<^esub>)) l r" using assms by (intro partial_equivalence_rel_equivalence_if_galois_equivalenceI galois_equivalence_if_galois_equivalenceI partial_equivalence_rel_leftI flip.partial_equivalence_rel_leftI in_codom_eq_in_dom_if_partial_equivalence_rel) auto subparagraph \<open>Simplification of GaloisGalois relator\<close> theorem Galois_eq_Galois_rel_compI: assumes "((\<le>\<^bsub>L1\<^esub>) \<equiv>\<^bsub>pre\<^esub> (\<le>\<^bsub>R1\<^esub>)) l1 r1" and "((\<le>\<^bsub>R2\<^esub>) \<stileturn>\<^bsub>pre\<^esub> (\<le>\<^bsub>L2\<^esub>)) r2 l2" and "middle_compatible_codom" shows "(\<^bsub>L\<^esub>\<lessapprox>) = ((\<^bsub>L1\<^esub>\<lessapprox>) \<circ>\<circ> (\<^bsub>L2\<^esub>\<lessapprox>))" using assms by (intro Galois_eq_Galois_rel_comp_if_galois_connection_if_galois_equivalenceI) auto text \<open>For theorems with weaker assumptions, see @{thm "Galois_eq_Galois_rel_compI'" "Galois_eq_Galois_rel_comp_if_galois_connection_if_galois_equivalenceI"}.\<close> subparagraph \<open>Simplification of Compatibility Assumption\<close> text \<open>See @{theory "Transport.Transport_Compositions_Generic_Base"}.\<close> end end
function h = fspecial3(type, sz, param) % FSPECIAL3 Create predefined 3-dimensional filters % % H = FSPECIAL3(TYPE, SZ, PARAM) % % H is a 3-dimensional (3D) filter of TYPE: % % 'gaussian' Rotationally symmetric Gaussian low-pass filter (default) % PARAM: standard deviation in each dimension (default % PARAM = [1.0 1.0 1.0]) % % SZ is a vector with the size of the output filter in each dimension, in % order [rows, columns, slices]. By default, SZ = [3 3 3]. Sizes have to % be odd numbers so that the filter can be centered around 0. % % See also: fspecial. % Author: Ramon Casero <[email protected]> % Copyright © 2011 University of Oxford % Version: 0.1.0 % % University of Oxford means the Chancellor, Masters and Scholars of % the University of Oxford, having an administrative office at % Wellington Square, Oxford OX1 2JD, UK. % % This file is part of Gerardus. % % This program 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. % % This program 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. The offer of this % program under the terms of the License is subject to the License % being interpreted in accordance with English Law and subject to any % action against the University of Oxford being under the jurisdiction % of the English Courts. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/>. % check arguments error(nargchk(0, 3, nargin, 'struct')); error(nargoutchk(0, 1, nargout, 'struct')); % defaults if (nargin < 1 || isempty(type)) type = 'gaussian'; end if (nargin < 2 || isempty(sz)) sz = [3 3 3]; end if (nargin < 3 || isempty(param)) switch type case 'gaussian' param = [1.0 1.0 1.0]; otherwise error('Filter type not implemented') end end % check that sizes are odd numbers if (any(~rem(sz,2))) error('Sizes have to be odd numbers') end % filter size to each side of 0 l = floor(sz/2); % compute filter switch type case 'gaussian' % filter domain [gr, gc, gs] = ndgrid(-l(1):l(1), -l(2):l(2), -l(3):l(3)); % compute gaussian function gr = gr / param(1); gc = gc / param(2); gs = gs / param(3); h = exp(-(gr.*gr + gc.*gc + gs.*gs)*.5); % normalize filtered intensity h = h / sum(h(:)); otherwise error('Filter type not implemented') end
using GoogleCloud using Base.Test @test 1 == 1
{-# OPTIONS --warning=error --safe --without-K #-} open import LogicalFormulae open import Orders.Total.Definition open import Orders.Total.Lemmas open import Maybe open import Agda.Primitive using (Level; lzero; lsuc; _⊔_) open import Vectors open import Numbers.Naturals.Semiring open import Numbers.Naturals.Order module KeyValue.LinearStore.Implementation {a b c} (keySet : Set a) (valueSet : Set b) (keyOrder : TotalOrder {_} keySet {c}) where record ReducedMap (min : keySet) : Set (a ⊔ b ⊔ c) record ReducedMap min where inductive field firstEntry : valueSet next : Maybe (Sg keySet (λ nextKey → (ReducedMap nextKey) && (TotalOrder._<_ keyOrder min nextKey))) addReducedMap : {min : keySet} → (k : keySet) → (v : valueSet) → (m : ReducedMap min) → ReducedMap (TotalOrder.min keyOrder min k) addReducedMap {min} k v m with TotalOrder.totality keyOrder min k addReducedMap {min} k v record { firstEntry = firstEntry ; next = no } | inl (inl min<k) = record { firstEntry = firstEntry ; next = yes (k , (record { firstEntry = v ; next = no} ,, min<k))} addReducedMap {min} k v record { firstEntry = minVal ; next = yes (nextKey , (m ,, pr)) } | inl (inl min<k) = record { firstEntry = minVal ; next = yes ((TotalOrder.min keyOrder nextKey k) , (addReducedMap {_} k v m ,, minFromBoth keyOrder pr min<k))} addReducedMap {min} k v record { firstEntry = firstEntry ; next = next } | inl (inr k<min) = record { firstEntry = v ; next = yes (min , (record { firstEntry = firstEntry ; next = next } ,, k<min)) } addReducedMap {min} k v record { firstEntry = firstEntry ; next = next } | inr min=k rewrite min=k = record { firstEntry = v ; next = next } lookupReduced : {min : keySet} → (m : ReducedMap min) → (target : keySet) → Maybe valueSet lookupReduced {min} m k with TotalOrder.totality keyOrder min k lookupReduced {min} record { firstEntry = firstEntry ; next = no } k | inl (inl min<k) = no lookupReduced {min} record { firstEntry = firstEntry ; next = (yes (newMin , (m ,, _))) } k | inl (inl min<k) = lookupReduced {newMin} m k lookupReduced {min} m k | inl (inr k<min) = no lookupReduced {min} record { firstEntry = firstEntry ; next = next } k | inr min=k = yes firstEntry countReduced : {min : keySet} → (m : ReducedMap min) → ℕ countReduced record { firstEntry = firstEntry ; next = no } = 1 countReduced record { firstEntry = firstEntry ; next = (yes (key , (m ,, pr))) } = succ (countReduced m) lookupReducedSucceedsAfterAdd : {min : keySet} → (k : keySet) → (v : valueSet) → (m : ReducedMap min) → (lookupReduced (addReducedMap k v m) k ≡ yes v) lookupReducedSucceedsAfterAdd {min} k v m with TotalOrder.totality keyOrder min k lookupReducedSucceedsAfterAdd {min} k v record { firstEntry = firstEntry ; next = no } | inl (inl min<k) with TotalOrder.totality keyOrder min k lookupReducedSucceedsAfterAdd {min} k v record { firstEntry = firstEntry ; next = no } | inl (inl min<k) | inl (inl _) with TotalOrder.totality keyOrder k k lookupReducedSucceedsAfterAdd {min} k v record { firstEntry = firstEntry ; next = no } | inl (inl min<k) | inl (inl _) | inl (inl k<k) = exFalso (TotalOrder.irreflexive keyOrder k<k) lookupReducedSucceedsAfterAdd {min} k v record { firstEntry = firstEntry ; next = no } | inl (inl min<k) | inl (inl _) | inl (inr k<k) = exFalso (TotalOrder.irreflexive keyOrder k<k) lookupReducedSucceedsAfterAdd {min} k v record { firstEntry = firstEntry ; next = no } | inl (inl min<k) | inl (inl _) | inr p = refl lookupReducedSucceedsAfterAdd {min} k v record { firstEntry = firstEntry ; next = no } | inl (inl min<k) | inl (inr k<min) = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder min<k k<min)) lookupReducedSucceedsAfterAdd {min} k v record { firstEntry = firstEntry ; next = no } | inl (inl min<k) | inr min=k rewrite min=k = exFalso (TotalOrder.irreflexive keyOrder min<k) lookupReducedSucceedsAfterAdd {min} k v record { firstEntry = firstEntry ; next = (yes (newMin , (m ,, pr))) } | inl (inl min<k) with TotalOrder.totality keyOrder min k lookupReducedSucceedsAfterAdd {min} k v record { firstEntry = firstEntry ; next = (yes (newMin , (m ,, pr))) } | inl (inl min<k) | inl (inl _) = lookupReducedSucceedsAfterAdd k v m lookupReducedSucceedsAfterAdd {min} k v record { firstEntry = firstEntry ; next = (yes (newMin , (m ,, pr))) } | inl (inl min<k) | inl (inr k<min) = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder min<k k<min)) lookupReducedSucceedsAfterAdd {min} k v record { firstEntry = firstEntry ; next = (yes (newMin , (m ,, pr))) } | inl (inl min<k) | inr min=k rewrite min=k = exFalso (TotalOrder.irreflexive keyOrder min<k) lookupReducedSucceedsAfterAdd {min} k v m | inl (inr k<min) with TotalOrder.totality keyOrder k k lookupReducedSucceedsAfterAdd {min} k v m | inl (inr k<min) | inl (inl k<k) = exFalso (TotalOrder.irreflexive keyOrder k<k) lookupReducedSucceedsAfterAdd {min} k v m | inl (inr k<min) | inl (inr k<k) = exFalso (TotalOrder.irreflexive keyOrder k<k) lookupReducedSucceedsAfterAdd {min} k v m | inl (inr k<min) | inr p = refl lookupReducedSucceedsAfterAdd {min} k v m | inr min=k with TotalOrder.totality keyOrder k k lookupReducedSucceedsAfterAdd {min} k v m | inr min=k | inl (inl k<k) = exFalso (TotalOrder.irreflexive keyOrder k<k) lookupReducedSucceedsAfterAdd {min} k v m | inr min=k | inl (inr k<k) = exFalso (TotalOrder.irreflexive keyOrder k<k) lookupReducedSucceedsAfterAdd {min} k v m | inr min=k | inr p with TotalOrder.totality keyOrder min k lookupReducedSucceedsAfterAdd {min} k v m | inr min=k | inr p | inl (inl min<k) rewrite min=k = exFalso (TotalOrder.irreflexive keyOrder min<k) lookupReducedSucceedsAfterAdd {min} k v m | inr min=k | inr p | inl (inr k<min) rewrite min=k = exFalso (TotalOrder.irreflexive keyOrder k<min) lookupReducedSucceedsAfterAdd {.k} k v record { firstEntry = firstEntry ; next = next } | inr refl | inr p | inr s = refl lookupReducedSucceedsAfterUnrelatedAdd : {min : keySet} → (unrelatedK : keySet) → (unrelatedV : valueSet) → (k : keySet) → (v : valueSet) → ((TotalOrder._<_ keyOrder unrelatedK k) || (TotalOrder._<_ keyOrder k unrelatedK)) → (m : ReducedMap min) → (lookupReduced m k ≡ yes v) → lookupReduced (addReducedMap unrelatedK unrelatedV m) k ≡ yes v lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v pr m lookupReducedSucceeds with TotalOrder.totality keyOrder min k' lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v pr m lookupReducedSucceeds | inl (inl min<k') with TotalOrder.totality keyOrder min k lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v pr record { firstEntry = firstEntry ; next = no } () | inl (inl min<k') | inl (inl min<k) lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v pr record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } lookupReducedSucceeds | inl (inl min<k') | inl (inl min<k) = lookupReducedSucceedsAfterUnrelatedAdd {a} k' v' k v pr fst lookupReducedSucceeds lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v (inl x) m lookupReducedSucceeds | inl (inl min<k') | inl (inr k<min) = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder k<min (TotalOrder.<Transitive keyOrder min<k' x))) lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v (inr k<k') m () | inl (inl min<k') | inl (inr k<min) lookupReducedSucceedsAfterUnrelatedAdd {.min} k' v' min v (inl x) m lookupReducedSucceeds | inl (inl min<k') | inr refl = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder x min<k')) lookupReducedSucceedsAfterUnrelatedAdd {.min} k' v' min v (inr x) record { firstEntry = v2 ; next = no } p | inl (inl min<k') | inr refl = applyEquality yes (yesInjective p) lookupReducedSucceedsAfterUnrelatedAdd {.min} k' v' min v (inr x) record { firstEntry = .v ; next = (yes (a , b)) } refl | inl (inl min<k') | inr refl = applyEquality yes refl lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v pr m lookupReducedSucceeds | inl (inr k'<min) with TotalOrder.totality keyOrder k' k lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v pr m lookupReducedSucceeds | inl (inr k'<min) | inl (inl k'<k) with TotalOrder.totality keyOrder min k lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v pr m lookupReducedSucceeds | inl (inr k'<min) | inl (inl k'<k) | inl (inl min<k) = lookupReducedSucceeds lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v pr m () | inl (inr k'<min) | inl (inl k'<k) | inl (inr k<min) lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v pr m lookupReducedSucceeds | inl (inr k'<min) | inl (inl k'<k) | inr refl = lookupReducedSucceeds lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v (inl x) m lookupReducedSucceeds | inl (inr k'<min) | inl (inr k<k') = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder x k<k')) lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v (inr x) m lookupReducedSucceeds | inl (inr k'<min) | inl (inr k<k') with TotalOrder.totality keyOrder min k lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v (inr _) m lookupReducedSucceeds | inl (inr k'<min) | inl (inr k<k') | inl (inl x) = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder x (TotalOrder.<Transitive keyOrder k<k' k'<min))) lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v (inr _) m () | inl (inr k'<min) | inl (inr k<k') | inl (inr x) lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v (inr _) m lookupReducedSucceeds | inl (inr k'<min) | inl (inr k<k') | inr x rewrite x = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder k<k' k'<min)) lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v (inl x) m lookupReducedSucceeds | inl (inr k'<min) | inr k'=k rewrite k'=k = exFalso (TotalOrder.irreflexive keyOrder x) lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v (inr x) m lookupReducedSucceeds | inl (inr k'<min) | inr k'=k rewrite k'=k = exFalso (TotalOrder.irreflexive keyOrder x) lookupReducedSucceedsAfterUnrelatedAdd {min} k' v' k v pr m lookupReducedSucceeds | inr refl with TotalOrder.totality keyOrder min k lookupReducedSucceedsAfterUnrelatedAdd {k'} k' v' k v (inl _) record { firstEntry = firstEntry ; next = no } () | inr refl | inl (inl min<k) lookupReducedSucceedsAfterUnrelatedAdd {k'} k' v' k v (inl _) record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } lookupReducedSucceeds | inr refl | inl (inl min<k) = lookupReducedSucceeds lookupReducedSucceedsAfterUnrelatedAdd {k'} k' v' k v (inr x) m lookupReducedSucceeds | inr refl | inl (inl min<k) = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder min<k x)) lookupReducedSucceedsAfterUnrelatedAdd {k'} k' v' k v (inl x) m () | inr refl | inl (inr k<min) lookupReducedSucceedsAfterUnrelatedAdd {k'} k' v' k v (inr x) m () | inr refl | inl (inr k<min) lookupReducedSucceedsAfterUnrelatedAdd {.min} .min v' min v (inl x) m lookupReducedSucceeds | inr refl | inr refl = exFalso (TotalOrder.irreflexive keyOrder x) lookupReducedSucceedsAfterUnrelatedAdd {.min} .min v' min v (inr x) m lookupReducedSucceeds | inr refl | inr refl = exFalso (TotalOrder.irreflexive keyOrder x) lookupReducedFailsAfterUnrelatedAdd : {min : keySet} → (unrelatedK : keySet) → (unrelatedV : valueSet) → (k : keySet) → ((TotalOrder._<_ keyOrder unrelatedK k) || (TotalOrder._<_ keyOrder k unrelatedK)) → (m : ReducedMap min) → (lookupReduced m k ≡ no) → lookupReduced (addReducedMap unrelatedK unrelatedV m) k ≡ no lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr m lookupReducedFails with TotalOrder.totality keyOrder min k' lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr m lookupReducedFails | inl (inl min<k') with TotalOrder.totality keyOrder min k lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr record { firstEntry = firstEntry ; next = no } lookupReducedFails | inl (inl min<k') | inl (inl min<k) with TotalOrder.totality keyOrder k' k lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr record { firstEntry = firstEntry ; next = no } lookupReducedFails | inl (inl min<k') | inl (inl min<k) | inl (inl x) = refl lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr record { firstEntry = firstEntry ; next = no } lookupReducedFails | inl (inl min<k') | inl (inl min<k) | inl (inr x) = refl lookupReducedFailsAfterUnrelatedAdd {min} .k v' k (inl x) record { firstEntry = firstEntry ; next = no } lookupReducedFails | inl (inl min<k') | inl (inl min<k) | inr refl = exFalso (TotalOrder.irreflexive keyOrder x) lookupReducedFailsAfterUnrelatedAdd {min} .k v' k (inr x) record { firstEntry = firstEntry ; next = no } lookupReducedFails | inl (inl min<k') | inl (inl min<k) | inr refl = exFalso (TotalOrder.irreflexive keyOrder x) lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } lookupReducedFails | inl (inl min<k') | inl (inl min<k) = lookupReducedFailsAfterUnrelatedAdd k' v' k pr fst lookupReducedFails lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr m lookupReducedFails | inl (inl min<k') | inl (inr k<min) = refl lookupReducedFailsAfterUnrelatedAdd {.min} k' v' min pr m () | inl (inl min<k') | inr refl lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr m lookupReducedFails | inl (inr k'<min) with TotalOrder.totality keyOrder min k lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr record { firstEntry = firstEntry ; next = next } lookupReducedFails | inl (inr k'<min) | inl (inl min<k) with TotalOrder.totality keyOrder k' k lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr record { firstEntry = firstEntry ; next = next } lookupReducedFails | inl (inr k'<min) | inl (inl min<k) | inl (inl k'<k) with TotalOrder.totality keyOrder min k lookupReducedFailsAfterUnrelatedAdd {min} k' v' k (inl x₁) record { firstEntry = firstEntry ; next = no } lookupReducedFails | inl (inr k'<min) | inl (inl min<k) | inl (inl k'<k) | inl (inl _) = refl lookupReducedFailsAfterUnrelatedAdd {min} k' v' k (inl x₁) record { firstEntry = firstEntry ; next = (yes (a , b)) } lookupReducedFails | inl (inr k'<min) | inl (inl min<k) | inl (inl k'<k) | inl (inl _) = lookupReducedFails lookupReducedFailsAfterUnrelatedAdd {min} k' v' k (inr x₁) record { firstEntry = firstEntry ; next = no } lookupReducedFails | inl (inr k'<min) | inl (inl min<k) | inl (inl k'<k) | inl (inl _) = refl lookupReducedFailsAfterUnrelatedAdd {min} k' v' k (inr x₁) record { firstEntry = firstEntry ; next = (yes (a , b)) } lookupReducedFails | inl (inr k'<min) | inl (inl min<k) | inl (inl k'<k) | inl (inl _) = lookupReducedFails lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr record { firstEntry = firstEntry ; next = next } lookupReducedFails | inl (inr k'<min) | inl (inl min<k) | inl (inl k'<k) | inl (inr x) = refl lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr record { firstEntry = firstEntry ; next = next } lookupReducedFails | inl (inr k'<min) | inl (inl min<k) | inl (inl k'<k) | inr refl = exFalso (TotalOrder.irreflexive keyOrder min<k) lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr record { firstEntry = firstEntry ; next = next } lookupReducedFails | inl (inr k'<min) | inl (inl min<k) | inl (inr k<k') = refl lookupReducedFailsAfterUnrelatedAdd {min} .k v' k (inl x) record { firstEntry = firstEntry ; next = next } lookupReducedFails | inl (inr k'<min) | inl (inl min<k) | inr refl = exFalso (TotalOrder.irreflexive keyOrder x) lookupReducedFailsAfterUnrelatedAdd {min} .k v' k (inr x) record { firstEntry = firstEntry ; next = next } lookupReducedFails | inl (inr k'<min) | inl (inl min<k) | inr refl = exFalso (TotalOrder.irreflexive keyOrder x) lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr m lookupReducedFails | inl (inr k'<min) | inl (inr k<min) with TotalOrder.totality keyOrder k' k lookupReducedFailsAfterUnrelatedAdd {min} k' v' k (inl _) m lookupReducedFails | inl (inr k'<min) | inl (inr k<min) | inl (inl k'<k) with TotalOrder.totality keyOrder min k lookupReducedFailsAfterUnrelatedAdd {min} k' v' k (inl _) m lookupReducedFails | inl (inr k'<min) | inl (inr k<min) | inl (inl k'<k) | inl (inl min<k) = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder k<min min<k)) lookupReducedFailsAfterUnrelatedAdd {min} k' v' k (inl _) m lookupReducedFails | inl (inr k'<min) | inl (inr k<min) | inl (inl k'<k) | inl (inr k<min') = refl lookupReducedFailsAfterUnrelatedAdd {min} k' v' k (inl _) m lookupReducedFails | inl (inr k'<min) | inl (inr k<min) | inl (inl k'<k) | inr refl = exFalso (TotalOrder.irreflexive keyOrder k<min) lookupReducedFailsAfterUnrelatedAdd {min} k' v' k (inr x) m lookupReducedFails | inl (inr k'<min) | inl (inr k<min) | inl (inl k'<k) = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder k'<k x)) lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr m lookupReducedFails | inl (inr k'<min) | inl (inr k<min) | inl (inr k<k') = refl lookupReducedFailsAfterUnrelatedAdd {min} .k v' k (inl x) m lookupReducedFails | inl (inr k'<min) | inl (inr k<min) | inr refl = exFalso (TotalOrder.irreflexive keyOrder x) lookupReducedFailsAfterUnrelatedAdd {min} .k v' k (inr x) m lookupReducedFails | inl (inr k'<min) | inl (inr k<min) | inr refl = exFalso (TotalOrder.irreflexive keyOrder x) lookupReducedFailsAfterUnrelatedAdd {min} k' v' k pr m () | inl (inr k'<min) | inr min=k lookupReducedFailsAfterUnrelatedAdd {min} .min v' k pr m lookupReducedFails | inr refl with TotalOrder.totality keyOrder min k lookupReducedFailsAfterUnrelatedAdd {min} .min v' k pr record { firstEntry = firstEntry ; next = no } lookupReducedFails | inr refl | inl (inl min<k) = refl lookupReducedFailsAfterUnrelatedAdd {min} .min v' k pr record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } lookupReducedFails | inr refl | inl (inl min<k) = lookupReducedFails lookupReducedFailsAfterUnrelatedAdd {min} .min v' k pr m lookupReducedFails | inr refl | inl (inr k<min) = refl lookupReducedFailsAfterUnrelatedAdd {min} .min v' k pr m () | inr refl | inr min=k countReducedBehavesWhenAddingNotPresent : {min : keySet} → (k : keySet) → (v : valueSet) → (m : ReducedMap min) → (lookupReduced m k ≡ no) → countReduced (addReducedMap k v m) ≡ succ (countReduced m) countReducedBehavesWhenAddingNotPresent {min} k v m lookupReducedFails with TotalOrder.totality keyOrder k min countReducedBehavesWhenAddingNotPresent {min} k v record { firstEntry = firstEntry ; next = next } lookupReducedFails | inl (inl k<min) with TotalOrder.totality keyOrder min k countReducedBehavesWhenAddingNotPresent {min} k v record { firstEntry = firstEntry ; next = next } lookupReducedFails | inl (inl k<min) | inl (inl min<k) = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder min<k k<min)) countReducedBehavesWhenAddingNotPresent {min} k v record { firstEntry = firstEntry ; next = next } lookupReducedFails | inl (inl k<min) | inl (inr _) = refl countReducedBehavesWhenAddingNotPresent {min} k v record { firstEntry = firstEntry ; next = next } lookupReducedFails | inl (inl k<min) | inr refl = exFalso (TotalOrder.irreflexive keyOrder k<min) countReducedBehavesWhenAddingNotPresent {min} k v record { firstEntry = firstEntry ; next = next } lookupReducedFails | inl (inr min<k) with TotalOrder.totality keyOrder min k countReducedBehavesWhenAddingNotPresent {min} k v record { firstEntry = firstEntry ; next = no } lookupReducedFails | inl (inr min<k) | inl (inl _) = refl countReducedBehavesWhenAddingNotPresent {min} k v record { firstEntry = firstEntry ; next = (yes (a , b)) } lookupReducedFails | inl (inr min<k) | inl (inl _) = applyEquality succ (countReducedBehavesWhenAddingNotPresent k v (_&&_.fst b) lookupReducedFails) countReducedBehavesWhenAddingNotPresent {min} k v record { firstEntry = firstEntry ; next = next } lookupReducedFails | inl (inr min<k) | inl (inr k<min) = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder min<k k<min)) countReducedBehavesWhenAddingNotPresent {min} k v record { firstEntry = firstEntry ; next = next } lookupReducedFails | inl (inr min<k) | inr refl = exFalso (TotalOrder.irreflexive keyOrder min<k) countReducedBehavesWhenAddingNotPresent {min} k v m lookupReducedFails | inr refl with TotalOrder.totality keyOrder min min countReducedBehavesWhenAddingNotPresent {k} k v m lookupReducedFails | inr refl | inl (inl min<min) = exFalso (TotalOrder.irreflexive keyOrder min<min) countReducedBehavesWhenAddingNotPresent {k} k v m lookupReducedFails | inr refl | inl (inr min<min) = exFalso (TotalOrder.irreflexive keyOrder min<min) countReducedBehavesWhenAddingNotPresent {k} k v record { firstEntry = firstEntry ; next = no } () | inr refl | inr p countReducedBehavesWhenAddingNotPresent {k} k v record { firstEntry = firstEntry ; next = (yes x) } () | inr refl | inr p countReducedBehavesWhenAddingPresent : {min : keySet} → (k : keySet) → (v v' : valueSet) → (m : ReducedMap min) → (lookupReduced m k ≡ yes v') → countReduced (addReducedMap k v m) ≡ countReduced m countReducedBehavesWhenAddingPresent {min} k v v' m lookupReducedSucceeds with TotalOrder.totality keyOrder k min countReducedBehavesWhenAddingPresent {min} k v v' m lookupReducedSucceeds | inl (inl k<min) with TotalOrder.totality keyOrder min k countReducedBehavesWhenAddingPresent {min} k v v' m lookupReducedSucceeds | inl (inl k<min) | inl (inl min<k) = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder k<min min<k)) countReducedBehavesWhenAddingPresent {min} k v v' m () | inl (inl k<min) | inl (inr _) countReducedBehavesWhenAddingPresent {min} k v v' m lookupReducedSucceeds | inl (inl k<min) | inr q = exFalso (TotalOrder.irreflexive keyOrder (identityOfIndiscernablesLeft (TotalOrder._<_ keyOrder) k<min (equalityCommutative q))) countReducedBehavesWhenAddingPresent {min} k v v' m lookupReducedSucceeds | inl (inr min<k) with TotalOrder.totality keyOrder min k countReducedBehavesWhenAddingPresent {min} k v v' record { firstEntry = firstEntry ; next = no } () | inl (inr min<k) | inl (inl _) countReducedBehavesWhenAddingPresent {min} k v v' record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } lookupReducedSucceeds | inl (inr min<k) | inl (inl _) = applyEquality succ (countReducedBehavesWhenAddingPresent k v v' fst lookupReducedSucceeds) countReducedBehavesWhenAddingPresent {min} k v v' m () | inl (inr min<k) | inl (inr k<min) countReducedBehavesWhenAddingPresent {min} k v v' m lookupReducedSucceeds | inl (inr min<k) | inr q = exFalso (TotalOrder.irreflexive keyOrder (identityOfIndiscernablesLeft (λ a b → TotalOrder._<_ keyOrder a b) min<k q)) countReducedBehavesWhenAddingPresent {min} k v v' m lookupReducedSucceeds | inr q with TotalOrder.totality keyOrder min min countReducedBehavesWhenAddingPresent {min} k v v' m lookupReducedSucceeds | inr q | inl (inl x) = exFalso (TotalOrder.irreflexive keyOrder x) countReducedBehavesWhenAddingPresent {min} k v v' m lookupReducedSucceeds | inr q | inl (inr x) = exFalso (TotalOrder.irreflexive keyOrder x) countReducedBehavesWhenAddingPresent {min} k v v' record { firstEntry = firstEntry ; next = no } lookupReducedSucceeds | inr _ | inr p with TotalOrder.totality keyOrder min k countReducedBehavesWhenAddingPresent {min} k v v' record { firstEntry = firstEntry ; next = no } () | inr _ | inr p | inl (inl x) countReducedBehavesWhenAddingPresent {min} k v v' record { firstEntry = firstEntry ; next = no } () | inr _ | inr p | inl (inr x`) countReducedBehavesWhenAddingPresent {.k} k v v' record { firstEntry = firstEntry ; next = no } lookupReducedSucceeds | inr q | inr p | inr refl = refl countReducedBehavesWhenAddingPresent {min} k v v' record { firstEntry = firstEntry ; next = (yes (a , b)) } lookupReducedSucceeds | inr q | inr p with TotalOrder.totality keyOrder k k countReducedBehavesWhenAddingPresent {min} k v v' record { firstEntry = firstEntry ; next = (yes (a , b)) } lookupReducedSucceeds | inr q | inr p | inl (inl x) = exFalso (TotalOrder.irreflexive keyOrder x) countReducedBehavesWhenAddingPresent {min} k v v' record { firstEntry = firstEntry ; next = (yes (a , b)) } lookupReducedSucceeds | inr q | inr p | inl (inr x) = exFalso (TotalOrder.irreflexive keyOrder x) countReducedBehavesWhenAddingPresent {min} k v v' record { firstEntry = firstEntry ; next = (yes (a , (m ,, pr))) } q | inr q1 | inr p | inr x with TotalOrder.totality keyOrder min k countReducedBehavesWhenAddingPresent {.k} k v v' record { firstEntry = firstEntry ; next = (yes (a , (m ,, pr))) } q | inr refl | inr p | inr x | inl (inl min<k) = exFalso (TotalOrder.irreflexive keyOrder min<k) countReducedBehavesWhenAddingPresent {.k} k v v' record { firstEntry = firstEntry ; next = (yes (a , (m ,, pr))) } q | inr q1 | inr p | inr x | inr refl = refl data Map : Set (a ⊔ b ⊔ c) where empty : Map nonempty : {min : keySet} → ReducedMap min → Map addMap : (m : Map) → (k : keySet) → (v : valueSet) → Map addMap empty k v = nonempty {min = k} record { firstEntry = v ; next = no } addMap (nonempty x) k v = nonempty (addReducedMap k v x) lookup : (m : Map) → (target : keySet) → Maybe valueSet lookup empty t = no lookup (nonempty x) t = lookupReduced x t count : (m : Map) → ℕ count empty = 0 count (nonempty x) = countReduced x keysReduced : {min : keySet} → (m : ReducedMap min) → Vec keySet (countReduced m) keysReduced {min = min} record { firstEntry = firstEntry ; next = no } = min ,- [] keysReduced {min = min} record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } = min ,- (keysReduced fst) keys : (m : Map) → Vec keySet (count m) keys empty = [] keys (nonempty m) = keysReduced m lookupReducedWhenLess : {min : keySet} → (m : ReducedMap min) → (k : keySet) → (TotalOrder._<_ keyOrder k min) → (lookupReduced m k ≡ no) lookupReducedWhenLess {min} m k k<min with TotalOrder.totality keyOrder min k lookupReducedWhenLess {min} m k k<min | inl (inl min<k) = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder k<min min<k)) lookupReducedWhenLess {min} m k k<min | inl (inr _) = refl lookupReducedWhenLess {min} m k k<min | inr min=k rewrite min=k = exFalso (TotalOrder.irreflexive keyOrder k<min) lookupCertainReduced : {min : keySet} → (m : ReducedMap min) → (k : keySet) → (vecContains (keysReduced m) k) → Sg valueSet (λ v → lookupReduced m k ≡ yes v) lookupCertainReduced {min} record { firstEntry = firstEntry ; next = no } k pr = firstEntry , q where t : min ≡ k t = vecSolelyContains k pr q : lookupReduced {min} (record { firstEntry = firstEntry ; next = no }) k ≡ yes firstEntry q with TotalOrder.totality keyOrder k k q | inl (inl k<k) = exFalso (TotalOrder.irreflexive keyOrder k<k) q | inl (inr k<k) = exFalso (TotalOrder.irreflexive keyOrder k<k) q | inr p with TotalOrder.totality keyOrder min k q | inr p | inl (inl min<k) rewrite t = exFalso (TotalOrder.irreflexive keyOrder min<k) q | inr p | inl (inr k<min) rewrite t = exFalso (TotalOrder.irreflexive keyOrder k<min) q | inr p | inr x = refl lookupCertainReduced {min} record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } k pr with TotalOrder.totality keyOrder min k lookupCertainReduced {min} record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } k record { index = zero ; index<m = _ ; isHere = isHere } | inl (inl min<k) rewrite isHere = exFalso (TotalOrder.irreflexive keyOrder min<k) lookupCertainReduced {min} record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } k record { index = (succ index) ; index<m = index<m ; isHere = isHere } | inl (inl min<k) = lookupCertainReduced fst k record { index = index ; index<m = canRemoveSuccFrom<N index<m ; isHere = isHere } lookupCertainReduced {min} record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } k record { index = zero ; index<m = _ ; isHere = isHere } | inl (inr k<min) rewrite isHere = exFalso (TotalOrder.irreflexive keyOrder k<min) lookupCertainReduced {min} record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } k record { index = (succ index) ; index<m = index<m ; isHere = isHere } | inl (inr k<min) with TotalOrder.totality keyOrder a k lookupCertainReduced {min} record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } k record { index = (succ index) ; index<m = index<m ; isHere = isHere } | inl (inr k<min) | inl (inl a<k) = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder k<min (TotalOrder.<Transitive keyOrder snd a<k))) lookupCertainReduced {min} record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } k record { index = (succ index) ; index<m = index<m ; isHere = isHere } | inl (inr k<min) | inl (inr k<a) = exFalso h where f : Sg valueSet (λ v → lookupReduced fst k ≡ yes v) f = lookupCertainReduced fst k record { index = index ; index<m = canRemoveSuccFrom<N index<m ; isHere = isHere } g : lookupReduced fst k ≡ no g = lookupReducedWhenLess fst k k<a noIsNotYes : {a : _} → {A : Set a} → {b : A} → (no ≡ yes b) → False noIsNotYes {a} {A} {b} () h : False h with f h | a , b rewrite g = noIsNotYes b lookupCertainReduced {min} record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } k record { index = (succ index) ; index<m = index<m ; isHere = isHere } | inl (inr k<min) | inr refl = exFalso (TotalOrder.irreflexive keyOrder (TotalOrder.<Transitive keyOrder snd k<min)) lookupCertainReduced {min} record { firstEntry = firstEntry ; next = (yes (a , (fst ,, snd))) } k pr | inr min=k = firstEntry , refl lookupCertain : (m : Map) → (k : keySet) → (vecContains (keys m) k) → Sg valueSet (λ v → lookup m k ≡ yes v) lookupCertain empty k record { index = index ; index<m = (le x ()) ; isHere = isHere } lookupCertain (nonempty {min} m) k pr = lookupCertainReduced {min} m k pr
program TeaBreak; begin ;;;;;;;;;; writeln ( 'Say "BREAK!!" ' ) ; ;;;;;;;;;; break end.
(** * Bicolano: Big step (interface only) *) (* <Insert License Here> $Id: BigStep.v 68 2006-02-02 15:06:27Z davidpichardie $ *) (** Big step semantics. @author Benjamin Gregoire *) (* Hendra : - Modified to suit DEX program. - Also trim the system to contain only Arithmetic *) Require Export DEX_Domain. Set Implicit Arguments. Definition cons_option (A:Set) (o:option A) (l:list A) := match o with | None => l | Some e => e::l end. Unset Implicit Arguments. Section TRANS. Set Implicit Arguments. Variable A B :Type. Variable R : A -> A + B -> Prop. Inductive TransStep_l : A -> A + B -> Prop := | TransStep_l_refl : forall a, TransStep_l a (inl _ a) | TransStep_l_one : forall a r, R a r -> TransStep_l a r | TransStep_l_trans : forall a1 a2 r, R a1 (inl _ a2) -> TransStep_l a2 r -> TransStep_l a1 r. Variable R' : A -> A -> Prop. Inductive ClosReflTrans : A -> A -> Prop := | ClosReflTrans_refl : forall a, ClosReflTrans a a | ClosReflTrans_trans : forall a a' a'', R' a a' -> ClosReflTrans a' a'' -> ClosReflTrans a a''. Unset Implicit Arguments. End TRANS. Open Scope type_scope. Module Type DEX_BIGSTEP. Declare Module DEX_Dom : DEX_SEMANTIC_DOMAIN. Load "DEX_BigStepLoad.v". Parameter IntraStepStar_ind : forall (p:DEX_Program) (P : DEX_Method -> DEX_IntraNormalState -> DEX_IntraNormalState + DEX_ReturnState -> Prop), (forall m s, P m s (inl _ s)) -> (forall m s r, DEX_exec_return p m s r -> P m s (inr _ r)) -> (forall m s s' , DEX_exec_intra p m s s' -> forall r, DEX_IntraStepStar p m s' r -> P m s' r -> P m s r) -> forall m s r, DEX_IntraStepStar p m s r -> P m s r. Parameter IntraStepStar_intra_ind : forall (p:DEX_Program) (P : DEX_Method -> DEX_IntraNormalState -> DEX_IntraNormalState -> Prop), (forall m s, P m s s) -> (forall m s s', DEX_exec_intra p m s s' -> forall s'', DEX_IntraStepStar_intra p m s' s'' -> P m s' s'' -> P m s s'') -> forall m s s', DEX_IntraStepStar_intra p m s s' -> P m s s'. Parameter BigStep_ind : forall (p:DEX_Program) (P : DEX_Method -> DEX_IntraNormalState -> DEX_ReturnState -> Prop), (forall m s r, DEX_exec_return p m s r -> P m s r) -> (forall m s s' , DEX_exec_intra p m s s' -> forall r, DEX_BigStep p m s' r -> P m s' r -> P m s r) -> forall m s r, DEX_BigStep p m s r -> P m s r. Parameter ReachableStar_ind : forall (p:DEX_Program) (P : (DEX_Method * DEX_IntraNormalState) -> (DEX_Method * DEX_IntraNormalState) -> Prop), (forall m s, P (m,s) (m,s)) -> (forall m s s', DEX_exec_intra p m s s' -> forall m' s'', ClosReflTrans (DEX_ReachableStep p) (m,s') (m',s'') -> P (m,s') (m',s'') -> P (m,s) (m',s'')) -> forall ms ms', ClosReflTrans (DEX_ReachableStep p) ms ms' -> P ms ms'. End DEX_BIGSTEP.
(* * SPDX-License-Identifier: MIT * *) From Coq Require Import List Lia. From SPICY Require Import MyPrelude Maps ChMaps Messages Keys Automation Tactics Simulation AdversaryUniverse ModelCheck.SafeProtocol ModelCheck.ProtocolFunctions ModelCheck.SilentStepElimination ModelCheck.SteppingTactics ModelCheck.InvariantSearch . From protocols Require Import GenProto. From SPICY Require IdealWorld RealWorld. Import IdealWorld.IdealNotations RealWorld.RealWorldNotations SimulationAutomation. From Frap Require Sets. Module Foo <: Sets.EMPTY. End Foo. Module Import SN := Sets.SetNotations(Foo). Set Implicit Arguments. Open Scope protocol_scope. Module MyProtocolSecure <: AutomatedSafeProtocolSS. Import MyProtocol. (* Some things may need to change here. t__hon is where we place the * type that the protocol computes. It is set to Nat now, because we * return a natual number. *) Definition t__hon := Nat. Definition t__adv := Unit. Definition b := tt. (* These two variables hook up the starting points for both specification and * implementation universes. If you followed the template above, this shouldn't * need to be changed. *) Definition iu0 := ideal_univ_start. Definition ru0 := real_univ_start. Import Gen Tacs. (* These are here to help the proof automation. Don't change. *) #[export] Hint Unfold t__hon t__adv b ru0 iu0 ideal_univ_start real_univ_start : core. #[export] Hint Unfold mkiU mkiUsr mkrU mkrUsr mkKeys : core. (* (* Set Ltac Profiling. *) *) Lemma safe_invariant : invariantFor {| Initial := {(ru0, iu0, true)}; Step := @stepSS t__hon t__adv |} (@safety_inv t__hon t__adv). (* (fun st => safety st /\ alignment st /\ returns_align st). *) Proof. unfold invariantFor ; unfold Initial, Step ; intros ; simpl in * ; split_ors ; try contradiction ; subst. autounfold in H0 ; unfold fold_left, fst, snd in *. time ( repeat transition_system_step ). Unshelve. all: exact 0 || auto. Qed. Lemma U_good : @universe_starts_sane _ Unit b ru0. Proof. autounfold; unfold universe_starts_sane; simpl. repeat (apply conj); intros; eauto. - focus_user; auto. - econstructor. - unfold AdversarySafety.keys_honest; rewrite Forall_natmap_forall; intros. unfold mkrUsr; simpl. rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty; eauto. - unfold lameAdv; simpl; eauto. Qed. Lemma universe_starts_safe : universe_ok ru0. Proof. pose proof (adversary_is_lame_adv_univ_ok_clauses U_good). unfold universe_ok ; autounfold ; simpl ; intuition eauto . - econstructor; eauto. - unfold keys_and_permissions_good; solve_simple_maps; intuition eauto. solve_simple_maps; eauto. rewrite Forall_natmap_forall; intros. solve_simple_maps; simpl ; unfold permission_heap_good; intros; solve_simple_maps; solve_concrete_maps; eauto. - unfold user_cipher_queues_ok. rewrite Forall_natmap_forall; intros. focus_user ; simpl in *; econstructor; eauto. - unfold honest_nonces_ok, honest_user_nonces_ok, honest_nonces_ok ; repeat simple apply conj ; intros ; clean_map_lookups ; intros ; focus_user ; try contradiction; try discriminate; simpl; repeat (apply conj); intros; clean_map_lookups; eauto. - unfold honest_users_only_honest_keys; intros. focus_user; subst; simpl in *; clean_map_lookups; unfold mkrUsr; simpl; rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty; eauto; simpl in *; solve_concrete_perm_merges; solve_concrete_maps; solve_simple_maps; eauto. Qed. End MyProtocolSecure.
line 1 line 2 line 3 line 4 line5 hello world
module DataTypes where import Control.Monad.Except import Data.Array import Data.Complex import Data.IORef import Data.Ratio import GHC.IO.Handle import ParserCombinators (ParseError) type Env = IORef EnvFrame type Bindings = [(String, IORef LispVal)] data EnvFrame = Global { bindings :: Bindings } | Frame { parent :: Env , bindings :: Bindings } type IOThrowsError = ExceptT LispError IO type PrimitiveFunc = ([LispVal] -> ThrowsError LispVal) type IOPrimitiveFunc = ([LispVal] -> IOThrowsError LispVal) type ThrowsError = Either LispError data LispError = NumArgs Arity Int [LispVal] | TypeMismatch String LispVal | Parser ParseError | BadSpecialForm String LispVal | NotFunction String String | UnboundVar String String | Default String instance Show LispError where show = showError data LispVal = Vector (Array Integer LispVal) | Atom String | List [LispVal] | DottedList [LispVal] LispVal | Integer Integer | Rational Rational | Float Double | Complex (Complex Double) | String String | Character Char | Bool Bool | IOFunc String IOPrimitiveFunc | Port Handle | PrimitiveFunc String PrimitiveFunc | Func { name :: String , params :: [String] , vararg :: (Maybe String) , body :: [LispVal] , closure :: Env } | Void instance Show LispVal where show = showVal data Arity = Min Int | MinMax Int Int unwordsList :: [LispVal] -> String unwordsList = unwords . map showVal showVal :: LispVal -> String showVal (String contents) = "\"" ++ contents ++ "\"" showVal (Atom name') = name' showVal (Integer contents) = show contents showVal (Rational contents) = show (numerator contents) ++ "/" ++ show (denominator contents) showVal (Float contents) = show contents showVal (Complex contents) = show (realPart contents) ++ (if imagPart contents < 0 then "" else "+") ++ show (imagPart contents) ++ "i" showVal (Character contents) = show contents showVal (Bool True) = "#t" showVal (Bool False) = "#f" showVal (List contents) = "(" ++ unwordsList contents ++ ")" showVal (Vector contents) = "#(" ++ unwordsList (elems contents) ++ ")" showVal (DottedList h t) = "(" ++ unwordsList h ++ " . " ++ showVal t ++ ")" showVal (PrimitiveFunc name' _) = "#<procedure:" ++ name' ++ ">" showVal Func {name = name'} = "#<procedure:" ++ name' ++ ">" showVal (Port _) = "<IO port>" showVal (IOFunc name' _) = "#<IO primitive:" ++ name' ++ ">" showVal Void = "" showError :: LispError -> String showError (Default message) = message showError (UnboundVar message varname) = message ++ ": " ++ varname showError (BadSpecialForm message form) = message ++ ": " ++ show form showError (NotFunction message func) = message ++ ": " ++ show func showError (NumArgs expected found args) = let error' = case expected of Min min' -> "arity mismatch;\nthe expected number of arguments does not match the given number" ++ "\nexpected: at least " ++ show min' ++ "\ngiven: " ++ show found MinMax min' max' -> "arity mismatch;\nthe expected number of arguments does not match the given number" ++ "\nexpected: " ++ (if min' == max' then show min' else "between " ++ show min' ++ " and " ++ show max') ++ "\ngiven: " ++ show found argsError = case args of [] -> "" a -> "\narguments:\n" ++ unwordsList a in error' ++ argsError showError (TypeMismatch expected found) = "Invalid type: expected " ++ expected ++ ", found " ++ show found showError (Parser parseErr) = "Parse error at " ++ show parseErr trapError :: (Show a, MonadError a m) => m String -> m String trapError action = catchError action (return . show) extractValue :: ThrowsError a -> a extractValue (Right val) = val
@kwdef mutable struct FxpSubHandler <: AbstractHandler id = 0 end @register(FxpSubHandler, -, [Number, Number] => [Number]) function (handler::FxpSubHandler)(netlist::Netlist, inputs::Vector{Variable}, outputs::Vector{Variable}) # check size if getsize(netlist, getname(inputs[1])) != (1, 1) && getsize(netlist, getname(inputs[1])) != (1, 1) error("FXP subtract does not support matrix hardware generation yet.") end outstring = """ $stdcomment // BEGIN f_sub$(handler.id) fxp_sub #( .BIT_WIDTH(BIT_WIDTH) ) f_sub$(handler.id) ( .a($(inputs[1].name)), .b($(inputs[2].name)), .y($(outputs[1].name)) ); // END f_sub$(handler.id) \n""" handler.id += 1 return outstring end
[STATEMENT] lemma blinfun_scaleR_rep_eq[simp]: "blinfun_scaleR a b c = a c *\<^sub>R b" [PROOF STATE] proof (prove) goal (1 subgoal): 1. blinfun_apply (blinfun_scaleR a b) c = blinfun_apply a c *\<^sub>R b [PROOF STEP] by (simp add: blinfun_scaleR_def)
% -------------------------------------- PREAMBLE STARTS HERE -------------------------------------------- % This is the preamble. It sets the main options for your document and load the packages used. % Load packages: making changes here can cause errors. \documentclass{article} % Define document class. Shouldn't change. \usepackage[a4paper]{geometry} % Calls and sets into A4 size mode \usepackage{graphicx} \usepackage{booktabs} \usepackage{tabularx} \usepackage{import} % This package allows us to import files. \usepackage{multirow} \usepackage{adjustbox} % This package allows you to adapt table and figure sizes to fit the page and is required by iebaltab \usepackage{geometry} \usepackage{subcaption} % This packages is used to create subfigures \usepackage{float} \usepackage{setspace} \doublespacing % Comment out (write % at the beginning of the line) to use single spacing \usepackage{indentfirst} % Indents the fist paragraph of each section \usepackage{parskip} % This packages sets the spacing between two paragraphs \usepackage{mathtools} \usepackage{hyperref} \title{ SFS Machine Learning Repo \\ Lasso and Ridge Explained Mathematically } \author{} \date{} % Uncomment this to not print date or insert specific date % -------------------------------------- PREAMBLE ENDS HERE -------------------------------------------- \begin{document} \maketitle \tableofcontents % Comment out to not print summary \newpage \section{Introduction} Yay! You opened this because you like math. In this document, we'll summarize the mathematical concepts needed to understand the basics of what's going on in Lasso and Ridge. Unless I cite things explicitly, assume the knowledge comes from my course with Prof. Ani Silwal in in Spring 2019. I also encourage you to refer to this book for a great theoretical explanation of just about anything: http://faculty.marshall.usc.edu/gareth-james/ISL/index.html. \newpage \section{OLS, conceptually revisited} Let's pretend we're students entering our fourth year at Hogwarts School for Witchcraft and Wizardry. We really need a new broomstick, so we plan a trip to Diagon Alley. We're eyeing the Firebolt model but, since we're not familiar with the muggle internet, we can only \textit{estimate} the true cost of the broomstick. Good thing we've taken Arithmancy with Professor Tiongson. He taught us that we can generalize the cost of any broomsticks, $y$, by creating a mathematical relationship between known variables, or $x$'s. But we don't know what the real $y$'s actually are, so we'll need an estimator called $\hat{y}$ that uses some information from our $x$'s to take a guess at the real $y$. Now there are of course many variables we may use to estimate the cost of a broomstick, such as $x_1$, the average cost of last year's top selling broomstick models, $x_2$, the yearly rate of inflation, and, knowing that pricing patterns often relate to the product release cycle, $x_3$, the number of days since the last major broomstick model release. We might also want to take into account the number of features the broomstick offers, the broomsticks' length, weight, the number of hours required for the broomstick's production, and whether or not Lucious Malfoy, being among the snobby and pure-blood supremacist families, plans to purchase a set for the Slytherin Quidditch Team. If it peeks Malfoy's interest, it's not likely to be priced for the common folk. See? The number of variables at our disposal quickly adds up. Good thing we paid attention in class! We learned that we can express $\hat{y}$ by using the "standard" linear equation model, which looks something like this $$\hat{y} = \beta_0 + \beta_{1}x_1 + \beta_{2}x_2 + \beta_{n}x_n + \varepsilon$$ where $\beta_0$ is our constant, $\beta_i$'s our coefficients, and $\varepsilon$ our error term. So when we \texttt{reg y x} in Stata, we're basically just telling the computer to fit the data to this equation the best it can. But How does Stata actually calculate all the components of the equation? It minimizes the sum of the squared error term, or minimizing $$(all\:distances \:from \:the \:'dots' \:on \:the \:scatterplot \:to \:the \:line \:running \:through \:them)^2$$ We can express this idea mathematically by adding up all of the differences between the actual broomstick costs and estimated costs like this $$\sum(y_i - \hat{y})^2 $$ Why do we square the difference between the estimated and actual measurements? Who knows. What it does, in essence, is disproportionately penalize the estimated measurements that are \textit{farther} away from the actual measurement compared to those that quite close. Since we know that $\hat{y}$ can be expressed as $\hat{y} = \beta_0 + \beta_{1}x_1 + \beta_{2}x_2 + \beta_{n}x_n + \varepsilon$, we can substitute this later equation into our $\sum$ equation (and distributing the negative to all terms in the expression): $$\sum(y_i - \beta_0 - \beta_{1}x_1 - \beta_{2}x_2 - \beta_{n}x_n )^2 $$ Remember, the goal is to minimize the value that results form this equation, which is the all of the error terms added up. Stata does this math in the background, spits out the coefficients that minimize the error value above, and we go on our merry way. If you ever want to know what math Stata is actually doing, it's usually buried out of sight in the command's \href{https://www.stata.com/manuals13/rregress.pdf}{help file}. \section{Lasso} Lasso adds a very slight modification to the OLS equation that makes it super meta. We'll get to this in a moment but first let's walk through what Lasso and Ridge algorithms are trying to do -- they're categorically different from OLS. OLS gives you coefficients for the only variables you give it; it does not tell you which variables to include or exclude in your model. You say, "great, I think $y_1$ the price of a broomstick relates to $x_1$, the average cost of broomsticks last year, and $x_2$, the number of features it has", you give those three variables to Stata as \texttt{reg price avcost nfeatures}, and Stata runs the equation above and gives you the value of coefficients to the input variables you gave it. Lasso (and Ridge) algorithms, on the other hand, tell you \textit{which} variables to include in your model (and, optionally, what the coefficients are on the variables the algorithm selects). This is a similar idea to stepwise functions. But unlike stepwise functions and OLS, the functions that Lasso and Ridge try to satisfy introduce a $\lambda$ variable. This lambda is an unknown constant that acts as a penalty applied to each additional coefficient -- or variable -- you include in the model. Some guy named \href{https://statweb.stanford.edu/~tibs/index.html}{Tibshirani} thought, in this age of computers, we should discourage people from just throwing in any variable they can think of and, instead, make sure we focus only on the few variables that matter the most for predictive power. His goal is to minimize $$ \frac{1}{n} \sum (y_i - x'_i \beta)^2 + \lambda \sum\ | \beta_j | $$ where the $\beta_j$'s are the coefficients for all the $x$'s and $\lambda$ is the penalty. Since we want to avoid high penalties, there are two ways we can do that: decrease $\lambda$ or decrease the number of included coefficients. One more thing. Notice what happens when $\lambda = 0$? $$\frac{1}{n} \sum (y_i - x'_i \beta)^2 + 0 \sum\ | \beta_j | $$ Right, the final term becomes 0. And this looks a lot like OLS...that's because it is OLS. $$\frac{1}{n} \sum (y_i - x'_i \beta)^2 + 0 $$ So, Lasso algorithms with $\lambda$ values $= 0$ is virtually the same equation as OLS. This makes sense, because in this 0-termed Lasso world we are still \textit{minimizing the sum of squared error terms} and there's no penalty for including additional coefficients as lambda is 0. \subsection{Lasso: an alternative visualization} We can also think of the lasso expression as solving the following equation. As James et al (2017) put it, Conceptually, for every value of $\lambda$, there must be some corresponding \textit{s} that will both minimize the sum of squared errors (the OLS, left-hand term), that also satisfies the sum of the betas (on the right). In essence, we must perform OLS while satisfying one extra condition. $$ minimize \; {\sum(y_i - \beta_0 - \Sigma\beta_{j}x_{ij} )^2} \; \; such \; that \; \; \Sigma|\beta_j| \: \leq \: s $$ What is \textit{s}? It's basically a constraint region that limits our ability to changes the values of the betas in order to reduce the Residual Sum of Squares. Notice that the sum of our betas must \textit{less than or equal to s}. Figure \ref{fig:f1} helps clarify things. \begin{figure} [H] \centering \caption{Solution of Lasso Equation, from Agor153 / CC BY-SA} \includegraphics[width=0.35\textwidth]{graphics/PQSQ2.png} \label{fig:f1} \end{figure} Here we simplified diagram where the "x" and "y" axes are represented by the value of two betas, $ \beta_1 $ and $ \beta_2 $. Instead of $ (x,y) $ our coordinate plane is thus represented by the set of values that represent $ (\beta_1, \beta_2 ) $. As such, a point somewhere on the "x" axis would indicate a $\beta_1 $ of value \textit{n} and no $\beta_2$ -- that term is dropped from our equation. Of course, in our models we often have many more explanatory variables than two -- so I think to think of the actual math happening in \textit{n}-dimensions where some betas have values and some are dropped altogether. The diamond-shape region near the origin is the constraint region determined by \textit{s}; our solution set must fall inside or on this region. The elliptical circles represent lines of constant error term: anywhere along the same indicates an array of betas that generate the same value for the Residual Sum of Squares. In traditional OLS, this region is not constrained by \textit{s}, or the diamond (James et al, 2017; p. 222). In both cases we want to move the "error" ellipses inward as much as possible to minimize the error term. But our solution set must lie on or inside the diamond, so the point at which we minimize the error term and simultaneously satisfy the constraint region is tangential to the constraint region. In lasso, we have a \emph{linear} constraint as indicated mathematically by our $ \Sigma|\beta_j| \: \leq \: s $ term -- or graphically by our diamond-shaped constraint region. Therefore, in lasso \textit{our solution set will almost always reside on an axis}. \section{Ridge} The general principles of Ridge are the same as Lasso: we determine which coefficients to include in the model by describing the combination coefficients as a function of error. The main difference is the final constraint term: in lasso the term is linear, while in ridge, it's squared: $$ minimize \; {\sum(y_i - \beta_0 - \Sigma\beta_{j}x_{ij} )^2} \; \; such \; that \; \; \Sigma(\beta_j)^2 \: \leq \: s $$ This small, one-term difference actually changes things drastically. Let's look at figure \ref{fig:f2}. \begin{figure} [H] \centering \caption{Solution of Lasso and Ridge Compared, adapted from Nicoguaro / CC BY (https://creativecommons.org/licenses/by/4.0)} \includegraphics[width=0.85\textwidth]{graphics/1600px-L1_and_L2_balls_edit} \label{fig:f2} \end{figure} Because of the \texit{squared} constraint term $\Sigma(\beta_{j})^2 \: \leq \: s $, the resulting region is spherical. This also means that our "error" ellipse (here represented by a line, oddly) will never intersect the constraint region on an axis. Thus, we will never drop any coefficients or covariates from the model because the OLS-derived error term will always be minimized at a $ (\beta_1, \beta_2 ) $ point where each beta as a non-zero value. \section{Thanks and Citations} James, Gareth; Witten, Daniela; Hastie, Trevor; Tibshirani, Robert. \textit{An Introduction to Statistical Learning with Applications in R}. New York: Springer, 2017. Silwal, Ani. Advanced Econometrics II. Georgetown University: Spring 2019. \end{document}
||| The Error monad (also called the Exception monad). module Control.Monad.Error.Interface import Control.Monad.Error.Either import Control.Monad.Maybe import Control.Monad.RWS.CPS import Control.Monad.Reader.Reader import Control.Monad.State.State import Control.Monad.Trans import Control.Monad.Writer.CPS %default total ||| The strategy of combining computations that can throw exceptions ||| by bypassing bound functions ||| from the point an exception is thrown to the point that it is handled. ||| Is parameterized over the type of error information and ||| the monad type constructor. ||| It is common to use `Either String` as the monad type constructor ||| for an error monad in which error descriptions take the form of strings. ||| In that case and many other common cases the resulting monad is already defined ||| as an instance of the 'MonadError' class. public export interface Monad m => MonadError e m | m where ||| Is used within a monadic computation to begin exception processing. throwError : e -> m a ||| A handler function to handle previous errors and return to normal execution. ||| A common idiom is: ||| ||| ```idris example ||| do { action1; action2; action3 } `catchError` handler ||| ``` catchError : m a -> (e -> m a) -> m a ||| Lifts an `Either e` into any `MonadError e`. public export liftEither : MonadError e m => Either e a -> m a liftEither = either throwError pure ||| Makes a success or failure of an action visible in ||| the return type. public export tryError : MonadError e m => m a -> m (Either e a) tryError action = (map Right action) `catchError` (pure . Left) ||| `MonadError` analogue to the `withEitherT` function. ||| Modify the value (but not the type) of an error. ||| If you need to change the type of `e` use `mapError`. public export withError : MonadError e m => (e -> e) -> m a -> m a withError f action = tryError action >>= either (throwError . f) pure ||| Flipped version of `catchError`. public export handleError : MonadError e m => (e -> m a) -> m a -> m a handleError = flip catchError ||| `MonadError` analogue of the `mapEitherT` function. The ||| computation is unwrapped, a function is applied to the `Either`, and ||| the result is lifted into the second `MonadError` instance. public export mapError : (MonadError e m, MonadError e' n) => (m (Either e a) -> n (Either e' b)) -> m a -> n b mapError f action = f (tryError action) >>= liftEither -------------------------------------------------------------------------------- -- Implementations -------------------------------------------------------------------------------- public export MonadError () Maybe where throwError () = Nothing catchError Nothing f = f () catchError x _ = x public export MonadError e (Either e) where throwError = Left Left l `catchError` h = h l Right r `catchError` _ = Right r public export Monad m => MonadError e (EitherT e m) where throwError = throwE catchError = catchE public export MonadError e m => MonadError e (MaybeT m) where throwError = lift . throwError catchError (MkMaybeT m) f = MkMaybeT (catchError m (runMaybeT . f)) public export MonadError e m => MonadError e (ReaderT r m) where throwError = lift . throwError catchError (MkReaderT m) f = MkReaderT $ \e => catchError (m e) (runReaderT e . f) public export MonadError e m => MonadError e (StateT r m) where throwError = lift . throwError catchError (ST m) f = ST $ \s => catchError (m s) (runStateT s . f) public export MonadError e m => MonadError e (RWST r w s m) where throwError = lift . throwError catchError (MkRWST m) f = MkRWST $ \r,w,s => catchError (m r w s) (\e => unRWST (f e) r w s) public export MonadError e m => MonadError e (WriterT w m) where throwError = lift . throwError catchError (MkWriterT m) f = MkWriterT $ \w => catchError (m w) (\e => unWriterT (f e) w)
// ARM7EJS CP15 Register Definition File // INCLUDE "arm926ejs.rd" // // <eof>
theory ntuples imports axioms_base begin text{* First we define ordered pairs, and then n-tuples, before we prove the fundamental property of the ordered pair. *} definition ordered_pair :: "Set \<Rightarrow> Set \<Rightarrow> Set" where "ordered_pair x y \<equiv> {{x}, {x,y}}" text{* Here we formalise n-tuples, as a subtype of Set. *} (* Taken from Product_Type.thy, lines 300-320*) nonterminal ntuple_args syntax "_ntuple" :: "ntuple_args \<Rightarrow> Set \<Rightarrow> Set" ("(1'\<langle>_,/ _'\<rangle>)") "_ntuple_arg" :: "Set \<Rightarrow> ntuple_args" ("_") "_ntuple_args" :: "ntuple_args \<Rightarrow> Set \<Rightarrow> ntuple_args" ("_,/ _") translations "\<langle>x, y\<rangle>" \<rightleftharpoons> "CONST ordered_pair x y" "_ntuple (_ntuple_args y z) x" \<rightleftharpoons> "_ntuple (_ntuple_arg (_ntuple y z)) x" (* "_abs (\<langle>x,y\<rangle>) t" \<rightharpoonup> "\<lambda>(x, y). t" *) (*not sure where it's useful*) value "\<langle>x,y,z,r,h\<rangle>" text{* The fundamental property of ordered pairs. *} lemma Prop4_3: "\<forall> x y u v :: Set. (\<langle>x,y\<rangle> = \<langle>u,v\<rangle>) \<longrightarrow> ((x=u) \<and> (y=v))" (* page 230 *) proof (rule allI, rule allI, rule allI, rule allI, rule impI) fix x y u v :: Set assume "\<langle>x,y\<rangle> = \<langle>u,v\<rangle>" -- "Assume (x,y) = (u,v)." then have 0: "{{x},{x,y}} = {{u},{u,v}}" -- "Then {{x},{x,y}} = {{u},{u,v}}." using ordered_pair_def by simp moreover have "{x} \<in> {{x}, {x,y}}" using pairing by auto -- " Since {x} E {{x}, {x,y}}," ultimately have "{x} \<in> {{u}, {u, v}}" -- "{x} E {{u}, {u, v}}." by auto moreover hence "{x} = {u} \<or> {x} = {u,v}" using pairing by (simp add: Rep_Set_inject) -- "Hence, {x} = {u} or {x} = {u,v}." moreover hence "x=u" by (metis Rep_Set_inject pairing) -- "In either case x=u." moreover have *: "{u,v} \<in> {{u},{u,v}}" using pairing by simp -- "Now, {u,v} E {{u},{u,v}};" moreover hence "{u,v} \<in> {{x},{x,y}}" using 0 by simp -- "so, {u,v} E {{x},{x,y}}." moreover then have 2:"{u,v} = {x} \<or> {u, v} = {x,y}" by (simp add: Rep_Set_inject pairing) -- "Then {u,v} = {x} or {u, v} = {x,y}." moreover have **: "{x,y} = {u} \<or> {x,y} = {u, v}" by (metis 0 Rep_Set_inverse pairing) -- "Similarly, {x,y} = {u} or {x,y} = {u, v}." moreover hence "y=v" (* Sledgehammer can find a proof from this poing already: by (metis Rep_Set_inverse calculation(3) calculation(6) pairing) *) proof (cases "{u,v} = {x} \<and> {x,y} = {u}") assume "{u,v} = {x} \<and> {x,y} = {u}" -- "If {u, v} = {x} and {x,y} = {u}," then have "x = y" by (metis Rep_Set_inverse pairing) moreover have "\<dots> = u" using \<open>x = u\<close> calculation by blast moreover have "\<dots> = v" by (metis Rep_Set_inverse \<open>{u, v} = {x} \<and> {x, y} = {u}\<close> pairing) -- " then x = y = u = v;" thus ?thesis by (metis Rep_Set_inject \<open>{u, v} = { x} \<and> {x, y} = { u}\<close> pairing) next assume *: "\<not>({u,v} = {x} \<and> {x,y} = {u})" -- " if not," then have "{u, v} = {x,y}" using calculation(6) calculation(7) by auto -- "{u, v} = {x,y}." hence "{u, v} = {u, y}" by (simp add: calculation(3)) --"Hence, {u, v} = {u, y}." show "y=v" proof (cases "v\<noteq>u") assume "v\<noteq>u" thus "y=v" by (metis Rep_Set_inverse \<open>{u, v} = {u, y}\<close> pairing) --"So, if v \<noteq> u, then y = v;" next assume "\<not>(v\<noteq>u)" then have "y=u" using * \<open>{u, v} = {x, y}\<close> calculation(3) by auto -- "if v = u, then y = v." thus "y=v" using \<open>\<not> v \<noteq> u\<close> by blast --"Thus, in all cases, y = v." qed qed ultimately show "x = u \<and> y = v" by simp qed text{* The following exercises show that it doesn't matter how we define ordered pairs, as long as their fundamental property holds. *} text{* \textbf{FOMUS workshop extra exercise:} *} lemma Ex4_8_a: fixes op :: "Class \<Rightarrow> Class \<Rightarrow> Class" ("(\<lceil>_ , _\<rceil>)") assumes "\<lceil>X,Y\<rceil> = { {\<emptyset>,X} , {{\<emptyset>,Y}} } " shows "\<forall> x y u v :: Set. (\<lceil>x,y\<rceil> = \<lceil>u,v\<rceil>) \<longrightarrow> ((x=u) \<and> (y=v))" oops text{* \textbf{FOMUS workshop extra exercise:} *} lemma Ex4_8_b: fixes op :: "Class \<Rightarrow> Class \<Rightarrow> Class" ("(\<lceil>_ , _\<rceil>)") assumes "\<lceil>X,Y\<rceil> = { {\<emptyset>,{X}} , {{Y}} } " shows "\<forall> x y u v :: Set. (\<lceil>x,y\<rceil> = \<lceil>u,v\<rceil>) \<longrightarrow> ((x=u) \<and> (y=v))" oops (* The following contains ToTuple and the relevant lemmas from FOL_Formula. TO-DO: define the notation "\<langle>x_1,\<dots>,x_n\<rangle>" *) text {* Sometimes we need to use metafunctions of type nat \<Rightarrow> Set to describe tuples. \texttt{ToTuple} takes an interpretation \tt{i::nat$\Rightarrow$Set} and an Isabelle-natural number \tt{n::nat} and returns the tuple \tt{$\langle i(0), \dots, i(n)\rangle$} In this way we can refer to arbitrary n-tuples. *} primrec ToTuple :: "[nat \<Rightarrow> Set, nat] \<Rightarrow> Set" where "ToTuple i 0 = i(0)" | "ToTuple i (Suc n) = \<langle>ToTuple i n, i(Suc n)\<rangle>" -- "We sometimes call (ToTuple i n) the (n+1)-tuple coming from i." notation ToTuple ("(\<langle>\<dots>,(1_)((2_))\<rangle>)") (* For now, I don't know how to refer to an argument twice in a notation. It should be: \<langle> (1_)(0),...,(1_)((2_))\<rangle>. *) abbreviation ToTuple_add1 :: "(nat\<Rightarrow>Set) \<Rightarrow> nat \<Rightarrow> Set \<Rightarrow> Set" ("(\<langle>\<dots>, _ (_), _\<rangle>)") where "\<langle>\<dots>,i(n),x\<rangle> \<equiv> \<langle> \<langle>\<dots>,i(n)\<rangle>,x\<rangle>" abbreviation ToTuple_add2 :: "(nat\<Rightarrow>Set) \<Rightarrow> nat \<Rightarrow> Set \<Rightarrow> Set \<Rightarrow> Set" ("(\<langle>\<dots>,_ (_), _, _\<rangle>)") where "\<langle>\<dots>,i(n),x,y\<rangle> \<equiv> \<langle> \<langle>\<dots>,i(n)\<rangle>,x,y\<rangle>" text {* Some basic lemmas about n-tuples. *} lemma Tuple_Eq: "\<langle>\<dots>,i(n)\<rangle> = \<langle>\<dots>,j(n)\<rangle> \<Longrightarrow> \<forall>k \<le> n. i(k) = j(k)" -- "Equal n-tuples from different interpretations imply that the interpretations are the same below n." proof (induct n, simp_all) fix n::nat assume IH: "(\<langle>\<dots>,i(n)\<rangle> = \<langle>\<dots>,j(n)\<rangle> \<Longrightarrow> \<forall>k\<le>n. i(k) = j(k))" and assm: "\<langle>\<dots>,i(n), i(Suc n)\<rangle> = \<langle>\<dots>, j(n), j(Suc n)\<rangle>" thus "\<forall>k\<le>Suc n. i k = j k" using Prop4_3 le_Suc_eq by blast qed lemma Tuple_Dom: "\<lbrakk>\<And>k. k \<le> n \<Longrightarrow> x(k) = y(k)\<rbrakk> \<Longrightarrow> \<langle>\<dots>,x(n)\<rangle> = \<langle>\<dots>,y(n)\<rangle>" -- "If two interpretations are the same below n, then they produce the same n-tuples." by (induct n, simp_all) lemma Tuple_All1: "(\<forall>v. \<forall>i. \<phi>( \<langle>\<dots>, i(n), v\<rangle> )) \<Longrightarrow> (\<forall>i. \<phi>( \<langle>\<dots>,i(Suc n)\<rangle> ))" -- "If \<phi> holds for every (n+2) tuple, whose first (n+1) elements may come from any i, then \<phi> holds for the (n+2) tuple coming from any i." by simp lemma Tuple_All2: "(\<forall>i. \<phi>( \<langle>\<dots>, i(Suc n)\<rangle> )) \<Longrightarrow> (\<forall>v. \<forall>i. \<phi>(\<langle>\<dots>,i(n), v\<rangle>))" -- "The reverse of Tuple_All1." proof fix v assume A1: "\<forall>i. \<phi>( \<langle>\<dots>, i(Suc n)\<rangle> )" show "\<forall>i. \<phi>(\<langle>\<dots>,i(n), v\<rangle>)" proof fix i :: "nat \<Rightarrow> Set" have "ToTuple (\<lambda>k. if k = (Suc n) then v else i(k)) (Suc n) = \<langle>ToTuple (\<lambda>k. if k = (Suc n) then v else i(k)) n, v\<rangle>" by simp also have "\<dots> = \<langle>\<dots>,i(n), v\<rangle>" using Tuple_Dom [of n i "\<lambda>k. if k = (Suc n) then v else i(k)"] by simp finally show "\<phi>(\<langle>\<dots>, i(n), v\<rangle>)" using A1 by metis qed qed lemma Tuple_All: "(\<forall>i::nat\<Rightarrow>Set. \<phi>( \<langle>\<dots>, i(Suc n)\<rangle>)) \<longleftrightarrow> (\<forall>v::Set. \<forall>i::nat\<Rightarrow>Set. \<phi>(\<langle>\<dots>, i(n), v\<rangle>))" using Tuple_All1 Tuple_All2 by auto end
! { dg-do run } ! Tests the fix for PR33897, in which gfortran missed that the ! declaration of 'setbd' in 'nxtstg2' made it external. Also ! the ENTRY 'setbd' would conflict with the external 'setbd'. ! ! Contributed by Michael Richmond <[email protected]> ! MODULE ksbin1_aux_mod CONTAINS SUBROUTINE nxtstg1() INTEGER :: i i = setbd() ! available by host association. if (setbd () .ne. 99 ) call abort () END SUBROUTINE nxtstg1 SUBROUTINE nxtstg2() INTEGER :: i integer :: setbd ! makes it external. i = setbd() ! this is the PR if (setbd () .ne. 42 ) call abort () END SUBROUTINE nxtstg2 FUNCTION binden() INTEGER :: binden INTEGER :: setbd binden = 0 ENTRY setbd() setbd = 99 END FUNCTION binden END MODULE ksbin1_aux_mod PROGRAM test USE ksbin1_aux_mod, only : nxtstg1, nxtstg2 integer setbd ! setbd is external, since not use assoc. CALL nxtstg1() CALL nxtstg2() if (setbd () .ne. 42 ) call abort () call foo contains subroutine foo USE ksbin1_aux_mod ! module setbd is available if (setbd () .ne. 99 ) call abort () end subroutine END PROGRAM test INTEGER FUNCTION setbd() setbd=42 END FUNCTION setbd ! { dg-final { cleanup-modules "ksbin1_aux_mod" } }
[STATEMENT] lemma CJ_9a: "\<lfloor>\<^bold>\<diamond>\<^sub>p\<^bold>O\<langle>B|A\<rangle> \<^bold>\<rightarrow> \<^bold>\<box>\<^sub>p\<^bold>O\<langle>B|A\<rangle>\<rfloor>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>c. (\<lambda>w. \<I>(\<lambda>v. pv w v \<and> ob (A c) (B c))) \<sqsubseteq> (\<lambda>w. pv w \<sqsubseteq> (\<^bold>O\<langle>B|A\<rangle>) c) [PROOF STEP] by simp
#= test_timeevolution: - Julia version: 1.5.2 - Author: qcancam - Date: 2021-01-03 =# include("../src/MatrixProductStates.jl") using .MatrixProductStates, SparseArrays, Arpack, PyCall, PyPlot #np=pyimport("numpy") #@pyimport matplotlib.pyplot as plt g = 1.0; L = 5 T=8.0 N=1000.0 τ = T/N function H_TFIM(g, L) H = Array{Complex{Float64}, 2}[] id = [1 0; 0 1] σˣ = [0 1; 1 0] σᶻ = [1 0; 0 -1] for i in 1:L-2 push!(H,-σᶻ⊗σᶻ-g*σˣ⊗ id) end #=L-1=# push!(H,-σᶻ⊗σᶻ-g*(σˣ⊗ id+ id⊗ σˣ)) return H end function H_TFIM_MPO(g, L) id = [1 0; 0 1] σˣ = [0 1; 1 0] σᶻ = [1 0; 0 -1] W_tnsr = zeros(Complex{Float64}, 3, 3, 2, 2) W_tnsr[1, 1, :, :] = id W_tnsr[2, 1, :, :] = -σᶻ*0 W_tnsr[3, 1, :, :] = -σˣ W_tnsr[3, 2, :, :] = σᶻ*0 W_tnsr[3, 3, :, :] = id return MPO(W_tnsr, L) end H = H_TFIM(g, L) ψ = randn(MPS{L, Complex{Float64}}, 100, 2) ϕ,time_list,expect_list= real_time_evolution(ψ, H[1],H[2],H[L-1],H_TFIM_MPO(g,L), T,N,50) #ϕ= real_time_evolution(ψ, H[1],H[2],H[L-1],H_TFIM_MPO(g,L), T,N,50) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(time_list, expect_list, "-", c="b", ms=10) ax.set_xlabel("t") ax.set_ylabel("⟨-∑σˣ(t)⟩") #ax.set_title("2D Line Plot Sample") #ax.grid(true) plt.show()
import tactic.basic import tactic.interactive import .formula /-- A formula is satisfied by an assignment if it evaluates to true. -/ @[simp] def satisfies (asgn : symbol → Prop) (modal_asgn : formula → Prop) : formula → Prop | ⊤ := true | ⊥ := false | (formula.symbol s) := asgn s | ¬a := ¬satisfies a | (a ∧ b) := satisfies a ∧ satisfies b | (a ∨ b) := satisfies a ∨ satisfies b | (a ⟶ b) := satisfies a → satisfies b | (a ↔ b) := satisfies a ↔ satisfies b | □a := modal_asgn □a | ◇a := modal_asgn ◇a /-- A tautology is a formula that is always true. -/ def tautology (a : formula) := ∀v m, satisfies v m a /-- A model is a collection of worlds with a relation and an interpretation function that determines at which worlds sentence symbols are true. -/ structure model := {world : Type} (w : set world) (r : world → world → Prop) (v : symbol → set world) /-- Definition of truth at a world in a model. -/ @[simp] def truth (m : model) : m.world → formula → Prop | _ ⊥ := false | _ ⊤ := true | w (formula.symbol s) := w ∈ (m.v s) | w ¬a := ¬truth w a | w (a ∧ b) := truth w a ∧ truth w b | w (a ∨ b) := truth w a ∨ truth w b | w (a ⟶ b) := truth w a → truth w b | w (a ↔ b) := truth w a ↔ truth w b | w □a := ∀w' ∈ m.w, m.r w w' → truth w' a | w ◇a := ∃w' ∈ m.w, m.r w w' ∧ truth w' a notation ⟨m, w⟩ ` ⊩ ` a := truth m w a /-- A formula is true in a model iff it is true in all worlds in the model. -/ @[simp] def true_in (m : model) (a : formula) := ∀w ∈ m.w, ⟨m, w⟩ ⊩ a reserve infix ` ⊩ ` :15 notation m ⊩ a := true_in m a /-- A formula is true in a set of models iff it is true in all models in the set. -/ @[simp] def valid (𝒞 : set model) (a : formula) := ∀m ∈ 𝒞, m ⊩ a reserve prefix `⊨ ` :15 reserve infix ` ⊨ ` :15 notation 𝒞 ⊨ a := valid 𝒞 a notation ⊨ a := set.univ ⊨ a @[simp] lemma valid_imp_valid_in (a : formula) {ha : ⊨ a} {𝒞 : set model} : 𝒞 ⊨ a := begin intros m _, apply ha, tautology, end @[simp] def k (a b : formula) := □(a ⟶ b) ⟶ (□a ⟶ □b) theorem k.valid : ∀(a b : formula), ⊨ k a b := begin intros a b, intros m _ w hw, intros h₁ h₂, intros w' _ hr, apply h₁, assumption', apply h₂, assumption', end @[simp] def dual (a : formula) := ◇a ↔ ¬□¬a theorem dual.valid : ∀a : formula, ⊨ dual a := begin intro a, intros m _ w hw, apply iff.intro, { intro h₁, intro h₂, simp at *, apply exists.elim h₁, intros w' hw', cases hw', cases hw'_right, apply h₂ w', assumption', }, { intro h₁, simp at *, assumption, } end lemma foo (a : formula) (m : model) (w ∈ m.w) (v : symbol → Prop) (hv : ∀s, v s ↔ ⟨m, w⟩ ⊩ formula.symbol s) (mv : formula → Prop) (hmv : ∀a, mv a ↔ ⟨m, w⟩ ⊩ a) : satisfies v mv a ↔ ⟨m, w⟩ ⊩ a := begin induction a, repeat { simp * at *, }, end /-- All tautologies are valid. -/ theorem tautology.valid (a : formula) : tautology a → ⊨ a := begin contrapose, intros h₁ h₂, simp at h₁, apply exists.elim h₁, intros m hm, cases hm with w hw, cases hw, apply hw_right, have h := foo a m w hw_left (λs, ⟨m, w⟩ ⊩ formula.symbol s) (by simp) (λa, ⟨m, w⟩ ⊩ a) (by simp), simp [←h], apply h₂, end theorem mp (a b : formula) (m : model) (w ∈ m.w) : (⟨m, w⟩ ⊩ a ⟶ b) → (⟨m, w⟩ ⊩ a) → (⟨m, w⟩ ⊩ b) := begin intros hab ha, apply hab, assumption, end theorem mp_valid {𝒞 : set model} (a b : formula) : (𝒞 ⊨ a ⟶ b) → (𝒞 ⊨ a) → (𝒞 ⊨ b) := begin intros hab ha m _ w _, apply mp, assumption', apply hab, assumption', apply ha, assumption', end theorem nec_valid {𝒞 : set model} (a : formula) : (𝒞 ⊨ a) → (𝒞 ⊨ □a) := begin intro ha, intros m _ w _, intros w' _ hww', apply ha, assumption', end
using Documenter, Neurthino makedocs(; modules = [Neurthino], authors = "Johannes Schumann, Tamas Gal", format = Documenter.HTML( prettyurls = get(ENV, "CI", nothing) == "true", assets = ["assets/logo.ico"], ), pages=[ "Introduction" => "index.md", "API" => "api.md", ], repo="https://github.com/KM3NeT/Neurthino.jl/blob/{commit}{path}#L{line}", sitename="Neurthino.jl", ) deploydocs(; repo="github.com/KM3NeT/Neurthino.jl", )
#ifndef MSNHINFERENCECFG_H #define MSNHINFERENCECFG_H #include <stdint.h> #include <float.h> #include <string> #include <vector> #include <chrono> #include "Msnhnet/utils/MsnhException.h" #include "Msnhnet/config/MsnhnetMacro.h" #include <math.h> #include <string.h> #ifdef USE_OMP #include <omp.h> #endif #ifdef USE_NEON #include <arm_neon.h> #endif #ifdef USE_OPEN_BLAS #include <cblas.h> #endif #ifdef USE_OPENGL #include <Msnhnet/config/MsnhnetOpenGL.h> #endif #ifndef OMP_THREAD #define OMP_THREAD omp_get_max_threads() #endif #define CUDA_THREADS 512 #define MIN_OMP_DATA 10000 #define MSNHNET_VERSION 1200 #define EFFCIENT_ALIGN 16 enum ActivationType { LOGISTIC, RELU, RELU6, RELIE, RAMP, TANH, PRELU, PLSE, LEAKY, ELU, LOGGY, STAIR, HARDTAN, LHTAN, SOFT_PLUS, SELU, SWISH, HARD_SWISH, MISH, NORM_CHAN, NORM_CHAN_SOFTMAX, NORM_CHAN_SOFTMAX_MAXVAL, NONE }; enum LayerType { CONVOLUTIONAL, DECONVOLUTIONAL, CONNECTED, MAXPOOL, LOCAL_AVGPOOL, GLOBAL_AVGPOOL, SOFTMAX, CROP, ROUTE, VARIABLE_OP, NORMALIZATION, AVGPOOL, ACTIVE, BATCHNORM, NETWORK, YOLO, YOLO_OUT, GAUSSIAN_YOLO, UPSAMPLE, L2NORM, EMPTY, VIEW, PERMUTE, PIXEL_SHUFFLE, SLICE, REDUCTION, CONFIG, RES_BLOCK, RES_2_BLOCK, CONCAT_BLOCK, ADD_BLOCK, PADDING }; enum Arithmetic { ARITH_ADD = 0, ARITH_SUB, ARITH_SUB_INV, ARITH_MUL, ARITH_DIV, ARITH_DIV_INV }; enum Scientific { SCI_ABS=0, SCI_ACOS, SCI_ASIN, SCI_ATAN, SCI_COS, SCI_COSH, SCI_SIN, SCI_SINH, SCI_TAN, SCI_TANH, SCI_EXP, SCI_POW, SCI_LOG, SCI_LOG10, SCI_SQRT }; enum ReductionType { REDUCTION_SUM, REDUCTION_MEAN }; enum WeightsType { NO_WEIGHTS, PER_FEATURE, PER_CHANNEL }; enum WeightsNorm { NO_NORM, RELU_NORM, SOFTMAX_NORM }; #endif
[STATEMENT] lemma wp3char[rule_format]: "none_MT_rules C xs \<and> C (AllowPortFromTo a b po)=\<emptyset> \<and> wellformed_policy3(xs@[DenyAllFromTo a b]) \<longrightarrow> AllowPortFromTo a b po \<notin> set xs" [PROOF STATE] proof (prove) goal (1 subgoal): 1. none_MT_rules C xs \<and> C (AllowPortFromTo a b po) = \<emptyset> \<and> wellformed_policy3 (xs @ [DenyAllFromTo a b]) \<longrightarrow> AllowPortFromTo a b po \<notin> set xs [PROOF STEP] apply (induct xs,simp_all) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>aa xs. none_MT_rules C xs \<and> C (AllowPortFromTo a b po) = \<emptyset> \<and> wellformed_policy3 (xs @ [DenyAllFromTo a b]) \<longrightarrow> AllowPortFromTo a b po \<notin> set xs \<Longrightarrow> dom (C aa) \<noteq> {} \<and> none_MT_rules C xs \<and> C (AllowPortFromTo a b po) = \<emptyset> \<and> wellformed_policy3 (aa # xs @ [DenyAllFromTo a b]) \<longrightarrow> AllowPortFromTo a b po \<noteq> aa \<and> AllowPortFromTo a b po \<notin> set xs [PROOF STEP] by (metis domNMT wp3Conc)
%% FUNCTION nchoose % How many unique combinations of 1 to N elements are there. This % function is not intended to directly called by users. % See the Logistic_iMSF function. % %% LICENSE % This program 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. % % This program 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 program. If not, see <http://www.gnu.org/licenses/>. % % Copyright (C) 2011 - 2012 Lei Yuan, Jiayu Zhou, and Jieping Ye % % You are suggested to first read the Manual. % For any problem, please contact with Jiayu Zhou via [email protected] % % Last modified on June 12, 2012. % %% RELATED FUNCTIONS % init_opts, Construct_iMSF, Logistic_iMSF, MultiSource_LogisticR function W = nchoose(S) N = numel(S) ; % How many unique combinations of 1 to N elements are there M = (2^N)-1 ; if N > 18, warning('Nchoose:LargeOutput', ... 'There are %d unique combinations. Please be patient ...',M) ; end S = S(:).' ; % make the set a row vector, for uniform output W = cell(M,1) ; % Pre-allocation of output p2=2.^(N-1:-1:0) ; % This part of the formula can be taken out of the loop for i=1:M, % calculate the (reversed) binary representation of i % select the elements of the set based on this representation W{i} = S(bitget(i*p2,N) > 0) ; end
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Floris van Doorn -/ import geometry.manifold.vector_bundle.tangent /-! # The derivative of functions between smooth manifolds Let `M` and `M'` be two smooth manifolds with corners over a field `𝕜` (with respective models with corners `I` on `(E, H)` and `I'` on `(E', H')`), and let `f : M → M'`. We define the derivative of the function at a point, within a set or along the whole space, mimicking the API for (Fréchet) derivatives. It is denoted by `mfderiv I I' f x`, where "m" stands for "manifold" and "f" for "Fréchet" (as in the usual derivative `fderiv 𝕜 f x`). ## Main definitions * `unique_mdiff_on I s` : predicate saying that, at each point of the set `s`, a function can have at most one derivative. This technical condition is important when we define `mfderiv_within` below, as otherwise there is an arbitrary choice in the derivative, and many properties will fail (for instance the chain rule). This is analogous to `unique_diff_on 𝕜 s` in a vector space. Let `f` be a map between smooth manifolds. The following definitions follow the `fderiv` API. * `mfderiv I I' f x` : the derivative of `f` at `x`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. If the map is not differentiable, this is `0`. * `mfderiv_within I I' f s x` : the derivative of `f` at `x` within `s`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. If the map is not differentiable within `s`, this is `0`. * `mdifferentiable_at I I' f x` : Prop expressing whether `f` is differentiable at `x`. * `mdifferentiable_within_at 𝕜 f s x` : Prop expressing whether `f` is differentiable within `s` at `x`. * `has_mfderiv_at I I' f s x f'` : Prop expressing whether `f` has `f'` as a derivative at `x`. * `has_mfderiv_within_at I I' f s x f'` : Prop expressing whether `f` has `f'` as a derivative within `s` at `x`. * `mdifferentiable_on I I' f s` : Prop expressing that `f` is differentiable on the set `s`. * `mdifferentiable I I' f` : Prop expressing that `f` is differentiable everywhere. * `tangent_map I I' f` : the derivative of `f`, as a map from the tangent bundle of `M` to the tangent bundle of `M'`. We also establish results on the differential of the identity, constant functions, charts, extended charts. For functions between vector spaces, we show that the usual notions and the manifold notions coincide. ## Implementation notes The tangent bundle is constructed using the machinery of topological fiber bundles, for which one can define bundled morphisms and construct canonically maps from the total space of one bundle to the total space of another one. One could use this mechanism to construct directly the derivative of a smooth map. However, we want to define the derivative of any map (and let it be zero if the map is not differentiable) to avoid proof arguments everywhere. This means we have to go back to the details of the definition of the total space of a fiber bundle constructed from core, to cook up a suitable definition of the derivative. It is the following: at each point, we have a preferred chart (used to identify the fiber above the point with the model vector space in fiber bundles). Then one should read the function using these preferred charts at `x` and `f x`, and take the derivative of `f` in these charts. Due to the fact that we are working in a model with corners, with an additional embedding `I` of the model space `H` in the model vector space `E`, the charts taking values in `E` are not the original charts of the manifold, but those ones composed with `I`, called extended charts. We define `written_in_ext_chart I I' x f` for the function `f` written in the preferred extended charts. Then the manifold derivative of `f`, at `x`, is just the usual derivative of `written_in_ext_chart I I' x f`, at the point `(ext_chart_at I x) x`. There is a subtelty with respect to continuity: if the function is not continuous, then the image of a small open set around `x` will not be contained in the source of the preferred chart around `f x`, which means that when reading `f` in the chart one is losing some information. To avoid this, we include continuity in the definition of differentiablity (which is reasonable since with any definition, differentiability implies continuity). *Warning*: the derivative (even within a subset) is a linear map on the whole tangent space. Suppose that one is given a smooth submanifold `N`, and a function which is smooth on `N` (i.e., its restriction to the subtype `N` is smooth). Then, in the whole manifold `M`, the property `mdifferentiable_on I I' f N` holds. However, `mfderiv_within I I' f N` is not uniquely defined (what values would one choose for vectors that are transverse to `N`?), which can create issues down the road. The problem here is that knowing the value of `f` along `N` does not determine the differential of `f` in all directions. This is in contrast to the case where `N` would be an open subset, or a submanifold with boundary of maximal dimension, where this issue does not appear. The predicate `unique_mdiff_on I N` indicates that the derivative along `N` is unique if it exists, and is an assumption in most statements requiring a form of uniqueness. On a vector space, the manifold derivative and the usual derivative are equal. This means in particular that they live on the same space, i.e., the tangent space is defeq to the original vector space. To get this property is a motivation for our definition of the tangent space as a single copy of the vector space, instead of more usual definitions such as the space of derivations, or the space of equivalence classes of smooth curves in the manifold. ## Tags Derivative, manifold -/ noncomputable theory open_locale classical topology manifold bundle open set universe u section derivatives_definitions /-! ### Derivative of maps between manifolds The derivative of a smooth map `f` between smooth manifold `M` and `M'` at `x` is a bounded linear map from the tangent space to `M` at `x`, to the tangent space to `M'` at `f x`. Since we defined the tangent space using one specific chart, the formula for the derivative is written in terms of this specific chart. We use the names `mdifferentiable` and `mfderiv`, where the prefix letter `m` means "manifold". -/ variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] {E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H') {M' : Type*} [topological_space M'] [charted_space H' M'] /-- Property in the model space of a model with corners of being differentiable within at set at a point, when read in the model vector space. This property will be lifted to manifolds to define differentiable functions between manifolds. -/ def differentiable_within_at_prop (f : H → H') (s : set H) (x : H) : Prop := differentiable_within_at 𝕜 (I' ∘ f ∘ (I.symm)) (⇑(I.symm) ⁻¹' s ∩ set.range I) (I x) /-- Being differentiable in the model space is a local property, invariant under smooth maps. Therefore, it will lift nicely to manifolds. -/ lemma differentiable_within_at_local_invariant_prop : (cont_diff_groupoid ⊤ I).local_invariant_prop (cont_diff_groupoid ⊤ I') (differentiable_within_at_prop I I') := { is_local := begin assume s x u f u_open xu, have : I.symm ⁻¹' (s ∩ u) ∩ set.range I = (I.symm ⁻¹' s ∩ set.range I) ∩ I.symm ⁻¹' u, by simp only [set.inter_right_comm, set.preimage_inter], rw [differentiable_within_at_prop, differentiable_within_at_prop, this], symmetry, apply differentiable_within_at_inter, have : u ∈ 𝓝 (I.symm (I x)), by { rw [model_with_corners.left_inv], exact is_open.mem_nhds u_open xu }, apply continuous_at.preimage_mem_nhds I.continuous_symm.continuous_at this, end, right_invariance' := begin assume s x f e he hx h, rw differentiable_within_at_prop at h ⊢, have : I x = (I ∘ e.symm ∘ I.symm) (I (e x)), by simp only [hx] with mfld_simps, rw this at h, have : I (e x) ∈ (I.symm) ⁻¹' e.target ∩ set.range I, by simp only [hx] with mfld_simps, have := ((mem_groupoid_of_pregroupoid.2 he).2.cont_diff_within_at this), convert (h.comp' _ (this.differentiable_within_at le_top)).mono_of_mem _ using 1, { ext y, simp only with mfld_simps }, refine mem_nhds_within.mpr ⟨I.symm ⁻¹' e.target, e.open_target.preimage I.continuous_symm, by simp_rw [set.mem_preimage, I.left_inv, e.maps_to hx], _⟩, mfld_set_tac end, congr_of_forall := begin assume s x f g h hx hf, apply hf.congr, { assume y hy, simp only with mfld_simps at hy, simp only [h, hy] with mfld_simps }, { simp only [hx] with mfld_simps } end, left_invariance' := begin assume s x f e' he' hs hx h, rw differentiable_within_at_prop at h ⊢, have A : (I' ∘ f ∘ I.symm) (I x) ∈ (I'.symm ⁻¹' e'.source ∩ set.range I'), by simp only [hx] with mfld_simps, have := ((mem_groupoid_of_pregroupoid.2 he').1.cont_diff_within_at A), convert (this.differentiable_within_at le_top).comp _ h _, { ext y, simp only with mfld_simps }, { assume y hy, simp only with mfld_simps at hy, simpa only [hy] with mfld_simps using hs hy.1 } end } /-- Predicate ensuring that, at a point and within a set, a function can have at most one derivative. This is expressed using the preferred chart at the considered point. -/ def unique_mdiff_within_at (s : set M) (x : M) := unique_diff_within_at 𝕜 ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) /-- Predicate ensuring that, at all points of a set, a function can have at most one derivative. -/ def unique_mdiff_on (s : set M) := ∀x∈s, unique_mdiff_within_at I s x /-- `mdifferentiable_within_at I I' f s x` indicates that the function `f` between manifolds has a derivative at the point `x` within the set `s`. This is a generalization of `differentiable_within_at` to manifolds. We require continuity in the definition, as otherwise points close to `x` in `s` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def mdifferentiable_within_at (f : M → M') (s : set M) (x : M) := continuous_within_at f s x ∧ differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) lemma mdifferentiable_within_at_iff_lift_prop_within_at (f : M → M') (s : set M) (x : M) : mdifferentiable_within_at I I' f s x ↔ lift_prop_within_at (differentiable_within_at_prop I I') f s x := by refl /-- `mdifferentiable_at I I' f x` indicates that the function `f` between manifolds has a derivative at the point `x`. This is a generalization of `differentiable_at` to manifolds. We require continuity in the definition, as otherwise points close to `x` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def mdifferentiable_at (f : M → M') (x : M) := continuous_at f x ∧ differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f) (range I) ((ext_chart_at I x) x) lemma mdifferentiable_at_iff_lift_prop_at (f : M → M') (x : M) : mdifferentiable_at I I' f x ↔ lift_prop_at (differentiable_within_at_prop I I') f x := begin congrm _ ∧ _, { rw continuous_within_at_univ }, { simp [differentiable_within_at_prop, set.univ_inter] } end /-- `mdifferentiable_on I I' f s` indicates that the function `f` between manifolds has a derivative within `s` at all points of `s`. This is a generalization of `differentiable_on` to manifolds. -/ def mdifferentiable_on (f : M → M') (s : set M) := ∀x ∈ s, mdifferentiable_within_at I I' f s x /-- `mdifferentiable I I' f` indicates that the function `f` between manifolds has a derivative everywhere. This is a generalization of `differentiable` to manifolds. -/ def mdifferentiable (f : M → M') := ∀x, mdifferentiable_at I I' f x /-- Prop registering if a local homeomorphism is a local diffeomorphism on its source -/ def local_homeomorph.mdifferentiable (f : local_homeomorph M M') := (mdifferentiable_on I I' f f.source) ∧ (mdifferentiable_on I' I f.symm f.target) variables [smooth_manifold_with_corners I M] [smooth_manifold_with_corners I' M'] /-- `has_mfderiv_within_at I I' f s x f'` indicates that the function `f` between manifolds has, at the point `x` and within the set `s`, the derivative `f'`. Here, `f'` is a continuous linear map from the tangent space at `x` to the tangent space at `f x`. This is a generalization of `has_fderiv_within_at` to manifolds (as indicated by the prefix `m`). The order of arguments is changed as the type of the derivative `f'` depends on the choice of `x`. We require continuity in the definition, as otherwise points close to `x` in `s` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def has_mfderiv_within_at (f : M → M') (s : set M) (x : M) (f' : tangent_space I x →L[𝕜] tangent_space I' (f x)) := continuous_within_at f s x ∧ has_fderiv_within_at (written_in_ext_chart_at I I' x f : E → E') f' ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) /-- `has_mfderiv_at I I' f x f'` indicates that the function `f` between manifolds has, at the point `x`, the derivative `f'`. Here, `f'` is a continuous linear map from the tangent space at `x` to the tangent space at `f x`. We require continuity in the definition, as otherwise points close to `x` `s` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def has_mfderiv_at (f : M → M') (x : M) (f' : tangent_space I x →L[𝕜] tangent_space I' (f x)) := continuous_at f x ∧ has_fderiv_within_at (written_in_ext_chart_at I I' x f : E → E') f' (range I) ((ext_chart_at I x) x) /-- Let `f` be a function between two smooth manifolds. Then `mfderiv_within I I' f s x` is the derivative of `f` at `x` within `s`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. -/ def mfderiv_within (f : M → M') (s : set M) (x : M) : tangent_space I x →L[𝕜] tangent_space I' (f x) := if mdifferentiable_within_at I I' f s x then (fderiv_within 𝕜 (written_in_ext_chart_at I I' x f) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) : _) else 0 /-- Let `f` be a function between two smooth manifolds. Then `mfderiv I I' f x` is the derivative of `f` at `x`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. -/ def mfderiv (f : M → M') (x : M) : tangent_space I x →L[𝕜] tangent_space I' (f x) := if mdifferentiable_at I I' f x then (fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : E → E') (range I) ((ext_chart_at I x) x) : _) else 0 /-- The derivative within a set, as a map between the tangent bundles -/ def tangent_map_within (f : M → M') (s : set M) : tangent_bundle I M → tangent_bundle I' M' := λp, ⟨f p.1, (mfderiv_within I I' f s p.1 : tangent_space I p.1 → tangent_space I' (f p.1)) p.2⟩ /-- The derivative, as a map between the tangent bundles -/ def tangent_map (f : M → M') : tangent_bundle I M → tangent_bundle I' M' := λp, ⟨f p.1, (mfderiv I I' f p.1 : tangent_space I p.1 → tangent_space I' (f p.1)) p.2⟩ end derivatives_definitions section derivatives_properties /-! ### Unique differentiability sets in manifolds -/ variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] -- {E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] {E'' : Type*} [normed_add_comm_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] {f f₀ f₁ : M → M'} {x : M} {s t : set M} {g : M' → M''} {u : set M'} lemma unique_mdiff_within_at_univ : unique_mdiff_within_at I univ x := begin unfold unique_mdiff_within_at, simp only [preimage_univ, univ_inter], exact I.unique_diff _ (mem_range_self _) end variable {I} lemma unique_mdiff_within_at_iff {s : set M} {x : M} : unique_mdiff_within_at I s x ↔ unique_diff_within_at 𝕜 ((ext_chart_at I x).symm ⁻¹' s ∩ (ext_chart_at I x).target) ((ext_chart_at I x) x) := begin apply unique_diff_within_at_congr, rw [nhds_within_inter, nhds_within_inter, nhds_within_ext_chart_at_target_eq] end lemma unique_mdiff_within_at.mono (h : unique_mdiff_within_at I s x) (st : s ⊆ t) : unique_mdiff_within_at I t x := unique_diff_within_at.mono h $ inter_subset_inter (preimage_mono st) (subset.refl _) lemma unique_mdiff_within_at.inter' (hs : unique_mdiff_within_at I s x) (ht : t ∈ 𝓝[s] x) : unique_mdiff_within_at I (s ∩ t) x := begin rw [unique_mdiff_within_at, ext_chart_at_preimage_inter_eq], exact unique_diff_within_at.inter' hs (ext_chart_at_preimage_mem_nhds_within I x ht) end lemma unique_mdiff_within_at.inter (hs : unique_mdiff_within_at I s x) (ht : t ∈ 𝓝 x) : unique_mdiff_within_at I (s ∩ t) x := begin rw [unique_mdiff_within_at, ext_chart_at_preimage_inter_eq], exact unique_diff_within_at.inter hs (ext_chart_at_preimage_mem_nhds I x ht) end lemma is_open.unique_mdiff_within_at (xs : x ∈ s) (hs : is_open s) : unique_mdiff_within_at I s x := begin have := unique_mdiff_within_at.inter (unique_mdiff_within_at_univ I) (is_open.mem_nhds hs xs), rwa univ_inter at this end lemma unique_mdiff_on.inter (hs : unique_mdiff_on I s) (ht : is_open t) : unique_mdiff_on I (s ∩ t) := λx hx, unique_mdiff_within_at.inter (hs _ hx.1) (is_open.mem_nhds ht hx.2) lemma is_open.unique_mdiff_on (hs : is_open s) : unique_mdiff_on I s := λx hx, is_open.unique_mdiff_within_at hx hs lemma unique_mdiff_on_univ : unique_mdiff_on I (univ : set M) := is_open_univ.unique_mdiff_on /- We name the typeclass variables related to `smooth_manifold_with_corners` structure as they are necessary in lemmas mentioning the derivative, but not in lemmas about differentiability, so we want to include them or omit them when necessary. -/ variables [Is : smooth_manifold_with_corners I M] [I's : smooth_manifold_with_corners I' M'] [I''s : smooth_manifold_with_corners I'' M''] {f' f₀' f₁' : tangent_space I x →L[𝕜] tangent_space I' (f x)} {g' : tangent_space I' (f x) →L[𝕜] tangent_space I'' (g (f x))} /-- `unique_mdiff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_mdiff_within_at.eq (U : unique_mdiff_within_at I s x) (h : has_mfderiv_within_at I I' f s x f') (h₁ : has_mfderiv_within_at I I' f s x f₁') : f' = f₁' := U.eq h.2 h₁.2 theorem unique_mdiff_on.eq (U : unique_mdiff_on I s) (hx : x ∈ s) (h : has_mfderiv_within_at I I' f s x f') (h₁ : has_mfderiv_within_at I I' f s x f₁') : f' = f₁' := unique_mdiff_within_at.eq (U _ hx) h h₁ /-! ### General lemmas on derivatives of functions between manifolds We mimick the API for functions between vector spaces -/ lemma mdifferentiable_within_at_iff {f : M → M'} {s : set M} {x : M} : mdifferentiable_within_at I I' f s x ↔ continuous_within_at f s x ∧ differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' s) ((ext_chart_at I x) x) := begin refine and_congr iff.rfl (exists_congr $ λ f', _), rw [inter_comm], simp only [has_fderiv_within_at, nhds_within_inter, nhds_within_ext_chart_at_target_eq] end include Is I's /-- One can reformulate differentiability within a set at a point as continuity within this set at this point, and differentiability in any chart containing that point. -/ lemma mdifferentiable_within_at_iff_of_mem_source {x' : M} {y : M'} (hx : x' ∈ (charted_space.chart_at H x).source) (hy : f x' ∈ (charted_space.chart_at H' y).source) : mdifferentiable_within_at I I' f s x' ↔ continuous_within_at f s x' ∧ differentiable_within_at 𝕜 ((ext_chart_at I' y) ∘ f ∘ ((ext_chart_at I x).symm)) (((ext_chart_at I x).symm) ⁻¹' s ∩ set.range I) ((ext_chart_at I x) x') := (differentiable_within_at_local_invariant_prop I I').lift_prop_within_at_indep_chart (structure_groupoid.chart_mem_maximal_atlas _ x) hx (structure_groupoid.chart_mem_maximal_atlas _ y) hy lemma mfderiv_within_zero_of_not_mdifferentiable_within_at (h : ¬ mdifferentiable_within_at I I' f s x) : mfderiv_within I I' f s x = 0 := by simp only [mfderiv_within, h, if_neg, not_false_iff] lemma mfderiv_zero_of_not_mdifferentiable_at (h : ¬ mdifferentiable_at I I' f x) : mfderiv I I' f x = 0 := by simp only [mfderiv, h, if_neg, not_false_iff] theorem has_mfderiv_within_at.mono (h : has_mfderiv_within_at I I' f t x f') (hst : s ⊆ t) : has_mfderiv_within_at I I' f s x f' := ⟨ continuous_within_at.mono h.1 hst, has_fderiv_within_at.mono h.2 (inter_subset_inter (preimage_mono hst) (subset.refl _)) ⟩ theorem has_mfderiv_at.has_mfderiv_within_at (h : has_mfderiv_at I I' f x f') : has_mfderiv_within_at I I' f s x f' := ⟨ continuous_at.continuous_within_at h.1, has_fderiv_within_at.mono h.2 (inter_subset_right _ _) ⟩ lemma has_mfderiv_within_at.mdifferentiable_within_at (h : has_mfderiv_within_at I I' f s x f') : mdifferentiable_within_at I I' f s x := ⟨h.1, ⟨f', h.2⟩⟩ lemma has_mfderiv_at.mdifferentiable_at (h : has_mfderiv_at I I' f x f') : mdifferentiable_at I I' f x := ⟨h.1, ⟨f', h.2⟩⟩ @[simp, mfld_simps] lemma has_mfderiv_within_at_univ : has_mfderiv_within_at I I' f univ x f' ↔ has_mfderiv_at I I' f x f' := by simp only [has_mfderiv_within_at, has_mfderiv_at, continuous_within_at_univ] with mfld_simps theorem has_mfderiv_at_unique (h₀ : has_mfderiv_at I I' f x f₀') (h₁ : has_mfderiv_at I I' f x f₁') : f₀' = f₁' := begin rw ← has_mfderiv_within_at_univ at h₀ h₁, exact (unique_mdiff_within_at_univ I).eq h₀ h₁ end lemma has_mfderiv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_mfderiv_within_at I I' f (s ∩ t) x f' ↔ has_mfderiv_within_at I I' f s x f' := begin rw [has_mfderiv_within_at, has_mfderiv_within_at, ext_chart_at_preimage_inter_eq, has_fderiv_within_at_inter', continuous_within_at_inter' h], exact ext_chart_at_preimage_mem_nhds_within I x h, end lemma has_mfderiv_within_at_inter (h : t ∈ 𝓝 x) : has_mfderiv_within_at I I' f (s ∩ t) x f' ↔ has_mfderiv_within_at I I' f s x f' := begin rw [has_mfderiv_within_at, has_mfderiv_within_at, ext_chart_at_preimage_inter_eq, has_fderiv_within_at_inter, continuous_within_at_inter h], exact ext_chart_at_preimage_mem_nhds I x h, end lemma has_mfderiv_within_at.union (hs : has_mfderiv_within_at I I' f s x f') (ht : has_mfderiv_within_at I I' f t x f') : has_mfderiv_within_at I I' f (s ∪ t) x f' := begin split, { exact continuous_within_at.union hs.1 ht.1 }, { convert has_fderiv_within_at.union hs.2 ht.2, simp only [union_inter_distrib_right, preimage_union] } end lemma has_mfderiv_within_at.nhds_within (h : has_mfderiv_within_at I I' f s x f') (ht : s ∈ 𝓝[t] x) : has_mfderiv_within_at I I' f t x f' := (has_mfderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_mfderiv_within_at.has_mfderiv_at (h : has_mfderiv_within_at I I' f s x f') (hs : s ∈ 𝓝 x) : has_mfderiv_at I I' f x f' := by rwa [← univ_inter s, has_mfderiv_within_at_inter hs, has_mfderiv_within_at_univ] at h lemma mdifferentiable_within_at.has_mfderiv_within_at (h : mdifferentiable_within_at I I' f s x) : has_mfderiv_within_at I I' f s x (mfderiv_within I I' f s x) := begin refine ⟨h.1, _⟩, simp only [mfderiv_within, h, if_pos] with mfld_simps, exact differentiable_within_at.has_fderiv_within_at h.2 end lemma mdifferentiable_within_at.mfderiv_within (h : mdifferentiable_within_at I I' f s x) : (mfderiv_within I I' f s x) = fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : _) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) := by simp only [mfderiv_within, h, if_pos] lemma mdifferentiable_at.has_mfderiv_at (h : mdifferentiable_at I I' f x) : has_mfderiv_at I I' f x (mfderiv I I' f x) := begin refine ⟨h.1, _⟩, simp only [mfderiv, h, if_pos] with mfld_simps, exact differentiable_within_at.has_fderiv_within_at h.2 end lemma mdifferentiable_at.mfderiv (h : mdifferentiable_at I I' f x) : (mfderiv I I' f x) = fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : _) (range I) ((ext_chart_at I x) x) := by simp only [mfderiv, h, if_pos] lemma has_mfderiv_at.mfderiv (h : has_mfderiv_at I I' f x f') : mfderiv I I' f x = f' := (has_mfderiv_at_unique h h.mdifferentiable_at.has_mfderiv_at).symm lemma has_mfderiv_within_at.mfderiv_within (h : has_mfderiv_within_at I I' f s x f') (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I' f s x = f' := by { ext, rw hxs.eq h h.mdifferentiable_within_at.has_mfderiv_within_at } lemma mdifferentiable.mfderiv_within (h : mdifferentiable_at I I' f x) (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I' f s x = mfderiv I I' f x := begin apply has_mfderiv_within_at.mfderiv_within _ hxs, exact h.has_mfderiv_at.has_mfderiv_within_at end lemma mfderiv_within_subset (st : s ⊆ t) (hs : unique_mdiff_within_at I s x) (h : mdifferentiable_within_at I I' f t x) : mfderiv_within I I' f s x = mfderiv_within I I' f t x := ((mdifferentiable_within_at.has_mfderiv_within_at h).mono st).mfderiv_within hs omit Is I's lemma mdifferentiable_within_at.mono (hst : s ⊆ t) (h : mdifferentiable_within_at I I' f t x) : mdifferentiable_within_at I I' f s x := ⟨ continuous_within_at.mono h.1 hst, differentiable_within_at.mono h.2 (inter_subset_inter (preimage_mono hst) (subset.refl _)) ⟩ lemma mdifferentiable_within_at_univ : mdifferentiable_within_at I I' f univ x ↔ mdifferentiable_at I I' f x := by simp only [mdifferentiable_within_at, mdifferentiable_at, continuous_within_at_univ] with mfld_simps lemma mdifferentiable_within_at_inter (ht : t ∈ 𝓝 x) : mdifferentiable_within_at I I' f (s ∩ t) x ↔ mdifferentiable_within_at I I' f s x := begin rw [mdifferentiable_within_at, mdifferentiable_within_at, ext_chart_at_preimage_inter_eq, differentiable_within_at_inter, continuous_within_at_inter ht], exact ext_chart_at_preimage_mem_nhds I x ht end lemma mdifferentiable_within_at_inter' (ht : t ∈ 𝓝[s] x) : mdifferentiable_within_at I I' f (s ∩ t) x ↔ mdifferentiable_within_at I I' f s x := begin rw [mdifferentiable_within_at, mdifferentiable_within_at, ext_chart_at_preimage_inter_eq, differentiable_within_at_inter', continuous_within_at_inter' ht], exact ext_chart_at_preimage_mem_nhds_within I x ht end lemma mdifferentiable_at.mdifferentiable_within_at (h : mdifferentiable_at I I' f x) : mdifferentiable_within_at I I' f s x := mdifferentiable_within_at.mono (subset_univ _) (mdifferentiable_within_at_univ.2 h) lemma mdifferentiable_within_at.mdifferentiable_at (h : mdifferentiable_within_at I I' f s x) (hs : s ∈ 𝓝 x) : mdifferentiable_at I I' f x := begin have : s = univ ∩ s, by rw univ_inter, rwa [this, mdifferentiable_within_at_inter hs, mdifferentiable_within_at_univ] at h, end lemma mdifferentiable_on.mono (h : mdifferentiable_on I I' f t) (st : s ⊆ t) : mdifferentiable_on I I' f s := λx hx, (h x (st hx)).mono st lemma mdifferentiable_on_univ : mdifferentiable_on I I' f univ ↔ mdifferentiable I I' f := by { simp only [mdifferentiable_on, mdifferentiable_within_at_univ] with mfld_simps, refl } lemma mdifferentiable.mdifferentiable_on (h : mdifferentiable I I' f) : mdifferentiable_on I I' f s := (mdifferentiable_on_univ.2 h).mono (subset_univ _) lemma mdifferentiable_on_of_locally_mdifferentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ mdifferentiable_on I I' f (s ∩ u)) : mdifferentiable_on I I' f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (mdifferentiable_within_at_inter (is_open.mem_nhds t_open xt)).1 (ht x ⟨xs, xt⟩) end include Is I's @[simp, mfld_simps] lemma mfderiv_within_univ : mfderiv_within I I' f univ = mfderiv I I' f := begin ext x : 1, simp only [mfderiv_within, mfderiv] with mfld_simps, rw mdifferentiable_within_at_univ end lemma mfderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_mdiff_within_at I s x) : mfderiv_within I I' f (s ∩ t) x = mfderiv_within I I' f s x := by rw [mfderiv_within, mfderiv_within, ext_chart_at_preimage_inter_eq, mdifferentiable_within_at_inter ht, fderiv_within_inter (ext_chart_at_preimage_mem_nhds I x ht) hs] lemma mdifferentiable_at_iff_of_mem_source {x' : M} {y : M'} (hx : x' ∈ (charted_space.chart_at H x).source) (hy : f x' ∈ (charted_space.chart_at H' y).source) : mdifferentiable_at I I' f x' ↔ continuous_at f x' ∧ differentiable_within_at 𝕜 ((ext_chart_at I' y) ∘ f ∘ ((ext_chart_at I x).symm)) (set.range I) ((ext_chart_at I x) x') := mdifferentiable_within_at_univ.symm.trans $ (mdifferentiable_within_at_iff_of_mem_source hx hy).trans $ by rw [continuous_within_at_univ, set.preimage_univ, set.univ_inter] omit Is I's /-! ### Deriving continuity from differentiability on manifolds -/ theorem has_mfderiv_within_at.continuous_within_at (h : has_mfderiv_within_at I I' f s x f') : continuous_within_at f s x := h.1 theorem has_mfderiv_at.continuous_at (h : has_mfderiv_at I I' f x f') : continuous_at f x := h.1 lemma mdifferentiable_within_at.continuous_within_at (h : mdifferentiable_within_at I I' f s x) : continuous_within_at f s x := h.1 lemma mdifferentiable_at.continuous_at (h : mdifferentiable_at I I' f x) : continuous_at f x := h.1 lemma mdifferentiable_on.continuous_on (h : mdifferentiable_on I I' f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma mdifferentiable.continuous (h : mdifferentiable I I' f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at include Is I's lemma tangent_map_within_subset {p : tangent_bundle I M} (st : s ⊆ t) (hs : unique_mdiff_within_at I s p.1) (h : mdifferentiable_within_at I I' f t p.1) : tangent_map_within I I' f s p = tangent_map_within I I' f t p := begin simp only [tangent_map_within] with mfld_simps, rw mfderiv_within_subset st hs h, end lemma tangent_map_within_univ : tangent_map_within I I' f univ = tangent_map I I' f := by { ext p : 1, simp only [tangent_map_within, tangent_map] with mfld_simps } lemma tangent_map_within_eq_tangent_map {p : tangent_bundle I M} (hs : unique_mdiff_within_at I s p.1) (h : mdifferentiable_at I I' f p.1) : tangent_map_within I I' f s p = tangent_map I I' f p := begin rw ← mdifferentiable_within_at_univ at h, rw ← tangent_map_within_univ, exact tangent_map_within_subset (subset_univ _) hs h, end @[simp, mfld_simps] lemma tangent_map_within_proj {p : tangent_bundle I M} : (tangent_map_within I I' f s p).proj = f p.proj := rfl @[simp, mfld_simps] lemma tangent_map_within_fst {p : tangent_bundle I M} : (tangent_map_within I I' f s p).1 = f p.1 := rfl @[simp, mfld_simps] lemma tangent_map_proj {p : tangent_bundle I M} : (tangent_map I I' f p).proj = f p.proj := rfl @[simp, mfld_simps] lemma tangent_map_fst {p : tangent_bundle I M} : (tangent_map I I' f p).1 = f p.1 := rfl omit Is I's /-! ### Congruence lemmas for derivatives on manifolds -/ lemma has_mfderiv_within_at.congr_of_eventually_eq (h : has_mfderiv_within_at I I' f s x f') (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_mfderiv_within_at I I' f₁ s x f' := begin refine ⟨continuous_within_at.congr_of_eventually_eq h.1 h₁ hx, _⟩, apply has_fderiv_within_at.congr_of_eventually_eq h.2, { have : (ext_chart_at I x).symm ⁻¹' {y | f₁ y = f y} ∈ 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) := ext_chart_at_preimage_mem_nhds_within I x h₁, apply filter.mem_of_superset this (λy, _), simp only [hx] with mfld_simps {contextual := tt} }, { simp only [hx] with mfld_simps }, end lemma has_mfderiv_within_at.congr_mono (h : has_mfderiv_within_at I I' f s x f') (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_mfderiv_within_at I I' f₁ t x f' := (h.mono h₁).congr_of_eventually_eq (filter.mem_inf_of_right ht) hx lemma has_mfderiv_at.congr_of_eventually_eq (h : has_mfderiv_at I I' f x f') (h₁ : f₁ =ᶠ[𝓝 x] f) : has_mfderiv_at I I' f₁ x f' := begin rw ← has_mfderiv_within_at_univ at ⊢ h, apply h.congr_of_eventually_eq _ (mem_of_mem_nhds h₁ : _), rwa nhds_within_univ end include Is I's lemma mdifferentiable_within_at.congr_of_eventually_eq (h : mdifferentiable_within_at I I' f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : mdifferentiable_within_at I I' f₁ s x := (h.has_mfderiv_within_at.congr_of_eventually_eq h₁ hx).mdifferentiable_within_at variables (I I') lemma filter.eventually_eq.mdifferentiable_within_at_iff (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : mdifferentiable_within_at I I' f s x ↔ mdifferentiable_within_at I I' f₁ s x := begin split, { assume h, apply h.congr_of_eventually_eq h₁ hx }, { assume h, apply h.congr_of_eventually_eq _ hx.symm, apply h₁.mono, intro y, apply eq.symm } end variables {I I'} lemma mdifferentiable_within_at.congr_mono (h : mdifferentiable_within_at I I' f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : mdifferentiable_within_at I I' f₁ t x := (has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at ht hx h₁).mdifferentiable_within_at lemma mdifferentiable_within_at.congr (h : mdifferentiable_within_at I I' f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : mdifferentiable_within_at I I' f₁ s x := (has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at ht hx (subset.refl _)).mdifferentiable_within_at lemma mdifferentiable_on.congr_mono (h : mdifferentiable_on I I' f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : mdifferentiable_on I I' f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma mdifferentiable_at.congr_of_eventually_eq (h : mdifferentiable_at I I' f x) (hL : f₁ =ᶠ[𝓝 x] f) : mdifferentiable_at I I' f₁ x := ((h.has_mfderiv_at).congr_of_eventually_eq hL).mdifferentiable_at lemma mdifferentiable_within_at.mfderiv_within_congr_mono (h : mdifferentiable_within_at I I' f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_mdiff_within_at I t x) (h₁ : t ⊆ s) : mfderiv_within I I' f₁ t x = (mfderiv_within I I' f s x : _) := (has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at hs hx h₁).mfderiv_within hxt lemma filter.eventually_eq.mfderiv_within_eq (hs : unique_mdiff_within_at I s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : mfderiv_within I I' f₁ s x = (mfderiv_within I I' f s x : _) := begin by_cases h : mdifferentiable_within_at I I' f s x, { exact ((h.has_mfderiv_within_at).congr_of_eventually_eq hL hx).mfderiv_within hs }, { unfold mfderiv_within, rw [if_neg h, if_neg], rwa ← hL.mdifferentiable_within_at_iff I I' hx } end lemma mfderiv_within_congr (hs : unique_mdiff_within_at I s x) (hL : ∀ x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : mfderiv_within I I' f₁ s x = (mfderiv_within I I' f s x : _) := filter.eventually_eq.mfderiv_within_eq hs (filter.eventually_eq_of_mem (self_mem_nhds_within) hL) hx lemma tangent_map_within_congr (h : ∀ x ∈ s, f x = f₁ x) (p : tangent_bundle I M) (hp : p.1 ∈ s) (hs : unique_mdiff_within_at I s p.1) : tangent_map_within I I' f s p = tangent_map_within I I' f₁ s p := begin simp only [tangent_map_within, h p.fst hp, true_and, eq_self_iff_true, heq_iff_eq, sigma.mk.inj_iff], congr' 1, exact mfderiv_within_congr hs h (h _ hp) end lemma filter.eventually_eq.mfderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) : mfderiv I I' f₁ x = (mfderiv I I' f x : _) := begin have A : f₁ x = f x := (mem_of_mem_nhds hL : _), rw [← mfderiv_within_univ, ← mfderiv_within_univ], rw ← nhds_within_univ at hL, exact hL.mfderiv_within_eq (unique_mdiff_within_at_univ I) A end /-! ### Composition lemmas -/ omit Is I's lemma written_in_ext_chart_comp (h : continuous_within_at f s x) : {y | written_in_ext_chart_at I I'' x (g ∘ f) y = ((written_in_ext_chart_at I' I'' (f x) g) ∘ (written_in_ext_chart_at I I' x f)) y} ∈ 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) := begin apply @filter.mem_of_superset _ _ ((f ∘ (ext_chart_at I x).symm)⁻¹' (ext_chart_at I' (f x)).source) _ (ext_chart_at_preimage_mem_nhds_within I x (h.preimage_mem_nhds_within (ext_chart_at_source_mem_nhds _ _))), mfld_set_tac, end variable (x) include Is I's I''s theorem has_mfderiv_within_at.comp (hg : has_mfderiv_within_at I' I'' g u (f x) g') (hf : has_mfderiv_within_at I I' f s x f') (hst : s ⊆ f ⁻¹' u) : has_mfderiv_within_at I I'' (g ∘ f) s x (g'.comp f') := begin refine ⟨continuous_within_at.comp hg.1 hf.1 hst, _⟩, have A : has_fderiv_within_at ((written_in_ext_chart_at I' I'' (f x) g) ∘ (written_in_ext_chart_at I I' x f)) (continuous_linear_map.comp g' f' : E →L[𝕜] E'') ((ext_chart_at I x).symm ⁻¹' s ∩ range (I)) ((ext_chart_at I x) x), { have : (ext_chart_at I x).symm ⁻¹' (f ⁻¹' (ext_chart_at I' (f x)).source) ∈ 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) := (ext_chart_at_preimage_mem_nhds_within I x (hf.1.preimage_mem_nhds_within (ext_chart_at_source_mem_nhds _ _))), unfold has_mfderiv_within_at at *, rw [← has_fderiv_within_at_inter' this, ← ext_chart_at_preimage_inter_eq] at hf ⊢, have : written_in_ext_chart_at I I' x f ((ext_chart_at I x) x) = (ext_chart_at I' (f x)) (f x), by simp only with mfld_simps, rw ← this at hg, apply has_fderiv_within_at.comp ((ext_chart_at I x) x) hg.2 hf.2 _, assume y hy, simp only with mfld_simps at hy, have : f (((chart_at H x).symm : H → M) (I.symm y)) ∈ u := hst hy.1.1, simp only [hy, this] with mfld_simps }, apply A.congr_of_eventually_eq (written_in_ext_chart_comp hf.1), simp only with mfld_simps end /-- The chain rule. -/ theorem has_mfderiv_at.comp (hg : has_mfderiv_at I' I'' g (f x) g') (hf : has_mfderiv_at I I' f x f') : has_mfderiv_at I I'' (g ∘ f) x (g'.comp f') := begin rw ← has_mfderiv_within_at_univ at *, exact has_mfderiv_within_at.comp x (hg.mono (subset_univ _)) hf subset_preimage_univ end theorem has_mfderiv_at.comp_has_mfderiv_within_at (hg : has_mfderiv_at I' I'' g (f x) g') (hf : has_mfderiv_within_at I I' f s x f') : has_mfderiv_within_at I I'' (g ∘ f) s x (g'.comp f') := begin rw ← has_mfderiv_within_at_univ at *, exact has_mfderiv_within_at.comp x (hg.mono (subset_univ _)) hf subset_preimage_univ end lemma mdifferentiable_within_at.comp (hg : mdifferentiable_within_at I' I'' g u (f x)) (hf : mdifferentiable_within_at I I' f s x) (h : s ⊆ f ⁻¹' u) : mdifferentiable_within_at I I'' (g ∘ f) s x := begin rcases hf.2 with ⟨f', hf'⟩, have F : has_mfderiv_within_at I I' f s x f' := ⟨hf.1, hf'⟩, rcases hg.2 with ⟨g', hg'⟩, have G : has_mfderiv_within_at I' I'' g u (f x) g' := ⟨hg.1, hg'⟩, exact (has_mfderiv_within_at.comp x G F h).mdifferentiable_within_at end lemma mdifferentiable_at.comp (hg : mdifferentiable_at I' I'' g (f x)) (hf : mdifferentiable_at I I' f x) : mdifferentiable_at I I'' (g ∘ f) x := (hg.has_mfderiv_at.comp x hf.has_mfderiv_at).mdifferentiable_at lemma mfderiv_within_comp (hg : mdifferentiable_within_at I' I'' g u (f x)) (hf : mdifferentiable_within_at I I' f s x) (h : s ⊆ f ⁻¹' u) (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I'' (g ∘ f) s x = (mfderiv_within I' I'' g u (f x)).comp (mfderiv_within I I' f s x) := begin apply has_mfderiv_within_at.mfderiv_within _ hxs, exact has_mfderiv_within_at.comp x hg.has_mfderiv_within_at hf.has_mfderiv_within_at h end lemma mfderiv_comp (hg : mdifferentiable_at I' I'' g (f x)) (hf : mdifferentiable_at I I' f x) : mfderiv I I'' (g ∘ f) x = (mfderiv I' I'' g (f x)).comp (mfderiv I I' f x) := begin apply has_mfderiv_at.mfderiv, exact has_mfderiv_at.comp x hg.has_mfderiv_at hf.has_mfderiv_at end lemma mdifferentiable_on.comp (hg : mdifferentiable_on I' I'' g u) (hf : mdifferentiable_on I I' f s) (st : s ⊆ f ⁻¹' u) : mdifferentiable_on I I'' (g ∘ f) s := λx hx, mdifferentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma mdifferentiable.comp (hg : mdifferentiable I' I'' g) (hf : mdifferentiable I I' f) : mdifferentiable I I'' (g ∘ f) := λx, mdifferentiable_at.comp x (hg (f x)) (hf x) lemma tangent_map_within_comp_at (p : tangent_bundle I M) (hg : mdifferentiable_within_at I' I'' g u (f p.1)) (hf : mdifferentiable_within_at I I' f s p.1) (h : s ⊆ f ⁻¹' u) (hps : unique_mdiff_within_at I s p.1) : tangent_map_within I I'' (g ∘ f) s p = tangent_map_within I' I'' g u (tangent_map_within I I' f s p) := begin simp only [tangent_map_within] with mfld_simps, rw mfderiv_within_comp p.1 hg hf h hps, refl end lemma tangent_map_comp_at (p : tangent_bundle I M) (hg : mdifferentiable_at I' I'' g (f p.1)) (hf : mdifferentiable_at I I' f p.1) : tangent_map I I'' (g ∘ f) p = tangent_map I' I'' g (tangent_map I I' f p) := begin simp only [tangent_map] with mfld_simps, rw mfderiv_comp p.1 hg hf, refl end lemma tangent_map_comp (hg : mdifferentiable I' I'' g) (hf : mdifferentiable I I' f) : tangent_map I I'' (g ∘ f) = (tangent_map I' I'' g) ∘ (tangent_map I I' f) := by { ext p : 1, exact tangent_map_comp_at _ (hg _) (hf _) } end derivatives_properties section mfderiv_fderiv /-! ### Relations between vector space derivative and manifold derivative The manifold derivative `mfderiv`, when considered on the model vector space with its trivial manifold structure, coincides with the usual Frechet derivative `fderiv`. In this section, we prove this and related statements. -/ variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E'] {f : E → E'} {s : set E} {x : E} lemma unique_mdiff_within_at_iff_unique_diff_within_at : unique_mdiff_within_at (𝓘(𝕜, E)) s x ↔ unique_diff_within_at 𝕜 s x := by simp only [unique_mdiff_within_at] with mfld_simps alias unique_mdiff_within_at_iff_unique_diff_within_at ↔ unique_mdiff_within_at.unique_diff_within_at unique_diff_within_at.unique_mdiff_within_at lemma unique_mdiff_on_iff_unique_diff_on : unique_mdiff_on (𝓘(𝕜, E)) s ↔ unique_diff_on 𝕜 s := by simp [unique_mdiff_on, unique_diff_on, unique_mdiff_within_at_iff_unique_diff_within_at] alias unique_mdiff_on_iff_unique_diff_on ↔ unique_mdiff_on.unique_diff_on unique_diff_on.unique_mdiff_on @[simp, mfld_simps] lemma written_in_ext_chart_model_space : written_in_ext_chart_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) x f = f := rfl lemma has_mfderiv_within_at_iff_has_fderiv_within_at {f'} : has_mfderiv_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x f' ↔ has_fderiv_within_at f f' s x := by simpa only [has_mfderiv_within_at, and_iff_right_iff_imp] with mfld_simps using has_fderiv_within_at.continuous_within_at alias has_mfderiv_within_at_iff_has_fderiv_within_at ↔ has_mfderiv_within_at.has_fderiv_within_at has_fderiv_within_at.has_mfderiv_within_at lemma has_mfderiv_at_iff_has_fderiv_at {f'} : has_mfderiv_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x f' ↔ has_fderiv_at f f' x := by rw [← has_mfderiv_within_at_univ, has_mfderiv_within_at_iff_has_fderiv_within_at, has_fderiv_within_at_univ] alias has_mfderiv_at_iff_has_fderiv_at ↔ has_mfderiv_at.has_fderiv_at has_fderiv_at.has_mfderiv_at /-- For maps between vector spaces, `mdifferentiable_within_at` and `fdifferentiable_within_at` coincide -/ theorem mdifferentiable_within_at_iff_differentiable_within_at : mdifferentiable_within_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s x ↔ differentiable_within_at 𝕜 f s x := begin simp only [mdifferentiable_within_at] with mfld_simps, exact ⟨λH, H.2, λH, ⟨H.continuous_within_at, H⟩⟩ end alias mdifferentiable_within_at_iff_differentiable_within_at ↔ mdifferentiable_within_at.differentiable_within_at differentiable_within_at.mdifferentiable_within_at /-- For maps between vector spaces, `mdifferentiable_at` and `differentiable_at` coincide -/ theorem mdifferentiable_at_iff_differentiable_at : mdifferentiable_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) f x ↔ differentiable_at 𝕜 f x := begin simp only [mdifferentiable_at, differentiable_within_at_univ] with mfld_simps, exact ⟨λH, H.2, λH, ⟨H.continuous_at, H⟩⟩ end alias mdifferentiable_at_iff_differentiable_at ↔ mdifferentiable_at.differentiable_at differentiable_at.mdifferentiable_at /-- For maps between vector spaces, `mdifferentiable_on` and `differentiable_on` coincide -/ theorem mdifferentiable_on_iff_differentiable_on : mdifferentiable_on (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s ↔ differentiable_on 𝕜 f s := by simp only [mdifferentiable_on, differentiable_on, mdifferentiable_within_at_iff_differentiable_within_at] alias mdifferentiable_on_iff_differentiable_on ↔ mdifferentiable_on.differentiable_on differentiable_on.mdifferentiable_on /-- For maps between vector spaces, `mdifferentiable` and `differentiable` coincide -/ theorem mdifferentiable_iff_differentiable : mdifferentiable (𝓘(𝕜, E)) (𝓘(𝕜, E')) f ↔ differentiable 𝕜 f := by simp only [mdifferentiable, differentiable, mdifferentiable_at_iff_differentiable_at] alias mdifferentiable_iff_differentiable ↔ mdifferentiable.differentiable differentiable.mdifferentiable /-- For maps between vector spaces, `mfderiv_within` and `fderiv_within` coincide -/ @[simp] theorem mfderiv_within_eq_fderiv_within : mfderiv_within (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s x = fderiv_within 𝕜 f s x := begin by_cases h : mdifferentiable_within_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s x, { simp only [mfderiv_within, h, if_pos] with mfld_simps }, { simp only [mfderiv_within, h, if_neg, not_false_iff], rw [mdifferentiable_within_at_iff_differentiable_within_at] at h, exact (fderiv_within_zero_of_not_differentiable_within_at h).symm } end /-- For maps between vector spaces, `mfderiv` and `fderiv` coincide -/ @[simp] theorem mfderiv_eq_fderiv : mfderiv (𝓘(𝕜, E)) (𝓘(𝕜, E')) f x = fderiv 𝕜 f x := begin rw [← mfderiv_within_univ, ← fderiv_within_univ], exact mfderiv_within_eq_fderiv_within end end mfderiv_fderiv section specific_functions /-! ### Differentiability of specific functions -/ variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] {E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H') {M' : Type*} [topological_space M'] [charted_space H' M'] [smooth_manifold_with_corners I' M'] namespace continuous_linear_map variables (f : E →L[𝕜] E') {s : set E} {x : E} protected lemma has_mfderiv_within_at : has_mfderiv_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x f := f.has_fderiv_within_at.has_mfderiv_within_at protected lemma has_mfderiv_at : has_mfderiv_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x f := f.has_fderiv_at.has_mfderiv_at protected lemma mdifferentiable_within_at : mdifferentiable_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x := f.differentiable_within_at.mdifferentiable_within_at protected lemma mdifferentiable_on : mdifferentiable_on 𝓘(𝕜, E) 𝓘(𝕜, E') f s := f.differentiable_on.mdifferentiable_on protected lemma mdifferentiable_at : mdifferentiable_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x := f.differentiable_at.mdifferentiable_at protected lemma mdifferentiable : mdifferentiable 𝓘(𝕜, E) 𝓘(𝕜, E') f := f.differentiable.mdifferentiable lemma mfderiv_eq : mfderiv 𝓘(𝕜, E) 𝓘(𝕜, E') f x = f := f.has_mfderiv_at.mfderiv lemma mfderiv_within_eq (hs : unique_mdiff_within_at 𝓘(𝕜, E) s x) : mfderiv_within 𝓘(𝕜, E) 𝓘(𝕜, E') f s x = f := f.has_mfderiv_within_at.mfderiv_within hs end continuous_linear_map namespace continuous_linear_equiv variables (f : E ≃L[𝕜] E') {s : set E} {x : E} protected lemma has_mfderiv_within_at : has_mfderiv_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x (f : E →L[𝕜] E') := f.has_fderiv_within_at.has_mfderiv_within_at protected lemma has_mfderiv_at : has_mfderiv_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x (f : E →L[𝕜] E') := f.has_fderiv_at.has_mfderiv_at protected lemma mdifferentiable_within_at : mdifferentiable_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x := f.differentiable_within_at.mdifferentiable_within_at protected lemma mdifferentiable_on : mdifferentiable_on 𝓘(𝕜, E) 𝓘(𝕜, E') f s := f.differentiable_on.mdifferentiable_on protected lemma mdifferentiable_at : mdifferentiable_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x := f.differentiable_at.mdifferentiable_at protected lemma mdifferentiable : mdifferentiable 𝓘(𝕜, E) 𝓘(𝕜, E') f := f.differentiable.mdifferentiable lemma mfderiv_eq : mfderiv 𝓘(𝕜, E) 𝓘(𝕜, E') f x = (f : E →L[𝕜] E') := f.has_mfderiv_at.mfderiv lemma mfderiv_within_eq (hs : unique_mdiff_within_at 𝓘(𝕜, E) s x) : mfderiv_within 𝓘(𝕜, E) 𝓘(𝕜, E') f s x = (f : E →L[𝕜] E') := f.has_mfderiv_within_at.mfderiv_within hs end continuous_linear_equiv variables {s : set M} {x : M} section id /-! #### Identity -/ lemma has_mfderiv_at_id (x : M) : has_mfderiv_at I I (@_root_.id M) x (continuous_linear_map.id 𝕜 (tangent_space I x)) := begin refine ⟨continuous_id.continuous_at, _⟩, have : ∀ᶠ y in 𝓝[range I] ((ext_chart_at I x) x), ((ext_chart_at I x) ∘ (ext_chart_at I x).symm) y = id y, { apply filter.mem_of_superset (ext_chart_at_target_mem_nhds_within I x), mfld_set_tac }, apply has_fderiv_within_at.congr_of_eventually_eq (has_fderiv_within_at_id _ _) this, simp only with mfld_simps end theorem has_mfderiv_within_at_id (s : set M) (x : M) : has_mfderiv_within_at I I (@_root_.id M) s x (continuous_linear_map.id 𝕜 (tangent_space I x)) := (has_mfderiv_at_id I x).has_mfderiv_within_at lemma mdifferentiable_at_id : mdifferentiable_at I I (@_root_.id M) x := (has_mfderiv_at_id I x).mdifferentiable_at lemma mdifferentiable_within_at_id : mdifferentiable_within_at I I (@_root_.id M) s x := (mdifferentiable_at_id I).mdifferentiable_within_at lemma mdifferentiable_id : mdifferentiable I I (@_root_.id M) := λx, mdifferentiable_at_id I lemma mdifferentiable_on_id : mdifferentiable_on I I (@_root_.id M) s := (mdifferentiable_id I).mdifferentiable_on @[simp, mfld_simps] lemma mfderiv_id : mfderiv I I (@_root_.id M) x = (continuous_linear_map.id 𝕜 (tangent_space I x)) := has_mfderiv_at.mfderiv (has_mfderiv_at_id I x) lemma mfderiv_within_id (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I (@_root_.id M) s x = (continuous_linear_map.id 𝕜 (tangent_space I x)) := begin rw mdifferentiable.mfderiv_within (mdifferentiable_at_id I) hxs, exact mfderiv_id I end @[simp, mfld_simps] lemma tangent_map_id : tangent_map I I (id : M → M) = id := by { ext1 ⟨x, v⟩, simp [tangent_map] } lemma tangent_map_within_id {p : tangent_bundle I M} (hs : unique_mdiff_within_at I s p.proj) : tangent_map_within I I (id : M → M) s p = p := begin simp only [tangent_map_within, id.def], rw mfderiv_within_id, { rcases p, refl }, { exact hs } end end id section const /-! #### Constants -/ variables {c : M'} lemma has_mfderiv_at_const (c : M') (x : M) : has_mfderiv_at I I' (λy : M, c) x (0 : tangent_space I x →L[𝕜] tangent_space I' c) := begin refine ⟨continuous_const.continuous_at, _⟩, simp only [written_in_ext_chart_at, (∘), has_fderiv_within_at_const] end theorem has_mfderiv_within_at_const (c : M') (s : set M) (x : M) : has_mfderiv_within_at I I' (λy : M, c) s x (0 : tangent_space I x →L[𝕜] tangent_space I' c) := (has_mfderiv_at_const I I' c x).has_mfderiv_within_at lemma mdifferentiable_at_const : mdifferentiable_at I I' (λy : M, c) x := (has_mfderiv_at_const I I' c x).mdifferentiable_at lemma mdifferentiable_within_at_const : mdifferentiable_within_at I I' (λy : M, c) s x := (mdifferentiable_at_const I I').mdifferentiable_within_at lemma mdifferentiable_const : mdifferentiable I I' (λy : M, c) := λx, mdifferentiable_at_const I I' lemma mdifferentiable_on_const : mdifferentiable_on I I' (λy : M, c) s := (mdifferentiable_const I I').mdifferentiable_on @[simp, mfld_simps] lemma mfderiv_const : mfderiv I I' (λy : M, c) x = (0 : tangent_space I x →L[𝕜] tangent_space I' c) := has_mfderiv_at.mfderiv (has_mfderiv_at_const I I' c x) lemma mfderiv_within_const (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I' (λy : M, c) s x = (0 : tangent_space I x →L[𝕜] tangent_space I' c) := (has_mfderiv_within_at_const _ _ _ _ _).mfderiv_within hxs end const section arithmetic /-! #### Arithmetic Note that in the in `has_mfderiv_at` lemmas there is an abuse of the defeq between `E'` and `tangent_space 𝓘(𝕜, E') (f z)` (similarly for `g',F',p',q'`). In general this defeq is not canonical, but in this case (the tangent space of a vector space) it is canonical. -/ section group variables {I} {z : M} {f g : M → E'} {f' g' : tangent_space I z →L[𝕜] E'} lemma has_mfderiv_at.add (hf : has_mfderiv_at I 𝓘(𝕜, E') f z f') (hg : has_mfderiv_at I 𝓘(𝕜, E') g z g') : has_mfderiv_at I 𝓘(𝕜, E') (f + g) z (f' + g') := ⟨hf.1.add hg.1, hf.2.add hg.2⟩ lemma mdifferentiable_at.add (hf : mdifferentiable_at I 𝓘(𝕜, E') f z) (hg : mdifferentiable_at I 𝓘(𝕜, E') g z) : mdifferentiable_at I 𝓘(𝕜, E') (f + g) z := (hf.has_mfderiv_at.add hg.has_mfderiv_at).mdifferentiable_at lemma mdifferentiable.add (hf : mdifferentiable I 𝓘(𝕜, E') f) (hg : mdifferentiable I 𝓘(𝕜, E') g) : mdifferentiable I 𝓘(𝕜, E') (f + g) := λ x, (hf x).add (hg x) lemma mfderiv_add (hf : mdifferentiable_at I 𝓘(𝕜, E') f z) (hg : mdifferentiable_at I 𝓘(𝕜, E') g z) : (mfderiv I 𝓘(𝕜, E') (f + g) z : tangent_space I z →L[𝕜] E') = (mfderiv I 𝓘(𝕜, E') f z + mfderiv I 𝓘(𝕜, E') g z : tangent_space I z →L[𝕜] E') := (hf.has_mfderiv_at.add hg.has_mfderiv_at).mfderiv lemma has_mfderiv_at.const_smul (hf : has_mfderiv_at I 𝓘(𝕜, E') f z f') (s : 𝕜) : has_mfderiv_at I 𝓘(𝕜, E') (s • f) z (s • f') := ⟨hf.1.const_smul s, hf.2.const_smul s⟩ lemma mdifferentiable_at.const_smul (hf : mdifferentiable_at I 𝓘(𝕜, E') f z) (s : 𝕜) : mdifferentiable_at I 𝓘(𝕜, E') (s • f) z := (hf.has_mfderiv_at.const_smul s).mdifferentiable_at lemma mdifferentiable.const_smul (s : 𝕜) (hf : mdifferentiable I 𝓘(𝕜, E') f) : mdifferentiable I 𝓘(𝕜, E') (s • f) := λ x, (hf x).const_smul s lemma const_smul_mfderiv (hf : mdifferentiable_at I 𝓘(𝕜, E') f z) (s : 𝕜) : (mfderiv I 𝓘(𝕜, E') (s • f) z : tangent_space I z →L[𝕜] E') = (s • mfderiv I 𝓘(𝕜, E') f z : tangent_space I z →L[𝕜] E') := (hf.has_mfderiv_at.const_smul s).mfderiv lemma has_mfderiv_at.neg (hf : has_mfderiv_at I 𝓘(𝕜, E') f z f') : has_mfderiv_at I 𝓘(𝕜, E') (-f) z (-f') := ⟨hf.1.neg, hf.2.neg⟩ lemma has_mfderiv_at_neg : has_mfderiv_at I 𝓘(𝕜, E') (-f) z (-f') ↔ has_mfderiv_at I 𝓘(𝕜, E') f z f' := ⟨λ hf, by { convert hf.neg; rw [neg_neg] }, λ hf, hf.neg⟩ lemma mdifferentiable_at.neg (hf : mdifferentiable_at I 𝓘(𝕜, E') f z) : mdifferentiable_at I 𝓘(𝕜, E') (-f) z := hf.has_mfderiv_at.neg.mdifferentiable_at lemma mdifferentiable_at_neg : mdifferentiable_at I 𝓘(𝕜, E') (-f) z ↔ mdifferentiable_at I 𝓘(𝕜, E') f z := ⟨λ hf, by { convert hf.neg; rw [neg_neg] }, λ hf, hf.neg⟩ lemma mdifferentiable.neg (hf : mdifferentiable I 𝓘(𝕜, E') f) : mdifferentiable I 𝓘(𝕜, E') (-f) := λ x, (hf x).neg lemma mfderiv_neg (f : M → E') (x : M) : (mfderiv I 𝓘(𝕜, E') (-f) x : tangent_space I x →L[𝕜] E') = (- mfderiv I 𝓘(𝕜, E') f x : tangent_space I x →L[𝕜] E') := begin simp_rw [mfderiv], by_cases hf : mdifferentiable_at I 𝓘(𝕜, E') f x, { exact hf.has_mfderiv_at.neg.mfderiv }, { rw [if_neg hf], rw [← mdifferentiable_at_neg] at hf, rw [if_neg hf, neg_zero] }, end lemma has_mfderiv_at.sub (hf : has_mfderiv_at I 𝓘(𝕜, E') f z f') (hg : has_mfderiv_at I 𝓘(𝕜, E') g z g') : has_mfderiv_at I 𝓘(𝕜, E') (f - g) z (f'- g') := ⟨hf.1.sub hg.1, hf.2.sub hg.2⟩ lemma mdifferentiable_at.sub (hf : mdifferentiable_at I 𝓘(𝕜, E') f z) (hg : mdifferentiable_at I 𝓘(𝕜, E') g z) : mdifferentiable_at I 𝓘(𝕜, E') (f - g) z := (hf.has_mfderiv_at.sub hg.has_mfderiv_at).mdifferentiable_at lemma mdifferentiable.sub (hf : mdifferentiable I 𝓘(𝕜, E') f) (hg : mdifferentiable I 𝓘(𝕜, E') g) : mdifferentiable I 𝓘(𝕜, E') (f - g) := λ x, (hf x).sub (hg x) lemma mfderiv_sub (hf : mdifferentiable_at I 𝓘(𝕜, E') f z) (hg : mdifferentiable_at I 𝓘(𝕜, E') g z) : (mfderiv I 𝓘(𝕜, E') (f - g) z : tangent_space I z →L[𝕜] E') = (mfderiv I 𝓘(𝕜, E') f z - mfderiv I 𝓘(𝕜, E') g z : tangent_space I z →L[𝕜] E') := (hf.has_mfderiv_at.sub hg.has_mfderiv_at).mfderiv end group section algebra_over_ring variables {I} {z : M} {F' : Type*} [normed_ring F'] [normed_algebra 𝕜 F'] {p q : M → F'} {p' q' : tangent_space I z →L[𝕜] F'} lemma has_mfderiv_within_at.mul' (hp : has_mfderiv_within_at I 𝓘(𝕜, F') p s z p') (hq : has_mfderiv_within_at I 𝓘(𝕜, F') q s z q') : has_mfderiv_within_at I 𝓘(𝕜, F') (p * q) s z (p z • q' + p'.smul_right (q z) : E →L[𝕜] F') := ⟨hp.1.mul hq.1, by simpa only with mfld_simps using hp.2.mul' hq.2⟩ lemma has_mfderiv_at.mul' (hp : has_mfderiv_at I 𝓘(𝕜, F') p z p') (hq : has_mfderiv_at I 𝓘(𝕜, F') q z q') : has_mfderiv_at I 𝓘(𝕜, F') (p * q) z (p z • q' + p'.smul_right (q z) : E →L[𝕜] F') := has_mfderiv_within_at_univ.mp $ hp.has_mfderiv_within_at.mul' hq.has_mfderiv_within_at lemma mdifferentiable_within_at.mul (hp : mdifferentiable_within_at I 𝓘(𝕜, F') p s z) (hq : mdifferentiable_within_at I 𝓘(𝕜, F') q s z) : mdifferentiable_within_at I 𝓘(𝕜, F') (p * q) s z := (hp.has_mfderiv_within_at.mul' hq.has_mfderiv_within_at).mdifferentiable_within_at lemma mdifferentiable_at.mul (hp : mdifferentiable_at I 𝓘(𝕜, F') p z) (hq : mdifferentiable_at I 𝓘(𝕜, F') q z) : mdifferentiable_at I 𝓘(𝕜, F') (p * q) z := (hp.has_mfderiv_at.mul' hq.has_mfderiv_at).mdifferentiable_at lemma mdifferentiable_on.mul (hp : mdifferentiable_on I 𝓘(𝕜, F') p s) (hq : mdifferentiable_on I 𝓘(𝕜, F') q s) : mdifferentiable_on I 𝓘(𝕜, F') (p * q) s := λ x hx, (hp x hx).mul $ hq x hx lemma mdifferentiable.mul (hp : mdifferentiable I 𝓘(𝕜, F') p) (hq : mdifferentiable I 𝓘(𝕜, F') q) : mdifferentiable I 𝓘(𝕜, F') (p * q) := λ x, (hp x).mul (hq x) end algebra_over_ring section algebra_over_comm_ring variables {I} {z : M} {F' : Type*} [normed_comm_ring F'] [normed_algebra 𝕜 F'] {p q : M → F'} {p' q' : tangent_space I z →L[𝕜] F'} lemma has_mfderiv_within_at.mul (hp : has_mfderiv_within_at I 𝓘(𝕜, F') p s z p') (hq : has_mfderiv_within_at I 𝓘(𝕜, F') q s z q') : has_mfderiv_within_at I 𝓘(𝕜, F') (p * q) s z (p z • q' + q z • p' : E →L[𝕜] F') := by { convert hp.mul' hq, ext z, apply mul_comm } lemma has_mfderiv_at.mul (hp : has_mfderiv_at I 𝓘(𝕜, F') p z p') (hq : has_mfderiv_at I 𝓘(𝕜, F') q z q') : has_mfderiv_at I 𝓘(𝕜, F') (p * q) z (p z • q' + q z • p' : E →L[𝕜] F') := has_mfderiv_within_at_univ.mp $ hp.has_mfderiv_within_at.mul hq.has_mfderiv_within_at end algebra_over_comm_ring end arithmetic namespace model_with_corners /-! #### Model with corners -/ protected lemma has_mfderiv_at {x} : has_mfderiv_at I 𝓘(𝕜, E) I x (continuous_linear_map.id _ _) := ⟨I.continuous_at, (has_fderiv_within_at_id _ _).congr' I.right_inv_on (mem_range_self _)⟩ protected lemma has_mfderiv_within_at {s x} : has_mfderiv_within_at I 𝓘(𝕜, E) I s x (continuous_linear_map.id _ _) := I.has_mfderiv_at.has_mfderiv_within_at protected lemma mdifferentiable_within_at {s x} : mdifferentiable_within_at I 𝓘(𝕜, E) I s x := I.has_mfderiv_within_at.mdifferentiable_within_at protected lemma mdifferentiable_at {x} : mdifferentiable_at I 𝓘(𝕜, E) I x := I.has_mfderiv_at.mdifferentiable_at protected lemma mdifferentiable_on {s} : mdifferentiable_on I 𝓘(𝕜, E) I s := λ x hx, I.mdifferentiable_within_at protected lemma mdifferentiable : mdifferentiable I (𝓘(𝕜, E)) I := λ x, I.mdifferentiable_at lemma has_mfderiv_within_at_symm {x} (hx : x ∈ range I) : has_mfderiv_within_at 𝓘(𝕜, E) I I.symm (range I) x (continuous_linear_map.id _ _) := ⟨I.continuous_within_at_symm, (has_fderiv_within_at_id _ _).congr' (λ y hy, I.right_inv_on hy.1) ⟨hx, mem_range_self _⟩⟩ lemma mdifferentiable_on_symm : mdifferentiable_on (𝓘(𝕜, E)) I I.symm (range I) := λ x hx, (I.has_mfderiv_within_at_symm hx).mdifferentiable_within_at end model_with_corners section charts variable {e : local_homeomorph M H} lemma mdifferentiable_at_atlas (h : e ∈ atlas H M) {x : M} (hx : x ∈ e.source) : mdifferentiable_at I I e x := begin refine ⟨(e.continuous_on x hx).continuous_at (is_open.mem_nhds e.open_source hx), _⟩, have mem : I ((chart_at H x : M → H) x) ∈ I.symm ⁻¹' ((chart_at H x).symm ≫ₕ e).source ∩ range I, by simp only [hx] with mfld_simps, have : (chart_at H x).symm.trans e ∈ cont_diff_groupoid ∞ I := has_groupoid.compatible _ (chart_mem_atlas H x) h, have A : cont_diff_on 𝕜 ∞ (I ∘ ((chart_at H x).symm.trans e) ∘ I.symm) (I.symm ⁻¹' ((chart_at H x).symm.trans e).source ∩ range I) := this.1, have B := A.differentiable_on le_top (I ((chart_at H x : M → H) x)) mem, simp only with mfld_simps at B, rw [inter_comm, differentiable_within_at_inter] at B, { simpa only with mfld_simps }, { apply is_open.mem_nhds ((local_homeomorph.open_source _).preimage I.continuous_symm) mem.1 } end lemma mdifferentiable_on_atlas (h : e ∈ atlas H M) : mdifferentiable_on I I e e.source := λx hx, (mdifferentiable_at_atlas I h hx).mdifferentiable_within_at lemma mdifferentiable_at_atlas_symm (h : e ∈ atlas H M) {x : H} (hx : x ∈ e.target) : mdifferentiable_at I I e.symm x := begin refine ⟨(e.continuous_on_symm x hx).continuous_at (is_open.mem_nhds e.open_target hx), _⟩, have mem : I x ∈ I.symm ⁻¹' (e.symm ≫ₕ chart_at H (e.symm x)).source ∩ range (I), by simp only [hx] with mfld_simps, have : e.symm.trans (chart_at H (e.symm x)) ∈ cont_diff_groupoid ∞ I := has_groupoid.compatible _ h (chart_mem_atlas H _), have A : cont_diff_on 𝕜 ∞ (I ∘ (e.symm.trans (chart_at H (e.symm x))) ∘ I.symm) (I.symm ⁻¹' (e.symm.trans (chart_at H (e.symm x))).source ∩ range I) := this.1, have B := A.differentiable_on le_top (I x) mem, simp only with mfld_simps at B, rw [inter_comm, differentiable_within_at_inter] at B, { simpa only with mfld_simps }, { apply (is_open.mem_nhds ((local_homeomorph.open_source _).preimage I.continuous_symm) mem.1) } end lemma mdifferentiable_on_atlas_symm (h : e ∈ atlas H M) : mdifferentiable_on I I e.symm e.target := λx hx, (mdifferentiable_at_atlas_symm I h hx).mdifferentiable_within_at lemma mdifferentiable_of_mem_atlas (h : e ∈ atlas H M) : e.mdifferentiable I I := ⟨mdifferentiable_on_atlas I h, mdifferentiable_on_atlas_symm I h⟩ lemma mdifferentiable_chart (x : M) : (chart_at H x).mdifferentiable I I := mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _) /-- The derivative of the chart at a base point is the chart of the tangent bundle, composed with the identification between the tangent bundle of the model space and the product space. -/ lemma tangent_map_chart {p q : tangent_bundle I M} (h : q.1 ∈ (chart_at H p.1).source) : tangent_map I I (chart_at H p.1) q = (equiv.sigma_equiv_prod _ _).symm ((chart_at (model_prod H E) p : tangent_bundle I M → model_prod H E) q) := begin dsimp [tangent_map], rw mdifferentiable_at.mfderiv, { refl }, { exact mdifferentiable_at_atlas _ (chart_mem_atlas _ _) h } end /-- The derivative of the inverse of the chart at a base point is the inverse of the chart of the tangent bundle, composed with the identification between the tangent bundle of the model space and the product space. -/ lemma tangent_map_chart_symm {p : tangent_bundle I M} {q : tangent_bundle I H} (h : q.1 ∈ (chart_at H p.1).target) : tangent_map I I (chart_at H p.1).symm q = ((chart_at (model_prod H E) p).symm : model_prod H E → tangent_bundle I M) ((equiv.sigma_equiv_prod H E) q) := begin dsimp only [tangent_map], rw mdifferentiable_at.mfderiv (mdifferentiable_at_atlas_symm _ (chart_mem_atlas _ _) h), -- a trivial instance is needed after the rewrite, handle it right now. rotate, { apply_instance }, simp only [continuous_linear_map.coe_coe, tangent_bundle.chart_at, h, tangent_bundle_core, chart_at, sigma.mk.inj_iff] with mfld_simps, end end charts end specific_functions /-! ### Differentiable local homeomorphisms -/ namespace local_homeomorph.mdifferentiable variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H} {M : Type*} [topological_space M] [charted_space H M] {E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] {E'' : Type*} [normed_add_comm_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] {e : local_homeomorph M M'} (he : e.mdifferentiable I I') {e' : local_homeomorph M' M''} include he lemma symm : e.symm.mdifferentiable I' I := ⟨he.2, he.1⟩ protected lemma mdifferentiable_at {x : M} (hx : x ∈ e.source) : mdifferentiable_at I I' e x := (he.1 x hx).mdifferentiable_at (is_open.mem_nhds e.open_source hx) lemma mdifferentiable_at_symm {x : M'} (hx : x ∈ e.target) : mdifferentiable_at I' I e.symm x := (he.2 x hx).mdifferentiable_at (is_open.mem_nhds e.open_target hx) variables [smooth_manifold_with_corners I M] [smooth_manifold_with_corners I' M'] [smooth_manifold_with_corners I'' M''] lemma symm_comp_deriv {x : M} (hx : x ∈ e.source) : (mfderiv I' I e.symm (e x)).comp (mfderiv I I' e x) = continuous_linear_map.id 𝕜 (tangent_space I x) := begin have : (mfderiv I I (e.symm ∘ e) x) = (mfderiv I' I e.symm (e x)).comp (mfderiv I I' e x) := mfderiv_comp x (he.mdifferentiable_at_symm (e.map_source hx)) (he.mdifferentiable_at hx), rw ← this, have : mfderiv I I (_root_.id : M → M) x = continuous_linear_map.id _ _ := mfderiv_id I, rw ← this, apply filter.eventually_eq.mfderiv_eq, have : e.source ∈ 𝓝 x := is_open.mem_nhds e.open_source hx, exact filter.mem_of_superset this (by mfld_set_tac) end lemma comp_symm_deriv {x : M'} (hx : x ∈ e.target) : (mfderiv I I' e (e.symm x)).comp (mfderiv I' I e.symm x) = continuous_linear_map.id 𝕜 (tangent_space I' x) := he.symm.symm_comp_deriv hx /-- The derivative of a differentiable local homeomorphism, as a continuous linear equivalence between the tangent spaces at `x` and `e x`. -/ protected def mfderiv {x : M} (hx : x ∈ e.source) : tangent_space I x ≃L[𝕜] tangent_space I' (e x) := { inv_fun := (mfderiv I' I e.symm (e x)), continuous_to_fun := (mfderiv I I' e x).cont, continuous_inv_fun := (mfderiv I' I e.symm (e x)).cont, left_inv := λy, begin have : (continuous_linear_map.id _ _ : tangent_space I x →L[𝕜] tangent_space I x) y = y := rfl, conv_rhs { rw [← this, ← he.symm_comp_deriv hx] }, refl end, right_inv := λy, begin have : (continuous_linear_map.id 𝕜 _ : tangent_space I' (e x) →L[𝕜] tangent_space I' (e x)) y = y := rfl, conv_rhs { rw [← this, ← he.comp_symm_deriv (e.map_source hx)] }, rw e.left_inv hx, refl end, .. mfderiv I I' e x } lemma mfderiv_bijective {x : M} (hx : x ∈ e.source) : function.bijective (mfderiv I I' e x) := (he.mfderiv hx).bijective lemma mfderiv_injective {x : M} (hx : x ∈ e.source) : function.injective (mfderiv I I' e x) := (he.mfderiv hx).injective lemma mfderiv_surjective {x : M} (hx : x ∈ e.source) : function.surjective (mfderiv I I' e x) := (he.mfderiv hx).surjective lemma ker_mfderiv_eq_bot {x : M} (hx : x ∈ e.source) : linear_map.ker (mfderiv I I' e x) = ⊥ := (he.mfderiv hx).to_linear_equiv.ker lemma range_mfderiv_eq_top {x : M} (hx : x ∈ e.source) : linear_map.range (mfderiv I I' e x) = ⊤ := (he.mfderiv hx).to_linear_equiv.range lemma range_mfderiv_eq_univ {x : M} (hx : x ∈ e.source) : range (mfderiv I I' e x) = univ := (he.mfderiv_surjective hx).range_eq lemma trans (he': e'.mdifferentiable I' I'') : (e.trans e').mdifferentiable I I'' := begin split, { assume x hx, simp only with mfld_simps at hx, exact ((he'.mdifferentiable_at hx.2).comp _ (he.mdifferentiable_at hx.1)).mdifferentiable_within_at }, { assume x hx, simp only with mfld_simps at hx, exact ((he.symm.mdifferentiable_at hx.2).comp _ (he'.symm.mdifferentiable_at hx.1)).mdifferentiable_within_at } end end local_homeomorph.mdifferentiable /-! ### Differentiability of `ext_chart_at` -/ section ext_chart_at variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] {s : set M} {x y : M} lemma has_mfderiv_at_ext_chart_at (h : y ∈ (chart_at H x).source) : has_mfderiv_at I 𝓘(𝕜, E) (ext_chart_at I x) y (mfderiv I I (chart_at H x) y : _) := I.has_mfderiv_at.comp y ((mdifferentiable_chart I x).mdifferentiable_at h).has_mfderiv_at lemma has_mfderiv_within_at_ext_chart_at (h : y ∈ (chart_at H x).source) : has_mfderiv_within_at I 𝓘(𝕜, E) (ext_chart_at I x) s y (mfderiv I I (chart_at H x) y : _) := (has_mfderiv_at_ext_chart_at I h).has_mfderiv_within_at lemma mdifferentiable_at_ext_chart_at (h : y ∈ (chart_at H x).source) : mdifferentiable_at I 𝓘(𝕜, E) (ext_chart_at I x) y := (has_mfderiv_at_ext_chart_at I h).mdifferentiable_at lemma mdifferentiable_on_ext_chart_at : mdifferentiable_on I 𝓘(𝕜, E) (ext_chart_at I x) (chart_at H x).source := λ y hy, (has_mfderiv_within_at_ext_chart_at I hy).mdifferentiable_within_at end ext_chart_at /-! ### Unique derivative sets in manifolds -/ section unique_mdiff variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H} {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] {E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] {s : set M} /-- If a set has the unique differential property, then its image under a local diffeomorphism also has the unique differential property. -/ lemma unique_mdiff_on.unique_mdiff_on_preimage [smooth_manifold_with_corners I' M'] (hs : unique_mdiff_on I s) {e : local_homeomorph M M'} (he : e.mdifferentiable I I') : unique_mdiff_on I' (e.target ∩ e.symm ⁻¹' s) := begin /- Start from a point `x` in the image, and let `z` be its preimage. Then the unique derivative property at `x` is expressed through `ext_chart_at I' x`, and the unique derivative property at `z` is expressed through `ext_chart_at I z`. We will argue that the composition of these two charts with `e` is a local diffeomorphism in vector spaces, and therefore preserves the unique differential property thanks to lemma `has_fderiv_within_at.unique_diff_within_at`, saying that a differentiable function with onto derivative preserves the unique derivative property.-/ assume x hx, let z := e.symm x, have z_source : z ∈ e.source, by simp only [hx.1] with mfld_simps, have zx : e z = x, by simp only [z, hx.1] with mfld_simps, let F := ext_chart_at I z, -- the unique derivative property at `z` is expressed through its preferred chart, -- that we call `F`. have B : unique_diff_within_at 𝕜 (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) (F z), { have : unique_mdiff_within_at I s z := hs _ hx.2, have S : e.source ∩ e ⁻¹' ((ext_chart_at I' x).source) ∈ 𝓝 z, { apply is_open.mem_nhds, apply e.continuous_on.preimage_open_of_open e.open_source (is_open_ext_chart_at_source I' x), simp only [z_source, zx] with mfld_simps }, have := this.inter S, rw [unique_mdiff_within_at_iff] at this, exact this }, -- denote by `G` the change of coordinate, i.e., the composition of the two extended charts and -- of `e` let G := F.symm ≫ e.to_local_equiv ≫ (ext_chart_at I' x), -- `G` is differentiable have Diff : ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x)).mdifferentiable I I', { have A := mdifferentiable_of_mem_atlas I (chart_mem_atlas H z), have B := mdifferentiable_of_mem_atlas I' (chart_mem_atlas H' x), exact A.symm.trans (he.trans B) }, have Mmem : (chart_at H z : M → H) z ∈ ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x)).source, by simp only [z_source, zx] with mfld_simps, have A : differentiable_within_at 𝕜 G (range I) (F z), { refine (Diff.mdifferentiable_at Mmem).2.congr (λp hp, _) _; simp only [G, F] with mfld_simps }, -- let `G'` be its derivative let G' := fderiv_within 𝕜 G (range I) (F z), have D₁ : has_fderiv_within_at G G' (range I) (F z) := A.has_fderiv_within_at, have D₂ : has_fderiv_within_at G G' (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) (F z) := D₁.mono (by mfld_set_tac), -- The derivative `G'` is onto, as it is the derivative of a local diffeomorphism, the composition -- of the two charts and of `e`. have C : dense_range (G' : E → E'), { have : G' = mfderiv I I' ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x)) ((chart_at H z : M → H) z), by { rw (Diff.mdifferentiable_at Mmem).mfderiv, refl }, rw this, exact (Diff.mfderiv_surjective Mmem).dense_range }, -- key step: thanks to what we have proved about it, `G` preserves the unique derivative property have key : unique_diff_within_at 𝕜 (G '' (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target)) (G (F z)) := D₂.unique_diff_within_at B C, have : G (F z) = (ext_chart_at I' x) x, by { dsimp [G, F], simp only [hx.1] with mfld_simps }, rw this at key, apply key.mono, show G '' (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) ⊆ (ext_chart_at I' x).symm ⁻¹' e.target ∩ (ext_chart_at I' x).symm ⁻¹' (e.symm ⁻¹' s) ∩ range (I'), rw image_subset_iff, mfld_set_tac end /-- If a set in a manifold has the unique derivative property, then its pullback by any extended chart, in the vector space, also has the unique derivative property. -/ lemma unique_mdiff_on.unique_diff_on_target_inter (hs : unique_mdiff_on I s) (x : M) : unique_diff_on 𝕜 ((ext_chart_at I x).target ∩ ((ext_chart_at I x).symm ⁻¹' s)) := begin -- this is just a reformulation of `unique_mdiff_on.unique_mdiff_on_preimage`, using as `e` -- the local chart at `x`. assume z hz, simp only with mfld_simps at hz, have : (chart_at H x).mdifferentiable I I := mdifferentiable_chart _ _, have T := (hs.unique_mdiff_on_preimage this) (I.symm z), simp only [hz.left.left, hz.left.right, hz.right, unique_mdiff_within_at] with mfld_simps at ⊢ T, convert T using 1, rw @preimage_comp _ _ _ _ (chart_at H x).symm, mfld_set_tac end /-- When considering functions between manifolds, this statement shows up often. It entails the unique differential of the pullback in extended charts of the set where the function can be read in the charts. -/ lemma unique_mdiff_on.unique_diff_on_inter_preimage (hs : unique_mdiff_on I s) (x : M) (y : M') {f : M → M'} (hf : continuous_on f s) : unique_diff_on 𝕜 ((ext_chart_at I x).target ∩ ((ext_chart_at I x).symm ⁻¹' (s ∩ f⁻¹' (ext_chart_at I' y).source))) := begin have : unique_mdiff_on I (s ∩ f ⁻¹' (ext_chart_at I' y).source), { assume z hz, apply (hs z hz.1).inter', apply (hf z hz.1).preimage_mem_nhds_within, exact (is_open_ext_chart_at_source I' y).mem_nhds hz.2 }, exact this.unique_diff_on_target_inter _ end open bundle variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] (Z : M → Type*) [topological_space (total_space Z)] [∀ b, topological_space (Z b)] [∀ b, add_comm_monoid (Z b)] [∀ b, module 𝕜 (Z b)] [fiber_bundle F Z] [vector_bundle 𝕜 F Z] [smooth_vector_bundle F Z I] /-- In a smooth fiber bundle, the preimage under the projection of a set with unique differential in the basis also has unique differential. -/ lemma unique_mdiff_on.smooth_bundle_preimage (hs : unique_mdiff_on I s) : unique_mdiff_on (I.prod (𝓘(𝕜, F))) (π Z ⁻¹' s) := begin /- Using a chart (and the fact that unique differentiability is invariant under charts), we reduce the situation to the model space, where we can use the fact that products respect unique differentiability. -/ assume p hp, replace hp : p.fst ∈ s, by simpa only with mfld_simps using hp, let e₀ := chart_at H p.1, let e := chart_at (model_prod H F) p, have h2s : ∀ x, x ∈ e.target ∩ e.symm ⁻¹' (π Z ⁻¹' s) ↔ (x.1 ∈ e₀.target ∧ (e₀.symm) x.1 ∈ (trivialization_at F Z p.1).base_set) ∧ (e₀.symm) x.1 ∈ s, { intro x, have A : x ∈ e.target ↔ x.1 ∈ e₀.target ∧ (e₀.symm) x.1 ∈ (trivialization_at F Z p.1).base_set, { simp only [e, fiber_bundle.charted_space_chart_at, trivialization.mem_target, bundle.total_space.proj] with mfld_simps }, rw [← A, mem_inter_iff, and.congr_right_iff], intro hx, simp only [fiber_bundle.charted_space_chart_at_symm_fst p x hx] with mfld_simps }, -- It suffices to prove unique differentiability in a chart suffices h : unique_mdiff_on (I.prod (𝓘(𝕜, F))) (e.target ∩ e.symm ⁻¹' (π Z ⁻¹' s)), { have A : unique_mdiff_on (I.prod (𝓘(𝕜, F))) (e.symm.target ∩ e.symm.symm ⁻¹' (e.target ∩ e.symm⁻¹' (π Z ⁻¹' s))), { apply h.unique_mdiff_on_preimage, exact (mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _)).symm, apply_instance }, have : p ∈ e.symm.target ∩ e.symm.symm ⁻¹' (e.target ∩ e.symm⁻¹' (π Z ⁻¹' s)), { simp only [e, hp] with mfld_simps }, apply (A _ this).mono, assume q hq, simp only [e, local_homeomorph.left_inv _ hq.1] with mfld_simps at hq, simp only [hq] with mfld_simps }, assume q hq, simp only [unique_mdiff_within_at, model_with_corners.prod, -preimage_inter] with mfld_simps, have : 𝓝[(I.symm ⁻¹' (e₀.target ∩ e₀.symm⁻¹' s) ∩ range I) ×ˢ univ] (I q.1, q.2) ≤ 𝓝[(λ (p : E × F), (I.symm p.1, p.snd)) ⁻¹' (e.target ∩ e.symm ⁻¹' (π Z ⁻¹' s)) ∩ (range I ×ˢ univ)] (I q.1, q.2), { rw [nhds_within_le_iff, mem_nhds_within], refine ⟨(λ (p : E × F), (I.symm p.1, p.snd)) ⁻¹' e.target, _, _, _⟩, { exact e.open_target.preimage (I.continuous_symm.prod_map continuous_id) }, { simp only [prod.mk.eta] with mfld_simps at hq, simp only [prod.mk.eta, hq] with mfld_simps }, rintro x hx, simp only with mfld_simps at hx, have h2x := hx, simp only [e, fiber_bundle.charted_space_chart_at, trivialization.mem_target] with mfld_simps at h2x, simp only [h2s, hx, h2x, -preimage_inter] with mfld_simps }, refine unique_diff_within_at.mono_nhds _ this, rw [h2s] at hq, -- apply unique differentiability of products to conclude apply unique_diff_on.prod _ unique_diff_on_univ, { simp only [hq] with mfld_simps }, { assume x hx, have A : unique_mdiff_on I (e₀.target ∩ e₀.symm⁻¹' s), { apply hs.unique_mdiff_on_preimage, exact (mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _)), apply_instance }, simp only [unique_mdiff_on, unique_mdiff_within_at, preimage_inter] with mfld_simps at A, have B := A (I.symm x) hx.1.1 hx.1.2, rwa [← preimage_inter, model_with_corners.right_inv _ hx.2] at B } end lemma unique_mdiff_on.tangent_bundle_proj_preimage (hs : unique_mdiff_on I s): unique_mdiff_on I.tangent (π (tangent_space I) ⁻¹' s) := hs.smooth_bundle_preimage _ end unique_mdiff
module Index -- Definitions and encodings of some linear type formers import Linear.Types -- Some equality combinators and lemmas for linear types import Linear.Equality -- Quantitative containers import QCont -- Quantitative polynomial functors import QPF -- Examples of using both QCont and QPF import Examples
Formal statement is: lemma cos_arg_i_mult_zero [simp]: "y \<noteq> 0 \<Longrightarrow> Re y = 0 \<Longrightarrow> cos (arg y) = 0" Informal statement is: If $y$ is a nonzero complex number with real part $0$, then $\cos(\arg(y)) = 0$.
If $s$ and $t$ are compact sets, then the set of all differences $x - y$ where $x \in s$ and $y \in t$ is compact.
cc Copyright (C) 2004-2009: Leslie Greengard and June-Yub Lee cc Contact: [email protected] cc cc This software is being released under a FreeBSD license cc (see license.txt in this directory). c*********************************************************************** subroutine dirft1d1(nj,xj,cj, iflag, ms,fk) implicit none integer nj, iflag, ms real*8 xj(nj) complex*16 cj(nj), fk(-ms/2:(ms-1)/2) c ---------------------------------------------------------------------- c direct computation of nonuniform FFT c c nj c fk(k1) = SUM cj(j) exp(+/-i k1 xj(j)) c j=1 c c for -ms/2 <= k1 <= (ms-1)/2 c c If (iflag .ge.0) the + sign is used in the exponential. c If (iflag .lt.0) the - sign is used in the exponential. c c*********************************************************************** integer j, k1 complex*16 zf, cm1 c do k1 = -ms/2, (ms-1)/2 fk(k1) = dcmplx(0d0,0d0) enddo c do j = 1, nj if (iflag .ge. 0) then zf = dcmplx(dcos(xj(j)),+dsin(xj(j))) else zf = dcmplx(dcos(xj(j)),-dsin(xj(j))) endif c cm1 = cj(j) do k1 = 0, (ms-1)/2 fk(k1) = fk(k1) + cm1 cm1 = cm1 * zf enddo c zf = dconjg(zf) cm1 = cj(j) do k1 = -1, -ms/2, -1 cm1 = cm1 * zf fk(k1) = fk(k1) + cm1 enddo enddo end c c c c c c*********************************************************************** subroutine dirft1d2(nj,xj,cj, iflag, ms,fk) implicit none integer nj, iflag, ms real*8 xj(nj) complex*16 cj(nj), fk(-ms/2:(ms-1)/2) c ---------------------------------------------------------------------- c direct computation of nonuniform FFT c c cj(j) = SUM fk(k1) exp(+/-i k1 xj(j)) c k1 c for j = 1,...,nj c c where -ms/2 <= k1 <= (ms-1)/2 c c c If (iflag .ge.0) the + sign is used in the exponential. c If (iflag .lt.0) the - sign is used in the exponential. c*********************************************************************** integer j, k1 complex*16 zf, cm1 c do j = 1, nj if (iflag .ge. 0) then zf = dcmplx(dcos(xj(j)),+dsin(xj(j))) else zf = dcmplx(dcos(xj(j)),-dsin(xj(j))) endif c cj(j) = fk(0) cm1 = zf do k1 = 1, (ms-1)/2 cj(j) = cj(j) + cm1*fk(k1)+dconjg(cm1)*fk(-k1) cm1 = cm1 * zf enddo if (ms/2*2.eq.ms) cj(j) = cj(j) + dconjg(cm1)*fk(-ms/2) enddo end c c c c c c c*********************************************************************** subroutine dirft1d3(nj,xj,cj, iflag, nk,sk,fk) implicit none integer nj, iflag, nk real*8 xj(nj), sk(nk) complex*16 cj(nj), fk(nk) c ---------------------------------------------------------------------- c direct computation of nonuniform FFT c c nj c fk(k) = SUM cj(j) exp(+/-i s(k) xj(j)) c j=1 c c for k = 1, ..., nk c c If (iflag .ge.0) the + sign is used in the exponential. c If (iflag .lt.0) the - sign is used in the exponential. c c*********************************************************************** integer j, k real*8 ssk c do k = 1, nk if (iflag .ge. 0) then ssk = sk(k) else ssk = -sk(k) endif c fk(k) = dcmplx(0d0, 0d0) do j = 1, nj fk(k) = fk(k) +cj(j)*dcmplx(dcos(ssk*xj(j)),dsin(ssk*xj(j))) enddo enddo end
program fac_init use fac_mod implicit none integer :: i do i = 0, 5 print '(A, I1, A, I6)', 'factorial(', i, ') =', factorial(i) end do end program fac_init
||| Red black trees, adapted from Purely functional data structures by Chris Okasaki. ||| ||| You are guaranteed to get the correct value for a key. ||| ||| TODO: Implement deletion. ||| ||| The code has a lot of duplication that can not be unduplicated in trivially ||| , due to the need to prove different things in different cases. module TypedContainers.RBTree import Data.Nat import Data.DPair import Data.List import TypedContainers.In import TypedContainers.LawfulOrd import TypedContainers.RBTree.Base import TypedContainers.RBTree.Index import TypedContainers.RBTree.Insert %default total export data RBTree : (kt : Type) -> (kord : LawfulOrd kt) => (kt -> Type) -> Type where MkRBTree : GoodTree {height, color, kt, kord, vt, keys} -> RBTree kt vt {kord} export empty : LawfulOrd kt => RBTree kt vt empty = MkRBTree (Empty Refl) export insert : LawfulOrd kt => (k : kt) -> vt k -> RBTree kt vt -> RBTree kt vt insert k v (MkRBTree tree) = let Evidence _ (Evidence _ tree') = insertG k v tree in MkRBTree tree' export index : LawfulOrd kt => kt -> RBTree kt vt -> Maybe (DPair kt vt) index k (MkRBTree tree) = case indexGMaybe k tree {foldRight = \_, _ => (), foldLeft = id} of Left _ => Nothing Right (MkDPair k' $ Evidence _ v) => Just $ MkDPair k' v export index' : LawfullerOrd kt => (k : kt) -> RBTree kt vt -> Maybe (vt k) index' k (MkRBTree tree) = case indexGMaybe k tree {foldRight = \k', (p, _) => p, foldLeft = id} of Left _ => Nothing Right (MkDPair k' $ Evidence p v) => let 0 p = realEquality k' k p in Just $ rewrite sym p in v
#pragma once #include "BoundingVolume.h" #include "Library.h" #include "Tile.h" #include "TileContext.h" #include "TileID.h" #include "TileRefine.h" #include "TilesetOptions.h" #include <CesiumAsync/AsyncSystem.h> #include <CesiumAsync/IAssetAccessor.h> #include <CesiumAsync/IAssetRequest.h> #include <gsl/span> #include <spdlog/fwd.h> #include <cstddef> #include <memory> namespace Cesium3DTilesSelection { /** * @brief The information that is passed to a {@link TileContentLoader} to * create a {@link TileContentLoadResult}. * * For many types of tile content, only the `pRequest` field is required. The * other members are used for content that can generate child tiles, like * external tilesets or composite tiles. These members are usually initialized * from * the corresponding members of the {@link Tile} that the content belongs to. */ struct CESIUM3DTILESSELECTION_API TileContentLoadInput { /** * @brief Creates a new, uninitialized instance for the given tile. * * The `asyncSystem`, `pLogger`, `pAssetAccessor` and `pRequest` will have * default values, and have to be initialized before this instance is passed * to one of the loader functions. * * @param tile The {@link Tile} that the content belongs to */ TileContentLoadInput(const Tile& tile); /** * @brief Creates a new instance * * @param asyncSystem The async system to use for tile content loading. * @param pLogger The logger that will be used * @param pAssetAccessor The asset accessor to make further requests with. * @param pRequest The original tile request and its response. * @param tile The {@link Tile} that the content belongs to. */ TileContentLoadInput( const CesiumAsync::AsyncSystem& asyncSystem, const std::shared_ptr<spdlog::logger>& pLogger, const std::shared_ptr<CesiumAsync::IAssetAccessor>& pAssetAccessor, const std::shared_ptr<CesiumAsync::IAssetRequest>& pRequest, const Tile& tile); /** * @brief Creates a new instance. * * @param asyncSystem The async system to use for tile content loading. * @param pLogger The logger that will be used * @param pAssetAccessor The asset accessor to make further requests with. * @param pRequest The original tile request and its response. * @param tileID The {@link TileID} * @param tileBoundingVolume The tile {@link BoundingVolume} * @param tileContentBoundingVolume The tile content {@link BoundingVolume} * @param tileRefine The {@link TileRefine} strategy * @param tileGeometricError The geometric error of the tile * @param tileTransform The tile transform */ TileContentLoadInput( const CesiumAsync::AsyncSystem& asyncSystem, const std::shared_ptr<spdlog::logger>& pLogger, const std::shared_ptr<CesiumAsync::IAssetAccessor>& pAssetAccessor, const std::shared_ptr<CesiumAsync::IAssetRequest>& pRequest, const TileID& tileID, const BoundingVolume& tileBoundingVolume, const std::optional<BoundingVolume>& tileContentBoundingVolume, TileRefine tileRefine, double tileGeometricError, const glm::dmat4& tileTransform, const TilesetContentOptions& contentOptions); /** * @brief The async system to use for tile content loading. */ CesiumAsync::AsyncSystem asyncSystem; /** * @brief The logger that receives details of loading errors and warnings. */ std::shared_ptr<spdlog::logger> pLogger; /** * @brief The asset accessor to make further requests with. */ std::shared_ptr<CesiumAsync::IAssetAccessor> pAssetAccessor; /** * @brief The asset request and response data for the tile. */ std::shared_ptr<CesiumAsync::IAssetRequest> pRequest; /** * @brief The {@link TileID}. */ TileID tileID; /** * @brief The tile {@link BoundingVolume}. */ BoundingVolume tileBoundingVolume; /** * @brief Tile content {@link BoundingVolume}. */ std::optional<BoundingVolume> tileContentBoundingVolume; /** * @brief The {@link TileRefine}. */ TileRefine tileRefine; /** * @brief The geometric error. */ double tileGeometricError; /** * @brief The tile transform */ glm::dmat4 tileTransform; /** * @brief Options for parsing content and creating Gltf models. */ TilesetContentOptions contentOptions; }; } // namespace Cesium3DTilesSelection
/** *@file CosanBO.h *@author Xinyu Zhang *@brief CosanBO *@date 2021-04-10 */ #ifndef __COSANBO_H_INCLUDED__ #define __COSANBO_H_INCLUDED__ #include <string> #ifndef FMT_HEADER_ONLY #define FMT_HEADER_ONLY #include <fmt/format.h> #endif #include <gsl/gsl> #include <type_traits> #include <cosan/utils/utils.h> #include <cosan/utils/Exceptions.h> #include <random> template<typename NumericType> concept Numeric = std::is_arithmetic<NumericType>::value ; template <class T, class U> concept Derived = std::is_base_of<U, T>::value; namespace Cosan { // template<typename NumericType, // typename = typename std::enable_if<std::is_arithmetic<NumericType>::value,NumericType>::type // > /** Description: data structure for matrix. Will be used throughout the project. */ template<Numeric NumericType> using CosanMatrix = Eigen::Matrix<NumericType, Eigen::Dynamic, Eigen::Dynamic> ; // template<typename NumericType, // typename = typename std::enable_if<std::is_arithmetic<NumericType>::value,NumericType>::type // > /** Description: data structure for column vector. Will be used throughout the project. */ template<Numeric NumericType> using CosanColVector = Eigen::Matrix<NumericType, Eigen::Dynamic, 1> ; // template<typename NumericType, // typename = typename std::enable_if<std::is_arithmetic<NumericType>::value,NumericType>::type // > /** Description: data structure for row vector. Will be used throughout the project. */ template<Numeric NumericType> using CosanRowVector = Eigen::Matrix<NumericType, 1, Eigen::Dynamic> ; // typedef std::variant<CosanMatrix<unsigned int>, CosanMatrix<unsigned long>, // CosanMatrix<unsigned long long>, > /** * @brief Cosan Base Object * @details: Description: Base object CosanBO which all other Cosan objects inherited from. * */ class CosanBO { public: /** * @brief Default constructor. **/ CosanBO(){ } // virtual ~CosanBO(); // virtual CosanBO *Shallow_copy() const; // virtual CosanBO *Deep_copy() const; /** * @brief Get the name of the objects. * @details Description: Get the name of the object. It should return "Abstract Object" **/ virtual const std::string GetName() const { return "Abstract Object";} // virtual bool SaveFile(const std::string &path ,const std::string & prefix = ""); // virtual bool LoadFile(const std::string &path); // void PrintModel(); // virtual bool Equals(CosanBO* other, float accuracy = 0.0); // virtual CosanBO* Clone(); protected: }; } #endif
from scipy.signal import butter, welch, filtfilt, lfilter from scipy import signal from matplotlib import pyplot as plt import numpy as np class preprocesamiento: def __init__(self, X, Y, fm): self.X = np.asarray(X.copy()) self.Y = np.asarray(Y.copy()) self.fm = fm self.num_channels = self.X.shape[1] self.num_trials = self.X.shape[0] self.size_trials = self.X.shape[2] def copy(self, pre): self.X = pre.X.copy() self.Y = pre.Y.copy() self.fm = pre.fm.copy() self.num_channels = self.X.shape[1] self.num_trials = self.X.shape[0] self.size_trials = self.X.shape[2] def getDatos(self): return self.X.copy(), self.Y.copy() def get_fm(self): return self.fm def promediar_trials(self, cantidad): #Los trials que son del mismo tipo deben ser promediados #N=4 (se promediaran 4 trials) clase1 = [] clase2 = [] clases = np.unique(self.Y) for (i,trial) in zip(self.Y,self.X): if i == clases[0]: clase1.append(trial) else: clase2.append(trial) clase1 = np.asarray(clase1) clase2 = np.asarray(clase2) resultado1 = [] N = 0 while (N+cantidad)<len(clase1): grupo = clase1[N:(N+cantidad),:,:] grupo_m = np.mean(grupo, axis=0) resultado1.append(grupo_m) N = N+cantidad resultado2 = [] N = 0 while (N+cantidad)<len(clase1): grupo = clase2[N:(N+cantidad),:,:] grupo_m = np.mean(grupo, axis=0) resultado2.append(grupo_m) N = N+cantidad X = [] X.append(resultado1) X.append(resultado2) Y = [] Y.extend(np.zeros(len(resultado1))) Y.extend(np.ones(len(resultado2))) X = np.asarray(X) Y = np.asarray(Y) X = np.reshape(X, (X.shape[0]*X.shape[1], X.shape[2], X.shape[3])) self.X = X.copy() self.Y = Y.copy() self.num_trials = len(X) def promediar_clase(self, cantidad, clase): trials = [] resultado = [] Y = [] N = 0 for (i,trial) in zip(self.Y,self.X): if i == clase: trials.append(trial) trials = np.asarray(trials) while (N+cantidad)<len(trials): grupo = trials[N:(N+cantidad),:,:] grupo_m = np.mean(grupo, axis=0) resultado.append(grupo_m) N = N+cantidad Y.append(clase) resultado = np.asarray(resultado) Y = np.array(Y) return resultado, Y def promediar_todas_clases(self, cantidad): clases = np.unique(self.Y) resultados, y = self.promediar_clase(cantidad, clases[0]) indice = 1 labels = [] labels.extend(y) while indice < len(clases): r, y = self.promediar_clase(cantidad, clases[indice]) resultados = np.concatenate((resultados, r), axis=0) labels.extend(y) indice += 1 resultados = np.asarray(resultados) labels = np.asarray(labels) def promediar_trials_canal(self, canal): #Funcion que devuelve el promedio de los trials clases = np.unique(self.Y) promedios = [] for c in clases: p = self.X[[pos for pos,x1 in enumerate(self.Y) if x1 == c],:,:] print(p.shape) media = p.mean(0)[canal] print(p.shape) promedios.append(media) promedios = np.asarray(promedios) return promedios def select_classes(self, clases): new_X = [] new_Y = [] position = 0 for i in self.Y: if i in clases: new_X.append(self.X[position]) if len(np.unique(clases)) == 2: if i == clases[0]: #if i > 0: new_Y.extend([1]) else: new_Y.extend([0]) else: new_Y.extend([i]) position += 1 self.X = np.asarray(new_X) self.Y = np.asarray(new_Y) self.num_channels = self.X.shape[1] self.num_trials = self.X.shape[0] self.size_trials = self.X.shape[2] def particionar_en_trozos_trial(self, size_trozos, start_task=3): #Hasta el segundo 3 estamos ante no actividad #A partir del segundo 3 estamos ante una clase de imaginacion tanto motora #como visual cantidad = int(self.X.shape[2]/(size_trozos*self.fm))*self.X.shape[0] X = np.zeros((cantidad, self.X.shape[1], int(size_trozos*self.fm))) Y = np.zeros(cantidad, dtype=int) indice = 0 for trial, etiqueta in zip(self.X, self.Y): inicio = 1 final = inicio + int(size_trozos*self.fm) while final <= trial.shape[1]: trozo = trial[:, inicio:final] X[indice,:,:] = trozo if final<= (start_task*self.fm): Y[indice] = 0 #No imaginacion else: if etiqueta == 0: Y[indice] = etiqueta + 1 #Se marca con la etiqueta de la clase else: Y[indice] = etiqueta indice += 1 inicio = final final = inicio + int(size_trozos*self.fm) X = X[0:indice,:,:] Y = Y[0:indice] self.X = X.copy() self.Y = Y.copy() def asignar_etiqueta_binaria(self): new_y = [] etiquetas = np.unique(self.Y) for i in self.Y: if etiquetas[0] == i: new_y.extend([0]) else: new_y.extend([1]) self.Y = new_y.copy() def delete_bad_channels(self, show=0): #Funcion para eliminar los canales con mucho ruido x_mean = self.X.mean(0) #Calculamos la desviacion estandard de cada canal array_canales = [] for ch in range(x_mean.shape[0]): canal = x_mean[ch,:] array_canales.extend([np.std(canal)]) array_canales = np.asarray(array_canales) mean_std = array_canales.mean() new_ch = [] for ch in range(len(array_canales)): if array_canales[ch] > 2*mean_std: #Se elimina el canal self.num_channels -= 1 if show == 1: print('[+] - Delete channel : ', ch) else: new_ch.extend([ch]) self.X = self.X[:,new_ch,:] def seleccionar_canales(self, canales): self.X = self.X[:,canales,:] self.num_channels = len(canales) def cut(self, ini_task, end_task, ventana=1, solape=0): #Funcion para cortar los trials pos = 0 chunks = [] labels = [] end_t = end_task*self.fm for tarea in self.X: start_chunk = int((ini_task)*self.fm) end_chunk = start_chunk + int(ventana*self.fm) while end_chunk <= end_t: chunk = tarea[:,start_chunk:end_chunk] start_chunk = (end_chunk) - int(solape*self.fm) end_chunk = start_chunk + int(ventana*self.fm) chunks.append(chunk) labels.extend([self.Y[pos]]) pos = pos + 1 self.Y = np.asarray(labels).copy() self.X = np.asarray(chunks).copy() self.num_trials = self.X.shape[0] self.size_trials = self.X.shape[2] def delete_DC(self): #Eliminamos la linea base de los canales for i in range(self.num_trials): for ch in range(self.num_channels): channel = self.X[i,ch,:] self.X[i,ch,:] = channel - np.mean(channel) def normalizar(self): for i in range(self.num_trials): for ch in range(self.num_channels): channel = self.X[i,ch,:] self.X[i,ch,:] = (channel-np.min(channel))/(np.max(channel)-np.min(channel)) def z_normalizar(self): for i in range(self.num_trials): for ch in range(self.num_channels): channel = self.X[i,ch,:] self.X[i,ch,:] = (channel-np.mean(channel))/(np.std(channel)) def resamplear(self, new_fm): newNumSamples = int((self.size_trials / self.fm) * new_fm) X_new = np.zeros((self.X.shape[0], self.X.shape[1], newNumSamples)) for i in range(self.num_trials): for ch in range(self.num_channels): channel = self.X[i,ch,:] newNumSamples = int((channel.shape[0] / self.fm) * new_fm) y = signal.resample(channel, newNumSamples) X_new[i,ch,:] = y self.X = X_new.copy() self.fm = new_fm self.size_trials = newNumSamples def butter_bandpass(self, lowcut, highcut, order=5): nyq = 0.5 * self.fm low = lowcut / nyq high = highcut / nyq b, a = butter(order, [low, high], btype='band') return b, a def filtrar_butter(self, band1, band2, order): b, a = self.butter_bandpass(band1, band2, order) for i in range(self.num_trials): for ch in range(self.num_channels): channel = self.X[i,ch,:] tamano = channel.shape[0] channel = np.concatenate((channel, channel)) y = lfilter(b, a, channel) y = y[0:tamano] self.X[i,ch,:] = y def filtrar_conv(self): '''We design a FIR filter using the window method. We'll pass in 400 as the first argument (we're using 400 taps). Higher numbers mean more precise filtering (the cutoff at our chosen frequencies will be steeper), but more processing and, in a real-time setting, increased latency. The latency when filtering using n stops is about n/2 samples, so in this case we would get a latency of about 200 milliseconds. For our purposes, the precise choice of this first parameter is not very critical.''' filtro = signal.firwin(400, [0.01, 0.06], pass_zero=False) for i in range(self.num_trials): for ch in range(self.num_channels): channel = self.X[i,ch,:] y = signal.convolve(channel, filtro, mode='same') self.X[i,ch,:] = y def promediar(self, trial, canal): suma = np.zeros(trial.shape[1]) for ch in range(trial.shape[0]): if not ch == canal: suma = suma + trial[ch, :] return suma/trial.shape[0] def CAR(self): '''Implementacion de un filtro CAR''' new_trials = np.zeros((self.X.shape[0], self.X.shape[1], self.X.shape[2])) posicion = 0 for posicion in range(0, self.X.shape[0]): trial = self.X[posicion] for ch in range(trial.shape[0]): canal = trial[ch, :] #Promediamos los otros canales promedio = self.promediar(trial, ch) canal_CAR = canal - promedio new_trials[posicion,ch,:] = canal_CAR posicion +=1 self.X = new_trials
//---------------------------------------------------------------------------// // Copyright (c) 2013-2015 Kyle Lutz <[email protected]> // // 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 // // See http://boostorg.github.com/compute for more information. //---------------------------------------------------------------------------// #define BOOST_TEST_MODULE TestImage3D #include <boost/test/unit_test.hpp> #include <boost/compute/system.hpp> #include <boost/compute/image/image3d.hpp> #include "context_setup.hpp" namespace compute = boost::compute; BOOST_AUTO_TEST_CASE(image3d_get_supported_formats) { const std::vector<compute::image_format, mi_stl_allocator<compute::image_format>> formats = compute::image3d::get_supported_formats(context); } // check type_name() for image3d BOOST_AUTO_TEST_CASE(image3d_type_name) { BOOST_CHECK( std::strcmp( boost::compute::type_name<boost::compute::image3d>(), "image3d_t") == 0); } BOOST_AUTO_TEST_SUITE_END()
/- Copyright (c) 2022 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne ! This file was ported from Lean 3 source module measure_theory.function.strongly_measurable.lp ! leanprover-community/mathlib commit f2ce6086713c78a7f880485f7917ea547a215982 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.MeasureTheory.Function.SimpleFuncDenseLp import Mathbin.MeasureTheory.Function.StronglyMeasurable.Basic /-! # Finitely strongly measurable functions in `Lp` Functions in `Lp` for `0 < p < ∞` are finitely strongly measurable. ## Main statements * `mem_ℒp.ae_fin_strongly_measurable`: if `mem_ℒp f p μ` with `0 < p < ∞`, then `ae_fin_strongly_measurable f μ`. * `Lp.fin_strongly_measurable`: for `0 < p < ∞`, `Lp` functions are finitely strongly measurable. ## References * Hytönen, Tuomas, Jan Van Neerven, Mark Veraar, and Lutz Weis. Analysis in Banach spaces. Springer, 2016. -/ open MeasureTheory Filter TopologicalSpace Function open ENNReal Topology MeasureTheory namespace MeasureTheory -- mathport name: «expr →ₛ » local infixr:25 " →ₛ " => SimpleFunc variable {α G : Type _} {p : ℝ≥0∞} {m m0 : MeasurableSpace α} {μ : Measure α} [NormedAddCommGroup G] {f : α → G} theorem Memℒp.finStronglyMeasurableOfStronglyMeasurable (hf : Memℒp f p μ) (hf_meas : StronglyMeasurable f) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : FinStronglyMeasurable f μ := by borelize G haveI : separable_space (Set.range f ∪ {0} : Set G) := hf_meas.separable_space_range_union_singleton let fs := simple_func.approx_on f hf_meas.measurable (Set.range f ∪ {0}) 0 (by simp) refine' ⟨fs, _, _⟩ · have h_fs_Lp : ∀ n, mem_ℒp (fs n) p μ := simple_func.mem_ℒp_approx_on_range hf_meas.measurable hf exact fun n => (fs n).measure_support_lt_top_of_memℒp (h_fs_Lp n) hp_ne_zero hp_ne_top · intro x apply simple_func.tendsto_approx_on apply subset_closure simp #align measure_theory.mem_ℒp.fin_strongly_measurable_of_strongly_measurable MeasureTheory.Memℒp.finStronglyMeasurableOfStronglyMeasurable theorem Memℒp.aeFinStronglyMeasurable (hf : Memℒp f p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : AeFinStronglyMeasurable f μ := ⟨hf.AeStronglyMeasurable.mk f, ((memℒp_congr_ae hf.AeStronglyMeasurable.ae_eq_mk).mp hf).finStronglyMeasurableOfStronglyMeasurable hf.AeStronglyMeasurable.stronglyMeasurable_mk hp_ne_zero hp_ne_top, hf.AeStronglyMeasurable.ae_eq_mk⟩ #align measure_theory.mem_ℒp.ae_fin_strongly_measurable MeasureTheory.Memℒp.aeFinStronglyMeasurable theorem Integrable.aeFinStronglyMeasurable (hf : Integrable f μ) : AeFinStronglyMeasurable f μ := (memℒp_one_iff_integrable.mpr hf).AeFinStronglyMeasurable one_ne_zero ENNReal.coe_ne_top #align measure_theory.integrable.ae_fin_strongly_measurable MeasureTheory.Integrable.aeFinStronglyMeasurable theorem lp.finStronglyMeasurable (f : lp G p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : FinStronglyMeasurable f μ := (lp.memℒp f).finStronglyMeasurableOfStronglyMeasurable (lp.stronglyMeasurable f) hp_ne_zero hp_ne_top #align measure_theory.Lp.fin_strongly_measurable MeasureTheory.lp.finStronglyMeasurable end MeasureTheory
#--------------------------------------------------------- # # Tracer Transport Operators #--------------------------------------------------------- #md # !!! tip #md # This example is also available as a Jupyter notebook: #md # [`tracer_transport_operators.ipynb`](@__NBVIEWER_ROOT_URL__/examples/generated/tracer_transport_operators.ipynb) # To model marine biogeochemical processes on a global scale we need to be able to account for the movement of chemical constituents both horizontally and vertically. # We do this with a **tracer transport operator**. # When this operator acts on a tracer field it produces the advective-diffusive divergence of the tracer. #--------------------------------------------------------- # ## Discretization #--------------------------------------------------------- # In order to represent the transport operator on a computer one needs to discretize the tracer concentration field and the operator. # Once discretized the tracer field is represented as a vector and the operator is represented as a sparse matrix. #md # !!! note #md # A sparse matrix behaves the same way as a regular matrix. #md # The only difference is that in a sparse matrix the majority of the entries are zeros. #md # These zeros are not stored explicitly to save computer memory making it possible to deal with fairly high resolution ocean models. #nb # > **Note** #nb # > A sparse matrix behaves the same way as a regular matrix. #nb # > The only difference is that in a sparse matrix the majority of the entries are zeros. #nb # > These zeros are not stored explicitly to save computer memory making it possible to deal with fairly high resolution ocean models. # Mathematically, the discretization converts an expression with partial derivatives into a matrix vector product. # For the ocean circulation, we do the following conversion # # $$\nabla \cdot \left[ \boldsymbol{u} - \mathbf{K} \cdot \nabla \right] C \longrightarrow \mathbf{T} \, \boldsymbol{C}$$ # # where $C(\boldsymbol{r})$ is a tracer concentration at location $\boldsymbol{r}$. # (We often omit the $\boldsymbol{r}$ dependency in equations for brevity.) # The $\nabla \cdot \left[ \boldsymbol{u} - \mathbf{K} \cdot \nabla \right] C$ term is the flux divergence of the tracer due to the marine currents and turbulent eddies. # ($\boldsymbol{u}$ is the 3D current velocity and $\mathbf{K}$ the diffusivity matrix.) # The matrix $\mathbf{T}$ is the flux divergence transport matrix and $\boldsymbol{C}$ is the tracer concentration vector. # # One can go a long way towards understanding what a tracer transport operator is by playing with a simple model with only a few boxes, which is the goal of this example. # The simple box model we consider is embeded in a 2×2×2 "shoebox". # It has 5 *wet* boxes and 3 *dry* boxes, as illustrated below: #md # ```@raw html #md # <img src="https://user-images.githubusercontent.com/4486578/58314610-3b130b80-7e53-11e9-9fe8-9527cdcca2d0.png" width =800> #md # ``` #nb # <img src="https://user-images.githubusercontent.com/4486578/58314610-3b130b80-7e53-11e9-9fe8-9527cdcca2d0.png" width =800> # The circulation consists of # - a meridional overturning circulation flowing in a cycle through boxes 1 → 2 → 6 → 5 → 1 (shown in the "meridional section 1" panel above) # - a zonal current in a reentrant cycling through boxes 1 → 3 → 1 (shown in the "layer 1" panel above) # - vertical mixing representing deep convection between boxes 2 ↔ 6 (not shown) #--------------------------------------------------------- # ## The model grid and the transport matrix #--------------------------------------------------------- # Like for any models using AIBECS, we start by telling Julia just that: using AIBECS # We then load the shoebox model via wet3D, grd, T = Primeau_2x2x2.load() ; # where we have loaded 3 objects, `wet3D`, `grd`, and `T`. # `wet3D` is 3D array representing the 3D ocean with `true` for "wet" boxes and `false` for "dry" boxes. # Let's have a look at its contents: wet3D # It's a 2×2×2 `BitArray`, i.e., an array of bit elements (the `true` and `false` entries). # You can check that it matches our "shoebox" model. # (Well, except for the orientation, for which northwards in the box model is downwards in the array.) # We can find all the wet boxes simply via findall(wet3D) # These are the 3D indices of the wet boxes, `(i,j,k)`, called the "cartesian" indices. # If you want the "linear" indices, i.e., the numbers as shown in the image of the shoebox model, you can simply transform `wet3D` into a vector, via iwet = findall(vec(wet3D)) # We can also check that we indeed have the expected number of wet boxes via nb = length(iwet) # Now let's look at the grid, `grd`: grd # It's an `OceanGrid` object, of size 2×2×2, as expected. # This object is defined in the [OceanGrids](https://github.com/briochemc/OceanGrids.jl) package, on which AIBECS depends. # There are many ways to look inside the grid, one of which is to iterate over it: [println(box) for box in grd] ; # shows some details about all the boxes of the model, one at a time. # The `grd` object also contains other information about the grid, like the 3D depths of the boxes: grd.depth_3D # or the 3D latitudes: grd.lat_3D # where you can check that northwards = downwards in the array. # You may notice these come with units! # This helps ensure that degrees of latitude are not confused with meters for example. #md # !!! note #md # Julia comes with [Unitful](https://github.com/PainterQubits/Unitful.jl), a package for using units, which AIBECS uses. #nb # > **Note** #nb # > Julia comes with [Unitful](https://github.com/PainterQubits/Unitful.jl), a package for using units, which AIBECS uses. # Finally, let's have a look at the transport matrix `T`, which represents $\nabla \cdot \left[ \boldsymbol{u} - \mathbf{K} \cdot \nabla \right]$, i.e., the flux divergence operator for dissolved tracers: T # It's a sparse matrix (a `SparseMatrixCSC` object in Julia), which only stores those entries that are not zero. # We can display the full matrix via Matrix(T) # to check its structure out. # Note that all the diagonal terms are positive, which is the sign that the transport matrix acts as a divergence, which would be positive for a box containing all the tracer. # For example, if there was only some tracer in box 2, then that tracer should "diverge" away from that box, resulting in the positiva value in that box: j = 2 # index where we put some tracer x = 1.0 * [i == j for i in 1:nb] # vector of 0's except for index j x, (T * x)[j] # shows that the flux divergence `T * x` is positive where we injected the tracer. #--------------------------------------------------------- # ## Radiocarbon #--------------------------------------------------------- # Radiocarbon, ¹⁴C, is produced by cosmic rays in the lower stratosphere and upper troposphere. # It quickly reacts with oxygen to produce ¹⁴CO₂, which is then mixed throughout the troposphere and enters the ocean through air–sea gas exchange. # Because the halflife of radiocarbon is only 5730 years a significant amount of decay can occur before the dissolved inorganic radiocarbon (DI¹⁴C) can mix uniformally throughout the ocean. # As such the ¹⁴C serves as a tracer label for water that was recently in contact with the atmosphere. # ### Tracer Equation # Mathematically, the ¹⁴C tracer concentration, denoted $R$ (for Radiocarbon), satisfies the following tracer equation: # # $$\frac{\partial R}{\partial t} + \nabla \cdot \left[ \boldsymbol{u} - \mathbf{K} \cdot \nabla \right] R = \Lambda(R_\mathsf{atm} - R) - R / \tau,$$ # # where $\Lambda(R_\mathsf{atm} - R)$ represents the air–sea exchanges and $R / \tau$ the radioactive decay rate. # ($\tau$ is the radioactive decay timescale.) # The discretized tracer is thus given by # # $$\frac{\partial \boldsymbol{R}}{\partial t} + \mathbf{T} \, \boldsymbol{R} = \mathbf{\Lambda}(R_\mathsf{atm} - \boldsymbol{R}) - \boldsymbol{R} / \tau.$$ # ### Translation to AIBECS Code # We will perform an idealized radiocarbon simulation in our model and use the ocean circulation defined earlier using AIBECS. # In this model we prescribe the atmospheric concentration, $R_\mathsf{atm}$, to be simply equal to 1. # (We do not specify its unit or its specific value because it is not important for determining the age of a water parcel — only the decay rate does.) # To use AIBECS, one must put the equations into the generic form of # # $$\frac{\partial \boldsymbol{x}}{\partial t} + \mathbf{T}(\boldsymbol{p}) \, \boldsymbol{x} = \boldsymbol{G}(\boldsymbol{x}, \boldsymbol{p}),$$ # # where $\boldsymbol{x}$ is the state vector, $\boldsymbol{p}$ is the vector of model parameters, $\mathbf{T}(\boldsymbol{p})$ is the transport operator, and $\boldsymbol{G}(\boldsymbol{x}, \boldsymbol{p})$ is the local sources minus sinks. # In our radiocarbon-model context, with $\boldsymbol{x} = \boldsymbol{R}$, we have that # # $$\boldsymbol{G}(\boldsymbol{x}, \boldsymbol{p}) = \mathbf{\Lambda}(R_\mathsf{atm} - \boldsymbol{x}) - \boldsymbol{x} / \tau.$$ # # Hence, we must create `T(p)` and `G(x,p)` to give AIBECS the means to simulate the tracer distribution and/or its evolution in time. # #### Sources and Sinks # The local sources and sinks are thus simply given by function G(x, p) τ, Ratm = p.τ, p.Ratm return Λ(Ratm .- x, p) - x / τ end # where `τ` is the decay rate timescale and `Ratm` is the atmospheric concentration of radiocarbon. # We must define the air–sea exchange rate, `Λ(x,p)`, which requires us to define which boxes are located at the surface first. # This is done, e.g., via surface_boxes = grd.depth_3D[iwet] .== grd.depth[1] # The air–sea exchange rate is then given by function Λ(x, p) λ, h = p.λ, p.h return λ / h * surface_boxes .* x end # where `λ` is the piston velocity and `h` is the height of the top layer of the model grid. # #### Parameters # For the air–sea gas exchange, we use a constant piston velocity $\lambda$ of 50m / 10years, which will happen in the top layer, of height given by, well, the height of the top layer. # And for the radioactive decay we use a timescale $\tau$ of 5730/log(2) years. # We define these as parameters using the dedicated API from the AIBECS: t = empty_parameter_table() # initialize an empty table of parameters add_parameter!(t, :τ, 5730u"yr"/log(2)) # radioactive decay e-folding timescale add_parameter!(t, :λ, 50u"m" / 10u"yr") # piston velocity add_parameter!(t, :h, grd.δdepth[1]) # height of top layer add_parameter!(t, :Ratm, 1.0u"mol/m^3") # atmospheric concentration t # shows the parameters that you just created. # We now generate a new object to contain all these parameters via initialize_Parameters_type(t, "C14_shoebox_parameters") # creates the type for parameters p = C14_shoebox_parameters() # creates the parameters object # #### Generate the state function and its Jacobian # The last step for the setup is for AIBECS to create $\boldsymbol{F}(\boldsymbol{x}, \boldsymbol{p}) = \boldsymbol{G}(\boldsymbol{x}, \boldsymbol{p}) - \mathbf{T}(\boldsymbol{p}) \, \boldsymbol{x}$, which defines the rate of change of the state, $\boldsymbol{x}$. # This is done via F, ∇ₓF = state_function_and_Jacobian(p -> T, G) # generates the state function (and its Jacobian!) x = zeros(nb) F(x,p) # Note here that AIBECS has automatically created `∇ₓF`, i.e., $\nabla_{\boldsymbol{x}}\boldsymbol{F}(\boldsymbol{x}, \boldsymbol{p})$, which is the Jacobian of the system. # This Jacobian will be useful in the simulations below. # That's it! # Your model is entirely setup and ready to be used for simulations! #--------------------------------------------------------- # ## Time stepping #--------------------------------------------------------- # One way to see how the tracer evolves with time is to time step it. # Here we will use the [Crank-Nicolson](https://en.wikipedia.org/wiki/Crank%E2%80%93Nicolson_method) scheme embedded in AIBECS. # # A single step is performed via, e.g., δt = ustrip(1.0u"yr" |> u"s") AIBECS.crank_nicolson_step(x, p, δt, F, ∇ₓF) # We can write a function to run all the time steps and save them into a `x_hist` object, via function time_steps(x₀, Δt, n, F, ∇ₓF) x_hist = [x₀] δt = Δt / n for i in 1:n push!(x_hist, AIBECS.crank_nicolson_step(last(x_hist), p, δt, F, ∇ₓF)) end return reduce(hcat, x_hist), 0:δt:Δt end #md # !!! note #md # We store all the history of `x` in `x_hist`. #md # At each step, the `push!` function adds a new `x` to `x_hist`. #md # Technically, `x_hist` is a vector of vectors, so at the end, we horizontally concatenate it via `reduce(hcat, x_hist)` to rearrange it into a 2D array. #nb # > **Note** #nb # > We store all the history of `x` in `x_hist`. #nb # > At each step, the `push!` function adds a new `x` to `x_hist`. #nb # > Technically, `x_hist` is a vector of vectors, so at the end, we horizontally concatenate it via `reduce(hcat, x_hist)` to rearrange it into a 2D array. # Now let's simulate the evolution of radiocarbon for 7500 years, starting from a concentration of 1 everywhere, via Δt = ustrip(7500u"yr" |> u"s") # 7500 years in seconds x₀ = ones(5) # x_hist, t_hist = time_steps(x₀, Δt, 1000, F, ∇ₓF) # runs the simulation # This should take a few seconds to run. #md # !!! note #md # AIBECS also has other time-stepping methods available, including Euler-froward (fast but unstable), Euler-backwards (like Crank-Nicolson, slow but stable), and Crank-Nicolson-Leapfrog (Fast-ish and more stable than Euler forward). #nb # > **Note** #nb # > AIBECS also has other time-stepping methods available, including Euler-froward (fast but unstable), Euler-backwards (like Crank-Nicolson, slow but stable), and Crank-Nicolson-Leapfrog (Fast-ish and more stable than Euler forward). # Once it's done, we can plot the evolution of radiocarbon through time via using PyPlot clf() C14age_hist = -log.(x_hist) * ustrip(p.τ * u"s" |> u"yr") plot(t_hist * ustrip(1u"s" |> u"yr"), C14age_hist') xlabel("simulation time (years)") ylabel("¹⁴C age (years)") legend("box " .* string.(iwet)) title("Simulation of the evolution of ¹⁴C age with Crank-Nicolson time steps") gcf() # The box model took more than 4000 years to spin up to equilibrium. # For a box model that's no big deal because it is not computationally expensive to run the model, but for a big circulation model waiting for the model to spinup is painfully long. # We therefore want a better way to find the equilibrium solution. #--------------------------------------------------------- # ## Solving Directly for the Steady State #--------------------------------------------------------- # With the AIBECS, you can create the steady state problem and solve it in just 2 commands: prob = SteadyStateProblem(F, ∇ₓF, x, p) x_final = solve(prob, CTKAlg()).u # Converting radiocarbon into years gives the following values C14age_final = -log.(x_final) * p.τ * u"s" .|> u"yr" println.("box ", iwet, ": ", C14age_final); # These are exactly the limit that the Radiocarbon age reaches after about 4000 years of simulation! # So what happened there? # Well, AIBECS used a version of [Newton's method](https://en.wikipedia.org/wiki/Newton%27s_method) to solve for $\boldsymbol{F}(\boldsymbol{x}, \boldsymbol{p}) = 0$. # Simply put, Newton's method iterates on the state via the recursion relation # # $$\boldsymbol{x}_{n+1} = \boldsymbol{x}_n - \nabla_{\boldsymbol{x}}\boldsymbol{F}(\boldsymbol{x}, \boldsymbol{p})^{-1} \boldsymbol{F}(\boldsymbol{x}, \boldsymbol{p}).$$ # Here, our radiocarbon model only requires a single iteration. # This is because the state function, $\boldsymbol{F}(\boldsymbol{x}, \boldsymbol{p})$, is linear.
function state = is_octave() % is_octave: checks if the script is running on Octave or MATLAB. % % INPUT % None. % % OUTPUT % state, TRUE or FALSE. % % Copyright (C) 2014, Rodrigo Gonzalez, all rights reserved. % % This file is part of NaveGo, an open-source MATLAB toolbox for % simulation of integrated navigation systems. % % NaveGo is free software: you can redistribute it and/or modify % it under the terms of the GNU Lesser General Public License (LGPL) % version 3 as published by the Free Software Foundation. % % This program 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 Lesser General Public License for more details. % % You should have received a copy of the GNU Lesser General Public % License along with this program. If not, see % <http://www.gnu.org/licenses/>. % % References: % % % Version: 001 % Date: 2021/12/09 % Author: Rodrigo Gonzalez <[email protected]> % URL: https://github.com/rodralez/navego state = exist('OCTAVE_VERSION', 'builtin') ~= 0; end
require(data.table) require(Rcpp) require(ggplot2) nextTime = function(n, rateParameter) { return(sapply(1:n,function(i) -log(1.0 - runif(1)) / rateParameter)) } # Randomly calculate message interarrivals using Poisson processes messages = data.table("Interarrival" = nextTime(1000,1/10)) # Sum up interarrivals to get timestamps for each message messages[,Timestamp:=cumsum(Interarrival)] # Assigning each message a constant service time. You could use a distribution here serviceTime=5 messages[,serviceTime := serviceTime] # Lets randomly increase the service time for some of the messages to simulate jitter messages[runif(n=10, min=0, max=.N),serviceTime := runif(n=.N, min=90, max=100)] messages[,responseTime := calculateResponseTime(Timestamp, serviceTime)] ggplot(messages, aes(x=Timestamp, y=responseTime))+ geom_point(color="cornflowerblue")+ gtheme()+ ylab("Response Time")+ scale_y_continuous(breaks=number_ticks(10), limits=c(0,150)) ggplot(messages, aes(x=responseTime))+ stat_ecdf(color="cornflowerblue")+ gtheme()+ ylab("Percentile")+ xlab("Response Time")+ scale_y_continuous(breaks=number_ticks(10))+ scale_x_continuous(breaks=number_ticks(10)) # Calculate the latency difference between each message messages[order(Timestamp), latencyDiff:=c(0,diff(responseTime))] ggplot(messages[latencyDiff>0], aes(x=latencyDiff)) + stat_ecdf()+ gtheme()+ coord_cartesian(ylim=c(0.8,1))+ ylab("Percentile")+ xlab("Latency Delta")+ scale_y_continuous(breaks=number_ticks(10))+ scale_x_continuous(breaks=number_ticks(10)) # Identify all messages having "high" latency messages[,highLatency := responseTime > 25] # Identify contiguous sets of high latency messages using a run length encoding (see data.table ?rleid) messages[,burstIdx := rleid(highLatency)] # Mark messages which participated in a burst that contained an abnormal latencyDiff (service time). # Max latency diff should in theory be the service time, given two messages arriving at exactly the same time messages[,`Caused by Jitter` := max(latencyDiff, na.rm=T) > serviceTime,by=burstIdx] ggplot(messages, aes(x=responseTime, color=`Caused by Jitter`)) + stat_ecdf()+ gtheme()+ ylab("Percentile")+ xlab("Response Time")+ scale_y_continuous(breaks=number_ticks(10))+ scale_x_continuous(breaks=number_ticks(10))+ scale_color_manual(values=c('cornflowerblue', 'green4')) #filter to only high latency messages highLatencyMessages = messages[highLatency == TRUE]
(** This file is a part of a formalisation of a subset of Core Erlang. We prove the reflexivity and compatibility of the logical relations. *) Require Export LogRel. Import ListNotations. Lemma Vrel_Var_compat : forall Γ n, n < Γ -> Vrel_open Γ (EVar n) (EVar n). Proof. unfold Vrel_open, Grel. intros. destruct H0, H1. simpl subst. specialize (H2 n H). repeat break_match_hyp; auto; contradiction. Qed. Global Hint Resolve Vrel_Var_compat : core. Lemma Vrel_FunId_compat : forall Γ n, n < Γ -> Vrel_open Γ (EFunId n) (EFunId n). Proof. unfold Vrel_open, Grel. intros. destruct H0, H1. simpl subst. specialize (H2 n H). repeat break_match_hyp; auto; contradiction. Qed. Global Hint Resolve Vrel_FunId_compat : core. Lemma Vrel_Lit_compat_closed : forall m l, Vrel m (ELit l) (ELit l). Proof. intros. rewrite Vrel_Fix_eq. unfold Vrel_rec. repeat constructor. Qed. Global Hint Resolve Vrel_Lit_compat_closed : core. Lemma Vrel_Lit_compat : forall Γ l, Vrel_open Γ (ELit l) (ELit l). Proof. unfold Vrel_open. intros. simpl. auto. Qed. Global Hint Resolve Vrel_Lit_compat : core. Lemma Vrel_Pid_compat_closed : forall m p, Vrel m (EPid p) (EPid p). Proof. intros. rewrite Vrel_Fix_eq. unfold Vrel_rec. repeat constructor. Qed. Global Hint Resolve Vrel_Pid_compat_closed : core. Lemma Vrel_Pid_compat : forall Γ p, Vrel_open Γ (EPid p) (EPid p). Proof. unfold Vrel_open. intros. simpl. auto. Qed. Global Hint Resolve Vrel_Pid_compat : core. Lemma Vrel_Nil_compat_closed: forall m, Vrel m ENil ENil. Proof. split; constructor; constructor. Qed. Global Hint Resolve Vrel_Nil_compat_closed : core. Lemma Vrel_Nil_compat : forall Γ, Vrel_open Γ ENil ENil. Proof. unfold Vrel_open. intros. simpl. auto. Qed. Global Hint Resolve Vrel_Nil_compat : core. Lemma Vrel_Cons_compat_closed : forall m v1 v1' v2 v2', Vrel m v1 v1' -> Vrel m v2 v2' -> Vrel m (VCons v1 v2) (VCons v1' v2'). Proof. intros. rewrite Vrel_Fix_eq. split. 2: split. 1-2: constructor. * apply Vrel_closed in H. apply H. * apply Vrel_closed in H0. apply H0. * apply Vrel_closed in H. apply H. * apply Vrel_closed in H0. apply H0. * intros. rewrite Vrel_Fix_eq in H. rewrite Vrel_Fix_eq in H0. split; [apply H | apply H0]. Unshelve. all: lia. Qed. Global Hint Resolve Vrel_Cons_compat_closed : core. Lemma Vrel_Cons_compat : forall Γ v1 v1' v2 v2', Vrel_open Γ v1 v1' -> Vrel_open Γ v2 v2' -> Vrel_open Γ (VCons v1 v2) (VCons v1' v2'). Proof. intros. unfold Vrel_open. intros. simpl. apply Vrel_Cons_compat_closed; [apply H | apply H0]; auto. Qed. Global Hint Resolve Vrel_Cons_compat : core. Lemma Vrel_Fun_compat : forall Γ vl1 vl2 b1 b2, length vl1 = length vl2 -> Erel_open (S (length vl1) + Γ) b1 b2 -> Vrel_open Γ (EFun vl1 b1) (EFun vl2 b2). Proof. intros. unfold Vrel_open. induction n using lt_wf_ind. intros. assert (forall m : nat, m < n -> forall ξ₁ ξ₂ : Substitution, Grel m Γ ξ₁ ξ₂ -> Vrel m (EFun vl1 b1).[ξ₁] (EFun vl2 b2).[ξ₂]) as IH. auto. clear H1. inversion H2 as [? [? ?] ]. simpl. rewrite Vrel_Fix_eq. unfold Vrel_rec at 1. intuition idtac. - constructor. rewrite Nat.add_0_r. eapply Erel_open_scope in H0. destruct H0. eapply subst_preserves_scope_exp in H0. exact H0. replace (S (length vl1)) with (S (length vl1) + 0) at 2 by lia. fold_upn. eapply upn_scope. auto. - constructor. rewrite Nat.add_0_r. eapply Erel_open_scope in H0. destruct H0. rewrite H in H5. eapply subst_preserves_scope_exp in H5. exact H5. replace (S (length vl2)) with (S (length vl2) + 0) at 2 by lia. fold_upn. eapply upn_scope. auto. - break_match_goal. 2: { apply Nat.eqb_neq in Heqb. congruence. } + intros. unfold Erel_open, Erel in H0. do 2 rewrite subst_comp. epose proof (nH0 := H0 m _ _ _). destruct nH0 as [nCl1 [nCl2 nH0]]. split. 2: split. exact nCl1. exact nCl2. intros. eapply nH0. 3: exact H9. lia. auto. Unshelve. split. 2: split. 1-2: fold_upn; rewrite subst_list_extend; auto. 1: rewrite <- H5. 2: apply Nat.eqb_eq in Heqb; rewrite <- Heqb in H6; rewrite <- H6. * replace (S (Datatypes.length vals1)) with (length (EFun vl1 b1.[upn (S (Datatypes.length vals1)) ξ₁] :: vals1)) by auto. apply scoped_list_subscoped; auto. apply biforall_vrel_closed in H7. constructor. 2: apply H7; auto. simpl. epose (IH m Hmn ξ₁ ξ₂ _). apply Vrel_closed_l in v. simpl in v. rewrite H5. exact v. * simpl. lia. * apply Nat.eqb_eq in Heqb. repeat rewrite <- H6, <- H5. replace (S (Datatypes.length vals1)) with (length (EFun vl2 b2.[upn (S (Datatypes.length vals2)) ξ₂] :: vals2)). 2: simpl; lia. apply scoped_list_subscoped; auto. apply biforall_vrel_closed in H7. constructor. 2: apply H7; auto. simpl. epose (IH m Hmn ξ₁ ξ₂ _). apply Vrel_closed_r in v. simpl in v. rewrite H6. exact v. * simpl. lia. * do 2 fold_upn. rewrite subst_list_extend, subst_list_extend; auto. intros. destruct x; simpl. ** apply IH; auto. eapply Grel_downclosed. eauto. ** pose (list_subst_get_possibilities x vals1 ξ₁). pose (list_subst_get_possibilities x vals2 ξ₂). assert (length vals1 = length vals2). { lia. } rewrite H9 in *. destruct o, o0, H10, H11; try lia. -- rewrite H10, H11. apply indexed_to_biforall. exact H7. lia. -- rewrite H10, H11. specialize (H4 (x - length vals2)). repeat break_match_goal; auto. eapply Vrel_downclosed. all: apply H4; lia. ** simpl. auto. ** simpl. auto. Unshelve. 1-2: eapply Grel_downclosed; eauto. 1-2: lia. Unshelve. 1-2: lia. Qed. Global Hint Resolve Vrel_Fun_compat : core. Ltac unfold_hyps := match goal with | [ H: exists _, _ |- _] => destruct H | [ H: _ /\ _ |- _] => destruct H end. Lemma Erel_Val_compat_closed : forall {n v v'}, Vrel n v v' -> Erel n v v'. Proof. intros. unfold Erel, exp_rel. pose proof (Vrel_possibilities H). intuition eauto. * do 2 unfold_hyps. subst. destruct H0, H1. eapply H3; eauto. * do 2 unfold_hyps. subst. destruct H1, H1. eapply H3; eauto. * do 5 unfold_hyps. subst. destruct H0, H1. subst. eapply H3; eauto. eapply Vrel_downclosed. eauto. * destruct H1, H3. eapply H4; eauto. eapply Vrel_downclosed. eauto. * subst. destruct H0, H1. eapply H2. 3: exact H3. lia. apply Vrel_Nil_compat_closed. Unshelve. all: auto. Qed. Global Hint Resolve Erel_Val_compat_closed : core. Lemma Erel_Val_compat : forall {Γ v v'}, Vrel_open Γ v v' -> Erel_open Γ v v'. Proof. intros. unfold Erel_open, Vrel_open in *. auto. Qed. Global Hint Resolve Erel_Val_compat : core. Lemma Vrel_open_Erel_open : forall Γ v v', Vrel_open Γ v v' -> Erel_open Γ v v'. Proof. eauto. Qed. Global Hint Resolve Vrel_open_Erel_open : core. Lemma match_pattern_Vrel : forall p v1 v2 n, Vrel n v1 v2 -> (forall l1, (match_pattern p v1 = Some l1 -> exists l2, match_pattern p v2 = Some l2 /\ list_biforall (Vrel n) l1 l2)). Proof. intros. assert (VALCLOSED v1) by (eapply Vrel_closed in H; apply H). assert (VALCLOSED v2) by (eapply Vrel_closed in H; apply H). generalize dependent v2. revert n. generalize dependent v1. revert l1. generalize dependent p. induction p; destruct v1, v2; intros; try inversion_is_value; rewrite Vrel_Fix_eq in H; destruct H as [Cl1 [Cl2 H]]; try contradiction; simpl in H0; try congruence. * break_match_hyp. 2: congruence. inversion H0. subst. exists []. split. apply lit_eqb_eq in Heqb. subst. simpl. rewrite lit_eqb_refl. auto. constructor. * break_match_hyp. 2: congruence. inversion H0. subst. exists []. split. apply Nat.eqb_eq in Heqb. subst. simpl. rewrite Nat.eqb_refl. auto. constructor. * inversion H0. subst. exists [ELit l0]. simpl. split; constructor. rewrite Vrel_Fix_eq. simpl; auto. constructor. * subst. inversion H0. subst. exists [EPid p0]. split; constructor. apply Vrel_Pid_compat_closed. constructor. * inversion H0. subst. exists [EFun vl0 v2]; simpl; split; auto. constructor. 2: constructor. rewrite Vrel_Fix_eq; simpl; auto. * inversion H0; subst. exists [ENil]; split; auto. constructor. 2: constructor. apply Vrel_Nil_compat_closed. * inversion H0. subst. exists [VCons v2_1 v2_2]; split; auto. constructor. 2: constructor. rewrite Vrel_Fix_eq; simpl; auto. * inversion H0. subst. exists []. split; auto. constructor. * inversion Cl1. inversion Cl2. subst. destruct H. rewrite <- Vrel_Fix_eq in H. rewrite <- Vrel_Fix_eq in H3. break_match_hyp; try congruence. break_match_hyp; try congruence. inversion H0. subst. apply (IHp1 l) in H. apply (IHp2 l0) in H3. all: auto. destruct H as [l11 [Hb Hbif]]. destruct H3 as [l12 [Hb2 Hbif2]]. exists (l11 ++ l12). split; simpl. now rewrite Hb, Hb2. apply biforall_app; auto. Qed. Lemma nomatch_pattern_Vrel : forall p v1 v2 n, Vrel n v1 v2 -> match_pattern p v1 = None -> match_pattern p v2 = None. Proof. intros. assert (VALCLOSED v1) by (eapply Vrel_closed in H; apply H). assert (VALCLOSED v2) by (eapply Vrel_closed in H; apply H). generalize dependent v2. revert n. generalize dependent v1. induction p; destruct v1, v2; intros; try inversion_is_value; rewrite Vrel_Fix_eq in H; destruct H as [Cl1 [Cl2 H]]; try contradiction; simpl in H0; try congruence; auto. * break_match_hyp. congruence. simpl. subst. now rewrite Heqb. * break_match_hyp. congruence. simpl. subst. now rewrite Heqb. * inversion Cl1. inversion Cl2. subst. destruct H. rewrite <- Vrel_Fix_eq in H. rewrite <- Vrel_Fix_eq in H3. break_match_hyp; try congruence. break_match_hyp; try congruence. - simpl. eapply IHp2 in Heqo0. 3: exact H3. all: auto. rewrite Heqo0. break_match_goal; auto. - simpl. eapply IHp1 in Heqo. 3: exact H. all: auto. rewrite Heqo; auto. Qed. Lemma Erel_Case_compat_closed : forall n e1 e2 e1' e2' e3 e3' p, Erel n e1 e1' -> EXP pat_vars p ⊢ e2 -> EXP pat_vars p ⊢ e2' -> (forall m (Hmn : m <= n) vl vl', length vl = pat_vars p -> list_biforall (Vrel m) vl vl' -> Erel m e2.[list_subst vl idsubst ] e2'.[list_subst vl' idsubst]) -> Erel n e3 e3' -> Erel n (ECase e1 p e2 e3) (ECase e1' p e2' e3'). Proof. intros. destruct H, H3, H4, H5. split. 2: split. 1-2: constructor; auto. 1-2: now rewrite Nat.add_0_r. intros. destruct H8, H10. inversion H9; subst; try inversion_is_value. epose proof (H6 k _ (FCase p e2 e3 ::F1) (FCase p e2' e3' ::F2) _ H18) as T. destruct T. exists (S x). constructor. auto. Unshelve. lia. split. 2: split. 1-2: constructor; auto; now constructor. intros. assert (VALCLOSED v1) by (apply Vrel_closed in H12; apply H12). inversion H13; subst; try inversion_is_value. * eapply match_pattern_Vrel in H23 as H23_2. 2: exact H12. destruct H23_2 as [l2 [M2 Bif]]. inversion H13; subst; try inversion_is_value. 2: congruence. rewrite H26 in H23. inversion H23. subst. apply match_pattern_length in H26 as H26_2. eapply biforall_impl in Bif. 2: intros; eapply Vrel_downclosed; exact H15. specialize (H2 k0 ltac:(lia) l l2 (eq_sym H26_2) Bif). destruct H2 as [Cl1 [Cl2 H2]]. eapply H2 in H27. destruct H27. exists (S x). eapply term_case_true; eauto. lia. split. 2: split. all: auto. intros. eapply H11. 3: exact H16. lia. auto. * eapply nomatch_pattern_Vrel in H23 as H23_2. 2: exact H12. inversion H13; subst; try inversion_is_value. congruence. eapply H7 in H24. destruct H24. exists (S x). apply term_case_false; eauto. lia. split. 2: split. all: auto. intros. eapply H11. 3: exact H16. lia. auto. Unshelve. lia. Qed. Lemma Erel_Var_compat : forall Γ n, n < Γ -> Erel_open Γ (EVar n) (EVar n). Proof. auto. Qed. Global Hint Resolve Erel_Var_compat : core. Lemma Erel_FunId_compat : forall Γ n, n < Γ -> Erel_open Γ (EFunId n) (EFunId n). Proof. auto. Qed. Global Hint Resolve Erel_FunId_compat : core. Lemma Erel_Lit_compat : forall Γ l, Erel_open Γ (ELit l) (ELit l). Proof. auto. Qed. Global Hint Resolve Erel_Lit_compat : core. Lemma Erel_Fun_compat : forall Γ (vl vl' : list Var) b b', length vl = length vl' -> Erel_open (S (length vl) + Γ) b b' -> Erel_open Γ (EFun vl b) (EFun vl' b'). Proof. auto. Qed. Global Hint Resolve Erel_Fun_compat : core. Lemma Erel_Let_compat_closed : forall n x y (e2 e2' : Exp), (forall m (Hmn : m <= n) v2 v2', Vrel m v2 v2' -> Erel m e2.[v2/] e2'.[v2'/]) -> forall m (Hmn : m <= n) e1 e1', Erel m e1 e1' -> Erel m (ELet x e1 e2) (ELet y e1' e2'). Proof. intros. destruct (Erel_closed H0) as [IsClosed_e1 IsClosed_e2]. unfold Erel, exp_rel. specialize (H 0 ltac:(lia) (ELit 0%Z) (ELit 0%Z) (Vrel_Lit_compat_closed 0 0%Z)) as H'. split. 2: split. * apply Erel_closed_l in H'. constructor; auto. apply subst_implies_scope_exp_1; auto. * apply Erel_closed_r in H'. constructor; auto. apply subst_implies_scope_exp_1; auto. * intros. destruct m0; inversion H2; try inversion_is_value. subst. destruct H0, H3. eapply H4 in H5. destruct H5. exists (S x0). constructor. exact H5. lia. apply Erel_closed_l in H' as e1H. apply subst_implies_scope_exp_1 in e1H. apply Erel_closed_r, subst_implies_scope_exp_1 in H' as e2H. destruct H1, H6. split. 2: split. 1-2: constructor; auto; now constructor. intros. assert (VALCLOSED v1) by (apply Vrel_closed in H8; apply H8). assert (VALCLOSED v2) by (apply Vrel_closed in H8; apply H8). inversion H9; subst. 2-6: inversion H10. eapply H in H18. destruct H18. exists (S x0). constructor. auto. exact H12. 2: exact H8. lia. lia. split. 2: split. all: auto. intros. eapply H7. 3: exact H15. lia. auto. inversion_is_value. Qed. Global Hint Resolve Erel_Let_compat_closed : core. Lemma Erel_Let_compat : forall Γ x x' (e1 e1' e2 e2': Exp), Erel_open Γ e1 e1' -> Erel_open (S Γ) e2 e2' -> Erel_open Γ (ELet x e1 e2) (ELet x' e1' e2'). Proof. intros. unfold Erel_open. intros. cbn. eapply Erel_Let_compat_closed; auto. intros. do 2 rewrite subst_comp, substcomp_scons, substcomp_id_r. apply H0. apply Vrel_closed in H2 as v. destruct v. split. 2: split. 1-2: intro; intros; destruct v; cbn; auto; apply H1; lia. intros. destruct x0; auto. simpl. destruct H1, H6. specialize (H7 x0 ltac:(lia)). break_match_goal. break_match_goal; auto. eapply Vrel_downclosed; eauto. lia. Unshelve. lia. Qed. Global Hint Resolve Erel_Let_compat : core. Lemma Erel_LetRec_compat_closed : forall n f1 f2 vl1 vl2 (b b' e e' : Exp) m (Hmn : m <= n) (CL1 : EXP S (length vl1) ⊢ b) (CL1 : EXP S (length vl2) ⊢ b') (CL1 : EXP 1 ⊢ e) (CL1 : EXP 1 ⊢ e'), Erel m e.[EFun vl1 b/] e'.[EFun vl2 b'/] -> Erel m (ELetRec f1 vl1 b e) (ELetRec f2 vl2 b' e'). Proof. intros. unfold Erel, exp_rel. split. 2: split. * constructor. rewrite Nat.add_0_r. auto. auto. * constructor. rewrite Nat.add_0_r. auto. auto. * intros. inversion H1; try inversion_is_value. subst. destruct H0, H2. eapply H in H8. destruct H8. exists (S x). constructor. exact H4. lia. split. 2: split. all: auto. intros. eapply H3 in H7. exact H7. lia. auto. Qed. Global Hint Resolve Erel_LetRec_compat_closed : core. Lemma Erel_LetRec_compat : forall Γ f1 f2 vl1 vl2 (e1 e1' e2 e2': Exp), length vl1 = length vl2 -> Erel_open (S (length vl1) + Γ) e1 e1' -> Erel_open (S Γ) e2 e2' -> Erel_open Γ (ELetRec f1 vl1 e1 e2) (ELetRec f2 vl2 e1' e2'). Proof. intros. unfold Erel_open. intros. cbn. apply Erel_open_scope in H0 as e1CL. apply Erel_open_scope in H1 as e2CL. assert (EXP S (length vl1) ⊢ e1.[upn (S (length vl1)) ξ₁]) as E1SC. { destruct e1CL, e2CL. pose (subst_preserves_scope_exp). pose (i e1 (S (length vl1) + Γ)) as HH. destruct HH. clear H8. apply (H7 H3 (S (length vl1)) (upn (S (length vl1)) ξ₁)). replace (S (length vl1)) with (S (length vl1) + 0) at 2 by lia. apply upn_scope. apply H2. } assert (EXP S (length vl2) ⊢ e1'.[upn (S (length vl2)) ξ₂]) as E1'SC. { destruct e1CL, e2CL. pose (subst_preserves_scope_exp). pose (i e1' (S (length vl2) + Γ)) as HH. destruct HH. clear H8. rewrite H in H4. apply (H7 H4 (S (length vl2)) (upn (S (length vl2)) ξ₂)). replace (S (length vl2)) with (S (length vl2) + 0) at 2 by lia. apply upn_scope. apply H2. } assert (EXP 1 ⊢ e2.[up_subst ξ₁]) as E2SC. { destruct e1CL, e2CL. pose (subst_preserves_scope_exp). pose (i e2 (S Γ)) as HH. destruct HH. clear H8. apply (H7 H5 1 (up_subst ξ₁)). replace 1 with (1 + 0) by lia. apply up_scope. apply H2. } assert (EXP 1 ⊢ e2'.[up_subst ξ₂]) as E2'SC. { destruct e1CL, e2CL. pose (subst_preserves_scope_exp). pose (i e2' (S Γ)) as HH. destruct HH. clear H8. apply (H7 H6 1 (up_subst ξ₂)). replace 1 with (1 + 0) by lia. apply up_scope. apply H2. } eapply Erel_LetRec_compat_closed; auto. * intros. do 2 rewrite subst_comp, substcomp_scons, substcomp_id_r. apply H1. inversion H2. destruct H4. split. 2: split. - intro. intros. destruct v; simpl. + eapply Vrel_Fun_compat, Erel_Val_compat, Erel_open_closed in H0. 2: exact H3. 2: auto. destruct H0. inversion H0. simpl in H8. exact H8. + apply H2. lia. - intro. intros. destruct v; simpl. + rewrite H in H0. eapply Vrel_Fun_compat, Erel_Val_compat, Erel_open_closed in H0. 2: exact H4. 2: auto. destruct H0. inversion H7. simpl in H8. exact H8. + apply H4. lia. - intros. destruct x. + simpl. eapply Vrel_Fun_compat; eauto. + simpl. specialize (H5 x ltac:(lia)). break_match_goal. break_match_goal. all: try lia. eapply Vrel_downclosed; eauto. Unshelve. lia. Qed. Global Hint Resolve Erel_LetRec_compat : core. Lemma Erel_Cons_compat_closed : forall m e1 e1' e2 e2', Erel m e1 e1' -> Erel m e2 e2' -> Erel m (ECons e1 e2) (ECons e1' e2'). Proof. intros. destruct H, H0, H1, H2. split. 2: split. 1-2: constructor; auto. intros. destruct H5, H7. destruct m0. inversion H6. inversion H9. inversion H6; try inversion_is_value. subst. epose (H4 m0 _ (FCons1 e1 ::F1) (FCons1 e1' ::F2) _ H11). destruct t. exists (S x). constructor. auto. Unshelve. lia. split. 2: split. 1-2: constructor; auto; constructor; auto. intros. assert (VALCLOSED v1) by (apply Vrel_closed in H9; apply H9). inversion H10; subst; try inversion_is_value. epose (H3 k _ (FCons2 v1 :: F1) (FCons2 v2 :: F2) _ H18). destruct t. exists (S x). econstructor; eauto. Unshelve. lia. split. 2: split. 1-2: constructor; apply Vrel_closed in H9; destruct H9; auto; constructor; auto. intros. assert (VALCLOSED v0) by (apply Vrel_closed in H13; apply H13). inversion H14; subst; try inversion_is_value. eapply H8 in H24. destruct H24. exists (S x). constructor; eauto. lia. eapply Vrel_Cons_compat_closed. eapply Vrel_downclosed. eassumption. eapply Vrel_downclosed. eassumption. Unshelve. all: lia. Qed. Global Hint Resolve Erel_Cons_compat_closed : core. Lemma Erel_Cons_compat : forall Γ v1 v1' v2 v2', Erel_open Γ v1 v1' -> Erel_open Γ v2 v2' -> Erel_open Γ (ECons v1 v2) (ECons v1' v2'). Proof. unfold Erel_open. intros. simpl. apply Erel_Cons_compat_closed; [apply H | apply H0]; auto. Qed. Global Hint Resolve Erel_Cons_compat : core. Lemma Vrel_Fun_right : forall m v2 vl b, Vrel m (EFun vl b) v2 -> exists b' vl', length vl = length vl' /\ v2 = EFun vl' b'. Proof. intros. rewrite Vrel_Fix_eq in H. destruct H, H0. destruct v2; try contradiction. break_match_hyp. apply Nat.eqb_eq in Heqb0. 2: contradiction. do 2 eexists. split; eauto. Qed. Lemma Erel_App_compat_ind : forall hds hds' tl tl' F1 F2 k0 v1 v2 (* P1 P1' P2 P2' *), list_biforall (Erel k0) hds hds' -> list_biforall (Vrel k0) tl tl' -> Vrel k0 v1 v2 -> FSCLOSED F1 -> FSCLOSED F2 -> (forall m : nat, m <= k0 -> forall v1 v2 : Exp, Vrel m v1 v2 -> | F1, v1 | m ↓ -> | F2, v2 | ↓) -> frame_rel k0 (fun (m' : nat) (_ : m' <= k0) => Vrel m') (FApp2 v1 (* P1 *) hds tl (* P2 *) :: F1) (FApp2 v2 (* P1' *) hds' tl' (* P2' *) :: F2). Proof. induction hds; intros. * inversion H. subst. apply biforall_length in H0 as LEN. assert (list_biforall (Vrel k0) tl tl') as BF by auto. apply biforall_vrel_closed in H0 as [H0_1 H0_2]. split. 2: split. 1-2: constructor; auto; constructor; auto; apply Vrel_closed in H1; apply H1. intros. inversion H5; subst. - inversion H0. inversion H7. - apply Vrel_Fun_right in H1 as v; destruct v as [e1 [vl1 [? ?]]]. subst. rewrite Vrel_Fix_eq in H1. destruct H1 as [VCL1 [VCL2 H1]]. rewrite H6, Nat.eqb_refl in H1. epose proof (H1 k _ (tl ++ [v0]) (tl' ++ [v3]) _ _ _) as E. destruct E as [E1CL [E2CL ?]]. eapply H7 in H14. destruct H14. exists (S x). constructor. + exact H0_2. + lia. + apply Vrel_closed in H0; apply H0. + exact H8. + lia. + split. 2: split. all: auto. intros. eapply H4 in H11. exact H11. lia. auto. - inversion H0. inversion H7. - inversion H0. inversion H7. - inversion H0. inversion H7. - inversion H0. inversion H7. - inversion H0. inversion H7. * inversion H. subst. apply biforall_length in H0 as LEN. apply biforall_vrel_closed in H0 as v. destruct v. apply biforall_erel_closed in H as v. destruct v. apply Vrel_closed in H1 as v. destruct v. split. 2: split. 1-2: constructor; auto; now constructor. intros. inversion H14; subst. - inversion H13. inversion H16. - eapply H7 in H24. destruct H24. exists (S x). econstructor; auto. apply Vrel_closed in H13; apply H13. exact H15. lia. apply IHhds; auto. + inversion H. eapply biforall_impl in H25. exact H25. intros. eapply Erel_downclosed; eauto. + apply biforall_app. eapply biforall_impl in H0. exact H0. intros. eapply Vrel_downclosed; eauto. constructor. 2: constructor. eapply Vrel_downclosed; eauto. + eapply Vrel_downclosed; eauto. + intros. eapply H4 in H19. exact H19. lia. auto. - inversion H13. inversion H16. - inversion H13. inversion H16. - inversion H13. inversion H16. - inversion H13. inversion H16. - inversion H13. inversion H16. Unshelve. all: auto; try lia. ** rewrite app_length. simpl. lia. ** rewrite app_length. simpl. lia. ** apply biforall_app. -- eapply biforall_impl in BF. exact BF. intros. eapply Vrel_downclosed; eauto. -- constructor. eapply Vrel_downclosed. eauto. constructor. Unshelve. all: lia. Qed. Lemma Erel_App_compat_helper : forall es es' k F1 F2 (FCL1 : FSCLOSED F1) (FCL2 : FSCLOSED F2), (forall m : nat, m <= S k -> forall v1 v2 : Exp, Vrel m v1 v2 -> | F1, v1 | m ↓ -> | F2, v2 | ↓) -> list_biforall (Erel k) es es' -> forall m, m <= k -> forall v1 v2 : Exp, Vrel m v1 v2 -> | FApp1 es :: F1, v1 | m ↓ -> | FApp1 es' :: F2, v2 | ↓. Proof. destruct es; intros. * apply biforall_length in H0 as L. apply eq_sym, length_zero_iff_nil in L. subst. apply Vrel_closed in H2 as H2'. destruct H2' as [H2'1 H2'2]. inversion H3; subst; try inversion_is_value. - apply Vrel_Fun_right in H2 as v; destruct v as [e1 [vl1 [? ?]]]. apply eq_sym, length_zero_iff_nil in H4. subst. rewrite Vrel_Fix_eq in H2. destruct H2 as [VCL1 [VCL2 ?]]. rewrite Nat.eqb_refl in H2. specialize (H2 k0 ltac:(lia) [] [] (eq_refl _) (eq_refl _) ltac:(constructor)). simpl in H2. destruct H2 as [ECL1 [ECL2 ?]]. eapply H2 in H5. destruct H5. exists (S x). constructor. eauto. lia. split. 2: split. all: auto. intros. eapply H. 2: exact H4. lia. auto. * inversion H3; subst. - inversion H2. inversion H5. - inversion H0. subst. destruct H6 as [ECL1 [ECL2 ?]]. eapply H4 in H10. destruct H10. exists (S x). econstructor. apply Vrel_closed in H2; apply H2. exact H5. lia. apply Vrel_closed in H2 as v. destruct v. eapply Erel_App_compat_ind; auto. + eapply biforall_impl in H8; eauto. intros. eapply Erel_downclosed; eauto. + constructor. + eapply Vrel_downclosed; eauto. + intros. eapply H in H12; eauto. lia. - inversion H2. inversion H5. - inversion H2. inversion H5. - inversion H2. inversion H5. - inversion H2. inversion H5. - inversion H2. inversion_is_value. Unshelve. auto. all: lia. Qed. Lemma Erel_App_compat_closed : forall n e es e' es', Erel n e e' -> list_biforall (Erel n) es es' -> Erel n (EApp e es) (EApp e' es'). Proof. intros. destruct H, H1. split. 2: split. 1-2: constructor; auto; rewrite <- indexed_to_forall; apply biforall_erel_closed in H0; apply H0. (* eval e *) intros. inversion H4; try inversion_is_value. subst. intros. eapply H2 in H9. destruct H9. exists (S x). constructor. exact H5. lia. destruct H3, H5. split. 2: split. 1-2: constructor; auto. 1-2: constructor; apply biforall_erel_closed in H0; apply H0. (* eval es *) intros. eapply Erel_App_compat_helper in H8. exact H8. all: auto. intros. eapply H6 in H12; eauto. lia. eapply biforall_impl in H0. exact H0. intros. eapply Erel_downclosed; eauto. Unshelve. lia. Qed. Global Hint Resolve Erel_App_compat_closed : core. Lemma Erel_App_compat : forall Γ e es e' es', Erel_open Γ e e' -> list_biforall (Erel_open Γ) es es' -> Erel_open Γ (EApp e es) (EApp e' es'). Proof. intros. unfold Erel_open. intros. cbn. eapply Erel_App_compat_closed; auto. eapply biforall_map; eauto. Qed. Global Hint Resolve Erel_App_compat : core. Lemma Erel_Case_compat : forall Γ e1 e2 e1' e2' e3 e3' p, Erel_open Γ e1 e1' -> Erel_open (pat_vars p + Γ) e2 e2' -> Erel_open Γ e3 e3' -> Erel_open Γ (ECase e1 p e2 e3) (ECase e1' p e2' e3'). Proof. intros. unfold Erel_open. intros. cbn. eapply Erel_Case_compat_closed; auto. * apply Erel_open_scope_l in H0. apply -> subst_preserves_scope_exp. exact H0. rewrite <- (Nat.add_0_r (pat_vars p)) at 2. apply upn_scope. apply H2. * apply Erel_open_scope_r in H0. apply -> subst_preserves_scope_exp. exact H0. rewrite <- (Nat.add_0_r (pat_vars p)) at 2. apply upn_scope. apply H2. * intros. rewrite <- H3. apply biforall_length in H4 as H4'. rewrite subst_comp, substcomp_list, substcomp_id_r. rewrite H4'. rewrite subst_comp, substcomp_list, substcomp_id_r. apply H0. rewrite <- H3. apply Grel_list; auto. eapply Grel_downclosed. exact H2. Unshelve. lia. Qed. Global Hint Resolve Erel_Case_compat : core. Lemma Erel_BIF_compat_ind : forall hds hds' tl tl' F1 F2 k0 v1 v2 (* P1 P1' P2 P2' *), list_biforall (Erel k0) hds hds' -> list_biforall (Vrel k0) tl tl' -> Vrel k0 v1 v2 -> FSCLOSED F1 -> FSCLOSED F2 -> (forall m : nat, m <= k0 -> forall v1 v2 : Exp, Vrel m v1 v2 -> | F1, v1 | m ↓ -> | F2, v2 | ↓) -> frame_rel k0 (fun (m' : nat) (_ : m' <= k0) => Vrel m') (FBIF2 v1 (* P1 *) hds tl (* P2 *) :: F1) (FBIF2 v2 (* P1' *) hds' tl' (* P2' *) :: F2). Proof. induction hds; intros. * inversion H. subst. apply biforall_length in H0 as LEN. assert (list_biforall (Vrel k0) tl tl') as BF by auto. apply biforall_vrel_closed in H0 as [H0_1 H0_2]. split. 2: split. 1-2: constructor; auto; constructor; auto; apply Vrel_closed in H1; apply H1. intros. apply Vrel_closed in H0 as H0'. destruct H0' as [H0'1 H0'2]. inversion H5; subst; try inversion_is_value. rewrite Vrel_Fix_eq in H1. destruct H1 as [VCL1 [VCL2 H1]]. destruct v2; subst; try contradiction. rewrite Vrel_Fix_eq in H0. destruct H0 as [VCL3 [VCL4 H0]]. destruct v3; subst; try contradiction. apply element_exist in LEN as EE. destruct EE as [fs [ls eq]]. subst. simpl in LEN. inversion LEN. apply eq_sym, length_zero_iff_nil in H1. subst. clear LEN. inversion BF; subst. rewrite Vrel_Fix_eq in H7. destruct H7 as [VCL5 [VCL6 H7]]. destruct fs; subst; try contradiction. eapply H4 in H11 as [x H0]. exists (S x). constructor. exact H0. lia. apply Vrel_Lit_compat_closed. * inversion H. subst. apply biforall_length in H0 as LEN. apply biforall_vrel_closed in H0 as v. destruct v. apply biforall_erel_closed in H as v. destruct v. apply Vrel_closed in H1 as v. destruct v. split. 2: split. 1-2: constructor; auto; now constructor. intros. inversion H14; subst. - inversion H13. inversion H16. - eapply H7 in H24. destruct H24. exists (S x). econstructor; auto. apply Vrel_closed in H13; apply H13. exact H15. lia. apply IHhds; auto. + inversion H. eapply biforall_impl in H25. exact H25. intros. eapply Erel_downclosed; eauto. + apply biforall_app. eapply biforall_impl in H0. exact H0. intros. eapply Vrel_downclosed; eauto. constructor. 2: constructor. eapply Vrel_downclosed; eauto. + eapply Vrel_downclosed; eauto. + intros. eapply H4 in H19. exact H19. lia. auto. - inversion H13. inversion H16. - inversion H13. inversion H16. - inversion H13. inversion H16. - inversion H13. inversion H16. - inversion H13. inversion H16. Unshelve. all: auto; try lia. Qed. Lemma Erel_BIF_compat_helper : forall es es' k F1 F2 (FCL1 : FSCLOSED F1) (FCL2 : FSCLOSED F2), (forall m : nat, m <= S k -> forall v1 v2 : Exp, Vrel m v1 v2 -> | F1, v1 | m ↓ -> | F2, v2 | ↓) -> list_biforall (Erel k) es es' -> forall m, m <= k -> forall v1 v2 : Exp, Vrel m v1 v2 -> | FBIF1 es :: F1, v1 | m ↓ -> | FBIF1 es' :: F2, v2 | ↓. Proof. destruct es; intros. * apply biforall_length in H0 as L. apply eq_sym, length_zero_iff_nil in L. subst. apply Vrel_closed in H2 as H2'. destruct H2' as [H2'1 H2'2]. inversion H3; subst; try inversion_is_value. * apply Vrel_closed in H2 as H2'. destruct H2' as [H2'1 H2'2]. inversion H3; subst; try inversion_is_value. - inversion H0. subst. destruct H6 as [ECL1 [ECL2 ?]]. eapply H4 in H10. destruct H10. exists (S x). econstructor. apply Vrel_closed in H2; apply H2. exact H5. lia. apply Vrel_closed in H2 as v. destruct v. eapply Erel_BIF_compat_ind; auto. + eapply biforall_impl in H8; eauto. intros. eapply Erel_downclosed; eauto. + constructor. + eapply Vrel_downclosed; eauto. + intros. eapply H in H12; eauto. lia. Unshelve. auto. all: lia. Qed. Lemma Erel_BIF_compat_closed : forall p1 p2 es es' n, list_biforall (Erel n) es es' -> Erel n p1 p2 -> Erel n (EBIF p1 es) (EBIF p2 es'). Proof. intros. destruct H0,H1. split. 2: split. 1-2: constructor; auto. 1-2: rewrite <- indexed_to_forall; apply biforall_erel_closed in H; apply H. (* eval e *) intros. inversion H4; try inversion_is_value. subst. intros. eapply H2 in H9. destruct H9. exists (S x). constructor. exact H5. lia. destruct H3, H5. split. 2: split. 1-2: constructor; auto. 1-2: constructor; apply biforall_erel_closed in H; apply H. (* eval es *) intros. eapply Erel_BIF_compat_helper in H8. exact H8. all: auto. intros. eapply H6 in H12; eauto. lia. eapply biforall_impl in H. exact H. intros. eapply Erel_downclosed; eauto. Unshelve. lia. Qed. Lemma Erel_BIF_compat : forall p1 p2 es es' Γ, Erel_open Γ p1 p2 -> list_biforall (Erel_open Γ) es es' -> Erel_open Γ (EBIF p1 es) (EBIF p2 es'). Proof. intros. unfold Erel_open. intros. cbn. eapply Erel_BIF_compat_closed; auto. eapply biforall_map; eauto. Qed. Global Hint Resolve Erel_BIF_compat : core. (** TODO: will be changed in the future: *) Lemma Erel_Receive_compat_closed : forall l1 l2 n, (* Erel n e1 e2 -> *) EXPCLOSED (EReceive l1) -> EXPCLOSED (EReceive l2) -> Erel n (EReceive l1) (EReceive l2). Proof. intros. unfold Erel, exp_rel. split. 2: split. 1-2: auto. intros. inversion H2; subst; try inversion_is_value. Qed. (** TODO: will be changed in the future: *) Lemma Erel_Receive_compat : forall l1 l2 Γ, (* Erel_open Γ e1 e2 -> *) EXP Γ ⊢ EReceive l1 -> EXP Γ ⊢ EReceive l2 -> Erel_open Γ (EReceive l1) (EReceive l2). Proof. intros. unfold Erel_open. intros. simpl. apply Erel_Receive_compat_closed; auto. replace (EReceive (map (fun '(p, v) => (p, v.[upn (pat_vars p) ξ₁])) l1)) with ((EReceive l1).[ξ₁]) by auto. apply -> subst_preserves_scope_exp; eauto. apply H1. replace (EReceive (map (fun '(p, v) => (p, v.[upn (pat_vars p) ξ₂])) l2)) with ((EReceive l2).[ξ₂]) by auto. apply -> subst_preserves_scope_exp; eauto. apply H1. Qed. Global Hint Resolve Erel_Receive_compat : core. Theorem Erel_Vrel_Fundamental_helper : forall (e : Exp), (forall Γ, EXP Γ ⊢ e -> Erel_open Γ e e) /\ (forall Γ, VAL Γ ⊢ e -> Vrel_open Γ e e). Proof. induction e using Exp_ind2 with (Q := fun l => Forall (fun e => (forall Γ, EXP Γ ⊢ e -> Erel_open Γ e e) /\ (forall Γ, VAL Γ ⊢ e -> Vrel_open Γ e e)) l) (W := fun l => Forall (fun '(_,e) => (forall Γ, EXP Γ ⊢ e -> Erel_open Γ e e) /\ (forall Γ, VAL Γ ⊢ e -> Vrel_open Γ e e)) l); intuition auto; try inversion_is_value. * apply Erel_Val_compat, Vrel_Var_compat. inversion H. now inversion H0. * apply Vrel_Var_compat. now inversion H. * apply Erel_Val_compat, Vrel_FunId_compat. inversion H. now inversion H0. * apply Vrel_FunId_compat. now inversion H. * apply Erel_Val_compat, Vrel_Fun_compat; auto. apply H. inversion H1. now inversion H2. * apply Vrel_Fun_compat; auto. apply H. now inversion H1. * inversion H1. subst. 2: inversion H2. apply Erel_App_compat. apply H. auto. apply forall_biforall_refl. apply Forall_and_inv in IHe0. destruct IHe0. assert (Forall (fun x : Exp => Erel_open Γ x x) el). { rewrite <- indexed_to_forall in H5. clear H H0 H1 H4 H3. induction el; constructor. * inversion H2. inversion H5. subst. apply H1. auto. * inversion H2. inversion H5. subst. apply IHel; auto. } auto. * inversion H3. subst. 2: inversion H4. apply Erel_Let_compat. now apply H. now apply H1. * inversion H3. subst. 2: inversion H4. apply Erel_LetRec_compat. auto. now apply H. now apply H1. * inversion H5. subst. 2: inversion H6. apply Erel_Case_compat. now apply H. now apply H1. now apply H3. * inversion H3. subst. 2: inversion H4. apply Erel_Cons_compat. now apply H. now apply H1. * inversion H3. inversion H4. subst. apply Erel_Val_compat. apply Vrel_Cons_compat. now apply H0. now apply H2. * inversion H3. subst. apply Vrel_Cons_compat. now apply H0. now apply H2. * inversion H1. subst. 2: inversion H2. apply Erel_BIF_compat. now apply H. assert (Forall (fun x : Exp => Erel_open Γ x x) l). { rewrite <- indexed_to_forall in H5. induction l; constructor. * inversion H5. inversion IHe0. now apply H10. * inversion H5. inversion IHe0. subst. apply IHl; auto. constructor; auto. now rewrite <- indexed_to_forall. } now apply forall_biforall_refl. Qed. Theorem Erel_Fundamental : forall (e : Exp) (Γ : nat), EXP Γ ⊢ e -> Erel_open Γ e e. Proof. intros. apply Erel_Vrel_Fundamental_helper. auto. Qed. Global Hint Resolve Erel_Fundamental : core. Theorem Vrel_Fundamental : forall (v : Exp) (Γ : nat), VAL Γ ⊢ v -> Vrel_open Γ v v. Proof. intros. apply Erel_Vrel_Fundamental_helper. auto. Qed. Global Hint Resolve Vrel_Fundamental : core. Lemma Grel_ids : forall n, Grel n 0 idsubst idsubst. Proof. intros. unfold Grel. intuition auto using scope_idsubst. exfalso; auto. inversion H. Qed. Theorem Vrel_Fundamental_closed : forall (v : Exp), VALCLOSED v -> forall n, Vrel n v v. Proof. intros. replace v with (v.[idsubst]). eapply Vrel_Fundamental; eauto using Grel_ids. apply idsubst_is_id. Qed. Global Hint Resolve Vrel_Fundamental_closed : core. Theorem Erel_Fundamental_closed : forall (e : Exp), EXPCLOSED e -> forall n, Erel n e e. Proof. intros. replace e with (e.[idsubst]). eapply Erel_Fundamental; eauto using Grel_ids. apply idsubst_is_id. Qed. Global Hint Resolve Erel_Fundamental_closed : core. Theorem Grel_Fundamental : forall (ξ : Substitution) (Γ : nat), SUBSCOPE Γ ⊢ ξ ∷ 0 -> forall n, Grel n Γ ξ ξ. Proof. intros. unfold Grel. intuition. break_match_goal. apply Vrel_Fundamental_closed. specialize (H x H0). rewrite Heqs in H. auto. specialize (H x H0). rewrite Heqs in H. inversion H. Qed. Global Hint Resolve Grel_Fundamental : core. Lemma Frel_Case : forall n (e2 e2' e3 e3' : Exp) p (CL1 : EXP pat_vars p ⊢ e2) (CL2 : EXP pat_vars p ⊢ e2'), (forall m, m <= n -> forall vl1 vl2, length vl1 = pat_vars p -> list_biforall (Vrel m) vl1 vl2 -> Erel m e2.[list_subst vl1 idsubst] e2'.[list_subst vl2 idsubst]) -> (forall m, m <= n -> Erel m e3 e3') -> forall m F1 F2, m <= n -> Frel m F1 F2 -> Frel m (FCase p e2 e3::F1) (FCase p e2' e3'::F2). Proof. intros. destruct H2, H3. specialize (H0 m H1) as H0'. apply Erel_closed in H0' as v. destruct v. split. 2: split. 1-2: constructor; auto; now constructor. intros. apply Vrel_closed in H7 as v. destruct v. inversion H8; subst; try inversion_is_value. * eapply match_pattern_Vrel in H18 as H18'. 2: apply H7. destruct H18' as [l2 [M2 Bif]]. apply match_pattern_length in H18. eapply biforall_impl in Bif. 2: { intros; eapply Vrel_downclosed; exact H11. } specialize (H k ltac:(lia) l l2 (eq_sym H18) Bif) as [? [? ?]]. eapply H12 in H19. destruct H19. exists (S x). eapply term_case_true; auto. exact M2. exact H13. lia. split; [ auto | split ]; auto. intros. eapply H4. 3: exact H14. lia. auto. * eapply nomatch_pattern_Vrel in H18 as H18'. 2: apply H7. destruct H0' as [? [? ?]]. eapply H13 in H19. destruct H19. exists (S x). apply term_case_false; auto. exact H14. lia. split; [ auto | split ]; auto. intros. eapply H4. 3: exact H15. lia. auto. Unshelve. lia. Qed. Lemma Frel_Let : forall n (e2 e2' : Exp) x x', (forall m v1 v2, m <= n -> Vrel m v1 v2 -> Erel m (e2.[v1/]) (e2'.[v2/])) -> forall m F1 F2, m <= n -> Frel m F1 F2 -> Frel m (FLet x e2::F1) (FLet x' e2'::F2). Proof. intros. destruct H1, H2. specialize (H m (ELit 0%Z) (ELit 0%Z) H0 ltac:(auto)) as H'. apply Erel_closed in H' as v. destruct v. apply subst_implies_scope_exp_1 in H4. apply subst_implies_scope_exp_1 in H5. split. 2: split. 1-2: constructor; auto; now constructor. intros. apply Vrel_closed in H6 as v. destruct v. inversion H7; subst; try inversion_is_value. eapply (H k) in H16. destruct H16. exists (S x0). constructor. auto. exact H10. lia. eapply Vrel_downclosed. eauto. lia. split. 2: split. 1-2: easy. intros. eapply H3 in H13. exact H13. lia. auto. Unshelve. lia. Qed. Lemma Frel_App1 : forall n (es es' : list Exp), list_biforall (fun e1 e2 => forall m, m <= n -> Erel m e1 e2) es es' -> forall m F1 F2, m <= n -> Frel m F1 F2 -> Frel m (FApp1 es::F1) (FApp1 es'::F2). Proof. intros. destruct H1, H2. split. 2: split. * constructor; auto. constructor. eapply biforall_impl in H. apply biforall_erel_closed in H. apply H. intros. apply H4. exact H0. * constructor; auto. constructor. eapply biforall_impl in H. apply biforall_erel_closed in H. apply H. intros. apply H4. exact H0. * intros. destruct (Vrel_closed H4). inversion H5; subst; try inversion_is_value. - inversion H. subst. eapply H11 in H13. destruct H13. exists (S x). econstructor. auto. exact H8. exact H0. lia. apply Erel_App_compat_ind; auto. + eapply biforall_impl. 2: exact H14. intros. eapply H12. lia. + constructor. + eapply Vrel_downclosed. eauto. + intros. eapply H3 in H16. exact H16. lia. auto. - inversion H. subst. apply Vrel_Fun_right in H4 as v. destruct v, H8, H8. apply eq_sym, length_zero_iff_nil in H8. subst. rewrite Vrel_Fix_eq in H4. destruct H4, H8. rewrite Nat.eqb_refl in H9. specialize (H9 k ltac:(lia) [] [] (eq_refl _) (eq_refl _) ltac:(constructor)). eapply H9 in H12. destruct H12. exists (S x0). constructor. exact H10. lia. split. 2: split. 1-2: auto. intros. eapply H3 in H14. exact H14. lia. auto. Unshelve. auto. Qed. Lemma Frel_App2 : forall n (es es' : list Exp) v1 v1' vs vs', (forall m, m <= n -> Vrel m v1 v1') -> list_biforall (fun v1 v2 => forall m, m <= n -> Vrel m v1 v2) vs vs' -> list_biforall (fun e1 e2 => forall m, m <= n -> Erel m e1 e2) es es' -> forall m F1 F2, m <= n -> Frel m F1 F2 -> Frel m (FApp2 v1 es vs::F1) (FApp2 v1' es' vs'::F2). Proof. intros. destruct H3, H4. apply Erel_App_compat_ind. * eapply biforall_impl. 2: exact H1. intros. now apply H6. * eapply biforall_impl. 2: exact H0. intros. now apply H6. * now apply H. * easy. * easy. * intros. eapply H5 in H8. exact H8. lia. auto. Qed. Lemma Frel_BIF1 : forall n (es es' : list Exp), list_biforall (fun e1 e2 => forall m, m <= n -> Erel m e1 e2) es es' -> forall m F1 F2, m <= n -> Frel m F1 F2 -> Frel m (FBIF1 es::F1) (FBIF1 es'::F2). Proof. intros. destruct H1, H2. split. 2: split. * constructor; auto. constructor. eapply biforall_impl in H. apply biforall_erel_closed in H. apply H. intros. apply H4. exact H0. * constructor; auto. constructor. eapply biforall_impl in H. apply biforall_erel_closed in H. apply H. intros. apply H4. exact H0. * intros. destruct (Vrel_closed H4). inversion H5; subst; try inversion_is_value. - inversion H. subst. eapply H11 in H13. destruct H13. exists (S x). econstructor. auto. exact H8. exact H0. lia. apply Erel_BIF_compat_ind; auto. + eapply biforall_impl. 2: exact H14. intros. eapply H12. lia. + constructor. + eapply Vrel_downclosed. eauto. + intros. eapply H3 in H16. exact H16. lia. auto. Unshelve. auto. Qed. Lemma Frel_BIF2 : forall n (es es' : list Exp) v1 v1' vs vs', (forall m, m <= n -> Vrel m v1 v1') -> list_biforall (fun v1 v2 => forall m, m <= n -> Vrel m v1 v2) vs vs' -> list_biforall (fun e1 e2 => forall m, m <= n -> Erel m e1 e2) es es' -> forall m F1 F2, m <= n -> Frel m F1 F2 -> Frel m (FBIF2 v1 es vs::F1) (FBIF2 v1' es' vs'::F2). Proof. intros. destruct H3, H4. apply Erel_BIF_compat_ind. * eapply biforall_impl. 2: exact H1. intros. now apply H6. * eapply biforall_impl. 2: exact H0. intros. now apply H6. * now apply H. * easy. * easy. * intros. eapply H5 in H8. exact H8. lia. auto. Qed. Lemma Frel_Cons_tail : forall n (e2 e2' : Exp), (forall m, m <= n -> Erel m e2 e2') -> forall m F1 F2, m <= n -> Frel m F1 F2 -> Frel m (FCons1 e2::F1) (FCons1 e2'::F2). Proof. intros. destruct H1, H2. specialize (H m H0) as H'. apply Erel_closed in H' as v. destruct v. split. 2: split. 1-2: constructor; auto; now constructor. intros. apply Vrel_closed in H6 as v. destruct v. inversion H7; subst; try inversion_is_value. eapply H' in H15. destruct H15. exists (S x). econstructor. auto. exact H10. lia. split. 2: split. 1-2: constructor; auto; now constructor. intros. apply Vrel_closed in H13 as v. destruct v. inversion H14; subst; try inversion_is_value. eapply H3 in H24. subst. destruct H24. exists (S x). constructor; auto. exact H18. lia. subst. eapply Vrel_Cons_compat_closed. eapply Vrel_downclosed; eassumption. eapply Vrel_downclosed; eassumption. Unshelve. all: lia. Qed. Lemma Frel_Cons_head : forall n (v1 v1' : Exp), (forall m, m <= n -> Vrel m v1 v1') -> forall m F1 F2, m <= n -> Frel m F1 F2 -> Frel m (FCons2 v1::F1) (FCons2 v1'::F2). Proof. intros. destruct H1, H2. specialize (H m H0) as H'. apply Vrel_closed in H' as v. destruct v. split. 2: split. 1-2: constructor; auto; now constructor. intros. apply Vrel_closed in H6 as v. destruct v. inversion H7; subst; try inversion_is_value. eapply H3 in H16. 2: lia. destruct H16. exists (S x). econstructor; auto. exact H10. eapply Vrel_Cons_compat_closed. eapply Vrel_downclosed; eassumption. eapply Vrel_downclosed; eassumption. Unshelve. all: lia. Qed. Theorem Frel_Fundamental_closed : forall (F : FrameStack) (n : nat), FSCLOSED F -> Frel n F F. Proof. induction F; intros. * cbn. split. 2: split. 1-2: constructor. intros. exists 0. constructor. apply Vrel_closed in H0; apply H0. * split. 2: split. all: auto. intros. destruct a; inversion H; inversion H4. - eapply Frel_App1; eauto. subst. eapply forall_biforall_refl, Forall_impl. 2: exact H7. intros. auto. - eapply Frel_App2; eauto; subst. + eapply forall_biforall_refl, Forall_impl. 2: exact H11. intros. auto. + eapply forall_biforall_refl, Forall_impl. 2: exact H10. intros. auto. - eapply Frel_Let; eauto. intros. subst. eapply Erel_Fundamental; eauto. unfold Grel. destruct (Vrel_closed H10). split. 2: split. 1-2: apply cons_scope; auto. intros. inversion H6; subst. 2: inversion H11. simpl. auto. - eapply Frel_Case; eauto. intros. subst. eapply Erel_Fundamental; eauto. rewrite <- H12. eapply (Grel_list _ _ _ _ _ 0) in H13. rewrite Nat.add_0_r in H13. exact H13. apply Grel_Fundamental. apply scope_idsubst. - eapply Frel_Cons_tail; eauto. - eapply Frel_Cons_head; eauto. - eapply Frel_BIF1; eauto. subst. eapply forall_biforall_refl, Forall_impl. 2: exact H7. intros. auto. - eapply Frel_BIF2; eauto; subst. + eapply forall_biforall_refl, Forall_impl. 2: exact H11. intros. auto. + eapply forall_biforall_refl, Forall_impl. 2: exact H10. intros. auto. Qed. Global Hint Resolve Frel_Fundamental_closed : core.
install.packages("devtools", dependencies = TRUE) devtools::install_github("ucbds-infra/ottr@stable")
double complex function corr(nb,c,q,p,s) use cdat, only : im,al,pi implicit real*8 (a-h,o-z) real*8, intent(in) :: q(nb),p(nb),s(nb) complex*16, intent(in) :: c(nb) complex*16 :: mat(nb,nb),z,z0,c0(nb) common/wave/q0,p0,a0,sigma a = al alfa = 2d0*a0 as=a+alfa av=a*alfa/as an=dsqrt(2d0*dsqrt(av/as)) an0=dsqrt(dsqrt(a/pi)) an2=dsqrt(dsqrt(alfa/pi)) !---- compute c0_k = <psi0|g_k> do j=1,nb dq=q(j)-q0 dp=p(j)-p0 d2=-0.5d0*av*dq*dq d0=-0.5d0/as*dp*dp d1=(alfa*p(j)+a*p0)/as*dq c0(j)=exp(d2+d0+im*d1)*an enddo corr = (0d0,0d0) do i=1,nb corr = corr+conjg(c0(i))*exp(im*s(i))*c(i) enddo end function corr
module Arrow where import Graphics.Gloss import Data.Complex type Arrow = Complex Float vectorize :: Arrow -> Vector vectorize a = (realPart a, imagPart a) -- Rotate an arrow according to its frequency in cycles per second updateArrow :: Arrow -> Integer -> Float -> Arrow updateArrow arrow frequency t = cis (2 * pi * fromInteger frequency * t) * arrow -- Create a path through a list of arrows arranged tip to tail arrange :: [Arrow] -> Path arrange = map vectorize . scanl (+) (0 :+ 0) endpoint :: [Arrow] -> Point endpoint = last . arrange
(* Author: Ondrej Kuncar, TU Muenchen *) section {* Pervasive test of code generator *} theory Generate_Efficient_Datastructures imports Candidates "~~/src/HOL/Library/DAList_Multiset" "~~/src/HOL/Library/RBT_Mapping" "~~/src/HOL/Library/RBT_Set" begin (* The following code equations have to be deleted because they use lists to implement sets in the code generetor. *) lemma [code, code del]: "Sup_pred_inst.Sup_pred = Sup_pred_inst.Sup_pred" .. lemma [code, code del]: "Inf_pred_inst.Inf_pred = Inf_pred_inst.Inf_pred" .. lemma [code, code del]: "pred_of_set = pred_of_set" .. lemma [code, code del]: "Wellfounded.acc = Wellfounded.acc" .. lemma [code, code del]: "Cardinality.card' = Cardinality.card'" .. lemma [code, code del]: "Cardinality.finite' = Cardinality.finite'" .. lemma [code, code del]: "Cardinality.subset' = Cardinality.subset'" .. lemma [code, code del]: "Cardinality.eq_set = Cardinality.eq_set" .. lemma [code, code del]: "(Gcd :: nat set \<Rightarrow> nat) = Gcd" .. lemma [code, code del]: "(Lcm :: nat set \<Rightarrow> nat) = Lcm" .. lemma [code, code del]: "(Gcd :: int set \<Rightarrow> int) = Gcd" .. lemma [code, code del]: "(Lcm :: int set \<Rightarrow> int) = Lcm" .. (* If the code generation ends with an exception with the following message: '"List.set" is not a constructor, on left hand side of equation: ...', the code equation in question has to be either deleted (like many others in this file) or implemented for RBT trees. *) export_code _ checking SML OCaml? Haskell? (* Extra setup to make Scala happy *) (* If the compilation fails with an error "ambiguous implicit values", read \<section>7.1 in the Code Generation Manual *) lemma [code]: "(lfp :: ('a :: complete_linorder \<Rightarrow> 'a) \<Rightarrow> 'a) f = Inf {u. f u \<le> u}" unfolding lfp_def by blast export_code _ checking Scala? end
[GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M m : M ⊢ ↑(-ι Q) m * ↑(-ι Q) m = ↑(algebraMap R (CliffordAlgebra Q)) (↑Q m) [PROOFSTEP] simp [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M ⊢ AlgHom.comp involute involute = AlgHom.id R (CliffordAlgebra Q) [PROOFSTEP] ext [GOAL] case a.h R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x✝ : M ⊢ ↑(LinearMap.comp (AlgHom.toLinearMap (AlgHom.comp involute involute)) (ι Q)) x✝ = ↑(LinearMap.comp (AlgHom.toLinearMap (AlgHom.id R (CliffordAlgebra Q))) (ι Q)) x✝ [PROOFSTEP] simp [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M m : M ⊢ unop (↑(LinearMap.comp (↑(opLinearEquiv R)) (ι Q)) m * ↑(LinearMap.comp (↑(opLinearEquiv R)) (ι Q)) m) = unop (↑(algebraMap R (CliffordAlgebra Q)ᵐᵒᵖ) (↑Q m)) [PROOFSTEP] simp [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M m : M ⊢ ↑reverse (↑(ι Q) m) = ↑(ι Q) m [PROOFSTEP] simp [reverse] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M r : R ⊢ ↑reverse (↑(algebraMap R (CliffordAlgebra Q)) r) = ↑(algebraMap R (CliffordAlgebra Q)) r [PROOFSTEP] simp [reverse] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M ⊢ ↑reverse 1 = 1 [PROOFSTEP] convert reverse.commutes (Q := Q) (1 : R) [GOAL] case h.e'_2.h.e'_6 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M ⊢ 1 = ↑(algebraMap R (CliffordAlgebra Q)) 1 [PROOFSTEP] simp [GOAL] case h.e'_3 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M ⊢ 1 = ↑(algebraMap R (CliffordAlgebra Q)) 1 [PROOFSTEP] simp [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a b : CliffordAlgebra Q ⊢ ↑reverse (a * b) = ↑reverse b * ↑reverse a [PROOFSTEP] simp [reverse] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M ⊢ LinearMap.comp reverse reverse = LinearMap.id [PROOFSTEP] ext m [GOAL] case h R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M m : CliffordAlgebra Q ⊢ ↑(LinearMap.comp reverse reverse) m = ↑LinearMap.id m [PROOFSTEP] simp only [LinearMap.id_apply, LinearMap.comp_apply] [GOAL] case h R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M m : CliffordAlgebra Q ⊢ ↑reverse (↑reverse m) = m [PROOFSTEP] induction m using CliffordAlgebra.induction [GOAL] case h.h_grade0 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M r✝ : R ⊢ ↑reverse (↑reverse (↑(algebraMap R (CliffordAlgebra Q)) r✝)) = ↑(algebraMap R (CliffordAlgebra Q)) r✝ case h.h_grade1 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x✝ : M ⊢ ↑reverse (↑reverse (↑(ι Q) x✝)) = ↑(ι Q) x✝ case h.h_mul R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a✝² b✝ : CliffordAlgebra Q a✝¹ : ↑reverse (↑reverse a✝²) = a✝² a✝ : ↑reverse (↑reverse b✝) = b✝ ⊢ ↑reverse (↑reverse (a✝² * b✝)) = a✝² * b✝ case h.h_add R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a✝² b✝ : CliffordAlgebra Q a✝¹ : ↑reverse (↑reverse a✝²) = a✝² a✝ : ↑reverse (↑reverse b✝) = b✝ ⊢ ↑reverse (↑reverse (a✝² + b✝)) = a✝² + b✝ [PROOFSTEP] case h_grade0 => rw [reverse.commutes, reverse.commutes] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M r✝ : R ⊢ ↑reverse (↑reverse (↑(algebraMap R (CliffordAlgebra Q)) r✝)) = ↑(algebraMap R (CliffordAlgebra Q)) r✝ [PROOFSTEP] case h_grade0 => rw [reverse.commutes, reverse.commutes] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M r✝ : R ⊢ ↑reverse (↑reverse (↑(algebraMap R (CliffordAlgebra Q)) r✝)) = ↑(algebraMap R (CliffordAlgebra Q)) r✝ [PROOFSTEP] rw [reverse.commutes, reverse.commutes] [GOAL] case h.h_grade1 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x✝ : M ⊢ ↑reverse (↑reverse (↑(ι Q) x✝)) = ↑(ι Q) x✝ case h.h_mul R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a✝² b✝ : CliffordAlgebra Q a✝¹ : ↑reverse (↑reverse a✝²) = a✝² a✝ : ↑reverse (↑reverse b✝) = b✝ ⊢ ↑reverse (↑reverse (a✝² * b✝)) = a✝² * b✝ case h.h_add R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a✝² b✝ : CliffordAlgebra Q a✝¹ : ↑reverse (↑reverse a✝²) = a✝² a✝ : ↑reverse (↑reverse b✝) = b✝ ⊢ ↑reverse (↑reverse (a✝² + b✝)) = a✝² + b✝ [PROOFSTEP] case h_grade1 => rw [reverse_ι, reverse_ι] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x✝ : M ⊢ ↑reverse (↑reverse (↑(ι Q) x✝)) = ↑(ι Q) x✝ [PROOFSTEP] case h_grade1 => rw [reverse_ι, reverse_ι] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x✝ : M ⊢ ↑reverse (↑reverse (↑(ι Q) x✝)) = ↑(ι Q) x✝ [PROOFSTEP] rw [reverse_ι, reverse_ι] [GOAL] case h.h_mul R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a✝² b✝ : CliffordAlgebra Q a✝¹ : ↑reverse (↑reverse a✝²) = a✝² a✝ : ↑reverse (↑reverse b✝) = b✝ ⊢ ↑reverse (↑reverse (a✝² * b✝)) = a✝² * b✝ case h.h_add R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a✝² b✝ : CliffordAlgebra Q a✝¹ : ↑reverse (↑reverse a✝²) = a✝² a✝ : ↑reverse (↑reverse b✝) = b✝ ⊢ ↑reverse (↑reverse (a✝² + b✝)) = a✝² + b✝ [PROOFSTEP] case h_mul a b ha hb => rw [reverse.map_mul, reverse.map_mul, ha, hb] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a b : CliffordAlgebra Q ha : ↑reverse (↑reverse a) = a hb : ↑reverse (↑reverse b) = b ⊢ ↑reverse (↑reverse (a * b)) = a * b [PROOFSTEP] case h_mul a b ha hb => rw [reverse.map_mul, reverse.map_mul, ha, hb] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a b : CliffordAlgebra Q ha : ↑reverse (↑reverse a) = a hb : ↑reverse (↑reverse b) = b ⊢ ↑reverse (↑reverse (a * b)) = a * b [PROOFSTEP] rw [reverse.map_mul, reverse.map_mul, ha, hb] [GOAL] case h.h_add R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a✝² b✝ : CliffordAlgebra Q a✝¹ : ↑reverse (↑reverse a✝²) = a✝² a✝ : ↑reverse (↑reverse b✝) = b✝ ⊢ ↑reverse (↑reverse (a✝² + b✝)) = a✝² + b✝ [PROOFSTEP] case h_add a b ha hb => rw [reverse.map_add, reverse.map_add, ha, hb] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a b : CliffordAlgebra Q ha : ↑reverse (↑reverse a) = a hb : ↑reverse (↑reverse b) = b ⊢ ↑reverse (↑reverse (a + b)) = a + b [PROOFSTEP] case h_add a b ha hb => rw [reverse.map_add, reverse.map_add, ha, hb] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a b : CliffordAlgebra Q ha : ↑reverse (↑reverse a) = a hb : ↑reverse (↑reverse b) = b ⊢ ↑reverse (↑reverse (a + b)) = a + b [PROOFSTEP] rw [reverse.map_add, reverse.map_add, ha, hb] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M ⊢ LinearMap.comp reverse (AlgHom.toLinearMap involute) = LinearMap.comp (AlgHom.toLinearMap involute) reverse [PROOFSTEP] ext x [GOAL] case h R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x : CliffordAlgebra Q ⊢ ↑(LinearMap.comp reverse (AlgHom.toLinearMap involute)) x = ↑(LinearMap.comp (AlgHom.toLinearMap involute) reverse) x [PROOFSTEP] simp only [LinearMap.comp_apply, AlgHom.toLinearMap_apply] [GOAL] case h R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x : CliffordAlgebra Q ⊢ ↑reverse (↑involute x) = ↑involute (↑reverse x) [PROOFSTEP] induction x using CliffordAlgebra.induction [GOAL] case h.h_grade0 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M r✝ : R ⊢ ↑reverse (↑involute (↑(algebraMap R (CliffordAlgebra Q)) r✝)) = ↑involute (↑reverse (↑(algebraMap R (CliffordAlgebra Q)) r✝)) case h.h_grade1 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x✝ : M ⊢ ↑reverse (↑involute (↑(ι Q) x✝)) = ↑involute (↑reverse (↑(ι Q) x✝)) case h.h_mul R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a✝² b✝ : CliffordAlgebra Q a✝¹ : ↑reverse (↑involute a✝²) = ↑involute (↑reverse a✝²) a✝ : ↑reverse (↑involute b✝) = ↑involute (↑reverse b✝) ⊢ ↑reverse (↑involute (a✝² * b✝)) = ↑involute (↑reverse (a✝² * b✝)) case h.h_add R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a✝² b✝ : CliffordAlgebra Q a✝¹ : ↑reverse (↑involute a✝²) = ↑involute (↑reverse a✝²) a✝ : ↑reverse (↑involute b✝) = ↑involute (↑reverse b✝) ⊢ ↑reverse (↑involute (a✝² + b✝)) = ↑involute (↑reverse (a✝² + b✝)) [PROOFSTEP] case h_grade0 => simp [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M r✝ : R ⊢ ↑reverse (↑involute (↑(algebraMap R (CliffordAlgebra Q)) r✝)) = ↑involute (↑reverse (↑(algebraMap R (CliffordAlgebra Q)) r✝)) [PROOFSTEP] case h_grade0 => simp [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M r✝ : R ⊢ ↑reverse (↑involute (↑(algebraMap R (CliffordAlgebra Q)) r✝)) = ↑involute (↑reverse (↑(algebraMap R (CliffordAlgebra Q)) r✝)) [PROOFSTEP] simp [GOAL] case h.h_grade1 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x✝ : M ⊢ ↑reverse (↑involute (↑(ι Q) x✝)) = ↑involute (↑reverse (↑(ι Q) x✝)) case h.h_mul R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a✝² b✝ : CliffordAlgebra Q a✝¹ : ↑reverse (↑involute a✝²) = ↑involute (↑reverse a✝²) a✝ : ↑reverse (↑involute b✝) = ↑involute (↑reverse b✝) ⊢ ↑reverse (↑involute (a✝² * b✝)) = ↑involute (↑reverse (a✝² * b✝)) case h.h_add R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a✝² b✝ : CliffordAlgebra Q a✝¹ : ↑reverse (↑involute a✝²) = ↑involute (↑reverse a✝²) a✝ : ↑reverse (↑involute b✝) = ↑involute (↑reverse b✝) ⊢ ↑reverse (↑involute (a✝² + b✝)) = ↑involute (↑reverse (a✝² + b✝)) [PROOFSTEP] case h_grade1 => simp [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x✝ : M ⊢ ↑reverse (↑involute (↑(ι Q) x✝)) = ↑involute (↑reverse (↑(ι Q) x✝)) [PROOFSTEP] case h_grade1 => simp [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x✝ : M ⊢ ↑reverse (↑involute (↑(ι Q) x✝)) = ↑involute (↑reverse (↑(ι Q) x✝)) [PROOFSTEP] simp [GOAL] case h.h_mul R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a✝² b✝ : CliffordAlgebra Q a✝¹ : ↑reverse (↑involute a✝²) = ↑involute (↑reverse a✝²) a✝ : ↑reverse (↑involute b✝) = ↑involute (↑reverse b✝) ⊢ ↑reverse (↑involute (a✝² * b✝)) = ↑involute (↑reverse (a✝² * b✝)) case h.h_add R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a✝² b✝ : CliffordAlgebra Q a✝¹ : ↑reverse (↑involute a✝²) = ↑involute (↑reverse a✝²) a✝ : ↑reverse (↑involute b✝) = ↑involute (↑reverse b✝) ⊢ ↑reverse (↑involute (a✝² + b✝)) = ↑involute (↑reverse (a✝² + b✝)) [PROOFSTEP] case h_mul a b ha hb => simp only [ha, hb, reverse.map_mul, AlgHom.map_mul] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a b : CliffordAlgebra Q ha : ↑reverse (↑involute a) = ↑involute (↑reverse a) hb : ↑reverse (↑involute b) = ↑involute (↑reverse b) ⊢ ↑reverse (↑involute (a * b)) = ↑involute (↑reverse (a * b)) [PROOFSTEP] case h_mul a b ha hb => simp only [ha, hb, reverse.map_mul, AlgHom.map_mul] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a b : CliffordAlgebra Q ha : ↑reverse (↑involute a) = ↑involute (↑reverse a) hb : ↑reverse (↑involute b) = ↑involute (↑reverse b) ⊢ ↑reverse (↑involute (a * b)) = ↑involute (↑reverse (a * b)) [PROOFSTEP] simp only [ha, hb, reverse.map_mul, AlgHom.map_mul] [GOAL] case h.h_add R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a✝² b✝ : CliffordAlgebra Q a✝¹ : ↑reverse (↑involute a✝²) = ↑involute (↑reverse a✝²) a✝ : ↑reverse (↑involute b✝) = ↑involute (↑reverse b✝) ⊢ ↑reverse (↑involute (a✝² + b✝)) = ↑involute (↑reverse (a✝² + b✝)) [PROOFSTEP] case h_add a b ha hb => simp only [ha, hb, reverse.map_add, AlgHom.map_add] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a b : CliffordAlgebra Q ha : ↑reverse (↑involute a) = ↑involute (↑reverse a) hb : ↑reverse (↑involute b) = ↑involute (↑reverse b) ⊢ ↑reverse (↑involute (a + b)) = ↑involute (↑reverse (a + b)) [PROOFSTEP] case h_add a b ha hb => simp only [ha, hb, reverse.map_add, AlgHom.map_add] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M a b : CliffordAlgebra Q ha : ↑reverse (↑involute a) = ↑involute (↑reverse a) hb : ↑reverse (↑involute b) = ↑involute (↑reverse b) ⊢ ↑reverse (↑involute (a + b)) = ↑involute (↑reverse (a + b)) [PROOFSTEP] simp only [ha, hb, reverse.map_add, AlgHom.map_add] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M ⊢ ↑reverse (List.prod (List.map ↑(ι Q) [])) = List.prod (List.reverse (List.map ↑(ι Q) [])) [PROOFSTEP] simp [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x : M xs : List M ⊢ ↑reverse (List.prod (List.map (↑(ι Q)) (x :: xs))) = List.prod (List.reverse (List.map (↑(ι Q)) (x :: xs))) [PROOFSTEP] simp [reverse_prod_map_ι xs] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M ⊢ ↑involute (List.prod (List.map ↑(ι Q) [])) = (-1) ^ List.length [] • List.prod (List.map ↑(ι Q) []) [PROOFSTEP] simp [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x : M xs : List M ⊢ ↑involute (List.prod (List.map (↑(ι Q)) (x :: xs))) = (-1) ^ List.length (x :: xs) • List.prod (List.map (↑(ι Q)) (x :: xs)) [PROOFSTEP] simp [pow_succ, involute_prod_map_ι xs] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M ⊢ Submodule.comap (AlgHom.toLinearMap involute) (LinearMap.range (ι Q)) = LinearMap.range (ι Q) [PROOFSTEP] rw [← submodule_map_involute_eq_comap, ι_range_map_involute] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M n : ZMod 2 ⊢ Submodule.map (AlgHom.toLinearMap involute) (evenOdd Q n) = evenOdd Q n [PROOFSTEP] simp_rw [evenOdd, Submodule.map_iSup, Submodule.map_pow, ι_range_map_involute] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M n : ZMod 2 ⊢ Submodule.comap (AlgHom.toLinearMap involute) (evenOdd Q n) = evenOdd Q n [PROOFSTEP] rw [← submodule_map_involute_eq_comap, evenOdd_map_involute] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M ⊢ Submodule.map reverse (LinearMap.range (ι Q)) = LinearMap.range (ι Q) [PROOFSTEP] rw [reverse, Submodule.map_comp, ι_range_map_lift, LinearMap.range_comp, ← Submodule.map_comp] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M ⊢ Submodule.map (LinearMap.comp ↑(LinearEquiv.symm (MulOpposite.opLinearEquiv R)) ↑(MulOpposite.opLinearEquiv R)) (LinearMap.range (ι Q)) = LinearMap.range (ι Q) [PROOFSTEP] exact Submodule.map_id _ [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M ⊢ Submodule.comap reverse (LinearMap.range (ι Q)) = LinearMap.range (ι Q) [PROOFSTEP] rw [← submodule_map_reverse_eq_comap, ι_range_map_reverse] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M p q : Submodule R (CliffordAlgebra Q) ⊢ Submodule.map reverse (p * q) = Submodule.map reverse q * Submodule.map reverse p [PROOFSTEP] simp_rw [reverse, Submodule.map_comp, Submodule.map_mul, Submodule.map_unop_mul] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M p q : Submodule R (CliffordAlgebra Q) ⊢ Submodule.comap reverse (p * q) = Submodule.comap reverse q * Submodule.comap reverse p [PROOFSTEP] simp_rw [← submodule_map_reverse_eq_comap, submodule_map_mul_reverse] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M p : Submodule R (CliffordAlgebra Q) n : ℕ ⊢ Submodule.map reverse (p ^ n) = Submodule.map reverse p ^ n [PROOFSTEP] simp_rw [reverse, Submodule.map_comp, Submodule.map_pow, Submodule.map_unop_pow] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M p : Submodule R (CliffordAlgebra Q) n : ℕ ⊢ Submodule.comap reverse (p ^ n) = Submodule.comap reverse p ^ n [PROOFSTEP] simp_rw [← submodule_map_reverse_eq_comap, submodule_map_pow_reverse] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M n : ZMod 2 ⊢ Submodule.map reverse (evenOdd Q n) = evenOdd Q n [PROOFSTEP] simp_rw [evenOdd, Submodule.map_iSup, submodule_map_pow_reverse, ι_range_map_reverse] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M n : ZMod 2 ⊢ Submodule.comap reverse (evenOdd Q n) = evenOdd Q n [PROOFSTEP] rw [← submodule_map_reverse_eq_comap, evenOdd_map_reverse] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x : CliffordAlgebra Q h : x ∈ evenOdd Q 0 ⊢ ↑involute x = x [PROOFSTEP] refine' even_induction Q (AlgHom.commutes _) _ _ x h [GOAL] case refine'_1 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x : CliffordAlgebra Q h : x ∈ evenOdd Q 0 ⊢ ∀ {x y : CliffordAlgebra Q} {hx : x ∈ evenOdd Q 0} {hy : y ∈ evenOdd Q 0}, ↑involute x = x → ↑involute y = y → ↑involute (x + y) = x + y [PROOFSTEP] rintro x y _hx _hy ihx ihy [GOAL] case refine'_1 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x✝ : CliffordAlgebra Q h : x✝ ∈ evenOdd Q 0 x y : CliffordAlgebra Q _hx : x ∈ evenOdd Q 0 _hy : y ∈ evenOdd Q 0 ihx : ↑involute x = x ihy : ↑involute y = y ⊢ ↑involute (x + y) = x + y [PROOFSTEP] rw [map_add, ihx, ihy] [GOAL] case refine'_2 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x : CliffordAlgebra Q h : x ∈ evenOdd Q 0 ⊢ ∀ (m₁ m₂ : M) {x : CliffordAlgebra Q} {hx : x ∈ evenOdd Q 0}, ↑involute x = x → ↑involute (↑(ι Q) m₁ * ↑(ι Q) m₂ * x) = ↑(ι Q) m₁ * ↑(ι Q) m₂ * x [PROOFSTEP] intro m₁ m₂ x _hx ihx [GOAL] case refine'_2 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x✝ : CliffordAlgebra Q h : x✝ ∈ evenOdd Q 0 m₁ m₂ : M x : CliffordAlgebra Q _hx : x ∈ evenOdd Q 0 ihx : ↑involute x = x ⊢ ↑involute (↑(ι Q) m₁ * ↑(ι Q) m₂ * x) = ↑(ι Q) m₁ * ↑(ι Q) m₂ * x [PROOFSTEP] rw [map_mul, map_mul, involute_ι, involute_ι, ihx, neg_mul_neg] [GOAL] R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x : CliffordAlgebra Q h : x ∈ evenOdd Q 1 ⊢ ↑involute x = -x [PROOFSTEP] refine' odd_induction Q involute_ι _ _ x h [GOAL] case refine'_1 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x : CliffordAlgebra Q h : x ∈ evenOdd Q 1 ⊢ ∀ {x y : CliffordAlgebra Q} {hx : x ∈ evenOdd Q 1} {hy : y ∈ evenOdd Q 1}, ↑involute x = -x → ↑involute y = -y → ↑involute (x + y) = -(x + y) [PROOFSTEP] rintro x y _hx _hy ihx ihy [GOAL] case refine'_1 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x✝ : CliffordAlgebra Q h : x✝ ∈ evenOdd Q 1 x y : CliffordAlgebra Q _hx : x ∈ evenOdd Q 1 _hy : y ∈ evenOdd Q 1 ihx : ↑involute x = -x ihy : ↑involute y = -y ⊢ ↑involute (x + y) = -(x + y) [PROOFSTEP] rw [map_add, ihx, ihy, neg_add] [GOAL] case refine'_2 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x : CliffordAlgebra Q h : x ∈ evenOdd Q 1 ⊢ ∀ (m₁ m₂ : M) {x : CliffordAlgebra Q} {hx : x ∈ evenOdd Q 1}, ↑involute x = -x → ↑involute (↑(ι Q) m₁ * ↑(ι Q) m₂ * x) = -(↑(ι Q) m₁ * ↑(ι Q) m₂ * x) [PROOFSTEP] intro m₁ m₂ x _hx ihx [GOAL] case refine'_2 R : Type u_1 inst✝² : CommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M Q : QuadraticForm R M x✝ : CliffordAlgebra Q h : x✝ ∈ evenOdd Q 1 m₁ m₂ : M x : CliffordAlgebra Q _hx : x ∈ evenOdd Q 1 ihx : ↑involute x = -x ⊢ ↑involute (↑(ι Q) m₁ * ↑(ι Q) m₂ * x) = -(↑(ι Q) m₁ * ↑(ι Q) m₂ * x) [PROOFSTEP] rw [map_mul, map_mul, involute_ι, involute_ι, ihx, neg_mul_neg, mul_neg]
# Custom, hardcoded streamers abstract type CustomROOTStruct end # KM3NeT struct KM3NETDAQHit <: CustomROOTStruct dom_id::Int32 channel_id::UInt8 tdc::Int32 tot::UInt8 end function readtype(io::IO, T::Type{KM3NETDAQHit}) T(readtype(io, Int32), read(io, UInt8), read(io, Int32), read(io, UInt8)) end # Experimental implementation for maximum performance (using reinterpret) primitive type DAQHit 80 end function Base.getproperty(hit::DAQHit, s::Symbol) r = Ref(hit) GC.@preserve r begin if s === :dom_id return ntoh(unsafe_load(Ptr{Int32}(Base.unsafe_convert(Ptr{Cvoid}, r)))) elseif s === :channel_id return unsafe_load(Ptr{UInt8}(Base.unsafe_convert(Ptr{Cvoid}, r)+4)) elseif s === :tdc return unsafe_load(Ptr{UInt32}(Base.unsafe_convert(Ptr{Cvoid}, r)+5)) elseif s === :tot return unsafe_load(Ptr{UInt8}(Base.unsafe_convert(Ptr{Cvoid}, r)+9)) end end error("unknown field $s of type $(typeof(hit))") end Base.show(io::IO, h::DAQHit) = print(io, "DAQHit(", h.dom_id, ',', h.channel_id, ',', h.tdc, ',', h.tot, ')') struct KM3NETDAQTriggeredHit dom_id::Int32 channel_id::UInt8 tdc::Int32 tot::UInt8 trigger_mask::UInt64 end function readtype(io::IO, T::Type{KM3NETDAQTriggeredHit}) dom_id = readtype(io, Int32) channel_id = read(io, UInt8) tdc = read(io, Int32) tot = read(io, UInt8) skip(io, 6) trigger_mask = readtype(io, UInt64) T(dom_id, channel_id, tdc, tot, trigger_mask) end struct KM3NETDAQEventHeader detector_id::Int32 run::Int32 frame_index::Int32 UTC_seconds::UInt32 UTC_16nanosecondcycles::UInt32 trigger_counter::UInt64 trigger_mask::UInt64 overlays::UInt32 end function readtype(io::IO, T::Type{KM3NETDAQEventHeader}) skip(io, 18) detector_id = readtype(io, Int32) run = readtype(io, Int32) frame_index = readtype(io, Int32) skip(io, 6) UTC_seconds = readtype(io, UInt32) UTC_16nanosecondcycles = readtype(io, UInt32) skip(io, 6) trigger_counter = readtype(io, UInt64) skip(io, 6) trigger_mask = readtype(io, UInt64) overlays = readtype(io, UInt32) T(detector_id, run, frame_index, UTC_seconds, UTC_16nanosecondcycles, trigger_counter, trigger_mask, overlays) end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % GEANT manual in LaTeX form % % % % Michel Goossens (for translation into LaTeX) % % Version 1.00 % % Last Mod. Jan 24 1991 1300 MG + IB % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \Origin{R.Brun} \Submitted{01.11.83} \Revised{17.12.93} \Version{Geant 3.16} \Routid{HITS120} \Makehead{DETector Digitisation parameters} \Shubr{GSDETD}{(CHSET,CHDET,ND,CHNMSD,NBITSD)} \begin{DLtt}{MMMMMMMM} \item[CHSET] ({\tt CHARACTER*4}) set name; \item[CHDET] ({\tt CHARACTER*4}) detector name; \item[ND] ({\tt INTEGER}) number of elements per digitisation; \item[CHNMSD] ({\tt CHARACTER*4}) array of {\tt ND} names for the digitisation elements; \item[NBITSD] ({\tt INTEGER}) array of {\tt ND}, {\tt NBITSD(I)} ({\tt I=1,...,ND}) is the number of bits into which to pack the {\tt I$^{th}$} element of the digit. \end{DLtt} Defines digitisation parameters for detector {\tt CHDET} of set {\tt CHSET}. The routine must be called at initialisation, after the geometrical volumes have been defined, to describe the digitisation elements and the way to pack them in the data structure {\tt JDIGI}. \section*{Example} Following on from the example in {\tt [HITS110]}, we want to add the digitisation information to detector {\tt EPHI} of set {\tt ECAL}. The information which should be stored for each digitisation is the ADC pulse height in the lead glass block, so that a digitisation in this scheme could look like: \begin{center} \begin{tabular}{l@{\hspace{2cm}}l} Element & Value \\ \hline \tt EPHI & 12 \\ \tt EZRI & 41 \\ \tt BLOC & 3 \\ \tt ADC & 789 \\ \end{tabular} \end{center} The code to define the digitisation information could be: \begin{verbatim} CHARACTER*4 CHNMSD DATA CHNMSD/'ADC '/ DATA NBITSD/16/ CALL GSDETD('ECAL','BLOC',1,CHNMSD,NBITSD) \end{verbatim} \Shubr{GFDETD}{(CHSET,CHDET,ND*,CHNMSD*,NBITSD*)} Returns the digitisation parameters for detector {\tt CHDET} of set {\tt CHSET}. All arguments as explained in \Rind{GSDETD}.
export leastsq,∂leastsq "least square" function leastsq(obj,pre) cost=sum((obj-pre).^2)/size(pre)[end] end function ∂leastsq(obj,pre) cost=pre-obj end
module Examples.Declassification.DatingSystem import Pruviloj.Disjoint import DepSec.Labeled import DepSec.DIO import DepSec.Declassification import Examples.AuthorityLattice %language ElabReflection %default total data Gender : Type where Unknown : Gender M : Gender F : Gender implementation DecEq Gender where decEq Unknown Unknown = Yes Refl decEq Unknown M = No (%runElab disjoint) decEq Unknown F = No (%runElab disjoint) decEq M Unknown = No (%runElab disjoint) decEq M M = Yes Refl decEq M F = No (%runElab disjoint) decEq F Unknown = No (%runElab disjoint) decEq F M = No (%runElab disjoint) decEq F F = Yes Refl record ProfileInfo (Owner : Principal) where constructor MkProfileInfo name : Labeled Owner String gender : Labeled Owner Gender birthdate : Labeled Owner String interests : Labeled Owner String city : Labeled Owner String DiscoveryResult : Principal -> Type DiscoveryResult = ProfileInfo Discoverer : Type Discoverer = {bOwner : Principal} -> (b : ProfileInfo bOwner) -> DIO bOwner (Maybe (DiscoveryResult bOwner)) record Profile (Owner : Principal) where constructor MkProfile info : ProfileInfo Owner discoverer : Discoverer data GenProfile : (Principal : Type) -> Type where MkGenProfile : {t : Principal} -> Profile t -> GenProfile Principal data Authority : a -> Type where ||| TCB MkAuthority : (t : a) -> Authority t authorityHatch : { l, l' : Principal } -> (s ** (l = s, Authority s)) -> Labeled l a -> Labeled l' a authorityHatch {l} = tokenHatch (\s => (l=s, Authority s)) -------------------------------------------------------------------------------- -- Convenience -------------------------------------------------------------------------------- %hint hint1 : {a : Principal} -> leq a a hint1 {a} = reflexive a implicit genderToString : Gender -> String genderToString M = "Male" genderToString F = "Female" genderToString Unknown = "Unknown" implicit profileToString : (p : DiscoveryResult viewer) -> DIO viewer String profileToString (MkProfileInfo name gender birthdate likes location) = pure ("NAME: " ++ !(unlabel name) ++ "\n" ++ "BIRTHDATE: " ++ !(unlabel birthdate) ++ "\n" ++ "LIKES: " ++ !(unlabel likes) ++ "\n" ++ "LOCATION: " ++ !(unlabel location) ++ "\n") implicit toLabeled : Poset labelType => {l : labelType} -> String -> Labeled l String toLabeled x = label x implicit toLabeledG : Poset labelType => {l : labelType} -> Gender -> Labeled l Gender toLabeledG x = label x -------------------------------------------------------------------------------- -- UTCB -------------------------------------------------------------------------------- sampleDiscoverer : {A, B : Principal} -> Authority A -> (a : ProfileInfo A) -> (b : ProfileInfo B) -> DIO B (Maybe (DiscoveryResult B)) sampleDiscoverer {A} {B} auth a b = do bGender <- unlabel $ gender b aGender <- unlabel $ authorityHatch (A ** (Refl, auth)) (gender a) aName <- unlabel $ authorityHatch (A ** (Refl, auth)) (name a) case decEq bGender aGender of Yes prf => pure Nothing No contra => let result : DiscoveryResult B = MkProfileInfo (label aName) (label Unknown) "" "" "" in pure $ Just result -------------------------------------------------------------------------------- -- TCB -------------------------------------------------------------------------------- profileBob : Profile Bob profileBob = let profileInfo = MkProfileInfo "Bob" M "1994" "Nothing" "Aarhus" in MkProfile profileInfo (sampleDiscoverer (MkAuthority Bob) profileInfo) profileAlice : Profile Alice profileAlice = let profileInfo = MkProfileInfo "Alice" F "1993" "Hunting" "Aarhus" in MkProfile profileInfo (sampleDiscoverer (MkAuthority Alice) profileInfo) profileChuck : Profile Chuck profileChuck = let profileInfo = MkProfileInfo "Chuck" M "1992" "Swimming" "Ribe" in MkProfile profileInfo (sampleDiscoverer (MkAuthority Chuck) profileInfo) profileQueueAlice : List (GenProfile Principal) profileQueueAlice = [MkGenProfile profileBob, MkGenProfile profileChuck] printAlice : String -> DIO Alice () printAlice x = lift $ putStrLn x runThroughQueueAlice : (acc : DIO Alice ()) -> List (GenProfile Principal) -> DIO Alice () runThroughQueueAlice acc [] = acc runThroughQueueAlice acc ((MkGenProfile p) :: xs) = let thisProfilePrint : DIO Alice () = do acc result <- (discoverer p) (info profileAlice) case result of Nothing => printAlice "Did not wanna be seen" Just result' => printAlice !result' in runThroughQueueAlice thisProfilePrint xs main : IO () main = do putStrLn "########## Alice's queue is checked ##########\n" run $ runThroughQueueAlice (pure ()) profileQueueAlice putStrLn "########## Done checking ##########" pure ()
State Before: K : Type u V V₁ V₂ V₃ : Type v V' V'₁ : Type v' V'' : Type v'' ι✝ : Type w ι' : Type w' η : Type u₁' φ : η → Type ?u.352311 R : Type u inst✝⁴ : Ring R inst✝³ : StrongRankCondition R M : Type v inst✝² : AddCommGroup M inst✝¹ : Module R M ι : Type u_1 v : ι → M i : LinearIndependent R v w : Set M inst✝ : Fintype ↑w s : span R w = ⊤ ⊢ (#ι) ≤ ↑(Fintype.card ↑w) State After: K : Type u V V₁ V₂ V₃ : Type v V' V'₁ : Type v' V'' : Type v'' ι✝ : Type w ι' : Type w' η : Type u₁' φ : η → Type ?u.352311 R : Type u inst✝⁴ : Ring R inst✝³ : StrongRankCondition R M : Type v inst✝² : AddCommGroup M inst✝¹ : Module R M ι : Type u_1 v : ι → M i : LinearIndependent R v w : Set M inst✝ : Fintype ↑w s : span R w = ⊤ ⊢ range v ≤ ↑(span R w) Tactic: apply linearIndependent_le_span' v i w State Before: K : Type u V V₁ V₂ V₃ : Type v V' V'₁ : Type v' V'' : Type v'' ι✝ : Type w ι' : Type w' η : Type u₁' φ : η → Type ?u.352311 R : Type u inst✝⁴ : Ring R inst✝³ : StrongRankCondition R M : Type v inst✝² : AddCommGroup M inst✝¹ : Module R M ι : Type u_1 v : ι → M i : LinearIndependent R v w : Set M inst✝ : Fintype ↑w s : span R w = ⊤ ⊢ range v ≤ ↑(span R w) State After: K : Type u V V₁ V₂ V₃ : Type v V' V'₁ : Type v' V'' : Type v'' ι✝ : Type w ι' : Type w' η : Type u₁' φ : η → Type ?u.352311 R : Type u inst✝⁴ : Ring R inst✝³ : StrongRankCondition R M : Type v inst✝² : AddCommGroup M inst✝¹ : Module R M ι : Type u_1 v : ι → M i : LinearIndependent R v w : Set M inst✝ : Fintype ↑w s : span R w = ⊤ ⊢ range v ≤ ↑⊤ Tactic: rw [s] State Before: K : Type u V V₁ V₂ V₃ : Type v V' V'₁ : Type v' V'' : Type v'' ι✝ : Type w ι' : Type w' η : Type u₁' φ : η → Type ?u.352311 R : Type u inst✝⁴ : Ring R inst✝³ : StrongRankCondition R M : Type v inst✝² : AddCommGroup M inst✝¹ : Module R M ι : Type u_1 v : ι → M i : LinearIndependent R v w : Set M inst✝ : Fintype ↑w s : span R w = ⊤ ⊢ range v ≤ ↑⊤ State After: no goals Tactic: exact le_top
In 2011 Rice University released a study , " Atlas of Sustainable Strategies for Galveston Island , " which argued that the West End of Galveston was quickly eroding and that the City should reduce construction and / or population in that area . It recommended against any rebuilding of the West End in the event of damage due to another hurricane . Scientists increasingly recognize that barrier islands are inherently unstable and cannot be permanently fixed .
[STATEMENT] theorem stat_ref_comp_to_non_ground_fam_inter: assumes stat_ref_G: "\<forall>q \<in> Q. statically_complete_calculus Bot_G (Inf_G_q q) (entails_q q) (Red_I_q q) (Red_F_q q)" and sat_n_imp: "\<And>N. saturated N \<Longrightarrow> \<exists>q \<in> Q. ground_Inf_overapproximated q N" shows "statically_complete_calculus Bot_F Inf_F entails_\<G> Red_I_\<G> Red_F_\<G>_empty" [PROOF STATE] proof (prove) goal (1 subgoal): 1. statically_complete_calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty [PROOF STEP] using empty_ord.calculus_axioms [PROOF STATE] proof (prove) using this: calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty goal (1 subgoal): 1. statically_complete_calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty [PROOF STEP] unfolding statically_complete_calculus_def statically_complete_calculus_axioms_def [PROOF STATE] proof (prove) using this: calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty goal (1 subgoal): 1. calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty \<and> (\<forall>B N. B \<in> Bot_F \<longrightarrow> empty_ord.saturated N \<longrightarrow> N \<Turnstile>\<inter>\<G> {B} \<longrightarrow> (\<exists>B'\<in>Bot_F. B' \<in> N)) [PROOF STEP] proof (standard, clarify) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>B N. \<lbrakk>calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty; B \<in> Bot_F; empty_ord.saturated N; N \<Turnstile>\<inter>\<G> {B}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] fix B N [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>B N. \<lbrakk>calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty; B \<in> Bot_F; empty_ord.saturated N; N \<Turnstile>\<inter>\<G> {B}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] assume b_in: "B \<in> Bot_F" and sat_n: "saturated N" and entails_bot: "N \<Turnstile>\<inter>\<G> {B}" [PROOF STATE] proof (state) this: B \<in> Bot_F empty_ord.saturated N N \<Turnstile>\<inter>\<G> {B} goal (1 subgoal): 1. \<And>B N. \<lbrakk>calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty; B \<in> Bot_F; empty_ord.saturated N; N \<Turnstile>\<inter>\<G> {B}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] then [PROOF STATE] proof (chain) picking this: B \<in> Bot_F empty_ord.saturated N N \<Turnstile>\<inter>\<G> {B} [PROOF STEP] obtain q where q_in: "q \<in> Q" and inf_subs: "ground.Inf_from_q q (\<G>_Fset_q q N) \<subseteq> {\<iota>. \<exists>\<iota>'\<in> Inf_from N. \<G>_I_q q \<iota>' \<noteq> None \<and> \<iota> \<in> the (\<G>_I_q q \<iota>')} \<union> Red_I_q q (\<G>_Fset_q q N)" [PROOF STATE] proof (prove) using this: B \<in> Bot_F empty_ord.saturated N N \<Turnstile>\<inter>\<G> {B} goal (1 subgoal): 1. (\<And>q. \<lbrakk>q \<in> Q; ground.Inf_from_q q (\<G>_Fset_q q N) \<subseteq> {\<iota>. \<exists>\<iota>'\<in>Inf_from N. \<G>_I_q q \<iota>' \<noteq> None \<and> \<iota> \<in> the (\<G>_I_q q \<iota>')} \<union> Red_I_q q (\<G>_Fset_q q N)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] using sat_n_imp[of N] [PROOF STATE] proof (prove) using this: B \<in> Bot_F empty_ord.saturated N N \<Turnstile>\<inter>\<G> {B} empty_ord.saturated N \<Longrightarrow> \<exists>q\<in>Q. ground.Inf_from_q q (\<G>_Fset_q q N) \<subseteq> {\<iota>. \<exists>\<iota>'\<in>Inf_from N. \<G>_I_q q \<iota>' \<noteq> None \<and> \<iota> \<in> the (\<G>_I_q q \<iota>')} \<union> Red_I_q q (\<G>_Fset_q q N) goal (1 subgoal): 1. (\<And>q. \<lbrakk>q \<in> Q; ground.Inf_from_q q (\<G>_Fset_q q N) \<subseteq> {\<iota>. \<exists>\<iota>'\<in>Inf_from N. \<G>_I_q q \<iota>' \<noteq> None \<and> \<iota> \<in> the (\<G>_I_q q \<iota>')} \<union> Red_I_q q (\<G>_Fset_q q N)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: q \<in> Q ground.Inf_from_q q (\<G>_Fset_q q N) \<subseteq> {\<iota>. \<exists>\<iota>'\<in>Inf_from N. \<G>_I_q q \<iota>' \<noteq> None \<and> \<iota> \<in> the (\<G>_I_q q \<iota>')} \<union> Red_I_q q (\<G>_Fset_q q N) goal (1 subgoal): 1. \<And>B N. \<lbrakk>calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty; B \<in> Bot_F; empty_ord.saturated N; N \<Turnstile>\<inter>\<G> {B}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] interpret q_calc: calculus Bot_F Inf_F "entails_\<G>_q q" "Red_I_\<G>_q q" "Red_F_\<G>_q q" [PROOF STATE] proof (prove) goal (1 subgoal): 1. calculus Bot_F Inf_F (\<lambda>N1 N2. entails_q q (\<G>_Fset_q q N1) (\<G>_Fset_q q N2)) (Red_I_\<G>_q q) (Red_F_\<G>_q q) [PROOF STEP] using all_red_crit[rule_format, OF q_in] [PROOF STATE] proof (prove) using this: calculus Bot_F Inf_F (\<lambda>N1 N2. entails_q q (\<G>_Fset_q q N1) (\<G>_Fset_q q N2)) (Red_I_\<G>_q q) (Red_F_\<G>_q q) goal (1 subgoal): 1. calculus Bot_F Inf_F (\<lambda>N1 N2. entails_q q (\<G>_Fset_q q N1) (\<G>_Fset_q q N2)) (Red_I_\<G>_q q) (Red_F_\<G>_q q) [PROOF STEP] . [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>B N. \<lbrakk>calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty; B \<in> Bot_F; empty_ord.saturated N; N \<Turnstile>\<inter>\<G> {B}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] have n_q_sat: "q_calc.saturated N" [PROOF STATE] proof (prove) goal (1 subgoal): 1. q_calc.saturated N [PROOF STEP] using q_in sat_int_to_sat_q sat_n [PROOF STATE] proof (prove) using this: q \<in> Q empty_ord.saturated ?N = (\<forall>qi\<in>Q. calculus.saturated Inf_F (Red_I_\<G>_q qi) ?N) empty_ord.saturated N goal (1 subgoal): 1. q_calc.saturated N [PROOF STEP] by simp [PROOF STATE] proof (state) this: q_calc.saturated N goal (1 subgoal): 1. \<And>B N. \<lbrakk>calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty; B \<in> Bot_F; empty_ord.saturated N; N \<Turnstile>\<inter>\<G> {B}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] interpret lifted_q_calc: tiebreaker_lifting Bot_F Inf_F Bot_G "entails_q q" "Inf_G_q q" "Red_I_q q" "Red_F_q q" "\<G>_F_q q" "\<G>_I_q q" [PROOF STATE] proof (prove) goal (1 subgoal): 1. tiebreaker_lifting Bot_F Inf_F Bot_G (entails_q q) (Inf_G_q q) (Red_I_q q) (Red_F_q q) (\<G>_F_q q) (\<G>_I_q q) Prec_F_g [PROOF STEP] using q_in [PROOF STATE] proof (prove) using this: q \<in> Q goal (1 subgoal): 1. tiebreaker_lifting Bot_F Inf_F Bot_G (entails_q q) (Inf_G_q q) (Red_I_q q) (Red_F_q q) (\<G>_F_q q) (\<G>_I_q q) Prec_F_g [PROOF STEP] by (simp add: standard_lifting_family) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>B N. \<lbrakk>calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty; B \<in> Bot_F; empty_ord.saturated N; N \<Turnstile>\<inter>\<G> {B}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] have n_lift_sat: "lifted_q_calc.calc.saturated N" [PROOF STATE] proof (prove) goal (1 subgoal): 1. local.lifted_q_calc.saturated N [PROOF STEP] using n_q_sat [PROOF STATE] proof (prove) using this: q_calc.saturated N goal (1 subgoal): 1. local.lifted_q_calc.saturated N [PROOF STEP] unfolding Red_I_\<G>_q_def lifted_q_calc.Red_I_\<G>_def lifted_q_calc.saturated_def q_calc.saturated_def [PROOF STATE] proof (prove) using this: Inf_from N \<subseteq> {\<iota> \<in> Inf_F. \<G>_I_q q \<iota> \<noteq> None \<and> the (\<G>_I_q q \<iota>) \<subseteq> Red_I_q q (lifted_q_calc.\<G>_Fset N) \<or> \<G>_I_q q \<iota> = None \<and> \<G>_F_q q (concl_of \<iota>) \<subseteq> lifted_q_calc.\<G>_Fset N \<union> Red_F_q q (lifted_q_calc.\<G>_Fset N)} goal (1 subgoal): 1. Inf_from N \<subseteq> {\<iota> \<in> Inf_F. \<G>_I_q q \<iota> \<noteq> None \<and> the (\<G>_I_q q \<iota>) \<subseteq> Red_I_q q (lifted_q_calc.\<G>_Fset N) \<or> \<G>_I_q q \<iota> = None \<and> \<G>_F_q q (concl_of \<iota>) \<subseteq> lifted_q_calc.\<G>_Fset N \<union> Red_F_q q (lifted_q_calc.\<G>_Fset N)} [PROOF STEP] by auto [PROOF STATE] proof (state) this: local.lifted_q_calc.saturated N goal (1 subgoal): 1. \<And>B N. \<lbrakk>calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty; B \<in> Bot_F; empty_ord.saturated N; N \<Turnstile>\<inter>\<G> {B}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] have ground_sat_n: "lifted_q_calc.ground.saturated (\<G>_Fset_q q N)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. lifted_q_calc.ground.saturated (lifted_q_calc.\<G>_Fset N) [PROOF STEP] by (rule lifted_q_calc.sat_imp_ground_sat[OF n_lift_sat]) (use n_lift_sat inf_subs ground.Inf_from_q_def in auto) [PROOF STATE] proof (state) this: lifted_q_calc.ground.saturated (lifted_q_calc.\<G>_Fset N) goal (1 subgoal): 1. \<And>B N. \<lbrakk>calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty; B \<in> Bot_F; empty_ord.saturated N; N \<Turnstile>\<inter>\<G> {B}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] have ground_n_entails_bot: "entails_\<G>_q q N {B}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. entails_q q (lifted_q_calc.\<G>_Fset N) (lifted_q_calc.\<G>_Fset {B}) [PROOF STEP] using q_in entails_bot [PROOF STATE] proof (prove) using this: q \<in> Q N \<Turnstile>\<inter>\<G> {B} goal (1 subgoal): 1. entails_q q (lifted_q_calc.\<G>_Fset N) (lifted_q_calc.\<G>_Fset {B}) [PROOF STEP] unfolding entails_\<G>_def [PROOF STATE] proof (prove) using this: q \<in> Q \<forall>q\<in>Q. entails_q q (\<G>_Fset_q q N) (\<G>_Fset_q q {B}) goal (1 subgoal): 1. entails_q q (lifted_q_calc.\<G>_Fset N) (lifted_q_calc.\<G>_Fset {B}) [PROOF STEP] by simp [PROOF STATE] proof (state) this: entails_q q (lifted_q_calc.\<G>_Fset N) (lifted_q_calc.\<G>_Fset {B}) goal (1 subgoal): 1. \<And>B N. \<lbrakk>calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty; B \<in> Bot_F; empty_ord.saturated N; N \<Turnstile>\<inter>\<G> {B}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] interpret statically_complete_calculus Bot_G "Inf_G_q q" "entails_q q" "Red_I_q q" "Red_F_q q" [PROOF STATE] proof (prove) goal (1 subgoal): 1. statically_complete_calculus Bot_G (Inf_G_q q) (entails_q q) (Red_I_q q) (Red_F_q q) [PROOF STEP] using stat_ref_G[rule_format, OF q_in] [PROOF STATE] proof (prove) using this: statically_complete_calculus Bot_G (Inf_G_q q) (entails_q q) (Red_I_q q) (Red_F_q q) goal (1 subgoal): 1. statically_complete_calculus Bot_G (Inf_G_q q) (entails_q q) (Red_I_q q) (Red_F_q q) [PROOF STEP] . [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>B N. \<lbrakk>calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty; B \<in> Bot_F; empty_ord.saturated N; N \<Turnstile>\<inter>\<G> {B}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] obtain BG where bg_in: "BG \<in> \<G>_F_q q B" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>BG. BG \<in> \<G>_F_q q B \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] using lifted_q_calc.Bot_map_not_empty[OF b_in] [PROOF STATE] proof (prove) using this: \<G>_F_q q B \<noteq> {} goal (1 subgoal): 1. (\<And>BG. BG \<in> \<G>_F_q q B \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: BG \<in> \<G>_F_q q B goal (1 subgoal): 1. \<And>B N. \<lbrakk>calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty; B \<in> Bot_F; empty_ord.saturated N; N \<Turnstile>\<inter>\<G> {B}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] then [PROOF STATE] proof (chain) picking this: BG \<in> \<G>_F_q q B [PROOF STEP] have "BG \<in> Bot_G" [PROOF STATE] proof (prove) using this: BG \<in> \<G>_F_q q B goal (1 subgoal): 1. BG \<in> Bot_G [PROOF STEP] using lifted_q_calc.Bot_map[OF b_in] [PROOF STATE] proof (prove) using this: BG \<in> \<G>_F_q q B \<G>_F_q q B \<subseteq> Bot_G goal (1 subgoal): 1. BG \<in> Bot_G [PROOF STEP] by blast [PROOF STATE] proof (state) this: BG \<in> Bot_G goal (1 subgoal): 1. \<And>B N. \<lbrakk>calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty; B \<in> Bot_F; empty_ord.saturated N; N \<Turnstile>\<inter>\<G> {B}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] then [PROOF STATE] proof (chain) picking this: BG \<in> Bot_G [PROOF STEP] have "\<exists>BG'\<in>Bot_G. BG' \<in> \<G>_Fset_q q N" [PROOF STATE] proof (prove) using this: BG \<in> Bot_G goal (1 subgoal): 1. \<exists>BG'\<in>Bot_G. BG' \<in> lifted_q_calc.\<G>_Fset N [PROOF STEP] using ground_sat_n ground_n_entails_bot statically_complete[of BG, OF _ ground_sat_n] bg_in lifted_q_calc.ground.entail_set_all_formulas[of "\<G>_Fset_q q N" "\<G>_Fset_q q {B}"] [PROOF STATE] proof (prove) using this: BG \<in> Bot_G lifted_q_calc.ground.saturated (lifted_q_calc.\<G>_Fset N) entails_q q (lifted_q_calc.\<G>_Fset N) (lifted_q_calc.\<G>_Fset {B}) \<lbrakk>BG \<in> Bot_G; entails_q q (lifted_q_calc.\<G>_Fset N) {BG}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_G. B' \<in> lifted_q_calc.\<G>_Fset N BG \<in> \<G>_F_q q B entails_q q (lifted_q_calc.\<G>_Fset N) (lifted_q_calc.\<G>_Fset {B}) = (\<forall>C\<in>lifted_q_calc.\<G>_Fset {B}. entails_q q (lifted_q_calc.\<G>_Fset N) {C}) goal (1 subgoal): 1. \<exists>BG'\<in>Bot_G. BG' \<in> lifted_q_calc.\<G>_Fset N [PROOF STEP] by simp [PROOF STATE] proof (state) this: \<exists>BG'\<in>Bot_G. BG' \<in> lifted_q_calc.\<G>_Fset N goal (1 subgoal): 1. \<And>B N. \<lbrakk>calculus Bot_F Inf_F (\<Turnstile>\<inter>\<G>) empty_ord.Red_I Red_F_\<G>_empty; B \<in> Bot_F; empty_ord.saturated N; N \<Turnstile>\<inter>\<G> {B}\<rbrakk> \<Longrightarrow> \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<exists>BG'\<in>Bot_G. BG' \<in> lifted_q_calc.\<G>_Fset N [PROOF STEP] show "\<exists>B'\<in> Bot_F. B' \<in> N" [PROOF STATE] proof (prove) using this: \<exists>BG'\<in>Bot_G. BG' \<in> lifted_q_calc.\<G>_Fset N goal (1 subgoal): 1. \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] using lifted_q_calc.Bot_cond [PROOF STATE] proof (prove) using this: \<exists>BG'\<in>Bot_G. BG' \<in> lifted_q_calc.\<G>_Fset N \<G>_F_q q ?C \<inter> Bot_G \<noteq> {} \<longrightarrow> ?C \<in> Bot_F goal (1 subgoal): 1. \<exists>B'\<in>Bot_F. B' \<in> N [PROOF STEP] by blast [PROOF STATE] proof (state) this: \<exists>B'\<in>Bot_F. B' \<in> N goal: No subgoals! [PROOF STEP] qed
Require Import Coq.Program.Program. Require Import Fiat.Common. (** * Various useful lemmas about logic *) (** We prove things here mainly for the purpose of [setoid_rewrite]ing with instances of [impl] and [iff]. *) Local Arguments impl / . Local Arguments flip / . Local Arguments pointwise_relation / . Local Hint Extern 1 => progress simpl in *. Local Hint Extern 1 => progress subst; eauto. (* WTF? *) Local Hint Extern 1 => progress destruct_head_hnf sig. Section forall_eq. (** We prove some lemmas about [forall] and [eq], for the benefit of setoid rewriting. *) Definition iff_remove_forall_eql A x (P : _ -> Prop) : iff (forall y : A, y = x -> P y) (P x). Proof. firstorder. Defined. Definition iff_remove_forall_eqr A x (P : _ -> Prop) : iff (forall y : A, x = y -> P y) (P x). Proof. firstorder. Defined. (** These versions are around twice as fast as the [iff] versions... not sure why. *) Definition remove_forall_eql A x (P : _ -> Prop) : flip impl (forall y : A, y = x -> P y) (P x) := proj2 (@iff_remove_forall_eql A x P). Definition remove_forall_eql' A x (P : _ -> Prop) : impl (forall y : A, y = x -> P y) (P x) := proj1 (@iff_remove_forall_eql A x P). Definition remove_forall_eqr A x (P : _ -> Prop) : flip impl (forall y : A, x = y -> P y) (P x) := proj2 (@iff_remove_forall_eqr A x P). Definition remove_forall_eqr' A x (P : _ -> Prop) : impl (forall y : A, x = y -> P y) (P x) := proj1 (@iff_remove_forall_eqr A x P). Section and. (** Variants for equalities with /\ *) Definition iff_remove_forall_eql_and A x (P : _ -> Prop) (Q : A -> Prop) : iff (forall y : A, (y = x /\ Q y) -> P y) (Q x -> P x). Proof. firstorder. Qed. Definition iff_remove_forall_eqr_and A x (P : _ -> Prop) (Q : A -> Prop) : iff (forall y : A, (x = y /\ Q y) -> P y) (Q x -> P x). Proof. firstorder. Qed. Definition iff_remove_forall_and_eql A x (P : _ -> Prop) (Q : A -> Prop) : iff (forall y : A, (Q y /\ y = x) -> P y) (Q x -> P x). Proof. firstorder. Qed. Definition iff_remove_forall_and_eqr A x (P : _ -> Prop) (Q : A -> Prop) : iff (forall y : A, (Q y /\ x = y) -> P y) (Q x -> P x). Proof. firstorder. Qed. Definition remove_forall_eql_and A x (P : _ -> Prop) (Q : A -> Prop) : flip impl (forall y : A, (y = x /\ Q y) -> P y) (Q x -> P x) := proj2 (@iff_remove_forall_eql_and A x P Q). Definition remove_forall_eql_and' A x (P : _ -> Prop) (Q : A -> Prop) : impl (forall y : A, (y = x /\ Q y) -> P y) (Q x -> P x) := proj1 (@iff_remove_forall_eql_and A x P Q). Definition remove_forall_eqr_and A x (P : _ -> Prop) (Q : A -> Prop) : flip impl (forall y : A, (x = y /\ Q y) -> P y) (Q x -> P x) := proj2 (@iff_remove_forall_eqr_and A x P Q). Definition remove_forall_eqr_and' A x (P : _ -> Prop) (Q : A -> Prop) : impl (forall y : A, (x = y /\ Q y) -> P y) (Q x -> P x) := proj1 (@iff_remove_forall_eqr_and A x P Q). Definition remove_forall_and_eql A x (P : _ -> Prop) (Q : A -> Prop) : flip impl (forall y : A, (Q y /\ y = x) -> P y) (Q x -> P x) := proj2 (@iff_remove_forall_and_eql A x P Q). Definition remove_forall_and_eql' A x (P : _ -> Prop) (Q : A -> Prop) : impl (forall y : A, (Q y /\ y = x) -> P y) (Q x -> P x) := proj1 (@iff_remove_forall_and_eql A x P Q). Definition remove_forall_and_eqr A x (P : _ -> Prop) (Q : A -> Prop) : flip impl (forall y : A, (Q y /\ x = y) -> P y) (Q x -> P x) := proj2 (@iff_remove_forall_and_eqr A x P Q). Definition remove_forall_and_eqr' A x (P : _ -> Prop) (Q : A -> Prop) : impl (forall y : A, (Q y /\ x = y) -> P y) (Q x -> P x) := proj1 (@iff_remove_forall_and_eqr A x P Q). End and. End forall_eq. Section exists_and_eq. (** And now with [exists] *) Definition iff_remove_exists_and_eql A x (P : _ -> Prop) : iff (exists y : A, P y /\ y = x) (P x). Proof. firstorder. Qed. Definition iff_remove_exists_and_eqr A x (P : _ -> Prop) : iff (exists y : A, P y /\ x = y) (P x). Proof. firstorder. Defined. Definition iff_remove_exists_eql_and A x (P : _ -> Prop) : iff (exists y : A, y = x /\ P y) (P x). Proof. firstorder. Qed. Definition iff_remove_exists_eqr_and A x (P : _ -> Prop) : iff (exists y : A, x = y /\ P y) (P x). Proof. firstorder. Defined. (** These versions are around twice as fast as the [iff] versions... not sure why. *) Definition remove_exists_and_eql A x (P : _ -> Prop) : flip impl (exists y : A, P y /\ y = x) (P x) := proj2 (@iff_remove_exists_and_eql A x P). Definition remove_exists_and_eql' A x (P : _ -> Prop) : impl (exists y : A, P y /\ y = x) (P x) := proj1 (@iff_remove_exists_and_eql A x P). Definition remove_exists_and_eqr A x (P : _ -> Prop) : flip impl (exists y : A, P y /\ x = y) (P x) := proj2 (@iff_remove_exists_and_eqr A x P). Definition remove_exists_and_eqr' A x (P : _ -> Prop) : impl (exists y : A, P y /\ x = y) (P x) := proj1 (@iff_remove_exists_and_eqr A x P). Definition remove_exists_eql_and A x (P : _ -> Prop) : flip impl (exists y : A, y = x /\ P y) (P x) := proj2 (@iff_remove_exists_eql_and A x P). Definition remove_exists_eql_and' A x (P : _ -> Prop) : impl (exists y : A, y = x /\ P y) (P x) := proj1 (@iff_remove_exists_eql_and A x P). Definition remove_exists_eqr_and A x (P : _ -> Prop) : flip impl (exists y : A, x = y /\ P y) (P x) := proj2 (@iff_remove_exists_eqr_and A x P). Definition remove_exists_eqr_and' A x (P : _ -> Prop) : impl (exists y : A, x = y /\ P y) (P x) := proj1 (@iff_remove_exists_eqr_and A x P). End exists_and_eq. Lemma forall_sig_prop A P (Q : _ -> Prop) : (forall x : @sig A P, Q x) <-> (forall x y, Q (exist P x y)). Proof. firstorder. Defined. Lemma forall_commute A P Q (R : forall x : A, P x -> Q x -> Prop) : (forall x y z, R x y z) <-> (forall x z y, R x y z). Proof. firstorder. Defined. Lemma flip_a_impl_b_impl_a (A : Prop) B : flip impl (B -> A) A. Proof. firstorder. Defined. Lemma exists_sig A P Q : (exists x : @sig A P, Q x) <-> (exists x y, Q (exist P x y)). Proof. firstorder eauto. Defined. Lemma exists_and_comm A B Q : (exists x : A, B /\ Q x) <-> (B /\ exists x : A, Q x). Proof. firstorder. Defined. Lemma exists_and_assoc A B Q : (exists x : A, (Q x /\ B)) <-> ((exists x : A, Q x) /\ B). Proof. firstorder. Defined. Lemma impl_exists A P Q (H : exists x : A, impl Q (P x)) : impl Q (exists x : A, P x). Proof. firstorder. Defined. #[global] Hint Resolve impl_exists : typeclass_instances.
-- | The Metropolis transition. module Strategy.Metropolis (metropolis) where import Control.Monad.State.Strict import Data.Maybe import Numeric.LinearAlgebra import Math.Probably.Sampler import Math.Probably.Types import Math.Probably.Utils -- | The Metropolis transition for a symmetric proposal. Uses a simple -- spherical Gaussian with standard deviation specified by the first -- argument. metropolis :: Maybe Double -> Transition Double metropolis e = do Chain current@(ds, cs) target _ t <- get let sd = fromMaybe t e pcs <- lift $ perturb cs sd zc <- lift unit let next = nextState target current (ds, pcs) sd zc put $ Chain next target (logObjective target next) sd return next perturb :: ContinuousParams -> Double -> Prob (ContinuousParams) perturb q sd = fmap fromList $ mapM (`normal` sd) (toList q) acceptRatio :: Target -> Parameters -> Parameters -> Double -> Double acceptRatio target c@(_, current) p@(_, proposed) sd = exp . min 0 $ logObjective target p + log (sphereGauss current proposed sd) - logObjective target c - log (sphereGauss proposed current sd) nextState :: Target -> Parameters -> Parameters -> Double -> Double -> Parameters nextState target current proposed sd z | z < acceptProb = proposed | otherwise = current where ratio = acceptRatio target current proposed sd acceptProb | isNaN ratio = 0 | otherwise = ratio
function q = mat2quat(mat,varargin) % converts direction cosine matrix to quaternion % % Syntax % q = mat2quat(mat) % % Input % mat - vector of matrixes % % Output % q - @quaternion % % See also % % quaternion_matrix Euler axis2quat hr2quat % % Description % Wertz says to the algo similar to this with largest divisor % q4 = 1/2*sqrt((1+mat(1,1)+mat(2,2)+mat(3,3))); % Eqn 12-14a - c % Quat(1) = (mat(2,3)-mat(3,2))/q4/4; % Quat(2) = (mat(3,1)-mat(1,3))/q4/4; % Quat(3) = (mat(1,2)-mat(2,1))/q4/4; % Quat(4) = q4 Quat=zeros(4,1); %Compute absolute values of the four quaternions from diags of Eqn 12-13 %absQ=0.5*sqrt([1 -1 -1;-1 1 -1;-1 -1 1;1 1 1]*diag(mat)+1); absQ(1,:) = 0.5 * sqrt(1+mat(1,1,:)+mat(2,2,:)+mat(3,3,:)); absQ(2,:) = 0.5 * sqrt(1-mat(1,1,:)-mat(2,2,:)+mat(3,3,:)); absQ(3,:) = 0.5 * sqrt(1+mat(1,1,:)-mat(2,2,:)-mat(3,3,:)); absQ(4,:) = 0.5 * sqrt(1-mat(1,1,:)+mat(2,2,:)-mat(3,3,:)); [~,ind]=max(absQ); % Select biggest for best accuracy qind = ind == 1; if any(qind) Quat(1,qind)=absQ(1,qind); Quat(2,qind)=squeeze((mat(2,3,qind)-mat(3,2,qind))).'.*0.25./absQ(1,qind); Quat(3,qind)=squeeze((mat(3,1,qind)-mat(1,3,qind))).'.*0.25./absQ(1,qind); Quat(4,qind)=squeeze((mat(1,2,qind)-mat(2,1,qind))).'.*0.25./absQ(1,qind); end qind = ind == 2; if any(qind) Quat(1,qind)=squeeze(mat(1,2,qind)-mat(2,1,qind)).'.*0.25./absQ(2,qind); Quat(2,qind)=squeeze(mat(3,1,qind)+mat(1,3,qind)).'.*0.25./absQ(2,qind); Quat(3,qind)=squeeze(mat(3,2,qind)+mat(2,3,qind)).'.*0.25./absQ(2,qind); Quat(4,qind)=absQ(2,qind); end qind = ind == 3; if any(qind) Quat(1,qind)=squeeze(mat(2,3,qind)-mat(3,2,qind)).'.*0.25./absQ(3,qind); Quat(2,qind)=absQ(3,qind); Quat(3,qind)=squeeze(mat(1,2,qind)+mat(2,1,qind)).'.*0.25./absQ(3,qind); Quat(4,qind)=squeeze(mat(3,1,qind)+mat(1,3,qind)).'.*0.25./absQ(3,qind); end qind = ind == 4; if any(qind) Quat(1,qind)=squeeze(mat(3,1,qind)-mat(1,3,qind)).'.*0.25./absQ(4,qind); Quat(2,qind)=squeeze(mat(1,2,qind)+mat(2,1,qind)).'.*0.25./absQ(4,qind); Quat(3,qind)=absQ(4,qind); Quat(4,qind)=squeeze(mat(2,3,qind)+mat(3,2,qind)).'.*0.25./absQ(4,qind); end q = quaternion(real(Quat)); q = q./norm(q); q = inv(q).';
If $n > 1$, then the sum of the $n$th roots of $c$ is $0$.
# Use baremodule to shave off a few KB from the serialized `.ji` file baremodule CUTENSOR_CUDA112_jll using Base using Base: UUID import JLLWrappers JLLWrappers.@generate_main_file_header("CUTENSOR_CUDA112") JLLWrappers.@generate_main_file("CUTENSOR_CUDA112", UUID("973b338e-f8c7-52f3-bf7b-688ce4a92402")) end # module CUTENSOR_CUDA112_jll
[STATEMENT] lemma ufa_compress_aux: assumes I: "ufa_invar l" assumes L[simp]: "x<length l" shows "ufa_invar (l[x := rep_of l x])" and "\<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ufa_invar (l[x := rep_of l x]) &&& \<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] proof - [PROOF STATE] proof (state) goal (2 subgoals): 1. ufa_invar (l[x := rep_of l x]) 2. \<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] { [PROOF STATE] proof (state) goal (2 subgoals): 1. ufa_invar (l[x := rep_of l x]) 2. \<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] fix i [PROOF STATE] proof (state) goal (2 subgoals): 1. ufa_invar (l[x := rep_of l x]) 2. \<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] assume "i<length (l[x := rep_of l x])" [PROOF STATE] proof (state) this: i < length (l[x := rep_of l x]) goal (2 subgoals): 1. ufa_invar (l[x := rep_of l x]) 2. \<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] hence IL: "i<length l" [PROOF STATE] proof (prove) using this: i < length (l[x := rep_of l x]) goal (1 subgoal): 1. i < length l [PROOF STEP] by simp [PROOF STATE] proof (state) this: i < length l goal (2 subgoals): 1. ufa_invar (l[x := rep_of l x]) 2. \<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] have G1: "l[x := rep_of l x] ! i < length (l[x := rep_of l x])" [PROOF STATE] proof (prove) goal (1 subgoal): 1. l[x := rep_of l x] ! i < length (l[x := rep_of l x]) [PROOF STEP] using I IL [PROOF STATE] proof (prove) using this: ufa_invar l i < length l goal (1 subgoal): 1. l[x := rep_of l x] ! i < length (l[x := rep_of l x]) [PROOF STEP] by (auto dest: ufa_invarD[OF I] simp: nth_list_update rep_of_bound) [PROOF STATE] proof (state) this: l[x := rep_of l x] ! i < length (l[x := rep_of l x]) goal (2 subgoals): 1. ufa_invar (l[x := rep_of l x]) 2. \<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] from I IL [PROOF STATE] proof (chain) picking this: ufa_invar l i < length l [PROOF STEP] have G2: "rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i)" [PROOF STATE] proof (prove) using this: ufa_invar l i < length l goal (1 subgoal): 1. rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) [PROOF STEP] proof (induct rule: rep_of_induct) [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>i. \<lbrakk>ufa_invar l; i < length l; l ! i = i\<rbrakk> \<Longrightarrow> rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) 2. \<And>i. \<lbrakk>ufa_invar l; i < length l; l ! i \<noteq> i; rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i)\<rbrakk> \<Longrightarrow> rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) [PROOF STEP] case (base i) [PROOF STATE] proof (state) this: ufa_invar l i < length l l ! i = i goal (2 subgoals): 1. \<And>i. \<lbrakk>ufa_invar l; i < length l; l ! i = i\<rbrakk> \<Longrightarrow> rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) 2. \<And>i. \<lbrakk>ufa_invar l; i < length l; l ! i \<noteq> i; rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i)\<rbrakk> \<Longrightarrow> rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) [PROOF STEP] thus ?case [PROOF STATE] proof (prove) using this: ufa_invar l i < length l l ! i = i goal (1 subgoal): 1. rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) [PROOF STEP] apply (cases "x=i") [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<lbrakk>ufa_invar l; i < length l; l ! i = i; x = i\<rbrakk> \<Longrightarrow> rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) 2. \<lbrakk>ufa_invar l; i < length l; l ! i = i; x \<noteq> i\<rbrakk> \<Longrightarrow> rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) [PROOF STEP] apply (auto intro: rep_of.domintros simp: rep_of_refl) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done [PROOF STATE] proof (state) this: rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) goal (1 subgoal): 1. \<And>i. \<lbrakk>ufa_invar l; i < length l; l ! i \<noteq> i; rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i)\<rbrakk> \<Longrightarrow> rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>i. \<lbrakk>ufa_invar l; i < length l; l ! i \<noteq> i; rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i)\<rbrakk> \<Longrightarrow> rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) [PROOF STEP] case (step i) [PROOF STATE] proof (state) this: ufa_invar l i < length l l ! i \<noteq> i rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i) goal (1 subgoal): 1. \<And>i. \<lbrakk>ufa_invar l; i < length l; l ! i \<noteq> i; rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i)\<rbrakk> \<Longrightarrow> rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) [PROOF STEP] hence D: "rep_of_dom (l[x := rep_of l x], i)" [PROOF STATE] proof (prove) using this: ufa_invar l i < length l l ! i \<noteq> i rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i) goal (1 subgoal): 1. rep_of_dom (l[x := rep_of l x], i) [PROOF STEP] apply - [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>ufa_invar l; i < length l; l ! i \<noteq> i; rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i)\<rbrakk> \<Longrightarrow> rep_of_dom (l[x := rep_of l x], i) [PROOF STEP] apply (rule rep_of.domintros) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>ufa_invar l; i < length l; l ! i \<noteq> i; rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i); l[x := rep_of l x] ! i \<noteq> i\<rbrakk> \<Longrightarrow> rep_of_dom (l[x := rep_of l x], l[x := rep_of l x] ! i) [PROOF STEP] apply (cases "x=i") [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<lbrakk>ufa_invar l; i < length l; l ! i \<noteq> i; rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i); l[x := rep_of l x] ! i \<noteq> i; x = i\<rbrakk> \<Longrightarrow> rep_of_dom (l[x := rep_of l x], l[x := rep_of l x] ! i) 2. \<lbrakk>ufa_invar l; i < length l; l ! i \<noteq> i; rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i); l[x := rep_of l x] ! i \<noteq> i; x \<noteq> i\<rbrakk> \<Longrightarrow> rep_of_dom (l[x := rep_of l x], l[x := rep_of l x] ! i) [PROOF STEP] apply (auto intro: rep_of.domintros simp: rep_of_min) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done [PROOF STATE] proof (state) this: rep_of_dom (l[x := rep_of l x], i) goal (1 subgoal): 1. \<And>i. \<lbrakk>ufa_invar l; i < length l; l ! i \<noteq> i; rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i)\<rbrakk> \<Longrightarrow> rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) [PROOF STEP] thus ?case [PROOF STATE] proof (prove) using this: rep_of_dom (l[x := rep_of l x], i) goal (1 subgoal): 1. rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) [PROOF STEP] apply simp [PROOF STATE] proof (prove) goal (1 subgoal): 1. rep_of_dom (l[x := rep_of l x], i) \<Longrightarrow> rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] using step [PROOF STATE] proof (prove) using this: ufa_invar l i < length l l ! i \<noteq> i rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i) goal (1 subgoal): 1. rep_of_dom (l[x := rep_of l x], i) \<Longrightarrow> rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] apply - [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>rep_of_dom (l[x := rep_of l x], i); ufa_invar l; i < length l; l ! i \<noteq> i; rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i)\<rbrakk> \<Longrightarrow> rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] apply (subst rep_of.psimps[OF D]) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>rep_of_dom (l[x := rep_of l x], i); ufa_invar l; i < length l; l ! i \<noteq> i; rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i)\<rbrakk> \<Longrightarrow> (if l[x := rep_of l x] ! i = i then i else rep_of (l[x := rep_of l x]) (l[x := rep_of l x] ! i)) = rep_of l i [PROOF STEP] apply (cases "x=i") [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<lbrakk>rep_of_dom (l[x := rep_of l x], i); ufa_invar l; i < length l; l ! i \<noteq> i; rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i); x = i\<rbrakk> \<Longrightarrow> (if l[x := rep_of l x] ! i = i then i else rep_of (l[x := rep_of l x]) (l[x := rep_of l x] ! i)) = rep_of l i 2. \<lbrakk>rep_of_dom (l[x := rep_of l x], i); ufa_invar l; i < length l; l ! i \<noteq> i; rep_of (l[x := rep_of l x]) (l ! i) = rep_of l (l ! i) \<and> rep_of_dom (l[x := rep_of l x], l ! i); x \<noteq> i\<rbrakk> \<Longrightarrow> (if l[x := rep_of l x] ! i = i then i else rep_of (l[x := rep_of l x]) (l[x := rep_of l x] ! i)) = rep_of l i [PROOF STEP] apply (auto simp: rep_of_min rep_of_idx) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>rep_of_dom (l[i := rep_of l i], i); ufa_invar l; i < length l; l ! i \<noteq> i; x = i; rep_of (l[i := rep_of l i]) (l ! i) = rep_of l i; rep_of_dom (l[i := rep_of l i], l ! i); rep_of l i \<noteq> i\<rbrakk> \<Longrightarrow> rep_of (l[i := rep_of l i]) (rep_of l i) = rep_of l i [PROOF STEP] apply (subst rep_of.psimps[where i="rep_of l i"]) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<lbrakk>rep_of_dom (l[i := rep_of l i], i); ufa_invar l; i < length l; l ! i \<noteq> i; x = i; rep_of (l[i := rep_of l i]) (l ! i) = rep_of l i; rep_of_dom (l[i := rep_of l i], l ! i); rep_of l i \<noteq> i\<rbrakk> \<Longrightarrow> rep_of_dom (l[i := rep_of l i], rep_of l i) 2. \<lbrakk>rep_of_dom (l[i := rep_of l i], i); ufa_invar l; i < length l; l ! i \<noteq> i; x = i; rep_of (l[i := rep_of l i]) (l ! i) = rep_of l i; rep_of_dom (l[i := rep_of l i], l ! i); rep_of l i \<noteq> i\<rbrakk> \<Longrightarrow> (if l[i := rep_of l i] ! rep_of l i = rep_of l i then rep_of l i else rep_of (l[i := rep_of l i]) (l[i := rep_of l i] ! rep_of l i)) = rep_of l i [PROOF STEP] apply (auto intro: rep_of.domintros simp: rep_of_min) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done [PROOF STATE] proof (state) this: rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) goal (2 subgoals): 1. ufa_invar (l[x := rep_of l x]) 2. \<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] note G1 G2 [PROOF STATE] proof (state) this: l[x := rep_of l x] ! i < length (l[x := rep_of l x]) rep_of (l[x := rep_of l x]) i = rep_of l i \<and> rep_of_dom (l[x := rep_of l x], i) goal (2 subgoals): 1. ufa_invar (l[x := rep_of l x]) 2. \<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] } [PROOF STATE] proof (state) this: ?i2 < length (l[x := rep_of l x]) \<Longrightarrow> l[x := rep_of l x] ! ?i2 < length (l[x := rep_of l x]) ?i2 < length (l[x := rep_of l x]) \<Longrightarrow> rep_of (l[x := rep_of l x]) ?i2 = rep_of l ?i2 \<and> rep_of_dom (l[x := rep_of l x], ?i2) goal (2 subgoals): 1. ufa_invar (l[x := rep_of l x]) 2. \<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] note G=this [PROOF STATE] proof (state) this: ?i2 < length (l[x := rep_of l x]) \<Longrightarrow> l[x := rep_of l x] ! ?i2 < length (l[x := rep_of l x]) ?i2 < length (l[x := rep_of l x]) \<Longrightarrow> rep_of (l[x := rep_of l x]) ?i2 = rep_of l ?i2 \<and> rep_of_dom (l[x := rep_of l x], ?i2) goal (2 subgoals): 1. ufa_invar (l[x := rep_of l x]) 2. \<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] thus "\<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i" [PROOF STATE] proof (prove) using this: ?i2 < length (l[x := rep_of l x]) \<Longrightarrow> l[x := rep_of l x] ! ?i2 < length (l[x := rep_of l x]) ?i2 < length (l[x := rep_of l x]) \<Longrightarrow> rep_of (l[x := rep_of l x]) ?i2 = rep_of l ?i2 \<and> rep_of_dom (l[x := rep_of l x], ?i2) goal (1 subgoal): 1. \<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i [PROOF STEP] by auto [PROOF STATE] proof (state) this: \<forall>i<length l. rep_of (l[x := rep_of l x]) i = rep_of l i goal (1 subgoal): 1. ufa_invar (l[x := rep_of l x]) [PROOF STEP] from G [PROOF STATE] proof (chain) picking this: ?i2 < length (l[x := rep_of l x]) \<Longrightarrow> l[x := rep_of l x] ! ?i2 < length (l[x := rep_of l x]) ?i2 < length (l[x := rep_of l x]) \<Longrightarrow> rep_of (l[x := rep_of l x]) ?i2 = rep_of l ?i2 \<and> rep_of_dom (l[x := rep_of l x], ?i2) [PROOF STEP] show "ufa_invar (l[x := rep_of l x])" [PROOF STATE] proof (prove) using this: ?i2 < length (l[x := rep_of l x]) \<Longrightarrow> l[x := rep_of l x] ! ?i2 < length (l[x := rep_of l x]) ?i2 < length (l[x := rep_of l x]) \<Longrightarrow> rep_of (l[x := rep_of l x]) ?i2 = rep_of l ?i2 \<and> rep_of_dom (l[x := rep_of l x], ?i2) goal (1 subgoal): 1. ufa_invar (l[x := rep_of l x]) [PROOF STEP] by (auto simp: ufa_invar_def) [PROOF STATE] proof (state) this: ufa_invar (l[x := rep_of l x]) goal: No subgoals! [PROOF STEP] qed
module IR.StackSet import IR import IR.Lens manage : Eq wid => wid -> Workspace wid -> Workspace wid manage wid (MkWorkspace l Nothing) = MkWorkspace l (Just (MkStack wid [] [])) manage wid (MkWorkspace l (Just (MkStack wid' a b))) = MkWorkspace l (Just (MkStack wid a (wid' :: b))) integrate : (s : Stack wid) -> Vect (stackLength s) wid integrate (MkStack x ys zs) = rewrite plusSuccRightSucc (length ys) (length zs) in reverse (fromList ys) ++ x :: fromList zs member : Eq wid => wid -> StackSet wid sid -> Bool member wid s = maybe False (\stack => elem wid (integrate stack)) (workspaceStack' . screenWorkspace' . stackSetCurrent' ^$ s) filter : (wid -> Bool) -> Stack wid -> Maybe (Stack wid) filter p (MkStack f ls rs) = case filter p (f::rs) of f'::rs' => Just (MkStack f' (filter p ls) rs') [] => case filter p ls of f'::ls' => Just (MkStack f' ls' []) [] => Nothing stackSetStack : Lens (StackSet wid sid) (Maybe (Stack wid)) stackSetStack = workspaceStack' . screenWorkspace' . stackSetCurrent' -- TODO: Use more than stackSetCurrent' delete : Eq wid => wid -> StackSet wid sid -> StackSet wid sid delete wid = stackSetStack ^%= (>>= filter (/= wid)) insertUp : Eq wid => wid -> StackSet wid sid -> StackSet wid sid insertUp wid s = if member wid s then s else insert where insert = workspaceStack' . screenWorkspace' . stackSetCurrent' ^%= Just . maybe (MkStack wid [] []) (\(MkStack t l r) => MkStack wid l (t::r)) $ s modify' : (Stack wid -> Stack wid) -> StackSet wid sid -> StackSet wid sid modify' f = stackSetStack ^%= map f stackSetPeek : StackSet wid sid -> Maybe wid stackSetPeek ss = map (\s => stackFocus' ^$ s) (stackSetStack ^$ ss) reverseStack : Stack wid -> Stack wid reverseStack (MkStack t ls rs) = MkStack t rs ls focusUp' : Stack wid -> Stack wid focusUp' (MkStack t [] []) = MkStack t [] [] focusUp' (MkStack t (l::ls) rs) = MkStack l ls (t::rs) focusUp' (MkStack t [] rs) = let (x::xs) = reverse (t::fromList rs) in MkStack x (toList xs) [] focusDown' : Stack wid -> Stack wid focusDown' = reverseStack . focusUp' . reverseStack focusDown : StackSet wid sid -> StackSet wid sid focusDown = modify' focusDown' focusUp : StackSet wid sid -> StackSet wid sid focusUp = modify' focusUp' focusWindow : Eq wid => wid -> StackSet wid sid -> StackSet wid sid focusWindow wid s = fromMaybe s (find ((== Just wid) . stackSetPeek) (take (maybe 0 stackLength (stackSetStack ^$ s)) (iterate focusUp s))) swapUp' : Stack wid -> Stack wid swapUp' (MkStack t (l::ls) rs) = MkStack t ls (l::rs) swapUp' (MkStack t [] rs) = MkStack t (reverse rs) [] swapUp : StackSet wid sid -> StackSet wid sid swapUp = modify' swapUp' swapDown : StackSet wid sid -> StackSet wid sid swapDown = modify' (reverseStack . swapUp' . reverseStack) windows : (StackSet wid sid -> StackSet wid sid) -> { [IR wid sid, STATE (IRState wid sid)] } Eff () windows f = do update (irStateStackSet' ^%= f) runLayout
struct ModelParam{p, T, V <: AbstractVector{T}, P <: Tuple} <: parameter{T} v::V Θ::P end function ModelParam(::Type{Val{p}}, x::V, Θ::P) where {p, T, V <: AbstractVector{T}, P <: Tuple} ModelParam{p, T, V, P}(x, Θ) end log_jacobian(A::ModelParam) = sum(log_jacobian.(A.Θ)) update!(A::ModelParam) = update!.(A.Θ) Base.size(A::ModelParam{p}) where p = ( p, ) Base.length(A::ModelParam{p}) where p = p Base.@pure param_length(x::Tuple) = Val{sum(length.(x))} @generated cum_inds(x::Tuple{P}) where P = tuple(cumsum([ConstrainedParameters.type_length.(P)...])...) construct(Θ::Tuple, ::Type{Val{p}} = param_length(Θ)) where p = construct(SlidingVec(zeros(p,1),0,p), Θ, Val{p}) sconstruct(Θ::Tuple, ::Type{Val{p}} = param_length(Θ)) where p = construct(SVector{p}(zeros(p)), Θ, Val{p}) function construct(x::V, Θ::P, ::Type{Val{p}} = param_length(Θ)) where {p, T, V <: AbstractVector{T}, P <: Tuple} ModelParam(Val{p}, x, construct.(Θ, (x,), cum_inds(Θ))) end function log_density(x::AbstractVector, θ::Tuple, data, ::Type{p} = param_length(θ)) where p param = construct(x, θ, p) log_jacobian(param) + Main.log_density(data, param.Θ...) end function log_density(Θ::ModelParam, data) log_jacobian(Θ) + Main.log_density(data, Θ.Θ...) end function log_density(x::AbstractVector, Θ::ModelParam, data) Θ.v .= x update!(Θ) log_jacobian(Θ) + Main.log_density(data, Θ.Θ...) end
#pragma once #include <optional> #include <sam.h> #include <gsl/span> #include "clocks.h" #include "utils.h" namespace mcu { class I2cMaster { public: I2cMaster(Sercom* sercom, const mcu::ClockGenerator& clock, const mcu::ClockGenerator& slowClock, unsigned frequency = 100000) :port{sercom->I2CM} { int sercomIndex = mcu::util::getSercomIndex(sercom); PM->APBCMASK.reg |= 1 << (PM_APBCMASK_SERCOM0_Pos + sercomIndex); clock.routeToPeripheral(GCLK_CLKCTRL_ID_SERCOM0_CORE_Val + sercomIndex); slowClock.routeToPeripheral(GCLK_CLKCTRL_ID_SERCOMX_SLOW_Val); port.CTRLA.reg = SERCOM_I2CM_CTRLA_MODE_I2C_MASTER; (void)port.CTRLB.reg; volatile uint32_t ctrla = port.CTRLA.reg; port.CTRLB.reg = 0; port.BAUD.reg = computeBaud(frequency, clock.frequency); while (port.STATUS.bit.SYNCBUSY); port.CTRLA.bit.ENABLE = true; while (port.STATUS.bit.SYNCBUSY); port.STATUS.bit.BUSSTATE = BusstateIdle; } std::optional<std::byte> readReg(uint8_t slaveAddress, uint8_t reg) { port.ADDR.reg = (slaveAddress << 1) | 0; while (port.INTFLAG.reg == 0); port.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB; if (port.STATUS.reg & (StatusErrorMask | SERCOM_I2CM_STATUS_RXNACK) != 0) { if (port.STATUS.bit.BUSSTATE == BusstateOwner) port.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop); return std::nullopt; } port.DATA.reg = reg; while (port.INTFLAG.reg == 0); port.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB; if (port.STATUS.reg & StatusErrorMask) { if (port.STATUS.bit.BUSSTATE == BusstateOwner) port.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop); return std::nullopt; } port.ADDR.reg = (slaveAddress << 1) | 1; while (port.INTFLAG.reg == 0); port.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB; if (port.STATUS.reg & (StatusErrorMask | SERCOM_I2CM_STATUS_RXNACK) != 0) { if (port.STATUS.bit.BUSSTATE == BusstateOwner) port.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop); return std::nullopt; } std::byte result = static_cast<std::byte>(port.DATA.reg); port.CTRLB.reg = SERCOM_I2CM_CTRLB_ACKACT | SERCOM_I2CM_CTRLB_CMD(CommandStop); return result; } bool writeReg(uint8_t slaveAddress, uint8_t reg, std::byte data) { port.ADDR.reg = (slaveAddress << 1) | 0; while (port.INTFLAG.reg == 0); port.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB; if (port.STATUS.reg & (StatusErrorMask | SERCOM_I2CM_STATUS_RXNACK) != 0) { if (port.STATUS.bit.BUSSTATE == BusstateOwner) port.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop); return false; } port.DATA.reg = reg; while (port.INTFLAG.reg == 0); port.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB; if (port.STATUS.reg & (StatusErrorMask | SERCOM_I2CM_STATUS_RXNACK) != 0) { if (port.STATUS.bit.BUSSTATE == BusstateOwner) port.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop); return false; } port.DATA.reg = static_cast<uint8_t>(data); while (port.INTFLAG.reg == 0); port.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB; if (port.STATUS.reg & (StatusErrorMask) != 0) { if (port.STATUS.bit.BUSSTATE == BusstateOwner) port.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop); return false; } port.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop); return true; } private: SercomI2cm& port; static constexpr unsigned CommandRead = 0x2; static constexpr unsigned CommandStop = 0x3; static constexpr unsigned BusstateIdle = 0x1; static constexpr unsigned BusstateOwner = 0x2; static constexpr unsigned StatusErrorMask = SERCOM_I2CM_STATUS_ARBLOST; static constexpr unsigned i2cRise = 215; static constexpr uint16_t computeBaud(unsigned desiredFrequency, unsigned coreFrequency) { // coreFreq - (desiredFreq * 10) - (coreFreq * desiredFreq * i2cRise) // BAUD + BAUDLOW = ------------------------------------------------------------------ // desiredFreq int baudSum = (((coreFrequency - (desiredFrequency * 10) - (i2cRise * (desiredFrequency / 100) * (coreFrequency / 1000) / 10000)) * 10 + 5) / (desiredFrequency * 10)); assert(2 <= baudSum && baudSum <= 0xff*2); if (baudSum % 2 == 1) return (baudSum / 2) | ((baudSum / 2 + 1) << 8); else return baudSum / 2; } }; }
State Before: μ : YoungDiagram x : ℕ hx : x ∈ rowLens μ ⊢ 0 < x State After: μ : YoungDiagram x : ℕ hx : ∃ a, a ∈ List.range (colLen μ 0) ∧ rowLen μ a = x ⊢ 0 < x Tactic: rw [rowLens, List.mem_map] at hx State Before: μ : YoungDiagram x : ℕ hx : ∃ a, a ∈ List.range (colLen μ 0) ∧ rowLen μ a = x ⊢ 0 < x State After: case intro.intro μ : YoungDiagram i : ℕ hi : i ∈ List.range (colLen μ 0) ⊢ 0 < rowLen μ i Tactic: obtain ⟨i, hi, rfl : μ.rowLen i = x⟩ := hx State Before: case intro.intro μ : YoungDiagram i : ℕ hi : i ∈ List.range (colLen μ 0) ⊢ 0 < rowLen μ i State After: no goals Tactic: rwa [List.mem_range, ← mem_iff_lt_colLen, mem_iff_lt_rowLen] at hi
The Tupolev Tu @-@ 73 jet @-@ engined bomber project was suffering delays in early 1947 and Tupolev suggested re @-@ engining the Tu @-@ 2 medium bomber with imported British Rolls @-@ Royce Nene jet engines to produce a jet bomber as quickly as possible . Design work began well before official approval was received on 31 May 1947 for one Tu @-@ 2S to be converted in the OKB 's workshop and another five to be converted at Zavod ( Factory ) Nr. 23 , but construction of the prototype had already begun in early May under the bureau designation Tu @-@ 77 .
install.packages("R.utils") install.packages("gridExtra") source("http://www.bioconductor.org/biocLite.R") biocLite("affy") biocLite("simpleaffy") biocLite("scales") biocLite("limma") biocLite("SAGx") biocLite("Heatplus") biocLite("topGO")
#include "ccv.h" #ifdef HAVE_CBLAS #include <cblas.h> #endif double ccv_trace(ccv_matrix_t* mat) { return 0; } double ccv_norm(ccv_matrix_t* mat, int type) { return 0; } double ccv_normalize(ccv_matrix_t* a, ccv_matrix_t** b, int btype, int l_type) { ccv_dense_matrix_t* da = ccv_get_dense_matrix(a); assert(CCV_GET_CHANNEL(da->type) == CCV_C1); char identifier[20]; memset(identifier, 0, 20); snprintf(identifier, 20, "ccv_normalize(%d)", l_type); uint64_t sig = (da->sig == 0) ? 0 : ccv_matrix_generate_signature(identifier, 20, da->sig, 0); btype = (btype == 0) ? CCV_GET_DATA_TYPE(da->type) | CCV_C1 : CCV_GET_DATA_TYPE(btype) | CCV_C1; ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, da->rows, da->cols, CCV_ALL_DATA_TYPE | CCV_C1, btype, sig); ccv_cache_return(db, 0); double sum = 0; int i, j; unsigned char* a_ptr = da->data.ptr; unsigned char* b_ptr = db->data.ptr; switch (l_type) { case CCV_L2_NORM: #define for_block(__for_set, __for_get) \ for (i = 0; i < da->rows; i++) \ { \ for (j = 0; j < da->cols; j++) \ sum += __for_get(a_ptr, j, 0) * __for_get(a_ptr, j, 0); \ a_ptr += da->step; \ } \ sum = sqrt(sum); \ double inv = 1.0 / sqrt(sum); \ a_ptr = da->data.ptr; \ for (i = 0; i < da->rows; i++) \ { \ for (j = 0; j < da->cols; j++) \ __for_set(b_ptr, j, __for_get(a_ptr, j, 0) * inv, 0); \ a_ptr += da->step; \ b_ptr += db->step; \ } ccv_matrix_setter(db->type, ccv_matrix_getter, da->type, for_block); #undef for_block break; } return sum; } double ccv_sum(ccv_matrix_t* mat) { ccv_dense_matrix_t* dmt = ccv_get_dense_matrix(mat); double sum = 0; unsigned char* m_ptr = dmt->data.ptr; int i, j; #define for_block(dummy, __for_get) \ for (i = 0; i < dmt->rows; i++) \ { \ for (j = 0; j < dmt->cols; j++) \ sum += __for_get(m_ptr, j, 0); \ m_ptr += dmt->step; \ } ccv_matrix_getter(dmt->type, for_block); #undef for_block return sum; } void ccv_zero(ccv_matrix_t* mat) { ccv_dense_matrix_t* dmt = ccv_get_dense_matrix(mat); memset(dmt->data.ptr, 0, dmt->step * dmt->rows); } void ccv_substract(ccv_matrix_t* a, ccv_matrix_t* b, ccv_matrix_t** c, int type) { ccv_dense_matrix_t* da = ccv_get_dense_matrix(a); ccv_dense_matrix_t* db = ccv_get_dense_matrix(b); assert(da->rows == db->rows && da->cols == db->cols && CCV_GET_DATA_TYPE(da->type) == CCV_GET_DATA_TYPE(db->type) && CCV_GET_CHANNEL(da->type) == CCV_GET_CHANNEL(db->type)); uint64_t sig = ccv_matrix_generate_signature("ccv_substract", 13, da->sig, db->sig, 0); int no_8u_type = (da->type & CCV_8U) ? CCV_32S : da->type; type = (type == 0) ? CCV_GET_DATA_TYPE(no_8u_type) | CCV_GET_CHANNEL(da->type) : CCV_GET_DATA_TYPE(type) | CCV_GET_CHANNEL(da->type); ccv_dense_matrix_t* dc = *c = ccv_dense_matrix_renew(*c, da->rows, da->cols, CCV_ALL_DATA_TYPE | CCV_GET_CHANNEL(da->type), type, sig); ccv_cache_return(dc, ); int i, j; unsigned char* aptr = da->data.ptr; unsigned char* bptr = db->data.ptr; unsigned char* cptr = dc->data.ptr; #define for_block(__for_get, __for_set) \ for (i = 0; i < da->rows; i++) \ { \ for (j = 0; j < da->cols; j++) \ { \ __for_set(cptr, j, __for_get(aptr, j, 0) - __for_get(bptr, j, 0), 0); \ } \ aptr += da->step; \ bptr += db->step; \ cptr += dc->step; \ } ccv_matrix_getter(da->type, ccv_matrix_setter, dc->type, for_block); #undef for_block } void ccv_gemm(ccv_matrix_t* a, ccv_matrix_t* b, double alpha, ccv_matrix_t* c, double beta, int transpose, ccv_matrix_t** d, int type) { ccv_dense_matrix_t* da = ccv_get_dense_matrix(a); ccv_dense_matrix_t* db = ccv_get_dense_matrix(b); ccv_dense_matrix_t* dc = (c == 0) ? 0 : ccv_get_dense_matrix(c); assert(CCV_GET_DATA_TYPE(da->type) == CCV_GET_DATA_TYPE(db->type) && CCV_GET_CHANNEL_NUM(da->type) == 1 && CCV_GET_CHANNEL_NUM(db->type) == 1 && ((transpose & CCV_A_TRANSPOSE) ? da->rows : da->cols) == ((transpose & CCV_B_TRANSPOSE) ? db->cols : db->rows)); if (dc != 0) assert(CCV_GET_DATA_TYPE(dc->type) == CCV_GET_DATA_TYPE(da->type) && CCV_GET_CHANNEL_NUM(dc->type) == 1 && ((transpose & CCV_A_TRANSPOSE) ? da->cols : da->rows) == dc->rows && ((transpose & CCV_B_TRANSPOSE) ? db->rows : db->cols) == dc->cols); char identifier[20]; memset(identifier, 0, 20); snprintf(identifier, 20, "ccv_gemm(%d)", transpose); uint64_t sig = (dc == 0) ? ((da->sig == 0 || db->sig == 0) ? 0 : ccv_matrix_generate_signature(identifier, 20, da->sig, db->sig, 0)) : ((da->sig == 0 || db->sig == 0 || dc->sig == 0) ? 0 : ccv_matrix_generate_signature(identifier, 20, da->sig, db->sig, dc->sig, 0)); type = CCV_GET_DATA_TYPE(da->type) | CCV_GET_CHANNEL(da->type); ccv_dense_matrix_t* dd = *d = ccv_dense_matrix_renew(*d, (transpose & CCV_A_TRANSPOSE) ? da->cols : da->rows, (transpose & CCV_B_TRANSPOSE) ? db->rows : db->cols, type, type, sig); ccv_cache_return(dd, ); if (dd != dc && dc != 0) memcpy(dd->data.ptr, dc->data.ptr, dc->step * dc->rows); #ifdef HAVE_CBLAS switch (CCV_GET_DATA_TYPE(dd->type)) { case CCV_32F: cblas_sgemm(CblasRowMajor, (transpose & CCV_A_TRANSPOSE) ? CblasTrans : CblasNoTrans, (transpose & CCV_B_TRANSPOSE) ? CblasTrans : CblasNoTrans, dd->rows, dd->cols, da->cols, alpha, da->data.fl, da->cols, db->data.fl, db->cols, beta, dd->data.fl, dd->cols); break; case CCV_64F: cblas_dgemm(CblasRowMajor, (transpose & CCV_A_TRANSPOSE) ? CblasTrans : CblasNoTrans, (transpose & CCV_B_TRANSPOSE) ? CblasTrans : CblasNoTrans, dd->rows, dd->cols, (transpose & CCV_A_TRANSPOSE) ? da->rows : da->cols, alpha, da->data.db, da->cols, db->data.db, db->cols, beta, dd->data.db, dd->cols); break; } #endif }
If $S$ is a nonempty open connected subset of a topological space $T$, and if every point of $T$ that is a limit point of $S$ is in $S$, then $S = T$.
To comply with the General Data Protection Regulations (GDPR) we would like your consent to take photos of your child, and use them in the ways described on the form. If you’re not happy for us to do this, we can accommodate your preferences. If you have not returned the form could you please kindly return the form by Friday 13th July by clicking on the attachment below.
# CS510 Homework 2: Homography-based Image Stitching # Haomin He # Reference: # https://docs.opencv.org/3.4/da/df5/tutorial_py_sift_intro.html # https://www.pyimagesearch.com/2016/01/11/opencv-panorama-stitching/ # https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_matcher/py_matcher.html # https://github.com/ojhaChandu/CV-Codes # https://github.com/krutikabapat/Image_Stitching # https://github.com/a514514772 # https://github.com/ShrishtiManjeshwar/Image-Stitching # https://github.com/dani-amirtharaj/KeyPointDetection-Homography-EpipolarGeometry # https://github.com/hughesj919/HomographyEstimation/ # https://stackoverflow.com/questions/30716610/how-to-get-pixel-coordinates-from-feature-matching-in-opencv-python # https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_core/py_basic_ops/py_basic_ops.html import cv2 import sys import numpy as np import random def ex_find_homography_ransac(list_pairs_matched_keypoints, threshold_ratio_inliers=0.85, threshold_reprojtion_error=3, max_num_trial=1000): ''' Apply RANSAC algorithm to find a homography transformation matrix that align 2 sets of feature points, transform the first set of feature point to the second (e.g. warp image 1 to image 2) :param list_pairs_matched_keypoints: has the format as a list of pairs of matched points: [[[p1x,p1y],[p2x,p2y]],....] :param threshold_ratio_inliers: threshold on the ratio of inliers over the total number of samples, accept the estimated homography if ratio is higher than the threshold :param threshold_reprojtion_error: threshold of reprojection error (measured as euclidean distance, in pixels) to determine whether a sample is inlier or outlier :param max_num_trial: the maximum number of trials to do take sample and do testing to find the best homography matrix :return best_H: the best found homography matrix ''' best_H = None listlength = len(list_pairs_matched_keypoints) for every in range(listlength): list_pairs_matched_keypoints[every] = list_pairs_matched_keypoints[every][0] + list_pairs_matched_keypoints[every][1] inlinersMost = [] for each in range(max_num_trial): # Apply RANSAC algorithm to find a homography transformation matrix point1 = list_pairs_matched_keypoints[random.randrange(0, listlength)] point2 = list_pairs_matched_keypoints[random.randrange(0, listlength)] # Variants of numpy.stack function to stack so as to make a single array vertically tempVar = np.vstack((point1, point2)) point3 = list_pairs_matched_keypoints[random.randrange(0, listlength)] tempVar = np.vstack((tempVar, point3)) point4 = list_pairs_matched_keypoints[random.randrange(0, listlength)] tempVar = np.vstack((tempVar, point4)) #print(tempVar[0]) # build the matrix matrixH = buildMatrix(tempVar) inlierCount = [] for count in range(listlength): # find the distance between estimated points and original points distance = CalDistance(list_pairs_matched_keypoints[count], matrixH) if distance < 5: inlierCount.append(list_pairs_matched_keypoints[count]) # set maximum inliner value if len(inlierCount) > len(inlinersMost): inlinersMost = inlierCount best_H = matrixH if len(inlinersMost) > (listlength * threshold_ratio_inliers): break return best_H def buildMatrix(tempPoints): thislist = [] # build the matrix for each in tempPoints: point1 = np.matrix([each.item(0), each.item(1), 1]) #print(point1) point2 = np.matrix([each.item(2), each.item(3), 1]) temp1 = [0, 0, 0, -point2.item(2) * point1.item(0), -point2.item(2) * point1.item(1), -point2.item(2) * point1.item(2), point2.item(1) * point1.item(0), point2.item(1) * point1.item(1), point2.item(1) * point1.item(2)] temp2 = [-point2.item(2) * point1.item(0), -point2.item(2) * point1.item(1), -point2.item(2) * point1.item(2), 0, 0, 0, point2.item(0) * point1.item(0), point2.item(0) * point1.item(1), point2.item(0) * point1.item(2)] thislist.append(temp2) thislist.append(temp1) #print(thislist) matrixBuild = np.matrix(thislist) # Singular Value Decomposition # Factors the matrix a as u * np.diag(s) * v, where u and v are unitary and s is a 1-d array of a‘s singular values U, s, V = np.linalg.svd(matrixBuild) # shapes an array without changing data of array # shape to three by three matrix matrixH = np.reshape(V[8], (3, 3)) matrixH = (1/matrixH.item(8)) * matrixH return matrixH def CalDistance(point, matrixH): # find the distance between estimated points and original points point1 = np.transpose(np.matrix([point[0], point[1], 1])) # find estimated point mayPoint2 = np.dot(matrixH, point1) mayPoint2 = (1/mayPoint2.item(2)) * mayPoint2 # find original point point2 = np.transpose(np.matrix([point[2], point[3], 1])) dis = point2 - mayPoint2 # return one of eight different matrix norms return np.linalg.norm(dis) def ex_extract_and_match_feature(img_1, img_2, ratio_robustness=0.7): ''' 1/ extract SIFT feature from image 1 and image 2, 2/ use a bruteforce search to find pairs of matched features: for each feature point in img_1, find its best matched feature point in img_2 3/ apply ratio test to select the set of robust matched points :param img_1: input image 1 :param img_2: input image 2 :param ratio_robustness: ratio for the robustness test :return list_pairs_matched_keypoints: has the format as list of pairs of matched points: [[[p1x,p1y],[p2x,p2y]]] ''' # ============================== # ===== 1/ extract features from input image 1 and image 2 # ============================== # First to create SIFT object sift = cv2.xfeatures2d.SIFT_create() # Finds the keypoint and descriptors in the images keypoints1, descriptor1 = sift.detectAndCompute(img_1,None) keypoints2, descriptor2 = sift.detectAndCompute(img_2,None) # ============================== # ===== 2/ use bruteforce search to find a list of pairs of matched feature points # ============================== list_pairs_matched_keypoints = [] # using cv2.BFMatcher(). It takes two optional params. First one is normType. It specifies the distance measurement to be used. # Second param is boolean variable, crossCheck which is false by default. If it is true, Matcher returns only those matches with value (i,j) bruteforce = cv2.BFMatcher() # use BFMatcher.knnMatch() to get k best matches. # we will take k=2 so that we can apply ratio test explained by D.Lowe in his paper. bestmatches = bruteforce.knnMatch(descriptor1, descriptor2, k = 2) matches = [] for m,n in bestmatches: if m.distance < 0.75 * n.distance: matches.append(m) #print(matches) # queryIdx - The index or row of the kp1 interest point matrix that matches # trainIdx - The index or row of the kp2 interest point matrix that matches for match in matches: # Get the matching keypoints for each of the images img1_idx = match.queryIdx img2_idx = match.trainIdx # x - columns # y - rows # Get the coordinates [x1,y1] = keypoints1[img1_idx].pt [x2,y2] = keypoints2[img2_idx].pt list_pairs_matched_keypoints.append([[x1,y1], [x2,y2]]) #print(list_pairs_matched_keypoints) return list_pairs_matched_keypoints def ex_warp_blend_crop_image(img_1,H_1,img_2): ''' 1/ warp image img_1 using the homography H_1 to align it with image img_2 (using backward warping and bilinear resampling) 2/ stitch image img_1 to image img_2 and apply average blending to blend the 2 images into a single panorama image 3/ find the best bounding box for the resulting stitched image :param img_1: :param H_1: :param img_2: :return img_panorama: resulting panorama image ''' img_panorama = None # ===== use a backward warping algorithm to warp the source # 1/ to do so, we first create the inverse transform; 2/ use bilinear interpolation for resampling # ===== blend images: average blending # ===== find the best bounding box for the resulting stitched image so that it will contain all pixels from 2 original images # It returns a tuple of number of rows, columns and channels rows, columns, channels = img_1.shape # find corners corner1 = np.float32([[0, 0], [0, rows-1], [columns-1, rows-1], [columns-1, 0]]).reshape(-1, 1, 2) # transforms every element of src by treating it as a 2D or 3D vector corner1Trans = np.squeeze(cv2.perspectiveTransform(corner1, H_1)) # find all edge points # left most point, top most point, right most point, lowest point left = min(corner1Trans[0][0], corner1Trans[1][0]) top = min(corner1Trans[0][1], corner1Trans[3][1]) right = max(corner1Trans[2][0], corner1Trans[3][0]) bottom = max(corner1Trans[1][1], corner1Trans[2][1]) # calculate differences temp1 = (right - left, bottom - top) temp2 = (len(img_2[0]) - int(left), len(img_2) - int(top)) pickMax = max(temp1, temp2) # warp image img_1 using the homography H_1 to align it with image img_2 if left < 0 and top < 0: warp = np.float32([[1,0, -left], [0,1, -top], [0,0,1]]) elif left < 0: warp = np.float32([[1,0, -left], [0,1,0], [0,0,1]]) elif left < 0: warp = np.float32([[1,0,0], [0,1, -top], [0,0,1]]) else: warp = np.float32([[1,0,0], [0,1,0], [0,0,1]]) # alignment transformation # Matrix product of two arrays img_panorama = cv2.warpPerspective(img_1, np.matmul(warp, H_1), pickMax) img_panorama[-int(top):-int(top)+len(img_2), -int(left):-int(left)+len(img_2[0])]=img_2 return img_panorama def stitch_images(img_1, img_2): ''' :param img_1: input image 1. We warp this image to align and stich it to the image 2 :param img_2: is the reference image. We will not warp this image :return img_panorama: the resulting stiched image ''' print('==============================') print('===== stitch two images to generate one panorama image') print('==============================') # ===== extract and match features from image 1 and image 2 list_pairs_matched_keypoints = ex_extract_and_match_feature(img_1=img_1, img_2=img_2, ratio_robustness=0.7) # ===== use RANSAC algorithm to find homography to warp image 1 to align it to image 2 H_1 = ex_find_homography_ransac(list_pairs_matched_keypoints, threshold_ratio_inliers=0.85, threshold_reprojtion_error=3, max_num_trial=1000) # ===== warp image 1, blend it with image 2 using average blending to produce the resulting panorama image img_panorama = ex_warp_blend_crop_image(img_1=img_1,H_1=H_1, img_2=img_2) return img_panorama if __name__ == "__main__": print('==================================================') print('PSU CS 410/510, Winter 2019, HW2: image stitching') print('==================================================') path_file_image_1 = sys.argv[1] path_file_image_2 = sys.argv[2] path_file_image_result = sys.argv[3] # ===== read 2 input images img_1 = cv2.imread(path_file_image_1) img_2 = cv2.imread(path_file_image_2) # ===== create a panorama image by stitch image 1 to image 2 img_panorama = stitch_images(img_1=img_1, img_2=img_2) # ===== save panorama image cv2.imwrite(filename=path_file_image_result, img=(img_panorama).clip(0.0, 255.0).astype(np.uint8))
function fem2d_pack_test09 ( ) %*****************************************************************************80 % %% TEST09 demonstrates ELEMENTS_EPS with T4 elements. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 14 February 2003 % % Author: % % John Burkardt % element_order = 4; nelemx = 7; nelemy = 5; element_num = grid_t4_element_num ( nelemx, nelemy ); node_num = grid_t4_node_num ( nelemx, nelemy ); code = 'T4'; file_name = 'fem2d_pack_test_t4.eps'; title = 'Grid of T4 Elements'; fprintf ( 1, '\n' ); fprintf ( 1, 'TEST09\n' ); fprintf ( 1, ' ELEMENTS_EPS creates an Encapsulated PostScript\n' ); fprintf ( 1, ' file containing an image of a T4 mesh.\n' ); element_node = grid_t4_element ( nelemx, nelemy ); node = 0; for row = 0 : nelemy y = ( ( 3*nelemy - row ) * 0.0 ... + ( + row ) * 6.0 ) ... / ( 3*nelemy ); for col = 0 : nelemx node = node + 1; x = ( ( 2*nelemx - col ) * 0.0 ... + ( + col ) * 6.0 ) ... / ( 2*nelemx ); node_x(node) = x; node_y(node) = y; end % % Skip over the two rows of interior nodes. % node = node + nelemx; node = node + nelemx; end % % The coordinates of interior nodes are the average of the vertices. % for element = 1 : element_num node = element_node(4,element); node_x(node) = sum ( node_x(element_node(1:3,element)) ) / 3.0; node_y(node) = sum ( node_y(element_node(1:3,element)) ) / 3.0; end for element = 1 : element_num element_mask(element) = 1; end elements_eps ( file_name, node_num, node_x, node_y, code, ... element_order, element_num, element_mask, element_node, title ); return end
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl, Reid Barton -/ import combinatorics.quiver.basic import tactic.basic /-! # Categories Defines a category, as a type class parametrised by the type of objects. ## Notations Introduces notations * `X ⟶ Y` for the morphism spaces, * `f ≫ g` for composition in the 'arrows' convention. Users may like to add `f ⊚ g` for composition in the standard convention, using ```lean local notation f ` ⊚ `:80 g:80 := category.comp g f -- type as \oo ``` -/ /-- The typeclass `category C` describes morphisms associated to objects of type `C : Type u`. The universe levels of the objects and morphisms are independent, and will often need to be specified explicitly, as `category.{v} C`. Typically any concrete example will either be a `small_category`, where `v = u`, which can be introduced as ``` universes u variables {C : Type u} [small_category C] ``` or a `large_category`, where `u = v+1`, which can be introduced as ``` universes u variables {C : Type (u+1)} [large_category C] ``` In order for the library to handle these cases uniformly, we generally work with the unconstrained `category.{v u}`, for which objects live in `Type u` and morphisms live in `Type v`. Because the universe parameter `u` for the objects can be inferred from `C` when we write `category C`, while the universe parameter `v` for the morphisms can not be automatically inferred, through the category theory library we introduce universe parameters with morphism levels listed first, as in ``` universes v u ``` or ``` universes v₁ v₂ u₁ u₂ ``` when multiple independent universes are needed. This has the effect that we can simply write `category.{v} C` (that is, only specifying a single parameter) while `u` will be inferred. Often, however, it's not even necessary to include the `.{v}`. (Although it was in earlier versions of Lean.) If it is omitted a "free" universe will be used. -/ library_note "category_theory universes" universes v u namespace category_theory /-- A preliminary structure on the way to defining a category, containing the data, but none of the axioms. -/ class category_struct (obj : Type u) extends quiver.{v+1} obj : Type (max u (v+1)) := (id : Π X : obj, hom X X) (comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z)) notation `𝟙` := category_struct.id -- type as \b1 infixr ` ≫ `:80 := category_struct.comp -- type as \gg /-- The typeclass `category C` describes morphisms associated to objects of type `C`. The universe levels of the objects and morphisms are unconstrained, and will often need to be specified explicitly, as `category.{v} C`. (See also `large_category` and `small_category`.) See https://stacks.math.columbia.edu/tag/0014. -/ class category (obj : Type u) extends category_struct.{v} obj : Type (max u (v+1)) := (id_comp' : ∀ {X Y : obj} (f : hom X Y), 𝟙 X ≫ f = f . obviously) (comp_id' : ∀ {X Y : obj} (f : hom X Y), f ≫ 𝟙 Y = f . obviously) (assoc' : ∀ {W X Y Z : obj} (f : hom W X) (g : hom X Y) (h : hom Y Z), (f ≫ g) ≫ h = f ≫ (g ≫ h) . obviously) -- `restate_axiom` is a command that creates a lemma from a structure field, -- discarding any auto_param wrappers from the type. -- (It removes a backtick from the name, if it finds one, and otherwise adds "_lemma".) restate_axiom category.id_comp' restate_axiom category.comp_id' restate_axiom category.assoc' attribute [simp] category.id_comp category.comp_id category.assoc attribute [trans] category_struct.comp /-- A `large_category` has objects in one universe level higher than the universe level of the morphisms. It is useful for examples such as the category of types, or the category of groups, etc. -/ abbreviation large_category (C : Type (u+1)) : Type (u+1) := category.{u} C /-- A `small_category` has objects and morphisms in the same universe level. -/ abbreviation small_category (C : Type u) : Type (u+1) := category.{u} C section variables {C : Type u} [category.{v} C] {X Y Z : C} initialize_simps_projections category (to_category_struct_to_quiver_hom → hom, to_category_struct_comp → comp, to_category_struct_id → id, -to_category_struct) /-- postcompose an equation between morphisms by another morphism -/ lemma eq_whisker {f g : X ⟶ Y} (w : f = g) (h : Y ⟶ Z) : f ≫ h = g ≫ h := by rw w /-- precompose an equation between morphisms by another morphism -/ lemma whisker_eq (f : X ⟶ Y) {g h : Y ⟶ Z} (w : g = h) : f ≫ g = f ≫ h := by rw w infixr ` =≫ `:80 := eq_whisker infixr ` ≫= `:80 := whisker_eq lemma eq_of_comp_left_eq {f g : X ⟶ Y} (w : ∀ {Z : C} (h : Y ⟶ Z), f ≫ h = g ≫ h) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_right_eq {f g : Y ⟶ Z} (w : ∀ {X : C} (h : X ⟶ Y), h ≫ f = h ≫ g) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_left_eq' (f g : X ⟶ Y) (w : (λ {Z : C} (h : Y ⟶ Z), f ≫ h) = (λ {Z : C} (h : Y ⟶ Z), g ≫ h)) : f = g := eq_of_comp_left_eq (λ Z h, by convert congr_fun (congr_fun w Z) h) lemma eq_of_comp_right_eq' (f g : Y ⟶ Z) (w : (λ {X : C} (h : X ⟶ Y), h ≫ f) = (λ {X : C} (h : X ⟶ Y), h ≫ g)) : f = g := eq_of_comp_right_eq (λ X h, by convert congr_fun (congr_fun w X) h) lemma id_of_comp_left_id (f : X ⟶ X) (w : ∀ {Y : C} (g : X ⟶ Y), f ≫ g = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } lemma id_of_comp_right_id (f : X ⟶ X) (w : ∀ {Y : C} (g : Y ⟶ X), g ≫ f = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } lemma dite_comp {P : Prop} [decidable P] {X Y Z : C} (f : P → (X ⟶ Y)) (f' : ¬P → (X ⟶ Y)) (g : Y ⟶ Z) : (if h : P then f h else f' h) ≫ g = (if h : P then f h ≫ g else f' h ≫ g) := by { split_ifs; refl } /-- A morphism `f` is an epimorphism if it can be "cancelled" when precomposed: `f ≫ g = f ≫ h` implies `g = h`. See https://stacks.math.columbia.edu/tag/003B. -/ class epi (f : X ⟶ Y) : Prop := (left_cancellation : Π {Z : C} (g h : Y ⟶ Z) (w : f ≫ g = f ≫ h), g = h) /-- A morphism `f` is a monomorphism if it can be "cancelled" when postcomposed: `g ≫ f = h ≫ f` implies `g = h`. See https://stacks.math.columbia.edu/tag/003B. -/ class mono (f : X ⟶ Y) : Prop := (right_cancellation : Π {Z : C} (g h : Z ⟶ X) (w : g ≫ f = h ≫ f), g = h) instance (X : C) : epi (𝟙 X) := ⟨λ Z g h w, by simpa using w⟩ instance (X : C) : mono (𝟙 X) := ⟨λ Z g h w, by simpa using w⟩ lemma cancel_epi (f : X ⟶ Y) [epi f] {g h : Y ⟶ Z} : (f ≫ g = f ≫ h) ↔ g = h := ⟨ λ p, epi.left_cancellation g h p, begin intro a, subst a end ⟩ lemma cancel_mono (f : X ⟶ Y) [mono f] {g h : Z ⟶ X} : (g ≫ f = h ≫ f) ↔ g = h := ⟨ λ p, mono.right_cancellation g h p, begin intro a, subst a end ⟩ lemma cancel_epi_id (f : X ⟶ Y) [epi f] {h : Y ⟶ Y} : (f ≫ h = f) ↔ h = 𝟙 Y := by { convert cancel_epi f, simp, } lemma cancel_mono_id (f : X ⟶ Y) [mono f] {g : X ⟶ X} : (g ≫ f = f) ↔ g = 𝟙 X := by { convert cancel_mono f, simp, } lemma epi_comp {X Y Z : C} (f : X ⟶ Y) [epi f] (g : Y ⟶ Z) [epi g] : epi (f ≫ g) := begin split, intros Z a b w, apply (cancel_epi g).1, apply (cancel_epi f).1, simpa using w, end lemma mono_comp {X Y Z : C} (f : X ⟶ Y) [mono f] (g : Y ⟶ Z) [mono g] : mono (f ≫ g) := begin split, intros Z a b w, apply (cancel_mono f).1, apply (cancel_mono g).1, simpa using w, end lemma mono_of_mono {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [mono (f ≫ g)] : mono f := begin split, intros Z a b w, replace w := congr_arg (λ k, k ≫ g) w, dsimp at w, rw [category.assoc, category.assoc] at w, exact (cancel_mono _).1 w, end lemma mono_of_mono_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [mono h] (w : f ≫ g = h) : mono f := by { substI h, exact mono_of_mono f g, } lemma epi_of_epi {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [epi (f ≫ g)] : epi g := begin split, intros Z a b w, replace w := congr_arg (λ k, f ≫ k) w, dsimp at w, rw [←category.assoc, ←category.assoc] at w, exact (cancel_epi _).1 w, end lemma epi_of_epi_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [epi h] (w : f ≫ g = h) : epi g := by substI h; exact epi_of_epi f g end section variable (C : Type u) variable [category.{v} C] universe u' instance ulift_category : category.{v} (ulift.{u'} C) := { hom := λ X Y, (X.down ⟶ Y.down), id := λ X, 𝟙 X.down, comp := λ _ _ _ f g, f ≫ g } -- We verify that this previous instance can lift small categories to large categories. example (D : Type u) [small_category D] : large_category (ulift.{u+1} D) := by apply_instance end end category_theory /-- Many proofs in the category theory library use the `dsimp, simp` pattern, which typically isn't necessary elsewhere. One would usually hope that the same effect could be achieved simply with `simp`. The essential issue is that composition of morphisms involves dependent types. When you have a chain of morphisms being composed, say `f : X ⟶ Y` and `g : Y ⟶ Z`, then `simp` can operate succesfully on the morphisms (e.g. if `f` is the identity it can strip that off). However if we have an equality of objects, say `Y = Y'`, then `simp` can't operate because it would break the typing of the composition operations. We rarely have interesting equalities of objects (because that would be "evil" --- anything interesting should be expressed as an isomorphism and tracked explicitly), except of course that we have plenty of definitional equalities of objects. `dsimp` can apply these safely, even inside a composition. After `dsimp` has cleared up the object level, `simp` can resume work on the morphism level --- but without the `dsimp` step, because `simp` looks at expressions syntactically, the relevant lemmas might not fire. There's no bound on how many times you potentially could have to switch back and forth, if the `simp` introduced new objects we again need to `dsimp`. In practice this does occur, but only rarely, because `simp` tends to shorten chains of compositions (i.e. not introduce new objects at all). -/ library_note "dsimp, simp"
%{ B_LoopDeLoopCam.m Animate several camera motions around a surface. Matt Sheen, [email protected] %} close all; clear all; fig = figure; %% Compound Patch - same from folder 2, example b pX = [-1 1 0; 0 0 0]'; pY = [-1/3 -1/3 2/3; -1/3 -1/3 2/3]'; pZ = [0 0 0; 0 0.5 0]'; p1 = patch(pX,pY,pZ,'red'); p1.FaceAlpha = 0.5; OrigVerts = p1.Vertices; %% Set initial camera position. axis(2*[-10 10 -10 10 -10 10]) campos([8,8,8]); camtarget([0,0,0]); camva(40); %Turning the axis grid on to help get perspective of movement fig.Children.ZGrid = 'on'; fig.Children.YGrid = 'on'; fig.Children.XGrid = 'on'; vel = 0.1*[0 1 0]; rot = angle2dcm(0,0,-0.02); dt = 0.5; center = [0 0 0]; totalRot = eye(3,3); %% Cam mode 1: fixed everything. Camera stays exactly the same throughout. input('Press enter to see default camera orientation.'); for i = 1:1000 %Moving the plane is the same as previous example totalRot = totalRot*rot; center = dt*(totalRot*vel')' + center; %transform the velocity, keep track of the center position. p1.Vertices = (totalRot*OrigVerts')' + repmat(center,[size(OrigVerts,1),1]); %Rotate the patch object about its center and add new center point. pause(0.01); end %% Cam mode 2: let's follow the plane. Camera keeps the plane in the center of view, but does not change orientation. input('Press enter to see plane-centering camera.'); for i = 1:1000 %Moving the plane is the same as previous example totalRot = totalRot*rot; center = dt*(totalRot*vel')' + center; %transform the velocity, keep track of the center position. p1.Vertices = (totalRot*OrigVerts')' + repmat(center,[size(OrigVerts,1),1]); %Rotate the patch object about its center and add new center point. %CAMERA CHANGES: camtarget(center); %make the target be the center of the plane. campos(center+[5,5,5]); %make the camera position be a fixed offset from the center of the plane. pause(0.01); end %% Cam mode 3: let's fly the plane. Camera also changes orientation with the plane. input('Press enter to see plane-following camera.'); for i = 1:1000 %Moving the plane is the same as previous example totalRot = totalRot*rot; center = dt*(totalRot*vel')' + center; %transform the velocity, keep track of the center position. p1.Vertices = (totalRot*OrigVerts')' + repmat(center,[size(OrigVerts,1),1]); %Rotate the patch object about its center and add new center point. %CAMERA CHANGES: camtarget(center); %Camera target is the center of the plane. campos(center+5*(totalRot*[0.5 -1 0.5]')'); %Camera position is a little behind, up, and to the right of the plane (helps see what's going on). Note that we have to transform the camera offset from plane frame to world frame. camup(totalRot*[0 0 1]'); % The camera should think "up" is the up vector of the plane. So we take the plane's up and transform it into the world frame. pause(0.01); end
classdef RigidJoint < CoordinateFrame % A coordinate frame that is rigidly attached to the origin a rigid % joint and the child link of the joint. In addition, this class stores % the type, rotation axis, child link, and limit of the rigid joints. % % Copyright (c) 2016-2017, AMBER Lab % All right reserved. % % Redistribution and use in source and binary forms, with or without % modification, are permitted only in compliance with the BSD 3-Clause % license, see % http://www.opensource.org/licenses/bsd-license.php properties (SetAccess=protected, GetAccess=public) % The type of the rigid joint % % @note valid joint types include: % revolute, prismatic, continuous, fixed. % % @type char Type % The rotation axis vector of the rigid joint % % @note it must be a 3x1 vector. % % @type rowvec Axis % The name of the child link % % @type char Child % The name of the parent link % % @type char Parent % A structure data stores the physical limits of the rigid joints % % Required fields of limit: % effort: the maximum actuator effort @type double % lower: the minimum allowable displacement @type double % upper: the maximum allowable displacement @type double % velocity: the maximum allowable velocity @type double % % @type struct Limit % A structure contains information about the actuator for the joint % % An empty property indicates the joint is not actuated. % % @type struct Actuator end properties (Hidden, SetAccess=protected, GetAccess=public) % The indices of kinematic chains from the base to the current % joint % % @type rowvec ChainIndices % The twist from the base frame % % @type rowvec Twist % The twist pairs of all precedent joints (coordinate frame) % % @type SymExpression TwistPairs end methods function obj = RigidJoint(varargin) % The class constructor function % % Parameters: % varargin: variable nama-value pair input arguments, in detail: % Name: the name of the frame @type char % Reference: the reference frame @type CoordinateFrame % Offset: the offset of the origin @type rowvec % R: the rotation matrix or the Euler angles @type rowvec % Axis: the rotation axis vector @type rowvec % Type: the type of the joints @type char % Child: the child link frame @type RigidLink % Limit: the joint physical limits @type struct % consruct the superclass object first obj = obj@CoordinateFrame(varargin{:}); if nargin == 0 return; end argin = struct(varargin{:}); % validate and assign the joint type if isfield(argin, 'Type') && ~isempty(argin.Type) obj = obj.setType(argin.Type); else error('The joint type is not defined.'); end % validate and assign the joint axis if isfield(argin, 'Axis') && ~isempty(argin.Axis) obj = obj.setAxis(argin.Axis); elseif strcmp(obj.Type, 'fixed') obj = obj.setAxis([0,0,1]); else error('The joint rotation axis is not defined.'); end % validate and assign the child link if isfield(argin, 'Child') && ~isempty(argin.Child) obj = obj.setChild(argin.Child); else error('The child link is not defined.'); end % validate and assign the parent link if isfield(argin, 'Parent') && ~isempty(argin.Parent) obj = obj.setParent(argin.Parent); else error('The parent link is not defined.'); end % validate and assign the physical limits if isfield(argin, 'Limit') && ~isempty(argin.Limit) obj = obj.setLimit(argin.Limit); else warning('The joint limits are not defined. Using default values.'); default_limit = struct(... 'effort',0,... 'lower',-inf,... 'upper',inf,... 'velocity',inf); obj = obj.setLimit(default_limit); end % validate and assign the actuator info if isfield(argin, 'Actuator') && ~isempty(argin.Actuator) obj = obj.setActuator(argin.Actuator); end end end %% methods defined in external files methods obj = setAxis(obj, axis); obj = setType(obj, type); obj = setParent(obj, parent); obj = setChild(obj, child); obj = setLimit(obj, varargin); obj = setActuator(obj, varargin); obj = setChainIndices(obj, indices); xi = getTwist(obj); obj = computeTwist(obj); obj = setTwistPairs(obj, dofs, q); end end
The Lord of the Rushie River ; Blackie , 1938
# Модель расчетов Расчет профиля и навески разбит на несколько этапов 1. Оптимизация профиля по ионному балансу. Профиль оптимизируется по сере и хлору 2. Перерасчет профиля по требуемому EC 3. Перерасчет профиля по коэфициентам 4. Расчет навески удобрений # Расчет EC ## Формула Зоневельда Выполняется при условии того что ионный баланс равен нулю $$ \left( \frac{m_{NH_4}}{M_N} + \frac{2 m_{Ca}}{M_{Ca}} + \frac{2 m_{Mg}}{M_{Mg}} + \frac{m_{K}}{M_{K}} \right) - \left( \frac{m_{NO_3}}{M_N} + \frac{m_{P}}{M_{P}} + \frac{2m_{S}}{M_{S}} + \frac{m_{Cl}}{M_{Cl}} \right) = 0 $$ Тогда: $$ EC = 0.095 \left( \frac{m_{NH_4}}{M_N} + \frac{2 m_{Ca}}{M_{Ca}} + \frac{2 m_{Mg}}{M_{Mg}} + \frac{m_{K}}{M_{K}} \right) + 0.19 $$ Где: \ $M$ --- молярная масса\ $m$ --- профиль, в мг/л (ppm) ```python m_NO3 = 220 m_NH4 = 20 m_P = 40 m_K = 280 m_Ca = 140 m_Mg = 56 m_S = 51.07 m_Cl = 0 M_N = 14.0067 M_Ca = 40.078 M_Mg = 24.305 M_K = 39.0983 M_P = 30.973 M_S = 32.065 M_Cl = 35.45 cations = ((m_NH4/ M_N) + ((2*m_Ca) / M_Ca) + ((2*m_Mg) / M_Mg) + (m_K / M_K) ) anions = ((m_NO3/ M_N) + (m_P / M_P) + ((2*m_S)/ M_S) + (m_Cl/ M_Cl)) EC = (0.095 * cations) + 0.19 print(cations, anions) print(f'I = {cations-anions:0.2f}') print(f'EC = {EC:.3f}') ``` 20.183806662456348 20.183620939926474 I = 0.00 EC = 2.107 ## Ионный баланс профиля Оптимизация профиля достижением нулевого ионного баланса (сумма катионов и анионов должна быть равна нулю) Основой является формула ионного баланса $$ \left( \frac{m_{NH_4}}{M_N} + \frac{2 m_{Ca}}{M_{Ca}} + \frac{2 m_{Mg}}{M_{Mg}} + \frac{m_{K}}{M_{K}} \right) - \left( \frac{m_{NO_3}}{M_N} + \frac{m_{P}}{M_{P}} + \frac{2m_{S}}{M_{S}} + \frac{m_{Cl}}{M_{Cl}} \right) = 0 $$ Баланс производится по сере или кальцию, в зависимости от того что крутим ```python # Install a pip package in the current Jupyter kernel import sys !{sys.executable} -m pip install sympy numpy scipy import sympy as sym from sympy import Eq sym.init_printing() from IPython.display import Math, display ``` Requirement already satisfied: sympy in /home/apkawa/.local/lib/python3.9/site-packages (1.7.1) Requirement already satisfied: numpy in /usr/lib/python3/dist-packages (1.19.4) Collecting scipy Downloading scipy-1.6.0-cp39-cp39-manylinux1_x86_64.whl (27.3 MB)  |████████████████████████████████| 27.3 MB 12.2 MB/s eta 0:00:01 [?25hRequirement already satisfied: mpmath>=0.19 in /home/apkawa/.local/lib/python3.9/site-packages (from sympy) (1.1.0) Installing collected packages: scipy Successfully installed scipy-1.6.0 ```python import sympy as sym sym.init_printing() elements = ['NO3', 'NH4', 'P', 'K', 'Ca', 'Mg', 'S', 'Cl'] m = dict(zip(elements, sym.symbols([f'm_{e}' for e in elements]))) M = dict(zip(elements, sym.symbols([f'M_{e}' for e in elements]))) repl = { m['NO3'] : 220, m['NH4'] : 20, m['P'] : 40, m['K'] : 280, m['Ca'] : 140, m['Mg'] : 56, m['S']: 51.07, m['Cl']: 0, # Молярные массы M['NO3'] : 14.0067, M['NH4'] : 14.0067, M['Ca'] : 40.078, M['Mg'] : 24.305, M['K'] : 39.0983, M['P'] : 30.973, M['S'] : 32.065, M['Cl']: 35.45, } # Уравнение ионного баланса Cations = ((m['NH4']/ M['NH4']) + ((2*m['Ca']) / M['Ca']) + ((2*m['Mg']) / M['Mg']) + (m['K'] / M['K'])) Anions = ((m['NO3']/ M['NO3']) + (m['P'] / M['P']) + ((2*m['S'])/ M['S']) + (m['Cl']/ M['Cl'])) Ionic_balance = sym.Eq((Cations - Anions), 0) I = (Cations - Anions).subs(repl) print("Проверка что профиль сбалансирован") print(f"I = {I:0.3f}") # Решаем уравнение через серу solved_S = sym.solve([Ionic_balance],(m['S']))[m['S']] mS = solved_S.subs(repl) print(f'm_S = {mS:.2f}') I = (Cations - Anions).subs({**repl, **{m['S']: mS}}) print(f"I = {I:0.3f}") print("Сера через кальций") display(sym.Eq(m['S'], solved_S)) r2 = {**repl, **{ m['NO3'] : 200, m['NH4'] : 20, m['P'] : 40, m['K'] : 180, m['Ca'] : 200, m['Mg'] : 50, }} mS = solved_S.subs(r2) print(f'm_S = {mS:.2f}') r2[m['S']] = mS I = (Cations - Anions).subs(r2) print(f"I = {I:0.3f}") print("Кальций через серу") r2 = {**r2, **{m['S']: mS}} solved_Ca = sym.solve([Ionic_balance],(m['Ca']))[m['Ca']] display(sym.Eq(m['Ca'], solved_Ca)) mCa = solved_Ca.subs(r2) print(f'm_Ca = {mCa:.2f}') I = (Cations - Anions).subs({**r2, **{m['Ca']: mCa}}) print(f"I = {I:0.3f}") ``` Проверка что профиль сбалансирован I = 0.000 m_S = 51.07 I = 0.000 Сера через кальций $\displaystyle m_{S} = \frac{- M_{Ca} M_{Cl} M_{K} M_{Mg} M_{NH4} M_{NO3} M_{S} m_{P} - M_{Ca} M_{Cl} M_{K} M_{Mg} M_{NH4} M_{P} M_{S} m_{NO3} + M_{Ca} M_{Cl} M_{K} M_{Mg} M_{NO3} M_{P} M_{S} m_{NH4} + 2 M_{Ca} M_{Cl} M_{K} M_{NH4} M_{NO3} M_{P} M_{S} m_{Mg} + M_{Ca} M_{Cl} M_{Mg} M_{NH4} M_{NO3} M_{P} M_{S} m_{K} - M_{Ca} M_{K} M_{Mg} M_{NH4} M_{NO3} M_{P} M_{S} m_{Cl} + 2 M_{Cl} M_{K} M_{Mg} M_{NH4} M_{NO3} M_{P} M_{S} m_{Ca}}{2 M_{Ca} M_{Cl} M_{K} M_{Mg} M_{NH4} M_{NO3} M_{P}}$ m_S = 73.05 I = 0.000 Кальций через серу $\displaystyle m_{Ca} = \frac{2 M_{Ca} M_{Cl} M_{K} M_{Mg} M_{NH4} M_{NO3} M_{P} m_{S} + M_{Ca} M_{Cl} M_{K} M_{Mg} M_{NH4} M_{NO3} M_{S} m_{P} + M_{Ca} M_{Cl} M_{K} M_{Mg} M_{NH4} M_{P} M_{S} m_{NO3} - M_{Ca} M_{Cl} M_{K} M_{Mg} M_{NO3} M_{P} M_{S} m_{NH4} - 2 M_{Ca} M_{Cl} M_{K} M_{NH4} M_{NO3} M_{P} M_{S} m_{Mg} - M_{Ca} M_{Cl} M_{Mg} M_{NH4} M_{NO3} M_{P} M_{S} m_{K} + M_{Ca} M_{K} M_{Mg} M_{NH4} M_{NO3} M_{P} M_{S} m_{Cl}}{2 M_{Cl} M_{K} M_{Mg} M_{NH4} M_{NO3} M_{P} M_{S}}$ m_Ca = 200.00 I = 0.000 ```python print(solved_S) print(solved_Ca) ``` (-M_Ca*M_Cl*M_K*M_Mg*M_NH4*M_NO3*M_S*m_P - M_Ca*M_Cl*M_K*M_Mg*M_NH4*M_P*M_S*m_NO3 + M_Ca*M_Cl*M_K*M_Mg*M_NO3*M_P*M_S*m_NH4 + 2*M_Ca*M_Cl*M_K*M_NH4*M_NO3*M_P*M_S*m_Mg + M_Ca*M_Cl*M_Mg*M_NH4*M_NO3*M_P*M_S*m_K - M_Ca*M_K*M_Mg*M_NH4*M_NO3*M_P*M_S*m_Cl + 2*M_Cl*M_K*M_Mg*M_NH4*M_NO3*M_P*M_S*m_Ca)/(2*M_Ca*M_Cl*M_K*M_Mg*M_NH4*M_NO3*M_P) (2*M_Ca*M_Cl*M_K*M_Mg*M_NH4*M_NO3*M_P*m_S + M_Ca*M_Cl*M_K*M_Mg*M_NH4*M_NO3*M_S*m_P + M_Ca*M_Cl*M_K*M_Mg*M_NH4*M_P*M_S*m_NO3 - M_Ca*M_Cl*M_K*M_Mg*M_NO3*M_P*M_S*m_NH4 - 2*M_Ca*M_Cl*M_K*M_NH4*M_NO3*M_P*M_S*m_Mg - M_Ca*M_Cl*M_Mg*M_NH4*M_NO3*M_P*M_S*m_K + M_Ca*M_K*M_Mg*M_NH4*M_NO3*M_P*M_S*m_Cl)/(2*M_Cl*M_K*M_Mg*M_NH4*M_NO3*M_P*M_S) ## ЕС профиля Коррекция профиля по EC производится по формуле Зоневельда $$ EC = 0.095 \left( \frac{m_{NH_4} r}{M_N} + \frac{2 m_{Ca} r}{M_{Ca}} + \frac{2 m_{Mg} r}{M_{Mg}} + \frac{m_{K} r}{M_{K}} \right) + 0.19 $$ где $r$ - это коэфициент приведения ```python elements = ['NO3', 'NH4', 'P', 'K', 'Ca', 'Mg', 'S', 'Cl'] r = sym.symbols('r') EC, NH4NO3, KMg, KCa, KN, PN, N = sym.symbols(['EC', 'K_NH4NO3', 'K_KMg', 'K_KCa', 'K_KN', 'K_PN', 'm_N']) m = dict(zip(elements, sym.symbols([f'm_{e}' for e in elements]))) M = dict(zip(elements, sym.symbols([f'M_{e}' for e in elements]))) repl = { r: 1, m['NO3'] : 200, m['NH4'] : 20, m['P'] : 40, m['K'] : 180, m['Ca'] : 200, m['Mg'] : 50, m['S']: 72.44, m['Cl']: 0.0, # Молярные массы M['NO3'] : 14.0067, M['NH4'] : 14.0067, M['Ca'] : 40.078, M['Mg'] : 24.305, M['K'] : 39.0983, M['P'] : 30.0983, M['S'] : 32.065, M['Cl']: 35.45, } # Формулы коэфициентов NH4NO3f = sym.Eq(m['NH4'] / m['NO3'], NH4NO3) Nf = sym.Eq(m['NH4'] + m['NO3'], N) Sum_k = sym.Eq(sum([N, m['K'], m['Ca'], m['Mg']]), 1) KCaf = sym.Eq(m['K'] / m['Ca'], KCa) KMgf = sym.Eq(m['K'] / m['Mg'], KMg) KNf = sym.Eq(m['K'] / N, KN) # Решаем обратную задачу перевода из коэфициентов в элементы # Решаем систему уравнений NH4NO3_s = sym.solve([NH4NO3f, Nf], [m['NH4'], m['NO3']]) print("Решаем систему уравнений для NH3 и NO3") display({ Nf, NH4NO3f, }) print("Результат") display(sym.Eq(m['NH4'], NH4NO3_s[m['NH4']])) display(sym.Eq(m['NO3'], NH4NO3_s[m['NO3']])) Elements = [N, m['K'], m['Ca'], m['Mg']] NKCaMg_s = sym.solve([Sum_k, KNf, KCaf, KMgf], Elements) print("Решаем систему уравнений для N, K, Ca, Mg") display({ Sum_k, KNf, KCaf, KMgf }) print("Результат") for e in Elements: display(sym.Eq(e, NKCaMg_s[e])) # Уравнение ионного баланса Cations = ( ((m['NH4'] * r) / M['NH4']) + ((2*m['Ca']*r) / M['Ca']) + ((2*m['Mg']*r) / M['Mg']) + ((m['K']*r) / M['K']) ) Anions = ((m['NO3']/ M['NO3']) + (m['P'] / M['P']) + ((2*m['S'])/ M['S']) + (m['Cl']/ M['Cl'])) ECf = sym.Eq(EC, 0.095 * Cations + 0.19) # Вычисляем текущий EC ECv = ECf.subs(repl).rhs print('Текущий EC') print(f'EC = {ECv:0.3f}') # Вычисляем существующие коэфициенты r_k = { N: repl[m['NO3']] + repl[m['NH4']], NH4NO3: repl[m['NH4']] / repl[m['NO3']], KCa: repl[m['K']] / repl[m['Ca']], KMg: repl[m['K']] / repl[m['Mg']], } r_k[KN] = repl[m['K']] / r_k[N] print(r_k) print("Вычисляем % элементов по коэфициентам") rN = NKCaMg_s[N].subs(r_k) rK = NKCaMg_s[m['K']].subs(r_k) rCa = NKCaMg_s[m['Ca']].subs(r_k) rMg = NKCaMg_s[m['Mg']].subs(r_k) rNH4 = NH4NO3_s[m['NH4']].subs({**r_k, N: rN}) rNO3 = NH4NO3_s[m['NO3']].subs({**r_k, N: rN}) print(f'rN={rN:.4f} rNO3={rNO3:.4f} rNH4={rNH4:.4f} rK={rK:.4f} rCa={rCa:.4f} rMg={rMg:.4f}') # Решаем уравнение print("Решаем уравнение с неизвестной r") display(ECf) solved_r = sym.solve([ECf],(r))[r] display(sym.Eq(r, solved_r)) ECnew = ECv r2 = {**repl, EC: ECnew, m['NH4'] : rNH4, m['NO3']: rNO3, m['K'] : rK, m['Ca'] : rCa, m['Mg'] : rMg, } # Вычисляем коэфициент r_k = solved_r.subs(r2) print(f'r = {r_k:0.2f}') print('Проверяем новый ЕС') EC_p = EC.subs({**r2, r: r_k }) print(f'EC = {EC_p:0.3f}') print('Считаем новый профиль') r3 = dict(repl) for e in ['NO3', 'NH4', 'K', 'Ca', 'Mg']: mE = r2[m[e]] * r_k r3[m[e]] = mE print(f'{e}={mE:.2f}') I = (Cations - Anions).subs(r3) print(f"I = {I:0.3f}") mS = solved_S.subs(r3) print(f'S={r3[m["S"]]:0.2f} -> {mS:0.2f}') # Фосфор - неизменен, сера пересчитывается по балансу print("Пересчитываем на EC=1.5") r2 = {**r2, EC: 1.5, m['NH4'] : rNH4, m['K'] : rK, m['Ca'] : rCa, m['Mg'] : rMg, } # Вычисляем коэфициент r_k = solved_r.subs(r2) print(f'r = {r_k:0.2f}') print('Проверяем новый ЕС') EC_p = EC.subs({**r2, r: r_k }) print(f'EC = {EC_p:0.3f}') print('Считаем новый профиль') r3 = dict(repl) for e in ['NO3', 'NH4', 'K', 'Ca', 'Mg']: mE = r2[m[e]] * r_k r3[m[e]] = mE print(f'{e}={mE:.2f}') print(f"NH4/NO3 = {r3[m['NH4']] / r3[m['NO3']]}") I = (Cations - Anions).subs(r3) print(f"I = {I:0.3f}") mS = solved_S.subs(r3) print(f'S={r3[m["S"]]:0.2f} -> {mS:0.2f}') I = (Cations - Anions).subs({**r3, m['S']: mS}) print(f"I = {I:0.3f}") ``` Решаем систему уравнений для NH3 и NO3 $\displaystyle \left\{\frac{m_{NH4}}{m_{NO3}} = K_{NH4NO3}, m_{NH4} + m_{NO3} = m_{N}\right\}$ Результат $\displaystyle m_{NH4} = \frac{K_{NH4NO3} m_{N}}{K_{NH4NO3} + 1}$ $\displaystyle m_{NO3} = \frac{m_{N}}{K_{NH4NO3} + 1}$ Решаем систему уравнений для N, K, Ca, Mg $\displaystyle \left\{\frac{m_{K}}{m_{Ca}} = K_{KCa}, \frac{m_{K}}{m_{Mg}} = K_{KMg}, \frac{m_{K}}{m_{N}} = K_{KN}, m_{Ca} + m_{K} + m_{Mg} + m_{N} = 1\right\}$ Результат $\displaystyle m_{N} = \frac{K_{KCa} K_{KMg}}{K_{KCa} K_{KMg} K_{KN} + K_{KCa} K_{KMg} + K_{KCa} K_{KN} + K_{KMg} K_{KN}}$ $\displaystyle m_{K} = \frac{K_{KCa} K_{KMg} K_{KN}}{K_{KCa} K_{KMg} K_{KN} + K_{KCa} K_{KMg} + K_{KCa} K_{KN} + K_{KMg} K_{KN}}$ $\displaystyle m_{Ca} = \frac{K_{KMg} K_{KN}}{K_{KCa} K_{KMg} K_{KN} + K_{KCa} K_{KMg} + K_{KCa} K_{KN} + K_{KMg} K_{KN}}$ $\displaystyle m_{Mg} = \frac{K_{KCa} K_{KN}}{K_{KCa} K_{KMg} K_{KN} + K_{KCa} K_{KMg} + K_{KCa} K_{KN} + K_{KMg} K_{KN}}$ Текущий EC EC = 2.102 {m_N: 220, K_NH4NO3: 0.1, K_KCa: 0.9, K_KMg: 3.6, K_KN: 0.8181818181818182} Вычисляем % элементов по коэфициентам rN=0.3385 rNO3=0.3077 rNH4=0.0308 rK=0.2769 rCa=0.3077 rMg=0.0769 Решаем уравнение с неизвестной r $\displaystyle EC = 0.19 + \frac{0.095 m_{NH4} r}{M_{NH4}} + \frac{0.19 m_{Mg} r}{M_{Mg}} + \frac{0.095 m_{K} r}{M_{K}} + \frac{0.19 m_{Ca} r}{M_{Ca}}$ $\displaystyle r = \frac{200.0 EC M_{Ca} M_{K} M_{Mg} M_{NH4} - 38.0 M_{Ca} M_{K} M_{Mg} M_{NH4}}{19.0 M_{Ca} M_{K} M_{Mg} m_{NH4} + 38.0 M_{Ca} M_{K} M_{NH4} m_{Mg} + 19.0 M_{Ca} M_{Mg} M_{NH4} m_{K} + 38.0 M_{K} M_{Mg} M_{NH4} m_{Ca}}$ r = 650.00 Проверяем новый ЕС EC = 2.102 Считаем новый профиль NO3=200.00 NH4=20.00 K=180.00 Ca=200.00 Mg=50.00 I = 0.000 S=72.44 -> 72.45 Пересчитываем на EC=1.5 r = 445.34 Проверяем новый ЕС EC = 1.500 Считаем новый профиль NO3=137.03 NH4=13.70 K=123.32 Ca=137.03 Mg=34.26 NH4/NO3 = 0.100000000000000 I = -1.841 S=72.44 -> 42.93 I = 0.000 ```python # Печатаем уравнения для кодирования for e, f in NH4NO3_s.items(): print(f'{e} = {f}') for e, f in NKCaMg_s.items(): print(f'{e} = {f}') print(f'r = {solved_r}') ``` m_NH4 = K_NH4NO3*m_N/(K_NH4NO3 + 1) m_NO3 = m_N/(K_NH4NO3 + 1) m_N = K_KCa*K_KMg/(K_KCa*K_KMg*K_KN + K_KCa*K_KMg + K_KCa*K_KN + K_KMg*K_KN) m_K = K_KCa*K_KMg*K_KN/(K_KCa*K_KMg*K_KN + K_KCa*K_KMg + K_KCa*K_KN + K_KMg*K_KN) m_Ca = K_KMg*K_KN/(K_KCa*K_KMg*K_KN + K_KCa*K_KMg + K_KCa*K_KN + K_KMg*K_KN) m_Mg = K_KCa*K_KN/(K_KCa*K_KMg*K_KN + K_KCa*K_KMg + K_KCa*K_KN + K_KMg*K_KN) r = (200.0*EC*M_Ca*M_K*M_Mg*M_NH4 - 38.0*M_Ca*M_K*M_Mg*M_NH4)/(19.0*M_Ca*M_K*M_Mg*m_NH4 + 38.0*M_Ca*M_K*M_NH4*m_Mg + 19.0*M_Ca*M_Mg*M_NH4*m_K + 38.0*M_K*M_Mg*M_NH4*m_Ca) ## Расчет навески ```python ''' Решение через уравнение ''' elements = ['NO3', 'NH4', 'P', 'K', 'Ca', 'Mg', 'S', 'Cl'] Fertilizers = [ 'Ca(NO3)2', 'KNO3', 'NH4NO3', 'MgSO4', 'KH2PO4', 'K2SO4', # 'Mg(NO3)2', 'CaCl2', ] F = dict(zip(Fertilizers, sym.symbols([f'F_{e}' for e in Fertilizers]))) m = dict(zip(elements, sym.symbols([f'm_{e}' for e in elements]))) M = dict(zip(elements, sym.symbols([f'M_{e}' for e in elements]))) F_elems = [ #['NO3', ['Ca(NO3)2', 'KNO3', 'NH4NO3']], ['NH4', ['NH4NO3']], ['P', ['KH2PO4']], ['K', ['KNO3', 'KH2PO4', 'K2SO4']], ['Ca', ['CaCl2', 'Ca(NO3)2']], ['Mg', ['MgSO4', 'Mg(NO3)2']], ['S', ['MgSO4', 'K2SO4']], ['Cl', ['CaCl2']], ] System = [] for [el, fer] in F_elems: for _f in fer: if _f in Fertilizers: F[f'{_f}_{el}'] = sym.symbols(f'F_{_f}_{el}') System.append( Eq(m[el], sum([F[_f]*F[f'{_f}_{el}'] for _f in fer if _f in Fertilizers]) )) print("Решаем систему уравнений") display(System) ferts = sym.solve(System, [F[_f] for _f in Fertilizers]) print("Уравнения по каждому удобрению") for _f in Fertilizers: if _f in Fertilizers: display( Eq(F[_f], ferts[F[_f]]) ) repl = { #NPK m['NO3'] : 200, m['NH4'] : 20, m['P'] : 40, m['K'] : 180, m['Ca'] : 200, m['Mg'] : 50, m['S']: 68.52, m['Cl']: 10, # Молярные массы M['NO3'] : 14.0067, M['NH4'] : 14.0067, M['Ca'] : 40.078, M['Mg'] : 24.305, M['K'] : 39.0983, M['P'] : 30.0983, M['S'] : 32.065, M['Cl']: 35.45, } repl[m['S']] = solved_S.subs(repl) ferts_perc ={ # Процентовки 'Ca(NO3)2_Ca':16.972, 'Ca(NO3)2_NO3':11.863, 'KNO3_K':38.672, 'KNO3_NO3':13.854, 'NH4NO3_NO3':17.499, 'NH4NO3_NH4':17.499, 'MgSO4_Mg':9.861, 'MgSO4_S':13.010, 'KH2PO4_K':28.731, 'KH2PO4_P':22.761, 'K2SO4_K':44.874, 'K2SO4_S':18.401, 'Mg(NO3)2_Mg': 9.479, 'Mg(NO3)2_NO3': 10.925, 'CaCl2_Ca':18.294, 'CaCl2_Cl':32.366, } for [k, v] in ferts_perc.items(): if k in F: repl[F[k]] = v print("Подставля процентовку удобрений получаем расчет, в г") weights = {} for _f in Fertilizers: w = ferts[F[_f]].subs(repl) display(Eq(F[_f], round(w,4))) weights[_f] = w print("Проверка профиля") for _e in elements: Ep = repl[m[_e]] Ef = 0 for _f in Fertilizers: k = f'{_f}_{_e}' if k in ferts_perc and _f in weights: Ef += weights[_f] * (ferts_perc[k]) print(f'{_e} = {Ep} - {Ef:0.2f} = {round(Ef - Ep,2)}') ``` Решаем систему уравнений $\displaystyle \left[ m_{NH4} = F_{NH4NO3} F_{NH4NO3 NH4}, \ m_{P} = F_{KH2PO4} F_{KH2PO4 P}, \ m_{K} = F_{K2SO4} F_{K2SO4 K} + F_{KH2PO4} F_{KH2PO4 K} + F_{KNO3} F_{KNO3 K}, \ m_{Ca} = F_{Ca(NO3)2} F_{Ca(NO3)2 Ca} + F_{CaCl2} F_{CaCl2 Ca}, \ m_{Mg} = F_{MgSO4} F_{MgSO4 Mg}, \ m_{S} = F_{K2SO4} F_{K2SO4 S} + F_{MgSO4} F_{MgSO4 S}, \ m_{Cl} = F_{CaCl2} F_{CaCl2 Cl}\right]$ Уравнения по каждому удобрению $\displaystyle F_{Ca(NO3)2} = \frac{- F_{CaCl2 Ca} m_{Cl} + F_{CaCl2 Cl} m_{Ca}}{F_{Ca(NO3)2 Ca} F_{CaCl2 Cl}}$ $\displaystyle F_{KNO3} = \frac{- F_{K2SO4 K} F_{KH2PO4 P} F_{MgSO4 Mg} m_{S} + F_{K2SO4 K} F_{KH2PO4 P} F_{MgSO4 S} m_{Mg} - F_{K2SO4 S} F_{KH2PO4 K} F_{MgSO4 Mg} m_{P} + F_{K2SO4 S} F_{KH2PO4 P} F_{MgSO4 Mg} m_{K}}{F_{K2SO4 S} F_{KH2PO4 P} F_{KNO3 K} F_{MgSO4 Mg}}$ $\displaystyle F_{NH4NO3} = \frac{m_{NH4}}{F_{NH4NO3 NH4}}$ $\displaystyle F_{MgSO4} = \frac{m_{Mg}}{F_{MgSO4 Mg}}$ $\displaystyle F_{KH2PO4} = \frac{m_{P}}{F_{KH2PO4 P}}$ $\displaystyle F_{K2SO4} = \frac{F_{MgSO4 Mg} m_{S} - F_{MgSO4 S} m_{Mg}}{F_{K2SO4 S} F_{MgSO4 Mg}}$ $\displaystyle F_{CaCl2} = \frac{m_{Cl}}{F_{CaCl2 Cl}}$ Подставля процентовку удобрений получаем расчет, в г $\displaystyle F_{Ca(NO3)2} = 11.4511$ $\displaystyle F_{KNO3} = 3.2255$ $\displaystyle F_{NH4NO3} = 1.1429$ $\displaystyle F_{MgSO4} = 5.0705$ $\displaystyle F_{KH2PO4} = 1.7574$ $\displaystyle F_{K2SO4} = 0.1064$ $\displaystyle F_{CaCl2} = 0.309$ Проверка профиля NO3 = 200 - 200.53 = 0.53 NH4 = 20 - 20.00 = 0 P = 40 - 40.00 = 0 K = 180 - 180.00 = 0.0 Ca = 200 - 200.00 = 0.0 Mg = 50 - 50.00 = 0 S = 67.9239233594011 - 67.92 = 0 Cl = 10 - 10.00 = 0 ```python """ Алгоритмическое решение """ elements = ['NO3', 'NH4', 'P', 'K', 'Ca', 'Mg', 'S', 'Cl'] Fertilizers = [ 'K2SO4', 'Ca(NO3)2', 'KNO3', 'NH4NO3', 'MgSO4', 'KH2PO4', #'Mg(NO3)2', 'CaCl2', ] F_elems = dict([ ['NO3', ['Ca(NO3)2', 'KNO3', 'NH4NO3', 'Mg(NO3)2']], ['NH4', ['NH4NO3']], ['P', ['KH2PO4']], ['K', ['KNO3', 'KH2PO4', 'K2SO4']], ['Ca', ['CaCl2', 'Ca(NO3)2']], ['Mg', ['MgSO4', 'Mg(NO3)2']], ['S', ['MgSO4', 'K2SO4']], ['Cl', ['CaCl2']], ] ) npk = { 'NO3' : 200, 'NH4' : 20, 'P' : 40, 'K' : 180, 'Ca' : 200, 'Mg' : 56, 'Cl': 10, 'S': 67.92, } ferts_perc ={ # Процентовки 'Ca(NO3)2_Ca':16.972, 'Ca(NO3)2_NO3':11.863, 'KNO3_K':38.672, 'KNO3_NO3':13.854, 'NH4NO3_NO3':17.499, 'NH4NO3_NH4':17.499, 'MgSO4_Mg':9.861, 'MgSO4_S':13.010, 'KH2PO4_K':28.731, 'KH2PO4_P':22.761, 'K2SO4_K':44.874, 'K2SO4_S':18.401, 'Mg(NO3)2_Mg': 9.479, 'Mg(NO3)2_NO3': 10.925, 'CaCl2_Ca':18.294, 'CaCl2_Cl':32.366, } for (k, v) in list(ferts_perc.items()): f, el = k.split('_') if f not in ferts_perc: ferts_perc[f] = {} ferts_perc[f][el] = v #print(ferts_perc) dNPK = dict(sorted(npk.items(), key=lambda i: i[1])) #print(dNPK) weights = {} for el in dNPK: for _f in Fertilizers: if _f not in F_elems[el]: continue if el == 'NO3': continue if _f in weights or _f not in Fertilizers: continue perc = dict(ferts_perc[_f]) w = dNPK[el] / perc.pop(el) print(f'{_f} = {round(w,4)}') for _el, _p in perc.items(): dNPK[_el] -= w * _p weights[_f] = w print("Проверка профиля") for _e in elements: Ep = npk[_e] Ef = 0 for _f in Fertilizers: k = f'{_f}_{_e}' if k in ferts_perc and _f in weights: Ef += weights[_f] * (ferts_perc[k]) print(f'{_e} = {Ep:0.2f} - {Ef:0.2f} = {round(Ep - Ef,2)}') # На данный момент оно собирает неточно ``` CaCl2 = 0.309 NH4NO3 = 1.1429 KH2PO4 = 1.7574 MgSO4 = 5.6789 K2SO4 = -0.3241 KNO3 = 3.7249 Ca(NO3)2 = 11.4511 Проверка профиля NO3 = 200.00 - 207.45 = -7.45 NH4 = 20.00 - 20.00 = 0.0 P = 40.00 - 40.00 = 0.0 K = 180.00 - 180.00 = 0.0 Ca = 200.00 - 200.00 = 0.0 Mg = 56.00 - 56.00 = 0.0 S = 67.92 - 67.92 = 0.0 Cl = 10.00 - 10.00 = 0.0 ```python """ Решение системами линейных уравнений """ # Пока не работает elements = ['NO3', 'NH4', 'P', 'K', 'Ca', 'Mg', 'S', 'Cl'] Fertilizers = [ 'K2SO4', 'Ca(NO3)2', 'KNO3', 'NH4NO3', 'MgSO4', 'KH2PO4', #'Mg(NO3)2', 'CaCl2', ] F_elems = dict([ ['NO3', ['Ca(NO3)2', 'KNO3', 'NH4NO3', 'Mg(NO3)2']], ['NH4', ['NH4NO3']], ['P', ['KH2PO4']], ['K', ['KNO3', 'KH2PO4', 'K2SO4']], ['Ca', ['CaCl2', 'Ca(NO3)2']], ['Mg', ['MgSO4', 'Mg(NO3)2']], ['S', ['MgSO4', 'K2SO4']], ['Cl', ['CaCl2']], ] ) npk = { 'NO3' : 200, 'NH4' : 20, 'P' : 40, 'K' : 180, 'Ca' : 200, 'Mg' : 56, 'Cl': 10, 'S': 67.92, } ferts_perc ={ # Процентовки 'Ca(NO3)2_Ca':16.972, 'Ca(NO3)2_NO3':11.863, 'KNO3_K':38.672, 'KNO3_NO3':13.854, 'NH4NO3_NO3':17.499, 'NH4NO3_NH4':17.499, 'MgSO4_Mg':9.861, 'MgSO4_S':13.010, 'KH2PO4_K':28.731, 'KH2PO4_P':22.761, 'K2SO4_K':44.874, 'K2SO4_S':18.401, 'Mg(NO3)2_Mg': 9.479, 'Mg(NO3)2_NO3': 10.925, 'CaCl2_Ca':18.294, 'CaCl2_Cl':32.366, } for (k, v) in list(ferts_perc.items()): f, el = k.split('_') if f not in ferts_perc: ferts_perc[f] = {} ferts_perc[f][el] = v # Решение A = [] for el, ferts in F_elems.items(): r = [] for f in Fertilizers: if f not in ferts: r.append(0) else: r.append(ferts_perc[f][el]) A.append(r) B = [[npk[el]] for el in F_elems] print(A) print(B) print(len(A[0]), len(B)) A_len = len(A[0]) B_len = len(B) if A_len < B_len: for i in range(B_len - A_len): for r in A: r.append(1) r = [i[0] for i in numpy.linalg.solve(A,B)] print(r[-1]) weights = dict(zip(Fertilizers, r)) for f, w in weights.items(): print(f'{f} = {w:.2f}') # Проверка print("Проверка профиля") for _e in elements: Ep = npk[_e] Ef = 0 for _f in Fertilizers: k = f'{_f}_{_e}' if k in ferts_perc and _f in weights: Ef += weights[_f] * (ferts_perc[k]) print(f'{_e} = {Ep:0.2f} - {Ef:0.2f} = {round(Ep - Ef,2)}') ``` [[0, 11.863, 13.854, 17.499, 0, 0, 0], [0, 0, 0, 17.499, 0, 0, 0], [0, 0, 0, 0, 0, 22.761, 0], [44.874, 0, 38.672, 0, 0, 28.731, 0], [0, 16.972, 0, 0, 0, 0, 18.294], [0, 0, 0, 0, 9.861, 0, 0], [18.401, 0, 0, 0, 13.01, 0, 0], [0, 0, 0, 0, 0, 0, 32.366]] [[200], [20], [40], [180], [200], [56], [67.92], [10]] 7 8 15.236063909134588 K2SO4 = -0.06 Ca(NO3)2 = 11.06 KNO3 = 3.52 NH4NO3 = 0.27 MgSO4 = 4.13 KH2PO4 = 1.09 CaCl2 = -0.16 Проверка профиля NO3 = 200.00 - 184.76 = 15.24 NH4 = 20.00 - 4.76 = 15.24 P = 40.00 - 24.76 = 15.24 K = 180.00 - 164.76 = 15.24 Ca = 200.00 - 184.76 = 15.24 Mg = 56.00 - 40.76 = 15.24 S = 67.92 - 52.68 = 15.24 Cl = 10.00 - -5.24 = 15.24 ```python import numpy.linalg """ x - y = -5 2x + y = -7 """ a = [[1, -1], [2, 1]] b = [[-5], [-7]] r = numpy.linalg.solve(a,b) print(f"x={r[0][0]} y={r[1][0]}") """ x - y + z = -5 2x + y + z = -7 """ a = [[1, -1, 1], [2, 1, 1], [1,1,1]] b = [[-5], [-7], [0]] r = numpy.linalg.solve(a,b) print(f"x={r[0][0]} y={r[1][0]} z={r[2][0]}") print(-10-4+9) print(2*-10+4+9) """ x - y = -5 2x + y = -7 2x + y = 10 """ a = [[1, -1, 1], [2, 1, 1], [1, 1, 1]] b = [[-5], [-7], [10]] r = numpy.linalg.solve(a,b) print(f"x={r[0][0]} y={r[1][0]} z={r[2][0]}") print(-10-4+9) print(2*-10+4+9) """ 17.33x = 200 17.33x = 20 """ a = [[17.33], [17.33]] b = [200, 20] w = numpy.linalg.lstsq(a,b)[0][0] print(w) ``` x=-4.0 y=1.0 x=-7.0 y=2.5 z=4.5 -5 -7 x=-17.0 y=7.5 z=19.5 -5 -7 6.347374495095211 110.0 <ipython-input-51-5da7e57cab58>:51: FutureWarning: `rcond` parameter will change to the default of machine precision times ``max(M, N)`` where M and N are the input matrix dimensions. To use the future default and silence this warning we advise to pass `rcond=None`, to keep using the old, explicitly pass `rcond=-1`. w = numpy.linalg.lstsq(a,b)[0][0] ```python import numpy as np # https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.linalg.lstsq.html#numpy.linalg.lstsq x = np.array([0, 1, 2, 3]) y = np.array([-1, 0.2, 0.9, 2.1]) A = np.vstack([x, np.ones(len(x))]).T print(A) r = np.linalg.lstsq(A, y) print(r) m, c = r[0] print(m, c) ``` [[0. 1.] [1. 1.] [2. 1.] [3. 1.]] (array([ 1. , -0.95]), array([0.05]), 2, array([4.10003045, 1.09075677])) 1.0000000000000002 -0.9499999999999996 <ipython-input-38-694e3cc76ac4>:7: FutureWarning: `rcond` parameter will change to the default of machine precision times ``max(M, N)`` where M and N are the input matrix dimensions. To use the future default and silence this warning we advise to pass `rcond=None`, to keep using the old, explicitly pass `rcond=-1`. r = np.linalg.lstsq(A, y) ```python import numpy as np A = [[0, 11.863, 13.854, 17.499, 0, 0, 0], [0, 0, 0, 17.499, 0, 0, 0], [0, 0, 0, 0, 0, 22.761, 0], [44.874, 0, 38.672, 0, 0, 28.731, 0], [0, 16.972, 0, 0, 0, 0, 18.294], [0, 0, 0, 0, 9.861, 0, 0], [18.401, 0, 0, 0, 13.01, 0, 0], [0, 0, 0, 0, 0, 0, 32.366]] B = [[200], [20], [40], [180], [200], [56], [67.92], [10]] A_len = len(A[0]) B_len = len(B) r = np.linalg.qr([A, B]) print(r) ```
section \<open>Getting Small Representative Polynomials via Factorization\<close> text \<open>In this theory we import a factorization algorithm for integer polynomials to turn a representing polynomial of some algebraic number into a list of irreducible polynomials where exactly one list element represents the same number. Moreover, we prove that the certain polynomial operations preserve irreducibility, so that no factorization is required.\<close> theory Factors_of_Int_Poly imports Berlekamp_Zassenhaus.Factorize_Int_Poly Algebraic_Numbers_Prelim begin lemma degree_of_gcd: "degree (gcd q r) \<noteq> 0 \<longleftrightarrow> degree (gcd (of_int_poly q :: 'a :: {field_char_0, field_gcd} poly) (of_int_poly r)) \<noteq> 0" proof - let ?r = "of_rat :: rat \<Rightarrow> 'a" interpret rpoly: field_hom' ?r by (unfold_locales, auto simp: of_rat_add of_rat_mult) { fix p have "of_int_poly p = map_poly (?r o of_int) p" unfolding o_def by auto also have "\<dots> = map_poly ?r (map_poly of_int p)" by (subst map_poly_map_poly, auto) finally have "of_int_poly p = map_poly ?r (map_poly of_int p)" . } note id = this show ?thesis unfolding id by (fold hom_distribs, simp add: gcd_rat_to_gcd_int) qed definition factors_of_int_poly :: "int poly \<Rightarrow> int poly list" where "factors_of_int_poly p = map (abs_int_poly o fst) (snd (factorize_int_poly p))" lemma factors_of_int_poly_const: assumes "degree p = 0" shows "factors_of_int_poly p = []" proof - from degree0_coeffs[OF assms] obtain a where p: "p = [: a :]" by auto show ?thesis unfolding p factors_of_int_poly_def factorize_int_poly_generic_def x_split_def by (cases "a = 0", auto simp add: Let_def factorize_int_last_nz_poly_def) qed lemma factors_of_int_poly: defines "rp \<equiv> ipoly :: int poly \<Rightarrow> 'a :: {field_gcd,field_char_0} \<Rightarrow> 'a" assumes "factors_of_int_poly p = qs" shows "\<And> q. q \<in> set qs \<Longrightarrow> irreducible q \<and> lead_coeff q > 0 \<and> degree q \<le> degree p \<and> degree q \<noteq> 0" "p \<noteq> 0 \<Longrightarrow> rp p x = 0 \<longleftrightarrow> (\<exists> q \<in> set qs. rp q x = 0)" "p \<noteq> 0 \<Longrightarrow> rp p x = 0 \<Longrightarrow> \<exists>! q \<in> set qs. rp q x = 0" "distinct qs" proof - obtain c qis where factt: "factorize_int_poly p = (c,qis)" by force from assms[unfolded factors_of_int_poly_def factt] have qs: "qs = map (abs_int_poly \<circ> fst) (snd (c, qis))" by auto note fact = factorize_int_poly(1)[OF factt] note fact_mem = factorize_int_poly(2,3)[OF factt] have sqf: "square_free_factorization p (c, qis)" by (rule fact(1)) note sff = square_free_factorizationD[OF sqf] have sff': "p = Polynomial.smult c (\<Prod>(a, i)\<leftarrow> qis. a ^ Suc i)" unfolding sff(1) prod.distinct_set_conv_list[OF sff(5)] .. { fix q assume q: "q \<in> set qs" then obtain r i where qi: "(r,i) \<in> set qis" and qr: "q = abs_int_poly r" unfolding qs by auto from split_list[OF qi] obtain qis1 qis2 where qis: "qis = qis1 @ (r,i) # qis2" by auto have dvd: "r dvd p" unfolding sff' qis dvd_def by (intro exI[of _ "smult c (r ^ i * (\<Prod>(a, i)\<leftarrow>qis1 @ qis2. a ^ Suc i))"], auto) from fact_mem[OF qi] have r0: "r \<noteq> 0" by auto from qi factt have p: "p \<noteq> 0" by (cases p, auto) with dvd have deg: "degree r \<le> degree p" by (metis dvd_imp_degree_le) with fact_mem[OF qi] r0 show "irreducible q \<and> lead_coeff q > 0 \<and> degree q \<le> degree p \<and> degree q \<noteq> 0" unfolding qr lead_coeff_abs_int_poly by auto } note * = this show "distinct qs" unfolding distinct_conv_nth proof (intro allI impI) fix i j assume "i < length qs" "j < length qs" and diff: "i \<noteq> j" hence ij: "i < length qis" "j < length qis" and id: "qs ! i = abs_int_poly (fst (qis ! i))" "qs ! j = abs_int_poly (fst (qis ! j))" unfolding qs by auto obtain qi I where qi: "qis ! i = (qi, I)" by force obtain qj J where qj: "qis ! j = (qj, J)" by force from sff(5)[unfolded distinct_conv_nth, rule_format, OF ij diff] qi qj have diff: "(qi, I) \<noteq> (qj, J)" by auto from ij qi qj have "(qi, I) \<in> set qis" "(qj, J) \<in> set qis" unfolding set_conv_nth by force+ from sff(3)[OF this diff] sff(2) this have cop: "coprime qi qj" "degree qi \<noteq> 0" "degree qj \<noteq> 0" by auto note i = cf_pos_poly_main[of qi, unfolded smult_prod monom_0] note j = cf_pos_poly_main[of qj, unfolded smult_prod monom_0] from cop(2) i have deg: "degree (qs ! i) \<noteq> 0" by (auto simp: id qi) have cop: "coprime (qs ! i) (qs ! j)" unfolding id qi qj fst_conv apply (rule coprime_prod[of "[:sgn (lead_coeff qi):]" "[:sgn (lead_coeff qj):]"]) using cop unfolding i j by (auto simp: sgn_eq_0_iff) show "qs ! i \<noteq> qs ! j" proof assume id: "qs ! i = qs ! j" have "degree (gcd (qs ! i) (qs ! j)) = degree (qs ! i)" unfolding id by simp also have "\<dots> \<noteq> 0" using deg by simp finally show False using cop by simp qed qed assume p: "p \<noteq> 0" from fact(1) p have c: "c \<noteq> 0" using sff(1) by auto let ?r = "of_int :: int \<Rightarrow> 'a" let ?rp = "map_poly ?r" have rp: "\<And> x p. rp p x = 0 \<longleftrightarrow> poly (?rp p) x = 0" unfolding rp_def .. have "rp p x = 0 \<longleftrightarrow> rp (\<Prod>(x, y)\<leftarrow>qis. x ^ Suc y) x = 0" unfolding sff'(1) unfolding rp hom_distribs using c by simp also have "\<dots> = (\<exists> (q,i) \<in>set qis. poly (?rp (q ^ Suc i)) x = 0)" unfolding qs rp of_int_poly_hom.hom_prod_list poly_prod_list_zero_iff set_map by fastforce also have "\<dots> = (\<exists> (q,i) \<in>set qis. poly (?rp q) x = 0)" unfolding of_int_poly_hom.hom_power poly_power_zero_iff by auto also have "\<dots> = (\<exists> q \<in> fst ` set qis. poly (?rp q) x = 0)" by force also have "\<dots> = (\<exists> q \<in> set qs. rp q x = 0)" unfolding rp qs snd_conv o_def bex_simps set_map by simp finally show iff: "rp p x = 0 \<longleftrightarrow> (\<exists> q \<in> set qs. rp q x = 0)" by auto assume "rp p x = 0" with iff obtain q where q: "q \<in> set qs" and rtq: "rp q x = 0" by auto then obtain i q' where qi: "(q',i) \<in> set qis" and qq': "q = abs_int_poly q'" unfolding qs by auto show "\<exists>! q \<in> set qs. rp q x = 0" proof (intro ex1I, intro conjI, rule q, rule rtq, clarify) fix r assume "r \<in> set qs" and rtr: "rp r x = 0" then obtain j r' where rj: "(r',j) \<in> set qis" and rr': "r = abs_int_poly r'" unfolding qs by auto from rtr rtq have rtr: "rp r' x = 0" and rtq: "rp q' x = 0" unfolding rp rr' qq' by auto from rtr rtq have "[:-x,1:] dvd ?rp q'" "[:-x,1:] dvd ?rp r'" unfolding rp by (auto simp: poly_eq_0_iff_dvd) hence "[:-x,1:] dvd gcd (?rp q') (?rp r')" by simp hence "gcd (?rp q') (?rp r') = 0 \<or> degree (gcd (?rp q') (?rp r')) \<noteq> 0" by (metis is_unit_gcd_iff is_unit_iff_degree is_unit_pCons_iff one_poly_eq_simps(1)) hence "gcd q' r' = 0 \<or> degree (gcd q' r') \<noteq> 0" unfolding gcd_eq_0_iff degree_of_gcd[of q' r',symmetric] by auto hence "\<not> coprime q' r'" by auto with sff(3)[OF qi rj] have "q' = r'" by auto thus "r = q" unfolding rr' qq' by simp qed qed lemma factors_int_poly_represents: fixes x :: "'a :: {field_char_0,field_gcd}" assumes p: "p represents x" shows "\<exists> q \<in> set (factors_of_int_poly p). q represents x \<and> irreducible q \<and> lead_coeff q > 0 \<and> degree q \<le> degree p" proof - from representsD[OF p] have p: "p \<noteq> 0" and rt: "ipoly p x = 0" by auto note fact = factors_of_int_poly[OF refl] from fact(2)[OF p, of x] rt obtain q where q: "q \<in> set (factors_of_int_poly p)" and rt: "ipoly q x = 0" by auto from fact(1)[OF q] rt show ?thesis by (intro bexI[OF _ q], auto simp: represents_def irreducible_def) qed corollary irreducible_represents_imp_degree: fixes x :: "'a :: {field_char_0,field_gcd}" assumes "irreducible f" and "f represents x" and "g represents x" shows "degree f \<le> degree g" proof - from factors_of_int_poly(1)[OF refl, of _ g] factors_of_int_poly(3)[OF refl, of g x] assms(3) obtain h where *: "h represents x" "degree h \<le> degree g" "irreducible h" by blast let ?af = "abs_int_poly f" let ?ah = "abs_int_poly h" from assms have af: "irreducible ?af" "?af represents x" "lead_coeff ?af > 0" by fastforce+ from * have ah: "irreducible ?ah" "?ah represents x" "lead_coeff ?ah > 0" by fastforce+ from algebraic_imp_represents_unique[of x] af ah have id: "?af = ?ah" unfolding algebraic_iff_represents by blast show ?thesis using arg_cong[OF id, of degree] \<open>degree h \<le> degree g\<close> by simp qed lemma irreducible_preservation: fixes x :: "'a :: {field_char_0,field_gcd}" assumes irr: "irreducible p" and x: "p represents x" and y: "q represents y" and deg: "degree p \<ge> degree q" and f: "\<And> q. q represents y \<Longrightarrow> (f q) represents x \<and> degree (f q) \<le> degree q" and pr: "primitive q" shows "irreducible q" proof (rule ccontr) define pp where "pp = abs_int_poly p" have dp: "degree p \<noteq> 0" using x by (rule represents_degree) have dq: "degree q \<noteq> 0" using y by (rule represents_degree) from dp have p0: "p \<noteq> 0" by auto from x deg irr p0 have irr: "irreducible pp" and x: "pp represents x" and deg: "degree pp \<ge> degree q" and cf_pos: "lead_coeff pp > 0" unfolding pp_def lead_coeff_abs_int_poly by (auto intro!: representsI) from x have ax: "algebraic x" unfolding algebraic_altdef_ipoly represents_def by blast assume "\<not> ?thesis" from this irreducible_connect_int[of q] pr have "\<not> irreducible\<^sub>d q" by auto from this dq obtain r where r: "degree r \<noteq> 0" "degree r < degree q" and "r dvd q" by auto then obtain rr where q: "q = r * rr" unfolding dvd_def by auto have "degree q = degree r + degree rr" using dq unfolding q by (subst degree_mult_eq, auto) with r have rr: "degree rr \<noteq> 0" "degree rr < degree q" by auto from representsD(2)[OF y, unfolded q hom_distribs] have "ipoly r y = 0 \<or> ipoly rr y = 0" by auto with r rr have "r represents y \<or> rr represents y" unfolding represents_def by auto with r rr obtain r where r: "r represents y" "degree r < degree q" by blast from f[OF r(1)] deg r(2) obtain r where r: "r represents x" "degree r < degree pp" by auto from factors_int_poly_represents[OF r(1)] r(2) obtain r where r: "r represents x" "irreducible r" "lead_coeff r > 0" and deg: "degree r < degree pp" by force from algebraic_imp_represents_unique[OF ax] r irr cf_pos x have "r = pp" by auto with deg show False by auto qed declare irreducible_const_poly_iff [simp] lemma poly_uminus_irreducible: assumes p: "irreducible (p :: int poly)" and deg: "degree p \<noteq> 0" shows "irreducible (poly_uminus p)" proof- from deg_nonzero_represents[OF deg] obtain x :: complex where x: "p represents x" by auto from represents_uminus[OF x] have y: "poly_uminus p represents (- x)" . show ?thesis proof (rule irreducible_preservation[OF p x y], force) from deg irreducible_imp_primitive[OF p] have "primitive p" by auto then show "primitive (poly_uminus p)" by simp fix q assume "q represents (- x)" from represents_uminus[OF this] have "(poly_uminus q) represents x" by simp thus "(poly_uminus q) represents x \<and> degree (poly_uminus q) \<le> degree q" by auto qed qed lemma reflect_poly_irreducible: fixes x :: "'a :: {field_char_0,field_gcd}" assumes p: "irreducible p" and x: "p represents x" and x0: "x \<noteq> 0" shows "irreducible (reflect_poly p)" proof - from represents_inverse[OF x0 x] have y: "(reflect_poly p) represents (inverse x)" by simp from x0 have ix0: "inverse x \<noteq> 0" by auto show ?thesis proof (rule irreducible_preservation[OF p x y]) from x irreducible_imp_primitive[OF p] show "primitive (reflect_poly p)" by (auto simp: content_reflect_poly) fix q assume "q represents (inverse x)" from represents_inverse[OF ix0 this] have "(reflect_poly q) represents x" by simp with degree_reflect_poly_le show "(reflect_poly q) represents x \<and> degree (reflect_poly q) \<le> degree q" by auto qed (insert p, auto simp: degree_reflect_poly_le) qed lemma poly_add_rat_irreducible: assumes p: "irreducible p" and deg: "degree p \<noteq> 0" shows "irreducible (cf_pos_poly (poly_add_rat r p))" proof - from deg_nonzero_represents[OF deg] obtain x :: complex where x: "p represents x" by auto from represents_add_rat[OF x] have y: "cf_pos_poly (poly_add_rat r p) represents (of_rat r + x)" by simp show ?thesis proof (rule irreducible_preservation[OF p x y], force) fix q assume "q represents (of_rat r + x)" from represents_add_rat[OF this, of "- r"] have "(poly_add_rat (- r) q) represents x" by (simp add: of_rat_minus) thus "(poly_add_rat (- r) q) represents x \<and> degree (poly_add_rat (- r) q) \<le> degree q" by auto qed (insert p, auto) qed lemma poly_mult_rat_irreducible: assumes p: "irreducible p" and deg: "degree p \<noteq> 0" and r: "r \<noteq> 0" shows "irreducible (cf_pos_poly (poly_mult_rat r p))" proof - from deg_nonzero_represents[OF deg] obtain x :: complex where x: "p represents x" by auto from represents_mult_rat[OF r x] have y: "cf_pos_poly (poly_mult_rat r p) represents (of_rat r * x)" by simp show ?thesis proof (rule irreducible_preservation[OF p x y], force simp: r) fix q from r have r': "inverse r \<noteq> 0" by simp assume "q represents (of_rat r * x)" from represents_mult_rat[OF r' this] have "(poly_mult_rat (inverse r) q) represents x" using r by (simp add: of_rat_divide field_simps) thus "(poly_mult_rat (inverse r) q) represents x \<and> degree (poly_mult_rat (inverse r) q) \<le> degree q" using r by auto qed (insert p r, auto) qed interpretation coeff_lift_hom: factor_preserving_hom "coeff_lift :: 'a :: {comm_semiring_1,semiring_no_zero_divisors} \<Rightarrow> _" by (unfold_locales, auto) end
[STATEMENT] lemma trace_is_Nil[simp]: "\<And>i. (trace d i xs = []) = (xs = [])" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>i. (trace d i xs = []) = (xs = []) [PROOF STEP] by (case_tac "xs") simp_all
Reines , F. & C. L. Cowan , Jr . " On the Detection of the Free Neutrino " , Los Alamos National Laboratory ( LANL ) ( through predecessor agency Los Alamos Scientific Laboratory ) , United States Department of Energy ( through predecessor agency the Atomic Energy Commission ) , ( August 6 , 1953 ) .
From machine_program_logic.program_logic Require Import weakestpre. From HypVeri Require Import machine_extra lifting rules.rules_base. From HypVeri.algebra Require Import base reg mem pagetable mailbox base_extra. From HypVeri.lang Require Import lang_extra reg_extra current_extra. Require Import stdpp.fin. Require Import stdpp.listset_nodup. Section run. Context `{hypparams:HypervisorParameters}. Context `{vmG: !gen_VMG Σ}. Lemma run {E w1 w2 w3 q s p_tx R' Q P} ai i R P': let T := (▷ (PC @@ V0 ->r ai) ∗ ▷ (ai ->a w1) ∗ ▷ (V0 -@{q}A> s) ∗ ▷ (TX@ V0 := p_tx) ∗ ▷ (R0 @@ V0 ->r w2) ∗ ▷ (R1 @@ V0 ->r w3))%I in let T' := ((PC @@ V0 ->r (ai ^+ 1)%f) ∗ ai ->a w1 ∗ V0 -@{q}A> s ∗ TX@ V0 := p_tx ∗ R0 @@ V0 ->r w2 ∗ R1 @@ V0 ->r w3)%I in (tpa ai) ∈ s -> (tpa ai) ≠ p_tx -> i ≠ V0 -> decode_instruction w1 = Some Hvc -> decode_hvc_func w2 = Some Run -> decode_vmid w3 = Some i -> {SS{{ T ∗ ▷ (VMProp i (Q) (1/2)%Qp) ∗ ▷ (VMProp V0 P 1%Qp) ∗ ▷ (T' ∗ R ∗ VMProp V0 P' (1/2)%Qp -∗ (Q ∗ R')) ∗ ▷ R }}} ExecI @ V0 ;E {{{ RET (true, ExecI); R' ∗ VMProp V0 P' (1/2)%Qp}}}. Proof. simpl. iIntros (Hin Hnottx Hneq_v Hdecode Hhvc Hvmid ϕ) "[(>Hpc & >Hapc & >Hacc & >tx & >Hr0 & >Hr1) (HPropi & HPropz & Himpl & HR)] Hϕ". iApply (sswp_lift_atomic_step ExecI); [done|]. iIntros (n σ1) "%Hsche Hσ". rewrite /scheduled in Hsche. simpl in Hsche. rewrite /scheduler in Hsche. apply bool_decide_unpack in Hsche as Hcur. clear Hsche. apply fin_to_nat_inj in Hcur. iModIntro. iDestruct "Hσ" as "(%Hneq & Hmemown & Hreg & Hmb & ? & Hown & Haccessown & Hrest)". (* valid regs *) iDestruct (gen_reg_valid1 PC V0 ai Hcur with "Hreg Hpc") as "%Hpc". iDestruct (gen_reg_valid1 R0 V0 w2 Hcur with "Hreg Hr0") as "%Hr0". iDestruct (gen_reg_valid1 R1 V0 w3 Hcur with "Hreg Hr1") as "%Hr1". (* valid pt *) iDestruct (access_agree_check_true (tpa ai) with "Haccessown Hacc") as %Hacc;first exact Hin. iDestruct (mb_valid_tx with "Hmb tx") as %Htx. subst p_tx. (* valid mem *) iDestruct (gen_mem_valid ai w1 with "Hmemown Hapc") as "%Hmem". iSplit. - (* reducible *) iPureIntro. apply (reducible_normal V0 Hvc ai w1);eauto. - iModIntro. iIntros (m2 σ2) "[%U PAuth] %HstepP". apply (step_ExecI_normal V0 Hvc ai w1) in HstepP; eauto. remember (exec Hvc σ1) as c2 eqn:Heqc2. rewrite /exec /hvc in Heqc2; eauto. rewrite Hr0 /= Hhvc /run Hr1 in Heqc2. simpl in Heqc2. rewrite /unpack_hvc_result_yield Hvmid in Heqc2. simpl in Heqc2. rewrite /is_primary Hcur in Heqc2. destruct HstepP as [Hstep1 Hstep2]. case_bool_decide;last done. subst c2. simpl in Hstep1, Hstep2. subst σ2 m2. simpl. rewrite /gen_vm_interp /update_incr_PC. rewrite (preserve_get_mb_gmap σ1). rewrite (preserve_get_rx_gmap σ1). rewrite (preserve_get_own_gmap σ1). rewrite (preserve_get_access_gmap σ1). rewrite (preserve_get_excl_gmap σ1). rewrite (preserve_get_trans_gmap σ1). rewrite (preserve_get_hpool_gset σ1). rewrite (preserve_get_retri_gmap σ1). rewrite (preserve_inv_trans_pgt_consistent σ1). rewrite (preserve_inv_trans_wellformed σ1). rewrite (preserve_inv_trans_ps_disj σ1). all: try rewrite p_upd_id_mb p_upd_pc_mb //. all: try rewrite p_upd_id_pgt p_upd_pc_pgt //. all: try rewrite p_upd_id_trans p_upd_pc_trans //. rewrite p_upd_id_mem p_upd_pc_mem. iFrame. iDestruct ((gen_reg_update1_global PC V0 ai (ai ^+ 1)%f) with "Hreg Hpc") as "HpcUpd". rewrite (preserve_get_reg_gmap (update_offset_PC σ1 1) (update_current_vmid _ _));last rewrite p_upd_id_reg //. rewrite ->(u_upd_pc_regs _ V0 ai 1); auto. + iDestruct (VMProp_update V0 U P P' with "PAuth HPropz") as "HTemp". iMod "HpcUpd". iMod "HTemp". iDestruct "HTemp" as "[PAuth HPropz]". iModIntro. iDestruct "HpcUpd" as "[? Hpc]". iFrame. iSplitL "PAuth". by iExists P'. iSplit; first done. rewrite /just_scheduled_vms /just_scheduled. assert (filter (λ id : vmid, base.negb (scheduled σ1 id) && scheduled (update_current_vmid (update_offset_PC σ1 1) i) id = true) (seq 0 n) = [fin_to_nat i]) as ->. { rewrite /scheduled /machine.scheduler Hneq //= /scheduler. rewrite /update_current_vmid //=. pose proof (NoDup_seq 0 vm_count) as ND. pose proof (NoDup_singleton ((@fin_to_nat (@vm_count H) i))) as ND'. set f := (λ id : nat, base.negb (bool_decide ((@fin_to_nat (@vm_count H) σ1.1.1.2) = id)) && bool_decide ((@fin_to_nat (@vm_count H) i) = id) = true). pose proof (NoDup_filter f _ ND) as ND''. assert (f i) as Prf. { subst f. simpl. unfold base.negb. repeat case_bool_decide; eauto. rewrite Hcur in H1. exfalso. apply Hneq_v. symmetry. apply fin_to_nat_inj. done. } assert (In (@fin_to_nat (@vm_count H) i) (seq 0 vm_count)) as Prf'. { rewrite <-elem_of_list_In. rewrite elem_of_seq. split. - solve_finz. - rewrite plus_O_n. pose proof (fin_to_nat_lt i). auto. } rewrite <-elem_of_list_In in Prf'. assert (In (@fin_to_nat (@vm_count H) i) (filter f (seq 0 vm_count))) as Prf''. { rewrite <-elem_of_list_In. by apply (iffRL (elem_of_list_filter f (seq 0 vm_count) i)). } rewrite <-elem_of_list_In in Prf''. assert (forall x, x ≠ (@fin_to_nat (@vm_count H) i) -> not (In x (filter f (seq 0 vm_count)))) as excl. { intros x neq c. rewrite <-elem_of_list_In in c. rewrite ->elem_of_list_filter in c. destruct c as [c' _]. subst f. simpl in c'. unfold base.negb in c'. case_match. - by rewrite andb_false_l in c'. - rewrite andb_true_l in c'. apply neq. rewrite ->bool_decide_eq_true in c'. by symmetry. } apply Permutation_length_1_inv. apply NoDup_Permutation; auto. intros x'. split. - intros T. rewrite ->elem_of_list_singleton in T. rewrite T; auto. - intros T. rewrite ->elem_of_list_singleton. rewrite ->elem_of_list_In in T. destruct (decide (x' = i)) as [? | n']; auto. exfalso. by apply (excl x' n'). } iSimpl. assert ((negb (scheduled (update_current_vmid (update_offset_PC σ1 1) i) V0) && true = true)) as ->. { rewrite andb_true_r. rewrite /scheduled /machine.scheduler //= /scheduler. rewrite /update_current_vmid //=. apply eq_true_not_negb. intros c. rewrite ->bool_decide_eq_true in c. apply Hneq_v. apply fin_to_nat_inj. done. } iDestruct (VMProp_split with "HPropz") as "[HPropz1 HPropz2]". iDestruct ("Himpl" with "[Hpc Hapc Hacc Hr0 Hr1 HR HPropz1 tx]") as "[Q R']". iFrame. iSplitR "Hϕ R' HPropz2". iSplit; last done. iExists (Q)%I. iFrame. iApply ("Hϕ" with "[R' HPropz2]"). iFrame. + apply get_reg_gmap_get_reg_Some; auto. Qed. Lemma run_not_primary {E wi r0 r2 q s p_tx } ai i : (tpa ai) ∈ s -> (tpa ai) ≠ p_tx -> decode_instruction wi = Some Hvc -> decode_hvc_func r0 = Some Run -> i ≠ V0 -> {SS{{ ▷ (PC @@ i ->r ai) ∗ ▷ (ai ->a wi) ∗ ▷ (i -@{q}A> s) ∗ ▷ (TX@ i := p_tx) ∗ ▷ (R0 @@ i ->r r0) ∗ ▷ (R2 @@ i ->r r2) }}} ExecI @ i ;E {{{ RET (false, ExecI); PC @@ i ->r (ai ^+ 1)%f ∗ ai ->a wi ∗ i -@{q}A> s ∗ TX@ i := p_tx ∗ R0 @@ i ->r (encode_hvc_ret_code Error) ∗ R2 @@ i ->r (encode_hvc_error Denied) }}}. Proof. iIntros (Hin_acc Hneq_tx Hdecode_i Hdecode_f Hneq_v0 Φ) "(>PC & >mem_ins & >acc & >tx & >R0 & >R2) HΦ". iApply (sswp_lift_atomic_step ExecI);[done|]. iIntros (n σ1) "%Hsche state". rewrite /scheduled /= /scheduler in Hsche. assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. } clear Hsche. iModIntro. iDestruct "state" as "(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl & trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)". (* valid regs *) iDestruct ((gen_reg_valid3 i PC ai R0 r0 R2 r2 Heq_cur) with "regs PC R0 R2") as "(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R2)";eauto. (* valid pt *) iDestruct (access_agree_check_true (tpa ai) i with "pgt_acc acc") as %Hcheckpg_ai;eauto. (* valid mem *) iDestruct (gen_mem_valid ai wi with "mem mem_ins") as %Hlookup_ai. (* valid tx *) iDestruct (mb_valid_tx i p_tx with "mb tx") as %Heq_tx. (* valid tran *) iSplit. - (* reducible *) iPureIntro. apply (reducible_normal i Hvc ai wi);auto. rewrite Heq_tx //. - iModIntro. iIntros (m2 σ2) "vmprop_auth %HstepP". iFrame "vmprop_auth". apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto. 2: rewrite Heq_tx //. remember (exec Hvc σ1) as c2 eqn:Heqc2. rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /= /lang.run /is_primary in Heqc2. case_bool_decide. rewrite H0 in Heq_cur. rewrite Heq_cur // in Hneq_v0. destruct HstepP;subst m2 σ2; subst c2; simpl. iDestruct (hvc_error_update (E:= E) Denied with "PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]") as ">[[$ $] ?]";auto. rewrite /scheduled /machine.scheduler /= /scheduler. rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur. case_bool_decide;last contradiction. simpl. iApply "HΦ". iFrame. by iFrame. Qed. Lemma run_invalid_vmid {E wi r0 r1 r2 q s p_tx } ai : (tpa ai) ∈ s -> (tpa ai) ≠ p_tx -> decode_instruction wi = Some Hvc -> decode_hvc_func r0 = Some Run -> decode_vmid r1 = None -> {SS{{ ▷ (PC @@ V0 ->r ai) ∗ ▷ (ai ->a wi) ∗ ▷ (V0 -@{q}A> s) ∗ ▷ (TX@ V0 := p_tx) ∗ ▷ (R0 @@ V0 ->r r0) ∗ ▷ (R1 @@ V0 ->r r1) ∗ ▷ (R2 @@ V0 ->r r2) }}} ExecI @ V0 ;E {{{ RET (false, ExecI); PC @@ V0 ->r (ai ^+ 1)%f ∗ ai ->a wi ∗ V0 -@{q}A> s ∗ TX@ V0 := p_tx ∗ R0 @@ V0 ->r (encode_hvc_ret_code Error) ∗ R1 @@ V0 ->r r1 ∗ R2 @@ V0 ->r (encode_hvc_error InvParam) }}}. Proof. iIntros (Hin_acc Hneq_tx Hdecode_i Hdecode_f Hdecode_vmid Φ) "(>PC & >mem_ins & >acc & >tx & >R0 &>R1 & >R2) HΦ". iApply (sswp_lift_atomic_step ExecI);[done|]. iIntros (n σ1) "%Hsche state". rewrite /scheduled /= /scheduler in Hsche. assert (σ1.1.1.2 = V0) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. } clear Hsche. iModIntro. iDestruct "state" as "(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl & trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)". (* valid regs *) iDestruct ((gen_reg_valid4 V0 PC ai R0 r0 R1 r1 R2 r2 Heq_cur) with "regs PC R0 R1 R2") as "(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)";eauto. (* valid pt *) iDestruct (access_agree_check_true (tpa ai) V0 with "pgt_acc acc") as %Hcheckpg_ai;eauto. (* valid mem *) iDestruct (gen_mem_valid ai wi with "mem mem_ins") as %Hlookup_ai. (* valid tx *) iDestruct (mb_valid_tx V0 p_tx with "mb tx") as %Heq_tx. (* valid tran *) iSplit. - (* reducible *) iPureIntro. apply (reducible_normal V0 Hvc ai wi);auto. rewrite Heq_tx //. - iModIntro. iIntros (m2 σ2) "vmprop_auth %HstepP". iFrame "vmprop_auth". apply (step_ExecI_normal V0 Hvc ai wi) in HstepP;eauto. 2: rewrite Heq_tx //. remember (exec Hvc σ1) as c2 eqn:Heqc2. rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /= /lang.run /is_primary in Heqc2. case_bool_decide;last contradiction. rewrite Hlookup_R1 /= Hdecode_vmid /= in Heqc2. destruct HstepP;subst m2 σ2; subst c2; simpl. iDestruct (hvc_error_update (E:= E) InvParam with "PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]") as ">[[$ $] ?]";auto. rewrite /scheduled /machine.scheduler /= /scheduler. rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur. case_bool_decide;last contradiction. simpl. iApply "HΦ". iFrame. by iFrame. Qed. Lemma run_primary {E wi r0 r1 q s p_tx} ai : (tpa ai) ∈ s -> (tpa ai) ≠ p_tx -> decode_instruction wi = Some Hvc -> decode_hvc_func r0 = Some Run -> decode_vmid r1 = Some V0 -> {SS{{ ▷ (PC @@ V0 ->r ai) ∗ ▷ (ai ->a wi) ∗ ▷ (V0 -@{q}A> s) ∗ ▷ (TX@ V0 := p_tx) ∗ ▷ (R0 @@ V0 ->r r0) ∗ ▷ (R1 @@ V0 ->r r1)}}} ExecI @ V0 ;E {{{ RET (false, ExecI); PC @@ V0 ->r (ai ^+ 1)%f ∗ ai ->a wi ∗ V0 -@{q}A> s ∗ TX@ V0 := p_tx ∗ R0 @@ V0 ->r r0 ∗ R1 @@ V0 ->r r1}}}. Proof. iIntros (Hin_acc Hneq_tx Hdecode_i Hdecode_f Hdecode_vmid Φ) "(>PC & >mem_ins & >acc & >tx & >R0 & >R1) HΦ". iApply (sswp_lift_atomic_step ExecI);[done|]. iIntros (n σ1) "%Hsche state". rewrite /scheduled /= /scheduler in Hsche. assert (σ1.1.1.2 = V0) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. } clear Hsche. iModIntro. iDestruct "state" as "(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl & trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)". (* valid regs *) iDestruct ((gen_reg_valid3 V0 PC ai R0 r0 R1 r1 Heq_cur) with "regs PC R0 R1") as "(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1)";eauto. (* valid pt *) iDestruct (access_agree_check_true (tpa ai) V0 with "pgt_acc acc") as %Hcheckpg_ai;eauto. (* valid mem *) iDestruct (gen_mem_valid ai wi with "mem mem_ins") as %Hlookup_ai. (* valid tx *) iDestruct (mb_valid_tx V0 p_tx with "mb tx") as %Heq_tx. (* valid tran *) iSplit. - (* reducible *) iPureIntro. apply (reducible_normal V0 Hvc ai wi);auto. rewrite Heq_tx //. - iModIntro. iIntros (m2 σ2) "vmprop_auth %HstepP". iFrame "vmprop_auth". apply (step_ExecI_normal V0 Hvc ai wi) in HstepP;eauto. 2: rewrite Heq_tx //. remember (exec Hvc σ1) as c2 eqn:Heqc2. rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /= /lang.run /is_primary in Heqc2. case_bool_decide;last contradiction. rewrite Hlookup_R1 /= Hdecode_vmid /= in Heqc2. destruct HstepP;subst m2 σ2; subst c2; simpl. rewrite /gen_vm_interp. rewrite (preserve_get_mb_gmap σ1). rewrite (preserve_get_rx_gmap σ1). rewrite (preserve_get_own_gmap σ1). rewrite (preserve_get_access_gmap σ1). rewrite (preserve_get_excl_gmap σ1). rewrite (preserve_get_trans_gmap σ1). rewrite (preserve_get_hpool_gset σ1). rewrite (preserve_get_retri_gmap σ1). rewrite (preserve_inv_trans_pgt_consistent σ1). rewrite (preserve_inv_trans_wellformed σ1). rewrite (preserve_inv_trans_ps_disj σ1). all: try rewrite p_upd_id_mb p_upd_pc_mb //. all: try rewrite p_upd_id_pgt p_upd_pc_pgt //. all: try rewrite p_upd_id_trans p_upd_pc_trans //. rewrite p_upd_id_mem p_upd_pc_mem. iFrame. (* upd reg*) rewrite (preserve_get_reg_gmap (update_incr_PC σ1) (update_current_vmid _ _)). 2: rewrite p_upd_id_reg //. rewrite (u_upd_pc_regs _ V0 ai). 2: rewrite //. 2: solve_reg_lookup. iDestruct ((gen_reg_update1_global PC V0 _ (ai ^+ 1)%f) with "regs PC") as ">($ & PC)";eauto. iModIntro. iSplit. iPureIntro. auto. (* just_schedule *) rewrite /just_scheduled_vms /just_scheduled. rewrite /scheduled /machine.scheduler /= /scheduler. rewrite /update_current_vmid /= Heq_cur. set fl := (filter _ _). assert (fl = []) as ->. { rewrite /fl. induction n. - simpl. rewrite filter_nil //=. - rewrite seq_S. rewrite list.filter_app. rewrite IHn. simpl. rewrite filter_cons_False /=. rewrite filter_nil. auto. rewrite andb_negb_l. done. } iSplitR;first done. case_bool_decide; last contradiction. simpl. iApply "HΦ". iFrame. Qed. End run.
Divine behavior was believed to govern all of nature . Except for the few deities who disrupted the divine order , the gods ' actions maintained maat and created and sustained all living things . They did this work using a force the Egyptians called heka , a term usually translated as " magic " . <unk> was a fundamental power that the creator god used to form the world and the gods themselves .
Stansfield was diagnosed with colorectal cancer in April 2010 . He returned to training after surgery and chemotherapy , but died on 10 August that year . A foundation in his name was posthumously set up by his family to provide sporting opportunities and raise awareness of colorectal cancer . He has posthumously been featured on a Flybe airliner livery and tourist currency in Exeter .
View Cart “iPhone Diagnostic Service“ has been added to your cart. Drop your iPhone 5 only to discover the front glass had cracked or shattered? Don’t worry, we promise you’re not alone. Join the many happy customers who have purchased our newest and most popular repair, and had their iPhone back in as little as two days as good as new! Ready to get started? It’s as easy as adding the service to your cart, completing our check-out process, and shipping your phone to our mail-in repair location.
REBOL [] os-id: _ ; possible values (words): ; Execution: Build the target directly without generating a Makefile ; makefile: Generate a makefile for GNU make ; nmake: Generate an NMake file for CL target: 'execution extensions: make map! [ ; NAME VALUE ; VALUE: one of ; + builtin ; - disabled ; * dynamic ; [modules] dynamic with selected modules ; FFI and ODBC have dependencies outside of what's available on a stock ; standard C compiler with POSIX or Win32. Disable these extensions by ; default. (Review the general policy for default inclusions.) ; Clipboard is only implemented in Windows at the moment. BMP + Clipboard - Console + Crypt + Debugger + DNS + Event + Filesystem + GIF + Gob + JavaScript - JPG + Library + Locale + Network + ODBC - PNG + Process + TCC - Time + UUID + UTF + Vector + View + ] rebol-tool: _ ; fallback value if system/options/boot fails ; possible combination: ; [gcc _ ld _] ; [cl _ link _] toolset: [ ;name executable-file-path (_ being default) gcc _ ld _ strip _ ] ;one of "no", "'asserts", "'symbols" or "'sanitize" debug: no ; one of 'no', 1, 2 or 4 ; optimize: 2 ; one of [c gnu89 gnu99 c99 c11 c++ c++98 c++0x c++11 c++14 c++17] ; standard: 'c rigorous: no static: no pkg-config: try get-env "PKGCONFIG" ;path to pkg-config, or default odbc-requires-ltdl: no with-tcc: no ; Console API for windows does not exist before vista. ; pre-vista: no git-commit: _ includes: _ definitions: _ cflags: _ libraries: _ ldflags: _ main: _ top: _ config: _
# load the ggplot libraries library(tidyverse) # read in the data temp <- read_tsv("average_fractionMissing.txt") # make a basic plot ggplot(temp, aes(x = AverageSpC, y = FracMissing)) + geom_point() + geom_smooth(method = "loess", span = 0.05) + ggtitle("Fraction Missing Data versus Average SpC") + labs(x = "Average SpC", y = "Fraction Missing") # expanded x-axis plot ggplot(temp, aes(x = AverageSpC, y = FracMissing)) + coord_cartesian(xlim = c(0, 50)) + geom_line() + # geom_smooth(method = "loess", span = 0.05) + ggtitle("Missing versus Average SpC") + labs( x = "Average SpC", y = "Fraction Missing") + geom_vline(xintercept = 2.5, linetype = "dotted") + geom_vline(xintercept = 5.0, linetype = "dashed") sessionInfo()
# Decision Lens API # # No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # # OpenAPI spec version: 1.0 # # Generated by: https://github.com/swagger-api/swagger-codegen.git #' MinifiedYearlyFieldValue Class #' #' @field nv #' @field ct #' @field fmn #' #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export MinifiedYearlyFieldValue <- R6::R6Class( 'MinifiedYearlyFieldValue', public = list( `nv` = NULL, `ct` = NULL, `fmn` = NULL, initialize = function(`nv`, `ct`, `fmn`){ if (!missing(`nv`)) { stopifnot(is.numeric(`nv`), length(`nv`) == 1) self$`nv` <- `nv` } if (!missing(`ct`)) { stopifnot(is.numeric(`ct`), length(`ct`) == 1) self$`ct` <- `ct` } if (!missing(`fmn`)) { stopifnot(is.character(`fmn`), length(`fmn`) == 1) self$`fmn` <- `fmn` } }, toJSON = function() { MinifiedYearlyFieldValueObject <- list() if (!is.null(self$`nv`)) { MinifiedYearlyFieldValueObject[['nv']] <- self$`nv` } if (!is.null(self$`ct`)) { MinifiedYearlyFieldValueObject[['ct']] <- self$`ct` } if (!is.null(self$`fmn`)) { MinifiedYearlyFieldValueObject[['fmn']] <- self$`fmn` } MinifiedYearlyFieldValueObject }, fromJSON = function(MinifiedYearlyFieldValueJson) { MinifiedYearlyFieldValueObject <- dlensFromJSON(MinifiedYearlyFieldValueJson) if (!is.null(MinifiedYearlyFieldValueObject$`nv`)) { self$`nv` <- MinifiedYearlyFieldValueObject$`nv` } if (!is.null(MinifiedYearlyFieldValueObject$`ct`)) { self$`ct` <- MinifiedYearlyFieldValueObject$`ct` } if (!is.null(MinifiedYearlyFieldValueObject$`fmn`)) { self$`fmn` <- MinifiedYearlyFieldValueObject$`fmn` } }, toJSONString = function() { sprintf( '{ "nv": %d, "ct": %d, "fmn": %s }', self$`nv`, self$`ct`, self$`fmn` ) }, fromJSONString = function(MinifiedYearlyFieldValueJson) { MinifiedYearlyFieldValueObject <- dlensFromJSON(MinifiedYearlyFieldValueJson) self$`nv` <- MinifiedYearlyFieldValueObject$`nv` self$`ct` <- MinifiedYearlyFieldValueObject$`ct` self$`fmn` <- MinifiedYearlyFieldValueObject$`fmn` } ) )
Several species coined in genera other than Allosaurus are also now thought to be synonymous with A. fragilis . Labrosaurus ferox was named in 1884 by Marsh for an oddly formed partial lower jaw , with a prominent gap in the tooth row at the tip of the jaw , and a rear section greatly expanded and turned down . Later researchers suggested that the bone was pathologic , showing an injury to the living animal , and that part of the unusual form of the rear of the bone was due to plaster reconstruction . It is recognized as most likely a specimen of A. fragilis . Allosaurus valens is a typo for Antrodemus valens accidentally used by Friedrich von Huene in 1932 ; Antrodemus valens itself may also pertain to Allosaurus fragilis , as Gilmore suggested in 1920 . <unk> <unk> , based on a scrap of vertebra Marsh first thought to be a mammalian jaw , may or may not be the same as Allosaurus .
module Remotelib2 import Remotelib1 export rem2 : String rem2 = rem1 ++ " - what a delight!"
{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-matches -fno-warn-name-shadowing -fno-warn-missing-signatures #-} {-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, UndecidableInstances, FlexibleContexts, TypeSynonymInstances #-} --------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- -- | -- | Module : Test Morris -- | Creator: Xiao Ling -- | Created: 12/8/2015 -- | see : https://github.com/snoyberg/conduit -- | --------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- module Tmorris where import Data.List import Data.Random import Data.Conduit import Data.List.Split import qualified Data.Conduit.List as Cl import Control.Monad.Identity import Criterion.Main import Core import Statistics import Morris main :: IO () main = return ()
\vsssub \subsubsection{Gridded GRIB output post-processor} \label{sec:ww3grib} \vsssub \proddefH{ww3\_grib}{w3grib}{ww3\_grib.ftn} \proddeff{Input}{ww3\_grib.inp}{Traditional configuration file.}{10} (App.~\ref{sec:config151}) \proddefa{mod\_def.ww3}{Model definition file.}{20} \proddefa{out\_grd.ww3}{Raw gridded output data.}{20} \proddeff{Output}{standard out}{Formatted output of program.}{6} \proddefa{gribfile}{GRIB file.}{50} \vspace{\baselineskip} \noindent This post-processor packs fields of mean wave parameters in GRIB format, using GRIB version II and \ncep's w3 and bacio library routines, or in GRIB2, using NCEPS's operational package. Additional packing data can be found in Table~\ref{tab:fields} on page \pageref{tab:fields}. The GRIB packing is performed using the \ncep's GRIB tables as described in \cite{rep:GRIB1}. Because the w3 and bacio routine are not fully portable, they are not supplied with the code. The user will have to provide corresponding routines. It is suggested that such routines are activated with additional \ws\ switches in the mandatory switch group containing the `{\F nogrb}' switch, as if presently the case with the \ncep\ routines. The GRIB2 packing is performed according to \cite{rep:GRIB2}, and is performed with NCEP's standard operational packages. Table~\ref{tab:fields} shows the {\F kpds(5)} data values for GRIB packing. For the partitioned data, the first number identifies the wind sea, the second number identifies swell. Most data are packed as surface data ({\F kpds(6) = 0}). For the partitioned swell fields, however, consecutive fields are packed at consecutive levels, with the level type indicator set to ({\F kpds(6) = 241}). {\F kpds(7)} identifies the actual level or swell field number. Table~\ref{tab:fields} shows several {\F kpds} data values for GRIB2 packing. The first number in the table represents {\F listsec0(2)}, which identifies the discipline type (e.g., oceanography, meteorology, etc.) The second number represents {\F kpds(1)}, which identifies the parameter category (e.g., waves, circulation, ice, etc.) within the discipline type. The third number represents {\F kpds(2)}, which identifies the actual parameter. For the partitioned data, A/B means A for wind sea and B for swell. Additionally {\F kpds(10) = 0} for surface data, and {\F kpds(10) = 241 } to pack consecutive swell fields at consecutive levels. {\F kpds(12)} identifies the actual level or swell field number. Although the above input file contains flags for all 31 output fields of \ws, not all fields can be packed in GRIB. If a parameter is chosen for which GRIB packing is not available, a message will be printed to standard output. Table~\ref{tab:fields} shows which parameter can be packed in GRIB. Note that at \ncep\ the conversions from GRIB to GRIB2 coincided with the introduction of partitioned wave model output. This required some duplicate definitions in GRIB and some apparent inconsistencies between GRIB and GRIB2 packing. \pb
# This rule return a json string from AVU's set to an object # Argument 1: The object name (/nlmumc/home/rods/test.file, /nlmumc/home/rods, [email protected], demoResc) # Argument 2: The object type -d for data object # -R for resource # -C for collection # -u for user # Argument 3: the JSON root according to https://github.com/MaastrichtUniversity/irods_avu_json. # Example : irule -F getJsonFromObj.r "*object='/nlmumc/home/rods/test.file'" "*objectType='-d'" "*jsonRoot='root'" main(){ # Defining result first is mandatory! *result = "" # Call the python function getJsonFromObj(*object, *objectType, *jsonRoot, *result) # Print writeLine("stdout", *result) } INPUT *object=$'/nlmumc/home/rods/test.file', *objectType=$'-d', *jsonRoot=$'root' OUTPUT ruleExecOut
\section{Introduction} The following documentation provides a closer look at network installation on the third-floor labs while giving an inside look at the materials used and areas involved. The IT Team at Rubin is in charge of installing the fiber optic cable that originates at the computer room located on the second floor of the main building and extending to the fiber distribution box that IT will install on the third floor. Other Rubin Staff members will carry out any other connections related to this activity. The IT requirements are the following: Install six pair single-mode fibers and six pair multimode fibers from the Computer room to the fiber boxes that needed to be installed on the third floor The cables used for this project were OS2 LC Full duplex and OM3 LC Full duplex.
lemma ball_minus_countable_nonempty: assumes "countable (A :: 'a :: euclidean_space set)" "r > 0" shows "ball z r - A \<noteq> {}"
-- An implementation of Olivier Danvy's Type-Directed Partial Evaluation (POPL 1996) -- for STLC with sum types using continuations in form of shift and reset. -- -- The algorithm was originally for a two-level lambda-calculus. -- Our use of Kripke semantics makes the effect of fresh variable generation explicit and formal. open import Library module DanvyShiftResetLiftable where data Base : Set where α β : Base open import Formulas Base open import Derivations Base -- Continutation monad with answer type R. -- (Cf. Haskell's Control.Monad.Cont.Cont = (A → R) → R). record M (R A : Cxt → Set) (Γ : Cxt) : Set where constructor shift field run : KFun (KFun A R) R Γ open M -- shift : ∀{R A Γ} (f : KFun (KFun A R) R Γ) → M R A Γ -- shift f .run σ k = f σ k reset : ∀{A} → M A A →̇ A reset m = m .run id≤ λ τ → id return : ∀{R A} → □ A →̇ M R A return x .run τ k = k id≤ (x τ) return' : ∀{R A} → □ A →̇ M R (□ A) return' x .run τ k = k id≤ λ τ₁ → x (τ₁ • τ) -- Bind _>>=_ : ∀{R A B Γ} (m : M R A Γ) (f : KFun A (M R B) Γ) → M R B Γ (m >>= f) .run σ k = m .run σ λ τ a → f (τ • σ) a .run id≤ λ τ′ → k (τ′ • τ) -- Map _<$>_ : ∀{R A B} (f : A →̇ B) → M R A →̇ M R B (f <$> m) .run σ k = m .run σ λ τ → k τ ∘ f _<&>_ : ∀{R A B Γ} (m : M R A Γ) (f : A →̇ B) → M R B Γ (m <&> f) .run σ k = m .run σ λ τ → k τ ∘ f -- Kripke map K$ : ∀{R A B} → KFun A B →̇ KFun (M R A) (M R B) K$ f τ m .run σ k = m .run σ λ τ′ a → k τ′ (f (τ′ • (σ • τ)) a) -- We use a continuation monad with answer type Nf. M' : (X : Cxt → Set) (Γ : Cxt) → Set M' X Γ = ∀ {C} → M (Nf' C) X Γ T⟦_⟧ : (A : Form) (Γ : Cxt) → Set T⟦ Atom P ⟧ = □ (Nf' (Atom P)) T⟦ True ⟧ Γ = ⊤ T⟦ False ⟧ Γ = ⊥ T⟦ A ∨ B ⟧ Γ = T⟦ A ⟧ Γ ⊎ T⟦ B ⟧ Γ T⟦ A ∧ B ⟧ Γ = T⟦ A ⟧ Γ × T⟦ B ⟧ Γ T⟦ A ⇒ B ⟧ Γ = ∀{Δ} (τ : Δ ≤ Γ) → T⟦ A ⟧ Δ → M' T⟦ B ⟧ Δ -- Monotonicity of the model is proven by induction on the proposition. -- monT : ∀ A {Γ Δ} (τ : Δ ≤ Γ) → T⟦ A ⟧ Γ → T⟦ A ⟧ Δ monT : ∀ A → Mon T⟦ A ⟧ monT (Atom P) = mon□ monT True = _ monT False τ () monT (A ∨ B) τ = map-⊎ (monT A τ) (monT B τ) monT (A ∧ B) τ (a , b) = monT A τ a , monT B τ b monT (A ⇒ B) τ f σ = f (σ • τ) fresh : ∀{A Γ} → □ (Ne' A) (Γ ∙ A) fresh τ′ = hyp (monH τ′ top) -- Reflection / reification, proven simultaneously by induction on the proposition. -- Reflection is η-expansion (and recursively reflection); mutual reflect : ∀ A → □ (Ne' A) →̇ M' T⟦ A ⟧ reflect (Atom P) t = return' (ne ∘′ t) -- λ τ → ne (monNe τ t) reflect True t = return _ reflect False t = shift λ τ k → falseE (t τ) reflect (A ∨ B) t = shift λ τ k → orE (t τ) (reset (K$ k (weak id≤) (inj₁ <$> reflect A fresh))) (reset (K$ k (weak id≤) (inj₂ <$> reflect B fresh))) -- ((inj₂ <$> reflect B (hyp top)) .run λ τ → k (τ • weak id≤)) -- Wrong: -- (reset (k (weak id≤) <$> (inj₁ <$> reflect A (hyp top)))) -- reflect (A ∧ B) t = do -- a ← reflect A (andE₁ t) -- b ← reflect B (andE₂ t) -- return (a , b) reflect (A ∧ B) t = reflect A ( andE₁ ∘ t ) >>= λ τ a → reflect B (mon□ {Ne' B} τ (andE₂ ∘ t)) >>= λ τ′ b → return λ τ₁ → monT A (τ₁ • τ′) a , monT B τ₁ b reflect (A ⇒ B) t = return' λ τ a → reflect B λ τ′ → impE (t (τ′ • τ)) (reify A a τ′) reify : ∀ A → T⟦ A ⟧ →̇ □ (Nf' A) reify (Atom P) t = t reify True _ τ = trueI reify False () reify (A ∨ B) (inj₁ a) τ = orI₁ (reify A a τ) reify (A ∨ B) (inj₂ b) τ = orI₂ (reify B b τ) reify (A ∧ B) (a , b) τ = andI (reify A a τ) (reify B b τ) reify (A ⇒ B) f τ = impI $ reset $ reflect A fresh >>= λ τ′ a → f (τ′ • weak τ) a <&> λ b → reify B b id≤ -- Fundamental theorem -- Delayed lifting record ◇ (G : Cxt → Set) (Γ : Cxt) : Set where constructor dia; field {Δ} : Cxt τ : Γ ≤ Δ γ : G Δ mon◇ : ∀{P} → Mon (◇ P) mon◇ τ′ (dia τ p) = dia (τ′ • τ) p -- NB: ◇ is a monad module Monad◇ where return◇ : ∀{P} → P →̇ ◇ P return◇ = dia id≤ join◇ : ∀{P} → ◇ (◇ P) →̇ ◇ P join◇ (dia τ d) = mon◇ τ d -- join◇ (dia τ (dia τ′ a)) = dia (τ • τ′) a map◇ : ∀{P Q} → (P →̇ Q) → ◇ P →̇ ◇ Q map◇ f (dia τ p) = dia τ (f p) -- Extension of T⟦_⟧ to contexts to classify semantic environments. G⟦_⟧ : ∀ (Γ Δ : Cxt) → Set G⟦ ε ⟧ _ = ⊤ G⟦ Γ ∙ A ⟧ = ◇ λ Δ → G⟦ Γ ⟧ Δ × T⟦ A ⟧ Δ -- monG is lazy except for matching on the context. monG : ∀{Γ} → Mon G⟦ Γ ⟧ monG {ε} τ _ = _ monG {Γ ∙ A} τ γ = mon◇ τ γ -- Environment extension. ext : ∀ A {Γ Δ₁ Δ} → (τ : Δ ≤ Δ₁) (γ : G⟦ Γ ⟧ Δ₁) → (a : T⟦ A ⟧ Δ) → □ G⟦ Γ ∙ A ⟧ Δ ext A τ γ a τ′ = dia τ′ (monG τ γ , a) -- Lookup in the environment. -- Accumulates embedded weakenings from environment. fundH : ∀{A Γ} (x : Hyp A Γ) → G⟦ Γ ⟧ →̇ □ T⟦ A ⟧ fundH {A} top (dia τ′ (_ , a)) τ = monT A (τ • τ′) a fundH (pop x) (dia τ′ (γ , _)) τ = fundH x γ (τ • τ′) -- The fundamental theorem: -- A call-by-value interpreter. fund : ∀{Γ A} (t : Γ ⊢ A) → G⟦ Γ ⟧ →̇ M' T⟦ A ⟧ fund (hyp {A} x) γ = return (fundH x γ) fund (impI {A} t) γ = return' λ τ a → fund t (ext A τ γ a id≤) fund (impE t u) γ = fund t γ >>= λ τ f → fund u (monG τ γ) >>= λ τ′ a → f τ′ a fund (andI {A} {B} t u) γ = fund t γ >>= λ τ a → fund u (monG τ γ) >>= λ τ′ b → return λ τ₁ → monT A (τ₁ • τ′) a , monT B τ₁ b fund (andE₁ t) γ = proj₁ <$> fund t γ fund (andE₂ t) γ = proj₂ <$> fund t γ fund (orI₁ t) γ = inj₁ <$> fund t γ fund (orI₂ t) γ = inj₂ <$> fund t γ fund (orE {A} {B} t u v) γ = fund t γ >>= λ τ → [ (λ a → fund u (ext A τ γ a id≤)) , (λ b → fund v (ext B τ γ b id≤)) ] fund (falseE t) γ = fund t γ >>= λ τ () fund trueI γ = return _ -- Identity environment ide : ∀ Γ → □ (M' G⟦ Γ ⟧) Γ ide ε τ = return _ ide (Γ ∙ A) τ = ide Γ (τ • weak id≤) >>= λ τ₁ γ → reflect A (mon□ (τ₁ • τ) fresh) >>= λ τ₂ a → return (ext A τ₂ γ a) -- return λ τ₃ → dia τ₃ (monG τ₂ γ , a) -- Normalization norm : ∀{A Γ} (t : Γ ⊢ A) → Nf Γ A norm {A} {Γ} t = reset $ ide Γ id≤ >>= λ _ γ → fund t γ <&> λ a → reify A a id≤ -- Testing idD : (A : Form) → ε ⊢ (A ⇒ A) idD A = impI (hyp top) test : let A = Atom α; B = Atom β in Nf ε (A ∨ B ⇒ A ∨ B) test = norm (idD (Atom α ∨ Atom β)) test2 = norm (idD (Atom α ∨ Atom β ∨ Atom α)) test3 = norm (idD False) -- Q.E.D. -} -- -} -- -} -- -} -- -} -- -} -- -}
#include <boost/make_unique.hpp>
{- Byzantine Fault Tolerant Consensus Verification in Agda, version 0.9. Copyright (c) 2021, Oracle and/or its affiliates. Licensed under the Universal Permissive License v 1.0 as shown at https://opensource.oracle.com/licenses/upl -} module Dijkstra.Syntax where open import Dijkstra.EitherD open import Dijkstra.EitherLike open import Dijkstra.RWS open import Haskell.Prelude open import Optics.All {- Within a "Dijkstra-fied" monad `M`, `if` and `ifD` are semantically interchangeable. The difference is in how proof obligations are generated - with the *D variants generating new weakestPre obligations for each case. In some cases, this is helpful for structuring proofs, while in other cases it is unnecessary and introduces more structure to the proof without adding any benefit. A rule of thumb is that, if the "scrutinee" (whatever we are doing case analysis on, i.e., the first argument) is the value provided via >>= (bind) by a previous code block, then we already have a weakestPre proof obligation, so introducing additional ones via the *D variants only creates more work and provides no additional benefit. -} record MonadIfD {ℓ₁ ℓ₂ ℓ₃ : Level} (M : Set ℓ₁ → Set ℓ₂) : Set (ℓ₂ ℓ⊔ ℓ+1 ℓ₁ ℓ⊔ ℓ+1 ℓ₃) where infix 1 ifD‖_ field ⦃ monad ⦄ : Monad M ifD‖_ : ∀ {A : Set ℓ₁} → Guards{ℓ₂}{ℓ₃} (M A) → M A open MonadIfD ⦃ ... ⦄ public module _ {ℓ₁ ℓ₂ ℓ₃} {M : Set ℓ₁ → Set ℓ₂} where private variable A : Set ℓ₁ B : Set ℓ₃ infix 0 ifD_then_else_ ifD_then_else_ : ⦃ _ : MonadIfD{ℓ₃ = ℓ₃} M ⦄ ⦃ _ : ToBool B ⦄ → B → (c₁ c₂ : M A) → M A ifD b then c₁ else c₂ = ifD‖ b ≔ c₁ ‖ otherwise≔ c₂ whenD : ∀ {ℓ₂ ℓ₃} {M : Set → Set ℓ₂} {B : Set ℓ₃} ⦃ _ : MonadIfD{ℓ0}{ℓ₂}{ℓ₃} M ⦄ ⦃ _ : ToBool B ⦄ → B → M Unit → M Unit whenD b f = ifD b then f else pure unit module _ {ℓ₁ ℓ₂} {M : Set ℓ₁ → Set ℓ₂} where private variable A B : Set ℓ₁ ifMD : ⦃ mi : MonadIfD{ℓ₃ = ℓ₁} M ⦄ ⦃ _ : ToBool B ⦄ → M B → (c₁ c₂ : M A) → M A ifMD{B = B} ⦃ mi ⦄ m c₁ c₂ = do x ← m ifD x then c₁ else c₂ record MonadMaybeD {ℓ₁ ℓ₂ : Level} (M : Set ℓ₁ → Set ℓ₂) : Set (ℓ₂ ℓ⊔ ℓ+1 ℓ₁) where field ⦃ monad ⦄ : Monad M maybeD : ∀ {A B : Set ℓ₁} → M B → (A → M B) → Maybe A → M B open MonadMaybeD ⦃ ... ⦄ public infix 0 caseMD_of_ caseMD_of_ : ∀ {ℓ₁ ℓ₂} {M : Set ℓ₁ → Set ℓ₂} ⦃ _ : MonadMaybeD M ⦄ {A B : Set ℓ₁} → Maybe A → (Maybe A → M B) → M B caseMD m of f = maybeD (f nothing) (f ∘ just) m record MonadEitherD {ℓ₁ ℓ₂ : Level} (M : Set ℓ₁ → Set ℓ₂) : Set (ℓ₂ ℓ⊔ ℓ+1 ℓ₁) where field ⦃ monad ⦄ : Monad M eitherD : ∀ {E A B : Set ℓ₁} → (E → M B) → (A → M B) → Either E A → M B open MonadEitherD ⦃ ... ⦄ public hiding (eitherD) eitherD : ∀ {ℓ₁ ℓ₂ ℓ₃} {M : Set ℓ₁ → Set ℓ₂} ⦃ med : MonadEitherD M ⦄ → ∀ {EL : Set ℓ₁ → Set ℓ₁ → Set ℓ₃} ⦃ _ : EitherLike EL ⦄ → ∀ {E A B : Set ℓ₁} → (E → M B) → (A → M B) → EL E A → M B eitherD ⦃ med = med ⦄ f₁ f₂ e = MonadEitherD.eitherD med f₁ f₂ (toEither e) infix 0 case⊎D_of_ case⊎D_of_ : ∀ {ℓ₁ ℓ₂ ℓ₃} {M : Set ℓ₁ → Set ℓ₂} ⦃ _ : MonadEitherD M ⦄ → ∀ {EL : Set ℓ₁ → Set ℓ₁ → Set ℓ₃} ⦃ _ : EitherLike EL ⦄ → ∀ {E A B : Set ℓ₁} → EL E A → (EL E A → M B) → M B case⊎D e of f = eitherD (f ∘ fromEither ∘ Left) (f ∘ fromEither ∘ Right) e