text
stringlengths 0
3.34M
|
---|
# Flow driven by an oscillating solid cylinder and bounded by a stationary outer hollow cylinder
\begin{equation}\label{p1introhpa} \Psi _{\eta \eta \tau }^{\mathrm{Sym}} = \frac{1}{{R_s }}\Psi^{\mathrm{Sym}}_{\eta \eta \eta \eta } + \Psi^{\mathrm{Sym}}_{\eta \eta \eta } \Psi _\theta^{\mathrm{Sym}} - \Psi^{\mathrm{Sym}}_{\eta \eta \theta } \Psi^{\mathrm{Sym}}_\eta, \\
\quad \Psi^{\mathrm{Sym}}(\eta= 0) = 0,\quad \Psi^{\mathrm{Sym}}_{\eta\eta}(\eta= 0) = 0, \qquad \Psi^{\mathrm{Sym}}(\eta= 1) = 0, \quad \Psi^{\mathrm{Sym}}_\eta(\eta= 1) = - \mu sin\theta, \qquad
0 \le \eta \le1, \quad 0 \le \theta \le \pi
\end{equation}
## Calculating $\Psi(\theta,\eta)$ the steady state solution $\theta$-marching
The governing equation is solved using:
* Half domain $\eta$-domain $0 \le \eta \le 1$
* $\theta$ marching with some of the nonlinear terms being explicit
## Summary of results
## Small $R_s$ series solution
```julia
using DifferentialEquations
using Plots
using BenchmarkTools
using DelimitedFiles
using LaTeXStrings
using SparseArrays
using LinearAlgebra
using StaticArrays
using Printf
```
```julia
pyplot()
function steady_diffeq_psi_bvp!(dψ, ψ, p, η) # This works for the ODEsolver psi is a matrix
Reynolds_number, m, Δθ, μ, ψ_previous = p
dψ[1] = ψ[2]
dψ[2] = ψ[3]
dψ[3] = ψ[4]
if m == 2
dψ[4] = -Reynolds_number*(ψ[4]*ψ[1]-ψ[3]*ψ[2])/Δθ
elseif θ_order == "2ndOrder" && m > 3
dψ[4] = -Reynolds_number*(ψ[4]*(1.5*ψ[1]-2.0*ψ_previous[m-1](η)[1]+ 0.5*ψ_previous[m-2](η)[1])-(1.5*ψ[3]-2.0*ψ_previous[m-1](η)[3]+0.5*ψ_previous[m-2](η)[3])*ψ[2])/Δθ
else
dψ[4] = -Reynolds_number*(ψ[4]*(ψ[1]-ψ_previous[m-1](η)[1])-(ψ[3]-ψ_previous[m-1](η)[3])*ψ[2])/Δθ
end
end
function bc_bvp!(residual, u, p, η) # psi[1] is the beginning of the etaspan, and psi[end] is the ending
Reynolds_number, m, Δθ, μ, ψ_previous = p
residual[1] = u[1][1] # The psi[1] (i.e ψ(η=0)=0 solution at the beginning of the time span should be 0)
residual[2] = u[1][3] # ψ_ηη(η=0)=0 should be 0 at first time step
residual[3] = u[end][1] # (i.e ψ(η=1)=0 solution at the end of the time span should be 0)
residual[4] = u[end][2] + 1.0*μ*sin((m-1)*Δθ)
end
function Ψ_smallr(θ::Float64, η::Float64 ,r::Float64, number_of_terms::Int)
terms = [
-η*(η^2-1)*sin(θ)/2.0,
r*η*(η^2-1)^2.0*(2.0+η^2)*sin(2*θ)/560.0,
r^2.0*η*(η^2-1)^2*((-591 -2294*η^2 + 161*η^4 + 1428*η^6)*sin(θ) +
+3.0*(423 + 166*η^2 - 553*η^4 - 84*η^6)sin(3*θ))/62092800.0,
r^3.0*η*(η - 1)^2*(η + 1)^2*(2184*η^10*cos(θ)^2 + 1540*η^10 + 24213*η^8*cos(θ)^2 - 44205*η^8 +
+ 18942*η^6*cos(θ)^2 + 33446*η^6 - 101444*η^4*cos(θ)^2 + 66052*η^4 - 23086*η^2*cos(θ)^2 -
6746*η^2 - 14889*cos(θ)^2 - 9383)*sin(θ)*cos(θ)/28252224000,
r^4.0*η*(η - 1)^2*(η + 1)^2*(968647680*η^14*sin(θ)^5 + 14774464320*η^14*sin(θ) + 3510571680*η^14*sin(3*θ) -
393513120*η^14*sin(5*θ) - 39671478000*η^12*sin(θ)^5 - 75537556710*η^12*sin(θ) -
28276357725*η^12*sin(3*θ) - 3752563815*η^12*sin(5*θ) - 181021246560*η^10*sin(θ)^5 +
357286638324*η^10*sin(θ) + 75142631718*η^10*sin(3*θ) - 1180776366*η^10*sin(5*θ) +
677920708080*η^8*sin(θ)^5 - 645834258762*η^8*sin(θ) - 123813530379*η^8*sin(3*θ) -
1711397457*η^8*sin(5*θ) + 193167076032*η^6*sin(θ)^5 - 82870720296*η^6*sin(θ) +
215941919508*η^6*sin(3*θ) + 59820477948*η^6*sin(5*θ) + 153978403824*η^4*sin(θ)^5 -
123221433370*η^4*sin(θ) + 181687022685*η^4*sin(3*θ) - 60662329497*η^4*sin(5*θ) -
500785425504*η^2*sin(θ)^5 + 367229681332*η^2*sin(θ) - 134582502330*η^2*sin(3*θ) -
33288605262*η^2*sin(5*θ) - 1507832445168*sin(θ)^5 + 969877856394*sin(θ) - 482955016725*sin(3*θ) -
9092499471*sin(5*θ))/16189310893916160000
]
if number_of_terms < 6
return sum(terms[1:number_of_terms])
else
return term[1]
end
end
```
Ψ_smallr (generic function with 1 method)
```julia
const N = 128; # Total number of intervals (steps-1) in the η direction
const M = 128; # Total number of intervals (steps-1) in the θ direction
const etaspan=(0, 1.0)
const Δη = 2.0/N;
const Δθ = pi/M;
const μ = 1.0
ψ_previous = zeros(N+1)
sol_psi = Array{ODESolution,1}(undef, M+1) #Declaring an array for every \psi(\eta)^{(n)} solution
Reynolds_number = 2.0
m = 2
ψ0 = [0.0 ,0.7, 0.0, -2.0 ]
θ_order = "1stOrder"
p=(Reynolds_number, m, Δθ, μ, sol_psi, θ_order )
bvp_psi0_2point = TwoPointBVProblem(steady_diffeq_psi_bvp!, bc_bvp!, ψ0, etaspan, p )
sol_psi[m] = @time solve(bvp_psi0_2point, alg_hints = [:stiff], MIRK4(),dt=0.01) #Very accurate solver
for m = 3:M+1
p=(Reynolds_number, m, Δθ, μ, sol_psi, θ_order)
ψ0 = [0.0 ,sol_psi[m-1][1][2], 0.0, sol_psi[m-1][1][4] ]
if m > 3
ψ0 = [0.0 ,sol_psi[m-1][1][2] + (sol_psi[m-1][1][2]-sol_psi[m-2][1][2]) , 0.0, sol_psi[m-1][1][4] + (sol_psi[m-1][1][4]-sol_psi[m-2][1][4])]
end
bvp_psi0_2point = TwoPointBVProblem(steady_diffeq_psi_bvp!, bc_bvp!, ψ0, etaspan, p )
sol_psi[m] = @time solve(bvp_psi0_2point, alg_hints = [:stiff], MIRK4(),dt=0.01) #Very accurate solver
end
```
7.453398 seconds (26.43 M allocations: 1.748 GiB, 5.38% gc time, 91.76% compilation time)
1.859223 seconds (36.48 M allocations: 1.543 GiB, 13.99% gc time, 9.31% compilation time)
1.351891 seconds (28.64 M allocations: 1.205 GiB, 13.80% gc time)
2.022508 seconds (42.97 M allocations: 1.808 GiB, 13.06% gc time)
1.694754 seconds (35.82 M allocations: 1.508 GiB, 14.56% gc time)
1.664201 seconds (35.82 M allocations: 1.508 GiB, 13.50% gc time)
1.992494 seconds (42.97 M allocations: 1.808 GiB, 13.35% gc time)
1.682419 seconds (35.81 M allocations: 1.507 GiB, 14.47% gc time)
1.983731 seconds (42.97 M allocations: 1.808 GiB, 13.37% gc time)
2.006141 seconds (42.97 M allocations: 1.808 GiB, 14.12% gc time)
1.990921 seconds (42.97 M allocations: 1.808 GiB, 13.24% gc time)
2.670352 seconds (57.33 M allocations: 2.416 GiB, 14.17% gc time)
2.656399 seconds (57.33 M allocations: 2.416 GiB, 13.52% gc time)
2.672361 seconds (57.33 M allocations: 2.416 GiB, 14.34% gc time)
2.651466 seconds (57.35 M allocations: 2.416 GiB, 13.56% gc time)
2.671103 seconds (57.35 M allocations: 2.416 GiB, 14.17% gc time)
2.978558 seconds (64.53 M allocations: 2.720 GiB, 13.36% gc time)
3.669077 seconds (78.90 M allocations: 3.325 GiB, 13.94% gc time)
2.991602 seconds (64.53 M allocations: 2.719 GiB, 14.03% gc time)
3.315823 seconds (71.70 M allocations: 3.020 GiB, 13.68% gc time)
3.308715 seconds (71.72 M allocations: 3.022 GiB, 13.72% gc time)
3.304128 seconds (71.73 M allocations: 3.023 GiB, 13.82% gc time)
3.369497 seconds (71.73 M allocations: 3.023 GiB, 14.37% gc time)
3.679074 seconds (78.90 M allocations: 3.325 GiB, 13.75% gc time)
3.743601 seconds (78.86 M allocations: 3.322 GiB, 14.13% gc time)
3.980322 seconds (86.05 M allocations: 3.625 GiB, 13.63% gc time)
4.727071 seconds (100.43 M allocations: 4.232 GiB, 14.44% gc time)
3.715993 seconds (78.86 M allocations: 3.322 GiB, 14.27% gc time)
3.721317 seconds (78.90 M allocations: 3.325 GiB, 13.93% gc time)
3.396215 seconds (71.68 M allocations: 3.019 GiB, 14.14% gc time)
4.401088 seconds (93.21 M allocations: 3.927 GiB, 14.12% gc time)
4.406916 seconds (93.21 M allocations: 3.927 GiB, 14.59% gc time)
4.400873 seconds (93.19 M allocations: 3.925 GiB, 14.23% gc time)
4.860003 seconds (100.36 M allocations: 4.227 GiB, 14.38% gc time)
4.141288 seconds (86.05 M allocations: 3.625 GiB, 14.58% gc time)
4.122750 seconds (86.06 M allocations: 3.626 GiB, 14.52% gc time)
4.514366 seconds (93.25 M allocations: 3.929 GiB, 14.78% gc time)
4.845608 seconds (100.39 M allocations: 4.230 GiB, 14.32% gc time)
4.757445 seconds (100.39 M allocations: 4.230 GiB, 14.58% gc time)
5.105338 seconds (107.61 M allocations: 4.536 GiB, 14.18% gc time)
4.966064 seconds (107.63 M allocations: 4.537 GiB, 13.76% gc time)
5.375932 seconds (114.76 M allocations: 4.836 GiB, 14.20% gc time)
5.745856 seconds (121.94 M allocations: 5.139 GiB, 14.60% gc time)
5.800451 seconds (121.94 M allocations: 5.139 GiB, 14.29% gc time)
5.445677 seconds (114.74 M allocations: 4.834 GiB, 14.74% gc time)
5.671784 seconds (121.92 M allocations: 5.137 GiB, 14.00% gc time)
5.860278 seconds (121.94 M allocations: 5.139 GiB, 14.24% gc time)
5.657485 seconds (121.94 M allocations: 5.139 GiB, 14.40% gc time)
5.952083 seconds (129.10 M allocations: 5.440 GiB, 13.86% gc time)
6.406602 seconds (136.30 M allocations: 5.745 GiB, 14.27% gc time)
6.546653 seconds (136.27 M allocations: 5.742 GiB, 14.32% gc time)
6.209757 seconds (129.05 M allocations: 5.436 GiB, 14.43% gc time)
6.150710 seconds (129.12 M allocations: 5.442 GiB, 14.38% gc time)
6.451097 seconds (136.29 M allocations: 5.743 GiB, 14.31% gc time)
6.792685 seconds (143.47 M allocations: 6.046 GiB, 14.40% gc time)
6.770532 seconds (143.47 M allocations: 6.046 GiB, 14.27% gc time)
6.765100 seconds (143.50 M allocations: 6.049 GiB, 14.44% gc time)
7.336618 seconds (150.67 M allocations: 6.351 GiB, 15.13% gc time)
7.123619 seconds (143.41 M allocations: 6.042 GiB, 14.87% gc time)
6.756294 seconds (136.29 M allocations: 5.743 GiB, 15.24% gc time)
7.122598 seconds (143.47 M allocations: 6.046 GiB, 14.89% gc time)
7.131010 seconds (143.47 M allocations: 6.046 GiB, 14.92% gc time)
7.514641 seconds (150.65 M allocations: 6.349 GiB, 14.94% gc time)
7.527298 seconds (150.65 M allocations: 6.349 GiB, 15.07% gc time)
7.425015 seconds (150.65 M allocations: 6.349 GiB, 14.69% gc time)
7.461186 seconds (150.65 M allocations: 6.349 GiB, 14.99% gc time)
7.463904 seconds (150.65 M allocations: 6.349 GiB, 14.94% gc time)
7.048534 seconds (150.65 M allocations: 6.349 GiB, 15.46% gc time)
6.729506 seconds (150.65 M allocations: 6.349 GiB, 12.11% gc time)
6.388140 seconds (143.47 M allocations: 6.046 GiB, 11.18% gc time)
6.401229 seconds (143.47 M allocations: 6.046 GiB, 11.86% gc time)
5.939682 seconds (136.29 M allocations: 5.743 GiB, 11.91% gc time)
5.913320 seconds (136.29 M allocations: 5.743 GiB, 11.54% gc time)
5.877229 seconds (136.29 M allocations: 5.743 GiB, 11.82% gc time)
5.903590 seconds (136.23 M allocations: 5.739 GiB, 11.94% gc time)
6.201380 seconds (143.49 M allocations: 6.048 GiB, 11.91% gc time)
6.167117 seconds (143.47 M allocations: 6.046 GiB, 11.83% gc time)
5.561880 seconds (129.10 M allocations: 5.440 GiB, 11.84% gc time)
5.557158 seconds (129.10 M allocations: 5.440 GiB, 12.18% gc time)
5.599228 seconds (129.10 M allocations: 5.440 GiB, 12.16% gc time)
5.553268 seconds (129.12 M allocations: 5.442 GiB, 11.87% gc time)
5.526532 seconds (129.05 M allocations: 5.436 GiB, 11.79% gc time)
5.253182 seconds (121.94 M allocations: 5.139 GiB, 12.02% gc time)
5.198816 seconds (121.94 M allocations: 5.139 GiB, 11.82% gc time)
5.209516 seconds (121.94 M allocations: 5.139 GiB, 11.88% gc time)
4.874155 seconds (114.76 M allocations: 4.836 GiB, 11.67% gc time)
4.909975 seconds (114.74 M allocations: 4.834 GiB, 11.86% gc time)
4.872808 seconds (114.74 M allocations: 4.834 GiB, 11.69% gc time)
4.569229 seconds (107.56 M allocations: 4.531 GiB, 11.79% gc time)
4.854127 seconds (114.77 M allocations: 4.837 GiB, 11.72% gc time)
4.626984 seconds (107.59 M allocations: 4.534 GiB, 12.12% gc time)
4.257486 seconds (100.46 M allocations: 4.235 GiB, 11.42% gc time)
3.956893 seconds (93.26 M allocations: 3.931 GiB, 12.26% gc time)
3.656977 seconds (86.06 M allocations: 3.626 GiB, 12.20% gc time)
4.280513 seconds (100.39 M allocations: 4.230 GiB, 11.94% gc time)
3.353905 seconds (78.86 M allocations: 3.322 GiB, 11.52% gc time)
3.356216 seconds (78.88 M allocations: 3.323 GiB, 12.44% gc time)
3.318119 seconds (78.86 M allocations: 3.322 GiB, 11.95% gc time)
3.922619 seconds (93.23 M allocations: 3.928 GiB, 11.97% gc time)
3.326826 seconds (78.86 M allocations: 3.322 GiB, 12.37% gc time)
3.628760 seconds (86.05 M allocations: 3.625 GiB, 11.83% gc time)
2.719436 seconds (64.50 M allocations: 2.716 GiB, 11.95% gc time)
3.022818 seconds (71.72 M allocations: 3.022 GiB, 12.00% gc time)
3.324631 seconds (78.86 M allocations: 3.322 GiB, 11.97% gc time)
3.325722 seconds (78.90 M allocations: 3.325 GiB, 12.17% gc time)
3.310949 seconds (78.88 M allocations: 3.323 GiB, 11.73% gc time)
3.317540 seconds (78.90 M allocations: 3.325 GiB, 11.89% gc time)
2.986594 seconds (71.73 M allocations: 3.023 GiB, 11.80% gc time)
2.993953 seconds (71.73 M allocations: 3.023 GiB, 12.00% gc time)
2.703356 seconds (64.55 M allocations: 2.720 GiB, 12.07% gc time)
2.673449 seconds (64.55 M allocations: 2.720 GiB, 11.95% gc time)
2.688989 seconds (64.53 M allocations: 2.719 GiB, 11.81% gc time)
2.393959 seconds (57.35 M allocations: 2.416 GiB, 12.20% gc time)
2.645196 seconds (64.52 M allocations: 2.717 GiB, 11.75% gc time)
2.659090 seconds (64.52 M allocations: 2.718 GiB, 12.26% gc time)
2.055480 seconds (50.17 M allocations: 2.114 GiB, 11.26% gc time)
2.068132 seconds (50.15 M allocations: 2.113 GiB, 12.22% gc time)
2.048642 seconds (50.15 M allocations: 2.113 GiB, 12.03% gc time)
1.783346 seconds (42.97 M allocations: 1.808 GiB, 12.05% gc time)
1.760886 seconds (42.97 M allocations: 1.808 GiB, 12.37% gc time)
1.483986 seconds (35.81 M allocations: 1.507 GiB, 11.46% gc time)
1.449109 seconds (35.81 M allocations: 1.507 GiB, 11.96% gc time)
1.497638 seconds (35.81 M allocations: 1.507 GiB, 12.29% gc time)
1.446808 seconds (35.81 M allocations: 1.507 GiB, 11.67% gc time)
1.465124 seconds (35.81 M allocations: 1.507 GiB, 11.52% gc time)
1.176366 seconds (28.64 M allocations: 1.205 GiB, 12.68% gc time)
1.166509 seconds (28.64 M allocations: 1.205 GiB, 11.64% gc time)
0.590178 seconds (14.31 M allocations: 616.557 MiB, 11.73% gc time)
```julia
θ_profile = 2
#print(varinfo(r"sol_psi"));
plot(sol_psi[θ_profile],vars=(1), linecolor=:red, label = "Julia solution",xlabel=L"\eta", ylabel=L"Ψ")
plot!( x-> Ψ_smallr((θ_profile-1)*Δθ, x ,Reynolds_number, 3) , 0,1,linestyle=:dot, linewidth = 2.0, linecolor=:blue, label = "Small R analytical",title="R = "*string(p[1])*L", \Psi^{(0)}",size=(1100,500), legend=false) #outertopright
```
```julia
shooting_sol_psi = Array{ODESolution,1}(undef, M+1) #Declaring an array for every \psi(\eta)^{(n)} solution
Reynolds = 50.0
m = 2
ψ0 = [0.0 ,0.5, 0.0, -2.5 ]
p=(Reynolds, m, Δθ, μ, ψ_previous)
bvp_shooting = BVProblem(steady_diffeq_psi_bvp!, bc_bvp!, ψ0, etaspan, p )
shooting_sol_psi[m] = @time solve(bvp_shooting, alg_hints=[:stiff], reltol=1e-5, abstol=1e-5 , GeneralMIRK4(),dt=0.01)
for m = 3:10
p=(Reynolds, m, Δθ, μ, sol_psi[m-1])
ψ0 = [0.0 ,sol_psi[m-1][1][2], 0.0, sol_psi[m-1][1][4] ]
bvp_shooting = BVProblem(steady_diffeq_psi_bvp!, bc_bvp!, ψ0, etaspan, p )
shooting_sol_psi[m] = @time solve(bvp_shooting, alg_hints = [:stiff], MIRK4(),dt=0.01) #Very accurate solver
end
```
```julia
θ_profile = 5
#print(varinfo(r"sol_psi"));
plot(shooting_sol_psi[θ_profile],vars=(1), linecolor=:red, label = "Julia solution",xlabel=L"\eta", ylabel=L"Ψ")
plot!( x-> Ψ_smallr((θ_profile-1)*Δθ, x ,Reynolds_number, 3) , 0,1,linestyle=:dot, linewidth = 2.0, linecolor=:blue, label = "Small R analytical",title="R = "*string(p[1])*L", \Psi^{(0)}",size=(1100,500), legend=false) #outertopright
```
```julia
sol_psi
```
129-element Vector{ODESolution}:
#undef
ODESolution{Float64, 2, Vector{Vector{Float64}}, Nothing, Nothing, Vector{Float64}, Nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}, MIRK4, SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}, Nothing}([[5.64237288394698e-37, 0.014121278133684991, 0.0, -0.09093155135947402], [0.0001411976260782483, 0.01411673155611702, -0.0009093155089158798, -0.09093154855231894], [0.0002823043206065453, 0.014103091823974503, -0.0018186308494240275, -0.09093150645467972], [0.0004232291520573789, 0.014080358942308633, -0.0027279451798513906, -0.09093132411547523], [0.0005638811890154721, 0.014048532930753544, -0.0036372563135417687, -0.09093083354067252], [0.0007041695004019882, 0.014007613840322517, -0.004546560050226363, -0.09092980007866033], [0.0008440031559001237, 0.013957601776868663, -0.005455849512007229, -0.0909279229572215], [0.0009832912266483625, 0.013898496931156442, -0.006365114485458256, -0.09092483596957848], [0.0011219427862672355, 0.01383029961547536, -0.007274340771319379, -0.09092010830629647], [0.001259866912284611, 0.01375301030671284, -0.008183509543222712, -0.0909132455291648] … [0.001984393171926432, -0.019488234517031657, -0.05809565391323126, 0.02953337371275538], [0.0017866111492546627, -0.020067641058628054, -0.057778278695080613, 0.033958800376187], [0.001583051671790433, -0.020643650858297623, -0.05741613314066732, 0.038487659203672066], [0.0013737509627635056, -0.021215811018973352, -0.057008176271577136, 0.043121292872991324], [0.0011587498266499546, -0.02178365816550148, -0.0565533533281599, 0.047861116464059224], [0.0009380937546543557, -0.022346718303057088, -0.0560505949988165, 0.05270862693804844], [0.0007118330316485675, -0.022904506667356654, -0.055498816550133404, 0.05766541350288926], [0.00048002284465273077, -0.023456527565646187, -0.05489691684857426, 0.06273316895082216], [0.00024272339295799703, -0.02400227420731552, -0.054243777263546795, 0.06791370206274774], [-2.938735877055719e-39, -0.024541228522912288, -0.05353826044065926, 0.0732089511842343]], nothing, nothing, [0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}(ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}(steady_diffeq_psi_bvp!, UniformScaling{Bool}(true), nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, SciMLBase.DEFAULT_OBSERVED, nothing), SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}(bc_bvp!), [0.0, 0.7, 0.0, -2.0], (0, 1.0), (10.0, 2, 0.02454369260617026, 1.0, ODESolution[#= circular reference @-4 =# … #= circular reference @-4 =#], "2ndOrder"), SciMLBase.StandardBVProblem(), Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}()), MIRK4(BoundaryValueDiffEq.var"#1#2"()), SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}([0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], [[5.64237288394698e-37, 0.014121278133684991, 0.0, -0.09093155135947402], [0.0001411976260782483, 0.01411673155611702, -0.0009093155089158798, -0.09093154855231894], [0.0002823043206065453, 0.014103091823974503, -0.0018186308494240275, -0.09093150645467972], [0.0004232291520573789, 0.014080358942308633, -0.0027279451798513906, -0.09093132411547523], [0.0005638811890154721, 0.014048532930753544, -0.0036372563135417687, -0.09093083354067252], [0.0007041695004019882, 0.014007613840322517, -0.004546560050226363, -0.09092980007866033], [0.0008440031559001237, 0.013957601776868663, -0.005455849512007229, -0.0909279229572215], [0.0009832912266483625, 0.013898496931156442, -0.006365114485458256, -0.09092483596957848], [0.0011219427862672355, 0.01383029961547536, -0.007274340771319379, -0.09092010830629647], [0.001259866912284611, 0.01375301030671284, -0.008183509543222712, -0.0909132455291648] … [0.001984393171926432, -0.019488234517031657, -0.05809565391323126, 0.02953337371275538], [0.0017866111492546627, -0.020067641058628054, -0.057778278695080613, 0.033958800376187], [0.001583051671790433, -0.020643650858297623, -0.05741613314066732, 0.038487659203672066], [0.0013737509627635056, -0.021215811018973352, -0.057008176271577136, 0.043121292872991324], [0.0011587498266499546, -0.02178365816550148, -0.0565533533281599, 0.047861116464059224], [0.0009380937546543557, -0.022346718303057088, -0.0560505949988165, 0.05270862693804844], [0.0007118330316485675, -0.022904506667356654, -0.055498816550133404, 0.05766541350288926], [0.00048002284465273077, -0.023456527565646187, -0.05489691684857426, 0.06273316895082216], [0.00024272339295799703, -0.02400227420731552, -0.054243777263546795, 0.06791370206274774], [-2.938735877055719e-39, -0.024541228522912288, -0.05353826044065926, 0.0732089511842343]]), false, 0, nothing, :Success)
ODESolution{Float64, 2, Vector{Vector{Float64}}, Nothing, Nothing, Vector{Float64}, Nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}, MIRK4, SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}, Nothing}([[-8.140910013685193e-38, 0.02823202480015266, 0.0, -0.18179014881819447], [0.00028228994964344984, 0.028222935292770836, -0.0018179014598782995, -0.18179013892650672], [0.0005643981091434948, 0.028195666772175165, -0.0036358024976879317, -0.18179004198580506], [0.000846142688410146, 0.028150219249740312, -0.005453701346562929, -0.18178965635378108], [0.0011273418975947, 0.028086592766826176, -0.007271593553132287, -0.1817886464745448], [0.0014078139475462066, 0.028004787428327075, -0.00908947064197721, -0.18178654364800517], [0.0016873770506700668, 0.02790480344953281, -0.010907318789298888, -0.18178274710191128], [0.0019658494223213662, 0.02778664121619448, -0.012725117508799677, -0.1817765253615105], [0.0022430492828643283, 0.02765030135765811, -0.014542838352722697, -0.1817670179104045], [0.0025187948605277705, 0.027495784832900078, -0.016360443630924298, -0.18175323713485886] … [0.003967524294739174, -0.03896339842441541, -0.11616623430294865, 0.05894825219632538], [0.0035720921891963173, -0.040121966786241095, -0.11553269555403514, 0.0677937570877067], [0.003165107559806745, -0.0412737540483752, -0.114809669575186, 0.07684613564693647], [0.002746642726518104, -0.042417854950532755, -0.11399507428242897, 0.08610807998503964], [0.0023167791664395424, -0.04355334327464426, -0.11308679996135211, 0.09558242709624121], [0.0018756077248260254, -0.04467927156099843, -0.1120827077249801, 0.10527217779807053], [0.001423228828981497, -0.045794670807988026, -0.11098062777352956, 0.11518051744264333], [0.0009597527052551602, -0.046898550153385836, -0.10977835743748852, 0.1253108385705726], [0.00048529959932669403, -0.047989896534884315, -0.10847365898366247, 0.13566676569686986], [4.84639460929378e-41, -0.049067674327418015, -0.10706425716183855, 0.14625218243808158]], nothing, nothing, [0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}(ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}(steady_diffeq_psi_bvp!, UniformScaling{Bool}(true), nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, SciMLBase.DEFAULT_OBSERVED, nothing), SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}(bc_bvp!), [0.0, 0.014121278133684991, 0.0, -0.09093155135947402], (0, 1.0), (10.0, 3, 0.02454369260617026, 1.0, ODESolution[#= circular reference @-4 =# … #= circular reference @-4 =#], "2ndOrder"), SciMLBase.StandardBVProblem(), Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}()), MIRK4(BoundaryValueDiffEq.var"#1#2"()), SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}([0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], [[-8.140910013685193e-38, 0.02823202480015266, 0.0, -0.18179014881819447], [0.00028228994964344984, 0.028222935292770836, -0.0018179014598782995, -0.18179013892650672], [0.0005643981091434948, 0.028195666772175165, -0.0036358024976879317, -0.18179004198580506], [0.000846142688410146, 0.028150219249740312, -0.005453701346562929, -0.18178965635378108], [0.0011273418975947, 0.028086592766826176, -0.007271593553132287, -0.1817886464745448], [0.0014078139475462066, 0.028004787428327075, -0.00908947064197721, -0.18178654364800517], [0.0016873770506700668, 0.02790480344953281, -0.010907318789298888, -0.18178274710191128], [0.0019658494223213662, 0.02778664121619448, -0.012725117508799677, -0.1817765253615105], [0.0022430492828643283, 0.02765030135765811, -0.014542838352722697, -0.1817670179104045], [0.0025187948605277705, 0.027495784832900078, -0.016360443630924298, -0.18175323713485886] … [0.003967524294739174, -0.03896339842441541, -0.11616623430294865, 0.05894825219632538], [0.0035720921891963173, -0.040121966786241095, -0.11553269555403514, 0.0677937570877067], [0.003165107559806745, -0.0412737540483752, -0.114809669575186, 0.07684613564693647], [0.002746642726518104, -0.042417854950532755, -0.11399507428242897, 0.08610807998503964], [0.0023167791664395424, -0.04355334327464426, -0.11308679996135211, 0.09558242709624121], [0.0018756077248260254, -0.04467927156099843, -0.1120827077249801, 0.10527217779807053], [0.001423228828981497, -0.045794670807988026, -0.11098062777352956, 0.11518051744264333], [0.0009597527052551602, -0.046898550153385836, -0.10977835743748852, 0.1253108385705726], [0.00048529959932669403, -0.047989896534884315, -0.10847365898366247, 0.13566676569686986], [4.84639460929378e-41, -0.049067674327418015, -0.10706425716183855, 0.14625218243808158]]), false, 0, nothing, :Success)
ODESolution{Float64, 2, Vector{Vector{Float64}}, Nothing, Nothing, Vector{Float64}, Nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}, MIRK4, SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}, Nothing}([[1.6743278021979124e-38, 0.04231674270620078, 0.0, -0.2724606972023678], [0.0004231220169466114, 0.042303119671769675, -0.0027246068109730947, -0.27246065205286785], [0.0008459715732210508, 0.04226225057382891, -0.0054492123839150345, -0.2724604160933644], [0.001268276208291681, 0.04219413543848534, -0.008173813471346901, -0.2724596880220841], [0.0016897634621089001, 0.04209877434272453, -0.010898402811510825, -0.27245796643909537], [0.0021101608758479066, 0.04197616746454113, -0.013622967132763973, -0.27245455099700866], [0.0025291959932524054, 0.041826315152960314, -0.01634748517174596, -0.27244854400431556], [0.002946596362777308, 0.04164921801778978, -0.019071925709811994, -0.2724388524737945], [0.003362089540726768, 0.0414448770388978, -0.02179624563213576, -0.27242419060635], [0.00377540309558162, 0.041213293694768977, -0.02452038801378389, -0.272403082698657] … [0.005947985600019452, -0.05840940116201235, -0.17421225152828593, 0.08792935904580378], [0.005355196178866445, -0.060146907519548, -0.17326692210172867, 0.10118808530158907], [0.004745081183317187, -0.06187429247291748, -0.17218745167184996, 0.11475822550194467], [0.004117748586533801, -0.06359019897393749, -0.1709707057794641, 0.12864387712020556], [0.0034733200895746452, -0.06529323842149455, -0.1696135079400118, 0.14284935220958428], [0.002811931439061794, -0.06698199023010432, -0.16811263735999374, 0.15737920537727593], [0.0021337327492819288, -0.06865500137419905, -0.16646482636062868, 0.17223826440781945], [0.0014388888289782742, -0.0703107859050688, -0.16466675748095186, 0.18743166379536763], [0.0007275795131236673, -0.07194782443710354, -0.16271506022987484, 0.20296488147106775], [-1.0494391238147567e-40, -0.07356456359966743, -0.1606063074536803, 0.21884377904241017]], nothing, nothing, [0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}(ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}(steady_diffeq_psi_bvp!, UniformScaling{Bool}(true), nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, SciMLBase.DEFAULT_OBSERVED, nothing), SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}(bc_bvp!), [0.0, 0.02823202480015266, 0.0, -0.18179014881819447], (0, 1.0), (10.0, 4, 0.02454369260617026, 1.0, ODESolution[#= circular reference @-4 =# … #= circular reference @-4 =#], "2ndOrder"), SciMLBase.StandardBVProblem(), Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}()), MIRK4(BoundaryValueDiffEq.var"#1#2"()), SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}([0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], [[1.6743278021979124e-38, 0.04231674270620078, 0.0, -0.2724606972023678], [0.0004231220169466114, 0.042303119671769675, -0.0027246068109730947, -0.27246065205286785], [0.0008459715732210508, 0.04226225057382891, -0.0054492123839150345, -0.2724604160933644], [0.001268276208291681, 0.04219413543848534, -0.008173813471346901, -0.2724596880220841], [0.0016897634621089001, 0.04209877434272453, -0.010898402811510825, -0.27245796643909537], [0.0021101608758479066, 0.04197616746454113, -0.013622967132763973, -0.27245455099700866], [0.0025291959932524054, 0.041826315152960314, -0.01634748517174596, -0.27244854400431556], [0.002946596362777308, 0.04164921801778978, -0.019071925709811994, -0.2724388524737945], [0.003362089540726768, 0.0414448770388978, -0.02179624563213576, -0.27242419060635], [0.00377540309558162, 0.041213293694768977, -0.02452038801378389, -0.272403082698657] … [0.005947985600019452, -0.05840940116201235, -0.17421225152828593, 0.08792935904580378], [0.005355196178866445, -0.060146907519548, -0.17326692210172867, 0.10118808530158907], [0.004745081183317187, -0.06187429247291748, -0.17218745167184996, 0.11475822550194467], [0.004117748586533801, -0.06359019897393749, -0.1709707057794641, 0.12864387712020556], [0.0034733200895746452, -0.06529323842149455, -0.1696135079400118, 0.14284935220958428], [0.002811931439061794, -0.06698199023010432, -0.16811263735999374, 0.15737920537727593], [0.0021337327492819288, -0.06865500137419905, -0.16646482636062868, 0.17223826440781945], [0.0014388888289782742, -0.0703107859050688, -0.16466675748095186, 0.18743166379536763], [0.0007275795131236673, -0.07194782443710354, -0.16271506022987484, 0.20296488147106775], [-1.0494391238147567e-40, -0.07356456359966743, -0.1606063074536803, 0.21884377904241017]]), false, 0, nothing, :Success)
ODESolution{Float64, 2, Vector{Vector{Float64}}, Nothing, Nothing, Vector{Float64}, Nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}, MIRK4, SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}, Nothing}([[1.4693679385278594e-38, 0.05636697730623635, 0.0, -0.3628825749963151], [0.0005636092926349222, 0.05634883317838178, -0.003628825419913044, -0.3628824843966992], [0.0011268557027448072, 0.056294400804989646, -0.007257648583188773, -0.362882079201108], [0.0016893763480525068, 0.056203680229911686, -0.010886464566276016, -0.3628809595256361], [0.0022508083470432986, 0.05607667157066065, -0.014515263117917534, -0.3628784599167322], [0.0028107888200120884, 0.05591337508494286, -0.018144026010571985, -0.3628736508755401], [0.0033689548909080842, 0.05571379126359046, -0.021772724410084432, -0.3628653409818264], [0.003924943690239937, 0.05547792094968082, -0.0254013162695532, -0.3628520796074365], [0.004478392359301898, 0.055205765483571916, -0.02902974375322684, -0.36283216020648423], [0.005028938055978572, 0.05489732687352483, -0.03265793069612346, -0.3628036241668329] … [0.007924566654592067, -0.07781432510266907, -0.23219606253047395, 0.11639848525597311], [0.007134833729777358, -0.08013017339363608, -0.2309441825485958, 0.13404635385513006], [0.0063220078746172945, -0.08243261358228114, -0.22951374889156817, 0.15211012715402483], [0.00548623216736517, -0.08471983924469427, -0.22790057482064596, 0.17059538940373015], [0.004627667960792719, -0.08699000180562276, -0.22610041631680425, 0.18950801835272033], [0.003746495306618057, -0.08924120995038463, -0.22410896896188817, 0.208854222572438], [0.0028429133859766698, -0.09147152900367199, -0.221921864429461, 0.2286405822455489], [0.0019171409462868368, -0.09367898027116052, -0.2195346665490631, 0.24887409375436556], [0.0009694167449033337, -0.09586154033946494, -0.21694286690404613, 0.26956221844299794], [-1.3775324423698682e-40, -0.0980171403295606, -0.21414187991921102, 0.2907129359670615]], nothing, nothing, [0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}(ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}(steady_diffeq_psi_bvp!, UniformScaling{Bool}(true), nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, SciMLBase.DEFAULT_OBSERVED, nothing), SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}(bc_bvp!), [0.0, 0.04231674270620078, 0.0, -0.2724606972023678], (0, 1.0), (10.0, 5, 0.02454369260617026, 1.0, ODESolution[#= circular reference @-4 =# … #= circular reference @-4 =#], "2ndOrder"), SciMLBase.StandardBVProblem(), Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}()), MIRK4(BoundaryValueDiffEq.var"#1#2"()), SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}([0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], [[1.4693679385278594e-38, 0.05636697730623635, 0.0, -0.3628825749963151], [0.0005636092926349222, 0.05634883317838178, -0.003628825419913044, -0.3628824843966992], [0.0011268557027448072, 0.056294400804989646, -0.007257648583188773, -0.362882079201108], [0.0016893763480525068, 0.056203680229911686, -0.010886464566276016, -0.3628809595256361], [0.0022508083470432986, 0.05607667157066065, -0.014515263117917534, -0.3628784599167322], [0.0028107888200120884, 0.05591337508494286, -0.018144026010571985, -0.3628736508755401], [0.0033689548909080842, 0.05571379126359046, -0.021772724410084432, -0.3628653409818264], [0.003924943690239937, 0.05547792094968082, -0.0254013162695532, -0.3628520796074365], [0.004478392359301898, 0.055205765483571916, -0.02902974375322684, -0.36283216020648423], [0.005028938055978572, 0.05489732687352483, -0.03265793069612346, -0.3628036241668329] … [0.007924566654592067, -0.07781432510266907, -0.23219606253047395, 0.11639848525597311], [0.007134833729777358, -0.08013017339363608, -0.2309441825485958, 0.13404635385513006], [0.0063220078746172945, -0.08243261358228114, -0.22951374889156817, 0.15211012715402483], [0.00548623216736517, -0.08471983924469427, -0.22790057482064596, 0.17059538940373015], [0.004627667960792719, -0.08699000180562276, -0.22610041631680425, 0.18950801835272033], [0.003746495306618057, -0.08924120995038463, -0.22410896896188817, 0.208854222572438], [0.0028429133859766698, -0.09147152900367199, -0.221921864429461, 0.2286405822455489], [0.0019171409462868368, -0.09367898027116052, -0.2195346665490631, 0.24887409375436556], [0.0009694167449033337, -0.09586154033946494, -0.21694286690404613, 0.26956221844299794], [-1.3775324423698682e-40, -0.0980171403295606, -0.21414187991921102, 0.2907129359670615]]), false, 0, nothing, :Success)
ODESolution{Float64, 2, Vector{Vector{Float64}}, Nothing, Nothing, Vector{Float64}, Nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}, MIRK4, SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}, Nothing}([[1.080730199096385e-38, 0.07036888832102602, 0.0, -0.4529555461656288], [0.0007036133906224105, 0.07034624054536227, -0.004529554856289572, -0.45295538029057286], [0.0014067738257891396, 0.07027829723633992, -0.009059105842497526, -0.4529547168812501], [0.0021090283504591398, 0.07016505846444084, -0.013588645774127456, -0.45295305896574034], [0.00280992401075201, 0.07000652440234756, -0.01811816084545822, -0.4529495795241761], [0.0035090078553559998, 0.06980269540762955, -0.022647627337907417, -0.4529431233824032], [0.004205826937927116, 0.0695535721382386, -0.027177008351064617, -0.45293220985047805], [0.004899928320806165, 0.06925915570054972, -0.03170625056378319, -0.4529150360934894], [0.005590859080377539, 0.06891944782961062, -0.036235281032576803, -0.4528894812187842], [0.006278166314389895, 0.06853445110119112, -0.04076400403439158, -0.4528531110603845] … [0.009895938133493301, -0.09716351392461761, -0.29011083877700866, 0.14418713655073412], [0.008909822393930098, -0.10005704806350842, -0.28855928406836867, 0.16621009623043884], [0.007894852582836134, -0.10293395684602025, -0.2867848985099428, 0.18875445068058996], [0.006851206182505617, -0.10579198577793221, -0.28478243321822927, 0.2118272432258307], [0.005779083483807369, -0.10862882751821173, -0.2825465671148346, 0.23543587693140042], [0.004678708118324583, -0.11144212113831929, -0.28007190309944935, 0.2595881612389135], [0.0035503275981007567, -0.11422945134083735, -0.2773529637344035, 0.2842923630835177], [0.002394213863423847, -0.11698834763231072, -0.2743841863938507, 0.30955726292710395], [0.0012106638391341281, -0.11971628344468753, -0.27115991782606425, 0.33539221618569526], [4.649267995970449e-41, -0.1224106751992162, -0.26767440807232046, 0.36180722057704046]], nothing, nothing, [0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}(ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}(steady_diffeq_psi_bvp!, UniformScaling{Bool}(true), nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, SciMLBase.DEFAULT_OBSERVED, nothing), SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}(bc_bvp!), [0.0, 0.05636697730623635, 0.0, -0.3628825749963151], (0, 1.0), (10.0, 6, 0.02454369260617026, 1.0, ODESolution[#= circular reference @-4 =# … #= circular reference @-4 =#], "2ndOrder"), SciMLBase.StandardBVProblem(), Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}()), MIRK4(BoundaryValueDiffEq.var"#1#2"()), SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}([0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], [[1.080730199096385e-38, 0.07036888832102602, 0.0, -0.4529555461656288], [0.0007036133906224105, 0.07034624054536227, -0.004529554856289572, -0.45295538029057286], [0.0014067738257891396, 0.07027829723633992, -0.009059105842497526, -0.4529547168812501], [0.0021090283504591398, 0.07016505846444084, -0.013588645774127456, -0.45295305896574034], [0.00280992401075201, 0.07000652440234756, -0.01811816084545822, -0.4529495795241761], [0.0035090078553559998, 0.06980269540762955, -0.022647627337907417, -0.4529431233824032], [0.004205826937927116, 0.0695535721382386, -0.027177008351064617, -0.45293220985047805], [0.004899928320806165, 0.06925915570054972, -0.03170625056378319, -0.4529150360934894], [0.005590859080377539, 0.06891944782961062, -0.036235281032576803, -0.4528894812187842], [0.006278166314389895, 0.06853445110119112, -0.04076400403439158, -0.4528531110603845] … [0.009895938133493301, -0.09716351392461761, -0.29011083877700866, 0.14418713655073412], [0.008909822393930098, -0.10005704806350842, -0.28855928406836867, 0.16621009623043884], [0.007894852582836134, -0.10293395684602025, -0.2867848985099428, 0.18875445068058996], [0.006851206182505617, -0.10579198577793221, -0.28478243321822927, 0.2118272432258307], [0.005779083483807369, -0.10862882751821173, -0.2825465671148346, 0.23543587693140042], [0.004678708118324583, -0.11144212113831929, -0.28007190309944935, 0.2595881612389135], [0.0035503275981007567, -0.11422945134083735, -0.2773529637344035, 0.2842923630835177], [0.002394213863423847, -0.11698834763231072, -0.2743841863938507, 0.30955726292710395], [0.0012106638391341281, -0.11971628344468753, -0.27115991782606425, 0.33539221618569526], [4.649267995970449e-41, -0.1224106751992162, -0.26767440807232046, 0.36180722057704046]]), false, 0, nothing, :Success)
ODESolution{Float64, 2, Vector{Vector{Float64}}, Nothing, Nothing, Vector{Float64}, Nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}, MIRK4, SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}, Nothing}([[-5.48768958619898e-38, 0.08431057489162343, 0.0, -0.5425924134396577], [0.000843015316852544, 0.0842834452736518, -0.005425923137881829, -0.5425921395737013], [0.001685488041439631, 0.08420205644876916, -0.010851840140139412, -0.5425911204669023], [0.002526875582142443, 0.08406640852381918, -0.016277740922493285, -0.5425887640456014], [0.003366635349029725, 0.08387650174265308, -0.021703607512372144, -0.5425840850285971], [0.004204224755688009, 0.083632336584639, -0.02712941012737953, -0.542575707181894], [0.005039101222232091, 0.08333391390225917, -0.032555103280735034, -0.54256186646026], [0.005870722179886213, 0.08298123509748098, -0.03798062192251531, -0.5425404150205856], [0.006698545077520351, 0.0825743023365008, -0.043405877625288504, -0.5425088260879989], [0.0075220273905246444, 0.08211311880237421, -0.04883075482262474, -0.5424641996517403] … [0.01186078219629966, -0.11644278505108142, -0.3479380368466246, 0.17104794601659967], [0.0106789870420082, -0.11991317612744333, -0.3460962289925482, 0.19741760646695536], [0.009462584488356834, -0.12336382020329192, -0.34398758931419815, 0.2244157244728877], [0.008211785452042417, -0.12679201739420365, -0.3416057900783007, 0.2520509987484214], [0.006926828166458092, -0.13019500409654983, -0.3389444144596332, 0.2803325575083978], [0.005607978823416567, -0.1335699520742109, -0.3359969519813643, 0.30927001221861433], [0.004255532224238804, -0.1369139674969512, -0.33275679339253145, 0.3388735164960711], [0.002869812440728033, -0.14022408992450955, -0.32921722492857963, 0.3691538306941812], [0.0014511734865969878, -0.14349729122997806, -0.3253714218951785, 0.40012239276045075], [8.355587527734006e-42, -0.14673047445536175, -0.32121244150942263, 0.43179139602209105]], nothing, nothing, [0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}(ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}(steady_diffeq_psi_bvp!, UniformScaling{Bool}(true), nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, SciMLBase.DEFAULT_OBSERVED, nothing), SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}(bc_bvp!), [0.0, 0.07036888832102602, 0.0, -0.4529555461656288], (0, 1.0), (10.0, 7, 0.02454369260617026, 1.0, ODESolution[#= circular reference @-4 =# … #= circular reference @-4 =#], "2ndOrder"), SciMLBase.StandardBVProblem(), Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}()), MIRK4(BoundaryValueDiffEq.var"#1#2"()), SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}([0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], [[-5.48768958619898e-38, 0.08431057489162343, 0.0, -0.5425924134396577], [0.000843015316852544, 0.0842834452736518, -0.005425923137881829, -0.5425921395737013], [0.001685488041439631, 0.08420205644876916, -0.010851840140139412, -0.5425911204669023], [0.002526875582142443, 0.08406640852381918, -0.016277740922493285, -0.5425887640456014], [0.003366635349029725, 0.08387650174265308, -0.021703607512372144, -0.5425840850285971], [0.004204224755688009, 0.083632336584639, -0.02712941012737953, -0.542575707181894], [0.005039101222232091, 0.08333391390225917, -0.032555103280735034, -0.54256186646026], [0.005870722179886213, 0.08298123509748098, -0.03798062192251531, -0.5425404150205856], [0.006698545077520351, 0.0825743023365008, -0.043405877625288504, -0.5425088260879989], [0.0075220273905246444, 0.08211311880237421, -0.04883075482262474, -0.5424641996517403] … [0.01186078219629966, -0.11644278505108142, -0.3479380368466246, 0.17104794601659967], [0.0106789870420082, -0.11991317612744333, -0.3460962289925482, 0.19741760646695536], [0.009462584488356834, -0.12336382020329192, -0.34398758931419815, 0.2244157244728877], [0.008211785452042417, -0.12679201739420365, -0.3416057900783007, 0.2520509987484214], [0.006926828166458092, -0.13019500409654983, -0.3389444144596332, 0.2803325575083978], [0.005607978823416567, -0.1335699520742109, -0.3359969519813643, 0.30927001221861433], [0.004255532224238804, -0.1369139674969512, -0.33275679339253145, 0.3388735164960711], [0.002869812440728033, -0.14022408992450955, -0.32921722492857963, 0.3691538306941812], [0.0014511734865969878, -0.14349729122997806, -0.3253714218951785, 0.40012239276045075], [8.355587527734006e-42, -0.14673047445536175, -0.32121244150942263, 0.43179139602209105]]), false, 0, nothing, :Success)
ODESolution{Float64, 2, Vector{Vector{Float64}}, Nothing, Nothing, Vector{Float64}, Nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}, MIRK4, SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}, Nothing}([[2.938735877055719e-38, 0.09818058039262945, 0.0, -0.6317102238598824], [0.0009817005188968017, 0.09814899488551956, -0.006317100726817852, -0.6317098067645348], [0.001962769327793609, 0.09805423840780289, -0.012634192350250584, -0.6317083270048124], [0.0029425747176388376, 0.09789631111316137, -0.01895126119918417, -0.6317050996832315], [0.003920484981734411, 0.09767521333382259, -0.025268284477509523, -0.6316989850466639], [0.004895868418053176, 0.09739094569451343, -0.031585225727731654, -0.6316883910915491], [0.00586809333292221, 0.09704350927163012, -0.03790203032576596, -0.6316712771936364], [0.006836528046522433, 0.09663290579726214, -0.04421862101708435, -0.6316451587448688], [0.007800540900650833, 0.09615913790760608, -0.05053489350417543, -0.631607112775281], [0.008759500269186492, 0.095622209435208, -0.05685071209503956, -0.6315537845331954] … [0.013817823504116747, -0.13563868295292442, -0.40565713721093033, 0.19684294099757826], [0.012441187893141678, -0.13968490385985324, -0.40353590786938315, 0.22752472428369444], [0.011024201278734031, -0.14370836615443386, -0.40110418752439114, 0.2589428377242926], [0.009567106894717436, -0.14770592793815615, -0.39835456108525563, 0.2911077186160302], [0.008070179766414998, -0.1516743726315197, -0.39527950659799654, 0.32403031230717444], [0.006533727462889663, -0.15561040787897593, -0.3918713898553332, 0.35772213504156], [0.0049580908604152565, -0.15951066439672834, -0.38812245834898074, 0.39219534274314594], [0.003343644917783657, -0.16337169475651306, -0.3840248345020092, 0.42746280631976125], [0.0016907994641254132, -0.16718997209781955, -0.3795705081129331, 0.4635381941255962], [-5.739718509874451e-42, -0.17096188876030122, -0.374751327936459, 0.5004360622908265]], nothing, nothing, [0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}(ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}(steady_diffeq_psi_bvp!, UniformScaling{Bool}(true), nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, SciMLBase.DEFAULT_OBSERVED, nothing), SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}(bc_bvp!), [0.0, 0.08431057489162343, 0.0, -0.5425924134396577], (0, 1.0), (10.0, 8, 0.02454369260617026, 1.0, ODESolution[#= circular reference @-4 =# … #= circular reference @-4 =#], "2ndOrder"), SciMLBase.StandardBVProblem(), Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}()), MIRK4(BoundaryValueDiffEq.var"#1#2"()), SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}([0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], [[2.938735877055719e-38, 0.09818058039262945, 0.0, -0.6317102238598824], [0.0009817005188968017, 0.09814899488551956, -0.006317100726817852, -0.6317098067645348], [0.001962769327793609, 0.09805423840780289, -0.012634192350250584, -0.6317083270048124], [0.0029425747176388376, 0.09789631111316137, -0.01895126119918417, -0.6317050996832315], [0.003920484981734411, 0.09767521333382259, -0.025268284477509523, -0.6316989850466639], [0.004895868418053176, 0.09739094569451343, -0.031585225727731654, -0.6316883910915491], [0.00586809333292221, 0.09704350927163012, -0.03790203032576596, -0.6316712771936364], [0.006836528046522433, 0.09663290579726214, -0.04421862101708435, -0.6316451587448688], [0.007800540900650833, 0.09615913790760608, -0.05053489350417543, -0.631607112775281], [0.008759500269186492, 0.095622209435208, -0.05685071209503956, -0.6315537845331954] … [0.013817823504116747, -0.13563868295292442, -0.40565713721093033, 0.19684294099757826], [0.012441187893141678, -0.13968490385985324, -0.40353590786938315, 0.22752472428369444], [0.011024201278734031, -0.14370836615443386, -0.40110418752439114, 0.2589428377242926], [0.009567106894717436, -0.14770592793815615, -0.39835456108525563, 0.2911077186160302], [0.008070179766414998, -0.1516743726315197, -0.39527950659799654, 0.32403031230717444], [0.006533727462889663, -0.15561040787897593, -0.3918713898553332, 0.35772213504156], [0.0049580908604152565, -0.15951066439672834, -0.38812245834898074, 0.39219534274314594], [0.003343644917783657, -0.16337169475651306, -0.3840248345020092, 0.42746280631976125], [0.0016907994641254132, -0.16718997209781955, -0.3795705081129331, 0.4635381941255962], [-5.739718509874451e-42, -0.17096188876030122, -0.374751327936459, 0.5004360622908265]]), false, 0, nothing, :Success)
ODESolution{Float64, 2, Vector{Vector{Float64}}, Nothing, Nothing, Vector{Float64}, Nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}, MIRK4, SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}, Nothing}([[1.7053432249598616e-37, 0.1119665819629551, 0.0, -0.7202196797552226], [0.0011195457830274124, 0.11193057098483081, -0.007202194617955223, -0.7202190756117942], [0.0022383713466973087, 0.11182253811302618, -0.014404376291316743, -0.7202170046204931], [0.003355756472989717, 0.1116424835610973, -0.02160652690624297, -0.7202126916902131], [0.0044709809470765815, 0.1113904077710823, -0.028808618022225802, -0.720204846972711], [0.005583324560208602, 0.11106631154246177, -0.036010605738273235, -0.7201916688079967], [0.00669206711414783, 0.11067019621229049, -0.043212425594351137, -0.7201708478279382], [0.0077964884276557804, 0.11020206388609062, -0.050413987519572157, -0.7201395721983223], [0.008895868345542134, 0.10966191771898225, -0.05761517083839487, -0.7200945339742233], [0.009989486750773354, 0.10904976224641588, -0.06481581934581898, -0.7200319365383379] … [0.01576576626713532, -0.15473723541120032, -0.46325347946601975, 0.22139613550542536], [0.014195269583392234, -0.1593581212389787, -0.4608654204028471, 0.25635554758288637], [0.012578689305969476, -0.16395336445841935, -0.4581235481108997, 0.2921607722080563], [0.010916299693083414, -0.1685193844447494, -0.45501934368292607, 0.3288240555150082], [0.009208411237207463, -0.1730525147625282, -0.45154416293569666, 0.36635821779496525], [0.0074553715295412205, -0.17754900188302722, -0.4476892303199289, 0.40477672430072487], [0.0056575661376222055, -0.18200500383705562, -0.44344563208789856, 0.44409376301646897], [0.0038154194967643293, -0.1864165887954489, -0.43880430864562664, 0.48432433009494025], [0.0019293958160884303, -0.19077973356866992, -0.4337560460091747, 0.5254843237334358], [7.475405359323349e-41, -0.19509032201612825, -0.4282914662764844, 0.567590647336526]], nothing, nothing, [0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}(ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}(steady_diffeq_psi_bvp!, UniformScaling{Bool}(true), nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, SciMLBase.DEFAULT_OBSERVED, nothing), SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}(bc_bvp!), [0.0, 0.09818058039262945, 0.0, -0.6317102238598824], (0, 1.0), (10.0, 9, 0.02454369260617026, 1.0, ODESolution[#= circular reference @-4 =# … #= circular reference @-4 =#], "2ndOrder"), SciMLBase.StandardBVProblem(), Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}()), MIRK4(BoundaryValueDiffEq.var"#1#2"()), SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}([0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], [[1.7053432249598616e-37, 0.1119665819629551, 0.0, -0.7202196797552226], [0.0011195457830274124, 0.11193057098483081, -0.007202194617955223, -0.7202190756117942], [0.0022383713466973087, 0.11182253811302618, -0.014404376291316743, -0.7202170046204931], [0.003355756472989717, 0.1116424835610973, -0.02160652690624297, -0.7202126916902131], [0.0044709809470765815, 0.1113904077710823, -0.028808618022225802, -0.720204846972711], [0.005583324560208602, 0.11106631154246177, -0.036010605738273235, -0.7201916688079967], [0.00669206711414783, 0.11067019621229049, -0.043212425594351137, -0.7201708478279382], [0.0077964884276557804, 0.11020206388609062, -0.050413987519572157, -0.7201395721983223], [0.008895868345542134, 0.10966191771898225, -0.05761517083839487, -0.7200945339742233], [0.009989486750773354, 0.10904976224641588, -0.06481581934581898, -0.7200319365383379] … [0.01576576626713532, -0.15473723541120032, -0.46325347946601975, 0.22139613550542536], [0.014195269583392234, -0.1593581212389787, -0.4608654204028471, 0.25635554758288637], [0.012578689305969476, -0.16395336445841935, -0.4581235481108997, 0.2921607722080563], [0.010916299693083414, -0.1685193844447494, -0.45501934368292607, 0.3288240555150082], [0.009208411237207463, -0.1730525147625282, -0.45154416293569666, 0.36635821779496525], [0.0074553715295412205, -0.17754900188302722, -0.4476892303199289, 0.40477672430072487], [0.0056575661376222055, -0.18200500383705562, -0.44344563208789856, 0.44409376301646897], [0.0038154194967643293, -0.1864165887954489, -0.43880430864562664, 0.48432433009494025], [0.0019293958160884303, -0.19077973356866992, -0.4337560460091747, 0.5254843237334358], [7.475405359323349e-41, -0.19509032201612825, -0.4282914662764844, 0.567590647336526]]), false, 0, nothing, :Success)
ODESolution{Float64, 2, Vector{Vector{Float64}}, Nothing, Nothing, Vector{Float64}, Nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}, MIRK4, SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}, Nothing}([[4.408103815583578e-39, 0.12565684715463812, 0.0, -0.8080355511784268], [0.001256433798969777, 0.12561644538515263, -0.00808035249882258, -0.8080347122112512], [0.0025120595628334917, 0.12549524016298885, -0.016160687259697815, -0.8080319076699362], [0.003766069258306806, 0.1252932317757835, -0.024240980794074538, -0.8080262752929835], [0.005017654856323787, 0.12501042079872707, -0.03232119812534059, -0.8080163801675789], [0.006266008335582163, 0.12464680823802768, -0.04040128707759484, -0.808000218002914], [0.007510321687808195, 0.12420239573130241, -0.04848117260360352, -0.8079752196905262], [0.00874978692530825, 0.12367718580443952, -0.05656075116470537, -0.8079382571295447], [0.009983596091368948, 0.12307118218434976, -0.06463988517517902, -0.8078856502887024], [0.011210941274061434, 0.12238439016690068, -0.0727183975232754, -0.8078131754711572] … [0.017703318716179754, -0.17372460014751628, -0.5207088887227889, 0.2444998154367442], [0.01594007964008896, -0.17891881478458738, -0.5180687170899294, 0.2836927763418225], [0.014125036998065516, -0.18408465215942657, -0.5150318406852743, 0.323843091926375], [0.012258494558115899, -0.1892180971211709, -0.5115886150872806, 0.36496503771677874], [0.010340796724381224, -0.19431503735056554, -0.5077292499688383, 0.40707353140533337], [0.0083723295162267, -0.19937126186755694, -0.5034438022997704, 0.45018420921023306], [0.006353521562607802, -0.20438245946697048, -0.49872216874865155, 0.49431350977908234], [0.004284845112474038, -0.20934421707387532, -0.493554077204549, 0.539478766441809], [0.0021668170620586904, -0.2142520180094043, -0.4879290773307973, 0.585698308708023], [-4.304788882405838e-42, -0.2191012401568698, -0.4818365300534785, 0.6329915740025376]], nothing, nothing, [0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], nothing, BVProblem{Vector{Float64}, Tuple{Int64, Float64}, true, Tuple{Float64, Int64, Float64, Float64, Vector{ODESolution}, String}, ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}, SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}, SciMLBase.StandardBVProblem, Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}(ODEFunction{true, typeof(steady_diffeq_psi_bvp!), UniformScaling{Bool}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED), Nothing}(steady_diffeq_psi_bvp!, UniformScaling{Bool}(true), nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, SciMLBase.DEFAULT_OBSERVED, nothing), SciMLBase.TwoPointBVPFunction{typeof(bc_bvp!)}(bc_bvp!), [0.0, 0.1119665819629551, 0.0, -0.7202196797552226], (0, 1.0), (10.0, 10, 0.02454369260617026, 1.0, ODESolution[#= circular reference @-4 =# … #= circular reference @-4 =#], "2ndOrder"), SciMLBase.StandardBVProblem(), Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}()), MIRK4(BoundaryValueDiffEq.var"#1#2"()), SciMLBase.LinearInterpolation{Vector{Float64}, Vector{Vector{Float64}}}([0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 … 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0], [[4.408103815583578e-39, 0.12565684715463812, 0.0, -0.8080355511784268], [0.001256433798969777, 0.12561644538515263, -0.00808035249882258, -0.8080347122112512], [0.0025120595628334917, 0.12549524016298885, -0.016160687259697815, -0.8080319076699362], [0.003766069258306806, 0.1252932317757835, -0.024240980794074538, -0.8080262752929835], [0.005017654856323787, 0.12501042079872707, -0.03232119812534059, -0.8080163801675789], [0.006266008335582163, 0.12464680823802768, -0.04040128707759484, -0.808000218002914], [0.007510321687808195, 0.12420239573130241, -0.04848117260360352, -0.8079752196905262], [0.00874978692530825, 0.12367718580443952, -0.05656075116470537, -0.8079382571295447], [0.009983596091368948, 0.12307118218434976, -0.06463988517517902, -0.8078856502887024], [0.011210941274061434, 0.12238439016690068, -0.0727183975232754, -0.8078131754711572] … [0.017703318716179754, -0.17372460014751628, -0.5207088887227889, 0.2444998154367442], [0.01594007964008896, -0.17891881478458738, -0.5180687170899294, 0.2836927763418225], [0.014125036998065516, -0.18408465215942657, -0.5150318406852743, 0.323843091926375], [0.012258494558115899, -0.1892180971211709, -0.5115886150872806, 0.36496503771677874], [0.010340796724381224, -0.19431503735056554, -0.5077292499688383, 0.40707353140533337], [0.0083723295162267, -0.19937126186755694, -0.5034438022997704, 0.45018420921023306], [0.006353521562607802, -0.20438245946697048, -0.49872216874865155, 0.49431350977908234], [0.004284845112474038, -0.20934421707387532, -0.493554077204549, 0.539478766441809], [0.0021668170620586904, -0.2142520180094043, -0.4879290773307973, 0.585698308708023], [-4.304788882405838e-42, -0.2191012401568698, -0.4818365300534785, 0.6329915740025376]]), false, 0, nothing, :Success)
#undef
#undef
#undef
⋮
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
```julia
print(sol_psi[5][1],"\n", sol_psi[5][end])
```
[-3.8420014968235095e-5, 0.050641993362604186, 0.00033567023175691546, -0.38943034564136414]
[-4.749118334328344e-5, -0.09625013264384731, -0.10881839803935389, 4.537873265491412]
```julia
plot([sol_psi[2][end][4],sol_psi[6][end][4],sol_psi[15][end][4]])
```
```julia
```
|
module BTree.Complete.Base.Properties {A : Set} where
open import BTree {A}
open import BTree.Complete.Base {A}
open import BTree.Equality {A}
open import BTree.Equality.Properties {A}
lemma-≃-⋗ : {l l' r' : BTree} → l ≃ l' → l' ⋗ r' → l ⋗ r'
lemma-≃-⋗ (≃nd x x' ≃lf ≃lf ≃lf) (⋗lf .x') = ⋗lf x
lemma-≃-⋗ (≃nd {r = r} x x' l≃r l≃l' l'≃r') (⋗nd .x' x'' r' l'' l'⋗r'') = ⋗nd x x'' r l'' (lemma-≃-⋗ l≃l' l'⋗r'')
lemma-⋗-≃ : {l r r' : BTree} → l ⋗ r → r ≃ r' → l ⋗ r'
lemma-⋗-≃ (⋗lf x) ≃lf = ⋗lf x
lemma-⋗-≃ (⋗nd {r' = r'} x x' r l' l⋗r') (≃nd {l' = l''} .x' x'' l'≃r' l'≃l'' l''≃r'') = ⋗nd x x'' r l'' (lemma-⋗-≃ l⋗r' (trans≃ (symm≃ l'≃r') (trans≃ l'≃l'' l''≃r'')))
|
import ch1
namespace Set
theorem russels_paradox : ¬ ∃ S : Set, ∀ x, x ∈ S ↔ x ∉ x :=
begin
rintro ⟨S, hs⟩,
specialize hs S,
exact (iff_not_self _).mp hs,
end
-- axiom of specification is enabled by has_sep and mem_sep
theorem univ_not_set : ¬ ∃ S : Set, ∀ x, x ∈ S :=
begin
rintro ⟨S, hs⟩,
apply russels_paradox,
let B := {x ∈ S | x ∉ x},
refine ⟨B, _⟩,
intro x,
rw mem_sep,
exact and_iff_right (hs x),
end
theorem univ_not_set' (A : Set) : ∃ x, x ∉ A :=
begin
let B := {x ∈ A | x ∉ x},
refine ⟨B, _⟩,
intro he,
suffices h : B ∈ B ↔ B ∈ A ∧ B ∉ B,
rw @and_iff_right _ (B ∉ B) he at h,
exact (iff_not_self (B ∈ B)).mp h,
exact mem_sep,
end
-- set union enabled by Union and mem_Union
theorem union_empty_eq_empty : (∅ : Set).Union = ∅ :=
begin
apply ext, intro z,
rw (iff_false _).mpr (mem_empty z),
rw iff_false,
rw mem_Union,
rintro ⟨y, H, hi⟩,
exact mem_empty y H,
end
def Inter (A : Set) : Set := {x ∈ A.Union | ∀ z ∈ A, x ∈ z}
def inhab (A : Set) : Prop := ∃ x, x ∈ A
theorem ne_empty_of_inhabited (A : Set) (h : A.inhab) : A ≠ ∅ :=
begin
cases h with x h,
intro he,
rw he at h,
exact mem_empty x h,
end
theorem inhabited_of_ne_empty {A : Set} (hA : A ≠ ∅) : A.inhab :=
begin
apply classical.by_contradiction, intro hni, apply hA, rw eq_empty, intros z hz, apply hni, exact ⟨_, hz⟩,
end
lemma vacuous {p : Set → Prop} : ∀ x : Set, x ∈ (∅ : Set) → p x :=
begin
intros x hx, exfalso, exact mem_empty _ hx,
end
theorem exists_unique_of_exists {p : Set → Prop} (h : ∃ x : Set, ∀ z, z ∈ x ↔ p z) : ∃! x : Set, ∀ z, z ∈ x ↔ p z :=
begin
cases h with x h,
refine ⟨x, h, (λ y H, _)⟩,
refine ext (λ z, _),
simp only [h z, H z],
end
theorem exists_unique_Inter {A : Set} (h : A.inhab) : ∃! B : Set, ∀ x, x ∈ B ↔ ∀ z ∈ A, x ∈ z :=
begin
apply exists_unique_of_exists,
cases h with c hin,
refine ⟨{x ∈ c | ∀ z ∈ A, x ∈ z}, (λ z, _)⟩,
simp only [mem_sep],
split,
rintro ⟨hz, ha⟩, exact ha,
intro h,
exact ⟨h c hin, h⟩,
end
theorem not_exists_Inter_empty : ¬ ∃ B : Set, ∀ x, x ∈ B ↔ ∀ z ∈ (∅ : Set), x ∈ z :=
begin
rintro ⟨B, h⟩,
apply univ_not_set,
refine ⟨B, _⟩,
intro x,
specialize h x,
rw h,
intros a he,
exfalso, exact mem_empty a he,
end
theorem no_abs_complement {A : Set} [decidable_pred (λ x, x ∈ A)] : ¬ ∃ B : Set, ∀ x, x ∈ B ↔ x ∉ A :=
begin
rintro ⟨B, h⟩,
apply univ_not_set,
refine ⟨A ∪ B, _⟩,
intro x,
specialize h x,
simp only [mem_union, h],
exact decidable.em _,
end
theorem p10 {a B : Set} (h : a ∈ B) : a.powerset ∈ B.Union.powerset.powerset :=
begin
rw mem_powerset,
intros x h₂,
rw mem_powerset at h₂,
rw mem_powerset,
intros z h₃,
rw mem_Union,
exact ⟨a, h, h₂ h₃⟩,
end
@[simp]
lemma mem_Inter {A x : Set} : x ∈ A.Inter ↔ A.inhab ∧ ∀ z ∈ A, x ∈ z :=
begin
simp [Inter, mem_sep, inhab], intro ha, split,
{ rintro ⟨z, hz, hx⟩, exact ⟨_, hz⟩, },
{ rintro ⟨x, hx⟩, exact ⟨_, hx, ha _ hx⟩, },
end
lemma subset_self {A : Set} : A ⊆ A := (λ x hx, hx)
lemma eq_iff_subset_and_subset {A B : Set} : A = B ↔ A ⊆ B ∧ B ⊆ A :=
begin
split, intro he, rw he, exact ⟨subset_self, subset_self⟩,
rintro ⟨ha, hb⟩, apply ext, intro x, rw iff_iff_implies_and_implies, rw subset_def at *, exact ⟨@ha x, @hb x⟩,
end
lemma diff_ne_empty_of_ne {B A : Set} (hBA : B ⊆ A) (hne : B ≠ A) : (A \ B) ≠ ∅ :=
begin
intro he, apply hne, rw eq_iff_subset_and_subset, refine ⟨hBA, _⟩,
intros x hx, apply classical.by_contradiction, intro hxB,
apply mem_empty x, rw ←he, rw mem_diff, exact ⟨hx, hxB⟩,
end
lemma subset_trans {A B C : Set} (hA : A ⊆ B) (hB : B ⊆ C) : A ⊆ C := (λ x hx, hB (hA hx))
lemma subset_Union {X Y : Set} (h : X ∈ Y) : X ⊆ Y.Union :=
begin
simp only [subset_def, mem_Union, exists_prop], exact (λ z hz, ⟨_, h, hz⟩),
end
lemma subset_Inter {X Y : Set} (h : X ∈ Y) : Y.Inter ⊆ X :=
begin
simp only [subset_def, mem_Inter], exact (λ z ⟨hi, ha⟩, ha _ h),
end
lemma mem_powerset_self {X : Set} : X ∈ X.powerset :=
begin
rw mem_powerset, exact subset_self,
end
@[simp]
lemma sep_subset {a : Set} {p : Set → Prop} : {x ∈ a | p x} ⊆ a := (λ x hx, (mem_sep.mp hx).left)
theorem p21 {A B : Set} : (A ∪ B).Union = A.Union ∪ B.Union :=
begin
apply ext, simp only [exists_prop, mem_union, mem_Union], intro x, split,
{ rintro ⟨X, (hX|hX), hx⟩,
{ left, exact ⟨_, hX, hx⟩, },
{ right, exact ⟨_, hX, hx⟩, }, },
{ rintro (⟨X, hX, hx⟩|⟨X, hX, hx⟩),
{ exact ⟨_, or.inl hX, hx⟩, },
{ exact ⟨_, or.inr hX, hx⟩, }, },
end
lemma union_comm {x y : Set} : x ∪ y = y ∪ x :=
begin
apply ext, simp only [mem_union, or_comm, forall_const, iff_self],
end
lemma union_empty {x : Set} : x ∪ ∅ = x :=
begin
apply ext, simp only [mem_union, mem_empty, forall_const, iff_self, or_false],
end
lemma inter_comm {x y : Set} : x ∩ y = y ∩ x :=
begin
apply ext, simp only [mem_inter, and_comm, iff_self, implies_true_iff],
end
lemma inter_union {A B C : Set} : A ∩ (B ∪ C) = A ∩ B ∪ A ∩ C :=
begin
apply ext, simp only [and_or_distrib_left, forall_const, mem_inter, iff_self, mem_union],
end
lemma union_inter {A B C : Set} : (A ∪ B) ∩ C = A ∩ C ∪ B ∩ C :=
begin
apply ext, simp only [mem_inter, mem_union, or_and_distrib_right, forall_const, iff_self],
end
lemma union_assoc {A B C : Set} : A ∪ (B ∪ C) = (A ∪ B) ∪ C :=
begin
apply ext, simp only [mem_union, or_assoc, forall_const, iff_self],
end
lemma inter_empty {A : Set} : A ∩ ∅ = ∅ :=
begin
simp only [eq_empty, mem_inter, mem_empty, forall_const, not_false_iff, and_false],
end
lemma subset_union_left {A B : Set} : A ⊆ A ∪ B := subset_union_of_subset subset_self
lemma subset_union_right {A B : Set} : B ⊆ A ∪ B := begin rw union_comm, exact subset_union_left, end
lemma subset_union_of_subset_left {A B C : Set} (hAB : A ⊆ B) : A ⊆ B ∪ C :=
begin intros x hx, rw mem_union, exact or.inl (hAB hx), end
lemma subset_union_of_subset_right {A B C : Set} (hAB : A ⊆ C) : A ⊆ B ∪ C :=
begin intros x hx, rw mem_union, exact or.inr (hAB hx), end
lemma union_subset_of_subset_of_subset {A B C : Set} (hA : A ⊆ C) (hB : B ⊆ C) : (A ∪ B) ⊆ C :=
begin
intro x, rw mem_union, rintro (hx|hx),
{ exact hA hx, },
{ exact hB hx, },
end
lemma union_eq_union_diff {A B : Set} : A ∪ B = A ∪ (B \ A) :=
begin
apply ext, simp only [mem_union, mem_diff, or_and_distrib_left, classical.em, forall_const, and_true, iff_self],
end
lemma union_eq_left_of_subset {A B : Set} (hBA : B ⊆ A) : A ∪ B = A :=
begin
rw eq_iff_subset_and_subset,
exact ⟨union_subset_of_subset_of_subset subset_self hBA, subset_union_left⟩,
end
lemma union_diff_eq_self_of_subset {A B : Set} (hAB : A ⊆ B) : A ∪ (B \ A) = B :=
begin
rw [←union_eq_union_diff, eq_iff_subset_and_subset],
exact ⟨union_subset_of_subset_of_subset hAB subset_self, subset_union_right⟩,
end
lemma diff_singleton_union_eq {A x : Set} (xA : x ∈ A) : (A \ {x}) ∪ {x} = A :=
begin
rw union_comm, apply union_diff_eq_self_of_subset,
intros z zx, rw mem_singleton at zx, subst zx, exact xA,
end
lemma subset_diff {A B : Set} : A \ B ⊆ A :=
begin
intros x hx, rw mem_diff at hx, exact hx.left,
end
lemma self_inter_diff_empty {A B : Set} : A ∩ (B \ A) = ∅ :=
begin
simp [eq_empty, mem_inter, mem_diff], intros x hA hB, exact hA,
end
lemma subset_Union_of_mem {X K : Set} (hXK : X ∈ K) : X ⊆ K.Union :=
begin
intros z hz, rw mem_Union, exact ⟨_, hXK, hz⟩,
end
lemma Union_powerset_subset_self {X : Set} : X.powerset.Union ⊆ X :=
begin
intros z hz, simp only [mem_Union, exists_prop, mem_powerset] at hz, rcases hz with ⟨Y, hYX, hzy⟩,
exact hYX hzy,
end
lemma Union_subset_of_subset_powerset {X Y : Set} (h : X ⊆ Y.powerset) : X.Union ⊆ Y :=
begin
intros x hx, rw mem_Union at hx, rcases hx with ⟨Z, hZX, hxZ⟩, specialize h hZX, rw mem_powerset at h,
exact h hxZ,
end
lemma diff_diff_eq_self_of_subset {A B : Set} (hBA : B ⊆ A) : A \ (A \ B) = B :=
begin
apply ext, intro x, simp only [mem_diff], split,
rintro ⟨hA, h⟩, apply classical.by_contradiction, intro hB, exact h ⟨hA, hB⟩,
intro hB, refine ⟨hBA hB, _⟩, rintro ⟨hA, hB'⟩, exact hB' hB,
end
lemma empty_subset {A : Set} : ∅ ⊆ A :=
λ x : Set, assume hx : x ∈ ∅, show x ∈ A, from false.elim (mem_empty x hx)
lemma prod_subset_of_subset_of_subset {A B : Set} (hAB : A ⊆ B) {C D : Set} (hCD : C ⊆ D) : A.prod C ⊆ B.prod D :=
begin
intros z hz, simp only [mem_prod, exists_prop] at *,
rcases hz with ⟨a, ha, c, hc, he⟩,
exact ⟨_, hAB ha, _, hCD hc, he⟩,
end
lemma inter_eq_of_subset {A B : Set} (hAB : A ⊆ B) : B ∩ A = A :=
begin
apply ext, intro x, rw mem_inter, split,
rintro ⟨hB, hA⟩, exact hA,
intro hA, exact ⟨hAB hA, hA⟩,
end
lemma inter_subset_right {A B : Set} : A ∩ B ⊆ B :=
begin
intros x xAB, rw mem_inter at xAB, exact xAB.right,
end
lemma inter_subset_left {A B : Set} : A ∩ B ⊆ A :=
begin
intros x xAB, rw mem_inter at xAB, exact xAB.left,
end
lemma diff_sub_diff_of_sub {A B : Set} (AB : A ⊆ B) {C : Set} : C \ B ⊆ C \ A :=
begin
intros x xCB, rw mem_diff at *, exact ⟨xCB.left, assume xA, xCB.right (AB xA)⟩,
end
lemma mem_sep' {X : Set} {p : Set → Prop} {x : Set} (xX : x ∈ X) : x ∈ {x ∈ X | p x} ↔ p x :=
by simp only [mem_sep, xX, true_and]
lemma inter_eq_of_sub {A B : Set} (AB : A ⊆ B) : A ∩ B = A :=
begin
apply ext, intro x, rw mem_inter, split,
rintro ⟨xA, -⟩, exact xA,
intro xA, exact ⟨xA, AB xA⟩,
end
lemma singleton_ne_empty {x : Set} : ({x} : Set) ≠ ∅ :=
begin
apply ne_empty_of_inhabited, use x, rw mem_singleton,
end
lemma sub_inter_of_sub {x a b : Set} (xa : x ⊆ a) (xb : x ⊆ b) : x ⊆ a ∩ b :=
begin
intros z zx, rw mem_inter, exact ⟨xa zx, xb zx⟩,
end
lemma Union_sub_of_sub {A B : Set} (AB : A ⊆ B) : A.Union ⊆ B.Union :=
begin
simp only [subset_def, mem_Union, exists_prop],
rintros x ⟨y, yA, xy⟩, exact ⟨_, AB yA, xy⟩,
end
lemma Union_sub {A X : Set} (h : ∀ {x : Set}, x ∈ X → x ⊆ A) : X.Union ⊆ A :=
begin
intro z, rw mem_Union, rintro ⟨x, xX, zx⟩, exact h xX zx,
end
lemma Union_diff_empty_eq {A : Set} : A.Union = (A \ {∅}).Union :=
begin
apply ext, simp only [mem_Union, exists_prop, mem_diff, mem_singleton], intro x, split,
rintro ⟨y, yA, xy⟩, refine ⟨_, ⟨yA, _⟩, xy⟩, apply ne_empty_of_inhabited, rw inhab, exact ⟨_, xy⟩,
rintro ⟨y, ⟨yA, -⟩, xy⟩, finish,
end
lemma union_eq_Union {A B : Set} : A ∪ B = Union {A, B} :=
begin
apply ext, simp only [mem_union, mem_Union, exists_prop, mem_insert, mem_singleton], intro x, split,
finish,
rintro ⟨z, (hz|hz), xz⟩; finish,
end
lemma Union_empty : Union ∅ = ∅ :=
begin
rw eq_empty, intros z h, rw mem_Union at h, rcases h with ⟨x, h, -⟩, exact mem_empty _ h,
end
lemma inhab_of_Union_inhab {S : Set} (inh : S.Union.inhab) : S.inhab :=
begin
obtain ⟨x, hx⟩ := inh, rw mem_Union at hx, rcases hx with ⟨y, yS, xy⟩,
exact ⟨_, yS⟩,
end
end Set |
[STATEMENT]
lemma cos_periodic [simp]: "cos (x + 2 * pi) = cos x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cos (x + 2 * pi) = cos x
[PROOF STEP]
by (simp add: cos_add sin_double cos_double) |
(*Congruence is weaker than reflexivity when it comes to higher level than necessary equalities:*)
Goal @eq Set nat nat.
congruence.
Qed.
Goal @eq Type nat nat.
Fail congruence. (*bug*)
reflexivity.
Qed.
Variable T : Type.
Goal @eq Type T T.
congruence.
Qed.
|
# Research
The title of the notebook should be coherent with file name. Namely, file name should be:
author's initials_progressive number_title.ipynb
# Purpose
State the purpose of the notebook.
# Methodology
Quickly describe assumptions and processing steps.
# WIP - improvements
(WORK IN PROGRESS)
Use this section only if the notebook is not final.
Notable TODOs:
* todo 1
* todo 2
* todo 3
## Results
Describe and comment the most important results.
# Suggested next steps
State suggested next steps, based on results obtained in this notebook.
# Setup
```python
# %load imports.py
"""
These is the standard setup for the notebooks.
"""
%matplotlib inline
%load_ext autoreload
%autoreload 2
from jupyterthemes import jtplot
jtplot.style(theme='onedork', context='notebook', ticks=True, grid=False)
import pandas as pd
pd.options.display.max_rows = 999
pd.options.display.max_columns = 999
pd.set_option("display.max_columns", None)
import numpy as np
import os
import matplotlib.pyplot as plt
#plt.style.use('paper')
#import data
import copy
from mdldb.tables import Run
from sklearn.pipeline import Pipeline
from rolldecayestimators.transformers import CutTransformer, LowpassFilterDerivatorTransformer, ScaleFactorTransformer, OffsetTransformer
from rolldecayestimators.direct_estimator_cubic import EstimatorQuadraticB, EstimatorCubic
from rolldecayestimators.ikeda_estimator import IkedaQuadraticEstimator
import rolldecayestimators.equations as equations
import rolldecayestimators.lambdas as lambdas
from rolldecayestimators.substitute_dynamic_symbols import lambdify
import rolldecayestimators.symbols as symbols
import sympy as sp
from sklearn.metrics import r2_score
from src.data import database
```
|
lemma metric_isCont_LIM_compose2: fixes f :: "'a :: metric_space \<Rightarrow> _" assumes f [unfolded isCont_def]: "isCont f a" and g: "g \<midarrow>f a\<rightarrow> l" and inj: "\<exists>d>0. \<forall>x. x \<noteq> a \<and> dist x a < d \<longrightarrow> f x \<noteq> f a" shows "(\<lambda>x. g (f x)) \<midarrow>a\<rightarrow> l" |
{-# OPTIONS --universe-polymorphism #-}
module AutoMisc where
-- prelude
postulate
Level : Set
lzero : Level
lsuc : (i : Level) → Level
{-# BUILTIN LEVEL Level #-}
{-# BUILTIN LEVELZERO lzero #-}
{-# BUILTIN LEVELSUC lsuc #-}
data _≡_ {a} {A : Set a} (x : A) : A → Set where
refl : x ≡ x
trans : ∀ {a} {A : Set a} → {x y z : A} → x ≡ y → y ≡ z → x ≡ z
trans refl refl = refl
sym : ∀ {a} {A : Set a} → {x y : A} → x ≡ y → y ≡ x
sym refl = refl
cong : ∀ {a b} {A : Set a} {B : Set b}
(f : A → B) {x y} → x ≡ y → f x ≡ f y
cong f refl = refl
data _IsRelatedTo_ {a : Level} {Carrier : Set a} (x y : Carrier) : Set a where
relTo : (x∼y : x ≡ y) → x IsRelatedTo y
begin_ : {a : Level} {Carrier : Set a} → {x y : Carrier} → x IsRelatedTo y → x ≡ y
begin relTo x∼y = x∼y
_∎ : {a : Level} {Carrier : Set a} → (x : Carrier) → x IsRelatedTo x
_∎ _ = relTo refl
_≡⟨_⟩_ : {a : Level} {Carrier : Set a} → (x : Carrier) {y z : Carrier} → x ≡ y → y IsRelatedTo z → x IsRelatedTo z
_ ≡⟨ x∼y ⟩ relTo y∼z = relTo (trans x∼y y∼z)
data ℕ : Set where
zero : ℕ
suc : (n : ℕ) → ℕ
_+_ : ℕ → ℕ → ℕ
zero + n = n
suc m + n = suc (m + n)
data ⊥ : Set where
¬ : Set → Set
¬ A = A → ⊥
data Π (A : Set) (F : A → Set) : Set where
fun : ((a : A) → F a) → Π A F
data Σ (A : Set) (F : A → Set) : Set where
ΣI : (a : A) → (F a) → Σ A F
data Fin : ℕ → Set where
zero : ∀ {n} → Fin (suc n)
suc : ∀ {n} → Fin n → Fin (suc n)
data List (X : Set) : Set where
[] : List X
_∷_ : X → List X → List X
_++_ : {X : Set} → List X → List X → List X
[] ++ ys = ys
(x ∷ xs) ++ ys = x ∷ (xs ++ ys)
data Vec (X : Set) : ℕ → Set where
[] : Vec X zero
_∷_ : ∀ {n} → X → Vec X n → Vec X (suc n)
module AdditionCommutative where
lemma : ∀ n m → (n + suc m) ≡ suc (n + m)
lemma n m = {!!}
lemma' : ∀ n m → (n + suc m) ≡ suc (n + m)
lemma' zero m = refl
lemma' (suc n) m = cong suc (lemma' n m)
addcommut : ∀ n m → (n + m) ≡ (m + n)
addcommut n m = {!!}
module Drink where
postulate RAA : (A : Set) → (¬ A → ⊥) → A
drink : (A : Set) → (a : A)
→ (Drink : A → Set) → Σ A (λ x → (Drink x) → Π A Drink)
drink A a Drink = {!!}
module VecMap where
map : {X Y : Set} → {n : ℕ} → (X → Y) → Vec X n → Vec Y n
map f xs = {!!}
module Disproving where
p : {X : Set} → (xs ys : List X) → (xs ++ ys) ≡ (ys ++ xs)
p = {!!}
|
"""
Common exceptions
https://github.com/frictionlessdata/DataPackage.jl#exceptions
"""
struct PackageError <: Exception
message::String
end
|
(**************************************************************************)
(* This file is part of CertrBPF, *)
(* a formally verified rBPF verifier + interpreter + JIT in Coq. *)
(* *)
(* Copyright (C) 2022 Inria *)
(* *)
(* 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 2 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. *)
(* *)
(**************************************************************************)
From compcert Require Import Integers Values AST Memory Memtype.
From bpf.comm Require Import BinrBPF State Monad rBPFMonadOp.
From bpf.model Require Import Syntax Semantics.
From bpf.isolation Require Import CommonISOLib AlignChunk RegsInv MemInv VerifierInv CheckMem StateInv IsolationLemma.
From Coq Require Import ZArith Lia.
Open Scope Z_scope.
Axiom call_inv_0: forall st1 st2 b ofs res
(Hreg : register_inv st1)
(Hcall: exec_function (Vptr b ofs) st1 = Some (res, st2)),
register_inv st2.
Axiom call_inv_1: forall st1 st2 b ofs res
(Hmem : memory_inv st1)
(Hcall: exec_function (Vptr b ofs) st1 = Some (res, st2)),
memory_inv st2.
Axiom call_inv_2: forall st st1 st2 b ofs res
(Hst0 : state_include st st1)
(Hcall: exec_function (Vptr b ofs) st1 = Some (res, st2)),
state_include st st2.
Lemma call_inv: forall st st1 st2 b ofs res
(Hreg : register_inv st1)
(Hmem : memory_inv st1)
(Hst0 : state_include st st1)
(Hcall: exec_function (Vptr b ofs) st1 = Some (res, st2)),
register_inv st2 /\ memory_inv st2 /\ state_include st st2.
Proof.
intros.
split; [eapply call_inv_0; eauto | split; [eapply call_inv_1; eauto | eapply call_inv_2; eauto]].
Qed.
Lemma step_preserving_inv:
forall st st1 st2 t
(Hreg: register_inv st1)
(Hmem: memory_inv st1)
(Hst0 : state_include st st1)
(Hsem: step st1 = Some (t, st2)),
register_inv st2 /\ memory_inv st2 /\ state_include st st2.
Proof.
unfold step.
unfold_monad.
intros.
match goal with
| H: match (if ?X then _ else _) with | _ => _ end = Some _ |- _ =>
destruct X; [| inversion H]
end.
destruct (Decode.decode _) in Hsem; [| inversion Hsem].
destruct i in Hsem.
- (* BPF_NEG *)
apply reg_inv_eval_reg with (r:= r) in Hreg as Heval_reg.
destruct Heval_reg as (vl & Heval_reg).
destruct a; rewrite Heval_reg in Hsem; simpl in Hsem.
+ inversion Hsem.
split.
eapply reg_inv_upd_reg; eauto.
split.
eapply mem_inv_upd_reg; eauto.
eapply state_include_upd_reg; eauto.
+ inversion Hsem.
split.
eapply reg_inv_upd_reg; eauto.
split.
eapply mem_inv_upd_reg; eauto.
eapply state_include_upd_reg; eauto.
- (* BPF_BINARY *)
eapply step_preserving_inv_alu; eauto.
- (* BPF_JA *)
match goal with
| H : (if ?X then _ else _) = _ |- _ =>
destruct X; inversion H
end.
split; [eapply reg_inv_upd_pc; eauto |
split; [eapply mem_inv_upd_pc; eauto | eapply state_include_upd_pc; eauto]].
- (* BPF_JUMP *)
eapply step_preserving_inv_branch; eauto.
- (* BPF_LDDW_low *)
unfold rBPFValues.sint32_to_vint in Hsem.
simpl in Hsem.
inversion Hsem; clear Hsem.
split; [eapply reg_inv_upd_reg; eauto |
split; [eapply mem_inv_upd_reg; eauto | eapply state_include_upd_reg; eauto]].
- (* BPF_LDDW_high *)
unfold rBPFValues.sint32_to_vint in Hsem.
destruct Val.orl; inversion Hsem.
split; [eapply reg_inv_upd_reg; eauto |
split; [eapply mem_inv_upd_reg; eauto | eapply state_include_upd_reg; eauto]].
- (* BPF_LDX *)
eapply step_preserving_inv_ld; eauto.
- (* BPF_ST *)
eapply step_preserving_inv_st; eauto.
- (* BPF_CALL *)
assert (Hget_call: forall i, exists ptr,
_bpf_get_call (Vint i) st1 = Some (ptr, st1) /\
(ptr = Vnullptr \/ (exists b ofs, ptr = Vptr b ofs /\ ((Mem.valid_pointer (bpf_m st1) b (Ptrofs.unsigned ofs)
|| Mem.valid_pointer (bpf_m st1) b (Ptrofs.unsigned ofs - 1)) = true)%bool))). {
intro.
apply lemma_bpf_get_call.
}
specialize (Hget_call (Int.repr (Int64.unsigned (Int64.repr (Int.signed i))))).
destruct Hget_call as (ptr & Hget_call & Hres).
rewrite Hget_call in Hsem.
destruct Hres as [Hnull | (b & ofs & Hptr & Hvalid)]; unfold cmp_ptr32_nullM, rBPFValues.cmp_ptr32_null in Hsem; subst.
+ simpl in Hsem.
rewrite Int.eq_true in Hsem.
inversion Hsem; split; [eapply reg_inv_upd_flag; eauto |
split; [eapply mem_inv_upd_flag; eauto | eapply state_include_upd_flag; eauto]].
+ destruct Val.cmpu_bool eqn:cmp; [| inversion Hsem].
destruct b0.
* inversion Hsem; split; [eapply reg_inv_upd_flag; eauto |
split; [eapply mem_inv_upd_flag; eauto | eapply state_include_upd_flag; eauto]].
* assert (Hexec: forall b ofs st1,
exists v st2, exec_function (Vptr b ofs) st1 = Some (Vint v, st2) /\ rBPFValues.cmp_ptr32_null (State.eval_mem st1) (Vptr b ofs) = Some false) by apply lemma_exec_function0.
specialize (Hexec b ofs st1).
destruct Hexec as (res & st' & Hexec & _).
rewrite Hexec in Hsem.
eapply call_inv in Hexec; eauto.
destruct res; inversion Hsem.
destruct Hexec as (Hreg_st & Hmem_st & Hver_st).
split; [eapply reg_inv_upd_reg; eauto |
split; [eapply mem_inv_upd_reg; eauto | eapply state_include_upd_reg; eauto]].
- (* BPF_RET *)
inversion Hsem.
split; [eapply reg_inv_upd_flag; eauto |
split; [eapply mem_inv_upd_flag; eauto | eapply state_include_upd_flag; eauto]].
- (* BPF_ERR *)
inversion Hsem.
split; [eapply reg_inv_upd_flag; eauto |
split; [ eapply mem_inv_upd_flag; eauto | eapply state_include_upd_flag; eauto]].
Qed.
Lemma bpf_interpreter_aux_preserving_inv:
forall st fuel st1 st2 t
(Hreg: register_inv st1)
(Hmem: memory_inv st1)
(Hst0 : state_include st st1)
(Hsem: bpf_interpreter_aux fuel st1 = Some (t, st2)),
register_inv st2 /\ memory_inv st2 /\ state_include st st2.
Proof.
induction fuel; intros.
- simpl in Hsem.
inversion Hsem; split; [eapply reg_inv_upd_flag; eauto |
split; [eapply mem_inv_upd_flag; eauto | eapply state_include_upd_flag; eauto]].
- simpl in Hsem.
unfold eval_ins_len, eval_pc, eval_flag, upd_pc_incr, bindM, returnM in Hsem.
destruct Int.ltu.
+ destruct step eqn: Hstep; [| inversion Hsem].
destruct p.
destruct Flag.flag_eq.
* destruct Int.ltu.
{
eapply step_preserving_inv in Hstep; eauto.
destruct Hstep as (Hreg_s & Hmem_s & Hver_s).
assert (Hinv: register_inv (State.upd_pc_incr s) /\ memory_inv (State.upd_pc_incr s) /\ state_include st (State.upd_pc_incr s)). {
split; [eapply reg_inv_upd_pc_incr; eauto |
split; [eapply mem_inv_upd_pc_incr; eauto | eapply state_include_upd_pc_incr; eauto]].
}
destruct Int.cmpu; [| inversion Hsem].
destruct Hinv as (Hreg_s' & Hmem_s' & Hver_s').
specialize (IHfuel (State.upd_pc_incr s) st2 t Hreg_s' Hmem_s' Hver_s' Hsem).
congruence.
}
{
eapply step_preserving_inv in Hstep; eauto.
destruct Hstep as (Hreg_s & Hmem_s & Hver_s).
assert (Hinv: register_inv (State.upd_pc_incr s) /\ memory_inv (State.upd_pc_incr s) /\ state_include st (State.upd_pc_incr s)). {
split; [eapply reg_inv_upd_pc_incr; eauto |
split; [eapply mem_inv_upd_pc_incr; eauto | eapply state_include_upd_pc_incr; eauto]].
}
inversion Hsem.
clear - Hreg_s Hmem_s Hver_s.
split; [eapply reg_inv_upd_flag; eauto |
split; [eapply mem_inv_upd_flag; eauto | eapply state_include_upd_flag; eauto]].
}
* inversion Hsem. subst.
eapply step_preserving_inv in Hstep; eauto.
+ inversion Hsem; split; [eapply reg_inv_upd_flag; eauto |
split; [eapply mem_inv_upd_flag; eauto | eapply state_include_upd_flag; eauto]].
Qed.
Theorem bpf_interpreter_preserving_inv:
forall st fuel st1 st2 t
(Hreg: register_inv st1)
(Hmem: memory_inv st1)
(Hst0 : state_include st st1)
(Hsem: bpf_interpreter fuel st1 = Some (t, st2)),
register_inv st2 /\ memory_inv st2 /\ state_include st st2.
Proof.
intros.
unfold bpf_interpreter in Hsem.
unfold upd_reg, eval_flag, eval_reg, bindM, returnM in Hsem.
destruct bpf_interpreter_aux eqn: Haux; [| inversion Hsem].
destruct p.
eapply bpf_interpreter_aux_preserving_inv in Haux; eauto.
destruct Flag.flag_eq.
- inversion Hsem.
subst.
auto.
- inversion Hsem.
subst.
auto.
Qed. |
@doc raw"""
JONSWAP{K}(α,ωₚ,γ,r)
JONSWAP{K}(x)
4 parameter JONSWAP model for vertical displacement.
# Type parameter
The type parameter `K` is a non-negative integer representing the ammount of aliasing to be done.
This is useful as some devices have high-pass filters which limit the ammount of aliasing that will be present in a recorded series.
In particular, a `JONSWAP{K}` model for a series recorded every `Δ` seconds would be appropriate for a series sampled every `Δ` seconds and filtered with a high-pass filter at `(2K-1)π/Δ`.
# Arguments
- `α`: The scale parameter.
- `ωₚ`: The peak angular frequency.
- `γ`: The peak enhancement factor.
- `r`: The tail decay index.
# Vector constructor arguments
- `x`: Vector of parameters `[α,ωₚ,γ,r]`.
# Background
The JONSWAP spectral density function is
```math
f(ω) = αω^{-r}\exp\left \{-\frac{r}{4}\left(\frac{|ω|}{ωₚ}\right)^{-4}\right \}γ^{δ(|ω|)}
```
where
```math
δ(ω) = \exp\left\{-\tfrac{1}{2 (0.07+0.02\cdot\mathbb{1}_{ωₚ>|ω|})^2}\left (\tfrac{|ω|}{ωₚ}-1\right )^2\right\}.
```
"""
struct JONSWAP{K} <: WhittleLikelihoodInference.UnknownAcvTimeSeriesModel{1,Float64}
α::Float64
ωₚ::Float64
γ::Float64
r::Float64
r_over4::Float64
ωₚ²::Float64
ωₚ³::Float64
ωₚ⁴::Float64
ωₚ⁶::Float64
logγ::Float64
function JONSWAP{K}(α,ωₚ,γ,r) where {K}
α > 0 || throw(ArgumentError("JONSWAP requires α > 0"))
ωₚ > 0 || throw(ArgumentError("JONSWAP requires ωₚ > 0"))
γ >= 1 || throw(ArgumentError("JONSWAP requires γ > 1"))
r > 1 || throw(ArgumentError("JONSWAP requires r > 1"))
new{K}(α,ωₚ,γ,r,r/4,ωₚ^2,ωₚ^3,ωₚ^4,ωₚ^6,log(γ))
end
function JONSWAP{K}(x::AbstractVector{Float64}) where {K}
@boundscheck checkparameterlength(x,JONSWAP{K})
@inbounds JONSWAP{K}(x[1], x[2], x[3], x[4])
end
end
# functions to throw informative error if type parameter not provided
JONSWAP(x::AbstractVector{Float64}) = JONSWAP(1,1,1,1)
JONSWAP(α,ωₚ,γ,r) = error("JONSWAP process requires the ammount of aliasing specified as a type parameter. Use JONSWAP{K}() where K ∈ N.")
WhittleLikelihoodInference.npars(::Type{JONSWAP{K}}) where {K} = 4
WhittleLikelihoodInference.nalias(::JONSWAP{K}) where {K} = K
WhittleLikelihoodInference.lowerbounds(::Type{JONSWAP{K}}) where {K} = [0,0,1,1]
WhittleLikelihoodInference.upperbounds(::Type{JONSWAP{K}}) where {K} = [Inf,Inf,Inf,Inf]
@inline @fastmath function WhittleLikelihoodInference.sdf(model::JONSWAP{K}, ω::Real) where {K}
α,ωₚ,γ,r = model.α,model.ωₚ,model.γ,model.r
ω = abs(ω)
if ω > 1e-10
σ1² = 0.0049 + 0.0032 * (ω > ωₚ)
δ = exp(-1 / (2σ1²) * (ω / ωₚ - 1)^2)
ωₚ⁴_over_ω⁴ = model.ωₚ⁴ / (ω^4)
return (α * ω^(-r) * exp(-(model.r_over4) * ωₚ⁴_over_ω⁴) * γ^δ) / 2
else
return 0.0
end
end
@propagate_inbounds @fastmath function WhittleLikelihoodInference.grad_add_sdf!(out, model::JONSWAP{K}, ω::Real) where {K}
@boundscheck checkbounds(out,1:4)
@inbounds begin
ω = abs(ω)
if ω > 1e-10
α,ωₚ,γ,r = model.α,model.ωₚ,model.γ,model.r
σ1² = 0.0049 + 0.0032 * (ω > ωₚ)
δ = exp(-1 / (2σ1²) * (ω / ωₚ - 1)^2)
ω⁻⁴ = ω^(-4)
ωₚ⁴_over_ω⁴ = model.ωₚ⁴ * ω⁻⁴
sdf = (α * ω^(-r) * exp(-(model.r_over4) * ωₚ⁴_over_ω⁴) * γ^δ) / 2
∂S∂α = sdf / α
∂S∂ωₚ = sdf * (δ*model.logγ * ω / σ1² *(ω-ωₚ) / model.ωₚ³ - r*model.ωₚ³*ω⁻⁴)
∂S∂γ = sdf * δ / γ
∂S∂r = sdf * (-log(ω)-ωₚ⁴_over_ω⁴/4)
out[1] += ∂S∂α
out[2] += ∂S∂ωₚ
out[3] += ∂S∂γ
out[4] += ∂S∂r
end # 0 otherwise
end
return nothing
end
@propagate_inbounds @fastmath function WhittleLikelihoodInference.hess_add_sdf!(out, model::JONSWAP{K}, ω::Real) where {K}
@boundscheck checkbounds(out,1:10)
@inbounds begin
ω = abs(ω)
if ω > 1e-10
α,ωₚ,γ,r = model.α,model.ωₚ,model.γ,model.r
σ1² = 0.0049 + 0.0032 * (ω > ωₚ)
δ = exp(-1 / (2σ1²) * (ω / ωₚ - 1)^2)
ω⁻⁴ = ω^(-4)
ωₚ⁴_over_ω⁴ = model.ωₚ⁴ * ω⁻⁴
ωₚ³_over_ω⁴ = model.ωₚ³ * ω⁻⁴
sdf = (α * ω^(-r) * exp(-(model.r_over4) * ωₚ⁴_over_ω⁴) * γ^δ) / 2
δωlogγ_over_σ1² = δ*model.logγ * ω / σ1²
∂S∂ωₚUsepart = (δ*model.logγ * ω / σ1² *(ω-ωₚ) / model.ωₚ³ - r*ωₚ³_over_ω⁴)
∂S∂ωₚ = sdf * ∂S∂ωₚUsepart
δ_over_γ = δ / γ
∂S∂γ = sdf * δ_over_γ
∂r_part = (-log(ω)-ωₚ⁴_over_ω⁴/4)
∂S∂r = sdf * ∂r_part
∂S∂αωₚ = ∂S∂ωₚ / α
∂S∂αγ = ∂S∂γ / α
∂S∂αr = ∂S∂r / α
∂S∂ωₚ2 = ∂S∂ωₚ * ∂S∂ωₚUsepart + sdf * (δωlogγ_over_σ1² *((-3ω + 2ωₚ)/model.ωₚ⁴ + ω * (ω-ωₚ)^2/model.ωₚ⁶/σ1²) - 3r*model.ωₚ²*ω⁻⁴)
∂S∂ωₚγ = ∂S∂γ * ∂S∂ωₚUsepart + sdf * δ_over_γ * ω / σ1²*(ω-ωₚ)/model.ωₚ³
∂S∂ωₚr = ∂S∂r * ∂S∂ωₚUsepart - sdf * model.ωₚ³*ω⁻⁴
∂S∂γ2 = δ_over_γ * (∂S∂γ - sdf/γ)
∂S∂γr = ∂S∂r * δ_over_γ
∂S∂r2 = ∂S∂r * ∂r_part
# out[1] += 0
out[2] += ∂S∂αωₚ
out[3] += ∂S∂αγ
out[4] += ∂S∂αr
out[5] += ∂S∂ωₚ2
out[6] += ∂S∂ωₚγ
out[7] += ∂S∂ωₚr
out[8] += ∂S∂γ2
out[9] += ∂S∂γr
out[10] += ∂S∂r2
end # 0 otherwise
end
return nothing
end |
{-# OPTIONS --without-K #-}
module SEquivSCPermEquiv where
-- Data types from standard library
open import Level using (zero)
open import Data.Nat using (ℕ; _+_)
open import Data.Fin using (Fin; inject+; raise)
open import Data.Sum using (inj₁; inj₂)
open import Data.Product using (_,_; proj₁; proj₂)
open import Data.Vec using (tabulate) renaming (_++_ to _++V_)
open import Function using (_∘_; id)
-- Properties from standard library
open import Data.Vec.Properties using (lookup∘tabulate)
open import Relation.Binary using (Setoid)
open import Function.Equality using (_⇨_; _⟨$⟩_; _⟶_)
renaming (_∘_ to _⊚_; id to id⊚)
open import Relation.Binary.PropositionalEquality
using (_≡_; refl; sym; trans; cong; cong₂; setoid; →-to-⟶;
module ≡-Reasoning)
-- Next are imports from our libraries of Proofs (FiniteFunctions and
-- VectorLemmas)
open import Proofs using (finext; _!!_; tabulate-split)
-- Next we import our notions of equivalences
open import Equiv using (_∼_; module qinv; mkqinv; _≃_)
-- Next we import sets equipped with equivalence relations and
-- specialize to our notions of equivalence
open import SetoidEquiv
using (
≃S-Setoid; -- statement of thm2
_≃S_; -- statement of thm2
module _≃S_; -- proof of thm2
module _≋_; -- proof of thm2
equiv; -- proof of thm2
equivS; -- proof of thm2
_≋_ -- proof of thm2
-- id≃S
-- 0≃S;
-- _≃S≡_;
-- _⊎≃S_
)
-- Finally we import our definition of permutations. We start with Vec
-- (Fin m) n for arbitrary m and n which---if well-formed---would
-- define a permutation in the Cauchy representation. These vectors
-- assume a canonical enumeration of the finite sets which we make
-- explicit in the module Enumeration. To ensure these vectors are
-- well-formed, we define a concrete permutation as a pair of two such
-- vectors with two proofs that they compose to the identity
-- permutation.
open import FinVec using (_∘̂_; 1C)
open import FinVecProperties using (~⇒≡; !!⇒∘̂; 1C!!i≡i; cauchyext)
open import EnumEquiv using (Enum; 0E; _⊕e_; eval-left; eval-right)
open import FiniteType using (FiniteType; ∣_∣)
open import ConcretePermutation -- using (CPerm; cp; p≡; 0p; idp; _⊎p_) -- ; SCPerm)
open import ConcretePermutationProperties -- using (CPerm; cp; p≡; 0p; idp; _⊎p_) -- ; SCPerm)
------------------------------------------------------------------------------
-- The big (semantic) theorem!
thm2 : ∀ {A B : Set} → (a : FiniteType A) → (b : FiniteType B) →
(≃S-Setoid A B) ≃S (SCPerm ∣ b ∣ ∣ a ∣)
thm2 {A} {B} (n , (enumA , mkqinv labelA αA βA))
(m , (enumB , mkqinv labelB αB βB)) =
equiv fwd' bwd' α β
where
open ≡-Reasoning
AS = setoid A
BS = setoid B
A≃Fn : A ≃ Fin n
A≃Fn = (enumA , mkqinv labelA αA βA)
B≃Fn : B ≃ Fin m
B≃Fn = (enumB , mkqinv labelB αB βB)
CP⇨ = SCPerm m n ⇨ SCPerm m n
fwd : (AS ≃S BS) → CPerm m n
fwd A≃B = cp (tabulate f) (tabulate g) (~⇒≡ β) (~⇒≡ α)
where
module A≃SB = _≃S_ A≃B
f : Fin n → Fin m
f j = enumB (A≃SB.f ⟨$⟩ labelA j)
g : Fin m → Fin n
g j = enumA (A≃SB.g ⟨$⟩ labelB j)
α : f ∘ g ∼ id
α i =
begin
(enumB (A≃SB.f ⟨$⟩ (labelA (enumA (A≃SB.g ⟨$⟩ labelB i))))
≡⟨ cong (λ x → enumB (A≃SB.f ⟨$⟩ x)) (βA ((A≃SB.g ⟨$⟩ labelB i))) ⟩
enumB (A≃SB.f ⟨$⟩ (A≃SB.g ⟨$⟩ labelB i))
≡⟨ cong enumB (A≃SB.α refl) ⟩
enumB (labelB i)
≡⟨ αB i ⟩
i ∎)
β : g ∘ f ∼ id
β i =
begin (
enumA (A≃SB.g ⟨$⟩ labelB (enumB (A≃SB.f ⟨$⟩ labelA i)))
≡⟨ cong (λ x → enumA (A≃SB.g ⟨$⟩ x)) (βB _) ⟩
enumA (A≃SB.g ⟨$⟩ (A≃SB.f ⟨$⟩ labelA i))
≡⟨ cong enumA (A≃SB.β refl) ⟩
enumA (labelA i)
≡⟨ αA i ⟩
i ∎)
fwd' : ≃S-Setoid A B ⟶ setoid (CPerm m n)
fwd' = record
{ _⟨$⟩_ = fwd
; cong = λ {i} {j} i≋j → p≡ (finext (λ k → cong enumB (f≡ i≋j (labelA k)) ))
}
where open _≋_
bwd : CPerm m n → (AS ≃S BS)
bwd (cp p₁ p₂ αp βp) = equiv f g α β
where
f : AS ⟶ BS
f = →-to-⟶ (λ a → labelB (p₁ !! enumA a))
g : BS ⟶ AS
g = →-to-⟶ (λ b → labelA (p₂ !! (enumB b)))
α : Setoid._≈_ (BS ⇨ BS) (f ⊚ g) id⊚
α {b} {.b} refl =
begin (
labelB (p₁ !! (enumA (labelA (p₂ !! (enumB b)))))
≡⟨ cong (λ x → labelB (p₁ !! x)) (αA _) ⟩
labelB (p₁ !! (p₂ !! enumB b))
≡⟨ cong labelB (!!⇒∘̂ _ _ (enumB b)) ⟩
labelB ((p₂ ∘̂ p₁) !! enumB b)
≡⟨ cong (λ x → (labelB (x !! enumB b))) βp ⟩
labelB (1C !! enumB b)
≡⟨ cong labelB 1C!!i≡i ⟩
labelB (enumB b)
≡⟨ βB b ⟩
b ∎)
β : Setoid._≈_ (AS ⇨ AS) (g ⊚ f) id⊚
β {a} {.a} refl =
begin (
labelA (p₂ !! (enumB (labelB (p₁ !! enumA a))))
≡⟨ cong (λ x → labelA (p₂ !! x)) (αB _) ⟩
labelA (p₂ !! (p₁ !! enumA a))
≡⟨ cong labelA (!!⇒∘̂ _ _ (enumA a)) ⟩
labelA ((p₁ ∘̂ p₂) !! enumA a)
≡⟨ cong (λ x → labelA (x !! enumA a)) αp ⟩
labelA (1C !! enumA a)
≡⟨ cong labelA 1C!!i≡i ⟩
labelA (enumA a)
≡⟨ βA a ⟩
a ∎)
bwd' : setoid (CPerm m n) ⟶ ≃S-Setoid A B
bwd' = record
{ _⟨$⟩_ = bwd
; cong = λ { {π} {.π} refl → equivS (λ _ → refl) (λ _ → refl) }
}
α : Setoid._≈_ CP⇨ (fwd' ⊚ bwd') id⊚
α {cp π πᵒ αp βp} refl = p≡ (trans (finext pf₁) (cauchyext π))
where
pf₁ : (j : Fin n) → enumB (labelB (π !! enumA (labelA j))) ≡ π !! j
pf₁ j =
begin (
enumB (labelB (π !! enumA (labelA j)))
≡⟨ αB _ ⟩
π !! enumA (labelA j)
≡⟨ cong (_!!_ π) (αA _) ⟩
π !! j ∎)
β : {x y : AS ≃S BS} → x ≋ y → ((bwd' ⊚ fwd') ⟨$⟩ x) ≋ y
β {equiv f g α β} {equiv f₁ g₁ α₁ β₁} (equivS f≡ g≡) =
equivS (λ a → trans (pf₁ a) (f≡ a)) (λ b → trans (pf₂ b) (g≡ b))
where
pf₁ : ∀ a → labelB (tabulate (λ j → enumB (f ⟨$⟩ labelA j)) !! (enumA a)) ≡ f ⟨$⟩ a
pf₁ a =
begin (
labelB (tabulate (λ j → enumB (f ⟨$⟩ labelA j)) !! enumA a)
≡⟨ cong labelB (lookup∘tabulate _ (enumA a)) ⟩
labelB (enumB (f ⟨$⟩ labelA (enumA a)))
≡⟨ βB _ ⟩
f ⟨$⟩ labelA (enumA a)
≡⟨ cong (_⟨$⟩_ f) (βA _) ⟩
f ⟨$⟩ a ∎)
pf₂ : ∀ b → labelA (tabulate (λ j → enumA (g ⟨$⟩ labelB j)) !! (enumB b)) ≡ g ⟨$⟩ b
pf₂ b =
begin (
labelA (tabulate (λ j → enumA (g ⟨$⟩ labelB j)) !! enumB b)
≡⟨ cong labelA (lookup∘tabulate _ (enumB b)) ⟩
labelA (enumA (g ⟨$⟩ labelB (enumB b)))
≡⟨ βA _ ⟩
g ⟨$⟩ labelB (enumB b)
≡⟨ cong (_⟨$⟩_ g) (βB _) ⟩
g ⟨$⟩ b ∎ )
-- Start proving some of the transport lemmas.
-- Need to do:
-- 1. prove that we have a bijective morphism of carriers: done, this is thm2 (fwd is the morphism)
-- 2. prove that it preserves:
-- a. id (done)
-- b. 0 (done)
-- c. + (done)
-- d. *
{--
Is this still important or has it been subsumed by the categorical work ???
Still important, I believe. It will be used in proving the categorical
components of CPermCat.
open _≃S_
lemma_1a : ∀ {n} {A : Set} → (EA : Enum A n) → f (thm2 EA EA) ⟨$⟩ id≃S ≡ idp
lemma_1a (f' , mkqinv g α _) = p≡ (trans (finext α) F.reveal1C)
-- this is redundant, as it follows from lemma_1a.
lemma_1b : ∀ {n} {A : Set} → (EA : Enum A n) → (g (thm2 EA EA) ⟨$⟩ idp) ≋ id≃S
lemma_1b (enumA , mkqinv g _ β) =
equivS (λ x → trans (cong g 1C!!i≡i) (β x)) (λ x → trans (cong g 1C!!i≡i) (β x))
lemma2 : f (thm2 0E 0E) ⟨$⟩ 0≃S ≡ 0p
lemma2 = p≡ F.reveal0C -- p≡ refl
lemma3 : ∀ {n₁ n₂} {A B C D : Set} {EA : Enum A n₁} {EB : Enum B n₁}
{EC : Enum C n₂} {ED : Enum D n₂} → (x : A ≃S≡ B) → (y : C ≃S≡ D) →
f (thm2 (EA ⊕e EC) (EB ⊕e ED)) ⟨$⟩ (x ⊎≃S y) ≡
(f (thm2 EA EB) ⟨$⟩ x) ⊎p (f (thm2 EC ED) ⟨$⟩ y)
lemma3 {n₁} {n₂} {EA = EA} {EB} {EC} {ED} (equiv f₄ g₄ α₄ β₄) (equiv f₅ g₅ α₅ β₅) =
p≡ (
begin (
CPerm.π (f (thm2 (EA ⊕e EC) (EB ⊕e ED)) ⟨$⟩ (x ⊎≃S y))
≡⟨ refl ⟩ -- inline f, fwd and π
tabulate {n₁ + n₂} (λ j → enumBD (x⊎y.f ⟨$⟩ qAC.g j))
≡⟨ tabulate-split {n₁} {n₂} {f = λ j → enumBD (x⊎y.f ⟨$⟩ qAC.g j)} ⟩
tabulate {n₁} (λ j → enumBD (x⊎y.f ⟨$⟩ qAC.g (inject+ n₂ j))) ++V
tabulate {n₂} (λ j → enumBD (x⊎y.f ⟨$⟩ qAC.g (raise n₁ j)))
≡⟨ cong₂ _++V_ (finext {n₁} pf₁) (finext pf₂) ⟩
tabulate {n₁} (λ j → inject+ n₂ (tabulate (λ i → enumB (f₄ ⟨$⟩ qA.g i)) !! j)) ++V
tabulate {n₂} (λ j → raise n₁ (tabulate (λ i → enumD (f₅ ⟨$⟩ qC.g i)) !! j))
≡⟨ sym F.reveal⊎c ⟩ -- going up, inline f, fwd, ⊎p and π
CPerm.π ((f (thm2 EA EB) ⟨$⟩ x) ⊎p (f (thm2 EC ED) ⟨$⟩ y)) ∎))
where
open ≡-Reasoning
x = equiv f₄ g₄ α₄ β₄
y = equiv f₅ g₅ α₅ β₅
enumB = proj₁ EB
enumD = proj₁ ED
enumAC = proj₁ (EA ⊕e EC)
module qAC = qinv (proj₂ (EA ⊕e EC))
module qA = qinv (proj₂ EA)
module qC = qinv (proj₂ EC)
enumBD = proj₁ (EB ⊕e ED)
module x⊎y = _≃S_ (x ⊎≃S y)
pf₁ : (i : Fin n₁) →
enumBD (x⊎y.f ⟨$⟩ qAC.g (inject+ n₂ i)) ≡
inject+ n₂ (tabulate (λ i₁ → enumB (f₄ ⟨$⟩ qA.g i₁)) !! i)
pf₁ i =
begin (
enumBD (x⊎y.f ⟨$⟩ qAC.g (inject+ n₂ i))
≡⟨ cong (λ j → enumBD (x⊎y.f ⟨$⟩ j)) (eval-left {eA = EA} {EC} i) ⟩
enumBD (x⊎y.f ⟨$⟩ inj₁ (qA.g i))
≡⟨ refl ⟩ -- once the inj₁ is exposed, the rest happens by β-reduction
inject+ n₂ (enumB (f₄ ⟨$⟩ qA.g i))
≡⟨ cong (inject+ n₂) (sym (lookup∘tabulate _ i)) ⟩
inject+ n₂ (tabulate (λ j → enumB (f₄ ⟨$⟩ qA.g j)) !! i) ∎)
pf₂ : (i : Fin n₂) →
enumBD (x⊎y.f ⟨$⟩ qAC.g (raise n₁ i)) ≡
raise n₁ (tabulate (λ i₁ → enumD (f₅ ⟨$⟩ qC.g i₁)) !! i)
pf₂ i =
begin (
enumBD (x⊎y.f ⟨$⟩ qAC.g (raise n₁ i))
≡⟨ cong (λ j → enumBD (x⊎y.f ⟨$⟩ j)) (eval-right {eA = EA} {EC} i) ⟩
enumBD (x⊎y.f ⟨$⟩ inj₂ (qC.g i))
≡⟨ refl ⟩
raise n₁ (enumD (f₅ ⟨$⟩ qC.g i))
≡⟨ cong (raise n₁) (sym (lookup∘tabulate _ i)) ⟩
raise n₁ (tabulate (λ i₁ → enumD (f₅ ⟨$⟩ qC.g i₁)) !! i) ∎)
-}
|
# Computes an isomorphic permutation group of the reduced degree.
# INPUT:
# > G - a finite group
# OUTPUT:
# > A group isomorphic to G which is a permutation group (and saved as such by GAP).
# The degree is also reduced with SmallerDegreePermutationRepresentation (not guaranteed to be optimal, though).
InstallGlobalFunction( GSPermutationGroup, function( G )
return Image( SmallerDegreePermutationRepresentation( Image( IsomorphismPermGroup( G ) ) ) );
end );
|
function f = sqrt( f )
%SQRT Square root.
% SQRT(F) returns the square root of a positive SEPARABLEAPPROX F.
% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.
% Empty check:
if ( isempty(f) )
return
end
if ( isreal(f) )
% Positive/negative test.
bool = singleSignTest(f); % Returns TRUE if there is no sign change.
if ( ~bool )
error('CHEBFUN:SEPARABLEAPPROX:sqrt:notSmooth', ...
'Sign change detected. Unable to represent the result.');
end
end
f = compose(f, @sqrt);
end |
State Before: n : ℕ
⊢ (map { toFun := Prod.swap, inj' := (_ : Function.Injective Prod.swap) } (antidiagonal n)).val = (antidiagonal n).val State After: no goals Tactic: simp [antidiagonal, Multiset.Nat.map_swap_antidiagonal] |
{- 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
-}
{-# OPTIONS --allow-unsolved-metas #-}
-- This module provides some scaffolding to define the handlers for our fake/simple "implementation"
-- and connect them to the interface of the SystemModel.
open import Optics.All
open import LibraBFT.Prelude
open import LibraBFT.Lemmas
open import LibraBFT.Base.ByteString
open import LibraBFT.Base.Encode
open import LibraBFT.Base.KVMap
open import LibraBFT.Base.PKCS
open import LibraBFT.Hash
open import LibraBFT.Impl.Base.Types
open import LibraBFT.Impl.Consensus.Types
open import LibraBFT.Impl.Util.Util
open import LibraBFT.Impl.Properties.Aux -- TODO-1: maybe Aux properties should be in this file?
open import LibraBFT.Concrete.System impl-sps-avp
open import LibraBFT.Concrete.System.Parameters
open EpochConfig
open import LibraBFT.Yasm.Yasm (ℓ+1 0ℓ) EpochConfig epochId authorsN ConcSysParms NodeId-PK-OK
open Structural impl-sps-avp
module LibraBFT.Impl.Handle.Properties
(hash : BitString → Hash)
(hash-cr : ∀{x y} → hash x ≡ hash y → Collision hash x y ⊎ x ≡ y)
where
open import LibraBFT.Impl.Consensus.ChainedBFT.EventProcessor hash hash-cr
open import LibraBFT.Impl.Handle hash hash-cr
----- Properties that bridge the system model gap to the handler -----
msgsToSendWereSent1 : ∀ {pid ts pm vm} {st : EventProcessor}
→ send (V vm) ∈ proj₂ (peerStep pid (P pm) ts st)
→ ∃[ αs ] (SendVote vm αs ∈ LBFT-outs (handle pid (P pm) ts) st)
msgsToSendWereSent1 {pid} {ts} {pm} {vm} {st} send∈acts
with send∈acts
-- The fake handler sends only to node 0 (fakeAuthor), so this doesn't
-- need to be very general yet.
-- TODO-1: generalize this proof so it will work when the set of recipients is
-- not hard coded.
-- The system model allows any message sent to be received by any peer (so the list of
-- recipients it essentially ignored), meaning that our safety proofs will be for a slightly
-- stronger model. Progress proofs will require knowledge of recipients, though, so we will
-- keep the implementation model faithful to the implementation.
...| here refl = fakeAuthor ∷ [] , here refl
msgsToSendWereSent : ∀ {pid ts nm m} {st : EventProcessor}
→ m ∈ proj₂ (peerStepWrapper pid nm st)
→ ∃[ vm ] (m ≡ V vm × send (V vm) ∈ proj₂ (peerStep pid nm ts st))
msgsToSendWereSent {pid} {nm = nm} {m} {st} m∈outs
with nm
...| C _ = ⊥-elim (¬Any[] m∈outs)
...| V _ = ⊥-elim (¬Any[] m∈outs)
...| P pm
with m∈outs
...| here v∈outs
with m
...| P _ = ⊥-elim (P≢V v∈outs)
...| C _ = ⊥-elim (C≢V v∈outs)
...| V vm rewrite sym v∈outs = vm , refl , here refl
----- Properties that relate handler to system state -----
postulate -- TODO-2: this will be proved for the implementation, confirming that honest
-- participants only store QCs comprising votes that have actually been sent.
-- Votes stored in highesQuorumCert and highestCommitCert were sent before.
-- Note that some implementations might not ensure this, but LibraBFT does
-- because even the leader of the next round sends its own vote to itself,
-- as opposed to using it to construct a QC using its own unsent vote.
qcVotesSentB4 : ∀{e pid ps vs pk q vm}{st : SystemState e}
→ ReachableSystemState st
→ initialised st pid ≡ initd
→ ps ≡ peerStates st pid
→ q QC∈VoteMsg vm
→ vm ^∙ vmSyncInfo ≡ mkSyncInfo (ps ^∙ epHighestQC) (ps ^∙ epHighestCommitQC)
→ vs ∈ qcVotes q
→ MsgWithSig∈ pk (proj₂ vs) (msgPool st)
|
/-
Copyright (c) 2020 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import algebra.continued_fractions.computation.approximations
import algebra.continued_fractions.computation.correctness_terminating
import algebra.order.archimedean
import data.rat.floor
/-!
# Termination of Continued Fraction Computations (`gcf.of`)
## Summary
We show that the continued fraction for a value `v`, as defined in
`algebra.continued_fractions.computation.basic`, terminates if and only if `v` corresponds to a
rational number, that is `↑v = q` for some `q : ℚ`.
## Main Theorems
- `generalized_continued_fraction.coe_of_rat` shows that
`generalized_continued_fraction.of v = generalized_continued_fraction.of q` for `v : α` given that
`↑v = q` and `q : ℚ`.
- `generalized_continued_fraction.terminates_iff_rat` shows that
`generalized_continued_fraction.of v` terminates if and only if `↑v = q` for some `q : ℚ`.
## Tags
rational, continued fraction, termination
-/
namespace generalized_continued_fraction
open generalized_continued_fraction (of)
variables {K : Type*} [linear_ordered_field K] [floor_ring K]
/-
We will have to constantly coerce along our structures in the following proofs using their provided
map functions.
-/
local attribute [simp] pair.map int_fract_pair.mapFr
section rat_of_terminates
/-!
### Terminating Continued Fractions Are Rational
We want to show that the computation of a continued fraction `generalized_continued_fraction.of v`
terminates if and only if `v ∈ ℚ`. In this section, we show the implication from left to right.
We first show that every finite convergent corresponds to a rational number `q` and then use the
finite correctness proof (`of_correctness_of_terminates`) of `generalized_continued_fraction.of` to
show that `v = ↑q`.
-/
variables (v : K) (n : ℕ)
lemma exists_gcf_pair_rat_eq_of_nth_conts_aux :
∃ (conts : pair ℚ),
(of v).continuants_aux n = (conts.map coe : pair K) :=
nat.strong_induction_on n
begin
clear n,
let g := of v,
assume n IH,
rcases n with _|_|n,
-- n = 0
{ suffices : ∃ (gp : pair ℚ), pair.mk (1 : K) 0 = gp.map coe, by simpa [continuants_aux],
use (pair.mk 1 0),
simp },
-- n = 1
{ suffices : ∃ (conts : pair ℚ), pair.mk g.h 1 = conts.map coe, by
simpa [continuants_aux],
use (pair.mk ⌊v⌋ 1),
simp },
-- 2 ≤ n
{ cases (IH (n + 1) $ lt_add_one (n + 1)) with pred_conts pred_conts_eq, -- invoke the IH
cases s_ppred_nth_eq : (g.s.nth n) with gp_n,
-- option.none
{ use pred_conts,
have : g.continuants_aux (n + 2) = g.continuants_aux (n + 1), from
continuants_aux_stable_of_terminated (n + 1).le_succ s_ppred_nth_eq,
simp only [this, pred_conts_eq] },
-- option.some
{ -- invoke the IH a second time
cases (IH n $ lt_of_le_of_lt (n.le_succ) $ lt_add_one $ n + 1)
with ppred_conts ppred_conts_eq,
obtain ⟨a_eq_one, z, b_eq_z⟩ : gp_n.a = 1 ∧ ∃ (z : ℤ), gp_n.b = (z : K), from
of_part_num_eq_one_and_exists_int_part_denom_eq s_ppred_nth_eq,
-- finally, unfold the recurrence to obtain the required rational value.
simp only [a_eq_one, b_eq_z,
(continuants_aux_recurrence s_ppred_nth_eq ppred_conts_eq pred_conts_eq)],
use (next_continuants 1 (z : ℚ) ppred_conts pred_conts),
cases ppred_conts, cases pred_conts,
simp [next_continuants, next_numerator, next_denominator] } }
end
lemma exists_gcf_pair_rat_eq_nth_conts :
∃ (conts : pair ℚ), (of v).continuants n = (conts.map coe : pair K) :=
by { rw [nth_cont_eq_succ_nth_cont_aux], exact (exists_gcf_pair_rat_eq_of_nth_conts_aux v $ n + 1) }
lemma exists_rat_eq_nth_numerator : ∃ (q : ℚ), (of v).numerators n = (q : K) :=
begin
rcases (exists_gcf_pair_rat_eq_nth_conts v n) with ⟨⟨a, _⟩, nth_cont_eq⟩,
use a,
simp [num_eq_conts_a, nth_cont_eq],
end
lemma exists_rat_eq_nth_denominator : ∃ (q : ℚ), (of v).denominators n = (q : K) :=
begin
rcases (exists_gcf_pair_rat_eq_nth_conts v n) with ⟨⟨_, b⟩, nth_cont_eq⟩,
use b,
simp [denom_eq_conts_b, nth_cont_eq]
end
/-- Every finite convergent corresponds to a rational number. -/
lemma exists_rat_eq_nth_convergent : ∃ (q : ℚ), (of v).convergents n = (q : K) :=
begin
rcases (exists_rat_eq_nth_numerator v n) with ⟨Aₙ, nth_num_eq⟩,
rcases (exists_rat_eq_nth_denominator v n) with ⟨Bₙ, nth_denom_eq⟩,
use (Aₙ / Bₙ),
simp [nth_num_eq, nth_denom_eq, convergent_eq_num_div_denom]
end
variable {v}
/-- Every terminating continued fraction corresponds to a rational number. -/
theorem exists_rat_eq_of_terminates
(terminates : (of v).terminates) :
∃ (q : ℚ), v = ↑q :=
begin
obtain ⟨n, v_eq_conv⟩ : ∃ n, v = (of v).convergents n, from
of_correctness_of_terminates terminates,
obtain ⟨q, conv_eq_q⟩ :
∃ (q : ℚ), (of v).convergents n = (↑q : K), from exists_rat_eq_nth_convergent v n,
have : v = (↑q : K), from eq.trans v_eq_conv conv_eq_q,
use [q, this]
end
end rat_of_terminates
section rat_translation
/-!
### Technical Translation Lemmas
Before we can show that the continued fraction of a rational number terminates, we have to prove
some technical translation lemmas. More precisely, in this section, we show that, given a rational
number `q : ℚ` and value `v : K` with `v = ↑q`, the continued fraction of `q` and `v` coincide.
In particular, we show that
```lean
(↑(generalized_continued_fraction.of q : generalized_continued_fraction ℚ)
: generalized_continued_fraction K)
= generalized_continued_fraction.of v`
```
in `generalized_continued_fraction.coe_of_rat`.
To do this, we proceed bottom-up, showing the correspondence between the basic functions involved in
the computation first and then lift the results step-by-step.
-/
/- The lifting works for arbitrary linear ordered fields with a floor function. -/
variables {v : K} {q : ℚ} (v_eq_q : v = (↑q : K)) (n : ℕ)
include v_eq_q
/-! First, we show the correspondence for the very basic functions in
`generalized_continued_fraction.int_fract_pair`. -/
namespace int_fract_pair
lemma coe_of_rat_eq :
((int_fract_pair.of q).mapFr coe : int_fract_pair K) = int_fract_pair.of v :=
by simp [int_fract_pair.of, v_eq_q]
lemma coe_stream_nth_rat_eq :
((int_fract_pair.stream q n).map (mapFr coe) : option $ int_fract_pair K)
= int_fract_pair.stream v n :=
begin
induction n with n IH,
case nat.zero : { simp [int_fract_pair.stream, (coe_of_rat_eq v_eq_q)] },
case nat.succ :
{ rw v_eq_q at IH,
cases stream_q_nth_eq : (int_fract_pair.stream q n) with ifp_n,
case option.none : { simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq] },
case option.some :
{ cases ifp_n with b fr,
cases decidable.em (fr = 0) with fr_zero fr_ne_zero,
{ simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq, fr_zero] },
{ replace IH : some (int_fract_pair.mk b ↑fr) = int_fract_pair.stream ↑q n, by
rwa [stream_q_nth_eq] at IH,
have : (fr : K)⁻¹ = ((fr⁻¹ : ℚ) : K), by norm_cast,
have coe_of_fr := (coe_of_rat_eq this),
simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq, fr_ne_zero],
unfold_coes,
simpa [coe_of_fr] } } }
end
lemma coe_stream_rat_eq :
((int_fract_pair.stream q).map (option.map (mapFr coe)) : stream $ option $ int_fract_pair K) =
int_fract_pair.stream v :=
by { funext n, exact (int_fract_pair.coe_stream_nth_rat_eq v_eq_q n) }
end int_fract_pair
/-! Now we lift the coercion results to the continued fraction computation. -/
lemma coe_of_h_rat_eq : (↑((of q).h : ℚ) : K) = (of v).h :=
begin
unfold of int_fract_pair.seq1,
rw ←(int_fract_pair.coe_of_rat_eq v_eq_q),
simp
end
lemma coe_of_s_nth_rat_eq :
(((of q).s.nth n).map (pair.map coe) : option $ pair K) = (of v).s.nth n :=
begin
simp only [of, int_fract_pair.seq1, seq.map_nth, seq.nth_tail],
simp only [seq.nth],
rw [←(int_fract_pair.coe_stream_rat_eq v_eq_q)],
rcases succ_nth_stream_eq : (int_fract_pair.stream q (n + 1)) with _ | ⟨_, _⟩;
simp [stream.map, stream.nth, succ_nth_stream_eq]
end
lemma coe_of_s_rat_eq : (((of q).s).map (pair.map coe) : seq $ pair K) = (of v).s :=
by { ext n, rw ←(coe_of_s_nth_rat_eq v_eq_q), refl }
/-- Given `(v : K), (q : ℚ), and v = q`, we have that `gcf.of q = gcf.of v` -/
lemma coe_of_rat_eq :
(⟨(of q).h, (of q).s.map (pair.map coe)⟩ : generalized_continued_fraction K) = of v :=
begin
cases gcf_v_eq : (of v) with h s, subst v,
obtain rfl : ↑⌊↑q⌋ = h, by { injection gcf_v_eq },
simp [coe_of_h_rat_eq rfl, coe_of_s_rat_eq rfl, gcf_v_eq]
end
lemma of_terminates_iff_of_rat_terminates {v : K} {q : ℚ} (v_eq_q : v = (q : K)) :
(of v).terminates ↔ (of q).terminates :=
begin
split;
intro h;
cases h with n h;
use n;
simp only [seq.terminated_at, (coe_of_s_nth_rat_eq v_eq_q n).symm] at h ⊢;
cases ((of q).s.nth n);
trivial
end
end rat_translation
section terminates_of_rat
/-!
### Continued Fractions of Rationals Terminate
Finally, we show that the continued fraction of a rational number terminates.
The crucial insight is that, given any `q : ℚ` with `0 < q < 1`, the numerator of `int.fract q` is
smaller than the numerator of `q`. As the continued fraction computation recursively operates on
the fractional part of a value `v` and `0 ≤ int.fract v < 1`, we infer that the numerator of the
fractional part in the computation decreases by at least one in each step. As `0 ≤ int.fract v`,
this process must stop after finite number of steps, and the computation hence terminates.
-/
namespace int_fract_pair
variables {q : ℚ} {n : ℕ}
/--
Shows that for any `q : ℚ` with `0 < q < 1`, the numerator of the fractional part of
`int_fract_pair.of q⁻¹` is smaller than the numerator of `q`.
-/
/-- Shows that the sequence of numerators of the fractional parts of the stream is strictly
antitone. -/
lemma stream_succ_nth_fr_num_lt_nth_fr_num_rat {ifp_n ifp_succ_n : int_fract_pair ℚ}
(stream_nth_eq : int_fract_pair.stream q n = some ifp_n)
(stream_succ_nth_eq : int_fract_pair.stream q (n + 1) = some ifp_succ_n) :
ifp_succ_n.fr.num < ifp_n.fr.num :=
begin
obtain ⟨ifp_n', stream_nth_eq', ifp_n_fract_ne_zero, int_fract_pair.of_eq_ifp_succ_n⟩ :
∃ ifp_n', int_fract_pair.stream q n = some ifp_n' ∧ ifp_n'.fr ≠ 0
∧ int_fract_pair.of ifp_n'.fr⁻¹ = ifp_succ_n, from
succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq,
have : ifp_n = ifp_n', by injection (eq.trans stream_nth_eq.symm stream_nth_eq'),
cases this,
rw [←int_fract_pair.of_eq_ifp_succ_n],
cases (nth_stream_fr_nonneg_lt_one stream_nth_eq) with zero_le_ifp_n_fract ifp_n_fract_lt_one,
have : 0 < ifp_n.fr, from (lt_of_le_of_ne zero_le_ifp_n_fract $ ifp_n_fract_ne_zero.symm),
exact (of_inv_fr_num_lt_num_of_pos this)
end
lemma stream_nth_fr_num_le_fr_num_sub_n_rat : ∀ {ifp_n : int_fract_pair ℚ},
int_fract_pair.stream q n = some ifp_n → ifp_n.fr.num ≤ (int_fract_pair.of q).fr.num - n :=
begin
induction n with n IH,
case nat.zero
{ assume ifp_zero stream_zero_eq,
have : int_fract_pair.of q = ifp_zero, by injection stream_zero_eq,
simp [le_refl, this.symm] },
case nat.succ
{ assume ifp_succ_n stream_succ_nth_eq,
suffices : ifp_succ_n.fr.num + 1 ≤ (int_fract_pair.of q).fr.num - n, by
{ rw [int.coe_nat_succ, sub_add_eq_sub_sub],
solve_by_elim [le_sub_right_of_add_le] },
rcases (succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq) with
⟨ifp_n, stream_nth_eq, -⟩,
have : ifp_succ_n.fr.num < ifp_n.fr.num, from
stream_succ_nth_fr_num_lt_nth_fr_num_rat stream_nth_eq stream_succ_nth_eq,
have : ifp_succ_n.fr.num + 1 ≤ ifp_n.fr.num, from int.add_one_le_of_lt this,
exact (le_trans this (IH stream_nth_eq)) }
end
lemma exists_nth_stream_eq_none_of_rat (q : ℚ) : ∃ (n : ℕ), int_fract_pair.stream q n = none :=
begin
let fract_q_num := (int.fract q).num, let n := fract_q_num.nat_abs + 1,
cases stream_nth_eq : (int_fract_pair.stream q n) with ifp,
{ use n, exact stream_nth_eq },
{ -- arrive at a contradiction since the numerator decreased num + 1 times but every fractional
-- value is nonnegative.
have ifp_fr_num_le_q_fr_num_sub_n : ifp.fr.num ≤ fract_q_num - n, from
stream_nth_fr_num_le_fr_num_sub_n_rat stream_nth_eq,
have : fract_q_num - n = -1, by
{ have : 0 ≤ fract_q_num, from rat.num_nonneg_iff_zero_le.elim_right (int.fract_nonneg q),
simp [(int.nat_abs_of_nonneg this), sub_add_eq_sub_sub_swap, sub_right_comm] },
have : ifp.fr.num ≤ -1, by rwa this at ifp_fr_num_le_q_fr_num_sub_n,
have : 0 ≤ ifp.fr, from (nth_stream_fr_nonneg_lt_one stream_nth_eq).left,
have : 0 ≤ ifp.fr.num, from rat.num_nonneg_iff_zero_le.elim_right this,
linarith }
end
end int_fract_pair
/-- The continued fraction of a rational number terminates. -/
theorem terminates_of_rat (q : ℚ) : (of q).terminates :=
exists.elim (int_fract_pair.exists_nth_stream_eq_none_of_rat q)
( assume n stream_nth_eq_none,
exists.intro n
( have int_fract_pair.stream q (n + 1) = none, from
int_fract_pair.stream_is_seq q stream_nth_eq_none,
(of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none.elim_right this) ) )
end terminates_of_rat
/--
The continued fraction `generalized_continued_fraction.of v` terminates if and only if `v ∈ ℚ`.
-/
theorem terminates_iff_rat (v : K) : (of v).terminates ↔ ∃ (q : ℚ), v = (q : K) :=
iff.intro
( assume terminates_v : (of v).terminates,
show ∃ (q : ℚ), v = (q : K), from exists_rat_eq_of_terminates terminates_v )
( assume exists_q_eq_v : ∃ (q : ℚ), v = (↑q : K),
exists.elim exists_q_eq_v
( assume q,
assume v_eq_q : v = ↑q,
have (of q).terminates, from terminates_of_rat q,
(of_terminates_iff_of_rat_terminates v_eq_q).elim_right this ) )
end generalized_continued_fraction
|
------------------------------------------------------------------------
-- The Agda standard library
--
-- Showing natural numbers
------------------------------------------------------------------------
{-# OPTIONS --without-K --safe #-}
module Data.Nat.Show where
open import Data.Nat
open import Relation.Nullary.Decidable using (True)
open import Data.String.Base as String using (String)
open import Data.Digit
open import Data.Product using (proj₁)
open import Function
open import Data.List.Base
-- showInBase b n is a string containing the representation of n in
-- base b.
showInBase : (base : ℕ)
{base≥2 : True (2 ≤? base)}
{base≤16 : True (base ≤? 16)} →
ℕ → String
showInBase base {base≥2} {base≤16} n =
String.fromList $
map (showDigit {base≤16 = base≤16}) $
reverse $
proj₁ $ toDigits base {base≥2 = base≥2} n
-- show n is a string containing the decimal expansion of n (starting
-- with the most significant digit).
show : ℕ → String
show = showInBase 10
|
[STATEMENT]
lemma diamond_lower_bound_left:
"|x>(d(y) * d(z)) \<le> |x>d(z)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. | x > (d y * d z) \<le> | x > d z
[PROOF STEP]
using diamond_lower_bound_right d_commutative
[PROOF STATE]
proof (prove)
using this:
| ?x > (d ?y * d ?z) \<le> | ?x > d ?y
d ?x * d ?y = d ?y * d ?x
goal (1 subgoal):
1. | x > (d y * d z) \<le> | x > d z
[PROOF STEP]
by force |
module fcvode_extras
implicit none
contains
integer(c_int) function RhsFnReal(tn, yvec, fvec, rpar, neq) &
result(ierr) bind(C,name='RhsFnReal')
use, intrinsic :: iso_c_binding
implicit none
real(c_double), value :: tn
integer(c_int), value :: neq
! type(c_ptr), value :: sunvec_y
! type(c_ptr), value :: sunvec_f
! type(c_ptr), value :: user_data
! pointers to data in SUNDAILS vectors
real(c_double) :: yvec(neq)
real(c_double) :: fvec(neq)
real(c_double), intent(inout) :: rpar(neq*4)
real(c_double) :: energy(neq)
! print*, "r1", rpar(1)
! print*, "r2", rpar(2)
! print*, rpar(3)
! print*, rpar(4)
call f_rhs(neq, tn, yvec, fvec, rpar, 0)
! print*, "after r1", rpar(1)
! print*, "after r2", rpar(2)
! print*, "after r3", rpar(3)
! print*, "after r4", rpar(4)
ierr = 0
end function RhsFnReal
end module fcvode_extras
|
type $ClassA <class {@e1 i32, @e2 f32, @e3 f64}>
type $ClassB <class {@e1 i32}>
func $foo() void {
var %Reg1 <* <$ClassB>>
dassign %Reg1 0 (intrinsicopwithtype ptr <* <$ClassB>> DEX_CONST_CLASS ())
intrinsiccallwithtype <* <$ClassA>> DEX_CHECK_CAST (dread ptr %Reg1 0)
}
|
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE BangPatterns #-}
module Numeric.MCMC.RiemannianLangevin (
MarkovChain(..)
, Options, createOptions
, runChain, localMean, perturb
) where
import Numeric.MCMC.Langevin hiding (Options, runChain)
import Numeric.LinearAlgebra
import Control.Arrow
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.Reader
import System.Random.MWC
import System.Random.MWC.Distributions
-- | Options for the chain. The target (expected to be a log density), the
-- right matrix product of its curvature and gradient, the inverse Fisher metric tensor,
-- its (Cholesky) square root, and the step size.
data Options = Options {
_target :: [Double] -> Double -- Target (log density)
, _curvatureXgradient :: [Double] -> [Double] -- Curvature right-multiplied by gradient
, _invFisherMetric :: [Double] -> Matrix Double -- Inverse Fisher metric tensor
, _sqrtInvFisherMetric :: [Double] -> Matrix Double -- Square root of the tensor
, _eps :: {-# UNPACK #-} !Double -- Step size
}
-- | A result with this type has a view of the chain options.
type ViewsOptions = ReaderT Options
-- | Construct Options (data constructor not exported).
-- FIXME sqrtm is not converging; alternatives?
createOptions :: ([Double] -> Double) -- Target (log density)
-> ([Double] -> [Double]) -- Gradient
-> ([Double] -> [[Double]]) -- Hessian
-> Double -- Step size
-> Options -- Options
createOptions t g h =
Options t curvatureXgradient invFisherMetric sqrtInvFisherMetric
where curvatureXgradient xs =
let mat = invFisherMetric xs <> fromColumns [fromList (g xs)]
in concat . toLists . trans $ mat
invFisherMetric = pinv . fromRows . map (fromList . map (* (-1))) . h
sqrtInvFisherMetric x = let z = schur (invFisherMetric x)
in fst z <> sqrtm (snd z) <> trans (fst z)
{-# INLINE createOptions #-}
-- | Non-isotropic Gaussian density.
nonIsoGauss :: [Double] -> [Double] -> Matrix Double -> Double
nonIsoGauss xs mu sig = exp val
where val = -0.5*p*log (2*pi) - 0.5*ldet - 0.5*
(trans (xsM `sub` muM) <> invSig <> (xsM `sub` muM)) @@> (0, 0)
(xsM, muM) = (\f (a, b) -> (f a, f b)) (\l -> fromColumns [fromList l]) (xs, mu)
p = fromIntegral $ cols sig
(invSig, (ldet, _)) = invlndet sig
{-# INLINE nonIsoGauss #-}
-- | Mean function for the discretized Riemannian Langevin diffusion.
localMean :: Monad m
=> [Double] -- Current state
-> ViewsOptions m [Double] -- Localized mean of proposal distribution
localMean t = do
Options _ c _ _ e <- ask
return $! zipWith (+) t (map (* (0.5 * e^(2 :: Int))) (c t))
{-# INLINE localMean #-}
-- | Perturb the state, creating a new proposal.
perturb :: PrimMonad m
=> [Double] -- Current state
-> Gen (PrimState m) -- MWC PRNG
-> ViewsOptions m [Double] -- Resulting perturbation.
perturb t g = do
Options _ _ _ s _ <- ask
zs <- replicateM (length t) (lift $ standard g)
t0 <- localMean t
let adjustedBrownianMotion = s t <> fromColumns [fromList zs]
abmList = concat . toLists . trans $ adjustedBrownianMotion
perturbedState = zipWith (+) t0 t1
t1 = map (* eps) abmList
return $! perturbedState
{-# INLINE perturb #-}
-- | Perform a Metropolis accept/reject step.
metropolisStep :: PrimMonad m
=> MarkovChain -- Current state
-> Gen (PrimState m) -- MWC PRNG
-> ViewsOptions m MarkovChain -- New state
metropolisStep state g = do
Options target _ iF _ e <- ask
let (t0, nacc) = (theta &&& accepts) state
zc <- lift $ uniformR (0, 1) g
proposal <- perturb t0 g
t0Mean <- localMean t0
proposalMean <- localMean proposal
let mc = if zc < acceptProb
then (proposal, 1)
else (t0, 0)
acceptProb = if isNaN val then 1 else val where val = arRatio
arRatio = exp . min 0 $
target proposal + log (nonIsoGauss proposal t0Mean ((e^(2::Int)) `scale` iF t0))
- target t0 - log (nonIsoGauss t0 proposalMean ((e^(2::Int)) `scale` iF proposal))
return $! MarkovChain (fst mc) (nacc + snd mc)
{-# INLINE metropolisStep #-}
-- | Diffuse through states.
runChain :: Options -- Options of the Markov chain.
-> Int -- Number of epochs to iterate the chain.
-> Int -- Print every nth iteration
-> MarkovChain -- Initial state of the Markov chain.
-> Gen RealWorld -- MWC PRNG
-> IO MarkovChain -- End state of the Markov chain, wrapped in IO.
runChain = go
where go o n t !c g | n == 0 = return c
| n `rem` t /= 0 = do
r <- runReaderT (metropolisStep c g) o
go o (n - 1) t r g
| otherwise = do
r <- runReaderT (metropolisStep c g) o
print r
go o (n - 1) t r g
{-# INLINE runChain #-}
|
-- %language FirstClassReflection
-- %default total
%reflection
ups : Nat -> Nat
ups (S k) = k
|
import Mathlib.Algebra.Group.Defs
import Mathlib.Init.Algebra.Order
import ECTate.Algebra.Ring.Basic
import Mathlib.Init.Data.Nat.Lemmas
import ECTate.Init.Data.Int.Lemmas
import ECTate.Data.Nat.Enat
import ECTate.Algebra.EllipticCurve.Kronecker
import Mathlib.Tactic.LibrarySearch
import Mathlib.Tactic.Ring
import Mathlib.Tactic.Convert
import Mathlib.Data.Nat.Prime
import Mathlib.Data.Int.GCD
--class ValueMonoid (A : Type u) extends AddCommMonoid A, LinearOrder A
open Enat
section Obvious
lemma match_non_zero (x : ℕ∪∞) {c1 c2 : β} : x ≠ 0 → (match x with | 0 => c1 | _ => c2) = c2 := by
intro h
match x with
| ofN 0 => exact False.elim (h (Eq.refl 0))
| ∞ => simp
| ofN (_ + 1) => simp
theorem nat_mul_left_cancel (a b c : Nat) (h : a ≠ 0) : a * b = a * c → b = c :=
Nat.eq_of_mul_eq_mul_left (Nat.pos_of_ne_zero h)
end Obvious
@[ext]
structure SurjVal {R : Type u} (p : R) [CommRing R] [IsDomain R] where
v : R → ℕ∪∞
v_uniformizer' : v p = 1
v_mul_eq_add_v' (a b : R) : v (a * b) = v a + v b
v_add_ge_min_v' (a b : R) : v (a + b) ≥ min (v a) (v b)
v_eq_top_iff_zero' (a : R) : v a = ∞ ↔ a = 0
instance {R : Type u} (p : R) [CommRing R] [IsDomain R] : FunLike (SurjVal p) R (λ _ => ℕ∪∞) :=
{ coe := SurjVal.v
coe_injective' := by
intro x y h
ext :1
assumption }
instance {R : Type u} (p : R) [CommRing R] [IsDomain R] : CoeFun (SurjVal p) (λ _ => R → ℕ∪∞) := ⟨SurjVal.v⟩
namespace SurjVal
variable {R : Type u} {p : R} [CommRing R] [IsDomain R] (v : SurjVal p)
-- TODO make naming consistent
@[simp]
theorem v_uniformizer : v p = 1 := v.v_uniformizer'
@[simp]
theorem v_mul_eq_add_v (a b : R) : v (a * b) = v a + v b := v.v_mul_eq_add_v' a b
theorem v_add_ge_min_v (a b : R) : v (a + b) ≥ min (v a) (v b) := v.v_add_ge_min_v' a b
@[simp]
theorem v_eq_top_iff_zero (a : R) : v a = ∞ ↔ a = 0 := v.v_eq_top_iff_zero' a
end SurjVal
variable {R : Type u} [CommRing R] [IsDomain R]
namespace SurjVal
-- TODO namespace these
lemma p_non_zero {p : R} (nav : SurjVal p) : ¬p = 0 := by
rw [←nav.v_eq_top_iff_zero, nav.v_uniformizer]
simp
@[simp]
lemma val_zero {p : R} (nav : SurjVal p) : nav 0 = ∞ := (nav.v_eq_top_iff_zero 0).2 rfl
lemma val_mul_ge_left {p : R} (nav : SurjVal p) (a b : R) : nav (a * b) ≥ nav a :=
le_trans (le_add_right (nav a) (nav b)) (le_of_eq (nav.v_mul_eq_add_v a b).symm)
lemma val_mul_ge_right {p : R} (nav : SurjVal p) (a b : R) : nav (a * b) ≥ nav b := by
rw [mul_comm]
exact val_mul_ge_left nav b a
lemma val_mul_ge_of_left_ge {p : R} (nav : SurjVal p) {a b : R} (ha : nav a ≥ n) :
nav (a * b) ≥ n :=
le_trans ha (val_mul_ge_left nav a b)
lemma val_mul_ge_of_right_ge {p : R} (nav : SurjVal p) {a b : R} (hb : nav b ≥ n) :
nav (a * b) ≥ n :=
le_trans hb (val_mul_ge_right nav a b)
lemma val_mul_ge_of_both_ge {p : R} (nav : SurjVal p) {a b : R} (ha : nav a ≥ m) (hb : nav b ≥ n) :
nav (a * b) ≥ m + n := by
rw [nav.v_mul_eq_add_v]
exact add_le_add ha hb
@[simp]
lemma val_of_one {p : R} (nav : SurjVal p) : nav 1 = 0 := by
apply Enat.add_right_cancel_ofN 1
simp only [Nat.cast_one, zero_add]
rw [←SurjVal.v_uniformizer nav, ←SurjVal.v_mul_eq_add_v nav, one_mul]
lemma val_pow_ge_of_ge {p : R} (nav : SurjVal p) {a : R} (k : ℕ) (ha : nav a ≥ m) :
nav (a ^ k) ≥ k • m := by
induction k with
| zero => simp [zero_nsmul]
| succ k ih =>
simp only [succ_nsmul, pow_succ]
apply val_mul_ge_of_both_ge _ ha ih
lemma val_pow_eq_of_eq {p : R} (nav : SurjVal p) {a : R} (k : ℕ) (ha : nav a = m) :
nav (a ^ k) = k * m := by
induction k with
| zero => simp
| succ k ih =>
simp only [pow_succ, Nat.cast_succ, add_mul, one_mul, add_comm]
rw [nav.v_mul_eq_add_v, ha, ih]
@[simp]
lemma val_pow_eq {p : R} (nav : SurjVal p) {a : R} (k : ℕ) :
nav (a ^ k) = k * nav a := val_pow_eq_of_eq nav k rfl
lemma val_add_ge_of_ge {p : R} (nav : SurjVal p) {a b : R} (ha : nav a ≥ n) (hb : nav b ≥ n) :
nav (a + b) ≥ n := le_trans (le_min ha hb) (nav.v_add_ge_min_v a b)
def nat_of_val {p : R} (nav : SurjVal p) {a : R} (h : a ≠ 0) : ℕ :=
to_nat ((not_iff_not.2 (nav.v_eq_top_iff_zero a)).2 h)
/-
lemma val_of_add_one {p : R} (nav : SurjVal p) (h : nav x ≥ 1): nav (x + 1) = 0 := by
apply le_antisymm
. apply le_of_not_lt
intro h'
sorry
. apply le_trans _ (nav.v_add_ge_min_v x 1)
apply le_min (le_trans (le_succ 0) h) (le_of_eq (val_of_one nav).symm)
-/
lemma val_of_minus_one {p : R} (nav : SurjVal p) : nav (-1) = 0 := by
cases Enat.eq_zero_or_pos (nav (-1)) with
| inl h => exact h
| inr h =>
have contradiction : nav 1 > 0 := by
rw [←neg_neg 1, ←one_mul 1, neg_mul_eq_neg_mul, neg_mul_eq_mul_neg, nav.v_mul_eq_add_v]
apply Enat.lt_add_right _ _ _ h
rw [val_of_one] at contradiction
exact False.elim ((lt_irrefl 0) contradiction)
@[simp]
lemma val_neg {p : R} (nav : SurjVal p) : nav (-x) = nav x := by
rw [←one_mul x, neg_mul_eq_neg_mul, nav.v_mul_eq_add_v, val_of_minus_one, one_mul, zero_add]
theorem v_sub_ge_min_v (nav : SurjVal p) (a b : R) : nav (a - b) ≥ min (nav a) (nav b) := by
rw [sub_eq_add_neg]
convert nav.v_add_ge_min_v a (-b) using 2
simp
lemma val_sub_ge_of_ge {p : R} (nav : SurjVal p) {a b : R} (ha : nav a ≥ n) (hb : nav b ≥ n) :
nav (a - b) ≥ n := by
rw [sub_eq_add_neg]
apply val_add_ge_of_ge
assumption
simpa
theorem v_add_eq_min_v {p : R} (nav : SurjVal p) {a b : R} (h : nav a < nav b) :
nav (a + b) = nav a := by
apply le_antisymm
. apply le_of_not_lt
intro h'
have hm : nav a < nav (-b) := by rwa [val_neg]
apply lt_irrefl (nav a)
apply lt_of_lt_of_le (lt_min h' hm)
rw [(show nav a = nav (a + b + -b) by simp)]
exact nav.v_add_ge_min_v (a + b) (-b)
. exact le_trans (le_min (le_of_eq rfl) (le_of_lt h)) (SurjVal.v_add_ge_min_v nav a b)
theorem val_of_pow_uniformizer {p : R} (nav : SurjVal p) {n : ℕ} : nav (p ^ n) = n := by
induction n with
| zero =>
rw [pow_zero]
exact val_of_one nav
| succ n ih =>
rw [pow_succ, SurjVal.v_mul_eq_add_v nav, ih, SurjVal.v_uniformizer nav]
simp [Nat.succ_eq_add_one, add_comm]
end SurjVal
structure EnatValRing {R : Type u} (p : R) [CommRing R] [IsDomain R] where
valtn : SurjVal p
decr_val : R → R
/-- reduce the element x by valuation n (by dividing by an appropriate power of the uniformizer) -/
sub_val : ℕ → R → R := Nat.iterate decr_val
sub_val_eq : sub_val = Nat.iterate decr_val := by rfl
zero_valtn_decr {x : R} (h : valtn x = 0) : decr_val x = x
pos_valtn_decr {x : R} (h : valtn x > 0) : x = p * decr_val x -- TODO remove
residue_char : ℕ
norm_repr : R → R --generalization of modulo
norm_repr_spec : ∀ r, valtn (r - norm_repr r) > 0
inv_mod : R → R
inv_mod_spec : ∀ r, valtn r = 0 → valtn (r * inv_mod r - 1) > 0
inv_mod_spec' : ∀ r, valtn r > 0 → valtn (inv_mod r) > 0
inv_mod_spec'' : ∀ r s, valtn (r - s) > 0 → inv_mod r = inv_mod s
pth_root : R → R
pth_root_spec : residue_char = 0 ∨ ∀ r, valtn (pth_root r ^ residue_char - r) > 0
count_roots_cubic : (a b c d : R) → Nat
-- count_roots_cubic_spec : ∀ (a b c d : R), exists a smallest finset of elts solving
quad_roots_in_residue_field : R → R → R → Bool
namespace EnatValRing
open SurjVal
@[simp]
lemma decr_val_zero {p : R} (evr : EnatValRing p) : evr.decr_val 0 = 0 := by
have v_decr_zero : p * evr.decr_val 0 = 0 := by
apply Eq.symm
apply evr.pos_valtn_decr
rw [val_zero]
exact Enat.lt_top 0
rw [mul_eq_zero] at v_decr_zero
exact Or.resolve_left v_decr_zero (p_non_zero evr.valtn)
@[simp]
lemma decr_val_neg {p : R} (evr : EnatValRing p) (x : R) : evr.decr_val (-x) = -evr.decr_val x := by
cases @eq_zero_or_pos _ _ (evr.valtn x) with
| inl h =>
have hm : evr.valtn (-x) = 0 := by simp [h]
rw [evr.zero_valtn_decr h, evr.zero_valtn_decr hm]
| inr h =>
have hm : evr.valtn (-x) > 0 := by simp [h]
apply nzero_mul_left_cancel p _ _ (p_non_zero evr.valtn)
rw [←neg_mul_eq_mul_neg, ←evr.pos_valtn_decr h, ←evr.pos_valtn_decr hm]
@[simp]
lemma decr_val_p_mul {p : R} (evr : EnatValRing p) (x : R) : evr.decr_val (p * x) = x := by
have h : (p * x) = p * decr_val evr (p * x) := by
apply evr.pos_valtn_decr
rw [evr.valtn.v_mul_eq_add_v, evr.valtn.v_uniformizer]
rw [add_comm, ← Enat.succ_eq_add_one]
apply Enat.succ_pos
apply nzero_mul_left_cancel p _ _ (p_non_zero evr.valtn)
exact h.symm
@[simp]
lemma sub_val_zero_n {p : R} (evr : EnatValRing p) (n : ℕ) : sub_val evr n 0 = 0 := by
induction n with
| zero => simp [sub_val_eq]
| succ n ih => simpa [sub_val_eq, decr_val_zero] using ih
@[simp]
lemma sub_val_x_zero {p : R} (evr : EnatValRing p) (x : R) : sub_val evr 0 x = x := by simp [sub_val_eq]
lemma sub_val_val_zero {p : R} (evr : EnatValRing p) (x : R) (m : ℕ) (h : evr.valtn x = 0) :
sub_val evr m x = x := by
induction m with
| zero => exact sub_val_x_zero evr x
| succ m ih => simpa [sub_val_eq, zero_valtn_decr _ h] using ih
lemma sub_val_val_pos_succ {p : R} (evr : EnatValRing p) (x : R) (m : ℕ) :
sub_val evr (Nat.succ m) x = sub_val evr m (evr.decr_val x) := by
simp [sub_val_eq]
lemma val_decr_val {p : R} (evr : EnatValRing p) {m : Nat} (x : R) (h : evr.valtn x = m) :
evr.valtn (evr.decr_val x) = ↑(m - 1) := by
cases m with
| zero => rwa [evr.zero_valtn_decr h]
| succ m =>
have x_pos_val : evr.valtn x > 0 := by
rw [h]
exact succ_pos m
apply add_right_cancel_ofN 1
simp at * -- TODO fix nonterminal
rw [←evr.valtn.v_uniformizer, ←evr.valtn.v_mul_eq_add_v, mul_comm,
←evr.pos_valtn_decr x_pos_val, h, evr.valtn.v_uniformizer]
lemma sub_val_decr_val_comm {p : R} (evr : EnatValRing p) (x : R) (n : ℕ) :
sub_val evr n (evr.decr_val x) = evr.decr_val (sub_val evr n x) := by
simp [sub_val_eq]
rw [← Function.iterate_succ_apply' evr.decr_val]
rw [← Function.iterate_succ_apply evr.decr_val]
lemma val_sub_val_eq {p : R} (evr : EnatValRing p) (x : R) {m : ℕ} (n : ℕ) (h : evr.valtn x = m) :
evr.valtn (sub_val evr n x) = ↑(m - n) := by
induction n with
| zero => rwa [sub_val_x_zero, Nat.sub_zero]
| succ n ih =>
cases m with
| zero =>
rw [Nat.zero_sub] at ih
rw [Nat.zero_sub, sub_val_val_zero evr x n.succ h]
exact h
| succ m =>
rw [sub_val_val_pos_succ, sub_val_decr_val_comm, val_decr_val evr (sub_val evr n x) ih,
Nat.succ_eq_add_one n, Nat.sub_sub]
lemma val_sub_val_le {p : R} (evr : EnatValRing p) (x : R) {m : ℕ} (n : ℕ) (h : evr.valtn x ≥ m) :
evr.valtn (sub_val evr n x) ≥ ↑(m - n) := by
cases enat_disjunction (evr.valtn x) with
| inl h' =>
have topcase : x = 0 := (evr.valtn.v_eq_top_iff_zero x).1 h'
rw [topcase, sub_val_zero_n, (evr.valtn.v_eq_top_iff_zero 0).2 rfl]
exact le.below_top
| inr h' =>
have H : ∀ (a : ℕ), evr.valtn x = a → evr.valtn (sub_val evr n x) ≥ (m - n) := by
intro a ha
have h'' := val_sub_val_eq evr x n ha
rw [h'']
apply (le_ofN (m - n) (a - n)).2
rw [ha] at h
apply Nat.sub_le_sub_right ((le_ofN m a).1 h)
exact Exists.elim h' H
lemma factor_p_of_le_val {p : R} (evr : EnatValRing p) {x : R} {n : ℕ} (h : evr.valtn x ≥ n) :
x = p ^ n * sub_val evr n x := by
induction n with
| zero => simp [sub_val_eq]
| succ n ih =>
rw [sub_val_val_pos_succ, sub_val_decr_val_comm, pow_succ', mul_assoc]
have pos_val : evr.valtn (sub_val evr n x) > 0 := by
have h' := val_sub_val_le evr x n h
rw [Nat.succ_eq_add_one, Nat.add_sub_self_left] at h'
exact lt_of_succ_le h'
rw [←evr.pos_valtn_decr pos_val]
apply ih
exact le_of_succ_le h
lemma factor_p_of_eq_val {p : R} (evr : EnatValRing p) {x : R} {n : ℕ} (h : evr.valtn x = n) :
x = p ^ n * sub_val evr n x := factor_p_of_le_val evr (le_of_eq (Eq.symm h))
lemma sub_val_p_mul {p : R} (evr : EnatValRing p) (x : R) (n : ℕ) : sub_val evr n (p ^ n * x) = x :=
by
induction n with
| zero =>
rw [pow_zero, one_mul]
exact sub_val_x_zero evr x
| succ n ih =>
rwa [sub_val_val_pos_succ evr, pow_succ, mul_assoc, decr_val_p_mul]
lemma sub_val_neg {p : R} (evr : EnatValRing p) {x : R} {n : ℕ} : sub_val evr n (-x) = -sub_val evr n x := by
induction n with
| zero => simp [sub_val_x_zero]
| succ n ih =>
cases @eq_zero_or_pos _ _ (evr.valtn x) with
| inl h' =>
have h'm : evr.valtn (-x) = 0 := by simp [h']
rw [sub_val_val_zero evr _ _ h', sub_val_val_zero evr _ _ h'm]
| inr h' =>
rw [sub_val_val_pos_succ evr _ _, sub_val_val_pos_succ evr _ _, sub_val_decr_val_comm, ih,
decr_val_neg, sub_val_decr_val_comm]
lemma sub_val_add {p : R} (evr : EnatValRing p) {x y : R} {n : ℕ} (hx : evr.valtn x ≥ n)
(hy : evr.valtn y ≥ n) : sub_val evr n (x + y) = sub_val evr n x + sub_val evr n y := by
apply nzero_mul_left_cancel (p ^ n)
. exact pow_ne_zero n (p_non_zero evr.valtn)
. rw [←factor_p_of_le_val evr (_ : evr.valtn (x + y) ≥ n), mul_add, ←factor_p_of_le_val evr hx, ←factor_p_of_le_val evr hy]
exact le_trans (le_min hx hy) (evr.valtn.v_add_ge_min_v x y)
lemma sub_val_sub {p : R} (evr : EnatValRing p) {x y : R} {n : ℕ} (hx : evr.valtn x ≥ n)
(hy : evr.valtn y ≥ n) : sub_val evr n (x - y) = sub_val evr n x - sub_val evr n y :=
by
rw [sub_eq_add_neg, sub_eq_add_neg, sub_val_add evr hx, sub_val_neg]
simpa
lemma sub_val_mul_left {p : R} (evr : EnatValRing p) {x y : R} {n : ℕ} (hx : evr.valtn x ≥ n) :
sub_val evr n (x * y) = sub_val evr n x * y := by
apply nzero_mul_left_cancel (p ^ n)
. exact pow_ne_zero n (p_non_zero evr.valtn)
. rw [←factor_p_of_le_val evr (_ : evr.valtn (x * y) ≥ n), ←mul_assoc, ←factor_p_of_le_val evr hx]
exact le_trans hx (val_mul_ge_left evr.valtn x y)
lemma sub_val_mul_right {p : R} (evr : EnatValRing p) {x y : R} {n : ℕ} (hy : evr.valtn y ≥ n) :
sub_val evr n (x * y) = x * sub_val evr n y :=
by rw [mul_comm x y, sub_val_mul_left evr hy, mul_comm]
lemma sub_val_mul_sub_val {p : R} (evr : EnatValRing p) {x y : R} (n m : ℕ)
(hx : evr.valtn x ≥ n) (hy : evr.valtn y ≥ m) :
sub_val evr n x * sub_val evr m y = sub_val evr (n + m) (x * y) := by
apply nzero_mul_left_cancel (p ^ (n + m)) _ _ (pow_ne_zero _ (p_non_zero evr.valtn))
rw [←factor_p_of_le_val evr (_ : evr.valtn (x * y) ≥ (n + m)), pow_add, mul_assoc,
mul_comm (p ^ m), ← mul_assoc,
← mul_assoc,
←factor_p_of_le_val evr (_ : evr.valtn x ≥ n), mul_assoc, mul_comm _ (p ^ m),
←factor_p_of_le_val evr (_ : evr.valtn y ≥ m)]
. assumption
. assumption
. rw [SurjVal.v_mul_eq_add_v]
exact add_le_add hx hy
lemma sub_val_mul {p : R} (evr : EnatValRing p) {x y : R} (n m : ℕ) {nm : ℕ} (h : n + m = nm)
(hx : evr.valtn x ≥ n) (hy : evr.valtn y ≥ m) :
sub_val evr nm (x * y) = sub_val evr n x * sub_val evr m y := by
rw [← h, sub_val_mul_sub_val _ _ _ hx hy]
lemma sub_val_pow {p : R} (evr : EnatValRing p) {x : R} (n k : ℕ) {nm : ℕ} (h : k * n = nm)
(hx : evr.valtn x ≥ n) :
sub_val evr nm (x ^ k) = sub_val evr n x ^ k := by
induction k generalizing nm with
| zero => simp [← h]
| succ k ih =>
rw [pow_succ, sub_val_mul _ n (k * n), pow_succ, ← ih]
rfl
rw [← h, Nat.succ_mul, add_comm]
exact hx
convert val_pow_ge_of_ge evr.valtn k hx
exact ofNat_mul_eq_smul k n
lemma sub_val_sub_val {p : R} (evr : EnatValRing p) {x : R} {m n : ℕ} :
sub_val evr n (sub_val evr m x) = sub_val evr (m + n) x := by
have general : ∀ y : R, sub_val evr n (sub_val evr m y) = sub_val evr (m + n) y := by
induction m with
| zero => simp [sub_val_x_zero]
| succ m ih =>
intro y
cases @eq_zero_or_pos _ _ (evr.valtn y) with
| inl h' => simp [sub_val_val_zero evr y _ h']
| inr h' =>
rw [sub_val_val_pos_succ evr y m, Nat.succ_add, sub_val_val_pos_succ evr y _]
exact ih (evr.decr_val y)
exact general x
def has_double_root {p : R} (evr : EnatValRing p) (a b c : R) :=
evr.valtn a = 0 ∧ evr.valtn (b ^ 2 - 4 * a * c) > 0
def double_root {p : R} (evr : EnatValRing p) (a b c : R) :=
if evr.residue_char = 2 then
evr.norm_repr c
else
evr.norm_repr (-b * evr.inv_mod (2 * a))
lemma val_poly_of_double_root {p : R} (evr : EnatValRing p) (a b c : R)
(H : has_double_root evr a b c) :
evr.valtn (a * (double_root evr a b c)^2 + b * (double_root evr a b c) + c) > 0 ∧
evr.valtn (2*a*(double_root evr a b c) + b) > 0 := by sorry
lemma pth_root_pos_of_pos {p : R} (evr : EnatValRing p) (r : R) (ha : 0 < evr.valtn r)
(hchar : evr.residue_char ≠ 0) :
evr.valtn (evr.pth_root r) > 0 :=
by
suffices 0 < evr.valtn (evr.pth_root r ^ evr.residue_char) by
. simp at this
exact this.2
have :
min (SurjVal.v evr.valtn (pth_root evr r ^ evr.residue_char - r)) (SurjVal.v evr.valtn r) > 0 :=
min_rec' (LT.lt 0) (evr.pth_root_spec.resolve_left hchar r) ha -- TODO ew
have := this.trans_le (evr.valtn.v_add_ge_min_v (evr.pth_root r ^ evr.residue_char - r) r)
simpa using this
end EnatValRing
lemma ndiv_mul_left (a b p : ℕ) : (a * b) % p ≠ 0 → a % p ≠ 0 := by
intro hab ha
apply hab
simp [Nat.mul_mod, ha]
lemma ndiv_mul_right (a b p : ℕ) : (a * b) % p ≠ 0 → b % p ≠ 0 := by
rw [Nat.mul_comm]
exact ndiv_mul_left b a p
-- lemma Nat.Prime_test (p : ℕ) : Nat.Prime p ↔ (1 < p ∧ (∀ a b : ℕ, a < p → b < p → (a * b) % p = 0 → a % p = 0 ∨ b % p = 0)) := by
-- apply Iff.intro
-- . intro H
-- apply And.intro (H.left)
-- intro a b _ _
-- apply H.right a b
-- . intro H
-- apply And.intro (H.left)
-- intro a b p_div_ab
-- rw [Nat.mul_mod] at p_div_ab
-- have p_pos : p > 0 := lt_trans Nat.zero_lt_one H.left;
-- have h := H.right (a % p) (b % p) (Nat.mod_lt a p_pos) (Nat.mod_lt b p_pos) p_div_ab;
-- rwa [Nat.mod_mod _ p, Nat.mod_mod _ p] at h
instance : DecidablePred (Nat.Prime . : ℕ → Prop) := Nat.decidablePrime
--match p with
--| 0 => sorry --isFalse (not_and_of_not_left _ (not_lt_of_ge (le_of_lt Nat.zero_lt_one)))
--| 1 => isFalse (not_and_of_not_left _ (not_lt_of_ge (le_of_eq rfl)))
--| Nat.succ (Nat.succ p') => sorry
--def fmul_eq_addf {R R' : Type u} [Mul R] [Add R'] (f : R → R') (x y : R) : Prop := f (x * y) = f x + f y
-- @[extern "blah"]
-- def nat_valuation_aux : ℕ → ℕ → ℕ
-- | _, 0 => 0
-- | 0, (_+1) => 0
-- | 1, (_+1) => 0
-- | (q+2), (m+1) => if (m+1) % (q+2) ≠ 0 then 0 else Nat.succ (nat_valuation_aux (q+2) ((m+1) / (q+2)))
-- termination_by nat_valuation_aux p k => k
-- decreasing_by
-- simp [WellFoundedRelation.rel, measure, invImage, InvImage, Nat.lt_wfRel]
-- exact Nat.div_lt_self (Nat.zero_lt_succ m) (Nat.succ_lt_succ (Nat.zero_lt_succ q))
lemma Nat.div_pos_of_mod {a b : ℕ} (ha : 0 < a) (hb : 1 < b) (hab : a % b = 0) : 0 < a / b :=
Nat.div_pos (Nat.le_of_dvd ha (dvd_of_mod_eq_zero hab)) (lt_of_succ_lt hb)
def nat_valuation_aux'' (q : ℕ) (hq : 1 < q) : (m : ℕ) → 0 < m → ℕ → ℕ
| m, hm, n => if hmq : m % q == 0 then (nat_valuation_aux'' q hq (m / q) (Nat.div_pos_of_mod hm hq (by simpa using hmq)) (n + 1)) else n
decreasing_by
simp [WellFoundedRelation.rel, measure, invImage, InvImage, Nat.lt_wfRel]
exact Nat.div_lt_self hm hq
-- TODO unusedVariable linter fails
lemma nat_valuation_aux''_of_dvd_induction : ∀ (M m : ℕ) (hM : m ≤ M) (hm : 0 < m) (n : ℕ)
(hmq : m % q = 0), ↑(nat_valuation_aux'' q hq m hm n) = succ ↑(nat_valuation_aux'' q hq (m / q)
(Nat.div_pos_of_mod hm hq hmq) n) := by
intro M
induction M with
| zero =>
intro m mle0 hm n hmq
rw [Nat.le_zero] at mle0
exact ((ne_of_gt hm) mle0).elim
| succ M IH =>
intro m m_le_sM hm n hmq
cases LE.le.lt_or_eq m_le_sM with
| inl mltsM =>
exact IH m (Nat.le_of_lt_succ mltsM) hm n hmq
| inr meqsM =>
cases em ((m / q) % q == 0) with
| inl h =>
rw [nat_valuation_aux'', nat_valuation_aux'', dif_pos h]
simp only [beq_iff_eq, succ_ofNat, Nat.cast_succ]
rw [dif_pos hmq]
simp only [meqsM]
rw [meqsM] at hm h hmq
exact IH (M.succ/q) (Nat.le_of_lt_succ (Nat.div_lt_self hm hq))
(Nat.div_pos_of_mod hm hq hmq) (n+1) (by simpa using h)
| inr h =>
rw [nat_valuation_aux'', nat_valuation_aux'', dif_neg h, dif_pos, nat_valuation_aux'', dif_neg h]
. simp
. simp only [hmq]
lemma nat_valuation_aux''_of_dvd (q : ℕ) (hq : 1 < q) (m : ℕ) (hm : 0 < m) (n : ℕ) (hmq : m % q = 0) :
nat_valuation_aux'' q hq m hm n = succ (nat_valuation_aux'' q hq (m / q) (Nat.div_pos_of_mod hm hq hmq) n) :=
nat_valuation_aux''_of_dvd_induction m m (le_refl m) hm n hmq
lemma nat_valuation_aux''_of_not_dvd (q : ℕ) (hq : 1 < q) (m : ℕ) (hm : 0 < m)
(hmq : m % q ≠ 0) : nat_valuation_aux'' q hq m hm 0 = 0 :=
by
have hmq_bool : ¬m % q == 0 := by
intro H
apply hmq (eq_of_beq H)
rw [nat_valuation_aux'', dif_neg hmq_bool]
-- set_option trace.compiler.ir.result true in
def nat_valuation_aux' (q : ℕ) (hq : 1 < q) : (m : ℕ) → 0 < m → ℕ∪∞
| m, hm => nat_valuation_aux'' q hq m hm 0
lemma nat_valuation_aux'_of_not_dvd (q : ℕ) (hq : 1 < q) (m : ℕ) (hm : 0 < m)
(hmq : m % q ≠ 0) : nat_valuation_aux' q hq m hm = 0 :=
by
rw [nat_valuation_aux']
simp [nat_valuation_aux''_of_not_dvd q hq m hm hmq]
lemma nat_valuation_aux'_of_dvd (q : ℕ) (hq : 1 < q) (m : ℕ) (hm : 0 < m)
(hmq : m % q = 0) : nat_valuation_aux' q hq m hm = succ (nat_valuation_aux' q hq (m / q)
(Nat.div_pos_of_mod hm hq hmq)) :=
by
simp [nat_valuation_aux', nat_valuation_aux''_of_dvd q hq m hm 0 hmq]
lemma nat_val_aux'_succ (q m : ℕ) (hq) : nat_valuation_aux' (q+2) hq (m+1) (Nat.zero_lt_succ _) =
if hmq : (m+1) % (q+2) ≠ 0 then 0 else succ (nat_valuation_aux' (q+2) hq ((m+1) / (q+2)) (Nat.div_pos_of_mod (Nat.zero_lt_succ _) hq (not_not.mp hmq))) :=
by
simp only [Nat.succ_ne_zero, dite_false, ne_eq, ite_not]
cases em ((m + 1) % (q + 2) = 0) with
| inl h =>
rw [dif_neg (not_not_intro h)]
exact nat_valuation_aux'_of_dvd _ _ _ _ h
| inr h =>
rw [dif_pos h]
exact nat_valuation_aux'_of_not_dvd _ _ _ _ h
def nat_valuation_aux (q : ℕ) (hq : 1 < q) : ℕ → ℕ∪∞ :=
λ m => if hm : m = 0 then ∞ else nat_valuation_aux' q hq m (Nat.pos_of_ne_zero hm)
@[simp]
lemma nat_val_aux_zero (p : ℕ) (hp) : nat_valuation_aux p hp 0 = ∞ := by
simp [nat_valuation_aux]
lemma x' {a b : Nat} (h : (a+1) % (b+1) = 0) : (a+1) ≥ (b+1) := Nat.le_of_dvd (Nat.succ_pos _) (Nat.dvd_of_mod_eq_zero h)
lemma nat_val_aux_succ (q m : ℕ) (hq) : nat_valuation_aux (q+2) hq (m+1) =
if (m+1) % (q+2) ≠ 0 then 0 else succ (nat_valuation_aux (q+2) hq ((m+1) / (q+2))) := by
simp only [nat_valuation_aux, Nat.succ_ne_zero, dite_false, ne_eq, ite_not]
by_cases hmq : (m + 1) % (q + 2) = 0
. have h : (m + 1) / (q + 2) ≠ 0 := by
apply Nat.ne_of_gt
apply Nat.div_pos (x' hmq) (lt_trans (Nat.lt_succ_self 0) hq)
rw [if_pos hmq, dif_neg h]
exact nat_valuation_aux'_of_dvd (q+2) hq (m+1) _ hmq
. rw [if_neg hmq]
exact nat_valuation_aux'_of_not_dvd (q+2) hq (m+1) _ hmq
/-
def nat_valuation : ℕ → ℕ → ℕ∪∞
| _, 0 => ∞
| 0, (_+1) => 0
| 1, (_+1) => ∞
| (q+2), (m+1) => if (m+1) % (q+2) ≠ 0 then 0 else succ (nat_valuation (q+2) ((m+1) / (q+2)))
termination_by nat_valuation p k => k
decreasing_by
simp [WellFoundedRelation.rel, measure, invImage, InvImage, Nat.lt_wfRel]
exact Nat.div_lt_self (Nat.zero_lt_succ m) (Nat.succ_lt_succ (Nat.zero_lt_succ q))
-/
def nat_valuation : ℕ → ℕ → ℕ∪∞
| _, 0 => ∞
| 0, (_+1) => 0
| 1, (_+1) => ∞
| (q+2), (m+1) => nat_valuation_aux (q+2) (Nat.succ_lt_succ (Nat.zero_lt_succ q)) (m+1)
lemma nat_valuation_add_two (q m : ℕ) :
nat_valuation (q+2) m = nat_valuation_aux (q+2) (Nat.succ_lt_succ (Nat.zero_lt_succ q)) m := by
cases m
. rfl
. simp [nat_valuation]
lemma nat_valuation_of_one_lt (p m : ℕ) (hp : 1 < p) : nat_valuation p m = nat_valuation_aux p hp m :=
by cases p
case zero => cases hp
case succ p =>
cases p
case zero => cases hp.ne rfl
case succ q =>
cases m
. rfl
. simp [nat_valuation]
@[simp]
lemma nat_val_zero (p : ℕ) : nat_valuation p 0 = ∞ := by
simp [nat_valuation]
lemma nat_val_succ (q m : ℕ) : nat_valuation (q+2) (m+1) = if (m+1) % (q+2) ≠ 0 then 0 else succ (nat_valuation (q+2) ((m+1) / (q+2))) :=
by simp [nat_valuation_add_two, nat_val_aux_succ]
namespace Int
def int_val (p : ℕ) (k : ℤ) : ℕ∪∞ :=
nat_valuation p (natAbs k)
@[simp]
lemma int_val_uniformizer {p : ℕ} (gt1 : 1 < p) : int_val p p = 1 := by
simp only [natAbs_cast, int_val]
match p with
| 0 =>
apply False.elim
apply Nat.not_lt_zero 1
assumption
| Nat.succ 0 =>
apply False.elim
apply Nat.lt_irrefl 1
assumption
| q+2 =>
rw [nat_val_succ, Nat.mod_self, if_neg _]
rw [Nat.div_self, nat_val_succ, if_pos, succ_zero]
rw [Nat.mod_eq_of_lt]
exact Nat.succ_ne_zero 0
assumption
exact lt_trans (Nat.lt_succ_self 0) gt1
exact Ne.irrefl
@[simp]
lemma int_val_zero {p : ℕ} : int_val p 0 = ∞ := by simp [natAbs_cast, int_val]
lemma mod_mul (a b c : Nat) (h : a % c = 0) : (a * b) % c = 0 :=
by rw [Nat.mul_mod, h, zero_mul, Nat.zero_mod]
lemma nat_mul_div_assoc' (a b c : Nat) : c > 0 → a % c = 0 → a * b / c = a / c * b := by
intro hc hmod
apply nat_mul_left_cancel c _ _ (ne_of_gt hc)
rw [Nat.mul_div_cancel' (Nat.dvd_of_mod_eq_zero _), ←mul_assoc, Nat.mul_div_cancel' (Nat.dvd_of_mod_eq_zero hmod)]
exact mod_mul a b c hmod
lemma nat_mul_div_assoc (a b c : Nat) : c > 0 → b % c = 0 → a * b / c = a * (b / c) := by
intro hc hmod
rw [mul_comm, nat_mul_div_assoc' b a c hc hmod, mul_comm]
lemma nat_val_aux'_mul_eq_add (p : ℕ) (prime : Nat.Prime p) (hp : 1 < p := prime.one_lt) (a b : ℕ)
(ha : 0 < a) (hb : 0 < b) :
nat_valuation_aux' p hp (a * b) (Nat.mul_pos ha hb) = nat_valuation_aux' p hp a ha + nat_valuation_aux' p hp b hb := by
have general (n : ℕ) : ∀ c d hc hd, c + d ≤ n → nat_valuation_aux' p hp (c * d) (Nat.mul_pos hc hd) = nat_valuation_aux' p hp c hc + nat_valuation_aux' p hp d hd := by
induction n with
| zero =>
intro c d hc hd h_sum
rw [Nat.eq_zero_of_add_eq_zero_right (Nat.eq_zero_of_le_zero h_sum)] at hc
exact (lt_irrefl 0 hc).elim
| succ n ih =>
intro c d hc hd h_sum
cases c with
| zero => cases hc
| succ c => cases d with
| zero => cases hd
| succ d =>
match Nat.le.dest (Nat.succ_le_of_lt prime.one_lt) with
| ⟨q, hq⟩ =>
rw [(show Nat.succ 1 = 2 by rfl), Nat.add_comm] at hq
have mul_s_s : c.succ * d.succ = (c * d + c + d).succ := by simp [Nat.succ_mul, Nat.mul_succ, Nat.add_succ]
simp only [←hq, mul_s_s, nat_valuation_add_two, nat_valuation_aux]
simp only [hq, (show c * d + c + d + 1 = (c + 1) * (d + 1) by ring)]
cases Nat.eq_zero_or_pos ((c + 1) * (d + 1) % p) with
| inl h =>
have hh : (c + 1) % p = 0 ∨(d + 1) % p = 0 := sorry
cases hh with
| inl h' =>
subst hq
rw [nat_valuation_aux'_of_dvd _ _ _ _ h', succ_add]
have sum_le_n : (c + 1) / (q + 2) + (d + 1) ≤ n := by
apply Nat.le_of_lt_succ
apply lt_of_lt_of_le _ h_sum
apply Nat.add_lt_add_right
apply Nat.div_lt_self _ prime.one_lt
rw [Nat.add_comm]
apply Nat.lt_add_right 0 1 c (Nat.lt_succ_self 0)
rw [←ih ((c + 1) / (q + 2)) (d + 1) _ _ sum_le_n]
have hey := nat_mul_div_assoc' (c+1) (d+1) (q+2) (lt_trans (Nat.lt_succ_self 0) prime.one_lt) h'
simp only [hey.symm, mul_s_s.symm]
apply nat_valuation_aux'_of_dvd (q+2) hp ((c+1) * (d+1)) _ h
| inr h' =>
subst hq
rw [nat_valuation_aux'_of_dvd _ _ _ _ h', add_succ]
have sum_le_n : (c + 1) + (d + 1) / (q + 2) ≤ n := by
apply Nat.le_of_lt_succ
apply lt_of_lt_of_le _ h_sum
apply Nat.add_lt_add_left
apply Nat.div_lt_self _ prime.one_lt
rw [Nat.add_comm]
apply Nat.lt_add_right 0 1 d (Nat.lt_succ_self 0)
rw [←ih (c + 1) ((d + 1) / (q + 2)) _ _ sum_le_n]
have hey := nat_mul_div_assoc (c+1) (d+1) (q+2) (lt_trans (Nat.lt_succ_self 0) prime.one_lt) h'
simp only [hey.symm, mul_s_s.symm]
apply nat_valuation_aux'_of_dvd (q+2) hp ((c+1) * (d+1)) _ h
| inr h =>
have hc := ndiv_mul_left _ _ _ (ne_of_gt h)
have hd := ndiv_mul_right _ _ _ (ne_of_gt h)
simp [nat_valuation_aux'_of_not_dvd _ _ _ _ hc, nat_valuation_aux'_of_not_dvd _ _ _ _ hd]
simp [←mul_s_s, nat_valuation_aux'_of_not_dvd _ _ _ _ (ne_of_gt h)]
apply general (a + b) a b ha hb (le_refl _)
lemma nat_val_aux_mul_eq_add (p : ℕ) (prime : Nat.Prime p) (hp : 1 < p := prime.one_lt) (a b : ℕ) :
nat_valuation_aux p hp (a * b) = nat_valuation_aux p hp a + nat_valuation_aux p hp b := by
cases a with
| zero => simp [nat_valuation_aux]
| succ a => cases b with
| zero => simp [nat_valuation_aux]
| succ b =>
exact nat_val_aux'_mul_eq_add p prime prime.one_lt a.succ b.succ _ _
lemma nat_val_mul_eq_add (p : ℕ) (prime : Nat.Prime p) (a b : ℕ) :
nat_valuation p (a * b) = nat_valuation p a + nat_valuation p b := by
convert nat_val_aux_mul_eq_add p prime prime.one_lt a b <;>
ext <;>
rw [(nat_valuation_of_one_lt p _ prime.one_lt)]
lemma int_val_mul_eq_add {p : ℕ} (prime : Nat.Prime p) (a b : ℤ) :
int_val p (a * b) = int_val p a + int_val p b := by
simp [int_val, natAbs_mul]
exact nat_val_mul_eq_add p prime (natAbs a) (natAbs b)
lemma nat_val_add_eq_min (p a b : ℕ) (h : nat_valuation p a < nat_valuation p b) :
nat_valuation p (a + b) = nat_valuation p a := by sorry
lemma nat_val_add_ge_min (p a b : ℕ) : nat_valuation p (a + b) ≥ min (nat_valuation p a) (nat_valuation p b) := by
cases lt_trichotomy (nat_valuation p a) (nat_valuation p b) with -- TODO use rcases
| inl h =>
simp only [min, if_pos (le_of_lt h)]
exact le_of_eq (nat_val_add_eq_min p a b h).symm
| inr h => cases h with
| inl h =>
simp only [min, if_pos (le_of_eq h)]
sorry
| inr h =>
simp only [add_comm a b, min, if_neg (not_le_of_lt h)]
exact le_of_eq (nat_val_add_eq_min p b a h).symm
--lemma natAbs_add (a b : ℤ) : natAbs (a + b) = max (natAbs a) (natAbs b) - min (natAbs a) (natAbs b) := by sorry
lemma natAbs_add (a b : ℤ) : natAbs (a + b) = max (natAbs a) (natAbs b) - min (natAbs a) (natAbs b) := by sorry
lemma int_val_add_ge_min (p : ℕ) (a b : ℤ) : int_val p (a + b) ≥ min (int_val p a) (int_val p b) := by
simp [int_val, natAbs_add]
-- exact nat_val_add_ge_min p (natAbs a) (natAbs b)
sorry
lemma int_val_add_eq_min (p : ℕ) (a b : ℤ) (h : int_val p a < int_val p b) :
int_val p (a + b) = int_val p a := by sorry
@[simp]
lemma int_val_eq_top_iff_zero {p : ℕ} (gt1 : 1 < p) (a : ℤ) : int_val p a = ∞ ↔ a = 0 := by
apply Iff.intro
. intro hval
simp [int_val, nat_valuation] at hval
cases abs_a : (natAbs a) with
| zero => exact natAbs_eq_zero.1 abs_a
| succ n =>
cases hp : p with
| zero =>
rw [hp] at gt1
apply False.elim ((of_decide_eq_true rfl : ¬1 < 0) gt1)
| succ p' =>
cases hp' : p' with
| zero =>
rw [hp, hp'] at gt1
apply False.elim ((of_decide_eq_true rfl : ¬1 < 1) gt1)
| succ n =>
simp [hp, hp', abs_a, nat_valuation_aux, nat_valuation_aux'] at hval
. intro ha
simp [ha, int_val, nat_valuation]
def primeVal {p : ℕ} (hp : Nat.Prime p) : SurjVal (p : ℤ) := {
v := int_val p
v_uniformizer' := int_val_uniformizer hp.one_lt
v_mul_eq_add_v' := int_val_mul_eq_add hp
v_add_ge_min_v' := int_val_add_ge_min p
v_eq_top_iff_zero' := int_val_eq_top_iff_zero hp.one_lt }
def decr_val_p (p : ℕ) (k : ℤ) : ℤ :=
if k % p == 0 then k / p else k
def sub_val_p (p : ℕ) (val : ℤ → ℕ∪∞) (n : ℕ) (k : ℤ) : ℤ :=
k / (p ^ ((min (n : ℕ∪∞) (val k)).to_nat sorry) : ℕ)
@[simp]
lemma nat_valuation_eq_zero_iff {p : ℕ} (hp : 1 < p) {k : ℕ} : nat_valuation p k = 0 ↔ k % p ≠ 0 :=
by
have := nat_val_aux_succ
simp only [nat_valuation, ne_eq]
aesop
-- change (Enat.succ _ = 0) at a -- TODO doesn't work
@[simp]
lemma int_valuation_eq_zero_iff {p : ℕ} {k : ℤ} (hp : 1 < p) : int_val p k = 0 ↔ k % p ≠ 0 :=
by
simp [int_val]
rw [nat_valuation_eq_zero_iff hp]
rw [not_iff_not]
aesop
. cases k
. aesop
exact eq_zero_of_natAbs_eq_zero a
. aesop
rw [← Int.natAbs_eq_zero]
sorry
sorry
@[simp]
lemma primeVal_eq_zero_iff {p : ℕ} {k : ℤ} (hp : Nat.Prime p) : primeVal hp k = 0 ↔ k % p ≠ 0 :=
by rw [primeVal, int_valuation_eq_zero_iff hp.one_lt]
lemma zero_valtn_decr_p {p : ℕ} {k : ℤ} {hp : Nat.Prime p} (h : primeVal hp k = 0) :
decr_val_p p k = k :=
by
simp [decr_val_p] at *
aesop
def norm_repr_p (p : ℕ) (x : ℤ) : ℤ := x % (p : ℤ)
def modulo (x : ℤ) (p : ℕ) := x % (p:ℤ)
def inv_mod (x : ℤ) (p : ℕ) := gcdA x p
def count_roots_cubic_aux (a b c d : ℤ) (p : ℕ) (x : ℕ) : ℕ := match x with
| Nat.zero => if d = 0 then 1 else 0
| Nat.succ x' => (if (a * (x^3 : ℕ) + b * (x^2 : ℕ) + c * x + d) % (p : ℤ) = 0 then 1 else 0) + count_roots_cubic_aux a b c d p x'
def count_roots_cubic (a b c d : ℤ) (p : ℕ) : ℕ :=
count_roots_cubic_aux (modulo a p) (modulo b p) (modulo c p) (modulo d p) p (p - 1)
def primeEVR {p : ℕ} (hp : Nat.Prime p) : EnatValRing (p : ℤ) := {
valtn := primeVal hp
decr_val := decr_val_p p
-- sub_val := sub_val_p p (primeVal hp).v
-- sub_val_eq := sorry
zero_valtn_decr := zero_valtn_decr_p -- todo we really shouldn't need this!
pos_valtn_decr := sorry
residue_char := p
norm_repr := (. % p)
norm_repr_spec := by
intro r
simp [pos_iff_ne_zero, Int.sub_emod]
inv_mod := (inv_mod . p)
inv_mod_spec := by
intro r h
simp [inv_mod, pos_iff_ne_zero, Int.sub_emod]
rw [Int.emod_emod]
rw [Int.emod_emod] -- TODO why doesn't simp do this?
sorry
inv_mod_spec' := sorry
inv_mod_spec'' := sorry
pth_root := id
pth_root_spec := by
right
intro r
simp [inv_mod, pos_iff_ne_zero, Int.sub_emod]
rw [Int.emod_emod]
rw [Int.emod_emod] -- TODO why doesn't simp do this?
rw [←Int.sub_emod]
sorry -- needs fermat's little theorem
count_roots_cubic :=
-- TODO fix this, should we way quicker to count roots, probably in cohen
(Int.count_roots_cubic . . . . p)
-- count_roots_cubic_spec := sorry
quad_roots_in_residue_field := fun a b c => Int.quad_root_in_ZpZ a b c p }
#eval (primeEVR (sorry : Nat.Prime 2)).valtn 4
#eval (primeEVR (sorry : Nat.Prime 2)).norm_repr 4
#eval (primeEVR (sorry : Nat.Prime 2)).decr_val 4
#eval (primeEVR (sorry : Nat.Prime 3)).inv_mod 2
#eval (primeEVR (sorry : Nat.Prime 3)).pth_root 2
#eval (primeEVR (sorry : Nat.Prime 3)).count_roots_cubic 1 0 2 0
#eval (primeEVR (sorry : Nat.Prime 3)).quad_roots_in_residue_field 1 0 1
def has_double_root (a b c : ℤ) {p : ℕ} (hp : Nat.Prime p) :=
let v_p := (primeEVR hp).valtn.v
v_p a = 0 ∧ v_p (b ^ 2 - 4 * a * c) > 0
def double_root (a b c : ℤ) (p : ℕ) :=
-- dbg_trace (a,b,c)
if p = 2 then
modulo c 2
else
modulo (-b * inv_mod (2 * a) p) p
lemma val_poly_of_double_root {p : ℕ} (hp : Nat.Prime p) (a b c : ℤ)
(H : has_double_root a b c hp) :
(primeEVR hp).valtn (a * (double_root a b c p)^2 + b * (double_root a b c p) + c) > 0 ∧
(primeEVR hp).valtn (2*a*(double_root a b c p) + b) > 0 := by sorry
end Int
-- #lint
|
library(shiny)
shinyUI(fluidPage(
titlePanel("Single Cell RNAseq"),
sidebarLayout(
sidebarPanel(
radioButtons(inputId ="Dataset1",
label=h3("Data Set"),choices=as.list(samples),
selected=samples[1]),
textInput(inputId ="text", label = h3("Input Gene Name"), value = "Enter SINGLE gene only..."),
actionButton(inputId = "update", "Update Plot !"),
p("Click the above button to Update Plot After Input Gene Name (Required), e.g. CD8A (Human), Cd8a (Mouse)"),
textInput(inputId ="threshold", label = h3("low expression threshold"), value = 0),
selectInput(inputId ="Color1",
label=h3("Select a Color for high expression"),choices=list("red", "blue", "green", "purple", "black"),
selected="red"),
selectInput(inputId ="dotsize",
label=h3("Select a dot size"),choices=list(1,2,3,4,5,6,7),
selected=2),
downloadButton('downloadplot', 'Download Plot')
),
# mainPanel(
# plotOutput("distPlot",height = "1000px", width = "1000px")
#)
mainPanel(
fluidRow(
splitLayout(cellWidths = c("100%", "40%"),
plotOutput("distPlot",height = "800px", width = "800px",
hover = "plot_hover",click = "plot_click",
dblclick = "plot_dblclick")
#, plotOutput("distPlot2",height = "700px", width = "700px",hover = "plot_hover2",click = "plot_click2",
# dblclick = "plot_dblclick2",brush = "plot_brush2")
)
#column(6,plotOutput(outputId="distPlot", width="700px",height="700px")),
#column(6,plotOutput(outputId="distPlot2", width="700px",height="700px"))
)
,
fluidRow(
column(6,verbatimTextOutput("info3")),
column(6,verbatimTextOutput("info4"))
#fluidRow(h4("Plot 1 Values Displayed"),verbatimTextOutput("info")),
#fluidRow(h4("Plot 2 Values Displayed"),verbatimTextOutput("info2"))
)
)
)))
|
[STATEMENT]
lemma c_process_prop_1 [simp]: "process_prop_1 (c_failures step out s\<^sub>0, {})"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. process_prop_1 (c_failures step out s\<^sub>0, {})
[PROOF STEP]
proof (simp add: process_prop_1_def)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. ([], {}) \<in> c_failures step out s\<^sub>0
[PROOF STEP]
have "([], {(x, p). p \<noteq> out s\<^sub>0 x}) \<in> c_failures step out s\<^sub>0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ([], {(x, p). p \<noteq> out s\<^sub>0 x}) \<in> c_failures step out s\<^sub>0
[PROOF STEP]
by (rule R0)
[PROOF STATE]
proof (state)
this:
([], {(x, p). p \<noteq> out s\<^sub>0 x}) \<in> c_failures step out s\<^sub>0
goal (1 subgoal):
1. ([], {}) \<in> c_failures step out s\<^sub>0
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
([], {(x, p). p \<noteq> out s\<^sub>0 x}) \<in> c_failures step out s\<^sub>0
goal (1 subgoal):
1. ([], {}) \<in> c_failures step out s\<^sub>0
[PROOF STEP]
have "{} \<subseteq> {(x, p). p \<noteq> out s\<^sub>0 x}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. {} \<subseteq> {(x, p). p \<noteq> out s\<^sub>0 x}
[PROOF STEP]
..
[PROOF STATE]
proof (state)
this:
{} \<subseteq> {(x, p). p \<noteq> out s\<^sub>0 x}
goal (1 subgoal):
1. ([], {}) \<in> c_failures step out s\<^sub>0
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
([], {(x, p). p \<noteq> out s\<^sub>0 x}) \<in> c_failures step out s\<^sub>0
{} \<subseteq> {(x, p). p \<noteq> out s\<^sub>0 x}
[PROOF STEP]
show "([], {}) \<in> c_failures step out s\<^sub>0"
[PROOF STATE]
proof (prove)
using this:
([], {(x, p). p \<noteq> out s\<^sub>0 x}) \<in> c_failures step out s\<^sub>0
{} \<subseteq> {(x, p). p \<noteq> out s\<^sub>0 x}
goal (1 subgoal):
1. ([], {}) \<in> c_failures step out s\<^sub>0
[PROOF STEP]
by (rule R2)
[PROOF STATE]
proof (state)
this:
([], {}) \<in> c_failures step out s\<^sub>0
goal:
No subgoals!
[PROOF STEP]
qed |
Require Import HoTT.Classes.interfaces.abstract_algebra
HoTT.Classes.interfaces.orders
HoTT.Classes.theory.rationals
HoTT.Classes.orders.orders
HoTT.Classes.theory.premetric
HoTT.Classes.implementations.assume_rationals
HoTT.HSet HoTT.Basics.Trunc HProp HSet
Types.Universe
TruncType Types.Sigma
HIT.quotient.
Require Import HoTTClasses.partiality
sierpinsky
dedekind.
Require Export Rlow Opens Functions.
Set Implicit Arguments.
(** * D_op: operator which takes a function and a rational
and gives the open in which the function is bigger than the
rational *)
(** see a similart construction with Dedekind cuts in
Coquand-Spitters 09, Integrals and valuations *)
Section Dop.
Context `{Funext} `{Univalence}.
Definition D_op {A :hSet} (q : Q) : mf A -> OS A :=
fun f z => let (rl,_) := (f z) in (elt rl q).
(** Correctness of the definition *)
Lemma D_op_correct {A:hSet}: forall f q (x:A),
(D_op q f) x <-> QRlow q < (f x).
Proof.
intros f q x; split; intro HH.
+ unfold D_op in HH.
destruct (f x); simpl.
red; unfold Rllt.
apply tr.
exists q.
split; trivial.
unfold QRlow.
simpl; intros Hn.
unfold semi_decide, Rllt_semi_dec,
decidable_semi_decide in Hn.
destruct (dec (q < q)).
generalize (@eq_not_lt Q).
intros SS; specialize (SS _ _ q q).
apply SS.
reflexivity.
apply l.
case (not_bot Hn).
+ unfold D_op.
red in HH.
destruct (f x).
simpl in H.
unfold QRlow in H.
unfold Rllt in H.
revert HH; apply (Trunc_ind _);
intros (s,(E1,E2)).
simpl in E2.
unfold semi_decide, Rllt_semi_dec,
decidable_semi_decide in E2.
destruct (dec (s < q)) in E2.
case E2; apply top_greatest.
assert (Hsq : Qle q s).
apply Fpo_Qle_Qlt; trivial.
apply Rlow_mon with rl s.
trivial.
unfold Rlle; trivial.
trivial.
Qed.
(** Monotonicity of the operator on the functional arg*)
Lemma D_op_mon_f {A:hSet}: forall q (f:mf A) g,
fle f g -> D_op q f ⊆ D_op q g.
Proof.
intros q f g Hfg z; unfold D_op.
assert (Hle : Rlle (f z) (g z)).
apply Hfg.
destruct (f z).
destruct (g z).
apply imply_le.
exact (Hle q).
Qed.
(** Monotonicity of the operator on the rational arg*)
Lemma D_op_mon_q {A:hSet} : forall p q (f : mf A),
Qle p q -> D_op q f ⊆ D_op p f.
Proof.
intros p q f Hpq.
assert (Haux : forall z, D_op q f z -> D_op p f z).
intros z.
intros Hq.
apply D_op_correct.
apply D_op_correct in Hq.
red; red in Hq.
unfold Rllt in *.
revert Hq; apply (Trunc_ind _).
intros Hq; apply tr.
destruct Hq as (s,(Hq1,Hq2)).
exists s; split.
+ trivial.
+ intros Ho. apply Hq2.
apply Rlow_mon with (QRlow p) s.
reflexivity.
intros v Hv.
unfold QRlow.
simpl in *.
unfold semi_decide, Rllt_semi_dec,
decidable_semi_decide in *.
destruct (dec (v < q)).
apply top_greatest.
destruct (dec (v < p)).
assert (Hr : v < q).
apply orders.lt_le_trans with p; try trivial.
case (n Hr).
trivial. trivial.
+ intros z; apply imply_le; exact (Haux z).
Qed.
Hint Resolve D_op_mon_f D_op_mon_q.
End Dop. |
(* Example in linked lists *)
theory IHT_Linked_List
imports "../SepLogicTime/SLTC_Main" "../Asymptotics/Asymptotics_Recurrences"
begin
section \<open>List assertion\<close>
datatype 'a node = Node (val: "'a") (nxt: "'a node ref option")
setup \<open>fold add_rewrite_rule @{thms node.sel}\<close>
setup \<open>add_forward_prfstep (equiv_forward_th @{thm node.simps(1)})\<close>
fun node_encode :: "'a::heap node \<Rightarrow> nat" where
"node_encode (Node x r) = to_nat (x, r)"
instance node :: (heap) heap
apply (rule heap_class.intro)
apply (rule countable_classI [of "node_encode"])
apply (case_tac x, simp_all, case_tac y, simp_all)
..
fun os_list :: "'a::heap list \<Rightarrow> 'a node ref option \<Rightarrow> assn" where
"os_list [] p = \<up>(p = None)"
| "os_list (x # l) (Some p) = (\<exists>\<^sub>Aq. p \<mapsto>\<^sub>r Node x q * os_list l q)"
| "os_list (x # l) None = false"
setup \<open>fold add_rewrite_ent_rule @{thms os_list.simps}\<close>
lemma os_list_empty [forward_ent]:
"os_list [] p \<Longrightarrow>\<^sub>A \<up>(p = None)" by auto2
lemma os_list_Cons [forward_ent]:
"os_list (x # l) p \<Longrightarrow>\<^sub>A (\<exists>\<^sub>Aq. the p \<mapsto>\<^sub>r Node x q * os_list l q * \<up>(p \<noteq> None))"
@proof @case "p = None" @qed
lemma os_list_none: "emp \<Longrightarrow>\<^sub>A os_list [] None" by auto2
lemma os_list_constr_ent:
"p \<mapsto>\<^sub>r Node x q * os_list l q \<Longrightarrow>\<^sub>A os_list (x # l) (Some p)" by auto2
setup \<open>fold add_entail_matcher [@{thm os_list_none}, @{thm os_list_constr_ent}]\<close>
setup \<open>fold del_prfstep_thm @{thms os_list.simps}\<close>
type_synonym 'a os_list = "'a node ref option"
section \<open>Basic operations\<close>
definition os_empty :: "'a::heap os_list Heap" where
"os_empty = return None"
lemma os_empty_rule [hoare_triple]:
"<$1> os_empty <os_list []>" by auto2
definition os_is_empty :: "'a::heap os_list \<Rightarrow> bool Heap" where
"os_is_empty b = return (b = None)"
lemma os_is_empty_rule [hoare_triple]:
"<os_list xs b * $1> os_is_empty b <\<lambda>r. os_list xs b * \<up>(r \<longleftrightarrow> xs = [])>"
@proof @case "xs = []" @have "xs = hd xs # tl xs" @qed
definition os_prepend :: "'a \<Rightarrow> 'a::heap os_list \<Rightarrow> 'a os_list Heap" where
"os_prepend a n = do { p \<leftarrow> ref (Node a n); return (Some p) }"
lemma os_prepend_rule [hoare_triple]:
"<os_list xs n * $2> os_prepend x n <os_list (x # xs)>" by auto2
definition os_pop :: "'a::heap os_list \<Rightarrow> ('a \<times> 'a os_list) Heap" where
"os_pop r = (case r of
None \<Rightarrow> raise ''Empty Os_list'' |
Some p \<Rightarrow> do {m \<leftarrow> !p; return (val m, nxt m)})"
lemma os_pop_rule [hoare_triple]:
"<os_list xs (Some p) * $2>
os_pop (Some p)
<\<lambda>(x,r'). os_list (tl xs) r' * p \<mapsto>\<^sub>r (Node x r') * \<up>(x = hd xs)>"
@proof @case "xs = []" @have "xs = hd xs # tl xs" @qed
section \<open>Reverse\<close>
partial_function (heap_time) os_reverse_aux :: "'a::heap os_list \<Rightarrow> 'a os_list \<Rightarrow> 'a os_list Heap" where
"os_reverse_aux q p = (case p of
None \<Rightarrow> return q |
Some r \<Rightarrow> do {
v \<leftarrow> !r;
r := Node (val v) q;
os_reverse_aux p (nxt v) })"
lemma os_reverse_aux_rule [hoare_triple]:
"<os_list xs p * os_list ys q * $(2 * length xs + 1)>
os_reverse_aux q p
<os_list ((rev xs) @ ys)>"
@proof @induct xs arbitrary p q ys @qed
definition os_reverse :: "'a::heap os_list \<Rightarrow> 'a os_list Heap" where
"os_reverse p = os_reverse_aux None p"
lemma os_reverse_rule:
"<os_list xs p * $(2 * length xs + 1)>
os_reverse p
<os_list (rev xs)>" by auto2
section \<open>Remove\<close>
setup \<open>fold add_rewrite_rule @{thms removeAll.simps}\<close>
partial_function (heap_time) os_rem :: "'a::heap \<Rightarrow> 'a node ref option \<Rightarrow> 'a node ref option Heap" where
"os_rem x b = (case b of
None \<Rightarrow> return None |
Some p \<Rightarrow> do {
n \<leftarrow> !p;
q \<leftarrow> os_rem x (nxt n);
(if val n = x then
return q
else do {
p := Node (val n) q;
return (Some p) }) })"
lemma os_rem_rule [hoare_triple]:
"<os_list xs b * $(4 * length xs + 1)>
os_rem x b
<\<lambda>r. os_list (removeAll x xs) r>\<^sub>t"
@proof @induct xs arbitrary b @qed
section \<open>Extract list\<close>
partial_function (heap_time) extract_list :: "'a::heap os_list \<Rightarrow> 'a list Heap" where
"extract_list p = (case p of
None \<Rightarrow> return []
| Some pp \<Rightarrow> do {
v \<leftarrow> !pp;
ls \<leftarrow> extract_list (nxt v);
return (val v # ls)
})"
lemma extract_list_rule [hoare_triple]:
"<os_list l p * $(2 * length l + 1)>
extract_list p
<\<lambda>r. os_list l p * \<up>(r = l)>"
@proof @induct l arbitrary p @qed
section \<open>Ordered insert\<close>
fun list_insert :: "'a::ord \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"list_insert x [] = [x]"
| "list_insert x (y # ys) = (
if x \<le> y then x # (y # ys) else y # list_insert x ys)"
setup \<open>fold add_rewrite_rule @{thms list_insert.simps}\<close>
lemma list_insert_length [rewrite_arg]:
"length (list_insert x xs) = length xs + 1"
@proof @induct xs @qed
lemma list_insert_mset [rewrite]:
"mset (list_insert x xs) = {#x#} + mset xs"
@proof @induct xs @qed
lemma list_insert_set [rewrite]:
"set (list_insert x xs) = {x} \<union> set xs"
@proof @induct xs @qed
lemma list_insert_sorted [forward]:
"sorted xs \<Longrightarrow> sorted (list_insert x xs)"
@proof @induct xs @qed
partial_function (heap_time) os_insert :: "'a::{ord,heap} \<Rightarrow> 'a os_list \<Rightarrow> 'a os_list Heap" where
"os_insert x b = (case b of
None \<Rightarrow> os_prepend x None
| Some p \<Rightarrow> do {
v \<leftarrow> !p;
(if x \<le> val v then os_prepend x b
else do {
q \<leftarrow> os_insert x (nxt v);
p := Node (val v) q;
return (Some p) }) })"
lemma os_insert_to_fun [hoare_triple]:
"<os_list xs b * $(3 * length xs + 2)>
os_insert x b
<os_list (list_insert x xs)>\<^sub>t"
@proof @induct xs arbitrary b @qed
section \<open>Insertion sort\<close>
fun insert_sort :: "'a::ord list \<Rightarrow> 'a list" where
"insert_sort [] = []"
| "insert_sort (x # xs) = list_insert x (insert_sort xs)"
setup \<open>fold add_rewrite_rule @{thms insert_sort.simps}\<close>
lemma insert_sort_length [rewrite_arg]:
"length (insert_sort xs) = length xs"
@proof @induct xs @qed
lemma insert_sort_mset [rewrite]:
"mset (insert_sort xs) = mset xs"
@proof @induct xs @qed
lemma insert_sort_sorted [forward]:
"sorted (insert_sort xs)"
@proof @induct xs @qed
lemma insert_sort_is_sort [rewrite]:
"insert_sort xs = sort xs" by auto2
fun os_insert_sort_aux :: "'a::{heap,ord} list \<Rightarrow> 'a os_list Heap" where
"os_insert_sort_aux [] = (return None)"
| "os_insert_sort_aux (x # xs) = do {
b \<leftarrow> os_insert_sort_aux xs;
b' \<leftarrow> os_insert x b;
return b'
}"
lemma os_insert_sort_aux_correct [hoare_triple]:
"<$(2 * length xs * length xs + length xs + 1)>
os_insert_sort_aux xs
<os_list (insert_sort xs)>\<^sub>t"
@proof @induct xs @qed
definition os_insert_sort :: "'a::{ord,heap} list \<Rightarrow> 'a list Heap" where
"os_insert_sort xs = do {
p \<leftarrow> os_insert_sort_aux xs;
l \<leftarrow> extract_list p;
return l
}"
definition os_insert_sort_time :: "nat \<Rightarrow> nat" where [rewrite]:
"os_insert_sort_time n = 2 * n * n + 3 * n + 3"
lemma os_insert_sort_rule [hoare_triple]:
"<$(os_insert_sort_time (length xs))>
os_insert_sort xs
<\<lambda>ys. \<up>(ys = sort xs)>\<^sub>t" by auto2
lemma os_insert_sort_time_monotonic [backward]:
"n \<le> m \<Longrightarrow> os_insert_sort_time n \<le> os_insert_sort_time m"
@proof @have "3 * n \<le> 3 * m" @qed
setup \<open>del_prfstep_thm @{thm os_insert_sort_time_def}\<close>
(* Alternative proof using bigO *)
fun os_insert_sort_aux' :: "'a::{heap,ord} list \<Rightarrow> 'a os_list Heap" where
"os_insert_sort_aux' [] = (return None)"
| "os_insert_sort_aux' (x # xs) = do {
b \<leftarrow> os_insert_sort_aux' xs;
b' \<leftarrow> os_insert x b;
return b'
}"
fun os_insert_sort_aux_time :: "nat \<Rightarrow> nat" where
"os_insert_sort_aux_time 0 = 1"
| "os_insert_sort_aux_time (Suc n) = os_insert_sort_aux_time n + 3 * n + 2 + 1"
setup \<open>add_rewrite_rule @{thm os_insert_sort_aux_time.simps(1)}\<close>
lemma os_insert_sort_aux_time_simps [rewrite]:
"os_insert_sort_aux_time (n + 1) = os_insert_sort_aux_time n + 3 * n + 2 + 1" by simp
lemma os_insert_sort_aux_correct':
"<$(os_insert_sort_aux_time (length xs))>
os_insert_sort_aux' xs
<os_list (insert_sort xs)>\<^sub>t"
@proof @induct xs @qed
lemma os_insert_sort_aux_time_asym': "os_insert_sort_aux_time \<in> \<Theta>(\<lambda>n. n * n)"
by (rule bigTheta_linear_recurrence[where N=0]) auto
end
|
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include "allvars.h"
#include "proto.h"
#ifdef SUBFIND
#include "subfind.h"
/*! Structure for communication during the density computation. Holds data that is sent to other processors.
*/
static struct nearestdata_in
{
MyDouble Pos[3];
MyIDType ID;
MyFloat Hsml;
MyFloat Density;
MyFloat Dist[2];
int Count;
long long Index[2];
int NodeList[NODELISTLENGTH];
}
*NearestDataIn, *NearestDataGet;
static struct nearestdata_out
{
MyFloat Dist[2];
long long Index[2];
int Count;
}
*NearestDataResult, *NearestDataOut;
void subfind_find_nearesttwo(void)
{
int i, j, k, l, ndone, ndone_flag, dummy;
int ngrp, sendTask, recvTask, place, nexport, nimport, maxexport;
if(ThisTask == 0)
printf("Start finding nearest two (%d particles on task=%d)\n", NumPartGroup, ThisTask);
/* allocate buffers to arrange communication */
Ngblist = (int *) mymalloc(NumPartGroup * sizeof(int));
Dist2list = (double *) mymalloc(NumPartGroup * sizeof(double));
All.BunchSize =
(int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) +
sizeof(struct nearestdata_in) + sizeof(struct nearestdata_out) +
sizemax(sizeof(struct nearestdata_in),
sizeof(struct nearestdata_out))));
DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index));
DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist));
maxexport = All.BunchSize - 2 * NTopleaves / NODELISTLENGTH;
for(i = 0; i < NumPartGroup; i++)
NgbLoc[i].count = 0;
/* we will repeat the whole thing for those particles where we didn't find enough neighbours */
i = 0; /* begin with this index */
do
{
for(j = 0; j < NTask; j++)
{
Send_count[j] = 0;
Exportflag[j] = -1;
}
/* do local particles and prepare export list */
for(nexport = 0; i < NumPartGroup; i++)
{
if(subfind_nearesttwo_evaluate(i, 0, &nexport, Send_count) < 0)
break;
}
qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare);
MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);
for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++)
{
Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask];
nimport += Recv_count[j];
if(j > 0)
{
Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1];
Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1];
}
}
NearestDataGet = (struct nearestdata_in *) mymalloc(nimport * sizeof(struct nearestdata_in));
NearestDataIn = (struct nearestdata_in *) mymalloc(nexport * sizeof(struct nearestdata_in));
/* prepare particle data for export */
for(j = 0; j < nexport; j++)
{
place = DataIndexTable[j].Index;
NearestDataIn[j].Pos[0] = P[place].Pos[0];
NearestDataIn[j].Pos[1] = P[place].Pos[1];
NearestDataIn[j].Pos[2] = P[place].Pos[2];
NearestDataIn[j].Hsml = P[place].DM_Hsml;
NearestDataIn[j].ID = P[place].ID;
NearestDataIn[j].Density = P[place].u.DM_Density;
NearestDataIn[j].Count = NgbLoc[place].count;
for(k = 0; k < NgbLoc[place].count; k++)
{
NearestDataIn[j].Dist[k] = R2Loc[place].dist[k];
NearestDataIn[j].Index[k] = NgbLoc[place].index[k];
}
memcpy(NearestDataIn[j].NodeList,
DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int));
}
/* exchange particle data */
for(ngrp = 1; ngrp < (1 << PTask); ngrp++)
{
sendTask = ThisTask;
recvTask = ThisTask ^ ngrp;
if(recvTask < NTask)
{
if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)
{
/* get the particles */
MPI_Sendrecv(&NearestDataIn[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(struct nearestdata_in), MPI_BYTE,
recvTask, TAG_DENS_A,
&NearestDataGet[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(struct nearestdata_in), MPI_BYTE,
recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
myfree(NearestDataIn);
NearestDataResult = (struct nearestdata_out *) mymalloc(nimport * sizeof(struct nearestdata_out));
NearestDataOut = (struct nearestdata_out *) mymalloc(nexport * sizeof(struct nearestdata_out));
/* now do the particles that were sent to us */
for(j = 0; j < nimport; j++)
subfind_nearesttwo_evaluate(j, 1, &dummy, &dummy);
if(i >= NumPartGroup)
ndone_flag = 1;
else
ndone_flag = 0;
MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
/* get the result */
for(ngrp = 1; ngrp < (1 << PTask); ngrp++)
{
sendTask = ThisTask;
recvTask = ThisTask ^ ngrp;
if(recvTask < NTask)
{
if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)
{
/* send the results */
MPI_Sendrecv(&NearestDataResult[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(struct nearestdata_out),
MPI_BYTE, recvTask, TAG_DENS_B,
&NearestDataOut[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(struct nearestdata_out),
MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
/* add the result to the local particles */
for(j = 0; j < nexport; j++)
{
place = DataIndexTable[j].Index;
for(k = 0; k < NearestDataOut[j].Count; k++)
{
if(NgbLoc[place].count >= 1)
if(NgbLoc[place].index[0] == NearestDataOut[j].Index[k])
continue;
if(NgbLoc[place].count == 2)
if(NgbLoc[place].index[1] == NearestDataOut[j].Index[k])
continue;
if(NgbLoc[place].count < 2)
{
l = NgbLoc[place].count;
NgbLoc[place].count++;
}
else
{
if(R2Loc[place].dist[0] > R2Loc[place].dist[1])
l = 0;
else
l = 1;
if(NearestDataOut[j].Dist[k] >= R2Loc[place].dist[l])
continue;
}
R2Loc[place].dist[l] = NearestDataOut[j].Dist[k];
NgbLoc[place].index[l] = NearestDataOut[j].Index[k];
if(NgbLoc[place].count == 2)
if(NgbLoc[place].index[0] == NgbLoc[place].index[1])
{
/*
printf("taaa=%d i=%d task_0=%d index_0=%d task_1=%d index_1=%d\n",
ThisTask, place,
NgbLoc[place].task[0], NgbLoc[place].index[0],
NgbLoc[place].task[1], NgbLoc[place].index[1]);
printf
("NearestDataOut[j].Count=%d l=%d k=%d task_0=%d index_0=%d task_1=%d index_1=%d\n",
NearestDataOut[j].Count, l, k, NearestDataOut[j].Task[0], NearestDataOut[j].Index[0],
NearestDataOut[j].Task[1], NearestDataOut[j].Index[1]);
*/
endrun(112);
}
}
}
myfree(NearestDataOut);
myfree(NearestDataResult);
myfree(NearestDataGet);
}
while(ndone < NTask);
myfree(DataNodeList);
myfree(DataIndexTable);
myfree(Dist2list);
myfree(Ngblist);
}
/*! This function represents the core of the SPH density computation. The
* target particle may either be local, or reside in the communication
* buffer.
*/
int subfind_nearesttwo_evaluate(int target, int mode, int *nexport, int *nsend_local)
{
int j, k, n, count;
MyIDType ID;
long long index[2];
double dist[2];
int startnode, numngb, numngb_inbox, listindex = 0;
double hmax;
double h, h2, hinv, hinv3;
double r2, density;
MyDouble *pos;
numngb = 0;
if(mode == 0)
{
ID = P[target].ID;
density = P[target].u.DM_Density;
pos = P[target].Pos;
h = P[target].DM_Hsml;
count = NgbLoc[target].count;
for(k = 0; k < count; k++)
{
dist[k] = R2Loc[target].dist[k];
index[k] = NgbLoc[target].index[k];
}
}
else
{
ID = NearestDataGet[target].ID;
density = NearestDataGet[target].Density;
pos = NearestDataGet[target].Pos;
h = NearestDataGet[target].Hsml;
count = NearestDataGet[target].Count;
for(k = 0; k < count; k++)
{
dist[k] = NearestDataGet[target].Dist[k];
index[k] = NearestDataGet[target].Index[k];
}
}
h2 = h * h;
hinv = 1.0 / h;
hinv3 = hinv * hinv * hinv;
if(mode == 0)
{
startnode = All.MaxPart; /* root node */
}
else
{
startnode = NearestDataGet[target].NodeList[0];
startnode = Nodes[startnode].u.d.nextnode; /* open it */
}
numngb = 0;
if(count == 2)
if(index[0] == index[1])
{
/* printf("T-A-S-K=%d target=%d mode=%d task_0=%d index_0=%d task_1=%d index_1=%d\n",
ThisTask, target, mode, task[0], index[0], task[1], index[1]);
*/
endrun(1232);
}
while(startnode >= 0)
{
while(startnode >= 0)
{
numngb_inbox =
subfind_ngb_treefind_nearesttwo(pos, h, target, &startnode, mode, &hmax, nexport, nsend_local);
if(numngb_inbox < 0)
return -1;
for(n = 0; n < numngb_inbox; n++)
{
j = Ngblist[n];
r2 = Dist2list[n];
if(P[j].ID != ID) /* exclude the self-particle */
{
if(P[j].u.DM_Density > density) /* we only look at neighbours that are denser */
{
if(count < 2)
{
dist[count] = r2;
index[count] = (((long long) ThisTask) << 32) + j;
count++;
}
else
{
if(dist[0] > dist[1])
k = 0;
else
k = 1;
if(r2 < dist[k])
{
dist[k] = r2;
index[k] = (((long long) ThisTask) << 32) + j;
}
}
}
numngb++;
}
}
}
if(mode == 1)
{
listindex++;
if(listindex < NODELISTLENGTH)
{
startnode = NearestDataGet[target].NodeList[listindex];
if(startnode >= 0)
startnode = Nodes[startnode].u.d.nextnode; /* open it */
}
}
}
if(mode == 0)
{
NgbLoc[target].count = count;
for(k = 0; k < count; k++)
{
R2Loc[target].dist[k] = dist[k];
NgbLoc[target].index[k] = index[k];
}
if(count == 2)
if(NgbLoc[target].index[0] == NgbLoc[target].index[1])
{
/*
printf("TASK=%d target=%d task_0=%d index_0=%d task_1=%d index_1=%d\n",
ThisTask, target,
NgbLoc[target].task[0], NgbLoc[target].index[0],
NgbLoc[target].task[1], NgbLoc[target].index[1]);
*/
endrun(2);
}
}
else
{
NearestDataResult[target].Count = count;
for(k = 0; k < count; k++)
{
NearestDataResult[target].Dist[k] = dist[k];
NearestDataResult[target].Index[k] = index[k];
}
if(count == 2)
if(NearestDataResult[target].Index[0] == NearestDataResult[target].Index[1])
{
/*
printf("TASK!!=%d target=%d task_0=%d index_0=%d task_1=%d index_1=%d\n",
ThisTask, target,
NearestDataResult[target].Task[0], NearestDataResult[target].Index[0],
NearestDataResult[target].Task[1], NearestDataResult[target].Index[1]);
*/
endrun(22);
}
}
return 0;
}
int subfind_ngb_treefind_nearesttwo(MyDouble searchcenter[3], double hsml, int target, int *startnode,
int mode, double *hmax, int *nexport, int *nsend_local)
{
int numngb, no, p, task, nexport_save, exported = 0;
struct NODE *current;
double dx, dy, dz, dist, r2;
#ifdef PERIODIC
double xtmp;
#endif
nexport_save = *nexport;
*hmax = 0;
numngb = 0;
no = *startnode;
while(no >= 0)
{
if(no < All.MaxPart) /* single particle */
{
p = no;
no = Nextnode[no];
#ifdef DENSITY_SPLIT_BY_TYPE
if(!((1 << P[p].Type) & (DENSITY_SPLIT_BY_TYPE)))
continue;
#else
if(!((1 << P[p].Type) & (FOF_PRIMARY_LINK_TYPES)))
continue;
#endif
dist = hsml;
dx = NGB_PERIODIC_LONG_X(P[p].Pos[0] - searchcenter[0]);
if(dx > dist)
continue;
dy = NGB_PERIODIC_LONG_Y(P[p].Pos[1] - searchcenter[1]);
if(dy > dist)
continue;
dz = NGB_PERIODIC_LONG_Z(P[p].Pos[2] - searchcenter[2]);
if(dz > dist)
continue;
if((r2 = (dx * dx + dy * dy + dz * dz)) > dist * dist)
continue;
Dist2list[numngb] = r2;
Ngblist[numngb++] = p;
}
else
{
if(no >= All.MaxPart + MaxNodes) /* pseudo particle */
{
if(mode == 1)
endrun(12312);
if(target >= 0) /* if no target is given, export will not occur */
{
exported = 1;
if(Exportflag[task = DomainTask[no - (All.MaxPart + MaxNodes)]] != target)
{
Exportflag[task] = target;
Exportnodecount[task] = NODELISTLENGTH;
}
if(Exportnodecount[task] == NODELISTLENGTH)
{
if(*nexport >= All.BunchSize)
{
*nexport = nexport_save;
if(nexport_save == 0)
endrun(13004); /* in this case, the buffer is too small to process even a single particle */
for(task = 0; task < NTask; task++)
nsend_local[task] = 0;
for(no = 0; no < nexport_save; no++)
nsend_local[DataIndexTable[no].Task]++;
return -1;
}
Exportnodecount[task] = 0;
Exportindex[task] = *nexport;
DataIndexTable[*nexport].Task = task;
DataIndexTable[*nexport].Index = target;
DataIndexTable[*nexport].IndexGet = *nexport;
*nexport = *nexport + 1;
nsend_local[task]++;
}
DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]++] =
DomainNodeIndex[no - (All.MaxPart + MaxNodes)];
if(Exportnodecount[task] < NODELISTLENGTH)
DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]] = -1;
}
no = Nextnode[no - MaxNodes];
continue;
}
current = &Nodes[no];
if(mode == 1)
{
if(current->u.d.bitflags & (1 << BITFLAG_TOPLEVEL)) /* we reached a top-level node again, which means that we are done with the branch */
{
*startnode = -1;
return numngb;
}
}
no = current->u.d.sibling; /* in case the node can be discarded */
dist = hsml + 0.5 * current->len;;
dx = NGB_PERIODIC_LONG_X(current->center[0] - searchcenter[0]);
if(dx > dist)
continue;
dy = NGB_PERIODIC_LONG_Y(current->center[1] - searchcenter[1]);
if(dy > dist)
continue;
dz = NGB_PERIODIC_LONG_Z(current->center[2] - searchcenter[2]);
if(dz > dist)
continue;
/* now test against the minimal sphere enclosing everything */
dist += FACT1 * current->len;
if(dx * dx + dy * dy + dz * dz > dist * dist)
continue;
no = current->u.d.nextnode; /* ok, we need to open the node */
}
}
*startnode = -1;
return numngb;
}
#endif
|
[STATEMENT]
lemma Gen_Shleg_0 [simp]: "k < n \<Longrightarrow> Gen_Shleg k 0 = 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. k < n \<Longrightarrow> local.Gen_Shleg k 0 = 0
[PROOF STEP]
by (simp add: Gen_Shleg_altdef zero_power) |
function res = bf_inverse_champagne(BF, S)
% Computes Champagne filters
% See Owen et al. Performance evaluation of the Champagne source
% reconstruction algorithm on simulated and real M/EEG data. Neuroimage. 2012 Mar;60(1):305-23
% Code contributed by Sri Nagarajan
% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: bf_inverse_champagne.m 7703 2019-11-22 12:06:29Z guillaume $
%--------------------------------------------------------------------------
if nargin == 0
nem = cfg_entry;
nem.tag = 'nem';
nem.name = 'Number of EM iterations';
nem.strtype = 'n';
nem.num = [1 1];
nem.val = {100};
vcs = cfg_menu;
vcs.tag = 'vcs';
vcs.name = 'Voxel covariance structure';
vcs.labels = {
'scalar'
'diagonal'
'general'
}';
vcs.values = {0, 1, 2};
vcs.val = {2};
nupd = cfg_menu;
nupd.tag = 'nupd';
nupd.name = 'Noise covariance';
nupd.labels = {
'use provided'
'learn scalar'
'learn diagonal'
}';
nupd.values = {0, 1, 2};
nupd.val = {0};
champagne = cfg_branch;
champagne.tag = 'champagne';
champagne.name = 'Champagne';
champagne.val = {nem, vcs, nupd};
res = champagne;
return
elseif nargin < 2
error('Two input arguments are required');
end
C = BF.features.(S.modality).C;
Y = BF.features.(S.modality).Y;
L = S.L;
W = cell(size(L));
nvert = numel(W);
nd = size(L{1}, 2);
LL = zeros(size(L{1}, 1), nvert*nd);
ind = 1;
spm('Pointer', 'Watch');drawnow;
spm_progress_bar('Init', nvert, ['Preparing ' S.modality ' leadfields']); drawnow;
if nvert > 100, Ibar = floor(linspace(1, nvert,100));
else Ibar = 1:nvert; end
for i = 1:nvert
for j = 1:nd
lf = L{i}(:, j);
LL(:, ind) = lf./norm(lf);
ind = ind+1;
end
if ismember(i, Ibar)
spm_progress_bar('Set', i); drawnow;
end
end
Fgraph = spm_figure('GetWin', 'Champagne'); figure(Fgraph); clf
%****************************************************************************************
[gamma,x,w,sigu,like]=champagne_aug2015(Y, LL, C, S.nem, nd, S.vcs, S.nupd, [], 0, Fgraph);
%****************************************************************************************
spm_progress_bar('Init', nvert, ['Preparing ' S.modality ' filters']); drawnow;
if nvert > 100, Ibar = floor(linspace(1, nvert,100));
else Ibar = 1:nvert; end
for i = 1:nvert
W{i} = w((i-1)*nd+(1:3), :);
if ismember(i, Ibar)
spm_progress_bar('Set', i); drawnow;
end
end
spm_progress_bar('Clear');
spm('Pointer', 'Arrow');
res.W = W; |
------------------------------------------------------------------------------
-- Group theory properties using Agsy
------------------------------------------------------------------------------
{-# OPTIONS --allow-unsolved-metas #-}
{-# OPTIONS --exact-split #-}
{-# OPTIONS --no-sized-types #-}
{-# OPTIONS --no-universe-polymorphism #-}
{-# OPTIONS --without-K #-}
-- Tested with the development version of the Agda standard library on
-- 02 February 2012.
module Agsy.GroupTheory where
open import Data.Product
open import Relation.Binary.PropositionalEquality
open ≡-Reasoning
infix 8 _⁻¹
infixl 7 _·_
------------------------------------------------------------------------------
-- Group theory axioms
postulate
G : Set -- The universe.
ε : G -- The identity element.
_·_ : G → G → G -- The binary operation.
_⁻¹ : G → G -- The inverse function.
assoc : ∀ x y z → x · y · z ≡ x · (y · z)
leftIdentity : ∀ x → ε · x ≡ x
rightIdentity : ∀ x → x · ε ≡ x
leftInverse : ∀ x → x ⁻¹ · x ≡ ε
rightInverse : ∀ x → x · x ⁻¹ ≡ ε
-- Properties
y≡x⁻¹[xy] : ∀ a b → b ≡ a ⁻¹ · (a · b)
y≡x⁻¹[xy] a b = {!-t 20 -m!} -- Agsy fails
x≡[xy]y⁻¹ : ∀ a b → a ≡ (a · b) · b ⁻¹
x≡[xy]y⁻¹ a b = {!-t 20 -m!} -- Agsy fails
rightIdentityUnique : Σ G λ u → (∀ x → x · u ≡ x) ×
(∀ u' → (∀ x → x · u' ≡ x) → u ≡ u')
rightIdentityUnique = {!-t 20 -m!} -- Agsy fails
-- ε
-- , rightIdentity
-- , λ x x' → begin
-- ε ≡⟨ sym (x' ε) ⟩
-- ε · x ≡⟨ leftIdentity x ⟩
-- x
-- ∎
rightIdentityUnique' : ∀ x u → x · u ≡ x → ε ≡ u
rightIdentityUnique' x u xu≡x = {!-t 20 -m!} -- Agsy fails
leftIdentityUnique : Σ G λ u → (∀ x → u · x ≡ x) ×
(∀ u' → (∀ x → u' · x ≡ x) → u ≡ u')
leftIdentityUnique = {!-t 20 -m!} -- Agsy fails
-- ε
-- , leftIdentity
-- , λ x x' → begin
-- ε ≡⟨ sym (x' ε) ⟩
-- x · ε ≡⟨ rightIdentity x ⟩
-- x
-- ∎
leftIdentityUnique' : ∀ x u → u · x ≡ x → ε ≡ u
leftIdentityUnique' x u ux≡x = {!-t 20 -m!}
rightCancellation : ∀ x y z → y · x ≡ z · x → y ≡ z
rightCancellation x y z = λ hyp → {!-t 20 -m!} -- Agsy fails
leftCancellation : ∀ x y z → x · y ≡ x · z → y ≡ z
leftCancellation x y z = λ hyp → {!-t 20 -m!} -- Agsy fails
leftCancellationER : (x y z : G) → x · y ≡ x · z → y ≡ z
leftCancellationER x y z x·y≡x·z =
begin
y ≡⟨ sym (leftIdentity y) ⟩
ε · y ≡⟨ subst (λ t → ε · y ≡ t · y) (sym (leftInverse x)) refl ⟩
x ⁻¹ · x · y ≡⟨ assoc (x ⁻¹) x y ⟩
x ⁻¹ · (x · y) ≡⟨ subst (λ t → x ⁻¹ · (x · y) ≡ x ⁻¹ · t) x·y≡x·z refl ⟩
x ⁻¹ · (x · z) ≡⟨ sym (assoc (x ⁻¹) x z) ⟩
x ⁻¹ · x · z ≡⟨ subst (λ t → x ⁻¹ · x · z ≡ t · z) (leftInverse x) refl ⟩
ε · z ≡⟨ leftIdentity z ⟩
z
∎
rightInverseUnique : ∀ x → Σ G λ r → (x · r ≡ ε) ×
(∀ r' → x · r' ≡ ε → r ≡ r')
rightInverseUnique x = {!-t 20 -m!} -- Agsy fails
rightInverseUnique' : ∀ x r → x · r ≡ ε → x ⁻¹ ≡ r
rightInverseUnique' x r = λ hyp → {!-t 20 -m!} -- Agsy fails
leftInverseUnique : ∀ x → Σ G λ l → (l · x ≡ ε) ×
(∀ l' → l' · x ≡ ε → l ≡ l')
leftInverseUnique x = {!-t 20 -m!} -- Agsy fails
⁻¹-involutive : ∀ x → x ⁻¹ ⁻¹ ≡ x
⁻¹-involutive x = {!-t 20 -m!} -- Agsy fails
inverseDistribution : ∀ x y → (x · y) ⁻¹ ≡ y ⁻¹ · x ⁻¹
inverseDistribution x y = {!-t 20 -m!} -- Agsy fails
-- If the square of every element is the identity, the system is
-- commutative. From: TPTP 6.4.0. File: Problems/GRP/GRP001-2.p
x²≡ε→comm : (∀ a → a · a ≡ ε) → ∀ {b c d} → b · c ≡ d → c · b ≡ d
x²≡ε→comm hyp {b} {c} {d} bc≡d = {!-t 20 -m!} -- Agsy fails
|
[GOAL]
⊢ ConcreteCategory BoolRingCat
[PROOFSTEP]
dsimp [BoolRingCat]
[GOAL]
⊢ ConcreteCategory (Bundled BooleanRing)
[PROOFSTEP]
infer_instance
-- Porting note: disabled `simps`
-- Invalid simp lemma BoolRingCat.hasForgetToCommRing_forget₂_obj_str_add.
-- The given definition is not a constructor application:
-- inferInstance.1
-- @[simps]
[GOAL]
α β : BoolRingCat
e : ↑α ≃+* ↑β
⊢ ↑e ≫ ↑(RingEquiv.symm e) = 𝟙 α
[PROOFSTEP]
ext
[GOAL]
case w
α β : BoolRingCat
e : ↑α ≃+* ↑β
x✝ : (forget BoolRingCat).obj α
⊢ ↑(↑e ≫ ↑(RingEquiv.symm e)) x✝ = ↑(𝟙 α) x✝
[PROOFSTEP]
exact e.symm_apply_apply _
[GOAL]
α β : BoolRingCat
e : ↑α ≃+* ↑β
⊢ ↑(RingEquiv.symm e) ≫ ↑e = 𝟙 β
[PROOFSTEP]
ext
[GOAL]
case w
α β : BoolRingCat
e : ↑α ≃+* ↑β
x✝ : (forget BoolRingCat).obj β
⊢ ↑(↑(RingEquiv.symm e) ≫ ↑e) x✝ = ↑(𝟙 β) x✝
[PROOFSTEP]
exact e.apply_symm_apply _
|
/-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Scott Morrison
! This file was ported from Lean 3 source module topology.sheaves.sheaf_of_functions
! leanprover-community/mathlib commit 70fd9563a21e7b963887c9360bd29b2393e6225a
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Topology.Sheaves.PresheafOfFunctions
import Mathbin.Topology.Sheaves.SheafCondition.UniqueGluing
/-!
# Sheaf conditions for presheaves of (continuous) functions.
We show that
* `Top.presheaf.to_Type_is_sheaf`: not-necessarily-continuous functions into a type form a sheaf
* `Top.presheaf.to_Types_is_sheaf`: in fact, these may be dependent functions into a type family
For
* `Top.sheaf_to_Top`: continuous functions into a topological space form a sheaf
please see `topology/sheaves/local_predicate.lean`, where we set up a general framework
for constructing sub(pre)sheaves of the sheaf of dependent functions.
## Future work
Obviously there's more to do:
* sections of a fiber bundle
* various classes of smooth and structure preserving functions
* functions into spaces with algebraic structure, which the sections inherit
-/
open CategoryTheory
open CategoryTheory.Limits
open TopologicalSpace
open TopologicalSpace.Opens
universe u
noncomputable section
variable (X : TopCat.{u})
open TopCat
namespace TopCat.Presheaf
/-- We show that the presheaf of functions to a type `T`
(no continuity assumptions, just plain functions)
form a sheaf.
In fact, the proof is identical when we do this for dependent functions to a type family `T`,
so we do the more general case.
-/
theorem to_Types_isSheaf (T : X → Type u) : (presheafToTypes X T).IsSheaf :=
isSheaf_of_isSheafUniqueGluing_types _ fun ι U sf hsf =>
-- We use the sheaf condition in terms of unique gluing
-- U is a family of open sets, indexed by `ι` and `sf` is a compatible family of sections.
-- In the informal comments below, I'll just write `U` to represent the union.
by
-- Our first goal is to define a function "lifted" to all of `U`.
-- We do this one point at a time. Using the axiom of choice, we can pick for each
-- `x : supr U` an index `i : ι` such that `x` lies in `U i`
choose index index_spec using fun x : supᵢ U => opens.mem_supr.mp x.2
-- Using this data, we can glue our functions together to a single section
let s : ∀ x : supᵢ U, T x := fun x => sf (index x) ⟨x.1, index_spec x⟩
refine' ⟨s, _, _⟩
· intro i
ext x
-- Now we need to verify that this lifted function restricts correctly to each set `U i`.
-- Of course, the difficulty is that at any given point `x ∈ U i`,
-- we may have used the axiom of choice to pick a different `j` with `x ∈ U j`
-- when defining the function.
-- Thus we'll need to use the fact that the restrictions are compatible.
convert congr_fun (hsf (index ⟨x, _⟩) i) ⟨x, ⟨index_spec ⟨x.1, _⟩, x.2⟩⟩
ext
rfl
· -- Now we just need to check that the lift we picked was the only possible one.
-- So we suppose we had some other gluing `t` of our sections
intro t ht
-- and observe that we need to check that it agrees with our choice
-- for each `f : s .X` and each `x ∈ supr U`.
ext x
convert congr_fun (ht (index x)) ⟨x.1, index_spec x⟩
ext
rfl
#align Top.presheaf.to_Types_is_sheaf TopCat.Presheaf.to_Types_isSheaf
-- We verify that the non-dependent version is an immediate consequence:
/-- The presheaf of not-necessarily-continuous functions to
a target type `T` satsifies the sheaf condition.
-/
theorem to_Type_isSheaf (T : Type u) : (presheafToType X T).IsSheaf :=
to_Types_isSheaf X fun _ => T
#align Top.presheaf.to_Type_is_sheaf TopCat.Presheaf.to_Type_isSheaf
end TopCat.Presheaf
namespace TopCat
/-- The sheaf of not-necessarily-continuous functions on `X` with values in type family
`T : X → Type u`.
-/
def sheafToTypes (T : X → Type u) : Sheaf (Type u) X :=
⟨presheafToTypes X T, Presheaf.to_Types_isSheaf _ _⟩
#align Top.sheaf_to_Types TopCat.sheafToTypes
/-- The sheaf of not-necessarily-continuous functions on `X` with values in a type `T`.
-/
def sheafToType (T : Type u) : Sheaf (Type u) X :=
⟨presheafToType X T, Presheaf.to_Type_isSheaf _ _⟩
#align Top.sheaf_to_Type TopCat.sheafToType
end TopCat
|
(** Algebra5
author Hidetsune Kobayashi
Group You Santo
Department of Mathematics
Nihon University
[email protected]
May 3, 2004.
April 6, 2007 (revised).
chapter 4. Ring theory (continued)
section 6. operation of ideals
section 7. direct product1, general case
section 8. Chinese remainder theorem
section 9. addition of finite elements of a ring and ideal_multiplication
section 10. extension and contraction
section 11. complete system of representatives
section 12. Polynomial ring
section 13. addition and multiplication of polyn_exprs
section 14. the degree of a polynomial
**)
theory Algebra5 imports Algebra4 begin
section "Operation of ideals"
lemma (in Ring) ideal_sumTr1:"\<lbrakk>ideal R A; ideal R B\<rbrakk> \<Longrightarrow>
A \<minusplus> B = \<Inter> {J. ideal R J \<and> (A \<union> B) \<subseteq> J}"
apply (frule sum_ideals[of "A" "B"], assumption,
frule sum_ideals_la1[of "A" "B"], assumption,
frule sum_ideals_la2[of "A" "B"], assumption)
apply (rule equalityI)
(* A \<minusplus>\<^sub>R B \<subseteq> \<Inter>{J. ideal R J \<and> A \<union> B \<subseteq> J} *)
apply (rule_tac A = "{J. ideal R J \<and> (A \<union> B) \<subseteq> J}" and C = "A \<minusplus> B" in
Inter_greatest)
apply (simp, (erule conjE)+)
apply (rule_tac A = A and B = B and I = X in sum_ideals_cont,
simp add:ideal_subset1, simp add:ideal_subset1, assumption+)
apply (rule_tac B = "A \<minusplus> B" and A = "{J. ideal R J \<and> (A \<union> B) \<subseteq> J}" in
Inter_lower)
apply simp
done
lemma (in Ring) sum_ideals_commute:"\<lbrakk>ideal R A; ideal R B\<rbrakk> \<Longrightarrow>
A \<minusplus> B = B \<minusplus> A"
apply (frule ideal_sumTr1 [of "B"], assumption+,
frule ideal_sumTr1 [of "A" "B"], assumption+)
apply (simp add:Un_commute[of "B" "A"])
done
lemma (in Ring) ideal_prod_mono1:"\<lbrakk>ideal R A; ideal R B; ideal R C;
A \<subseteq> B \<rbrakk> \<Longrightarrow> A \<diamondsuit>\<^sub>r C \<subseteq> B \<diamondsuit>\<^sub>r C"
apply (frule ideal_prod_ideal[of "B" "C"], assumption+)
apply (rule ideal_prod_subTr[of "A" "C" "B \<diamondsuit>\<^sub>r C"], assumption+)
apply (rule ballI)+
apply (frule_tac c = i in subsetD[of "A" "B"], assumption+)
apply (rule_tac i = i and j = j in prod_mem_prod_ideals[of "B" "C"],
assumption+)
done
lemma (in Ring) ideal_prod_mono2:"\<lbrakk>ideal R A; ideal R B; ideal R C;
A \<subseteq> B \<rbrakk> \<Longrightarrow> C \<diamondsuit>\<^sub>r A \<subseteq> C \<diamondsuit>\<^sub>r B"
apply (frule ideal_prod_mono1[of "A" "B" "C"], assumption+)
apply (simp add:ideal_prod_commute)
done
lemma (in Ring) cont_ideal_prod:"\<lbrakk>ideal R A; ideal R B; ideal R C;
A \<subseteq> C; B \<subseteq> C \<rbrakk> \<Longrightarrow> A \<diamondsuit>\<^sub>r B \<subseteq> C"
apply (simp add:ideal_prod_def)
apply (rule subsetI, simp)
apply (frule ideal_prod_ideal[of "A" "B"], assumption,
frule_tac a = "A \<diamondsuit>\<^sub>r B" in forall_spec,
thin_tac "\<forall>xa. ideal R xa \<and> {x. \<exists>i\<in>A. \<exists>j\<in>B. x = i \<cdot>\<^sub>r j} \<subseteq> xa \<longrightarrow> x \<in> xa",
simp)
apply (rule subsetI, simp, (erule bexE)+, simp add:prod_mem_prod_ideals)
apply (frule ideal_prod_la1[of "A" "B"], assumption,
frule_tac c = x in subsetD[of "A \<diamondsuit>\<^sub>r B" "A"], assumption+,
simp add:subsetD)
done
lemma (in Ring) ideal_distrib:"\<lbrakk>ideal R A; ideal R B; ideal R C\<rbrakk> \<Longrightarrow>
A \<diamondsuit>\<^sub>r (B \<minusplus> C) = A \<diamondsuit>\<^sub>r B \<minusplus> A \<diamondsuit>\<^sub>r C"
apply (frule sum_ideals[of "B" "C"], assumption,
frule ideal_prod_ideal[of "A" "B \<minusplus> C"], assumption+,
frule ideal_prod_ideal[of "A" "B"], assumption+,
frule ideal_prod_ideal[of "A" "C"], assumption+,
frule sum_ideals[of "A \<diamondsuit>\<^sub>r B" "A \<diamondsuit>\<^sub>r C"], assumption)
apply (rule equalityI)
apply (rule ideal_prod_subTr[of "A" "B \<minusplus> C" "A \<diamondsuit>\<^sub>r B \<minusplus> A \<diamondsuit>\<^sub>r C"], assumption+)
apply (rule ballI)+
apply (frule_tac x = j in ideals_set_sum[of B C], assumption+,
(erule bexE)+, simp) apply (
thin_tac "j = h \<plusminus> k",
frule_tac h = i in ideal_subset[of "A"], assumption+,
frule_tac h = h in ideal_subset[of "B"], assumption+,
frule_tac h = k in ideal_subset[of "C"], assumption+)
apply (simp add:ring_distrib1)
apply (frule_tac i = i and j = h in prod_mem_prod_ideals[of "A" "B"],
assumption+,
frule_tac i = i and j = k in prod_mem_prod_ideals[of "A" "C"],
assumption+)
apply (frule sum_ideals_la1[of "A \<diamondsuit>\<^sub>r B" "A \<diamondsuit>\<^sub>r C"], assumption+,
frule sum_ideals_la2[of "A \<diamondsuit>\<^sub>r B" "A \<diamondsuit>\<^sub>r C"], assumption+)
apply (frule_tac c = "i \<cdot>\<^sub>r h" in subsetD[of "A \<diamondsuit>\<^sub>r B" "A \<diamondsuit>\<^sub>r B \<minusplus> A \<diamondsuit>\<^sub>r C"],
assumption+,
frule_tac c = "i \<cdot>\<^sub>r k" in subsetD[of "A \<diamondsuit>\<^sub>r C" "A \<diamondsuit>\<^sub>r B \<minusplus> A \<diamondsuit>\<^sub>r C"],
assumption+)
apply (simp add:ideal_pOp_closed)
apply (rule sum_ideals_cont[of "A \<diamondsuit>\<^sub>r (B \<minusplus> C)" "A \<diamondsuit>\<^sub>r B" "A \<diamondsuit>\<^sub>r C" ],
assumption+)
apply (rule ideal_prod_subTr[of "A" "B" "A \<diamondsuit>\<^sub>r (B \<minusplus> C)"], assumption+)
apply (rule ballI)+
apply (frule sum_ideals_la1[of "B" "C"], assumption+,
frule_tac c = j in subsetD[of "B" "B \<minusplus> C"], assumption+,
rule_tac i = i and j = j in prod_mem_prod_ideals[of "A" "B \<minusplus> C"],
assumption+)
apply (rule ideal_prod_subTr[of "A" "C" "A \<diamondsuit>\<^sub>r (B \<minusplus> C)"], assumption+)
apply (rule ballI)+
apply (frule sum_ideals_la2[of "B" "C"], assumption+,
frule_tac c = j in subsetD[of "C" "B \<minusplus> C"], assumption+,
rule_tac i = i and j = j in prod_mem_prod_ideals[of "A" "B \<minusplus> C"],
assumption+)
done
definition
coprime_ideals::"[_, 'a set, 'a set] \<Rightarrow> bool" where
"coprime_ideals R A B \<longleftrightarrow> A \<minusplus>\<^bsub>R\<^esub> B = carrier R"
lemma (in Ring) coprimeTr:"\<lbrakk>ideal R A; ideal R B\<rbrakk> \<Longrightarrow>
coprime_ideals R A B = (\<exists>a \<in> A. \<exists>b \<in> B. a \<plusminus> b = 1\<^sub>r)"
apply (rule iffI)
apply (simp add:coprime_ideals_def)
apply (cut_tac ring_one, frule sym, thin_tac "A \<minusplus> B = carrier R", simp,
thin_tac "carrier R = A \<minusplus> B", frule ideals_set_sum[of A B],
assumption+, (erule bexE)+, frule sym, blast)
apply (erule bexE)+
apply (frule ideal_subset1[of A], frule ideal_subset1[of B])
apply (frule_tac a = a and b = b in set_sum_mem[of _ A _ B], assumption+)
apply (simp add:coprime_ideals_def)
apply (frule sum_ideals[of "A" "B"], assumption+,
frule ideal_inc_one[of "A \<minusplus> B"], assumption)
apply (simp add:coprime_ideals_def)
done
lemma (in Ring) coprime_int_prod:"\<lbrakk>ideal R A; ideal R B; coprime_ideals R A B\<rbrakk>
\<Longrightarrow> A \<inter> B = A \<diamondsuit>\<^sub>r B"
apply (frule ideal_prod_la1[of "A" "B"], assumption+,
frule ideal_prod_la2[of "A" "B"], assumption+)
apply (rule equalityI)
defer
(** A \<diamondsuit>\<^bsub>R\<^esub> B \<subseteq> A \<inter> B **)
apply simp
apply (simp add:coprime_ideals_def)
apply (frule int_ideal[of "A" "B"], assumption)
apply (frule idealprod_whole_r[of "A \<inter> B"])
apply (frule sym, thin_tac "A \<minusplus> B = carrier R", simp)
apply (simp add:ideal_distrib)
apply (simp add:ideal_prod_commute[of "A \<inter> B" "A"])
apply (cut_tac Int_lower1[of "A" "B"], cut_tac Int_lower2[of "A" "B"])
apply (frule ideal_prod_mono2[of "A \<inter> B" "B" "A"], assumption+,
frule ideal_prod_mono1[of "A \<inter> B" "A" "B"], assumption+)
apply (frule ideal_prod_ideal[of "A \<inter> B" "B"], assumption+,
frule ideal_prod_ideal[of "A" "A \<inter> B"], assumption+,
frule ideal_subset1[of "A \<diamondsuit>\<^sub>r (A \<inter> B)"],
frule ideal_subset1[of "(A \<inter> B) \<diamondsuit>\<^sub>r B"])
apply (frule ideal_prod_ideal[of A B], assumption+,
frule sum_ideals_cont[of "A \<diamondsuit>\<^sub>r B" "A \<diamondsuit>\<^sub>r (A \<inter> B)" "(A \<inter> B) \<diamondsuit>\<^sub>r B"],
assumption+)
apply simp
done
lemma (in Ring) coprime_elems:"\<lbrakk>ideal R A; ideal R B; coprime_ideals R A B\<rbrakk> \<Longrightarrow>
\<exists>a\<in>A. \<exists>b\<in>B. a \<plusminus> b = 1\<^sub>r"
by (simp add:coprimeTr)
lemma (in Ring) coprime_elemsTr:"\<lbrakk>ideal R A; ideal R B; a\<in>A; b\<in>B; a \<plusminus> b = 1\<^sub>r\<rbrakk>
\<Longrightarrow> pj R A b = 1\<^sub>r\<^bsub>(qring R A)\<^esub> \<and> pj R B a = 1\<^sub>r\<^bsub>(qring R B)\<^esub>"
apply (frule pj_Hom [OF Ring, of "A"],
frule pj_Hom [OF Ring, of "B"])
apply (frule qring_ring[of "A"], frule qring_ring[of "B"])
apply (cut_tac ring_is_ag,
frule Ring.ring_is_ag[of "R /\<^sub>r A"],
frule Ring.ring_is_ag[of "R /\<^sub>r B"])
apply (frule_tac a = a and b = b in aHom_add[of "R" "R /\<^sub>r A" "pj R A"],
assumption+,
simp add:rHom_def, simp add:ideal_subset,
simp add:ideal_subset, simp)
apply (frule ideal_subset[of "A" "a"], assumption,
frule ideal_subset[of "B" "b"], assumption+)
apply (simp only:pj_zero[OF Ring, THEN sym, of "A" "a"],
frule rHom_mem[of "pj R A" "R" "qring R A" "b"], assumption+,
simp add:aGroup.l_zero[of "R /\<^sub>r A"])
apply (simp add:rHom_one[OF Ring, of "qring R A"])
apply (frule_tac a = a and b = b in aHom_add[of "R" "R /\<^sub>r B" "pj R B"],
assumption+,
simp add:rHom_def, simp add:ideal_subset,
simp add:ideal_subset, simp)
apply (simp only:pj_zero[OF Ring, THEN sym, of "B" "b"],
frule rHom_mem[of "pj R B" "R" "qring R B" "a"], assumption+,
simp add:aGroup.ag_r_zero[of "R /\<^sub>r B"])
apply (simp add:rHom_one[OF Ring, of "qring R B"])
done
lemma (in Ring) partition_of_unity:"\<lbrakk>ideal R A; a \<in> A; b \<in> carrier R;
a \<plusminus> b = 1\<^sub>r; u \<in> carrier R; v \<in> carrier R\<rbrakk> \<Longrightarrow>
pj R A (a \<cdot>\<^sub>r v \<plusminus> b \<cdot>\<^sub>r u ) = pj R A u"
apply (frule pj_Hom [OF Ring, of "A"],
frule ideal_subset [of "A" "a"], assumption+,
frule ring_tOp_closed[of "a" "v"], assumption+,
frule ring_tOp_closed[of "b" "u"], assumption+,
frule qring_ring[of "A"])
apply (simp add:ringhom1[OF Ring, of "qring R A" "a \<cdot>\<^sub>r v" "b \<cdot>\<^sub>r u" "pj R A"])
apply (frule ideal_ring_multiple1[of "A" "a" "v"], assumption+,
simp add:pj_zero[OF Ring, THEN sym, of "A" "a \<cdot>\<^sub>r v"],
frule rHom_mem[of "pj R A" "R" "qring R A" "b \<cdot>\<^sub>r u"], assumption+,
simp add:Ring.l_zero, simp add:rHom_tOp[OF Ring])
apply (frule ringhom1[OF Ring, of "qring R A" "a" "b" "pj R A"], assumption+,
simp,
simp add:pj_zero[OF Ring, THEN sym, of "A" "a"],
frule rHom_mem[of "pj R A" "R" "qring R A" "b"], assumption+,
simp add:Ring.l_zero)
apply (simp add:rHom_one[OF Ring, of "qring R A" "pj R A"],
rotate_tac -2, frule sym, thin_tac "1\<^sub>r\<^bsub>R /\<^sub>r A\<^esub> = pj R A b",
simp,
rule Ring.ring_l_one[of "qring R A" "pj R A u"], assumption)
apply (simp add:rHom_mem)
done
lemma (in Ring) coprimes_commute:"\<lbrakk>ideal R A; ideal R B; coprime_ideals R A B \<rbrakk>
\<Longrightarrow> coprime_ideals R B A"
apply (simp add:coprime_ideals_def)
apply (simp add:sum_ideals_commute)
done
lemma (in Ring) coprime_surjTr:"\<lbrakk>ideal R A; ideal R B; coprime_ideals R A B;
X \<in> carrier (qring R A); Y \<in> carrier (qring R B) \<rbrakk> \<Longrightarrow>
\<exists>r\<in>carrier R. pj R A r = X \<and> pj R B r = Y"
apply (frule qring_ring [of "A"],
frule qring_ring [of "B"],
frule coprime_elems [of "A" "B"], assumption+,
frule pj_Hom [OF Ring, of "A"],
frule pj_Hom [OF Ring, of "B"])
apply (erule bexE)+
apply (simp add:qring_carrier[of "A"],
simp add:qring_carrier[of "B"], (erule bexE)+,
rename_tac a b u v)
apply (rotate_tac -1, frule sym, thin_tac "v \<uplus>\<^bsub>R\<^esub> B = Y",
rotate_tac -3, frule sym, thin_tac "u \<uplus>\<^bsub>R\<^esub> A = X", simp)
apply (frule_tac h = a in ideal_subset[of "A"], assumption+,
frule_tac h = b in ideal_subset[of "B"], assumption+,
frule_tac x = a and y = v in ring_tOp_closed, assumption+,
frule_tac x = b and y = u in ring_tOp_closed, assumption+,
cut_tac ring_is_ag,
frule_tac x = "a \<cdot>\<^sub>r v" and y = "b \<cdot>\<^sub>r u" in aGroup.ag_pOp_closed[of "R"],
assumption+)
apply (frule_tac a = a and b = b and u = u and v = v in
partition_of_unity[of "A"], assumption+,
simp add:pj_mem[OF Ring, of "A"])
apply (frule_tac a = b and b = a and u = v and v = u in
partition_of_unity[of "B"], assumption+,
subst aGroup.ag_pOp_commute[of "R"], assumption+,
simp add:pj_mem[OF Ring, of "B"])
apply (frule_tac x = "b \<cdot>\<^sub>r u" and y = "a \<cdot>\<^sub>r v" in
aGroup.ag_pOp_commute[of "R"], assumption+, simp)
apply (simp add:pj_mem[OF Ring], blast)
done
lemma (in Ring) coprime_n_idealsTr0:"\<lbrakk>ideal R A; ideal R B; ideal R C;
coprime_ideals R A C; coprime_ideals R B C \<rbrakk> \<Longrightarrow>
coprime_ideals R (A \<diamondsuit>\<^sub>r B) C"
apply (simp add:coprimeTr[of "A" "C"],
simp add:coprimeTr[of "B" "C"], (erule bexE)+)
apply (cut_tac ring_is_ag,
frule_tac h = a in ideal_subset[of "A"], assumption+,
frule_tac h = aa in ideal_subset[of "B"], assumption+,
frule_tac h = b in ideal_subset[of "C"], assumption+,
frule_tac h = ba in ideal_subset[of "C"], assumption+,
frule_tac x = a and y = b in aGroup.ag_pOp_closed, assumption+)
apply (frule_tac x = "a \<plusminus> b" and y = aa and z = ba in ring_distrib1,
assumption+) apply (
rotate_tac 6, frule sym, thin_tac "a \<plusminus> b = 1\<^sub>r",
frule sym, thin_tac "aa \<plusminus> ba = 1\<^sub>r")
apply (simp only:ring_distrib2)
apply (rotate_tac -1, frule sym, thin_tac "1\<^sub>r = a \<plusminus> b", simp,
thin_tac "aa \<plusminus> ba = 1\<^sub>r")
apply (simp add:ring_r_one,
thin_tac "a \<cdot>\<^sub>r aa \<plusminus> b \<cdot>\<^sub>r aa \<plusminus> (a \<cdot>\<^sub>r ba \<plusminus> b \<cdot>\<^sub>r ba) \<in> carrier R",
thin_tac "a \<plusminus> b = a \<cdot>\<^sub>r aa \<plusminus> b \<cdot>\<^sub>r aa \<plusminus> (a \<cdot>\<^sub>r ba \<plusminus> b \<cdot>\<^sub>r ba)")
apply (frule_tac x = a and y = aa in ring_tOp_closed, assumption+,
frule_tac x = b and y = aa in ring_tOp_closed, assumption+,
frule_tac x = a and y = ba in ring_tOp_closed, assumption+,
frule_tac x = b and y = ba in ring_tOp_closed, assumption+,
frule_tac x = "a \<cdot>\<^sub>r ba" and y = "b \<cdot>\<^sub>r ba" in aGroup.ag_pOp_closed,
assumption+)
apply (simp add:aGroup.ag_pOp_assoc,
frule sym, thin_tac "1\<^sub>r = a \<cdot>\<^sub>r aa \<plusminus> (b \<cdot>\<^sub>r aa \<plusminus> (a \<cdot>\<^sub>r ba \<plusminus> b \<cdot>\<^sub>r ba))")
apply (frule_tac i = a and j = aa in prod_mem_prod_ideals[of "A" "B"],
assumption+)
apply (frule_tac x = ba and r = a in ideal_ring_multiple[of "C"],
assumption+,
frule_tac x = ba and r = b in ideal_ring_multiple[of "C"],
assumption+,
frule_tac x = b and r = aa in ideal_ring_multiple1[of "C"],
assumption+)
apply (frule_tac I = C and x = "a \<cdot>\<^sub>r ba" and y = "b \<cdot>\<^sub>r ba" in
ideal_pOp_closed, assumption+,
frule_tac I = C and x = "b \<cdot>\<^sub>r aa" and y = "a \<cdot>\<^sub>r ba \<plusminus> b \<cdot>\<^sub>r ba" in
ideal_pOp_closed, assumption+)
apply (frule ideal_prod_ideal[of "A" "B"], assumption)
apply (subst coprimeTr, assumption+, blast)
done
lemma (in Ring) coprime_n_idealsTr1:"ideal R C \<Longrightarrow>
(\<forall>k \<le> n. ideal R (J k)) \<and> (\<forall>i \<le> n. coprime_ideals R (J i) C) \<longrightarrow>
coprime_ideals R (i\<Pi>\<^bsub>R,n\<^esub> J) C"
apply (induct_tac n)
apply (rule impI)
apply (erule conjE)
apply simp
apply (rule impI)
apply (erule conjE)
apply (cut_tac n = "Suc n" in n_in_Nsetn)
apply (cut_tac n = n in Nset_Suc) apply simp
apply (cut_tac n = n and J = J in n_prod_ideal,
rule allI, simp)
apply (rule_tac A = "i\<Pi>\<^bsub>R,n\<^esub> J" and B = "J (Suc n)" in
coprime_n_idealsTr0[of _ _ "C"], simp+)
done
lemma (in Ring) coprime_n_idealsTr2:"\<lbrakk>ideal R C; (\<forall>k \<le> n. ideal R (J k));
(\<forall>i \<le> n. coprime_ideals R (J i) C) \<rbrakk> \<Longrightarrow>
coprime_ideals R (i\<Pi>\<^bsub>R,n\<^esub> J) C"
by (simp add:coprime_n_idealsTr1)
lemma (in Ring) coprime_n_idealsTr3:"(\<forall>k \<le> (Suc n). ideal R (J k)) \<and>
(\<forall>i \<le> (Suc n). \<forall>j \<le> (Suc n). i \<noteq> j \<longrightarrow>
coprime_ideals R (J i) (J j)) \<longrightarrow> coprime_ideals R (i\<Pi>\<^bsub>R,n\<^esub> J) (J (Suc n))"
apply (rule impI, erule conjE)
apply (case_tac "n = 0", simp)
apply (simp add:Nset_1)
apply (cut_tac nat_eq_le[of "Suc n" "Suc n"],
frule_tac a = "Suc n" in forall_spec, assumption)
apply (rotate_tac 1, frule_tac a = "Suc n" in forall_spec, assumption,
thin_tac "\<forall>j\<le>Suc n. Suc n \<noteq> j \<longrightarrow> coprime_ideals R (J (Suc n)) (J j)")
apply (rule_tac C = "J (Suc n)" and n = n and J = J in coprime_n_idealsTr2,
assumption, rule allI, simp)
apply (rule allI, rule impI)
apply (frule_tac a = i in forall_spec, simp,
thin_tac "\<forall>i\<le>Suc n. \<forall>j\<le>Suc n. i \<noteq> j \<longrightarrow> coprime_ideals R (J i) (J j)",
rotate_tac -1,
frule_tac a = "Suc n" in forall_spec, assumption+)
apply simp+
done
lemma (in Ring) coprime_n_idealsTr4:"\<lbrakk>(\<forall>k \<le> (Suc n). ideal R (J k)) \<and>
(\<forall>i \<le> (Suc n). \<forall>j \<le> (Suc n). i \<noteq> j \<longrightarrow>
coprime_ideals R (J i) (J j))\<rbrakk> \<Longrightarrow> coprime_ideals R (i\<Pi>\<^bsub>R,n\<^esub> J) (J (Suc n))"
apply (simp add:coprime_n_idealsTr3)
done
section "Direct product1, general case"
definition
prod_tOp :: "['i set, 'i \<Rightarrow> ('a, 'm) Ring_scheme] \<Rightarrow>
('i \<Rightarrow> 'a) \<Rightarrow> ('i \<Rightarrow> 'a) \<Rightarrow> ('i \<Rightarrow> 'a)" where
"prod_tOp I A = (\<lambda>f\<in>carr_prodag I A. \<lambda>g\<in>carr_prodag I A.
\<lambda>x\<in>I. (f x) \<cdot>\<^sub>r\<^bsub>(A x)\<^esub> (g x))"
(** Let x \<in> I, then A x is a ring, {A x | x \<in> I} is a set of rings. **)
definition
prod_one::"['i set, 'i \<Rightarrow> ('a, 'm) Ring_scheme] \<Rightarrow> ('i \<Rightarrow> 'a)" where
"prod_one I A == \<lambda>x\<in>I. 1\<^sub>r\<^bsub>(A x)\<^esub>"
(** 1\<^sub>(A x) is the unit of a ring A x. **)
definition
prodrg :: "['i set, 'i \<Rightarrow> ('a, 'more) Ring_scheme] \<Rightarrow> ('i \<Rightarrow> 'a) Ring" where
"prodrg I A = \<lparr>carrier = carr_prodag I A, pop = prod_pOp I A, mop =
prod_mOp I A, zero = prod_zero I A, tp = prod_tOp I A,
un = prod_one I A \<rparr>"
(** I is the index set **)
abbreviation
PRODRING ("(r\<Pi>\<^bsub>_\<^esub>/ _)" [72,73]72) where
"r\<Pi>\<^bsub>I\<^esub> A == prodrg I A"
definition
augm_func :: "[nat, nat \<Rightarrow> 'a,'a set, nat, nat \<Rightarrow> 'a, 'a set] \<Rightarrow> nat \<Rightarrow> 'a" where
"augm_func n f A m g B = (\<lambda>i\<in>{j. j \<le> (n + m)}. if i \<le> n then f i else
if (Suc n) \<le> i \<and> i \<le> n + m then g ((sliden (Suc n)) i) else undefined)"
(* Remark. g is a function of Nset (m - 1) \<rightarrow> B *)
definition
ag_setfunc :: "[nat, nat \<Rightarrow> ('a, 'more) Ring_scheme, nat,
nat \<Rightarrow> ('a, 'more) Ring_scheme] \<Rightarrow> (nat \<Rightarrow> 'a) set \<Rightarrow> (nat \<Rightarrow> 'a) set
\<Rightarrow> (nat \<Rightarrow> 'a) set" where
"ag_setfunc n B1 m B2 X Y =
{f. \<exists>g. \<exists>h. (g\<in>X) \<and>(h\<in>Y) \<and>(f = (augm_func n g (Un_carrier {j. j \<le> n} B1)
m h (Un_carrier {j. j \<le> (m - 1)} B2)))}"
(* Later we consider X = ac_Prod_Rg (Nset n) B1 and Y = ac_Prod_Rg (Nset (m - 1)) B2 *)
primrec
ac_fProd_Rg :: "[nat, nat \<Rightarrow> ('a, 'more) Ring_scheme] \<Rightarrow>
(nat \<Rightarrow> 'a) set"
where
fprod_0: "ac_fProd_Rg 0 B = carr_prodag {0::nat} B"
| frpod_n: "ac_fProd_Rg (Suc n) B = ag_setfunc n B (Suc 0) (compose {0::nat}
B (slide (Suc n))) (carr_prodag {j. j \<le> n} B) (carr_prodag {0} (compose {0} B (slide (Suc n))))"
definition
prodB1 :: "[('a, 'm) Ring_scheme, ('a, 'm) Ring_scheme] \<Rightarrow>
(nat \<Rightarrow> ('a, 'm) Ring_scheme)" where
"prodB1 R S = (\<lambda>k. if k=0 then R else if k=Suc 0 then S else
undefined)"
definition
Prod2Rg :: "[('a, 'm) Ring_scheme, ('a, 'm) Ring_scheme]
\<Rightarrow> (nat \<Rightarrow> 'a) Ring" (infixl "\<Oplus>\<^sub>r" 80) where
"A1 \<Oplus>\<^sub>r A2 = prodrg {0, Suc 0} (prodB1 A1 A2)"
text \<open>Don't try \<open>(Prod_ring (Nset n) B) \<Oplus>\<^sub>r (B (Suc n))\<close>\<close>
lemma carr_prodrg_mem_eq:"\<lbrakk>f \<in> carrier (r\<Pi>\<^bsub>I\<^esub> A); g \<in> carrier (r\<Pi>\<^bsub>I\<^esub> A);
\<forall>i\<in>I. f i = g i \<rbrakk> \<Longrightarrow> f = g"
by (simp add:prodrg_def carr_prodag_def, (erule conjE)+,
rule funcset_eq[of _ I], assumption+)
lemma prod_tOp_mem:"\<lbrakk>\<forall>k\<in>I. Ring (A k); X \<in> carr_prodag I A;
Y \<in> carr_prodag I A\<rbrakk> \<Longrightarrow> prod_tOp I A X Y \<in> carr_prodag I A"
apply (subst carr_prodag_def, simp)
apply (rule conjI)
apply (simp add:prod_tOp_def restrict_def extensional_def)
apply (rule conjI)
apply (rule Pi_I)
apply (simp add:Un_carrier_def prod_tOp_def)
apply (simp add:carr_prodag_def, (erule conjE)+)
apply (blast dest: Ring.ring_tOp_closed del:PiE)
apply (rule ballI)
apply (simp add:prod_tOp_def)
apply (simp add:carr_prodag_def, (erule conjE)+)
apply (simp add:Ring.ring_tOp_closed)
done
lemma prod_tOp_func:"\<forall>k\<in>I. Ring (A k) \<Longrightarrow>
prod_tOp I A \<in> carr_prodag I A \<rightarrow> carr_prodag I A \<rightarrow> carr_prodag I A"
by (simp add:prod_tOp_mem)
lemma prod_one_func:"\<forall>k\<in>I. Ring (A k) \<Longrightarrow>
prod_one I A \<in> carr_prodag I A"
apply (simp add:prod_one_def carr_prodag_def)
apply (rule conjI)
apply (rule Pi_I)
apply (simp add:Un_carrier_def)
apply (blast dest: Ring.ring_one)
apply (simp add: Ring.ring_one)
done
lemma prodrg_carrier:"\<forall>k\<in>I. Ring (A k) \<Longrightarrow>
carrier (prodrg I A) = carrier (prodag I A)"
by (simp add:prodrg_def prodag_def)
lemma prodrg_ring:"\<forall>k\<in>I. Ring (A k) \<Longrightarrow> Ring (prodrg I A)"
apply (rule Ring.intro)
apply (simp add:prodrg_def)
apply (rule prod_pOp_func,
rule ballI, simp add:Ring.ring_is_ag)
apply (simp add:prodrg_def, rule prod_pOp_assoc,
simp add:Ring.ring_is_ag, assumption+)
apply (simp add:prodrg_def, rule prod_pOp_commute,
simp add:Ring.ring_is_ag, assumption+)
apply (simp add:prodrg_def, rule prod_mOp_func,
simp add:Ring.ring_is_ag)
apply (simp add:prodrg_def)
apply (cut_tac X = a in prod_mOp_mem[of "I" "A"])
apply (simp add:Ring.ring_is_ag, assumption)
apply (cut_tac X = "prod_mOp I A a" and Y = a in prod_pOp_mem[of "I" "A"],
simp add:Ring.ring_is_ag, assumption+,
cut_tac prod_zero_func[of "I" "A"])
apply (rule carr_prodag_mem_eq[of "I" "A"],
simp add:Ring.ring_is_ag, assumption+,
rule ballI, simp add:prod_pOp_def,
subst prod_mOp_mem_i, simp add:Ring.ring_is_ag, assumption+,
subst prod_zero_i, simp add:Ring.ring_is_ag, assumption+,
rule aGroup.l_m, simp add:Ring.ring_is_ag,
simp add:prodag_comp_i, simp add:Ring.ring_is_ag)
apply (simp add:prodrg_def,
rule prod_zero_func, simp add:Ring.ring_is_ag)
apply (simp add:prodrg_def,
cut_tac prod_zero_func[of "I" "A"],
cut_tac X = "prod_zero I A" and Y = a in prod_pOp_mem[of "I" "A"],
simp add:Ring.ring_is_ag, assumption+,
rule carr_prodag_mem_eq[of "I" "A"],
simp add:Ring.ring_is_ag, assumption+)
apply (rule ballI)
apply (simp add:prod_pOp_def prod_zero_def)
apply (rule aGroup.ag_l_zero, simp add:Ring.ring_is_ag)
apply (simp add:prodag_comp_i, simp add:Ring.ring_is_ag)
apply (simp add:prodrg_def,
rule prod_tOp_func, simp add:Ring.ring_is_ag)
apply (simp add:prodrg_def)
apply (frule_tac X = a and Y = b in prod_tOp_mem[of "I" "A"], assumption+,
frule_tac X = "prod_tOp I A a b" and Y = c in
prod_tOp_mem[of "I" "A"], assumption+,
frule_tac X = b and Y = c in prod_tOp_mem[of "I" "A"], assumption+,
frule_tac X = a and Y = "prod_tOp I A b c" in
prod_tOp_mem[of "I" "A"], assumption+)
apply (rule carr_prodag_mem_eq[of "I" "A"],
simp add:Ring.ring_is_ag, assumption+, rule ballI)
apply (simp add:prod_tOp_def)
apply (rule Ring.ring_tOp_assoc, simp, (simp add:prodag_comp_i)+)
apply (simp add:prodrg_def)
apply (frule_tac X = a and Y = b in prod_tOp_mem[of "I" "A"], assumption+,
frule_tac X = b and Y = a in prod_tOp_mem[of "I" "A"], assumption+,
rule carr_prodag_mem_eq[of "I" "A"],
simp add:Ring.ring_is_ag, assumption+)
apply (rule ballI, simp add:prod_tOp_def)
apply (rule Ring.ring_tOp_commute, (simp add:prodag_comp_i)+)
apply (simp add:prodrg_def, rule prod_one_func, assumption)
apply (simp add:prodrg_def)
apply (cut_tac X = b and Y = c in prod_pOp_mem[of "I" "A"],
simp add:Ring.ring_is_ag, assumption+,
cut_tac X = a and Y = b in prod_tOp_mem[of "I" "A"], assumption+,
cut_tac X = a and Y = c in prod_tOp_mem[of "I" "A"], assumption+,
cut_tac X = "prod_tOp I A a b" and Y = "prod_tOp I A a c" in
prod_pOp_mem[of "I" "A"], simp add:Ring.ring_is_ag, assumption+)
apply (rule carr_prodag_mem_eq[of "I" "A"],
simp add:Ring.ring_is_ag, rule prod_tOp_mem[of "I" "A"], assumption+)
apply (rule ballI, simp add:prod_tOp_def prod_pOp_def)
apply (rule Ring.ring_distrib1, (simp add:prodag_comp_i)+)
apply (simp add:prodrg_def,
cut_tac prod_one_func[of "I" "A"],
cut_tac X = "prod_one I A" and Y = a in prod_tOp_mem[of "I" "A"],
assumption+)
apply (rule carr_prodag_mem_eq[of "I" "A"],
simp add:Ring.ring_is_ag, assumption+,
rule ballI, simp add:prod_tOp_def prod_one_def,
rule Ring.ring_l_one, simp, simp add:prodag_comp_i)
apply simp
done
lemma prodrg_elem_extensional:"\<lbrakk>\<forall>k\<in>I. Ring (A k); f \<in> carrier (prodrg I A)\<rbrakk>
\<Longrightarrow> f \<in> extensional I"
apply (simp add:prodrg_carrier)
apply (simp add:prodag_def carr_prodag_def)
done
lemma prodrg_pOp:"\<forall>k\<in>I. Ring (A k) \<Longrightarrow>
pop (prodrg I A) = prod_pOp I A"
apply (simp add:prodrg_def)
done
lemma prodrg_mOp:"\<forall>k\<in>I. Ring (A k) \<Longrightarrow>
mop (prodrg I A) = prod_mOp I A"
apply (simp add:prodrg_def)
done
lemma prodrg_zero:"\<forall>k\<in>I. Ring (A k) \<Longrightarrow>
zero (prodrg I A) = prod_zero I A"
apply (simp add:prodrg_def)
done
lemma prodrg_tOp:"\<forall>k\<in>I. Ring (A k) \<Longrightarrow>
tp (prodrg I A) = prod_tOp I A"
apply (simp add:prodrg_def)
done
lemma prodrg_one:"\<forall>k\<in>I. Ring (A k) \<Longrightarrow>
un (prodrg I A) = prod_one I A"
apply (simp add:prodrg_def)
done
lemma prodrg_sameTr5:"\<lbrakk>\<forall>k\<in>I. Ring (A k); \<forall>k\<in>I. A k = B k\<rbrakk>
\<Longrightarrow> prod_tOp I A = prod_tOp I B"
apply (frule prod_tOp_func)
apply (subgoal_tac "carr_prodag I A = carr_prodag I B", simp)
apply (frule prod_tOp_func [of "I" "B"])
apply (rule funcset_eq [of _ "carr_prodag I B" _])
apply (simp add:prod_tOp_def extensional_def)
apply (simp add:prod_tOp_def extensional_def)
apply (rule ballI)
apply (frule_tac x = x in funcset_mem [of "prod_tOp I A" "carr_prodag I B"
"carr_prodag I B \<rightarrow> carr_prodag I B"], assumption+)
apply (frule_tac x = x in funcset_mem [of "prod_tOp I B" "carr_prodag I B"
"carr_prodag I B \<rightarrow> carr_prodag I B"], assumption+)
apply (thin_tac " prod_tOp I A
\<in> carr_prodag I B \<rightarrow> carr_prodag I B \<rightarrow> carr_prodag I B")
apply (thin_tac "prod_tOp I B
\<in> carr_prodag I B \<rightarrow> carr_prodag I B \<rightarrow> carr_prodag I B")
apply (rule funcset_eq [of _ "carr_prodag I B"])
apply (simp add:prod_tOp_def extensional_def)
apply (simp add:prod_tOp_def extensional_def)
apply (rule ballI)
apply (frule_tac f = "prod_tOp I A x" and A = "carr_prodag I B" and
x = xa in funcset_mem, assumption+)
apply (frule_tac f = "prod_tOp I B x" and A = "carr_prodag I B" and
x = xa in funcset_mem, assumption+)
apply (subgoal_tac "\<forall>k\<in>I. aGroup (B k)")
apply (rule carr_prodag_mem_eq, assumption+)
apply (rule ballI, simp add:prod_tOp_def)
apply (rule ballI, rule Ring.ring_is_ag, simp)
apply (subgoal_tac "\<forall>k\<in>I. aGroup (A k)")
apply (simp add:prodag_sameTr1)
apply (rule ballI, rule Ring.ring_is_ag, simp)
done
lemma prodrg_sameTr6:"\<lbrakk>\<forall>k\<in>I. Ring (A k); \<forall>k\<in>I. A k = B k\<rbrakk>
\<Longrightarrow> prod_one I A = prod_one I B"
apply (frule prod_one_func [of "I" "A"])
apply (cut_tac prodag_sameTr1[of "I" "A" "B"])
apply (rule carr_prodag_mem_eq[of I A "prod_one I A" "prod_one I B"])
apply (simp add:Ring.ring_is_ag, assumption)
apply (cut_tac prod_one_func [of "I" "B"], simp)
apply simp
apply (rule ballI, simp add:prod_one_def)
apply (simp add:Ring.ring_is_ag, simp)
done
lemma prodrg_same:"\<lbrakk>\<forall>k\<in>I. Ring (A k); \<forall>k\<in>I. A k = B k\<rbrakk>
\<Longrightarrow> prodrg I A = prodrg I B"
apply (subgoal_tac "\<forall>k\<in>I. aGroup (A k)")
apply (frule prodag_sameTr1, assumption+)
apply (frule prodag_sameTr2, assumption+)
apply (frule prodag_sameTr3, assumption+)
apply (frule prodag_sameTr4, assumption+)
apply (frule prodrg_sameTr5, assumption+)
apply (frule prodrg_sameTr6, assumption+)
apply (simp add:prodrg_def)
apply (rule ballI, rule Ring.ring_is_ag, simp)
done
lemma prodrg_component:"\<lbrakk>f \<in> carrier (prodrg I A); i \<in> I\<rbrakk> \<Longrightarrow>
f i \<in> carrier (A i)"
by (simp add:prodrg_def carr_prodag_def)
lemma project_rhom:"\<lbrakk>\<forall>k\<in>I. Ring (A k); j \<in> I\<rbrakk> \<Longrightarrow>
PRoject I A j \<in> rHom ( prodrg I A) (A j)"
apply (simp add:rHom_def)
apply (rule conjI)
apply (simp add:aHom_def)
apply (rule conjI)
apply (rule Pi_I)
apply (simp add:prodrg_carrier)
apply (cut_tac prodag_carrier[of I A], simp)
apply (simp add:PRoject_def)
apply (cut_tac prodag_carrier[of I A], simp,
thin_tac "carrier (a\<Pi>\<^bsub>I\<^esub> A) = carr_prodag I A")
apply (simp add:prodag_comp_i)
apply (simp add:Ring.ring_is_ag)
apply (simp add:Ring.ring_is_ag)
apply (subgoal_tac "\<forall>k\<in>I. aGroup (A k)")
apply (frule project_aHom [of "I" "A" "j"], assumption+)
apply (rule conjI)
apply (simp add:prodrg_carrier aHom_def)
apply (simp add:prodrg_carrier)
apply (simp add:prodrg_pOp)
apply (simp add:prodag_pOp[THEN sym])
apply (simp add:aHom_def)
apply (rule ballI, simp add:Ring.ring_is_ag)
apply (rule conjI)
apply (rule ballI)+
apply (simp add:prodrg_carrier)
apply (cut_tac prodag_carrier[of I A], simp)
apply (frule_tac X = x and Y = y in prod_tOp_mem[of I A], assumption+)
apply (simp add:prodrg_tOp)
apply (simp add:PRoject_def)
apply (simp add:prod_tOp_def)
apply (rule ballI)
apply (simp add:Ring.ring_is_ag)
apply (frule prodrg_ring [of "I" "A"])
apply (frule Ring.ring_one[of "r\<Pi>\<^bsub>I\<^esub> A"])
apply (simp add:prodrg_carrier)
apply (cut_tac prodag_carrier[of I A], simp)
apply (simp add:PRoject_def) apply (simp add:prodrg_def)
apply (fold prodrg_def) apply (simp add:prod_one_def)
apply (rule ballI)
apply (simp add:Ring.ring_is_ag)
done
lemma augm_funcTr:"\<lbrakk>\<forall>k \<le>(Suc n). Ring (B k);
f \<in> carr_prodag {i. i \<le> (Suc n)} B\<rbrakk> \<Longrightarrow>
f = augm_func n (restrict f {i. i \<le> n}) (Un_carrier {i. i \<le> n} B) (Suc 0)
(\<lambda>x\<in>{0::nat}. f (x + Suc n))
(Un_carrier {0} (compose {0} B (slide (Suc n))))"
apply (rule carr_prodag_mem_eq [of "{i. i \<le> (Suc n)}" "B" "f"
"augm_func n (restrict f {i. i \<le> n}) (Un_carrier {i. i \<le> n} B) (Suc 0)
(\<lambda>x\<in>{0}. f (x + Suc n)) (Un_carrier {0} (compose {0} B (slide (Suc n))))"])
apply (rule ballI, simp add:Ring.ring_is_ag)
apply (simp add:augm_func_def)
apply (simp add:carr_prodag_def)
apply (rule conjI)
apply (simp add:augm_func_def)
apply (rule conjI)
apply (rule Pi_I)
apply (simp add:augm_func_def sliden_def)
apply (erule conjE)+
apply (frule_tac x = x in funcset_mem[of f "{i. i \<le> Suc n}"
"Un_carrier {i. i \<le> Suc n} B"]) apply simp
apply simp
apply (rule impI)
apply (rule_tac x = "Suc n" in funcset_mem[of f "{i. i \<le> Suc n}"
"Un_carrier {i. i \<le> Suc n} B"], assumption) apply simp
apply (rule allI, (erule conjE)+)
apply (simp add:augm_func_def)
apply (case_tac "i \<le> n", simp add:sliden_def)
apply (simp add:sliden_def, rule impI)
apply (simp add:nat_not_le_less,
frule_tac m = n and n = i in Suc_leI,
frule_tac m = i and n = "Suc n" in Nat.le_antisym, assumption+,
simp)
apply (rule ballI, simp)
apply (simp add:augm_func_def sliden_def)
apply (rule impI, simp add:nat_not_le_less)
apply (frule_tac n = l in Suc_leI[of n _])
apply (frule_tac m = l and n = "Suc n" in Nat.le_antisym, assumption+,
simp)
done
lemma A_to_prodag_mem:"\<lbrakk>Ring A; \<forall>k\<in>I. Ring (B k); \<forall>k\<in>I. (S k) \<in>
rHom A (B k); x \<in> carrier A \<rbrakk> \<Longrightarrow> A_to_prodag A I S B x \<in> carr_prodag I B"
apply (simp add:carr_prodag_def)
apply (rule conjI)
apply (simp add:A_to_prodag_def extensional_def)
apply (rule conjI)
apply (rule Pi_I)
apply (simp add: A_to_prodag_def)
apply (subgoal_tac "(S xa) \<in> rHom A (B xa)") prefer 2 apply simp
apply (thin_tac "\<forall>k\<in>I. S k \<in> rHom A (B k)")
apply (frule_tac f = "S xa" and A = A and R = "B xa" in rHom_mem, assumption+)
apply (simp add:Un_carrier_def) apply blast
apply (rule ballI)
apply (simp add:A_to_prodag_def)
apply (rule_tac f = "S i" and A = A and R = "B i" and a = x in rHom_mem)
apply simp
apply assumption
done
lemma A_to_prodag_rHom:"\<lbrakk>Ring A; \<forall>k\<in>I. Ring (B k); \<forall>k\<in>I. (S k) \<in>
rHom A (B k) \<rbrakk> \<Longrightarrow> A_to_prodag A I S B \<in> rHom A (r\<Pi>\<^bsub>I\<^esub> B)"
apply (simp add:rHom_def [of "A" "r\<Pi>\<^bsub>I\<^esub> B"])
apply (rule conjI)
apply (cut_tac A_to_prodag_aHom[of A I B S])
apply (subst aHom_def, simp)
apply (simp add:prodrg_carrier)
apply (simp add:aHom_def)
apply (simp add:prodrg_def)
apply (cut_tac prodag_pOp[of I B], simp)
apply (rule ballI, simp add:Ring.ring_is_ag,
simp add:Ring.ring_is_ag,
rule ballI, simp add:Ring.ring_is_ag)
apply (rule ballI)
apply (simp add:rHom_def)
apply (rule conjI)
apply (rule ballI)+
apply (frule_tac x = x and y = y in Ring.ring_tOp_closed[of A], assumption+)
apply (frule_tac x = "x \<cdot>\<^sub>r\<^bsub>A\<^esub> y" in A_to_prodag_mem[of A I B S], assumption+,
frule_tac x = x in A_to_prodag_mem[of A I B S], assumption+,
frule_tac x = y in A_to_prodag_mem[of A I B S], assumption+)
apply (simp add:prodrg_tOp[of I B])
apply (frule_tac X = "A_to_prodag A I S B x " and Y = "A_to_prodag A I S B y" in prod_tOp_mem[of I B], assumption+)
apply (cut_tac X = "A_to_prodag A I S B (x \<cdot>\<^sub>r\<^bsub>A\<^esub> y)" and Y = "prod_tOp I B (A_to_prodag A I S B x) (A_to_prodag A I S B y)" in carr_prodag_mem_eq[of I B])
apply (rule ballI, simp add:Ring.ring_is_ag) apply assumption+
apply (rule ballI, simp add:prod_tOp_def A_to_prodag_def)
apply (frule_tac x = l in bspec, assumption,
thin_tac "\<forall>k\<in>I. Ring (B k)",
frule_tac x = l in bspec, assumption,
thin_tac "\<forall>k\<in>I. S k \<in> rHom A (B k)")
apply (simp add:rHom_tOp) apply simp
apply (simp add:prodrg_one[of I B])
apply (frule prod_one_func[of I B])
apply (frule Ring.ring_one[of A],
frule_tac x = "1\<^sub>r\<^bsub>A\<^esub>" in A_to_prodag_mem[of A I B S], assumption+)
apply (cut_tac X = "A_to_prodag A I S B 1\<^sub>r\<^bsub>A\<^esub>" and Y = "prod_one I B" in
carr_prodag_mem_eq[of I B])
apply (rule ballI, simp add:Ring.ring_is_ag)
apply assumption+
apply (rule ballI)
apply (subst A_to_prodag_def, simp add:prod_one_def)
apply (frule_tac x = l in bspec, assumption,
thin_tac "\<forall>k\<in>I. Ring (B k)",
frule_tac x = l in bspec, assumption,
thin_tac "\<forall>k\<in>I. S k \<in> rHom A (B k)")
apply (simp add:rHom_one)
apply assumption
done
lemma ac_fProd_ProdTr1:"\<forall>k \<le> (Suc n). Ring (B k) \<Longrightarrow>
ag_setfunc n B (Suc 0) (compose {0::nat} B (slide (Suc n)))
(carr_prodag {i. i \<le> n} B) (carr_prodag {0}
(compose {0} B (slide (Suc n)))) \<subseteq> carr_prodag {i. i \<le> (Suc n)} B"
apply (rule subsetI)
apply (simp add:ag_setfunc_def)
apply (erule exE, erule conjE, erule exE, erule conjE)
apply (simp,
thin_tac "x =
augm_func n g (Un_carrier {j. j \<le> n} B) (Suc 0) h
(Un_carrier {0} (compose {0} B (slide (Suc n))))")
apply (simp add:carr_prodag_def [of "{j. j \<le> (Suc n)}" "B"])
apply (rule conjI)
apply (simp add:augm_func_def)
apply (rule conjI)
apply (simp add:Pi_def) apply (rule allI) apply (rule impI)
apply (simp add:augm_func_def)
apply (case_tac "x \<le> n")
apply simp apply (simp add:carr_prodag_def)
apply (erule conjE)+ apply (frule_tac x = x in mem_of_Nset [of _ "n"])
apply (frule_tac f = g and x = x in funcset_mem[of _ "{j. j \<le> n}"
"Un_carrier {j. j \<le> n} B"], assumption+)
apply (simp add:Un_carrier_def,
erule exE, erule conjE, erule exE, simp, erule conjE,
frule_tac x = i and y = n and z = "Suc n" in le_less_trans,
simp,
frule_tac x = i and y = "Suc n" in less_imp_le, blast)
apply (simp add:sliden_def)
apply (simp add:carr_prodag_def Un_carrier_def, (erule conjE)+)
apply (simp add:compose_def slide_def)
apply (cut_tac n_in_Nsetn[of "Suc n"], blast)
apply (rule allI, rule impI)
apply (simp add:augm_func_def)
apply (case_tac "i \<le> n", simp)
apply (simp add:carr_prodag_def [of "{i. i \<le> n}" _])
apply simp apply (thin_tac "g \<in> carr_prodag {i. i \<le> n} B")
apply (simp add: not_less [symmetric, of _ n],
frule_tac n = i in Suc_leI[of n],
frule_tac m = i and n = "Suc n" in le_antisym, assumption+, simp)
apply (simp add:carr_prodag_def compose_def slide_def sliden_def)
done
lemma ac_fProd_Prod:"\<forall>k \<le> n. Ring (B k) \<Longrightarrow>
ac_fProd_Rg n B = carr_prodag {j. j \<le> n} B"
apply (case_tac "n = 0")
apply simp
apply (subgoal_tac "\<exists>m. n = Suc m")
apply (subgoal_tac "\<forall>m. n = Suc m \<longrightarrow>
ac_fProd_Rg n B = carr_prodag {j. j \<le> n} B")
apply blast apply (thin_tac "\<exists>m. n = Suc m")
apply (rule allI, rule impI) apply (simp, thin_tac "n = Suc m")
apply (rule equalityI)
apply (simp add:ac_fProd_ProdTr1)
apply (rule subsetI)
apply (rename_tac m f)
apply (frule augm_funcTr, assumption+)
apply (simp add:ag_setfunc_def)
apply (subgoal_tac "(restrict f {j. j \<le> m}) \<in> carr_prodag {j. j \<le> m} B")
apply (subgoal_tac "(\<lambda>x\<in>{0::nat}. f (Suc (x + m))) \<in> carr_prodag {0}
(compose {0} B (slide (Suc m)))")
apply blast
apply (thin_tac "f =
augm_func m (restrict f {i. i \<le> m}) (Un_carrier {i. i \<le> m} B)
(Suc 0) (\<lambda>x\<in>{0}. f (Suc (x + m)))
(Un_carrier {0} (compose {0} B (slide (Suc m))))")
apply (simp add:carr_prodag_def)
apply (rule conjI)
apply (simp add:Pi_def restrict_def)
apply (simp add:Un_carrier_def compose_def slide_def)
apply (simp add:compose_def slide_def)
apply (thin_tac "f =
augm_func m (restrict f {i. i \<le> m}) (Un_carrier {i. i \<le> m} B)
(Suc 0) (\<lambda>x\<in>{0}. f (Suc (x + m)))
(Un_carrier {0} (compose {0} B (slide (Suc m))))")
apply (simp add:carr_prodag_def)
apply (simp add:Un_carrier_def)
apply (simp add:Pi_def)
apply (rule allI) apply (rule impI)
apply (erule conjE)+
apply (rotate_tac 1)
apply (frule_tac a = x in forall_spec, simp)
apply (erule exE,
thin_tac "\<forall>x\<le>Suc m. \<exists>xa. (\<exists>i\<le>Suc m. xa = carrier (B i)) \<and> f x \<in> xa")
apply (frule_tac a = x in forall_spec, simp)
apply blast
apply (cut_tac t = n in Suc_pred[THEN sym], simp)
apply blast
done
text\<open>A direct product of a finite number of rings defined with
\<open>ac_fProd_Rg\<close> is equal to that defined by using \<open>carr_prodag\<close>.\<close>
definition
fprodrg :: "[nat, nat \<Rightarrow> ('a, 'more) Ring_scheme] \<Rightarrow>
\<lparr>carrier:: (nat \<Rightarrow> 'a) set, pop::[(nat \<Rightarrow> 'a), (nat \<Rightarrow> 'a)]
\<Rightarrow> (nat \<Rightarrow> 'a), mop:: (nat \<Rightarrow> 'a) \<Rightarrow> (nat \<Rightarrow> 'a), zero::(nat \<Rightarrow> 'a),
tp :: [(nat \<Rightarrow> 'a), (nat \<Rightarrow> 'a)] \<Rightarrow> (nat \<Rightarrow> 'a), un :: (nat \<Rightarrow> 'a) \<rparr>" where
"fprodrg n B = \<lparr> carrier = ac_fProd_Rg n B,
pop = \<lambda>f. \<lambda>g. prod_pOp {i. i \<le> n} B f g, mop = \<lambda>f. prod_mOp {i. i \<le> n} B f,
zero = prod_zero {i. i \<le> n} B, tp = \<lambda>f. \<lambda>g. prod_tOp {i. i \<le> n} B f g,
un = prod_one {i. i \<le> n} B \<rparr>"
definition
fPRoject ::"[nat, nat \<Rightarrow> ('a, 'more) Ring_scheme, nat]
\<Rightarrow> (nat \<Rightarrow> 'a) \<Rightarrow> 'a" where
"fPRoject n B x = (\<lambda>f\<in>ac_fProd_Rg n B. f x)"
lemma fprodrg_ring:"\<forall>k \<le> n. Ring (B k) \<Longrightarrow> Ring (fprodrg n B)"
apply (simp add:fprodrg_def)
apply (frule ac_fProd_Prod)
apply simp
apply (fold prodrg_def)
apply (simp add:prodrg_ring)
done
section "Chinese remainder theorem"
lemma Chinese_remTr1:"\<lbrakk>Ring A; \<forall>k \<le> (n::nat). ideal A (J k);
\<forall>k \<le> n. B k = qring A (J k); \<forall>k \<le> n. S k = pj A (J k) \<rbrakk> \<Longrightarrow>
ker\<^bsub>A,(r\<Pi>\<^bsub>{j. j \<le> n}\<^esub> B)\<^esub> (A_to_prodag A {j. j \<le> n} S B) =
\<Inter> {I. \<exists>k\<in>{j. j \<le> n}. I = (J k)}"
apply (rule equalityI)
apply (rule subsetI)
apply (simp add:ker_def)
apply (rule allI, rule impI)
apply (rename_tac a K, erule conjE)
apply (simp add:prodrg_def, simp add:A_to_prodag_def prod_one_def)
apply (erule exE, erule conjE)
apply (subgoal_tac "(\<lambda>k\<in>{j. j \<le> n}. S k a) k = (\<lambda>x\<in>{j. j \<le> n}. \<zero>\<^bsub>B x\<^esub>) k")
apply (thin_tac "(\<lambda>k\<in>{j. j \<le> n}. S k a) = prod_zero {j. j \<le> n} B")
apply simp apply (frule_tac I = "J k" in Ring.qring_zero [of "A"])
apply simp
apply (frule_tac I = "J k" and x = a in pj_mem [of "A"]) apply simp
apply assumption apply simp
apply (frule_tac I = "J k" and a = a in Ring.a_in_ar_coset [of "A"])
apply simp apply assumption apply simp
apply (simp add:prod_zero_def)
apply (rule subsetI)
apply (simp add:CollectI ker_def)
apply (cut_tac Nset_inc_0[of n])
apply (frule_tac a = "J 0" in forall_spec, blast)
apply (frule_tac x = 0 in spec, simp)
apply (frule_tac h = x in Ring.ideal_subset [of "A" "J 0"], simp+)
apply (thin_tac "x \<in> J 0")
apply (simp add:A_to_prodag_def prodrg_def)
apply (simp add:prod_zero_def)
apply (rule funcset_eq [of _ "{j. j \<le> n}"])
apply (simp add:extensional_def restrict_def)+
apply (rule allI, rule impI)
apply (simp add:Ring.qring_zero)
apply (frule_tac a = xa in forall_spec, assumption,
thin_tac "\<forall>k \<le> n. ideal A (J k)")
apply (subst pj_mem [of "A"], assumption+)
apply (frule_tac I = "J xa" and a = x in Ring.a_in_ar_coset [of "A"],
assumption+)
apply (rule_tac a = x and I = "J xa" in Ring.Qring_fix1 [of "A"], assumption+)
apply blast
done
(** n **)
apply (rule impI)
apply (subgoal_tac "\<Inter>{I. \<exists>k \<le> (Suc (Suc n)). I = J k} =
(\<Inter>{I. \<exists>k \<le> (Suc n). I = J k}) \<inter> (J (Suc (Suc n)))")
apply (subgoal_tac "\<Inter>{I. \<exists>k \<le> (Suc n). I = J k} = (i\<Pi>\<^bsub>R,(Suc n)\<^esub> J)")
(* apply (simp del:ideal_n_prodSn)*)
apply (frule_tac n = "Suc n" and J = J in coprime_n_idealsTr4)
apply (simp del:ideal_n_prodSn)
apply (subst coprime_int_prod)
apply (rule n_prod_ideal)
apply (rule allI, simp, simp, assumption)
apply simp apply (cut_tac n = "Suc n" in Nsetn_sub_mem1)
apply simp
apply (thin_tac "(\<forall>k\<le>Suc n. ideal R (J k)) \<and>
(\<forall>i\<le>Suc n. \<forall>j\<le>Suc n. i \<noteq> j \<longrightarrow> coprime_ideals R (J i) (J j)) \<longrightarrow>
\<Inter>{I. \<exists>k\<le>Suc n. I = J k} = i\<Pi>\<^bsub>R,Suc n\<^esub> J",
thin_tac "(\<forall>k\<le>Suc (Suc n). ideal R (J k)) \<and>
(\<forall>i\<le>Suc (Suc n).
\<forall>j\<le>Suc (Suc n). i \<noteq> j \<longrightarrow> coprime_ideals R (J i) (J j))")
apply (rule equalityI, rule subsetI, simp)
apply (rule conjI,
rule allI, rule impI, erule exE, erule conjE, simp,
frule_tac a = xa in forall_spec,
frule_tac x = k and y = "Suc n" and z = "Suc (Suc n)" in
le_less_trans, simp,
frule_tac x = k and y = "Suc (Suc n)" in less_imp_le, blast)
apply simp
apply (frule_tac a = "J (Suc (Suc n))" in forall_spec,
cut_tac n = "Suc (Suc n)" in le_refl, blast, simp)
apply (rule subsetI, simp, rule allI, rule impI)
apply (erule exE, erule conjE)
apply (erule conjE,
case_tac "k = Suc (Suc n)", simp)
apply (frule_tac m = k and n = "Suc (Suc n)" in noteq_le_less, assumption,
thin_tac "k \<le> Suc (Suc n)")
apply (frule_tac x = k and n = "Suc n" in Suc_less_le)
apply (frule_tac a = xa in forall_spec,
blast,
thin_tac "\<forall>xa. (\<exists>k\<le>Suc n. xa = J k) \<longrightarrow> x \<in> xa",
simp)
done
lemma (in Ring) coprime_prod_int2:"\<lbrakk> \<forall>k \<le> (Suc n). ideal R (J k);
\<forall>i \<le> (Suc n). \<forall>j \<le> (Suc n). (i \<noteq>j \<longrightarrow> coprime_ideals R (J i) (J j))\<rbrakk>
\<Longrightarrow> (\<Inter> {I. \<exists>k \<le> (Suc n). I = (J k)} = ideal_n_prod R (Suc n) J)"
apply (simp add:coprime_prod_int2Tr)
done
lemma (in Ring) coprime_2_n:"\<lbrakk>ideal R A; ideal R B\<rbrakk> \<Longrightarrow>
(qring R A) \<Oplus>\<^sub>r (qring R B) = r\<Pi>\<^bsub>{j. j \<le> (Suc 0)}\<^esub> (prodB1 (qring R A) (qring R B))"
apply (simp add:Prod2Rg_def Nset_1)
done
text\<open>In this and following lemmata, ideals A and B are of type
\<open>('a, 'more) RingType_scheme\<close>. Don't try
\<open>(r\<Pi>\<^sub>(Nset n) B) \<Oplus>\<^sub>r B (Suc n)\<close>\<close>
lemma (in Ring) A_to_prodag2_hom:"\<lbrakk>ideal R A; ideal R B; S 0 = pj R A;
S (Suc 0) = pj R B\<rbrakk> \<Longrightarrow>
A_to_prodag R {j. j \<le> (Suc 0)} S (prodB1 (qring R A) (qring R B)) \<in>
rHom R (qring R A \<Oplus>\<^sub>r qring R B)"
apply (subst coprime_2_n [of "A" "B"], assumption+)
apply (rule A_to_prodag_rHom, rule Ring_axioms)
apply (rule ballI)
apply (case_tac "k = 0")
apply (simp add:prodB1_def)
apply (simp add:qring_ring)
apply (simp)
apply (frule_tac n = k in Suc_leI[of 0], thin_tac "0 < k")
apply (frule_tac m = k and n = "Suc 0" in le_antisym, assumption)
apply (simp, simp add:prodB1_def, simp add:qring_ring)
apply (rule ballI)
apply (simp add:Nset_1)
apply (erule disjE)
apply (simp add:prodB1_def, rule pj_Hom, rule Ring_axioms, assumption)
apply (simp, simp add:prodB1_def)
apply (rule pj_Hom, rule Ring_axioms, assumption+)
done
lemma (in Ring) A2coprime_rsurjecTr:"\<lbrakk>ideal R A; ideal R B; S 0 = pj R A;
S (Suc 0) = pj R B\<rbrakk> \<Longrightarrow>
(carrier (qring R A \<Oplus>\<^sub>r qring R B)) =
carr_prodag {j. j \<le> (Suc 0)} (prodB1 (qring R A) (qring R B))"
apply (simp add:Prod2Rg_def prodrg_def Nset_1)
done
lemma (in Ring) A2coprime_rsurjec:"\<lbrakk>ideal R A; ideal R B; S 0 = pj R A;
S (Suc 0) = pj R B; coprime_ideals R A B\<rbrakk> \<Longrightarrow>
surjec\<^bsub>R,((qring R A) \<Oplus>\<^sub>r (qring R B))\<^esub>
(A_to_prodag R {j. j\<le>(Suc 0)} S (prodB1 (qring R A) (qring R B)))"
apply (frule A_to_prodag2_hom [of "A" "B" "S"], assumption+)
apply (simp add:surjec_def)
apply (rule conjI,
simp add:rHom_def)
apply (rule surj_to_test[of "A_to_prodag R {j. j \<le> (Suc 0)} S
(prodB1 (qring R A) (qring R B))" "carrier R"
"carrier (qring R A \<Oplus>\<^sub>r qring R B)"])
apply (simp add:rHom_def aHom_def)
apply (rule ballI)
apply (frule rHom_func[of "A_to_prodag R {j. j \<le> (Suc 0)} S
(prodB1 (R /\<^sub>r A) (R /\<^sub>r B))" R],
thin_tac "A_to_prodag R {j. j \<le> (Suc 0)} S (prodB1 (R /\<^sub>r A) (R /\<^sub>r B))
\<in> rHom R (R /\<^sub>r A \<Oplus>\<^sub>r R /\<^sub>r B)")
apply (simp add:A2coprime_rsurjecTr[of A B S])
apply (simp add:Nset_1)
apply (frule_tac X = "b 0" and Y = "b (Suc 0)" in
coprime_surjTr[of A B], assumption+)
apply (simp add:carr_prodag_def prodB1_def,
simp add:carr_prodag_def prodB1_def)
apply (erule bexE)
apply (frule_tac x = r in funcset_mem[of "A_to_prodag R {0, Suc 0} S
(prodB1 (R /\<^sub>r A) (R /\<^sub>r B))"
"carrier R" "carr_prodag {0, Suc 0} (prodB1 (R /\<^sub>r A) (R /\<^sub>r B))"],
assumption+)
apply (cut_tac X = "A_to_prodag R {0, Suc 0} S (prodB1 (R /\<^sub>r A) (R /\<^sub>r B)) r"
and Y = b in
carr_prodag_mem_eq[of "{0, Suc 0}" "prodB1 (R /\<^sub>r A) (R /\<^sub>r B)"])
apply (rule ballI)
apply (simp, erule disjE)
apply (simp add:prodB1_def, fold prodB1_def,
simp add:qring_ring Ring.ring_is_ag)
apply (simp add:prodB1_def, fold prodB1_def,
simp add:qring_ring Ring.ring_is_ag)
apply assumption+
apply (rule ballI, simp, erule disjE, simp)
apply (subst A_to_prodag_def, simp)
apply (subst A_to_prodag_def, simp)
apply blast
done
lemma (in Ring) prod2_n_Tr1:"\<lbrakk>\<forall>k \<le> (Suc 0). ideal R (J k);
\<forall>k \<le> (Suc 0). B k = qring R (J k);
\<forall>k \<le> (Suc 0). S k = pj R (J k) \<rbrakk> \<Longrightarrow>
A_to_prodag R {j. j \<le> (Suc 0)} S
(prodB1 (qring R (J 0)) (qring R (J (Suc 0)))) =
A_to_prodag R {j. j \<le> (Suc 0)} S B"
apply (subgoal_tac "\<forall>k \<le> (Suc 0). (prodB1 (qring R (J 0)) (qring R (J (Suc 0)))) k = B k")
apply (simp add:A_to_prodag_def)
apply (rule allI, rule impI)
apply (case_tac "k = 0", simp add:Nset_1_1)
apply (simp add:prodB1_def)
apply (simp add:Nset_1_1)
apply (simp add:prodB1_def)
done
lemma (in aGroup) restrict_prod_Suc:"\<lbrakk>\<forall>k \<le> (Suc (Suc n)). ideal R (J k);
\<forall>k \<le> (Suc (Suc n)). B k = R /\<^sub>r J k;
\<forall>k \<le> (Suc (Suc n)). S k = pj R (J k);
f \<in> carrier (r\<Pi>\<^bsub>{j. j \<le> (Suc (Suc n))}\<^esub> B)\<rbrakk> \<Longrightarrow>
restrict f {j. j \<le> (Suc n)} \<in> carrier (r\<Pi>\<^bsub>{j. j \<le> (Suc n)}\<^esub> B)"
apply (cut_tac Nsetn_sub_mem1[of "Suc n"])
apply (simp add:prodrg_def)
apply (simp add:carr_prodag_def, (erule conjE)+)
apply (simp add:Un_carrier_def)
apply (rule Pi_I)
apply simp
apply (frule_tac x = x in funcset_mem[of f "{j. j \<le> (Suc (Suc n))}"
"\<Union>{X. \<exists>i \<le> (Suc (Suc n)). X = carrier (R /\<^sub>r J i)}"],
simp)
apply simp
apply (erule exE, erule conjE, erule exE, erule conjE, simp)
apply (rotate_tac -5)
apply (frule_tac a = x in forall_spec) apply simp
apply blast
done
lemma (in Ring) Chinese_remTr2:"(\<forall>k \<le> (Suc n). ideal R (J k)) \<and>
(\<forall>k\<le>(Suc n). B k = qring R (J k)) \<and>
(\<forall>k\<le>(Suc n). S k = pj R (J k)) \<and>
(\<forall>i\<le>(Suc n). \<forall>j\<le> (Suc n). (i \<noteq>j \<longrightarrow>
coprime_ideals R (J i) (J j))) \<longrightarrow>
surjec\<^bsub>R,(r\<Pi>\<^bsub>{j. j\<le> (Suc n)}\<^esub> B)\<^esub>
(A_to_prodag R {j. j\<le>(Suc n)} S B)"
apply (cut_tac Ring)
apply (induct_tac n)
(* case n = 0, i.e. two coprime_ideals *) (** use coprime_surjTr **)
apply (rule impI) apply (erule conjE)+
apply (frule A_to_prodag_rHom [of R "{j. j \<le> Suc 0}" "B" "S"])
apply (rule ballI, simp add:Ring.qring_ring)
apply (rule ballI, simp add:pj_Hom)
apply (frule rHom_func[of "A_to_prodag R {j. j \<le> (Suc 0)} S B" R
"r\<Pi>\<^bsub>{j. j \<le> (Suc 0)}\<^esub> B"])
apply (simp add:surjec_def)
apply (rule conjI)
apply (simp add:rHom_def)
apply (rule surj_to_test, assumption+)
apply (rule ballI) apply (simp add:Nset_1)
apply (cut_tac coprime_elems [of "J 0" "J (Suc 0)"])
apply (rename_tac f)
apply (erule bexE, erule bexE)
apply (simp add:prodrg_def) apply (fold prodrg_def)
apply (cut_tac X = "f 0" and Y = "f (Suc 0)" in
coprime_surjTr[of "J 0" "J (Suc 0)"], simp+)
apply (simp add:carr_prodag_def, simp add:carr_prodag_def)
apply (erule bexE, (erule conjE)+)
apply (frule_tac x = r in funcset_mem[of "A_to_prodag R {0, Suc 0} S B"
"carrier R" "carr_prodag {0, Suc 0} B"], assumption+)
apply (cut_tac X = "A_to_prodag R {0, Suc 0} S B r" and Y = f in
carr_prodag_mem_eq[of "{0, Suc 0}" B])
apply (rule ballI, simp, erule disjE, simp add:qring_ring
Ring.ring_is_ag,
simp add:Ring.qring_ring Ring.ring_is_ag)
apply assumption+
apply (rule ballI, simp, erule disjE, simp)
apply (simp add:A_to_prodag_def, simp add:A_to_prodag_def)
apply blast apply simp+
apply (rule impI, (erule conjE)+)
(**** n ****)
apply (cut_tac n = "Suc n" in Nsetn_sub_mem1)
apply (subgoal_tac "\<forall>k\<in>{i. i \<le> Suc (Suc n)}. Ring (B k)")
apply (frule_tac I = "{i. i \<le> Suc (Suc n)}" in A_to_prodag_rHom [of "R" _ "B" "S"])
apply assumption
apply (rule ballI)
apply (simp add:pj_Hom)
apply simp
apply (subst surjec_def, rule conjI,
simp add:rHom_def)
apply (cut_tac n = "Suc n" in coprime_n_idealsTr4[of _ J])
apply blast
apply (frule_tac f = "A_to_prodag R {j. j \<le> (Suc (Suc n))} S B" and
A = R in rHom_func)
apply (rule_tac f = "A_to_prodag R {j. j \<le> (Suc (Suc n))} S B" and
A = "carrier R" and B = "carrier (r\<Pi>\<^bsub>{j. j \<le> (Suc (Suc n))}\<^esub> B)" in
surj_to_test, assumption+)
apply (rule ballI)
apply (cut_tac n = "Suc n" in n_prod_ideal[of _ J])
apply (rule allI, simp)
apply (frule_tac A = "i\<Pi>\<^bsub>R,(Suc n)\<^esub> J" and B = "J (Suc (Suc n))" in
coprime_elems,
cut_tac n = "Suc (Suc n)" in n_in_Nsetn,
blast, assumption)
apply (erule bexE, erule bexE) apply (rename_tac n f a b)
apply (thin_tac " coprime_ideals R (i\<Pi>\<^bsub>R,(Suc n)\<^esub> J) (J (Suc (Suc n)))")
apply (cut_tac n = "Suc n" and a = a and J = J in ele_n_prod,
rule allI, simp, assumption)
apply (cut_tac ring_is_ag)
apply (frule_tac n = n and f = f in aGroup.restrict_prod_Suc[of R _ R J B S],
assumption+)
apply (frule_tac S = "r\<Pi>\<^bsub>{j. j \<le> (Suc n)}\<^esub> B" and
f = "A_to_prodag R {j. j \<le> (Suc n)} S B" in surjec_surj_to[of R])
apply (frule_tac f = "A_to_prodag R {j. j \<le> (Suc n)} S B" and A = "carrier R"
and B = "carrier (r\<Pi>\<^bsub>{j. j \<le> (Suc n)}\<^esub> B)" and
b = "restrict f {j. j \<le> (Suc n)}" in surj_to_el2, assumption)
apply (erule bexE, rename_tac n f a b u)
apply (cut_tac n = "Suc (Suc n)" in n_in_Nsetn,
frule_tac f = f and I = "{j. j \<le> (Suc (Suc n))}" and A = B and
i = "Suc (Suc n)" in prodrg_component, assumption)
apply simp
apply (frule_tac J = "J (Suc (Suc n))" and X = "f (Suc (Suc n))" in
pj_surj_to[of R], simp, assumption)
apply (erule bexE, rename_tac n f a b u v)
apply (frule_tac a = "Suc (Suc n)" in forall_spec, simp,
frule_tac I = "J (Suc (Suc n))" and h = b in Ring.ideal_subset[of R],
assumption+,
cut_tac I = "i\<Pi>\<^bsub>R,n\<^esub> J \<diamondsuit>\<^sub>r\<^bsub>R\<^esub> J (Suc n)" and h = a in
Ring.ideal_subset[of R], assumption+)
apply (frule_tac x = b and y = u in Ring.ring_tOp_closed[of R], assumption+,
frule_tac x = a and y = v in Ring.ring_tOp_closed[of R], assumption+,
frule Ring.ring_is_ag[of R],
frule_tac x = "b \<cdot>\<^sub>r\<^bsub>R\<^esub> u" and y = "a \<cdot>\<^sub>r\<^bsub>R\<^esub> v" in aGroup.ag_pOp_closed[of R],
assumption+)
apply (frule_tac f = "A_to_prodag R {j. j \<le> (Suc (Suc n))} S B" and
A = "carrier R" and B = "carrier (r\<Pi>\<^bsub>{j. j \<le> (Suc (Suc n))}\<^esub> B)" and
x = "b \<cdot>\<^sub>r\<^bsub>R\<^esub> u \<plusminus>\<^bsub>R\<^esub> a \<cdot>\<^sub>r\<^bsub>R\<^esub> v" in funcset_mem, assumption+)
apply (frule_tac f = "A_to_prodag R {j. j \<le> (Suc (Suc n))} S B
(b \<cdot>\<^sub>r\<^bsub>R\<^esub> u \<plusminus>\<^bsub>R\<^esub> a \<cdot>\<^sub>r\<^bsub>R\<^esub> v)" and I = "{j. j \<le> (Suc (Suc n))}"
and g = f in carr_prodrg_mem_eq, simp)
apply (rule ballI)
apply (subst A_to_prodag_def, simp)
apply (frule_tac I = "J i" in pj_Hom[of R], simp)
apply (simp add: rHom_add)
apply (frule_tac a = i in forall_spec, assumption,
thin_tac "\<forall>k \<le> (Suc (Suc n)). ideal R (J k)",
frule_tac I = "J i" in Ring.qring_ring[of R], assumption,
thin_tac "\<forall>k \<le> (Suc (Suc n)). Ring (R /\<^sub>r J k)",
frule_tac R = "R /\<^sub>r (J i)" and x = b and y = u and f = "pj R (J i)" in
rHom_tOp[of R], assumption+, simp,
thin_tac "pj R (J i) (b \<cdot>\<^sub>r\<^bsub>R\<^esub> u) = pj R (J i) b \<cdot>\<^sub>r\<^bsub>R /\<^sub>r J i\<^esub> pj R (J i) u",
frule_tac R = "R /\<^sub>r (J i)" and x = a and y = v and f = "pj R (J i)" in
rHom_tOp[of R], simp add:Ring.qring_ring, assumption+)
apply (frule_tac f = "pj R (J i)" and R = "R /\<^sub>r J i" and a = v in
rHom_mem[of _ R], assumption+,
frule_tac f = "pj R (J i)" and R = "R /\<^sub>r J i" and a = u in
rHom_mem[of _ R], assumption+,
frule_tac f = "pj R (J i)" and R = "R /\<^sub>r J i" and a = b in
rHom_mem[of _ R], assumption+,
frule_tac f = "pj R (J i)" and R = "R /\<^sub>r J i" and a = a in
rHom_mem[of _ R], assumption+)
apply (frule_tac R = "R /\<^sub>r J i" in Ring.ring_is_ag)
apply (case_tac "i \<le> (Suc n)")
apply (frule_tac I1 = "J i" and x1 = a in pj_zero[THEN sym, of R ],
assumption+, simp,
thin_tac "pj R (J i) (a \<cdot>\<^sub>r\<^bsub>R\<^esub> v) = \<zero>\<^bsub>R /\<^sub>r J i\<^esub> \<cdot>\<^sub>r\<^bsub>R /\<^sub>r J i\<^esub> pj R (J i) v")
apply (simp add:Ring.ring_times_0_x)
apply (frule_tac f = "pj R (J i)" and A = R and R = "R /\<^sub>r J i" and
x = a and y = b in rHom_add, assumption+, simp,
thin_tac "A_to_prodag R {j. j \<le> Suc (Suc n)} S B
(b \<cdot>\<^sub>r u) \<plusminus>\<^bsub>r\<Pi>\<^bsub>{i. i \<le> Suc (Suc n)}\<^esub> B\<^esub>
A_to_prodag R {j. j \<le> Suc (Suc n)} S B (a \<cdot>\<^sub>r v)
\<in> carrier (r\<Pi>\<^bsub>{j. j \<le> Suc (Suc n)}\<^esub> B)")
apply (simp add:aGroup.ag_l_zero)
apply (rotate_tac -1, frule sym, thin_tac " pj R (J i) 1\<^sub>r\<^bsub>R\<^esub> = pj R (J i) b",
simp add:rHom_one) apply (simp add:Ring.ring_l_one)
apply (simp add:aGroup.ag_r_zero)
apply (frule_tac f = "A_to_prodag R {j. j \<le> (Suc n)} S B u" and
g = "restrict f {j. j \<le> (Suc n)}" and x = i in eq_fun_eq_val,
thin_tac "A_to_prodag R {j. j\<le>(Suc n)} S B u = restrict f {j. j\<le>(Suc n)}")
apply (simp add:A_to_prodag_def)
apply simp
apply (frule_tac y = i and x = "Suc n" in not_le_imp_less,
frule_tac m = "Suc n" and n = i in Suc_leI,
frule_tac m = i and n = "Suc (Suc n)" in Nat.le_antisym, assumption+,
simp)
apply (frule_tac I1 = "J (Suc (Suc n))" and x1 = b in pj_zero[THEN sym, of
R ], assumption+, simp add:Ring.ring_times_0_x)
apply (frule_tac f = "pj R (J (Suc (Suc n)))" and A = R and
R = "R /\<^sub>r J (Suc (Suc n))" and
x = a and y = b in rHom_add, assumption+, simp)
apply (simp add:aGroup.ag_r_zero)
apply (rotate_tac -1, frule sym,
thin_tac "pj R (J (Suc (Suc n))) 1\<^sub>r\<^bsub>R\<^esub> = pj R (J (Suc (Suc n))) a",
simp add:rHom_one,
simp add:Ring.ring_l_one)
apply (simp add:aGroup.ag_l_zero)
apply blast
apply (rule ballI, simp add:Ring.qring_ring)
done
lemma (in Ring) Chinese_remTr3:"\<lbrakk>\<forall>k \<le> (Suc n). ideal R (J k);
\<forall>k \<le> (Suc n). B k = qring R (J k); \<forall>k\<le> (Suc n). S k = pj R (J k);
\<forall>i \<le> (Suc n). \<forall>j \<le> (Suc n). (i \<noteq>j \<longrightarrow> coprime_ideals R (J i) (J j))\<rbrakk> \<Longrightarrow>
surjec\<^bsub>R,(r\<Pi>\<^bsub>{j. j \<le> (Suc n)}\<^esub> B)\<^esub>
(A_to_prodag R {j. j \<le> (Suc n)} S B)"
apply (simp add:Chinese_remTr2 [of "n" "J" "B" "S"])
done
lemma (in Ring) imset:"\<lbrakk>\<forall>k\<le> (Suc n). ideal R (J k)\<rbrakk>
\<Longrightarrow> {I. \<exists>k\<le> (Suc n). I = J k} = {J k| k. k \<in> {j. j \<le> (Suc n)}}"
apply blast
done
theorem (in Ring) Chinese_remThm:"\<lbrakk>(\<forall>k \<le> (Suc n). ideal R (J k));
\<forall>k\<le>(Suc n). B k = qring R (J k); \<forall>k \<le> (Suc n). S k = pj R (J k);
\<forall>i \<le> (Suc n). \<forall>j \<le> (Suc n). (i \<noteq>j \<longrightarrow> coprime_ideals R (J i) (J j))\<rbrakk>
\<Longrightarrow> bijec\<^bsub>(qring R (\<Inter> {J k | k. k\<in>{j. j \<le> (Suc n)}})),(r\<Pi>\<^bsub>{j. j \<le> (Suc n)}\<^esub> B)\<^esub>
((A_to_prodag R {j. j \<le> (Suc n)} S B)\<degree>\<^bsub>R,(prodrg {j. j \<le> (Suc n)} B)\<^esub>)"
apply (frule Chinese_remTr3, assumption+)
apply (cut_tac I = "{j. j \<le> (Suc n)}" and A = B in prodrg_ring)
apply (rule ballI, simp add:qring_ring)
apply (cut_tac surjec_ind_bijec [of "R" "r\<Pi>\<^bsub>{j. j \<le> (Suc n)}\<^esub> B"
"A_to_prodag R {j. j \<le> (Suc n)} S B"])
apply (cut_tac Ring,
simp add:Chinese_remTr1 [of "R" "Suc n" "J" "B" "S"])
apply (simp add:imset, rule Ring_axioms, assumption+)
apply (rule A_to_prodag_rHom, rule Ring_axioms)
apply (rule ballI)
apply (simp add:qring_ring)
apply (rule ballI, simp, rule pj_Hom, rule Ring_axioms, simp)
apply assumption
done
lemma (in Ring) prod_prime:"\<lbrakk>ideal R A; \<forall>k\<le>(Suc n). prime_ideal R (P k);
\<forall>l\<le>(Suc n). \<not> (A \<subseteq> P l);
\<forall>k\<le> (Suc n). \<forall>l\<le> (Suc n). k = l \<or> \<not> (P k) \<subseteq> (P l)\<rbrakk> \<Longrightarrow>
\<forall>i \<le> (Suc n). (nprod R (ppa R P A i) n \<in> A \<and>
(\<forall>l \<in> {j. j\<le>(Suc n)} - {i}. nprod R (ppa R P A i) n \<in> P l) \<and>
(nprod R (ppa R P A i) n \<notin> P i))"
apply (rule allI, rule impI)
apply (rule conjI)
apply (frule_tac i = i in prod_primeTr1[of n P A], assumption+)
apply (frule_tac n = n and f = "ppa R P A i" in ideal_nprod_inc[of A])
apply (rule allI, rule impI)
apply (rotate_tac -2,
frule_tac a = ia in forall_spec, assumption,
thin_tac "\<forall>l \<le> n.
ppa R P A i l \<in> A \<and>
ppa R P A i l \<in> P (skip i l) \<and> ppa R P A i l \<notin> P i",
simp add:ideal_subset)
apply (rotate_tac -1,
frule_tac a = n in forall_spec, simp,
thin_tac "\<forall>l\<le> n.
ppa R P A i l \<in> A \<and>
ppa R P A i l \<in> P (skip i l) \<and> ppa R P A i l \<notin> P i",
(erule conjE)+,
blast, assumption)
apply (frule_tac i = i in prod_primeTr1[of n P A], assumption+)
apply (rule conjI)
apply (rule ballI)
apply (frule_tac a = l in forall_spec, simp,
frule_tac I = "P l" in prime_ideal_ideal)
apply (frule_tac n = n and f = "ppa R P A i" and A = "P l" in ideal_nprod_inc)
apply (rule allI) apply (simp add:ppa_mem, simp)
apply (case_tac "l < i",
thin_tac "\<forall>l\<le> (Suc n). \<not> A \<subseteq> P l",
thin_tac "\<forall>k\<le> (Suc n). \<forall>l \<le> (Suc n). k = l \<or> \<not> P k \<subseteq> P l")
apply (erule conjE,
frule_tac x = l and y = i and z = "Suc n" in less_le_trans,
assumption,
frule_tac x = l and n = n in Suc_less_le)
apply (rotate_tac 2,
frule_tac a = l in forall_spec, assumption,
thin_tac "\<forall>l\<le>n. ppa R P A i l \<in> A \<and>
ppa R P A i l \<in> P (skip i l) \<and> ppa R P A i l \<notin> P i",
thin_tac "l < Suc n")
apply (simp only:skip_im_Tr1_2, blast)
apply (frule_tac x = l and y = i in leI,
thin_tac "\<not> l < i",
cut_tac x = l and A = "{j. j \<le> (Suc n)}" and a = i in in_diff1)
apply simp
apply (erule conjE,
frule not_sym, thin_tac "l \<noteq> i",
frule_tac x = i and y = l in le_imp_less_or_eq,
erule disjE, thin_tac "i \<le> l",
frule_tac x = i and n = l in less_le_diff)
apply (cut_tac i = i and n = n and x = "l - Suc 0" in skip_im_Tr2_1,
simp, assumption+, simp,
frule_tac x = l and n = n in le_Suc_diff_le)
apply (rotate_tac -7,
frule_tac a = "l - Suc 0" in forall_spec, assumption,
thin_tac "\<forall>l\<le>n. ppa R P A i l \<in> A \<and>
ppa R P A i l \<in> P (skip i l) \<and> ppa R P A i l \<notin> P i",
simp, (erule conjE)+)
apply blast
apply simp
apply assumption
apply (frule_tac a = i in forall_spec, assumption,
thin_tac "\<forall>k\<le> (Suc n). prime_ideal R (P k)")
apply (rule_tac P = "P i" and n = n and f = "ppa R P A i" in
prime_nprod_exc, assumption+)
apply (rule allI, rule impI)
apply (rotate_tac -3,
frule_tac a = ia in forall_spec, assumption,
thin_tac "\<forall>l \<le> n.
ppa R P A i l \<in> A \<and>
ppa R P A i l \<in> P (skip i l) \<and> ppa R P A i l \<notin> P i",
simp add:ideal_subset)
apply (rule allI, rule impI) apply (
rotate_tac 4,
frule_tac a = l in forall_spec, assumption,
thin_tac "\<forall>l\<le> n.
ppa R P A i l \<in> A \<and>
ppa R P A i l \<in> P (skip i l) \<and> ppa R P A i l \<notin> P i",
simp)
done
lemma skip_im1:"\<lbrakk>i \<le> (Suc n); P \<in> {j. j \<le> (Suc n)} \<rightarrow> Collect (prime_ideal R)\<rbrakk>
\<Longrightarrow>
compose {j. j \<le> n} P (skip i) ` {j. j \<le> n} = P ` ({j. j \<le> (Suc n)} - {i})"
apply (cut_tac skip_fun[of i n])
apply (subst setim_cmpfn[of _ _ _ _ "{X. prime_ideal R X}"], assumption+)
apply simp
apply (simp add:skip_fun_im)
done
lemma (in Ring) mutch_aux1:"\<lbrakk>ideal R A; i \<le> (Suc n);
P \<in> {j. j \<le> (Suc n)} \<rightarrow> Collect (prime_ideal R)\<rbrakk> \<Longrightarrow>
compose {j. j \<le> n} P (skip i) \<in> {j. j \<le> n} \<rightarrow> Collect (prime_ideal R)"
apply (cut_tac skip_fun[of i n])
apply (simp add:composition[of "skip i" "{j. j \<le> n}" "{j. j \<le> (Suc n)}" P
"Collect (prime_ideal R)"])
done
lemma (in Ring) prod_n_ideal_contTr0:"(\<forall>l\<le> n. ideal R (J l)) \<longrightarrow>
i\<Pi>\<^bsub>R,n\<^esub> J \<subseteq> \<Inter>{X. (\<exists>k\<le>n. X = (J k))}"
apply (induct_tac n)
apply simp
apply (rule impI)
apply (cut_tac n = n in Nsetn_sub_mem1,
simp)
apply (cut_tac n = n in n_prod_ideal[of _ J], simp)
apply (cut_tac I = "i\<Pi>\<^bsub>R,n\<^esub> J" and J = "J (Suc n)" in
ideal_prod_sub_Int) apply assumption apply simp
apply (frule_tac A = "i\<Pi>\<^bsub>R,n\<^esub> J \<diamondsuit>\<^sub>r\<^bsub>R\<^esub> J (Suc n)" and
B = "i\<Pi>\<^bsub>R,n\<^esub> J \<inter> J (Suc n)" and
C = "\<Inter>{X. \<exists>k\<le> n. X = J k} \<inter> J (Suc n)" in subset_trans)
apply (rule_tac A = "i\<Pi>\<^bsub>R,n\<^esub> J" and B = "\<Inter>{X. \<exists>k\<le>n. X = J k}" and
C = "J (Suc n)" in inter_mono, assumption)
apply (rule_tac A = "i\<Pi>\<^bsub>R,n\<^esub> J \<diamondsuit>\<^sub>r J (Suc n)" and
B = "\<Inter>{X. \<exists>k\<le> n. X = J k} \<inter> J (Suc n)" and
C = "\<Inter>{X. \<exists>k\<le> (Suc n). X = J k}" in subset_trans,
assumption)
apply (rule subsetI)
apply simp
apply (rule allI, rule impI)
apply (erule exE, (erule conjE)+)
apply (case_tac "k = Suc n", simp)
apply (frule_tac m = k and n = "Suc n" in noteq_le_less, assumption)
apply (thin_tac " k \<le> Suc n")
apply (frule_tac x = k and n = "Suc n" in less_le_diff,
thin_tac "k < Suc n", simp, thin_tac "\<forall>l\<le>Suc n. ideal R (J l)")
apply (frule_tac a = xa in forall_spec, blast,
thin_tac "\<forall>xa. (\<exists>k\<le>n. xa = J k) \<longrightarrow> x \<in> xa",
simp)
done
lemma (in Ring) prod_n_ideal_contTr:"\<lbrakk>\<forall>l\<le> n. ideal R (J l)\<rbrakk> \<Longrightarrow>
i\<Pi>\<^bsub>R,n\<^esub> J \<subseteq> \<Inter>{X. (\<exists>k \<le> n. X = (J k))}"
apply (simp add:prod_n_ideal_contTr0)
done
lemma (in Ring) prod_n_ideal_cont2:"\<lbrakk>\<forall>l\<le> (n::nat). ideal R (J l);
prime_ideal R P; \<Inter>{X. (\<exists>k\<le> n. X = (J k))} \<subseteq> P\<rbrakk> \<Longrightarrow>
\<exists>l\<le> n. (J l) \<subseteq> P"
apply (frule prod_n_ideal_contTr[of n J])
apply (frule_tac A = "i\<Pi>\<^bsub>R,n\<^esub> J" and B = "\<Inter>{X. \<exists>k\<le> n. X = J k}" and C = P
in subset_trans, assumption+)
apply (thin_tac "\<Inter>{X. \<exists>k\<le> n. X = J k} \<subseteq> P",
thin_tac "i\<Pi>\<^bsub>R,n\<^esub> J \<subseteq> \<Inter>{X. \<exists>k\<le> n. X = J k}")
apply (simp add:ideal_n_prod_prime)
done
lemma (in Ring) prod_n_ideal_cont3:"\<lbrakk>\<forall>l\<le> (n::nat). ideal R (J l);
prime_ideal R P; \<Inter>{X. (\<exists>k\<le> n. X = (J k))} = P\<rbrakk> \<Longrightarrow>
\<exists>l\<le> n. (J l) = P"
apply (frule prod_n_ideal_cont2[of n J P], assumption+)
apply simp
apply (erule exE)
apply (subgoal_tac "J l = P")
apply blast
apply (rule equalityI, simp)
apply (rule subsetI)
apply (rotate_tac -4, frule sym, thin_tac "\<Inter>{X. \<exists>k\<le> n. X = J k} = P")
apply simp
apply blast
done
definition
ideal_quotient :: "[_ , 'a set, 'a set] \<Rightarrow> 'a set" where
"ideal_quotient R A B = {x| x. x \<in> carrier R \<and> (\<forall>b\<in>B. x \<cdot>\<^sub>r\<^bsub>R\<^esub> b \<in> A)}"
abbreviation
IDEALQT ("(3_/ \<dagger>\<^sub>_/ _)" [82,82,83]82) where
"A \<dagger>\<^sub>R B == ideal_quotient R A B"
lemma (in Ring) ideal_quotient_is_ideal:
"\<lbrakk>ideal R A; ideal R B\<rbrakk> \<Longrightarrow> ideal R (ideal_quotient R A B)"
apply (rule ideal_condition)
apply (rule subsetI)
apply (simp add:ideal_quotient_def CollectI)
apply (simp add:ideal_quotient_def)
apply (cut_tac ring_zero)
apply (subgoal_tac "\<forall>b\<in>B. \<zero> \<cdot>\<^sub>r b \<in> A")
apply blast
apply (rule ballI)
apply (frule_tac h = b in ideal_subset[of B], assumption)
apply (frule_tac x = b in ring_times_0_x )
apply (simp add:ideal_zero)
apply (rule ballI)+
apply (simp add:ideal_quotient_def, (erule conjE)+,
rule conjI)
apply (rule ideal_pOp_closed)
apply (simp add:whole_ideal, assumption+)
apply (cut_tac ring_is_ag)
apply (simp add:aGroup.ag_mOp_closed)
apply (rule ballI)
apply (subst ring_distrib2)
apply (simp add:ideal_subset, assumption)
apply (cut_tac ring_is_ag, simp add: aGroup.ag_mOp_closed)
apply (frule_tac a1 = y and b1 = b in ring_inv1_1 [THEN sym])
apply (simp add:ideal_subset, simp)
apply (rule ideal_pOp_closed, assumption+, simp)
apply (rule ideal_inv1_closed, assumption+, simp)
apply (rule ballI)+
apply (simp add:ideal_quotient_def)
apply (rule conjI)
apply (erule conjE)
apply (simp add:ring_tOp_closed)
apply (erule conjE)
apply (rule ballI)
apply (subst ring_tOp_assoc, assumption+, simp add:ideal_subset)
apply (simp add:ideal_ring_multiple [of "A"])
done
section \<open>Addition of finite elements of a ring and \<open>ideal_multiplication\<close>\<close>
text\<open>We consider sum in an abelian group\<close>
lemma (in aGroup) nsum_mem1Tr:" A +> J \<Longrightarrow>
(\<forall>j \<le> n. f j \<in> J) \<longrightarrow> nsum A f n \<in> J"
apply (induct_tac n)
apply (rule impI)
apply simp
apply (rule impI)
apply simp
apply (rule asubg_pOp_closed, assumption+)
apply simp
done
lemma (in aGroup) fSum_mem:"\<lbrakk>\<forall>j \<in> nset (Suc n) m. f j \<in> carrier A; n < m\<rbrakk> \<Longrightarrow>
fSum A f (Suc n) m \<in> carrier A"
apply (simp add:fSum_def)
apply (rule nsum_mem)
apply (rule allI, simp add:cmp_def slide_def)
apply (rule impI)
apply (frule_tac x = "Suc (n + j)" in bspec)
apply (simp add:nset_def, arith)
done
lemma (in aGroup) nsum_mem1:"\<lbrakk>A +> J; \<forall>j \<le> n. f j \<in> J\<rbrakk> \<Longrightarrow> nsum A f n \<in> J"
apply (simp add:nsum_mem1Tr)
done
lemma (in aGroup) nsum_eq_i:"\<lbrakk>\<forall>j\<le>n. f j \<in> carrier A; \<forall>j\<le>n. g j \<in> carrier A;
i \<le> n; \<forall>l \<le> i. f l = g l\<rbrakk> \<Longrightarrow> nsum A f i = nsum A g i"
apply (rule nsum_eq)
apply (rule allI, rule impI, simp)+
done
lemma (in aGroup) nsum_cmp_eq:"\<lbrakk>f \<in> {j. j\<le>(n::nat)} \<rightarrow> carrier A;
h1 \<in> {j. j \<le> n} \<rightarrow> {j. j \<le> n}; h2 \<in> {j. j \<le> n} \<rightarrow> {j. j \<le> n}; i \<le> n\<rbrakk> \<Longrightarrow>
nsum A (cmp f (cmp h2 h1)) i = nsum A (cmp (cmp f h2) h1) i"
apply (rule nsum_eq_i [of n "cmp f (cmp h2 h1)" "cmp (cmp f h2) h1" i])
apply (rule allI, rule impI, simp add:cmp_def)
apply ((rule funcset_mem, assumption)+, simp)
apply (rule allI, rule impI, simp add:cmp_def,
(rule funcset_mem, assumption)+, simp+)
apply (rule allI, rule impI, simp add:cmp_def)
done
lemma (in aGroup) nsum_cmp_eq_transpos:"\<lbrakk> \<forall>j\<le>(Suc n). f j \<in> carrier A;
i \<le> n;i \<noteq> n \<rbrakk> \<Longrightarrow>
nsum A (cmp f (cmp (transpos i n) (cmp (transpos n (Suc n)) (transpos i n))))
(Suc n) = nsum A (cmp f (transpos i (Suc n))) (Suc n)"
apply (rule nsum_eq [of "Suc n" "cmp f (cmp (transpos i n)
(cmp (transpos n (Suc n)) (transpos i n)))"
"cmp f (transpos i (Suc n))"])
apply (rule allI, rule impI)
apply (simp add:cmp_def)
apply (cut_tac i = i and n = "Suc n" and j = n and l = j in transpos_mem,
simp+)
apply (cut_tac i = n and n = "Suc n" and j = "Suc n" and l = "transpos i n j"
in transpos_mem, simp+)
apply (cut_tac i = i and n = "Suc n" and j = n and
l = "transpos n (Suc n) (transpos i n j)" in transpos_mem,
simp+)
apply (rule allI, rule impI, simp add:cmp_def)
apply (cut_tac i = i and n = "Suc n" and j = "Suc n" and l = j in transpos_mem,
simp+)
apply (rule allI, rule impI)
apply (simp add:cmp_def)
apply (thin_tac "\<forall>j\<le>Suc n. f j \<in> carrier A",
rule eq_elems_eq_val[of _ _ f])
apply (simp add:transpos_def)
done
lemma transpos_Tr_n1:"Suc (Suc 0) \<le> n \<Longrightarrow>
transpos (n - Suc 0) n n = n - Suc 0"
apply (simp add:transpos_def)
done
lemma transpos_Tr_n2:"Suc (Suc 0) \<le> n \<Longrightarrow>
transpos (n - (Suc 0)) n (n - (Suc 0)) = n"
apply (simp add:transpos_def)
done
lemma (in aGroup) additionTr0:"\<lbrakk>0 < n; \<forall>j \<le> n. f j \<in> carrier A\<rbrakk>
\<Longrightarrow> nsum A (cmp f (transpos (n - 1) n)) n = nsum A f n"
apply (case_tac "n \<le> 1")
apply simp
apply (frule Suc_leI [of "0" "n"])
apply (frule le_antisym [of "n" "Suc 0"], assumption+, simp)
apply (simp add:cmp_def)
apply (subst transpos_ij_1[of 0 "Suc 0"], simp+)
apply (subst transpos_ij_2[of 0 "Suc 0"], simp+)
apply (rule ag_pOp_commute, simp+)
apply (frule not_le_imp_less[of n "Suc 0"])
apply (frule_tac Suc_leI [of "Suc 0" "n"],
thin_tac "\<not> n \<le> Suc 0")
apply (cut_tac nsum_suc[of A f "n - Suc 0"], simp)
apply (cut_tac nsum_suc[of A "cmp f (transpos (n - Suc 0) n)" "n - Suc 0"],
simp,
thin_tac "\<Sigma>\<^sub>e A f n = \<Sigma>\<^sub>e A f (n - Suc 0) \<plusminus> f n",
thin_tac "\<Sigma>\<^sub>e A (cmp f (transpos (n - Suc 0) n)) n =
\<Sigma>\<^sub>e A (cmp f (transpos (n - Suc 0) n)) (n - Suc 0) \<plusminus>
(cmp f (transpos (n - Suc 0) n) n)")
apply (case_tac "n = Suc (Suc 0)", simp)
apply (cut_tac transpos_id_1[of "Suc 0" "Suc (Suc 0)" "Suc (Suc 0)" 0],
cut_tac transpos_ij_1[of "Suc 0" "Suc (Suc 0)" "Suc (Suc 0)"],
cut_tac transpos_ij_2[of "Suc 0" "Suc (Suc 0)" "Suc (Suc 0)"],
simp add:cmp_def,
thin_tac "n = Suc (Suc 0)",
thin_tac "transpos (Suc 0) (Suc (Suc 0)) 0 = 0",
thin_tac "transpos (Suc 0) (Suc (Suc 0)) (Suc 0) = Suc (Suc 0)",
thin_tac "transpos (Suc 0) (Suc (Suc 0)) (Suc (Suc 0)) = Suc 0")
apply (subst ag_pOp_assoc, simp+)
apply (subst ag_pOp_commute[of "f (Suc (Suc 0))" "f (Suc 0)"], simp+)
apply (subst ag_pOp_assoc[THEN sym], simp+)
apply (frule not_sym)
apply (frule noteq_le_less[of "Suc (Suc 0)" n], assumption,
thin_tac "Suc (Suc 0) \<le> n")
apply (cut_tac nsum_suc[of A f "n - Suc 0 - Suc 0"])
apply (cut_tac Suc_pred[of "n - Suc 0"], simp del:nsum_suc)
apply (cut_tac nsum_suc[of A "cmp f (transpos (n - Suc 0) n)"
"n - Suc (Suc 0)"], simp del:nsum_suc,
thin_tac "\<Sigma>\<^sub>e A f (n - Suc 0) = \<Sigma>\<^sub>e A f (n - Suc (Suc 0)) \<plusminus> f (n - Suc 0)",
thin_tac "Suc (n - Suc (Suc 0)) = n - Suc 0",
thin_tac "\<Sigma>\<^sub>e A (cmp f (transpos (n - Suc 0) n)) (n - Suc 0) =
\<Sigma>\<^sub>e A (cmp f (transpos (n - Suc 0) n)) (n - Suc (Suc 0)) \<plusminus>
(cmp f (transpos (n - Suc 0) n)) (n - Suc 0)")
apply (cut_tac nsum_eq_i[of n "cmp f (transpos (n - Suc 0) n)" f
"n - Suc (Suc 0)"], simp,
thin_tac "\<Sigma>\<^sub>e A (cmp f (transpos (n - Suc 0) n)) (n - Suc (Suc 0)) =
\<Sigma>\<^sub>e A f (n - Suc (Suc 0))")
apply (simp add:cmp_def)
apply (cut_tac transpos_ij_1[of "n - Suc 0" n n], simp)
apply (cut_tac transpos_ij_2[of "n - Suc 0" n n], simp)
apply (subst ag_pOp_assoc,
rule nsum_mem, rule allI, rule impI)
apply (frule_tac x = j and y = "n - Suc (Suc 0)" and z = n in
le_less_trans, simp, frule_tac x = j and y = n in less_imp_le)
apply simp+
apply (subst ag_pOp_commute[of "f n"], simp, simp)
apply (subst ag_pOp_assoc[THEN sym],
rule nsum_mem, rule allI, rule impI,
frule_tac x = j and y = "n - Suc (Suc 0)" and z = n in
le_less_trans, simp, frule_tac x = j and y = n in less_imp_le)
apply simp+
apply (rule allI, rule impI, simp add:cmp_def)
apply (cut_tac i = "n - Suc 0" and n = n and j = n and l = j in transpos_mem,
simp+)
apply (rule allI, rule impI)
apply (simp add:cmp_def)
apply (cut_tac i = "n - Suc 0" and n = n and j = n and x = l in transpos_id,
simp+)
apply (cut_tac x = l and y = "n - Suc (Suc 0)" and z = n in le_less_trans,
assumption) apply simp
apply arith
apply simp
apply arith
done
lemma (in aGroup) additionTr1:"\<lbrakk> \<forall>f. \<forall>h. f \<in> {j. j\<le>(Suc n)} \<rightarrow> carrier A \<and>
h \<in> {j. j\<le>(Suc n)} \<rightarrow> {j. j\<le>(Suc n)} \<and> inj_on h {j. j\<le>(Suc n)} \<longrightarrow>
nsum A (cmp f h) (Suc n) = nsum A f (Suc n);
f \<in> {j. j\<le>(Suc (Suc n))} \<rightarrow> carrier A;
h \<in> {j. j\<le>(Suc (Suc n))} \<rightarrow> {j. j\<le>(Suc (Suc n))};
inj_on h {j. j\<le>(Suc (Suc n))}; h (Suc (Suc n)) = Suc (Suc n)\<rbrakk>
\<Longrightarrow> nsum A (cmp f h) (Suc (Suc n)) = nsum A f (Suc (Suc n))"
apply (subgoal_tac "f \<in> {j. j\<le>(Suc n)} \<rightarrow> carrier A")
apply (subgoal_tac "h \<in> {j. j\<le>(Suc n)} \<rightarrow> {j. j\<le>(Suc n)}")
apply (subgoal_tac "inj_on h {j. j\<le>(Suc n)}")
apply (subgoal_tac "nsum A (cmp f h) (Suc n) = nsum A f (Suc n)")
apply (thin_tac "\<forall>f. \<forall>h. f \<in> {j. j\<le>(Suc n)} \<rightarrow> carrier A \<and>
h \<in> {j. j\<le>(Suc n)} \<rightarrow> {j. j\<le>(Suc n)} \<and> inj_on h {j. j\<le>(Suc n)} \<longrightarrow>
nsum A (cmp f h) (Suc n) = nsum A f (Suc n)")
prefer 2 apply simp
apply simp
apply (thin_tac "nsum A (cmp f h) n \<plusminus> (cmp f h (Suc n)) = nsum A f n \<plusminus> (f (Suc n))")
apply (simp add:cmp_def)
apply (thin_tac "\<forall>f h. (f \<in> {j. j \<le> Suc n} \<rightarrow> carrier A) \<and>
(h \<in> {j. j\<le>Suc n} \<rightarrow> {j. j\<le>Suc n}) \<and> (inj_on h {j. j\<le>Suc n}) \<longrightarrow>
\<Sigma>\<^sub>e A (cmp f h) (Suc n) = \<Sigma>\<^sub>e A f (Suc n)")
apply (frule Nset_injTr0 [of "h" "Suc n"], assumption+, simp)
apply (frule Nset_injTr0 [of "h" "Suc n"], assumption+, simp)
apply (simp add:Pi_def)
done
lemma (in aGroup) additionTr1_1:"\<lbrakk>\<forall>f. \<forall>h. f \<in> {j. j\<le>Suc n} \<rightarrow> carrier A \<and>
h \<in> {j. j\<le>Suc n} \<rightarrow> {j. j\<le>Suc n} \<and> inj_on h {j. j\<le>Suc n} \<longrightarrow>
nsum A (cmp f h) (Suc n) = nsum A f (Suc n);
f \<in> {j. j\<le>Suc (Suc n)} \<rightarrow> carrier A; i \<le> n\<rbrakk> \<Longrightarrow>
nsum A (cmp f (transpos i (Suc n))) (Suc (Suc n)) = nsum A f (Suc (Suc n))"
apply (rule additionTr1 [of "n" "f" "transpos i (Suc n)"], assumption+)
apply (rule transpos_hom [of "i" "Suc (Suc n)" "Suc n"])
apply simp+
apply (rule transpos_inj [of "i" "Suc (Suc n)" "Suc n"])
apply simp+
apply (subst transpos_id[of i "Suc (Suc n)" "Suc n" "Suc (Suc n)"])
apply simp+
done
lemma (in aGroup) additionTr1_2:"\<lbrakk>\<forall>f. \<forall>h. f \<in> {j. j\<le>Suc n} \<rightarrow> carrier A \<and>
h \<in> {j. j\<le>Suc n} \<rightarrow> {j. j\<le>Suc n} \<and>
inj_on h {j. j\<le>Suc n} \<longrightarrow>
nsum A (cmp f h) (Suc n) = nsum A f (Suc n);
f \<in> {j. j\<le> Suc (Suc n)} \<rightarrow> carrier A; i \<le> (Suc n)\<rbrakk> \<Longrightarrow>
nsum A (cmp f (transpos i (Suc (Suc n)))) (Suc (Suc n)) =
nsum A f (Suc (Suc n))"
apply (case_tac "i = Suc n")
apply (simp del:nsum_suc)
apply (cut_tac additionTr0 [of "Suc (Suc n)" "f"], simp, simp,
rule allI, rule impI, rule funcset_mem[of f "{j. j \<le> Suc (Suc n)}"
"carrier A"], (simp del:nsum_suc)+)
apply (subst nsum_cmp_eq_transpos [THEN sym, of "Suc n" f i],
rule allI, rule impI, rule funcset_mem[of f "{j. j \<le> Suc (Suc n)}"
"carrier A"], assumption+,
simp, assumption+)
apply (subst nsum_cmp_eq [of "f" "Suc (Suc n)"
"cmp (transpos (Suc n) (Suc(Suc n))) (transpos i (Suc n))"
"transpos i (Suc n)" "Suc (Suc n)"], assumption+,
rule Pi_I, simp add:cmp_def,
rule transpos_mem, (simp del:nsum_suc)+,
rule transpos_mem, (simp del:nsum_suc)+,
rule Pi_I, simp,
rule transpos_mem, (simp del:nsum_suc)+)
apply (subst nsum_cmp_eq [of "cmp f (transpos i (Suc n))" "Suc (Suc n)"
"(transpos i (Suc n))" "transpos (Suc n) (Suc (Suc n))" "Suc (Suc n)"],
rule Pi_I, simp add:cmp_def,
rule funcset_mem[of f "{j. j \<le> Suc (Suc n)}" "carrier A"], assumption,
simp,
rule transpos_mem, (simp del:nsum_suc)+,
(rule Pi_I, simp,
rule transpos_mem, (simp del:nsum_suc)+)+)
apply (subst additionTr1_1 [of "n" "cmp (cmp f (transpos i (Suc n)))
(transpos (Suc n) (Suc (Suc n)))" "i"], assumption+,
rule cmp_fun [of _ "{j. j \<le> (Suc (Suc n))}"
"{j. j \<le> (Suc (Suc n))}" _ "carrier A"],
rule transpos_hom, simp, simp, simp,
rule cmp_fun [of _ "{j. j \<le> (Suc (Suc n))}"
"{j. j \<le> (Suc (Suc n))}" "f" "carrier A"],
rule transpos_hom, simp, simp, assumption+, arith)
apply (cut_tac additionTr0 [of "Suc (Suc n)" "cmp f (transpos i (Suc n))"],
simp del:nsum_suc,
thin_tac "nsum A (cmp
(cmp f (transpos i (Suc n))) (transpos (Suc n) (Suc (Suc n)))) (Suc (Suc n))
= nsum A (cmp f (transpos i (Suc n))) (Suc (Suc n))")
apply (rule additionTr1_1, assumption+, arith, simp,
rule allI, rule impI, simp add:cmp_def,
rule funcset_mem[of f "{j. j \<le> Suc (Suc n)}" "carrier A"],
assumption)
apply (simp add:transpos_mem)
done
lemma (in aGroup) additionTr2:" \<forall>f. \<forall>h. f \<in> {j. j \<le> (Suc n)} \<rightarrow> carrier A \<and>
h \<in> {j. j \<le> (Suc n)} \<rightarrow> {j. j \<le> (Suc n)} \<and>
inj_on h {j. j \<le> (Suc n)} \<longrightarrow>
nsum A (cmp f h) (Suc n) = nsum A f (Suc n)"
apply (induct_tac n)
apply (rule allI)+
apply (rule impI, (erule conjE)+)
apply (simp add:cmp_def)
apply (case_tac "h 0 = 0")
apply (simp add:Nset_1)
apply (simp add:Nset_1 ag_pOp_commute)
(************* n *****************)
apply (rule allI)+
apply (rule impI, (erule conjE)+)
apply (case_tac "h (Suc (Suc n)) = Suc (Suc n)")
apply (rule additionTr1, assumption+)
apply (frule_tac f = h and n = "Suc (Suc n)" in inj_surj, assumption+)
apply (frule sym, thin_tac "h ` {i. i \<le> Suc (Suc n)} = {i. i \<le> Suc (Suc n)}")
apply (cut_tac n = "Suc (Suc n)" in n_in_Nsetn)
apply (frule_tac a = "Suc (Suc n)" and A = "{i. i \<le> Suc (Suc n)}" and
B = "h ` {i. i \<le> Suc (Suc n)}" in eq_set_inc, assumption+)
apply (thin_tac "{i. i \<le> Suc (Suc n)} = h ` {i. i \<le> Suc (Suc n)}")
apply (simp del:nsum_suc add:image_def)
apply (erule exE, erule conjE)
apply (frule sym, thin_tac "Suc (Suc n) = h x")
apply (frule_tac i = x and n = "Suc (Suc n)" and j = "Suc (Suc n)" in
transpos_ij_2, simp del:nsum_suc add:n_in_Nsetn)
apply (rule contrapos_pp, (simp del:nsum_suc)+)
apply (frule_tac x = "transpos x (Suc (Suc n)) (Suc (Suc n))" and y = x and
f = h in eq_elems_eq_val,
thin_tac "transpos x (Suc (Suc n)) (Suc (Suc n)) = x",
simp del:nsum_suc)
apply (frule_tac f = h and A = "{i. i \<le> Suc (Suc n)}" and x = x and
y = "Suc (Suc n)" in inj_onTr2, simp, simp,
frule not_sym, simp)
apply (cut_tac f1 = "cmp f h" and n1 = n and i1 = x in
additionTr1_2[THEN sym], assumption)
apply (rule cmp_fun, simp, assumption, arith)
apply (simp del:nsum_suc,
thin_tac "\<Sigma>\<^sub>e A (cmp f h) (Suc (Suc n)) =
\<Sigma>\<^sub>e A (cmp (cmp f h) (transpos x (Suc (Suc n)))) (Suc (Suc n))")
apply (frule_tac f = f and n = "Suc n" and A = "carrier A" in func_pre)
apply (cut_tac f = "cmp h (transpos x (Suc (Suc n)))" and A = "{j. j \<le> (Suc ( Suc n))}" and ?A1.0 = "{j. j \<le> (Suc n)}" in restrict_inj)
apply (rule_tac f = "transpos x (Suc (Suc n))" and A = "{j. j \<le> Suc (Suc n)}"
and B = "{j. j \<le> Suc (Suc n)}" and g = h and C = "{j. j \<le> Suc (Suc n)}" in
cmp_inj, simp,
rule transpos_hom, simp, simp, assumption+,
rule transpos_inj, simp, simp, assumption+,
rule subsetI, simp)
apply (subst nsum_cmp_assoc,
rule allI, rule impI, simp add:Pi_def,
rule transpos_hom, assumption, simp, assumption+)
apply (cut_tac f = "cmp f (cmp h (transpos x (Suc (Suc n))))" and n = "Suc n"
in nsum_suc[of A ], simp del:nsum_suc,
thin_tac "\<Sigma>\<^sub>e A (cmp f (cmp h (transpos x (Suc (Suc n))))) (Suc (Suc n)) =
\<Sigma>\<^sub>e A (cmp f (cmp h (transpos x (Suc (Suc n))))) (Suc n) \<plusminus>
cmp f (cmp h (transpos x (Suc (Suc n)))) (Suc (Suc n))")
apply (frule_tac x = f in spec,
thin_tac "\<forall>f h. f \<in> {j. j \<le> Suc n} \<rightarrow> carrier A \<and>
h \<in> {j. j \<le> Suc n} \<rightarrow> {j. j \<le> Suc n} \<and>
inj_on h {j. j \<le> Suc n} \<longrightarrow>
\<Sigma>\<^sub>e A (cmp f h) (Suc n) = \<Sigma>\<^sub>e A f (Suc n)")
apply (frule_tac a = "cmp h (transpos x (Suc (Suc n)))" in forall_spec,
thin_tac "\<forall>h. f \<in> {j. j \<le> Suc n} \<rightarrow> carrier A \<and>
h \<in> {j. j \<le> Suc n} \<rightarrow> {j. j \<le> Suc n} \<and> inj_on h {j. j \<le> Suc n} \<longrightarrow>
\<Sigma>\<^sub>e A (cmp f h) (Suc n) = \<Sigma>\<^sub>e A f (Suc n)")
apply simp
apply (rule Pi_I)
apply (simp add:cmp_def)
apply (case_tac "xa = x", simp)
apply (cut_tac i = x and n = "Suc (Suc n)" and j = "Suc (Suc n)" in
transpos_ij_1, simp, simp, simp, simp,
frule_tac x = "Suc (Suc n)" and f = h and A = "{j. j \<le> Suc (Suc n)}"
and B = "{j. j \<le> Suc (Suc n)}" in funcset_mem, simp,
thin_tac "h \<in> {j. j \<le> Suc (Suc n)} \<rightarrow> {j. j \<le> Suc (Suc n)}")
apply (cut_tac m = "h (Suc (Suc n))" and n = "Suc (Suc n)" in noteq_le_less,
simp, simp,
rule_tac x = "h (Suc (Suc n))" and n = "Suc n" in Suc_less_le,
assumption)
apply (subst transpos_id, simp, simp, simp, simp,
frule_tac x = xa and f = h and A = "{j. j \<le> Suc (Suc n)}" and
B = "{j. j \<le> Suc (Suc n)}" in funcset_mem, simp)
apply (frule_tac f = h and A = "{j. j \<le> Suc (Suc n)}" and x = xa and y = x
in injective, simp, simp, assumption)
apply (cut_tac m = "h xa" and n = "Suc (Suc n)" in noteq_le_less, simp,
simp)
apply (rule Suc_less_le, assumption,
thin_tac "\<forall>h. f \<in> {j. j \<le> Suc n} \<rightarrow> carrier A \<and>
h \<in> {j. j \<le> Suc n} \<rightarrow> {j. j \<le> Suc n} \<and> inj_on h {j. j \<le> Suc n} \<longrightarrow>
\<Sigma>\<^sub>e A (cmp f h) (Suc n) = \<Sigma>\<^sub>e A f (Suc n)")
apply (simp del:nsum_suc add:cmp_def)
apply simp
done
lemma (in aGroup) addition2:"\<lbrakk>f \<in> {j. j \<le> (Suc n)} \<rightarrow> carrier A;
h \<in> {j. j \<le> (Suc n)} \<rightarrow> {j. j \<le> (Suc n)}; inj_on h {j. j \<le> (Suc n)}\<rbrakk> \<Longrightarrow>
nsum A (cmp f h) (Suc n) = nsum A f (Suc n)"
apply (simp del:nsum_suc add:additionTr2)
done
lemma (in aGroup) addition21:"\<lbrakk>f \<in> {j. j \<le> n} \<rightarrow> carrier A;
h \<in> {j. j \<le> n} \<rightarrow> {j. j \<le> n}; inj_on h {j. j \<le> n}\<rbrakk> \<Longrightarrow>
nsum A (cmp f h) n = nsum A f n"
apply (case_tac "n = 0")
apply (simp add: cmp_def)
apply (cut_tac f = f and n = "n - Suc 0" and h = h in addition2)
apply simp+
done
lemma (in aGroup) addition3:"\<lbrakk>\<forall>j \<le> (Suc n). f j \<in> carrier A; j \<le> (Suc n);
j \<noteq> Suc n\<rbrakk> \<Longrightarrow> nsum A f (Suc n) = nsum A (cmp f (transpos j (Suc n))) (Suc n)"
apply (rule addition2 [THEN sym,of "f" "n" "transpos j (Suc n)"])
apply (simp)
apply (rule transpos_hom, assumption+, simp, assumption)
apply (rule transpos_inj, simp+)
done
lemma (in aGroup) nsum_splitTr:"(\<forall>j \<le> (Suc (n + m)). f j \<in> carrier A) \<longrightarrow>
nsum A f (Suc (n + m)) = nsum A f n \<plusminus> (nsum A (cmp f (slide (Suc n))) m)"
apply (induct_tac m)
apply (rule impI) apply (simp add:slide_def cmp_def)
apply (rule impI, simp del:nsum_suc)
apply (cut_tac n = "Suc (n + na)" in nsum_suc[of A f],
simp del:nsum_suc,
thin_tac "\<Sigma>\<^sub>e A f (Suc (Suc (n + na))) =
\<Sigma>\<^sub>e A f n \<plusminus> \<Sigma>\<^sub>e A (cmp f (slide (Suc n))) na \<plusminus> f (Suc (Suc (n + na)))")
apply (cut_tac f = "cmp f (slide (Suc n))" and n = na in nsum_suc[of A],
simp del:nsum_suc)
apply (subst ag_pOp_assoc)
apply (rule nsum_mem, rule allI, simp)
apply (rule_tac n = na in nsum_mem,
thin_tac "\<Sigma>\<^sub>e A (cmp f (slide (Suc n))) (Suc na) =
\<Sigma>\<^sub>e A (cmp f (slide (Suc n))) na \<plusminus> (cmp f (slide (Suc n)) (Suc na))")
apply (rule allI, rule impI,
simp add:cmp_def slide_def, simp)
apply (simp add:cmp_def slide_def)
done
lemma (in aGroup) nsum_split:"\<forall>j \<le> (Suc (n + m)). f j \<in> carrier A \<Longrightarrow>
nsum A f (Suc (n + m)) = nsum A f n \<plusminus> (nsum A (cmp f (slide (Suc n))) m)"
by (simp del:nsum_suc add:nsum_splitTr)
lemma (in aGroup) nsum_split1:"\<lbrakk>\<forall>j \<le> m. f j \<in> carrier A; n < m\<rbrakk> \<Longrightarrow>
nsum A f m = nsum A f n \<plusminus> (fSum A f (Suc n) m)"
apply (cut_tac nsum_split[of n "m - n - Suc 0" f])
apply simp
apply (simp add:fSum_def)
apply simp
done
lemma (in aGroup) nsum_minusTr:" (\<forall>j \<le> n. f j \<in> carrier A) \<longrightarrow>
-\<^sub>a (nsum A f n) = nsum A (\<lambda>x\<in>{j. j \<le> n}. -\<^sub>a (f x)) n"
apply (induct_tac n)
apply (rule impI, simp)
apply (rule impI)
apply (subst nsum_suc, subst nsum_suc)
apply (subst ag_p_inv)
apply (rule_tac n = n in nsum_mem [of _ f],
rule allI, simp, simp)
apply (subgoal_tac "\<forall>j\<le>n. f j \<in> carrier A", simp)
apply (rule_tac a = "\<Sigma>\<^sub>e A (\<lambda>u. if u \<le> n then -\<^sub>a (f u) else undefined) n"
and b = "\<Sigma>\<^sub>e A (\<lambda>x\<in>{j. j \<le> (Suc n)}. -\<^sub>a (f x)) n" and c = "-\<^sub>a (f (Suc n))"
in ag_pOp_add_r,
rule_tac n = n in nsum_mem,
rule allI, rule impI, simp,
rule ag_mOp_closed, simp)
apply (rule_tac n = n in nsum_mem,
rule allI, rule impI, simp,
rule ag_mOp_closed, simp,
rule ag_mOp_closed, simp)
apply (rule_tac f = "\<lambda>u. if u \<le> n then -\<^sub>a (f u) else undefined" and
n = n and g = "\<lambda>x\<in>{j. j \<le> (Suc n)}. -\<^sub>a (f x)" in nsum_eq,
rule allI, rule impI,
simp, rule ag_mOp_closed, simp,
rule allI, simp, rule impI, rule ag_mOp_closed, simp)
apply (rule allI, simp)
apply (rule allI, simp)
done
lemma (in aGroup) nsum_minus:"\<forall>j \<le> n. f j \<in> carrier A \<Longrightarrow>
-\<^sub>a (nsum A f n) = nsum A (\<lambda>x\<in>{j. j \<le> n}. -\<^sub>a (f x)) n"
apply (simp add:nsum_minusTr)
done
lemma (in aGroup) ring_nsum_zeroTr:"(\<forall>j \<le> (n::nat). f j \<in> carrier A) \<and>
(\<forall>j \<le> n. f j = \<zero>) \<longrightarrow> nsum A f n = \<zero>"
apply (induct_tac n)
apply (rule impI) apply (erule conjE)+ apply simp
apply (rule impI, (erule conjE)+)
apply (cut_tac n = n in Nsetn_sub_mem1, simp)
apply (simp add:ag_inc_zero)
apply (cut_tac ag_inc_zero,
simp add:ag_r_zero)
done
lemma (in aGroup) ring_nsum_zero:"\<forall>j \<le> (n::nat). f j = \<zero> \<Longrightarrow> \<Sigma>\<^sub>e A f n = \<zero>"
apply (cut_tac ring_nsum_zeroTr[of n f])
apply (simp add:ag_inc_zero)
done
lemma (in aGroup) ag_nsum_1_nonzeroTr:
"\<forall>f. (\<forall>j \<le> n. f j \<in> carrier A) \<and>
(l \<le> n \<and> (\<forall>j \<in> {j. j \<le> n} - {l}. f j = \<zero>))
\<longrightarrow> nsum A f n = f l"
apply (induct_tac n)
apply simp
apply (rule allI,
rule impI, (erule conjE)+)
apply (case_tac "l = Suc n")
apply simp
apply (subgoal_tac "{j. j \<le> Suc n} - {Suc n} = {j. j \<le> n}", simp,
frule ring_nsum_zero, simp)
apply (rule ag_l_zero, simp)
apply (rule equalityI, rule subsetI, simp,
rule subsetI, simp)
apply (frule_tac m = l and n = "Suc n" in noteq_le_less, assumption,
thin_tac "l \<le> Suc n",
frule_tac x = l and n = n in Suc_less_le)
apply (cut_tac n = n in Nsetn_sub_mem1, simp)
apply (thin_tac "\<forall>f. (\<forall>j\<le>n. f j \<in> carrier A) \<and>
(\<forall>j\<in>{j. j \<le> n} - {l}. f j = \<zero>) \<longrightarrow>
\<Sigma>\<^sub>e A f n = f l",
frule_tac a = l in forall_spec, simp)
apply (simp add:ag_r_zero)
done
lemma (in aGroup) ag_nsum_1_nonzero:"\<lbrakk>\<forall>j \<le> n. f j \<in> carrier A; l \<le> n;
\<forall>j\<in>({j. j \<le> n} - {l}). f j = \<zero> \<rbrakk> \<Longrightarrow> nsum A f n = f l"
apply (simp add:ag_nsum_1_nonzeroTr[of n l])
done
definition
set_mult :: "[_ , 'a set, 'a set] \<Rightarrow> 'a set" where
"set_mult R A B = {z. \<exists>x\<in>A. \<exists>y\<in>B. x \<cdot>\<^sub>r\<^bsub>R\<^esub> y = z}"
definition
sum_mult :: "[_ , 'a set, 'a set] \<Rightarrow> 'a set" where
"sum_mult R A B = {x. \<exists>n. \<exists>f \<in> {j. j \<le> (n::nat)}
\<rightarrow> set_mult R A B. nsum R f n = x}"
(*
zero_fini::"[_ , 'a set, 'a set] \<Rightarrow> (nat \<Rightarrow> 'a)"
"zero_fini R A B i == \<zero> \<cdot>\<^sub>r \<zero>" *)
lemma (in Ring) set_mult_sub:"\<lbrakk>A \<subseteq> carrier R; B \<subseteq> carrier R\<rbrakk> \<Longrightarrow>
set_mult R A B \<subseteq> carrier R"
apply (rule subsetI, simp add:set_mult_def, (erule bexE)+,
frule sym, thin_tac "xa \<cdot>\<^sub>r y = x", simp)
apply (rule ring_tOp_closed, (simp add:subsetD)+)
done
lemma (in Ring) set_mult_mono:"\<lbrakk>A1 \<subseteq> carrier R; A2 \<subseteq> carrier R; A1 \<subseteq> A2;
B \<subseteq> carrier R\<rbrakk> \<Longrightarrow> set_mult R A1 B \<subseteq> set_mult R A2 B"
apply (rule subsetI)
apply (simp add:set_mult_def, (erule bexE)+)
apply (frule_tac c = xa in subsetD[of A1 A2], assumption+)
apply blast
done
lemma (in Ring) sum_mult_Tr1:"\<lbrakk>A \<subseteq> carrier R; B \<subseteq> carrier R\<rbrakk> \<Longrightarrow>
(\<forall>j \<le> n. f j \<in> set_mult R A B) \<longrightarrow> nsum R f n \<in> carrier R"
apply (cut_tac ring_is_ag)
apply (induct_tac n)
apply (rule impI, simp)
apply (frule set_mult_sub[of A B], assumption, simp add:subsetD)
apply (rule impI)
apply (cut_tac n = n in Nsetn_sub_mem1, simp)
apply (frule set_mult_sub[of A B], assumption)
apply (frule_tac a = "Suc n" in forall_spec, simp,
frule_tac c = "f (Suc n)" in subsetD[of "set_mult R A B" "carrier R"],
assumption)
apply (rule aGroup.ag_pOp_closed, assumption+)
done
lemma (in Ring) sum_mult_mem:"\<lbrakk>A \<subseteq> carrier R; B \<subseteq> carrier R;
\<forall>j \<le> n. f j \<in> set_mult R A B\<rbrakk> \<Longrightarrow> nsum R f n \<in> carrier R"
apply (cut_tac ring_is_ag)
apply (simp add:sum_mult_Tr1)
done
lemma (in Ring) sum_mult_mem1:"\<lbrakk>A \<subseteq> carrier R; B \<subseteq> carrier R;
x \<in> sum_mult R A B\<rbrakk> \<Longrightarrow>
\<exists>n. \<exists>f\<in>{j. j \<le> (n::nat)} \<rightarrow> set_mult R A B. nsum R f n = x"
by (simp add:sum_mult_def)
lemma (in Ring) sum_mult_subR:"\<lbrakk>A \<subseteq> carrier R; B \<subseteq> carrier R\<rbrakk> \<Longrightarrow>
sum_mult R A B \<subseteq> carrier R"
apply (rule subsetI)
apply (frule_tac x = x in sum_mult_mem1[of A B], assumption+)
apply (erule exE, erule bexE, frule sym, thin_tac "\<Sigma>\<^sub>e R f n = x", simp)
apply (cut_tac ring_is_ag)
apply (rule aGroup.nsum_mem[of R], assumption)
apply (rule allI, rule impI)
apply (frule_tac f = f and A = "{j. j \<le> n}" and B = "set_mult R A B" and
x = j in funcset_mem, simp)
apply (frule set_mult_sub[of A B], assumption)
apply (simp add:subsetD)
done
lemma (in Ring) times_mem_sum_mult:"\<lbrakk>A \<subseteq> carrier R; B \<subseteq> carrier R;
a \<in> A; b \<in> B \<rbrakk> \<Longrightarrow> a \<cdot>\<^sub>r b \<in> sum_mult R A B"
apply (simp add:sum_mult_def)
apply (subgoal_tac "(\<lambda>i\<in>{j. j \<le> (0::nat)}. a \<cdot>\<^sub>r b) \<in> {j. j \<le> 0} \<rightarrow> set_mult R A B")
apply (subgoal_tac "nsum R (\<lambda>i\<in>{j. j \<le> (0::nat)}. a \<cdot>\<^sub>r b) 0 = a \<cdot>\<^sub>r b")
apply blast
apply simp
apply (rule Pi_I, simp add:set_mult_def, blast)
done
lemma (in Ring) mem_minus_sum_multTr2:"\<lbrakk>A \<subseteq> carrier R; B \<subseteq> carrier R;
\<forall>j \<le> n. f j \<in> set_mult R A B; i \<le> n\<rbrakk> \<Longrightarrow> f i \<in> carrier R"
apply (frule_tac a = i in forall_spec, simp)
apply (frule set_mult_sub[of A B], assumption, simp add:subsetD)
done
lemma (in aGroup) nsum_jointfun:"\<lbrakk>\<forall>j \<le> n. f j \<in> carrier A;
\<forall>j \<le> m. g j \<in> carrier A\<rbrakk> \<Longrightarrow>
\<Sigma>\<^sub>e A (jointfun n f m g) (Suc (n + m)) = \<Sigma>\<^sub>e A f n \<plusminus> (\<Sigma>\<^sub>e A g m)"
apply (subst nsum_split)
apply (rule allI, rule impI)
apply (frule_tac f = f and n = n and A = "carrier A" and g = g and m = m
and B = "carrier A" in jointfun_mem, assumption+, simp)
apply (subgoal_tac "nsum A (jointfun n f m g) n = nsum A f n")
apply (subgoal_tac "nsum A (cmp (jointfun n f m g) (slide (Suc n))) m =
nsum A g m")
apply simp
apply (thin_tac "nsum A (jointfun n f m g) n = nsum A f n")
apply (rule nsum_eq)
apply (rule allI, rule impI,
simp add:cmp_def jointfun_def slide_def sliden_def,
assumption)
apply (rule allI, simp add:cmp_def jointfun_def slide_def sliden_def)
apply (rule nsum_eq)
apply (rule allI, rule impI,
simp add:jointfun_def, assumption)
apply (rule allI, rule impI)
apply (simp add:jointfun_def)
done
lemma (in Ring) sum_mult_pOp_closed:"\<lbrakk>A \<subseteq> carrier R; B \<subseteq> carrier R;
a \<in> sum_mult R A B; b \<in> sum_mult R A B \<rbrakk> \<Longrightarrow> a \<plusminus>\<^bsub>R\<^esub> b \<in> sum_mult R A B"
apply (cut_tac ring_is_ag)
apply (simp add:sum_mult_def)
apply ((erule exE)+, (erule bexE)+)
apply (rename_tac n m f g)
apply (frule sym, thin_tac "\<Sigma>\<^sub>e R f n = a", frule sym,
thin_tac "\<Sigma>\<^sub>e R g m = b", simp)
apply (frule set_mult_sub[of A B], assumption)
apply (subst aGroup.nsum_jointfun[THEN sym, of R], assumption)
apply (rule allI, rule impI,
frule_tac f = f and A = "{j. j \<le> n}" and B = "set_mult R A B" and
x = j in funcset_mem, simp, simp add:subsetD)
apply (rule allI, rule impI,
frule_tac f = g and A = "{j. j \<le> m}" and B = "set_mult R A B" and
x = j in funcset_mem, simp, simp add:subsetD)
apply (frule_tac f = f and n = n and A = "set_mult R A B" and g = g and m = m
and B = "set_mult R A B" in jointfun_hom, assumption+)
apply (simp del:nsum_suc)
apply blast
done
lemma (in Ring) set_mult_mOp_closed:"\<lbrakk>A \<subseteq> carrier R; ideal R B;
x \<in> set_mult R A B\<rbrakk> \<Longrightarrow> -\<^sub>a x \<in> set_mult R A B"
apply (cut_tac ring_is_ag,
simp add:set_mult_def,
(erule bexE)+, frule sym, thin_tac "xa \<cdot>\<^sub>r y = x", simp,
frule_tac c = xa in subsetD[of A "carrier R"], assumption+,
frule ideal_subset1[of B],
frule_tac c = y in subsetD[of B "carrier R"], assumption+,
simp add:ring_inv1_2,
frule_tac I = B and x = y in ideal_inv1_closed,
assumption+)
apply blast
done
lemma (in Ring) set_mult_ring_times_closed:"\<lbrakk>A \<subseteq> carrier R; ideal R B;
x \<in> set_mult R A B; r \<in> carrier R\<rbrakk> \<Longrightarrow> r \<cdot>\<^sub>r x \<in> set_mult R A B"
apply (cut_tac ring_is_ag,
simp add:set_mult_def,
(erule bexE)+, frule sym, thin_tac "xa \<cdot>\<^sub>r y = x", simp,
frule_tac c = xa in subsetD[of A "carrier R"], assumption+,
frule ideal_subset1[of B],
frule_tac c = y in subsetD[of B "carrier R"], assumption,
frule_tac x = r and y = "xa \<cdot>\<^sub>r y" in ring_tOp_commute,
simp add:ring_tOp_closed, simp,
subst ring_tOp_assoc, assumption+)
apply (frule_tac x = y and y = r in ring_tOp_commute, assumption+,
simp,
frule_tac x = y and r = r in ideal_ring_multiple [of B], assumption+)
apply blast
done
lemma (in Ring) set_mult_sub_sum_mult:"\<lbrakk>A \<subseteq> carrier R; ideal R B\<rbrakk> \<Longrightarrow>
set_mult R A B \<subseteq> sum_mult R A B"
apply (rule subsetI)
apply (simp add:sum_mult_def)
apply (cut_tac f = "(\<lambda>i\<in>{j. j \<le> (0::nat)}. x)" in nsum_0[of R])
apply (cut_tac n_in_Nsetn[of 0],
simp del:nsum_0)
apply (cut_tac f = "\<lambda>i\<in>{j. j \<le> (0::nat)}. x" and B = "%_. set_mult R A B" in
Pi_I[of "{j. j \<le> 0}"],
simp)
apply (subgoal_tac "\<Sigma>\<^sub>e R (\<lambda>i\<in>{j. j \<le> 0}. x) 0 = x")
apply blast
apply simp
done
lemma (in Ring) sum_mult_pOp_closedn:"\<lbrakk>A \<subseteq> carrier R; ideal R B\<rbrakk> \<Longrightarrow>
(\<forall>j \<le> n. f j \<in> set_mult R A B) \<longrightarrow> \<Sigma>\<^sub>e R f n \<in> sum_mult R A B"
apply (induct_tac n)
apply (rule impI, simp)
apply (frule set_mult_sub_sum_mult[of A B], assumption+, simp add:subsetD)
apply (rule impI)
apply simp
apply (frule_tac a = "Suc n" in forall_spec, simp)
apply (frule set_mult_sub_sum_mult[of A B], assumption+,
frule_tac c= "f (Suc n)" in
subsetD[of "set_mult R A B" "sum_mult R A B"], assumption+)
apply (rule sum_mult_pOp_closed, assumption,
simp add:ideal_subset1, assumption+)
done
lemma (in Ring) mem_minus_sum_multTr4:"\<lbrakk>A \<subseteq> carrier R; ideal R B\<rbrakk> \<Longrightarrow>
(\<forall>j \<le> n. f j \<in> set_mult R A B) \<longrightarrow> -\<^sub>a (nsum R f n) \<in> sum_mult R A B"
apply (cut_tac ring_is_ag)
apply (induct_tac n)
apply (rule impI)
apply (cut_tac n_in_Nsetn[of 0])
apply (frule_tac x = "f 0" in set_mult_mOp_closed[of A B], assumption+)
apply simp
apply (frule set_mult_sub_sum_mult[of A B], assumption+,
simp add:subsetD)
apply (rule impI)
apply (cut_tac n = n in Nsetn_sub_mem1, simp)
apply (frule sum_mult_subR[of A B], simp add:ideal_subset1)
apply (frule_tac n = n and f = f in sum_mult_pOp_closedn[of A B], assumption,
cut_tac n = n in Nsetn_sub_mem1, simp)
apply (frule_tac c = "\<Sigma>\<^sub>e R f n" in subsetD[of "sum_mult R A B" "carrier R"],
assumption+,
frule_tac a = "Suc n" in forall_spec, simp,
thin_tac "\<forall>j\<le>Suc n. f j \<in> set_mult R A B",
frule set_mult_sub[of A B], simp add:ideal_subset1,
frule_tac c = "f (Suc n)" in subsetD[of "set_mult R A B" "carrier R"],
assumption+ )
apply (frule_tac x = "\<Sigma>\<^sub>e R f n" and y = "f (Suc n)" in aGroup.ag_p_inv[of R],
assumption+, simp)
apply (rule_tac a = "-\<^sub>a (\<Sigma>\<^sub>e R f n)" and b = "-\<^sub>a (f (Suc n))" in
sum_mult_pOp_closed[of A B], assumption+,
simp add:ideal_subset1, assumption)
apply (frule_tac x = "f (Suc n)" in set_mult_mOp_closed[of A B], assumption+,
frule set_mult_sub_sum_mult[of A B], assumption+)
apply (simp add:subsetD)
done
lemma (in Ring) sum_mult_iOp_closed:"\<lbrakk>A \<subseteq> carrier R; ideal R B;
x \<in> sum_mult R A B \<rbrakk> \<Longrightarrow> -\<^sub>a x \<in> sum_mult R A B"
apply (frule sum_mult_mem1 [of A B x],
simp add:ideal_subset1, assumption)
apply (erule exE, erule bexE, frule sym, thin_tac "\<Sigma>\<^sub>e R f n = x")
apply simp
apply (frule_tac n = n and f = f in mem_minus_sum_multTr4[of A B],
assumption+)
apply (simp add:Pi_def)
done
lemma (in Ring) sum_mult_ring_multiplicationTr:
"\<lbrakk>A \<subseteq> carrier R; ideal R B; r \<in> carrier R\<rbrakk> \<Longrightarrow>
(\<forall>j \<le> n. f j \<in> set_mult R A B) \<longrightarrow> r \<cdot>\<^sub>r (nsum R f n) \<in> sum_mult R A B"
apply (cut_tac ring_is_ag)
apply (induct_tac n)
apply (rule impI, simp)
apply (simp add:set_mult_def)
apply ((erule bexE)+, frule sym, thin_tac "x \<cdot>\<^sub>r y = f 0", simp)
apply (frule_tac c = x in subsetD[of A "carrier R"], assumption+)
apply (frule ideal_subset1[of B],
frule_tac c = y in subsetD[of B "carrier R"], assumption,
frule_tac x = r and y = "x \<cdot>\<^sub>r y" in ring_tOp_commute,
simp add:ring_tOp_closed, simp,
subst ring_tOp_assoc, assumption+)
apply (frule_tac x = y and y = r in ring_tOp_commute, assumption+,
simp,
frule_tac x = y and r = r in ideal_ring_multiple [of B], assumption+)
apply (rule times_mem_sum_mult, assumption+)
apply (rule impI)
apply (cut_tac n = n in Nsetn_sub_mem1, simp)
apply (frule_tac f = f and n = n in aGroup.nsum_mem,
frule set_mult_sub [of "A" "B"], simp add:ideal_subset1,
rule allI, rule impI, cut_tac n = n in Nsetn_sub_mem1,
simp add: subsetD,
frule_tac a = "Suc n" in forall_spec, simp)
apply (frule set_mult_sub[of A B], simp add:ideal_subset1,
frule_tac c = "f (Suc n)" in subsetD[of "set_mult R A B" "carrier R"],
assumption)
apply (simp add: ring_distrib1)
apply (rule sum_mult_pOp_closed[of A B], assumption+,
simp add:ideal_subset1, assumption)
apply (frule_tac x = "f (Suc n)" in set_mult_ring_times_closed [of A B _ r],
assumption+, simp, assumption,
frule set_mult_sub_sum_mult[of A B], assumption+,
simp add:subsetD)
done
lemma (in Ring) sum_mult_ring_multiplication:"\<lbrakk>A \<subseteq> carrier R; ideal R B;
r \<in> carrier R; a \<in> sum_mult R A B\<rbrakk> \<Longrightarrow> r \<cdot>\<^sub>r a \<in> sum_mult R A B"
apply (cut_tac ring_is_ag)
apply (frule sum_mult_mem1[of A B a],
simp add:ideal_subset1, assumption)
apply (erule exE, erule bexE, frule sym, thin_tac "\<Sigma>\<^sub>e R f n = a", simp)
apply (subgoal_tac "\<forall>j \<le> n. f j \<in> set_mult R A B")
apply (simp add:sum_mult_ring_multiplicationTr)
apply (simp add:Pi_def)
done
lemma (in Ring) ideal_sum_mult:"\<lbrakk>A \<subseteq> carrier R; A \<noteq> {}; ideal R B\<rbrakk> \<Longrightarrow>
ideal R (sum_mult R A B)"
apply (simp add:ideal_def [of _ "sum_mult R A B"])
apply (cut_tac ring_is_ag)
apply (rule conjI)
apply (rule aGroup.asubg_test, assumption+)
apply (rule subsetI)
apply (frule_tac x = x in sum_mult_mem1[of A B],
simp add:ideal_subset1, assumption,
erule exE, erule bexE, frule sym, thin_tac "\<Sigma>\<^sub>e R f n = x", simp)
apply (rule_tac f = f and n = n in sum_mult_mem[of A B _ _], assumption+)
apply (simp add:ideal_subset1)
apply (simp add:Pi_def)
apply (frule nonempty_ex[of A], erule exE)
apply (frule ideal_zero[of B])
apply (frule_tac a = x and b = \<zero> in times_mem_sum_mult[of A B],
simp add:ideal_subset1, assumption+) apply blast
apply (rule ballI)+
apply (rule_tac a = a and b = "-\<^sub>a b" in sum_mult_pOp_closed[of A B],
assumption, simp add:ideal_subset1, assumption+,
rule_tac x = b in sum_mult_iOp_closed[of A B], assumption+)
apply (rule ballI)+
apply (rule sum_mult_ring_multiplication, assumption+)
done
lemma (in Ring) ideal_inc_set_multTr:"\<lbrakk>A \<subseteq> carrier R; ideal R B; ideal R C;
set_mult R A B \<subseteq> C \<rbrakk> \<Longrightarrow>
\<forall>f \<in> {j. j \<le> (n::nat)} \<rightarrow> set_mult R A B. \<Sigma>\<^sub>e R f n \<in> C"
apply (induct_tac n)
apply (simp add:subsetD)
apply (rule ballI)
apply (
frule_tac f = f and A = "{j. j \<le> Suc n}" and x = "Suc n" and
B = "set_mult R A B"in funcset_mem, simp,
frule_tac c = "f (Suc n)" in subsetD[of "set_mult R A B" "C"],
assumption+, simp)
apply (rule ideal_pOp_closed[of C], assumption+,
cut_tac n = n in Nsetn_sub_mem1,
frule_tac x = f in bspec, simp)
apply (simp add:Pi_def, assumption+)
done
lemma (in Ring) ideal_inc_set_mult:"\<lbrakk>A \<subseteq> carrier R; ideal R B; ideal R C;
set_mult R A B \<subseteq> C \<rbrakk> \<Longrightarrow> sum_mult R A B \<subseteq> C"
apply (rule subsetI)
apply (frule_tac x = x in sum_mult_mem1[of A B],
simp add:ideal_subset1, assumption+)
apply (erule exE, erule bexE, frule sym, thin_tac "\<Sigma>\<^sub>e R f n = x", simp,
thin_tac "x = \<Sigma>\<^sub>e R f n", simp add:subsetD)
apply (simp add:ideal_inc_set_multTr)
done
lemma (in Ring) AB_inc_sum_mult:"\<lbrakk>ideal R A; ideal R B\<rbrakk> \<Longrightarrow>
sum_mult R A B \<subseteq> A \<inter> B"
apply (frule ideal_subset1[of A], frule ideal_subset1[of B])
apply (frule ideal_inc_set_mult [of "A" "B" "A"], assumption+)
apply (rule subsetI,
simp add:set_mult_def, (erule bexE)+, frule sym, thin_tac "xa \<cdot>\<^sub>r y = x",
simp,
frule_tac c = xa in subsetD[of A "carrier R"], assumption+,
frule_tac c = y in subsetD[of B "carrier R"], assumption+,
subst ring_tOp_commute, assumption+,
simp add:ideal_ring_multiple)
apply (frule ideal_inc_set_mult [of "A" "B" "B"], assumption+)
apply (rule subsetI,
simp add:set_mult_def, (erule bexE)+, frule sym, thin_tac "xa \<cdot>\<^sub>r y = x",
simp,
frule_tac c = xa in subsetD[of A "carrier R"], assumption+,
simp add:ideal_ring_multiple)
apply simp
done
lemma (in Ring) sum_mult_is_ideal_prod:"\<lbrakk>ideal R A; ideal R B\<rbrakk> \<Longrightarrow>
sum_mult R A B = A \<diamondsuit>\<^sub>r B"
apply (rule equalityI)
apply (frule ideal_prod_ideal [of "A" "B"], assumption+)
apply (rule ideal_inc_set_mult)
apply (simp add:ideal_subset1)+
apply (rule subsetI)
apply (simp add:set_mult_def ideal_prod_def)
apply (auto del:subsetI)
apply (rule subsetI)
apply (simp add:ideal_prod_def)
apply (frule ideal_subset1[of A],
frule ideal_sum_mult[of A B],
frule ideal_zero[of A], blast, assumption)
apply (frule_tac a = "sum_mult R A B" in forall_spec, simp)
apply (rule subsetI, simp,
thin_tac "\<forall>xa. ideal R xa \<and> {x. \<exists>i\<in>A. \<exists>j\<in>B. x = i \<cdot>\<^sub>r j} \<subseteq> xa \<longrightarrow> x \<in> xa",
(erule bexE)+, simp)
apply (rule times_mem_sum_mult, assumption,
simp add:ideal_subset1, assumption+)
done
lemma (in Ring) ideal_prod_assocTr1:"\<lbrakk>ideal R A; ideal R B; ideal R C; y \<in> C\<rbrakk>
\<Longrightarrow> \<forall>f \<in> {j. j\<le>(n::nat)} \<rightarrow> set_mult R A B. (\<Sigma>\<^sub>e R f n) \<cdot>\<^sub>r y \<in> A \<diamondsuit>\<^sub>r (B \<diamondsuit>\<^sub>r C)"
apply (cut_tac ring_is_ag)
apply (frule ideal_prod_ideal[of "B" "C"], assumption+,
subst sum_mult_is_ideal_prod[of A "B \<diamondsuit>\<^sub>r C", THEN sym], assumption+)
apply (induct_tac n)
apply simp
apply (simp add:ideal_prod_assocTr0)
apply (rule ballI,
frule_tac x = f in bspec,
thin_tac "\<forall>f\<in>{j. j \<le> n} \<rightarrow> set_mult R A B.
\<Sigma>\<^sub>e R f n \<cdot>\<^sub>r y \<in> sum_mult R A (B \<diamondsuit>\<^sub>r C)",
rule Pi_I, simp,
frule_tac f = f and A = "{j. j \<le> Suc n}" and B = "set_mult R A B" and
x = x in funcset_mem, simp, assumption)
apply simp
apply (frule ideal_subset1[of A], frule ideal_subset1[of B],
frule set_mult_sub[of A B], assumption,
frule_tac f = f and A = "{j. j \<le> (Suc n)}" in extend_fun[of _ _
"set_mult R A B"
"carrier R"], assumption,
subst ring_distrib2,
simp add:ideal_subset)
apply (rule aGroup.nsum_mem, assumption)
apply (simp add:Pi_def)
apply (simp add:funcset_mem del:Pi_I',
frule_tac f = f and A = "{j. j \<le> Suc n}" and B = "set_mult R A B" and
x = "Suc n" in funcset_mem, simp)
apply (frule ideal_subset1[of A],
frule ideal_zero[of A],
frule ideal_sum_mult[of A "B \<diamondsuit>\<^sub>r C"], blast, assumption)
apply (rule ideal_pOp_closed, assumption+)
apply (simp add:ideal_prod_assocTr0)
done
lemma (in Ring) ideal_quotient_idealTr:"\<lbrakk>ideal R A; ideal R B; ideal R C;
x \<in> carrier R;\<forall>c\<in>C. x \<cdot>\<^sub>r c \<in> ideal_quotient R A B\<rbrakk> \<Longrightarrow>
f\<in>{j. j \<le> n} \<rightarrow> set_mult R B C \<longrightarrow> x \<cdot>\<^sub>r (nsum R f n) \<in> A"
apply (frule ideal_subset1 [of "A"],
frule ideal_subset1 [of "B"])
apply (induct_tac n)
apply (rule impI)
apply (cut_tac n_in_Nsetn[of 0])
apply (frule funcset_mem, assumption+)
apply (thin_tac "f \<in> {j. j \<le> 0} \<rightarrow> set_mult R B C")
apply (simp add:set_mult_def)
apply (erule bexE)+
apply (frule sym, thin_tac "xa \<cdot>\<^sub>r y = f 0", simp)
apply (frule_tac h = xa in ideal_subset[of B], assumption,
frule_tac h = y in ideal_subset[of C], assumption)
apply (frule_tac x = xa and y = y in ring_tOp_commute, assumption+,
simp)
apply (subst ring_tOp_assoc[THEN sym], assumption+)
apply (frule_tac x = y in bspec, assumption,
thin_tac "\<forall>c\<in>C. x \<cdot>\<^sub>r c \<in> A \<dagger>\<^sub>R B")
apply (simp add:ideal_quotient_def)
(****** n ********)
apply (rule impI)
apply (frule func_pre) apply simp
apply (cut_tac ring_is_ag)
apply (frule ideal_subset1[of B], frule ideal_subset1[of C],
frule set_mult_sub[of B C], assumption+)
apply (cut_tac n = n in nsum_memr [of _ "f"],
rule allI, rule impI,
frule_tac x = i in funcset_mem, simp, simp add:subsetD)
apply (frule_tac a = n in forall_spec, simp)
apply (thin_tac "\<forall>l\<le>n. \<Sigma>\<^sub>e R f l \<in> carrier R",
frule_tac f = f and A = "{j. j \<le> Suc n}" and B = "set_mult R B C"
and x = "Suc n" in funcset_mem, simp,
frule_tac c = "f (Suc n)" in subsetD[of "set_mult R B C" " carrier R"],
assumption+)
apply (subst ring_distrib1, assumption+)
apply (rule ideal_pOp_closed[of A], assumption+)
apply (simp add: set_mult_def, (erule bexE)+,
fold set_mult_def,
frule sym, thin_tac "xa \<cdot>\<^sub>r y = f (Suc n)", simp)
apply (frule_tac c = xa in subsetD[of B "carrier R"], assumption+,
frule_tac c = y in subsetD[of C "carrier R"], assumption+,
frule_tac x = xa and y = y in ring_tOp_commute, assumption, simp,
subst ring_tOp_assoc[THEN sym], assumption+)
apply (simp add:ideal_quotient_def)
done
lemma (in Ring) ideal_quotient_ideal:"\<lbrakk>ideal R A; ideal R B; ideal R C\<rbrakk> \<Longrightarrow>
A \<dagger>\<^sub>R B \<dagger>\<^sub>R C = A \<dagger>\<^sub>R B \<diamondsuit>\<^sub>r C"
apply (rule equalityI)
apply (rule subsetI)
apply (simp add:ideal_quotient_def [of _ _ "C"])
apply (erule conjE)
apply (simp add:ideal_quotient_def [of _ _ "B \<diamondsuit>\<^sub>r C"])
apply (rule ballI)
apply (simp add:sum_mult_is_ideal_prod [THEN sym])
apply (simp add:sum_mult_def)
apply (erule exE, erule bexE)
apply (rename_tac x c n f)
apply (frule sym) apply simp
apply (simp add:ideal_quotient_idealTr)
apply (rule subsetI)
apply (simp add:sum_mult_is_ideal_prod [THEN sym])
apply (simp add:ideal_quotient_def)
apply (erule conjE)
apply (rule ballI)
apply (rename_tac x c)
apply (frule ideal_subset [of "C"], assumption+)
apply (simp add:ring_tOp_closed)
apply (rule ballI)
apply (rename_tac x v u)
apply (frule ideal_subset [of "B"], assumption+)
apply (subst ring_tOp_assoc, assumption+)
apply (frule ideal_subset1[of B],
frule ideal_subset1[of C],
frule_tac a = u and b = v in times_mem_sum_mult[of B C], assumption+)
apply (frule_tac x = u and y = v in ring_tOp_commute, assumption,
simp)
done
lemma (in Ring) ideal_prod_assocTr:"\<lbrakk>ideal R A; ideal R B; ideal R C\<rbrakk> \<Longrightarrow>
\<forall>f. (f \<in> {j. j \<le> (n::nat)} \<rightarrow> set_mult R (A \<diamondsuit>\<^sub>r B) C \<longrightarrow>
(\<Sigma>\<^sub>e R f n) \<in> A \<diamondsuit>\<^sub>r (B \<diamondsuit>\<^sub>r C))"
apply (subgoal_tac "\<forall>x\<in>(A \<diamondsuit>\<^sub>r B). \<forall>y\<in>C. x \<cdot>\<^sub>r y \<in> A \<diamondsuit>\<^sub>r (B \<diamondsuit>\<^sub>r C)")
apply (induct_tac n)
apply (rule allI) apply (rule impI)
apply (frule_tac f = f and A = "{j. j \<le> 0}" and B = "set_mult R (A \<diamondsuit>\<^sub>r B) C"
and x = 0 in funcset_mem, simp, simp)
apply (simp add:set_mult_def)
apply ((erule bexE)+, frule sym, thin_tac "x \<cdot>\<^sub>r y = f 0", simp)
apply (rule allI, rule impI)
apply (frule func_pre)
apply (frule_tac a = f in forall_spec, simp,
thin_tac "\<forall>f. f \<in> {j. j \<le> n} \<rightarrow> set_mult R (A \<diamondsuit>\<^sub>r B) C \<longrightarrow>
\<Sigma>\<^sub>e R f n \<in> A \<diamondsuit>\<^sub>r (B \<diamondsuit>\<^sub>r C)",
frule ideal_prod_ideal[of "B" "C"], assumption+,
frule ideal_prod_ideal[of "A" "B \<diamondsuit>\<^sub>r C"], assumption+, simp)
apply (rule ideal_pOp_closed[of "A \<diamondsuit>\<^sub>r (B \<diamondsuit>\<^sub>r C)"], assumption+)
apply (cut_tac n = "Suc n" in n_in_Nsetn,
frule_tac f = f and A = "{j. j \<le> Suc n}" and
B = "set_mult R (A \<diamondsuit>\<^sub>r B) C" and x = "Suc n" in funcset_mem, assumption)
apply (thin_tac "f \<in> {j. j \<le> n} \<rightarrow> set_mult R (A \<diamondsuit>\<^sub>r B) C",
thin_tac "f \<in> {j. j \<le> Suc n} \<rightarrow> set_mult R (A \<diamondsuit>\<^sub>r B) C")
apply (simp add:set_mult_def)
apply ((erule bexE)+,
frule sym, thin_tac "x \<cdot>\<^sub>r y = f (Suc n)", simp)
apply (rule ballI)+
apply (simp add:sum_mult_is_ideal_prod[of A B, THEN sym])
apply (frule ideal_subset1[of A], frule ideal_subset1[of B],
frule_tac x = x in sum_mult_mem1[of A B], assumption+)
apply (erule exE, erule bexE, frule sym, thin_tac "\<Sigma>\<^sub>e R f n = x",
simp)
apply (simp add:ideal_prod_assocTr1)
done
lemma (in Ring) ideal_prod_assoc:"\<lbrakk>ideal R A; ideal R B; ideal R C\<rbrakk> \<Longrightarrow>
(A \<diamondsuit>\<^sub>r B) \<diamondsuit>\<^sub>r C = A \<diamondsuit>\<^sub>r (B \<diamondsuit>\<^sub>r C)"
apply (rule equalityI)
apply (rule subsetI)
apply (frule ideal_prod_ideal[of "A" "B"], assumption+)
apply (frule sum_mult_is_ideal_prod[of "A \<diamondsuit>\<^sub>r B" "C"], assumption+)
apply (frule sym) apply (thin_tac "sum_mult R (A \<diamondsuit>\<^sub>r B) C = (A \<diamondsuit>\<^sub>r B) \<diamondsuit>\<^sub>r C")
apply simp apply (thin_tac "(A \<diamondsuit>\<^sub>r B) \<diamondsuit>\<^sub>r C = sum_mult R (A \<diamondsuit>\<^sub>r B) C")
apply (thin_tac "ideal R (A \<diamondsuit>\<^sub>r B)")
apply (frule ideal_prod_ideal[of "B" "C"], assumption+)
apply (simp add:sum_mult_def)
apply (erule exE, erule bexE)
apply (frule sym, thin_tac "\<Sigma>\<^sub>e R f n = x", simp)
apply (simp add:ideal_prod_assocTr)
apply (rule subsetI)
apply (frule ideal_prod_ideal[of "B" "C"], assumption+)
apply (simp add:ideal_prod_commute [of "A" "B \<diamondsuit>\<^sub>r C"])
apply (frule ideal_prod_ideal[of "A" "B"], assumption+)
apply (simp add:ideal_prod_commute[of "A \<diamondsuit>\<^sub>r B" "C"])
apply (simp add:ideal_prod_commute[of "A" "B"])
apply (simp add:ideal_prod_commute[of "B" "C"])
apply (frule ideal_prod_ideal[of "C" "B"], assumption+)
apply (frule sum_mult_is_ideal_prod[of "C \<diamondsuit>\<^sub>r B" "A"], assumption+)
apply (frule sym) apply (thin_tac "sum_mult R (C \<diamondsuit>\<^sub>r B) A = (C \<diamondsuit>\<^sub>r B) \<diamondsuit>\<^sub>r A")
apply simp apply (thin_tac "(C \<diamondsuit>\<^sub>r B) \<diamondsuit>\<^sub>r A = sum_mult R (C \<diamondsuit>\<^sub>r B) A")
apply (thin_tac "ideal R (C \<diamondsuit>\<^sub>r B)")
apply (frule ideal_prod_ideal[of "B" "A"], assumption+)
apply (simp add:sum_mult_def)
apply (erule exE, erule bexE)
apply (frule sym, thin_tac "\<Sigma>\<^sub>e R f n = x", simp)
apply (simp add:ideal_prod_assocTr)
done
lemma (in Ring) prod_principal_idealTr0:" \<lbrakk>a \<in> carrier R; b \<in> carrier R;
z \<in> set_mult R (R \<diamondsuit>\<^sub>p a) (R \<diamondsuit>\<^sub>p b)\<rbrakk> \<Longrightarrow> z \<in> R \<diamondsuit>\<^sub>p (a \<cdot>\<^sub>r b)"
apply (simp add:set_mult_def, (erule bexE)+,
simp add:Rxa_def, (erule bexE)+, simp)
apply (frule_tac x = r and y = a and z = "ra \<cdot>\<^sub>r b" in ring_tOp_assoc,
assumption+, simp add:ring_tOp_closed, simp)
apply (simp add:ring_tOp_assoc[THEN sym, of a _ b])
apply (frule_tac x = a and y = ra in ring_tOp_commute, assumption+, simp)
apply (simp add:ring_tOp_assoc[of _ a b],
frule_tac x = a and y = b in ring_tOp_closed, assumption)
apply (simp add:ring_tOp_assoc[THEN sym, of _ _ "a \<cdot>\<^sub>r b"],
frule sym, thin_tac "r \<cdot>\<^sub>r ra \<cdot>\<^sub>r (a \<cdot>\<^sub>r b) = z", simp,
frule_tac x = r and y = ra in ring_tOp_closed, assumption+)
apply blast
done
lemma (in Ring) prod_principal_idealTr1:" \<lbrakk>a \<in> carrier R; b \<in> carrier R\<rbrakk> \<Longrightarrow>
\<forall>f \<in> {j. j \<le> (n::nat)} \<rightarrow> set_mult R (R \<diamondsuit>\<^sub>p a) (R \<diamondsuit>\<^sub>p b).
\<Sigma>\<^sub>e R f n \<in> R \<diamondsuit>\<^sub>p (a \<cdot>\<^sub>r b)"
apply (induct_tac n)
apply (rule ballI,
frule_tac f = f in funcset_mem[of _ "{j. j \<le> 0}"
"set_mult R (R \<diamondsuit>\<^sub>p a) (R \<diamondsuit>\<^sub>p b)"], simp)
apply (simp add:prod_principal_idealTr0)
apply (rule ballI,
frule func_pre,
frule_tac x = f in bspec, assumption,
thin_tac "\<forall>f\<in>{j. j \<le> n} \<rightarrow> set_mult R (R \<diamondsuit>\<^sub>p a) (R \<diamondsuit>\<^sub>p b).
\<Sigma>\<^sub>e R f n \<in> R \<diamondsuit>\<^sub>p (a \<cdot>\<^sub>r b)")
apply (frule ring_tOp_closed[of a b], assumption)
apply (frule principal_ideal[of "a \<cdot>\<^sub>r b"], simp,
rule ideal_pOp_closed, assumption+)
apply (cut_tac n = "Suc n" in n_in_Nsetn,
frule_tac f = f and A = "{j. j \<le> Suc n}" and
B = "set_mult R (R \<diamondsuit>\<^sub>p a) (R \<diamondsuit>\<^sub>p b)" in funcset_mem, assumption)
apply (simp add:prod_principal_idealTr0)
done
lemma (in Ring) prod_principal_ideal:"\<lbrakk>a \<in> carrier R; b \<in> carrier R\<rbrakk> \<Longrightarrow>
(Rxa R a) \<diamondsuit>\<^sub>r (Rxa R b) = Rxa R (a \<cdot>\<^sub>r b)"
apply (frule principal_ideal[of "a"],
frule principal_ideal[of "b"])
apply (subst sum_mult_is_ideal_prod[THEN sym, of "Rxa R a" "Rxa R b"],
assumption+)
apply (rule equalityI)
apply (rule subsetI)
apply (simp add:sum_mult_def)
apply (erule exE, erule bexE)
apply (frule sym, thin_tac "\<Sigma>\<^sub>e R f n = x", simp, thin_tac "x = \<Sigma>\<^sub>e R f n")
apply (simp add:prod_principal_idealTr1)
apply (rule subsetI)
apply (simp add:Rxa_def, fold Rxa_def)
apply (erule bexE)
apply (simp add:ring_tOp_assoc[THEN sym])
apply (frule ideal_subset1[of "R \<diamondsuit>\<^sub>p a"],
frule ideal_subset1[of "R \<diamondsuit>\<^sub>p b"])
apply (rule_tac a = "r \<cdot>\<^sub>r a" and b = b in times_mem_sum_mult[of "R \<diamondsuit>\<^sub>p a"
"R \<diamondsuit>\<^sub>p b"], assumption+)
apply (simp add:Rxa_def, blast)
apply (simp add:a_in_principal)
done
lemma (in Ring) principal_ideal_n_pow1:"a \<in> carrier R \<Longrightarrow>
(Rxa R a)\<^bsup>\<diamondsuit>R n\<^esup> = Rxa R (a^\<^bsup>R n \<^esup>)"
apply (cut_tac ring_one)
apply (induct_tac n)
apply simp
apply (cut_tac a_in_principal[of "1\<^sub>r"])
apply (frule principal_ideal[of "1\<^sub>r"])
apply (frule ideal_inc_one, assumption, simp)
apply (simp add:ring_one)
apply simp
apply (frule_tac n = n in npClose[of a],
subst prod_principal_ideal, assumption+)
apply (simp add:ring_tOp_commute)
done
lemma (in Ring) principal_ideal_n_pow:"\<lbrakk>a \<in> carrier R; I = Rxa R a\<rbrakk> \<Longrightarrow>
I \<^bsup>\<diamondsuit>R n\<^esup> = Rxa R (a^\<^bsup>R n\<^esup>)"
apply simp
apply (rule principal_ideal_n_pow1[of "a" "n"], assumption+)
done
text\<open>more about \<open>ideal_n_prod\<close>\<close>
lemma (in Ring) nprod_eqTr:" f \<in> {j. j \<le> (n::nat)} \<rightarrow> carrier R \<and>
g \<in> {j. j \<le> n} \<rightarrow> carrier R \<and> (\<forall>j \<le> n. f j = g j) \<longrightarrow>
nprod R f n = nprod R g n"
apply (induct_tac n)
apply simp
apply (rule impI, (erule conjE)+)
apply (frule func_pre[of f], frule func_pre[of g],
cut_tac n = n in Nsetn_sub_mem1, simp)
done
lemma (in Ring) nprod_eq:"\<lbrakk>\<forall>j \<le> n. f j \<in> carrier R; \<forall>j \<le> n. g j \<in> carrier R;
(\<forall>j \<le> (n::nat). f j = g j)\<rbrakk> \<Longrightarrow> nprod R f n = nprod R g n"
apply (cut_tac nprod_eqTr[of f n g])
apply simp
done
definition
mprod_expR :: "[('b, 'm) Ring_scheme, nat \<Rightarrow> nat, nat \<Rightarrow> 'b, nat] \<Rightarrow> 'b" where
"mprod_expR R e f n = nprod R (\<lambda>j. ((f j)^\<^bsup>R (e j)\<^esup>)) n"
(** Note that e j is a natural number for all j in Nset n **)
lemma (in Ring) mprodR_Suc:"\<lbrakk>e \<in> {j. j \<le> (Suc n)} \<rightarrow> {j. (0::nat) \<le> j};
f \<in> {j. j \<le> (Suc n)} \<rightarrow> carrier R\<rbrakk> \<Longrightarrow>
mprod_expR R e f (Suc n) =
(mprod_expR R e f n) \<cdot>\<^sub>r ((f (Suc n))^\<^bsup>R (e (Suc n))\<^esup>)"
apply (simp add:mprod_expR_def)
done
lemma (in Ring) mprod_expR_memTr:"e \<in> {j. j \<le> n} \<rightarrow> {j. (0::nat) \<le> j} \<and>
f \<in> {j. j \<le> n} \<rightarrow> carrier R \<longrightarrow> mprod_expR R e f n \<in> carrier R"
apply (induct_tac n)
apply (rule impI, (erule conjE)+)
apply (cut_tac n_in_Nsetn[of 0],
simp add: mprod_expR_def)
apply (rule npClose,
simp add:Pi_def)
apply (rule impI, (erule conjE)+)
apply (frule func_pre[of "e"], frule func_pre[of "f"])
apply simp
apply (simp add:mprodR_Suc)
apply (rule ring_tOp_closed, assumption+)
apply (rule npClose, cut_tac n = "Suc n" in n_in_Nsetn)
apply (simp add:Pi_def)
done
lemma (in Ring) mprod_expR_mem:"\<lbrakk> e \<in> {j. j \<le> n} \<rightarrow> {j. (0::nat) \<le> j};
f \<in> {j. j \<le> n} \<rightarrow> carrier R\<rbrakk> \<Longrightarrow> mprod_expR R e f n \<in> carrier R"
apply (simp add:mprod_expR_memTr)
done
lemma (in Ring) prod_n_principal_idealTr:"e \<in> {j. j\<le>n} \<rightarrow> {j. (0::nat)\<le>j} \<and>
f \<in> {j. j\<le>n} \<rightarrow> carrier R \<and> (\<forall>k \<le> n. J k = (Rxa R (f k))\<^bsup>\<diamondsuit>R (e k)\<^esup>) \<longrightarrow>
ideal_n_prod R n J = Rxa R (mprod_expR R e f n)"
apply (induct_tac n)
apply (rule impI) apply (erule conjE)+
apply (simp add:mprod_expR_def)
apply (subgoal_tac "J 0 = R \<diamondsuit>\<^sub>p (f 0) \<^bsup>\<diamondsuit>R (e 0)\<^esup>")
apply simp
apply (rule principal_ideal_n_pow[of "f 0" "R \<diamondsuit>\<^sub>p (f 0)"])
apply (cut_tac n_in_Nsetn[of 0], simp add:Pi_def) apply simp
apply (cut_tac n_in_Nsetn[of 0], simp)
apply (rule impI, (erule conjE)+)
apply (frule func_pre[of "e"], frule func_pre[of "f"])
apply (cut_tac n = n in Nsetn_sub_mem1,
simp add:mprodR_Suc)
apply (cut_tac n = "Suc n" in n_in_Nsetn, simp)
apply (frule_tac A = "{j. j \<le> Suc n}" and x = "Suc n" in funcset_mem[of "f" _ "carrier R"], simp)
apply (frule_tac a = "f (Suc n)" and I = "R \<diamondsuit>\<^sub>p (f (Suc n))" and n = "e (Suc n)" in principal_ideal_n_pow) apply simp
apply (subst prod_principal_ideal[THEN sym])
apply (simp add:mprod_expR_mem)
apply (rule npClose, assumption+) apply simp
done
(************* used in Valuation2.thy *****************)
lemma (in Ring) prod_n_principal_ideal:"\<lbrakk>e \<in> {j. j\<le>n} \<rightarrow> {j. (0::nat)\<le>j};
f \<in> {j. j\<le>n} \<rightarrow> carrier R; \<forall>k\<le> n. J k = (Rxa R (f k))\<^bsup>\<diamondsuit>R (e k)\<^esup>\<rbrakk> \<Longrightarrow>
ideal_n_prod R n J = Rxa R (mprod_expR R e f n)"
apply (simp add:prod_n_principal_idealTr[of e n f J])
done
(*******************************************************)
lemma (in Idomain) a_notin_n_pow1:"\<lbrakk>a \<in> carrier R; \<not> Unit R a; a \<noteq> \<zero>; 0 < n\<rbrakk>
\<Longrightarrow> a \<notin> (Rxa R a) \<^bsup>\<diamondsuit>R (Suc n)\<^esup>"
apply (rule contrapos_pp)
apply (simp del:ipSuc) apply (simp del:ipSuc)
apply (frule principal_ideal[of "a"])
apply (frule principal_ideal_n_pow[of "a" "R \<diamondsuit>\<^sub>p a" "Suc n"])
apply simp apply (simp del:ipSuc)
apply (thin_tac "R \<diamondsuit>\<^sub>p a \<^bsup>\<diamondsuit>R (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (a^\<^bsup>R n\<^esup> \<cdot>\<^sub>r a)")
apply (thin_tac "ideal R (R \<diamondsuit>\<^sub>p a)")
apply (simp add:Rxa_def)
apply (erule bexE)
apply (frule npClose[of "a" "n"])
apply (simp add:ring_tOp_assoc[THEN sym])
apply (frule ring_l_one[THEN sym, of "a"])
apply (subgoal_tac "1\<^sub>r \<cdot>\<^sub>r a = r \<cdot>\<^sub>r a^\<^bsup>R n\<^esup> \<cdot>\<^sub>r a")
apply (cut_tac b = "r \<cdot>\<^sub>r (a^\<^bsup>R n\<^esup>)" in idom_mult_cancel_r[of "1\<^sub>r" _ "a"])
apply (simp add:ring_one) apply (simp add:ring_tOp_closed)
apply assumption+
apply (thin_tac "1\<^sub>r \<cdot>\<^sub>r a = r \<cdot>\<^sub>r a^\<^bsup>R n\<^esup> \<cdot>\<^sub>r a",
thin_tac "a = 1\<^sub>r \<cdot>\<^sub>r a",
thin_tac "a = r \<cdot>\<^sub>r a^\<^bsup>R n\<^esup> \<cdot>\<^sub>r a")
apply (subgoal_tac "1\<^sub>r = r \<cdot>\<^sub>r (a^\<^bsup>R (Suc (n - Suc 0))\<^esup>)") prefer 2
apply (simp del:ipSuc)
apply (thin_tac "1\<^sub>r = r \<cdot>\<^sub>r a^\<^bsup>R n\<^esup>")
apply (simp del:Suc_pred)
apply (frule npClose[of "a" "n - Suc 0"])
apply (simp add:ring_tOp_assoc[THEN sym])
apply (frule_tac x = r and y = "a^\<^bsup>R (n - Suc 0)\<^esup>" in ring_tOp_closed, assumption)
apply (simp add:ring_tOp_commute[of _ a])
apply (simp add:Unit_def) apply blast
apply simp
done
lemma (in Idomain) a_notin_n_pow2:"\<lbrakk>a \<in> carrier R; \<not> Unit R a; a \<noteq> \<zero>;
0 < n\<rbrakk> \<Longrightarrow> a^\<^bsup>R n\<^esup> \<notin> (Rxa R a) \<^bsup>\<diamondsuit>R (Suc n)\<^esup>"
apply (rule contrapos_pp)
apply (simp del:ipSuc, simp del:ipSuc)
apply (frule principal_ideal[of "a"])
apply (frule principal_ideal_n_pow[of "a" "R \<diamondsuit>\<^sub>p a" "Suc n"])
apply (simp, simp del:ipSuc)
apply (thin_tac "R \<diamondsuit>\<^sub>p a \<^bsup>\<diamondsuit>R (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (a^\<^bsup>R n\<^esup> \<cdot>\<^sub>r a)")
apply (thin_tac "ideal R (R \<diamondsuit>\<^sub>p a)")
apply (simp add:Rxa_def)
apply (erule bexE)
apply (frule idom_potent_nonzero[of "a" "n"], assumption+)
apply (frule npClose[of "a" "n"])
apply (frule ring_l_one[THEN sym, of "a^\<^bsup>R n\<^esup> "])
apply (subgoal_tac "1\<^sub>r \<cdot>\<^sub>r (a^\<^bsup>R n\<^esup>) = r \<cdot>\<^sub>r ((a^\<^bsup>R n\<^esup>) \<cdot>\<^sub>r a)")
prefer 2 apply simp
apply (thin_tac "a^\<^bsup>R n\<^esup> = 1\<^sub>r \<cdot>\<^sub>r a^\<^bsup>R n\<^esup>",
thin_tac "a^\<^bsup>R n\<^esup> = r \<cdot>\<^sub>r (a^\<^bsup>R n\<^esup> \<cdot>\<^sub>r a)")
apply (simp add:ring_tOp_commute[of "a^\<^bsup>R n\<^esup>" a])
apply (simp add:ring_tOp_assoc[THEN sym])
apply (cut_tac ring_one,
frule_tac b = "r \<cdot>\<^sub>r a" in idom_mult_cancel_r[of "1\<^sub>r" _ "a^\<^bsup>R n\<^esup>"],
simp add:ring_tOp_closed,
assumption+)
apply (simp add:ring_tOp_commute[of _ a])
apply (simp add:Unit_def, blast)
done
lemma (in Idomain) n_pow_not_prime:"\<lbrakk>a \<in> carrier R; a \<noteq> \<zero>; 0 < n\<rbrakk>
\<Longrightarrow> \<not> prime_ideal R ((Rxa R a) \<^bsup>\<diamondsuit>R (Suc n)\<^esup>)"
apply (case_tac "n = 0")
apply simp
apply (case_tac "Unit R a")
apply (simp del:ipSuc add:prime_ideal_def, rule impI)
apply (frule principal_ideal[of "a"])
apply (frule principal_ideal_n_pow[of "a" "R \<diamondsuit>\<^sub>p a" "Suc n"])
apply simp apply (simp del:npow_suc)
apply (simp del:npow_suc add:idom_potent_unit [of "a" "Suc n"])
apply (thin_tac "R \<diamondsuit>\<^sub>p a \<diamondsuit>\<^sub>r R \<diamondsuit>\<^sub>p a \<^bsup>\<diamondsuit>R n\<^esup> = R \<diamondsuit>\<^sub>p (a^\<^bsup>R (Suc n)\<^esup>)")
apply (frule npClose[of "a" "Suc n"])
apply (frule a_in_principal[of "a^\<^bsup>R (Suc n)\<^esup>"])
apply (simp add: ideal_inc_unit)
apply (frule a_notin_n_pow1[of "a" "n"], assumption+)
apply (frule a_notin_n_pow2[of "a" "n"], assumption+)
apply (frule npClose[of "a" "n"])
apply (frule principal_ideal[of "a"])
apply (frule principal_ideal_n_pow[of "a" "R \<diamondsuit>\<^sub>p a" "Suc n"])
apply simp apply (simp del:ipSuc npow_suc)
apply (thin_tac "R \<diamondsuit>\<^sub>p a \<^bsup>\<diamondsuit>R (Suc n)\<^esup> = R \<diamondsuit>\<^sub>p (a^\<^bsup>R (Suc n)\<^esup>)")
apply (subst prime_ideal_def)
apply (simp del:npow_suc) apply (rule impI)
apply (subgoal_tac "(a^\<^bsup>R n\<^esup>) \<cdot>\<^sub>r a \<in> R \<diamondsuit>\<^sub>p (a^\<^bsup>R (Suc n)\<^esup>)")
apply blast
apply (simp add:Rxa_def)
apply (frule ring_tOp_closed[of "a" "a^\<^bsup>R n\<^esup>"], assumption+)
apply (frule ring_l_one[THEN sym, of "a \<cdot>\<^sub>r (a^\<^bsup>R n\<^esup>)"])
apply (cut_tac ring_one)
apply (simp add:ring_tOp_commute[of _ a], blast)
done
lemma (in Idomain) principal_pow_prime_condTr:
"\<lbrakk>a \<in> carrier R; a \<noteq> \<zero>; prime_ideal R ((Rxa R a) \<^bsup>\<diamondsuit>R (Suc n)\<^esup>)\<rbrakk> \<Longrightarrow> n = 0"
apply (rule contrapos_pp, (simp del:ipSuc)+)
apply (frule n_pow_not_prime[of "a" "n"], assumption+)
apply (simp del:ipSuc)
done
lemma (in Idomain) principal_pow_prime_cond:
"\<lbrakk>a \<in> carrier R; a \<noteq> \<zero>; prime_ideal R ((Rxa R a) \<^bsup>\<diamondsuit>R n\<^esup>)\<rbrakk> \<Longrightarrow> n = Suc 0"
apply (case_tac "n = 0")
apply simp
apply (simp add:prime_ideal_def) apply (erule conjE)
apply (cut_tac ring_one, simp)
apply (subgoal_tac "prime_ideal R (R \<diamondsuit>\<^sub>p a \<^bsup>\<diamondsuit>R (Suc (n - Suc 0))\<^esup>)")
apply (frule principal_pow_prime_condTr[of "a" "n - Suc 0"], assumption+)
apply simp apply simp
done
section "Extension and contraction"
locale TwoRings = Ring +
fixes R' (structure)
assumes secondR: "Ring R'"
definition
i_contract :: "['a \<Rightarrow> 'b, ('a, 'm1) Ring_scheme, ('b, 'm2) Ring_scheme,
'b set] \<Rightarrow> 'a set" where
"i_contract f R R' J = invim f (carrier R) J"
definition
i_extension :: "['a \<Rightarrow> 'b, ('a, 'm1) Ring_scheme, ('b, 'm2) Ring_scheme,
'a set] \<Rightarrow> 'b set" where
"i_extension f R R' I = sum_mult R' (f ` I) (carrier R')"
lemma (in TwoRings) i_contract_sub:"\<lbrakk>f \<in> rHom R R'; ideal R' J \<rbrakk> \<Longrightarrow>
(i_contract f R R' J) \<subseteq> carrier R"
by (auto simp add:i_contract_def invim_def)
lemma (in TwoRings) i_contract_mono:"\<lbrakk>f \<in> rHom R R'; ideal R' J1; ideal R' J2;
J1 \<subseteq> J2 \<rbrakk> \<Longrightarrow> i_contract f R R' J1 \<subseteq> i_contract f R R' J2"
apply (rule subsetI)
apply (simp add:i_contract_def invim_def) apply (erule conjE)
apply (rule subsetD, assumption+)
done
lemma (in TwoRings) i_contract_prime:"\<lbrakk>f \<in> rHom R R'; prime_ideal R' P\<rbrakk> \<Longrightarrow>
prime_ideal R (i_contract f R R' P)"
apply (cut_tac Ring,
cut_tac secondR)
apply (simp add:prime_ideal_def, (erule conjE)+)
apply (simp add:i_contract_ideal)
apply (rule conjI)
apply (rule contrapos_pp, simp+)
apply (simp add:i_contract_def invim_def, erule conjE)
apply (simp add:rHom_one)
apply (rule ballI)+
apply (frule_tac a = x in rHom_mem[of "f" "R" "R'"], assumption+,
frule_tac a = y in rHom_mem[of "f" "R" "R'"], assumption+)
apply (rule impI)
apply (simp add:i_contract_def invim_def, erule conjE)
apply (simp add:rHom_tOp)
done
lemma (in TwoRings) i_extension_ideal:"\<lbrakk>f \<in> rHom R R'; ideal R I \<rbrakk> \<Longrightarrow>
ideal R' (i_extension f R R' I)"
apply (cut_tac Ring, cut_tac secondR)
apply (simp add:i_extension_def)
apply (rule Ring.ideal_sum_mult [of "R'" "f ` I" "carrier R'"], assumption+)
apply (rule subsetI)
apply (simp add:image_def)
apply (erule bexE, frule_tac a = xa in rHom_mem[of f R R'],
rule ideal_subset, assumption+, simp)
apply (frule ideal_zero, simp, blast)
apply (simp add:Ring.whole_ideal[of R'])
done
lemma (in TwoRings) i_extension_mono:"\<lbrakk>f \<in> rHom R R'; ideal R I1; ideal R I2;
I1 \<subseteq> I2 \<rbrakk> \<Longrightarrow> (i_extension f R R' I1) \<subseteq> (i_extension f R R' I2)"
apply (rule subsetI)
apply (simp add:i_extension_def)
apply (simp add:sum_mult_def)
apply (erule exE, erule bexE)
apply (cut_tac Ring.set_mult_mono[of R' "f ` I1" "f ` I2" "carrier R'"])
apply (frule_tac f = fa and A = "{j. j \<le> n}" in extend_fun[of _ _
"set_mult R' (f ` I1) (carrier R')" "set_mult R' (f ` I2) (carrier R')"],
assumption+) apply blast
apply (simp add:secondR)
apply (simp add:image_def, rule subsetI, simp, erule bexE,
frule_tac h = xb in ideal_subset[of I1], assumption, simp add:rHom_mem)
apply (simp add:image_def, rule subsetI, simp, erule bexE,
frule_tac h = xb in ideal_subset[of I2], assumption, simp add:rHom_mem)
apply (rule subsetI,
simp add:image_def, erule bexE,
frule_tac c = xb in subsetD[of I1 I2], assumption+, blast)
apply simp
done
lemma (in TwoRings) e_c_inc_self:"\<lbrakk>f \<in> rHom R R'; ideal R I\<rbrakk> \<Longrightarrow>
I \<subseteq> i_contract f R R' (i_extension f R R' I)"
apply (rule subsetI)
apply (simp add:i_contract_def i_extension_def invim_def)
apply (simp add:ideal_subset)
apply (cut_tac secondR,
frule Ring.ring_one [of "R'"])
apply (frule_tac h = x in ideal_subset[of I], assumption,
frule_tac f = f and A = R and R = R' and a = x in rHom_mem, assumption)
apply (frule_tac t = "f x" in Ring.ring_r_one[THEN sym, of R'], assumption)
apply (frule_tac a = "f x" and b = "1\<^sub>r\<^bsub>R'\<^esub>" in Ring.times_mem_sum_mult[of R'
"f ` I" "carrier R'"],
rule subsetI,
simp add:image_def, erule bexE,
frule_tac h = xb in ideal_subset[of I], assumption,
simp add:rHom_mem, simp,
simp add:image_def, blast, assumption+)
apply simp
done
lemma (in TwoRings) c_e_incd_self:"\<lbrakk>f \<in> rHom R R'; ideal R' J \<rbrakk> \<Longrightarrow>
i_extension f R R' (i_contract f R R' J) \<subseteq> J"
apply (rule subsetI)
apply (simp add:i_extension_def)
apply (simp add:sum_mult_def)
apply (erule exE, erule bexE)
apply (cut_tac secondR,
frule_tac n = n and f = fa in Ring.ideal_nsum_closed[of R' J ],
assumption)
apply (rule allI, rule impI) apply (
frule_tac f = fa and A = "{j. j \<le> n}" and
B = "set_mult R' (f ` i_contract f R R' J) (carrier R')" and x = j in
funcset_mem, simp) apply (
thin_tac "fa \<in> {j. j \<le> n} \<rightarrow> set_mult R' (f ` i_contract f R R' J) (carrier R')")
apply (simp add:set_mult_def, (erule bexE)+,
simp add:i_contract_def invim_def, erule conjE)
apply (frule_tac x = "f xa" and r = y in Ring.ideal_ring_multiple1[of R' J],
assumption+, simp)
apply simp
done
lemma (in TwoRings) c_e_c_eq_c:"\<lbrakk>f \<in> rHom R R'; ideal R' J \<rbrakk> \<Longrightarrow>
i_contract f R R' (i_extension f R R' (i_contract f R R' J))
= i_contract f R R' J"
apply (frule i_contract_ideal [of "f" "J"], assumption)
apply (frule e_c_inc_self [of "f" "i_contract f R R' J"], assumption+)
apply (frule c_e_incd_self [of "f" "J"], assumption+)
apply (frule i_contract_mono [of "f"
"i_extension f R R' (i_contract f R R' J)" "J"])
apply (rule i_extension_ideal, assumption+)
apply (rule equalityI, assumption+)
done
lemma (in TwoRings) e_c_e_eq_e:"\<lbrakk>f \<in> rHom R R'; ideal R I \<rbrakk> \<Longrightarrow>
i_extension f R R' (i_contract f R R' (i_extension f R R' I))
= i_extension f R R' I"
apply (frule i_extension_ideal [of "f" "I"], assumption+)
apply (frule c_e_incd_self [of "f" "i_extension f R R' I"], assumption+)
apply (rule equalityI, assumption+)
apply (thin_tac "i_extension f R R' (i_contract f R R' (i_extension f R R' I))
\<subseteq> i_extension f R R' I")
apply (frule e_c_inc_self [of "f" "I"], assumption+)
apply (rule i_extension_mono [of "f" "I"
"i_contract f R R' (i_extension f R R' I)"], assumption+)
apply (rule i_contract_ideal, assumption+)
done
section "Complete system of representatives"
definition
csrp_fn :: "[_, 'a set] \<Rightarrow> 'a set \<Rightarrow> 'a" where
"csrp_fn R I = (\<lambda>x\<in>carrier (R /\<^sub>r I). (if x = I then \<zero>\<^bsub>R\<^esub> else SOME y. y \<in> x))"
definition
csrp :: "[_ , 'a set] \<Rightarrow> 'a set" where
"csrp R I == (csrp_fn R I) ` (carrier (R /\<^sub>r I))"
(** complete system of representatives having 1-1 correspondence with
carrier (R /\<^sub>r I) **)
lemma (in Ring) csrp_mem:"\<lbrakk>ideal R I; a \<in> carrier R\<rbrakk> \<Longrightarrow>
csrp_fn R I (a \<uplus>\<^bsub>R\<^esub> I) \<in> a \<uplus>\<^bsub>R\<^esub> I"
apply (simp add:csrp_fn_def qring_carrier)
apply (case_tac "a \<uplus>\<^bsub>R\<^esub> I = I") apply simp
apply (rule conjI, rule impI)
apply (simp add:ideal_zero)
apply (rule impI)
apply (cut_tac ring_zero)
apply (frule_tac x = \<zero> in bspec, assumption+)
apply (thin_tac "\<forall>a\<in>carrier R. a \<uplus>\<^bsub>R\<^esub> I \<noteq> I")
apply (frule ideal_zero[of "I"])
apply (frule ar_coset_same4[of "I" "\<zero>"], assumption+, simp)
apply simp
apply (rule conjI)
apply (rule impI, rule someI2_ex)
apply (frule a_in_ar_coset[of "I" "a"], assumption+, blast, assumption+)
apply (rule impI)
apply (frule_tac x = a in bspec, assumption+,
thin_tac "\<forall>aa\<in>carrier R. aa \<uplus>\<^bsub>R\<^esub> I \<noteq> a \<uplus>\<^bsub>R\<^esub> I", simp)
done
lemma (in Ring) csrp_same:"\<lbrakk>ideal R I; a \<in> carrier R\<rbrakk> \<Longrightarrow>
csrp_fn R I (a \<uplus>\<^bsub>R\<^esub> I) \<uplus>\<^bsub>R\<^esub> I = a \<uplus>\<^bsub>R\<^esub> I"
apply (frule csrp_mem[of "I" "a"], assumption+)
apply (rule ar_cos_same[of "a" "I" "csrp_fn R I (a \<uplus>\<^bsub>R\<^esub> I)"], assumption+)
done
lemma (in Ring) csrp_mem1:"\<lbrakk>ideal R I; x \<in> carrier (R /\<^sub>r I)\<rbrakk> \<Longrightarrow>
csrp_fn R I x \<in> x"
apply (simp add:qring_carrier, erule bexE, frule sym,
thin_tac "a \<uplus>\<^bsub>R\<^esub> I = x", simp)
apply (simp add:csrp_mem)
done
lemma (in Ring) csrp_fn_mem:"\<lbrakk>ideal R I; x \<in> carrier (R /\<^sub>r I)\<rbrakk> \<Longrightarrow>
(csrp_fn R I x) \<in> carrier R"
apply (simp add:qring_carrier, erule bexE, frule sym,
thin_tac "a \<uplus>\<^bsub>R\<^esub> I = x", simp,
frule_tac a = a in csrp_mem[of "I"], assumption+)
apply (rule_tac a = a and x = "csrp_fn R I (a \<uplus>\<^bsub>R\<^esub> I)" in
ar_coset_subsetD[of "I"], assumption+)
done
lemma (in Ring) csrp_eq_coset:"\<lbrakk>ideal R I; x \<in> carrier (R /\<^sub>r I)\<rbrakk> \<Longrightarrow>
(csrp_fn R I x) \<uplus>\<^bsub>R\<^esub> I = x"
apply (simp add:qring_carrier, erule bexE)
apply (frule sym, thin_tac "a \<uplus>\<^bsub>R\<^esub> I = x", simp)
apply (frule_tac a = a in csrp_mem[of "I"], assumption+)
apply (rule ar_cos_same, assumption+)
done
lemma (in Ring) csrp_nz_nz:"\<lbrakk>ideal R I; x \<in> carrier (R /\<^sub>r I);
x \<noteq> \<zero>\<^bsub>(R /\<^sub>r I)\<^esub>\<rbrakk> \<Longrightarrow> (csrp_fn R I x) \<noteq> \<zero>"
apply (rule contrapos_pp, simp+)
apply (frule csrp_eq_coset[of "I" "x"], assumption+, simp)
apply (simp add:qring_zero[of "I"])
apply (frule ideal_zero[of "I"]) apply (
cut_tac ring_zero)
apply (simp add:Qring_fix1 [of "\<zero>" "I"])
done
lemma (in Ring) csrp_diff_in_vpr:"\<lbrakk>ideal R I; x \<in> carrier R\<rbrakk> \<Longrightarrow>
x \<plusminus> (-\<^sub>a (csrp_fn R I (pj R I x))) \<in> I"
apply (frule csrp_mem[of "I" "x"],
frule csrp_same[of "I" "x"],
simp add:pj_mem, assumption,
frule ar_coset_subsetD[of I x "csrp_fn R I (x \<uplus>\<^bsub>R\<^esub> I)"],
assumption+)
apply (frule belong_ar_coset2[of I x "csrp_fn R I (x \<uplus>\<^bsub>R\<^esub> I)"], assumption+,
frule ideal_inv1_closed[of I "csrp_fn R I (x \<uplus>\<^bsub>R\<^esub> I) \<plusminus> -\<^sub>a x"], assumption+,
cut_tac ring_is_ag,
frule aGroup.ag_mOp_closed[of R x], assumption,
simp add:aGroup.ag_pOp_commute[of R "csrp_fn R I (x \<uplus>\<^bsub>R\<^esub> I)" "-\<^sub>a x"])
apply (simp add:aGroup.ag_p_inv[of R "-\<^sub>a x" "csrp_fn R I (x \<uplus>\<^bsub>R\<^esub> I)"],
simp add:aGroup.ag_inv_inv,
cut_tac Ring, simp add:pj_mem[of R I x])
done
lemma (in Ring) csrp_pj:"\<lbrakk>ideal R I; x \<in> carrier (R /\<^sub>r I)\<rbrakk> \<Longrightarrow>
(pj R I) (csrp_fn R I x) = x"
apply(cut_tac Ring,
frule csrp_fn_mem[of "I" "x"], assumption+,
simp add:pj_mem[of "R" "I" "csrp_fn R I x"],
simp add:csrp_eq_coset)
done
section "Polynomial ring"
text\<open>In this section, we treat a ring of polynomials over a ring S.
Numbers are of type ant\<close>
definition
pol_coeff :: "[('a, 'more) Ring_scheme, (nat \<times> (nat \<Rightarrow> 'a))] \<Rightarrow> bool" where
"pol_coeff S c \<longleftrightarrow> (\<forall>j \<le> (fst c). (snd c) j \<in> carrier S)"
definition
c_max :: "[('a, 'more) Ring_scheme, nat \<times> (nat \<Rightarrow> 'a)] \<Rightarrow> nat" where
"c_max S c = (if {j. j \<le> (fst c) \<and> (snd c) j \<noteq> \<zero>\<^bsub>S\<^esub>} = {} then 0 else
n_max {j. j \<le> (fst c) \<and> (snd c) j \<noteq> \<zero>\<^bsub>S\<^esub>})"
definition
polyn_expr :: "[('a, 'more) Ring_scheme, 'a, nat, nat \<times> (nat \<Rightarrow> 'a)] \<Rightarrow> 'a" where
"polyn_expr R X k c == nsum R (\<lambda>j. ((snd c) j) \<cdot>\<^sub>r\<^bsub>R\<^esub> (X^\<^bsup>R j\<^esup>)) k"
definition
algfree_cond :: "[('a, 'm) Ring_scheme, ('a, 'm1) Ring_scheme,
'a] \<Rightarrow> bool" where
"algfree_cond R S X \<longleftrightarrow> (\<forall>c. pol_coeff S c \<and> (\<forall>k \<le> (fst c).
(nsum R (\<lambda>j. ((snd c) j) \<cdot>\<^sub>r\<^bsub>R\<^esub> (X^\<^bsup>R j\<^esup>)) k = \<zero>\<^bsub>R\<^esub> \<longrightarrow>
(\<forall>j \<le> k. (snd c) j = \<zero>\<^bsub>S\<^esub>))))"
locale PolynRg = Ring +
fixes S (structure)
fixes X (structure)
assumes X_mem_R:"X \<in> carrier R"
and not_zeroring:"\<not> Zero_ring S"
and subring: "Subring R S"
and algfree: "algfree_cond R S X"
and S_X_generate:"x \<in> carrier R \<Longrightarrow>
\<exists>f. pol_coeff S f \<and> x = polyn_expr R X (fst f) f"
(** a polynomial is an element of a polynomial ring **)
section \<open>Addition and multiplication of \<open>polyn_exprs\<close>\<close>
subsection \<open>Simple properties of a \<open>polyn_ring\<close>\<close>
lemma Subring_subset:"Subring R S \<Longrightarrow> carrier S \<subseteq> carrier R"
by (simp add:Subring_def)
lemma (in Ring) subring_Ring:"Subring R S \<Longrightarrow> Ring S"
by (simp add:Subring_def)
lemma (in Ring) mem_subring_mem_ring:"\<lbrakk>Subring R S; x \<in> carrier S\<rbrakk> \<Longrightarrow>
x \<in> carrier R"
by (simp add:Subring_def, (erule conjE)+, simp add: subsetD)
lemma (in Ring) Subring_pOp_ring_pOp:"\<lbrakk>Subring R S; a \<in> carrier S;
b \<in> carrier S \<rbrakk> \<Longrightarrow> a \<plusminus>\<^bsub>S\<^esub> b = a \<plusminus> b"
apply (simp add:Subring_def, (erule conjE)+)
apply (frule rHom_add[of "ridmap S" S R a b], assumption+)
apply (cut_tac Ring.ring_is_ag[of S],
frule aGroup.ag_pOp_closed[of S a b], assumption+,
simp add:ridmap_def, assumption)
done
lemma (in Ring) Subring_tOp_ring_tOp:"\<lbrakk>Subring R S; a \<in> carrier S;
b \<in> carrier S \<rbrakk> \<Longrightarrow> a \<cdot>\<^sub>r\<^bsub>S\<^esub> b = a \<cdot>\<^sub>r b"
apply (simp add:Subring_def, (erule conjE)+)
apply (frule rHom_tOp[of "S" "R" "a" "b" "ridmap S"], rule Ring_axioms, assumption+)
apply (frule Ring.ring_tOp_closed[of "S" "a" "b"], assumption+,
simp add:ridmap_def)
done
lemma (in Ring) Subring_one_ring_one:"Subring R S \<Longrightarrow> 1\<^sub>r\<^bsub>S\<^esub> = 1\<^sub>r"
apply (simp add:Subring_def, (erule conjE)+)
apply (frule rHom_one[of "S" "R" "ridmap S"], rule Ring_axioms, assumption+)
apply (simp add:ridmap_def, simp add:Ring.ring_one[of S])
done
lemma (in Ring) Subring_zero_ring_zero:"Subring R S \<Longrightarrow> \<zero>\<^bsub>S\<^esub> = \<zero>"
apply (simp add:Subring_def, (erule conjE)+,
frule rHom_0_0[of "S" "R" "ridmap S"], rule Ring_axioms, assumption+,
simp add:ridmap_def, simp add:Ring.ring_zero[of "S"])
done
lemma (in Ring) Subring_minus_ring_minus:"\<lbrakk>Subring R S; x \<in> carrier S\<rbrakk>
\<Longrightarrow> -\<^sub>a\<^bsub>S\<^esub> x = -\<^sub>a x"
apply (simp add:Subring_def, (erule conjE)+, simp add:rHom_def, (erule conjE)+)
apply (cut_tac ring_is_ag, frule Ring.ring_is_ag[of "S"])
apply (frule aHom_inv_inv[of "S" "R" "ridmap S" "x"], assumption+,
frule aGroup.ag_mOp_closed[of "S" "x"], assumption+)
apply (simp add:ridmap_def)
done
lemma (in PolynRg) Subring_pow_ring_pow:"x \<in> carrier S \<Longrightarrow>
x^\<^bsup>S n\<^esup> = x^\<^bsup>R n\<^esup>"
apply (cut_tac subring, frule subring_Ring)
apply (induct_tac n)
apply (simp, simp add:Subring_one_ring_one)
apply (frule_tac n = n in Ring.npClose[of S x], assumption+)
apply (simp add:Subring_tOp_ring_tOp)
done
lemma (in PolynRg) is_Ring: "Ring R" ..
lemma (in PolynRg) polyn_ring_nonzero:"1\<^sub>r \<noteq> \<zero>"
apply (cut_tac Ring, cut_tac subring)
apply (simp add:Subring_zero_ring_zero[THEN sym])
apply (simp add:Subring_one_ring_one[THEN sym])
apply (simp add:not_zeroring)
done
lemma (in PolynRg) polyn_ring_S_nonzero:"1\<^sub>r\<^bsub>S\<^esub> \<noteq> \<zero>\<^bsub>S\<^esub>"
apply (cut_tac subring)
apply (simp add:Subring_zero_ring_zero)
apply (simp add:Subring_one_ring_one)
apply (simp add:polyn_ring_nonzero)
done
lemma (in PolynRg) polyn_ring_X_nonzero:"X \<noteq> \<zero>"
apply (cut_tac algfree,
cut_tac subring)
apply (simp add:algfree_cond_def)
apply (rule contrapos_pp, simp+)
apply (drule_tac x = "Suc 0" in spec)
apply (subgoal_tac "pol_coeff S ((Suc 0),
(\<lambda>j\<in>{l. l \<le> (Suc 0)}. if j = 0 then \<zero>\<^bsub>S\<^esub> else 1\<^sub>r\<^bsub>S\<^esub>))")
apply (drule_tac x = "\<lambda>j\<in>{l. l \<le> (Suc 0)}. if j = 0 then \<zero>\<^bsub>S\<^esub> else 1\<^sub>r\<^bsub>S\<^esub>" in
spec)
apply (erule conjE, simp)
apply (simp only:Nset_1)
apply (drule_tac a = "Suc 0" in forall_spec, simp)
apply simp
apply (cut_tac subring, simp add:Subring_zero_ring_zero,
simp add:Subring_one_ring_one, cut_tac ring_zero, cut_tac ring_one,
simp add:ring_r_one, simp add:ring_times_x_0, cut_tac ring_is_ag,
simp add:aGroup.ag_r_zero,
drule_tac a = "Suc 0" in forall_spec, simp, simp)
apply (cut_tac polyn_ring_S_nonzero, simp add:Subring_zero_ring_zero)
apply (thin_tac "\<forall>b. pol_coeff S (Suc 0, b) \<and>
(\<forall>k\<le>Suc 0. \<Sigma>\<^sub>e R (\<lambda>j. b j \<cdot>\<^sub>r \<zero>^\<^bsup>R j\<^esup>) k = \<zero> \<longrightarrow> (\<forall>j\<le>k. b j = \<zero>\<^bsub>S\<^esub>))",
simp add:pol_coeff_def,
rule allI,
simp add:Subring_def, simp add:Ring.ring_zero,
(rule impI)+,
simp add:Ring.ring_one)
done
subsection "Coefficients of a polynomial"
lemma (in PolynRg) pol_coeff_split:"pol_coeff S f = pol_coeff S (fst f, snd f)"
by simp
lemma (in PolynRg) pol_coeff_cartesian:"pol_coeff S c \<Longrightarrow>
(fst c, snd c) = c"
by simp
lemma (in PolynRg) split_pol_coeff:"\<lbrakk>pol_coeff S c; k \<le> (fst c)\<rbrakk> \<Longrightarrow>
pol_coeff S (k, snd c)"
by (simp add:pol_coeff_def)
lemma (in PolynRg) pol_coeff_pre:"pol_coeff S ((Suc n), f) \<Longrightarrow>
pol_coeff S (n, f)"
apply (simp add:pol_coeff_def)
done
lemma (in PolynRg) pol_coeff_le:"\<lbrakk>pol_coeff S c; n \<le> (fst c)\<rbrakk> \<Longrightarrow>
pol_coeff S (n, (snd c))"
apply (simp add:pol_coeff_def)
done
lemma (in PolynRg) pol_coeff_mem:"\<lbrakk>pol_coeff S c; j \<le> (fst c)\<rbrakk> \<Longrightarrow>
((snd c) j) \<in> carrier S"
by (simp add:pol_coeff_def)
lemma (in PolynRg) pol_coeff_mem_R:"\<lbrakk>pol_coeff S c; j \<le> (fst c)\<rbrakk>
\<Longrightarrow> ((snd c) j) \<in> carrier R"
apply (cut_tac subring, frule subring_Ring)
apply (frule pol_coeff_mem[of c "j"], assumption+,
simp add:mem_subring_mem_ring)
done
lemma (in PolynRg) Slide_pol_coeff:"\<lbrakk>pol_coeff S c; n < (fst c)\<rbrakk> \<Longrightarrow>
pol_coeff S (((fst c) - Suc n), (\<lambda>x. (snd c) (Suc (n + x))))"
apply (simp add: pol_coeff_def)
done
subsection \<open>Addition of \<open>polyn_exprs\<close>\<close>
lemma (in PolynRg) monomial_mem:"pol_coeff S c \<Longrightarrow>
\<forall>j \<le> (fst c). (snd c) j \<cdot>\<^sub>r X^\<^bsup>R j\<^esup> \<in> carrier R"
apply (rule allI, rule impI)
apply (rule ring_tOp_closed)
apply (simp add:pol_coeff_mem_R[of c],
cut_tac X_mem_R, simp add:npClose)
done
lemma (in PolynRg) polyn_mem:"\<lbrakk>pol_coeff S c; k \<le> (fst c)\<rbrakk> \<Longrightarrow>
polyn_expr R X k c \<in> carrier R"
apply (simp add:polyn_expr_def,
cut_tac ring_is_ag)
apply (rule aGroup.nsum_mem[of R k "\<lambda>j. (snd c) j \<cdot>\<^sub>r X^\<^bsup>R j\<^esup>"], assumption+)
apply (simp add:monomial_mem)
done
lemma (in PolynRg) polyn_exprs_eq:"\<lbrakk>pol_coeff S c; pol_coeff S d;
k \<le> (min (fst c) (fst d)); \<forall>j \<le> k. (snd c) j = (snd d) j\<rbrakk> \<Longrightarrow>
polyn_expr R X k c = polyn_expr R X k d"
apply (cut_tac ring_is_ag,
simp add:polyn_expr_def,
cut_tac subring,
cut_tac X_mem_R)
apply (rule aGroup.nsum_eq[of R k "\<lambda>j. (snd c) j \<cdot>\<^sub>r X^\<^bsup>R j\<^esup>"
"\<lambda>j. (snd d) j \<cdot>\<^sub>r X^\<^bsup>R j\<^esup>"], assumption)
apply (simp add:monomial_mem)+
done
lemma (in PolynRg) polyn_expr_restrict:"pol_coeff S (Suc n, f) \<Longrightarrow>
polyn_expr R X n (Suc n, f) = polyn_expr R X n (n, f)"
apply (cut_tac subring, frule subring_Ring,
cut_tac pol_coeff_le[of "(Suc n, f)" n])
apply (cut_tac polyn_exprs_eq[of "(Suc n, f)" "(n, f)" n],
(simp add:pol_coeff_split[THEN sym])+)
done
lemma (in PolynRg) polyn_expr_short:"\<lbrakk>pol_coeff S c; k \<le> (fst c)\<rbrakk> \<Longrightarrow>
polyn_expr R X k c = polyn_expr R X k (k, snd c)"
apply (rule polyn_exprs_eq[of c "(k, snd c)" k], assumption+)
apply (simp add:pol_coeff_def)
apply (simp)
apply simp
done
lemma (in PolynRg) polyn_expr0:"pol_coeff S c \<Longrightarrow>
polyn_expr R X 0 c = (snd c) 0"
apply (simp add:polyn_expr_def)
apply (cut_tac subring,
cut_tac subring_Ring[of S])
apply (frule pol_coeff_mem[of c 0], simp)
apply (frule mem_subring_mem_ring [of S "(snd c) 0"], assumption)
apply (simp add:ring_r_one, assumption)
done
lemma (in PolynRg) polyn_expr_split:"
polyn_expr R X k f = polyn_expr R X k (fst f, snd f)"
by simp
lemma (in PolynRg) polyn_Suc:"Suc n \<le> (fst c) \<Longrightarrow>
polyn_expr R X (Suc n) ((Suc n), (snd c)) =
polyn_expr R X n c \<plusminus> ((snd c) (Suc n)) \<cdot>\<^sub>r (X^\<^bsup>R (Suc n)\<^esup>)"
by (simp add:polyn_expr_def)
lemma (in PolynRg) polyn_Suc_split:"pol_coeff S (Suc n, f) \<Longrightarrow>
polyn_expr R X (Suc n) ((Suc n), f) =
polyn_expr R X n (n, f) \<plusminus> (f (Suc n)) \<cdot>\<^sub>r (X^\<^bsup>R (Suc n)\<^esup>)"
apply (cut_tac polyn_Suc[of n "(Suc n, f)"])
apply (simp del:npow_suc)
apply (subst polyn_expr_short[of "(Suc n, f)" n], assumption+, simp)
apply (simp del:npow_suc)
apply simp
done
lemma (in PolynRg) polyn_n_m:"\<lbrakk>pol_coeff S c; n < m; m \<le> (fst c)\<rbrakk> \<Longrightarrow>
polyn_expr R X m (m, (snd c)) = polyn_expr R X n (n, (snd c)) \<plusminus>
(fSum R (\<lambda>j. ((snd c) j) \<cdot>\<^sub>r (X^\<^bsup>R j\<^esup>)) (Suc n) m)"
apply (simp add:polyn_expr_def, cut_tac ring_is_ag)
apply (rule aGroup.nsum_split1[of "R" m "\<lambda>j. ((snd c) j) \<cdot>\<^sub>r (X^\<^bsup>R j\<^esup>)" n],
assumption+)
apply (rule allI, rule impI)
apply (frule_tac monomial_mem[of c],
frule_tac i = j and j = m and k = "(fst c)" in le_trans, assumption+,
simp+)
done
lemma (in PolynRg) polyn_n_m1:"\<lbrakk>pol_coeff S c; n < m; m \<le> (fst c)\<rbrakk> \<Longrightarrow>
polyn_expr R X m c = polyn_expr R X n c \<plusminus>
(fSum R (\<lambda>j. ((snd c) j) \<cdot>\<^sub>r (X^\<^bsup>R j\<^esup>)) (Suc n) m)"
apply (subst polyn_expr_short[of c n], assumption)
apply (frule_tac x = n and y = m and z = "fst c" in less_le_trans, assumption,
simp add:less_imp_le)
apply (subst polyn_expr_short[of c m], assumption+)
apply (simp add:polyn_n_m)
done
lemma (in PolynRg) polyn_n_m_mem:"\<lbrakk>pol_coeff S c; n < m; m \<le> (fst c)\<rbrakk> \<Longrightarrow>
(fSum R (\<lambda>j. ((snd c) j) \<cdot>\<^sub>r (X^\<^bsup>R j\<^esup>)) (Suc n) m) \<in> carrier R"
apply (simp add:fSum_def)
apply (cut_tac ring_is_ag,
rule_tac n = "m - Suc n" in aGroup.nsum_mem, assumption+)
apply (rule allI, rule impI,
simp del:npow_suc add:cmp_def slide_def)
apply (rule ring_tOp_closed)
apply (simp add:pol_coeff_def)
apply (frule_tac a = "Suc (n + j)" in forall_spec, arith)
apply (cut_tac subring)
apply (simp add:mem_subring_mem_ring)
apply (rule npClose)
apply (cut_tac X_mem_R,
simp del:npow_suc add:npClose)
done
lemma (in PolynRg) polyn_n_ms_eq:"\<lbrakk>pol_coeff S c; pol_coeff S d;
m \<le> min (fst c) (fst d); n < m;
\<forall>j\<in>nset (Suc n) m. (snd c) j = (snd d) j\<rbrakk> \<Longrightarrow>
(fSum R (\<lambda>j. ((snd c) j) \<cdot>\<^sub>r (X^\<^bsup>R j\<^esup>)) (Suc n) m) =
(fSum R (\<lambda>j. ((snd d) j) \<cdot>\<^sub>r (X^\<^bsup>R j\<^esup>)) (Suc n) m)"
apply (cut_tac ring_is_ag)
apply (cut_tac aGroup.fSum_eq1[of R "Suc n" m "\<lambda>j. (snd c) j \<cdot>\<^sub>r X^\<^bsup>R j\<^esup>"
"\<lambda>j. (snd d) j \<cdot>\<^sub>r X^\<^bsup>R j\<^esup>"],
assumption+)
apply (rule Suc_leI, assumption,
simp add:nset_def, simp add:monomial_mem)
apply (frule Suc_leI,
rule ballI, simp add:nset_def)
apply (simp add:monomial_mem)
apply simp
done
lemma (in PolynRg) polyn_addTr:
"(pol_coeff S (n, f)) \<and> (pol_coeff S (n, g)) \<longrightarrow>
(polyn_expr R X n (n, f)) \<plusminus> (polyn_expr R X n (n, g)) =
nsum R (\<lambda>j. ((f j) \<plusminus>\<^bsub>S\<^esub> (g j)) \<cdot>\<^sub>r (X^\<^bsup>R j\<^esup>)) n"
apply (cut_tac subring,
frule subring_Ring[of S])
apply (induct_tac n)
apply (rule impI, simp, erule conjE)
apply (simp add:polyn_expr0)
apply (cut_tac pol_coeff_mem[of "(0, f)" 0], simp,
cut_tac pol_coeff_mem[of "(0, g)" 0], simp,
frule mem_subring_mem_ring[of S "f 0"], assumption+,
frule mem_subring_mem_ring[of S "g 0"], assumption+,
frule Ring.ring_is_ag[of S],
frule aGroup.ag_pOp_closed[of S "f 0" "g 0"], assumption+,
frule mem_subring_mem_ring[of S "f 0 \<plusminus>\<^bsub>S\<^esub> g 0"], assumption+)
apply (simp add:ring_r_one)
apply (simp add:Subring_pOp_ring_pOp[of S "f 0" "g 0"])
apply (simp del:npow_suc)+
apply (rule impI, erule conjE)
apply (frule_tac n = n in pol_coeff_pre[of _ f],
frule_tac n = n in pol_coeff_pre[of _ g], simp del:npow_suc)
apply (cut_tac n = n and c = "(Suc n, f)" in polyn_Suc, simp del:npow_suc,
simp del:npow_suc,
thin_tac "polyn_expr R X (Suc n) (Suc n, f) =
polyn_expr R X n (Suc n, f) \<plusminus> f (Suc n) \<cdot>\<^sub>r X^\<^bsup>R (Suc n)\<^esup>")
apply (cut_tac n = n and c = "(Suc n, g)" in polyn_Suc, simp del:npow_suc,
simp del:npow_suc,
thin_tac "polyn_expr R X (Suc n) (Suc n, g) =
polyn_expr R X n (Suc n, g) \<plusminus> g (Suc n) \<cdot>\<^sub>r X^\<^bsup>R (Suc n)\<^esup>")
apply (cut_tac c = "(Suc n, f)" and k = n in polyn_mem, assumption,
simp del:npow_suc,
cut_tac k = n and c = "(Suc n, g)" in polyn_mem, assumption,
simp del:npow_suc)
apply (frule_tac j = "Suc n" and c = "(Suc n, f)" in pol_coeff_mem_R, simp,
frule_tac j = "Suc n" and c = "(Suc n, g)" in pol_coeff_mem_R, simp,
cut_tac X_mem_R,
frule_tac n = "Suc n" in npClose[of "X"], simp del:npow_suc)
apply (frule_tac x = "f (Suc n)" and y = "X^\<^bsup>R (Suc n)\<^esup>" in ring_tOp_closed,
assumption+,
frule_tac x = "g (Suc n)" and y = "X^\<^bsup>R (Suc n)\<^esup>" in ring_tOp_closed,
assumption+)
apply (cut_tac ring_is_ag,
subst aGroup.pOp_assocTr43, assumption+)
apply (frule_tac x = "f (Suc n) \<cdot>\<^sub>r X^\<^bsup>R (Suc n)\<^esup>" and
y = "polyn_expr R X n (Suc n, g)" in aGroup.ag_pOp_commute[of R],
assumption+, simp del:npow_suc,
thin_tac "f (Suc n) \<cdot>\<^sub>r X^\<^bsup>R (Suc n)\<^esup> \<plusminus> polyn_expr R X n (Suc n, g) =
polyn_expr R X n (Suc n, g) \<plusminus> f (Suc n) \<cdot>\<^sub>r X^\<^bsup>R (Suc n)\<^esup>")
apply (subst aGroup.pOp_assocTr43[THEN sym], assumption+,
simp del:npow_suc add:polyn_expr_restrict)
apply (frule_tac c = "(Suc n, f)" and j = "Suc n" in pol_coeff_mem, simp,
frule_tac c = "(Suc n, g)" and j = "Suc n" in pol_coeff_mem, simp)
apply (subst ring_distrib2[THEN sym], assumption+)
apply (frule_tac c = "(Suc n, f)" and j = "Suc n" in pol_coeff_mem, simp,
frule_tac c = "(Suc n, g)" and j = "Suc n" in pol_coeff_mem, simp)
apply (frule_tac a = "f (Suc n)" and b = "g (Suc n)" in
Subring_pOp_ring_pOp[of S], simp, simp)
apply simp
done
lemma (in PolynRg) polyn_add_n:"\<lbrakk>pol_coeff S (n, f); pol_coeff S (n, g)\<rbrakk> \<Longrightarrow>
(polyn_expr R X n (n, f)) \<plusminus> (polyn_expr R X n (n, g)) =
nsum R (\<lambda>j. ((f j) \<plusminus>\<^bsub>S\<^esub> (g j)) \<cdot>\<^sub>r (X^\<^bsup>R j\<^esup>)) n"
by (simp add:polyn_addTr)
definition
add_cf :: "[('a, 'm) Ring_scheme, nat \<times> (nat \<Rightarrow> 'a), nat \<times> (nat \<Rightarrow> 'a)] \<Rightarrow>
nat \<times> (nat \<Rightarrow> 'a)" where
"add_cf S c d =
(if (fst c) < (fst d) then ((fst d), \<lambda>j. (if j \<le> (fst c)
then (((snd c) j) \<plusminus>\<^bsub>S\<^esub> ((snd d) j)) else ((snd d) j)))
else if (fst c) = (fst d) then ((fst c), \<lambda>j. ((snd c) j \<plusminus>\<^bsub>S\<^esub> (snd d) j))
else ((fst c), \<lambda>j. (if j \<le> (fst d) then
((snd c) j \<plusminus>\<^bsub>S\<^esub> (snd d) j) else ((snd c) j))))"
lemma (in PolynRg) add_cf_pol_coeff:"\<lbrakk>pol_coeff S c; pol_coeff S d\<rbrakk>
\<Longrightarrow> pol_coeff S (add_cf S c d)"
apply (cut_tac subring,
frule subring_Ring[of S], frule Ring.ring_is_ag[of S])
apply (simp add:pol_coeff_def)
apply (rule allI, rule impI)
apply (case_tac "(fst c) < (fst d)", simp add:add_cf_def)
apply (rule impI, rule aGroup.ag_pOp_closed, assumption+, simp+)
apply (drule leI[of "fst c" "fst d"],
drule le_imp_less_or_eq[of "fst d" "fst c"])
apply (erule disjE)
apply (simp add:add_cf_def, rule impI)
apply (frule Ring.ring_is_ag[of S], rule aGroup.ag_pOp_closed, assumption,
simp+)
apply (simp add:add_cf_def)
apply (frule Ring.ring_is_ag[of S], rule aGroup.ag_pOp_closed, assumption,
simp+)
done
lemma (in PolynRg) add_cf_len:"\<lbrakk>pol_coeff S c; pol_coeff S d\<rbrakk>
\<Longrightarrow> fst (add_cf S c d) = (max (fst c) (fst d))"
by (simp add: add_cf_def max.absorb1 max.absorb2)
lemma (in PolynRg) polyn_expr_restrict1:"\<lbrakk>pol_coeff S (n, f);
pol_coeff S (Suc (m + n), g)\<rbrakk> \<Longrightarrow>
polyn_expr R X (m + n) (add_cf S (n, f) (m + n, g)) =
polyn_expr R X (m + n) (m + n, snd (add_cf S (n, f) (Suc (m + n), g)))"
apply (frule pol_coeff_pre[of "m+n" g])
apply (frule add_cf_pol_coeff[of "(n, f)" "(Suc (m + n), g)"], assumption+,
frule add_cf_pol_coeff[of "(n, f)" "(m + n, g)"], assumption+)
apply (rule polyn_exprs_eq[of "add_cf S (n, f) (m + n, g)"
"(m + n, snd (add_cf S (n, f) (Suc (m + n), g)))" "m + n"], assumption+)
apply (rule split_pol_coeff[of "add_cf S (n, f) (Suc (m + n), g)" "m + n"],
assumption, simp add:add_cf_len)
apply (simp add:add_cf_len)
apply (rule allI, rule impI)
apply (simp add:add_cf_def)
done
lemma (in PolynRg) polyn_add_n1:"\<lbrakk>pol_coeff S (n, f); pol_coeff S (n, g)\<rbrakk> \<Longrightarrow>
(polyn_expr R X n (n, f)) \<plusminus> (polyn_expr R X n (n, g)) =
polyn_expr R X n (add_cf S (n, f) (n, g))"
apply (subst polyn_add_n, assumption+)
apply (simp add:polyn_expr_def add_cf_def)
done
lemma (in PolynRg) add_cf_val_hi:"(fst c) < (fst d) \<Longrightarrow>
snd (add_cf S c d) (fst d) = (snd d) (fst d)"
by (simp add:add_cf_def)
lemma (in PolynRg) add_cf_commute:"\<lbrakk>pol_coeff S c; pol_coeff S d\<rbrakk>
\<Longrightarrow> \<forall>j \<le> (max (fst c) (fst d)). snd (add_cf S c d) j =
snd (add_cf S d c) j"
apply (cut_tac subring, frule subring_Ring,
frule Ring.ring_is_ag[of S])
apply (simp add: add_cf_def max.absorb1 max.absorb2)
apply (case_tac "(fst c) = (fst d)", simp add: pol_coeff_def)
apply (rule allI, rule impI,
rule aGroup.ag_pOp_commute[of S], simp+)
apply (case_tac "(fst d) < (fst c)", simp,
rule allI, rule impI,
rule aGroup.ag_pOp_commute, assumption+)
apply (frule_tac x = j and y = "fst d" and z = "fst c" in le_less_trans,
assumption+, frule_tac x = j and y = "fst c" in less_imp_le,
thin_tac "j < fst c", simp add:pol_coeff_mem, simp add:pol_coeff_mem)
apply simp
apply (frule leI[of "fst d" "fst c"],
frule noteq_le_less[of "fst c" "fst d"], assumption,
rule allI, rule impI,
simp)
apply (rule aGroup.ag_pOp_commute, assumption+,
simp add:pol_coeff_mem,
frule_tac x = j and y = "fst c" and z = "fst d" in le_less_trans,
assumption+, frule_tac x = j and y = "fst d" in less_imp_le,
thin_tac "j < fst d", simp add:pol_coeff_mem)
done
lemma (in PolynRg) polyn_addTr1:"pol_coeff S (n, f) \<Longrightarrow>
\<forall>g. pol_coeff S (n + m, g) \<longrightarrow>
(polyn_expr R X n (n, f) \<plusminus> (polyn_expr R X (n + m) ((n + m), g))
= polyn_expr R X (n + m) (add_cf S (n, f) ((n + m), g)))"
apply (cut_tac subring, frule subring_Ring)
apply (induct_tac m)
apply (rule allI, rule impI, simp)
apply (simp add:polyn_add_n1)
apply (simp add:add.commute[of n])
apply (rule allI, rule impI)
apply (frule_tac n = "na + n" and f = g in pol_coeff_pre)
apply (drule_tac a = g in forall_spec, assumption)
apply (cut_tac n = "na + n" and c = "(Suc (na + n), g)" in polyn_Suc,
simp, simp del:npow_suc,
thin_tac "polyn_expr R X (Suc (na + n)) (Suc (na + n), g) =
polyn_expr R X (na + n) (Suc (na + n), g) \<plusminus>
g (Suc (na + n)) \<cdot>\<^sub>r X^\<^bsup>R (Suc (na + n))\<^esup>")
apply (frule_tac c = "(n, f)" and k = n in polyn_mem, simp,
frule_tac c = "(Suc (na + n), g)" and k = "na + n" in polyn_mem, simp,
frule_tac c = "(Suc (na + n), g)" in monomial_mem)
apply (drule_tac a = "Suc (na + n)" in forall_spec, simp del:npow_suc,
cut_tac ring_is_ag,
subst aGroup.ag_pOp_assoc[THEN sym], assumption+, simp del:npow_suc)
apply (simp del:npow_suc add:polyn_expr_restrict)
apply (frule_tac c = "(n, f)" and d = "(Suc (na + n), g)" in
add_cf_pol_coeff, assumption+,
frule_tac c = "(n, f)" and d = "(na + n, g)" in
add_cf_pol_coeff, assumption+)
apply (frule_tac c = "add_cf S (n, f) (Suc (na + n), g)" and
n = "na + n" and m = "Suc (na + n)" in polyn_n_m, simp,
subst add_cf_len, assumption+, simp)
apply (cut_tac k = "Suc (na + n)" and f = "add_cf S (n, f) (Suc (na + n), g)"
in polyn_expr_split)
apply (frule_tac c = "(n, f)" and d = "(Suc (na + n), g)" in
add_cf_len, assumption+, simp del: npow_suc add: max.absorb1 max.absorb2)
apply (thin_tac "polyn_expr R X (Suc (na + n))
(Suc (na + n), snd (add_cf S (n, f) (Suc (na + n), g))) =
polyn_expr R X (na + n)
(na + n, snd (add_cf S (n, f) (Suc (na + n), g))) \<plusminus>
\<Sigma>\<^sub>f R (\<lambda>j. snd (add_cf S (n, f) (Suc (na + n), g)) j \<cdot>\<^sub>r
X^\<^bsup>R j\<^esup>) (Suc (na + n)) (Suc (na + n))",
thin_tac "polyn_expr R X (Suc (na + n)) (add_cf S (n, f) (Suc (na + n),
g)) =
polyn_expr R X (na + n)
(na + n, snd (add_cf S (n, f) (Suc (na + n), g))) \<plusminus>
\<Sigma>\<^sub>f R (\<lambda>j. snd (add_cf S (n, f) (Suc (na + n), g)) j \<cdot>\<^sub>r
X^\<^bsup>R j\<^esup>) (Suc (na + n)) (Suc (na + n))")
apply (simp del:npow_suc add:fSum_def cmp_def slide_def)
apply (cut_tac d = "(Suc (na + n), g)" in add_cf_val_hi[of "(n, f)"],
simp, simp del:npow_suc,
thin_tac "snd (add_cf S (n, f) (Suc (na + n), g)) (Suc (na + n)) =
g (Suc (na + n))")
apply (frule_tac c = "add_cf S (n, f) (Suc (na + n), g)" and k = "na + n" in
polyn_mem, simp,
frule_tac c = "add_cf S (n, f) (na + n, g)" and k = "na + n" in
polyn_mem, simp )
apply (subst add_cf_len, assumption+, simp del:npow_suc)
apply (frule_tac a = "polyn_expr R X (na + n) (add_cf S (n, f) (na + n, g))"
and b = "polyn_expr R X (na + n) (add_cf S (n, f) (Suc (na + n), g))"
and c = "g (Suc (na + n)) \<cdot>\<^sub>r X^\<^bsup>R (Suc (na + n))\<^esup>" in
aGroup.ag_pOp_add_r[of R], assumption+)
apply (rule_tac c = "add_cf S (n, f) (na + n, g)" and
d = "add_cf S (n, f) (Suc (na + n), g)" and k = "na + n" in
polyn_exprs_eq, assumption+, simp,
subst add_cf_len, assumption+)
apply (simp)
apply (rule allI, rule impI,
(subst add_cf_def)+, simp,
frule_tac m = na and g = g in polyn_expr_restrict1[of n f], assumption,
simp del:npow_suc)
done
lemma (in PolynRg) polyn_add:"\<lbrakk>pol_coeff S (n, f); pol_coeff S (m, g)\<rbrakk>
\<Longrightarrow> polyn_expr R X n (n, f) \<plusminus> (polyn_expr R X m (m, g))
= polyn_expr R X (max n m) (add_cf S (n, f) (m, g))"
apply (cut_tac less_linear[of n m])
apply (erule disjE,
frule polyn_addTr1[of n f "m - n"],
drule_tac a = g in forall_spec, simp, simp add: max.absorb1 max.absorb2)
apply (erule disjE,
simp add:polyn_add_n1)
apply (frule polyn_mem[of "(n, f)" n], simp,
frule polyn_mem[of "(m, g)" m], simp)
apply (cut_tac ring_is_ag, simp add:aGroup.ag_pOp_commute)
apply (frule polyn_addTr1[of m g "n - m"],
drule_tac a = f in forall_spec, simp, simp,
frule add_cf_commute[of "(m, g)" "(n, f)"], assumption+,
simp add:max_def,
frule add_cf_pol_coeff[of "(n, f)" "(m, g)"], assumption+,
frule add_cf_pol_coeff[of "(m, g)" "(n, f)"], assumption+)
apply (rule polyn_exprs_eq[of "add_cf S (m, g) (n, f)"
"add_cf S (n, f) (m, g)" n], assumption+)
apply (simp add:add_cf_len, simp)
done
lemma (in PolynRg) polyn_add1:"\<lbrakk>pol_coeff S c; pol_coeff S d\<rbrakk>
\<Longrightarrow> polyn_expr R X (fst c) c \<plusminus> (polyn_expr R X (fst d) d)
= polyn_expr R X (max (fst c) (fst d)) (add_cf S c d)"
apply (cases c)
apply (cases d)
apply (simp add: polyn_add)
done
lemma (in PolynRg) polyn_minus_nsum:"\<lbrakk>pol_coeff S c; k \<le> (fst c)\<rbrakk> \<Longrightarrow>
-\<^sub>a (polyn_expr R X k c) = nsum R (\<lambda>j. ((-\<^sub>a\<^bsub>S\<^esub> ((snd c) j)) \<cdot>\<^sub>r (X^\<^bsup>R j\<^esup>))) k"
apply (cut_tac subring,
frule subring_Ring[of S],
frule Ring.ring_is_ag[of S],
cut_tac ring_is_ag,
cut_tac X_mem_R)
apply (simp add:polyn_expr_def,
subst aGroup.nsum_minus[of R], assumption)
apply (frule monomial_mem[of c], rule allI, rule impI,
frule_tac i = j and j = k and k = "fst c" in le_trans, assumption+,
simp)
apply (rule aGroup.nsum_eq, assumption,
rule allI, rule impI, simp,
rule aGroup.ag_mOp_closed, assumption)
apply (frule monomial_mem[of c],
frule_tac i = j and j = k and k = "fst c" in le_trans, assumption+,
simp)
apply (rule allI, rule impI,
rule ring_tOp_closed)
apply (frule_tac j = j in pol_coeff_mem[of c])
apply (frule_tac i = j and j = k and k = "fst c" in le_trans, assumption+,
simp add:Subring_minus_ring_minus,
frule_tac x = "(snd c) j" in mem_subring_mem_ring[of S], assumption,
simp add:aGroup.ag_mOp_closed,
simp add:npClose)
apply (rule allI, rule impI, simp,
cut_tac j = j in pol_coeff_mem[of c], assumption,
rule_tac i = j and j = k and k = "fst c" in le_trans, assumption+)
apply (simp add:Subring_minus_ring_minus,
frule_tac x = "(snd c) j" in mem_subring_mem_ring[of S], assumption)
apply (subst ring_inv1_1, assumption+)
apply (simp add:npClose, simp)
done
lemma (in PolynRg) minus_pol_coeff:"pol_coeff S c \<Longrightarrow>
pol_coeff S ((fst c), (\<lambda>j. (-\<^sub>a\<^bsub>S\<^esub> ((snd c) j))))"
apply (simp add:pol_coeff_def)
apply (rule allI, rule impI)
apply (cut_tac subring, frule subring_Ring)
apply (frule Ring.ring_is_ag[of "S"])
apply (rule aGroup.ag_mOp_closed, assumption)
apply simp
done
lemma (in PolynRg) polyn_minus:"\<lbrakk>pol_coeff S c; k \<le> (fst c)\<rbrakk> \<Longrightarrow>
-\<^sub>a (polyn_expr R X k c) =
polyn_expr R X k (fst c, (\<lambda>j. (-\<^sub>a\<^bsub>S\<^esub> ((snd c) j))))"
apply (cases c)
apply (subst polyn_minus_nsum)
apply (simp_all add: polyn_expr_def)
done
definition
m_cf :: "[('a, 'm) Ring_scheme, nat \<times> (nat \<Rightarrow> 'a)] \<Rightarrow> nat \<times> (nat \<Rightarrow> 'a)" where
"m_cf S c = (fst c, (\<lambda>j. (-\<^sub>a\<^bsub>S\<^esub> ((snd c) j))))"
lemma (in PolynRg) m_cf_pol_coeff:"pol_coeff S c \<Longrightarrow>
pol_coeff S (m_cf S c)"
by (simp add:m_cf_def, simp add:minus_pol_coeff)
lemma (in PolynRg) m_cf_len:"pol_coeff S c \<Longrightarrow>
fst (m_cf S c) = fst c"
by (simp add:m_cf_def)
lemma (in PolynRg) polyn_minus_m_cf:"\<lbrakk>pol_coeff S c; k \<le> (fst c)\<rbrakk> \<Longrightarrow>
-\<^sub>a (polyn_expr R X k c) =
polyn_expr R X k (m_cf S c)"
by (simp add:m_cf_def polyn_minus)
lemma (in PolynRg) polyn_zero_minus_zero:"\<lbrakk>pol_coeff S c; k \<le> (fst c)\<rbrakk> \<Longrightarrow>
(polyn_expr R X k c = \<zero>) = (polyn_expr R X k (m_cf S c) = \<zero>)"
apply (cut_tac ring_is_ag)
apply (simp add:polyn_minus_m_cf[THEN sym])
apply (rule iffI, simp)
apply (simp add:aGroup.ag_inv_zero)
apply (frule polyn_mem[of c k], assumption)
apply (frule aGroup.ag_inv_inv[of "R" "polyn_expr R X k c"], assumption)
apply (simp add:aGroup.ag_inv_zero)
done
lemma (in PolynRg) coeff_0_pol_0:"\<lbrakk>pol_coeff S c; k \<le> fst c\<rbrakk> \<Longrightarrow>
(\<forall>j\<le> k. (snd c) j = \<zero>\<^bsub>S\<^esub>) = (polyn_expr R X k c = \<zero>)"
apply (rule iffI)
apply (cut_tac ring_is_ag, cut_tac subring,
frule subring_Ring)
apply (simp add:Subring_zero_ring_zero)
apply (simp add:polyn_expr_def,
rule aGroup.nsum_zeroA[of R], assumption)
apply (rule allI, rule impI,
cut_tac X_mem_R)
apply (drule_tac a = j in forall_spec, simp,
frule_tac n = j in npClose[of X], simp)
apply (simp add:ring_times_0_x)
apply (cases c)
using algfree [simplified algfree_cond_def] by (auto simp add: polyn_expr_def)
subsection \<open>Multiplication of \<open>pol_exprs\<close>\<close>
subsection "Multiplication"
definition
ext_cf :: "[('a, 'm) Ring_scheme, nat, nat \<times> (nat \<Rightarrow> 'a)] \<Rightarrow>
nat \<times> (nat \<Rightarrow> 'a)" where
"ext_cf S n c = (n + fst c, \<lambda>i. if n \<le> i then (snd c) (sliden n i) else \<zero>\<^bsub>S\<^esub>)"
(* 0 0 g(0) g(m)
0 n m+n , where (m, g) is a pol_coeff **)
definition
sp_cf :: "[('a, 'm) Ring_scheme, 'a, nat \<times> (nat \<Rightarrow> 'a)] \<Rightarrow> nat \<times> (nat \<Rightarrow> 'a)" where
"sp_cf S a c = (fst c, \<lambda>j. a \<cdot>\<^sub>r\<^bsub>S\<^esub> ((snd c) j))" (* scalar times cf *)
definition
special_cf :: "('a, 'm) Ring_scheme \<Rightarrow> nat \<times> (nat \<Rightarrow> 'a)" ("C\<^sub>0") where
"C\<^sub>0 S = (0, \<lambda>j. 1\<^sub>r\<^bsub>S\<^esub>)"
lemma (in PolynRg) special_cf_pol_coeff:"pol_coeff S (C\<^sub>0 S)"
apply (cut_tac subring, frule subring_Ring)
apply (simp add:pol_coeff_def special_cf_def)
apply (simp add:Ring.ring_one)
done
lemma (in PolynRg) special_cf_len:"fst (C\<^sub>0 S) = 0"
apply (simp add:special_cf_def)
done
lemma (in PolynRg) ext_cf_pol_coeff:"pol_coeff S c \<Longrightarrow>
pol_coeff S (ext_cf S n c)"
apply (simp add: pol_coeff_def ext_cf_def sliden_def)
apply (rule impI)
apply (rule Ring.ring_zero)
apply (rule subring_Ring)
apply (rule subring)
done
lemma (in PolynRg) ext_cf_len:"pol_coeff S c \<Longrightarrow>
fst (ext_cf S m c) = m + fst c"
by (simp add:ext_cf_def)
lemma (in PolynRg) ext_special_cf_len:"fst (ext_cf S m (C\<^sub>0 S)) = m"
apply (cut_tac special_cf_pol_coeff)
apply (simp add:ext_cf_len special_cf_def)
done
lemma (in PolynRg) ext_cf_self:"pol_coeff S c \<Longrightarrow>
\<forall>j \<le> (fst c). snd (ext_cf S 0 c) j = (snd c) j"
apply (rule allI, rule impI, simp add:ext_cf_def sliden_def)
done
lemma (in PolynRg) ext_cf_hi:"pol_coeff S c \<Longrightarrow>
(snd c) (fst c) =
snd (ext_cf S n c) (n + (fst c))"
apply (subst ext_cf_def)
apply (simp add:sliden_def)
done
lemma (in PolynRg) ext_special_cf_hi:"snd (ext_cf S n (C\<^sub>0 S)) n = 1\<^sub>r\<^bsub>S\<^esub>"
apply (cut_tac special_cf_pol_coeff)
apply (cut_tac ext_cf_hi[of "C\<^sub>0 S" n, THEN sym])
apply (simp add:special_cf_def, assumption)
done
lemma (in PolynRg) ext_cf_lo_zero:"\<lbrakk>pol_coeff S c; 0 < n; x \<le> (n - Suc 0)\<rbrakk>
\<Longrightarrow> snd (ext_cf S n c) x = \<zero>\<^bsub>S\<^esub>"
apply (cut_tac Suc_le_mono[THEN sym, of x "n - Suc 0"], simp,
cut_tac x = x and y = "Suc x" and z = n in less_le_trans,
simp, assumption,
simp add:nat_not_le_less[THEN sym, of x n],
thin_tac "x \<le> n - Suc 0")
apply (simp add:ext_cf_def)
done
lemma (in PolynRg) ext_special_cf_lo_zero:"\<lbrakk>0 < n; x \<le> (n - Suc 0)\<rbrakk>
\<Longrightarrow> snd (ext_cf S n (C\<^sub>0 S)) x = \<zero>\<^bsub>S\<^esub>"
by (cut_tac special_cf_pol_coeff,
frule ext_cf_lo_zero[of "C\<^sub>0 S" n], assumption+)
lemma (in PolynRg) sp_cf_pol_coeff:"\<lbrakk>pol_coeff S c; a \<in> carrier S\<rbrakk> \<Longrightarrow>
pol_coeff S (sp_cf S a c)"
apply (cut_tac subring, frule subring_Ring)
apply (simp add:pol_coeff_def sp_cf_def,
rule allI, rule impI,
rule Ring.ring_tOp_closed, assumption+)
apply simp
done
lemma (in PolynRg) sp_cf_len:"\<lbrakk>pol_coeff S c; a \<in> carrier S\<rbrakk> \<Longrightarrow>
fst (sp_cf S a c) = fst c"
by (simp add:sp_cf_def)
lemma (in PolynRg) sp_cf_val:"\<lbrakk>pol_coeff S c; j \<le> (fst c); a \<in> carrier S\<rbrakk> \<Longrightarrow>
snd (sp_cf S a c) j = a \<cdot>\<^sub>r\<^bsub>S\<^esub> ((snd c) j)"
by (simp add:sp_cf_def)
lemma (in PolynRg) polyn_ext_cf_lo_zero:"\<lbrakk>pol_coeff S c; 0 < j\<rbrakk> \<Longrightarrow>
polyn_expr R X (j - Suc 0) (ext_cf S j c) = \<zero>"
apply (simp add:polyn_expr_def, cut_tac ring_is_ag,
rule aGroup.nsum_zeroA, assumption)
apply (rule allI, rule impI)
apply (frule_tac x = ja in ext_cf_lo_zero [of c j], assumption+)
apply (cut_tac X_mem_R, frule_tac n = ja in npClose[of X])
apply (cut_tac subring,
simp add:Subring_zero_ring_zero,
simp add:ring_times_0_x)
done
lemma (in PolynRg) monomial_d:"pol_coeff S c \<Longrightarrow>
polyn_expr R X d (ext_cf S d c) = ((snd c) 0) \<cdot>\<^sub>r X^\<^bsup>R d\<^esup>"
apply (cut_tac ring_is_ag,
cut_tac subring,
cut_tac X_mem_R,
frule subring_Ring[of S])
apply (frule pol_coeff_mem [of c 0], simp)
apply (case_tac "d = 0")
apply simp
apply (simp add:polyn_expr_def ext_cf_def sliden_def)
apply (frule ext_cf_pol_coeff[of c d])
apply (cut_tac polyn_Suc[of "d - Suc 0" "ext_cf S d c"])
apply (simp)
apply (cut_tac polyn_ext_cf_lo_zero[of c d], simp,
thin_tac "polyn_expr R X (d - Suc 0) (ext_cf S d c) = \<zero>")
apply (frule monomial_mem[of "ext_cf S d c"], simp add:ext_cf_len,
drule_tac a = d in forall_spec, simp, simp add:aGroup.ag_l_zero)
apply (subst polyn_expr_short[of "ext_cf S d c" d], assumption,
simp add:ext_cf_len)
apply (simp,
subst ext_cf_def, simp add:sliden_def , assumption+,
simp add:ext_cf_len)
done
lemma (in PolynRg) X_to_d:" X^\<^bsup>R d\<^esup> = polyn_expr R X d (ext_cf S d (C\<^sub>0 S))"
apply (cut_tac special_cf_pol_coeff)
apply (subst monomial_d[of "C\<^sub>0 S" d], assumption+)
apply (subst special_cf_def, simp)
apply (cut_tac subring, frule subring_Ring)
apply (simp add:Subring_one_ring_one)
apply (cut_tac X_mem_R, frule_tac n = d in npClose[of X])
apply (simp add:ring_l_one)
done
lemma (in PolynRg) c_max_ext_special_cf:"c_max S (ext_cf S n (C\<^sub>0 S)) = n"
apply (cut_tac polyn_ring_S_nonzero,
cut_tac subring, frule subring_Ring)
apply (simp add:c_max_def special_cf_def ext_cf_def)
apply (cut_tac n_max[of "{j. (n \<le> j \<longrightarrow> j = n) \<and> n \<le> j}" n])
apply (erule conjE)+ apply simp
apply (rule subsetI, simp, erule conjE, simp)
apply (cut_tac le_refl[of n], blast)
done
lemma (in PolynRg) scalar_times_polynTr:"a \<in> carrier S \<Longrightarrow>
\<forall>f. pol_coeff S (n, f) \<longrightarrow>
a \<cdot>\<^sub>r (polyn_expr R X n (n, f)) = polyn_expr R X n (sp_cf S a (n, f))"
apply (cut_tac subring,
cut_tac X_mem_R,
frule_tac x = a in mem_subring_mem_ring, assumption)
apply (induct_tac n,
rule allI, rule impI, simp add:polyn_expr_def sp_cf_def,
cut_tac n_in_Nsetn[of "0"])
apply (cut_tac subring_Ring,
frule_tac c = "(0, f)" in pol_coeff_mem[of _ "0"], simp)
apply (simp,
frule_tac x = "f 0" in mem_subring_mem_ring, assumption)
apply ( simp add:Subring_tOp_ring_tOp,
frule_tac y = "f 0" in ring_tOp_closed[of a], assumption+,
cut_tac ring_one, simp add:ring_tOp_assoc, assumption)
apply (rule allI, rule impI,
frule subring_Ring,
frule_tac n = n and f = f in pol_coeff_pre,
drule_tac x = f in spec, simp)
apply (cut_tac n = n and c = "(Suc n, f)" in polyn_Suc, simp,
simp del:npow_suc,
thin_tac "polyn_expr R X (Suc n) (Suc n, f) =
polyn_expr R X n (Suc n, f) \<plusminus> f (Suc n) \<cdot>\<^sub>r X^\<^bsup>R (Suc n)\<^esup>")
apply (cut_tac n = n and c = "sp_cf S a (Suc n, f)" in polyn_Suc,
simp add:sp_cf_len)
apply (frule_tac c = "(Suc n, f)" and a = a in sp_cf_len, assumption+,
simp only:fst_conv)
apply (cut_tac k = "Suc n" and f = "sp_cf S a (Suc n, f)" in
polyn_expr_split, simp del:npow_suc,
thin_tac "polyn_expr R X (Suc n) (Suc n, snd (sp_cf S a (Suc n, f))) =
polyn_expr R X n (sp_cf S a (Suc n, f)) \<plusminus>
snd (sp_cf S a (Suc n, f)) (Suc n) \<cdot>\<^sub>r X^\<^bsup>R (Suc n)\<^esup>",
thin_tac "polyn_expr R X (Suc n) (sp_cf S a (Suc n, f)) =
polyn_expr R X n (sp_cf S a (Suc n, f)) \<plusminus>
snd (sp_cf S a (Suc n, f)) (Suc n) \<cdot>\<^sub>r X^\<^bsup>R (Suc n)\<^esup>")
apply (frule_tac c = "(Suc n, f)" and a = a in sp_cf_pol_coeff, assumption)
apply (frule_tac c = "(Suc n, f)" and k = n in polyn_mem,
simp,
frule_tac c = "(Suc n, f)" in monomial_mem,
drule_tac a = "Suc n" in forall_spec, simp,
simp only:snd_conv)
apply (subst ring_distrib1, assumption+,
subst polyn_expr_restrict, assumption+, simp del:npow_suc,
subst sp_cf_val, assumption, simp, assumption,
simp only:snd_conv,
frule_tac c = "(Suc n, f)" and j = "Suc n" in pol_coeff_mem,
simp, simp only:snd_conv,
simp del:npow_suc add:Subring_tOp_ring_tOp,
subst ring_tOp_assoc[THEN sym, of a], assumption+,
simp add:mem_subring_mem_ring, rule npClose, assumption)
apply (cut_tac ring_is_ag,
rule aGroup.ag_pOp_add_r, assumption+,
rule polyn_mem, rule sp_cf_pol_coeff, assumption+,
simp add:sp_cf_len,
rule polyn_mem, assumption, simp add:sp_cf_len,
frule_tac c = "(Suc n, f)" and j = "Suc n" in pol_coeff_mem_R,
simp, simp only:snd_conv,
(rule ring_tOp_closed)+, assumption+, rule npClose, assumption)
apply (rule_tac c = "sp_cf S a (n, f)" and d = "sp_cf S a (Suc n, f)" and
k = n in polyn_exprs_eq, rule sp_cf_pol_coeff, assumption+,
simp add:sp_cf_len)
apply (rule allI, rule impI,
(subst sp_cf_def)+, simp)
done
lemma (in PolynRg) scalar_times_pol_expr:"\<lbrakk>a \<in> carrier S; pol_coeff S c;
n \<le> fst c\<rbrakk> \<Longrightarrow>
a \<cdot>\<^sub>r (polyn_expr R X n c) = polyn_expr R X n (sp_cf S a c)"
apply (cases c) apply (simp only:)
apply (rename_tac m g)
apply (thin_tac "c = (m, g)")
apply (frule_tac c = "(m, g)" and k = n in polyn_expr_short, simp,
simp)
apply (frule scalar_times_polynTr[of a n],
drule_tac x = g in spec)
apply (frule_tac c = "(m, g)" and n = n in pol_coeff_le, simp, simp,
thin_tac "polyn_expr R X n (m, g) = polyn_expr R X n (n, g)",
thin_tac "a \<cdot>\<^sub>r polyn_expr R X n (n, g) =
polyn_expr R X n (sp_cf S a (n, g))")
apply (frule_tac c = "(m, g)" and n = n in pol_coeff_le, simp, simp,
frule_tac c = "(n, g)" and a = a in sp_cf_pol_coeff, assumption,
frule_tac c = "(m, g)" and a = a in sp_cf_pol_coeff, assumption)
apply (rule_tac c = "sp_cf S a (n, g)" and d = "sp_cf S a (m, g)" and
k = n in polyn_exprs_eq, assumption+)
apply (simp add:sp_cf_len)
apply (rule allI, (subst sp_cf_def)+, simp)
done
lemma (in PolynRg) sp_coeff_nonzero:"\<lbrakk>Idomain S; a \<in> carrier S; a \<noteq> \<zero>\<^bsub>S\<^esub>;
pol_coeff S c; (snd c) j \<noteq> \<zero>\<^bsub>S\<^esub>; j \<le> (fst c)\<rbrakk> \<Longrightarrow>
snd (sp_cf S a c) j \<noteq> \<zero>\<^bsub>S\<^esub>"
apply (simp add:sp_cf_def)
apply (frule_tac y = "(snd c) j" in Idomain.idom_tOp_nonzeros[of S a],
assumption+,
simp add:pol_coeff_def, simp add:Pi_def, assumption+)
done
lemma (in PolynRg) ext_cf_inductTl:"pol_coeff S (Suc n, f) \<Longrightarrow>
polyn_expr R X (n + j) (ext_cf S j (Suc n, f)) =
polyn_expr R X (n + j) (ext_cf S j (n, f))"
apply (frule pol_coeff_pre[of n f],
frule ext_cf_pol_coeff[of "(Suc n, f)" j],
frule ext_cf_pol_coeff[of "(n, f)" j],
rule polyn_exprs_eq[of "ext_cf S j (Suc n, f)" "ext_cf S j (n, f)"
"n + j"], assumption+)
apply (simp add:ext_cf_len)
apply (rule allI, (subst ext_cf_def)+, simp add:sliden_def)
done
lemma (in PolynRg) low_deg_terms_zeroTr:"
pol_coeff S (n, f) \<longrightarrow>
polyn_expr R X (n + j) (ext_cf S j (n, f)) =
(X^\<^bsup>R j\<^esup>) \<cdot>\<^sub>r (polyn_expr R X n (n, f))"
apply (cut_tac ring_is_ag,
cut_tac X_mem_R, frule npClose[of "X" "j"])
apply (induct_tac n)
apply (rule impI, simp)
apply (case_tac "j = 0", simp add:ext_cf_def sliden_def polyn_expr_def)
apply (frule_tac c = "(0, f)" and j = 0 in pol_coeff_mem_R, simp, simp)
apply (simp add:ring_r_one ring_l_one)
apply (cut_tac polyn_Suc[of "j - Suc 0" "ext_cf S j (0, f)"],
simp del:npow_suc)
apply (frule ext_cf_len[of "(0, f)" j],
cut_tac polyn_expr_split[of j "ext_cf S j (0, f)"], simp,
thin_tac "polyn_expr R X j (ext_cf S j (0, f)) =
polyn_expr R X (j - Suc 0) (ext_cf S j (0, f)) \<plusminus>
snd (ext_cf S j (0, f)) j \<cdot>\<^sub>r X^\<^bsup>R j\<^esup>")
apply (simp add:polyn_ext_cf_lo_zero[of "(0, f)" j],
thin_tac "polyn_expr R X j (j, snd (ext_cf S j (0, f))) =
\<zero> \<plusminus> snd (ext_cf S j (0, f)) j \<cdot>\<^sub>r X^\<^bsup>R j\<^esup>",
frule ext_cf_hi[THEN sym, of "(0, f)" j], simp add:polyn_expr_def)
apply (frule_tac c = "(0, f)" and j = 0 in pol_coeff_mem_R, simp, simp)
apply (subst aGroup.ag_l_zero, assumption, simp add:ring_tOp_closed,
simp add:ring_r_one, subst ring_tOp_commute, assumption+, simp)
apply (simp add:ext_cf_len)
apply (rule impI,
cut_tac subring,
cut_tac subring_Ring[of S],
frule_tac n = n in pol_coeff_pre[of _ "f"])
apply simp
apply (subst polyn_expr_split)
apply (cut_tac n = "n + j" and c = "ext_cf S j (Suc n, f)" in polyn_Suc,
simp add:ext_cf_len)
apply (subst ext_cf_len, assumption+, simp del:npow_suc add:add.commute[of j],
thin_tac "polyn_expr R X (Suc (n + j))
(Suc (n + j), snd (ext_cf S j (Suc n, f))) =
polyn_expr R X (n + j) (ext_cf S j (Suc n, f)) \<plusminus>
snd (ext_cf S j (Suc n, f)) (Suc (n + j)) \<cdot>\<^sub>r X^\<^bsup>R (Suc (n + j))\<^esup>",
subst ext_cf_inductTl, assumption+, simp del:npow_suc,
thin_tac "polyn_expr R X (n + j) (ext_cf S j (n, f)) =
X^\<^bsup>R j\<^esup> \<cdot>\<^sub>r polyn_expr R X n (n, f)")
apply (cut_tac c1 = "(Suc n, f)" and n1 = j in ext_cf_hi[THEN sym],
assumption+,
simp del:npow_suc add:add.commute[of j])
apply (cut_tac n = n and c = "(Suc n, f)" in polyn_Suc, simp,
simp del:npow_suc)
apply (frule_tac c = "(Suc n, f)" and k = n in polyn_mem, simp,
frule_tac c = "(Suc n, f)" and j = "Suc n" in pol_coeff_mem_R, simp,
simp del:npow_suc,
frule_tac x = "f (Suc n)" and y = "X^\<^bsup>R (Suc n)\<^esup>" in ring_tOp_closed,
rule npClose, assumption,
subst ring_distrib1, assumption+)
apply (subst polyn_expr_restrict, assumption+)
apply (rule_tac a = "f (Suc n) \<cdot>\<^sub>r X^\<^bsup>R (Suc (n + j))\<^esup> " and
b = "X^\<^bsup>R j\<^esup> \<cdot>\<^sub>r (f (Suc n) \<cdot>\<^sub>r X^\<^bsup>R (Suc n)\<^esup>)" and
c = "X^\<^bsup>R j\<^esup> \<cdot>\<^sub>r polyn_expr R X n (n, f)" in aGroup.ag_pOp_add_l,
assumption+,
rule ring_tOp_closed, assumption+, rule npClose, assumption,
(rule ring_tOp_closed, assumption+)+,
simp add:polyn_mem,
frule_tac n = "Suc n" in npClose[of X],
subst ring_tOp_assoc[THEN sym], assumption+,
subst ring_tOp_commute[of "X^\<^bsup>R j\<^esup>"], assumption,
simp add:pol_coeff_mem,
subst ring_tOp_assoc, assumption+,
subst npMulDistr[of X], assumption, simp add:add.commute[of j])
apply simp
done
lemma (in PolynRg) low_deg_terms_zero:"pol_coeff S (n, f) \<Longrightarrow>
polyn_expr R X (n + j) (ext_cf S j (n, f)) =
(X^\<^bsup>R j\<^esup>) \<cdot>\<^sub>r (polyn_expr R X n (n, f))"
by (simp add:low_deg_terms_zeroTr)
lemma (in PolynRg) low_deg_terms_zero1:"pol_coeff S c \<Longrightarrow>
polyn_expr R X ((fst c) + j) (ext_cf S j c) =
(X^\<^bsup>R j\<^esup>) \<cdot>\<^sub>r (polyn_expr R X (fst c) c)"
by (cases c) (simp add: low_deg_terms_zeroTr)
lemma (in PolynRg) polyn_expr_tOpTr:"pol_coeff S (n, f) \<Longrightarrow>
\<forall>g. (pol_coeff S (m, g) \<longrightarrow> (\<exists>h. pol_coeff S ((n + m), h) \<and>
h (n + m) = (f n) \<cdot>\<^sub>r\<^bsub>S\<^esub> (g m) \<and>
(polyn_expr R X (n + m) (n + m, h) =
(polyn_expr R X n (n, f)) \<cdot>\<^sub>r (polyn_expr R X m (m, g)))))"
apply (cut_tac subring,
cut_tac X_mem_R,
frule subring_Ring[of S])
apply (induct_tac m)
apply (rule allI, rule impI, simp)
apply (simp add:polyn_expr_def [of R X 0])
apply (frule_tac c = "(0,g)" in pol_coeff_mem[of _ 0], simp, simp,
frule_tac c = "(0,g)" in pol_coeff_mem_R[of _ 0], simp, simp)
apply (simp add:ring_r_one,
frule_tac c = "(n, f)" and k = n in polyn_mem, simp,
simp only:ring_tOp_commute[of "polyn_expr R X n (n, f)"],
subst scalar_times_pol_expr, assumption+, simp)
apply (cut_tac f = "sp_cf S (g 0) (n, f)" in pol_coeff_split)
apply (simp add:sp_cf_len)
apply (cut_tac f = "sp_cf S (g 0) (n, f)" in polyn_expr_split[of n],
simp only:sp_cf_len, simp only:fst_conv,
frule_tac a = "g 0" in sp_cf_pol_coeff[of "(n, f)"], assumption+,
simp,
subgoal_tac "snd (sp_cf S (g 0) (n, f)) n = (f n) \<cdot>\<^sub>r\<^bsub>S\<^esub> (g 0)", blast)
apply (thin_tac "pol_coeff S (n, snd (sp_cf S (g 0) (n, f)))",
thin_tac "polyn_expr R X n (sp_cf S (g 0) (n, f)) =
polyn_expr R X n (n, snd (sp_cf S (g 0) (n, f)))",
thin_tac "pol_coeff S (sp_cf S (g 0) (n, f))")
apply (subst sp_cf_val[of "(n, f)" n], assumption+, simp, assumption, simp,
frule_tac c = "(n,f)" in pol_coeff_mem[of _ n], simp, simp,
simp add:Ring.ring_tOp_commute)
apply (rule allI, rule impI)
apply (frule_tac n = na and f = g in pol_coeff_pre,
drule_tac a = g in forall_spec, assumption+)
apply (erule exE, (erule conjE)+)
apply (cut_tac n = na and c = "(Suc na, g)" in polyn_Suc, (simp del:npow_suc)+,
thin_tac "polyn_expr R X (Suc na) (Suc na, g) =
polyn_expr R X na (Suc na, g) \<plusminus> g (Suc na) \<cdot>\<^sub>r X^\<^bsup>R (Suc na)\<^esup>",
subst polyn_expr_restrict, assumption)
apply (frule_tac c = "(n, f)" and k = n in polyn_mem,simp del:npow_suc,
frule_tac c = "(na, g)" and k = na in polyn_mem, simp del:npow_suc,
frule_tac c = "(Suc na, g)" in monomial_mem, simp del:npow_suc,
drule_tac a = "Suc na" in forall_spec, simp del:npow_suc)
apply (subst ring_distrib1, assumption+)
apply (rotate_tac 8, drule sym,
simp del:npow_suc)
apply (thin_tac "polyn_expr R X n (n, f) \<cdot>\<^sub>r polyn_expr R X na (na, g) =
polyn_expr R X (n + na) (n + na, h)")
apply (frule_tac c = "(Suc na, g)" and j ="Suc na" in pol_coeff_mem_R, simp,
simp del:npow_suc,
frule_tac c = "(Suc na, g)" and j ="Suc na" in pol_coeff_mem, simp,
simp del:npow_suc)
apply (subst ring_tOp_commute, assumption+,
subst ring_tOp_assoc, assumption+, rule npClose, assumption+,
subst low_deg_terms_zero[THEN sym], assumption+)
apply (frule_tac c = "(n, f)" and n = "Suc na" in ext_cf_pol_coeff)
apply (frule_tac c = "ext_cf S (Suc na) (n, f)" and a = "g (Suc na)" in
sp_cf_pol_coeff, assumption)
apply (subst scalar_times_pol_expr, assumption+,
simp add:ext_cf_len,
cut_tac k = "n + Suc na" and
f = "sp_cf S (g (Suc na)) (ext_cf S (Suc na) (n, f))" in
polyn_expr_split,
simp only:sp_cf_len,
thin_tac "polyn_expr R X (n + Suc na)
(sp_cf S (g (Suc na)) (ext_cf S (Suc na) (n, f))) =
polyn_expr R X (n + Suc na)
(fst (ext_cf S (Suc na) (n, f)),
snd (sp_cf S (g (Suc na)) (ext_cf S (Suc na) (n, f))))",
simp only:ext_cf_len, simp only:fst_conv,
simp add:add.commute[of _ n])
apply (subst polyn_add, assumption+,
cut_tac f = "sp_cf S (g (Suc na)) (ext_cf S (Suc na) (n, f))" in
pol_coeff_split, simp only:sp_cf_len, simp only:ext_cf_len,
simp add:add.commute[of _ n], simp add: max_def,
frule_tac c = "sp_cf S (g (Suc na)) (ext_cf S (Suc na) (n, f))"
in pol_coeff_cartesian,
simp only:sp_cf_len, simp only:ext_cf_len,
simp add:add.commute[of _ n],
thin_tac "(Suc (n + na),
snd (sp_cf S (g (Suc na)) (ext_cf S (Suc na) (n, f)))) =
sp_cf S (g (Suc na)) (ext_cf S (Suc na) (n, f))",
frule_tac c = "(n + na, h)" and
d = "sp_cf S (g (Suc na)) (ext_cf S (Suc na) (n, f))" in
add_cf_pol_coeff, assumption)
apply (cut_tac k = "Suc (n + na)" and f = "add_cf S (n + na, h)
(sp_cf S (g (Suc na)) (ext_cf S (Suc na) (n, f)))" in polyn_expr_split,
simp only:mp,
thin_tac "polyn_expr R X (Suc (n + na))
(add_cf S (n + na, h)
(sp_cf S (g (Suc na)) (ext_cf S (Suc na) (n, f)))) =
polyn_expr R X (Suc (n + na))
(fst (add_cf S (n + na, h)
(sp_cf S (g (Suc na)) (ext_cf S (Suc na) (n, f)))),
snd (add_cf S (n + na, h)
(sp_cf S (g (Suc na)) (ext_cf S (Suc na) (n, f)))))",
subst add_cf_len, assumption+,
simp add:sp_cf_len, simp add:ext_cf_len max_def,
cut_tac f = "add_cf S (n + na, h)
(sp_cf S (g (Suc na)) (ext_cf S (Suc na) (n, f)))" in
pol_coeff_split,
simp only:add_cf_len,
simp only:sp_cf_len, simp add:ext_cf_len, simp add:max_def,
thin_tac "pol_coeff S
(add_cf S (n + na, h)
(sp_cf S (g (Suc na)) (ext_cf S (Suc na) (n, f))))",
subgoal_tac "snd (add_cf S (n + na, h) (sp_cf S (g (Suc na))
(ext_cf S (Suc na) (n, f)))) (Suc (n + na)) = f n \<cdot>\<^sub>r\<^bsub>S\<^esub> g (Suc na)",
simp add:add.commute[of _ n], blast)
apply (subst add_cf_def, simp add:sp_cf_len ext_cf_len,
subst sp_cf_def, simp add:ext_cf_len,
subst ext_cf_def, simp add:sliden_def,
frule pol_coeff_mem[of "(n, f)" n], simp,
simp add:Ring.ring_tOp_commute)
done
lemma (in PolynRg) polyn_expr_tOp:"\<lbrakk>
pol_coeff S (n, f); pol_coeff S (m, g)\<rbrakk> \<Longrightarrow> \<exists>e. pol_coeff S ((n + m), e) \<and>
e (n + m) = (f n) \<cdot>\<^sub>r\<^bsub>S\<^esub> (g m) \<and>
polyn_expr R X (n + m)(n + m, e) =
(polyn_expr R X n (n, f)) \<cdot>\<^sub>r (polyn_expr R X m (m, g))"
by (simp add:polyn_expr_tOpTr)
lemma (in PolynRg) polyn_expr_tOp_c:"\<lbrakk>pol_coeff S c; pol_coeff S d\<rbrakk> \<Longrightarrow>
\<exists>e. pol_coeff S e \<and> (fst e = fst c + fst d) \<and>
(snd e) (fst e) = (snd c (fst c)) \<cdot>\<^sub>r\<^bsub>S\<^esub> (snd d) (fst d) \<and>
polyn_expr R X (fst e) e =
(polyn_expr R X (fst c) c) \<cdot>\<^sub>r (polyn_expr R X (fst d) d)"
by (cases c, cases d) (simp add: polyn_expr_tOpTr)
section "The degree of a polynomial"
lemma (in PolynRg) polyn_degreeTr:"\<lbrakk>pol_coeff S c; k \<le> (fst c)\<rbrakk> \<Longrightarrow>
(polyn_expr R X k c = \<zero> ) = ({j. j \<le> k \<and> (snd c) j \<noteq> \<zero>\<^bsub>S\<^esub>} = {})"
apply (subst coeff_0_pol_0[THEN sym, of c k], assumption+)
apply blast
done
lemma (in PolynRg) higher_part_zero:"\<lbrakk>pol_coeff S c; k < fst c;
\<forall>j\<in>nset (Suc k) (fst c). snd c j = \<zero>\<^bsub>S\<^esub>\<rbrakk> \<Longrightarrow>
\<Sigma>\<^sub>f R (\<lambda>j. snd c j \<cdot>\<^sub>r X^\<^bsup>R j\<^esup>) (Suc k) (fst c) = \<zero>"
apply (cut_tac ring_is_ag,
rule aGroup.fSum_zero1[of R k "fst c" "\<lambda>j. snd c j \<cdot>\<^sub>r X^\<^bsup>R j\<^esup>"],
assumption+)
apply (rule ballI,
drule_tac x = j in bspec, assumption, simp)
apply (cut_tac subring,
simp add:Subring_zero_ring_zero,
cut_tac X_mem_R,
frule_tac n = j in npClose[of X],
simp add:ring_times_0_x)
done
lemma (in PolynRg) coeff_nonzero_polyn_nonzero:"\<lbrakk>pol_coeff S c; k \<le> (fst c)\<rbrakk>
\<Longrightarrow> (polyn_expr R X k c \<noteq> \<zero>) = (\<exists>j\<le>k. (snd c) j \<noteq> \<zero>\<^bsub>S\<^esub> )"
by (simp add:coeff_0_pol_0[THEN sym, of c k])
lemma (in PolynRg) pol_expr_unique:"\<lbrakk>p \<in> carrier R; p \<noteq> \<zero>;
pol_coeff S c; p = polyn_expr R X (fst c) c; (snd c) (fst c) \<noteq> \<zero>\<^bsub>S\<^esub>;
pol_coeff S d; p = polyn_expr R X (fst d) d; (snd d) (fst d) \<noteq> \<zero>\<^bsub>S\<^esub>\<rbrakk> \<Longrightarrow>
(fst c) = (fst d) \<and> (\<forall>j \<le> (fst c). (snd c) j = (snd d) j)"
apply (cut_tac ring_is_ag,
cut_tac subring, frule subring_Ring,
frule Ring.ring_is_ag[of S])
apply (frule m_cf_pol_coeff[of d])
apply (frule polyn_minus_m_cf[of d "fst d"], simp)
apply (drule sym, drule sym, simp)
apply (rotate_tac -2, drule sym, drule sym)
apply (frule_tac x = p in aGroup.ag_r_inv1[of R], assumption, simp,
thin_tac "p = polyn_expr R X (fst c) c",
thin_tac "polyn_expr R X (fst d) d = polyn_expr R X (fst c) c",
thin_tac "-\<^sub>a (polyn_expr R X (fst c) c) =
polyn_expr R X (fst d) (m_cf S d)")
apply (frule polyn_add1[of c "m_cf S d"], assumption+, simp add:m_cf_len,
thin_tac "polyn_expr R X (fst c) c \<plusminus> polyn_expr R X (fst d) (m_cf S d)
= polyn_expr R X (max (fst c) (fst d)) (add_cf S c (m_cf S d))",
thin_tac "polyn_expr R X (fst c) c \<noteq>
polyn_expr R X (max (fst c) (fst d)) (add_cf S c (m_cf S d))")
apply (frule_tac add_cf_pol_coeff[of c "m_cf S d"], simp add:m_cf_len)
apply (cut_tac coeff_0_pol_0[THEN sym, of "add_cf S c (m_cf S d)"
"max (fst c) (fst d)"],
drule sym, simp,
thin_tac "polyn_expr R X (max (fst c) (fst d))
(add_cf S c (m_cf S d)) = \<zero>",
thin_tac "pol_coeff S (add_cf S c (m_cf S d))",
thin_tac "pol_coeff S (m_cf S d)")
apply (case_tac "fst c = fst d", simp)
apply (rule allI, rule impI,
drule_tac a = j in forall_spec, assumption)
apply (simp add:add_cf_def m_cf_def m_cf_len)
apply (frule_tac j = j in pol_coeff_mem[of c], simp,
frule_tac j = j in pol_coeff_mem[of d], simp)
apply (subst aGroup.ag_eq_diffzero[of S], assumption+)
apply (simp add:add_cf_def)
apply (case_tac "\<not> (fst c) \<le> (fst d)", simp)
apply (simp add:m_cf_len)
apply (drule_tac a = "fst c" in forall_spec, simp, simp)
apply simp
apply (drule_tac a = "fst d" in forall_spec, simp, simp add:m_cf_len)
apply (case_tac "fst c \<noteq> fst d",
frule noteq_le_less[of "fst c" "fst d"], assumption, simp)
apply (simp add:m_cf_def)
apply (frule pol_coeff_mem[of d "fst d"], simp)
apply (frule Ring.ring_is_ag[of S],
frule aGroup.ag_inv_inv[of S "snd d (fst d)"], assumption)
apply (simp add:aGroup.ag_inv_zero)
apply simp
apply simp
apply (simp add:add_cf_len m_cf_len)
done
lemma (in PolynRg) pol_expr_unique2:"\<lbrakk>pol_coeff S c; pol_coeff S d;
fst c = fst d\<rbrakk> \<Longrightarrow>
(polyn_expr R X (fst c) c = polyn_expr R X (fst d) d ) =
(\<forall>j \<le> (fst c). (snd c) j = (snd d) j)"
apply (cut_tac ring_is_ag,
cut_tac subring, frule subring_Ring,
frule Ring.ring_is_ag[of S])
apply (rule iffI)
apply (frule m_cf_pol_coeff[of d])
apply (frule polyn_mem[of c "fst c"], simp,
frule polyn_mem[of d "fst d"], simp)
apply (frule aGroup.ag_eq_diffzero[of R "polyn_expr R X (fst c) c"
"polyn_expr R X (fst d) d"], assumption+,
simp,
simp only:polyn_minus_m_cf[of d "fst d"],
drule sym, simp)
apply (frule polyn_add1[of c "m_cf S d"], assumption+, simp add:m_cf_len)
apply (thin_tac "polyn_expr R X (fst c) d \<plusminus> polyn_expr R X (fst c)
(m_cf S d) =
polyn_expr R X (fst c) (add_cf S c (m_cf S d))",
thin_tac "polyn_expr R X (fst c) c = polyn_expr R X (fst c) d",
thin_tac "polyn_expr R X (fst c) d \<in> carrier R",
drule sym)
apply (frule_tac add_cf_pol_coeff[of c "m_cf S d"], simp add:m_cf_len)
apply (frule coeff_0_pol_0[THEN sym, of "add_cf S c (m_cf S d)"
"fst c"],
simp add:add_cf_len, simp add:m_cf_len,
thin_tac "\<zero> = polyn_expr R X (fst d) (add_cf S c (m_cf S d))",
thin_tac "pol_coeff S (add_cf S c (m_cf S d))")
apply (simp add:add_cf_def m_cf_def)
apply (rule allI, rule impI)
apply (drule_tac a = j in forall_spec, assumption)
apply (frule_tac j = j in pol_coeff_mem[of c], simp,
frule_tac j = j in pol_coeff_mem[of d], simp)
apply (simp add:aGroup.ag_eq_diffzero[THEN sym])
apply simp
apply (rule polyn_exprs_eq[of c d "fst d"], assumption+)
apply (simp, assumption+)
done
lemma (in PolynRg) pol_expr_unique3:"\<lbrakk>pol_coeff S c; pol_coeff S d;
fst c < fst d\<rbrakk> \<Longrightarrow>
(polyn_expr R X (fst c) c = polyn_expr R X (fst d) d ) =
((\<forall>j \<le> (fst c). (snd c) j = (snd d) j) \<and>
(\<forall>j\<in>nset (Suc (fst c)) (fst d). (snd d) j = \<zero>\<^bsub>S\<^esub>))"
apply (rule iffI)
apply (cut_tac ring_is_ag,
cut_tac subring, frule subring_Ring,
frule Ring.ring_is_ag[of S])
apply (frule m_cf_pol_coeff[of d])
apply (frule polyn_mem[of c "fst c"], simp,
frule polyn_mem[of d "fst d"], simp)
apply (frule aGroup.ag_eq_diffzero[of R "polyn_expr R X (fst c) c"
"polyn_expr R X (fst d) d"], assumption+,
simp,
simp only:polyn_minus_m_cf[of d "fst d"],
drule sym, simp)
apply (frule polyn_add1[of c "m_cf S d"], assumption+, simp add:m_cf_len,
thin_tac "polyn_expr R X (fst c) c \<plusminus> polyn_expr R X (fst d)
(m_cf S d) =
polyn_expr R X (max (fst c) (fst d)) (add_cf S c (m_cf S d))",
thin_tac "polyn_expr R X (fst d) d = polyn_expr R X (fst c) c",
thin_tac "polyn_expr R X (fst c) c \<in> carrier R", drule sym)
apply (frule_tac add_cf_pol_coeff[of c "m_cf S d"], simp add:m_cf_len)
apply (frule coeff_0_pol_0[THEN sym, of "add_cf S c (m_cf S d)"
"max (fst c) (fst d)"],
simp add:add_cf_len m_cf_len, simp,
thin_tac "polyn_expr R X (max (fst c) (fst d))
(add_cf S c (m_cf S d)) = \<zero>",
thin_tac "pol_coeff S (add_cf S c (m_cf S d))")
apply (simp add:add_cf_def m_cf_def max_def)
apply (rule conjI)
apply (rule allI, rule impI,
frule_tac x = j and y = "fst c" and z = "fst d" in le_less_trans,
assumption+,
frule_tac x = j and y = "fst d" in less_imp_le)
apply (drule_tac a = j in forall_spec, simp, simp)
apply (frule_tac j = j in pol_coeff_mem[of c], simp,
frule_tac j = j in pol_coeff_mem[of d], simp)
apply (simp add:aGroup.ag_eq_diffzero[THEN sym])
apply (rule ballI, simp add:nset_def, erule conjE)
apply (cut_tac x = "fst c" and y = "Suc (fst c)" and z = j in
less_le_trans, simp, assumption)
apply (cut_tac m1 = "fst c" and n1 = j in nat_not_le_less[THEN sym], simp)
apply (drule_tac a = j in forall_spec, assumption, simp,
frule_tac j = j in pol_coeff_mem[of d], simp)
apply (frule_tac x = "snd d j" in aGroup.ag_inv_inv[of S], assumption,
simp add:aGroup.ag_inv_inv aGroup.ag_inv_zero)
apply (cut_tac polyn_n_m[of d "fst c" "fst d"])
apply (subst polyn_expr_split[of "fst d" d], simp,
thin_tac "polyn_expr R X (fst d) d =
polyn_expr R X (fst c) (fst c, snd d) \<plusminus>
\<Sigma>\<^sub>f R (\<lambda>j. snd d j \<cdot>\<^sub>r X^\<^bsup>R j\<^esup>) (Suc (fst c)) (fst d)", erule conjE)
apply (subst higher_part_zero[of d "fst c"], assumption+)
apply (frule pol_coeff_le[of d "fst c"], simp add:less_imp_le,
frule polyn_mem[of "(fst c, snd d)" "fst c"], simp,
cut_tac ring_is_ag,
simp add:aGroup.ag_r_zero,
subst polyn_expr_short[THEN sym, of d "fst c"], assumption+,
simp add:less_imp_le)
apply (rule polyn_exprs_eq[of c d "fst c"], assumption+)
apply (simp, assumption+)
apply (simp add:less_imp_le)
done
lemma (in PolynRg) polyn_degree_unique:"\<lbrakk>pol_coeff S c; pol_coeff S d;
polyn_expr R X (fst c) c = polyn_expr R X (fst d) d\<rbrakk> \<Longrightarrow>
c_max S c = c_max S d"
apply (cut_tac ring_is_ag,
cut_tac subring,
frule subring_Ring,
frule Ring.ring_is_ag[of S])
apply (case_tac "polyn_expr R X (fst d) d = \<zero>\<^bsub>R\<^esub>")
apply (cut_tac coeff_0_pol_0[THEN sym, of d "fst d"], simp,
cut_tac coeff_0_pol_0[THEN sym, of c "fst c"], simp)
apply (simp add:c_max_def, assumption, simp, assumption, simp)
apply (frule polyn_mem[of c "fst c"], simp, frule polyn_mem[of d "fst d"],
simp)
apply (frule aGroup.ag_eq_diffzero[of "R" "polyn_expr R X (fst c) c"
"polyn_expr R X (fst d) d"], assumption+)
apply (simp only:polyn_minus_m_cf[of d "fst d"],
frule m_cf_pol_coeff [of d])
apply (frule polyn_add1[of c "m_cf S d"], assumption+,
simp only:m_cf_len)
apply (rotate_tac -1, drule sym, simp,
thin_tac "polyn_expr R X (fst d) d \<plusminus>
polyn_expr R X (fst d) (m_cf S d) = \<zero>",
frule add_cf_pol_coeff[of c "m_cf S d"], assumption+)
apply (cut_tac coeff_0_pol_0[THEN sym, of "add_cf S c (m_cf S d)"
"fst (add_cf S c (m_cf S d))"],
simp add:add_cf_len m_cf_len,
thin_tac "polyn_expr R X (max (fst c) (fst d))
(add_cf S c (m_cf S d)) = \<zero>",
thin_tac "pol_coeff S (add_cf S c (m_cf S d))",
thin_tac "pol_coeff S (m_cf S d)")
apply (frule coeff_nonzero_polyn_nonzero[of d "fst d"], simp, simp)
apply (drule sym, simp)
apply (frule coeff_nonzero_polyn_nonzero[of c "fst c"], simp, simp)
apply (simp add:c_max_def, rule conjI, rule impI, blast,
rule conjI, rule impI, blast)
apply (rule n_max_eq_sets)
apply (rule equalityI)
apply (rule subsetI, simp)
apply (erule conjE)
apply (case_tac "fst c \<le> fst d")
apply (frule_tac i = x in le_trans[of _ "fst c" "fst d"], assumption+, simp,
rule contrapos_pp, simp+, simp add:max_def,
frule_tac i = x in le_trans[of _ "fst c" "fst d"], assumption+,
drule_tac a = x in forall_spec, assumption,
drule le_imp_less_or_eq[of "fst c" "fst d"],
erule disjE, simp add:add_cf_def m_cf_len m_cf_def,
frule_tac j = x in pol_coeff_mem[of c], assumption+,
simp add:aGroup.ag_inv_zero aGroup.ag_r_zero[of S])
apply (simp add:add_cf_def m_cf_len m_cf_def,
rotate_tac -1, drule sym, simp,
frule_tac j = x in pol_coeff_mem[of c], simp,
simp add:aGroup.ag_inv_zero aGroup.ag_r_zero[of S])
apply (simp add:nat_not_le_less) (* \<not> fst c \<le> fst d *)
apply (case_tac "\<not> x \<le> (fst d)", simp,
simp add:nat_not_le_less,
frule_tac x = "fst d" and y = x and z = "fst c" in
less_le_trans, assumption+,
drule_tac x = x in spec, simp add:max_def,
simp add:add_cf_def m_cf_len m_cf_def)
apply (simp,
drule_tac x = x in spec, simp add:max_def,
rule contrapos_pp, simp+,
simp add:add_cf_def m_cf_len m_cf_def,
frule_tac j = x in pol_coeff_mem[of c],
frule_tac x = x and y = "fst d" and z = "fst c" in
le_less_trans, assumption+, simp add:less_imp_le,
simp add:aGroup.ag_inv_zero aGroup.ag_r_zero[of S])
apply (rule subsetI, simp, erule conjE,
case_tac "fst d \<le> fst c",
frule_tac i = x and j = "fst d" and k = "fst c" in le_trans,
assumption+, simp,
drule_tac x = x in spec, simp add:max_def,
rule contrapos_pp, simp+,
simp add:add_cf_def m_cf_len m_cf_def)
apply (case_tac "fst d = fst c", simp, rotate_tac -1, drule sym, simp,
frule_tac j = x in pol_coeff_mem[of d], assumption,
frule_tac x = "snd d x" in aGroup.ag_mOp_closed, assumption+,
simp add:aGroup.ag_l_zero,
frule_tac x = "snd d x" in aGroup.ag_inv_inv[of S],
assumption, simp add:aGroup.ag_inv_zero)
apply (drule noteq_le_less[of "fst d" "fst c"], assumption,
simp,
frule_tac j = x in pol_coeff_mem[of d], assumption,
frule_tac x = "snd d x" in aGroup.ag_mOp_closed, assumption+,
simp add:aGroup.ag_l_zero,
frule_tac x = "snd d x" in aGroup.ag_inv_inv[of S],
assumption, simp add:aGroup.ag_inv_zero)
apply (simp add:nat_not_le_less,
case_tac "\<not> x \<le> fst c", simp,
simp add:nat_not_le_less,
drule_tac x = x in spec, simp add:max_def,
simp add:add_cf_def m_cf_len m_cf_def,
frule_tac j = x in pol_coeff_mem[of d], assumption,
frule_tac x = "snd d x" in aGroup.ag_mOp_closed, assumption+,
simp add:aGroup.ag_l_zero,
frule_tac x = "snd d x" in aGroup.ag_inv_inv[of S],
assumption, simp add:aGroup.ag_inv_zero)
apply (simp,
drule_tac x = x in spec, simp add:max_def,
rule contrapos_pp, simp+,
simp add:add_cf_def m_cf_len m_cf_def,
frule_tac x = x and y = "fst c" and z = "fst d" in le_less_trans,
assumption+, frule_tac x = x and y = "fst d" in less_imp_le,
frule_tac j = x in pol_coeff_mem[of d], assumption,
frule_tac x = "snd d x" in aGroup.ag_mOp_closed, assumption+,
simp add:aGroup.ag_l_zero,
frule_tac x = "snd d x" in aGroup.ag_inv_inv[of S],
assumption, simp add:aGroup.ag_inv_zero)
apply (thin_tac "\<forall>j\<le>max (fst c) (fst d). snd (add_cf S c (m_cf S d)) j = \<zero>\<^bsub>S\<^esub>")
apply (rotate_tac -1, drule sym, simp)
apply (simp add:coeff_0_pol_0[THEN sym, of c "fst c"])
apply blast
apply simp+
done
lemma (in PolynRg) ex_polyn_expr:"p \<in> carrier R \<Longrightarrow>
\<exists>c. pol_coeff S c \<and> p = polyn_expr R X (fst c) c"
apply (cut_tac S_X_generate[of p], blast)
apply assumption
done
lemma (in PolynRg) c_max_eqTr0:"\<lbrakk>pol_coeff S c; k \<le> (fst c);
polyn_expr R X k c = polyn_expr R X (fst c) c; \<exists>j\<le>k. (snd c) j \<noteq> \<zero>\<^bsub>S\<^esub>\<rbrakk> \<Longrightarrow>
c_max S (k, snd c) = c_max S c"
apply (simp add:polyn_expr_short[of c k],
frule pol_coeff_le[of c k], assumption+,
rule polyn_degree_unique[of "(k, snd c)" c], assumption+,
simp)
done
definition
cf_sol :: "[('a, 'b) Ring_scheme, ('a, 'b1) Ring_scheme, 'a, 'a,
nat \<times> (nat \<Rightarrow> 'a)] \<Rightarrow> bool" where
"cf_sol R S X p c \<longleftrightarrow> pol_coeff S c \<and> (p = polyn_expr R X (fst c) c)"
definition
deg_n ::"[('a, 'b) Ring_scheme, ('a, 'b1) Ring_scheme, 'a, 'a] \<Rightarrow> nat" where
"deg_n R S X p = c_max S (SOME c. cf_sol R S X p c)"
definition
deg ::"[('a, 'b) Ring_scheme, ('a, 'b1) Ring_scheme, 'a, 'a] \<Rightarrow> ant" where
"deg R S X p = (if p = \<zero>\<^bsub>R\<^esub> then -\<infinity> else (an (deg_n R S X p)))"
lemma (in PolynRg) ex_cf_sol:"p \<in> carrier R \<Longrightarrow>
\<exists>c. cf_sol R S X p c"
apply (unfold cf_sol_def)
apply (frule ex_polyn_expr[of p], (erule exE)+)
apply (cut_tac n = "fst c" in le_refl, blast)
done
lemma (in PolynRg) deg_in_aug_minf:"p \<in> carrier R \<Longrightarrow>
deg R S X p \<in> Z\<^sub>-\<^sub>\<infinity>"
apply (simp add:aug_minf_def deg_def an_def)
done
lemma (in PolynRg) deg_noninf:"p \<in> carrier R \<Longrightarrow>
deg R S X p \<noteq> \<infinity>"
apply (cut_tac deg_in_aug_minf[of p], simp add:deg_def,
simp add:aug_minf_def)
apply (case_tac "p = \<zero>\<^bsub>R\<^esub>", simp+)
done
lemma (in PolynRg) deg_ant_int:"\<lbrakk>p \<in> carrier R; p \<noteq> \<zero>\<rbrakk>
\<Longrightarrow> deg R S X p = ant (int (deg_n R S X p))"
by (simp add:deg_def an_def)
lemma (in PolynRg) deg_an:"\<lbrakk>p \<in> carrier R; p \<noteq> \<zero>\<rbrakk>
\<Longrightarrow> deg R S X p = an (deg_n R S X p)"
by (simp add:deg_def)
lemma (in PolynRg) pol_SOME_1:"p \<in> carrier R \<Longrightarrow>
cf_sol R S X p (SOME f. cf_sol R S X p f)"
apply (frule ex_cf_sol[of p])
apply (rule_tac P = "cf_sol R S X p" in someI_ex, assumption)
done
lemma (in PolynRg) pol_SOME_2:"p \<in> carrier R \<Longrightarrow>
pol_coeff S (SOME c. cf_sol R S X p c) \<and>
p = polyn_expr R X (fst (SOME c. cf_sol R S X p c))
(SOME c. cf_sol R S X p c)"
apply (frule pol_SOME_1[of p])
apply (simp add:cf_sol_def)
done
lemma (in PolynRg) coeff_max_zeroTr:"pol_coeff S c \<Longrightarrow>
\<forall>j. j \<le> (fst c) \<and> (c_max S c) < j \<longrightarrow> (snd c) j = \<zero>\<^bsub>S\<^esub>"
apply (case_tac "\<forall>j \<le> (fst c). (snd c) j = \<zero>\<^bsub>S\<^esub>", rule allI, rule impI,
erule conjE, simp)
apply simp
apply (frule coeff_nonzero_polyn_nonzero[THEN sym, of c "fst c"], simp,
simp)
apply (rule allI, rule impI, erule conjE,
simp add:c_max_def,
simp add:polyn_degreeTr[of c "fst c"])
apply (subgoal_tac "{j. j \<le> (fst c) \<and> (snd c) j \<noteq> \<zero>\<^bsub>S\<^esub>} \<subseteq> {j. j \<le> (fst c)}",
frule n_max[of "{j. j \<le> (fst c) \<and> (snd c) j \<noteq> \<zero>\<^bsub>S\<^esub>}" "fst c"], blast)
apply (case_tac "\<forall>x\<le>fst c. snd c x = \<zero>\<^bsub>S\<^esub> ", blast, simp)
apply (erule conjE)
apply (rule contrapos_pp, simp+,
thin_tac "\<exists>x\<le>fst c. snd c x \<noteq> \<zero>\<^bsub>S\<^esub>",
thin_tac "{j. j \<le> fst c \<and> snd c j \<noteq> \<zero>\<^bsub>S\<^esub>} \<subseteq> {j. j \<le> fst c}",
thin_tac "snd c (n_max {j. j \<le> fst c \<and> snd c j \<noteq> \<zero>\<^bsub>S\<^esub>}) \<noteq> \<zero>\<^bsub>S\<^esub>",
drule_tac a = j in forall_spec, simp)
apply simp
apply (rule subsetI, simp)
done
lemma (in PolynRg) coeff_max_nonzeroTr:"\<lbrakk>pol_coeff S c;
\<exists>j \<le> (fst c). (snd c) j \<noteq> \<zero>\<^bsub>S\<^esub>\<rbrakk> \<Longrightarrow> (snd c) (c_max S c) \<noteq> \<zero>\<^bsub>S\<^esub>"
apply (simp add:c_max_def)
apply (subgoal_tac "{j. j \<le> (fst c) \<and> (snd c) j \<noteq> \<zero>\<^bsub>S\<^esub>} \<subseteq> {j. j \<le> (fst c)}",
frule n_max[of "{j. j \<le> (fst c) \<and> (snd c) j \<noteq> \<zero>\<^bsub>S\<^esub>}" "fst c"], blast)
apply (erule conjE, simp)
apply (rule subsetI, simp)
done
lemma (in PolynRg) coeff_max_bddTr:"pol_coeff S c \<Longrightarrow> c_max S c \<le> (fst c)"
apply (case_tac "\<forall>j\<le>(fst c). (snd c) j = \<zero>\<^bsub>S\<^esub>", simp add:c_max_def)
apply (simp add:c_max_def,
frule polyn_degreeTr[of c "fst c"], simp, simp,
subgoal_tac "{j. j \<le> (fst c) \<and> (snd c) j \<noteq> \<zero>\<^bsub>S\<^esub>} \<subseteq> {j. j \<le> (fst c)}",
frule n_max[of "{j. j \<le> (fst c) \<and> (snd c) j \<noteq> \<zero>\<^bsub>S\<^esub>}" "fst c"],
blast, erule conjE, simp)
apply (rule subsetI, simp)
done
lemma (in PolynRg) pol_coeff_max:"pol_coeff S c \<Longrightarrow>
pol_coeff S ((c_max S c), snd c)"
apply (rule pol_coeff_le[of c "c_max S c"], assumption)
apply (simp add:coeff_max_bddTr)
done
lemma (in PolynRg) polyn_c_max:"pol_coeff S c \<Longrightarrow>
polyn_expr R X (fst c) c = polyn_expr R X (c_max S c) c"
apply (case_tac "(c_max S c) = (fst c)", simp)
apply (frule coeff_max_bddTr[of c],
frule noteq_le_less[of "c_max S c" "fst c"], assumption)
apply (subst polyn_n_m1[of c "c_max S c" "fst c"], assumption+, simp)
apply (frule_tac polyn_mem[of c "c_max S c"], assumption+)
apply (subst higher_part_zero[of c "c_max S c"], assumption+)
apply (frule coeff_max_zeroTr[of c],
rule ballI, simp add:nset_def)
apply (cut_tac ring_is_ag, simp add:aGroup.ag_r_zero)
done
lemma (in PolynRg) pol_deg_eq_c_max:"\<lbrakk>p \<in> carrier R;
pol_coeff S c; p = polyn_expr R X (fst c) c\<rbrakk> \<Longrightarrow>
deg_n R S X p = c_max S c"
apply (cut_tac subring, frule subring_Ring)
apply (frule polyn_c_max[of c])
apply (frule pol_SOME_2[of p])
apply (subst deg_n_def, erule conjE)
apply (rule polyn_degree_unique[of "Eps (cf_sol R S X p)" "c"], simp,
assumption)
apply simp
done
lemma (in PolynRg) pol_deg_le_n:"\<lbrakk>p \<in> carrier R; pol_coeff S c;
p = polyn_expr R X (fst c) c\<rbrakk> \<Longrightarrow> deg_n R S X p \<le> (fst c)"
apply (frule pol_deg_eq_c_max[of p c], assumption+,
frule coeff_max_bddTr[of c])
apply simp
done
lemma (in PolynRg) pol_len_gt_deg:"\<lbrakk>p \<in> carrier R; pol_coeff S c;
p = polyn_expr R X (fst c) c; deg R S X p < (an j); j \<le> (fst c)\<rbrakk>
\<Longrightarrow> (snd c) j = \<zero>\<^bsub>S\<^esub>"
apply (case_tac "p = \<zero>\<^bsub>R\<^esub>", simp, drule sym)
apply (simp add:coeff_0_pol_0[THEN sym, of c "fst c"])
apply (simp add:deg_def, simp add:aless_natless)
apply (drule sym, simp)
apply (frule coeff_max_zeroTr[of c])
apply (simp add:pol_deg_eq_c_max)
done
lemma (in PolynRg) pol_diff_deg_less:"\<lbrakk>p \<in> carrier R; pol_coeff S c;
p = polyn_expr R X (fst c) c; pol_coeff S d;
fst c = fst d; (snd c) (fst c) = (snd d) (fst d)\<rbrakk> \<Longrightarrow>
p \<plusminus> (-\<^sub>a (polyn_expr R X (fst d) d)) = \<zero> \<or>
deg_n R S X (p \<plusminus> (-\<^sub>a (polyn_expr R X (fst d) d))) < (fst c)"
apply (cut_tac ring_is_ag,
cut_tac subring, frule subring_Ring)
apply (case_tac "p \<plusminus>\<^bsub>R\<^esub> (-\<^sub>a\<^bsub>R\<^esub> (polyn_expr R X (fst d) d)) = \<zero>\<^bsub>R\<^esub>", simp)
apply simp
apply (simp add:polyn_minus_m_cf[of d "fst d"],
frule m_cf_pol_coeff[of d])
apply (cut_tac polyn_add1[of c "m_cf S d"], simp add:m_cf_len,
thin_tac "polyn_expr R X (fst d) c \<plusminus> polyn_expr R X (fst d) (m_cf S d)
= polyn_expr R X (fst d) (add_cf S c (m_cf S d))")
apply (frule add_cf_pol_coeff[of c "m_cf S d"], assumption+)
apply (cut_tac polyn_mem[of "add_cf S c (m_cf S d)" "fst d"],
frule pol_deg_le_n[of "polyn_expr R X (fst d) (add_cf S c (m_cf S d))"
"add_cf S c (m_cf S d)"], assumption+,
simp add:add_cf_len m_cf_len,
simp add:add_cf_len m_cf_len)
apply (rule noteq_le_less[of "deg_n R S X (polyn_expr R X (fst d)
(add_cf S c (m_cf S d)))" "fst d"], assumption)
apply (rule contrapos_pp, simp+)
apply (cut_tac pol_deg_eq_c_max[of "polyn_expr R X (fst d)
(add_cf S c (m_cf S d))" "add_cf S c (m_cf S d)"],
simp,
thin_tac "deg_n R S X (polyn_expr R X (fst d) (add_cf S c (m_cf S d)))
= fst d")
apply (frule coeff_nonzero_polyn_nonzero[of "add_cf S c (m_cf S d)" "fst d"],
simp add:add_cf_len m_cf_len, simp,
thin_tac "polyn_expr R X (fst d) (add_cf S c (m_cf S d)) \<noteq> \<zero>",
frule coeff_max_nonzeroTr[of "add_cf S c (m_cf S d)"],
simp add:add_cf_len m_cf_len,
thin_tac "\<exists>j\<le>fst d. snd (add_cf S c (m_cf S d)) j \<noteq> \<zero>\<^bsub>S\<^esub>",
thin_tac "pol_coeff S (m_cf S d)",
thin_tac "pol_coeff S (add_cf S c (m_cf S d))",
thin_tac "polyn_expr R X (fst d) (add_cf S c (m_cf S d)) \<in>
carrier R", simp,
thin_tac "c_max S (add_cf S c (m_cf S d)) = fst d")
apply (simp add:add_cf_def m_cf_def,
frule pol_coeff_mem[of d "fst d"], simp,
frule Ring.ring_is_ag[of S],
simp add:aGroup.ag_r_inv1, assumption+,
simp add:add_cf_len m_cf_len, assumption,
simp add:add_cf_len m_cf_len, assumption+)
done
lemma (in PolynRg) pol_pre_lt_deg:"\<lbrakk>p \<in> carrier R; pol_coeff S c;
deg_n R S X p \<le> (fst c); (deg_n R S X p) \<noteq> 0;
p = polyn_expr R X (deg_n R S X p) c \<rbrakk> \<Longrightarrow>
(deg_n R S X (polyn_expr R X ((deg_n R S X p) - Suc 0) c)) < (deg_n R S X p)"
apply (frule polyn_expr_short[of c "deg_n R S X p"], assumption)
apply (cut_tac pol_deg_le_n[of "polyn_expr R X (deg_n R S X p - Suc 0) c"
"(deg_n R S X p - Suc 0, snd c)"], simp)
apply (rule polyn_mem[of c "deg_n R S X p - Suc 0"], assumption+,
arith,
rule pol_coeff_le[of c "deg_n R S X p - Suc 0"], assumption,
arith, simp)
apply (subst polyn_expr_short[of c "deg_n R S X p - Suc 0"],
assumption+, arith, simp)
done
lemma (in PolynRg) pol_deg_n:"\<lbrakk>p \<in> carrier R; pol_coeff S c;
n \<le> fst c; p = polyn_expr R X n c; (snd c) n \<noteq> \<zero>\<^bsub>S\<^esub>\<rbrakk> \<Longrightarrow>
deg_n R S X p = n"
apply (simp add:polyn_expr_short[of c n])
apply (frule pol_coeff_le[of c n], assumption+,
cut_tac pol_deg_eq_c_max[of p "(n, snd c)"],
drule sym, simp, simp add:c_max_def)
apply (rule conjI, rule impI, cut_tac le_refl[of n],
thin_tac "deg_n R S X p =
(if \<forall>x\<le>n. snd c x = \<zero>\<^bsub>S\<^esub> then 0
else n_max {j. j \<le> fst (n, snd c) \<and> snd (n, snd c) j \<noteq> \<zero>\<^bsub>S\<^esub>})",
drule_tac a = n in forall_spec, assumption, simp)
apply (rule impI)
apply (cut_tac n_max[of "{j. j \<le> n \<and> snd c j \<noteq> \<zero>\<^bsub>S\<^esub>}" n], erule conjE,
drule_tac x = n in bspec, simp, simp)
apply (rule subsetI, simp, blast,
drule sym, simp, assumption)
apply simp
done
lemma (in PolynRg) pol_expr_deg:"\<lbrakk>p \<in> carrier R; p \<noteq> \<zero>\<rbrakk>
\<Longrightarrow> \<exists>c. pol_coeff S c \<and> deg_n R S X p \<le> (fst c) \<and>
p = polyn_expr R X (deg_n R S X p) c \<and>
(snd c) (deg_n R S X p) \<noteq> \<zero>\<^bsub>S\<^esub>"
apply (cut_tac subring,
frule subring_Ring)
apply (frule ex_polyn_expr[of p], erule exE, erule conjE)
apply (frule_tac c = c in polyn_c_max)
apply (frule_tac c = c in pol_deg_le_n[of p], assumption+)
apply (frule_tac c1 = c and k1 ="fst c" in coeff_0_pol_0[THEN sym], simp)
apply (subgoal_tac "p = polyn_expr R X (deg_n R S X p) c \<and>
snd c (deg_n R S X p) \<noteq> \<zero>\<^bsub>S\<^esub>", blast)
apply (subst pol_deg_eq_c_max, assumption+)+
apply simp
apply (cut_tac c = c in coeff_max_nonzeroTr, simp+)
done
lemma (in PolynRg) deg_n_pos:"p \<in> carrier R \<Longrightarrow> 0 \<le> deg_n R S X p"
by simp
lemma (in PolynRg) pol_expr_deg1:"\<lbrakk>p \<in> carrier R; d = na (deg R S X p)\<rbrakk> \<Longrightarrow>
\<exists>c. (pol_coeff S c \<and> p = polyn_expr R X d c)"
apply (cut_tac subring, frule subring_Ring)
apply (case_tac "p = \<zero>\<^bsub>R\<^esub>",
simp add:deg_def na_minf,
subgoal_tac "pol_coeff S (0, (\<lambda>j. \<zero>\<^bsub>S\<^esub>))",
subgoal_tac "\<zero> = polyn_expr R X d (0, (\<lambda>j. \<zero>\<^bsub>S\<^esub>))", blast,
cut_tac coeff_0_pol_0[of "(d, \<lambda>j. \<zero>\<^bsub>S\<^esub>)" d], simp+,
simp add:pol_coeff_def,
simp add:Ring.ring_zero)
apply (simp add:deg_def na_an,
frule pol_expr_deg[of p], assumption,
erule exE, (erule conjE)+,
unfold split_paired_all, simp, blast)
done
end
|
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import group_theory.perm.support
import group_theory.order_of_element
import data.finset.fin
import data.int.order.units
/-!
# Sign of a permutation
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
The main definition of this file is `equiv.perm.sign`, associating a `ℤˣ` sign with a
permutation.
This file also contains miscellaneous lemmas about `equiv.perm` and `equiv.swap`, building on top
of those in `data/equiv/basic` and other files in `group_theory/perm/*`.
-/
universes u v
open equiv function fintype finset
open_locale big_operators
variables {α : Type u} {β : Type v}
-- An example on how to determine the order of an element of a finite group.
example : order_of (-1 : ℤˣ) = 2 :=
order_of_eq_prime (int.units_sq _) dec_trivial
namespace equiv.perm
/--
`mod_swap i j` contains permutations up to swapping `i` and `j`.
We use this to partition permutations in `matrix.det_zero_of_row_eq`, such that each partition
sums up to `0`.
-/
def mod_swap [decidable_eq α] (i j : α) : setoid (perm α) :=
⟨λ σ τ, σ = τ ∨ σ = swap i j * τ,
λ σ, or.inl (refl σ),
λ σ τ h, or.cases_on h (λ h, or.inl h.symm) (λ h, or.inr (by rw [h, swap_mul_self_mul])),
λ σ τ υ hστ hτυ, by cases hστ; cases hτυ; try {rw [hστ, hτυ, swap_mul_self_mul]}; simp [hστ, hτυ] ⟩
instance {α : Type*} [fintype α] [decidable_eq α] (i j : α) : decidable_rel (mod_swap i j).r :=
λ σ τ, or.decidable
lemma perm_inv_on_of_perm_on_finset {s : finset α} {f : perm α}
(h : ∀ x ∈ s, f x ∈ s) {y : α} (hy : y ∈ s) : f⁻¹ y ∈ s :=
begin
have h0 : ∀ y ∈ s, ∃ x (hx : x ∈ s), y = (λ i (hi : i ∈ s), f i) x hx :=
finset.surj_on_of_inj_on_of_card_le (λ x hx, (λ i hi, f i) x hx)
(λ a ha, h a ha) (λ a₁ a₂ ha₁ ha₂ heq, (equiv.apply_eq_iff_eq f).mp heq) rfl.ge,
obtain ⟨y2, hy2, heq⟩ := h0 y hy,
convert hy2,
rw heq,
simp only [inv_apply_self]
end
lemma perm_inv_maps_to_of_maps_to (f : perm α) {s : set α} [finite s] (h : set.maps_to f s s) :
set.maps_to (f⁻¹ : _) s s :=
by casesI nonempty_fintype s; exact λ x hx, set.mem_to_finset.mp $
perm_inv_on_of_perm_on_finset
(λ a ha, set.mem_to_finset.mpr (h (set.mem_to_finset.mp ha)))
(set.mem_to_finset.mpr hx)
@[simp] lemma perm_inv_maps_to_iff_maps_to {f : perm α} {s : set α} [finite s] :
set.maps_to (f⁻¹ : _) s s ↔ set.maps_to f s s :=
⟨perm_inv_maps_to_of_maps_to f⁻¹, perm_inv_maps_to_of_maps_to f⟩
lemma perm_inv_on_of_perm_on_finite {f : perm α} {p : α → Prop} [finite {x // p x}]
(h : ∀ x, p x → p (f x)) {x : α} (hx : p x) : p (f⁻¹ x) :=
perm_inv_maps_to_of_maps_to f h hx
/-- If the permutation `f` maps `{x // p x}` into itself, then this returns the permutation
on `{x // p x}` induced by `f`. Note that the `h` hypothesis is weaker than for
`equiv.perm.subtype_perm`. -/
abbreviation subtype_perm_of_fintype (f : perm α) {p : α → Prop} [fintype {x // p x}]
(h : ∀ x, p x → p (f x)) : perm {x // p x} :=
f.subtype_perm (λ x, ⟨h x, λ h₂, f.inv_apply_self x ▸ perm_inv_on_of_perm_on_finite h h₂⟩)
@[simp] lemma subtype_perm_of_fintype_apply (f : perm α) {p : α → Prop} [fintype {x // p x}]
(h : ∀ x, p x → p (f x)) (x : {x // p x}) : subtype_perm_of_fintype f h x = ⟨f x, h x x.2⟩ := rfl
@[simp] lemma subtype_perm_of_fintype_one (p : α → Prop) [fintype {x // p x}]
(h : ∀ x, p x → p ((1 : perm α) x)) : @subtype_perm_of_fintype α 1 p _ h = 1 :=
equiv.ext $ λ ⟨_, _⟩, rfl
lemma perm_maps_to_inl_iff_maps_to_inr {m n : Type*} [finite m] [finite n] (σ : perm (m ⊕ n)) :
set.maps_to σ (set.range sum.inl) (set.range sum.inl) ↔
set.maps_to σ (set.range sum.inr) (set.range sum.inr) :=
begin
casesI nonempty_fintype m,
casesI nonempty_fintype n,
split; id
{ intros h,
classical,
rw ←perm_inv_maps_to_iff_maps_to at h,
intro x,
cases hx : σ x with l r, },
{ rintros ⟨a, rfl⟩,
obtain ⟨y, hy⟩ := h ⟨l, rfl⟩,
rw [←hx, σ.inv_apply_self] at hy,
exact absurd hy sum.inl_ne_inr},
{ rintros ⟨a, ha⟩, exact ⟨r, rfl⟩, },
{ rintros ⟨a, ha⟩, exact ⟨l, rfl⟩, },
{ rintros ⟨a, rfl⟩,
obtain ⟨y, hy⟩ := h ⟨r, rfl⟩,
rw [←hx, σ.inv_apply_self] at hy,
exact absurd hy sum.inr_ne_inl},
end
lemma mem_sum_congr_hom_range_of_perm_maps_to_inl {m n : Type*} [finite m] [finite n]
{σ : perm (m ⊕ n)} (h : set.maps_to σ (set.range sum.inl) (set.range sum.inl)) :
σ ∈ (sum_congr_hom m n).range :=
begin
casesI nonempty_fintype m,
casesI nonempty_fintype n,
classical,
have h1 : ∀ (x : m ⊕ n), (∃ (a : m), sum.inl a = x) → (∃ (a : m), sum.inl a = σ x),
{ rintros x ⟨a, ha⟩, apply h, rw ← ha, exact ⟨a, rfl⟩ },
have h3 : ∀ (x : m ⊕ n), (∃ (b : n), sum.inr b = x) → (∃ (b : n), sum.inr b = σ x),
{ rintros x ⟨b, hb⟩,
apply (perm_maps_to_inl_iff_maps_to_inr σ).mp h,
rw ← hb, exact ⟨b, rfl⟩ },
let σ₁' := subtype_perm_of_fintype σ h1,
let σ₂' := subtype_perm_of_fintype σ h3,
let σ₁ := perm_congr (equiv.of_injective _ sum.inl_injective).symm σ₁',
let σ₂ := perm_congr (equiv.of_injective _ sum.inr_injective).symm σ₂',
rw [monoid_hom.mem_range, prod.exists],
use [σ₁, σ₂],
rw [perm.sum_congr_hom_apply],
ext,
cases x with a b,
{ rw [equiv.sum_congr_apply, sum.map_inl, perm_congr_apply, equiv.symm_symm,
apply_of_injective_symm sum.inl_injective],
erw subtype_perm_apply,
rw [of_injective_apply, subtype.coe_mk, subtype.coe_mk] },
{ rw [equiv.sum_congr_apply, sum.map_inr, perm_congr_apply, equiv.symm_symm,
apply_of_injective_symm sum.inr_injective],
erw subtype_perm_apply,
rw [of_injective_apply, subtype.coe_mk, subtype.coe_mk] }
end
lemma disjoint.order_of {σ τ : perm α} (hστ : disjoint σ τ) :
order_of (σ * τ) = nat.lcm (order_of σ) (order_of τ) :=
begin
have h : ∀ n : ℕ, (σ * τ) ^ n = 1 ↔ σ ^ n = 1 ∧ τ ^ n = 1 :=
λ n, by rw [hστ.commute.mul_pow, disjoint.mul_eq_one_iff (hστ.pow_disjoint_pow n n)],
exact nat.dvd_antisymm hστ.commute.order_of_mul_dvd_lcm (nat.lcm_dvd
(order_of_dvd_of_pow_eq_one ((h (order_of (σ * τ))).mp (pow_order_of_eq_one (σ * τ))).1)
(order_of_dvd_of_pow_eq_one ((h (order_of (σ * τ))).mp (pow_order_of_eq_one (σ * τ))).2)),
end
lemma disjoint.extend_domain {α : Type*} {p : β → Prop} [decidable_pred p]
(f : α ≃ subtype p) {σ τ : perm α} (h : disjoint σ τ) :
disjoint (σ.extend_domain f) (τ.extend_domain f) :=
begin
intro b,
by_cases pb : p b,
{ refine (h (f.symm ⟨b, pb⟩)).imp _ _;
{ intro h,
rw [extend_domain_apply_subtype _ _ pb, h, apply_symm_apply, subtype.coe_mk] } },
{ left,
rw [extend_domain_apply_not_subtype _ _ pb] }
end
variable [decidable_eq α]
section fintype
variable [fintype α]
lemma support_pow_coprime {σ : perm α} {n : ℕ} (h : nat.coprime n (order_of σ)) :
(σ ^ n).support = σ.support :=
begin
obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime h,
exact le_antisymm (support_pow_le σ n) (le_trans (ge_of_eq (congr_arg support hm))
(support_pow_le (σ ^ n) m)),
end
end fintype
/-- Given a list `l : list α` and a permutation `f : perm α` such that the nonfixed points of `f`
are in `l`, recursively factors `f` as a product of transpositions. -/
def swap_factors_aux : Π (l : list α) (f : perm α), (∀ {x}, f x ≠ x → x ∈ l) →
{l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g}
| [] := λ f h, ⟨[], equiv.ext $ λ x, by { rw [list.prod_nil],
exact (not_not.1 (mt h (list.not_mem_nil _))).symm }, by simp⟩
| (x :: l) := λ f h,
if hfx : x = f x
then swap_factors_aux l f
(λ y hy, list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h hy))
else let m := swap_factors_aux l (swap x (f x) * f)
(λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy,
list.mem_of_ne_of_mem this.2 (h this.1)) in
⟨swap x (f x) :: m.1,
by rw [list.prod_cons, m.2.1, ← mul_assoc,
mul_def (swap x (f x)), swap_swap, ← one_def, one_mul],
λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ h, ⟨x, f x, hfx, h⟩) (m.2.2 _)⟩
/-- `swap_factors` represents a permutation as a product of a list of transpositions.
The representation is non unique and depends on the linear order structure.
For types without linear order `trunc_swap_factors` can be used. -/
def swap_factors [fintype α] [linear_order α] (f : perm α) :
{l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} :=
swap_factors_aux ((@univ α _).sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _))
/-- This computably represents the fact that any permutation can be represented as the product of
a list of transpositions. -/
def trunc_swap_factors [fintype α] (f : perm α) :
trunc {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} :=
quotient.rec_on_subsingleton (@univ α _).1
(λ l h, trunc.mk (swap_factors_aux l f h))
(show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _)
/-- An induction principle for permutations. If `P` holds for the identity permutation, and
is preserved under composition with a non-trivial swap, then `P` holds for all permutations. -/
@[elab_as_eliminator] lemma swap_induction_on [finite α] {P : perm α → Prop} (f : perm α) :
P 1 → (∀ f x y, x ≠ y → P f → P (swap x y * f)) → P f :=
begin
casesI nonempty_fintype α,
cases (trunc_swap_factors f).out with l hl,
induction l with g l ih generalizing f,
{ simp only [hl.left.symm, list.prod_nil, forall_true_iff] {contextual := tt} },
{ assume h1 hmul_swap,
rcases hl.2 g (by simp) with ⟨x, y, hxy⟩,
rw [← hl.1, list.prod_cons, hxy.2],
exact hmul_swap _ _ _ hxy.1
(ih _ ⟨rfl, λ v hv, hl.2 _ (list.mem_cons_of_mem _ hv)⟩ h1 hmul_swap) }
end
lemma closure_is_swap [finite α] : subgroup.closure {σ : perm α | is_swap σ} = ⊤ :=
begin
casesI nonempty_fintype α,
refine eq_top_iff.mpr (λ x hx, _),
obtain ⟨h1, h2⟩ := subtype.mem (trunc_swap_factors x).out,
rw ← h1,
exact subgroup.list_prod_mem _ (λ y hy, subgroup.subset_closure (h2 y hy)),
end
/-- Like `swap_induction_on`, but with the composition on the right of `f`.
An induction principle for permutations. If `P` holds for the identity permutation, and
is preserved under composition with a non-trivial swap, then `P` holds for all permutations. -/
@[elab_as_eliminator] lemma swap_induction_on' [finite α] {P : perm α → Prop} (f : perm α) :
P 1 → (∀ f x y, x ≠ y → P f → P (f * swap x y)) → P f :=
λ h1 IH, inv_inv f ▸ swap_induction_on f⁻¹ h1 (λ f, IH f⁻¹)
lemma is_conj_swap {w x y z : α} (hwx : w ≠ x) (hyz : y ≠ z) : is_conj (swap w x) (swap y z) :=
is_conj_iff.2 (have h : ∀ {y z : α}, y ≠ z → w ≠ z →
(swap w y * swap x z) * swap w x * (swap w y * swap x z)⁻¹ = swap y z :=
λ y z hyz hwz, by rw [mul_inv_rev, swap_inv, swap_inv, mul_assoc (swap w y),
mul_assoc (swap w y), ← mul_assoc _ (swap x z), swap_mul_swap_mul_swap hwx hwz,
← mul_assoc, swap_mul_swap_mul_swap hwz.symm hyz.symm],
if hwz : w = z
then have hwy : w ≠ y, by cc,
⟨swap w z * swap x y, by rw [swap_comm y z, h hyz.symm hwy]⟩
else ⟨swap w y * swap x z, h hyz hwz⟩)
/-- set of all pairs (⟨a, b⟩ : Σ a : fin n, fin n) such that b < a -/
def fin_pairs_lt (n : ℕ) : finset (Σ a : fin n, fin n) :=
(univ : finset (fin n)).sigma (λ a, (range a).attach_fin
(λ m hm, (mem_range.1 hm).trans a.2))
lemma mem_fin_pairs_lt {n : ℕ} {a : Σ a : fin n, fin n} :
a ∈ fin_pairs_lt n ↔ a.2 < a.1 :=
by simp only [fin_pairs_lt, fin.lt_iff_coe_lt_coe, true_and, mem_attach_fin, mem_range, mem_univ,
mem_sigma]
/-- `sign_aux σ` is the sign of a permutation on `fin n`, defined as the parity of the number of
pairs `(x₁, x₂)` such that `x₂ < x₁` but `σ x₁ ≤ σ x₂` -/
def sign_aux {n : ℕ} (a : perm (fin n)) : ℤˣ :=
∏ x in fin_pairs_lt n, if a x.1 ≤ a x.2 then -1 else 1
@[simp] lemma sign_aux_one (n : ℕ) : sign_aux (1 : perm (fin n)) = 1 :=
begin
unfold sign_aux,
conv { to_rhs, rw ← @finset.prod_const_one ℤˣ _
(fin_pairs_lt n) },
exact finset.prod_congr rfl (λ a ha, if_neg (mem_fin_pairs_lt.1 ha).not_le)
end
/-- `sign_bij_aux f ⟨a, b⟩` returns the pair consisting of `f a` and `f b` in decreasing order. -/
def sign_bij_aux {n : ℕ} (f : perm (fin n)) (a : Σ a : fin n, fin n) :
Σ a : fin n, fin n :=
if hxa : f a.2 < f a.1 then ⟨f a.1, f a.2⟩ else ⟨f a.2, f a.1⟩
lemma sign_bij_aux_inj {n : ℕ} {f : perm (fin n)} : ∀ a b : Σ a : fin n, fin n,
a ∈ fin_pairs_lt n → b ∈ fin_pairs_lt n →
sign_bij_aux f a = sign_bij_aux f b → a = b :=
λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, begin
unfold sign_bij_aux at h,
rw mem_fin_pairs_lt at *,
have : ¬b₁ < b₂ := hb.le.not_lt,
split_ifs at h;
simp only [*, (equiv.injective f).eq_iff, eq_self_iff_true, and_self, heq_iff_eq] at *,
end
lemma sign_bij_aux_surj {n : ℕ} {f : perm (fin n)} : ∀ a ∈ fin_pairs_lt n,
∃ b ∈ fin_pairs_lt n, a = sign_bij_aux f b :=
λ ⟨a₁, a₂⟩ ha,
if hxa : f⁻¹ a₂ < f⁻¹ a₁
then ⟨⟨f⁻¹ a₁, f⁻¹ a₂⟩, mem_fin_pairs_lt.2 hxa,
by { dsimp [sign_bij_aux],
rw [apply_inv_self, apply_inv_self, if_pos (mem_fin_pairs_lt.1 ha)] }⟩
else ⟨⟨f⁻¹ a₂, f⁻¹ a₁⟩, mem_fin_pairs_lt.2 $ (le_of_not_gt hxa).lt_of_ne $ λ h,
by simpa [mem_fin_pairs_lt, (f⁻¹).injective h, lt_irrefl] using ha,
by { dsimp [sign_bij_aux],
rw [apply_inv_self, apply_inv_self, if_neg (mem_fin_pairs_lt.1 ha).le.not_lt] }⟩
lemma sign_bij_aux_mem {n : ℕ} {f : perm (fin n)} : ∀ a : Σ a : fin n, fin n,
a ∈ fin_pairs_lt n → sign_bij_aux f a ∈ fin_pairs_lt n :=
λ ⟨a₁, a₂⟩ ha, begin
unfold sign_bij_aux,
split_ifs with h,
{ exact mem_fin_pairs_lt.2 h },
{ exact mem_fin_pairs_lt.2
((le_of_not_gt h).lt_of_ne (λ h, (mem_fin_pairs_lt.1 ha).ne (f.injective h.symm))) }
end
@[simp] lemma sign_aux_inv {n : ℕ} (f : perm (fin n)) : sign_aux f⁻¹ = sign_aux f :=
prod_bij (λ a ha, sign_bij_aux f⁻¹ a)
sign_bij_aux_mem
(λ ⟨a, b⟩ hab, if h : f⁻¹ b < f⁻¹ a
then by rw [sign_bij_aux, dif_pos h, if_neg h.not_le, apply_inv_self,
apply_inv_self, if_neg (mem_fin_pairs_lt.1 hab).not_le]
else by rw [sign_bij_aux, if_pos (le_of_not_gt h), dif_neg h, apply_inv_self,
apply_inv_self, if_pos (mem_fin_pairs_lt.1 hab).le])
sign_bij_aux_inj
sign_bij_aux_surj
lemma sign_aux_mul {n : ℕ} (f g : perm (fin n)) :
sign_aux (f * g) = sign_aux f * sign_aux g :=
begin
rw ← sign_aux_inv g,
unfold sign_aux,
rw ← prod_mul_distrib,
refine prod_bij (λ a ha, sign_bij_aux g a) sign_bij_aux_mem _ sign_bij_aux_inj sign_bij_aux_surj,
rintros ⟨a, b⟩ hab,
rw [sign_bij_aux, mul_apply, mul_apply],
rw mem_fin_pairs_lt at hab,
by_cases h : g b < g a,
{ rw dif_pos h,
simp only [not_le_of_gt hab, mul_one, perm.inv_apply_self, if_false] },
{ rw [dif_neg h, inv_apply_self, inv_apply_self, if_pos hab.le],
by_cases h₁ : f (g b) ≤ f (g a),
{ have : f (g b) ≠ f (g a),
{ rw [ne.def, f.injective.eq_iff, g.injective.eq_iff],
exact ne_of_lt hab },
rw [if_pos h₁, if_neg (h₁.lt_of_ne this).not_le],
refl },
{ rw [if_neg h₁, if_pos (lt_of_not_ge h₁).le],
refl } }
end
private lemma sign_aux_swap_zero_one' (n : ℕ) :
sign_aux (swap (0 : fin (n + 2)) 1) = -1 :=
show _ = ∏ x : Σ a : fin (n + 2), fin (n + 2) in {(⟨1, 0⟩ : Σ a : fin (n + 2), fin (n + 2))},
if (equiv.swap 0 1) x.1 ≤ swap 0 1 x.2 then (-1 : ℤˣ) else 1,
begin
refine eq.symm (prod_subset (λ ⟨x₁, x₂⟩,
by simp [mem_fin_pairs_lt, fin.one_pos] {contextual := tt}) (λ a ha₁ ha₂, _)),
rcases a with ⟨a₁, a₂⟩,
replace ha₁ : a₂ < a₁ := mem_fin_pairs_lt.1 ha₁,
dsimp only,
rcases a₁.zero_le.eq_or_lt with rfl|H,
{ exact absurd a₂.zero_le ha₁.not_le },
rcases a₂.zero_le.eq_or_lt with rfl|H',
{ simp only [and_true, eq_self_iff_true, heq_iff_eq, mem_singleton] at ha₂,
have : 1 < a₁ := lt_of_le_of_ne (nat.succ_le_of_lt ha₁) (ne.symm ha₂),
have h01 : equiv.swap (0 : fin (n + 2)) 1 0 = 1, by simp, -- TODO : fix properly
norm_num [swap_apply_of_ne_of_ne (ne_of_gt H) ha₂, this.not_le, h01] },
{ have le : 1 ≤ a₂ := nat.succ_le_of_lt H',
have lt : 1 < a₁ := le.trans_lt ha₁,
have h01 : equiv.swap (0 : fin (n + 2)) 1 1 = 0, by simp, -- TODO
rcases le.eq_or_lt with rfl|lt',
{ norm_num [swap_apply_of_ne_of_ne H.ne' lt.ne', H.not_le, h01] },
{ norm_num [swap_apply_of_ne_of_ne (ne_of_gt H) (ne_of_gt lt),
swap_apply_of_ne_of_ne (ne_of_gt H') (ne_of_gt lt'), ha₁.not_le] } }
end
private lemma sign_aux_swap_zero_one {n : ℕ} (hn : 2 ≤ n) :
sign_aux (swap (⟨0, lt_of_lt_of_le dec_trivial hn⟩ : fin n)
⟨1, lt_of_lt_of_le dec_trivial hn⟩) = -1 :=
begin
rcases n with _|_|n,
{ norm_num at hn },
{ norm_num at hn },
{ exact sign_aux_swap_zero_one' n }
end
lemma sign_aux_swap : ∀ {n : ℕ} {x y : fin n} (hxy : x ≠ y),
sign_aux (swap x y) = -1
| 0 := dec_trivial
| 1 := dec_trivial
| (n+2) := λ x y hxy,
have h2n : 2 ≤ n + 2 := dec_trivial,
by { rw [← is_conj_iff_eq, ← sign_aux_swap_zero_one h2n],
exact (monoid_hom.mk' sign_aux sign_aux_mul).map_is_conj (is_conj_swap hxy dec_trivial) }
/-- When the list `l : list α` contains all nonfixed points of the permutation `f : perm α`,
`sign_aux2 l f` recursively calculates the sign of `f`. -/
def sign_aux2 : list α → perm α → ℤˣ
| [] f := 1
| (x::l) f := if x = f x then sign_aux2 l f else -sign_aux2 l (swap x (f x) * f)
lemma sign_aux_eq_sign_aux2 {n : ℕ} : ∀ (l : list α) (f : perm α) (e : α ≃ fin n)
(h : ∀ x, f x ≠ x → x ∈ l), sign_aux ((e.symm.trans f).trans e) = sign_aux2 l f
| [] f e h := have f = 1, from equiv.ext $
λ y, not_not.1 (mt (h y) (list.not_mem_nil _)),
by rw [this, one_def, equiv.trans_refl, equiv.symm_trans_self, ← one_def,
sign_aux_one, sign_aux2]
| (x::l) f e h := begin
rw sign_aux2,
by_cases hfx : x = f x,
{ rw if_pos hfx,
exact sign_aux_eq_sign_aux2 l f _ (λ y (hy : f y ≠ y), list.mem_of_ne_of_mem
(λ h : y = x, by simpa [h, hfx.symm] using hy) (h y hy) ) },
{ have hy : ∀ y : α, (swap x (f x) * f) y ≠ y → y ∈ l, from λ y hy,
have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy,
list.mem_of_ne_of_mem this.2 (h _ this.1),
have : (e.symm.trans (swap x (f x) * f)).trans e =
(swap (e x) (e (f x))) * (e.symm.trans f).trans e,
by ext; simp [← equiv.symm_trans_swap_trans, mul_def],
have hefx : e x ≠ e (f x), from mt e.injective.eq_iff.1 hfx,
rw [if_neg hfx, ← sign_aux_eq_sign_aux2 _ _ e hy, this, sign_aux_mul, sign_aux_swap hefx],
simp only [neg_neg, one_mul, neg_mul]}
end
/-- When the multiset `s : multiset α` contains all nonfixed points of the permutation `f : perm α`,
`sign_aux2 f _` recursively calculates the sign of `f`. -/
def sign_aux3 [fintype α] (f : perm α) {s : multiset α} : (∀ x, x ∈ s) → ℤˣ :=
quotient.hrec_on s (λ l h, sign_aux2 l f)
(trunc.induction_on (fintype.trunc_equiv_fin α)
(λ e l₁ l₂ h, function.hfunext
(show (∀ x, x ∈ l₁) = ∀ x, x ∈ l₂, by simp only [h.mem_iff])
(λ h₁ h₂ _, by rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₁ _),
← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₂ _)])))
lemma sign_aux3_mul_and_swap [fintype α] (f g : perm α) (s : multiset α) (hs : ∀ x, x ∈ s) :
sign_aux3 (f * g) hs = sign_aux3 f hs * sign_aux3 g hs ∧ ∀ x y, x ≠ y →
sign_aux3 (swap x y) hs = -1 :=
let ⟨l, hl⟩ := quotient.exists_rep s in
let e := equiv_fin α in
begin
clear _let_match,
subst hl,
show sign_aux2 l (f * g) = sign_aux2 l f * sign_aux2 l g ∧
∀ x y, x ≠ y → sign_aux2 l (swap x y) = -1,
have hfg : (e.symm.trans (f * g)).trans e = (e.symm.trans f).trans e * (e.symm.trans g).trans e,
from equiv.ext (λ h, by simp [mul_apply]),
split,
{ rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _),
← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), hfg, sign_aux_mul] },
{ assume x y hxy,
have hexy : e x ≠ e y, from mt e.injective.eq_iff.1 hxy,
rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), symm_trans_swap_trans, sign_aux_swap hexy] }
end
/-- `sign` of a permutation returns the signature or parity of a permutation, `1` for even
permutations, `-1` for odd permutations. It is the unique surjective group homomorphism from
`perm α` to the group with two elements.-/
def sign [fintype α] : perm α →* ℤˣ := monoid_hom.mk'
(λ f, sign_aux3 f mem_univ) (λ f g, (sign_aux3_mul_and_swap f g _ mem_univ).1)
section sign
variable [fintype α]
@[simp] lemma sign_mul (f g : perm α) : sign (f * g) = sign f * sign g :=
monoid_hom.map_mul sign f g
@[simp] lemma sign_trans (f g : perm α) : sign (f.trans g) = sign g * sign f :=
by rw [←mul_def, sign_mul]
@[simp] lemma sign_one : (sign (1 : perm α)) = 1 :=
monoid_hom.map_one sign
@[simp] lemma sign_refl : sign (equiv.refl α) = 1 :=
monoid_hom.map_one sign
@[simp] lemma sign_inv (f : perm α) : sign f⁻¹ = sign f :=
by rw [monoid_hom.map_inv sign f, int.units_inv_eq_self]
@[simp] lemma sign_symm (e : perm α) : sign e.symm = sign e :=
sign_inv e
lemma sign_swap {x y : α} (h : x ≠ y) : sign (swap x y) = -1 :=
(sign_aux3_mul_and_swap 1 1 _ mem_univ).2 x y h
@[simp] lemma sign_swap' {x y : α} :
(swap x y).sign = if x = y then 1 else -1 :=
if H : x = y then by simp [H, swap_self] else
by simp [sign_swap H, H]
lemma is_swap.sign_eq {f : perm α} (h : f.is_swap) : sign f = -1 :=
let ⟨x, y, hxy⟩ := h in hxy.2.symm ▸ sign_swap hxy.1
@[simp] lemma sign_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) :
sign ((e.symm.trans f).trans e) = sign f :=
sign_aux3_symm_trans_trans f e mem_univ mem_univ
@[simp] lemma sign_trans_trans_symm [decidable_eq β] [fintype β] (f : perm β) (e : α ≃ β) :
sign ((e.trans f).trans e.symm) = sign f :=
sign_symm_trans_trans f e.symm
lemma sign_prod_list_swap {l : list (perm α)}
(hl : ∀ g ∈ l, is_swap g) : sign l.prod = (-1) ^ l.length :=
have h₁ : l.map sign = list.replicate l.length (-1) :=
list.eq_replicate.2 ⟨by simp, λ u hu,
let ⟨g, hg⟩ := list.mem_map.1 hu in
hg.2 ▸ (hl _ hg.1).sign_eq⟩,
by rw [← list.prod_replicate, ← h₁, list.prod_hom _ (@sign α _ _)]
variable (α)
lemma sign_surjective [nontrivial α] : function.surjective (sign : perm α → ℤˣ) :=
λ a, (int.units_eq_one_or a).elim
(λ h, ⟨1, by simp [h]⟩)
(λ h, let ⟨x, y, hxy⟩ := exists_pair_ne α in
⟨swap x y, by rw [sign_swap hxy, h]⟩ )
variable {α}
lemma eq_sign_of_surjective_hom {s : perm α →* ℤˣ} (hs : surjective s) : s = sign :=
have ∀ {f}, is_swap f → s f = -1 :=
λ f ⟨x, y, hxy, hxy'⟩, hxy'.symm ▸ by_contradiction (λ h,
have ∀ f, is_swap f → s f = 1 := λ f ⟨a, b, hab, hab'⟩,
by { rw [← is_conj_iff_eq, ← or.resolve_right (int.units_eq_one_or _) h, hab'],
exact s.map_is_conj (is_conj_swap hab hxy) },
let ⟨g, hg⟩ := hs (-1) in
let ⟨l, hl⟩ := (trunc_swap_factors g).out in
have ∀ a ∈ l.map s, a = (1 : ℤˣ) := λ a ha,
let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this _ (hl.2 _ hg.1),
have s l.prod = 1,
by rw [← l.prod_hom s, list.eq_replicate_length.2 this, list.prod_replicate, one_pow],
by { rw [hl.1, hg] at this,
exact absurd this dec_trivial }),
monoid_hom.ext $ λ f,
let ⟨l, hl₁, hl₂⟩ := (trunc_swap_factors f).out in
have hsl : ∀ a ∈ l.map s, a = (-1 : ℤˣ) := λ a ha,
let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this (hl₂ _ hg.1),
by rw [← hl₁, ← l.prod_hom s, list.eq_replicate_length.2 hsl, list.length_map,
list.prod_replicate, sign_prod_list_swap hl₂]
lemma sign_subtype_perm (f : perm α) {p : α → Prop} [decidable_pred p]
(h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : sign (subtype_perm f h₁) = sign f :=
let l := (trunc_swap_factors (subtype_perm f h₁)).out in
have hl' : ∀ g' ∈ l.1.map of_subtype, is_swap g' :=
λ g' hg',
let ⟨g, hg⟩ := list.mem_map.1 hg' in
hg.2 ▸ (l.2.2 _ hg.1).of_subtype_is_swap,
have hl'₂ : (l.1.map of_subtype).prod = f,
by rw [l.1.prod_hom of_subtype, l.2.1, of_subtype_subtype_perm _ h₂],
by { conv { congr, rw ← l.2.1, skip, rw ← hl'₂ },
rw [sign_prod_list_swap l.2.2, sign_prod_list_swap hl', list.length_map] }
lemma sign_eq_sign_of_equiv [decidable_eq β] [fintype β] (f : perm α) (g : perm β)
(e : α ≃ β) (h : ∀ x, e (f x) = g (e x)) : sign f = sign g :=
have hg : g = (e.symm.trans f).trans e, from equiv.ext $ by simp [h],
by rw [hg, sign_symm_trans_trans]
lemma sign_bij [decidable_eq β] [fintype β]
{f : perm α} {g : perm β} (i : Π x : α, f x ≠ x → β)
(h : ∀ x hx hx', i (f x) hx' = g (i x hx))
(hi : ∀ x₁ x₂ hx₁ hx₂, i x₁ hx₁ = i x₂ hx₂ → x₁ = x₂)
(hg : ∀ y, g y ≠ y → ∃ x hx, i x hx = y) :
sign f = sign g :=
calc sign f = sign (subtype_perm f $ by simp : perm {x // f x ≠ x}) :
(sign_subtype_perm _ _ (λ _, id)).symm
... = sign (subtype_perm g $ by simp : perm {x // g x ≠ x}) :
sign_eq_sign_of_equiv _ _
(equiv.of_bijective (λ x : {x // f x ≠ x},
(⟨i x.1 x.2, have f (f x) ≠ f x, from mt (λ h, f.injective h) x.2,
by { rw [← h _ x.2 this], exact mt (hi _ _ this x.2) x.2 }⟩ : {y // g y ≠ y}))
⟨λ ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq (hi _ _ _ _ (subtype.mk.inj h)),
λ ⟨y, hy⟩, let ⟨x, hfx, hx⟩ := hg y hy in ⟨⟨x, hfx⟩, subtype.eq hx⟩⟩)
(λ ⟨x, _⟩, subtype.eq (h x _ _))
... = sign g : sign_subtype_perm _ _ (λ _, id)
/-- If we apply `prod_extend_right a (σ a)` for all `a : α` in turn,
we get `prod_congr_right σ`. -/
lemma prod_prod_extend_right {α : Type*} [decidable_eq α] (σ : α → perm β)
{l : list α} (hl : l.nodup) (mem_l : ∀ a, a ∈ l) :
(l.map (λ a, prod_extend_right a (σ a))).prod = prod_congr_right σ :=
begin
ext ⟨a, b⟩ : 1,
-- We'll use induction on the list of elements,
-- but we have to keep track of whether we already passed `a` in the list.
suffices : (a ∈ l ∧ (l.map (λ a, prod_extend_right a (σ a))).prod (a, b) = (a, σ a b)) ∨
(a ∉ l ∧ (l.map (λ a, prod_extend_right a (σ a))).prod (a, b) = (a, b)),
{ obtain ⟨_, prod_eq⟩ := or.resolve_right this (not_and.mpr (λ h _, h (mem_l a))),
rw [prod_eq, prod_congr_right_apply] },
clear mem_l,
induction l with a' l ih,
{ refine or.inr ⟨list.not_mem_nil _, _⟩,
rw [list.map_nil, list.prod_nil, one_apply] },
rw [list.map_cons, list.prod_cons, mul_apply],
rcases ih (list.nodup_cons.mp hl).2 with ⟨mem_l, prod_eq⟩ | ⟨not_mem_l, prod_eq⟩; rw prod_eq,
{ refine or.inl ⟨list.mem_cons_of_mem _ mem_l, _⟩,
rw prod_extend_right_apply_ne _ (λ (h : a = a'), (list.nodup_cons.mp hl).1 (h ▸ mem_l)) },
by_cases ha' : a = a',
{ rw ← ha' at *,
refine or.inl ⟨l.mem_cons_self a, _⟩,
rw prod_extend_right_apply_eq },
{ refine or.inr ⟨λ h, not_or ha' not_mem_l ((list.mem_cons_iff _ _ _).mp h), _⟩,
rw prod_extend_right_apply_ne _ ha' },
end
section congr
variables [decidable_eq β] [fintype β]
@[simp] lemma sign_prod_extend_right (a : α) (σ : perm β) :
(prod_extend_right a σ).sign = σ.sign :=
sign_bij (λ (ab : α × β) _, ab.snd)
(λ ⟨a', b⟩ hab hab', by simp [eq_of_prod_extend_right_ne hab])
(λ ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ hab₁ hab₂ h,
by simpa [eq_of_prod_extend_right_ne hab₁, eq_of_prod_extend_right_ne hab₂] using h)
(λ y hy, ⟨(a, y), by simpa, by simp⟩)
lemma sign_prod_congr_right (σ : α → perm β) :
sign (prod_congr_right σ) = ∏ k, (σ k).sign :=
begin
obtain ⟨l, hl, mem_l⟩ := finite.exists_univ_list α,
have l_to_finset : l.to_finset = finset.univ,
{ apply eq_top_iff.mpr,
intros b _,
exact list.mem_to_finset.mpr (mem_l b) },
rw [← prod_prod_extend_right σ hl mem_l, sign.map_list_prod,
list.map_map, ← l_to_finset, list.prod_to_finset _ hl],
simp_rw ← λ a, sign_prod_extend_right a (σ a)
end
lemma sign_prod_congr_left (σ : α → perm β) :
sign (prod_congr_left σ) = ∏ k, (σ k).sign :=
begin
refine (sign_eq_sign_of_equiv _ _ (prod_comm β α) _).trans (sign_prod_congr_right σ),
rintro ⟨b, α⟩,
refl
end
@[simp] lemma sign_perm_congr (e : α ≃ β) (p : perm α) :
(e.perm_congr p).sign = p.sign :=
sign_eq_sign_of_equiv _ _ e.symm (by simp)
@[simp] lemma sign_sum_congr (σa : perm α) (σb : perm β) :
(sum_congr σa σb).sign = σa.sign * σb.sign :=
begin
suffices : (sum_congr σa (1 : perm β)).sign = σa.sign ∧
(sum_congr (1 : perm α) σb).sign = σb.sign,
{ rw [←this.1, ←this.2, ←sign_mul, sum_congr_mul, one_mul, mul_one], },
split,
{ apply σa.swap_induction_on _ (λ σa' a₁ a₂ ha ih, _),
{ simp },
{ rw [←one_mul (1 : perm β), ←sum_congr_mul, sign_mul, sign_mul, ih, sum_congr_swap_one,
sign_swap ha, sign_swap (sum.inl_injective.ne_iff.mpr ha)], }, },
{ apply σb.swap_induction_on _ (λ σb' b₁ b₂ hb ih, _),
{ simp },
{ rw [←one_mul (1 : perm α), ←sum_congr_mul, sign_mul, sign_mul, ih, sum_congr_one_swap,
sign_swap hb, sign_swap (sum.inr_injective.ne_iff.mpr hb)], }, }
end
@[simp] lemma sign_subtype_congr {p : α → Prop} [decidable_pred p]
(ep : perm {a // p a}) (en : perm {a // ¬ p a}) :
(ep.subtype_congr en).sign = ep.sign * en.sign :=
by simp [subtype_congr]
@[simp] lemma sign_extend_domain (e : perm α)
{p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) :
equiv.perm.sign (e.extend_domain f) = equiv.perm.sign e :=
by simp only [equiv.perm.extend_domain, sign_subtype_congr, sign_perm_congr, sign_refl, mul_one]
@[simp] lemma sign_of_subtype {p : α → Prop} [decidable_pred p]
(f : equiv.perm (subtype p)) : equiv.perm.sign (f.of_subtype) = equiv.perm.sign f :=
sign_extend_domain f (equiv.refl (subtype p))
end congr
end sign
end equiv.perm
|
function margLogPr = calcLogMargPrObsSeqFAST( LL, Eta )
% calcLogMargPrObsSeqFAST
% Provides fast calculation of marginal likelihood
% for a particular sequence of data, given HMM parameters in the form
% soft evidence LL, where LL(kk,tt) = p( X{ii}(tt) | theta(kk) )
% transition weights Pz, which may be non-normalized
% Massages input data and then calls a super-efficient MEX function
% "FilterFwdC" to perform dynamic programming.
%INPUT
% LL := KiixTii matrix of log likelihoods soft evidence
% Pz := KiixKii matrix of transition weights (non-normalized)
%OUTPUT
% margLogPr := scalar value of log( X_ii | F_ii, theta, Eta_ii )
K = size(Eta,2);
if K == 0
margLogPr = -Inf;
return;
end
Pi = bsxfun( @rdivide, Eta, sum(Eta,2) );
% Need to turn log_lik into lik. We know lik = exp( log_lik )
% For numerical stability, we find M = max( log_lik )
% we compute L = exp( log_lik - M )
% and we thus have lik up to multiplicative constant
% since lik \propto L = exp( log_lik ) / exp( M )
% We find a unique "normalizer" M_t for each time step
% normC = 1 x T
normC = max( LL,[],1);
if K == 1
margLogPr = sum(normC );
return;
end
Lik = exp( bsxfun( @minus, LL, normC ) );
[~,margLogPr] = FilterFwdC( Pi, Lik, 1/K*ones(1,K) );
margLogPr = margLogPr + sum( normC );
end % main function
|
function fx1 = p01_fx1 ( x )
%*****************************************************************************80
%
%% P01_FX1 evaluates the derivative of the function for problem 1.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 07 May 2011
%
% Author:
%
% John Burkardt
%
% Parameters:
%
% Input, real X, the abscissa.
%
% Output, real FX1, the first derivative of the function at X.
%
fx1 = cos ( x ) - 0.5;
return
end
|
(** * Piggy Bank Contract *)
(** Implementation of a piggy bank smart contract.
The contract is based on the Concordium example.
https://developer.concordium.software/en/mainnet/smart-contracts/tutorials/piggy-bank/writing.html#piggy-bank-writing
*)
From ConCert.Utils Require Import RecordUpdate.
From ConCert.Execution Require Import Blockchain.
From ConCert.Execution Require Import ContractCommon.
From ConCert.Execution Require Import Monad.
From ConCert.Execution Require Import ResultMonad.
From ConCert.Execution Require Import Serializable.
From Coq Require Import List. Import ListNotations.
From Coq Require Import ZArith.
(** * Types *)
Section PiggyBankTypes.
Local Set Nonrecursive Elimination Schemes.
Local Set Primitive Projections.
Context `{BaseTypes : ChainBase}.
Inductive PiggyState :=
| Intact
| Smashed.
Inductive Msg :=
| Insert
| Smash.
Record State :=
build_state {
balance : Amount;
owner : Address;
piggyState : PiggyState
}.
Definition Setup : Type := unit.
Definition Error : Type := N.
Definition Result : Type := result (State * list ActionBody) Error.
(* begin hide *)
MetaCoq Run (make_setters State).
Section Serialization.
Global Instance piggyState_serializable : Serializable PiggyState :=
Derive Serializable PiggyState_rect<Intact, Smashed>.
Global Instance state_serializable : Serializable State :=
Derive Serializable State_rect<build_state>.
Global Instance msg_serializable : Serializable Msg :=
Derive Serializable Msg_rect<Insert, Smash>.
End Serialization.
(* end hide *)
End PiggyBankTypes.
(** * Error codes *)
Section PiggyBankErrors.
Open Scope N_scope.
Definition error_no_msg : Error := 1.
Definition error_not_owner : Error := 2.
Definition error_already_smashed : Error := 3.
Definition error_amount_not_positive : Error := 4.
End PiggyBankErrors.
(** * Implementation *)
Section PiggyBankImpl.
Context `{BaseTypes : ChainBase}.
Open Scope Z.
Definition is_smashed (state : State) : bool :=
match state.(piggyState) with
| Intact => false
| Smashed => true
end.
Definition insert (state : State) (ctx : ContractCallContext) : Result :=
let amount := ctx.(ctx_amount) in
do _ <- throwIf (amount <=? 0) error_amount_not_positive;
do _ <- throwIf (is_smashed state) error_already_smashed;
let state := state<| balance ::= Z.add amount |> in
Ok (state, []).
Definition smash (state : State) (ctx : ContractCallContext) : Result :=
let owner := state.(owner) in
do _ <- throwIf (is_smashed state) error_already_smashed;
do _ <- throwIf (address_neqb ctx.(ctx_from) owner) error_not_owner;
let state := state<| balance := 0 |> in
let acts := [act_transfer owner state.(balance)] in
Ok (state, acts).
Definition receive (chain : Chain)
(ctx : ContractCallContext)
(state : State)
(msg : option Msg)
: Result :=
match msg with
| Some Insert => insert state ctx
| Some Smash => smash state ctx
| None => Err error_no_msg
end.
Definition init (chain : Chain)
(ctx : ContractCallContext)
(_ : Setup)
: result State Error :=
Ok {|
balance := 0;
owner := ctx.(ctx_from);
piggyState := Intact
|}.
Definition contract : Contract Setup Msg State Error :=
build_contract init receive.
End PiggyBankImpl.
|
If $h$ is bilinear, then $h( \sum_{i \in S} f_i, \sum_{j \in T} g_j) = \sum_{(i,j) \in S \times T} h(f_i, g_j)$. |
section \<open>Transition Systems and Trace Theory\<close>
theory Transition_System_Traces
imports
Transition_System_Extensions
Traces
begin
lemma (in transition_system) words_infI_construct[rule_format, intro?]:
assumes "\<forall> v. v \<le>\<^sub>F\<^sub>I w \<longrightarrow> path v p"
shows "run w p"
using assms by coinduct auto
lemma (in transition_system) words_infI_construct':
assumes "\<And> k. \<exists> v. v \<le>\<^sub>F\<^sub>I w \<and> k < length v \<and> path v p"
shows "run w p"
proof
fix u
assume 1: "u \<le>\<^sub>F\<^sub>I w"
obtain v where 2: "v \<le>\<^sub>F\<^sub>I w" "length u < length v" "path v p" using assms(1) by auto
have 3: "length u \<le> length v" using 2(2) by simp
have 4: "u \<le> v" using prefix_fininf_length 1 2(1) 3 by this
show "path u p" using 4 2(3) by auto
qed
lemma (in transition_system) words_infI_construct_chain[intro]:
assumes "chain w" "\<And> k. path (w k) p"
shows "run (limit w) p"
proof (rule words_infI_construct')
fix k
obtain l where 1: "k < length (w l)" using assms(1) by rule
show "\<exists> v. v \<le>\<^sub>F\<^sub>I limit w \<and> k < length v \<and> path v p"
proof (intro exI conjI)
show "w l \<le>\<^sub>F\<^sub>I limit w" using chain_prefix_limit assms(1) by this
show "k < length (w l)" using 1 by this
show "path (w l) p" using assms(2) by this
qed
qed
lemma (in transition_system) words_fin_blocked:
assumes "\<And> w. path w p \<Longrightarrow> A \<inter> set w = {} \<Longrightarrow> A \<inter> {a. enabled a (target w p)} \<subseteq> A \<inter> {a. enabled a p}"
assumes "path w p" "A \<inter> {a. enabled a p} \<inter> set w = {}"
shows "A \<inter> set w = {}"
using assms by (induct w rule: rev_induct, auto)
locale transition_system_traces =
transition_system ex en +
traces ind
for ex :: "'action \<Rightarrow> 'state \<Rightarrow> 'state"
and en :: "'action \<Rightarrow> 'state \<Rightarrow> bool"
and ind :: "'action \<Rightarrow> 'action \<Rightarrow> bool"
+
assumes en: "ind a b \<Longrightarrow> en a p \<Longrightarrow> en b p \<longleftrightarrow> en b (ex a p)"
assumes ex: "ind a b \<Longrightarrow> en a p \<Longrightarrow> en b p \<Longrightarrow> ex b (ex a p) = ex a (ex b p)"
begin
lemma diamond_bottom:
assumes "ind a b"
assumes "en a p" "en b p"
shows "en a (ex b p)" "en b (ex a p)" "ex b (ex a p) = ex a (ex b p)"
using assms independence_symmetric en ex by metis+
lemma diamond_right:
assumes "ind a b"
assumes "en a p" "en b (ex a p)"
shows "en a (ex b p)" "en b p" "ex b (ex a p) = ex a (ex b p)"
using assms independence_symmetric en ex by metis+
lemma diamond_left:
assumes "ind a b"
assumes "en a (ex b p)" "en b p"
shows "en a p" "en b (ex a p)" "ex b (ex a p) = ex a (ex b p)"
using assms independence_symmetric en ex by metis+
lemma eq_swap_word:
assumes "w\<^sub>1 =\<^sub>S w\<^sub>2" "path w\<^sub>1 p"
shows "path w\<^sub>2 p"
using assms diamond_right by (induct, auto)
lemma eq_fin_word:
assumes "w\<^sub>1 =\<^sub>F w\<^sub>2" "path w\<^sub>1 p"
shows "path w\<^sub>2 p"
using assms eq_swap_word by (induct, auto)
lemma le_fin_word:
assumes "w\<^sub>1 \<preceq>\<^sub>F w\<^sub>2" "path w\<^sub>2 p"
shows "path w\<^sub>1 p"
using assms eq_fin_word by blast
lemma le_fininf_word:
assumes "w\<^sub>1 \<preceq>\<^sub>F\<^sub>I w\<^sub>2" "run w\<^sub>2 p"
shows "path w\<^sub>1 p"
using assms le_fin_word by blast
lemma le_inf_word:
assumes "w\<^sub>2 \<preceq>\<^sub>I w\<^sub>1" "run w\<^sub>1 p"
shows "run w\<^sub>2 p"
using assms le_fininf_word by (blast intro: words_infI_construct)
lemma eq_inf_word:
assumes "w\<^sub>1 =\<^sub>I w\<^sub>2" "run w\<^sub>1 p"
shows "run w\<^sub>2 p"
using assms le_inf_word by auto
lemma eq_swap_execute:
assumes "path w\<^sub>1 p" "w\<^sub>1 =\<^sub>S w\<^sub>2"
shows "fold ex w\<^sub>1 p = fold ex w\<^sub>2 p"
using assms(2, 1) diamond_right by (induct, auto)
lemma eq_fin_execute:
assumes "path w\<^sub>1 p" "w\<^sub>1 =\<^sub>F w\<^sub>2"
shows "fold ex w\<^sub>1 p = fold ex w\<^sub>2 p"
using assms(2, 1) eq_fin_word eq_swap_execute by (induct, auto)
lemma diamond_fin_word_step:
assumes "Ind {a} (set v)" "en a p" "path v p"
shows "path v (ex a p)"
using diamond_bottom assms by (induct v arbitrary: p, auto, metis)
lemma diamond_inf_word_step:
assumes "Ind {a} (sset w)" "en a p" "run w p"
shows "run w (ex a p)"
using diamond_fin_word_step assms by (fast intro: words_infI_construct)
lemma diamond_fin_word_inf_word:
assumes "Ind (set v) (sset w)" "path v p" "run w p"
shows "run w (fold ex v p)"
using diamond_inf_word_step assms by (induct v arbitrary: p, auto)
lemma diamond_fin_word_inf_word':
assumes "Ind (set v) (sset w)" "path (u @ v) p" "run (u @- w) p"
shows "run (u @- v @- w) p"
using assms diamond_fin_word_inf_word by auto
end
end
|
println("£")
println("\302\243"); # works if your terminal is utf-8
|
[GOAL]
τ : Type u_1
α : Type u_2
ϕ : τ → α → α
s : Set α
⊢ IsInvariant ϕ s ↔ ∀ (t : τ), ϕ t '' s ⊆ s
[PROOFSTEP]
simp_rw [IsInvariant, mapsTo']
[GOAL]
τ : Type u_1
inst✝³ : AddMonoid τ
inst✝² : TopologicalSpace τ
inst✝¹ : ContinuousAdd τ
α : Type u_2
inst✝ : TopologicalSpace α
ϕ : Flow τ α
f₁ : τ → α → α
cont'✝¹ : Continuous (uncurry f₁)
map_add'✝¹ : ∀ (t₁ t₂ : τ) (x : α), f₁ (t₁ + t₂) x = f₁ t₁ (f₁ t₂ x)
map_zero'✝¹ : ∀ (x : α), f₁ 0 x = x
f₂ : τ → α → α
cont'✝ : Continuous (uncurry f₂)
map_add'✝ : ∀ (t₁ t₂ : τ) (x : α), f₂ (t₁ + t₂) x = f₂ t₁ (f₂ t₂ x)
map_zero'✝ : ∀ (x : α), f₂ 0 x = x
h :
∀ (t : τ) (x : α),
toFun { toFun := f₁, cont' := cont'✝¹, map_add' := map_add'✝¹, map_zero' := map_zero'✝¹ } t x =
toFun { toFun := f₂, cont' := cont'✝, map_add' := map_add'✝, map_zero' := map_zero'✝ } t x
⊢ { toFun := f₁, cont' := cont'✝¹, map_add' := map_add'✝¹, map_zero' := map_zero'✝¹ } =
{ toFun := f₂, cont' := cont'✝, map_add' := map_add'✝, map_zero' := map_zero'✝ }
[PROOFSTEP]
congr
[GOAL]
case e_toFun
τ : Type u_1
inst✝³ : AddMonoid τ
inst✝² : TopologicalSpace τ
inst✝¹ : ContinuousAdd τ
α : Type u_2
inst✝ : TopologicalSpace α
ϕ : Flow τ α
f₁ : τ → α → α
cont'✝¹ : Continuous (uncurry f₁)
map_add'✝¹ : ∀ (t₁ t₂ : τ) (x : α), f₁ (t₁ + t₂) x = f₁ t₁ (f₁ t₂ x)
map_zero'✝¹ : ∀ (x : α), f₁ 0 x = x
f₂ : τ → α → α
cont'✝ : Continuous (uncurry f₂)
map_add'✝ : ∀ (t₁ t₂ : τ) (x : α), f₂ (t₁ + t₂) x = f₂ t₁ (f₂ t₂ x)
map_zero'✝ : ∀ (x : α), f₂ 0 x = x
h :
∀ (t : τ) (x : α),
toFun { toFun := f₁, cont' := cont'✝¹, map_add' := map_add'✝¹, map_zero' := map_zero'✝¹ } t x =
toFun { toFun := f₂, cont' := cont'✝, map_add' := map_add'✝, map_zero' := map_zero'✝ } t x
⊢ f₁ = f₂
[PROOFSTEP]
funext
[GOAL]
case e_toFun.h.h
τ : Type u_1
inst✝³ : AddMonoid τ
inst✝² : TopologicalSpace τ
inst✝¹ : ContinuousAdd τ
α : Type u_2
inst✝ : TopologicalSpace α
ϕ : Flow τ α
f₁ : τ → α → α
cont'✝¹ : Continuous (uncurry f₁)
map_add'✝¹ : ∀ (t₁ t₂ : τ) (x : α), f₁ (t₁ + t₂) x = f₁ t₁ (f₁ t₂ x)
map_zero'✝¹ : ∀ (x : α), f₁ 0 x = x
f₂ : τ → α → α
cont'✝ : Continuous (uncurry f₂)
map_add'✝ : ∀ (t₁ t₂ : τ) (x : α), f₂ (t₁ + t₂) x = f₂ t₁ (f₂ t₂ x)
map_zero'✝ : ∀ (x : α), f₂ 0 x = x
h :
∀ (t : τ) (x : α),
toFun { toFun := f₁, cont' := cont'✝¹, map_add' := map_add'✝¹, map_zero' := map_zero'✝¹ } t x =
toFun { toFun := f₂, cont' := cont'✝, map_add' := map_add'✝, map_zero' := map_zero'✝ } t x
x✝¹ : τ
x✝ : α
⊢ f₁ x✝¹ x✝ = f₂ x✝¹ x✝
[PROOFSTEP]
exact h _ _
[GOAL]
τ : Type u_1
inst✝³ : AddCommGroup τ
inst✝² : TopologicalSpace τ
inst✝¹ : TopologicalAddGroup τ
α : Type u_2
inst✝ : TopologicalSpace α
ϕ : Flow τ α
s : Set α
h : ∀ (t : τ), toFun ϕ t '' s ⊆ s
t : τ
x✝ : α
hx : x✝ ∈ s
⊢ toFun ϕ t (toFun ϕ (-t) x✝) = x✝
[PROOFSTEP]
simp [← map_add]
[GOAL]
τ : Type u_1
inst✝³ : AddCommGroup τ
inst✝² : TopologicalSpace τ
inst✝¹ : TopologicalAddGroup τ
α : Type u_2
inst✝ : TopologicalSpace α
ϕ : Flow τ α
s : Set α
h : ∀ (t : τ), toFun ϕ t '' s = s
t : τ
⊢ toFun ϕ t '' s ⊆ s
[PROOFSTEP]
rw [h t]
[GOAL]
τ : Type u_1
inst✝³ : AddCommGroup τ
inst✝² : TopologicalSpace τ
inst✝¹ : TopologicalAddGroup τ
α : Type u_2
inst✝ : TopologicalSpace α
ϕ : Flow τ α
x✝² x✝¹ : τ
x✝ : α
⊢ (fun t => toFun ϕ (-t)) (x✝² + x✝¹) x✝ = (fun t => toFun ϕ (-t)) x✝² ((fun t => toFun ϕ (-t)) x✝¹ x✝)
[PROOFSTEP]
dsimp
[GOAL]
τ : Type u_1
inst✝³ : AddCommGroup τ
inst✝² : TopologicalSpace τ
inst✝¹ : TopologicalAddGroup τ
α : Type u_2
inst✝ : TopologicalSpace α
ϕ : Flow τ α
x✝² x✝¹ : τ
x✝ : α
⊢ toFun ϕ (-(x✝² + x✝¹)) x✝ = toFun ϕ (-x✝²) (toFun ϕ (-x✝¹) x✝)
[PROOFSTEP]
rw [neg_add, map_add]
[GOAL]
τ : Type u_1
inst✝³ : AddCommGroup τ
inst✝² : TopologicalSpace τ
inst✝¹ : TopologicalAddGroup τ
α : Type u_2
inst✝ : TopologicalSpace α
ϕ : Flow τ α
x✝ : α
⊢ (fun t => toFun ϕ (-t)) 0 x✝ = x✝
[PROOFSTEP]
dsimp
[GOAL]
τ : Type u_1
inst✝³ : AddCommGroup τ
inst✝² : TopologicalSpace τ
inst✝¹ : TopologicalAddGroup τ
α : Type u_2
inst✝ : TopologicalSpace α
ϕ : Flow τ α
x✝ : α
⊢ toFun ϕ (-0) x✝ = x✝
[PROOFSTEP]
rw [neg_zero, map_zero_apply]
[GOAL]
τ : Type u_1
inst✝³ : AddCommGroup τ
inst✝² : TopologicalSpace τ
inst✝¹ : TopologicalAddGroup τ
α : Type u_2
inst✝ : TopologicalSpace α
ϕ : Flow τ α
t : τ
⊢ Continuous (toFun ϕ t)
[PROOFSTEP]
rw [← curry_uncurry ϕ.toFun]
[GOAL]
τ : Type u_1
inst✝³ : AddCommGroup τ
inst✝² : TopologicalSpace τ
inst✝¹ : TopologicalAddGroup τ
α : Type u_2
inst✝ : TopologicalSpace α
ϕ : Flow τ α
t : τ
⊢ Continuous (curry (uncurry ϕ.toFun) t)
[PROOFSTEP]
apply continuous_curry
[GOAL]
case h
τ : Type u_1
inst✝³ : AddCommGroup τ
inst✝² : TopologicalSpace τ
inst✝¹ : TopologicalAddGroup τ
α : Type u_2
inst✝ : TopologicalSpace α
ϕ : Flow τ α
t : τ
⊢ Continuous (uncurry ϕ.toFun)
[PROOFSTEP]
exact ϕ.cont'
[GOAL]
τ : Type u_1
inst✝³ : AddCommGroup τ
inst✝² : TopologicalSpace τ
inst✝¹ : TopologicalAddGroup τ
α : Type u_2
inst✝ : TopologicalSpace α
ϕ : Flow τ α
t : τ
x : α
⊢ toFun ϕ (-t) (toFun ϕ t x) = x
[PROOFSTEP]
rw [← map_add, neg_add_self, map_zero_apply]
[GOAL]
τ : Type u_1
inst✝³ : AddCommGroup τ
inst✝² : TopologicalSpace τ
inst✝¹ : TopologicalAddGroup τ
α : Type u_2
inst✝ : TopologicalSpace α
ϕ : Flow τ α
t : τ
x : α
⊢ toFun ϕ t (toFun ϕ (-t) x) = x
[PROOFSTEP]
rw [← map_add, add_neg_self, map_zero_apply]
|
/-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import linear_algebra.basic
import order.atoms
/-!
# Simple Modules
## Main Definitions
* `is_simple_module` indicates that a module has no proper submodules
(the only submodules are `⊥` and `⊤`).
* `is_semisimple_module` indicates that every submodule has a complement, or equivalently,
the module is a direct sum of simple modules.
* A `division_ring` structure on the endomorphism ring of a simple module.
## Main Results
* Schur's Lemma: `bijective_or_eq_zero` shows that a linear map between simple modules
is either bijective or 0, leading to a `division_ring` structure on the endomorphism ring.
## TODO
* Artin-Wedderburn Theory
* Unify with the work on Schur's Lemma in a category theory context
-/
variables (R : Type*) [ring R] (M : Type*) [add_comm_group M] [module R M]
/-- A module is simple when it has only two submodules, `⊥` and `⊤`. -/
abbreviation is_simple_module := (is_simple_lattice (submodule R M))
/-- A module is semisimple when every submodule has a complement, or equivalently, the module
is a direct sum of simple modules. -/
abbreviation is_semisimple_module := (is_complemented (submodule R M))
-- Making this an instance causes the linter to complain of "dangerous instances"
theorem is_simple_module.nontrivial [is_simple_module R M] : nontrivial M :=
⟨⟨0, begin
have h : (⊥ : submodule R M) ≠ ⊤ := bot_ne_top,
contrapose! h,
ext,
simp [submodule.mem_bot,submodule.mem_top, h x],
end⟩⟩
variables {R} {M} {m : submodule R M} {N : Type*} [add_comm_group N] [module R N]
theorem is_simple_module_iff_is_atom :
is_simple_module R m ↔ is_atom m :=
begin
rw ← set.is_simple_lattice_Iic_iff_is_atom,
apply order_iso.is_simple_lattice_iff,
exact submodule.map_subtype.rel_iso m,
end
namespace is_simple_module
variable [hm : is_simple_module R m]
@[simp]
lemma is_atom : is_atom m := is_simple_module_iff_is_atom.1 hm
end is_simple_module
theorem is_semisimple_of_Sup_simples_eq_top
(h : Sup {m : submodule R M | is_simple_module R m} = ⊤) :
is_semisimple_module R M :=
is_complemented_of_Sup_atoms_eq_top (by simp_rw [← h, is_simple_module_iff_is_atom])
namespace is_semisimple_module
variable [is_semisimple_module R M]
theorem Sup_simples_eq_top : Sup {m : submodule R M | is_simple_module R m} = ⊤ :=
begin
simp_rw is_simple_module_iff_is_atom,
exact Sup_atoms_eq_top,
end
instance is_semisimple_submodule {m : submodule R M} : is_semisimple_module R m :=
begin
have f : submodule R m ≃o set.Iic m := submodule.map_subtype.rel_iso m,
exact f.is_complemented_iff.2 is_modular_lattice.is_complemented_Iic,
end
end is_semisimple_module
theorem is_semisimple_iff_top_eq_Sup_simples :
Sup {m : submodule R M | is_simple_module R m} = ⊤ ↔ is_semisimple_module R M :=
⟨is_semisimple_of_Sup_simples_eq_top, by { introI, exact is_semisimple_module.Sup_simples_eq_top }⟩
namespace linear_map
theorem injective_or_eq_zero [is_simple_module R M] (f : M →ₗ[R] N) :
function.injective f ∨ f = 0 :=
begin
rw [← ker_eq_bot, ← ker_eq_top],
apply eq_bot_or_eq_top,
end
theorem injective_of_ne_zero [is_simple_module R M] {f : M →ₗ[R] N} (h : f ≠ 0) :
function.injective f :=
f.injective_or_eq_zero.resolve_right h
theorem surjective_or_eq_zero [is_simple_module R N] (f : M →ₗ[R] N) :
function.surjective f ∨ f = 0 :=
begin
rw [← range_eq_top, ← range_eq_bot, or_comm],
apply eq_bot_or_eq_top,
end
theorem surjective_of_ne_zero [is_simple_module R N] {f : M →ₗ[R] N} (h : f ≠ 0) :
function.surjective f :=
f.surjective_or_eq_zero.resolve_right h
/-- Schur's Lemma for linear maps between (possibly distinct) simple modules -/
theorem bijective_or_eq_zero [is_simple_module R M] [is_simple_module R N]
(f : M →ₗ[R] N) :
function.bijective f ∨ f = 0 :=
begin
by_cases h : f = 0,
{ right,
exact h },
exact or.intro_left _ ⟨injective_of_ne_zero h, surjective_of_ne_zero h⟩,
end
theorem bijective_of_ne_zero [is_simple_module R M] [is_simple_module R N]
{f : M →ₗ[R] N} (h : f ≠ 0):
function.bijective f :=
f.bijective_or_eq_zero.resolve_right h
/-- Schur's Lemma makes the endomorphism ring of a simple module a division ring. -/
noncomputable instance [decidable_eq (module.End R M)] [is_simple_module R M] :
division_ring (module.End R M) :=
{ inv := λ f, if h : f = 0 then 0 else (linear_map.inverse f
(equiv.of_bijective _ (bijective_of_ne_zero h)).inv_fun
(equiv.of_bijective _ (bijective_of_ne_zero h)).left_inv
(equiv.of_bijective _ (bijective_of_ne_zero h)).right_inv),
exists_pair_ne := ⟨0, 1, begin
haveI := is_simple_module.nontrivial R M,
have h := exists_pair_ne M,
contrapose! h,
intros x y,
simp_rw [ext_iff, one_apply, zero_apply] at h,
rw [← h x, h y],
end⟩,
mul_inv_cancel := begin
intros a a0,
change (a * (dite _ _ _)) = 1,
ext,
rw [dif_neg a0, mul_eq_comp, one_apply, comp_apply],
exact (equiv.of_bijective _ (bijective_of_ne_zero a0)).right_inv x,
end,
inv_zero := dif_pos rfl,
.. (linear_map.endomorphism_ring : ring (module.End R M))}
end linear_map
|
lemma eucl_rel_poly_0: "eucl_rel_poly 0 y (0, 0)" |
[GOAL]
r : Type u
m : Type u → Type v
α β γ ω : Type w
x y : ContT r m α
h : ∀ (f : α → m r), run x f = run y f
⊢ x = y
[PROOFSTEP]
unfold ContT
[GOAL]
r : Type u
m : Type u → Type v
α β γ ω : Type w
x y : ContT r m α
h : ∀ (f : α → m r), run x f = run y f
⊢ x = y
[PROOFSTEP]
ext
[GOAL]
case h
r : Type u
m : Type u → Type v
α β γ ω : Type w
x y : ContT r m α
h : ∀ (f : α → m r), run x f = run y f
x✝ : α → m r
⊢ x x✝ = y x✝
[PROOFSTEP]
apply h
[GOAL]
r : Type u
m : Type u → Type v
α β γ ω : Type w
⊢ ∀ {α : Type ?u.3230} (x : ContT r m α), id <$> x = x
[PROOFSTEP]
intros
[GOAL]
r : Type u
m : Type u → Type v
α β γ ω : Type w
α✝ : Type ?u.3230
x✝ : ContT r m α✝
⊢ id <$> x✝ = x✝
[PROOFSTEP]
rfl
[GOAL]
r : Type u
m : Type u → Type v
α β γ ω : Type w
⊢ ∀ {α β : Type ?u.3230} (x : α) (f : α → ContT r m β), pure x >>= f = f x
[PROOFSTEP]
intros
[GOAL]
r : Type u
m : Type u → Type v
α β γ ω : Type w
α✝ β✝ : Type ?u.3230
x✝ : α✝
f✝ : α✝ → ContT r m β✝
⊢ pure x✝ >>= f✝ = f✝ x✝
[PROOFSTEP]
ext
[GOAL]
case h
r : Type u
m : Type u → Type v
α β γ ω : Type w
α✝ β✝ : Type ?u.3230
x✝ : α✝
f✝¹ : α✝ → ContT r m β✝
f✝ : β✝ → m r
⊢ run (pure x✝ >>= f✝¹) f✝ = run (f✝¹ x✝) f✝
[PROOFSTEP]
rfl
[GOAL]
r : Type u
m : Type u → Type v
α β γ ω : Type w
⊢ ∀ {α β γ : Type ?u.3230} (x : ContT r m α) (f : α → ContT r m β) (g : β → ContT r m γ),
x >>= f >>= g = x >>= fun x => f x >>= g
[PROOFSTEP]
intros
[GOAL]
r : Type u
m : Type u → Type v
α β γ ω : Type w
α✝ β✝ γ✝ : Type ?u.3230
x✝ : ContT r m α✝
f✝ : α✝ → ContT r m β✝
g✝ : β✝ → ContT r m γ✝
⊢ x✝ >>= f✝ >>= g✝ = x✝ >>= fun x => f✝ x >>= g✝
[PROOFSTEP]
ext
[GOAL]
case h
r : Type u
m : Type u → Type v
α β γ ω : Type w
α✝ β✝ γ✝ : Type ?u.3230
x✝ : ContT r m α✝
f✝¹ : α✝ → ContT r m β✝
g✝ : β✝ → ContT r m γ✝
f✝ : γ✝ → m r
⊢ run (x✝ >>= f✝¹ >>= g✝) f✝ = run (x✝ >>= fun x => f✝¹ x >>= g✝) f✝
[PROOFSTEP]
rfl
[GOAL]
r : Type u
m : Type u → Type v
α✝ β✝ γ ω : Type w
inst✝¹ : Monad m
inst✝ : LawfulMonad m
α β : Type u
x : m α
f : α → m β
⊢ monadLift (x >>= f) = monadLift x >>= monadLift ∘ f
[PROOFSTEP]
ext
[GOAL]
case h
r : Type u
m : Type u → Type v
α✝ β✝ γ ω : Type w
inst✝¹ : Monad m
inst✝ : LawfulMonad m
α β : Type u
x : m α
f : α → m β
f✝ : β → m r
⊢ run (monadLift (x >>= f)) f✝ = run (monadLift x >>= monadLift ∘ f) f✝
[PROOFSTEP]
simp only [monadLift, MonadLift.monadLift, (· ∘ ·), (· >>= ·), bind_assoc, id.def, run, ContT.monadLift]
[GOAL]
r : Type u
m : Type u → Type v
α β γ ω : Type w
⊢ ∀ {α ω γ : Type ?u.4864} (cmd : ContT r m α) (next : Label ω (ContT r m) γ → α → ContT r m ω),
(callCC fun f => cmd >>= next f) = do
let x ← cmd
callCC fun f => next f x
[PROOFSTEP]
intros
[GOAL]
r : Type u
m : Type u → Type v
α β γ ω : Type w
α✝ ω✝ γ✝ : Type ?u.4864
cmd✝ : ContT r m α✝
next✝ : Label ω✝ (ContT r m) γ✝ → α✝ → ContT r m ω✝
⊢ (callCC fun f => cmd✝ >>= next✝ f) = do
let x ← cmd✝
callCC fun f => next✝ f x
[PROOFSTEP]
ext
[GOAL]
case h
r : Type u
m : Type u → Type v
α β γ ω : Type w
α✝ ω✝ γ✝ : Type ?u.4864
cmd✝ : ContT r m α✝
next✝ : Label ω✝ (ContT r m) γ✝ → α✝ → ContT r m ω✝
f✝ : ω✝ → m r
⊢ run (callCC fun f => cmd✝ >>= next✝ f) f✝ =
run
(do
let x ← cmd✝
callCC fun f => next✝ f x)
f✝
[PROOFSTEP]
rfl
[GOAL]
r : Type u
m : Type u → Type v
α β γ ω : Type w
⊢ ∀ {α : Type ?u.4864} (β : Type ?u.4864) (x : α) (dead : Label α (ContT r m) β → β → ContT r m α),
(callCC fun f => goto f x >>= dead f) = pure x
[PROOFSTEP]
intros
[GOAL]
r : Type u
m : Type u → Type v
α β γ ω : Type w
α✝ β✝ : Type ?u.4864
x✝ : α✝
dead✝ : Label α✝ (ContT r m) β✝ → β✝ → ContT r m α✝
⊢ (callCC fun f => goto f x✝ >>= dead✝ f) = pure x✝
[PROOFSTEP]
ext
[GOAL]
case h
r : Type u
m : Type u → Type v
α β γ ω : Type w
α✝ β✝ : Type ?u.4864
x✝ : α✝
dead✝ : Label α✝ (ContT r m) β✝ → β✝ → ContT r m α✝
f✝ : α✝ → m r
⊢ run (callCC fun f => goto f x✝ >>= dead✝ f) f✝ = run (pure x✝) f✝
[PROOFSTEP]
rfl
[GOAL]
r : Type u
m : Type u → Type v
α β γ ω : Type w
⊢ ∀ {α β : Type ?u.4864} (dummy : ContT r m α), (callCC fun x => dummy) = dummy
[PROOFSTEP]
intros
[GOAL]
r : Type u
m : Type u → Type v
α β γ ω : Type w
α✝ β✝ : Type ?u.4864
dummy✝ : ContT r m α✝
⊢ (callCC fun x => dummy✝) = dummy✝
[PROOFSTEP]
ext
[GOAL]
case h
r : Type u
m : Type u → Type v
α β γ ω : Type w
α✝ β✝ : Type ?u.4864
dummy✝ : ContT r m α✝
f✝ : α✝ → m r
⊢ run (callCC fun x => dummy✝) f✝ = run dummy✝ f✝
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝ : Monad m
α β ε : Type u
x : Label (Except ε α) m β
i : α
⊢ goto (mkLabel x) i = mk (Except.ok <$> goto x (Except.ok i))
[PROOFSTEP]
cases x
[GOAL]
case mk
m : Type u → Type v
inst✝ : Monad m
α β ε : Type u
i : α
apply✝ : Except ε α → m β
⊢ goto (mkLabel { apply := apply✝ }) i = mk (Except.ok <$> goto { apply := apply✝ } (Except.ok i))
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
⊢ ∀ {α ω γ : Type u} (cmd : ExceptT ε m α) (next : Label ω (ExceptT ε m) γ → α → ExceptT ε m ω),
(callCC fun f => cmd >>= next f) = do
let x ← cmd
callCC fun f => next f x
[PROOFSTEP]
intros
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : ExceptT ε m α✝
next✝ : Label ω✝ (ExceptT ε m) γ✝ → α✝ → ExceptT ε m ω✝
⊢ (callCC fun f => cmd✝ >>= next✝ f) = do
let x ← cmd✝
callCC fun f => next✝ f x
[PROOFSTEP]
simp [callCC, ExceptT.callCC, callCC_bind_right]
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : ExceptT ε m α✝
next✝ : Label ω✝ (ExceptT ε m) γ✝ → α✝ → ExceptT ε m ω✝
⊢ (ExceptT.mk do
let x ← ExceptT.run cmd✝
callCC fun f =>
match x with
| Except.ok x => ExceptT.run (next✝ (ExceptT.mkLabel f) x)
| Except.error e => pure (Except.error e)) =
do
let x ← cmd✝
ExceptT.mk (callCC fun x_1 => ExceptT.run (next✝ (ExceptT.mkLabel x_1) x))
[PROOFSTEP]
ext
[GOAL]
case h
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : ExceptT ε m α✝
next✝ : Label ω✝ (ExceptT ε m) γ✝ → α✝ → ExceptT ε m ω✝
⊢ ExceptT.run
(ExceptT.mk do
let x ← ExceptT.run cmd✝
callCC fun f =>
match x with
| Except.ok x => ExceptT.run (next✝ (ExceptT.mkLabel f) x)
| Except.error e => pure (Except.error e)) =
ExceptT.run do
let x ← cmd✝
ExceptT.mk (callCC fun x_1 => ExceptT.run (next✝ (ExceptT.mkLabel x_1) x))
[PROOFSTEP]
dsimp
[GOAL]
case h
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : ExceptT ε m α✝
next✝ : Label ω✝ (ExceptT ε m) γ✝ → α✝ → ExceptT ε m ω✝
⊢ (do
let x ← ExceptT.run cmd✝
callCC fun f =>
match x with
| Except.ok x => ExceptT.run (next✝ (ExceptT.mkLabel f) x)
| Except.error e => pure (Except.error e)) =
do
let x ← ExceptT.run cmd✝
match x with
| Except.ok x => callCC fun x_1 => ExceptT.run (next✝ (ExceptT.mkLabel x_1) x)
| Except.error e => pure (Except.error e)
[PROOFSTEP]
congr with ⟨⟩
[GOAL]
case h.e_a.h.error
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : ExceptT ε m α✝
next✝ : Label ω✝ (ExceptT ε m) γ✝ → α✝ → ExceptT ε m ω✝
a✝ : ε
⊢ (callCC fun f =>
match Except.error a✝ with
| Except.ok x => ExceptT.run (next✝ (ExceptT.mkLabel f) x)
| Except.error e => pure (Except.error e)) =
match Except.error a✝ with
| Except.ok x => callCC fun x_1 => ExceptT.run (next✝ (ExceptT.mkLabel x_1) x)
| Except.error e => pure (Except.error e)
[PROOFSTEP]
simp [ExceptT.bindCont, @callCC_dummy m _]
[GOAL]
case h.e_a.h.ok
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : ExceptT ε m α✝
next✝ : Label ω✝ (ExceptT ε m) γ✝ → α✝ → ExceptT ε m ω✝
a✝ : α✝
⊢ (callCC fun f =>
match Except.ok a✝ with
| Except.ok x => ExceptT.run (next✝ (ExceptT.mkLabel f) x)
| Except.error e => pure (Except.error e)) =
match Except.ok a✝ with
| Except.ok x => callCC fun x_1 => ExceptT.run (next✝ (ExceptT.mkLabel x_1) x)
| Except.error e => pure (Except.error e)
[PROOFSTEP]
simp [ExceptT.bindCont, @callCC_dummy m _]
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
⊢ ∀ {α : Type u} (β : Type u) (x : α) (dead : Label α (ExceptT ε m) β → β → ExceptT ε m α),
(callCC fun f => goto f x >>= dead f) = pure x
[PROOFSTEP]
intros
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
x✝ : α✝
dead✝ : Label α✝ (ExceptT ε m) β✝ → β✝ → ExceptT ε m α✝
⊢ (callCC fun f => goto f x✝ >>= dead✝ f) = pure x✝
[PROOFSTEP]
simp [callCC, ExceptT.callCC, callCC_bind_right, ExceptT.goto_mkLabel, map_eq_bind_pure_comp, bind_assoc,
@callCC_bind_left m _, Function.comp]
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
x✝ : α✝
dead✝ : Label α✝ (ExceptT ε m) β✝ → β✝ → ExceptT ε m α✝
⊢ ExceptT.mk (pure (Except.ok x✝)) = pure x✝
[PROOFSTEP]
ext
[GOAL]
case h
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
x✝ : α✝
dead✝ : Label α✝ (ExceptT ε m) β✝ → β✝ → ExceptT ε m α✝
⊢ ExceptT.run (ExceptT.mk (pure (Except.ok x✝))) = ExceptT.run (pure x✝)
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
⊢ ∀ {α β : Type u} (dummy : ExceptT ε m α), (callCC fun x => dummy) = dummy
[PROOFSTEP]
intros
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
dummy✝ : ExceptT ε m α✝
⊢ (callCC fun x => dummy✝) = dummy✝
[PROOFSTEP]
simp [callCC, ExceptT.callCC, @callCC_dummy m _]
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
dummy✝ : ExceptT ε m α✝
⊢ ExceptT.mk (ExceptT.run dummy✝) = dummy✝
[PROOFSTEP]
ext
[GOAL]
case h
m : Type u → Type v
inst✝² : Monad m
ε : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
dummy✝ : ExceptT ε m α✝
⊢ ExceptT.run (ExceptT.mk (ExceptT.run dummy✝)) = ExceptT.run dummy✝
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
⊢ ∀ {α ω γ : Type u} (cmd : OptionT m α) (next : Label ω (OptionT m) γ → α → OptionT m ω),
(callCC fun f => cmd >>= next f) = do
let x ← cmd
callCC fun f => next f x
[PROOFSTEP]
intros
[GOAL]
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : OptionT m α✝
next✝ : Label ω✝ (OptionT m) γ✝ → α✝ → OptionT m ω✝
⊢ (callCC fun f => cmd✝ >>= next✝ f) = do
let x ← cmd✝
callCC fun f => next✝ f x
[PROOFSTEP]
simp [callCC, OptionT.callCC, callCC_bind_right]
[GOAL]
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : OptionT m α✝
next✝ : Label ω✝ (OptionT m) γ✝ → α✝ → OptionT m ω✝
⊢ (OptionT.mk do
let x ← OptionT.run cmd✝
callCC fun f =>
match x with
| some a => OptionT.run (next✝ (OptionT.mkLabel f) a)
| none => pure none) =
do
let x ← cmd✝
OptionT.mk (callCC fun x_1 => OptionT.run (next✝ (OptionT.mkLabel x_1) x))
[PROOFSTEP]
ext
[GOAL]
case h
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : OptionT m α✝
next✝ : Label ω✝ (OptionT m) γ✝ → α✝ → OptionT m ω✝
⊢ OptionT.run
(OptionT.mk do
let x ← OptionT.run cmd✝
callCC fun f =>
match x with
| some a => OptionT.run (next✝ (OptionT.mkLabel f) a)
| none => pure none) =
OptionT.run do
let x ← cmd✝
OptionT.mk (callCC fun x_1 => OptionT.run (next✝ (OptionT.mkLabel x_1) x))
[PROOFSTEP]
dsimp
[GOAL]
case h
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : OptionT m α✝
next✝ : Label ω✝ (OptionT m) γ✝ → α✝ → OptionT m ω✝
⊢ (do
let x ← OptionT.run cmd✝
callCC fun f =>
match x with
| some a => OptionT.run (next✝ (OptionT.mkLabel f) a)
| none => pure none) =
do
let x ← OptionT.run cmd✝
match x with
| some a => callCC fun x => OptionT.run (next✝ (OptionT.mkLabel x) a)
| none => pure none
[PROOFSTEP]
congr with ⟨⟩
[GOAL]
case h.e_a.h.none
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : OptionT m α✝
next✝ : Label ω✝ (OptionT m) γ✝ → α✝ → OptionT m ω✝
⊢ (callCC fun f =>
match none with
| some a => OptionT.run (next✝ (OptionT.mkLabel f) a)
| none => pure none) =
match none with
| some a => callCC fun x => OptionT.run (next✝ (OptionT.mkLabel x) a)
| none => pure none
[PROOFSTEP]
simp [@callCC_dummy m _]
[GOAL]
case h.e_a.h.some
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : OptionT m α✝
next✝ : Label ω✝ (OptionT m) γ✝ → α✝ → OptionT m ω✝
val✝ : α✝
⊢ (callCC fun f =>
match some val✝ with
| some a => OptionT.run (next✝ (OptionT.mkLabel f) a)
| none => pure none) =
match some val✝ with
| some a => callCC fun x => OptionT.run (next✝ (OptionT.mkLabel x) a)
| none => pure none
[PROOFSTEP]
simp [@callCC_dummy m _]
[GOAL]
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
⊢ ∀ {α : Type u} (β : Type u) (x : α) (dead : Label α (OptionT m) β → β → OptionT m α),
(callCC fun f => goto f x >>= dead f) = pure x
[PROOFSTEP]
intros
[GOAL]
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
x✝ : α✝
dead✝ : Label α✝ (OptionT m) β✝ → β✝ → OptionT m α✝
⊢ (callCC fun f => goto f x✝ >>= dead✝ f) = pure x✝
[PROOFSTEP]
simp [callCC, OptionT.callCC, callCC_bind_right, OptionT.goto_mkLabel, map_eq_bind_pure_comp, bind_assoc,
@callCC_bind_left m _, Function.comp]
[GOAL]
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
x✝ : α✝
dead✝ : Label α✝ (OptionT m) β✝ → β✝ → OptionT m α✝
⊢ OptionT.mk (pure (some x✝)) = pure x✝
[PROOFSTEP]
ext
[GOAL]
case h
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
x✝ : α✝
dead✝ : Label α✝ (OptionT m) β✝ → β✝ → OptionT m α✝
⊢ OptionT.run (OptionT.mk (pure (some x✝))) = OptionT.run (pure x✝)
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
⊢ ∀ {α β : Type u} (dummy : OptionT m α), (callCC fun x => dummy) = dummy
[PROOFSTEP]
intros
[GOAL]
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
dummy✝ : OptionT m α✝
⊢ (callCC fun x => dummy✝) = dummy✝
[PROOFSTEP]
simp [callCC, OptionT.callCC, @callCC_dummy m _]
[GOAL]
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
dummy✝ : OptionT m α✝
⊢ OptionT.mk (OptionT.run dummy✝) = dummy✝
[PROOFSTEP]
ext
[GOAL]
case h
m : Type u → Type v
inst✝² : Monad m
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
dummy✝ : OptionT m α✝
⊢ OptionT.run (OptionT.mk (OptionT.run dummy✝)) = OptionT.run dummy✝
[PROOFSTEP]
rfl
/- Porting note: In Lean 3, `One ω` is required for `MonadLift (WriterT ω m)`. In Lean 4,
`EmptyCollection ω` or `Monoid ω` is required. So we give definitions for the both
instances. -/
[GOAL]
m : Type u → Type v
inst✝¹ : Monad m
α : Type u_1
β ω : Type u
inst✝ : EmptyCollection ω
x : Label (α × ω) m β
i : α
⊢ goto (mkLabel x) i = monadLift (goto x (i, ∅))
[PROOFSTEP]
cases x
[GOAL]
case mk
m : Type u → Type v
inst✝¹ : Monad m
α : Type u_1
β ω : Type u
inst✝ : EmptyCollection ω
i : α
apply✝ : α × ω → m β
⊢ goto (mkLabel { apply := apply✝ }) i = monadLift (goto { apply := apply✝ } (i, ∅))
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝¹ : Monad m
α : Type u_1
β ω : Type u
inst✝ : Monoid ω
x : Label (α × ω) m β
i : α
⊢ goto (mkLabel' x) i = monadLift (goto x (i, 1))
[PROOFSTEP]
cases x
[GOAL]
case mk
m : Type u → Type v
inst✝¹ : Monad m
α : Type u_1
β ω : Type u
inst✝ : Monoid ω
i : α
apply✝ : α × ω → m β
⊢ goto (mkLabel' { apply := apply✝ }) i = monadLift (goto { apply := apply✝ } (i, 1))
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝ : Monad m
α β σ : Type u
x : Label (α × σ) m (β × σ)
i : α
⊢ goto (mkLabel x) i = StateT.mk fun s => goto x (i, s)
[PROOFSTEP]
cases x
[GOAL]
case mk
m : Type u → Type v
inst✝ : Monad m
α β σ : Type u
i : α
apply✝ : α × σ → m (β × σ)
⊢ goto (mkLabel { apply := apply✝ }) i = StateT.mk fun s => goto { apply := apply✝ } (i, s)
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝² : Monad m
σ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
⊢ ∀ {α ω γ : Type u} (cmd : StateT σ m α) (next : Label ω (StateT σ m) γ → α → StateT σ m ω),
(callCC fun f => cmd >>= next f) = do
let x ← cmd
callCC fun f => next f x
[PROOFSTEP]
intros
[GOAL]
m : Type u → Type v
inst✝² : Monad m
σ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : StateT σ m α✝
next✝ : Label ω✝ (StateT σ m) γ✝ → α✝ → StateT σ m ω✝
⊢ (callCC fun f => cmd✝ >>= next✝ f) = do
let x ← cmd✝
callCC fun f => next✝ f x
[PROOFSTEP]
simp [callCC, StateT.callCC, callCC_bind_right]
[GOAL]
m : Type u → Type v
inst✝² : Monad m
σ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : StateT σ m α✝
next✝ : Label ω✝ (StateT σ m) γ✝ → α✝ → StateT σ m ω✝
⊢ (StateT.mk fun r => do
let x ← StateT.run cmd✝ r
callCC fun f => StateT.run (next✝ (StateT.mkLabel f) x.fst) x.snd) =
do
let x ← cmd✝
StateT.mk fun r => callCC fun f' => StateT.run (next✝ (StateT.mkLabel f') x) r
[PROOFSTEP]
ext
[GOAL]
case h
m : Type u → Type v
inst✝² : Monad m
σ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : StateT σ m α✝
next✝ : Label ω✝ (StateT σ m) γ✝ → α✝ → StateT σ m ω✝
s✝ : σ
⊢ StateT.run
(StateT.mk fun r => do
let x ← StateT.run cmd✝ r
callCC fun f => StateT.run (next✝ (StateT.mkLabel f) x.fst) x.snd)
s✝ =
StateT.run
(do
let x ← cmd✝
StateT.mk fun r => callCC fun f' => StateT.run (next✝ (StateT.mkLabel f') x) r)
s✝
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝² : Monad m
σ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
⊢ ∀ {α : Type u} (β : Type u) (x : α) (dead : Label α (StateT σ m) β → β → StateT σ m α),
(callCC fun f => goto f x >>= dead f) = pure x
[PROOFSTEP]
intros
[GOAL]
m : Type u → Type v
inst✝² : Monad m
σ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
x✝ : α✝
dead✝ : Label α✝ (StateT σ m) β✝ → β✝ → StateT σ m α✝
⊢ (callCC fun f => goto f x✝ >>= dead✝ f) = pure x✝
[PROOFSTEP]
simp [callCC, StateT.callCC, callCC_bind_left, StateT.goto_mkLabel]
[GOAL]
m : Type u → Type v
inst✝² : Monad m
σ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
x✝ : α✝
dead✝ : Label α✝ (StateT σ m) β✝ → β✝ → StateT σ m α✝
⊢ (StateT.mk fun r => pure (x✝, r)) = pure x✝
[PROOFSTEP]
ext
[GOAL]
case h
m : Type u → Type v
inst✝² : Monad m
σ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
x✝ : α✝
dead✝ : Label α✝ (StateT σ m) β✝ → β✝ → StateT σ m α✝
s✝ : σ
⊢ StateT.run (StateT.mk fun r => pure (x✝, r)) s✝ = StateT.run (pure x✝) s✝
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝² : Monad m
σ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
⊢ ∀ {α β : Type u} (dummy : StateT σ m α), (callCC fun x => dummy) = dummy
[PROOFSTEP]
intros
[GOAL]
m : Type u → Type v
inst✝² : Monad m
σ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
dummy✝ : StateT σ m α✝
⊢ (callCC fun x => dummy✝) = dummy✝
[PROOFSTEP]
simp [callCC, StateT.callCC, callCC_bind_right, @callCC_dummy m _]
[GOAL]
m : Type u → Type v
inst✝² : Monad m
σ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
dummy✝ : StateT σ m α✝
⊢ (StateT.mk fun r => StateT.run dummy✝ r) = dummy✝
[PROOFSTEP]
ext
[GOAL]
case h
m : Type u → Type v
inst✝² : Monad m
σ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
dummy✝ : StateT σ m α✝
s✝ : σ
⊢ StateT.run (StateT.mk fun r => StateT.run dummy✝ r) s✝ = StateT.run dummy✝ s✝
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝ : Monad m
α : Type u_1
ρ β : Type u
x : Label α m β
i : α
⊢ goto (mkLabel ρ x) i = monadLift (goto x i)
[PROOFSTEP]
cases x
[GOAL]
case mk
m : Type u → Type v
inst✝ : Monad m
α : Type u_1
ρ β : Type u
i : α
apply✝ : α → m β
⊢ goto (mkLabel ρ { apply := apply✝ }) i = monadLift (goto { apply := apply✝ } i)
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ρ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
⊢ ∀ {α ω γ : Type u} (cmd : ReaderT ρ m α) (next : Label ω (ReaderT ρ m) γ → α → ReaderT ρ m ω),
(callCC fun f => cmd >>= next f) = do
let x ← cmd
callCC fun f => next f x
[PROOFSTEP]
intros
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ρ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : ReaderT ρ m α✝
next✝ : Label ω✝ (ReaderT ρ m) γ✝ → α✝ → ReaderT ρ m ω✝
⊢ (callCC fun f => cmd✝ >>= next✝ f) = do
let x ← cmd✝
callCC fun f => next✝ f x
[PROOFSTEP]
simp [callCC, ReaderT.callCC, callCC_bind_right]
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ρ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : ReaderT ρ m α✝
next✝ : Label ω✝ (ReaderT ρ m) γ✝ → α✝ → ReaderT ρ m ω✝
⊢ (ReaderT.mk fun r => do
let x ← ReaderT.run cmd✝ r
callCC fun f => ReaderT.run (next✝ (ReaderT.mkLabel ρ f) x) r) =
do
let x ← cmd✝
ReaderT.mk fun r => callCC fun f' => ReaderT.run (next✝ (ReaderT.mkLabel ρ f') x) r
[PROOFSTEP]
ext
[GOAL]
case h
m : Type u → Type v
inst✝² : Monad m
ρ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ ω✝ γ✝ : Type u
cmd✝ : ReaderT ρ m α✝
next✝ : Label ω✝ (ReaderT ρ m) γ✝ → α✝ → ReaderT ρ m ω✝
ctx✝ : ρ
⊢ ReaderT.run
(ReaderT.mk fun r => do
let x ← ReaderT.run cmd✝ r
callCC fun f => ReaderT.run (next✝ (ReaderT.mkLabel ρ f) x) r)
ctx✝ =
ReaderT.run
(do
let x ← cmd✝
ReaderT.mk fun r => callCC fun f' => ReaderT.run (next✝ (ReaderT.mkLabel ρ f') x) r)
ctx✝
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ρ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
⊢ ∀ {α : Type u} (β : Type u) (x : α) (dead : Label α (ReaderT ρ m) β → β → ReaderT ρ m α),
(callCC fun f => goto f x >>= dead f) = pure x
[PROOFSTEP]
intros
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ρ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
x✝ : α✝
dead✝ : Label α✝ (ReaderT ρ m) β✝ → β✝ → ReaderT ρ m α✝
⊢ (callCC fun f => goto f x✝ >>= dead✝ f) = pure x✝
[PROOFSTEP]
simp [callCC, ReaderT.callCC, callCC_bind_left, ReaderT.goto_mkLabel]
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ρ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
x✝ : α✝
dead✝ : Label α✝ (ReaderT ρ m) β✝ → β✝ → ReaderT ρ m α✝
⊢ (ReaderT.mk fun r => pure x✝) = pure x✝
[PROOFSTEP]
ext
[GOAL]
case h
m : Type u → Type v
inst✝² : Monad m
ρ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
x✝ : α✝
dead✝ : Label α✝ (ReaderT ρ m) β✝ → β✝ → ReaderT ρ m α✝
ctx✝ : ρ
⊢ ReaderT.run (ReaderT.mk fun r => pure x✝) ctx✝ = ReaderT.run (pure x✝) ctx✝
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ρ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
⊢ ∀ {α β : Type u} (dummy : ReaderT ρ m α), (callCC fun x => dummy) = dummy
[PROOFSTEP]
intros
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ρ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
dummy✝ : ReaderT ρ m α✝
⊢ (callCC fun x => dummy✝) = dummy✝
[PROOFSTEP]
simp [callCC, ReaderT.callCC, @callCC_dummy m _]
[GOAL]
m : Type u → Type v
inst✝² : Monad m
ρ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
dummy✝ : ReaderT ρ m α✝
⊢ (ReaderT.mk fun r => ReaderT.run dummy✝ r) = dummy✝
[PROOFSTEP]
ext
[GOAL]
case h
m : Type u → Type v
inst✝² : Monad m
ρ : Type u
inst✝¹ : MonadCont m
inst✝ : LawfulMonadCont m
α✝ β✝ : Type u
dummy✝ : ReaderT ρ m α✝
ctx✝ : ρ
⊢ ReaderT.run (ReaderT.mk fun r => ReaderT.run dummy✝ r) ctx✝ = ReaderT.run dummy✝ ctx✝
[PROOFSTEP]
rfl
[GOAL]
m : Type u → Type v
inst✝ : Monad m
m₁ : Type u₀ → Type v₀
m₂ : Type u₁ → Type v₁
α₁ r₁ : Type u₀
α₂ r₂ : Type u₁
F : m₁ r₁ ≃ m₂ r₂
G : α₁ ≃ α₂
f : ContT r₁ m₁ α₁
⊢ (fun f r => ↑F.symm (f fun x => ↑F (r (↑G.symm x)))) ((fun f r => ↑F (f fun x => ↑F.symm (r (↑G x)))) f) = f
[PROOFSTEP]
funext r
[GOAL]
case h
m : Type u → Type v
inst✝ : Monad m
m₁ : Type u₀ → Type v₀
m₂ : Type u₁ → Type v₁
α₁ r₁ : Type u₀
α₂ r₂ : Type u₁
F : m₁ r₁ ≃ m₂ r₂
G : α₁ ≃ α₂
f : ContT r₁ m₁ α₁
r : α₁ → m₁ r₁
⊢ (fun f r => ↑F.symm (f fun x => ↑F (r (↑G.symm x)))) ((fun f r => ↑F (f fun x => ↑F.symm (r (↑G x)))) f) r = f r
[PROOFSTEP]
simp
[GOAL]
m : Type u → Type v
inst✝ : Monad m
m₁ : Type u₀ → Type v₀
m₂ : Type u₁ → Type v₁
α₁ r₁ : Type u₀
α₂ r₂ : Type u₁
F : m₁ r₁ ≃ m₂ r₂
G : α₁ ≃ α₂
f : ContT r₂ m₂ α₂
⊢ (fun f r => ↑F (f fun x => ↑F.symm (r (↑G x)))) ((fun f r => ↑F.symm (f fun x => ↑F (r (↑G.symm x)))) f) = f
[PROOFSTEP]
funext r
[GOAL]
case h
m : Type u → Type v
inst✝ : Monad m
m₁ : Type u₀ → Type v₀
m₂ : Type u₁ → Type v₁
α₁ r₁ : Type u₀
α₂ r₂ : Type u₁
F : m₁ r₁ ≃ m₂ r₂
G : α₁ ≃ α₂
f : ContT r₂ m₂ α₂
r : α₂ → m₂ r₂
⊢ (fun f r => ↑F (f fun x => ↑F.symm (r (↑G x)))) ((fun f r => ↑F.symm (f fun x => ↑F (r (↑G.symm x)))) f) r = f r
[PROOFSTEP]
simp
|
We have some great news for those of you on Xbox now, as Activision and Microsoft have decided to offer something of a great treat for this weekend. For this weekend only, you’ll be able to play COD Ghosts multiplayer online for free, no questions asked.
In an interesting move, this will actually mark the first occasion where a free Call of Duty demo has been offered on console. Unsurprisingly, this is Xbox only on either Xbox 360 or Xbox One with no information whatsoever on the same deal taking place for PS3 and PS4 users.
COD Ghosts will be free on Friday March 7 at 1pm Eastern Time and will run through until Monday at the same time, that’s 10am for those on Pacific Time.
The maps that will be offered will be Strikezone, Warhawk and Prison Break, while players will also be able to get a taster of COD Ghosts Extinction as well – a lovely gesture you have to say.
Some players are already questioning the timing of this incentive though. As we all know, Titanfall is launching on March 11. Is this an attempt by Activision to remind everyone that COD Ghosts is still the number one shooter on Xbox One, regardless of the arrival of Titanfall?
Let us know your thoughts on this and whether you intend to take advantage of the free weekend. Do you think the COD Ghosts popularity is starting to slow down with those more interested in Titanfall? |
function lung_image = PTKFillCoronalHoles(lung_image, is_right, reporting)
% PTKFillCoronalHoles. Operates on each coronal slice, applying a closing
% filter then filling interior holes
%
%
%
% Licence
% -------
% Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
% Author: Tom Doel, 2012. www.tomdoel.com
% Distributed under the GNU GPL v3 licence. Please see website for details.
%
reporting.ShowProgress('Filling holes');
max_non_coronal_voxel_size = max(lung_image.VoxelSize(2:3));
opening_size = 10/max_non_coronal_voxel_size;
closing_size = 10/max_non_coronal_voxel_size;
lung_image.AddBorder(10);
for coronal_index = 11 : lung_image.ImageSize(1) - 10
reporting.UpdateProgressStage(coronal_index - 11, lung_image.ImageSize(1) - 20);
coronal_slice = lung_image.GetSlice(coronal_index, PTKImageOrientation.Coronal);
if ~isempty(is_right)
coronal_slice = OpenOrClose(coronal_slice, is_right, opening_size, closing_size, reporting);
end
coronal_slice = imclose(coronal_slice, strel('disk', round(closing_size)));
coronal_slice = imfill(coronal_slice, 'holes');
lung_image.ReplaceImageSlice(coronal_slice, coronal_index, PTKImageOrientation.Coronal);
end
lung_image.RemoveBorder(10);
reporting.CompleteProgress;
end
function mask = OpenOrClose(mask, is_right, opening_size, closing_size, reporting)
closed_image = imclose(mask, strel('disk', round(closing_size)));
opened_image = imopen(mask, strel('disk', round(opening_size)));
threshold = PTKImage(~(closed_image & opened_image));
threshold.AddBorder(1);
image_size = threshold.ImageSize;
raw_image = zeros(image_size);
if (is_right)
raw_image(2, 2:end-1, 2) = 2;
raw_image(end-1, 2:end-1, 2) = 1;
else
raw_image(2, 2:end-1, 2) = 1;
raw_image(end-1, 2:end-1, 2) = 2;
end
raw_image(2:end-1, end-1, 2) = 2;
raw_image(2:end-1, 2, 2) = 2;
right_border_indices = threshold.LocalToGlobalIndices(find(raw_image == 1));
other_border_indices = threshold.LocalToGlobalIndices(find(raw_image == 2));
start_points = {right_border_indices, other_border_indices};
reporting.PushProgress;
regions = PTKMultipleRegionGrowing(threshold, start_points, reporting);
reporting.PopProgress;
regions.RemoveBorder(1);
closed_region = (regions.RawImage == 1);
mask(closed_region) = closed_image(closed_region);
mask(~closed_region) = opened_image(~closed_region);
end
|
[GOAL]
⊢ catalan 0 = 1
[PROOFSTEP]
rw [catalan]
[GOAL]
n : ℕ
⊢ catalan (n + 1) = ∑ i : Fin (Nat.succ n), catalan ↑i * catalan (n - ↑i)
[PROOFSTEP]
rw [catalan]
[GOAL]
n : ℕ
⊢ catalan (n + 1) = ∑ ij in Nat.antidiagonal n, catalan ij.fst * catalan ij.snd
[PROOFSTEP]
rw [catalan_succ, Nat.sum_antidiagonal_eq_sum_range_succ (fun x y => catalan x * catalan y) n, sum_range]
[GOAL]
⊢ catalan 1 = 1
[PROOFSTEP]
simp [catalan_succ]
[GOAL]
n i : ℕ
h : i ≤ n
⊢ gosperCatalan (n + 1) (i + 1) - gosperCatalan (n + 1) i =
↑(Nat.centralBinom i) / (↑i + 1) * ↑(Nat.centralBinom (n - i)) / (↑n - ↑i + 1)
[PROOFSTEP]
have l₁ : (n : ℚ) + 1 ≠ 0 := by norm_cast; exact n.succ_ne_zero
[GOAL]
n i : ℕ
h : i ≤ n
⊢ ↑n + 1 ≠ 0
[PROOFSTEP]
norm_cast
[GOAL]
n i : ℕ
h : i ≤ n
⊢ ¬n + 1 = 0
[PROOFSTEP]
exact n.succ_ne_zero
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
⊢ gosperCatalan (n + 1) (i + 1) - gosperCatalan (n + 1) i =
↑(Nat.centralBinom i) / (↑i + 1) * ↑(Nat.centralBinom (n - i)) / (↑n - ↑i + 1)
[PROOFSTEP]
have l₂ : (n : ℚ) + 1 + 1 ≠ 0 := by norm_cast; exact (n + 1).succ_ne_zero
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
⊢ ↑n + 1 + 1 ≠ 0
[PROOFSTEP]
norm_cast
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
⊢ ¬n + 1 + 1 = 0
[PROOFSTEP]
exact (n + 1).succ_ne_zero
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
⊢ gosperCatalan (n + 1) (i + 1) - gosperCatalan (n + 1) i =
↑(Nat.centralBinom i) / (↑i + 1) * ↑(Nat.centralBinom (n - i)) / (↑n - ↑i + 1)
[PROOFSTEP]
have l₃ : (i : ℚ) + 1 ≠ 0 := by norm_cast; exact i.succ_ne_zero
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
⊢ ↑i + 1 ≠ 0
[PROOFSTEP]
norm_cast
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
⊢ ¬i + 1 = 0
[PROOFSTEP]
exact i.succ_ne_zero
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
⊢ gosperCatalan (n + 1) (i + 1) - gosperCatalan (n + 1) i =
↑(Nat.centralBinom i) / (↑i + 1) * ↑(Nat.centralBinom (n - i)) / (↑n - ↑i + 1)
[PROOFSTEP]
have l₄ : (n : ℚ) - i + 1 ≠ 0 := by norm_cast; exact (n - i).succ_ne_zero
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
⊢ ↑n - ↑i + 1 ≠ 0
[PROOFSTEP]
norm_cast
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
⊢ ¬n - i + 1 = 0
[PROOFSTEP]
exact (n - i).succ_ne_zero
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
l₄ : ↑n - ↑i + 1 ≠ 0
⊢ gosperCatalan (n + 1) (i + 1) - gosperCatalan (n + 1) i =
↑(Nat.centralBinom i) / (↑i + 1) * ↑(Nat.centralBinom (n - i)) / (↑n - ↑i + 1)
[PROOFSTEP]
have h₁ := (mul_div_cancel_left (↑(Nat.centralBinom (i + 1))) l₃).symm
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
l₄ : ↑n - ↑i + 1 ≠ 0
h₁ : ↑(Nat.centralBinom (i + 1)) = (↑i + 1) * ↑(Nat.centralBinom (i + 1)) / (↑i + 1)
⊢ gosperCatalan (n + 1) (i + 1) - gosperCatalan (n + 1) i =
↑(Nat.centralBinom i) / (↑i + 1) * ↑(Nat.centralBinom (n - i)) / (↑n - ↑i + 1)
[PROOFSTEP]
have h₂ := (mul_div_cancel_left (↑(Nat.centralBinom (n - i + 1))) l₄).symm
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
l₄ : ↑n - ↑i + 1 ≠ 0
h₁ : ↑(Nat.centralBinom (i + 1)) = (↑i + 1) * ↑(Nat.centralBinom (i + 1)) / (↑i + 1)
h₂ : ↑(Nat.centralBinom (n - i + 1)) = (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) / (↑n - ↑i + 1)
⊢ gosperCatalan (n + 1) (i + 1) - gosperCatalan (n + 1) i =
↑(Nat.centralBinom i) / (↑i + 1) * ↑(Nat.centralBinom (n - i)) / (↑n - ↑i + 1)
[PROOFSTEP]
have h₃ : ((i : ℚ) + 1) * (i + 1).centralBinom = 2 * (2 * i + 1) * i.centralBinom := by
exact_mod_cast Nat.succ_mul_centralBinom_succ i
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
l₄ : ↑n - ↑i + 1 ≠ 0
h₁ : ↑(Nat.centralBinom (i + 1)) = (↑i + 1) * ↑(Nat.centralBinom (i + 1)) / (↑i + 1)
h₂ : ↑(Nat.centralBinom (n - i + 1)) = (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) / (↑n - ↑i + 1)
⊢ (↑i + 1) * ↑(Nat.centralBinom (i + 1)) = 2 * (2 * ↑i + 1) * ↑(Nat.centralBinom i)
[PROOFSTEP]
exact_mod_cast Nat.succ_mul_centralBinom_succ i
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
l₄ : ↑n - ↑i + 1 ≠ 0
h₁ : ↑(Nat.centralBinom (i + 1)) = (↑i + 1) * ↑(Nat.centralBinom (i + 1)) / (↑i + 1)
h₂ : ↑(Nat.centralBinom (n - i + 1)) = (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) / (↑n - ↑i + 1)
h₃ : (↑i + 1) * ↑(Nat.centralBinom (i + 1)) = 2 * (2 * ↑i + 1) * ↑(Nat.centralBinom i)
⊢ gosperCatalan (n + 1) (i + 1) - gosperCatalan (n + 1) i =
↑(Nat.centralBinom i) / (↑i + 1) * ↑(Nat.centralBinom (n - i)) / (↑n - ↑i + 1)
[PROOFSTEP]
have h₄ : ((n : ℚ) - i + 1) * (n - i + 1).centralBinom = 2 * (2 * (n - i) + 1) * (n - i).centralBinom := by
exact_mod_cast Nat.succ_mul_centralBinom_succ (n - i)
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
l₄ : ↑n - ↑i + 1 ≠ 0
h₁ : ↑(Nat.centralBinom (i + 1)) = (↑i + 1) * ↑(Nat.centralBinom (i + 1)) / (↑i + 1)
h₂ : ↑(Nat.centralBinom (n - i + 1)) = (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) / (↑n - ↑i + 1)
h₃ : (↑i + 1) * ↑(Nat.centralBinom (i + 1)) = 2 * (2 * ↑i + 1) * ↑(Nat.centralBinom i)
⊢ (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) = 2 * (2 * (↑n - ↑i) + 1) * ↑(Nat.centralBinom (n - i))
[PROOFSTEP]
exact_mod_cast Nat.succ_mul_centralBinom_succ (n - i)
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
l₄ : ↑n - ↑i + 1 ≠ 0
h₁ : ↑(Nat.centralBinom (i + 1)) = (↑i + 1) * ↑(Nat.centralBinom (i + 1)) / (↑i + 1)
h₂ : ↑(Nat.centralBinom (n - i + 1)) = (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) / (↑n - ↑i + 1)
h₃ : (↑i + 1) * ↑(Nat.centralBinom (i + 1)) = 2 * (2 * ↑i + 1) * ↑(Nat.centralBinom i)
h₄ : (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) = 2 * (2 * (↑n - ↑i) + 1) * ↑(Nat.centralBinom (n - i))
⊢ gosperCatalan (n + 1) (i + 1) - gosperCatalan (n + 1) i =
↑(Nat.centralBinom i) / (↑i + 1) * ↑(Nat.centralBinom (n - i)) / (↑n - ↑i + 1)
[PROOFSTEP]
simp only [gosperCatalan]
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
l₄ : ↑n - ↑i + 1 ≠ 0
h₁ : ↑(Nat.centralBinom (i + 1)) = (↑i + 1) * ↑(Nat.centralBinom (i + 1)) / (↑i + 1)
h₂ : ↑(Nat.centralBinom (n - i + 1)) = (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) / (↑n - ↑i + 1)
h₃ : (↑i + 1) * ↑(Nat.centralBinom (i + 1)) = 2 * (2 * ↑i + 1) * ↑(Nat.centralBinom i)
h₄ : (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) = 2 * (2 * (↑n - ↑i) + 1) * ↑(Nat.centralBinom (n - i))
⊢ ↑(Nat.centralBinom (i + 1)) * ↑(Nat.centralBinom (n + 1 - (i + 1))) * (2 * ↑(i + 1) - ↑(n + 1)) /
(2 * ↑(n + 1) * (↑(n + 1) + 1)) -
↑(Nat.centralBinom i) * ↑(Nat.centralBinom (n + 1 - i)) * (2 * ↑i - ↑(n + 1)) / (2 * ↑(n + 1) * (↑(n + 1) + 1)) =
↑(Nat.centralBinom i) / (↑i + 1) * ↑(Nat.centralBinom (n - i)) / (↑n - ↑i + 1)
[PROOFSTEP]
push_cast
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
l₄ : ↑n - ↑i + 1 ≠ 0
h₁ : ↑(Nat.centralBinom (i + 1)) = (↑i + 1) * ↑(Nat.centralBinom (i + 1)) / (↑i + 1)
h₂ : ↑(Nat.centralBinom (n - i + 1)) = (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) / (↑n - ↑i + 1)
h₃ : (↑i + 1) * ↑(Nat.centralBinom (i + 1)) = 2 * (2 * ↑i + 1) * ↑(Nat.centralBinom i)
h₄ : (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) = 2 * (2 * (↑n - ↑i) + 1) * ↑(Nat.centralBinom (n - i))
⊢ ↑(Nat.centralBinom (i + 1)) * ↑(Nat.centralBinom (n + 1 - (i + 1))) * (2 * (↑i + 1) - (↑n + 1)) /
(2 * (↑n + 1) * (↑n + 1 + 1)) -
↑(Nat.centralBinom i) * ↑(Nat.centralBinom (n + 1 - i)) * (2 * ↑i - (↑n + 1)) / (2 * (↑n + 1) * (↑n + 1 + 1)) =
↑(Nat.centralBinom i) / (↑i + 1) * ↑(Nat.centralBinom (n - i)) / (↑n - ↑i + 1)
[PROOFSTEP]
rw [show n + 1 - i = n - i + 1 by rw [Nat.add_comm (n - i) 1, ← (Nat.add_sub_assoc h 1), add_comm]]
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
l₄ : ↑n - ↑i + 1 ≠ 0
h₁ : ↑(Nat.centralBinom (i + 1)) = (↑i + 1) * ↑(Nat.centralBinom (i + 1)) / (↑i + 1)
h₂ : ↑(Nat.centralBinom (n - i + 1)) = (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) / (↑n - ↑i + 1)
h₃ : (↑i + 1) * ↑(Nat.centralBinom (i + 1)) = 2 * (2 * ↑i + 1) * ↑(Nat.centralBinom i)
h₄ : (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) = 2 * (2 * (↑n - ↑i) + 1) * ↑(Nat.centralBinom (n - i))
⊢ n + 1 - i = n - i + 1
[PROOFSTEP]
rw [Nat.add_comm (n - i) 1, ← (Nat.add_sub_assoc h 1), add_comm]
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
l₄ : ↑n - ↑i + 1 ≠ 0
h₁ : ↑(Nat.centralBinom (i + 1)) = (↑i + 1) * ↑(Nat.centralBinom (i + 1)) / (↑i + 1)
h₂ : ↑(Nat.centralBinom (n - i + 1)) = (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) / (↑n - ↑i + 1)
h₃ : (↑i + 1) * ↑(Nat.centralBinom (i + 1)) = 2 * (2 * ↑i + 1) * ↑(Nat.centralBinom i)
h₄ : (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) = 2 * (2 * (↑n - ↑i) + 1) * ↑(Nat.centralBinom (n - i))
⊢ ↑(Nat.centralBinom (i + 1)) * ↑(Nat.centralBinom (n + 1 - (i + 1))) * (2 * (↑i + 1) - (↑n + 1)) /
(2 * (↑n + 1) * (↑n + 1 + 1)) -
↑(Nat.centralBinom i) * ↑(Nat.centralBinom (n - i + 1)) * (2 * ↑i - (↑n + 1)) / (2 * (↑n + 1) * (↑n + 1 + 1)) =
↑(Nat.centralBinom i) / (↑i + 1) * ↑(Nat.centralBinom (n - i)) / (↑n - ↑i + 1)
[PROOFSTEP]
rw [h₁, h₂, h₃, h₄]
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
l₄ : ↑n - ↑i + 1 ≠ 0
h₁ : ↑(Nat.centralBinom (i + 1)) = (↑i + 1) * ↑(Nat.centralBinom (i + 1)) / (↑i + 1)
h₂ : ↑(Nat.centralBinom (n - i + 1)) = (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) / (↑n - ↑i + 1)
h₃ : (↑i + 1) * ↑(Nat.centralBinom (i + 1)) = 2 * (2 * ↑i + 1) * ↑(Nat.centralBinom i)
h₄ : (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) = 2 * (2 * (↑n - ↑i) + 1) * ↑(Nat.centralBinom (n - i))
⊢ 2 * (2 * ↑i + 1) * ↑(Nat.centralBinom i) / (↑i + 1) * ↑(Nat.centralBinom (n + 1 - (i + 1))) *
(2 * (↑i + 1) - (↑n + 1)) /
(2 * (↑n + 1) * (↑n + 1 + 1)) -
↑(Nat.centralBinom i) * (2 * (2 * (↑n - ↑i) + 1) * ↑(Nat.centralBinom (n - i)) / (↑n - ↑i + 1)) *
(2 * ↑i - (↑n + 1)) /
(2 * (↑n + 1) * (↑n + 1 + 1)) =
↑(Nat.centralBinom i) / (↑i + 1) * ↑(Nat.centralBinom (n - i)) / (↑n - ↑i + 1)
[PROOFSTEP]
field_simp
[GOAL]
n i : ℕ
h : i ≤ n
l₁ : ↑n + 1 ≠ 0
l₂ : ↑n + 1 + 1 ≠ 0
l₃ : ↑i + 1 ≠ 0
l₄ : ↑n - ↑i + 1 ≠ 0
h₁ : ↑(Nat.centralBinom (i + 1)) = (↑i + 1) * ↑(Nat.centralBinom (i + 1)) / (↑i + 1)
h₂ : ↑(Nat.centralBinom (n - i + 1)) = (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) / (↑n - ↑i + 1)
h₃ : (↑i + 1) * ↑(Nat.centralBinom (i + 1)) = 2 * (2 * ↑i + 1) * ↑(Nat.centralBinom i)
h₄ : (↑n - ↑i + 1) * ↑(Nat.centralBinom (n - i + 1)) = 2 * (2 * (↑n - ↑i) + 1) * ↑(Nat.centralBinom (n - i))
⊢ (2 * (2 * ↑i + 1) * ↑(Nat.centralBinom i) * ↑(Nat.centralBinom (n - i)) * (2 * (↑i + 1) - (↑n + 1)) *
((↑n - ↑i + 1) * (2 * (↑n + 1) * (↑n + 1 + 1))) -
(↑i + 1) * (2 * (↑n + 1) * (↑n + 1 + 1)) *
(↑(Nat.centralBinom i) * (2 * (2 * (↑n - ↑i) + 1) * ↑(Nat.centralBinom (n - i))) * (2 * ↑i - (↑n + 1)))) *
((↑i + 1) * (↑n - ↑i + 1)) =
↑(Nat.centralBinom i) * ↑(Nat.centralBinom (n - i)) *
((↑i + 1) * (2 * (↑n + 1) * (↑n + 1 + 1)) * ((↑n - ↑i + 1) * (2 * (↑n + 1) * (↑n + 1 + 1))))
[PROOFSTEP]
ring
[GOAL]
n : ℕ
⊢ gosperCatalan (n + 1) (n + 1) - gosperCatalan (n + 1) 0 = ↑(Nat.centralBinom (n + 1)) / (↑n + 2)
[PROOFSTEP]
have : (n : ℚ) + 1 ≠ 0 := by norm_cast; exact n.succ_ne_zero
[GOAL]
n : ℕ
⊢ ↑n + 1 ≠ 0
[PROOFSTEP]
norm_cast
[GOAL]
n : ℕ
⊢ ¬n + 1 = 0
[PROOFSTEP]
exact n.succ_ne_zero
[GOAL]
n : ℕ
this : ↑n + 1 ≠ 0
⊢ gosperCatalan (n + 1) (n + 1) - gosperCatalan (n + 1) 0 = ↑(Nat.centralBinom (n + 1)) / (↑n + 2)
[PROOFSTEP]
have : (n : ℚ) + 1 + 1 ≠ 0 := by norm_cast; exact (n + 1).succ_ne_zero
[GOAL]
n : ℕ
this : ↑n + 1 ≠ 0
⊢ ↑n + 1 + 1 ≠ 0
[PROOFSTEP]
norm_cast
[GOAL]
n : ℕ
this : ↑n + 1 ≠ 0
⊢ ¬n + 1 + 1 = 0
[PROOFSTEP]
exact (n + 1).succ_ne_zero
[GOAL]
n : ℕ
this✝ : ↑n + 1 ≠ 0
this : ↑n + 1 + 1 ≠ 0
⊢ gosperCatalan (n + 1) (n + 1) - gosperCatalan (n + 1) 0 = ↑(Nat.centralBinom (n + 1)) / (↑n + 2)
[PROOFSTEP]
have h : (n : ℚ) + 2 ≠ 0 := by norm_cast; exact (n + 1).succ_ne_zero
[GOAL]
n : ℕ
this✝ : ↑n + 1 ≠ 0
this : ↑n + 1 + 1 ≠ 0
⊢ ↑n + 2 ≠ 0
[PROOFSTEP]
norm_cast
[GOAL]
n : ℕ
this✝ : ↑n + 1 ≠ 0
this : ↑n + 1 + 1 ≠ 0
⊢ ¬n + 2 = 0
[PROOFSTEP]
exact (n + 1).succ_ne_zero
[GOAL]
n : ℕ
this✝ : ↑n + 1 ≠ 0
this : ↑n + 1 + 1 ≠ 0
h : ↑n + 2 ≠ 0
⊢ gosperCatalan (n + 1) (n + 1) - gosperCatalan (n + 1) 0 = ↑(Nat.centralBinom (n + 1)) / (↑n + 2)
[PROOFSTEP]
simp only [gosperCatalan, Nat.sub_zero, Nat.centralBinom_zero, Nat.sub_self]
[GOAL]
n : ℕ
this✝ : ↑n + 1 ≠ 0
this : ↑n + 1 + 1 ≠ 0
h : ↑n + 2 ≠ 0
⊢ ↑(Nat.centralBinom (n + 1)) * ↑1 * (2 * ↑(n + 1) - ↑(n + 1)) / (2 * ↑(n + 1) * (↑(n + 1) + 1)) -
↑1 * ↑(Nat.centralBinom (n + 1)) * (2 * ↑0 - ↑(n + 1)) / (2 * ↑(n + 1) * (↑(n + 1) + 1)) =
↑(Nat.centralBinom (n + 1)) / (↑n + 2)
[PROOFSTEP]
field_simp
[GOAL]
n : ℕ
this✝ : ↑n + 1 ≠ 0
this : ↑n + 1 + 1 ≠ 0
h : ↑n + 2 ≠ 0
⊢ (↑(Nat.centralBinom (n + 1)) * (2 * (↑n + 1) - (↑n + 1)) - ↑(Nat.centralBinom (n + 1)) * (-1 + -↑n)) * (↑n + 2) =
↑(Nat.centralBinom (n + 1)) * (2 * (↑n + 1) * (↑n + 1 + 1))
[PROOFSTEP]
ring
[GOAL]
n : ℕ
⊢ catalan n = Nat.centralBinom n / (n + 1)
[PROOFSTEP]
suffices (catalan n : ℚ) = Nat.centralBinom n / (n + 1)
by
have h := Nat.succ_dvd_centralBinom n
exact_mod_cast this
[GOAL]
n : ℕ
this : ↑(catalan n) = ↑(Nat.centralBinom n) / (↑n + 1)
⊢ catalan n = Nat.centralBinom n / (n + 1)
[PROOFSTEP]
have h := Nat.succ_dvd_centralBinom n
[GOAL]
n : ℕ
this : ↑(catalan n) = ↑(Nat.centralBinom n) / (↑n + 1)
h : n + 1 ∣ Nat.centralBinom n
⊢ catalan n = Nat.centralBinom n / (n + 1)
[PROOFSTEP]
exact_mod_cast this
[GOAL]
n : ℕ
⊢ ↑(catalan n) = ↑(Nat.centralBinom n) / (↑n + 1)
[PROOFSTEP]
induction' n using Nat.case_strong_induction_on with d hd
[GOAL]
case hz
⊢ ↑(catalan 0) = ↑(Nat.centralBinom 0) / (↑0 + 1)
[PROOFSTEP]
simp
[GOAL]
case hi
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
⊢ ↑(catalan (Nat.succ d)) = ↑(Nat.centralBinom (Nat.succ d)) / (↑(Nat.succ d) + 1)
[PROOFSTEP]
simp_rw [catalan_succ, Nat.cast_sum, Nat.cast_mul]
[GOAL]
case hi
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
⊢ ∑ x : Fin (Nat.succ d), ↑(catalan ↑x) * ↑(catalan (d - ↑x)) = ↑(Nat.centralBinom (Nat.succ d)) / (↑(Nat.succ d) + 1)
[PROOFSTEP]
trans (∑ i : Fin d.succ, Nat.centralBinom i / (i + 1) * (Nat.centralBinom (d - i) / (d - i + 1)) : ℚ)
[GOAL]
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
⊢ ∑ x : Fin (Nat.succ d), ↑(catalan ↑x) * ↑(catalan (d - ↑x)) =
∑ i : Fin (Nat.succ d), ↑(Nat.centralBinom ↑i) / (↑↑i + 1) * (↑(Nat.centralBinom (d - ↑i)) / (↑d - ↑↑i + 1))
[PROOFSTEP]
congr
[GOAL]
case e_f
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
⊢ (fun x => ↑(catalan ↑x) * ↑(catalan (d - ↑x))) = fun i =>
↑(Nat.centralBinom ↑i) / (↑↑i + 1) * (↑(Nat.centralBinom (d - ↑i)) / (↑d - ↑↑i + 1))
[PROOFSTEP]
ext1 x
[GOAL]
case e_f.h
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
x : Fin (Nat.succ d)
⊢ ↑(catalan ↑x) * ↑(catalan (d - ↑x)) =
↑(Nat.centralBinom ↑x) / (↑↑x + 1) * (↑(Nat.centralBinom (d - ↑x)) / (↑d - ↑↑x + 1))
[PROOFSTEP]
have m_le_d : x.val ≤ d := by apply Nat.le_of_lt_succ; apply x.2
[GOAL]
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
x : Fin (Nat.succ d)
⊢ ↑x ≤ d
[PROOFSTEP]
apply Nat.le_of_lt_succ
[GOAL]
case a
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
x : Fin (Nat.succ d)
⊢ ↑x < Nat.succ d
[PROOFSTEP]
apply x.2
[GOAL]
case e_f.h
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
x : Fin (Nat.succ d)
m_le_d : ↑x ≤ d
⊢ ↑(catalan ↑x) * ↑(catalan (d - ↑x)) =
↑(Nat.centralBinom ↑x) / (↑↑x + 1) * (↑(Nat.centralBinom (d - ↑x)) / (↑d - ↑↑x + 1))
[PROOFSTEP]
have d_minus_x_le_d : (d - x.val) ≤ d := tsub_le_self
[GOAL]
case e_f.h
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
x : Fin (Nat.succ d)
m_le_d : ↑x ≤ d
d_minus_x_le_d : d - ↑x ≤ d
⊢ ↑(catalan ↑x) * ↑(catalan (d - ↑x)) =
↑(Nat.centralBinom ↑x) / (↑↑x + 1) * (↑(Nat.centralBinom (d - ↑x)) / (↑d - ↑↑x + 1))
[PROOFSTEP]
rw [hd _ m_le_d, hd _ d_minus_x_le_d]
[GOAL]
case e_f.h
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
x : Fin (Nat.succ d)
m_le_d : ↑x ≤ d
d_minus_x_le_d : d - ↑x ≤ d
⊢ ↑(Nat.centralBinom ↑x) / (↑↑x + 1) * (↑(Nat.centralBinom (d - ↑x)) / (↑(d - ↑x) + 1)) =
↑(Nat.centralBinom ↑x) / (↑↑x + 1) * (↑(Nat.centralBinom (d - ↑x)) / (↑d - ↑↑x + 1))
[PROOFSTEP]
norm_cast
[GOAL]
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
⊢ ∑ i : Fin (Nat.succ d), ↑(Nat.centralBinom ↑i) / (↑↑i + 1) * (↑(Nat.centralBinom (d - ↑i)) / (↑d - ↑↑i + 1)) =
↑(Nat.centralBinom (Nat.succ d)) / (↑(Nat.succ d) + 1)
[PROOFSTEP]
trans (∑ i : Fin d.succ, (gosperCatalan (d + 1) (i + 1) - gosperCatalan (d + 1) i))
[GOAL]
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
⊢ ∑ i : Fin (Nat.succ d), ↑(Nat.centralBinom ↑i) / (↑↑i + 1) * (↑(Nat.centralBinom (d - ↑i)) / (↑d - ↑↑i + 1)) =
∑ i : Fin (Nat.succ d), (gosperCatalan (d + 1) (↑i + 1) - gosperCatalan (d + 1) ↑i)
[PROOFSTEP]
refine' sum_congr rfl fun i _ => _
[GOAL]
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
i : Fin (Nat.succ d)
x✝ : i ∈ univ
⊢ ↑(Nat.centralBinom ↑i) / (↑↑i + 1) * (↑(Nat.centralBinom (d - ↑i)) / (↑d - ↑↑i + 1)) =
gosperCatalan (d + 1) (↑i + 1) - gosperCatalan (d + 1) ↑i
[PROOFSTEP]
rw [gosper_trick i.is_le, mul_div]
[GOAL]
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
⊢ ∑ i : Fin (Nat.succ d), (gosperCatalan (d + 1) (↑i + 1) - gosperCatalan (d + 1) ↑i) =
↑(Nat.centralBinom (Nat.succ d)) / (↑(Nat.succ d) + 1)
[PROOFSTEP]
rw [← sum_range fun i => gosperCatalan (d + 1) (i + 1) - gosperCatalan (d + 1) i, sum_range_sub, Nat.succ_eq_add_one]
[GOAL]
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
⊢ gosperCatalan (d + 1) (d + 1) - gosperCatalan (d + 1) 0 = ↑(Nat.centralBinom (d + 1)) / (↑(d + 1) + 1)
[PROOFSTEP]
rw [gosper_catalan_sub_eq_central_binom_div d]
[GOAL]
d : ℕ
hd : ∀ (m : ℕ), m ≤ d → ↑(catalan m) = ↑(Nat.centralBinom m) / (↑m + 1)
⊢ ↑(Nat.centralBinom (d + 1)) / (↑d + 2) = ↑(Nat.centralBinom (d + 1)) / (↑(d + 1) + 1)
[PROOFSTEP]
norm_cast
[GOAL]
⊢ catalan 2 = 2
[PROOFSTEP]
unfold catalan
[GOAL]
⊢ ∑ i : Fin (Nat.succ 1), catalan ↑i * catalan (1 - ↑i) = 2
[PROOFSTEP]
rfl
[GOAL]
⊢ catalan 3 = 5
[PROOFSTEP]
unfold catalan
[GOAL]
⊢ ∑ i : Fin (Nat.succ 2), catalan ↑i * catalan (2 - ↑i) = 5
[PROOFSTEP]
rfl
[GOAL]
a b : Finset (Tree Unit)
x✝¹ x✝ : Tree Unit × Tree Unit
x₁ x₂ y₁ y₂ : Tree Unit
h : (fun x => node () x.fst x.snd) (x₁, x₂) = (fun x => node () x.fst x.snd) (y₁, y₂)
⊢ (x₁, x₂) = (y₁, y₂)
[PROOFSTEP]
simpa using h
[GOAL]
n : ℕ
ijh : { x // x ∈ Nat.antidiagonal n }
⊢ (invImage (fun a => sizeOf a) instWellFoundedRelation).1 (↑ijh).fst (Nat.succ n)
[PROOFSTEP]
simp_wf
[GOAL]
n : ℕ
ijh : { x // x ∈ Nat.antidiagonal n }
⊢ (↑ijh).fst < Nat.succ n
[PROOFSTEP]
try exact Nat.lt_succ_of_le (fst_le ijh.2)
[GOAL]
n : ℕ
ijh : { x // x ∈ Nat.antidiagonal n }
⊢ (↑ijh).fst < Nat.succ n
[PROOFSTEP]
exact Nat.lt_succ_of_le (fst_le ijh.2)
[GOAL]
[PROOFSTEP]
try exact Nat.lt_succ_of_le (snd_le ijh.2)
[GOAL]
[PROOFSTEP]
exact Nat.lt_succ_of_le (snd_le ijh.2)
[GOAL]
n : ℕ
ijh : { x // x ∈ Nat.antidiagonal n }
⊢ (invImage (fun a => sizeOf a) instWellFoundedRelation).1 (↑ijh).snd (Nat.succ n)
[PROOFSTEP]
simp_wf
[GOAL]
n : ℕ
ijh : { x // x ∈ Nat.antidiagonal n }
⊢ (↑ijh).snd < Nat.succ n
[PROOFSTEP]
try exact Nat.lt_succ_of_le (fst_le ijh.2)
[GOAL]
n : ℕ
ijh : { x // x ∈ Nat.antidiagonal n }
⊢ (↑ijh).snd < Nat.succ n
[PROOFSTEP]
exact Nat.lt_succ_of_le (fst_le ijh.2)
[GOAL]
n : ℕ
ijh : { x // x ∈ Nat.antidiagonal n }
⊢ (↑ijh).snd < Nat.succ n
[PROOFSTEP]
try exact Nat.lt_succ_of_le (snd_le ijh.2)
[GOAL]
n : ℕ
ijh : { x // x ∈ Nat.antidiagonal n }
⊢ (↑ijh).snd < Nat.succ n
[PROOFSTEP]
exact Nat.lt_succ_of_le (snd_le ijh.2)
[GOAL]
⊢ treesOfNumNodesEq 0 = {nil}
[PROOFSTEP]
rw [treesOfNumNodesEq]
[GOAL]
n : ℕ
⊢ treesOfNumNodesEq (n + 1) =
Finset.biUnion (Nat.antidiagonal n) fun ij => pairwiseNode (treesOfNumNodesEq ij.fst) (treesOfNumNodesEq ij.snd)
[PROOFSTEP]
rw [treesOfNumNodesEq]
[GOAL]
n : ℕ
⊢ (Finset.biUnion (attach (Nat.antidiagonal n)) fun ijh =>
pairwiseNode (treesOfNumNodesEq (↑ijh).fst) (treesOfNumNodesEq (↑ijh).snd)) =
Finset.biUnion (Nat.antidiagonal n) fun ij => pairwiseNode (treesOfNumNodesEq ij.fst) (treesOfNumNodesEq ij.snd)
[PROOFSTEP]
ext
[GOAL]
case a
n : ℕ
a✝ : Tree Unit
⊢ (a✝ ∈
Finset.biUnion (attach (Nat.antidiagonal n)) fun ijh =>
pairwiseNode (treesOfNumNodesEq (↑ijh).fst) (treesOfNumNodesEq (↑ijh).snd)) ↔
a✝ ∈
Finset.biUnion (Nat.antidiagonal n) fun ij => pairwiseNode (treesOfNumNodesEq ij.fst) (treesOfNumNodesEq ij.snd)
[PROOFSTEP]
simp
[GOAL]
x : Tree Unit
n : ℕ
⊢ x ∈ treesOfNumNodesEq n ↔ numNodes x = n
[PROOFSTEP]
induction x using Tree.unitRecOn generalizing n
[GOAL]
case base
n : ℕ
⊢ nil ∈ treesOfNumNodesEq n ↔ numNodes nil = n
[PROOFSTEP]
cases n
[GOAL]
case ind
x✝ y✝ : Tree Unit
a✝¹ : ∀ {n : ℕ}, x✝ ∈ treesOfNumNodesEq n ↔ numNodes x✝ = n
a✝ : ∀ {n : ℕ}, y✝ ∈ treesOfNumNodesEq n ↔ numNodes y✝ = n
n : ℕ
⊢ node () x✝ y✝ ∈ treesOfNumNodesEq n ↔ numNodes (node () x✝ y✝) = n
[PROOFSTEP]
cases n
[GOAL]
case base.zero
⊢ nil ∈ treesOfNumNodesEq Nat.zero ↔ numNodes nil = Nat.zero
[PROOFSTEP]
simp [treesOfNumNodesEq_succ, Nat.succ_eq_add_one, *]
[GOAL]
case base.succ
n✝ : ℕ
⊢ nil ∈ treesOfNumNodesEq (Nat.succ n✝) ↔ numNodes nil = Nat.succ n✝
[PROOFSTEP]
simp [treesOfNumNodesEq_succ, Nat.succ_eq_add_one, *]
[GOAL]
case ind.zero
x✝ y✝ : Tree Unit
a✝¹ : ∀ {n : ℕ}, x✝ ∈ treesOfNumNodesEq n ↔ numNodes x✝ = n
a✝ : ∀ {n : ℕ}, y✝ ∈ treesOfNumNodesEq n ↔ numNodes y✝ = n
⊢ node () x✝ y✝ ∈ treesOfNumNodesEq Nat.zero ↔ numNodes (node () x✝ y✝) = Nat.zero
[PROOFSTEP]
simp [treesOfNumNodesEq_succ, Nat.succ_eq_add_one, *]
[GOAL]
case ind.succ
x✝ y✝ : Tree Unit
a✝¹ : ∀ {n : ℕ}, x✝ ∈ treesOfNumNodesEq n ↔ numNodes x✝ = n
a✝ : ∀ {n : ℕ}, y✝ ∈ treesOfNumNodesEq n ↔ numNodes y✝ = n
n✝ : ℕ
⊢ node () x✝ y✝ ∈ treesOfNumNodesEq (Nat.succ n✝) ↔ numNodes (node () x✝ y✝) = Nat.succ n✝
[PROOFSTEP]
simp [treesOfNumNodesEq_succ, Nat.succ_eq_add_one, *]
[GOAL]
case base.succ
n✝ : ℕ
⊢ ¬0 = n✝ + 1
[PROOFSTEP]
exact (Nat.succ_ne_zero _).symm
[GOAL]
n : ℕ
⊢ ∀ (x : Tree Unit), x ∈ ↑(treesOfNumNodesEq n) ↔ x ∈ {x | numNodes x = n}
[PROOFSTEP]
simp
[GOAL]
n : ℕ
⊢ card (treesOfNumNodesEq n) = catalan n
[PROOFSTEP]
induction' n using Nat.case_strong_induction_on with n ih
[GOAL]
case hz
⊢ card (treesOfNumNodesEq 0) = catalan 0
[PROOFSTEP]
simp
[GOAL]
case hi
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
⊢ card (treesOfNumNodesEq (Nat.succ n)) = catalan (Nat.succ n)
[PROOFSTEP]
rw [treesOfNumNodesEq_succ, card_biUnion, catalan_succ']
[GOAL]
case hi
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
⊢ ∑ u in Nat.antidiagonal n, card (pairwiseNode (treesOfNumNodesEq u.fst) (treesOfNumNodesEq u.snd)) =
∑ ij in Nat.antidiagonal n, catalan ij.fst * catalan ij.snd
[PROOFSTEP]
apply sum_congr rfl
[GOAL]
case hi
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
⊢ ∀ (x : ℕ × ℕ),
x ∈ Nat.antidiagonal n →
card (pairwiseNode (treesOfNumNodesEq x.fst) (treesOfNumNodesEq x.snd)) = catalan x.fst * catalan x.snd
[PROOFSTEP]
rintro ⟨i, j⟩ H
[GOAL]
case hi.mk
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
i j : ℕ
H : (i, j) ∈ Nat.antidiagonal n
⊢ card (pairwiseNode (treesOfNumNodesEq (i, j).fst) (treesOfNumNodesEq (i, j).snd)) =
catalan (i, j).fst * catalan (i, j).snd
[PROOFSTEP]
rw [card_map, card_product, ih _ (fst_le H), ih _ (snd_le H)]
[GOAL]
case hi
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
⊢ ∀ (x : ℕ × ℕ),
x ∈ Nat.antidiagonal n →
∀ (y : ℕ × ℕ),
y ∈ Nat.antidiagonal n →
x ≠ y →
Disjoint (pairwiseNode (treesOfNumNodesEq x.fst) (treesOfNumNodesEq x.snd))
(pairwiseNode (treesOfNumNodesEq y.fst) (treesOfNumNodesEq y.snd))
[PROOFSTEP]
simp_rw [disjoint_left]
[GOAL]
case hi
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
⊢ ∀ (x : ℕ × ℕ),
x ∈ Nat.antidiagonal n →
∀ (y : ℕ × ℕ),
y ∈ Nat.antidiagonal n →
x ≠ y →
∀ ⦃a : Tree Unit⦄,
a ∈ pairwiseNode (treesOfNumNodesEq x.fst) (treesOfNumNodesEq x.snd) →
¬a ∈ pairwiseNode (treesOfNumNodesEq y.fst) (treesOfNumNodesEq y.snd)
[PROOFSTEP]
rintro ⟨i, j⟩ _ ⟨i', j'⟩
_
-- Porting note: was clear * -; tidy
[GOAL]
case hi.mk.mk
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
i j : ℕ
a✝¹ : (i, j) ∈ Nat.antidiagonal n
i' j' : ℕ
a✝ : (i', j') ∈ Nat.antidiagonal n
⊢ (i, j) ≠ (i', j') →
∀ ⦃a : Tree Unit⦄,
a ∈ pairwiseNode (treesOfNumNodesEq (i, j).fst) (treesOfNumNodesEq (i, j).snd) →
¬a ∈ pairwiseNode (treesOfNumNodesEq (i', j').fst) (treesOfNumNodesEq (i', j').snd)
[PROOFSTEP]
intros h a
[GOAL]
case hi.mk.mk
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
i j : ℕ
a✝¹ : (i, j) ∈ Nat.antidiagonal n
i' j' : ℕ
a✝ : (i', j') ∈ Nat.antidiagonal n
h : (i, j) ≠ (i', j')
a : Tree Unit
⊢ a ∈ pairwiseNode (treesOfNumNodesEq (i, j).fst) (treesOfNumNodesEq (i, j).snd) →
¬a ∈ pairwiseNode (treesOfNumNodesEq (i', j').fst) (treesOfNumNodesEq (i', j').snd)
[PROOFSTEP]
cases' a with a l r
[GOAL]
case hi.mk.mk.nil
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
i j : ℕ
a✝¹ : (i, j) ∈ Nat.antidiagonal n
i' j' : ℕ
a✝ : (i', j') ∈ Nat.antidiagonal n
h : (i, j) ≠ (i', j')
⊢ nil ∈ pairwiseNode (treesOfNumNodesEq (i, j).fst) (treesOfNumNodesEq (i, j).snd) →
¬nil ∈ pairwiseNode (treesOfNumNodesEq (i', j').fst) (treesOfNumNodesEq (i', j').snd)
[PROOFSTEP]
intro h
[GOAL]
case hi.mk.mk.nil
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
i j : ℕ
a✝¹ : (i, j) ∈ Nat.antidiagonal n
i' j' : ℕ
a✝ : (i', j') ∈ Nat.antidiagonal n
h✝ : (i, j) ≠ (i', j')
h : nil ∈ pairwiseNode (treesOfNumNodesEq (i, j).fst) (treesOfNumNodesEq (i, j).snd)
⊢ ¬nil ∈ pairwiseNode (treesOfNumNodesEq (i', j').fst) (treesOfNumNodesEq (i', j').snd)
[PROOFSTEP]
simp at h
[GOAL]
case hi.mk.mk.node
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
i j : ℕ
a✝¹ : (i, j) ∈ Nat.antidiagonal n
i' j' : ℕ
a✝ : (i', j') ∈ Nat.antidiagonal n
h : (i, j) ≠ (i', j')
a : Unit
l r : Tree Unit
⊢ node a l r ∈ pairwiseNode (treesOfNumNodesEq (i, j).fst) (treesOfNumNodesEq (i, j).snd) →
¬node a l r ∈ pairwiseNode (treesOfNumNodesEq (i', j').fst) (treesOfNumNodesEq (i', j').snd)
[PROOFSTEP]
intro h1 h2
[GOAL]
case hi.mk.mk.node
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
i j : ℕ
a✝¹ : (i, j) ∈ Nat.antidiagonal n
i' j' : ℕ
a✝ : (i', j') ∈ Nat.antidiagonal n
h : (i, j) ≠ (i', j')
a : Unit
l r : Tree Unit
h1 : node a l r ∈ pairwiseNode (treesOfNumNodesEq (i, j).fst) (treesOfNumNodesEq (i, j).snd)
h2 : node a l r ∈ pairwiseNode (treesOfNumNodesEq (i', j').fst) (treesOfNumNodesEq (i', j').snd)
⊢ False
[PROOFSTEP]
apply h
[GOAL]
case hi.mk.mk.node
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
i j : ℕ
a✝¹ : (i, j) ∈ Nat.antidiagonal n
i' j' : ℕ
a✝ : (i', j') ∈ Nat.antidiagonal n
h : (i, j) ≠ (i', j')
a : Unit
l r : Tree Unit
h1 : node a l r ∈ pairwiseNode (treesOfNumNodesEq (i, j).fst) (treesOfNumNodesEq (i, j).snd)
h2 : node a l r ∈ pairwiseNode (treesOfNumNodesEq (i', j').fst) (treesOfNumNodesEq (i', j').snd)
⊢ (i, j) = (i', j')
[PROOFSTEP]
trans (numNodes l, numNodes r)
[GOAL]
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
i j : ℕ
a✝¹ : (i, j) ∈ Nat.antidiagonal n
i' j' : ℕ
a✝ : (i', j') ∈ Nat.antidiagonal n
h : (i, j) ≠ (i', j')
a : Unit
l r : Tree Unit
h1 : node a l r ∈ pairwiseNode (treesOfNumNodesEq (i, j).fst) (treesOfNumNodesEq (i, j).snd)
h2 : node a l r ∈ pairwiseNode (treesOfNumNodesEq (i', j').fst) (treesOfNumNodesEq (i', j').snd)
⊢ (i, j) = (numNodes l, numNodes r)
[PROOFSTEP]
simp at h1
[GOAL]
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
i j : ℕ
a✝¹ : (i, j) ∈ Nat.antidiagonal n
i' j' : ℕ
a✝ : (i', j') ∈ Nat.antidiagonal n
h : (i, j) ≠ (i', j')
a : Unit
l r : Tree Unit
h2 : node a l r ∈ pairwiseNode (treesOfNumNodesEq (i', j').fst) (treesOfNumNodesEq (i', j').snd)
h1 : numNodes l = i ∧ numNodes r = j
⊢ (i, j) = (numNodes l, numNodes r)
[PROOFSTEP]
simp [h1]
[GOAL]
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
i j : ℕ
a✝¹ : (i, j) ∈ Nat.antidiagonal n
i' j' : ℕ
a✝ : (i', j') ∈ Nat.antidiagonal n
h : (i, j) ≠ (i', j')
a : Unit
l r : Tree Unit
h1 : node a l r ∈ pairwiseNode (treesOfNumNodesEq (i, j).fst) (treesOfNumNodesEq (i, j).snd)
h2 : node a l r ∈ pairwiseNode (treesOfNumNodesEq (i', j').fst) (treesOfNumNodesEq (i', j').snd)
⊢ (numNodes l, numNodes r) = (i', j')
[PROOFSTEP]
simp at h2
[GOAL]
n : ℕ
ih : ∀ (m : ℕ), m ≤ n → card (treesOfNumNodesEq m) = catalan m
i j : ℕ
a✝¹ : (i, j) ∈ Nat.antidiagonal n
i' j' : ℕ
a✝ : (i', j') ∈ Nat.antidiagonal n
h : (i, j) ≠ (i', j')
a : Unit
l r : Tree Unit
h1 : node a l r ∈ pairwiseNode (treesOfNumNodesEq (i, j).fst) (treesOfNumNodesEq (i, j).snd)
h2 : numNodes l = i' ∧ numNodes r = j'
⊢ (numNodes l, numNodes r) = (i', j')
[PROOFSTEP]
simp [h2]
|
rebol []
append XFL-action-rules [
DOMDocument-upd [
[
"DOMDocument" |
"symbols"
](
parse-xfl content
) |
"DOMTimeline" (
parse-xfl/act content 'DOMTimeline-upd
) |
"DOMBitmapItem" (
if any [
find Media-to-remove atts/("name")
0 = select Media-counter (atts/("name"))
] [
;ask ["removing:" mold atts]
append log_removed rejoin [atts/("name") tab atts/("href") lf]
error? try [delete join xfl-folder-new to-rebol-file as-string utf8/decode atts/("href")]
error? try [delete join xfl-folder-new [%bin/ atts/("bitmapDataHRef")]]
clear current-node
]
) |
["media" | "timelines"] (
parse-xfl content
) |
"DOMSoundItem" (
if any [
0 = select Media-counter (atts/("name"))
] [
;ask ["removing:" mold atts]
append log_removed rejoin [atts/("name") tab atts/("href") lf]
error? try [delete join xfl-folder-new [%LIBRARY/ to-rebol-file as-string utf8/decode atts/("href")]]
error? try [delete join xfl-folder-new [%bin/ atts/("soundDataHRef")]]
clear current-node
]
) |
"Include" (
if 0 = select Symbol-counter (atts/("href")) [
;ask ["removing:" mold atts]
append log_removed rejoin [atts/("href") lf]
error? try [delete join xfl-folder-new [%LIBRARY/ to-rebol-file as-string utf8/decode atts/("href")]]
clear current-node
]
) |
"folders" |
"swatchLists" |
"extendedSwatchLists" |
"PrinterSettings" |
"publishHistory"
]
DOMSymbolItem-upd [
"DOMSymbolItem" (
tmp_isSymbolGraphic?: "graphic" = select atts "symbolType"
parse-xfl content
tmp_isSymbolGraphic?: none
) |
"timeline" (
parse-xfl/act content 'DOMTimeline-upd
)
]
DOMTimeline-upd [
[
"DOMTimeline" |
"layers" |
"frames" |
"DOMFrame" |
"elements" |
"DOMGroup" |
"members" |
"Actionscript"
] (
parse-xfl content
) |
"DOMLayer" (
;remove-atts atts ["current" | "isSelected"]
parse-xfl content
) |
"DOMShape" (
;remove-atts atts ["selected"]
ch: checksum mold content
parse-xfl/act content 'DOMShape-upd
current-node: nodes-stack/-1
;ask mold current-node
;probe nodes-stack/-5/2
;probe select nodes-stack/-5/2/2 "layerType"
if all [
false ;do not use this optimisation now
not tmp_isSymbolGraphic?
not in-guide?
not in-tween?
tmp: select shape-counter ch
tmp/1 > 2
] [
either tmp/3 [
;ask ["USINGSYMB:" ch tmp/1]
change current-node get-symbol-dom join "__symbol_" ch
][
;ask ["SHPUPD:" ch tmp/1]
change current-node get-symbol-dom shape-to-symbol current-node ch
tmp/3: true
]
]
;either tmp: select shape-counter ch: checksum mold content [
; tmp/1: tmp/1 + 1
;][ repend/only append shape-counter ch [1 content] ]
;ask ["CHCHCH" checksum mold content]
) |
"DOMSymbolInstance" (
) |
"DOMBitmapInstance" (
remove-atts atts ["selected"]
) |
"matrix" (
tmp_matrix: copy []
parse-xfl content
) |
"Matrix" (
append tmp_matrix atts
) |
"script" (
comment {
either all [
block? content
string? content/1
1 = length? content
][
insert content/1 "<![CDATA["
append content/1 "]]>"
][
ask ["SCRIPT???" mold current-node]
]
}
) |
"DOMDynamicText" |
"MorphShape" |
"SoundEnvelope" |
"tweens" |
"morphHintsList" |
"DOMStaticText" |
"transformationPoint" ;do nothing
]
DOMShape-upd [
"strokes" (
tmp_strokes: copy []
parse-xfl content
;print ["strokes:" mold tmp_strokes]
) |
"edges" (
used-BB-opt?: false
parse-xfl content
) |
"Edge" (
case [
all [used-BB-opt? find atts "cubics"] [clear current-node]
all [
;false
tmp: select atts "edges"
] [
;probe atts probe tmp_fills ask ""
fill0: select tmp_fills select atts "fillStyle0"
fill1: select tmp_fills select atts "fillStyle1"
fill0bmp: all [fill0 select fill0 "bitmapPath"]
fill1bmp: all [fill1 select fill1 "bitmapPath"]
;print [mold fill0bmp mold fill1bmp] ask ""
;probe tmp_fills
;probe atts
case [
;false
all [
fill1bmp
none? find noBB-fills fill1bmp
none? fill0
none? select atts "strokeStyle"
]
[
print ["USING BB 1" fill1bmp]
used-BB-opt?: true
probe bb: get-edges-BB tmp
x1: form-float round/to bb/1 .5
y1: form-float round/to bb/2 .5
x2: form-float round/to bb/3 .5
y2: form-float round/to bb/4 .5
clear tmp
insert tmp rejoin [
#"!" x1 #" " y1
#"|" x2 #" " y1
#"!" x2 #" " y1
#"|" x2 #" " y2
#"!" x2 #" " y2
#"|" x1 #" " y2
#"!" x1 #" " y2
#"|" x1 #" " y1
]
;probe atts
;ask ""
]
all [
fill0bmp
none? find noBB-fills fill0bmp
none? fill1
none? select atts "strokeStyle"
] [
used-BB-opt?: true
print ["USING BB 0" fill0bmp]
probe bb: get-edges-BB tmp
x1: form-float round/to bb/1 .5
y1: form-float round/to bb/2 .5
x2: form-float round/to bb/3 .5
y2: form-float round/to bb/4 .5
clear tmp
insert tmp rejoin [
#"!" x1 #" " y1
#"|" x1 #" " y2
#"!" x1 #" " y2
#"|" x2 #" " y2
#"!" x2 #" " y2
#"|" x2 #" " y1
#"!" x2 #" " y1
#"|" x1 #" " y1
]
;probe atts
;ask ""
]
]
]
]
) |
"StrokeStyle" (
append tmp_strokes select atts "index"
tmp_strokeStyle: copy atts
parse-xfl content
append/only tmp_strokes tmp_strokeStyle
) |
"SolidStroke" (
append tmp_strokeStyle atts
parse-xfl content
append/only append tmp_strokeStyle 'fill tmp_fill
) |
"RaggedStroke" (
append tmp_strokeStyle atts
parse-xfl content
append/only append tmp_strokeStyle 'fill tmp_fill
) |
"StippleStroke" (
append tmp_strokeStyle atts
parse-xfl content
append/only append tmp_strokeStyle 'fill tmp_fill
) |
"transformationPoint" |
"matrix" (
tmp_matrix: copy []
parse-xfl content
) |
"Matrix" (
append tmp_matrix atts
) |
"fills" (
tmp_fills: copy []
parse-xfl content
) |
"FillStyle" (
append tmp_fills select atts "index"
tmp_fillStyle: copy atts
parse-xfl content
append/only tmp_fills tmp_fillStyle
) |
"GradientEntry" (
append/only tmp_gradients atts
) |
"fill" (
tmp_fill: copy []
parse-xfl content
) |
"SolidColor" (
append/only append tmp_fill 'SolidColor atts
) |
"RadialGradient" (
tmp_gradients: copy []
parse-xfl content
append/only append tmp_fillStyle 'matrix tmp_matrix
append/only append tmp_fillStyle 'gradients tmp_gradients
) |
"BitmapFill" (
append tmp_fillStyle atts
if tmp: select crops atts/("bitmapPath") [
atts/("bitmapPath"): to-string tmp/7
opt-updateBmpMATRIX second first get-nodes content %matrix/Matrix tmp
]
probe current-node
;ask ""
) |
"LinearGradient" (
append/only append tmp_fillStyle 'gradients content
) |
"DottedStroke"
]
] |
open import Categories
open import Monads
open import Level
import Monads.CatofAdj
module Monads.CatofAdj.TermAdjHom
{c d}
{C : Cat {c}{d}}
(M : Monad C)
(A : Cat.Obj (Monads.CatofAdj.CatofAdj M {c ⊔ d}{c ⊔ d})) where
open import Library
open import Functors
open import Adjunctions
open import Monads.EM M
open Monads.CatofAdj M
open import Monads.CatofAdj.TermAdjObj M
open Cat
open Fun
open Adj
open Monad
open ObjAdj
K' : Fun (D A) (D EMObj)
K' = record {
OMap = λ X → record {
acar = OMap (R (adj A)) X;
astr = λ Z f → subst (λ Z → Hom C Z (OMap (R (adj A)) X))
(fcong Z (cong OMap (law A)))
(HMap (R (adj A)) (right (adj A) f));
alaw1 = λ {Z} {f} → alaw1lem
(TFun M)
(L (adj A))
(R (adj A))
(law A)
(η M)
(right (adj A))
(left (adj A))
(ηlaw A)
(natleft (adj A) (iden C) (right (adj A) f) (iden (D A)))
(lawb (adj A) f);
alaw2 = λ {Z} {W} {k} {f} → alaw2lem
(TFun M)
(L (adj A))
(R (adj A))
(law A)
(right (adj A))
(bind M)
(natright (adj A))
(bindlaw A {_}{_}{k})};
HMap = λ {X} {Y} f → record {
amor = HMap (R (adj A)) f;
ahom = λ {Z} {g} → ahomlem
(TFun M)
(L (adj A))
(R (adj A))
(law A)
(right (adj A))
(natright (adj A))};
fid = AlgMorphEq (fid (R (adj A)));
fcomp = AlgMorphEq (fcomp (R (adj A)))}
Llaw' : K' ○ L (adj A) ≅ L (adj EMObj)
Llaw' = FunctorEq
_
_
(ext (λ X → AlgEq
(fcong X (cong OMap (law A)))
((ext λ Z → dext (λ {f} {f'} p → Llawlem
(TFun M)
(L (adj A))
(R (adj A))
(law A)
(right (adj A))
(bind M)
(bindlaw A)
p)))))
(iext λ X → iext λ Y → ext λ f → AlgMorphEq'
(AlgEq
(fcong X (cong OMap (law A)))
((ext λ Z → dext (λ {f₁} {f'} p → Llawlem
(TFun M)
(L (adj A))
(R (adj A))
(law A)
(right (adj A))
(bind M)
(bindlaw A)
p))))
(AlgEq
(fcong Y (cong OMap (law A)))
((ext λ Z → dext (λ {f₁} {f'} p → Llawlem
(TFun M)
(L (adj A))
(R (adj A))
(law A)
(right (adj A))
(bind M)
(bindlaw A)
p))))
(dcong
(refl {x = f})
(ext (λ _ → cong₂
(Hom C)
(fcong X (cong OMap (law A)))
(fcong Y (cong OMap (law A)))))
(dicong
(refl {x = Y})
(ext (λ z → cong
(λ F → Hom C X z → Hom C (F X) (F z))
(cong OMap (law A))))
(dicong
(refl {x = X})
(ext (λ z → cong
(λ F → ∀ {y} → Hom C z y → Hom C (F z) (F y))
(cong OMap (law A))))
(cong HMap (law A))))))
Rlaw' : R (adj A) ≅ R (adj EMObj) ○ K'
Rlaw' = FunctorEq _ _ refl refl
rightlaw' : {X : Obj C} {Y : Obj (D A)} {f : Hom C X (OMap (R (adj A)) Y)} →
HMap K' (right (adj A) f)
≅
right (adj EMObj)
{X}
{OMap K' Y}
(subst (Hom C X) (fcong Y (cong OMap Rlaw')) f)
rightlaw' {X = X}{Y = Y}{f = f} = AlgMorphEq'
(AlgEq (fcong X (cong OMap (law A)))
(ext λ Z → dext (λ p → Llawlem (TFun M)
(L (adj A))
(R (adj A))
(law A)
(right (adj A))
(bind M)
(bindlaw A) p )))
refl
(trans (cong (λ (f₁ : Hom C X (OMap (R (adj A)) Y)) →
HMap (R (adj A)) (right (adj A) f₁)) (sym (stripsubst (Hom C X) f (fcong Y (cong OMap Rlaw')))) ) (sym (stripsubst (λ Z → Hom C Z (OMap (R (adj A)) Y)) ( ((HMap (R (adj A))
(right (adj A)
(subst (Hom C X) (fcong Y (cong (λ r → OMap r) Rlaw')) f))))) (fcong X (cong OMap (law A))))))
EMHom : Hom CatofAdj A EMObj
EMHom = record {
K = K';
Llaw = Llaw';
Rlaw = Rlaw';
rightlaw = rightlaw'}
|
lemma zero_in_smallomega_iff [simp]: "(\<lambda>_. 0) \<in> \<omega>[F](f) \<longleftrightarrow> eventually (\<lambda>x. f x = 0) F" |
Program Definition test (a b : nat) : { x : nat | x = a + b } :=
((a + b) : { x : nat | x = a + b }).
Proof.
intros.
reflexivity.
Qed.
Print test.
Require Import List.
Program hd_opt (l : list nat) : { x : nat | x <> 0 } :=
match l with
nil => 1
| a :: l => a
end.
|
Fan Yang is a Davisites Davisite who, when she was a teenager, http://www.sacbee.com/content/news/science/story/13392634p14234090c.html discovered a chemical compound that stops bacteria from attaching to contact lenses, reducing the possibility of eye infections.
She won second place in the biochemistry category of Intels International Science and Engineering Fair and the 2005 grand prize at the http://www.srsefair.org/ Sacramento Regional Science and Engineering Fair. She will attend http://www.jhu.edu/ John Hopkins University.
She came up with the need for such a chemical when she was told by her eye doctor that contact lenses carry the risk of eye infection.
Her mother works as a lab technician at UC Davis
|
lemma uniformly_continuous_on_setdist: "uniformly_continuous_on T (\<lambda>y. (setdist {y} S))" |
You guys, I am so behind!
I’ve had Amazon Prime for years, but I used it primarily (pun, sorry) for the free shipping, video streaming, Kindle Lending, and Prime Day sales.
But I was totally missing out!
Did you know about Prime Reading? You probably do. As I said, I’m behind. I recently went camping and wanted to load up my Kindle with things to read by the fire. While I was browsing, I came across this new-to-me-but maybe-not-to-the-rest-of-the-world feature and about danced a jig.
Tons of free things to read! I loaded up and took my devices to the mountains. There’s nothing like relaxing by a fire in total darkness with a nice book to read.
The fire where actual Prime Reading took place.
Okay, now back to Prime Reading itself. If you’re already a member of the Amazon Prime program, it’s included at no additional charge (unlike the Kindle Unlimited program). You don’t even have to own a Kindle. All you need is a device of your choosing and the free reading apps.
Boom! You get access to tons of books and magazines. And they are actually items you’d want to read! Seriously, go look. You’ll find something to enjoy or mock (whatever suits you).
Choose your books or magazines from the Prime Reading selection.
When you’re done, return the item.
You can check out 10 items at a time! TEN!
Even if you hate the book, you’re not losing any money. It’s risk-free reading from your couch. No trip to the library needed.
I didn’t know about Prime Reading, but it makes me much more willing to pay the new, higher price. And it makes me wonder what else I’m missing out on.
So are you already using Prime Reading? If so, what should I check out next? Or are you just as behind as me?
I’m so behind also! I think I used it once last year but was confused and thought it was Kindle Unlimited. I saw the 10 books thing but didn’t understand when I couldn’t check out another book (which was the K-unlimited) I still probably haven’t returned that first book! Ha!
That’s exactly what I thought! I didn’t know Prime Reading was a different thing. I morphed it with Kindle Unlimited and the Kindle Owner’s Lending Library. There are so many ways to get lots of books for a good price! |
[STATEMENT]
lemma (in uniform_space) cauchy_filter_complete_converges:
assumes "cauchy_filter F" "complete A" "F \<le> principal A" "F \<noteq> bot"
shows "\<exists>c. F \<le> nhds c"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<exists>c. F \<le> nhds c
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
cauchy_filter F
complete A
F \<le> principal A
F \<noteq> bot
goal (1 subgoal):
1. \<exists>c. F \<le> nhds c
[PROOF STEP]
unfolding complete_uniform
[PROOF STATE]
proof (prove)
using this:
cauchy_filter F
\<forall>F\<le>principal A. F \<noteq> bot \<longrightarrow> cauchy_filter F \<longrightarrow> (\<exists>x\<in>A. F \<le> nhds x)
F \<le> principal A
F \<noteq> bot
goal (1 subgoal):
1. \<exists>c. F \<le> nhds c
[PROOF STEP]
by blast |
[STATEMENT]
lemma powr_bounds_real:
fixes f g l1 u1 l2 u2 l u :: "real \<Rightarrow> real"
defines "P \<equiv> \<lambda>l u x. f x \<in> {l1 x..u1 x} \<longrightarrow> g x \<in> {l2 x..u2 x} \<longrightarrow> f x powr g x \<in> {l..u}"
shows "\<forall>x. l1 x \<ge> 0 \<longrightarrow> l1 x \<ge> 1 \<longrightarrow> l2 x \<ge> 0 \<longrightarrow> P (l1 x powr l2 x) (u1 x powr u2 x) x"
and "\<forall>x. l1 x \<ge> 0 \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<ge> 0 \<longrightarrow> P (l1 x powr u2 x) (u1 x powr l2 x) x"
and "\<forall>x. l1 x \<ge> 0 \<longrightarrow> l1 x \<ge> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr u2 x) x"
and "\<forall>x. l1 x > 0 \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x"
and "\<forall>x. l1 x \<ge> 0 \<longrightarrow> l1 x \<le> 1 \<longrightarrow> u1 x \<ge> 1 \<longrightarrow> l2 x \<ge> 0 \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x"
and "\<forall>x. l1 x > 0 \<longrightarrow> l1 x \<le> 1 \<longrightarrow> u1 x \<ge> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x"
and "\<forall>x. l1 x \<ge> 0 \<longrightarrow> l1 x \<ge> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> u2 x \<ge> 0 \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x"
and "\<forall>x. l1 x > 0 \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> u2 x \<ge> 0 \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x"
and "\<forall>x. l1 x > 0 \<longrightarrow> l1 x \<le> 1 \<longrightarrow> u1 x \<ge> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> u2 x \<ge> 0 \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow>
l x \<le> u1 x powr l2 x \<longrightarrow> u x \<ge> l1 x powr l2 x \<longrightarrow> u x \<ge> u1 x powr u2 x \<longrightarrow> P (l x) (u x) x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ((\<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr l2 x) (u1 x powr u2 x) x &&& \<forall>x. 0 \<le> l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr l2 x) x) &&& \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr u2 x) x &&& \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x) &&& (\<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x &&& \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x) &&& \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x &&& \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x &&& \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
proof goal_cases
[PROOF STATE]
proof (state)
goal (9 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr l2 x) (u1 x powr u2 x) x
2. \<forall>x. 0 \<le> l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr l2 x) x
3. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr u2 x) x
4. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x
5. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
6. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
7. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
8. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
9. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
case 1
[PROOF STATE]
proof (state)
this:
goal (9 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr l2 x) (u1 x powr u2 x) x
2. \<forall>x. 0 \<le> l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr l2 x) x
3. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr u2 x) x
4. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x
5. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
6. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
7. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
8. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
9. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr l2 x) (u1 x powr u2 x) x
[PROOF STEP]
by (auto simp: P_def powr_def intro: mult_monos)
[PROOF STATE]
proof (state)
this:
\<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr l2 x) (u1 x powr u2 x) x
goal (8 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr l2 x) x
2. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr u2 x) x
3. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x
4. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
5. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
6. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
7. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
8. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (8 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr l2 x) x
2. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr u2 x) x
3. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x
4. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
5. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
6. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
7. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
8. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
case 2
[PROOF STATE]
proof (state)
this:
goal (8 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr l2 x) x
2. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr u2 x) x
3. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x
4. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
5. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
6. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
7. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
8. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr l2 x) x
[PROOF STEP]
by (auto simp: P_def powr_def intro: mult_monos)
[PROOF STATE]
proof (state)
this:
\<forall>x. 0 \<le> l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr l2 x) x
goal (7 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr u2 x) x
2. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x
3. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
4. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
5. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
6. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
7. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (7 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr u2 x) x
2. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x
3. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
4. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
5. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
6. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
7. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
case 3
[PROOF STATE]
proof (state)
this:
goal (7 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr u2 x) x
2. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x
3. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
4. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
5. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
6. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
7. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr u2 x) x
[PROOF STEP]
by (auto simp: P_def powr_def intro: mult_monos)
[PROOF STATE]
proof (state)
this:
\<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr u2 x) x
goal (6 subgoals):
1. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x
2. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
3. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
4. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
5. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
6. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (6 subgoals):
1. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x
2. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
3. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
4. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
5. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
6. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
case 4
[PROOF STATE]
proof (state)
this:
goal (6 subgoals):
1. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x
2. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
3. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
4. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
5. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
6. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x
[PROOF STEP]
by (auto simp: P_def powr_def intro: mult_monos)
[PROOF STATE]
proof (state)
this:
\<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr u2 x) (l1 x powr l2 x) x
goal (5 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
2. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
3. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
4. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
5. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (5 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
2. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
3. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
4. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
5. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
case 5
[PROOF STATE]
proof (state)
this:
goal (5 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
2. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
3. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
4. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
5. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
note comm = mult.commute[of _ "ln x" for x :: real]
[PROOF STATE]
proof (state)
this:
?a * ln ?x3 = ln ?x3 * ?a
goal (5 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
2. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
3. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
4. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
5. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
[PROOF STEP]
by (auto simp: P_def powr_def comm intro: mult_monos)
[PROOF STATE]
proof (state)
this:
\<forall>x. 0 \<le> l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> 0 \<le> l2 x \<longrightarrow> P (l1 x powr u2 x) (u1 x powr u2 x) x
goal (4 subgoals):
1. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
2. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
3. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
4. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (4 subgoals):
1. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
2. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
3. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
4. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
case 6
[PROOF STATE]
proof (state)
this:
goal (4 subgoals):
1. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
2. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
3. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
4. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
note comm = mult.commute[of _ "ln x" for x :: real]
[PROOF STATE]
proof (state)
this:
?a * ln ?x3 = ln ?x3 * ?a
goal (4 subgoals):
1. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
2. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
3. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
4. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
[PROOF STEP]
by (auto simp: P_def powr_def comm intro: mult_monos)
[PROOF STATE]
proof (state)
this:
\<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> u2 x \<le> 0 \<longrightarrow> P (u1 x powr l2 x) (l1 x powr l2 x) x
goal (3 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
2. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
3. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (3 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
2. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
3. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
case 7
[PROOF STATE]
proof (state)
this:
goal (3 subgoals):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
2. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
3. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
[PROOF STEP]
by (auto simp: P_def powr_def intro: mult_monos)
[PROOF STATE]
proof (state)
this:
\<forall>x. 0 \<le> l1 x \<longrightarrow> 1 \<le> l1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (u1 x powr l2 x) (u1 x powr u2 x) x
goal (2 subgoals):
1. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
2. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
2. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
case 8
[PROOF STATE]
proof (state)
this:
goal (2 subgoals):
1. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
2. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
[PROOF STEP]
by (auto simp: P_def powr_def intro: mult_monos)
[PROOF STATE]
proof (state)
this:
\<forall>x. 0 < l1 x \<longrightarrow> u1 x \<le> 1 \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> P (l1 x powr u2 x) (l1 x powr l2 x) x
goal (1 subgoal):
1. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
case 9
[PROOF STATE]
proof (state)
this:
goal (1 subgoal):
1. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
[PROOF STEP]
unfolding P_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> f x \<in> {l1 x..u1 x} \<longrightarrow> g x \<in> {l2 x..u2 x} \<longrightarrow> f x powr g x \<in> {l x..u x}
[PROOF STEP]
proof (safe, goal_cases)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. \<lbrakk>0 < l1 x; l1 x \<le> 1; 1 \<le> u1 x; l2 x \<le> 0; 0 \<le> u2 x; l x \<le> l1 x powr u2 x; l x \<le> u1 x powr l2 x; l1 x powr l2 x \<le> u x; u1 x powr u2 x \<le> u x; f x \<in> {l1 x..u1 x}; g x \<in> {l2 x..u2 x}\<rbrakk> \<Longrightarrow> f x powr g x \<in> {l x..u x}
[PROOF STEP]
case (1 x)
[PROOF STATE]
proof (state)
this:
0 < l1 x
l1 x \<le> 1
1 \<le> u1 x
l2 x \<le> 0
0 \<le> u2 x
l x \<le> l1 x powr u2 x
l x \<le> u1 x powr l2 x
l1 x powr l2 x \<le> u x
u1 x powr u2 x \<le> u x
f x \<in> {l1 x..u1 x}
g x \<in> {l2 x..u2 x}
goal (1 subgoal):
1. \<And>x. \<lbrakk>0 < l1 x; l1 x \<le> 1; 1 \<le> u1 x; l2 x \<le> 0; 0 \<le> u2 x; l x \<le> l1 x powr u2 x; l x \<le> u1 x powr l2 x; l1 x powr l2 x \<le> u x; u1 x powr u2 x \<le> u x; f x \<in> {l1 x..u1 x}; g x \<in> {l2 x..u2 x}\<rbrakk> \<Longrightarrow> f x powr g x \<in> {l x..u x}
[PROOF STEP]
define l' where "l' = (\<lambda>x. min (ln (l1 x) * u2 x) (ln (u1 x) * l2 x))"
[PROOF STATE]
proof (state)
this:
l' = (\<lambda>x. min (ln (l1 x) * u2 x) (ln (u1 x) * l2 x))
goal (1 subgoal):
1. \<And>x. \<lbrakk>0 < l1 x; l1 x \<le> 1; 1 \<le> u1 x; l2 x \<le> 0; 0 \<le> u2 x; l x \<le> l1 x powr u2 x; l x \<le> u1 x powr l2 x; l1 x powr l2 x \<le> u x; u1 x powr u2 x \<le> u x; f x \<in> {l1 x..u1 x}; g x \<in> {l2 x..u2 x}\<rbrakk> \<Longrightarrow> f x powr g x \<in> {l x..u x}
[PROOF STEP]
define u' where "u' = (\<lambda>x. max (ln (l1 x) * l2 x) (ln (u1 x) * u2 x))"
[PROOF STATE]
proof (state)
this:
u' = (\<lambda>x. max (ln (l1 x) * l2 x) (ln (u1 x) * u2 x))
goal (1 subgoal):
1. \<And>x. \<lbrakk>0 < l1 x; l1 x \<le> 1; 1 \<le> u1 x; l2 x \<le> 0; 0 \<le> u2 x; l x \<le> l1 x powr u2 x; l x \<le> u1 x powr l2 x; l1 x powr l2 x \<le> u x; u1 x powr u2 x \<le> u x; f x \<in> {l1 x..u1 x}; g x \<in> {l2 x..u2 x}\<rbrakk> \<Longrightarrow> f x powr g x \<in> {l x..u x}
[PROOF STEP]
from 1 spec[OF mult_bounds_real(9)[of "\<lambda>x. ln (l1 x)" "\<lambda>x. ln (u1 x)" l2 u2 l' u'
"\<lambda>x. ln (f x)" g], of x]
[PROOF STATE]
proof (chain)
picking this:
0 < l1 x
l1 x \<le> 1
1 \<le> u1 x
l2 x \<le> 0
0 \<le> u2 x
l x \<le> l1 x powr u2 x
l x \<le> u1 x powr l2 x
l1 x powr l2 x \<le> u x
u1 x powr u2 x \<le> u x
f x \<in> {l1 x..u1 x}
g x \<in> {l2 x..u2 x}
ln (l1 x) \<le> 0 \<longrightarrow> 0 \<le> ln (u1 x) \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l' x \<le> ln (l1 x) * u2 x \<longrightarrow> l' x \<le> ln (u1 x) * l2 x \<longrightarrow> ln (l1 x) * l2 x \<le> u' x \<longrightarrow> ln (u1 x) * u2 x \<le> u' x \<longrightarrow> ln (f x) \<in> {ln (l1 x)..ln (u1 x)} \<longrightarrow> g x \<in> {l2 x..u2 x} \<longrightarrow> ln (f x) * g x \<in> {l' x..u' x}
[PROOF STEP]
have "ln (f x) * g x \<in> {l' x..u' x}"
[PROOF STATE]
proof (prove)
using this:
0 < l1 x
l1 x \<le> 1
1 \<le> u1 x
l2 x \<le> 0
0 \<le> u2 x
l x \<le> l1 x powr u2 x
l x \<le> u1 x powr l2 x
l1 x powr l2 x \<le> u x
u1 x powr u2 x \<le> u x
f x \<in> {l1 x..u1 x}
g x \<in> {l2 x..u2 x}
ln (l1 x) \<le> 0 \<longrightarrow> 0 \<le> ln (u1 x) \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l' x \<le> ln (l1 x) * u2 x \<longrightarrow> l' x \<le> ln (u1 x) * l2 x \<longrightarrow> ln (l1 x) * l2 x \<le> u' x \<longrightarrow> ln (u1 x) * u2 x \<le> u' x \<longrightarrow> ln (f x) \<in> {ln (l1 x)..ln (u1 x)} \<longrightarrow> g x \<in> {l2 x..u2 x} \<longrightarrow> ln (f x) * g x \<in> {l' x..u' x}
goal (1 subgoal):
1. ln (f x) * g x \<in> {l' x..u' x}
[PROOF STEP]
by (auto simp: powr_def mult.commute l'_def u'_def)
[PROOF STATE]
proof (state)
this:
ln (f x) * g x \<in> {l' x..u' x}
goal (1 subgoal):
1. \<And>x. \<lbrakk>0 < l1 x; l1 x \<le> 1; 1 \<le> u1 x; l2 x \<le> 0; 0 \<le> u2 x; l x \<le> l1 x powr u2 x; l x \<le> u1 x powr l2 x; l1 x powr l2 x \<le> u x; u1 x powr u2 x \<le> u x; f x \<in> {l1 x..u1 x}; g x \<in> {l2 x..u2 x}\<rbrakk> \<Longrightarrow> f x powr g x \<in> {l x..u x}
[PROOF STEP]
with 1
[PROOF STATE]
proof (chain)
picking this:
0 < l1 x
l1 x \<le> 1
1 \<le> u1 x
l2 x \<le> 0
0 \<le> u2 x
l x \<le> l1 x powr u2 x
l x \<le> u1 x powr l2 x
l1 x powr l2 x \<le> u x
u1 x powr u2 x \<le> u x
f x \<in> {l1 x..u1 x}
g x \<in> {l2 x..u2 x}
ln (f x) * g x \<in> {l' x..u' x}
[PROOF STEP]
have "f x powr g x \<in> {exp (l' x)..exp (u' x)}"
[PROOF STATE]
proof (prove)
using this:
0 < l1 x
l1 x \<le> 1
1 \<le> u1 x
l2 x \<le> 0
0 \<le> u2 x
l x \<le> l1 x powr u2 x
l x \<le> u1 x powr l2 x
l1 x powr l2 x \<le> u x
u1 x powr u2 x \<le> u x
f x \<in> {l1 x..u1 x}
g x \<in> {l2 x..u2 x}
ln (f x) * g x \<in> {l' x..u' x}
goal (1 subgoal):
1. f x powr g x \<in> {exp (l' x)..exp (u' x)}
[PROOF STEP]
by (auto simp: powr_def mult.commute)
[PROOF STATE]
proof (state)
this:
f x powr g x \<in> {exp (l' x)..exp (u' x)}
goal (1 subgoal):
1. \<And>x. \<lbrakk>0 < l1 x; l1 x \<le> 1; 1 \<le> u1 x; l2 x \<le> 0; 0 \<le> u2 x; l x \<le> l1 x powr u2 x; l x \<le> u1 x powr l2 x; l1 x powr l2 x \<le> u x; u1 x powr u2 x \<le> u x; f x \<in> {l1 x..u1 x}; g x \<in> {l2 x..u2 x}\<rbrakk> \<Longrightarrow> f x powr g x \<in> {l x..u x}
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
f x powr g x \<in> {exp (l' x)..exp (u' x)}
goal (1 subgoal):
1. \<And>x. \<lbrakk>0 < l1 x; l1 x \<le> 1; 1 \<le> u1 x; l2 x \<le> 0; 0 \<le> u2 x; l x \<le> l1 x powr u2 x; l x \<le> u1 x powr l2 x; l1 x powr l2 x \<le> u x; u1 x powr u2 x \<le> u x; f x \<in> {l1 x..u1 x}; g x \<in> {l2 x..u2 x}\<rbrakk> \<Longrightarrow> f x powr g x \<in> {l x..u x}
[PROOF STEP]
from 1
[PROOF STATE]
proof (chain)
picking this:
0 < l1 x
l1 x \<le> 1
1 \<le> u1 x
l2 x \<le> 0
0 \<le> u2 x
l x \<le> l1 x powr u2 x
l x \<le> u1 x powr l2 x
l1 x powr l2 x \<le> u x
u1 x powr u2 x \<le> u x
f x \<in> {l1 x..u1 x}
g x \<in> {l2 x..u2 x}
[PROOF STEP]
have "exp (l' x) = min (l1 x powr u2 x) (u1 x powr l2 x)"
[PROOF STATE]
proof (prove)
using this:
0 < l1 x
l1 x \<le> 1
1 \<le> u1 x
l2 x \<le> 0
0 \<le> u2 x
l x \<le> l1 x powr u2 x
l x \<le> u1 x powr l2 x
l1 x powr l2 x \<le> u x
u1 x powr u2 x \<le> u x
f x \<in> {l1 x..u1 x}
g x \<in> {l2 x..u2 x}
goal (1 subgoal):
1. exp (l' x) = min (l1 x powr u2 x) (u1 x powr l2 x)
[PROOF STEP]
by (auto simp add: l'_def powr_def min_def mult.commute)
[PROOF STATE]
proof (state)
this:
exp (l' x) = min (l1 x powr u2 x) (u1 x powr l2 x)
goal (1 subgoal):
1. \<And>x. \<lbrakk>0 < l1 x; l1 x \<le> 1; 1 \<le> u1 x; l2 x \<le> 0; 0 \<le> u2 x; l x \<le> l1 x powr u2 x; l x \<le> u1 x powr l2 x; l1 x powr l2 x \<le> u x; u1 x powr u2 x \<le> u x; f x \<in> {l1 x..u1 x}; g x \<in> {l2 x..u2 x}\<rbrakk> \<Longrightarrow> f x powr g x \<in> {l x..u x}
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
exp (l' x) = min (l1 x powr u2 x) (u1 x powr l2 x)
goal (1 subgoal):
1. \<And>x. \<lbrakk>0 < l1 x; l1 x \<le> 1; 1 \<le> u1 x; l2 x \<le> 0; 0 \<le> u2 x; l x \<le> l1 x powr u2 x; l x \<le> u1 x powr l2 x; l1 x powr l2 x \<le> u x; u1 x powr u2 x \<le> u x; f x \<in> {l1 x..u1 x}; g x \<in> {l2 x..u2 x}\<rbrakk> \<Longrightarrow> f x powr g x \<in> {l x..u x}
[PROOF STEP]
from 1
[PROOF STATE]
proof (chain)
picking this:
0 < l1 x
l1 x \<le> 1
1 \<le> u1 x
l2 x \<le> 0
0 \<le> u2 x
l x \<le> l1 x powr u2 x
l x \<le> u1 x powr l2 x
l1 x powr l2 x \<le> u x
u1 x powr u2 x \<le> u x
f x \<in> {l1 x..u1 x}
g x \<in> {l2 x..u2 x}
[PROOF STEP]
have "exp (u' x) = max (l1 x powr l2 x) (u1 x powr u2 x)"
[PROOF STATE]
proof (prove)
using this:
0 < l1 x
l1 x \<le> 1
1 \<le> u1 x
l2 x \<le> 0
0 \<le> u2 x
l x \<le> l1 x powr u2 x
l x \<le> u1 x powr l2 x
l1 x powr l2 x \<le> u x
u1 x powr u2 x \<le> u x
f x \<in> {l1 x..u1 x}
g x \<in> {l2 x..u2 x}
goal (1 subgoal):
1. exp (u' x) = max (l1 x powr l2 x) (u1 x powr u2 x)
[PROOF STEP]
by (auto simp add: u'_def powr_def max_def mult.commute)
[PROOF STATE]
proof (state)
this:
exp (u' x) = max (l1 x powr l2 x) (u1 x powr u2 x)
goal (1 subgoal):
1. \<And>x. \<lbrakk>0 < l1 x; l1 x \<le> 1; 1 \<le> u1 x; l2 x \<le> 0; 0 \<le> u2 x; l x \<le> l1 x powr u2 x; l x \<le> u1 x powr l2 x; l1 x powr l2 x \<le> u x; u1 x powr u2 x \<le> u x; f x \<in> {l1 x..u1 x}; g x \<in> {l2 x..u2 x}\<rbrakk> \<Longrightarrow> f x powr g x \<in> {l x..u x}
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
f x powr g x \<in> {min (l1 x powr u2 x) (u1 x powr l2 x)..max (l1 x powr l2 x) (u1 x powr u2 x)}
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
f x powr g x \<in> {min (l1 x powr u2 x) (u1 x powr l2 x)..max (l1 x powr l2 x) (u1 x powr u2 x)}
goal (1 subgoal):
1. f x powr g x \<in> {l x..u x}
[PROOF STEP]
using 1(5-9)
[PROOF STATE]
proof (prove)
using this:
f x powr g x \<in> {min (l1 x powr u2 x) (u1 x powr l2 x)..max (l1 x powr l2 x) (u1 x powr u2 x)}
0 \<le> u2 x
l x \<le> l1 x powr u2 x
l x \<le> u1 x powr l2 x
l1 x powr l2 x \<le> u x
u1 x powr u2 x \<le> u x
goal (1 subgoal):
1. f x powr g x \<in> {l x..u x}
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
f x powr g x \<in> {l x..u x}
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<forall>x. 0 < l1 x \<longrightarrow> l1 x \<le> 1 \<longrightarrow> 1 \<le> u1 x \<longrightarrow> l2 x \<le> 0 \<longrightarrow> 0 \<le> u2 x \<longrightarrow> l x \<le> l1 x powr u2 x \<longrightarrow> l x \<le> u1 x powr l2 x \<longrightarrow> l1 x powr l2 x \<le> u x \<longrightarrow> u1 x powr u2 x \<le> u x \<longrightarrow> P (l x) (u x) x
goal:
No subgoals!
[PROOF STEP]
qed |
using Gadfly
function testMultipleStarts(tsize::Int=300, npoints::Int=20)
SpeedImage = ones(tsize, tsize)
SourcePoint = rand(2, npoints) .* tsize .+ 1
return FastMarching.msfm(SpeedImage, SourcePoint, true, true)
end # function testMultipleStarts
t1 = testMultipleStarts()
draw(PNG("multiplestart.png"), plot(; z=t1, Geom.contour))
|
import data.nat.basic
namespace nat
lemma lt_iff_add_one_le {m n : ℕ} :
m < n ↔ m + 1 ≤ n := by rw succ_le_iff
lemma add_lt_add_of_le_of_le_of_lt_or_lt {a b c d : nat} :
a ≤ b → c ≤ d → (a < b ∨ c < d) → a + c < b + d :=
begin
intros h1 h2 h3, cases h3,
apply add_lt_add_of_lt_of_le; assumption,
apply add_lt_add_of_le_of_lt; assumption
end
lemma max_succ_succ {m n} :
max (succ m) (succ n) = succ (max m n) :=
begin
by_cases h1 : m ≤ n,
rw [max_eq_right h1, max_eq_right (succ_le_succ h1)],
{ rw not_le at h1, have h2 := le_of_lt h1,
rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] }
end
end nat |
(* Title: HOL/GCD.thy
Author: Christophe Tabacznyj
Author: Lawrence C. Paulson
Author: Amine Chaieb
Author: Thomas M. Rasmussen
Author: Jeremy Avigad
Author: Tobias Nipkow
This file deals with the functions gcd and lcm. Definitions and
lemmas are proved uniformly for the natural numbers and integers.
This file combines and revises a number of prior developments.
The original theories "GCD" and "Primes" were by Christophe Tabacznyj
and Lawrence C. Paulson, based on @{cite davenport92}. They introduced
gcd, lcm, and prime for the natural numbers.
The original theory "IntPrimes" was by Thomas M. Rasmussen, and
extended gcd, lcm, primes to the integers. Amine Chaieb provided
another extension of the notions to the integers, and added a number
of results to "Primes" and "GCD". IntPrimes also defined and developed
the congruence relations on the integers. The notion was extended to
the natural numbers by Chaieb.
Jeremy Avigad combined all of these, made everything uniform for the
natural numbers and the integers, and added a number of new theorems.
Tobias Nipkow cleaned up a lot.
*)
section \<open>Greatest common divisor and least common multiple\<close>
theory GCD
imports Groups_List Code_Numeral
begin
subsection \<open>Abstract bounded quasi semilattices as common foundation\<close>
locale bounded_quasi_semilattice = abel_semigroup +
fixes top :: 'a ("\<^bold>\<top>") and bot :: 'a ("\<^bold>\<bottom>")
and normalize :: "'a \<Rightarrow> 'a"
assumes idem_normalize [simp]: "a \<^bold>* a = normalize a"
and normalize_left_idem [simp]: "normalize a \<^bold>* b = a \<^bold>* b"
and normalize_idem [simp]: "normalize (a \<^bold>* b) = a \<^bold>* b"
and normalize_top [simp]: "normalize \<^bold>\<top> = \<^bold>\<top>"
and normalize_bottom [simp]: "normalize \<^bold>\<bottom> = \<^bold>\<bottom>"
and top_left_normalize [simp]: "\<^bold>\<top> \<^bold>* a = normalize a"
and bottom_left_bottom [simp]: "\<^bold>\<bottom> \<^bold>* a = \<^bold>\<bottom>"
begin
lemma left_idem [simp]:
"a \<^bold>* (a \<^bold>* b) = a \<^bold>* b"
using assoc [of a a b, symmetric] by simp
lemma right_idem [simp]:
"(a \<^bold>* b) \<^bold>* b = a \<^bold>* b"
using left_idem [of b a] by (simp add: ac_simps)
lemma comp_fun_idem: "comp_fun_idem f"
by standard (simp_all add: fun_eq_iff ac_simps)
interpretation comp_fun_idem f
by (fact comp_fun_idem)
lemma top_right_normalize [simp]:
"a \<^bold>* \<^bold>\<top> = normalize a"
using top_left_normalize [of a] by (simp add: ac_simps)
lemma bottom_right_bottom [simp]:
"a \<^bold>* \<^bold>\<bottom> = \<^bold>\<bottom>"
using bottom_left_bottom [of a] by (simp add: ac_simps)
lemma normalize_right_idem [simp]:
"a \<^bold>* normalize b = a \<^bold>* b"
using normalize_left_idem [of b a] by (simp add: ac_simps)
end
locale bounded_quasi_semilattice_set = bounded_quasi_semilattice
begin
interpretation comp_fun_idem f
by (fact comp_fun_idem)
definition F :: "'a set \<Rightarrow> 'a"
where
eq_fold: "F A = (if finite A then Finite_Set.fold f \<^bold>\<top> A else \<^bold>\<bottom>)"
lemma infinite [simp]:
"infinite A \<Longrightarrow> F A = \<^bold>\<bottom>"
by (simp add: eq_fold)
lemma set_eq_fold [code]:
"F (set xs) = fold f xs \<^bold>\<top>"
by (simp add: eq_fold fold_set_fold)
lemma empty [simp]:
"F {} = \<^bold>\<top>"
by (simp add: eq_fold)
lemma insert [simp]:
"F (insert a A) = a \<^bold>* F A"
by (cases "finite A") (simp_all add: eq_fold)
lemma normalize [simp]:
"normalize (F A) = F A"
by (induct A rule: infinite_finite_induct) simp_all
lemma in_idem:
assumes "a \<in> A"
shows "a \<^bold>* F A = F A"
using assms by (induct A rule: infinite_finite_induct)
(auto simp: left_commute [of a])
lemma union:
"F (A \<union> B) = F A \<^bold>* F B"
by (induct A rule: infinite_finite_induct)
(simp_all add: ac_simps)
lemma remove:
assumes "a \<in> A"
shows "F A = a \<^bold>* F (A - {a})"
proof -
from assms obtain B where "A = insert a B" and "a \<notin> B"
by (blast dest: mk_disjoint_insert)
with assms show ?thesis by simp
qed
lemma insert_remove:
"F (insert a A) = a \<^bold>* F (A - {a})"
by (cases "a \<in> A") (simp_all add: insert_absorb remove)
end
subsection \<open>Abstract GCD and LCM\<close>
class gcd = zero + one + dvd +
fixes gcd :: "'a \<Rightarrow> 'a \<Rightarrow> 'a"
and lcm :: "'a \<Rightarrow> 'a \<Rightarrow> 'a"
class Gcd = gcd +
fixes Gcd :: "'a set \<Rightarrow> 'a"
and Lcm :: "'a set \<Rightarrow> 'a"
syntax
"_GCD1" :: "pttrns \<Rightarrow> 'b \<Rightarrow> 'b" ("(3GCD _./ _)" [0, 10] 10)
"_GCD" :: "pttrn \<Rightarrow> 'a set \<Rightarrow> 'b \<Rightarrow> 'b" ("(3GCD _\<in>_./ _)" [0, 0, 10] 10)
"_LCM1" :: "pttrns \<Rightarrow> 'b \<Rightarrow> 'b" ("(3LCM _./ _)" [0, 10] 10)
"_LCM" :: "pttrn \<Rightarrow> 'a set \<Rightarrow> 'b \<Rightarrow> 'b" ("(3LCM _\<in>_./ _)" [0, 0, 10] 10)
translations
"GCD x y. f" \<rightleftharpoons> "GCD x. GCD y. f"
"GCD x. f" \<rightleftharpoons> "CONST Gcd (CONST range (\<lambda>x. f))"
"GCD x\<in>A. f" \<rightleftharpoons> "CONST Gcd ((\<lambda>x. f) ` A)"
"LCM x y. f" \<rightleftharpoons> "LCM x. LCM y. f"
"LCM x. f" \<rightleftharpoons> "CONST Lcm (CONST range (\<lambda>x. f))"
"LCM x\<in>A. f" \<rightleftharpoons> "CONST Lcm ((\<lambda>x. f) ` A)"
class semiring_gcd = normalization_semidom + gcd +
assumes gcd_dvd1 [iff]: "gcd a b dvd a"
and gcd_dvd2 [iff]: "gcd a b dvd b"
and gcd_greatest: "c dvd a \<Longrightarrow> c dvd b \<Longrightarrow> c dvd gcd a b"
and normalize_gcd [simp]: "normalize (gcd a b) = gcd a b"
and lcm_gcd: "lcm a b = normalize (a * b div gcd a b)"
begin
lemma gcd_greatest_iff [simp]: "a dvd gcd b c \<longleftrightarrow> a dvd b \<and> a dvd c"
by (blast intro!: gcd_greatest intro: dvd_trans)
lemma gcd_dvdI1: "a dvd c \<Longrightarrow> gcd a b dvd c"
by (rule dvd_trans) (rule gcd_dvd1)
lemma gcd_dvdI2: "b dvd c \<Longrightarrow> gcd a b dvd c"
by (rule dvd_trans) (rule gcd_dvd2)
lemma dvd_gcdD1: "a dvd gcd b c \<Longrightarrow> a dvd b"
using gcd_dvd1 [of b c] by (blast intro: dvd_trans)
lemma dvd_gcdD2: "a dvd gcd b c \<Longrightarrow> a dvd c"
using gcd_dvd2 [of b c] by (blast intro: dvd_trans)
lemma gcd_0_left [simp]: "gcd 0 a = normalize a"
by (rule associated_eqI) simp_all
lemma gcd_0_right [simp]: "gcd a 0 = normalize a"
by (rule associated_eqI) simp_all
lemma gcd_eq_0_iff [simp]: "gcd a b = 0 \<longleftrightarrow> a = 0 \<and> b = 0"
(is "?P \<longleftrightarrow> ?Q")
proof
assume ?P
then have "0 dvd gcd a b"
by simp
then have "0 dvd a" and "0 dvd b"
by (blast intro: dvd_trans)+
then show ?Q
by simp
next
assume ?Q
then show ?P
by simp
qed
lemma unit_factor_gcd: "unit_factor (gcd a b) = (if a = 0 \<and> b = 0 then 0 else 1)"
proof (cases "gcd a b = 0")
case True
then show ?thesis by simp
next
case False
have "unit_factor (gcd a b) * normalize (gcd a b) = gcd a b"
by (rule unit_factor_mult_normalize)
then have "unit_factor (gcd a b) * gcd a b = gcd a b"
by simp
then have "unit_factor (gcd a b) * gcd a b div gcd a b = gcd a b div gcd a b"
by simp
with False show ?thesis
by simp
qed
lemma is_unit_gcd_iff [simp]:
"is_unit (gcd a b) \<longleftrightarrow> gcd a b = 1"
by (cases "a = 0 \<and> b = 0") (auto simp: unit_factor_gcd dest: is_unit_unit_factor)
sublocale gcd: abel_semigroup gcd
proof
fix a b c
show "gcd a b = gcd b a"
by (rule associated_eqI) simp_all
from gcd_dvd1 have "gcd (gcd a b) c dvd a"
by (rule dvd_trans) simp
moreover from gcd_dvd1 have "gcd (gcd a b) c dvd b"
by (rule dvd_trans) simp
ultimately have P1: "gcd (gcd a b) c dvd gcd a (gcd b c)"
by (auto intro!: gcd_greatest)
from gcd_dvd2 have "gcd a (gcd b c) dvd b"
by (rule dvd_trans) simp
moreover from gcd_dvd2 have "gcd a (gcd b c) dvd c"
by (rule dvd_trans) simp
ultimately have P2: "gcd a (gcd b c) dvd gcd (gcd a b) c"
by (auto intro!: gcd_greatest)
from P1 P2 show "gcd (gcd a b) c = gcd a (gcd b c)"
by (rule associated_eqI) simp_all
qed
sublocale gcd: bounded_quasi_semilattice gcd 0 1 normalize
proof
show "gcd a a = normalize a" for a
proof -
have "a dvd gcd a a"
by (rule gcd_greatest) simp_all
then show ?thesis
by (auto intro: associated_eqI)
qed
show "gcd (normalize a) b = gcd a b" for a b
using gcd_dvd1 [of "normalize a" b]
by (auto intro: associated_eqI)
show "gcd 1 a = 1" for a
by (rule associated_eqI) simp_all
qed simp_all
lemma gcd_self: "gcd a a = normalize a"
by (fact gcd.idem_normalize)
lemma gcd_left_idem: "gcd a (gcd a b) = gcd a b"
by (fact gcd.left_idem)
lemma gcd_right_idem: "gcd (gcd a b) b = gcd a b"
by (fact gcd.right_idem)
lemma gcdI:
assumes "c dvd a" and "c dvd b"
and greatest: "\<And>d. d dvd a \<Longrightarrow> d dvd b \<Longrightarrow> d dvd c"
and "normalize c = c"
shows "c = gcd a b"
by (rule associated_eqI) (auto simp: assms intro: gcd_greatest)
lemma gcd_unique:
"d dvd a \<and> d dvd b \<and> normalize d = d \<and> (\<forall>e. e dvd a \<and> e dvd b \<longrightarrow> e dvd d) \<longleftrightarrow> d = gcd a b"
by rule (auto intro: gcdI simp: gcd_greatest)
lemma gcd_dvd_prod: "gcd a b dvd k * b"
using mult_dvd_mono [of 1] by auto
lemma gcd_proj2_if_dvd: "b dvd a \<Longrightarrow> gcd a b = normalize b"
by (rule gcdI [symmetric]) simp_all
lemma gcd_proj1_if_dvd: "a dvd b \<Longrightarrow> gcd a b = normalize a"
by (rule gcdI [symmetric]) simp_all
lemma gcd_proj1_iff: "gcd m n = normalize m \<longleftrightarrow> m dvd n"
proof
assume *: "gcd m n = normalize m"
show "m dvd n"
proof (cases "m = 0")
case True
with * show ?thesis by simp
next
case [simp]: False
from * have **: "m = gcd m n * unit_factor m"
by (simp add: unit_eq_div2)
show ?thesis
by (subst **) (simp add: mult_unit_dvd_iff)
qed
next
assume "m dvd n"
then show "gcd m n = normalize m"
by (rule gcd_proj1_if_dvd)
qed
lemma gcd_proj2_iff: "gcd m n = normalize n \<longleftrightarrow> n dvd m"
using gcd_proj1_iff [of n m] by (simp add: ac_simps)
lemma gcd_mult_left: "gcd (c * a) (c * b) = normalize (c * gcd a b)"
proof (cases "c = 0")
case True
then show ?thesis by simp
next
case False
then have *: "c * gcd a b dvd gcd (c * a) (c * b)"
by (auto intro: gcd_greatest)
moreover from False * have "gcd (c * a) (c * b) dvd c * gcd a b"
by (metis div_dvd_iff_mult dvd_mult_left gcd_dvd1 gcd_dvd2 gcd_greatest mult_commute)
ultimately have "normalize (gcd (c * a) (c * b)) = normalize (c * gcd a b)"
by (auto intro: associated_eqI)
then show ?thesis
by (simp add: normalize_mult)
qed
lemma gcd_mult_right: "gcd (a * c) (b * c) = normalize (gcd b a * c)"
using gcd_mult_left [of c a b] by (simp add: ac_simps)
lemma dvd_lcm1 [iff]: "a dvd lcm a b"
by (metis div_mult_swap dvd_mult2 dvd_normalize_iff dvd_refl gcd_dvd2 lcm_gcd)
lemma dvd_lcm2 [iff]: "b dvd lcm a b"
by (metis dvd_div_mult dvd_mult dvd_normalize_iff dvd_refl gcd_dvd1 lcm_gcd)
lemma dvd_lcmI1: "a dvd b \<Longrightarrow> a dvd lcm b c"
by (rule dvd_trans) (assumption, blast)
lemma dvd_lcmI2: "a dvd c \<Longrightarrow> a dvd lcm b c"
by (rule dvd_trans) (assumption, blast)
lemma lcm_dvdD1: "lcm a b dvd c \<Longrightarrow> a dvd c"
using dvd_lcm1 [of a b] by (blast intro: dvd_trans)
lemma lcm_dvdD2: "lcm a b dvd c \<Longrightarrow> b dvd c"
using dvd_lcm2 [of a b] by (blast intro: dvd_trans)
lemma lcm_least:
assumes "a dvd c" and "b dvd c"
shows "lcm a b dvd c"
proof (cases "c = 0")
case True
then show ?thesis by simp
next
case False
then have *: "is_unit (unit_factor c)"
by simp
show ?thesis
proof (cases "gcd a b = 0")
case True
with assms show ?thesis by simp
next
case False
have "a * b dvd normalize (c * gcd a b)"
using assms by (subst gcd_mult_left [symmetric]) (auto intro!: gcd_greatest simp: mult_ac)
with False have "(a * b div gcd a b) dvd c"
by (subst div_dvd_iff_mult) auto
thus ?thesis by (simp add: lcm_gcd)
qed
qed
lemma lcm_least_iff [simp]: "lcm a b dvd c \<longleftrightarrow> a dvd c \<and> b dvd c"
by (blast intro!: lcm_least intro: dvd_trans)
lemma normalize_lcm [simp]: "normalize (lcm a b) = lcm a b"
by (simp add: lcm_gcd dvd_normalize_div)
lemma lcm_0_left [simp]: "lcm 0 a = 0"
by (simp add: lcm_gcd)
lemma lcm_0_right [simp]: "lcm a 0 = 0"
by (simp add: lcm_gcd)
lemma lcm_eq_0_iff: "lcm a b = 0 \<longleftrightarrow> a = 0 \<or> b = 0"
(is "?P \<longleftrightarrow> ?Q")
proof
assume ?P
then have "0 dvd lcm a b"
by simp
also have "lcm a b dvd (a * b)"
by simp
finally show ?Q
by auto
next
assume ?Q
then show ?P
by auto
qed
lemma zero_eq_lcm_iff: "0 = lcm a b \<longleftrightarrow> a = 0 \<or> b = 0"
using lcm_eq_0_iff[of a b] by auto
lemma lcm_eq_1_iff [simp]: "lcm a b = 1 \<longleftrightarrow> is_unit a \<and> is_unit b"
by (auto intro: associated_eqI)
lemma unit_factor_lcm: "unit_factor (lcm a b) = (if a = 0 \<or> b = 0 then 0 else 1)"
using lcm_eq_0_iff[of a b] by (cases "lcm a b = 0") (auto simp: lcm_gcd)
sublocale lcm: abel_semigroup lcm
proof
fix a b c
show "lcm a b = lcm b a"
by (simp add: lcm_gcd ac_simps normalize_mult dvd_normalize_div)
have "lcm (lcm a b) c dvd lcm a (lcm b c)"
and "lcm a (lcm b c) dvd lcm (lcm a b) c"
by (auto intro: lcm_least
dvd_trans [of b "lcm b c" "lcm a (lcm b c)"]
dvd_trans [of c "lcm b c" "lcm a (lcm b c)"]
dvd_trans [of a "lcm a b" "lcm (lcm a b) c"]
dvd_trans [of b "lcm a b" "lcm (lcm a b) c"])
then show "lcm (lcm a b) c = lcm a (lcm b c)"
by (rule associated_eqI) simp_all
qed
sublocale lcm: bounded_quasi_semilattice lcm 1 0 normalize
proof
show "lcm a a = normalize a" for a
proof -
have "lcm a a dvd a"
by (rule lcm_least) simp_all
then show ?thesis
by (auto intro: associated_eqI)
qed
show "lcm (normalize a) b = lcm a b" for a b
using dvd_lcm1 [of "normalize a" b] unfolding normalize_dvd_iff
by (auto intro: associated_eqI)
show "lcm 1 a = normalize a" for a
by (rule associated_eqI) simp_all
qed simp_all
lemma lcm_self: "lcm a a = normalize a"
by (fact lcm.idem_normalize)
lemma lcm_left_idem: "lcm a (lcm a b) = lcm a b"
by (fact lcm.left_idem)
lemma lcm_right_idem: "lcm (lcm a b) b = lcm a b"
by (fact lcm.right_idem)
lemma gcd_lcm:
assumes "a \<noteq> 0" and "b \<noteq> 0"
shows "gcd a b = normalize (a * b div lcm a b)"
proof -
from assms have [simp]: "a * b div gcd a b \<noteq> 0"
by (subst dvd_div_eq_0_iff) auto
let ?u = "unit_factor (a * b div gcd a b)"
have "gcd a b * normalize (a * b div gcd a b) =
gcd a b * ((a * b div gcd a b) * (1 div ?u))"
by simp
also have "\<dots> = a * b div ?u"
by (subst mult.assoc [symmetric]) auto
also have "\<dots> dvd a * b"
by (subst div_unit_dvd_iff) auto
finally have "gcd a b dvd ((a * b) div lcm a b)"
by (intro dvd_mult_imp_div) (auto simp: lcm_gcd)
moreover have "a * b div lcm a b dvd a" and "a * b div lcm a b dvd b"
using assms by (subst div_dvd_iff_mult; simp add: lcm_eq_0_iff mult.commute[of b "lcm a b"])+
ultimately have "normalize (gcd a b) = normalize (a * b div lcm a b)"
apply -
apply (rule associated_eqI)
using assms
apply (auto simp: div_dvd_iff_mult zero_eq_lcm_iff)
done
thus ?thesis by simp
qed
lemma lcm_1_left: "lcm 1 a = normalize a"
by (fact lcm.top_left_normalize)
lemma lcm_1_right: "lcm a 1 = normalize a"
by (fact lcm.top_right_normalize)
lemma lcm_mult_left: "lcm (c * a) (c * b) = normalize (c * lcm a b)"
proof (cases "c = 0")
case True
then show ?thesis by simp
next
case False
then have *: "lcm (c * a) (c * b) dvd c * lcm a b"
by (auto intro: lcm_least)
moreover have "lcm a b dvd lcm (c * a) (c * b) div c"
by (intro lcm_least) (auto intro!: dvd_mult_imp_div simp: mult_ac)
hence "c * lcm a b dvd lcm (c * a) (c * b)"
using False by (subst (asm) dvd_div_iff_mult) (auto simp: mult_ac intro: dvd_lcmI1)
ultimately have "normalize (lcm (c * a) (c * b)) = normalize (c * lcm a b)"
by (auto intro: associated_eqI)
then show ?thesis
by (simp add: normalize_mult)
qed
lemma lcm_mult_right: "lcm (a * c) (b * c) = normalize (lcm b a * c)"
using lcm_mult_left [of c a b] by (simp add: ac_simps)
lemma lcm_mult_unit1: "is_unit a \<Longrightarrow> lcm (b * a) c = lcm b c"
by (rule associated_eqI) (simp_all add: mult_unit_dvd_iff dvd_lcmI1)
lemma lcm_mult_unit2: "is_unit a \<Longrightarrow> lcm b (c * a) = lcm b c"
using lcm_mult_unit1 [of a c b] by (simp add: ac_simps)
lemma lcm_div_unit1:
"is_unit a \<Longrightarrow> lcm (b div a) c = lcm b c"
by (erule is_unitE [of _ b]) (simp add: lcm_mult_unit1)
lemma lcm_div_unit2: "is_unit a \<Longrightarrow> lcm b (c div a) = lcm b c"
by (erule is_unitE [of _ c]) (simp add: lcm_mult_unit2)
lemma normalize_lcm_left: "lcm (normalize a) b = lcm a b"
by (fact lcm.normalize_left_idem)
lemma normalize_lcm_right: "lcm a (normalize b) = lcm a b"
by (fact lcm.normalize_right_idem)
lemma comp_fun_idem_gcd: "comp_fun_idem gcd"
by standard (simp_all add: fun_eq_iff ac_simps)
lemma comp_fun_idem_lcm: "comp_fun_idem lcm"
by standard (simp_all add: fun_eq_iff ac_simps)
lemma gcd_dvd_antisym: "gcd a b dvd gcd c d \<Longrightarrow> gcd c d dvd gcd a b \<Longrightarrow> gcd a b = gcd c d"
proof (rule gcdI)
assume *: "gcd a b dvd gcd c d"
and **: "gcd c d dvd gcd a b"
have "gcd c d dvd c"
by simp
with * show "gcd a b dvd c"
by (rule dvd_trans)
have "gcd c d dvd d"
by simp
with * show "gcd a b dvd d"
by (rule dvd_trans)
show "normalize (gcd a b) = gcd a b"
by simp
fix l assume "l dvd c" and "l dvd d"
then have "l dvd gcd c d"
by (rule gcd_greatest)
from this and ** show "l dvd gcd a b"
by (rule dvd_trans)
qed
declare unit_factor_lcm [simp]
lemma lcmI:
assumes "a dvd c" and "b dvd c" and "\<And>d. a dvd d \<Longrightarrow> b dvd d \<Longrightarrow> c dvd d"
and "normalize c = c"
shows "c = lcm a b"
by (rule associated_eqI) (auto simp: assms intro: lcm_least)
lemma gcd_dvd_lcm [simp]: "gcd a b dvd lcm a b"
using gcd_dvd2 by (rule dvd_lcmI2)
lemmas lcm_0 = lcm_0_right
lemma lcm_unique:
"a dvd d \<and> b dvd d \<and> normalize d = d \<and> (\<forall>e. a dvd e \<and> b dvd e \<longrightarrow> d dvd e) \<longleftrightarrow> d = lcm a b"
by rule (auto intro: lcmI simp: lcm_least lcm_eq_0_iff)
lemma lcm_proj1_if_dvd:
assumes "b dvd a" shows "lcm a b = normalize a"
proof -
have "normalize (lcm a b) = normalize a"
by (rule associatedI) (use assms in auto)
thus ?thesis by simp
qed
lemma lcm_proj2_if_dvd: "a dvd b \<Longrightarrow> lcm a b = normalize b"
using lcm_proj1_if_dvd [of a b] by (simp add: ac_simps)
lemma lcm_proj1_iff: "lcm m n = normalize m \<longleftrightarrow> n dvd m"
proof
assume *: "lcm m n = normalize m"
show "n dvd m"
proof (cases "m = 0")
case True
then show ?thesis by simp
next
case [simp]: False
from * have **: "m = lcm m n * unit_factor m"
by (simp add: unit_eq_div2)
show ?thesis by (subst **) simp
qed
next
assume "n dvd m"
then show "lcm m n = normalize m"
by (rule lcm_proj1_if_dvd)
qed
lemma lcm_proj2_iff: "lcm m n = normalize n \<longleftrightarrow> m dvd n"
using lcm_proj1_iff [of n m] by (simp add: ac_simps)
lemma gcd_mono: "a dvd c \<Longrightarrow> b dvd d \<Longrightarrow> gcd a b dvd gcd c d"
by (simp add: gcd_dvdI1 gcd_dvdI2)
lemma lcm_mono: "a dvd c \<Longrightarrow> b dvd d \<Longrightarrow> lcm a b dvd lcm c d"
by (simp add: dvd_lcmI1 dvd_lcmI2)
lemma dvd_productE:
assumes "p dvd a * b"
obtains x y where "p = x * y" "x dvd a" "y dvd b"
proof (cases "a = 0")
case True
thus ?thesis by (intro that[of p 1]) simp_all
next
case False
define x y where "x = gcd a p" and "y = p div x"
have "p = x * y" by (simp add: x_def y_def)
moreover have "x dvd a" by (simp add: x_def)
moreover from assms have "p dvd gcd (b * a) (b * p)"
by (intro gcd_greatest) (simp_all add: mult.commute)
hence "p dvd b * gcd a p" by (subst (asm) gcd_mult_left) auto
with False have "y dvd b"
by (simp add: x_def y_def div_dvd_iff_mult assms)
ultimately show ?thesis by (rule that)
qed
lemma gcd_mult_unit1:
assumes "is_unit a" shows "gcd (b * a) c = gcd b c"
proof -
have "gcd (b * a) c dvd b"
using assms dvd_mult_unit_iff by blast
then show ?thesis
by (rule gcdI) simp_all
qed
lemma gcd_mult_unit2: "is_unit a \<Longrightarrow> gcd b (c * a) = gcd b c"
using gcd.commute gcd_mult_unit1 by auto
lemma gcd_div_unit1: "is_unit a \<Longrightarrow> gcd (b div a) c = gcd b c"
by (erule is_unitE [of _ b]) (simp add: gcd_mult_unit1)
lemma gcd_div_unit2: "is_unit a \<Longrightarrow> gcd b (c div a) = gcd b c"
by (erule is_unitE [of _ c]) (simp add: gcd_mult_unit2)
lemma normalize_gcd_left: "gcd (normalize a) b = gcd a b"
by (fact gcd.normalize_left_idem)
lemma normalize_gcd_right: "gcd a (normalize b) = gcd a b"
by (fact gcd.normalize_right_idem)
lemma gcd_add1 [simp]: "gcd (m + n) n = gcd m n"
by (rule gcdI [symmetric]) (simp_all add: dvd_add_left_iff)
lemma gcd_add2 [simp]: "gcd m (m + n) = gcd m n"
using gcd_add1 [of n m] by (simp add: ac_simps)
lemma gcd_add_mult: "gcd m (k * m + n) = gcd m n"
by (rule gcdI [symmetric]) (simp_all add: dvd_add_right_iff)
end
class ring_gcd = comm_ring_1 + semiring_gcd
begin
lemma gcd_neg1 [simp]: "gcd (-a) b = gcd a b"
by (rule sym, rule gcdI) (simp_all add: gcd_greatest)
lemma gcd_neg2 [simp]: "gcd a (-b) = gcd a b"
by (rule sym, rule gcdI) (simp_all add: gcd_greatest)
lemma gcd_neg_numeral_1 [simp]: "gcd (- numeral n) a = gcd (numeral n) a"
by (fact gcd_neg1)
lemma gcd_neg_numeral_2 [simp]: "gcd a (- numeral n) = gcd a (numeral n)"
by (fact gcd_neg2)
lemma gcd_diff1: "gcd (m - n) n = gcd m n"
by (subst diff_conv_add_uminus, subst gcd_neg2[symmetric], subst gcd_add1, simp)
lemma gcd_diff2: "gcd (n - m) n = gcd m n"
by (subst gcd_neg1[symmetric]) (simp only: minus_diff_eq gcd_diff1)
lemma lcm_neg1 [simp]: "lcm (-a) b = lcm a b"
by (rule sym, rule lcmI) (simp_all add: lcm_least lcm_eq_0_iff)
lemma lcm_neg2 [simp]: "lcm a (-b) = lcm a b"
by (rule sym, rule lcmI) (simp_all add: lcm_least lcm_eq_0_iff)
lemma lcm_neg_numeral_1 [simp]: "lcm (- numeral n) a = lcm (numeral n) a"
by (fact lcm_neg1)
lemma lcm_neg_numeral_2 [simp]: "lcm a (- numeral n) = lcm a (numeral n)"
by (fact lcm_neg2)
end
class semiring_Gcd = semiring_gcd + Gcd +
assumes Gcd_dvd: "a \<in> A \<Longrightarrow> Gcd A dvd a"
and Gcd_greatest: "(\<And>b. b \<in> A \<Longrightarrow> a dvd b) \<Longrightarrow> a dvd Gcd A"
and normalize_Gcd [simp]: "normalize (Gcd A) = Gcd A"
assumes dvd_Lcm: "a \<in> A \<Longrightarrow> a dvd Lcm A"
and Lcm_least: "(\<And>b. b \<in> A \<Longrightarrow> b dvd a) \<Longrightarrow> Lcm A dvd a"
and normalize_Lcm [simp]: "normalize (Lcm A) = Lcm A"
begin
lemma Lcm_Gcd: "Lcm A = Gcd {b. \<forall>a\<in>A. a dvd b}"
by (rule associated_eqI) (auto intro: Gcd_dvd dvd_Lcm Gcd_greatest Lcm_least)
lemma Gcd_Lcm: "Gcd A = Lcm {b. \<forall>a\<in>A. b dvd a}"
by (rule associated_eqI) (auto intro: Gcd_dvd dvd_Lcm Gcd_greatest Lcm_least)
lemma Gcd_empty [simp]: "Gcd {} = 0"
by (rule dvd_0_left, rule Gcd_greatest) simp
lemma Lcm_empty [simp]: "Lcm {} = 1"
by (auto intro: associated_eqI Lcm_least)
lemma Gcd_insert [simp]: "Gcd (insert a A) = gcd a (Gcd A)"
proof -
have "Gcd (insert a A) dvd gcd a (Gcd A)"
by (auto intro: Gcd_dvd Gcd_greatest)
moreover have "gcd a (Gcd A) dvd Gcd (insert a A)"
proof (rule Gcd_greatest)
fix b
assume "b \<in> insert a A"
then show "gcd a (Gcd A) dvd b"
proof
assume "b = a"
then show ?thesis
by simp
next
assume "b \<in> A"
then have "Gcd A dvd b"
by (rule Gcd_dvd)
moreover have "gcd a (Gcd A) dvd Gcd A"
by simp
ultimately show ?thesis
by (blast intro: dvd_trans)
qed
qed
ultimately show ?thesis
by (auto intro: associated_eqI)
qed
lemma Lcm_insert [simp]: "Lcm (insert a A) = lcm a (Lcm A)"
proof (rule sym)
have "lcm a (Lcm A) dvd Lcm (insert a A)"
by (auto intro: dvd_Lcm Lcm_least)
moreover have "Lcm (insert a A) dvd lcm a (Lcm A)"
proof (rule Lcm_least)
fix b
assume "b \<in> insert a A"
then show "b dvd lcm a (Lcm A)"
proof
assume "b = a"
then show ?thesis by simp
next
assume "b \<in> A"
then have "b dvd Lcm A"
by (rule dvd_Lcm)
moreover have "Lcm A dvd lcm a (Lcm A)"
by simp
ultimately show ?thesis
by (blast intro: dvd_trans)
qed
qed
ultimately show "lcm a (Lcm A) = Lcm (insert a A)"
by (rule associated_eqI) (simp_all add: lcm_eq_0_iff)
qed
lemma LcmI:
assumes "\<And>a. a \<in> A \<Longrightarrow> a dvd b"
and "\<And>c. (\<And>a. a \<in> A \<Longrightarrow> a dvd c) \<Longrightarrow> b dvd c"
and "normalize b = b"
shows "b = Lcm A"
by (rule associated_eqI) (auto simp: assms dvd_Lcm intro: Lcm_least)
lemma Lcm_subset: "A \<subseteq> B \<Longrightarrow> Lcm A dvd Lcm B"
by (blast intro: Lcm_least dvd_Lcm)
lemma Lcm_Un: "Lcm (A \<union> B) = lcm (Lcm A) (Lcm B)"
proof -
have "\<And>d. \<lbrakk>Lcm A dvd d; Lcm B dvd d\<rbrakk> \<Longrightarrow> Lcm (A \<union> B) dvd d"
by (meson UnE Lcm_least dvd_Lcm dvd_trans)
then show ?thesis
by (meson Lcm_subset lcm_unique normalize_Lcm sup.cobounded1 sup.cobounded2)
qed
lemma Gcd_0_iff [simp]: "Gcd A = 0 \<longleftrightarrow> A \<subseteq> {0}"
(is "?P \<longleftrightarrow> ?Q")
proof
assume ?P
show ?Q
proof
fix a
assume "a \<in> A"
then have "Gcd A dvd a"
by (rule Gcd_dvd)
with \<open>?P\<close> have "a = 0"
by simp
then show "a \<in> {0}"
by simp
qed
next
assume ?Q
have "0 dvd Gcd A"
proof (rule Gcd_greatest)
fix a
assume "a \<in> A"
with \<open>?Q\<close> have "a = 0"
by auto
then show "0 dvd a"
by simp
qed
then show ?P
by simp
qed
lemma Lcm_1_iff [simp]: "Lcm A = 1 \<longleftrightarrow> (\<forall>a\<in>A. is_unit a)"
(is "?P \<longleftrightarrow> ?Q")
proof
assume ?P
show ?Q
proof
fix a
assume "a \<in> A"
then have "a dvd Lcm A"
by (rule dvd_Lcm)
with \<open>?P\<close> show "is_unit a"
by simp
qed
next
assume ?Q
then have "is_unit (Lcm A)"
by (blast intro: Lcm_least)
then have "normalize (Lcm A) = 1"
by (rule is_unit_normalize)
then show ?P
by simp
qed
lemma unit_factor_Lcm: "unit_factor (Lcm A) = (if Lcm A = 0 then 0 else 1)"
proof (cases "Lcm A = 0")
case True
then show ?thesis
by simp
next
case False
with unit_factor_normalize have "unit_factor (normalize (Lcm A)) = 1"
by blast
with False show ?thesis
by simp
qed
lemma unit_factor_Gcd: "unit_factor (Gcd A) = (if Gcd A = 0 then 0 else 1)"
by (simp add: Gcd_Lcm unit_factor_Lcm)
lemma GcdI:
assumes "\<And>a. a \<in> A \<Longrightarrow> b dvd a"
and "\<And>c. (\<And>a. a \<in> A \<Longrightarrow> c dvd a) \<Longrightarrow> c dvd b"
and "normalize b = b"
shows "b = Gcd A"
by (rule associated_eqI) (auto simp: assms Gcd_dvd intro: Gcd_greatest)
lemma Gcd_eq_1_I:
assumes "is_unit a" and "a \<in> A"
shows "Gcd A = 1"
proof -
from assms have "is_unit (Gcd A)"
by (blast intro: Gcd_dvd dvd_unit_imp_unit)
then have "normalize (Gcd A) = 1"
by (rule is_unit_normalize)
then show ?thesis
by simp
qed
lemma Lcm_eq_0_I:
assumes "0 \<in> A"
shows "Lcm A = 0"
proof -
from assms have "0 dvd Lcm A"
by (rule dvd_Lcm)
then show ?thesis
by simp
qed
lemma Gcd_UNIV [simp]: "Gcd UNIV = 1"
using dvd_refl by (rule Gcd_eq_1_I) simp
lemma Lcm_UNIV [simp]: "Lcm UNIV = 0"
by (rule Lcm_eq_0_I) simp
lemma Lcm_0_iff:
assumes "finite A"
shows "Lcm A = 0 \<longleftrightarrow> 0 \<in> A"
proof (cases "A = {}")
case True
then show ?thesis by simp
next
case False
with assms show ?thesis
by (induct A rule: finite_ne_induct) (auto simp: lcm_eq_0_iff)
qed
lemma Gcd_image_normalize [simp]: "Gcd (normalize ` A) = Gcd A"
proof -
have "Gcd (normalize ` A) dvd a" if "a \<in> A" for a
proof -
from that obtain B where "A = insert a B"
by blast
moreover have "gcd (normalize a) (Gcd (normalize ` B)) dvd normalize a"
by (rule gcd_dvd1)
ultimately show "Gcd (normalize ` A) dvd a"
by simp
qed
then have "Gcd (normalize ` A) dvd Gcd A" and "Gcd A dvd Gcd (normalize ` A)"
by (auto intro!: Gcd_greatest intro: Gcd_dvd)
then show ?thesis
by (auto intro: associated_eqI)
qed
lemma Gcd_eqI:
assumes "normalize a = a"
assumes "\<And>b. b \<in> A \<Longrightarrow> a dvd b"
and "\<And>c. (\<And>b. b \<in> A \<Longrightarrow> c dvd b) \<Longrightarrow> c dvd a"
shows "Gcd A = a"
using assms by (blast intro: associated_eqI Gcd_greatest Gcd_dvd normalize_Gcd)
lemma dvd_GcdD: "x dvd Gcd A \<Longrightarrow> y \<in> A \<Longrightarrow> x dvd y"
using Gcd_dvd dvd_trans by blast
lemma dvd_Gcd_iff: "x dvd Gcd A \<longleftrightarrow> (\<forall>y\<in>A. x dvd y)"
by (blast dest: dvd_GcdD intro: Gcd_greatest)
lemma Gcd_mult: "Gcd ((*) c ` A) = normalize (c * Gcd A)"
proof (cases "c = 0")
case True
then show ?thesis by auto
next
case [simp]: False
have "Gcd ((*) c ` A) div c dvd Gcd A"
by (intro Gcd_greatest, subst div_dvd_iff_mult)
(auto intro!: Gcd_greatest Gcd_dvd simp: mult.commute[of _ c])
then have "Gcd ((*) c ` A) dvd c * Gcd A"
by (subst (asm) div_dvd_iff_mult) (auto intro: Gcd_greatest simp: mult_ac)
moreover have "c * Gcd A dvd Gcd ((*) c ` A)"
by (intro Gcd_greatest) (auto intro: mult_dvd_mono Gcd_dvd)
ultimately have "normalize (Gcd ((*) c ` A)) = normalize (c * Gcd A)"
by (rule associatedI)
then show ?thesis by simp
qed
lemma Lcm_eqI:
assumes "normalize a = a"
and "\<And>b. b \<in> A \<Longrightarrow> b dvd a"
and "\<And>c. (\<And>b. b \<in> A \<Longrightarrow> b dvd c) \<Longrightarrow> a dvd c"
shows "Lcm A = a"
using assms by (blast intro: associated_eqI Lcm_least dvd_Lcm normalize_Lcm)
lemma Lcm_dvdD: "Lcm A dvd x \<Longrightarrow> y \<in> A \<Longrightarrow> y dvd x"
using dvd_Lcm dvd_trans by blast
lemma Lcm_dvd_iff: "Lcm A dvd x \<longleftrightarrow> (\<forall>y\<in>A. y dvd x)"
by (blast dest: Lcm_dvdD intro: Lcm_least)
lemma Lcm_mult:
assumes "A \<noteq> {}"
shows "Lcm ((*) c ` A) = normalize (c * Lcm A)"
proof (cases "c = 0")
case True
with assms have "(*) c ` A = {0}"
by auto
with True show ?thesis by auto
next
case [simp]: False
from assms obtain x where x: "x \<in> A"
by blast
have "c dvd c * x"
by simp
also from x have "c * x dvd Lcm ((*) c ` A)"
by (intro dvd_Lcm) auto
finally have dvd: "c dvd Lcm ((*) c ` A)" .
moreover have "Lcm A dvd Lcm ((*) c ` A) div c"
by (intro Lcm_least dvd_mult_imp_div)
(auto intro!: Lcm_least dvd_Lcm simp: mult.commute[of _ c])
ultimately have "c * Lcm A dvd Lcm ((*) c ` A)"
by auto
moreover have "Lcm ((*) c ` A) dvd c * Lcm A"
by (intro Lcm_least) (auto intro: mult_dvd_mono dvd_Lcm)
ultimately have "normalize (c * Lcm A) = normalize (Lcm ((*) c ` A))"
by (rule associatedI)
then show ?thesis by simp
qed
lemma Lcm_no_units: "Lcm A = Lcm (A - {a. is_unit a})"
proof -
have "(A - {a. is_unit a}) \<union> {a\<in>A. is_unit a} = A"
by blast
then have "Lcm A = lcm (Lcm (A - {a. is_unit a})) (Lcm {a\<in>A. is_unit a})"
by (simp add: Lcm_Un [symmetric])
also have "Lcm {a\<in>A. is_unit a} = 1"
by simp
finally show ?thesis
by simp
qed
lemma Lcm_0_iff': "Lcm A = 0 \<longleftrightarrow> (\<nexists>l. l \<noteq> 0 \<and> (\<forall>a\<in>A. a dvd l))"
by (metis Lcm_least dvd_0_left dvd_Lcm)
lemma Lcm_no_multiple: "(\<forall>m. m \<noteq> 0 \<longrightarrow> (\<exists>a\<in>A. \<not> a dvd m)) \<Longrightarrow> Lcm A = 0"
by (auto simp: Lcm_0_iff')
lemma Lcm_singleton [simp]: "Lcm {a} = normalize a"
by simp
lemma Lcm_2 [simp]: "Lcm {a, b} = lcm a b"
by simp
lemma Gcd_1: "1 \<in> A \<Longrightarrow> Gcd A = 1"
by (auto intro!: Gcd_eq_1_I)
lemma Gcd_singleton [simp]: "Gcd {a} = normalize a"
by simp
lemma Gcd_2 [simp]: "Gcd {a, b} = gcd a b"
by simp
lemma Gcd_mono:
assumes "\<And>x. x \<in> A \<Longrightarrow> f x dvd g x"
shows "(GCD x\<in>A. f x) dvd (GCD x\<in>A. g x)"
proof (intro Gcd_greatest, safe)
fix x assume "x \<in> A"
hence "(GCD x\<in>A. f x) dvd f x"
by (intro Gcd_dvd) auto
also have "f x dvd g x"
using \<open>x \<in> A\<close> assms by blast
finally show "(GCD x\<in>A. f x) dvd \<dots>" .
qed
lemma Lcm_mono:
assumes "\<And>x. x \<in> A \<Longrightarrow> f x dvd g x"
shows "(LCM x\<in>A. f x) dvd (LCM x\<in>A. g x)"
proof (intro Lcm_least, safe)
fix x assume "x \<in> A"
hence "f x dvd g x" by (rule assms)
also have "g x dvd (LCM x\<in>A. g x)"
using \<open>x \<in> A\<close> by (intro dvd_Lcm) auto
finally show "f x dvd \<dots>" .
qed
end
subsection \<open>An aside: GCD and LCM on finite sets for incomplete gcd rings\<close>
context semiring_gcd
begin
sublocale Gcd_fin: bounded_quasi_semilattice_set gcd 0 1 normalize
defines
Gcd_fin ("Gcd\<^sub>f\<^sub>i\<^sub>n") = "Gcd_fin.F :: 'a set \<Rightarrow> 'a" ..
abbreviation gcd_list :: "'a list \<Rightarrow> 'a"
where "gcd_list xs \<equiv> Gcd\<^sub>f\<^sub>i\<^sub>n (set xs)"
sublocale Lcm_fin: bounded_quasi_semilattice_set lcm 1 0 normalize
defines
Lcm_fin ("Lcm\<^sub>f\<^sub>i\<^sub>n") = Lcm_fin.F ..
abbreviation lcm_list :: "'a list \<Rightarrow> 'a"
where "lcm_list xs \<equiv> Lcm\<^sub>f\<^sub>i\<^sub>n (set xs)"
lemma Gcd_fin_dvd:
"a \<in> A \<Longrightarrow> Gcd\<^sub>f\<^sub>i\<^sub>n A dvd a"
by (induct A rule: infinite_finite_induct)
(auto intro: dvd_trans)
lemma dvd_Lcm_fin:
"a \<in> A \<Longrightarrow> a dvd Lcm\<^sub>f\<^sub>i\<^sub>n A"
by (induct A rule: infinite_finite_induct)
(auto intro: dvd_trans)
lemma Gcd_fin_greatest:
"a dvd Gcd\<^sub>f\<^sub>i\<^sub>n A" if "finite A" and "\<And>b. b \<in> A \<Longrightarrow> a dvd b"
using that by (induct A) simp_all
lemma Lcm_fin_least:
"Lcm\<^sub>f\<^sub>i\<^sub>n A dvd a" if "finite A" and "\<And>b. b \<in> A \<Longrightarrow> b dvd a"
using that by (induct A) simp_all
lemma gcd_list_greatest:
"a dvd gcd_list bs" if "\<And>b. b \<in> set bs \<Longrightarrow> a dvd b"
by (rule Gcd_fin_greatest) (simp_all add: that)
lemma lcm_list_least:
"lcm_list bs dvd a" if "\<And>b. b \<in> set bs \<Longrightarrow> b dvd a"
by (rule Lcm_fin_least) (simp_all add: that)
lemma dvd_Gcd_fin_iff:
"b dvd Gcd\<^sub>f\<^sub>i\<^sub>n A \<longleftrightarrow> (\<forall>a\<in>A. b dvd a)" if "finite A"
using that by (auto intro: Gcd_fin_greatest Gcd_fin_dvd dvd_trans [of b "Gcd\<^sub>f\<^sub>i\<^sub>n A"])
lemma dvd_gcd_list_iff:
"b dvd gcd_list xs \<longleftrightarrow> (\<forall>a\<in>set xs. b dvd a)"
by (simp add: dvd_Gcd_fin_iff)
lemma Lcm_fin_dvd_iff:
"Lcm\<^sub>f\<^sub>i\<^sub>n A dvd b \<longleftrightarrow> (\<forall>a\<in>A. a dvd b)" if "finite A"
using that by (auto intro: Lcm_fin_least dvd_Lcm_fin dvd_trans [of _ "Lcm\<^sub>f\<^sub>i\<^sub>n A" b])
lemma lcm_list_dvd_iff:
"lcm_list xs dvd b \<longleftrightarrow> (\<forall>a\<in>set xs. a dvd b)"
by (simp add: Lcm_fin_dvd_iff)
lemma Gcd_fin_mult:
"Gcd\<^sub>f\<^sub>i\<^sub>n (image (times b) A) = normalize (b * Gcd\<^sub>f\<^sub>i\<^sub>n A)" if "finite A"
using that by induction (auto simp: gcd_mult_left)
lemma Lcm_fin_mult:
"Lcm\<^sub>f\<^sub>i\<^sub>n (image (times b) A) = normalize (b * Lcm\<^sub>f\<^sub>i\<^sub>n A)" if "A \<noteq> {}"
proof (cases "b = 0")
case True
moreover from that have "times 0 ` A = {0}"
by auto
ultimately show ?thesis
by simp
next
case False
show ?thesis proof (cases "finite A")
case False
moreover have "inj_on (times b) A"
using \<open>b \<noteq> 0\<close> by (rule inj_on_mult)
ultimately have "infinite (times b ` A)"
by (simp add: finite_image_iff)
with False show ?thesis
by simp
next
case True
then show ?thesis using that
by (induct A rule: finite_ne_induct) (auto simp: lcm_mult_left)
qed
qed
lemma unit_factor_Gcd_fin:
"unit_factor (Gcd\<^sub>f\<^sub>i\<^sub>n A) = of_bool (Gcd\<^sub>f\<^sub>i\<^sub>n A \<noteq> 0)"
by (rule normalize_idem_imp_unit_factor_eq) simp
lemma unit_factor_Lcm_fin:
"unit_factor (Lcm\<^sub>f\<^sub>i\<^sub>n A) = of_bool (Lcm\<^sub>f\<^sub>i\<^sub>n A \<noteq> 0)"
by (rule normalize_idem_imp_unit_factor_eq) simp
lemma is_unit_Gcd_fin_iff [simp]:
"is_unit (Gcd\<^sub>f\<^sub>i\<^sub>n A) \<longleftrightarrow> Gcd\<^sub>f\<^sub>i\<^sub>n A = 1"
by (rule normalize_idem_imp_is_unit_iff) simp
lemma is_unit_Lcm_fin_iff [simp]:
"is_unit (Lcm\<^sub>f\<^sub>i\<^sub>n A) \<longleftrightarrow> Lcm\<^sub>f\<^sub>i\<^sub>n A = 1"
by (rule normalize_idem_imp_is_unit_iff) simp
lemma Gcd_fin_0_iff:
"Gcd\<^sub>f\<^sub>i\<^sub>n A = 0 \<longleftrightarrow> A \<subseteq> {0} \<and> finite A"
by (induct A rule: infinite_finite_induct) simp_all
lemma Lcm_fin_0_iff:
"Lcm\<^sub>f\<^sub>i\<^sub>n A = 0 \<longleftrightarrow> 0 \<in> A" if "finite A"
using that by (induct A) (auto simp: lcm_eq_0_iff)
lemma Lcm_fin_1_iff:
"Lcm\<^sub>f\<^sub>i\<^sub>n A = 1 \<longleftrightarrow> (\<forall>a\<in>A. is_unit a) \<and> finite A"
by (induct A rule: infinite_finite_induct) simp_all
end
context semiring_Gcd
begin
lemma Gcd_fin_eq_Gcd [simp]:
"Gcd\<^sub>f\<^sub>i\<^sub>n A = Gcd A" if "finite A" for A :: "'a set"
using that by induct simp_all
lemma Gcd_set_eq_fold [code_unfold]:
"Gcd (set xs) = fold gcd xs 0"
by (simp add: Gcd_fin.set_eq_fold [symmetric])
lemma Lcm_fin_eq_Lcm [simp]:
"Lcm\<^sub>f\<^sub>i\<^sub>n A = Lcm A" if "finite A" for A :: "'a set"
using that by induct simp_all
lemma Lcm_set_eq_fold [code_unfold]:
"Lcm (set xs) = fold lcm xs 1"
by (simp add: Lcm_fin.set_eq_fold [symmetric])
end
subsection \<open>Coprimality\<close>
context semiring_gcd
begin
lemma coprime_imp_gcd_eq_1 [simp]:
"gcd a b = 1" if "coprime a b"
proof -
define t r s where "t = gcd a b" and "r = a div t" and "s = b div t"
then have "a = t * r" and "b = t * s"
by simp_all
with that have "coprime (t * r) (t * s)"
by simp
then show ?thesis
by (simp add: t_def)
qed
lemma gcd_eq_1_imp_coprime [dest!]:
"coprime a b" if "gcd a b = 1"
proof (rule coprimeI)
fix c
assume "c dvd a" and "c dvd b"
then have "c dvd gcd a b"
by (rule gcd_greatest)
with that show "is_unit c"
by simp
qed
lemma coprime_iff_gcd_eq_1 [presburger, code]:
"coprime a b \<longleftrightarrow> gcd a b = 1"
by rule (simp_all add: gcd_eq_1_imp_coprime)
lemma is_unit_gcd [simp]:
"is_unit (gcd a b) \<longleftrightarrow> coprime a b"
by (simp add: coprime_iff_gcd_eq_1)
lemma coprime_add_one_left [simp]: "coprime (a + 1) a"
by (simp add: gcd_eq_1_imp_coprime ac_simps)
lemma coprime_add_one_right [simp]: "coprime a (a + 1)"
using coprime_add_one_left [of a] by (simp add: ac_simps)
lemma coprime_mult_left_iff [simp]:
"coprime (a * b) c \<longleftrightarrow> coprime a c \<and> coprime b c"
proof
assume "coprime (a * b) c"
with coprime_common_divisor [of "a * b" c]
have *: "is_unit d" if "d dvd a * b" and "d dvd c" for d
using that by blast
have "coprime a c"
by (rule coprimeI, rule *) simp_all
moreover have "coprime b c"
by (rule coprimeI, rule *) simp_all
ultimately show "coprime a c \<and> coprime b c" ..
next
assume "coprime a c \<and> coprime b c"
then have "coprime a c" "coprime b c"
by simp_all
show "coprime (a * b) c"
proof (rule coprimeI)
fix d
assume "d dvd a * b"
then obtain r s where d: "d = r * s" "r dvd a" "s dvd b"
by (rule dvd_productE)
assume "d dvd c"
with d have "r * s dvd c"
by simp
then have "r dvd c" "s dvd c"
by (auto intro: dvd_mult_left dvd_mult_right)
from \<open>coprime a c\<close> \<open>r dvd a\<close> \<open>r dvd c\<close>
have "is_unit r"
by (rule coprime_common_divisor)
moreover from \<open>coprime b c\<close> \<open>s dvd b\<close> \<open>s dvd c\<close>
have "is_unit s"
by (rule coprime_common_divisor)
ultimately show "is_unit d"
by (simp add: d is_unit_mult_iff)
qed
qed
lemma coprime_mult_right_iff [simp]:
"coprime c (a * b) \<longleftrightarrow> coprime c a \<and> coprime c b"
using coprime_mult_left_iff [of a b c] by (simp add: ac_simps)
lemma coprime_power_left_iff [simp]:
"coprime (a ^ n) b \<longleftrightarrow> coprime a b \<or> n = 0"
proof (cases "n = 0")
case True
then show ?thesis
by simp
next
case False
then have "n > 0"
by simp
then show ?thesis
by (induction n rule: nat_induct_non_zero) simp_all
qed
lemma coprime_power_right_iff [simp]:
"coprime a (b ^ n) \<longleftrightarrow> coprime a b \<or> n = 0"
using coprime_power_left_iff [of b n a] by (simp add: ac_simps)
lemma prod_coprime_left:
"coprime (\<Prod>i\<in>A. f i) a" if "\<And>i. i \<in> A \<Longrightarrow> coprime (f i) a"
using that by (induct A rule: infinite_finite_induct) simp_all
lemma prod_coprime_right:
"coprime a (\<Prod>i\<in>A. f i)" if "\<And>i. i \<in> A \<Longrightarrow> coprime a (f i)"
using that prod_coprime_left [of A f a] by (simp add: ac_simps)
lemma prod_list_coprime_left:
"coprime (prod_list xs) a" if "\<And>x. x \<in> set xs \<Longrightarrow> coprime x a"
using that by (induct xs) simp_all
lemma prod_list_coprime_right:
"coprime a (prod_list xs)" if "\<And>x. x \<in> set xs \<Longrightarrow> coprime a x"
using that prod_list_coprime_left [of xs a] by (simp add: ac_simps)
lemma coprime_dvd_mult_left_iff:
"a dvd b * c \<longleftrightarrow> a dvd b" if "coprime a c"
proof
assume "a dvd b"
then show "a dvd b * c"
by simp
next
assume "a dvd b * c"
show "a dvd b"
proof (cases "b = 0")
case True
then show ?thesis
by simp
next
case False
then have unit: "is_unit (unit_factor b)"
by simp
from \<open>coprime a c\<close>
have "gcd (b * a) (b * c) * unit_factor b = b"
by (subst gcd_mult_left) (simp add: ac_simps)
moreover from \<open>a dvd b * c\<close>
have "a dvd gcd (b * a) (b * c) * unit_factor b"
by (simp add: dvd_mult_unit_iff unit)
ultimately show ?thesis
by simp
qed
qed
lemma coprime_dvd_mult_right_iff:
"a dvd c * b \<longleftrightarrow> a dvd b" if "coprime a c"
using that coprime_dvd_mult_left_iff [of a c b] by (simp add: ac_simps)
lemma divides_mult:
"a * b dvd c" if "a dvd c" and "b dvd c" and "coprime a b"
proof -
from \<open>b dvd c\<close> obtain b' where "c = b * b'" ..
with \<open>a dvd c\<close> have "a dvd b' * b"
by (simp add: ac_simps)
with \<open>coprime a b\<close> have "a dvd b'"
by (simp add: coprime_dvd_mult_left_iff)
then obtain a' where "b' = a * a'" ..
with \<open>c = b * b'\<close> have "c = (a * b) * a'"
by (simp add: ac_simps)
then show ?thesis ..
qed
lemma div_gcd_coprime:
assumes "a \<noteq> 0 \<or> b \<noteq> 0"
shows "coprime (a div gcd a b) (b div gcd a b)"
proof -
let ?g = "gcd a b"
let ?a' = "a div ?g"
let ?b' = "b div ?g"
let ?g' = "gcd ?a' ?b'"
have dvdg: "?g dvd a" "?g dvd b"
by simp_all
have dvdg': "?g' dvd ?a'" "?g' dvd ?b'"
by simp_all
from dvdg dvdg' obtain ka kb ka' kb' where
kab: "a = ?g * ka" "b = ?g * kb" "?a' = ?g' * ka'" "?b' = ?g' * kb'"
unfolding dvd_def by blast
from this [symmetric] have "?g * ?a' = (?g * ?g') * ka'" "?g * ?b' = (?g * ?g') * kb'"
by (simp_all add: mult.assoc mult.left_commute [of "gcd a b"])
then have dvdgg':"?g * ?g' dvd a" "?g* ?g' dvd b"
by (auto simp: dvd_mult_div_cancel [OF dvdg(1)] dvd_mult_div_cancel [OF dvdg(2)] dvd_def)
have "?g \<noteq> 0"
using assms by simp
moreover from gcd_greatest [OF dvdgg'] have "?g * ?g' dvd ?g" .
ultimately show ?thesis
using dvd_times_left_cancel_iff [of "gcd a b" _ 1]
by simp (simp only: coprime_iff_gcd_eq_1)
qed
lemma gcd_coprime:
assumes c: "gcd a b \<noteq> 0"
and a: "a = a' * gcd a b"
and b: "b = b' * gcd a b"
shows "coprime a' b'"
proof -
from c have "a \<noteq> 0 \<or> b \<noteq> 0"
by simp
with div_gcd_coprime have "coprime (a div gcd a b) (b div gcd a b)" .
also from assms have "a div gcd a b = a'"
using dvd_div_eq_mult gcd_dvd1 by blast
also from assms have "b div gcd a b = b'"
using dvd_div_eq_mult gcd_dvd1 by blast
finally show ?thesis .
qed
lemma gcd_coprime_exists:
assumes "gcd a b \<noteq> 0"
shows "\<exists>a' b'. a = a' * gcd a b \<and> b = b' * gcd a b \<and> coprime a' b'"
proof -
have "coprime (a div gcd a b) (b div gcd a b)"
using assms div_gcd_coprime by auto
then show ?thesis
by force
qed
lemma pow_divides_pow_iff [simp]:
"a ^ n dvd b ^ n \<longleftrightarrow> a dvd b" if "n > 0"
proof (cases "gcd a b = 0")
case True
then show ?thesis
by simp
next
case False
show ?thesis
proof
let ?d = "gcd a b"
from \<open>n > 0\<close> obtain m where m: "n = Suc m"
by (cases n) simp_all
from False have zn: "?d ^ n \<noteq> 0"
by (rule power_not_zero)
from gcd_coprime_exists [OF False]
obtain a' b' where ab': "a = a' * ?d" "b = b' * ?d" "coprime a' b'"
by blast
assume "a ^ n dvd b ^ n"
then have "(a' * ?d) ^ n dvd (b' * ?d) ^ n"
by (simp add: ab'(1,2)[symmetric])
then have "?d^n * a'^n dvd ?d^n * b'^n"
by (simp only: power_mult_distrib ac_simps)
with zn have "a' ^ n dvd b' ^ n"
by simp
then have "a' dvd b' ^ n"
using dvd_trans[of a' "a'^n" "b'^n"] by (simp add: m)
then have "a' dvd b' ^ m * b'"
by (simp add: m ac_simps)
moreover have "coprime a' (b' ^ n)"
using \<open>coprime a' b'\<close> by simp
then have "a' dvd b'"
using \<open>a' dvd b' ^ n\<close> coprime_dvd_mult_left_iff dvd_mult by blast
then have "a' * ?d dvd b' * ?d"
by (rule mult_dvd_mono) simp
with ab'(1,2) show "a dvd b"
by simp
next
assume "a dvd b"
with \<open>n > 0\<close> show "a ^ n dvd b ^ n"
by (induction rule: nat_induct_non_zero)
(simp_all add: mult_dvd_mono)
qed
qed
lemma coprime_crossproduct:
fixes a b c d :: 'a
assumes "coprime a d" and "coprime b c"
shows "normalize a * normalize c = normalize b * normalize d \<longleftrightarrow>
normalize a = normalize b \<and> normalize c = normalize d"
(is "?lhs \<longleftrightarrow> ?rhs")
proof
assume ?rhs
then show ?lhs by simp
next
assume ?lhs
from \<open>?lhs\<close> have "normalize a dvd normalize b * normalize d"
by (auto intro: dvdI dest: sym)
with \<open>coprime a d\<close> have "a dvd b"
by (simp add: coprime_dvd_mult_left_iff normalize_mult [symmetric])
from \<open>?lhs\<close> have "normalize b dvd normalize a * normalize c"
by (auto intro: dvdI dest: sym)
with \<open>coprime b c\<close> have "b dvd a"
by (simp add: coprime_dvd_mult_left_iff normalize_mult [symmetric])
from \<open>?lhs\<close> have "normalize c dvd normalize d * normalize b"
by (auto intro: dvdI dest: sym simp add: mult.commute)
with \<open>coprime b c\<close> have "c dvd d"
by (simp add: coprime_dvd_mult_left_iff coprime_commute normalize_mult [symmetric])
from \<open>?lhs\<close> have "normalize d dvd normalize c * normalize a"
by (auto intro: dvdI dest: sym simp add: mult.commute)
with \<open>coprime a d\<close> have "d dvd c"
by (simp add: coprime_dvd_mult_left_iff coprime_commute normalize_mult [symmetric])
from \<open>a dvd b\<close> \<open>b dvd a\<close> have "normalize a = normalize b"
by (rule associatedI)
moreover from \<open>c dvd d\<close> \<open>d dvd c\<close> have "normalize c = normalize d"
by (rule associatedI)
ultimately show ?rhs ..
qed
lemma gcd_mult_left_left_cancel:
"gcd (c * a) b = gcd a b" if "coprime b c"
proof -
have "coprime (gcd b (a * c)) c"
by (rule coprimeI) (auto intro: that coprime_common_divisor)
then have "gcd b (a * c) dvd a"
using coprime_dvd_mult_left_iff [of "gcd b (a * c)" c a]
by simp
then show ?thesis
by (auto intro: associated_eqI simp add: ac_simps)
qed
lemma gcd_mult_left_right_cancel:
"gcd (a * c) b = gcd a b" if "coprime b c"
using that gcd_mult_left_left_cancel [of b c a]
by (simp add: ac_simps)
lemma gcd_mult_right_left_cancel:
"gcd a (c * b) = gcd a b" if "coprime a c"
using that gcd_mult_left_left_cancel [of a c b]
by (simp add: ac_simps)
lemma gcd_mult_right_right_cancel:
"gcd a (b * c) = gcd a b" if "coprime a c"
using that gcd_mult_right_left_cancel [of a c b]
by (simp add: ac_simps)
lemma gcd_exp_weak:
"gcd (a ^ n) (b ^ n) = normalize (gcd a b ^ n)"
proof (cases "a = 0 \<and> b = 0 \<or> n = 0")
case True
then show ?thesis
by (cases n) simp_all
next
case False
then have "coprime (a div gcd a b) (b div gcd a b)" and "n > 0"
by (auto intro: div_gcd_coprime)
then have "coprime ((a div gcd a b) ^ n) ((b div gcd a b) ^ n)"
by simp
then have "1 = gcd ((a div gcd a b) ^ n) ((b div gcd a b) ^ n)"
by simp
then have "normalize (gcd a b ^ n) = normalize (gcd a b ^ n * \<dots>)"
by simp
also have "\<dots> = gcd (gcd a b ^ n * (a div gcd a b) ^ n) (gcd a b ^ n * (b div gcd a b) ^ n)"
by (rule gcd_mult_left [symmetric])
also have "(gcd a b) ^ n * (a div gcd a b) ^ n = a ^ n"
by (simp add: ac_simps div_power dvd_power_same)
also have "(gcd a b) ^ n * (b div gcd a b) ^ n = b ^ n"
by (simp add: ac_simps div_power dvd_power_same)
finally show ?thesis by simp
qed
lemma division_decomp:
assumes "a dvd b * c"
shows "\<exists>b' c'. a = b' * c' \<and> b' dvd b \<and> c' dvd c"
proof (cases "gcd a b = 0")
case True
then have "a = 0 \<and> b = 0"
by simp
then have "a = 0 * c \<and> 0 dvd b \<and> c dvd c"
by simp
then show ?thesis by blast
next
case False
let ?d = "gcd a b"
from gcd_coprime_exists [OF False]
obtain a' b' where ab': "a = a' * ?d" "b = b' * ?d" "coprime a' b'"
by blast
from ab'(1) have "a' dvd a" ..
with assms have "a' dvd b * c"
using dvd_trans [of a' a "b * c"] by simp
from assms ab'(1,2) have "a' * ?d dvd (b' * ?d) * c"
by simp
then have "?d * a' dvd ?d * (b' * c)"
by (simp add: mult_ac)
with \<open>?d \<noteq> 0\<close> have "a' dvd b' * c"
by simp
then have "a' dvd c"
using \<open>coprime a' b'\<close> by (simp add: coprime_dvd_mult_right_iff)
with ab'(1) have "a = ?d * a' \<and> ?d dvd b \<and> a' dvd c"
by (simp add: ac_simps)
then show ?thesis by blast
qed
lemma lcm_coprime: "coprime a b \<Longrightarrow> lcm a b = normalize (a * b)"
by (subst lcm_gcd) simp
end
context ring_gcd
begin
lemma coprime_minus_left_iff [simp]:
"coprime (- a) b \<longleftrightarrow> coprime a b"
by (rule; rule coprimeI) (auto intro: coprime_common_divisor)
lemma coprime_minus_right_iff [simp]:
"coprime a (- b) \<longleftrightarrow> coprime a b"
using coprime_minus_left_iff [of b a] by (simp add: ac_simps)
lemma coprime_diff_one_left [simp]: "coprime (a - 1) a"
using coprime_add_one_right [of "a - 1"] by simp
lemma coprime_doff_one_right [simp]: "coprime a (a - 1)"
using coprime_diff_one_left [of a] by (simp add: ac_simps)
end
context semiring_Gcd
begin
lemma Lcm_coprime:
assumes "finite A"
and "A \<noteq> {}"
and "\<And>a b. a \<in> A \<Longrightarrow> b \<in> A \<Longrightarrow> a \<noteq> b \<Longrightarrow> coprime a b"
shows "Lcm A = normalize (\<Prod>A)"
using assms
proof (induct rule: finite_ne_induct)
case singleton
then show ?case by simp
next
case (insert a A)
have "Lcm (insert a A) = lcm a (Lcm A)"
by simp
also from insert have "Lcm A = normalize (\<Prod>A)"
by blast
also have "lcm a \<dots> = lcm a (\<Prod>A)"
by (cases "\<Prod>A = 0") (simp_all add: lcm_div_unit2)
also from insert have "coprime a (\<Prod>A)"
by (subst coprime_commute, intro prod_coprime_left) auto
with insert have "lcm a (\<Prod>A) = normalize (\<Prod>(insert a A))"
by (simp add: lcm_coprime)
finally show ?case .
qed
lemma Lcm_coprime':
"card A \<noteq> 0 \<Longrightarrow>
(\<And>a b. a \<in> A \<Longrightarrow> b \<in> A \<Longrightarrow> a \<noteq> b \<Longrightarrow> coprime a b) \<Longrightarrow>
Lcm A = normalize (\<Prod>A)"
by (rule Lcm_coprime) (simp_all add: card_eq_0_iff)
end
text \<open>And some consequences: cancellation modulo @{term m}\<close>
lemma mult_mod_cancel_right:
fixes m :: "'a::{euclidean_ring_cancel,semiring_gcd}"
assumes eq: "(a * n) mod m = (b * n) mod m" and "coprime m n"
shows "a mod m = b mod m"
proof -
have "m dvd (a*n - b*n)"
using eq mod_eq_dvd_iff by blast
then have "m dvd a-b"
by (metis \<open>coprime m n\<close> coprime_dvd_mult_left_iff left_diff_distrib')
then show ?thesis
using mod_eq_dvd_iff by blast
qed
lemma mult_mod_cancel_left:
fixes m :: "'a::{euclidean_ring_cancel,semiring_gcd}"
assumes "(n * a) mod m = (n * b) mod m" and "coprime m n"
shows "a mod m = b mod m"
by (metis assms mult.commute mult_mod_cancel_right)
subsection \<open>GCD and LCM for multiplicative normalisation functions\<close>
class semiring_gcd_mult_normalize = semiring_gcd + normalization_semidom_multiplicative
begin
lemma mult_gcd_left: "c * gcd a b = unit_factor c * gcd (c * a) (c * b)"
by (simp add: gcd_mult_left normalize_mult mult.assoc [symmetric])
lemma mult_gcd_right: "gcd a b * c = gcd (a * c) (b * c) * unit_factor c"
using mult_gcd_left [of c a b] by (simp add: ac_simps)
lemma gcd_mult_distrib': "normalize c * gcd a b = gcd (c * a) (c * b)"
by (subst gcd_mult_left) (simp_all add: normalize_mult)
lemma gcd_mult_distrib: "k * gcd a b = gcd (k * a) (k * b) * unit_factor k"
proof-
have "normalize k * gcd a b = gcd (k * a) (k * b)"
by (simp add: gcd_mult_distrib')
then have "normalize k * gcd a b * unit_factor k = gcd (k * a) (k * b) * unit_factor k"
by simp
then have "normalize k * unit_factor k * gcd a b = gcd (k * a) (k * b) * unit_factor k"
by (simp only: ac_simps)
then show ?thesis
by simp
qed
lemma gcd_mult_lcm [simp]: "gcd a b * lcm a b = normalize a * normalize b"
by (simp add: lcm_gcd normalize_mult dvd_normalize_div)
lemma lcm_mult_gcd [simp]: "lcm a b * gcd a b = normalize a * normalize b"
using gcd_mult_lcm [of a b] by (simp add: ac_simps)
lemma mult_lcm_left: "c * lcm a b = unit_factor c * lcm (c * a) (c * b)"
by (simp add: lcm_mult_left mult.assoc [symmetric] normalize_mult)
lemma mult_lcm_right: "lcm a b * c = lcm (a * c) (b * c) * unit_factor c"
using mult_lcm_left [of c a b] by (simp add: ac_simps)
lemma lcm_gcd_prod: "lcm a b * gcd a b = normalize (a * b)"
by (simp add: lcm_gcd dvd_normalize_div normalize_mult)
lemma lcm_mult_distrib': "normalize c * lcm a b = lcm (c * a) (c * b)"
by (subst lcm_mult_left) (simp add: normalize_mult)
lemma lcm_mult_distrib: "k * lcm a b = lcm (k * a) (k * b) * unit_factor k"
proof-
have "normalize k * lcm a b = lcm (k * a) (k * b)"
by (simp add: lcm_mult_distrib')
then have "normalize k * lcm a b * unit_factor k = lcm (k * a) (k * b) * unit_factor k"
by simp
then have "normalize k * unit_factor k * lcm a b = lcm (k * a) (k * b) * unit_factor k"
by (simp only: ac_simps)
then show ?thesis
by simp
qed
lemma coprime_crossproduct':
fixes a b c d
assumes "b \<noteq> 0"
assumes unit_factors: "unit_factor b = unit_factor d"
assumes coprime: "coprime a b" "coprime c d"
shows "a * d = b * c \<longleftrightarrow> a = c \<and> b = d"
proof safe
assume eq: "a * d = b * c"
hence "normalize a * normalize d = normalize c * normalize b"
by (simp only: normalize_mult [symmetric] mult_ac)
with coprime have "normalize b = normalize d"
by (subst (asm) coprime_crossproduct) simp_all
from this and unit_factors show "b = d"
by (rule normalize_unit_factor_eqI)
from eq have "a * d = c * d" by (simp only: \<open>b = d\<close> mult_ac)
with \<open>b \<noteq> 0\<close> \<open>b = d\<close> show "a = c" by simp
qed (simp_all add: mult_ac)
lemma gcd_exp [simp]:
"gcd (a ^ n) (b ^ n) = gcd a b ^ n"
using gcd_exp_weak[of a n b] by (simp add: normalize_power)
end
subsection \<open>GCD and LCM on \<^typ>\<open>nat\<close> and \<^typ>\<open>int\<close>\<close>
instantiation nat :: gcd
begin
fun gcd_nat :: "nat \<Rightarrow> nat \<Rightarrow> nat"
where "gcd_nat x y = (if y = 0 then x else gcd y (x mod y))"
definition lcm_nat :: "nat \<Rightarrow> nat \<Rightarrow> nat"
where "lcm_nat x y = x * y div (gcd x y)"
instance ..
end
instantiation int :: gcd
begin
definition gcd_int :: "int \<Rightarrow> int \<Rightarrow> int"
where "gcd_int x y = int (gcd (nat \<bar>x\<bar>) (nat \<bar>y\<bar>))"
definition lcm_int :: "int \<Rightarrow> int \<Rightarrow> int"
where "lcm_int x y = int (lcm (nat \<bar>x\<bar>) (nat \<bar>y\<bar>))"
instance ..
end
lemma gcd_int_int_eq [simp]:
"gcd (int m) (int n) = int (gcd m n)"
by (simp add: gcd_int_def)
lemma gcd_nat_abs_left_eq [simp]:
"gcd (nat \<bar>k\<bar>) n = nat (gcd k (int n))"
by (simp add: gcd_int_def)
lemma gcd_nat_abs_right_eq [simp]:
"gcd n (nat \<bar>k\<bar>) = nat (gcd (int n) k)"
by (simp add: gcd_int_def)
lemma abs_gcd_int [simp]:
"\<bar>gcd x y\<bar> = gcd x y"
for x y :: int
by (simp only: gcd_int_def)
lemma gcd_abs1_int [simp]:
"gcd \<bar>x\<bar> y = gcd x y"
for x y :: int
by (simp only: gcd_int_def) simp
lemma gcd_abs2_int [simp]:
"gcd x \<bar>y\<bar> = gcd x y"
for x y :: int
by (simp only: gcd_int_def) simp
lemma lcm_int_int_eq [simp]:
"lcm (int m) (int n) = int (lcm m n)"
by (simp add: lcm_int_def)
lemma lcm_nat_abs_left_eq [simp]:
"lcm (nat \<bar>k\<bar>) n = nat (lcm k (int n))"
by (simp add: lcm_int_def)
lemma lcm_nat_abs_right_eq [simp]:
"lcm n (nat \<bar>k\<bar>) = nat (lcm (int n) k)"
by (simp add: lcm_int_def)
lemma lcm_abs1_int [simp]:
"lcm \<bar>x\<bar> y = lcm x y"
for x y :: int
by (simp only: lcm_int_def) simp
lemma lcm_abs2_int [simp]:
"lcm x \<bar>y\<bar> = lcm x y"
for x y :: int
by (simp only: lcm_int_def) simp
lemma abs_lcm_int [simp]: "\<bar>lcm i j\<bar> = lcm i j"
for i j :: int
by (simp only: lcm_int_def)
lemma gcd_nat_induct [case_names base step]:
fixes m n :: nat
assumes "\<And>m. P m 0"
and "\<And>m n. 0 < n \<Longrightarrow> P n (m mod n) \<Longrightarrow> P m n"
shows "P m n"
proof (induction m n rule: gcd_nat.induct)
case (1 x y)
then show ?case
using assms neq0_conv by blast
qed
lemma gcd_neg1_int [simp]: "gcd (- x) y = gcd x y"
for x y :: int
by (simp only: gcd_int_def) simp
lemma gcd_neg2_int [simp]: "gcd x (- y) = gcd x y"
for x y :: int
by (simp only: gcd_int_def) simp
lemma gcd_cases_int:
fixes x y :: int
assumes "x \<ge> 0 \<Longrightarrow> y \<ge> 0 \<Longrightarrow> P (gcd x y)"
and "x \<ge> 0 \<Longrightarrow> y \<le> 0 \<Longrightarrow> P (gcd x (- y))"
and "x \<le> 0 \<Longrightarrow> y \<ge> 0 \<Longrightarrow> P (gcd (- x) y)"
and "x \<le> 0 \<Longrightarrow> y \<le> 0 \<Longrightarrow> P (gcd (- x) (- y))"
shows "P (gcd x y)"
using assms by auto arith
lemma gcd_ge_0_int [simp]: "gcd (x::int) y >= 0"
for x y :: int
by (simp add: gcd_int_def)
lemma lcm_neg1_int: "lcm (- x) y = lcm x y"
for x y :: int
by (simp only: lcm_int_def) simp
lemma lcm_neg2_int: "lcm x (- y) = lcm x y"
for x y :: int
by (simp only: lcm_int_def) simp
lemma lcm_cases_int:
fixes x y :: int
assumes "x \<ge> 0 \<Longrightarrow> y \<ge> 0 \<Longrightarrow> P (lcm x y)"
and "x \<ge> 0 \<Longrightarrow> y \<le> 0 \<Longrightarrow> P (lcm x (- y))"
and "x \<le> 0 \<Longrightarrow> y \<ge> 0 \<Longrightarrow> P (lcm (- x) y)"
and "x \<le> 0 \<Longrightarrow> y \<le> 0 \<Longrightarrow> P (lcm (- x) (- y))"
shows "P (lcm x y)"
using assms by (auto simp: lcm_neg1_int lcm_neg2_int) arith
lemma lcm_ge_0_int [simp]: "lcm x y \<ge> 0"
for x y :: int
by (simp only: lcm_int_def)
lemma gcd_0_nat: "gcd x 0 = x"
for x :: nat
by simp
lemma gcd_0_int [simp]: "gcd x 0 = \<bar>x\<bar>"
for x :: int
by (auto simp: gcd_int_def)
lemma gcd_0_left_nat: "gcd 0 x = x"
for x :: nat
by simp
lemma gcd_0_left_int [simp]: "gcd 0 x = \<bar>x\<bar>"
for x :: int
by (auto simp: gcd_int_def)
lemma gcd_red_nat: "gcd x y = gcd y (x mod y)"
for x y :: nat
by (cases "y = 0") auto
text \<open>Weaker, but useful for the simplifier.\<close>
lemma gcd_non_0_nat: "y \<noteq> 0 \<Longrightarrow> gcd x y = gcd y (x mod y)"
for x y :: nat
by simp
lemma gcd_1_nat [simp]: "gcd m 1 = 1"
for m :: nat
by simp
lemma gcd_Suc_0 [simp]: "gcd m (Suc 0) = Suc 0"
for m :: nat
by simp
lemma gcd_1_int [simp]: "gcd m 1 = 1"
for m :: int
by (simp add: gcd_int_def)
lemma gcd_idem_nat: "gcd x x = x"
for x :: nat
by simp
lemma gcd_idem_int: "gcd x x = \<bar>x\<bar>"
for x :: int
by (auto simp: gcd_int_def)
declare gcd_nat.simps [simp del]
text \<open>
\<^medskip> \<^term>\<open>gcd m n\<close> divides \<open>m\<close> and \<open>n\<close>.
The conjunctions don't seem provable separately.
\<close>
instance nat :: semiring_gcd
proof
fix m n :: nat
show "gcd m n dvd m" and "gcd m n dvd n"
proof (induct m n rule: gcd_nat_induct)
case (step m n)
then have "gcd n (m mod n) dvd m"
by (metis dvd_mod_imp_dvd)
with step show "gcd m n dvd m"
by (simp add: gcd_non_0_nat)
qed (simp_all add: gcd_0_nat gcd_non_0_nat)
next
fix m n k :: nat
assume "k dvd m" and "k dvd n"
then show "k dvd gcd m n"
by (induct m n rule: gcd_nat_induct) (simp_all add: gcd_non_0_nat dvd_mod gcd_0_nat)
qed (simp_all add: lcm_nat_def)
instance int :: ring_gcd
proof
fix k l r :: int
show [simp]: "gcd k l dvd k" "gcd k l dvd l"
using gcd_dvd1 [of "nat \<bar>k\<bar>" "nat \<bar>l\<bar>"]
gcd_dvd2 [of "nat \<bar>k\<bar>" "nat \<bar>l\<bar>"]
by simp_all
show "lcm k l = normalize (k * l div gcd k l)"
using lcm_gcd [of "nat \<bar>k\<bar>" "nat \<bar>l\<bar>"]
by (simp add: nat_eq_iff of_nat_div abs_mult abs_div)
assume "r dvd k" "r dvd l"
then show "r dvd gcd k l"
using gcd_greatest [of "nat \<bar>r\<bar>" "nat \<bar>k\<bar>" "nat \<bar>l\<bar>"]
by simp
qed simp
lemma gcd_le1_nat [simp]: "a \<noteq> 0 \<Longrightarrow> gcd a b \<le> a"
for a b :: nat
by (rule dvd_imp_le) auto
lemma gcd_le2_nat [simp]: "b \<noteq> 0 \<Longrightarrow> gcd a b \<le> b"
for a b :: nat
by (rule dvd_imp_le) auto
lemma gcd_le1_int [simp]: "a > 0 \<Longrightarrow> gcd a b \<le> a"
for a b :: int
by (rule zdvd_imp_le) auto
lemma gcd_le2_int [simp]: "b > 0 \<Longrightarrow> gcd a b \<le> b"
for a b :: int
by (rule zdvd_imp_le) auto
lemma gcd_pos_nat [simp]: "gcd m n > 0 \<longleftrightarrow> m \<noteq> 0 \<or> n \<noteq> 0"
for m n :: nat
using gcd_eq_0_iff [of m n] by arith
lemma gcd_pos_int [simp]: "gcd m n > 0 \<longleftrightarrow> m \<noteq> 0 \<or> n \<noteq> 0"
for m n :: int
using gcd_eq_0_iff [of m n] gcd_ge_0_int [of m n] by arith
lemma gcd_unique_nat: "d dvd a \<and> d dvd b \<and> (\<forall>e. e dvd a \<and> e dvd b \<longrightarrow> e dvd d) \<longleftrightarrow> d = gcd a b"
for d a :: nat
using gcd_unique by fastforce
lemma gcd_unique_int:
"d \<ge> 0 \<and> d dvd a \<and> d dvd b \<and> (\<forall>e. e dvd a \<and> e dvd b \<longrightarrow> e dvd d) \<longleftrightarrow> d = gcd a b"
for d a :: int
using zdvd_antisym_nonneg by auto
interpretation gcd_nat:
semilattice_neutr_order gcd "0::nat" Rings.dvd "\<lambda>m n. m dvd n \<and> m \<noteq> n"
by standard (auto simp: gcd_unique_nat [symmetric] intro: dvd_antisym dvd_trans)
lemma gcd_proj1_if_dvd_int [simp]: "x dvd y \<Longrightarrow> gcd x y = \<bar>x\<bar>"
for x y :: int
by (metis abs_dvd_iff gcd_0_left_int gcd_unique_int)
lemma gcd_proj2_if_dvd_int [simp]: "y dvd x \<Longrightarrow> gcd x y = \<bar>y\<bar>"
for x y :: int
by (metis gcd_proj1_if_dvd_int gcd.commute)
text \<open>\<^medskip> Multiplication laws.\<close>
lemma gcd_mult_distrib_nat: "k * gcd m n = gcd (k * m) (k * n)"
for k m n :: nat
\<comment> \<open>\<^cite>\<open>\<open>page 27\<close> in davenport92\<close>\<close>
by (simp add: gcd_mult_left)
lemma gcd_mult_distrib_int: "\<bar>k\<bar> * gcd m n = gcd (k * m) (k * n)"
for k m n :: int
by (simp add: gcd_mult_left abs_mult)
text \<open>\medskip Addition laws.\<close>
(* TODO: add the other variations? *)
lemma gcd_diff1_nat: "m \<ge> n \<Longrightarrow> gcd (m - n) n = gcd m n"
for m n :: nat
by (subst gcd_add1 [symmetric]) auto
lemma gcd_diff2_nat: "n \<ge> m \<Longrightarrow> gcd (n - m) n = gcd m n"
for m n :: nat
by (metis gcd.commute gcd_add2 gcd_diff1_nat le_add_diff_inverse2)
lemma gcd_non_0_int:
fixes x y :: int
assumes "y > 0" shows "gcd x y = gcd y (x mod y)"
proof (cases "x mod y = 0")
case False
then have neg: "x mod y = y - (- x) mod y"
by (simp add: zmod_zminus1_eq_if)
have xy: "0 \<le> x mod y"
by (simp add: assms)
show ?thesis
proof (cases "x < 0")
case True
have "nat (- x mod y) \<le> nat y"
by (simp add: assms dual_order.order_iff_strict)
moreover have "gcd (nat (- x)) (nat y) = gcd (nat (- x mod y)) (nat y)"
using True assms gcd_non_0_nat nat_mod_distrib by auto
ultimately have "gcd (nat (- x)) (nat y) = gcd (nat y) (nat (x mod y))"
using assms
by (simp add: neg nat_diff_distrib') (metis gcd.commute gcd_diff2_nat)
with assms \<open>0 \<le> x mod y\<close> show ?thesis
by (simp add: True dual_order.order_iff_strict gcd_int_def)
next
case False
with assms xy have "gcd (nat x) (nat y) = gcd (nat y) (nat x mod nat y)"
using gcd_red_nat by blast
with False assms show ?thesis
by (simp add: gcd_int_def nat_mod_distrib)
qed
qed (use assms in auto)
lemma gcd_red_int: "gcd x y = gcd y (x mod y)"
for x y :: int
proof (cases y "0::int" rule: linorder_cases)
case less
with gcd_non_0_int [of "- y" "- x"] show ?thesis
by auto
next
case greater
with gcd_non_0_int [of y x] show ?thesis
by auto
qed auto
(* TODO: differences, and all variations of addition rules
as simplification rules for nat and int *)
(* TODO: add the three variations of these, and for ints? *)
lemma finite_divisors_nat [simp]: (* FIXME move *)
fixes m :: nat
assumes "m > 0"
shows "finite {d. d dvd m}"
proof-
from assms have "{d. d dvd m} \<subseteq> {d. d \<le> m}"
by (auto dest: dvd_imp_le)
then show ?thesis
using finite_Collect_le_nat by (rule finite_subset)
qed
lemma finite_divisors_int [simp]:
fixes i :: int
assumes "i \<noteq> 0"
shows "finite {d. d dvd i}"
proof -
have "{d. \<bar>d\<bar> \<le> \<bar>i\<bar>} = {- \<bar>i\<bar>..\<bar>i\<bar>}"
by (auto simp: abs_if)
then have "finite {d. \<bar>d\<bar> \<le> \<bar>i\<bar>}"
by simp
from finite_subset [OF _ this] show ?thesis
using assms by (simp add: dvd_imp_le_int subset_iff)
qed
lemma Max_divisors_self_nat [simp]: "n \<noteq> 0 \<Longrightarrow> Max {d::nat. d dvd n} = n"
by (fastforce intro: antisym Max_le_iff[THEN iffD2] simp: dvd_imp_le)
lemma Max_divisors_self_int [simp]:
assumes "n \<noteq> 0" shows "Max {d::int. d dvd n} = \<bar>n\<bar>"
proof (rule antisym)
show "Max {d. d dvd n} \<le> \<bar>n\<bar>"
using assms by (auto intro: abs_le_D1 dvd_imp_le_int intro!: Max_le_iff [THEN iffD2])
qed (simp add: assms)
lemma gcd_is_Max_divisors_nat:
fixes m n :: nat
assumes "n > 0" shows "gcd m n = Max {d. d dvd m \<and> d dvd n}"
proof (rule Max_eqI[THEN sym], simp_all)
show "finite {d. d dvd m \<and> d dvd n}"
by (simp add: \<open>n > 0\<close>)
show "\<And>y. y dvd m \<and> y dvd n \<Longrightarrow> y \<le> gcd m n"
by (simp add: \<open>n > 0\<close> dvd_imp_le)
qed
lemma gcd_is_Max_divisors_int:
fixes m n :: int
assumes "n \<noteq> 0" shows "gcd m n = Max {d. d dvd m \<and> d dvd n}"
proof (rule Max_eqI[THEN sym], simp_all)
show "finite {d. d dvd m \<and> d dvd n}"
by (simp add: \<open>n \<noteq> 0\<close>)
show "\<And>y. y dvd m \<and> y dvd n \<Longrightarrow> y \<le> gcd m n"
by (simp add: \<open>n \<noteq> 0\<close> zdvd_imp_le)
qed
lemma gcd_code_int [code]: "gcd k l = \<bar>if l = 0 then k else gcd l (\<bar>k\<bar> mod \<bar>l\<bar>)\<bar>"
for k l :: int
using gcd_red_int [of "\<bar>k\<bar>" "\<bar>l\<bar>"] by simp
lemma coprime_Suc_left_nat [simp]:
"coprime (Suc n) n"
using coprime_add_one_left [of n] by simp
lemma coprime_Suc_right_nat [simp]:
"coprime n (Suc n)"
using coprime_Suc_left_nat [of n] by (simp add: ac_simps)
lemma coprime_diff_one_left_nat [simp]:
"coprime (n - 1) n" if "n > 0" for n :: nat
using that coprime_Suc_right_nat [of "n - 1"] by simp
lemma coprime_diff_one_right_nat [simp]:
"coprime n (n - 1)" if "n > 0" for n :: nat
using that coprime_diff_one_left_nat [of n] by (simp add: ac_simps)
lemma coprime_crossproduct_nat:
fixes a b c d :: nat
assumes "coprime a d" and "coprime b c"
shows "a * c = b * d \<longleftrightarrow> a = b \<and> c = d"
using assms coprime_crossproduct [of a d b c] by simp
lemma coprime_crossproduct_int:
fixes a b c d :: int
assumes "coprime a d" and "coprime b c"
shows "\<bar>a\<bar> * \<bar>c\<bar> = \<bar>b\<bar> * \<bar>d\<bar> \<longleftrightarrow> \<bar>a\<bar> = \<bar>b\<bar> \<and> \<bar>c\<bar> = \<bar>d\<bar>"
using assms coprime_crossproduct [of a d b c] by simp
subsection \<open>Bezout's theorem\<close>
text \<open>
Function \<open>bezw\<close> returns a pair of witnesses to Bezout's theorem --
see the theorems that follow the definition.
\<close>
fun bezw :: "nat \<Rightarrow> nat \<Rightarrow> int * int"
where "bezw x y =
(if y = 0 then (1, 0)
else
(snd (bezw y (x mod y)),
fst (bezw y (x mod y)) - snd (bezw y (x mod y)) * int(x div y)))"
lemma bezw_0 [simp]: "bezw x 0 = (1, 0)"
by simp
lemma bezw_non_0:
"y > 0 \<Longrightarrow> bezw x y =
(snd (bezw y (x mod y)), fst (bezw y (x mod y)) - snd (bezw y (x mod y)) * int(x div y))"
by simp
declare bezw.simps [simp del]
lemma bezw_aux: "int (gcd x y) = fst (bezw x y) * int x + snd (bezw x y) * int y"
proof (induct x y rule: gcd_nat_induct)
case (step m n)
then have "fst (bezw m n) * int m + snd (bezw m n) * int n - int (gcd m n)
= int m * snd (bezw n (m mod n)) -
(int (m mod n) * snd (bezw n (m mod n)) + int n * (int (m div n) * snd (bezw n (m mod n))))"
by (simp add: bezw_non_0 gcd_non_0_nat field_simps)
also have "\<dots> = int m * snd (bezw n (m mod n)) - (int (m mod n) + int (n * (m div n))) * snd (bezw n (m mod n))"
by (simp add: distrib_right)
also have "\<dots> = 0"
by (metis cancel_comm_monoid_add_class.diff_cancel mod_mult_div_eq of_nat_add)
finally show ?case
by simp
qed auto
lemma bezout_int: "\<exists>u v. u * x + v * y = gcd x y"
for x y :: int
proof -
have aux: "x \<ge> 0 \<Longrightarrow> y \<ge> 0 \<Longrightarrow> \<exists>u v. u * x + v * y = gcd x y" for x y :: int
apply (rule_tac x = "fst (bezw (nat x) (nat y))" in exI)
apply (rule_tac x = "snd (bezw (nat x) (nat y))" in exI)
by (simp add: bezw_aux gcd_int_def)
consider "x \<ge> 0" "y \<ge> 0" | "x \<ge> 0" "y \<le> 0" | "x \<le> 0" "y \<ge> 0" | "x \<le> 0" "y \<le> 0"
using linear by blast
then show ?thesis
proof cases
case 1
then show ?thesis by (rule aux)
next
case 2
then show ?thesis
using aux [of x "-y"]
by (metis gcd_neg2_int mult.commute mult_minus_right neg_0_le_iff_le)
next
case 3
then show ?thesis
using aux [of "-x" y]
by (metis gcd.commute gcd_neg2_int mult.commute mult_minus_right neg_0_le_iff_le)
next
case 4
then show ?thesis
using aux [of "-x" "-y"]
by (metis diff_0 diff_ge_0_iff_ge gcd_neg1_int gcd_neg2_int mult.commute mult_minus_right)
qed
qed
text \<open>Versions of Bezout for \<open>nat\<close>, by Amine Chaieb.\<close>
lemma Euclid_induct [case_names swap zero add]:
fixes P :: "nat \<Rightarrow> nat \<Rightarrow> bool"
assumes c: "\<And>a b. P a b \<longleftrightarrow> P b a"
and z: "\<And>a. P a 0"
and add: "\<And>a b. P a b \<longrightarrow> P a (a + b)"
shows "P a b"
proof (induct "a + b" arbitrary: a b rule: less_induct)
case less
consider (eq) "a = b" | (lt) "a < b" "a + b - a < a + b" | "b = 0" | "b + a - b < a + b"
by arith
show ?case
proof (cases a b rule: linorder_cases)
case equal
with add [rule_format, OF z [rule_format, of a]] show ?thesis by simp
next
case lt: less
then consider "a = 0" | "a + b - a < a + b" by arith
then show ?thesis
proof cases
case 1
with z c show ?thesis by blast
next
case 2
also have *: "a + b - a = a + (b - a)" using lt by arith
finally have "a + (b - a) < a + b" .
then have "P a (a + (b - a))" by (rule add [rule_format, OF less])
then show ?thesis by (simp add: *[symmetric])
qed
next
case gt: greater
then consider "b = 0" | "b + a - b < a + b" by arith
then show ?thesis
proof cases
case 1
with z c show ?thesis by blast
next
case 2
also have *: "b + a - b = b + (a - b)" using gt by arith
finally have "b + (a - b) < a + b" .
then have "P b (b + (a - b))" by (rule add [rule_format, OF less])
then have "P b a" by (simp add: *[symmetric])
with c show ?thesis by blast
qed
qed
qed
lemma bezout_lemma_nat:
fixes d::nat
shows "\<lbrakk>d dvd a; d dvd b; a * x = b * y + d \<or> b * x = a * y + d\<rbrakk>
\<Longrightarrow> \<exists>x y. d dvd a \<and> d dvd a + b \<and> (a * x = (a + b) * y + d \<or> (a + b) * x = a * y + d)"
apply auto
apply (metis add_mult_distrib2 left_add_mult_distrib)
apply (rule_tac x=x in exI)
by (metis add_mult_distrib2 mult.commute add.assoc)
lemma bezout_add_nat:
"\<exists>(d::nat) x y. d dvd a \<and> d dvd b \<and> (a * x = b * y + d \<or> b * x = a * y + d)"
proof (induct a b rule: Euclid_induct)
case (swap a b)
then show ?case
by blast
next
case (zero a)
then show ?case
by fastforce
next
case (add a b)
then show ?case
by (meson bezout_lemma_nat)
qed
lemma bezout1_nat: "\<exists>(d::nat) x y. d dvd a \<and> d dvd b \<and> (a * x - b * y = d \<or> b * x - a * y = d)"
using bezout_add_nat[of a b] by (metis add_diff_cancel_left')
lemma bezout_add_strong_nat:
fixes a b :: nat
assumes a: "a \<noteq> 0"
shows "\<exists>d x y. d dvd a \<and> d dvd b \<and> a * x = b * y + d"
proof -
consider d x y where "d dvd a" "d dvd b" "a * x = b * y + d"
| d x y where "d dvd a" "d dvd b" "b * x = a * y + d"
using bezout_add_nat [of a b] by blast
then show ?thesis
proof cases
case 1
then show ?thesis by blast
next
case H: 2
show ?thesis
proof (cases "b = 0")
case True
with H show ?thesis by simp
next
case False
then have bp: "b > 0" by simp
with dvd_imp_le [OF H(2)] consider "d = b" | "d < b"
by atomize_elim auto
then show ?thesis
proof cases
case 1
with a H show ?thesis
by (metis Suc_pred add.commute mult.commute mult_Suc_right neq0_conv)
next
case 2
show ?thesis
proof (cases "x = 0")
case True
with a H show ?thesis by simp
next
case x0: False
then have xp: "x > 0" by simp
from \<open>d < b\<close> have "d \<le> b - 1" by simp
then have "d * b \<le> b * (b - 1)" by simp
with xp mult_mono[of "1" "x" "d * b" "b * (b - 1)"]
have dble: "d * b \<le> x * b * (b - 1)" using bp by simp
from H(3) have "d + (b - 1) * (b * x) = d + (b - 1) * (a * y + d)"
by simp
then have "d + (b - 1) * a * y + (b - 1) * d = d + (b - 1) * b * x"
by (simp only: mult.assoc distrib_left)
then have "a * ((b - 1) * y) + d * (b - 1 + 1) = d + x * b * (b - 1)"
by algebra
then have "a * ((b - 1) * y) = d + x * b * (b - 1) - d * b"
using bp by simp
then have "a * ((b - 1) * y) = d + (x * b * (b - 1) - d * b)"
by (simp only: diff_add_assoc[OF dble, of d, symmetric])
then have "a * ((b - 1) * y) = b * (x * (b - 1) - d) + d"
by (simp only: diff_mult_distrib2 ac_simps)
with H(1,2) show ?thesis
by blast
qed
qed
qed
qed
qed
lemma bezout_nat:
fixes a :: nat
assumes a: "a \<noteq> 0"
shows "\<exists>x y. a * x = b * y + gcd a b"
proof -
obtain d x y where d: "d dvd a" "d dvd b" and eq: "a * x = b * y + d"
using bezout_add_strong_nat [OF a, of b] by blast
from d have "d dvd gcd a b"
by simp
then obtain k where k: "gcd a b = d * k"
unfolding dvd_def by blast
from eq have "a * x * k = (b * y + d) * k"
by auto
then have "a * (x * k) = b * (y * k) + gcd a b"
by (algebra add: k)
then show ?thesis
by blast
qed
subsection \<open>LCM properties on \<^typ>\<open>nat\<close> and \<^typ>\<open>int\<close>\<close>
lemma lcm_altdef_int [code]: "lcm a b = \<bar>a\<bar> * \<bar>b\<bar> div gcd a b"
for a b :: int
by (simp add: abs_mult lcm_gcd abs_div)
lemma prod_gcd_lcm_nat: "m * n = gcd m n * lcm m n"
for m n :: nat
by (simp add: lcm_gcd)
lemma prod_gcd_lcm_int: "\<bar>m\<bar> * \<bar>n\<bar> = gcd m n * lcm m n"
for m n :: int
by (simp add: lcm_gcd abs_div abs_mult)
lemma lcm_pos_nat: "m > 0 \<Longrightarrow> n > 0 \<Longrightarrow> lcm m n > 0"
for m n :: nat
using lcm_eq_0_iff [of m n] by auto
lemma lcm_pos_int: "m \<noteq> 0 \<Longrightarrow> n \<noteq> 0 \<Longrightarrow> lcm m n > 0"
for m n :: int
by (simp add: less_le lcm_eq_0_iff)
lemma dvd_pos_nat: "n > 0 \<Longrightarrow> m dvd n \<Longrightarrow> m > 0" (* FIXME move *)
for m n :: nat
by auto
lemma lcm_unique_nat:
"a dvd d \<and> b dvd d \<and> (\<forall>e. a dvd e \<and> b dvd e \<longrightarrow> d dvd e) \<longleftrightarrow> d = lcm a b"
for a b d :: nat
by (auto intro: dvd_antisym lcm_least)
lemma lcm_unique_int:
"d \<ge> 0 \<and> a dvd d \<and> b dvd d \<and> (\<forall>e. a dvd e \<and> b dvd e \<longrightarrow> d dvd e) \<longleftrightarrow> d = lcm a b"
for a b d :: int
using lcm_least zdvd_antisym_nonneg by auto
lemma lcm_proj2_if_dvd_nat [simp]: "x dvd y \<Longrightarrow> lcm x y = y"
for x y :: nat
by (simp add: lcm_proj2_if_dvd)
lemma lcm_proj2_if_dvd_int [simp]: "x dvd y \<Longrightarrow> lcm x y = \<bar>y\<bar>"
for x y :: int
by (simp add: lcm_proj2_if_dvd)
lemma lcm_proj1_if_dvd_nat [simp]: "x dvd y \<Longrightarrow> lcm y x = y"
for x y :: nat
by (subst lcm.commute) (erule lcm_proj2_if_dvd_nat)
lemma lcm_proj1_if_dvd_int [simp]: "x dvd y \<Longrightarrow> lcm y x = \<bar>y\<bar>"
for x y :: int
by (subst lcm.commute) (erule lcm_proj2_if_dvd_int)
lemma lcm_proj1_iff_nat [simp]: "lcm m n = m \<longleftrightarrow> n dvd m"
for m n :: nat
by (metis lcm_proj1_if_dvd_nat lcm_unique_nat)
lemma lcm_proj2_iff_nat [simp]: "lcm m n = n \<longleftrightarrow> m dvd n"
for m n :: nat
by (metis lcm_proj2_if_dvd_nat lcm_unique_nat)
lemma lcm_proj1_iff_int [simp]: "lcm m n = \<bar>m\<bar> \<longleftrightarrow> n dvd m"
for m n :: int
by (metis dvd_abs_iff lcm_proj1_if_dvd_int lcm_unique_int)
lemma lcm_proj2_iff_int [simp]: "lcm m n = \<bar>n\<bar> \<longleftrightarrow> m dvd n"
for m n :: int
by (metis dvd_abs_iff lcm_proj2_if_dvd_int lcm_unique_int)
lemma lcm_1_iff_nat [simp]: "lcm m n = Suc 0 \<longleftrightarrow> m = Suc 0 \<and> n = Suc 0"
for m n :: nat
using lcm_eq_1_iff [of m n] by simp
lemma lcm_1_iff_int [simp]: "lcm m n = 1 \<longleftrightarrow> (m = 1 \<or> m = -1) \<and> (n = 1 \<or> n = -1)"
for m n :: int
by auto
subsection \<open>The complete divisibility lattice on \<^typ>\<open>nat\<close> and \<^typ>\<open>int\<close>\<close>
text \<open>
Lifting \<open>gcd\<close> and \<open>lcm\<close> to sets (\<open>Gcd\<close> / \<open>Lcm\<close>).
\<open>Gcd\<close> is defined via \<open>Lcm\<close> to facilitate the proof that we have a complete lattice.
\<close>
instantiation nat :: semiring_Gcd
begin
interpretation semilattice_neutr_set lcm "1::nat"
by standard simp_all
definition "Lcm M = (if finite M then F M else 0)" for M :: "nat set"
lemma Lcm_nat_empty: "Lcm {} = (1::nat)"
by (simp add: Lcm_nat_def del: One_nat_def)
lemma Lcm_nat_insert: "Lcm (insert n M) = lcm n (Lcm M)" for n :: nat
by (cases "finite M") (auto simp: Lcm_nat_def simp del: One_nat_def)
lemma Lcm_nat_infinite: "infinite M \<Longrightarrow> Lcm M = 0" for M :: "nat set"
by (simp add: Lcm_nat_def)
lemma dvd_Lcm_nat [simp]:
fixes M :: "nat set"
assumes "m \<in> M"
shows "m dvd Lcm M"
proof -
from assms have "insert m M = M"
by auto
moreover have "m dvd Lcm (insert m M)"
by (simp add: Lcm_nat_insert)
ultimately show ?thesis
by simp
qed
lemma Lcm_dvd_nat [simp]:
fixes M :: "nat set"
assumes "\<forall>m\<in>M. m dvd n"
shows "Lcm M dvd n"
proof (cases "n > 0")
case False
then show ?thesis by simp
next
case True
then have "finite {d. d dvd n}"
by (rule finite_divisors_nat)
moreover have "M \<subseteq> {d. d dvd n}"
using assms by fast
ultimately have "finite M"
by (rule rev_finite_subset)
then show ?thesis
using assms by (induct M) (simp_all add: Lcm_nat_empty Lcm_nat_insert)
qed
definition "Gcd M = Lcm {d. \<forall>m\<in>M. d dvd m}" for M :: "nat set"
instance
proof
fix N :: "nat set"
fix n :: nat
show "Gcd N dvd n" if "n \<in> N"
using that by (induct N rule: infinite_finite_induct) (auto simp: Gcd_nat_def)
show "n dvd Gcd N" if "\<And>m. m \<in> N \<Longrightarrow> n dvd m"
using that by (induct N rule: infinite_finite_induct) (auto simp: Gcd_nat_def)
show "n dvd Lcm N" if "n \<in> N"
using that by (induct N rule: infinite_finite_induct) auto
show "Lcm N dvd n" if "\<And>m. m \<in> N \<Longrightarrow> m dvd n"
using that by (induct N rule: infinite_finite_induct) auto
show "normalize (Gcd N) = Gcd N" and "normalize (Lcm N) = Lcm N"
by simp_all
qed
end
lemma Gcd_nat_eq_one: "1 \<in> N \<Longrightarrow> Gcd N = 1"
for N :: "nat set"
by (rule Gcd_eq_1_I) auto
instance nat :: semiring_gcd_mult_normalize
by intro_classes (auto simp: unit_factor_nat_def)
text \<open>Alternative characterizations of Gcd:\<close>
lemma Gcd_eq_Max:
fixes M :: "nat set"
assumes "finite (M::nat set)" and "M \<noteq> {}" and "0 \<notin> M"
shows "Gcd M = Max (\<Inter>m\<in>M. {d. d dvd m})"
proof (rule antisym)
from assms obtain m where "m \<in> M" and "m > 0"
by auto
from \<open>m > 0\<close> have "finite {d. d dvd m}"
by (blast intro: finite_divisors_nat)
with \<open>m \<in> M\<close> have fin: "finite (\<Inter>m\<in>M. {d. d dvd m})"
by blast
from fin show "Gcd M \<le> Max (\<Inter>m\<in>M. {d. d dvd m})"
by (auto intro: Max_ge Gcd_dvd)
from fin show "Max (\<Inter>m\<in>M. {d. d dvd m}) \<le> Gcd M"
proof (rule Max.boundedI, simp_all)
show "(\<Inter>m\<in>M. {d. d dvd m}) \<noteq> {}"
by auto
show "\<And>a. \<forall>x\<in>M. a dvd x \<Longrightarrow> a \<le> Gcd M"
by (meson Gcd_dvd Gcd_greatest \<open>0 < m\<close> \<open>m \<in> M\<close> dvd_imp_le dvd_pos_nat)
qed
qed
lemma Gcd_remove0_nat: "finite M \<Longrightarrow> Gcd M = Gcd (M - {0})"
for M :: "nat set"
proof (induct pred: finite)
case (insert x M)
then show ?case
by (simp add: insert_Diff_if)
qed auto
lemma Lcm_in_lcm_closed_set_nat:
fixes M :: "nat set"
assumes "finite M" "M \<noteq> {}" "\<And>m n. \<lbrakk>m \<in> M; n \<in> M\<rbrakk> \<Longrightarrow> lcm m n \<in> M"
shows "Lcm M \<in> M"
using assms
proof (induction M rule: finite_linorder_min_induct)
case (insert x M)
then have "\<And>m n. m \<in> M \<Longrightarrow> n \<in> M \<Longrightarrow> lcm m n \<in> M"
by (metis dvd_lcm1 gr0I insert_iff lcm_pos_nat nat_dvd_not_less)
with insert show ?case
by simp (metis Lcm_nat_empty One_nat_def dvd_1_left dvd_lcm2)
qed auto
lemma Lcm_eq_Max_nat:
fixes M :: "nat set"
assumes M: "finite M" "M \<noteq> {}" "0 \<notin> M" and lcm: "\<And>m n. \<lbrakk>m \<in> M; n \<in> M\<rbrakk> \<Longrightarrow> lcm m n \<in> M"
shows "Lcm M = Max M"
proof (rule antisym)
show "Lcm M \<le> Max M"
by (simp add: Lcm_in_lcm_closed_set_nat \<open>finite M\<close> \<open>M \<noteq> {}\<close> lcm)
show "Max M \<le> Lcm M"
by (meson Lcm_0_iff Max_in M dvd_Lcm dvd_imp_le le_0_eq not_le)
qed
lemma mult_inj_if_coprime_nat:
"inj_on f A \<Longrightarrow> inj_on g B \<Longrightarrow> (\<And>a b. \<lbrakk>a\<in>A; b\<in>B\<rbrakk> \<Longrightarrow> coprime (f a) (g b)) \<Longrightarrow>
inj_on (\<lambda>(a, b). f a * g b) (A \<times> B)"
for f :: "'a \<Rightarrow> nat" and g :: "'b \<Rightarrow> nat"
by (auto simp: inj_on_def coprime_crossproduct_nat simp del: One_nat_def)
subsubsection \<open>Setwise GCD and LCM for integers\<close>
instantiation int :: Gcd
begin
definition Gcd_int :: "int set \<Rightarrow> int"
where "Gcd K = int (GCD k\<in>K. (nat \<circ> abs) k)"
definition Lcm_int :: "int set \<Rightarrow> int"
where "Lcm K = int (LCM k\<in>K. (nat \<circ> abs) k)"
instance ..
end
lemma Gcd_int_eq [simp]:
"(GCD n\<in>N. int n) = int (Gcd N)"
by (simp add: Gcd_int_def image_image)
lemma Gcd_nat_abs_eq [simp]:
"(GCD k\<in>K. nat \<bar>k\<bar>) = nat (Gcd K)"
by (simp add: Gcd_int_def)
lemma abs_Gcd_eq [simp]:
"\<bar>Gcd K\<bar> = Gcd K" for K :: "int set"
by (simp only: Gcd_int_def)
lemma Gcd_int_greater_eq_0 [simp]:
"Gcd K \<ge> 0"
for K :: "int set"
using abs_ge_zero [of "Gcd K"] by simp
lemma Gcd_abs_eq [simp]:
"(GCD k\<in>K. \<bar>k\<bar>) = Gcd K"
for K :: "int set"
by (simp only: Gcd_int_def image_image) simp
lemma Lcm_int_eq [simp]:
"(LCM n\<in>N. int n) = int (Lcm N)"
by (simp add: Lcm_int_def image_image)
lemma Lcm_nat_abs_eq [simp]:
"(LCM k\<in>K. nat \<bar>k\<bar>) = nat (Lcm K)"
by (simp add: Lcm_int_def)
lemma abs_Lcm_eq [simp]:
"\<bar>Lcm K\<bar> = Lcm K" for K :: "int set"
by (simp only: Lcm_int_def)
lemma Lcm_int_greater_eq_0 [simp]:
"Lcm K \<ge> 0"
for K :: "int set"
using abs_ge_zero [of "Lcm K"] by simp
lemma Lcm_abs_eq [simp]:
"(LCM k\<in>K. \<bar>k\<bar>) = Lcm K"
for K :: "int set"
by (simp only: Lcm_int_def image_image) simp
instance int :: semiring_Gcd
proof
fix K :: "int set" and k :: int
show "Gcd K dvd k" and "k dvd Lcm K" if "k \<in> K"
using that Gcd_dvd [of "nat \<bar>k\<bar>" "(nat \<circ> abs) ` K"]
dvd_Lcm [of "nat \<bar>k\<bar>" "(nat \<circ> abs) ` K"]
by (simp_all add: comp_def)
show "k dvd Gcd K" if "\<And>l. l \<in> K \<Longrightarrow> k dvd l"
proof -
have "nat \<bar>k\<bar> dvd (GCD k\<in>K. nat \<bar>k\<bar>)"
by (rule Gcd_greatest) (use that in auto)
then show ?thesis by simp
qed
show "Lcm K dvd k" if "\<And>l. l \<in> K \<Longrightarrow> l dvd k"
proof -
have "(LCM k\<in>K. nat \<bar>k\<bar>) dvd nat \<bar>k\<bar>"
by (rule Lcm_least) (use that in auto)
then show ?thesis by simp
qed
qed (simp_all add: sgn_mult)
instance int :: semiring_gcd_mult_normalize
by intro_classes (auto simp: sgn_mult)
subsection \<open>GCD and LCM on \<^typ>\<open>integer\<close>\<close>
instantiation integer :: gcd
begin
context
includes integer.lifting
begin
lift_definition gcd_integer :: "integer \<Rightarrow> integer \<Rightarrow> integer" is gcd .
lift_definition lcm_integer :: "integer \<Rightarrow> integer \<Rightarrow> integer" is lcm .
end
instance ..
end
lifting_update integer.lifting
lifting_forget integer.lifting
context
includes integer.lifting
begin
lemma gcd_code_integer [code]: "gcd k l = \<bar>if l = (0::integer) then k else gcd l (\<bar>k\<bar> mod \<bar>l\<bar>)\<bar>"
by transfer (fact gcd_code_int)
lemma lcm_code_integer [code]: "lcm a b = \<bar>a\<bar> * \<bar>b\<bar> div gcd a b"
for a b :: integer
by transfer (fact lcm_altdef_int)
end
code_printing
constant "gcd :: integer \<Rightarrow> _" \<rightharpoonup>
(OCaml) "!(fun k l -> if Z.equal k Z.zero then/ Z.abs l else if Z.equal/ l Z.zero then Z.abs k else Z.gcd k l)"
and (Haskell) "Prelude.gcd"
and (Scala) "_.gcd'((_)')"
\<comment> \<open>There is no gcd operation in the SML standard library, so no code setup for SML\<close>
text \<open>Some code equations\<close>
lemmas Gcd_nat_set_eq_fold [code] = Gcd_set_eq_fold [where ?'a = nat]
lemmas Lcm_nat_set_eq_fold [code] = Lcm_set_eq_fold [where ?'a = nat]
lemmas Gcd_int_set_eq_fold [code] = Gcd_set_eq_fold [where ?'a = int]
lemmas Lcm_int_set_eq_fold [code] = Lcm_set_eq_fold [where ?'a = int]
text \<open>Fact aliases.\<close>
lemma lcm_0_iff_nat [simp]: "lcm m n = 0 \<longleftrightarrow> m = 0 \<or> n = 0"
for m n :: nat
by (fact lcm_eq_0_iff)
lemma lcm_0_iff_int [simp]: "lcm m n = 0 \<longleftrightarrow> m = 0 \<or> n = 0"
for m n :: int
by (fact lcm_eq_0_iff)
lemma dvd_lcm_I1_nat [simp]: "k dvd m \<Longrightarrow> k dvd lcm m n"
for k m n :: nat
by (fact dvd_lcmI1)
lemma dvd_lcm_I2_nat [simp]: "k dvd n \<Longrightarrow> k dvd lcm m n"
for k m n :: nat
by (fact dvd_lcmI2)
lemma dvd_lcm_I1_int [simp]: "i dvd m \<Longrightarrow> i dvd lcm m n"
for i m n :: int
by (fact dvd_lcmI1)
lemma dvd_lcm_I2_int [simp]: "i dvd n \<Longrightarrow> i dvd lcm m n"
for i m n :: int
by (fact dvd_lcmI2)
lemmas Gcd_dvd_nat [simp] = Gcd_dvd [where ?'a = nat]
lemmas Gcd_dvd_int [simp] = Gcd_dvd [where ?'a = int]
lemmas Gcd_greatest_nat [simp] = Gcd_greatest [where ?'a = nat]
lemmas Gcd_greatest_int [simp] = Gcd_greatest [where ?'a = int]
lemma dvd_Lcm_int [simp]: "m \<in> M \<Longrightarrow> m dvd Lcm M"
for M :: "int set"
by (fact dvd_Lcm)
lemma gcd_neg_numeral_1_int [simp]: "gcd (- numeral n :: int) x = gcd (numeral n) x"
by (fact gcd_neg1_int)
lemma gcd_neg_numeral_2_int [simp]: "gcd x (- numeral n :: int) = gcd x (numeral n)"
by (fact gcd_neg2_int)
lemma gcd_proj1_if_dvd_nat [simp]: "x dvd y \<Longrightarrow> gcd x y = x"
for x y :: nat
by (fact gcd_nat.absorb1)
lemma gcd_proj2_if_dvd_nat [simp]: "y dvd x \<Longrightarrow> gcd x y = y"
for x y :: nat
by (fact gcd_nat.absorb2)
lemma Gcd_in:
fixes A :: "nat set"
assumes "\<And>a b. a \<in> A \<Longrightarrow> b \<in> A \<Longrightarrow> gcd a b \<in> A"
assumes "A \<noteq> {}"
shows "Gcd A \<in> A"
proof (cases "A = {0}")
case False
with assms obtain x where "x \<in> A" "x > 0"
by auto
thus "Gcd A \<in> A"
proof (induction x rule: less_induct)
case (less x)
show ?case
proof (cases "x = Gcd A")
case False
have "\<exists>y\<in>A. \<not>x dvd y"
using False less.prems by (metis Gcd_dvd Gcd_greatest_nat gcd_nat.asym)
then obtain y where y: "y \<in> A" "\<not>x dvd y"
by blast
have "gcd x y \<in> A"
by (rule assms(1)) (use \<open>x \<in> A\<close> y in auto)
moreover have "gcd x y < x"
using \<open>x > 0\<close> y by (metis gcd_dvd1 gcd_dvd2 nat_dvd_not_less nat_neq_iff)
moreover have "gcd x y > 0"
using \<open>x > 0\<close> by auto
ultimately show ?thesis using less.IH by blast
qed (use less in auto)
qed
qed auto
lemma bezout_gcd_nat':
fixes a b :: nat
shows "\<exists>x y. b * y \<le> a * x \<and> a * x - b * y = gcd a b \<or> a * y \<le> b * x \<and> b * x - a * y = gcd a b"
using bezout_nat[of a b]
by (metis add_diff_cancel_left' diff_zero gcd.commute gcd_0_nat
le_add_same_cancel1 mult.right_neutral zero_le)
lemmas Lcm_eq_0_I_nat [simp] = Lcm_eq_0_I [where ?'a = nat]
lemmas Lcm_0_iff_nat [simp] = Lcm_0_iff [where ?'a = nat]
lemmas Lcm_least_int [simp] = Lcm_least [where ?'a = int]
subsection \<open>Characteristic of a semiring\<close>
definition (in semiring_1) semiring_char :: "'a itself \<Rightarrow> nat"
where "semiring_char _ = Gcd {n. of_nat n = (0 :: 'a)}"
context semiring_1
begin
context
fixes CHAR :: nat
defines "CHAR \<equiv> semiring_char (Pure.type :: 'a itself)"
begin
lemma of_nat_CHAR [simp]: "of_nat CHAR = (0 :: 'a)"
proof -
have "CHAR \<in> {n. of_nat n = (0::'a)}"
unfolding CHAR_def semiring_char_def
proof (rule Gcd_in, clarify)
fix a b :: nat
assume *: "of_nat a = (0 :: 'a)" "of_nat b = (0 :: 'a)"
show "of_nat (gcd a b) = (0 :: 'a)"
proof (cases "a = 0")
case False
with bezout_nat obtain x y where "a * x = b * y + gcd a b"
by blast
hence "of_nat (a * x) = (of_nat (b * y + gcd a b) :: 'a)"
by (rule arg_cong)
thus "of_nat (gcd a b) = (0 :: 'a)"
using * by simp
qed (use * in auto)
next
have "of_nat 0 = (0 :: 'a)"
by simp
thus "{n. of_nat n = (0 :: 'a)} \<noteq> {}"
by blast
qed
thus ?thesis
by simp
qed
lemma of_nat_eq_0_iff_char_dvd: "of_nat n = (0 :: 'a) \<longleftrightarrow> CHAR dvd n"
proof
assume "of_nat n = (0 :: 'a)"
thus "CHAR dvd n"
unfolding CHAR_def semiring_char_def by (intro Gcd_dvd) auto
next
assume "CHAR dvd n"
then obtain m where "n = CHAR * m"
by auto
thus "of_nat n = (0 :: 'a)"
by simp
qed
lemma CHAR_eqI:
assumes "of_nat c = (0 :: 'a)"
assumes "\<And>x. of_nat x = (0 :: 'a) \<Longrightarrow> c dvd x"
shows "CHAR = c"
using assms by (intro dvd_antisym) (auto simp: of_nat_eq_0_iff_char_dvd)
lemma CHAR_eq0_iff: "CHAR = 0 \<longleftrightarrow> (\<forall>n>0. of_nat n \<noteq> (0::'a))"
by (auto simp: of_nat_eq_0_iff_char_dvd)
lemma CHAR_pos_iff: "CHAR > 0 \<longleftrightarrow> (\<exists>n>0. of_nat n = (0::'a))"
using CHAR_eq0_iff neq0_conv by blast
lemma CHAR_eq_posI:
assumes "c > 0" "of_nat c = (0 :: 'a)" "\<And>x. x > 0 \<Longrightarrow> x < c \<Longrightarrow> of_nat x \<noteq> (0 :: 'a)"
shows "CHAR = c"
proof (rule antisym)
from assms have "CHAR > 0"
by (auto simp: CHAR_pos_iff)
from assms(3)[OF this] show "CHAR \<ge> c"
by force
next
have "CHAR dvd c"
using assms by (auto simp: of_nat_eq_0_iff_char_dvd)
thus "CHAR \<le> c"
using \<open>c > 0\<close> by (intro dvd_imp_le) auto
qed
end
end
lemma (in semiring_char_0) CHAR_eq_0 [simp]: "semiring_char (Pure.type :: 'a itself) = 0"
by (simp add: CHAR_eq0_iff)
(* nicer notation *)
syntax "_type_char" :: "type => nat" ("(1CHAR/(1'(_')))")
translations "CHAR('t)" => "CONST semiring_char (CONST Pure.type :: 't itself)"
print_translation \<open>
let
fun char_type_tr' ctxt [Const (\<^const_syntax>\<open>Pure.type\<close>, Type (_, [T]))] =
Syntax.const \<^syntax_const>\<open>_type_char\<close> $ Syntax_Phases.term_of_typ ctxt T
in [(\<^const_syntax>\<open>semiring_char\<close>, char_type_tr')] end
\<close>
end
|
variables P Q S T R : Prop.
lemma exA (H1 : (P ∧ Q) ∧ R)
(H2 : S ∧ T) : Q ∧ S :=
and.intro -- Q ∧ S
(and.elim_right --Q
(and.elim_left H1))
(and.elim_left H2). -- S
lemma exC (H1 : P)
(H2 : P →(P → Q)) : Q :=
show Q,
from (H2 H1 (show P,
from (H1))).
lemma exD : (P ∧ Q) → P :=
assume H : P ∧ Q,
(and.elim_left H).
lemma exE (H : P) : Q → P ∧ Q :=
assume H1 : Q,
and.intro
H -- P
H1. -- Q
|
[STATEMENT]
lemma "(x \<cdot> y)\<^sup>\<star> \<cdot> x = x \<cdot> (y \<cdot> x)\<^sup>\<star>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (x \<cdot> y)\<^sup>\<star> \<cdot> x = x \<cdot> (y \<cdot> x)\<^sup>\<star>
[PROOF STEP]
(*nitpick [expect=genuine]*)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (x \<cdot> y)\<^sup>\<star> \<cdot> x = x \<cdot> (y \<cdot> x)\<^sup>\<star>
[PROOF STEP]
oops |
{-
This second-order equational theory was created from the following second-order syntax description:
syntax QIO
type
T : 0-ary
P : 0-ary
term
new : P.T -> T
measure : P T T -> T
applyX : P P.T -> T
applyI2 : P P.T -> T
applyDuv : P P (P,P).T -> T
applyDu : P P.T -> T
applyDv : P P.T -> T
theory
(A) a:P t u:T |> applyX (a, b.measure(b, t, u)) = measure(a, u, t)
(B) a:P b:P t u:P.T |> measure(a, applyDu(b, b.t[b]), applyDv(b, b.u[b])) = applyDuv(a, b, a b.measure(a, t[b], u[b]))
(D) t u:T |> new(a.measure(a, t, u)) = t
(E) b:P t:(P, P).T |> new(a.applyDuv(a, b, a b. t[a,b])) = applyDu(b, b.new(a.t[a,b]))
-}
module QIO.Equality where
open import SOAS.Common
open import SOAS.Context
open import SOAS.Variable
open import SOAS.Families.Core
open import SOAS.Families.Build
open import SOAS.ContextMaps.Inductive
open import QIO.Signature
open import QIO.Syntax
open import SOAS.Metatheory.SecondOrder.Metasubstitution QIO:Syn
open import SOAS.Metatheory.SecondOrder.Equality QIO:Syn
private
variable
α β γ τ : QIOT
Γ Δ Π : Ctx
infix 1 _▹_⊢_≋ₐ_
-- Axioms of equality
data _▹_⊢_≋ₐ_ : ∀ 𝔐 Γ {α} → (𝔐 ▷ QIO) α Γ → (𝔐 ▷ QIO) α Γ → Set where
A : ⁅ P ⁆ ⁅ T ⁆ ⁅ T ⁆̣ ▹ ∅ ⊢ applyX 𝔞 (measure x₀ 𝔟 𝔠) ≋ₐ measure 𝔞 𝔠 𝔟
B : ⁅ P ⁆ ⁅ P ⁆ ⁅ P ⊩ T ⁆ ⁅ P ⊩ T ⁆̣ ▹ ∅ ⊢ measure 𝔞 (applyDu 𝔟 (𝔠⟨ x₀ ⟩)) (applyDv 𝔟 (𝔡⟨ x₀ ⟩)) ≋ₐ applyDuv 𝔞 𝔟 (measure x₀ (𝔠⟨ x₁ ⟩) (𝔡⟨ x₁ ⟩))
D : ⁅ T ⁆ ⁅ T ⁆̣ ▹ ∅ ⊢ new (measure x₀ 𝔞 𝔟) ≋ₐ 𝔞
E : ⁅ P ⁆ ⁅ P · P ⊩ T ⁆̣ ▹ ∅ ⊢ new (applyDuv x₀ 𝔞 (𝔟⟨ x₀ ◂ x₁ ⟩)) ≋ₐ applyDu 𝔞 (new (𝔟⟨ x₀ ◂ x₁ ⟩))
open EqLogic _▹_⊢_≋ₐ_
open ≋-Reasoning
|
# DM test
# 7 de julio de 2016
setwd("~/Documentos/tesina/datos")
rm(list=ls())
graphics.off()
# Leer los datos
library(xlsx)
df = read.xlsx("compModelos.xlsx", sheetName="res", colIndex = c(1:4), rowIndex = c(1:37))
library(forecast)
horizonte = 10
dm.stat = numeric(length=horizonte)
dm.p = numeric(length=horizonte)
for (i in c(1:horizonte)) {
# H0 = Los dos metodos tienen la misma precision de pronostico
dm1 = dm.test (
e1 = df$ann18,
e2 = df$ann19,
# "less" implica que Ha = metodo 2 tiene menor precision que metodo 1
alternative = "less",
h = i,
power = 2
)
dm.stat[i] = dm1$statistic
dm.p[i] = dm1$p.value
}
data.frame(cbind(dm.stat, dm.p)) |
/*! \file ExtremaRootFinding.h
* \brief header file for finding roots and extrema of a function
\todo not implemented yet
*/
#ifndef MINMAXROOT_H
#define MINMAXROOT_H
#include <cmath>
#include <iostream>
#include <gsl/gsl_math.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include <Precision.h>
#include <Function.h>
#include <Matrix.h>
#include <GMatrix.h>
#include <Interpolate.h>
using namespace std;
namespace Math
{
//// Brent bracket search for extrema
//Double_t Brent();
}
#endif
|
[STATEMENT]
lemma rk_triple_le : "rk {A, B, C} \<le> 3"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. rk {A, B, C} \<le> 3
[PROOF STEP]
by (metis Suc_numeral Un_commute insert_absorb2 insert_is_Un linear matroid_ax_2_alt numeral_2_eq_2
numeral_3_eq_3 numeral_le_one_iff numeral_plus_one rk_couple rk_singleton semiring_norm(70)) |
"""
Acts as a store for build information. Passed around to the important setps
"""
type MarbleDoc
docname::AbstractString # For loggin and tex output
settings::SettingsBundle
raw # The file. The stream. The whatever
tree::Markdown.MD # Parsed markdown tree
content::AbstractString # Rendered markdown tree w/o main template
final::AbstractString # Final document, ready for handoff to another processor
cache::States # Storage of cached files
templates::LazyTemplateLoader # Templateing environment
scratch # Place for individual elements to store and share data while rendering
# log
function MarbleDoc(docname, raw, cache, settings)
templates = LazyTemplateLoader([
settings["paths"]["template"],
mrbldir("templates"),
"$(Pkg.dir("Marble"))/templates"
];
block_start_string=settings["JINJA_block_start_string"],
block_end_string=settings["JINJA_block_end_string"],
variable_start_string=settings["JINJA_variable_start_string"],
variable_end_string=settings["JINJA_variable_end_string"],
comment_start_string=settings["JINJA_comment_start_string"],
comment_end_string=settings["JINJA_comment_end_string"],
keep_trailing_newline=true,
)
return new(
docname,
settings,
raw,
Markdown.MD(),
"",
"",
cache,
templates,
Dict())
end
end
"""
Simplification of MarbleDoc constructor
"""
function Marble.MarbleDoc(contents, path, docname; cache=nothing)
# Configure the build env
settings = get_settings(path)
create_paths(settings)
cache = cache == nothing ? States("$(settings["paths"]["cache"])/hashes.json") : cache
return Marble.MarbleDoc(
docname,
contents,
cache,
settings)
end
############## The Main Build Process ##############
"""
Takes in a MarbleDoc and parses the Markdown in the primary_file setting
"""
function Base.parse(env::MarbleDoc)
if env.settings["debug"]
println("PARSING") # LOGGING
end
env.scratch[:analysis] = get_analysis(env)
env.tree = Markdown.parse(env.raw, flavor=:mrbl)
end
"""
Takes and manipulates the freshly parsed Tree
"""
function process(env::MarbleDoc)
if env.settings["debug"]
println("PROCESSING") # LOGGING
end
# Make any Document tags part of the ENV
for e in env.tree.content
if isa(e, Document)
add!(env.settings, e.data)
end
end
#=
I don't like this implementation. I would prefere something more like
# References
{references}
where the header does not have any magic meaning
=#
ref_ind = 0
addrefs = false
walk(env) do e, c, env
try
if isa(e, Markdown.Header) &&
strip(e.text[1]) == env.settings["references_header"]
ref_ind = c[1]
addrefs = true
end
catch
end
end
# replace header with actual element
if ref_ind != 0
# deleteat!(env.tree.content, ref_ind)
insert!(env.tree.content, ref_ind + 1, Tex("\\printbibliography[heading=none]\n"))
end
# probably side load the processors, e.g. for processor in processors...
# skip
end
"""
Takes a marble and converst the abstract tree object, and renders
each object to it's corrisponding Latex (could be HTML. Who knows)
"""
function render(env::MarbleDoc)
if env.settings["debug"]
println("RENDERING") # LOGGING
end
env.content = jinja(env, env.tree)
end
"""
Takes the finished document and puts it into template
"""
function template(env::MarbleDoc)
if env.settings["debug"]
println("TEMLATING") # LOGGING
end
env.final = JinjaTemplates.render(env.templates, "documents/$(env.settings["template"]).tex";
settings=flatten(env.settings),
content=env.content
)
# Write to file
texfile = "$(env.settings["paths"]["base"])/$(get_basename(env)).tex"
open(texfile, "w") do f
write(f, env.final)
end
# show(env.final)
end
"""
Takes the finished document, and calls a build script (probably lualatex)
"""
function build(env::MarbleDoc)
if env.settings["debug"]
println("BUILDING") # LOGGING
end
print("Building $(env.docname)... ")
basename = get_basename(env)
texfile = "$(env.settings["paths"]["base"])/$(get_basename(env)).tex"
builddir = relpath(env.settings["paths"]["build"])
logf = open(joinpath(env.settings["paths"]["log"], "$(get_basename(env))_build.log"), "w")
write(logf, "\n===== Build at $(now()) =====\n")
if env.settings["topdf"]
try
runindir(builddir) do
run(pipeline(`latexmk -$(env.settings["texcmd"]) -shell-escape -halt-on-error $(env.settings["paths"]["base"])/$(basename).tex`; stdout=logf, stderr=logf))
end
println("DONE")
catch y
if !isa(y, ErrorException)
rethrow(y)
end
print_with_color(:red, "BUILD FAILED: ")
println("See $(abspath(env.settings["paths"]["log"]))/$(basename)_build.log for details.")
return nothing
finally
close(logf)
end
end
end
############## The Supporting Functions ##############
"""
Run the analysis CMD specified in the `analysis` command
"""
function get_analysis(env)
# Execute the analysis script.
if "analysis" in keys(env.settings)
a_file = env.settings["analysis"]
# Use cached settings if analysis.jl is up to date
if changed(env.cache, a_file)
# Get the executable command
exec = map(split(env.settings["analysiscmd"], ' ')) do command
if command == "\$filename"
return a_file
else
return command
end
end
try
out = JSON.parse(readstring(`$exec`))
open(f->JSON.print(f, out),
"$(env.settings["paths"]["cache"])/analysis.json",
"w")
catch y
out = Dict()
warn("Analysis script `$(env.settings["analysis"])` failed to run.")
println(y)
end
pin!(env.cache, a_file)
else
println("Using cached analysis file")
out = JSON.parsefile("$(env.settings["paths"]["cache"])/analysis.json")
end
else
out = Dict()
end
return out
end
"""
Needs to add support for inlines and nested block elements
NEEDS TO MAKE A COPY OF THE TREE, OR ELSE WALKING GETS WIERD
f should accept e, c, env::MarbleEnv
e → The element itself
c → The coordinates for this element (array of indicies)
env → The tree itself
"""
function walk(f::Function, env::MarbleDoc)
for i in 1:length(env.tree.content)
n = length(env.tree.content) + 1 - i
f(env.tree.content[n], (n,), env)
end
end
|
\documentclass{charun}
\title{Docker notes, version 0.7.209}
\author{Remigiusz Suwalski}
\usepackage{xcolor}
\newcommand{\important}[1]{\textbf{\color{blue}#1}}
\newminted{bash}{firstnumber=last}
\renewcommand{\theFancyVerbLine}{\sffamily \textcolor[rgb]{0.5,0.5,1.0}{\oldstylenums{\arabic{FancyVerbLine}}}}
% copied from https://tex.stackexchange.com/questions/132849/how-can-i-change-the-font-size-of-the-number-in-minted-environment
\usepackage[scaled=0.85]{beramono}
% copied from https://tex.stackexchange.com/questions/484273/textbf-in-mintinline
\usepackage{hyperref}
\usepackage{paralist}
\begin{document}
\begin{multicols*}{2}
\maketitle
\raggedright
\input{sections/docker-run}
\input{sections/docker-image}
\input{sections/docker-container}
\input{sections/docker-system}
\input{sections/docker-build}
\input{sections/docker-login}
\section{Aliases}
\input{sections/aliases}
\end{multicols*}
\end{document} |
/**
*
* @file qwrapper_dtrtri.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Julien Langou
* @author Henricus Bouwmeester
* @author Mathieu Faverge
* @date 2010-11-15
* @generated d Tue Jan 7 11:44:56 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_dtrtri(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, PLASMA_enum diag,
int n, int nb,
double *A, int lda,
PLASMA_sequence *sequence, PLASMA_request *request,
int iinfo)
{
QUARK_Insert_Task(
quark, CORE_dtrtri_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(PLASMA_enum), &diag, VALUE,
sizeof(int), &n, VALUE,
sizeof(double)*nb*nb, A, INOUT,
sizeof(int), &lda, VALUE,
sizeof(PLASMA_sequence*), &sequence, VALUE,
sizeof(PLASMA_request*), &request, VALUE,
sizeof(int), &iinfo, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dtrtri_quark = PCORE_dtrtri_quark
#define CORE_dtrtri_quark PCORE_dtrtri_quark
#endif
void CORE_dtrtri_quark(Quark *quark)
{
PLASMA_enum uplo;
PLASMA_enum diag;
int N;
double *A;
int LDA;
PLASMA_sequence *sequence;
PLASMA_request *request;
int iinfo;
int info;
quark_unpack_args_8(quark, uplo, diag, N, A, LDA, sequence, request, iinfo);
info = LAPACKE_dtrtri_work(
LAPACK_COL_MAJOR,
lapack_const(uplo), lapack_const(diag),
N, A, LDA);
if ((sequence->status == PLASMA_SUCCESS) && (info > 0))
plasma_sequence_flush(quark, sequence, request, iinfo + info);
}
|
theory RollingRule imports HOLCF
begin
(* http://afp.sourceforge.net/browser_info/current/AFP/WorkerWrapper/FixedPointTheorems.html *)
lemma rolling_rule_ltr: "fix\<cdot>(g oo f) \<sqsubseteq> g\<cdot>(fix\<cdot>(f oo g))"
proof -
have "g\<cdot>(fix\<cdot>(f oo g)) \<sqsubseteq> g\<cdot>(fix\<cdot>(f oo g))"
by (rule below_refl) -- {* reflexivity *}
hence "g\<cdot>((f oo g)\<cdot>(fix\<cdot>(f oo g))) \<sqsubseteq> g\<cdot>(fix\<cdot>(f oo g))"
using fix_eq[where F="f oo g"] by simp -- {* computation *}
hence "(g oo f)\<cdot>(g\<cdot>(fix\<cdot>(f oo g))) \<sqsubseteq> g\<cdot>(fix\<cdot>(f oo g))"
by simp -- {* re-associate @{term "op oo"} *}
thus "fix\<cdot>(g oo f) \<sqsubseteq> g\<cdot>(fix\<cdot>(f oo g))"
using fix_least_below by blast -- {* induction *}
qed
lemma rolling_rule_rtl: "g\<cdot>(fix\<cdot>(f oo g)) \<sqsubseteq> fix\<cdot>(g oo f)"
proof -
have "fix\<cdot>(f oo g) \<sqsubseteq> f\<cdot>(fix\<cdot>(g oo f))" by (rule rolling_rule_ltr)
hence "g\<cdot>(fix\<cdot>(f oo g)) \<sqsubseteq> g\<cdot>(f\<cdot>(fix\<cdot>(g oo f)))"
by (rule monofun_cfun_arg) -- {* g is monotonic *}
thus "g\<cdot>(fix\<cdot>(f oo g)) \<sqsubseteq> fix\<cdot>(g oo f)"
using fix_eq[where F="g oo f"] by simp -- {* computation *}
qed
lemma rolling_rule: "fix\<cdot>(g oo f) = g\<cdot>(fix\<cdot>(f oo g))"
by (rule below_antisym[OF rolling_rule_ltr rolling_rule_rtl])
lemma rolling_rule2:
assumes "cont F" and "cont G"
shows "fix\<cdot>(\<Lambda> x. G (F x)) = G (fix\<cdot>(\<Lambda> x. F (G x)))"
using cont_compose[OF assms(1), cont2cont] cont_compose[OF assms(2), cont2cont]
using rolling_rule[where g = "\<Lambda> x. G x" and f = "\<Lambda> x. F x"]
by (auto simp add: oo_def)
end
|
```python
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('classic')
%matplotlib inline
```
# Class 5: Managing Data with Pandas
Pandas is a Python library for managing datasets. Documentation and examples are available on the website for Pandas: http://pandas.pydata.org/.
In this Notebook, we'll make use of a dataset containing long-run averages of inflation, money growth, and real GDP. The dataset is available here: https://raw.githubusercontent.com/letsgoexploring/economic-data/master/quantity-theory/csv/quantity_theory_data.csv (Python code to generate the dataset: https://github.com/letsgoexploring/economic-data). Recall that the quantity theory of money implies the following linear relationship between the long-run rate of money growth, the long-run rate of inflation, and the long-run rate of real GDP growth in a country:
\begin{align}
\text{inflation} & = \text{money growth} - \text{real GDP growth},
\end{align}
Generally, we treat real GDP growth and money supply growth as exogenous so this is a theory about the determination of inflation.
### Import Pandas
```python
# Import the Pandas module as pd
import pandas as pd
```
### Import data from a csv file
Pandas has a function called `read_csv()` for reading data from a csv file into a Pandas `DataFrame` object.
```python
# Import quantity theory data into a Pandas DataFrame called 'df' with country names as the index.
# Directly from internet
df = pd.read_csv('https://raw.githubusercontent.com/letsgoexploring/economic-data/master/quantity-theory/csv/quantity_theory_data.csv')
# From current working directory
# df = pd.read_csv('qtyTheoryData.csv')
```
```python
# Print the first 5 rows
print(df.head())
```
country iso code observations inflation money growth \
0 Albania ALB 21 0.05453 0.12879
1 Algeria DZA 51 0.10913 0.16370
2 Angola AGO 20 0.88679 1.08457
3 Antigua and Barbuda ATG 38 0.04052 0.09903
4 Argentina ARG 54 0.74972 0.79170
gdp growth
0 0.04829
1 0.03896
2 0.08592
3 0.03673
4 0.02468
```python
# Print the last 10 rows
print(df.tail(10))
```
country iso code observations inflation money growth \
168 Ukraine UKR 23 0.61867 0.58537
169 United Arab Emirates ARE 40 0.03659 0.14033
170 United States USA 54 0.03442 0.05753
171 Uruguay URY 54 0.37658 0.41383
172 Vanuatu VUT 36 0.03611 0.08343
173 Venezuela, RB VEN 53 0.20726 0.27581
174 West Bank and Gaza PSE 17 0.03864 0.12528
175 Yemen, Rep. YEM 24 0.14770 0.13852
176 Zambia ZMB 27 0.22850 0.24470
177 Zimbabwe ZWE 32 -0.00128 -0.13307
gdp growth
168 -0.01070
169 0.04811
170 0.03140
171 0.02294
172 0.02972
173 0.02793
174 0.03389
175 0.04008
176 0.01208
177 0.00839
```python
# Print the type of variable 'df'
print(type(df))
```
<class 'pandas.core.frame.DataFrame'>
### Properties of `DataFrame` objects
Like entries in a spreadsheet file, elements in a `DataFrame` object have row (or *index*) and column coordinates. Column names are always strings. Index elements can be integers, strings, or dates.
```python
# Print the columns of df
print(df.columns)
```
Index(['country', 'iso code', 'observations', 'inflation', 'money growth',
'gdp growth'],
dtype='object')
```python
# Create a new variable called 'money' equal to the 'money growth' column and print
money = df['money growth']
print(money)
```
0 0.12879
1 0.16370
2 1.08457
3 0.09903
4 0.79170
...
173 0.27581
174 0.12528
175 0.13852
176 0.24470
177 -0.13307
Name: money growth, Length: 178, dtype: float64
```python
# Print the type of the variable money
print(type(money))
```
<class 'pandas.core.series.Series'>
A Pandas `Series` stores one column of data. Like a `DataFrame`, a `Series` object has an index. Note that `money` has the same index as `df`. Instead of having a column, the `Series` has a `name` attribute.
```python
# Print the name of the 'money' variable
print(money.name)
```
money growth
Select multiple columns of a `DataFrame` by puting the desired column names in a set a of square brackets (i.e., in a `list`).
```python
# Print the first 5 rows of just the inflation, money growth, and gdp growth columns
print(df[['inflation','money growth','gdp growth']].head())
```
inflation money growth gdp growth
0 0.05453 0.12879 0.04829
1 0.10913 0.16370 0.03896
2 0.88679 1.08457 0.08592
3 0.04052 0.09903 0.03673
4 0.74972 0.79170 0.02468
As mentioned, the set of row coordinates is the index. Unless specified otherwise, Pandas automatically assigns an integer index starting at 0 to rows of the `DataFrame`.
```python
# Print the index of 'df'
print(df.index)
```
RangeIndex(start=0, stop=178, step=1)
Note that in the index of the `df` is the numbers 0 through 177. We could have specified a different index when we imported the data using `read_csv()`. For example, suppose we want to the country names to be the index of `df`. Since country names are in the first column of the data file, we can pass the argument `index_col=0` to `read_csv()`
```python
# Import quantity theory data into a Pandas DataFrame called 'df' with country names as the index.
df = pd.read_csv('https://raw.githubusercontent.com/letsgoexploring/economic-data/master/quantity-theory/csv/quantity_theory_data.csv',index_col=0)
# Print first 5 rows of df
print(df.head())
```
iso code observations inflation money growth \
country
Albania ALB 21 0.05453 0.12879
Algeria DZA 51 0.10913 0.16370
Angola AGO 20 0.88679 1.08457
Antigua and Barbuda ATG 38 0.04052 0.09903
Argentina ARG 54 0.74972 0.79170
gdp growth
country
Albania 0.04829
Algeria 0.03896
Angola 0.08592
Antigua and Barbuda 0.03673
Argentina 0.02468
Use the `loc` attribute to select rows of the `DataFrame` by index *values*.
```python
# Create a new variable called 'usa_row' equal to the 'United States' row and print
usa_row = df.loc['United States']
print(usa_row)
```
iso code USA
observations 54
inflation 0.03442
money growth 0.05753
gdp growth 0.0314
Name: United States, dtype: object
Use `iloc` attribute to select row based on integer location (starting from 0).
```python
# Create a new variable called 'third_row' equal to the third row in the DataFrame and print
third_row = df.iloc[2]
print(third_row)
```
iso code AGO
observations 20
inflation 0.88679
money growth 1.08457
gdp growth 0.08592
Name: Angola, dtype: object
There are several ways to return a single element of a Pandas `DataFrame`. For example, here are three that we want to return the value of inflation for the United States from the DataFrame `df`:
1. `df.loc['United States','inflation']`
2. `df.loc['United States']['inflation']`
3. `df['inflation']['United States']`
The first method points directly to the element in the `df` while the second and third methods return *copies* of the element. That means that you can modify the value of inflation for the United States by running:
df.loc['United States','inflation'] = new_value
But running either:
df.loc['United States']['inflation'] = new_value
or:
df['inflation']['United States'] = new_value
will return an error.
```python
# Print the inflation rate of the United States (By index and column together)
print('Long-run average inflation in US: ',df.loc['United States','inflation'])
```
Long-run average inflation in US: 0.03442
```python
# Print the inflation rate of the United States (first by index, then by column)
print('Long-run average inflation in US: ',df.loc['United States']['inflation'])
```
Long-run average inflation in US: 0.03442
```python
# Print the inflation rate of the United States (first by column, then by index)
print('Long-run average inflation in US: ',df['inflation']['United States'])
```
Long-run average inflation in US: 0.03442
New columns are easily created as functions of existing columns.
```python
# Create a new column called 'difference' equal to the money growth column minus
# the inflation column and print the modified DataFrame
df['difference'] = df['money growth'] - df['inflation']
print(df['difference'])
```
country
Albania 0.07426
Algeria 0.05457
Angola 0.19778
Antigua and Barbuda 0.05851
Argentina 0.04198
...
Venezuela, RB 0.06855
West Bank and Gaza 0.08664
Yemen, Rep. -0.00918
Zambia 0.01620
Zimbabwe -0.13179
Name: difference, Length: 178, dtype: float64
```python
# Print the average difference between money growth and inflation
print(df.difference.mean())
```
0.06339837078651682
```python
# Remove the following columns from the DataFrame: 'iso code','observations','difference'
df = df.drop(['iso code','observations','difference'],axis=1)
# Print the modified DataFrame
print(df)
```
inflation money growth gdp growth
country
Albania 0.05453 0.12879 0.04829
Algeria 0.10913 0.16370 0.03896
Angola 0.88679 1.08457 0.08592
Antigua and Barbuda 0.04052 0.09903 0.03673
Argentina 0.74972 0.79170 0.02468
... ... ... ...
Venezuela, RB 0.20726 0.27581 0.02793
West Bank and Gaza 0.03864 0.12528 0.03389
Yemen, Rep. 0.14770 0.13852 0.04008
Zambia 0.22850 0.24470 0.01208
Zimbabwe -0.00128 -0.13307 0.00839
[178 rows x 3 columns]
### Methods
A Pandas `DataFrame` has a bunch of useful methods defined for it. `describe()` returns some summary statistics.
```python
# Print the summary statistics for 'df'
print(df.describe())
```
inflation money growth gdp growth
count 178.000000 178.000000 178.000000
mean 0.128568 0.191966 0.037594
std 0.172497 0.170733 0.022616
min -0.001280 -0.133070 -0.025240
25% 0.042493 0.102785 0.024382
50% 0.070050 0.140935 0.037745
75% 0.132060 0.210498 0.048245
max 1.277050 1.224430 0.165480
The `corr()` method returns a `DataFrame` containing the correlation coefficients of the specified `DataFrame`.
```python
# Create a variable called 'correlations' containg the correlation coefficients for columns in 'df'
correlations = df.corr()
# Print the correlation coefficients
print(correlations)
```
inflation money growth gdp growth
inflation 1.000000 0.971200 -0.041515
money growth 0.971200 1.000000 0.088061
gdp growth -0.041515 0.088061 1.000000
```python
# Print the correlation coefficient for inflation and money growth
print('corr of inflation and money growth: ',round(correlations.loc['inflation','money growth'],4))
# Print the correlation coefficient for inflation and real GDP growth
print('corr of inflation and gdp growth: ',round(correlations.loc['inflation','gdp growth'],4))
# Print the correlation coefficient for money growth and real GDP growth
print('corr of money growth and gdp growth:',round(correlations.loc['money growth','gdp growth'],4))
```
corr of inflation and money growth: 0.9712
corr of inflation and gdp growth: -0.0415
corr of money growth and gdp growth: 0.0881
`sort_values()` returns a copy of the original `DataFrame` sorted along the given column. The optional argument `ascending` is set to `True` by default, but can be changed to `False` if you want to print the lowest first.
```python
# Print rows for the countries with the 10 lowest inflation rates
print(df.sort_values('inflation').head(10))
```
inflation money growth gdp growth
country
Zimbabwe -0.00128 -0.13307 0.00839
Djibouti 0.00035 0.07940 0.01683
Germany 0.01120 0.07852 0.01233
Hong Kong SAR, China 0.01452 0.10295 0.03778
Ireland 0.01467 0.13223 0.03552
France 0.01560 0.07038 0.01316
Kosovo 0.01659 0.09355 0.03622
Greece 0.01736 0.01533 -0.00487
Switzerland 0.01754 0.06243 0.01750
Austria 0.01757 0.08010 0.01543
```python
# Print rows for the countries with the 10 highest inflation rates
print(df.sort_values('inflation',ascending=False).head(10))
```
inflation money growth gdp growth
country
Congo, Dem. Rep. 1.27705 1.22443 -0.00239
Brazil 0.88891 0.92023 0.04208
Angola 0.88679 1.08457 0.08592
Argentina 0.74972 0.79170 0.02468
Nicaragua 0.62762 0.67775 0.02522
Belarus 0.62519 0.65668 0.05171
Ukraine 0.61867 0.58537 -0.01070
Peru 0.48310 0.54905 0.03510
Armenia 0.46680 0.48970 0.05726
Azerbaijan 0.45091 0.52949 0.05724
Note that `sort_values` and `sort_index` return *copies* of the original `DataFrame`. If, in the previous example, we had wanted to actually modify `df`, we would have need to explicitly overwrite it:
df = df.sort_index(ascending=False)
```python
# Print first 10 rows with the index sorted in descending alphabetical order
print(df.sort_index(ascending=False).head(10))
```
inflation money growth gdp growth
country
Zimbabwe -0.00128 -0.13307 0.00839
Zambia 0.22850 0.24470 0.01208
Yemen, Rep. 0.14770 0.13852 0.04008
West Bank and Gaza 0.03864 0.12528 0.03389
Venezuela, RB 0.20726 0.27581 0.02793
Vanuatu 0.03611 0.08343 0.02972
Uruguay 0.37658 0.41383 0.02294
United States 0.03442 0.05753 0.03140
United Arab Emirates 0.03659 0.14033 0.04811
Ukraine 0.61867 0.58537 -0.01070
### Quick plotting example
Construct a graph that visually confirms the quantity theory of money by making a scatter plot with average money growth on the horizontal axis and average inflation on the vertical axis. Set the marker size `s` to 50 and opacity (`alpha`) 0.25. Add a 45 degree line, axis labels, and a title. Lower and upper limits for the horizontal and vertical axes should be -0.2 and 1.2.
```python
# Create data for 45 degree line
x45 = [-0.2,1.2]
y45 = [-0.2,1.2]
# Create figure and axis
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
# Plot 45 degree line and create legend in lower right corner
ax.plot(x45,y45,'-r',label = '$45^{\circ}$')
ax.legend(loc='lower right')
# Scatter plot of data inflation against money growth
ax.scatter(df['money growth'],df['inflation'],s=50,alpha = 0.25)
ax.set_xlim([-0.2,1.2])
ax.set_ylim([-0.2,1.2])
ax.set_xlabel('money growth')
ax.set_ylabel('inflation')
ax.set_title('Average inflation against average money growth \nfor '+str(len(df.index))+' countries.')
ax.grid()
```
### Exporting a `DataFrame` to csv
Use the DataFrame method `to_csv()` to export DataFrame to a csv file.
```python
# Export the DataFrame 'df' to a csv file called 'modified_data.csv'.
df.to_csv('modified_data.csv')
```
|
using Plots
using CSV
using Printf
using DataFrames
using LaTeXStrings
using LsqFit # Required for the statistics on the fitting process
using FrictionModels
# Read in a CSV file containing the data to fit.
#
# The file is structured as follows:
# Column 1: Time
# Column 2: Velocity
# Column 3: Normal force
# Column 4: Friction Force
println(pwd())
data = CSV.read("examples//test_data_1.csv", DataFrame)
# Construct an initial estimate for model parameters
init_guess = HyperbolicModel(
0.15,
2.0,
20.0,
1.0,
0.1,
0.1
)
# Fit the model
results = fit_model(
init_guess, # Initial Guess
data[:,1], # Time
data[:,4], # Friction Force
data[:,3], # Normal Force
data[:,2] # Velocity
)
# Solve the model
F = friction.(results.model, data[:,3], data[:,2])
# Plot the data
plt = plot(
data[:,2], F,
xlabel = L"v(t)",
ylabel = L"F(t)",
label = "Fitted Model",
lw = 2,
legend = :bottomright
)
plot!(
plt,
data[:,2], data[:,4],
st = :scatter,
label = "Measured Data"
)
display(plt)
# Print out the coefficients of the fitted model
@printf("Fitted Model Coefficients:\n")
# Print out statistitics related to the fit
sigma = stderror(results.fit)
confidence = confidence_interval(results.fit)
# Print out the results
@printf("friction_coefficient: %f\n\tError: %f\n\tConfidence Interval: (%f, %f)\n",
results.model.friction_coefficient,
sigma[1],
confidence[1][1],
confidence[1][2]
)
@printf("normalization_coefficient: %f\n\tError: %f\n\tConfidence Interval: (%f, %f)\n",
results.model.normalization_coefficient,
sigma[2],
confidence[2][1],
confidence[2][2]
)
@printf("dissipation_coefficient: %f\n\tError: %f\n\tConfidence Interval: (%f, %f)\n",
results.model.dissipation_coefficient,
sigma[3],
confidence[3][1],
confidence[3][2]
)
@printf("hysteresis_coefficient: %f\n\tError: %f\n\tConfidence Interval: (%f, %f)\n",
results.model.hysteresis_coefficient,
sigma[4],
confidence[4][1],
confidence[4][2]
)
@printf(
"stribeck_velocity: %f\n\tError: %f\n\tConfidence Interval: (%f, %f)\n",
results.model.stribeck_velocity,
sigma[5],
confidence[5][1],
confidence[5][2]
)
@printf(
"viscous_damping: %f\n\tError: %f\n\tConfidence Interval: (%f, %f)\n",
results.model.viscous_damping,
sigma[6],
confidence[6][1],
confidence[6][2]
)
|
[STATEMENT]
lemma nonword_has_nonterminal:
"is_sentence a \<Longrightarrow> \<not> (is_word a) \<Longrightarrow> \<exists> k. k < length a \<and> is_nonterminal (a ! k)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_sentence a; \<not> is_word a\<rbrakk> \<Longrightarrow> \<exists>k<length a. is_nonterminal (a ! k)
[PROOF STEP]
apply (auto simp add: is_sentence_def list_all_iff is_word_def)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>x. \<lbrakk>Ball (set a) is_symbol; x \<in> set a; \<not> is_terminal x\<rbrakk> \<Longrightarrow> \<exists>k<length a. is_nonterminal (a ! k)
[PROOF STEP]
by (metis in_set_conv_nth is_symbol_distinct) |
\documentclass[handout]{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{\bl}[1]{{\textcolor{blue}{#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}
\useinnertheme{rectangles}
\useoutertheme{infolines}
\usecolortheme{whale}
\definecolor{mygreen}{cmyk}{0.82,0.11,1,0.25}
\setbeamercolor{structure}{fg=mygreen}
\setbeamercolor{frametitle}{fg=black,bg=mygreen}
\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[]{Chen Greif, Dan Li, Dominik Sch\"{o}tzau, \underline{Michael Wathen}}
\institute[]{\Big{Eindhoven precond}}
\date[]{$17^{\tiny{\mbox{th}}}$ June 2015 \\ Preconditioning 2015 \\ Eindhoven}
\begin{document}
\begin{frame}
\institute[]{The University of British Columbia}
\title{Block Preconditioners for an Incompressible Magnetohydrodynamics Problem}
\titlepage
\author{Michael Wathen}
\author{Michael Wathen}
\title{MHD}
\author{Michael Wathen}
\end{frame}
\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}
\frametitle{Steady-state Navier-Stokes equations}
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}
where $\re{u}$ is the fluids velocity; $\re{p}$ is the fluids pressure; $\re{f}$ is the body force acting on the fluid and $\re{\nu}$ the kinematic viscosity.
\end{frame}
\begin{frame}{Steady-state Navier-Stokes equations}
Corresponding linear system:
$$\re{\mathcal{K}_{\rm NS}=\begin{pmatrix}
A+0 & B^T \\
B & 0
\end{pmatrix}
\begin{pmatrix}
u\\p
\end{pmatrix}=
\begin{pmatrix}
f \\ 0
\end{pmatrix}
}$$
where $\re{A\in\mathbb{R}^{n_u\times n_u}}$ is the discrete Laplacian; $\re{O\in\mathbb{R}^{n_u\times n_u}}$ is the convection operator and $\re{B\in\mathbb{R}^{m_u\times n_u}}$ is a discrete divergence operator with full row rank.
\bl{Note}: due to convection term the linear system is non-symmetric
\vspace{2mm}
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}{Time-Harmonic Maxwell in mixed form}
Maxwell operator in mixed form:
\begin{subequations}\nonumber
\re{\begin{alignat}2
\nabla\times( \nabla\times {b}) -k^2 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}
where $\re{b}$ is the magnetic vector field, $\re{r}$ is the scalar multiplier and $\re{k}$ is the wave number.
\vspace{2mm}
Note: for the MHD system $\re{k = 0}$
\end{frame}
\begin{frame}
Discretised and linearised Incompressible Navier-Stokes system
\begin{equation}
\nonumber
\re{\begin{pmatrix}
M-k^2X & D^T \\
D & 0
\end{pmatrix}
\begin{pmatrix}
b \\
r
\end{pmatrix}
=
\begin{pmatrix}
g \\
0
\end{pmatrix}},
\end{equation}
where $\re{M\in\mathbb{R}^{n_b\times n_b}}$ is the discrete curl-curl operator; $\re{X\in\mathbb{R}^{n_b\times n_b}}$ the discrete mass matrix; $\re{D\in\mathbb{R}^{m_b\times n_b}}$ the discrete divergence operator
\vspace{2mm}
\bl{Note:} $\re{M}$ is semidefinate with nulity $\re{m_b}$.
\vspace{2mm}
A significant amount of literature on time-harmonic Maxwell: notably for us, work of \gr{Hiptmair 1999} and \gr{Hiptmair \& Xu 2007} for solving shifted curl-curl equations in a fully scalable fashion.
\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}
\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)}$$
\vspace{2mm}
\bl{Note:} $\re{{\mathcal{P}_{\rm MH}}}$ remains impractical due to coupling terms. Dual Schur complement approximation for velocity-magnetic unknowns
$$\re{\mathcal{P}_{\rm schurMH} =
\left(
\begin{array}{cccc}
F + N_C & B^T & 0 & 0\\
0 & -{S} & 0 & 0 \\
0 & 0 & M+X & 0\\
0 & 0 & 0 & L
\end{array}
\right)}$$
where $\re{N_C = C^T (M + X)^{-1}C}$
\end{frame}
\begin{frame}{Approximation for $\re{N_C}$}
\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}
% \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} |
(*
* Copyright 2016, NICTA
*
* This software may be distributed and modified according to the terms of
* the GNU General Public License version 2. Note that NO WARRANTY is provided.
* See "LICENSE_GPLv2.txt" for details.
*
* @TAG(NICTA_GPL)
*)
theory Corres_Tac
imports
"Cogent_Corres"
"../cogent/isa/ProofTrace"
"../cogent/isa/CogentHelper"
Value_Relation_Generation
begin
(*
* Fix Cogent/C mismatch caused by unused return values of C blocks.
* Cogent code can bind a value without using it. This commonly appears in code like
*
* -- first, a message from our sponsors
* let debug_output = stuff
* and _ = _debug_print debug_output
* -- now back to our regularly scheduled programming
* ...
*
* where debug_output becomes unused because the call to _debug_print is stripped for verification.
*
* When AutoCorres comes across this code, it figures that debug_output is unused,
* so its generated code for "stuff" appends "gets (\<lambda>_. ())".
* This breaks Corres_Tac's expectation that the C code for "stuff" returns a value that
* corresponds to the Cogent code.
*
* We fix that up by walking the AutoCorres output and removing the extra "gets (\<lambda>_. ())",
* allowing the original return value of "stuff" to be propagated.
* The most annoying bit is that the last statement of a monad block is the most deeply nested.
* So our rules need to iterate through pairs of consecutive statements in the same manner
* as @{term simp_last_bind}. The other annoying bit is that we need to change the return type
* from unit to the corresponding type (e.g. of debug_output).
* We use a stack of schematic variables to remember where to apply the type changes.
*
* This could also be fixed directly in AutoCorres, assuming someone remembers how l2 works...
*)
definition "cogent_C_unused_return__internal X Y \<equiv> X = (do Y; return () od)"
lemma cogent_C_unused_return_step:
"\<And>A A' B B'. A = A' \<Longrightarrow> B = B' \<Longrightarrow> A >>= K_bind B = A' >>= K_bind B'"
"\<And>A A' B B'. A = A' \<Longrightarrow> (\<And>v. B v = B' v) \<Longrightarrow> A >>= B = A' >>= B'"
by meson+
(* This should be the only interesting statement block.
* For Let and LetBang codegen, C always returns true and R is unused,
* so we don't care what the rules do to it. *)
lemma cogent_C_unused_return_L:
"\<lbrakk> L = L';
cogent_C_unused_return__internal (L' :: ('s, unit) nondet_monad) (L'' :: ('s, 'a) nondet_monad);
X = X' \<rbrakk> \<Longrightarrow>
(do (_ :: unit) \<leftarrow> condition C L R; X od)
=
(do (_ :: 'a) \<leftarrow> condition C L'' (do R; return undefined od); X' od)"
apply (simp add: cogent_C_unused_return__internal_def)
(* goal assumptions cause normal monad_eq to loop *)
apply (tactic {* simp_tac (@{context} addsimps (MonadEqThms.get @{context})) 1 *})
apply blast
done
lemma cogent_C_unused_return__internal:
"\<And>A. cogent_C_unused_return__internal (do v \<leftarrow> A; gets (\<lambda>_. ()) od) A"
"\<And>A A' B B'. \<lbrakk> A = A'; (\<And>v. cogent_C_unused_return__internal (B v) (B' v)) \<rbrakk> \<Longrightarrow>
cogent_C_unused_return__internal (A >>= B) (A' >>= B')"
"\<And>A A'. A = A' \<Longrightarrow> cogent_C_unused_return__internal A A'"
by (monad_eq simp: cogent_C_unused_return__internal_def | blast)+
(* Test: *)
schematic_lemma
(* input *)
"(do stuff1;
stuff2;
_ \<leftarrow>
condition C1
(do _ \<leftarrow>
condition C2
(do _ \<leftarrow> gets (\<lambda>_. r1);
gets (\<lambda>_. ()) od) (* <-- *)
bla1;
gets (\<lambda>_. ()) od) (* <-- *)
bla2;
_ \<leftarrow>
condition C3 stuff3 stuff4; (* no change *)
stuff5 od)
= ?A"
(* expected output *)
"?A =
(do stuff1;
stuff2;
_ \<leftarrow>
condition C1
(condition C2
(gets (\<lambda>_. r1))
(do bla1; return undefined od))
(do bla2; return undefined od);
_ \<leftarrow>
condition C3 stuff3 stuff4;
stuff5 od)"
(* do it *)
apply ((rule cogent_C_unused_return_L cogent_C_unused_return_step cogent_C_unused_return__internal refl)+)[1]
(* check *)
by (rule refl)
(* Apply the rewrite to a corres proof state.
* In corres_tac, we apply this tactic blindly and it rewrites all unit-returning blocks
* in the C code. This should be safe because no genuine Cogent code ever returns unit
* (the unit type in Cogent is currently compiled to unit_t in C, instead of void). *)
(* FIXME: maybe make this part of Tidy *)
context update_sem_init begin
lemma cogent_corres_unused_return:
"m = m' \<Longrightarrow>
corres srel c m' \<xi> \<gamma> \<Xi> \<Gamma> \<sigma> s \<Longrightarrow>
corres srel c m \<xi> \<gamma> \<Xi> \<Gamma> \<sigma> s"
by simp
ML {*
fun cogent_C_unused_return_tac ctxt = let
(* import into ctxt's locale *)
val corres_rule = Proof_Context.get_thm ctxt "cogent_corres_unused_return"
in fn n =>
rtac corres_rule n
THEN SOLVES (REPEAT_DETERM
(resolve_tac ctxt @{thms cogent_C_unused_return_L cogent_C_unused_return_step
cogent_C_unused_return__internal refl} n)) end
*}
end
ML {*
(* Create derivative equations that only apply in a given context.
*
* make_contextual_eq_thms "f" ["a = b", "c = d"] ctxt
* = ["f a = f b", "f c = f d"]
*)
fun make_contextual_eq_thms (context : term) (eq_thms : thm list) ctxt : thm list =
let fun dest_eq (Const (@{const_name "Trueprop"}, _) $ eq) = dest_eq eq
| dest_eq (Const (@{const_name "Pure.eq"}, _) $ l $ r) = (l, r)
| dest_eq (Const (@{const_name "HOL.eq"}, _) $ l $ r) = (l, r)
| dest_eq t = raise (TERM ("ContextThms.dest_eq", [t]))
fun make_eq_thm thm0 =
let val ((_, [thm]), _) = Variable.import true [thm0] (Variable.set_body false ctxt);
val (lhs, rhs) = dest_eq (Thm.prop_of thm)
handle TERM _ => raise THM ("make_contextual_eq_thms: not an equation", 0, [thm0])
val prop = @{term Trueprop} $ (@{term "op ="} $ (context $ lhs) $ (context $ rhs))
val prop' = map_types (K dummyT) prop |> Syntax.check_term ctxt
handle ERROR _ => raise TERM ("make_contextual_eq_thms: equality term is invalid", [prop])
fun free_var v = case Syntax.check_term ctxt (Free (v, dummyT)) of
Free (_, TFree _) => true
| _ => false
in Goal.prove ctxt (filter free_var (Term.add_free_names prop' [])) [] prop'
(K (simp_tac (ctxt addsimps [thm]) 1))
handle ERROR msg => raise TERM ("make_contextual_eq_thms proof failed:\n" ^ msg, [prop']) end
in map make_eq_thm eq_thms end
*}
lemma simp_trivial_gets:
"do x \<leftarrow> gets (\<lambda>_. v); B x od = B v"
by simp
(* Limit simp_trivial_gets to the top level *)
local_setup {*
fn ctxt =>
Local_Theory.note
((Binding.name "corres_simp_gets", []),
(make_contextual_eq_thms @{term "\<lambda>m. update_sem_init.corres abs_typing abs_repr srel c m \<xi>' \<gamma> \<Xi>' \<Gamma>' \<sigma> s"} @{thms simp_trivial_gets} ctxt))
ctxt |> snd
*}
lemma simp_condition_bind:
"do retval \<leftarrow> condition b x y; gets (\<lambda>s. retval) od = condition b x y" by simp
local_setup {*
fn ctxt =>
Local_Theory.note
((Binding.name "corres_simp_cond_gets", []),
(make_contextual_eq_thms @{term "\<lambda>m. update_sem_init.corres abs_typing abs_repr srel c m \<xi>' \<gamma> \<Xi>' \<Gamma>' \<sigma> s"} @{thms simp_condition_bind} ctxt))
ctxt |> snd
*}
lemma ucast_up_lesseq[OF refl]:
"upcast = ucast
\<Longrightarrow> is_up (upcast :: ('a :: len) word \<Rightarrow> ('b :: len) word)
\<Longrightarrow> (upcast x \<le> upcast y) = (x \<le> y)"
by (simp add: word_le_nat_alt unat_ucast_upcast)
lemma ucast_up_less[OF refl]:
"upcast = ucast
\<Longrightarrow> is_up (upcast :: ('a :: len) word \<Rightarrow> ('b :: len) word)
\<Longrightarrow> (upcast x < upcast y) = (x < y)"
by (simp add: word_less_nat_alt unat_ucast_upcast)
lemma ucast_up_mod[OF refl]:
"upcast = ucast
\<Longrightarrow> is_up (upcast :: ('c :: len) word \<Rightarrow> ('d :: len) word)
\<Longrightarrow> (upcast x mod upcast y) = upcast (x mod y)"
apply (rule word_unat.Rep_eqD)
apply (simp only: unat_mod unat_ucast_upcast)
done
lemma ucast_up_div[OF refl]:
"upcast = ucast
\<Longrightarrow> is_up (upcast :: ('c :: len) word \<Rightarrow> ('d :: len) word)
\<Longrightarrow> (upcast x div upcast y) = upcast (x div y)"
apply (rule word_unat.Rep_eqD)
apply (simp only: unat_div unat_ucast_upcast)
done
lemma ucast_up_eq_0[OF refl]:
"upcast = ucast
\<Longrightarrow> is_up (upcast :: ('c :: len) word \<Rightarrow> ('d :: len) word)
\<Longrightarrow> (upcast x = 0) = (x = 0)"
by (metis word_unat.Rep_inject unat_ucast_upcast ucast_0)
lemma ucast_down_bitwise[OF refl]:
"dcast = ucast
\<Longrightarrow> (bitOR (dcast x) (dcast y)) = dcast (bitOR x y)"
"dcast = ucast
\<Longrightarrow> (bitAND (dcast x) (dcast y)) = dcast (bitAND x y)"
"dcast = ucast
\<Longrightarrow> (bitXOR (dcast x) (dcast y)) = dcast (bitXOR x y)"
"dcast = ucast
\<Longrightarrow> is_down (dcast :: ('a :: len) word \<Rightarrow> ('b :: len) word)
\<Longrightarrow> (bitNOT (dcast x)) = dcast (bitNOT x)"
by (auto intro!: word_eqI simp add: word_size nth_ucast word_ops_nth_size
is_down_def target_size_def source_size_def)
lemma ucast_down_shiftl[OF refl]:
"dcast = ucast
\<Longrightarrow> is_down (dcast :: ('a :: len) word \<Rightarrow> ('b :: len) word)
\<Longrightarrow> dcast (x << n) = dcast x << n"
apply clarsimp
apply (rule word_eqI)
apply (simp add: word_size nth_shiftl nth_ucast)
apply (simp add: is_down_def source_size_def target_size_def word_size)
apply auto
done
lemma ucast_up_down_shiftr[OF refl]:
"dcast = ucast
\<Longrightarrow> is_down (dcast :: ('a :: len) word \<Rightarrow> ('b :: len) word)
\<Longrightarrow> dcast (ucast x >> n) = x >> n"
apply clarsimp
apply (rule word_eqI)
apply (simp add: word_size nth_shiftr nth_ucast)
apply (simp add: is_down_def source_size_def target_size_def word_size)
apply (auto dest: test_bit_size simp: word_size)
done
lemma ucast_up_sless_disgusting[OF refl]:
"(upcast :: ('c :: len) word \<Rightarrow> ('d :: len) word) = ucast
\<Longrightarrow> len_of TYPE('c) < len_of TYPE('d)
\<Longrightarrow> (upcast x <s upcast y) = (x < y)"
apply (clarsimp simp: word_sless_msb_less msb_nth nth_ucast
word_less_nat_alt unat_ucast_upcast
is_up_def source_size_def target_size_def word_size)
apply (auto dest: test_bit_size simp: word_size)
done
lemma ucast_up_sle_disgusting[OF refl]:
"(upcast :: ('c :: len) word \<Rightarrow> ('d :: len) word) = ucast
\<Longrightarrow> len_of TYPE('c) < len_of TYPE('d)
\<Longrightarrow> (upcast x <=s upcast y) = (x \<le> y)"
apply (clarsimp simp: word_sle_msb_le msb_nth nth_ucast
word_le_nat_alt unat_ucast_upcast
is_up_def source_size_def target_size_def word_size)
apply (auto dest: test_bit_size simp: word_size)
done
(* Corres tactic *)
ML {*
(* Used to decode Cogent Var indices *)
fun decode_isa_nat @{term "0 :: nat"} = 0
| decode_isa_nat (@{term Suc} $ n) = decode_isa_nat n + 1
| decode_isa_nat n = HOLogic.dest_number n |> snd
fun TRY_FST tac1 tac2 st = (tac2 ORELSE ((DETERM tac1) THEN tac2)) st
fun TRY_FST_N tac1 tac2 st = (tac2 ORELSE (tac1 THEN tac2)) st
fun TRY_MORE_FST tac1 tac2 st = (tac2 ORELSE ((DETERM tac1) THEN (TRY_MORE_FST tac1 tac2))) st
(* Determine whether a Cogent type contains a TFun anywhere.
* This is used as a crude heuristic for applying corres_let_gets_propagate. *)
fun Cogent_type_contains_TFun (Const (@{const_name TFun}, _)) = true
| Cogent_type_contains_TFun (Abs (_, _, t)) = Cogent_type_contains_TFun t
| Cogent_type_contains_TFun (f $ x) = Cogent_type_contains_TFun f orelse Cogent_type_contains_TFun x
| Cogent_type_contains_TFun _ = false
(* Matches within a typing judgement. *)
fun Cogent_typing_returns_TFun (@{term Trueprop} $
(Const (@{const_name typing}, _) $ tenv $ kind $ env $ expr $ typ)) =
Cogent_type_contains_TFun typ
| Cogent_typing_returns_TFun t = raise TERM ("Cogent_typing_returns_TFun: not a typing rule", [t])
(* Number of expected nondet_monad statements for each Cogent atom in a Let. *)
fun atom_stmts @{const_name Var} = SOME 1
| atom_stmts @{const_name Prim} = NONE
| atom_stmts @{const_name App} = SOME 2
| atom_stmts @{const_name Con} = SOME 1
| atom_stmts @{const_name Promote} = SOME 1
| atom_stmts @{const_name Struct} = SOME 1
| atom_stmts @{const_name Unit} = SOME 1
| atom_stmts @{const_name Lit} = SOME 1
| atom_stmts @{const_name Cast} = SOME 1
| atom_stmts @{const_name Tuple} = SOME 1
| atom_stmts @{const_name Esac} = SOME 1
| atom_stmts @{const_name Fun} = SOME 1
| atom_stmts @{const_name AFun} = SOME 1
(* Let (Put...) is handled outside of corres_let_tac. *)
| atom_stmts _ = NONE
fun sigil_atom_stmts @{const_name Member} Unboxed = SOME 1
| sigil_atom_stmts @{const_name Member} _ = SOME 2
| sigil_atom_stmts _ _ = NONE
fun rec_sigil (Const (@{const_name TRecord}, _) $ _ $ @{term Unboxed}) = SOME Unboxed
| rec_sigil (Const (@{const_name TRecord}, _) $ _ $ @{term ReadOnly}) = SOME ReadOnly
| rec_sigil (Const (@{const_name TRecord}, _) $ _ $ @{term Writable}) = SOME Writable
| rec_sigil _ = NONE
(* Guess the number of statements for this atom.
* "Member (Var 0) 0" is passed as {head = Member, args = [Var 0, 0]}.
* The type env is used to distinguish unboxed and boxed member accesses. *)
fun atom_stmts' (head : string) (args : term list) (env : term) =
case atom_stmts head of SOME n => SOME n | NONE => (case (head, args)
of (@{const_name Member}, Const (@{const_name Var}, _) $ n :: _) => let
val ty = case nth (HOLogic.dest_list env) (decode_isa_nat n) of
(Const (@{const_name Some}, _) $ ty) => ty | t => raise TERM ("atom_stmts': Gamma none", [t])
val sg = case rec_sigil ty of SOME s => s | _ => raise TERM ("atom_stmts': no sig", [ty])
in sigil_atom_stmts head sg end
| (@{const_name Prim}, primop :: _) => let
val is_guarded = case head_of primop of @{const "LShift"} => true
| @{const "RShift"} => true | @{const "Divide"} => true
| @{const "Mod"} => true | _ => false
in if is_guarded then SOME 2 else SOME 1 end
| _ => NONE)
(* Inspect a "corres ..." subgoal. *)
fun dest_corres_prop prop =
case prop of
@{term Trueprop} $ (Const (@{const_name "update_sem_init.corres"}, _) $
_ $ _ $ (* locale parameters *)
srel $ cogent $ m $ xi $ gam $ Xi $ Gam $ si $ s) =>
SOME (srel, cogent, m, xi, gam, Xi, Gam, si, s)
| _ => NONE
fun dest_corres_goal goal_num st =
if Thm.nprems_of st < goal_num then NONE else
Logic.concl_of_goal (Thm.prop_of st) goal_num |> dest_corres_prop
(* Guess the C types mentioned in a rule. This can reduce the amount of
* val_rel and type_rels that we need to unfold.
* Ideally, this should be tracked in the lemma buckets. *)
fun scrape_C_types thm = let
fun filter_Const P (Const (c_name, _)) = if P c_name then [c_name] else []
| filter_Const P (f $ x) = filter_Const P f @ filter_Const P x
| filter_Const P (Abs (_, _, t)) = filter_Const P t
| filter_Const _ _ = []
fun c_type_name str = String.tokens (fn x => x = #".") str
|> filter (String.isSuffix "_C") |> take 1
in Thm.prop_of thm
|> filter_Const (c_type_name #> null #> not)
|> map c_type_name |> List.concat
|> distinct (op =)
end
(* Apply a conversion to the n'th arg in the concl of the chosen subgoal. *)
fun nth_arg_conv_tac n ngoal ctxt conv st = if Thm.nprems_of st < ngoal then no_tac st else
let val subgoal = Logic.get_goal (Thm.prop_of st) ngoal
val all_vars = length (strip_all_vars subgoal)
val imps = length (Logic.strip_imp_prems (strip_all_body subgoal))
val goal_concl = Logic.concl_of_goal (Thm.prop_of st) ngoal
in
Conv.gconv_rule
(Utils.nth_arg_conv n conv
|> (if fst (strip_comb goal_concl) = @{term Trueprop} then Conv.arg_conv else I)
|> Conv.concl_conv imps
|> (fn conv => Conv.params_conv all_vars (K conv) ctxt)) ngoal st
|> Seq.succeed
end
handle CTERM _ => no_tac st
(* Remove "val_rel a a'" assumptions if a' does not appear anywhere else in the subgoal.
Special case for appearance within corres propositions - ignore elements of \<gamma>
that are not given types in \<Gamma>. *)
val val_rel_thin_tac = SUBGOAL (fn (goal, n) => let
val hyps = Logic.strip_assums_hyp goal
val concl = Logic.strip_assums_concl goal
fun match_xi_bvars (Const (@{const_name Cons}, _) $ _ $ xs)
(Const (@{const_name Cons}, _) $ Const (@{const_name None}, _) $ ys) = match_xi_bvars xs ys
| match_xi_bvars (Const (@{const_name Cons}, _) $ x $ xs)
(Const (@{const_name Cons}, _) $ y $ ys) = maps spot_bvars [x, y] @ match_xi_bvars xs ys
| match_xi_bvars xs ys = maps spot_bvars [xs, ys]
and spot_bvars t = case (dest_corres_prop t, t) of
(SOME (srel, cogent, m, xi, gam, Xi, Gam, si, s), _)
=> maps spot_bvars [srel, cogent, m, xi, Xi, si, s] @ match_xi_bvars gam Gam
| (NONE, f $ x) => spot_bvars f @ spot_bvars x
| (NONE, Abs (_, _, bd)) => map (fn x => x - 1) (filter (fn x => x > 0) (spot_bvars bd))
| (NONE, Bound n) => [n]
| _ => []
val used_bvars = (maps spot_bvars (concl :: hyps))
|> map (fn x => (x, ())) |> Inttab.make_list
fun keep (@{term Trueprop} $ (Const (@{const_name val_rel}, _) $ _ $ Bound n))
= (Inttab.lookup used_bvars n <> SOME [()])
| keep _ = true
val drops = filter_out (keep o fst) (hyps ~~ (0 upto length hyps - 1))
|> map snd |> rev
fun thin i = (rotate_tac i n THEN etac thin_rl n THEN rotate_tac (~ i) n)
in EVERY (map thin drops) end)
fun corres_tac ctxt
(typing_tree : thm Tree)
(fun_defs : thm list)
(absfun_corres : thm list)
(fun_corres : thm list)
(corres_if: thm)
(corres_esac: thm list)
(val_rel_simps : thm list)
(type_rel_simps : thm list)
(tag_enum_defs : thm list)
(LETBANG_TRUE_def: thm)
(list_to_map_simps: thm list)
(verbose : bool)
: tactic =
let
fun corres_Cogent_head goal_num st =
Option.map (#2 #> strip_comb #> fst #> dest_Const #> fst) (dest_corres_goal goal_num st)
fun get_thm nm = Proof_Context.get_thm ctxt nm;
fun get_thms nm = Proof_Context.get_thms ctxt nm;
(* Basic rules. *)
val corres_let = get_thm "corres_let";
val corres_nested_let = get_thm "corres_nested_let";
val corres_let_propagate = get_thm "corres_let_gets_propagate";
val corres_letbang = get_thm "corres_letbang";
val corres_app_concrete = get_thm "corres_app_concrete";
val corres_var = get_thm "corres_var";
val corres_con = get_thm "corres_con";
val corres_lit = get_thm "corres_lit";
val corres_prim1 = get_thm "corres_prim1";
val corres_prim2 = get_thm "corres_prim2";
val corres_prim2_partial_right = get_thm "corres_prim2_partial_right";
val corres_prim2_partial_left = get_thm "corres_prim2_partial_left";
val eval_prim_simps = @{thms eval_prim_u_def
ucast_down_add ucast_down_mult up_ucast_inj_eq
ucast_down_minus ucast_up_less ucast_up_lesseq
ucast_down_bitwise[symmetric] ucast_down_shiftl unat_ucast_upcast
ucast_up_down_shiftr ucast_id
ucast_up_div ucast_up_mod ucast_up_eq_0 checked_div_def
ucast_up_sle_disgusting ucast_up_sless_disgusting
is_up_def is_down_def source_size_def
target_size_def word_size ucast_down_ucast_id
};
val eval_prim_ineq_guard_simps = @{thms word_less_nat_alt word_le_nat_alt}
val corres_unit = get_thm "corres_unit";
val corres_fun = get_thm "corres_fun";
val corres_afun = get_thm "corres_afun";
val corres_cast = get_thms "corres_cast";
val corres_struct = get_thm "corres_struct";
val corres_promote = get_thm "corres_promote";
val corres_let_put_unboxed = get_thm "corres_let_put_unboxed'";
val corres_no_let_put_unboxed = get_thm "corres_no_let_put_unboxed'";
(* Type-specialised rule buckets. *)
val net_resolve_tac = Tactic.build_net #> resolve_from_net_tac ctxt
val corres_case_rule = Case.get ctxt |> net_resolve_tac;
val corres_member_boxed_rule = MemberReadOnly.get ctxt |> net_resolve_tac;
val corres_take_boxed_rule = TakeBoxed.get ctxt |> net_resolve_tac;
val corres_take_unboxed_rule = TakeUnboxed.get ctxt |> net_resolve_tac;
val corres_put_boxed_rule = PutBoxed.get ctxt |> net_resolve_tac;
val corres_let_put_boxed_rule = LetPutBoxed.get ctxt |> net_resolve_tac;
(* Miscellaneous rules. *)
val bind_assoc_sym = @{thm bind_assoc[symmetric]};
val recguard_true_rule = get_thm "condition_true_pure";
val type_rel_simps = type_rel_simps @ TypeRelSimp.get ctxt;
val val_rel_simps_prim = @{thms val_rel_word}
@ [get_thm "val_rel_bool_t_C_def"]
val val_rel_simps = val_rel_simps @ ValRelSimp.get ctxt;
fun make_thm_index guess thms = let
val nmths = map swap (maps (fn t => map (pair t) (guess t)) thms)
in Symtab.make_list nmths end
fun lookup_thm_index table = List.mapPartial (Symtab.lookup table) #> List.concat #> distinct Thm.eq_thm
val type_rel_index = make_thm_index scrape_C_types type_rel_simps
val val_rel_index = make_thm_index guess_val_rel_type val_rel_simps
(* Basic tactics. *)
fun SOLVES' tac = fn n => SOLVES (tac n);
fun TRY' tac = fn n => TRY (tac n);
val simp = asm_full_simp_tac ctxt;
val subgoal_simp = TRY' (SOLVES' simp);
fun simp_add thms = asm_full_simp_tac (add_simps thms ctxt);
fun subgoal_simp_add thms = TRY' (SOLVES' (simp_add thms));
fun fastforce_add thms = Clasimp.fast_force_tac (add_simps thms ctxt);
fun clarsimp_add thms = Clasimp.clarsimp_tac (add_simps thms ctxt);
fun subst thms = EqSubst.eqsubst_tac ctxt [0] thms;
val rule = rtac;
val rules = resolve_tac ctxt;
(* Common simpsets. *)
val val_rel_simp_ctxt = ctxt addsimps val_rel_simps
val type_rel_simp_ctxt = ctxt addsimps type_rel_simps
fun subgoal_val_rel_simp_add thms = TRY' (val_rel_thin_tac
THEN' SOLVES' (asm_full_simp_tac (val_rel_simp_ctxt addsimps thms)))
fun subgoal_type_rel_simp_add thms = TRY' (SOLVES' (asm_full_simp_tac (type_rel_simp_ctxt addsimps thms)))
fun subgoal_val_rel_clarsimp_add thms = TRY' (val_rel_thin_tac
THEN' SOLVES' (Clasimp.clarsimp_tac (val_rel_simp_ctxt addsimps thms)))
fun real_goal_of (@{term Pure.imp} $ _ $ t) = real_goal_of t
| real_goal_of (@{term Trueprop} $ t) = real_goal_of t
| real_goal_of (Const (@{const_name Pure.all}, _) $ Abs (x, ty, t)) = betapply (real_goal_of t, Free (x, ty))
| real_goal_of t = t
(* Apply an abstract function corres rule.
* These rules may come in all shapes and sizes; try to solve their assumptions by simp. *)
fun apply_absfun absfun_thm st =
if exists_subterm (fn t => is_const @{const_name measure_call} t) (Thm.prop_of st)
then (* resolve AutoCorres' "measure_call" construct *)
st |>
(rule (get_thm "corres_measure_call_subst") 1
THEN
(fn st => (case Logic.concl_of_goal (Thm.prop_of st) 1 |> real_goal_of of
Const (@{const_name "monad_mono"}, _) $ Abs (_ (* measure var *), _, call) =>
case fst (strip_comb call) of
Const (f, _) => rule (get_thm (Long_Name.base_name f ^ "_mono")) 1 st)
handle Match => raise TERM ("Corres_Tac: failed to resolve measure_call",
[Logic.concl_of_goal (Thm.prop_of st) 1]))
THEN
(rule absfun_thm
THEN_ALL_NEW
(SOLVES' (val_rel_thin_tac THEN'
(rule @{thm order_refl} ORELSE'
simp_add (type_rel_simps @ val_rel_simps @ @{thms recguard_dec_def}))))) 1
)
else
st |>
(rule absfun_thm
THEN_ALL_NEW
(SOLVES' (val_rel_thin_tac THEN' simp_add (type_rel_simps @ val_rel_simps @ @{thms recguard_dec_def})))) 1
(* Strip the recursion guard from recursive function bodies.
* We try to simp away the guard condition. *)
fun simp_recguard_tac n st =
case dest_corres_goal n st of
NONE => raise THM ("corres_tac/simp_recguard_tac: expected a corres subgoal here", 0, [st])
| SOME (_, _, c_def, _, _, _, _, _, _) =>
(case strip_comb c_def of
(Const (@{const_name condition}, _), _) =>
(case (if verbose then tracing "Proving: recursion guard\n" else ();
subst [recguard_true_rule] n THEN SOLVES (simp n)) st |> Seq.pull of
SOME (st', _) => Seq.succeed st'
| NONE => raise THM ("corres_tac/simp_recguard_tac: failed to discharge recursion guard\n", 0, [st]))
| _ => all_tac st);
(* Prove corres recursively. *)
fun corres_tac_rec typing_tree depth = let
fun print msg st = ((if verbose then tracing (String.implode (replicate (depth*2) #" ") ^ msg ^ "\n") else ()); Seq.single st);
fun tree_nth nth = List.nth (tree_rest typing_tree, nth);
fun rule_tree nth n st = TRY (TRY_FST (simp n) (rule (tree_hd (tree_nth nth)) n) |> SOLVES) st
handle Subscript => (print "Warning: rule_tree failed" THEN no_tac) st;
fun corres_tac_nth nth st = corres_tac_rec (tree_nth nth) (depth+1) st;
fun tree_nth' tree nth = List.nth (tree_rest tree, nth);
fun rule_tree' tree nth n st = rule (tree_hd (tree_nth' tree nth)) n st
handle Subscript => (print "Warning: rule_tree' failed" THEN no_tac) st;
(* For Let (Fun...) and similar constructs, we need to remember the value of the Fun
* so that we can apply the corres lemma for that function. *)
fun apply_corres_let n st =
(if Cogent_typing_returns_TFun (Thm.prop_of (tree_hd (tree_nth 1))) (* check the type of the bound-expr *)
then (print "Debug: using corres_let_propagate" THEN rule corres_let_propagate n) st
else rule corres_let n st
) handle Subscript => (print "Warning: tree_nth failed in apply_corres_let" THEN no_tac) st
(* Process a program of the form (Let x y...).
* While x is guaranteed to be an atomic expression, atoms may translate
* to more than one statement in the C monad.
* For two-statement atoms, we use bind_assoc to pull out the statement pair
* before continuing.
*)
fun corres_let_tac n st =
(case dest_corres_goal n st of
SOME (_, Const (@{const_name Cogent.Let}, _) $ lhs $ rhs, _, _, _, _, env, _, _) =>
(case strip_comb lhs of
(Const (lhs_head, _), args) =>
(case atom_stmts' lhs_head args env of
SOME 1 => apply_corres_let n
THEN print ("corres_let: " ^ lhs_head)
THEN rule_tree 0 n
THEN rule_tree 1 n
THEN TRY (corres_tac_nth 1)
THEN TRY (corres_tac_nth 2)
| SOME 2 => subst [bind_assoc_sym] n
THEN apply_corres_let n
THEN print ("corres_let: " ^ lhs_head)
THEN rule_tree 0 n
THEN rule_tree 1 n
THEN TRY (corres_tac_nth 1)
THEN TRY (corres_tac_nth 2)
| _ => no_tac)
| _ => no_tac)
| _ => no_tac) st;
(* Check the head of the Cogent program before applying a tactic.
* This is useful when the tactic doesn't fail quickly (eg. for type-specialised rule buckets). *)
fun check_Cogent_head head tac st =
case corres_Cogent_head 1 st of
NONE => tac st (* not sure if we'd expect this to work *)
| SOME head' => if head = head' then tac st else no_tac st;
in
(fn t => case corres_Cogent_head 1 t of SOME h => print ("Proving: " ^ h) t | _ => all_tac t)
THEN
(* Evaluate Cogent environment lookups (ie. list lookups) eagerly *)
((nth_arg_conv_tac 7 (* \<gamma> *) 1 ctxt (Simplifier.rewrite ctxt)
THEN nth_arg_conv_tac 9 (* \<Gamma> *) 1 ctxt (Simplifier.rewrite ctxt))
THEN
(* Prune val_rel assumptions and variables. *)
val_rel_thin_tac 1 THEN prune_params_tac ctxt
THEN
((rule corres_var 1
THEN print "corres_var"
THEN subgoal_simp 1)
ORELSE
(rule corres_unit 1
THEN print "corres_unit"
THEN subgoal_val_rel_simp_add [] 1)
ORELSE
(rule corres_con 1
THEN print "corres_con"
THEN subgoal_val_rel_simp_add [] 1)
ORELSE
(rule corres_lit 1
THEN print "corres_lit"
THEN subgoal_val_rel_simp_add [] 1)
ORELSE
(rule corres_prim1 1
THEN print "corres_prim (unary)"
THEN val_rel_thin_tac 1 THEN fastforce_add (val_rel_simps_prim @ eval_prim_simps) 1)
ORELSE
(rule corres_prim2 1
THEN print "corres_prim (binary)"
THEN val_rel_thin_tac 1 THEN fastforce_add (val_rel_simps_prim @ eval_prim_simps) 1)
ORELSE
(rule corres_prim2_partial_right 1
THEN print "corres_prim (binary, partial, right)"
THEN (val_rel_thin_tac THEN' simp_add (eval_prim_simps @ val_rel_simps)
THEN_ALL_NEW simp_add (eval_prim_simps @ eval_prim_ineq_guard_simps)) 1
THEN subgoal_val_rel_simp_add (eval_prim_simps @ eval_prim_ineq_guard_simps) 1
)
ORELSE
(rule corres_prim2_partial_left 1
THEN print "corres_prim (binary, partial, left)"
THEN (val_rel_thin_tac THEN' simp_add (eval_prim_simps @ val_rel_simps)
THEN_ALL_NEW simp_add (eval_prim_simps @ eval_prim_ineq_guard_simps)) 1
THEN subgoal_val_rel_simp_add (eval_prim_simps @ eval_prim_ineq_guard_simps) 1
)
ORELSE
(rule corres_fun 1
THEN print "corres_fun"
THEN subgoal_val_rel_simp_add [] 1)
ORELSE
(rule corres_afun 1
THEN print "corres_afun"
THEN subgoal_val_rel_simp_add [] 1)
ORELSE
((simp_tac (put_simpset HOL_basic_ss ctxt addsimps list_to_map_simps) 1)
THEN rule corres_struct 1
THEN print "corres_struct"
THEN subgoal_val_rel_simp_add [] 1)
ORELSE
(rules corres_cast 1
THEN print "corres_cast"
THEN rule_tree 0 1
THEN subgoal_simp 1)
ORELSE check_Cogent_head @{const_name App}
(((fn n => rule corres_app_concrete n
THEN print "corres_app_concrete"
THEN simp n THEN simp n
THEN rules fun_corres n)
THEN_ALL_NEW subgoal_simp_add (@{thm recguard_dec_def} :: fun_corres)) 1)
ORELSE check_Cogent_head @{const_name App}
(APPEND_LIST (map apply_absfun absfun_corres)
THEN print "corres_app_abstract")
ORELSE
(rule corres_promote 1
THEN print "corres_promote"
THEN TRY (TRY_FST (simp 1) (rule_tree' (tree_nth 0) 0 1) |> SOLVES)
THEN subgoal_val_rel_clarsimp_add [] 1)
ORELSE
(rules corres_esac 1
THEN print "corres_esac"
THEN subgoal_simp 1
THEN subgoal_simp 1
THEN subgoal_simp 1
THEN subgoal_val_rel_simp_add [] 1
ORELSE check_Cogent_head @{const_name Member}
(corres_member_boxed_rule 1
THEN print "corres_member_boxed"
THEN rule_tree 0 1
THEN subgoal_simp 1
THEN subgoal_simp 1
THEN subgoal_type_rel_simp_add [] 1
THEN subgoal_type_rel_simp_add [] 1
THEN rule_tree 0 1
THEN TRY (TRY_FST (simp 1) (rule_tree' (tree_nth 0) 0 1) |> SOLVES))
ORELSE
(rule (Proof_Context.get_thm ctxt "corres_member_unboxed") 1
THEN subgoal_val_rel_clarsimp_add [] 1)
ORELSE check_Cogent_head @{const_name Take}
(corres_take_unboxed_rule 1
THEN print "corres_take_unboxed"
THEN subgoal_simp 1
THEN rule_tree 0 1
THEN subgoal_val_rel_simp_add [] 1
THEN subgoal_type_rel_simp_add [] 1
THEN subgoal_type_rel_simp_add [] 1
THEN TRY (TRY (simp 1) THEN SOLVES (rule (tree_hd typing_tree) 1))
THEN rule_tree 1 1
THEN rule_tree 3 1
THEN rule_tree 2 1
THEN subgoal_simp 1
THEN TRY (corres_tac_nth 3))
ORELSE check_Cogent_head @{const_name Take}
(corres_take_boxed_rule 1
THEN print "corres_take_boxed"
THEN subgoal_simp 1
THEN rule_tree 0 1
THEN subgoal_val_rel_simp_add [] 1
THEN subgoal_type_rel_simp_add [] 1
THEN subgoal_type_rel_simp_add [] 1
THEN TRY (TRY_FST (simp 1) (SOLVES (rule (tree_hd typing_tree) 1)))
THEN rule_tree 1 1
THEN rule_tree 3 1
THEN rule_tree 2 1
THEN subgoal_simp 1
THEN TRY (corres_tac_nth 3))
ORELSE
(rule corres_if 1
THEN print "corres_if"
THEN rule_tree 0 1
THEN rule_tree 1 1
THEN subgoal_val_rel_simp_add [] 1
THEN TRY (corres_tac_nth 2)
THEN TRY (corres_tac_nth 3))
ORELSE check_Cogent_head @{const_name Let}
(rule corres_let_put_unboxed 1
THEN print "corres_put_unboxed"
THEN subgoal_simp 1
THEN subgoal_simp 1
THEN rule_tree 0 1
THEN rule_tree 1 1
THEN subgoal_val_rel_clarsimp_add [] 1
THEN TRY (corres_tac_nth 2))
ORELSE check_Cogent_head @{const_name Put}
(rule corres_no_let_put_unboxed 1
THEN print "corres_put_unboxed (no let)"
THEN subgoal_simp 1
THEN subgoal_simp 1
THEN TRY (TRY (simp 1) THEN SOLVES (rule (tree_hd typing_tree) 1))
THEN subgoal_val_rel_clarsimp_add [] 1)
ORELSE check_Cogent_head @{const_name Let}
(corres_let_put_boxed_rule 1
THEN print "corres_let_put_boxed"
THEN rule_tree 0 1
THEN subgoal_simp 1
THEN subgoal_type_rel_simp_add [] 1
THEN subgoal_simp 1
THEN subgoal_simp 1
THEN TRY (TRY_FST (simp 1) (SOLVES (rule (tree_hd typing_tree) 1)))
THEN rule_tree 1 1
THEN subgoal_simp 1
THEN TRY (corres_tac_nth 2))
ORELSE check_Cogent_head @{const_name Put}
(corres_put_boxed_rule 1
THEN print "corres_put_boxed"
THEN rule_tree' (tree_nth 0 handle Subscript => error "tree_nth failed") 0 1
THEN subgoal_simp 1
THEN subgoal_type_rel_simp_add [] 1
THEN subgoal_simp 1
THEN subgoal_simp 1
THEN TRY (TRY_FST (simp 1) (SOLVES (rule (tree_hd typing_tree) 1)))
THEN subgoal_simp 1)
ORELSE check_Cogent_head @{const_name Case}
(rtac (get_thm "corres_simp_cond_gets" RS @{thm iffD2}) 1 THEN
(corres_case_rule 1
THEN print "corres_case"
THEN subgoal_simp 1
THEN subgoal_simp 1
THEN rule_tree 0 1
THEN subgoal_simp 1
THEN rule_tree 1 1
THEN rule_tree 2 1
THEN rule_tree 3 1
THEN TRY (corres_tac_nth 2)
THEN TRY (corres_tac_nth 3)))
ORELSE check_Cogent_head @{const_name Let}
(rtac corres_nested_let 1
THEN print "corres_let (nested)"
THEN rule_tree 0 1
THEN rule_tree 1 1
THEN TRY (corres_tac_nth 1)
THEN TRY (corres_tac_nth 2))
ORELSE corres_let_tac 1
ORELSE check_Cogent_head @{const_name LetBang}
((simp_tac (put_simpset HOL_basic_ss ctxt addsimps [LETBANG_TRUE_def]) 1)
THEN
rule corres_letbang 1
THEN print "corres_letbang"
THEN rule_tree 0 1
THEN rule_tree 1 1
THEN rule_tree 3 1
THEN subgoal_simp 1
THEN TRY (corres_tac_nth 1)
THEN TRY (corres_tac_nth 2))
ORELSE check_Cogent_head @{const_name Split}
(rtac (get_thm "corres_split") 1
THEN print "corres_split"
THEN rule_tree 0 1
THEN subgoal_val_rel_simp_add [] 1
THEN subgoal_simp 1
THEN rule_tree 1 1
THEN rule_tree 2 1
THEN subgoal_val_rel_simp_add [] 1
THEN subgoal_val_rel_simp_add [] 1
THEN TRY (corres_tac_nth 1))
)))
end
in
(simp_tac (put_simpset HOL_basic_ss ctxt addsimps fun_defs) 1)
THEN simp_recguard_tac 1
THEN (fn st => (if verbose then tracing "Fixing unused variables\n" else ();
cogent_C_unused_return_tac ctxt 1 st))
THEN corres_tac_rec typing_tree 0
end
*}
ML{*
fun peel_two tree = hd (tree_rest (hd (tree_rest (hd tree))));
*}
(* Analyse the program and generate proofs based on its call tree. *)
ML {*
fun partition _ [] = ([], [])
| partition P (x::xs) = let val (ps, ns) = partition P xs in
if P x then (x::ps, ns) else (ps, x::ns) end
fun max a b = if a < b then b else a
fun maximum [] = error "maximum: empty list"
| maximum [x] = x
| maximum (x::xs) = max x (maximum xs)
fun get_Cogent_funtype ctxt fname = let
val simps = Proof_Context.get_thms ctxt "abbreviated_type_defs"
in
Proof_Context.get_thm ctxt (fname ^ "_type_def")
|> simplify (ctxt addsimps simps)
end
(* check whether the function argument type contains a TFun *)
fun funtype_is_first_order (funtype:term) =
case funtype of (Const (@{const_name Pair}, _) $ _ $
(Const (@{const_name Pair}, _) $ arg $ _)) =>
not (Cogent_type_contains_TFun arg)
| _ => raise TERM ("Expected a Cogent type signature", [funtype])
(* scrape all direct function calls *)
val get_simple_function_calls = let
fun search (Const (@{const_name App}, _) $
(Const (@{const_name Fun}, _) $ Const (callee, _) $ _) $ _) = [Long_Name.base_name callee]
| search (Const (@{const_name App}, _) $
(Const (@{const_name AFun}, _) $ callee $ _) $ _) = [Utils.decode_isa_string callee]
| search (f $ x) = search f @ search x
| search _ = []
in search end
(*
* Infer a call graph. We assume that the program only has:
* - first-order Cogent functions,
* - first-order abstract functions, and
* - second-order abstract functions with first-order Cogent function arguments.
*)
datatype FunType = AbsFun | CogentFun;
(* Warning: CogentCallTree inlines a full subtree at each call site.
* If this doesn't scale, we will need more indirection. *)
datatype 'a CogentCallOrder = FirstOrderCall of 'a CogentCallTree
| SecondOrderCall of ('a CogentCallTree * (term * 'a CogentCallTree) list)
and 'a CogentCallTree = CogentCallTree of ('a * FunType * string * 'a CogentCallOrder list);
fun CogentCallTree_name (CogentCallTree (_, _, name, _)) = name
fun CogentCallTree_funtype (CogentCallTree (_, typ, _, _)) = typ
fun CogentCallTree_data (CogentCallTree (a, _, _, _)) = a
fun CogentCallTree_calls (CogentCallTree (_, _, _, calls)) = calls
(* We need a stack of environments \<xi> to verify with higher-order absfuns later on.
* Each such function call increments \<xi>.
* Get the stack height and the position of each function in the call tree.
* Note that a function may appear in multiple environments. *)
fun calc_call_depth tr = maximum (0 :: map calc_call_order_depth (CogentCallTree_calls tr))
and calc_call_order_depth (FirstOrderCall f) = calc_call_depth f
| calc_call_order_depth (SecondOrderCall (f, args)) =
maximum (map calc_call_depth (f::map snd args)) + (if CogentCallTree_funtype f = AbsFun then 1 else 0)
(*
* FIXME: this only deals with one function (call tree) at a time.
* If there are multiple entry points, we'd want to handle them simultaneously
* to avoid redundant \<xi>'s and subproofs.
*)
fun annotate_depth tr = let
fun annotate' d (CogentCallTree ((), ty, name, calls)) = let
in CogentCallTree (d, ty, name, map (annotate_call' d) calls) end
and annotate_call' d (FirstOrderCall f) = FirstOrderCall (annotate' d f)
| annotate_call' d (SecondOrderCall (f, args)) = let
val d' = if CogentCallTree_funtype f = AbsFun then d-1 else 0
in SecondOrderCall (annotate' d f, map (apsnd (annotate' d')) args) end
in annotate' (calc_call_depth tr) tr end
fun make_call_tree (Cogent_functions, Cogent_abstract_functions) HO_hints ctxt = let
val Cogent_abstract_functions_HO =
filter_out (get_Cogent_funtype ctxt #> Thm.prop_of #> Utils.rhs_of_eq #> funtype_is_first_order)
Cogent_abstract_functions
val FO_call_graph =
Cogent_functions
|> map (fn n => (n, Proof_Context.get_thm ctxt (n ^ "_def") |> Thm.prop_of |> Utils.rhs_of_eq
|> get_simple_function_calls |> distinct (op =)))
|> map (apsnd (filter (fn f => not (exists (fn af => f = af) Cogent_abstract_functions_HO))))
val absfun_decls = map (fn name => (name, CogentCallTree ((), AbsFun, name, []))) Cogent_abstract_functions
fun func_name (Left f) = f
| func_name (Right f) = f
fun add_fun (name, FO_callees) table = let
fun subtree f = case Symtab.lookup table f of
SOME tr => tr
| (* assume that we get Cogent_functions in topological order *)
NONE => error ("make_call_tree: " ^ quote name ^ " calls " ^ quote f ^
" but we don't know anything about it (yet)")
val FO_callees' = FO_callees
|> map (fn f => FirstOrderCall (subtree f))
val HO_callees = Symtab.lookup_list HO_hints name
|> map (fn (f, args) => SecondOrderCall (subtree (func_name f), map (apsnd (subtree o func_name)) args))
in Symtab.update_new (name, CogentCallTree ((), CogentFun, name, FO_callees' @ HO_callees)) table end
in
fold add_fun FO_call_graph (Symtab.make absfun_decls)
end
(* Obtain the absfuns included in each \<xi>_n, up to the call tree depth. *)
fun make_uabsfuns_defs (tr as CogentCallTree (depth, _, _, _)) = let
fun collect_absfuns d (CogentCallTree (d', ty, name, calls)) callees =
(if d = d' andalso ty = AbsFun then [(AbsFun, name, map CogentCallTree_name callees)] else []) @
maps (fn c => case c of
FirstOrderCall t => collect_absfuns d t []
| SecondOrderCall (f, args) => collect_absfuns d f (map snd args) @
maps (fn arg => collect_absfuns d (snd arg) []) args) calls
in map (fn d => collect_absfuns d tr []) (0 upto depth) end
(* Define each of the \<xi>_n. *)
fun define_uabsfuns (defs : string list list) ctxt : ((term * (string * thm)) list * Proof.context) = let
fun define _ [] ctxt = ([], ctxt)
| define n (absfuns::defs') ctxt = let
val name = "\<xi>_" ^ string_of_int n
val typ = @{typ "(funtyp, abstyp, ptrtyp) uabsfuns"}
val rhs = Const (@{const_name undefined}, typ) (* FIXME *)
val (thm, ctxt) = Specification.definition
(NONE, ((Binding.name (name ^ "_def"), []),
@{mk_term "?name \<equiv> ?def" (name, def)} (Free (name, typ), rhs))) ctxt
val (thms, ctxt) = define (n+1) defs' ctxt
in (thm::thms, ctxt) end
in define 0 defs ctxt end
(* Convenience wrapper. *)
fun define_uabsfuns' tr ctxt =
make_uabsfuns_defs tr
|> map (map #2 o filter (fn (funtyp, _, _) => funtyp = AbsFun))
|> (fn defs => define_uabsfuns defs ctxt)
|> snd
fun isAutoCorresFunRec ctxt f =
(Proof_Context.get_thms ctxt (f ^ "'.simps"); true)
handle ERROR _ => false
(* Manufacture fake corres rules for first-order absfuns. *)
fun generate_FO_absfun_corres (xi:term) ctxt (fname:string) = let
val abs_rel = Syntax.read_term ctxt "abs_rel"
val state_rel = Syntax.read_term ctxt "state_rel"
val Xi = Syntax.read_term ctxt "\<Xi> :: string \<Rightarrow> poly_type"
val _ = if isAutoCorresFunRec ctxt fname then
error ("Corres_Tac: expected first-order function call for " ^ quote fname ^ " but it is recursive")
else ()
val cfun = Syntax.read_term ctxt (fname ^ "'")
val prop = @{mk_term "Trueprop (?abs_rel ?Xi ?state_rel ?fname ?xi ?cfun)"
(abs_rel, Xi, state_rel, fname, xi, cfun)}
(abs_rel, Xi, state_rel, Utils.encode_isa_string fname, xi, cfun)
|> strip_type |> Syntax.check_term ctxt
in
Goal.prove ctxt [] [] prop (K (Skip_Proof.cheat_tac ctxt 1)) RS Proof_Context.get_thm ctxt "afun_corres"
end
(* The same, but for (higher-order absfun, callees) pairs. *)
fun generate_HO_absfun_corres (xi:term) ctxt (fname:string) (callees:(term * string) list) min_measure = let
val corres = Syntax.read_term ctxt "corres"
val state_rel = Syntax.read_term ctxt "state_rel"
val Xi = Syntax.read_term ctxt "\<Xi> :: string \<Rightarrow> poly_type"
val cfun = Syntax.read_term ctxt (fname ^ "'")
val prop = if isAutoCorresFunRec ctxt fname
then @{mk_term "\<lbrakk> i < length \<gamma>; val_rel (\<gamma> ! i) v'; \<Gamma> ! i = Some (fst (snd (?Xi ?fname))); m \<ge> ?min_m \<rbrakk> \<Longrightarrow>
?corres ?state_rel (App (AFun ?fname []) (Var i))
(do x \<leftarrow> ?cfun m v'; gets (\<lambda>s. x) od) ?xi \<gamma> ?Xi \<Gamma> \<sigma> s"
(corres, Xi, state_rel, fname, xi, cfun, min_m)}
(corres, Xi, state_rel, Utils.encode_isa_string fname, xi, cfun,
Int.toString min_measure |> Syntax.read_term ctxt)
else @{mk_term "\<lbrakk> i < length \<gamma>; val_rel (\<gamma> ! i) v'; \<Gamma> ! i = Some (fst (snd (?Xi ?fname))) \<rbrakk> \<Longrightarrow>
?corres ?state_rel (App (AFun ?fname []) (Var i))
(do x \<leftarrow> ?cfun v'; gets (\<lambda>s. x) od) ?xi \<gamma> ?Xi \<Gamma> \<sigma> s"
(corres, Xi, state_rel, fname, xi, cfun)}
(corres, Xi, state_rel, Utils.encode_isa_string fname, xi, cfun)
fun callee_assm (getter, callee) = @{mk_term "Trueprop (?getter v' = ?callee_tag)" (getter, callee_tag)}
(getter, Syntax.read_term ctxt ("FUN_ENUM_" ^ callee))
fun give_xi_type (t as Const (nm, T)) = (if nm = fst (dest_Const Xi) then Xi else t)
| give_xi_type t = t
val prop' = map callee_assm callees |> foldr Logic.mk_implies prop
|> strip_type |> map_aterms give_xi_type |> Syntax.check_term ctxt
in
Goal.prove ctxt ["i", "\<gamma>", "\<Gamma>", "v", "v'", "\<sigma>", "s", "m"] [] prop' (K (Skip_Proof.cheat_tac ctxt 1))
end
fun unfold_abbreviatedType_term ctxt (Const (nm, @{typ "Cogent.type"}))
= if String.isPrefix "abbreviatedType" (Long_Name.base_name nm)
then Proof_Context.get_thm ctxt (nm ^ "_def")
|> safe_mk_meta_eq |> Thm.concl_of |> Logic.dest_equals |> snd |> SOME
else NONE
| unfold_abbreviatedType_term _ _ = NONE
(* Generate and prove corres rules for Cogent functions. *)
fun make_FO_fun_corres_prop xi_index ctxt fname min_measure = let
val read = Syntax.read_term ctxt
val Xi = read "\<Xi> :: string \<Rightarrow> poly_type"
fun give_xi_type (t as Const (nm, T)) = (if nm = fst (dest_Const Xi) then Xi else t)
| give_xi_type t = t
val cfun = read (fname ^ "'")
val prop = if isAutoCorresFunRec ctxt fname
then @{mk_term "\<And>a a' \<sigma> s m. val_rel a a' \<Longrightarrow> m \<ge> ?min_m \<Longrightarrow>
?corres ?state_rel ?cogent (?cfun m a') ?\<xi> [a] ?\<Xi> [Some (fst (snd ?cogent_type))] \<sigma> s"
(corres, state_rel, cogent, cfun, \<xi>, \<Xi>, cogent_type, min_m)}
(read "corres", read "state_rel", read fname, cfun,
read ("\<xi>_" ^ Int.toString xi_index), Xi, read (fname ^ "_type"),
Int.toString min_measure |> Syntax.read_term ctxt)
else @{mk_term "\<And>a a' \<sigma> s. val_rel a a' \<Longrightarrow>
?corres ?state_rel ?cogent (?cfun a') ?\<xi> [a] ?\<Xi> [Some (fst (snd ?cogent_type))] \<sigma> s"
(corres, state_rel, cogent, cfun, \<xi>, \<Xi>, cogent_type)}
(read "corres", read "state_rel", read fname, cfun,
read ("\<xi>_" ^ Int.toString xi_index), Xi, read (fname ^ "_type"))
in prop |> strip_type |> map_aterms give_xi_type |> Syntax.check_term ctxt end
(* Unfold types in corres rules. *)
fun unfold_Cogent_simps ctxt =
Proof_Context.get_thms ctxt "fst_conv" @
Proof_Context.get_thms ctxt "snd_conv" @
Proof_Context.get_thms ctxt "abbreviated_type_defs"
fun unfold_Cogent_types ctxt simps fname thm =
Local_Defs.unfold ctxt (Proof_Context.get_thms ctxt (fname ^ "_type_def") @ simps) thm
fun mapAccumL _ [] acc = ([], acc)
| mapAccumL f (x::xs) acc = let val (x', acc') = f x acc
val (xs', acc'') = mapAccumL f xs acc'
in (x'::xs', acc'') end
type obligations = (string * FunType * string list * cterm) Symtab.table
fun corres_tree_obligations trs ctxt : obligations = let
fun descend (CogentCallTree ((xi_index, _), AbsFun, name, [])) tab = let
val thm_name = name ^ "_corres_" ^ string_of_int xi_index in
if Symtab.defined tab thm_name then (thm_name, tab) else let
(* generate a fake corres rule and for interesting reasons throw it away *)
val x = generate_FO_absfun_corres (Syntax.read_term ctxt ("\<xi>_" ^ string_of_int xi_index)) ctxt name
|> forall_intr_vars
in tracing (" adding thm " ^ thm_name);
(thm_name, Symtab.update (thm_name, (name, AbsFun, [], Thm.cprop_of x)) tab) end end
| descend (CogentCallTree ((xi_index, min_measure), CogentFun, name, callees)) tab = let
(* Calls to CogentFuns, which we should prove. *)
val thm_name = name ^ "_corres_" ^ string_of_int xi_index
in if Symtab.defined tab thm_name then (thm_name, tab) else let
val (callee_nms, tab) = mapAccumL (fn c => fn tab => case c of
FirstOrderCall f => descend f tab
| SecondOrderCall (f as CogentCallTree ((fxi_index, fmin_measure), AbsFun, fname, []), args) => let
(* Second-order AbsFun calls are specialised to their callees. *)
val nm = (space_implode "_" (fname::map (CogentCallTree_name o snd) args)
^ "_corres_" ^ string_of_int fxi_index)
in if Symtab.defined tab nm then (nm, tab) else let
val tab = fold (snd oo descend) (map snd args) tab
val f_thm = generate_HO_absfun_corres (Syntax.read_term ctxt ("\<xi>_" ^ string_of_int fxi_index))
ctxt fname (map (apsnd CogentCallTree_name) args) fmin_measure
|> forall_intr_vars
in tracing (" adding thm " ^ nm);
(nm, Symtab.update (nm, (fname, AbsFun, [], Thm.cprop_of f_thm)) tab) end end
| tr' => raise TERM ("descend: callees: tr': " ^ @{make_string} tr', [])
) callees tab
val prop = make_FO_fun_corres_prop xi_index ctxt name min_measure
val _ = tracing (" adding thm " ^ thm_name)
in (thm_name, Symtab.update (thm_name, (name, CogentFun, callee_nms, Thm.cterm_of ctxt prop)) tab) end end
| descend tr' _ = raise TERM ("descend: tr': " ^ @{make_string} tr', [])
val tab = fold (snd oo descend o snd) (Symtab.dest trs) Symtab.empty
in tab end
fun corres_tac_driver corres_tac typing_tree_of ctxt (tab : obligations) thm_name
= case Symtab.lookup tab thm_name of SOME (fname, CogentFun, assums, prop) => let
val lookup_assums = map (Symtab.lookup tab #> the) assums
val (callee_info, callee_abs_info) = lookup_assums
|> partition (fn v => #2 v = CogentFun)
val (callee_names, callee_abs_names) = (callee_info, callee_abs_info) |> apply2 (map #1)
val (callee_thm_props, callee_abs_thm_props) = (callee_info, callee_abs_info) |> apply2 (map #4)
val type_unfold_simps = unfold_Cogent_simps ctxt
val fun_defs = Proof_Context.get_thms ctxt (fname ^ "_def") @
Proof_Context.get_thms ctxt (fname ^ "'_def'") @
Proof_Context.get_thms ctxt (fname ^ "_type_def") @
type_unfold_simps
val _ = @{trace} ("corres_tac_driver: Proving " ^ thm_name,
{ prop = prop, callee_props = callee_thm_props,
callee_abs_props = callee_abs_thm_props })
in Goal.prove ctxt []
(map Thm.term_of (callee_thm_props @ callee_abs_thm_props))
(Thm.term_of prop)
(fn args => let
val callee_thms = take (length callee_thm_props) (#prems args) ~~ callee_names
|> map (fn (assum, name) => unfold_Cogent_types ctxt type_unfold_simps name assum)
val callee_abs_thms = drop (length callee_thm_props) (#prems args) ~~ callee_abs_names
|> map (fn (assum, name) => simp_xi ctxt assum |> unfold_Cogent_types ctxt type_unfold_simps name)
val _ = @{trace} ("Assumptions for " ^ thm_name, callee_thms, callee_abs_thms)
in corres_tac (#context args) (peel_two (typing_tree_of fname))
fun_defs callee_abs_thms callee_thms end)
end
| SOME (_, AbsFun, [], _) => @{thm TrueI}
| v => error ("corres_tac_driver: tab contents: " ^ thm_name ^ ": " ^ @{make_string} v)
fun finalise (tab : obligations) ctxt thm_tab = let
fun to_rsn NONE = Thm.trivial @{cpat "?P :: prop"}
| to_rsn (SOME thm) = thm
fun cleanup thm = thm
|> (ALLGOALS val_rel_thin_tac
THEN prune_params_tac ctxt
THEN distinct_subgoals_tac)
|> Seq.hd
fun inner nm ftab =
case Symtab.lookup ftab nm of SOME thm => (thm, ftab)
| NONE => let
val _ = tracing ("finalise: " ^ nm)
val assum_nms = Symtab.lookup tab nm |> the |> #3
val (concr_assums, abs_assums) = partition (fn n => CogentFun = (Symtab.lookup tab n |> the |> #2)) assum_nms
val assum_nms = concr_assums @ abs_assums
val thm = Symtab.lookup thm_tab nm |> the
val (assums, ftab) = mapAccumL inner assum_nms ftab
val rthm = case thm of NONE => NONE
| SOME t => if Thm.eq_thm (t, @{thm TrueI}) then NONE
else SOME ((map to_rsn assums MRS gen_all (Variable.maxidx_of ctxt) t) |> cleanup)
in (rthm, Symtab.update (nm, rthm) ftab) end
in fold (snd oo inner) (Symtab.keys tab) Symtab.empty end
fun all_corres_goals corres_tac typing_tree_of time_limit ctxt (tab : obligations) =
let
val tl = Time.fromSeconds time_limit
fun driver nm = Timing.timing (try (TimeLimit.timeLimit tl
(corres_tac_driver corres_tac typing_tree_of ctxt tab))) nm
|> (fn (dur, res) => (tracing ("Time for " ^ nm ^ ": " ^ Timing.message dur); res))
|> (fn NONE => (tracing ("Failed: " ^ nm); (nm, NONE))
| SOME thm => (tracing ("Succeeded: " ^ nm); (nm, SOME thm)))
val res = Par_List.map driver (Symtab.keys tab)
val thm_tab = Symtab.make res
in thm_tab end
(* Top-level driver that attempts to prove a CogentCallTree.
* For each function in the tree, it proves a corres theorem and assigns a standard name.
* If a theorem by that name already exists, that is used instead.
*
* The naming scheme is: <fun>_[<funarg1>_<funarg2>_...]_corres_<xi_index>
* Eg. for f called with function arguments g and h: f_g_h_corres_1
* These names can be obtained using callee_corres_thms.
*
* Known issues:
* - Does not handle C recursion guards.
* - Does not handle higher-order CogentFuns.
* - Should be parallelised.
*)
fun corres_tree tr typing_tree_of corres_tac run_proofs skip_initial time_limit ctxt = let
fun cache_proof ctxt thm_name (make_thms : unit -> thm list) =
(Proof_Context.get_thms ctxt thm_name, ctxt)
handle ERROR _ =>
Utils.define_lemmas thm_name (make_thms ()) ctxt
fun mapAccumL _ [] acc = ([], acc)
| mapAccumL f (x::xs) acc = let val (x', acc') = f x acc
val (xs', acc'') = mapAccumL f xs acc'
in (x'::xs', acc'') end
val type_unfold_simps = unfold_Cogent_simps ctxt
val skip_ctr = Unsynchronized.ref skip_initial
val failed_proofs = Unsynchronized.ref []
fun descend (CogentCallTree (xi_index, AbsFun, name, [])) ctxt = let
(* Simple AbsFun calls. Higher-order calls are handled elsewhere. *)
val (thm, ctxt) =
cache_proof ctxt (name ^ "_corres_" ^ string_of_int xi_index) (fn () =>
[generate_FO_absfun_corres (Syntax.read_term ctxt ("\<xi>_" ^ string_of_int xi_index)) ctxt name
|> unfold_Cogent_types ctxt type_unfold_simps name])
in (CogentCallTree ((xi_index, thm), AbsFun, name, []), ctxt) end
| descend (CogentCallTree (xi_index, CogentFun, name, callees)) ctxt = let
(* Calls to CogentFuns, which we should prove. *)
val (callees', ctxt) = mapAccumL (fn c => fn ctxt => case c of
FirstOrderCall f => descend f ctxt |> apfst FirstOrderCall
| SecondOrderCall (f as CogentCallTree (fxi_index, AbsFun, fname, []), args) => let
(* Second-order AbsFun calls are specialised to their callees. *)
val (args', ctxt) = mapAccumL descend (map snd args) ctxt
val (f_thm, ctxt) = cache_proof ctxt
(space_implode "_" (fname::map (CogentCallTree_name o snd) args) ^ "_corres_" ^ string_of_int fxi_index)
(fn () => [generate_HO_absfun_corres (Syntax.read_term ctxt ("\<xi>_" ^ string_of_int fxi_index))
ctxt fname (map (apsnd CogentCallTree_name) args) 42
|> unfold_Cogent_types ctxt type_unfold_simps fname])
in (SecondOrderCall (CogentCallTree ((fxi_index, f_thm), AbsFun, fname, []), map fst args ~~ args'), ctxt) end)
callees ctxt
val thm_name = name ^ "_corres_" ^ string_of_int xi_index
val _ = if !skip_ctr > 0 then @{trace} ("skipping " ^ string_of_int (!skip_ctr) ^ " more") else ()
val run_proofs = run_proofs andalso !skip_ctr <= 0
val _ = (skip_ctr := !skip_ctr-1)
val (thm, ctxt) =
cache_proof ctxt thm_name (fn () => let
(* Warning: actual proofs ahead. *)
val corres = Syntax.read_term ctxt "corres"
val fun_term = Syntax.read_term ctxt name
val fun_type = Syntax.read_term ctxt (name ^ "_type")
val fun_c = Syntax.read_term ctxt (name ^ "'")
val state_rel = Syntax.read_term ctxt "state_rel"
val xi = Syntax.read_term ctxt ("\<xi>_" ^ string_of_int xi_index)
val Xi = Syntax.read_term ctxt "\<Xi> :: string \<Rightarrow> poly_type"
val prop = @{mk_term "\<And>a a' \<sigma> s. val_rel a a' \<Longrightarrow> ?corres ?state_rel ?fun_term (?fun_c a') ?xi [a] ?Xi
[Some (fst (snd ?fun_type))] \<sigma> s"
(corres, state_rel, fun_term, fun_c, xi, Xi, fun_type)}
(corres, state_rel, fun_term, fun_c, xi, Xi, fun_type)
|> strip_type |> Syntax.check_term ctxt
val (callee_thms, callee_abs_thms) = callees'
|> map (fn call => case call of FirstOrderCall f => f
| SecondOrderCall (f, _) => f)
|> partition (fn tr => CogentCallTree_funtype tr = CogentFun)
|> apply2 (map (CogentCallTree_data #> snd))
val (callee_thms, callee_abs_thms) = (List.concat callee_thms, List.concat callee_abs_thms)
val fun_defs = Proof_Context.get_thms ctxt (name ^ "_def") @
Proof_Context.get_thms ctxt (name ^ "'_def'") @
Proof_Context.get_thms ctxt (name ^ "_type_def") @
type_unfold_simps
val _ = @{trace} ("cogent_corres_tree: " ^ (if run_proofs then "Proving " else "Skipping ") ^ thm_name,
{ prop = Thm.cterm_of ctxt prop,
callees = callees
|> map (fn call => case call of FirstOrderCall f => f
| SecondOrderCall (f, _) => f)
|> map CogentCallTree_name |> commas })
fun fallback_thm msg = (warning ("Failed to prove " ^ thm_name ^ "; error: " ^ msg);
failed_proofs := thm_name :: !failed_proofs;
Goal.prove ctxt [] [] prop (K (Skip_Proof.cheat_tac ctxt 1)))
val (time, thms) = (fn f => Timing.timing f ()) (fn () =>
[(TimeLimit.timeLimit (Time.fromSeconds time_limit) (fn () =>
(((((Goal.prove ctxt [] [] prop (fn {context, prems} =>
if not run_proofs then Skip_Proof.cheat_tac ctxt 1 else
(corres_tac context (peel_two (typing_tree_of name)) fun_defs
callee_abs_thms callee_thms))
handle Bind => fallback_thm (@{make_string} Bind))
handle Match => fallback_thm (@{make_string} Match))
handle Option => fallback_thm (@{make_string} Option))
handle THM t => fallback_thm (@{make_string} (THM t)))
handle TERM t => fallback_thm (@{make_string} (TERM t)))
handle ERROR e => fallback_thm (@{make_string} (ERROR e))) ()
handle TimeLimit.TimeOut => fallback_thm (@{make_string} TimeLimit.TimeOut))
|> unfold_Cogent_types ctxt type_unfold_simps name])
val _ = tracing ("Time for " ^ thm_name ^ ": " ^ Timing.message time)
in thms end)
in (CogentCallTree ((xi_index, thm), CogentFun, name, callees'), ctxt) end
val (tr', ctxt) = descend tr ctxt
val _ = if null (!failed_proofs) then () else warning ("Failed proofs: " ^ commas_quote (!failed_proofs))
in (tr', ctxt) end
(* Convenience function for getting the expected corres thm names. *)
fun callee_corres_thms (CogentCallTree (_, _, _, callees)) = callees
|> map (fn call => case call of
FirstOrderCall f => (f, CogentCallTree_name f ^ "_corres_" ^ string_of_int (CogentCallTree_data f))
| SecondOrderCall (f, args) => (f, space_implode "_" (map CogentCallTree_name (f :: map snd args)) ^
"_corres_" ^ string_of_int (CogentCallTree_data f)))
|> partition (fn (tr, _) => CogentCallTree_funtype tr = CogentFun)
|> apply2 (map snd)
(* Assign AutoCorres recursion measures.
* Each second-order function call involves a trip to the dispatcher,
* meaning that the measure decreases by 2 instead of 1. *)
fun calc_call_measure tr = maximum (1 :: map calc_call_order_measure (CogentCallTree_calls tr))
and calc_call_order_measure (FirstOrderCall f) = 1 + calc_call_measure f
| calc_call_order_measure (SecondOrderCall (f, args)) =
1 + max (maximum (map (calc_call_measure o snd) args) + 2) (calc_call_measure f)
fun annotate_measure tr = let
fun annotate' d (CogentCallTree (x, ty, name, calls)) = let
in CogentCallTree ((x, d), ty, name, map (annotate_call' d) calls) end
and annotate_call' d (FirstOrderCall f) = FirstOrderCall (annotate' (d-1) f)
| annotate_call' d (SecondOrderCall (f, args)) =
SecondOrderCall (annotate' (d-1) f, map (apsnd (annotate' (d-3))) args)
in annotate' (calc_call_measure tr) tr end
fun map_annotations f (CogentCallTree (a, ty, name, calls)) =
CogentCallTree (f a, ty, name, calls |>
map (fn c => case c of FirstOrderCall a => FirstOrderCall (map_annotations f a)
| SecondOrderCall (a, bs) =>
SecondOrderCall (map_annotations f a, map (apsnd (map_annotations f)) bs)))
*}
end
|
(* Title: HOL/Proofs/Extraction/Greatest_Common_Divisor.thy
Author: Stefan Berghofer, TU Muenchen
Author: Helmut Schwichtenberg, LMU Muenchen
*)
section \<open>Greatest common divisor\<close>
theory Greatest_Common_Divisor
imports QuotRem
begin
theorem greatest_common_divisor:
"\<And>n::nat. Suc m < n \<Longrightarrow>
\<exists>k n1 m1. k * n1 = n \<and> k * m1 = Suc m \<and>
(\<forall>l l1 l2. l * l1 = n \<longrightarrow> l * l2 = Suc m \<longrightarrow> l \<le> k)"
proof (induct m rule: nat_wf_ind)
case (1 m n)
from division obtain r q where h1: "n = Suc m * q + r" and h2: "r \<le> m"
by iprover
show ?case
proof (cases r)
case 0
with h1 have "Suc m * q = n" by simp
moreover have "Suc m * 1 = Suc m" by simp
moreover have "l * l1 = n \<Longrightarrow> l * l2 = Suc m \<Longrightarrow> l \<le> Suc m" for l l1 l2
by (cases l2) simp_all
ultimately show ?thesis by iprover
next
case (Suc nat)
with h2 have h: "nat < m" by simp
moreover from h have "Suc nat < Suc m" by simp
ultimately have "\<exists>k m1 r1. k * m1 = Suc m \<and> k * r1 = Suc nat \<and>
(\<forall>l l1 l2. l * l1 = Suc m \<longrightarrow> l * l2 = Suc nat \<longrightarrow> l \<le> k)"
by (rule 1)
then obtain k m1 r1 where h1': "k * m1 = Suc m"
and h2': "k * r1 = Suc nat"
and h3': "\<And>l l1 l2. l * l1 = Suc m \<Longrightarrow> l * l2 = Suc nat \<Longrightarrow> l \<le> k"
by iprover
have mn: "Suc m < n" by (rule 1)
from h1 h1' h2' Suc have "k * (m1 * q + r1) = n"
by (simp add: add_mult_distrib2 mult.assoc [symmetric])
moreover have "l \<le> k" if ll1n: "l * l1 = n" and ll2m: "l * l2 = Suc m" for l l1 l2
proof -
have "l * (l1 - l2 * q) = Suc nat"
by (simp add: diff_mult_distrib2 h1 Suc [symmetric] mn ll1n ll2m [symmetric])
with ll2m show "l \<le> k" by (rule h3')
qed
ultimately show ?thesis using h1' by iprover
qed
qed
extract greatest_common_divisor
text \<open>
The extracted program for computing the greatest common divisor is
@{thm [display] greatest_common_divisor_def}
\<close>
instantiation nat :: default
begin
definition "default = (0::nat)"
instance ..
end
instantiation prod :: (default, default) default
begin
definition "default = (default, default)"
instance ..
end
instantiation "fun" :: (type, default) default
begin
definition "default = (\<lambda>x. default)"
instance ..
end
lemma "greatest_common_divisor 7 12 = (4, 3, 2)" by eval
end
|
{-# OPTIONS --safe --warning=error --without-K #-}
open import LogicalFormulae
open import Groups.Lemmas
open import Groups.Definition
open import Setoids.Orders.Partial.Definition
open import Setoids.Setoids
open import Functions.Definition
open import Sets.EquivalenceRelations
open import Rings.Definition
open import Rings.Orders.Partial.Definition
open import Numbers.Naturals.Semiring
open import Numbers.Naturals.Order
module Rings.Orders.Partial.Lemmas {n m p : _} {A : Set n} {S : Setoid {n} {m} A} {_+_ : A → A → A} {_*_ : A → A → A} {_<_ : Rel {_} {p} A} {R : Ring S _+_ _*_} {pOrder : SetoidPartialOrder S _<_} (pRing : PartiallyOrderedRing R pOrder) where
abstract
open PartiallyOrderedRing pRing
open Setoid S
open SetoidPartialOrder pOrder
open Ring R
open Group additiveGroup
open Equivalence eq
open import Rings.Lemmas R
ringAddInequalities : {w x y z : A} → w < x → y < z → (w + y) < (x + z)
ringAddInequalities {w = w} {x} {y} {z} w<x y<z = <Transitive (orderRespectsAddition w<x y) (<WellDefined groupIsAbelian groupIsAbelian (orderRespectsAddition y<z x))
ringCanMultiplyByPositive : {x y c : A} → (Ring.0R R) < c → x < y → (x * c) < (y * c)
ringCanMultiplyByPositive {x} {y} {c} 0<c x<y = SetoidPartialOrder.<WellDefined pOrder reflexive (Group.identRight additiveGroup) q'
where
have : 0R < (y + Group.inverse additiveGroup x)
have = SetoidPartialOrder.<WellDefined pOrder (Group.invRight additiveGroup) reflexive (orderRespectsAddition x<y (Group.inverse additiveGroup x))
p1 : 0R < ((y * c) + ((Group.inverse additiveGroup x) * c))
p1 = SetoidPartialOrder.<WellDefined pOrder reflexive (transitive *Commutative (transitive *DistributesOver+ ((Group.+WellDefined additiveGroup) *Commutative *Commutative))) (orderRespectsMultiplication have 0<c)
p' : 0R < ((y * c) + (Group.inverse additiveGroup (x * c)))
p' = SetoidPartialOrder.<WellDefined pOrder reflexive (Group.+WellDefined additiveGroup reflexive (transitive (transitive *Commutative ringMinusExtracts) (inverseWellDefined additiveGroup *Commutative))) p1
q : (0R + (x * c)) < (((y * c) + (Group.inverse additiveGroup (x * c))) + (x * c))
q = orderRespectsAddition p' (x * c)
q' : (x * c) < ((y * c) + 0R)
q' = SetoidPartialOrder.<WellDefined pOrder (Group.identLeft additiveGroup) (transitive (symmetric (Group.+Associative additiveGroup)) (Group.+WellDefined additiveGroup reflexive (Group.invLeft additiveGroup))) q
ringCanMultiplyByPositive' : {x y c : A} → (Ring.0R R) < c → x < y → (c * x) < (c * y)
ringCanMultiplyByPositive' {x} {y} {c} 0<c x<y = SetoidPartialOrder.<WellDefined pOrder *Commutative *Commutative (ringCanMultiplyByPositive 0<c x<y)
ringMultiplyPositives : {x y a b : A} → 0R < x → 0R < a → (x < y) → (a < b) → (x * a) < (y * b)
ringMultiplyPositives {x} {y} {a} {b} 0<x 0<a x<y a<b = SetoidPartialOrder.<Transitive pOrder (ringCanMultiplyByPositive 0<a x<y) (<WellDefined *Commutative *Commutative (ringCanMultiplyByPositive (SetoidPartialOrder.<Transitive pOrder 0<x x<y) a<b))
ringSwapNegatives : {x y : A} → (Group.inverse (Ring.additiveGroup R) x) < (Group.inverse (Ring.additiveGroup R) y) → y < x
ringSwapNegatives {x} {y} -x<-y = SetoidPartialOrder.<WellDefined pOrder (transitive (symmetric (Group.+Associative additiveGroup)) (transitive (Group.+WellDefined additiveGroup reflexive (Group.invLeft additiveGroup)) (Group.identRight additiveGroup))) (Group.identLeft additiveGroup) v
where
t : ((Group.inverse additiveGroup x) + y) < ((Group.inverse additiveGroup y) + y)
t = orderRespectsAddition -x<-y y
u : (y + (Group.inverse additiveGroup x)) < 0R
u = SetoidPartialOrder.<WellDefined pOrder (groupIsAbelian) (Group.invLeft additiveGroup) t
v : ((y + (Group.inverse additiveGroup x)) + x) < (0R + x)
v = orderRespectsAddition u x
ringSwapNegatives' : {x y : A} → x < y → (Group.inverse (Ring.additiveGroup R) y) < (Group.inverse (Ring.additiveGroup R) x)
ringSwapNegatives' {x} {y} x<y = ringSwapNegatives (<WellDefined (Equivalence.symmetric eq (invTwice additiveGroup _)) (Equivalence.symmetric eq (invTwice additiveGroup _)) x<y)
ringCanMultiplyByNegative : {x y c : A} → c < (Ring.0R R) → x < y → (y * c) < (x * c)
ringCanMultiplyByNegative {x} {y} {c} c<0 x<y = ringSwapNegatives u
where
open Equivalence eq
p1 : (c + Group.inverse additiveGroup c) < (0R + Group.inverse additiveGroup c)
p1 = orderRespectsAddition c<0 _
0<-c : 0R < (Group.inverse additiveGroup c)
0<-c = SetoidPartialOrder.<WellDefined pOrder (Group.invRight additiveGroup) (Group.identLeft additiveGroup) p1
t : (x * Group.inverse additiveGroup c) < (y * Group.inverse additiveGroup c)
t = ringCanMultiplyByPositive 0<-c x<y
u : (Group.inverse additiveGroup (x * c)) < Group.inverse additiveGroup (y * c)
u = SetoidPartialOrder.<WellDefined pOrder ringMinusExtracts ringMinusExtracts t
anyComparisonImpliesNontrivial : {a b : A} → a < b → (0R ∼ 1R) → False
anyComparisonImpliesNontrivial {a} {b} a<b 0=1 = irreflexive (<WellDefined (oneZeroImpliesAllZero 0=1) (oneZeroImpliesAllZero 0=1) a<b)
moveInequality : {a b : A} → a < b → 0R < (b + inverse a)
moveInequality {a} {b} a<b = <WellDefined invRight reflexive (orderRespectsAddition a<b (inverse a))
moveInequality' : {a b : A} → a < b → (a + inverse b) < 0R
moveInequality' {a} {b} a<b = <WellDefined reflexive invRight (orderRespectsAddition a<b (inverse b))
greaterImpliesNotEqual : {a b : A} → a < b → (a ∼ b → False)
greaterImpliesNotEqual {a} {b} a<b a=b = irreflexive (<WellDefined a=b reflexive a<b)
greaterImpliesNotEqual' : {a b : A} → a < b → (b ∼ a → False)
greaterImpliesNotEqual' {a} {b} a<b a=b = irreflexive (<WellDefined reflexive a=b a<b)
negativeInequality : {a : A} → a < 0G → 0G < inverse a
negativeInequality {a} a<0 = <WellDefined invRight identLeft (orderRespectsAddition a<0 (inverse a))
negativeInequality' : {a : A} → 0G < a → inverse a < 0G
negativeInequality' {a} 0<a = <WellDefined identLeft invRight (orderRespectsAddition 0<a (inverse a))
open import Rings.InitialRing R
fromNIncreasing : (0R < 1R) → (n : ℕ) → (fromN n) < (fromN (succ n))
fromNIncreasing 0<1 zero = <WellDefined reflexive (symmetric identRight) 0<1
fromNIncreasing 0<1 (succ n) = <WellDefined groupIsAbelian groupIsAbelian (orderRespectsAddition (fromNIncreasing 0<1 n) 1R)
fromNPreservesOrder : (0R < 1R) → {a b : ℕ} → (a <N b) → (fromN a) < (fromN b)
fromNPreservesOrder 0<1 {zero} {succ zero} a<b = fromNIncreasing 0<1 0
fromNPreservesOrder 0<1 {zero} {succ (succ b)} a<b = <Transitive (fromNPreservesOrder 0<1 (succIsPositive b)) (fromNIncreasing 0<1 (succ b))
fromNPreservesOrder 0<1 {succ a} {succ b} a<b = <WellDefined groupIsAbelian groupIsAbelian (orderRespectsAddition (fromNPreservesOrder 0<1 (canRemoveSuccFrom<N a<b)) 1R)
|
/-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.nat.basic
import Mathlib.PostPort
namespace Mathlib
/-!
# Definitions and properties of `gcd`, `lcm`, and `coprime`
-/
namespace nat
/-! ### `gcd` -/
theorem gcd_dvd (m : ℕ) (n : ℕ) : gcd m n ∣ m ∧ gcd m n ∣ n := sorry
theorem gcd_dvd_left (m : ℕ) (n : ℕ) : gcd m n ∣ m :=
and.left (gcd_dvd m n)
theorem gcd_dvd_right (m : ℕ) (n : ℕ) : gcd m n ∣ n :=
and.right (gcd_dvd m n)
theorem gcd_le_left {m : ℕ} (n : ℕ) (h : 0 < m) : gcd m n ≤ m :=
le_of_dvd h (gcd_dvd_left m n)
theorem gcd_le_right (m : ℕ) {n : ℕ} (h : 0 < n) : gcd m n ≤ n :=
le_of_dvd h (gcd_dvd_right m n)
theorem dvd_gcd {m : ℕ} {n : ℕ} {k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n := sorry
theorem dvd_gcd_iff {m : ℕ} {n : ℕ} {k : ℕ} : k ∣ gcd m n ↔ k ∣ m ∧ k ∣ n := sorry
theorem gcd_comm (m : ℕ) (n : ℕ) : gcd m n = gcd n m :=
dvd_antisymm (dvd_gcd (gcd_dvd_right m n) (gcd_dvd_left m n)) (dvd_gcd (gcd_dvd_right n m) (gcd_dvd_left n m))
theorem gcd_eq_left_iff_dvd {m : ℕ} {n : ℕ} : m ∣ n ↔ gcd m n = m := sorry
theorem gcd_eq_right_iff_dvd {m : ℕ} {n : ℕ} : m ∣ n ↔ gcd n m = m :=
eq.mpr (id (Eq._oldrec (Eq.refl (m ∣ n ↔ gcd n m = m)) (gcd_comm n m))) gcd_eq_left_iff_dvd
theorem gcd_assoc (m : ℕ) (n : ℕ) (k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) := sorry
@[simp] theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 :=
Eq.trans (gcd_comm n 1) (gcd_one_left n)
theorem gcd_mul_left (m : ℕ) (n : ℕ) (k : ℕ) : gcd (m * n) (m * k) = m * gcd n k := sorry
theorem gcd_mul_right (m : ℕ) (n : ℕ) (k : ℕ) : gcd (m * n) (k * n) = gcd m k * n := sorry
theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : 0 < m) : 0 < gcd m n :=
pos_of_dvd_of_pos (gcd_dvd_left m n) mpos
theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : 0 < n) : 0 < gcd m n :=
pos_of_dvd_of_pos (gcd_dvd_right m n) npos
theorem eq_zero_of_gcd_eq_zero_left {m : ℕ} {n : ℕ} (H : gcd m n = 0) : m = 0 :=
or.elim (eq_zero_or_pos m) id fun (H1 : 0 < m) => absurd (Eq.symm H) (ne_of_lt (gcd_pos_of_pos_left n H1))
theorem eq_zero_of_gcd_eq_zero_right {m : ℕ} {n : ℕ} (H : gcd m n = 0) : n = 0 :=
eq_zero_of_gcd_eq_zero_left (eq.mp (Eq._oldrec (Eq.refl (gcd m n = 0)) (gcd_comm m n)) H)
theorem gcd_div {m : ℕ} {n : ℕ} {k : ℕ} (H1 : k ∣ m) (H2 : k ∣ n) : gcd (m / k) (n / k) = gcd m n / k := sorry
theorem gcd_dvd_gcd_of_dvd_left {m : ℕ} {k : ℕ} (n : ℕ) (H : m ∣ k) : gcd m n ∣ gcd k n :=
dvd_gcd (dvd.trans (gcd_dvd_left m n) H) (gcd_dvd_right m n)
theorem gcd_dvd_gcd_of_dvd_right {m : ℕ} {k : ℕ} (n : ℕ) (H : m ∣ k) : gcd n m ∣ gcd n k :=
dvd_gcd (gcd_dvd_left n m) (dvd.trans (gcd_dvd_right n m) H)
theorem gcd_dvd_gcd_mul_left (m : ℕ) (n : ℕ) (k : ℕ) : gcd m n ∣ gcd (k * m) n :=
gcd_dvd_gcd_of_dvd_left n (dvd_mul_left m k)
theorem gcd_dvd_gcd_mul_right (m : ℕ) (n : ℕ) (k : ℕ) : gcd m n ∣ gcd (m * k) n :=
gcd_dvd_gcd_of_dvd_left n (dvd_mul_right m k)
theorem gcd_dvd_gcd_mul_left_right (m : ℕ) (n : ℕ) (k : ℕ) : gcd m n ∣ gcd m (k * n) :=
gcd_dvd_gcd_of_dvd_right m (dvd_mul_left n k)
theorem gcd_dvd_gcd_mul_right_right (m : ℕ) (n : ℕ) (k : ℕ) : gcd m n ∣ gcd m (n * k) :=
gcd_dvd_gcd_of_dvd_right m (dvd_mul_right n k)
theorem gcd_eq_left {m : ℕ} {n : ℕ} (H : m ∣ n) : gcd m n = m :=
dvd_antisymm (gcd_dvd_left m n) (dvd_gcd (dvd_refl m) H)
theorem gcd_eq_right {m : ℕ} {n : ℕ} (H : n ∣ m) : gcd m n = n :=
eq.mpr (id (Eq._oldrec (Eq.refl (gcd m n = n)) (gcd_comm m n)))
(eq.mpr (id (Eq._oldrec (Eq.refl (gcd n m = n)) (gcd_eq_left H))) (Eq.refl n))
@[simp] theorem gcd_mul_left_left (m : ℕ) (n : ℕ) : gcd (m * n) n = n :=
dvd_antisymm (gcd_dvd_right (m * n) n) (dvd_gcd (dvd_mul_left n m) (dvd_refl n))
@[simp] theorem gcd_mul_left_right (m : ℕ) (n : ℕ) : gcd n (m * n) = n :=
eq.mpr (id (Eq._oldrec (Eq.refl (gcd n (m * n) = n)) (gcd_comm n (m * n))))
(eq.mpr (id (Eq._oldrec (Eq.refl (gcd (m * n) n = n)) (gcd_mul_left_left m n))) (Eq.refl n))
@[simp] theorem gcd_mul_right_left (m : ℕ) (n : ℕ) : gcd (n * m) n = n :=
eq.mpr (id (Eq._oldrec (Eq.refl (gcd (n * m) n = n)) (mul_comm n m)))
(eq.mpr (id (Eq._oldrec (Eq.refl (gcd (m * n) n = n)) (gcd_mul_left_left m n))) (Eq.refl n))
@[simp] theorem gcd_mul_right_right (m : ℕ) (n : ℕ) : gcd n (n * m) = n :=
eq.mpr (id (Eq._oldrec (Eq.refl (gcd n (n * m) = n)) (gcd_comm n (n * m))))
(eq.mpr (id (Eq._oldrec (Eq.refl (gcd (n * m) n = n)) (gcd_mul_right_left m n))) (Eq.refl n))
@[simp] theorem gcd_gcd_self_right_left (m : ℕ) (n : ℕ) : gcd m (gcd m n) = gcd m n :=
dvd_antisymm (gcd_dvd_right m (gcd m n)) (dvd_gcd (gcd_dvd_left m n) (dvd_refl (gcd m n)))
@[simp] theorem gcd_gcd_self_right_right (m : ℕ) (n : ℕ) : gcd m (gcd n m) = gcd n m :=
eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (gcd n m) = gcd n m)) (gcd_comm n m)))
(eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (gcd m n) = gcd m n)) (gcd_gcd_self_right_left m n))) (Eq.refl (gcd m n)))
@[simp] theorem gcd_gcd_self_left_right (m : ℕ) (n : ℕ) : gcd (gcd n m) m = gcd n m :=
eq.mpr (id (Eq._oldrec (Eq.refl (gcd (gcd n m) m = gcd n m)) (gcd_comm (gcd n m) m)))
(eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (gcd n m) = gcd n m)) (gcd_gcd_self_right_right m n))) (Eq.refl (gcd n m)))
@[simp] theorem gcd_gcd_self_left_left (m : ℕ) (n : ℕ) : gcd (gcd m n) m = gcd m n :=
eq.mpr (id (Eq._oldrec (Eq.refl (gcd (gcd m n) m = gcd m n)) (gcd_comm m n)))
(eq.mpr (id (Eq._oldrec (Eq.refl (gcd (gcd n m) m = gcd n m)) (gcd_gcd_self_left_right m n))) (Eq.refl (gcd n m)))
theorem gcd_add_mul_self (m : ℕ) (n : ℕ) (k : ℕ) : gcd m (n + k * m) = gcd m n := sorry
theorem gcd_eq_zero_iff {i : ℕ} {j : ℕ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := sorry
/-! ### `lcm` -/
theorem lcm_comm (m : ℕ) (n : ℕ) : lcm m n = lcm n m :=
id
(eq.mpr (id (Eq._oldrec (Eq.refl (m * n / gcd m n = n * m / gcd n m)) (mul_comm m n)))
(eq.mpr (id (Eq._oldrec (Eq.refl (n * m / gcd m n = n * m / gcd n m)) (gcd_comm m n))) (Eq.refl (n * m / gcd n m))))
@[simp] theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 :=
id
(eq.mpr (id (Eq._oldrec (Eq.refl (0 * m / gcd 0 m = 0)) (zero_mul m)))
(eq.mpr (id (Eq._oldrec (Eq.refl (0 / gcd 0 m = 0)) (nat.zero_div (gcd 0 m)))) (Eq.refl 0)))
@[simp] theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 :=
lcm_comm 0 m ▸ lcm_zero_left m
@[simp] theorem lcm_one_left (m : ℕ) : lcm 1 m = m := sorry
@[simp] theorem lcm_one_right (m : ℕ) : lcm m 1 = m :=
lcm_comm 1 m ▸ lcm_one_left m
@[simp] theorem lcm_self (m : ℕ) : lcm m m = m := sorry
theorem dvd_lcm_left (m : ℕ) (n : ℕ) : m ∣ lcm m n :=
dvd.intro (n / gcd m n) (Eq.symm (nat.mul_div_assoc m (gcd_dvd_right m n)))
theorem dvd_lcm_right (m : ℕ) (n : ℕ) : n ∣ lcm m n :=
lcm_comm n m ▸ dvd_lcm_left n m
theorem gcd_mul_lcm (m : ℕ) (n : ℕ) : gcd m n * lcm m n = m * n := sorry
theorem lcm_dvd {m : ℕ} {n : ℕ} {k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k := sorry
theorem lcm_assoc (m : ℕ) (n : ℕ) (k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) := sorry
theorem lcm_ne_zero {m : ℕ} {n : ℕ} (hm : m ≠ 0) (hn : n ≠ 0) : lcm m n ≠ 0 := sorry
/-!
### `coprime`
See also `nat.coprime_of_dvd` and `nat.coprime_of_dvd'` to prove `nat.coprime m n`.
-/
protected instance coprime.decidable (m : ℕ) (n : ℕ) : Decidable (coprime m n) :=
eq.mpr sorry (nat.decidable_eq (gcd m n) 1)
theorem coprime.gcd_eq_one {m : ℕ} {n : ℕ} : coprime m n → gcd m n = 1 :=
id
theorem coprime.symm {m : ℕ} {n : ℕ} : coprime n m → coprime m n :=
Eq.trans (gcd_comm m n)
theorem coprime.dvd_of_dvd_mul_right {m : ℕ} {n : ℕ} {k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m := sorry
theorem coprime.dvd_of_dvd_mul_left {m : ℕ} {n : ℕ} {k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n :=
coprime.dvd_of_dvd_mul_right H1 (eq.mp (Eq._oldrec (Eq.refl (k ∣ m * n)) (mul_comm m n)) H2)
theorem coprime.gcd_mul_left_cancel {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) : gcd (k * m) n = gcd m n := sorry
theorem coprime.gcd_mul_right_cancel (m : ℕ) {k : ℕ} {n : ℕ} (H : coprime k n) : gcd (m * k) n = gcd m n :=
eq.mpr (id (Eq._oldrec (Eq.refl (gcd (m * k) n = gcd m n)) (mul_comm m k)))
(eq.mpr (id (Eq._oldrec (Eq.refl (gcd (k * m) n = gcd m n)) (coprime.gcd_mul_left_cancel m H))) (Eq.refl (gcd m n)))
theorem coprime.gcd_mul_left_cancel_right {k : ℕ} {m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (k * n) = gcd m n := sorry
theorem coprime.gcd_mul_right_cancel_right {k : ℕ} {m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (n * k) = gcd m n :=
eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (n * k) = gcd m n)) (mul_comm n k)))
(eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (k * n) = gcd m n)) (coprime.gcd_mul_left_cancel_right n H)))
(Eq.refl (gcd m n)))
theorem coprime_div_gcd_div_gcd {m : ℕ} {n : ℕ} (H : 0 < gcd m n) : coprime (m / gcd m n) (n / gcd m n) := sorry
theorem not_coprime_of_dvd_of_dvd {m : ℕ} {n : ℕ} {d : ℕ} (dgt1 : 1 < d) (Hm : d ∣ m) (Hn : d ∣ n) : ¬coprime m n :=
fun (co : gcd m n = 1) =>
not_lt_of_ge (le_of_dvd zero_lt_one (eq.mpr (id (Eq._oldrec (Eq.refl (d ∣ 1)) (Eq.symm co))) (dvd_gcd Hm Hn))) dgt1
theorem exists_coprime {m : ℕ} {n : ℕ} (H : 0 < gcd m n) : ∃ (m' : ℕ), ∃ (n' : ℕ), coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n := sorry
theorem exists_coprime' {m : ℕ} {n : ℕ} (H : 0 < gcd m n) : ∃ (g : ℕ), ∃ (m' : ℕ), ∃ (n' : ℕ), 0 < g ∧ coprime m' n' ∧ m = m' * g ∧ n = n' * g := sorry
theorem coprime.mul {m : ℕ} {n : ℕ} {k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k :=
Eq.trans (coprime.gcd_mul_left_cancel n H1) H2
theorem coprime.mul_right {k : ℕ} {m : ℕ} {n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) :=
coprime.symm (coprime.mul (coprime.symm H1) (coprime.symm H2))
theorem coprime.coprime_dvd_left {m : ℕ} {k : ℕ} {n : ℕ} (H1 : m ∣ k) (H2 : coprime k n) : coprime m n := sorry
theorem coprime.coprime_dvd_right {m : ℕ} {k : ℕ} {n : ℕ} (H1 : n ∣ m) (H2 : coprime k m) : coprime k n :=
coprime.symm (coprime.coprime_dvd_left H1 (coprime.symm H2))
theorem coprime.coprime_mul_left {k : ℕ} {m : ℕ} {n : ℕ} (H : coprime (k * m) n) : coprime m n :=
coprime.coprime_dvd_left (dvd_mul_left m k) H
theorem coprime.coprime_mul_right {k : ℕ} {m : ℕ} {n : ℕ} (H : coprime (m * k) n) : coprime m n :=
coprime.coprime_dvd_left (dvd_mul_right m k) H
theorem coprime.coprime_mul_left_right {k : ℕ} {m : ℕ} {n : ℕ} (H : coprime m (k * n)) : coprime m n :=
coprime.coprime_dvd_right (dvd_mul_left n k) H
theorem coprime.coprime_mul_right_right {k : ℕ} {m : ℕ} {n : ℕ} (H : coprime m (n * k)) : coprime m n :=
coprime.coprime_dvd_right (dvd_mul_right n k) H
theorem coprime.coprime_div_left {m : ℕ} {n : ℕ} {a : ℕ} (cmn : coprime m n) (dvd : a ∣ m) : coprime (m / a) n := sorry
theorem coprime.coprime_div_right {m : ℕ} {n : ℕ} {a : ℕ} (cmn : coprime m n) (dvd : a ∣ n) : coprime m (n / a) :=
coprime.symm (coprime.coprime_div_left (coprime.symm cmn) dvd)
theorem coprime_mul_iff_left {k : ℕ} {m : ℕ} {n : ℕ} : coprime (m * n) k ↔ coprime m k ∧ coprime n k := sorry
theorem coprime_mul_iff_right {k : ℕ} {m : ℕ} {n : ℕ} : coprime k (m * n) ↔ coprime k m ∧ coprime k n := sorry
theorem coprime.gcd_left (k : ℕ) {m : ℕ} {n : ℕ} (hmn : coprime m n) : coprime (gcd k m) n :=
coprime.coprime_dvd_left (gcd_dvd_right k m) hmn
theorem coprime.gcd_right (k : ℕ) {m : ℕ} {n : ℕ} (hmn : coprime m n) : coprime m (gcd k n) :=
coprime.coprime_dvd_right (gcd_dvd_right k n) hmn
theorem coprime.gcd_both (k : ℕ) (l : ℕ) {m : ℕ} {n : ℕ} (hmn : coprime m n) : coprime (gcd k m) (gcd l n) :=
coprime.gcd_right l (coprime.gcd_left k hmn)
theorem coprime.mul_dvd_of_dvd_of_dvd {a : ℕ} {n : ℕ} {m : ℕ} (hmn : coprime m n) (hm : m ∣ a) (hn : n ∣ a) : m * n ∣ a := sorry
theorem coprime_one_left (n : ℕ) : coprime 1 n :=
gcd_one_left
theorem coprime_one_right (n : ℕ) : coprime n 1 :=
gcd_one_right
theorem coprime.pow_left {m : ℕ} {k : ℕ} (n : ℕ) (H1 : coprime m k) : coprime (m ^ n) k :=
nat.rec_on n (coprime_one_left k) fun (n : ℕ) (IH : coprime (m ^ n) k) => coprime.mul H1 IH
theorem coprime.pow_right {m : ℕ} {k : ℕ} (n : ℕ) (H1 : coprime k m) : coprime k (m ^ n) :=
coprime.symm (coprime.pow_left n (coprime.symm H1))
theorem coprime.pow {k : ℕ} {l : ℕ} (m : ℕ) (n : ℕ) (H1 : coprime k l) : coprime (k ^ m) (l ^ n) :=
coprime.pow_right n (coprime.pow_left m H1)
theorem coprime.eq_one_of_dvd {k : ℕ} {m : ℕ} (H : coprime k m) (d : k ∣ m) : k = 1 :=
eq.mpr (id (Eq._oldrec (Eq.refl (k = 1)) (Eq.symm (coprime.gcd_eq_one H))))
(eq.mpr (id (Eq._oldrec (Eq.refl (k = gcd k m)) (gcd_eq_left d))) (Eq.refl k))
@[simp] theorem coprime_zero_left (n : ℕ) : coprime 0 n ↔ n = 1 := sorry
@[simp] theorem coprime_zero_right (n : ℕ) : coprime n 0 ↔ n = 1 := sorry
@[simp] theorem coprime_one_left_iff (n : ℕ) : coprime 1 n ↔ True := sorry
@[simp] theorem coprime_one_right_iff (n : ℕ) : coprime n 1 ↔ True := sorry
@[simp] theorem coprime_self (n : ℕ) : coprime n n ↔ n = 1 := sorry
/-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. -/
def prod_dvd_and_dvd_of_dvd_prod {m : ℕ} {n : ℕ} {k : ℕ} (H : k ∣ m * n) : Subtype fun (d : (Subtype fun (m' : ℕ) => m' ∣ m) × Subtype fun (n' : ℕ) => n' ∣ n) => k = ↑(prod.fst d) * ↑(prod.snd d) :=
(fun (_x : ℕ) (h0 : gcd k m = _x) =>
nat.cases_on _x
(fun (h0 : gcd k m = 0) =>
Eq._oldrec
(fun (H : 0 ∣ m * n) (h0 : gcd 0 m = 0) =>
Eq._oldrec
(fun (H : 0 ∣ 0 * n) (h0 : gcd 0 0 = 0) =>
{ val := ({ val := 0, property := sorry }, { val := n, property := dvd_refl n }), property := sorry })
sorry H h0)
sorry H h0)
(fun (n_1 : ℕ) (h0 : gcd k m = Nat.succ n_1) =>
(fun (h0 : gcd k m = Nat.succ n_1) =>
{ val := ({ val := gcd k m, property := gcd_dvd_right k m }, { val := k / gcd k m, property := sorry }),
property := sorry })
h0)
h0)
(gcd k m) sorry
theorem gcd_mul_dvd_mul_gcd (k : ℕ) (m : ℕ) (n : ℕ) : gcd k (m * n) ∣ gcd k m * gcd k n := sorry
theorem coprime.gcd_mul (k : ℕ) {m : ℕ} {n : ℕ} (h : coprime m n) : gcd k (m * n) = gcd k m * gcd k n :=
dvd_antisymm (gcd_mul_dvd_mul_gcd k m n)
(coprime.mul_dvd_of_dvd_of_dvd (coprime.gcd_both k k h) (gcd_dvd_gcd_mul_right_right k m n)
(gcd_dvd_gcd_mul_left_right k n m))
theorem pow_dvd_pow_iff {a : ℕ} {b : ℕ} {n : ℕ} (n0 : 0 < n) : a ^ n ∣ b ^ n ↔ a ∣ b := sorry
theorem gcd_mul_gcd_of_coprime_of_mul_eq_mul {a : ℕ} {b : ℕ} {c : ℕ} {d : ℕ} (cop : coprime c d) (h : a * b = c * d) : gcd a c * gcd b c = c := sorry
|
lemma coeffs_eq_Nil [simp]: "coeffs p = [] \<longleftrightarrow> p = 0" |
\documentclass[11pt]{article}
\begin{document}
\section{Publication Plans}
\begin{itemize}
\item Journal article(s) in Journal of Computers in Mathematics and Science Teaching (JCMST). JCMST is a highly respected scholarly journal that offers an in-depth forum for the interchange of information in the fields of science, mathematics, and computer science.
%
\item Conference presentations through the Special Interest Group on Computer Science Education (SIGCSE) of the Association for Computing Machinery, Inc. (ACM). SIGCSE's mission is to provide a forum for educators to discuss issues related to the development, implementation, and/or evaluation of computing programs, curricula, and courses, as well as syllabi, laboratories, and other elements of teaching and pedagogy.
%
\item Conference presentation at the International Conference on Physics Education (ICPE). ICPE brings together people working in physics educational research and in physics education at all types of schools from all over the world to enable them to share and exchange our experience.
%
\item Journal article in Physics Education. Physics Education is the international journal for everyone involved with the teaching of physics in schools and colleges. The articles reflect the needs and interests of secondary school teachers, teacher trainers and those involved with courses up to introductory undergraduate level.
%
\item Small workshops at the Association for Biology Laboratory Education (ABLE) conferences. ABLE's mission is to promote information exchange among university and college educators actively concerned with teaching biology in a laboratory setting. Each conference brings together a group of selected presenters with about 140 participants from university and college biology departments throughout Canada and the U.S. In three very full days, the participants are actively involved in four 3-hour ``hands on" workshops and several shorter ``mini" workshops. The workshop presenters provide all of the essential information and experiences that the potential user of the laboratory would require in order to ``take it home" and use the exercise in their own teaching program. The workshops are published in Tested Studies for Laboratory Teaching, the conference proceedings published by ABLE. Selected articles are also available online.
%
\item Conference presentations through the Society for Industrial and Applied Mathematics (SIAM). SIAM's Education Committee holds a session at the Joint Math Meeting that focuses on educational issues. They also work to provide curriculum input for programs in mathematical sciences or computational sciences as well as at a national level, including K-12.
%http://www.siam.org/students/resources/report.php
%
\item Conference presentations through the American Nuclear Society (ANS). ANS's Education Training and Workforce Development Division hosts tracks at National Meetings that would be appropriate for this work.
\end{itemize}
\end{document} |
include("silenttests.jl")
include("othertests.jl")
|
#include <boost/spirit/include/classic_error_handling.hpp>
|
import MyNat
open MyNat
example (P Q : Type) (p : P) (h : P -> Q) : Q := by
exact h p
example : ℕ -> ℕ := by
intro n
exact 3 * n + 2
example (P Q R S T U: Type)
(p : P)
(h : P → Q)
(i : Q → R)
(j : Q → T)
(k : S → T)
(l : T → U)
: U := by
have q := h p
have t := j q
have u := l t
exact u
example (P Q R S T U: Type)
(p : P)
(h : P → Q)
(i : Q → R)
(j : Q → T)
(k : S → T)
(l : T → U)
: U := by
apply l
apply j
apply h
exact p
example (P Q : Type) : P → (Q → P) := by
intro p _
exact p
example (P Q R : Type) : (P → (Q → R)) → ((P → Q) → (P → R)) := by
intro a b c
have q := b c
have r := a c q
exact r
example (P Q F : Type) : (P → Q) → ((Q → F) → (P → F)) := by
intro a b c
apply b
apply a
exact c
example (P Q : Type) : (P → Q) → ((Q → empty) → (P → empty)) := by
intro a b c
apply b
apply a
exact c
example (A B C D E F G H I J K L : Type)
(f1 : A → B) (f2 : B → E) (f3 : E → D) (f4 : D → A) (f5 : E → F)
(f6 : F → C) (f7 : B → C) (f8 : F → G) (f9 : G → J) (f10 : I → J)
(f11 : J → I) (f12 : I → H) (f13 : E → H) (f14 : H → K) (f15 : I → L)
: A → L := by
intro a
exact f15 (f11 (f9 (f8 (f5 (f2 (f1 a))))))
|
(*** Introduction to Computational Logic, Coq part of Assignment 9 ***)
Require Import Arith Lia.
(*** Exercise 9.1 ***)
(* The first 5 exercises are stated for the explicit definition of x <= y. *)
Section LE.
Definition le (x y : nat) : Prop :=
exists k, x + k = y.
Notation "x <= y" := (le x y).
Notation "x < y" := (le (S x) y).
Definition dec (X : Prop) :=
{X} + {~ X}.
Lemma origin x :
0 <= x.
Proof.
now exists x.
Qed.
Lemma refl x :
x <= x.
Proof.
now exists 0.
Qed.
Lemma trans x y z :
x <= y -> y <= z -> x <= z.
Proof.
intros [k H1] [l H2].
exists (k + l). now rewrite plus_assoc, H1.
Qed.
Lemma antisym x y :
x <= y -> y <= x -> x = y.
Proof.
intros [k H1] [l H2].
assert (H: forall m n, m + n = m -> n = 0).
{ intros m n. induction m as [|m IH].
- now cbn.
- cbn. intros H%Nat.succ_inj. apply IH, H.
}
rewrite <- H1 in H2. rewrite <- plus_assoc in H2. apply H, plus_is_O in H2 as [H2 _].
now rewrite H2, Nat.add_0_r in H1.
Qed.
Lemma shift x y :
S x <= S y <-> x <= y.
Proof.
split.
- intros [k H]. exists k. cbn. now apply Nat.succ_inj.
- intros [k H]. exists k. cbn. now rewrite H.
Qed.
Lemma strict x :
~ x < x.
Proof.
intros [k H]. destruct k.
- cbn in H. rewrite Nat.add_0_r in H. now apply Nat.neq_succ_diag_l in H.
Abort.
Lemma minimum x :
~ x < 0.
Proof.
intros H. destruct H as [k H]. lia.
Qed.
(*** Exercise 9.2 ***)
Lemma add_sub_eq x y :
x + y - x = y.
Proof.
induction x as [|x IH]; cbn.
- apply Nat.sub_0_r.
- exact IH.
Qed.
Lemma le_add_sub x y :
x <= y -> x + (y - x) = y.
Proof.
intros [k H].
Abort.
(*** Exercise 9.3 ***)
Lemma linearity :
forall n m, n <= m \/ m <= n.
Proof.
intros n m. induction n as [|n IH] in m |-*.
- left. apply origin.
- destruct m.
+ right. now exists (S n).
+ destruct (IH m) as [[k H1]|[l H2]].
* left. exists k. cbn. now rewrite H1.
* right. exists l. cbn. now rewrite H2.
Qed.
Lemma trichotomy :
forall n m, n < m \/ n = m \/ m < n.
Proof.
intros n m. specialize (linearity n m) as [[k H1]|[l H2]].
- left. exists (k - 1). rewrite <- H1.
Abort.
Lemma not_lt_le x y :
~ (y < x) -> x <= y.
Proof.
(*...*)
Admitted.
Lemma not_lt_eq x y :
~ (x < y) -> ~ (y < x) -> x = y.
Proof.
(*...*)
Admitted.
(*** Exercise 9.4 ***)
Lemma le_iff x y :
x <= y <-> x - y = 0.
Proof.
split.
- intros [k <-]. lia.
- intros H. exists (y - x). lia.
Qed.
Lemma le_dec x y :
dec (x <= y).
Proof.
induction x as [|x IH] in y |-*.
- left. apply origin.
- destruct y.
+ right. apply minimum.
+ specialize (IH y) as [H|H].
* left. destruct H as [k H]. exists k. cbn. now rewrite H.
* right. contradict H. destruct H as [k H]. cbn in H.
exists k. now apply Nat.succ_inj.
Qed.
Lemma le_dec' x y :
dec (x <= y).
Proof.
destruct (x - y) eqn:H.
- left. now apply le_iff.
- right. intros H2. apply le_iff in H2. congruence.
Qed.
Fixpoint le_bool (x y : nat) : bool :=
match x, y with
| O, y => true
| S _, O => false
| S x, S y => le_bool x y
end.
Lemma le_bool_spec x y :
x <= y <-> le_bool x y = true.
Proof.
split.
- intros H. destruct (le_bool x y) eqn:H2.
+ reflexivity.
+ rewrite <- H2. destruct x, y.
* reflexivity.
* reflexivity.
* exfalso. now apply (minimum x).
* destruct H as [k H].
Abort.
(*** Exercise 9.5 ***)
Lemma nat_dec (x y : nat) :
dec (x = y).
Proof.
(*...*)
Admitted.
End LE.
(*** Exercise 9.6 ***)
(* We now switch to the pre-defined x <= y and fully rely on lia. *)
Lemma size_induction X (f : X -> nat) (p : X -> Type) :
(forall x, (forall y, f y < f x -> p y) -> p x) -> forall x, p x.
Proof.
(* intros H x. specialize (H x). apply H. *)
(* intros y H2. induction (f x) as [|fx IH]. *)
(* - destruct (f y). *)
(* + *)
Admitted.
Lemma complete_induction (p : nat -> Type) :
(forall x, (forall y, y < x -> p y) -> p x) -> forall x, p x.
Proof.
apply (size_induction _ (fun x => x)).
Qed.
(*** Exercise 9.7 ***)
Lemma div_mod_unique y a b a' b' :
b <= y -> b' <= y -> a * S y + b = a' * S y + b' -> a = a' /\ b = b'.
Proof.
intros H1 H2.
induction a as [|a IH] in a' |-*; destruct a'; cbn.
- lia.
- lia.
- lia.
- specialize (IH a'). lia.
Qed.
Lemma le_lt_dec x y :
{x <= y} + {y < x}.
Proof.
induction x as [|x IH] in y |-*.
- left. lia.
- destruct y as [|y].
+ right. lia.
+ specialize (IH y) as [IH|IH].
* left. lia.
* right. lia.
Qed.
Theorem div_mod x y :
{ a & { b & x = a * S y + b /\ b <= y}}.
Proof.
(*...*)
Admitted.
Definition D (x y : nat) := (*...*) 0.
Definition M (x y : nat) := (*...*) 0.
Lemma DM_spec1 x y :
x = D x y * S y + M x y.
Proof.
(*...*)
Admitted.
Lemma DM_spec2 x y :
M x y <= y.
Proof.
(*...*)
Admitted.
(*** Exercise 9.8 ***)
Definition divides x y :=
x <> 0 /\ exists k, y = k * x.
Lemma divides_dec x y :
dec (divides x y).
Proof.
(*...*)
Admitted.
Definition cong x y k :=
(x <= y /\ divides k (y - x)) \/ (y < x /\ divides k (x - y)).
Lemma cong_dec x y k :
dec (cong x y k).
Proof.
(*...*)
Admitted.
(*** Exercise 9.10 ***)
Definition spec_exp mu :=
forall f n, (f (mu f n) = true -> mu f n <= n /\ forall k, k < mu f n -> f k = false)
/\ (f (mu f n) = false -> mu f n = n /\ forall k, k <= n -> f k = false).
Definition wf X (R : X -> X -> Prop) :=
forall f, (exists x, f x = true) -> exists x, f x = true /\ forall y, f y = true -> R x y.
Lemma nat_wf mu :
spec_exp mu -> wf nat (fun x y => x <= y).
Proof.
(*...*)
Admitted.
(*** Exercise 9.11 ***)
Section S1.
Variables (f: nat -> bool)
(mu: nat -> nat)
(R1: mu 0 = 0)
(R2: forall n, mu (S n) = if f (mu n) then mu n else S n).
Goal forall n, if f (mu n)
then mu n <= n /\ forall k, k < mu n -> f k = false
else mu n = n /\ forall k, k <= n -> f k = false.
Proof.
(*...*)
Admitted.
Variables (mu': nat -> nat)
(R1': mu' 0 = 0)
(R2': forall n, mu' (S n) = if f (mu' n) then mu' n else S n).
Goal forall n, mu n = mu' n.
Proof.
(*...*)
Admitted.
End S1.
Section S2.
Variables (f: nat -> bool) (mu: nat -> nat).
Variable (R: forall n, if f (mu n)
then mu n <= n /\ forall k, k < mu n -> f k = false
else mu n = n /\ forall k, k <= n -> f k = false ).
Goal forall n, mu n <= n.
Proof.
(*...*)
Admitted.
Goal forall n k, k < mu n -> f k = false.
Proof.
(*...*)
Admitted.
Goal forall n, mu n < n -> f (mu n) = true.
Proof.
(*...*)
Admitted.
End S2.
Section S3.
Variables (f: nat -> bool) (mu: nat -> nat).
Variables (R1: forall n, mu n <= n)
(R2: forall n k, k < mu n -> f k = false)
(R3: forall n, mu n < n -> f (mu n) = true).
Goal mu 0 = 0.
Proof.
(*...*)
Admitted.
Goal forall n, mu (S n) = if f (mu n) then mu n else S n.
Proof.
(*...*)
Admitted.
End S3.
(*** Exercise 9.12 ***)
Section Challenge.
Variable D M : nat -> nat -> nat.
Hypothesis DM1 : forall x y, x = D x y * S y + M x y.
Hypothesis DM2 : forall x y, M x y <= y.
Goal forall x y, y < x -> D x y = S (D (x - S y) y).
Proof.
(*...*)
Admitted.
Goal forall x y, x <= y -> D x y = 0.
Proof.
(*...*)
Admitted.
End Challenge.
|
# Árvore de decisão: o aprendizado de máquina presente no computador de classificação de rochas
<h1>Sumário da apresentação<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Introdução" data-toc-modified-id="Introdução-1">Introdução</a></span></li><li><span><a href="#Metodologia" data-toc-modified-id="Metodologia-2">Metodologia</a></span></li><li><span><a href="#Importando-as-dependências-necessárias" data-toc-modified-id="Importando-as-dependências-necessárias-3">Importando as dependências necessárias</a></span></li><li><span><a href="#Criando-o-seu-dado-(Tabela-de-Frequências):" data-toc-modified-id="Criando-o-seu-dado-(Tabela-de-Frequências):-4">Criando o seu dado (Tabela de Frequências):</a></span></li><li><span><a href="#Transformando-o-seu-dado-em-um-objeto-do-pandas" data-toc-modified-id="Transformando-o-seu-dado-em-um-objeto-do-pandas-5">Transformando o seu dado em um objeto do pandas</a></span></li></ul></div>
## Introdução
* Árvores de decisão são metaheurísticas dentro do campo da inteligência artificial que têm sido amplamente utilizadas para construir modelos de classificação, pois esses modelos se assemelham muito ao raciocínio humano sendo fáceis de entender.
* O algoritmo é estruturado como uma série modelos sequenciais, que combinam logicamenteum conjunto de testes simples, onde cada teste compara um atributo numérico com um valor limite ou um atributo nominal com um conjunto de valores possíveis \cite{Kotsiantis2013}.
## Metodologia
* O algoritmo de árvore de decisão \cite{sklearn_api} é proposto para a solução de um problema de classificação de rochas simples do tipo binária\cite{scikit-learn}.
* Classificação do tipo binária baseia-se em dois aspectos principais a entropia e o ganho de informação \cite{Sayad2020}. O ganho de informação ou divergência \textit{Kullback–Leibler} é a diferença das entropia nas iterações i e i+1. Onde
$$ i = 0,1,2,3 ..., n \ \forall \ n \in \mathbb{I} $$
* A entropia pode ser definida com base na tabela de frequências que carrega as informações do seu dado. Quando a tabela de frequencia possui dois atributos a entropia pode ser escrita como:
\begin{equation}
E(t,x) = \sum_{c \in x} P(c)E(c)
\end{equation}
Existe uma variação da árvore de decião que utiliza a rega de bayes sendo conhecia como árvore de decisão bayesiana.
O teorema de bayes e uma igualdade simples que afirma $prob(A \ e \ B) = prob(B \ e\ A)$ :
\begin{equation}
P(B|A) = \frac{prob(A|B) prob(B)}{prob(A)} \nonumber
\end{equation}
Onde
* $prob(A)$ probabilidade total
* $prob(B)$ é chamado de probabilidade a priori a qual será modificada pela experiência
* $prob(A|B)$ é a verossimilança que determina a experiência
* $prob(B|A)$ é a probabilidade posterior, ou o nível de crença após a realização do experimento
Esse teorema é útil quando interpretado como uma regra para indução: os dados e o evento A são considerados como sucessores de B, o grau de crença anterior a realização do experimento.
## Importando as dependências necessárias
```python
# -*- coding: utf-8 -*-
%matplotlib inline
import pandas as pd # biblioteca que trabalha com tabela de dados
from sklearn import tree # modelo de árvore de decisão do Sci-kit
from IPython.display import Image # pacote que carrega imagens
from PIL import Image, ImageFilter # pacote que processa imagens
```
## Criando o seu dado (Tabela de Frequências):
```python
features = [[140, 1], [130, 1],
[150, 0], [170, 0]]# diâmetro e gomos
labels = [0, 0, 1, 1] # 0 é maçã e 1 é laranja
```
## Transformando o seu dado em um objeto do pandas
```python
Tabela = {'diâmetro': [140, 130, 150, 170],
'gomo': [1, 1, 0 ,0 ],
'frutas': [0, 0, 1, 1]
}
TF = pd.DataFrame(data=Tabela)
print(TF)
```
diâmetro gomo frutas
0 140 1 0
1 130 1 0
2 150 0 1
3 170 0 1
```python
# o classificador encontra padrões nos dados de treinamento
clf = tree.DecisionTreeClassifier() # instância do classificador
clf = clf.fit(features, labels) # fit encontra padrões nos dados
# iremos utilizar para classificar uma nova fruta
print(clf.predict([[9, 0]]))
```
[0]
# No caso do computador classificador de rochas ...
[Chaves classificadoras](imagens/perguntas.pdf)
```python
im = Image.open( 'imagens/perguntas.png' )
im.show()
```
```python
# no caso classificação de rochas (Banco de rochas):
nr = 15 # número total de rochas do treinamento
BD = {'Possui cristais?': [1,1,1,1,1,0,0,0,0,0,0,0,0,0,0],
'Possui camadas?' : [1,1,0,0,0],
'As camadas possuem materiais diferentes:': [1,0]
}
rochas = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] # Ids de rochas
```
# References
(<a id="cit-Kotsiantis2013" href="#call-Kotsiantis2013">Kotsiantis, 2013</a>) Kotsiantis S. B., ``_Decision trees: a recent overview_'', Artificial Intelligence Review, vol. 39, number 4, pp. 261--283, Apr 2013. [online](https://doi.org/10.1007/s10462-011-9272-4)
(<a id="cit-sklearn_api" href="#call-sklearn_api">Buitinck, Louppe <em>et al.</em>, 2013</a>) L. Buitinck, G. Louppe, M. Blondel <em>et al.</em>, ``_API design for machine learning software: experiences from the scikit-learn
project_'', ECML PKDD Workshop: Languages for Data Mining and Machine Learning, 2013.
(<a id="cit-scikit-learn" href="#call-scikit-learn">Pedregosa, Varoquaux <em>et al.</em>, 2011</a>) Pedregosa F., Varoquaux G., Gramfort A. <em>et al.</em>, ``_Scikit-learn: Machine Learning in Python_'', Journal of Machine Learning Research, vol. 12, number , pp. 2825--2830, 2011.
(<a id="cit-Sayad2020" href="#call-Sayad2020">Saed, 2020</a>) Dr. Saed, ``_An Introduction to Data Science: Decision Tree_'', 2020. [online](https://www.saedsayad.com/data_mining_map.htm)
```python
```
|
(*
Copyright 2018
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
theory multitasking_init_opt_mem
imports tasks_opt
begin
text \<open>Up to two locales per function in the binary.\<close>
locale multitasking_init_function = tasks_opt_context +
fixes rsp\<^sub>0 rbp\<^sub>0 a multitasking_init_opt_ret :: \<open>64 word\<close>
and v\<^sub>0 :: \<open>8 word\<close>
and blocks :: \<open>(nat \<times> 64 word \<times> nat) set\<close>
assumes seps: \<open>seps blocks\<close>
and masters:
\<open>master blocks (a, 1) 0\<close>
\<open>master blocks (rsp\<^sub>0, 8) 1\<close>
and ret_address: \<open>outside multitasking_init_opt_ret 500 556\<close> \<comment> \<open>Only works for non-recursive functions.\<close>
begin
text \<open>
The Floyd invariant expresses for some locations properties that are invariably true.
Simply expresses that a byte in the memory remains untouched.
\<close>
definition pp_\<Theta> :: floyd_invar where
\<open>pp_\<Theta> \<equiv> [
\<comment> \<open>precondition\<close>
boffset+500 \<mapsto> \<lambda>\<sigma>. regs \<sigma> rsp = rsp\<^sub>0
\<and> regs \<sigma> rbp = rbp\<^sub>0
\<and> \<sigma> \<turnstile> *[rsp\<^sub>0,8] = boffset+multitasking_init_opt_ret
\<and> \<sigma> \<turnstile> *[a,1] = v\<^sub>0,
boffset+555 \<mapsto> \<lambda>\<sigma>. regs \<sigma> rsp = rsp\<^sub>0+0
\<and> regs \<sigma> rbp = rbp\<^sub>0+0
\<and> \<sigma> \<turnstile> *[rsp\<^sub>0,8] = boffset+multitasking_init_opt_ret
\<and> \<sigma> \<turnstile> *[a,1] = v\<^sub>0,
\<comment> \<open>postcondition\<close>
boffset+multitasking_init_opt_ret \<mapsto> \<lambda>\<sigma>. \<sigma> \<turnstile> *[a,1] = v\<^sub>0
\<and> regs \<sigma> rsp = rsp\<^sub>0+8
\<^cancel>\<open>\<and> regs \<sigma> rbp = rbp\<^sub>0\<close> \<comment> \<open>TODO: work in flow-through of rbp0 as necessary (such as when pushed, etc.)\<close>
]\<close>
text \<open>Adding some rules to the simplifier to simplify proofs.\<close>
schematic_goal pp_\<Theta>_zero[simp]:
\<open>pp_\<Theta> boffset = ?x\<close>
unfolding pp_\<Theta>_def
by simp
schematic_goal pp_\<Theta>_numeral_l[simp]:
\<open>pp_\<Theta> (n + boffset) = ?x\<close>
unfolding pp_\<Theta>_def
by simp
schematic_goal pp_\<Theta>_numeral_r[simp]:
\<open>pp_\<Theta> (boffset + n) = ?x\<close>
unfolding pp_\<Theta>_def
by simp
lemma rewrite_multitasking_init_opt_mem:
\<open>is_std_invar multitasking_init_opt_ret (floyd.invar multitasking_init_opt_ret pp_\<Theta>)\<close>
text \<open>Boilerplate code to start the VCG\<close>
apply (rule floyd_invarI)
apply (rewrite at \<open>floyd_vcs multitasking_init_opt_ret \<hole> _\<close> pp_\<Theta>_def)
apply (intro floyd_vcsI)
text \<open>Subgoal for rip = boffset+500\<close>
subgoal premises prems for \<sigma>
text \<open>Insert relevant knowledge\<close>
apply (insert prems seps ret_address)
text \<open>Apply VCG/symb.\ execution\<close>
apply (restart_symbolic_execution?, (symbolic_execution masters: masters)+, (finish_symbolic_execution masters: masters)?)+
done
text \<open>Subgoal for rip = boffset+555\<close>
subgoal premises prems for \<sigma>
text \<open>Insert relevant knowledge\<close>
apply (insert prems seps ret_address)
text \<open>Apply VCG/symb.\ execution\<close>
apply (restart_symbolic_execution?, (symbolic_execution masters: masters)+, (finish_symbolic_execution masters: masters)?)+
done
text \<open>Trivial ending subgoal.\<close>
subgoal
by simp
done
end
end
|
/-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro
-/
import Std.Data.Nat.Lemmas
/-!
# Definitions and properties of `gcd`, `lcm`, and `coprime`
-/
namespace Nat
theorem gcd_rec (m n : Nat) : gcd m n = gcd (n % m) m :=
match m with
| 0 => by have := (mod_zero n).symm; rwa [gcd_zero_right]
| _ + 1 => by simp [gcd_succ]
@[elab_as_elim] theorem gcd.induction {P : Nat → Nat → Prop} (m n : Nat)
(H0 : ∀n, P 0 n) (H1 : ∀ m n, 0 < m → P (n % m) m → P m n) : P m n :=
Nat.strongInductionOn (motive := fun m => ∀ n, P m n) m
(fun
| 0, _ => H0
| _+1, IH => fun _ => H1 _ _ (succ_pos _) (IH _ (mod_lt _ (succ_pos _)) _) )
n
/-- The least common multiple of `m` and `n`, defined using `gcd`. -/
def lcm (m n : Nat) : Nat := m * n / gcd m n
/-- `m` and `n` are coprime, or relatively prime, if their `gcd` is 1. -/
@[reducible] def coprime (m n : Nat) : Prop := gcd m n = 1
---
theorem gcd_dvd (m n : Nat) : (gcd m n ∣ m) ∧ (gcd m n ∣ n) := by
induction m, n using gcd.induction with
| H0 n => rw [gcd_zero_left]; exact ⟨Nat.dvd_zero n, Nat.dvd_refl n⟩
| H1 m n _ IH => rw [← gcd_rec] at IH; exact ⟨IH.2, (dvd_mod_iff IH.2).1 IH.1⟩
theorem gcd_dvd_left (m n : Nat) : gcd m n ∣ m := (gcd_dvd m n).left
theorem gcd_dvd_right (m n : Nat) : gcd m n ∣ n := (gcd_dvd m n).right
theorem gcd_le_left (n) (h : 0 < m) : gcd m n ≤ m := le_of_dvd h <| gcd_dvd_left m n
theorem gcd_le_right (n) (h : 0 < n) : gcd m n ≤ n := le_of_dvd h <| gcd_dvd_right m n
theorem dvd_gcd : k ∣ m → k ∣ n → k ∣ gcd m n := by
induction m, n using gcd.induction with intro km kn
| H0 n => rw [gcd_zero_left]; exact kn
| H1 n m _ IH => rw [gcd_rec]; exact IH ((dvd_mod_iff km).2 kn) km
theorem dvd_gcd_iff : k ∣ gcd m n ↔ k ∣ m ∧ k ∣ n :=
⟨fun h => let ⟨h₁, h₂⟩ := gcd_dvd m n; ⟨Nat.dvd_trans h h₁, Nat.dvd_trans h h₂⟩,
fun ⟨h₁, h₂⟩ => dvd_gcd h₁ h₂⟩
theorem gcd_comm (m n : Nat) : gcd m n = gcd n m :=
dvd_antisymm
(dvd_gcd (gcd_dvd_right m n) (gcd_dvd_left m n))
(dvd_gcd (gcd_dvd_right n m) (gcd_dvd_left n m))
theorem gcd_eq_left_iff_dvd : m ∣ n ↔ gcd m n = m :=
⟨fun h => by rw [gcd_rec, mod_eq_zero_of_dvd h, gcd_zero_left],
fun h => h ▸ gcd_dvd_right m n⟩
theorem gcd_eq_right_iff_dvd : m ∣ n ↔ gcd n m = m := by
rw [gcd_comm]; exact gcd_eq_left_iff_dvd
theorem gcd_assoc (m n k : Nat) : gcd (gcd m n) k = gcd m (gcd n k) :=
dvd_antisymm
(dvd_gcd
(Nat.dvd_trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n))
(dvd_gcd (Nat.dvd_trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n))
(gcd_dvd_right (gcd m n) k)))
(dvd_gcd
(dvd_gcd (gcd_dvd_left m (gcd n k))
(Nat.dvd_trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k)))
(Nat.dvd_trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k)))
@[simp] theorem gcd_one_right (n : Nat) : gcd n 1 = 1 := (gcd_comm n 1).trans (gcd_one_left n)
theorem gcd_mul_left (m n k : Nat) : gcd (m * n) (m * k) = m * gcd n k := by
induction n, k using gcd.induction with
| H0 k => simp
| H1 n k _ IH => rwa [← mul_mod_mul_left, ← gcd_rec, ← gcd_rec] at IH
theorem gcd_mul_right (m n k : Nat) : gcd (m * n) (k * n) = gcd m k * n := by
rw [Nat.mul_comm m n, Nat.mul_comm k n, Nat.mul_comm (gcd m k) n, gcd_mul_left]
theorem gcd_pos_of_pos_left {m : Nat} (n : Nat) (mpos : 0 < m) : 0 < gcd m n :=
pos_of_dvd_of_pos (gcd_dvd_left m n) mpos
theorem gcd_pos_of_pos_right (m : Nat) {n : Nat} (npos : 0 < n) : 0 < gcd m n :=
pos_of_dvd_of_pos (gcd_dvd_right m n) npos
theorem div_gcd_pos_of_pos_left (b : Nat) (h : 0 < a) : 0 < a / a.gcd b :=
(Nat.le_div_iff_mul_le <| Nat.gcd_pos_of_pos_left _ h).2 (Nat.one_mul _ ▸ Nat.gcd_le_left _ h)
theorem div_gcd_pos_of_pos_right (a : Nat) (h : 0 < b) : 0 < b / a.gcd b :=
(Nat.le_div_iff_mul_le <| Nat.gcd_pos_of_pos_right _ h).2 (Nat.one_mul _ ▸ Nat.gcd_le_right _ h)
theorem eq_zero_of_gcd_eq_zero_left {m n : Nat} (H : gcd m n = 0) : m = 0 :=
match eq_zero_or_pos m with
| .inl H0 => H0
| .inr H1 => absurd (Eq.symm H) (ne_of_lt (gcd_pos_of_pos_left _ H1))
theorem eq_zero_of_gcd_eq_zero_right {m n : Nat} (H : gcd m n = 0) : n = 0 := by
rw [gcd_comm] at H
exact eq_zero_of_gcd_eq_zero_left H
theorem gcd_ne_zero_left : m ≠ 0 → gcd m n ≠ 0 := mt eq_zero_of_gcd_eq_zero_left
theorem gcd_ne_zero_right : n ≠ 0 → gcd m n ≠ 0 := mt eq_zero_of_gcd_eq_zero_right
theorem gcd_div {m n k : Nat} (H1 : k ∣ m) (H2 : k ∣ n) :
gcd (m / k) (n / k) = gcd m n / k :=
match eq_zero_or_pos k with
| .inl H0 => by simp [H0]
| .inr H3 => by
apply Nat.eq_of_mul_eq_mul_right H3
rw [Nat.div_mul_cancel (dvd_gcd H1 H2), ← gcd_mul_right,
Nat.div_mul_cancel H1, Nat.div_mul_cancel H2]
theorem gcd_dvd_gcd_of_dvd_left {m k : Nat} (n : Nat) (H : m ∣ k) : gcd m n ∣ gcd k n :=
dvd_gcd (Nat.dvd_trans (gcd_dvd_left m n) H) (gcd_dvd_right m n)
theorem gcd_dvd_gcd_of_dvd_right {m k : Nat} (n : Nat) (H : m ∣ k) : gcd n m ∣ gcd n k :=
dvd_gcd (gcd_dvd_left n m) (Nat.dvd_trans (gcd_dvd_right n m) H)
theorem gcd_dvd_gcd_mul_left (m n k : Nat) : gcd m n ∣ gcd (k * m) n :=
gcd_dvd_gcd_of_dvd_left _ (Nat.dvd_mul_left _ _)
theorem gcd_dvd_gcd_mul_right (m n k : Nat) : gcd m n ∣ gcd (m * k) n :=
gcd_dvd_gcd_of_dvd_left _ (Nat.dvd_mul_right _ _)
theorem gcd_dvd_gcd_mul_left_right (m n k : Nat) : gcd m n ∣ gcd m (k * n) :=
gcd_dvd_gcd_of_dvd_right _ (Nat.dvd_mul_left _ _)
theorem gcd_dvd_gcd_mul_right_right (m n k : Nat) : gcd m n ∣ gcd m (n * k) :=
gcd_dvd_gcd_of_dvd_right _ (Nat.dvd_mul_right _ _)
theorem gcd_eq_left {m n : Nat} (H : m ∣ n) : gcd m n = m :=
dvd_antisymm (gcd_dvd_left _ _) (dvd_gcd (Nat.dvd_refl _) H)
theorem gcd_eq_right {m n : Nat} (H : n ∣ m) : gcd m n = n := by
rw [gcd_comm, gcd_eq_left H]
@[simp] theorem gcd_mul_left_left (m n : Nat) : gcd (m * n) n = n :=
dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (Nat.dvd_mul_left _ _) (Nat.dvd_refl _))
@[simp] theorem gcd_mul_left_right (m n : Nat) : gcd n (m * n) = n := by
rw [gcd_comm, gcd_mul_left_left]
@[simp] theorem gcd_mul_right_left (m n : Nat) : gcd (n * m) n = n := by
rw [Nat.mul_comm, gcd_mul_left_left]
@[simp] theorem gcd_mul_right_right (m n : Nat) : gcd n (n * m) = n := by
rw [gcd_comm, gcd_mul_right_left]
@[simp] theorem gcd_gcd_self_right_left (m n : Nat) : gcd m (gcd m n) = gcd m n :=
dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (gcd_dvd_left _ _) (Nat.dvd_refl _))
@[simp] theorem gcd_gcd_self_right_right (m n : Nat) : gcd m (gcd n m) = gcd n m := by
rw [gcd_comm n m, gcd_gcd_self_right_left]
@[simp] theorem gcd_gcd_self_left_right (m n : Nat) : gcd (gcd n m) m = gcd n m := by
rw [gcd_comm, gcd_gcd_self_right_right]
@[simp] theorem gcd_gcd_self_left_left (m n : Nat) : gcd (gcd m n) m = gcd m n := by
rw [gcd_comm m n, gcd_gcd_self_left_right]
theorem gcd_add_mul_self (m n k : Nat) : gcd m (n + k * m) = gcd m n := by
simp [gcd_rec m (n + k * m), gcd_rec m n]
theorem gcd_eq_zero_iff {i j : Nat} : gcd i j = 0 ↔ i = 0 ∧ j = 0 :=
⟨fun h => ⟨eq_zero_of_gcd_eq_zero_left h, eq_zero_of_gcd_eq_zero_right h⟩,
fun h => by simp [h]⟩
/-! ### `lcm` -/
theorem lcm_comm (m n : Nat) : lcm m n = lcm n m := by
rw [lcm, lcm, Nat.mul_comm n m, gcd_comm n m]
@[simp] theorem lcm_zero_left (m : Nat) : lcm 0 m = 0 := by simp [lcm]
@[simp] theorem lcm_zero_right (m : Nat) : lcm m 0 = 0 := by simp [lcm]
@[simp] theorem lcm_one_left (m : Nat) : lcm 1 m = m := by simp [lcm]
@[simp] theorem lcm_one_right (m : Nat) : lcm m 1 = m := by simp [lcm]
@[simp] theorem lcm_self (m : Nat) : lcm m m = m := by
match eq_zero_or_pos m with
| .inl h => rw [h, lcm_zero_left]
| .inr h => simp [lcm, Nat.mul_div_cancel _ h]
theorem dvd_lcm_left (m n : Nat) : m ∣ lcm m n :=
⟨n / gcd m n, by rw [← Nat.mul_div_assoc m (Nat.gcd_dvd_right m n)]; rfl⟩
theorem dvd_lcm_right (m n : Nat) : n ∣ lcm m n := lcm_comm n m ▸ dvd_lcm_left n m
theorem gcd_mul_lcm (m n : Nat) : gcd m n * lcm m n = m * n := by
rw [lcm, Nat.mul_div_cancel' (Nat.dvd_trans (gcd_dvd_left m n) (Nat.dvd_mul_right m n))]
theorem lcm_dvd {m n k : Nat} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k := by
match eq_zero_or_pos k with
| .inl h => rw [h]; exact Nat.dvd_zero _
| .inr kpos =>
apply Nat.dvd_of_mul_dvd_mul_left (gcd_pos_of_pos_left n (pos_of_dvd_of_pos H1 kpos))
rw [gcd_mul_lcm, ← gcd_mul_right, Nat.mul_comm n k]
exact dvd_gcd (Nat.mul_dvd_mul_left _ H2) (Nat.mul_dvd_mul_right H1 _)
theorem lcm_assoc (m n k : Nat) : lcm (lcm m n) k = lcm m (lcm n k) :=
dvd_antisymm
(lcm_dvd
(lcm_dvd (dvd_lcm_left m (lcm n k)) (Nat.dvd_trans (dvd_lcm_left n k) (dvd_lcm_right m (lcm n k))))
(Nat.dvd_trans (dvd_lcm_right n k) (dvd_lcm_right m (lcm n k))))
(lcm_dvd
(Nat.dvd_trans (dvd_lcm_left m n) (dvd_lcm_left (lcm m n) k))
(lcm_dvd (Nat.dvd_trans (dvd_lcm_right m n) (dvd_lcm_left (lcm m n) k))
(dvd_lcm_right (lcm m n) k)))
theorem lcm_ne_zero (hm : m ≠ 0) (hn : n ≠ 0) : lcm m n ≠ 0 := by
intro h
have h1 := gcd_mul_lcm m n
rw [h, Nat.mul_zero] at h1
match mul_eq_zero.1 h1.symm with
| .inl hm1 => exact hm hm1
| .inr hn1 => exact hn hn1
/-!
### `coprime`
See also `nat.coprime_of_dvd` and `nat.coprime_of_dvd'` to prove `nat.coprime m n`.
-/
instance (m n : Nat) : Decidable (coprime m n) := inferInstanceAs (Decidable (_ = 1))
theorem coprime_iff_gcd_eq_one : coprime m n ↔ gcd m n = 1 := .rfl
theorem coprime.gcd_eq_one : coprime m n → gcd m n = 1 := id
theorem coprime.symm : coprime n m → coprime m n := (gcd_comm m n).trans
theorem coprime_comm : coprime n m ↔ coprime m n := ⟨coprime.symm, coprime.symm⟩
theorem coprime.dvd_of_dvd_mul_right (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m := by
let t := dvd_gcd (Nat.dvd_mul_left k m) H2
rwa [gcd_mul_left, H1.gcd_eq_one, Nat.mul_one] at t
theorem coprime.dvd_of_dvd_mul_left (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n :=
H1.dvd_of_dvd_mul_right (by rwa [Nat.mul_comm])
theorem coprime.gcd_mul_left_cancel (m : Nat) (H : coprime k n) : gcd (k * m) n = gcd m n :=
have H1 : coprime (gcd (k * m) n) k := by
rw [coprime, Nat.gcd_assoc, H.symm.gcd_eq_one, gcd_one_right]
dvd_antisymm
(dvd_gcd (H1.dvd_of_dvd_mul_left (gcd_dvd_left _ _)) (gcd_dvd_right _ _))
(gcd_dvd_gcd_mul_left _ _ _)
theorem coprime.gcd_mul_right_cancel (m : Nat) (H : coprime k n) : gcd (m * k) n = gcd m n := by
rw [Nat.mul_comm m k, H.gcd_mul_left_cancel m]
theorem coprime.gcd_mul_left_cancel_right (n : Nat)
(H : coprime k m) : gcd m (k * n) = gcd m n := by
rw [gcd_comm m n, gcd_comm m (k * n), H.gcd_mul_left_cancel n]
theorem coprime.gcd_mul_right_cancel_right (n : Nat)
(H : coprime k m) : gcd m (n * k) = gcd m n := by
rw [Nat.mul_comm n k, H.gcd_mul_left_cancel_right n]
theorem coprime_div_gcd_div_gcd
(H : 0 < gcd m n) : coprime (m / gcd m n) (n / gcd m n) := by
rw [coprime_iff_gcd_eq_one, gcd_div (gcd_dvd_left m n) (gcd_dvd_right m n), Nat.div_self H]
theorem not_coprime_of_dvd_of_dvd (dgt1 : 1 < d) (Hm : d ∣ m) (Hn : d ∣ n) : ¬ coprime m n :=
fun co => Nat.not_le_of_gt dgt1 <| Nat.le_of_dvd Nat.zero_lt_one <| by
rw [← co.gcd_eq_one]; exact dvd_gcd Hm Hn
theorem exists_coprime (H : 0 < gcd m n) :
∃ m' n', coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n :=
⟨_, _, coprime_div_gcd_div_gcd H,
(Nat.div_mul_cancel (gcd_dvd_left m n)).symm,
(Nat.div_mul_cancel (gcd_dvd_right m n)).symm⟩
theorem exists_coprime' (H : 0 < gcd m n) :
∃ g m' n', 0 < g ∧ coprime m' n' ∧ m = m' * g ∧ n = n' * g :=
let ⟨m', n', h⟩ := exists_coprime H; ⟨_, m', n', H, h⟩
theorem coprime.mul (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k :=
(H1.gcd_mul_left_cancel n).trans H2
theorem coprime.mul_right (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) :=
(H1.symm.mul H2.symm).symm
theorem coprime.coprime_dvd_left (H1 : m ∣ k) (H2 : coprime k n) : coprime m n := by
apply eq_one_of_dvd_one
rw [coprime] at H2
have := Nat.gcd_dvd_gcd_of_dvd_left n H1
rwa [← H2]
theorem coprime.coprime_dvd_right (H1 : n ∣ m) (H2 : coprime k m) : coprime k n :=
(H2.symm.coprime_dvd_left H1).symm
theorem coprime.coprime_mul_left (H : coprime (k * m) n) : coprime m n :=
H.coprime_dvd_left (Nat.dvd_mul_left _ _)
theorem coprime.coprime_mul_right (H : coprime (m * k) n) : coprime m n :=
H.coprime_dvd_left (Nat.dvd_mul_right _ _)
theorem coprime.coprime_mul_left_right (H : coprime m (k * n)) : coprime m n :=
H.coprime_dvd_right (Nat.dvd_mul_left _ _)
theorem coprime.coprime_mul_right_right (H : coprime m (n * k)) : coprime m n :=
H.coprime_dvd_right (Nat.dvd_mul_right _ _)
theorem coprime.coprime_div_left (cmn : coprime m n) (dvd : a ∣ m) : coprime (m / a) n := by
match eq_zero_or_pos a with
| .inl h0 =>
rw [h0] at dvd
rw [Nat.eq_zero_of_zero_dvd dvd] at cmn ⊢
simp; assumption
| .inr hpos =>
let ⟨k, hk⟩ := dvd
rw [hk, Nat.mul_div_cancel_left _ hpos]
rw [hk] at cmn
exact cmn.coprime_mul_left
theorem coprime.coprime_div_right (cmn : coprime m n) (dvd : a ∣ n) : coprime m (n / a) :=
(cmn.symm.coprime_div_left dvd).symm
theorem coprime_mul_iff_left : coprime (m * n) k ↔ coprime m k ∧ coprime n k :=
⟨fun h => ⟨h.coprime_mul_right, h.coprime_mul_left⟩,
fun ⟨h, _⟩ => by rwa [coprime_iff_gcd_eq_one, h.gcd_mul_left_cancel n]⟩
theorem coprime_mul_iff_right : coprime k (m * n) ↔ coprime k m ∧ coprime k n := by
rw [@coprime_comm k, @coprime_comm k, @coprime_comm k, coprime_mul_iff_left]
theorem coprime.gcd_left (k : Nat) (hmn : coprime m n) : coprime (gcd k m) n :=
hmn.coprime_dvd_left <| gcd_dvd_right k m
theorem coprime.gcd_right (k : Nat) (hmn : coprime m n) : coprime m (gcd k n) :=
hmn.coprime_dvd_right <| gcd_dvd_right k n
theorem coprime.gcd_both (k l : Nat) (hmn : coprime m n) : coprime (gcd k m) (gcd l n) :=
(hmn.gcd_left k).gcd_right l
theorem coprime.mul_dvd_of_dvd_of_dvd (hmn : coprime m n) (hm : m ∣ a) (hn : n ∣ a) : m * n ∣ a :=
let ⟨_, hk⟩ := hm
hk.symm ▸ Nat.mul_dvd_mul_left _ (hmn.symm.dvd_of_dvd_mul_left (hk ▸ hn))
@[simp]
@[simp] theorem coprime_zero_right (n : Nat) : coprime n 0 ↔ n = 1 := by simp [coprime]
theorem coprime_one_left : ∀ n, coprime 1 n := gcd_one_left
theorem coprime_one_right : ∀ n, coprime n 1 := gcd_one_right
@[simp] theorem coprime_one_left_eq_true (n) : coprime 1 n = True := eq_true (coprime_one_left _)
@[simp] theorem coprime_one_right_eq_true (n) : coprime n 1 = True := eq_true (coprime_one_right _)
@[simp] theorem coprime_self (n : Nat) : coprime n n ↔ n = 1 := by simp [coprime]
theorem coprime.pow_left (n : Nat) (H1 : coprime m k) : coprime (m ^ n) k := by
induction n with
| zero => exact coprime_one_left _
| succ n ih => have hm := H1.mul ih; rwa [Nat.pow_succ, Nat.mul_comm]
theorem coprime.pow_right (n : Nat) (H1 : coprime k m) : coprime k (m ^ n) :=
(H1.symm.pow_left n).symm
theorem coprime.pow {k l : Nat} (m n : Nat) (H1 : coprime k l) : coprime (k ^ m) (l ^ n) :=
(H1.pow_left _).pow_right _
theorem coprime.eq_one_of_dvd {k m : Nat} (H : coprime k m) (d : k ∣ m) : k = 1 := by
rw [← H.gcd_eq_one, gcd_eq_left d]
/-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. -/
def prod_dvd_and_dvd_of_dvd_prod {k m n : Nat} (H : k ∣ m * n) :
{d : {m' // m' ∣ m} × {n' // n' ∣ n} // k = d.1.val * d.2.val} :=
if h0 : gcd k m = 0 then
⟨⟨⟨0, eq_zero_of_gcd_eq_zero_right h0 ▸ Nat.dvd_refl 0⟩,
⟨n, Nat.dvd_refl n⟩⟩,
eq_zero_of_gcd_eq_zero_left h0 ▸ (Nat.zero_mul n).symm⟩
else by
have hd : gcd k m * (k / gcd k m) = k := Nat.mul_div_cancel' (gcd_dvd_left k m)
refine ⟨⟨⟨gcd k m, gcd_dvd_right k m⟩, ⟨k / gcd k m, ?_⟩⟩, hd.symm⟩
apply Nat.dvd_of_mul_dvd_mul_left (Nat.pos_of_ne_zero h0)
rw [hd, ← gcd_mul_right]
exact Nat.dvd_gcd (Nat.dvd_mul_right _ _) H
theorem gcd_mul_dvd_mul_gcd (k m n : Nat) : gcd k (m * n) ∣ gcd k m * gcd k n := by
let ⟨⟨⟨m', hm'⟩, ⟨n', hn'⟩⟩, (h : gcd k (m * n) = m' * n')⟩ :=
prod_dvd_and_dvd_of_dvd_prod <| gcd_dvd_right k (m * n)
rw [h]
have h' : m' * n' ∣ k := h ▸ gcd_dvd_left ..
exact Nat.mul_dvd_mul
(dvd_gcd (Nat.dvd_trans (Nat.dvd_mul_right m' n') h') hm')
(dvd_gcd (Nat.dvd_trans (Nat.dvd_mul_left n' m') h') hn')
theorem coprime.gcd_mul (k : Nat) (h : coprime m n) : gcd k (m * n) = gcd k m * gcd k n :=
dvd_antisymm
(gcd_mul_dvd_mul_gcd k m n)
((h.gcd_both k k).mul_dvd_of_dvd_of_dvd
(gcd_dvd_gcd_mul_right_right ..)
(gcd_dvd_gcd_mul_left_right ..))
theorem gcd_mul_gcd_of_coprime_of_mul_eq_mul
(cop : coprime c d) (h : a * b = c * d) : a.gcd c * b.gcd c = c := by
apply dvd_antisymm
· apply ((cop.gcd_left _).mul (cop.gcd_left _)).dvd_of_dvd_mul_right
rw [← h]
apply Nat.mul_dvd_mul (gcd_dvd ..).1 (gcd_dvd ..).1
· rw [gcd_comm a, gcd_comm b]
refine Nat.dvd_trans ?_ (gcd_mul_dvd_mul_gcd ..)
rw [h, gcd_mul_right_right d c]; apply Nat.dvd_refl
|
import torch
import numpy as np
def xavier_initialier(module, magnitude=3, rnd_type='uniform', factor_type='avg'):
"""
Xavier initializer,
Valid factor_type: 'avg', 'in', 'out'
Valid rnd_type: 'uniform', 'gaussian'
"""
# initialize the rest with Xavier
# reference: https://github.com/dmlc/mxnet/blob/master/python/mxnet/initializer.py
if module.bias is not None:
module.bias.data.zero_()
shape = module.weight.size()
hw_scale = 1.
if len(shape) > 2:
hw_scale = np.prod(shape[2:])
try:
fan_in, fan_out = shape[1] * hw_scale, shape[0] * hw_scale
except:
raise ValueError("Strange shape {} of module {}".format(shape, module))
factor = 1
if factor_type == "avg":
factor = (fan_in + fan_out) / 2.0
elif factor_type == "in":
factor = fan_in
elif factor_type == "out":
factor = fan_out
else:
raise ValueError("Incorrect factor type")
scale = np.sqrt(magnitude / factor)
if rnd_type == 'uniform':
module.weight.data.uniform_(-scale, scale)
elif rnd_type == 'gaussian':
module.weight.data.normal_(0, scale)
else:
raise ValueError("Incorrect rnd type! Weight not initialized.")
def fixmag_initialier(data, magnitude=3, rnd_type='gaussian'):
"""
Directly specify the magnitude
Valid factor_type: 'avg', 'in', 'out'
Valid rnd_type: 'uniform', 'gaussian'
"""
if rnd_type == 'uniform':
data.uniform_(-magnitude, magnitude)
elif rnd_type == 'gaussian':
data.normal_(0, magnitude)
else:
raise ValueError("Incorrect rnd type! Weight not initialized.")
|
/-
Copyright (c) 2021 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying, Rémy Degenne
! This file was ported from Lean 3 source module probability.process.adapted
! 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.Probability.Process.Filtration
import Mathbin.Topology.Instances.Discrete
/-!
# Adapted and progressively measurable processes
This file defines some standard definition from the theory of stochastic processes including
filtrations and stopping times. These definitions are used to model the amount of information
at a specific time and are the first step in formalizing stochastic processes.
## Main definitions
* `measure_theory.adapted`: a sequence of functions `u` is said to be adapted to a
filtration `f` if at each point in time `i`, `u i` is `f i`-strongly measurable
* `measure_theory.prog_measurable`: a sequence of functions `u` is said to be progressively
measurable with respect to a filtration `f` if at each point in time `i`, `u` restricted to
`set.Iic i × Ω` is strongly measurable with respect to the product `measurable_space` structure
where the σ-algebra used for `Ω` is `f i`.
## Main results
* `adapted.prog_measurable_of_continuous`: a continuous adapted process is progressively measurable.
## Tags
adapted, progressively measurable
-/
open Filter Order TopologicalSpace
open Classical MeasureTheory NNReal ENNReal Topology BigOperators
namespace MeasureTheory
variable {Ω β ι : Type _} {m : MeasurableSpace Ω} [TopologicalSpace β] [Preorder ι]
{u v : ι → Ω → β} {f : Filtration ι m}
/-- A sequence of functions `u` is adapted to a filtration `f` if for all `i`,
`u i` is `f i`-measurable. -/
def Adapted (f : Filtration ι m) (u : ι → Ω → β) : Prop :=
∀ i : ι, strongly_measurable[f i] (u i)
#align measure_theory.adapted MeasureTheory.Adapted
namespace Adapted
@[protected, to_additive]
theorem mul [Mul β] [ContinuousMul β] (hu : Adapted f u) (hv : Adapted f v) : Adapted f (u * v) :=
fun i => (hu i).mul (hv i)
#align measure_theory.adapted.mul MeasureTheory.Adapted.mul
#align measure_theory.adapted.add MeasureTheory.Adapted.add
@[protected, to_additive]
theorem div [Div β] [ContinuousDiv β] (hu : Adapted f u) (hv : Adapted f v) : Adapted f (u / v) :=
fun i => (hu i).div (hv i)
#align measure_theory.adapted.div MeasureTheory.Adapted.div
#align measure_theory.adapted.sub MeasureTheory.Adapted.sub
@[protected, to_additive]
theorem inv [Group β] [TopologicalGroup β] (hu : Adapted f u) : Adapted f u⁻¹ := fun i => (hu i).inv
#align measure_theory.adapted.inv MeasureTheory.Adapted.inv
#align measure_theory.adapted.neg MeasureTheory.Adapted.neg
@[protected]
theorem smul [SMul ℝ β] [ContinuousSMul ℝ β] (c : ℝ) (hu : Adapted f u) : Adapted f (c • u) :=
fun i => (hu i).const_smul c
#align measure_theory.adapted.smul MeasureTheory.Adapted.smul
@[protected]
theorem stronglyMeasurable {i : ι} (hf : Adapted f u) : strongly_measurable[m] (u i) :=
(hf i).mono (f.le i)
#align measure_theory.adapted.strongly_measurable MeasureTheory.Adapted.stronglyMeasurable
theorem stronglyMeasurable_le {i j : ι} (hf : Adapted f u) (hij : i ≤ j) :
strongly_measurable[f j] (u i) :=
(hf i).mono (f.mono hij)
#align measure_theory.adapted.strongly_measurable_le MeasureTheory.Adapted.stronglyMeasurable_le
end Adapted
theorem adapted_const (f : Filtration ι m) (x : β) : Adapted f fun _ _ => x := fun i =>
stronglyMeasurable_const
#align measure_theory.adapted_const MeasureTheory.adapted_const
variable (β)
theorem adapted_zero [Zero β] (f : Filtration ι m) : Adapted f (0 : ι → Ω → β) := fun i =>
@stronglyMeasurable_zero Ω β (f i) _ _
#align measure_theory.adapted_zero MeasureTheory.adapted_zero
variable {β}
theorem Filtration.adapted_natural [MetrizableSpace β] [mβ : MeasurableSpace β] [BorelSpace β]
{u : ι → Ω → β} (hum : ∀ i, strongly_measurable[m] (u i)) :
Adapted (Filtration.natural u hum) u := by
intro i
refine' strongly_measurable.mono _ (le_supᵢ₂_of_le i (le_refl i) le_rfl)
rw [stronglyMeasurable_iff_measurable_separable]
exact ⟨measurable_iff_comap_le.2 le_rfl, (hum i).isSeparable_range⟩
#align measure_theory.filtration.adapted_natural MeasureTheory.Filtration.adapted_natural
/-- Progressively measurable process. A sequence of functions `u` is said to be progressively
measurable with respect to a filtration `f` if at each point in time `i`, `u` restricted to
`set.Iic i × Ω` is measurable with respect to the product `measurable_space` structure where the
σ-algebra used for `Ω` is `f i`.
The usual definition uses the interval `[0,i]`, which we replace by `set.Iic i`. We recover the
usual definition for index types `ℝ≥0` or `ℕ`. -/
def ProgMeasurable [MeasurableSpace ι] (f : Filtration ι m) (u : ι → Ω → β) : Prop :=
∀ i, strongly_measurable[Subtype.measurableSpace.Prod (f i)] fun p : Set.Iic i × Ω => u p.1 p.2
#align measure_theory.prog_measurable MeasureTheory.ProgMeasurable
theorem progMeasurable_const [MeasurableSpace ι] (f : Filtration ι m) (b : β) :
ProgMeasurable f (fun _ _ => b : ι → Ω → β) := fun i =>
@stronglyMeasurable_const _ _ (Subtype.measurableSpace.Prod (f i)) _ _
#align measure_theory.prog_measurable_const MeasureTheory.progMeasurable_const
namespace ProgMeasurable
variable [MeasurableSpace ι]
protected theorem adapted (h : ProgMeasurable f u) : Adapted f u :=
by
intro i
have : u i = (fun p : Set.Iic i × Ω => u p.1 p.2) ∘ fun x => (⟨i, set.mem_Iic.mpr le_rfl⟩, x) :=
rfl
rw [this]
exact (h i).compMeasurable measurable_prod_mk_left
#align measure_theory.prog_measurable.adapted MeasureTheory.ProgMeasurable.adapted
protected theorem comp {t : ι → Ω → ι} [TopologicalSpace ι] [BorelSpace ι] [MetrizableSpace ι]
(h : ProgMeasurable f u) (ht : ProgMeasurable f t) (ht_le : ∀ i ω, t i ω ≤ i) :
ProgMeasurable f fun i ω => u (t i ω) ω :=
by
intro i
have :
(fun p : ↥(Set.Iic i) × Ω => u (t (p.fst : ι) p.snd) p.snd) =
(fun p : ↥(Set.Iic i) × Ω => u (p.fst : ι) p.snd) ∘ fun p : ↥(Set.Iic i) × Ω =>
(⟨t (p.fst : ι) p.snd, set.mem_Iic.mpr ((ht_le _ _).trans p.fst.prop)⟩, p.snd) :=
rfl
rw [this]
exact (h i).compMeasurable ((ht i).Measurable.subtype_mk.prod_mk measurable_snd)
#align measure_theory.prog_measurable.comp MeasureTheory.ProgMeasurable.comp
section Arithmetic
@[to_additive]
protected theorem mul [Mul β] [ContinuousMul β] (hu : ProgMeasurable f u)
(hv : ProgMeasurable f v) : ProgMeasurable f fun i ω => u i ω * v i ω := fun i =>
(hu i).mul (hv i)
#align measure_theory.prog_measurable.mul MeasureTheory.ProgMeasurable.mul
#align measure_theory.prog_measurable.add MeasureTheory.ProgMeasurable.add
@[to_additive]
protected theorem finset_prod' {γ} [CommMonoid β] [ContinuousMul β] {U : γ → ι → Ω → β}
{s : Finset γ} (h : ∀ c ∈ s, ProgMeasurable f (U c)) : ProgMeasurable f (∏ c in s, U c) :=
Finset.prod_induction U (ProgMeasurable f) (fun _ _ => ProgMeasurable.mul)
(progMeasurable_const _ 1) h
#align measure_theory.prog_measurable.finset_prod' MeasureTheory.ProgMeasurable.finset_prod'
#align measure_theory.prog_measurable.finset_sum' MeasureTheory.ProgMeasurable.finset_sum'
@[to_additive]
protected theorem finset_prod {γ} [CommMonoid β] [ContinuousMul β] {U : γ → ι → Ω → β}
{s : Finset γ} (h : ∀ c ∈ s, ProgMeasurable f (U c)) :
ProgMeasurable f fun i a => ∏ c in s, U c i a :=
by
convert prog_measurable.finset_prod' h
ext (i a)
simp only [Finset.prod_apply]
#align measure_theory.prog_measurable.finset_prod MeasureTheory.ProgMeasurable.finset_prod
#align measure_theory.prog_measurable.finset_sum MeasureTheory.ProgMeasurable.finset_sum
@[to_additive]
protected theorem inv [Group β] [TopologicalGroup β] (hu : ProgMeasurable f u) :
ProgMeasurable f fun i ω => (u i ω)⁻¹ := fun i => (hu i).inv
#align measure_theory.prog_measurable.inv MeasureTheory.ProgMeasurable.inv
#align measure_theory.prog_measurable.neg MeasureTheory.ProgMeasurable.neg
@[to_additive]
protected theorem div [Group β] [TopologicalGroup β] (hu : ProgMeasurable f u)
(hv : ProgMeasurable f v) : ProgMeasurable f fun i ω => u i ω / v i ω := fun i =>
(hu i).div (hv i)
#align measure_theory.prog_measurable.div MeasureTheory.ProgMeasurable.div
#align measure_theory.prog_measurable.sub MeasureTheory.ProgMeasurable.sub
end Arithmetic
end ProgMeasurable
theorem progMeasurable_of_tendsto' {γ} [MeasurableSpace ι] [PseudoMetrizableSpace β]
(fltr : Filter γ) [fltr.ne_bot] [fltr.IsCountablyGenerated] {U : γ → ι → Ω → β}
(h : ∀ l, ProgMeasurable f (U l)) (h_tendsto : Tendsto U fltr (𝓝 u)) : ProgMeasurable f u :=
by
intro i
apply
@stronglyMeasurable_of_tendsto (Set.Iic i × Ω) β γ (MeasurableSpace.prod _ (f i)) _ _ fltr _ _ _
_ fun l => h l i
rw [tendsto_pi_nhds] at h_tendsto⊢
intro x
specialize h_tendsto x.fst
rw [tendsto_nhds] at h_tendsto⊢
exact fun s hs h_mem => h_tendsto { g | g x.snd ∈ s } (hs.Preimage (continuous_apply x.snd)) h_mem
#align measure_theory.prog_measurable_of_tendsto' MeasureTheory.progMeasurable_of_tendsto'
theorem progMeasurable_of_tendsto [MeasurableSpace ι] [PseudoMetrizableSpace β] {U : ℕ → ι → Ω → β}
(h : ∀ l, ProgMeasurable f (U l)) (h_tendsto : Tendsto U atTop (𝓝 u)) : ProgMeasurable f u :=
progMeasurable_of_tendsto' atTop h h_tendsto
#align measure_theory.prog_measurable_of_tendsto MeasureTheory.progMeasurable_of_tendsto
/-- A continuous and adapted process is progressively measurable. -/
theorem Adapted.progMeasurable_of_continuous [TopologicalSpace ι] [MetrizableSpace ι]
[SecondCountableTopology ι] [MeasurableSpace ι] [OpensMeasurableSpace ι]
[PseudoMetrizableSpace β] (h : Adapted f u) (hu_cont : ∀ ω, Continuous fun i => u i ω) :
ProgMeasurable f u := fun i =>
@stronglyMeasurable_uncurry_of_continuous_of_stronglyMeasurable _ _ (Set.Iic i) _ _ _ _ _ _ _
(f i) _ (fun ω => (hu_cont ω).comp continuous_induced_dom) fun j => (h j).mono (f.mono j.Prop)
#align measure_theory.adapted.prog_measurable_of_continuous MeasureTheory.Adapted.progMeasurable_of_continuous
/-- For filtrations indexed by a discrete order, `adapted` and `prog_measurable` are equivalent.
This lemma provides `adapted f u → prog_measurable f u`.
See `prog_measurable.adapted` for the reverse direction, which is true more generally. -/
theorem Adapted.progMeasurable_of_discrete [TopologicalSpace ι] [DiscreteTopology ι]
[SecondCountableTopology ι] [MeasurableSpace ι] [OpensMeasurableSpace ι]
[PseudoMetrizableSpace β] (h : Adapted f u) : ProgMeasurable f u :=
h.progMeasurable_of_continuous fun _ => continuous_of_discreteTopology
#align measure_theory.adapted.prog_measurable_of_discrete MeasureTheory.Adapted.progMeasurable_of_discrete
-- this dot notation will make more sense once we have a more general definition for predictable
theorem Predictable.adapted {f : Filtration ℕ m} {u : ℕ → Ω → β} (hu : Adapted f fun n => u (n + 1))
(hu0 : strongly_measurable[f 0] (u 0)) : Adapted f u := fun n =>
match n with
| 0 => hu0
| n + 1 => (hu n).mono (f.mono n.le_succ)
#align measure_theory.predictable.adapted MeasureTheory.Predictable.adapted
end MeasureTheory
|
/*
* Created by Robin Raymond.
* Copyright 2009-2011. Robin Raymond. All rights reserved.
*
* This file is part of zsLib.
*
* zsLib is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License (LGPL) as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* zsLib 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 zsLib; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include <zsLib/zsHelpers.h>
//#include <boost/test/unit_test_suite.hpp>
//#include <boost/test/unit_test.hpp>
//#include <boost/test/test_tools.hpp>
#include "boost_replacement.h"
BOOST_AUTO_TEST_SUITE(zsLibStringTest)
BOOST_AUTO_TEST_CASE(Test_PUID_GUID)
{
zsLib::PUID puid1 = zsLib::createPUID();
zsLib::PUID puid2 = zsLib::createPUID();
zsLib::UUID uuid1 = zsLib::createUUID();
zsLib::UUID uuid2 = zsLib::createUUID();
BOOST_CHECK(sizeof(puid1) == sizeof(zsLib::PUID))
BOOST_CHECK(puid1 != puid2)
BOOST_CHECK(sizeof(uuid1) == sizeof(zsLib::UUID))
BOOST_CHECK(uuid1 != uuid2)
}
BOOST_AUTO_TEST_CASE(Test_atomic_inc_dec)
{
zsLib::ULONG value = 0;
zsLib::ULONG value1 = zsLib::atomicIncrement(value);
BOOST_EQUAL(1, value);
BOOST_EQUAL(1, value1);
BOOST_EQUAL(1, zsLib::atomicGetValue(value));
zsLib::ULONG value2 = zsLib::atomicIncrement(value);
BOOST_EQUAL(2, value);
BOOST_EQUAL(2, value2);
BOOST_EQUAL(2, zsLib::atomicGetValue(value));
zsLib::ULONG value3 = zsLib::atomicDecrement(value);
BOOST_EQUAL(1, value);
BOOST_EQUAL(1, value3);
BOOST_EQUAL(1, zsLib::atomicGetValue(value));
zsLib::ULONG value4 = zsLib::atomicDecrement(value);
BOOST_EQUAL(0, value);
BOOST_EQUAL(0, value4);
BOOST_EQUAL(0, zsLib::atomicGetValue(value));
}
BOOST_AUTO_TEST_CASE(TestHelper_atomic_get_set)
{
zsLib::DWORD value = 0;
BOOST_EQUAL(0, zsLib::atomicGetValue32(value))
zsLib::atomicSetValue32(value, 1);
BOOST_EQUAL(1, zsLib::atomicGetValue32(value))
zsLib::atomicSetValue32(value, 0xFFFFFFFF);
BOOST_EQUAL(0xFFFFFFFF, zsLib::atomicGetValue32(value))
}
BOOST_AUTO_TEST_SUITE_END()
|
Require Import Coq.Lists.List Coq.Setoids.Setoid Coq.Classes.RelationClasses Coq.Classes.Morphisms.
Require Export Fiat.Common.Coq__8_4__8_5__Compat.
Set Implicit Arguments.
Local Coercion is_true : bool >-> Sortclass.
#[global]
Instance proper_if {A B R}
{test : bool} {then_case else_case}
`{Proper (A -> B) R then_case, Proper (A -> B) R else_case}
: Proper R (fun x => if test then then_case x else else_case x).
Proof.
destruct test; trivial.
Qed.
#[global]
Instance proper_idmap {A R}
: Proper (R ==> R) (fun x : A => x).
Proof. repeat intro; assumption. Qed.
#[global]
Instance proper_const {A B} {R1 : relation A} {R2}
`{Reflexive B R2} v
: Proper (R1 ==> R2) (fun _ => v).
Proof.
repeat intro; reflexivity.
Qed.
Lemma pointwise_Proper {A B} R (f : A -> B) `{forall x, Proper R (f x)}
: Proper (pointwise_relation A R) f.
Proof.
unfold Proper in *.
repeat intro; trivial.
Qed.
#[global]
Hint Extern 10 (Proper (pointwise_relation _ _) _) => class_apply @pointwise_Proper : typeclass_instances.
Global Instance sumbool_rect_Proper {L R : Prop} {P} {R1}
: Proper (pointwise_relation L R1 ==> pointwise_relation R R1 ==> @forall_relation _ (fun _ : {L} + {R} => P) (fun _ => R1))
(@sumbool_rect L R (fun _ => P)).
Proof.
intros ?????? [a|a]; simpl in *; eauto.
Qed.
Global Hint Extern 0 (Proper _ (@sumbool_rect ?L ?R (fun _ => ?P))) => refine (@sumbool_rect_Proper L R P _) : typeclass_instances.
Global Instance andb_Proper
: Proper (eq ==> eq ==> eq) andb.
Proof.
repeat ((intro; progress subst) || intros []); try reflexivity.
Qed.
Global Instance orb_Proper
: Proper (eq ==> eq ==> eq) orb.
Proof.
repeat ((intro; progress subst) || intros []); try reflexivity.
Qed.
Global Instance map_Proper_eq {A B}
: Proper (pointwise_relation _ eq ==> eq ==> eq) (@map A B).
Proof.
intros ?? H ? ls ?; subst.
induction ls; trivial; simpl.
hnf in H; rewrite H, IHls; reflexivity.
Qed.
Global Instance bool_rect_Proper {P} {R1}
: Proper (R1 ==> R1 ==> @forall_relation _ (fun _ : bool => P) (fun _ => R1))
(@bool_rect (fun _ => P)).
Proof.
intros ?????? [|]; simpl in *; eauto.
Qed.
Global Instance fst_eq_Proper {A B} : Proper (eq ==> eq) (@fst A B).
Proof.
repeat intro; subst; reflexivity.
Qed.
Global Instance snd_eq_Proper {A B} : Proper (eq ==> eq) (@snd A B).
Proof.
repeat intro; subst; reflexivity.
Qed.
Global Instance: Proper (eq ==> Basics.flip Basics.impl) is_true | 10 := _.
Global Instance: Proper (eq ==> Basics.impl) is_true | 10 := _.
Global Instance: Proper (eq ==> iff) is_true | 5 := _.
Global Instance: Proper (eq ==> eq) is_true | 0 := _.
Global Instance istrue_impl_Proper
: Proper (implb ==> Basics.impl) is_true.
Proof.
intros [] []; compute; trivial.
Qed.
Global Instance istrue_flip_impl_Proper
: Proper (Basics.flip implb ==> Basics.flip Basics.impl) is_true.
Proof.
intros [] []; compute; trivial.
Qed.
Global Instance implb_Reflexive : Reflexive implb | 1.
Proof. intros []; reflexivity. Qed.
Global Instance implb_Transitive : Transitive implb | 1.
Proof. intros [] [] []; simpl; trivial. Qed.
Global Instance implb_Antisymmetric : @Antisymmetric _ eq _ implb | 1.
Proof. intros [] [] []; simpl; trivial. Qed.
Global Instance flip_implb_Reflexive : Reflexive (Basics.flip implb) | 1.
Proof. intros []; reflexivity. Qed.
Global Instance flip_implb_Transitive : Transitive (Basics.flip implb) | 1.
Proof. intros [] [] []; simpl; trivial. Qed.
Global Instance flip_implb_Antisymmetric : @Antisymmetric _ eq _ (Basics.flip implb) | 1.
Proof. intros [] []; compute; intros [] []; trivial. Qed.
Global Instance implb_implb_Proper0
: Proper (implb ==> Basics.flip implb ==> Basics.flip implb) implb.
Proof. intros [] [] ? [] []; compute; trivial. Qed.
Global Instance implb_implb_Proper1
: Proper (Basics.flip implb ==> implb ==> implb) implb.
Proof. intros [] [] ? [] []; compute; trivial. Qed.
Global Instance implb_flip_implb_Proper0
: Proper (Basics.flip implb ==> implb ==> Basics.flip implb) (Basics.flip implb).
Proof. intros [] [] ? [] []; compute; trivial. Qed.
Global Instance implb_flip_implb_Proper1
: Proper (implb ==> Basics.flip implb ==> implb) (Basics.flip implb).
Proof. intros [] [] ? [] []; compute; trivial. Qed.
Global Instance subrelation_eq_pointwise {A B} : subrelation (@eq (A -> B)) (pointwise_relation A eq).
Proof.
compute; intros; subst; reflexivity.
Qed.
Global Instance and_flip_impl_Proper
: Proper (Basics.flip Basics.impl ==> Basics.flip Basics.impl ==> Basics.flip Basics.impl) and | 10.
Proof. lazy; tauto. Qed.
#[global]
Hint Extern 0 (Proper (_ ==> Basics.impl --> _) and) => apply and_flip_impl_Proper : typeclass_instances.
#[global]
Hint Extern 0 (Proper (Basics.impl --> _ ==> _) and) => apply and_flip_impl_Proper : typeclass_instances.
Global Instance eq_eq_impl_impl_Proper
: Proper (eq ==> eq ==> Basics.impl) Basics.impl | 1
:= _.
Global Instance map_Proper_eq_In {A B ls}
: Proper (forall_relation (fun a x y => List.In a ls -> x = y) ==> eq) (fun f => @List.map A B f ls).
Proof.
induction ls as [|l ls IHls];
unfold forall_relation.
{ repeat intro; reflexivity. }
{ intros ?? H.
simpl; rewrite H by (left; reflexivity).
f_equal.
rewrite IHls; [ reflexivity | ].
intros ??; apply H; right; assumption. }
Qed.
(** If we don't know the relation, default to assuming that it's equality, if the type is not a function *)
#[global]
Hint Extern 0 (@Reflexive ?T ?e)
=> is_evar e;
lazymatch T with
| forall x : _, _ => fail
| _ => refine eq_Reflexive
end : typeclass_instances.
Lemma pointwise_Reflexive {A B R} {_ : @Reflexive B R}
: Reflexive (pointwise_relation A R).
Proof.
repeat intro; reflexivity.
Qed.
#[global]
Hint Extern 1 (Reflexive (pointwise_relation _ _)) => apply @pointwise_Reflexive : typeclass_instances.
Ltac solve_Proper_eqs :=
idtac;
lazymatch goal with
| [ |- Proper _ _ ] => apply @reflexive_proper; solve_Proper_eqs
| [ |- Reflexive (_ ==> _)%signature ]
=> apply @reflexive_eq_dom_reflexive; solve_Proper_eqs
| [ |- Reflexive _ ] => try apply eq_Reflexive
end.
Ltac is_evar_or_eq e :=
first [ is_evar e
| match e with
| eq => idtac
end ].
Ltac is_evar_or_eq_or_evar_free e :=
first [ is_evar_or_eq e
| try (has_evar e; fail 1) ].
#[global]
Hint Extern 1 (Proper ?e _) =>
is_evar_or_eq e; solve_Proper_eqs : typeclass_instances.
#[global]
Hint Extern 1 (Proper (?e1 ==> ?e2) _) =>
is_evar_or_eq e1; is_evar_or_eq_or_evar_free e2; solve_Proper_eqs : typeclass_instances.
#[global]
Hint Extern 1 (Proper (?e1 ==> ?e2 ==> ?e3) _) =>
is_evar_or_eq e1; is_evar_or_eq e2; is_evar_or_eq_or_evar_free e3; solve_Proper_eqs : typeclass_instances.
#[global]
Hint Extern 1 (Proper (?e1 ==> ?e2 ==> ?e3 ==> ?e4) _) =>
is_evar_or_eq e1; is_evar_or_eq e2; is_evar_or_eq e3; is_evar_or_eq_or_evar_free e4; solve_Proper_eqs : typeclass_instances.
|
module examplesPaperJFP.loadAllOOAgdaPart2 where
-- This is a continuation of the file loadAllOOAgdaPart1
-- giving the code from the ooAgda paper
-- This file was split into two because of a builtin IO which
-- makes loading files from part1 and part2 incompatible.
-- Note that some files which are directly in the libary can be found
-- in loadAllOOAgdaFilesAsInLibrary
-- Sect 1 - 7 are in loadAllOOAgdaPart1.agda
-- 8. State-Dependent Objects and IO
-- 8.1 State-Dependent Interfaces
import examplesPaperJFP.StatefulObject
-- 8.2 State-Dependent Objects
-- 8.2.1. Example of Use of Safe Stack
import examplesPaperJFP.safeFibStackMachineObjectOriented
-- 8.3 Reasoning About Stateful Objects
import examplesPaperJFP.StackBisim
-- 8.3.1. Bisimilarity
-- 8.3.2. Verifying stack laws}
-- 8.3.3. Bisimilarity of different stack implementations
-- 8.4. State-Dependent IO
import examplesPaperJFP.StateDependentIO
-- 9. A Drawing Program in Agda
-- code as in paper adapted to new Agda
open import examplesPaperJFP.IOGraphicsLib
-- code as in library see loadAllOOAgdaFilesAsInLibrary.agda
-- open import SizedIO.IOGraphicsLib
open import examplesPaperJFP.ExampleDrawingProgram
-- 10. A Graphical User Interface using an Object
-- 10.1. wxHaskell
-- 10.2. A Library for Object-Based GUIs in Agda
open import examplesPaperJFP.VariableList
open import examplesPaperJFP.WxGraphicsLib
open import examplesPaperJFP.VariableListForDispatchOnly
-- 10.3 Example: A GUI controlling a Space Ship in Agda
open import examplesPaperJFP.SpaceShipSimpleVar
open import examplesPaperJFP.SpaceShipCell
open import examplesPaperJFP.SpaceShipAdvanced
-- 11. Related Work
open import examplesPaperJFP.agdaCodeBrady
-- 12. Conclusion
-- Bibliography
|
! *******************************************************************
! * *
! * Real*8 Function dlavx1 *
! * *
! *******************************************************************
! Double Precision Version 1.62
! Written by Gordon A. Fenton, 1989
! Latest Update: Jul 10, 2002
!
! PURPOSE returns the covariance between two points along a 1-D Markov
! process.
!
! Returns the covariance between two points, separated by distance T, in
! a 1-D Markov process. The covariance function is given by
!
! B(T) = var * exp( -2|T|/dthx )
!
! where var is the point variance and dthx is the scale of fluctuation.
! var and dthx are brought into this routine through the common
! block DPARAM.
!
! If var < 0, then this function returns the variance of a local average
! of the process, |var|*V(T), averaged over the distance T, where V(T) is
! the variance function (see E.H. Vanmarcke, "Random Fields: Analysis and
! Synthesis", MIT Press, 1984, Chapter 5).
! T
! V(T) = (2/T) * INT (1-s/T)*r(s) ds
! 0
! where r(s) is the correlation function: r(s) = B(s)/var. The integration
! gives us
!
! V(T) = (2/a*a) * [ a + exp(-a) - 1]
!
! where a = 2*T/dthx. When dthx >> T, a third order Taylor's series expansion
! gives the numerically improved approximation
!
! V(T) = [1 - 2*|T|/(3*dthx) ], dthx >> T
!
! and when dthx << T, the exp(-a) term disappears because `a' becomes very
! large, leaving us with
!
! V(T) = (dthx/T) * [ 1 - (dthx/2T) ]
!
!
! REVISION HISTORY:
! 1.1 explicitly accomodate the case when dthx = 0.
! 1.2 corrected bug introduced in 1.1 (missed multiplying by var)
! 1.3 improved limit handling
! 1.4 added lvarfn flag to end of /dparam/ common block. Set it to
! true if the variance function is to be returned. Otherwise this
! function returns the covariance. (Apr 29/00)
! 1.5 eliminated lvarfn -- now return covariances only if var < 0 (Mar 2/01)
! 1.6 reversed default - now return covariances if var > 0 (Apr 11/01)
! 1.61 revised above documentation to reflect revision 1.6 (May 9/01)
! 1.62 corrected erroneous documentation above re variance func (Jul 10/02)
! =======================================================================
real*8 function dlavx1( T )
implicit real*8 (a-h,o-z)
common/dparam/ var, dpb, dthx, dthy, dthz
data zero/0.d0/, half/0.5d0/, one/1.d0/, two/2.d0/, three/3.d0/
data small/0.0067d0/, big/1.d6/
abs(x) = dabs(x)
exp(x) = dexp(x)
aT = abs(T)
if( var .lt. zero ) then ! return variance function
if( dthx .ge. big*aT ) then
if( dthx .eq. zero ) then
dlavx1 = -var
else
dlavx1 = -var*(one - two*aT/(three*dthx))
endif
elseif( dthx .le. small*aT ) then
rx = dthx/aT
dlavx1 = -var*rx*(one - half*rx)
else
a = dthx/abs(T)
b = half*a
c = exp(-one/b) - one
dlavx1 = -var*a*(one + b*c)
endif
else ! return covariance
if( dthx .eq. zero ) then
if( T .eq. zero ) then
dlavx1 = var
else
dlavx1 = zero
endif
else
dlavx1 = var*exp( -two*aT/dthx )
endif
endif
return
end
|
import data.set.basic -- hide
import tactic -- hide
open set -- hide
open set function -- hide
variables {X Y I: Type} -- hide
/-
# Level 1: The image of an indexed union
This level is similar to the previous one. You can use a similar strategy.
-/
/- Lemma
If f is a function and Aᵢ are sets, then f(⋃ Aᵢ) = ⋃ f(Aᵢ)
-/
lemma image_Union (f: X → Y) ( A : I → set X) : f '' ( ⋃ i, A i ) = ⋃ i, f '' A i :=
begin
ext y,
split,
{
intro h1,
cases h1 with x hx, -- millor donar noms, per facilitar l'argument
cases hx with hx1 hx2, -- no tenia bons noms, però almenys són més curts
simp,
rw ← hx2, --aquí voldria combinar dues hipotesis per obtenir el goal
cases hx1 with U hU,
simp at hU,
cases hU with hU1 hU2,
cases hU1 with i hi,
-- Ara hem de fer servir les hipòtesis que tenim...
use i, -- l'index que busquem l'acabem d'obtenir al pas anterior
use x,
rw hi,
exact ⟨hU2, rfl⟩,
},
{
intro h1,
simp at h1,
cases h1 with i hx,
simp,
cases hx with x hx2,
cases hx2 with hxA hxy,
use x,
use i,
{
exact hxA,
},
{
exact hxy,
},
},
end
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Countable sets.
-/
import data.equiv.list data.set.finite logic.function data.set.function
noncomputable theory
open function set encodable
open classical (hiding some)
local attribute [instance] prop_decidable
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
namespace set
/-- Countable sets
A set is countable if there exists an encoding of the set into the natural numbers.
An encoding is an injection with a partial inverse, which can be viewed as a
constructive analogue of countability. (For the most part, theorems about
`countable` will be classical and `encodable` will be constructive.)
-/
def countable (s : set α) : Prop := nonempty (encodable s)
lemma countable_iff_exists_injective {s : set α} :
countable s ↔ ∃f:s → ℕ, injective f :=
⟨λ ⟨h⟩, by exactI ⟨encode, encode_injective⟩,
λ ⟨f, h⟩, ⟨⟨f, partial_inv f, partial_inv_left h⟩⟩⟩
lemma countable_iff_exists_inj_on {s : set α} :
countable s ↔ ∃ f : α → ℕ, inj_on f s :=
countable_iff_exists_injective.trans
⟨λ ⟨f, hf⟩, ⟨λ a, if h : a ∈ s then f ⟨a, h⟩ else 0,
λ a b as bs h, congr_arg subtype.val $
hf $ by simpa [as, bs] using h⟩,
λ ⟨f, hf⟩, ⟨_, inj_on_iff_injective.1 hf⟩⟩
lemma countable_iff_exists_surjective [ne : inhabited α] {s : set α} :
countable s ↔ ∃f:ℕ → α, s ⊆ range f :=
⟨λ ⟨h⟩, by exactI ⟨λ n, ((decode s n).map subtype.val).iget,
λ a as, ⟨encode (⟨a, as⟩ : s), by simp [encodek]⟩⟩,
λ ⟨f, hf⟩, ⟨⟨
λ x, inv_fun f x.1,
λ n, if h : f n ∈ s then some ⟨f n, h⟩ else none,
λ ⟨x, hx⟩, begin
have := inv_fun_eq (hf hx), dsimp at this ⊢,
simp [this, hx]
end⟩⟩⟩
def countable.to_encodable {s : set α} : countable s → encodable s :=
classical.choice
lemma countable_encodable' (s : set α) [H : encodable s] : countable s :=
⟨H⟩
lemma countable_encodable [encodable α] (s : set α) : countable s :=
⟨by apply_instance⟩
@[simp] lemma countable_empty : countable (∅ : set α) :=
⟨⟨λ x, x.2.elim, λ n, none, λ x, x.2.elim⟩⟩
@[simp] lemma countable_singleton (a : α) : countable ({a} : set α) :=
⟨of_equiv _ (equiv.set.singleton a)⟩
lemma countable_subset {s₁ s₂ : set α} (h : s₁ ⊆ s₂) : countable s₂ → countable s₁
| ⟨H⟩ := ⟨@of_inj _ _ H _ (embedding_of_subset h).2⟩
lemma countable_image {s : set α} (f : α → β) (hs : countable s) : countable (f '' s) :=
let f' : s → f '' s := λ⟨a, ha⟩, ⟨f a, mem_image_of_mem f ha⟩ in
have hf' : surjective f', from assume ⟨b, a, ha, hab⟩, ⟨⟨a, ha⟩, subtype.eq hab⟩,
⟨@encodable.of_inj _ _ hs.to_encodable (surj_inv hf') (injective_surj_inv hf')⟩
lemma countable_range [encodable α] (f : α → β) : countable (range f) :=
by rw ← image_univ; exact countable_image _ (countable_encodable _)
lemma countable_Union {t : α → set β} [encodable α] (ht : ∀a, countable (t a)) :
countable (⋃a, t a) :=
by haveI := (λ a, (ht a).to_encodable);
rw Union_eq_range_sigma; apply countable_range
lemma countable_bUnion {s : set α} {t : α → set β} (hs : countable s) (ht : ∀a∈s, countable (t a)) :
countable (⋃a∈s, t a) :=
begin
rw bUnion_eq_Union,
haveI := hs.to_encodable,
exact countable_Union (by simpa using ht)
end
lemma countable_sUnion {s : set (set α)} (hs : countable s) (h : ∀a∈s, countable a) :
countable (⋃₀ s) :=
by rw sUnion_eq_bUnion; exact countable_bUnion hs h
lemma countable_Union_Prop {p : Prop} {t : p → set β} (ht : ∀h:p, countable (t h)) :
countable (⋃h:p, t h) :=
by by_cases p; simp [h, ht]
lemma countable_union {s₁ s₂ : set α} (h₁ : countable s₁) (h₂ : countable s₂) : countable (s₁ ∪ s₂) :=
by rw union_eq_Union; exact
countable_Union (bool.forall_bool.2 ⟨h₂, h₁⟩)
lemma countable_insert {s : set α} {a : α} (h : countable s) : countable (insert a s) :=
by rw [set.insert_eq]; from countable_union (countable_singleton _) h
lemma countable_finite {s : set α} : finite s → countable s
| ⟨h⟩ := nonempty_of_trunc (by exactI trunc_encodable_of_fintype s)
lemma countable_set_of_finite_subset {s : set α} : countable s →
countable {t | finite t ∧ t ⊆ s} | ⟨h⟩ :=
begin
resetI,
refine countable_subset _ (countable_range
(λ t : finset s, {a | ∃ h:a ∈ s, subtype.mk a h ∈ t})),
rintro t ⟨⟨ht⟩, ts⟩,
refine ⟨finset.univ.map (embedding_of_subset ts),
set.ext $ λ a, _⟩,
simp, split,
{ rintro ⟨as, b, bt, e⟩,
cases congr_arg subtype.val e, exact bt },
{ exact λ h, ⟨ts h, _, h, rfl⟩ }
end
lemma countable_pi {π : α → Type*} [fintype α] {s : Πa, set (π a)} (hs : ∀a, countable (s a)) :
countable {f : Πa, π a | ∀a, f a ∈ s a} :=
countable_subset
(show {f : Πa, π a | ∀a, f a ∈ s a} ⊆ range (λf : Πa, s a, λa, (f a).1), from
assume f hf, ⟨λa, ⟨f a, hf a⟩, funext $ assume a, rfl⟩) $
have trunc (encodable (Π (a : α), s a)), from
@encodable.fintype_pi α _ _ _ (assume a, (hs a).to_encodable),
trunc.induction_on this $ assume h,
@countable_range _ _ h _
end set
|
#' @title
#' Reduced-rank ridge regression with rank and tuning parameter selected by cross validation
#'
#' @description
#' This function performs reduced-rank ridge regression with the rank and the
#' tuning parameter selected by cross validation.
#'
#' @usage
#' RRS.cv(Y, X, nfold = 10, rankmax = min(dim(Y), dim(X)), nlam = 100,
#' lambda = seq(0, 100, length = nlam), norder = NULL,
#' nest.tune = FALSE, fold.drop = 0)
#'
#' @param Y response matrix.
#' @param X design matrix.
#' @param nfold the number of folds used in cross validation. Default is 10.
#' @param rankmax the maximum rank allowed.
#' @param nlam the number of tuning parameter candidates. Default is 100.
#' @param lambda the tuning sequence of length \code{nlam}.
#' @param norder a vector of length n that assigns samples to multiple folds
#' for cross validation. Default is NULL and then \code{norder} will be
#' generated randomly.
#' @param nest.tune a logical value to specify whether to tune the rank and lambda
#' in a nested way. Default is FALSE.
#' @param fold.drop the number of folds to drop. Default is 0.
#'
#'
#' @return The function returns a list:
#' \item{cr_path}{a matrix displays the path of model selection.}
#' \item{C}{the estimated low-rank coefficient matrix.}
#' \item{rank}{the selected rank.}
#' \item{lam}{the selected tuning parameter for ridge penalty.}
#'
#' @references Mukherjee, A., & Zhu, J. (2011).
#' Reduced Rank Ridge Regression and Its Kernel Extensions.
#' Statistical analysis and data mining,
#' 4(6), 612–622.
#'
# @importFrom rrpack rrs.fit
#' @export
RRS.cv<-function(Y, X, nfold = 10, rankmax = min(dim(Y), dim(X)), nlam = 100,
lambda = seq(0, 100, length = nlam), norder = NULL, nest.tune = FALSE,
fold.drop = 0)
{
p <- ncol(X)
q <- ncol(Y)
n <- nrow(Y)
ndel <- round(n/nfold)
if (is.null(norder)) {
norder <- sample(1:n, n)
}
cr_path <- array(dim = c(nlam, rankmax + 1, nfold), NA)
for (f in 1:nfold) {
if (f != nfold) {
iddel <- norder[(1 + ndel * (f - 1)):(ndel * f)]
}
else {
iddel <- norder[(1 + ndel * (f - 1)):n]
}
ndel <- length(iddel)
nf <- n - ndel
Xf <- X[-iddel, ]
Xfdel <- X[iddel, ]
Yf <- Y[-iddel, ]
Yfdel <- Y[iddel, ]
for (ll in 1:nlam) {
ini <- rrs.fit(Yf, Xf, lambda = lambda[ll], nrank = rankmax)
C_ls <- ini$coef.ls
A <- ini$A
tempFit <- Xfdel %*% C_ls
tempC <- matrix(nrow = nrow(A), ncol = nrow(A), 0)
for (i in 1:rankmax) {
tempC <- tempC + A[, i] %*% t(A[, i])
cr_path[ll, i + 1, f] <- sum((Yfdel - tempFit %*%
tempC)^2)
}
cr_path[ll, 1, f] <- sum(Yfdel^2)
}
}
index <- order(apply(cr_path, 3, sum))[1:ifelse(nfold > 5,
nfold - fold.drop, nfold)]
crerr <- apply(cr_path[, , index], c(1, 2), sum)/length(index) *
nfold
minid <- which.min(crerr)
minid2 <- ceiling(minid/nlam)
rankest <- minid2 - 1
minid1 <- minid - nlam * (minid2 - 1)
if (nest.tune == TRUE) {
lambda <- exp(seq(log(lambda[max(minid1 - 1, 1)] + 1e-04),
log(lambda[min(minid1 + 1, nlam)]), length = nlam))
cr_path <- array(dim = c(nlam, rankmax + 1, nfold), NA)
ndel <- round(n/nfold)
for (f in 1:nfold) {
if (f != nfold) {
iddel <- norder[(1 + ndel * (f - 1)):(ndel *
f)]
}
else {
iddel <- norder[(1 + ndel * (f - 1)):n]
ndel <- length(iddel)
}
nf <- n - ndel
Xf <- X[-iddel, ]
Xfdel <- X[iddel, ]
Yf <- Y[-iddel, ]
Yfdel <- Y[iddel, ]
for (ll in 1:nlam) {
ini <- rrs.fit(Yf, Xf, lambda = lambda[ll], nrank = rankmax)
C_ls <- ini$coef.ls
A <- ini$A
tempFit <- Xfdel %*% C_ls
tempC <- matrix(nrow = nrow(A), ncol = nrow(A),
0)
for (i in 1:rankmax) {
tempC <- tempC + A[, i] %*% t(A[, i])
cr_path[ll, i + 1, f] <- sum((Yfdel - tempFit %*%
tempC)^2)
}
cr_path[ll, 1, f] <- sum(Yfdel^2)
}
}
index <- order(apply(cr_path, 3, sum))[1:ifelse(nfold >
5, nfold - fold.drop, nfold)]
crerr <- apply(cr_path[, , index], c(1, 2), sum)/length(index) *
nfold
minid <- which.min(crerr)
minid2 <- ceiling(minid/nlam)
rankest <- minid2 - 1
minid1 <- minid - nlam * (minid2 - 1)
}
if (rankest == 0) {
list(cr_path = cr_path, CRE = crerr, norder = norder,
C = matrix(nrow = p, ncol = q, 0), rank = 0)
}
else {
fit <- rrs.fit(Y, X, lambda = lambda[minid1], nrank = rankmax)
C_lslam <- fit$coef.ls
A <- fit$A
list(cr_path = cr_path, CRE = crerr, ID = c(minid1, minid2),
norder = norder, C = C_lslam %*% A[, 1:rankest] %*%
t(A[, 1:rankest]), rank = rankest, lam = lambda[minid1])
}
}
|
// Copyright Aleksey Gurtovoy 2001-2006
//
// 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://www.boost.org/libs/mpl for documentation.
// $Id: include_preprocessed.hpp,v 1.2 2009/02/16 01:51:06 wdong-pku Exp $
// $Date: 2009/02/16 01:51:06 $
// $Revision: 1.2 $
// NO INCLUDE GUARDS, THE HEADER IS INTENDED FOR MULTIPLE INCLUSION!
#include <boost/mpl/aux_/config/workaround.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/stringize.hpp>
# define AUX778076_HEADER \
aux_/preprocessed/plain/BOOST_MPL_PREPROCESSED_HEADER \
/**/
#if BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(700))
# define AUX778076_INCLUDE_STRING BOOST_PP_STRINGIZE(boost/mpl/list/AUX778076_HEADER)
# include AUX778076_INCLUDE_STRING
# undef AUX778076_INCLUDE_STRING
#else
# include BOOST_PP_STRINGIZE(boost/mpl/list/AUX778076_HEADER)
#endif
# undef AUX778076_HEADER
#undef BOOST_MPL_PREPROCESSED_HEADER
|
-- Idris2
module Sinter.ANF
import Data.List
import Data.Vect
import Data.String.Extra
import Core.Context
import Core.CompileExpr
import Compiler.ANF
import Compiler.Common
import Idris.Driver
------------
-- SINTER --
------------
sqBrack : String -> String
sqBrack s = "[ " ++ s ++ " ]"
-- only literals in sinter are ints
data SinterLit
= SinInt Int Nat -- TODO: Int is value then width
| SinStr String
-- IDs are basically strings (not really, TODO)
data SinterID = MkSinterID String
genSinterID : SinterID -> String
genSinterID (MkSinterID id_) = id_
Show SinterID where
show = genSinterID
-- declared here, defined later
data SinterGlobal : Type where
-- an expression is a list of expressions, an ID, or a literal
data Sexpr : Type where
SexprList : (es : List Sexpr) -> Sexpr
SexprID : (id_ : SinterID) -> Sexpr
SexprLit : SinterLit -> Sexpr
SexprLet : (next : Sexpr) -> (defFun : SinterGlobal) -> Sexpr -- let-in for sinter
genSexpr : Sexpr -> String
genSexpr (SexprList []) = "[]"
genSexpr (SexprList es) =
let
exprs = map genSexpr es
in sqBrack $ join " " exprs
-- in "[ " ++ (concat exprs) ++ " ]"
genSexpr (SexprID id_) = show id_
genSexpr (SexprLit (SinInt v w)) =
"( " ++ show w ++ "; " ++ show v ++ " )"
genSexpr (SexprLit (SinStr s)) =
show s
-- TODO
genSexpr (SexprLet next defFun) =
genSexpr next
Show Sexpr where
show = genSexpr
-------------------------------
-- Things that can be global --
-------------------------------
-- declared earlier, defined here
data SinterGlobal = SinDef SinterID (List SinterID) Sexpr
| SinDecl SinterID (List SinterID)
| SinType SinterID (List SinterID)
genSinter : SinterGlobal -> String
genSinter (SinDef fName args body) =
let
args' = map show args
argsStr = sqBrack $ join " " args'
in sqBrack $ "def " ++ show fName ++ " " ++ argsStr ++ "\n\t"
++ genSexpr body
genSinter (SinDecl fName args) =
let
args' = map show args
argsStr = sqBrack $ join " " args'
in sqBrack $ "dec " ++ show fName ++ " " ++ argsStr
genSinter (SinType tName membs) =
let
membs' = map show membs
membsStr = sqBrack $ join " " membs'
in sqBrack $ "type " ++ show tName ++ membsStr
Show SinterGlobal where
show = genSinter
testCase : SinterGlobal
testCase = SinDef (MkSinterID "test") [(MkSinterID "arg1"), (MkSinterID "arg2")]
(SexprList [SexprLit (SinInt 1 2)])
-----------------------
-- Sinter primitives --
-----------------------
||| Primitive implemented in sinter
sinterPrim : String -> Sexpr
sinterPrim name = SexprID $ MkSinterID name
||| Primitive supplied by stdlib
sinterStdlib : String -> Sexpr
sinterStdlib name = SexprID $ MkSinterID ("stdlib_" ++ name)
||| Call the special sinter function for creating closures
sinterClosureCon : Sexpr
sinterClosureCon = sinterPrim ">makeClosure"
||| Call the special sinter function for running or adding args to closures
sinterClosureAdd : Sexpr
sinterClosureAdd = sinterPrim ">closureAddElem"
||| Crash sinter very inelegantly
sinterCrash : Sexpr
sinterCrash = SexprList [ sinterPrim "CRASH" ]
------------------
-- GORY DETAILS --
------------------
||| Symbol for indicating membership of namespace: "--|"
specialSep : String
specialSep = "--|"
||| Symbol for indicating record access: "."
recordAcc : String
recordAcc = "."
||| Separate two ids by "specialSep"
stitch : SinterID -> SinterID -> SinterID
stitch (MkSinterID x) (MkSinterID y) = MkSinterID $ x ++ specialSep ++ y
||| Turn a NS into a string separated by "specialSep"
mangleNS : Namespace -> SinterID
mangleNS ns = MkSinterID $ showNSWithSep specialSep ns
||| Sinter doesn't have a concept of NameSpaces, so define unique, but
||| identifiable names/strings instead.
mangle : Name -> SinterID
mangle (NS nameSpace name) =
let
nameSpace' = mangleNS nameSpace
name' = mangle name
in
stitch nameSpace' name'
mangle (UN x) = MkSinterID x
mangle (MN x i) = MkSinterID $ x ++ "-" ++ show i
mangle (PV n i) = MkSinterID $ (show $ mangle n) ++ "-" ++ show i
--mangle (DN x y) = MkSinterID x -- FIXME: correct? (assumes x repr.s y)
mangle (DN _ y) = mangle y -- ^ incorrect! the Name itself still
-- needs to be mangled; the way to display
-- it doesn't necessarily match our way of
-- representing names.
mangle (RF x) = MkSinterID $ recordAcc ++ x
mangle (Nested (i, j) n) =
MkSinterID $ "nested_" ++ (show i) ++ "_" ++ (show j) ++ (show $ mangle n)
-- string repr.n of case followed by unique Int (?)
mangle (CaseBlock x i) = MkSinterID $ "case_" ++ x ++ "-" ++ (show i)
mangle (WithBlock x i) = MkSinterID $ "with_" ++ x ++ "-" ++ (show i)
mangle (Resolved i) = MkSinterID $ "resolved_" ++ (show i)
idrisWorld : Sexpr
idrisWorld = SexprID $ MkSinterID "**IDRIS_WORLD**"
||| Assume < 2^31 number of args to any function (seriously, what would you do
||| with 2^31 args?...)
nArgsWidth : Nat
nArgsWidth = 32
||| Turn all the arguments (including the scope) into SinterIDs
superArgsToSinter : List Name -> List SinterID
superArgsToSinter ns = map mangle ns
-- Constants
constantToSexpr : Constant -> Sexpr
constantToSexpr (I x) = ?sexprConstI
constantToSexpr (BI x) = ?sexprConstBI
constantToSexpr (B8 x) = SexprLit $ SinInt (cast x) 8
constantToSexpr (B16 x) = SexprLit $ SinInt (cast x) 16
constantToSexpr (B32 x) = SexprLit $ SinInt (cast x) 32
constantToSexpr (B64 x) = SexprLit $ SinInt (cast x) 64
constantToSexpr (Str x) = SexprLit $ SinStr x
constantToSexpr (Ch x) = ?constantToSexpr_rhs_8
constantToSexpr (Db x) = ?constantToSexpr_rhs_9
constantToSexpr WorldVal = idrisWorld
constantToSexpr IntType = ?constantToSexpr_rhs_11
constantToSexpr IntegerType = ?constantToSexpr_rhs_12
constantToSexpr Bits8Type = ?constantToSexpr_rhs_13
constantToSexpr Bits16Type = ?constantToSexpr_rhs_14
constantToSexpr Bits32Type = ?constantToSexpr_rhs_15
constantToSexpr Bits64Type = ?constantToSexpr_rhs_16
constantToSexpr StringType = ?constantToSexpr_rhs_17
constantToSexpr CharType = ?constantToSexpr_rhs_18
constantToSexpr DoubleType = ?constantToSexpr_rhs_19
constantToSexpr WorldType = ?constantToSexpr_rhs_20
intNameToSinterID : Int -> SinterID
intNameToSinterID i = MkSinterID $ "a" ++ show i
aVarToSexpr : AVar -> Sexpr
aVarToSexpr (ALocal i) = SexprID $ intNameToSinterID i
aVarToSexpr ANull = SexprLit $ SinInt 0 1
mutual
-- Primitive Functions
primFnToSexpr : PrimFn arity -> Vect arity AVar -> Sexpr
primFnToSexpr (Add ty) [x, y] =
SexprList [ sinterStdlib "add", aVarToSexpr x, aVarToSexpr y ]
primFnToSexpr (Sub ty) [x, y] =
SexprList [ sinterStdlib "sub", aVarToSexpr x, aVarToSexpr y ]
primFnToSexpr (Mul ty) [x, y] =
SexprList [ sinterStdlib "mul", aVarToSexpr x, aVarToSexpr y ]
primFnToSexpr (Div ty) [x, y] =
SexprList [ sinterStdlib "div", aVarToSexpr x, aVarToSexpr y ]
primFnToSexpr (Mod ty) [x, y] =
SexprList [ sinterStdlib "mod", aVarToSexpr x, aVarToSexpr y ]
primFnToSexpr (Neg ty) [x] =
SexprList [ sinterStdlib "neg", aVarToSexpr x ]
primFnToSexpr (ShiftL ty) [x, y] =
SexprList [ sinterStdlib "shiftl", aVarToSexpr x, aVarToSexpr y ]
primFnToSexpr (ShiftR ty) [x, y] =
SexprList [ sinterStdlib "shiftr", aVarToSexpr x, aVarToSexpr y ]
primFnToSexpr (BAnd ty) [x, y] =
SexprList [ sinterStdlib "bitwAnd", aVarToSexpr x, aVarToSexpr y ]
primFnToSexpr (BOr ty) [x, y] =
SexprList [ sinterStdlib "bitwOr", aVarToSexpr x, aVarToSexpr y ]
primFnToSexpr (BXOr ty) [x, y] =
SexprList [ sinterStdlib "bitwXor", aVarToSexpr x, aVarToSexpr y ]
primFnToSexpr (LT ty) [x, y] =
SexprList [ sinterStdlib "lt", aVarToSexpr x, aVarToSexpr y ]
primFnToSexpr (LTE ty) [x, y] =
SexprList [ sinterStdlib "lte", aVarToSexpr x, aVarToSexpr y ]
primFnToSexpr (EQ ty) [x, y] =
SexprList [ sinterStdlib "eq", aVarToSexpr x, aVarToSexpr y ]
primFnToSexpr (GTE ty) [x, y] =
SexprList [ sinterStdlib "gte", aVarToSexpr x, aVarToSexpr y ]
primFnToSexpr (GT ty) [x, y] =
SexprList [ sinterStdlib "gt", aVarToSexpr x, aVarToSexpr y ]
-- TODO
primFnToSexpr StrLength [s] = ?sinterStrLen
primFnToSexpr StrHead [s] = ?sinterStrHead
primFnToSexpr StrTail [s] = ?sinterStrTail
primFnToSexpr StrIndex [s, i] = ?sinterStrIndex
primFnToSexpr StrCons [s1, s2] = ?sinterStrCons
primFnToSexpr StrAppend [s1, s2] =
SexprList [ sinterStdlib "strAppend", aVarToSexpr s1, aVarToSexpr s2 ]
primFnToSexpr StrReverse [s] = ?sinterStrReverse
primFnToSexpr StrSubstr [i, j, s] = ?sinterSubstr
-- TODO
primFnToSexpr DoubleExp [d] = ?primFnToSexpr_rhs_25
primFnToSexpr DoubleLog [d] = ?primFnToSexpr_rhs_26
primFnToSexpr DoubleSin [d] = ?primFnToSexpr_rhs_27
primFnToSexpr DoubleCos [d] = ?primFnToSexpr_rhs_28
primFnToSexpr DoubleTan [d] = ?primFnToSexpr_rhs_29
primFnToSexpr DoubleASin [d] = ?primFnToSexpr_rhs_30
primFnToSexpr DoubleACos [d] = ?primFnToSexpr_rhs_31
primFnToSexpr DoubleATan [d] = ?primFnToSexpr_rhs_32
primFnToSexpr DoubleSqrt [d] = ?primFnToSexpr_rhs_33
primFnToSexpr DoubleFloor [d] = ?primFnToSexpr_rhs_34
primFnToSexpr DoubleCeiling [d] = ?primFnToSexpr_rhs_35
-- TODO
primFnToSexpr (Cast x y) [z] = ?primFnToSexpr_rhs_36
primFnToSexpr BelieveMe [_, _, thing] = aVarToSexpr thing
-- ^ I believe this is correct?
primFnToSexpr Crash [fc, reason] =
sinterCrash
||| Create a call to a function which evaluates `in` over `let`
||| let f x = y in z
||| is equivalent to
||| (\f . z) (\x . y)
aLetToSexpr : FC -> (var : Int) -> (val : ANF) -> (in_expr : ANF) -> Sexpr
aLetToSexpr fc var val in_expr =
let
varName = intNameToSinterID var
cFunName = MkSinterID $ ">>let_" ++ ("a" ++ show var) ++ "_<<in_" ++ show fc
val_sexpr = anfToSexpr val
in_sexpr = anfToSexpr in_expr
--cFunDef = SinDef $ cFunName val_sexpr
in
?aLetToSexpr_rhs
anfToSexpr : ANF -> Sexpr
anfToSexpr (AV fc x) =
aVarToSexpr x
anfToSexpr (AAppName fc _ n fArgs) =
let
funName = SexprID $ mangle n
funArgs = map aVarToSexpr fArgs
in
SexprList $ funName :: funArgs
anfToSexpr (AUnderApp fc n missing partArgs) =
let
sinName = SexprID $ mangle n
sinMiss = SexprLit $ SinInt (cast missing) nArgsWidth
nArgs = length partArgs
sinNArgs = SexprLit $ SinInt (cast nArgs) nArgsWidth
-- number of args function expects
sinArity = SexprLit $ SinInt (cast (missing + nArgs)) nArgsWidth
-- list of arguments
sinArgs = SexprList $ map aVarToSexpr partArgs
in
-- make a closure containing the above info (sinter-specific closure)
SexprList [sinterClosureCon , sinName , sinArity , sinNArgs , sinArgs]
-- application of a closure to another argument; potentially to the last arg
anfToSexpr (AApp fc _ closure arg) =
let
sinClosure = aVarToSexpr closure
sinArg = aVarToSexpr arg
in
SexprList [sinterClosureAdd, sinClosure, sinArg]
anfToSexpr (ALet fc var let_expr in_expr) =
aLetToSexpr fc var let_expr in_expr
anfToSexpr (ACon fc n tag xs) =
let
(MkSinterID mn) = mangle n
name = MkSinterID $ mn ++ show tag
fArgs = map aVarToSexpr xs
in
SexprList $ (SexprID name) :: fArgs
anfToSexpr (AOp fc _ fn args) = primFnToSexpr fn args
anfToSexpr (AExtPrim fc _ n args) = ?anfToSexpr_rhs_8
anfToSexpr (AConCase fc avar alts m_default) = ?anfToSexpr_rhs_9
anfToSexpr (AConstCase fc x xs y) = ?anfToSexpr_rhs_10
anfToSexpr (APrimVal fc c) = constantToSexpr c
anfToSexpr (AErased fc) =
SexprLit $ SinInt 0 0
anfToSexpr (ACrash fc x) =
sinterCrash
compileANF : (Name, ANFDef) -> Core SinterGlobal
compileANF (n, (MkAFun args body)) =
let
sinName = mangle n
sinArgs = map intNameToSinterID args
sinBody = anfToSexpr body
in
pure $ SinDef sinName sinArgs sinBody
compileANF (n, (MkACon tag arity def)) = ?compileANF_rhs_3
compileANF (n, (MkAForeign ccs fargs x)) = ?compileANF_rhs_4
compileANF (n, (MkAError e)) = ?compileANF_rhs_5
----------------
-- TOP OF API --
----------------
compile : Ref Ctxt Defs -> (tmpDir : String) -> (outputDir : String) ->
ClosedTerm -> (outfile : String) -> Core (Maybe String)
compile context tmpDir outputDir term outfile =
do compData <- getCompileData False ANF term
let defs = anf compData
sinterGlobs <- traverse compileANF defs
-- readyForCG <- traverse bubbleLets sinterGlobs
?compile_rhs
execute : Ref Ctxt Defs -> (tmpDir : String) -> ClosedTerm -> Core ()
execute context tmpDir term =
throw $ InternalError "Sinter backend can only compile, sorry."
sinterCodegen : Codegen
sinterCodegen = MkCG compile execute
main : IO ()
main = mainWithCodegens [("sinter", sinterCodegen)]
|
module Program
import CommonTestingStuff
export
beforeString : String
beforeString = "before coop"
export
program : PrintString m => CanSleep m => Zippable m => Alternative m => m Unit
program = do
offset <- currentTime
printTime offset "start"
(<|>) (sleepFor 1.seconds) $
ignore $ zip {a=Unit} {b=Unit}
(forever $ do
printTime offset "proc 1, one"
printTime offset "proc 1, another")
(forever $ do
printTime offset " proc 2, one"
printTime offset " proc 2, another")
printTime offset "end"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.