text
stringlengths 0
3.34M
|
---|
On 14 June 2004 , Stansfield returned to the Conference with Hereford United , signed by Graham Turner to replace their previous season 's top scorer Steve Guinan , who had been sold to Cheltenham Town . He scored 20 goals across the season , including two on 25 March 2005 in a 6 – 0 win at Farnborough Town . In that match , he came on in the 77th minute for Daniel Carey @-@ Bertram , who had also scored two . Hereford reached the promotion play @-@ offs , where they lost in the semi @-@ finals to Stevenage . In the following season they won promotion by the play @-@ offs , with Stansfield starting in the final on 20 May 2006 at the Walkers Stadium in Leicester , a 3 – 2 extra @-@ time victory over Halifax Town .
|
function determ = line_adj_determinant ( n )
%*****************************************************************************80
%
%% LINE_ADJ_DETERM returns the determinant of the LINE_ADJ matrix.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 15 October 2007
%
% Author:
%
% John Burkardt
%
% Parameters:
%
% Input, integer N, the order of A.
%
% Output, real DETERM, the determinant.
%
if ( mod ( n, 4 ) == 1 )
determ = 0.0;
elseif ( mod ( n, 4 ) == 2 )
determ = - 1.0;
elseif ( mod ( n, 4 ) == 3 )
determ = 0.0;
elseif ( mod ( n, 4 ) == 0 )
determ = + 1.0;
end
return
end
|
/-
Copyright (c) 2020 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth, Yury Kudryashov, Frédéric Dupuis
! This file was ported from Lean 3 source module topology.algebra.infinite_sum.module
! leanprover-community/mathlib commit 32253a1a1071173b33dc7d6a218cf722c6feb514
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Topology.Algebra.InfiniteSum.Basic
import Mathbin.Topology.Algebra.Module.Basic
/-! # Infinite sums in topological vector spaces -/
variable {ι R R₂ M M₂ : Type _}
section SmulConst
variable [Semiring R] [TopologicalSpace R] [TopologicalSpace M] [AddCommMonoid M] [Module R M]
[ContinuousSMul R M] {f : ι → R}
theorem HasSum.smul_const {r : R} (hf : HasSum f r) (a : M) : HasSum (fun z => f z • a) (r • a) :=
hf.map ((smulAddHom R M).flip a) (continuous_id.smul continuous_const)
#align has_sum.smul_const HasSum.smul_const
theorem Summable.smul_const (hf : Summable f) (a : M) : Summable fun z => f z • a :=
(hf.HasSum.smul_const _).Summable
#align summable.smul_const Summable.smul_const
theorem tsum_smul_const [T2Space M] (hf : Summable f) (a : M) : (∑' z, f z • a) = (∑' z, f z) • a :=
(hf.HasSum.smul_const _).tsum_eq
#align tsum_smul_const tsum_smul_const
end SmulConst
section HasSum
-- Results in this section hold for continuous additive monoid homomorphisms or equivalences but we
-- don't have bundled continuous additive homomorphisms.
variable [Semiring R] [Semiring R₂] [AddCommMonoid M] [Module R M] [AddCommMonoid M₂] [Module R₂ M₂]
[TopologicalSpace M] [TopologicalSpace M₂] {σ : R →+* R₂} {σ' : R₂ →+* R} [RingHomInvPair σ σ']
[RingHomInvPair σ' σ]
/-- Applying a continuous linear map commutes with taking an (infinite) sum. -/
protected theorem ContinuousLinearMap.hasSum {f : ι → M} (φ : M →SL[σ] M₂) {x : M}
(hf : HasSum f x) : HasSum (fun b : ι => φ (f b)) (φ x) := by
simpa only using hf.map φ.to_linear_map.to_add_monoid_hom φ.continuous
#align continuous_linear_map.has_sum ContinuousLinearMap.hasSum
alias ContinuousLinearMap.hasSum ← HasSum.mapL
#align has_sum.mapL HasSum.mapL
protected theorem ContinuousLinearMap.summable {f : ι → M} (φ : M →SL[σ] M₂) (hf : Summable f) :
Summable fun b : ι => φ (f b) :=
(hf.HasSum.mapL φ).Summable
#align continuous_linear_map.summable ContinuousLinearMap.summable
alias ContinuousLinearMap.summable ← Summable.mapL
#align summable.mapL Summable.mapL
protected theorem ContinuousLinearMap.map_tsum [T2Space M₂] {f : ι → M} (φ : M →SL[σ] M₂)
(hf : Summable f) : φ (∑' z, f z) = ∑' z, φ (f z) :=
(hf.HasSum.mapL φ).tsum_eq.symm
#align continuous_linear_map.map_tsum ContinuousLinearMap.map_tsum
include σ'
/-- Applying a continuous linear map commutes with taking an (infinite) sum. -/
protected theorem ContinuousLinearEquiv.hasSum {f : ι → M} (e : M ≃SL[σ] M₂) {y : M₂} :
HasSum (fun b : ι => e (f b)) y ↔ HasSum f (e.symm y) :=
⟨fun h => by simpa only [e.symm.coe_coe, e.symm_apply_apply] using h.mapL (e.symm : M₂ →SL[σ'] M),
fun h => by simpa only [e.coe_coe, e.apply_symm_apply] using (e : M →SL[σ] M₂).HasSum h⟩
#align continuous_linear_equiv.has_sum ContinuousLinearEquiv.hasSum
/-- Applying a continuous linear map commutes with taking an (infinite) sum. -/
protected theorem ContinuousLinearEquiv.has_sum' {f : ι → M} (e : M ≃SL[σ] M₂) {x : M} :
HasSum (fun b : ι => e (f b)) (e x) ↔ HasSum f x := by
rw [e.has_sum, ContinuousLinearEquiv.symm_apply_apply]
#align continuous_linear_equiv.has_sum' ContinuousLinearEquiv.has_sum'
protected theorem ContinuousLinearEquiv.summable {f : ι → M} (e : M ≃SL[σ] M₂) :
(Summable fun b : ι => e (f b)) ↔ Summable f :=
⟨fun hf => (e.HasSum.1 hf.HasSum).Summable, (e : M →SL[σ] M₂).Summable⟩
#align continuous_linear_equiv.summable ContinuousLinearEquiv.summable
theorem ContinuousLinearEquiv.tsum_eq_iff [T2Space M] [T2Space M₂] {f : ι → M} (e : M ≃SL[σ] M₂)
{y : M₂} : (∑' z, e (f z)) = y ↔ (∑' z, f z) = e.symm y :=
by
by_cases hf : Summable f
·
exact
⟨fun h => (e.has_sum.mp ((e.summable.mpr hf).hasSum_iff.mpr h)).tsum_eq, fun h =>
(e.has_sum.mpr (hf.has_sum_iff.mpr h)).tsum_eq⟩
· have hf' : ¬Summable fun z => e (f z) := fun h => hf (e.summable.mp h)
rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable hf']
exact
⟨by
rintro rfl
simp, fun H => by simpa using congr_arg (fun z => e z) H⟩
#align continuous_linear_equiv.tsum_eq_iff ContinuousLinearEquiv.tsum_eq_iff
protected theorem ContinuousLinearEquiv.map_tsum [T2Space M] [T2Space M₂] {f : ι → M}
(e : M ≃SL[σ] M₂) : e (∑' z, f z) = ∑' z, e (f z) :=
by
refine' symm (e.tsum_eq_iff.mpr _)
rw [e.symm_apply_apply _]
#align continuous_linear_equiv.map_tsum ContinuousLinearEquiv.map_tsum
end HasSum
|
State Before: α : Type u_1
β : Type ?u.65317
inst✝¹ : TopologicalSpace α
inst✝ : TopologicalSpace β
n : ℕ
i : Fin (n + 1)
a : α
l : List α
hl : List.length l = n
⊢ Tendsto (fun p => insertNth p.fst i p.snd) (𝓝 a ×ˢ 𝓝 { val := l, property := hl })
(𝓝 (insertNth a i { val := l, property := hl })) State After: α : Type u_1
β : Type ?u.65317
inst✝¹ : TopologicalSpace α
inst✝ : TopologicalSpace β
n : ℕ
i : Fin (n + 1)
a : α
l : List α
hl : List.length l = n
⊢ Tendsto (fun x => ↑(insertNth x.fst i x.snd)) (𝓝 a ×ˢ 𝓝 { val := l, property := hl })
(𝓝
↑{ val := List.insertNth (↑i) a ↑{ val := l, property := hl },
property := (_ : List.length (List.insertNth (↑i) a ↑{ val := l, property := hl }) = n + 1) }) Tactic: rw [insertNth, tendsto_subtype_rng] State Before: α : Type u_1
β : Type ?u.65317
inst✝¹ : TopologicalSpace α
inst✝ : TopologicalSpace β
n : ℕ
i : Fin (n + 1)
a : α
l : List α
hl : List.length l = n
⊢ Tendsto (fun x => ↑(insertNth x.fst i x.snd)) (𝓝 a ×ˢ 𝓝 { val := l, property := hl })
(𝓝
↑{ val := List.insertNth (↑i) a ↑{ val := l, property := hl },
property := (_ : List.length (List.insertNth (↑i) a ↑{ val := l, property := hl }) = n + 1) }) State After: α : Type u_1
β : Type ?u.65317
inst✝¹ : TopologicalSpace α
inst✝ : TopologicalSpace β
n : ℕ
i : Fin (n + 1)
a : α
l : List α
hl : List.length l = n
⊢ Tendsto (fun x => List.insertNth (↑i) x.fst ↑x.snd) (𝓝 a ×ˢ 𝓝 { val := l, property := hl })
(𝓝 (List.insertNth (↑i) a l)) Tactic: simp [insertNth_val] State Before: α : Type u_1
β : Type ?u.65317
inst✝¹ : TopologicalSpace α
inst✝ : TopologicalSpace β
n : ℕ
i : Fin (n + 1)
a : α
l : List α
hl : List.length l = n
⊢ Tendsto (fun x => List.insertNth (↑i) x.fst ↑x.snd) (𝓝 a ×ˢ 𝓝 { val := l, property := hl })
(𝓝 (List.insertNth (↑i) a l)) State After: no goals Tactic: exact List.tendsto_insertNth tendsto_fst (Tendsto.comp continuousAt_subtype_val tendsto_snd : _) |
State Before: a b : Int
e : a = ↑(natAbs a)
⊢ ↑(natAbs a) ∣ b ↔ a ∣ b State After: no goals Tactic: rw [← e] State Before: a b : Int
e : a = -↑(natAbs a)
⊢ ↑(natAbs a) ∣ b ↔ a ∣ b State After: no goals Tactic: rw [← Int.neg_dvd, ← e] |
% Add SDP solver into the MATLAB path
function [success] = initSDP()
% restoredefaultpath;
addpath(genpath('../Solver/SDPNAL+v1.0/'), path);
%
end |
theory LaunchburyStacked
imports Terms Heap
begin
subsubsection {* The stackful natural semantics *}
text {* This semantics is a slight modification of the original semantics:
\begin{itemize}
\item The expression to be evaluated is the first element in the second associative list (the ``stack'').
\item To evaluate a variable its binding is moved on top of the stack.
\item When an application @{term "f x"} is evaluated, a new name @{term n} is created, the expression to be
evaluated is remembered as @{term "n x"} and @{term "(n, f)"} is put on top of the stack.
\end{itemize}
*}
inductive reds :: "heap \<Rightarrow> heap \<Rightarrow> heap \<Rightarrow> heap \<Rightarrow> bool" ("_ : _ \<Down> _ : _" [50,50,50,50] 50)
where
Lambda:
"\<Gamma> : (x, (Lam [y]. e)) # \<Gamma>' \<Down> \<Gamma> : (x, (Lam [y]. e)) # \<Gamma>'"
| Application: "\<lbrakk>
atom n \<sharp> (\<Gamma>,\<Gamma>',\<Delta>,\<Delta>',x,e,y,\<Theta>,\<Theta>',z);
atom z \<sharp> (\<Gamma>,\<Gamma>',\<Delta>,\<Delta>',x,e,y,\<Theta>,\<Theta>');
\<Gamma> : (n, e) # (x, App (Var n) y) # \<Gamma>' \<Down> \<Delta> : (n, Lam [z]. e') # (x, App (Var n) y) # \<Delta>';
\<Delta> : (x, e'[z ::= y]) # \<Delta>' \<Down> \<Theta> : \<Theta>'
\<rbrakk> \<Longrightarrow>
\<Gamma> : (x, App e y) # \<Gamma>' \<Down> \<Theta> : \<Theta>'"
| Variable: "\<lbrakk>
(y, e) \<in> set \<Gamma>;
delete y \<Gamma> : (y, e) # (x,Var y) # \<Gamma>' \<Down> \<Delta> : (y, z) # (x, Var y) # \<Delta>'
\<rbrakk> \<Longrightarrow>
\<Gamma> : (x, Var y) # \<Gamma>' \<Down> (y, z) # \<Delta> : (x, z) # \<Delta>'"
| Let: "\<lbrakk>
set (bn as) \<sharp>* (\<Gamma>, x, \<Gamma>');
asToHeap as @ \<Gamma> : (x, body) # \<Gamma>' \<Down> \<Delta> : \<Delta>'
\<rbrakk> \<Longrightarrow>
\<Gamma> : (x, Let as body) # \<Gamma>' \<Down> \<Delta> : \<Delta>'"
equivariance reds
nominal_inductive reds
avoids Application: "n" and "z"
by (auto simp add: fresh_star_def fresh_Cons fresh_Pair)
subsubsection {* Example evaluations *}
lemma eval_test:
"y \<noteq> x \<Longrightarrow> [] : [(x, Let (ACons y (Lam [z]. Var z) ANil) (Var y))] \<Down> [(y, Lam [z]. Var z)] : [(x, (Lam [z]. Var z))]"
by (auto intro!: Lambda Application Variable Let
simp add: fresh_Pair fresh_Cons fresh_Nil fresh_star_def exp_assn.bn_defs fresh_at_base)
lemma eval_test2:
"y \<noteq> x \<Longrightarrow> z \<noteq> y \<Longrightarrow> z \<noteq> x \<Longrightarrow> [] : [(x, Let (ACons y (Lam [z]. Var z) ANil) (App (Var y) y))] \<Down> [(y, Lam [z]. Var z)] : [(x, (Lam [z]. Var z))]"
apply (rule Let)
apply (simp add: fresh_Pair fresh_Cons fresh_at_base fresh_Nil fresh_star_def exp_assn.bn_defs)
apply simp
apply (rule obtain_fresh)
apply (erule Application[where z = z])
defer
apply (rule Variable, simp)
apply (rule Lambda)
apply simp
apply (rule Variable, simp)
apply simp
apply (rule Lambda)
apply (simp add: fresh_Pair fresh_Cons fresh_at_base fresh_Nil fresh_star_def)
done
subsubsection {* Properties of the semantics *}
text {*
This is the same semantics with additional distinctiveness requirements. This is defined in order to
obtain a more convenient induction rule.
*}
inductive distinct_reds :: "heap \<Rightarrow> heap \<Rightarrow> heap \<Rightarrow> heap \<Rightarrow> bool" ("_ : _ \<Down>d _ : _" [50,50,50,50] 50)
where
DLambda: "\<lbrakk>
distinctVars ((x, (Lam [y]. e)) # \<Gamma>' @ \<Gamma>)
\<rbrakk> \<Longrightarrow>
\<Gamma> : (x, (Lam [y]. e)) # \<Gamma>' \<Down>d \<Gamma> : (x, (Lam [y]. e)) # \<Gamma>'"
| DApplication: "\<lbrakk>
atom n \<sharp> (\<Gamma>,\<Gamma>',\<Delta>,\<Delta>',x,e,y,\<Theta>,\<Theta>',z);
atom z \<sharp> (\<Gamma>,\<Gamma>',\<Delta>,\<Delta>',x,e,y,\<Theta>,\<Theta>');
distinctVars (((x, App e y) # \<Gamma>') @ \<Gamma>);
distinctVars (((n, e) # (x, App (Var n) y) # \<Gamma>') @ \<Gamma>);
distinctVars (((n, Lam [z]. e') # (x, App (Var n) y) # \<Delta>') @ \<Delta>);
distinctVars (((x, e'[z ::= y]) # \<Delta>') @ \<Delta>);
distinctVars (\<Theta>' @ \<Theta>);
\<Gamma> : (n, e) # (x, App (Var n) y) # \<Gamma>' \<Down>d \<Delta> : (n, Lam [z]. e') # (x, App (Var n) y) # \<Delta>';
\<Delta> : (x, e'[z ::= y]) # \<Delta>' \<Down>d \<Theta> : \<Theta>'
\<rbrakk> \<Longrightarrow>
\<Gamma> : (x, App e y) # \<Gamma>' \<Down>d \<Theta> : \<Theta>'"
| DVariable: "\<lbrakk>
(y, e) \<in> set \<Gamma>;
distinctVars (((x, Var y) # \<Gamma>') @ \<Gamma>);
distinctVars (((y, e) # (x,Var y) # \<Gamma>') @ delete y \<Gamma>);
distinctVars (((y, z) # (x, Var y) # \<Delta>') @ \<Delta>);
distinctVars (((x, z) # \<Delta>') @ (y, z) # \<Delta>);
delete y \<Gamma> : (y, e) # (x,Var y) # \<Gamma>' \<Down>d \<Delta> : (y, z) # (x, Var y) # \<Delta>'
\<rbrakk> \<Longrightarrow>
\<Gamma> : (x, Var y) # \<Gamma>' \<Down>d (y, z) # \<Delta> : (x, z) # \<Delta>'"
| DLet: "\<lbrakk>
set (bn as) \<sharp>* (\<Gamma>, x, \<Gamma>');
distinctVars (((x, Let as body) # \<Gamma>') @ \<Gamma>);
distinctVars (((x, body) # \<Gamma>') @ asToHeap as @ \<Gamma>);
distinctVars (\<Delta>' @ \<Delta>);
asToHeap as @ \<Gamma> : (x, body) # \<Gamma>' \<Down>d \<Delta> : \<Delta>'
\<rbrakk> \<Longrightarrow>
\<Gamma> : (x, Let as body) # \<Gamma>' \<Down>d \<Delta> : \<Delta>'"
equivariance distinct_reds
nominal_inductive distinct_reds
avoids DApplication: "n" and "z"
apply (auto simp add: fresh_star_def fresh_Cons fresh_Pair)
done
lemma distinct_redsD1:
"\<Gamma> : \<Gamma>' \<Down>d \<Delta> : \<Delta>' \<Longrightarrow> \<Gamma> : \<Gamma>' \<Down> \<Delta> : \<Delta>'"
apply (nominal_induct rule: distinct_reds.strong_induct)
apply (auto intro:reds.intros simp add: fresh_star_Pair fresh_Pair)
done
lemma distinct_redsD2:
"\<Gamma> : \<Gamma>' \<Down>d \<Delta> : \<Delta>' \<Longrightarrow> distinctVars (\<Gamma>'@\<Gamma>)"
apply (nominal_induct rule: distinct_reds.strong_induct)
apply (auto)
done
lemma distinct_redsD3:
"\<Gamma> : \<Gamma>' \<Down>d \<Delta> : \<Delta>' \<Longrightarrow> distinctVars (\<Delta>'@\<Delta>)"
apply (nominal_induct rule: distinct_reds.strong_induct)
apply (auto)
done
lemma distinct_redsI:
"\<Gamma> : \<Gamma>' \<Down> \<Delta> : \<Delta>' \<Longrightarrow> distinctVars (\<Gamma>'@\<Gamma>) \<Longrightarrow> \<Gamma> : \<Gamma>' \<Down>d \<Delta> : \<Delta>'"
proof (nominal_induct rule: reds.strong_induct)
case Lambda thus ?case by (auto intro: distinct_reds.intros)
next
case (Application n \<Gamma> \<Gamma>' \<Delta> \<Delta>' x e y \<Theta> \<Theta>' z e')
have "atom n \<sharp> (\<Gamma>, \<Gamma>',\<Delta>,\<Delta>',x, e, y, \<Theta>, \<Theta>',z)"
using Application by simp
moreover
have "atom z \<sharp> (\<Gamma>, \<Gamma>', \<Delta>, \<Delta>', x, e, y, \<Theta>, \<Theta>')"
using Application by simp
moreover
assume "distinctVars (((x, App e y) # \<Gamma>') @ \<Gamma>)"
moreover
have "atom n \<sharp> (((x, App e y) # \<Gamma>') @ \<Gamma>)"
using Application
by (simp add: fresh_Cons fresh_Pair fresh_append)
hence "n \<notin> heapVars (((x, App e y) # \<Gamma>') @ \<Gamma>)"
by (metis heapVars_not_fresh)
with `distinctVars (((x, App e y) # \<Gamma>') @ \<Gamma>)`
have "distinctVars (((n, e) # (x, App (Var n) y) # \<Gamma>') @ \<Gamma>)"
by (simp add: distinctVars_append distinctVars_Cons)
moreover
note hyp1 = Application.hyps(21)[OF this]
note distinct_redsD3[OF hyp1]
moreover
hence "distinctVars (((x, e'[z::=y]) # \<Delta>') @ \<Delta>)"
by (simp add: distinctVars_append distinctVars_Cons)
moreover
note hyp2 = Application.hyps(23)[OF this]
note distinct_redsD3[OF hyp2]
moreover
note hyp1
moreover
note hyp2
ultimately
show ?case
by (rule DApplication[where n = n and z = z])
next
case (Variable y e \<Gamma> x \<Gamma>' \<Delta> z \<Delta>')
assume "(y, e) \<in> set \<Gamma>"
moreover
assume "distinctVars (((x, Var y) # \<Gamma>') @ \<Gamma>)"
moreover
have "distinctVars (((y, e) # (x, Var y) # \<Gamma>') @ delete y \<Gamma>)"
using Variable(1,4)
by (auto simp add: distinctVars_append distinctVars_Cons intro: distinctVars_delete heapVars_from_set)
moreover
note hyp = Variable.hyps(3)[OF this]
note distinct_redsD3[OF hyp]
moreover
hence "distinctVars (((x, z) # \<Delta>') @ (y, z) # \<Delta>)"
by (auto simp add: distinctVars_append distinctVars_Cons)
moreover
note hyp
ultimately
show ?case
by (rule DVariable)
next
case (Let as \<Gamma> x \<Gamma>' body \<Delta> \<Delta>')
hence "set (bn as) \<sharp>* (((x, Let as body) # \<Gamma>') @ \<Gamma>)"
by (auto simp add: fresh_star_Pair fresh_star_list)
hence "heapVars (asToHeap as) \<inter> heapVars (((x, Terms.Let as body) # \<Gamma>') @ \<Gamma>) = {}"
by (rule fresh_assn_distinct)
have "set (bn as) \<sharp>* (\<Gamma>, x, \<Gamma>')"
using Let by (simp add: fresh_star_Pair fresh_star_list)
moreover
assume "distinctVars (((x, Terms.Let as body) # \<Gamma>') @ \<Gamma>)"
moreover
hence "distinctVars (((x, body) # \<Gamma>') @ asToHeap as @ \<Gamma>)"
using `_ = {}`
by (auto simp add: distinctVars_append distinctVars_Cons)
moreover
note hyp = Let.hyps(5)[OF this]
note distinct_redsD3[OF hyp]
moreover
note hyp
ultimately
show ?case
by (rule DLet)
qed
lemma reds_pres_distinctVars:
"\<Gamma> : \<Gamma>' \<Down> \<Delta> : \<Delta>' \<Longrightarrow> distinctVars (\<Gamma>'@\<Gamma>) \<Longrightarrow> distinctVars (\<Delta>'@\<Delta>)"
by (metis distinct_redsD3 distinct_redsI)
lemmas reds_distinct_ind = distinct_reds.induct[OF distinct_redsI, consumes 2, case_names Lambda Application Variable Let]
lemmas reds_distinct_strong_ind = distinct_reds.strong_induct[OF distinct_redsI, consumes 2, case_names Lambda Application Variable Let]
lemma reds_doesnt_forget':
assumes "\<Gamma> : \<Gamma>' \<Down>d \<Delta> : \<Delta>'"
shows "heapVars \<Gamma> \<subseteq> heapVars \<Delta>" and "heapVars \<Gamma>' \<subseteq> heapVars \<Delta>'"
using assms
proof(induct rule: distinct_reds.induct)
case DLambda
case 1 show ?case by simp
case 2 show ?case by simp
next
case (DApplication n \<Gamma> \<Gamma>' \<Delta> \<Delta>' x e y \<Theta> \<Theta>' z e')
case 1
show ?case
using DApplication by simp
case 2
show ?case
proof
fix v
assume "v \<in> heapVars ((x, App e y) # \<Gamma>')"
hence "\<not>( atom v \<sharp> (x, App e y) # \<Gamma>')"
by (rule heapVars_not_fresh)
hence "v \<noteq> n"
by (metis DApplication(1) exp_assn.fresh(2) fresh_Cons fresh_Pair)
assume "v \<in> heapVars ((x, App e y) # \<Gamma>')"
hence "v \<in> heapVars ((n, e) # (x, App (Var n) y) # \<Gamma>')" by simp
hence "v \<in> heapVars ((n, Lam [z]. e') # (x, App (Var n) y) # \<Delta>')"
by (rule set_mp[OF DApplication(10)])
hence "v \<in> heapVars ((x, e'[z::=y]) # \<Delta>')"
using `v \<noteq> n` by simp
thus "v \<in> heapVars \<Theta>'"
by (rule set_mp[OF DApplication(13)])
qed
next
case (DVariable y e \<Gamma> x \<Gamma>' z \<Delta>' \<Delta>)
case 1
from DVariable(7)
show ?case by auto
case 2
from DVariable(3)
have "y \<notin> heapVars ((x, Var y) # \<Gamma>')"
by (metis distinctVars_ConsD(1) distinctVars_appendD1)
with DVariable(8)
show ?case
by auto
next
case (DLet as \<Gamma> x body \<Gamma>' \<Delta>' \<Delta>)
case 1 show ?case using DLet by simp
case 2 show ?case using DLet by simp
qed
text {* Heap entries are never removed. *}
lemma reds_doesnt_forget:
assumes "\<Gamma> : \<Gamma>' \<Down> \<Delta> : \<Delta>'"
assumes "distinctVars (\<Gamma>'@\<Gamma>)"
shows "heapVars \<Gamma> \<subseteq> heapVars \<Delta>" and "heapVars \<Gamma>' \<subseteq> heapVars \<Delta>'"
by (rule reds_doesnt_forget'[OF distinct_redsI[OF assms]])+
text {* The stack is never empty. *}
lemma stack_not_empty:
assumes "\<Gamma> : \<Gamma>' \<Down> \<Delta> : \<Delta>'"
shows "\<Delta>' \<noteq> []"
using assms
by (induct rule:reds.induct, simp_all)
text {* Evaluation does not change the name of the evaluation variable. *}
lemma stack_same_head:
assumes "\<Gamma> : \<Gamma>' \<Down> \<Delta> : \<Delta>'"
shows "fst (hd \<Delta>') = fst (hd \<Gamma>')"
using assms
by (induct rule:reds.induct, simp_all)
text {* Evaluation does not touch the tail of the stack. *}
lemma stack_unchanged:
assumes "\<Gamma> : (x, e) # \<Gamma>' \<Down> \<Delta> : (x, e') # \<Delta>'"
shows "\<Delta>' = \<Gamma>'"
proof-
{fix \<Gamma>' \<Delta>'
have "\<Gamma> : \<Gamma>' \<Down> \<Delta> : \<Delta>' \<Longrightarrow> tl \<Delta>' = tl \<Gamma>'"
by (induct rule:reds.induct, simp_all)
}
from this[OF assms]
show ?thesis by simp
qed
text {*
Fresh variables either stay fresh or are added to the heap.
*}
lemma reds_fresh':" \<lbrakk> \<Gamma> : \<Gamma>' \<Down>d \<Delta> : \<Delta>';
atom (x::var) \<sharp> (\<Gamma> , snd (hd \<Gamma>'))
\<rbrakk> \<Longrightarrow> atom x \<sharp> (\<Delta>, snd (hd \<Delta>')) \<or> x \<in> heapVars \<Delta>"
proof(nominal_induct avoiding: x rule: distinct_reds.strong_induct)
case (DLambda \<Gamma> x e) thus ?case by auto
next
case (DApplication n \<Gamma> \<Gamma>' \<Delta> \<Delta>' xa e y \<Theta> \<Theta>' z e' x)
from DApplication have [simp]:"atom x \<sharp> \<Gamma>" "atom x \<sharp> e" "atom x \<sharp> y" by (simp add: fresh_Pair)+
from `atom n \<sharp> x` have [simp]:"atom x \<sharp> n" by (metis fresh_at_base(2))
have [simp]:"atom z \<sharp> y" by fact
have "atom x \<sharp> (\<Gamma>, snd (hd ((n, e) # (xa, App (Var n) y) # \<Gamma>')))"
by simp
from DApplication.hyps(28)[OF this, simplified]
have "atom x \<sharp> (\<Delta>, Lam [z]. e') \<or> x \<in> heapVars \<Delta>".
thus ?case
proof
assume "atom x \<sharp> (\<Delta>, Lam [z]. e')"
hence [simp]:"atom x \<sharp> \<Delta>" by simp
assume "atom x \<sharp> (\<Delta>, Lam [z]. e')"
hence "atom x \<sharp> e' \<or> x = z"
by (simp add: fresh_Pair)+
hence "atom x \<sharp> (\<Delta>, snd (hd ((xa, e'[z::=y]) # \<Delta>')))"
proof
assume "atom x \<sharp> e'"
thus ?thesis
by (simp add: fresh_Pair subst_pres_fresh[rule_format])
next
assume "x = z"
hence "z = x" by (rule sym)
thus ?thesis
by (auto intro!:subst_is_fresh simp add: fresh_Pair)
qed
thus ?thesis
by (rule DApplication)
next
assume "x \<in> heapVars \<Delta>"
thus ?thesis
using reds_doesnt_forget'(1)[OF DApplication.hyps(29)]
by auto
qed
next
case(DVariable y e \<Gamma> xa \<Gamma>' z \<Delta>' \<Delta> x)
from `atom x \<sharp> _` ` (y, e) \<in> set \<Gamma>`
have "atom x \<sharp> delete y \<Gamma>" and "atom x \<sharp> e"
by (auto intro: fresh_delete dest:fresh_list_elem simp add: fresh_Pair)
hence "atom x \<sharp> (\<Delta>, snd (hd ((y, z) # (xa, Var y) # \<Delta>'))) \<or> x \<in> heapVars \<Delta>"
by -(rule DVariable, simp add: fresh_Pair)
thus ?case
by (auto simp add: fresh_Pair fresh_Cons fresh_at_base)
next
case (DLet as \<Gamma> xa body \<Gamma>' \<Delta>' \<Delta> x)
show ?case
proof (cases "atom x \<in> set (bn as)")
case False
hence "atom x \<sharp> as" using DLet.prems by(auto simp add: fresh_Pair)
show ?thesis
apply(rule DLet.hyps(8))
using DLet.prems `atom x \<sharp> as` False
by (auto simp add: fresh_Pair fresh_append fresh_fun_eqvt_app[OF asToHeap_eqvt])
next
case True
hence "x \<in> heapVars (asToHeap as)"
by(induct as rule:asToHeap.induct)(auto simp add: exp_assn.bn_defs)
thus ?thesis using reds_doesnt_forget'[OF DLet.hyps(7)] by auto
qed
qed
lemma reds_fresh: " \<lbrakk> \<Gamma> : (y, e) # \<Gamma>' \<Down>d \<Delta> : (y, z) # \<Delta>';
atom (x::var) \<sharp> (\<Gamma> , e)
\<rbrakk> \<Longrightarrow> atom x \<sharp> (\<Delta>, z) \<or> x \<in> heapVars \<Delta>"
by (metis (hide_lams, no_types) hd.simps reds_fresh' snd_conv)
end
|
module Logic.DiagonalProof {ℓ₁} {ℓ₂} where
import Lvl
open import Logic.Propositional{ℓ₁ Lvl.⊔ ℓ₂}
open import Logic.Predicate{ℓ₁}{ℓ₂}
open import Functional
open import Relator.Equals{ℓ₁}{ℓ₂}
open import Relator.Equals.Proofs{ℓ₁}{ℓ₂}
open import Type{ℓ₂}
diagonal-proof : ∀{T₁ T₂ : Type}(diff-oper : T₂ → T₂) → (∀{x} → (x ≢ diff-oper(x))) → (ff : T₁ → T₁ → T₂) → ∃{T₁ → T₂}(f ↦ (∀{a : T₁} → ¬(ff(a)(a) ≡ f(a))))
diagonal-proof(diff-oper)(diff-proof)(ff) = [∃]-intro (a ↦ diff-oper(ff(a)(a))) ⦃ \{a} → diff-proof{ff(a)(a)} ⦄
|
\documentclass[reprint,unsortedaddress,amsmath,amssymb,aps,prl,showkeys]{revtex4-2}
\usepackage{graphicx}% Include figure files
\usepackage{dcolumn}% Align table columns on decimal point
\usepackage{subfigure}
\usepackage{bookmark}
% \usepackage\textbf{{biblatex}}\textbf{}
\usepackage{float}
\usepackage{url}
\usepackage{bm}% bold math
\usepackage{hyperref}% add hypertext capabilities
\usepackage[mathlines]{lineno}% Enable numbering of text and display math
\begin{document}
\title{Vicissitudes of Cities Driven by Re-distributive Growth}
\author{Gezhi Xiu, Jianying Wang, Lei Dong}
\author{Yu Liu}
\email{[email protected]}
\affiliation{Institute of Remote Sensing and Geographic Information Systems (IRSGIS), Peking University}
\date{\today}
\begin{abstract}
We propose a spatial growth model to address how cities emerge, grow, and especially, compete, with limited resource and space. The approach emphasizes on the evolutionary trajectory of cities, simultaneously determined by local (e.g., topography) and regional (e.g., industrial status) conditions, which can be attributed to the competition for redistributive resources in a given space. To model this spatial competition mechanism, our out-of-equilibrium growth model is set with a fixed bound on global growth rates. We discuss two phases of urbanization predicted in our model: (a) free growth phase, and (b) resource constrained phase. Zipf's and Clark's laws in urban sciences are found in (a), indicating realistic urbanization process has not yet reached bottlenecks of resource; And when it reaches, (b) captures the inevitability of various urban diseases, such as urban shrinkage in developed cities and the spatial relocation of developments. Our approach sheds light on analyzing urbanization with early warnings of environmental capacity.
\end{abstract}
\maketitle
% \section{Introduction}
% 研究的是一个什么问题(spatial growth model),这个问题为什么重要?(可以从理论和实践两个角度说,但偏重于理论)% 现在的研究做了什么(现在这块写得太宽泛了,其实相关工作很多,也很具体),有哪些不足?这些不足产生的「可能的」原因是什么?
\textit{Introduction.} Spatial growth models are powerful tools to understand urban growth dynamics~\cite{PhysRevX.4.011008, Li2017Simple, makse1995modelling, rybski2013distance, nanda2017spatial}. Theoretically, such models fill the gap between macroscopic patterns, e.g. socio-economic scalars and material properties, and microscopic dynamics, e.g. individual level interaction patterns; Practically, they investigate how different growth factors contribute to city emergence, and how these dynamics lead to some well-observed scaling law~\cite{bettencourt2007growth,court2013origins,batty2008size,batty2019urbanscalinglaw}, fractality~\cite{batty1994fractal,batty2007cities}, and city size distributions (i.e., Zipf's law)~\cite{zipf1949human}, making quantitative predictions broadly through urban morphology and spatial structures for urban planers and policy makers~\cite{anas1998urban}. These existing works have built natural paths in deriving macroscopic dynamical state from microscopic growth rules. Most of these approaches are based on the assumptions of homogeneous growth in Euclidean geometry. However, recent discoveries of complex spatial phenomena associated with realistic urban systems are better described using fractal or discrete geometry\cite{makse1995modelling,louf2014congestion,PhysRevE.58.7054}, to better consist with growth dynamics in disordered contexts and media. In words, urban space has memory of active components over it. The memory of the potentials to grow are spatially heterogeneous, and adding up which limited by the regional capacity. Such consistent heterogeneity increases the significance of competition essence among cities, over ranking, spaces, and the number of employees.
In this Letter, we introduce a spatial growth model based on inconsistent space and memory-based growth dynamics to describe how cities emerge, grow, and compete over given space and resource. The spatial sprawl of cities and the advance of urbanization are realized by the sequential settlement of new citizens. Here, the location choice of new citizens follows those active population of the whole region, and thus gives the physical form of each city by the exclusive and continuous area containing offspring citizens of the same ancestor. We show that beyond the desolated growth of each city, competitions introduced by spatial specialization and resource limit result in the vicissitudes of cities and urban shrinkage. Our model combines two themes for many disciplines, including probability theory and ecology: The spatial preferential attachment mechanism~\cite{Li2017Simple}, and the existence of environmental capacity under competition~\cite{gude2020bacterial,liu2019an}.
On the first point, the \textit{rich get richer} mechanism is well-observed in social systems, especially, human settlements appear to be clustered hence cities~\cite{marsili1998interacting}. Literature has discussed how urban features emerge from preferential attachment via interaction density~\cite{ccolak2016understanding,louf2014congestion,fujita1976spatial}, e.g., multiplicative or correlated percolation~\cite{makse1995modelling,PhysRevE.58.7054,rybski2013distance}, spatial networks~\cite{marsili1998interacting,court2013origins,Li2017Simple}, and utility maximizing~\cite{PhysRevE.90.042815,axtell2001emergent}. Spatially, such mechanism leads to population clustering near every urban centers. Here, we take the spatial aspect from the idea of diffusion-limited aggregation~\cite{makse1995modelling, rybski2013distance, kleinberg2000navigation}, i.e., in each cities, new comers would settle near those active citizens.
On the second point, cities are systems with environmental capacity, that excessive employees do not guarantee the proportional urban output, considering the tradeoff in infrastructures and congestion. In words, the marginal effect of urbanization leads to decreases in urban attractiveness~\cite{atkinson2012urban, girardin2009quantifying,gomez2018explaining,parris2003characterizing,batty2008size}. These are poorly reflected in the referred works, which are mostly base on certain equilibrium conditions on growth rates or optimization aims~\cite{zipf1949human}, and predict constantly accelerating urbanization process. However, cities are inter-competitive and out-of-equilibrium to be consistent under circumstances towards sustainability\cite{fujita1976spatial,louf2014congestion,ccolak2016understanding}. Thus we include rules for spatial exclusiveness, and bounded growth rate in our model. Existing work has investigated in non-spatial context that systematic capacity puts severe constraints on the patterns of evolution~\cite{PhysRevE.55.R3817}. Here, our restriction are set to intensify inter-city competitions for active population\cite{batty2017urban}. We later prove that our space-relevant model extends the previous non-spatial predictions for city size distributions. These settings also result in realistic urban phenomena like superior switch\cite{gabaix2004evolution}, and urban shrinkage\cite{haase2014conceptualizing}, that cannot be formulated by existing growth models.
% 我们是怎么来解决这个问题的,有哪些重要的贡献。
%These concerns call for a general approach to model the spatial sprawl of emerging cities and their population under sustainable rules, regarding the competitions for space and resource.
% In brief, we propose an out-of-equilibrium spatial preferential growth model with restrictions on the maximum systematic growth rate. Existing work has investigated restrictions, non-spatial context proved that environmental capacity puts severe constraints on the patterns of evolution~\cite{PhysRevE.55.R3817}, such as fluctuations in city rank-size distribution. Our restriction setting is space-relevant, and is proved later to effectively enhance the intensity of competitions,
% \section{Results}
% \subsection{The Spatial Yule Model}
% 我们提出了一个模型,能干什么事儿,有什么好处。
\textit{Spatial Yule Model.} Our model tells how cities emerge, grow, and compete over space. Its dynamics are mainly determined through three quantitative and spatial rules: 1) \textit{Active citizen rule}. During urban growth process, we assume that only 'active' citizens attract new comers to a nearby place in their city, $k$ and $N_i$ are the number of cities and active citizens in the $i$th city, respectively. 2) \textit{Memory kernel rule}. We take $\sum_{i} N_i \le N^*$ ($N^* \gg 1$) as the satiation condition, i.e., when the total population exceeds $N^*$, a new comer would deactivate a random dweller who is previously active. This mechanism keeps only up to $N^*$ active citizens. Therefore we say these $N^*$ people add up to the memory kernel. 3) \emph{Spatial growth rule}. We assume the studied area is an $L\times L$ 2-dimensional continuous space ($L\gg 1$) with grid of cells, %(IN THE BEGINNING, YOU SAID IT'S A continuous space?),
i.e., the locations of citizens are continuous, but the boundaries of cities are discrete on cells. A new city is seeded randomly over the region as a Poisson point process~\cite{miles1970homogeneous}, and survives if its cell is not taken; Every new citizen settles at a constant distance $r\le 1$ and a random angle $\theta$ from its introducer. Once a cell $c$ has held a citizen from the $i$th city, any citizens from another city $j$ ($j\ne i$) cannot introduce new comers on cell $c$. Thus cities are identified through citizens' ancestral introducer and their geographical occupation of blocks.
Based on these rules, we can define the model with a set of two-phase master equations. Specifically, we assume that the probability of a population increase in city $i$ within the time interval $(t,t+dt)$ is $\beta_2N_idt$, where $\beta_2$ is the introduction rate of every active citizen; We also assume that new cities constantly emerge with a small rate $\beta_1kdt$, proportional to the number of cities, where $\beta_1$ is the rate of new city generation. A city's generation is confirmed only if its location is at an empty cell. The master equation can therefore be written as \begin{align}\frac{\partial}{\partial t}N_i(t) = \delta_{N_i(t)}\cdot k\beta_1+ (1-\delta_{N_i(t)})\cdot N_i\beta_2, \end{align} for the free growth phase, where urbanization is weakly dependent with space and resource $N^*$;
%[WHAT'S THE DEFINITION OF FREE GROWTH?],
and \begin{align}
dN_i(t)/dt = \beta_2 N_i(t) -\delta_{\{\sum N_i = N^*\}}\cdot\notag \\ \left(\beta_1k(t) + (N^*-N_i(t))\beta_2 \right)
\end{align}
for the resource constraint phase, where the total resource $N^*$ are partitioned, and new dwellers get resource only through redistribution.
%[WHAT'S THE DEFINITION OF RESOURCE CONSTRAINT PHASE?].
\begin{figure}
\centering
\includegraphics[width = 0.95\linewidth]{pics/sketchgood.pdf}
\caption{\textbf{(a)} Status in the memory kernel at the free growth phase, i.e., the total population is less than $N^*$. Existing citizens introduce new dwellers at the rate $\beta_2$, while each existing city (noted by nodes in different colors) introduces new cities at the rate $\beta_1$. \textbf{(b)} When the memory kernel is fulfilled, every introduction of new city or citizen leads to an ejection of existing active citizen currently included in the memory kernel. \textbf{(c)} The spatial aspect is that, an offspring citizen's placement is at distance $r$ from the ancestral dweller. Also, when the kernel is filled, a new yellow node ejects an existed blue node, or equivalently deprive her ability to introduce. \textbf{(d)} A simulated result for $L$, $r$, $\beta$ equals to $256$, $0.5$, and $4$, respectively. We choose $\beta = 4$ to avoid confusion of too many cities. This is parallel to a quarter of $2L\times 2L$ simulation with $\beta = 1$.}
\label{sketchpic}
\end{figure}
Though $\beta_1$, $\beta_2$ have their actual meaning of generation speed, the model's dynamics and patterns are only determined by the relative growth rate $\beta:= \beta_2/\beta_1$. This is parallel Yule's settings on modeling the distribution of species per genus~\cite{yule1925ii}.
%[WHY SET BETA? WHAT'S THE MEANING OF BETA],
So our model could be regarded as a spatial Yule model with constraints (SYM). A sketch for the SYM is shown in Fig. \ref{sketchpic}.
% 5. 模型需要哪些假设 6. 这些假设有什么理论和实证基础?
% [THE FOLLOWING PARA IS VERY CONFUSING. IF THIS IS ALSO RULES, YOU SHOULD PLACE THEM IN THE ABOVE PARA. IF THIS IS NOT, YOU SHOULD SPLIT THEM AND INSERT INTO THE PLACE THAT INTRODUCE PARAMETERS.]
The model implies some simple assumptions. First, urban developments are density-driven. Literature has suggested that density-driven social ties and interactions comprise an important driver of the economies of scale~\cite{pan2013urban, girardin2009quantifying, batty1992form}. In the SYM, we further assume only the density of attractive population is corresponding to urban developments. Such active part can be recognized as the total employed or productive people. Second, to make an analytic framework, the growth dynamics are set to be homogeneous. The choices of place of new comers are random; The rate of introduction and emergence is the same for every active citizen and every city. This diffusive setting of sequential settlements is also realistic urban growth~\cite{RevModPhys.87.925}.
In the numerical experiments, which is elaborated in \textit{SI}, the truly worth-tuning parameters are three, $\beta$, $r$, and $N^*$. $\beta$ contributes to the Zipf's coefficient and later defined turnover rate~\cite{rooney2006structural}; $r$ contributes to the fractality of urban areas and the time to fill the whole space; $N^*$ is the severeness of resource competition.
% 7. 这个模型能推出哪些结论(1,2,3)。这些结论能如何被数据验证。
% \subsection{The free growth phase}
\textit{The free growth phase.} SYM predicts the existence of three phases of regional growth of cities, distinguished by whether resource and space have been fully occupied: freely growth phase, economic constraint phase, and spatial constraint phase. We focus on the first two phases, which correspond with regional resource. Spatial constraint phase's evolution implies a fully urbanized area, which is unlikely seen in reality, we discuss the situation only in \textit{SI}. In the freely growth phase, cities grow desolately, without being limited by resource and space. In this phase, SYM reformulates two important properties, stately (1) Zipf's law~\cite{gabaix1999zipf's} for rank size distribution of cities' population, and (2) Clark's law for exponential decay of urban density\cite{clark1951urban}.
The populations of cities typically decay proportionally to the inverse of their ranks~\cite{gabaix1999zipf's}. This is referred as Zipf's law of cities' population sizes, i.e., the populations of cities distribute as a power of ranks, $f_r(r)\sim r^{-(1+\eta)}$. It is obvious that $N_i(t)$ has a geometric distribution~\cite{durrett1999essentials}, $P(N_i(t)=n)=e^{-\beta_1t}(1-\exp(- {\beta_1} t))^{n-1}$. Combining which with the assumption that the number of cities will grow exponentially at rate $\beta_1$, if we randomly pick an existing city, the waiting time since its first appearance is exponential with parameter $\beta_1$. Thus the distribution of population of a random city is
\begin{align}
f(n)=\frac{\Gamma(1+1/\beta)\Gamma(n)}{\beta\Gamma(n+1+1/\beta)}\approx Cn^{-1-1/\beta}, \ \text{as } n\to\infty,
\end{align}
where $\Gamma(\cdot)$ is Gamma function. This equation implies a Zipfian relationship with $n(\text{rank})\sim {rank}^{-\beta}$. Noticing that $\beta$ takes value from all positive real number in our model, we can derive arbitrary scaling behaviors by switching $\beta$. According to some studies~\cite{PhysRevLett.79.523}, the power law dependence of population frequency is $2.03\pm 0.05$ for the world, indicating that the average relative emerging rate of cities is around $1$.
Varying $\beta$ also leads to the consideration of different sizes of study area. A small (large) $\beta$ interprets that the emergence of cities is fast (slow), corresponding to a large (smaller) study area. %[HOW ABOUT A LARGER BETA?]
Thus varying $\beta$ is parallel to investigate the spatial density of cities in an urban system. Some urban systems tend to form new cities to have sufficient infrastructures and less diversity of urban output\cite{batty2008size} ($\beta > 1$) and some cities may go otherwise ($\beta< 1$). This value is actually a reflection of the intensity of regional population concentration in large cities. The experiments have confirmed our analytic results for free growth phase in SYM. %[I DON'T UNDERSTAND FROM `IT IS INTERESTING ... IN SYM. WHY THIS VALUE IS A REFECTION?]
A simulated validation for this result can be reflected in Fig.\ref{Fig2}. Notably, when $\beta$s are large ($>2$), the simulated Zipfian exponents are remarkably larger than their theoretical predictions. This is because the competition for space benefits small %[WHY LARGE SMALL CITIES?]
cities resulted from their higher density of edging cells, which is proved in \textit{SI}. For large $\beta$s, however, of the same rank, the probability of successful emergence of new city decreases due to relatively larger area of existing cities. This exasperates the concentration of active population in large cities.%% [UNCLEAR].
\begin{figure}[t]
\centering
\includegraphics[width = .99\linewidth]{pics/zipf_clark.pdf}
\caption{\textbf{(a)} The distribution of population among cities. In the simulation we take $N^* = 10^5$ and alternate $\beta$s. The realistic Zipf's coefficient is reproduced when $\beta\approx 1$. The theoretical predictions of the slopes are $-\beta$, and is well approximated when $\beta$s are small. Larger $\beta$ reduce the chance of latter city's emergence. Thus the spatial aspects of the SYM strengthen inequality. This result confirms that Zipf's law is valid for growing urban systems where all cities share the same rate to grow. From the other master equation we analyze that this observation vanishes if total growing force is finite. \textbf{(b)} The population distribution as a function of distance from a district's center. The vertical axis is logarithmic processed, which represents the exponential decaying of population distribution. Regardless of the finite-sample effect, we fit the middle part of spatial population density to the exponential distribution with a slope of $-1.076$.}
\label{Fig2}
\end{figure}
%% Clark
% [WHAT'S THE LOGIC SENTENCE FOR THE FOLLOWING PARA? I.E., WHAT'S THE CONNECTION BETWEEN THE FOLLOWING TO ABOVE-MENTIONED THINGS?]
SYM also revisits Clark's law in urban studies~\cite{clark1951urban}. In SYM, population density evolves as two-dimensional diffusion within a city\cite{doi:10.1137/0150099}, where we can focus the density's growth on each axis from the oldest citizens of a city. Let $
(d)$ denote the active population density of locations at the distance $d$ from a city center, and $t_n$ as the time for the $n$'th citizen to generate, we have
\begin{align}
\rho_{t_{n+1}}(d) = (\rho_{t_{n}}(d-r) + \rho_{t_{n}}(d+r) )/2.\label{loc_den}
\end{align} By re-scaling time as $\tau_n = t_n\cdot (k\beta_1+N\beta_2)/T$, for a sufficient large $T$, this equation results in an exponential decay of density
\begin{align}
\rho(d)\sim e^{-\alpha d}\label{clark_eq}.
\end{align} Details are presented in \textit{SI}.
A direct implication of Clark's law is the competition strengths at urban edges, which also influence the local Zipfian exponents. From Clark's law, the population density is just a function of city's age and the distance from urban center. Specifically, the density at the edges is important since it determines the competition advantages for space. The population within an edging cell of city $j$ is estimated by $e^{(T-T_j)}\int_{d}^{d+1}\rho(r)dr/(2\pi d)$, where $T_j$ is the emerging time of city $j$. We also have the waiting time $T_{n+1}-T_{n}\sim 1/n$, and the total population approximation $e^{\beta_1+\beta_2}$, combining which we derive the density of edging cells if time and the urban radius are given. Since the attractiveness of large urban center is larger, the edging population of large cities is actually smaller than minor cities. We validate our prediction with simulations in Fig.\@\ref{Fig2}. %[DON'T FOLLOW UP THIS PARA, WHY IT HERE, WHY IT IMPORTANT?] %We give a detailed derivation in Appendix B\ref{edge_comp}.
In supplement, larger $r$ will weaken the above prediction, since the settlement are more even, thus larger proportion of citizens live at edges. In reality, the metropolis areas over the world have very different densities. In SYM, it corresponds to the sprawl of a city with given population. It can also be taken as the area proportion for a city in the studied region. On the other hand, it also controls the spatial limit of cities given competitionless population.
\textit{The economic constraint phase}. The multi-perspective coincidence between the exponents derived in our model and those in empirical evidences of population studies indicates that only two observation scales (the generation rates of city and citizen) lead to the behaviors of regional dynamics. This means that the actual urban growth has not yet reached the constrained cases. However, preventive measures are still necessary. Thus we bring a general constraining parameter $N^*$ to further discuss the second phase of SYM, the economy constraint phase, i.e., the total population reaches $N^*$. Such setting is the abstract of many real-life rules set by global organizations such as the allowance of carbon emissions or sustainable development projects. In each city, a proportion of population are active. Here, $\sum_{i=1} N_i(t) = N^*$ for $t$ that is sufficiently large. If in some period, the minor cities generate more offspring than major ones and the superiority of remaining population within the memory kernel changes, minor city will increase its ranking, as the growing rate for each city $i$ is actually $N_i\beta_2$. As for the dynamics within memory kernel, in each city, $N_i$ acts as a random walk with absorption wall $0$, since no offspring will be expected if no nodes are left in the kernel. This result also works for single cell case within a city. Denote the population with cell $j$ of city $i$ as $m_{ij}$. According to~\cite{durrett1999essentials}, we use a result for branching process that a cell loses its vitality if the population goes downhill under a threshold \begin{align}\rho_{threshold} = k/\beta.\end{align} This value shall be regarded as the sign for \emph{urban shrinkage}, for the edging cells have lower density according to equation~\ref{clark_eq} thus have an exponentially higher probability to be languished. In other words, urban shrinkage shall be reasoned by limited systematic resources.
The kernel mechanism also plays a role at the cross-city scale: The preference of larger cities is easier to fail in a system with the memory kernel. The competition for active citizens in SYM receives more than pure birth settings because the sum of active population is given as $N^*$. In other words, SYM system doesn't consider natural growth. To test this interpretation, we analyze the turnover rate, defined as the average frequency of time steps in a realization that the second largest city surpasses the largest in active population. We conduct numerical experiments, and receive power law dependence of the frequency on simulating steps, shown in Fig.\@\ref{changerate}. Moreover, the switching is more likely to happen \textit{with} a memory kernel, i.e., turnover rate decay slower in probability if the system has constraints in resource. It is also a clear result since a growing society (a society without a memory kernel) suffer less from inter-specific competition.
\begin{figure}
\centering
\includegraphics[width = 0.47\textwidth]{pics/in_one_now_now.pdf}
\caption{The change rate statistics with \textbf{(a)} and without \textbf{(b)} a memory kernel. The kernel keeps turning over more often. With same $\beta$'s, a kernel-based SYM's decay in turnover rate is smaller. These results validate our prediction that with finite resource, advantages are more likely to be kept.}
\label{changerate}
\end{figure}
The last property of SYM is the fractality of urban envelop, stately, the length of urban edges vary with the used measurement. Inspired by multi-player interaction in fractal financial market\cite{PhysRevE.65.037106}, we interpret that fractal urban boundary is driven by the competition for land at cities' edges. In SYM, the uncertain competition for space lies in parameter $r$. A larger $r$ indicates larger randomness and brings an extra advantage for minor cities, resulting in a larger fractal dimension. We apply the box counting technique to calculate the fractal dimension of urban envelops, and receive an stable output of $d_f = 1.2\pm 0.05$ with $r = 0.5$, similar to empirical results\cite{batty1992form}. We also find larger $d_f$'s for greater $r$. These results validate our hypothesis that fractal edges coexist with spatial competition. Also, this result also confirms that SYM replicates an urban system.
\textit{Discussion}.
% 总结我们这个模型的发现有哪些,为什么我们这个好。
% Future endeavor
% 这两段是新写的。
% In this letter, we have proposed a simple model, spatial preferential growth with finite seeds, to simulate the emergence of cities and reveal the scaling laws as well as how economical dilemma would lead to spatial transitions. We account the emergence and growth of cities by adding and redistributing active population over given area. The model reveals the competition among cities in area and developmental potentials. We
% This model leads a way in the adaptation of realistic conditions in statistical physical modeling, by regardless of the whole present population within the system, and considering only the active part of them.
\textit{Discussion.} In summary, we have developed a spatial growth model to incorporate the effects of spatial and resource competitions in urban growth dynamics. The SYM recapitulates and generalizes earlier results from an urban growth model, including the emergence and condition of fractality, Zipf's and Clark's law. The memory kernel can shift the relative attractiveness of cities, with which the superiority of large cities stronger, while the sensitivity of the turnover rate to emergent rate $\beta$ also increases, when compared with memoryless models. The competition characterized by the memory kernel and spatial explicitation also lead to shifts in Zipfian exponent, vicissitudes, and stability criteria of large cities. These dynamics of space and resources suggests multiple avenues towards future study.
This \emph{Letter} concludes the urban system dynamics with only three key components, and presents fruitful results. The SYM leads a way in the adaptation of realistic conditions in statistical physical modeling, regardless of the whole present population within the system, and considering only the active part of them. SYM explains existing properties, such as fractality, Zipf's, and Clark's law, where we have both analytical mean-field derivations and bias analysis. More importantly, SYM predicts regional trends from a probabilistic perspective. With the simplicity of SYM, we manage to investigate the future phase transition of urban development in great detail, and explain the dilemmas of the present stage of urbanization through the competitions for systematic resource and space. The assumptions of SYM are well-held if sufficient divergence of meta-population across the world is considered. Simulations of this model can be adjust to heterogeneous geographical circumstances by applying the growing rate on each cell to the product of inherent dynamic $m_{ij}\cdot \beta_2$ and the local characteristic $c_{ij}$ to better suit for realistic conditions.
The memory kernel mechanism leads to a straightforward corollary that the reproductivity drives population's spatial transitions, as only those who are recorded in the kernel are considered as active citizens that attract new comers to his city. This result provides a bottom-up explanation for the transitions of urban centers with stochastic spatial shifts of cities' memorized people. It also tells that the economic growth is the basis of growth potentials. In reality, occasional events such as the discovery of new fossil fuel, or new technical revolutions, all lead to the growth of $N^*$. Under the circumstances of preferential attraction, if the size of the memory kernel cannot grow fast enough to match with the population, the concentration of production will go far from tolerance.
Taking the productive aspect together in the memory kernel reveals many other properties like the age structure. The stationary age can be calculated as the average time for a new city to emerge is $(\beta_2 N^* + \beta_1 k)^{-1}$, which equals to the average losing age of the whole kernel. This result gives an instruction of the length of workable age in a given social urban system.
% 不足
Although our results are not all analytically proved, we believe it is an essential step to strip out the power of urban dynamics. The model is non-commuting, but the community structure is naturally embedded. For further consideration, we can extend the model by adding links as the volume of exploration and preferential return between cities\cite{WANG2019121921}. The model can further be extended with multi-dimensional memory kernel, allowing one citizen to be introduced if different factors\cite{tokita2020social} (i.e., the existing citizens in different dimensions of kernel) agree to allow her in the system.
\bibliography{ref.bib}
\end{document} |
lemma prime_factorization_prod_mset: assumes "0 \<notin># A" shows "prime_factorization (prod_mset A) = \<Sum>\<^sub>#(image_mset prime_factorization A)" |
lemma not_measurable_UNIV [simp]: "UNIV \<notin> lmeasurable" |
[STATEMENT]
lemma reduced_reduce:
"reduced (reduce env t) (Mapping.keys env)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. reduced (reduce env t) (Mapping.keys env)
[PROOF STEP]
proof(induction t arbitrary: env)
[PROOF STATE]
proof (state)
goal (3 subgoals):
1. \<And>env. reduced (reduce env Trueif) (Mapping.keys env)
2. \<And>env. reduced (reduce env Falseif) (Mapping.keys env)
3. \<And>x1 t1 t2 env. \<lbrakk>\<And>env. reduced (reduce env t1) (Mapping.keys env); \<And>env. reduced (reduce env t2) (Mapping.keys env)\<rbrakk> \<Longrightarrow> reduced (reduce env (IF x1 t1 t2)) (Mapping.keys env)
[PROOF STEP]
case (IF x t1 t2)
[PROOF STATE]
proof (state)
this:
reduced (reduce ?env t1) (Mapping.keys ?env)
reduced (reduce ?env t2) (Mapping.keys ?env)
goal (3 subgoals):
1. \<And>env. reduced (reduce env Trueif) (Mapping.keys env)
2. \<And>env. reduced (reduce env Falseif) (Mapping.keys env)
3. \<And>x1 t1 t2 env. \<lbrakk>\<And>env. reduced (reduce env t1) (Mapping.keys env); \<And>env. reduced (reduce env t2) (Mapping.keys env)\<rbrakk> \<Longrightarrow> reduced (reduce env (IF x1 t1 t2)) (Mapping.keys env)
[PROOF STEP]
thus ?case
[PROOF STATE]
proof (prove)
using this:
reduced (reduce ?env t1) (Mapping.keys ?env)
reduced (reduce ?env t2) (Mapping.keys ?env)
goal (1 subgoal):
1. reduced (reduce env (IF x t1 t2)) (Mapping.keys env)
[PROOF STEP]
using IF.IH(1) IF.IH(2)
[PROOF STATE]
proof (prove)
using this:
reduced (reduce ?env t1) (Mapping.keys ?env)
reduced (reduce ?env t2) (Mapping.keys ?env)
reduced (reduce ?env t1) (Mapping.keys ?env)
reduced (reduce ?env t2) (Mapping.keys ?env)
goal (1 subgoal):
1. reduced (reduce env (IF x t1 t2)) (Mapping.keys env)
[PROOF STEP]
apply (auto simp: map_of_eq_None_iff image_iff reduced_mkIF split: option.split)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>\<And>env. reduced (reduce env t1) (Mapping.keys env); \<And>env. reduced (reduce env t2) (Mapping.keys env); Mapping.lookup env x = None\<rbrakk> \<Longrightarrow> reduced (mkIF x (reduce (Mapping.update x True env) t1) (reduce (Mapping.update x False env) t2)) (Mapping.keys env)
[PROOF STEP]
by (metis is_none_code(1) keys_is_none_rep keys_update reduced_mkIF)
[PROOF STATE]
proof (state)
this:
reduced (reduce env (IF x t1 t2)) (Mapping.keys env)
goal (2 subgoals):
1. \<And>env. reduced (reduce env Trueif) (Mapping.keys env)
2. \<And>env. reduced (reduce env Falseif) (Mapping.keys env)
[PROOF STEP]
qed auto |
module hamming
implicit none
contains
function compute(strand1, strand2, distance)
character(*) :: strand1, strand2
integer :: distance, i
logical :: compute
distance = 0
compute = .true.
if ( len(strand1) .NE. len(strand2) ) then
compute = .false.
return
end if
do i = 1,len(strand1)
if (strand1(i:i) .NE. strand2(i:i)) then
distance = distance + 1
end if
end do
end function compute
end module hamming
|
theorem IffNotNot {p: Prop}:
p ↔ ¬ ¬ p := by {
apply Iff.intro;
{exact fun h hn => hn h;}
{
intro h;
by_cases hp: p;
{exact hp;}
{exact False.elim (h hp);}
}
}
theorem ImpIffNotImpNot {p q: Prop}:
(p → q) ↔ (¬ q → ¬ p) := by {
apply Iff.intro;
{exact fun h hnq hp => hnq (h hp);}
{
intro h hp;
by_cases hq: q;
{exact hq;}
{exact False.elim ((h hq) hp);}
}
}
theorem IffIffNotIffNot {p q: Prop}:
(p ↔ q) ↔ (¬ q ↔ ¬ p) := by {
apply Iff.intro;
{exact fun h => ⟨ImpIffNotImpNot.1 h.1,ImpIffNotImpNot.1 h.2⟩;}
{exact fun h => ⟨ImpIffNotImpNot.2 h.1,ImpIffNotImpNot.2 h.2⟩;}
}
theorem NotExistsImpForall {α : Sort u} {p: α → Prop}:
(¬ (∃a: α, p a)) → (∀a: α, ¬ p a) :=
fun h a ha => h (Exists.intro a ha)
theorem NotFoallImpExists {α : Sort u} {p: α → Prop}:
¬ (∀a: α, p a) → (∃a: α, ¬ p a) := by {
intro h;
by_cases ha : (∃a: α, ¬ p a);
{exact ha;}
{exact False.elim (h (fun a => IffNotNot.2 (NotExistsImpForall ha a)));}
}
theorem ExistsIffNotForall {α : Sort u} {p: α → Prop}:
(¬ (∃a: α, p a)) ↔ (∀a: α, ¬ p a) := by {
apply Iff.intro;
{exact NotExistsImpForall;}
{exact fun h ⟨a, pa⟩ => (h a) pa;}
}
theorem ForallIffNotExists {α : Sort u} {p: α → Prop}:
¬ (∀a: α, p a) ↔ (∃a: α, ¬ p a) := by {
apply Iff.intro;
{exact NotFoallImpExists;}
{exact fun ⟨a, pa⟩ h => pa (h a);}
}
theorem NotOrIffNotAndNot {p q:Prop}:
¬ (p ∨ q) ↔ (¬ p) ∧ (¬ q) := by {
apply Iff.intro;
{
intro h;
by_cases hp:p;
{exact False.elim (h (Or.inl hp));}
{
by_cases hq:q;
{exact False.elim (h (Or.inr hq));}
{exact (And.intro hp hq)}
}
}
{
intro h hn;
cases hn;
case mpr.inl hn => {exact h.1 hn}
case mpr.inr hn => {exact h.2 hn}
}
}
theorem NotAndIffNotOrNot {p q:Prop}:
¬ (p ∧ q) ↔ (¬ p) ∨ (¬ q) := by {
apply Iff.intro;
{
intro h;
by_cases hp:p;
{
by_cases hq:q;
{exact False.elim (h (And.intro hp hq))}
{exact Or.inr hq;}
}
{exact Or.inl hp;}
}
{
intro h hn;
cases h;
case mpr.inl h => {exact h hn.1}
case mpr.inr h => {exact h hn.2}
}
}
|
import category_theory.preadditive.additive_functor
import algebra.category.Module.basic
import algebra.category.Group.preadditive
import for_mathlib.is_biprod
open category_theory category_theory.limits
namespace category_theory
namespace functor
variables {𝒜 ℬ : Type*} [category 𝒜] [category ℬ]
variables [preadditive 𝒜] [preadditive ℬ]
variables (F : 𝒜 ⥤ ℬ)
lemma additive_of_map_fst_add_snd [has_binary_biproducts 𝒜]
(h : ∀ A : 𝒜, F.map (biprod.fst + biprod.snd : A ⊞ A ⟶ A) =
F.map biprod.fst + F.map biprod.snd) :
F.additive :=
{ map_add' := λ A B f g,
begin
have : f + g = biprod.lift f g ≫ (biprod.fst + biprod.snd),
{ rw [preadditive.comp_add, biprod.lift_fst, biprod.lift_snd] },
rw [this, F.map_comp, h, preadditive.comp_add, ← F.map_comp, ← F.map_comp,
biprod.lift_fst, biprod.lift_snd],
end }
noncomputable
def obj_biprod_iso (F : 𝒜 ⥤ ℬ) [F.additive]
(A B : 𝒜) [has_binary_biproduct A B] [has_binary_biproduct (F.obj A) (F.obj B)] :
F.obj (A ⊞ B) ≅ F.obj A ⊞ F.obj B :=
is_biprod.iso_biprod _ (F.map_is_biprod _ (biprod.is_biprod A B))
instance forget₂_additive (R : Type*) [ring R] : (forget₂ (Module R) AddCommGroup).additive :=
{ map_add' := λ M N f g, rfl }
lemma map_is_zero {X : 𝒜} [F.additive] (hX : limits.is_zero X) :
limits.is_zero (F.obj X) :=
begin
rw limits.is_zero.iff_id_eq_zero at hX ⊢,
convert congr_arg (@category_theory.functor.map _ _ _ _ F _ _) hX;
simp,
end
end functor
end category_theory
|
# module Bukdu.Plug
# follow the https://github.com/elixir-plug/plug/blob/master/lib/plug/conn.ex
"""
Conn
"""
mutable struct Conn <: AbstractPlug
request::Deps.Request
# Fetchable fields
# cookies # the request cookies with the response cookies FIXME
body_params::Assoc # Plug.Parsers
query_params::Assoc # fetch_query_params
path_params::Assoc
params::Assoc # merge(body_params, query_params, path_params)
# Connection fields
halted::Bool # the boolean status on whether the pipeline was halted
end
Conn(request::Deps.Request) = Conn(request, Assoc(), Assoc(), Assoc(), Assoc(), false)
# module Bukdu.Plug
|
State Before: ⊢ Tendsto cos (𝓝[Ioi (-(π / 2))] (-(π / 2))) (𝓝[Ioi 0] 0) State After: case h1
⊢ Tendsto cos (𝓝[Ioi (-(π / 2))] (-(π / 2))) (𝓝 0)
case h2
⊢ ∀ᶠ (x : ℝ) in 𝓝[Ioi (-(π / 2))] (-(π / 2)), cos x ∈ Ioi 0 Tactic: apply tendsto_nhdsWithin_of_tendsto_nhds_of_eventually_within State Before: case h1
⊢ Tendsto cos (𝓝[Ioi (-(π / 2))] (-(π / 2))) (𝓝 0) State After: case h.e'_5.h.e'_3
⊢ 0 = cos (-(π / 2)) Tactic: convert continuous_cos.continuousWithinAt.tendsto State Before: case h.e'_5.h.e'_3
⊢ 0 = cos (-(π / 2)) State After: no goals Tactic: simp State Before: case h2
⊢ ∀ᶠ (x : ℝ) in 𝓝[Ioi (-(π / 2))] (-(π / 2)), cos x ∈ Ioi 0 State After: no goals Tactic: filter_upwards [Ioo_mem_nhdsWithin_Ioi
(left_mem_Ico.mpr (neg_lt_self pi_div_two_pos))]with x hx using cos_pos_of_mem_Ioo hx |
module Agda.Builtin.Size where
{-# BUILTIN SIZEUNIV SizeU #-}
{-# BUILTIN SIZE Size #-}
{-# BUILTIN SIZELT Size<_ #-}
{-# BUILTIN SIZESUC ↑_ #-}
{-# BUILTIN SIZEINF ω #-}
{-# BUILTIN SIZEMAX _⊔ˢ_ #-}
|
import unittest
import onnxruntime
import torch
import numpy as np
import io
import itertools
import copy
import os
import random
from torch.nn.utils import rnn as rnn_utils
from model_defs.lstm_flattening_result import (LstmFlatteningResultWithSeqLength,
LstmFlatteningResultWithoutSeqLength)
from model_defs.rnn_model_with_packed_sequence import (RnnModelWithPackedSequence,
RnnModelWithPackedSequenceWithState,
RnnModelWithPackedSequenceWithoutState)
from test_pytorch_common import (skipIfUnsupportedMinOpsetVersion, skipIfUnsupportedOpsetVersion,
skipIfNoLapack, disableScriptTest, skipIfONNXShapeInference,
skipIfUnsupportedMaxOpsetVersion, skipForAllOpsetVersions)
from test_pytorch_common import BATCH_SIZE
from test_pytorch_common import RNN_BATCH_SIZE, RNN_SEQUENCE_LENGTH, RNN_INPUT_SIZE, RNN_HIDDEN_SIZE
from typing import List, Tuple, Optional, Dict
from torch import Tensor
import model_defs.word_language_model as word_language_model
import onnx
import torchvision
from torchvision import ops
from torchvision.models.detection.image_list import ImageList
from torchvision.models.detection.transform import GeneralizedRCNNTransform
from torchvision.models.detection.rpn import AnchorGenerator, RPNHead, RegionProposalNetwork
from torchvision.models.detection.roi_heads import RoIHeads
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor, TwoMLPHead
from collections import OrderedDict
from torch.nn.utils.rnn import PackedSequence
def to_numpy(tensor):
if tensor.requires_grad:
return tensor.detach().cpu().numpy()
else:
return tensor.cpu().numpy()
def convert_to_onnx(model, input=None, opset_version=9, example_outputs=None,
do_constant_folding=True, keep_initializers_as_inputs=True,
dynamic_axes=None, input_names=None, output_names=None,
fixed_batch_size=False, training=None,
onnx_shape_inference=False):
# export the model to ONNX
f = io.BytesIO()
input_copy = copy.deepcopy(input)
torch.onnx._export(model, input_copy, f,
opset_version=opset_version,
example_outputs=example_outputs,
do_constant_folding=do_constant_folding,
keep_initializers_as_inputs=keep_initializers_as_inputs,
dynamic_axes=dynamic_axes,
input_names=input_names, output_names=output_names,
fixed_batch_size=fixed_batch_size, training=training,
onnx_shape_inference=onnx_shape_inference)
# compute onnxruntime output prediction
ort_sess = onnxruntime.InferenceSession(f.getvalue())
return ort_sess
def inline_flatten_list(inputs, res_list):
for i in inputs:
res_list.append(i) if not isinstance(i, (list, tuple)) else inline_flatten_list(i, res_list)
return res_list
def run_ort(ort_sess, input):
input_copy = copy.deepcopy(input)
input, _ = torch.jit._flatten(input_copy)
inputs = [to_numpy(inp) for inp in input]
ort_inputs = dict((ort_sess.get_inputs()[i].name, input) for i, input in enumerate(inputs))
ort_outs = ort_sess.run(None, ort_inputs)
return inline_flatten_list(ort_outs, [])
def ort_compare_with_pytorch(ort_outs, output, rtol, atol):
output, _ = torch.jit._flatten(output)
outputs = [to_numpy(outp) for outp in output]
# compare onnxruntime and PyTorch results
assert len(outputs) == len(ort_outs), "number of outputs differ"
# compare onnxruntime and PyTorch results
[np.testing.assert_allclose(out, ort_out, rtol=rtol, atol=atol) for out, ort_out in zip(outputs, ort_outs)]
def run_model_test(self, model, batch_size=2, state_dict=None,
input=None, use_gpu=True, rtol=0.001, atol=1e-7,
example_outputs=None, do_constant_folding=True,
dynamic_axes=None, test_with_inputs=None,
input_names=None, output_names=None,
fixed_batch_size=False, dict_check=True,
training=None, remained_onnx_input_idx=None):
if training is not None and training == torch.onnx.TrainingMode.TRAINING:
model.train()
elif training is None or training == torch.onnx.TrainingMode.EVAL:
model.eval()
if input is None:
input = torch.randn(batch_size, 3, 224, 224, requires_grad=True)
with torch.no_grad():
if isinstance(input, torch.Tensor):
input = (input,)
# In-place operators will update input tensor data as well.
# Thus inputs are replicated before every forward call.
if isinstance(input, dict):
input = (input,)
input_args = copy.deepcopy(input)
input_kwargs = {}
if dict_check and isinstance(input_args[-1], dict):
input_kwargs = input_args[-1]
input_args = input_args[:-1]
try:
model_copy = copy.deepcopy(model)
output = model_copy(*input_args, **input_kwargs)
except Exception:
output = model(*input_args, **input_kwargs)
if isinstance(output, torch.Tensor):
output = (output,)
if not dict_check and isinstance(input[-1], dict):
input = input + ({},)
ort_sess = convert_to_onnx(model, input=input, opset_version=self.opset_version,
example_outputs=output, do_constant_folding=do_constant_folding,
keep_initializers_as_inputs=self.keep_initializers_as_inputs,
dynamic_axes=dynamic_axes, input_names=input_names,
output_names=output_names, fixed_batch_size=fixed_batch_size, training=training,
onnx_shape_inference=self.onnx_shape_inference)
# compute onnxruntime output prediction
if remained_onnx_input_idx is not None:
input_onnx = []
for idx in remained_onnx_input_idx:
input_onnx.append(input[idx])
input = input_onnx
ort_outs = run_ort(ort_sess, input)
ort_compare_with_pytorch(ort_outs, output, rtol, atol)
# if additional test inputs are provided run the onnx
# model with these inputs and check the outputs
if test_with_inputs is not None:
for test_input in test_with_inputs:
if isinstance(test_input, torch.Tensor):
test_input = (test_input,)
test_input_copy = copy.deepcopy(test_input)
output = model(*test_input_copy)
if isinstance(output, torch.Tensor):
output = (output,)
if remained_onnx_input_idx is not None:
test_input_onnx = []
for idx in remained_onnx_input_idx:
test_input_onnx.append(test_input[idx])
test_input = test_input_onnx
ort_outs = run_ort(ort_sess, test_input)
ort_compare_with_pytorch(ort_outs, output, rtol, atol)
def _init_test_generalized_rcnn_transform():
min_size = 100
max_size = 200
image_mean = [0.485, 0.456, 0.406]
image_std = [0.229, 0.224, 0.225]
transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std)
return transform
def _init_test_rpn():
anchor_sizes = ((32,), (64,), (128,), (256,), (512,))
aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)
rpn_anchor_generator = AnchorGenerator(anchor_sizes, aspect_ratios)
out_channels = 256
rpn_head = RPNHead(out_channels, rpn_anchor_generator.num_anchors_per_location()[0])
rpn_fg_iou_thresh = 0.7
rpn_bg_iou_thresh = 0.3
rpn_batch_size_per_image = 256
rpn_positive_fraction = 0.5
rpn_pre_nms_top_n = dict(training=2000, testing=1000)
rpn_post_nms_top_n = dict(training=2000, testing=1000)
rpn_nms_thresh = 0.7
rpn_score_thresh = 0.0
rpn = RegionProposalNetwork(
rpn_anchor_generator, rpn_head,
rpn_fg_iou_thresh, rpn_bg_iou_thresh,
rpn_batch_size_per_image, rpn_positive_fraction,
rpn_pre_nms_top_n, rpn_post_nms_top_n, rpn_nms_thresh,
score_thresh=rpn_score_thresh)
return rpn
def _init_test_roi_heads_faster_rcnn():
out_channels = 256
num_classes = 91
box_fg_iou_thresh = 0.5
box_bg_iou_thresh = 0.5
box_batch_size_per_image = 512
box_positive_fraction = 0.25
bbox_reg_weights = None
box_score_thresh = 0.05
box_nms_thresh = 0.5
box_detections_per_img = 100
box_roi_pool = ops.MultiScaleRoIAlign(
featmap_names=["0", "1", "2", "3"],
output_size=7,
sampling_ratio=2)
resolution = box_roi_pool.output_size[0]
representation_size = 1024
box_head = TwoMLPHead(
out_channels * resolution ** 2,
representation_size)
representation_size = 1024
box_predictor = FastRCNNPredictor(
representation_size,
num_classes)
roi_heads = RoIHeads(
box_roi_pool, box_head, box_predictor,
box_fg_iou_thresh, box_bg_iou_thresh,
box_batch_size_per_image, box_positive_fraction,
bbox_reg_weights,
box_score_thresh, box_nms_thresh, box_detections_per_img)
return roi_heads
def set_rng_seed(seed):
torch.manual_seed(seed)
random.seed(seed)
np.random.seed(seed)
class TestONNXRuntime(unittest.TestCase):
from torch.onnx.symbolic_helper import _export_onnx_opset_version
opset_version = _export_onnx_opset_version
keep_initializers_as_inputs = True # For IR version 3 type export.
onnx_shape_inference = True
def setUp(self):
torch.manual_seed(0)
onnxruntime.set_seed(0)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(0)
np.random.seed(seed=0)
os.environ["ALLOW_RELEASED_ONNX_OPSET_ONLY"] = "0"
self.is_script_test_enabled = True
# The exported ONNX model may have less inputs than the pytorch model because of const folding.
# This mostly happens in unit test, where we widely use torch.size or torch.shape.
# So the output is only dependent on the input shape, not value.
# remained_onnx_input_idx is used to indicate which pytorch model input idx is remained in ONNX model.
def run_test(self, model, input, rtol=1e-3, atol=1e-7, do_constant_folding=True,
batch_size=2, use_gpu=True, dynamic_axes=None, test_with_inputs=None,
input_names=None, output_names=None, fixed_batch_size=False, dict_check=True,
training=None, remained_onnx_input_idx=None):
def _run_test(m, remained_onnx_input_idx):
return run_model_test(self, m, batch_size=batch_size,
input=input, use_gpu=use_gpu, rtol=rtol, atol=atol,
do_constant_folding=do_constant_folding,
dynamic_axes=dynamic_axes, test_with_inputs=test_with_inputs,
input_names=input_names, output_names=output_names,
fixed_batch_size=fixed_batch_size, dict_check=dict_check,
training=training, remained_onnx_input_idx=remained_onnx_input_idx)
if isinstance(remained_onnx_input_idx, dict):
scripting_remained_onnx_input_idx = remained_onnx_input_idx['scripting']
tracing_remained_onnx_input_idx = remained_onnx_input_idx['tracing']
else:
scripting_remained_onnx_input_idx = remained_onnx_input_idx
tracing_remained_onnx_input_idx = remained_onnx_input_idx
if self.is_script_test_enabled:
script_model = torch.jit.script(model)
_run_test(script_model, scripting_remained_onnx_input_idx)
_run_test(model, tracing_remained_onnx_input_idx)
def run_model_test_with_external_data(self, model, input, rtol=0.001, atol=1e-7,
example_outputs=None, do_constant_folding=True,
dynamic_axes=None, input_names=None, output_names=None,
ort_optim_on=True, training=None):
import os
import tempfile
if training is not None and training == torch.onnx.TrainingMode.TRAINING:
model.train()
elif training is None or training == torch.onnx.TrainingMode.EVAL:
model.eval()
with torch.no_grad():
if isinstance(input, torch.Tensor):
input = (input,)
# In-place operators will update input tensor data as well.
# Thus inputs are replicated before every forward call.
input_copy = copy.deepcopy(input)
output = model(*input_copy)
if isinstance(output, torch.Tensor):
output = (output,)
# export the model to ONNX
with tempfile.TemporaryDirectory() as tmpdirname:
model_file_name = os.path.join(tmpdirname, "model.onnx")
input_copy = copy.deepcopy(input)
torch.onnx.export(model, input_copy, model_file_name,
opset_version=self.opset_version,
example_outputs=output,
verbose=False,
do_constant_folding=do_constant_folding,
keep_initializers_as_inputs=self.keep_initializers_as_inputs,
dynamic_axes=dynamic_axes,
input_names=input_names, output_names=output_names,
use_external_data_format=True)
# compute onnxruntime output prediction
ort_sess_opt = onnxruntime.SessionOptions()
ort_sess_opt.graph_optimization_level = \
onnxruntime.GraphOptimizationLevel.ORT_ENABLE_EXTENDED if ort_optim_on else \
onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL
ort_sess = onnxruntime.InferenceSession(model_file_name, sess_options=ort_sess_opt)
input_copy = copy.deepcopy(input)
ort_outs = run_ort(ort_sess, input_copy)
ort_compare_with_pytorch(ort_outs, output, rtol, atol)
@skipIfUnsupportedMinOpsetVersion(9) # Because external data format was released with Opset 9.
def test_embedding_model_with_external_data(self):
class LargeModel(torch.nn.Module):
def __init__(self):
super(LargeModel, self).__init__()
dim = 15
n = 4 * 100
self.emb = torch.nn.Embedding(n, dim)
self.lin1 = torch.nn.Linear(dim, 1)
self.seq = torch.nn.Sequential(
self.emb,
self.lin1,
)
def forward(self, input):
return self.seq(input)
model = LargeModel()
x = torch.tensor([2], dtype=torch.long)
self.run_model_test_with_external_data(model, x)
@skipIfUnsupportedMinOpsetVersion(9) # Because external data format was released with Opset 9.
def test_mobilenet_v2_with_external_data(self):
model = torchvision.models.mobilenet_v2(pretrained=True)
x = torch.randn(2, 3, 224, 224, requires_grad=True)
# We are turning off Onnx Runtime optimization off in this test,
# because external data format is not supported to in ORT optimizer.
# Once that support is added, we can set ort_optim_on=True (default).
self.run_model_test_with_external_data(model, x, rtol=1e-3, atol=1e-5,
ort_optim_on=False)
@skipIfUnsupportedMinOpsetVersion(9) # Because external data format was released with Opset 9.
def test_attribute_with_external_data(self):
class LargeModel(torch.nn.Module):
def forward(self, x):
return x + torch.ones(2, 1024)
x = torch.randn(2, 1)
self.run_model_test_with_external_data(LargeModel(), x)
@skipIfUnsupportedMinOpsetVersion(9) # Because external data format was released with Opset 9.
@unittest.skip("Enable this once large model with subgraph is supported in ORT")
def test_subgraph_with_external_data(self):
class LargeModel(torch.nn.Module):
def forward(self, x):
for i in range(x.size(0)):
x = x + torch.ones(2, 1024)
return x
x = torch.randn(2, 1)
self.run_model_test_with_external_data(torch.jit.script(LargeModel()), x)
def test_fuse_conv_bn1d(self):
class Fuse(torch.nn.Module):
def __init__(self):
super(Fuse, self).__init__()
self.conv = torch.nn.Conv1d(16, 33, 3, stride=2)
self.bn = torch.nn.BatchNorm1d(33)
def forward(self, x):
out = self.conv(x)
return self.bn(out)
model = Fuse()
x = torch.randn(20, 16, 50, requires_grad=True)
self.run_test(model, (x,))
def test_fuse_conv_bn2d(self):
class Fuse(torch.nn.Module):
def __init__(self):
super(Fuse, self).__init__()
self.conv = torch.nn.Conv2d(3, 2, kernel_size=1, stride=2, padding=3, bias=False)
self.bn = torch.nn.BatchNorm2d(2)
def forward(self, x):
out = self.conv(x)
return self.bn(out)
model = Fuse()
x = torch.randn(2, 3, 2, 2, requires_grad=True)
self.run_test(model, (x,))
def test_fuse_conv_bn3d(self):
class Fuse(torch.nn.Module):
def __init__(self):
super(Fuse, self).__init__()
self.conv = torch.nn.Conv3d(3, 2, (3, 5, 2), stride=(2, 1, 1), padding=(3, 2, 0), bias=False)
self.bn = torch.nn.BatchNorm3d(2)
def forward(self, x):
out = self.conv(x)
return self.bn(out)
model = Fuse()
x = torch.randn(2, 3, 10, 50, 100, requires_grad=True)
self.run_test(model, (x,), rtol=1e-3, atol=1e-6)
def test_conv_tbc(self):
from torch.nn.modules.utils import _single
class ConvTBC(torch.nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, padding=0):
super(ConvTBC, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = _single(kernel_size)
self.padding = _single(padding)
self.weight = torch.nn.Parameter(
torch.Tensor(self.kernel_size[0], in_channels, out_channels)
)
self.bias = torch.nn.Parameter(torch.Tensor(out_channels))
self.reset_parameters()
def reset_parameters(self):
torch.nn.init.xavier_normal_(self.weight)
torch.nn.init.zeros_(self.bias)
def conv_tbc(self, input):
return torch.conv_tbc(
input.contiguous(), self.weight, self.bias, self.padding[0]
)
def forward(self, input):
return self.conv_tbc(input)
in_channels = 3
out_channels = 5
kernel_size = 5
model = ConvTBC(in_channels, out_channels, kernel_size, padding=0)
x = torch.randn(10, 7, in_channels, requires_grad=True)
self.run_test(model, (x,), atol=1e-5)
def test_reshape_constant_fold(self):
class Reshape(torch.nn.Module):
def __init__(self, ):
super(Reshape, self).__init__()
self.register_buffer("weight", torch.ones(5))
def forward(self, x):
scale_1 = self.weight.reshape(1, -1, 1, 1)
return x * scale_1
x = torch.randn(4, 5)
self.run_test(Reshape(), (x,), rtol=1e-3, atol=1e-5)
def run_word_language_model(self, model_name):
ntokens = 50
emsize = 5
nhid = 5
nlayers = 5
dropout = 0.2
tied = False
batchsize = 5
if model_name == "GRU":
model = word_language_model.RNNModelWithTensorHidden(model_name, ntokens, emsize,
nhid, nlayers, dropout, tied,
batchsize)
elif model_name == "LSTM":
model = word_language_model.RNNModelWithTupleHidden(model_name, ntokens, emsize,
nhid, nlayers, dropout, tied,
batchsize)
else:
model = word_language_model.RNNModel(model_name, ntokens, emsize,
nhid, nlayers, dropout, tied,
batchsize)
x = torch.arange(0, ntokens).long().view(-1, batchsize)
# Only support CPU version, since tracer is not working in GPU RNN.
self.run_test(model, (x, model.hidden))
def get_image_from_url(self, url, size=(300, 200)):
import os
from urllib.parse import urlsplit
from urllib import request
from PIL import Image
from torchvision import transforms
from torch._utils_internal import get_writable_path
filename = os.path.basename(urlsplit(url)[2])
data_dir = get_writable_path(os.path.join(os.path.dirname(__file__)))
path = os.path.join(data_dir, filename)
data = request.urlopen(url, timeout=15).read()
with open(path, "wb") as f:
f.write(data)
image = Image.open(path).convert("RGB")
image = image.resize(size, Image.BILINEAR)
to_tensor = transforms.ToTensor()
return to_tensor(image)
def get_test_images(self):
image_url = "http://farm3.staticflickr.com/2469/3915380994_2e611b1779_z.jpg"
image = self.get_image_from_url(url=image_url, size=(100, 320))
image_url2 = "https://pytorch.org/tutorials/_static/img/tv_tutorial/tv_image05.png"
image2 = self.get_image_from_url(url=image_url2, size=(250, 380))
return [image], [image2]
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest() # Faster RCNN model is not scriptable
def test_faster_rcnn(self):
model = torchvision.models.detection.faster_rcnn.fasterrcnn_resnet50_fpn(pretrained=True, min_size=200,
max_size=300)
model.eval()
x = torch.randn(2, 3, 200, 300, requires_grad=True)
self.run_test(model, (x,), rtol=1e-3, atol=1e-5)
self.run_test(model, (x,), input_names=["images_tensors"], output_names=["outputs"],
dynamic_axes={"images_tensors": [0, 1, 2, 3], "outputs": [0, 1, 2, 3]}, rtol=1e-3, atol=1e-5)
dummy_image = [torch.ones(3, 100, 100) * 0.3]
images, test_images = self.get_test_images()
self.run_test(model, (images,), test_with_inputs=[(images,), (test_images,), (dummy_image,)],
input_names=["images_tensors"], output_names=["outputs"],
dynamic_axes={"images_tensors": [0, 1, 2], "outputs": [0, 1, 2]}, rtol=1e-3, atol=1e-5)
self.run_test(model, (dummy_image,), test_with_inputs=[(dummy_image,), (images,)],
input_names=["images_tensors"], output_names=["outputs"],
dynamic_axes={"images_tensors": [0, 1, 2], "outputs": [0, 1, 2]}, rtol=1e-3, atol=1e-5)
def test_paste_mask_in_image(self):
# disable profiling
torch._C._jit_set_profiling_executor(False)
torch._C._jit_set_profiling_mode(False)
masks = torch.rand(10, 1, 26, 26)
boxes = torch.rand(10, 4)
boxes[:, 2:] += torch.rand(10, 2)
boxes *= 50
o_im_s = (100, 100)
from torchvision.models.detection.roi_heads import paste_masks_in_image
out = paste_masks_in_image(masks, boxes, o_im_s)
jit_trace = torch.jit.trace(paste_masks_in_image,
(masks, boxes,
[torch.tensor(o_im_s[0]),
torch.tensor(o_im_s[1])]))
out_trace = jit_trace(masks, boxes, [torch.tensor(o_im_s[0]), torch.tensor(o_im_s[1])])
assert torch.all(out.eq(out_trace))
masks2 = torch.rand(20, 1, 26, 26)
boxes2 = torch.rand(20, 4)
boxes2[:, 2:] += torch.rand(20, 2)
boxes2 *= 100
o_im_s2 = (200, 200)
from torchvision.models.detection.roi_heads import paste_masks_in_image
out2 = paste_masks_in_image(masks2, boxes2, o_im_s2)
out_trace2 = jit_trace(masks2, boxes2, [torch.tensor(o_im_s2[0]), torch.tensor(o_im_s2[1])])
assert torch.all(out2.eq(out_trace2))
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest()
def test_mask_rcnn(self):
model = torchvision.models.detection.mask_rcnn.maskrcnn_resnet50_fpn(pretrained=True, min_size=200,
max_size=300)
images, test_images = self.get_test_images()
self.run_test(model, (images,), rtol=1e-3, atol=1e-5)
self.run_test(model, (images,), input_names=["images_tensors"], output_names=["boxes", "labels", "scores", "masks"],
dynamic_axes={"images_tensors": [0, 1, 2], "boxes": [0, 1], "labels": [0],
"scores": [0], "masks": [0, 1, 2]}, rtol=1e-3, atol=1e-5)
dummy_image = [torch.ones(3, 100, 100) * 0.3]
self.run_test(model, (images,), test_with_inputs=[(images,), (test_images,), (dummy_image,)],
input_names=["images_tensors"], output_names=["boxes", "labels", "scores", "masks"],
dynamic_axes={"images_tensors": [0, 1, 2], "boxes": [0, 1], "labels": [0],
"scores": [0], "masks": [0, 1, 2]}, rtol=1e-3, atol=1e-5)
self.run_test(model, (dummy_image,), test_with_inputs=[(dummy_image,), (images,)],
input_names=["images_tensors"], output_names=["boxes", "labels", "scores", "masks"],
dynamic_axes={"images_tensors": [0, 1, 2], "boxes": [0, 1], "labels": [0],
"scores": [0], "masks": [0, 1, 2]}, rtol=1e-3, atol=1e-5)
def test_heatmaps_to_keypoints(self):
# disable profiling
torch._C._jit_set_profiling_executor(False)
torch._C._jit_set_profiling_mode(False)
maps = torch.rand(10, 1, 26, 26)
rois = torch.rand(10, 4)
from torchvision.models.detection.roi_heads import heatmaps_to_keypoints
out = heatmaps_to_keypoints(maps, rois)
jit_trace = torch.jit.trace(heatmaps_to_keypoints, (maps, rois))
out_trace = jit_trace(maps, rois)
assert torch.all(out[0].eq(out_trace[0]))
assert torch.all(out[1].eq(out_trace[1]))
maps2 = torch.rand(20, 2, 21, 21)
rois2 = torch.rand(20, 4)
from torchvision.models.detection.roi_heads import heatmaps_to_keypoints
out2 = heatmaps_to_keypoints(maps2, rois2)
out_trace2 = jit_trace(maps2, rois2)
assert torch.all(out2[0].eq(out_trace2[0]))
assert torch.all(out2[1].eq(out_trace2[1]))
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest()
def test_keypoint_rcnn(self):
model = torchvision.models.detection.keypoint_rcnn.keypointrcnn_resnet50_fpn(pretrained=True, min_size=200,
max_size=300)
images, test_images = self.get_test_images()
self.run_test(model, (images,), rtol=1e-3, atol=1e-5)
self.run_test(model, (images,), input_names=["images_tensors"],
output_names=["outputs1", "outputs2", "outputs3", "outputs4"],
dynamic_axes={"images_tensors": [0, 1, 2]},
rtol=1e-3, atol=1e-5)
dummy_images = [torch.ones(3, 100, 100) * 0.3]
self.run_test(model, (images,), test_with_inputs=[(images,), (test_images,), (dummy_images,)],
input_names=["images_tensors"], output_names=["outputs1", "outputs2", "outputs3", "outputs4"],
dynamic_axes={"images_tensors": [0, 1, 2]},
rtol=5e-3, atol=1e-5)
self.run_test(model, (dummy_images,), test_with_inputs=[(dummy_images,), (test_images,)],
input_names=["images_tensors"], output_names=["outputs1", "outputs2", "outputs3", "outputs4"],
dynamic_axes={"images_tensors": [0, 1, 2]},
rtol=5e-3, atol=1e-5)
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest()
def test_shufflenet_v2_dynamic_axes(self):
model = torchvision.models.shufflenet_v2_x0_5(pretrained=True)
dummy_input = torch.randn(1, 3, 224, 224, requires_grad=True)
test_inputs = torch.randn(3, 3, 224, 224, requires_grad=True)
self.run_test(model, (dummy_input,), test_with_inputs=[(dummy_input,), (test_inputs,)],
input_names=["input_images"], output_names=["outputs"],
dynamic_axes={"input_images": {0: "batch_size"}, "output": {0: "batch_size"}},
rtol=1e-3, atol=1e-5)
@disableScriptTest()
def test_word_language_model_RNN_TANH(self):
self.run_word_language_model("RNN_TANH")
@disableScriptTest()
def test_word_language_model_RNN_RELU(self):
self.run_word_language_model("RNN_RELU")
@disableScriptTest() # scripting prim::unchecked_cast prim::setattr
def test_word_language_model_LSTM(self):
self.run_word_language_model("LSTM")
def test_word_language_model_GRU(self):
self.run_word_language_model("GRU")
def test_index_1d(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[0]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
def test_index_2d_1dimslice(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[0:1, :]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
def test_index_2d_sliceint(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[1, :]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
def test_index_2d_neg_slice(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[0:-1, :]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_mask(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[torch.tensor([0, 1, 0], dtype=torch.uint8)]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
class MyModel(torch.nn.Module):
def forward(self, input):
return input[torch.tensor([0, 1, 0], dtype=torch.bool)]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
@skipIfUnsupportedMinOpsetVersion(9)
def test_data(self):
class Data(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return x.new_zeros(x.data.size())
x = torch.randn(3, 4)
self.run_test(Data(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(Data(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest() # Need type inference
def test_index_mask_nd(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[input > 0]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
@disableScriptTest()
def test_dict(self):
class MyModel(torch.nn.Module):
def forward(self, x_in):
x_out = {}
x_out["test_key_out"] = torch.add(x_in[list(x_in.keys())[0]], list(x_in.keys())[0])
return x_out
x = {torch.tensor(1.): torch.randn(1, 2, 3)}
self.run_test(MyModel(), (x, {}))
@disableScriptTest()
def test_dict_str(self):
class MyModel(torch.nn.Module):
def forward(self, x_in):
x_out = {}
x_out["test_key_out"] = torch.add(x_in["test_key_in"], 2.)
return x_out
x = {"test_key_in": torch.randn(1, 2, 3)}
self.run_test(MyModel(), (x, {}))
@disableScriptTest()
def test_dict_output(self):
class DictModelOutput(OrderedDict):
tensor_out: torch.Tensor
tuple_out: Optional[Tuple[torch.Tensor]] = None
list_out: Optional[List[torch.Tensor]] = None
class MyModel(torch.nn.Module):
def forward(self, a, b, c, d):
return DictModelOutput(
tensor_out=a,
tuple_out=(b, c),
list_out=[d],
)
a = torch.randn(2, 3)
b = torch.randn(2, 3)
c = torch.randn(2, 3)
d = torch.randn(2, 3)
self.run_test(MyModel(), (a, b, c, d))
def test_tuple_output(self):
class MyModel(torch.nn.Module):
def forward(self, a, b, c, d):
return a, (b, c), d
a = torch.randn(2, 3)
b = torch.randn(2, 3)
c = torch.randn(2, 3)
d = torch.randn(2, 3)
self.run_test(MyModel(), (a, b, c, d))
def test_nested_tuple_output(self):
class MyModel(torch.nn.Module):
def forward(self, a, b, c, d):
return a, ((b,), (c, d))
a = torch.randn(2, 3)
b = torch.randn(2, 3)
c = torch.randn(2, 3)
d = torch.randn(2, 3)
self.run_test(MyModel(), (a, b, c, d))
def test_tuple_input(self):
class TupleModel(torch.nn.Module):
def forward(self, a: Tuple[torch.Tensor, torch.Tensor]):
return a
x = (torch.randn(3, 4), torch.randn(4, 3))
self.run_test(TupleModel(), input=(x,))
def test_tuple_primitive_input(self):
class TupleModel(torch.nn.Module):
def forward(self, a: Tuple[int, torch.Tensor], b):
return a[0], a[1] + b
x = (3, torch.randn(4, 3))
y = torch.randn(4, 3)
self.run_test(TupleModel(), input=(x, y))
def test_nested_tuple_input(self):
class NestedTupleModel(torch.nn.Module):
def forward(self, a, b: Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]):
return a + b[0] + b[1][0] + b[1][1]
x = torch.randn(4, 5)
y = (torch.randn(4, 5), (torch.randn(1, 5), torch.randn(4, 1)))
self.run_test(NestedTupleModel(), input=(x, y))
@disableScriptTest()
def test_optional_inputs_with_no_optionals(self):
class NoOptionalModel(torch.nn.Module):
def forward(self, input):
return input
# Without empty optional arguments dictionary
x = torch.randn(2, 3)
self.run_test(NoOptionalModel(), (x,))
# With empty optional arguments dictionary
y = torch.randn(2, 3)
self.run_test(NoOptionalModel(), (y, {}))
@disableScriptTest()
def test_optional_inputs_with_mixed_optionals(self):
class MixedModel(torch.nn.Module):
def forward(self, x, y=None, z=None):
if y is not None:
return x + y
if z is not None:
return x + z
return x
x = torch.randn(2, 3)
y = torch.randn(2, 3)
z = torch.randn(2, 3)
# Without optional arguments dictionary
self.run_test(MixedModel(), (x, y, None))
self.run_test(MixedModel(), (x, None, z))
# With optional arguments dictionary
self.run_test(MixedModel(), (x, {"y": y, "z": None}))
self.run_test(MixedModel(), (x, {"y": None, "z": z}))
self.run_test(MixedModel(), (x, {"z": z}))
self.run_test(MixedModel(), (x, {"y": y}))
@disableScriptTest()
def test_optional_inputs_with_all_optionals(self):
class AllOptionalModel(torch.nn.Module):
def forward(self, y=None, z=None):
if y is not None:
return y
if z is not None:
return z
y = torch.randn(2, 3)
# Without optional arguments dictionary
self.run_test(AllOptionalModel(), (y, None))
# With optional arguments dictionary
self.run_test(AllOptionalModel(), {"y": y, "z": None})
@disableScriptTest()
def test_input_names_with_optional_args(self):
class NoOptionalModel(torch.nn.Module):
def forward(self, input):
return input
# Without empty optional arguments dictionary
x = torch.randn(2, 3)
self.run_test(NoOptionalModel(), (x,), input_names=["input_x"])
# With empty optional arguments dictionary
y = torch.randn(2, 3)
self.run_test(NoOptionalModel(), (y, {}))
class MixedModel(torch.nn.Module):
def forward(self, x, y=None, z=None):
if y is not None:
return x + y
if z is not None:
return x + z
return x
x = torch.randn(2, 3)
y = torch.randn(2, 3)
z = torch.randn(2, 3)
# Without optional arguments dictionary
self.run_test(MixedModel(), (x, y, None), input_names=["input_x", "input_y"])
self.run_test(MixedModel(), (x, None, z), input_names=["input_x", "input_z"])
# With optional arguments dictionary
self.run_test(MixedModel(), (x, {"y": y, "z": None}), input_names=["input_x", "input_y"])
self.run_test(MixedModel(), (x, {"y": None, "z": z}), input_names=["input_x", "input_z"])
class AllOptionalModel(torch.nn.Module):
def forward(self, y=None, z=None):
if y is not None:
return y
if z is not None:
return z
y = torch.randn(2, 3)
z = torch.randn(2, 3)
# Without optional arguments dictionary
self.run_test(AllOptionalModel(), (y, None), input_names=["input_y"])
self.run_test(AllOptionalModel(), (None, z), input_names=["input_z"])
# With optional arguments dictionary
self.run_test(AllOptionalModel(), {"y": y, "z": None}, input_names=["input_y"])
self.run_test(AllOptionalModel(), {"y": None, "z": z}, input_names=["input_z"])
def test_input_as_output(self):
class Model(torch.nn.Module):
def forward(self, x, y):
return x, y
x = torch.randn(2, 3)
y = torch.randn(3, 4)
self.run_test(Model(), (x, y), input_names=["x", "y"], output_names=["x_out", "y_out"])
@disableScriptTest()
def test_none_as_input(self):
class Model(torch.nn.Module):
def forward(self, x, y):
if y is not None:
return x + y
return x
x = torch.randn(2, 3)
self.run_test(Model(), (x, None))
@disableScriptTest()
def test_none_as_tuple_input(self):
class Model(torch.nn.Module):
def forward(self, x, y):
if y[0] is not None:
return x + y[0]
if y[1] is not None:
return x + y[1]
return x
x = torch.randn(2, 3)
y = torch.randn(2, 3)
self.run_test(Model(), (x, (None, y)))
@disableScriptTest()
def test_none_as_named_input(self):
class Model(torch.nn.Module):
def forward(self, x, y=None, z=None):
if y is not None:
return x + y
if z is not None:
return x + z
return x
x = torch.randn(2, 3)
z = torch.randn(2, 3)
self.run_test(Model(), (x, None, z))
def test_primitive_input_integer(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x: int, y):
return x + y
x = 3
y = torch.randint(10, (2, 3, 4))
self.run_test(Model(), (x, y))
def test_primitive_input_floating(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x: float, y):
return x + y
x = 3.0
y = torch.randn(2, 3, 4)
self.run_test(Model(), (x, y))
def test_primitive_input_bool(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, flag: bool, x, y):
if flag:
return x
else:
return y
flag = True
x = torch.randn(2, 3, 4)
y = torch.randn(2, 3, 4)
self.run_test(torch.jit.script(Model()), (flag, x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_cste_script(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.zeros(x.size(0)), torch.ones((x.size(1), x.size(0)), dtype=torch.int64)
x = torch.randn(3, 4)
self.run_test(MyModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(MyModel(), x, remained_onnx_input_idx=[])
def test_scalar_tensor(self):
class test(torch.nn.Module):
def forward(self, input):
return torch.scalar_tensor(input.size(0)), \
torch.scalar_tensor(input.size(1), dtype=torch.int64)
x = torch.randn(2, 3, 4)
y = torch.randn(7, 8, 9)
model = test()
self.run_test(model, x, test_with_inputs=[y],
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1, 2]})
def test_tensor(self):
class ScalarInputModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor(input.shape[1])
x = torch.randn(3, 4)
self.run_test(ScalarInputModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(ScalarInputModel(), x, remained_onnx_input_idx=[])
class TensorInputModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor([input.shape[0], input.shape[1]])
x = torch.randn(3, 4)
self.run_test(TensorInputModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(TensorInputModel(), x, remained_onnx_input_idx=[])
class FloatInputModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor([float(input)])
x = torch.randn(1)
self.run_test(FloatInputModel(), x)
class InputWithDtypeModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor(input.shape[1], dtype=torch.long)
x = torch.randn(3, 4)
self.run_test(InputWithDtypeModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(InputWithDtypeModel(), x, remained_onnx_input_idx=[])
class MixedInputModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor([input.shape[0], int(input)])
x = torch.randn(1)
self.run_test(MixedInputModel(), x)
def test_hardtanh(self):
model = torch.nn.Hardtanh(-1.5, 2.5)
x = torch.arange(-5, 5).to(dtype=torch.float32)
self.run_test(model, x)
def test_hardtanh_script_with_default_values(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.nn.functional.hardtanh(x)
x = torch.arange(-5, 5).to(dtype=torch.float32)
self.run_test(MyModel(), x)
def test_hardswish(self):
model = torch.nn.Hardswish()
x = torch.rand(3, 3).to(dtype=torch.float32)
self.run_test(model, x)
# Testing edge cases
x = torch.tensor(3).to(dtype=torch.float32)
self.run_test(model, x)
x = torch.tensor(-3).to(dtype=torch.float32)
self.run_test(model, x)
def test_hardswish_script(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.nn.functional.hardswish(x)
x = torch.rand(3, 3).to(dtype=torch.float32)
self.run_test(MyModel(), x)
def test_hardsigmoid(self):
model = torch.nn.Hardsigmoid()
x = torch.rand(3, 3).to(dtype=torch.float32)
self.run_test(model, x)
# corner cases
x = torch.tensor(3).to(dtype=torch.float32)
self.run_test(model, x)
x = torch.tensor(-3).to(dtype=torch.float32)
self.run_test(model, x)
def test_clamp(self):
class ClampModel(torch.nn.Module):
def forward(self, x):
return x.clamp(-0.5, 0.5)
x = torch.randn(3, 4)
self.run_test(ClampModel(), x)
class ClampMinModel(torch.nn.Module):
def forward(self, x):
return x.clamp(min=-0.5)
x = torch.randn(3, 4)
self.run_test(ClampMinModel(), x)
class ClampMaxModel(torch.nn.Module):
def forward(self, x):
return x.clamp(max=0.5)
x = torch.randn(3, 4)
self.run_test(ClampMaxModel(), x)
@skipIfUnsupportedMinOpsetVersion(8)
def test_clamp_dyn(self):
class ClampMaxModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return x.clamp(None, x.size(0))
x = torch.arange(16).view(4, 4).float()
self.run_test(ClampMaxModel(), x)
class ClampMinModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return x.clamp(x.size(0), None)
x = torch.arange(16).view(4, 4).float()
self.run_test(ClampMinModel(), x)
class ClampMinMaxModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return x.clamp(x.size(0), x.size(1))
x = torch.arange(16).view(2, 8).float()
self.run_test(ClampMinMaxModel(), x)
class ClampTensorModel(torch.nn.Module):
def forward(self, x, min, max):
return x.clamp(min, max)
x = torch.randn(3, 4)
y = torch.randn(3, 4)
z = torch.randn(3, 4)
self.run_test(ClampTensorModel(), (x, y, z))
class ClampTensorMinModel(torch.nn.Module):
def forward(self, x, min):
return x.clamp(min=min)
self.run_test(ClampTensorMinModel(), (x, y))
class ClampTensorMaxModel(torch.nn.Module):
def forward(self, x, max):
return x.clamp(max=max)
self.run_test(ClampTensorMaxModel(), (x, z))
@skipIfUnsupportedMinOpsetVersion(9)
def test_full_trace(self):
class FullModel(torch.nn.Module):
def forward(self, x):
return torch.full((3, 4), x, dtype=torch.long)
x = torch.tensor(12)
self.run_test(FullModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_full_script(self):
class FullModelScripting(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.full((3, 4), x, dtype=torch.long)
x = torch.tensor(12)
self.run_test(FullModelScripting(), x)
def test_fuse_addmm(self):
class AddmmModel(torch.nn.Module):
def forward(self, x):
return torch.mm(x, x) + x
x = torch.ones(3, 3)
self.run_test(AddmmModel(), x)
def test_maxpool(self):
model = torch.nn.MaxPool1d(2, stride=1)
x = torch.randn(20, 16, 50)
self.run_test(model, x)
def test_conv(self):
class TraceModel(torch.nn.Module):
def __init__(self):
super(TraceModel, self).__init__()
self.conv1 = torch.nn.Conv1d(16, 33, 3, stride=2)
self.conv2 = torch.nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1))
self.conv3 = torch.nn.Conv3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(4, 2, 0))
def forward(self, input1, input2, input3):
return self.conv1(input1), self.conv2(input2), self.conv3(input3)
x1 = torch.randn(20, 16, 50)
x2 = torch.randn(20, 16, 50, 100)
x3 = torch.randn(20, 16, 10, 50, 100)
self.run_test(TraceModel(), (x1, x2, x3), atol=10e-5)
def test_conv_shape_inference(self):
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.conv2 = torch.nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1))
def forward(self, input):
return self.conv2(input) + 2
x = torch.randn(20, 16, 50, 100)
self.run_test(Model(), x, atol=10e-5,
input_names=["x"],
dynamic_axes={"x": [0]})
def test_conv_transpose(self):
class TraceModel(torch.nn.Module):
def __init__(self):
super(TraceModel, self).__init__()
self.conv1 = torch.nn.ConvTranspose1d(16, 33, 3, stride=2)
self.conv2 = torch.nn.ConvTranspose2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1))
self.conv3 = torch.nn.ConvTranspose3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(4, 2, 0))
def forward(self, input1, input2, input3):
return self.conv1(input1), self.conv2(input2), self.conv3(input3)
x1 = torch.randn(20, 16, 50)
x2 = torch.randn(20, 16, 50, 100)
x3 = torch.randn(20, 16, 10, 50, 100)
self.run_test(TraceModel(), (x1, x2, x3), atol=10e-5)
# Conversion of Transpose depends on input shape to be known.
# The following test only works when onnx shape inference is enabled.
@skipIfONNXShapeInference(False)
def test_transpose_infer_shape(self):
class TransposeModule(torch.jit.ScriptModule):
def __init__(self):
super(TransposeModule, self).__init__()
self.conv = torch.nn.Conv2d(3, 1, 3, stride=2)
@torch.jit.script_method
def forward(self, x):
x = self.conv(x)
return x.transpose(0, 1)
x = torch.randn(32, 3, 64, 64)
y = torch.randn(16, 3, 8, 64)
self.run_test(TransposeModule(), x, input_names=["x"],
dynamic_axes={"x": [0, 2]},
test_with_inputs=[y])
def squeeze_model_tests(self, d, x1, x2):
class Squeeze(torch.nn.Module):
def __init__(self, d):
super(Squeeze, self).__init__()
self.d = d
def forward(self, x):
if self.d is not None:
return torch.squeeze(x, dim=self.d)
else:
return torch.squeeze(x)
x2 = [] if x2 is None else [x2]
if len(x2) > 0:
self.run_test(Squeeze(d), x1,
input_names=["input"], dynamic_axes={"input": {0: "0", 1: "1", 2: "2"}},
test_with_inputs=x2)
else:
self.run_test(Squeeze(d), x1)
def test_squeeze_without_no_op(self):
x = torch.randn(2, 1, 4)
self.squeeze_model_tests(1, x, None)
@skipIfUnsupportedMinOpsetVersion(11)
def test_squeeze_dynamic(self):
x_squeeze = torch.randn(2, 1, 4)
x_noop = torch.randn(2, 2, 3)
self.squeeze_model_tests(1, x_squeeze, x_noop)
def test_squeeze_neg_without_no_op(self):
x = torch.randn(2, 1, 4)
self.squeeze_model_tests(-2, x, None)
@skipIfUnsupportedMinOpsetVersion(11)
def test_squeeze_neg(self):
x_squeeze = torch.randn(2, 1, 4)
x_noop = torch.randn(2, 2, 3)
self.squeeze_model_tests(-2, x_squeeze, x_noop)
def test_squeeze_all_dims(self):
x_squeeze = torch.randn(2, 1, 4)
x_noop = torch.randn(2, 2, 3)
self.squeeze_model_tests(None, x_squeeze, x_noop)
@skipIfUnsupportedMinOpsetVersion(11)
def test_squeeze_no_op(self):
x_noop = torch.randn(2, 1, 4)
x_squeeze = torch.randn(2, 2, 1)
self.squeeze_model_tests(2, x_noop, x_squeeze)
@skipIfUnsupportedMinOpsetVersion(11)
def test_squeeze_runtime_dim(self):
class Squeeze(torch.nn.Module):
def forward(self, d1, d2):
t = torch.zeros(d1[0], d2[0])
return t.squeeze(0)
d1 = torch.tensor([1])
d3 = torch.tensor([3])
d4 = torch.tensor([4])
self.run_test(Squeeze(), (d1, d4), test_with_inputs=[(d3, d4)])
self.run_test(Squeeze(), (d3, d4), test_with_inputs=[(d1, d3)])
def test_squeeze(self):
class Squeeze(torch.nn.Module):
def forward(self, x):
return torch.squeeze(x, dim=-2)
x = torch.randn(2, 1, 4)
self.run_test(Squeeze(), x)
def test_unsqueeze(self):
class Unsqueeze(torch.nn.Module):
def forward(self, x):
return torch.unsqueeze(x, dim=-2)
x = torch.randn(2, 3, 4)
self.run_test(Unsqueeze(), x)
def test_maxpool_default_stride(self):
class MaxPoolModel(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.max_pool2d(x, 2)
model = MaxPoolModel()
x = torch.randn(10, 20, 16, 50)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(8)
def test_maxpool_adaptive(self):
model = torch.nn.AdaptiveMaxPool1d((5), return_indices=False)
x = torch.randn(20, 16, 50, requires_grad=True)
y = torch.randn(32, 16, 50, requires_grad=True)
self.run_test(model, x, input_names=["x"],
dynamic_axes={"x" : [0]},
test_with_inputs=[y])
def test_maxpool_2d(self):
model = torch.nn.MaxPool2d(5, padding=(1, 2))
x = torch.randn(1, 20, 16, 50, requires_grad=True)
self.run_test(model, x)
def test_maxpool_1d_ceil(self):
model = torch.nn.MaxPool1d(3, 2, ceil_mode=True)
x = torch.randn(20, 16, 50)
self.run_test(model, x)
def test_maxpool_2d_ceil(self):
model = torch.nn.MaxPool2d(3, 2, ceil_mode=True)
x = torch.randn(20, 16, 50, 32)
self.run_test(model, x)
def test_maxpool_3d_ceil(self):
model = torch.nn.MaxPool3d(3, 2, ceil_mode=True)
x = torch.randn(20, 16, 50, 44, 31)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(8)
@disableScriptTest() # Functional module not scriptable
def test_maxpool_with_indices(self):
model = torch.nn.MaxPool1d(2, stride=1, return_indices=True)
x = torch.randn(20, 16, 50)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(10)
def test_maxpool_dilation(self):
model = torch.nn.MaxPool1d(2, stride=1, dilation=2)
x = torch.randn(20, 16, 50)
self.run_test(model, x)
def test_avgpool_default_stride(self):
class AvgPoolModel(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.avg_pool2d(x, 2)
model = AvgPoolModel()
x = torch.randn(10, 20, 16, 50)
self.run_test(model, x)
def test_avgpool(self):
model = torch.nn.AvgPool1d(2, stride=1)
x = torch.randn(20, 16, 50)
self.run_test(model, x)
def test_avgpool_1d_ceil(self):
model = torch.nn.AvgPool1d(3, 2, ceil_mode=True)
x = torch.randn(1, 1, 7)
self.run_test(model, x)
def test_avgpool_2d_ceil(self):
model = torch.nn.AvgPool2d(3, 2, ceil_mode=True)
x = torch.randn(20, 16, 50, 32)
self.run_test(model, x)
def test_avgpool_3d_ceil(self):
model = torch.nn.AvgPool3d(3, 2, ceil_mode=True)
x = torch.randn(20, 16, 50, 44, 31)
y = torch.randn(32, 8, 50, 44, 31)
self.run_test(model, x, input_names=["x"],
dynamic_axes={"x" : [0, 1]},
test_with_inputs=[y])
@skipIfUnsupportedMinOpsetVersion(9)
def test_floating_point(self):
class FloatingPoint(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
if x.is_floating_point():
return x.new_zeros(x.shape)
return x.new_zeros(x.shape)
x = torch.randn(2, 3, 4)
self.run_test(FloatingPoint(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(FloatingPoint(), x, remained_onnx_input_idx=[])
class FloatingPoint(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
if x.size(0) > 1:
a = x + 2
if a.is_floating_point():
return x + 1
return x + 1
return x
x = torch.randn(2, 3, 4)
self.run_test(FloatingPoint(), x)
# Operator rank mismatch between outputs of two branches for opsets below 11.
@skipIfUnsupportedMinOpsetVersion(11)
@skipIfONNXShapeInference(False)
def test_floating_point_infer_dtype(self):
class FloatingPoint(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
if x.size(0) > 1:
a = x + 2
if a.is_floating_point():
return x.new_zeros(x.shape[1:])
return x.new_zeros(x.shape)
return x
x = torch.randn(2, 3, 4)
self.run_test(FloatingPoint(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(FloatingPoint(), x, remained_onnx_input_idx=[])
class FloatingPoint(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
if x.size(0) > 1:
a = x + 2
if a.is_floating_point():
return x + 1
return x
return x
x = torch.randn(2, 3, 4).to(torch.int32)
self.run_test(FloatingPoint(), x)
@skipIfUnsupportedMinOpsetVersion(12)
def test_prim_min(self):
@torch.jit.script
def list_append(boxes: List[torch.Tensor]):
temp = []
for i, b in enumerate(boxes): # enumerate is creating a prim::min op in torch graph
temp.append(torch.full_like(b[:, 1], i))
return temp[0]
class Min(torch.nn.Module):
def forward(self, x):
boxes = [x, x, x]
return list_append(boxes)
x = torch.rand(5, 5)
self.run_test(Min(), (x,))
class M(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
i = 3
return min(x[i], i)
x = torch.arange(6, dtype=torch.int64)
self.run_test(M(), (x,))
def test_arithmetic(self):
class ArithmeticModule(torch.nn.Module):
def forward(self, x):
x = x + 2
x = x - 4
x = x * 6
x = x / 8
return x
x = torch.randn(2, 3, 4)
self.run_test(ArithmeticModule(), x)
def test_arithmetic_prim_long(self):
class ArithmeticModule(torch.nn.Module):
def forward(self, x, y: int):
x = x + y
x = x - y
x = x * (y * 3)
x = x / (y * 4)
return x
x = torch.randn(2, 3, 4)
y = 2
self.run_test(ArithmeticModule(), (x, y))
class ArithmeticModule(torch.nn.Module):
def forward(self, x):
x = x + 2
x = x - 3
return x.shape[0]
x = torch.randn(2, 3, 4)
self.run_test(ArithmeticModule(), x, remained_onnx_input_idx=[])
def test_arithmetic_prim_float(self):
class ArithmeticModule(torch.nn.Module):
def forward(self, x, y: float):
x = x + y
x = x - y
x = x * (y * 3)
x = x / (y * 4)
return x
x = torch.randn(2, 3, 4)
y = 2.5
self.run_test(ArithmeticModule(), (x, y))
class ArithmeticModule(torch.nn.Module):
def forward(self, x):
x = x + 2
x = x - 3
return x.shape[1] / 2
x = torch.randn(2, 3, 4)
self.run_test(ArithmeticModule(), x, remained_onnx_input_idx=[])
def test_arithmetic_prim_bool(self):
class ArithmeticModule(torch.nn.Module):
def forward(self, x, y: int, z: bool, t: float):
x = x + y
x = x - y
if z:
x = x * (y * 3)
x = x / (y * 4)
return x / t, z
x = torch.randn(2, 3, 4)
y = 2
z = False
t = 2.5
self.run_test(ArithmeticModule(), (x, y, z, t))
class ArithmeticModule(torch.nn.Module):
def forward(self, x: int, y: int):
return x == y
x = 3
y = 2
self.run_test(ArithmeticModule(), (x, y))
@disableScriptTest()
def test_tuple_with_none_outputs(self):
class TupleModel(torch.nn.Module):
def forward(self, x):
l = (x, None, (x, None))
return (x, l)
model = TupleModel()
x = torch.randn(3, 4)
self.run_test(TupleModel(), (x,))
# In scripting the first transpose node do not carry shape and dtype info.
# The following test only works when onnx shape inference is enabled.
@skipIfONNXShapeInference(False)
def test_arithmetic_infer_dtype(self):
class ArithmeticModule(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
x = x.t()
x = x + 2
x = x - 4
x = x * 6
x = x / 8
return x
x = torch.randn(2, 3)
self.run_test(ArithmeticModule(), x)
def test_floor_div(self):
class FloorDivModule(torch.nn.Module):
def forward(self, x, y):
return x // 3, x // 2., \
x.to(dtype=torch.float64) // 3, x.to(dtype=torch.float64) // 2., \
x.to(dtype=torch.int64) // 3, x.to(dtype=torch.int64) // 2., \
x // (y + 1.).to(dtype=torch.int64), x // y, \
x.to(dtype=torch.float64) // y.to(dtype=torch.int64), x.to(dtype=torch.float64) // y.to(dtype=torch.float64), \
x.to(dtype=torch.int64) // y.to(dtype=torch.int64), x.to(dtype=torch.int64) // y
x = torch.randn(2, 3, 4)
y = torch.arange(1, 2 * 3 * 4 + 1).reshape(2, 3, 4)
self.run_test(FloorDivModule(), (x, y))
def test_floor_div_script(self):
class FloorDivModule(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x, y):
return x // 3, x // 2., x // y
x = torch.randn(2, 3, 4)
y = torch.randn(2, 3, 4)
self.run_test(FloorDivModule(), (x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_floordiv(self):
class FloordivModule(torch.nn.Module):
def forward(self, x):
return x.new_zeros(x.size(2) // x.size(1))
x = torch.randn(2, 3, 4)
self.run_test(FloordivModule(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(FloordivModule(), (x,), remained_onnx_input_idx=[])
def test_div(self):
class DivModule(torch.nn.Module):
def forward(self, x, y):
return x / y, torch.true_divide(x, y)
x = torch.randn(2, 3, 4).to(torch.int)
y = torch.arange(1, 2 * 3 * 4 + 1).reshape(2, 3, 4).to(torch.int)
self.run_test(DivModule(), (x, y))
self.run_test(DivModule(), (x.float(), y.float()))
# Note: div cannot (generally) be exported via scripting
# since its type promotion logic is dependent on knowing the scalar types
# of the input tensors. That is, the ONNX graph is dependent on the
# data type of the inputs. This makes it appropriate for tracing only.
def test_div_promotion_trace(self):
class DivModule(torch.nn.Module):
def forward(self, x, y):
return x / y, torch.true_divide(x, y)
x = torch.randn(2, 3, 4).to(torch.int)
y = torch.arange(1, 2 * 3 * 4 + 1).reshape(2, 3, 4).to(torch.int)
prev_default = torch.get_default_dtype()
torch.set_default_dtype(torch.float)
self.run_test(torch.jit.trace(DivModule(), (x, y)), (x, y))
torch.set_default_dtype(torch.double)
self.run_test(torch.jit.trace(DivModule(), (x, y)), (x, y))
torch.set_default_dtype(prev_default)
# In scripting x, y do not carry shape and dtype info.
# The following test only works when onnx shape inference is enabled.
@skipIfONNXShapeInference(False)
def test_div_promotion_script(self):
class DivModule(torch.nn.Module):
def forward(self, x, y):
# Add transpose to hide shape/type information
# Otherwise shape and type are still avaiable from input.
x = x.transpose(1, 2)
y = y.transpose(1, 2)
return x / y, torch.true_divide(x, y)
x = torch.randn(2, 3, 4).to(torch.int)
y = torch.arange(1, 2 * 3 * 4 + 1).reshape(2, 3, 4).to(torch.int)
prev_default = torch.get_default_dtype()
# 1. x,y are int, and output is float.
# This can be handled by the default case, where both are cast to float.
# It works even if type of x, y are unknown.
torch.set_default_dtype(torch.float)
self.run_test(torch.jit.script(DivModule()), (x, y))
# 2. x,y are int, and output is double.
# This can be handled by the default case, where both are cast to double.
# It works even if type of x, y are unknown.
torch.set_default_dtype(torch.double)
self.run_test(torch.jit.script(DivModule()), (x, y))
# 3. x is int, y is double, and output is double.
# This can only be handled when both type of x and y are known.
torch.set_default_dtype(prev_default)
x = torch.randn(2, 3, 4).to(torch.int)
y = torch.arange(1, 2 * 3 * 4 + 1).reshape(2, 3, 4).to(torch.double)
self.run_test(torch.jit.script(DivModule()), (x, y))
def test_div_rounding_mode(self):
class TrueDivModule(torch.nn.Module):
def forward(self, x, y):
return (x.div(y, rounding_mode=None),
torch.div(x, y, rounding_mode=None))
class TruncDivModule(torch.nn.Module):
def forward(self, x, y):
return (x.div(y, rounding_mode="trunc"),
torch.div(x, y, rounding_mode="trunc"))
class FloorDivModule(torch.nn.Module):
def forward(self, x, y):
return (x.div(y, rounding_mode="floor"),
torch.div(x, y, rounding_mode="floor"))
modules = [TrueDivModule(), TruncDivModule()]
if self.opset_version >= 9:
modules.append(FloorDivModule())
x = (torch.randn(2, 3, 4) * 100).to(torch.int)
y = torch.arange(1, 2 * 3 * 4 + 1).reshape(2, 3, 4).to(torch.int)
for module in modules:
self.run_test(module, (x, y))
self.run_test(torch.jit.trace(module, (x, y)), (x, y))
self.run_test(torch.jit.script(module), (x, y))
x = torch.randn(2, 3, 4)
y = torch.rand(2, 3, 4) * 10.0 + 0.1
for module in modules:
self.run_test(module, (x, y))
self.run_test(torch.jit.trace(module, (x, y)), (x, y))
self.run_test(torch.jit.script(module), (x, y))
def test_slice_trace(self):
class MyModule(torch.nn.Module):
def forward(self, x):
return x[0:1]
x = torch.randn(3)
self.run_test(MyModule(), x)
def test_slice_neg(self):
class NegSlice(torch.nn.Module):
def forward(self, x):
return x[-1:]
x = torch.randn(3, 4, 5)
self.run_test(NegSlice(), x)
def test_slice_neg_large(self):
class NegSlice(torch.nn.Module):
def forward(self, x):
return x[:, :, -3:-1, :, -1]
x = torch.randn(3, 4, 5, 6, 7)
self.run_test(NegSlice(), x)
def test_slice_neg_large_negone(self):
class NegSlice(torch.nn.Module):
def forward(self, x):
return x[:, :, :, :, -1]
x = torch.randn(3, 4, 5, 6, 7)
self.run_test(NegSlice(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_slice_with_input_index(self):
class InputIndexSlice(torch.nn.Module):
def forward(self, x, y):
x[:y.size(0), 0, :] = y
return x
x = torch.zeros((56, 6, 256))
y = torch.rand((22, 256))
self.run_test(InputIndexSlice(), (x, y))
@skipIfUnsupportedMinOpsetVersion(10)
@disableScriptTest() # scripting tuple/list append
def test_slice_dynamic(self):
class DynamicSliceExportMod(torch.nn.Module):
def forward(self, x):
results = []
for i in range(4):
results.append(x[:x.size(0) - i, i:x.size(2), i:3])
return tuple(results)
x = torch.rand(5, 5, 5)
y = torch.randn(6, 7, 8)
self.run_test(DynamicSliceExportMod(), x, test_with_inputs=[y],
input_names=["input_1"],
output_names=["output_1"],
dynamic_axes={"input_1": [0, 1, 2],
"output_1": [0, 1, 2]})
@skipIfUnsupportedMinOpsetVersion(10)
def test_slice_dynamic_script(self):
class DynamicSliceModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return x[1:x.size(1)]
x = torch.rand(1, 2)
self.run_test(DynamicSliceModel(), x)
@skipIfUnsupportedMinOpsetVersion(10)
def test_slice_dynamic_shape_script(self):
class DynamicSliceModel(torch.nn.Module):
def forward(self, x):
return x.new_zeros(x.shape[1:x.size(2)])
x = torch.rand(1, 2, 3, 4)
self.run_test(DynamicSliceModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3]})
self.run_test(DynamicSliceModel(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(10)
@disableScriptTest() # scripting tuple/list append
def test_slice_dynamic_to_end(self):
class DynamicSliceExportMod(torch.nn.Module):
def forward(self, x):
results = []
for i in range(4):
results.append(x[:, i:, x.size(2) - 5])
return tuple(results)
x = torch.rand(5, 5, 5)
self.run_test(DynamicSliceExportMod(), x,
dynamic_axes={"input_1": [0, 1, 2],
"output_1": [0, 1, 2]})
def test_square(self):
class Square(torch.nn.Module):
def forward(self, x):
return torch.square(x)
x = torch.randn(2, 3, 4)
self.run_test(Square(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_arange_dynamic(self):
class ArangeModel(torch.nn.Module):
def forward(self, input):
return torch.arange(input.shape[0]), \
torch.arange(12), \
torch.arange(start=input.shape[0], end=input.shape[0] + 5)
x = torch.randn(5, 3, 2)
y = torch.randn(8, 3, 2)
self.run_test(ArangeModel(), x, test_with_inputs=[y],
input_names=["input_1"],
output_names=["output_1", "output_2", "output_3"],
dynamic_axes={"input_1": [0],
"output_1": [0]})
self.run_test(torch.jit.script(ArangeModel()), x,
test_with_inputs=[y], input_names=["input_1"],
output_names=["output_1", "output_2", "output_3"],
dynamic_axes={"input_1": [0],
"output_1": [0]})
@skipIfUnsupportedMinOpsetVersion(9)
def test_dynamic_arange_out(self):
class ArangeOutModel(torch.nn.Module):
def forward(self, end):
out_t = torch.tensor([1], dtype=torch.int64)
return torch.arange(end, out=out_t)
x = torch.tensor(8)
self.run_test(ArangeOutModel(), (x))
@skipIfUnsupportedMinOpsetVersion(9)
def test_dynamic_arange_start_out(self):
class ArangeStartOutModel(torch.nn.Module):
def forward(self, start, end):
out_t = torch.tensor([1], dtype=torch.int64)
return torch.arange(start.size(0), end, out=out_t)
x = torch.randn(2, 3, 4)
y = torch.tensor(8)
self.run_test(ArangeStartOutModel(), (x, y),
input_names=["x", "y"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(ArangeStartOutModel(), (x, y), remained_onnx_input_idx=[1])
@skipIfUnsupportedMinOpsetVersion(9)
def test_linspace(self):
class LinspaceModel(torch.nn.Module):
def forward(self, start, end, steps):
return torch.linspace(start, end, steps)
x = torch.tensor(3, dtype=torch.float)
y = torch.tensor(10, dtype=torch.float)
z = torch.tensor(5, dtype=torch.int)
self.run_test(LinspaceModel(), (x, y, z))
@skipIfUnsupportedMinOpsetVersion(9)
def test_arange_with_floats_out(self):
class ArangeModelEnd(torch.nn.Module):
def forward(self, end):
out_t = torch.tensor([1], dtype=torch.float)
return torch.arange(end, out=out_t)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(ArangeModelEnd(), (y))
class ArangeModelStep(torch.nn.Module):
def forward(self, start, end):
out_t = torch.tensor([1], dtype=torch.float)
return torch.arange(start.size(0), end, 1.5, out=out_t)
x = torch.randn(2, 3, 4)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(ArangeModelStep(), (x, y), input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2]})
self.run_test(ArangeModelStep(), (x, y), remained_onnx_input_idx=[1])
@skipIfUnsupportedMinOpsetVersion(9)
def test_arange_with_floats(self):
class ArangeModelEnd(torch.nn.Module):
def forward(self, end):
return torch.arange(end)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(ArangeModelEnd(), (y))
class ArangeModelStep(torch.nn.Module):
def forward(self, start, end):
return torch.arange(start.size(0), end, 1.5)
x = torch.randn(2, 3, 4)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(ArangeModelStep(), (x, y), input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2]})
self.run_test(ArangeModelStep(), (x, y), remained_onnx_input_idx=[1])
class ArangeModelStepNeg(torch.nn.Module):
def forward(self, start, end):
return torch.arange(end, start.size(0), -1.5)
x = torch.randn(2, 3, 4)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(ArangeModelStepNeg(), (x, y), input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2]})
self.run_test(ArangeModelStepNeg(), (x, y), remained_onnx_input_idx=[1])
class ArangeModelStart(torch.nn.Module):
def forward(self, start, end):
return torch.arange(start.size(0), end)
x = torch.randn(2, 3, 4)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(ArangeModelStart(), (x, y), input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2]})
self.run_test(ArangeModelStart(), (x, y), remained_onnx_input_idx=[1])
@skipIfUnsupportedMinOpsetVersion(9)
def test_arange_with_floats_override(self):
class ArangeModelEnd(torch.nn.Module):
def forward(self, end):
return torch.arange(end, dtype=torch.int64)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(ArangeModelEnd(), (y))
class ArangeModelStep(torch.nn.Module):
def forward(self, start, end):
return torch.arange(start.size(0), end, 1.5, dtype=torch.int64)
x = torch.randn(2, 3, 4)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(ArangeModelStep(), (x, y), input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2]})
self.run_test(ArangeModelStep(), (x, y), remained_onnx_input_idx=[1])
@skipIfUnsupportedMinOpsetVersion(11)
def test_arange_out(self):
class ArangeOutModel(torch.nn.Module):
def forward(self, end):
out_t = torch.tensor([1], dtype=torch.float)
return torch.arange(end, out=out_t)
x = torch.tensor(8.5, dtype=torch.float)
self.run_test(ArangeOutModel(), (x))
@skipIfUnsupportedMinOpsetVersion(11)
def test_arange_start_out(self):
class ArangeStartOutModel(torch.nn.Module):
def forward(self, start, end):
out_t = torch.tensor([1], dtype=torch.float)
return torch.arange(start.size(0), end, out=out_t)
x = torch.randn(2, 3, 4)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(ArangeStartOutModel(), (x, y), input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2]})
self.run_test(ArangeStartOutModel(), (x, y), remained_onnx_input_idx=[1])
@skipIfUnsupportedMinOpsetVersion(11)
def test_arange_no_type(self):
class ArangeModel(torch.nn.Module):
def forward(self, end):
return torch.arange(end), \
torch.arange(0, end)
x = torch.tensor(6.2, dtype=torch.float)
self.run_test(ArangeModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_size(self):
class SizeModel(torch.nn.Module):
def forward(self, input):
return torch.arange(input.size(0)), torch.arange(input.size(-1)), torch.ones(input.shape)
x = torch.randn(5, 3, 2)
self.run_test(SizeModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(SizeModel(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
@disableScriptTest() # x.stride() not scriptable
def test_as_strided(self):
class Model(torch.nn.Module):
def forward(self, x):
chunk_size = list(x.size())
chunk_size[1] = chunk_size[1] * 2 - 1
chunk_stride = list(x.stride())
chunk_stride[1] = chunk_stride[1] // 2
return x.as_strided((3, 3, 3), (1, 4, 2), storage_offset=2), x.as_strided(chunk_size, chunk_stride)
x = torch.randn(5, 8, 7)
self.run_test(Model(), x)
@disableScriptTest() # Ellipses followed by tensor indexing not scriptable
def test_tensor_index_advanced_indexing_ellipsis(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[..., torch.tensor([2, 1]), torch.tensor([0, 3])]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), (m1,))
def test_tensor_index_advanced_indexing(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[:, torch.tensor([[0, 2], [1, 1]]), :, torch.tensor([2, 1]), torch.tensor([0, 3])]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), (m1,))
class MyModel(torch.nn.Module):
def forward(self, input):
return input[:, torch.tensor([0, 2]), None, 2:4, torch.tensor([[1, 3], [4, 0]])]
self.run_test(MyModel(), (m1,))
class MyModel(torch.nn.Module):
def forward(self, input):
return input[:, torch.tensor([0, 2]), torch.tensor([1]), 2:4, torch.tensor([[1], [4]])]
self.run_test(MyModel(), (m1,))
def test_tensor_index_advanced_indexing_consecutive(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[:, torch.tensor([0, 2]), torch.tensor([[1, 3], [4, 0]]), None]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), (m1,))
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put(self):
class IndexPutModel(torch.nn.Module):
def forward(self, x, ind, update):
x[ind] = update
return x
x = torch.randn(3, 4)
ind = torch.tensor([1], dtype=torch.long)
update = torch.ones(4)
self.run_test(IndexPutModel(), (x, ind, update))
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_singular(self):
class IndexPutBoolModel(torch.nn.Module):
def forward(self, mask, indices):
mask[indices] = True
return mask
mask = torch.zeros(100, dtype=torch.bool)
indices = (torch.rand(25) * mask.shape[0]).to(torch.int64)
self.run_test(IndexPutBoolModel(), (mask, indices))
class IndexPutFloatModel(torch.nn.Module):
def forward(self, mask, indices):
mask[indices] = torch.tensor(5.5)
return mask
mask = torch.rand(100, dtype=torch.float)
indices = (torch.rand(50) * mask.shape[0]).to(torch.int64)
self.run_test(IndexPutFloatModel(), (mask, indices))
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_accumulate(self):
class IndexPutModel(torch.nn.Module):
def forward(self, x, ind, update):
return x.index_put((ind, ), update, accumulate=True)
x = torch.randn(3, 4)
ind = torch.tensor([2], dtype=torch.long)
update = torch.ones(4)
self.run_test(IndexPutModel(), (x, ind, update))
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_slice_index(self):
class IndexPutModel(torch.nn.Module):
def forward(self, x, update):
x[1:2, 1:3, torch.tensor([1])] += update
return x
x = torch.randn(3, 4, 5)
update = torch.tensor([10, 15]).view(1, 2, 1)
self.run_test(IndexPutModel(), (x, update))
class IndexPutModel2(torch.nn.Module):
def forward(self, x, update):
x[torch.tensor([0, 2]), torch.tensor([1, 2])] += update
return x
x = torch.randn(3, 4, 5)
update = torch.randn(2, 5)
self.run_test(IndexPutModel2(), (x, update))
class IndexPutModel3(torch.nn.Module):
def forward(self, x, update):
x[torch.tensor([0, 2]), 1:2] += update
return x
x = torch.randn(3, 4, 5)
update = torch.tensor([10, 15]).view(2, 1, 1)
self.run_test(IndexPutModel3(), (x, update))
class IndexPutModel4(torch.nn.Module):
def forward(self, x, update):
x[torch.tensor([0, 2]), 2] += update
return x
x = torch.randn(3, 4, 5)
update = torch.tensor([10, 15]).view(2, 1)
self.run_test(IndexPutModel4(), (x, update))
class IndexPutModel5(torch.nn.Module):
def forward(self, x, update):
x[1:3, torch.tensor([0, 2]), 2] += update
return x
x = torch.randn(3, 4, 5)
update = torch.tensor([10, 15]).view(2, 1)
self.run_test(IndexPutModel5(), (x, update))
class IndexPutModel6(torch.nn.Module):
def forward(self, x, update):
x[1:3, 0] = update
return x
x = torch.randn(3, 4, 5)
update = torch.arange(2 * 5).to(torch.float).view(2, 5)
self.run_test(IndexPutModel6(), (x, update))
class IndexPutModel7(torch.nn.Module):
def forward(self, x, update):
x[1:, 0] = update
return x
x = torch.randn(3, 4, 5)
update = torch.arange(2 * 5).to(torch.float).view(2, 5)
self.run_test(IndexPutModel7(), (x, update))
class IndexPutModel8(torch.nn.Module):
def forward(self, x, update):
x[:3, 0] = update
return x
x = torch.randn(3, 4, 5)
update = torch.arange(3 * 5).to(torch.float).view(3, 5)
self.run_test(IndexPutModel8(), (x, update))
class IndexPutModel9(torch.nn.Module):
def forward(self, poses):
w = 32
x = poses[:, :, 0] - (w - 1) // 2
boxes = torch.zeros([poses.shape[0], 17, 4])
boxes[:, :, 0] = x
return boxes
x = torch.zeros([2, 17, 3], dtype=torch.int64)
self.run_test(IndexPutModel9(), (x,))
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest() # Ellipses followed by tensor indexing not scriptable
def test_index_put_ellipsis(self):
class IndexPutModel(torch.nn.Module):
def forward(self, x, update):
x[..., torch.tensor([2, 1, 3]), 2:4] += update
return x
x = torch.randn(3, 4, 5, 6, 7)
update = torch.randn(3, 1, 1, 3, 2)
self.run_test(IndexPutModel(), (x, update))
class IndexPutModel2(torch.nn.Module):
def forward(self, x, update):
x[2, ..., torch.tensor([2, 1, 3]), 2:4] += update
return x
x = torch.randn(3, 4, 5, 6, 7)
update = torch.randn(4, 1, 3, 2)
self.run_test(IndexPutModel2(), (x, update))
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_loop(self):
@torch.jit.script
def ngram_attention_bias(sequence_length: int, ngram: int, device: torch.device, dtype: torch.dtype):
bias = torch.ones((ngram, sequence_length), device=device, dtype=dtype) * float("-inf")
for stream_idx in range(ngram):
for i in range(sequence_length):
bias = bias * 2
bias[stream_idx, i] = 5
bias = bias * 5
bias[0, 0] = 5
for stream_idx in range(ngram):
for i in range(sequence_length):
bias[stream_idx, i] = 5
bias[0, i] = 5
return bias
class ScriptModel(torch.nn.Module):
def __init__(self):
super(ScriptModel, self).__init__()
self.ngram = 2
self.max_target_positions = 512
def forward(self, hidden_states):
seq_length, batch_size = hidden_states.shape[:2]
predict_causal_mask = ngram_attention_bias(
self.max_target_positions, self.ngram, hidden_states.device, hidden_states.dtype
)
predict_causal_mask = predict_causal_mask[:, :seq_length]
return predict_causal_mask
x = torch.randn(6, 2)
y = torch.randn(4, 1)
self.run_test(ScriptModel(), x, input_names=["x"],
dynamic_axes={"x": {0: "seq_length", 1: "batch_size"}}, test_with_inputs=[y])
@skipIfUnsupportedMinOpsetVersion(11)
def test_copy_(self):
class CopyModel(torch.nn.Module):
def forward(self, x, data):
x[1:3] = data
return x
x = torch.randn(3, 4)
update = torch.randn(2, 4)
self.run_test(CopyModel(), (x, update))
# mixed slice and select
class CopyModel2(torch.nn.Module):
def forward(self, x, data):
x[1:3, 0] = data
return x
x = torch.randn(3, 4)
update = torch.tensor([0], dtype=torch.float32)
self.run_test(CopyModel2(), (x, update))
update = torch.tensor([2, 3], dtype=torch.float32)
self.run_test(CopyModel2(), (x, update))
update = torch.randn(2)
self.run_test(CopyModel2(), (x, update))
class CopyModel3(torch.nn.Module):
def forward(self, x, data):
x[1, 1:3] = data
return x
x = torch.randn(3, 4)
update = torch.tensor([0], dtype=torch.float32)
self.run_test(CopyModel3(), (x, update))
update = torch.tensor([2, 3], dtype=torch.float32)
self.run_test(CopyModel3(), (x, update))
update = torch.randn(2)
self.run_test(CopyModel3(), (x, update))
class CopyModel4(torch.nn.Module):
def forward(self, x, ind, data):
x[ind] = data
return x
x = torch.randn(3, 4)
ind = torch.tensor(2)
data = torch.randn(4)
self.run_test(CopyModel4(), (x, ind, data))
class CopyModel5(torch.nn.Module):
def forward(self, x, mask):
if mask is not None:
x.copy_(mask)
return x
x = torch.randn(3, 4)
mask = torch.randn(3, 1)
self.run_test(CopyModel5(), (x, mask))
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest() # Model not scriptable (output with shape doesn't match the broadcast shape)
def test_copy_tracing(self):
class CopyModel(torch.nn.Module):
def forward(self, x, data):
x[1, 1:3] = data
return x
x = torch.randn(3, 4)
update = torch.randn(1, 2)
self.run_test(CopyModel(), (x, update))
@skipIfUnsupportedMinOpsetVersion(11)
def test_copy_ellipsis(self):
class CopyModel(torch.nn.Module):
def forward(self, x, update):
x[..., 1] = update
return x
x = torch.randn(2, 3, 4)
update = torch.ones(1)
self.run_test(CopyModel(), (x, update))
x = torch.randn(2, 3, 4, 5, 6)
update = torch.ones(1)
self.run_test(CopyModel(), (x, update))
@skipIfUnsupportedMinOpsetVersion(11)
def test_copy_ellipsis_script(self):
class CopyModel(torch.nn.Module):
def forward(self, x, update):
# Insert reshape node to ensure no shape/type info for
# x in scripting, without onnx shape inference.
x = x.reshape(4, 3, 5, 6)
x[2, ..., 1:3] = update
return x
x = torch.randn(3, 4, 5, 6)
update = torch.ones(1)
self.run_test(CopyModel(), (x, update))
@skipIfUnsupportedMinOpsetVersion(10)
def test_flip(self):
class MyModule(torch.nn.Module):
def forward(self, x):
return torch.flip(x, dims=[0])
x = torch.tensor(np.arange(6.0).reshape(2, 3))
self.run_test(MyModule(), x)
def test_random(self):
class RandN(torch.nn.Module):
def forward(self, x):
return torch.mul(x, (torch.randn(2, 3, 4) + x).size(0))
x = torch.randn(2, 3, 4)
self.run_test(RandN(), x)
class Rand(torch.nn.Module):
def forward(self, x):
return torch.mul(x, (torch.rand(2, 3, 4) + x).size(0))
x = torch.randn(2, 3, 4)
self.run_test(Rand(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_random_dynamic_size(self):
class RandN(torch.nn.Module):
def forward(self, x):
return torch.mul(x, torch.randn(x.size()).size(1))
x = torch.randn(2, 3, 4)
self.run_test(RandN(), x)
class Rand(torch.nn.Module):
def forward(self, x):
return torch.mul(x, torch.rand(x.size()).size(1))
x = torch.randn(2, 3, 4)
self.run_test(Rand(), x)
def test_random_like(self):
class RandNLike(torch.nn.Module):
def forward(self, x):
return torch.mul(x, torch.randn_like(x).size(0))
x = torch.randn(2, 3, 4)
self.run_test(RandNLike(), x)
self.run_test(torch.jit.script(RandNLike()), x)
class RandLike(torch.nn.Module):
def forward(self, x):
return torch.mul(x, torch.rand_like(x).size(0))
x = torch.randn(2, 3, 4)
self.run_test(RandLike(), x)
self.run_test(torch.jit.script(RandLike()), x)
def test_random_like_dtype(self):
class RandNLike(torch.nn.Module):
def forward(self, x):
return torch.mul(x.to(torch.double), torch.randn_like(x, dtype=torch.double).size(0))
x = torch.randn(2, 3, 4)
self.run_test(RandNLike(), x)
class RandLike(torch.nn.Module):
def forward(self, x):
return torch.mul(x.to(torch.double), torch.rand_like(x, dtype=torch.double).size(0))
x = torch.randn(2, 3, 4)
self.run_test(RandLike(), x)
def test_bernoulli(self):
class Bernoulli(torch.nn.Module):
def forward(self, x):
return torch.mul(x, torch.bernoulli(x).size(0))
x = torch.empty(3, 3).uniform_(0, 1)
self.run_test(Bernoulli(), x)
x = torch.empty(2, 3, 3, dtype=torch.double).uniform_(0, 1)
self.run_test(Bernoulli(), x)
# Enable test when fix for allowzero is in ORT
@skipForAllOpsetVersions()
@skipIfUnsupportedMinOpsetVersion(14)
def test_reshape_allowzero(self):
class ReshapeModel(torch.nn.Module):
def forward(self, x):
x = x.reshape(3, 4, 0)
return x
x = torch.randn(0, 3, 4)
self.run_test(ReshapeModel(), x)
def test_reshape_different_rank(self):
class ReshapeModel(torch.nn.Module):
def forward(self, x):
x = x.reshape(-1, 2, 4, 4, 5, 5)
return x
x = torch.randn(1, 32, 5, 5)
self.run_test(ReshapeModel(), x)
def _interpolate(self, x, mode, use_size, is_upsample, align_corners=False):
class MyModel(torch.nn.Module):
__constants__ = ["mode", "use_size", "is_upsample", "size", "scale", "size_array", "scale_array", "align_corners"]
def __init__(self, mode, use_size, is_upsample, align_corners):
super(MyModel, self).__init__()
self.mode = mode
self.use_size = use_size
self.is_upsample = is_upsample
self.align_corners = align_corners
self.scale = 2.0 if self.is_upsample else 0.5
self.size = 24 if self.is_upsample else 2
if x.dim() == 3:
self.scale_array = [2.3]
self.size_array = [16]
elif x.dim() == 4:
self.scale_array = [2.3, 3.1]
self.size_array = [16, 32]
else:
self.scale_array = [2.3, 3.1, 4.6]
self.size_array = [16, 32, 64]
def forward(self, x):
if self.use_size:
if self.align_corners:
return torch.nn.functional.interpolate(x, mode=self.mode, size=self.size, align_corners=True), \
torch.nn.functional.interpolate(x, mode=self.mode, size=self.size_array, align_corners=True)
return torch.nn.functional.interpolate(x, mode=self.mode, size=self.size), \
torch.nn.functional.interpolate(x, mode=self.mode, size=self.size_array)
if self.align_corners:
return torch.nn.functional.interpolate(x, mode=self.mode,
scale_factor=self.scale, recompute_scale_factor=False), \
torch.nn.functional.interpolate(x, mode=self.mode,
scale_factor=self.scale_array, recompute_scale_factor=False)
return torch.nn.functional.interpolate(x, mode=self.mode,
scale_factor=self.scale, recompute_scale_factor=False), \
torch.nn.functional.interpolate(x, mode=self.mode,
scale_factor=self.scale_array, recompute_scale_factor=False)
model = MyModel(mode, use_size, is_upsample, align_corners)
self.run_test(model, x, atol=1e-6)
def _interpolate_tests(self, is_upsample):
# - cubic mode is not supported for opsets below 11;
# - linear mode does not match for opsets below 11;
modes = ["nearest", "linear", "bicubic"]
if self.opset_version < 11:
modes = ["nearest"]
x = [torch.randn(1, 2, 6, requires_grad=True),
torch.randn(1, 2, 4, 6, requires_grad=True),
torch.randn(1, 2, 4, 4, 6, requires_grad=True)]
for mode in modes:
for xi in x:
mode_i = mode
# TODO: enable bicubic downsample when ORT precision loss fixed
if mode == "bicubic" and xi.dim() != 4:
continue
elif mode == "linear":
if xi.dim() == 3:
# TODO : enable when linear mode is implemented for 1d inputs in ORT
continue
elif xi.dim() == 4:
mode_i = "bilinear"
elif xi.dim() == 5:
# TODO : enable when linear mode is implemented for 3d inputs in ORT
mode_i = "trilinear"
continue
self._interpolate(xi, mode_i, True, is_upsample)
# test with align_corners if supported
if mode != "nearest":
self._interpolate(xi, mode_i, True, is_upsample, True)
# the following cases, require dynamic sizes/scales,
# which which is not supported for opset_version < 9
if self.opset_version >= 9:
self._interpolate(xi, mode_i, True, is_upsample)
# test with align_corners if supported
if mode != "nearest":
self._interpolate(xi, mode_i, False, is_upsample, True)
self._interpolate(xi, mode_i, False, is_upsample)
# ONNX export failed on interpolate scripting because dynamic size not supported for opsets below 9.
@skipIfUnsupportedMinOpsetVersion(9)
def test_interpolate_upsample(self):
self._interpolate_tests(True)
@skipIfUnsupportedMaxOpsetVersion(8)
@disableScriptTest()
def test_interpolate_upsample_trace(self):
self._interpolate_tests(True)
@skipIfUnsupportedMinOpsetVersion(9)
def test_interpolate_function_substitution(self):
class ScriptModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.nn.functional.interpolate(x, mode="nearest", scale_factor=2.)
class ScriptModule(torch.jit.ScriptModule):
def __init__(self):
super(ScriptModule, self).__init__()
self.submodule = ScriptModel()
@torch.jit.script_method
def forward(self, input):
return self.submodule(input)
x = torch.randn(1, 2, 4, 4, 6)
self.run_test(ScriptModule(), (x,))
@torch.jit.script
def script_method(x):
return torch.nn.functional.interpolate(x, mode="nearest", scale_factor=2.)
class TracingModule(torch.nn.Module):
def forward(self, x):
return script_method(x)
self.run_test(TracingModule(), (x,))
@skipIfUnsupportedMinOpsetVersion(10)
def test_interpolate_downsample(self):
self._interpolate_tests(False)
@skipIfUnsupportedMinOpsetVersion(11)
def test_interpolate_no_shape(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x, y):
x = torch.add(x, x)
out1 = torch.nn.functional.interpolate(x, mode="bilinear", size=(16, 16), align_corners=False)
out2 = torch.nn.functional.interpolate(x, mode="nearest", size=(int(y.size(0)), int(y.size(1))))
return out1, out2
x = torch.randn(1, 2, 4, 4, requires_grad=True)
y = torch.randn(16, 16, requires_grad=True)
self.run_test(MyModel(), (x, y), input_names=["x", "y"], dynamic_axes={"x": [0, 1, 2, 3], "y": [0, 1]})
self.run_test(MyModel(), (x, y), remained_onnx_input_idx=[0])
# scripting will throw the OnnxRuntimeError
@disableScriptTest()
def test_interpolate_adaptive_pooling_error(self):
x = torch.randn(1, 2, 6, requires_grad=True)
with self.assertRaises(RuntimeError) as cm:
self._interpolate(x, "area", True, True)
with self.assertRaises(RuntimeError) as cm:
self._interpolate(x, "area", False, True)
def test_groupnorm(self):
model = torch.nn.GroupNorm(3, 6, 0.002)
x = torch.randn(4, 6, 180, 180, 180)
self.run_test(model, x)
model = torch.nn.GroupNorm(1, 6, 0.002)
x = torch.randn(4, 6, 180, 180)
self.run_test(model, x)
model = torch.nn.GroupNorm(6, 6, 0.002)
x = torch.randn(4, 6, 180, 180)
self.run_test(model, x)
@disableScriptTest()
def test_groupnorm_noaffine(self):
model = torch.nn.GroupNorm(4, 8, 0.002, affine=False)
x = torch.randn(3, 8, 224, 224)
self.run_test(model, x)
model = torch.nn.GroupNorm(1, 6, 0.002, affine=False)
x = torch.randn(4, 6, 180, 180)
self.run_test(model, x)
model = torch.nn.GroupNorm(6, 6, 0.002, affine=False)
x = torch.randn(4, 6, 180, 180)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_listunpack(self):
class ListUnpack(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
a, b = x.shape
return x.new_zeros((a, b))
x = torch.randn(2, 3)
self.run_test(ListUnpack(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(ListUnpack(), x, remained_onnx_input_idx=[])
class ListUnpackSlice(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
a, b = x.shape[2:]
return x.new_zeros((a, b))
x = torch.randn(2, 3, 4, 5)
self.run_test(ListUnpackSlice(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3]})
self.run_test(ListUnpackSlice(), x, remained_onnx_input_idx=[])
def test_pow(self):
class PowModule(torch.nn.Module):
def forward(self, x, y):
return x.pow(y)
x = torch.randn(2, 3, 4)
y = torch.randn(2, 3, 4)
self.run_test(PowModule(), (x, y))
x = torch.randint(10, (2, 3, 4))
y = torch.randint(10, (2, 3, 4)).to(dtype=torch.int32)
self.run_test(PowModule(), (x, y))
x = torch.randint(10, (2, 3, 4))
y = torch.randint(10, (2, 3, 4))
self.run_test(PowModule(), (x, y))
x = torch.randn(2, 3, 4).to(dtype=torch.float64)
y = torch.randint(10, (2, 3, 4))
self.run_test(PowModule(), (x, y))
class PowModule2(torch.nn.Module):
def forward(self, x):
return torch.pow(2, x)
x = torch.randn(1, 10)
self.run_test(PowModule2(), (x,))
x = torch.randint(10, (2, 3, 4))
self.run_test(PowModule2(), (x,))
x = torch.randn(1, 10).to(dtype=torch.float64)
self.run_test(PowModule2(), (x,))
class PowModule3(torch.nn.Module):
def forward(self, x, y):
return y[torch.pow(2, x)]
x = torch.randint(5, (2, 3, 4))
y = torch.rand(100)
self.run_test(PowModule3(), (x, y))
# the arithmeticOps(Add\Sub\Mul\Div\Gemm\Pow\Mod) with low precision include unit8 will be failed in ORT
# add to(dtype=torch.long) to avoid ORT output type does not match expected type.
# will be fixed in ONNX version 14.
@skipIfUnsupportedMaxOpsetVersion(13)
def test_arithmeticOps_with_low_precision(self):
class AddModule(torch.nn.Module):
def forward(self, x, y):
return x + y
class SubModule(torch.nn.Module):
def forward(self, x, y):
return x - y
class MulModule(torch.nn.Module):
def forward(self, x, y):
return x * y
class DivModule(torch.nn.Module):
def forward(self, x, y):
return x / y
class PowModule(torch.nn.Module):
def forward(self, x, y):
return x.pow(y)
x = torch.tensor([2, 3, 5], dtype=torch.uint8)
y = torch.tensor([2, 3, 5], dtype=torch.uint8)
z = torch.tensor([1], dtype=torch.uint8)
self.run_test(AddModule(), (x, y))
self.run_test(SubModule(), (x, y))
self.run_test(MulModule(), (x, y))
self.run_test(DivModule(), (x, y))
self.run_test(PowModule(), (x, z))
x = torch.tensor([2, 3, 5], dtype=torch.int8)
y = torch.tensor([2, 3, 5], dtype=torch.int8)
z = torch.tensor([1], dtype=torch.int8)
self.run_test(AddModule(), (x, y))
self.run_test(SubModule(), (x, y))
self.run_test(MulModule(), (x, y))
self.run_test(DivModule(), (x, y))
self.run_test(PowModule(), (x, z))
x = torch.tensor([2, 3, 5], dtype=torch.int16)
y = torch.tensor([2, 3, 5], dtype=torch.int16)
z = torch.tensor([1], dtype=torch.int16)
self.run_test(AddModule(), (x, y))
self.run_test(SubModule(), (x, y))
self.run_test(MulModule(), (x, y))
self.run_test(DivModule(), (x, y))
self.run_test(PowModule(), (x, z))
x = torch.tensor([2, 3, 5], dtype=torch.uint8)
y = torch.tensor([2, 3, 5], dtype=torch.float32)
z = torch.tensor([1], dtype=torch.float64)
self.run_test(AddModule(), (x, y))
self.run_test(SubModule(), (x, y))
self.run_test(MulModule(), (x, y))
self.run_test(DivModule(), (x, y))
self.run_test(PowModule(), (x, z))
x = torch.tensor([2, 3, 5], dtype=torch.uint8)
y = torch.tensor([2, 3, 5], dtype=torch.int64)
z = torch.tensor([1], dtype=torch.int32)
self.run_test(AddModule(), (x, y))
self.run_test(SubModule(), (x, y))
self.run_test(MulModule(), (x, y))
self.run_test(DivModule(), (x, y))
self.run_test(PowModule(), (x, z))
# fmod was added in version 10
@skipIfUnsupportedMinOpsetVersion(10)
@skipIfUnsupportedMaxOpsetVersion(13)
def test_mod_with_low_precision(self):
class ModModule(torch.nn.Module):
def forward(self, x, y):
return torch.fmod(x, y).to(dtype=torch.long)
x = torch.tensor([2, 3, 5], dtype=torch.uint8)
y = torch.tensor([2, 3, 5], dtype=torch.uint8)
self.run_test(ModModule(), (x, y))
x = torch.tensor([2, 3, 5], dtype=torch.int8)
y = torch.tensor([2, 3, 5], dtype=torch.int8)
self.run_test(ModModule(), (x, y))
x = torch.tensor([2, 3, 5], dtype=torch.int16)
y = torch.tensor([2, 3, 5], dtype=torch.int16)
self.run_test(ModModule(), (x, y))
x = torch.tensor([2, 3, 5], dtype=torch.uint8)
y = torch.tensor([2, 3, 5], dtype=torch.int32)
self.run_test(ModModule(), (x, y))
x = torch.tensor([2, 3, 5], dtype=torch.uint8)
y = torch.tensor([2, 3, 5], dtype=torch.float64)
self.run_test(ModModule(), (x, y))
def test_std(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.std(input, unbiased=False)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
class StandardDeviationUnbiased(torch.nn.Module):
def forward(self, input):
return torch.std(input, unbiased=True)
model = StandardDeviationUnbiased()
self.run_test(model, x)
def test_std_along_dims(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.std(input, dim=(0, 1), unbiased=False)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
class StandardDeviationUnbiased(torch.nn.Module):
def forward(self, input):
return torch.std(input, dim=(0, 1), unbiased=True)
x = torch.randn(2, 3, 4)
model = StandardDeviationUnbiased()
self.run_test(model, x)
def test_std_keepdim(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.std(input, dim=(0, 1), unbiased=False, keepdim=True)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
class StandardDeviationUnbiased(torch.nn.Module):
def forward(self, input):
return torch.std(input, dim=(0, 1), unbiased=True, keepdim=True)
x = torch.randn(2, 3, 4)
model = StandardDeviationUnbiased()
self.run_test(model, x)
def test_std_correction(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.std(input, dim=(0, 1), correction=3, keepdim=True)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
def test_var(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var(input, unbiased=False)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
class VarianceUnbiased(torch.nn.Module):
def forward(self, input):
return torch.var(input, unbiased=True)
model = VarianceUnbiased()
self.run_test(model, x)
class VarianceSqrt(torch.nn.Module):
def forward(self, input):
y = torch.var(input, 1)
return torch.sqrt(y + 1e-8)
x = torch.randn(1, 2, 3, 300, 300)
model = VarianceSqrt()
self.run_test(model, x)
def test_var_along_dims(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var(input, dim=(0, 1), unbiased=False)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
class VarianceUnbiased(torch.nn.Module):
def forward(self, input):
return torch.var(input, dim=(0, 1), unbiased=True)
x = torch.randn(2, 3, 4)
model = VarianceUnbiased()
self.run_test(model, x)
def test_var_keepdim(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var(input, dim=(0, 1), unbiased=False, keepdim=True)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
class VarianceUnbiased(torch.nn.Module):
def forward(self, input):
return torch.var(input, dim=(0, 1), unbiased=True, keepdim=True)
x = torch.randn(2, 3, 4)
model = VarianceUnbiased()
self.run_test(model, x)
def test_var_correction(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var(input, dim=(0, 1), correction=3, keepdim=True)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
def test_var_mean(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, unbiased=False)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
class VarianceUnbiased(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, unbiased=True)
model = VarianceUnbiased()
self.run_test(model, x)
def test_var_mean_along_dims(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(0, 1), unbiased=False)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
class VarianceUnbiased(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(0, 1), unbiased=True)
x = torch.randn(2, 3, 4)
model = VarianceUnbiased()
self.run_test(model, x)
def test_var_mean_mixed_dims(self):
class ReverseDims(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(2, 1), unbiased=False)
x = torch.randn(2, 3, 4)
model = ReverseDims()
self.run_test(model, x)
class SkipDims(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(0, 2), unbiased=False)
x = torch.randn(2, 3, 4)
model = SkipDims()
self.run_test(model, x)
class NonZeroDims(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(1, 2), unbiased=False)
x = torch.randn(2, 3, 4)
model = NonZeroDims()
self.run_test(model, x)
def test_var_mean_keepdim(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(0, 1), unbiased=False, keepdim=True)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
class VarianceUnbiased(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(0, 1), unbiased=True, keepdim=True)
x = torch.randn(2, 3, 4)
model = VarianceUnbiased()
self.run_test(model, x)
def test_var_mean_correction(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(0, 1), correction=3, keepdim=True)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
def test_std_mean(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.std_mean(input, unbiased=False)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
class StandardDeviationUnbiased(torch.nn.Module):
def forward(self, input):
return torch.std_mean(input, unbiased=True)
model = StandardDeviationUnbiased()
self.run_test(model, x)
def test_std_mean_along_dims(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.std_mean(input, dim=(0, 1), unbiased=False)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
class VarianceUnbiased(torch.nn.Module):
def forward(self, input):
return torch.std_mean(input, dim=(0, 1), unbiased=True)
x = torch.randn(2, 3, 4)
model = VarianceUnbiased()
self.run_test(model, x)
def test_std_mean_keepdim(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.std_mean(input, dim=(0, 1), unbiased=False, keepdim=True)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
class StandardDeviationUnbiased(torch.nn.Module):
def forward(self, input):
return torch.std_mean(input, dim=(0, 1), unbiased=True, keepdim=True)
x = torch.randn(2, 3, 4)
model = StandardDeviationUnbiased()
self.run_test(model, x)
def test_std_mean_correction(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(0, 1), correction=3, keepdim=True)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
def test_bitshift(self):
class BitshiftModel(torch.nn.Module):
def forward(self, input, input2):
return input >> 1, input << 3.1, \
input2 >> torch.tensor([1, 2]), input2 << 4.2
input = torch.arange(24, dtype=torch.float32).reshape(3, 4, 2)
input2 = torch.arange(24, dtype=torch.int64).reshape(3, 4, 2)
self.run_test(BitshiftModel(), (input, input2))
def test_bitshift_other_fp(self):
class BitshiftModel(torch.nn.Module):
def forward(self, input):
return input << 2.4
input = torch.arange(24, dtype=torch.int64).reshape(3, 4, 2)
self.run_test(BitshiftModel(), input)
# uint8 not implemented in ORT for Mul used in
# exporting bitshift for opset_version < 10
@skipIfUnsupportedMinOpsetVersion(11)
def test_bitshift_uint8(self):
class BitshiftModel(torch.nn.Module):
def forward(self, input, input2):
return input >> 1, input << 3., \
input2 >> torch.tensor([1, 2], dtype=torch.uint8), input2 << 4.
input = torch.arange(24, dtype=torch.uint8).reshape(3, 4, 2)
input2 = torch.arange(24, dtype=torch.uint8).reshape(3, 4, 2)
self.run_test(BitshiftModel(), (input, input2))
def test_narrow(self):
class NarrowModel(torch.nn.Module):
def forward(self, input):
return torch.narrow(input, 0, 0, 2)
x = torch.randn(3, 3, requires_grad=True)
self.run_test(NarrowModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_narrow_dynamic(self):
class NarrowModel(torch.nn.Module):
def forward(self, input):
return torch.narrow(input, 0, 0, input.shape[0] - 1)
x = torch.randn(3, 3, requires_grad=True)
self.run_test(NarrowModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_fill(self):
class IndexFillModel(torch.nn.Module):
def forward(self, input):
index = torch.tensor([2, 0])
return input.index_fill(2, index, -1)
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(IndexFillModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_copy(self):
class IndexCopyModel(torch.nn.Module):
def forward(self, input):
index = torch.tensor([2, 0])
source = torch.ones(3, 2, 5)
return input.index_copy(1, index, source)
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(IndexCopyModel(), x)
def test_select(self):
class Select(torch.nn.Module):
def forward(self, x):
return x[:, 1]
x = torch.randn(3, 4)
self.run_test(Select(), x)
def test_select_negative_index(self):
class Select(torch.nn.Module):
def forward(self, x):
return x[:, -1]
x = torch.randn(3, 4)
self.run_test(Select(), x)
def test_index_select_constant_scaler_index(self):
class IndexSelectScalerIndexModel(torch.nn.Module):
def forward(self, x):
index = 2
return torch.index_select(x, 1, torch.tensor(index))
x = torch.randn(3, 4)
self.run_test(IndexSelectScalerIndexModel(), x)
def test_index_select_scaler_index(self):
class IndexSelectScalerIndexModel(torch.nn.Module):
def __init__(self, index_base):
super(IndexSelectScalerIndexModel, self).__init__()
self.index_base = torch.tensor(index_base)
def forward(self, x, index_offset):
index = self.index_base + index_offset
return torch.index_select(x, 1, index)
x = torch.randn(3, 4)
offset = 2
index_offset = torch.tensor(offset)
base = 1
self.run_test(IndexSelectScalerIndexModel(base), (x, index_offset))
def test_take(self):
class TakeModel(torch.nn.Module):
def forward(self, x, y):
return torch.take(x, y)
x = torch.randn(6, 4, 3, 3)
y = torch.tensor([4, 1, 7, 15, 63])
self.run_test(TakeModel(), (x, y))
def test_topk(self):
class MyModule(torch.nn.Module):
def forward(self, x):
return torch.topk(x, 3)
x = torch.arange(1., 6., requires_grad=True)
self.run_test(MyModule(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_topk_smallest_unsorted(self):
class MyModule(torch.nn.Module):
def forward(self, x, k):
# When sorted=False, order of elements in the outout tensors
# are not expected to match between PyTorch and ORT
topk_unsorted = torch.topk(x, k, largest=False, sorted=False)
topk_sorted = torch.topk(x, k, largest=False, sorted=True)
return topk_sorted, torch.sort(topk_unsorted.values).values
x = torch.arange(1., 6., requires_grad=True)
k = torch.tensor(3)
self.run_test(MyModule(), (x, k))
@skipIfUnsupportedMinOpsetVersion(10)
def test_topk_script(self):
class MyModuleDynamic(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x, k):
return torch.topk(x, k)
x = torch.arange(1., 6., requires_grad=True)
k = torch.tensor(3)
self.run_test(MyModuleDynamic(), [x, k])
@skipIfUnsupportedOpsetVersion([7])
def test_normalize(self):
class Model(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.normalize(x)
x = torch.randn(3, 3)
self.run_test(Model(), x)
def test_layer_norm(self):
model = torch.nn.LayerNorm([10, 10])
x = torch.randn(20, 5, 10, 10)
self.run_test(model, x)
def test_batchnorm1d(self):
x = torch.randn(10, 10)
model = torch.nn.BatchNorm1d(10, affine=True)
self.run_test(model, x)
x = torch.randn(10, 10, 128)
self.run_test(model, x)
def test_batchnorm1d_noaffine(self):
x = torch.randn(10, 10)
model = torch.nn.BatchNorm1d(10, affine=False)
self.run_test(model, x)
x = torch.randn(10, 10, 128)
self.run_test(model, x)
def test_batchnorm1d_norunningstats(self):
x = torch.randn(10, 10)
model = torch.nn.BatchNorm1d(10, track_running_stats=False)
self.run_test(model, x)
x = torch.randn(10, 10, 128)
self.run_test(model, x)
def test_batchnorm2d(self):
x = torch.randn(10, 3, 128, 128)
model = torch.nn.BatchNorm2d(3, affine=True)
self.run_test(model, x)
def test_batchnorm2d_noaffine(self):
x = torch.randn(10, 3, 128, 128)
model = torch.nn.BatchNorm2d(3, affine=False)
self.run_test(model, x)
def test_batchnorm2d_norunningstats(self):
x = torch.randn(10, 3, 128, 128)
model = torch.nn.BatchNorm2d(3, track_running_stats=False)
self.run_test(model, x)
def test_batchnorm3d(self):
x = torch.randn(10, 3, 128, 128, 128)
model = torch.nn.BatchNorm3d(3, affine=True)
self.run_test(model, x)
def test_batchnorm3d_noaffine(self):
x = torch.randn(10, 3, 128, 128, 128)
model = torch.nn.BatchNorm3d(3, affine=False)
self.run_test(model, x)
def test_instancenorm1d_runningstats(self):
x = torch.randn(10, 5, 128)
model = torch.nn.InstanceNorm1d(5, affine=True, track_running_stats=True)
self.run_test(model, x)
model = torch.nn.InstanceNorm1d(5, affine=False, track_running_stats=True)
self.run_test(model, x)
def test_instancenorm1d_norunningstats(self):
x = torch.randn(10, 5, 128)
model = torch.nn.InstanceNorm1d(5, affine=True, track_running_stats=False)
self.run_test(model, x)
model = torch.nn.InstanceNorm1d(5, affine=False, track_running_stats=False)
self.run_test(model, x)
def test_instancenorm2d_runningstats(self):
x = torch.randn(10, 3, 128, 128)
model = torch.nn.InstanceNorm2d(3, affine=True, track_running_stats=True)
self.run_test(model, x)
model = torch.nn.InstanceNorm2d(3, affine=False, track_running_stats=True)
self.run_test(model, x)
def test_instancenorm2d_norunningstats(self):
x = torch.randn(10, 3, 128, 128)
model = torch.nn.InstanceNorm2d(3, affine=True, track_running_stats=False)
self.run_test(model, x)
model = torch.nn.InstanceNorm2d(3, affine=False, track_running_stats=False)
self.run_test(model, x)
def test_instancenorm3d_runningstats(self):
x = torch.randn(10, 3, 128, 128, 128)
model = torch.nn.InstanceNorm3d(3, affine=True, track_running_stats=True)
self.run_test(model, x)
model = torch.nn.InstanceNorm3d(3, affine=False, track_running_stats=True)
self.run_test(model, x)
def test_instancenorm3d_norunningstats(self):
x = torch.randn(10, 3, 128, 128, 128)
model = torch.nn.InstanceNorm3d(3, affine=True, track_running_stats=False)
self.run_test(model, x)
model = torch.nn.InstanceNorm3d(3, affine=False, track_running_stats=False)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_scatter_with_scalar(self):
class ScatterModel(torch.nn.Module):
def forward(self, input, indices):
values = 1.0
return input.scatter(1, indices, values)
input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]], dtype=torch.float64)
indices = torch.tensor([[1, 0], [0, 1], [0, 1]], dtype=torch.int64)
self.run_test(ScatterModel(), input=(input, indices))
@skipIfUnsupportedMinOpsetVersion(9)
def test_scatter_with_scalar_different_types(self):
# Tests the case when scalar src (updates values) type is different
# from self type. Happens only with scalar src - PyTorch does not
# allow this when src is a tensor.
class ScatterModel(torch.nn.Module):
def forward(self, input, indices):
values = 1.0
return input.scatter(1, indices, values)
input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]], dtype=torch.float32)
indices = torch.tensor([[1, 0], [0, 1], [0, 1]], dtype=torch.int64)
self.run_test(ScatterModel(), input=(input, indices))
@skipIfUnsupportedMinOpsetVersion(9)
def test_scatter(self):
class ScatterModel(torch.nn.Module):
def forward(self, input, indices, values):
return input.scatter(1, indices, values)
input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])
indices = torch.tensor([[1, 0], [0, 1], [0, 1]], dtype=torch.int64)
values = torch.tensor([[1.0, 1.1], [2.0, 2.1], [3.0, 3.1]])
self.run_test(ScatterModel(), input=(input, indices, values))
input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
indices = torch.tensor([[1, 0], [0, 2], [0, 1]], dtype=torch.int64)
values = torch.tensor([[1.0, 1.1], [2.0, 2.1], [3.0, 3.1]])
self.run_test(ScatterModel(), (input, indices, values))
input = torch.zeros(3, 4, 5, 6)
indices = torch.tensor([[1, 0], [0, 2], [0, 1]], dtype=torch.int64)
indices = indices.view(3, 2, 1, 1).expand(3, 2, 5, 6)
values = torch.arange(3 * 2 * 5 * 6, dtype=torch.float32).view(3, 2, 5, 6)
self.run_test(ScatterModel(), (input, indices, values))
input = torch.zeros(3, 4, 2)
indices = torch.tensor([[[1, 0], [0, 2]], [[1, 1], [0, 1]], [[2, 1], [2, 2]]])
values = torch.arange(3 * 2 * 2, dtype=torch.float32).view(3, 2, 2)
self.run_test(ScatterModel(), (input, indices, values))
@skipIfUnsupportedMinOpsetVersion(9)
def test_scatter_add(self):
class ScatterModel(torch.nn.Module):
def forward(self, input, indices, values):
return input.scatter_add(1, indices, values)
input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
indices = torch.tensor([[1, 0], [0, 1], [0, 1]], dtype=torch.int64)
values = torch.tensor([[1.0, 1.1], [2.0, 2.1], [3.0, 3.1]])
self.run_test(ScatterModel(), input=(input, indices, values))
@torch.jit.script
def scatter_sum(src: torch.Tensor, index: torch.Tensor):
size = src.size()
out = torch.zeros(size, dtype=src.dtype)
return out.scatter_add_(1, index, src)
class ScatterModel(torch.nn.Module):
def forward(self, src, index):
return scatter_sum(src, index)
src = torch.rand(3, 2)
index = torch.tensor([[0, 1], [0, 1], [0, 1]], dtype=torch.int64)
self.run_test(ScatterModel(), (src, index))
@skipIfUnsupportedMinOpsetVersion(9)
def test_one_hot(self):
class OneHot(torch.nn.Module):
def __init__(self, num_classes):
super().__init__()
self.num_classes = num_classes
def forward(self, x):
return torch.nn.functional.one_hot(x, self.num_classes)
x = torch.arange(10)
self.run_test(OneHot(15), (x))
@skipIfUnsupportedMinOpsetVersion(9)
def test_gather(self):
class GatherModel(torch.nn.Module):
def forward(self, input, indices):
return input.gather(1, indices)
input = torch.tensor([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]])
indices = torch.tensor([[1, 0], [0, 1], [0, 1]], dtype=torch.int64)
self.run_test(GatherModel(), input=(input, indices))
@disableScriptTest() # RuntimeError: Python type cannot be used as a value
@skipIfUnsupportedMinOpsetVersion(11)
def test_gather_constant_fold(self):
class GatherModule(torch.nn.Module):
def __init__(self):
super(GatherModule, self).__init__()
self.register_buffer("weight", torch.ones(5))
def forward(self, x):
# shape is of rank 0
shape = self.weight.shape[0]
m = 5 - shape
return x.clamp(min=m)
x = torch.randn(1)
self.run_test(GatherModule(), (x,))
class GatherModule(torch.nn.Module):
def __init__(self):
super(GatherModule, self).__init__()
self.register_buffer("weight", torch.ones(2))
def forward(self, x):
# shape is of rank 0
shape = self.weight.shape[0]
pad = [1, shape, shape, shape]
zero_pad = torch.nn.ZeroPad2d(pad)
return zero_pad(x)
x = torch.randn(1, 3, 2)
self.run_test(GatherModule(), (x,))
@skipIfUnsupportedOpsetVersion([13])
@skipIfUnsupportedMinOpsetVersion(9)
def test_expand(self):
class ExpandModel(torch.nn.Module):
def forward(self, input):
return input.expand(2, 3, -1)
input = torch.randn(2, 1, 4)
self.run_test(ExpandModel(), input=(input))
class ExpandInferDimModel(torch.nn.Module):
def forward(self, input):
return input.expand(-1, input.size(0))
input = torch.randn(3, 1)
self.run_test(ExpandInferDimModel(), input=(input))
class ExpandTensorSizeModel(torch.nn.Module):
def forward(self, input, size):
return input.expand(size)
input = torch.randn(3,)
size = torch.tensor(-1)
self.run_test(ExpandTensorSizeModel(), input=(input, size))
@skipIfUnsupportedMinOpsetVersion(11) # index_put is supported in opsets >= 11
def test_dynamic_expand_as(self):
class Model(torch.nn.Module):
def forward(self, x):
x[:, x.size(0):] = 0
return x
x = torch.ones(2, 5)
x2 = torch.randn(3, 4)
self.run_test(Model(), (x, ),
input_names=["x"],
dynamic_axes={"x": [0, 1]},
test_with_inputs=[x2])
class Model(torch.nn.Module):
def forward(self, x):
x[:, x.size(0):] = torch.tensor([1, 2, 3])
return x
x = torch.ones(2, 5, 3)
x2 = torch.randn(3, 4, 3)
self.run_test(Model(), (x, ),
input_names=["x"],
dynamic_axes={"x": [0, 1, 2]},
test_with_inputs=[x2])
def test_multinomial(self):
class Multinomial(torch.nn.Module):
def forward(self, weight):
return torch.multinomial(weight, 3, replacement=True)
class MultinomialNoReplacement(torch.nn.Module):
def forward(self, weight):
return torch.multinomial(weight, 1)
weight = torch.tensor([[0, 10, 0, 0], [0, 0, 100, 0]], dtype=torch.float)
self.run_test(Multinomial(), (weight,))
self.run_test(MultinomialNoReplacement(), (weight,))
def _test_reduced_ops(self, op):
class ReducedOpModule(torch.nn.Module):
def forward(self, input):
return op(input, dim=-1)
if op != torch.mean: # torch.mean only supports float types
x = torch.randint(10, (4, 4), dtype=torch.uint8)
self.run_test(ReducedOpModule(), x)
x = torch.randint(10, (4, 4), dtype=torch.int8)
self.run_test(ReducedOpModule(), x)
x = torch.randint(10, (4, 4), dtype=torch.int16)
self.run_test(ReducedOpModule(), x)
x = torch.randint(10, (4, 4), dtype=torch.int32)
self.run_test(ReducedOpModule(), x)
x = torch.randint(10, (4, 4), dtype=torch.int64)
self.run_test(ReducedOpModule(), x)
# torch.mean only supports float types
# ORT does not support double ReduceProd for double
if op != torch.prod and op != torch.mean:
x = torch.randn(4, 5, dtype=torch.double)
self.run_test(ReducedOpModule(), x)
if op != torch.prod: # torch.prod not implemented for Half
x = torch.randn(4, 4, dtype=torch.half)
self.run_test(ReducedOpModule(), x)
x = torch.randn(4, 5, dtype=torch.float)
self.run_test(ReducedOpModule(), x)
def test_reduced_sum(self):
return self._test_reduced_ops(op=torch.sum)
def test_reduced_mean(self):
return self._test_reduced_ops(op=torch.mean)
def test_reduced_prod(self):
return self._test_reduced_ops(op=torch.prod)
def test_reduced_min_max(self):
class ReducedMinMaxModule(torch.nn.Module):
def forward(self, input):
return torch.min(input, dim=-1)[0], torch.max(input, dim=0)[0]
x = torch.randint(10, (4, 4), dtype=torch.int32)
self.run_test(ReducedMinMaxModule(), x)
x = torch.randint(10, (4, 4), dtype=torch.int64)
self.run_test(ReducedMinMaxModule(), x)
x = torch.randn(4, 5, dtype=torch.float)
self.run_test(ReducedMinMaxModule(), x)
def test_reduce_log_sum_exp(self):
class ReduceLogSumExpModel(torch.nn.Module):
def forward(self, input):
a = torch.logsumexp(input, dim=0)
b = torch.logsumexp(input, dim=(0, 1))
return a + b
x = torch.randn(4, 4, requires_grad=True)
self.run_test(ReduceLogSumExpModel(), x)
def test_softmax(self):
for i in range(-4, 3):
model = torch.nn.Softmax(dim=i)
input = torch.randn(3, 4, 5, 6)
self.run_test(model, input)
class SoftmaxUnknownRank(torch.nn.Module):
def __init__(self, i):
super().__init__()
self.softmax = torch.nn.Softmax(dim=i)
def forward(self, x):
return self.softmax(x.reshape(3, 4, 5, 6))
model = torch.jit.script(SoftmaxUnknownRank(i))
self.run_test(model, input)
def test_softmax_large_values(self):
input = torch.tensor([[-1e12, -1e12, -1e12], [1e12, 0.0, -5.0], [3.0, 4.0, 5.0]])
for i in range(-2, 1):
model = torch.nn.Softmax(dim=i)
self.run_test(model, input)
class SoftmaxUnknownRank(torch.nn.Module):
def __init__(self, i):
super().__init__()
self.softmax = torch.nn.Softmax(dim=i)
def forward(self, x):
return self.softmax(x.reshape(3, 3))
model = torch.jit.script(SoftmaxUnknownRank(i))
self.run_test(model, input)
def test_logsoftmax(self):
for i in range(7)[2:]:
model = torch.nn.LogSoftmax(dim=i - 1)
dims = [2] * (i - 2) + [3, 4]
input = torch.ones(*dims, requires_grad=True)
self.run_test(model, input)
def test_logsoftmax_dim(self):
for i in range(-4, 3):
model = torch.nn.LogSoftmax(dim=i)
input = torch.randn(3, 4, 5, 6)
self.run_test(model, input)
def test_logsoftmax_dtype(self):
class Model(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.log_softmax(x, dim=1, dtype=torch.float64)
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(Model(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_no_hidden(self):
class LSTMModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.rnn = torch.nn.LSTM(input_size=16, hidden_size=16)
def forward(self, x):
return self.rnn(x)
input = torch.randn((10, 16, 16))
self.run_test(LSTMModel(), (input,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_proj_no_hidden(self):
class LSTMModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.rnn = torch.nn.LSTM(input_size=16, hidden_size=16, proj_size=8)
def forward(self, x):
return self.rnn(x)
input = torch.randn((10, 16, 16))
with self.assertRaises(RuntimeError):
self.run_test(LSTMModel(), (input,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm(self):
class LSTMModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.rnn = torch.nn.LSTM(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, 1, bidirectional=False)
def forward(self, x, h0, c0):
return self.rnn(x, (h0, c0))
input = torch.randn(RNN_SEQUENCE_LENGTH, BATCH_SIZE, RNN_INPUT_SIZE)
h0 = torch.randn(1, BATCH_SIZE, RNN_HIDDEN_SIZE)
c0 = torch.randn(1, BATCH_SIZE, RNN_HIDDEN_SIZE)
self.run_test(LSTMModel(), (input, h0, c0))
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_cell(self):
class LSTMCellModel(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.lstm_cell = torch.nn.LSTMCell(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, bias=bias)
def forward(self, x, h0, c0):
return self.lstm_cell(x, (h0, c0))
input = torch.randn(BATCH_SIZE, RNN_INPUT_SIZE)
h0 = torch.randn(BATCH_SIZE, RNN_HIDDEN_SIZE)
c0 = torch.randn(BATCH_SIZE, RNN_HIDDEN_SIZE)
for bias in [True, False]:
self.run_test(LSTMCellModel(bias), (input, h0, c0))
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_default_init_state(self):
class LSTMModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.rnn = torch.nn.LSTM(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, 1, bidirectional=False)
def forward(self, x):
return self.rnn(x)
input = torch.randn(RNN_SEQUENCE_LENGTH, BATCH_SIZE, RNN_INPUT_SIZE)
self.run_test(LSTMModel(), input)
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_fixed_batch_size(self):
class LSTMModel(torch.nn.Module):
def __init__(self):
super(LSTMModel, self).__init__()
self.lstm = torch.nn.LSTM(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, 1, bidirectional=False)
self.RNN_HIDDEN_SIZE = RNN_HIDDEN_SIZE
def forward(self, input):
batch_size = input.size()[1]
h0 = torch.ones([1, batch_size, self.RNN_HIDDEN_SIZE])
c0 = torch.ones([1, batch_size, self.RNN_HIDDEN_SIZE])
return self.lstm(input, (h0, c0))
input = torch.randn(RNN_SEQUENCE_LENGTH, BATCH_SIZE, RNN_INPUT_SIZE)
# verify with different input of same batch size
input2 = torch.randn(RNN_SEQUENCE_LENGTH, BATCH_SIZE, RNN_INPUT_SIZE)
self.run_test(LSTMModel(), input, fixed_batch_size=True, test_with_inputs=[input2])
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_post_fix_init_state(self):
class LSTMModel(torch.nn.Module):
def __init__(self):
super(LSTMModel, self).__init__()
self.lstm = torch.nn.LSTM(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, 1, bidirectional=False)
self.RNN_HIDDEN_SIZE = RNN_HIDDEN_SIZE
def forward(self, input):
batch_size = input.size()[1]
h0 = torch.ones([1, batch_size, self.RNN_HIDDEN_SIZE])
c0 = torch.ones([1, batch_size, self.RNN_HIDDEN_SIZE])
return self.lstm(input, (h0, c0))
model = LSTMModel()
input = torch.randn(RNN_SEQUENCE_LENGTH, 1, RNN_INPUT_SIZE)
# verify with different input of different batch size
input2 = torch.randn(RNN_SEQUENCE_LENGTH, BATCH_SIZE, RNN_INPUT_SIZE)
self.run_test(model, input, input_names=["input.1"], dynamic_axes={"input.1" : {0 : "seq", 1 : "batch"}},
test_with_inputs=[input2])
def test_lstm_constant_folding(self):
class LstmNet(torch.nn.Module):
def __init__(self, input_size, hidden_size, num_layers, bidirectional):
super(LstmNet, self).__init__()
self.lstm = torch.nn.LSTM(input_size, hidden_size, num_layers, bidirectional=bidirectional)
def forward(self, input, initial_state: Tuple[torch.Tensor, torch.Tensor]):
return self.lstm(input, initial_state)
def get_LstmNet_model_and_inputs(input_size, hidden_size, num_layers, batch_size,
seq_len, bidirectional):
num_directions = 2 if bidirectional else 1
model = LstmNet(input_size, hidden_size, num_layers, bidirectional)
input = torch.randn(seq_len, batch_size, input_size)
h0 = torch.randn(num_layers * num_directions, batch_size, hidden_size)
c0 = torch.randn(num_layers * num_directions, batch_size, hidden_size)
return model, (input, (h0, c0))
batch_size1 = 3
model1, input1 = get_LstmNet_model_and_inputs(7, 3, 2, batch_size1, 5, True)
self.run_test(model1, input1, do_constant_folding=True)
batch_size2 = 4
model2, input2 = get_LstmNet_model_and_inputs(5, 4, 3, batch_size2, 7, False)
self.run_test(model2, input2, do_constant_folding=True)
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_no_bias(self):
class LstmNet(torch.nn.Module):
def __init__(self, num_layers, bidirectional):
super(LstmNet, self).__init__()
self.lstm = torch.nn.LSTM(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, num_layers, bias=False, bidirectional=bidirectional)
def forward(self, input, initial_state: Tuple[torch.Tensor, torch.Tensor]):
return self.lstm(input, initial_state)
def get_LstmNet_model_and_inputs(num_layers, bidirectional):
input = torch.randn(RNN_SEQUENCE_LENGTH, BATCH_SIZE, RNN_INPUT_SIZE)
num_directions = 2 if bidirectional else 1
model = LstmNet(num_layers, bidirectional)
h0 = torch.randn(num_layers * num_directions, BATCH_SIZE, RNN_HIDDEN_SIZE)
c0 = torch.randn(num_layers * num_directions, BATCH_SIZE, RNN_HIDDEN_SIZE)
return model, (input, (h0, c0))
num_layers = [1, 1, 2, 3]
bidirectional = [True, False, True, False]
models_and_inputs = [get_LstmNet_model_and_inputs(n, b) for n, b in zip(num_layers, bidirectional)]
for model, input in models_and_inputs:
self.run_test(model, input)
@disableScriptTest()
def test_rnn_no_bias(self):
def make_model(layers, packed_sequence):
batch_first = True if packed_sequence == 2 else False
model = torch.nn.RNN(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, layers, bidirectional=False,
batch_first=batch_first, bias=False)
if packed_sequence == 1:
model = RnnModelWithPackedSequence(model, False)
if packed_sequence == 2:
model = RnnModelWithPackedSequence(model, True)
return model
def make_input(batch_size, layers, packed_sequence):
batch_first = True if packed_sequence == 2 else False
seq_lengths = np.random.randint(1, RNN_SEQUENCE_LENGTH + 1, size=batch_size)
seq_lengths = list(reversed(sorted(map(int, seq_lengths))))
inputs = [torch.randn(l, RNN_INPUT_SIZE) for l in seq_lengths]
inputs = rnn_utils.pad_sequence(inputs, batch_first=batch_first)
inputs = [inputs]
h0 = torch.randn(layers, batch_size, RNN_HIDDEN_SIZE)
inputs.append(h0)
if packed_sequence != 0:
inputs.append(torch.IntTensor(seq_lengths))
if len(inputs) == 1:
input = inputs[0]
else:
input = tuple(inputs)
return input
layers = [1, 3, 1, 3, 1, 3]
packed_sequence = [0, 0, 1, 1, 2, 2]
models = [make_model(l, p) for l, p in zip(layers, packed_sequence)]
inputs = [make_input(RNN_BATCH_SIZE, l, p) for l, p in zip(layers, packed_sequence)]
for model, input in zip(models, inputs):
self.run_test(model, input, batch_size=RNN_BATCH_SIZE)
def test_gru_no_bias(self):
class GruNet(torch.nn.Module):
def __init__(self, input_size, hidden_size, num_layers, bidirectional):
super(GruNet, self).__init__()
self.mygru = torch.nn.GRU(input_size, hidden_size, num_layers, bidirectional=bidirectional, bias=False)
def forward(self, input, initial_state):
out = self.mygru(input, initial_state)
return out
def get_GruNet_model_and_inputs(input_size, hidden_size, num_layers, batch_size,
seq_len, bidirectional):
num_directions = 2 if bidirectional else 1
model = GruNet(input_size, hidden_size, num_layers, bidirectional)
input = torch.randn(seq_len, batch_size, input_size)
h0 = torch.randn(num_layers * num_directions, batch_size, hidden_size)
return model, (input, h0)
input_size = [7, 5]
hidden_size = [3, 4]
num_layers = [2, 3]
batch_size = [3, 4]
seq_len = [5, 7]
bidirectional = [True, False]
models_and_inputs = [get_GruNet_model_and_inputs(i, h, n, b, s, bi)
for i, h, n, b, s, bi in zip(input_size, hidden_size, num_layers, batch_size, seq_len, bidirectional)]
for model, input in models_and_inputs:
self.run_test(model, input, do_constant_folding=True)
def test_gru_constant_folding(self):
class GruNet(torch.nn.Module):
def __init__(self, input_size, hidden_size, num_layers, bidirectional):
super(GruNet, self).__init__()
self.mygru = torch.nn.GRU(input_size, hidden_size, num_layers, bidirectional=bidirectional)
def forward(self, input, initial_state):
out = self.mygru(input, initial_state)
return out
def get_GruNet_model_and_inputs(input_size, hidden_size, num_layers, batch_size,
seq_len, bidirectional):
num_directions = 2 if bidirectional else 1
model = GruNet(input_size, hidden_size, num_layers, bidirectional)
input = torch.randn(seq_len, batch_size, input_size)
h0 = torch.randn(num_layers * num_directions, batch_size, hidden_size)
return model, (input, h0)
batch_size1 = 3
model1, input1 = get_GruNet_model_and_inputs(7, 3, 2, batch_size1, 5, True)
self.run_test(model1, input1, do_constant_folding=True)
batch_size2 = 4
model2, input2 = get_GruNet_model_and_inputs(5, 4, 3, batch_size2, 7, False)
self.run_test(model2, input2, do_constant_folding=True)
@skipIfUnsupportedMinOpsetVersion(8)
def test_max_tensors(self):
class MaxModel(torch.nn.Module):
def forward(self, input, other):
return torch.max(input, other)
model = MaxModel()
x = torch.randn(4, 4, requires_grad=True)
y = torch.randn(4, 1, requires_grad=True)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_arange_end(self):
class ArangeScript(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, a):
return torch.arange(a.size(0), dtype=torch.float).view(-1, 1) + a
x = torch.randn(3, 4, requires_grad=True)
outputs = ArangeScript()(x)
self.run_test(ArangeScript(), x)
class ArangeModel(torch.nn.Module):
def forward(self, a):
return torch.arange(a.size(0), dtype=torch.float).view(-1, 1) + a
self.run_test(ArangeModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_arange_end_notype(self):
class ArangeScript(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, a):
return torch.arange(a.size(0))
x = torch.randn(3, 4, requires_grad=True)
outputs = ArangeScript()(x)
self.run_test(ArangeScript(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(ArangeScript(), x, remained_onnx_input_idx=[])
class ArangeModel(torch.nn.Module):
def forward(self, a):
return torch.arange(a.size(0))
self.run_test(ArangeModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(ArangeModel(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_arange_start_end(self):
class ArangeScript(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, a):
return torch.arange(2, a.size(0) + 2, dtype=torch.float).view(-1, 1) + a
x = torch.randn(3, 4, requires_grad=True)
self.run_test(ArangeScript(), x)
class ArangeModel(torch.nn.Module):
def forward(self, a):
return torch.arange(2, a.size(0) + 2, dtype=torch.float).view(-1, 1) + a
self.run_test(ArangeModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_arange_start_end_notype(self):
class ArangeScript(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, a):
return torch.arange(2.7, a.size(0) + 2).view(-1, 1) + a
x = torch.randn(3, 4, requires_grad=True)
self.run_test(ArangeScript(), x)
class ArangeModel(torch.nn.Module):
def forward(self, a):
return torch.arange(2.7, a.size(0) + 2).view(-1, 1) + a
self.run_test(ArangeModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_arange_start_end_step(self):
class ArangeScript(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, a):
return torch.arange(2, a.size(0) * a.size(1) + 2, a.size(1), dtype=torch.float).view(-1, 1) + a
x = torch.randn(3, 4, requires_grad=True)
self.run_test(ArangeScript(), x)
class ArangeModel(torch.nn.Module):
def forward(self, a):
return torch.arange(2, a.size(0) * a.size(1) + 2, a.size(1), dtype=torch.float).view(-1, 1) + a
self.run_test(ArangeModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_arange_start_end_step_notype(self):
class ArangeScript(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, a):
return torch.arange(2.7, a.size(0) * a.size(1) + 2, a.size(1)).view(-1, 1) + a
x = torch.randn(3, 4, requires_grad=True)
self.run_test(ArangeScript(), x)
class ArangeModel(torch.nn.Module):
def forward(self, a):
return torch.arange(2.7, a.size(0) * a.size(1) + 2, a.size(1)).view(-1, 1) + a
self.run_test(ArangeModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test__dim_arange(self):
class DimArange(torch.nn.Module):
def forward(self, input):
return torch._dim_arange(input, 1)
x = torch.ones(5, 6)
self.run_test(DimArange(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
remained_onnx_input_idx = None if self.opset_version < 11 else []
self.run_test(DimArange(), x, remained_onnx_input_idx=remained_onnx_input_idx)
def _test_compare_ops(self, model, num_inputs):
x_float = torch.randn(1, 2, 3, 4, requires_grad=True)
x_int = torch.randint(10, (3, 4), dtype=torch.int32)
if num_inputs > 1:
y_float = torch.randn(1, 2, 3, 4, requires_grad=True)
y_int = torch.randint(10, (3, 4), dtype=torch.int32)
self.run_test(model, (x_float, y_float))
self.run_test(model, (x_float, y_int))
self.run_test(model, (x_int, y_float))
self.run_test(model, (x_int, y_int))
else:
self.run_test(model, x_float)
self.run_test(model, x_int)
@skipIfUnsupportedMinOpsetVersion(9)
def test_logical_and(self):
class AndModel(torch.nn.Module):
def forward(self, x, y):
return torch.logical_and(x, y)
x = torch.randint(0, 2, (5, 5), dtype=torch.bool)
y = torch.randint(0, 2, (5, 5), dtype=torch.bool)
self.run_test(AndModel(), input=(x, y))
x = torch.randint(10, (5, 5), dtype=torch.int32)
y = torch.randint(10, (5, 5), dtype=torch.int32)
self.run_test(AndModel(), input=(x, y))
x = torch.randint(10, (5, 5), dtype=torch.double)
y = torch.randint(10, (5, 5), dtype=torch.double)
self.run_test(AndModel(), input=(x, y))
x = torch.randint(10, (2, 3, 5), dtype=torch.float32)
y = torch.randint(10, (2, 3, 5), dtype=torch.long)
self.run_test(AndModel(), input=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_logical_or(self):
class OrModel(torch.nn.Module):
def forward(self, x, y):
return torch.logical_or(x, y)
x = torch.randint(0, 2, (5, 5), dtype=torch.bool)
y = torch.randint(0, 2, (5, 5), dtype=torch.bool)
self.run_test(OrModel(), input=(x, y))
x = torch.randint(10, (5, 5), dtype=torch.int32)
y = torch.randint(10, (5, 5), dtype=torch.int32)
self.run_test(OrModel(), input=(x, y))
x = torch.randint(10, (5, 5), dtype=torch.double)
y = torch.randint(10, (5, 5), dtype=torch.double)
self.run_test(OrModel(), input=(x, y))
x = torch.randint(10, (2, 3, 5), dtype=torch.float32)
y = torch.randint(10, (2, 3, 5), dtype=torch.long)
self.run_test(OrModel(), input=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_logical_xor(self):
class XorModel(torch.nn.Module):
def forward(self, x, y):
return torch.logical_xor(x, y)
x = torch.randint(0, 2, (5, 5), dtype=torch.bool)
y = torch.randint(0, 2, (5, 5), dtype=torch.bool)
self.run_test(XorModel(), input=(x, y))
x = torch.randint(10, (5, 5), dtype=torch.int32)
y = torch.randint(10, (5, 5), dtype=torch.int32)
self.run_test(XorModel(), input=(x, y))
x = torch.randint(10, (5, 5), dtype=torch.double)
y = torch.randint(10, (5, 5), dtype=torch.double)
self.run_test(XorModel(), input=(x, y))
x = torch.randint(10, (2, 3, 5), dtype=torch.float32)
y = torch.randint(10, (2, 3, 5), dtype=torch.long)
self.run_test(XorModel(), input=(x, y))
def test_gt(self):
class GreaterModel(torch.nn.Module):
def forward(self, input, other):
return input > other
self._test_compare_ops(GreaterModel(), 2)
@skipIfUnsupportedMinOpsetVersion(9)
def test_ge(self):
class GreaterOrEqualModel(torch.nn.Module):
def forward(self, input, other):
return input >= other
self._test_compare_ops(GreaterOrEqualModel(), 2)
def test_gt_scalar(self):
class GreaterModel(torch.nn.Module):
def forward(self, input):
return input > 1
self._test_compare_ops(GreaterModel(), 1)
def test_gt_primitive(self):
class GreaterModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.y : int = 2
def forward(self, x: int):
return self.y > x
x = 3
self.run_test(GreaterModel(), (x, ))
@skipIfUnsupportedMinOpsetVersion(9)
def test_ge_scalar(self):
class GreaterOrEqualModel(torch.nn.Module):
def forward(self, input):
return input >= 1
self._test_compare_ops(GreaterOrEqualModel(), 1)
def test_lt(self):
class LessModel(torch.nn.Module):
def forward(self, input, other):
return input > other
self._test_compare_ops(LessModel(), 2)
@skipIfUnsupportedMinOpsetVersion(9)
def test_le(self):
class LessOrEqualModel(torch.nn.Module):
def forward(self, input, other):
return input <= other
self._test_compare_ops(LessOrEqualModel(), 2)
def test_lt_scalar(self):
class LessModel(torch.nn.Module):
def forward(self, input):
return input < 1
self._test_compare_ops(LessModel(), 1)
@skipIfUnsupportedMinOpsetVersion(9)
def test_le_scalar(self):
class LessOrEqualModel(torch.nn.Module):
def forward(self, input):
return input <= 1
self._test_compare_ops(LessOrEqualModel(), 1)
def test_matmul(self):
class MatmulModel(torch.nn.Module):
def forward(self, input, other):
return torch.matmul(input, other)
x = torch.randn(3, 4, requires_grad=True)
y = torch.randn(4, 5, requires_grad=True)
self.run_test(MatmulModel(), (x, y))
x = torch.randint(10, (3, 4))
y = torch.randint(10, (4, 5))
self.run_test(MatmulModel(), (x, y))
def test_matmul_batch(self):
class MatmulModel(torch.nn.Module):
def forward(self, input, other):
return torch.matmul(input, other)
x = torch.randn(2, 3, 4, requires_grad=True)
y = torch.randn(2, 4, 5, requires_grad=True)
self.run_test(MatmulModel(), (x, y))
x = torch.randint(10, (2, 3, 4))
y = torch.randint(10, (2, 4, 5))
self.run_test(MatmulModel(), (x, y))
def _argmin_argmax_model(self, input):
class ArgminArgmaxModel(torch.nn.Module):
def forward(self, input):
return torch.argmin(input), \
torch.argmax(input), \
torch.argmin(input, keepdim=True), \
torch.argmax(input, keepdim=True)
self.run_test(ArgminArgmaxModel(), input)
def test_argmin_argmax(self):
input = torch.randn(7, 3, 5)
self._argmin_argmax_model(input)
# Argmin and Argmax with "select_last_index" is not supprted before opset 12
# "select_last_index" was added in opset 12 to deal with corner case where the
# same value appears multiple times in the tensor
@skipIfUnsupportedMinOpsetVersion(12)
def test_argmin_argmax_select_last_index(self):
input = torch.tensor([[1., 2., 3.],
[1., 1., 2.]])
self._argmin_argmax_model(input)
input = torch.ones(7, 3, 5)
self._argmin_argmax_model(input)
def test_repeat(self):
class RepeatModel(torch.nn.Module):
def forward(self, x, y):
x2 = x.repeat(y.shape[0], 1)
y1 = y.view(-1, 1)
return x2 + y1
x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5, 8, 9])
self.run_test(RepeatModel(), (x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_repeat_interleave(self):
class FlattenModel(torch.nn.Module):
def forward(self, x):
return x.repeat_interleave(2)
x = torch.tensor([1, 2, 3])
self.run_test(FlattenModel(), (x,))
class DimsModel(torch.nn.Module):
def forward(self, x):
return x.repeat_interleave(4, dim=1)
x = torch.tensor([[1, 2], [3, 4]])
self.run_test(DimsModel(), (x,))
class DimsModel2(torch.nn.Module):
def forward(self, x):
repeats = torch.tensor([4])
return torch.repeat_interleave(x, repeats, dim=1)
x = torch.tensor([[1, 2], [3, 4]])
self.run_test(DimsModel2(), (x,))
class RepeatsDimsModel(torch.nn.Module):
def forward(self, x):
repeats = torch.tensor([1, 2])
return torch.repeat_interleave(x, repeats, dim=0)
x = torch.tensor([[1, 2], [3, 4]])
self.run_test(RepeatsDimsModel(), (x,))
class RepeatsDimsModel2(torch.nn.Module):
def forward(self, x):
repeats = torch.tensor([1, 2])
return torch.repeat_interleave(x, repeats, dim=1)
x = torch.tensor([[1, 2], [3, 4]])
self.run_test(RepeatsDimsModel2(), (x,))
@skipIfUnsupportedMinOpsetVersion(13)
def test_dynamic_repeat_interleave(self):
class SingleDynamicModel(torch.nn.Module):
def forward(self, x):
repeats = torch.tensor(4)
return torch.repeat_interleave(x, repeats, dim=1)
x = torch.tensor([[1, 2, 4], [3, 4, 7]])
another_x = torch.tensor([[7, 8], [5, 6]])
self.run_test(SingleDynamicModel(), x, test_with_inputs=[another_x],
input_names=["input_1"], dynamic_axes={"input_1" : {1 : "w"}})
class NegDynamicModel(torch.nn.Module):
def forward(self, x):
repeats = torch.tensor(4)
return torch.repeat_interleave(x, repeats, dim=-1)
x = torch.tensor([[1, 2, 4], [3, 4, 7]])
another_x = torch.tensor([[7, 8], [5, 6]])
self.run_test(NegDynamicModel(), x, test_with_inputs=[another_x],
input_names=["input_1"], dynamic_axes={"input_1" : {1 : "w"}})
class SingleDynamicModelFloat(torch.nn.Module):
def forward(self, x):
repeats = torch.tensor([4])
return torch.repeat_interleave(x, repeats, dim=0)
x = torch.tensor([[1.1, 2.1], [3.1, 4.1]])
another_x = torch.tensor([[7.1, 8.1], [5.1, 6.1]])
self.run_test(SingleDynamicModelFloat(), x, test_with_inputs=[another_x],
input_names=["input_1"], dynamic_axes={"input_1" : {0 : "h"}})
class DynamicRepeatsModel(torch.nn.Module):
def forward(self, x, repeats):
return torch.repeat_interleave(x, repeats, dim=1)
x = torch.tensor([[1, 2, 4], [3, 4, 7]])
another_x = torch.tensor([[7, 8], [5, 6]])
repeats = torch.tensor([2])
another_repeats = torch.tensor([4])
self.run_test(DynamicRepeatsModel(), (x, repeats), test_with_inputs=[(another_x, another_repeats)],
input_names=["input_1", "repeats_1"],
dynamic_axes={"input_1" : {1 : "w"}, "repeats_1" : {0 : "r"}})
class DynamicRepeatsModel2(torch.nn.Module):
def forward(self, x, repeats):
return torch.repeat_interleave(x, repeats, dim=1)
x = torch.tensor([[1, 2, 4], [3, 4, 7]])
repeats = torch.tensor([2])
another_repeats = torch.tensor([4])
self.run_test(DynamicRepeatsModel2(), (x, repeats), test_with_inputs=[(x, another_repeats)],
input_names=["input_1", "repeats_1"],
dynamic_axes={"repeats_1" : {0 : "r"}})
@skipIfUnsupportedMinOpsetVersion(13)
def test_multiple_dynamic_repeat_interleave(self):
class DynamicRepeatsModel(torch.nn.Module):
def forward(self, x, repeats):
return torch.repeat_interleave(x, repeats, dim=1)
x = torch.tensor([[1, 2, 4], [3, 4, 7]])
repeats = torch.tensor([2, 3, 4])
another_repeats = torch.tensor([4, 3, 2])
self.run_test(DynamicRepeatsModel(), (x, repeats), test_with_inputs=[(x, another_repeats)],
input_names=["input_1", "repeats_1"],
dynamic_axes={"repeats_1" : {0 : "r"}})
class DynamicRepeatsModel2(torch.nn.Module):
def forward(self, x, repeats):
return torch.repeat_interleave(x, repeats, dim=0)
x = torch.tensor([[1, 2, 4], [3, 4, 7]])
repeats = torch.tensor([2, 3])
another_repeats = torch.tensor([4, 3])
self.run_test(DynamicRepeatsModel2(), (x, repeats), test_with_inputs=[(x, another_repeats)],
input_names=["input_1", "repeats_1"],
dynamic_axes={"repeats_1" : {0 : "r"}})
def test_view(self):
class ViewModel(torch.nn.Module):
def forward(self, input):
return input.view(4, 24)
x = torch.randint(10, (4, 2, 3, 4), dtype=torch.int32)
self.run_test(ViewModel(), x)
def test_view_dynamic(self):
class ViewModel(torch.nn.Module):
def forward(self, input, other):
return input.view(other.shape)
x = torch.randn(2, 3, 4)
shape = torch.randn(6, 4)
self.run_test(ViewModel(), (x, shape),
input_names=["x", "shape"], dynamic_axes={"x": [0, 1, 2], "shape": [0, 1]})
self.run_test(ViewModel(), (x, shape), remained_onnx_input_idx=[0])
def test_view_dynamic_zero_dim(self):
class ViewModel(torch.nn.Module):
def forward(self, input):
input = input.view(-1, 2)
return input.view(1, -1)
x = torch.ones(2)
another_x = torch.empty((0,))
self.run_test(ViewModel(), x, test_with_inputs=[another_x],
input_names=["input_1"], dynamic_axes={"input_1": [0, ]})
def test_view_as(self):
class ViewModel(torch.nn.Module):
def forward(self, input, other):
return input.view_as(other)
x = torch.randn(2, 3, 4)
y = torch.randn(6, 4)
self.run_test(ViewModel(), (x, y))
def test_linear(self):
class LinearModel(torch.nn.Module):
def __init__(self):
super(LinearModel, self).__init__()
self.fc = torch.nn.Linear(16, 16)
def forward(self, x):
out = self.fc(x)
out = self.fc(out)
return out
x = torch.randn(3, 16)
self.run_test(LinearModel(), (x,))
class LinearModel(torch.nn.Module):
def forward(self, input, weight, bias):
return torch.nn.functional.linear(input, weight, bias)
# input of rank 2
x = torch.randn(2, 2)
y = torch.randn(2, 2)
z = torch.randn(1)
self.run_test(LinearModel(), (x, y, z))
# input of rank 3
x = torch.randn(3, 3, 3)
y = torch.randn(3, 3)
z = torch.randn(1)
self.run_test(LinearModel(), (x, y, z))
@disableScriptTest()
def test_weight_norm(self):
# addmm for 3-d inputs converts to onnx::MatMul
model = torch.nn.utils.weight_norm(torch.nn.Linear(5, 10), dim=1)
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(model, x)
# addmm for 2-d inputs converts to onnx::Gemm
model = torch.nn.utils.weight_norm(torch.nn.Linear(5, 10), dim=1)
x = torch.randn(4, 5, requires_grad=True)
self.run_test(model, x)
model = torch.nn.utils.weight_norm(torch.nn.Conv1d(1, 1, 3))
x = torch.randn(1, 1, 5, requires_grad=True)
self.run_test(model, x)
model = torch.nn.utils.weight_norm(torch.nn.Conv1d(1, 1, 3), dim=-2)
x = torch.randn(1, 1, 5, requires_grad=True)
self.run_test(model, x)
model = torch.nn.utils.weight_norm(torch.nn.Conv1d(3, 6, 3), name="weight")
x = torch.randn(3, 3, 5, requires_grad=True)
self.run_test(model, x)
@disableScriptTest()
def test_weight_norm_nodim(self):
# addmm for 3-d inputs converts to onnx::MatMul
model = torch.nn.utils.weight_norm(torch.nn.Linear(5, 10), dim=None)
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(model, x)
# addmm for 2-d inputs converts to onnx::Gemm
model = torch.nn.utils.weight_norm(torch.nn.Linear(5, 10), dim=None)
x = torch.randn(4, 5, requires_grad=True)
self.run_test(model, x)
def test_flatten(self):
class FlattenModel(torch.nn.Module):
def forward(self, input):
return torch.flatten(input)
x = torch.randint(10, (1, 2, 3, 4))
self.run_test(FlattenModel(), x)
def test_flatten2d(self):
class FlattenModel(torch.nn.Module):
def forward(self, input):
return torch.flatten(input, 1)
x = torch.randint(10, (1, 2, 3, 4))
self.run_test(FlattenModel(), x)
def test_flatten2d_neg(self):
class FlattenModel(torch.nn.Module):
def forward(self, x):
return torch.flatten(x, 1, -1), torch.flatten(x, 0, -2), torch.flatten(x, 1, -2)
x = torch.randint(10, (1, 2, 3, 4))
self.run_test(FlattenModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_flatten_dynamic_axes(self):
class MyModule(torch.nn.Module):
def forward(self, x):
return torch.flatten(x, start_dim=2, end_dim=3)
batch_size = 3
x = torch.randn(batch_size, 5, 4, 5)
y = torch.randn(5, 5, 4, 5)
model = MyModule()
self.run_test(model, x, test_with_inputs=[y],
input_names=["input"],
output_names=["output"],
dynamic_axes={"input" : {0 : "batch_size"},
"output" : {0 : "batch_size"}})
@skipIfUnsupportedMinOpsetVersion(11)
def test_getitem(self):
class GetItemModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x, y, z, ind):
# this will create prim::ListConstruct(x, y, z) + aten::__getitem__
arr = [x, y, z]
return arr[ind]
x = torch.randn(3, 4, 5)
y = torch.randn(1, 4, 5)
z = torch.randn(2, 4, 5)
ind = torch.tensor(1, dtype=torch.long)
self.run_test(GetItemModel(), (x, y, z, ind))
ind = torch.tensor(-2, dtype=torch.long)
self.run_test(GetItemModel(), (x, y, z, ind))
def test_item(self):
class M(torch.nn.Module):
def forward(self, x, y, i: int):
return int(x[y[i]].item())
x = torch.arange(6, dtype=torch.float)
y = torch.tensor([0, 1, 2, 3, 4], dtype=torch.long)
i = 3
self.run_test(torch.jit.script(M()), (x, y, i))
@disableScriptTest() # torch.nonzero(x, as_tuple=True) is not scriptable.
@skipIfUnsupportedMinOpsetVersion(9)
def test_nonzero(self):
class NonzeroModel(torch.nn.Module):
def forward(self, x):
return x.nonzero(), x.nonzero(as_tuple=True)
x = torch.randn(60).index_fill_(0, torch.randint(0, 60, (20,)), 0).view(3, 4, 5)
self.run_test(NonzeroModel(), (x,))
def test_unbind(self):
class UnbindModel(torch.nn.Module):
def forward(self, input):
_, out, _ = input.unbind()
return out
x = torch.randn(3, 4, 5)
self.run_test(UnbindModel(), x)
class UnbindModel2(torch.nn.Module):
def forward(self, input):
_, out, _, _ = input.unbind(1)
return out
x = torch.randn(3, 4, 5)
self.run_test(UnbindModel2(), x)
class UnbindModel3(torch.nn.Module):
def forward(self, input):
_, out, _, _ = input.unbind(-2)
return out
x = torch.randn(3, 4, 5)
self.run_test(UnbindModel3(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_len(self):
class LenModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return len(input.unbind()) + input
x = torch.randn(4, 5)
self.run_test(LenModel(), x, input_names=["input"], dynamic_axes={"input": {0: "seq"}},
test_with_inputs=(torch.randn(5, 5),))
@skipIfUnsupportedMinOpsetVersion(9)
def test_len_list(self):
class LenListModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.ones(len(input.shape))
x = torch.randn(4, 5)
self.run_test(LenListModel(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_unbind_dynamic(self):
class UnbindModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return input.unbind()[1]
x = torch.randn(3, 4, 5)
self.run_test(UnbindModel(), x)
class UnbindModel2(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return input.unbind(-1)[1]
x = torch.randn(3, 4, 5)
self.run_test(UnbindModel2(), x)
@disableScriptTest() # scripting tests run for opsets > 11. See: test_split_script
def test_split(self):
class SplitModel(torch.nn.Module):
def forward(self, input):
return input.split([2, 1, 2]), input.split([3, 2])[0]
x = torch.randn(5, 4, 3)
self.run_test(SplitModel(), x)
class SplitModel2(torch.nn.Module):
def forward(self, input):
return input.split([2, 1, 1], -2), input.split([2, 2], -2)[-1]
x = torch.randn(5, 4, 3)
self.run_test(SplitModel2(), x)
class SplitModel3(torch.nn.Module):
def forward(self, input):
return input.split([2, 1, 2])
x = torch.randn(5, 4, 3)
self.run_test(SplitModel3(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_split_script(self):
class SplitModel(torch.nn.Module):
def forward(self, input):
return input.split([2, 1, 2]), input.split([3, 2])[0]
x = torch.randn(5, 4, 3)
self.run_test(SplitModel(), x)
class SplitModel2(torch.nn.Module):
def forward(self, input):
return input.split([2, 1, 1], -2), input.split([2, 2], -2)[-1]
x = torch.randn(5, 4, 3)
self.run_test(SplitModel2(), x)
class SplitModel3(torch.nn.Module):
def forward(self, input):
return input.split([2, 1, 2])
x = torch.randn(5, 4, 3)
self.run_test(SplitModel3(), x)
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest()
def test_split_size_as_list(self):
class SplitModel(torch.nn.Module):
def forward(self, input, split_sizes: List[int]):
out = []
split_list: List[torch.Tensor] = input.split(split_sizes)
for ob in split_list:
out.append(ob)
return torch.cat(out, dim=0)
x = torch.randn(6, 4, 3)
split_sizes = [torch.tensor(2), torch.tensor(4)]
self.run_test(SplitModel(), (x, split_sizes))
@skipIfUnsupportedMinOpsetVersion(11)
def test_split_size_with_slice(self):
class SplitModule(torch.nn.Module):
def forward(self, x, y, t):
splits = (x.size(1), y.size(1))
out, out2 = torch.split(t, splits, dim=1)
return out, out2
x = torch.randn(2, 3)
y = torch.randn(2, 4)
t = torch.randn(2, 7)
self.run_test(SplitModule(), (x, y, t), input_names=["x", "y", "t"],
dynamic_axes={"x": [0, 1], "y": [0, 1], "t": [0, 1]})
self.run_test(SplitModule(), (x, y, t), remained_onnx_input_idx=[2])
@skipIfUnsupportedMinOpsetVersion(11)
def test_split_dynamic(self):
class SplitModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return input.split(2)[1]
x = torch.randn(5, 4, 3)
self.run_test(SplitModel(), x)
class SplitModel2(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return input.split(2, -3)[1]
x = torch.randn(5, 4, 3)
self.run_test(SplitModel2(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_split_dynamic_axes(self):
class Split(torch.nn.Module):
def forward(self, x):
return x.split(1, dim=-1)
x = torch.randn(4, 384, 2)
input_names = ["logits"]
self.run_test(Split(), x, input_names=input_names,
dynamic_axes={input_names[0]: {0: 'batch'}})
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest()
def test_chunk(self):
class ChunkModel(torch.nn.Module):
def __init__(self, dim=1):
super(ChunkModel, self).__init__()
self.dim = dim
def forward(self, x):
return torch.chunk(x, 3, dim=self.dim)
model = ChunkModel()
model.eval()
model_neg_dim = ChunkModel(-1)
model_neg_dim.eval()
x = torch.randn(1, 18)
for dim_size_ in range(13, 16):
y = torch.randn(1, dim_size_)
self.run_test(model, x, test_with_inputs=[y],
input_names=["x"],
dynamic_axes={"x": {0: "batch_size", 1: "dims"}})
self.run_test(model_neg_dim, x, test_with_inputs=[y],
input_names=["x"],
dynamic_axes={"x": {0: "batch_size", 1: "dims"}})
@skipIfUnsupportedMinOpsetVersion(11)
def test_dynamic_chunk(self):
class ChunkModel(torch.nn.Module):
def __init__(self, dim=1):
super(ChunkModel, self).__init__()
self.dim = dim
def forward(self, x):
return torch.chunk(x, x.size(0), dim=self.dim)
model = ChunkModel()
model.eval()
model_neg_dim = ChunkModel(-1)
model_neg_dim.eval()
x = torch.randn(3, 18)
for dim_size_ in range(13, 16):
y = torch.randn(3, dim_size_)
self.run_test(model, x, test_with_inputs=[y],
input_names=["x"],
dynamic_axes={"x": {0: "batch_size", 1: "dims"}})
self.run_test(model_neg_dim, x, test_with_inputs=[y],
input_names=["x"],
dynamic_axes={"x": {0: "batch_size", 1: "dims"}})
def test_concat(self):
class ConcatModel(torch.nn.Module):
def forward(self, x, y, z):
return torch.cat((x, y, z))
x = torch.randn(3, 4, 5)
y = torch.randn(1, 4, 5)
z = torch.randn(2, 4, 5)
self.run_test(ConcatModel(), (x, y, z))
@skipIfUnsupportedMinOpsetVersion(11)
def test_concat_dynamic(self):
class ConcatDynamicModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.cat(x.unbind())
x = torch.randn(4, 5, 6)
self.run_test(ConcatDynamicModel(), x)
def test_stack(self):
class StackModel(torch.nn.Module):
def forward(self, x, y, z):
return torch.stack((x, y, z), 1)
x = torch.randn(3, 4, 5)
y = torch.randn(3, 4, 5)
z = torch.randn(3, 4, 5)
self.run_test(StackModel(), (x, y, z))
@skipIfUnsupportedMinOpsetVersion(11)
def test_stack_dynamic(self):
class StackDynamicModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.stack(x.unbind(), 1)
x = torch.randn(4, 5, 6)
self.run_test(StackDynamicModel(), x)
def test_loop_dynamic(self):
class LoopModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
for i in range(x.size(2)):
x = x + i
return x
model = LoopModel()
inputs = torch.zeros(1, 2, 3, dtype=torch.long)
self.run_test(model, inputs)
@skipIfUnsupportedMinOpsetVersion(9)
def test_loop_nested(self):
class NestedLoopsModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
for i in range(5):
a = 0
while a < 4:
a += 1
x = x + a
return x
model = NestedLoopsModel()
inputs = torch.zeros(1, 2, 3, dtype=torch.long)
self.run_test(model, inputs)
@skipIfUnsupportedMinOpsetVersion(11)
def test_loop_with_list(self):
class ListLoopModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
res = []
res1 = []
arr = x.split([3, 4, 1, 1, 2, 3, 2], 0)
res2 = torch.zeros(3, 4, dtype=torch.long)
res3 = []
res4 = []
for i in range(len(arr)):
res.append(arr[i].sum(0, False))
res1.append(arr[-1 - i].sum(0, False))
res2 += 1
res3 = res3 + [arr[i].sum(0, False)]
res4 += [arr[-1 - i].sum(0, False)]
return res, res1, res2, torch.stack(res3), torch.stack(res4)
model = ListLoopModel()
inputs = torch.randn(16)
self.run_test(model, inputs)
@skipIfONNXShapeInference(False)
@skipIfUnsupportedMinOpsetVersion(11)
def test_loop_transpose(self):
class LoopModel(torch.nn.Module):
def forward(self, x):
res = torch.zeros_like(x[0])
for i in range(x.size(0)):
res += x[0].transpose(0, 1)
return res
model = torch.jit.script(LoopModel())
x = torch.randn(5, 3, 3)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_loop_multi_dim(self):
class LoopMultiDimModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x, y):
for x_ in torch.flip(x.narrow(0, 0, 7), [0]):
y = x_[0][y]
return y
model = LoopMultiDimModel()
x = torch.randint(0, 5, (8, 1, 17), dtype=torch.long)
y = torch.ones(1, dtype=torch.long)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
def test_list(self):
class ListModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
tensors = x.unbind()
res = []
res.append(tensors[0])
res.append(tensors[1])
res.pop(1)
res.insert(0, tensors[1])
res.append(tensors[2])
res += [tensors[3], tensors[4]]
res = res + [tensors[5]]
return torch.ones(len(res))
model = ListModel()
inputs = torch.randn(16, 1)
self.run_test(model, inputs)
@skipIfUnsupportedMinOpsetVersion(11)
def test_list_append(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
res += [torch.matmul(x[i], y)]
return res
model = torch.jit.script(ListModel())
x = torch.randn(16, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_append_nested(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
for j in range(x.size(1)):
res += [torch.matmul(x[i][j], y)]
return res
model = torch.jit.script(ListModel())
x = torch.randn(4, 4, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(14) # Need onnx::identity of sequence in opset 14
def test_list_append_nested_2(self):
class ListModel(torch.nn.Module):
def forward(self, x):
res = []
res_replicate = []
for i in range(x.size(0)):
if len(res) > 2:
for j in range(x.size(1)):
res.append(x[i][j])
res_replicate.append(res[-1])
res.append(res_replicate[-1])
return res, res_replicate
model = torch.jit.script(ListModel())
x = torch.randn(4, 4, 3, 4)
self.run_test(model, (x, ))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_append_nested_mixed_dtype(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
for j in range(x.size(1)):
if i == j:
res.append(x == y)
else:
res.append(x != y)
return res
model = torch.jit.script(ListModel())
x = torch.randn(4, 4, 3, 4)
y = torch.randn(3, 4)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
def test_list_pop(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
res += [torch.matmul(x[i], y)]
res.pop()
return res
model = torch.jit.script(ListModel())
x = torch.randn(16, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_pop_nested(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
for j in range(x.size(1)):
res += [torch.matmul(x[i][j], y)]
res.pop()
res += [torch.matmul(x[i][0], y)]
return res
model = torch.jit.script(ListModel())
x = torch.randn(4, 4, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
def test_list_del(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
res += [torch.matmul(x[i], y)]
del res[2]
return res
model = torch.jit.script(ListModel())
x = torch.randn(16, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_del_nested(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
for j in range(x.size(1)):
res += [torch.matmul(x[i][j], y)]
del res[i]
res += [torch.matmul(x[i][0], y)]
return res
model = torch.jit.script(ListModel())
x = torch.randn(4, 4, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@unittest.skip("Enable this once remove is supported by pytorch")
@skipIfUnsupportedMinOpsetVersion(11)
def test_list_remove(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
res += [torch.matmul(x[i], y)]
# The following fails with pytorch
# RuntimeError: Boolean value of Tensor with more than one value is ambiguous
res.remove(res[2])
return res
model = torch.jit.script(ListModel())
x = torch.randn(16, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
def test_list_set(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
res.append(x[i])
res[y] = x[y]
return res
model = torch.jit.script(ListModel())
x = torch.randn(12, 4)
y = torch.tensor(2, dtype=torch.long)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_idx_sum(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
indices = torch.arange(x.size(0))
res = []
for i in range(x.size(0)):
res.append(x[i])
return res[torch.sum(indices[:y])]
model = torch.jit.script(ListModel())
x = torch.randn(12, 4)
y = torch.tensor(2, dtype=torch.long)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_tensor_factories(self):
class TensorFactory(torch.nn.Module):
def forward(self, x):
return torch.zeros(x.size()) + torch.ones(x.size())
x = torch.randn(2, 3, 4)
self.run_test(TensorFactory(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(TensorFactory(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_tensor_factories_script(self):
class TensorFactory(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.zeros(x.shape, dtype=torch.float) + torch.ones(x.shape, dtype=torch.float)
x = torch.randn(2, 3, 4)
self.run_test(TensorFactory(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(TensorFactory(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_tensor_like_factories_script(self):
class TensorFactory(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
zeros = torch.zeros_like(x, dtype=torch.float, layout=torch.strided, device=torch.device("cpu"))
ones = torch.ones_like(x, dtype=torch.float, layout=torch.strided, device=torch.device("cpu"))
return zeros + ones
x = torch.randn(2, 3, 4)
self.run_test(TensorFactory(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(TensorFactory(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_eye(self):
class TensorFactory(torch.nn.Module):
def forward(self, x):
return torch.eye(x.size()[1], 3), torch.eye(4, 4, dtype=torch.long), \
torch.eye(x.size()[1], 2, dtype=torch.long), torch.eye(x.shape[0]), \
torch.eye(x.shape[0], dtype=torch.float64)
x = torch.randn(2, 3, 4)
another_x = torch.randn(5, 6, 7)
self.run_test(TensorFactory(), x, test_with_inputs=[another_x],
input_names=["input_1"], dynamic_axes={"input_1": [0, 1, 2]})
@skipIfUnsupportedMinOpsetVersion(9)
def test_inplace_zero(self):
class Zero_(torch.nn.Module):
def forward(self, x):
return x.zero_(), x
x = torch.randn(2, 3, 4)
self.run_test(Zero_(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(Zero_(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_new_zeros(self):
class Zero_(torch.nn.Module):
def forward(self, x):
return x.new_zeros(x.shape[1:2]), x.new_zeros(x.shape[2:], dtype=torch.long)
x = torch.randn(2, 3, 4)
self.run_test(Zero_(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(Zero_(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_new_ones(self):
class OnesModel(torch.nn.Module):
def forward(self, x):
return x.new_ones(x.shape[1:2]), x.new_ones(x.shape[2:], dtype=torch.long)
x = torch.randn(2, 3, 4)
self.run_test(OnesModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(OnesModel(), x, remained_onnx_input_idx=[])
@skipIfONNXShapeInference(True)
@skipIfUnsupportedMinOpsetVersion(9)
def test_tolist(self):
class List(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
cur_shape = torch._shape_as_tensor(input)
final_shape: List[int] = cur_shape.tolist()
pad_tensor = torch.zeros([1, 2] + final_shape)
return pad_tensor
x = torch.randn(2, 3)
self.run_test(List(), (x,))
@skipIfUnsupportedMinOpsetVersion(9)
@disableScriptTest()
def test_list_pass(self):
class Slice(torch.nn.Module):
def forward(self, x, y):
return x.new_zeros(x.shape[2:] + y.shape[1:])
x = torch.randn(2, 3, 4, 5)
y = torch.randn(1, 2, 3, 4)
self.run_test(Slice(), (x, y), input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2, 3], "y": [0, 1, 2, 3]})
self.run_test(Slice(), (x, y), remained_onnx_input_idx=[])
class Size(torch.nn.Module):
def forward(self, x, y):
return x.new_zeros(x.shape + y.shape)
x = torch.randn(2, 3, 4)
y = torch.randn(1, 2, 3)
self.run_test(Size(), (x, y), input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2], "y": [0, 1, 2]})
self.run_test(Size(), (x, y), remained_onnx_input_idx=[])
class Array(torch.nn.Module):
def forward(self, x, y):
arr1 = [x.shape[0], x.shape[1], 2]
arr2 = [y.shape[0], y.shape[1]]
return x.new_zeros(arr1 + arr2)
x = torch.randn(2, 3, 4)
y = torch.randn(1, 2, 3)
self.run_test(Array(), (x, y), input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2], "y": [0, 1, 2]})
self.run_test(Array(), (x, y), remained_onnx_input_idx=[])
class List(torch.nn.Module):
def forward(self, x, y):
l1 = list(x.shape)
l2 = list(y.shape)
return x.new_zeros(l1 + l2)
x = torch.randn(2, 3, 4)
y = torch.randn(1, 2, 3)
self.run_test(List(), (x, y), input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2], "y": [0, 1, 2]})
self.run_test(List(), (x, y), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_new_empty(self):
class Emtpy(torch.nn.Module):
def forward(self, x):
return x.new_empty(x.shape[0]).fill_(0), x.new_empty(x.shape[0], dtype=torch.long) * 0
x = torch.randn(2, 3, 4)
self.run_test(Emtpy(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(Emtpy(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_new_full(self):
class Full(torch.nn.Module):
def forward(self, x):
return x.new_full(x.shape[1:2], 5), x.new_full(x.shape[0:1], 1.3, dtype=torch.long)
x = torch.randn(2, 3, 4)
self.run_test(Full(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(Full(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_inplace_list(self):
class Arithmetic(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x, y):
return torch.cat([x.add_(3), y.fill_(0)])
x = torch.randn(2, 3)
y = torch.randn(2, 3)
self.run_test(Arithmetic(), (x, y), input_names=["x", "y"],
dynamic_axes={"x": [0, 1], "y": [0, 1]})
self.run_test(Arithmetic(), (x, y), remained_onnx_input_idx=[0])
@skipIfUnsupportedMinOpsetVersion(9)
def test_inplace_fill(self):
class Fill_(torch.nn.Module):
def forward(self, x):
return x.fill_(3), x
x = torch.randn(2, 3, 4)
self.run_test(Fill_(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(Fill_(), x, remained_onnx_input_idx=[])
def test_inplace_arithmetic(self):
class Arithmetic(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x, y):
x.add_(3)
y.mul_(x)
return x, y
x = torch.randn(2, 3, 4)
y = torch.randn(2, 3, 4)
self.run_test(Arithmetic(), (x, y))
def test_inplace_arithmetic_half(self):
class InplaceAddModel(torch.nn.Module):
def forward(self, x, y):
return x.add_(y)
class InplaceMulModel(torch.nn.Module):
def forward(self, x, y):
return x.mul_(y)
x = torch.randn(2, 2, dtype=torch.half)
y = torch.randn(2, 2, dtype=torch.float)
self.run_test(InplaceAddModel(), (x, y), rtol=1e-2, atol=1e-2)
self.run_test(InplaceMulModel(), (x, y), rtol=1e-2, atol=1e-2)
@skipIfUnsupportedMinOpsetVersion(9)
def test_inplace_with_loop(self):
class M(torch.nn.Module):
def forward(self, x):
a = torch.ones(12,)
for i in range(10):
a.add_(torch.ones(12,))
return a + x
m = M()
x = torch.randn(12,)
self.run_test(torch.jit.script(M()), (x))
@skipIfUnsupportedMinOpsetVersion(9)
def test_inplace_with_loop_2(self):
class M(torch.nn.Module):
def forward(self, x):
_bias = torch.ones(12,)
a = torch.ones(12,) # used in loop, altered.
a_ref = a # not used in loop, should be altered.
b = x.clone() # used in loop, not be altered.
b_ref = b # not used in loop, should not be altered.
for i in range(10):
if i == 3:
for j in range(5):
a += _bias
_bias.add_(torch.ones(12,))
b = b + torch.ones(12,)
_bias.add_(torch.ones(12,))
a += _bias
# TODO: value for a_ref is incorrect.
# a_ref += torch.ones(12,)
b_ref += torch.ones(12,)
return _bias + x, a, b, b_ref
m = M()
x = torch.zeros(12,)
self.run_test(torch.jit.script(M()), (x))
@skipIfUnsupportedMinOpsetVersion(11)
def test_inplace_attr_with_loop(self):
class M(torch.nn.Module):
def __init__(self):
super().__init__()
self._bias = torch.arange(12,)
def forward(self, x):
self._bias = torch.arange(12,)
for i in range(10):
if i == 3:
for j in range(5):
self._bias += torch.arange(12,)
return self._bias + x
m = M()
x = torch.zeros(12,)
self.run_test(torch.jit.script(M()), (x))
@skipIfUnsupportedMinOpsetVersion(11)
def test_inplace_attr_copy_with_loop(self):
class M(torch.nn.Module):
def __init__(self):
super().__init__()
self._bias = torch.arange(12,)
def forward(self, x):
self._bias = torch.arange(12,)
for i in range(10):
if i == 3:
for j in range(5):
self._bias.copy_(torch.arange(12,))
self._bias.copy_(self._bias + torch.arange(12,))
self._bias.copy_(self._bias + torch.arange(12,))
return self._bias + x
m = M()
x = torch.zeros(12,)
self.run_test(torch.jit.script(M()), (x))
@skipIfUnsupportedMinOpsetVersion(14) # Need onnx::identity of sequence in opset 14
def test_inplace_sequence_with_loop(self):
class M(torch.nn.Module):
def process(self, beam_hyps: List[torch.Tensor], done: torch.Tensor, x):
batch_size = x.shape[0]
for i in range(batch_size):
if done[i]:
continue
beam_idx = 0
for _, token in enumerate(x[i]):
beam_hyps.append(token)
beam_idx += 1
if beam_idx == 6:
break
done[i] = len(beam_hyps) > 4
return beam_hyps, done
def forward(self, x):
beam_hyps: List[torch.Tensor] = []
batch_size = x.shape[0]
cur_len = 0
max_len = x.shape[1]
done = torch.zeros(batch_size, dtype=torch.bool)
while cur_len < max_len:
beam_hyps, done = self.process(beam_hyps, done, x[:, 0, :])
cur_len = cur_len + 1
return beam_hyps
m = torch.jit.script(M())
x = torch.randn(8, 4, 3)
self.run_test(torch.jit.script(M()), (x))
@disableScriptTest() # Sort with dynamic dim not supported in ONNX
def test_sort(self):
class SortModel(torch.nn.Module):
def forward(self, x):
out = []
for i in range(-2, 2):
out.append(torch.sort(x, dim=i, descending=True))
return out
x = torch.randn(3, 4)
self.run_test(SortModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest() # Sort with dynamic dim not supported in ONNX
def test_sort_ascending(self):
class SortModel(torch.nn.Module):
def forward(self, x):
out = []
for i in range(-2, 2):
out.append(torch.sort(x, dim=i, descending=False))
return out
x = torch.randn(3, 4)
self.run_test(SortModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_masked_fill(self):
class MaskedFillModel(torch.nn.Module):
def forward(self, x):
mask = torch.tensor([[0, 0, 1], [1, 1, 0]], dtype=torch.uint8)
return x.masked_fill(mask, 2)
x = torch.zeros(4, 2, 3, requires_grad=True)
self.run_test(MaskedFillModel(), x)
class MaskedFillModel2(torch.nn.Module):
def forward(self, x):
return x.masked_fill(x > 3, -1)
x = torch.arange(16).view(2, 2, 4).to(torch.float32)
self.run_test(MaskedFillModel2(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_masked_fill_inplace(self):
class MaskedFillModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
mask = torch.tensor([[0, 0, 1], [1, 1, 0]], dtype=torch.uint8)
x.masked_fill_(mask, 2)
return x
x = torch.zeros(4, 2, 3, requires_grad=True)
self.run_test(MaskedFillModel(), x)
class MaskedFillModel2(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
x.masked_fill_(x > 3, -1)
return x
x = torch.arange(16).view(2, 2, 4).to(torch.float32)
self.run_test(MaskedFillModel2(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_masked_scatter(self):
class MaskedScatterModel(torch.nn.Module):
def forward(self, x):
return torch.masked_scatter(x, x.ge(0.5), torch.ones(100, 100) * 5)
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(MaskedScatterModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_masked_select(self):
class MaskedSelectModel(torch.nn.Module):
def forward(self, x):
return torch.masked_select(x, x.ge(0.5))
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(MaskedSelectModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_to_masked_fill(self):
class MaskedFillModel(torch.nn.Module):
def forward(self, input_mask, some_const):
mask = input_mask.clone()
mask[mask != some_const] = 1
mask[mask == some_const] = 0
return mask
mask = torch.randn(2, 2, 2, requires_grad=True)
constant = torch.tensor(5, dtype=torch.float)
self.run_test(MaskedFillModel(), (mask, constant))
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_to_masked_scatter(self):
class MaskedScatterModel(torch.nn.Module):
def forward(self, input_mask, some_const):
mask = input_mask.clone()
mask[mask != some_const] = torch.ones(8)
return mask
mask = torch.randn(2, 2, 2, requires_grad=True)
constant = torch.tensor(5, dtype=torch.float)
self.run_test(MaskedScatterModel(), (mask, constant))
@skipIfUnsupportedMinOpsetVersion(9)
def test_pixel_shuffle(self):
class PixelShuffle(torch.nn.Module):
def forward(self, x):
return torch.pixel_shuffle(x, upscale_factor=2)
x = torch.randn(2, 16, 4, 3, requires_grad=True)
self.run_test(PixelShuffle(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_scalar_type(self):
class ArithmeticModel(torch.nn.Module):
def forward(self, x):
return x.size(0) * 2 * x, 2 - x
x = torch.ones(2, 3, dtype=torch.float32)
self.run_test(ArithmeticModel(), x)
class ReciprocalModel(torch.nn.Module):
def forward(self, x):
return torch.reciprocal(x)
x = torch.tensor([2.0, 4.0], dtype=torch.double)
self.run_test(ReciprocalModel(), x)
class ComparisonModel(torch.nn.Module):
def forward(self, x, y):
a = torch.tensor([12.0])
return x.lt(1.5) & y.le(2) & x.le(1), x.gt(y), x.lt(y), a.ge(x.size(0))
x = torch.ones(2, 3, dtype=torch.int32)
y = torch.ones(2, 3, dtype=torch.float32)
self.run_test(ComparisonModel(), (x, y))
class MatMulModel(torch.nn.Module):
def forward(self, x):
return (torch.mm(x, x) + x + torch.mm(x, x) + x)
x = torch.ones(3, 3)
self.run_test(MatMulModel(), x)
class AddMMModel(torch.nn.Module):
def forward(self, x):
return torch.mm(x, x) + x
x = torch.ones(3, 3)
self.run_test(AddMMModel(), x)
class FullModel(torch.nn.Module):
# add is used for exporting full
def forward(self, x):
return torch.full((3, 4), x)
x = torch.tensor(12.)
self.run_test(FullModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_full_like(self):
class FullLikeModel(torch.nn.Module):
def forward(self, x):
return torch.full_like(x, 4)
x = torch.tensor(12)
self.run_test(FullLikeModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_full_like_value(self):
class FullLikeModel(torch.nn.Module):
def forward(self, x, y):
out = y + 2
return torch.full_like(x, out)
x = torch.tensor(12)
y = torch.tensor(2)
self.run_test(FullLikeModel(), (x, y))
def test_l1_norm(self):
class NormModel(torch.nn.Module):
def forward(self, x):
return torch.norm(x, p=1, dim=-1, keepdim=False)
x = torch.randn(4, 2, 3, requires_grad=True)
self.run_test(NormModel(), x)
def test_l2_norm(self):
class NormModel(torch.nn.Module):
def forward(self, x):
return torch.norm(x, p=2, dim=-2, keepdim=False)
x = torch.randn(4, 2, 3, requires_grad=True)
self.run_test(NormModel(), x)
def test_frobenius_norm(self):
class NormModel(torch.nn.Module):
def forward(self, x):
return torch.norm(x, p="fro", dim=0, keepdim=False)
x = torch.randn(4, 2, 3, requires_grad=True)
self.run_test(NormModel(), x)
def test_frobenius_norm_keepdim(self):
class NormModel(torch.nn.Module):
def forward(self, x):
return torch.norm(x, p="fro", dim=(0, 1), keepdim=True)
x = torch.randn(4, 2, 3, requires_grad=True)
self.run_test(NormModel(), x)
def test_unfold(self):
class UnfoldModel(torch.nn.Module):
def forward(self, x):
return x.unfold(dimension=2, size=2, step=2)
x = torch.randn(4, 2, 3, requires_grad=True)
y = torch.randn(2, 1, 3, requires_grad=True)
self.run_test(UnfoldModel(), x,
dynamic_axes={"x": [0, 1]},
input_names=["x"],
test_with_inputs=[y])
@skipIfONNXShapeInference(False)
def test_unfold_infer_shape(self):
class UnfoldModule(torch.jit.ScriptModule):
def __init__(self):
super(UnfoldModule, self).__init__()
self.conv = torch.nn.Conv1d(3, 1, 3, stride=2)
@torch.jit.script_method
def forward(self, x):
x = self.conv(x)
return x.unfold(dimension=2, size=2, step=2)
x = torch.randn(32, 3, 64)
self.run_test(UnfoldModule(), x)
@skipIfUnsupportedMinOpsetVersion(12)
def test_unfold_dynamic_inputs(self):
class UnfoldModel(torch.nn.Module):
def forward(self, x):
return x.unfold(dimension=2, size=x.shape[1], step=x.shape[1] - 1)
x = torch.randn(4, 2, 4, requires_grad=True)
self.run_test(UnfoldModel(), x)
class UnfoldModel(torch.nn.Module):
def forward(self, x):
return x.unfold(dimension=2, size=x.shape[1], step=1)
x = torch.randn(4, 2, 4, requires_grad=True)
self.run_test(UnfoldModel(), x)
@skipIfUnsupportedMinOpsetVersion(9) # MatMul long inputs is added in ONNX opset 9.
def test_mv(self):
class MatmulModel(torch.nn.Module):
def forward(self, input, other):
return torch.mv(input, other)
x = torch.randn(4, 5, requires_grad=True)
y = torch.randn(5, requires_grad=True)
self.run_test(MatmulModel(), (x, y))
x = torch.randint(10, (4, 5))
y = torch.randint(10, (5, ))
self.run_test(MatmulModel(), (x, y))
@skipIfUnsupportedMinOpsetVersion(9) # MatMul long inputs is added in ONNX opset 9.
def test_dot(self):
class MatmulModel(torch.nn.Module):
def forward(self, input, other):
return torch.dot(input, other)
x = torch.randn(5, requires_grad=True)
y = torch.randn(5, requires_grad=True)
self.run_test(MatmulModel(), (x, y))
x = torch.randint(10, (5, ))
y = torch.randint(10, (5, ))
self.run_test(MatmulModel(), (x, y))
@disableScriptTest() # SpectralNorm not TorchScript compatible.
def test_spectral_norm(self):
m = torch.nn.utils.spectral_norm(torch.nn.Linear(2, 4))
x = torch.randn(6, 2)
self.run_test(m, (x, ))
def test_prelu(self):
class PReluModel(torch.nn.Module):
def __init__(self):
super(PReluModel, self).__init__()
self.prelu = torch.nn.PReLU()
def forward(self, x):
return self.prelu(x)
x = torch.randn(2, 3, 4)
y = torch.randn(2, 4, 5)
self.run_test(PReluModel(), x, input_names=["x"],
dynamic_axes={"x": [1, 2]},
test_with_inputs=[y])
def test_relu6(self):
class Relu6Model(torch.nn.Module):
def __init__(self):
super(Relu6Model, self).__init__()
self.relu6 = torch.nn.ReLU6()
def forward(self, x):
return self.relu6(x)
x = torch.randn(2, 3, 4) * 100.0
y = torch.randn(2, 4, 5) * 100.0
self.run_test(Relu6Model(), x, input_names=['x'],
dynamic_axes={'x': [1, 2]},
test_with_inputs=[y])
def test_silu(self):
class SiLUModel(torch.nn.Module):
def __init__(self):
super(SiLUModel, self).__init__()
self.silu = torch.nn.SiLU()
def forward(self, x):
return self.silu(x)
x = torch.randn(2, 3, 4)
self.run_test(SiLUModel(), (x))
@skipIfUnsupportedMinOpsetVersion(14)
def test_tril(self):
class trilModel(torch.nn.Module):
def forward(self, x):
return torch.tril(x)
x = torch.randn(2, 3, 4)
self.run_test(trilModel(), (x))
class trilModelwithDiagonal(torch.nn.Module):
def forward(self, x):
return torch.tril(x, diagonal=1)
x = torch.randn(2, 3, 4)
self.run_test(trilModelwithDiagonal(), (x))
class trilModelwithNegDiagonal(torch.nn.Module):
def forward(self, x):
return torch.tril(x, diagonal=-1)
x = torch.randn(2, 3, 4)
self.run_test(trilModelwithNegDiagonal(), (x))
@skipIfUnsupportedMinOpsetVersion(14)
def test_triu(self):
class triuModel(torch.nn.Module):
def forward(self, x):
return torch.triu(x)
x = torch.randn(2, 3, 4)
self.run_test(triuModel(), (x))
class triuModelwithDiagonal(torch.nn.Module):
def forward(self, x):
return torch.triu(x, diagonal=1)
x = torch.randn(2, 3, 4)
self.run_test(triuModelwithDiagonal(), (x))
class trilModelwithNegDiagonal(torch.nn.Module):
def forward(self, x):
return torch.tril(x, diagonal=-1)
x = torch.randn(2, 3, 4)
self.run_test(trilModelwithNegDiagonal(), (x))
def test_mish(self):
class MishModel(torch.nn.Module):
def __init__(self):
super(MishModel, self).__init__()
self.mish = torch.nn.Mish()
def forward(self, x):
return self.mish(x)
x = torch.randn(2, 3, 4)
self.run_test(MishModel(), (x))
def test_remainder(self):
class RemainderModel(torch.nn.Module):
def forward(self, input, other):
return torch.remainder(input, other)
x = torch.randn(4, 2, 3)
y = torch.randn(1, 2, 1)
self.run_test(RemainderModel(), (x, y))
def test_remainder_scalar(self):
class RemainderModel(torch.nn.Module):
def forward(self, input):
return torch.remainder(input, 2.55)
x = torch.randint(10, (2, 3))
self.run_test(RemainderModel(), x)
@skipIfUnsupportedMinOpsetVersion(10)
def test_fmod(self):
class FModModel(torch.nn.Module):
def forward(self, input, other):
return torch.fmod(input, other)
x = torch.randn(4, 2, 3)
y = torch.randn(1, 2, 1)
self.run_test(FModModel(), (x, y))
@skipIfUnsupportedMinOpsetVersion(10)
def test_fmod_scalar(self):
class FModModel(torch.nn.Module):
def forward(self, input):
return torch.fmod(input, 2.55)
x = torch.randint(10, (2, 3))
self.run_test(FModModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_glu(self):
class GluModel(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.glu(x)
x = torch.randn(2, 4, 5, 6, requires_grad=True)
self.run_test(GluModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_gelu(self):
class GeluModel(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.gelu(x)
x = torch.randn(2, 4, 5, 6, requires_grad=True)
self.run_test(GeluModel(), x)
def test_add_inplace(self):
class InplaceAddModel(torch.nn.Module):
def forward(self, x):
x += 12
return x
x = torch.randn(4, 2, 3, requires_grad=True)
self.run_test(InplaceAddModel(), x)
def test_rsqrt(self):
class RsqrtModel(torch.nn.Module):
def forward(self, x):
return x.rsqrt()
x = torch.randn(4, 2, 3, requires_grad=True, dtype=torch.float64)
self.run_test(RsqrtModel(), x)
def test_rsqrt_zeros(self):
class RsqrtModel(torch.nn.Module):
def forward(self, x):
return x.rsqrt()
x = torch.zeros(4, 2, 3, requires_grad=True, dtype=torch.float64)
self.run_test(RsqrtModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_unique(self):
class UniqueModel(torch.nn.Module):
def forward(self, x):
return torch.unique(x, sorted=True, return_inverse=False, return_counts=True)
x = torch.tensor([1, 3, 2, 3], dtype=torch.long)
self.run_test(UniqueModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_unique_along_dim(self):
class UniqueModel(torch.nn.Module):
def forward(self, x):
return torch.unique(x, dim=0, sorted=True, return_inverse=True, return_counts=False)
x = torch.tensor([1, 3, 2, 3], dtype=torch.long)
self.run_test(UniqueModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_cumsum(self):
class CumSum(torch.nn.Module):
def forward(self, input):
return torch.cumsum(input, dim=0)
x = torch.randn(2, 3, 4)
model = CumSum()
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_cumsum_with_cast(self):
class CumSum(torch.nn.Module):
def forward(self, input):
return torch.cumsum(input, dim=0, dtype=torch.float32)
model = CumSum()
x = torch.tensor([2, 3, 4], dtype=torch.int32)
self.run_test(model, x)
x = torch.tensor([False, True, True])
self.run_test(model, x)
@disableScriptTest() # error in propagate as assign input shape
@skipIfUnsupportedMinOpsetVersion(10)
def test_embedding_bag(self):
model = torch.nn.EmbeddingBag(10, 5, mode="sum", scale_grad_by_freq=True)
input = torch.randint(10, (7,))
offset = torch.tensor([0, 2, 5, 6])
self.run_test(model, (input, offset))
model = torch.nn.EmbeddingBag(10, 5, mode="sum", include_last_offset=True)
input = torch.randint(10, (7,))
offset = torch.tensor([0, 2, 5, 6])
self.run_test(model, (input, offset))
model = torch.nn.EmbeddingBag(10, 5, mode="max")
input = torch.randint(10, (7, 5))
self.run_test(model, (input))
@skipIfUnsupportedMinOpsetVersion(11)
def test_embedding_bag_1d_per_sample_weights(self):
class EmbeddingModel(torch.nn.Module):
def forward(self, embedding_matrix, input, offset, weights):
return torch.nn.functional.embedding_bag(input, embedding_matrix, offsets=offset,
mode="sum", per_sample_weights=weights)
model = EmbeddingModel()
x = torch.randint(7, (6,))
w = torch.randn(6, )
offset = torch.tensor([0, 2, 5])
embedding_matrix = torch.rand(10, 15)
self.run_test(model, (embedding_matrix, x, offset, w))
@skipIfUnsupportedMinOpsetVersion(11)
def test_embedding_bag_2d_per_sample_weights(self):
class EmbeddingModel(torch.nn.Module):
def forward(self, embedding_matrix, input, weights):
return torch.nn.functional.embedding_bag(input, embedding_matrix,
mode="sum", per_sample_weights=weights)
embedding_matrix = torch.rand(10, 15)
model = EmbeddingModel()
x = torch.randint(7, (2, 3))
w = torch.randn(2, 3)
self.run_test(model, (embedding_matrix, x, w))
@disableScriptTest() # scripting prim::Uninitialized, prim::dtype, prim::unchecked_cast
@skipIfUnsupportedMinOpsetVersion(11)
@unittest.skip("Due to ONNX Loop shape inference issue.")
def test_embedding_bag_dynamic_input(self):
class EmbeddingModel1D(torch.nn.Module):
def forward(self, embedding_matrix, input, weights, offsets):
return torch.nn.functional.embedding_bag(input, embedding_matrix, offsets=offsets,
mode="sum", per_sample_weights=weights)
model = EmbeddingModel1D()
x = torch.randint(7, (6,))
w = torch.randn(6, )
offsets = torch.tensor([0, 2, 5], dtype=torch.long)
embedding_matrix = torch.rand(10, 15)
x2 = torch.randint(7, (2,))
w2 = torch.randn(2, )
embedding_matrix2 = torch.rand(12, 25)
offsets2 = torch.tensor([0, ], dtype=torch.long)
self.run_test(model, (embedding_matrix, x, w, offsets),
test_with_inputs=[(embedding_matrix2, x2, w2, offsets2)],
input_names=["embedding_matrix", "x", "offsets", "w"],
dynamic_axes={"embedding_matrix": [0, 1], "x": [0], "offsets": [0], "w": [0]})
class EmbeddingModel2D(torch.nn.Module):
def forward(self, embedding_matrix, input, weights):
return torch.nn.functional.embedding_bag(input, embedding_matrix,
mode="sum", per_sample_weights=weights)
model = EmbeddingModel2D()
x = torch.randint(7, (2, 3))
w = torch.randn(2, 3)
embedding_matrix = torch.rand(10, 15)
x2 = torch.randint(7, (3, 5))
w2 = torch.randn(3, 5)
embedding_matrix2 = torch.rand(12, 25)
self.run_test(model, (embedding_matrix, x, w),
test_with_inputs=[(embedding_matrix2, x2, w2)],
input_names=["embedding_matrix", "x", "w"],
dynamic_axes={"embedding_matrix": [0, 1], "x": [0, 1], "w": [0, 1]})
@skipIfUnsupportedMinOpsetVersion(8)
def test_meshgrid(self):
class Meshgrid(torch.nn.Module):
def forward(self, x, y, z):
output1, output2, output3 = torch.meshgrid(x, y, z)
return output1, output2, output3
x = torch.randn(3, requires_grad=True)
y = torch.zeros(4, requires_grad=True)
z = torch.randn(5, requires_grad=True)
self.run_test(Meshgrid(), (x, y, z))
@skipIfUnsupportedMinOpsetVersion(8)
def test_meshgrid_scalar(self):
class Meshgrid(torch.nn.Module):
def forward(self, x, y, z):
output1, output2, output3 = torch.meshgrid(x, y, z)
return output1, output2, output3
x = torch.ones(3, requires_grad=True)
y = torch.zeros(4, requires_grad=True)
z = torch.tensor(2.0)
self.run_test(Meshgrid(), (x, y, z))
def test_baddbmm(self):
class MyModule(torch.nn.Module):
def forward(self, input, batch1, batch2):
return torch.baddbmm(input, batch1, batch2, alpha=torch.tensor(5), beta=3.5)
x = torch.randn(10, 3, 5)
batch1 = torch.randn(10, 3, 4)
batch2 = torch.randn(10, 4, 5)
model = MyModule()
self.run_test(model, (x, batch1, batch2))
def test_baddbmm_dynamic(self):
class MyModule(torch.nn.Module):
def forward(self, input, batch1, batch2, alpha, beta):
return torch.baddbmm(input, batch1, batch2, alpha=alpha, beta=beta)
x = torch.randn(10, 3, 5)
batch1 = torch.randn(10, 3, 4)
batch2 = torch.randn(10, 4, 5)
alpha = torch.tensor(5)
beta = torch.tensor(3.5)
model = MyModule()
self.run_test(model, (x, batch1, batch2, alpha, beta))
def test_numel(self):
class MyModule(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return input.numel() * input
x = torch.randn(2, 3, 5)
model = MyModule()
self.run_test(model, (x,))
def test_numel_empty(self):
class MyModule(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return input.numel() * input
x = torch.randn(0)
model = MyModule()
self.run_test(model, (x,))
def test_dtype(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input, other):
return input.to(dtype=other.dtype) + other
x = torch.randn(2, 3)
y = torch.randn(2, 3)
self.run_test(MyModel(), (x, y))
def test_dtype_eq(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input, other):
if input.dtype == other.dtype:
return input + other
return input
x = torch.randn(2, 3)
y = torch.randn(2, 3)
self.run_test(MyModel(), (x, y))
def test_cast_to(self):
class MyModule(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input, other):
return input.to(other) + other
x = torch.randn(2, 3, 4)
y = torch.tensor([1], dtype=torch.int64)
model = MyModule()
self.run_test(model, (x, y))
def test_cast_to_bool(self):
class MyModule(torch.nn.Module):
def forward(self, input, other):
return torch.cat((input.to(other), other), 0)
x = torch.randn(2, 3, 4)
y = torch.zeros([2, 3, 4], dtype=torch.bool)
model = MyModule()
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_type_as(self):
class MyModule(torch.nn.Module):
def forward(self, x):
y = torch.tensor([1.0])
return x.type_as(y)
a = torch.tensor([True, False], dtype=torch.bool)
b = torch.randn(3, 4, dtype=torch.double)
c = torch.ones((2, 2), dtype=torch.int64)
model = MyModule()
self.run_test(model, a)
self.run_test(model, b)
self.run_test(model, c)
@skipIfUnsupportedMinOpsetVersion(9)
def test_ones_bool(self):
class MyModule(torch.nn.Module):
def forward(self, input):
true = torch.ones(input.shape, dtype=torch.bool)
return input.to(true) & true
x = torch.randn(2, 3, 4)
model = MyModule()
self.run_test(model, x)
def test_log(self):
class Log(torch.nn.Module):
def forward(self, input):
return torch.log(input)
x = torch.rand(2, 3, 4)
model = Log()
self.run_test(model, x)
def test_log1p(self):
class Log1p(torch.nn.Module):
def forward(self, input):
return torch.log1p(input)
x = torch.rand(2, 3, 4)
model = Log1p()
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_round(self):
class Round(torch.nn.Module):
def forward(self, x):
return torch.round(x)
x = torch.tensor([0.9920, -1.0362, -1.5000, 3.5000], requires_grad=True)
self.run_test(Round(), x)
def test_constant_pad(self):
model = torch.nn.ConstantPad1d(2, 3.5)
x = torch.randn(2, 4, 4)
self.run_test(model, x)
model = torch.nn.ConstantPad2d((3, 0, 2, 1), 3.5)
x = torch.randn(2, 2, 4, 4)
self.run_test(model, x)
# Dynamic padding is added in opset 11
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest() # Functional module not scriptable
def test_pad_types(self):
# Test for different pad integer types
class Pad(torch.nn.Module):
def forward(self, x, pad: List[int]):
return torch.nn.functional.pad(x, pad)
x = torch.randn(2, 2, 4, 4)
y = pad = (torch.tensor(2, dtype=torch.int32), torch.tensor(4, dtype=torch.int32))
self.run_test(Pad(), (x, y))
y = pad = (torch.tensor(2, dtype=torch.int64), torch.tensor(4, dtype=torch.int64))
self.run_test(Pad(), (x, y))
@skipIfUnsupportedMaxOpsetVersion(10)
def test_unsupported_pad(self):
class Pad(torch.nn.Module):
def forward(self, x, pad):
return torch.nn.functional.pad(x, pad)
def run():
x = torch.randn(2, 2, 4, 4)
y = pad = (torch.tensor(2, dtype=torch.int32), torch.tensor(4, dtype=torch.int32))
p = Pad()
f = io.BytesIO()
torch.onnx._export(p, (x, y), f)
with self.assertRaises(RuntimeError) as cm:
run()
the_exception = cm.exception
self.assertEqual("Unsupported: ONNX export of Pad in opset 9. The sizes of the padding must be constant. " +
"Please try opset version 11.", the_exception.args[0])
@skipIfUnsupportedMinOpsetVersion(9)
def test_if_fold(self):
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.dim() == 2:
y = y + 4
y = y + 2
else:
y = y - 1
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.numel() > 1:
y = y + 4
else:
y = y + 2
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.dim() != 3:
y = y + 4
y = y + 2
else:
return y
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.dim() >= 1:
y = y + 4
else:
y = y - 1
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.dim() <= 1:
y = y + 4
else:
y = y + 2
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.dim() < 3 and y.dtype == torch.int:
y = y + 4
y = y + 2
else:
return y
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.dim() == 3 and y.dtype == torch.int:
y = y + 4
y = y + 2
else:
y = y + 1
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.numel() != 0 and y.dim() == 2:
y = y + 4
y = y + 2
else:
return y
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, x, y):
if x.numel() == y.numel():
y = x + y
else:
y = y - x
return y
x = torch.ones((3, 4), dtype=torch.int)
y = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), (x, y))
class IfFoldModel(torch.nn.Module):
def forward(self, x, y):
if x.numel() != y.numel():
y = x + y
else:
y = y - x
return y
x = torch.ones((3, 4), dtype=torch.int)
y = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
@skipIfONNXShapeInference(False)
def test_uninitialized(self):
class UninitializedModel(torch.nn.Module):
def forward(self, y):
if y.shape[1] < 5:
if y.size(0) == 1:
y = y + 4
else:
return y
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(UninitializedModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
@skipIfONNXShapeInference(False)
def test_uninitialized_dynamic(self):
class UninitializedModel(torch.nn.Module):
def forward(self, y):
if y.shape[1] < 5:
if y.size(0) == 1:
y = y + 4
else:
return y
return y
x = torch.ones((3, 4), dtype=torch.int)
y = torch.ones((6, 7), dtype=torch.int)
self.run_test(UninitializedModel(), x, test_with_inputs=[y],
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1]})
def test_reflection_pad(self):
model = torch.nn.ReflectionPad1d(2)
x = torch.randn(2, 4, 4)
self.run_test(model, x)
model = torch.nn.ReflectionPad2d((3, 0, 2, 1))
x = torch.randn(2, 2, 4, 4)
self.run_test(model, x)
def test_replication_pad(self):
model = torch.nn.ReplicationPad1d(2)
x = torch.randn(2, 4, 4)
self.run_test(model, x)
model = torch.nn.ReplicationPad2d((3, 0, 2, 1))
x = torch.randn(2, 2, 4, 4)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_im2col(self):
class Unfold(torch.nn.Module):
def forward(self, input):
return torch.nn.functional.unfold(input, kernel_size=(10, 15), dilation=2, padding=5, stride=3), \
torch.nn.functional.unfold(input, kernel_size=(2, 2), dilation=1, padding=0, stride=3), \
torch.nn.functional.unfold(input, kernel_size=(1, 1), dilation=5, padding=2, stride=3)
x = torch.rand(1, 1, 200, 100)
self.run_test(Unfold(), x)
@skipIfNoLapack
@skipIfUnsupportedMinOpsetVersion(11)
def test_det(self):
class Det(torch.nn.Module):
def forward(self, x):
return torch.linalg.det(x)
x = torch.randn(2, 3, 5, 5)
self.run_test(Det(), x)
# This test checks output scalar type in the ONNX graph should not be null
# https://github.com/pytorch/pytorch/issues/28607
@skipIfUnsupportedMinOpsetVersion(10)
def test_trace_script(self):
@torch.jit.script
def center_slice_helper(input, h_offset):
return input[:, h_offset:]
class CenterCrop(torch.nn.Module):
def forward(self, input):
return center_slice_helper(input, torch.tensor(input.shape[1] - 1))
x = torch.randn(3, 4)
self.run_test(CenterCrop(), x)
@skipIfNoLapack
@skipIfUnsupportedMinOpsetVersion(11)
def test_logdet(self):
class LogDet(torch.nn.Module):
def forward(self, x):
return torch.logdet(x)
x = torch.randn(2, 3, 5, 5)
self.run_test(LogDet(), x)
def test_dim(self):
class DimModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
out = input * 2
out *= out.dim()
return out
empty_input = torch.randn(0, requires_grad=True)
multi_dim_input = torch.randn(1, 2, 3, requires_grad=True)
self.run_test(DimModel(), empty_input)
self.run_test(DimModel(), multi_dim_input)
@skipIfUnsupportedMinOpsetVersion(11)
def test_dim_1(self):
class M(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, poses):
boxes = torch.zeros([poses.shape[0], 2, 4])
batch_boxes = []
for kp_boxes in boxes:
kp_boxes = torchvision.ops.clip_boxes_to_image(kp_boxes, (2, 3))
batch_boxes.append(kp_boxes)
return batch_boxes
dummy_inputs = torch.rand(2, 2, 3)
self.run_test(M(), (dummy_inputs, ), input_names=['x'], dynamic_axes={"x": [0]})
@skipIfUnsupportedMinOpsetVersion(12)
def test_outer(self):
class Outer(torch.nn.Module):
def forward(self, x, y):
return torch.outer(x, y)
x = torch.arange(1, 5)
y = torch.arange(1, 4)
self.run_test(Outer(), input=(x, y))
x = torch.arange(1, 6).to(dtype=torch.float32)
y = torch.arange(1, 4).to(dtype=torch.long)
self.run_test(Outer(), input=(x, y))
x = torch.arange(2, 5).to(dtype=torch.float32)
y = torch.arange(2, 4).to(dtype=torch.float64)
self.run_test(Outer(), input=(x, y))
x = torch.arange(3, 6).to(dtype=torch.int32)
y = torch.arange(4, 7).to(dtype=torch.long)
self.run_test(Outer(), input=(x, y))
@skipIfUnsupportedMinOpsetVersion(12)
def test_einsum(self):
class EinsumModelBatchDiagonal(torch.nn.Module):
def forward(self, x):
eqn = "...ii ->...i"
return torch.einsum(eqn, x)
x = torch.randn(3, 5, 5)
self.run_test(EinsumModelBatchDiagonal(), input=(x,))
class EinsumModelBatchMatmul(torch.nn.Module):
def forward(self, x, y):
eqn = "bij, bjk -> bik"
return torch.einsum(eqn, x, y)
x = torch.randn(5, 2, 3)
y = torch.randn(5, 3, 4)
self.run_test(EinsumModelBatchMatmul(), input=(x, y))
class EinsumModelInnerProd(torch.nn.Module):
def forward(self, x, y):
eqn = "i,i"
return torch.einsum(eqn, x, y)
x = torch.randn(5)
y = torch.randn(5)
self.run_test(EinsumModelInnerProd(), input=(x, y))
class EinsumModelTranspose(torch.nn.Module):
def forward(self, x):
eqn = "ij->ji"
return torch.einsum(eqn, x)
x = torch.randn(3, 4)
self.run_test(EinsumModelTranspose(), input=(x,))
@skipIfUnsupportedMinOpsetVersion(12)
def test_crossentropyloss(self):
for ignore_index in [-100, 1]:
x = torch.randn(3, 5)
y = torch.empty(3, dtype=torch.long).random_(5)
y[y == 1] = ignore_index
self._crossentropyloss(x, y, ignore_index)
x = torch.randn(3, 5, 2)
y = torch.empty(3, 2, dtype=torch.long).random_(5)
y[y == 1] = ignore_index
self._crossentropyloss(x, y, ignore_index)
x = torch.randn(3, 5, 2, 7)
y = torch.empty(3, 2, 7, dtype=torch.long).random_(5)
y[y == 1] = ignore_index
self._crossentropyloss(x, y, ignore_index)
def _crossentropyloss(self, x, y, ignore_index):
class CrossEntropyLossNone(torch.nn.Module):
def __init__(self, ignore_index):
super(CrossEntropyLossNone, self).__init__()
if ignore_index == -100:
self.loss = torch.nn.CrossEntropyLoss(reduction="none")
else:
self.loss = torch.nn.CrossEntropyLoss(reduction="none", ignore_index=ignore_index)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(CrossEntropyLossNone(ignore_index), input=(x, y))
class CrossEntropyLossNoneWeight(torch.nn.Module):
def __init__(self, ignore_index):
super(CrossEntropyLossNoneWeight, self).__init__()
if ignore_index == -100:
self.loss = torch.nn.CrossEntropyLoss(reduction="none", weight=torch.randn(5))
else:
self.loss = torch.nn.CrossEntropyLoss(reduction="none", weight=torch.randn(5), ignore_index=ignore_index)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(CrossEntropyLossNoneWeight(ignore_index), input=(x, y))
class CrossEntropyLossSum(torch.nn.Module):
def __init__(self, ignore_index):
super(CrossEntropyLossSum, self).__init__()
if ignore_index == -100:
self.loss = torch.nn.CrossEntropyLoss(reduction="sum")
else:
self.loss = torch.nn.CrossEntropyLoss(reduction="sum", ignore_index=ignore_index)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(CrossEntropyLossSum(ignore_index), input=(x, y))
class CrossEntropyLossSumWeight(torch.nn.Module):
def __init__(self, ignore_index):
super(CrossEntropyLossSumWeight, self).__init__()
if ignore_index == -100:
self.loss = torch.nn.CrossEntropyLoss(reduction="sum", weight=torch.randn(5))
else:
self.loss = torch.nn.CrossEntropyLoss(reduction="sum", weight=torch.randn(5), ignore_index=ignore_index)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(CrossEntropyLossSumWeight(ignore_index), input=(x, y))
class CrossEntropyLossMean(torch.nn.Module):
def __init__(self, ignore_index):
super(CrossEntropyLossMean, self).__init__()
if ignore_index == -100:
self.loss = torch.nn.CrossEntropyLoss()
else:
self.loss = torch.nn.CrossEntropyLoss(ignore_index=ignore_index)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(CrossEntropyLossMean(ignore_index), input=(x, y))
class CrossEntropyLossMeanWeight(torch.nn.Module):
def __init__(self, ignore_index):
super(CrossEntropyLossMeanWeight, self).__init__()
if ignore_index == -100:
self.loss = torch.nn.CrossEntropyLoss(weight=torch.randn(5))
else:
self.loss = torch.nn.CrossEntropyLoss(weight=torch.randn(5), ignore_index=ignore_index)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(CrossEntropyLossMeanWeight(ignore_index), input=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_kldiv_loss(self):
x = torch.randn(5)
y = torch.randn(5)
self._kldiv_loss(x, y)
x = torch.randn(2, 3, 5)
y = torch.randn(2, 3, 5)
self._kldiv_loss(x, y)
x = torch.randn(2, 3, 5, 7)
y = torch.randn(2, 3, 5, 7)
self._kldiv_loss(x, y)
def _kldiv_loss(self, x, y):
class KLDivLossNone(torch.nn.Module):
def __init__(self):
super(KLDivLossNone, self).__init__()
self.loss = torch.nn.KLDivLoss(reduction="none", log_target=True)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(KLDivLossNone(), input=(x, y))
class KLDivLossMean(torch.nn.Module):
def __init__(self):
super(KLDivLossMean, self).__init__()
self.loss = torch.nn.KLDivLoss(reduction="mean", log_target=False)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(KLDivLossMean(), input=(x, y))
class KLDivLossSum(torch.nn.Module):
def __init__(self):
super(KLDivLossSum, self).__init__()
self.loss = torch.nn.KLDivLoss(reduction="sum", log_target=True)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(KLDivLossSum(), input=(x, y))
class KLDivLossBatchMean(torch.nn.Module):
def __init__(self):
super(KLDivLossBatchMean, self).__init__()
self.loss = torch.nn.KLDivLoss(reduction="batchmean", log_target=False)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(KLDivLossBatchMean(), input=(x, y))
class KLDivLossMiniBatchMean(torch.nn.Module):
def __init__(self):
super(KLDivLossMiniBatchMean, self).__init__()
self.loss = torch.nn.KLDivLoss(reduction="batchmean", size_average=False, log_target=True)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(KLDivLossMiniBatchMean(), input=(x, y))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss(self):
class NLLModel(torch.nn.Module):
def __init__(self):
super(NLLModel, self).__init__()
self.loss = torch.nn.NLLLoss(reduction="none")
self.m = torch.nn.LogSoftmax(dim=1)
def forward(self, input, target):
output = self.loss(self.m(2 * input), target)
return output
N, C = 5, 4
input = torch.randn(N, 16)
target = torch.empty(N, dtype=torch.long).random_(0, C)
# using test data containing default ignore_index=-100
target[target == 1] = -100
self.run_test(NLLModel(), (input, target))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss_2d_none(self):
class NLLModel(torch.nn.Module):
def __init__(self):
super(NLLModel, self).__init__()
self.loss = torch.nn.NLLLoss(reduction="none")
self.conv = torch.nn.Conv2d(16, C, (3, 3))
self.m = torch.nn.LogSoftmax(dim=1)
def forward(self, input, target):
output = self.loss(self.m(self.conv(input)), target)
return output
N, C = 5, 4
input = torch.randn(N, 16, 10, 10)
target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C)
# using test data containing default ignore_index=-100
target[target == 1] = -100
self.run_test(NLLModel(), (input, target))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss_2d_mean(self):
class NLLModel(torch.nn.Module):
def __init__(self):
super(NLLModel, self).__init__()
self.loss = torch.nn.NLLLoss(reduction="mean")
self.conv = torch.nn.Conv2d(16, C, (3, 3))
self.m = torch.nn.LogSoftmax(dim=1)
def forward(self, input, target):
output = self.loss(self.m(self.conv(input)), target)
return output
N, C = 5, 4
input = torch.randn(N, 16, 10, 10)
target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C)
# using test data containing default ignore_index=-100
target[target == 1] = -100
self.run_test(NLLModel(), (input, target))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss_2d_sum(self):
class NLLModel(torch.nn.Module):
def __init__(self):
super(NLLModel, self).__init__()
self.loss = torch.nn.NLLLoss(reduction="sum")
self.conv = torch.nn.Conv2d(16, C, (3, 3))
self.m = torch.nn.LogSoftmax(dim=1)
def forward(self, input, target):
output = self.loss(self.m(self.conv(input)), target)
return output
N, C = 5, 4
input = torch.randn(N, 16, 10, 10)
target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C)
# using test data containing default ignore_index=-100
target[target == 1] = -100
self.run_test(NLLModel(), (input, target))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss_2d_mean_weights(self):
class NLLModel(torch.nn.Module):
def __init__(self):
super(NLLModel, self).__init__()
self.loss = torch.nn.NLLLoss(reduction="mean", weight=torch.randn(C))
self.conv = torch.nn.Conv2d(16, C, (3, 3))
self.m = torch.nn.LogSoftmax(dim=1)
def forward(self, input, target):
output = self.loss(self.m(self.conv(input)), target)
return output
N, C = 5, 4
input = torch.randn(N, 16, 10, 10)
target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C)
# using test data containing default ignore_index=-100
target[target == 1] = -100
self.run_test(NLLModel(), (input, target))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss_2d_mean_ignore_index(self):
class NLLModel(torch.nn.Module):
def __init__(self):
super(NLLModel, self).__init__()
self.loss = torch.nn.NLLLoss(reduction="mean", ignore_index=1)
self.conv = torch.nn.Conv2d(16, C, (3, 3))
self.m = torch.nn.LogSoftmax(dim=1)
def forward(self, input, target):
output = self.loss(self.m(self.conv(input)), target)
return output
N, C = 5, 4
input = torch.randn(N, 16, 10, 10)
target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C)
self.run_test(NLLModel(), (input, target))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss_dynamic_ignore_index(self):
import torch.nn.functional as F
def linear_combination(x, y, epsilon):
return epsilon * x + (1 - epsilon) * y
def reduce_loss(loss, reduction='mean'):
return loss.mean() if reduction == 'mean' else loss.sum() if reduction == 'sum' else loss
class LabelSmoothingCrossEntropy(torch.nn.Module):
def __init__(self, epsilon: float = 0.1, reduction='mean'):
super().__init__()
self.epsilon = epsilon
self.reduction = reduction
def forward(self, preds, target, start_position):
n = preds.size()[-1]
log_preds = F.log_softmax(preds, dim=-1)
ignore_index = start_position.size(1)
nll = F.nll_loss(log_preds, target, reduction=self.reduction, ignore_index=ignore_index)
return nll + start_position.float()
N = 5
preds = torch.randn(N, 16)
target = torch.randint(5, (N,))
start_position = torch.randint(10, (N, N))
self.run_test(LabelSmoothingCrossEntropy(), (preds, target, start_position))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss_2d_mean_ignore_index_weights(self):
class NLLModel(torch.nn.Module):
def __init__(self):
super(NLLModel, self).__init__()
self.loss = torch.nn.NLLLoss(reduction="mean", weight=torch.randn(C), ignore_index=1)
self.conv = torch.nn.Conv2d(16, C, (3, 3))
self.m = torch.nn.LogSoftmax(dim=1)
def forward(self, input, target):
output = self.loss(self.m(self.conv(input)), target)
return output
N, C = 5, 4
input = torch.randn(N, 16, 10, 10)
target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C)
self.run_test(NLLModel(), (input, target))
@skipIfUnsupportedMinOpsetVersion(12)
def test_binary_cross_entropy_with_logits(self):
x = torch.randn(5)
y = torch.empty(5).random_(2)
self._bce_logits(x, y)
x = torch.randn(3, 4)
y = torch.empty(3, 4).random_(2)
weight = torch.tensor([3])
self._bce_logits_wegiht(x, y, weight)
x = torch.randn(3, 2, 4)
y = torch.empty(3, 2, 4).random_(2)
pos_weight = torch.empty([2, 4]).random_(2)
self._bce_logits_posweight(x, y, pos_weight)
x = torch.randn(3, 3, 4)
y = torch.empty(3, 3, 4).random_(2)
weight = torch.tensor([3])
pos_weight = torch.empty([3, 4]).random_(2)
self._bce_logits_loss_weight_posweight(x, y, weight, pos_weight)
def _bce_logits(self, x, y):
class BCEWithLogitsLossNone(torch.nn.Module):
def forward(self, input, target):
return torch.nn.functional.binary_cross_entropy_with_logits(input, target, reduction="none")
self.run_test(BCEWithLogitsLossNone(), input=(x, y))
class BCEWithLogitsLossMean(torch.nn.Module):
def forward(self, input, target):
return torch.nn.functional.binary_cross_entropy_with_logits(input, target, reduction="mean")
self.run_test(BCEWithLogitsLossMean(), input=(x, y))
class BCEWithLogitsLossSum(torch.nn.Module):
def forward(self, input, target):
return torch.nn.functional.binary_cross_entropy_with_logits(input, target, reduction="sum")
self.run_test(BCEWithLogitsLossSum(), input=(x, y))
def _bce_logits_wegiht(self, x, y, weight):
class BCEWithLogitsLossWegihtNone(torch.nn.Module):
def forward(self, input, target, weight):
return torch.nn.functional.binary_cross_entropy_with_logits(input, target, weight=weight, reduction="none")
self.run_test(BCEWithLogitsLossWegihtNone(), input=(x, y, weight))
class BCEWithLogitsLossWegihtMean(torch.nn.Module):
def forward(self, input, target, weight):
return torch.nn.functional.binary_cross_entropy_with_logits(input, target, weight=weight, reduction="mean")
self.run_test(BCEWithLogitsLossWegihtMean(), input=(x, y, weight))
class BCEWithLogitsLossWegihtSum(torch.nn.Module):
def forward(self, input, target, weight):
return torch.nn.functional.binary_cross_entropy_with_logits(input, target, weight=weight, reduction="sum")
self.run_test(BCEWithLogitsLossWegihtSum(), input=(x, y, weight))
def _bce_logits_posweight(self, x, y, pos_weight):
class BCEWithLogitsLossPosWegihtNone(torch.nn.Module):
def forward(self, input, target, pos_weight):
return torch.nn.functional.binary_cross_entropy_with_logits(input, target, pos_weight=pos_weight, reduction="none")
self.run_test(BCEWithLogitsLossPosWegihtNone(), input=(x, y, pos_weight))
class BCEWithLogitsLossPosWegihtMean(torch.nn.Module):
def forward(self, input, target, pos_weight):
return torch.nn.functional.binary_cross_entropy_with_logits(input, target, pos_weight=pos_weight, reduction="mean")
self.run_test(BCEWithLogitsLossPosWegihtMean(), input=(x, y, pos_weight))
class BCEWithLogitsLossPosWegihtSum(torch.nn.Module):
def forward(self, input, target, pos_weight):
return torch.nn.functional.binary_cross_entropy_with_logits(input, target, pos_weight=pos_weight, reduction="sum")
self.run_test(BCEWithLogitsLossPosWegihtSum(), input=(x, y, pos_weight))
def _bce_logits_loss_weight_posweight(self, x, y, weight, pos_weight):
class BCEWithLogitsLossWeightPosweightNone(torch.nn.Module):
def forward(self, input, target, weight, pos_weight):
return torch.nn.functional.binary_cross_entropy_with_logits(input, target, weight=weight,
pos_weight=pos_weight, reduction="none")
self.run_test(BCEWithLogitsLossWeightPosweightNone(), input=(x, y, weight, pos_weight))
class BCEWithLogitsLossWeightPosweightMean(torch.nn.Module):
def forward(self, input, target, weight, pos_weight):
return torch.nn.functional.binary_cross_entropy_with_logits(input, target, weight=weight,
pos_weight=pos_weight, reduction="mean")
self.run_test(BCEWithLogitsLossWeightPosweightMean(), input=(x, y, weight, pos_weight))
class BCEWithLogitsLossWeightPosweightSum(torch.nn.Module):
def forward(self, input, target, weight, pos_weight):
return torch.nn.functional.binary_cross_entropy_with_logits(input, target, weight=weight,
pos_weight=pos_weight, reduction="sum")
self.run_test(BCEWithLogitsLossWeightPosweightSum(), input=(x, y, weight, pos_weight))
def test_torch_mm(self):
class M(torch.nn.Module):
def forward(self, mat1, mat2):
mm = torch.mm(mat1, mat2)
return mm
mat1 = torch.randn(2, 3)
mat2 = torch.randn(3, 3)
self.run_test(M(), input=(mat1, mat2))
@skipIfUnsupportedMinOpsetVersion(9) # Because where op is not supported for opset < 9.
def test_where_with_bool_tensor(self):
class M(torch.nn.Module):
def forward(self, mat1, mat2):
out = torch.where(mat1 > 0, mat1, mat2)
return out
mat1 = torch.randn(2, 3)
mat2 = torch.ones(2, 3)
self.run_test(M(), input=(mat1, mat2))
@skipIfUnsupportedMinOpsetVersion(9) # Because where op is not supported for opset < 9.
def test_where_with_byte_tensor(self):
class M(torch.nn.Module):
def forward(self, cond, mat1, mat2):
out = torch.where(cond, mat1, mat2)
return out
cond = torch.ones(2, 3, dtype=torch.uint8)
cond[1, 2] = 0
mat1 = torch.randn(2, 3)
mat2 = torch.ones(2, 3)
self.run_test(M(), input=(cond, mat1, mat2))
@skipIfUnsupportedMinOpsetVersion(10) # ONNX IsInf op is added in opset 10.
def test_isinf(self):
class M(torch.nn.Module):
def forward(self, x):
return x.isinf()
x = torch.tensor([[1, 2, float("inf")], [2, float("nan"), float("inf")]])
self.run_test(M(), (x, ))
@skipIfUnsupportedMinOpsetVersion(9) # ONNX IsNaN op is added in opset 9.
def test_isnan(self):
class M(torch.nn.Module):
def forward(self, x):
return x.isnan()
x = torch.tensor([[1, 2, float("inf")], [2, float("nan"), float("inf")]])
self.run_test(M(), (x, ))
@skipIfUnsupportedMinOpsetVersion(9)
def test_any(self):
class M(torch.nn.Module):
def forward(self, x):
return x.any()
x = torch.tensor([[True, False], [False, False]])
self.run_test(M(), (x, ))
@skipIfUnsupportedMinOpsetVersion(9)
def test_all(self):
class M(torch.nn.Module):
def forward(self, x):
return x.all()
x = torch.tensor([[True, False], [False, False]])
self.run_test(M(), (x, ))
def test_dropout(self):
class M(torch.nn.Module):
def __init__(self):
super(M, self).__init__()
self.dropout = torch.nn.Dropout(0.3)
def forward(self, x):
dropout = self.dropout(x)
return dropout
x = torch.randn(10, 3, 53)
self.run_test(M(), (x))
def test_shape_constant_fold(self):
class ShapeModule(torch.nn.Module):
def __init__(self):
super(ShapeModule, self).__init__()
self.register_buffer("weight", torch.ones(5))
def forward(self, x):
shape = self.weight.shape[0]
return x + shape
x = torch.randn(2, 5)
self.run_test(ShapeModule(), (x,), rtol=1e-3, atol=1e-5)
@skipIfUnsupportedMinOpsetVersion(12)
def test_celu(self):
class Celu(torch.nn.Module):
def __init__(self):
super(Celu, self).__init__()
self.celu = torch.nn.CELU(alpha=1.0)
def forward(self, input):
return self.celu(input)
input = torch.randn(2)
self.run_test(Celu(), (input,))
@skipIfUnsupportedMinOpsetVersion(12)
def test_celu_default(self):
class Celu(torch.nn.Module):
def __init__(self):
super(Celu, self).__init__()
self.celu = torch.nn.CELU()
def forward(self, input):
return self.celu(input)
input = torch.randn(2)
self.run_test(Celu(), (input,))
@skipIfUnsupportedMinOpsetVersion(12)
def test_celu_alpha(self):
class Celu(torch.nn.Module):
def __init__(self):
super(Celu, self).__init__()
self.celu = torch.nn.CELU(alpha=2.)
def forward(self, input):
return self.celu(input)
input = torch.randn(2)
self.run_test(Celu(), (input,))
@skipIfUnsupportedMinOpsetVersion(12)
def test_celu_cast(self):
class Celu(torch.nn.Module):
def __init__(self):
super(Celu, self).__init__()
self.celu = torch.nn.CELU()
def forward(self, input):
return self.celu(input)
input = torch.randn(2, 5, 7, dtype=torch.float64)
self.run_test(Celu(), (input,))
def test_lower_tuple(self):
class TupleModule(torch.nn.Module):
def forward(self, input1, input2, input3):
# type: (Tensor, Tensor, Tensor) -> Tensor
a = (input1, input2)
b = a
c = (input1, input2, input3)
for i in range(5):
d = a[0]
for j in range(2):
e, f = a
a = (d, f)
f = c[2]
if f.size(0) != input1.size(-1):
g = b[1]
b = (g, f)
else:
k = c[1:]
b = (f, k[0])
m, n = b
c = (input1, n, m)
p, q, r = c
return p + q + r
input1 = torch.randn(2)
input2 = torch.randn(2)
input3 = torch.randn(2)
self.run_test(TupleModule(), (input1, input2, input3))
def test_lower_tuple_2(self):
class TupleModule(torch.nn.Module):
def forward(self, input1, input2):
# type: (Tensor, Tensor) -> Tuple[Tensor, Tensor]
a = (input1, input2)
for x in range(5):
c, d = a
a = (c, d)
return a
input1 = torch.randn(2)
input2 = torch.randn(2)
self.run_test(TupleModule(), (input1, input2))
def test_lower_tuple_3(self):
class TupleModule(torch.nn.Module):
def forward(self, input1, input2):
# type: (Tuple[Tensor, Tensor], Tuple[Tensor, Tensor])
a = input1
b = input2
for x in range(5):
c, d = a
e, f = b
if c.shape[0] == e.shape[0]:
e = e + c
else:
f = f + d
a = (e, f)
b = (c, d)
return a , b
input1 = (torch.randn(2), torch.randn(2))
input2 = (torch.randn(2), torch.randn(2))
self.run_test(TupleModule(), (input1, input2))
@skipIfUnsupportedMinOpsetVersion(9)
def test_where(self):
class Model(torch.nn.Module):
def forward(self, cond, input, other):
return torch.where(cond, input, other)
x = torch.randint(0, 1, (2, 3, 4), dtype=torch.bool)
y = torch.randn(2, 1, 4)
z = torch.ones(2, 3, 1)
self.run_test(Model(), (x, y, z))
@skipIfUnsupportedMinOpsetVersion(9)
@disableScriptTest() # scripting tests run for opsets > 11. See: test_where_condition_script
def test_where_condition(self):
class Model1(torch.nn.Module):
def forward(self, input):
return torch.stack(torch.where(input > 0.5), dim=1)
x = torch.randint(0, 2, (2, 3, 4), dtype=bool)
self.run_test(Model1(), (x))
class Model2(torch.nn.Module):
def forward(self, input, other):
return torch.stack(torch.where(input > other), dim=1)
x = torch.randint(0, 1, (2, 3, 4), dtype=bool)
y = torch.randint(1, 2, (2, 3, 4), dtype=bool)
self.run_test(Model2(), (x, y))
@skipIfUnsupportedOpsetVersion([13])
@skipIfUnsupportedMinOpsetVersion(11)
def test_where_condition_script(self):
class Model1(torch.nn.Module):
def forward(self, input):
return torch.stack(torch.where(input > 0.5), dim=1)
x = torch.randint(0, 2, (2, 3, 4), dtype=bool)
self.run_test(Model1(), (x))
class Model2(torch.nn.Module):
def forward(self, input, other):
return torch.stack(torch.where(input > other), dim=1)
x = torch.randint(0, 1, (2, 3, 4), dtype=bool)
y = torch.randint(1, 2, (2, 3, 4), dtype=bool)
self.run_test(Model2(), (x, y))
def test_empty_branch(self):
class EmptyBranchModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
out = input + 1
if out.dim() > 2:
if out.dim() > 3:
out += 3
else:
pass
else:
pass
return out
x = torch.randn(1, 2, 3, requires_grad=True)
self.run_test(EmptyBranchModel(), x)
@disableScriptTest()
def test_derive_index(self):
class MyModule(torch.nn.Module):
def forward(self, x: torch.Tensor):
j = []
for idx in range(len(x) - 1, -len(x), -2):
y = x[idx]
j += [x * y]
return j
x = torch.randn(5, 13)
self.run_test(MyModule(), x)
class MyModule(torch.nn.Module):
def forward(self, x: torch.Tensor):
j = []
for idx in range(-len(x), len(x) - 1, 2):
y = x[idx]
j += [x * y]
return j
x = torch.randn(5, 13)
self.run_test(MyModule(), x)
class MyModule(torch.nn.Module):
def forward(self, x: torch.Tensor):
j = []
for idx in range(len(x) - 1, -len(x), -3):
y = x[idx]
j += [x * y]
return j
self.run_test(MyModule(), x)
class MyModule(torch.nn.Module):
def forward(self, x: torch.Tensor):
j = []
for idx in range(-len(x), len(x) - 1, 3):
y = x[idx]
j += [x * y]
return j
self.run_test(MyModule(), x)
@skipIfONNXShapeInference(False)
@skipIfUnsupportedMinOpsetVersion(11)
def test_if_transpose(self):
class IfModel(torch.nn.Module):
def forward(self, x):
x = x.transpose(0, 1)
if x.size(0) == 2:
return x.transpose(0, 1)
else:
return x
x = torch.randn(2, 3)
self.run_test(torch.jit.script(IfModel()), x,
output_names=["output_1"],
dynamic_axes={"output_1": [0, 1]})
@skipIfONNXShapeInference(False)
@skipIfUnsupportedMinOpsetVersion(13)
def test_if_list(self):
class IfModel(torch.nn.Module):
def forward(self, x, y, cond):
res = []
if cond:
res = res + [x]
else:
res = res + [y]
return res
x = torch.randn(2, 3)
y = torch.randn(3, 3)
cond = torch.tensor(1, dtype=torch.bool)
self.run_test(torch.jit.script(IfModel()), (x, y, cond))
@skipIfUnsupportedMinOpsetVersion(13)
def test_if_view(self):
class IfModel(torch.nn.Module):
def forward(self, x, y, cond):
bs, seq = y.shape[:2]
if cond:
res = x.view(bs, seq, -1)
else:
res = y
return res.transpose(1, 2)
x = torch.randn(2, 16, 2, 2)
y = torch.randn(2, 16, 8)
cond = torch.tensor(1, dtype=torch.bool)
self.run_test(torch.jit.script(IfModel()), (x, y, cond),
output_names=["output_1"],
dynamic_axes={"output_1": [1]})
def test_onnx_proto_checker(self):
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, x):
return 2 * x
x = torch.randn(1, 2, 3, requires_grad=True)
f = io.BytesIO()
torch.onnx._export(Model(), x, f)
model = onnx.load(f)
model.ir_version = 0
def check_proto():
torch._C._check_onnx_proto(model.SerializeToString())
self.assertRaises(RuntimeError, check_proto)
@disableScriptTest() # dtype mismatch
def test_split_tensor_scalar(self):
class SplitModel(torch.nn.Module):
def forward(self, x):
return torch.split(x, x.size(1))
x = torch.randn(1, 2, 3, requires_grad=True)
self.run_test(SplitModel(), x)
def test_split_tensor_multi(self):
class SplitModel(torch.nn.Module):
def forward(self, x):
return torch.split(x, torch.ones(3))
x = torch.randn(1, 2, 3, requires_grad=True)
def run_model():
SplitModel(x)
self.assertRaises(TypeError, run_model)
@skipIfUnsupportedMinOpsetVersion(9)
def test_embedding(self):
class EmbedModel(torch.nn.Module):
def forward(self, input, emb):
return torch.nn.functional.embedding(input, emb, padding_idx=1)
model = EmbedModel()
x = torch.randint(4, (4,))
x[2] = x[0] = 1
embedding_matrix = torch.rand(10, 3)
self.run_test(model, (x, embedding_matrix))
x = torch.randint(4, (4, 3, 2))
x[2] = 1
x[0][1] = 1
self.run_test(model, (x, embedding_matrix))
self.run_test(model, (x, embedding_matrix), training=torch.onnx.TrainingMode.TRAINING)
class EmbedModelWithoutPaddingIdx(torch.nn.Module):
def forward(self, input, emb):
return torch.nn.functional.embedding(input, emb)
model = EmbedModelWithoutPaddingIdx()
x = torch.randint(4, (4, 3, 2))
self.run_test(model, (x, embedding_matrix))
@skipIfUnsupportedMinOpsetVersion(9)
def test_embedding_module(self):
class EmbedModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.emb = torch.nn.Embedding(4, 3, padding_idx=1)
self.emb2 = torch.nn.Embedding(4, 3, padding_idx=1)
with torch.no_grad():
self.emb2.weight[1] = torch.ones(3)
def forward(self, input):
return self.emb(input), self.emb2(input)
model = EmbedModel()
x = torch.randint(4, (4,))
x[2] = x[0] = 1
self.run_test(model, (x,))
x = torch.randint(4, (4, 3, 2))
x[2] = 1
x[0][1] = 1
self.run_test(model, (x,))
class EmbedModelWithoutPaddingIdx(torch.nn.Module):
def __init__(self):
super().__init__()
self.emb = torch.nn.Embedding(4, 3)
def forward(self, input):
return self.emb(input)
model = EmbedModelWithoutPaddingIdx()
x = torch.randint(4, (4, 3, 2))
self.run_test(model, (x,))
def _dispatch_rnn_test(self, name, *args, **kwargs):
if name == "elman":
self._elman_rnn_test(*args, **kwargs)
if name == "lstm":
self._lstm_test(*args, **kwargs)
if name == "gru":
self._gru_test(*args, **kwargs)
def _elman_rnn_test(self, layers, nonlinearity, bidirectional,
initial_state, packed_sequence, dropout):
class ElmanWithStateModel(torch.nn.Module):
def __init__(self, layers, nonlinearity, bidirect, dropout, batch_first):
super(ElmanWithStateModel, self).__init__()
self.batch_first = batch_first
self.inner_model = torch.nn.RNN(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, layers, nonlinearity=nonlinearity,
bidirectional=bidirectional, dropout=dropout, batch_first=batch_first)
def forward(self, input: PackedSequence, hx=None):
return self.inner_model(input, hx)
class ElmanWithoutStateModel(torch.nn.Module):
def __init__(self, layers, nonlinearity, bidirect, dropout, batch_first):
super(ElmanWithoutStateModel, self).__init__()
self.batch_first = batch_first
self.inner_model = torch.nn.RNN(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, layers, nonlinearity=nonlinearity,
bidirectional=bidirectional, dropout=dropout, batch_first=batch_first)
def forward(self, input: PackedSequence):
return self.inner_model(input)
batch_first = packed_sequence == 2
if initial_state:
model = ElmanWithStateModel(layers=layers, bidirect=bidirectional, nonlinearity=nonlinearity,
dropout=dropout, batch_first=batch_first)
if packed_sequence:
model = RnnModelWithPackedSequenceWithState(model, batch_first)
else:
model = ElmanWithStateModel(layers=layers, bidirect=bidirectional,
nonlinearity=nonlinearity, dropout=dropout,
batch_first=batch_first)
if packed_sequence:
model = RnnModelWithPackedSequenceWithoutState(model, batch_first)
def make_input(batch_size):
seq_lengths = np.random.randint(1, RNN_SEQUENCE_LENGTH + 1, size=batch_size)
seq_lengths = list(reversed(sorted(map(int, seq_lengths))))
inputs = [torch.randn(l, RNN_INPUT_SIZE) for l in seq_lengths]
inputs = rnn_utils.pad_sequence(inputs, batch_first=batch_first)
inputs = [inputs]
directions = 2 if bidirectional else 1
if initial_state:
h0 = torch.randn(directions * layers, batch_size, RNN_HIDDEN_SIZE)
inputs.append(h0)
if packed_sequence != 0:
inputs.append(torch.IntTensor(seq_lengths))
if len(inputs) == 1:
input = inputs[0]
else:
input = tuple(inputs)
return input
input = make_input(RNN_BATCH_SIZE)
self.run_test(model, input, batch_size=RNN_BATCH_SIZE)
# test that the model still runs with a different batch size
other_input = make_input(RNN_BATCH_SIZE + 1)
self.run_test(model, other_input, batch_size=RNN_BATCH_SIZE + 1)
def _lstm_test(self, layers, bidirectional, initial_state,
packed_sequence, dropout):
batch_first = packed_sequence == 2
if packed_sequence:
model = LstmFlatteningResultWithSeqLength(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, layers,
bidirectional, dropout, batch_first)
if initial_state:
model = RnnModelWithPackedSequenceWithState(model, batch_first)
else:
model = RnnModelWithPackedSequenceWithoutState(model, batch_first)
else:
model = LstmFlatteningResultWithoutSeqLength(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, layers,
bidirectional, dropout, batch_first)
def make_input(batch_size):
seq_lengths = np.random.randint(1, RNN_SEQUENCE_LENGTH + 1, size=batch_size)
seq_lengths = list(reversed(sorted(map(int, seq_lengths))))
inputs = [torch.randn(l, RNN_INPUT_SIZE) for l in seq_lengths]
inputs = rnn_utils.pad_sequence(inputs, batch_first=batch_first)
inputs = [inputs]
directions = 2 if bidirectional else 1
if initial_state:
h0 = torch.randn(directions * layers, batch_size, RNN_HIDDEN_SIZE)
c0 = torch.randn(directions * layers, batch_size, RNN_HIDDEN_SIZE)
inputs.append((h0, c0))
if packed_sequence != 0:
inputs.append(torch.IntTensor(seq_lengths))
if len(inputs) == 1:
input = inputs[0]
else:
input = tuple(inputs)
return input
input = make_input(RNN_BATCH_SIZE)
self.run_test(model, input, batch_size=RNN_BATCH_SIZE)
# test that the model still runs with a different batch size
other_input = make_input(RNN_BATCH_SIZE + 1)
self.run_test(model, other_input, batch_size=RNN_BATCH_SIZE + 1)
def _gru_test(self, layers, bidirectional, initial_state,
packed_sequence, dropout):
class GRUWithStateModel(torch.nn.Module):
def __init__(self, layers, bidirect, dropout, batch_first):
super(GRUWithStateModel, self).__init__()
self.batch_first = batch_first
self.inner_model = torch.nn.GRU(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, num_layers=layers,
bidirectional=bidirectional, dropout=dropout,
batch_first=batch_first)
def forward(self, input: PackedSequence, hx):
return self.inner_model(input, hx)
class GRUWithoutStateModel(torch.nn.Module):
def __init__(self, layers, bidirect, dropout, batch_first):
super(GRUWithoutStateModel, self).__init__()
self.batch_first = batch_first
self.inner_model = torch.nn.GRU(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, num_layers=layers,
bidirectional=bidirectional, dropout=dropout,
batch_first=batch_first)
def forward(self, input: PackedSequence):
return self.inner_model(input)
class GRUNoSeqLengthWithoutStateModel(torch.nn.Module):
def __init__(self, layers, bidirect, dropout, batch_first):
super(GRUNoSeqLengthWithoutStateModel, self).__init__()
self.batch_first = batch_first
self.inner_model = torch.nn.GRU(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, num_layers=layers,
bidirectional=bidirectional, dropout=dropout,
batch_first=batch_first)
def forward(self, input):
return self.inner_model(input)
class GRUNoSeqLengthWithStateModel(torch.nn.Module):
def __init__(self, layers, bidirect, dropout, batch_first):
super(GRUNoSeqLengthWithStateModel, self).__init__()
self.batch_first = batch_first
self.inner_model = torch.nn.GRU(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, num_layers=layers,
bidirectional=bidirectional, dropout=dropout,
batch_first=batch_first)
def forward(self, input, hx):
return self.inner_model(input, hx)
batch_first = packed_sequence == 2
if packed_sequence:
if initial_state:
model = GRUWithStateModel(layers=layers, bidirect=bidirectional, dropout=dropout,
batch_first=batch_first)
model = RnnModelWithPackedSequenceWithState(model, batch_first)
else:
model = GRUWithoutStateModel(layers=layers, bidirect=bidirectional, dropout=dropout,
batch_first=batch_first)
model = RnnModelWithPackedSequenceWithoutState(model, batch_first)
else:
if initial_state:
model = GRUNoSeqLengthWithStateModel(layers=layers, bidirect=bidirectional,
dropout=dropout, batch_first=batch_first)
else:
model = GRUNoSeqLengthWithoutStateModel(layers=layers, bidirect=bidirectional,
dropout=dropout, batch_first=batch_first)
def make_input(batch_size):
seq_lengths = np.random.randint(1, RNN_SEQUENCE_LENGTH + 1, size=batch_size)
seq_lengths = list(reversed(sorted(map(int, seq_lengths))))
inputs = [torch.randn(l, RNN_INPUT_SIZE) for l in seq_lengths]
inputs = rnn_utils.pad_sequence(inputs, batch_first=batch_first)
inputs = [inputs]
directions = 2 if bidirectional else 1
if initial_state:
h0 = torch.randn(directions * layers, batch_size, RNN_HIDDEN_SIZE)
inputs.append(h0)
if packed_sequence != 0:
inputs.append(torch.IntTensor(seq_lengths))
if len(inputs) == 1:
input = inputs[0]
else:
input = tuple(inputs)
return input
input = make_input(RNN_BATCH_SIZE)
self.run_test(model, input, batch_size=RNN_BATCH_SIZE)
# test that the model still runs with a different batch size
other_input = make_input(RNN_BATCH_SIZE + 1)
self.run_test(model, other_input, batch_size=RNN_BATCH_SIZE + 1)
@disableScriptTest() # TODO: RuntimeError: Exporting the operator __is_ to ONNX is not supported
def test_transformer_encoder(self):
from torch.nn import TransformerEncoderLayer, TransformerEncoder
class MyModule(torch.nn.Module):
def __init__(self, ninp, nhead, nhid, dropout, nlayers):
super(MyModule, self).__init__()
encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout)
self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers)
def forward(self, input):
return self.transformer_encoder(input)
x = torch.rand(10, 32, 512)
self.run_test(MyModule(512, 8, 2048 , 0., 3), (x,), atol=1e-6)
@skipIfUnsupportedMinOpsetVersion(10)
def test_fake_quantize_per_tensor(self):
class FakeQuantizePerTensorModel(torch.nn.Module):
def forward(self, input):
scale = 1. / 127
zero_point = 0
quant_min = -128
quant_max = 127
return torch.fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max)
x = torch.randn(6, 4, 3, 3)
self.run_test(FakeQuantizePerTensorModel(), (x))
@skipIfUnsupportedMinOpsetVersion(13)
def test_fake_quantize_per_channel(self):
class FakeQuantizePerChannelModel(torch.nn.Module):
def forward(self, input):
amax = torch.ones(4)
scale = amax / 127.
zero_point = torch.zeros_like(amax, dtype=torch.int)
# Quantize twice to test differnet branches
y = torch.fake_quantize_per_channel_affine(input, scale, zero_point, 1, 0, 255)
return torch.fake_quantize_per_channel_affine(y, scale, zero_point, 1, -128, 127)
x = torch.randn(6, 4, 3, 3)
self.run_test(FakeQuantizePerChannelModel(), (x))
def test_batchnorm_training(self):
class MyModule(torch.nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.bn1 = torch.nn.BatchNorm2d(3, affine=False)
self.cv1 = torch.nn.Conv2d(3, 3, 10)
self.bn2 = torch.nn.BatchNorm2d(3, affine=True)
self.cv2 = torch.nn.Conv2d(3, 3, 10)
self.bn3 = torch.nn.BatchNorm2d(3, affine=False)
def forward(self, x):
x = self.bn1(x)
x = self.cv1(x)
x = self.bn2(x)
x = self.cv2(x)
x = self.bn3(x)
return x
x = torch.randn(10, 3, 20, 20) * 2
model_export = MyModule()
self.run_test(model_export, (x,), training=torch.onnx.TrainingMode.TRAINING, rtol=1e-3, atol=1e-5)
model_export.train()
self.run_test(model_export, (x, ), training=torch.onnx.TrainingMode.PRESERVE, rtol=1e-3, atol=1e-5)
def test_batchnorm_training_mode_fix_layer(self):
class MyModule(torch.nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.bn1 = torch.nn.BatchNorm2d(3, affine=True)
self.cv1 = torch.nn.Conv2d(3, 3, 10)
self.bn2 = torch.nn.BatchNorm2d(3, affine=False)
self.cv2 = torch.nn.Conv2d(3, 3, 10)
self.bn3 = torch.nn.BatchNorm2d(3, affine=True)
self.bn3.eval()
def forward(self, x):
x = self.bn1(x)
x = self.cv1(x)
x = self.bn2(x)
x = self.cv2(x)
x = self.bn3(x)
return x
x = torch.randn(10, 3, 128, 128)
model_export = MyModule()
self.run_test(model_export, (x,), training=torch.onnx.TrainingMode.TRAINING, rtol=1e-3, atol=1e-5)
model_export.train()
self.run_test(model_export, (x,), training=torch.onnx.TrainingMode.PRESERVE, rtol=1e-3, atol=1e-5)
def test_batchnorm_eval_mode_train_layer(self):
class MyModule(torch.nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.bn1 = torch.nn.BatchNorm2d(3, affine=True)
self.cv1 = torch.nn.Conv2d(3, 3, 10)
self.bn2 = torch.nn.BatchNorm2d(3, affine=False)
self.cv2 = torch.nn.Conv2d(3, 3, 10)
self.bn3 = torch.nn.BatchNorm2d(3, affine=True)
self.bn3.train()
def forward(self, x):
x = self.bn1(x)
x = self.cv1(x)
x = self.bn2(x)
x = self.cv2(x)
x = self.bn3(x)
return x
x = torch.randn(10, 3, 128, 128)
model_export = MyModule()
self.run_test(model_export, (x,), training=torch.onnx.TrainingMode.EVAL, rtol=1e-3, atol=1e-5)
model_export.eval()
self.run_test(model_export, (x,), training=torch.onnx.TrainingMode.PRESERVE, rtol=1e-3, atol=1e-5)
@skipIfUnsupportedMinOpsetVersion(12)
def test_dropout_training(self):
class MyModule(torch.nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.dropout = torch.nn.Dropout(0.4)
def forward(self, x):
dropout = self.dropout(x)
return dropout
model = MyModule()
x = torch.randn(10)
model.train()
ort_sess = convert_to_onnx(model, input=(x,), opset_version=self.opset_version,
training=torch.onnx.TrainingMode.TRAINING)
ort_outs = run_ort(ort_sess, input=(x,))
assert not torch.all(torch.eq(x, torch.from_numpy(ort_outs[0])))
script_model = torch.jit.script(model)
output = model(x)
ort_sess = convert_to_onnx(script_model, input=(x,), opset_version=self.opset_version,
example_outputs=output,
training=torch.onnx.TrainingMode.TRAINING)
ort_outs = run_ort(ort_sess, input=(x,))
assert not torch.all(torch.eq(x, torch.from_numpy(ort_outs[0])))
@skipIfUnsupportedMinOpsetVersion(12)
def test_dropout_training_zero(self):
class MyModule(torch.nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.dropout = torch.nn.Dropout(0.5)
def forward(self, x):
dropout = self.dropout(x)
return dropout
model = MyModule()
# ensure there are no zeros in the input
x = torch.randn(10, 3, 128, 128)
y = x.numpy()
y_mask = np.where(y == 0, 1, y)
input = torch.from_numpy(y_mask)
nb_elements = torch.numel(input)
model.train()
ort_sess = convert_to_onnx(model, input=(x,), opset_version=self.opset_version,
training=torch.onnx.TrainingMode.TRAINING)
ort_outs = run_ort(ort_sess, input=(x,))
y = model(input)
output = y.cpu().numpy()
ort_mask = np.where(ort_outs[0] != 0, 1, 0)
pyt_mask = np.where(output != 0, 1, 0)
ratio_pytorch = np.sum(pyt_mask) / nb_elements
ratio_ort = np.sum(ort_mask) / nb_elements
np.testing.assert_allclose(ratio_pytorch, ratio_ort, rtol=0.01, atol=0.01)
script_model = torch.jit.script(model)
y = model(input)
output = y.cpu().numpy()
ort_sess = convert_to_onnx(script_model, input=(x,), opset_version=self.opset_version,
example_outputs=y,
training=torch.onnx.TrainingMode.TRAINING)
ort_outs = run_ort(ort_sess, input=(x,))
ort_mask = np.where(ort_outs[0] != 0, 1, 0)
pyt_mask = np.where(output != 0, 1, 0)
ratio_pytorch = np.sum(pyt_mask) / nb_elements
ratio_ort = np.sum(ort_mask) / nb_elements
np.testing.assert_allclose(ratio_pytorch, ratio_ort, rtol=0.01, atol=0.01)
def test_conv_bn(self):
class MyModule(torch.nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.conv = torch.nn.Conv2d(3, 16, kernel_size=1, stride=2, padding=3, bias=True)
self.bn = torch.nn.BatchNorm2d(16, affine=True)
def forward(self, x):
x = self.conv(x)
bn = self.bn(x)
return bn
model_export = MyModule()
x = torch.randn(10, 3, 128, 128)
self.run_test(model_export, (x,), training=torch.onnx.TrainingMode.EVAL)
self.run_test(model_export, (x,), training=torch.onnx.TrainingMode.TRAINING, rtol=1e-3, atol=1e-5)
def test_multiple_conv_bn(self):
class MyModule(torch.nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.conv1 = torch.nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.conv2 = torch.nn.Conv2d(64, 2, kernel_size=1, stride=1, padding=0, bias=False)
self.conv3 = torch.nn.Conv2d(2, 2, kernel_size=3, stride=1, padding=1, bias=False)
self.bn = torch.nn.BatchNorm2d(64)
self.bn2 = torch.nn.BatchNorm2d(2)
self.relu = torch.nn.ReLU(inplace=True)
self.maxpool = torch.nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
def forward(self, x):
x = self.conv1(x)
x = self.bn(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu(x)
x = self.conv3(x)
x = self.bn2(x)
x = self.relu(x)
return x
model_export = MyModule()
x = torch.randn(2, 3, 224, 224)
self.run_test(model_export, (x,), training=torch.onnx.TrainingMode.TRAINING, rtol=1e-3, atol=1e-5)
self.run_test(model_export, (x,), training=torch.onnx.TrainingMode.EVAL)
def test_script_custom_class_error(self):
class BoxCoder(object):
def __init__(self, bbox_xform_clip: float):
# type: (float) -> None
self.bbox_xform_clip = bbox_xform_clip
def decode(self, rel_codes, boxes):
# type: (Tensor, List[Tensor]) -> Tensor
boxes = torch.cat(boxes, dim=0)
pred_ctr_x = torch.clamp(rel_codes[:, 0::4], max=self.bbox_xform_clip) * boxes[:, 2]
return pred_ctr_x
class MyModule(torch.nn.Module):
__annotations__ = {
"box_coder": BoxCoder,
}
def __init__(self):
super(MyModule, self).__init__()
self.box_coder = BoxCoder(1.4)
def forward(self, box_regression: torch.Tensor, proposals: List[torch.Tensor]):
return self.box_coder.decode(box_regression, proposals)
model = torch.jit.script(MyModule())
box_regression = torch.randn([4, 4])
proposal = [torch.randn(2, 4), torch.randn(2, 4)]
outputs = model(box_regression, proposal)
with self.assertRaises(RuntimeError) as cm:
convert_to_onnx(model, input=(box_regression, proposal),
example_outputs=outputs)
def test_initializer_sequence(self):
class MyModule(torch.nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(MyModule, self).__init__()
self.fc1 = torch.nn.Linear(input_size, hidden_size)
self.relu = torch.nn.ReLU()
self.fc2 = torch.nn.Linear(hidden_size, num_classes)
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
return out
test_model = MyModule(3, 4, 10)
state_dict_list = [k for (k, v) in test_model.state_dict().items()]
named_params_list = [k for (k, v) in test_model.named_parameters()]
x = torch.randn(32, 3)
f = io.BytesIO()
torch.onnx._export(test_model, (x,), f, _retain_param_name=True, do_constant_folding=False)
loaded_model = onnx.load_from_string(f.getvalue())
actual_list = [p.name for p in loaded_model.graph.initializer]
assert actual_list == state_dict_list, \
"Initializers' sequence is not as same as state_dict(). Expected: (" \
+ ", ".join(state_dict_list) + "). Actual:(" + ", ".join(actual_list) + ")."
assert actual_list == named_params_list, \
"Initializers' sequence is not as same as named_parameters(). Expected: (" \
+ ", ".join(named_params_list) + "). Actual:(" + ", ".join(actual_list) + ")."
def test_initializer_sequence_script_model(self):
def list_is_expected(short_list, long_list) -> bool:
if (len(short_list) > len(long_list)):
return False
for i in range(len(short_list)):
if (short_list[i] not in long_list[i]):
return False
return True
def loop(x, y):
for i in range(int(y)):
x = x + i
return x
class MyModule(torch.nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(MyModule, self).__init__()
self.fc1 = torch.nn.Linear(input_size, hidden_size)
self.relu = torch.nn.ReLU()
self.fc2 = torch.nn.Linear(hidden_size, num_classes)
def forward(self, x, y):
x = loop(x, y)
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
return out
test_model = torch.jit.script(MyModule(3, 4, 10))
state_dict_list = [k for (k, v) in test_model.state_dict().items()]
named_params_list = [k for (k, v) in test_model.named_parameters()]
x = torch.ones(2, 3, dtype=torch.float)
y = torch.tensor(5, dtype=torch.long)
example_output = (test_model(x, y),)
f = io.BytesIO()
torch.onnx.export(test_model, (x, y), f, example_outputs=example_output, _retain_param_name=True, do_constant_folding=False)
loaded_model = onnx.load_from_string(f.getvalue())
actual_list = [p.name for p in loaded_model.graph.initializer]
assert list_is_expected(state_dict_list, actual_list), \
"ScriptModel - Initializers' sequence is not as same as state_dict(). Expected: (" \
+ ", ".join(state_dict_list) + "). Actual:(" + ", ".join(actual_list) + ")."
assert list_is_expected(named_params_list, actual_list), \
"ScriptModel - Initializers' sequence is not as same as named_parameters(). Expected: (" \
+ ", ".join(named_params_list) + "). Actual:(" + ", ".join(actual_list) + ")."
@skipIfUnsupportedMinOpsetVersion(11)
def test_nms(self):
boxes = torch.rand(5, 4)
boxes[:, 2:] += torch.rand(5, 2)
scores = torch.randn(5)
class Module(torch.nn.Module):
def forward(self, boxes, scores):
return ops.nms(boxes, scores, 0.5)
self.run_test(Module(), (boxes, scores))
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest()
def test_clip_boxes_to_image(self):
boxes = torch.randn(5, 4) * 500
boxes[:, 2:] += boxes[:, :2]
size = torch.randn(200, 300)
size_2 = torch.randn(300, 400)
class Module(torch.nn.Module):
def forward(self, boxes, size):
shape = (size.shape[0], size.shape[1])
return ops.boxes.clip_boxes_to_image(boxes, shape)
self.run_test(Module(), (boxes, size),
input_names=["boxes", "size"],
dynamic_axes={"size": [0, 1]},
test_with_inputs=[(boxes, size), (boxes, size_2)])
@skipIfUnsupportedMinOpsetVersion(11)
def test_roi_align(self):
x = torch.rand(1, 1, 10, 10, dtype=torch.float32)
single_roi = torch.tensor([[0, 0, 0, 4, 4]], dtype=torch.float32)
model = ops.RoIAlign((5, 5), 1., 2)
self.run_test(model, (x, single_roi))
@skipIfUnsupportedMinOpsetVersion(11)
def test_roi_align_aligned(self):
x = torch.rand(1, 1, 10, 10, dtype=torch.float32)
single_roi = torch.tensor([[0, 1.5, 1.5, 3, 3]], dtype=torch.float32)
model1 = ops.RoIAlign((5, 5), 1., 2, aligned=True)
self.run_test(model1, (x, single_roi))
x = torch.rand(1, 1, 10, 10, dtype=torch.float32)
single_roi = torch.tensor([[0, 0.2, 0.3, 4.5, 3.5]], dtype=torch.float32)
model2 = ops.RoIAlign((5, 5), 0.5, 3, aligned=True)
self.run_test(model2, (x, single_roi))
x = torch.rand(1, 1, 10, 10, dtype=torch.float32)
single_roi = torch.tensor([[0, 0.2, 0.3, 4.5, 3.5]], dtype=torch.float32)
model3 = ops.RoIAlign((5, 5), 1.8, 2, aligned=True)
self.run_test(model3, (x, single_roi))
x = torch.rand(1, 1, 10, 10, dtype=torch.float32)
single_roi = torch.tensor([[0, 0.2, 0.3, 4.5, 3.5]], dtype=torch.float32)
model4 = ops.RoIAlign((2, 2), 2.5, 0, aligned=True)
self.run_test(model4, (x, single_roi))
@skipIfUnsupportedMinOpsetVersion(11)
def test_roi_pool(self):
x = torch.rand(1, 1, 10, 10, dtype=torch.float32)
rois = torch.tensor([[0, 0, 0, 4, 4]], dtype=torch.float32)
pool_h = 5
pool_w = 5
model = ops.RoIPool((pool_h, pool_w), 2.)
self.run_test(model, (x, rois))
@skipIfUnsupportedMinOpsetVersion(11)
def test_resize_images(self):
class TransformModule(torch.nn.Module):
def __init__(self):
super(TransformModule, self).__init__()
self.transform = _init_test_generalized_rcnn_transform()
def forward(self, images):
return self.transform.resize(images, None)[0]
input = torch.rand(3, 10, 20)
input_test = torch.rand(3, 100, 150)
self.run_test(TransformModule(), (input,),
input_names=["input1"], dynamic_axes={"input1": [0, 1, 2]},
test_with_inputs=[(input,), (input_test,)])
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest()
def test_transform_images(self):
class TransformModule(torch.nn.Module):
def __init__(self):
super(TransformModule, self).__init__()
self.transform = _init_test_generalized_rcnn_transform()
def forward(self, images: List[torch.Tensor]):
return self.transform(images)[0].tensors
input = torch.rand(3, 100, 200), torch.rand(3, 200, 200)
input_test = torch.rand(3, 100, 200), torch.rand(3, 200, 200)
self.run_test(TransformModule(), (input,), test_with_inputs=[(input,), (input_test,)])
def get_features(self, images):
s0, s1 = images.shape[-2:]
features = [
("0", torch.rand(2, 256, s0 // 4, s1 // 4)),
("1", torch.rand(2, 256, s0 // 8, s1 // 8)),
("2", torch.rand(2, 256, s0 // 16, s1 // 16)),
("3", torch.rand(2, 256, s0 // 32, s1 // 32)),
("4", torch.rand(2, 256, s0 // 64, s1 // 64)),
]
features = OrderedDict(features)
return features
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest()
def test_rpn(self):
set_rng_seed(0)
class RPNModule(torch.nn.Module):
def __init__(self):
super(RPNModule, self).__init__()
self.rpn = _init_test_rpn()
def forward(self, images, features: Dict[str, torch.Tensor]):
images_m = ImageList(images, [(i.shape[-1], i.shape[-2]) for i in images])
return self.rpn(images_m, features)
images = torch.rand(2, 3, 150, 150)
features = self.get_features(images)
images2 = torch.rand(2, 3, 80, 80)
test_features = self.get_features(images2)
model = RPNModule()
model.eval()
model(images, features)
self.run_test(model, (images, features),
input_names=["input1", "input2", "input3", "input4", "input5", "input6"],
dynamic_axes={"input1": [0, 1, 2, 3], "input2": [0, 1, 2, 3],
"input3": [0, 1, 2, 3], "input4": [0, 1, 2, 3],
"input5": [0, 1, 2, 3], "input6": [0, 1, 2, 3]},
test_with_inputs=[(images, features), (images2, test_features)],
dict_check=False)
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest()
def test_multi_scale_roi_align(self):
class TransformModule(torch.nn.Module):
def __init__(self):
super(TransformModule, self).__init__()
self.model = ops.MultiScaleRoIAlign(["feat1", "feat2"], 3, 2)
self.image_sizes = [(512, 512)]
def forward(self, input, boxes):
# type: (Dict[str, torch.Tensor], List[torch.Tensor]) -> torch.Tensor
return self.model(input, boxes, self.image_sizes)
i = OrderedDict()
i["feat1"] = torch.rand(1, 5, 64, 64)
i["feat2"] = torch.rand(1, 5, 16, 16)
boxes = torch.rand(6, 4) * 256
boxes[:, 2:] += boxes[:, :2]
i1 = OrderedDict()
i1["feat1"] = torch.rand(1, 5, 64, 64)
i1["feat2"] = torch.rand(1, 5, 16, 16)
boxes1 = torch.rand(6, 4) * 256
boxes1[:, 2:] += boxes1[:, :2]
self.run_test(TransformModule(), (i, [boxes],), test_with_inputs=[(i, [boxes],), (i1, [boxes1],)])
@skipIfUnsupportedMinOpsetVersion(11)
@disableScriptTest()
def test_roi_heads(self):
class RoiHeadsModule(torch.nn.Module):
def __init__(self):
super(RoiHeadsModule, self).__init__()
self.transform = _init_test_generalized_rcnn_transform()
self.rpn = _init_test_rpn()
self.roi_heads = _init_test_roi_heads_faster_rcnn()
def forward(self, images, features: Dict[str, torch.Tensor]):
original_image_sizes = [(img.shape[-1], img.shape[-2]) for img in images]
images_m = ImageList(images, [(i.shape[-1], i.shape[-2]) for i in images])
proposals, _ = self.rpn(images_m, features)
detections, _ = self.roi_heads(features, proposals, images_m.image_sizes)
detections = self.transform.postprocess(detections,
images_m.image_sizes,
original_image_sizes)
return detections
images = torch.rand(2, 3, 100, 100)
features = self.get_features(images)
images2 = torch.rand(2, 3, 150, 150)
test_features = self.get_features(images2)
model = RoiHeadsModule()
model.eval()
model(images, features)
self.run_test(model, (images, features),
input_names=["input1", "input2", "input3", "input4", "input5", "input6"],
dynamic_axes={"input1": [0, 1, 2, 3], "input2": [0, 1, 2, 3], "input3": [0, 1, 2, 3],
"input4": [0, 1, 2, 3], "input5": [0, 1, 2, 3], "input6": [0, 1, 2, 3]},
test_with_inputs=[(images, features), (images2, test_features)],
dict_check=False)
def test_set_(self):
class M(torch.nn.Module):
def forward(self, x, y):
x.set_(y)
return x
x = torch.ones(2, 3)
y = torch.randn(4, 6)
self.run_test(M(), (x, y), remained_onnx_input_idx=[1])
y2 = torch.randn(5, 2)
self.run_test(M(), (x, y), remained_onnx_input_idx=[1], input_names=['x', 'y'],
dynamic_axes={'x': [0, 1], 'y': [0, 1]},
test_with_inputs=[(y, y2)])
@skipIfUnsupportedMinOpsetVersion(9)
def test_set_attr_modules(self):
class InnerModule2(torch.nn.Module):
def __init__(self, embedding_dim):
super().__init__()
self.weights = InnerModule2.get_embedding(embedding_dim)
self.register_buffer("_float_tensor", torch.FloatTensor(1))
self.const = 2
@staticmethod
def get_embedding(embedding_dim: int):
emb = 4 / ((embedding_dim // 2) - 1)
emb = torch.exp(torch.arange((embedding_dim // 2), dtype=torch.float) * -emb)
return emb
def forward(self, input, incremental_state: Optional[torch.Tensor] = None):
bsz, seq_len = input.shape[0], input.shape[1]
self.const = 3
if self.weights is None:
self.weights = InnerModule.get_embedding(self.embedding_dim)
self.weights = self.weights.to(self._float_tensor)
self.weights = self.weights * self.const
if incremental_state is not None:
pos = seq_len
return self.weights[1 + pos, :].expand(bsz, 1, -1)
return (
self.weights.index_select(0, torch.ones((bsz * seq_len), dtype=torch.int64)).view(bsz, seq_len, -1)
)
class InnerModule(torch.nn.Module):
def __init__(self, embedding_dim):
super().__init__()
self.weights = InnerModule.get_embedding(embedding_dim)
self.module = InnerModule2(embedding_dim=8)
@staticmethod
def get_embedding(embedding_dim: int):
emb = 4 / ((embedding_dim // 2) - 1)
emb = torch.exp(torch.arange((embedding_dim // 2), dtype=torch.float) * -emb)
return emb
def forward(self, x):
return self.module(x) + self.weights
class Module(torch.nn.Module):
def __init__(self):
super(Module, self).__init__()
self.module = InnerModule(embedding_dim=8)
def forward(self, x):
return self.module(x)
x = torch.randn(3, 256)
self.run_test(Module(), (x, ), input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(Module(), (x, ), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_set_attr_modules_2(self):
class InnerModule(torch.nn.Module):
def __init__(self, embedding_dim):
super().__init__()
self.embedding_dim = embedding_dim
self.const = 2.5
self.weights = InnerModule.get_embedding(self.embedding_dim)
self.register_buffer("_float_tensor", torch.FloatTensor(1))
@staticmethod
def get_embedding(embedding_dim: int):
emb = 4 / ((embedding_dim // 2) - 1)
emb = torch.exp(torch.arange((embedding_dim // 2), dtype=torch.float) * -emb)
return emb
def forward(self, input, incremental_state: Optional[torch.Tensor] = None):
bsz, seq_len = input.shape[0], input.shape[1]
self.const = 1.5
self.weights = InnerModule.get_embedding(self.embedding_dim)
return (
self.weights.index_select(0, torch.ones((bsz * seq_len), dtype=torch.int64)).view(bsz, seq_len, -1)
) * self.const
class Module(torch.nn.Module):
def __init__(self):
super(Module, self).__init__()
self.module = InnerModule(embedding_dim=8)
def forward(self, x):
return self.module(x)
x = torch.randn(3, 256)
self.run_test(Module(), (x, ), input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(Module(), (x, ), remained_onnx_input_idx=[])
def test_set_attr(self):
class MyModule(torch.nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.conv = torch.nn.Conv1d(3, 10, 2)
self.b = False
def forward(self, box_regression, weight):
self.b = True
self.conv.weight = weight
w = torch.softmax(self.conv.weight, dim=0)
self.conv.weight = w + w
if self.b:
return box_regression + self.conv.weight
else:
return box_regression - self.conv.weight
model = torch.jit.script(MyModule())
weight = torch.ones(3, 2)
box_regression = torch.randn(3, 2)
self.run_test(model, (box_regression, weight))
@skipIfUnsupportedMinOpsetVersion(11)
def test_set_attr_2(self):
class MyModule(torch.nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.conv = torch.nn.Conv1d(10, 3, 3)
self.conv.bias = torch.nn.Parameter(torch.zeros(3, 10, 3))
def set_cell_anchors(self, anchors):
if self.conv.bias is not None:
b = self.conv.bias
assert b is not None
self.conv.bias = anchors + b
elif self.conv.weight is not None:
self.conv.weight = torch.randn(3, 10)
self.conv.bias = self.conv.weight[:]
def forward(self, anchors) -> Optional[torch.Tensor]:
self.set_cell_anchors(anchors)
return self.conv.bias
model = torch.jit.script(MyModule())
anchors = torch.ones(3, 10, 3)
self.run_test(model, (anchors))
@skipIfUnsupportedMinOpsetVersion(11)
def test_set_attr_3(self):
class MyModule(torch.nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.conv = torch.nn.Conv1d(10, 3, 3)
self.conv.weight = torch.nn.Parameter(torch.zeros(3, 10))
self.conv.bias = torch.nn.Parameter(torch.zeros(3, 10, 3))
def set_cell_anchors(self, anchors, boxes):
self.conv.weight = torch.ones(3, 10)
if self.conv.bias is not None:
self.conv.bias = torch.randn(3, 10, 3)
self.conv.weight = anchors + self.conv.weight
boxes[:] = torch.zeros(2, 3)
def forward(self, anchors) -> Tuple[torch.Tensor, torch.Tensor]:
boxes = torch.ones(2, 2, 3)
self.set_cell_anchors(anchors, boxes)
if self.conv.bias is not None:
return self.conv.weight, boxes
return anchors, boxes
model = torch.jit.script(MyModule())
anchors = torch.rand(3, 10)
self.run_test(model, (anchors))
@skipIfUnsupportedMinOpsetVersion(11)
def test_set_attr_4(self):
class MyModule(torch.nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.conv = torch.nn.Conv1d(10, 3, 3)
self.conv.bias = torch.nn.Parameter(torch.zeros(3, 10, 3))
def set_cell_anchors(self, anchors):
self.conv.weight = torch.zeros(10, 3)
if self.conv.bias is not None:
w = self.conv.bias
assert w is not None
self.conv.bias = anchors + w
else:
self.conv.bias = torch.ones(3, 10, 3)
def forward(self, feature_maps, anchors) -> Tuple[torch.Tensor, torch.Tensor]:
self.set_cell_anchors(anchors)
result = []
if self.conv.bias is not None:
a = self.conv.bias
assert a is not None
result += [a]
result += [feature_maps]
return result[0], result[1]
model = torch.jit.script(MyModule())
x = torch.rand(5, 11, 30)
anchors = torch.ones(3, 10, 3)
self.run_test(model, (x, anchors))
@skipIfUnsupportedMinOpsetVersion(11)
def test_set_attr_5(self):
class MyModule(torch.nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.conv = torch.nn.Conv1d(10, 3, 3)
self.conv.bias = torch.nn.Parameter(torch.zeros(3, 10, 3))
def set_cell_anchors(self, anchors):
self.conv.weight = torch.arange(10)
for i in range(10):
if i == 3:
for j in range(10):
w = self.conv.weight
self.conv.weight = torch.arange(10) + w
self.conv.weight = self.conv.weight + torch.arange(10)
# NOTE: `is not None` and `assert` is for passing torchscript.
if self.conv.bias is not None:
a = self.conv.bias
assert a is not None
self.conv.bias = anchors + a
def forward(self, anchors):
self.set_cell_anchors(anchors)
return self.conv.weight, self.conv.bias
model = torch.jit.script(MyModule())
anchors = torch.ones(3, 10, 3)
self.run_test(model, (anchors))
@skipIfUnsupportedMinOpsetVersion(11)
def test_set_attr_in_loop(self):
class MyModule(torch.nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.conv = torch.nn.Conv1d(10, 3, 3)
self.conv.weight = torch.nn.Parameter(torch.zeros(3, 10))
self.conv.bias = torch.nn.Parameter(torch.zeros(3, 10, 3))
def set_cell_anchors(self, anchors, boxes):
self.conv.weight = torch.randn(3, 10)
for i in range(self.conv.weight.size(0)):
for j in range(10):
self.conv.bias = torch.randn(3, 10, 3)
self.conv.weight = anchors * i
boxes[j] += torch.ones(3, 3)
def forward(self, anchors) -> Tuple[torch.Tensor, torch.Tensor]:
boxes = torch.ones(10, 3, 3)
self.set_cell_anchors(anchors, boxes)
if self.conv.bias is not None:
return self.conv.weight, boxes
return anchors, boxes
model = torch.jit.script(MyModule())
anchors = torch.rand(10)
self.run_test(model, anchors)
@skipIfUnsupportedMinOpsetVersion(13)
def test_set_attr_in_loop_with_list(self):
class MyModule(torch.nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.conv = torch.nn.Conv1d(10, 3, 3)
self.conv.weight = torch.nn.Parameter(torch.zeros(3, 10))
self.conv.bias = torch.nn.Parameter(torch.zeros(3, 10, 3))
self.boxes : List[torch.Tensor] = [torch.ones(1)] # Workaround placeholder for TorchScript
def set_cell_anchors(self, anchors):
self.conv.weight = torch.randn(3, 10)
for i in range(self.conv.weight.size(0)):
for j in range(10):
self.conv.bias = torch.randn(3, 10, 3)
self.conv.weight = anchors * i
self.boxes.append(torch.ones(3, 3))
def forward(self, anchors) -> Tuple[torch.Tensor, List[torch.Tensor]]:
self.boxes = []
self.set_cell_anchors(anchors)
if self.conv.bias is not None:
return self.conv.weight, self.boxes
return anchors, self.boxes
model = torch.jit.script(MyModule())
anchors = torch.rand(10)
self.run_test(model, anchors)
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_if(self):
@torch.jit.script
def check_init(input_data, hidden_size, prev_state):
# type: (torch.Tensor, int, torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]
batch_size = input_data.size(0)
spatial_size_0 = input_data.size(2)
spatial_size_1 = input_data.size(3)
# generate empty prev_state, if None is provided
state_size = (2, batch_size, hidden_size, spatial_size_0, spatial_size_1)
state = torch.zeros(state_size, device=input_data.device)
state_copy = torch.zeros(state_size, device=input_data.device)
if prev_state.size(0) == 0:
state[:] = torch.zeros(batch_size, hidden_size, spatial_size_0, spatial_size_1) + state[:]
state_copy[:] = torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1) * 2
state_copy[:] = torch.zeros(batch_size, hidden_size, spatial_size_0, spatial_size_1) * 2
else:
state[:] = torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1) * 4
return state, state_copy
class Example(torch.nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.hidden_size = hidden_size
def forward(self, input_data, prev_state):
prev_state = check_init(input_data, self.hidden_size, prev_state)
return prev_state[0], prev_state[1]
model = Example(10)
random_data = torch.rand((1, 5, 30, 30))
empty_tensor = torch.tensor([], dtype=torch.float).view(0, 0, 0, 0, 0)
self.run_test(model, (random_data, empty_tensor),
input_names=["random_data", "empty_tensor"],
dynamic_axes={"random_data": [0, 1, 2, 3], "empty_tensor": [0, 1, 2, 3, 4]})
self.run_test(model, (random_data, empty_tensor), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_if_2(self):
@torch.jit.script
def check_init(input_data, hidden_size, prev_state):
# type: (torch.Tensor, int, torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]
batch_size = input_data.size(0)
spatial_size_0 = input_data.size(2)
spatial_size_1 = input_data.size(3)
# generate empty prev_state, if None is provided
state_size = (2, batch_size, hidden_size, spatial_size_0, spatial_size_1)
state = torch.zeros(state_size, device=input_data.device)
state_copy = torch.zeros(state_size, device=input_data.device)
if prev_state.size(0) == 0:
for i in range(2):
state[:] = torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1) * i
state_copy[:] = torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1) * i
elif prev_state.size(0) == 1:
s = state[:]
state[:] = prev_state + s
elif prev_state.size(0) == 2:
state[:] = torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1) * 4
return state, state_copy
class Example(torch.nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.hidden_size = hidden_size
def forward(self, input_data, prev_state):
prev_state = check_init(input_data, self.hidden_size, prev_state)
return prev_state[0], prev_state[1]
model = Example(10)
random_data = torch.rand((1, 5, 30, 30))
empty_tensor = torch.tensor([], dtype=torch.float).view(0, 0, 0, 0, 0)
random_state = torch.rand((1, 1, 10, 30, 30))
self.run_test(model, (random_data, empty_tensor),
input_names=["data", "state"],
dynamic_axes={"state": [0, 1, 2, 3, 4]},
test_with_inputs=[(random_data, random_state)])
self.run_test(model, (random_data, empty_tensor), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_if_3(self):
@torch.jit.script
def check_init(input_data, hidden_size, prev_state):
# type: (torch.Tensor, int, torch.Tensor) -> torch.Tensor
batch_size = input_data.size(0)
spatial_size_0 = input_data.size(2)
spatial_size_1 = input_data.size(3)
# generate empty prev_state, if None is provided
state_size = (2, batch_size, hidden_size, spatial_size_0, spatial_size_1)
state = torch.zeros(state_size, device=input_data.device)
if prev_state.size(0) < 2:
state = state * 3
if prev_state.size(0) == 0:
state[:] = torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1) * 3
else:
state = state + 2
return state
class Example(torch.nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.hidden_size = hidden_size
def forward(self, input_data, prev_state):
prev_state = check_init(input_data, self.hidden_size, prev_state)
return prev_state
model = Example(4)
random_data = torch.rand((1, 5, 4, 4))
empty_tensor = torch.tensor([], dtype=torch.float).view(0, 0, 0, 0, 0)
self.run_test(model, (random_data, empty_tensor),
input_names=["random_data", "empty_tensor"],
dynamic_axes={"random_data": [0, 1, 2, 3], "empty_tensor": [0, 1, 2, 3, 4]})
self.run_test(model, (random_data, empty_tensor), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_if_4(self):
@torch.jit.script
def check_init(input_data, hidden_size, prev_state):
# type: (torch.Tensor, int, torch.Tensor) -> torch.Tensor
batch_size = input_data.size(0)
spatial_size_0 = input_data.size(2)
spatial_size_1 = input_data.size(3)
# generate empty prev_state, if None is provided
state_size = (2, batch_size, hidden_size, spatial_size_0, spatial_size_1)
state = torch.zeros(state_size, device=input_data.device)
if prev_state.size(0) == 0:
state = state + 3
state[:] = torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1) * 3
state = state + 3
state[:] = torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1) * 4
else:
state = state + 2
return state
class Example(torch.nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.hidden_size = hidden_size
def forward(self, input_data, prev_state):
prev_state = check_init(input_data, self.hidden_size, prev_state)
return prev_state
model = Example(4)
random_data = torch.rand((1, 5, 4, 4))
empty_tensor = torch.tensor([], dtype=torch.float).view(0, 0, 0, 0, 0)
self.run_test(model, (random_data, empty_tensor),
input_names=["random_data", "empty_tensor"],
dynamic_axes={"random_data": [0, 1, 2, 3], "empty_tensor": [0, 1, 2, 3, 4]})
self.run_test(model, (random_data, empty_tensor), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_if_5(self):
@torch.jit.script
def check_init(input_data, hidden_size, prev_state):
# type: (torch.Tensor, int, torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]
batch_size = input_data.size(0)
spatial_size_0 = input_data.size(2)
spatial_size_1 = input_data.size(3)
# generate empty prev_state, if None is provided
state_size = (2, batch_size, hidden_size, spatial_size_0, spatial_size_1)
state = torch.zeros(state_size, device=input_data.device)
state_ref = state
if prev_state.size(0) == 0:
state[:] = torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1) * 3
state = state + 3
state[:] = torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1) * 4
else:
state = state + 2
return state, state_ref
class Example(torch.nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.hidden_size = hidden_size
def forward(self, input_data, prev_state):
prev_state, state_ref = check_init(input_data, self.hidden_size, prev_state)
return prev_state, state_ref
model = Example(4)
random_data = torch.rand((1, 5, 4, 4))
empty_tensor = torch.tensor([], dtype=torch.float).view(0, 0, 0, 0, 0)
self.run_test(model, (random_data, empty_tensor),
input_names=["random_data", "empty_tensor"],
dynamic_axes={"random_data": [0, 1, 2, 3], "empty_tensor": [0, 1, 2, 3, 4]})
self.run_test(model, (random_data, empty_tensor), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_list_append_in_block(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
res.append(torch.matmul(x[i], y))
return res
model = torch.jit.script(ListModel())
x = torch.randn(16, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_append_in_nested_block(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
for j in range(x.size(1)):
res.append(torch.matmul(x[i][j], y))
return res
model = torch.jit.script(ListModel())
x = torch.randn(4, 4, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_pop_in_block(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
elem = torch.matmul(x[0], y)
for i in range(x.size(0)):
res.append(torch.matmul(x[i], y))
for i in range(x.size(0)):
elem = res.pop()
for i in range(x.size(0)):
res.append(torch.matmul(x[i], y))
elem = res.pop()
return res.append(elem)
model = torch.jit.script(ListModel())
x = torch.randn(16, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_del_in_block(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
elem = torch.matmul(x[0], y)
for i in range(x.size(0)):
res.append(torch.matmul(x[i], y))
for i in range(x.size(0)):
del res[0]
for i in range(x.size(0)):
res.append(torch.matmul(x[i], y))
del res[0]
return res.append(elem)
model = torch.jit.script(ListModel())
x = torch.randn(16, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
def test_list_unpack(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
elem = torch.matmul(x[0], y)
for i in range(x.size(0)):
res.append(torch.matmul(x[i], y))
a, b, c = res
return a, b
model = torch.jit.script(ListModel())
x = torch.randn(3, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_inplace_ops(self):
@torch.jit.script
def check_init(input_data, hidden_size):
# type: (torch.Tensor, int) -> torch.Tensor
batch_size = input_data.size(0)
spatial_size_0 = input_data.size(2)
spatial_size_1 = input_data.size(3)
# generate empty prev_state, if None is provided
state_size = (2, batch_size, hidden_size, spatial_size_0, spatial_size_1)
state = torch.zeros(state_size, device=input_data.device)
if input_data.size(0) == 1:
state[1] += torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1) * 2
state[1] /= torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1) * 3
for i in range(input_data.size(0)):
state[1] += torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1)
state[1] /= torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1) * i
return state
class Example(torch.nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.hidden_size = hidden_size
def forward(self, input_data):
state = check_init(input_data, self.hidden_size)
return state
model = Example(10)
random_data = torch.rand((1, 5, 30, 30))
self.run_test(model, (random_data), input_names=["random_data"],
dynamic_axes={"random_data": [0, 1, 2, 3]})
self.run_test(model, (random_data), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_input_mask_model(self):
class InputMaskModel(torch.nn.Module):
def __init__(self, output_size):
super(InputMaskModel, self).__init__()
self.bias = torch.nn.Parameter(torch.empty(
output_size,
dtype=torch.float))
with torch.no_grad():
self.bias.zero_()
def forward(self, model_input, y):
input_mask = (model_input <= 0) | (model_input > 25)
y[input_mask, :] = 0.0
output = y + self.bias
return output
output_size = 4
m = InputMaskModel(output_size)
x = torch.tensor([0, 4, 24, 25], dtype=torch.int64)
y = torch.tensor([[0.1, 0.2, 0.3, 0.4], [0.1, 0.2, 0.3, 0.4],
[0.1, 0.2, 0.3, 0.4], [0.1, 0.2, 0.3, 0.4]], dtype=torch.float)
self.run_test(m, (x, y))
class InputMaskModel(torch.nn.Module):
def __init__(self, output_size):
super(InputMaskModel, self).__init__()
def forward(self, model_input_1, model_input_2, y):
input_mask_1 = (model_input_1 <= 0) | (model_input_1 > 25)
input_mask_2 = (model_input_2 < 1) | (model_input_2 >= 12)
y[input_mask_1, input_mask_2] = 0.0
return y
output_size = 4
m = InputMaskModel(output_size)
x1 = torch.tensor([0, 4, 24, 25], dtype=torch.int64)
x2 = torch.tensor([0, 3, 12, 15], dtype=torch.int64)
y = torch.tensor([[0.1, 0.2, 0.3, 0.4], [0.1, 0.2, 0.3, 0.4],
[0.1, 0.2, 0.3, 0.4], [0.1, 0.2, 0.3, 0.4]], dtype=torch.float)
self.run_test(m, (x1, x2, y))
@disableScriptTest()
def test_unsafe_chunk(self):
class ChunkModel(torch.nn.Module):
def forward(self, x):
return torch.unsafe_chunk(x, 3, dim=1)
model = ChunkModel()
model.eval()
x = torch.randn(1, 18)
self.run_test(model, x, input_names=["x"])
def test_symbolic_shape_inference(self):
# ConstantOfShape is tested in test_embedding_bag
# Tile is tested in test_repeat
# test Shape, Reshape, Transpose, Gather
class ShapeModel(torch.nn.Module):
def forward(self, x, y):
shape = x.size()[:3] + (-1,) # shape [4], ("batch", 3, 4, -1)
y = y.reshape(shape) # batch, 3, 4, 10/batch
return y.transpose(1, 2)
model = ShapeModel()
model.eval()
x = torch.ones(2, 3, 4, 5)
y = torch.ones(3, 4, 5, 2)
self.run_test(model, (x, y), input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2, 3], "y": [0, 1, 2, 3]})
self.run_test(model, (x, y), remained_onnx_input_idx=[1])
class ViewModel(torch.nn.Module):
def forward(self, x):
return x.view(-1)
model = ViewModel()
model.eval()
x = torch.tensor(2.)
self.run_test(model, (x,))
# test prim::ListConstruct for Reshape input 1
class ViewModel_2(torch.nn.Module):
def forward(self, x):
N, C, H, W = x.shape[0], x.shape[2], x.shape[3], x.shape[4]
x1 = x.view(N, -1, C, H, W)
x2 = x1.permute(0, 3, 4, 1, 2)
return x2.reshape(N, -1, C)
model = ViewModel_2()
model.eval()
x = torch.ones(2, 3, 4, 5, 6)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_symbolic_shape_inference_arange(self):
# test Range
class ArangeModel(torch.nn.Module):
def forward(self, signal):
frame_step = 2
outer_dimensions = signal.size()[:-2]
frames, frame_length = signal.size()[-2:]
subframe_length = signal.size()[0]
subframe_step = frame_step // subframe_length
subframes_per_frame = frame_length // subframe_length
output_size = frame_step * (frames - 1) + frame_length
output_subframes = output_size // subframe_length
frame = torch.arange(0, output_subframes)
return frame
model = ArangeModel()
model.eval()
M, C, K, N = 1, 2, 3, 4
x = torch.randint(5, (M, C, K, N))
y = torch.randint(5, (M, C + 1, K + 1, N + 1))
self.run_test(model, x, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3]})
self.run_test(model, x, remained_onnx_input_idx=[])
self.run_test(model, x, input_names=["x"],
dynamic_axes={"x" : [0, 1, 2, 3]}, test_with_inputs=[(x,), (y,)])
@skipIfUnsupportedMinOpsetVersion(11)
def test_symbolic_shape_inference_box(self):
# test NonZero
class BoxModel(torch.nn.Module):
def forward(self, boxes):
min_size = 1e-2
ws, hs = boxes[:, 2] - boxes[:, 0], boxes[:, 3] - boxes[:, 1]
keep = (ws >= min_size) & (hs >= min_size)
keep = torch.where(keep)[0]
return keep
model = BoxModel()
model.eval()
x = torch.ones(2, 4)
y = torch.ones(3, 5)
self.run_test(model, x)
self.run_test(model, x, input_names=["x"],
dynamic_axes={"x" : [0, 1]}, test_with_inputs=[(x,), (y,)])
@skipIfUnsupportedMinOpsetVersion(11)
def test_symbolic_shape_inference_box_if(self):
# test If
class BoxIfModel(torch.nn.Module):
def forward(self, boxes, scores):
score_thresh = 0.0
inds = torch.where(scores > score_thresh)[0]
boxes_1 = boxes[inds]
if boxes_1.numel() > 3:
return boxes_1
else:
return boxes_1 * 2
model = BoxIfModel()
model.eval()
boxes = torch.ones(2, 4)
scores = torch.ones(1, 4)
self.run_test(model, (boxes, scores))
@skipIfUnsupportedMinOpsetVersion(11)
def test_symbolic_shape_inference_arange_2(self):
# test Range
class ArangeModel(torch.nn.Module):
def forward(self, start):
return torch.arange(start.size(0), 8.5, 1.5, dtype=torch.int64)
x = torch.randn(2, 3, 4)
self.run_test(ArangeModel(), (x,), input_names=['x'], dynamic_axes={"x": [0, 1, 2]})
self.run_test(ArangeModel(), (x,), remained_onnx_input_idx=[])
class ArangeModel2(torch.nn.Module):
def forward(self, start):
return torch.arange(start.size(0), 8.5, 1.5, dtype=torch.double)
x = torch.randn(2, 3, 4)
self.run_test(ArangeModel2(), (x,), input_names=['x'], dynamic_axes={"x": [0, 1, 2]})
self.run_test(ArangeModel2(), (x,), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_symbolic_shape_inference_nonzero(self):
class OneLikeModel(torch.nn.Module):
def forward(self, x):
ones = torch.ones_like(x, dtype=torch.float, layout=torch.strided, device=torch.device("cpu"))
return torch.nonzero(ones)
x = torch.randn(2)
self.run_test(OneLikeModel(), x, input_names=['x'], dynamic_axes={"x": [0]})
self.run_test(OneLikeModel(), x, remained_onnx_input_idx=[])
x = torch.randn(2, 3, 4)
self.run_test(OneLikeModel(), x, input_names=['x'], dynamic_axes={"x": [0, 1, 2]})
self.run_test(OneLikeModel(), x, remained_onnx_input_idx=[])
class ZeroLikeModel(torch.nn.Module):
def forward(self, x):
zeros = torch.zeros_like(x, dtype=torch.float, layout=torch.strided, device=torch.device("cpu"))
return torch.nonzero(zeros)
x = torch.randn(2)
self.run_test(ZeroLikeModel(), x, input_names=['x'], dynamic_axes={"x": [0]})
self.run_test(ZeroLikeModel(), x, remained_onnx_input_idx=[])
x = torch.randn(2, 3, 4)
self.run_test(ZeroLikeModel(), x, input_names=['x'], dynamic_axes={"x": [0, 1, 2]})
self.run_test(ZeroLikeModel(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_symbolic_shape_inference_expand_1(self):
class ExpandModel(torch.nn.Module):
def forward(self, x):
return x.expand(4, 6, 2)
x = torch.randn(6, 1, requires_grad=True)
self.run_test(ExpandModel(), (x,))
@skipIfUnsupportedMinOpsetVersion(9)
@disableScriptTest() # Test code not scriptable
def test_symbolic_shape_inference_expand_2(self):
class M(torch.nn.Module):
def forward(self, x):
input_shape = x.size()
batch_size, seq_length = input_shape
seq_ids = torch.arange(seq_length)
causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
return causal_mask.transpose(0, 1)
x = torch.randn(3, 16)
self.run_test(M(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(M(), (x,), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(10)
@disableScriptTest() # Test code not scriptable
def test_symbolic_shape_inference_slice(self):
class M(torch.nn.Module):
def forward(self, x, position_bias):
input_shape = x.size()
batch_size, seq_length = input_shape
position_bias = position_bias[:, :, -seq_length:, :]
return position_bias.transpose(0, 1)
x = torch.randn(3, 16)
position_bias = torch.randn(1, 3, 20, 8)
self.run_test(M(), (x, position_bias), input_names=["x", "position_bias"],
dynamic_axes={"x": [0, 1], "position_bias": [0, 1, 2, 3]})
self.run_test(M(), (x, position_bias), remained_onnx_input_idx=[1])
def test_symbolic_shape_inference_slice_2(self):
class M(torch.nn.Module):
def forward(self, position_bias):
position_bias = position_bias[:, :, -2:, :]
return position_bias.transpose(0, 1)
position_bias = torch.randn(1, 3, 20, 8)
self.run_test(M(), (position_bias,))
@skipIfUnsupportedMinOpsetVersion(9)
@disableScriptTest()
def test_symbolic_shape_inference_time(self):
input = torch.randn(RNN_SEQUENCE_LENGTH, BATCH_SIZE, RNN_INPUT_SIZE)
h0 = torch.randn(1, BATCH_SIZE, RNN_HIDDEN_SIZE)
c0 = torch.randn(1, BATCH_SIZE, RNN_HIDDEN_SIZE)
model_lstm = torch.nn.LSTM(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, 1, bidirectional=False)
self.run_test(model_lstm, (input, (h0, c0)), input_names=["x", "y"],
dynamic_axes={"x" : [0, 1]})
model_gru = torch.nn.GRU(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, 1, bidirectional=False, bias=False)
self.run_test(model_gru, (input, h0), input_names=["x", "y"],
dynamic_axes={"x" : [0, 1]})
model_rnn = torch.nn.RNN(RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, 1, bidirectional=False, bias=False)
self.run_test(model_rnn, (input, h0), input_names=["x", "y"],
dynamic_axes={"x" : [0, 1]})
def test_symbolic_shape_inference_dynamic_axes(self):
class M(torch.nn.Module):
def forward(self, input_ids):
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
return input_ids.transpose(0, 1)
x = torch.randn(3, 16)
self.run_test(M(), (x,), input_names=["input_ids"],
dynamic_axes={"input_ids": {0: "batch", 1: "sequence"}})
@skipIfUnsupportedMinOpsetVersion(9)
def test_hann_window_periodic(self):
class HannWindowModule_Periodic(torch.nn.Module):
def __init__(self):
super(HannWindowModule_Periodic, self).__init__()
self.window_length = 0
def forward(self, x, window_length: int):
self.window_length = window_length
return torch.add(x, torch.hann_window(self.window_length, periodic=True, dtype=torch.float))
win_length = 100
x = torch.randn(win_length)
module = HannWindowModule_Periodic()
self.run_test(module, (x, win_length))
@skipIfUnsupportedMinOpsetVersion(9)
def test_hann_window_not_periodic(self):
class HannWindowModule_NotPeriodic(torch.nn.Module):
def __init__(self):
super(HannWindowModule_NotPeriodic, self).__init__()
self.window_length = 0
def forward(self, x, window_length: int):
self.window_length = window_length
return torch.add(x, torch.hann_window(self.window_length, periodic=False, dtype=torch.float))
win_length = 100
x = torch.randn(win_length)
module = HannWindowModule_NotPeriodic()
self.run_test(module, (x, win_length))
@skipIfUnsupportedMinOpsetVersion(9)
@disableScriptTest()
def test_hann_window_default_values(self):
class HannWindowModule(torch.nn.Module):
def __init__(self):
super(HannWindowModule, self).__init__()
self.window_length = 0
def forward(self, x, window_length: int):
import torch.nn.functional as F
self.window_length = window_length
return torch.add(x, F.relu(torch.hann_window(self.window_length)))
win_length = 100
x = torch.randn(win_length, dtype=torch.float)
module = HannWindowModule()
output = module(x, win_length)
self.run_test(module, (x, win_length))
@skipIfUnsupportedMinOpsetVersion(12)
@disableScriptTest()
def test_tensordot_dim_count(self):
class M(torch.nn.Module):
def forward(self, x, y):
output = torch.tensordot(x, y, 2)
return output
x = torch.randint(6, (7, 5, 3, 4))
y = torch.randint(6, (3, 4, 9, 2))
self.run_test(M(), (x, y))
@skipIfUnsupportedMinOpsetVersion(12)
def test_tensordot_dim_list(self):
class M(torch.nn.Module):
def forward(self, x, y):
output = torch.tensordot(x, y, ([1, -2, -1], [1, 0, 3]))
return output
x = torch.randint(6, (7, 4, 3, 5, 2))
y = torch.randint(6, (5, 4, 4, 2, 6))
self.run_test(M(), (x, y))
@skipIfUnsupportedMinOpsetVersion(12)
@disableScriptTest()
def test_tensordot_dynamic_dim(self):
class M(torch.nn.Module):
def forward(self, x, y):
output = torch.tensordot(x, y, 2)
return output
x = torch.randint(6, (7, 5, 3, 4))
y = torch.randint(6, (3, 4, 9, 2))
new_x = torch.randint(6, (8, 6, 2, 5))
new_y = torch.randint(6, (2, 5, 3, 4))
self.run_test(M(), (x, y), test_with_inputs=[(new_x, new_y)],
input_names=["input_x", "input_y"],
dynamic_axes={"input_x": [0, 1, 2, 3], "input_y": [0, 1, 2, 3]})
@skipIfUnsupportedMinOpsetVersion(9)
def test_to_device(self):
class M_ToDevice(torch.nn.Module):
def forward(self, x, y):
return x.to(y.device), y
class M_ToDeviceDtype(torch.nn.Module):
def forward(self, x, y):
return x.to(y.device, dtype=torch.long), y
x = torch.randn(6)
y = torch.randn(6)
self.run_test(M_ToDevice(), (x, y))
self.run_test(M_ToDeviceDtype(), (x, y))
@skipIfUnsupportedMinOpsetVersion(9)
@disableScriptTest()
def test_fill(self):
class FillModule(torch.nn.Module):
def forward(self, x, filled_value: int):
return x.fill_(filled_value)
x = torch.randn((4, 5, 6))
filled_value = 7
self.run_test(FillModule(), (x, filled_value))
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_add_normal(self):
class M(torch.nn.Module):
def __init__(self, dim, index, updates):
super(M, self).__init__()
self.dim = dim
self.index = index
self.updates = updates
def forward(self, x):
x.index_add_(self.dim, self.index, self.updates)
return x
x = torch.ones(5, 4, 3)
updates = torch.tensor([[1], [4], [7], [3], [2]], dtype=torch.float)
index = torch.tensor([0, 2, 3, 1, 4])
self.run_test(M(0, index, updates), (x,))
updates = torch.tensor([[[1, 5, 7], [2, 4, 5], [5, 5, 6], [2, 3, 4]]], dtype=torch.float)
index = torch.tensor([0, 2, 3, 1])
self.run_test(M(1, index, updates), (x,))
updates = torch.tensor([[[1, 2, 3], [4, 5, 6], [7, 8, 9], [2, 3, 4]]], dtype=torch.float)
index = torch.tensor([0, 2, 1])
self.run_test(M(2, index, updates), (x,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_add_dim_size_differ(self):
class M(torch.nn.Module):
def __init__(self, dim, index, updates):
super(M, self).__init__()
self.dim = dim
self.index = index
self.updates = updates
def forward(self, x):
x.index_add_(self.dim, self.index, self.updates)
return x
x = torch.ones(5, 4, 3)
updates = torch.tensor([[[1, 5, 7], [2, 4, 5], [5, 5, 6]]], dtype=torch.float)
index = torch.tensor([0, 2, 1])
self.run_test(M(1, index, updates), (x,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_add_in_loop(self):
class M(torch.nn.Module):
def __init__(self, dim, index, updates, loop_count):
super(M, self).__init__()
self.dim = dim
self.index = index
self.updates = updates
self.loop_count = loop_count
def forward(self, x):
for i in range(self.loop_count):
x.index_add_(self.dim, self.index, self.updates)
return x
x = torch.ones(5, 4, 3)
updates = torch.tensor([[[1, 5, 7], [2, 4, 5], [5, 5, 6], [2, 3, 4]]], dtype=torch.float)
index = torch.tensor([0, 2, 3, 1])
loop_count = torch.randint(20, (1, ))[0].item()
self.run_test(M(1, index, updates, loop_count), (x,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_add_if(self):
class M(torch.nn.Module):
def __init__(self, dim, updates, index_true, index_false):
super(M, self).__init__()
self.dim = dim
self.updates = updates
self.index_true = index_true
self.index_false = index_false
def forward(self, x, cond):
if cond:
x.index_add_(self.dim, self.index_true, self.updates)
else:
x.index_add_(self.dim, self.index_false, self.updates)
return x
x = torch.ones(5, 4, 3)
updates = torch.tensor([[[1, 5, 7], [2, 4, 5], [5, 5, 6], [2, 3, 4]]], dtype=torch.float)
index_true = torch.tensor([0, 2, 3, 1])
index_false = torch.tensor([1, 0, 2, 3])
cond = torch.tensor(1, dtype=torch.bool)
self.run_test(torch.jit.script(M(1, updates, index_true, index_false)), (x, cond))
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_add_dynamic_axes(self):
class M(torch.nn.Module):
def __init__(self, dim, index, updates):
super(M, self).__init__()
self.dim = dim
self.index = index
self.updates = updates
def forward(self, x):
x.index_add_(self.dim, self.index, self.updates)
return x
x = torch.ones(5, 4, 3)
y = torch.ones(7, 8, 3)
updates = torch.tensor([[[1, 5, 7], [2, 4, 5], [5, 5, 6], [2, 3, 4]]], dtype=torch.float)
index = torch.tensor([0, 2, 3, 1])
self.run_test(M(1, index, updates), (x,), test_with_inputs=[y],
input_names=['input_1'],
dynamic_axes={'input_1': [0, 1]})
def test_roll(self):
class M(torch.nn.Module):
def __init__(self, shifts, dims):
super(M, self).__init__()
self.shifts = shifts
self.dims = dims
def forward(self, x):
return torch.roll(x, self.shifts, self.dims)
x = torch.randn(2, 3, 4)
self.run_test(M([1, 1], [1, 0]), (x,))
self.run_test(M([0, 1, 2], [1, 0, 2]), (x,))
self.run_test(M(2, 1), (x,))
self.run_test(M([-1, 3], [-2, -1]), (x,))
def test_sum(self):
class M(torch.nn.Module):
def forward(self, x):
return torch.sum(x)
x = torch.ones(12, 3)
self.run_test(M(), (x,), input_names=['x'], dynamic_axes={'x': [0]})
def test_sum_empty_tensor(self):
class M(torch.nn.Module):
def forward(self, x):
return x[0:0].sum(), x.sum()
x = torch.ones(12)
self.run_test(M(), (x,))
x = torch.ones(2, 0, 3)
self.run_test(M(), (x,))
x = torch.ones(0)
self.run_test(M(), (x,))
@skipIfUnsupportedMinOpsetVersion(11)
def test_broad_cast_tensors(self):
class M(torch.nn.Module):
def forward(self, x, y):
m = torch.broadcast_tensors(x, y)
return m
x = torch.randint(5, (1,))
y = torch.randint(5, (5,))
self.run_test(M(), (x, y))
x = torch.randint(5, (4, 2, 1, 4))
y = torch.randint(5, (2, 3, 1))
self.run_test(M(), (x, y))
x = torch.randn(2, 1, 4)
y = torch.randn(5, 2, 3, 1)
self.run_test(M(), (x, y))
@disableScriptTest()
@skipIfUnsupportedMinOpsetVersion(11)
def test_dist_normal(self):
class M(torch.nn.Module):
def forward(self, x, y):
return torch.distributions.Normal(x, y).sample().size(0), x, y
self.run_test(M(), (torch.tensor([0.0]), torch.tensor([[1.0], [2.0]])))
self.run_test(M(), (torch.tensor([0.0]), torch.tensor([1.0])))
self.run_test(M(), (torch.tensor([[[0.0], [10.0]], [[2.0], [8.0]], [[2.0], [8.0]]]), torch.tensor([[1.0], [3.0]])))
@disableScriptTest()
@skipIfUnsupportedMinOpsetVersion(11)
def test_dist_normal_correctness(self):
class M(torch.nn.Module):
def forward(self, x, y):
return torch.distributions.Normal(x, y).sample([20000])
expected_mean = 5.0
expected_std = 10.0
model_export = M()
dummy_input = (torch.tensor([expected_mean]), torch.tensor([expected_std]))
ort_sess = convert_to_onnx(model_export, input=dummy_input, opset_version=self.opset_version,
training=torch.onnx.TrainingMode.EVAL)
ort_out = run_ort(ort_sess, input=dummy_input)
actual_std = np.std(ort_out)
actual_mean = np.mean(ort_out)
assert abs(abs(actual_mean) - expected_mean) <= expected_mean * 0.1, \
"the gap of mean between ort outputs and expected one is unacceptable."
assert abs(abs(actual_std) - expected_std) <= expected_std * 0.1, \
"the gap of variance between ort outputs and expected one is unacceptable."
@disableScriptTest()
@skipIfUnsupportedMinOpsetVersion(11)
def test_dist_uniform(self):
class M(torch.nn.Module):
def forward(self, x, y):
return torch.distributions.Uniform(x, y).sample().size(0), x , y
self.run_test(M(), (torch.tensor([0.0]), torch.tensor([10.0])))
self.run_test(M(), (torch.tensor([[0.0], [6.0]]), torch.tensor([[1.0], [7.0]])))
self.run_test(M(), (torch.tensor([1.0]), torch.tensor([[10.0], [7.0], [9.0], [20.0]])))
@disableScriptTest()
@skipIfUnsupportedMinOpsetVersion(11)
def test_dist_uniform_correctness(self):
class M(torch.nn.Module):
def forward(self, x, y):
return torch.distributions.Uniform(x, y).sample([10000])
expected_min = 5.0
expected_max = 10.0
expected_mean = (expected_min + expected_max) / 2
model_export = M()
dummy_input = (torch.tensor([expected_min]), torch.tensor([expected_max]))
ort_sess = convert_to_onnx(model_export, input=dummy_input, opset_version=self.opset_version,
training=torch.onnx.TrainingMode.EVAL)
ort_out = run_ort(ort_sess, input=dummy_input)
actual_min = np.min(ort_out)
actual_max = np.max(ort_out)
actual_mean = np.mean(ort_out)
assert actual_min >= expected_min, "the minimum value of ort outputs is out of scope."
assert actual_max <= expected_max, "the maximum value of ort outputs is out of scope."
assert abs(actual_mean - expected_mean) <= expected_mean * 0.05, \
"the mean value of ort outputs is out of scope."
@skipIfUnsupportedMinOpsetVersion(13)
def test_sequence_to_int(self):
class M(torch.nn.Module):
def forward(self, x):
result = torch.tensor([2 for i in range(x.size()[0])], dtype=torch.int)
return x, result
x = torch.randn(10, 5)
self.run_test(M(), (x,))
@skipIfUnsupportedMinOpsetVersion(13)
def test_sequence_to_float(self):
class M(torch.nn.Module):
def forward(self, x):
result = torch.tensor([1.1 for i in range(x.size()[0])], dtype=torch.float)
return x, result
x = torch.randn(10, 5)
self.run_test(M(), (x,))
@skipIfUnsupportedMinOpsetVersion(13)
def test_sequence_to_bool(self):
class M(torch.nn.Module):
def forward(self, x):
result = torch.tensor([False for i in range(x.size()[0])], dtype=torch.bool)
return x, result
x = torch.randn(10, 5)
self.run_test(M(), (x,))
def test_tuple_output_from_if_with_raised_exception(self):
class M(torch.nn.Module):
def __init__(self):
super(M, self).__init__()
def forward(self, t: Tensor) -> Tuple[Tensor, Tensor]:
if float(t) < 0:
raise Exception("Negative input")
else:
return torch.zeros(5), torch.zeros(5)
x = torch.zeros(1)
self.run_test(torch.jit.script(M()), (x,))
def make_test(name, base, layer, bidirectional, initial_state,
variable_length, dropout, script_test_min_opset_version,
**extra_kwargs):
test_name = str("_".join([
"test", name, layer[1],
bidirectional[1], initial_state[1],
variable_length[1], dropout[1]
]))
# Cannot export with older opsets because of "ConstantFill" op
# ConstantFill was a temp op removed at opset 8. This is no longer supported by onnxruntime
# There are still some issues prevent us from enabling script test for these scenarios:
# test_gru_*:
# Operator aten::as_tensor is not supported by exporter yet.
# - https://msdata.visualstudio.com/Vienna/_workitems/edit/1055382
# Operator aten::_pack_padded_sequence is not supported by exporter yet.
# - https://msdata.visualstudio.com/Vienna/_workitems/edit/1055384
@disableScriptTest()
@skipIfUnsupportedMinOpsetVersion(9)
def f(self):
self.is_script_test_enabled = self.opset_version >= script_test_min_opset_version
self._dispatch_rnn_test(
base,
layers=layer[0],
bidirectional=bidirectional[0],
initial_state=initial_state[0],
packed_sequence=variable_length[0],
dropout=dropout[0],
**extra_kwargs)
f.__name__ = test_name
setattr(TestONNXRuntime, f.__name__, f)
def setup_rnn_tests():
layers_opts = [
(1, "unilayer"),
(3, "trilayer")
]
bidirectional_opts = [
(False, "forward"),
(True, "bidirectional")
]
initial_state_opts = [
(True, "with_initial_state"),
(False, "no_initial_state")
]
variable_length_opts = [
(0, "without_sequence_lengths"),
(1, "with_variable_length_sequences"),
(2, "with_batch_first_sequence_lengths")
]
dropout_opts = [
(0.2, "with_dropout"),
(0.0, "without_dropout")
]
test_count = 0
for (layer, bidirectional, initial_state, variable_length, dropout) in \
itertools.product(
layers_opts,
bidirectional_opts,
initial_state_opts,
variable_length_opts,
dropout_opts,):
for base, name, extra_kwargs in (
("elman", "elman_relu", {"nonlinearity": u"relu"}),
("elman", "elman_tanh", {"nonlinearity": u"tanh"}),
("lstm", "lstm", {}),
("gru", "gru", {})
):
# Need Add between list of tensors
script_test_min_opset_version = 11
if ( # compiling in script mode fails with errors like:
# torch.jit.frontend.UnsupportedNodeError: annotated assignments
# without assigned value aren't supported
# https://msdata.visualstudio.com/Vienna/_workitems/edit/1160723
base == 'elman' or
# compiling in script mode fails with errors like:
# RuntimeError: Arguments for call are not valid.
# https://msdata.visualstudio.com/Vienna/_workitems/edit/1160723
base == 'lstm'):
script_test_min_opset_version = float("inf")
make_test(name, base, layer, bidirectional, initial_state,
variable_length, dropout, script_test_min_opset_version,
**extra_kwargs)
test_count += 1
# sanity check that a representative example does exist
TestONNXRuntime.test_gru_trilayer_forward_with_initial_state_without_sequence_lengths_with_dropout
# make sure no one accidentally disables all the tests without
# noticing
if test_count != 192:
raise ValueError("Expected 192 tests but found {}".format(test_count))
setup_rnn_tests()
# opset 7 tests
TestONNXRuntime_opset7 = type(str("TestONNXRuntime_opset7"),
(unittest.TestCase,),
dict(TestONNXRuntime.__dict__, opset_version=7))
# opset 8 tests
TestONNXRuntime_opset8 = type(str("TestONNXRuntime_opset8"),
(unittest.TestCase,),
dict(TestONNXRuntime.__dict__, opset_version=8))
# opset 10 tests
TestONNXRuntime_opset10 = type(str("TestONNXRuntime_opset10"),
(unittest.TestCase,),
dict(TestONNXRuntime.__dict__, opset_version=10))
# opset 11 tests
TestONNXRuntime_opset11 = type(str("TestONNXRuntime_opset11"),
(unittest.TestCase,),
dict(TestONNXRuntime.__dict__, opset_version=11))
# opset 12 tests
TestONNXRuntime_opset12 = type(str("TestONNXRuntime_opset12"),
(unittest.TestCase,),
dict(TestONNXRuntime.__dict__, opset_version=12))
# opset 9 tests, with keep_initializers_as_inputs=False for
# IR version 4 style export.
TestONNXRuntime_opset9_IRv4 = type(str("TestONNXRuntime_opset9_IRv4"),
(unittest.TestCase,),
dict(TestONNXRuntime.__dict__,
keep_initializers_as_inputs=False))
# opset 10 tests, with keep_initializers_as_inputs=False for
# IR version 4 style export.
TestONNXRuntime_opset10_IRv4 = type(str("TestONNXRuntime_opset10_IRv4"),
(unittest.TestCase,),
dict(TestONNXRuntime.__dict__, opset_version=10,
keep_initializers_as_inputs=False))
# opset 11 tests, with keep_initializers_as_inputs=False for
# IR version 4 style export.
TestONNXRuntime_opset11_IRv4 = type(str("TestONNXRuntime_opset11_IRv4"),
(unittest.TestCase,),
dict(TestONNXRuntime.__dict__, opset_version=11,
keep_initializers_as_inputs=False))
# opset 12 tests, with keep_initializers_as_inputs=False for
# IR version 4 style export.
TestONNXRuntime_opset12_IRv4 = type(str("TestONNXRuntime_opset12_IRv4"),
(unittest.TestCase,),
dict(TestONNXRuntime.__dict__, opset_version=12,
keep_initializers_as_inputs=False))
# opset 13 tests
TestONNXRuntime_opset13 = type(str("TestONNXRuntime_opset13"),
(unittest.TestCase,),
dict(TestONNXRuntime.__dict__, opset_version=13,
keep_initializers_as_inputs=False,
onnx_shape_inference=True))
# opset 14 tests
TestONNXRuntime_opset14 = type(str("TestONNXRuntime_opset14"),
(unittest.TestCase,),
dict(TestONNXRuntime.__dict__, opset_version=14,
keep_initializers_as_inputs=False,
onnx_shape_inference=True))
if __name__ == "__main__":
unittest.main()
|
[GOAL]
R : Type u_1
inst✝ : CommSemiring R
p : R[X]
hp : Monic p
⊢ IsPrimitive p
[PROOFSTEP]
rintro r ⟨q, h⟩
[GOAL]
case intro
R : Type u_1
inst✝ : CommSemiring R
p : R[X]
hp : Monic p
r : R
q : R[X]
h : p = ↑C r * q
⊢ IsUnit r
[PROOFSTEP]
exact isUnit_of_mul_eq_one r (q.coeff p.natDegree) (by rwa [← coeff_C_mul, ← h])
[GOAL]
R : Type u_1
inst✝ : CommSemiring R
p : R[X]
hp : Monic p
r : R
q : R[X]
h : p = ↑C r * q
⊢ r * coeff q (natDegree p) = 1
[PROOFSTEP]
rwa [← coeff_C_mul, ← h]
[GOAL]
R : Type u_1
inst✝¹ : CommSemiring R
inst✝ : Nontrivial R
p : R[X]
hp : IsPrimitive p
⊢ p ≠ 0
[PROOFSTEP]
rintro rfl
[GOAL]
R : Type u_1
inst✝¹ : CommSemiring R
inst✝ : Nontrivial R
hp : IsPrimitive 0
⊢ False
[PROOFSTEP]
exact (hp 0 (dvd_zero (C 0))).ne_zero rfl
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
⊢ content p ∣ coeff p n
[PROOFSTEP]
by_cases h : n ∈ p.support
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
h : n ∈ support p
⊢ content p ∣ coeff p n
[PROOFSTEP]
apply Finset.gcd_dvd h
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
h : ¬n ∈ support p
⊢ content p ∣ coeff p n
[PROOFSTEP]
rw [mem_support_iff, Classical.not_not] at h
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
h : coeff p n = 0
⊢ content p ∣ coeff p n
[PROOFSTEP]
rw [h]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
h : coeff p n = 0
⊢ content p ∣ 0
[PROOFSTEP]
apply dvd_zero
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
⊢ content (↑C r) = ↑normalize r
[PROOFSTEP]
rw [content]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
⊢ Finset.gcd (support (↑C r)) (coeff (↑C r)) = ↑normalize r
[PROOFSTEP]
by_cases h0 : r = 0
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0 : r = 0
⊢ Finset.gcd (support (↑C r)) (coeff (↑C r)) = ↑normalize r
[PROOFSTEP]
simp [h0]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0 : ¬r = 0
⊢ Finset.gcd (support (↑C r)) (coeff (↑C r)) = ↑normalize r
[PROOFSTEP]
have h : (C r).support = {0} := support_monomial _ h0
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0 : ¬r = 0
h : support (↑C r) = {0}
⊢ Finset.gcd (support (↑C r)) (coeff (↑C r)) = ↑normalize r
[PROOFSTEP]
simp [h]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
⊢ content 0 = 0
[PROOFSTEP]
rw [← C_0, content_C, normalize_zero]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
⊢ content 1 = 1
[PROOFSTEP]
rw [← C_1, content_C, normalize_one]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ content (X * p) = content p
[PROOFSTEP]
rw [content, content, Finset.gcd_def, Finset.gcd_def]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ Multiset.gcd (Multiset.map (coeff (X * p)) (support (X * p)).val) =
Multiset.gcd (Multiset.map (coeff p) (support p).val)
[PROOFSTEP]
refine' congr rfl _
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ Multiset.map (coeff (X * p)) (support (X * p)).val = Multiset.map (coeff p) (support p).val
[PROOFSTEP]
have h : (X * p).support = p.support.map ⟨Nat.succ, Nat.succ_injective⟩ :=
by
ext a
simp only [exists_prop, Finset.mem_map, Function.Embedding.coeFn_mk, Ne.def, mem_support_iff]
cases' a with a
· simp [coeff_X_mul_zero, Nat.succ_ne_zero]
rw [mul_comm, coeff_mul_X]
constructor
· intro h
use a
· rintro ⟨b, ⟨h1, h2⟩⟩
rw [← Nat.succ_injective h2]
apply h1
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ support (X * p) = Finset.map { toFun := Nat.succ, inj' := Nat.succ_injective } (support p)
[PROOFSTEP]
ext a
[GOAL]
case a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
a : ℕ
⊢ a ∈ support (X * p) ↔ a ∈ Finset.map { toFun := Nat.succ, inj' := Nat.succ_injective } (support p)
[PROOFSTEP]
simp only [exists_prop, Finset.mem_map, Function.Embedding.coeFn_mk, Ne.def, mem_support_iff]
[GOAL]
case a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
a : ℕ
⊢ ¬coeff (X * p) a = 0 ↔ ∃ a_1, ¬coeff p a_1 = 0 ∧ Nat.succ a_1 = a
[PROOFSTEP]
cases' a with a
[GOAL]
case a.zero
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ ¬coeff (X * p) Nat.zero = 0 ↔ ∃ a, ¬coeff p a = 0 ∧ Nat.succ a = Nat.zero
[PROOFSTEP]
simp [coeff_X_mul_zero, Nat.succ_ne_zero]
[GOAL]
case a.succ
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
a : ℕ
⊢ ¬coeff (X * p) (Nat.succ a) = 0 ↔ ∃ a_1, ¬coeff p a_1 = 0 ∧ Nat.succ a_1 = Nat.succ a
[PROOFSTEP]
rw [mul_comm, coeff_mul_X]
[GOAL]
case a.succ
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
a : ℕ
⊢ ¬coeff p a = 0 ↔ ∃ a_1, ¬coeff p a_1 = 0 ∧ Nat.succ a_1 = Nat.succ a
[PROOFSTEP]
constructor
[GOAL]
case a.succ.mp
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
a : ℕ
⊢ ¬coeff p a = 0 → ∃ a_2, ¬coeff p a_2 = 0 ∧ Nat.succ a_2 = Nat.succ a
[PROOFSTEP]
intro h
[GOAL]
case a.succ.mp
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
a : ℕ
h : ¬coeff p a = 0
⊢ ∃ a_1, ¬coeff p a_1 = 0 ∧ Nat.succ a_1 = Nat.succ a
[PROOFSTEP]
use a
[GOAL]
case a.succ.mpr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
a : ℕ
⊢ (∃ a_1, ¬coeff p a_1 = 0 ∧ Nat.succ a_1 = Nat.succ a) → ¬coeff p a = 0
[PROOFSTEP]
rintro ⟨b, ⟨h1, h2⟩⟩
[GOAL]
case a.succ.mpr.intro.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
a b : ℕ
h1 : ¬coeff p b = 0
h2 : Nat.succ b = Nat.succ a
⊢ ¬coeff p a = 0
[PROOFSTEP]
rw [← Nat.succ_injective h2]
[GOAL]
case a.succ.mpr.intro.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
a b : ℕ
h1 : ¬coeff p b = 0
h2 : Nat.succ b = Nat.succ a
⊢ ¬coeff p b = 0
[PROOFSTEP]
apply h1
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : support (X * p) = Finset.map { toFun := Nat.succ, inj' := Nat.succ_injective } (support p)
⊢ Multiset.map (coeff (X * p)) (support (X * p)).val = Multiset.map (coeff p) (support p).val
[PROOFSTEP]
rw [h]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : support (X * p) = Finset.map { toFun := Nat.succ, inj' := Nat.succ_injective } (support p)
⊢ Multiset.map (coeff (X * p)) (Finset.map { toFun := Nat.succ, inj' := Nat.succ_injective } (support p)).val =
Multiset.map (coeff p) (support p).val
[PROOFSTEP]
simp only [Finset.map_val, Function.comp_apply, Function.Embedding.coeFn_mk, Multiset.map_map]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : support (X * p) = Finset.map { toFun := Nat.succ, inj' := Nat.succ_injective } (support p)
⊢ Multiset.map (fun x => coeff (X * p) (Nat.succ x)) (support p).val = Multiset.map (coeff p) (support p).val
[PROOFSTEP]
refine' congr (congr rfl _) rfl
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : support (X * p) = Finset.map { toFun := Nat.succ, inj' := Nat.succ_injective } (support p)
⊢ (fun x => coeff (X * p) (Nat.succ x)) = coeff p
[PROOFSTEP]
ext a
[GOAL]
case h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : support (X * p) = Finset.map { toFun := Nat.succ, inj' := Nat.succ_injective } (support p)
a : ℕ
⊢ coeff (X * p) (Nat.succ a) = coeff p a
[PROOFSTEP]
rw [mul_comm]
[GOAL]
case h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : support (X * p) = Finset.map { toFun := Nat.succ, inj' := Nat.succ_injective } (support p)
a : ℕ
⊢ coeff (p * X) (Nat.succ a) = coeff p a
[PROOFSTEP]
simp [coeff_mul_X]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
k : ℕ
⊢ content (X ^ k) = 1
[PROOFSTEP]
induction' k with k hi
[GOAL]
case zero
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
⊢ content (X ^ Nat.zero) = 1
[PROOFSTEP]
simp
[GOAL]
case succ
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
k : ℕ
hi : content (X ^ k) = 1
⊢ content (X ^ Nat.succ k) = 1
[PROOFSTEP]
rw [pow_succ, content_X_mul, hi]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
⊢ content X = 1
[PROOFSTEP]
rw [← mul_one X, content_X_mul, content_one]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
p : R[X]
⊢ content (↑C r * p) = ↑normalize r * content p
[PROOFSTEP]
by_cases h0 : r = 0
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
p : R[X]
h0 : r = 0
⊢ content (↑C r * p) = ↑normalize r * content p
[PROOFSTEP]
simp [h0]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
p : R[X]
h0 : ¬r = 0
⊢ content (↑C r * p) = ↑normalize r * content p
[PROOFSTEP]
rw [content]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
p : R[X]
h0 : ¬r = 0
⊢ Finset.gcd (support (↑C r * p)) (coeff (↑C r * p)) = ↑normalize r * content p
[PROOFSTEP]
rw [content]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
p : R[X]
h0 : ¬r = 0
⊢ Finset.gcd (support (↑C r * p)) (coeff (↑C r * p)) = ↑normalize r * Finset.gcd (support p) (coeff p)
[PROOFSTEP]
rw [← Finset.gcd_mul_left]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
p : R[X]
h0 : ¬r = 0
⊢ Finset.gcd (support (↑C r * p)) (coeff (↑C r * p)) = Finset.gcd (support p) fun x => r * coeff p x
[PROOFSTEP]
refine' congr (congr rfl _) _
[GOAL]
case neg.refine'_1
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
p : R[X]
h0 : ¬r = 0
⊢ support (↑C r * p) = support p
[PROOFSTEP]
ext
[GOAL]
case neg.refine'_2
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
p : R[X]
h0 : ¬r = 0
⊢ coeff (↑C r * p) = fun x => r * coeff p x
[PROOFSTEP]
ext
[GOAL]
case neg.refine'_1.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
p : R[X]
h0 : ¬r = 0
a✝ : ℕ
⊢ a✝ ∈ support (↑C r * p) ↔ a✝ ∈ support p
[PROOFSTEP]
simp [h0, mem_support_iff]
[GOAL]
case neg.refine'_2.h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
p : R[X]
h0 : ¬r = 0
x✝ : ℕ
⊢ coeff (↑C r * p) x✝ = r * coeff p x✝
[PROOFSTEP]
simp [h0, mem_support_iff]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
k : ℕ
⊢ content (↑(monomial k) r) = ↑normalize r
[PROOFSTEP]
rw [← C_mul_X_pow_eq_monomial, content_C_mul, content_X_pow, mul_one]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ content p = 0 ↔ p = 0
[PROOFSTEP]
rw [content, Finset.gcd_eq_zero_iff]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ (∀ (x : ℕ), x ∈ support p → coeff p x = 0) ↔ p = 0
[PROOFSTEP]
constructor
[GOAL]
case mp
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ (∀ (x : ℕ), x ∈ support p → coeff p x = 0) → p = 0
[PROOFSTEP]
intro h
[GOAL]
case mpr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ p = 0 → ∀ (x : ℕ), x ∈ support p → coeff p x = 0
[PROOFSTEP]
intro h
[GOAL]
case mp
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : ∀ (x : ℕ), x ∈ support p → coeff p x = 0
⊢ p = 0
[PROOFSTEP]
ext n
[GOAL]
case mp.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : ∀ (x : ℕ), x ∈ support p → coeff p x = 0
n : ℕ
⊢ coeff p n = coeff 0 n
[PROOFSTEP]
by_cases h0 : n ∈ p.support
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : ∀ (x : ℕ), x ∈ support p → coeff p x = 0
n : ℕ
h0 : n ∈ support p
⊢ coeff p n = coeff 0 n
[PROOFSTEP]
rw [h n h0, coeff_zero]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : ∀ (x : ℕ), x ∈ support p → coeff p x = 0
n : ℕ
h0 : ¬n ∈ support p
⊢ coeff p n = coeff 0 n
[PROOFSTEP]
rw [mem_support_iff] at h0
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : ∀ (x : ℕ), x ∈ support p → coeff p x = 0
n : ℕ
h0 : ¬coeff p n ≠ 0
⊢ coeff p n = coeff 0 n
[PROOFSTEP]
push_neg at h0
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : ∀ (x : ℕ), x ∈ support p → coeff p x = 0
n : ℕ
h0 : coeff p n = 0
⊢ coeff p n = coeff 0 n
[PROOFSTEP]
simp [h0]
[GOAL]
case mpr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : p = 0
⊢ ∀ (x : ℕ), x ∈ support p → coeff p x = 0
[PROOFSTEP]
intro x
[GOAL]
case mpr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : p = 0
x : ℕ
⊢ x ∈ support p → coeff p x = 0
[PROOFSTEP]
simp [h]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ normUnit (content p) = 1
[PROOFSTEP]
by_cases hp0 : p.content = 0
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
hp0 : content p = 0
⊢ normUnit (content p) = 1
[PROOFSTEP]
simp [hp0]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
hp0 : ¬content p = 0
⊢ normUnit (content p) = 1
[PROOFSTEP]
ext
[GOAL]
case neg.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
hp0 : ¬content p = 0
⊢ ↑(normUnit (content p)) = ↑1
[PROOFSTEP]
apply mul_left_cancel₀ hp0
[GOAL]
case neg.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
hp0 : ¬content p = 0
⊢ content p * ↑(normUnit (content p)) = content p * ↑1
[PROOFSTEP]
erw [← normalize_apply, normalize_content, mul_one]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
h : natDegree p < n
⊢ content p = Finset.gcd (Finset.range n) (coeff p)
[PROOFSTEP]
apply dvd_antisymm_of_normalize_eq normalize_content Finset.normalize_gcd
[GOAL]
case hab
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
h : natDegree p < n
⊢ content p ∣ Finset.gcd (Finset.range n) (coeff p)
[PROOFSTEP]
rw [Finset.dvd_gcd_iff]
[GOAL]
case hab
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
h : natDegree p < n
⊢ ∀ (b : ℕ), b ∈ Finset.range n → content p ∣ coeff p b
[PROOFSTEP]
intro i _
[GOAL]
case hab
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
h : natDegree p < n
i : ℕ
a✝ : i ∈ Finset.range n
⊢ content p ∣ coeff p i
[PROOFSTEP]
apply content_dvd_coeff _
[GOAL]
case hba
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
h : natDegree p < n
⊢ Finset.gcd (Finset.range n) (coeff p) ∣ content p
[PROOFSTEP]
apply Finset.gcd_mono
[GOAL]
case hba.h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
h : natDegree p < n
⊢ support p ⊆ Finset.range n
[PROOFSTEP]
intro i
[GOAL]
case hba.h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
h : natDegree p < n
i : ℕ
⊢ i ∈ support p → i ∈ Finset.range n
[PROOFSTEP]
simp only [Nat.lt_succ_iff, mem_support_iff, Ne.def, Finset.mem_range]
[GOAL]
case hba.h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
h : natDegree p < n
i : ℕ
⊢ ¬coeff p i = 0 → i < n
[PROOFSTEP]
contrapose!
[GOAL]
case hba.h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
h : natDegree p < n
i : ℕ
⊢ n ≤ i → coeff p i = 0
[PROOFSTEP]
intro h1
[GOAL]
case hba.h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
n : ℕ
h : natDegree p < n
i : ℕ
h1 : n ≤ i
⊢ coeff p i = 0
[PROOFSTEP]
apply coeff_eq_zero_of_natDegree_lt (lt_of_lt_of_le h h1)
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ content p = gcd (leadingCoeff p) (content (eraseLead p))
[PROOFSTEP]
by_cases h : p = 0
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : p = 0
⊢ content p = gcd (leadingCoeff p) (content (eraseLead p))
[PROOFSTEP]
simp [h]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : ¬p = 0
⊢ content p = gcd (leadingCoeff p) (content (eraseLead p))
[PROOFSTEP]
rw [← leadingCoeff_eq_zero, leadingCoeff, ← Ne.def, ← mem_support_iff] at h
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : natDegree p ∈ support p
⊢ content p = gcd (leadingCoeff p) (content (eraseLead p))
[PROOFSTEP]
rw [content, ← Finset.insert_erase h, Finset.gcd_insert, leadingCoeff, content, eraseLead_support]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : natDegree p ∈ support p
⊢ gcd (coeff p (natDegree p)) (Finset.gcd (Finset.erase (support p) (natDegree p)) (coeff p)) =
gcd (coeff p (natDegree p)) (Finset.gcd (Finset.erase (support p) (natDegree p)) (coeff (eraseLead p)))
[PROOFSTEP]
refine' congr rfl (Finset.gcd_congr rfl fun i hi => _)
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : natDegree p ∈ support p
i : ℕ
hi : i ∈ Finset.erase (support p) (natDegree p)
⊢ coeff p i = coeff (eraseLead p) i
[PROOFSTEP]
rw [Finset.mem_erase] at hi
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : natDegree p ∈ support p
i : ℕ
hi : i ≠ natDegree p ∧ i ∈ support p
⊢ coeff p i = coeff (eraseLead p) i
[PROOFSTEP]
rw [eraseLead_coeff, if_neg hi.1]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
r : R
⊢ r ∣ content p ↔ ↑C r ∣ p
[PROOFSTEP]
rw [C_dvd_iff_dvd_coeff]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
r : R
⊢ r ∣ content p ↔ ∀ (i : ℕ), r ∣ coeff p i
[PROOFSTEP]
constructor
[GOAL]
case mp
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
r : R
⊢ r ∣ content p → ∀ (i : ℕ), r ∣ coeff p i
[PROOFSTEP]
intro h i
[GOAL]
case mp
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
r : R
h : r ∣ content p
i : ℕ
⊢ r ∣ coeff p i
[PROOFSTEP]
apply h.trans (content_dvd_coeff _)
[GOAL]
case mpr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
r : R
⊢ (∀ (i : ℕ), r ∣ coeff p i) → r ∣ content p
[PROOFSTEP]
intro h
[GOAL]
case mpr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
r : R
h : ∀ (i : ℕ), r ∣ coeff p i
⊢ r ∣ content p
[PROOFSTEP]
rw [content, Finset.dvd_gcd_iff]
[GOAL]
case mpr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
r : R
h : ∀ (i : ℕ), r ∣ coeff p i
⊢ ∀ (b : ℕ), b ∈ support p → r ∣ coeff p b
[PROOFSTEP]
intro i _
[GOAL]
case mpr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
r : R
h : ∀ (i : ℕ), r ∣ coeff p i
i : ℕ
a✝ : i ∈ support p
⊢ r ∣ coeff p i
[PROOFSTEP]
apply h i
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ IsPrimitive p ↔ content p = 1
[PROOFSTEP]
rw [← normalize_content, normalize_eq_one, IsPrimitive]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ (∀ (r : R), ↑C r ∣ p → IsUnit r) ↔ IsUnit (content p)
[PROOFSTEP]
simp_rw [← dvd_content_iff_C_dvd]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ (∀ (r : R), r ∣ content p → IsUnit r) ↔ IsUnit (content p)
[PROOFSTEP]
exact ⟨fun h => h p.content (dvd_refl p.content), fun h r hdvd => isUnit_of_dvd_unit hdvd h⟩
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ p = ↑C (content p) * primPart p
[PROOFSTEP]
by_cases h : p = 0
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : p = 0
⊢ p = ↑C (content p) * primPart p
[PROOFSTEP]
simp [h]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : ¬p = 0
⊢ p = ↑C (content p) * primPart p
[PROOFSTEP]
rw [primPart, if_neg h, ← Classical.choose_spec (C_content_dvd p)]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ IsPrimitive (primPart p)
[PROOFSTEP]
by_cases h : p = 0
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : p = 0
⊢ IsPrimitive (primPart p)
[PROOFSTEP]
simp [h]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : ¬p = 0
⊢ IsPrimitive (primPart p)
[PROOFSTEP]
rw [← content_eq_zero_iff] at h
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h✝ : ¬p = 0
h : ¬content p = 0
⊢ IsPrimitive (primPart p)
[PROOFSTEP]
rw [isPrimitive_iff_content_eq_one]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h✝ : ¬p = 0
h : ¬content p = 0
⊢ content (primPart p) = 1
[PROOFSTEP]
apply mul_left_cancel₀ h
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h✝ : ¬p = 0
h : ¬content p = 0
⊢ content p * content (primPart p) = content p * 1
[PROOFSTEP]
conv_rhs => rw [p.eq_C_content_mul_primPart, mul_one, content_C_mul, normalize_content]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h✝ : ¬p = 0
h : ¬content p = 0
| content p * 1
[PROOFSTEP]
rw [p.eq_C_content_mul_primPart, mul_one, content_C_mul, normalize_content]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h✝ : ¬p = 0
h : ¬content p = 0
| content p * 1
[PROOFSTEP]
rw [p.eq_C_content_mul_primPart, mul_one, content_C_mul, normalize_content]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h✝ : ¬p = 0
h : ¬content p = 0
| content p * 1
[PROOFSTEP]
rw [p.eq_C_content_mul_primPart, mul_one, content_C_mul, normalize_content]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
⊢ natDegree (primPart p) = natDegree p
[PROOFSTEP]
by_cases h : C p.content = 0
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : ↑C (content p) = 0
⊢ natDegree (primPart p) = natDegree p
[PROOFSTEP]
rw [C_eq_zero, content_eq_zero_iff] at h
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : p = 0
⊢ natDegree (primPart p) = natDegree p
[PROOFSTEP]
simp [h]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : ¬↑C (content p) = 0
⊢ natDegree (primPart p) = natDegree p
[PROOFSTEP]
conv_rhs => rw [p.eq_C_content_mul_primPart, natDegree_mul h p.primPart_ne_zero, natDegree_C, zero_add]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : ¬↑C (content p) = 0
| natDegree p
[PROOFSTEP]
rw [p.eq_C_content_mul_primPart, natDegree_mul h p.primPart_ne_zero, natDegree_C, zero_add]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : ¬↑C (content p) = 0
| natDegree p
[PROOFSTEP]
rw [p.eq_C_content_mul_primPart, natDegree_mul h p.primPart_ne_zero, natDegree_C, zero_add]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
h : ¬↑C (content p) = 0
| natDegree p
[PROOFSTEP]
rw [p.eq_C_content_mul_primPart, natDegree_mul h p.primPart_ne_zero, natDegree_C, zero_add]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
hp : IsPrimitive p
⊢ primPart p = p
[PROOFSTEP]
rw [← one_mul p.primPart, ← C_1, ← hp.content_eq_one, ← p.eq_C_content_mul_primPart]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
⊢ IsUnit (primPart (↑C r))
[PROOFSTEP]
by_cases h0 : r = 0
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0 : r = 0
⊢ IsUnit (primPart (↑C r))
[PROOFSTEP]
simp [h0]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0 : ¬r = 0
⊢ IsUnit (primPart (↑C r))
[PROOFSTEP]
unfold IsUnit
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0 : ¬r = 0
⊢ ∃ u, ↑u = primPart (↑C r)
[PROOFSTEP]
refine'
⟨⟨C ↑(normUnit r)⁻¹, C ↑(normUnit r), by rw [← RingHom.map_mul, Units.inv_mul, C_1], by
rw [← RingHom.map_mul, Units.mul_inv, C_1]⟩,
_⟩
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0 : ¬r = 0
⊢ ↑C ↑(normUnit r)⁻¹ * ↑C ↑(normUnit r) = 1
[PROOFSTEP]
rw [← RingHom.map_mul, Units.inv_mul, C_1]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0 : ¬r = 0
⊢ ↑C ↑(normUnit r) * ↑C ↑(normUnit r)⁻¹ = 1
[PROOFSTEP]
rw [← RingHom.map_mul, Units.mul_inv, C_1]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0 : ¬r = 0
⊢ ↑{ val := ↑C ↑(normUnit r)⁻¹, inv := ↑C ↑(normUnit r), val_inv := (_ : ↑C ↑(normUnit r)⁻¹ * ↑C ↑(normUnit r) = 1),
inv_val := (_ : ↑C ↑(normUnit r) * ↑C ↑(normUnit r)⁻¹ = 1) } =
primPart (↑C r)
[PROOFSTEP]
rw [← normalize_eq_zero, ← C_eq_zero] at h0
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0✝ : ¬r = 0
h0 : ¬↑C (↑normalize r) = 0
⊢ ↑{ val := ↑C ↑(normUnit r)⁻¹, inv := ↑C ↑(normUnit r), val_inv := (_ : ↑C ↑(normUnit r)⁻¹ * ↑C ↑(normUnit r) = 1),
inv_val := (_ : ↑C ↑(normUnit r) * ↑C ↑(normUnit r)⁻¹ = 1) } =
primPart (↑C r)
[PROOFSTEP]
apply mul_left_cancel₀ h0
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0✝ : ¬r = 0
h0 : ¬↑C (↑normalize r) = 0
⊢ ↑C (↑normalize r) *
↑{ val := ↑C ↑(normUnit r)⁻¹, inv := ↑C ↑(normUnit r), val_inv := (_ : ↑C ↑(normUnit r)⁻¹ * ↑C ↑(normUnit r) = 1),
inv_val := (_ : ↑C ↑(normUnit r) * ↑C ↑(normUnit r)⁻¹ = 1) } =
↑C (↑normalize r) * primPart (↑C r)
[PROOFSTEP]
conv_rhs => rw [← content_C, ← (C r).eq_C_content_mul_primPart]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0✝ : ¬r = 0
h0 : ¬↑C (↑normalize r) = 0
| ↑C (↑normalize r) * primPart (↑C r)
[PROOFSTEP]
rw [← content_C, ← (C r).eq_C_content_mul_primPart]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0✝ : ¬r = 0
h0 : ¬↑C (↑normalize r) = 0
| ↑C (↑normalize r) * primPart (↑C r)
[PROOFSTEP]
rw [← content_C, ← (C r).eq_C_content_mul_primPart]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0✝ : ¬r = 0
h0 : ¬↑C (↑normalize r) = 0
| ↑C (↑normalize r) * primPart (↑C r)
[PROOFSTEP]
rw [← content_C, ← (C r).eq_C_content_mul_primPart]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0✝ : ¬r = 0
h0 : ¬↑C (↑normalize r) = 0
⊢ ↑C (↑normalize r) *
↑{ val := ↑C ↑(normUnit r)⁻¹, inv := ↑C ↑(normUnit r), val_inv := (_ : ↑C ↑(normUnit r)⁻¹ * ↑C ↑(normUnit r) = 1),
inv_val := (_ : ↑C ↑(normUnit r) * ↑C ↑(normUnit r)⁻¹ = 1) } =
↑C r
[PROOFSTEP]
simp only [Units.val_mk, normalize_apply, RingHom.map_mul]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
r : R
h0✝ : ¬r = 0
h0 : ¬↑C (↑normalize r) = 0
⊢ ↑C r * ↑C ↑(normUnit r) * ↑C ↑(normUnit r)⁻¹ = ↑C r
[PROOFSTEP]
rw [mul_assoc, ← RingHom.map_mul, Units.mul_inv, C_1, mul_one]
[GOAL]
R : Type u_1
inst✝⁶ : CommRing R
inst✝⁵ : IsDomain R
inst✝⁴ : NormalizedGCDMonoid R
S : Type u_2
inst✝³ : Ring S
inst✝² : IsDomain S
inst✝¹ : Algebra R S
inst✝ : NoZeroSMulDivisors R S
p : R[X]
s : S
hpzero : p ≠ 0
hp : ↑(aeval s) p = 0
⊢ ↑(aeval s) (primPart p) = 0
[PROOFSTEP]
rw [eq_C_content_mul_primPart p, map_mul, aeval_C] at hp
[GOAL]
R : Type u_1
inst✝⁶ : CommRing R
inst✝⁵ : IsDomain R
inst✝⁴ : NormalizedGCDMonoid R
S : Type u_2
inst✝³ : Ring S
inst✝² : IsDomain S
inst✝¹ : Algebra R S
inst✝ : NoZeroSMulDivisors R S
p : R[X]
s : S
hpzero : p ≠ 0
hp : ↑(algebraMap R S) (content p) * ↑(aeval s) (primPart p) = 0
⊢ ↑(aeval s) (primPart p) = 0
[PROOFSTEP]
have hcont : p.content ≠ 0 := fun h => hpzero (content_eq_zero_iff.1 h)
[GOAL]
R : Type u_1
inst✝⁶ : CommRing R
inst✝⁵ : IsDomain R
inst✝⁴ : NormalizedGCDMonoid R
S : Type u_2
inst✝³ : Ring S
inst✝² : IsDomain S
inst✝¹ : Algebra R S
inst✝ : NoZeroSMulDivisors R S
p : R[X]
s : S
hpzero : p ≠ 0
hp : ↑(algebraMap R S) (content p) * ↑(aeval s) (primPart p) = 0
hcont : content p ≠ 0
⊢ ↑(aeval s) (primPart p) = 0
[PROOFSTEP]
replace hcont := Function.Injective.ne (NoZeroSMulDivisors.algebraMap_injective R S) hcont
[GOAL]
R : Type u_1
inst✝⁶ : CommRing R
inst✝⁵ : IsDomain R
inst✝⁴ : NormalizedGCDMonoid R
S : Type u_2
inst✝³ : Ring S
inst✝² : IsDomain S
inst✝¹ : Algebra R S
inst✝ : NoZeroSMulDivisors R S
p : R[X]
s : S
hpzero : p ≠ 0
hp : ↑(algebraMap R S) (content p) * ↑(aeval s) (primPart p) = 0
hcont : ↑(algebraMap R S) (content p) ≠ ↑(algebraMap R S) 0
⊢ ↑(aeval s) (primPart p) = 0
[PROOFSTEP]
rw [map_zero] at hcont
[GOAL]
R : Type u_1
inst✝⁶ : CommRing R
inst✝⁵ : IsDomain R
inst✝⁴ : NormalizedGCDMonoid R
S : Type u_2
inst✝³ : Ring S
inst✝² : IsDomain S
inst✝¹ : Algebra R S
inst✝ : NoZeroSMulDivisors R S
p : R[X]
s : S
hpzero : p ≠ 0
hp : ↑(algebraMap R S) (content p) * ↑(aeval s) (primPart p) = 0
hcont : ↑(algebraMap R S) (content p) ≠ 0
⊢ ↑(aeval s) (primPart p) = 0
[PROOFSTEP]
exact eq_zero_of_ne_zero_of_mul_left_eq_zero hcont hp
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
inst✝³ : IsDomain R
inst✝² : NormalizedGCDMonoid R
S : Type u_2
inst✝¹ : CommRing S
inst✝ : IsDomain S
f : R →+* S
hinj : Function.Injective ↑f
p : R[X]
s : S
hpzero : p ≠ 0
hp : eval₂ f s p = 0
⊢ eval₂ f s (primPart p) = 0
[PROOFSTEP]
rw [eq_C_content_mul_primPart p, eval₂_mul, eval₂_C] at hp
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
inst✝³ : IsDomain R
inst✝² : NormalizedGCDMonoid R
S : Type u_2
inst✝¹ : CommRing S
inst✝ : IsDomain S
f : R →+* S
hinj : Function.Injective ↑f
p : R[X]
s : S
hpzero : p ≠ 0
hp : ↑f (content p) * eval₂ f s (primPart p) = 0
⊢ eval₂ f s (primPart p) = 0
[PROOFSTEP]
have hcont : p.content ≠ 0 := fun h => hpzero (content_eq_zero_iff.1 h)
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
inst✝³ : IsDomain R
inst✝² : NormalizedGCDMonoid R
S : Type u_2
inst✝¹ : CommRing S
inst✝ : IsDomain S
f : R →+* S
hinj : Function.Injective ↑f
p : R[X]
s : S
hpzero : p ≠ 0
hp : ↑f (content p) * eval₂ f s (primPart p) = 0
hcont : content p ≠ 0
⊢ eval₂ f s (primPart p) = 0
[PROOFSTEP]
replace hcont := Function.Injective.ne hinj hcont
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
inst✝³ : IsDomain R
inst✝² : NormalizedGCDMonoid R
S : Type u_2
inst✝¹ : CommRing S
inst✝ : IsDomain S
f : R →+* S
hinj : Function.Injective ↑f
p : R[X]
s : S
hpzero : p ≠ 0
hp : ↑f (content p) * eval₂ f s (primPart p) = 0
hcont : ↑f (content p) ≠ ↑f 0
⊢ eval₂ f s (primPart p) = 0
[PROOFSTEP]
rw [map_zero] at hcont
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
inst✝³ : IsDomain R
inst✝² : NormalizedGCDMonoid R
S : Type u_2
inst✝¹ : CommRing S
inst✝ : IsDomain S
f : R →+* S
hinj : Function.Injective ↑f
p : R[X]
s : S
hpzero : p ≠ 0
hp : ↑f (content p) * eval₂ f s (primPart p) = 0
hcont : ↑f (content p) ≠ 0
⊢ eval₂ f s (primPart p) = 0
[PROOFSTEP]
exact eq_zero_of_ne_zero_of_mul_left_eq_zero hcont hp
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
a : R
p q : R[X]
h : ↑C a ∣ p - q
⊢ gcd a (content p) = gcd a (content q)
[PROOFSTEP]
rw [content_eq_gcd_range_of_lt p (max p.natDegree q.natDegree).succ
(lt_of_le_of_lt (le_max_left _ _) (Nat.lt_succ_self _))]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
a : R
p q : R[X]
h : ↑C a ∣ p - q
⊢ gcd a (Finset.gcd (Finset.range (Nat.succ (max (natDegree p) (natDegree q)))) (coeff p)) = gcd a (content q)
[PROOFSTEP]
rw [content_eq_gcd_range_of_lt q (max p.natDegree q.natDegree).succ
(lt_of_le_of_lt (le_max_right _ _) (Nat.lt_succ_self _))]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
a : R
p q : R[X]
h : ↑C a ∣ p - q
⊢ gcd a (Finset.gcd (Finset.range (Nat.succ (max (natDegree p) (natDegree q)))) (coeff p)) =
gcd a (Finset.gcd (Finset.range (Nat.succ (max (natDegree p) (natDegree q)))) (coeff q))
[PROOFSTEP]
apply Finset.gcd_eq_of_dvd_sub
[GOAL]
case h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
a : R
p q : R[X]
h : ↑C a ∣ p - q
⊢ ∀ (x : ℕ), x ∈ Finset.range (Nat.succ (max (natDegree p) (natDegree q))) → a ∣ coeff p x - coeff q x
[PROOFSTEP]
intro x _
[GOAL]
case h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
a : R
p q : R[X]
h : ↑C a ∣ p - q
x : ℕ
a✝ : x ∈ Finset.range (Nat.succ (max (natDegree p) (natDegree q)))
⊢ a ∣ coeff p x - coeff q x
[PROOFSTEP]
cases' h with w hw
[GOAL]
case h.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
a : R
p q : R[X]
x : ℕ
a✝ : x ∈ Finset.range (Nat.succ (max (natDegree p) (natDegree q)))
w : (fun x => R[X]) a
hw : p - q = ↑C a * w
⊢ a ∣ coeff p x - coeff q x
[PROOFSTEP]
use w.coeff x
[GOAL]
case h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
a : R
p q : R[X]
x : ℕ
a✝ : x ∈ Finset.range (Nat.succ (max (natDegree p) (natDegree q)))
w : (fun x => R[X]) a
hw : p - q = ↑C a * w
⊢ coeff p x - coeff q x = a * coeff w x
[PROOFSTEP]
rw [← coeff_sub, hw, coeff_C_mul]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
⊢ gcd (content (eraseLead (p * q))) (leadingCoeff p) = gcd (content (eraseLead p * q)) (leadingCoeff p)
[PROOFSTEP]
rw [gcd_comm (content _) _, gcd_comm (content _) _]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
⊢ gcd (leadingCoeff p) (content (eraseLead (p * q))) = gcd (leadingCoeff p) (content (eraseLead p * q))
[PROOFSTEP]
apply gcd_content_eq_of_dvd_sub
[GOAL]
case h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
⊢ ↑C (leadingCoeff p) ∣ eraseLead (p * q) - eraseLead p * q
[PROOFSTEP]
rw [← self_sub_C_mul_X_pow, ← self_sub_C_mul_X_pow, sub_mul, sub_sub, add_comm, sub_add, sub_sub_cancel,
leadingCoeff_mul, RingHom.map_mul, mul_assoc, mul_assoc]
[GOAL]
case h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
⊢ ↑C (leadingCoeff p) ∣
↑C (leadingCoeff p) * (X ^ natDegree p * q) - ↑C (leadingCoeff p) * (↑C (leadingCoeff q) * X ^ natDegree (p * q))
[PROOFSTEP]
apply dvd_sub (Dvd.intro _ rfl) (Dvd.intro _ rfl)
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
⊢ content (p * q) = content p * content q
[PROOFSTEP]
classical
suffices h : ∀ (n : ℕ) (p q : R[X]), (p * q).degree < n → (p * q).content = p.content * q.content
· apply h
apply lt_of_le_of_lt degree_le_natDegree (WithBot.coe_lt_coe.2 (Nat.lt_succ_self _))
intro n
induction' n with n ih
· intro p q hpq
dsimp at hpq
rw [Nat.cast_withBot, WithBot.coe_zero, Nat.WithBot.lt_zero_iff, degree_eq_bot, mul_eq_zero] at hpq
rcases hpq with (rfl | rfl) <;> simp
intro p q hpq
by_cases p0 : p = 0
· simp [p0]
by_cases q0 : q = 0
· simp [q0]
rw [degree_eq_natDegree (mul_ne_zero p0 q0), Nat.cast_withBot, Nat.cast_withBot, WithBot.coe_lt_coe,
Nat.lt_succ_iff_lt_or_eq, ← WithBot.coe_lt_coe, ← Nat.cast_withBot, ← degree_eq_natDegree (mul_ne_zero p0 q0),
natDegree_mul p0 q0] at hpq
rcases hpq with (hlt | heq)
· apply ih _ _ hlt
rw [← p.natDegree_primPart, ← q.natDegree_primPart, ← WithBot.coe_eq_coe, WithBot.coe_add, ← Nat.cast_withBot, ←
degree_eq_natDegree p.primPart_ne_zero, ← Nat.cast_withBot, ← degree_eq_natDegree q.primPart_ne_zero] at heq
rw [p.eq_C_content_mul_primPart, q.eq_C_content_mul_primPart]
suffices h : (q.primPart * p.primPart).content = 1
·
rw [mul_assoc, content_C_mul, content_C_mul, mul_comm p.primPart, mul_assoc, content_C_mul, content_C_mul, h, mul_one,
content_primPart, content_primPart, mul_one, mul_one]
rw [← normalize_content, normalize_eq_one, isUnit_iff_dvd_one, content_eq_gcd_leadingCoeff_content_eraseLead,
leadingCoeff_mul, gcd_comm]
apply (gcd_mul_dvd_mul_gcd _ _ _).trans
rw [content_mul_aux, ih, content_primPart, mul_one, gcd_comm, ← content_eq_gcd_leadingCoeff_content_eraseLead,
content_primPart, one_mul, mul_comm q.primPart, content_mul_aux, ih, content_primPart, mul_one, gcd_comm, ←
content_eq_gcd_leadingCoeff_content_eraseLead, content_primPart]
· rw [Nat.cast_withBot, ← heq, degree_mul, WithBot.add_lt_add_iff_right]
· apply degree_erase_lt p.primPart_ne_zero
· rw [Ne.def, degree_eq_bot]
apply q.primPart_ne_zero
· rw [mul_comm, Nat.cast_withBot, ← heq, degree_mul, WithBot.add_lt_add_iff_left]
· apply degree_erase_lt q.primPart_ne_zero
· rw [Ne.def, degree_eq_bot]
apply p.primPart_ne_zero
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
⊢ content (p * q) = content p * content q
[PROOFSTEP]
suffices h : ∀ (n : ℕ) (p q : R[X]), (p * q).degree < n → (p * q).content = p.content * q.content
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
h : ∀ (n : ℕ) (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
⊢ content (p * q) = content p * content q
[PROOFSTEP]
apply h
[GOAL]
case a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
h : ∀ (n : ℕ) (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
⊢ degree (p * q) < ↑?n
case n
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
h : ∀ (n : ℕ) (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
⊢ ℕ
[PROOFSTEP]
apply lt_of_le_of_lt degree_le_natDegree (WithBot.coe_lt_coe.2 (Nat.lt_succ_self _))
[GOAL]
case h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
⊢ ∀ (n : ℕ) (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
[PROOFSTEP]
intro n
[GOAL]
case h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
n : ℕ
⊢ ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
[PROOFSTEP]
induction' n with n ih
[GOAL]
case h.zero
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
⊢ ∀ (p q : R[X]), degree (p * q) < ↑Nat.zero → content (p * q) = content p * content q
[PROOFSTEP]
intro p q hpq
[GOAL]
case h.zero
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ p q : R[X]
hpq : degree (p * q) < ↑Nat.zero
⊢ content (p * q) = content p * content q
[PROOFSTEP]
dsimp at hpq
[GOAL]
case h.zero
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ p q : R[X]
hpq : degree (p * q) < ↑0
⊢ content (p * q) = content p * content q
[PROOFSTEP]
rw [Nat.cast_withBot, WithBot.coe_zero, Nat.WithBot.lt_zero_iff, degree_eq_bot, mul_eq_zero] at hpq
[GOAL]
case h.zero
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ p q : R[X]
hpq : p = 0 ∨ q = 0
⊢ content (p * q) = content p * content q
[PROOFSTEP]
rcases hpq with (rfl | rfl)
[GOAL]
case h.zero.inl
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q✝ q : R[X]
⊢ content (0 * q) = content 0 * content q
[PROOFSTEP]
simp
[GOAL]
case h.zero.inr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q p : R[X]
⊢ content (p * 0) = content p * content 0
[PROOFSTEP]
simp
[GOAL]
case h.succ
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
⊢ ∀ (p q : R[X]), degree (p * q) < ↑(Nat.succ n) → content (p * q) = content p * content q
[PROOFSTEP]
intro p q hpq
[GOAL]
case h.succ
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
hpq : degree (p * q) < ↑(Nat.succ n)
⊢ content (p * q) = content p * content q
[PROOFSTEP]
by_cases p0 : p = 0
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
hpq : degree (p * q) < ↑(Nat.succ n)
p0 : p = 0
⊢ content (p * q) = content p * content q
[PROOFSTEP]
simp [p0]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
hpq : degree (p * q) < ↑(Nat.succ n)
p0 : ¬p = 0
⊢ content (p * q) = content p * content q
[PROOFSTEP]
by_cases q0 : q = 0
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
hpq : degree (p * q) < ↑(Nat.succ n)
p0 : ¬p = 0
q0 : q = 0
⊢ content (p * q) = content p * content q
[PROOFSTEP]
simp [q0]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
hpq : degree (p * q) < ↑(Nat.succ n)
p0 : ¬p = 0
q0 : ¬q = 0
⊢ content (p * q) = content p * content q
[PROOFSTEP]
rw [degree_eq_natDegree (mul_ne_zero p0 q0), Nat.cast_withBot, Nat.cast_withBot, WithBot.coe_lt_coe,
Nat.lt_succ_iff_lt_or_eq, ← WithBot.coe_lt_coe, ← Nat.cast_withBot, ← degree_eq_natDegree (mul_ne_zero p0 q0),
natDegree_mul p0 q0] at hpq
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
hpq : degree (p * q) < ↑n ∨ natDegree p + natDegree q = n
p0 : ¬p = 0
q0 : ¬q = 0
⊢ content (p * q) = content p * content q
[PROOFSTEP]
rcases hpq with (hlt | heq)
[GOAL]
case neg.inl
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
hlt : degree (p * q) < ↑n
⊢ content (p * q) = content p * content q
[PROOFSTEP]
apply ih _ _ hlt
[GOAL]
case neg.inr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : natDegree p + natDegree q = n
⊢ content (p * q) = content p * content q
[PROOFSTEP]
rw [← p.natDegree_primPart, ← q.natDegree_primPart, ← WithBot.coe_eq_coe, WithBot.coe_add, ← Nat.cast_withBot, ←
degree_eq_natDegree p.primPart_ne_zero, ← Nat.cast_withBot, ← degree_eq_natDegree q.primPart_ne_zero] at heq
[GOAL]
case neg.inr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : degree (primPart p) + degree (primPart q) = ↑n
⊢ content (p * q) = content p * content q
[PROOFSTEP]
rw [p.eq_C_content_mul_primPart, q.eq_C_content_mul_primPart]
[GOAL]
case neg.inr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : degree (primPart p) + degree (primPart q) = ↑n
⊢ content (↑C (content p) * primPart p * (↑C (content q) * primPart q)) =
content (↑C (content p) * primPart p) * content (↑C (content q) * primPart q)
[PROOFSTEP]
suffices h : (q.primPart * p.primPart).content = 1
[GOAL]
case neg.inr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : degree (primPart p) + degree (primPart q) = ↑n
h : content (primPart q * primPart p) = 1
⊢ content (↑C (content p) * primPart p * (↑C (content q) * primPart q)) =
content (↑C (content p) * primPart p) * content (↑C (content q) * primPart q)
[PROOFSTEP]
rw [mul_assoc, content_C_mul, content_C_mul, mul_comm p.primPart, mul_assoc, content_C_mul, content_C_mul, h, mul_one,
content_primPart, content_primPart, mul_one, mul_one]
[GOAL]
case h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : degree (primPart p) + degree (primPart q) = ↑n
⊢ content (primPart q * primPart p) = 1
[PROOFSTEP]
rw [← normalize_content, normalize_eq_one, isUnit_iff_dvd_one, content_eq_gcd_leadingCoeff_content_eraseLead,
leadingCoeff_mul, gcd_comm]
[GOAL]
case h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : degree (primPart p) + degree (primPart q) = ↑n
⊢ gcd (content (eraseLead (primPart q * primPart p))) (leadingCoeff (primPart q) * leadingCoeff (primPart p)) ∣ 1
[PROOFSTEP]
apply (gcd_mul_dvd_mul_gcd _ _ _).trans
[GOAL]
case h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : degree (primPart p) + degree (primPart q) = ↑n
⊢ gcd (content (eraseLead (primPart q * primPart p))) (leadingCoeff (primPart q)) *
gcd (content (eraseLead (primPart q * primPart p))) (leadingCoeff (primPart p)) ∣
1
[PROOFSTEP]
rw [content_mul_aux, ih, content_primPart, mul_one, gcd_comm, ← content_eq_gcd_leadingCoeff_content_eraseLead,
content_primPart, one_mul, mul_comm q.primPart, content_mul_aux, ih, content_primPart, mul_one, gcd_comm, ←
content_eq_gcd_leadingCoeff_content_eraseLead, content_primPart]
[GOAL]
case h.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : degree (primPart p) + degree (primPart q) = ↑n
⊢ degree (eraseLead (primPart p) * primPart q) < ↑n
[PROOFSTEP]
rw [Nat.cast_withBot, ← heq, degree_mul, WithBot.add_lt_add_iff_right]
[GOAL]
case h.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : degree (primPart p) + degree (primPart q) = ↑n
⊢ degree (eraseLead (primPart p)) < degree (primPart p)
[PROOFSTEP]
apply degree_erase_lt p.primPart_ne_zero
[GOAL]
case h.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : degree (primPart p) + degree (primPart q) = ↑n
⊢ degree (primPart q) ≠ ⊥
[PROOFSTEP]
rw [Ne.def, degree_eq_bot]
[GOAL]
case h.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : degree (primPart p) + degree (primPart q) = ↑n
⊢ ¬primPart q = 0
[PROOFSTEP]
apply q.primPart_ne_zero
[GOAL]
case h.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : degree (primPart p) + degree (primPart q) = ↑n
⊢ degree (eraseLead (primPart q) * primPart p) < ↑n
[PROOFSTEP]
rw [mul_comm, Nat.cast_withBot, ← heq, degree_mul, WithBot.add_lt_add_iff_left]
[GOAL]
case h.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : degree (primPart p) + degree (primPart q) = ↑n
⊢ degree (eraseLead (primPart q)) < degree (primPart q)
[PROOFSTEP]
apply degree_erase_lt q.primPart_ne_zero
[GOAL]
case h.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : degree (primPart p) + degree (primPart q) = ↑n
⊢ degree (primPart p) ≠ ⊥
[PROOFSTEP]
rw [Ne.def, degree_eq_bot]
[GOAL]
case h.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p✝ q✝ : R[X]
n : ℕ
ih : ∀ (p q : R[X]), degree (p * q) < ↑n → content (p * q) = content p * content q
p q : R[X]
p0 : ¬p = 0
q0 : ¬q = 0
heq : degree (primPart p) + degree (primPart q) = ↑n
⊢ ¬primPart p = 0
[PROOFSTEP]
apply p.primPart_ne_zero
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
⊢ IsPrimitive (p * q)
[PROOFSTEP]
rw [isPrimitive_iff_content_eq_one, content_mul, hp.content_eq_one, hq.content_eq_one, mul_one]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
h0 : p * q ≠ 0
⊢ primPart (p * q) = primPart p * primPart q
[PROOFSTEP]
rw [Ne.def, ← content_eq_zero_iff, ← C_eq_zero] at h0
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
h0✝ : ¬p * q = 0
h0 : ¬↑C (content (p * q)) = 0
⊢ primPart (p * q) = primPart p * primPart q
[PROOFSTEP]
apply mul_left_cancel₀ h0
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
h0✝ : ¬p * q = 0
h0 : ¬↑C (content (p * q)) = 0
⊢ ↑C (content (p * q)) * primPart (p * q) = ↑C (content (p * q)) * (primPart p * primPart q)
[PROOFSTEP]
conv_lhs => rw [← (p * q).eq_C_content_mul_primPart, p.eq_C_content_mul_primPart, q.eq_C_content_mul_primPart]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
h0✝ : ¬p * q = 0
h0 : ¬↑C (content (p * q)) = 0
| ↑C (content (p * q)) * primPart (p * q)
[PROOFSTEP]
rw [← (p * q).eq_C_content_mul_primPart, p.eq_C_content_mul_primPart, q.eq_C_content_mul_primPart]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
h0✝ : ¬p * q = 0
h0 : ¬↑C (content (p * q)) = 0
| ↑C (content (p * q)) * primPart (p * q)
[PROOFSTEP]
rw [← (p * q).eq_C_content_mul_primPart, p.eq_C_content_mul_primPart, q.eq_C_content_mul_primPart]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
h0✝ : ¬p * q = 0
h0 : ¬↑C (content (p * q)) = 0
| ↑C (content (p * q)) * primPart (p * q)
[PROOFSTEP]
rw [← (p * q).eq_C_content_mul_primPart, p.eq_C_content_mul_primPart, q.eq_C_content_mul_primPart]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
h0✝ : ¬p * q = 0
h0 : ¬↑C (content (p * q)) = 0
⊢ ↑C (content p) * primPart p * (↑C (content q) * primPart q) = ↑C (content (p * q)) * (primPart p * primPart q)
[PROOFSTEP]
rw [content_mul, RingHom.map_mul]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
h0✝ : ¬p * q = 0
h0 : ¬↑C (content (p * q)) = 0
⊢ ↑C (content p) * primPart p * (↑C (content q) * primPart q) =
↑C (content p) * ↑C (content q) * (primPart p * primPart q)
[PROOFSTEP]
ring
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : q ≠ 0
⊢ p ∣ primPart q ↔ p ∣ q
[PROOFSTEP]
refine' ⟨fun h => h.trans (Dvd.intro_left _ q.eq_C_content_mul_primPart.symm), fun h => _⟩
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : q ≠ 0
h : p ∣ q
⊢ p ∣ primPart q
[PROOFSTEP]
rcases h with ⟨r, rfl⟩
[GOAL]
case intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
hp : IsPrimitive p
r : R[X]
hq : p * r ≠ 0
⊢ p ∣ primPart (p * r)
[PROOFSTEP]
apply Dvd.intro _
[GOAL]
case intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
hp : IsPrimitive p
r : R[X]
hq : p * r ≠ 0
⊢ p * ?m.658553 = primPart (p * r)
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
hp : IsPrimitive p
r : R[X]
hq : p * r ≠ 0
⊢ R[X]
[PROOFSTEP]
rw [primPart_mul hq, hp.primPart_eq]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
⊢ ∃ r, IsPrimitive r ∧ ∀ (s : R[X]), p ∣ s ∧ q ∣ s ↔ r ∣ s
[PROOFSTEP]
classical
have h : ∃ (n : ℕ) (r : R[X]), r.natDegree = n ∧ r.IsPrimitive ∧ p ∣ r ∧ q ∣ r :=
⟨(p * q).natDegree, p * q, rfl, hp.mul hq, dvd_mul_right _ _, dvd_mul_left _ _⟩
rcases Nat.find_spec h with ⟨r, rdeg, rprim, pr, qr⟩
refine' ⟨r, rprim, fun s => ⟨_, fun rs => ⟨pr.trans rs, qr.trans rs⟩⟩⟩
suffices hs : ∀ (n : ℕ) (s : R[X]), s.natDegree = n → p ∣ s ∧ q ∣ s → r ∣ s
· apply hs s.natDegree s rfl
clear s
by_contra' con
rcases Nat.find_spec con with ⟨s, sdeg, ⟨ps, qs⟩, rs⟩
have s0 : s ≠ 0 := by
contrapose! rs
simp [rs]
have hs :=
Nat.find_min' h
⟨_, s.natDegree_primPart, s.isPrimitive_primPart, (hp.dvd_primPart_iff_dvd s0).2 ps,
(hq.dvd_primPart_iff_dvd s0).2 qs⟩
rw [← rdeg] at hs
by_cases sC : s.natDegree ≤ 0
· rw [eq_C_of_natDegree_le_zero (le_trans hs sC), isPrimitive_iff_content_eq_one, content_C, normalize_eq_one] at rprim
rw [eq_C_of_natDegree_le_zero (le_trans hs sC), ← dvd_content_iff_C_dvd] at rs
apply rs rprim.dvd
have hcancel := natDegree_cancelLeads_lt_of_natDegree_le_natDegree hs (lt_of_not_ge sC)
rw [sdeg] at hcancel
apply Nat.find_min con hcancel
refine' ⟨_, rfl, ⟨dvd_cancelLeads_of_dvd_of_dvd pr ps, dvd_cancelLeads_of_dvd_of_dvd qr qs⟩, fun rcs => rs _⟩
rw [← rprim.dvd_primPart_iff_dvd s0]
rw [cancelLeads, tsub_eq_zero_iff_le.mpr hs, pow_zero, mul_one] at rcs
have h := dvd_add rcs (Dvd.intro_left (C (leadingCoeff s) * X ^ (natDegree s - natDegree r)) rfl)
have hC0 := rprim.ne_zero
rw [Ne.def, ← leadingCoeff_eq_zero, ← C_eq_zero] at hC0
rw [sub_add_cancel, ← rprim.dvd_primPart_iff_dvd (mul_ne_zero hC0 s0)] at h
rcases isUnit_primPart_C r.leadingCoeff with ⟨u, hu⟩
apply h.trans (Associated.symm ⟨u, _⟩).dvd
rw [primPart_mul (mul_ne_zero hC0 s0), hu, mul_comm]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
⊢ ∃ r, IsPrimitive r ∧ ∀ (s : R[X]), p ∣ s ∧ q ∣ s ↔ r ∣ s
[PROOFSTEP]
have h : ∃ (n : ℕ) (r : R[X]), r.natDegree = n ∧ r.IsPrimitive ∧ p ∣ r ∧ q ∣ r :=
⟨(p * q).natDegree, p * q, rfl, hp.mul hq, dvd_mul_right _ _, dvd_mul_left _ _⟩
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
⊢ ∃ r, IsPrimitive r ∧ ∀ (s : R[X]), p ∣ s ∧ q ∣ s ↔ r ∣ s
[PROOFSTEP]
rcases Nat.find_spec h with ⟨r, rdeg, rprim, pr, qr⟩
[GOAL]
case intro.intro.intro.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
⊢ ∃ r, IsPrimitive r ∧ ∀ (s : R[X]), p ∣ s ∧ q ∣ s ↔ r ∣ s
[PROOFSTEP]
refine' ⟨r, rprim, fun s => ⟨_, fun rs => ⟨pr.trans rs, qr.trans rs⟩⟩⟩
[GOAL]
case intro.intro.intro.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
s : R[X]
⊢ p ∣ s ∧ q ∣ s → r ∣ s
[PROOFSTEP]
suffices hs : ∀ (n : ℕ) (s : R[X]), s.natDegree = n → p ∣ s ∧ q ∣ s → r ∣ s
[GOAL]
case intro.intro.intro.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
s : R[X]
hs : ∀ (n : ℕ) (s : R[X]), natDegree s = n → p ∣ s ∧ q ∣ s → r ∣ s
⊢ p ∣ s ∧ q ∣ s → r ∣ s
[PROOFSTEP]
apply hs s.natDegree s rfl
[GOAL]
case hs
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
s : R[X]
⊢ ∀ (n : ℕ) (s : R[X]), natDegree s = n → p ∣ s ∧ q ∣ s → r ∣ s
[PROOFSTEP]
clear s
[GOAL]
case hs
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
⊢ ∀ (n : ℕ) (s : R[X]), natDegree s = n → p ∣ s ∧ q ∣ s → r ∣ s
[PROOFSTEP]
by_contra' con
[GOAL]
case hs
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
⊢ False
[PROOFSTEP]
rcases Nat.find_spec con with ⟨s, sdeg, ⟨ps, qs⟩, rs⟩
[GOAL]
case hs.intro.intro.intro.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
⊢ False
[PROOFSTEP]
have s0 : s ≠ 0 := by
contrapose! rs
simp [rs]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
⊢ s ≠ 0
[PROOFSTEP]
contrapose! rs
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
ps : p ∣ s
qs : q ∣ s
rs : s = 0
⊢ r ∣ s
[PROOFSTEP]
simp [rs]
[GOAL]
case hs.intro.intro.intro.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
⊢ False
[PROOFSTEP]
have hs :=
Nat.find_min' h
⟨_, s.natDegree_primPart, s.isPrimitive_primPart, (hp.dvd_primPart_iff_dvd s0).2 ps,
(hq.dvd_primPart_iff_dvd s0).2 qs⟩
[GOAL]
case hs.intro.intro.intro.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : Nat.find h ≤ natDegree s
⊢ False
[PROOFSTEP]
rw [← rdeg] at hs
[GOAL]
case hs.intro.intro.intro.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
⊢ False
[PROOFSTEP]
by_cases sC : s.natDegree ≤ 0
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : natDegree s ≤ 0
⊢ False
[PROOFSTEP]
rw [eq_C_of_natDegree_le_zero (le_trans hs sC), isPrimitive_iff_content_eq_one, content_C, normalize_eq_one] at rprim
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim✝ : IsPrimitive (↑C (coeff r 0))
rprim : IsUnit (coeff r 0)
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : natDegree s ≤ 0
⊢ False
[PROOFSTEP]
rw [eq_C_of_natDegree_le_zero (le_trans hs sC), ← dvd_content_iff_C_dvd] at rs
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim✝ : IsPrimitive (↑C (coeff r 0))
rprim : IsUnit (coeff r 0)
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs✝ : ¬↑C (coeff r 0) ∣ s
rs : ¬coeff r 0 ∣ content s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : natDegree s ≤ 0
⊢ False
[PROOFSTEP]
apply rs rprim.dvd
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : ¬natDegree s ≤ 0
⊢ False
[PROOFSTEP]
have hcancel := natDegree_cancelLeads_lt_of_natDegree_le_natDegree hs (lt_of_not_ge sC)
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : ¬natDegree s ≤ 0
hcancel : natDegree (cancelLeads r s) < natDegree s
⊢ False
[PROOFSTEP]
rw [sdeg] at hcancel
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : ¬natDegree s ≤ 0
hcancel : natDegree (cancelLeads r s) < Nat.find con
⊢ False
[PROOFSTEP]
apply Nat.find_min con hcancel
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : ¬natDegree s ≤ 0
hcancel : natDegree (cancelLeads r s) < Nat.find con
⊢ ∃ s_1, natDegree s_1 = natDegree (cancelLeads r s) ∧ (p ∣ s_1 ∧ q ∣ s_1) ∧ ¬r ∣ s_1
[PROOFSTEP]
refine' ⟨_, rfl, ⟨dvd_cancelLeads_of_dvd_of_dvd pr ps, dvd_cancelLeads_of_dvd_of_dvd qr qs⟩, fun rcs => rs _⟩
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : ¬natDegree s ≤ 0
hcancel : natDegree (cancelLeads r s) < Nat.find con
rcs : r ∣ cancelLeads r s
⊢ r ∣ s
[PROOFSTEP]
rw [← rprim.dvd_primPart_iff_dvd s0]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : ¬natDegree s ≤ 0
hcancel : natDegree (cancelLeads r s) < Nat.find con
rcs : r ∣ cancelLeads r s
⊢ r ∣ primPart s
[PROOFSTEP]
rw [cancelLeads, tsub_eq_zero_iff_le.mpr hs, pow_zero, mul_one] at rcs
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : ¬natDegree s ≤ 0
hcancel : natDegree (cancelLeads r s) < Nat.find con
rcs : r ∣ ↑C (leadingCoeff r) * s - ↑C (leadingCoeff s) * X ^ (natDegree s - natDegree r) * r
⊢ r ∣ primPart s
[PROOFSTEP]
have h := dvd_add rcs (Dvd.intro_left (C (leadingCoeff s) * X ^ (natDegree s - natDegree r)) rfl)
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h✝ : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h✝
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : ¬natDegree s ≤ 0
hcancel : natDegree (cancelLeads r s) < Nat.find con
rcs : r ∣ ↑C (leadingCoeff r) * s - ↑C (leadingCoeff s) * X ^ (natDegree s - natDegree r) * r
h :
r ∣
↑C (leadingCoeff r) * s - ↑C (leadingCoeff s) * X ^ (natDegree s - natDegree r) * r +
↑C (leadingCoeff s) * X ^ (natDegree s - natDegree r) * r
⊢ r ∣ primPart s
[PROOFSTEP]
have hC0 := rprim.ne_zero
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h✝ : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h✝
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : ¬natDegree s ≤ 0
hcancel : natDegree (cancelLeads r s) < Nat.find con
rcs : r ∣ ↑C (leadingCoeff r) * s - ↑C (leadingCoeff s) * X ^ (natDegree s - natDegree r) * r
h :
r ∣
↑C (leadingCoeff r) * s - ↑C (leadingCoeff s) * X ^ (natDegree s - natDegree r) * r +
↑C (leadingCoeff s) * X ^ (natDegree s - natDegree r) * r
hC0 : r ≠ 0
⊢ r ∣ primPart s
[PROOFSTEP]
rw [Ne.def, ← leadingCoeff_eq_zero, ← C_eq_zero] at hC0
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h✝ : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h✝
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : ¬natDegree s ≤ 0
hcancel : natDegree (cancelLeads r s) < Nat.find con
rcs : r ∣ ↑C (leadingCoeff r) * s - ↑C (leadingCoeff s) * X ^ (natDegree s - natDegree r) * r
h :
r ∣
↑C (leadingCoeff r) * s - ↑C (leadingCoeff s) * X ^ (natDegree s - natDegree r) * r +
↑C (leadingCoeff s) * X ^ (natDegree s - natDegree r) * r
hC0 : ¬↑C (leadingCoeff r) = 0
⊢ r ∣ primPart s
[PROOFSTEP]
rw [sub_add_cancel, ← rprim.dvd_primPart_iff_dvd (mul_ne_zero hC0 s0)] at h
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h✝ : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h✝
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : ¬natDegree s ≤ 0
hcancel : natDegree (cancelLeads r s) < Nat.find con
rcs : r ∣ ↑C (leadingCoeff r) * s - ↑C (leadingCoeff s) * X ^ (natDegree s - natDegree r) * r
h : r ∣ primPart (↑C (leadingCoeff r) * s)
hC0 : ¬↑C (leadingCoeff r) = 0
⊢ r ∣ primPart s
[PROOFSTEP]
rcases isUnit_primPart_C r.leadingCoeff with ⟨u, hu⟩
[GOAL]
case neg.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h✝ : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h✝
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : ¬natDegree s ≤ 0
hcancel : natDegree (cancelLeads r s) < Nat.find con
rcs : r ∣ ↑C (leadingCoeff r) * s - ↑C (leadingCoeff s) * X ^ (natDegree s - natDegree r) * r
h : r ∣ primPart (↑C (leadingCoeff r) * s)
hC0 : ¬↑C (leadingCoeff r) = 0
u : R[X]ˣ
hu : ↑u = primPart (↑C (leadingCoeff r))
⊢ r ∣ primPart s
[PROOFSTEP]
apply h.trans (Associated.symm ⟨u, _⟩).dvd
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hp : IsPrimitive p
hq : IsPrimitive q
h✝ : ∃ n r, natDegree r = n ∧ IsPrimitive r ∧ p ∣ r ∧ q ∣ r
r : R[X]
rdeg : natDegree r = Nat.find h✝
rprim : IsPrimitive r
pr : p ∣ r
qr : q ∣ r
con : ∃ n s, natDegree s = n ∧ (p ∣ s ∧ q ∣ s) ∧ ¬r ∣ s
s : R[X]
sdeg : natDegree s = Nat.find con
rs : ¬r ∣ s
ps : p ∣ s
qs : q ∣ s
s0 : s ≠ 0
hs : natDegree r ≤ natDegree s
sC : ¬natDegree s ≤ 0
hcancel : natDegree (cancelLeads r s) < Nat.find con
rcs : r ∣ ↑C (leadingCoeff r) * s - ↑C (leadingCoeff s) * X ^ (natDegree s - natDegree r) * r
h : r ∣ primPart (↑C (leadingCoeff r) * s)
hC0 : ¬↑C (leadingCoeff r) = 0
u : R[X]ˣ
hu : ↑u = primPart (↑C (leadingCoeff r))
⊢ primPart s * ↑u = primPart (↑C (leadingCoeff r) * s)
[PROOFSTEP]
rw [primPart_mul (mul_ne_zero hC0 s0), hu, mul_comm]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hq : q ≠ 0
⊢ p ∣ q ↔ content p ∣ content q ∧ primPart p ∣ primPart q
[PROOFSTEP]
constructor
[GOAL]
case mp
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hq : q ≠ 0
⊢ p ∣ q → content p ∣ content q ∧ primPart p ∣ primPart q
[PROOFSTEP]
intro h
[GOAL]
case mpr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hq : q ≠ 0
⊢ content p ∣ content q ∧ primPart p ∣ primPart q → p ∣ q
[PROOFSTEP]
intro h
[GOAL]
case mp
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hq : q ≠ 0
h : p ∣ q
⊢ content p ∣ content q ∧ primPart p ∣ primPart q
[PROOFSTEP]
rcases h with ⟨r, rfl⟩
[GOAL]
case mp.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p r : R[X]
hq : p * r ≠ 0
⊢ content p ∣ content (p * r) ∧ primPart p ∣ primPart (p * r)
[PROOFSTEP]
rw [content_mul, p.isPrimitive_primPart.dvd_primPart_iff_dvd hq]
[GOAL]
case mp.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p r : R[X]
hq : p * r ≠ 0
⊢ content p ∣ content p * content r ∧ primPart p ∣ p * r
[PROOFSTEP]
exact ⟨Dvd.intro _ rfl, p.primPart_dvd.trans (Dvd.intro _ rfl)⟩
[GOAL]
case mpr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hq : q ≠ 0
h : content p ∣ content q ∧ primPart p ∣ primPart q
⊢ p ∣ q
[PROOFSTEP]
rw [p.eq_C_content_mul_primPart, q.eq_C_content_mul_primPart]
[GOAL]
case mpr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hq : q ≠ 0
h : content p ∣ content q ∧ primPart p ∣ primPart q
⊢ ↑C (content p) * primPart p ∣ ↑C (content q) * primPart q
[PROOFSTEP]
exact mul_dvd_mul (RingHom.map_dvd C h.1) h.2
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
⊢ ∃ c, ∀ (d : R[X]), p ∣ d ∧ q ∣ d ↔ c ∣ d
[PROOFSTEP]
rcases exists_primitive_lcm_of_isPrimitive p.isPrimitive_primPart q.isPrimitive_primPart with ⟨r, rprim, hr⟩
[GOAL]
case intro.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q r : R[X]
rprim : IsPrimitive r
hr : ∀ (s : R[X]), primPart p ∣ s ∧ primPart q ∣ s ↔ r ∣ s
⊢ ∃ c, ∀ (d : R[X]), p ∣ d ∧ q ∣ d ↔ c ∣ d
[PROOFSTEP]
refine' ⟨C (lcm p.content q.content) * r, fun s => _⟩
[GOAL]
case intro.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q r : R[X]
rprim : IsPrimitive r
hr : ∀ (s : R[X]), primPart p ∣ s ∧ primPart q ∣ s ↔ r ∣ s
s : R[X]
⊢ p ∣ s ∧ q ∣ s ↔ ↑C (lcm (content p) (content q)) * r ∣ s
[PROOFSTEP]
by_cases hs : s = 0
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q r : R[X]
rprim : IsPrimitive r
hr : ∀ (s : R[X]), primPart p ∣ s ∧ primPart q ∣ s ↔ r ∣ s
s : R[X]
hs : s = 0
⊢ p ∣ s ∧ q ∣ s ↔ ↑C (lcm (content p) (content q)) * r ∣ s
[PROOFSTEP]
simp [hs]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q r : R[X]
rprim : IsPrimitive r
hr : ∀ (s : R[X]), primPart p ∣ s ∧ primPart q ∣ s ↔ r ∣ s
s : R[X]
hs : ¬s = 0
⊢ p ∣ s ∧ q ∣ s ↔ ↑C (lcm (content p) (content q)) * r ∣ s
[PROOFSTEP]
by_cases hpq : C (lcm p.content q.content) = 0
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q r : R[X]
rprim : IsPrimitive r
hr : ∀ (s : R[X]), primPart p ∣ s ∧ primPart q ∣ s ↔ r ∣ s
s : R[X]
hs : ¬s = 0
hpq : ↑C (lcm (content p) (content q)) = 0
⊢ p ∣ s ∧ q ∣ s ↔ ↑C (lcm (content p) (content q)) * r ∣ s
[PROOFSTEP]
rw [C_eq_zero, lcm_eq_zero_iff, content_eq_zero_iff, content_eq_zero_iff] at hpq
[GOAL]
case pos
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q r : R[X]
rprim : IsPrimitive r
hr : ∀ (s : R[X]), primPart p ∣ s ∧ primPart q ∣ s ↔ r ∣ s
s : R[X]
hs : ¬s = 0
hpq : p = 0 ∨ q = 0
⊢ p ∣ s ∧ q ∣ s ↔ ↑C (lcm (content p) (content q)) * r ∣ s
[PROOFSTEP]
rcases hpq with (hpq | hpq)
[GOAL]
case pos.inl
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q r : R[X]
rprim : IsPrimitive r
hr : ∀ (s : R[X]), primPart p ∣ s ∧ primPart q ∣ s ↔ r ∣ s
s : R[X]
hs : ¬s = 0
hpq : p = 0
⊢ p ∣ s ∧ q ∣ s ↔ ↑C (lcm (content p) (content q)) * r ∣ s
[PROOFSTEP]
simp [hpq, hs]
[GOAL]
case pos.inr
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q r : R[X]
rprim : IsPrimitive r
hr : ∀ (s : R[X]), primPart p ∣ s ∧ primPart q ∣ s ↔ r ∣ s
s : R[X]
hs : ¬s = 0
hpq : q = 0
⊢ p ∣ s ∧ q ∣ s ↔ ↑C (lcm (content p) (content q)) * r ∣ s
[PROOFSTEP]
simp [hpq, hs]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q r : R[X]
rprim : IsPrimitive r
hr : ∀ (s : R[X]), primPart p ∣ s ∧ primPart q ∣ s ↔ r ∣ s
s : R[X]
hs : ¬s = 0
hpq : ¬↑C (lcm (content p) (content q)) = 0
⊢ p ∣ s ∧ q ∣ s ↔ ↑C (lcm (content p) (content q)) * r ∣ s
[PROOFSTEP]
iterate 3 rw [dvd_iff_content_dvd_content_and_primPart_dvd_primPart hs]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q r : R[X]
rprim : IsPrimitive r
hr : ∀ (s : R[X]), primPart p ∣ s ∧ primPart q ∣ s ↔ r ∣ s
s : R[X]
hs : ¬s = 0
hpq : ¬↑C (lcm (content p) (content q)) = 0
⊢ p ∣ s ∧ q ∣ s ↔ ↑C (lcm (content p) (content q)) * r ∣ s
[PROOFSTEP]
rw [dvd_iff_content_dvd_content_and_primPart_dvd_primPart hs]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q r : R[X]
rprim : IsPrimitive r
hr : ∀ (s : R[X]), primPart p ∣ s ∧ primPart q ∣ s ↔ r ∣ s
s : R[X]
hs : ¬s = 0
hpq : ¬↑C (lcm (content p) (content q)) = 0
⊢ (content p ∣ content s ∧ primPart p ∣ primPart s) ∧ q ∣ s ↔ ↑C (lcm (content p) (content q)) * r ∣ s
[PROOFSTEP]
rw [dvd_iff_content_dvd_content_and_primPart_dvd_primPart hs]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q r : R[X]
rprim : IsPrimitive r
hr : ∀ (s : R[X]), primPart p ∣ s ∧ primPart q ∣ s ↔ r ∣ s
s : R[X]
hs : ¬s = 0
hpq : ¬↑C (lcm (content p) (content q)) = 0
⊢ (content p ∣ content s ∧ primPart p ∣ primPart s) ∧ content q ∣ content s ∧ primPart q ∣ primPart s ↔
↑C (lcm (content p) (content q)) * r ∣ s
[PROOFSTEP]
rw [dvd_iff_content_dvd_content_and_primPart_dvd_primPart hs]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q r : R[X]
rprim : IsPrimitive r
hr : ∀ (s : R[X]), primPart p ∣ s ∧ primPart q ∣ s ↔ r ∣ s
s : R[X]
hs : ¬s = 0
hpq : ¬↑C (lcm (content p) (content q)) = 0
⊢ (content p ∣ content s ∧ primPart p ∣ primPart s) ∧ content q ∣ content s ∧ primPart q ∣ primPart s ↔
content (↑C (lcm (content p) (content q)) * r) ∣ content s ∧
primPart (↑C (lcm (content p) (content q)) * r) ∣ primPart s
[PROOFSTEP]
rw [content_mul, rprim.content_eq_one, mul_one, content_C, normalize_lcm, lcm_dvd_iff,
primPart_mul (mul_ne_zero hpq rprim.ne_zero), rprim.primPart_eq,
IsUnit.mul_left_dvd _ _ _ (isUnit_primPart_C (lcm p.content q.content)), ← hr s.primPart]
[GOAL]
case neg
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q r : R[X]
rprim : IsPrimitive r
hr : ∀ (s : R[X]), primPart p ∣ s ∧ primPart q ∣ s ↔ r ∣ s
s : R[X]
hs : ¬s = 0
hpq : ¬↑C (lcm (content p) (content q)) = 0
⊢ (content p ∣ content s ∧ primPart p ∣ primPart s) ∧ content q ∣ content s ∧ primPart q ∣ primPart s ↔
(content p ∣ content s ∧ content q ∣ content s) ∧ primPart p ∣ primPart s ∧ primPart q ∣ primPart s
[PROOFSTEP]
tauto
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
hp : p ≠ 0
q : R[X]
⊢ degree (gcd p q) ≤ degree p
[PROOFSTEP]
have := natDegree_le_iff_degree_le.mp (natDegree_le_of_dvd (gcd_dvd_left p q) hp)
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p : R[X]
hp : p ≠ 0
q : R[X]
this : degree (gcd p q) ≤ ↑(natDegree p)
⊢ degree (gcd p q) ≤ degree p
[PROOFSTEP]
rwa [degree_eq_natDegree hp]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hq : q ≠ 0
⊢ degree (gcd p q) ≤ degree q
[PROOFSTEP]
rw [gcd_comm]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizedGCDMonoid R
p q : R[X]
hq : q ≠ 0
⊢ degree (gcd q p) ≤ degree q
[PROOFSTEP]
exact degree_gcd_le_left hq p
|
import tactic
import .sub_module
import tactic.push_neg
import .morphism
import .homothetic
import .kernel
open Kernel range morphism homothetic
open stability
universe variables u v w w'
lemma Fact {R : Type v}[ring R]{M1 : Type w}[add_comm_group M1] [module R M1]
(p1 : submodule R M1) (hyp : p1 = ⊤ ∨ p1 = ⊥ )(z : M1)(hyp' : z ∈ p1)(hyp'' : z ≠ 0) : p1 = ⊤ := begin
rcases hyp, assumption, rw hyp at hyp', rw submodule.mem_bot at hyp', by contradiction,
end
namespace Irreductible
variables {G : Type u} [group G] {R : Type v}[ring R]
variables {M : Type w}[add_comm_group M] [module R M] ( ρ : group_representation G R M)
def Irreductible := ∀ {p : submodule R M}, (stable_submodule ρ p) → (p = ⊤ ∨ p = ⊥)
end Irreductible
namespace morphism.from_irreductible
open Irreductible linear_map
variables {G : Type u} [group G] {R : Type v}[ring R]
variables {M1 : Type w} [add_comm_group M1] [module R M1]
{M2 : Type w'} [add_comm_group M2] [module R M2]
{ ρ1 : group_representation G R M1}
{ρ2 : group_representation G R M2}
(f : ρ1 ⟶ ρ2)
--
-- Faire les choses plus proprement en definissant une strucure ⊤ ⊥ sur les representation
--
theorem pre_Schur_ker (hyp : Irreductible ρ1) :
(ker f.ℓ = ⊤ ∨ ker f.ℓ = ⊥ ) := hyp (ker_is_stable_submodule f)
theorem pre_Schur_range (hyp : Irreductible ρ2) :
(range f.ℓ = ⊤ ∨ range f.ℓ = ⊥ ) :=
hyp (range_is_stable_submodule f)
open linear_map
variables (hyp : Irreductible ρ2 )
#check f
#check pre_Schur_range f (by assumption)
/--
little modification of Serre `Representations linéaires des groupes finis`.
We have no assumption of field just a ring (`NOT` only commutative). `NOT` dimension.
-/
theorem Schur₁ (hyp1 : Irreductible ρ1)(hyp2 : Irreductible ρ2) : (∃ x : M1, (f.ℓ x ≠ 0)) →
(ker f.ℓ = ⊥ ) ∧ range f.ℓ = ⊤ :=
begin
intros hyp_not_nul,
rcases hyp_not_nul with ⟨x,hyp_not_nul⟩,
split, swap,
apply Fact, -- ici ?
apply pre_Schur_range, --- on ne comprend plus !
assumption,
rw linear_map.mem_range,
use x,
exact hyp_not_nul,
let schur := (hyp1 (ker_is_stable_submodule f)),unfold Ker at schur,
rcases schur, swap,assumption,
rw schur,
have R : x ∈ ker f.ℓ ,
rw schur, trivial,
rw linear_map.mem_ker at R,
trivial,
end
end morphism.from_irreductible
namespace Schur₂
open Irreductible morphism.from_irreductible
open_locale classical
variables {G : Type u} [group G] {R : Type v}[comm_ring R]{M : Type w}[add_comm_group M] [module R M]
variables {ρ : group_representation G R M}
theorem Schur₂(f : ρ ⟶ ρ) [re : Irreductible ρ] :
(∃ r : R, ∃ m0 : M, m0 ≠ 0 ∧ f.ℓ m0 + r • m0 = 0) → (∃ r : R, ∀ m : M, f.ℓ m + r • m = 0) :=
begin
--intro hyp,
rintros ⟨r,m0,⟨spec,spectral⟩⟩,
use r,
-- We proof g = f + r id =0. The idea is ker g is stable, so equal to {0} or M. But m0 ∈ Ker f and m0 ≠ 0 so Ker f = M
let g := f + r • 𝟙 ρ,
-- first step g.ℓ m0 = 0
have certif_m0_in_ker : g.ℓ m0 = 0,
erw [add_ext,
smul_ext, one_ext],
exact spectral,
let schur := (Schur₁ g) ( by assumption ) (by assumption), -- swap, exact re
by_contra, -- re doesnt work
push_neg at a,
rcases a with ⟨ζ,n ⟩,
have R : (f.ℓ) ζ + r • ζ = g.ℓ ζ,
erw [add_ext,smul_ext,one_ext],
exact rfl,
rw R at n,
let V := (schur ⟨ζ,n⟩).1,
have : m0 ∈ linear_map.ker g.ℓ,
rw linear_map.mem_ker,
exact certif_m0_in_ker,
rw V at this,
rw submodule.mem_bot at this,
by contradiction,
end
/-
example (P : Prop) (h : P ∨ ¬ P) : ¬ ¬ P → P := begin
intros hnn,
cases h,
assumption,
by contradiction,
end
example (P Q : Prop) : (P → Q) ↔ (¬ Q → ¬ P) := begin
split,
intro hpq,
intro hnQ,
intro hp,
end
example (X :Type) (P : X → Prop ) (hyp : (∃ x : X, ¬ (P x)) → false ) : ∀ x, P x := begin
intro,
contrapose! hyp,
use x,
end
example (X :Type) (P : X → Prop ) (hyp : (∃ x : X, ¬ (P x)) → false ) : ∀ x, P x := begin
by_contra,
rw not_forall at a,
exact hyp a,
end
-/ |
[GOAL]
ι : Type u
hi : Nonempty ι
R : Type v
inst✝¹ : Semiring R
p : ℕ
inst✝ : CharP R p
x : ℕ
i : ι
h : ↑x = 0
j : ι
⊢ ↑(Pi.evalRingHom (fun x => R) j) ↑x = 0
[PROOFSTEP]
rw [map_natCast, h]
[GOAL]
ι : Type u
hi : Nonempty ι
R : Type v
inst✝¹ : Semiring R
p : ℕ
inst✝ : CharP R p
x : ℕ
i : ι
h : ↑x = 0
⊢ ↑(Pi.evalRingHom (fun x => R) i) ↑x = 0
[PROOFSTEP]
rw [h, RingHom.map_zero]
|
SUBROUTINE IM_RTBL ( iret )
C************************************************************************
C* IM_RTBL *
C* *
C* From GEMPAK original, optimized for NIDS only. *
C* REF : Logical indicating if plot is BREF or VEL plot *
C************************************************************************
INCLUDE 'GEMPRM.PRM'
INCLUDE 'IMGDEF.CMN'
INCLUDE 'RADMAP.CMN'
C------------------------------------------------------------------------
iret = 0
cmsorc = 'NIDS'
if ( REF ) then
cmlutf = 'nids_ref16.tbl'
cmtype = 'BREF'
else
cmlutf = 'nids_vel.tbl'
cmtype = 'VEL'
endif
immnpx = 0
immxpx = 15
RETURN
END
|
using Test, Statistics, LinearAlgebra, Random
# make stable linear dynamics
Random.seed!(0)
eye = DifferentialDynamicProgramming.eye
costs = map(1:10) do MCiteration
h = .01 # time step
n = 10 # state dimension
m = 2 # control dimension
A = randn(n,n)
A = A-A' # skew-symmetric = pure imaginary eigenvalues
A = exp(h*A) # discrete time
B = h*randn(n,m)
# quadratic costs
Q = h*eye(n)
R = .1*h*eye(m)
# control limits
lims = []# ones(m,1)*[-1 1]*.6
T = 1000 # horizon
x0 = ones(n,1) # initial state
u0 = .1*randn(m,T) # initial controls
# optimization problem
N = T+1
fx = A
fu = B
cxx = Q
cxu = zeros(size(B))
cuu = R
# Specify dynamics functions
function lin_dyn_df(x,u,Q,R)
u[isnan.(u)] .= 0
cx = Q*x
cu = R*u
fxx=fxu=fuu = []
return fx,fu,fxx,fxu,fuu,cx,cu,cxx,cxu,cuu
end
function lin_dyn_f(x,u,A,B)
u[isnan.(u)] .= 0
xnew = A*x + B*u
return xnew
end
function lin_dyn_cost(x,u,Q)
c = 0.5*sum(x.*(Q*x)) + 0.5*sum(u.*(R*u))
return c
end
f(x,u,i) = lin_dyn_f(x,u,A,B)
costfun(x,u) = lin_dyn_cost(x,u,Q)
df(x,u) = lin_dyn_df(x,u,Q,R)
# plotFn(x) = plot(squeeze(x,2)')
# run the optimization
@time x, u, L, Vx, Vxx, cost, otrace = iLQG(f,costfun,df, x0, u0, lims=lims, verbosity=3);
# using Plots
# plot(x', title="States", subplot=1, layout=(3,1), show=true)
# plot!(u', title="Control signals", subplot=2, show=true)
# plot!(cost, title="Cost", subplot=3, show=true)
sum(cost)
end
@test maximum(costs) < 25 # This should be the case most of the times
@test mean(costs) < 10 # This should be the case most of the times
@test minimum(costs) < 5 # This should be the case most of the times
|
From iris.algebra Require Export auth gmap frac agree excl vector.
From Perennial.algebra Require Export big_op.
From Perennial.Helpers Require Export Tactics List ListLen BigOp Transitions iris ipm.
From Perennial.base_logic Require Export ghost_var.
From Perennial.program_logic Require Export ncinv.
From Perennial.goose_lang Require Export proofmode wpc_proofmode array.
From Perennial.goose_lang Require Export into_val.
From Perennial.goose_lang.lib Require Export
persistent_readonly slice slice.typed_slice struct loop lock control map.typed_map time proph.
Export uPred.
Global Set Default Proof Using "Type".
Global Set Printing Projections.
Global Opaque load_ty store_ty.
Import sel_patterns.
Fixpoint fix_frame_selpat (Hs: list sel_pat) : list sel_pat :=
match Hs with
| nil => []
| SelIntuitionistic :: Hs => fix_frame_selpat Hs ++ [SelIntuitionistic]
| SelPure :: Hs => fix_frame_selpat Hs ++ [SelPure]
| s :: Hs => s :: fix_frame_selpat Hs
end.
Ltac iFrame_hyps_fast :=
repeat match goal with
| |- envs_entails ?Δ (?P ∗ _)%I =>
lazymatch Δ with
| context[Esnoc _ ?i P] => iFrameHyp i
end
end.
Ltac iFrame_go Hs :=
lazymatch Hs with
| [] => idtac
| SelPure :: ?Hs => iFrameAnyPure; iFrame_go Hs
| SelIntuitionistic :: ?Hs => iFrameAnyIntuitionistic; iFrame_go Hs
| SelSpatial :: ?Hs => iFrame_hyps_fast; iFrameAnySpatial; iFrame_go Hs
| SelIdent ?H :: ?Hs => iFrameHyp H; iFrame_go Hs
end.
Tactic Notation "iFrame" constr(Hs) :=
let Hs := sel_pat.parse Hs in
let Hs := (eval cbv in (fix_frame_selpat Hs)) in
iFrame_go Hs.
|
------------------------------------------------------------------------------
-- The division specification
------------------------------------------------------------------------------
{-# OPTIONS --exact-split #-}
{-# OPTIONS --no-sized-types #-}
{-# OPTIONS --no-universe-polymorphism #-}
{-# OPTIONS --without-K #-}
module LTC-PCF.Program.Division.Specification where
open import LTC-PCF.Base
open import LTC-PCF.Data.Nat
open import LTC-PCF.Data.Nat.Inequalities
------------------------------------------------------------------------------
-- Specification: The division is total and the result is correct.
divSpec : D → D → D → Set
divSpec i j q = N q ∧ (∃[ r ] N r ∧ r < j ∧ i ≡ j * q + r)
|
program test
use, intrinsic :: iso_fortran_env, only : error_unit
print *, "Error unit ", error_unit
end program test
|
[STATEMENT]
lemma eucl_truncate_down_Basis[simp]:
"i \<in> Basis \<Longrightarrow> eucl_truncate_down e x \<bullet> i = truncate_down e (x \<bullet> i)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. i \<in> Basis \<Longrightarrow> eucl_truncate_down e x \<bullet> i = truncate_down e (x \<bullet> i)
[PROOF STEP]
by (simp add: eucl_truncate_down_def) |
#%%
"""
Created on July 05 2021
The Heston-Hull-White model and pricing European Options with Monte Carlo and the COS method
This code is purely educational and comes from "Financial Engineering" course by L.A. Grzelak
The course is based on the book “Mathematical Modeling and Computation
in Finance: With Exercises and Python and MATLAB Computer Codes”,
by C.W. Oosterlee and L.A. Grzelak, World Scientific Publishing Europe Ltd, 2019.
@author: Lech A. Grzelak
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.special as sp
import scipy.integrate as integrate
import enum
# This class defines puts and calls
class OptionType(enum.Enum):
CALL = 1.0
PUT = -1.0
def CallPutOptionPriceCOSMthd_StochIR(cf,CP,S0,tau,K,N,L,P0T):
# cf - characteristic function as a functon, in the book denoted as \varphi
# CP - C for call and P for put
# S0 - Initial stock price
# tau - time to maturity
# K - list of strikes
# N - Number of expansion terms
# L - size of truncation domain (typ.:L=8 or L=10)
# P0T - zero-coupon bond for maturity T.
# reshape K to a column vector
if K is not np.array:
K = np.array(K).reshape([len(K),1])
#assigning i=sqrt(-1)
i = np.complex(0.0,1.0)
x0 = np.log(S0 / K)
# truncation domain
a = 0.0 - L * np.sqrt(tau)
b = 0.0 + L * np.sqrt(tau)
# sumation from k = 0 to k=N-1
k = np.linspace(0,N-1,N).reshape([N,1])
u = k * np.pi / (b - a)
# Determine coefficients for Put Prices
H_k = CallPutCoefficients(OptionType.PUT,a,b,k)
mat = np.exp(i * np.outer((x0 - a) , u))
temp = cf(u) * H_k
temp[0] = 0.5 * temp[0]
value = K * np.real(mat.dot(temp))
# we use call-put parity for call options
if CP == OptionType.CALL:
value = value + S0 - K * P0T
return value
# Determine coefficients for Put Prices
def CallPutCoefficients(CP,a,b,k):
if CP==OptionType.CALL:
c = 0.0
d = b
coef = Chi_Psi(a,b,c,d,k)
Chi_k = coef["chi"]
Psi_k = coef["psi"]
if a < b and b < 0.0:
H_k = np.zeros([len(k),1])
else:
H_k = 2.0 / (b - a) * (Chi_k - Psi_k)
elif CP==OptionType.PUT:
c = a
d = 0.0
coef = Chi_Psi(a,b,c,d,k)
Chi_k = coef["chi"]
Psi_k = coef["psi"]
H_k = 2.0 / (b - a) * (- Chi_k + Psi_k)
return H_k
def Chi_Psi(a,b,c,d,k):
psi = np.sin(k * np.pi * (d - a) / (b - a)) - np.sin(k * np.pi * (c - a)/(b - a))
psi[1:] = psi[1:] * (b - a) / (k[1:] * np.pi)
psi[0] = d - c
chi = 1.0 / (1.0 + np.power((k * np.pi / (b - a)) , 2.0))
expr1 = np.cos(k * np.pi * (d - a)/(b - a)) * np.exp(d) - np.cos(k * np.pi
* (c - a) / (b - a)) * np.exp(c)
expr2 = k * np.pi / (b - a) * np.sin(k * np.pi *
(d - a) / (b - a)) - k * np.pi / (b - a) * np.sin(k
* np.pi * (c - a) / (b - a)) * np.exp(c)
chi = chi * (expr1 + expr2)
value = {"chi":chi,"psi":psi }
return value
def EUOptionPriceFromMCPathsGeneralizedStochIR(CP,S,K,T,M):
# S is a vector of Monte Carlo samples at T
result = np.zeros([len(K),1])
if CP == OptionType.CALL:
for (idx,k) in enumerate(K):
result[idx] = np.mean(1.0/M*np.maximum(S-k,0.0))
elif CP == OptionType.PUT:
for (idx,k) in enumerate(K):
result[idx] = np.mean(1.0/M*np.maximum(k-S,0.0))
return result
def CIR_Sample(NoOfPaths,kappa,gamma,vbar,s,t,v_s):
delta = 4.0 *kappa*vbar/gamma/gamma
c= 1.0/(4.0*kappa)*gamma*gamma*(1.0-np.exp(-kappa*(t-s)))
kappaBar = 4.0*kappa*v_s*np.exp(-kappa*(t-s))/(gamma*gamma*(1.0-np.exp(-kappa*(t-s))))
sample = c* np.random.noncentral_chisquare(delta,kappaBar,NoOfPaths)
return sample
def GeneratePathsHestonHW_AES(NoOfPaths,NoOfSteps,P0T,T,S_0,kappa,gamma,rhoxr,rhoxv,vbar,v0,lambd,eta):
# time-step needed for differentiation
dt = 0.0001
f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2*dt)
# Initial interest rate is a forward rate at time t->0
r0 = f0T(0.00001)
theta = lambda t: 1.0/lambd * (f0T(t+dt)-f0T(t-dt))/(2.0*dt) + f0T(t) + eta*eta/(2.0*lambd*lambd)*(1.0-np.exp(-2.0*lambd*t))
Z1 = np.random.normal(0.0,1.0,[NoOfPaths,NoOfSteps])
Z2 = np.random.normal(0.0,1.0,[NoOfPaths,NoOfSteps])
Z3 = np.random.normal(0.0,1.0,[NoOfPaths,NoOfSteps])
W1 = np.zeros([NoOfPaths, NoOfSteps+1])
W2 = np.zeros([NoOfPaths, NoOfSteps+1])
W3 = np.zeros([NoOfPaths, NoOfSteps+1])
V = np.zeros([NoOfPaths, NoOfSteps+1])
X = np.zeros([NoOfPaths, NoOfSteps+1])
R = np.zeros([NoOfPaths, NoOfSteps+1])
M_t = np.ones([NoOfPaths,NoOfSteps+1])
R[:,0]=r0
V[:,0]=v0
X[:,0]=np.log(S_0)
time = np.zeros([NoOfSteps+1])
dt = T / float(NoOfSteps)
for i in range(0,NoOfSteps):
# making sure that samples from normal have mean 0 and variance 1
if NoOfPaths > 1:
Z1[:,i] = (Z1[:,i] - np.mean(Z1[:,i])) / np.std(Z1[:,i])
Z2[:,i] = (Z2[:,i] - np.mean(Z2[:,i])) / np.std(Z2[:,i])
Z3[:,i] = (Z3[:,i] - np.mean(Z3[:,i])) / np.std(Z3[:,i])
W1[:,i+1] = W1[:,i] + np.power(dt, 0.5)*Z1[:,i]
W2[:,i+1] = W2[:,i] + np.power(dt, 0.5)*Z2[:,i]
W3[:,i+1] = W3[:,i] + np.power(dt, 0.5)*Z3[:,i]
R[:,i+1] = R[:,i] + lambd*(theta(time[i]) - R[:,i]) * dt + eta* (W1[:,i+1]-W1[:,i])
M_t[:,i+1] = M_t[:,i] * np.exp(0.5*(R[:,i+1] + R[:,i])*dt)
# Exact samles for the variance process
V[:,i+1] = CIR_Sample(NoOfPaths,kappa,gamma,vbar,0,dt,V[:,i])
k0 = -rhoxv /gamma * kappa*vbar*dt
k2 = rhoxv/gamma
k1 = kappa*k2 -0.5
k3 = np.sqrt(1.0-rhoxr*rhoxr - rhoxv*rhoxv)
X[:,i+1] = X[:,i] + k0 + (k1*dt - k2)*V[:,i] + R[:,i]*dt + k2*V[:,i+1]+\
+ np.sqrt(V[:,i]*dt)*(rhoxr*Z1[:,i] + k3 * Z3[:,i])
# Moment matching component, i.e.: ensure that E(S(T)/M(T))= S0
a = S_0 / np.mean(np.exp(X[:,i+1])/M_t[:,i+1])
X[:,i+1] = X[:,i+1] + np.log(a)
time[i+1] = time[i] +dt
#Compute exponent
S = np.exp(X)
paths = {"time":time,"S":S,"R":R,"M_t":M_t}
return paths
def GeneratePathsHestonHWEuler(NoOfPaths,NoOfSteps,P0T,T,S_0,kappa,gamma,rhoxr,rhoxv,vbar,v0,lambd,eta):
# time-step needed for differentiation
dt = 0.0001
f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2*dt)
# Initial interest rate is a forward rate at time t->0
r0 = f0T(0.00001)
theta = lambda t: 1.0/lambd * (f0T(t+dt)-f0T(t-dt))/(2.0*dt) + f0T(t) + eta*eta/(2.0*lambd*lambd)*(1.0-np.exp(-2.0*lambd*t))
Z1 = np.random.normal(0.0,1.0,[NoOfPaths,NoOfSteps])
Z2 = np.random.normal(0.0,1.0,[NoOfPaths,NoOfSteps])
Z3 = np.random.normal(0.0,1.0,[NoOfPaths,NoOfSteps])
W1 = np.zeros([NoOfPaths, NoOfSteps+1])
W2 = np.zeros([NoOfPaths, NoOfSteps+1])
W3 = np.zeros([NoOfPaths, NoOfSteps+1])
V = np.zeros([NoOfPaths, NoOfSteps+1])
X = np.zeros([NoOfPaths, NoOfSteps+1])
R = np.zeros([NoOfPaths, NoOfSteps+1])
M_t = np.ones([NoOfPaths,NoOfSteps+1])
R[:,0]=r0
V[:,0]=v0
X[:,0]=np.log(S_0)
time = np.zeros([NoOfSteps+1])
dt = T / float(NoOfSteps)
for i in range(0,NoOfSteps):
# making sure that samples from normal have mean 0 and variance 1
if NoOfPaths > 1:
Z1[:,i] = (Z1[:,i] - np.mean(Z1[:,i])) / np.std(Z1[:,i])
Z2[:,i] = (Z2[:,i] - np.mean(Z2[:,i])) / np.std(Z2[:,i])
Z3[:,i] = (Z3[:,i] - np.mean(Z3[:,i])) / np.std(Z3[:,i])
W1[:,i+1] = W1[:,i] + np.power(dt, 0.5)*Z1[:,i]
W2[:,i+1] = W2[:,i] + np.power(dt, 0.5)*Z2[:,i]
W3[:,i+1] = W3[:,i] + np.power(dt, 0.5)*Z3[:,i]
# Truncated boundary condition
R[:,i+1] = R[:,i] + lambd*(theta(time[i]) - R[:,i]) * dt + eta* (W1[:,i+1]-W1[:,i])
M_t[:,i+1] = M_t[:,i] * np.exp(0.5*(R[:,i+1] + R[:,i])*dt)
V[:,i+1] = V[:,i] + kappa*(vbar - V[:,i]) * dt + gamma* np.sqrt(V[:,i]) * (W2[:,i+1]-W2[:,i])
V[:,i+1] = np.maximum(V[:,i+1],0.0)
term1 = rhoxr * (W1[:,i+1]-W1[:,i]) + rhoxv * (W2[:,i+1]-W2[:,i]) \
+ np.sqrt(1.0-rhoxr*rhoxr-rhoxv*rhoxv)* (W3[:,i+1]-W3[:,i])
X[:,i+1] = X[:,i] + (R[:,i] - 0.5*V[:,i])*dt + np.sqrt(V[:,i])*term1
time[i+1] = time[i] +dt
# Moment matching component, i.e.: ensure that E(S(T)/M(T))= S0
a = S_0 / np.mean(np.exp(X[:,i+1])/M_t[:,i+1])
X[:,i+1] = X[:,i+1] + np.log(a)
#Compute exponent
S = np.exp(X)
paths = {"time":time,"S":S,"R":R,"M_t":M_t}
return paths
# Exact expectation E(sqrt(V(t)))
def meanSqrtV_3(kappa,v0,vbar,gamma):
delta = 4.0 *kappa*vbar/gamma/gamma
c= lambda t: 1.0/(4.0*kappa)*gamma*gamma*(1.0-np.exp(-kappa*(t)))
kappaBar = lambda t: 4.0*kappa*v0*np.exp(-kappa*t)/(gamma*gamma*(1.0-np.exp(-kappa*t)))
temp1 = lambda t: np.sqrt(2.0*c(t))* sp.gamma((1.0+delta)/2.0)/sp.gamma(delta/2.0)*sp.hyp1f1(-0.5,delta/2.0,-kappaBar(t)/2.0)
return temp1
def C_H1HW(u,tau,lambd):
i = np.complex(0.0,1.0)
C = (i*u - 1.0)/lambd * (1-np.exp(-lambd*tau))
return C
def D_H1HW(u,tau,kappa,gamma,rhoxv):
i = np.complex(0.0,1.0)
D1 = np.sqrt(np.power(kappa-gamma*rhoxv*i*u,2)+(u*u+i*u)*gamma*gamma)
g = (kappa-gamma*rhoxv*i*u-D1)/(kappa-gamma*rhoxv*i*u+D1)
C = (1.0-np.exp(-D1*tau))/(gamma*gamma*(1.0-g*np.exp(-D1*tau)))\
*(kappa-gamma*rhoxv*i*u-D1)
return C
def A_H1HW(u,tau,P0T,lambd,eta,kappa,gamma,vbar,v0,rhoxv,rhoxr):
i = np.complex(0.0,1.0)
D1 = np.sqrt(np.power(kappa-gamma*rhoxv*i*u,2)+(u*u+i*u)*gamma*gamma)
g = (kappa-gamma*rhoxv*i*u-D1)/(kappa-gamma*rhoxv*i*u+D1)
# function theta(t)
dt = 0.0001
f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2.0*dt)
theta = lambda t: 1.0/lambd * (f0T(t+dt)-f0T(t-dt))/(2.0*dt) + f0T(t) + eta*eta/(2.0*lambd*lambd)*(1.0-np.exp(-2.0*lambd*t))
# Integration in the function I_1
N = 500
z = np.linspace(0,tau-1e-10,N)
f1 = (1.0-np.exp(-lambd*z))*theta(tau-z)
value1 = integrate.trapz(f1,z)
# Note that I_1_adj also allows for theta to be time-dependent
# therefore it is not exactly the same as given in the book
I_1_adj = (i*u-1.0) * value1
I_2 = tau/(gamma**2.0) *(kappa-gamma*rhoxv*i*u-D1) - 2.0/(gamma**2.0)*np.log((1.0-g*np.exp(-D1*tau))/(1.0-g))
I_3 = 1.0/(2.0*np.power(lambd,3.0))* np.power(i+u,2.0)*(3.0+np.exp(-2.0*lambd*tau)-4.0*np.exp(-lambd*tau)-2.0*lambd*tau)
meanSqrtV = meanSqrtV_3(kappa,v0,vbar,gamma)
f2 = meanSqrtV(tau-z)*(1.0-np.exp(-lambd*z))
value2 = integrate.trapz(f2,z)
I_4 = -1.0/lambd * (i*u+u**2.0)*value2
return I_1_adj + kappa*vbar*I_2 + 0.5*eta**2.0*I_3+eta*rhoxr*I_4
def ChFH1HWModel(P0T,lambd,eta,tau,kappa,gamma,vbar,v0,rhoxv, rhoxr):
# Determine initial interest rate r(0)
dt = 0.0001
f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2.0*dt)
r0 =f0T(0.00001)
C = lambda u: C_H1HW(u,tau,lambd)
D = lambda u: D_H1HW(u,tau,kappa,gamma,rhoxv)
A = lambda u: A_H1HW(u,tau,P0T,lambd,eta,kappa,gamma,vbar,v0,rhoxv,rhoxr)
cf = lambda u: np.exp(A(u) + C(u)*r0 + D(u)*v0 )
return cf
def mainCalculation():
CP = OptionType.CALL
NoOfPaths = 10000
NoOfSteps = 500
# HW model settings
lambd = 1.12
eta = 0.01
S0 = 100.0
T = 15.0
r = 0.1
# Strike range
K = np.linspace(.01,1.8*S0*np.exp(r*T),20)
K = np.array(K).reshape([len(K),1])
# We define a ZCB curve (obtained from the market)
P0T = lambda T: np.exp(-r*T)
# Settings for the COS method
N = 2000
L = 15
gamma = 0.3
vbar = 0.05
v0 = 0.02
rhoxr = 0.5
rhoxv =-0.8
kappa = 0.5
np.random.seed(1)
paths = GeneratePathsHestonHWEuler(NoOfPaths,NoOfSteps,P0T,T,S0,kappa,gamma,rhoxr,rhoxv,vbar,v0,lambd,eta)
S = paths["S"]
M_t = paths["M_t"]
print(np.mean(S[:,-1]/M_t[:,-1]))
valueOptMC= EUOptionPriceFromMCPathsGeneralizedStochIR(CP,S[:,-1],K,T,M_t[:,-1])
np.random.seed(1)
pathsExact = GeneratePathsHestonHW_AES(NoOfPaths,NoOfSteps,P0T,T,S0,kappa,gamma,rhoxr,rhoxv,vbar,v0,lambd,eta)
S_ex = pathsExact["S"]
M_t_ex = pathsExact["M_t"]
valueOptMC_ex= EUOptionPriceFromMCPathsGeneralizedStochIR(CP,S_ex[:,-1],K,T,M_t_ex[:,-1])
print(np.mean(S_ex[:,-1]/M_t_ex[:,-1]))
plt.figure(1)
plt.plot(K,valueOptMC)
plt.plot(K,valueOptMC_ex,'.k')
plt.ylim([0.0,110.0])
# The COS method
cf2 = ChFH1HWModel(P0T,lambd,eta,T,kappa,gamma,vbar,v0,rhoxv, rhoxr)
u=np.array([1.0,2.0,3.0])
print(cf2(u))
valCOS = CallPutOptionPriceCOSMthd_StochIR(cf2, CP, S0, T, K, N, L,P0T(T))
plt.plot(K,valCOS,'--r')
plt.legend(['Euler','AES','COS'])
plt.grid()
plt.xlabel('strike, K')
plt.ylabel('EU Option Value, K')
print("Value from the COS method:")
print(valCOS)
mainCalculation() |
Require Import Coq.Lists.List.
Require Import Coq.Lists.SetoidList.
Require Import Coq.micromega.Lia.
Require Import Coq.Arith.Peano_dec.
Require Import Coq.ZArith.ZArith.
Require Import Coq.Arith.Arith.
Require Import Coq.Classes.Morphisms.
Require Import Coq.Numbers.Natural.Peano.NPeano.
Require Import Crypto.Util.NatUtil.
Require Import Crypto.Util.Pointed.
Require Import Crypto.Util.Prod.
Require Import Crypto.Util.Decidable.
Require Crypto.Util.Option.
Require Export Crypto.Util.FixCoqMistakes.
Require Export Crypto.Util.Tactics.BreakMatch.
Require Export Crypto.Util.Tactics.DestructHead.
Require Import Crypto.Util.Tactics.SpecializeBy.
Require Import Crypto.Util.Tactics.RewriteHyp.
Require Import Crypto.Util.Tactics.ConstrFail.
Require Import Crypto.Util.Tactics.SplitInContext.
Import ListNotations.
Local Open Scope list_scope.
Scheme Equality for list.
Definition list_case
{A} (P : list A -> Type) (N : P nil) (C : forall x xs, P (cons x xs))
(ls : list A)
: P ls
:= match ls return P ls with
| nil => N
| cons x xs => C x xs
end.
Definition list_case_nodep
{A} (P : Type) (N : P) (C : A -> list A -> P)
(ls : list A)
: P
:= match ls with
| nil => N
| cons x xs => C x xs
end.
Global Instance list_rect_Proper_dep_gen {A P} (RP : forall x : list A, P x -> P x -> Prop)
: Proper (RP nil ==> forall_relation (fun x => forall_relation (fun xs => RP xs ==> RP (cons x xs))) ==> forall_relation RP) (@list_rect A P) | 10.
Proof.
cbv [forall_relation respectful]; intros N N' HN C C' HC ls.
induction ls as [|l ls IHls]; cbn [list_rect];
repeat first [ apply IHls | apply HC | apply HN | progress intros | reflexivity ].
Qed.
Global Instance list_rect_Proper_dep {A P} : Proper (eq ==> forall_relation (fun _ => forall_relation (fun _ => forall_relation (fun _ => eq))) ==> forall_relation (fun _ => eq)) (@list_rect A P) | 1.
Proof.
cbv [forall_relation respectful Proper]; intros; eapply (@list_rect_Proper_dep_gen A P (fun _ => eq)); cbv [forall_relation respectful]; intros; subst; eauto.
Qed.
Global Instance list_rect_arrow_Proper_dep {A P Q} : Proper ((eq ==> eq) ==> forall_relation (fun _ => forall_relation (fun _ => (eq ==> eq) ==> (eq ==> eq))) ==> forall_relation (fun _ => eq ==> eq)) (@list_rect A (fun x => P x -> Q x)) | 10.
Proof.
cbv [forall_relation respectful Proper]; intros; eapply (@list_rect_Proper_dep_gen A (fun x => P x -> Q x) (fun _ => eq ==> eq)%signature); intros; subst; eauto.
Qed.
Global Instance list_case_Proper_dep {A P} : Proper (eq ==> forall_relation (fun _ => forall_relation (fun _ => eq)) ==> forall_relation (fun _ => eq)) (@list_case A P) | 1.
Proof.
cbv [forall_relation]; intros N N' ? C C' HC ls; subst N'; revert N; destruct ls; eauto.
Qed.
Global Instance list_rect_Proper_gen {A P} R
: Proper (R ==> (eq ==> eq ==> R ==> R) ==> eq ==> R) (@list_rect A (fun _ => P)) | 10.
Proof. repeat intro; subst; apply (@list_rect_Proper_dep_gen A (fun _ => P) (fun _ => R)); cbv [forall_relation respectful] in *; eauto. Qed.
Global Instance list_rect_Proper {A P} : Proper (eq ==> pointwise_relation _ (pointwise_relation _ (pointwise_relation _ eq)) ==> eq ==> eq) (@list_rect A (fun _ => P)).
Proof. repeat intro; subst; apply (@list_rect_Proper_dep A (fun _ => P)); eauto. Qed.
Global Instance list_rect_arrow_Proper {A P Q}
: Proper ((eq ==> eq) ==> (eq ==> eq ==> (eq ==> eq) ==> eq ==> eq) ==> eq ==> eq ==> eq)
(@list_rect A (fun _ => P -> Q)) | 10.
Proof. eapply list_rect_Proper_gen. Qed.
Global Instance list_case_Proper {A P} : Proper (eq ==> pointwise_relation _ (pointwise_relation _ eq) ==> eq ==> eq) (@list_case A (fun _ => P)).
Proof. repeat intro; subst; apply (@list_case_Proper_dep A (fun _ => P)); eauto. Qed.
Create HintDb distr_length discriminated.
Create HintDb simpl_set_nth discriminated.
Create HintDb simpl_update_nth discriminated.
Create HintDb simpl_nth_default discriminated.
Create HintDb simpl_nth_error discriminated.
Create HintDb simpl_firstn discriminated.
Create HintDb simpl_skipn discriminated.
Create HintDb simpl_fold_right discriminated.
Create HintDb simpl_fold_left discriminated.
Create HintDb simpl_sum_firstn discriminated.
Create HintDb push_map discriminated.
Create HintDb push_combine discriminated.
Create HintDb push_flat_map discriminated.
Create HintDb push_rev discriminated.
Create HintDb push_fold_right discriminated.
Create HintDb push_fold_left discriminated.
Create HintDb push_partition discriminated.
Create HintDb pull_nth_error discriminated.
Create HintDb push_nth_error discriminated.
Create HintDb pull_nth_default discriminated.
Create HintDb push_nth_default discriminated.
Create HintDb pull_firstn discriminated.
Create HintDb push_firstn discriminated.
Create HintDb pull_skipn discriminated.
Create HintDb push_skipn discriminated.
Create HintDb push_sum discriminated.
Create HintDb pull_update_nth discriminated.
Create HintDb push_update_nth discriminated.
Create HintDb znonzero discriminated.
#[global]
Hint Rewrite
@app_length
@rev_length
@map_length
@seq_length
@fold_left_length
@split_length_l
@split_length_r
@firstn_length
@combine_length
@prod_length
: distr_length.
#[global]
Hint Rewrite
rev_involutive
: push_rev.
Global Hint Extern 1 => progress autorewrite with distr_length in * : distr_length.
Ltac distr_length := autorewrite with distr_length in *;
try solve [simpl in *; intros; (idtac + exfalso); lia].
Module Export List.
Local Set Implicit Arguments.
Import ListNotations.
(** From the 8.6 Standard Library *)
Section Elts.
Variable A : Type.
(** Results about [nth_error] *)
Lemma nth_error_In l n (x : A) : nth_error l n = Some x -> In x l.
Proof using Type.
revert n. induction l as [|a l IH]; intros [|n]; simpl; try easy.
- injection 1; auto.
- eauto.
Qed.
End Elts.
Section Map.
Variables (A : Type) (B : Type).
Variable f : A -> B.
Lemma map_nil : forall A B (f : A -> B), map f nil = nil.
Proof using Type. reflexivity. Qed.
Lemma map_cons (x:A)(l:list A) : map f (x::l) = (f x) :: (map f l).
Proof using Type.
reflexivity.
Qed.
Lemma map_repeat x n : map f (List.repeat x n) = List.repeat (f x) n.
Proof using Type. induction n; simpl List.repeat; simpl map; congruence. Qed.
End Map.
#[global]
Hint Rewrite @map_cons @map_nil @map_repeat : push_map.
#[global]
Hint Rewrite @map_app : push_map.
Section FlatMap.
Lemma flat_map_nil {A B} (f:A->list B) : List.flat_map f (@nil A) = nil.
Proof. reflexivity. Qed.
Lemma flat_map_cons {A B} (f:A->list B) x xs :
(List.flat_map f (x::xs) = (f x++List.flat_map f xs))%list.
Proof. reflexivity. Qed.
End FlatMap.
#[global]
Hint Rewrite @flat_map_cons @flat_map_nil : push_flat_map.
Lemma rev_cons {A} x ls : @rev A (x :: ls) = rev ls ++ [x]. Proof. reflexivity. Qed.
#[global]
Hint Rewrite @rev_cons : list.
Section FoldRight.
Context {A B} (f:B->A->A).
Lemma fold_right_nil : forall {A B} (f:B->A->A) a,
List.fold_right f a nil = a.
Proof using Type. reflexivity. Qed.
Lemma fold_right_cons : forall a b bs,
fold_right f a (b::bs) = f b (fold_right f a bs).
Proof using Type. reflexivity. Qed.
Lemma fold_right_snoc a x ls:
@fold_right A B f a (ls ++ [x]) = fold_right f (f x a) ls.
Proof using Type.
rewrite <-(rev_involutive ls), <-rev_cons.
rewrite !fold_left_rev_right; reflexivity.
Qed.
End FoldRight.
#[global]
Hint Rewrite @fold_right_nil @fold_right_cons @fold_right_snoc : simpl_fold_right push_fold_right.
Section Partition.
Lemma partition_nil {A} (f:A->_) : partition f nil = (nil, nil).
Proof. reflexivity. Qed.
Lemma partition_cons {A} (f:A->_) x xs : partition f (x::xs) =
if f x
then (x :: (fst (partition f xs)), (snd (partition f xs)))
else ((fst (partition f xs)), x :: (snd (partition f xs))).
Proof. cbv [partition]; break_match; reflexivity. Qed.
End Partition.
#[global]
Hint Rewrite @partition_nil @partition_cons : push_partition.
Lemma in_seq len start n :
In n (seq start len) <-> start <= n < start+len.
Proof.
revert start. induction len as [|len IHlen]; simpl; intros.
- rewrite <- plus_n_O. split;[easy|].
intros (H,H'). apply (Lt.lt_irrefl _ (Lt.le_lt_trans _ _ _ H H')).
- rewrite IHlen, <- plus_n_Sm; simpl; split.
* intros [H|H]; subst; intuition auto with arith.
* intros (H,H'). destruct (Lt.le_lt_or_eq _ _ H); intuition.
Qed.
Section Facts.
Variable A : Type.
Theorem length_zero_iff_nil (l : list A):
length l = 0 <-> l=[].
Proof using Type.
split; [now destruct l | now intros ->].
Qed.
End Facts.
Section Cutting.
Variable A : Type.
Local Notation firstn := (@firstn A).
Lemma firstn_nil n: firstn n [] = [].
Proof using Type. induction n; now simpl. Qed.
Lemma firstn_cons n a l: firstn (S n) (a::l) = a :: (firstn n l).
Proof using Type. now simpl. Qed.
Lemma firstn_all l: firstn (length l) l = l.
Proof using Type. induction l as [| ? ? H]; simpl; [reflexivity | now rewrite H]. Qed.
Lemma firstn_all2 n: forall (l:list A), (length l) <= n -> firstn n l = l.
Proof using Type. induction n as [|k iHk].
- intro l. inversion 1 as [H1|?].
rewrite (length_zero_iff_nil l) in H1. subst. now simpl.
- destruct l as [|x xs]; simpl.
* now reflexivity.
* simpl. intro H. apply Peano.le_S_n in H. f_equal. apply iHk, H.
Qed.
Lemma firstn_O l: firstn 0 l = [].
Proof using Type. now simpl. Qed.
Lemma firstn_le_length n: forall l:list A, length (firstn n l) <= n.
Proof using Type.
induction n as [|k iHk]; simpl; [auto | destruct l as [|x xs]; simpl].
- auto with arith.
- apply le_n_S, iHk.
Qed.
Lemma firstn_length_le: forall l:list A, forall n:nat,
n <= length l -> length (firstn n l) = n.
Proof using Type. induction l as [|x xs Hrec].
- simpl. intros n H. apply le_n_0_eq in H. rewrite <- H. now simpl.
- destruct n as [|n].
* now simpl.
* simpl. intro H. apply le_S_n in H. now rewrite (Hrec n H).
Qed.
Lemma firstn_app n:
forall l1 l2,
firstn n (l1 ++ l2) = (firstn n l1) ++ (firstn (n - length l1) l2).
Proof using Type. induction n as [|k iHk]; intros l1 l2.
- now simpl.
- destruct l1 as [|x xs].
* unfold List.firstn at 2, length. now rewrite 2!app_nil_l, <- minus_n_O.
* rewrite <- app_comm_cons. simpl. f_equal. apply iHk.
Qed.
Lemma firstn_app_2 n:
forall l1 l2,
firstn ((length l1) + n) (l1 ++ l2) = l1 ++ firstn n l2.
Proof using Type. induction n as [| k iHk];intros l1 l2.
- unfold List.firstn at 2. rewrite <- plus_n_O, app_nil_r.
rewrite firstn_app. rewrite <- minus_diag_reverse.
unfold List.firstn at 2. rewrite app_nil_r. apply firstn_all.
- destruct l2 as [|x xs].
* simpl. rewrite app_nil_r. apply firstn_all2. auto with arith.
* rewrite firstn_app. assert (H0 : (length l1 + S k - length l1) = S k).
auto with arith.
rewrite H0, firstn_all2; [reflexivity | auto with arith].
Qed.
Lemma firstn_firstn:
forall l:list A,
forall i j : nat,
firstn i (firstn j l) = firstn (min i j) l.
Proof using Type. induction l as [|x xs Hl].
- intros. simpl. now rewrite ?firstn_nil.
- destruct i.
* intro. now simpl.
* destruct j.
+ now simpl.
+ simpl. f_equal. apply Hl.
Qed.
End Cutting.
Lemma fold_right_rev_left A B (f : B -> A -> B) (l : list A) (i : B)
: fold_left f (rev l) i = fold_right (fun x y => f y x) i l.
Proof.
now rewrite <- fold_left_rev_right, rev_involutive.
Qed.
Section FoldLeft.
Context {A B} (f:A->B->A).
Lemma fold_left_nil : forall {A B} (f:A->B->A) a,
List.fold_left f nil a = a.
Proof using Type. reflexivity. Qed.
Lemma fold_left_cons : forall a b bs,
fold_left f (b::bs) a = fold_left f bs (f a b).
Proof using Type. reflexivity. Qed.
Lemma fold_left_snoc a x ls:
@fold_left A B f (ls ++ [x]) a = f (fold_left f ls a) x.
Proof using Type.
rewrite <-(rev_involutive ls), <-rev_cons.
rewrite !fold_right_rev_left; reflexivity.
Qed.
End FoldLeft.
#[global]
Hint Rewrite @fold_left_nil @fold_left_cons @fold_left_snoc : simpl_fold_left push_fold_left.
(** new operations *)
Definition enumerate {A} (ls : list A) : list (nat * A)
:= combine (seq 0 (length ls)) ls.
End List.
#[global]
Hint Rewrite @firstn_skipn : simpl_firstn.
#[global]
Hint Rewrite @firstn_skipn : simpl_skipn.
#[global]
Hint Rewrite @firstn_nil @firstn_cons @List.firstn_all @firstn_O @firstn_app_2 @List.firstn_firstn : push_firstn.
#[global]
Hint Rewrite @firstn_nil @firstn_cons @List.firstn_all @firstn_O @firstn_app_2 @List.firstn_firstn : simpl_firstn.
#[global]
Hint Rewrite @firstn_app : push_firstn.
#[global]
Hint Rewrite <- @firstn_cons @firstn_app @List.firstn_firstn : pull_firstn.
#[global]
Hint Rewrite @firstn_all2 @removelast_firstn @firstn_removelast using lia : push_firstn.
#[global]
Hint Rewrite @firstn_all2 @removelast_firstn @firstn_removelast using lia : simpl_firstn.
Local Arguments value / _ _.
Local Arguments error / _.
Definition list_beq_hetero {A B} (f : A -> B -> bool)
:= fix list_beq_hetero (l1 : list A) (l2 : list B) : bool
:= match l1, l2 with
| [], [] => true
| [], _ | _, [] => false
| x :: xs, y :: ys => f x y && list_beq_hetero xs ys
end%bool.
Definition sum_firstn l n := fold_right Z.add 0%Z (firstn n l).
Definition sum xs := sum_firstn xs (length xs).
Section map2.
Context {A B C}
(f : A -> B -> C).
Fixpoint map2 (la : list A) (lb : list B) : list C :=
match la, lb with
| nil, _ => nil
| _, nil => nil
| a :: la', b :: lb'
=> f a b :: map2 la' lb'
end.
End map2.
(* xs[n] := f xs[n] *)
Fixpoint update_nth {T} n f (xs:list T) {struct n} :=
match n with
| O => match xs with
| nil => nil
| x'::xs' => f x'::xs'
end
| S n' => match xs with
| nil => nil
| x'::xs' => x'::update_nth n' f xs'
end
end.
(* xs[n] := x *)
Definition set_nth {T} n x (xs:list T)
:= update_nth n (fun _ => x) xs.
Definition splice_nth {T} n (x:T) xs := firstn n xs ++ x :: skipn (S n) xs.
#[global]
Hint Unfold splice_nth : core.
Fixpoint take_while {T} (f : T -> bool) (ls : list T) : list T
:= match ls with
| nil => nil
| cons x xs => if f x then x :: @take_while T f xs else nil
end.
Fixpoint drop_while {T} (f : T -> bool) (ls : list T) : list T
:= match ls with
| nil => nil
| cons x xs => if f x then @drop_while T f xs else x :: xs
end.
Ltac boring :=
simpl; intuition auto with zarith datatypes;
repeat match goal with
| [ H : _ |- _ ] => rewrite H; clear H
| [ |- context[match ?pf with end] ] => solve [ case pf ]
| _ => progress autounfold in *
| _ => progress autorewrite with core
| _ => progress simpl in *
| _ => progress intuition auto with zarith datatypes
end; eauto.
Ltac boring_list :=
repeat match goal with
| _ => progress boring
| _ => progress autorewrite with distr_length simpl_nth_default simpl_update_nth simpl_set_nth simpl_nth_error in *
end.
Section Relations.
Fixpoint list_eq {A B} eq (x : list A) (y : list B) :=
match x, y with
| [], [] => True
| [], _ | _, [] => False
| x :: xs, y :: ys => eq x y /\ list_eq eq xs ys
end.
Local Ltac t :=
repeat first [ progress cbn in *
| progress break_match
| intro
| intuition congruence
| progress destruct_head'_and
| solve [ apply reflexivity
| apply symmetry; eassumption
| eapply transitivity; eassumption
| eauto ] ].
Fixpoint list_eq_refl {T} {R} {Reflexive_R:@Reflexive T R} (ls : list T) : list_eq R ls ls.
Proof. destruct ls; cbn; repeat split; auto. Defined.
Global Instance Reflexive_list_eq {T} {R} {Reflexive_R:@Reflexive T R}
: Reflexive (list_eq R) | 1
:= list_eq_refl.
Lemma list_eq_sym {A B} {R1 R2 : _ -> _ -> Prop} (HR : forall v1 v2, R1 v1 v2 -> R2 v2 v1)
: forall v1 v2, @list_eq A B R1 v1 v2 -> list_eq R2 v2 v1.
Proof. induction v1; t. Qed.
Lemma list_eq_trans {A B C} {R1 R2 R3 : _ -> _ -> Prop}
(HR : forall v1 v2 v3, R1 v1 v2 -> R2 v2 v3 -> R3 v1 v3)
: forall v1 v2 v3, @list_eq A B R1 v1 v2 -> @list_eq B C R2 v2 v3 -> @list_eq A C R3 v1 v3.
Proof. induction v1; t. Qed.
Global Instance Transitive_list_eq {T} {R} {Transitive_R:@Transitive T R}
: Transitive (list_eq R) | 1 := list_eq_trans Transitive_R.
Global Instance Symmetric_list_eq {T} {R} {Symmetric_R:@Symmetric T R}
: Symmetric (list_eq R) | 1 := list_eq_sym Symmetric_R.
Global Instance Equivalence_list_eq {T} {R} {Equivalence_R:@Equivalence T R}
: Equivalence (list_eq R). Proof. split; exact _. Qed.
End Relations.
Definition list_leq_to_eq {A} {x y : list A} : x = y -> list_eq eq x y.
Proof. destruct 1; reflexivity. Defined.
Fixpoint list_eq_to_leq {A} {x y : list A} {struct x} : list_eq eq x y -> x = y.
Proof.
destruct x, y; cbn; try reflexivity; destruct 1; try apply f_equal2; eauto.
Defined.
Lemma list_leq_to_eq_refl {A x} : @list_leq_to_eq A x x eq_refl = reflexivity _.
Proof. destruct x; cbn; reflexivity. Qed.
Lemma list_eq_to_leq_refl {A x} : @list_eq_to_leq A x x (reflexivity _) = eq_refl.
Proof.
induction x as [|x xs IH]; cbn; rewrite ?IH; try reflexivity.
Qed.
Lemma list_leq_to_eq_to_leq {A x y} v : @list_eq_to_leq A x y (@list_leq_to_eq A x y v) = v.
Proof.
now subst; rewrite list_leq_to_eq_refl, list_eq_to_leq_refl.
Qed.
Lemma list_eq_to_leq_to_eq {A x y} v : @list_leq_to_eq A x y (@list_eq_to_leq A x y v) = v.
Proof.
revert y v.
induction x as [|x xs IH], y as [|y ys]; try specialize (IH ys); cbn.
1-3: intro H; destruct H; reflexivity.
intro H; destruct H as [? H]; subst; specialize (IH H).
cbv [list_leq_to_eq] in *; subst.
break_innermost_match_hyps; subst; reflexivity.
Qed.
Lemma UIP_nil {A} (p q : @nil A = @nil A) : p = q.
Proof.
rewrite <- (list_leq_to_eq_to_leq p), <- (list_leq_to_eq_to_leq q); simpl; reflexivity.
Qed.
Lemma invert_list_eq {A x y} (p : @list_eq A A eq x y) : { pf : x = y | list_leq_to_eq pf = p }.
Proof. eexists; apply list_eq_to_leq_to_eq. Qed.
Lemma invert_eq_list {A x y} (p : x = y) : { pf : @list_eq A A eq x y | list_eq_to_leq pf = p }.
Proof. eexists; apply list_leq_to_eq_to_leq. Qed.
Ltac destr_list_eq H :=
lazymatch type of H with
| True => first [ clear H | destruct H ]
| False => destruct H
| _ = _ /\ _
=> let H' := fresh in
destruct H as [H' H];
destr_list_eq H
| list_eq eq _ _
=> first [ apply list_eq_to_leq in H
| let H' := fresh in
rename H into H';
destruct (invert_list_eq H') as [H ?]; subst H' ]
end.
Ltac inversion_list_step :=
match goal with
| [ H : nil = nil |- _ ] => clear H
| [ H : cons _ _ = nil |- _ ] => solve [ inversion H ]
| [ H : nil = cons _ _ |- _ ] => solve [ inversion H ]
| [ H : nil = nil |- _ ]
=> assert (eq_refl = H) by apply UIP_nil; subst H
| [ H : cons _ _ = cons _ _ |- _ ]
=> apply list_leq_to_eq in H; cbn [list_eq] in H;
destr_list_eq H
| [ H : cons _ _ = cons _ _ |- _ ]
=> let H' := fresh in
rename H into H';
destruct (invert_eq_list H') as [H ?]; subst H';
cbn [list_eq] in H; destr_list_eq H
end.
Ltac inversion_list := repeat inversion_list_step.
Lemma list_bl_hetero {A B} {AB_beq : A -> B -> bool} {AB_R : A -> B -> Prop}
(AB_bl : forall x y, AB_beq x y = true -> AB_R x y)
: forall {x y},
list_beq_hetero AB_beq x y = true -> list_eq AB_R x y.
Proof using Type.
induction x, y; cbn in *; eauto; try congruence.
rewrite Bool.andb_true_iff; intuition eauto.
Qed.
Lemma list_lb_hetero {A B} {AB_beq : A -> B -> bool} {AB_R : A -> B -> Prop}
(AB_lb : forall x y, AB_R x y -> AB_beq x y = true)
: forall {x y},
list_eq AB_R x y -> list_beq_hetero AB_beq x y = true.
Proof using Type.
induction x, y; cbn in *; rewrite ?Bool.andb_true_iff; intuition (congruence || eauto).
Qed.
Lemma list_beq_hetero_uniform {A : Type} A_beq {x y}
: list_beq_hetero A_beq x y = @list_beq A A_beq x y.
Proof. destruct x, y; cbn; reflexivity. Qed.
Lemma list_bl_hetero_eq {A}
{A_beq : A -> A -> bool}
(A_bl : forall x y, A_beq x y = true -> x = y)
{x y}
: list_beq_hetero A_beq x y = true -> x = y.
Proof using Type. rewrite list_beq_hetero_uniform; now apply internal_list_dec_bl. Qed.
Lemma list_lb_hetero_eq {A}
{A_beq : A -> A -> bool}
(A_lb : forall x y, x = y -> A_beq x y = true)
{x y}
: x = y -> list_beq_hetero A_beq x y = true.
Proof using Type. rewrite list_beq_hetero_uniform; now apply internal_list_dec_lb. Qed.
Lemma eqlistA_bl {A eqA} {R : relation A}
(H : forall x y : A, eqA x y = true -> R x y)
: forall x y, list_beq A eqA x y = true -> eqlistA R x y.
Proof.
induction x, y; cbn; auto; try discriminate; constructor.
all: rewrite Bool.andb_true_iff in *; destruct_head'_and; eauto.
Qed.
Lemma eqlistA_lb {A eqA} {R : relation A}
(H : forall x y : A, R x y -> eqA x y = true)
: forall x y, eqlistA R x y -> list_beq A eqA x y = true.
Proof.
induction x, y; cbn; auto; try discriminate; inversion 1; subst.
all: rewrite Bool.andb_true_iff; eauto.
Qed.
Lemma nth_default_cons : forall {T} (x u0 : T) us, nth_default x (u0 :: us) 0 = u0.
Proof. auto. Qed.
#[global]
Hint Rewrite @nth_default_cons : simpl_nth_default.
#[global]
Hint Rewrite @nth_default_cons : push_nth_default.
Lemma nth_default_cons_S : forall {A} us (u0 : A) n d,
nth_default d (u0 :: us) (S n) = nth_default d us n.
Proof. boring. Qed.
#[global]
Hint Rewrite @nth_default_cons_S : simpl_nth_default.
#[global]
Hint Rewrite @nth_default_cons_S : push_nth_default.
Lemma nth_default_nil : forall {T} n (d : T), nth_default d nil n = d.
Proof. induction n; boring. Qed.
#[global]
Hint Rewrite @nth_default_nil : simpl_nth_default.
#[global]
Hint Rewrite @nth_default_nil : push_nth_default.
Lemma nth_error_nil_error : forall {A} n, nth_error (@nil A) n = None.
Proof. induction n; boring. Qed.
#[global]
Hint Rewrite @nth_error_nil_error : simpl_nth_error.
Ltac nth_tac' :=
intros; simpl in *; unfold error,value in *; repeat progress (match goal with
| [ |- context[nth_error nil ?n] ] => rewrite nth_error_nil_error
| [ H: ?x = Some _ |- context[match ?x with Some _ => ?a | None => ?a end ] ] => destruct x
| [ H: ?x = None _ |- context[match ?x with Some _ => ?a | None => ?a end ] ] => destruct x
| [ |- context[match ?x with Some _ => ?a | None => ?a end ] ] => destruct x
| [ |- context[match nth_error ?xs ?i with Some _ => _ | None => _ end ] ] => case_eq (nth_error xs i); intros
| [ |- context[(if lt_dec ?a ?b then _ else _) = _] ] => destruct (lt_dec a b)
| [ |- context[_ = (if lt_dec ?a ?b then _ else _)] ] => destruct (lt_dec a b)
| [ H: context[(if lt_dec ?a ?b then _ else _) = _] |- _ ] => destruct (lt_dec a b)
| [ H: context[_ = (if lt_dec ?a ?b then _ else _)] |- _ ] => destruct (lt_dec a b)
| [ H: _ /\ _ |- _ ] => destruct H
| [ H: Some _ = Some _ |- _ ] => injection H; clear H; intros; subst
| [ H: None = Some _ |- _ ] => inversion H
| [ H: Some _ = None |- _ ] => inversion H
| [ |- Some _ = Some _ ] => apply f_equal
end); eauto; try (autorewrite with list in *); try lia; eauto.
Lemma nth_error_map {A B f n l}
: nth_error (@map A B f l) n = option_map f (nth_error l n).
Proof. revert n; induction l, n; nth_tac'. Qed.
Lemma nth_error_map_ex : forall A B (f:A->B) i xs y,
nth_error (map f xs) i = Some y ->
exists x, nth_error xs i = Some x /\ f x = y.
Proof. intros *; rewrite nth_error_map; edestruct nth_error; nth_tac'. Qed.
Lemma nth_error_seq : forall i start len,
nth_error (seq start len) i =
if lt_dec i len
then Some (start + i)
else None.
induction i as [|? IHi]; destruct len; nth_tac'; erewrite IHi; nth_tac'.
Qed.
Lemma nth_error_error_length : forall A i (xs:list A), nth_error xs i = None ->
i >= length xs.
Proof.
induction i as [|? IHi]; destruct xs; nth_tac'; try match goal with H : _ |- _ => specialize (IHi _ H) end; lia.
Qed.
Lemma nth_error_value_length : forall A i (xs:list A) x, nth_error xs i = Some x ->
i < length xs.
Proof.
induction i as [|? IHi]; destruct xs; nth_tac'; try match goal with H : _ |- _ => specialize (IHi _ _ H) end; lia.
Qed.
Lemma nth_error_length_error : forall A i (xs:list A),
i >= length xs ->
nth_error xs i = None.
Proof.
induction i as [|? IHi]; destruct xs; nth_tac'; rewrite IHi by lia; auto.
Qed.
Global Hint Resolve nth_error_length_error : core.
#[global]
Hint Rewrite @nth_error_length_error using lia : simpl_nth_error.
Lemma map_nth_default : forall (A B : Type) (f : A -> B) n x y l,
(n < length l) -> nth_default y (map f l) n = f (nth_default x l n).
Proof.
intros A B f n x y l H.
unfold nth_default.
erewrite map_nth_error.
reflexivity.
nth_tac'.
let H0 := match goal with H0 : _ = None |- _ => H0 end in
pose proof (nth_error_error_length A n l H0).
lia.
Qed.
#[global]
Hint Rewrite @map_nth_default using lia : push_nth_default.
Ltac nth_tac :=
repeat progress (try nth_tac'; try (match goal with
| [ H: nth_error (map _ _) _ = Some _ |- _ ] => destruct (nth_error_map_ex _ _ _ _ _ _ H); clear H
| [ H: nth_error (seq _ _) _ = Some _ |- _ ] => rewrite nth_error_seq in H
| [H: nth_error _ _ = None |- _ ] => specialize (nth_error_error_length _ _ _ H); intro; clear H
end)).
Lemma app_cons_app_app : forall T xs (y:T) ys, xs ++ y :: ys = (xs ++ (y::nil)) ++ ys.
Proof. induction xs; boring. Qed.
Lemma unfold_set_nth {T} n x
: forall xs,
@set_nth T n x xs
= match n with
| O => match xs with
| nil => nil
| x'::xs' => x::xs'
end
| S n' => match xs with
| nil => nil
| x'::xs' => x'::set_nth n' x xs'
end
end.
Proof.
induction n; destruct xs; reflexivity.
Qed.
Lemma simpl_set_nth_0 {T} x
: forall xs,
@set_nth T 0 x xs
= match xs with
| nil => nil
| x'::xs' => x::xs'
end.
Proof. intro; rewrite unfold_set_nth; reflexivity. Qed.
Lemma simpl_set_nth_S {T} x n
: forall xs,
@set_nth T (S n) x xs
= match xs with
| nil => nil
| x'::xs' => x'::set_nth n x xs'
end.
Proof. intro; rewrite unfold_set_nth; reflexivity. Qed.
#[global]
Hint Rewrite @simpl_set_nth_S @simpl_set_nth_0 : simpl_set_nth.
Lemma update_nth_ext {T} f g n
: forall xs, (forall x, nth_error xs n = Some x -> f x = g x)
-> @update_nth T n f xs = @update_nth T n g xs.
Proof.
induction n as [|n IHn]; destruct xs; simpl; intros H;
try rewrite IHn; try rewrite H;
try congruence; trivial.
Qed.
Global Instance update_nth_Proper {T}
: Proper (eq ==> pointwise_relation _ eq ==> eq ==> eq) (@update_nth T).
Proof. repeat intro; subst; apply update_nth_ext; trivial. Qed.
Global Instance update_nth_Proper_eq {A} : Proper (eq ==> (eq ==> eq) ==> eq ==> eq) (@update_nth A) | 1.
Proof. repeat intro; subst; apply update_nth_Proper; repeat intro; eauto. Qed.
Lemma update_nth_id_eq_specific {T} f n
: forall (xs : list T) (H : forall x, nth_error xs n = Some x -> f x = x),
update_nth n f xs = xs.
Proof.
induction n as [|n IHn]; destruct xs; simpl; intros H;
try rewrite IHn; try rewrite H; unfold value in *;
try congruence; assumption.
Qed.
#[global]
Hint Rewrite @update_nth_id_eq_specific using congruence : simpl_update_nth.
Lemma update_nth_id_eq : forall {T} f (H : forall x, f x = x) n (xs : list T),
update_nth n f xs = xs.
Proof. intros; apply update_nth_id_eq_specific; trivial. Qed.
#[global]
Hint Rewrite @update_nth_id_eq using congruence : simpl_update_nth.
Lemma update_nth_id : forall {T} n (xs : list T),
update_nth n (fun x => x) xs = xs.
Proof. intros; apply update_nth_id_eq; trivial. Qed.
#[global]
Hint Rewrite @update_nth_id : simpl_update_nth.
Lemma nth_update_nth : forall m {T} (xs:list T) (n:nat) (f:T -> T),
nth_error (update_nth m f xs) n =
if eq_nat_dec n m
then option_map f (nth_error xs n)
else nth_error xs n.
Proof.
induction m as [|? IHm].
{ destruct n, xs; auto. }
{ destruct xs, n; intros; simpl; auto;
[ | rewrite IHm ]; clear IHm;
edestruct eq_nat_dec; reflexivity. }
Qed.
#[global]
Hint Rewrite @nth_update_nth : push_nth_error.
#[global]
Hint Rewrite <- @nth_update_nth : pull_nth_error.
Lemma length_update_nth : forall {T} i f (xs:list T), length (update_nth i f xs) = length xs.
Proof.
induction i, xs; boring.
Qed.
#[global]
Hint Rewrite @length_update_nth : distr_length.
Lemma nth_set_nth : forall m {T} (xs:list T) (n:nat) x,
nth_error (set_nth m x xs) n =
if eq_nat_dec n m
then (if lt_dec n (length xs) then Some x else None)
else nth_error xs n.
Proof.
intros m T xs n x; unfold set_nth; rewrite nth_update_nth.
destruct (nth_error xs n) eqn:?, (lt_dec n (length xs)) as [p|p];
rewrite <- nth_error_Some in p;
solve [ reflexivity
| exfalso; apply p; congruence ].
Qed.
#[global]
Hint Rewrite @nth_set_nth : push_nth_error.
Lemma length_set_nth : forall {T} i x (xs:list T), length (set_nth i x xs) = length xs.
Proof. intros; apply length_update_nth. Qed.
#[global]
Hint Rewrite @length_set_nth : distr_length.
Lemma nth_error_length_exists_value : forall {A} (i : nat) (xs : list A),
(i < length xs)%nat -> exists x, nth_error xs i = Some x.
Proof.
induction i, xs; boring; try lia.
Qed.
Lemma nth_error_length_not_error : forall {A} (i : nat) (xs : list A),
nth_error xs i = None -> (i < length xs)%nat -> False.
Proof.
intros A i xs H H0.
destruct (nth_error_length_exists_value i xs); intuition; congruence.
Qed.
Lemma nth_error_value_eq_nth_default : forall {T} i (x : T) xs,
nth_error xs i = Some x -> forall d, nth_default d xs i = x.
Proof.
unfold nth_default; boring.
Qed.
#[global]
Hint Rewrite @nth_error_value_eq_nth_default using eassumption : simpl_nth_default.
Lemma skipn0 : forall {T} (xs:list T), skipn 0 xs = xs.
Proof. auto. Qed.
Lemma destruct_repeat : forall {A} xs y, (forall x : A, In x xs -> x = y) ->
xs = nil \/ exists xs', xs = y :: xs' /\ (forall x : A, In x xs' -> x = y).
Proof.
destruct xs as [|? xs]; intros; try tauto.
right.
exists xs; split.
+ f_equal; auto using in_eq.
+ intros; auto using in_cons.
Qed.
Lemma splice_nth_equiv_update_nth : forall {T} n f d (xs:list T),
splice_nth n (f (nth_default d xs n)) xs =
if lt_dec n (length xs)
then update_nth n f xs
else xs ++ (f d)::nil.
Proof.
induction n, xs; boring_list; break_match; auto; lia.
Qed.
Lemma splice_nth_equiv_update_nth_update : forall {T} n f d (xs:list T),
n < length xs ->
splice_nth n (f (nth_default d xs n)) xs = update_nth n f xs.
Proof.
intros.
rewrite splice_nth_equiv_update_nth; break_match; auto; lia.
Qed.
Lemma splice_nth_equiv_update_nth_snoc : forall {T} n f d (xs:list T),
n >= length xs ->
splice_nth n (f (nth_default d xs n)) xs = xs ++ (f d)::nil.
Proof.
intros.
rewrite splice_nth_equiv_update_nth; break_match; auto; lia.
Qed.
Definition IMPOSSIBLE {T} : list T. exact nil. Qed.
Ltac remove_nth_error :=
repeat match goal with
| _ => exfalso; solve [ eauto using @nth_error_length_not_error ]
| [ |- context[match nth_error ?ls ?n with _ => _ end] ]
=> destruct (nth_error ls n) eqn:?
end.
Lemma update_nth_equiv_splice_nth: forall {T} n f (xs:list T),
update_nth n f xs =
if lt_dec n (length xs)
then match nth_error xs n with
| Some v => splice_nth n (f v) xs
| None => IMPOSSIBLE
end
else xs.
Proof.
induction n as [|? IHn]; destruct xs; intros;
autorewrite with simpl_update_nth simpl_nth_default in *; simpl in *;
try (erewrite IHn; clear IHn); auto.
repeat break_match; remove_nth_error; try reflexivity; try lia.
Qed.
Lemma splice_nth_equiv_set_nth : forall {T} n x (xs:list T),
splice_nth n x xs =
if lt_dec n (length xs)
then set_nth n x xs
else xs ++ x::nil.
Proof. intros T n x xs; rewrite splice_nth_equiv_update_nth with (f := fun _ => x); auto. Qed.
Lemma splice_nth_equiv_set_nth_set : forall {T} n x (xs:list T),
n < length xs ->
splice_nth n x xs = set_nth n x xs.
Proof. intros T n x xs H; rewrite splice_nth_equiv_update_nth_update with (f := fun _ => x); auto. Qed.
Lemma splice_nth_equiv_set_nth_snoc : forall {T} n x (xs:list T),
n >= length xs ->
splice_nth n x xs = xs ++ x::nil.
Proof. intros T n x xs H; rewrite splice_nth_equiv_update_nth_snoc with (f := fun _ => x); auto. Qed.
Lemma set_nth_equiv_splice_nth: forall {T} n x (xs:list T),
set_nth n x xs =
if lt_dec n (length xs)
then splice_nth n x xs
else xs.
Proof.
intros T n x xs; unfold set_nth; rewrite update_nth_equiv_splice_nth with (f := fun _ => x); auto.
repeat break_match; remove_nth_error; trivial.
Qed.
Lemma combine_update_nth : forall {A B} n f g (xs:list A) (ys:list B),
combine (update_nth n f xs) (update_nth n g ys) =
update_nth n (fun xy => (f (fst xy), g (snd xy))) (combine xs ys).
Proof.
induction n as [|? IHn]; destruct xs, ys; simpl; try rewrite IHn; reflexivity.
Qed.
(* grumble, grumble, [rewrite] is bad at inferring the identity function, and constant functions *)
Ltac rewrite_rev_combine_update_nth :=
let lem := match goal with
| [ |- context[update_nth ?n (fun xy => (@?f xy, @?g xy)) (combine ?xs ?ys)] ]
=> let f := match (eval cbv [fst] in (fun y x => f (x, y))) with
| fun _ => ?f => f
end in
let g := match (eval cbv [snd] in (fun x y => g (x, y))) with
| fun _ => ?g => g
end in
constr:(@combine_update_nth _ _ n f g xs ys)
end in
rewrite <- lem.
Lemma combine_update_nth_l : forall {A B} n (f : A -> A) xs (ys:list B),
combine (update_nth n f xs) ys =
update_nth n (fun xy => (f (fst xy), snd xy)) (combine xs ys).
Proof.
intros ??? f xs ys.
etransitivity; [ | apply combine_update_nth with (g := fun x => x) ].
rewrite update_nth_id; reflexivity.
Qed.
Lemma combine_update_nth_r : forall {A B} n (g : B -> B) (xs:list A) (ys:list B),
combine xs (update_nth n g ys) =
update_nth n (fun xy => (fst xy, g (snd xy))) (combine xs ys).
Proof.
intros ??? g xs ys.
etransitivity; [ | apply combine_update_nth with (f := fun x => x) ].
rewrite update_nth_id; reflexivity.
Qed.
Lemma combine_set_nth : forall {A B} n (x:A) xs (ys:list B),
combine (set_nth n x xs) ys =
match nth_error ys n with
| None => combine xs ys
| Some y => set_nth n (x,y) (combine xs ys)
end.
Proof.
intros A B n x xs ys; unfold set_nth; rewrite combine_update_nth_l.
nth_tac;
[ repeat rewrite_rev_combine_update_nth; apply f_equal2
| assert (nth_error (combine xs ys) n = None)
by (apply nth_error_None; rewrite combine_length; lia * ) ];
autorewrite with simpl_update_nth; reflexivity.
Qed.
Lemma nth_error_value_In : forall {T} n xs (x:T),
nth_error xs n = Some x -> In x xs.
Proof.
induction n; destruct xs; nth_tac.
Qed.
Lemma In_nth_error_value : forall {T} xs (x:T),
In x xs -> exists n, nth_error xs n = Some x.
Proof.
induction xs as [|?? IHxs]; nth_tac; destruct_head or; subst.
- exists 0; reflexivity.
- edestruct IHxs as [x0]; eauto. exists (S x0). eauto.
Qed.
Lemma nth_value_index : forall {T} i xs (x:T),
nth_error xs i = Some x -> In i (seq 0 (length xs)).
Proof.
induction i as [|? IHi]; destruct xs; nth_tac; right.
rewrite <- seq_shift; apply in_map; eapply IHi; eauto.
Qed.
Lemma nth_error_app : forall {T} n (xs ys:list T), nth_error (xs ++ ys) n =
if lt_dec n (length xs)
then nth_error xs n
else nth_error ys (n - length xs).
Proof.
induction n as [|n IHn]; destruct xs as [|? xs]; nth_tac;
rewrite IHn; destruct (lt_dec n (length xs)); trivial; lia.
Qed.
Lemma nth_default_app : forall {T} n x (xs ys:list T), nth_default x (xs ++ ys) n =
if lt_dec n (length xs)
then nth_default x xs n
else nth_default x ys (n - length xs).
Proof.
intros T n x xs ys.
unfold nth_default.
rewrite nth_error_app.
destruct (lt_dec n (length xs)); auto.
Qed.
#[global]
Hint Rewrite @nth_default_app : push_nth_default.
Lemma combine_truncate_r : forall {A B} (xs : list A) (ys : list B),
combine xs ys = combine xs (firstn (length xs) ys).
Proof.
induction xs; destruct ys; boring.
Qed.
Lemma combine_truncate_l : forall {A B} (xs : list A) (ys : list B),
combine xs ys = combine (firstn (length ys) xs) ys.
Proof.
induction xs; destruct ys; boring.
Qed.
Lemma combine_app_samelength : forall {A B} (xs xs':list A) (ys ys':list B),
length xs = length ys ->
combine (xs ++ xs') (ys ++ ys') = combine xs ys ++ combine xs' ys'.
Proof.
induction xs, xs', ys, ys'; boring; lia.
Qed.
Lemma map_fst_combine {A B} (xs:list A) (ys:list B) : List.map fst (List.combine xs ys) = List.firstn (length ys) xs.
Proof.
revert xs; induction ys; destruct xs; simpl; solve [ trivial | congruence ].
Qed.
Lemma map_snd_combine {A B} (xs:list A) (ys:list B) : List.map snd (List.combine xs ys) = List.firstn (length xs) ys.
Proof.
revert xs; induction ys; destruct xs; simpl; solve [ trivial | congruence ].
Qed.
#[global]
Hint Rewrite @map_fst_combine @map_snd_combine : push_map.
Lemma skipn_nil : forall {A} n, skipn n nil = @nil A.
Proof. destruct n; auto. Qed.
#[global]
Hint Rewrite @skipn_nil : simpl_skipn.
#[global]
Hint Rewrite @skipn_nil : push_skipn.
Lemma skipn_0 : forall {A} xs, @skipn A 0 xs = xs.
Proof. reflexivity. Qed.
#[global]
Hint Rewrite @skipn_0 : simpl_skipn.
#[global]
Hint Rewrite @skipn_0 : push_skipn.
Lemma skipn_cons_S : forall {A} n x xs, @skipn A (S n) (x::xs) = @skipn A n xs.
Proof. reflexivity. Qed.
#[global]
Hint Rewrite @skipn_cons_S : simpl_skipn.
#[global]
Hint Rewrite @skipn_cons_S : push_skipn.
Lemma skipn_app : forall {A} n (xs ys : list A),
skipn n (xs ++ ys) = skipn n xs ++ skipn (n - length xs) ys.
Proof.
induction n, xs, ys; boring.
Qed.
#[global]
Hint Rewrite @skipn_app : push_skipn.
Lemma skipn_skipn {A} n1 n2 (ls : list A)
: skipn n2 (skipn n1 ls) = skipn (n1 + n2) ls.
Proof.
revert n2 ls; induction n1, ls;
simpl; autorewrite with simpl_skipn;
boring.
Qed.
#[global]
Hint Rewrite @skipn_skipn : simpl_skipn.
#[global]
Hint Rewrite <- @skipn_skipn : push_skipn.
#[global]
Hint Rewrite @skipn_skipn : pull_skipn.
Lemma skipn_firstn {A} (ls : list A) n m
: skipn n (firstn m ls) = firstn (m - n) (skipn n ls).
Proof.
revert n m; induction ls, m, n; simpl; autorewrite with simpl_skipn simpl_firstn; boring_list.
Qed.
Lemma firstn_skipn_add {A} (ls : list A) n m
: firstn n (skipn m ls) = skipn m (firstn (m + n) ls).
Proof.
revert n m; induction ls, m; simpl; autorewrite with simpl_skipn simpl_firstn; boring_list.
Qed.
Lemma firstn_skipn_add' {A} (ls : list A) n m
: firstn n (skipn m ls) = skipn m (firstn (n + m) ls).
Proof. rewrite firstn_skipn_add; do 2 f_equal; auto with arith. Qed.
#[global]
Hint Rewrite <- @firstn_skipn_add @firstn_skipn_add' : simpl_firstn.
#[global]
Hint Rewrite <- @firstn_skipn_add @firstn_skipn_add' : simpl_skipn.
Lemma firstn_app_inleft : forall {A} n (xs ys : list A), (n <= length xs)%nat ->
firstn n (xs ++ ys) = firstn n xs.
Proof.
induction n, xs, ys; boring; try lia.
Qed.
#[global]
Hint Rewrite @firstn_app_inleft using solve [ distr_length ] : simpl_firstn.
#[global]
Hint Rewrite @firstn_app_inleft using solve [ distr_length ] : push_firstn.
Lemma skipn_app_inleft : forall {A} n (xs ys : list A), (n <= length xs)%nat ->
skipn n (xs ++ ys) = skipn n xs ++ ys.
Proof.
induction n, xs, ys; boring; try lia.
Qed.
#[global]
Hint Rewrite @skipn_app_inleft using solve [ distr_length ] : push_skipn.
Lemma firstn_map : forall {A B} (f : A -> B) n (xs : list A), firstn n (map f xs) = map f (firstn n xs).
Proof. induction n, xs; boring. Qed.
#[global]
Hint Rewrite @firstn_map : push_firstn.
#[global]
Hint Rewrite <- @firstn_map : pull_firstn.
Lemma skipn_map : forall {A B} (f : A -> B) n (xs : list A), skipn n (map f xs) = map f (skipn n xs).
Proof. induction n, xs; boring. Qed.
#[global]
Hint Rewrite @skipn_map : push_skipn.
#[global]
Hint Rewrite <- @skipn_map : pull_skipn.
Lemma firstn_all : forall {A} n (xs:list A), n = length xs -> firstn n xs = xs.
Proof.
induction n, xs; boring; lia.
Qed.
#[global]
Hint Rewrite @firstn_all using solve [ distr_length ] : simpl_firstn.
#[global]
Hint Rewrite @firstn_all using solve [ distr_length ] : push_firstn.
Lemma skipn_all : forall {T} n (xs:list T),
(n >= length xs)%nat ->
skipn n xs = nil.
Proof.
induction n, xs; boring; lia.
Qed.
#[global]
Hint Rewrite @skipn_all using solve [ distr_length ] : simpl_skipn.
#[global]
Hint Rewrite @skipn_all using solve [ distr_length ] : push_skipn.
Lemma firstn_app_sharp : forall {A} n (l l': list A),
length l = n ->
firstn n (l ++ l') = l.
Proof.
intros.
rewrite firstn_app_inleft; auto using firstn_all; lia.
Qed.
#[global]
Hint Rewrite @firstn_app_sharp using solve [ distr_length ] : simpl_firstn.
#[global]
Hint Rewrite @firstn_app_sharp using solve [ distr_length ] : push_firstn.
Lemma skipn_app_sharp : forall {A} n (l l': list A),
length l = n ->
skipn n (l ++ l') = l'.
Proof.
intros.
rewrite skipn_app_inleft; try rewrite skipn_all; auto; lia.
Qed.
#[global]
Hint Rewrite @skipn_app_sharp using solve [ distr_length ] : simpl_skipn.
#[global]
Hint Rewrite @skipn_app_sharp using solve [ distr_length ] : push_skipn.
Lemma skipn_length : forall {A} n (xs : list A),
length (skipn n xs) = (length xs - n)%nat.
Proof.
induction n, xs; boring.
Qed.
#[global]
Hint Rewrite @skipn_length : distr_length.
Lemma length_cons : forall {T} (x:T) xs, length (x::xs) = S (length xs).
reflexivity.
Qed.
#[global]
Hint Rewrite @length_cons : distr_length.
Lemma length_cons_full {T} n (x:list T) (t:T) (H: length (t :: x) = S n)
: length x = n.
Proof. distr_length. Qed.
Lemma cons_length : forall A (xs : list A) a, length (a :: xs) = S (length xs).
Proof.
auto.
Qed.
Lemma length0_nil : forall {A} (xs : list A), length xs = 0%nat -> xs = nil.
Proof.
induction xs; boring; discriminate.
Qed.
Lemma length_tl {A} ls : length (@tl A ls) = (length ls - 1)%nat.
Proof. destruct ls; cbn [tl length]; lia. Qed.
#[global]
Hint Rewrite @length_tl : distr_length.
Lemma length_snoc {A : Type} (l : list A) a : length (l ++ [a]) = S (length l).
Proof. simpl_list; boring. Qed.
#[global]
Hint Rewrite @length_snoc : distr_length.
Lemma combine_cons : forall {A B} a b (xs:list A) (ys:list B),
combine (a :: xs) (b :: ys) = (a,b) :: combine xs ys.
Proof. reflexivity. Qed.
#[global]
Hint Rewrite @combine_cons : push_combine.
Lemma firstn_combine : forall {A B} n (xs:list A) (ys:list B),
firstn n (combine xs ys) = combine (firstn n xs) (firstn n ys).
Proof.
induction n, xs, ys; boring.
Qed.
#[global]
Hint Rewrite @firstn_combine : push_firstn.
#[global]
Hint Rewrite <- @firstn_combine : pull_firstn.
Lemma combine_nil_r : forall {A B} (xs:list A),
combine xs (@nil B) = nil.
Proof.
induction xs; boring.
Qed.
#[global]
Hint Rewrite @combine_nil_r : push_combine.
Lemma combine_snoc {A B} xs : forall ys x y,
length xs = length ys ->
@combine A B (xs ++ (x :: nil)) (ys ++ (y :: nil)) = combine xs ys ++ ((x, y) :: nil).
Proof.
induction xs; intros; destruct ys; distr_length; cbn;
try rewrite IHxs by lia; reflexivity.
Qed.
#[global]
Hint Rewrite @combine_snoc using (solve [distr_length]) : push_combine.
Lemma skipn_combine : forall {A B} n (xs:list A) (ys:list B),
skipn n (combine xs ys) = combine (skipn n xs) (skipn n ys).
Proof.
induction n, xs, ys; boring.
rewrite combine_nil_r; reflexivity.
Qed.
#[global]
Hint Rewrite @skipn_combine : push_skipn.
#[global]
Hint Rewrite <- @skipn_combine : pull_skipn.
Lemma break_list_last: forall {T} (xs:list T),
xs = nil \/ exists xs' y, xs = xs' ++ y :: nil.
Proof.
destruct xs using rev_ind; auto.
right; do 2 eexists; auto.
Qed.
Lemma break_list_first: forall {T} (xs:list T),
xs = nil \/ exists x xs', xs = x :: xs'.
Proof.
destruct xs; auto.
right; do 2 eexists; auto.
Qed.
Lemma list012 : forall {T} (xs:list T),
xs = nil
\/ (exists x, xs = x::nil)
\/ (exists x xs' y, xs = x::xs'++y::nil).
Proof.
destruct xs as [|? xs]; auto.
right.
destruct xs using rev_ind. {
left; eexists; auto.
} {
right; repeat eexists; auto.
}
Qed.
Lemma nil_length0 : forall {T}, length (@nil T) = 0%nat.
Proof.
auto.
Qed.
#[global]
Hint Rewrite @nil_length0 : distr_length.
Lemma nth_error_Some_nth_default : forall {T} i x (l : list T), (i < length l)%nat ->
nth_error l i = Some (nth_default x l i).
Proof.
intros ? ? ? ? i_lt_length.
destruct (nth_error_length_exists_value _ _ i_lt_length) as [k nth_err_k].
unfold nth_default.
rewrite nth_err_k.
reflexivity.
Qed.
Lemma update_nth_cons : forall {T} f (u0 : T) us, update_nth 0 f (u0 :: us) = (f u0) :: us.
Proof. reflexivity. Qed.
#[global]
Hint Rewrite @update_nth_cons : simpl_update_nth.
Lemma set_nth_cons : forall {T} (x u0 : T) us, set_nth 0 x (u0 :: us) = x :: us.
Proof. intros; apply update_nth_cons. Qed.
#[global]
Hint Rewrite @set_nth_cons : simpl_set_nth.
Lemma cons_update_nth : forall {T} n f (y : T) us,
y :: update_nth n f us = update_nth (S n) f (y :: us).
Proof.
induction n; boring.
Qed.
#[global]
Hint Rewrite <- @cons_update_nth : simpl_update_nth.
Lemma update_nth_nil : forall {T} n f, update_nth n f (@nil T) = @nil T.
Proof.
induction n; boring.
Qed.
#[global]
Hint Rewrite @update_nth_nil : simpl_update_nth.
Lemma cons_set_nth : forall {T} n (x y : T) us,
y :: set_nth n x us = set_nth (S n) x (y :: us).
Proof. intros; apply cons_update_nth. Qed.
#[global]
Hint Rewrite <- @cons_set_nth : simpl_set_nth.
Lemma set_nth_nil : forall {T} n (x : T), set_nth n x nil = nil.
Proof. intros; apply update_nth_nil. Qed.
#[global]
Hint Rewrite @set_nth_nil : simpl_set_nth.
Lemma skipn_nth_default : forall {T} n us (d : T), (n < length us)%nat ->
skipn n us = nth_default d us n :: skipn (S n) us.
Proof.
induction n as [|n IHn]; destruct us as [|? us]; intros d H; nth_tac.
rewrite (IHn us d) at 1 by lia.
nth_tac.
Qed.
Lemma nth_default_out_of_bounds : forall {T} n us (d : T), (n >= length us)%nat ->
nth_default d us n = d.
Proof.
induction n as [|n IHn]; unfold nth_default; nth_tac;
let us' := match goal with us : list _ |- _ => us end in
destruct us' as [|? us]; nth_tac.
assert (n >= length us)%nat by lia.
pose proof (nth_error_length_error _ n us).
specialize_by_assumption.
rewrite_hyp * in *.
congruence.
Qed.
#[global]
Hint Rewrite @nth_default_out_of_bounds using lia : simpl_nth_default.
Ltac nth_error_inbounds :=
match goal with
| [ |- context[match nth_error ?xs ?i with Some _ => _ | None => _ end ] ] =>
case_eq (nth_error xs i);
match goal with
| [ |- forall _, nth_error xs i = Some _ -> _ ] =>
let x := fresh "x" in
let H := fresh "H" in
intros x H;
repeat progress erewrite H;
repeat progress erewrite (nth_error_value_eq_nth_default i xs x); auto
| [ |- nth_error xs i = None -> _ ] =>
let H := fresh "H" in
intros H;
destruct (nth_error_length_not_error _ _ H);
try solve [distr_length]
end;
idtac
end.
Ltac set_nth_inbounds :=
match goal with
| [ |- context[set_nth ?i ?x ?xs] ] =>
rewrite (set_nth_equiv_splice_nth i x xs);
destruct (lt_dec i (length xs));
match goal with
| [ H : ~ (i < (length xs))%nat |- _ ] => destruct H
| [ H : (i < (length xs))%nat |- _ ] => try solve [distr_length]
end
end.
Ltac update_nth_inbounds :=
match goal with
| [ |- context[update_nth ?i ?f ?xs] ] =>
rewrite (update_nth_equiv_splice_nth i f xs);
destruct (lt_dec i (length xs));
match goal with
| [ H : ~ (i < (length xs))%nat |- _ ] => destruct H
| [ H : (i < (length xs))%nat |- _ ] => remove_nth_error; try solve [distr_length]
end
end.
Ltac nth_inbounds := nth_error_inbounds || set_nth_inbounds || update_nth_inbounds.
Definition nth_dep {A} (ls : list A) (n : nat) (pf : n < length ls) : A.
Proof.
refine (match nth_error ls n as v return nth_error ls n = v -> A with
| Some v => fun _ => v
| None => fun bad => match _ : False with end
end eq_refl).
apply (proj1 (@nth_error_None _ _ _)) in bad; generalize dependent (length ls); clear.
abstract (intros; lia).
Defined.
Lemma nth_error_nth_dep {A} ls n pf : nth_error ls n = Some (@nth_dep A ls n pf).
Proof.
unfold nth_dep.
generalize dependent (@nth_error_None A ls n).
edestruct nth_error; boring.
Qed.
Lemma nth_default_nth_dep {A} d ls n pf : nth_default d ls n = @nth_dep A ls n pf.
Proof.
unfold nth_dep.
generalize dependent (@nth_error_None A ls n).
destruct (nth_error ls n) eqn:?; boring.
erewrite nth_error_value_eq_nth_default by eassumption; reflexivity.
Qed.
Lemma nth_default_in_bounds : forall {T} (d' d : T) n us, (n < length us)%nat ->
nth_default d us n = nth_default d' us n.
Proof.
intros; now unshelve erewrite !nth_default_nth_dep.
Qed.
Global Hint Resolve nth_default_in_bounds : simpl_nth_default.
Lemma cons_eq_head : forall {T} (x y:T) xs ys, x::xs = y::ys -> x=y.
Proof.
intros; congruence.
Qed.
Lemma cons_eq_tail : forall {T} (x y:T) xs ys, x::xs = y::ys -> xs=ys.
Proof.
intros; congruence.
Qed.
Lemma map_nth_default_always {A B} (f : A -> B) (n : nat) (x : A) (l : list A)
: nth_default (f x) (map f l) n = f (nth_default x l n).
Proof.
revert n; induction l; simpl; intro n; destruct n; [ try reflexivity.. ].
nth_tac.
Qed.
#[global]
Hint Rewrite @map_nth_default_always : push_nth_default.
Lemma map_S_seq {A} (f:nat->A) len : forall start,
List.map (fun i => f (S i)) (seq start len) = List.map f (seq (S start) len).
Proof. induction len as [|len IHlen]; intros; simpl; rewrite ?IHlen; reflexivity. Qed.
Lemma seq_snoc len : forall start, seq start (S len) = seq start len ++ ((start + len)%nat :: nil).
Proof.
induction len; intros.
{ cbv [seq app]. autorewrite with natsimplify; reflexivity. }
{ remember (S len); simpl seq.
rewrite (IHlen (S start)); subst; simpl seq.
rewrite Nat.add_succ_r; reflexivity. }
Qed.
Lemma seq_len_0 a : seq a 0 = nil. Proof. reflexivity. Qed.
Lemma seq_add start a b : seq start (a + b) = seq start a ++ seq (start + a) b.
Proof.
revert start b; induction a as [|a IHa]; cbn; intros start b.
{ f_equal; lia. }
{ rewrite IHa; do 3 f_equal; lia. }
Qed.
Lemma map_seq_ext {A} (f g : nat -> A) (n m k : nat)
(H : forall i : nat, n <= i <= m + k -> f i = g (i + (m - n))%nat)
(Hnm : n <= m) :
map f (seq n k) = map g (seq m k).
Proof.
generalize dependent m; generalize dependent n; induction k as [|k IHk]; intros; simpl.
- reflexivity.
- simpl; rewrite H by lia; replace (n + (m - n))%nat with m by lia.
rewrite (IHk (S n) (S m)); [reflexivity| |lia].
intros; rewrite Nat.sub_succ; apply H; lia. Qed.
Lemma map_seq_pred n m :
seq n m = map (fun i => (i - 1)%nat) (seq (S n) m).
Proof. rewrite <- map_id at 1; apply map_seq_ext; intros; lia. Qed.
Lemma map_seq_succ n m :
seq (S n) m = map (fun i => (i + 1)%nat) (seq n m).
Proof. rewrite <- map_id at 1; symmetry; apply map_seq_ext; intros; lia. Qed.
Lemma fold_right_and_Truth_forall_In_iff : forall {T} (l : list T) (P : T -> Prop) (Tr : Prop),
(Tr /\ forall x, In x l -> P x) <-> fold_right and Tr (map P l).
Proof.
induction l as [|?? IHl]; intros; simpl; try tauto.
rewrite <- IHl by assumption.
intuition (subst; auto).
Qed.
Lemma fold_right_and_True_forall_In_iff : forall {T} (l : list T) (P : T -> Prop),
(forall x, In x l -> P x) <-> fold_right and True (map P l).
Proof.
intros; rewrite <- fold_right_and_Truth_forall_In_iff; tauto.
Qed.
Lemma fold_right_invariant : forall {A B} P (f: A -> B -> B) l x,
P x -> (forall y, In y l -> forall z, P z -> P (f y z)) ->
P (fold_right f x l).
Proof.
induction l as [|a l IHl]; intros ? ? step; auto.
simpl.
apply step; try apply in_eq.
apply IHl; auto.
intros y in_y_l.
apply (in_cons a) in in_y_l.
auto.
Qed.
Lemma fold_left_and_Truth_forall_In_iff : forall {T} (l : list T) (P : T -> Prop) (Tr : Prop),
(Tr /\ forall x, In x l -> P x) <-> fold_left and (map P l) Tr.
Proof.
induction l as [|?? IHl]; intros; simpl; try tauto.
rewrite <- IHl.
intuition (subst; auto).
Qed.
Lemma fold_left_and_True_forall_In_iff : forall {T} (l : list T) (P : T -> Prop),
(forall x, In x l -> P x) <-> fold_left and (map P l) True.
Proof.
intros; rewrite <- fold_left_and_Truth_forall_In_iff; tauto.
Qed.
Lemma fold_left_invariant : forall {A B} P (f: B -> A -> B) l x,
P x -> (forall y, In y l -> forall z, P z -> P (f z y)) ->
P (fold_left f l x).
Proof.
pose proof in_rev.
split_iff.
intros; rewrite <- fold_left_rev_right; eapply fold_right_invariant;
eauto.
Qed.
Lemma In_firstn : forall {T} n l (x : T), In x (firstn n l) -> In x l.
Proof.
induction n; destruct l; boring.
Qed.
Lemma In_skipn : forall {T} n l (x : T), In x (skipn n l) -> In x l.
Proof.
induction n; destruct l; boring.
Qed.
Lemma In_firstn_skipn_split {T} n (x : T)
: forall l, In x l <-> In x (firstn n l) \/ In x (skipn n l).
Proof.
intro l; split; revert l; induction n; destruct l; boring.
match goal with
| [ IH : forall l, In ?x l -> _ \/ _, H' : In ?x ?ls |- _ ]
=> destruct (IH _ H')
end; auto.
Qed.
Lemma firstn_firstn_min : forall {A} m n (l : list A),
firstn n (firstn m l) = firstn (min n m) l.
Proof.
induction m as [|? IHm]; destruct n; intros l; try lia; auto.
destruct l; auto.
simpl.
f_equal.
apply IHm; lia.
Qed.
Lemma firstn_firstn : forall {A} m n (l : list A), (n <= m)%nat ->
firstn n (firstn m l) = firstn n l.
Proof.
intros A m n l H; rewrite firstn_firstn_min.
apply Min.min_case_strong; intro; [ reflexivity | ].
assert (n = m) by lia; subst; reflexivity.
Qed.
#[global]
Hint Rewrite @firstn_firstn using lia : push_firstn.
Lemma firstn_succ : forall {A} (d : A) n l, (n < length l)%nat ->
firstn (S n) l = (firstn n l) ++ nth_default d l n :: nil.
Proof.
intros A d; induction n as [|? IHn]; destruct l; rewrite ?(@nil_length0 A); intros; try lia.
+ rewrite nth_default_cons; auto.
+ simpl.
rewrite nth_default_cons_S.
rewrite <-IHn by (rewrite cons_length in *; lia).
reflexivity.
Qed.
Lemma firstn_seq k a b
: firstn k (seq a b) = seq a (min k b).
Proof.
revert k a; induction b as [|? IHb], k; simpl; try reflexivity.
intros; rewrite IHb; reflexivity.
Qed.
#[global]
Hint Rewrite @firstn_seq : push_firstn.
Lemma skipn_seq k a b
: skipn k (seq a b) = seq (k + a) (b - k).
Proof.
revert k a; induction b as [|? IHb], k; simpl; try reflexivity.
intros; rewrite IHb; simpl; f_equal; lia.
Qed.
Lemma update_nth_out_of_bounds : forall {A} n f xs, n >= length xs -> @update_nth A n f xs = xs.
Proof.
induction n as [|n IHn]; destruct xs; simpl; try congruence; try lia; intros.
rewrite IHn by lia; reflexivity.
Qed.
#[global]
Hint Rewrite @update_nth_out_of_bounds using lia : simpl_update_nth.
Lemma update_nth_nth_default_full : forall {A} (d:A) n f l i,
nth_default d (update_nth n f l) i =
if lt_dec i (length l) then
if (eq_nat_dec i n) then f (nth_default d l i)
else nth_default d l i
else d.
Proof.
induction n as [|n IHn]; (destruct l; simpl in *; [ intros i **; destruct i; simpl; try reflexivity; lia | ]);
intros i **; repeat break_match; subst; try destruct i;
repeat first [ progress break_match
| progress subst
| progress boring
| progress autorewrite with simpl_nth_default
| lia ].
Qed.
#[global]
Hint Rewrite @update_nth_nth_default_full : push_nth_default.
Lemma update_nth_nth_default : forall {A} (d:A) n f l i, (0 <= i < length l)%nat ->
nth_default d (update_nth n f l) i =
if (eq_nat_dec i n) then f (nth_default d l i) else nth_default d l i.
Proof. intros; rewrite update_nth_nth_default_full; repeat break_match; boring. Qed.
#[global]
Hint Rewrite @update_nth_nth_default using (lia || distr_length; lia) : push_nth_default.
Lemma set_nth_nth_default_full : forall {A} (d:A) n v l i,
nth_default d (set_nth n v l) i =
if lt_dec i (length l) then
if (eq_nat_dec i n) then v
else nth_default d l i
else d.
Proof. intros; apply update_nth_nth_default_full; assumption. Qed.
#[global]
Hint Rewrite @set_nth_nth_default_full : push_nth_default.
Lemma set_nth_nth_default : forall {A} (d:A) n x l i, (0 <= i < length l)%nat ->
nth_default d (set_nth n x l) i =
if (eq_nat_dec i n) then x else nth_default d l i.
Proof. intros; apply update_nth_nth_default; assumption. Qed.
#[global]
Hint Rewrite @set_nth_nth_default using (lia || distr_length; lia) : push_nth_default.
Lemma nth_default_preserves_properties : forall {A} (P : A -> Prop) l n d,
(forall x, In x l -> P x) -> P d -> P (nth_default d l n).
Proof.
intros A P l n d H H0; rewrite nth_default_eq.
destruct (nth_in_or_default n l d); auto.
congruence.
Qed.
Lemma nth_default_preserves_properties_length_dep :
forall {A} (P : A -> Prop) l n d,
(forall x, In x l -> n < (length l) -> P x) -> ((~ n < length l) -> P d) -> P (nth_default d l n).
Proof.
intros A P l n d H H0.
destruct (lt_dec n (length l)).
+ rewrite nth_default_eq; auto using nth_In.
+ rewrite nth_default_out_of_bounds by lia.
auto.
Qed.
Lemma nth_error_first : forall {T} (a b : T) l,
nth_error (a :: l) 0 = Some b -> a = b.
Proof.
intros; simpl in *.
unfold value in *.
congruence.
Qed.
Lemma nth_error_exists_first : forall {T} l (x : T) (H : nth_error l 0 = Some x),
exists l', l = x :: l'.
Proof.
induction l; try discriminate; intros x H; eexists.
apply nth_error_first in H.
subst; eauto.
Qed.
Lemma list_elementwise_eq : forall {T} (l1 l2 : list T),
(forall i, nth_error l1 i = nth_error l2 i) -> l1 = l2.
Proof.
induction l1, l2; intros H; try reflexivity;
pose proof (H 0%nat) as Hfirst; simpl in Hfirst; inversion Hfirst.
f_equal.
apply IHl1.
intros i; specialize (H (S i)).
boring.
Qed.
Lemma sum_firstn_all_succ : forall n l, (length l <= n)%nat ->
sum_firstn l (S n) = sum_firstn l n.
Proof.
unfold sum_firstn; intros.
autorewrite with push_firstn; reflexivity.
Qed.
#[global]
Hint Rewrite @sum_firstn_all_succ using lia : simpl_sum_firstn.
Lemma sum_firstn_all : forall n l, (length l <= n)%nat ->
sum_firstn l n = sum_firstn l (length l).
Proof.
unfold sum_firstn; intros.
autorewrite with push_firstn; reflexivity.
Qed.
#[global]
Hint Rewrite @sum_firstn_all using lia : simpl_sum_firstn.
Lemma sum_firstn_succ_default : forall l i,
sum_firstn l (S i) = (nth_default 0 l i + sum_firstn l i)%Z.
Proof.
unfold sum_firstn; induction l as [|a l IHl], i;
intros; autorewrite with simpl_nth_default simpl_firstn simpl_fold_right in *;
try reflexivity.
rewrite IHl; lia.
Qed.
#[global]
Hint Rewrite @sum_firstn_succ_default : simpl_sum_firstn.
Lemma sum_firstn_0 : forall xs,
sum_firstn xs 0 = 0%Z.
Proof.
destruct xs; reflexivity.
Qed.
#[global]
Hint Rewrite @sum_firstn_0 : simpl_sum_firstn.
Lemma sum_firstn_succ : forall l i x,
nth_error l i = Some x ->
sum_firstn l (S i) = (x + sum_firstn l i)%Z.
Proof.
intros; rewrite sum_firstn_succ_default.
erewrite nth_error_value_eq_nth_default by eassumption; reflexivity.
Qed.
#[global]
Hint Rewrite @sum_firstn_succ using congruence : simpl_sum_firstn.
Lemma sum_firstn_succ_cons : forall x xs i,
sum_firstn (x :: xs) (S i) = (x + sum_firstn xs i)%Z.
Proof.
unfold sum_firstn; simpl; reflexivity.
Qed.
#[global]
Hint Rewrite @sum_firstn_succ_cons : simpl_sum_firstn.
Lemma sum_firstn_nil : forall i,
sum_firstn nil i = 0%Z.
Proof. destruct i; reflexivity. Qed.
#[global]
Hint Rewrite @sum_firstn_nil : simpl_sum_firstn.
Lemma sum_firstn_succ_default_rev : forall l i,
sum_firstn l i = (sum_firstn l (S i) - nth_default 0 l i)%Z.
Proof.
intros; rewrite sum_firstn_succ_default; lia.
Qed.
Lemma sum_firstn_succ_rev : forall l i x,
nth_error l i = Some x ->
sum_firstn l i = (sum_firstn l (S i) - x)%Z.
Proof.
intros; erewrite sum_firstn_succ by eassumption; lia.
Qed.
Lemma sum_firstn_nonnegative : forall n l, (forall x, In x l -> 0 <= x)%Z
-> (0 <= sum_firstn l n)%Z.
Proof.
induction n as [|n IHn]; destruct l as [|? l]; autorewrite with simpl_sum_firstn; simpl; try lia.
{ specialize (IHn l).
destruct n; simpl; autorewrite with simpl_sum_firstn simpl_nth_default in *;
intuition auto with zarith. }
Qed.
Global Hint Resolve sum_firstn_nonnegative : znonzero.
Lemma sum_firstn_app : forall xs ys n,
sum_firstn (xs ++ ys) n = (sum_firstn xs n + sum_firstn ys (n - length xs))%Z.
Proof.
induction xs as [|a xs IHxs]; simpl.
{ intros ys n; autorewrite with simpl_sum_firstn; simpl.
f_equal; lia. }
{ intros ys [|n]; autorewrite with simpl_sum_firstn; simpl; [ reflexivity | ].
rewrite IHxs; lia. }
Qed.
Lemma sum_firstn_app_sum : forall xs ys n,
sum_firstn (xs ++ ys) (length xs + n) = (sum_firstn xs (length xs) + sum_firstn ys n)%Z.
Proof.
intros; rewrite sum_firstn_app; autorewrite with simpl_sum_firstn.
do 2 f_equal; lia.
Qed.
#[global]
Hint Rewrite @sum_firstn_app_sum : simpl_sum_firstn.
Lemma sum_cons xs x : sum (x :: xs) = (x + sum xs)%Z.
Proof. reflexivity. Qed.
#[global]
Hint Rewrite sum_cons : push_sum.
Lemma sum_nil : sum nil = 0%Z.
Proof. reflexivity. Qed.
#[global]
Hint Rewrite sum_nil : push_sum.
Lemma sum_app x y : sum (x ++ y) = (sum x + sum y)%Z.
Proof. induction x; rewrite ?app_nil_l, <-?app_comm_cons; autorewrite with push_sum; lia. Qed.
#[global]
Hint Rewrite sum_app : push_sum.
Lemma sum_rev x : sum (rev x) = sum x.
Proof. induction x; cbn [rev]; autorewrite with push_sum; lia. Qed.
#[global]
Hint Rewrite sum_rev : push_sum.
Lemma nth_error_skipn : forall {A} n (l : list A) m,
nth_error (skipn n l) m = nth_error l (n + m).
Proof.
induction n as [|n IHn]; destruct l; boring.
apply nth_error_nil_error.
Qed.
#[global]
Hint Rewrite @nth_error_skipn : push_nth_error.
Lemma nth_default_skipn : forall {A} (l : list A) d n m, nth_default d (skipn n l) m = nth_default d l (n + m).
Proof.
cbv [nth_default]; intros.
rewrite nth_error_skipn.
reflexivity.
Qed.
#[global]
Hint Rewrite @nth_default_skipn : push_nth_default.
Lemma sum_firstn_skipn : forall l n m, sum_firstn l (n + m) = (sum_firstn l n + sum_firstn (skipn n l) m)%Z.
Proof.
induction m; intros.
+ rewrite sum_firstn_0. autorewrite with natsimplify. lia.
+ rewrite <-plus_n_Sm, !sum_firstn_succ_default.
rewrite nth_default_skipn.
lia.
Qed.
Lemma nth_default_seq_inbounds d s n i (H:(i < n)%nat) :
List.nth_default d (List.seq s n) i = (s+i)%nat.
Proof.
progress cbv [List.nth_default].
rewrite nth_error_seq.
break_innermost_match; solve [ trivial | lia ].
Qed.
#[global]
Hint Rewrite @nth_default_seq_inbounds using lia : push_nth_default.
Lemma sum_firstn_prefix_le' : forall l n m, (forall x, In x l -> (0 <= x)%Z) ->
(sum_firstn l n <= sum_firstn l (n + m))%Z.
Proof.
intros l n m H.
rewrite sum_firstn_skipn.
pose proof (sum_firstn_nonnegative m (skipn n l)) as Hskipn_nonneg.
match type of Hskipn_nonneg with
?P -> _ => assert P as Q; [ | specialize (Hskipn_nonneg Q); lia ] end.
intros x HIn_skipn.
apply In_skipn in HIn_skipn.
auto.
Qed.
Lemma sum_firstn_prefix_le : forall l n m, (forall x, In x l -> (0 <= x)%Z) ->
(n <= m)%nat ->
(sum_firstn l n <= sum_firstn l m)%Z.
Proof.
intros l n m H H0.
replace m with (n + (m - n))%nat by lia.
auto using sum_firstn_prefix_le'.
Qed.
Lemma sum_firstn_pos_lt_succ : forall l n m, (forall x, In x l -> (0 <= x)%Z) ->
(n < length l)%nat ->
(sum_firstn l n < sum_firstn l (S m))%Z ->
(n <= m)%nat.
Proof.
intros l n m H H0 H1.
destruct (le_dec n m); auto.
replace n with (m + (n - m))%nat in H1 by lia.
rewrite sum_firstn_skipn in H1.
rewrite sum_firstn_succ_default in *.
match goal with H : (?a + ?b < ?c + ?a)%Z |- _ => assert (H2 : (b < c)%Z) by lia end.
destruct (lt_dec m (length l)). {
rewrite skipn_nth_default with (d := 0%Z) in H2 by assumption.
replace (n - m)%nat with (S (n - S m))%nat in H2 by lia.
rewrite sum_firstn_succ_cons in H2.
pose proof (sum_firstn_nonnegative (n - S m) (skipn (S m) l)) as H3.
match type of H3 with
?P -> _ => assert P as Q; [ | specialize (H3 Q); lia ] end.
intros ? A.
apply In_skipn in A.
apply H in A.
lia.
} {
rewrite skipn_all, nth_default_out_of_bounds in H2 by lia.
rewrite sum_firstn_nil in H2; lia.
}
Qed.
Definition NotSum {T} (xs : list T) (v : nat) := True.
Ltac NotSum :=
lazymatch goal with
| [ |- NotSum ?xs (length ?xs + _)%nat ] => fail
| [ |- NotSum _ _ ] => exact I
end.
Lemma sum_firstn_app_hint : forall xs ys n, NotSum xs n ->
sum_firstn (xs ++ ys) n = (sum_firstn xs n + sum_firstn ys (n - length xs))%Z.
Proof. auto using sum_firstn_app. Qed.
#[global]
Hint Rewrite sum_firstn_app_hint using solve [ NotSum ] : simpl_sum_firstn.
Lemma nth_default_map2 : forall {A B C} (f : A -> B -> C) ls1 ls2 i d d1 d2,
nth_default d (map2 f ls1 ls2) i =
if lt_dec i (min (length ls1) (length ls2))
then f (nth_default d1 ls1 i) (nth_default d2 ls2 i)
else d.
Proof.
induction ls1 as [|a ls1 IHls1], ls2.
+ cbv [map2 length min].
intros.
break_match; try lia.
apply nth_default_nil.
+ cbv [map2 length min].
intros.
break_match; try lia.
apply nth_default_nil.
+ cbv [map2 length min].
intros.
break_match; try lia.
apply nth_default_nil.
+ simpl.
destruct i.
- intros. rewrite !nth_default_cons.
break_match; auto; lia.
- intros d d1 d2. rewrite !nth_default_cons_S.
rewrite IHls1 with (d1 := d1) (d2 := d2).
repeat break_match; auto; lia.
Qed.
Lemma map2_cons : forall A B C (f : A -> B -> C) ls1 ls2 a b,
map2 f (a :: ls1) (b :: ls2) = f a b :: map2 f ls1 ls2.
Proof.
reflexivity.
Qed.
Lemma map2_nil_l : forall A B C (f : A -> B -> C) ls2,
map2 f nil ls2 = nil.
Proof.
reflexivity.
Qed.
Lemma map2_nil_r : forall A B C (f : A -> B -> C) ls1,
map2 f ls1 nil = nil.
Proof.
destruct ls1; reflexivity.
Qed.
Local Hint Resolve map2_nil_r map2_nil_l : core.
Ltac simpl_list_lengths := repeat match goal with
| H : context[length (@nil ?A)] |- _ => rewrite (@nil_length0 A) in H
| H : context[length (_ :: _)] |- _ => rewrite length_cons in H
| |- context[length (@nil ?A)] => rewrite (@nil_length0 A)
| |- context[length (_ :: _)] => rewrite length_cons
end.
Section OpaqueMap2.
Local Opaque map2.
Lemma map2_length : forall A B C (f : A -> B -> C) ls1 ls2,
length (map2 f ls1 ls2) = min (length ls1) (length ls2).
Proof.
induction ls1 as [|a ls1 IHls1], ls2; intros; try solve [cbv; auto].
rewrite map2_cons, !length_cons, IHls1.
auto.
Qed.
Hint Rewrite @map2_length : distr_length.
Lemma map2_app : forall A B C (f : A -> B -> C) ls1 ls2 ls1' ls2',
(length ls1 = length ls2) ->
map2 f (ls1 ++ ls1') (ls2 ++ ls2') = map2 f ls1 ls2 ++ map2 f ls1' ls2'.
Proof.
induction ls1 as [|a ls1 IHls1], ls2; intros; rewrite ?map2_nil_r, ?app_nil_l; try congruence;
simpl_list_lengths; try lia.
rewrite <-!app_comm_cons, !map2_cons.
rewrite IHls1; auto.
Qed.
End OpaqueMap2.
#[global]
Hint Rewrite @map2_length : distr_length.
Lemma firstn_update_nth {A}
: forall f m n (xs : list A), firstn m (update_nth n f xs) = update_nth n f (firstn m xs).
Proof.
induction m; destruct n, xs;
autorewrite with simpl_firstn simpl_update_nth;
congruence.
Qed.
#[global]
Hint Rewrite @firstn_update_nth : push_firstn.
#[global]
Hint Rewrite @firstn_update_nth : pull_update_nth.
#[global]
Hint Rewrite <- @firstn_update_nth : pull_firstn.
#[global]
Hint Rewrite <- @firstn_update_nth : push_update_nth.
Global Instance fold_right_Proper {A B} : Proper (pointwise_relation _ (pointwise_relation _ eq) ==> eq ==> eq ==> eq) (@fold_right A B) | 1.
Proof.
cbv [pointwise_relation]; intros f g Hfg x y ? ls ls' ?; subst y ls'; revert x.
induction ls as [|l ls IHls]; cbn [fold_right]; intro; rewrite ?IHls, ?Hfg; reflexivity.
Qed.
Global Instance fold_right_Proper_eq {A B} : Proper ((eq ==> eq ==> eq) ==> eq ==> eq ==> eq) (@fold_right A B) | 1.
Proof. cbv [respectful]; repeat intro; subst; apply fold_right_Proper; repeat intro; eauto. Qed.
Global Instance fold_left_Proper {A B} : Proper (pointwise_relation _ (pointwise_relation _ eq) ==> eq ==> eq ==> eq) (@fold_left A B) | 1.
Proof.
repeat intro; rewrite <- !fold_left_rev_right; apply fold_right_Proper; cbv [pointwise_relation] in *; eauto; congruence.
Qed.
Global Instance fold_left_Proper_eq {A B} : Proper ((eq ==> eq ==> eq) ==> eq ==> eq ==> eq) (@fold_left A B) | 1.
Proof. cbv [respectful]; repeat intro; subst; apply fold_left_Proper; repeat intro; eauto. Qed.
Require Import Coq.Lists.SetoidList.
Global Instance Proper_nth_default : forall A eq,
Proper (eq==>eqlistA eq==>Logic.eq==>eq) (nth_default (A:=A)).
Proof.
intros A ee x y H; subst; induction 1.
+ repeat intro; rewrite !nth_default_nil; assumption.
+ intros x1 y0 H2; subst; destruct y0; rewrite ?nth_default_cons, ?nth_default_cons_S; auto.
Qed.
Lemma fold_right_andb_true_map_iff A (ls : list A) f
: List.fold_right andb true (List.map f ls) = true <-> forall i, List.In i ls -> f i = true.
Proof.
induction ls as [|a ls IHls]; simpl; [ | rewrite Bool.andb_true_iff, IHls ]; try tauto.
intuition (congruence || eauto).
Qed.
Lemma fold_right_andb_true_iff_fold_right_and_True (ls : list bool)
: List.fold_right andb true ls = true <-> List.fold_right and True (List.map (fun b => b = true) ls).
Proof.
rewrite <- (map_id ls) at 1.
rewrite fold_right_andb_true_map_iff, fold_right_and_True_forall_In_iff; reflexivity.
Qed.
Lemma fold_left_andb_true_map_iff A (ls : list A) f
: List.fold_left andb (List.map f ls) true = true <-> forall i, List.In i ls -> f i = true.
Proof.
rewrite <- fold_left_rev_right, <- map_rev; setoid_rewrite Bool.andb_comm.
rewrite fold_right_andb_true_map_iff.
setoid_rewrite <- in_rev; reflexivity.
Qed.
Lemma fold_left_andb_true_iff_fold_left_and_True (ls : list bool)
: List.fold_left andb ls true = true <-> List.fold_left and (List.map (fun b => b = true) ls) True.
Proof.
rewrite <- (map_id ls) at 1.
rewrite fold_left_andb_true_map_iff, fold_left_and_True_forall_In_iff; reflexivity.
Qed.
Lemma fold_right_andb_truth_map_iff A (ls : list A) f t
: List.fold_right andb t (List.map f ls) = true <-> (t = true /\ forall i, List.In i ls -> f i = true).
Proof.
induction ls as [|a ls IHls]; simpl; [ | rewrite Bool.andb_true_iff, IHls ]; try tauto.
intuition (congruence || eauto).
Qed.
Lemma fold_right_andb_truth_iff_fold_right_and_Truth (ls : list bool) t
: List.fold_right andb t ls = true <-> List.fold_right and (t = true) (List.map (fun b => b = true) ls).
Proof.
rewrite <- (map_id ls) at 1.
rewrite fold_right_andb_truth_map_iff, fold_right_and_Truth_forall_In_iff; reflexivity.
Qed.
Lemma fold_left_andb_truth_map_iff A (ls : list A) f t
: List.fold_left andb (List.map f ls) t = true <-> (t = true /\ forall i, List.In i ls -> f i = true).
Proof.
rewrite <- fold_left_rev_right, <- map_rev; setoid_rewrite Bool.andb_comm.
rewrite fold_right_andb_truth_map_iff.
setoid_rewrite <- in_rev; reflexivity.
Qed.
Lemma fold_left_andb_truth_iff_fold_left_and_Truth (ls : list bool) t
: List.fold_left andb ls t = true <-> List.fold_left and (List.map (fun b => b = true) ls) (t = true).
Proof.
rewrite <- (map_id ls) at 1.
rewrite fold_left_andb_truth_map_iff, fold_left_and_Truth_forall_In_iff; reflexivity.
Qed.
Lemma Forall2_forall_iff : forall {A B} (R : A -> B -> Prop) (xs : list A) (ys : list B) d1 d2, length xs = length ys ->
(Forall2 R xs ys <-> (forall i, (i < length xs)%nat -> R (nth_default d1 xs i) (nth_default d2 ys i))).
Proof.
intros A B R xs ys d1 d2 H; split; [ intros H0 i H1 | intros H0 ].
+ revert xs ys H H0 H1.
induction i as [|i IHi]; intros xs ys H H0 H1; destruct H0; distr_length; autorewrite with push_nth_default; auto.
eapply IHi; auto. lia.
+ revert xs ys H H0; induction xs as [|a xs IHxs]; intros ys H H0; destruct ys; distr_length; econstructor.
- specialize (H0 0%nat).
autorewrite with push_nth_default in *; auto.
apply H0; lia.
- apply IHxs; try lia.
intros i H1.
specialize (H0 (S i)).
autorewrite with push_nth_default in *; auto.
apply H0; lia.
Qed.
Lemma Forall2_forall_iff' : forall {A} R (xs ys : list A) d, length xs = length ys ->
(Forall2 R xs ys <-> (forall i, (i < length xs)%nat -> R (nth_default d xs i) (nth_default d ys i))).
Proof. intros; apply Forall2_forall_iff; assumption. Qed.
Lemma nth_default_firstn : forall {A} (d : A) l i n,
nth_default d (firstn n l) i = if le_dec n (length l)
then if lt_dec i n then nth_default d l i else d
else nth_default d l i.
Proof.
intros A d l i; induction n as [|n IHn]; break_match; autorewrite with push_nth_default; auto; try lia.
+ rewrite (firstn_succ d) by lia.
autorewrite with push_nth_default; repeat (break_match_hyps; break_match; distr_length);
rewrite Min.min_l in * by lia; try lia.
- apply IHn; lia.
- replace i with n in * by lia.
rewrite Nat.sub_diag.
autorewrite with push_nth_default; auto.
+ rewrite nth_default_out_of_bounds; break_match_hyps; distr_length; auto; lia.
+ rewrite firstn_all2 by lia.
auto.
Qed.
#[global]
Hint Rewrite @nth_default_firstn : push_nth_default.
Lemma nth_error_repeat {T} x n i v : nth_error (@repeat T x n) i = Some v -> v = x.
Proof.
revert n x v; induction i as [|i IHi]; destruct n; simpl in *; eauto; congruence.
Qed.
#[global]
Hint Rewrite repeat_length : distr_length.
Lemma repeat_spec_iff : forall {A} (ls : list A) x n,
(length ls = n /\ forall y, In y ls -> y = x) <-> ls = repeat x n.
Proof.
intros A ls x n; split; [ revert A ls x n | intro; subst; eauto using repeat_length, repeat_spec ].
induction ls as [|a ls IHls], n; simpl; intros; intuition try congruence.
f_equal; auto.
Qed.
Lemma repeat_spec_eq : forall {A} (ls : list A) x n,
length ls = n
-> (forall y, In y ls -> y = x)
-> ls = repeat x n.
Proof.
intros; apply repeat_spec_iff; auto.
Qed.
Lemma tl_repeat {A} x n : tl (@repeat A x n) = repeat x (pred n).
Proof. destruct n; reflexivity. Qed.
Lemma firstn_repeat : forall {A} x n k, firstn k (@repeat A x n) = repeat x (min k n).
Proof. induction n, k; boring. Qed.
#[global]
Hint Rewrite @firstn_repeat : push_firstn.
Lemma skipn_repeat : forall {A} x n k, skipn k (@repeat A x n) = repeat x (n - k).
Proof. induction n, k; boring. Qed.
#[global]
Hint Rewrite @skipn_repeat : push_skipn.
Global Instance Proper_map {A B} {RA RB} {Equivalence_RB:Equivalence RB}
: Proper ((RA==>RB) ==> eqlistA RA ==> eqlistA RB) (@List.map A B).
Proof.
repeat intro.
match goal with [H:eqlistA _ _ _ |- _ ] => induction H end; [reflexivity|].
cbv [respectful] in *; econstructor; eauto.
Qed.
Lemma pointwise_map {A B} : Proper ((pointwise_relation _ eq) ==> eq ==> eq) (@List.map A B).
Proof.
repeat intro; cbv [pointwise_relation] in *; subst.
match goal with [H:list _ |- _ ] => induction H as [|? IH IHIH] end; [reflexivity|].
simpl. rewrite IHIH. congruence.
Qed.
Lemma map_map2 {A B C D} (f:A -> B -> C) (g:C -> D) (xs:list A) (ys:list B) : List.map g (map2 f xs ys) = map2 (fun (a : A) (b : B) => g (f a b)) xs ys.
Proof.
revert ys; induction xs as [|a xs IHxs]; intros ys; [reflexivity|].
destruct ys; [reflexivity|].
simpl. rewrite IHxs. reflexivity.
Qed.
Lemma map2_fst {A B C} (f:A -> C) (xs:list A) : forall (ys:list B), length xs = length ys ->
map2 (fun (a : A) (_ : B) => f a) xs ys = List.map f xs.
Proof.
induction xs as [|a xs IHxs]; intros ys **; [reflexivity|].
destruct ys; [simpl in *; discriminate|].
simpl. rewrite IHxs by eauto. reflexivity.
Qed.
Lemma map2_flip {A B C} (f:A -> B -> C) (xs:list A) : forall (ys: list B),
map2 (fun b a => f a b) ys xs = map2 f xs ys.
Proof.
induction xs as [|a xs IHxs]; destruct ys; try reflexivity; [].
simpl. rewrite IHxs. reflexivity.
Qed.
Lemma map2_snd {A B C} (f:B -> C) (xs:list A) : forall (ys:list B), length xs = length ys ->
map2 (fun (_ : A) (b : B) => f b) xs ys = List.map f ys.
Proof. intros. rewrite map2_flip. eauto using map2_fst. Qed.
Lemma map2_map {A B C A' B'} (f:A -> B -> C) (g:A' -> A) (h:B' -> B) (xs:list A') (ys:list B')
: map2 f (List.map g xs) (List.map h ys) = map2 (fun a b => f (g a) (h b)) xs ys.
Proof.
revert ys; induction xs as [|a xs IHxs]; destruct ys; intros; try reflexivity; [].
simpl. rewrite IHxs. reflexivity.
Qed.
Definition expand_list_helper {A} (default : A) (ls : list A) (n : nat) (idx : nat) : list A
:= nat_rect
(fun _ => nat -> list A)
(fun _ => nil)
(fun n' rec_call idx
=> cons (List.nth_default default ls idx) (rec_call (S idx)))
n
idx.
Definition expand_list {A} (default : A) (ls : list A) (n : nat) : list A
:= expand_list_helper default ls n 0.
Lemma expand_list_helper_correct {A} (default : A) (ls : list A) (n idx : nat) (H : (idx + n <= length ls)%nat)
: expand_list_helper default ls n idx
= List.firstn n (List.skipn idx ls).
Proof.
cbv [expand_list_helper]; revert idx H.
induction n as [|n IHn]; cbn; intros.
{ reflexivity. }
{ rewrite IHn by lia.
erewrite (@skipn_nth_default _ idx ls) by lia.
reflexivity. }
Qed.
Lemma expand_list_correct (n : nat) {A} (default : A) (ls : list A) (H : List.length ls = n)
: expand_list default ls n = ls.
Proof.
subst; cbv [expand_list]; rewrite expand_list_helper_correct by reflexivity.
rewrite skipn_0, firstn_all; reflexivity.
Qed.
Ltac expand_lists _ :=
let default_for A :=
match goal with
| _ => (eval lazy in (_ : pointed A))
| _ => constr_fail_with ltac:(fun _ => idtac "Warning: could not infer a default value for list type" A)
end in
let T := lazymatch goal with |- _ = _ :> ?T => T end in
let v := fresh in
evar (v : T); transitivity v;
[ subst v
| repeat match goal with
| [ H : @List.length ?A ?f = ?n |- context[?f] ]
=> let v := default_for A in
rewrite <- (@expand_list_correct n A v f H);
clear H
end;
lazymatch goal with
| [ H : List.length ?f = _ |- context[?f] ]
=> fail 0 "Could not expand list" f
| _ => idtac
end;
subst v; reflexivity ].
Lemma single_list_rect_to_match A (P:list A -> Type) (Pnil: P nil) (PS: forall a tl, P (a :: tl)) ls :
@list_rect A P Pnil (fun a tl _ => PS a tl) ls = match ls with
| cons a tl => PS a tl
| nil => Pnil
end.
Proof. destruct ls; reflexivity. Qed.
Lemma partition_app A (f : A -> bool) (a b : list A)
: partition f (a ++ b) = (fst (partition f a) ++ fst (partition f b),
snd (partition f a) ++ snd (partition f b)).
Proof.
revert b; induction a, b; cbn; rewrite ?app_nil_r; eta_expand; try reflexivity.
rewrite !IHa; cbn; break_match; reflexivity.
Qed.
Lemma flat_map_map A B C (f : A -> B) (g : B -> list C) (xs : list A)
: flat_map g (map f xs) = flat_map (fun x => g (f x)) xs.
Proof. induction xs; cbn; congruence. Qed.
Lemma flat_map_singleton A B (f : A -> B) (xs : list A)
: flat_map (fun x => cons (f x) nil) xs = map f xs.
Proof. induction xs; cbn; congruence. Qed.
Lemma flat_map_ext A B (f g : A -> list B) xs (H : forall x, In x xs -> f x = g x)
: flat_map f xs = flat_map g xs.
Proof. induction xs; cbn in *; [ reflexivity | rewrite IHxs; f_equal ]; intros; intuition auto. Qed.
Global Instance flat_map_Proper A B : Proper (pointwise_relation _ eq ==> eq ==> eq) (@flat_map A B).
Proof. repeat intro; subst; apply flat_map_ext; auto. Qed.
Global Instance map_Proper_eq {A B} : Proper ((eq ==> eq) ==> eq ==> eq) (@List.map A B) | 1.
Proof. repeat intro; subst; apply pointwise_map; repeat intro; eauto. Qed.
Global Instance flat_map_Proper_eq {A B} : Proper ((eq ==> eq) ==> eq ==> eq) (@List.flat_map A B) | 1.
Proof. repeat intro; subst; apply flat_map_Proper; repeat intro; eauto. Qed.
Global Instance partition_Proper {A} : Proper (pointwise_relation _ eq ==> eq ==> eq) (@List.partition A).
Proof.
cbv [pointwise_relation]; intros f g Hfg ls ls' ?; subst ls'.
induction ls as [|l ls IHls]; cbn [partition]; rewrite ?IHls, ?Hfg; reflexivity.
Qed.
Global Instance partition_Proper_eq {A} : Proper ((eq ==> eq) ==> eq ==> eq) (@List.partition A) | 1.
Proof. repeat intro; subst; apply partition_Proper; repeat intro; eauto. Qed.
Lemma partition_map A B (f : B -> bool) (g : A -> B) xs
: partition f (map g xs) = (map g (fst (partition (fun x => f (g x)) xs)),
map g (snd (partition (fun x => f (g x)) xs))).
Proof. induction xs; cbn; [ | rewrite !IHxs ]; break_match; reflexivity. Qed.
Lemma map_fst_partition A B (f : B -> bool) (g : A -> B) xs
: map g (fst (partition (fun x => f (g x)) xs)) = fst (partition f (map g xs)).
Proof. rewrite partition_map; reflexivity. Qed.
Lemma map_snd_partition A B (f : B -> bool) (g : A -> B) xs
: map g (snd (partition (fun x => f (g x)) xs)) = snd (partition f (map g xs)).
Proof. rewrite partition_map; reflexivity. Qed.
Lemma partition_In A (f:A -> bool) xs : forall x, @In A x xs <-> @In A x (if f x then fst (partition f xs) else snd (partition f xs)).
Proof.
intro x; destruct (f x) eqn:?; split; intros; repeat apply conj; revert dependent x;
(induction xs as [|x' xs IHxs]; cbn; [ | destruct (f x') eqn:?, (partition f xs) ]; cbn in *; subst; intuition (subst; auto));
congruence.
Qed.
Lemma fst_partition_In A f xs : forall x, @In A x (fst (partition f xs)) <-> f x = true /\ @In A x xs.
Proof.
intro x; split; intros; repeat apply conj; revert dependent x;
(induction xs as [|x' xs IHxs]; cbn; [ | destruct (f x') eqn:?, (partition f xs) ]; cbn in *; subst; intuition (subst; auto));
congruence.
Qed.
Lemma snd_partition_In A f xs : forall x, @In A x (snd (partition f xs)) <-> f x = false /\ @In A x xs.
Proof.
intro x; split; intros; repeat apply conj; revert dependent x;
(induction xs as [|x' xs IHxs]; cbn; [ | destruct (f x') eqn:?, (partition f xs) ]; cbn in *; subst; intuition (subst; auto));
congruence.
Qed.
Lemma list_rect_map A B P (f : A -> B) N C ls
: @list_rect B P N C (map f ls) = @list_rect A (fun ls => P (map f ls)) N (fun x xs rest => C (f x) (map f xs) rest) ls.
Proof. induction ls as [|x xs IHxs]; cbn; [ | rewrite IHxs ]; reflexivity. Qed.
Lemma flat_map_app A B (f : A -> list B) xs ys
: flat_map f (xs ++ ys) = flat_map f xs ++ flat_map f ys.
Proof. induction xs as [|x xs IHxs]; cbn; rewrite ?IHxs, <- ?app_assoc; reflexivity. Qed.
#[global]
Hint Rewrite flat_map_app : push_flat_map.
Lemma map_flat_map A B C (f : A -> list B) (g : B -> C) xs
: map g (flat_map f xs) = flat_map (fun x => map g (f x)) xs.
Proof. induction xs as [|x xs IHxs]; cbn; rewrite ?map_app; congruence. Qed.
Lemma flat_map_rev A B (f : A -> list B) xs
: flat_map f (rev xs) = rev (flat_map (fun x => rev (f x)) xs).
Proof.
induction xs as [|x xs IHxs]; cbn; autorewrite with push_flat_map; rewrite ?rev_app_distr, ?IHxs, ?rev_involutive, ?app_nil_r; reflexivity.
Qed.
#[global]
Hint Rewrite flat_map_rev : push_flat_map.
Lemma rev_flat_map A B (f : A -> list B) xs
: rev (flat_map f xs) = flat_map (fun x => rev (f x)) (rev xs).
Proof. rewrite flat_map_rev; setoid_rewrite rev_involutive; reflexivity. Qed.
#[global]
Hint Rewrite rev_flat_map : push_rev.
Lemma combine_map_map A B C D (f : A -> B) (g : C -> D) xs ys
: combine (map f xs) (map g ys) = map (fun ab => (f (fst ab), g (snd ab))) (combine xs ys).
Proof. revert ys; induction xs, ys; cbn; congruence. Qed.
Lemma combine_map_l A B C (f : A -> B) xs ys
: @combine B C (map f xs) ys = map (fun ab => (f (fst ab), snd ab)) (combine xs ys).
Proof. rewrite <- combine_map_map with (f:=f) (g:=fun x => x), map_id; reflexivity. Qed.
Lemma combine_map_r A B C (f : B -> C) xs ys
: @combine A C xs (map f ys) = map (fun ab => (fst ab, f (snd ab))) (combine xs ys).
Proof. rewrite <- combine_map_map with (g:=f) (f:=fun x => x), map_id; reflexivity. Qed.
Lemma combine_same A xs
: @combine A A xs xs = map (fun x => (x, x)) xs.
Proof. induction xs; cbn; congruence. Qed.
Lemma if_singleton A (b:bool) (x y : A) : (if b then x::nil else y::nil) = (if b then x else y)::nil.
Proof. now case b. Qed.
Lemma flat_map_if_In A B (b : A -> bool) (f g : A -> list B) xs (b' : bool)
: (forall v, In v xs -> b v = b') -> flat_map (fun x => if b x then f x else g x) xs = if b' then flat_map f xs else flat_map g xs.
Proof. induction xs as [|x xs IHxs]; cbn; [ | intro H; rewrite IHxs, H by eauto ]; case b'; reflexivity. Qed.
Lemma flat_map_if_In_sumbool A B X Y (b : forall a : A, sumbool (X a) (Y a)) (f g : A -> list B) xs (b' : bool)
: (forall v, In v xs -> (if b v then true else false) = b') -> flat_map (fun x => if b x then f x else g x) xs = if b' then flat_map f xs else flat_map g xs.
Proof.
intro H; erewrite <- flat_map_if_In by refine H.
apply flat_map_Proper; [ intro | reflexivity ]; break_innermost_match; reflexivity.
Qed.
Lemma map_if_In A B (b : A -> bool) (f g : A -> B) xs (b' : bool)
: (forall v, In v xs -> b v = b') -> map (fun x => if b x then f x else g x) xs = if b' then map f xs else map g xs.
Proof. induction xs as [|x xs IHxs]; cbn; [ | intro H; rewrite IHxs, H by eauto ]; case b'; reflexivity. Qed.
Lemma map_if_In_sumbool A B X Y (b : forall a : A, sumbool (X a) (Y a)) (f g : A -> B) xs (b' : bool)
: (forall v, In v xs -> (if b v then true else false) = b') -> map (fun x => if b x then f x else g x) xs = if b' then map f xs else map g xs.
Proof.
intro H; erewrite <- map_if_In by refine H.
apply map_ext_in; intro; break_innermost_match; reflexivity.
Qed.
Lemma fold_right_map A B C (f : A -> B) xs (F : _ -> _ -> C) v
: fold_right F v (map f xs) = fold_right (fun x y => F (f x) y) v xs.
Proof. revert v; induction xs; cbn; intros; congruence. Qed.
Lemma fold_right_flat_map A B C (f : A -> list B) xs (F : _ -> _ -> C) v
: fold_right F v (flat_map f xs) = fold_right (fun x y => fold_right F y (f x)) v xs.
Proof. revert v; induction xs; cbn; intros; rewrite ?fold_right_app; congruence. Qed.
Lemma fold_right_ext_in A B f g v xs : (forall x y, List.In x xs -> f x y = g x y) -> @fold_right A B f v xs = fold_right g v xs.
Proof. induction xs; cbn; intro H; rewrite ?H, ?IHxs; auto. Qed.
Lemma fold_right_ext A B f g v xs : (forall x y, f x y = g x y) -> @fold_right A B f v xs = fold_right g v xs.
Proof. intros; apply fold_right_ext_in; eauto. Qed.
Lemma fold_right_id_ext A B f v xs : (forall x y, f x y = y) -> @fold_right A B f v xs = v.
Proof. induction xs; cbn; intro H; rewrite ?H; auto. Qed.
Lemma fold_left_map A B C f f' l a
: @fold_left A B f (@List.map C _ f' l) a = fold_left (fun x y => f x (f' y)) l a.
Proof. revert a; induction l; cbn [List.map List.fold_left]; auto. Qed.
Lemma fold_left_flat_map A B C (f : A -> list B) xs (F : _ -> _ -> C) v
: fold_left F (flat_map f xs) v = fold_left (fun x y => fold_left F (f y) x) xs v.
Proof. revert v; induction xs; cbn; intros; rewrite ?fold_left_app; congruence. Qed.
Lemma fold_left_ext_in A B f g v xs : (forall x y, List.In y xs -> f x y = g x y) -> @fold_left A B f xs v = fold_left g xs v.
Proof. intros; rewrite <- !fold_left_rev_right; apply fold_right_ext_in; intros *; rewrite <- in_rev; eauto. Qed.
Lemma fold_left_ext A B f g v xs : (forall x y, f x y = g x y) -> @fold_left A B f v xs = fold_left g v xs.
Proof. intros; apply fold_left_ext_in; eauto. Qed.
Lemma fold_left_id_ext A B f v xs : (forall x y, f x y = x) -> @fold_left A B f xs v = v.
Proof. induction xs; cbn; intro H; rewrite ?H; auto. Qed.
Lemma nth_error_repeat_alt {A} (v : A) n i
: nth_error (repeat v n) i = if dec (i < n)%nat then Some v else None.
Proof.
revert i; induction n as [|n IHn], i; cbn; try reflexivity.
cbn [nth_error]; rewrite IHn; do 2 edestruct dec; try reflexivity; lia.
Qed.
Lemma nth_default_repeat A (v:A) n (d:A) i : nth_default d (repeat v n) i = if dec (i < n)%nat then v else d.
Proof.
cbv [nth_default]; rewrite nth_error_repeat_alt; now break_innermost_match.
Qed.
#[global]
Hint Rewrite nth_default_repeat : push_nth_default simpl_nth_default.
Lemma fold_right_if_dec_eq_seq A start len i f (x v : A)
: ((start <= i < start + len)%nat -> f i v = x)
-> (forall j v, (i <> j)%nat -> f j v = v)
-> fold_right f v (seq start len) = if dec (start <= i < start + len)%nat then x else v.
Proof.
revert start v; induction len as [|len IHlen]; intros start v H H'; [ | rewrite seq_snoc, fold_right_app; cbn [fold_right] ].
{ edestruct dec; try reflexivity; lia. }
{ destruct (dec (i = (start + len)%nat)); subst; [ | rewrite H' by lia ];
rewrite IHlen; eauto; intros; clear IHlen;
repeat match goal with
| _ => reflexivity
| _ => lia
| _ => progress subst
| _ => progress specialize_by lia
| [ H : context[dec ?P] |- _ ] => destruct (dec P)
| [ |- context[dec ?P] ] => destruct (dec P)
| [ H : f _ _ = _ |- _ ] => rewrite H
| [ H : forall j, f j ?v = _ |- context[f _ ?v] ] => rewrite H
end. }
Qed.
Lemma fold_left_if_dec_eq_seq A start len i f (x v : A)
: ((start <= i < start + len)%nat -> f v i = x)
-> (forall j v, (i <> j)%nat -> f v j = v)
-> fold_left f (seq start len) v = if dec (start <= i < start + len)%nat then x else v.
Proof.
revert start v; induction len as [|len IHlen]; intros start v H H'; [ | rewrite seq_snoc, fold_left_app; cbn [fold_left] ].
{ edestruct dec; try reflexivity; lia. }
{ destruct (dec (i = (start + len)%nat)); subst; [ | rewrite H' by lia ];
rewrite IHlen; eauto; intros; clear IHlen;
repeat match goal with
| _ => reflexivity
| _ => lia
| _ => progress subst
| _ => progress specialize_by lia
| [ H : context[dec ?P] |- _ ] => destruct (dec P)
| [ |- context[dec ?P] ] => destruct (dec P)
| [ H : f _ _ = _ |- _ ] => rewrite H
| [ H : forall j, f j ?v = _ |- context[f _ ?v] ] => rewrite H
end. }
Qed.
Lemma fold_left_push A (x y : A) (f : A -> A -> A)
(f_assoc : forall x y z, f (f x y) z = f x (f y z))
ls
: f x (fold_left f ls y) = fold_left f ls (f x y).
Proof.
revert x y; induction ls as [|l ls IHls]; cbn; [ reflexivity | ].
intros; rewrite IHls; f_equal; auto.
Qed.
Lemma fold_right_push A (x y : A) (f : A -> A -> A)
(f_assoc : forall x y z, f (f x y) z = f x (f y z))
ls
: f (fold_right f x ls) y = fold_right f (f x y) ls.
Proof.
rewrite <- (rev_involutive ls), !fold_left_rev_right, fold_left_push with (f:=fun x y => f y x); auto.
Qed.
Lemma nth_error_combine {A B} n (ls1 : list A) (ls2 : list B)
: nth_error (combine ls1 ls2) n = match nth_error ls1 n, nth_error ls2 n with
| Some v1, Some v2 => Some (v1, v2)
| _, _ => None
end.
Proof.
revert ls2 n; induction ls1 as [|l1 ls1 IHls1], ls2, n; cbn [combine nth_error]; try reflexivity; auto.
edestruct nth_error; reflexivity.
Qed.
Lemma combine_repeat {A B} (a : A) (b : B) n : combine (repeat a n) (repeat b n) = repeat (a, b) n.
Proof. induction n; cbn; congruence. Qed.
Lemma combine_rev_rev_samelength {A B} ls1 ls2 : length ls1 = length ls2 -> @combine A B (rev ls1) (rev ls2) = rev (combine ls1 ls2).
Proof.
revert ls2; induction ls1 as [|? ? IHls1], ls2; cbn in *; try congruence; intros.
rewrite combine_app_samelength, IHls1 by (rewrite ?rev_length; congruence); cbn [combine].
reflexivity.
Qed.
Lemma map_nth_default_seq {A} (d:A) n ls
: length ls = n -> List.map (List.nth_default d ls) (List.seq 0 n) = ls.
Proof.
intro; subst.
rewrite <- (List.rev_involutive ls); generalize (List.rev ls); clear ls; intro ls.
rewrite List.rev_length.
induction ls; cbn [length List.rev]; [ reflexivity | ].
rewrite seq_snoc, List.map_app.
apply f_equal2; [ | cbn; rewrite nth_default_app, List.rev_length, Nat.sub_diag ];
[ etransitivity; [ | eassumption ]; apply List.map_ext_in; intro; rewrite Lists.List.in_seq;
rewrite nth_default_app, List.rev_length; intros
| ].
all: edestruct lt_dec; try (exfalso; lia).
all: reflexivity.
Qed.
Lemma nth_error_firstn A ls n i
: List.nth_error (@List.firstn A n ls) i = if lt_dec i n then List.nth_error ls i else None.
Proof.
revert ls i; induction n, ls, i; cbn; try reflexivity; destruct lt_dec; try reflexivity; rewrite IHn.
all: destruct lt_dec; try reflexivity; lia.
Qed.
Lemma nth_error_rev A n ls : List.nth_error (@List.rev A ls) n = if lt_dec n (length ls) then List.nth_error ls (length ls - S n) else None.
Proof.
destruct lt_dec; [ | rewrite nth_error_length_error; rewrite ?List.rev_length; try reflexivity; lia ].
revert dependent n; induction ls as [|x xs IHxs]; cbn [length List.rev]; try reflexivity; intros; try lia.
{ rewrite nth_error_app, List.rev_length, Nat.sub_succ.
destruct lt_dec.
{ rewrite IHxs by lia.
rewrite <- (Nat.succ_pred_pos (length xs - n)) by lia.
cbn [List.nth_error].
f_equal; lia. }
{ assert (n = length xs) by lia; subst.
rewrite Nat.sub_diag.
reflexivity. } }
Qed.
Lemma concat_fold_right_app A ls
: @List.concat A ls = List.fold_right (@List.app A) nil ls.
Proof. induction ls; cbn; eauto. Qed.
Lemma map_update_nth_ext {A B n} f1 f2 f3 ls1 ls2
: map f3 ls1 = ls2
-> (forall x, List.In x ls1 -> f3 (f2 x) = f1 (f3 x))
-> map f3 (@update_nth A n f2 ls1) = @update_nth B n f1 ls2.
Proof.
revert ls1 ls2; induction n as [|n IHn], ls1 as [|x1 xs1], ls2 as [|x2 xs2]; cbn; intros H0 H1; try discriminate; try reflexivity.
all: inversion H0; clear H0; subst.
all: f_equal; eauto using or_introl.
Qed.
Lemma push_f_list_rect {P P'} (f : P -> P') {A} Pnil Pcons Pcons' ls
(Hcons : forall x xs rec, f (Pcons x xs rec)
= Pcons' x xs (f rec))
: f (list_rect (fun _ : list A => P) Pnil Pcons ls)
= list_rect
(fun _ => _)
(f Pnil)
Pcons'
ls.
Proof.
induction ls as [|x xs IHxs]; cbn [list_rect]; [ reflexivity | ].
rewrite Hcons, IHxs; reflexivity.
Qed.
Lemma eq_app_list_rect {A} (ls1 ls2 : list A)
: List.app ls1 ls2 = list_rect _ ls2 (fun x _ rec => x :: rec) ls1.
Proof. revert ls2; induction ls1, ls2; cbn; f_equal; eauto. Qed.
Lemma eq_flat_map_list_rect {A B} f (ls : list A)
: @flat_map A B f ls = list_rect _ nil (fun x _ rec => f x ++ rec) ls.
Proof. induction ls; cbn; eauto. Qed.
Lemma eq_partition_list_rect {A} f (ls : list A)
: @partition A f ls = list_rect _ (nil, nil) (fun x _ '(a, b) => bool_rect (fun _ => _) (x :: a, b) (a, x :: b) (f x)) ls.
Proof. induction ls; cbn; eauto. Qed.
Lemma eq_fold_right_list_rect {A B} f v (ls : list _)
: @fold_right A B f v ls = list_rect _ v (fun x _ rec => f x rec) ls.
Proof. induction ls; cbn; eauto. Qed.
Lemma eq_fold_left_list_rect {A B} f v (ls : list _)
: @fold_left A B f ls v = list_rect _ (fun v => v) (fun x _ rec v => rec (f v x)) ls v.
Proof. revert f v; induction ls; cbn; eauto. Qed.
Lemma eq_map_list_rect {A B} f (ls : list _)
: @List.map A B f ls = list_rect _ nil (fun x _ rec => f x :: rec) ls.
Proof. induction ls; cbn; eauto. Qed.
Lemma eq_flat_map_fold_right {A B} f (ls : list A)
: @flat_map A B f ls = fold_right (fun x y => f x ++ y) nil ls.
Proof. induction ls; cbn; eauto. Qed.
Lemma eq_flat_map_fold_left_gen {A B} f (ls : list A) ls'
: fold_left (fun x y => x ++ f y) ls ls' = ls' ++ @flat_map A B f ls.
Proof. revert ls'; induction ls; cbn; intros; rewrite ?app_nil_r, ?IHls, ?app_assoc; eauto. Qed.
Lemma eq_flat_map_fold_left {A B} f (ls : list A)
: @flat_map A B f ls = fold_left (fun x y => x ++ f y) ls nil.
Proof. rewrite eq_flat_map_fold_left_gen; reflexivity. Qed.
Lemma map_repeat {A B} (f : A -> B) v k
: List.map f (List.repeat v k) = List.repeat (f v) k.
Proof. induction k; cbn; f_equal; assumption. Qed.
Lemma map_const {A B} (v : B) (ls : list A)
: List.map (fun _ => v) ls = List.repeat v (List.length ls).
Proof. induction ls; cbn; f_equal; assumption. Qed.
Lemma Forall2_rev {A B R ls1 ls2}
: @List.Forall2 A B R ls1 ls2
-> List.Forall2 R (rev ls1) (rev ls2).
Proof using Type.
induction 1; cbn [rev]; [ constructor | ].
apply Forall2_app; auto.
Qed.
Lemma Forall2_update_nth {A B f g n R ls1 ls2}
: @List.Forall2 A B R ls1 ls2
-> (forall v1, nth_error ls1 n = Some v1 -> forall v2, nth_error ls2 n = Some v2 -> R v1 v2 -> R (f v1) (g v2))
-> @List.Forall2 A B R (update_nth n f ls1) (update_nth n g ls2).
Proof using Type.
intro H; revert n; induction H, n; cbn [nth_error update_nth].
all: repeat first [ progress intros
| progress specialize_by_assumption
| assumption
| match goal with
| [ |- List.Forall2 _ _ _ ] => constructor
| [ H : forall x, Some _ = Some x -> _ |- _ ] => specialize (H _ eq_refl)
| [ IH : forall n : nat, _, H : forall v1, nth_error ?l ?n = Some v1 -> _ |- _ ] => specialize (IH n H)
end ].
Qed.
Fixpoint remove_duplicates' {A} (beq : A -> A -> bool) (ls : list A) : list A
:= match ls with
| nil => nil
| cons x xs => if existsb (beq x) xs
then @remove_duplicates' A beq xs
else x :: @remove_duplicates' A beq xs
end.
Definition remove_duplicates {A} (beq : A -> A -> bool) (ls : list A) : list A
:= List.rev (remove_duplicates' beq (List.rev ls)).
Fixpoint find_duplicates' {A} (beq : A -> A -> bool) (ls : list A) : list A
:= match ls with
| nil => nil
| cons x xs => if existsb (beq x) xs
then x :: @find_duplicates' A beq xs
else @find_duplicates' A beq xs
end.
Definition find_duplicates {A} (beq : A -> A -> bool) (ls : list A) : list A
:= remove_duplicates beq (find_duplicates' beq ls).
Lemma InA_remove_duplicates'
{A} (A_beq : A -> A -> bool)
(R : A -> A -> Prop)
{R_Transitive : Transitive R}
(A_bl : forall x y, A_beq x y = true -> R x y)
(ls : list A)
: forall x, InA R x (remove_duplicates' A_beq ls) <-> InA R x ls.
Proof using Type.
induction ls as [|x xs IHxs]; intro y; [ reflexivity | ].
cbn [remove_duplicates']; break_innermost_match;
rewrite ?InA_cons, IHxs; [ | reflexivity ].
split; [ now auto | ].
intros [?|?]; subst; auto; [].
rewrite existsb_exists in *.
destruct_head'_ex; destruct_head'_and.
match goal with H : _ |- _ => apply A_bl in H end.
rewrite InA_alt.
eexists; split; [ | eassumption ].
etransitivity; eassumption.
Qed.
Lemma InA_remove_duplicates
{A} (A_beq : A -> A -> bool)
(R : A -> A -> Prop)
{R_Transitive : Transitive R}
(A_bl : forall x y, A_beq x y = true -> R x y)
(ls : list A)
: forall x, InA R x (remove_duplicates A_beq ls) <-> InA R x ls.
Proof using Type.
cbv [remove_duplicates]; intro.
rewrite InA_rev, InA_remove_duplicates', InA_rev; auto; reflexivity.
Qed.
Lemma InA_eq_In_iff {A} x ls
: InA eq x ls <-> @List.In A x ls.
Proof using Type.
rewrite InA_alt.
repeat first [ progress destruct_head'_and
| progress destruct_head'_ex
| progress subst
| solve [ eauto ]
| apply conj
| progress intros ].
Qed.
Lemma NoDupA_eq_NoDup {A} ls
: @NoDupA A eq ls <-> NoDup ls.
Proof using Type.
split; intro H; induction H; constructor; eauto;
(idtac + rewrite <- InA_eq_In_iff + rewrite InA_eq_In_iff); assumption.
Qed.
Lemma in_remove_duplicates'
{A} (A_beq : A -> A -> bool) (A_bl : forall x y, A_beq x y = true -> x = y)
(ls : list A)
: forall x, List.In x (remove_duplicates' A_beq ls) <-> List.In x ls.
Proof using Type.
intro x; rewrite <- !InA_eq_In_iff; apply InA_remove_duplicates'; eauto; exact _.
Qed.
Lemma in_remove_duplicates
{A} (A_beq : A -> A -> bool) (A_bl : forall x y, A_beq x y = true -> x = y)
(ls : list A)
: forall x, List.In x (remove_duplicates A_beq ls) <-> List.In x ls.
Proof using Type.
intro x; rewrite <- !InA_eq_In_iff; apply InA_remove_duplicates; eauto; exact _.
Qed.
Lemma NoDupA_remove_duplicates' {A} (A_beq : A -> A -> bool)
(R : A -> A -> Prop)
{R_Transitive : Transitive R}
(A_lb : forall x y, A_beq x y = true -> R x y)
(A_bl : forall x y, R x y -> A_beq x y = true)
(ls : list A)
: NoDupA R (remove_duplicates' A_beq ls).
Proof using Type.
induction ls as [|x xs IHxs]; [ now constructor | ].
cbn [remove_duplicates']; break_innermost_match; [ assumption | constructor; auto ]; [].
intro H'.
cut (false = true); [ discriminate | ].
match goal with H : _ = false |- _ => rewrite <- H end.
rewrite existsb_exists in *.
rewrite InA_remove_duplicates' in H' by eauto.
rewrite InA_alt in H'.
destruct_head'_ex; destruct_head'_and.
eauto.
Qed.
Lemma NoDupA_remove_duplicates {A} (A_beq : A -> A -> bool)
(R : A -> A -> Prop)
{R_Equivalence : Equivalence R}
(A_lb : forall x y, A_beq x y = true -> R x y)
(A_bl : forall x y, R x y -> A_beq x y = true)
(ls : list A)
: NoDupA R (remove_duplicates A_beq ls).
Proof using Type.
cbv [remove_duplicates].
apply NoDupA_rev; [ assumption | ].
apply NoDupA_remove_duplicates'; auto; exact _.
Qed.
Lemma NoDup_remove_duplicates' {A} (A_beq : A -> A -> bool)
(R : A -> A -> Prop)
(A_lb : forall x y, A_beq x y = true -> x = y)
(A_bl : forall x y, x = y -> A_beq x y = true)
(ls : list A)
: NoDup (remove_duplicates' A_beq ls).
Proof using Type.
apply NoDupA_eq_NoDup, NoDupA_remove_duplicates'; auto; exact _.
Qed.
Lemma NoDup_remove_duplicates {A} (A_beq : A -> A -> bool)
(A_lb : forall x y, A_beq x y = true -> x = y)
(A_bl : forall x y, x = y -> A_beq x y = true)
(ls : list A)
: NoDup (remove_duplicates A_beq ls).
Proof using Type.
apply NoDupA_eq_NoDup, NoDupA_remove_duplicates; auto; exact _.
Qed.
Lemma remove_duplicates'_eq_NoDupA {A} (A_beq : A -> A -> bool)
(R : A -> A -> Prop)
(A_lb : forall x y, A_beq x y = true -> R x y)
(ls : list A)
: NoDupA R ls -> remove_duplicates' A_beq ls = ls.
Proof using Type.
intro H; induction H as [|x xs H0 H1 IHxs]; [ reflexivity | ].
cbn [remove_duplicates'].
rewrite IHxs.
repeat first [ break_innermost_match_step
| reflexivity
| progress destruct_head'_ex
| progress destruct_head'_and
| progress rewrite existsb_exists in *
| progress rewrite InA_alt in *
| match goal with
| [ H : ~(exists x, and _ _) |- _ ]
=> specialize (fun x H0 H1 => H (ex_intro _ x (conj H0 H1)))
end
| solve [ exfalso; eauto ] ].
Qed.
Lemma remove_duplicates_eq_NoDupA {A} (A_beq : A -> A -> bool)
(R : A -> A -> Prop)
{R_equiv : Equivalence R}
(A_lb : forall x y, A_beq x y = true -> R x y)
(ls : list A)
: NoDupA R ls -> remove_duplicates A_beq ls = ls.
Proof using Type.
cbv [remove_duplicates]; intro.
erewrite remove_duplicates'_eq_NoDupA by (eauto + apply NoDupA_rev; eauto).
rewrite rev_involutive; reflexivity.
Qed.
Lemma remove_duplicates'_eq_NoDup {A} (A_beq : A -> A -> bool)
(A_lb : forall x y, A_beq x y = true -> x = y)
(ls : list A)
: NoDup ls -> remove_duplicates' A_beq ls = ls.
Proof using Type.
intro H; apply remove_duplicates'_eq_NoDupA with (R:=eq); eauto.
now apply NoDupA_eq_NoDup.
Qed.
Lemma remove_duplicates_eq_NoDup {A} (A_beq : A -> A -> bool)
(A_lb : forall x y, A_beq x y = true -> x = y)
(ls : list A)
: NoDup ls -> remove_duplicates A_beq ls = ls.
Proof using Type.
intro H; apply remove_duplicates_eq_NoDupA with (R:=eq); eauto; try exact _.
now apply NoDupA_eq_NoDup.
Qed.
Lemma eq_repeat_nat_rect {A} x n
: @List.repeat A x n
= nat_rect _ nil (fun k repeat_k => x :: repeat_k) n.
Proof using Type. induction n; cbn; f_equal; assumption. Qed.
Lemma eq_firstn_nat_rect {A} n ls
: @List.firstn A n ls
= nat_rect
_
(fun _ => nil)
(fun n' firstn_n' ls
=> match ls with
| nil => nil
| cons x xs => x :: firstn_n' xs
end)
n ls.
Proof using Type. revert ls; induction n, ls; cbn; f_equal; auto. Qed.
Lemma eq_skipn_nat_rect {A} n ls
: @List.skipn A n ls
= nat_rect
_
(fun ls => ls)
(fun n' skipn_n' ls
=> match ls with
| nil => nil
| cons x xs => skipn_n' xs
end)
n ls.
Proof using Type. revert ls; induction n, ls; cbn; f_equal; auto. Qed.
Lemma eq_combine_list_rect {A B} xs ys
: @List.combine A B xs ys
= list_rect
_
(fun _ => nil)
(fun x xs combine_xs ys
=> match ys with
| nil => nil
| y :: ys => (x, y) :: combine_xs ys
end)
xs ys.
Proof using Type. revert ys; induction xs, ys; cbn; f_equal; auto. Qed.
Lemma eq_length_list_rect {A} xs
: @List.length A xs
= (list_rect _)
0%nat
(fun _ xs length_xs => S length_xs)
xs.
Proof using Type. induction xs; cbn; f_equal; auto. Qed.
Lemma eq_rev_list_rect {A} xs
: @List.rev A xs
= (list_rect _)
nil
(fun x xs rev_xs => rev_xs ++ [x])
xs.
Proof using Type. induction xs; cbn; f_equal; auto. Qed.
Lemma eq_update_nth_nat_rect {A} n f xs
: @update_nth A n f xs
= (nat_rect _)
(fun xs => match xs with
| nil => nil
| x' :: xs' => f x' :: xs'
end)
(fun n' update_nth_n' xs
=> match xs with
| nil => nil
| x' :: xs' => x' :: update_nth_n' xs'
end)
n
xs.
Proof using Type. revert xs; induction n, xs; cbn; f_equal; auto. Qed.
Lemma flat_map_const_nil {A B} ls : @flat_map A B (fun _ => nil) ls = nil.
Proof using Type. induction ls; cbn; auto. Qed.
Lemma Forall_map_iff {A B} (f : A -> B) ls P
: Forall P (List.map f ls) <-> Forall (fun x => P (f x)) ls.
Proof.
induction ls as [|?? IH]; cbn [List.map]; split; intro H; inversion_clear H; constructor; split_iff; auto.
Qed.
Lemma ForallOrdPairs_map_iff {A B} (f : A -> B) ls P
: ForallOrdPairs P (List.map f ls) <-> ForallOrdPairs (fun x y => P (f x) (f y)) ls.
Proof.
pose proof (@Forall_map_iff A B f) as HF.
induction ls as [|?? IH]; cbn [List.map]; split; intro H; inversion_clear H; constructor; split_iff; auto.
Qed.
Lemma HdRel_map_iff {A B} (f : A -> B) R x xs
: HdRel R (f x) (List.map f xs) <-> HdRel (fun x y => R (f x) (f y)) x xs.
Proof.
destruct xs; split; intro H; inversion_clear H; constructor; auto.
Qed.
Lemma Sorted_map_iff {A B} (f : A -> B) R ls
: Sorted R (List.map f ls) <-> Sorted (fun x y => R (f x) (f y)) ls.
Proof.
induction ls as [|?? IH]; cbn [List.map]; split; intro H; inversion_clear H;
constructor; split_iff; auto; now apply HdRel_map_iff.
Qed.
Lemma In_nth_error_iff {A l x}
: In x l <-> exists n : nat, @nth_error A l n = Some x.
Proof.
split; [ now apply In_nth_error | intros [? ?]; eapply nth_error_In; eassumption ].
Qed.
Lemma fold_right_fun_apply {A B C} (ls : list B) (f : B -> C -> (A -> C)) init x
: fold_right (fun b F a => f b (F a) a) init ls x = fold_right (fun b c => f b c x) (init x) ls.
Proof. induction ls as [|?? IH]; cbn; now f_equal. Qed.
Ltac make_fold_right_fun_apply ty :=
multimatch ty with
| context[@fold_right ?AC ?B ?f ?init ?ls ?x]
=> let fv := fresh in
let b := fresh "b" in
let F := fresh "F" in
let a := fresh "a" in
let f := lazymatch
constr:(
fun b F a
=> match f b F a return _ with
| fv
=> ltac:(let fv := (eval cbv [fv] in fv) in
lazymatch (eval pattern a, (F a), b in fv) with
| ?f _ _ _ => refine (fun x y z => f z y x)
end)
end) with
| fun _ _ _ => ?f => (eval cbv beta in f)
| ?f => idtac "failed to eliminate the functional dependencies of" f;
fail 0 "failed to eliminate the functional dependencies of" f
end in
constr:(@fold_right_fun_apply _ _ _ ls f init x)
end.
Ltac rewrite_fold_right_fun_apply :=
match goal with
| [ H : ?T |- _ ] => let pf := make_fold_right_fun_apply T in
rewrite pf in H
| [ |- ?T ] => let pf := make_fold_right_fun_apply T in
rewrite pf
end.
Lemma fold_left_fun_apply {A B C} (ls : list B) (f : C -> B -> (A -> C)) init x
: fold_left (fun F b a => f (F a) b a) ls init x = fold_left (fun b c => f b c x) ls (init x).
Proof. rewrite <- !fold_left_rev_right; now rewrite_fold_right_fun_apply. Qed.
Ltac make_fold_left_fun_apply ty :=
multimatch ty with
| context[@fold_left ?AC ?B ?f ?ls ?init ?x]
=> let fv := fresh in
let b := fresh "b" in
let F := fresh "F" in
let a := fresh "a" in
let f := lazymatch
constr:(
fun F b a
=> match f F b a return _ with
| fv
=> ltac:(let fv := (eval cbv [fv] in fv) in
lazymatch (eval pattern a, b, (F a) in fv) with
| ?f _ _ _ => refine (fun x y z => f z y x)
end)
end) with
| fun _ _ _ => ?f => (eval cbv beta in f)
| ?f => idtac "failed to eliminate the functional dependencies of" f;
fail 0 "failed to eliminate the functional dependencies of" f
end in
constr:(@fold_left_fun_apply _ _ _ ls f init x)
end.
Ltac rewrite_fold_left_fun_apply :=
match goal with
| [ H : ?T |- _ ] => let pf := make_fold_left_fun_apply T in
rewrite pf in H
| [ |- ?T ] => let pf := make_fold_left_fun_apply T in
rewrite pf
end.
Definition span_cps' {A} (f : A -> bool) {T} (k : list A * list A -> T)
:= fix span_cps' (ls : list A) (prefix : list A) : T
:= match ls with
| nil => k (List.rev prefix, ls)
| x :: xs => if f x then span_cps' xs (x :: prefix) else k (List.rev prefix, ls)
end.
Definition span_cps {A} (f : A -> bool) (ls : list A) {T} (k : list A * list A -> T) : T
:= span_cps' f k ls [].
Definition span {A} (f : A -> bool) (ls : list A) : list A * list A
:= span_cps f ls id.
Definition takeWhile {A} (f : A -> bool) (ls : list A) : list A := fst (span f ls).
Definition dropWhile {A} (f : A -> bool) (ls : list A) : list A := snd (span f ls).
Lemma span_cps'_id A f xs T k prefix
: @span_cps' A f T k xs prefix = k (List.rev prefix ++ fst (span f xs), snd (span f xs)).
Proof.
revert T k prefix; induction xs as [|?? IH]; intros; cbn; try (rewrite !IH; clear IH); cbv [id]; break_innermost_match; cbn [List.rev fst snd List.app]; rewrite ?List.app_nil_l, ?List.app_nil_r, <- ?List.app_assoc; try reflexivity.
Qed.
Lemma span_cps_id A f xs T k
: @span_cps A f xs T k = k (span f xs).
Proof. cbv [span_cps]; rewrite span_cps'_id; destruct span; reflexivity. Qed.
Lemma span_nil A f : @span A f nil = (nil, nil).
Proof. reflexivity. Qed.
Lemma span_cons A f x xs : @span A f (x :: xs) = if f x then let '(xs, ys) := span f xs in (x :: xs, ys) else (nil, x :: xs).
Proof. cbv [span span_cps]; cbn; rewrite !span_cps'_id; cbv [id]; reflexivity. Qed.
Lemma span_app {A} f xs
: fst (@span A f xs) ++ snd (@span A f xs) = xs.
Proof. induction xs; rewrite ?span_nil, ?span_cons; break_innermost_match; boring. Qed.
Lemma takeWhile_app_dropWhile {A} f xs
: @takeWhile A f xs ++ @dropWhile A f xs = xs.
Proof. apply span_app. Qed.
Lemma filter_fst_span {A} f xs
: filter f (fst (@span A f xs)) = fst (@span A f xs).
Proof. induction xs; rewrite ?span_nil, ?span_cons; break_innermost_match; boring. Qed.
Lemma filter_takeWhile {A} f xs
: filter f (@takeWhile A f xs) = @takeWhile A f xs.
Proof. apply filter_fst_span. Qed.
Lemma hd_not_snd_span {A} f xs x
(H : nth_error (snd (@span A f xs)) 0 = Some x)
: f x = false.
Proof.
induction xs.
all: repeat first [ rewrite !span_nil in *
| rewrite !span_cons in *
| progress cbn in *
| progress cbv [fst snd] in *
| congruence
| solve [ auto ]
| break_innermost_match_hyps_step ].
Qed.
Definition groupBy' {A} (f : A -> A -> bool)
:= fix groupBy' (ls : list A) (prefix : list A) : list (list A)
:= match ls with
| [] => []
| x :: xs => span_cps'
(f x) (fun '(xs, ys)
=> (x :: xs) :: match ys with
| [] => []
| _ => groupBy' ys []
end)
xs prefix
end.
Definition groupBy {A} (f : A -> A -> bool) (ls : list A) : list (list A)
:= groupBy' f ls [].
Definition span_cps'_rect A (f : A -> bool) T (k : list A * list A -> T)
(P : list A -> list A -> T -> Type)
(Pnil : forall prefix, P nil prefix (k (List.rev prefix, nil)))
(Pcons_true : forall x xs prefix rv, f x = true -> P xs (x :: prefix) rv -> P (x :: xs) prefix rv)
(Pcons_false : forall x ls prefix xs, f x = false -> ls = x :: xs -> P ls prefix (k (List.rev prefix, ls)))
: forall (ls : list A) (prefix : list A), P ls prefix (@span_cps' A f T k ls prefix).
Proof.
fix span_cps'_rect 1.
intro ls.
case_eq ls; [ | intros x xs ]; intros H prefix; cbn [span_cps'].
{ apply Pnil. }
{ destruct (f x) eqn:H'.
{ apply Pcons_true; [ apply H' | apply span_cps'_rect ]. }
{ generalize (Pcons_false x ls prefix xs H' H).
clear -H; subst ls; exact id. } }
Defined.
Fixpoint concat_groupBy' {A f} ls prefix {struct ls}
: match ls with
| nil => List.concat (@groupBy' A f ls prefix) = nil
| x :: xs
=> List.concat (@groupBy' A f ls prefix) = x :: List.rev prefix ++ xs
end.
Proof.
specialize (concat_groupBy' A f).
destruct ls as [|x xs].
{ reflexivity. }
{ cbn [groupBy'].
apply span_cps'_rect; cbn [concat List.rev List.app]; clear xs prefix.
{ intros; rewrite ?List.app_nil_l, ?List.app_nil_r; split; reflexivity. }
{ intros *; rewrite ?app_comm_cons, <- ?List.app_assoc; cbn [List.app]; trivial. }
{ intros x' ls xs' prefix' H H'.
specialize (concat_groupBy' ls); cbv beta iota in *.
subst ls.
rewrite concat_groupBy'; cbn.
reflexivity. } }
Qed.
Lemma concat_groupBy A f ls
: List.concat (@groupBy A f ls) = ls.
Proof.
cbv [groupBy]; destruct ls as [|x xs]; [ reflexivity | apply (concat_groupBy' (x :: xs)) ].
Qed.
Lemma eq_filter_nil_Forall_iff {A} f (xs : list A)
: filter f xs = nil <-> Forall (fun x => f x = false) xs.
Proof. induction xs; cbn; break_innermost_match; boring; inversion_list; inversion_one_head Forall; congruence. Qed.
Definition is_nil {A} (x : list A) : bool
:= match x with
| nil => true
| _ => false
end.
Lemma is_nil_eq_nil_iff {A x} : @is_nil A x = true <-> x = nil.
Proof. destruct x; cbv; split; congruence. Qed.
Lemma find_none_iff {A} (f : A -> bool) (xs : list A) : find f xs = None <-> forall x, In x xs -> f x = false.
Proof.
split; try apply find_none.
pose proof (find_some f xs) as H.
edestruct find; [ specialize (H _ eq_refl) | reflexivity ].
destruct H as [H1 H2].
intro H'; specialize (H' _ H1); congruence.
Qed.
Lemma find_none_iff_nth_error {A} (f : A -> bool) (xs : list A) : find f xs = None <-> forall n a, nth_error xs n = Some a -> f a = false.
Proof.
rewrite find_none_iff.
setoid_rewrite In_nth_error_iff.
intuition (destruct_head'_ex; eauto).
Qed.
Lemma find_some_iff {A} (f : A -> bool) (xs : list A) x
: find f xs = Some x
<-> exists n, nth_error xs n = Some x /\ f x = true /\ forall n', n' < n -> forall a, nth_error xs n' = Some a -> f a = false.
Proof.
induction xs as [|y xs IHxs]; cbn [find].
all: repeat first [ apply conj
| progress intros
| progress destruct_head'_ex
| progress destruct_head'_and
| progress Option.inversion_option
| progress break_innermost_match_hyps
| progress subst
| progress cbn in *
| assumption
| exists 0; cbn; repeat split; try assumption; (idtac + (intros; exfalso)); lia
| progress break_innermost_match
| reflexivity
| congruence
| match goal with
| [ H : nth_error nil ?i = _ |- _ ] => is_var i; destruct i
| [ H : nth_error (cons _ _) ?i = _ |- _ ] => is_var i; destruct i
| [ H : ?T <-> _, H' : ?T |- _ ] => destruct H as [H _]; specialize (H H')
| [ H : S ?x < S ?y |- _ ] => assert (x < y) by lia; clear H
| [ H : forall a, Some _ = Some a -> _ |- _ ] => specialize (H _ eq_refl)
| [ H : forall a, Some a = Some _ -> _ |- _ ] => specialize (H _ eq_refl)
| [ H : forall n, n < S ?v -> @?P n |- _ ]
=> assert (forall n, n < v -> P (S n)) by (intros ? ?; apply H; lia);
specialize (H 0 ltac:(lia))
end
| eexists (S _); cbn; repeat apply conj; [ eassumption | .. ]; try assumption; intros [|?]
| progress split_iff
| solve [ eauto with nocore ]
| progress specialize_by eauto ].
Qed.
Section find_index.
Context {A} (f : A -> bool).
Definition find_index (xs : list A) : option nat
:= option_map (@fst _ _) (find (fun v => f (snd v)) (enumerate xs)).
Lemma find_index_none_iff xs
: find_index xs = None <-> forall i a, nth_error xs i = Some a -> f a = false.
Proof using Type.
cbv [find_index enumerate].
edestruct find eqn:H; cbn; [ split; [ congruence | ] | split; [ intros _ | reflexivity ] ].
{ rewrite find_some_iff in H.
destruct H as [n H]; intro H'; specialize (H' n).
rewrite nth_error_combine, nth_error_seq in H.
break_innermost_match_hyps; destruct_head'_and; Option.inversion_option; subst; cbn in *.
specialize (H' _ eq_refl); congruence. }
{ rewrite find_none_iff_nth_error in H.
intros n a; specialize (H n (n, a)).
rewrite nth_error_combine, nth_error_seq in H.
edestruct lt_dec; [ | rewrite nth_error_length_error by lia; congruence ].
edestruct nth_error eqn:?; intros; Option.inversion_option; subst; specialize (H eq_refl); assumption. }
Qed.
Lemma find_index_some_iff xs n
: find_index xs = Some n
<-> ((exists x, nth_error xs n = Some x /\ f x = true) /\ forall n', n' < n -> forall a, nth_error xs n' = Some a -> f a = false).
Proof using Type.
cbv [find_index enumerate].
edestruct find eqn:H; cbn; [ | split; [ congruence | ] ].
{ rewrite find_some_iff in H.
destruct H as [n' H].
rewrite nth_error_combine, nth_error_seq in H.
setoid_rewrite nth_error_combine in H.
setoid_rewrite nth_error_seq in H.
break_innermost_match_hyps; split; intro H'; destruct_head'_and; Option.inversion_option; subst; cbn in *.
all: repeat apply conj; eauto.
{ let H := match goal with H : forall n, n < _ -> _ |- _ => H end in
intros i H' a' H''; specialize (H i H' (i, a'));
rewrite H'' in H;
break_innermost_match_hyps; [ specialize (H eq_refl); assumption | ].
rewrite nth_error_length_error in H'' by lia; congruence. }
{ match goal with |- Some ?n = Some ?m => destruct (lt_eq_lt_dec n m) end; destruct_head' sumbool; subst; try reflexivity.
all: match goal with H : forall n', n' < _ -> _ |- _ => specialize (H _ ltac:(eassumption)) end.
{ match goal with H : forall a, nth_error _ _ = Some _ -> _ |- _ => specialize (H _ ltac:(eassumption)); congruence end. }
{ destruct_head'_ex; destruct_head'_and.
break_innermost_match_hyps; try congruence; try lia.
Option.inversion_option; subst.
match goal with H : forall x, Some _ = Some x -> _ |- _ => specialize (H _ eq_refl) end.
cbn in *.
congruence. } } }
{ rewrite find_none_iff_nth_error in H.
intros [ [a [H0 H1]] ?]; specialize (H n (n, a)).
rewrite nth_error_combine, nth_error_seq, H0 in H.
break_innermost_match_hyps; [ | rewrite nth_error_length_error in H0 by lia; congruence ].
specialize (H eq_refl); cbn in *.
congruence. }
Qed.
End find_index.
Lemma fold_left_id {A B} init ls
: @fold_left A B (fun x _ => x) ls init = init.
Proof.
revert init; induction ls as [|x xs IHxs]; cbn [fold_left]; eauto.
Qed.
Lemma fold_left_cons {B} init ls
: @fold_left _ B (fun xs x => cons x xs) ls init = List.rev ls ++ init.
Proof.
revert init; induction ls as [|x xs IHxs]; cbn [fold_left List.rev];
intros; rewrite ?IHxs, ?List.app_nil_l, ?List.app_nil_r, <- ?List.app_assoc;
cbn [List.app]; reflexivity.
Qed.
Lemma map_swap_combine {A B} ls1 ls2
: List.map (fun xy => (snd xy, fst xy)) (List.combine ls2 ls1)
= @List.combine A B ls1 ls2.
Proof.
revert ls2; induction ls1 as [|x xs IHxs], ls2 as [|y ys]; cbn [List.combine List.map fst snd]; congruence.
Qed.
Lemma fold_right_higher_order A B C f a ls (F : _ -> C)
: fold_right (fun x acc a => acc (f x a)) F ls a
= F (@fold_right A B f a (List.rev ls)).
Proof.
revert F a; induction ls; cbn; try reflexivity; intros.
rewrite IHls, fold_right_app; cbn.
reflexivity.
Qed.
Lemma fold_right_rev_higher_order A B f a ls
: @fold_right A B f a (List.rev ls)
= fold_right (fun x acc a => acc (f x a)) id ls a.
Proof. symmetry; apply fold_right_higher_order. Qed.
Lemma fold_left_higher_order A B C f a ls (F : _ -> C)
: fold_left (fun acc x a => acc (f a x)) ls F a
= F (@fold_left A B f (List.rev ls) a).
Proof.
revert F a; induction ls; cbn; try reflexivity; intros.
rewrite IHls, fold_left_app; cbn.
reflexivity.
Qed.
Lemma fold_left_rev_higher_order A B f a ls
: @fold_left A B f (List.rev ls) a
= fold_left (fun acc x a => acc (f a x)) ls id a.
Proof. symmetry; apply fold_left_higher_order. Qed.
(* This module is here because the equivalent standard library functions fail to be "reified by unfolding". *)
Module Reifiable.
Section __.
Context {X : Type}
(eqb : X -> X -> bool)
(eqb_eq : forall x1 x2, eqb x1 x2 = true <-> x1 = x2).
Definition existsb (f : X -> bool) (l : list X) : bool :=
fold_right (fun x found => orb (f x) found) false l.
Lemma reifiable_existsb_is_existsb : forall (f : X -> bool) (l : list X),
existsb f l = List.existsb f l.
Proof. reflexivity. Qed.
Lemma existsb_eqb_true_iff : forall x l, existsb (eqb x) l = true <-> In x l.
Proof.
intros x l. rewrite reifiable_existsb_is_existsb. rewrite existsb_exists. split.
- intros [x0 [H1 H2]]. rewrite eqb_eq in H2. subst. assumption.
- intros H. exists x. split.
+ assumption.
+ apply eqb_eq. reflexivity.
Qed.
Lemma existsb_eqb_false_iff : forall x l, existsb (eqb x) l = false <-> ~In x l.
Proof.
intros. rewrite <- existsb_eqb_true_iff. split.
- intros H. rewrite H. auto.
- intros H. destruct (existsb (eqb x) l).
+ exfalso. apply H. reflexivity.
+ reflexivity.
Qed.
Definition nodupb (l : list X) :=
fold_right (fun x l' => if (existsb (eqb x) l') then l' else (x :: l')) [] l.
Lemma nodupb_in_iff (x : X) (l : list X) : In x l <-> In x (nodupb l).
Proof.
induction l as [|x' l' IHl'].
- reflexivity.
- simpl. destruct (existsb (eqb x') (nodupb l')) eqn:E.
+ rewrite existsb_eqb_true_iff in E. split.
-- intros [H|H].
++ rewrite <- H. apply E.
++ rewrite <- IHl'. apply H.
-- intros H. right. rewrite IHl'. apply H.
+ rewrite existsb_eqb_false_iff in E. split.
-- intros [H|H].
++ rewrite H. simpl. left. reflexivity.
++ simpl. right. rewrite <- IHl'. apply H.
-- simpl. intros [H|H].
++ left. apply H.
++ right. rewrite IHl'. apply H.
Qed.
Lemma nodupb_split (x : X) (l : list X) : In x l ->
exists l1 l2, nodupb l = l1 ++ [x] ++ l2 /\ ~ In x l1 /\ ~ In x l2.
Proof.
intros H. induction l as [| x' l'].
- simpl in H. destruct H.
- simpl in H. destruct H as [H|H].
+ rewrite H. clear H. simpl. destruct (existsb (eqb x) (nodupb l')) eqn:E.
-- rewrite existsb_eqb_true_iff in E. rewrite <- nodupb_in_iff in E.
apply IHl' in E. apply E.
-- exists []. exists (nodupb l'). split.
++ rewrite app_nil_l. reflexivity.
++ split.
--- auto.
--- rewrite <- existsb_eqb_false_iff. apply E.
+ apply IHl' in H. clear IHl'. simpl. destruct (existsb (eqb x') (nodupb l')) eqn:E.
-- apply H.
-- destruct H as [l1 [l2 [H1 [H2 H3] ] ] ]. exists (x' :: l1). exists l2. split.
++ rewrite H1. reflexivity.
++ split.
--- simpl. intros [H|H].
+++ rewrite H in *. rewrite H1 in E. apply existsb_eqb_false_iff in E. apply E.
repeat rewrite in_app_iff. right. left. simpl. left. reflexivity.
+++ apply H2. apply H.
--- apply H3.
Qed.
End __.
End Reifiable.
|
import Base.REPL: REPLDisplay
export Query, ask, form, answers, make_widget, on_done
immutable Query{T}
w::Widget
end
function (::Type{Query{Int}})()
t = TextInput(IOBuffer(copy(b"1234"),true,true))
t.optheight = 1
Query{Int}(t)
end
function on_done(f::Function,i::Query{Int})
i.w.on_done = str->f(parse(Int,str))
end
function (::Type{Query{AbstractString}})()
t = TextInput()
t.optheight = 1
Query{AbstractString}(t)
end
on_done(f::Function,i::Query{AbstractString}) = i.w.on_done = f
function display(d::REPLDisplay, w::Widget)
wait(InlineDialog(w,d.repl.t))
end
immutable Question
text::AbstractString
input::Query
end
function ask(question, answerT)
Question(question,Query{answerT}())
end
make_widget(i::Query) = i.w
function make_widget(q::Question)
cd = TerminalUI.CellDisplay(
Vector{VT100.Cell}[[
VT100.Cell(TerminalUI.dummycell(:default,:default,0),content = '['),
VT100.Cell(TerminalUI.dummycell(:green,:default,0),content = '?'),
VT100.Cell(TerminalUI.dummycell(:default,:default,0),content = ']')]])
cd2 = TerminalUI.CellDisplay(
Vector{VT100.Cell}[[
VT100.Cell(TerminalUI.dummycell(:default,:default,0),content = c)
for c in q.text]])
RowLayout([cd,cd2,q.input.w],[1,1,1],[4,strwidth(q.text)+1,0],3)
end
display(d::REPLDisplay, q::Question) = display(d,make_widget(q))
immutable Form
questions
chain::ScrollableChain
keyidxs
answers
end
function form(questions; style = :incremental)
widgets = map(x->make_widget(x[2]),questions)
if style == :incremental
for i = 2:length(widgets)
hide(widgets[i])
end
end
f = Form(questions,ScrollableChain(widgets),
Dict(k => i for (i,(k,_)) in enumerate(questions)),
Dict{Symbol,Any}())
for (k,q) in questions
on_done(q.input) do v
answer(f, k, v)
focus_next(f.chain, show_invisible = true) || (invalidate(f.chain); return :done)
end
end
f
end
display(d::REPLDisplay,f::Form) = display(d,f.chain)
FullScreenDialog(f::Form,tty) = FullScreenDialog(f.chain, tty)
function answer(form::Form, key, value)
# First record the answer
form.answers[key] = value
# Create a widget to permanently display the answer
str = sprint(print,value)
cd = TerminalUI.CellDisplay(
Vector{VT100.Cell}[[
VT100.Cell(TerminalUI.dummycell(:cyan,:default,Bright),content = c)
for c in str]])
# Replace the question widget with an answer widget
form.chain.children[form.keyidxs[key]].cols[3] = cd
end
answers(f::Form) = f.answers
make_widget(w::Widget) = w
make_widget(s::AbstractString) = Label(s)
function make_widget(a::Array)
if ndims(a) == 1
ScrollableChain(map(make_widget,a))
elseif ndims(a) == 2
if size(a)[1] > 1
widgets = [make_widget(a[:,i]) for i = 1:size(a)[2]]
else
widgets = map(make_widget,vec(a))
end
RowLayout(widgets,[1 for _ in widgets],[0 for _ in widgets],length(widgets))
else
error("Higher dimensional widgets only supported for
higher dimensional terminals")
end
end
|
/-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.set.pairwise
/-!
# Antichains
This file defines antichains. An antichain is a set where any two distinct elements are not related.
If the relation is `(≤)`, this corresponds to incomparability and usual order antichains. If the
relation is `G.adj` for `G : simple_graph α`, this corresponds to independent sets of `G`.
## Definitions
* `is_antichain r s`: Any two elements of `s : set α` are unrelated by `r : α → α → Prop`.
* `is_antichain.mk r s`: Turns `s` into an antichain by keeping only the "maximal" elements.
-/
open function set
variables {α β : Type*} {r r₁ r₂ : α → α → Prop} {r' : β → β → Prop} {s t : set α} {a : α}
protected lemma symmetric.compl (h : symmetric r) : symmetric rᶜ := λ x y hr hr', hr $ h hr'
/-- An antichain is a set such that no two distinct elements are related. -/
def is_antichain (r : α → α → Prop) (s : set α) : Prop := s.pairwise rᶜ
namespace is_antichain
protected lemma subset (hs : is_antichain r s) (h : t ⊆ s) : is_antichain r t := hs.mono h
lemma mono (hs : is_antichain r₁ s) (h : r₂ ≤ r₁) : is_antichain r₂ s := hs.mono' $ compl_le_compl h
lemma eq_of_related (hs : is_antichain r s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) (h : r a b) :
a = b :=
of_not_not $ λ hab, hs _ ha _ hb hab h
protected lemma is_antisymm (h : is_antichain r univ) : is_antisymm α r :=
⟨λ a b ha _, h.eq_of_related trivial trivial ha⟩
protected lemma subsingleton [is_trichotomous α r] (h : is_antichain r s) : s.subsingleton :=
begin
rintro a ha b hb,
obtain hab | hab | hab := trichotomous_of r a b,
{ exact h.eq_of_related ha hb hab },
{ exact hab },
{ exact (h.eq_of_related hb ha hab).symm }
end
protected lemma flip (hs : is_antichain r s) : is_antichain (flip r) s :=
λ a ha b hb h, hs _ hb _ ha h.symm
lemma swap (hs : is_antichain r s) : is_antichain (swap r) s := hs.flip
lemma image (hs : is_antichain r s) (f : α → β) (h : ∀ ⦃a b⦄, r' (f a) (f b) → r a b) :
is_antichain r' (f '' s) :=
begin
rintro _ ⟨b, hb, rfl⟩ _ ⟨c, hc, rfl⟩ hbc hr,
exact hs _ hb _ hc (ne_of_apply_ne _ hbc) (h hr),
end
lemma preimage (hs : is_antichain r s) {f : β → α} (hf : injective f)
(h : ∀ ⦃a b⦄, r' a b → r (f a) (f b)) :
is_antichain r' (f ⁻¹' s) :=
λ b hb c hc hbc hr, hs _ hb _ hc (hf.ne hbc) $ h hr
lemma _root_.is_antichain_insert :
is_antichain r (insert a s) ↔ is_antichain r s ∧ ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬ r a b ∧ ¬ r b a :=
set.pairwise_insert
protected lemma insert (hs : is_antichain r s) (hl : ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬ r b a)
(hr : ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬ r a b) :
is_antichain r (insert a s) :=
is_antichain_insert.2 ⟨hs, λ b hb hab, ⟨hr hb hab, hl hb hab⟩⟩
lemma _root_.is_antichain_insert_of_symmetric (hr : symmetric r) :
is_antichain r (insert a s) ↔ is_antichain r s ∧ ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬ r a b :=
pairwise_insert_of_symmetric hr.compl
lemma insert_of_symmetric (hs : is_antichain r s) (hr : symmetric r)
(h : ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬ r a b) :
is_antichain r (insert a s) :=
(is_antichain_insert_of_symmetric hr).2 ⟨hs, h⟩
/-- Turns a set into an antichain by keeping only the "maximal" elements. -/
protected def mk (r : α → α → Prop) (s : set α) : set α := {a ∈ s | ∀ ⦃b⦄, b ∈ s → r a b → a = b}
lemma mk_is_antichain (r : α → α → Prop) (s : set α) : is_antichain r (is_antichain.mk r s) :=
λ a ha b hb hab h, hab $ ha.2 hb.1 h
lemma mk_subset : is_antichain.mk r s ⊆ s := sep_subset _ _
/-- If `is_antichain.mk r s` is included in but *shadows* the antichain `t`, then it is actually
equal to `t`. -/
lemma mk_max (ht : is_antichain r t) (h : is_antichain.mk r s ⊆ t)
(hs : ∀ ⦃a⦄, a ∈ t → ∃ b ∈ is_antichain.mk r s, r a b) :
t = is_antichain.mk r s :=
begin
refine subset.antisymm (λ a ha, _) h,
obtain ⟨b, hb, hr⟩ := hs ha,
rwa of_not_not (λ hab, ht _ ha _ (h hb) hab hr),
end
end is_antichain
lemma set.subsingleton.is_antichain (hs : s.subsingleton) (r : α → α → Prop): is_antichain r s :=
hs.pairwise _
|
library(arrow)
library(data.table)
setDTthreads(12)
main <- function () {
start_time <- Sys.time()
files <- Sys.glob('/data/performance-benchmark-data/*.parquet')
dataframes <- lapply(files, function(x) { read_parquet(x) })
dataframe <- do.call(rbind, dataframes)
setDT(dataframe)
dataframe[, sales := quantity * price]
result = dataframe[,
.(total_spend = sum(sales),
avg_basket_size = mean(sales),
avg_price = mean(price),
n_transactions = .N,
n_visits = uniqueN(date),
n_brands = uniqueN(`brand-id`),
n_styles = uniqueN(`style-id`)),
by = `member-id`]
write_parquet(result, "datatable.parquet")
end_time <- Sys.time()
print(end_time - start_time)
}
main()
df <- read_parquet("datatable.parquet")
dim(df)
head(df)
colnames(df)
# 1 Part
# Time difference of 27.56955 secs
# 12 Parts
# Time difference of 2.378997 mins
|
module Term
-- Untyped lambda calculus with built-in natural numbers.
--
-- Note that variables in the lambda calculus are not
-- named but identified by their de Bruijn index.
import Data.Fin
import public Data.Vect
%default total
%access public export
--------------------------------------
-- Begin: TERMS OF THE LAMBDA CALCULUS
-- Data type of well-scoped terms
-- in the lambda calculus:
data Term : Nat -> Type where
-- Variable:
-- The data constructor for variables ('Var') takes
-- as arguments a de Bruijn index ('i').
TVar : (i : Fin n) -> Term n
-- Abstraction:
TAbs : Term (S n) -> Term n
-- Application:
TApp : Term n -> Term n -> Term n
-- Constant 'Zero' (natural number):
TZero : Term n
-- Successor:
TSucc : Term n -> Term n
-- Predecessor:
TPred : Term n -> Term n
-- Test for equality with 'Zero'
-- (with terms for the "then" and
-- "else" branches):
TIfz : Term n -> Term n -> Term n ->
Term n
-- End: TERMS OF THE LAMBDA CALCULUS
------------------------------------
---------------------------------------
-- Begin: VALUES IN THE LAMBDA CALCULUS
-- The following lambda calculus terms
-- are values (i.e. normal forms for
-- reduction under the "Step" relation):
-- (1) lambda abstractions (that are
-- not applied),
-- (2) the constant 'Zero',
-- (3) the natural number constants
-- (formed by applying 'Succ' to
-- another value).
data Value : Term 0 -> Type where
VZero : Value TZero
VSucc : Value e -> Value (TSucc e)
VAbs : Value (TAbs e)
valueTerm : {e : Term 0} -> Value e -> Term 0
valueTerm {e = e} _ = e
-- End: VALUES IN THE LAMBDA CALCULUS
-------------------------------------
|
Formal statement is: lemma not_bounded_UNIV[simp]: "\<not> bounded (UNIV :: 'a::{real_normed_vector, perfect_space} set)" Informal statement is: The set of all real vectors is not bounded. |
State Before: f g : CircleDeg1Lift
n : ℕ
⊢ Function.Commute ↑f fun x => x + ↑-[n+1] State After: no goals Tactic: simpa [sub_eq_add_neg] using f.commute_sub_nat (n + 1) |
Exercise material of the MSc-level course **Numerical Methods in Geotechnical Engineering**.
Held at Technische Universität Bergakademie Freiberg.
Comments to:
*Prof. Dr. Thomas Nagel
Chair of Soil Mechanics and Foundation Engineering
Geotechnical Institute
Technische Universität Bergakademie Freiberg.*
https://tu-freiberg.de/en/soilmechanics
```python
import numpy as np
import matplotlib.pyplot as plt
#Some plot settings
plt.style.use('seaborn-deep')
plt.rcParams['lines.linewidth']= 2.0
plt.rcParams['lines.color']= 'black'
plt.rcParams['legend.frameon']=True
plt.rcParams['font.family'] = 'serif'
plt.rcParams['legend.fontsize']=14
plt.rcParams['font.size'] = 14
plt.rcParams['axes.spines.right'] = False
plt.rcParams['axes.spines.top'] = False
plt.rcParams['axes.spines.left'] = True
plt.rcParams['axes.spines.bottom'] = True
plt.rcParams['axes.axisbelow'] = True
plt.rcParams['figure.figsize'] = (12, 6)
```
# Exercise 7 - 1D Consolidation, Terzaghi: Explicit version
## Governing differential equation
Neglecting lateral displacements and fluid flow
$$
\epsilon_{xx} = \epsilon_{yy} = 0 \quad \text{and} \quad q_x = q_y = 0
$$
the volume balance simplifies to
$$
\dot{\epsilon}_{zz} = \frac{\partial q_z}{\partial z}
$$
Now we substitute the constitutive law (linear elasticity) of the solid and Darcy's law for the fluid motion into the volume balance and get
$$
\dot{\sigma}_{zz}^\text{eff} = E_\text{S} \dot{\epsilon}_{zz} \quad \text{and} \quad \frac{\partial q_z}{\partial z} = - \frac{k}{\mu_\text{F}} \frac{\partial^2 p}{\partial z^2} \quad \text{ergibt} \quad
\frac{\dot{\sigma}_{zz}^\text{eff}}{E_\text{S}} = - \frac{k}{\mu_\text{F}} \frac{\partial^2 p}{\partial z^2}
$$
Assuming constant total stress (constant external loads) we find with the use of the effective stress principle
$$
\sigma_{zz} = \sigma_{zz}^\text{eff} + p = \text{const} \quad \rightarrow \quad \dot{\sigma}_{zz} = 0 = \dot{\sigma}_{zz}^\text{eff} + \dot{p}
$$
Substitution yields the partial, linear and homogeneous differential equation
$$
\dot{p} = \frac{E_\text{S} k}{\mu_\text{F}} p_{,zz} = \frac{E_\text{S} K_\text{D}}{\gamma_\text{F}} p_{,zz} = c_\text{v} p_{,zz} \quad \text{with } K_\text{D} = \frac{k\rho_\text{F} g}{\mu_\text{F}}
$$
$[k] = \text{m}^2$: intrinsic permeability
$[K_\text{D}] = \text{m s}^{-1}$: hydraulic conductivity
$[c_\text{v}] = \text{m}^2\text{s}^{-1}$: coefficient of consolidation
## Weak form
The pore pressure can have (the essential/Dirichlet) boundary conditions in the form:
$$
p = \bar{p}\ \forall z \in \partial \Omega_\mathrm{D}
$$
We now introduce a test function $\eta$ which vanishes where the pore pressure is given
$$
\eta = 0\ \forall z \in \partial \Omega_\mathrm{D}
$$
and construct the weak form (using integration by parts):
\begin{align}
0 &= \int \limits_0^H \eta \left[\dot{p} - c_\text{v} p_{,zz} \right] \text{d}z
\\
&= \int \limits_0^H \left[\eta \dot{p} - \left( \eta c_\text{v} p_{,z} \right)_{,z} + \eta_{,z} c_\text{v} p_{,z} \right] \, \text{d}z
\\
&= \int \limits_0^H \left[\eta \dot{p} + \eta_{,z} c_\text{v} p_{,z} \right] \, \text{d}z + \left[ \eta E_\text{S} q_z \right]^H_0
\end{align}
where the natural/Neumann boundary conditions have appeared.
## Finite elements in 1D
We have a soil column of height $H$ on top of the bed rock at $z=0$.
We first create an element class. An element knows the number of nodes it has, their IDs in the global node vector, and the coordinates of its nodes. Linear elements have 2 nodes and 2 quadrature points, quadratic elements 3 nodes and 3 quadrature points. The natural coordinates of the element run from -1 to 1, and the quadrature points and weights are directly taken from Numpy.
```python
#element class
class line_element():#local coordinates go from -1 to 1
#takes number of nodes, global nodal coordinates, global node ids
def __init__(self, nnodes=2, ncoords=[0.,1.], nids=[0,1]):
self.__nnodes = nnodes
if (len(ncoords) != self.__nnodes):
raise Exception("Number of coordinates does not match number \
of nodes of element (%i vs of %i)" %(self.__nnodes,len(ncoords)))
else:
self.__coords = np.array(ncoords)
self.__natural_coords = (self.__coords-self.__coords[0])/(self.__coords[-1]-self.__coords[0])*2. - 1.
if (len(nids) != self.__nnodes):
raise Exception("Number of node IDs does not match number \
of nodes of element (%i vs of %i)" %(self.__nnodes,len(nids)))
else:
self.__global_ids = np.array(nids)
self.__quad_degree = self.__nnodes
self.__quad_points, self.__quad_weights = np.polynomial.legendre.leggauss(self.__quad_degree)
```
Next, we wish to generate a one-dimensional mesh by specifying the length of a line, the number of elements into which the mesh is to be split, and the number of nodes per element.
```python
def number_of_nodes(nelems,nodes_per_elem):
return nelems*nodes_per_elem - (nelems - 1)
def generate_mesh(domain_length,nelems,nodes_per_elem):
nn = number_of_nodes(nelems,nodes_per_elem)
#coordinate vector of global nodes
global_nodal_coordinates = np.linspace(0.,domain_length,nn)
global_solution = np.array([0.]*nn)
#generate elements
element_vector = []
for i in range(nelems):
node_start = (nodes_per_elem-1)*i
element_vector.append(
line_element(nodes_per_elem,
global_nodal_coordinates[node_start:node_start+nodes_per_elem],
list(range(node_start,node_start+nodes_per_elem))))
return global_nodal_coordinates, element_vector, global_solution
```
## Shape functions in 1D
As in exercise 06, we allow linear and higher-order shape functions.
```python
#N
def shape_function(element_order,xi):
if (element_order == 2): #-1,1
return np.array([(1.-xi)/2., (1.+xi)/2.])
elif (element_order == 3): #-1, 0, 1
return np.array([(xi - 1.)*xi/2., (1-xi)*(1+xi), (1+xi)*xi/2.])
#dN_dxi
def dshape_function_dxi(element_order,xi):
if (element_order == 2): #-1,1
return np.array([-0.5*xi/xi, 0.5*xi/xi]) #xi only later for plotting dimensions
elif (element_order == 3):#-1,0,1
return np.array([xi - 0.5,-2.*xi,xi + 0.5])
#dz_dxi
def element_jacobian(element,xi):
element_order = element._line_element__nnodes
Jacobian = 0.
Jacobian += dshape_function_dxi(element_order,xi).dot(element._line_element__coords)
return Jacobian
#dN_dz
def grad_shape_function(element,xi):
element_order = element._line_element__nnodes
Jac = element_jacobian(element,xi)
return dshape_function_dxi(element_order,xi)/Jac
```
## Time and space discretization, Picard iterations
Using a forward Euler approach for simplicity we find the time-discrete weak form as ($p_{n+1} \equiv p$)
$$
0 = \int \limits_0^H \left[\eta \frac{p - p_n}{\Delta t} + \eta_{,z} c_\text{v} p_{n,z} \right] \, \text{d}z + \left[ \eta E_\text{S} q_z \right]^H_0
$$
Introducing standard FE approximations
$$
p \approx N_i \hat{p}_i, \quad \eta \approx N_i \hat{\eta}_i, \quad \frac{\partial p}{\partial z} \approx \nabla N_i \hat{p}_i, \quad \frac{\partial \eta}{\partial z} \approx \nabla N_i \hat{\eta}_i
$$
This yields
$$
\begin{align}
0 &= \int \limits_0^H \left[ N_i \hat{\eta}_i \frac{N_k \hat{p}_k - N_k \hat{p}_{n,k}}{\Delta t} + \nabla N_i \hat{\eta}_i c_\text{v} \nabla N_k \hat{p}_{n,k} \right] \, \text{d}z + \left[ N_i \hat{\eta}_i E_\text{S} q_z \right]^H_0
\end{align}
$$
Now we bring all quantities associated with the unknown pressure to the left-hand side (LHS) and all known quantities to the RHS:
$$
\hat{\eta}_i \int \limits_0^H \left[ N_i \frac{1}{\Delta t} N_k + \nabla N_i c_\text{v} \nabla N_k \right] \, \text{d}z\ \hat{p}_k = \hat{\eta}_i \left[ N_{n_\text{n}} E_\text{S} \bar{q}_z|_{z=H} \delta_{n_\text{n}i} - N_{n_\text{n}} E_\text{S} \bar{q}_z|_{z=0} \delta_{i0} \right] + \hat{\eta}_i \int \limits_0^H N_i \frac{1}{\Delta t} N_k \, \text{d}z\ \hat{p}_{n,k}
$$
can be simplified by realizing that the nodal test function values are arbitrary and thus
$$
\int \limits_0^H \left[ N_i \frac{1}{\Delta t} N_k \right] \, \text{d}z\ \hat{p}_k = N_{n_\text{n}} E_\text{S} \bar{q}_z|_{z=H} \delta_{n_\text{n}i} - N_{n_\text{n}} E_\text{S} \bar{q}_z|_{z=0} \delta_{i0} + \int \limits_0^H N_i \frac{1}{\Delta t} N_k \, \text{d}z\ \hat{p}_{n,k} - \int \limits_0^H \left[ \nabla N_i c_\text{v} \nabla N_k \right] \, \text{d}z\ \hat{p}_{n,k}
$$
which leaves us with $n_\text{n}$ equations for the $n_\text{n}$ unknown nodal pressures $\hat{p}_k$. If any coefficients in the above are taken as pressure-dependent, the system could be solved repeatedly usind Picard iterations. For strong non-linearities, a Newton linearization would typically be used.
### Question:
How would the equation differ for an explicit time integration scheme (forward Euler)?
What we require now is the local assembler to calculate the stiffness matrix and the local right-hand side. Local integration is performed by Gauss quadrature:
$$
\int \limits_{-1}^1 f(\xi)\,\text{d}\xi \approx \sum \limits_{i=1}^{n_\text{gp}} f(\xi_i) w_i
$$
## Local assember
```python
def Stiffness(z):
E0 = 5.e6 #Pa
return E0
def Conductivity(z):
kf = 1.e-9#m/s
return kf
def SpecificWeight(z):
g = 9.81 #m/s²
rhow = 1000. #kg/m³
return g*rhow
def ConsolidationCoeff(z):#m²/s
return Stiffness(z)*Conductivity(z)/SpecificWeight(z)
```
```python
def local_assembler(elem,dt,prev_sol):
element_order = elem._line_element__nnodes
K_loc = np.zeros((element_order,element_order))
b_loc = np.zeros(element_order)
z_nodes = elem._line_element__coords
for i in range(elem._line_element__quad_degree):
#local integration point coordinate
xi = elem._line_element__quad_points[i]
#shape function
N = shape_function(element_order,xi)
#gradient of shape function
dN_dX = grad_shape_function(elem,xi)
#determinant of Jacobian
detJ = np.abs(element_jacobian(elem,xi))
#integration weight
w = elem._line_element__quad_weights[i]
#global integration point coordinate (for spatially varying properties)
z_glob = np.dot(N,z_nodes)
#evaluation of local material/structural properties
E = Stiffness(z_glob)
#evaluation of local body force
CV = ConsolidationCoeff(z_glob)
#assembly of local stiffness matrix
K_loc += (np.outer(N,N) / dt )* w * detJ
#assembly of local RHS
p_prev = np.dot(N,prev_sol)#pressure in integration point
grad_p_prev = np.dot(dN_dX,prev_sol)
b_loc += (N * p_prev/dt - dN_dX * CV * grad_p_prev) * w * detJ
return K_loc,b_loc
```
## Global assembly
Now we can construct the global matrix system $\mathbf{K}\mathbf{u} = \mathbf{f}$ or $\mathbf{A}\mathbf{x}=\mathbf{b}$ (see lecture script).
```python
def global_assembler(nodes,elements,solution,dt):
K_glob = np.zeros((len(nodes),len(nodes)))
b_glob = np.zeros(len(nodes))
for i,elem in enumerate(elements):
start_id = elem._line_element__global_ids[0]
end_id = elem._line_element__global_ids[-1]
K_i, b_i = local_assembler(elem,dt,solution[start_id:end_id+1])
K_glob[start_id:end_id+1,start_id:end_id+1] += K_i
b_glob[start_id:end_id+1] += b_i
return K_glob, b_glob
```
## Application of boundary conditions
First we apply flux boundary conditions
```python
def apply_Neumann_bc(b_glob,node_id,value):
b_glob[node_id] += value
return b_glob
```
Then we apply Dirichlet bc
```python
def apply_Dirichlet_bc(K_glob,b_glob,node_id,value):
K_glob[node_id,:] = 0.# = K_glob[:,node_id] = 0.
K_glob[node_id,node_id] = 1.
b_glob[node_id] = value
return K_glob, b_glob
```
## Application of initial conditions
Since we're dealing with a time-dependent problem (rate problem) we require initial conditions for the pore pressure, i.e. $p_0 = p(t=0)\ \forall\ z$. Due to the very specific assumptions in deriving this consolidation equation, the initial pressure is given by the (suddenly) applied load:
$$
p_0 = \sigma_{zz} = \text{const.}
$$
```python
def apply_initial_conditions(solution,sig_v):
solution *= 0.
solution += sig_v
return
```
## Time loop and problem solution
We now establish the time loop and in each time step perform the global assembly, apply a vanishing traction on the top and constrain the displacement at the bottom to zero.
```python
def time_loop(dt,nodes,elements,solution):
#Startwerte
t_end = 100*24*60*60 #s
absolute_tolerance = 1.e-6
apply_initial_conditions(solution,200.e3)
y = [solution] #create a list that will hold the solution vectors at all time points
times = np.array([0.])
#
while times[-1]+dt < t_end: #repeat the loop as long as the final time step is below the end point
times = np.append(times,times[-1]+dt) #here define the next time point as the previous time point plus the time increment dt
K, f = global_assembler(nodes,elements,y[-1],dt)
#f = apply_Neumann_bc(f,len(nodes)-1,0)
K, f = apply_Dirichlet_bc(K, f, len(nodes)-1, 0.)#free draining top
solution = np.linalg.solve(K,f)
y.append(solution) #append the new found solution to the solution vector
return times, y
```
```python
#spatial discretization
H = 10.
nel = 20
n_per_el = 3
nodes,elements,solution=generate_mesh(H,nel,n_per_el)
```
```python
times, sols = time_loop(1*60.*60.,nodes,elements,solution)
```
```python
plt.xlabel('$z$ / m')
plt.ylabel('$p$ / kPa')
plt.title('Finite element solution')
plt.plot(nodes, sols[0]/1.e3, marker='o', label='$t = %i$ h' %(times[0]/60/60))
plt.plot(nodes, sols[1]/1.e3, marker='o', label='$t = %i$ h' %(times[1]/60/60))
plt.plot(nodes, sols[10]/1.e3, marker='o', label='$t = %i$ h' %(times[10]/60/60))
plt.plot(nodes, sols[-1]/1.e3, marker='o', label='$t = %i$ d' %(times[-1]/60/60/24))
#plt.plot(nodes, sols[200]/1.e3, marker='o', label='$t = %i$ d' %(times[200]/60/60/24))
#plt.plot(nodes, sols[-1]/1.e3, marker='o', label='$t = %i$ d' %(times[-1]/60/60/24))
plt.legend();
```
### Convergence study
Let's do a simple convergence study.
```python
dts = [1*3600,10.*3600,20.*3600]
nels = [10,20,40]
H = 10.
fig, ax = plt.subplots(nrows=3,ncols=3,figsize=(18,18))
for i,dt in enumerate(dts):
for j,nel in enumerate(nels):
#print("Running (n,dt) combination ", dt, nel)
number_of_elements = nel
nodes_per_element = 2
nodes,elements,solution=generate_mesh(H,number_of_elements,nodes_per_element)
times, sols = time_loop(dt,nodes,elements,solution)
ax[i][j].plot(nodes, sols[0]/1.e3, marker='o', label='$t = %i$ h' %(times[0]/60/60))
ax[i][j].plot(nodes, sols[1]/1.e3, marker='o', label='$t = %i$ h' %(times[1]/60/60))
ax[i][j].plot(nodes, sols[10]/1.e3, marker='o', label='$t = %i$ h' %(times[10]/60/60))
ax[i][j].plot(nodes, sols[-1]/1.e3, marker='o', label='$t = %i$ d' %(times[10]/60/60/24))
ax[i][j].set_xlabel('$z$ / m')
ax[i][j].set_ylabel('$p$ / kPa')
ax[i][j].set_title('dt = %i h, nel = %i' %(dt/3600,nel))
ax[i][j].legend(fontsize=10)
fig.tight_layout()
```
We observe that time step size and discretization size act together, and that unsuitable choices can lead to unphysical oscillations.
## Tasks
* What happens if you switch the element order to 3 in the last example?
* Explicit solutions can be coded so as to avoid matrix inversion.
```python
```
|
import pandas as pd
import numpy as np
class GAS:
class Data:
def __init__(self, data):
self.x = data.astype(np.float32)
self.N = self.x.shape[0]
def __init__(self, file):
trn, val, tst = load_data_and_clean_and_split(file)
self.trn = self.Data(trn)
self.val = self.Data(val)
self.tst = self.Data(tst)
self.n_dims = self.trn.x.shape[1]
def load_data(file):
data = pd.read_pickle(file)
# data = pd.read_pickle(file).sample(frac=0.25)
# data.to_pickle(file)
data.drop("Meth", axis=1, inplace=True)
data.drop("Eth", axis=1, inplace=True)
data.drop("Time", axis=1, inplace=True)
return data
def get_correlation_numbers(data):
C = data.corr()
A = C > 0.98
B = A.values.sum(axis=1)
return B
def load_data_and_clean(file):
data = load_data(file)
B = get_correlation_numbers(data)
while np.any(B > 1):
col_to_remove = np.where(B > 1)[0][0]
col_name = data.columns[col_to_remove]
data.drop(col_name, axis=1, inplace=True)
B = get_correlation_numbers(data)
# print(data.corr())
data = (data - data.mean()) / data.std()
return data
def load_data_and_clean_and_split(file):
data = load_data_and_clean(file).values
N_test = int(0.1 * data.shape[0])
data_test = data[-N_test:]
data_train = data[0:-N_test]
N_validate = int(0.1 * data_train.shape[0])
data_validate = data_train[-N_validate:]
data_train = data_train[0:-N_validate]
return data_train, data_validate, data_test
|
# ---
# title: 88. Merge Sorted Array
# id: problem88
# author: Tian Jun
# date: 2020-11-24
# difficulty: Easy
# categories: Array, Two Pointers
# link: <https://leetcode.com/problems/merge-sorted-array/description/>
# hidden: true
# ---
#
# Given two sorted integer arrays _nums1_ and _nums2_ , merge _nums2_ into
# _nums1_ as one sorted array.
#
# **Note:**
#
# * The number of elements initialized in _nums1_ and _nums2_ are _m_ and _n_ respectively.
# * You may assume that _nums1_ has enough space (size that is **equal** to _m_ \+ _n_ ) to hold additional elements from _nums2_.
#
# **Example:**
#
#
#
# Input:
# nums1 = [1,2,3,0,0,0], m = 3
# nums2 = [2,5,6], n = 3
#
# Output: [1,2,2,3,5,6]
#
#
#
#
# **Constraints:**
#
# * `-10^9 <= nums1[i], nums2[i] <= 10^9`
# * `nums1.length == m + n`
# * `nums2.length == n`
#
#
## @lc code=start
using LeetCode
function merge_sorted_array(
nums1::AbstractVector{Int}, m::Int, nums2::AbstractVector{Int}, n::Int
)::Nothing
i = m + n
while m > 0 && n > 0
if nums1[m] > nums2[n]
nums1[i] = nums1[m]
m -= 1
else
nums1[i] = nums2[n]
n -= 1
end
i -= 1
end
while n > 0
nums1[i] = nums2[n]
n -= 1
i -= 1
end
return nothing
end
## @lc code=end
|
import data.list.range
import data.list.join
@[reducible]
def fibonacci : ℕ → ℕ
| 0 := 0
| 1 := 1
| (n+2) := fibonacci n + fibonacci (n+1)
open nat list
---
@[reducible]
def fib_sum (n : ℕ) : ℕ :=
((range n).map fibonacci).sum
@[reducible]
def fib_odd_sum (n : ℕ) : ℕ :=
((range n).map (λ m, fibonacci (2*m + 1))).sum
@[reducible]
def fib_even_sum (n : ℕ) : ℕ :=
((range n).map (λ m, fibonacci (2*m))).sum
---
theorem fib_odd_sum_eq : ∀ (n : ℕ),
fib_odd_sum n = fibonacci (2*n)
| 0 := rfl
| (n+1) := by rw [fib_odd_sum,
sum_range_succ,
←fib_odd_sum,
fib_odd_sum_eq,
mul_add,
mul_one,
fibonacci]
---
theorem fib_even_sum_eq : ∀ {n : ℕ} (h : n > 0),
fib_even_sum n + 1 = fibonacci (2*n - 1)
| 0 h := (gt_irrefl 0 h).elim
| 1 _ := rfl
| (n+2) _ :=
have H : fib_even_sum (n+1) + 1 = fibonacci (2*(n+1) - 1) :=
fib_even_sum_eq (succ_pos n),
begin
rw [fib_even_sum,
sum_range_succ,
←fib_even_sum,
add_right_comm,
H,
mul_add,
mul_one,
mul_add],
change fibonacci (2*n + 1) + fibonacci (2*n + 1 + 1) =
fibonacci (2*n + 1 + 2),
rw [←fibonacci],
end
---
theorem fib_sum_eq : ∀ (n : ℕ),
fib_sum n + 1 = fibonacci (n+1)
| 0 := rfl
| (n+1) :=
begin
rw [fibonacci,
←fib_sum_eq n],
simp [range_succ, fib_sum,
add_left_comm, add_comm],
end
inductive bee : Type
| queen : bee
| worker : bee
| drone : bee
open bee list
instance : has_repr bee :=
⟨λ s, match s with
| queen := "Q"
| worker := "W"
| drone := "D"
end⟩
---
namespace bee
def parents : bee → list bee
| queen := [queen, drone]
| worker := [queen, drone]
| drone := [queen]
def ancestors (b : bee) : ℕ → list bee
| 0 := [b]
| (n+1) := ((ancestors n).map parents).join
---
def tree_json : bee → ℕ → string
| b 0 := "{\"name\":\"" ++ repr b ++ "\"}"
| b (n+1) := "{\"name\":\"" ++ repr b ++ "\",\"children\":[" ++
string.intercalate "," (b.parents.map (λ p, p.tree_json n)) ++ "]}"
---
lemma drone_ancestors_concat : ∀ (n : ℕ),
drone.ancestors (n+2) = drone.ancestors (n+1) ++ drone.ancestors n
| 0 := rfl
| (n+1) := begin
change ((ancestors _ (n+2)).map _).join = _,
conv { to_lhs,
rw [drone_ancestors_concat n,
map_append,
join_append], },
refl,
end
---
theorem drone_ancestors_length_eq_fib_succ : ∀ (n : ℕ),
(drone.ancestors n).length = fibonacci (n+1)
| 0 := rfl
| 1 := rfl
| (n+2) := begin
rw [drone_ancestors_concat,
length_append,
drone_ancestors_length_eq_fib_succ n,
drone_ancestors_length_eq_fib_succ (n+1),
add_comm],
refl,
end
end bee
---
inductive car : Type
| rabbit : car
| cadillac : car
open car list nat
instance : has_repr car :=
⟨λ s, match s with
| rabbit := "R"
| cadillac := "C"
end⟩
---
namespace car
@[reducible]
def size : car → ℕ
| rabbit := 1
| cadillac := 2
@[reducible]
def sum_size (cs : list car) : ℕ :=
(cs.map size).sum
lemma sum_size_cons (c : car) (cs : list car) :
sum_size (c :: cs) = sum_size cs + c.size :=
by simp only [sum_size, sum_cons, map, add_comm]
---
@[reducible]
def packings : ℕ → list (list car)
| 0 := [[]]
| 1 := [[rabbit]]
| (n+2) := (packings (n+1)).map (cons rabbit) ++
(packings n).map (cons cadillac)
---
theorem num_packings_eq_fib : ∀ (n : ℕ),
(packings n).length = fibonacci (n+1)
| 0 := rfl
| 1 := rfl
| (n+2) :=
begin
simp [packings, fibonacci, add_left_comm, add_comm],
rw [num_packings_eq_fib n,
num_packings_eq_fib (n+1),
add_left_comm,
add_right_inj,
fibonacci],
end
---
theorem packings_size : ∀ {n : ℕ} {cs : list car} (h : cs ∈ packings n),
sum_size cs = n
| 0 cs h :=
begin
rw mem_singleton.1 h,
refl,
end
| 1 cs h :=
begin
rw mem_singleton.1 h,
refl,
end
| (n+2) cs h :=
begin
simp [packings] at h,
rcases h with ⟨cs', h₁, h₂⟩ | ⟨cs', h₁, h₂⟩,
all_goals { rw [←h₂,
sum_size_cons,
size,
packings_size h₁], },
end
---
lemma car_size_ne_zero (c : car) : size c ≠ 0 :=
by cases c; contradiction
lemma sum_size_zero : ∀ {cs : list car} (h : sum_size cs = 0),
cs = []
| [] _ := rfl
| (c::cs) h :=
begin
exfalso,
rw [sum_size_cons,
add_eq_zero_iff] at h,
exact car_size_ne_zero c h.2,
end
---
lemma sum_size_one : ∀ {cs : list car} (h : sum_size cs = 1),
cs = [rabbit]
| [] h := by contradiction
| (rabbit::cs) h :=
begin
rw [sum_size_cons] at h,
simp,
exact sum_size_zero (succ.inj h),
end
| (cadillac::cs) h :=
begin
rw [sum_size_cons] at h,
have : sum_size cs + 1 = 0 := succ.inj h,
contradiction,
end
---
theorem all_packings : ∀ {n : ℕ} {cs : list car} (h : sum_size cs = n),
cs ∈ packings n
| 0 cs h := by simp [packings, sum_size_zero h]
| 1 cs h := by simp [packings, sum_size_one h]
| (n+2) [] h := by contradiction
| (n+2) (rabbit::cs) h :=
begin
rw [sum_size_cons,
add_left_inj 1] at h,
simp [packings, all_packings, h],
end
| (n+2) (cadillac::cs) h :=
begin
rw [sum_size_cons,
add_left_inj 2] at h,
simp [packings, all_packings, h],
end
end car
|
||| Adding colours to the adventure game
||| Ported from https://www.linuxjournal.com/content/programming-color-ncurses
module AdventureInColor
import Data.Nat
import NCurses
%default covering
-- Define symbols for the map
grass = ' '
empty = '.'
water = '~'
mountain = '^'
player = '*'
isMoveOkay : Position -> NCurses i i Bool
isMoveOkay pos = do c <- mvInCh pos
pure (c == grass || c == empty)
CFG = MkConfig
{ noDelayEnabled = False
, keypadEnabled = True
, colorEnabled = True
}
main : IO ()
main = runNCurses $ NCurses.do
-- Initialise curses
cBreak
noEcho
clear
keypad True
startColor
-- Grab size
size <- getSize
-- Initialise the colors
grassC <- initColorPair 1 Yellow Green
waterC <- initColorPair 2 Cyan Blue
mountainC <- initColorPair 3 Black White
playerC <- initColorPair 4 Red Magenta
-- Draw map
-- background
nSetAttr (CP grassC)
for_ @{NCURSES} [0..size.height] $ \ row =>
mvHLine (MkRow row) grass size.width
-- mountain
nSetAttr (CP mountainC)
for_ @{NCURSES} [half size.width .. threequarter size.width] $ \ col =>
mvVLine (MkPosition { row = 0, col }) mountain size.height
-- mountain path
nSetAttr (CP grassC)
mvHLine (MkRow $ quarter size.height) grass size.width
-- lake
nSetAttr (CP waterC)
for_ @{NCURSES} [1..half size.height] $ \ row =>
mvHLine (MkPosition { row, col = 1 }) water (third size.width)
-- wait for the user quitting
exploring playerC grassC size (MkRow $ pred size.height)
where
quarter : Nat -> Nat
quarter n = (n `divNatNZ` 4) %search
third : Nat -> Nat
third n = (n `divNatNZ` 3) %search
half : Nat -> Nat
half n = (n `divNatNZ` 2) %search
threequarter : Nat -> Nat
threequarter n = (3 * n `divNatNZ` 4) %search
step : ColorPair -> (pos, pos' : Position) -> NCurses CFG CFG Position
step emptyC pos pos'
= do ok <- isMoveOkay pos'
ifThenElse (not ok) (pure pos) $ do
nSetAttr (CP emptyC)
mvAddCh pos empty
pure pos'
exploring : (playerC, emptyC : ColorPair) ->
Size -> Position -> NCurses CFG CFG ()
exploring playerC emptyC sz pos@(MkPosition { row, col }) = NCurses.do
-- display player at position
nSetAttr (CP playerC)
mvAddCh pos player
move pos
refresh
-- wait for an input to move
Left c <- getCh
| Right 'q' => pure () -- quitting
| Right _ => exploring playerC emptyC sz pos -- invalid input
case c of
Up => do pos <- step emptyC pos (up pos)
exploring playerC emptyC sz pos
Down => do let pos' = down pos
let True = pos'.row < pred sz.height
| _ => exploring playerC emptyC sz pos
pos <- step emptyC pos pos'
exploring playerC emptyC sz pos
Left => do pos <- step emptyC pos (left pos)
exploring playerC emptyC sz pos
Right => do let pos' = right pos
let True = pos'.col < pred sz.width
| _ => exploring playerC emptyC sz pos
pos <- step emptyC pos pos'
exploring playerC emptyC sz pos
_ => exploring playerC emptyC sz pos -- invalid input
|
#include <cassert>
#include <iostream>
#include <set>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
const std::string PUZZLE_INPUT = R"(sayndz zfxlkl attjtww cti sokkmty brx fhh suelqbp
xmuf znkhaes pggrlp zia znkhaes znkhaes
nti rxr bogebb zdwrin
sryookh unrudn zrkz jxhrdo gctlyz
bssqn wbmdc rigc zketu ketichh enkixg bmdwc stnsdf jnz mqovwg ixgken
flawt cpott xth ucwgg xce jcubx wvl qsysa nlg
qovcqn zxcz vojsno nqoqvc hnf gqewlkd uevax vuna fxjkbll vfge
qrzf phwuf ligf xgen vkig elptd njdm gvqiu epfzsvk urbltg dqg
sfpku viwihi fje umdkwvi ejzhzj qrbl sfpku sad nawnow ksnku
nzhj mfudick ueaa jnhz kpy pzk
euiin xvl elaoelu wbdd xlv jtm nohtq gfdbgdg gdfggdb edtym
xfmkn wyww woe hwysuh gjw dtk utryasc dela eluk vmmun
nmag qfwe cwslmgd nlhf hpf
ifs sszo iod isf jna
pjptwg wreera leyb hmlbpf qcrbma ylgue
rwlpo jhla rprxvgs quguh pyybwgl qqvcb
rxtcpdy wmpci mpcwi vwvdzdn nfpnj rcsxinl itatg ycy hrctg ron wveju
zmkfn wip pyiz pyiz tnyg dvftf elks ezhotbj wip
sgmtfdd xdl sch sch yaxzh wphgksh knzrixp yaxzh etm czqbaa jldta
gnbr rnpd upe eeb sbq sbq oxc rwvugoj
cshk thcc emfxx emfxx pbtcf jpim vltkqar czy iudkac jhpcc nqs
uzbvx fkiuyk izxdiu yutntvn dixuzi hkyfnud oyz ynutntv
ewl mfns idy fphu yqccb pte unukirt unukirt fdx
lzn tin fgena qbql qycbdw gbtn lctlysx adhjfq blu aiv
ites ites pbxzunl vljzh lqgerta pbxzunl
vmk wjfzvhn pqkidze qfwh
tqprmc exypl caf kwikh mdyyljc pbo hhxxo skna
sqxgejb ejc fvup hpesvs luz fcxqwhr ypxof fxlcp pxyk xiczjri
vjg qcw fsyqaoj mxf jha feclqqr vzdqnk verw mvmvm pvdqtcd xsfu
fwwn ktvdh aecfv acfve yjozxwo cnujw bcgde lphnk knlph bqwlqju
uwwapm dlln uwwapm uwwapm
huupab ewetcte huupab ewetcte
wjs zipivpd klwafr ipcczg wbv uujstsw hykn
mgojdyh hlm xruta lbmaxit pabqrnp vkyigd ptpzr glin gfau pbo
tbwx baqxq vtz jwex tvz tzv
efopwx wfknzb ogaxln tqzrh jne zugd zpxikma
rdjsa arjds hqdldw fjrtl midt qjv jfrlt
dggqohj bidaaty iah lgmug wwmlbc lggmu laonaoq erkqrb tqolnns iygv qnonlst
msc glwn xjfnij itt pka irrafjd euazydj silo
zsyut znsht ldky zsyut dzcdft znsht
iit cyteu pib fgvrs iux ffctql pib zuzp zsbb ieoi
xxtwlu kqfxjhq isj xqjhfkq dohrs haovzc cgfwfrt munqon vuyexz nouqnm
eptpqgi uiflvd acj livzq ejtt bniud cjdh jkrcken lspfy tpxri zibj
zxme dpo fumup gly bkdcwxn lsly eglhe
uoshw ijoyiql rcskaa vjbqv roiinzi fppqdu
xuw vdbxie oypcx khxq xebjt oypcx uitqep vdbxie hoz
lrjv tdksk uebo wktebvx nlapmp udhhxh uliqbm cklyyf jlzw xrmdlvx
fosspck fosspck fosspck qyidyur hxnxmb dkpj
rmrvlms susvos idw hzy idw tjgxbc lhgqxr tjgxbc uuq
etjmbdr hwqe lnfwzni lnfwzni good eisci etjmbdr
yqde bmlcc yuel vpyplss vyvhho kslgiu lllhc jtkijdj uclz hfbqsf
tlohlvv tlohlvv bdqahw tlohlvv qavcqrn penia saafy
lvtzyt qffe eaikhv eaikhv wbnl mdkg mdkg utfrm
luowwk magp luowwk oyao oyao hsb yms
gnxply vsdqum nprf jik axdp ariqjpc hjqcc
izbo nkqkb xpqg pgxq qpxg gpm jxbkvu resj
hsgyxar hvsl ner zzmcn lcpdvqn ern
rfjlhu xkyh hafs cvvk drg vjsk mymc iab ycmlubx kpwemiw
wlci qhhpr vhpr oyrili cnynh sivdso ldjya wilc ioiyrl
cdfwd mbtk sienxui jsmxzo yxbeyl bybtc covxaq yuxn ktbvztl ktbvztl rcekjhk
ptenhqv tzdt phetqvn mfkdz
hmezeak pqvqld amsih jxqacc uferfyh nfqjsz rtuqdzz pohcx qia cpxho hgpqs
iygny dluc uxqz nlujm xkdtlm xbdgepg jwn ohl wpfll
lnqf pcxy cpit enp zpj lqfn oowgw yoxdff ohvcfcf fuvz qkpmb
oydu jlscilm pzxen nmtdngu tslcupx ntdgmun uztpx nlhh jqn llsv
euyx epn gyvg cwtoe ruyap yaurp uryap obbl ovo
pgo irm ksrxe qotuygd afwh qfhzfsr wafh dqjbwce dzfo hew skrxe
dpvel dpvel ipljjxs vrrsob iakey uheuu swxu qmnmn mpjkb jqrwfmv jozj
sempz plzxqe qvyg sempz fejux
cqgqvg zhqir rqzih vyu fmb mfb
uejl kjh ayz dzimg yzafvg dem vlogg
htfkd htfkd hwykmm htfkd
oxvgq wtai rkyyxya ldkecdv
lvlrsu rsullv pptnrwi slvulr vxrk dpzti
gde ixwoz nnsx nhc nzi
dsadkj qtgya wco psyondq jayad crc lswwm purrad pof
nocibgs hxqdejv nlqxdpu dvzd
jfaws aiwnjm tqjpgs fuiobz gwnemv hjevs xkbbgiq sakgv zmwpkuq grjllw
xrr jwhtchs boaqkg wjhdr xrr
vyapct tgw juzgwkz odddvof juzgwkz
unuu kubdd dxr drwg
qpefzz iemo fwa vhdcxx
hseqy copss gytzub lxi mrxtwc hxqqdfx ijt kcy tafjs jit
uevse rrq zmwyjfe xljx lhgnyzt rngvwqd
gfvpyhq xpdhind eocgpiz ebs pcmsgjy swni iwns thspnh yvbzxz fgb
hxr ehw ekfd ncxcs gxjmd oqszdjp fgu gwuoafw zumenf qltbw whzuxov
wfc pawqo pim jxgt dtiwzil hdptivc slkazm htafjih hzheez rkk amy
mgoatiy pkec ddvwyni zuya aqrcjes ubkaeus nuhhad upe qfem bpcc
rmyeg qfq bia lzk fusqfb ltvgry vggr xaxi avwdkbg zhlzt
zkjoeee dyi sxdwfqa irqljmw gek dgdb mrakr ddaznn zlh ajzzacf juv
kmqcy pohbej hujdgao rsxfkn vlu
scnpa hvl cybql lvh lbcyq msw deqqb yjpsndq
ndhjooo dpf ziey jtjlc eesag ldhgoif
tysbae wkpst kjz stpkw sil yetsba
ghvlfq flhvgq tgkjie gqlvfh
oimn vlmsljl ocala vokhrs odyv msn dzly wcky
cfjwmh rpsdor bttnkg jxenm mwdk mer jgsusdz cslf
ialvxk bvc qjfikr caw puhmmfl xpmsx
tyoey egcf dijg vywd enued uxkshz nav bdrn hjugffi iobqwiy
eykhxck shpfjhk vlqg alkenz kuj okxs oeth mqbr nfvqvkv xfvyi mboo
zbw curcajm mel jxqcw mpdscxq rhadty zrddeh wmedc wkcwt yvwm
iee hzeofmh pqlkkb azlam fpj hzeofmh ripi
sawaqek oyoiwtb npq pisadk nnd bzgo wiqme lxnvn
obqx ffiegn obxq for xobq
zwway wwazy aqxg gaxq
ebssilw nuscati mofyc sogyacc yujmdwu ehxsx qcaf udvoo nlcfaz eov
vnbe wtzzjn bczyxt crmvas zujy kukq zujy kukq
gvltk kgltv kglvt zflikic
hby pium gut fjqn sksoqyq kcliapa
tbonrr prf vga jqgw ulze ukfig
zafixw hia omgwoi noeiox fqbket iviidgp bebune kwcuotp slvy wcx
fjq cyecn fhxvj byv kojvj iaqd aaxva rkogp
vqbbt sjmr mxu mxu rlfj yqhtzv cuar yde yrs sjmr
iyxiyp auepgw dtpbyvu thuoai fpsfkpn bemgbsk lni ozy jogp xldyvvx fpsfkpn
jtha ibn ahbkh xzxkei tql mycvmyh ioyw
mpsc pvdiuu wqixxlo cqwmlrw cttoz lad
srl xxlnofu dqf snxd zjlp htxzd
fkv berlbyh kyna wkme qjzgh thpw frup
irhreaj udkpbza qmgp ormlipa lbyuc
empizc apcb ossmtj awk ttsgi bfoymzd ftx jkicph qqjv tywp fwzfe
zaqkd ysn zaluvs rljdk ast fjp amjqr uabrya ufswzjg vcldkxt hzsmrbl
qvy tqgnwj akibr tfjevhv vav
mhe sxg hacoa emh kasf hid jklfy ijk dih
qvwbenk akdctm jztmsx aqvpodu vmknns nck letcrk poba
lhve kkvff iiixid vtsun uvgte mmlxk pgd
gktphd aaoqwz lrvsuw ofcyvmi suvwrl dpqiol wjgj uqigjx
tbp xoc lmz dyzlvp bjleh pxj xjp xbil
gpzgvj tctszm tctszm pnp upqtmm rribg tctszm sllsbr
hpm qvjnd lyqg bybpwn etz pwfigbg uqgrvpg cvniubo
tpowus bdncyxg gmm ebfg zwoue izgkwtx gmtfeg xvudp xgmjp atrvn aqgl
wlrxvo wvonohi owxlvr owhnvoi
knyo aiixyi sjtqb kukhgv qkj qiuefb syhfc aoana okmot tdsmnoj eyzqjn
szhto szhto szhto fxpsavu dtcz hnwqdvk iza
poykme rboczge tuyiw sxr
lpgbp bpmf aiqy exzqt gxdoow yjp fxwdmt eoklc jnps zbnbiwr ppvl
huecy jjhyz pwcea ffofmj tts
ahbmkw brz xdenmw mwexnd ncdxgf gcxnfd
yhfnra vqljz bkyxzt vhtsyde ysaxt qbw
gqhiej rofhmp soeebdp rcuiblb rcuiblb rrnh nses
pxrwe suil iihzf lhcgmfm mqasxh ttpp kqitdyf cuabaa
cxl cwsp qyseogj dimvv igsoxu ncrexla ubrvpp oum usluv
rkmo jqqcdjb mobqcta pbcmoi afjlh mork
nmohoeq fezpxh fezpxh yec
yxlncrt ivi dajo tjpim tjpim
hzhy rcjs uhyvwz tdpxlqw itoiyf
ded apfmhe stfk ugyujv drwks zagqnw mbbzmvc aoupemq
iezre wivdwif xzytxe xwytd vpnol pljx aot phln ztncw
ozblu asda tkxh xqe pvijnl qwwh uvp bdhtgjt uynwtav cdz uqmvp
eukgtsy kdfb bdfk tnv dfkb ewdemb
rsf cxnk cid qsa zwk oetnggn
fpq oim zetbmlk fpq oim xgv cbaj cjrqm
phgldt fhmkc efkztj qidri vsv bvjf lfwfgm wfuoln toamg wfuoln idrs
iuc rrdnk rrdnk asqhnz qxkigmo eeoim mmdtgif akk
rfvsyy kopfhmd tnv ibo demeqm gxrxw hwk ukorln bep
ialo eogif sxlj xfegx nanch egoif eymwt
kttrpjq gbnyiat kptg oarewx vkmt gbnyiat szyokf
tjll xviodi tjll efc rliugl wfbbpq wsqvdli jur tjll bguqyu
uecm yzjhn vqf labnc xyaksj
hjtef zzq ellr wtrodcg drwqo ernt uzx sqiokam
izmh ddutl bdzft jvfthh
ecr xqrp qlxstu kgprd gqvtwni mkughf bulabe bvoxkx
jwsna vjwq swkycg cpp dvmyal xotxviy qkiva ffa eakwp fww yirri
ufnl lpuxw rjki nggh ajdkpvo oeuaemy bjisma vsjzc
ctxu aavlw rap fzxtcp msufn fzxtcp sdlaom vgvdvpc
rftw cyf twyxi orifavd
ogiht ertz wcw jnqdup phvp lbw
tplpyq jeh aobamqe bvaim qptac gssi mkjbaj
nmklyg iitx iczojzr vjspqb uooky uooky hjk
ggnekbb bnebggk sepzjd fvqfgr
wnfwrn yaiogv mbusuy cpbcgs thjea
atndjc dbjgdz guedeay rasa kfhame pusuu dbjgdz
xivzyml xivzyml eqsykxo bshvz xivzyml
nfe ayx gscy ylyp oqyl isatnpx poaelm zsrw dpd eyrdjpq yllk
feqktz mlm jhi yxigeu xzqa qwv yquxw emken jgqsp rojfcu
ruvfcud poubal xswer hfhpyp guf pzgzoq pzgzoq jwgxafi guf kqzzlu apg
rxwcsdc rxwcsdc ywu rxwcsdc
dmgsey xrtx wldwyxz avi
yxnqv ewlx fvif ozfcbxb zqapa yudqksk wlxe mjpvgz
ozoa ozoa hwkbp ozoa
qcv drtqn uqv kcsavgn ybzs tkw
njmloq wapa srm srm ifurca
ezm ccj rub yuaww xhee liikjee kcabgic sbgqx vrpyo pzmesdp ksvv
hycyne raaksm nylsc lcpgn akasrm vxwoaum
zhugs pqquitv bae lyozb fhij pcdcc bae rygsgm pqquitv pizz
oxx bzk grpis qiqljwh svkn
qcq qqc fzgn sqg
lclad motw ukz zghp
glr okzfs zgv ygsvv sauuog glr amxr vvmwmu khy eyh
ukpxpy rgnqyaw ncm coeblf
qdbr ortzo spvnrnq uomtj vffbeva
miwar bidfxp eibo qyee
yldec ghwj mxlemvi imac klkvmg fekxhp kevlzfr fcgnoq fncgqo
hlm vlol qdic rltij nlzxfys rzpoh
krpwspb yrosr hioqla dbpgzgu dvkvvc vvdckv lcjzb qbsbr acbi rtnk
iqtvk jcldzuv smly whmnte mdwlse mkxw mfnkv mkxw kes owkfh
iwcjmkt rnb bjcdjl furhzuu exs
kjwu iuaj ixkujoa jzeau whpn
tvj zrdy fwsbagh zrdy czuzum lxotprx wbohaai
crsyzod jouf osxntw iwzzie bodu scze gjxn vgxvqo gjxn mmthykb
dabjfb vjqz cvr gsymwoe qzpusj twvwhw gyvlqd kdrdkzm bdljp cvr
vmswdz lgjsvxz yjkgqkg tzmjkfp uzbmwxe kuqa dzomt hep jjlibs oxvpvq cix
iqgd btwdjd ncdrovj ltxqc orwhdlo orwhdlo
nxro uxj ovgha elvzl xmlzssr wonimvb urecfx dbfn kope
tbes cgyh fypswue fgxjqtd dxdrfm pzhnaeu kugspa
eouzw qrpokyb fyhpb bcvfvze brdwey gpaa fpqutw pbqkroy axtc egamku gxk
xdrovpt peeww wkcin suir gvrbix
hgsjks juvod jtii iijt
yaw hzifa wpagkd tgvmc iru yyeuy mgcvt fhiza
lsk lks kls edypaxo
tjz qjs mgoyd gomyd ztjbex nprwk vvw rtjsq quvf vuziqtb oygdm
kftodz xua lyxt zfadf fgdwt zfadf xua ehwykd wniahd mqoarg
qgiapb xptk iscyf zfspn qvrpva egufqte zfspn hksw xwxrs dkdruku vegfs
wqifs wfsevg iwnjjpi oajju tkvhpl lemuw
rzbmhso pbvb lfgpq fzjwxxh pqlgf rbhsomz
ufi aiyd gxozgx hygjp dtma uughdc ojumcf yuadt
caami tqzkvor tqzkvor tqzkvor
vhtnvyx myxdywi mwpwq hjxadd qkcj vvytxnh dmbea
jvjtcjg mbiwyad cup xkrfk puz uxpmutf rjxyxyn mfchc
ocrak zprfbgu pjjzl zoehfkm xqn qki uxq tcv emknqjp wvmkas
nxg myr myr vnfzpoy
gwu ezt kbmeouj sxue cxax gcquz ieegnal xecusia vxf
xermi xermi qporwc mzemns ticltnz ddpsstr ddpsstr slgbn
xnujwtw bvzv xjwntuw unxwtjw
tipo akp fkmcls wglmjq fnrtsv
fan dfbya qrp lcvxqqu ldpm gucmeky mrzy fixaph rygneb ocm pjh
ovtrqs ujmbnal geihpe mijhy eewuic toaxbp ipy tvb evlmrtd lbujmna
lsmbwwd hvurk ihbuek hvoyq erzomhn gue lpq dihon dgzvst
fuoshq hfrzeu zfrhue ufqohs
icgwnbi gmhogxu gmguohx toixb hfwj haxlav hbe jdpxeyi xtgfi
vfakk ioil hddqu sdztx hduqd bmiuyr vmas
mcvjjhf sfgt sfgt lambvp dnqc pfecquk
xgr omy bmoadg afbna mar nicpazd iveku zdioyo
rpipon dwg wgd pironp
fkyx wjefuy mfesst ztlf gnnceb rsbvuk ckilt kliqnm iuifcvu
lmgzx oknwr wmttry luipa vcttj nuqdmy
iota efrxkk daqzm certtoi nnvqrwz qrqgza tllwp efrxkk
alde wqmdjy erh txrtqm zuljg hspbnrd pvsnebh bkue pvsnebh txrtqm txtthn
hgggm rswwfpj uctzrv bylqeen dpbnw ostsjwn jtjiyuh ofxu mmmqlg ayhza opbgdrv
qmhkh orbeokv agosach lhujcju jzpp wmxtcy jcxglu iuwmzrv xwkgz sxlzld
dzcdm lwal xpujjm xpujjm lpfojz lqqcon qmqrg
gmwugq ceslt rxcogaq jwkraq
joxr brdy yixlou brdy lnr lnr
wbut pxlsclt igigapq zeacg jxiezn hvws wwz ujpbl fdjtfjw opod kea
tsodswf pufo zqrt zvcpu
nyy mrqmg zkt tslzsf zkt
hxywv lbmogd hhv npyzgjy whfvv mlfqjr ggjz owijo zmesslo gtvizw
xzz dvpzxbd wxwlp cye rcqpgrr gynzo nhy gzpk fpfmb
nhaakbv iazpdc yadqbe kmqm dffq lidnh cegjosw kgd hwivd wijj
cwmdyf huoy awihev qav cwmdyf rdwck hahj pesfyk uoju zrirjdu
qabl vwcwbb phnd xnp huuzwxl rukbp kod sfu ngcvgrt buncnfw
regyd gjzfwf hpuv zmm vphu gwffjz
rdf emo crsoeo bksetj aqfzm pphny
opbmboi iakvj ymjwm vxoq qvox yafk zkch adlusz
qhm jul zasv xhu qnhjwzx
mjmyvd mezfuls upbdpzw awc qxta bzrx tjpjmj dxfyewc zorm
bko kfokm htcpoqc liuvj xhmpcu ccqphot dthvo pfj dtxpmu xoocm cmxoo
kxv eenns qhpfsvo gqoyv jzjho aoscl fetug agxmfea aygpt
javmegf jlmt epdwy egfs hwv uszcqvn foixpz iukh dbuhqgs zgb
zrex zrex xtx ydan maomp hqdhh mfvan broh wvwhqbu
phatsot joipm pmniq arqzmbe vurl bgy iwbwk oyhngcv vnzbzgm bgy
xprufgn vhca nrs abuh zwsxmhk mqrj tyslsij ojkdzom wepxg koodzv ypvyy
vop nnpz mcod mlli ntyhz laqztb kauqkla gmrfte pcuhaci
vrenj lypors prknc djbdkzv amofdx
lgig lojnrw obusoc fkwe ggnv pydcraq bvdivl vev mrojjs rxa
qeg tap jocwlsm vqxa lmjscow
gptlrgq vdasm erdc oparmw
rgbsa nacqhvm pczf anupcp upudwgp
jbnobi ifhzrd ihrkkf osw wos lrnwv
aiuntpl fcxpmz fplacs fplacs tipm gfotkx
fsbnd qoc ozmbi rqv fmbxh tuso kfoxvjn ocja zzs jwplx
muaklvq ghozoxh nwxbh mgoou ufptl ouhh reyuf jougckd dgprag
gwbnqwv dtrd mkzxinl erxl zmfa skuu crxmp wwao wwvdpk nxbn lglzy
qeejk wvnypc yfzyfcr eeqkj
nmcp fmkgfyi grfthau azw
kkallxz rjke ukbt ixkhfb bktu jkre
pxj mnwe djrjde gpsc enqz pdbydx cktfs jjeddr
mgplj yyunujc vis odee ccesa yyg yjcnuyu doo utse
flyy juvxomm vcdcyva lfyy ozxnuzw bmgns
kmsypi zpbyiv rrycnb qos sslwyeo jgbyv njltzt fuwk nwfb ozcf xqnf
sdcvgmy sdcvgmy hzv uyq sdcvgmy
fyox vmgxahj ywaxbmm ugy ruwc mys yrjwr ozsxb vaq
gjpyc sgdn kgm fbvq cziui nzy bwu ezjkkus jrag
kxcr tgjxss xkcr bembjv rbbiw bwbri
dcz rrhvdc zbonfzy ubjt
rvq yjnzswt vatkopb xlj dwxig dqlt qts iva
lylclc jptz rbidu lbt byxk
lwre vwriwh afixsi vwriwh
kmvbflr nfptw fbglxh pyas dxmn hemf segaz zrs
dvbey zmj xfoi bma udtxhb
yryng geiwgz bbrvjp ala
olzicp olzicp qhhslry olzicp
exf xdmwh xdwhm nhjsssn rmlkdb excguia fex
xkwgeso htys sjdk jizciy gjjl phgqdjh wzdb izew zcrumu llxfp
frkohf oifsm aisebkt ijsfkot ukk
koqf xvoior tpe erfpnp npnx
sneysk nsxki wpmhd mdor akrpvgz moicncj sbsj owfhj exw
oqqbvk xztx gtxlms icmo
lfy ltq dlzqlvi ovbrsa gzm nhcjq umbtgm nhcjq
iuopdzq cqaeuu xuzngq kxlx laml slvvr frtml tvioiez vyoomw xickbqh
ckahov mepeku gtaf gtaf
tlto cnnz kzsbkjo kzsbkjo
kqf comkf dvrkyl jdsqi rnwvb vxvd pok
hncq xcx yuykfs egrruvw yqh smcou
tywyq xeq cix yywqt jhzptci hybcoe
zsw zsgot wnu sumd azmuos qawjaz rpf zkxgwdu iom igh
vmxmelt gll ysbbt yboqoyz ykdglk cnypf otn owsz ipn epfeka bkmy
wxjpce etzyavi whb sxzft bfu dgwnbgc nfw sxcteis qqpk
kofv dgoyme vlza oxhbo lrqt uic tvfqiyy iaqm afnk
nsmpg wkibdcz dxbw tlxzm zgwe nqwjji eacbhn blk
shlgws eencr rtufah kjyvqw transt ecsq otbf
obs xsjceex ffqj sob djpq jcda zlskve
rfqtle klarp mtzrx rasr eisqovk rpt vymibt zwrif ilsnd
ldu ffd ldu tizfexr fwpmyan
flxso tzec pzn flxso kzdouon tkvkj
tvd arh qywql uev btvnpm
wtwx kzafvk ybyzmhv mdbrphy vamlvr gbxhod tyulba krcqj ikotmla qfhpa
bnfin ebngj agfdfzu rhjtj aaqzh fsyp nilar uwurjnu hhmso hhmso
uanmesj vshh syosjdt xkormf syosjdt ifvytwl qnw vshh jkg
epyzcn pgdxgye lecnx nebg jzdhvge hfy imiyft
zonbcnv vuvg sxtuty zdhmiow lmud cuegzg
bxgft mxhzrh unqd pqpsnce khykn qlb oujdxpq pxrd jzxjuxr tij
qss mqirowz ijjswjm jjer utwn kuedqxx bxshuok qkfag dmfwcr
jgln zdohd xitfbge xbokj xxeuv wqhvhjo erg cua fhc mhwy
euo ousht ipxt tpzq vnbmlo wvbjpb yjg bwpjbv nzvsea aerhsqv
axhmi bcf zdx vplso xhmai qsk psolv
ydnpmyo pfba zmo nat ykwxvm ydnpmyo rtd uuvqqr hcfccbd rtd
ytp guw ydmyf rww oucmpf gemhpj labc
edpbefn awgg qzpe aat cupig
mmi ghdaoh ibx fbyj gge vmmssen nplt mmqcra omcvm uwa fxypxfc
kjaw mtijne cfmsigd zwcjjd ajxjlqr tbp bnilc
fse ele vcsyiv bfe udny vznrao mgrjfgw
hadl nikvvpf gmdg bkmgt ugj
xkis qmr cgz nresp gms zrii coxkke vfsqiil
wmicbf bkk wcwklfg vpcbeg kfmjab vabc dax tnao tnao fvvzeyq fqm
bct tvj tra soo stqao kqua ikupoy wulcu nauxkkb pvqxy bfu
wpz txdduxq gaehfki kxo lvjzpxu iqon swr eyihl nbbec
fuphnbj bdtz huwu zdtb ilgzpa uyaut vpy viff tuuya
cvusbh bgy apsao qsupha
jtzlbd ljfvh wkjrw xsah sef jygb pqym zbcwok zdmug qpym
hbibuax iorqc dqjrs daeb iorqc qiw sagyt rkc sagyt khbr
shz mgn pqrdbm jvace gfhnq ann zosq wdwzmuf kswsg dzt brlavyo
qiw cdvwds dckpruy pybjra lfvgfn cwj bajtud pojehb rzrzvwe
txfyk zkgeeu zkgeeu zkgeeu wskcv nccoz
eettnxq gbgr uiqonyz wqtgs ozfjbn gbgr
svd thmmr rbbtxn sxkq isxlnhf tamdlbe bqrgvu nmpvlkc spko
qmn rspbjme ikjddkq kdb ugpegi egipgu
ufffijo revqpep zfw kwd pnya blqo rnntzx anpy
piaeyf vbeye uuqd vbeye
hamd hap ekk lgla twto
isniinr crz sjpmfxn uskwj
lzeofk tavbq ijcglqy lvy jliqcyg lwlip
uhyyyw itlrf tdc iabeocv jzwnjh vqxll nefze pyrxmx eispxnm hzlksce
ucuh mlam bhyej rgzkew ctbo iswqnvg
ytmb toppqgp ytmb gqgpr gqgpr vps ebv
eavn atkqltv bjvojs kaskr vqltakt uiktr xglc eyb rkkas fhnf eaorqm
jmfipc ujggeh hdxpfa xtab ydkibi ycxn ujggeh icheh vpznael oprbf
xazqxg khlemu awh uwz vhnixk vdcty hkk
gcl kayi hfozask grpseyn zviy tzoum qywnr wqkhq
ctrrcpw wqfbylp wqfbylp wqfbylp
gtk lqohf hqeaku mdj zrfkmxn bcqgf msing
luhpel kexokpx vojap ldaexs bbbtz
oimnqb esg zyjmbfh dfyhcf khpo zjtgm yelztbs ugj zjtgm mxro xyfxpk
dgtsu vvk wwfugbx aai zlxab beyxcg bpx chc bnxui
irrwbo orwibr lqt qtl tqknh
ihjsg ihjsg powwy pycyqo ihjsg
xdcu outh fnqrc eihkss bdylm sjunib eihkss
jpnw ycimse rffu ismyce uhxl feai
yyodnh dvwshkx vulh pvxj ydhyno hyodny
vuuweg pfguvyu orhei orhei wrm amkr xecja lmnveth
wriwe xgtnvj tdmxf gadtqh bezjvz lifu
euft tchbm xmtlwji tchbm
cfi zudn zludl pwiu axe psed
dbtfwf ajxcudj uaxdjcj dxuajjc zouyy
fmycmej bqhe jyfecmm kkrv kcdvjoy
grtb uzs rkxzt hivhic brtg hwyc lsl iivhch qbcp
ymn xfpka hqm sldz dblvsoe
qrcapma hntgmy difrkpk difrkpk xlsph
flvqh akcw boxrz ywhq boxrz esnxzv boxrz
zrvh jskaw mfs fkj
abveb qxfnlfq abveb kbwiyvd abveb
pgarl nbfrenx rnxgx bdlkix liltdm dzcokeg fubupcg iwp xfayp obfaz nevfw
nuhvaci blyv fcsp adlanka sjy syj ysxl
avwakn dkoya yzuszuk lqrr oqfyd dmgbhd lqrr
pxa mcvtoug nlweso yffqc dtuagcd ovvrkz ggfhw wnlseo bpqbn ohxzs rxzo
djkcl kbgyfir ogquot uoqotg jtmyd ohudvle xrnbt yvsln wykqt hntc xlrhqrb
ykt tkxfmd exas kty
zebstke msbbndq itmli ubexmht vekvd xbmb iajbj wac sta
ptdg oftwo goiulah tfmsrqs jffxvnv ozaluj qlhqjy wyffa
xeq ezmlpw xgno xorvfo yzq vwif wsi
hdove hqbzhu pjrxlj uafuh rizlb advmkca
jzk ddoisdh tfjh yuvikps ixpkf hnu
kixa djx uksr ogxty dxj clda ukrs
xgiy diwbvn vphdbg qnelyz tqptqig lenyzq ecsswj
alx awj fpasmmg zukuh qaanvb too nvskuk too gnria
suo suo brw nazq suo dqv
tan uxiz oqa xyezcd lsaicjr bosiak rmmh
bidpomf dimcj qekero wbrc lewt kmgmlao
bciacj eye lxfpef cbdshd dhdsbc qwnhil iuokc
zduefht lrgfjn nclksm wpjpjr hkeqd oprsjcw
chhdr bram swdfjr yikqra xkzsloc otptp agec hhdrc uofljf toppt wpbyrwo
bwlpb nishr knnrysj bvr ftnb iedskch weo
czo hsfp wblh cru kzalun intt
jvob rppz rkwv hgyhrqg
sgo hued jnygge izf ztan kjgpcn fagff jsi ijcxzoi tgqjjp tgqjjp
ltjq zidjy rfmy yevuaa nlhfyg xytdtle wsqvzzx wfflboo nawhv golhf xhsti
bmtzlml xcbsquq vnfsux voep lkss ioim
ntfffh gcncwu mmymn wkwlswa gcncwu iaeyumz
kcgdm rbaau cwsoya pznnnn xzz zbbdlhw zxuelq xzz pjeq
xrmnuct kwvykx khxr ioua xnmtrcu xrnctum ujq imnt ecee
xjsgx fby fby fby ggtpgdm jqvuj qshewki tkml ymsazcq
sdbyhwg kewtrte novhdcp wbuaoh dtytgtx zez whygbds hpg
tjvaqo yrycda yrycda ldbp yrycda
kloi tmsocmx dza sqtxc wgevs zlevs vtm
ftnx drvdm ryjfdgw nerynh cwfjpa mddvr
wsqjyn svg ncw aesn hvuq vybajti aesn bql atxhp ipu
eye romgxj gumuke jwi jrf dtt kcj wmg waw
ptltud oymklv fgnmbc ete apanovb vpt vyospi
clkguhu rbxs lxtnmy ferdx qbmrpg pvojnj zbcffbp
itngp dvtlq fzxp cxrf gbxxqp aafls pfe bpxgxq
nmikrui ddsq srfilr gnuvghu mwnacz nlbdm zcjm uylgev umzu mftz nmikrui
bow jmnxyen bow hvz
lksibxk lefzh lksibxk nkxsi nkxsi pldvhk
osjlzns pihvr zpeu zxjgjb xplykfk xplykfk
hajmfss cardd kaddjw uicfde taue
rgwdjra sgifh ggt mpzx usghkos oob fvzx ghnyxr sblcif
dtu gnihpry kjdpiny xvax itmluk fxvgaap bei xuq wzcy rhb hailtgo
wwob ueldq ueldq glxc umimwv onu dxhmhis ebottoa lnysfiu
zfbyi eyq etaj idpbkf
qshcfjb ozzqigv raztm ymcv sgivwoc kightf dcaglk udah fdm
jmxr jrcnck enffwfl jycc jmxr cylnigo enffwfl
bkslhv tykqw tykqw mbeqrbt tykqw
vogf nhqltpt nhqltpt vogf kpc
ryayz ddktu rfhkmx xok xninjcm ijcrw fxu
cmezfj zaamjrs whlcuoo mug lcaqhkb ymkdci qexa onhgk pgy
hcrcok qri fki wbiog ptj pmgtdt
xsl mpfxwbz bmzxpwf hrysu bmfxwzp xfja
gybzho ktokndy rzkbr jcnp ahicq weccg pgrodkt che vaglyn omhmpo
vdv bngjox srs faymg xrmf enseu aygfm gvsd
nuzi xodkbag eevovl bfjuv nuzi xmejqn
kcswegw bpa dgil insf insf
stg tklrut poi knurfpf
pcs dgirfie yep lvkfk ype hntt athvad clfybsq ofjhegj epy qwawns
wjtpgd wjtpgd vxnapp mwyfsm vxnapp rvcswcs jksa
ckzslrg wdzeimw cqhp nfgk zgukvd yyt tra erkx wdzeimw
hsww avl vkmzej hsww
mum oczj jfew rag zjoc wjfe yqynjqt cbkcsgo mri
vjhfqdi vjhfqdi npfa pzdmy utlyw bwvbfm nqdv iiap ygpky bwvbfm eocya
ewkqi ckb yviuro mqz vtrdam yzkqzv ppbj lhmj blkafo juxvwke lvewc
ljrewgx sutnb hfsavbu jofr ltml mjzkzz nmjii sutnb eonegt
cxzv nepyrb wmejdo vwqi aeqys
sbx fmne obzdz rdnfb gmb sbx ykcae hbzom ncwju rhpiao obzdz
lsgfun cbmfjwk fya ktzxbwt
ica bpsk bwjwkp obloxdx uwoqdo bnnhjuc tlsx qtaacp bdooxxl jamy ade
psus wmtkg ikvfx fkvesj upqlhfs ueje nyt abxvo
adlbl hzskbrp ooht nps
wtcgnvy nvqtvx tvgnycw ntvcygw kkxcp zyjmpbh
xfxww xsddqe ewvmgw qxqwy wpabtz ppe zuiw zubcc onaqii
kkaeec xhcakul wrrvi dtlqfy ahqdilw bnt gwimw espaivx nam yfv
lxz jtc nkwgz nbgsao olsck emtltf xidwcvm lcjxq
eav dzh hnbp hnbp yeg
egaq yvat kavsige csar zsi sptai
pofijc ibdnoe caoazp azlnjk dqp chik lowll iby gpvjv ohm
ors lexk zcneaj rmesx jman uqkb kvkq zfufmn
qgsyzxd hlm juerg ortfzw hxjzg
fxwy lcoc fyxw pzhynp yfn zdzrz
datmws ckwghgr gbtyf lqrpfgl mbgpd dyjilr fgybt hxpg
mxw facxdnu wxm urltwtf qfo wtpwrj
esa srypq jauwv dpm wdgqq hrke icvudq bdmubb ellhfjh ttpjjd gxmg
gvwvqwj cbzzuvj eckube adqinpa djutlue wcpw vrt ucqwu ekruwsn
fhj fst zmtb yhwk dxlbozs fcb vjvuxin dxlbozs rixdvu
egfoep cvq icd prwj icyg
aojaa ezmcuf udreyi bja cyrtpl wjl
gjeka bsbufp tbqqq vbmnqg sfqtgac odhq xzsxt
yse gujdr ugjdr sye
tax hntqw phf eixjwfh qkylnu nkyuql ugsuj
wyh egum zizhfc jrq htbyug lop dsu
exh vfdoosj ajrna jbiaz lqsgvks xklqgjv abtmdud
juqc ormfa sab tucsfln detqfo feg kifsion juqc ovhra
hvcrh oddhme omzmu vmy she xulvfa fecmgi
ayo gspge nkmy yblsj lrsre nkmy pwocjz gdexqqx ovovm
acy sqcz ijl htt yjsi rly vea bck
bniafe yore xnh rkcfd hxfuzw xlr nkzmmcs ekwggiu kgoboi wfuzxh hwfxuz
weq crkeq cccphe dtozviy kzkkdr yku cephcc ctq zbau dewpi
vfla rzpl bnmx uvggon foivrb fval
ziaove lawkpdn ddwl sxj krroj rqmffxv babb
bdw dsifr kuueet hugddwt piz dwb sjixveg kmsoknq
czl feyxf soyvbj tnmpjn kklwi akx nqepntc
nrmhc tkkn jrxgc jrxgc tkkn
ufzn mrhiapi qrme kjlf qrme xpp qrme loyzizz xqm coli
qvaoye mysv ydfxr iixrw
dql tqarux fxqfn haoinu lyati xml
kyve obatly dgfjt fjz sqrz xlbst lgwlt zovih aepy otrpl oifid
ymawam afgye lcnpkmv feilfws vonseh rxrdco
tqij kuawg dmova slds imdtb sjsafo ffkzzl pxxenva wuakg efbgx
yrwoaos vpw ijjpua jnbxl sev yvgdxzr mpqa vpe lboh sev
krwdtd uglxtcz mljcgdk lqj fgpfle nuui cqk exr nuu oyn
dwd nwt idhclm vgkh rpubq wybhapp
hskhgpy gzvz jztbr jwv vcx vdjmnjr jrsp
ikml ceuhcng biu zoo gra bnnforx abzan hwsmd lmki tsl yvogo
kqfc younaz azvgfz gesajr tmwxvyb vmcdu dclwh rfjwhic slfym
pbrhjml rsacryg jga qvgks neh fcq qmi mwb juezk mjteeg alkb
pcj ujstl fkrqm eeczrle hbkcvm upbo mrb qrspjt
jbq rrk xjl rgokbnx hor ogg szxqu hysy vqj piorq wtrtrdk
bnq ntvhcrf vrm puer kde xaxkja sfxgjf
pgcicus hqeqkkx xqekqhk qqkxhke
puquxi hmeaehh oxe tasipw qzyg hyvy wcmpwe
hvs fxq wvfy zjepsl dvrfxnc xnvg
xle crcuc qkhnv crcuc oedez bjw pmwq
xzzpiy cjwss jwscs apb bpa
ydjhhf yeltadb lwi cjdcb ovaox xrdm vkxub
zax xza admbc lvpzfeh auxn rwasj
kebx eild nrskdr meja jxczomh gcne)";
std::vector<std::string> lines()
{
std::vector<std::string> result;
boost::split(result, PUZZLE_INPUT, boost::is_any_of("\n"));
return result;
}
std::vector<std::string> words(const std::string &line)
{
std::vector<std::string> result;
boost::split(result, line, boost::is_any_of(" "));
return result;
}
bool is_valid_1(const std::string &line)
{
bool found_duplicate = false;
std::set<std::string> found;
for (const auto &word : words(line))
{
if (!found.insert(word).second)
{
found_duplicate = true;
break;
}
}
return !found_duplicate;
}
bool are_anagrams(const std::string &w1, const std::string &w2)
{
if (w1.size() != w2.size())
return false;
std::string remaining = w2;
for (char ch : w1)
{
auto pos = remaining.find(ch);
if (pos == std::string::npos)
return false;
remaining.erase(pos, 1);
}
return true;
}
bool is_valid_2(const std::string &line)
{
if (!is_valid_1(line))
return false;
auto all_words = words(line);
for (const auto &w1 : all_words)
{
for (const auto &w2 : all_words)
{
if ((w1 != w2)
&& are_anagrams(w1, w2))
{
return false;
}
}
}
return true;
}
int count_valid(bool (*test)(const std::string &))
{
int num_valid = 0;
for (const auto &line : lines())
{
if (test(line))
{
num_valid += 1;
}
}
return num_valid;
}
int main(int /*argc*/, const char */*argv*/[])
{
assert(is_valid_1("aa bb cc dd ee") == true);
assert(is_valid_1("aa bb cc dd aa") == false);
assert(is_valid_1("aa bb cc dd aaa") == true);
assert(is_valid_2("abcde fghij") == true);
assert(is_valid_2("abcde xyz ecdab") == false);
assert(is_valid_2("a ab abc abd abf abj") == true);
assert(is_valid_2("iiii oiii ooii oooi oooo") == true);
assert(is_valid_2("oiii ioii iioi iiio") == false);
std::cout << "Answer #1: " << count_valid(&is_valid_1) << std::endl;
std::cout << "Answer #1: " << count_valid(&is_valid_2) << std::endl;
return 0;
} |
Formal statement is: lemma locally_path_connected_connected_component: "locally path_connected S \<Longrightarrow> locally path_connected (connected_component_set S x)" Informal statement is: If $S$ is locally path-connected, then the connected component of $S$ containing $x$ is also locally path-connected. |
\documentclass{tufte-handout}
\usepackage{amsmath,stmaryrd,amssymb,amsthm,url,booktabs,hyperref,enumerate}
\usepackage{tikz}
% \usepackage{enumitem} \setlist[itemize]{noitemsep, topsep=0pt}
\makeatletter
% Paragraph indentation and separation for normal text
\renewcommand{\@tufte@reset@par}{%
\setlength{\RaggedRightParindent}{0pc}% 1.0pc
\setlength{\JustifyingParindent}{0pc}% 1.0pc
\setlength{\parindent}{0pc}% 1pc
\setlength{\parskip}{0pt}%
}
\@tufte@reset@par
\makeatother
\ifpdf
\usepackage[all,pdf]{xy} %% NB this MUST be loaded last.
\else
\input xy
\xyoption{all}
\xyoption{2cell}
\xyoption{v2}
\fi
\parskip = 10pt
\def\into {\hookrightarrow}
\def\cE {\mathcal{E}}
\def\cC {\mathcal{C}}
\def\cR {\mathcal{R}}
\def\cD {\mathcal{D}}
\def\cP {\mathcal{P}}
\def\cT {\mathcal{T}}
\def\cN {\mathcal{N}}
\def\op {\mathrm{op}}
\def\pt {\mathrm{pt}}
\def\Set {\mathbf{Set}}
\def\Top {\mathbf{Top}}
\def\Ho {\mathbf{hTop}}
\def\slpcTop {\mathbf{slpcTop}}
\def\Cov {\mathbf{Cov}}
\def\Grp {\mathbf{Grp}}
\def\Gpd {\mathbf{Gpd}}
\def\RR{\mathbb{R}}
\def\NN{\mathbb{N}}
\def\ZZ{\mathbb{Z}}
\def\QQ{\mathbb{Q}}
\def\CC{\mathbb{C}}
\def\BB{\mathbb{B}}
\newcommand{\lecturenum}[1]{\marginnote{\color{red}Lecture #1}}
\DeclareMathOperator{\disc}{disc}
\DeclareMathOperator{\codisc}{codisc}
\DeclareMathOperator*{\colim}{colim}
\DeclareMathOperator{\Sh}{Sh}
\DeclareMathOperator{\id}{id}
\DeclareMathOperator{\Sub}{Sub}
\DeclareMathOperator{\Aut}{Aut}
\DeclareMathOperator{\Cont}{Cont}
\DeclareMathOperator{\im}{im}
\DeclareMathOperator{\pr}{pr}
\DeclareMathOperator{\ev}{ev}
\DeclareMathOperator{\Lift}{Lift}
\DeclareMathOperator{\Ad}{Ad}
\theoremstyle{definition}
\newtheorem{prop}{Proposition}
\newtheorem{lemma}{Lemma}
\newtheorem{definition}{Definition}
\newtheorem{example}{Example}
\newtheorem{ex}{Exercise}
% \newtheorem{exercise}{Exercise}
\newtheorem{theorem}{Theorem}
\newtheorem{corollary}{Corollary}
\newtheorem{q}{Question}
\newtheorem*{conj}{Conjecture}
\newtheorem*{rem}{Remark}
\newtheorem*{fact}{Fact}
\title{Algebraic Topology\thanks{This document is released under a CC-By license:
\href{https://creativecommons.org/licenses/by/4.0/}{\texttt{creativecommons.org/licenses/by/4.0/}}.}
}
\author[D.M.~Roberts]{David Michael Roberts}
\date{2019}
\begin{document}
\maketitle
\lecturenum{1} \section{What is it?}
Algebraic topology is the study of maps
\[
\{\text{Spaces}\} \longrightarrow \{\text{Algebraic objects}\},
\]
%
or rather, `well-behaved' such maps. They should also send continuous functions between spaces to
algebraic maps, respecting composition (so: \emph{functors}); they should send spaces built
out of simpler spaces to algebraic objects built out of simpler components, in a compatible way,
etc.
Here, `Spaces' roughly means topological spaces up to deformation (usually homotopy, but not
always). Such equivalence classes are called \emph{homotopy types}. `Algebraic objects' means
(abelian) groups, rings, modules, or even chain complexes of these \marginnote{a chain complex is a certain sequence of maps $\cdots \to V_0 \to V_1 \to V_2 \to
\cdots$}.
\begin{example}
How can we tell if the sphere $S^2$ and the torus $S^1\times S^1$ can or
cannot be deformed into each other? How would you prove it cannot be done?
\end{example}
\begin{example}
For a positive example, we \emph{can} squash $\RR^3 \setminus \{0\} \to S^2 \into
\RR^3 \setminus \{0\} $, sending $x\mapsto \frac{x}{|x|}$. This map continuously
deforms to the identity map. So dimension not necessarily preserved.
\end{example}
\begin{example}
Can we have $S^1 \sim S^2$?
\end{example}
\noindent We first need to understand how spaces are built
\section{Topological spaces}
Recall\ldots\marginnote{From Topology and Analysis III}
\begin{definition}
A \emph{topology} on a set $X$ is a collection $\cT$ of subsets of $X$
such that
\begin{enumerate}
\item $\emptyset,X\in\cT$
\item If $U,V\in \cT$ then $U\cap V\in \cT$
\item If $\{U_\alpha\}_{\alpha\in I}$ is an arbitrary family of sets in $\cT$, then $\bigcup_{\alpha\in I} U_\alpha \in \cT$\marginnote{$I$ here is an indexing set}
\end{enumerate}
If $U\in \cT$ we say $U$ is \emph{open}. A \emph{topological space} is a set $X$
eqipped with a topology $\cT$.
\end{definition}
\begin{example}
Take the set of real numbers, the \emph{Euclidean (`usual') topology} is
defined by saying a set is open iff it is a union of open intervals $(a,b)$ (including the
union of no sets ie $\emptyset$).\\
The \emph{discrete topology} on a set $X$ is defined by
taking every $\cT$ to consist of all subsets. The \emph{indiscrete topology} is defined by
taking $\cT$ to consist of just $\emptyset$ and $X$.
\end{example}
This definition is concise, but not always the best way to define a topology. We will also
use \emph{neighbourhoods}
\begin{definition}
A set $N\subseteq X$ is a \emph{neighbourhood}\marginnote{`nhd' is a good
abbreviation} (in a given topology $\cT$) of a point $x\in X$ if there is an open
set $U\subseteq N$ with $x\in U$.
\end{definition}
\begin{example}
Take $\RR$ with the Euclidean topology. $(-1,1)$, $[-1,1]$, $[-1,1)$ are all
neighbourhoods of every $-1<x<1$, but $[0,1)$ is not a neighbourhood of $0$. More
complicated: $[0,1] \cup \{2\}\cup [5,6]$ is a nhd of all $0<x<1$ and $5<x<6$.
\end{example}
\begin{example}
Consider a metric space $(X,d)$. The \emph{metric topology} is defined by saying a
subset $U\subseteq X$ is open iff for every $x\in U$ there is some $\varepsilon_x >
0$ with the open ball $B(x,\varepsilon_x) \subseteq U$. Open balls around $x$ are
neighbouhoods of $x$, as are closed balls.
\end{example}
Here is a more concrete approach that allows concise definitions of topologies:
\begin{definition}
A \emph{neighbourhood base} $\cN$ on a set $X$ is a family
$\{\cN(x)\}_{x\in X}$ where each $\cN(x)$ is a nonempty collection of subsets of $X$,
satisfying the following, for all $x\in X$:
\begin{enumerate}
\item For all $N\in \cN(x)$, $x\in N$;
\item For all $N_1,N_2 \in \cN(x)$, there is some $N\in \cN(x)$ with $N\subseteq N_1
\cap N_2$;
\item For all $N\in \cN(x)$ there is a subset $U\subseteq N$ such that $x\in U$ and for
all $y\in U$, there is some $V \in \cN(y)$ such that $V\subseteq U$.
\end{enumerate}
We say the sets in $\cN(x)$ are \emph{basic neighbourhoods} of $x$.
\end{definition}
As an example: given a topological space $(X,\cT)$ defining $\cN(x)$ to consist of all nhds
of $x$ gives a nhd base. Similarly, defining $\cN'(x)$ to consist of all open sets
containing $x$ defines a nhd base.
Given a neighbourhood base $\cN$ on a set $X$, define a subset $U\subseteq X$ to be
\emph{$\cN$-open} iff for all $x\in U$, there is an $N\in \cN(x)$ with $N\subseteq U$.
\begin{prop}
The $\cN$-open sets define a topology on $X$.
\end{prop}
\begin{proof}
We verify the axioms for a topology on $X$.
\begin{enumerate}
\item The condition that $\emptyset$ is $\cN$-open is vacuously true. And since $\cN(x)$ is
not empty, there is a basic nhd around every point, so $X$ is $\cN$-open.
\item Given $U,V$ both $\cN$-open, we want to show $U\cap V$ is $\cN$-open. So take $x\in
U\cap V$. We know there is $N_U,N_V \in \cN(x)$ with $N_U \subseteq U$ and $N_V \subseteq
V$, and also that $x\in N_U \cap N_V$, since it is in each of them. Thus there is some $N\in
\cN(x)$ with $N \subseteq N_U \cap N_V \subseteq U\cap V$, and this is true for all $x\in
U\cap V$. Hence $U\cap V$ is $\cN$-open.
\item Given a family $U_\alpha$, $\alpha\in I$, with each $U_\alpha$ $\cN$-open, we want to
show $U := \bigcup_{\alpha\in I}U_\alpha$ is $\cN$-open. Take $x\in U$, so there is some
$\alpha_0$ with $x\in U_{\alpha_0}$. But this set in $\cN$-open, so there is some nhd $N$ of
$x$ with $N\subseteq U_{\alpha_0} \subseteq U$, and this is true for all $x\in U$. So $U$ is
$\cN$-open. \qedhere
\end{enumerate}
\end{proof}
We call the topology from this proposition the topology generated by $\cN$. Neighbourhoods
in this topology are sets that contain a basic neighbourhood: $V$ is a neighbourhood of $x$
if there is some $N\in \cN(x)$ with $N\subseteq V$.
Given a neighbourhood base $\cN$ on $X$, we can identify the \emph{closure} of a set
$S \subset X$ as the collection of points $x\in X$ such that for all $N\in \cN(x)$,
$\exists s\in N\cap S$.
\begin{example}
Given a metric space $(X,d)$ the open balls form a nhd base on $X$ and the
topology they generate is the metric topology.
\end{example}
Hence many definitions you are familiar with from metric spaces work for topological spaces, if
they can be phrased in terms of basic nhds. In particular, continuity!
\begin{definition}
Let $\cN_X$ and $\cN_Y$ be neighbourhood bases on sets $X$ and $Y$
respectively. A function $f\colon X\to Y$ is \emph{continuous} if for every $x\in X$ and
$N\in \cN_Y(f(x))$, the set $f^{-1}(N)$ contains a basic nhd of $x$.
\end{definition}
This is a big generalisation of the $\varepsilon$-$\delta$ definition of continuity.
\begin{ex}
Show\marginnote{Recall a function is continuous for topologies if
$f^{-1}(U)$ is open for all open $U$.} that if $f\colon (X,\cN_X)\to (Y,\cN_Y)$ is
continuous as just defined, it is continuous for the topologies generated on $X$ and $Y$ by
these nhd bases.
\end{ex}
As a sanity check,\marginnote{You can check every function \emph{to} an indiscrete space
is continuous, as is every function \emph{on} a discrete space} the identity function
$\id_X$ on a space $X$ is indeed continuous.
\begin{definition}
A continuous function $f\colon X\to Y$ is a \emph{homeomorphism} if there is a continuous
function $g\colon Y\to X$ with $g\circ f = \id_X$ and $g\circ f = \id_Y$.
We then call $X$ and $Y$ \emph{homeomorphic}\marginnote{or just isomorphic, if I'm being lazy}
if there is a homeomorphism between them.
\end{definition}
Now we need to show how to build new spaces, and continuous maps relating them to the
original spaces.
\begin{definition}
Let $X$ be a set, $(Y_\alpha,\cN_\alpha)$, $\alpha \in I$ a family of
sets with nhd bases (not necessarily all unique), and $f_\alpha\colon X\to Y_\alpha$ a
family of functions. The \emph{initial topology} on $X$ is generated by the following nhd
base: a subset of $X$ is a basic nhd of $x$ iff\marginnote{Exercise: verify this is a nhd base!}
it is of the form $f_{\alpha_1}^{-1}(N_1) \cap \ldots \cap f_{\alpha_k}^{-1}(N_k)$ for
some $\alpha_1,\ldots,\alpha_k$ and $N_i \in \cN_{\alpha_i}(f_{\alpha_i}(x))$.
\end{definition}
This generalises the product topology, which is the case that $X = Y_1 \times Y_2$, and
$f_i\colon X\to Y_i$ is the projection $f_i(y_1,y_2) = y_i$, where $i=1,2$. But this
\emph{also} gives the subspace topology: take $f\colon X\into Y$ to be injective and define
the initial topology on $X$.
\begin{lemma}
Giving $X$ the initial topology, all the functions $f_\alpha\colon X\to
Y_\alpha$ are continuous. Moreover, a function $k\colon Z\to X$ is continuous iff
$f_\alpha\circ k\colon Z\to Y_\alpha$ is continuous for every $\alpha$.
\end{lemma}
\begin{example}\lecturenum{2}
If the set of functions consists of a single \emph{injective} map, namely $\iota\colon X\into Y$, with
$Y$ a space, then the initial topology is the subspace topology: basic nhds of $x$ correspond
to sets $\iota^{-1}(N)$ (basically $N\cap X$) for $N$ a basic nhd of $\iota(x)$.
\end{example}
\begin{example}
If however we have a constant function $c_{y_0}\colon X\to Y$, sending $x\mapsto y_0 \in Y$ for all $x$, then
for every nhd $N$ of $y_0$, $c_{y_0}^{-1}(N) = X$. So the only nhd of every $x\in X$ is $X$ itself.
Thus the initial topology is indiscrete in this case.
\end{example}
In general, given the family of functions $f_\alpha\colon X\to Y_\alpha$, there is a function
$(f_\alpha)\colon X\to \prod_\alpha Y_\alpha$. If we give $\prod_\alpha Y_\alpha$ the product
topology, then the initial topology on $X$ from the family of maps is the same as the initial
topology from the map $(f_\alpha)$ to the product space. So if this latter map is injective,
$X$ inherits the subspace topology from the product topology. This is the major use-case we
will come across for the initial topology.
\begin{example}
A submanifold $M\subseteq \RR^n$ gets its topology from the coordinate functions
$M\into \RR^n \xrightarrow{x_i} \RR$, and a map to $M$ is continuous iff the composite with
the maps to each factor of $\RR^n$ are continuous.
\end{example}
\begin{ex}
Given a set $X$, a space $Y$ and a function $f\colon X\to Y$, if two points $x_1,x_2$
satisfy $f(x_1)=f(x_2)$, show that a subset $V\subseteq X$ is a nhd of $x_1$ iff it is a nhd
of $x_2$, in the initial topology.
\end{ex}
The following will be even more important for us, and will be new to most.
\begin{definition}
Let $X$ be a set, $(Z_\beta,\cN_\beta)$, $\beta \in J$ a family of topological spaces
(not necessarily all unique), and $g_\beta\colon Z_\beta\to X$ a family of
functions (note the other direction!). The \emph{final topology}\marginnote{this really is
easier to describe using open sets, rather than nhds} on $X$ has open sets as
following: $U\subset X$ is open iff for all $\beta\in J$, $g_\beta^{-1}(U)$ is open in
$Z_\beta$.
\end{definition}
\begin{lemma}
Giving $X$ the final topology, all the functions $g_\beta\colon Z_\beta\to X$
are continuous. Moreover a function $h\colon X\to W$ is continuous for the final topology on
$X$ iff $h\circ g_\beta\colon Z_\beta\to W$ is continous for every $\beta\in J$.
\end{lemma}
We will give two special cases of this, and we will see them often.
\begin{example}
Let $Z$ be a topological space, and let $\sim$ be an equivalence
relation on $Z$, and define $X = Z/\!\sim$ to be the quotient by this relation. There is a
function $ \pi\colon Z\to X$ sending $y\mapsto [y]$. The final topology on $X$ has as open
sets those $U\subseteq X$ such that $\pi^{-1}(U)$ is open in $Z$.
\end{example}
For instance, we can give $S^2$ the initial topology for the maps $x_i\colon S^2 \to \RR^3
\xrightarrow{\pr_i} \RR$ (this is the usual topology on $S^2$), and then define an equivalence relation on
$S^2$ by $x\sim y$ iff $x = - y$. The quotient is $\mathbb{RP}^2$, the real projective
plane, and we give it the final topology coming from $S^2\to \mathbb{RP}^2$. This is the
topology it carries as a manifold. Incidentally, $S^2$ is an example of a \emph{covering
space} of $\mathbb{RP}^2$, the study of which will occupy the first section of the course.
Recall the definition of disjoint union of sets: given $Z_\beta$,
$\beta\in J$, a family of sets, we have $\mathrm{in}_\gamma \colon Z_\gamma \into
\bigsqcup_{\beta} Z_\beta$ with $Z_\beta \cap Z_\gamma = \emptyset$ for $\beta\neq \gamma$.
If $Z_\beta$ are spaces, then we give $\bigsqcup_{\beta} Z_\beta$ the final topology for
the maps $\mathrm{in}_\gamma$. This is \emph{disjoint union} or \emph{sum}
topology,\marginnote{an important fact is that the map
$\bigsqcup_\beta X\times Z_\beta \to X\times \bigsqcup_\beta Z_\beta$
is a homeomorphism (exercise!)} and $\bigsqcup_{\beta} Z_\beta$ is sometimes called the
\emph{topological sum}. A point in $\bigsqcup_{\beta} Z_\beta$ can be described by a pair
$(\beta,z)$, where $z \in Z_\beta$.
\begin{ex}
Given continuous functions $h_\beta\colon Z_\beta \to W$, there is a unique continuous function $h =
\langle h_\beta \rangle \colon \bigsqcup_\beta Z_\beta\to W$ with $h_\beta = h\circ
\mathrm{in}_\beta$, or in other words this diagram commutes:
\[
\xymatrix{
Z_\gamma \ar[r]^{\mathrm{in}_\gamma} \ar[dr]_{h_\gamma} & \bigsqcup_\beta
Z_\beta \ar[d]^h \\ & W
}
\]
\end{ex}
\begin{lemma}
The final topology on $X$ for $g_\beta\colon Z_\beta \to X$ agrees with the
final topology on $X$ for $g = \langle g_\beta \rangle\colon \bigsqcup_\beta Z_\beta \to X$,
using the sum topology.
\end{lemma}
\begin{proof}
We have that $U\subseteq X$ is open iff $\forall \beta$ $g_\beta^{-1}(U)$ is
open iff $\forall \beta$, $(g\circ \mathrm{in}_\beta)^{-1}(U) =
\mathrm{in}_\beta^{-1}\left(g^{-1}(U)\right)$ is open iff $g^{-1}(U)$ is open in the sum
topology.
\end{proof}
The idea behind the final topology, when $g_\beta\colon Z_\beta \to X$ are jointly
surjective,\marginnote{%
this means $\forall x\in X$, $\exists \beta, x\in Z_\beta$ with
$g_\beta(z) = x$}
is that we can put an equivalence relation on $\bigsqcup_\beta Z_\beta$
with $(\beta_1,z_1)\sim (\beta_2,z_2)$ iff $g_{\beta_1}(z_1) = g_{\beta_2}(z_2)\in X$. As a
set, $X$ is the set of equivalence classes under this relation, so you can think of it as
gluing together the \emph{underlying sets} of the spaces $Z_\beta$. The final topology on $X$ is
then the only sensible topology to described the space we get by gluing together the
\emph{spaces} $Z_\beta$.
\begin{ex}
Given an open cover $\{U_\alpha\}$ of a space $X$, then $X$ carries the final topology for
the inclusion maps $U_\alpha \into X$, or equivalently for the map
$\bigsqcup_\alpha U_\alpha\to X$.
\end{ex}
\begin{example}
An arbitrary manifold $M$ has the final topology arising from any choice of atlas.
\end{example}
\begin{ex}\label{ex:closed_cover_gluing_lemma}
Given a \emph{finite} closed cover $\{V_i\}_{i=1}^n$ of $X$, then $X$ carries the final
topology for $\bigsqcup_{i=1}^n V_i \to X$.
\end{ex}
\begin{example}\label{example:interval_final_topology}
Any closed interval $[a,b]\subset \RR$ with the subspace topology has the final topology
arising from a collection of subintervals $[a,t_1]$, $[t_1,t_2]$,\ldots,$[t_k,b]$, each
with the subspace topology from $\RR$.
\end{example}
These exercises give us what is sometimes known as the \emph{gluing lemma}:
\begin{lemma}\label{lemma:gluing_lemma}
Consider a space $X$ and an arbitrary open cover $\{U_\alpha\}_{\alpha\in I}$
(respectively a finite closed cover $\{V_i\}_{i=1}^n$) and suppose $Y$ is some other
topological space. Then if a function $f\colon X\to Y$ is continuous when restricted to each
$U_\alpha$ (resp.\ to each $V_i$) then $f$ is continuous.
\end{lemma}
Later we'll see spaces that are built up by gluing together lots
of `simple' spaces, like disks $D^n := \{x\in \RR^n\mod |x|\leq 1\}$ (with the subspace
topology from $\RR^n$). But what does `simple' here mean? Roughly, ``shrinkable to a
point''.
\section{Homotopy}
``Shrinkable'' implies a kind of continuous process in time. Consider the function $I\times D^n \to D^n$. Consider the map
\begin{align*}
H\colon I \times D^n & \to D^n\\
(t,\mathbf{x}) & \mapsto (1-t)\mathbf{x}
\end{align*}
Note that this gives maps $H_0\colon D^n\to D^n$ (the identity map) and $H_1$ (constant at $0$).
The function $H$ is continuous!
How should we see this?
The topology on $D^n$ is the subspace topology $D^n \subset \RR^n$,\marginnote{And $I\subset \RR$ has subspace topology} and $\RR^n$ has the product topology.
so the topology on $D^n$ is also the final topology for the coordinate functions
$x_i\colon D^n \to \RR^n \to \RR$.
So $H\colon I\times D^n \to D^n$ is continuous iff
\[
\xymatrix@R=0.5pc{
I\times D^n \ar[r]^{\id\times x_i} & I\times \RR \ar[r]& \RR\times\RR \ar[r]& \RR\\
(t,\mathbf{x}) \ar@{|->}[rr] && (t,x_i) \ar@{|->}[r] & tx_i
}
\]
But $I\times D^n \to \RR \times \RR$ is continuous by definition of final topology, and the following result:
\begin{ex}
If $f\colon X\to W$ and $g\colon Y\to Z$ are continuous, then so is $f\times g\colon X\times Y\to W\times Z$.
If both $X$ and $Y$ have at least one point each, then the reverse implication also holds.
\end{ex}
So if we can prove that multiplication $\RR\times \RR \to \RR$ is continuous, then $H$ is continuous.
But the standard topology on $\RR$ comes from the metric space structure, so can use sequential criterion for continuity.
Take $(a_n,b_n)\to (a,b)$ in $\RR\times \RR$, then:
\begin{align*}
|a_nb_n - ab| & = |a_nb_n -ab_n + ab_n - ab| \\
& \leq |a_n - a|\,|b_n| + |a|\,|b_n - b| \\
& \leq |a_n-a| \sup|b_n| + |a| \, |b_n - b|\qquad\text{(as $(b_n)$ converges, it is bounded)} \\
& \to 0+0
\end{align*}
Hence $H$ is continuous.
\begin{definition}
A space $X$ is \emph{contractible}\marginnote{or, \emph{contractible to $x_0\in X$}} if there is a point $x_0\in X$ and a continuous function $H\colon I\times X\to X$ such that $H(0,x) = x$ and $H(1,x) = x_0$ for all $x\in X$.
Such a function is called a \emph{contraction}.
\end{definition}
We have shown $D^n$ is contractible.
\begin{ex}
$\RR$ is contractible. An arbitrary product of contractible spaces is contractible.
\end{ex}
\begin{example}
Consider what it would mean if a discrete space $S$ were contractible: there would be an element $*\in S$ and a continuous function $h\colon I\times S \to S$ such that $h(0,s) = s$ and $h(1,s) = *$.
Restricting $h$ to $I\times \{s\}$ for some given $s$, we get a continuous function $I \into I\times S \to S$, whose range includes $*$ and $s$.
Since all functions with discrete domain are continuous, let us compose with the continuous function $\chi_{\{*\}}\colon S\to \RR$ that sends $*\mapsto 1$ and $s\mapsto 0$ for all $s\neq *$.
So we have a continuous function $\widetilde{h}\colon I\to \RR$ with $\widetilde{h}(0)=0$ and range contained in $\{0,1\}$.
By the intermediate value theorem, we must have $\widetilde{h}(1) = \chi_{\{*\}}(h(1,s))= 0$, so that $h(1,s) = *$, and hence $s=*$ for all $s\in S$.
Thus $S$ has exactly one element.
\end{example}
\begin{q}
If $X$ is contractible, does the choice of point $x_0\in X$ matter? Is $X$ also contractible
to $x\in X$ for $x\neq x_0$?
\end{q}
The interval can only map continuously to a discrete space if it is constant at some
element, or equivalently, its image consists of a single point, and this property is
important enough to have a name.
\begin{definition}\label{def:connected}
A space $X$ is \emph{connected}\marginnote{If you know the `usual' definition, this is
equivalent to it} if every continuous map to a discrete space has image a single point.
\end{definition}
So the interval $I$ is an example of a connected space. Even better: if a pair of points $x,y\in X$
have a \emph{path} between them (a map $I\xrightarrow{\gamma} X$ with $\gamma(0) = x$, $\gamma(1)=y$)
then any function $f\colon X\to S$ to a discrete space has $f(x)=f(y)$.
\begin{example}
Every contractible space is connected. This is because in a contractible space $X$, for every point $y$
there is the path $t\mapsto H(t,y)$ joining $y$ to the point $x_0$, so that $f(y)=f(x_0)$ for every map
$X\xrightarrow{f}S$ to discrete $S$.
\end{example}
There are however lots of spaces that are connected but not contractible, but we cannot
yet prove this.
This\lecturenum{3} is our first example of an invariant of spaces,\marginnote{%
Consider $\xymatrix@=1pc{X\ar[r]^\simeq \ar[d] & Z \ar[dl]\\ S}$ with $S$ discrete.
}
namely whether they are connected or not: a connected space $X$ cannot be homeomorphic
to a space $Z$ that is not connected. But, how can we tell non-connected spaces apart?
\begin{definition}
\begin{enumerate}
\item For any space $X$, a subset $Y\subseteq X$ is a \emph{connected component}
of $X$ if $Y$ is connected and for any connected $Y'\subseteq X$ such that $Y\subseteq Y'$,
then $Y= Y'$.
\item Put an equivalence relation on $X$ generated\marginnote{%
Exercise: If $C,D\subseteq X$ are connected, and $\exists x \in C\cap D$, then
$C\cup D$ is connected. Also show: the equivalence classes are the
connected components.}
by $x_1\sim x_2$ iff $x_1$ and $x_2$
are both contained in a connected subset $C\subseteq X$. Then define
$\pi_0(X) = X/\sim$, the \emph{set of connected components}.
\end{enumerate}
\end{definition}
Every connected space $X$ has $\pi_0(X) = *$, but now we can tell apart non-connected
spaces, by comparing their $\pi_0$.\marginnote{Such spaces are called `locally
connected', but we will eventually be
assuming a slightly stronger condition. Be warned: $\mathbb{Q}$ with the Euclidean
topology is \textbf{not} locally connected, nor are many very interesting examples!}
Every space that we will be consider in this
course can be written as $X = \bigsqcup_{\alpha\in\pi_0(X)} X_\alpha$, with $X_\alpha$
connected, and have a continuous function $X\to \pi_0(X)$ where $\pi_0(X)$ has the discrete
topology.
As a result, we need to try to understand \emph{connected} spaces, though we
will still \emph{use} non-connected spaces.
Can we get more out of the idea of contractions? Given $H\colon I\times X\to X$, we have
maps $H_i$ for $i=0,1$, namely $H_0 = \id_X$ and $H_1$ is constant at $x_0$. What if
$H_0$ and $H_1$ were other sorts of continuous maps? \medskip
\begin{example}\label{eg:annulus}
Consider the annulus $A(r,R) := \{x \in \mathbb{R}^2\mid r\leq |x| \leq R\}$, and the function
$H(t,x) = ((1-t)r + tR)x/|x|$.
\end{example}
What if we considered general continuous maps $X\to Y$ instead of just $X\to X$?
\begin{definition}
A \emph{homotopy} is a\marginnote{%
A useful picture is: $\xymatrix{
\{0\}\times X \ar[dr]^f\ar[d]\\
I\times X \ar[r]^H & Y\\
\{1\}\times X \ar[u] \ar[ur]_g
}$
} continuous function $H\colon I \times X\to Y$.
If $f = H(0,-)$ and $g = H(1,-)$, we say $H$ is a \emph{homotopy from $f$ to $g$}, and that $f$ and $g$ are \emph{homotopic}, written $f\sim g$.
\end{definition}
Example \ref{eg:annulus} gives a homotopy between the two `retraction' maps $A(r,R) \to
A(r,R)$, mapping points to the inner and outer circles respectively.
Algebraic topology most of the time considers functions \emph{up to homotopy}, and also
``spaces up to homotopy''.
\begin{definition}
A continuous function $f\colon X\to Y$ is called a \emph{homotopy equivalence} if there is a continuous function $g\colon Y\to X$ such that $g\circ f\sim \id_X$ and $f\circ g\sim \id_Y$. We then say $X$ and $Y$ are \emph{homotopy equivalent}.
\end{definition}
\begin{example}
A contractible space is homotopy equivalent to a one-point space.
\end{example}
You should think of homotopy equivalences as being `kinda like isomorphism', but coarser.
Going back to our original motivation, the maps
\[
\{\text{Spaces}\} \longrightarrow \{\text{Algebraic objects}\}
\]
under consideration should take homotopy equivalent spaces to isomorphic algebraic objects.
To make this more rigorous we will use the language of category theory.
%
Here is a super-important property of homotopies we will use continuously.
\begin{prop}
Given homotopies $H\colon I \times X \to Y$ and $H'\colon I \times X \to Y$ such that $H_1 = H'_0\colon X\to Y$, there is a homotopy $H''$ from $H_0$ to $H_1$, and a homotopy $\widetilde{H}$ from $H_1$ to $H_0$.
\end{prop}
\begin{proof}
We will use Exercise~\ref{ex:closed_cover_gluing_lemma} applied to the closed cover $\{[0,\frac12]\times X, [\frac12,1]\times X\}$ of $I\times X$.
Since $I \simeq [0,\frac12]$ and $I\simeq [\frac12,1]$, $H$ and $H'$ give us maps $[0,\frac12]\times X \simeq I\times X\xrightarrow{H} Y$ and $[0,\frac12]\times X \simeq I\times X\xrightarrow{H'} Y$ respectively. By the assumption on $H_1$ and $H'_0$, we get a well-defined function $H''\colon I\times X\to Y$, which is then continuous by the Exercise. It is a simple check to see it is a homotopy from $H_0$ to $H'_1$. \\
For the second part, let $c\colon I\to I$ be the function $c(t) = 1-t$. Then define $H''$ to be the composite $I\times X \xrightarrow{c\times \id_X} I \times X \xrightarrow{H}Y$, which has the required properties.
\end{proof}
Contractible spaces supply many homotopies.
\begin{lemma}
Every continuous function $f\colon X\to Y$, with $Y$ a contractible space (say to $y_0\in Y$), is homotopic to a function with range contained in $\{y_0\}$.
\end{lemma}
\begin{proof}
Let $H\colon I\times Y \to Y$ be a homotopy witnessing the contractility of $Y$. Then the composite $I\times X \xrightarrow{\id_I \times f} I\times Y \xrightarrow{H} Y$ is a homotopy from $f$ to the the desired function.
\end{proof}
As a corollary, every pair of functions to a contractible space are homotopic.
Since contractible spaces are in some sense trivial, maps to them are in the same sense trivial.
An important intermediate version of this is when we consider only the case where $X$ is discrete, or is even just $\pt$:
\begin{definition}
A space $Y$ is \emph{path-connected}\marginnote{This condition is equivalent to requiring
it for \emph{all} discrete spaces in place of $\pt$ (Exercise!)} if every map $\pt \to Y$ is homotopic
to every other such map.
\end{definition}
Unpacking this, we see this means that for any two points $\pt \to Y$ there is a path
$I\to Y$ connecting them, i.e.\ $H\colon I \simeq I \times \pt \to Y$.
\begin{prop}
A path-connected space is connected
\end{prop}
Let us define $[X,Y] = \{\text{continuous }f\colon X\to Y\}/\text{homotopy}$.
The set of \emph{path components} of $Y$ is then the set $[\pt,Y]$.
% If equipped with the final topology arising from the surjective function $Y\to [\pt,Y]$, we
% denote the resulting topological space by $[\pt,Y]^{top}$.
The space $Y$ is called \emph{path connected} if $[\pt,Y]=*$.
We have been discussing topological spaces and continuous maps, but also implicitly sets
and functions, not necessarily continuous, and passing between these two pictures. In
both cases we have composition that is associative, and identity maps. Later we shall be
using different classes of topological spaces in order to ensure the behaviour we
require will hold.
\begin{definition}
A \emph{category} $\cC$ consists of a collection of \emph{objects} $W,X,Y,Z,\ldots$ and for each pair of objects $X,Y$ a collection of \emph{morphisms}, denoted $\cC(X,Y)$, together with the following data:
\begin{enumerate}[i)]
\item For each pair $f\in \cC(X,Y)$ and $g\in \cC(Y,Z)$, a specified morphism $g\circ f\in \cC(X,Z)$,
\item For every object a specified morphism $\id_X\in\cC(X,X)$,
\end{enumerate}
\noindent
such that:
\begin{enumerate}
\item For every triple $h\in \cC(W,X)$, $f\in \cC(X,Y)$ and $g\in \cC(Y,Z)$ we have $g\circ(f\circ h) = (g\circ f)\circ h$,
\item For every object $X$ and $h\in \cC(W,X)$, $f\in \cC(X,Y)$ we have $\id_X\circ h = h$ and $f\circ \id_X = f$.
\end{enumerate}
For $f\in \cC(X,Y)$ we say $X$ is the \emph{source} of $f$, $Y$ is the \emph{target} of
$f$, and write $X=s(f)$, $Y=t(f)$. We also write $f\colon X\to Y$ or $X\xrightarrow{f}
Y$ to indicate that $f\in \cC(X,Y)$. If $\cC(X,Y)$ is a set\marginnote{Most categories
you will encounter are locally small} for all $X,Y$, then $\cC$ is called \emph{locally
small}, and each $\cC(X,Y)$ is called a \emph{hom-set}.
\end{definition}
Many examples of categories have objects sets carrying extra structure (for instance a
topology) and morphisms that are functions compatible with that structure---but not all
categories. We have seen $\Top$, the category of topological spaces (and continuous
maps) and $\Set$, the category of sets (and functions), and you implicitly already
know\marginnote{Vector spaces, (abelian) groups, manifolds, rings, \ldots}
many other examples.
\begin{example}
The category $\Set_*$ of pointed sets $(X,x)$ ($x\in X$ a specified element) and pointed maps
$(X,x) \to (Y,y)$ (functions $f\colon X\to Y$ with $f(x) = y)$) can be considered as consisting
of algebraic objects of the weakest sort (compare homomorphisms, linear transformations, ring
maps, etc, which preserve distinguised elements).
\end{example}
The whole point of categories is how they relate to each other, an isolated category can
only tell us so much.
\begin{definition}
Given categories $\cC$ and $\cD$, a \emph{functor} from $\cC$ to $\cD$, denoted $F\colon \cC\to \cD$ consists of the data:
\begin{enumerate}[i)]
\item For every object $X$ of $\cD$, a specified object $F(X)$ of $\cD$,
\item For every morphism $f\colon X\to Y$ of $\cC$, a specified morphism $F(f)\colon F(X) \to F(Y)$ of $\cD$
\end{enumerate}
\noindent
such that for every object $X$ of $\cC$, $F(\id_X)=\id_{F(X)}$, and for every pair $f\colon X\to Y$ and $g\colon Y\to Z$ of morphisms of $\cC$, $F(g\circ f) = F(g)\circ F(f)$. This latter property is called `functoriality'. For locally small categories, the assignment on morphisms gives a function $\cC(X,Y) \to \cD(F(X),F(Y))$.\marginnote{We will use this notation even without making that assumption}
\end{definition}
We have already see at least four examples of functors:
\begin{itemize}
\item The underlying set functor $U\colon \Top \to \Set$
\item The discrete topology functor $\mathrm{disc}\colon \Set \to \Top$\marginnote{the indiscrete topology also gives rise to a functor $\Set \to \Top$, but we won't be using it}
\item The set of connected components functor $\pi_0\colon \Top \to \Set$
\end{itemize}
\noindent
although we haven't yet seen why $\pi_0$ is a functor. We can compose functors in the
obvious way, so get functors $\mathrm{disc}U\colon\Top\to \Top$ and
$\mathrm{disc}\pi_0\colon\Top\to\Top$, for instance.
Here is a trivial-seeming example (aside from the identity functor).
Let $\cC$ be a category, and $\cD$ a \emph{subcategory}: a collection of some of the
objects of $\cC$ and some of the morphisms of $\cC$ that form a category by themselves.
Then the inclusion of the objects and the morphisms forms a functor $\cD\into \cC$, the
\emph{subcategory inclusion}. An important special case of this is when for every $X$
and $Y$ that are objects of $\cD$, every $\cD(X,Y) = \cC(X,Y)$; then $\cD$ is call a
\emph{full} subcategory. More generally we can consider a functor that is injective on
objects and morphisms to define a subcategory.
\begin{example}
The\marginnote{we have used and will use this result without comment} functor
$\mathrm{disc}\colon \Set \to \Top$ makes $\Set$ a full subcategory of $\Top$.
\end{example}
We will be later restricting attention to certain full subcategories of $\Top$.
\begin{lemma}\label{lemma:image_of_connected}
Let $X$ be a connected space, and let $f\colon X\to Y$ be a continuous function.
Then $\im(f) \subset Y$ is connected.
\end{lemma}
\begin{proof}
Let $S$ be a discrete space and let $g\colon \im(f)\to S$ be a continuous function.
Then the composite $X\to \im(f) \to S$ has image $\{s\}\subseteq S$, hence $\im(g)=\{s\}$
and so $\im(f)$ is connected.
\end{proof}
\begin{prop}
The assignment $X\mapsto \pi_0(X)$ is a functor $\Top \to \Set$.
\end{prop}
\begin{proof}
We need to show there is an assignment
$(f\colon X\to Y)\mapsto (\pi_0(f)\colon \pi_0(X) \to \pi_0(Y))$,
for an arbitrary continuous function $f$.
Fix $f\colon X\to Y$ and let $\alpha\in \pi_0(X)$. Then this corresponds to a connected
component $X_\alpha \subseteq X$, and we know $f\big|_{X_\alpha}$ has connected image.
Thus this image is contained inside a single connected component of $Y$, and we define
$\pi_0(f)(\alpha)$ to be the corresponding element of $\pi_0(Y)$.
Given another map $g\colon Y\to Z$, and the corresponding function
$\pi_0(g)\colon \pi_0(Y)\to\pi_0(Z)$, one can check that $\pi_0(g)\pi_0(f)(\alpha)$, for
$\alpha\in \pi_0(X)$ is the same as $\pi_0(g\circ f)(\alpha)$, and $\pi_0(\id)$ is also
the identity map. This proves that $\pi_0$ is a functor $\Top \to \Set$.
\end{proof}
Here is a bonus second proof for locally connected spaces.
\begin{proof}
We already know we have a map $X\to Y \to \pi_0(Y)$, where we give $\pi_0(Y)$ the discrete
topology. This is continuous since $Y$ is
locally connected, and we want to show this
\emph{descends} along $X\to \pi_0(X)$ to a map $\pi_0(X) \to \pi_0(Y)$.
Given any $\alpha \in \pi_0(X)$, it corresponds to a
connected component $X_\alpha$ of $X$. Look at the restriction of $X\to Y\to\pi_0(Y)$ to
$X_\alpha$: since $X_\alpha$ is connected, its image is exactly one point in $\pi_0(Y)$.
So define $\pi_0(f)(\alpha)=[f(x)]$ for an arbitrary $x\in X_\alpha$.
This defines $\pi_0(f)$. Moreover, the following diagram \emph{commutes}:
\[
\xymatrix{
X\ar[r]^f \ar[d] & Y \ar[d]\\
\pi_0(X) \ar[r]_{\pi_0(f)} & \pi_0(Y)
}
\]
Since the discrete topology on $\pi_0(X)$ is the same as the quotient topology, this is
a map between discrete spaces, hence continuous, but we are thinking of it as a map between
sets.
Now we want to show that $\pi_0(g\circ f) = \pi_0(g)\circ \pi_0(f)$. Given $\alpha \in
\pi_0(X)$, and $x\in X_\alpha$, then $\pi_0(f)(\alpha) = [f(x)]$. To define
$\pi_0(g)\left(\pi_0(f)(\alpha)\right)$, we need to choose a point in the component
$Y_{[f(x)]}$, so take it to be $f(x)$. Then $\pi_0(g)\left(\pi_0(f)(\alpha)\right) =
[g(f(x))]$, but this is just $\pi_0(g\circ f)(\alpha)$.
\end{proof}
\begin{ex}
Show that $[\pt,-]\colon \Top \to \Set$ is a functor.\marginnote{Or more generally,
$[X,-]\colon \Top\to \Set$!}
\end{ex}
Another important example of a category is the \emph{homotopy category} $\Ho$.
\marginnote{Exercise: prove this is a category} The objects are topological spaces, but
$\Ho(X,Y) = [X,Y]$. There is a functor $\Top \to \Ho$, which is the identity on objects,
and sends a map to its homotopy class. Objects are isomorphic in $\Ho$ iff they are
homotopy equivalent.
\begin{prop}
The\lecturenum{4} functor $\pi_0$ descends to a functor $\Ho \to \Set$
\end{prop}
\begin{proof}
We will prove that this is well-defined on morphism on hom-sets, the rest is routine.
For $f,g\colon X\to Y$ to be homotopic via $H\colon I\times X\to Y$, we need to show that for all $\alpha \in \pi_0(X)$, $\pi_0(f)(\alpha) = \pi_0(g)(\alpha)$.
Take $x$ in the connected component $X_\alpha$, then we have a map $I \to I \times X \xrightarrow{H} Y$, namely a path
$f(x) \rightsquigarrow g(x)$.
But $I$ is connected, so the image of the path is connected, so that $f(x)$ and $g(x)$ are in the same connected component. As $x$ was arbitrary $f(X_\alpha)$ and $g(X_\alpha)$ are both contained in the same connected component
of $Y$. Thus $\pi_0(f)(\alpha)=\pi_0(g)(\alpha)$.
\end{proof}
As a result, if $\pi_0(X) \not\simeq \pi_0(Y)$, the spaces $X$ and $Y$ cannot be homotopy equivalent, let alone homeomorphic.
\begin{ex}
Show the functor $[\pt,-]\colon \Top\to \Set$ descends to $\Ho\to\Set$.
\end{ex}
Here is a useful fact about spaces.
\begin{lemma}\label{lemma:pi0s_preserve_coprods}
For all families $X_\beta$, $\beta\in J$, of spaces, we have isomorphisms
\[
\bigsqcup_{\beta\in J} \pi_0(X_\beta) \xrightarrow{\simeq}
\pi_0(\bigsqcup_{\beta\in J} X_\beta)
\quad\text{and}\quad
\bigsqcup_{\beta\in J} [\pt,X_\beta] \xrightarrow{\simeq}
[\pt,\bigsqcup_{\beta\in J} X_\beta],
\]
with inverses induced by the family of maps $\mathrm{in}_\beta$.
That is, $\pi_0$ and $[\pt,-]$ \emph{preserve coproducts}.
\end{lemma}
Recall last time:\marginnote{$\xymatrix{\Top\ar[d] \ar[r]^{\pi_0}&\Set\\ \Ho\ar[ur]_{\pi_0}}$}
we had functors $\pi_0\colon \Top\to \Set$ and (abusing notation) $\pi_0\colon \Ho\to \Set$.
\begin{example}
If $X$ and $Y$ are spaces with $|\pi_0(X)|< |\pi_0(Y)|$, no continuous map $X\to Y$ is
surjective.
\end{example}
Here is an instructive example
\begin{example}
The \emph{topologist's sine curve} is the image $C$ of $[-1,1]\sqcup (0,1]\to \RR^2$ defined by
\[\begin{cases}
y \mapsto (0,y) & y\in [-1,1]\\
x \mapsto (x,\sin(\tfrac{1}{x})) & x\in (0,1]
\end{cases}\]
equipped with the \textbf{subspace topology}. This is a compact metric space, using the
inherited Euclidean metric. Fact: \emph{every} continuous function $f\colon C\to \{0,1\}$ is constant.
If $f(1,\sin(1))=1$, then $f(x,\sin(x))=1$ for every $x\in (0,1]$ (as intervals are connected).
If $f(0,0)=b \in \{0,1\}$, then $f(0,y) = b$ also, for all $y\in [-1,1]$.
The sequence $(\frac{1}{n\pi},0)$ converges to $(0,0)$ in $C$, so
$b = f(0,0) = \lim_{n\to\infty} f(\frac{1}{n\pi},0) = 1$ as $f$ is continuous and we are in a metric space.
Hence $C$ is connected, but there is \emph{no}\marginnote{Exercise: prove this by considering
$\lim_{n\to\infty}\gamma(\frac{1}{n})$} continuous function $\gamma\colon [0,1]\to C$ with
$\gamma(0)=(0,0)$ and $\gamma(1) = (1,\sin(1))$. Since intervals are path connected, we can
show $[\pt,C]=\{0,1\}$, but $\pi_0(C)=*$.
\end{example}
So we have two different invariants here, and there is always a surjective map
$[\pt,X]\to \pi_0(X)$. Moreover, the following square of functions between sets always commutes,
for any map $X\xrightarrow{f}Y$:
\[
\xymatrix{
[\pt,X] \ar[r]^{[\pt,f]} \ar[d] & [\pt,Y]\ar[d]\\
\pi_0(X) \ar[r]_{\pi_0(f)} & \pi_0(Y)
}
\]
This is thus an example of a \emph{natural transformation}.
\begin{definition}
Given functors $F,G\colon \cC \to \cD$, a natural transformation $\alpha\colon F\Rightarrow G$
consists of the data:
\begin{enumerate}[i)]
\item For every object $X$ of $\cC$, a specified morphism
$\alpha_X\colon F(X) \to G(X)$ (the \emph{components} of $\alpha$)
\end{enumerate}
such that for every morphism $f\colon X\to Y$ in $\cC$, the following square commutes:
\[
\xymatrix{
F(X) \ar[r]^{F(f)} \ar[d]_{\alpha_X} & F(Y)\ar[d]^{\alpha_Y}\\
G(X) \ar[r]_{G(f)} & F(Y)
}
\]
A natural transformation is called a \emph{natural isomorphism} if all of its components are
isomorphisms.
\end{definition}
For example, there are natural transformations
$\mathrm{disc}\;U \Rightarrow \id\colon \Top \to \Top$,
with component at $X$ the identity map $\mathrm{disc}(U(X)) \to X$, and
$U\Rightarrow \pi_0\colon \Top \to \Top$, with component $U(X)\to \pi_0(X)$.
We seek conditions that will define a full subcategory of $\Top$ such that the components
$[\pt,X] \to \pi_0(X)$ of the natural transformation $[\pt,-]\Rightarrow \pi_0$
are isomorphisms for all spaces $X$ in the subcategory.
\begin{definition}
A space $X$ is \emph{semilocally path connected} (slpc) if it has a neighbourhood base of sets $N$ such that for any two $x,y\in N$, there is a path in $X$ from $x$ to $y$.
\end{definition}
Note that a space is slpc iff every connected component is slpc, and if $X$ is homeomorphic to $Y$,
and one of them is slpc, then so is the other.
\begin{prop}
If $X$ is a semilocally path connected space, then $[\pt,X]\to \pi_0(X)$ is
an isomorphism.
\end{prop}
\begin{proof}
We are reduced to the case $X$ is connected ($\pi_0(X) = *$) and slpc, by Lemma~\ref{lemma:pi0s_preserve_coprods},
and the fact the case $X=\emptyset$ is trivial.
Since $X$ is connected, take $x\in X$ and define $\chi\colon X\to \{0,1\}$ by
\[
\chi(y) = \begin{cases}
1 & \exists y \rightsquigarrow x \\
0 & \text{otherwise}
\end{cases}
\]
where by $y\rightsquigarrow x$ I mean a path $\gamma\colon I\to X$ with $\gamma(0)=y$ and $\gamma(1)=x$.
We will show $\chi$ is continuous. Note that $\chi$ continuous $\Leftrightarrow$ $p^{-1}(0)$ and $p^{-1}(1)$ open $\Leftrightarrow$ $p^{-1}(1)$ open and closed. But $p^{-1}(1)=:C_x$ is the path component containing $x$.
Take $y\in C_x$ (so $\exists y\rightsquigarrow x$), and $V\ni y$ a path-connected nhd. Given $z\in V$, $\exists z\rightsquigarrow y$. Concatenate these paths to give
$z\rightsquigarrow x$, so that $z\in C_x$. This is true for all $z\in V$, so that $V\subseteq C_x$, hence $C_x$ contains a neighbourhood of each of its points, and so is open.
Conversely, take $y\in \overline{C_x}$, $V\ni y$ a path connected nhd. As $\exists z\in V\cap C_x \subseteq V$,
$\exists z\rightsquigarrow y$. But also have $V\cap C_x \subseteq C_x$, so $\exists z\rightsquigarrow x$. Concatenate paths to get $y\rightsquigarrow x$, so that $y\in C_x$.
This is true for all $y\in \overline{C_x}$, so $\overline{C_x} \subseteq C_x$ and $C_x$ is closed. Hence $\chi$ is continuous.
But $X$ is connected, and $\chi(x) = 1$, so that $\im\chi=\{1\}$, and so $C_x = \chi^{-1}(1) = X$.
Thus $[\pt,X] \to \pi_0(X) = *$ is an isomorphism.
\end{proof}
So we will consider for the rest of this section of the course only slpc spaces, which form a full
subcategory $\slpcTop \hookrightarrow \Top$.
Note that discrete spaces are slpc, so $\Set \hookrightarrow \slpcTop$ is a subcategory.
\begin{example}
Any path-connected space $X$ is slpc, since for any nhd $N$ and points $x,y\in N$, we know there is a
path $I\to X$ between $x$ and $y$.
\end{example}
\begin{ex}
Show that the product of two slpc spaces is slpc, and that any locally convex topological vector space is slpc.
\end{ex}
\begin{example}
Any manifold is slpc, since every point lives in a chart homeomorphic to some $\RR^n$, and $\RR^n$ is path-connected.
\end{example}
Be warned: subspaces of slpc spaces may not be slpc, for instance the topologist's sine curve is a subspace of the contractible $\RR^2$.
\begin{q}
If $X$ is slpc and $q\colon X\to Y$ is a quotient map,\marginnote{so $Y$ has the final topology wrt $q$}
then is $Y$ slpc?
\end{q}
%Here is a condition that can be used to transfer slpc-ness.
%\begin{definition}
%A \emph{local homeomorphism} $X\xrightarrow{p} Y$ is a map of spaces such that for all $x\in X$ there is basis of nhds $U$ of $x$ such that for each such $U$
%$\exists$ $V$ a nhd of $p(x)$ such that $p\big|_U\colon U \xrightarrow{\sim}V$.
%\end{definition}
%Examples include:\marginnote{A trivial example is the inclusion of an open subspace}
% maps $\sqcup U_\alpha \to X$ induced by open an open cover $\{U_\alpha\}$ of $X$,
%the exponential map $\exp\colon \CC \to \CC^\times$, the $n^\text{th}$-power map $U(1) \xrightarrow{(-)^n} U(1)$
%and the projection $S\times X\to X$ for $S$ discrete.
%\begin{lemma}
%If $X\xrightarrow{p}Y$ is a local homeomorphism, then $Y$ lpc implies $X$ is lpc. If $p$ is surjective
%then $X$ lpc implies $Y$ lpc. [[TRUE FOR SLPC??]]
%\end{lemma}
One last technical point
\begin{definition}
A \emph{pointed space} is a pair $(X,x)$ where $X$ is a topological space and $x\in X$.
A pointed map is a pointed map between the underlying pointed sets that is continuous.
These define a category $\Top_*$.
\end{definition}
A \emph{pointed homotopy} of pointed map $I\times X\to Y$, for $(X,x_0)$ and $(Y,y_0)$ pointed spaces, is required
to satisfy $H(t,x_0) =y_0$ for all $t\in I$.
Pointed homotopy classes of pointed map are denoted $[(X,x_0),(Y,y_0)]_*$.
The category $\Ho_*$ is defined analogously to $\Ho$.
We get a functor $\pi_0\colon \Ho_* \to\Set_*$.
\section{Covering spaces}
Sometimes when we are thinking about a particular space $X$, we need to construct other spaces
related to $X$ to study objects of interest.
\begin{example}
Take $X = \CC^\times :=\CC \setminus \{0\}$. Then the function $x\mapsto\sqrt{x}$ is
not well-defined, and if we take a branch cut to give an actual function, it is not continuous on $X$.
Even worse, if have a continuous function $f\colon \CC^\times \to \CC$, we may or may not have $x\mapsto f(\sqrt{x})$ continuous.
However, we \emph{do} get a continuous function if we change the domain somewhat.
The problem is that the function $Z :=\CC^\times \ni z\mapsto z^2 = x \in \CC^\times$ is not injective, so not invertible.
But if we are willing to take the domain to be $Z$, and so pass into $f$ the argument $z$ (which satisfies $z^2 = x$)
then we are now just dealing with a continuous function.
If $f$ is such that $f(z) = f(-z)$ for all $z\in Z$, then we get a well-defined function on $X$.
\end{example}
The properties of the map $z\mapsto z^2$ (at least away from $0$) and others like $z^n$, $\exp(z)$, rational functions away from poles and critical points and so on, lead to the notion of
covering spaces of certain domains in $\CC$. We have a general definition for arbitrary spaces.
%Given a local homeomorphism $X\xrightarrow{p}Y$, the \emph{fibre} $p^{-1}(y)\subset X$ over $y$ has the discrete topology for every $y\in Y$.
%We have no idea how $p^{-1}(\gamma(t))$ varies along a path $\gamma \colon I\to Y$.
%For example, given an arbitrary collection $B(x_\alpha,r_\alpha)\subset \RR^2$ of open balls,
%$\sqcup_\alpha B(x_\alpha,r_\alpha) \to \RR^2$ is a local homeomorphism, but the fibres can
%jump in size arbitrarily.
%We would like fibres `close' to a given $p^{-1}(y)$ to `vary continuously'. For spaces `vary continuously' really means homotopy equivalence.
%But for discrete spaces, homotopy equivalence is isomorphism.
\begin{definition}
A\marginnote{%
\[
\xymatrix{\pi^{-1}(V_x) \ar[r]^-\simeq \ar[d]_{\pi} & V_x \times \pi^{-1}(x)\ar[dl]^{\pr_1}\\V_x}
\]
}
\emph{covering space} $Z\xrightarrow{\pi} X$ of $X$ is a space $Z$ equipped with a map
$\pi$ such that for all $x\in X$ there is a nhd $V_x \ni x$ such that $\pi^{-1}(V_x)
\simeq V_x \times \pi^{-1}(x)$ \emph{over} $V_x$, where
$\pi^{-1}(x)$ has the discrete topology.\marginnote{NB: $V_x \times \pi^{-1}(x)\simeq \bigsqcup_{\pi^{-1}(x)}V_x$ for free}
(We will also call $\pi$ itself a
\emph{covering map}.)
\end{definition}
For a covering space $Z\xrightarrow{\pi}X$ and $x\in X$, let $Z_x :=\pi^{-1}(x)$ denotes the
\emph{fibre} over $x$.
We will also call $X$ the \emph{base space}.
Examples include: $\exp\colon \CC \to \CC^\times$, $S^2 \to \RR\mathbb{P}^2$,
$U(1) \xrightarrow{(-)^n} U(1)$, covers of the join $\infty$ of two circles.
\begin{ex}
Show that if $Z\xrightarrow{\pi} Y$ is a covering map, and $Y\xrightarrow{\rho} X$ is a
covering map with finite fibres (that is: $Y_x$ is finite for all $x\in X$),
then $Z\xrightarrow{\rho\pi} X$ is a covering map.
\end{ex}
\begin{prop}\label{prop:iso_fibres_of_cov_sp}
For a covering space $Z\xrightarrow{\pi}X$, if $\exists x_0 \rightsquigarrow x_1$, then $Z_{x_0} \simeq Z_{x_1}$.
\end{prop}
\lecturenum{5}
\begin{proof}
(First proof of Proposition~\ref{prop:iso_fibres_of_cov_sp}) Take $\gamma \colon I \to
X$, $\gamma(i) = x_i$, and an open cover $\{U_\alpha\}$ of $X$ over which $Z$
trivialises. We thus get an open cover $\gamma^{-1}(U_\alpha)$ of $I$, which has a
finite subcover $U_0,\ldots, U_N$, with $x_0 \in U_0$, $x_1 \in U_N$. The ordering is
chosen\marginnote{we can shrink the cover slightly to make this ordering well-defined,
if need be} so that the path enters $U_i$ before it enters $U_{i+1}$, and $U_i\cap
U_{i+1}$ has at least one point of the path in it.
We have isomorphisms $Z_{U_i} := \pi^{-1}(U_i) \xrightarrow{\phi_i} U_i \times F_i$ with
discrete spaces $F_i$. We have $Z_{x_0} \simeq F_0$, and for all $t\in
\gamma^{-1}(U_0)$, $Z_{\gamma(t)} \simeq F_0$. So for $\gamma(t) \in U_0\cap U_1$, we
have $F_0 \simeq Z_{\gamma(t)} \simeq F_1$. We can then prove by induction on $N$ that
$F_0 \simeq F_1 \simeq \cdots \simeq F_N$.
\end{proof}
So for slpc $X$ and each $\alpha \in \pi_0(X)$, there is associated to $Z\xrightarrow{\pi}X$
an isomorphism class of sets, the \emph{typical fibre} over all $x$ in the connected component
$X_\alpha\subseteq X$.
\textbf{Note:} Fibres can be empty! But we usually don't think about this case too much. For
$X$ pointed (by $x\in X$), we can consider pointed covering spaces $(Z,x) \to (X,x)$.
This is from one perspective just a choice of point $z\in Z_x$. For $X$ connected and slpc,
a pointed covering space has every fibre contain at least one point, namely the image of $z$ under
$Z_x \simeq Z_{x'}$.
We have categories $\Cov_X$ and $\Cov_{(X,x)}$ with objects covering spaces of $X$
(resp.\ pointed covering spaces of $(X,x)$) and maps
\[
\xymatrix{Z_1 \ar[rr] \ar[dr] && Z_2\ar[dl]\\& X}
\]
and analogously in the pointed case. We will study these categories and see what they
tell us about the topology of $X$.
\begin{example}
For $X = \CC \setminus \{p_1,\ldots,p_n\}$, the study of $\Cov_X$ tells us about possible
Riemann surfaces for holomorphic functions with critical values precisely $p_1,\ldots , p_n$.
\end{example}
For slpc and connected $X$, the fact that for a covering space $Z$ of $X$,
there merely \emph{exists} some $Z_{x_0} \simeq Z_{x_1}$
for arbitrary $x_0,x_1\in X$ can be improved. We first need a construction on covering spaces.
\begin{definition}\label{def:pullback_of_cov_sp}
Given a covering space $Z\xrightarrow{\pi} X$ and a map $Y\xrightarrow{f} X$, the \emph{pullback}
of $Z$\marginnote{actually $\pi$ doesn't have to a covering map; this construction works for any pair of maps to a space} is the subspace
\[
f^*Z := Y\times_X Z = \{ (y,z)\in Y\times Z \mid f(y) = \pi(z)\}\subseteq Y\times Z.
\]
It fits in a commutative square
\[
\xymatrix{
f^*Z \ar[d]_{p} \ar[r]^{\pr_2} & Z \ar[d]^\pi \\
Y \ar[r]_f & X
}
\]
\end{definition}
\begin{prop}
In the setting of Definition~\ref{def:pullback_of_cov_sp}:
\begin{enumerate}
\item $f^*Z\to Y$ is a covering space.\marginnote{Of these, only 1.\ relies on having a covering space to start with, 2.\ and 3.\ are general facts about pullbacks, where for 2.\ we replace $\Cov_X$ by the \emph{slice category} $\Top/X$, whose objects are maps to $X$, and morphisms are commuting triangles}
\item $f^*$ is a functor $\Cov_X \to \Cov_Y$.
\item Given $Y_2 \xrightarrow{g} Y_1 \xrightarrow{f} X$ and $Z\xrightarrow{\pi} X$, there is
a canonical isomorphism $(f\circ g)^*Z \simeq g^*f^*Z$ in $\Cov_{Y_2}$.
\end{enumerate}
\end{prop}
\begin{corollary}
The fibre $(f^*Z)_y$ is canonically isomorphic to $Z_{f(y)}$.
\end{corollary}
Now given a path $\gamma\colon I \to X$ and a covering space $Z\xrightarrow{\pi}X$, we can
pull back $Z$ to get a covering space $\gamma^*Z \to I$.
So let us try to understand covering spaces of $I$.
Certainly for discrete $S$, the projection $S\times I \to I$ is a covering space.
\begin{prop}\label{prop:covering_sp_of_interval_triv}
A covering space $Z\xrightarrow{\pi} I$ is isomorphic to the trivial covering space $\pi^{-1}(0) \times I \xrightarrow{\pr_2} I$
in $\Cov_I$.
\end{prop}
We first need a little helper lemma
\begin{lemma}
A covering space of a compact space $X$ trivialises\marginnote{might as well take the nhds to be open, and then consider a finite subcover} over a \emph{finite} cover of $X$ by nhds.
\end{lemma}
\begin{proof}(of Proposition~\ref{prop:covering_sp_of_interval_triv})
We use the lemma to trivialise $Z\to I$ over a finite cover of $I$,
which we can take to be by intervals $[0,t_1]$, $[s_2,t_2]$, \ldots, $[s_N,1]$
for $s_1=0<s_2<t_1<s_3<t_2<\cdots<s_N <t_{N-1} <1=t_N$.
We will proceed by induction on $N$, but this quickly reduces to the case of $N=2$.
So take a cover of $I$ by $[0,t]$ and $[s,1]$, where $\tau\colon Z_0 \times [0,t] \xrightarrow{\simeq}Z_{[0,t]}$
and we are given $\sigma\colon F\times [s,1]\xrightarrow{\simeq} Z_{[s,1]}$.\marginnote{we know abstractly that $F\simeq Z_0$, but this
proof will construct an isomorphism}
By restriction there is the composite map
\[
Z_0\times [s,t] \underset{\simeq}{\xrightarrow{\tau|_{[s,t]}}} Z_{[s,t]}
\underset{\simeq}{\xrightarrow{\sigma^{-1}|_{[s,t]}}} F\times [s,t] \xrightarrow{\pr_1} F.
\]
If we fix $z\in Z_0$, we get a continuous map $\{z\}\times [s,t] \to F$, which is thus
constant, say at $p_z\in F$. The function $z\mapsto p_z = \sigma^{-1}(\tau(z,s))$ is
then a bijection $\phi\colon Z_0 \xrightarrow{\simeq} F$.
We thus get maps $Z_0\times [0,t] \hookrightarrow Z \hookleftarrow F\times [s,1]
\xleftarrow{\phi\times \id} Z_0\times [s,1]$, which by construction agree on $Z_0\times
[s,t]$. There is thus a continuous map $Z_0 \times [0,1] \to Z$. Moreover, you can check
this map is a morphism of $\Cov_I$. There are likewise maps
\[
Z_{[0,t]}\xrightarrow{\simeq} Z_0\times [0,t] \hookrightarrow Z_0\times I
\hookleftarrow Z_0\times [s,1] \xleftarrow{\phi^{-1}\times \id} F\times [s,1]
\xleftarrow{\simeq} Z_{[s,1]}
\]
which agree on $Z_{[s,t]}$, hence a continuous map $Z\to Z_0\times I$.
This map is in $\Cov_I$ and can be checked by pointwise evaluation to be inverse to the
first one.
Hence we have an isomorphism $Z\simeq Z_0\times I$ in $\Cov_I$.
\end{proof}
%The isomorphism the proof constructs is even unqiue if we assume the isomorphism $\tau$ is the identity on $Z_0$.
\begin{corollary}
Given a covering space $Z\xrightarrow{\pi}I$ and a point $z\in Z_0$, there is a unique path
$\eta_z\colon I \to Z$ with $\eta_z(0)=z$ such that $\pi\circ \eta_z = \id$ (i.e.\ $\eta_z$ is a section of $\pi$)..
\end{corollary}
\begin{proof}
We can construct \emph{a} path, given $\tau\colon Z_0 \times I \xrightarrow{\simeq} Z$, by $\eta(t) = \tau(z,t)$. Since $\pi\circ\tau = \pr_2$, this has the required property.
Connectedness of $I$ and discreteness of $Z_0$ implies that given any other path $\eta'\colon I \to Z$ with $\eta'(0) = z$ and $\pi\circ \eta'=\id$, we must have $\tau^{-1}\circ \eta = \tau^{-1}\circ \eta'\colon I\to Z_0\times I$ which implies $\eta'=\eta$.
\end{proof}
And now we have a really important property of covering spaces
\begin{theorem}\label{prop:unique_path_lifting}
Given any covering space $Z\xrightarrow{\pi}X$, path $\gamma\colon I\to X$ and point $z\in Z_{\gamma(0)}$,
there is a unique lift $\widetilde{\gamma_z}\colon I\to Z$\marginnote{a \emph{lift} of a path $\gamma\colon I\to X$ is a path $\widetilde{\gamma}\colon I \to Z$ with $\pi\widetilde{\gamma}=\gamma$} with $\widetilde{\gamma_z}(0)=z$.
\end{theorem}
\begin{proof}
We can pull back $Z$ to get $p\colon \gamma^*Z\to I$. We have unique $\eta_z\colon I\to \gamma^*Z$
so that $\eta_{(0,z)}(0) = (0,z)$. Define $\widetilde{\gamma_z} = \pr_2\circ \eta_{(0,z)}\colon I \to Z$.
This path satisfies $\pi\circ\widetilde{\gamma_z} = \gamma\circ p\circ\eta_{(0,z)} = \gamma$.
Given any other lift $\lambda\colon I\to Z$, we get a second section of $p$ by $t\mapsto (t,\lambda(t))$, which by uniqueness of $\eta_{(0,z)}$ has to be equal to it, so that $\lambda = \widetilde{\gamma_z}$.
\end{proof}
We can then give a second, more explicit proof of Proposition~\ref{prop:iso_fibres_of_cov_sp}.
\begin{corollary}
A path $\gamma\colon I\to X$ defines a bijection
$\gamma_*\colon Z_{\gamma(0)} \xrightarrow{\simeq} Z_{\gamma(1)}$, by
$\gamma_*(z) = \widetilde{\gamma_z}(1)$.
\end{corollary}
\begin{proof}
We only have to start with that $\gamma_*$ is a function $Z_{\gamma(0)} \to
Z_{\gamma(1)}$, but the function $(-\gamma)_*\colon Z_{\gamma(1)} \to Z_{\gamma(0)}$,
where $-\gamma\colon I \to X$ is the path $-\gamma(x) = \gamma(1-x)$, is inverse to
$\gamma_*$. This is because the path $-\widetilde{\gamma_z}$ is a lift of $-\gamma$,
hence $(-\gamma)_*(\gamma_*(z)) = \widetilde{(-\gamma)_{\gamma_*(z)}}(1) =
\widetilde{\gamma_z}(0) = z$. A symmetric argument shows that
$\gamma_*\left((-\gamma)_*(z)\right)=z$ for $z\in Z_{\gamma(1)}$.
\end{proof}
A first observation is that this bijection is invariant\marginnote{consider
$\psi$ as a path in $I$ and see what happens in that case} under reparameterisations of $\gamma$:
given $\psi\colon I\xrightarrow{\simeq} I$ with $\psi(0)=0$ and $\psi(1)=1$, then clearly
$(\gamma\circ \psi)_*=\gamma_*\colon Z_{\gamma(0)} \to Z_{\gamma(1)}$.
Even\lecturenum{6} better, we get a function
\[
\{\text{paths }x_0 \rightsquigarrow x_1\text{ in }X\} \times Z_{x_0} \to Z_{x_1}
\]
If\marginnote{we can take quotient by reparametrisations if desired, in each of these functions} we take $x_0 = x_1 = x$, then this is a map
\[
\{\text{loops }x \rightsquigarrow x\text{ in }X\} \times Z_x \to Z_x
\]
such that each loop $x\rightsquigarrow x$ gives a bijection $Z_x\to Z_x$. So we can think of this instead as
\[
\{\text{loops }x \rightsquigarrow x\text{ in }X\} \to \Aut(Z_x).
\]
Alternatively, if we have a pointed covering space $(Z,z) \to (X,x)$, we have a canonical function
\begin{equation}\label{eq:loops_to_fibre}
\{\text{loops }x \rightsquigarrow x\text{ in }X\} \to Z_x
\end{equation}
\begin{example}
For $Z = S\times X$, $(\gamma)_* = \id_S$ always, and the image of (\ref{eq:loops_to_fibre})
(given some $(s,x)\in Z$) is just a single point. For instance, if $X=I$, we have seen this
will be the case for every covering space.
But for $X=S^1$, $Z=\RR \xrightarrow{\exp} S^1$, and taking
$x=1\in S^1$, $z = 0\in \RR$, then $Z_1 = \exp^{-1}(0) = 2\pi i \ZZ$, then
\[
\{\gamma\colon I\to S^1\mid \gamma(0) = \gamma(1) = 1\} \to 2\pi i \ZZ
\]
is \emph{onto}. The path $\widetilde{\gamma}_n = 2\pi inx$ lifts the path
$\gamma(x) = \exp(2\pi inx)$,
and $\widetilde{\gamma}_n(0) = 0$, $\widetilde{\gamma}_n(1) = 2\pi inx$.
The difference is that $\RR$ is path connected, but $X\times S$ is not, for $|S| > 1$.
\end{example}
In fact, for a covering space $(Z,z)\xrightarrow{\pi} (X,x)$ with $Z$ path connected
and $z'\in Z_x$, there is $\widetilde{\gamma}\colon I\to Z$ with $\widetilde{\gamma}(0)=z$,
$\widetilde{\gamma}(1)=z'$. Since $\widetilde{\gamma}$ lifts $\gamma = \pi\circ \widetilde{\gamma}$,
which satsfies $\gamma(0) = x = \gamma(1)$, the map (\ref{eq:loops_to_fibre}) is \textbf{onto}.
Thus paths constrain the sizes of fibres of connected covering spaces and vice versa.
Notice also that the set of loops is independent of the choice of covering space!
More generally, given points $z_\alpha$ in $Z_x$,\marginnote{that is: a section of $Z\to \pi_0(Z)$} one per path component of $Z$,
\[
\{\text{loops }x \rightsquigarrow x\text{ in }X\}\times \pi_0(Z) \simeq \{\text{loops }x \rightsquigarrow x\text{ in }X\}\times\{z_\alpha\} \to Z_x
\]
is always onto. There are a huge number of paths, and reparameterisations cuts things down somewhat.
But we shall go even better, and put a topology on the space of paths.
The fibres $Z_x$ of a covering space $Z$ are discrete spaces, but the set
$\Top(I,X)$ of paths $I\to X$ carries a topology when $X$ is a metric space; we can
consider $C(I,X)$ with the sup metric $d_\infty$. The aim is to give $\Top(I,X)$ a
topology for \emph{any} space, not necessarily metric.
\begin{lemma}\label{lemma:compact_open_base}
Let $X$ be a topological space, $\gamma\in \Top(I,X)$ a path,
$0=t_0 < t_1 < \cdots < t_N < t_{N+1} = 1$ a partition of $[0,1]$, and $U_0, \ldots, U_N \subseteq X$
a collection of basic nhds such that $U_i$ is a nhd of $\gamma(t))$ for all $t\in [t_i,t_{i+1}]$.
Define the subsets
\[
N_\gamma(t_1<\cdots<t_N;U_0,\ldots,U_n) :=\{\eta\colon I\to X\mid\forall i=0,\ldots N,\
\eta([t_i,t_{i+1}]) \subseteq U_i\} \subseteq \Top(I,X)
\]
Then these sets give a neighbourhood base on $\Top(I,X)$
\end{lemma}
\begin{definition}
The \emph{path space} $X^I$ is the set $\Top(I,X)$ equipped with the topology defined by
Lemma~\ref{lemma:compact_open_base}, which we call the \emph{compact-open topology}.
\end{definition}
When $X$ is a metric space, then the compact-open topology and the topology arising from the
sup metric coincide. A key property of the compact-open topology is that homotopies $H\colon
I\times I \to X$ give continuous paths $h\colon I \to X^I$ (defined by $h_t\colon s\mapsto H(t,s)$) and vice-versa. Moreover:
\begin{lemma}
\begin{enumerate}
\item The evaluation map $\ev\colon X^I \times I\to X$, $\ev(\gamma,t) = \gamma(t)$ is continuous, and
\item given a map $X\xrightarrow{f} Y$, the post-composition map $f_*\colon X^I \to Y^I$, $f_*(\gamma) = f\circ \gamma$, is continuous.
\end{enumerate}
\end{lemma}
Then given $t\in I$, the composite map $\ev_t\colon X^I \simeq X^I\times\{t\} \into X^I \times I \xrightarrow{\ev} X$ is continuous.
Usually we care just about the cases $t=0,1$.
We can then look at various subspaces of $X^I$, for a given $x\in X$:
\begin{align*}
P_xX & := \{\gamma \in X^I\mid \gamma(0)=x\} = \ev_0^{-1}(x)\\
P_x^yX & := \{\gamma \in X^I\mid \gamma(0)=x,\ \gamma(1)=y\} = \ev_0^{-1}(x)\cap \ev_1^{-1}(y)\\
\Omega_x X & := P_x^x X = \{\gamma \in X^I \mid \gamma(0) = x = \gamma(1)\}
\end{align*}
In particular, we have already seen the last two, albeit without their topologies. We also see that path
components of these spaces have something to do with homotopy classes of paths, perhaps with
constraints on endpoints.
A key property of the natural transformation $\id \Rightarrow \disc\pi_0\colon \slpcTop\to\slpcTop$
is that it has a universal property: given a discrete space $S$, an slpc space $X$ and a continuous
map $X\xrightarrow{f} S$, there is a \emph{unique} function $\pi_0(X)\to U(S)$ such that
\[
\xymatrix{
X \ar[r] \ar[d] & S\\
\disc(\pi_0(X)) \ar[ur]
}
\]
commutes. Hence if we take our function
\begin{equation}\label{eq:path_space_action_fibres}
P_x^yX \times Z_x \to Z_y
\end{equation}
from the previous lecture,
arising from a covering space $Z\to X$, and if we can show it is continuous, we would get a
factorisation
\[
P_x^y X\times Z_x\to \pi_0(P_x^y X\times Z_x) \simeq \pi_0(P_x^yX)\times Z_x \to Z_y
\]
where the unmarked isomorphism exist due to $Z_x$ being discrete.
If $Z$ is path connected, a fixing some $z\in Z_x$, we get a surjective map $\pi_0(P_x^y X)\to Z_y$,
which further constrains both the topology of the space of paths, and the possible fibres of
$Z\to X$. However, there are two issues:
\begin{enumerate}[(i)]
\item We yet don't know our path lifting function is continuous
\item We don't know if $P_x^y X$ is slpc, hence if path components and components agree.
\end{enumerate}
To address (i), the unique path lifting property from last lecture will be promoted to a
\marginnote{here $X^I \times_X Z = \{(\gamma,z)\mid \gamma(0) = \pi(z)\}$}
\emph{continuous function} $\Lift\colon X^I\times_X Z \to Z^I$. Combined with $Z^I \xrightarrow{\ev} Z$
we will be able to reconstruct (\ref{eq:path_space_action_fibres}) as
\[
P_x^y X \times Z_x \into X^I \times_X Z \xrightarrow{\Lift} Z^I \xrightarrow{\ev_1} Z
\]
factors through $Z_y \subset Z$. We already have the definition of $\Lift$, but we need to show
continuity.
\begin{theorem}
The function $\Lift\colon X^I\times_X Z \to Z^I$ is continuous.
\end{theorem}
\begin{proof}
We need to set up the ingredients, so take $\gamma \in X^I$,
define $x=\gamma(0)$, $y=\gamma(1)$, and take $z\in Z_x$.
Let $\widetilde{\gamma} = \Lift(\gamma,z)$, and $z'=\widetilde{\gamma}(1)\in Z_y$.
Take a basic nhd $N_{\widetilde{\gamma}} = N_{\widetilde{\gamma}}(t_1 < \cdots<t_n;U_0,\ldots, U_n)$.
We want to construct a basic nhd
\[
M(\gamma,z) \subseteq X^I \times_X Z
%:= \left(N_\gamma(s_1<\cdots<s_m;V_0,\ldots, V_m)\times W \right) \cap X^I \times_X Z
\]
of $(\gamma,z)$ such that $M(\gamma,z) \subseteq \Lift^{-1}(N_{\widetilde{\gamma}})$.
Since $Z\xrightarrow{\pi} X$ is locally trivial and $I$ is compact, we can find a sequence $W_0,\ldots,W_m\subseteq Z$ (with $m\geq n$) of nhds such that
\begin{itemize}
\item $\pi\big|_{W_i} \colon W_i \xrightarrow{\simeq} \pi(W_i)$ and each $\pi(W_i)$ is a nhd in $X$, and
\item $\forall i=0,\ldots, m$ $\exists j=j(i)$ with $W_i \subseteq U_j$.
\end{itemize}
There is then a refinement $0<s_1<\cdots<s_m < 1$\marginnote{so that $[s_i,s_{i+1}]\subseteq [t_j,t_{j+1}]$} such that $W_i$ is a nhd of $\widetilde{\gamma}(t)$ for all $t\in[s_i,s_{i+1}]$.
The set $\widetilde{N}_{\widetilde{\gamma}} := N_{\widetilde{\gamma}}(s_1<\cdots<s_m;W_0,\ldots,W_m) \subseteq Z$ is then contained in $N_{\widetilde{\gamma}}$.
But, defining $V_i := \pi(W_i)$, the partition $0<\cdots s_1 <s_m<1$ and the sets $V_0,\ldots,V_m$ satisfy the conditions required to define the basic nhd $N_\gamma(s_1<\cdots<s_m;V_0,\ldots, V_m)\subseteq X^I$. Also note that $z=\widetilde{\gamma}(0) \in W_0$, so we can define a nhd
\[
M(\gamma,z):= \left(N_\gamma(s_1<\cdots<s_m;V_0,\ldots, V_m)\times W \right) \cap X^I \times_X Z
\]
of $(\gamma,z)$. By construction $\pi(\widetilde{N}_{\widetilde{\gamma}}) \subseteq N_\gamma(s_1<\cdots<s_m;V_0,\ldots, V_m)$, but in fact $\Lift(M(\gamma,z)) = \widetilde{N}_{\widetilde{\gamma}} \subseteq N_{\widetilde{\gamma}}$, as desired.
\end{proof}
\begin{rem}
In fact, by the uniqueness of lifts, the map $\Lift$ is a bijection, and even a homeomorphism, with inverse $(\pi_*,\ev_0)\colon Z^I \to X^I \times _X Z$.
\end{rem}
So we have a continuous map $P_x^y X\times Z_x \to Z_y$, and thus get a function $\pi_0(P_x^yX) \times Z_x \to Z_y$.
But we would like to know that for any two points $\gamma,\eta\in P_x^yX$ in the same connected component, there is a path between them.
Such a path, recall, is a homotopy $H\colon I \times I \to X$ satisfying $H(s,0)=x$ and $H(s,1)=y$ $\forall x\in I$. Such a homotopy between paths will be said to \emph{fix endpoints}.
% We will give a sufficient condition, but the proof it is indeed sufficient will be relegated to a handout.
\begin{definition}
A space $X$ is called \emph{semilocally simply-connected}\marginnote{this is the last technical
condition on spaces we require in this section of the course}
(or \emph{slsc}) if every point has a basis of nhds $N$ that are path connected, and given
$x,y\in N$ and two paths $\gamma,\eta \in P_x^y N$, there is an endpoint-fixing homotopy
$I\times I \to X$ from $\gamma$ to $\eta$.
\end{definition}
Notice that if a space $X$ is slsc, then it is slpc.
\begin{example}
Any manifold is slsc, since every point has a nhd homeomorphic to some $\RR^n$,
which is convex.
\end{example}
\begin{example}
The \emph{Hawaiian earring} is the subspace
\[
\bigcup_{n\in \mathbb{N}} \left\{(x,y)\in \RR^2 \left|
||(x,y) - (\tfrac1n,0)|| = \tfrac1n\right.\right\}
\]
and is not slsc. Every nhd of the point $(0,0)$ contains loops that are not contractible, and
stay non-contractible in the full space.
\end{example}
\begin{theorem}[Wada 1955, improved in Roberts 2010]
If\marginnote{H.~Wada, ``Local connectivity of mapping spaces'', Duke Math. J. \textbf{22},
Number 3 (1955) pp 419--425. DMR ``Fundamental bigroupoids and 2-covering spaces'', Theorem 5.12.}
the space $X$ is semilocally simply-connected,
the spaces $X^I$, $P_xX$ and $P_x^yX$ (hence $\Omega_xX$) are semilocally path connected.
\end{theorem}
\begin{proof}(Non-examinable)
See Handout 1.
\end{proof}
A\lecturenum{7} question that may have occurred to you is what happens with the isomorphism
$\gamma_*\colon Z_x\to Z_y$ if we break the path $\gamma\colon I\to X$ into two
subpaths, say $x\rightsquigarrow x' \rightsquigarrow y$, and then compose the
corresponding isomorphisms $Z_x\xrightarrow{\simeq}Z_{x'}\xrightarrow{\simeq}Z_y$. Or,
starting from paths $\gamma,\eta\colon I\to X$ such that $\gamma(1) = \eta(0)$ and
defining the \emph{concatenation} $\gamma\#\eta\colon I\to X$ by
\[
\gamma\#\eta(t) = \begin{cases}
\gamma(2t) & t\in[0,\frac12]\\
\eta(2t-1) & t \in[\frac12,1]
\end{cases}
\]
how do $Z_{\gamma(0)} \xrightarrow{\gamma_*}
Z_{\gamma(1)}=Z_{\eta(0)}\xrightarrow{\eta_*}Z_{\eta(1)}$ and
$Z_\gamma(0) \xrightarrow{(\gamma\#\eta)_*}Z_{\eta(1)}$ relate?
\begin{lemma}
For paths $\gamma,\eta\colon I\to X$ such that $\gamma(1) = \eta(0)$,
$(\gamma\#\eta)_* = \eta_*\circ\gamma_*\colon Z_{\gamma(0)}\to Z_{\eta(1)}$.
\end{lemma}
In particular, for $\gamma,\eta\in \Omega_xX$, $\gamma\#\eta\in \Omega_xX$ and we have
the map $\Omega_x X \to \Aut(Z_x)$, which is compatible with path concatenation. But
$\#$ is not associative!
\begin{example}
Take $X=S^1$, and let $\gamma(t)=\exp(2\pi it)$.
\[
(\gamma\#\gamma)\#\gamma = \begin{cases}
\exp(8\pi it) & t\in[0,\frac12]\\
\exp(4\pi it) & t \in[\frac12,1]
\end{cases} \quad \text{but}\quad
\gamma\#(\gamma\#\gamma) = \begin{cases}
\exp(4\pi it) & t\in[0,\frac12]\\
\exp(8\pi it) & t \in[\frac12,1]
\end{cases}
\]
\end{example}
Let us re-examine how paths concatenate. Given $\gamma,\eta\colon I \to X$
such that $\gamma(1) = \eta(0)$, then we get a continuous function
$\langle\gamma,\eta\rangle\colon [0,2] \to X$. The concatenation $\gamma\#\eta$ is then
the precomposition of $\langle\gamma, \eta\rangle$ with the map $I=[0,1]
\xrightarrow{t\mapsto 2t} [0,2]$. If we had a third map, $\lambda\colon I\to X$ with
$\lambda(0)=\eta(1)$, then there is naturally a continuous function $\langle\gamma,
\eta,\lambda\rangle\colon [0,3]\to X$. But the concatenations $( \gamma \# \eta ) \#
\lambda$ and $\gamma \# ( \eta \# \lambda)$ arise from precomposing with two different
maps $I=[0,1]\to [0,3]$. These are\marginnote{%
\begin{tikzpicture}[scale=1.2]
\draw[step=1,gray,very thin] (0,0) grid (1,3);
\draw [thick,->] (0,0) -- (1.2,0);
\draw [thick,->] (0,0) -- (0,3.2);
\draw [domain=0:0.5, ultra thick] plot (\x, 2*\x);
\draw [domain=0.5:1, ultra thick] plot (\x, 4*\x-1);
\draw (0.5,1.7) node {$\phi$};
\end{tikzpicture}
\qquad
\begin{tikzpicture}[scale=1.2]
\draw[step=1,gray,very thin] (0,0) grid (1,3);
\draw [thick,->] (0,0) -- (1.2,0);
\draw [thick,->] (0,0) -- (0,3.2);
\draw [domain=0:0.5, ultra thick] plot (\x, 4*\x);
\draw [domain=0.5:1, ultra thick] plot (\x, 2*\x+1);
\draw (0.5,2.5) node {$\psi$};
\end{tikzpicture}
}
\begin{align*}
\phi\colon t& \mapsto \begin{cases}
4t & t\in [0,\frac12]\\
2t+1 & t\in [\frac12,1]
\end{cases}\\
\psi\colon t& \mapsto \begin{cases}
2t & t\in [0,\frac12]\\
4t-1 & t\in [\frac12,1]
\end{cases}
\end{align*}
with graphs as at right.
These two paths $I\to [0,3]$ are homotopic fixing endpoints by the homotopy $h_a(s,t) =
s\phi(t) + (1-s) \phi(t)$. If we then precompose
$\langle\gamma,\eta,\lambda\rangle\colon [0,3]\to X$ with $h_a\colon I\times I \to [0,3]$,
we get a homotopy between $( \gamma \# \eta ) \# \lambda$ and $\gamma \# ( \eta
\# \lambda)$. Path concatenation in $X$ is then \emph{homotopy associative}. But what
about inverses or an identity element? We will play the same trick, by considering a
`universal' case.
Given a path $\gamma\colon I \to X$, we have the reverse path $-\gamma$,
\marginnote{recall $-\gamma(t) := \gamma(1-t)$\\%}
%\marginnote{%
\noindent\begin{tikzpicture}[scale=1.2]
\draw[step=1,gray,very thin] (0,0) grid (1,1);
\draw [thick,->] (0,0) -- (1.2,0);
\draw [thick,->] (0,0) -- (0,1.2);
\draw [domain=0:0.5, ultra thick] plot (\x, 2*\x);
\draw [domain=0.5:1, ultra thick] plot (\x, 2-2*\x);
\draw (0.85,0.75) node {$\alpha$};
\end{tikzpicture}
\qquad
\begin{tikzpicture}[scale=1.2]
\draw[step=1,gray,very thin] (0,0) grid (1,1);
\draw [thick,->] (0,0) -- (1.2,0);
\draw [thick,->] (0,0) -- (0,1.2);
\draw [domain=0:1, ultra thick] plot (\x, 0);
% \draw [domain=0.5:1, ultra thick] plot (\x, 2-2*\x);
\end{tikzpicture}
\medskip
\noindent
\begin{tikzpicture}[scale=1.2]
\draw[step=1,gray,very thin] (0,0) grid (1,1);
\draw [thick,->] (0,0) -- (1.2,0);
\draw [thick,->] (0,0) -- (0,1.2);
\draw [domain=0:0.5, ultra thick] plot (\x, 1-2*\x);
\draw [domain=0.5:1, ultra thick] plot (\x, 2*\x-1);
\draw (0.65,0.6) node {$\beta$};
\end{tikzpicture}
\qquad
\begin{tikzpicture}[scale=1.2]
\draw[step=1,gray,very thin] (0,0) grid (1,1);
\draw [thick,->] (0,0) -- (1.2,0);
\draw [thick,->] (0,0) -- (0,1.2);
\draw [domain=0:1, ultra thick] plot (\x, 1);
% \draw [domain=0.5:1, ultra thick] plot (\x, 2-2*\x);
% \draw (0.5,2.5) node {$\psi$};
\end{tikzpicture}
\medskip
\noindent
\begin{tikzpicture}[scale=1.2]
\draw[step=1,gray,very thin] (0,0) grid (1,1);
\draw [thick,->] (0,0) -- (1.2,0);
\draw [thick,->] (0,0) -- (0,1.2);
\draw [domain=0:0.5, ultra thick] plot (\x, 2*\x);
\draw [domain=0.5:1, ultra thick] plot (\x, 1);
\draw (0.5,0.6) node {$\mu$};
\end{tikzpicture}
\qquad
\begin{tikzpicture}[scale=1.2]
\draw[step=1,gray,very thin] (0,0) grid (1,1);
\draw [thick,->] (0,0) -- (1.2,0);
\draw [thick,->] (0,0) -- (0,1.2);
\draw [domain=0:1, ultra thick] plot (\x, \x);
% \draw [domain=0.5:1, ultra thick] plot (\x, 2-2*\x);
% \draw (0.5,2.5) node {$\psi$};
\end{tikzpicture}
\medskip
\noindent
\begin{tikzpicture}[scale=1.2]
\draw[step=1,gray,very thin] (0,0) grid (1,1);
\draw [thick,->] (0,0) -- (1.2,0);
\draw [thick,->] (0,0) -- (0,1.2);
\draw [domain=0:0.5, ultra thick] plot (\x, 0);
\draw [domain=0.5:1, ultra thick] plot (\x, 2*\x-1);
\draw (0.6,0.6) node {$\nu$};
\end{tikzpicture}
\qquad
\begin{tikzpicture}[scale=1.2]
\draw[step=1,gray,very thin] (0,0) grid (1,1);
\draw [thick,->] (0,0) -- (1.2,0);
\draw [thick,->] (0,0) -- (0,1.2);
\draw [domain=0:1, ultra thick] plot (\x, \x);
% \draw [domain=0.5:1, ultra thick] plot (\x, 2-2*\x);
% \draw (0.5,2.5) node {$\psi$};
\end{tikzpicture}}
%
and the composite $\gamma \# (-\gamma)\colon I \to X$ can be factored as
$I\xrightarrow{\alpha} I \xrightarrow{\gamma} X$ for a certain path $I\xrightarrow{\alpha}
I$. If we instead concatenate in the other direction, namely $(-\gamma)\# \gamma\colon
I\to X$, then this factors as $I\xrightarrow{\beta} I\xrightarrow{\gamma}X$. Again
$\beta$ is a certain path in $I$. The graphs of both $\alpha$ and $\beta$ are shown at
right, and both of them are homotopic, fixing endpoints, to the constant functions at
$0$ and $1$ respectively, by taking an affine combination as in the definition of $h_a$
above. Then by composing the homotopies here with $\gamma$, we get homotopies between
the path $\gamma\#(-\gamma)$ and the constant path at $\gamma(0)$, and also between
$(-\gamma)\#\gamma$ and the constant path at $\gamma(1)$. So we have \emph{homotopy
inverses}.
If we want to think about a homotopy identity element, then we should use the constant
path $c_x\colon I\to X$ at a point $x\in X$, with $c_x(t)= x$, $\forall t\in I$. We can
factor the composite $\gamma\# c_{\gamma(1)}$ as $I\xrightarrow{\mu} I
\xrightarrow{\gamma} X$ for $\mu$ as shown at right, and factor $c_{\gamma(0)}\#\gamma$
as $I\xrightarrow{\nu} I \xrightarrow{\gamma} X$. As above, $\mu$ and $\nu$ are
homotopic, fixing endpoints, to the identity map $I\to I$.
If we turn the five homotopies $I\times I \to X$ described above into paths $I\to X^I$, then if we start from elements of $\Omega_x X$, these homotopies correspond to paths in $\Omega_x X$.
Thus $\Omega_x X$, which has a concatenation binary operator $\#\colon \Omega_xX \times \Omega_xX\to \Omega_xX$, acts like a group, except the group axioms only hold up to the existence of paths\marginnote{More is true, though we won't prove it: there are homotopies assembled out of these paths for all possible cases, for instance $I \times \Omega_x X \times \Omega_x X \times \Omega_x X \to \Omega_x X$}
\begin{align*}
( \gamma \# \eta ) \# \lambda & \rightsquigarrow \gamma \# ( \eta \# \lambda)\\
\gamma\# (-\gamma) &\rightsquigarrow c_{\gamma(0)}\\
(-\gamma)\# \gamma &\rightsquigarrow c_{\gamma(1)}\\
\gamma\# c_{\gamma(1)}&\rightsquigarrow \gamma \\
c_{\gamma(0)}\#\gamma &\rightsquigarrow \gamma
\end{align*}
in $\Omega_x X$. As a result we have proved most of
\begin{prop}
Let $(X,x)$ be a pointed space, with $X$ slsc. The set $\pi_0(\Omega_x X)$ carries the
structure of a group, its product arising from concatenation of loops and identity element
represented by the constant path at $x$.
\end{prop}
\begin{proof}
To exhibit the multiplication, consider the functor $\pi_0$ applied\marginnote{This requires knowing that $\#$ is continuous! See Assignment 2.} to $\#\colon \Omega_x X
\times \Omega_x X \to \Omega_x X$, giving $\pi_0(\Omega_x X \times \Omega_x X) \xrightarrow{\#}
\pi_0(\Omega_x X)$. But since $\pi_0(M\times N) \xrightarrow{\simeq}
\pi_0(M)\times\pi_0(N)$, for all slpc spaces $M$ and $N$, we get a composite
$\pi_0(\Omega_x X) \times \pi_0(\Omega_x X) \simeq \pi_0(\Omega_x X \times \Omega_x X)
\to \pi_0(\Omega_x X)$. This is associative and unital, and inverses exist, by the
existence of the paths above.
\end{proof}
\begin{definition}
For\marginnote{Recall we also proved $[\pt,-]$ descends to a functor $\Ho \to \Set$ in Assignment 1}
$(X,x)$ a pointed space its \emph{fundamental group at $x$} is
$\pi_1(X,x) := [\pt,\Omega_xX]$, which for $X$ a slsc space coincides with $\pi_0(\Omega_xX)$.
\end{definition}
From the previous reasoning, we have constructed from a covering space $Z\to X$ and
chosen basepoint $x\in X$ a permutation representation $\pi_1(X,x) \to \Aut(Z_x)$. If
$Z$ is path connected, and we choose $z\in Z_x$, we get a surjective map $\pi_1(X,x) \to
Z_x$, given by $\gamma\mapsto \gamma_*(z)$. This implies we have an upper bound on the
cardinality of fibres of any path connected covering space, and conversely, given a
connected covering space, the fibres give a lower bound on the number of distinct
homotopy classes of loops in $X$.
\begin{example}
The projection map $S^2 \to \mathbb{RP}^2$ is a covering space and $S^2$ is connected,
so there exist at least two non-homotopic loops in $\mathbb{RP}^2$ at any given
basepoint. One of these is the constant loop, so there exists a loop in $\mathbb{RP}^2$
not homotopic to it.
\end{example}
\begin{example}\label{eg:piS^1_infinite}
We have the covering space $\exp(2\pi i-)\colon \RR\to S^1$ with fibre
$\ZZ$ over $1\in S^1$, which implies $\pi_1(S^1,1)$ is an infinite group.
\end{example}
\begin{prop}
The loop space construction is a functor $\Omega\colon \Top_*\to \Top_*$.
\end{prop}
\begin{corollary}
The fundamental group\marginnote{Exercise: This functor is naturally isomorphic to $[(S^1,1),(X,x)]_*$} gives a functor
\[
\pi_1 := \pi_0 \circ \Omega\colon \Top_*\to \Grp.
\]
\end{corollary}
However,\lecturenum{8} as we have seen, we don't just get an action of $\pi_1(X,x)$ on the fibre $Z_x$
of a covering space. We also get what looks like an action of paths between different
points on fibres, but now points in one fibre are taken to points of another fibre. In
fact, if $X$ is not equipped with a basepoint to start with, or there are several
natural options and no one of those is canonical, then we can create an even richer
invariant, namely a \emph{groupoid}.
\begin{definition}
A \emph{groupoid} is a category where every morphism has an inverse.
\end{definition}
So that we have an idea of what kinds of groupoids arise, let us consider some examples.
We will be considering only \emph{small} groupoids: those locally small groupoids
$\Gamma$ where there is a set $\Gamma_0$ of objects. We can then take the disjoint union
of all the hom-sets to get the set $\Gamma_1= \bigsqcup_{x,y\in \Gamma_0} \Gamma(x,y)$ of morphisms, and specify the source and
target functions $s,t\colon \Gamma_1\rightrightarrows \Gamma_0$. Groupoids and functors
form a category $\Gpd$.
\begin{example}
\begin{enumerate}
\item Every set $S$ gives a groupoid $\disc(S)$, by taking the set of objects to be $S$, and to only have identity
morphisms. This gives a full subcategory inclusion $\disc\colon \Set \into \Gpd$, and such groupoids are called \emph{discrete}.
\item Every set $C$ also gives another groupoid $\codisc(C)$ with set of objects $C$, but with exactly
one morphism from any object to any other object. The set of morphisms is $C\times C$, and every
object $c\in C$ has the trivial group of automorphisms. Such groupids are called \emph{codiscrete}.
\item Let $G$ act on the set $Y$ on the right. Then there is a groupoid $Y/\!/G$ with object set $Y$, and set of
morphisms $Y\times G$. The source and target are given by $s(y,g)=y$, $t(y,g)=yg$, and composition is $(y,g)(yg,h) = (y,gh)$.
\begin{enumerate}
\item If $G=1$, then this recovers the first example.
\item If $Y=\pt$, then the information in the groupoid is essentially just that of the group $G$. Groupoids of this form will be denoted $\BB G$, and $\BB\colon \Grp \into \Gpd$ is the inclusion of a full subcategory.
\end{enumerate}
\end{enumerate}
\end{example}
A slogan people sometimes use is that a groupoid is like a group with `many identities',
but you can also usefully think of them as being a generalisation of a group action,
where you have different groups acting on different parts of the set. Here is a useful
lemma about the structure of groupoids.
\begin{lemma}
For any groupoid $\Gamma$, and given $x,y\in \Gamma_0$,\marginnote{using algebraic order of composition}
\begin{align*}
\Ad_a\colon \Gamma(x,x) & \xrightarrow{\simeq} \Gamma(y,y)\\
g & \mapsto a^{-1}ga
\end{align*}
is an isomorphism for any $a\in \Gamma(y,x)$\marginnote{$(\Ad_a)^{-1} = \Ad_{a^{-1}}$} and
the function
\begin{align*}
\Gamma(x,x)\times \Gamma(x,y) & \to \Gamma(x,y)\\
(g,a) & \mapsto ga
\end{align*}
is a free and transitive action.\marginnote{transitive: $(ba^{-1},a) \mapsto b$;\\
\noindent free: $ga=a$ implies $g = gaa^{-1} = aa^{-1} =\id_x$}
\end{lemma}
\begin{definition}
Given an slsc space $X$ and a specified subset $A\subseteq X$, the \emph{fundamental groupoid
based at $A$}
is the groupoid $\Pi_1(X,A)$ with set of objects $A$, and $\Pi_1(X,A)(x,y) = \pi_0(P_x^yX)$.
The composition map is induced from concatenation of paths:
\[
\pi_0(P_x^yX) \times \pi_0(P_y^zX) \simeq \pi_0(P_x^y X\times P_y^zX) \to \pi_0(P_x^zX)
\]
and\marginnote{the definition makes sense for more general spaces, but we are only consider slsc spaces here}
constant paths are the identity morphisms.
\end{definition}
As with other invariants, the fundamental groupoid is a functor. Define the category
$\Top^{(2)}$ to be the category with objects pairs $(X,A)$ where $X$ is a topological
space and $A\subseteq X$ is a subspace, and a morphism $(X,A) \to (Y,B)$ is a continuous
function $f\colon X\to Y$ such that $f(A) \subseteq B$. We have a full subcategory inclusion
$\Top_*\into \Top^{(2)}$.
\begin{prop}
The fundamental groupoid gives a functor $\Pi_1\colon \Top^{(2)}\to \Gpd$ such that
\[
\xymatrix{
\Top_* \ar[r]^{\pi_1} \ar[d] & \Grp \ar[d]^{\BB}\\
\Top^{(2)} \ar[r]_{\Pi_1} & \Gpd
}
\]
and moreover:\marginnote{The product/disjoint union of groupoids is
what you think it is: take the products/disjoint unions of the objects and the morphisms, respectively}
\begin{align*}
\Pi(X\times Y,A\times B) & \xrightarrow{\simeq} \Pi_1(X,A) \times \Pi_1(Y,B)\\
\Pi_1(X,A) \sqcup \Pi_1(Y,B) & \xrightarrow{\simeq} \Pi(X\sqcup Y,A\sqcup B)
\end{align*}
\end{prop}
We can include \emph{unbased} spaces $X$ into pairs, by taking $(X,X)$, giving another
fully faithful functor, $\Top \to \Top^{(2)}$. In this case, if the space $X$ has
\emph{no} preferred basepoints whatsoever, we can still define the fundamental groupoid
of $X$ itself as $\Pi_1(X,X)$, which is a functor $\Top \to \Gpd$.
We haven't yet seen how to calculate the fundamental group(oid) in
examples, so we will turn to that now. We need a name for spaces $X$ that have
$\Pi_1(X)$ trivial, in the sense of being codiscrete.
\begin{definition}
A space $X$ that satisfies $\Pi_1(X) = X\times X \rightrightarrows X$\marginnote{such spaces
also have $\Pi_1(X,A) = A\times A \rightrightarrows A$ for all $A\subseteq X$} is called
\emph{simply-connected}.
\end{definition}
\begin{example}
Convex subspaces $C\subseteq \RR^n$ are simply-connected, because any two points $v,w\in C$
can be joined by a path in $C$, and given two paths $\gamma,\eta\colon v\rightsquigarrow w$
the map $(s,t)\mapsto s\gamma(t)+(1-s)\eta(t)$ is a homotopy between them.
\end{example}
In particular, the interval $I$ is simply-connected. The fundamental groupoid $\Pi_1(I,\{0,1\})$
is important enough to have its own name: $\mathbf{2}$, sometimes denoted
$(0\xrightarrow{\sim} 1)$, as it has two objects $0,1$ and a unique isomorphism between them.
\begin{ex}
Define a \emph{star-shaped region}\marginnote{For $\mathcal{H} \subset \CC$ the
(open) upper half-plane, the set $\mathcal{H}\cup\mathbb{Q}$ is star-shaped, but not convex}
in a (real or complex) vector space $V$ to be a set
$K\subseteq V$ such that there is a point $v_0\in K$ such that for every $v\in K$ and $t\in I$,
$tv_0+(1-t)v\in K$. Prove that star-shaped regions are simply-connected.
\end{ex}
Simply-connected spaces are special for the following reason.
\begin{prop}
If $X$ is a simply-connected space, then every path connected covering space
$Z\xrightarrow{\pi} X$ is trivial, in the sense that $\pi$ is a homeomorphism.
\end{prop}
\begin{proof}
Recall that $\pi_1(X,x) \to Z_x$ is surjective for any $x\in X$, so $X$ simply-connected implies
$Z_x = \pt$ for all $x$. Thus $\pi$ is a bijection. The local triviality condition implies
that every $x\in X$ has an open set $U\ni x$ such that $\pi^{-1}(U) \to U$ is a homeomorphism.
Letting $U_\alpha$ range over such an cover of $X$, we can glue the inverses of these local
homeomorphisms into a into an inverse for $\pi$.
\end{proof}
\begin{example}
If $X$ is contractible then it is simply-connected. Let $H\colon I\times X \to X$ be a
contraction to $x_0\in X$. Consider the induced map $h= \Pi_1(H)\colon \Pi_1(I\times X,
\{0,1\}\times X) \to \Pi_1(X,X) = \Pi_1(X)$. The domain simplifies to be
$\Pi_1(I,\{0,1\})\times \Pi_1(X) = \mathbf{2}\times \Pi_1(X)$. Consider the induced maps
$\{i\}\times \Pi_1(X)\to \mathbf{2}\times \Pi_1(X) \to \Pi_1(X)$ for $i=0,1$. Since
$H\big|_{\{0\}\times X}=\id_X$, so $h_{\{0\}\times \Pi_1(X)}=\id_{\Pi_1(X)}$; and as
$H\big|_{\{1\}\times X}$ is constant at $x_0$, so $h(0,x) = x_0$ for all $x\in X$, and
$h\big|_{\{1\}\times \Pi_1(X)}$ sends every path to the constant path at $x_0$. We
already know that $X$ is path connected, so that for any $x,y\in X$ there is some path
between them. Given a path $\gamma\colon x\rightsquigarrow y$ consider the commutative square
\[
\xymatrix{
(0,x) \ar[r]^{(\id_0,[\gamma])} \ar[d] & (0,y) \\
(1,x) \ar[r]_{(\id_1,[\gamma])} & (1,y) \ar[u]
}
\]
in $\mathbf{2}\times \Pi_1(X)$ (recall all morphisms are invertible). Under $h$ this is sent to
\[
\xymatrix{
x\ar[r]^{[\gamma]} \ar[d] & y \\
x_0 \ar[r]_{\id} & x_0 \ar[u]
}
\]
The vertical arrows are independent of $[\gamma]$, so that every path $\gamma$ in $X$ is
homotopic to the composite the long way around the square, hence to every other path.
\end{example}
\end{document}
|
using Literate
using Plots
using Glob
notebooks = glob("*.*.jl")
for notebook in notebooks
NOTEBOOK = joinpath(@__DIR__, notebook)
MD_OUTPUT = joinpath(@__DIR__, "markdown")
NB_OUTPUT = joinpath(@__DIR__, "notebooks")
Literate.markdown(NOTEBOOK, MD_OUTPUT)
Literate.notebook(NOTEBOOK, NB_OUTPUT, execute=false)
end
|
#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/raw_function.hpp>
#include <boost/python/make_function.hpp>
#include <boost/python/pure_virtual.hpp>
#include <boost/python/tuple.hpp>
#include <boost/python/dict.hpp>
#include <boost/python/return_internal_reference.hpp>
#include <boost/python/return_by_value.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/with_custodian_and_ward.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/docstring_options.hpp>
#include <boost_adaptbx/iterator_range.h>
#include <scitbx/boost_python/container_conversions.h>
#include <boost/format.hpp>
#include <smtbx/refinement/constraints/reparametrisation.h>
namespace smtbx { namespace refinement { namespace constraints {
namespace boost_python {
/* Three goals may be pursued in relation to inheritance:
(1) Polymorphic calls from Python to C++
e.g. given a Python object s of type independent_site_parameter,
properly dispatch s.scatterers() to the appropriate ancestor in C++
(2) Given a C++ function taking an argument of type site_parameter *,
make sure that from the Python side one can pass to it an
object of type special_position_site_parameter, e.g.
(3) Make it possible to write new constraints in Python, which requires
polymorphic calls from C++ to Python.
Goals (1) and (2) are easily achieved with the usual flavour
of Boost.Python wrapper. That is to say that virtual or pure virtual
member functions are wrapped as any other member function, once and only
once in the class where they are introduced in the inheritance hierarchy,
e.g. linearise is wrapped as part of the wrapper of class parameter.
Boost.Python then auto-magically care of all the details. The only necessary
trick is to instruct Boost.Python to use boost::noncopyable storage for
any class with non-overriden pure virtual member functions,
as otherwise the code won't compile since Boost.Python will try
to construct an object.
Goal (3) requires to write an inordinate amount of boiler code. The
Boost.Python tutorial looks easy enough on that subject but the featured
example has only one base class and one derived class. For the non-trivial
hiearchy of ours, it scales very badly. In an earlier version, we had
attempted to reach that goal, but we have now decided against it,
until the need for writing reparametrisations in Python arises.
An orthogonal question is that of memory management for the instances
of parameter classes (and heirs). Since class reparametrisation owns the
pointers to the objects it refers too, we need to be very carefull that
the Python side releases ownership and transfers it correctly. The first
step to do that is to instruct Boost.Python to use std::auto_ptr storage
for all instanciable classes (i.e. without any non-overriden pure
virtual member functions). The second step is the Boost.Python binding
for class reparametrisation (see below).
*/
struct parameter_wrapper
{
typedef parameter wt;
static void wrap() {
using namespace boost::python;
return_internal_reference<> rir;
class_<wt,
boost::noncopyable>("parameter", no_init)
.add_property("index", &wt::index)
.add_property("n_arguments", &wt::n_arguments)
.def("argument", &wt::argument, rir)
.add_property("is_independent", &wt::is_independent)
.add_property("is_root", &wt::is_root)
.def("size", &wt::size)
.add_property("is_variable", &wt::is_variable)
.def("evaluate", &wt::evaluate, arg("unit_cell"))
.def("linearise", &wt::linearise,
(arg("unit_cell"), arg("jacobian_transpose")))
;
}
};
struct asu_parameter_wrapper
{
typedef asu_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<parameter>,
boost::noncopyable>("asu_parameter", no_init)
.def("component_indices_for",
&wt::component_indices_for,
arg("scatterer"))
.def("store", &wt::store, arg("unit_cell"))
.add_property("scatterers", &wt::scatterers)
;
}
};
struct single_asu_scatterer_parameter_wrapper
{
typedef single_asu_scatterer_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<asu_parameter>,
boost::noncopyable>("single_asu_scatterer_parameter", no_init)
;
}
};
struct scalar_parameter_wrapper
{
typedef scalar_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<parameter>,
boost::noncopyable>("scalar_parameter", no_init)
.def_readonly("value", &wt::value);
}
};
struct independent_scalar_parameter_wrapper
{
typedef independent_scalar_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<scalar_parameter>,
std::auto_ptr<wt> >("independent_scalar_parameter", no_init)
.def(init<double, optional<bool> >
((arg("value"), arg("variable")=true)));
implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();
}
};
struct twin_fraction_parameter_wrapper
{
typedef twin_fraction_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<independent_scalar_parameter>,
std::auto_ptr<wt> >("twin_fraction_parameter", no_init)
.def(init<cctbx::xray::twin_fraction<double> *>((
arg("twin_fraction"))));
implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();
}
};
struct extinction_parameter_wrapper
{
typedef extinction_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<independent_scalar_parameter>,
std::auto_ptr<wt> >("extinction_parameter", no_init)
.def(init<cctbx::xray::extinction_correction<double> *>((
arg("extinction"))));
implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();
}
};
template <int N>
struct small_vector_parameter_wrapper
{
typedef small_vector_parameter<N> wt;
static void wrap() {
using namespace boost::python;
return_value_policy<return_by_value> rbv;
std::string name = (
boost::format("small_%1%_vector_parameter") % N).str();
class_<wt,
bases<parameter>,
boost::noncopyable>(name.c_str(), no_init)
.add_property("value",
make_getter(&wt::value, rbv),
make_setter(&wt::value, rbv));
}
};
template <int N>
struct independent_small_vector_parameter_wrapper
{
typedef independent_small_vector_parameter<N> wt;
static void wrap() {
using namespace boost::python;
std::string name = (
boost::format("independent_small_%1%_vector_parameter") % N).str();
class_<wt,
bases<small_vector_parameter<N> >,
std::auto_ptr<wt> >(name.c_str(), no_init)
.def(init<af::small<double, N> const &, optional<bool> >
((arg("value"), arg("variable")=true)));
;
implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();
}
};
struct vector_parameter_wrapper {
typedef vector_parameter wt;
static void wrap() {
using namespace boost::python;
return_value_policy<return_by_value> rbv;
class_<wt,
bases<parameter>,
boost::noncopyable>("vector_parameter", no_init)
.add_property("value",
make_getter(&wt::value, rbv),
make_setter(&wt::value, rbv));
}
};
struct independent_vector_parameter_wrapper {
typedef independent_vector_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<vector_parameter>,
std::auto_ptr<wt> >("independent_vector_parameter", no_init)
.def(init<af::shared<double> const &, optional<bool> >
((arg("value"), arg("variable") = true)));
;
implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();
}
};
struct site_parameter_wrapper
{
typedef site_parameter wt;
static void wrap() {
using namespace boost::python;
return_value_policy<return_by_value> rbv;
class_<wt,
bases<parameter>,
boost::noncopyable>("site_parameter", no_init)
.add_property("value",
make_getter(&wt::value, rbv),
make_setter(&wt::value, rbv));
;
}
};
struct asu_site_parameter_wrapper
{
typedef asu_site_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<site_parameter, single_asu_scatterer_parameter>,
boost::noncopyable>("asu_site_parameter", no_init)
;
}
};
struct independent_site_parameter_wrapper
{
typedef independent_site_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<asu_site_parameter>,
std::auto_ptr<wt> >("independent_site_parameter", no_init)
.def(init<asu_parameter::scatterer_type *>(arg("scatterer")))
;
implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();
}
};
struct u_star_parameter_wrapper
{
typedef u_star_parameter wt;
static void wrap() {
using namespace boost::python;
return_value_policy<return_by_value> rbv;
class_<wt,
bases<parameter>,
boost::noncopyable>("u_star_parameter", no_init)
.add_property("value",
make_getter(&wt::value, rbv),
make_setter(&wt::value, rbv));
;
}
};
struct asu_u_star_parameter_wrapper
{
typedef asu_u_star_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<u_star_parameter, single_asu_scatterer_parameter>,
boost::noncopyable>("asu_u_star_parameter", no_init)
;
}
};
struct independent_u_star_parameter_wrapper
{
typedef independent_u_star_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<asu_u_star_parameter>,
std::auto_ptr<wt> >("independent_u_star_parameter", no_init)
.def(init<asu_parameter::scatterer_type *>(arg("scatterer")))
;
implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();
}
};
struct anharmonic_adp_parameter_wrapper {
typedef anharmonic_adp_parameter wt;
static void wrap() {
using namespace boost::python;
return_value_policy<return_by_value> rbv;
class_<wt,
bases<parameter>,
boost::noncopyable>("anharmonic_adp_parameter", no_init)
.add_property("value",
make_getter(&wt::value, rbv),
make_setter(&wt::value, rbv));
;
}
};
struct asu_anharmonic_adp_parameter_wrapper {
typedef asu_anharmonic_adp_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<anharmonic_adp_parameter, single_asu_scatterer_parameter>,
boost::noncopyable>("asu_anharmonic_adp_parameter", no_init)
;
}
};
struct independent_anharmonic_adp_parameter_wrapper {
typedef independent_anharmonic_adp_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<asu_anharmonic_adp_parameter>,
std::auto_ptr<wt> >("independent_anharmonic_adp_parameter", no_init)
.def(init<asu_parameter::scatterer_type *>(arg("scatterer")))
;
implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();
}
};
struct asu_occupancy_parameter_wrapper
{
typedef asu_occupancy_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<scalar_parameter, single_asu_scatterer_parameter>,
boost::noncopyable>("asu_occupancy_parameter", no_init)
;
}
};
struct independent_occupancy_parameter_wrapper
{
typedef independent_occupancy_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<asu_occupancy_parameter>,
std::auto_ptr<wt> >("independent_occupancy_parameter", no_init)
.def(init<asu_parameter::scatterer_type *>(arg("scatterer")))
;
implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();
}
};
struct asu_u_iso_parameter_wrapper
{
typedef asu_u_iso_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<scalar_parameter, single_asu_scatterer_parameter>,
boost::noncopyable>("asu_u_iso_parameter", no_init)
;
}
};
struct independent_u_iso_parameter_wrapper
{
typedef independent_u_iso_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<asu_u_iso_parameter>,
std::auto_ptr<wt> >("independent_u_iso_parameter", no_init)
.def(init<asu_parameter::scatterer_type *>(arg("scatterer")))
;
implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();
}
};
struct asu_fp_parameter_wrapper {
typedef asu_fp_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<scalar_parameter, single_asu_scatterer_parameter>,
boost::noncopyable>("asu_fp_parameter", no_init)
;
}
};
struct independent_fp_parameter_wrapper {
typedef independent_fp_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<asu_fp_parameter>,
std::auto_ptr<wt> >("independent_fp_parameter", no_init)
.def(init<asu_parameter::scatterer_type *>(arg("scatterer")))
;
implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();
}
};
struct asu_fdp_parameter_wrapper {
typedef asu_fdp_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<scalar_parameter, single_asu_scatterer_parameter>,
boost::noncopyable>("asu_fdp_parameter", no_init)
;
}
};
struct independent_fdp_parameter_wrapper {
typedef independent_fdp_parameter wt;
static void wrap() {
using namespace boost::python;
class_<wt,
bases<asu_fdp_parameter>,
std::auto_ptr<wt> >("independent_fdp_parameter", no_init)
.def(init<asu_parameter::scatterer_type *>(arg("scatterer")))
;
implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >();
}
};
struct index_range_to_tuple
{
static PyObject *convert(index_range const &ir) {
using namespace boost::python;
tuple t = ir.is_valid() ? make_tuple(ir.first(), ir.last()) : tuple();
return incref(t.ptr());
}
static PyTypeObject const *get_pytype() { return &PyTuple_Type; }
index_range_to_tuple() {
using namespace boost::python;
to_python_converter<index_range, index_range_to_tuple, true>();
}
};
struct reparametrisation_wrapper
{
typedef reparametrisation wt;
// Tricky code ahead!
static parameter *add(boost::python::tuple args,
boost::python::dict kwds)
{
using namespace boost::python;
// We have been called as add(self, klass, *args, **kwds)
object py_self = args[0], klass = args[1], param_args = args.slice(2, _);
wt &self = extract<wt &>(py_self)();
/* Construct a new parameter, taking advantage of Python dynamic
nature to call the constructor of the proper class through its wrapper
*/
object py_param = klass(*param_args, **kwds);
/* All Python wrapper in the parameter hierarchy have std::auto_ptr<>
storage and instruct Boost.Python of the conversion
from std::auto_ptr<> to std::auto_ptr<parameter> (downcast to base
class): thus the following 'extract' works.
*/
std::auto_ptr<parameter>
borrowed_param = extract<std::auto_ptr<parameter> >(py_param)();
/* Apply the official recipe to transfer ownership from Boost.Python
hands to the reparametrisation instance self
(http://www.boost.org/doc/libs/1_43_0/libs/python/doc/v2/faq.html#ownership).
*/
parameter *p = borrowed_param.get();
self.add(p);
borrowed_param.release();
return p;
}
static void wrap() {
using namespace boost::python;
boost_adaptbx::iterator_range_wrapper<wt::range>
::wrap("parameter_iterator");
class_<wt> klass("reparametrisation", no_init);
klass
.def(init<uctbx::unit_cell const &>(arg("unit_cell")))
.add_property("n_independents", &wt::n_independents)
.def("finalise", &wt::finalise)
.def("linearise", &wt::linearise)
.def("store", &wt::store)
.def("parameters", &wt::parameters)
.add_property("jacobian_transpose",
make_getter(&wt::jacobian_transpose))
.def("jacobian_transpose_matching",
&wt::jacobian_transpose_matching,
arg("mapping"))
.def("apply_shifts", &wt::apply_shifts)
.add_property("norm_of_independent_parameter_vector",
&wt::norm_of_independent_parameter_vector)
;
docstring_options no_signature(true, false);
klass
.def("add",
raw_function(make_function(add, return_internal_reference<>())),
"r.add(klass, *args, **kwds): create the parameter "
"klass(*args, **kwds) and add it to the reparametrisation r. "
"'klass' is therefore typically one of the class in the "
"parameter hierarchy, e.g.\n"
"r.add(independent_scalar_parameter, value=1., variable=True)\n"
"but it may also be a factory function.")
;
}
};
void debug(char const *msg, parameter const *p) {
std::cout << msg << p << std::endl;
}
void wrap_reparametrisation() {
using namespace boost::python;
index_range_to_tuple();
scitbx::boost_python::container_conversions::to_tuple_mapping<
asu_parameter::scatterer_sequence_type>();
parameter_wrapper::wrap();
asu_parameter_wrapper::wrap();
single_asu_scatterer_parameter_wrapper::wrap();
scalar_parameter_wrapper::wrap();
independent_scalar_parameter_wrapper::wrap();
twin_fraction_parameter_wrapper::wrap();
extinction_parameter_wrapper::wrap();
small_vector_parameter_wrapper<3>::wrap();
independent_small_vector_parameter_wrapper<3>::wrap();
small_vector_parameter_wrapper<6>::wrap();
independent_small_vector_parameter_wrapper<6>::wrap();
vector_parameter_wrapper::wrap();
independent_vector_parameter_wrapper::wrap();
site_parameter_wrapper::wrap();
asu_site_parameter_wrapper::wrap();
independent_site_parameter_wrapper::wrap();
u_star_parameter_wrapper::wrap();
asu_u_star_parameter_wrapper::wrap();
independent_u_star_parameter_wrapper::wrap();
anharmonic_adp_parameter_wrapper::wrap();
asu_anharmonic_adp_parameter_wrapper::wrap();
independent_anharmonic_adp_parameter_wrapper::wrap();
asu_occupancy_parameter_wrapper::wrap();
independent_occupancy_parameter_wrapper::wrap();
asu_u_iso_parameter_wrapper::wrap();
independent_u_iso_parameter_wrapper::wrap();
asu_fp_parameter_wrapper::wrap();
independent_fp_parameter_wrapper::wrap();
asu_fdp_parameter_wrapper::wrap();
independent_fdp_parameter_wrapper::wrap();
reparametrisation_wrapper::wrap();
def("debug", &debug);
}
}}}}
|
State Before: α : Type ?u.310360
β : Type ?u.310363
a b c d : ℝ≥0∞
r p q : ℝ≥0
ha : a ≠ 0
ha' : a ≠ ⊤
h : b = c / a
⊢ a * b = c State After: no goals Tactic: rw [h, ENNReal.mul_div_cancel' ha ha'] State Before: α : Type ?u.310360
β : Type ?u.310363
a b c d : ℝ≥0∞
r p q : ℝ≥0
ha : a ≠ 0
ha' : a ≠ ⊤
h : a * b = c
⊢ b = c / a State After: no goals Tactic: rw [← h, mul_div_assoc, ENNReal.mul_div_cancel' ha ha'] |
(* Copyright (c) 2011. Greg Morrisett, Gang Tan, Joseph Tassarotti,
Jean-Baptiste Tristan, and Edward Gan.
This file is part of RockSalt.
This file 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.
*)
(** Broke out the reasoning for the "masked jumps" used in the NaCL verifier
so I don't have to wait for long compile times on DFACorrectness.v
*)
Require Import Coqlib.
Require Import Parser.
Require Import Ascii.
Require Import String.
Require Import List.
Require Import Bits.
Require Import Decode.
Require Import ReinsVerifierDFA.
Require Import Eqdep.
Unset Automatic Introduction.
Set Implicit Arguments.
Require ExtrOcamlString.
Require ExtrOcamlNatBigInt.
Require ExtrOcamlNatInt.
Import X86_PARSER_ARG.
Import X86_PARSER.
Import X86_BASE_PARSER.
Import X86Syntax.
Require Import ReinsDFACorrectness.
Hint Constructors in_parser.
Import ABSTRACT_MAKE_DFA.
Lemma reinsjmp_nonIAT_parser_splits' :
forall s v,
in_parser reinsjmp_nonIAT_mask (flat_map byte_explode s) v ->
exists s1, exists s2, exists r,
(r <> ESP /\
flat_map byte_explode s = s1 ++ s2 /\
in_parser (reinsjmp_nonIAT_MASK_p r) s1 (fst v) /\
in_parser (reinsjmp_nonIAT_JMP_p r |+| reinsjmp_nonIAT_CALL_p r) s2 (snd v)) \/
(r = EAX /\
flat_map byte_explode s = s1 ++ s2 /\
in_parser reinsjmp_nonIAT_MASK_EAX25_p s1 (fst v) /\
in_parser (reinsjmp_nonIAT_JMP_p r |+| reinsjmp_nonIAT_CALL_p r) s2 (snd v)).
Proof.
unfold reinsjmp_nonIAT_mask, reinsjmp_nonIAT_p, reinsjmp_nonIAT_EAX25_p. simpl. unfold never.
intros.
repeat pinv ;
simpl ;
econstructor ; econstructor ; econstructor ;
(left ; repeat split ; eauto ; try congruence ;
match goal with
| [ H : in_parser (reinsjmp_nonIAT_JMP_p _) _ _ |- _ ] => eapply Alt_left_pi
| [ H : in_parser (reinsjmp_nonIAT_CALL_p _) _ _ |- _ ] => eapply Alt_right_pi
end ; exact H0) ||
(right ; repeat split ; eauto ; try congruence ;
match goal with
| [ H : in_parser (reinsjmp_nonIAT_JMP_p _) _ _ |- _ ] => eapply Alt_left_pi
| [ H : in_parser (reinsjmp_nonIAT_CALL_p _) _ _ |- _ ] => eapply Alt_right_pi
end ; exact H0).
Qed.
Lemma reinsjmp_IAT_JMP_or_RET_parser_splits' :
forall s v,
in_parser reinsjmp_IAT_JMP_or_RET_mask (flat_map byte_explode s) v ->
exists s1, exists s2,
flat_map byte_explode s = s1 ++ s2 /\
in_parser (reinsjmp_IAT_or_RET_MASK_p) s1 (fst v) /\
in_parser (reinsjmp_IAT_JMP_p |+| RET_p) s2 (snd v).
Proof.
unfold reinsjmp_IAT_JMP_or_RET_mask, reinsjmp_IAT_JMP_or_RET_p. simpl. unfold never.
intros.
repeat pinv ; simpl ;
econstructor ; econstructor ; econstructor ;
repeat split ; eauto ; try congruence ;
match goal with
| [ H : in_parser (reinsjmp_IAT_JMP_p) _ _ |- _ ] => eapply Alt_left_pi
| [ H : in_parser (RET_p) _ _ |- _ ] => eapply Alt_right_pi
end ; exact H0.
Qed.
Lemma byte_explode_bits b :
exists b1,exists b2,exists b3,exists b4,exists b5,exists b6,exists b7,exists b8,
byte_explode b = b1::b2::b3::b4::b5::b6::b7::b8::nil.
Proof.
unfold byte_explode. repeat econstructor.
Qed.
Local Open Scope nat_scope.
Lemma split_bytes_n :
forall n bs x1 x2,
flat_map byte_explode bs = x1 ++ x2 ->
length x1 = n * 8 ->
exists b1, exists b2,
bs = b1 ++ b2 /\ flat_map byte_explode b1 = x1 /\ flat_map byte_explode b2 = x2.
Proof.
induction n ; simpl ; intros.
destruct x1. simpl in *. exists nil. exists bs. simpl. auto.
simpl in H0. congruence.
destruct x1. simpl in H0. assert False ; [omega | contradiction].
destruct x1. simpl in H0. assert False ; [omega | contradiction].
destruct x1. simpl in H0. assert False ; [omega | contradiction].
destruct x1. simpl in H0. assert False ; [omega | contradiction].
destruct x1. simpl in H0. assert False ; [omega | contradiction].
destruct x1. simpl in H0. assert False ; [omega | contradiction].
destruct x1. simpl in H0. assert False ; [omega | contradiction].
destruct x1. simpl in H0. assert False ; [omega | contradiction].
simpl in H0. assert (length x1 = n*8). omega.
destruct bs.
simpl in H. congruence.
replace (flat_map byte_explode (i :: bs)) with
(byte_explode i ++ flat_map byte_explode bs) in H; auto.
generalize (byte_explode_bits i). t. rewrite H2 in *.
injection H . clear H. intros. subst.
specialize (IHn bs x1 x2 H H1). t.
exists (i::x). exists x0.
replace (flat_map byte_explode (i :: x)) with
(byte_explode i ++ (flat_map byte_explode x)) ; auto.
rewrite H2. split.
simpl. rewrite H3. reflexivity.
split.
rewrite H4. auto.
auto.
Qed.
Lemma reinsjmp_nonIAT_parser_splits :
forall bs v,
in_parser reinsjmp_nonIAT_mask (flat_map byte_explode bs) v ->
exists b1, exists b2, exists r,
(r <> ESP /\
bs = b1 ++ b2 /\
in_parser (reinsjmp_nonIAT_MASK_p r) (flat_map byte_explode b1) (fst v) /\
in_parser (reinsjmp_nonIAT_JMP_p r |+| reinsjmp_nonIAT_CALL_p r) (flat_map byte_explode b2) (snd v)) \/
(r = EAX /\
bs = b1 ++ b2 /\
in_parser reinsjmp_nonIAT_MASK_EAX25_p (flat_map byte_explode b1) (fst v) /\
in_parser (reinsjmp_nonIAT_JMP_p r |+| reinsjmp_nonIAT_CALL_p r) (flat_map byte_explode b2) (snd v)).
Proof.
intros.
generalize (reinsjmp_nonIAT_parser_splits' _ H). t. destruct H0. t.
assert (length x = 48).
unfold reinsjmp_nonIAT_MASK_p in H2. unfold bitsleft in H2.
unfold int32_p in H2. simpl in H2. repeat pinv ; simpl.
reflexivity. reflexivity.
generalize (split_bytes_n 6 _ _ _ H1 H4). t.
exists x2. exists x3. exists x1.
left. repeat split ; auto.
rewrite H6. exact H2.
rewrite H7. exact H3.
t. assert (length x = 40).
unfold reinsjmp_nonIAT_MASK_EAX25_p in H2. unfold bitsleft in H2.
unfold int32_p in H2. simpl in H2. repeat pinv ; simpl.
reflexivity. reflexivity.
generalize (split_bytes_n 5 _ _ _ H1 H4). t.
exists x2. exists x3. exists x1.
right. repeat split ; auto.
rewrite H6. exact H2.
rewrite H7. exact H3.
Qed.
Lemma reinsjmp_IAT_JMP_or_RET_parser_splits :
forall bs v,
in_parser reinsjmp_IAT_JMP_or_RET_mask (flat_map byte_explode bs) v ->
exists b1, exists b2,
bs = b1 ++ b2 /\
in_parser reinsjmp_IAT_or_RET_MASK_p (flat_map byte_explode b1) (fst v) /\
in_parser (reinsjmp_IAT_JMP_p |+| RET_p) (flat_map byte_explode b2) (snd v).
Proof.
intros. generalize (reinsjmp_IAT_JMP_or_RET_parser_splits' _ H). t.
assert (length x = 56).
unfold reinsjmp_IAT_or_RET_MASK_p in H1. unfold bitsleft in H1.
unfold int32_p in H1. simpl in H1. repeat pinv ; simpl ; auto.
generalize (split_bytes_n 7 _ _ _ H0 H3). t. exists x1. exists x2.
repeat split ; auto.
rewrite H5. exact H1.
rewrite H6. exact H2.
Qed.
Import CheckDeterministic.
Lemma byte2token_app xs n1 n2 :
List.map byte2token xs = n1 ++ n2 ->
exists b1, exists b2,
xs = b1 ++ b2 /\ List.map byte2token b1 = n1 /\ List.map byte2token b2 = n2.
Proof.
induction xs.
simpl. intros. generalize (nil_is_nil_app_nil _ _ H). t. subst.
exists nil. exists nil. auto.
simpl. intros. destruct n1.
simpl in *. destruct n2 ; try congruence.
injection H . clear H. intros. specialize (IHxs nil n2 H). t. subst.
exists x. exists (a::x0).
assert (x = nil).
destruct x ; auto. simpl in H2. congruence. subst. simpl. auto.
simpl in *. injection H. clear H. intros.
specialize (IHxs n1 n2 H). t.
exists (a::x). exists x0. rewrite H1.
split ; auto. simpl.
split.
rewrite H0. rewrite H2. reflexivity.
exact H3.
Qed.
Lemma nat2bools_byte2token_is_byte_explode xs :
flat_map nat2bools (List.map byte2token xs) = flat_map byte_explode xs.
Proof.
induction xs.
auto.
replace (flat_map byte_explode (a::xs)) with
(byte_explode a ++ (flat_map byte_explode xs)) ; auto.
replace (flat_map nat2bools (List.map byte2token (a::xs))) with
(nat2bools (byte2token a) ++ (flat_map nat2bools (List.map byte2token xs))) ; auto.
rewrite IHxs. replace (nat2bools (byte2token a)) with (byte_explode a) ; auto.
clear IHxs. unfold byte_explode, nat2bools.
replace (Z_of_nat (byte2token a)) with (Word.unsigned a) ; auto.
unfold byte2token.
rewrite inj_Zabs_nat. unfold Word.unsigned. generalize (Word.intrange _ a).
intros. rewrite (Zabs_eq _). reflexivity. omega.
Qed.
Lemma reg_parser r s :
in_parser (bitslist (register_to_bools r)) s tt ->
in_parser reg s r.
Proof.
unfold reg, field. destruct r ; simpl ; intros ; repeat pinv ;
repeat econstructor ; eauto.
Qed.
Lemma mask_parser s :
in_parser (int32_p safeMask) s tt ->
in_parser (word @ (fun w : int32 => Imm_op w %% operand_t)) s (Imm_op safeMask).
Proof.
unfold word, byte, field, int32_p. simpl. intros.
repeat pinv.
repeat econstructor. repeat rewrite <- app_assoc.
repeat rewrite -> app_nil_l. eexists. vm_compute. reflexivity.
Qed.
Lemma mask_parser' s :
in_parser (int32_p safeMask) s tt ->
in_parser word s safeMask.
Proof.
unfold word, byte, field, int32_p. simpl. intros.
repeat pinv.
repeat econstructor. repeat rewrite <- app_assoc.
repeat rewrite -> app_nil_l. eexists. vm_compute. reflexivity.
Qed.
Lemma reinsjmp_nonIAT_MASK_subset r s i :
in_parser (reinsjmp_nonIAT_MASK_p r) s i ->
in_parser instruction_parser s (mkPrefix None None false false, i).
Proof.
unfold reinsjmp_nonIAT_MASK_p. intros.
unfold instruction_parser, instruction_parser_list. eapply in_alts_app.
left. eapply in_map_alts. replace s with (nil ++ s) ; auto.
econstructor ; eauto.
unfold prefix_parser_nooverride, option_perm2.
econstructor ; eauto.
eapply Alt_left_pi.
econstructor ; eauto. reflexivity.
unfold instr_parsers_nosize_pre. simpl.
unfold bitsleft in H. repeat
match goal with
| [ H : in_parser (_ @ _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t
| [ H : in_parser (_ $ _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t
end ; subst.
repeat match goal with
| [ |- in_parser ((AND_p _) |+| _) _ _ ] => eapply Alt_left_pi
| [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi
end.
unfold AND_p, logic_or_arith_p. eapply Alt_right_pi. eapply Alt_right_pi.
eapply Alt_right_pi. eapply Alt_left_pi.
econstructor. econstructor. econstructor. eauto.
econstructor. econstructor. eauto.
econstructor. econstructor. eauto.
econstructor. econstructor. eauto.
econstructor. eapply reg_parser. destruct x21. eauto.
unfold imm_op. simpl. eapply mask_parser. destruct x22.
eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.
eauto. eauto. eauto. eauto. eauto. eauto. eauto. simpl.
reflexivity.
Qed.
Lemma reinsjmp_nonIAT_MASK_EAX25_subset s i :
in_parser reinsjmp_nonIAT_MASK_EAX25_p s i ->
in_parser instruction_parser s (mkPrefix None None false false, i).
Proof.
unfold reinsjmp_nonIAT_MASK_EAX25_p. intros.
unfold instruction_parser, instruction_parser_list. eapply in_alts_app.
left. eapply in_map_alts. replace s with (nil ++ s) ; auto.
econstructor ; eauto.
unfold prefix_parser_nooverride, option_perm2.
econstructor ; eauto.
eapply Alt_left_pi.
econstructor ; eauto. reflexivity.
unfold instr_parsers_nosize_pre. simpl.
unfold bitsleft in H. repeat
match goal with
| [ H : in_parser (_ @ _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t
| [ H : in_parser (_ $ _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t
end ; subst.
(*0x25 AND*)
repeat match goal with
| [ |- in_parser ((AND_p _) |+| _) _ _ ] => eapply Alt_left_pi
| [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi
end.
unfold AND_p , logic_or_arith_p. eapply Alt_right_pi. eapply Alt_right_pi.
eapply Alt_right_pi. eapply Alt_right_pi. eapply Alt_right_pi. eapply Alt_left_pi.
econstructor. econstructor. econstructor. eauto.
econstructor. econstructor. eauto.
unfold imm_op. simpl. eapply mask_parser. destruct x8.
eauto. eauto. eauto. eauto. eauto. eauto. eauto.
reflexivity.
Qed.
Lemma in_any_char :
forall s c i,
in_parser (Char_p c) s i ->
in_parser Any_p s i.
Proof.
intros. pinv. eauto.
Qed.
Lemma in_any_char2 :
forall s c1 c2 i,
in_parser (Cat_p (Char_p c1) (Cat_p (Char_p c2) Eps_p)) s i ->
in_parser (Cat_p Any_p (Cat_p Any_p Eps_p)) s i.
Proof.
intros. repeat pinv.
econstructor ; eauto.
Qed.
Definition string_to_register (str : string) : register :=
match str with
| "000"%string => EAX
| "001"%string => ECX
| "010"%string => EDX
| "011"%string => EBX
| "100"%string => ESP
| "101"%string => EBP
| "110"%string => ESI
| "111"%string => EDI
| _ => EAX
end.
Lemma bits_bitslist :
forall str s i c1 c2 c3,
c1 = "0" \/ c1 = "1" ->
c2 = "0" \/ c2 = "1" ->
c3 = "0" \/ c3 = "1" ->
str = String c1 (String c2 (String c3 EmptyString)) ->
in_parser (bits str) s i ->
in_parser (bitslist (register_to_bools (string_to_register str))) s tt.
Proof.
intros.
repeat pinv ; psimp ; repeat pinv ; simpl ;
repeat (econstructor ; econstructor ; eauto).
Qed.
Lemma reinsjmp_IAT_or_RET_MASK_subset s i :
in_parser (reinsjmp_IAT_or_RET_MASK_p) s i ->
in_parser instruction_parser s (mkPrefix None None false false, i).
Proof.
unfold reinsjmp_IAT_or_RET_MASK_p. intros.
unfold instruction_parser, instruction_parser_list. eapply in_alts_app.
left. eapply in_map_alts. replace s with (nil ++ s) ; auto.
econstructor ; eauto.
unfold prefix_parser_nooverride, option_perm2.
econstructor ; eauto.
eapply Alt_left_pi.
econstructor ; eauto.
reflexivity.
unfold instr_parsers_nosize_pre. simpl.
repeat match goal with
| [ |- in_parser ((AND_p _) |+| _) _ _ ] => eapply Alt_left_pi
| [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi
end.
unfold AND_p, logic_or_arith_p.
repeat eapply Alt_right_pi. unfold bitsleft in H.
repeat match goal with
| [ H : in_parser (_ @ _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t
| [ H : in_parser (_ $ _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t
end ; subst.
econstructor. econstructor. econstructor. eauto.
econstructor. econstructor. eauto.
econstructor. econstructor. econstructor. econstructor. eexact H11.
econstructor. eexact H15.
unfold rm00. eapply Alt_right_pi. eapply Alt_left_pi.
econstructor. econstructor. eexact H19.
econstructor. econstructor. econstructor. econstructor. econstructor.
unfold bits in H23. simpl in H23. unfold field'. eapply in_any_char2.
eauto. eauto. eauto. eapply reg_parser.
apply bits_bitslist with
(str := "100"%string) (c1 := "1") (c2 := "0") (c3 := "0")
(i := x33) ; auto.
eexact H27. eauto. eauto. eauto.
econstructor. eapply Alt_right_pi. eapply Alt_right_pi. eapply Alt_right_pi.
eapply Alt_right_pi. eapply Alt_left_pi. eexact H30.
eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.
simpl. eauto.
econstructor. eapply mask_parser'. destruct x38. eexact H31.
eauto. eauto. eauto. eauto. eauto. eauto.
repeat rewrite <- app_assoc. reflexivity.
eauto. eauto.
simpl. assert (x37 = (true, (false, (false, tt)))).
unfold bits in H30. simpl in H30. repeat pinv. reflexivity.
rewrite -> H. simpl. reflexivity.
Qed.
Lemma reinsjmp_nonIAT_jump_subset r s i :
in_parser (reinsjmp_nonIAT_JMP_p r |+| reinsjmp_nonIAT_CALL_p r) s i ->
in_parser instruction_parser s (mkPrefix None None false false, i).
Proof.
intros. unfold instruction_parser, instruction_parser_list.
eapply in_alts_app. left. eapply in_map_alts.
replace s with (nil ++ s) ; auto.
econstructor ; eauto.
unfold prefix_parser_nooverride, option_perm2.
econstructor.
eapply Alt_left_pi.
econstructor ; eauto.
reflexivity.
unfold instr_parsers_nosize_pre. simpl.
repeat pinv.
repeat match goal with
| [ |- in_parser (JMP_p |+| _) _ _ ] => eapply Alt_left_pi
| [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi
end.
unfold reinsjmp_nonIAT_JMP_p, JMP_p in *.
eapply Alt_right_pi. eapply Alt_right_pi. eapply Alt_left_pi.
unfold bitsleft in H.
repeat match goal with
| [ H : in_parser (_ @ _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t
| [ H : in_parser (_ $ _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t
end ; subst.
econstructor. econstructor. econstructor. eexact H3.
econstructor. econstructor. eexact H7.
unfold ext_op_modrm2.
econstructor. repeat eapply Alt_right_pi.
econstructor. eexact H11.
econstructor. eexact H14.
unfold rm11. econstructor. eapply reg_parser. destruct x18. eexact H15.
eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. auto. eauto.
eauto. simpl. reflexivity.
repeat match goal with
| [ |- in_parser (CALL_p |+| _) _ _ ] => eapply Alt_left_pi
| [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi
end.
unfold reinsjmp_nonIAT_CALL_p, CALL_p in *. eapply Alt_right_pi.
eapply Alt_left_pi. unfold bitsleft in H.
repeat match goal with
| [ H : in_parser (_ @ _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t
| [ H : in_parser (_ $ _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t
end ; subst.
econstructor. econstructor. econstructor. eexact H3.
econstructor. econstructor. eexact H7.
unfold ext_op_modrm2. econstructor. repeat eapply Alt_right_pi.
econstructor. eexact H11.
econstructor. eexact H14.
unfold rm11. econstructor. eapply reg_parser. destruct x18. eexact H15.
eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. auto. eauto.
eauto. simpl. reflexivity.
Qed.
Lemma reinsjmp_IAT_JMP_or_RET_jump_subset s i :
in_parser (reinsjmp_IAT_JMP_p |+| RET_p) s i ->
in_parser instruction_parser s (mkPrefix None None false false, i).
Proof.
intros. unfold instruction_parser, instruction_parser_list. eapply in_alts_app.
left. eapply in_map_alts.
replace s with (nil ++ s) ; auto.
econstructor ; eauto.
unfold prefix_parser_nooverride, option_perm2.
econstructor.
eapply Alt_left_pi.
econstructor ; eauto.
reflexivity.
unfold instr_parsers_nosize_pre. simpl.
repeat pinv.
repeat match goal with
| [ |- in_parser (JMP_p |+| _) _ _ ] => eapply Alt_left_pi
| [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi
end.
unfold reinsjmp_IAT_JMP_p, JMP_p in *. eapply Alt_right_pi. eapply Alt_right_pi.
eapply Alt_left_pi. unfold bitsleft in H.
repeat match goal with
| [ H : in_parser (_ @ _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t
| [ H : in_parser (_ $ _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t
end ; subst.
econstructor. econstructor. econstructor. eexact H3.
econstructor. econstructor. eexact H7.
unfold ext_op_modrm2. econstructor. eapply Alt_left_pi.
econstructor. eexact H11.
econstructor. eexact H15.
unfold rm00. eapply Alt_right_pi. eapply Alt_right_pi. eapply Alt_right_pi.
econstructor. econstructor. eexact H19.
eexact H20. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.
eauto. eauto. eauto. eauto. eauto. eauto.
repeat match goal with
| [ |- in_parser (RET_p |+| _) _ _ ] => eapply Alt_left_pi
| [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi
end.
exact H.
Qed.
Lemma reinsjmp_nonIAT_parser_inv r s1 s2 i1 i2:
r <> ESP ->
in_parser (reinsjmp_nonIAT_MASK_p r) s1 i1 ->
in_parser (reinsjmp_nonIAT_JMP_p r |+| reinsjmp_nonIAT_CALL_p r) s2 i2 ->
reinsjmp_nonIAT_mask_instr (mkPrefix None None false false) i1
(mkPrefix None None false false) i2 = true.
Proof.
unfold reinsjmp_nonIAT_MASK_p, reinsjmp_nonIAT_JMP_p, reinsjmp_nonIAT_CALL_p.
intros.
repeat pinv ; unfold reinsjmp_nonIAT_mask_instr ; simpl ;
destruct (register_eq_dec r ESP) ;
try congruence ;
destruct (register_eq_dec r r) ;
try congruence.
Qed.
Lemma reinsjmp_nonIAT_parser_EAX25_inv s1 s2 i1 i2:
in_parser reinsjmp_nonIAT_MASK_EAX25_p s1 i1 ->
in_parser (reinsjmp_nonIAT_JMP_p EAX |+| reinsjmp_nonIAT_CALL_p EAX) s2 i2 ->
reinsjmp_nonIAT_mask_instr (mkPrefix None None false false) i1
(mkPrefix None None false false) i2 = true.
Proof.
unfold reinsjmp_nonIAT_MASK_EAX25_p, reinsjmp_nonIAT_JMP_p, reinsjmp_nonIAT_CALL_p.
intros.
repeat pinv ; unfold reinsjmp_nonIAT_mask_instr ; simpl ; reflexivity.
Qed.
Lemma reinsjmp_IAT_JMP_or_RET_parser_inv s1 s2 i1 i2:
in_parser (reinsjmp_IAT_or_RET_MASK_p) s1 i1 ->
in_parser (reinsjmp_IAT_JMP_p |+| RET_p) s2 i2 ->
reinsjmp_IAT_or_RET_mask_instr (mkPrefix None None false false) i1
(mkPrefix None None false false) i2 = true.
Proof.
unfold reinsjmp_IAT_or_RET_MASK_p, reinsjmp_IAT_JMP_p, RET_p.
intros.
repeat pinv ; unfold reinsjmp_IAT_or_RET_mask_instr ; simpl ; reflexivity.
Qed.
Lemma reinsjmp_nonIAT_dfa_corr1 :
forall (d:DFA),
abstract_build_dfa 256 nat2bools 400 (par2rec reinsjmp_nonIAT_mask) = Some d ->
forall (bytes:list int8) (n:nat) (nats2:list nat),
dfa_recognize 256 d (List.map byte2token bytes) = Some (n,nats2) ->
exists bytes1, exists pfx1:prefix, exists ins1:instr, exists bytes2,
exists pfx2:prefix, exists ins2:instr,
in_parser reinsjmp_nonIAT_mask (flat_map byte_explode (bytes1 ++ bytes2))
(ins1,ins2) /\
in_parser instruction_parser (flat_map byte_explode bytes1) (pfx1,ins1) /\
in_parser instruction_parser (flat_map byte_explode bytes2) (pfx2,ins2) /\
n = length (bytes1 ++ bytes2) /\
bytes = bytes1 ++ bytes2 ++ (List.map nat_to_byte nats2) /\
reinsjmp_nonIAT_mask_instr pfx1 ins1 pfx2 ins2 = true /\
(forall ts3 ts4,
(length ts3 < length (bytes1 ++ bytes2))%nat ->
bytes = ts3 ++ ts4 ->
forall v0, ~ in_parser reinsjmp_nonIAT_mask (flat_map byte_explode ts3) v0).
Proof.
intros. subst.
rewrite build_dfa_eq in H.
generalize (dfa_recognize_corr _ _ _ _ H (List.map byte2token bytes)
(bytesLt256 _)).
clear H.
rewrite H0. clear H0.
mysimp.
generalize (byte2token_app _ _ _ H). t. subst.
rewrite (nat2bools_byte2token_is_byte_explode _) in H1.
generalize (reinsjmp_nonIAT_parser_splits _ H1). clear H1.
t. destruct H0. t. destruct x0. simpl in *.
exists x. exists (mkPrefix None None false false). exists i.
exists x3. exists (mkPrefix None None false false). exists i0.
split.
rewrite flat_map_app.
destruct x4 ; try congruence ;
repeat (try (eapply Alt_left_pi ; econstructor ; eauto ; fail)
; eapply Alt_right_pi).
split. apply (reinsjmp_nonIAT_MASK_subset H3).
split. eapply (reinsjmp_nonIAT_jump_subset H4).
split. rewrite H1. rewrite map_length. reflexivity.
split. subst. rewrite app_assoc.
assert (x2 = List.map nat_to_byte (List.map byte2token x2))
; [ idtac | congruence].
rewrite n2bs. reflexivity.
split. eapply reinsjmp_nonIAT_parser_inv ; eauto.
intros. rewrite H1 in H2.
specialize (H2 (List.map byte2token ts3) (List.map byte2token ts4)).
repeat rewrite map_length in H2.
specialize (H2 H5). subst. rewrite H6 in H2. rewrite map_app in H2.
specialize (H2 (eq_refl _)).
rewrite nat2bools_byte2token_is_byte_explode in H2.
intro. apply (H2 v0 H1).
t. destruct x0. simpl in *.
exists x. exists (mkPrefix None None false false). exists i.
exists x3. exists (mkPrefix None None false false). exists i0.
split.
rewrite flat_map_app.
destruct x4 ; try congruence ;
repeat (try (eapply Alt_left_pi ; econstructor ; eauto ; fail)
; eapply Alt_right_pi).
split. apply (reinsjmp_nonIAT_MASK_EAX25_subset H3).
split. eapply (reinsjmp_nonIAT_jump_subset H4).
split. rewrite H1. rewrite map_length. reflexivity.
split. subst. rewrite app_assoc.
assert (x2 = List.map nat_to_byte (List.map byte2token x2))
; [ idtac | congruence].
rewrite n2bs. reflexivity.
rewrite -> H0 in H4.
split. eapply reinsjmp_nonIAT_parser_EAX25_inv ; eauto.
intros. rewrite H1 in H2.
specialize (H2 (List.map byte2token ts3) (List.map byte2token ts4)).
repeat rewrite map_length in H2.
specialize (H2 H5). subst. rewrite H6 in H2. rewrite map_app in H2.
specialize (H2 (eq_refl _)).
rewrite nat2bools_byte2token_is_byte_explode in H2.
intro. apply (H2 v0 H0).
Qed.
Lemma reinsjmp_IAT_JMP_or_RET_dfa_corr1 :
forall (d:DFA),
abstract_build_dfa 256 nat2bools 400 (par2rec reinsjmp_IAT_JMP_or_RET_mask) = Some d ->
forall (bytes:list int8) (n:nat) (nats2:list nat),
dfa_recognize 256 d (List.map byte2token bytes) = Some (n,nats2) ->
exists bytes1, exists pfx1:prefix, exists ins1:instr, exists bytes2,
exists pfx2:prefix, exists ins2:instr,
in_parser reinsjmp_IAT_JMP_or_RET_mask (flat_map byte_explode (bytes1 ++ bytes2))
(ins1,ins2) /\
in_parser instruction_parser (flat_map byte_explode bytes1) (pfx1,ins1) /\
in_parser instruction_parser (flat_map byte_explode bytes2) (pfx2,ins2) /\
n = length (bytes1 ++ bytes2) /\
bytes = bytes1 ++ bytes2 ++ (List.map nat_to_byte nats2) /\
reinsjmp_IAT_or_RET_mask_instr pfx1 ins1 pfx2 ins2 = true /\
(forall ts3 ts4,
(length ts3 < length (bytes1 ++ bytes2))%nat ->
bytes = ts3 ++ ts4 ->
forall v0, ~ in_parser reinsjmp_IAT_JMP_or_RET_mask (flat_map byte_explode ts3) v0).
Proof.
intros. rewrite build_dfa_eq in H.
generalize (dfa_recognize_corr _ _ _ _ H (List.map byte2token bytes)
(bytesLt256 _)). clear H.
rewrite H0. clear H0. mysimp.
generalize (byte2token_app _ _ _ H). t. subst.
rewrite (nat2bools_byte2token_is_byte_explode _) in H1.
generalize (reinsjmp_IAT_JMP_or_RET_parser_splits _ H1). clear H1. t.
destruct x0. simpl in *.
exists x. exists (mkPrefix None None false false). exists i.
exists x3. exists (mkPrefix None None false false). exists i0.
split. rewrite flat_map_app. econstructor. eauto. eexact H3.
reflexivity. reflexivity.
split. apply (reinsjmp_IAT_or_RET_MASK_subset H1).
split. eapply (reinsjmp_IAT_JMP_or_RET_jump_subset H3).
split. rewrite H0. rewrite map_length. reflexivity.
split. subst. rewrite app_assoc.
assert (x2 = List.map nat_to_byte (List.map byte2token x2))
; [ idtac | congruence].
rewrite n2bs. reflexivity.
split. eapply reinsjmp_IAT_JMP_or_RET_parser_inv ; eauto.
intros. rewrite H0 in H2. specialize (H2 (List.map byte2token ts3)
(List.map byte2token ts4)). repeat rewrite map_length in H2.
specialize (H2 H4). subst. rewrite H5 in H2. rewrite map_app in H2.
specialize (H2 (eq_refl _)). rewrite nat2bools_byte2token_is_byte_explode in H2.
intro. apply (H2 v0 H0).
Qed.
Lemma flat_map_nil_is_nil x :
flat_map byte_explode x = nil -> x = nil.
Proof.
induction x ; intros.
reflexivity.
replace (flat_map byte_explode (a :: x))
with (byte_explode a ++ (flat_map byte_explode x)) in H ; auto.
generalize (nil_is_nil_app_nil _ _ (eq_sym H)). t.
clear IHx H H1.
assert False ; try contradiction.
unfold byte_explode in H0. congruence.
Qed.
(** This should get placed in DFACorrectness and used for the other 2 DFAs. *)
Lemma in_parser_implies_simple_parse
bytes1 pfx ins bytes2 :
in_parser instruction_parser (flat_map byte_explode bytes1) (pfx,ins) ->
simple_parse (bytes1 ++ bytes2) = Some (pfx, ins, bytes2).
Proof.
unfold simple_parse ; intros.
Opaque instruction_parser.
generalize (@simple_parse'_corr2
instruction_parser (bytes1 ++ bytes2) initial_parser_state nil
(eq_refl _) (eq_refl _)).
simpl. intros.
assert (forall s1 s2, nil = s1 ++ s2 ->
apply_null (snd (parser2regexp instruction_parser))
(deriv_parse' (fst (parser2regexp instruction_parser))
(flat_map byte_explode s1))
(wf_derivs (snd (parser2regexp instruction_parser))
(flat_map byte_explode s1)
(fst (parser2regexp instruction_parser))
(p2r_wf instruction_parser initial_ctxt)) = nil).
intros. clear H0.
generalize (nil_is_nil_app_nil _ _ H1). t. subst.
generalize (min_count_not_null _ min_instruction_bits).
generalize instruction_parser.
clear H H1. simpl.
intro.
generalize (apply_null (snd(parser2regexp p)) (fst (parser2regexp p))).
assert (wf_derivs (snd (parser2regexp p)) nil (fst (parser2regexp p))
(p2r_wf p initial_ctxt) = p2r_wf p initial_ctxt).
apply Coqlib.proof_irrelevance.
generalize H. clear H.
unfold parser2regexp.
generalize (p2r_wf p initial_ctxt).
intros. rewrite <- H in H0. exact H0.
specialize (H0 H1). clear H1.
destruct (simple_parse' initial_parser_state (bytes1 ++ bytes2)).
destruct p. t. destruct p.
assert (length bytes1 >= length x).
assert (length bytes1 < length x -> False).
intros.
eapply (H2 bytes1 bytes2 (eq_refl _) H3 _ H). omega.
assert (exists s2, bytes1 = x ++ s2).
generalize bytes1 x H3 H0.
induction bytes0 ; destruct x0 ; simpl ; intros.
exists nil. reflexivity.
assert False.
omega.
contradiction.
subst. eauto.
injection H5 ; clear H5 ; t ; subst.
assert (length bytes0 >= length x0).
omega.
specialize (IHbytes0 _ H6 H5). t.
subst. eauto.
t. subst. rewrite app_ass in H0. generalize (app_inv_head _ _ _ H0).
intros. subst. rewrite flat_map_app in H. generalize (parser_determ H).
intros. specialize (H4 _ _ (p,i) (eq_refl _) H1). t.
injection H5 ; intros.
rewrite (flat_map_nil_is_nil _ H4). subst. auto.
specialize (H0 bytes1 bytes2 (pfx,ins) (eq_refl _)). contradiction.
Qed.
Lemma reinsjmp_nonIAT_dfa_corr :
forall (d:DFA),
abstract_build_dfa 256 nat2bools 400 (par2rec reinsjmp_nonIAT_mask) = Some d ->
forall (bytes:list int8) (n:nat) (nats2:list nat),
dfa_recognize 256 d (List.map byte2token bytes) = Some (n, nats2) ->
exists bytes1, exists pfx1:prefix, exists ins1:instr, exists bytes2,
exists pfx2:prefix, exists ins2:instr,
simple_parse bytes = Some ((pfx1,ins1), bytes2 ++ List.map nat_to_byte nats2) /\
simple_parse (bytes2 ++ List.map nat_to_byte nats2) =
Some ((pfx2,ins2), List.map nat_to_byte nats2) /\
reinsjmp_nonIAT_mask_instr pfx1 ins1 pfx2 ins2 = true /\
n = length (bytes1 ++ bytes2) /\
bytes = bytes1 ++ bytes2 ++ (List.map nat_to_byte nats2).
Proof.
intros d H bytes n nats2 H1.
generalize (@reinsjmp_nonIAT_dfa_corr1 d H bytes n nats2 H1). t.
exists x. exists x0. exists x1. exists x2. exists x3. exists x4.
repeat split ; auto.
rewrite H5. apply in_parser_implies_simple_parse. exact H2.
apply in_parser_implies_simple_parse. exact H3.
Qed.
Lemma reinsjmp_IAT_JMP_or_RET_dfa_corr :
forall (d:DFA),
abstract_build_dfa 256 nat2bools 400 (par2rec reinsjmp_IAT_JMP_or_RET_mask) = Some d ->
forall (bytes:list int8) (n:nat) (nats2:list nat),
dfa_recognize 256 d (List.map byte2token bytes) = Some (n, nats2) ->
exists bytes1, exists pfx1:prefix, exists ins1:instr, exists bytes2,
exists pfx2:prefix, exists ins2:instr,
simple_parse bytes = Some ((pfx1,ins1), bytes2 ++ List.map nat_to_byte nats2) /\
simple_parse (bytes2 ++ List.map nat_to_byte nats2) =
Some ((pfx2,ins2), List.map nat_to_byte nats2) /\
reinsjmp_IAT_or_RET_mask_instr pfx1 ins1 pfx2 ins2 = true /\
n = length (bytes1 ++ bytes2) /\
bytes = bytes1 ++ bytes2 ++ (List.map nat_to_byte nats2).
Proof.
intros d H bytes n nats2 H1.
generalize (@reinsjmp_IAT_JMP_or_RET_dfa_corr1 d H bytes n nats2 H1). t.
exists x. exists x0. exists x1. exists x2. exists x3. exists x4.
repeat split ; auto.
rewrite H5. apply in_parser_implies_simple_parse. exact H2.
apply in_parser_implies_simple_parse. exact H3.
Qed.
Lemma reinsjmp_nonIAT_mask_dfa_length :
forall (d:DFA),
(* Need to use abstract_build_dfa for the same reason as above I believe *)
abstract_build_dfa 256 nat2bools 400 (par2rec reinsjmp_nonIAT_mask) = Some d ->
forall (bytes:list int8) (n:nat) (nats2:list nat),
dfa_recognize 256 d (List.map byte2token bytes) = Some (n, nats2) ->
(n <= 15).
Proof.
intros. apply reinsjmp_nonIAT_dfa_corr1 in H0.
destruct H0. destruct H0. destruct H0. destruct H0.
destruct H0. destruct H0. destruct H0.
destruct H1. destruct H2. destruct H3.
assert (max_bit_count reinsjmp_nonIAT_mask = Some 64).
vm_compute. reflexivity.
apply max_count_corr in H0.
rewrite H5 in H0.
rewrite byte_explode_mult_len in H0.
rewrite H3. omega.
auto.
Qed.
Lemma reinsjmp_IAT_JMP_or_RET_mask_dfa_length :
forall (d:DFA),
(* Need to use abstract_build_dfa for the same reason as above I believe *)
abstract_build_dfa 256 nat2bools 400 (par2rec reinsjmp_IAT_JMP_or_RET_mask) = Some d ->
forall (bytes:list int8) (n:nat) (nats2:list nat),
dfa_recognize 256 d (List.map byte2token bytes) = Some (n, nats2) ->
(n <= 15).
Proof.
intros. apply reinsjmp_IAT_JMP_or_RET_dfa_corr1 in H0.
destruct H0. destruct H0. destruct H0. destruct H0.
destruct H0. destruct H0. destruct H0.
destruct H1. destruct H2. destruct H3.
assert (max_bit_count reinsjmp_IAT_JMP_or_RET_mask = Some 104).
vm_compute; trivial.
apply max_count_corr in H0.
rewrite H5 in H0.
rewrite byte_explode_mult_len in H0.
rewrite H3. omega.
auto.
Qed.
|
lemma Poly_replicate_0 [simp]: "Poly (replicate n 0) = 0" |
[STATEMENT]
lemma le_spvec_empty1_sparse_row[rule_format]: "(sorted_spvec b) \<longrightarrow> (le_spvec [] b = (0 <= sparse_row_vector b))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sorted_spvec b \<longrightarrow> le_spvec [] b = (0 \<le> sparse_row_vector b)
[PROOF STEP]
apply (induct b)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. sorted_spvec [] \<longrightarrow> le_spvec [] [] = (0 \<le> sparse_row_vector [])
2. \<And>a b. sorted_spvec b \<longrightarrow> le_spvec [] b = (0 \<le> sparse_row_vector b) \<Longrightarrow> sorted_spvec (a # b) \<longrightarrow> le_spvec [] (a # b) = (0 \<le> sparse_row_vector (a # b))
[PROOF STEP]
apply (simp_all add: sorted_spvec_cons1)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>a b. sorted_spvec b \<longrightarrow> le_spvec [] b = (0 \<le> sparse_row_vector b) \<Longrightarrow> sorted_spvec (a # b) \<longrightarrow> le_spvec [] (a # b) = (0 \<le> singleton_matrix 0 (fst a) (snd a) + sparse_row_vector b)
[PROOF STEP]
apply (intro strip)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>a b. \<lbrakk>sorted_spvec b \<longrightarrow> le_spvec [] b = (0 \<le> sparse_row_vector b); sorted_spvec (a # b)\<rbrakk> \<Longrightarrow> le_spvec [] (a # b) = (0 \<le> singleton_matrix 0 (fst a) (snd a) + sparse_row_vector b)
[PROOF STEP]
apply (subst disj_matrices_add_zero_le)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>a b. \<lbrakk>sorted_spvec b \<longrightarrow> le_spvec [] b = (0 \<le> sparse_row_vector b); sorted_spvec (a # b)\<rbrakk> \<Longrightarrow> disj_matrices (singleton_matrix 0 (fst a) (snd a)) (sparse_row_vector b)
2. \<And>a b. \<lbrakk>sorted_spvec b \<longrightarrow> le_spvec [] b = (0 \<le> sparse_row_vector b); sorted_spvec (a # b)\<rbrakk> \<Longrightarrow> le_spvec [] (a # b) = (0 \<le> singleton_matrix 0 (fst a) (snd a) \<and> 0 \<le> sparse_row_vector b)
[PROOF STEP]
apply (auto simp add: disj_matrices_commute disj_sparse_row_singleton[OF order_refl] sorted_spvec_cons1)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
#' USGS data availability
#'
#' Imports a table of available parameters, period of record, and count. See \url{https://waterservices.usgs.gov/rest/Site-Service.html}
#' for more information.
#'
#' @param \dots see \url{https://waterservices.usgs.gov/rest/Site-Service.html} for a complete list of options. A list of arguments can also be supplied.
#' @param convertType logical, defaults to \code{TRUE}. If \code{TRUE}, the function will convert the data to dates, datetimes,
#' numerics based on a standard algorithm. If false, everything is returned as a character
#' @keywords data import USGS web service
#' @return A data frame with the following columns:
#' \tabular{lll}{
#' Name \tab Type \tab Description \cr
#' agency_cd \tab character \tab The NWIS code for the agency reporting the data\cr
#' site_no \tab character \tab The USGS site number \cr
#' station_nm \tab character \tab Site name \cr
#' site_tp_cd \tab character \tab Site type \cr
#' dec_lat_va \tab numeric \tab Decimal latitude\cr
#' dec_long_va \tab numeric \tab Decimal longitude \cr
#' coord_acy_cd \tab character \tab Latitude-longitude accuracy \cr
#' dec_coord_datum_cd \tab character \tab Decimal Latitude-longitude datum \cr
#' alt_va \tab character \tab Altitude of Gage or land surface \cr
#' alt_acy_va \tab character \tab Altitude accuracy \cr
#' alt_datum_cd \tab character \tab Altitude datum \cr
#' huc_cd \tab character \tab Hydrologic unit code \cr
#' data_type_cd \tab character \tab Data type \cr
#' parm_cd \tab character \tab Parameter code \cr
#' stat_cd \tab character \tab Statistical code \cr
#' dd_nu \tab character \tab Internal database key \cr
#' loc_web_ds \tab character \tab Additional measurement description \cr
#' medium_grp_cd \tab character \tab Medium group code \cr
#' parm_grp_cd \tab character \tab Parameter group code \cr
#' srs_id \tab character \tab SRS ID \cr
#' access_cd \tab character \tab Access code \cr
#' begin_date \tab Date \tab Begin date \cr
#' end_date \tab Date \tab End date \cr
#' count_nu \tab integer \tab Record count\cr
#' parameter_group_nm \tab character \tab Parameter group name \cr
#' parameter_nm \tab character \tab Parameter name \cr
#' casrn \tab character \tab Chemical Abstracts Service (CAS) Registry Number \cr
#' srsname \tab character \tab Substance Registry Services \cr
#' parameter_units \tab character \tab Parameter units \cr
#' }
#'
#' There are also several useful attributes attached to the data frame:
#' \tabular{lll}{
#' Name \tab Type \tab Description \cr
#' url \tab character \tab The url used to generate the data \cr
#' comment \tab character \tab Header comments from the RDB file \cr
#' queryTime \tab POSIXct \tab The time the data was returned \cr
#' }
#' @export
#' @examplesIf is_dataRetrieval_user()
#' \donttest{
#'
#' availableData <- whatNWISdata(siteNumber = '05114000')
#' # To find just unit value ('instantaneous') data:
#' uvData <- whatNWISdata(siteNumber = '05114000',service="uv")
#' uvDataMulti <- whatNWISdata(siteNumber = c('05114000','09423350'),service=c("uv","dv"))
#' flowAndTemp <- whatNWISdata(stateCd = "WI", service = "uv",
#' parameterCd = c("00060","00010"),
#' statCd = "00003")
#'
#' }
whatNWISdata <- function(..., convertType=TRUE){
matchReturn <- convertLists(...)
if("service" %in% names(matchReturn)){
service <- matchReturn$service
if(any(service %in% c("qw", "qwdata"))){
.Deprecated(old = "whatNWISdata", package = "dataRetrieval",
new = "whatWQPdata",
msg = "NWIS qw web services are being retired. Please see the vignette
'Changes to NWIS QW services' for more information.")
}
} else {
service <- "all"
}
if("statCd" %in% names(matchReturn)){
statCd <- matchReturn$statCd
matchReturn <- matchReturn[names(matchReturn) != "statCd"]
} else {
statCd <- "all"
}
if("parameterCd" %in% names(matchReturn)){
parameterCd <- matchReturn$parameterCd
matchReturn[["parameterCd"]] <- NULL
} else {
parameterCd <- "all"
}
matchReturn$service <- "site"
valuesList <- readNWISdots(matchReturn)
values <- sapply(valuesList$values, function(x) URLencode(x))
if(any(service == "iv")){
service[service == "iv"] <- "uv"
}
urlSitefile <- drURL('site', Access=pkg.env$access, seriesCatalogOutput='true',arg.list=values)
SiteFile <- importRDB1(urlSitefile, asDateTime = FALSE, convertType = convertType)
if(!("all" %in% service)){
SiteFile <- SiteFile[SiteFile$data_type_cd %in% service,]
}
if(!("all" %in% statCd)){
SiteFile <- SiteFile[SiteFile$stat_cd %in% c(statCd,NA),]
}
if(!("all" %in% parameterCd)){
SiteFile <- SiteFile[SiteFile$parm_cd %in% parameterCd,]
}
if(nrow(SiteFile) > 0 & convertType){
SiteFile$begin_date <- as.Date(lubridate::parse_date_time(SiteFile$begin_date, c("Ymd", "mdY", "Y!")))
SiteFile$end_date <- as.Date(lubridate::parse_date_time(SiteFile$end_date, c("Ymd", "mdY", "Y!")))
}
return(SiteFile)
}
|
/**
*
* @file qwrapper_cgemv_tile.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 Mark Gates
* @date 2010-11-15
* @generated c Tue Jan 7 11:44:59 2014
*
**/
#include <cblas.h>
#include "common.h"
/***************************************************************************//**
*
* Version of zgemv for tile storage, to avoid dependency problem when
* computations are done within the tile. alpha and beta are passed as
* pointers so they can depend on runtime values.
*
* @param[in] Alock
* Pointer to tile owning submatrix A.
*
* @param[in] xlock
* Pointer to tile owning subvector x.
*
* @param[in] ylock
* Pointer to tile owning subvector y.
*
**/
void QUARK_CORE_cgemv_tile(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum trans,
int m, int n,
const PLASMA_Complex32_t *alpha, const PLASMA_Complex32_t *A, int lda,
const PLASMA_Complex32_t *x, int incx,
const PLASMA_Complex32_t *beta, PLASMA_Complex32_t *y, int incy,
const PLASMA_Complex32_t *Alock,
const PLASMA_Complex32_t *xlock,
const PLASMA_Complex32_t *ylock)
{
/* Quick return. Bad things happen if sizeof(...)*m*n is zero in QUARK_Insert_Task */
if ( m == 0 || n == 0 )
return;
DAG_SET_PROPERTIES("gemv", "lightslateblue");
QUARK_Insert_Task(quark, CORE_cgemv_tile_quark, task_flags,
sizeof(PLASMA_enum), &trans, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex32_t), alpha, INPUT,
sizeof(PLASMA_Complex32_t)*m*n, A, NODEP, /* input; see Alock */
sizeof(int), &lda, VALUE,
sizeof(PLASMA_Complex32_t)*n, x, NODEP, /* input; see xlock */
sizeof(int), &incx, VALUE,
sizeof(PLASMA_Complex32_t), beta, INPUT,
sizeof(PLASMA_Complex32_t)*m, y, NODEP, /* inout; see ylock */
sizeof(int), &incy, VALUE,
sizeof(PLASMA_Complex32_t)*m*n, Alock, INPUT,
sizeof(PLASMA_Complex32_t)*n, xlock, INPUT,
sizeof(PLASMA_Complex32_t)*m, ylock, INOUT,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_cgemv_tile_quark = PCORE_cgemv_tile_quark
#define CORE_cgemv_tile_quark PCORE_cgemv_tile_quark
#endif
void CORE_cgemv_tile_quark(Quark *quark)
{
PLASMA_enum trans;
int m, n, lda, incx, incy;
const PLASMA_Complex32_t *alpha, *beta;
const PLASMA_Complex32_t *A, *x;
PLASMA_Complex32_t *y;
quark_unpack_args_11( quark, trans, m, n, alpha, A, lda, x, incx, beta, y, incy );
cblas_cgemv(
CblasColMajor,
(CBLAS_TRANSPOSE)trans,
m, n,
CBLAS_SADDR(*alpha), A, lda,
x, incx,
CBLAS_SADDR(*beta), y, incy );
}
|
Cars 140-142 were originally part of a large order of cars built by the St. Louis Car Co. for the Third Avenue Ry. of New York. These cars were resold in small lots to other companies all over the country. According to Buckley, these three, originally numbered 200-202, came to the ITS in June 1902, and were assigned to Danville city service before 1914; they were retired before 1920. This picture shows car 140 with its original door configuration and very worn paint. It has couplers, probably to provide for it to tow or be towed when necessary. |
module Issue533 where
data Empty : Set where
empty : {A B : Set} → (B → Empty) → B → A
empty f x with f x
... | ()
fail : ∀ {A : Set} → Empty → A
fail {A} = empty absurd
where
absurd : _ → Empty
absurd ()
-- should check (due to postponed emptyness constraint, see issue 479)
|
subroutine equilibration ( preeqObj, calcVars, exciton, results )
! ======================================================================
!
! Calculates pre-equlibrium and equlibrium particle emission.
! Various parts removed to separate subroutines to streamline
! the structure. 10/20/03
!
! Called by: simulatePreequilibrium
!
! Calls: AUXL FAM MOLNIX PEQEMT PREQAUX STSTCS
!
! CEM95 written by S. G. Mashnik
! Edited by A. J. Sierk, LANL T-2 February, 1996.
! Edited by A. J. Sierk, LANL T-2 November, 1997.
! Modified by AJS, February-March, 1999.
! Modified by SGM to include reduced masses, 1999
! Modified by SGM at 06/16/2000
! Last modification by SGM of 04/27/01, to get the module for CEM2k
! "Last" change: 13-AUG-2003 by NVMokhov
! Modified by A. J. Sierk, LANL T-16, October, 2003.
! Modified by K. K. Gudima, December, 2004.
! Edited by AJS, January, 2005.
! Edited by SGM 07/09/06 to account for the KKG 06/23/06 changes
! to use Fermi break-up model in Preco and Evap when A < 13.
! Edited by AJS, LANL T-2, December, 2011.
! Edited by LMK, XCP-3, July 2013 (included error protection).
! Modified by LMK, 2014-2015, for expanison of preeq to heavy ions
!
! ======================================================================
use, intrinsic :: iso_fortran_env, only: int32, real64
use preequilibriumParams, only : zro, one, two, thr, thousand, ato3rd, emnucb, &
& emnuct
implicit none
class(Preequilibrium), intent(inout) :: preeqObj
type(preequilibriumCalculation), intent(inout) :: calcVars
type(preeqExcitonData), intent(inout) :: exciton
type(preequilibriumResults), intent(inout) :: results
integer(int32) :: ipflg, k, lm, nsp
real(real64) :: am, pevap, ppre, rnp, rr, temp
logical preqgo
! ======================================================================
! Nucleus has low E* ( < 3 MeV) such that no preequilibrium emission will occur
if (results%residual%thermEnergy < thr) then
! Keep track of nuclei returned with less than 3 MeV of E*:
! Residual is stable
results%residual%state = stableState
! Check for photon emission:
if ( preeqObj%usePhotonEmission ) then
call preeqObj%photonEmission( results%progenyBnk( results%numProgeny ), &
& results%residual)
end if
return
endif
! ---------------------------------
! Beginning of main decay loop:
! ---------------------------------
do k = 1, results%maxProgeny
! Undergo Fermi Break-up if E* > E_binding (i.e. small nuclei)
if ( preeqObj%fbuObj%recommendFermiBreakUp(results%residual%numBaryons) ) then
call preeqObj%fermiPreeqInterface (results%residual, results )
results%residual%state = fermiBreakupState
return
endif
! Obtain energy information for residual
! (mass excess)
calcVars%dl = &
& preeqObj%molEnergy%defineEnergy &
& (calcVars%iz, calcVars%in, 2)
! (Pairing gap energies)
pevap = preeqObj%molEnergy%defineEnergy &
& (calcVars%iz, calcVars%in, 3)
! (Thermal energy of nucleus at rotating ground state)
results%residual%thermEnergy = results%residual%kinEnergy - pevap - results%residual%rotEnergy
! Determine if excited nucleus has low E* (no preequilibrium/evaporation emissions will occur below this threshold)
if (results%residual%thermEnergy <= 0.1d0) then
! Residual nucleus has reached a stable state
! NOTE: No compound nucleus remains at this point; it has reached a ground state (stable)
results%residual%state = stableState
! Check for photon emission:
if ( preeqObj%usePhotonEmission ) then
call preeqObj%photonEmission( results%progenyBnk( results%numProgeny ), &
& results%residual)
end if
return
endif
! Set up auxiliary quantities for finding prequilibrium
! emission widths:
am = preeqObj%fam (results%residual%numBaryons, results%residual%numProtons, &
& results%residual%thermEnergy, calcVars, 0)
calcVars%ac = 0.595d0*am
call preeqObj%preqaux (calcVars, rr, results)
! nsp is the number of excitons at which a compound nucleus is
! assumed to be formed.
nsp = int( sqrt( abs( 1.19d0 * am * results%residual%numBaryons * &
& results%residual%kinEnergy + 0.5d0 ) ) )
preqgo = (preeqObj%options%excludePreeq == 0) .and. (rr > zro)
lm = 0
10 continue
! Restore old logic of sharp transition when n > nsp AJS 07/08/05.
temp = dble(nsp)
if (temp < div0Lim .and. temp > -div0Lim) then
temp = div0Lim
write(preeqObj%io%message,2000) "172"
call preeqObj%io%print(4, 3, preeqObj%io%message)
end if
rnp = dble(exciton%numTotal)/temp
! Probability of undergoing pre-equilibrium emission (Eqn. 38 in CEM Manual)
! NOTE: The equation used is NOT the same as in the Manual! Either...
! (a) the manual needs corrected, or...
! (b) the parameters used ought to be refit.
ppre = one - exp(-0.5d0*((rnp - one)/preeqObj%options%emissionWidth)**2) ! Gaussian Probability Density Equation
! ppre = one - exp( -(rnp - one) / (2 * preeqObj%options%emissionWidth**2) ) ! Eqn. 38 of LA-UR-12-01364 (CEM Manual [2012])
if (exciton%numTotal < nsp .and. preeqObj%rng() < ppre .and. preqgo) then
! **************** Pre-equilibrium emission *************************
ipflg = 0
calcVars%exn = dble(exciton%numTotal)
! Undergo preequilibrium emission
call preeqObj%peqemt (calcVars, exciton, lm, ipflg, results)
! ipflg = 1 if number of excitons has changed;
if (ipflg == 1) go to 10
! Otherwise, prequilibrium particle of type lm was emitted (progeny stored into bank)
else
! ****************** equilibrium emission ***************************
! Calculate statistics on average E*, Z, A, L when nucleus enters
! statistical decay phase.
results%residual%state = compoundState
return
endif
end do
! Preequilibrium particle bank is completely filled during equilibration
write(preeqObj%io%message,1000) k
call preeqObj%io%print(1, 3, preeqObj%io%message)
write(preeqObj%io%message,1100)
call preeqObj%io%print(1, 3, preeqObj%io%message)
results%simState = 1
return
! ======================================================================
1000 format("Preequilibrium progeny bank is full (", i3, " progeny created).", &
& "Cannot simulate further equilibration of excited residual nucleus.")
1100 format(" Results may be suspect.")
2000 format("Divide by zero error prevented in 'equlibration.90', line ", A)
! ======================================================================
end subroutine equilibration
|
module Type.Size.Proofs where
import Lvl
open import Data
open import Data.Proofs
open import Functional
open import Function.Equals
open import Function.Inverseᵣ
open import Function.Inverse
open import Function.Proofs
open import Logic
open import Logic.IntroInstances
open import Logic.Propositional
open import Logic.Predicate
open import Structure.Setoid
open import Structure.Function
open import Structure.Function.Domain
open import Structure.Function.Domain.Proofs
open import Structure.Relator.Equivalence
open import Structure.Relator.Ordering
open import Structure.Relator.Properties
open import Type
import Type.Size
private variable ℓ ℓ₁ ℓ₂ ℓₑ ℓₑ₁ ℓₑ₂ ℓₑ₃ : Lvl.Level
private variable T A B C : Type{ℓ}
module _ ⦃ equiv : Equiv{ℓₑ}(T) ⦄ where
open Type.Size
[≼]-maximum : (_≼_ T (T → T) ⦃ [⊜]-equiv ⦄)
[≼]-maximum = [∃]-intro(const) ⦃ intro(proof) ⦄ where
proof : ∀{x y} → (const(x) ⊜ const(y)) → (x ≡ y)
proof{x}{y} (intro fneq) = fneq{x}
[≍]-reflexivity-raw : (T ≍ T)
[≍]-reflexivity-raw = [∃]-intro(id) ⦃ id-bijective ⦄
[≼]-reflexivity-raw : (T ≼ T)
[≼]-reflexivity-raw = [∃]-intro(id) ⦃ id-injective ⦄
[≽]-reflexivity-raw : (T ≽ T)
[≽]-reflexivity-raw = [∃]-intro(id) ⦃ id-surjective ⦄
[≼]-minimum-raw : ⦃ equiv-empty : Equiv{ℓₑ₁}(Empty{ℓ}) ⦄ → (_≼_ Empty ⦃ equiv-empty ⦄ T)
[≼]-minimum-raw = [∃]-intro(empty) ⦃ empty-injective ⦄
-- TODO: Impossible because there are no functions of type (T → ⊥)?
-- instance
-- [≽]-minimum : Weak.Properties.Maximum(_≽_ {ℓ})(Empty)
-- Weak.Properties.Maximum.proof([≽]-minimum) {T} {}
module _ ⦃ equiv-A : Equiv{ℓₑ₁}(A) ⦄ ⦃ equiv-B : Equiv{ℓₑ₂}(B) ⦄ where
open Type.Size
[≍]-to-[≼] : (A ≍ B) → (A ≼ B)
[≍]-to-[≼] ([∃]-intro(f) ⦃ f-bijective ⦄) =
([∃]-intro(f) ⦃ bijective-to-injective(f) ⦃ f-bijective ⦄ ⦄)
[≍]-to-[≽] : (A ≍ B) → (A ≽ B)
[≍]-to-[≽] ([∃]-intro(f) ⦃ f-bijective ⦄) =
([∃]-intro(f) ⦃ bijective-to-surjective(f) ⦃ f-bijective ⦄ ⦄)
[≽]-to-[≼] : (ab@([∃]-intro f) : (A ≽ B)) → ⦃ func : Function(f) ⦄ ⦃ inv-func : Function(invᵣ-surjective f) ⦄ → (B ≼ A)
[≽]-to-[≼] ([∃]-intro(f) ⦃ f-surjective ⦄) ⦃ inv-func ⦄ = [∃]-intro(invᵣ f ⦃ surjective-to-invertibleᵣ ⦄) ⦃ inverseᵣ-injective{f = f} ⦃ [∧]-elimᵣ([∃]-proof surjective-to-invertibleᵣ) ⦄ ⦄
{-[≼]-to-[≽] : (A ≼ B) → (B ≽ A)
[≼]-to-[≽] ([∃]-intro(f) ⦃ f-injective ⦄) =
{![∃]-intro()!}
-}
[≍]-symmetry-raw : (ab@([∃]-intro f) : (A ≍ B)) → ⦃ func : Function(f) ⦄ → (B ≍ A)
[≍]-symmetry-raw ([∃]-intro(f) ⦃ f-bijective ⦄)
= [∃]-intro(inv f ⦃ bijective-to-invertible ⦄) ⦃ inv-bijective{f = f} ⦃ inver = bijective-to-invertible ⦄ ⦄
module _ ⦃ equiv-A : Equiv{ℓₑ₁}(A) ⦄ ⦃ equiv-B : Equiv{ℓₑ₂}(B) ⦄ ⦃ equiv-C : Equiv{ℓₑ₃}(C) ⦄ where
open Type.Size
[≍]-transitivity-raw : (ab@([∃]-intro f) : (A ≍ B)) ⦃ func-f : Function(f) ⦄ → (bc@([∃]-intro g) : (B ≍ C)) ⦃ func-g : Function(g) ⦄ → (A ≍ C)
[≍]-transitivity-raw ([∃]-intro(f) ⦃ f-bijective ⦄) ([∃]-intro(g) ⦃ g-bijective ⦄)
= [∃]-intro(g ∘ f) ⦃ [∘]-bijective {f = g} {g = f} ⦃ g-bijective ⦄ ⦃ f-bijective ⦄ ⦄
[≼]-transitivity-raw : (A ≼ B) → (B ≼ C) → (A ≼ C)
[≼]-transitivity-raw ([∃]-intro(f) ⦃ f-injective ⦄) ([∃]-intro(g) ⦃ g-injective ⦄)
= [∃]-intro(g ∘ f) ⦃ [∘]-injective {f = g}{g = f} ⦃ g-injective ⦄ ⦃ f-injective ⦄ ⦄
[≽]-transitivity-raw : (A ≽ B) → (([∃]-intro g) : (B ≽ C)) ⦃ func-g : Function(g) ⦄ → (A ≽ C)
[≽]-transitivity-raw ([∃]-intro(f) ⦃ f-surjective ⦄) ([∃]-intro(g) ⦃ g-surjective ⦄)
= [∃]-intro(g ∘ f) ⦃ [∘]-surjective {f = g} {g = f} ⦃ g-surjective ⦄ ⦃ f-surjective ⦄ ⦄
module _ where
open import Relator.Equals renaming (_≡_ to _≡ₑ_)
open import Relator.Equals.Proofs
private
_≍_ : ∀{ℓ₁ ℓ₂} → (A : Type{ℓ₁}) → (B : Type{ℓ₂}) → Stmt
_≍_ A B = Type.Size._≍_ A B
_≼_ : ∀{ℓ₁ ℓ₂} → (A : Type{ℓ₁}) → (B : Type{ℓ₂}) → Stmt
_≼_ A B = Type.Size._≼_ A B
_≽_ : ∀{ℓ₁ ℓ₂} → (A : Type{ℓ₁}) → (B : Type{ℓ₂}) → Stmt
_≽_ A B = Type.Size._≽_ A B
_≭_ : ∀{ℓ₁ ℓ₂} → (A : Type{ℓ₁}) → (B : Type{ℓ₂}) → Stmt
_≭_ A B = Type.Size._≭_ A B
_≺_ : ∀{ℓ₁ ℓ₂} → (A : Type{ℓ₁}) → (B : Type{ℓ₂}) → Stmt
_≺_ A B = Type.Size._≺_ A B
_≻_ : ∀{ℓ₁ ℓ₂} → (A : Type{ℓ₁}) → (B : Type{ℓ₂}) → Stmt
_≻_ A B = Type.Size._≻_ A B
module _ {ℓ} where
instance
[≍]-reflexivity : Reflexivity(_≍_ {ℓ})
[≍]-reflexivity = intro [≍]-reflexivity-raw
instance
[≍]-symmetry : Symmetry(_≍_ {ℓ})
[≍]-symmetry = intro(f ↦ [≍]-symmetry-raw f)
instance
[≍]-transitivity : Transitivity(_≍_ {ℓ})
[≍]-transitivity = intro(f ↦ g ↦ [≍]-transitivity-raw f g)
instance
[≍]-equivalence : Equivalence(_≍_ {ℓ})
[≍]-equivalence = intro
instance
[≼]-reflexivity : Reflexivity(_≼_ {ℓ})
[≼]-reflexivity = intro [≼]-reflexivity-raw
instance
[≼]-transitivity : Transitivity(_≼_ {ℓ})
[≼]-transitivity = intro [≼]-transitivity-raw
instance
[≽]-reflexivity : Reflexivity(_≽_ {ℓ})
[≽]-reflexivity = intro [≽]-reflexivity-raw
instance
[≽]-transitivity : Transitivity(_≽_ {ℓ})
[≽]-transitivity = intro(p ↦ q ↦ [≽]-transitivity-raw p q)
instance
[≼]-minimum : Weak.Properties.LE.Minimum(_≼_ {ℓ})(Empty)
Weak.Properties.Extremumₗ.proof [≼]-minimum = [≼]-minimum-raw
-- TODO: Impossible because there are no functions of type (T → ⊥)?
-- instance
-- [≽]-minimum : Weak.Properties.Maximum(_≽_ {ℓ})(Empty)
-- Weak.Properties.Maximum.proof([≽]-minimum) {T} {}
-- TODO: Remove this and the similar one in the other module. A more general variant is defined in Relator.Equals.Proofs
module _ {A : Type{ℓ}} {B : Type{ℓ}} where
[≡]-to-[≍] : (A ≡ₑ B) → (A ≍ B)
[≡]-to-[≍] [≡]-intro = reflexivity(_≍_)
|
/-
# Flight Planning
This example is significantly larger than the previous examples and is in many ways more typical of the
type of system that would be encountered in industry. It is characterised by:
- a state of information on flights is held;
- messages are received concerning new and existing flights;
- the state is updated based on the content of the received messages;
- maintenance is performed on the state to, for example, remove expired entries;
- the state is queried for information.
## Background
One of the tasks required of an aircraft operator is to report an intent to fly to the Air Traffic
Services (ATS) provider. The operator must indicate where and when they intend to fly, and provide
various items of information concerning the flight and the aircraft with which the flight will
be conducted.
The reporting is carried out via a number of standard flight planning messages. These messages
are defined by the International Civil Aviation Organisation (ICAO) and documented in the
[Procedures for Air Navigation Services: Air Traffic Management (PANS-ATM)](https://store.icao.int/en/procedures-for-air-navigation-services-air-traffic-management-doc-4444).
It is document number 4444 published by ICAO, so is often referred to as _Doc 4444_.
Appendix 3 of PANS-ATM describes a number of messages employed for communicating flight information.
A subset of those specifically relate to flight planning:
| Message Type | Purpose |
| - | - |
| FPL | File a plan for an intended flight |
| DLA | Report a delay to a previously filed flight |
| CHG | Modify a previously filed flight plan |
| CNL | Cancel a planned flight |
| DEP | Report a flight has departed |
| ARR | Report a flight has arrived |
An example FPL message is:
```
(FPL-ABC123-IS
-B738/M-SADE2E3GHIRWZ/LB1
-YSSY0400
-M079F380 DCT WOL H65 RAZZI Q29 LIZZI DCT
-YMML0100
-PBN/A1B1C1D1O2S2T1 NAV/RNP2 DOF/230220 REG/VHXYZ SEL/AFPQ CODE/7C6DDF OPR/FLYOU ORGN/YSSYABCO PER/C)
```
Flight _ABC123_ is flying from _YSSY_ (Sydney) to _YMML_ (Melbourne) departing _0400_ on _20/2/2023_ with an
expected flight time of one hour. The aircraft is a Boeing 737-800 (_B738_). The text _WOL H65 RAZZI Q29 LIZZI DCT_
is a description of the route the flight will follow. The last line contains various pieces of additional information
such as the aircraft registration (_VHXYZ_).
A collection of numerically labelled fields are defined, each containing a subset of the information that relates to a flight.
Different messages are then defined by selecting the appropriate set of fields for
the purpose of the message. In the above FPL, those fields are:
| Field Number | Content |
| - | - |
| 7 | ABC123 |
| 8 | IS |
| 9 | B738/M |
| 10 | SADE2E3GHIRWZ/LB1 |
| 13 | YSSY0400 |
| 15 | M079F380 DCT WOL H65 RAZZI Q29 LIZZI DCT |
| 16 | YMML0100 |
| 18 | PBN/A1B1C1D1O2S2T1 NAV/RNP2 DOF/230220 REG/VHXYZ SEL/AFPQ CODE/7C6DDF OPR/FLYOU ORGN/YSSYABCO PER/C |
## The Specification
The specification is concerned with the processing of flight plan and related messages, and consists of:
- a model of the data elements, fields, flights and messages;
- definition of invariants on the flights and messages, which primarily capture consistency constraints between the different fields;
- the definition of a state that models a collection of flight information that might be held by a system;
- given a state and a received message, the specification of how a revised state is created from the supplied state and the message;
- some maintenance activities on the state;
- querying the state.
The model and program specification are contained in five modules:
| Module | Purpose |
| - | - |
| [Core](FPL/Core.md) | The core data elements from which higher level entities are built |
| [Field](FPL/Field.md) | The fields from which the messages are assembled |
| [Flight](FPL/Flight.md) | Data entity capturing all information on a flight |
| [Message](FPL/Message.md) | The various messages employed for flight planning purposes |
| [State](FPL/State.md) | The processing of messages with respect to a state |
These modules depend on the general purpose definitions in [Util](lib/Util.md), [Geo](lib/Geo.md) and [Temporal](lib/Temporal.md).
-/ |
SUBROUTINE ZGEMMF(TRANA,TRANB,M,N,K,ALPHA,A,LDA,B,LDB,BETA,C,LDC)
* .. Scalar Arguments ..
DOUBLE COMPLEX ALPHA,BETA
INTEGER K,LDA,LDB,LDC,M,N
CHARACTER TRANA,TRANB
* ..
* .. Array Arguments ..
DOUBLE COMPLEX A(LDA,*),B(LDB,*),C(LDC,*)
* ..
RETURN
*
* End of ZGEMM .
*
END
|
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
/* configuration.cc
Jeremy Barnesm, 18 February 2007
Copyright (c) 2007 Jeremy Barnes. All rights reserved.
Configuration file parser.
*/
#include <boost/algorithm/string/join.hpp>
#include "configuration.h"
#include "mldb/base/parse_context.h"
#include "mldb/utils/string_functions.h"
using namespace std;
using namespace MLDB;
namespace ML {
/*****************************************************************************/
/* CONFIGURATION::DATA */
/*****************************************************************************/
struct Configuration::Data {
typedef std::map<std::string, std::string> Entries;
Entries entries;
void copy_entries(const std::string & from,
const std::string & to)
{
//cerr << "** Copying entries from " << from << " to " << to << endl;
if (to.find(from) == 0)
throw Exception("Attempt to copy entries to within their tree");
string from2 = from + ".";
for (Entries::const_iterator it = entries.lower_bound(from);
it != entries.end() && it->first.find(from2) == 0; ++it) {
string rest(it->first, from2.size());
string key = add_prefix(to, rest);
entries[key] = it->second;
//cerr << "copying " << it->first << "=" << it->second << " to "
// << key << endl;
}
}
};
/*****************************************************************************/
/* CONFIGURATION */
/*****************************************************************************/
Configuration::
Configuration()
: data_(new Data()), prefix_(""), writeable_(true)
{
}
Configuration::
Configuration(const Configuration & other,
const std::string & prefix,
Prefix_Op op)
: data_(other.data_), writeable_(false)
{
if (op == PREFIX_REPLACE)
prefix_ = prefix;
else prefix_ = add_prefix(other.prefix(), prefix);
//cerr << "created new config with prefix=" << prefix_ << " from "
// << other.prefix_ << endl;
}
Configuration::Accessor
Configuration::
operator [] (const std::string & key)
{
string real_key = find_key(key, false /* find_parents */);
return Accessor(this, real_key);
}
std::string
Configuration::
operator [] (const std::string & key) const
{
string real_key = find_key(key, false /* find_parents */);
return data_->entries[real_key];
}
bool
Configuration::
count(const std::string & key, bool search_parents) const
{
string real_key = find_key(key, search_parents);
return data_->entries.count(real_key);
}
namespace {
bool shorter_prefix(string & prefix)
{
size_t pos = prefix.rfind('.');
if (pos == string::npos) {
if (prefix == "") return false;
prefix = "";
return true;
}
prefix = string(prefix, 0, pos);
return true;
}
void lengthen(string & prefix, const std::string & name)
{
if (prefix == "") prefix = name;
else prefix += "." + name;
}
} // file scope
std::string
Configuration::
find_key(const std::string & key,
bool search_parents) const
{
//cerr << "find_key(" << key << ", " << search_parents << ")" << endl;
/* If we search parents, then we look at succeedingly shorter prefixes
until we find it. */
string prefix = prefix_;
do {
string full = add_prefix(prefix, key);
//cerr << " prefix = " << prefix << " full = " << full << endl;
if (data_->entries.count(full)) {
//cerr << " --> found under " << full << endl;
return full;
}
} while (search_parents && shorter_prefix(prefix));
//cerr << " --> not found" << endl;
return add_prefix(prefix_, key); // not found; return first location
}
void
Configuration::
load(const std::string & filename)
{
MLDB::ParseContext context(filename);
parse(context);
}
void
Configuration::
parse_string(const std::string & str, const std::string & filename)
{
ParseContext context(filename, str.c_str(), str.c_str() + str.size());
parse(context);
}
namespace {
struct Found_End_Name {
bool operator () (char c) const
{
if (isalnum(c) || c == '_' || c == '.') return false;
return true;
}
};
std::string expect_name(ParseContext & context)
{
std::string result;
if (!context.match_text(result, Found_End_Name())
|| result.empty())
context.exception("expected name of option");
return result;
}
struct Found_End_Value {
bool operator () (char c) const
{
return c == '\n' || c == ';' || c == ' ' || c == '\t';
}
};
std::string expect_value(ParseContext & context)
{
std::string result;
if (!context.match_text(result, Found_End_Value())
|| result.empty())
context.exception("expected name of option");
return result;
}
} // file scope
void
Configuration::
parse(ParseContext & context)
{
string scope;
while (context) {
//cerr << "scope = " << scope << endl;
context.skip_whitespace();
if (context.match_eol()) continue; // blank line
else if (context.match_literal('#')) {
// comment
context.skip_line();
continue;
}
else if (context.match_literal('}')) {
// end of scope
//cerr << "end of scope = " << scope << endl;
if (!shorter_prefix(scope))
context.exception("configuration tried to close unopened "
"scope");
continue;
}
string name = expect_name(context);
context.skip_whitespace();
if (context.match_literal('=')) {
context.skip_whitespace();
string value = expect_value(context);
context.match_literal(';');
context.skip_whitespace();
if (context.match_literal('#'))
context.expect_text('\n', true, "expected comment");
context.expect_eol();
data_->entries[add_prefix(scope, name)] = value;
}
else if (context.match_literal(':')) {
// start a new scope copying from another
context.skip_whitespace();
string copy_from = expect_name(context);
context.skip_whitespace();
context.expect_literal('{');
lengthen(scope, name);
data_->copy_entries(copy_from, scope);
}
else if (context.match_literal('{')) {
// start a new scope
lengthen(scope, name);
}
else context.exception("expected :, = or { after name");
}
if (!scope.empty()) {
context.exception("configuration ended with scope " + scope
+ " open");
}
}
void
Configuration::
parse_command_line(const std::vector<std::string> & options)
{
/* Each option should be in the form key=value. We parse these simply. */
if (!writeable_)
throw Exception("Configuration::parse_command_line(): "
"object not writeable");
for (unsigned i = 0; i < options.size(); ++i) {
parse_string(options[i],
format("command line:%d:\"%s\"", i, options[i].c_str()));
}
}
std::string
Configuration::
add_prefix(const std::string & prefix, const std::string & rest)
{
string result = prefix;
lengthen(result, rest);
return result;
}
void
Configuration::
raw_set(const std::string & key, const std::string & value)
{
if (!writeable_)
throw Exception("Configuration::operator []: "
"object is not writeable");
data_->entries[key] = value;
}
std::string
Configuration::
raw_get(const std::string & key) const
{
return data_->entries[key];
}
bool
Configuration::
raw_count(const std::string & key) const
{
return data_->entries.count(key);
}
std::ostream &
operator << (std::ostream & stream, const Configuration::Accessor & acc)
{
return stream << acc.operator std::string();
}
std::vector<std::string>
Configuration::
allKeys() const
{
vector<string> result;
for (Data::Entries::const_iterator
it = data_->entries.begin(),
end = data_->entries.end();
it != end; ++it)
result.push_back(it->first);
return result;
}
/** Call after all keys have been consumed with findAndRemove */
void
Configuration::
throwOnUnknwonKeys(
vector<string> & keys,
const function<bool(const string & )> & ignoreKeyFct) const
{
string prefixDot = prefix_ + ".";
keys.erase(
remove_if(keys.begin(), keys.end(),
[&] (const std::string & str) {
return (ignoreKeyFct && ignoreKeyFct(str)) // fct says to ignore
|| str.find(prefixDot) != 0 // prefix not found
|| str.rfind(".") != prefixDot.size() - 1; // prefix found, but non terminal key
}),
keys.end());
if (!keys.empty()) {
throw MLDB::Exception("Unknown key(s) encountered in config: %s",
boost::algorithm::join(keys, " ").c_str());
}
}
} // namespace ML
|
{-# OPTIONS --without-K --rewriting #-}
open import lib.Basics
open import lib.NType2
open import lib.types.Sigma
module lib.types.Modality where
-- Where to put this? Or maybe there's
-- a simpler proof from some library function?
!ᵈ-inv-l-out : ∀ {ℓ} {A : Type ℓ} {P : A → Type ℓ}
{a₀ a₁ : A} {p : a₀ == a₁} {x₀ x₁ : P a₁}
→ (q : x₀ == x₁ [ P ↓ ! p ∙ p ])
→ x₀ == x₁
!ᵈ-inv-l-out {p = idp} q = q
record Modality ℓ : Type (lsucc ℓ) where
field
is-local : Type ℓ → Type ℓ
is-local-is-prop : {A : Type ℓ} → is-prop (is-local A)
◯ : Type ℓ → Type ℓ
◯-is-local : {A : Type ℓ} → is-local (◯ A)
η : {A : Type ℓ} → A → ◯ A
◯-elim : {A : Type ℓ} {B : ◯ A → Type ℓ}
(B-local : (x : ◯ A) → is-local (B x))
→ Π A (B ∘ η) → Π (◯ A) B
◯-elim-β : {A : Type ℓ} {B : ◯ A → Type ℓ}
(B-local : (x : ◯ A) → is-local (B x)) (f : Π A (B ∘ η))
→ (a : A) → ◯-elim B-local f (η a) == f a
◯-=-is-local : {A : Type ℓ} (a₀ a₁ : ◯ A) → is-local (a₀ == a₁)
◯-Type : Type (lsucc ℓ)
◯-Type = Σ (Type ℓ) is-local
{- elimination rules -}
module ◯Elim {A : Type ℓ} {B : ◯ A → Type ℓ}
(B-local : (x : ◯ A) → is-local (B x)) (η* : Π A (B ∘ η)) where
f = ◯-elim B-local η*
η-β = ◯-elim-β B-local η*
module ◯Rec {A : Type ℓ} {B : Type ℓ}
(B-local : is-local B) (η* : A → B)
= ◯Elim (λ _ → B-local) η*
◯-rec = ◯Rec.f
◯-rec-β = ◯Rec.η-β
{- functoriality -}
module ◯Fmap {A B : Type ℓ} (f : A → B) =
◯Rec ◯-is-local (η ∘ f)
◯-fmap = ◯Fmap.f
◯-fmap-β = ◯Fmap.η-β
◯-isemap : {A B : Type ℓ} (f : A → B) → is-equiv f → is-equiv (◯-fmap f)
◯-isemap f f-ise = is-eq _ (◯-fmap g) to-from from-to where
open is-equiv f-ise
abstract
to-from : ∀ ◯b → ◯-fmap f (◯-fmap g ◯b) == ◯b
to-from = ◯-elim
(λ ◯b → ◯-=-is-local (◯-fmap f (◯-fmap g ◯b)) ◯b)
(λ b → ap (◯-fmap f) (◯-fmap-β g b) ∙ ◯-fmap-β f (g b) ∙ ap η (f-g b))
from-to : ∀ ◯a → ◯-fmap g (◯-fmap f ◯a) == ◯a
from-to = ◯-elim
(λ ◯a → ◯-=-is-local (◯-fmap g (◯-fmap f ◯a)) ◯a)
(λ a → ap (◯-fmap g) (◯-fmap-β f a) ∙ ◯-fmap-β g (f a) ∙ ap η (g-f a))
◯-emap : {A B : Type ℓ} → A ≃ B → ◯ A ≃ ◯ B
◯-emap (f , f-ise) = ◯-fmap f , ◯-isemap f f-ise
{- equivalences preserve locality -}
-- This is the only appearence of univalence, but ...
local-is-replete : {A B : Type ℓ} → is-local A → A ≃ B → is-local B
local-is-replete w eq = transport is-local (ua eq) w
-- This name aligns with the current codebase better.
equiv-preserves-local : {A B : Type ℓ} → A ≃ B → is-local A → is-local B
equiv-preserves-local e A-is-loc = local-is-replete A-is-loc e
{- locality and [η] being an equivalence -}
local-implies-η-equiv : {A : Type ℓ} → is-local A → is-equiv (η {A})
local-implies-η-equiv {A} w = is-eq (η {A}) η-inv inv-l inv-r
where η-inv : ◯ A → A
η-inv = ◯-rec w (idf A)
abstract
inv-r : (a : A) → η-inv (η a) == a
inv-r = ◯-rec-β w (idf A)
inv-l : (a : ◯ A) → η (η-inv a) == a
inv-l = ◯-elim (λ a₀ → ◯-=-is-local _ _)
(λ a₀ → ap η (inv-r a₀))
abstract
η-equiv-implies-local : {A : Type ℓ} → is-equiv (η {A}) → is-local A
η-equiv-implies-local {A} eq = local-is-replete {◯ A} {A} ◯-is-local ((η , eq) ⁻¹)
retract-is-local : {A B : Type ℓ} (w : is-local A)
(f : A → B) (g : B → A) (r : (b : B) → f (g b) == b) →
is-local B
retract-is-local {A} {B} w f g r = η-equiv-implies-local (is-eq η η-inv inv-l inv-r)
where η-inv : ◯ B → B
η-inv = f ∘ (◯-rec w g)
inv-r : (b : B) → η-inv (η b) == b
inv-r b = ap f (◯-rec-β w g b) ∙ r b
inv-l : (b : ◯ B) → η (η-inv b) == b
inv-l = ◯-elim (λ b → ◯-=-is-local _ _) (λ b → ap η (inv-r b))
{- locality of identification -}
abstract
=-preserves-local : {A : Type ℓ} → is-local A → {a₀ a₁ : A} → is-local (a₀ == a₁)
=-preserves-local {A} w {a₀} {a₁} = local-is-replete
(◯-=-is-local (η a₀) (η a₁)) (ap-equiv (η , local-implies-η-equiv w) a₀ a₁ ⁻¹)
{- ◯-connectness and ◯-equivalences -}
is-◯-connected : Type ℓ → Type ℓ
is-◯-connected A = is-contr (◯ A)
is-◯-connected-is-prop : ∀ {A} → is-prop (is-◯-connected A)
is-◯-connected-is-prop {A} = is-contr-is-prop
is-◯-equiv : {A B : Type ℓ} → (A → B) → Type ℓ
is-◯-equiv {B = B} f = (b : B) → is-◯-connected (hfiber f b)
has-◯-conn-fibers = is-◯-equiv
is-lex : Type (lsucc ℓ)
is-lex = {A B : Type ℓ} (f : A → B)
→ is-◯-connected A → is-◯-connected B → is-◯-equiv f
equiv-preserves-◯-conn : {A B : Type ℓ} → A ≃ B → is-◯-connected A → is-◯-connected B
equiv-preserves-◯-conn e c = equiv-preserves-level (◯-emap e) {{c}}
total-◯-equiv : {A : Type ℓ} {P Q : A → Type ℓ} (φ : ∀ a → P a → Q a) →
(∀ a → is-◯-equiv (φ a)) → is-◯-equiv (Σ-fmap-r φ)
total-◯-equiv φ e (a , q) = equiv-preserves-◯-conn (hfiber-Σ-fmap-r φ q ⁻¹) (e a q)
module _ {A B : Type ℓ} {h : A → B} (c : is-◯-equiv h) (P : B → ◯-Type) where
abstract
pre∘-◯-conn-is-equiv : is-equiv (λ (s : Π B (fst ∘ P)) → s ∘ h)
pre∘-◯-conn-is-equiv = is-eq f g f-g g-f
where f : Π B (fst ∘ P) → Π A (fst ∘ P ∘ h)
f k a = k (h a)
helper : Π A (fst ∘ P ∘ h) → (b : B) → ◯ (Σ A (λ a → h a == b)) → (fst (P b))
helper t b = ◯-rec (snd (P b)) (λ x → transport (fst ∘ P) (snd x) (t (fst x)))
helper-β : (t : Π A (fst ∘ P ∘ h)) → (b : B) → (r : hfiber h b) →
helper t b (η r) == transport (fst ∘ P) (snd r) (t (fst r))
helper-β t b = ◯-rec-β (snd (P b)) (λ x → transport (fst ∘ P) (snd x) (t (fst x)))
g : Π A (fst ∘ P ∘ h) → Π B (fst ∘ P)
g t b = helper t b (contr-center (c b))
f-g : ∀ t → f (g t) == t
f-g t = λ= $ λ a → transport
(λ r → ◯-rec (snd (P (h a))) _ r == t a)
(! (contr-path (c (h a)) (η (a , idp))))
(◯-rec-β (snd (P (h a))) _ (a , idp))
g-f : ∀ k → g (f k) == k
g-f k = λ= λ (b : B) →
◯-elim {A = hfiber h b}
(λ r → =-preserves-local (snd (P b)) {g (f k) b})
(λ r → lemma₁ (fst r) b (snd r))
(contr-center (c b))
where lemma₀ : (a : A) → (b : B) → (p : h a == b) →
helper (k ∘ h) b (η (a , p)) == k b
lemma₀ a .(h a) idp = helper-β (k ∘ h) (h a) (a , idp)
lemma₁ : (a : A) → (b : B) → (p : h a == b) →
helper (k ∘ h) b (contr-center (c b)) == k b
lemma₁ a b p = transport! (λ r → helper (k ∘ h) b r == k b)
(contr-path (c b) (η (a , p))) (lemma₀ a b p)
◯-extend : Π A (fst ∘ P ∘ h) → Π B (fst ∘ P)
◯-extend = is-equiv.g pre∘-◯-conn-is-equiv
◯-extend-β : ∀ f a → ◯-extend f (h a) == f a
◯-extend-β f = app= (is-equiv.f-g pre∘-◯-conn-is-equiv f)
{- locality of function types -}
abstract
Π-is-local : {A : Type ℓ} {B : A → Type ℓ} (w : (a : A) → is-local (B a)) → is-local (Π A B)
Π-is-local {A} {B} w = retract-is-local {◯ (Π A B)} {Π A B} ◯-is-local η-inv η r
where η-inv : ◯ (Π A B) → Π A B
η-inv φ' a = ◯-rec (w a) (λ φ → φ a) φ'
r : (φ : Π A B) → η-inv (η φ) == φ
r φ = λ= (λ a → ◯-rec-β (w a) (λ φ₀ → φ₀ a) φ)
→-is-local : {A B : Type ℓ} → is-local B → is-local (A → B)
→-is-local w = Π-is-local (λ _ → w)
-- Fmap2 because of locality of function types
module ◯Fmap2 {A B C : Type ℓ} (η* : A → B → C) where
private module M = ◯Rec (→-is-local ◯-is-local) (◯-fmap ∘ η*)
f = M.f
η-β : ∀ a b → f (η a) (η b) == η (η* a b)
η-β a b = app= (M.η-β a) (η b) ∙ ◯-fmap-β (η* a) b
◯-fmap2 = ◯Fmap2.f
◯-fmap2-β = ◯Fmap2.η-β
{- locality of sigma types -}
abstract
Σ-is-local : {A : Type ℓ} (B : A → Type ℓ)
→ is-local A → ((a : A) → is-local (B a))
→ is-local (Σ A B)
Σ-is-local {A} B lA lB = retract-is-local {◯ (Σ A B)} {Σ A B} ◯-is-local η-inv η r
where h : ◯ (Σ A B) → A
h = ◯-rec lA fst
h-β : (ab : Σ A B) → h (η ab) == fst ab
h-β = ◯-rec-β lA fst
k : (w : ◯ (Σ A B)) → B (h w)
k = ◯-elim (lB ∘ h) λ ab → transport! B (h-β ab) (snd ab)
k-β : (ab : Σ A B) → k (η ab) == snd ab [ B ↓ h-β ab ]
k-β ab = from-transp! B (h-β ab) $
◯-elim-β (lB ∘ h) (λ ab → transport! B (h-β ab) (snd ab)) ab
η-inv : ◯ (Σ A B) → Σ A B
η-inv w = h w , k w
r : (x : Σ A B) → η-inv (η x) == x
r ab = pair= (h-β ab) (k-β ab)
×-is-local : {A B : Type ℓ}
→ is-local A → is-local B → is-local (A × B)
×-is-local {B = B} lA lB = Σ-is-local (λ _ → B) lA (λ _ → lB)
◯-×-econv : {A B : Type ℓ} → ◯ (A × B) ≃ ◯ A × ◯ B
◯-×-econv {A} {B} = equiv ◯-split ◯-pair inv-l inv-r
where ◯-fst : ◯ (A × B) → ◯ A
◯-fst = ◯-fmap fst
◯-fst-β : (ab : A × B) → ◯-fst (η ab) == η (fst ab)
◯-fst-β = ◯-fmap-β fst
◯-snd : ◯ (A × B) → ◯ B
◯-snd = ◯-fmap snd
◯-snd-β : (ab : A × B) → ◯-snd (η ab) == η (snd ab)
◯-snd-β = ◯-fmap-β snd
◯-split : ◯ (A × B) → ◯ A × ◯ B
◯-split = fanout ◯-fst ◯-snd
◯-pair : ◯ A × ◯ B → ◯ (A × B)
◯-pair = uncurry (◯-fmap2 _,_)
◯-pair-β : (a : A) (b : B) → ◯-pair (η a , η b) == η (a , b)
◯-pair-β = ◯-fmap2-β _,_
abstract
inv-l : (ab : ◯ A × ◯ B) → ◯-split (◯-pair ab) == ab
inv-l = uncurry $
◯-elim (λ _ → Π-is-local λ _ → =-preserves-local (×-is-local ◯-is-local ◯-is-local))
(λ a → ◯-elim (λ _ → =-preserves-local (×-is-local ◯-is-local ◯-is-local))
(λ b → ap ◯-split (◯-pair-β a b)
∙ pair×= (◯-fst-β (a , b)) (◯-snd-β (a , b))))
inv-r : (ab : ◯ (A × B)) → ◯-pair (◯-split ab) == ab
inv-r = ◯-elim (λ _ → ◯-=-is-local _ _)
(λ ab → ap ◯-pair (pair×= (◯-fst-β ab) (◯-snd-β ab)) ∙ ◯-pair-β (fst ab) (snd ab))
|
(* Title: A Definitional Encoding of TLA in Isabelle/HOL
Authors: Gudmund Grov <ggrov at inf.ed.ac.uk>
Stephan Merz <Stephan.Merz at loria.fr>
Year: 2011
Maintainer: Gudmund Grov <ggrov at inf.ed.ac.uk>
*)
section \<open>Lamport's Inc example\<close>
theory Inc
imports State
begin
text\<open>
This example illustrates use of the embedding by mechanising
the running example of Lamports original TLA paper \cite{Lamport94}.
\<close>
datatype pcount = a | b | g
locale Firstprogram =
fixes x :: "state \<Rightarrow> nat"
and y :: "state \<Rightarrow> nat"
and init :: "temporal"
and m1 :: "temporal"
and m2 :: "temporal"
and phi :: "temporal"
and Live :: "temporal"
defines "init \<equiv> TEMP $x = # 0 \<and> $y = # 0"
and "m1 \<equiv> TEMP x` = Suc<$x> \<and> y` = $y"
and "m2 \<equiv> TEMP y` = Suc<$y> \<and> x` = $x"
and "Live \<equiv> TEMP WF(m1)_(x,y) \<and> WF(m2)_(x,y)"
and "phi \<equiv> TEMP (init \<and> \<box>[m1 \<or> m2]_(x,y) \<and> Live)"
assumes bvar: "basevars (x,y)"
lemma (in Firstprogram) "STUTINV phi"
by (auto simp: phi_def init_def m1_def m2_def Live_def stutinvs nstutinvs livestutinv)
lemma (in Firstprogram) enabled_m1: "\<turnstile> Enabled \<langle>m1\<rangle>_(x,y)"
proof (clarify)
fix s
show "s \<Turnstile> Enabled \<langle>m1\<rangle>_(x,y)"
by (rule base_enabled[OF bvar]) (auto simp: m1_def tla_defs)
qed
lemma (in Firstprogram) enabled_m2: "\<turnstile> Enabled \<langle>m2\<rangle>_(x,y)"
proof (clarify)
fix s
show "s \<Turnstile> Enabled \<langle>m2\<rangle>_(x,y)"
by (rule base_enabled[OF bvar]) (auto simp: m2_def tla_defs)
qed
locale Secondprogram = Firstprogram +
fixes sem :: "state \<Rightarrow> nat"
and pc1 :: "state \<Rightarrow> pcount"
and pc2 :: "state \<Rightarrow> pcount"
and vars
and initPsi :: "temporal"
and alpha1 :: "temporal"
and alpha2 :: "temporal"
and beta1 :: "temporal"
and beta2 :: "temporal"
and gamma1 :: "temporal"
and gamma2 :: "temporal"
and n1 :: "temporal"
and n2 :: "temporal"
and Live2 :: "temporal"
and psi :: "temporal"
and I :: "temporal"
defines "vars \<equiv> LIFT (x,y,sem,pc1,pc2)"
and "initPsi \<equiv> TEMP $pc1 = # a \<and> $pc2 = # a \<and> $x = # 0 \<and> $y = # 0 \<and> $sem = # 1"
and "alpha1 \<equiv> TEMP $pc1 =#a \<and> # 0 < $sem \<and> pc1$ = #b \<and> sem$ = $sem - # 1 \<and> Unchanged (x,y,pc2)"
and "alpha2 \<equiv> TEMP $pc2 =#a \<and> # 0 < $sem \<and> pc2` = #b \<and> sem$ = $sem - # 1 \<and> Unchanged (x,y,pc1)"
and "beta1 \<equiv> TEMP $pc1 =#b \<and> pc1` = #g \<and> x` = Suc<$x> \<and> Unchanged (y,sem,pc2)"
and "beta2 \<equiv> TEMP $pc2 =#b \<and> pc2` = #g \<and> y` = Suc<$y> \<and> Unchanged (x,sem,pc1)"
and "gamma1 \<equiv> TEMP $pc1 =#g \<and> pc1` = #a \<and> sem` = Suc<$sem> \<and> Unchanged (x,y,pc2)"
and "gamma2 \<equiv> TEMP $pc2 =#g \<and> pc2` = #a \<and> sem` = Suc<$sem> \<and> Unchanged (x,y,pc1)"
and "n1 \<equiv> TEMP (alpha1 \<or> beta1 \<or> gamma1)"
and "n2 \<equiv> TEMP (alpha2 \<or> beta2 \<or> gamma2)"
and "Live2 \<equiv> TEMP SF(n1)_vars \<and> SF(n2)_vars"
and "psi \<equiv> TEMP (initPsi \<and> \<box>[n1 \<or> n2]_vars \<and> Live2)"
and "I \<equiv> TEMP ($sem = # 1 \<and> $pc1 = #a \<and> $pc2 = # a)
\<or> ($sem = # 0 \<and> (($pc1 = #a \<and> $pc2 \<in> {#b , #g})
\<or> ($pc2 = #a \<and> $pc1 \<in> {#b , #g})))"
assumes bvar2: "basevars vars"
lemmas (in Secondprogram) Sact2_defs = n1_def n2_def alpha1_def beta1_def gamma1_def alpha2_def beta2_def gamma2_def
text \<open>
Proving invariants is the basis of every effort of system verification.
We show that \<open>I\<close> is an inductive invariant of specification \<open>psi\<close>.
\<close>
lemma (in Secondprogram) psiI: "\<turnstile> psi \<longrightarrow> \<box>I"
proof -
have init: "\<turnstile> initPsi \<longrightarrow> I" by (auto simp: initPsi_def I_def)
have "|~ I \<and> Unchanged vars \<longrightarrow> \<circle>I" by (auto simp: I_def vars_def tla_defs)
moreover
have "|~ I \<and> n1 \<longrightarrow> \<circle>I" by (auto simp: I_def Sact2_defs tla_defs)
moreover
have "|~ I \<and> n2 \<longrightarrow> \<circle>I" by (auto simp: I_def Sact2_defs tla_defs)
ultimately have step: "|~ I \<and> [n1 \<or> n2]_vars \<longrightarrow> \<circle>I" by (force simp: actrans_def)
from init step have goal: "\<turnstile> initPsi \<and> \<box>[n1 \<or> n2]_vars \<longrightarrow> \<box>I" by (rule invmono)
have "\<turnstile> initPsi \<and> \<box>[n1 \<or> n2]_vars \<and> Live2 ==> \<turnstile> initPsi \<and> \<box>[n1 \<or> n2]_vars"
by auto
with goal show ?thesis unfolding psi_def by auto
qed
text \<open>
Using this invariant we now prove step simulation, i.e. the safety part of
the refinement proof.
\<close>
theorem (in Secondprogram) step_simulation: "\<turnstile> psi \<longrightarrow> init \<and> \<box>[m1 \<or> m2]_(x,y)"
proof -
have "\<turnstile> initPsi \<and> \<box>I \<and> \<box>[n1 \<or> n2]_vars \<longrightarrow> init \<and> \<box>[m1 \<or> m2]_(x,y)"
proof (rule refinement1)
show "\<turnstile> initPsi \<longrightarrow> init" by (auto simp: initPsi_def init_def)
next
show "|~ I \<and> \<circle>I \<and> [n1 \<or> n2]_vars \<longrightarrow> [m1 \<or> m2]_(x,y)"
by (auto simp: I_def m1_def m2_def vars_def Sact2_defs tla_defs)
qed
with psiI show ?thesis unfolding psi_def by force
qed
text \<open>
Liveness proofs require computing the enabledness conditions of actions.
The first lemma below shows that all steps are visible, i.e. they change
at least one variable.
\<close>
lemma (in Secondprogram) n1_ch: "|~ \<langle>n1\<rangle>_vars = n1"
proof -
have "|~ n1 \<longrightarrow> \<langle>n1\<rangle>_vars" by (auto simp: Sact2_defs tla_defs vars_def)
thus ?thesis by (auto simp: angle_actrans_sem[int_rewrite])
qed
lemma (in Secondprogram) enab_alpha1: "\<turnstile> $pc1 = #a \<longrightarrow> # 0 < $sem \<longrightarrow> Enabled alpha1"
proof (clarsimp simp: tla_defs)
fix s :: "state seq"
assume "pc1 (s 0) = a" and "0 < sem (s 0)"
thus "s \<Turnstile> Enabled alpha1"
by (intro base_enabled[OF bvar2]) (auto simp: Sact2_defs tla_defs vars_def)
qed
lemma (in Secondprogram) enab_beta1: "\<turnstile> $pc1 = #b \<longrightarrow> Enabled beta1"
proof (clarsimp simp: tla_defs)
fix s :: "state seq"
assume "pc1 (s 0) = b"
thus "s \<Turnstile> Enabled beta1"
by (intro base_enabled[OF bvar2]) (auto simp: Sact2_defs tla_defs vars_def)
qed
lemma (in Secondprogram) enab_gamma1: "\<turnstile> $pc1 = #g \<longrightarrow> Enabled gamma1"
proof (clarsimp simp: tla_defs)
fix s :: "state seq"
assume "pc1 (s 0) = g"
thus "s \<Turnstile> Enabled gamma1"
by (intro base_enabled[OF bvar2]) (auto simp: Sact2_defs tla_defs vars_def)
qed
lemma (in Secondprogram) enab_n1:
"\<turnstile> Enabled \<langle>n1\<rangle>_vars = ($pc1 = #a \<longrightarrow> # 0 < $sem)"
unfolding n1_ch[int_rewrite] proof (rule int_iffI)
show "\<turnstile> Enabled n1 \<longrightarrow> $pc1 = #a \<longrightarrow> # 0 < $sem"
by (auto elim!: enabledE simp: Sact2_defs tla_defs)
next
show "\<turnstile> ($pc1 = #a \<longrightarrow> # 0 < $sem) \<longrightarrow> Enabled n1"
proof (clarsimp simp: tla_defs)
fix s :: "state seq"
assume "pc1 (s 0) = a \<longrightarrow> 0 < sem (s 0)"
thus "s \<Turnstile> Enabled n1"
using enab_alpha1[unlift_rule]
enab_beta1[unlift_rule]
enab_gamma1[unlift_rule]
by (cases "pc1 (s 0)") (force simp: n1_def Enabled_disj[int_rewrite] tla_defs)+
qed
qed
text \<open>
The analogous properties for the second process are obtained by copy and paste.
\<close>
lemma (in Secondprogram) n2_ch: "|~ \<langle>n2\<rangle>_vars = n2"
proof -
have "|~ n2 \<longrightarrow> \<langle>n2\<rangle>_vars" by (auto simp: Sact2_defs tla_defs vars_def)
thus ?thesis by (auto simp: angle_actrans_sem[int_rewrite])
qed
lemma (in Secondprogram) enab_alpha2: "\<turnstile> $pc2 = #a \<longrightarrow> # 0 < $sem \<longrightarrow> Enabled alpha2"
proof (clarsimp simp: tla_defs)
fix s :: "state seq"
assume "pc2 (s 0) = a" and "0 < sem (s 0)"
thus "s \<Turnstile> Enabled alpha2"
by (intro base_enabled[OF bvar2]) (auto simp: Sact2_defs tla_defs vars_def)
qed
lemma (in Secondprogram) enab_beta2: "\<turnstile> $pc2 = #b \<longrightarrow> Enabled beta2"
proof (clarsimp simp: tla_defs)
fix s :: "state seq"
assume "pc2 (s 0) = b"
thus "s \<Turnstile> Enabled beta2"
by (intro base_enabled[OF bvar2]) (auto simp: Sact2_defs tla_defs vars_def)
qed
lemma (in Secondprogram) enab_gamma2: "\<turnstile> $pc2 = #g \<longrightarrow> Enabled gamma2"
proof (clarsimp simp: tla_defs)
fix s :: "state seq"
assume "pc2 (s 0) = g"
thus "s \<Turnstile> Enabled gamma2"
by (intro base_enabled[OF bvar2]) (auto simp: Sact2_defs tla_defs vars_def)
qed
lemma (in Secondprogram) enab_n2:
"\<turnstile> Enabled \<langle>n2\<rangle>_vars = ($pc2 = #a \<longrightarrow> # 0 < $sem)"
unfolding n2_ch[int_rewrite] proof (rule int_iffI)
show "\<turnstile> Enabled n2 \<longrightarrow> $pc2 = #a \<longrightarrow> # 0 < $sem"
by (auto elim!: enabledE simp: Sact2_defs tla_defs)
next
show "\<turnstile> ($pc2 = #a \<longrightarrow> # 0 < $sem) \<longrightarrow> Enabled n2"
proof (clarsimp simp: tla_defs)
fix s :: "state seq"
assume "pc2 (s 0) = a \<longrightarrow> 0 < sem (s 0)"
thus "s \<Turnstile> Enabled n2"
using enab_alpha2[unlift_rule]
enab_beta2[unlift_rule]
enab_gamma2[unlift_rule]
by (cases "pc2 (s 0)") (force simp: n2_def Enabled_disj[int_rewrite] tla_defs)+
qed
qed
text \<open>
We use rule \<open>SF2\<close> to prove that \<open>psi\<close> implements strong fairness
for the abstract action \<open>m1\<close>. Since strong fairness implies weak fairness,
it follows that \<open>psi\<close> refines the liveness condition of \<open>phi\<close>.
\<close>
lemma (in Secondprogram) psi_fair_m1: "\<turnstile> psi \<longrightarrow> SF(m1)_(x,y)"
proof -
have "\<turnstile> \<box>[n1 \<or> n2]_vars \<and> SF(n1)_vars \<and> \<box>(I \<and> SF(n2)_vars) \<longrightarrow> SF(m1)_(x,y)"
proof (rule SF2)
txt \<open>
Rule \<open>SF2\<close> requires us to choose a helpful action (whose effect implies
\<open>\<langle>m1\<rangle>_(x,y)\<close>) and a persistent condition, which will eventually remain
true if the helpful action is never executed. In our case, the helpful action
is \<open>beta1\<close> and the persistent condition is \<open>pc1 = b\<close>.
\<close>
show "|~ \<langle>(n1 \<or> n2) \<and> beta1\<rangle>_vars \<longrightarrow> \<langle>m1\<rangle>_(x,y)"
by (auto simp: beta1_def m1_def vars_def tla_defs)
next
show "|~ $pc1 = #b \<and> \<circle>($pc1 = #b) \<and> \<langle>(n1 \<or> n2) \<and> n1\<rangle>_vars \<longrightarrow> beta1"
by (auto simp: n1_def alpha1_def beta1_def gamma1_def tla_defs)
next
show "\<turnstile> $pc1 = #b \<and> Enabled \<langle>m1\<rangle>_(x, y) \<longrightarrow> Enabled \<langle>n1\<rangle>_vars"
unfolding enab_n1[int_rewrite] by auto
next
txt \<open>
The difficult part of the proof is showing that the persistent condition
will eventually always be true if the helpful action is never executed.
We show that (1) whenever the condition becomes true it remains so and
(2) eventually the condition must be true.
\<close>
show "\<turnstile> \<box>[(n1 \<or> n2) \<and> \<not> beta1]_vars
\<and> SF(n1)_vars \<and> \<box>(I \<and> SF(n2)_vars) \<and> \<box>\<diamond>Enabled \<langle>m1\<rangle>_(x, y)
\<longrightarrow> \<diamond>\<box>($pc1 = #b)"
proof -
have "\<turnstile> \<box>\<box>[(n1 \<or> n2) \<and> \<not> beta1]_vars \<longrightarrow> \<box>($pc1 = #b \<longrightarrow> \<box>($pc1 = #b))"
proof (rule STL4)
have "|~ $pc1 = #b \<and> [(n1 \<or> n2) \<and> \<not> beta1]_vars \<longrightarrow> \<circle>($pc1 = #b)"
by (auto simp: Sact2_defs vars_def tla_defs)
from this[THEN INV1]
show "\<turnstile> \<box>[(n1 \<or> n2) \<and> \<not> beta1]_vars \<longrightarrow> $pc1 = #b \<longrightarrow> \<box>($pc1 = #b)" by auto
qed
hence 1: "\<turnstile> \<box>[(n1 \<or> n2) \<and> \<not> beta1]_vars \<longrightarrow> \<diamond>($pc1 = #b) \<longrightarrow> \<diamond>\<box>($pc1 = #b)"
by (force intro: E31[unlift_rule])
have "\<turnstile> \<box>[(n1 \<or> n2) \<and> \<not> beta1]_vars \<and> SF(n1)_vars \<and> \<box>(I \<and> SF(n2)_vars)
\<longrightarrow> \<diamond>($pc1 = #b)"
proof -
txt \<open>
The plan of the proof is to show that from any state where \<open>pc1 = g\<close>
one eventually reaches \<open>pc1 = a\<close>, from where one eventually reaches
\<open>pc1 = b\<close>. The result follows by combining leadsto properties.
\<close>
let ?F = "LIFT (\<box>[(n1 \<or> n2) \<and> \<not> beta1]_vars \<and> SF(n1)_vars \<and> \<box>(I \<and> SF(n2)_vars))"
txt \<open>
Showing that \<open>pc1 = g\<close> leads to \<open>pc1 = a\<close> is a simple
application of rule \<open>SF1\<close> because the first process completely
controls this transition.
\<close>
have ga: "\<turnstile> ?F \<longrightarrow> ($pc1 = #g \<leadsto> $pc1 = #a)"
proof (rule SF1)
show "|~ $pc1 = #g \<and> [(n1 \<or> n2) \<and> \<not> beta1]_vars \<longrightarrow> \<circle>($pc1 = #g) \<or> \<circle>($pc1 = #a)"
by (auto simp: Sact2_defs vars_def tla_defs)
next
show "|~ $pc1 = #g \<and> \<langle>((n1 \<or> n2) \<and> \<not> beta1) \<and> n1\<rangle>_vars \<longrightarrow> \<circle>($pc1 = #a)"
by (auto simp: Sact2_defs vars_def tla_defs)
next
show "|~ $pc1 = #g \<and> Unchanged vars \<longrightarrow> \<circle>($pc1 = #g)"
by (auto simp: vars_def tla_defs)
next
have "\<turnstile> $pc1 = #g \<longrightarrow> Enabled \<langle>n1\<rangle>_vars"
unfolding enab_n1[int_rewrite] by (auto simp: tla_defs)
hence "\<turnstile> \<box>($pc1 = #g) \<longrightarrow> Enabled \<langle>n1\<rangle>_vars"
by (rule lift_imp_trans[OF ax1])
hence "\<turnstile> \<box>($pc1 = #g) \<longrightarrow> \<diamond>Enabled \<langle>n1\<rangle>_vars"
by (rule lift_imp_trans[OF _ E3])
thus "\<turnstile> \<box>($pc1 = #g) \<and> \<box>[(n1 \<or> n2) \<and> \<not> beta1]_vars \<and> \<box>(I \<and> SF(n2)_vars)
\<longrightarrow> \<diamond>Enabled \<langle>n1\<rangle>_vars"
by auto
qed
txt \<open>
The proof that \<open>pc1 = a\<close> leads to \<open>pc1 = b\<close> follows
the same basic schema. However, showing that \<open>n1\<close> is eventually
enabled requires reasoning about the second process, which must liberate
the critical section.
\<close>
have ab: "\<turnstile> ?F \<longrightarrow> ($pc1 = #a \<leadsto> $pc1 = #b)"
proof (rule SF1)
show "|~ $pc1 = #a \<and> [(n1 \<or> n2) \<and> \<not> beta1]_vars \<longrightarrow> \<circle>($pc1 = #a) \<or> \<circle>($pc1 = #b)"
by (auto simp: Sact2_defs vars_def tla_defs)
next
show "|~ $pc1 = #a \<and> \<langle>((n1 \<or> n2) \<and> \<not> beta1) \<and> n1\<rangle>_vars \<longrightarrow> \<circle>($pc1 = #b)"
by (auto simp: Sact2_defs vars_def tla_defs)
next
show "|~ $pc1 = #a \<and> Unchanged vars \<longrightarrow> \<circle>($pc1 = #a)"
by (auto simp: vars_def tla_defs)
next
txt \<open>We establish a suitable leadsto-chain.\<close>
let ?G = "LIFT \<box>[(n1 \<or> n2) \<and> \<not> beta1]_vars \<and> SF(n2)_vars \<and> \<box>($pc1 = #a \<and> I)"
have "\<turnstile> ?G \<longrightarrow> \<diamond>($pc2 = #a \<and> $pc1 = #a \<and> I)"
proof -
txt \<open>Rule \<open>SF1\<close> takes us from \<open>pc2 = b\<close> to \<open>pc2 = g\<close>.\<close>
have bg2: "\<turnstile> ?G \<longrightarrow> ($pc2 = #b \<leadsto> $pc2 = #g)"
proof (rule SF1)
show "|~ $pc2 = #b \<and> [(n1 \<or> n2) \<and> \<not>beta1]_vars \<longrightarrow> \<circle>($pc2 = #b) \<or> \<circle>($pc2 = #g)"
by (auto simp: Sact2_defs vars_def tla_defs)
next
show "|~ $pc2 = #b \<and> \<langle>((n1 \<or> n2) \<and> \<not>beta1) \<and> n2\<rangle>_vars \<longrightarrow> \<circle>($pc2 = #g)"
by (auto simp: Sact2_defs vars_def tla_defs)
next
show "|~ $pc2 = #b \<and> Unchanged vars \<longrightarrow> \<circle>($pc2 = #b)"
by (auto simp: vars_def tla_defs)
next
have "\<turnstile> $pc2 = #b \<longrightarrow> Enabled \<langle>n2\<rangle>_vars"
unfolding enab_n2[int_rewrite] by (auto simp: tla_defs)
hence "\<turnstile> \<box>($pc2 = #b) \<longrightarrow> Enabled \<langle>n2\<rangle>_vars"
by (rule lift_imp_trans[OF ax1])
hence "\<turnstile> \<box>($pc2 = #b) \<longrightarrow> \<diamond>Enabled \<langle>n2\<rangle>_vars"
by (rule lift_imp_trans[OF _ E3])
thus "\<turnstile> \<box>($pc2 = #b) \<and> \<box>[(n1 \<or> n2) \<and> \<not>beta1]_vars \<and> \<box>($pc1 = #a \<and> I)
\<longrightarrow> \<diamond>Enabled \<langle>n2\<rangle>_vars"
by auto
qed
txt \<open>Similarly, \<open>pc2 = b\<close> leads to \<open>pc2 = g\<close>.\<close>
have ga2: "\<turnstile> ?G \<longrightarrow> ($pc2 = #g \<leadsto> $pc2 = #a)"
proof (rule SF1)
show "|~ $pc2 = #g \<and> [(n1 \<or> n2) \<and> \<not>beta1]_vars \<longrightarrow> \<circle>($pc2 = #g) \<or> \<circle>($pc2 = #a)"
by (auto simp: Sact2_defs vars_def tla_defs)
next
show "|~ $pc2 = #g \<and> \<langle>((n1 \<or> n2) \<and> \<not>beta1) \<and> n2\<rangle>_vars \<longrightarrow> \<circle>($pc2 = #a)"
by (auto simp: n2_def alpha2_def beta2_def gamma2_def vars_def tla_defs)
next
show "|~ $pc2 = #g \<and> Unchanged vars \<longrightarrow> \<circle>($pc2 = #g)"
by (auto simp: vars_def tla_defs)
next
have "\<turnstile> $pc2 = #g \<longrightarrow> Enabled \<langle>n2\<rangle>_vars"
unfolding enab_n2[int_rewrite] by (auto simp: tla_defs)
hence "\<turnstile> \<box>($pc2 = #g) \<longrightarrow> Enabled \<langle>n2\<rangle>_vars"
by (rule lift_imp_trans[OF ax1])
hence "\<turnstile> \<box>($pc2 = #g) \<longrightarrow> \<diamond>Enabled \<langle>n2\<rangle>_vars"
by (rule lift_imp_trans[OF _ E3])
thus "\<turnstile> \<box>($pc2 = #g) \<and> \<box>[(n1 \<or> n2) \<and> \<not>beta1]_vars \<and> \<box>($pc1 = #a \<and> I)
\<longrightarrow> \<diamond>Enabled \<langle>n2\<rangle>_vars"
by auto
qed
with bg2 have "\<turnstile> ?G \<longrightarrow> ($pc2 = #b \<leadsto> $pc2 = #a)"
by (force elim: LT13[unlift_rule])
with ga2 have "\<turnstile> ?G \<longrightarrow> ($pc2 = #a \<or> $pc2 = #b \<or> $pc2 = #g) \<leadsto> ($pc2 = #a)"
unfolding LT17[int_rewrite] LT1[int_rewrite] by force
moreover
have "\<turnstile> $pc2 = #a \<or> $pc2 = #b \<or> $pc2 = #g"
proof (clarsimp simp: tla_defs)
fix s :: "state seq"
assume "pc2 (s 0) \<noteq> a" and "pc2 (s 0) \<noteq> g"
thus "pc2 (s 0) = b" by (cases "pc2 (s 0)") auto
qed
hence "\<turnstile> (($pc2 = #a \<or> $pc2 = #b \<or> $pc2 = #g) \<leadsto> $pc2 = #a) \<longrightarrow> \<diamond>($pc2 = #a)"
by (rule fmp[OF _ LT4])
ultimately
have "\<turnstile> ?G \<longrightarrow> \<diamond>($pc2 = #a)" by force
thus ?thesis by (auto intro!: SE3[unlift_rule])
qed
moreover
have "\<turnstile> \<diamond>($pc2 = #a \<and> $pc1 = #a \<and> I) \<longrightarrow> \<diamond>Enabled \<langle>n1\<rangle>_vars"
unfolding enab_n1[int_rewrite] by (rule STL4_eve) (auto simp: I_def tla_defs)
ultimately
show "\<turnstile> \<box>($pc1 = #a) \<and> \<box>[(n1 \<or> n2) \<and> \<not> beta1]_vars \<and> \<box>(I \<and> SF(n2)_vars)
\<longrightarrow> \<diamond>Enabled \<langle>n1\<rangle>_vars"
by (force simp: STL5[int_rewrite])
qed
from ga ab have "\<turnstile> ?F \<longrightarrow> ($pc1 = #g \<leadsto> $pc1 = #b)"
by (force elim: LT13[unlift_rule])
with ab have "\<turnstile> ?F \<longrightarrow> (($pc1 = #a \<or> $pc1 = #b \<or> $pc1 = #g) \<leadsto> $pc1 = #b)"
unfolding LT17[int_rewrite] LT1[int_rewrite] by force
moreover
have "\<turnstile> $pc1 = #a \<or> $pc1 = #b \<or> $pc1 = #g"
proof (clarsimp simp: tla_defs)
fix s :: "state seq"
assume "pc1 (s 0) \<noteq> a" and "pc1 (s 0) \<noteq> g"
thus "pc1 (s 0) = b" by (cases "pc1 (s 0)", auto)
qed
hence "\<turnstile> (($pc1 = #a \<or> $pc1 = #b \<or> $pc1 = #g) \<leadsto> $pc1 = #b) \<longrightarrow> \<diamond>($pc1 = #b)"
by (rule fmp[OF _ LT4])
ultimately show ?thesis by (rule lift_imp_trans)
qed
with 1 show ?thesis by force
qed
qed
with psiI show ?thesis unfolding psi_def Live2_def STL5[int_rewrite] by force
qed
text \<open>
In the same way we prove that \<open>psi\<close> implements strong fairness
for the abstract action \<open>m1\<close>. The proof is obtained by copy and paste
from the previous one.
\<close>
lemma (in Secondprogram) psi_fair_m2: "\<turnstile> psi \<longrightarrow> SF(m2)_(x,y)"
proof -
have "\<turnstile> \<box>[n1 \<or> n2]_vars \<and> SF(n2)_vars \<and> \<box>(I \<and> SF(n1)_vars) \<longrightarrow> SF(m2)_(x,y)"
proof (rule SF2)
txt \<open>
Rule \<open>SF2\<close> requires us to choose a helpful action (whose effect implies
\<open>\<langle>m2\<rangle>_(x,y)\<close>) and a persistent condition, which will eventually remain
true if the helpful action is never executed. In our case, the helpful action
is \<open>beta2\<close> and the persistent condition is \<open>pc2 = b\<close>.
\<close>
show "|~ \<langle>(n1 \<or> n2) \<and> beta2\<rangle>_vars \<longrightarrow> \<langle>m2\<rangle>_(x,y)"
by (auto simp: beta2_def m2_def vars_def tla_defs)
next
show "|~ $pc2 = #b \<and> \<circle>($pc2 = #b) \<and> \<langle>(n1 \<or> n2) \<and> n2\<rangle>_vars \<longrightarrow> beta2"
by (auto simp: n2_def alpha2_def beta2_def gamma2_def tla_defs)
next
show "\<turnstile> $pc2 = #b \<and> Enabled \<langle>m2\<rangle>_(x, y) \<longrightarrow> Enabled \<langle>n2\<rangle>_vars"
unfolding enab_n2[int_rewrite] by auto
next
txt \<open>
The difficult part of the proof is showing that the persistent condition
will eventually always be true if the helpful action is never executed.
We show that (1) whenever the condition becomes true it remains so and
(2) eventually the condition must be true.
\<close>
show "\<turnstile> \<box>[(n1 \<or> n2) \<and> \<not> beta2]_vars
\<and> SF(n2)_vars \<and> \<box>(I \<and> SF(n1)_vars) \<and> \<box>\<diamond>Enabled \<langle>m2\<rangle>_(x, y)
\<longrightarrow> \<diamond>\<box>($pc2 = #b)"
proof -
have "\<turnstile> \<box>\<box>[(n1 \<or> n2) \<and> \<not> beta2]_vars \<longrightarrow> \<box>($pc2 = #b \<longrightarrow> \<box>($pc2 = #b))"
proof (rule STL4)
have "|~ $pc2 = #b \<and> [(n1 \<or> n2) \<and> \<not> beta2]_vars \<longrightarrow> \<circle>($pc2 = #b)"
by (auto simp: Sact2_defs vars_def tla_defs)
from this[THEN INV1]
show "\<turnstile> \<box>[(n1 \<or> n2) \<and> \<not> beta2]_vars \<longrightarrow> $pc2 = #b \<longrightarrow> \<box>($pc2 = #b)" by auto
qed
hence 1: "\<turnstile> \<box>[(n1 \<or> n2) \<and> \<not> beta2]_vars \<longrightarrow> \<diamond>($pc2 = #b) \<longrightarrow> \<diamond>\<box>($pc2 = #b)"
by (force intro: E31[unlift_rule])
have "\<turnstile> \<box>[(n1 \<or> n2) \<and> \<not> beta2]_vars \<and> SF(n2)_vars \<and> \<box>(I \<and> SF(n1)_vars)
\<longrightarrow> \<diamond>($pc2 = #b)"
proof -
txt \<open>
The plan of the proof is to show that from any state where \<open>pc2 = g\<close>
one eventually reaches \<open>pc2 = a\<close>, from where one eventually reaches
\<open>pc2 = b\<close>. The result follows by combining leadsto properties.
\<close>
let ?F = "LIFT (\<box>[(n1 \<or> n2) \<and> \<not> beta2]_vars \<and> SF(n2)_vars \<and> \<box>(I \<and> SF(n1)_vars))"
txt \<open>
Showing that \<open>pc2 = g\<close> leads to \<open>pc2 = a\<close> is a simple
application of rule \<open>SF1\<close> because the second process completely
controls this transition.
\<close>
have ga: "\<turnstile> ?F \<longrightarrow> ($pc2 = #g \<leadsto> $pc2 = #a)"
proof (rule SF1)
show "|~ $pc2 = #g \<and> [(n1 \<or> n2) \<and> \<not> beta2]_vars \<longrightarrow> \<circle>($pc2 = #g) \<or> \<circle>($pc2 = #a)"
by (auto simp: Sact2_defs vars_def tla_defs)
next
show "|~ $pc2 = #g \<and> \<langle>((n1 \<or> n2) \<and> \<not> beta2) \<and> n2\<rangle>_vars \<longrightarrow> \<circle>($pc2 = #a)"
by (auto simp: n2_def alpha2_def beta2_def gamma2_def vars_def tla_defs)
next
show "|~ $pc2 = #g \<and> Unchanged vars \<longrightarrow> \<circle>($pc2 = #g)"
by (auto simp: vars_def tla_defs)
next
have "\<turnstile> $pc2 = #g \<longrightarrow> Enabled \<langle>n2\<rangle>_vars"
unfolding enab_n2[int_rewrite] by (auto simp: tla_defs)
hence "\<turnstile> \<box>($pc2 = #g) \<longrightarrow> Enabled \<langle>n2\<rangle>_vars"
by (rule lift_imp_trans[OF ax1])
hence "\<turnstile> \<box>($pc2 = #g) \<longrightarrow> \<diamond>Enabled \<langle>n2\<rangle>_vars"
by (rule lift_imp_trans[OF _ E3])
thus "\<turnstile> \<box>($pc2 = #g) \<and> \<box>[(n1 \<or> n2) \<and> \<not> beta2]_vars \<and> \<box>(I \<and> SF(n1)_vars)
\<longrightarrow> \<diamond>Enabled \<langle>n2\<rangle>_vars"
by auto
qed
txt \<open>
The proof that \<open>pc2 = a\<close> leads to \<open>pc2 = b\<close> follows
the same basic schema. However, showing that \<open>n2\<close> is eventually
enabled requires reasoning about the second process, which must liberate
the critical section.
\<close>
have ab: "\<turnstile> ?F \<longrightarrow> ($pc2 = #a \<leadsto> $pc2 = #b)"
proof (rule SF1)
show "|~ $pc2 = #a \<and> [(n1 \<or> n2) \<and> \<not> beta2]_vars \<longrightarrow> \<circle>($pc2 = #a) \<or> \<circle>($pc2 = #b)"
by (auto simp: Sact2_defs vars_def tla_defs)
next
show "|~ $pc2 = #a \<and> \<langle>((n1 \<or> n2) \<and> \<not> beta2) \<and> n2\<rangle>_vars \<longrightarrow> \<circle>($pc2 = #b)"
by (auto simp: n2_def alpha2_def beta2_def gamma2_def vars_def tla_defs)
next
show "|~ $pc2 = #a \<and> Unchanged vars \<longrightarrow> \<circle>($pc2 = #a)"
by (auto simp: vars_def tla_defs)
next
txt \<open>We establish a suitable leadsto-chain.\<close>
let ?G = "LIFT \<box>[(n1 \<or> n2) \<and> \<not> beta2]_vars \<and> SF(n1)_vars \<and> \<box>($pc2 = #a \<and> I)"
have "\<turnstile> ?G \<longrightarrow> \<diamond>($pc1 = #a \<and> $pc2 = #a \<and> I)"
proof -
txt \<open>Rule \<open>SF1\<close> takes us from \<open>pc1 = b\<close> to \<open>pc1 = g\<close>.\<close>
have bg1: "\<turnstile> ?G \<longrightarrow> ($pc1 = #b \<leadsto> $pc1 = #g)"
proof (rule SF1)
show "|~ $pc1 = #b \<and> [(n1 \<or> n2) \<and> \<not>beta2]_vars \<longrightarrow> \<circle>($pc1 = #b) \<or> \<circle>($pc1 = #g)"
by (auto simp: Sact2_defs vars_def tla_defs)
next
show "|~ $pc1 = #b \<and> \<langle>((n1 \<or> n2) \<and> \<not>beta2) \<and> n1\<rangle>_vars \<longrightarrow> \<circle>($pc1 = #g)"
by (auto simp: n1_def alpha1_def beta1_def gamma1_def vars_def tla_defs)
next
show "|~ $pc1 = #b \<and> Unchanged vars \<longrightarrow> \<circle>($pc1 = #b)"
by (auto simp: vars_def tla_defs)
next
have "\<turnstile> $pc1 = #b \<longrightarrow> Enabled \<langle>n1\<rangle>_vars"
unfolding enab_n1[int_rewrite] by (auto simp: tla_defs)
hence "\<turnstile> \<box>($pc1 = #b) \<longrightarrow> Enabled \<langle>n1\<rangle>_vars"
by (rule lift_imp_trans[OF ax1])
hence "\<turnstile> \<box>($pc1 = #b) \<longrightarrow> \<diamond>Enabled \<langle>n1\<rangle>_vars"
by (rule lift_imp_trans[OF _ E3])
thus "\<turnstile> \<box>($pc1 = #b) \<and> \<box>[(n1 \<or> n2) \<and> \<not>beta2]_vars \<and> \<box>($pc2 = #a \<and> I)
\<longrightarrow> \<diamond>Enabled \<langle>n1\<rangle>_vars"
by auto
qed
txt \<open>Similarly, \<open>pc1 = b\<close> leads to \<open>pc1 = g\<close>.\<close>
have ga1: "\<turnstile> ?G \<longrightarrow> ($pc1 = #g \<leadsto> $pc1 = #a)"
proof (rule SF1)
show "|~ $pc1 = #g \<and> [(n1 \<or> n2) \<and> \<not>beta2]_vars \<longrightarrow> \<circle>($pc1 = #g) \<or> \<circle>($pc1 = #a)"
by (auto simp: Sact2_defs vars_def tla_defs)
next
show "|~ $pc1 = #g \<and> \<langle>((n1 \<or> n2) \<and> \<not>beta2) \<and> n1\<rangle>_vars \<longrightarrow> \<circle>($pc1 = #a)"
by (auto simp: n1_def alpha1_def beta1_def gamma1_def vars_def tla_defs)
next
show "|~ $pc1 = #g \<and> Unchanged vars \<longrightarrow> \<circle>($pc1 = #g)"
by (auto simp: vars_def tla_defs)
next
have "\<turnstile> $pc1 = #g \<longrightarrow> Enabled \<langle>n1\<rangle>_vars"
unfolding enab_n1[int_rewrite] by (auto simp: tla_defs)
hence "\<turnstile> \<box>($pc1 = #g) \<longrightarrow> Enabled \<langle>n1\<rangle>_vars"
by (rule lift_imp_trans[OF ax1])
hence "\<turnstile> \<box>($pc1 = #g) \<longrightarrow> \<diamond>Enabled \<langle>n1\<rangle>_vars"
by (rule lift_imp_trans[OF _ E3])
thus "\<turnstile> \<box>($pc1 = #g) \<and> \<box>[(n1 \<or> n2) \<and> \<not>beta2]_vars \<and> \<box>($pc2 = #a \<and> I)
\<longrightarrow> \<diamond>Enabled \<langle>n1\<rangle>_vars"
by auto
qed
with bg1 have "\<turnstile> ?G \<longrightarrow> ($pc1 = #b \<leadsto> $pc1 = #a)"
by (force elim: LT13[unlift_rule])
with ga1 have "\<turnstile> ?G \<longrightarrow> ($pc1 = #a \<or> $pc1 = #b \<or> $pc1 = #g) \<leadsto> ($pc1 = #a)"
unfolding LT17[int_rewrite] LT1[int_rewrite] by force
moreover
have "\<turnstile> $pc1 = #a \<or> $pc1 = #b \<or> $pc1 = #g"
proof (clarsimp simp: tla_defs)
fix s :: "state seq"
assume "pc1 (s 0) \<noteq> a" and "pc1 (s 0) \<noteq> g"
thus "pc1 (s 0) = b" by (cases "pc1 (s 0)") auto
qed
hence "\<turnstile> (($pc1 = #a \<or> $pc1 = #b \<or> $pc1 = #g) \<leadsto> $pc1 = #a) \<longrightarrow> \<diamond>($pc1 = #a)"
by (rule fmp[OF _ LT4])
ultimately
have "\<turnstile> ?G \<longrightarrow> \<diamond>($pc1 = #a)" by force
thus ?thesis by (auto intro!: SE3[unlift_rule])
qed
moreover
have "\<turnstile> \<diamond>($pc1 = #a \<and> $pc2 = #a \<and> I) \<longrightarrow> \<diamond>Enabled \<langle>n2\<rangle>_vars"
unfolding enab_n2[int_rewrite] by (rule STL4_eve) (auto simp: I_def tla_defs)
ultimately
show "\<turnstile> \<box>($pc2 = #a) \<and> \<box>[(n1 \<or> n2) \<and> \<not> beta2]_vars \<and> \<box>(I \<and> SF(n1)_vars)
\<longrightarrow> \<diamond>Enabled \<langle>n2\<rangle>_vars"
by (force simp: STL5[int_rewrite])
qed
from ga ab have "\<turnstile> ?F \<longrightarrow> ($pc2 = #g \<leadsto> $pc2 = #b)"
by (force elim: LT13[unlift_rule])
with ab have "\<turnstile> ?F \<longrightarrow> (($pc2 = #a \<or> $pc2 = #b \<or> $pc2 = #g) \<leadsto> $pc2 = #b)"
unfolding LT17[int_rewrite] LT1[int_rewrite] by force
moreover
have "\<turnstile> $pc2 = #a \<or> $pc2 = #b \<or> $pc2 = #g"
proof (clarsimp simp: tla_defs)
fix s :: "state seq"
assume "pc2 (s 0) \<noteq> a" and "pc2 (s 0) \<noteq> g"
thus "pc2 (s 0) = b" by (cases "pc2 (s 0)") auto
qed
hence "\<turnstile> (($pc2 = #a \<or> $pc2 = #b \<or> $pc2 = #g) \<leadsto> $pc2 = #b) \<longrightarrow> \<diamond>($pc2 = #b)"
by (rule fmp[OF _ LT4])
ultimately show ?thesis by (rule lift_imp_trans)
qed
with 1 show ?thesis by force
qed
qed
with psiI show ?thesis unfolding psi_def Live2_def STL5[int_rewrite] by force
qed
text \<open>
We can now prove the main theorem, which states that \<open>psi\<close>
implements \<open>phi\<close>.
\<close>
theorem (in Secondprogram) impl: "\<turnstile> psi \<longrightarrow> phi"
unfolding phi_def Live_def
by (auto dest: step_simulation[unlift_rule]
lift_imp_trans[OF psi_fair_m1 SF_imp_WF, unlift_rule]
lift_imp_trans[OF psi_fair_m2 SF_imp_WF, unlift_rule])
end
|
lemma reflect_poly_at_0_eq_0_iff [simp]: "poly (reflect_poly p) 0 = 0 \<longleftrightarrow> p = 0" |
import SciLean.Core.Functions
namespace SciLean
variable {α β γ : Type}
variable {X Y Z : Type} [Hilbert X] [Hilbert Y] [Hilbert Z]
example : IsLin (SemiInner.semiInner : X → X → _) := by infer_instance done
example Ω : IsLin (λ x y : X => ⟪x, y⟫[Ω]) := by infer_instance done
example (x : X) Ω : IsLin (λ y : X => ⟪x, y⟫[Ω]) := by infer_instance done
-- example {X Y R D eval} [Vec R] [FinVec X] [SemiInner Y R D eval] [Vec Y]
-- : SemiInner (X ⊸ Y) R D eval := by infer_instance
-- example {X Y R D eval} [Vec R] [FinVec X] [SemiHilbert Y R D eval]
-- : SemiHilbert (X ⊸ Y) R D eval := by infer_instance
-- example {X Y} [FinVec X] [Hilbert Y] : Hilbert (X ⊸ Y) := by infer_instance
-- example {Y} [Hilbert Y] : Hilbert (ℝ ⊸ Y) := by infer_instance
-- example {X} [FinVec X] : SemiInner (X ⊸ ℝ) ℝ Unit (λ r _ => r) := by infer_instance
-- example {X} [FinVec X] : Hilbert (X ⊸ ℝ) := by infer_instance
-- This was a problem at some point
section mul_test
variable {X : Type} [Hilbert X] (x y : X) (r s : ℝ)
#check r * x
end mul_test
|
import Data.Either
import Data.List
import Data.Maybe
import Data.String
import Data.String.Parser
import System.File
wordParser : Parser String
wordParser = do chars <- some letter
pure $ pack chars
outputParser : Parser (List String, List String)
outputParser = do i <- wordParser `sepBy` spaces
spaces
token "|"
o <- wordParser `sepBy` spaces
pure (i, o)
parseOutput : String -> Maybe (List String, List String)
parseOutput s = case parse outputParser s of
Left _ => Nothing
Right (l, _) => Just l
parseLines : (String -> Maybe a) -> String -> List a
parseLines f s = catMaybes $ f <$> lines s
lenEq : Nat -> String -> Bool
lenEq n s = length s == n
sortString : String -> String
sortString s = pack $ sort $ unpack s
decodeall : List String -> Maybe (List (String, String))
decodeall l = do one <- find (lenEq 2) l
four <- find (lenEq 4) l
seven <- find (lenEq 3) l
eight <- find (lenEq 7) l
let zeroorsixornine = filter (lenEq 6) l
nine <- find (\x => (==) 4 $ length $ intersect (unpack x) (unpack four)) zeroorsixornine
let zeroorsix = delete nine zeroorsixornine
six <- find (\x => (==) 1 $ length $ intersect (unpack x) (unpack one)) zeroorsix
zero <- head' $ delete six $ zeroorsix
let twothreeorfive = filter (lenEq 5) l
three <- find (\x => (==) 2 $ length $ intersect (unpack x) (unpack one)) twothreeorfive
let twoorfive = delete three twothreeorfive
two <- find (\x => (==) 2 $ length $ ((\\) `on` unpack) six x) twoorfive
five <- head' $ delete three $ delete two $ twoorfive
pure $ [
(sortString $ zero, "0"),
(sortString $ one, "1"),
(sortString $ two, "2"),
(sortString $ three, "3"),
(sortString $ four, "4"),
(sortString $ five, "5"),
(sortString $ six, "6"),
(sortString $ seven, "7"),
(sortString $ eight, "8"),
(sortString $ nine, "9")
]
decode : (List String, List String) -> Maybe Nat
decode (i, o) = do m <- decodeall i
parsePositive $ fastAppend $ catMaybes $ ((flip lookup) m . sortString <$> o)
run : String -> IO String
run s = do let l = parseLines parseOutput s
let r = sum $ catMaybes $ decode <$> l
pure $ show r
main : IO ()
main = do Right s <- readFile "input.txt"
| Left err => putStrLn $ show err
run s >>= putStrLn
|
#!/usr/bin/python3
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import sys
# Plotting graphs for the simulator talk
# Read filenames
filename = "qsim_cnot.csv"
# Read the file into a dataframe
df = pd.read_csv(filename, comment='#', delim_whitespace=True)
# Plotting the graph
cols_list = list(range(1, len(df.columns)))
df.plot(0, y=cols_list, rot=1, logy=True, grid=True, style='o-', \
xlabel='Number of qubits', ylabel='Time taken per gate (seconds)',
title='Testing the controlled Not gate', linewidth=0.7)
plt.show()
|
!==============================================================================!
subroutine Cgns_Mod_Close_File
!------------------------------------------------------------------------------!
! Closes file_id file [parallel vesion] !
!------------------------------------------------------------------------------!
implicit none
!-----------------------------------[Locals]-----------------------------------!
integer :: error
!==============================================================================!
! Close a CGNS file
call Cgp_Close_F(file_id, & !(in )
error) !(out)
if (error .ne. 0) then
print *, "# Failed to close the file: ", trim(file_name)
call Cgp_Error_Exit_F()
endif
end subroutine |
#pragma once
#include <gsl/gsl>
#include "halley/utils/utils.h"
#include <vector>
namespace Halley {
class String;
class Path;
class FileSystem
{
public:
static bool exists(const Path& p);
static bool createDir(const Path& p);
static bool createParentDir(const Path& p);
static int64_t getLastWriteTime(const Path& p);
static bool isFile(const Path& p);
static bool isDirectory(const Path& p);
static void copyFile(const Path& src, const Path& dst);
static bool remove(const Path& path);
static void writeFile(const Path& path, gsl::span<const gsl::byte> data);
static void writeFile(const Path& path, const Bytes& data);
static Bytes readFile(const Path& path);
static std::vector<Path> enumerateDirectory(const Path& path);
static Path getRelative(const Path& path, const Path& parentPath);
static Path getAbsolute(const Path& path);
static size_t fileSize(const Path& path);
static Path getTemporaryPath();
static int runCommand(const String& command);
};
}
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
module Pinwheel.FourierSeries2D where
import Control.Monad as M
import Control.Monad.IO.Class
import Control.Monad.Trans.Resource
import qualified Data.Array.Accelerate as A
import Data.Array.Accelerate.LLVM.PTX as A
import Data.Array.IArray as IA
import Data.Array.Repa as R
import Data.Complex
import Data.Conduit as C
import Data.Conduit.List as CL
import Data.List as L
import Data.Vector.Generic as VG
import Data.Vector.Storable as VS
import Data.Vector.Unboxed as VU
import Foreign.CUDA.Driver as CUDA
import FourierMethod.FourierSeries2D
import Math.Gamma
import Pinwheel.Base
import Pinwheel.List
import Utils.BLAS
import Utils.Distribution
import Utils.List
import Utils.Parallel hiding ((.|))
import Utils.SimpsonRule
import Utils.Time
import DFT.Plan
import Filter.Utils
import Control.Concurrent.Async
import Numeric.GSL.Special.Bessel
pinwheelFourierSeries ::
( Storable e
, CUBLAS (Complex e)
, Unbox e
, RealFloat e
, A.Elt e
, A.Elt (Complex e)
, Floating (A.Exp e)
, A.FromIntegral Int e
, VG.Vector vector (Complex e)
, NFData (vector (Complex e))
)
=> [Int]
-> [PTX]
-> Int
-> Int
-> e
-> e
-> Int
-> Int
-> Int
-> Int
-> e
-> Int
-> Int
-> IO (IA.Array (Int, Int) (vector (Complex e)))
pinwheelFourierSeries deviceIDs ptxs numR2Freqs numPoints delta periodR2 phiFreq rhoFreq thetaFreq rFreq sigma numBatchR2 numBatchPinwheelFreqs = do
let idxs =
[ (radialFreq, angularFreq)
| radialFreq <- pinwheelFreqs rhoFreq rFreq
, angularFreq <- pinwheelFreqs phiFreq thetaFreq
]
centerR2Freq = div numR2Freqs 2
pinwheels <-
computeUnboxedP .
R.traverse
(fromListUnboxed (Z :. (L.length idxs)) idxs)
(\(Z :. freqs) -> (Z :. freqs :. numR2Freqs :. numR2Freqs)) $ \f (Z :. pFreq :. xFreq :. yFreq) ->
fourierMellin
sigma
(snd $ f (Z :. pFreq))
(fst $ f (Z :. pFreq))
( delta * fromIntegral (xFreq - centerR2Freq)
, delta * fromIntegral (yFreq - centerR2Freq))
-- pinwheels <-
-- M.mapM
-- (\idx ->
-- fmap
-- (CuMat (numR2Freqs ^ 2) (L.length idx) .
-- CuVecHost . VU.convert . toUnboxed) .
-- computeP .
-- R.traverse
-- (fromListUnboxed (Z :. (L.length idx)) idx)
-- (\(Z :. freqs) -> (Z :. numR2Freqs :. numR2Freqs :. freqs)) $ \f (Z :. xFreq :. yFreq :. pFreq) ->
-- fourierMellin
-- sigma
-- (snd $ f (Z :. pFreq))
-- (fst $ f (Z :. pFreq))
-- ( fromIntegral (xFreq - centerR2Freq)
-- , fromIntegral (yFreq - centerR2Freq))) .
-- divideListN numBatchPinwheelFreqs $
-- idxs
-- printCurrentTime "Compute Fourier Series... "
-- arr <-
-- computeFourierSeriesR2Stream
-- deviceIDs
-- ptxs
-- numR2Freqs
-- numPoints
-- periodR2
-- delta
-- numBatchR2
-- pinwheels
-- printCurrentTime "Compute Fourier Series Done"
let (radialLB, radialUB) = pinwheelFreqsBound rhoFreq rFreq
(angularLB, angularUB) = pinwheelFreqsBound phiFreq thetaFreq
return .
listArray ((radialLB, angularLB), (radialUB, angularUB)) .
parMap
rdeepseq
(\i ->
VG.convert . toUnboxed . computeS . R.slice pinwheels $ -- arr $
(Z :. i :. All :. All)) $
[0 .. (L.length idxs - 1)]
-- Stream
{-# INLINE source #-}
source :: Int -> Int -> Int -> Int -> ConduitT () (Int, Int) (ResourceT IO) ()
source phiFreq rhoFreq thetaFreq rFreq =
CL.sourceList
[ (radialFreq, angularFreq)
| radialFreq <- pinwheelFreqs rhoFreq rFreq
, angularFreq <- pinwheelFreqs phiFreq thetaFreq
]
conduit ::
( Storable e
, CUBLAS (Complex e)
, Unbox e
, RealFloat e
, A.Elt e
, A.Elt (Complex e)
, Floating (A.Exp e)
, A.FromIntegral Int e
, VG.Vector vector (Complex e)
)
=> [Int]
-> Int
-> Int
-> e
-> Int
-> e
-> [[CuMat (Complex e)]]
-> ConduitT (Int, Int) [vector (Complex e)] (ResourceT IO) ()
conduit deviceIDs numR2Freqs numPoints periodR2 batchSize sigma inverseR2Harmonics = do
liftIO $ printCurrentTime "conduit"
idx <- CL.take batchSize
unless
(L.null idx)
(do let centerR2Freq = div numR2Freqs 2
pinwheels <-
fmap
(CuMat (L.length idx) (numR2Freqs ^ 2) .
CuVecHost . VU.convert . toUnboxed) .
liftIO .
computeP .
R.traverse
(fromListUnboxed (Z :. (L.length idx)) idx)
(\(Z :. freqs) -> (Z :. freqs :. numR2Freqs :. numR2Freqs)) $ \f (Z :. pFreq :. xFreq :. yFreq) ->
fourierMellin
sigma
(snd $ f (Z :. pFreq))
(fst $ f (Z :. pFreq))
( fromIntegral (xFreq - centerR2Freq)
, fromIntegral (yFreq - centerR2Freq))
arr <-
liftIO $
computeFourierSeriesR2
deviceIDs
numR2Freqs
numPoints
periodR2
inverseR2Harmonics
[pinwheels]
yield .
L.map
(\i ->
VG.convert . toUnboxed . computeS . R.slice arr $
(Z :. i :. All :. All)) $
[0 .. (L.length idx - 1)])
pinwheelFourierSeriesStream ::
( Storable e
, CUBLAS (Complex e)
, Unbox e
, RealFloat e
, A.Elt e
, A.Elt (Complex e)
, Floating (A.Exp e)
, A.FromIntegral Int e
, VG.Vector vector (Complex e)
)
=> [Int]
-> [PTX]
-> Int
-> Int
-> e
-> e
-> Int
-> Int
-> Int
-> Int
-> e
-> Int
-> Int
-> Int
-> IO (IA.Array (Int, Int) (vector (Complex e)))
pinwheelFourierSeriesStream deviceIDs ptxs numR2Freqs numPoints delta periodR2 phiFreq rhoFreq thetaFreq rFreq sigma numBatchR2 batchSize numBatchPinwheelFreqs = do
inverseR2Harmonics <-
createInverseHarmonicMatriesGPU
ptxs
numBatchR2
numPoints
numR2Freqs
periodR2
delta
let (radialLB, radialUB) = pinwheelFreqsBound rhoFreq rFreq
(angularLB, angularUB) = pinwheelFreqsBound rhoFreq rFreq
fmap (listArray ((radialLB, angularLB), (radialUB, radialUB)) . L.concat) .
runConduitRes $
source phiFreq rhoFreq thetaFreq rFreq .|
conduit
deviceIDs
numR2Freqs
numPoints
periodR2
batchSize
sigma
inverseR2Harmonics .|
CL.consume
-- 2D spatial domain to frequency domain:
-- transform: cis (-freq * x)
-- inverse transform: cis (freq * x)
-- Analytical solution type 1
-- The pinwheel harmonics are cis (-freq * x)
{-# INLINE analyticalFourierSeriesFunc1 #-}
analyticalFourierSeriesFunc1 ::
(Eq e, Fractional e, RealFloat e, Gamma (Complex e))
=> Int
-> Int
-> e
-> e
-> e
-> e
-> e
-> Complex e
analyticalFourierSeriesFunc1 angularFreq radialFreq sigma periodR2 periodEnv phi rho =
let radialConst = 2 * pi / log periodEnv
in pi * ((0 :+ 1) ^ abs angularFreq) *
cis (fromIntegral (-angularFreq) * phi) *
((periodR2 / (pi * rho) :+ 0) **
((2 + sigma) :+ (radialConst * fromIntegral (-radialFreq)))) *
gamma
(((2 + fromIntegral (abs angularFreq) + sigma) :+
(radialConst * fromIntegral (-radialFreq))) /
2) /
gamma
(((fromIntegral (abs angularFreq) - sigma) :+
(radialConst * fromIntegral radialFreq)) /
2)
-- The pinwheel is in the frequency domain, the function computes the Fourier series
{-# INLINE analyticalFourierSeries1 #-}
analyticalFourierSeries1 ::
(Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)
=> Int
-> e
-> Int
-> Int
-> e
-> e
-> e
-> R.Array D DIM2 (Complex e)
analyticalFourierSeries1 numPoints delta angularFreq radialFreq sigma periodR2 periodEnv =
let center = div numPoints 2
in fromFunction (Z :. numPoints :. numPoints) $ \(Z :. i :. j) ->
let x = fromIntegral $ i - center
y = fromIntegral $ j - center
rho = sqrt $ x ^ 2 + y ^ 2
phi = atan2 y x
in if rho == 0
then 0
else analyticalFourierSeriesFunc1
angularFreq
radialFreq
sigma
periodR2
periodEnv
phi
(rho * delta)
-- The pinwheel is in the spatial domain, the function computes the Fourier coefficients
{-# INLINE analyticalFourierCoefficients1 #-}
analyticalFourierCoefficients1 ::
(Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)
=> Int
-> e
-> Int
-> Int
-> e
-> e
-> e
-> R.Array D DIM2 (Complex e)
analyticalFourierCoefficients1 numFreqs delta angularFreq radialFreq sigma periodR2 periodEnv =
let c = ((-1) ^ (abs angularFreq)) :+ 0
in R.map (* c) $
analyticalFourierSeries1 numFreqs delta angularFreq radialFreq sigma periodR2 periodEnv
-- Analytical solution type 2
-- The pinwheel harmonics are cis (freq * x)
{-# INLINE analyticalFourierSeriesFunc2 #-}
analyticalFourierSeriesFunc2 ::
(Eq e, Fractional e, RealFloat e, Gamma (Complex e))
=> Int
-> Int
-> e
-> e
-> e
-> e
-> e
-> Complex e
analyticalFourierSeriesFunc2 angularFreq radialFreq sigma periodR2 periodEnv phi rho =
let radialConst = 2 * pi / (log periodEnv)
in pi * ((0 :+ 1) ^ (abs angularFreq)) *
((cis (fromIntegral angularFreq * phi))) *
((periodR2 / (pi * rho) :+ 0) **
((2 + sigma) :+ (radialConst * fromIntegral radialFreq))) *
(gamma $
((2 + fromIntegral (abs angularFreq) + sigma) :+
(radialConst * fromIntegral radialFreq)) /
2) /
(gamma $
((fromIntegral (abs angularFreq) - sigma) :+
(radialConst * fromIntegral (-radialFreq))) /
2)
-- The pinwheel is in the frequency domain, the function computes the Fourier series
{-# INLINE analyticalFourierSeries2 #-}
analyticalFourierSeries2 ::
(Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)
=> Int
-> e
-> Int
-> Int
-> e
-> e
-> e
-> R.Array D DIM2 (Complex e)
analyticalFourierSeries2 numPoints delta angularFreq radialFreq sigma periodR2 periodEnv =
let center = div numPoints 2
arr =
fromFunction (Z :. numPoints :. numPoints) $ \(Z :. i :. j) ->
let x = delta * (fromIntegral $ i - center)
y = delta * (fromIntegral $ j - center)
rho = sqrt $ x ^ 2 + y ^ 2
phi = atan2 y x
in if rho == 0 -- || (rho > period / 2) -- || phi /= 0
then 0
else analyticalFourierSeriesFunc2
angularFreq
radialFreq
sigma
periodR2
periodEnv
phi
rho
-- if angularFreq == 0
-- then fromFunction (Z :. numPoints :. numPoints) $ \_ -> 0
-- else
in arr
-- The pinwheel is in the spatial domain, the function computes the Fourier coefficients
{-# INLINE analyticalFourierCoefficients2 #-}
analyticalFourierCoefficients2 ::
(Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)
=> Int
-> e
-> Int
-> Int
-> e
-> e
-> e
-> R.Array D DIM2 (Complex e)
analyticalFourierCoefficients2 numFreqs delta angularFreq radialFreq sigma periodR2 periodEnv =
let c = ((-1) ^ (abs angularFreq)) / periodR2 :+ 0
in R.map (* c) $
analyticalFourierSeries2
numFreqs
delta
angularFreq
radialFreq
sigma
periodR2
periodEnv
-- Analytical solution type 3
-- The pinwheel harmonics are cis (-freq * x)
-- The envelope is r^2 * r^\alpha, where \alpha \in (-2,-0.5)
{-# INLINE analyticalFourierSeriesFunc3 #-}
analyticalFourierSeriesFunc3 ::
(Eq e, Fractional e, RealFloat e, Gamma (Complex e))
=> Int
-> Int
-> e
-> e
-> e
-> e
-> e
-> Complex e
analyticalFourierSeriesFunc3 angularFreq radialFreq sigma periodR2 periodEnv phi rho =
let radialConst = 2 * pi / log periodEnv
in ((fromIntegral angularFreq ^ 2 :+ 0) -
((sigma + 2) :+ (radialConst * fromIntegral (-radialFreq))) ^ 2) /
(8 * pi) *
((0 :+ 1) ^ abs angularFreq) *
cis (fromIntegral (-angularFreq) * phi) /
(rho ^ 2 :+ 0) *
((periodR2 / (pi * rho) :+ 0) **
((2 + sigma) :+ (radialConst * fromIntegral (-radialFreq)))) *
gamma
(((2 + fromIntegral (abs angularFreq) + sigma) :+
(radialConst * fromIntegral (-radialFreq))) /
2) /
gamma
(((fromIntegral (abs angularFreq) - sigma) :+
(radialConst * fromIntegral radialFreq)) /
2)
{-# INLINE analyticalFourierSeries3 #-}
analyticalFourierSeries3 ::
(Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)
=> Int
-> e
-> Int
-> Int
-> e
-> e
-> e
-> R.Array D DIM2 (Complex e)
analyticalFourierSeries3 numPoints delta angularFreq radialFreq sigma periodR2 periodEnv =
let center = div numPoints 2
in fromFunction (Z :. numPoints :. numPoints) $ \(Z :. i :. j) ->
let x = fromIntegral $ i - center
y = fromIntegral $ j - center
rho = sqrt $ x ^ 2 + y ^ 2
phi = atan2 y x
in if rho == 0
then 0
else analyticalFourierSeriesFunc3
angularFreq
radialFreq
sigma
periodR2
periodEnv
phi
(rho * delta)
{-# INLINE analyticalFourierCoefficients3 #-}
analyticalFourierCoefficients3 ::
(Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)
=> Int
-> e
-> Int
-> Int
-> e
-> e
-> e
-> R.Array D DIM2 (Complex e)
analyticalFourierCoefficients3 numFreqs delta angularFreq radialFreq sigma periodR2 periodEnv =
let c = ((-1) ^ (abs angularFreq)) :+ 0
in R.map (* c) $
analyticalFourierSeries3 numFreqs delta angularFreq radialFreq sigma periodR2 periodEnv
pinwheelFourierCoefficientsAnatical ::
( Unbox e
, RealFloat e
, Gamma (Complex e)
, VG.Vector vector (Complex e)
, NFData (vector (Complex e))
)
=> Int
-> Int
-> Int
-> Int
-> Int
-> e
-> e
-> e
-> IA.Array (Int, Int) (vector (Complex e))
pinwheelFourierCoefficientsAnatical numR2Freqs phiFreq rhoFreq thetaFreq rFreq sigma periodR2 periodEnv =
let idxs =
[ (radialFreq, angularFreq)
| radialFreq <- pinwheelFreqs rhoFreq rFreq
, angularFreq <- pinwheelFreqs phiFreq thetaFreq
]
centerR2Freq = div numR2Freqs 2
(radialLB, radialUB) = pinwheelFreqsBound rhoFreq rFreq
(angularLB, angularUB) = pinwheelFreqsBound phiFreq thetaFreq
pinwheels =
parMap
rdeepseq
(\(radialFreq, angularFreq) ->
VG.convert .
toUnboxed .
computeS -- .
-- R.zipWith
-- (*)
-- (fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \(Z :. i :. j) ->
-- gaussian2D
-- (fromIntegral $ i - centerR2Freq)
-- (fromIntegral $ j - centerR2Freq)
-- (fromIntegral $ div centerR2Freq 1))
$
analyticalFourierCoefficients2
numR2Freqs
1
(angularFreq)
(radialFreq)
sigma
periodR2
periodEnv)
idxs
in listArray ((radialLB, angularLB), (radialUB, angularUB)) pinwheels
pinwheelFourierCoefficientsAnaticalList ::
( Unbox e
, RealFloat e
, Gamma (Complex e)
, VG.Vector vector (Complex e)
, NFData (vector (Complex e))
)
=> Int
-> Int
-> Int
-> Int
-> Int
-> e
-> e
-> e
-> [vector (Complex e)]
pinwheelFourierCoefficientsAnaticalList numR2Freqs phiFreq rhoFreq thetaFreq rFreq sigma periodR2 periodEnv =
let idxs =
[ (radialFreq, angularFreq)
| radialFreq <- [-rhoFreq .. rhoFreq]
, angularFreq <- [-phiFreq .. phiFreq]
]
centerR2Freq = div numR2Freqs 2
pinwheels =
parMap
rdeepseq
(\(radialFreq, angularFreq) ->
VG.convert . toUnboxed . computeS $
analyticalFourierCoefficients2
numR2Freqs
1
(angularFreq)
(radialFreq)
sigma
periodR2
periodEnv)
idxs
in pinwheels
pinwheelFourierCoefficientsAnaticalList1 ::
( Unbox e
, RealFloat e
, Gamma (Complex e)
, VG.Vector vector (Complex e)
, NFData (vector (Complex e))
)
=> Int
-> Int
-> Int
-> Int
-> Int
-> e
-> e
-> e
-> [vector (Complex e)]
pinwheelFourierCoefficientsAnaticalList1 numR2Freqs phiFreq rhoFreq thetaFreq rFreq sigma periodR2 periodEnv =
let idxs =
[ (radialFreq, angularFreq)
| radialFreq <- [-rhoFreq .. rhoFreq]
, angularFreq <- [-phiFreq .. phiFreq]
]
pinwheels =
parMap
rdeepseq
(\(radialFreq, angularFreq) ->
VG.convert . toUnboxed . computeS $
analyticalFourierCoefficients2
numR2Freqs
1
(angularFreq)
(radialFreq)
sigma
periodR2
periodEnv)
idxs
in pinwheels
pinwheelFourierCoefficientsAnaticalList2 ::
( Unbox e
, RealFloat e
, Gamma (Complex e)
, VG.Vector vector (Complex e)
, NFData (vector (Complex e))
)
=> Int
-> Int
-> Int
-> Int
-> Int
-> e
-> e
-> e
-> [vector (Complex e)]
pinwheelFourierCoefficientsAnaticalList2 numR2Freqs phiFreq rhoFreq thetaFreq rFreq sigma periodR2 periodEnv =
let idxs =
[ (radialFreq, angularFreq)
| radialFreq <- [rFreq,(rFreq - 1) .. -rFreq]
, angularFreq <- [thetaFreq,(thetaFreq - 1) .. -thetaFreq]
]
centerR2Freq = div numR2Freqs 2
radialConstant = 2 * pi / (log periodEnv)
pinwheels =
parMap
rdeepseq
(\(radialFreq, angularFreq) ->
VG.convert . toUnboxed . computeS $
fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \(Z :. x :. y) ->
let xFreq = fromIntegral $ x - centerR2Freq
yFreq = fromIntegral $ y - centerR2Freq
rho = sqrt $ xFreq ^ 2 + yFreq ^ 2
phi = atan2 yFreq xFreq
in if rho == 0
then 0
else ((0 :+ (-1)) ^ 1) *
((periodR2 / (pi * rho) :+ 0) **
(0 :+ fromIntegral radialFreq * radialConstant)) *
(cis $ phi * fromIntegral angularFreq))
idxs
in pinwheels
{-# INLINE analyticalFourierSeries2' #-}
analyticalFourierSeries2' ::
(Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)
=> Int
-> e
-> Int
-> Int
-> e
-> e
-> e
-> R.Array D DIM2 (Complex e)
analyticalFourierSeries2' numPoints _ angularFreq radialFreq sigma periodR2 periodEnv =
let center = div numPoints 2
arr =
fromFunction (Z :. numPoints :. numPoints) $ \(Z :. i :. j) ->
let x' = i - center
y' = j - center
in if x' == 0 && y' == 0
then 0
else let x =
if x' == 0
then 0
else if x' > 0
then 1 / (fromIntegral $ center + 1 - x')
else (-1) / (fromIntegral $ center + 1 + x')
y =
if y' == 0
then 0
else if y' > 0
then 1 / (fromIntegral $ center + 1 - y')
else (-1) / (fromIntegral $ center + 1 + y')
rho = sqrt $ x ^ 2 + y ^ 2
phi = atan2 y x
in analyticalFourierSeriesFunc2
angularFreq
radialFreq
sigma
periodR2
periodEnv
phi
rho
in arr
{-# INLINE analyticalFourierCoefficients2' #-}
analyticalFourierCoefficients2' ::
(Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)
=> Int
-> e
-> Int
-> Int
-> e
-> e
-> e
-> R.Array D DIM2 (Complex e)
analyticalFourierCoefficients2' numFreqs delta angularFreq radialFreq sigma periodR2 periodEnv =
let c = (-1) ^ (abs angularFreq) :+ 0
in R.map (* c) $
analyticalFourierSeries2'
numFreqs
delta
angularFreq
radialFreq
sigma
periodR2
periodEnv
pinwheelFourierCoefficientsAnatical' ::
( Unbox e
, RealFloat e
, Gamma (Complex e)
, VG.Vector vector (Complex e)
, NFData (vector (Complex e))
)
=> Int
-> Int
-> Int
-> Int
-> Int
-> e
-> e
-> e
-> IA.Array (Int, Int) (vector (Complex e))
pinwheelFourierCoefficientsAnatical' numR2Freqs phiFreq rhoFreq thetaFreq rFreq sigma periodR2 periodEnv =
let idxs =
[ (radialFreq, angularFreq)
| radialFreq <- pinwheelFreqs rhoFreq rFreq
, angularFreq <- pinwheelFreqs phiFreq thetaFreq
]
centerR2Freq = div numR2Freqs 2
(radialLB, radialUB) = pinwheelFreqsBound rhoFreq rFreq
(angularLB, angularUB) = pinwheelFreqsBound phiFreq thetaFreq
pinwheels =
parMap
rdeepseq
(\(radialFreq, angularFreq) ->
VG.convert .
toUnboxed .
computeS -- .
-- R.zipWith
-- (*)
-- (fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \(Z :. i :. j) ->
-- gaussian2D
-- (fromIntegral $ i - centerR2Freq)
-- (fromIntegral $ j - centerR2Freq)
-- (fromIntegral $ div centerR2Freq 2))
$
analyticalFourierCoefficients2'
numR2Freqs
1
(angularFreq)
(radialFreq)
sigma
periodR2
periodEnv)
idxs
in listArray ((radialLB, angularLB), (radialUB, angularUB)) pinwheels
{-# INLINE idealHighPassFilter #-}
idealHighPassFilter ::
(VG.Vector vector (Complex Double))
=> Double
-> Int
-> vector (Complex Double)
idealHighPassFilter radius numR2Freq =
let a = 1 / (radius * 2)
r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq
sinc x =
if x == 0
then 1
else (sin (pi * x)) / (pi * x)
in VG.fromList
[ if xFreq == 0 && yFreq == 0
then (1 - 1 / a ^ 2) :+ 0
else ((-1) * (sinc (xFreq / a)) * (sinc (yFreq / a)) / (a ^ 2)) :+ 0
| xFreq <- r2Freqs
, yFreq <- r2Freqs
]
{-# INLINE idealHighPassFilter1 #-}
idealHighPassFilter1 :: Int -> VS.Vector (Complex Double)
idealHighPassFilter1 numR2Freq =
let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq
in VS.fromList
[ if xFreq == 0 && yFreq == 0
then 0
else (-1) :+ 0
| xFreq <- r2Freqs
, yFreq <- r2Freqs
]
{-# INLINE gaussianHighPassFilter #-}
gaussianHighPassFilter :: Double -> Int -> VS.Vector (Complex Double)
gaussianHighPassFilter alpha numR2Freq =
let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq
in VS.fromList
[ if xFreq == 0 && yFreq == 0
then (1 - (pi / alpha)) :+ 0
else ((-1) * (pi / alpha) *
exp ((pi ^ 2 * (xFreq ^ 2 + yFreq ^ 2)) / (-alpha))) :+
0
| xFreq <- r2Freqs
, yFreq <- r2Freqs
]
{-# INLINE gaussianHighPassFilter1 #-}
gaussianHighPassFilter1 :: Double -> Double -> Int -> VS.Vector (Complex Double)
gaussianHighPassFilter1 radius alpha numR2Freq =
let a = 1 / (radius * 2)
r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq
sinc x =
if x == 0
then 1
else (sin (pi * x)) / (pi * x)
in VS.fromList
[ (sinc (xFreq / a) * sinc (yFreq / a) / (a ^ 2) -
(pi / alpha) * exp ((pi ^ 2 * (xFreq ^ 2 + yFreq ^ 2)) / (-alpha))) :+
0
| xFreq <- r2Freqs
, yFreq <- r2Freqs
]
{-# INLINE idealLowPassFilter #-}
idealLowPassFilter ::
(VG.Vector vector (Complex Double))
=> Double
-> Double
-> Int
-> vector (Complex Double)
idealLowPassFilter radius periodR2 numR2Freq =
let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq
in VG.fromList
[ let rho = 2 * pi * sqrt (xFreq ^ 2 + yFreq ^ 2) / periodR2
in if rho == 0
then 0
else radius / rho * bessel_J1 (radius * rho) / periodR2 / (2 * pi)^2 :+ 0
| xFreq <- r2Freqs
, yFreq <- r2Freqs
]
{-# INLINE gaussianLowPassFilter #-}
gaussianLowPassFilter :: Double -> Int -> VS.Vector (Complex Double)
gaussianLowPassFilter std numR2Freq =
let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq
in VS.fromList
[ ((std ^ 2) * exp ((-pi) * (xFreq ^ 2 + yFreq ^ 2) * (std ^ 2))) :+
0
| xFreq <- r2Freqs
, yFreq <- r2Freqs
]
{-# INLINE laplacianLowPassFilter #-}
laplacianLowPassFilter :: Double -> Int -> VS.Vector (Complex Double)
laplacianLowPassFilter a numR2Freq =
let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq
in VS.fromList
[ let s2 = xFreq ^ 2 + yFreq ^ 2
in if xFreq == 0 && yFreq == 0
then (1 - a / ((4 * pi * pi * s2 + a ^ 2) ** 1.5)) :+ 0
else (-a) / ((4 * pi * pi * s2 + a ^ 2) ** 1.5) :+ 0
| xFreq <- r2Freqs
, yFreq <- r2Freqs
]
{-# INLINE laplacianHighPassFilter #-}
laplacianHighPassFilter :: Int -> VS.Vector (Complex Double)
laplacianHighPassFilter numR2Freq =
let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq
in VS.fromList
[ if xFreq == 0 && yFreq == 0
then 8 -- -3.33
else if xFreq == 0 && abs yFreq == 1
then -1 -- 0.67
else if abs xFreq == 1 && yFreq == 0
then -1 -- 0.67
else if abs xFreq == 1 && abs yFreq == 1
then -1 -- 0.17
else 0
| xFreq <- r2Freqs
, yFreq <- r2Freqs
]
{-# INLINE convolveFrequency #-}
convolveFrequency ::
(VG.Vector vector (Complex Double))
=> DFTPlan
-> Int
-> vector (Complex Double)
-> IA.Array (Int, Int) (vector (Complex Double))
-> IO (IA.Array (Int, Int) (vector (Complex Double)))
convolveFrequency plan numR2Freq filter' arr = do
let dftPlanID = DFTPlanID DFT1DG [numR2Freq, numR2Freq] [0, 1]
idftPlanID = DFTPlanID IDFT1DG [numR2Freq, numR2Freq] [0, 1]
vecs = L.map VG.convert . IA.elems $ arr
filter =
VU.convert .
toUnboxed .
computeUnboxedS .
makeFilter2D . fromUnboxed (Z :. numR2Freq :. numR2Freq) . VG.convert $
filter'
dftF <- dftExecute plan dftPlanID filter
vecsF <- mapConcurrently (dftExecute plan dftPlanID) vecs
outputs <-
mapConcurrently (dftExecute plan idftPlanID . VS.zipWith (*) dftF) vecsF
return . listArray (bounds arr) . L.map VG.convert $ outputs
{-# INLINE convolveFrequency1 #-}
convolveFrequency1 ::
(VG.Vector vector (Complex Double))
=> DFTPlan
-> Int
-> vector (Complex Double)
-> IA.Array (Int, Int) (vector (Complex Double))
-> IO (IA.Array (Int, Int) (vector (Complex Double)))
convolveFrequency1 plan numR2Freq filter' arr = do
let dftPlanID = DFTPlanID DFT1DG [numR2Freq, numR2Freq] [0, 1]
idftPlanID = DFTPlanID IDFT1DG [numR2Freq, numR2Freq] [0, 1]
vecs = L.map VG.convert . IA.elems $ arr
filter =
VU.convert .
toUnboxed .
computeUnboxedS .
makeFilter2D . fromUnboxed (Z :. numR2Freq :. numR2Freq) . VG.convert $
filter'
dftF <- dftExecute plan dftPlanID filter
vecsF <- mapConcurrently (dftExecute plan dftPlanID) vecs
outputs <-
mapConcurrently (dftExecute plan idftPlanID . VS.zipWith (*) dftF) vecsF
return .
listArray (bounds arr) . L.map VG.convert . L.zipWith (VG.zipWith (-)) vecs $
outputs
{-# INLINE centerHollow #-}
centerHollow ::
(VG.Vector vector (Complex Double))
=> Int
-> IA.Array (Int, Int) (vector (Complex Double))
-> IA.Array (Int, Int) (vector (Complex Double))
centerHollow numR2Freq arr = centerHollowVector numR2Freq <$> arr
{-# INLINE centerHollowVector #-}
centerHollowVector ::
(VG.Vector vector (Complex Double))
=> Int
-> vector (Complex Double)
-> vector (Complex Double)
centerHollowVector numR2Freq vec =
let s = VG.sum vec / (fromIntegral (numR2Freq ^ 2) :+ 0)
in VG.map (\x -> x - s) vec
{-# INLINE centerHollowArray #-}
centerHollowArray ::
(R.Source s (Complex e), Unbox e, RealFloat e)
=> Int
-> R.Array s DIM2 (Complex e)
-> R.Array D DIM2 (Complex e)
centerHollowArray numR2Freq arr =
let s = sumAllS arr / (fromIntegral (numR2Freq ^ 2) :+ 0)
in R.map (\x -> x - s) $ arr
{-# INLINE centerHollowArray' #-}
centerHollowArray' ::
(R.Source s (Complex e), Unbox e, RealFloat e)
=> Int
-> R.Array s DIM2 (Complex e)
-> R.Array D DIM2 (Complex e)
centerHollowArray' numR2Freq arr =
let s = sumAllS arr
c = div numR2Freq 2
in R.traverse arr id $ \f idx@(Z :. i :. j) ->
if i == c && j == c
then (-s)
else f idx
envelopIntegral ::
Double -> Double -> Double -> Double -> Double -> Int -> Complex Double
envelopIntegral a b delta s period radialFreq =
let m = round $ (b - a) / delta
n =
if odd m
then m
else m - 1
-- weights = VU.fromList $ weightsSimpsonRule n
vec =
VU.generate n $ \i ->
let x = (a + fromIntegral i * delta)
-- in ((x :+ 0) ** (s :+ freq)) * ((pi :+ 0) ** (0 :+ freq)) *
-- (gamma ((0.5 :+ 0) * (1 :+ (-freq)))) /
-- (gamma ((0.5 :+ 0) * (1 :+ freq)))
in analyticalFourierSeriesFunc2 0 radialFreq s period period 0 x
-- in (delta / 3 :+ 0) * (VU.sum . VU.zipWith (*) vec $ weights)
in VU.sum vec
envelopIntegral2D ::
Int -> Double -> Double -> Double -> Int -> Complex Double
envelopIntegral2D numPoints delta s period radialFreq =
let center = div numPoints 2
-- weights = VU.fromList $ weightsSimpsonRule n
arr = analyticalFourierSeries2 numPoints delta 0 radialFreq s period period
in sumAllS arr
printEnvelopIntegral ::
Double -> Double -> Double -> Double -> Double -> Int -> IO ()
printEnvelopIntegral a b delta s period radialFreq =
let m = round $ (b - a) / delta
n =
if odd m
then m
else m - 1
weights = VU.fromList $ weightsSimpsonRule n
vec =
VU.generate n $ \i ->
let x = a + fromIntegral i * delta
in analyticalFourierSeriesFunc2 0 radialFreq s period period 0 x
in print $ VU.zipWith (*) weights vec
{-# INLINE createFrequencyArray #-}
createFrequencyArray ::
(RealFloat e) => Int -> (e -> e -> Complex e) -> R.Array D DIM2 (Complex e)
createFrequencyArray numR2Freqs f =
fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \(Z :. i :. j) ->
let x = fromIntegral $ i - div numR2Freqs 2
y = fromIntegral $ j - div numR2Freqs 2
rho = sqrt $ x ^ 2 + y ^ 2
phi = atan2 y x
in f phi rho
{-# INLINE createFrequencyArrayZeroCenter #-}
createFrequencyArrayZeroCenter ::
(RealFloat e) => Int -> (e -> e -> Complex e) -> R.Array D DIM2 (Complex e)
createFrequencyArrayZeroCenter numR2Freqs f =
fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \(Z :. i :. j) ->
let x = fromIntegral $ i - div numR2Freqs 2
y = fromIntegral $ j - div numR2Freqs 2
rho = sqrt $ x ^ 2 + y ^ 2
phi = atan2 y x
in if rho == 0
then 0
else f phi rho
|
\section{Implementation}
\label{sec:implementation}
\subsection{Pre-translation}
After parsing, our implementation does type checking. The type
checker does simple type reconstruction. Instead of doing full
unification, we require that the types of all bound variables must
either be given at the binding site, given through an \Verb|implicit|
declaration, or be obvious from their definition.
Unlike ML datatypes, we do not require disjoint union type
to be declared before they are used, or to have different unions
involve different tags. Therefore, a very small amount of implicit
subtyping is done between sums. Otherwise, if we had a
specifiation of queues of integers that included
\begin{Verbatim}
set iqueue
const emptyQueue
const enqueue : int*iqueue -> iqueue
const dequeue : iqueue -> `None + `Some:int*iqueue
\end{Verbatim}
\goodbreak\noindent
then the axiom
\begin{Verbatim}
dequeue emptyQueue = `None
\end{Verbatim}
would fail to typecheck (the most-precise set for the left-hand-side
is a two-element disjoint unition, while the most-precise set
for the right is a one-element disjoint union.)
\goodbreak
The type checker will also try to convert between $\Set$ and a
subset type $\LBRACE
x \ \COLON \Setexp\ \BAR \Proposition \RBRACE$ as necessary in order
to type check. Thus,
\begin{Verbatim}
set real
set nz_real = {x:real | not (x=zero)}
const one : real
const inv : nz_real -> nz_real
const ( * ) : real * real -> real
axiom field (x : real) =
not (x=zero) => x * (inv x) = one
\end{Verbatim}
is allowed, instead of requiring
\begin{Verbatim}
axiom field (x : real) =
not (x=zero) => x * ((inv (x:>nz_real)) :< real) = one
\end{Verbatim}
In this case, since \Verb|:>| and \Verb|:<| has computational content
(going into a subset involves pairing the item with the realizer of
the proposition; going out of a subset is then a first projection),
the typechecker rewrites the former version of \Verb|field| into the
latter before passing it on to the translation phase. If injections
into subsets cannot be justified in the theory (e.g., if the
\Verb|field| axiom lacked the premise \Verb|not (x=zero)|) then the
theory will still translate, but the generated assertions will not be
satisfied by any implementation.
\subsection{Realizability Translation}
\label{subsec:real-transl}
We first discuss the realizability translation of sets and terms, and
then focus on the translation of logic, which is the interesting part.
A set~$S$ is translated into a modest set $(\ut{S}, \tot{S},
{\per{S}})$ according to its structure: a basic set is translated to a
modest set whose underlying type is abstract, a product is translated
to a product of modest sets, a function space is translated to the
exponential of modest sets, etc. Thus we simply use the rich
categorical structure of~$\Mod{\PL}$ to interpret all the set
constructors.
Similarly, terms are translated to suitable ML terms according to
their structure. Note however, that there are terms whose validity
cannot be checked by RZ because that would require it to prove
arbitrary theorems. Such an example is the definite description
operator $\THE\ x \,.\, \phi(x)$, whose validity can be confirmed only
by proving that there exists a unique~$x$ satisfying~$\phi(x)$. In
such cases RZ emits proof obligations for the programmer to verify.
Note however, that the translated terms always have valid ML types,
even if the accompanying proof obligations are not satisfied.
The driving force behind the realizability translation of logic is a
theorem, see e.g.\ \cite[Thm.~4.4.10]{Troelstra:van-Dalen:88:1}, which
says that under the realizability interpretation every formula~$\phi$
is equivalent to one that says, informally speaking, ``there
exists~$r$, such that $r$ realizes $\phi$''. Furthermore, the formula
``$r$ realizes $\phi$'' is computationally trivial. We explain what
precisely this means next.
In classical logic a doubly negated formula $\lnot\lnot\phi$ is
equivalent to~$\phi$. Constructively, this is not true in general. To
see this, recall that in constructive logic $\lnot\phi$ is defined as
$\phi \implies \bot$ and observe that the underlying type of realizers
of $\lnot\lnot\phi$ is $(\ut{\phi} \to \mathtt{unit}) \to
\mathtt{unit}$. Terms of this type cannot be converted to terms of
type $\ut{\phi}$ in a general way (although conversion in the reverse
direction can be done quite easily, which shows that $\phi$ implies
$\lnot\lnot\phi$). Furthermore, terms of type $(\ut{\phi} \to
\mathtt{unit}) \to \mathtt{unit}$ do not compute much of anything, so
we might as well replace them by a special \emph{trivial realizer}
devoid of any computational meaning. We can think of the trivial
realizer as a term which witnesses validity of a formula but does not
compute anything.
In some cases it may happen even in constructive logic that
$\lnot\lnot\phi$ is equivalent to~$\phi$. When this is so we
call~$\phi$ a \emph{$\lnot\lnot$-stable formula}, or just \emph{stable
formula} for short. Stable formulas have trivial realizers, as they
are equivalent to doubly negated formulas. Among the stable formulas
the \emph{almost negative} formulas are important because they can be
easily recognized syntactically: they are built from any combination
of $\land$, $\implies$, $\forall$, $=$, and those basic predicates
that are known to be stable, but $\exists$ and $\lor$ are only allowed
to appear on the left side of an~$\implies$.\footnote{A
\emph{negative} formula is one that does not contain $\exists$ and
$\lor$ at all.}
The following theorem is a precise formulation of the claims we made
in a paragraph above.
\begin{theorem}
For every formula $\phi$ there exists a set~$R_\phi$ and an almost
negative formula $\phi'$ such that in the realizability
interpretation $\phi$ is equivalent to $\exists r \in R_\phi . \,
\phi'(r)$.
\end{theorem}
We omit the proof, as it is fairly standard and involves a
straightforward induction on the structure of~$\phi$. The set~$R_\phi$
in the theorem is simply the set of terms of the underlying
type~$\ut{\phi}$ of realizers, while the intuitive meaning of
$\phi'(r)$ is ``$r$ realizes $\phi$''.
RZ translates an axiom~$\phi$, or any other proposition it encounters,
by computing its underlying type $\ut{\phi}$ and the almost negative
formula $\phi'$ from the above theorem. In the output signature it
then emits
%
\begin{align*}
& \mathtt{val}\ r : \ut{\phi} \\
& \text{(* Assertion $\phi'(r)$ *)}
\end{align*}
%
This way the axiom~$\phi$ has been separated into its computational
content~$r$ and a statement $\phi'$ which describes when~$r$ is a
valid realizer of~$\phi$. Because $\phi'$ is almost negative it has no
computational content, which means that its classical and constructive
readings agree. Therefore a constructive mathematician and a classical
programmer will agree on the meaning of $\phi'(r)$.
RZ recognizes almost negative formulas and optimizes away their
realizers, as described below. In addition, the user may declare a
basic predicate or relation to be stable, which will be taken into
account by RZ during translation and optimization.
It seems worth noting that the computational irrelevance of
stable propositions is akin to \emph{proof irrelevance} studied by
Pfenning~\cite{pfenning01:_inten_exten_proof_irrel_modal_type_theor}.
This is not surprising in view of the well known fact that double
negation enjoys many formal properties of a modal possibility
operator.
\subsection{Optimization}
Propositions without constructive content have trivial realizers, and
so a final ``unit elimination'' pass both removes these and does
peephole simplification of the resulting signature. Without an optimizer,
the axioms of the theory \Verb|SQGROUP| would produce
\begin{Verbatim}
val unit : s -> top * top
(** Assertion unit (x:||s||) =
x * e =s= x and e * x =s= x
*)
val sqrt : s -> s * top
(** Assertion sqrt (x:||s||) =
pi0(sqrt x) : ||s|| and
pi0(sqrt x) * pi0(sqrt x) =s= x
*)
\end{Verbatim}
where \Verb|top| is the type of trivial realizers; we use
\Verb|top| instead of \Verb|unit| to emphasize that these trivial realizers are terminating and hence safe to eliminate; this would not necessarily
be true for terms of type \Verb|unit|. The optimizer can
easily tell from the types that the realizers for the \Verb|unit| and
\Verb|assoc| axioms are trivial and can be discarded, and that
although \Verb|sqrt| cannot be discarded entirely, part of its return
value is unnecessary. Assertions that reference discarded or optimized
constants are automatically rewritten to preserve well-typedness, and we obtain the translation of \Verb|SQGROUP| shown previously, which contains no
occurrences of \Verb|top|.
%%% Local Variables:
%%% mode: latex
%%% TeX-master: "case"
%%% End:
|
Formal statement is: lemma locally_path_connected_1: assumes "\<And>v x. \<lbrakk>openin (top_of_set S) v; x \<in> v\<rbrakk> \<Longrightarrow> \<exists>u. openin (top_of_set S) u \<and> path_connected u \<and> x \<in> u \<and> u \<subseteq> v" shows "locally path_connected S" Informal statement is: If every point in $S$ has a neighborhood that is path-connected, then $S$ is locally path-connected. |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2011 Gael Guennebaud <[email protected]>
// Copyright (C) 2012 Kolja Brix <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "../../test/sparse_solver.h"
#include <Eigen/IterativeSolvers>
template<typename T> void test_gmres_T()
{
GMRES<SparseMatrix<T>, DiagonalPreconditioner<T> > gmres_colmajor_diag;
GMRES<SparseMatrix<T>, IdentityPreconditioner > gmres_colmajor_I;
GMRES<SparseMatrix<T>, IncompleteLUT<T> > gmres_colmajor_ilut;
//GMRES<SparseMatrix<T>, SSORPreconditioner<T> > gmres_colmajor_ssor;
CALL_SUBTEST( check_sparse_square_solving(gmres_colmajor_diag) );
// CALL_SUBTEST( check_sparse_square_solving(gmres_colmajor_I) );
CALL_SUBTEST( check_sparse_square_solving(gmres_colmajor_ilut) );
//CALL_SUBTEST( check_sparse_square_solving(gmres_colmajor_ssor) );
}
void test_gmres()
{
CALL_SUBTEST_1(test_gmres_T<double>());
CALL_SUBTEST_2(test_gmres_T<std::complex<double> >());
}
|
a = [1, 2, 3, 4, 1, 2, 3, 4]
@show unique(a) Set(a)
|
Require Import Coq.Lists.List.
From MetaCoq.Lob.Template Require Export QuoteGround.Coq.Init.
Import ListNotations.
Local Notation iffT A B := (prod (A -> B) (B -> A)).
Lemma iff_forall_eq_some {A v P} : iffT match v return Type with Some v => P v | None => True end (forall a : A, v = Some a -> P a).
Proof.
split; destruct v; auto; intros ??; inversion 1; subst; assumption.
Defined.
Lemma iff_forall_neq_nil {A} {v : list A} {P} : iffT match v return Type with nil => True | _ => P end (v <> nil -> P).
Proof.
split; destruct v; intuition congruence.
Defined.
#[export] Instance quote_forall_eq_some {A v P} {q : ground_quotable (match v return Type with Some v => P v | None => True end)} {qv : quotation_of v} {qA : quotation_of A} {qP : quotation_of P} : ground_quotable (forall a : A, v = Some a -> P a)
:= ground_quotable_of_iffT iff_forall_eq_some.
#[export] Instance quote_forall_neq_nil {A v P} {q : ground_quotable (match v return Type with nil => True | _ => P end)} {qv : quotation_of v} {qA : quotation_of A} {qP : quotation_of P} : ground_quotable (v <> @nil A -> P)
:= ground_quotable_of_iffT iff_forall_neq_nil.
#[export] Instance quote_is_true_or_l {b} {P : Prop} {qP : quotation_of P} {quoteP : ground_quotable P} : ground_quotable (is_true b \/ P).
Proof.
apply quote_or_dec_l; try exact _; cbv [is_true]; decide equality.
Defined.
#[export] Instance quote_is_true_or_r {b} {P : Prop} {qP : quotation_of P} {quoteP : ground_quotable P} : ground_quotable (P \/ is_true b).
Proof.
apply quote_or_dec_r; try exact _; cbv [is_true]; decide equality.
Defined.
#[export] Hint Cut [ ( _ *) quote_forall_eq_some ( _ * ) quote_forall_eq_some ] : typeclass_instances.
#[export] Hint Cut [ ( _ *) quote_forall_neq_nil ( _ * ) quote_forall_neq_nil ] : typeclass_instances.
|
(* This file is generated by Why3's Coq driver *)
(* Beware! Only edit allowed sections below *)
Require Import BuiltIn.
Require Reals.R_sqrt.
Require BuiltIn.
Require HighOrd.
Require int.Int.
Require int.Abs.
Require int.MinMax.
Require int.EuclideanDivision.
Require real.Real.
Require real.FromInt.
Require real.Square.
Require map.Map.
Require map.Const.
Require set.Set.
Parameter infix_eqeq: forall {a:Type} {a_WT:WhyType a}, a -> a -> Prop.
Axiom infix_eqeq_spec :
forall {a:Type} {a_WT:WhyType a},
forall (a1:a) (b:a), (infix_eqeq a1 b) <-> (a1 = b).
Axiom assert_equal : True.
Axiom goal_comm :
forall {a:Type} {a_WT:WhyType a},
forall (a1:a) (b:a), (a1 = b) -> (b = a1).
Axiom t : Type.
Parameter t_WhyType : WhyType t.
Existing Instance t_WhyType.
Parameter teq: t -> t -> Prop.
Axiom teq_def : forall (x:t) (y:t), (teq x y) <-> (infix_eqeq x y).
Axiom teq_spec : forall (x:t) (y:t), (teq x y) <-> (x = y).
Parameter tzero: t.
Parameter tone: t.
Parameter prefix_mndt: t -> t.
Parameter infix_pldt: t -> t -> t.
Parameter infix_asdt: t -> t -> t.
Parameter inv: t -> t.
Axiom Assoc :
forall (x:t) (y:t) (z:t),
((infix_pldt (infix_pldt x y) z) = (infix_pldt x (infix_pldt y z))).
Axiom Unit_def_l : forall (x:t), ((infix_pldt tzero x) = x).
Axiom Unit_def_r : forall (x:t), ((infix_pldt x tzero) = x).
Axiom Inv_def_l : forall (x:t), ((infix_pldt (prefix_mndt x) x) = tzero).
Axiom Inv_def_r : forall (x:t), ((infix_pldt x (prefix_mndt x)) = tzero).
Axiom Comm : forall (x:t) (y:t), ((infix_pldt x y) = (infix_pldt y x)).
Axiom Assoc1 :
forall (x:t) (y:t) (z:t),
((infix_asdt (infix_asdt x y) z) = (infix_asdt x (infix_asdt y z))).
Axiom Mul_distr_l :
forall (x:t) (y:t) (z:t),
((infix_asdt x (infix_pldt y z)) =
(infix_pldt (infix_asdt x y) (infix_asdt x z))).
Axiom Mul_distr_r :
forall (x:t) (y:t) (z:t),
((infix_asdt (infix_pldt y z) x) =
(infix_pldt (infix_asdt y x) (infix_asdt z x))).
Axiom Comm1 : forall (x:t) (y:t), ((infix_asdt x y) = (infix_asdt y x)).
Axiom Unitary : forall (x:t), ((infix_asdt tone x) = x).
Axiom NonTrivialRing : ~ (tzero = tone).
Axiom Inverse :
forall (x:t), ~ (x = tzero) -> ((infix_asdt x (inv x)) = tone).
Parameter infix_mn: t -> t -> t.
Axiom infix_mn_def :
forall (x:t) (y:t), ((infix_mn x y) = (infix_pldt x (prefix_mndt y))).
Parameter infix_sl: t -> t -> t.
Axiom infix_sl_def :
forall (x:t) (y:t), ((infix_sl x y) = (infix_asdt x (inv y))).
Axiom add_div :
forall (x:t) (y:t) (z:t), ~ (z = tzero) ->
((infix_sl (infix_pldt x y) z) =
(infix_pldt (infix_sl x z) (infix_sl y z))).
Axiom sub_div :
forall (x:t) (y:t) (z:t), ~ (z = tzero) ->
((infix_sl (infix_mn x y) z) = (infix_mn (infix_sl x z) (infix_sl y z))).
Axiom neg_div :
forall (x:t) (y:t), ~ (y = tzero) ->
((infix_sl (prefix_mndt x) y) = (prefix_mndt (infix_sl x y))).
Axiom assoc_mul_div :
forall (x:t) (y:t) (z:t), ~ (z = tzero) ->
((infix_sl (infix_asdt x y) z) = (infix_asdt x (infix_sl y z))).
Axiom assoc_div_mul :
forall (x:t) (y:t) (z:t), (~ (y = tzero) /\ ~ (z = tzero)) ->
((infix_sl (infix_sl x y) z) = (infix_sl x (infix_asdt y z))).
Axiom assoc_div_div :
forall (x:t) (y:t) (z:t), (~ (y = tzero) /\ ~ (z = tzero)) ->
((infix_sl x (infix_sl y z)) = (infix_sl (infix_asdt x z) y)).
Parameter infix_mndt: t -> t -> t.
Axiom infix_mndt_def :
forall (x:t) (y:t), ((infix_mndt x y) = (infix_pldt x (prefix_mndt y))).
Parameter infix_sldt: t -> t -> t.
Axiom infix_sldt_def :
forall (x:t) (y:t), ~ (y = tzero) ->
((infix_sldt x y) = (infix_asdt x (inv y))).
Axiom infix_sldt_spec :
forall (x:t) (y:t), ~ (y = tzero) ->
((infix_sldt x y) = (infix_asdt x (inv y))).
Parameter infix_slas: R -> R -> R.
Axiom infix_slas_def :
forall (x:R) (y:R), ~ (y = 0%R) -> ((infix_slas x y) = (x / y)%R).
Parameter infix_eqas: R -> R -> Prop.
Axiom infix_eqas_def :
forall (x:R) (y:R), (infix_eqas x y) <-> (infix_eqeq x y).
Axiom infix_eqas_spec : forall (x:R) (y:R), (infix_eqas x y) <-> (x = y).
Parameter infix_lsgtas: R -> R -> Prop.
Axiom infix_lsgtas_def :
forall (x:R) (y:R), (infix_lsgtas x y) <-> ~ (infix_eqeq x y).
Axiom infix_lsgtas_spec :
forall (x:R) (y:R), (infix_lsgtas x y) <-> ~ (x = y).
Parameter infix_plas: R -> R -> R.
Axiom infix_plas_def : forall (x:R) (y:R), ((infix_plas x y) = (x + y)%R).
Parameter infix_mnas: R -> R -> R.
Axiom infix_mnas_def :
forall (x:R) (y:R), ((infix_mnas x y) = (x + (-y)%R)%R).
Parameter infix_asas: R -> R -> R.
Axiom infix_asas_def : forall (x:R) (y:R), ((infix_asas x y) = (x * y)%R).
Parameter infix_lseqas: R -> R -> Prop.
Axiom infix_lseqas_def :
forall (x:R) (y:R), (infix_lseqas x y) <-> (x <= y)%R.
Parameter prefix_mnas: R -> R.
Axiom prefix_mnas_def : forall (y:R), ((prefix_mnas y) = (-y)%R).
Parameter infix_lsas: R -> R -> Prop.
Axiom infix_lsas_def :
forall (x:R) (y:R),
(infix_lsas x y) <-> ((infix_lseqas x y) /\ (infix_lsgtas x y)).
Parameter infix_gtas: R -> R -> Prop.
Axiom infix_gtas_def :
forall (x:R) (y:R), (infix_gtas x y) <-> (infix_lsas y x).
Parameter infix_gteqas: R -> R -> Prop.
Axiom infix_gteqas_def :
forall (x:R) (y:R), (infix_gteqas x y) <-> (infix_lseqas y x).
Parameter from_int: Z -> R.
Axiom from_int_spec : forall (x:Z), ((from_int x) = (BuiltIn.IZR x)).
Axiom Zero : ((from_int 0%Z) = 0%R).
Axiom Add :
forall (x:Z) (y:Z),
((from_int (x + y)%Z) = (infix_plas (from_int x) (from_int y))).
Axiom One : ((from_int 1%Z) = 1%R).
Axiom Sub :
forall (x:Z) (y:Z),
((from_int (x - y)%Z) = (infix_mnas (from_int x) (from_int y))).
Axiom mul_pos :
forall (x:Z) (y:Z), (0%Z <= y)%Z ->
((from_int (x * y)%Z) = (infix_asas (from_int x) (from_int y))).
Axiom mul :
forall (x:Z) (y:Z), (0%Z <= y)%Z ->
((from_int (x * y)%Z) = (infix_asas (from_int x) (from_int y))).
Axiom mul_rev :
forall (x:Z) (y:Z), (0%Z <= y)%Z ->
((infix_asas (from_int x) (from_int y)) = (from_int (x * y)%Z)).
Axiom neg : forall (x:Z), ((from_int (-x)%Z) = (prefix_mnas (from_int x))).
Axiom injective :
forall (x:Z) (y:Z), ((from_int x) = (from_int y)) -> (x = y).
Axiom Monotonic :
forall (x:Z) (y:Z), (x <= y)%Z -> infix_lseqas (from_int x) (from_int y).
Axiom positive_inv :
forall (x:R), (infix_lsas 0%R x) -> infix_lsas 0%R (infix_slas 1%R x).
Axiom r_zeroLessOne : infix_lseqas 0%R 1%R.
Axiom r_compatOrderAdd :
forall (x:R) (y:R) (z:R), (infix_lseqas x y) ->
infix_lseqas (infix_plas x z) (infix_plas y z).
Axiom r_compatOrderMult :
forall (x:R) (y:R) (z:R), (infix_lseqas x y) -> (infix_lseqas 0%R z) ->
infix_lseqas (infix_asas x z) (infix_asas y z).
Axiom inv_order :
forall (a:R) (b:R), (infix_lsas 0%R a) -> (infix_lsas 0%R b) ->
(infix_lseqas a b) -> infix_lseqas (1%R / b)%R (1%R / a)%R.
Axiom inv_strict_order :
forall (a:R) (b:R), (infix_lsas 0%R a) -> (infix_lsas 0%R b) ->
(infix_lsas a b) -> infix_lsas (1%R / b)%R (1%R / a)%R.
Axiom invol_neg : forall (a:t), ((prefix_mndt (prefix_mndt a)) = a).
Axiom injective_neg :
forall (a:t) (b:t), ((prefix_mndt a) = (prefix_mndt b)) -> (a = b).
Axiom find_opposite :
forall (a:t) (b:t), ((infix_mndt a b) = tzero) -> (a = b).
Axiom add_opposite : forall (a:t), ((infix_pldt a (prefix_mndt a)) = tzero).
Axiom opposite : forall (a:t), ((infix_mndt a a) = tzero).
Axiom mult_num :
forall (a:t) (b:t) (c:t), ~ (c = tzero) ->
((infix_sldt (infix_asdt a b) c) = (infix_asdt a (infix_sldt b c))).
Axiom div_as_mult_inv :
forall (a:t) (b:t), ~ (b = tzero) ->
((infix_sldt a b) = (infix_asdt a (infix_sldt tone b))).
Axiom div_rev :
forall (a:t) (b:t), ~ (b = tzero) ->
((infix_asdt a (infix_sldt tone b)) = (infix_sldt a b)).
Axiom mult_div_num :
forall (a:t) (b:t) (c:t), ~ (c = tzero) ->
((infix_asdt (infix_sldt a c) b) = (infix_sldt (infix_asdt a b) c)).
Axiom mult_denom :
forall (a:t) (b:t) (c:t), ~ (c = tzero) -> ~ (b = tzero) ->
((infix_sldt a (infix_asdt b c)) =
(infix_asdt (infix_sldt a b) (infix_sldt tone c))).
Axiom mult_simpl :
forall (a:t) (b:t) (c:t), ~ (c = tzero) -> ~ (b = tzero) ->
((infix_sldt (infix_asdt a b) (infix_asdt c b)) = (infix_sldt a c)).
Axiom dic_simpl :
forall (a:t) (b:t) (c:t), ~ (c = tzero) -> ~ (b = tzero) ->
((infix_asdt (infix_sldt a (infix_asdt c b)) b) = (infix_sldt a c)).
Axiom simpl_with_tone :
forall (a:t) (b:t), ~ (a = tzero) -> ~ (b = tzero) ->
((infix_asdt (infix_sldt a b) (infix_sldt tone a)) = (infix_sldt tone b)).
Parameter im: t.
Axiom im_Def : ((infix_asdt im im) = (prefix_mndt tone)).
Parameter ttwo: t.
Axiom ttwo_def : (ttwo = (infix_pldt tone tone)).
Parameter r_to_t: R -> t.
Axiom r_to_t_zero : ((r_to_t 0%R) = tzero).
Axiom r_to_t_one : ((r_to_t 1%R) = tone).
Axiom r_to_t_add :
forall (i:R) (j:R),
((infix_pldt (r_to_t i) (r_to_t j)) = (r_to_t (infix_plas i j))).
Axiom r_to_t_opp :
forall (i:R), ((r_to_t (prefix_mnas i)) = (prefix_mndt (r_to_t i))).
Axiom r_to_t_div :
forall (i:R) (j:R), ~ (j = 0%R) ->
((r_to_t (infix_slas i j)) = (infix_sldt (r_to_t i) (r_to_t j))).
Axiom r_to_t_mult :
forall (i:R) (j:R),
((infix_asdt (r_to_t i) (r_to_t j)) = (r_to_t (infix_asas i j))).
Axiom r_to_t_sub :
forall (i:R) (j:R),
((infix_mndt (r_to_t i) (r_to_t j)) = (r_to_t (infix_mnas i j))).
Parameter real_part: t -> R.
Parameter im_part: t -> R.
Axiom Real_part_add :
forall (i:t) (j:t),
((real_part (infix_pldt i j)) = (infix_plas (real_part i) (real_part j))).
Axiom Im_part_add :
forall (i:t) (j:t),
((im_part (infix_pldt i j)) = (infix_plas (im_part i) (im_part j))).
Axiom Real_part_opposite :
forall (i:t), ((real_part (prefix_mndt i)) = (prefix_mnas (real_part i))).
Axiom Im_part_opposite :
forall (i:t), ((im_part (prefix_mndt i)) = (prefix_mnas (im_part i))).
Axiom Complex_decomp :
forall (i:t),
(i =
(infix_pldt (r_to_t (real_part i)) (infix_asdt im (r_to_t (im_part i))))).
Axiom Unic_decomp :
forall (i:t), forall (x:R) (y:R),
(i = (infix_pldt (r_to_t x) (infix_asdt im (r_to_t y)))) ->
(x = (real_part i)) /\ (y = (im_part i)).
Axiom unic_decomp :
forall (i:t) (x:R) (y:R),
(i = (infix_pldt (r_to_t x) (infix_asdt im (r_to_t y)))) ->
(x = (real_part i)) /\ (y = (im_part i)).
Axiom decomp_mult :
forall (a:t) (b:t),
((infix_asdt a b) =
(infix_pldt
(infix_mndt (infix_asdt (r_to_t (real_part a)) (r_to_t (real_part b)))
(infix_asdt (r_to_t (im_part a)) (r_to_t (im_part b))))
(infix_asdt im
(infix_pldt (infix_asdt (r_to_t (real_part a)) (r_to_t (im_part b)))
(infix_asdt (r_to_t (real_part b)) (r_to_t (im_part a))))))).
Axiom decomp_mult_real_part :
forall (a:t) (b:t),
((real_part (infix_asdt a b)) =
(infix_mnas (infix_asas (real_part a) (real_part b))
(infix_asas (im_part a) (im_part b)))).
Axiom decomp_mult_im_part :
forall (a:t) (b:t),
((im_part (infix_asdt a b)) =
(infix_plas (infix_asas (real_part a) (im_part b))
(infix_asas (real_part b) (im_part a)))).
Axiom non_zero_prod :
forall (a:t) (b:t), ~ (a = tzero) -> ~ (b = tzero) ->
~ ((infix_asdt a b) = tzero).
Axiom minus_tone :
forall (a:t), ((prefix_mndt a) = (infix_asdt (prefix_mndt tone) a)).
Axiom mult_neg_l :
forall (a:t) (b:t),
((infix_asdt (prefix_mndt a) b) = (prefix_mndt (infix_asdt a b))).
Axiom mult_neg_r :
forall (a:t) (b:t),
((infix_asdt a (prefix_mndt b)) = (prefix_mndt (infix_asdt a b))).
Axiom neg_neg_out : forall (a:t), ((prefix_mndt (prefix_mndt a)) = a).
Axiom div_neg_l :
forall (a:t) (b:t), ~ (b = tzero) ->
((infix_sldt (prefix_mndt a) b) = (prefix_mndt (infix_sldt a b))).
Axiom div_neg_r :
forall (a:t) (b:t), ~ (b = tzero) ->
((infix_sldt a (prefix_mndt b)) = (prefix_mndt (infix_sldt a b))).
Axiom invadd :
forall (i:t), ((prefix_mndt i) = (infix_asdt (prefix_mndt tone) i)).
Axiom notZeroAdd :
forall (x:t) (y:t), ~ (x = tzero) -> ~ ((infix_pldt x y) = y).
Axiom Absorbing_zero :
forall (a:t) (b:t),
((infix_asdt a b) = tzero) <-> (~ (a = tzero) -> (b = tzero)).
Axiom real_part_add :
forall (i:t) (j:t),
((real_part (infix_pldt i j)) = (infix_plas (real_part i) (real_part j))).
Axiom mult_im_rev : forall (a:t), ((infix_asdt a im) = (infix_asdt im a)).
Axiom im_im_elim :
forall (a:t), ((infix_asdt im (infix_asdt im a)) = (prefix_mndt a)).
Axiom im_im_fact :
forall (a:t) (b:t),
((infix_asdt (infix_asdt im a) (infix_asdt im b)) =
(prefix_mndt (infix_asdt a b))).
Axiom minus_minus_fact :
forall (a:t) (b:t),
((infix_asdt (prefix_mndt a) (prefix_mndt b)) = (infix_asdt a b)).
Axiom minus_minus_add :
forall (a:t) (b:t),
((infix_pldt (prefix_mndt a) (prefix_mndt b)) =
(prefix_mndt (infix_pldt a b))).
Axiom minus_minus_add_rev :
forall (a:t) (b:t),
((prefix_mndt (infix_pldt a b)) =
(infix_pldt (prefix_mndt a) (prefix_mndt b))).
Axiom minus_out_left :
forall (a:t) (b:t),
((infix_asdt (prefix_mndt a) b) = (prefix_mndt (infix_asdt a b))).
Axiom minus_out_right :
forall (a:t) (b:t),
((infix_asdt a (prefix_mndt b)) = (prefix_mndt (infix_asdt a b))).
Axiom minus_in_left :
forall (a:t) (b:t),
((prefix_mndt (infix_asdt a b)) = (infix_asdt (prefix_mndt a) b)).
Axiom minus_in_right :
forall (a:t) (b:t),
((prefix_mndt (infix_asdt a b)) = (infix_asdt a (prefix_mndt b))).
Axiom minus_add_out_left :
forall (a:t) (b:t),
((infix_pldt (prefix_mndt a) b) =
(prefix_mndt (infix_pldt a (prefix_mndt b)))).
Axiom minus_add_out_right :
forall (a:t) (b:t),
((infix_pldt a (prefix_mndt b)) =
(prefix_mndt (infix_pldt (prefix_mndt a) b))).
Axiom minus_add_in :
forall (a:t) (b:t),
((prefix_mndt (infix_pldt a b)) =
(infix_pldt (prefix_mndt a) (prefix_mndt b))).
Axiom minus_add_out :
forall (a:t) (b:t),
((infix_pldt (prefix_mndt a) (prefix_mndt b)) =
(prefix_mndt (infix_pldt a b))).
Axiom minus_eq :
forall (a:t) (b:t), (a = b) -> ((prefix_mndt a) = (prefix_mndt b)).
Axiom im_out_right :
forall (a:t) (b:t),
((infix_asdt (infix_asdt im a) b) = (infix_asdt im (infix_asdt a b))).
Axiom im_out_left :
forall (a:t) (b:t),
((infix_asdt a (infix_asdt im b)) = (infix_asdt im (infix_asdt a b))).
Axiom im_part_add :
forall (i:t) (j:t),
((im_part (infix_pldt i j)) = (infix_plas (im_part i) (im_part j))).
Axiom injective_real_part :
forall (i:t) (j:t), ~ ((real_part i) = (real_part j)) -> ~ (i = j).
Axiom injective_im_part :
forall (i:t) (j:t), ~ ((im_part i) = (im_part j)) -> ~ (i = j).
Axiom complex_decomp :
forall (i:t),
(i =
(infix_pldt (r_to_t (real_part i)) (infix_asdt im (r_to_t (im_part i))))).
Parameter real_: t -> Prop.
Axiom real__def : forall (x:t), (real_ x) <-> (infix_eqeq (im_part x) 0%R).
Parameter pure_im_: t -> Prop.
Axiom pure_im__def :
forall (x:t), (pure_im_ x) <-> (infix_eqeq (real_part x) 0%R).
Axiom r_to_t_real : forall (x:t), (real_ x) -> (x = (r_to_t (real_part x))).
Axiom real_r_to_t : forall (x:R), real_ (r_to_t x).
Axiom r_to_t_pure_im :
forall (x:t), (pure_im_ x) -> (x = (infix_asdt im (r_to_t (im_part x)))).
Axiom simpl_frac :
forall (x:t) (y:t), ~ (y = tzero) -> ((infix_sldt (infix_asdt x y) y) = x).
Axiom simpl_frac_ :
forall (x:t) (y:t) (z:t), ~ (y = tzero) -> ~ (z = tzero) ->
((infix_sldt (infix_asdt x y) (infix_asdt z y)) = (infix_sldt x z)).
Axiom fact_frac :
forall (x:t) (y:t) (z:t), ~ (z = tzero) ->
((infix_sldt (infix_asdt x y) z) = (infix_asdt x (infix_sldt y z))).
Axiom fact_frac_rev :
forall (x:t) (y:t) (z:t), ~ (z = tzero) ->
((infix_asdt x (infix_sldt y z)) = (infix_sldt (infix_asdt x y) z)).
Axiom inv_mult :
forall (x:t) (y:t), ~ (x = tzero) -> ~ (y = tzero) ->
((infix_asdt (infix_sldt tone x) (infix_sldt tone y)) =
(infix_sldt tone (infix_asdt x y))).
Axiom div_div :
forall (x:t) (y:t) (z:t), ~ (y = tzero) -> ~ (z = tzero) ->
((infix_sldt (infix_sldt x y) z) = (infix_sldt x (infix_asdt y z))).
Axiom div_div_rev :
forall (x:t) (y:t) (z:t), ~ (y = tzero) -> ~ (z = tzero) ->
((infix_sldt x (infix_asdt y z)) = (infix_sldt (infix_sldt x y) z)).
Axiom involutive_inv :
forall (a:t), ~ (a = tzero) -> ((infix_sldt tone (infix_sldt tone a)) = a).
Axiom twice : forall (i:t), ((infix_asdt ttwo i) = (infix_pldt i i)).
Axiom twice_half : ((infix_asdt ttwo (infix_sldt tone ttwo)) = tone).
Axiom half_plus_half :
forall (i:t), ((infix_pldt (infix_sldt i ttwo) (infix_sldt i ttwo)) = i).
Parameter infix_lseqdt: t -> t -> Prop.
Axiom infix_lseqdt_def :
forall (x:t) (y:t),
(infix_lseqdt x y) <->
(((real_ x) /\ ((real_ y) /\ (infix_lseqas (real_part x) (real_part y)))) \/
(infix_eqeq x y)).
Parameter infix_lsdt: t -> t -> Prop.
Axiom infix_lsdt_def :
forall (x:t) (y:t),
(infix_lsdt x y) <-> ((infix_lseqdt x y) /\ ~ (infix_eqeq x y)).
Parameter infix_gteqdt: t -> t -> Prop.
Axiom infix_gteqdt_def :
forall (x:t) (y:t), (infix_gteqdt x y) <-> (infix_lseqdt y x).
Parameter infix_gtdt: t -> t -> Prop.
Axiom infix_gtdt_def :
forall (x:t) (y:t),
(infix_gtdt x y) <-> ((infix_gteqdt x y) /\ ~ (infix_eqeq x y)).
Axiom Refl : forall (x:t), infix_lseqdt x x.
Axiom Trans :
forall (x:t) (y:t) (z:t), (infix_lseqdt x y) -> (infix_lseqdt y z) ->
infix_lseqdt x z.
Axiom Antisymm :
forall (x:t) (y:t), (infix_lseqdt x y) -> (infix_lseqdt y x) -> (x = y).
Axiom Refl1 : forall (x:t), infix_gteqdt x x.
Axiom Trans1 :
forall (x:t) (y:t) (z:t), (infix_gteqdt x y) -> (infix_gteqdt y z) ->
infix_gteqdt x z.
Axiom Antisymm1 :
forall (x:t) (y:t), (infix_gteqdt x y) -> (infix_gteqdt y x) -> (x = y).
Axiom Trans2 :
forall (x:t) (y:t) (z:t), (infix_lsdt x y) -> (infix_lsdt y z) ->
infix_lsdt x z.
Axiom Asymm : forall (x:t) (y:t), (infix_lsdt x y) -> ~ (infix_lsdt y x).
Axiom Trans3 :
forall (x:t) (y:t) (z:t), (infix_gtdt x y) -> (infix_gtdt y z) ->
infix_gtdt x z.
Axiom Asymm1 : forall (x:t) (y:t), (infix_gtdt x y) -> ~ (infix_gtdt y x).
Axiom r_to_t_inf :
forall (i:R) (j:R),
(infix_lseqdt (r_to_t i) (r_to_t j)) <-> (infix_lseqas i j).
Parameter pi: t.
Axiom pi_def : (real_ pi) /\ (infix_lsdt tzero pi).
Axiom inf_to_non_sup_eq :
forall (x:t) (y:t), (real_ x) -> (real_ y) -> (infix_lsdt x y) ->
~ (infix_gteqdt x y).
Axiom sup_eq_to_non_inf :
forall (x:t) (y:t), (real_ x) -> (real_ y) -> (infix_gteqdt x y) ->
~ (infix_lsdt x y).
Axiom sup_to_inf :
forall (x:t) (y:t), (real_ x) -> (real_ y) -> (infix_gtdt x y) ->
infix_lsdt y x.
Axiom inf_to_sup :
forall (x:t) (y:t), (real_ x) -> (real_ y) -> (infix_lsdt x y) ->
infix_gtdt y x.
Axiom sup_to_non_inf_eq :
forall (x:t) (y:t), (real_ x) -> (real_ y) -> (infix_gtdt x y) ->
~ (infix_lseqdt x y).
Axiom inf_eq_to_non_sup :
forall (x:t) (y:t), (real_ x) -> (real_ y) -> (infix_lseqdt x y) ->
~ (infix_gtdt x y).
Axiom non_inf_eq_to_sup :
forall (x:t) (y:t), (real_ x) -> (real_ y) -> ~ (infix_lseqdt x y) ->
infix_gtdt x y.
Axiom non_sup_toinf_eq :
forall (x:t) (y:t), (real_ x) -> (real_ y) -> ~ (infix_gtdt x y) ->
infix_lseqdt x y.
Axiom eq_to_leq_t :
forall (a:t) (b:t), (real_ a) -> (a = b) -> infix_lseqdt a b.
Axiom compat_r_to_t_infeq :
forall (a:R) (b:R), (infix_lseqas a b) ->
infix_lseqdt (r_to_t a) (r_to_t b).
Axiom compat_r_to_t_inf :
forall (a:R) (b:R), (infix_lsas a b) -> infix_lsdt (r_to_t a) (r_to_t b).
Axiom compat_r_to_t_supeq :
forall (a:R) (b:R), (infix_gteqas a b) ->
infix_gteqdt (r_to_t a) (r_to_t b).
Axiom compat_r_to_t_sup :
forall (a:R) (b:R), (infix_gtas a b) -> infix_gtdt (r_to_t a) (r_to_t b).
Axiom unic_inv :
forall (i:t) (j:t), ~ (i = tzero) -> ((infix_asdt i j) = tone) ->
(j = (inv i)).
Axiom inf_eq_def :
forall (x:t) (y:t),
(infix_lseqdt x y) <->
(((real_ x) /\ ((real_ y) /\ (infix_lseqas (real_part x) (real_part y)))) \/
(x = y)).
Axiom inf_minus :
forall (x:t) (y:t), (infix_lsdt x y) ->
infix_lsdt (prefix_mndt y) (prefix_mndt x).
Parameter t_real_part: t -> t.
Axiom t_real_part_def :
forall (x:t), ((t_real_part x) = (r_to_t (real_part x))).
Axiom t_real_part_spec : forall (x:t), real_ (t_real_part x).
Axiom t_real_part_inv :
forall (x:t),
((t_real_part (prefix_mndt x)) = (prefix_mndt (t_real_part x))).
Axiom simpl_leq_mult_div :
forall (a:t) (b:t) (c:t), ~ (b = tzero) -> ~ (c = tzero) ->
(infix_lseqdt a (infix_sldt tone (infix_asdt b c))) ->
infix_lseqdt (infix_asdt a b) (infix_sldt tone c).
Parameter t_im_part: t -> t.
Axiom t_im_part_def : forall (x:t), ((t_im_part x) = (r_to_t (im_part x))).
Axiom t_im_part_spec : forall (x:t), real_ (t_im_part x).
Axiom t_im_part_inv :
forall (x:t), ((t_im_part (prefix_mndt x)) = (prefix_mndt (t_im_part x))).
Axiom absorbing_zero :
forall (a:t) (b:t), ((infix_asdt a b) = tzero) ->
(~ (a = tzero) -> (b = tzero)) /\ (~ (b = tzero) -> (a = tzero)).
Axiom t_mult_real :
forall (a:t) (b:t),
((t_real_part (infix_asdt a b)) =
(infix_mndt (infix_asdt (t_real_part a) (t_real_part b))
(infix_asdt (t_im_part a) (t_im_part b)))).
Axiom mult_real_real :
forall (a:t) (b:t), (real_ a) -> (real_ b) ->
(((infix_asdt a b) =
(infix_asdt (r_to_t (real_part a)) (r_to_t (real_part b)))) /\
((infix_asdt (r_to_t (real_part a)) (r_to_t (real_part b))) =
(r_to_t (infix_asas (real_part a) (real_part b))))) /\
(((real_part (infix_asdt a b)) = (infix_asas (real_part a) (real_part b))) /\
((im_part (infix_asdt a b)) = 0%R)).
Axiom compat_order_mult :
forall (x:t) (y:t) (z:t), (infix_lseqdt x y) -> (real_ x) -> (real_ y) ->
(real_ z) -> (infix_lseqdt tzero z) ->
infix_lseqdt (infix_asdt x z) (infix_asdt y z).
Axiom mult_pos :
forall (x:t) (y:t), (infix_lseqdt tzero x) -> (infix_lseqdt tzero y) ->
infix_lseqdt tzero (infix_asdt x y).
Axiom strict_mult_pos :
forall (x:t) (y:t), (infix_lsdt tzero x) -> (infix_lsdt tzero y) ->
infix_lsdt tzero (infix_asdt x y).
Axiom rewrite_supeq :
forall (x:t) (y:t), (infix_lseqdt x y) -> infix_gteqdt y x.
Axiom rewrite_sup : forall (x:t) (y:t), (infix_lsdt x y) -> infix_gtdt y x.
Axiom inf_def :
forall (x:t) (y:t),
(infix_lsdt x y) <->
((real_ x) /\ ((real_ y) /\ (infix_lsas (real_part x) (real_part y)))).
Axiom sup_eq_def :
forall (x:t) (y:t),
(infix_gteqdt x y) <->
(((real_ x) /\ ((real_ y) /\ (infix_gteqas (real_part x) (real_part y)))) \/
(x = y)).
Axiom sup_def :
forall (x:t) (y:t),
(infix_gtdt x y) <->
((real_ x) /\ ((real_ y) /\ (infix_gtas (real_part x) (real_part y)))).
Axiom assoc_mult_div :
forall (x:t) (y:t) (z:t), ~ (z = tzero) ->
((infix_asdt x (infix_sldt y z)) = (infix_sldt (infix_asdt x y) z)).
Axiom transitive_infeq :
forall (a:t) (b:t) (c:t), (infix_lseqdt a b) -> (infix_lseqdt b c) ->
infix_lseqdt a c.
Axiom transitive_inf :
forall (a:t) (b:t) (c:t), (infix_lsdt a b) -> (infix_lsdt b c) ->
infix_lsdt a c.
Axiom transitive_inf_inv_r :
forall (a:t) (b:t) (c:t), (infix_lsdt a b) ->
(infix_lsdt b (infix_sldt tone c)) -> (infix_lseqdt tone c) ->
(infix_lsdt a b) /\ (infix_lsdt b tone).
Axiom transitive_leq_inv_r :
forall (a:t) (b:t) (c:t), (infix_lseqdt a b) ->
(infix_lseqdt b (infix_sldt tone c)) -> (infix_lseqdt tone c) ->
(infix_lseqdt a b) /\ (infix_lseqdt b tone).
Axiom infeq_scal_r :
forall (a:t) (b:t) (c:t), (infix_lseqdt a c) -> (infix_lseqdt tzero b) ->
infix_lseqdt (infix_asdt a b) (infix_asdt c b).
Axiom infeq_scal_l :
forall (a:t) (b:t) (c:t), (infix_lseqdt a c) -> (infix_lseqdt tzero b) ->
infix_lseqdt (infix_asdt b a) (infix_asdt b c).
Axiom transitive_supeq :
forall (a:t) (b:t) (c:t), (infix_gteqdt a b) -> (infix_gteqdt b c) ->
infix_gteqdt a c.
Axiom transitive_inf_l :
forall (a:t) (b:t) (c:t), (infix_lsdt a b) -> (infix_lseqdt b c) ->
infix_lsdt a c.
Axiom transitive_sup_l :
forall (a:t) (b:t) (c:t), (infix_gtdt a b) -> (infix_gteqdt b c) ->
infix_gtdt a c.
Axiom transitive_inf_r :
forall (a:t) (b:t) (c:t), (infix_lseqdt a b) -> (infix_lsdt b c) ->
infix_lsdt a c.
Axiom transitive_sup_r :
forall (a:t) (b:t) (c:t), (infix_gteqdt a b) -> (infix_gtdt b c) ->
infix_gtdt a c.
Axiom compat_mult_sup_eq_right :
forall (a:t) (b:t) (c:t), (infix_lseqdt tzero a) -> (infix_gteqdt b c) ->
infix_gteqdt (infix_asdt a b) (infix_asdt a c).
Axiom compat_mult_sup_right :
forall (a:t) (b:t) (c:t), (infix_lsdt tzero a) -> (infix_gtdt b c) ->
infix_gtdt (infix_asdt a b) (infix_asdt a c).
Axiom compat_mult_inf_right :
forall (a:t) (b:t) (c:t), (infix_lsdt tzero a) -> (infix_lsdt b c) ->
infix_lsdt (infix_asdt a b) (infix_asdt a c).
Axiom infeq_to_supeq :
forall (a:t) (b:t), (infix_lseqdt a b) -> infix_gteqdt b a.
Axiom supeq_elim_left :
forall (a:t) (b:t), (infix_gteqdt a b) ->
infix_gteqdt tzero (infix_mndt b a).
Axiom sup_elim_left :
forall (a:t) (b:t), (infix_gtdt a b) -> infix_gtdt tzero (infix_mndt b a).
Axiom infeq_elim_left :
forall (a:t) (b:t), (infix_lseqdt a b) ->
infix_lseqdt tzero (infix_mndt b a).
Axiom inf_elim_left :
forall (a:t) (b:t), (infix_lsdt a b) -> infix_lsdt tzero (infix_mndt b a).
Axiom t_im_real :
forall (a:t) (b:t),
((t_im_part (infix_asdt a b)) =
(infix_pldt (infix_asdt (t_real_part a) (t_im_part b))
(infix_asdt (t_im_part a) (t_real_part b)))).
Axiom t_decomp_mult :
forall (a:t) (b:t),
((infix_asdt a b) =
(infix_pldt
(infix_mndt (infix_asdt (t_real_part a) (t_real_part b))
(infix_asdt (t_im_part a) (t_im_part b)))
(infix_asdt im
(infix_pldt (infix_asdt (t_real_part a) (t_im_part b))
(infix_asdt (t_im_part a) (t_real_part b)))))).
Axiom t_complex_decomp :
forall (i:t),
(i = (infix_pldt (t_real_part i) (infix_asdt im (t_im_part i)))).
Axiom t_unic_decomp :
forall (i:t) (a:t) (b:t), (real_ a) -> (real_ b) ->
(i = (infix_pldt a (infix_asdt im b))) ->
(a = (t_real_part i)) /\ (b = (t_im_part i)).
Axiom t_decomp_minus :
forall (i:t) (a:t) (b:t), (real_ a) -> (real_ b) ->
(i = (infix_mndt a (infix_asdt im b))) ->
(a = (t_real_part i)) /\ ((prefix_mndt b) = (t_im_part i)).
Axiom real_sum :
forall (x:t) (y:t), (real_ x) -> (real_ y) -> real_ (infix_pldt x y).
Axiom set : forall (a:Type), Type.
Parameter set_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (set a).
Existing Instance set_WhyType.
Parameter mem: forall {a:Type} {a_WT:WhyType a}, a -> (set a) -> Prop.
Parameter infix_eqeq1:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (set a) -> Prop.
Axiom infix_eqeq_spec1 :
forall {a:Type} {a_WT:WhyType a},
forall (s1:set a) (s2:set a),
(infix_eqeq1 s1 s2) <-> forall (x:a), (mem x s1) <-> (mem x s2).
Axiom extensionality :
forall {a:Type} {a_WT:WhyType a},
forall (s1:set a) (s2:set a), (infix_eqeq1 s1 s2) -> (s1 = s2).
Parameter subset:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (set a) -> Prop.
Axiom subset_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s1:set a) (s2:set a),
(subset s1 s2) <-> forall (x:a), (mem x s1) -> mem x s2.
Axiom subset_refl :
forall {a:Type} {a_WT:WhyType a}, forall (s:set a), subset s s.
Axiom subset_trans :
forall {a:Type} {a_WT:WhyType a},
forall (s1:set a) (s2:set a) (s3:set a), (subset s1 s2) ->
(subset s2 s3) -> subset s1 s3.
Parameter is_empty: forall {a:Type} {a_WT:WhyType a}, (set a) -> Prop.
Axiom is_empty_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a), (is_empty s) <-> forall (x:a), ~ (mem x s).
Parameter empty: forall {a:Type} {a_WT:WhyType a}, set a.
Axiom empty_def : forall {a:Type} {a_WT:WhyType a}, is_empty (empty : set a).
Parameter add: forall {a:Type} {a_WT:WhyType a}, a -> (set a) -> set a.
Axiom add_spec :
forall {a:Type} {a_WT:WhyType a},
forall (x:a) (s:set a), forall (y:a),
(mem y (add x s)) <-> ((y = x) \/ (mem y s)).
Parameter singleton: forall {a:Type} {a_WT:WhyType a}, a -> set a.
Axiom singleton_def :
forall {a:Type} {a_WT:WhyType a},
forall (x:a), ((singleton x) = (add x (empty : set a))).
Parameter remove: forall {a:Type} {a_WT:WhyType a}, a -> (set a) -> set a.
Axiom remove_spec :
forall {a:Type} {a_WT:WhyType a},
forall (x:a) (s:set a), forall (y:a),
(mem y (remove x s)) <-> (~ (y = x) /\ (mem y s)).
Axiom add_remove :
forall {a:Type} {a_WT:WhyType a},
forall (x:a) (s:set a), (mem x s) -> ((add x (remove x s)) = s).
Axiom remove_add :
forall {a:Type} {a_WT:WhyType a},
forall (x:a) (s:set a), ((remove x (add x s)) = (remove x s)).
Axiom subset_remove :
forall {a:Type} {a_WT:WhyType a},
forall (x:a) (s:set a), subset (remove x s) s.
Parameter union:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (set a) -> set a.
Axiom union_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s1:set a) (s2:set a), forall (x:a),
(mem x (union s1 s2)) <-> ((mem x s1) \/ (mem x s2)).
Parameter inter:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (set a) -> set a.
Axiom inter_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s1:set a) (s2:set a), forall (x:a),
(mem x (inter s1 s2)) <-> ((mem x s1) /\ (mem x s2)).
Parameter diff:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (set a) -> set a.
Axiom diff_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s1:set a) (s2:set a), forall (x:a),
(mem x (diff s1 s2)) <-> ((mem x s1) /\ ~ (mem x s2)).
Axiom subset_diff :
forall {a:Type} {a_WT:WhyType a},
forall (s1:set a) (s2:set a), subset (diff s1 s2) s1.
Parameter choose: forall {a:Type} {a_WT:WhyType a}, (set a) -> a.
Axiom choose_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a), ~ (is_empty s) -> mem (choose s) s.
Parameter cardinal: forall {a:Type} {a_WT:WhyType a}, (set a) -> Z.
Axiom cardinal_nonneg :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a), ((cardinal s) >= 0%Z)%Z.
Axiom cardinal_empty :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a), ((cardinal s) = 0%Z) <-> (is_empty s).
Axiom cardinal_add :
forall {a:Type} {a_WT:WhyType a},
forall (x:a), forall (s:set a), ~ (mem x s) ->
((cardinal (add x s)) = (1%Z + (cardinal s))%Z).
Axiom cardinal_remove :
forall {a:Type} {a_WT:WhyType a},
forall (x:a), forall (s:set a), (mem x s) ->
((cardinal s) = (1%Z + (cardinal (remove x s)))%Z).
Axiom cardinal_subset :
forall {a:Type} {a_WT:WhyType a},
forall (s1:set a) (s2:set a), (subset s1 s2) ->
((cardinal s1) <= (cardinal s2))%Z.
Axiom subset_eq :
forall {a:Type} {a_WT:WhyType a},
forall (s1:set a) (s2:set a), (subset s1 s2) ->
((cardinal s1) = (cardinal s2)) -> infix_eqeq1 s1 s2.
Axiom cardinal1 :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a), ((cardinal s) = 1%Z) -> forall (x:a), (mem x s) ->
(x = (choose s)).
Axiom real_diff :
forall (x:t) (y:t), (real_ x) -> (real_ y) -> real_ (infix_mndt x y).
Axiom pure_im_sum :
forall (x:t) (y:t), (pure_im_ x) -> (pure_im_ y) ->
pure_im_ (infix_pldt x y).
Axiom equal_decomp :
forall (x:t) (y:t), ((real_part x) = (real_part y)) ->
((im_part x) = (im_part y)) -> (x = y).
Axiom t_equal_decomp :
forall (x:t) (y:t), ((t_real_part x) = (t_real_part y)) ->
((t_im_part x) = (t_im_part y)) -> (x = y).
Axiom pure_im_diff :
forall (x:t) (y:t), (pure_im_ x) -> (pure_im_ y) ->
pure_im_ (infix_mndt x y).
Axiom real_mult :
forall (x:t) (y:t), (real_ x) -> (real_ y) -> real_ (infix_asdt x y).
Axiom real_inv :
forall (x:t), (real_ x) -> ~ (x = tzero) -> real_ (infix_sldt tone x).
Axiom inv_pos :
forall (x:t), (real_ x) -> (infix_lsdt tzero x) ->
infix_gtdt (infix_sldt tone x) tzero.
Axiom lower_over_cons :
forall (a:t) (b:t) (c:t), (infix_lsdt tzero c) -> (infix_lseqdt tzero a) ->
(infix_lseqdt a b) -> infix_lseqdt (infix_sldt a c) (infix_sldt b c).
Axiom real_div :
forall (x:t) (y:t), (real_ x) -> ~ (y = tzero) -> (real_ y) ->
real_ (infix_sldt x y).
Axiom mult_im_im :
forall (a:t) (b:t), (pure_im_ a) -> (pure_im_ b) ->
((infix_asdt a b) =
(infix_asdt (infix_asdt im im)
(infix_asdt (r_to_t (im_part a)) (r_to_t (im_part b))))) /\
(((infix_asdt a b) =
(prefix_mndt (r_to_t (infix_asas (im_part a) (im_part b))))) /\
(((real_part (infix_asdt a b)) =
(prefix_mnas (infix_asas (im_part a) (im_part b)))) /\
((im_part (infix_asdt a b)) = 0%R))).
Axiom mult_real_im :
forall (a:t) (b:t), (real_ a) -> (pure_im_ b) ->
((infix_asdt a b) =
(infix_asdt im (infix_asdt (r_to_t (real_part a)) (r_to_t (im_part b))))) /\
(((infix_asdt a b) =
(infix_asdt im (r_to_t (infix_asas (real_part a) (im_part b))))) /\
(((real_part (infix_asdt a b)) = 0%R) /\
((im_part (infix_asdt a b)) = (infix_asas (real_part a) (im_part b))))).
Axiom mult_im_real :
forall (a:t) (b:t), (pure_im_ a) -> (real_ b) ->
((infix_asdt a b) =
(infix_asdt im (infix_asdt (r_to_t (im_part a)) (r_to_t (real_part b))))) /\
(((infix_asdt a b) =
(infix_asdt im (r_to_t (infix_asas (im_part a) (real_part b))))) /\
(((real_part (infix_asdt a b)) = 0%R) /\
((im_part (infix_asdt a b)) = (infix_asas (im_part a) (real_part b))))).
Axiom decomp_mult_gen :
forall (a:t) (b:t),
((real_part (infix_asdt a b)) =
(infix_mnas (infix_asas (real_part a) (real_part b))
(infix_asas (im_part a) (im_part b)))) /\
((im_part (infix_asdt a b)) =
(infix_plas (infix_asas (real_part a) (im_part b))
(infix_asas (im_part a) (real_part b)))).
Axiom inv_real :
forall (a:t), ~ (a = tzero) -> (real_ a) ->
((real_part (infix_sldt tone a)) = (infix_slas 1%R (real_part a))) /\
(real_ (infix_sldt tone a)).
Axiom zeroLessOne : infix_lseqdt tzero tone.
Axiom compatOrderAdd :
forall (x:t) (y:t) (z:t), (infix_lseqdt x y) -> (real_ x) -> (real_ y) ->
(real_ z) -> infix_lseqdt (infix_pldt x z) (infix_pldt y z).
Axiom positive_add :
forall (x:t) (y:t), (infix_lseqdt tzero x) -> (infix_lseqdt tzero y) ->
infix_lseqdt tzero (infix_pldt x y).
Axiom strict_positive_add_l :
forall (x:t) (y:t), (infix_lsdt tzero x) -> (infix_lseqdt tzero y) ->
infix_lsdt tzero (infix_pldt x y).
Axiom strict_compatOrderAdd :
forall (x:t) (y:t) (z:t) (t1:t), (infix_lsdt x y) -> (infix_lsdt z t1) ->
(real_ x) -> (real_ y) -> (real_ z) -> (real_ t1) ->
infix_lsdt (infix_pldt x z) (infix_pldt y t1).
Axiom compat_sup_add :
forall (x:t) (y:t) (z:t) (t1:t), (infix_gtdt x y) -> (infix_gtdt z t1) ->
(real_ x) -> (real_ y) -> (real_ z) -> (real_ t1) ->
infix_gtdt (infix_pldt x z) (infix_pldt y t1).
Axiom compat_supeq_mult :
forall (x:t) (y:t) (z:t), (infix_gteqdt x y) -> (real_ x) -> (real_ y) ->
(real_ z) -> (infix_lseqdt tzero z) ->
infix_gteqdt (infix_asdt x z) (infix_asdt y z).
Axiom compat_supeq_div :
forall (x:t) (y:t) (z:t), (infix_gteqdt x y) -> (real_ x) -> (real_ y) ->
(real_ z) -> (infix_lsdt tzero z) ->
infix_gteqdt (infix_sldt x z) (infix_sldt y z).
Axiom compat_infeq_div :
forall (x:t) (y:t) (z:t), (infix_lseqdt x y) -> (real_ x) -> (real_ y) ->
(real_ z) -> (infix_lsdt tzero z) ->
infix_lseqdt (infix_sldt x z) (infix_sldt y z).
Axiom compat_sup_div :
forall (x:t) (y:t) (z:t), (infix_gtdt x y) -> (real_ x) -> (real_ y) ->
(real_ z) -> (infix_lsdt tzero z) ->
infix_gtdt (infix_sldt x z) (infix_sldt y z).
Axiom compat_inf_div :
forall (x:t) (y:t) (z:t), (infix_lsdt x y) -> (real_ x) -> (real_ y) ->
(real_ z) -> (infix_lsdt tzero z) ->
infix_lsdt (infix_sldt x z) (infix_sldt y z).
Axiom strict_compat_order_mult :
forall (x:t) (y:t) (z:t), (infix_lsdt x y) -> (real_ x) -> (real_ y) ->
(real_ z) -> (infix_lsdt tzero z) ->
infix_lsdt (infix_asdt x z) (infix_asdt y z).
Axiom compat_order_mult_left :
forall (x:t) (y:t) (z:t), (infix_lseqdt x y) -> (real_ x) -> (real_ y) ->
(real_ z) -> (infix_lseqdt tzero z) ->
infix_lseqdt (infix_asdt x z) (infix_asdt y z).
Axiom strict_compat_order_mult_left :
forall (x:t) (y:t) (z:t), (infix_lsdt x y) -> (real_ x) -> (real_ y) ->
(real_ z) -> (infix_lsdt tzero z) ->
infix_lsdt (infix_asdt z x) (infix_asdt z y).
Axiom positive_prod_itself :
forall (x:t), (real_ x) -> infix_lseqdt tzero (infix_asdt x x).
Axiom strict_positive_prod_itself :
forall (x:t), (real_ x) -> ~ (x = tzero) ->
infix_lsdt tzero (infix_asdt x x).
Axiom compat_sup_mult :
forall (x:t) (y:t) (z:t), (infix_gteqdt x y) -> (real_ x) -> (real_ y) ->
(real_ z) -> (infix_lseqdt tzero z) ->
infix_gteqdt (infix_asdt x z) (infix_asdt y z).
Axiom strict_compat_sup_mult :
forall (x:t) (y:t) (z:t), (infix_gtdt x y) -> (real_ x) -> (real_ y) ->
(real_ z) -> (infix_lsdt tzero z) ->
infix_gtdt (infix_asdt x z) (infix_asdt y z).
Axiom compat_sup_mult_left :
forall (x:t) (y:t) (z:t), (infix_gteqdt x y) -> (real_ x) -> (real_ y) ->
(real_ z) -> (infix_lseqdt tzero z) ->
infix_gteqdt (infix_asdt z x) (infix_asdt z y).
Axiom strict_compat_sup_mult_left :
forall (x:t) (y:t) (z:t), (infix_gtdt x y) -> (real_ x) -> (real_ y) ->
(real_ z) -> (infix_lsdt tzero z) ->
infix_gtdt (infix_asdt z x) (infix_asdt z y).
Axiom inv_inf_eq :
forall (a:t) (b:t), (infix_lsdt tzero a) -> (infix_lsdt tzero b) ->
(infix_lseqdt a b) -> infix_lseqdt (infix_sldt tone b) (infix_sldt tone a).
Axiom inv_sup_eq :
forall (a:t) (b:t), (infix_lsdt tzero a) -> (infix_lsdt tzero b) ->
(infix_gteqdt a b) -> infix_gteqdt (infix_sldt tone b) (infix_sldt tone a).
Axiom inv_sup :
forall (x:t) (y:t), (real_ x) -> (real_ y) ->
((infix_lsdt tzero x) /\ (infix_lsdt x y)) ->
infix_gtdt (infix_sldt tone x) (infix_sldt tone y).
Axiom inv_eqinf :
forall (x:t) (y:t), (real_ x) -> (real_ y) ->
((infix_lsdt tzero x) /\ (infix_lseqdt x y)) ->
infix_gteqdt (infix_sldt tone x) (infix_sldt tone y).
Axiom inv_eqsup :
forall (x:t) (y:t), (real_ x) -> (real_ y) ->
((infix_gteqdt x y) /\ (infix_gtdt y tzero)) ->
infix_lseqdt (infix_sldt tone x) (infix_sldt tone y).
Axiom inv_inf :
forall (x:t) (y:t), (real_ x) -> (real_ y) ->
((infix_gtdt x y) /\ (infix_gtdt y tzero)) ->
infix_lsdt (infix_sldt tone x) (infix_sldt tone y).
Axiom inv_neg :
forall (x:t), (real_ x) -> (infix_gtdt tzero x) ->
infix_lsdt (infix_sldt tone x) tzero.
Axiom lower_inv :
forall (a:t) (b:t) (c:t), (infix_lsdt tzero b) -> (infix_lseqdt tzero a) ->
(infix_lseqdt b c) -> infix_gteqdt (infix_sldt a b) (infix_sldt a c).
Axiom zero_add_t :
forall (a1:t) (a2:t), (a1 = tzero) -> ((infix_pldt a1 a2) = a2).
Axiom add_zero_t :
forall (a1:t) (a2:t), (a2 = tzero) -> ((infix_pldt a1 a2) = a1).
Axiom one_mult_t :
forall (a1:t) (a2:t), (a1 = tone) -> ((infix_asdt a1 a2) = a2).
Axiom one_mult_t_const : forall (a:t), ((infix_asdt tone a) = a).
Axiom zero_mult_t_const : forall (a:t), ((infix_asdt tzero a) = tzero).
Axiom mult_zero_t_const : forall (a:t), ((infix_asdt a tzero) = tzero).
Axiom zero_mult_t :
forall (a1:t) (a2:t), (a1 = tzero) -> ((infix_asdt a1 a2) = tzero).
Axiom mult_zero_t :
forall (a1:t) (a2:t), (a1 = tzero) -> ((infix_asdt a2 a1) = tzero).
Axiom mult_one_t :
forall (a1:t) (a2:t), (a2 = tone) -> ((infix_asdt a1 a2) = a1).
Axiom add_eq_t :
forall (a1:t) (a2:t) (b1:t) (b2:t), (a1 = a2) -> (b1 = b2) ->
((infix_pldt a1 b1) = (infix_pldt a2 b2)).
Axiom add_eq_t_rev :
forall (a1:t) (a2:t) (b1:t) (b2:t), (a1 = a2) -> (b1 = b2) ->
((infix_pldt a1 b1) = (infix_pldt b2 a2)).
Axiom subs_eq :
forall (a1:t) (a2:t) (b1:t) (b2:t), (a1 = a2) -> (b1 = b2) ->
((infix_mndt a1 b1) = (infix_mndt a2 b2)).
Axiom subst_itself :
forall (a1:t) (a2:t), (a1 = a2) -> ((infix_mndt a1 a2) = tzero).
Axiom add_op :
forall (a1:t) (a2:t), (a1 = (prefix_mndt a2)) ->
((infix_pldt a1 a2) = tzero).
Axiom mult_eq_t :
forall (a1:t) (a2:t) (b1:t) (b2:t), (a1 = a2) -> (b1 = b2) ->
((infix_asdt a1 b1) = (infix_asdt a2 b2)).
Axiom mult_eq_t_rev :
forall (a1:t) (a2:t) (b1:t) (b2:t), (a1 = a2) -> (b1 = b2) ->
((infix_asdt a1 b1) = (infix_asdt b2 a2)).
Axiom mult_comm : forall (a:t) (b:t), ((infix_asdt a b) = (infix_asdt b a)).
Axiom mult_assoc :
forall (a:t) (b:t) (c:t),
((infix_asdt (infix_asdt a b) c) = (infix_asdt a (infix_asdt b c))).
Axiom mult_assoc_rev :
forall (a:t) (b:t) (c:t),
((infix_asdt a (infix_asdt b c)) = (infix_asdt (infix_asdt a b) c)).
Axiom div_mult :
forall (a:t) (b:t) (c:t), ~ (c = tzero) ->
((infix_asdt a (infix_sldt b c)) = (infix_sldt (infix_asdt a b) c)).
Axiom div_mult_rev :
forall (a:t) (b:t) (c:t), ~ (c = tzero) ->
((infix_sldt (infix_asdt a b) c) = (infix_asdt a (infix_sldt b c))).
Axiom triang_p :
forall (a:t) (b:t),
((infix_asdt (infix_pldt a b) (infix_pldt a b)) =
(infix_pldt
(infix_pldt (infix_asdt a a) (infix_asdt (infix_asdt ttwo a) b))
(infix_asdt b b))).
Axiom triang_n :
forall (a:t) (b:t),
((infix_asdt (infix_mndt a b) (infix_mndt a b)) =
(infix_pldt
(infix_mndt (infix_asdt a a) (infix_asdt (infix_asdt ttwo a) b))
(infix_asdt b b))).
Axiom triang_s :
forall (a:t) (b:t) (c:t) (d:t) (e:t),
((infix_pldt (infix_pldt (infix_pldt a b) c)
(infix_pldt (infix_mndt d b) e))
= (infix_pldt (infix_pldt a c) (infix_pldt d e))).
Axiom triang_t :
forall (a:t) (b:t),
((infix_asdt (infix_pldt a b) (infix_mndt a b)) =
(infix_mndt (infix_asdt a a) (infix_asdt b b))).
Axiom triang_sr :
forall (a:t) (b:t) (c:t) (d:t) (e:t),
((infix_pldt (infix_pldt (infix_mndt a b) c)
(infix_pldt (infix_pldt d b) e))
= (infix_pldt (infix_pldt a c) (infix_pldt d e))).
Axiom add_pos :
forall (x:t) (y:t), (infix_lseqdt tzero x) -> (infix_lseqdt tzero y) ->
infix_lseqdt tzero (infix_pldt x y).
Axiom add_pos_strit_l :
forall (x:t) (y:t), (infix_lsdt tzero x) -> (infix_lseqdt tzero y) ->
infix_lsdt tzero (infix_pldt x y).
Axiom add_pos_strit_r :
forall (x:t) (y:t), (infix_lseqdt tzero x) -> (infix_lsdt tzero y) ->
infix_lsdt tzero (infix_pldt x y).
Axiom modulus_pre_pre :
forall (a:t) (b:t) (c:t) (d:t),
((infix_pldt (infix_pldt (infix_asdt a b) (infix_asdt c d))
(infix_pldt (infix_asdt a d) (infix_asdt c b)))
=
(infix_pldt (infix_asdt a (infix_pldt b d))
(infix_asdt c (infix_pldt b d)))) /\
((infix_pldt (infix_pldt (infix_asdt a b) (infix_asdt c d))
(infix_pldt (infix_asdt a d) (infix_asdt c b)))
= (infix_asdt (infix_pldt a c) (infix_pldt b d))).
Axiom modulus_pre :
forall (a:t) (b:t) (c:t) (d:t),
((infix_pldt
(infix_pldt (infix_asdt (infix_asdt a b) (infix_asdt a b))
(infix_asdt (infix_asdt c d) (infix_asdt c d)))
(infix_pldt (infix_asdt (infix_asdt a d) (infix_asdt a d))
(infix_asdt (infix_asdt c b) (infix_asdt c b))))
=
(infix_asdt (infix_pldt (infix_asdt a a) (infix_asdt c c))
(infix_pldt (infix_asdt b b) (infix_asdt d d)))).
Parameter real_sqrt: R -> R.
Axiom real_sqrt_spec : forall (x:R), ((real_sqrt x) = (Reals.R_sqrt.sqrt x)).
Parameter square_rt: t -> t.
Axiom square_rt_def :
forall (x:t), (infix_lseqdt tzero x) ->
((square_rt x) = (r_to_t (real_sqrt (real_part x)))).
Axiom square_rt_spec :
forall (x:t), (infix_lseqdt tzero x) ->
((infix_asdt (square_rt x) (square_rt x)) = x) /\
(infix_lseqdt tzero (square_rt x)).
Axiom square_rt_eq :
forall (a:t) (b:t), (a = b) -> ((square_rt a) = (square_rt b)).
Axiom real_square_rt :
forall (x:t), (real_ x) -> (infix_lseqdt tzero x) -> real_ (square_rt x).
Axiom pos_square_rt :
forall (x:t), (real_ x) -> (infix_lseqdt tzero x) ->
infix_gteqdt (square_rt x) tzero.
Axiom square_rt_mult :
forall (t1:t) (t':t), (real_ t1) -> (infix_lseqdt tzero t1) ->
(real_ t') -> (infix_lseqdt tzero t') ->
((infix_asdt (square_rt t1) (square_rt t')) =
(square_rt (infix_asdt t1 t'))).
Parameter modulus: t -> t.
Axiom modulus_def :
forall (x:t),
((modulus x) =
(square_rt
(infix_pldt (infix_asdt (t_real_part x) (t_real_part x))
(infix_asdt (t_im_part x) (t_im_part x))))).
Axiom modulus_spec : forall (x:t), infix_lseqdt tzero (modulus x).
Parameter tone_modulus: t -> Prop.
Axiom tone_modulus_def :
forall (x:t), (tone_modulus x) <-> ((modulus x) = tone).
Axiom modulus_eq :
forall (x:t) (y:t),
((infix_asdt (t_real_part x) (t_real_part x)) =
(infix_asdt (t_real_part y) (t_real_part y))) ->
((infix_asdt (t_im_part x) (t_im_part x)) =
(infix_asdt (t_im_part y) (t_im_part y))) ->
((modulus x) = (modulus y)).
Axiom modulus_itself :
forall (x:t) (y:t), (x = y) -> ((modulus x) = (modulus y)).
Axiom modulus_real_pos :
forall (x:t), (real_ x) -> (infix_lseqdt tzero x) -> ((modulus x) = x).
Axiom strict_positive_modulus :
forall (x:t), ~ (x = tzero) -> infix_lsdt tzero (modulus x).
Axiom mult_modulus :
forall (x:t) (y:t),
((modulus (infix_asdt x y)) = (infix_asdt (modulus x) (modulus y))).
Axiom mult_modulus_non_null :
forall (x:t) (y:t), ~ (x = tzero) -> ~ (y = tzero) ->
~ ((modulus (infix_asdt x y)) = tzero).
Axiom modulus_to_non_null :
forall (x:t), (infix_lsdt tzero (modulus x)) -> ~ (x = tzero).
Axiom mult_tone_modulus :
forall (x:t) (y:t), (tone_modulus x) -> (tone_modulus y) ->
tone_modulus (infix_asdt x y).
Axiom modulus_pos :
forall (x:t), ~ (x = tzero) -> infix_lseqdt tzero (modulus x).
Axiom div_eq :
forall (a1:t) (a2:t) (b1:t) (b2:t), (a1 = a2) -> (b1 = b2) ->
~ (b1 = tzero) -> ((infix_sldt a1 b1) = (infix_sldt a2 b2)).
Axiom add_eq_inv_t :
forall (a1:t) (a2:t) (b1:t) (b2:t), (a1 = a2) -> (b1 = b2) ->
((infix_pldt a1 b1) = (infix_pldt b2 a2)).
Axiom mult_eq_inv_t :
forall (a1:t) (a2:t) (b1:t) (b2:t), (a1 = a2) -> (b1 = b2) ->
((infix_asdt a1 b1) = (infix_asdt b2 a2)).
Axiom sum_frac :
forall (a1:t) (a2:t) (b:t), ~ (b = tzero) ->
((infix_pldt (infix_sldt a1 b) (infix_sldt a2 b)) =
(infix_sldt (infix_pldt a1 a2) b)).
Axiom sum_frac_rev :
forall (a1:t) (a2:t) (b:t), ~ (b = tzero) ->
((infix_sldt (infix_pldt a1 a2) b) =
(infix_pldt (infix_sldt a1 b) (infix_sldt a2 b))).
Parameter op: forall {im1:Type} {im1_WT:WhyType im1}, im1 -> im1 -> im1.
Parameter po: forall {im1:Type} {im1_WT:WhyType im1}, im1 -> im1 -> im1.
Parameter inver: forall {im1:Type} {im1_WT:WhyType im1}, im1 -> im1.
Parameter filter:
forall {a:Type} {a_WT:WhyType a}, (a -> bool) -> (set a) -> set a.
Axiom filter_def :
forall {a:Type} {a_WT:WhyType a},
forall (p:a -> bool) (u:set a), forall (x:a),
(mem x (filter p u)) <-> (((p x) = true) /\ (mem x u)).
Axiom filter_cardinal :
forall {a:Type} {a_WT:WhyType a},
forall (p:a -> bool) (u:set a), ((cardinal (filter p u)) <= (cardinal u))%Z.
Parameter map:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a -> b) ->
(set a) -> set b.
Axiom map_def1 :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (u:set a), forall (y:b),
(mem y (map f u)) <-> exists x:a, (mem x u) /\ (y = (f x)).
Axiom map_def2 :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (u:set a), forall (x:a), (mem x u) -> mem (f x) (map f u).
Axiom map_cardinal :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (u:set a), ((cardinal (map f u)) <= (cardinal u))%Z.
Parameter eq_e: forall {a:Type} {a_WT:WhyType a}, a -> a -> Prop.
Axiom eq_e_def :
forall {a:Type} {a_WT:WhyType a},
forall (a1:a) (a':a), (eq_e a1 a') <-> (a1 = a').
Parameter fir:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a* b)%type ->
a.
Parameter sec:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a* b)%type ->
b.
Axiom projections :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (o:(a* b)%type), (o = (fir o, sec o)).
Axiom get_fir :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (a1:a) (b1:b), ((fir (a1, b1)) = a1).
Axiom get_sec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (a1:a) (b1:b), ((sec (a1, b1)) = b1).
(* Why3 assumption *)
Inductive ref (a:Type) :=
| mk_ref : a -> ref a.
Axiom ref_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (ref a).
Existing Instance ref_WhyType.
Arguments mk_ref {a}.
(* Why3 assumption *)
Definition contents {a:Type} {a_WT:WhyType a} (v:ref a) : a :=
match v with
| mk_ref x => x
end.
Parameter prefix_ex: forall {a:Type} {a_WT:WhyType a}, (ref a) -> a.
Axiom prefix_ex_def :
forall {a:Type} {a_WT:WhyType a},
forall (r:ref a), ((prefix_ex r) = (contents r)).
Axiom set_equal :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a), (forall (e:a), (mem e s) -> mem e s') ->
(forall (e:a), (mem e s') -> mem e s) -> (s = s').
Axiom union_exchange :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a), ~ (is_empty s') ->
((union (add (choose s') s) (remove (choose s') s')) = (union s s')).
Axiom get_filter :
forall {a:Type} {a_WT:WhyType a},
forall (p:a -> bool) (s:set a) (x:a), (mem x (filter p s)) ->
((p x) = true) /\ (mem x s).
Axiom set_filter :
forall {a:Type} {a_WT:WhyType a},
forall (p:a -> bool) (s:set a) (x:a), ((p x) = true) -> (mem x s) ->
mem x (filter p s).
Axiom inter_empty :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a), (is_empty s) -> is_empty (inter s s').
Axiom inter_empty_comm :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a), (is_empty s') -> is_empty (inter s s').
Axiom inter_sym :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a), ((inter s s') = (inter s' s)).
Axiom union_sym :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a), ((union s s') = (union s' s)).
Axiom union_empty :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a), (is_empty s) -> ((union s s') = s').
Axiom union_comm :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a), (is_empty s') -> ((union s s') = s).
Axiom union_members :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a),
(forall (a1:a), (mem a1 (union s s')) -> ~ (mem a1 s) -> mem a1 s') /\
forall (a1:a), (mem a1 (union s s')) -> ~ (mem a1 s') -> mem a1 s.
Axiom union_alt :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (e:a), (mem e (union s s')) -> ~ (mem e s) ->
mem e s'.
Axiom union_empty_comm :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a), (is_empty s') -> ((union s s') = s).
Axiom set_subset :
forall {a:Type} {a_WT:WhyType a},
forall (s':set a) (s:set a), (forall (e:a), (mem e s') -> mem e s) ->
subset s' s.
Axiom set_empty :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a), (forall (e:a), ~ (mem e s)) ->
(s = (empty : set a)) /\ (is_empty s).
Axiom get_empty :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a), (s = (empty : set a)) ->
(forall (e:a), ~ (mem e s)) /\ (is_empty s).
Axiom get_non_empty :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a), ~ (is_empty s) -> exists e:a, mem e s.
Axiom set_non_empty :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a), (exists e:a, mem e s) ->
~ (is_empty s) /\ ((cardinal s) > 0%Z)%Z.
Axiom set_pos_card_elt :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (a1:a), (mem a1 s) -> ((cardinal s) > 0%Z)%Z.
Axiom union_add :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (x:a), ~ (mem x s') ->
((union s (add x s')) = (add x (union s s'))).
Axiom union_add_mem :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (x:a) (y:a), (mem x (add y (union s s'))) ->
~ (mem x s') -> ~ (mem x s) -> (x = y).
Axiom union_add_comm :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (x:a), ~ (mem x s') ->
((add x (union s s')) = (union s (add x s'))).
Axiom remove_add1 :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (x:a), ~ (mem x s) -> ((remove x (add x s)) = s).
Axiom add_remove1 :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (x:a), (mem x s) -> ((add x (remove x s)) = s).
Parameter p_injective:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a -> b) ->
(set a) -> Prop.
Axiom p_injective_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a),
(p_injective f s) <->
forall (e:a) (e':a), (mem e s) -> (mem e' s) -> ~ (e = e') ->
~ ((f e) = (f e')).
Axiom set_map_mem :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (b1:b),
(exists a1:a, (mem a1 s) /\ (b1 = (f a1))) -> mem b1 (map f s).
Axiom map_add :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (x:a), ~ (mem x s) ->
((map f (add x s)) = (add (f x) (map f s))).
Axiom map_eq :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (g:a -> b) (s:set a),
(forall (e:a), (mem e s) -> ((f e) = (g e))) -> ((map f s) = (map g s)).
Axiom remove_mem :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (e:a) (f:a), (mem e (remove f s)) -> mem e s.
Axiom injective_map_cardinal :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a), (p_injective f s) ->
((cardinal (map f s)) = (cardinal s)).
Axiom set_map_mem_el :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (b1:b) (a1:a), (mem a1 s) -> (b1 = (f a1)) ->
mem b1 (map f s).
Axiom set_map_mem_el_gen :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (b1:b),
(exists a1:a, (mem a1 s) /\ (b1 = (f a1))) -> mem b1 (map f s).
Axiom map_antec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (b1:b), (mem b1 (map f s)) ->
exists a1:a, (mem a1 s) /\ (b1 = (f a1)).
Axiom map_antec_gen :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a), forall (b1:b), (mem b1 (map f s)) ->
exists a1:a, (mem a1 s) /\ (b1 = (f a1)).
Axiom map_remove_choose :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s:set a) (f:a -> b), (p_injective f s) ->
((map f (remove (choose s) s)) = (remove (f (choose s)) (map f s))).
Parameter antec_set:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (set a) ->
(a -> b) -> b -> set a.
Parameter result:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a -> b) ->
b -> a -> bool.
Axiom result_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (b1:b) (e:a),
(((result f b1) e) = true) <-> (eq_e (f e) b1).
Axiom antec_set_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s:set a) (f:a -> b) (b1:b), (mem b1 (map f s)) ->
((antec_set s f b1) = (filter (result f b1) s)).
Parameter remove_s:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (set a) -> set a.
Parameter result1: forall {a:Type} {a_WT:WhyType a}, (set a) -> a -> bool.
Axiom result_def1 :
forall {a:Type} {a_WT:WhyType a},
forall (s':set a) (e:a), (((result1 s') e) = true) <-> ~ (mem e s').
Axiom remove_s_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a), (subset s' s) ->
((remove_s s s') = (filter (result1 s') s)).
Axiom remove_s_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a), (subset s' s) -> forall (e:a),
(mem e (remove_s s s')) <-> ((mem e s) /\ ~ (mem e s')).
Parameter remove_antecs:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (set a) ->
(a -> b) -> b -> set a.
Axiom remove_antecs_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s:set a) (f:a -> b) (b1:b), (mem b1 (map f s)) ->
((remove_antecs s f b1) = (remove_s s (antec_set s f b1))).
Axiom remove_antecs_spec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s:set a) (f:a -> b) (b1:b), (mem b1 (map f s)) ->
(forall (e:a),
(mem e (remove_antecs s f b1)) <-> ((mem e s) /\ ~ ((f e) = b1))) /\
((cardinal (remove_antecs s f b1)) < (cardinal s))%Z.
Axiom map_remove_antec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s:set a) (f:a -> b) (b1:b), (mem b1 (map f s)) ->
((map f (remove_antecs s f b1)) = (remove b1 (map f s))).
Axiom map_non_empty :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a), ((cardinal s) > 0%Z)%Z ->
((cardinal (map f s)) > 0%Z)%Z.
Axiom non_empty_map :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a), ((cardinal (map f s)) > 0%Z)%Z ->
((cardinal s) > 0%Z)%Z.
Parameter right_injections:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, a -> (set b) ->
set (a* b)%type.
Axiom right_injections_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (a1:a) (s:set b),
((is_empty s) -> ((right_injections a1 s) = (empty : set (a* b)%type))) /\
(~ (is_empty s) ->
((right_injections a1 s) =
(add (a1, choose s) (right_injections a1 (remove (choose s) s))))).
Axiom right_injections_spec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (a1:a) (s:set b),
((cardinal (right_injections a1 s)) = (cardinal s)) /\
((forall (a':a), forall (b1:b),
(mem (a', b1) (right_injections a1 s)) <-> ((a' = a1) /\ (mem b1 s))) /\
((right_injections a1 s) = (map (fun (b1:b) => (a1, b1)) s))).
Parameter left_injections:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (set a) -> b ->
set (a* b)%type.
Axiom left_injections_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s:set a) (b1:b),
((is_empty s) -> ((left_injections s b1) = (empty : set (a* b)%type))) /\
(~ (is_empty s) ->
((left_injections s b1) =
(add (choose s, b1) (left_injections (remove (choose s) s) b1)))).
Axiom left_injections_spec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s:set a) (b1:b),
(forall (a1:a), forall (b':b),
(mem (a1, b') (left_injections s b1)) <-> ((mem a1 s) /\ (b' = b1))) /\
(((cardinal (left_injections s b1)) = (cardinal s)) /\
((left_injections s b1) = (map (fun (a1:a) => (a1, b1)) s))).
Axiom right_injections_l :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (a1:a) (s:set b),
((cardinal (right_injections a1 s)) = (cardinal s)) /\
((forall (a':a), forall (b1:b),
(mem (a', b1) (right_injections a1 s)) <-> ((a' = a1) /\ (mem b1 s))) /\
((right_injections a1 s) = (map (fun (b1:b) => (a1, b1)) s))).
Axiom left_injections_l :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s:set a) (b1:b),
(forall (a1:a), forall (b':b),
(mem (a1, b') (left_injections s b1)) <-> ((mem a1 s) /\ (b' = b1))) /\
(((cardinal (left_injections s b1)) = (cardinal s)) /\
((left_injections s b1) = (map (fun (a1:a) => (a1, b1)) s))).
Axiom disjoint_injections :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s:set a) (b1:b) (c:b), ~ (b1 = c) ->
(is_empty (inter (right_injections b1 s) (right_injections c s))) /\
(is_empty (inter (left_injections s b1) (left_injections s c))).
Axiom induction :
forall {a:Type} {a_WT:WhyType a},
forall (p:(set a) -> bool) (t1:set a),
(forall (s:set a), (is_empty s) -> ((p s) = true)) ->
(forall (s:set a), ((p s) = true) -> forall (t2:a), ~ (mem t2 s) ->
((p (add t2 s)) = true)) ->
((p t1) = true).
Axiom cardinal_sum :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a),
((cardinal (union s s')) =
(((cardinal s) + (cardinal s'))%Z - (cardinal (inter s s')))%Z).
Axiom cardinal_sum_empty_inter :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a), ((inter s s') = (empty : set a)) ->
((cardinal (union s s')) = ((cardinal s) + (cardinal s'))%Z).
Parameter cartesian_product:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (set a) ->
(set b) -> set (a* b)%type.
Axiom cartesian_product_spec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set b),
((cardinal (cartesian_product s1 s2)) = ((cardinal s1) * (cardinal s2))%Z) /\
((forall (a1:a), forall (b1:b),
(mem (a1, b1) (cartesian_product s1 s2)) <-> ((mem a1 s1) /\ (mem b1 s2))) /\
forall (o:(a* b)%type),
(mem o (cartesian_product s1 s2)) <->
((mem (fir o) s1) /\ (mem (sec o) s2))).
Parameter commute:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a* b)%type ->
(b* a)%type.
Axiom commute_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (o:(a* b)%type),
match o with
| (a1, b1) => ((commute o) = (b1, a1))
end.
Axiom commute_inj :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (a1:a) (a':a) (b1:b) (b':b), ((a1 = a') -> ~ (b1 = b')) ->
~ ((commute (a1, b1)) = (commute (a', b'))).
Axiom mem_cartesian_product :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set b) (a1:a) (b1:b), (mem a1 s1) -> (mem b1 s2) ->
mem (a1, b1) (cartesian_product s1 s2).
Axiom commute_inj_gen :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set b),
p_injective (fun (y0:(a* b)%type) => (commute y0))
(cartesian_product s1 s2).
Parameter commute_product:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (set a) ->
(set b) -> set (b* a)%type.
Axiom commute_product_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set b),
((commute_product s1 s2) =
(map (fun (y0:(a* b)%type) => (commute y0)) (cartesian_product s1 s2))).
Axiom commute_product_spec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set b),
((commute_product s1 s2) = (cartesian_product s2 s1)).
Parameter commute_product_el:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (set a) ->
(set b) -> set (b* a)%type.
Axiom commute_product_el_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set b),
((commute_product_el s1 s2) =
(map (fun (y0:(a* b)%type) => (commute y0)) (cartesian_product s1 s2))).
Axiom commute_product_el_spec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set b), forall (o:(a* b)%type),
match o with
| (a1, b1) =>
((mem o (cartesian_product s1 s2)) <-> ((mem a1 s1) /\ (mem b1 s2))) /\
(((mem a1 s1) /\ (mem b1 s2)) <->
(mem (b1, a1) (commute_product_el s1 s2)))
end.
Axiom cartesian_product_union :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set b) (s3:set b),
((cartesian_product s1 (union s2 s3)) =
(union (cartesian_product s1 s2) (cartesian_product s1 s3))).
Axiom cartesian_union_product :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set a) (s3:set b),
((cartesian_product (union s1 s2) s3) =
(union (cartesian_product s1 s3) (cartesian_product s2 s3))).
Axiom cartesian_product_cardone_r :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set b), ((cardinal s1) = 1%Z) ->
(infix_eqeq (cartesian_product s1 s2) (right_injections (choose s1) s2)) /\
(infix_eqeq (cartesian_product s1 s2)
(map (fun (e2:b) => (choose s1, e2)) s2)).
Axiom cartesian_product_cardone_l :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set b), ((cardinal s2) = 1%Z) ->
(infix_eqeq (cartesian_product s1 s2) (left_injections s1 (choose s2))) /\
(infix_eqeq (cartesian_product s1 s2)
(map (fun (e1:a) => (e1, choose s2)) s1)).
Axiom disjoint_cartesian_product_l :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set a) (s3:set b),
((inter s1 s2) = (empty : set a)) ->
((inter (cartesian_product s1 s3) (cartesian_product s2 s3)) =
(empty : set (a* b)%type)).
Axiom disjoint_cartesian_product_r :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set b) (s3:set b),
((inter s2 s3) = (empty : set b)) ->
((inter (cartesian_product s1 s2) (cartesian_product s1 s3)) =
(empty : set (a* b)%type)).
Parameter iter_union:
forall {a:Type} {a_WT:WhyType a}, (set (set a)) -> set a.
Axiom iter_union_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set (set a)),
((is_empty s) -> ((iter_union s) = (empty : set a))) /\
(~ (is_empty s) ->
((iter_union s) = (union (choose s) (iter_union (remove (choose s) s))))).
Parameter op_neutral_left:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) -> im1 -> Prop.
Axiom op_neutral_left_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (neutral:im1),
(op_neutral_left op1 neutral) <-> forall (e:im1), (((op1 neutral) e) = e).
Parameter op_neutral_right:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) -> im1 -> Prop.
Axiom op_neutral_right_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (neutral:im1),
(op_neutral_right op1 neutral) <-> forall (e:im1), (((op1 e) neutral) = e).
Parameter op_assoc:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) -> Prop.
Axiom op_assoc_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1),
(op_assoc op1) <->
forall (a:im1) (b:im1) (c:im1),
(((op1 ((op1 a) b)) c) = ((op1 a) ((op1 b) c))).
Parameter op_neutral_left_comm:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) -> im1 -> Prop.
Axiom op_neutral_left_comm_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (neutral:im1),
(op_neutral_left_comm op1 neutral) <->
forall (a:im1), (forall (b:im1), (((op1 a) b) = b)) -> (a = neutral).
Parameter commut:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) -> Prop.
Axiom commut_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1),
(commut op1) <-> forall (a:im1) (b:im1), (((op1 a) b) = ((op1 b) a)).
Parameter assoc:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) -> Prop.
Axiom assoc_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1),
(assoc op1) <->
forall (a:im1) (b:im1) (c:im1),
(((op1 ((op1 a) b)) c) = ((op1 a) ((op1 b) c))).
Parameter opposite_n:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) ->
(im1 -> im1 -> im1) -> im1 -> Prop.
Axiom opposite_n_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (po1:im1 -> im1 -> im1) (neutral:im1),
(opposite_n op1 po1 neutral) <-> forall (a:im1), (((po1 a) a) = neutral).
Parameter inverse:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) ->
(im1 -> im1 -> im1) -> (im1 -> im1) -> Prop.
Axiom inverse_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (po1:im1 -> im1 -> im1) (inver1:im1 -> im1),
(inverse op1 po1 inver1) <->
forall (a:im1) (b:im1), (((po1 a) b) = ((op1 a) (inver1 b))).
Parameter opposite1:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) ->
(im1 -> im1 -> im1) -> Prop.
Axiom opposite_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (po1:im1 -> im1 -> im1),
(opposite1 op1 po1) <-> forall (a:im1) (b:im1), (((op1 ((po1 a) b)) b) = a).
Parameter opposite_com:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) ->
(im1 -> im1 -> im1) -> Prop.
Axiom opposite_com_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (po1:im1 -> im1 -> im1),
(opposite_com op1 po1) <->
forall (a:im1) (b:im1), (((po1 ((op1 a) b)) b) = a).
Axiom refl :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (a:im1) (b:im1), (commut op1) ->
(((op1 a) b) = ((op1 b) a)).
Parameter neutral:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) -> im1 -> Prop.
Axiom neutral_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (neut:im1),
(neutral op1 neut) <->
((op_neutral_left op1 neut) /\
((op_neutral_right op1 neut) /\ (op_assoc op1))).
Axiom set_neutral :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (neut:im1), (op_neutral_left op1 neut) ->
(op_neutral_right op1 neut) -> (op_assoc op1) -> neutral op1 neut.
Parameter has_neutral:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) -> Prop.
Axiom has_neutral_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1),
(has_neutral op1) <-> exists e:im1, neutral op1 e.
Parameter iterates:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) -> im1 -> Prop.
Axiom iterates_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (neutral1:im1),
(iterates op1 neutral1) <->
((op_neutral_left op1 neutral1) /\
((op_neutral_right op1 neutral1) /\ (op_assoc op1))).
Parameter iterable:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) -> Prop.
Axiom iterable_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1),
(iterable op1) <-> exists e:im1, iterates op1 e.
Axiom iterates_ :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (neutral1:im1),
(op_neutral_left op1 neutral1) -> (op_neutral_right op1 neutral1) ->
(op_assoc op1) -> (iterates op1 neutral1) /\ (iterable op1).
Parameter neutral_elt:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) -> im1.
Axiom neutral_elt_spec :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1), forall (e:im1),
(neutral op1 e) <-> ((neutral_elt op1) = e).
Parameter inverse_tuple:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) ->
(im1 -> im1 -> im1) -> im1 -> Prop.
Axiom inverse_tuple_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (po1:im1 -> im1 -> im1) (neutral1:im1),
(inverse_tuple op1 po1 neutral1) <->
((opposite_n op1 po1 neutral1) /\
((opposite1 op1 po1) /\ (opposite_com op1 po1))).
Parameter iterate:
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
(im1 -> im1 -> im1) -> (set a) -> (a -> im1) -> im1.
Axiom Iterate_def_empty :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1), forall (s:set a), forall (f:a -> im1),
(commut op1) -> (iterable op1) -> (is_empty s) ->
((iterate op1 (empty : set a) f) = (neutral_elt op1)).
Axiom Iterate_one :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1), forall (s:set a), forall (f:a -> im1),
forall (x:a), (is_empty s) -> (commut op1) ->
((iterate op1 (add x s) f) = (f x)).
Axiom Iterate_add :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1), forall (s:set a), forall (f:a -> im1),
forall (x:a), ((cardinal s) > 0%Z)%Z -> (commut op1) -> ~ (mem x s) ->
((iterate op1 (add x s) f) = ((op1 (f x)) (iterate op1 s f))).
Axiom minus_zero :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (po1:im1 -> im1 -> im1) (a:im1),
(iterable op1) -> (inverse_tuple op1 po1 (neutral_elt op1)) ->
(((po1 a) (neutral_elt op1)) = a).
Axiom unic :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (po1:im1 -> im1 -> im1) (a:im1) (b:im1)
(c:im1),
(iterable op1) -> (commut op1) -> (((op1 a) b) = ((op1 a) c)) ->
(inverse_tuple op1 po1 (neutral_elt op1)) -> (b = c).
Axiom substract_comm :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (po1:im1 -> im1 -> im1) (a:im1) (b:im1)
(c:im1),
(iterable op1) -> (commut op1) ->
(inverse_tuple op1 po1 (neutral_elt op1)) ->
(((po1 ((op1 a) b)) a) = b) /\
((((po1 ((op1 b) a)) a) = b) /\
((((po1 a) ((po1 b) c)) = ((op1 ((po1 a) b)) c)) /\
(((po1 ((op1 a) b)) c) = ((op1 a) ((po1 b) c))))).
Parameter int_iterate:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) ->
(Z -> im1) -> Z -> Z -> im1.
Axiom int_iterate_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (i:Z) (j:Z),
((j <= i)%Z -> iterable op1) ->
((j <= i)%Z -> ((int_iterate op1 f i j) = (neutral_elt op1))) /\
(~ (j <= i)%Z ->
((j = (i + 1%Z)%Z) -> ((int_iterate op1 f i j) = (f i))) /\
(~ (j = (i + 1%Z)%Z) ->
((int_iterate op1 f i j) =
((op1 (f i)) (int_iterate op1 f (i + 1%Z)%Z j))))).
Axiom int_iterate_spec :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (i:Z) (j:Z),
((j <= i)%Z -> iterable op1) ->
((j <= i)%Z -> ((int_iterate op1 f i j) = (neutral_elt op1))) /\
((j = (i + 1%Z)%Z) ->
((int_iterate op1 f i j) = ((op1 (f i)) (neutral_elt op1)))).
Parameter int_int_iterate:
forall {im1:Type} {im1_WT:WhyType im1}, (im1 -> im1 -> im1) ->
(Z -> Z -> im1) -> Z -> Z -> Z -> Z -> im1.
Axiom int_int_iterate_def :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> Z -> im1) (i:Z) (j:Z) (k:Z) (l:Z),
(iterable op1) ->
((j <= i)%Z -> ((int_int_iterate op1 f i j k l) = (neutral_elt op1))) /\
(~ (j <= i)%Z ->
((int_int_iterate op1 f i j k l) =
((op1 (int_iterate op1 (f i) k l))
(int_int_iterate op1 f (i + 1%Z)%Z j k l)))).
Parameter element: forall {a:Type} {a_WT:WhyType a}, (set a) -> a.
Axiom element_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a), ((cardinal s) = 1%Z) -> ((element s) = (choose s)).
Axiom cardone :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (a1:a), (forall (b:a), (mem b s) <-> (b = a1)) ->
((cardinal s) > 0%Z)%Z -> ((cardinal s) = 1%Z) /\ ((element s) = a1).
Axiom set_cardone :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a), ((cardinal s) > 0%Z)%Z ->
(exists a1:a, forall (b:a), (mem b s) <-> (b = a1)) -> ((cardinal s) = 1%Z).
Axiom get_cardone :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a), ((cardinal s) = 1%Z) ->
exists a1:a, forall (b:a), (mem b s) <-> (b = a1).
Axiom get_cardone_elt :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (e:a), ((cardinal s) = 1%Z) -> (mem e s) ->
(e = (element s)).
Axiom set_cardone_elt :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (a1:a), (forall (b:a), (mem b s) <-> (b = a1)) ->
((cardinal s) = 1%Z) /\ ((element s) = a1).
Axiom set_cardone_elt_ :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (a1:a), (forall (b:a), (mem b s) <-> (b = a1)) ->
((cardinal s) = 1%Z).
Axiom cardzero :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a), (forall (b:a), ~ (mem b s)) -> ((cardinal s) = 0%Z).
Parameter to_set: forall {a:Type} {a_WT:WhyType a}, a -> set a.
Axiom to_set_def :
forall {a:Type} {a_WT:WhyType a},
forall (e:a), ((to_set e) = (add e (empty : set a))).
Axiom to_set_spec :
forall {a:Type} {a_WT:WhyType a},
forall (e:a),
((cardinal (to_set e)) = 1%Z) /\
forall (b:a), (mem b (to_set e)) -> (b = e).
Parameter to_fset: Z -> Z -> set Z.
Axiom to_fset_spec :
forall (i:Z) (j:Z),
((i < j)%Z -> ((cardinal (to_fset i j)) = (j - i)%Z)) /\
(((j <= i)%Z -> is_empty (to_fset i j)) /\
forall (k:Z), (mem k (to_fset i j)) <-> ((i <= k)%Z /\ (k < j)%Z)).
Axiom to_fset_unit_ext :
forall (i:Z) (j:Z), (i < j)%Z ->
((to_fset i j) = (add i (to_fset (i + 1%Z)%Z j))).
Axiom to_fset_ext :
forall (i:Z) (i':Z) (j:Z), ((i <= i')%Z /\ (i' <= j)%Z) ->
((to_fset i j) = (union (to_fset i i') (to_fset i' j))).
Axiom card_fset :
forall (n:Z), (0%Z <= n)%Z -> ((cardinal (to_fset 0%Z n)) = n).
Parameter p_injective_in:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a -> b) ->
(set a) -> (set b) -> Prop.
Axiom p_injective_in_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b),
(p_injective_in f s s') <->
forall (e:a), (mem e s) ->
(mem (f e) s') /\
forall (e1:a) (e':a), (mem e1 s) -> (mem e' s) -> ~ (e1 = e') ->
~ ((f e1) = (f e')).
Parameter equal_func:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a -> b) ->
(a -> b) -> Prop.
Axiom equal_func_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (g:a -> b),
(equal_func f g) <-> forall (e:a), ((f e) = (g e)).
Axiom set_equal_func :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (g:a -> b), (forall (e:a), ((f e) = (g e))) -> (f = g).
Axiom get_equal_func :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (g:a -> b), (equal_func f g) -> forall (e:a),
((f e) = (g e)).
Axiom set_injective :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a),
(forall (e:a) (e':a), (mem e s) -> (mem e' s) -> ~ (e = e') ->
~ ((f e) = (f e'))) ->
p_injective f s.
Parameter image:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a -> b) ->
(set a) -> set b.
Axiom image_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a), ((image f s) = (map f s)).
Axiom image_spec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a), forall (a1:b),
(mem a1 (image f s)) <->
exists antec_a:a, (mem antec_a s) /\ (a1 = (f antec_a)).
Axiom card_image :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a), ((cardinal (image f s)) <= (cardinal s))%Z.
Axiom card_image_injective :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a), (p_injective f s) ->
((cardinal (image f s)) = (cardinal s)).
Axiom get_injective :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a), (p_injective f s) -> forall (e:a) (e':a),
(mem e s) -> (mem e' s) -> ~ (e = e') -> ~ ((f e) = (f e')).
Axiom set_injective_in :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b),
(forall (e:a), (mem e s) -> mem (f e) s') ->
(forall (e:a) (e':a), (mem e s) -> (mem e' s) -> ~ (e = e') ->
~ ((f e) = (f e'))) ->
p_injective f s.
Axiom get_injective_in :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b), (p_injective_in f s s') ->
(forall (e:a), (mem e s) -> mem (f e) s') /\
forall (e:a) (e':a), (mem e s) -> (mem e' s) -> ~ (e = e') ->
~ ((f e) = (f e')).
Parameter p_surjective:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a -> b) ->
(set a) -> (set b) -> Prop.
Axiom p_surjective_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b),
(p_surjective f s s') <->
((forall (e:a), (mem e s) -> mem (f e) s') /\
forall (e':b), (mem e' s') -> exists e:a, (mem e s) /\ ((f e) = e')).
Axiom set_surjective :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b),
(forall (e:a), (mem e s) -> mem (f e) s') ->
(forall (e':b), (mem e' s') -> exists e:a, (mem e s) /\ ((f e) = e')) ->
p_surjective f s s'.
Axiom get_surjective :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b), (p_surjective f s s') ->
(forall (e:a), (mem e s) -> mem (f e) s') /\
forall (e':b), (mem e' s') -> exists e:a, (mem e s) /\ ((f e) = e').
Axiom image_surjective :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b), (p_surjective f s s') ->
((image f s) = s').
Parameter p_bijective:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a -> b) ->
(set a) -> (set b) -> Prop.
Axiom p_bijective_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b),
(p_bijective f s s') <-> ((p_injective_in f s s') /\ (p_surjective f s s')).
Axiom bijective_is_injective :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b), (p_bijective f s s') ->
p_injective f s.
Axiom bijective_is_surjective :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b), (p_bijective f s s') ->
p_surjective f s s'.
Axiom set_bijective :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b),
(forall (e:a), (mem e s) -> mem (f e) s') ->
(forall (e:a) (e':a), (mem e s) -> (mem e' s) -> ~ (e = e') ->
~ ((f e) = (f e'))) ->
(forall (e':b), (mem e' s') -> exists e:a, (mem e s) /\ ((f e) = e')) ->
(p_bijective f s s') /\ ((map f s) = s').
Axiom bijectivity_is_transitive :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}
{c:Type} {c_WT:WhyType c},
forall (f:a -> b) (g:b -> c) (s:set a) (s':set b) (s'':set c),
(p_bijective f s s') -> (p_bijective g s' s'') ->
p_bijective (fun (k:a) => (g (f k))) s s''.
Axiom bijective_image :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> a) (s:set a) (s':set a), (p_bijective f s s') ->
((cardinal s) = (cardinal s')) /\ (s' = (image f s)).
Axiom get_bijective :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b), (p_bijective f s s') ->
(forall (e:a), (mem e s) -> mem (f e) s') /\
((forall (e:a) (e':a), (mem e s) -> (mem e' s) -> ~ (e = e') ->
~ ((f e) = (f e'))) /\
((forall (e':b), (mem e' s') -> exists e:a, (mem e s) /\ ((f e) = e')) /\
((cardinal s) = (cardinal s')))).
Axiom bijective_eq :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (g:a -> b) (s:set a) (s':set b), (p_bijective f s s') ->
(forall (e:a), (mem e s) -> ((f e) = (g e))) -> p_bijective g s s'.
Axiom bijective_eq_gen :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b), (p_bijective f s s') ->
forall (g:a -> b), (forall (e:a), (mem e s) -> ((f e) = (g e))) ->
p_bijective g s s'.
Axiom bij_equal_card :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a), ((cardinal s) = (cardinal (map f s))) ->
p_bijective f s (map f s).
Axiom set_bijective_auto :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> a) (s:set a), (forall (e:a), (mem e s) -> mem (f e) s) ->
(forall (e':a), (mem e' s) -> exists e:a, (mem e s) /\ ((f e) = e')) ->
p_bijective f s s.
Parameter p_id: forall {a:Type} {a_WT:WhyType a}, a -> a.
Axiom p_id_def :
forall {a:Type} {a_WT:WhyType a}, forall (a1:a), ((p_id a1) = a1).
Parameter const:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, a -> b -> a.
Axiom const_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (a1:a) (b1:b), ((const a1 b1) = a1).
Parameter constant_f:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a -> b) ->
Prop.
Axiom constant_f_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b),
(constant_f f) <->
exists a1:b, (f = ((fun (y0:b) (y1:a) => (const y0 y1)) a1)).
Axiom iterate_empty :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1), (is_empty s) ->
(commut op1) -> (iterable op1) -> ((iterate op1 s t1) = (neutral_elt op1)).
Axiom iterate_one :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1),
((cardinal s) = 1%Z) -> (commut op1) ->
((iterate op1 s t1) = (t1 (choose s))).
Axiom iterate_add :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (f:a -> im1) (x:a),
(commut op1) -> (iterable op1) -> ~ (mem x s) ->
((iterate op1 (add x s) f) = ((op1 (f x)) (iterate op1 s f))).
Axiom iterate_add_ :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (f:a -> im1) (x:a),
(commut op1) -> ~ (mem x s) -> ~ (is_empty s) ->
((iterate op1 (add x s) f) = ((op1 (f x)) (iterate op1 s f))).
Axiom iterate_remove :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (f:a -> im1) (x:a),
(commut op1) -> (iterable op1) ->
(inverse_tuple op1 (fun (y0:im1) (y1:im1) => (po y0 y1)) (neutral_elt op1)) ->
(mem x s) -> ((iterate op1 (remove x s) f) = (po (iterate op1 s f) (f x))).
Axiom iterate_def_choose :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (f:a -> im1),
(((cardinal s) = 1%Z) -> iterable op1) -> (commut op1) -> ~ (is_empty s) ->
((iterate op1 s f) =
((op1 (f (choose s))) (iterate op1 (remove (choose s) s) f))).
Axiom choose_any :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (f:a -> im1) (t1:a),
(iterable op1) -> (commut op1) -> (mem t1 s) ->
((iterate op1 s f) = ((op1 (f t1)) (iterate op1 (remove t1 s) f))).
Axiom iterate_comp_iterate :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s1:set a) (f:a -> im1) (g:a -> im1),
(iterable op1) -> (commut op1) -> (assoc op1) ->
((iterate op1 s1 (fun (k:a) => ((op1 (f k)) (g k)))) =
((op1 (iterate op1 s1 (fun (k:a) => (f k))))
(iterate op1 s1 (fun (k:a) => (g k))))).
Axiom iterate_comp_iterate_com :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s1:set a) (f:a -> im1) (g:a -> im1),
(iterable op1) -> (commut op1) ->
(((op1 (iterate op1 s1 (fun (k:a) => (f k))))
(iterate op1 s1 (fun (k:a) => (g k))))
= (iterate op1 s1 (fun (k:a) => ((op1 (f k)) (g k))))).
Axiom iterate_transitivity :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (po1:im1 -> im1 -> im1) (s1:set a)
(s2:set a) (f:a -> im1),
(iterable op1) -> (commut op1) ->
(inverse_tuple op1 po1 (neutral_elt op1)) ->
((iterate op1 (union s1 s2) f) =
((po1 ((op1 (iterate op1 s1 f)) (iterate op1 s2 f)))
(iterate op1 (inter s1 s2) f))).
Axiom iterate_disjoint_transitivity :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s1:set a) (s2:set a) (t1:a -> im1),
(iterable op1) -> (commut op1) -> ((inter s1 s2) = (empty : set a)) ->
((iterate op1 (union s1 s2) t1) =
((op1 (iterate op1 s1 t1)) (iterate op1 s2 t1))).
Axiom iterate_eq :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (f:a -> im1) (g:a -> im1),
(forall (x:a), (mem x s) -> ((f x) = (g x))) -> (commut op1) ->
((is_empty s) -> iterable op1) -> ((iterate op1 s f) = (iterate op1 s g)).
Axiom iterate_map :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}
{im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set b) (f:b -> a) (t1:a -> im1),
((is_empty s) -> iterable op1) -> (commut op1) -> (p_injective f s) ->
((iterate op1 (map f s) t1) = (iterate op1 s (fun (b1:b) => (t1 (f b1))))).
Axiom iterate_cardone :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1), (iterable op1) ->
(commut op1) -> ((cardinal s) = 1%Z) ->
((iterate op1 s t1) = (t1 (element s))).
Axiom iterate_cardzero :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1), (commut op1) ->
(iterable op1) -> ((cardinal s) = 0%Z) ->
((iterate op1 s t1) = (neutral_elt op1)).
Axiom injec_iterate :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}
{im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (a1:a) (s:set b) (f:a -> b -> im1),
(iterable op1) -> (commut op1) ->
((iterate op1 s (f a1)) =
(iterate op1 (cartesian_product (to_set a1) s)
(fun (o:(a* b)%type) => ((f (fir o)) (sec o))))).
Axiom iterate_cartesian_product :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}
{im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s1:set a) (s2:set b) (f:a -> b -> im1),
(iterable op1) -> (commut op1) ->
((iterate op1 s1 (fun (a1:a) => (iterate op1 s2 (f a1)))) =
(iterate op1 (cartesian_product s1 s2)
(fun (o:(a* b)%type) => ((f (fir o)) (sec o))))).
Axiom iterate_eq_func :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (f1:a -> im1) (f2:a -> im1),
(commut op1) -> (iterable op1) -> (p_injective f1 s) ->
(p_injective f2 s) -> ((map f1 s) = (map f2 s)) ->
((iterate op1 s f1) = (iterate op1 s f2)).
Axiom int_iterate_def_empty :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (i:Z) (j:Z), (j <= i)%Z ->
(iterable op1) -> ((int_iterate op1 f i j) = (neutral_elt op1)).
Axiom int_iterate_def_plus_one :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (i:Z) (j:Z), (i < j)%Z ->
(((i + 1%Z)%Z = j) -> iterable op1) ->
((int_iterate op1 f i j) = ((op1 (f i)) (int_iterate op1 f (i + 1%Z)%Z j))).
Axiom int_iterate_cardone :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (i:Z) (j:Z),
(j = (i + 1%Z)%Z) -> ((int_iterate op1 f i j) = (f i)).
Axiom int_iterate_def_plus_one_com :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (i:Z) (j:Z), (i < j)%Z ->
((j = (i + 1%Z)%Z) -> iterable op1) ->
(((op1 (f i)) (int_iterate op1 f (i + 1%Z)%Z j)) = (int_iterate op1 f i j)).
Axiom int_iterate_to_iterate :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (i:Z) (j:Z),
((j <= i)%Z -> iterable op1) -> (commut op1) ->
((int_iterate op1 f i j) = (iterate op1 (to_fset i j) f)).
Axiom int_iterate_right_extension :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (i:Z) (j:Z), (iterable op1) ->
(i < j)%Z ->
((int_iterate op1 f i j) =
((op1 (int_iterate op1 f i (j - 1%Z)%Z)) (f (j - 1%Z)%Z))).
Axiom int_iterate_right_extension_ :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (i:Z) (j:Z), (assoc op1) ->
((i + 1%Z)%Z < j)%Z ->
((int_iterate op1 f i j) =
((op1 (int_iterate op1 f i (j - 1%Z)%Z)) (f (j - 1%Z)%Z))).
Axiom int_iterate_transitivity :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (i:Z) (k:Z) (j:Z),
(iterable op1) -> (iterable op1) ->
(op_neutral_left op1 (neutral_elt op1)) -> ((i <= k)%Z /\ (k <= j)%Z) ->
((int_iterate op1 f i j) =
((op1 (int_iterate op1 f i k)) (int_iterate op1 f k j))).
Axiom int_iterate_transitivity_ :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (i:Z) (k:Z) (j:Z),
(op_neutral_left op1 (neutral_elt op1)) -> ((i < k)%Z /\ (k < j)%Z) ->
((int_iterate op1 f i j) =
((op1 (int_iterate op1 f i k)) (int_iterate op1 f k j))).
Axiom int_iterate_comp_iterate :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (g:Z -> im1) (i:Z) (j:Z),
(iterable op1) -> (op_neutral_right op1 (neutral_elt op1)) ->
(commut op1) ->
((int_iterate op1 (fun (k:Z) => ((op1 (f k)) (g k))) i j) =
((op1 (int_iterate op1 f i j)) (int_iterate op1 g i j))).
Axiom int_iterate_attr_no_f :
forall {im1:Type} {im1_WT:WhyType im1} {im2:Type} {im2_WT:WhyType im2},
forall (op1:im1 -> im1 -> im1) (op2:im2 -> im2 -> im2) (t1:Z -> im1)
(t2:Z -> im2) (f:im1 -> im2) (i:Z) (j:Z),
(forall (x:Z), forall (y:im1),
(((op2 (t2 x)) (f y)) = (f ((op1 (t1 x)) y)))) ->
((f (neutral_elt op1)) = (neutral_elt op2)) -> (iterable op1) ->
(iterable op2) -> (forall (i1:Z), ((f (t1 i1)) = (t2 i1))) ->
((int_iterate op2 t2 i j) = (f (int_iterate op1 t1 i j))).
Axiom int_iterate_attr :
forall {im1:Type} {im1_WT:WhyType im1} {im2:Type} {im2_WT:WhyType im2},
forall (op1:im1 -> im1 -> im1) (op2:im2 -> im2 -> im2) (t1:Z -> im1)
(f:im1 -> im2) (i:Z) (j:Z),
(forall (x:Z), forall (y:im1),
(((op2 (f (t1 x))) (f y)) = (f ((op1 (t1 x)) y)))) ->
((f (neutral_elt op1)) = (neutral_elt op2)) -> (iterable op1) ->
(iterable op2) ->
((int_iterate op2 (fun (e:Z) => (f (t1 e))) i j) =
(f (int_iterate op1 t1 i j))).
Axiom int_iterate_attr_comm :
forall {im1:Type} {im1_WT:WhyType im1} {im2:Type} {im2_WT:WhyType im2},
forall (op1:im1 -> im1 -> im1) (op2:im2 -> im2 -> im2) (t1:Z -> im1)
(f:im1 -> im2) (i:Z) (j:Z),
(forall (x:Z), forall (y:im1),
(((op2 (f (t1 x))) (f y)) = (f ((op1 (t1 x)) y)))) ->
((f (neutral_elt op1)) = (neutral_elt op2)) -> (iterable op1) ->
(iterable op2) ->
((f (int_iterate op1 t1 i j)) =
(int_iterate op2 (fun (e:Z) => (f (t1 e))) i j)).
Axiom int_iterate_eq :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (g:Z -> im1) (i:Z) (j:Z),
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((j <= i)%Z -> iterable op1) ->
((int_iterate op1 f i j) = (int_iterate op1 g i j)).
Axiom int_iterate_left_right :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (l:Z) (k:Z) (h:Z),
(iterable op1) -> (commut op1) -> ((l <= k)%Z /\ (k <= h)%Z) ->
((int_iterate op1 f l k) =
(int_iterate op1 (fun (a:Z) => (f ((h - (a + 1%Z)%Z)%Z + l)%Z))
((h - k)%Z + l)%Z h)).
Axiom int_iterate_eq_func :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (i:Z) (j:Z) (f:Z -> im1) (g:Z -> im1),
(iterable op1) -> (commut op1) -> (p_injective f (to_fset i j)) ->
(p_injective g (to_fset i j)) ->
((map f (to_fset i j)) = (map g (to_fset i j))) ->
((int_iterate op1 f i j) = (int_iterate op1 g i j)).
Axiom int_iterate_map :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (i:Z) (j:Z) (k:Z) (l:Z) (f:Z -> Z)
(t1:Z -> im1),
((j <= i)%Z -> iterable op1) -> (commut op1) ->
(p_bijective f (to_fset i j) (to_fset k l)) ->
((int_iterate op1 t1 k l) =
(int_iterate op1 (fun (b:Z) => (t1 (f b))) i j)).
Axiom int_iterate_transl :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> im1) (i:Z) (j:Z) (k:Z),
(iterable op1) ->
((int_iterate op1 f i j) =
(int_iterate op1 (fun (b:Z) => (f (b + k)%Z)) (i - k)%Z (j - k)%Z)).
Axiom int_iterate_map_auto :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (i:Z) (j:Z) (f:Z -> Z) (t1:Z -> im1),
((j <= i)%Z -> iterable op1) -> (commut op1) ->
(p_bijective f (to_fset i j) (to_fset i j)) ->
((int_iterate op1 t1 i j) =
(int_iterate op1 (fun (b:Z) => (t1 (f b))) i j)).
Parameter nonn_part:
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
(im1 -> im1 -> im1) -> (set a) -> (a -> im1) -> set a.
Parameter result2:
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
(im1 -> im1 -> im1) -> (a -> im1) -> a -> bool.
Axiom result_def2 :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (t1:a -> im1) (e:a),
(((result2 op1 t1) e) = true) <-> ~ (neutral op1 (t1 e)).
Axiom nonn_part_def :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1),
((nonn_part op1 s t1) = (filter (result2 op1 t1) s)).
Axiom nonn_part_spec :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1), forall (e:a),
(mem e (nonn_part op1 s t1)) <-> ((mem e s) /\ ~ (neutral op1 (t1 e))).
Parameter n_part:
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
(im1 -> im1 -> im1) -> (set a) -> (a -> im1) -> set a.
Parameter result3:
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
(im1 -> im1 -> im1) -> (a -> im1) -> a -> bool.
Axiom result_def3 :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (t1:a -> im1) (e:a),
(((result3 op1 t1) e) = true) <-> (neutral op1 (t1 e)).
Axiom n_part_def :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1),
((n_part op1 s t1) = (filter (result3 op1 t1) s)).
Axiom n_part_spec :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1), forall (e:a),
(mem e (n_part op1 s t1)) <-> ((mem e s) /\ (neutral op1 (t1 e))).
Axiom nullity_partition :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1), (commut op1) ->
(s = (union (nonn_part op1 s t1) (n_part op1 s t1))) /\
((inter (nonn_part op1 s t1) (n_part op1 s t1)) = (empty : set a)).
Axiom iterate_neutral :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1), (iterable op1) ->
(commut op1) ->
(forall (a1:a), (mem a1 s) -> ((t1 a1) = (neutral_elt op1))) ->
((iterate op1 s t1) = (neutral_elt op1)).
Axiom iterate_nullity_partition :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1), (iterable op1) ->
(commut op1) ->
((iterate op1 s t1) = (iterate op1 (nonn_part op1 s t1) t1)).
Parameter couple:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}
{im1:Type} {im1_WT:WhyType im1},
(a -> b -> im1) -> (a* b)%type -> im1.
Axiom couple_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}
{im1:Type} {im1_WT:WhyType im1},
forall (f:a -> b -> im1) (o:(a* b)%type),
match o with
| (a1, b1) => ((couple f o) = ((f a1) b1))
end.
Axiom null_product :
forall (a:t) (b:t), ((infix_asdt a b) = tzero) ->
(a = tzero) \/ (b = tzero).
Axiom couple_value :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}
{im1:Type} {im1_WT:WhyType im1},
forall (f:a -> b -> im1) (o:(a* b)%type),
((couple f o) = ((f (fir o)) (sec o))).
Axiom couple_value_dev :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}
{im1:Type} {im1_WT:WhyType im1},
forall (f:a -> b -> im1) (o:(a* b)%type) (a1:a) (b1:b), (o = (a1, b1)) ->
((couple f o) = ((f a1) b1)).
Axiom neutral_tzero :
(neutral (fun (y0:t) (y1:t) => (infix_pldt y0 y1)) tzero) /\
(iterable (fun (y0:t) (y1:t) => (infix_pldt y0 y1))).
Parameter sum: forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> t) -> t.
Axiom sum_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t),
((sum s t1) = (iterate (fun (y0:t) (y1:t) => (infix_pldt y0 y1)) s t1)).
Parameter eq_t: t -> t -> Prop.
Axiom eq_t_def : forall (a:t) (a':t), (eq_t a a') <-> (a = a').
Axiom sum_empty :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t), (is_empty s) -> ((sum s t1) = tzero).
Axiom sum_one :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t), ((cardinal s) = 1%Z) ->
((sum s t1) = (t1 (choose s))).
Axiom sum_add :
forall {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> t) (x:b), ~ (mem x s) ->
((sum (add x s) f) = (infix_pldt (f x) (sum s f))).
Axiom sum_plus_one :
forall {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> t), ((cardinal s) > 1%Z)%Z ->
((sum s f) = (infix_pldt (f (choose s)) (sum (remove (choose s) s) f))).
Axiom sum_real :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> t), (forall (a1:a), (mem a1 s) -> real_ (f a1)) ->
((cardinal s) > 0%Z)%Z -> real_ (sum s f).
Axiom map_sum_eq :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> a) (t1:a -> t), (p_injective f s) ->
((sum (map f s) t1) = (sum s (fun (b1:b) => (t1 (f b1))))).
Axiom sum_comp :
forall {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> t) (g:b -> t),
((sum s (fun (k:b) => (infix_pldt (f k) (g k)))) =
(infix_pldt (sum s f) (sum s g))).
Axiom sum_iter_ :
(opposite_n (fun (y0:t) (y1:t) => (infix_pldt y0 y1))
(fun (y0:t) (y1:t) => (infix_mndt y0 y1)) tzero) /\
((opposite1 (fun (y0:t) (y1:t) => (infix_pldt y0 y1))
(fun (y0:t) (y1:t) => (infix_mndt y0 y1))) /\
((opposite_com (fun (y0:t) (y1:t) => (infix_pldt y0 y1))
(fun (y0:t) (y1:t) => (infix_mndt y0 y1))) /\
(inverse_tuple (fun (y0:t) (y1:t) => (infix_pldt y0 y1))
(fun (y0:t) (y1:t) => (infix_mndt y0 y1)) tzero))).
Axiom neutral_zero :
((neutral_elt (fun (y0:t) (y1:t) => (infix_pldt y0 y1))) = tzero).
Axiom sum_eq :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> t) (g:a -> t),
(forall (x:a), (mem x s) -> ((f x) = (g x))) -> ((sum s f) = (sum s g)).
Axiom sum_eq_gen :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (f:a -> t) (g:a -> t), (s = s') ->
(forall (x:a), (mem x s) -> ((f x) = (g x))) -> ((sum s f) = (sum s' g)).
Axiom sum_disjoint_transitivity :
forall {a:Type} {a_WT:WhyType a},
forall (s1:set a) (s2:set a) (t1:a -> t),
((inter s1 s2) = (empty : set a)) ->
((sum (union s1 s2) t1) = (infix_pldt (sum s1 t1) (sum s2 t1))).
Axiom sum_to_cartesian_product :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set b) (f:a -> b -> t),
((sum s1 (fun (a1:a) => (sum s2 (f a1)))) =
(sum (cartesian_product s1 s2)
(fun (o:(a* b)%type) => ((f (fir o)) (sec o))))).
Axiom sum_from_cartesian_product :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set b) (f:a -> b -> t),
((sum (cartesian_product s1 s2)
(fun (o:(a* b)%type) => ((f (fir o)) (sec o))))
= (sum s1 (fun (a1:a) => (sum s2 (f a1))))).
Parameter ind_sum: (Z -> t) -> Z -> Z -> t.
Axiom ind_sum_def :
forall (f:Z -> t) (i:Z) (j:Z),
((ind_sum f i j) =
(int_iterate (fun (y0:t) (y1:t) => (infix_pldt y0 y1)) f i j)).
Axiom ind_sum_to_int_iterate :
forall (f:Z -> t) (i:Z) (j:Z),
((ind_sum f i j) =
(int_iterate (fun (y0:t) (y1:t) => (infix_pldt y0 y1)) f i j)).
Axiom ind_sum_cardone :
forall (f:Z -> t) (i:Z) (j:Z), (j = (i + 1%Z)%Z) ->
((ind_sum f i j) = (f i)).
Axiom ind_sum_right_extension :
forall (f:Z -> t) (i:Z) (j:Z), (i < j)%Z ->
((ind_sum f i j) = (infix_pldt (ind_sum f i (j - 1%Z)%Z) (f (j - 1%Z)%Z))).
Axiom ind_sum_plus_one :
forall (f:Z -> t) (i:Z) (j:Z), (i < j)%Z ->
((ind_sum f i j) = (infix_pldt (f i) (ind_sum f (i + 1%Z)%Z j))).
Axiom real_ind_sum :
forall (f:Z -> t) (i:Z) (j:Z), (i < j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> real_ (f k)) ->
real_ (ind_sum f i j).
Axiom positive_ind_sum :
forall (f:Z -> t) (i:Z) (j:Z), (i < j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> infix_lseqdt tzero (f k)) ->
infix_lseqdt tzero (ind_sum f i j).
Axiom ind_sum_eq :
forall (f:Z -> t) (g:Z -> t) (i:Z) (j:Z),
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((ind_sum f i j) = (ind_sum g i j)).
Parameter fc: (Z -> t) -> t -> Z -> Z -> Z -> t.
Axiom fc_def :
forall (f:Z -> t) (g:t) (i:Z) (j:Z) (k:Z),
(((i <= k)%Z /\ (k < j)%Z) -> (((fc f g i j) k) = (f k))) /\
(~ ((i <= k)%Z /\ (k < j)%Z) -> (((fc f g i j) k) = g)).
Axiom ind_sum_eq_del_bound :
forall (f:Z -> t) (g:t) (i:Z) (j:Z),
((ind_sum (fc f g i j) i j) = (ind_sum f i j)).
Parameter fc1: (Z -> t) -> t -> Z -> Z -> Z -> t.
Axiom fc_def1 :
forall (f:Z -> t) (g:t) (i:Z) (j:Z) (k:Z),
(((i <= k)%Z /\ (k < j)%Z) -> (((fc1 f g i j) k) = (f k))) /\
(~ ((i <= k)%Z /\ (k < j)%Z) -> (((fc1 f g i j) k) = g)).
Axiom ind_sum_eq_del_bound_rev :
forall (f:Z -> t) (g:t) (i:Z) (j:Z),
((ind_sum f i j) = (ind_sum (fc1 f g i j) i j)).
Axiom ind_sum_eq_gen :
forall (f:Z -> t) (g:Z -> t) (i1:Z) (j1:Z) (i2:Z) (j2:Z), (i1 = i2) ->
(j1 = j2) ->
(forall (k:Z), ((i1 <= k)%Z /\ (k < j1)%Z) -> ((f k) = (g k))) ->
((ind_sum f i1 j1) = (ind_sum g i2 j2)).
Axiom ind_sum_eq_bound :
forall (f:Z -> t) (g:Z -> t) (i:Z) (j:Z), (i = j) ->
(forall (k:Z), ((0%Z <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((ind_sum f 0%Z i) = (ind_sum g 0%Z j)).
Axiom ind_sum_comp :
forall (f:Z -> t) (g:Z -> t) (i:Z) (j:Z),
((ind_sum (fun (k:Z) => (infix_pldt (f k) (g k))) i j) =
(infix_pldt (ind_sum f i j) (ind_sum g i j))).
Axiom ind_sum_comp_rev :
forall (f:Z -> t) (g:Z -> t) (i:Z) (i':Z) (j:Z) (j':Z), (i = i') ->
(j = j') ->
((infix_pldt (ind_sum f i j) (ind_sum g i' j')) =
(ind_sum (fun (k:Z) => (infix_pldt (f k) (g k))) i j)).
Axiom ind_sum_to_iterate :
forall (f:Z -> t) (i:Z) (j:Z),
((ind_sum f i j) =
(iterate (fun (y0:t) (y1:t) => (infix_pldt y0 y1)) (to_fset i j) f)).
Axiom ind_sum_to_sum :
forall (f:Z -> t) (i:Z) (j:Z), ((ind_sum f i j) = (sum (to_fset i j) f)).
Axiom map_ind_sum_eq :
forall (i:Z) (j:Z) (k:Z) (l:Z) (f:Z -> Z) (t1:Z -> t),
(p_bijective f (to_fset i j) (to_fset k l)) ->
((ind_sum t1 k l) = (ind_sum (fun (b:Z) => (t1 (f b))) i j)).
Axiom sum_scal :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> t) (s:set a) (c:t),
((sum s (fun (x:a) => (infix_asdt c (f x)))) = (infix_asdt c (sum s f))).
Axiom sum_scal_right :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> t) (s:set a) (c:t),
((sum s (fun (x:a) => (infix_asdt (f x) c))) = (infix_asdt (sum s f) c)).
Axiom sum_scal_rev_right :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> t) (s:set a) (c:t),
((infix_asdt (sum s f) c) = (sum s (fun (x:a) => (infix_asdt (f x) c)))).
Axiom sum_scal_rev :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> t) (s:set a) (c:t),
((infix_asdt c (sum s f)) = (sum s (fun (x:a) => (infix_asdt c (f x))))).
Axiom ind_sum_scal :
forall (f:Z -> t) (i:Z) (j:Z) (a:t),
((ind_sum (fun (i1:Z) => (infix_asdt a (f i1))) i j) =
(infix_asdt a (ind_sum f i j))).
Axiom ind_sum_scal_rev :
forall (f:Z -> t) (i:Z) (j:Z) (a:t),
((infix_asdt a (ind_sum f i j)) =
(ind_sum (fun (i1:Z) => (infix_asdt a (f i1))) i j)).
Axiom scal_ind_sum :
forall (f:Z -> t) (i:Z) (j:Z) (a:t),
((ind_sum (fun (i1:Z) => (infix_asdt (f i1) a)) i j) =
(infix_asdt (ind_sum f i j) a)).
Axiom scal_ind_sum_rev :
forall (f:Z -> t) (i:Z) (j:Z) (a:t),
((infix_asdt (ind_sum f i j) a) =
(ind_sum (fun (i1:Z) => (infix_asdt (f i1) a)) i j)).
Axiom sum_scal_gen :
forall (f:Z -> t) (s:set Z), forall (a:t),
((sum s (fun (i:Z) => (infix_asdt a (f i)))) = (infix_asdt a (sum s f))).
Axiom ind_sum_scal_gen :
forall (f:Z -> t) (i:Z) (j:Z), forall (a:t),
((ind_sum (fun (i1:Z) => (infix_asdt a (f i1))) i j) =
(infix_asdt a (ind_sum f i j))).
Axiom int_int_iterate_def_empty :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> Z -> im1) (i:Z) (j:Z) (k:Z) (l:Z),
(j <= i)%Z -> (iterable op1) ->
((int_int_iterate op1 f i j k l) = (neutral_elt op1)).
Axiom int_int_iterate_def_plus_one :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> Z -> im1) (i:Z) (j:Z) (k:Z) (l:Z),
(i < j)%Z -> (iterable op1) ->
((int_int_iterate op1 f i j k l) =
((op1 (int_iterate op1 (fun (n:Z) => ((f i) n)) k l))
(int_int_iterate op1 f (i + 1%Z)%Z j k l))).
Axiom int_int_iterate_to_int_iterate :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> Z -> im1) (i:Z) (j:Z) (k:Z) (l:Z),
(i <= j)%Z -> (iterable op1) ->
((int_int_iterate op1 f i j k l) =
(int_iterate op1 (fun (a:Z) => (int_iterate op1 (f a) k l)) i j)).
Axiom int_iterate_to_int_int_iterate :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> Z -> im1) (i:Z) (j:Z) (k:Z) (l:Z),
(i <= j)%Z -> (iterable op1) ->
((int_iterate op1 (fun (a:Z) => (int_iterate op1 (f a) k l)) i j) =
(int_int_iterate op1 f i j k l)).
Axiom int_int_iterate_to_iterate :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> Z -> im1) (i:Z) (j:Z) (k:Z) (l:Z),
(i <= j)%Z -> (iterable op1) -> (commut op1) ->
((int_int_iterate op1 f i j k l) =
(iterate op1 (cartesian_product (to_fset i j) (to_fset k l))
(fun (o:(Z* Z)%type) => ((f (fir o)) (sec o))))).
Axiom iterate_commute :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}
{im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s1:set a) (s2:set b) (f:a -> b -> im1),
(iterable op1) -> (commut op1) ->
((iterate op1 (cartesian_product s1 s2)
(fun (o:(a* b)%type) => ((f (fir o)) (sec o))))
=
(iterate op1 (cartesian_product s2 s1)
(fun (o:(b* a)%type) => ((f (sec o)) (fir o))))).
Axiom iterate_commute_ :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}
{im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s1:set a) (s2:set b) (f:a -> b -> im1),
(iterable op1) -> (commut op1) ->
((iterate op1 s1
(fun (a1:a) => (iterate op1 s2 (fun (a2:b) => ((f a1) a2)))))
=
(iterate op1 s2
(fun (a2:b) => (iterate op1 s1 (fun (a1:a) => ((f a1) a2)))))).
Axiom int_int_iterate_commute :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> Z -> im1) (i:Z) (j:Z) (k:Z) (l:Z),
(iterable op1) -> (commut op1) -> (i <= j)%Z -> (k <= l)%Z ->
((int_int_iterate op1 f i j k l) =
(int_int_iterate op1 (fun (a:Z) (b:Z) => ((f b) a)) k l i j)).
Axiom int_iterate_commute :
forall {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (f:Z -> Z -> im1) (i:Z) (j:Z) (k:Z) (l:Z),
(iterable op1) -> (commut op1) -> (i <= j)%Z -> (k <= l)%Z ->
((int_iterate op1 (fun (a:Z) => (int_iterate op1 (f a) k l)) i j) =
(int_iterate op1
(fun (a:Z) => (int_iterate op1 (fun (b:Z) => ((f b) a)) i j)) k l)).
Axiom ind_sum_commute :
forall (f:Z -> Z -> t) (i:Z) (j:Z) (k:Z) (l:Z), (i <= j)%Z -> (k <= l)%Z ->
((ind_sum (fun (k1:Z) => (ind_sum (f k1) k l)) i j) =
(ind_sum (fun (k1:Z) => (ind_sum (fun (k2:Z) => ((f k2) k1)) i j)) k l)).
Axiom sum_commute :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b -> t) (sa:set a) (sb:set b),
((sum sa (fun (a1:a) => (sum sb (f a1)))) =
(sum sb (fun (b1:b) => (sum sa (fun (a1:a) => ((f a1) b1)))))).
Parameter non_tzero:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> t) -> set a.
Axiom non_tzero_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t),
((non_tzero s t1) =
(nonn_part (fun (y0:t) (y1:t) => (infix_pldt y0 y1)) s t1)).
Axiom non_tzero_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t), forall (e:a),
(mem e (non_tzero s t1)) <-> ((mem e s) /\ ~ ((t1 e) = tzero)).
Axiom get_non_tzero_member :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t) (e:a), (mem e (non_tzero s t1)) ->
(mem e s) /\ ~ ((t1 e) = tzero).
Axiom set_non_tzero_member :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t) (e:a), (mem e s) -> ~ ((t1 e) = tzero) ->
mem e (non_tzero s t1).
Axiom set_non_tzero_member_gen :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t), forall (e:a),
((mem e s) /\ ~ ((t1 e) = tzero)) -> mem e (non_tzero s t1).
Axiom set_non_tzero_member_gen_ :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t), forall (e:a),
((mem e s) /\ ~ ((t1 e) = tzero)) -> mem e (non_tzero s t1).
Axiom sum_nullity_partition :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t), ((sum s t1) = (sum (non_tzero s t1) t1)).
Axiom non_null_map :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> a) (t1:a -> t),
((non_tzero (map f s) t1) =
(map f (non_tzero s (fun (b:a) => (t1 (f b)))))).
Axiom map_sum_eq_nonnull :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> a) (t1:a -> t),
(p_bijective f (non_tzero s (fun (b:a) => (t1 (f b))))
(non_tzero (map f s) t1)) ->
((sum (non_tzero (map f s) t1) t1) =
(sum (non_tzero s (fun (b:a) => (t1 (f b)))) (fun (b:a) => (t1 (f b))))).
Axiom sum_null_but_one :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t), ((cardinal (non_tzero s t1)) = 1%Z) ->
((sum s t1) = (t1 (element (non_tzero s t1)))).
Axiom sum_null :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t), ((cardinal (non_tzero s t1)) = 0%Z) ->
((sum s t1) = tzero).
Axiom sum_null_ :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t),
(forall (e:a), (mem e s) -> ((t1 e) = tzero)) -> ((sum s t1) = tzero).
Axiom sum_null_forall :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t),
(forall (e:a), (mem e s) -> ((t1 e) = tzero)) -> ((sum s t1) = tzero).
Axiom ind_sum_null :
forall (t1:Z -> t) (i:Z) (j:Z),
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((t1 k) = tzero)) ->
((ind_sum t1 i j) = tzero).
Axiom sum_null_but_one_elt :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t) (elt:a),
((mem elt s) /\ ~ ((t1 elt) = tzero)) ->
(forall (a1:a), (mem a1 s) -> ~ (a1 = elt) -> ((t1 a1) = tzero)) ->
((sum s t1) = (t1 elt)).
Axiom sum_null_but_maybe_one_elt :
forall {a:Type} {a_WT:WhyType a},
forall (t1:a -> t) (s:set a) (elt:a), (mem elt s) ->
(forall (k:a), (mem k s) -> ~ (k = elt) -> ((t1 k) = tzero)) ->
((sum s t1) = (t1 elt)).
Axiom ind_sum_null_but_maybe_one_elt :
forall (t1:Z -> t) (i:Z) (j:Z) (ind:Z), ((i <= ind)%Z /\ (ind < j)%Z) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ~ (k = ind) ->
((t1 k) = tzero)) ->
((ind_sum t1 i j) = (t1 ind)).
Axiom neutral_tone :
(neutral (fun (y0:t) (y1:t) => (infix_asdt y0 y1)) tone) /\
(iterable (fun (y0:t) (y1:t) => (infix_asdt y0 y1))).
Axiom product_iter :
(op_neutral_left (fun (y0:t) (y1:t) => (infix_asdt y0 y1)) tone) /\
(((op_neutral_right (fun (y0:t) (y1:t) => (infix_asdt y0 y1)) tone) /\
(op_assoc (fun (y0:t) (y1:t) => (infix_asdt y0 y1)))) /\
((commut (fun (y0:t) (y1:t) => (infix_asdt y0 y1))) /\
(iterates (fun (y0:t) (y1:t) => (infix_asdt y0 y1)) tone))).
Parameter product:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> t) -> t.
Axiom product_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t),
((product s t1) = (iterate (fun (y0:t) (y1:t) => (infix_asdt y0 y1)) s t1)).
Axiom product_eq :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t) (t':a -> t),
(forall (e:a), (mem e s) -> ((t1 e) = (t' e))) ->
((product s t1) = (product s t')).
Axiom product_eq_gen :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (t1:a -> t) (t':a -> t), (s = s') ->
(forall (e:a), (mem e s) -> ((t1 e) = (t' e))) ->
((product s t1) = (product s' t')).
Axiom product_empty :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> t), (is_empty s) -> ((product s f) = tone).
Axiom product_iter_ : iterable (fun (y0:t) (y1:t) => (infix_asdt y0 y1)).
Axiom add_product :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> t) (x:a), ~ (mem x s) ->
((product (add x s) f) = (infix_asdt (f x) (product s f))).
Axiom product_add :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> t) (x:a), ~ (mem x s) ->
((product (add x s) f) = (infix_asdt (product s f) (f x))).
Axiom neutral_one :
((neutral_elt (fun (y0:t) (y1:t) => (infix_asdt y0 y1))) = tone).
Parameter ind_product: (Z -> t) -> Z -> Z -> t.
Axiom ind_product_def :
forall (f:Z -> t) (i:Z) (j:Z),
((ind_product f i j) =
(int_iterate (fun (y0:t) (y1:t) => (infix_asdt y0 y1)) f i j)).
Axiom ind_product_eq :
forall (f:Z -> t) (g:Z -> t) (i:Z) (j:Z),
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((ind_product f i j) = (ind_product g i j)).
Axiom ind_product_cardone :
forall (f:Z -> t) (i:Z) (j:Z), (j = (i + 1%Z)%Z) ->
((ind_product f i j) = (f i)).
Axiom ind_product_eq_gen :
forall (f:Z -> t) (g:Z -> t) (i1:Z) (j1:Z) (i2:Z) (j2:Z),
(forall (k:Z), ((i1 <= k)%Z /\ (k < j1)%Z) -> ((f k) = (g k))) ->
(i1 = i2) -> (j1 = j2) -> ((ind_product f i1 j1) = (ind_product g i2 j2)).
Axiom ind_product_right_extension :
forall (f:Z -> t) (i:Z) (j:Z), (i < j)%Z ->
((ind_product f i j) =
(infix_asdt (ind_product f i (j - 1%Z)%Z) (f (j - 1%Z)%Z))).
Axiom ind_product_left_extension :
forall (f:Z -> t) (i:Z) (j:Z), (i < j)%Z ->
((ind_product f i j) = (infix_asdt (f i) (ind_product f (i + 1%Z)%Z j))).
Axiom ind_product_to_product :
forall (f:Z -> t) (i:Z) (j:Z),
((ind_product f i j) = (product (to_fset i j) f)).
Axiom map_product_eq :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> a) (t1:a -> t), (p_injective f s) ->
((product (map f s) t1) = (product s (fun (b1:b) => (t1 (f b1))))).
Axiom map_ind_product_eq :
forall (i:Z) (j:Z) (k:Z) (l:Z) (f:Z -> Z) (t1:Z -> t),
(p_bijective f (to_fset i j) (to_fset k l)) ->
((ind_product t1 k l) = (ind_product (fun (b:Z) => (t1 (f b))) i j)).
Axiom ind_product_right_extension_comm :
forall (f:Z -> t) (i:Z) (j:Z), (i < j)%Z ->
((infix_asdt (ind_product f i (j - 1%Z)%Z) (f (j - 1%Z)%Z)) =
(ind_product f i j)).
Axiom ind_product_eq_func :
forall (i:Z) (j:Z) (f1:Z -> t) (f2:Z -> t),
(p_injective f1 (to_fset i j)) -> (p_injective f2 (to_fset i j)) ->
((map f1 (to_fset i j)) = (map f2 (to_fset i j))) ->
((ind_product f1 i j) = (ind_product f2 i j)).
Axiom ind_product_trans :
forall (f:Z -> t) (i:Z) (k:Z) (j:Z), ((i <= k)%Z /\ (k <= j)%Z) ->
((ind_product f i j) =
(infix_asdt (ind_product f i k) (ind_product f k j))).
Axiom ind_product_zero_pre :
forall (f:Z -> t) (i:Z) (t1:Z) (j:Z), ((i <= t1)%Z /\ (t1 < j)%Z) ->
((f t1) = tzero) -> ((ind_product f i j) = tzero).
Axiom ind_product_zero :
forall (f:Z -> t) (i:Z) (j:Z), (i <= j)%Z ->
(exists t1:Z, ((i <= t1)%Z /\ (t1 < j)%Z) /\ ((f t1) = tzero)) ->
((ind_product f i j) = tzero).
Axiom ind_product_zero_elt :
forall (f:Z -> t) (i:Z) (j:Z) (t1:Z), (i <= j)%Z ->
((i <= t1)%Z /\ (t1 < j)%Z) -> ((f t1) = tzero) ->
((ind_product f i j) = tzero).
Axiom ind_product_const_tone :
forall (f:Z -> t) (i:Z) (j:Z), (i <= j)%Z ->
(forall (t1:Z), ((i <= t1)%Z /\ (t1 < j)%Z) -> ((f t1) = tone)) ->
((ind_product f i j) = tone).
Axiom div_plus_one :
forall (i:Z) (j:Z), (0%Z <= i)%Z -> (0%Z < j)%Z ->
(((int.EuclideanDivision.div i j) * j)%Z <= i)%Z /\
(i < (((int.EuclideanDivision.div i j) + 1%Z)%Z * j)%Z)%Z.
Axiom mod_is_inf :
forall (i:Z) (j:Z), (0%Z < j)%Z -> ((int.EuclideanDivision.mod1 i j) < j)%Z.
Axiom zero_add : forall (a1:Z) (a2:Z), (a1 = 0%Z) -> ((a1 + a2)%Z = a2).
Axiom add_zero : forall (a1:Z) (a2:Z), (a2 = 0%Z) -> ((a1 + a2)%Z = a1).
Axiom one_mult : forall (a1:Z) (a2:Z), (a1 = 1%Z) -> ((a1 * a2)%Z = a2).
Axiom mult_one : forall (a1:Z) (a2:Z), (a2 = 1%Z) -> ((a1 * a2)%Z = a1).
Axiom add_eq :
forall (a1:Z) (a2:Z) (b1:Z) (b2:Z), (a1 = a2) -> (b1 = b2) ->
((a1 + b1)%Z = (a2 + b2)%Z).
Axiom mult_eq :
forall (a1:Z) (a2:Z) (b1:Z) (b2:Z), (a1 = a2) -> (b1 = b2) ->
((a1 * b1)%Z = (a2 * b2)%Z).
Axiom add_eq_inv :
forall (a1:Z) (a2:Z) (b1:Z) (b2:Z), (a1 = a2) -> (b1 = b2) ->
((a1 + b1)%Z = (b2 + a2)%Z).
Axiom mult_eq_inv :
forall (a1:Z) (a2:Z) (b1:Z) (b2:Z), (a1 = a2) -> (b1 = b2) ->
((a1 * b1)%Z = (b2 * a2)%Z).
Axiom bound_eq :
forall (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < j)%Z) ->
(i = (int.EuclideanDivision.mod1 i j)).
Axiom bound_eq_rev :
forall (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < j)%Z) ->
((int.EuclideanDivision.mod1 i j) = i).
Axiom unicity_div_mod :
forall (i:Z) (j:Z) (q:Z) (r:Z), (0%Z < j)%Z -> (i = ((q * j)%Z + r)%Z) ->
((0%Z <= r)%Z /\ (r < j)%Z) ->
(q = (int.EuclideanDivision.div i j)) /\
(r = (int.EuclideanDivision.mod1 i j)).
Axiom unicity_div_gen :
forall (j:Z) (q:Z), (0%Z <= q)%Z -> (0%Z < j)%Z ->
(forall (i:Z), (0%Z <= i)%Z ->
((0%Z <= (i - (q * j)%Z)%Z)%Z /\ ((i - (q * j)%Z)%Z < j)%Z) ->
(q = (int.EuclideanDivision.div i j))) /\
forall (i:Z), (0%Z <= i)%Z ->
((0%Z <= (i - (q * j)%Z)%Z)%Z /\ ((i - (q * j)%Z)%Z < j)%Z) ->
((i - (j * q)%Z)%Z = (int.EuclideanDivision.mod1 i j)).
Axiom bound_mod :
forall (i:Z) (j:Z), (0%Z <= i)%Z -> (0%Z < j)%Z ->
(0%Z <= (int.EuclideanDivision.mod1 i j))%Z /\
((int.EuclideanDivision.mod1 i j) < j)%Z.
Axiom mod_eq :
forall (a:Z) (b:Z) (d:Z), (a = b) ->
((int.EuclideanDivision.mod1 a d) = (int.EuclideanDivision.mod1 b d)).
Axiom e_div_eq :
forall (a:Z) (b:Z) (d:Z), (a = b) ->
((int.EuclideanDivision.div a d) = (int.EuclideanDivision.div b d)).
Axiom decomp :
forall (i:Z) (j:Z), ~ (0%Z = j) ->
(i =
((j * (int.EuclideanDivision.div i j))%Z +
(int.EuclideanDivision.mod1 i j))%Z).
Axiom div_mod_eq :
forall (i:Z) (j:Z) (q:Z), (0%Z <= i)%Z -> (0%Z <= j)%Z -> (0%Z < q)%Z ->
((int.EuclideanDivision.div i q) = (int.EuclideanDivision.div j q)) ->
((int.EuclideanDivision.mod1 i q) = (int.EuclideanDivision.mod1 j q)) ->
(i = j).
Axiom mod_zero :
forall (i:Z) (j:Z), (0%Z <= i)%Z -> (0%Z < j)%Z ->
((int.EuclideanDivision.mod1 i j) = 0%Z) ->
(i = (j * (int.EuclideanDivision.div i j))%Z).
Axiom div_plus_quotient :
forall (i:Z) (j:Z), (0%Z <= i)%Z -> (0%Z < j)%Z ->
((int.EuclideanDivision.div (i + j)%Z j) =
((int.EuclideanDivision.div i j) + 1%Z)%Z).
Axiom div_plus_fact_gen_div :
forall (i:Z) (j:Z) (k:Z), (0%Z < j)%Z ->
((int.EuclideanDivision.div (i + (k * j)%Z)%Z j) =
((int.EuclideanDivision.div i j) + k)%Z).
Axiom mod_plus_fact_gen_mod :
forall (i:Z) (j:Z) (k:Z), (0%Z < j)%Z ->
((int.EuclideanDivision.mod1 ((k * j)%Z + i)%Z j) =
(int.EuclideanDivision.mod1 i j)).
Axiom bound_div :
forall (i:Z) (q:Z) (f:Z), (0%Z <= i)%Z -> (0%Z <= q)%Z -> (0%Z <= f)%Z ->
(i < (f * q)%Z)%Z ->
(0%Z <= (int.EuclideanDivision.div i q))%Z /\
(((0%Z <= ((int.EuclideanDivision.div i q) * q)%Z)%Z /\
((((int.EuclideanDivision.div i q) * q)%Z <= i)%Z /\
(i < (q * ((int.EuclideanDivision.div i q) + 1%Z)%Z)%Z)%Z)) /\
((int.EuclideanDivision.div i q) < f)%Z).
Axiom mod_upper_bound :
forall (i:Z) (q:Z), (0%Z < i)%Z -> (i = q) ->
((int.EuclideanDivision.mod1 i q) = 0%Z).
Axiom bound_div_gen :
forall (q:Z) (f:Z), (0%Z < q)%Z -> (0%Z <= f)%Z -> forall (i:Z),
((0%Z <= i)%Z /\ (i < (q * f)%Z)%Z) ->
((int.EuclideanDivision.div i q) < f)%Z.
Axiom mod_invariant :
forall (i:Z) (q:Z) (f:Z), (0%Z <= i)%Z -> (0%Z < q)%Z -> (0%Z < f)%Z ->
((int.EuclideanDivision.mod1
((q * (f * (int.EuclideanDivision.div i (q * f)%Z))%Z)%Z +
(int.EuclideanDivision.mod1 i (q * f)%Z))%Z
q)
= (int.EuclideanDivision.mod1 (int.EuclideanDivision.mod1 i (q * f)%Z) q)).
Axiom mod_inf :
forall (i:Z) (q:Z), ((0%Z <= i)%Z /\ (i < q)%Z) ->
((int.EuclideanDivision.mod1 i q) = i).
Axiom mod_mod_left :
forall (i:Z) (j:Z) (f:Z), (0%Z < j)%Z -> (0%Z < f)%Z ->
((int.EuclideanDivision.mod1 (int.EuclideanDivision.mod1 i (f * j)%Z) j) =
(int.EuclideanDivision.mod1 i j)).
Axiom mod_mod_i :
forall (i:Z) (j:Z), (0%Z < j)%Z ->
((int.EuclideanDivision.mod1 (int.EuclideanDivision.mod1 i j) j) =
(int.EuclideanDivision.mod1 i j)).
Axiom binary_prod :
forall (i:Z) (j:Z), (0%Z <= i)%Z -> (0%Z < j)%Z ->
((int.EuclideanDivision.mod1
((int.EuclideanDivision.mod1 i 2%Z) *
(int.EuclideanDivision.mod1 j 2%Z))%Z
2%Z)
= (int.EuclideanDivision.mod1 (i * j)%Z 2%Z)).
Axiom add_mod :
forall (a:Z) (b:Z) (c:Z), (c > 0%Z)%Z ->
((int.EuclideanDivision.mod1
((int.EuclideanDivision.mod1 a c) + (int.EuclideanDivision.mod1 b c))%Z
c)
= (int.EuclideanDivision.mod1 (a + b)%Z c)).
Axiom add_mod_left :
forall (a:Z) (b:Z) (c:Z), (c > 0%Z)%Z ->
((int.EuclideanDivision.mod1 ((int.EuclideanDivision.mod1 a c) + b)%Z c) =
(int.EuclideanDivision.mod1 (a + b)%Z c)).
Axiom add_mod_right :
forall (a:Z) (b:Z) (c:Z), (c > 0%Z)%Z ->
((int.EuclideanDivision.mod1 (a + (int.EuclideanDivision.mod1 b c))%Z c) =
(int.EuclideanDivision.mod1 (a + b)%Z c)).
Axiom mult_mod :
forall (a:Z) (b:Z) (c:Z), (c > 0%Z)%Z ->
((int.EuclideanDivision.mod1
((int.EuclideanDivision.mod1 a c) * (int.EuclideanDivision.mod1 b c))%Z
c)
= (int.EuclideanDivision.mod1 (a * b)%Z c)).
Axiom mod_mod_mult :
forall (a:Z) (b:Z) (c:Z), (0%Z < b)%Z ->
(((int.EuclideanDivision.mod1 a b) * (int.EuclideanDivision.mod1 c b))%Z =
(int.EuclideanDivision.mod1 (a * c)%Z b)).
Axiom mod_mod_mult_rev :
forall (a:Z) (b:Z) (c:Z), (0%Z < b)%Z ->
((int.EuclideanDivision.mod1 (a * c)%Z b) =
((int.EuclideanDivision.mod1 a b) * (int.EuclideanDivision.mod1 c b))%Z).
Axiom mod_minus :
forall (a:Z) (b:Z) (c:Z), (0%Z < b)%Z ->
((int.EuclideanDivision.mod1 a b) = c) ->
((int.EuclideanDivision.mod1 (-a)%Z b) =
(int.EuclideanDivision.mod1 (-c)%Z b)).
Axiom mult_mod_left :
forall (a:Z) (b:Z) (c:Z), (c > 0%Z)%Z ->
((int.EuclideanDivision.mod1 ((int.EuclideanDivision.mod1 a c) * b)%Z c) =
(int.EuclideanDivision.mod1 (a * b)%Z c)).
Axiom mult_mod_right :
forall (a:Z) (b:Z) (c:Z), (c > 0%Z)%Z ->
((int.EuclideanDivision.mod1 (a * (int.EuclideanDivision.mod1 b c))%Z c) =
(int.EuclideanDivision.mod1 (a * b)%Z c)).
Axiom mod_mod_right :
forall (i:Z) (j:Z) (f:Z), (0%Z <= i)%Z -> (0%Z < j)%Z -> (0%Z < f)%Z ->
((int.EuclideanDivision.mod1 (int.EuclideanDivision.mod1 i (j * f)%Z) j) =
(int.EuclideanDivision.mod1 i j)).
Axiom mod_mod_rev :
forall (i:Z) (j:Z) (f:Z), (0%Z <= i)%Z -> (0%Z < j)%Z -> (0%Z < f)%Z ->
((int.EuclideanDivision.mod1 i j) =
(int.EuclideanDivision.mod1 (int.EuclideanDivision.mod1 i (j * f)%Z) j)) /\
((int.EuclideanDivision.mod1 i j) =
(int.EuclideanDivision.mod1 (int.EuclideanDivision.mod1 i (f * j)%Z) j)).
Axiom mod_mod_plus :
forall (i:Z) (j:Z), (0%Z <= i)%Z -> (0%Z < j)%Z ->
((int.EuclideanDivision.mod1 i j) =
(int.EuclideanDivision.mod1 (int.EuclideanDivision.mod1 i (j + j)%Z) j)).
Axiom mod_mod_add_left :
forall (a:Z) (b:Z) (c:Z), (0%Z <= c)%Z ->
((int.EuclideanDivision.mod1 ((int.EuclideanDivision.mod1 a c) + b)%Z c) =
(int.EuclideanDivision.mod1 (a + b)%Z c)).
Axiom mod_mod_add_right :
forall (a:Z) (b:Z) (c:Z), (0%Z <= c)%Z ->
((int.EuclideanDivision.mod1 (a + (int.EuclideanDivision.mod1 b c))%Z c) =
(int.EuclideanDivision.mod1 (a + b)%Z c)).
Axiom mod_mod_add_left_rev :
forall (a:Z) (b:Z) (c:Z), (0%Z <= c)%Z ->
((int.EuclideanDivision.mod1 (a + b)%Z c) =
(int.EuclideanDivision.mod1 ((int.EuclideanDivision.mod1 a c) + b)%Z c)).
Axiom mod_mod_add_right_rev :
forall (a:Z) (b:Z) (c:Z), (0%Z <= c)%Z ->
((int.EuclideanDivision.mod1 (a + b)%Z c) =
(int.EuclideanDivision.mod1 (a + (int.EuclideanDivision.mod1 b c))%Z c)).
Axiom mult_assoc1 :
forall (i:Z) (q:Z) (f:Z), (0%Z <= i)%Z -> (0%Z < q)%Z -> (0%Z < f)%Z ->
((q * (f * (int.EuclideanDivision.div i (q * f)%Z))%Z)%Z =
((q * f)%Z * (int.EuclideanDivision.div i (q * f)%Z))%Z).
Axiom div_div1 :
forall (i:Z) (j:Z) (k:Z), (0%Z <= i)%Z -> (0%Z < j)%Z -> (0%Z < k)%Z ->
((int.EuclideanDivision.div (int.EuclideanDivision.div i k) j) =
(int.EuclideanDivision.div i (k * j)%Z)) /\
((int.EuclideanDivision.div (int.EuclideanDivision.div i k) j) =
(int.EuclideanDivision.div i (j * k)%Z)).
Axiom mod_div :
forall (i:Z) (j:Z) (k:Z), (0%Z <= i)%Z -> (0%Z < j)%Z -> (0%Z < k)%Z ->
((int.EuclideanDivision.div (int.EuclideanDivision.mod1 i (j * k)%Z) j) =
(int.EuclideanDivision.mod1 (int.EuclideanDivision.div i j) k)).
Axiom inf_mul :
forall (ia:Z) (ib:Z) (a:Z) (b:Z), ((0%Z <= ia)%Z /\ (ia < a)%Z) ->
((0%Z <= ib)%Z /\ (ib < b)%Z) ->
(((a * ib)%Z + ia)%Z < (a * b)%Z)%Z /\ (((ib * a)%Z + ia)%Z < (b * a)%Z)%Z.
Axiom inf_mul_gen :
forall (n:Z) (v:Z) (p:Z), ((0%Z <= p)%Z /\ (p < v)%Z) -> forall (k:Z),
((0%Z <= k)%Z /\ (k < n)%Z) -> (((k * v)%Z + p)%Z < (n * v)%Z)%Z.
Axiom inf_mul_gen_b :
forall (n:Z) (v:Z) (p:Z), ((0%Z <= p)%Z /\ (p < n)%Z) -> forall (k:Z),
((0%Z <= k)%Z /\ (k < v)%Z) -> (((p * v)%Z + k)%Z < (n * v)%Z)%Z.
Axiom inf_mul_comm :
forall (i:Z) (bi:Z) (quot:Z) (rest:Z), ((0%Z <= i)%Z /\ (i < bi)%Z) ->
(0%Z < rest)%Z -> (0%Z < quot)%Z -> (bi = (quot * rest)%Z) ->
((int.EuclideanDivision.mod1 i rest) < rest)%Z.
Parameter nonn_part1:
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
(im1 -> im1 -> im1) -> (set a) -> (a -> im1) -> set a.
Parameter result4:
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
(im1 -> im1 -> im1) -> (a -> im1) -> a -> bool.
Axiom result_def4 :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (t1:a -> im1) (e:a),
(((result4 op1 t1) e) = true) <-> ~ (neutral op1 (t1 e)).
Axiom nonn_part_def1 :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1),
((nonn_part1 op1 s t1) = (filter (result4 op1 t1) s)).
Axiom nonn_part_spec1 :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1), forall (e:a),
(mem e (nonn_part1 op1 s t1)) <-> ((mem e s) /\ ~ (neutral op1 (t1 e))).
Parameter n_part1:
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
(im1 -> im1 -> im1) -> (set a) -> (a -> im1) -> set a.
Parameter result5:
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
(im1 -> im1 -> im1) -> (a -> im1) -> a -> bool.
Axiom result_def5 :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (t1:a -> im1) (e:a),
(((result5 op1 t1) e) = true) <-> (neutral op1 (t1 e)).
Axiom n_part_def1 :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1),
((n_part1 op1 s t1) = (filter (result5 op1 t1) s)).
Axiom n_part_spec1 :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1), forall (e:a),
(mem e (n_part1 op1 s t1)) <-> ((mem e s) /\ (neutral op1 (t1 e))).
Axiom nullity_partition1 :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1), (commut op1) ->
(s = (union (nonn_part1 op1 s t1) (n_part1 op1 s t1))) /\
((inter (nonn_part1 op1 s t1) (n_part1 op1 s t1)) = (empty : set a)).
Axiom iterate_neutral1 :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1), (iterable op1) ->
(commut op1) ->
(forall (a1:a), (mem a1 s) -> ((t1 a1) = (neutral_elt op1))) ->
((iterate op1 s t1) = (neutral_elt op1)).
Axiom iterate_nullity_partition1 :
forall {a:Type} {a_WT:WhyType a} {im1:Type} {im1_WT:WhyType im1},
forall (op1:im1 -> im1 -> im1) (s:set a) (t1:a -> im1), (iterable op1) ->
(commut op1) ->
((iterate op1 s t1) = (iterate op1 (nonn_part1 op1 s t1) t1)).
Parameter indic: forall {a:Type} {a_WT:WhyType a}, a -> a -> t.
Axiom indic_def :
forall {a:Type} {a_WT:WhyType a},
forall (a1:a) (a':a),
((infix_eqeq a1 a') -> ((indic a1 a') = tone)) /\
(~ (infix_eqeq a1 a') -> ((indic a1 a') = tzero)).
Axiom indic_spec :
forall {a:Type} {a_WT:WhyType a},
forall (a1:a) (a':a),
((a1 = a') -> ((indic a1 a') = tone)) /\
(~ (a1 = a') -> ((indic a1 a') = tzero)).
Axiom get_indic :
forall {a:Type} {a_WT:WhyType a},
forall (a1:a) (a':a),
((a1 = a') -> ((indic a1 a') = tone)) /\
(~ (a1 = a') -> ((indic a1 a') = tzero)).
Parameter indic_bool: forall {a:Type} {a_WT:WhyType a}, a -> a -> bool.
Axiom indic_bool_def :
forall {a:Type} {a_WT:WhyType a},
forall (a1:a) (a':a),
((infix_eqeq a1 a') -> ((indic_bool a1 a') = true)) /\
(~ (infix_eqeq a1 a') -> ((indic_bool a1 a') = false)).
Axiom indic_bool_spec :
forall {a:Type} {a_WT:WhyType a},
forall (a1:a) (a':a),
((a1 = a') -> ((indic_bool a1 a') = true)) /\
(~ (a1 = a') -> ((indic_bool a1 a') = false)).
Axiom indic_comm :
forall {a:Type} {a_WT:WhyType a},
forall (a1:a) (a':a), ((indic a1 a') = (indic a' a1)).
Axiom indic_transl_r :
forall {a:Type} {a_WT:WhyType a},
forall (a1:a) (b:a) (c:a), (b = c) -> ((indic a1 b) = (indic a1 c)).
Axiom indic_transl_l :
forall {a:Type} {a_WT:WhyType a},
forall (a1:a) (b:a) (c:a), (b = c) -> ((indic b a1) = (indic c a1)).
Parameter indic_2:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, a -> a -> b ->
b -> t.
Axiom indic_2_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (a1:a) (a':a) (b1:b) (b':b),
((((indic_bool a1 a') = true) /\ ((indic_bool b1 b') = true)) ->
((indic_2 a1 a' b1 b') = tone)) /\
(~ (((indic_bool a1 a') = true) /\ ((indic_bool b1 b') = true)) ->
((indic_2 a1 a' b1 b') = tzero)).
Axiom indic_2_spec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (a1:a) (a':a) (b1:b) (b':b),
((indic_2 a1 a' b1 b') = (infix_asdt (indic a1 a') (indic b1 b'))) /\
((indic_2 a1 a' b1 b') = (indic (a1, b1) (a', b'))).
Axiom indic_2_if :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (i:a) (k:a) (j:b) (l:b),
(((i = k) /\ (j = l)) -> ((indic_2 i k j l) = tone)) /\
(~ ((i = k) /\ (j = l)) -> ((indic_2 i k j l) = tzero)).
Axiom indic_2_comm :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (a1:a) (a':a) (b1:b) (b':b),
((indic_2 a1 a' b1 b') = (indic_2 a' a1 b1 b')) /\
(((indic_2 a1 a' b1 b') = (indic_2 a1 a' b' b1)) /\
((indic_2 a1 a' b1 b') = (indic_2 a' a1 b' b1))).
Parameter sum_indic:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> t) -> a -> t.
Axiom sum_indic_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t) (i:a),
((sum_indic s t1 i) =
(sum s (fun (e:a) => (infix_asdt (t1 e) (indic i e))))).
Parameter bool_to_t: bool -> t.
Axiom bool_to_t_def :
forall (a:bool),
((a = true) -> ((bool_to_t a) = tone)) /\
(~ (a = true) -> ((bool_to_t a) = tzero)).
Parameter ind_sum_indic: (Z -> t) -> Z -> Z -> Z -> t.
Axiom ind_sum_indic_def :
forall (t1:Z -> t) (l:Z) (h:Z) (i:Z), (l < h)%Z ->
((ind_sum_indic t1 l h i) =
(ind_sum (fun (e:Z) => (infix_asdt (t1 e) (indic i e))) l h)).
Axiom ind_sum_indic_spec :
forall (t1:Z -> t) (l:Z) (h:Z) (i:Z), (l < h)%Z ->
((ind_sum_indic t1 l h i) = (sum_indic (to_fset l h) t1 i)).
Axiom sum_indic_t :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t) (i:a), (mem i s) ->
((sum_indic s t1 i) = (t1 i)).
Axiom sum_indic_ts :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t) (i:a), (mem i s) ->
((sum s (fun (e:a) => (infix_asdt (t1 e) (indic i e)))) = (t1 i)).
Axiom ind_sum_indic_t :
forall (t1:Z -> t) (l:Z) (h:Z) (i:Z), ((l <= i)%Z /\ (i < h)%Z) ->
((ind_sum_indic t1 l h i) = (t1 i)) /\
((ind_sum (fun (e:Z) => (infix_asdt (t1 e) (indic i e))) l h) = (t1 i)).
Axiom ind_sum_indic_t_quant :
forall (t1:Z -> t) (l:Z) (h:Z), forall (i:Z), ((l <= i)%Z /\ (i < h)%Z) ->
((ind_sum (fun (e:Z) => (infix_asdt (t1 e) (indic i e))) l h) = (t1 i)).
Axiom indic_div_mod :
forall (i:Z) (j:Z) (q:Z), (0%Z <= i)%Z -> (0%Z <= j)%Z -> (0%Z < q)%Z ->
((indic i j) =
(infix_asdt
(indic (int.EuclideanDivision.mod1 i q) (int.EuclideanDivision.mod1 j q))
(indic (int.EuclideanDivision.div i q) (int.EuclideanDivision.div j q)))).
Axiom indic_div_mod_gen :
forall (q:Z), (0%Z < q)%Z -> forall (i:Z) (j:Z),
((0%Z <= i)%Z /\ (0%Z <= j)%Z) ->
((indic i j) =
(infix_asdt
(indic (int.EuclideanDivision.mod1 i q) (int.EuclideanDivision.mod1 j q))
(indic (int.EuclideanDivision.div i q) (int.EuclideanDivision.div j q)))).
Axiom set_inf : True.
Axiom set_infeq : True.
Axiom bounded_cycle :
forall (a:Z) (b:Z) (c:Z) (d:Z), (0%Z <= a)%Z -> (0%Z < b)%Z ->
((0%Z <= d)%Z /\ (d < b)%Z) -> (0%Z < c)%Z ->
((int.EuclideanDivision.div ((a * b)%Z + d)%Z (b * c)%Z) =
(int.EuclideanDivision.div a c)).
Axiom div_mod_minus :
forall (a:Z) (b:Z), (0%Z < b)%Z -> ((0%Z < a)%Z /\ (a < b)%Z) ->
((int.EuclideanDivision.mod1 (-a)%Z b) =
(b - (int.EuclideanDivision.mod1 a b))%Z).
Axiom leq_trans :
forall (a:Z) (b:Z) (c:Z), (a <= b)%Z -> (b <= c)%Z -> (a <= c)%Z.
Axiom leq_trans_add :
forall (a:Z) (b:Z) (c:Z) (d:Z), (a <= c)%Z -> (b <= d)%Z ->
((a + b)%Z <= (c + d)%Z)%Z.
Axiom leq_trans_mult :
forall (a:Z) (b:Z) (c:Z), (0%Z <= c)%Z -> (a <= b)%Z ->
((a * c)%Z <= (b * c)%Z)%Z.
Axiom leq_trans_mult_right :
forall (a:Z) (b:Z) (c:Z), (0%Z <= c)%Z -> (a <= b)%Z ->
((c * a)%Z <= (c * b)%Z)%Z.
Axiom leq_trans_fact :
forall (a:Z) (b:Z) (c:Z) (n:Z), (0%Z <= n)%Z ->
((0%Z <= a)%Z /\ (a <= c)%Z) -> ((0%Z <= b)%Z /\ (b <= (c * n)%Z)%Z) ->
((a + b)%Z <= (c * (n + 1%Z)%Z)%Z)%Z.
Axiom leq_trans_facrev :
forall (a:Z) (b:Z) (c:Z) (n:Z), (0%Z <= n)%Z ->
((0%Z <= a)%Z /\ (a <= c)%Z) -> ((0%Z <= b)%Z /\ (b <= (c * n)%Z)%Z) ->
((b + a)%Z <= (c * (n + 1%Z)%Z)%Z)%Z.
Axiom neutrals :
(0%Z = (neutral_elt (fun (y0:Z) (y1:Z) => (y0 + y1)%Z))) /\
((1%Z = (neutral_elt (fun (y0:Z) (y1:Z) => (y0 * y1)%Z))) /\
((iterable (fun (y0:Z) (y1:Z) => (y0 + y1)%Z)) /\
(iterable (fun (y0:Z) (y1:Z) => (y0 * y1)%Z)))).
Parameter isum: forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> Z) -> Z.
Axiom isum_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> Z),
((isum s t1) = (iterate (fun (y0:Z) (y1:Z) => (y0 + y1)%Z) s t1)).
Axiom isum_iter : iterates (fun (y0:Z) (y1:Z) => (y0 + y1)%Z) 0%Z.
Axiom isum_iter__ : iterable (fun (y0:Z) (y1:Z) => (y0 + y1)%Z).
Axiom isum_eq :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> Z) (t':a -> Z),
(forall (e:a), (mem e s) -> ((t1 e) = (t' e))) ->
((isum s t1) = (isum s t')).
Axiom isum_eq_gen :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (t1:a -> Z) (t':a -> Z), (s = s') ->
(forall (e:a), (mem e s) -> ((t1 e) = (t' e))) ->
((isum s t1) = (isum s t')).
Axiom isum_add :
forall {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> Z) (x:b), ~ (mem x s) ->
((isum (add x s) f) = ((f x) + (isum s f))%Z).
Axiom mul_assoc :
forall (a:Z) (b:Z) (c:Z), (((a * b)%Z * c)%Z = (a * (b * c)%Z)%Z).
Axiom ad_assoc :
forall (a:Z) (b:Z) (c:Z), (((a + b)%Z + c)%Z = (a + (b + c)%Z)%Z).
Axiom ad_assoc_rev :
forall (a:Z) (b:Z) (c:Z), ((a + (b + c)%Z)%Z = ((a + b)%Z + c)%Z).
Axiom ad_seq_switch :
forall (a:Z) (b:Z) (c:Z) (a':Z) (b':Z) (c':Z), (a = a') -> (b = b') ->
(c = c') -> ((a' + (b' + c')%Z)%Z = (b + (c + a)%Z)%Z).
Axiom mul_comm : forall (a:Z) (b:Z), ((a * b)%Z = (b * a)%Z).
Axiom add_eq_i :
forall (a:Z) (a':Z) (b:Z) (b':Z), (a = a') -> (b = b') ->
((a + b)%Z = (a' + b')%Z).
Axiom mult_eq_i :
forall (a:Z) (a':Z) (b:Z) (b':Z), (a = a') -> (b = b') ->
((a * b)%Z = (a' * b')%Z).
Axiom mul_assoc_rev :
forall (a:Z) (b:Z) (c:Z), ((a * (b * c)%Z)%Z = ((a * b)%Z * c)%Z).
Axiom mult_add_distr :
forall (a:Z) (b:Z) (c:Z) (d:Z),
(((a + b)%Z * (c + d)%Z)%Z =
((((a * c)%Z + (a * d)%Z)%Z + (b * c)%Z)%Z + (b * d)%Z)%Z).
Axiom mult_add_right :
forall (a:Z) (b:Z) (c:Z), (((a + b)%Z * c)%Z = ((a * c)%Z + (b * c)%Z)%Z).
Axiom mult_add_right_rev :
forall (a:Z) (b:Z) (c:Z), (((a * c)%Z + (b * c)%Z)%Z = ((a + b)%Z * c)%Z).
Axiom mult_add_left :
forall (a:Z) (b:Z) (c:Z), ((a * (b + c)%Z)%Z = ((a * b)%Z + (a * c)%Z)%Z).
Axiom mult_add_left_rev :
forall (a:Z) (b:Z) (c:Z), (((a * b)%Z + (a * c)%Z)%Z = (a * (b + c)%Z)%Z).
Axiom mult_add_distr_rev :
forall (a:Z) (b:Z) (c:Z) (d:Z),
(((((a * c)%Z + (a * d)%Z)%Z + (b * c)%Z)%Z + (b * d)%Z)%Z =
((a + b)%Z * (c + d)%Z)%Z).
Axiom mul_assoc_comm :
forall (a:Z) (b:Z) (c:Z), (((a * b)%Z * c)%Z = (b * (a * c)%Z)%Z).
Axiom mul_assoc_rev_comm :
forall (a:Z) (b:Z) (c:Z), ((a * (b * c)%Z)%Z = ((a * c)%Z * b)%Z).
Axiom add_assoc :
forall (a:Z) (b:Z) (c:Z), (((a + b)%Z + c)%Z = (a + (b + c)%Z)%Z).
Axiom add_assoc_rev :
forall (a:Z) (b:Z) (c:Z), ((a + (b + c)%Z)%Z = ((a + b)%Z + c)%Z).
Axiom isum_empty :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> Z), (is_empty s) -> ((isum s f) = 0%Z).
Axiom isum_iter_ :
(opposite_n (fun (y0:Z) (y1:Z) => (y0 + y1)%Z)
(fun (y0:Z) (y1:Z) => (y0 - y1)%Z) 0%Z) /\
((opposite1 (fun (y0:Z) (y1:Z) => (y0 + y1)%Z)
(fun (y0:Z) (y1:Z) => (y0 - y1)%Z)) /\
((opposite_com (fun (y0:Z) (y1:Z) => (y0 + y1)%Z)
(fun (y0:Z) (y1:Z) => (y0 - y1)%Z)) /\
(inverse_tuple (fun (y0:Z) (y1:Z) => (y0 + y1)%Z)
(fun (y0:Z) (y1:Z) => (y0 - y1)%Z) 0%Z))).
Parameter ind_isum: (Z -> Z) -> Z -> Z -> Z.
Axiom ind_isum_def :
forall (f:Z -> Z) (i:Z) (j:Z),
((ind_isum f i j) = (int_iterate (fun (y0:Z) (y1:Z) => (y0 + y1)%Z) f i j)).
Axiom ind_isum_empty :
forall (f:Z -> Z) (i:Z) (j:Z), (j <= i)%Z -> ((ind_isum f i j) = 0%Z).
Axiom ind_isum_one :
forall (f:Z -> Z) (i:Z) (j:Z), (j = (i + 1%Z)%Z) ->
((ind_isum f i j) = (f i)).
Axiom ind_isum_plus_one :
forall (f:Z -> Z) (i:Z) (j:Z), (i < j)%Z ->
((ind_isum f i j) = ((f i) + (ind_isum f (i + 1%Z)%Z j))%Z).
Axiom ind_isum_to_isum :
forall (f:Z -> Z) (i:Z) (j:Z), (i < j)%Z ->
((ind_isum f i j) = (isum (to_fset i j) f)).
Axiom ind_isum_const :
forall (k:Z) (i:Z) (j:Z), (i < j)%Z ->
((ind_isum ((fun (y0:Z) (y1:Z) => (const y0 y1)) k) i j) =
(k * (j - i)%Z)%Z).
Axiom ind_isum_null :
forall (f:Z -> Z) (i:Z) (j:Z), (i < j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = 0%Z)) ->
((ind_isum f i j) = 0%Z).
Axiom ind_isum_right_extension :
forall (f:Z -> Z) (i:Z) (j:Z), (i <= j)%Z ->
((ind_isum f i (j + 1%Z)%Z) = ((ind_isum f i j) + (f j))%Z).
Axiom ind_isum_re :
forall (f:Z -> Z) (i:Z) (j:Z), (i < j)%Z ->
((ind_isum f i j) = ((ind_isum f i (j - 1%Z)%Z) + (f (j - 1%Z)%Z))%Z).
Axiom ind_isum_re_null :
forall (f:Z -> Z) (i:Z) (j:Z), (i < j)%Z -> ((f j) = 0%Z) ->
((ind_isum f i (j + 1%Z)%Z) = (ind_isum f i j)).
Axiom ind_isum_eq :
forall (f:Z -> Z) (g:Z -> Z) (i:Z) (j:Z),
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((ind_isum f i j) = (ind_isum g i j)).
Parameter fc2: (Z -> Z) -> (Z -> Z) -> (Z -> bool) -> Z -> Z.
Axiom fc_def2 :
forall (f:Z -> Z) (g:Z -> Z) (p:Z -> bool) (k:Z),
(((p k) = true) -> (((fc2 f g p) k) = (f k))) /\
(~ ((p k) = true) -> (((fc2 f g p) k) = (g k))).
Axiom ind_isum_to_guard :
forall (f:Z -> Z) (g:Z -> Z) (p:Z -> bool) (i:Z) (j:Z),
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((p k) = true)) ->
((ind_isum (fc2 f g p) i j) = (ind_isum f i j)).
Parameter fc3: (Z -> Z) -> (Z -> Z) -> (Z -> bool) -> Z -> Z.
Axiom fc_def3 :
forall (f:Z -> Z) (g:Z -> Z) (p:Z -> bool) (k:Z),
(((p k) = true) -> (((fc3 f g p) k) = (g k))) /\
(~ ((p k) = true) -> (((fc3 f g p) k) = (f k))).
Axiom ind_isum_no_guard :
forall (f:Z -> Z) (g:Z -> Z) (p:Z -> bool) (i:Z) (j:Z),
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ~ ((p k) = true)) ->
((ind_isum (fc3 f g p) i j) = (ind_isum f i j)).
Axiom ind_isum_eq_gen :
forall (f:Z -> Z) (g:Z -> Z) (i:Z) (i1:Z) (j:Z) (j1:Z),
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) -> (i = i1) ->
(j = j1) -> ((ind_isum f i j) = (ind_isum g i1 j1)).
Axiom ind_isum_func_const :
forall (k:Z) (f:Z -> Z) (i:Z) (j:Z), (i < j)%Z ->
(forall (l:Z), ((i <= l)%Z /\ (l < j)%Z) -> ((f l) = k)) ->
((ind_isum f i j) = (k * (j - i)%Z)%Z).
Axiom ind_isum_pos :
forall (f:Z -> Z) (i:Z) (j:Z), (i <= j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) >= 0%Z)%Z) ->
(0%Z <= (ind_isum f i j))%Z.
Parameter ind_iproduct: (Z -> Z) -> Z -> Z -> Z.
Axiom ind_iproduct_def :
forall (f:Z -> Z) (i:Z) (j:Z),
((ind_iproduct f i j) =
(int_iterate (fun (y0:Z) (y1:Z) => (y0 * y1)%Z) f i j)).
Axiom ind_iproduct_eq :
forall (f:Z -> Z) (g:Z -> Z) (i:Z) (j:Z),
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((ind_iproduct f i j) = (ind_iproduct g i j)).
Axiom ind_iproduct_eq_gen :
forall (f:Z -> Z) (g:Z -> Z) (i1:Z) (j1:Z) (i2:Z) (j2:Z),
(forall (k:Z), ((i1 <= k)%Z /\ (k < j1)%Z) -> ((f k) = (g k))) ->
(i1 = i2) -> (j1 = j2) -> ((ind_iproduct f i1 j1) = (ind_iproduct g i2 j2)).
Axiom mult_one_int : forall (a:Z) (b:Z), (b = 1%Z) -> ((a * b)%Z = a).
Axiom one_mult_int : forall (a:Z) (b:Z), (a = 1%Z) -> ((a * b)%Z = b).
Axiom mult_zero_int : forall (a:Z) (b:Z), (b = 0%Z) -> ((a * b)%Z = 0%Z).
Axiom zero_mult_int : forall (a:Z) (b:Z), (a = 0%Z) -> ((a * b)%Z = 0%Z).
Axiom iproduct_to_iterate :
forall (f:Z -> Z) (i:Z) (j:Z),
((ind_iproduct f i j) =
(int_iterate (fun (y0:Z) (y1:Z) => (y0 * y1)%Z) f i j)).
Axiom ind_isum_map_auto :
forall (i:Z) (j:Z) (f:Z -> Z) (t1:Z -> Z),
(p_bijective f (to_fset i j) (to_fset i j)) ->
((ind_isum t1 i j) = (ind_isum (fun (b:Z) => (t1 (f b))) i j)).
Axiom ind_isum_map :
forall (i:Z) (j:Z) (k:Z) (l:Z) (f:Z -> Z) (t1:Z -> Z),
(p_bijective f (to_fset i j) (to_fset k l)) ->
((ind_isum t1 k l) = (ind_isum (fun (b:Z) => (t1 (f b))) i j)).
Axiom ind_isum_map_auto_bij :
forall (i:Z) (j:Z) (f:Z -> Z) (t1:Z -> Z),
(forall (e:Z), ((i <= e)%Z /\ (e < j)%Z) ->
(i <= (f e))%Z /\ ((f e) < j)%Z) ->
(forall (e:Z) (e':Z), ((i <= e)%Z /\ (e < j)%Z) ->
((i <= e')%Z /\ (e' < j)%Z) -> ~ (e = e') -> ~ ((f e) = (f e'))) ->
(forall (e':Z), ((i <= e')%Z /\ (e' < j)%Z) ->
exists e:Z, ((i <= e)%Z /\ (e < j)%Z) /\ ((f e) = e')) ->
((ind_isum t1 i j) = (ind_isum (fun (b:Z) => (t1 (f b))) i j)).
Axiom ind_isum_map_bij :
forall (i:Z) (j:Z) (k:Z) (l:Z) (f:Z -> Z) (t1:Z -> Z),
(forall (e:Z), ((i <= e)%Z /\ (e < j)%Z) ->
(k <= (f e))%Z /\ ((f e) < l)%Z) ->
(forall (e:Z) (e':Z), ((i <= e)%Z /\ (e < j)%Z) ->
((i <= e')%Z /\ (e' < j)%Z) -> ~ (e = e') -> ~ ((f e) = (f e'))) ->
(forall (e':Z), ((k <= e')%Z /\ (e' < l)%Z) ->
exists e:Z, ((i <= e)%Z /\ (e < j)%Z) /\ ((f e) = e')) ->
((ind_isum t1 k l) = (ind_isum (fun (b:Z) => (t1 (f b))) i j)).
Axiom ind_iproduct_empty :
forall (f:Z -> Z) (i:Z) (j:Z), (i >= j)%Z -> ((ind_iproduct f i j) = 1%Z).
Axiom ind_iproduct_plus_one :
forall (f:Z -> Z) (i:Z) (j:Z), (i < j)%Z ->
((ind_iproduct f i j) = ((f i) * (ind_iproduct f (i + 1%Z)%Z j))%Z).
Axiom ind_iproduct_right_extension :
forall (f:Z -> Z) (i:Z) (j:Z), (i < j)%Z ->
((ind_iproduct f i j) =
((ind_iproduct f i (j - 1%Z)%Z) * (f (j - 1%Z)%Z))%Z).
Axiom ind_iproduct_right_extension_comm :
forall (f:Z -> Z) (i:Z) (j:Z), (i < j)%Z ->
(((ind_iproduct f i (j - 1%Z)%Z) * (f (j - 1%Z)%Z))%Z =
(ind_iproduct f i j)).
Axiom ind_iproduct_one :
forall (f:Z -> Z) (i:Z) (j:Z),
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = 1%Z)) ->
((ind_iproduct f i j) = 1%Z).
Axiom positive_iproduct :
forall (f:Z -> Z) (i:Z) (j:Z),
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) > 0%Z)%Z) ->
((ind_iproduct f i j) > 0%Z)%Z.
Axiom ind_iproduct_pos :
forall (f:Z -> Z) (i:Z) (j:Z),
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> (0%Z <= (f k))%Z) ->
(0%Z <= (ind_iproduct f i j))%Z.
Axiom ind_iproduct_left_right :
forall (f:Z -> Z) (l:Z) (k:Z) (h:Z), ((l <= k)%Z /\ (k <= h)%Z) ->
((ind_iproduct f l k) =
(ind_iproduct (fun (a:Z) => (f ((h - (a + 1%Z)%Z)%Z + l)%Z))
((h - k)%Z + l)%Z h)).
Axiom iterable_imult : iterable (fun (y0:Z) (y1:Z) => (y0 * y1)%Z).
Axiom int_minus_distr :
forall (a:Z) (b:Z), ((-(a + b)%Z)%Z = ((-a)%Z + (-b)%Z)%Z).
Axiom int_minus_eq : forall (a:Z) (b:Z), (a = b) -> ((-a)%Z = (-b)%Z).
Axiom ind_iproduct_map_auto :
forall (i:Z) (j:Z) (f:Z -> Z) (t1:Z -> Z),
(p_bijective f (to_fset i j) (to_fset i j)) ->
((ind_iproduct t1 i j) = (ind_iproduct (fun (b:Z) => (t1 (f b))) i j)).
Axiom ind_iproduct_map :
forall (i:Z) (j:Z) (k:Z) (l:Z) (f:Z -> Z) (t1:Z -> Z),
(p_bijective f (to_fset i j) (to_fset k l)) ->
((ind_iproduct t1 k l) = (ind_iproduct (fun (b:Z) => (t1 (f b))) i j)).
Axiom ind_iproduct_trans :
forall (f:Z -> Z) (i:Z) (k:Z) (j:Z), ((i <= k)%Z /\ (k <= j)%Z) ->
((ind_iproduct f i j) = ((ind_iproduct f i k) * (ind_iproduct f k j))%Z).
Axiom ind_isum_transl :
forall (f:Z -> Z) (i:Z) (j:Z) (k:Z),
((ind_isum f i j) =
(ind_isum (fun (b:Z) => (f (b + k)%Z)) (i - k)%Z (j - k)%Z)).
Axiom ind_isum_transl_plus_one :
forall (f:Z -> Z) (i:Z) (j:Z),
((ind_isum f i j) =
(ind_isum (fun (b:Z) => (f (b - 1%Z)%Z)) (i + 1%Z)%Z (j + 1%Z)%Z)).
Axiom ind_isum_transl_minus_one :
forall (f:Z -> Z) (i:Z) (j:Z),
((ind_isum f i j) =
(ind_isum (fun (b:Z) => (f (b + 1%Z)%Z)) (i - 1%Z)%Z (j - 1%Z)%Z)).
Axiom ind_isum_scal :
forall (f:Z -> Z) (i:Z) (j:Z) (a:Z), (i <= j)%Z ->
((ind_isum (fun (i1:Z) => (a * (f i1))%Z) i j) = (a * (ind_isum f i j))%Z).
Axiom minus_ind_isum :
forall (f:Z -> Z) (i:Z) (j:Z), (i <= j)%Z ->
((-(ind_isum f i j))%Z = (ind_isum (fun (i1:Z) => (-(f i1))%Z) i j)).
Axiom minus_ind_isum_rev :
forall (f:Z -> Z) (i:Z) (j:Z), (i <= j)%Z ->
((ind_isum (fun (i1:Z) => (-(f i1))%Z) i j) = (-(ind_isum f i j))%Z).
Axiom ind_isum_scal_rev :
forall (f:Z -> Z) (i:Z) (j:Z) (a:Z), (i <= j)%Z ->
((a * (ind_isum f i j))%Z = (ind_isum (fun (i1:Z) => (a * (f i1))%Z) i j)).
Axiom ind_isum_scal_rev_right :
forall (f:Z -> Z) (i:Z) (j:Z) (a:Z), (i <= j)%Z ->
(((ind_isum f i j) * a)%Z = (ind_isum (fun (i1:Z) => ((f i1) * a)%Z) i j)).
Axiom ind_isum_scal_right :
forall (f:Z -> Z) (i:Z) (j:Z) (a:Z), (i <= j)%Z ->
((ind_isum (fun (i1:Z) => ((f i1) * a)%Z) i j) = ((ind_isum f i j) * a)%Z).
Axiom ind_isum_bound :
forall (f:Z -> Z) (g:Z -> Z) (i:Z) (j:Z), (i < j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) < (g k))%Z) ->
((ind_isum f i j) < (ind_isum g i j))%Z.
Axiom comp_trans_equal_strict :
forall (a:Z) (b:Z) (c:Z), (a <= b)%Z -> (b < c)%Z -> (a < c)%Z.
Axiom compeq_trans_sum :
forall (a:Z) (b:Z) (c:Z), (b <= c)%Z -> ((a + b)%Z <= (a + c)%Z)%Z.
Axiom compeq_trans_sum_zero :
forall (a:Z) (b:Z), (0%Z <= b)%Z -> (a <= (a + b)%Z)%Z.
Axiom comp_trans_sum :
forall (a:Z) (b:Z) (c:Z), (b < c)%Z -> ((a + b)%Z < (a + c)%Z)%Z.
Axiom ind_isum_bound_eq :
forall (f:Z -> Z) (g:Z -> Z) (i:Z) (j:Z), (i <= j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) <= (g k))%Z) ->
((ind_isum f i j) <= (ind_isum g i j))%Z.
Axiom ind_isum_scal_gen :
forall (f:Z -> Z) (i:Z) (j:Z), forall (a:Z), ((i <= a)%Z /\ (a < j)%Z) ->
((ind_isum (fun (i1:Z) => (a * (f i1))%Z) i j) = (a * (ind_isum f i j))%Z).
Axiom ind_isum_trans :
forall (f:Z -> Z) (i:Z) (k:Z) (j:Z), ((i <= k)%Z /\ (k <= j)%Z) ->
((ind_isum f i j) = ((ind_isum f i k) + (ind_isum f k j))%Z).
Parameter power: Z -> Z -> Z.
Axiom power_def :
forall (e:Z) (i:Z), (i >= 0%Z)%Z ->
((i = 0%Z) -> ((power e i) = 1%Z)) /\
(~ (i = 0%Z) -> ((power e i) = (e * (power e (i - 1%Z)%Z))%Z)).
Axiom Power_zero : forall (i:Z), ((power i 0%Z) = 1%Z).
Axiom Power_one : forall (i:Z), ((power i 1%Z) = i).
Axiom Power_sum :
forall (x:Z) (y:Z) (i:Z), (x >= 0%Z)%Z -> (y >= 0%Z)%Z ->
((power i (x + y)%Z) = ((power i x) * (power i y))%Z).
Axiom Power_mult :
forall (x:Z) (y:Z) (i:Z), (x >= 0%Z)%Z -> (y >= 0%Z)%Z ->
((power i (x * y)%Z) = (power (power i x) y)).
Axiom power_plus_one :
forall (e:Z) (i:Z), (i >= 0%Z)%Z ->
((power e (i + 1%Z)%Z) = (e * (power e i))%Z).
Axiom power_to_ind_iproduct :
forall (e:Z) (i:Z), (0%Z <= i)%Z ->
((power e i) =
(ind_iproduct ((fun (y0:Z) (y1:Z) => (const y0 y1)) e) 0%Z i)).
Axiom power_transl :
forall (e:Z) (k:Z) (i:Z), (0%Z <= i)%Z ->
((power e i) =
(ind_iproduct ((fun (y0:Z) (y1:Z) => (const y0 y1)) e) k (k + i)%Z)).
Axiom ind_iproduct_to_power :
forall (e:Z) (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i <= j)%Z) ->
((ind_iproduct ((fun (y0:Z) (y1:Z) => (const y0 y1)) e) i j) =
(power e (j - i)%Z)).
Axiom ind_iproduct_to_power_gen :
forall (e:Z), forall (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i <= j)%Z) ->
((ind_iproduct ((fun (y0:Z) (y1:Z) => (const y0 y1)) e) i j) =
(power e (j - i)%Z)).
Axiom power_sum :
forall (x:Z) (n:Z) (m:Z), (n >= 0%Z)%Z -> (m >= 0%Z)%Z ->
((power x (n + m)%Z) = ((power x n) * (power x m))%Z).
Axiom power_sum_rev :
forall (x:Z) (n:Z) (m:Z), (n >= 0%Z)%Z -> (m >= 0%Z)%Z ->
(((power x n) * (power x m))%Z = (power x (n + m)%Z)).
Axiom power_eq :
forall (x:Z) (n:Z) (m:Z), (n = m) -> ((power x n) = (power x m)).
Axiom power_eq_gen :
forall (x:Z) (y:Z) (n:Z) (m:Z), (n = m) -> (x = y) ->
((power x n) = (power y m)).
Axiom power_decomp :
forall (i:Z), (i >= 1%Z)%Z ->
((ind_isum (fun (k:Z) => (power 2%Z (k + 1%Z)%Z)) 0%Z i) <
(power 2%Z (i + 1%Z)%Z))%Z.
Parameter fc4: Z -> Z -> Z.
Axiom fc_def4 :
forall (i:Z) (k:Z),
(((1%Z <= k)%Z /\ (k < (i + 1%Z)%Z)%Z) ->
(((fc4 i) k) = (power 2%Z (k - 1%Z)%Z))) /\
(~ ((1%Z <= k)%Z /\ (k < (i + 1%Z)%Z)%Z) -> (((fc4 i) k) = 0%Z)).
Axiom power_decomp_minus_one :
forall (i:Z), (i >= 1%Z)%Z ->
((ind_isum (fc4 i) 1%Z i) < (power 2%Z (i - 1%Z)%Z))%Z.
Axiom power_decomp_ :
forall (i:Z), (i >= 1%Z)%Z ->
((ind_isum (fun (k:Z) => (power 2%Z k)) 0%Z i) < (power 2%Z i))%Z.
Axiom power_decomp_one :
forall (i:Z), (i >= 1%Z)%Z ->
((ind_isum (fun (k:Z) => (power 2%Z (k + 1%Z)%Z)) 1%Z i) <
(power 2%Z (i + 1%Z)%Z))%Z.
Axiom power_decomp_one_ :
forall (i:Z), (i >= 1%Z)%Z ->
((ind_isum (fun (k:Z) => (power 2%Z k)) 1%Z i) < (power 2%Z i))%Z.
Axiom growing_mult :
forall (n:Z) (m:Z), (0%Z <= n)%Z -> (1%Z <= m)%Z -> ((n * m)%Z >= n)%Z.
Axiom strict_growing_mult :
forall (n:Z) (m:Z), (1%Z < n)%Z -> (1%Z < m)%Z -> ((n * m)%Z > n)%Z.
Axiom init_exp :
forall (k:Z),
((power k 0%Z) = 1%Z) /\
(((power k 1%Z) = k) /\ ((power k 2%Z) = (k * k)%Z)).
Axiom positive_int_exp :
forall (k:Z) (n:Z), (1%Z <= k)%Z -> (0%Z <= n)%Z ->
((power k n) >= 1%Z)%Z /\
(((power k n) > 0%Z)%Z /\ ((power k n) <= (power k (n + 1%Z)%Z))%Z).
Axiom strict_positive_int_exp :
forall (k:Z) (n:Z), (1%Z < k)%Z -> (0%Z < n)%Z ->
((power k n) > 1%Z)%Z /\
(((power k (n - 1%Z)%Z) < (power k n))%Z /\
((power k n) < (power k (n + 1%Z)%Z))%Z).
Axiom power_minus_one :
forall (i:Z), (0%Z <= i)%Z ->
(((int.EuclideanDivision.mod1 i 2%Z) = 0%Z) -> ((power (-1%Z)%Z i) = 1%Z)) /\
(((int.EuclideanDivision.mod1 i 2%Z) = 1%Z) ->
((power (-1%Z)%Z i) = (-1%Z)%Z)).
Axiom growing_exp :
forall (k:Z) (m:Z) (n:Z), (1%Z <= k)%Z -> ((0%Z <= m)%Z /\ (m <= n)%Z) ->
((power k m) <= (power k n))%Z.
Axiom strict_growing_exp :
forall (k:Z) (m:Z) (n:Z), (1%Z < k)%Z -> ((0%Z <= m)%Z /\ (m < n)%Z) ->
((power k m) < (power k n))%Z.
Axiom unicity_exp :
forall (k:Z) (m:Z) (n:Z), (1%Z < k)%Z -> (0%Z <= m)%Z -> (0%Z <= n)%Z ->
((power k m) = (power k n)) <-> (m = n).
Axiom bounded_sum_exp :
forall (i:Z) (j:Z) (m:Z) (n:Z), (0%Z <= m)%Z -> (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z m))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
(((i * (power 2%Z n))%Z + j)%Z < (power 2%Z (m + n)%Z))%Z.
Axiom power_minus_one1 :
forall (i:Z), (i >= 0%Z)%Z ->
(((int.EuclideanDivision.mod1 i 2%Z) = 0%Z) -> ((power (-1%Z)%Z i) = 1%Z)) /\
(((int.EuclideanDivision.mod1 i 2%Z) = 1%Z) ->
((power (-1%Z)%Z i) = (-1%Z)%Z)).
Parameter kth_right: Z -> Z -> Z -> (Z -> Z) -> Z.
Axiom kth_right_def :
forall (i:Z) (k:Z) (h:Z) (f:Z -> Z), (0%Z <= i)%Z -> (1%Z <= k)%Z ->
(forall (l:Z), (((h - k)%Z <= l)%Z /\ (l < h)%Z) -> (0%Z < (f l))%Z) ->
((kth_right i k h f) =
(int.EuclideanDivision.mod1
(int.EuclideanDivision.div i (ind_iproduct f ((h - k)%Z + 1%Z)%Z h))
(f (h - k)%Z))).
Axiom kth_right_spec :
forall (i:Z) (k:Z) (h:Z) (f:Z -> Z), (0%Z <= i)%Z -> (1%Z <= k)%Z ->
(forall (l:Z), (((h - k)%Z <= l)%Z /\ (l < h)%Z) -> (0%Z < (f l))%Z) ->
(0%Z <= (kth_right i k h f))%Z /\ ((kth_right i k h f) < (f (h - k)%Z))%Z.
Axiom kth_right_eq :
forall (i:Z) (k:Z) (h:Z) (f:Z -> Z) (g:Z -> Z), (0%Z <= i)%Z ->
(1%Z <= k)%Z ->
(forall (l:Z), (((h - k)%Z <= l)%Z /\ (l <= h)%Z) -> (0%Z < (f l))%Z) ->
(forall (l:Z), (((h - k)%Z <= l)%Z /\ (l <= h)%Z) -> ((f l) = (g l))) ->
((kth_right i k h f) = (kth_right i k h g)).
Axiom kth_right_trans :
forall (i:Z) (k:Z) (h:Z) (t1:Z) (f:Z -> Z), (0%Z <= i)%Z -> (1%Z <= k)%Z ->
(forall (l:Z), (0%Z < (f l))%Z) -> (0%Z <= h)%Z -> (0%Z <= t1)%Z ->
((kth_right (int.EuclideanDivision.div i (ind_iproduct f h (h + t1)%Z)) k h
f)
= (kth_right i (k + t1)%Z (h + t1)%Z f)).
Parameter kth_left: Z -> Z -> Z -> Z -> (Z -> Z) -> Z.
Axiom kth_left_def :
forall (i:Z) (k:Z) (l:Z) (h:Z) (f:Z -> Z), (0%Z <= i)%Z -> (0%Z <= l)%Z ->
((1%Z <= k)%Z /\ (k <= (h - l)%Z)%Z) ->
(forall (ind:Z), ((l <= ind)%Z /\ (ind < h)%Z) -> (0%Z < (f ind))%Z) ->
((kth_left i k l h f) = (kth_right i (((h - l)%Z - k)%Z + 1%Z)%Z h f)).
Axiom kth_left_spec :
forall (i:Z) (k:Z) (l:Z) (h:Z) (f:Z -> Z), (0%Z <= i)%Z -> (0%Z <= l)%Z ->
((1%Z <= k)%Z /\ (k <= (h - l)%Z)%Z) ->
(forall (ind:Z), ((l <= ind)%Z /\ (ind < h)%Z) -> (0%Z < (f ind))%Z) ->
((kth_left i k l h f) =
(int.EuclideanDivision.mod1
(int.EuclideanDivision.div i (ind_iproduct f (l + k)%Z h))
(f ((l + k)%Z - 1%Z)%Z))) /\
((0%Z <= (kth_left i k l h f))%Z /\
((kth_left i k l h f) < (f ((l + k)%Z - 1%Z)%Z))%Z).
Axiom kth_left_eq :
forall (i:Z) (k:Z) (l:Z) (h:Z) (f:Z -> Z) (g:Z -> Z), (0%Z <= i)%Z ->
((1%Z <= k)%Z /\ (k <= (h - l)%Z)%Z) -> (0%Z <= l)%Z ->
(forall (ind:Z), ((l <= ind)%Z /\ (ind < h)%Z) ->
((f ind) = (g ind)) /\ ((g ind) > 0%Z)%Z) ->
((kth_left i k l h f) = (kth_left i k l h g)).
Axiom kth_left_to_mod_div :
forall (i:Z) (k:Z) (l:Z) (h:Z) (f:Z -> Z), (0%Z <= i)%Z -> (0%Z <= l)%Z ->
((1%Z <= k)%Z /\ (k <= (h - l)%Z)%Z) ->
(forall (ind:Z), ((l <= ind)%Z /\ (ind <= h)%Z) -> ((f ind) > 0%Z)%Z) ->
((kth_left i k l h f) =
(int.EuclideanDivision.mod1
(int.EuclideanDivision.div i (ind_iproduct f (l + k)%Z h))
(f ((l + k)%Z - 1%Z)%Z))).
Axiom kth_left_trans :
forall (i:Z) (k:Z) (l:Z) (h:Z) (f:Z -> Z), (0%Z <= i)%Z -> (0%Z <= l)%Z ->
((1%Z <= k)%Z /\ (k < (h - l)%Z)%Z) ->
(forall (ind:Z), ((l <= ind)%Z /\ (ind <= h)%Z) -> ((f ind) > 0%Z)%Z) ->
((kth_left i k l h f) =
(kth_left (int.EuclideanDivision.div i (f (h - 1%Z)%Z)) k l (h - 1%Z)%Z f)).
Axiom div_isum_exponents :
forall (i:Z) (k:Z) (n:Z) (m:Z), (0%Z <= i)%Z -> (0%Z < k)%Z ->
(0%Z <= n)%Z -> (0%Z <= m)%Z ->
((power k (n + m)%Z) = ((power k n) * (power k m))%Z) /\
(((power k (n + 1%Z)%Z) = ((power k n) * k)%Z) /\
(((power k 1%Z) = k) /\
(((int.EuclideanDivision.div (int.EuclideanDivision.div i (power k n))
(power k m))
= (int.EuclideanDivision.div i (power k (n + m)%Z))) /\
((int.EuclideanDivision.div (int.EuclideanDivision.div i (power k n)) k)
= (int.EuclideanDivision.div i (power k (n + 1%Z)%Z)))))).
Parameter divp: Z -> Z -> Z.
Axiom divp_def :
forall (i:Z) (j:Z), (0%Z <= i)%Z -> (0%Z < j)%Z ->
((divp i j) = ((int.EuclideanDivision.div i j) * j)%Z).
Axiom divp_spec :
forall (i:Z) (j:Z), (0%Z <= i)%Z -> (0%Z < j)%Z ->
(i = ((divp i j) + (int.EuclideanDivision.mod1 i j))%Z) /\
((((divp i j) <= i)%Z /\ (i < (((divp i j) + 1%Z)%Z * j)%Z)%Z) /\
((i > j)%Z -> ((divp i j) > 0%Z)%Z)).
Axiom kth_right_div_mod :
forall (i:Z) (k:Z) (h:Z) (f:Z -> Z), (0%Z <= i)%Z -> (1%Z <= k)%Z ->
(forall (k1:Z), (0%Z < (f k1))%Z) ->
((kth_right i k h f) =
(int.EuclideanDivision.div
(int.EuclideanDivision.mod1 i (ind_iproduct f (h - k)%Z h))
(ind_iproduct f ((h - k)%Z + 1%Z)%Z h))).
Axiom kth_head :
forall (i:Z) (h:Z) (f:Z -> Z), (0%Z <= i)%Z -> (1%Z <= h)%Z ->
(forall (k:Z), (0%Z < (f k))%Z) ->
((kth_right i 1%Z h f) = (int.EuclideanDivision.mod1 i (f (h - 1%Z)%Z))).
Parameter weighted_kth_right: Z -> Z -> Z -> (Z -> Z) -> Z.
Axiom weighted_kth_right_def :
forall (i:Z) (k:Z) (h:Z) (f:Z -> Z), (0%Z <= i)%Z ->
(forall (k1:Z), (0%Z < (f k1))%Z) -> (1%Z <= k)%Z ->
((weighted_kth_right i k h f) =
((kth_right i k h f) * (ind_iproduct f ((h - k)%Z + 1%Z)%Z h))%Z).
Axiom weighted_kth_right_ :
forall (i:Z) (k:Z) (h:Z) (f:Z -> Z), (1%Z <= k)%Z -> (0%Z <= i)%Z ->
(forall (k1:Z), (0%Z < (f k1))%Z) ->
((int.EuclideanDivision.mod1 i (ind_iproduct f (h - k)%Z h)) =
((weighted_kth_right i k h f) +
(int.EuclideanDivision.mod1 i (ind_iproduct f ((h - k)%Z + 1%Z)%Z h)))%Z).
Axiom kth_right_decomposition :
forall (i:Z) (k:Z) (h:Z) (f:Z -> Z), (0%Z <= i)%Z -> (1%Z <= k)%Z ->
(forall (k1:Z), (0%Z < (f k1))%Z) ->
((int.EuclideanDivision.mod1 i (ind_iproduct f (h - k)%Z h)) =
(ind_isum (fun (a:Z) => (weighted_kth_right i a h f)) 1%Z (k + 1%Z)%Z)).
Axiom kth_left_div_mod :
forall (i:Z) (k:Z) (l:Z) (h:Z) (f:Z -> Z), (0%Z <= i)%Z ->
((0%Z <= l)%Z /\ (l <= h)%Z) -> ((1%Z <= k)%Z /\ (k <= (h - l)%Z)%Z) ->
(forall (k1:Z), (0%Z < (f k1))%Z) ->
((kth_left i k l h f) =
(int.EuclideanDivision.div
(int.EuclideanDivision.mod1 i (ind_iproduct f ((l + k)%Z - 1%Z)%Z h))
(ind_iproduct f (l + k)%Z h))).
Parameter weighted_kth_left: Z -> Z -> Z -> Z -> (Z -> Z) -> Z.
Axiom weighted_kth_left_def :
forall (i:Z) (k:Z) (l:Z) (h:Z) (f:Z -> Z), (0%Z <= i)%Z -> (l <= h)%Z ->
((1%Z <= k)%Z /\ (k <= (h - l)%Z)%Z) ->
(forall (k1:Z), (0%Z < (f k1))%Z) ->
((weighted_kth_left i k l h f) =
(weighted_kth_right i (((h - l)%Z - k)%Z + 1%Z)%Z h f)).
Axiom weighted_kth_left_ :
forall (i:Z) (k:Z) (l:Z) (h:Z) (f:Z -> Z), (0%Z <= i)%Z -> (l <= h)%Z ->
((1%Z <= k)%Z /\ (k <= (h - l)%Z)%Z) ->
(forall (k1:Z), (0%Z < (f k1))%Z) ->
((int.EuclideanDivision.mod1 i (ind_iproduct f ((l + k)%Z - 1%Z)%Z h)) =
((weighted_kth_left i k l h f) +
(int.EuclideanDivision.mod1 i (ind_iproduct f (l + k)%Z h)))%Z).
Axiom bounded_kth_left_decomposition :
forall (i:Z) (k:Z) (l:Z) (h:Z) (f:Z -> Z), (0%Z <= i)%Z -> (l <= h)%Z ->
((1%Z <= k)%Z /\ (k <= (h - l)%Z)%Z) ->
(forall (k1:Z), (0%Z < (f k1))%Z) ->
((int.EuclideanDivision.mod1 i (ind_iproduct f ((l + k)%Z - 1%Z)%Z h)) =
(ind_isum (fun (a:Z) => (weighted_kth_left i a l h f)) k
((h - l)%Z + 1%Z)%Z)).
Axiom kth_left_decomposition :
forall (i:Z) (l:Z) (h:Z) (f:Z -> Z),
((0%Z <= i)%Z /\ (i < (ind_iproduct f l h))%Z) -> (l < h)%Z ->
(forall (k:Z), (0%Z < (f k))%Z) ->
(i =
(ind_isum (fun (a:Z) => (weighted_kth_left i a l h f)) 1%Z
((h - l)%Z + 1%Z)%Z)).
Parameter binary: (Z -> Z) -> Prop.
Axiom binary_def :
forall (t1:Z -> Z),
(binary t1) <-> forall (k:Z), (0%Z <= (t1 k))%Z /\ ((t1 k) < 2%Z)%Z.
Axiom set_binary :
forall (t1:Z -> Z),
(forall (k:Z), (0%Z <= (t1 k))%Z /\ ((t1 k) < 2%Z)%Z) -> binary t1.
Axiom get_binary :
forall (t1:Z -> Z), (binary t1) -> forall (k:Z),
(0%Z <= (t1 k))%Z /\ ((t1 k) < 2%Z)%Z.
Parameter shift: forall {a:Type} {a_WT:WhyType a}, (Z -> a) -> Z -> Z -> a.
Axiom shift_def :
forall {a:Type} {a_WT:WhyType a},
forall (f:Z -> a) (i:Z) (k:Z), ((shift f i k) = (f (k + i)%Z)).
Axiom shift_value :
forall {a:Type} {a_WT:WhyType a},
forall (f:Z -> a) (i:Z) (k:Z), ((shift f i k) = (f (k + i)%Z)).
Axiom shiftz :
forall {a:Type} {a_WT:WhyType a},
forall (f:Z -> a) (k:Z), ((shift f 0%Z k) = (f k)).
Axiom shiftz_gen :
forall {a:Type} {a_WT:WhyType a},
forall (f:Z -> a) (i:Z) (k:Z), (i = 0%Z) -> ((shift f i k) = (f k)).
Axiom shiftz_quant :
forall {a:Type} {a_WT:WhyType a},
forall (f:Z -> a),
((((fun (y0:Z -> a) (y1:Z) (y2:Z) => (shift y0 y1 y2)) f) 0%Z) = f).
Axiom shiftz_quant_rev :
forall {a:Type} {a_WT:WhyType a},
forall (f:Z -> a),
(f = (((fun (y0:Z -> a) (y1:Z) (y2:Z) => (shift y0 y1 y2)) f) 0%Z)).
Parameter concat_fun:
forall {a:Type} {a_WT:WhyType a}, (Z -> a) -> (Z -> a) -> Z -> Z -> a.
Axiom concat_fun_def :
forall {a:Type} {a_WT:WhyType a},
forall (f:Z -> a) (g:Z -> a) (i:Z) (k:Z),
((k < i)%Z -> ((concat_fun f g i k) = (f k))) /\
(~ (k < i)%Z -> ((concat_fun f g i k) = (g (k - i)%Z))).
Axiom shift_add :
forall {a:Type} {a_WT:WhyType a},
forall (f:Z -> a) (i:Z) (j:Z) (k:Z),
((shift (((fun (y0:Z -> a) (y1:Z) (y2:Z) => (shift y0 y1 y2)) f) j) i k) =
(shift f (i + j)%Z k)).
Axiom concat_fun_value :
forall {a:Type} {a_WT:WhyType a},
forall (f:Z -> a) (g:Z -> a) (i:Z) (k:Z),
((k < i)%Z -> ((concat_fun f g i k) = (f k))) /\
(~ (k < i)%Z -> ((concat_fun f g i k) = (g (k - i)%Z))).
Axiom concat_eq :
forall {a:Type} {a_WT:WhyType a},
forall (f1:Z -> a) (g1:Z -> a) (f2:Z -> a) (g2:Z -> a) (i1:Z) (i2:Z) (k:Z),
(forall (l:Z), (l < i1)%Z -> ((f1 l) = (f2 l))) ->
(forall (l:Z), (l >= 0%Z)%Z -> ((g1 l) = (g2 l))) -> (i1 = i2) ->
((concat_fun f1 g1 i1 k) = (concat_fun f2 g2 i2 k)).
Parameter mod_func:
forall {a:Type} {a_WT:WhyType a}, (Z -> a) -> Z -> Z -> a.
Axiom mod_func_def :
forall {a:Type} {a_WT:WhyType a},
forall (f:Z -> a) (k:Z) (i:Z), (k > 0%Z)%Z ->
((mod_func f k i) = (f (int.EuclideanDivision.mod1 i k))).
Axiom mod_func_inf :
forall {a:Type} {a_WT:WhyType a},
forall (f:Z -> a) (k:Z) (i:Z), (k > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < k)%Z) -> ((mod_func f k i) = (f i)).
Axiom shift_mod :
forall {a:Type} {a_WT:WhyType a},
forall (f:Z -> a) (k:Z) (i:Z), (k > 0%Z)%Z ->
((mod_func f k i) =
(shift (((fun (y0:Z -> a) (y1:Z) (y2:Z) => (mod_func y0 y1 y2)) f) k) k i)).
Axiom shift_mod_rev :
forall {a:Type} {a_WT:WhyType a},
forall (f:Z -> a) (k:Z) (i:Z), (k > 0%Z)%Z ->
((shift (((fun (y0:Z -> a) (y1:Z) (y2:Z) => (mod_func y0 y1 y2)) f) k) k i)
= (mod_func f k i)).
Parameter head_bit: Z -> Z -> Z.
Axiom head_bit_def :
forall (i:Z) (k:Z), (k > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z k))%Z) ->
((head_bit i k) = (int.EuclideanDivision.div i (power 2%Z (k - 1%Z)%Z))).
Axiom head_bit_spec :
forall (i:Z) (k:Z), (k > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z k))%Z) ->
(0%Z <= (head_bit i k))%Z /\ ((head_bit i k) <= 1%Z)%Z.
Parameter tail_bits: Z -> Z -> Z.
Axiom tail_bits_def :
forall (i:Z) (k:Z), (k > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z k))%Z) ->
((tail_bits i k) = (int.EuclideanDivision.mod1 i (power 2%Z (k - 1%Z)%Z))).
Axiom tail_bits_spec :
forall (i:Z) (k:Z), (k > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z k))%Z) ->
(0%Z <= (tail_bits i k))%Z /\
((tail_bits i k) <= (power 2%Z (k - 1%Z)%Z))%Z.
Parameter ht_to_int: Z -> Z -> Z -> Z.
Axiom ht_to_int_def :
forall (hi:Z) (ti:Z) (k:Z), (0%Z < k)%Z ->
((0%Z <= hi)%Z /\ (hi < 2%Z)%Z) ->
((0%Z <= ti)%Z /\ (ti < (power 2%Z (k - 1%Z)%Z))%Z) ->
((ht_to_int hi ti k) = ((hi * (power 2%Z (k - 1%Z)%Z))%Z + ti)%Z).
Axiom head_tail_inv :
forall (i:Z) (k:Z), (k > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z k))%Z) ->
((ht_to_int (head_bit i k) (tail_bits i k) k) = i).
Axiom ht_to_int_head :
forall (i:Z) (ti:Z) (k:Z), (k > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z k))%Z) ->
((0%Z <= ti)%Z /\ (ti < (power 2%Z (k - 1%Z)%Z))%Z) ->
((head_bit (ht_to_int (head_bit i k) ti k) k) = (head_bit i k)).
Axiom ht_to_int_tail :
forall (hi:Z) (i:Z) (k:Z), (k > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z k))%Z) ->
((0%Z <= hi)%Z /\ (hi < 2%Z)%Z) ->
((tail_bits (ht_to_int hi (tail_bits i k) k) k) = (tail_bits i k)).
Axiom concat_fun_bin_i :
forall (f:Z -> Z) (g:Z -> Z) (i:Z) (k:Z), (binary f) -> (binary g) ->
(0%Z <= (concat_fun f g i k))%Z /\ ((concat_fun f g i k) < 2%Z)%Z.
Axiom shift_bin_i :
forall (f:Z -> Z) (i:Z) (k:Z), (binary f) ->
(0%Z <= (shift f i k))%Z /\ ((shift f i k) < 2%Z)%Z.
Axiom concat_fun_bin :
forall (f:Z -> Z) (g:Z -> Z) (i:Z), (binary f) -> (binary g) ->
binary
((((fun (y0:Z -> Z) (y1:Z -> Z) (y2:Z) (y3:Z) => (concat_fun y0 y1 y2 y3))
f)
g)
i).
Axiom mod_func_bin :
forall (f:Z -> Z) (k:Z), (k > 0%Z)%Z -> (binary f) ->
binary (((fun (y0:Z -> Z) (y1:Z) (y2:Z) => (mod_func y0 y1 y2)) f) k).
Axiom shift_bin :
forall (f:Z -> Z) (i:Z), (binary f) ->
binary (((fun (y0:Z -> Z) (y1:Z) (y2:Z) => (shift y0 y1 y2)) f) i).
Axiom binary_comp :
forall (f:Z -> Z) (g:Z -> Z), (binary f) -> binary (fun (x:Z) => (f (g x))).
Axiom set_is_all_binary :
forall (t1:Z -> Z),
(forall (k:Z), (0%Z <= (t1 k))%Z /\ ((t1 k) < 2%Z)%Z) -> binary t1.
Parameter nary_length: Z -> Z -> Z.
Axiom nary_length_spec :
forall (i:Z) (n:Z), (1%Z < n)%Z -> (0%Z <= i)%Z ->
((0%Z < i)%Z ->
((power n ((nary_length i n) - 1%Z)%Z) <= i)%Z /\
(i < (power n (nary_length i n)))%Z) /\
(((i < n)%Z -> ((nary_length i n) = 1%Z)) /\
(((nary_length i n) >= 1%Z)%Z /\
(i = (int.EuclideanDivision.mod1 i (power n (nary_length i n)))))).
Parameter binary_length: Z -> Z.
Axiom binary_length_def :
forall (i:Z), (0%Z <= i)%Z -> ((binary_length i) = (nary_length i 2%Z)).
Axiom binary_length_spec :
forall (i:Z), (0%Z <= i)%Z ->
((0%Z < i)%Z ->
((power 2%Z ((binary_length i) - 1%Z)%Z) <= i)%Z /\
(i < (power 2%Z (binary_length i)))%Z) /\
(((i < 2%Z)%Z -> ((binary_length i) = 1%Z)) /\
(((binary_length i) >= 1%Z)%Z /\
(i = (int.EuclideanDivision.mod1 i (power 2%Z (binary_length i)))))).
Axiom set_binary_length :
forall (i:Z) (k:Z), (0%Z <= i)%Z -> (0%Z <= k)%Z ->
((0%Z < i)%Z -> ((power 2%Z (k - 1%Z)%Z) <= i)%Z /\ (i < (power 2%Z k))%Z) ->
((i < 2%Z)%Z -> (k = 1%Z)) -> (k = (binary_length i)).
Axiom set_binary_length_b :
forall (i:Z) (k:Z), (0%Z <= i)%Z -> (0%Z < k)%Z -> (i < (power 2%Z k))%Z ->
((binary_length i) <= k)%Z.
Axiom real : forall (x:t), (real_ x) -> (x = (r_to_t (real_part x))).
Axiom pure_im :
forall (x:t), (pure_im_ x) -> (x = (infix_asdt im (r_to_t (im_part x)))).
Axiom im_dec : ((real_part im) = 0%R) /\ ((im_part im) = 1%R).
Axiom tone_dec : ((real_part tone) = 1%R) /\ ((im_part tone) = 0%R).
Axiom tzero_dec : ((real_part tzero) = 0%R) /\ ((im_part tzero) = 0%R).
Axiom ttwo_dec : ((real_part ttwo) = 2%R) /\ ((im_part ttwo) = 0%R).
Parameter i_to_t: Z -> t.
Axiom i_to_t_def : forall (i:Z), ((i_to_t i) = (r_to_t (from_int i))).
Axiom i_to_t_spec : forall (i:Z), real_ (i_to_t i).
Axiom i_to_t_zero : ((i_to_t 0%Z) = tzero).
Axiom i_to_t_eq : forall (i:Z) (j:Z), (i = j) -> ((i_to_t i) = (i_to_t j)).
Axiom i_to_t_nzero : forall (i:Z), ~ (i = 0%Z) -> ~ ((i_to_t i) = tzero).
Axiom i_to_t_one : ((i_to_t 1%Z) = tone).
Axiom i_to_t_add :
forall (i:Z) (j:Z),
((infix_pldt (i_to_t i) (i_to_t j)) = (i_to_t (i + j)%Z)).
Axiom i_to_t_add_rev :
forall (i:Z) (j:Z),
((i_to_t (i + j)%Z) = (infix_pldt (i_to_t i) (i_to_t j))).
Axiom i_to_t_ttwo : ((i_to_t 2%Z) = ttwo).
Axiom i_to_t_pos :
forall (a:Z), (0%Z <= a)%Z -> infix_lseqdt tzero (i_to_t a).
Axiom i_to_t_mult_pos :
forall (i:Z) (j:Z), (0%Z <= j)%Z ->
((infix_asdt (i_to_t i) (i_to_t j)) = (i_to_t (i * j)%Z)).
Axiom i_to_t_mult :
forall (i:Z) (j:Z),
((infix_asdt (i_to_t i) (i_to_t j)) = (i_to_t (i * j)%Z)).
Axiom i_to_t_mult_rev :
forall (i:Z) (j:Z),
((i_to_t (i * j)%Z) = (infix_asdt (i_to_t i) (i_to_t j))).
Axiom i_to_t_mult_assoc :
forall (x:t) (i:Z) (j:Z),
((infix_asdt x (i_to_t (i * j)%Z)) =
(infix_asdt (infix_asdt x (i_to_t i)) (i_to_t j))).
Axiom i_to_t_mult_assoc_rev :
forall (x:t) (i:Z) (j:Z),
((infix_asdt (infix_asdt x (i_to_t i)) (i_to_t j)) =
(infix_asdt x (i_to_t (i * j)%Z))).
Axiom i_to_t_sub :
forall (i:Z) (j:Z),
((infix_mndt (i_to_t i) (i_to_t j)) = (i_to_t (i - j)%Z)).
Axiom i_to_t_opp :
forall (i:Z), ((i_to_t (-i)%Z) = (prefix_mndt (i_to_t i))).
Axiom i_to_t_div :
forall (i:Z) (j:Z), ~ (j = 0%Z) ->
((infix_sldt (i_to_t (i * j)%Z) (i_to_t j)) = (i_to_t i)).
Axiom i_to_t_minus_mult :
forall (i:Z) (j:Z),
((infix_asdt (i_to_t (-i)%Z) (i_to_t j)) =
(infix_asdt (i_to_t i) (i_to_t (-j)%Z))).
Axiom compat_i_to_t_infeq :
forall (a:Z) (b:Z), (a <= b)%Z -> infix_lseqdt (i_to_t a) (i_to_t b).
Axiom compat_i_to_t_inf :
forall (a:Z) (b:Z), (a < b)%Z -> infix_lsdt (i_to_t a) (i_to_t b).
Axiom compat_i_to_t_supeq :
forall (a:Z) (b:Z), (a >= b)%Z -> infix_gteqdt (i_to_t a) (i_to_t b).
Axiom compat_i_to_t_sup :
forall (a:Z) (b:Z), (a > b)%Z -> infix_gtdt (i_to_t a) (i_to_t b).
Axiom positive_int_squrt :
forall (i:Z), (i > 0%Z)%Z -> infix_gtdt (square_rt (i_to_t i)) tzero.
Axiom non_null_int_squrt :
forall (i:Z), (i > 0%Z)%Z -> ~ ((square_rt (i_to_t i)) = tzero).
Axiom ind_sum_constant :
forall (f:Z -> t) (valu:t) (i:Z) (j:Z), (i <= j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = valu)) ->
((ind_sum f i j) = (infix_asdt valu (i_to_t (j - i)%Z))).
Axiom abs_eqinf :
forall (x:Z) (y:Z), ((x <= y)%Z /\ (y <= 0%Z)%Z) ->
((ZArith.BinInt.Z.abs x) >= (ZArith.BinInt.Z.abs y))%Z.
Axiom abs_inf :
forall (x:Z) (y:Z), ((0%Z < x)%Z /\ ((x < y)%Z /\ (y <= 0%Z)%Z)) ->
((ZArith.BinInt.Z.abs x) > (ZArith.BinInt.Z.abs y))%Z.
Axiom abs_eqsup :
forall (x:Z) (y:Z), ((0%Z >= x)%Z /\ (x >= y)%Z) ->
((ZArith.BinInt.Z.abs x) <= (ZArith.BinInt.Z.abs y))%Z.
Axiom abs_sup :
forall (x:Z) (y:Z), ((0%Z >= x)%Z /\ (x > y)%Z) ->
((ZArith.BinInt.Z.abs x) < (ZArith.BinInt.Z.abs y))%Z.
Axiom inv_negeq :
forall (x:Z), (0%Z >= x)%Z -> ((ZArith.BinInt.Z.abs x) >= 0%Z)%Z.
Axiom inv_neg1 :
forall (x:Z), (0%Z > x)%Z -> ((ZArith.BinInt.Z.abs x) > 0%Z)%Z.
Parameter cpower: t -> Z -> t.
Axiom Cpower_zero : forall (i:t), ((cpower i 0%Z) = tone).
Axiom Cpower_one : forall (i:t), ((cpower i 1%Z) = i).
Axiom Cpower_sum :
forall (i:t), forall (n:Z) (m:Z), ((i = tzero) -> ~ (n = (-m)%Z)) ->
((cpower i (n + m)%Z) = (infix_asdt (cpower i n) (cpower i m))).
Axiom zero_poower : forall (e:Z), ~ (e = 0%Z) -> ((cpower tzero e) = tzero).
Parameter squarert_two: t.
Axiom squarert_two_def : (squarert_two = (square_rt ttwo)).
Axiom real_squarert_two : real_ squarert_two.
Axiom squarertTwo : ((cpower squarert_two 2%Z) = ttwo).
Axiom complete_rt_two :
forall (a:t), (a = (infix_sldt squarert_two ttwo)) ->
((infix_asdt squarert_two a) = tone).
Axiom cpower_sum :
forall (x:t) (n:Z) (m:Z), ((x = tzero) -> ~ (n = (-m)%Z)) ->
((cpower x (n + m)%Z) = (infix_asdt (cpower x n) (cpower x m))).
Axiom cpower_one : forall (x:t) (n:Z), (n = 1%Z) -> ((cpower x n) = x).
Axiom cpower_sum_rev :
forall (x:t) (n:Z) (m:Z), ((x = tzero) -> ~ (n = (-m)%Z)) ->
((infix_asdt (cpower x n) (cpower x m)) = (cpower x (n + m)%Z)).
Axiom cpower_plus_one :
forall (e:t) (i:Z), ((e = tzero) -> ~ (i = (-1%Z)%Z)) ->
((cpower e (i + 1%Z)%Z) = (infix_asdt (cpower e i) e)).
Axiom cpower_zero : forall (e:t), ((cpower e 0%Z) = tone).
Axiom cpower_eq :
forall (e:t) (e':t) (i:Z) (i':Z), (e = e') -> (i = i') ->
((cpower e i) = (cpower e' i')).
Axiom cpower_inv :
forall (e:t) (i:Z), ~ (e = tzero) ->
((infix_asdt (cpower e i) (cpower e (-i)%Z)) = tone).
Axiom cpower_inv_rew :
forall (e:t) (i:Z), ~ (e = tzero) ->
((cpower e i) = (infix_sldt tone (cpower e (-i)%Z))).
Axiom inv_cpower :
forall (e:t) (i:Z), ~ ((cpower e i) = tzero) ->
((infix_sldt tone (cpower e i)) = (cpower e (-i)%Z)).
Axiom cpower_mult_split :
forall (x:t) (y:t) (m:Z), (0%Z <= m)%Z ->
((cpower (infix_asdt x y) m) = (infix_asdt (cpower x m) (cpower y m))).
Axiom cpower_inv_out :
forall (x:t) (y:t), ~ (y = tzero) ->
((infix_asdt (cpower (infix_asdt (infix_sldt tone (square_rt y)) x) 2%Z) y)
= (cpower x 2%Z)).
Axiom cpower_subst :
forall (x:t) (n:Z) (m:Z), ((x = tzero) -> ~ (n = m)) ->
((infix_asdt (infix_sldt tone (cpower x n)) (cpower x m)) =
(cpower x (m - n)%Z)).
Axiom cpower_tone_pos :
forall (m:Z), (m >= 0%Z)%Z -> ((cpower tone m) = tone).
Axiom mult_cpower :
forall (x:t) (x':t) (i:Z), (0%Z <= i)%Z ->
((infix_asdt (cpower x i) (cpower x' i)) = (cpower (infix_asdt x x') i)).
Axiom mult_cpower_rev :
forall (x:t) (x':t) (i:Z), (0%Z <= i)%Z ->
((cpower (infix_asdt x x') i) = (infix_asdt (cpower x i) (cpower x' i))).
Axiom cpower_iterate :
forall (e:t) (i:Z), (0%Z <= i)%Z ->
((cpower e i) =
(int_iterate (fun (y0:t) (y1:t) => (infix_asdt y0 y1))
((fun (y0:t) (y1:Z) => (const y0 y1)) e) 0%Z i)).
Axiom cpower_modulus :
forall (x:t) (n:Z), (0%Z <= n)%Z ->
((modulus (cpower x n)) = (cpower (modulus x) n)) /\
(((n > 0%Z)%Z -> (infix_lsdt (modulus x) tone) ->
infix_lsdt (modulus (cpower x n)) tone) /\
(((n > 0%Z)%Z -> ((modulus x) = tone) -> ((modulus (cpower x n)) = tone)) /\
(((n > 0%Z)%Z -> (infix_gtdt (modulus x) tone) ->
infix_gtdt (modulus (cpower x n)) tone) /\
(((n > 0%Z)%Z -> (infix_lsdt (modulus (cpower x n)) tone) ->
infix_lsdt (modulus x) tone) /\
(((n > 0%Z)%Z -> ((modulus (cpower x n)) = tone) ->
((modulus x) = tone)) /\
((n > 0%Z)%Z -> (infix_gtdt (modulus (cpower x n)) tone) ->
infix_gtdt (modulus x) tone)))))).
Axiom cpower_mult_pre :
forall (x:t) (n:Z) (m:Z), (0%Z <= m)%Z ->
((cpower x (n * m)%Z) = (cpower (cpower x n) m)).
Axiom cpower_mult :
forall (x:t) (n:Z) (m:Z), ((cpower x (n * m)%Z) = (cpower (cpower x n) m)).
Axiom cpower_mult_rev :
forall (x:t) (n:Z) (m:Z), ((cpower (cpower x n) m) = (cpower x (n * m)%Z)).
Axiom non_zero_cpower_pos :
forall (i:t) (n:Z), ~ (i = tzero) -> (n >= 0%Z)%Z ->
~ ((cpower i n) = tzero).
Axiom inv_cpower_ :
forall (e:t) (i:Z), ~ (e = tzero) ->
((infix_sldt tone (cpower e i)) = (cpower e (-i)%Z)).
Axiom zero_cpower_pos :
forall (n:Z), (n > 0%Z)%Z -> ((cpower tzero n) = tzero).
Axiom zero_cpower : forall (n:Z), ~ (n = 0%Z) -> ((cpower tzero n) = tzero).
Axiom non_zero_cpower :
forall (i:t) (n:Z), ~ (i = tzero) -> ~ ((cpower i n) = tzero).
Axiom real_cpower_pos :
forall (elt:t) (i:Z), (real_ elt) -> (0%Z <= i)%Z -> real_ (cpower elt i).
Axiom real_cpower :
forall (elt:t) (i:Z), (real_ elt) -> real_ (cpower elt i).
Axiom real_cpower_is_pos :
forall (elt:t) (i:Z), (real_ elt) -> (infix_lseqdt tzero elt) ->
(0%Z <= i)%Z -> infix_lseqdt tzero (cpower elt i).
Axiom real_cpower_is_strict_pos :
forall (elt:t) (i:Z), (real_ elt) -> (infix_lsdt tzero elt) ->
(0%Z <= i)%Z -> infix_lsdt tzero (cpower elt i).
Axiom real_modulus_square :
forall (x:t), (real_ x) -> ((cpower (modulus x) 2%Z) = (cpower x 2%Z)).
Axiom real_modulus_pos :
forall (x:t), (real_ x) -> (infix_gteqdt x tzero) -> ((modulus x) = x).
Axiom square_frac_modulus :
forall (x:t) (y:t),
((cpower (modulus (infix_sldt x y)) 2%Z) =
(infix_sldt (cpower (modulus x) 2%Z) (cpower (modulus y) 2%Z))).
Axiom extract_2_sq_modulus :
forall (x:t) (y:t) (a:t), ~ (a = tzero) -> ~ (y = tzero) ->
((infix_sldt (cpower (modulus x) 2%Z) (cpower (modulus y) 2%Z)) =
(infix_sldt (infix_asdt a (cpower (modulus x) 2%Z))
(infix_asdt a (cpower (modulus y) 2%Z)))).
Axiom cpower_2_modulus_simpl :
forall (x:t) (y:t) (z:t), ~ (x = tzero) -> ~ (y = tzero) ->
~ (z = tzero) ->
((infix_sldt (cpower (modulus (infix_asdt x y)) 2%Z)
(cpower (modulus (infix_asdt z y)) 2%Z))
= (infix_sldt (cpower (modulus x) 2%Z) (cpower (modulus z) 2%Z))).
Axiom cpower_cpower :
forall (x:t) (a:Z) (b:Z), ((cpower (cpower x a) b) = (cpower x (a * b)%Z)).
Axiom pre_cond_int_ :
forall (a:t) (b:t) (c:t), (infix_lsdt a b) -> (infix_lsdt tzero c) ->
infix_lsdt (infix_asdt a c) (infix_asdt b c).
Axiom growing_mult1 :
forall (n:t) (m:t), (infix_lseqdt tzero n) -> (infix_lseqdt tone m) ->
infix_lseqdt n (infix_asdt n m).
Axiom strict_growing_mult_pos :
forall (n:t) (m:t), (infix_lsdt tone n) -> (infix_lsdt tone m) ->
infix_lsdt n (infix_asdt n m).
Axiom init_exp1 :
forall (k:t),
((cpower k 0%Z) = tone) /\
(((cpower k 1%Z) = k) /\ ((cpower k 2%Z) = (infix_asdt k k))).
Axiom int_exp_pos :
forall (k:t) (n:Z), (infix_lseqdt tone k) -> (0%Z <= n)%Z ->
(infix_gteqdt (cpower k n) tone) /\
((infix_gtdt (cpower k n) tzero) /\
(infix_lseqdt (cpower k n) (cpower k (n + 1%Z)%Z))).
Axiom strict_int_exp_pos :
forall (k:t) (n:Z), (infix_lsdt tone k) -> (0%Z < n)%Z ->
(infix_gtdt (cpower k n) tone) /\
((infix_lsdt (cpower k (n - 1%Z)%Z) (cpower k n)) /\
(infix_lsdt (cpower k n) (cpower k (n + 1%Z)%Z))).
Axiom strict_int_exp_neg :
forall (k:t) (n:Z), (infix_lsdt tone k) -> (n < 0%Z)%Z ->
(infix_lsdt (cpower k n) tone) /\
((infix_lsdt (cpower k (n - 1%Z)%Z) (cpower k n)) /\
(infix_lsdt (cpower k n) (cpower k (n + 1%Z)%Z))).
Axiom int_exp_neg :
forall (k:t) (n:Z), (infix_lseqdt tone k) -> (n < 0%Z)%Z ->
(infix_lseqdt (cpower k n) tone) /\
((infix_gtdt (cpower k n) tzero) /\
(infix_lseqdt (cpower k n) (cpower k (n + 1%Z)%Z))).
Axiom positive_exp :
forall (k:t) (m:Z), (infix_lseqdt tone k) -> infix_lsdt tzero (cpower k m).
Axiom growing_exp_pos :
forall (k:t) (m:Z) (n:Z), (infix_lseqdt tone k) ->
((0%Z <= m)%Z /\ (m <= n)%Z) -> infix_lseqdt (cpower k m) (cpower k n).
Axiom growing_exp1 :
forall (k:t) (m:Z) (n:Z), (infix_lseqdt tone k) -> (m <= n)%Z ->
infix_lseqdt (cpower k m) (cpower k n).
Axiom growing_exp_arg :
forall (k:t) (k':t) (n:Z),
((infix_lseqdt tzero k) /\ (infix_lseqdt k k')) -> (0%Z <= n)%Z ->
infix_lseqdt (cpower k n) (cpower k' n).
Axiom strict_growing_exp1 :
forall (k:t) (m:Z) (n:Z), (infix_lsdt tone k) -> (m < n)%Z ->
infix_lsdt (cpower k m) (cpower k n).
Axiom cpower_comm_pos :
forall (x:t) (y:t) (n:Z), (infix_lseqdt tone x) -> (infix_lseqdt tone y) ->
(0%Z <= n)%Z ->
((cpower (infix_asdt x y) n) = (infix_asdt (cpower x n) (cpower y n))).
Axiom cpower_comm :
forall (x:t) (y:t) (n:Z), (infix_lseqdt tone x) -> (infix_lseqdt tone y) ->
((cpower (infix_asdt x y) n) = (infix_asdt (cpower x n) (cpower y n))).
Axiom unicity_exp1 :
forall (k:t) (m:Z) (n:Z), (infix_lsdt tone k) ->
((cpower k m) = (cpower k n)) <-> (m = n).
Parameter power_: Z -> Z -> Z.
Axiom power__def :
forall (e:Z) (i:Z),
((i >= 0%Z)%Z -> ((power_ e i) = (power e i))) /\
(~ (i >= 0%Z)%Z -> ((power_ e i) = 0%Z)).
Axiom Power_zero_ : forall (i:Z), ((power_ i 0%Z) = 1%Z).
Axiom Power_one_ : forall (i:Z), ((power_ i 1%Z) = i).
Axiom Power_sum_ :
forall (x:Z) (y:Z) (i:Z), (0%Z <= x)%Z -> (y >= 0%Z)%Z ->
((power_ i (x + y)%Z) = ((power_ i x) * (power_ i y))%Z).
Axiom Power_mult_ :
forall (x:Z) (y:Z) (i:Z), (x >= 0%Z)%Z -> (y >= 0%Z)%Z ->
((power i (x * y)%Z) = (power (power i x) y)).
Axiom Power_pos_ : forall (i:Z), (i >= 0%Z)%Z -> ((power_ i 0%Z) > 0%Z)%Z.
Axiom Power_pos_gen_ :
forall (i:Z) (j:Z), (i > 0%Z)%Z -> (j >= 0%Z)%Z -> (0%Z < (power_ i j))%Z.
Axiom power_two_ :
forall (x:Z), (0%Z <= x)%Z -> ((power_ x 2%Z) = (x * x)%Z).
Axiom power_plus_one_two :
forall (x:Z), (0%Z <= x)%Z ->
((power_ 2%Z (x + 1%Z)%Z) = ((power_ 2%Z x) + (power_ 2%Z x))%Z).
Parameter polysquare: Z -> Z -> Z -> Z -> Z.
Axiom polysquare_def :
forall (n:Z) (a2:Z) (a1:Z) (a0:Z), (0%Z < n)%Z -> (0%Z <= a2)%Z ->
(0%Z <= a1)%Z -> (0%Z <= a0)%Z ->
((polysquare n a2 a1 a0) =
(((a2 * (power_ n 2%Z))%Z + (a1 * n)%Z)%Z + a0)%Z).
Axiom polysquare_spec :
forall (n:Z) (a2:Z) (a1:Z) (a0:Z), (0%Z < n)%Z -> (0%Z <= a2)%Z ->
(0%Z <= a1)%Z -> (0%Z <= a0)%Z -> (0%Z <= (polysquare n a2 a1 a0))%Z.
Axiom polysquare_leq_trans :
forall (n:Z) (a2:Z) (a1:Z) (a0:Z) (b2:Z) (b1:Z) (b0:Z) (pa:Z) (pb:Z) (ps:Z),
(0%Z < n)%Z -> (0%Z <= a2)%Z -> (0%Z <= a1)%Z -> (0%Z <= a0)%Z ->
(0%Z <= b2)%Z -> (0%Z <= b1)%Z -> (0%Z <= b0)%Z ->
(pa <= (polysquare n a2 a1 a0))%Z -> (pb <= (polysquare n b2 b1 b0))%Z ->
(ps <= (pa + pb)%Z)%Z ->
(ps <= (polysquare n (a2 + b2)%Z (a1 + b1)%Z (a0 + b0)%Z))%Z.
Axiom polysquare_leq_trans_sc :
forall (n:Z) (a2:Z) (a1:Z) (a0:Z) (b2:Z) (b1:Z) (b0:Z) (pa:Z) (sc:Z) (ps:Z),
(0%Z < n)%Z -> (0%Z <= a2)%Z -> (0%Z <= a1)%Z -> (0%Z <= a0)%Z ->
(0%Z <= sc)%Z -> ((sc * a2)%Z <= b2)%Z -> ((sc * a1)%Z <= b1)%Z ->
((sc * a0)%Z <= b0)%Z -> (pa <= (polysquare n a2 a1 a0))%Z ->
(ps <= (sc * pa)%Z)%Z -> (ps <= (polysquare n b2 b1 b0))%Z.
Axiom polysquare_update :
forall (na:Z) (nb:Z) (a2:Z) (a1:Z) (a0:Z) (pa:Z),
((0%Z < na)%Z /\ (na <= nb)%Z) -> (0%Z <= a2)%Z -> (0%Z <= a1)%Z ->
(0%Z <= a0)%Z -> (pa <= (polysquare na a2 a1 a0))%Z ->
(pa <= (polysquare nb a2 a1 a0))%Z.
Axiom cpower_i_to_t :
forall (a:Z) (b:Z), (0%Z <= b)%Z ->
((i_to_t (power_ a b)) = (cpower (i_to_t a) b)).
Axiom cpower_i_to_t_rev :
forall (a:Z) (b:Z), (0%Z <= b)%Z ->
((cpower (i_to_t a) b) = (i_to_t (power_ a b))).
Axiom geometric_series :
forall (a:t) (q:t) (n:Z), (1%Z <= n)%Z ->
((sum (to_fset 0%Z n) (fun (i:Z) => (infix_asdt a (cpower q i)))) =
(infix_sldt (infix_asdt a (infix_mndt tone (cpower q n)))
(infix_mndt tone q))).
Axiom ind_geometric_series_r :
forall (a:t) (q:t) (n:Z), (n >= 1%Z)%Z ->
((ind_sum (fun (i:Z) => (infix_asdt a (cpower q i))) 0%Z n) =
(infix_sldt (infix_asdt a (infix_mndt tone (cpower q n)))
(infix_mndt tone q))).
Axiom ind_geometric_series :
forall (q:t) (n:Z), (n >= 1%Z)%Z ->
((ind_sum (fun (i:Z) => (cpower q i)) 0%Z n) =
(infix_sldt (infix_mndt tone (cpower q n)) (infix_mndt tone q))).
Axiom geometric_series_init_one :
forall (q:t) (n:Z), (n >= 1%Z)%Z ->
((sum (to_fset 0%Z n) (fun (i:Z) => (cpower q i))) =
(infix_sldt (infix_mndt tone (cpower q n)) (infix_mndt tone q))).
Axiom positive_cpower_2 :
forall (x:t), ~ (tzero = x) -> infix_lsdt tzero (cpower x 2%Z).
Axiom positive_cpower_2_mod :
forall (x:t), infix_lseqdt tzero (cpower (modulus x) 2%Z).
Axiom cpower_2_mod_non_null :
forall (x:t), ~ (x = tzero) -> infix_lsdt tzero (cpower (modulus x) 2%Z).
Axiom cpower_2_mod_mult_non_null :
forall (x:t) (y:t), ~ (x = tzero) -> ~ (y = tzero) ->
infix_lsdt tzero (cpower (modulus x) 2%Z).
Axiom growing_cpower_2 :
forall (x:t) (y:t), ((infix_lseqdt tzero x) /\ (infix_lseqdt x y)) ->
infix_lseqdt (cpower x 2%Z) (cpower y 2%Z).
Axiom cpower_incr_power_2 :
forall (k:Z), (0%Z <= k)%Z ->
((cpower (i_to_t (power 2%Z k)) 2%Z) = (i_to_t (power_ 2%Z (2%Z * k)%Z))).
Axiom cpower_modulus_incr_power_2 :
forall (k:Z), (0%Z <= k)%Z ->
((cpower (modulus (i_to_t (power 2%Z k))) 2%Z) =
(i_to_t (power_ 2%Z (2%Z * k)%Z))).
Axiom cpower_modulus_supeq :
forall (x:t) (y:t) (i:Z), (i >= 1%Z)%Z ->
(infix_gteqdt (modulus x) (modulus y)) ->
infix_gteqdt (cpower (modulus x) i) (cpower (modulus y) i).
Axiom cpower_modulus_div_simpl :
forall (x:t) (y:t) (z:t) (i:Z), (i >= 1%Z)%Z -> (infix_lseqdt tzero x) ->
(infix_lsdt tzero y) -> (infix_lsdt tzero z) ->
((infix_sldt (cpower x i) (cpower y i)) =
(infix_sldt (cpower (modulus (infix_asdt x z)) i)
(cpower (modulus (infix_asdt y z)) i))).
Axiom cpower_two_modulus_div_simpl :
forall (x:t) (y:t) (z:t), ~ (tzero = y) -> ~ (tzero = z) ->
((infix_sldt (cpower x 2%Z) (cpower y 2%Z)) =
(infix_sldt (cpower (modulus (infix_asdt x z)) 2%Z)
(cpower (modulus (infix_asdt y z)) 2%Z))).
Axiom angle : Type.
Parameter angle_WhyType : WhyType angle.
Existing Instance angle_WhyType.
Parameter ang_inv: angle -> angle.
Parameter ang_add: angle -> angle -> angle.
Parameter ang_exp: angle -> t.
Axiom ang_exp_spec : forall (us:angle), ~ ((ang_exp us) = tzero).
Parameter arg: t -> angle.
Axiom arg_spec : forall (x:t), ((ang_exp (arg x)) = x).
Parameter ang_zero: angle.
Axiom Assoc2 :
forall (x:angle) (y:angle) (z:angle),
((ang_add (ang_add x y) z) = (ang_add x (ang_add y z))).
Axiom Unit_def_l1 : forall (x:angle), ((ang_add ang_zero x) = x).
Axiom Unit_def_r1 : forall (x:angle), ((ang_add x ang_zero) = x).
Axiom Inv_def_l1 : forall (x:angle), ((ang_add (ang_inv x) x) = ang_zero).
Axiom Inv_def_r1 : forall (x:angle), ((ang_add x (ang_inv x)) = ang_zero).
Axiom Comm2 : forall (x:angle) (y:angle), ((ang_add x y) = (ang_add y x)).
Parameter exp: t -> t.
Parameter e: t.
Axiom e_def : (e = (exp tone)).
Axiom e_diff_tzero : forall (x:t), ~ ((exp x) = tzero).
Axiom Exp_one : real_ (exp tone).
Axiom Exp_zero : ((exp tzero) = tone).
Axiom Exp_sum :
forall (x:t) (y:t), ((exp (infix_pldt x y)) = (infix_asdt (exp x) (exp y))).
Axiom exp_one : real_ e.
Axiom exp_sum :
forall (x:t) (y:t), ((exp (infix_pldt x y)) = (infix_asdt (exp x) (exp y))).
Axiom exp_eq : forall (t1:t) (t2:t), (t1 = t2) -> ((exp t1) = (exp t2)).
Axiom exp_sum_rev :
forall (x:t) (y:t), ((infix_asdt (exp x) (exp y)) = (exp (infix_pldt x y))).
Axiom exp_inv :
forall (i:t), ~ ((exp i) = tzero) ->
((exp (prefix_mndt i)) = (infix_sldt tone (exp i))).
Axiom exp_inv_rev :
forall (i:t), ~ ((exp i) = tzero) ->
((infix_sldt tone (exp i)) = (exp (prefix_mndt i))).
Axiom exp_mult_pre :
forall (x:t) (y:Z), (y >= 0%Z)%Z ->
((exp (infix_asdt x (i_to_t y))) = (cpower (exp x) y)).
Axiom exp_mult :
forall (x:t) (y:Z), ((exp (infix_asdt x (i_to_t y))) = (cpower (exp x) y)).
Axiom cpower_to_exp :
forall (x:t) (y:Z), ((cpower (exp x) y) = (exp (infix_asdt x (i_to_t y)))).
Axiom Exp_quarter_pi :
((exp (infix_sldt (infix_asdt im pi) (i_to_t 4%Z))) =
(infix_pldt (infix_sldt squarert_two ttwo)
(infix_asdt im (infix_sldt squarert_two ttwo)))).
Axiom exp_h_pi : ((exp (infix_sldt (infix_asdt im pi) ttwo)) = im).
Parameter two_pi_i: t.
Axiom two_pi_i_def : (two_pi_i = (infix_asdt (infix_asdt im pi) ttwo)).
Axiom exp_pi : ((exp (infix_asdt im pi)) = (prefix_mndt tone)).
Axiom exp_two_pi : ((exp two_pi_i) = tone).
Axiom exp_two_pi_mul :
forall (k:Z), ((exp (infix_asdt (i_to_t k) two_pi_i)) = tone).
Axiom exp_two_pi_mul_den :
forall (k:Z) (l:Z), ~ (k = 0%Z) ->
((exp (infix_sldt (infix_asdt (i_to_t (k * l)%Z) two_pi_i) (i_to_t k))) =
tone).
Axiom exp_two_pi_mul_den_add :
forall (k:Z) (l:Z) (m:Z),
((exp (infix_asdt (i_to_t ((k * m)%Z + l)%Z) two_pi_i)) =
(exp (infix_asdt (i_to_t l) two_pi_i))).
Parameter ang_mult_int: angle -> Z -> angle.
Axiom ang_mult_int_def :
forall (theta:angle) (i:Z),
((i = 0%Z) -> ((ang_mult_int theta i) = ang_zero)) /\
(~ (i = 0%Z) ->
((i > 0%Z)%Z ->
((ang_mult_int theta i) =
(ang_add (ang_mult_int theta (i - 1%Z)%Z) theta))) /\
(~ (i > 0%Z)%Z ->
((ang_mult_int theta i) = (ang_inv (ang_mult_int theta (-i)%Z))))).
Axiom add_im_re :
forall (i:t) (j:t),
((infix_pldt i j) =
(infix_pldt (infix_pldt (t_real_part i) (t_real_part j))
(infix_asdt im (infix_pldt (t_im_part i) (t_im_part j))))) /\
(((t_real_part (infix_pldt i j)) =
(infix_pldt (t_real_part i) (t_real_part j))) /\
((t_im_part (infix_pldt i j)) = (infix_pldt (t_im_part i) (t_im_part j)))).
Axiom add_real_part :
forall (i:t) (j:t),
((infix_pldt (t_real_part i) (t_real_part j)) =
(t_real_part (infix_pldt i j))).
Axiom add_im_part :
forall (i:t) (j:t),
((infix_pldt (t_im_part i) (t_im_part j)) = (t_im_part (infix_pldt i j))).
Axiom add_real_part_rev :
forall (i:t) (j:t),
((t_real_part (infix_pldt i j)) =
(infix_pldt (t_real_part i) (t_real_part j))).
Axiom add_im_part_rev :
forall (i:t) (j:t),
((t_im_part (infix_pldt i j)) = (infix_pldt (t_im_part i) (t_im_part j))).
Axiom mult_distr_add_r :
forall (a:t) (b:t) (c:t),
((infix_asdt a (infix_pldt b c)) =
(infix_pldt (infix_asdt a b) (infix_asdt a c))).
Axiom mult_distr_minus :
forall (a:t) (b:t) (c:t),
((infix_asdt a (infix_mndt b c)) =
(infix_mndt (infix_asdt a b) (infix_asdt a c))).
Axiom sum_constant :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t) (x:t),
(forall (e1:a), (mem e1 s) -> ((t1 e1) = x)) ->
((sum s t1) = (infix_asdt (i_to_t (cardinal s)) x)).
Axiom sum_const_one :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (t1:a -> t),
(forall (e1:a), (mem e1 s) -> ((t1 e1) = tone)) ->
((sum s t1) = (i_to_t (cardinal s))).
Axiom div_distr_add :
forall (a:t) (b:t) (c:t), ~ (a = tzero) ->
((infix_sldt (infix_pldt b c) a) =
(infix_pldt (infix_sldt b a) (infix_sldt c a))).
Axiom div_distr_minus :
forall (a:t) (b:t) (c:t), ~ (a = tzero) ->
((infix_sldt (infix_mndt b c) a) =
(infix_mndt (infix_sldt b a) (infix_sldt c a))).
Axiom div_distr_add_rev :
forall (a:t) (b:t) (c:t), ~ (a = tzero) ->
((infix_pldt (infix_sldt b a) (infix_sldt c a)) =
(infix_sldt (infix_pldt b c) a)).
Axiom div_distr_minus_rev :
forall (a:t) (b:t) (c:t), ~ (a = tzero) ->
((infix_mndt (infix_sldt b a) (infix_sldt c a)) =
(infix_sldt (infix_mndt b c) a)).
Axiom mult_distr_add_l :
forall (a:t) (b:t) (c:t),
((infix_asdt (infix_pldt b c) a) =
(infix_pldt (infix_asdt a b) (infix_asdt a c))).
Axiom mult_distr_minus_r :
forall (a:t) (b:t) (c:t),
((infix_asdt a (infix_mndt b c)) =
(infix_mndt (infix_asdt a b) (infix_asdt a c))).
Axiom minus_distr_op :
forall (a:t) (b:t) (c:t),
((infix_mndt a (infix_pldt b c)) = (infix_mndt (infix_mndt a b) c)).
Axiom mult_distr_minus_l :
forall (a:t) (b:t) (c:t),
((infix_asdt (infix_mndt b c) a) =
(infix_mndt (infix_asdt a b) (infix_asdt a c))).
Axiom assoc_right :
forall (a:t) (b:t) (c:t),
((infix_pldt a (infix_pldt b c)) = (infix_pldt (infix_pldt a b) c)).
Axiom assoc_right_mult :
forall (a:t) (b:t) (c:t),
((infix_asdt a (infix_asdt b c)) = (infix_asdt (infix_asdt a b) c)).
Axiom minus_elim :
forall (a:t) (b:t), ((infix_mndt a b) = (infix_pldt a (prefix_mndt b))).
Axiom minus_distr_elim :
forall (a:t) (b:t) (c:t),
((infix_mndt a (infix_pldt b c)) =
(infix_pldt (infix_pldt a (prefix_mndt b)) (prefix_mndt c))).
Axiom plus_minus_distr_elim :
forall (a:t) (b:t) (c:t),
((infix_pldt a (prefix_mndt (infix_pldt b c))) =
(infix_pldt (infix_pldt a (prefix_mndt b)) (prefix_mndt c))).
Axiom def_by_minus :
forall (x:t) (y:t) (z:t), (x = (infix_mndt y z)) -> (y = (infix_pldt x z)).
Axiom switch :
forall (a:t) (b:t) (c:t),
((infix_pldt (infix_pldt a b) c) = (infix_pldt (infix_pldt a c) b)).
Axiom meet_a_c :
forall (a:t) (b:t) (c:t) (d:t),
((infix_pldt (infix_pldt (infix_pldt a b) c) d) =
(infix_pldt (infix_pldt (infix_pldt a c) b) d)).
Axiom meet_a_d :
forall (a:t) (b:t) (c:t) (d:t),
((infix_pldt (infix_pldt (infix_pldt a b) c) d) =
(infix_pldt (infix_pldt (infix_pldt a d) b) c)).
Axiom meet_b_c :
forall (a:t) (b:t) (c:t) (d:t),
((infix_pldt (infix_pldt (infix_pldt a b) c) d) =
(infix_pldt (infix_pldt (infix_pldt b c) a) d)).
Axiom meet_b_d :
forall (a:t) (b:t) (c:t) (d:t),
((infix_pldt (infix_pldt (infix_pldt a b) c) d) =
(infix_pldt (infix_pldt (infix_pldt b d) a) c)).
Axiom meet_c_d :
forall (a:t) (b:t) (c:t) (d:t),
((infix_pldt (infix_pldt (infix_pldt a b) c) d) =
(infix_pldt (infix_pldt (infix_pldt c d) a) b)).
Axiom inv_add :
forall (a:t) (b:t), ((infix_pldt (infix_pldt a (prefix_mndt a)) b) = b).
Axiom switch_m :
forall (a:t) (b:t) (c:t),
((infix_pldt (infix_pldt a b) c) = (infix_pldt (infix_pldt a c) b)).
Axiom meet_a_c_m :
forall (a:t) (b:t) (c:t) (d:t),
((infix_pldt (infix_pldt (infix_pldt a b) c) d) =
(infix_pldt (infix_pldt (infix_pldt a c) b) d)).
Axiom meet_a_d_m :
forall (a:t) (b:t) (c:t) (d:t),
((infix_pldt (infix_pldt (infix_pldt a b) c) d) =
(infix_pldt (infix_pldt (infix_pldt a d) b) c)).
Axiom meet_b_c_m :
forall (a:t) (b:t) (c:t) (d:t),
((infix_pldt (infix_pldt (infix_pldt a b) c) d) =
(infix_pldt (infix_pldt (infix_pldt b c) a) d)).
Axiom meet_b_d_m :
forall (a:t) (b:t) (c:t) (d:t),
((infix_pldt (infix_pldt (infix_pldt a b) c) d) =
(infix_pldt (infix_pldt (infix_pldt b d) a) c)).
Axiom meet_c_d_m :
forall (a:t) (b:t) (c:t) (d:t),
((infix_pldt (infix_pldt (infix_pldt a b) c) d) =
(infix_pldt (infix_pldt (infix_pldt c d) a) b)).
Axiom t_real_part_add :
forall (a:t) (b:t),
((t_real_part (infix_pldt a b)) =
(infix_pldt (t_real_part a) (t_real_part b))).
Axiom t_real_part_subs :
forall (a:t) (b:t),
((t_real_part (infix_mndt a b)) =
(infix_mndt (t_real_part a) (t_real_part b))).
Axiom t_im_part_add :
forall (a:t) (b:t),
((t_im_part (infix_pldt a b)) = (infix_pldt (t_im_part a) (t_im_part b))).
Axiom t_im_part_subs :
forall (a:t) (b:t),
((t_im_part (infix_mndt a b)) = (infix_mndt (t_im_part a) (t_im_part b))).
Axiom t_real_part_real : forall (a:t), (real_ a) -> ((t_real_part a) = a).
Axiom t_real_part_im :
forall (a:t), (pure_im_ a) -> ((t_real_part a) = tzero).
Axiom im_t_im_part_im :
forall (a:t), (pure_im_ a) -> ((infix_asdt im (t_im_part a)) = a).
Axiom t_im_part_im :
forall (a:t), (pure_im_ a) ->
((t_im_part a) = (infix_asdt (prefix_mndt im) a)).
Axiom t_im_part_real : forall (a:t), (real_ a) -> ((t_im_part a) = tzero).
Axiom a_div_b_mult_a :
forall (a:t) (b:t) (c:t) (d:t), ~ (b = tzero) -> ~ (c = tzero) ->
(d = (infix_sldt tone b)) -> (a = c) ->
((infix_asdt (infix_sldt a b) (infix_sldt tone c)) = d).
Parameter conjugate: t -> t.
Axiom conjugate_def :
forall (i:t),
((conjugate i) =
(infix_mndt (t_real_part i) (infix_asdt im (t_im_part i)))).
Axiom real_part_conjugate :
forall (i:t), ((t_real_part (conjugate i)) = (t_real_part i)).
Axiom im_part_conjugate :
forall (i:t), ((t_im_part (conjugate i)) = (prefix_mndt (t_im_part i))).
Axiom invol_conjugate : forall (i:t), ((conjugate (conjugate i)) = i).
Axiom add_conjugate :
forall (i:t) (j:t),
((conjugate (infix_pldt i j)) = (infix_pldt (conjugate i) (conjugate j))).
Axiom add_own_conjugate :
forall (i:t),
((infix_pldt i (conjugate i)) = (infix_asdt ttwo (t_real_part i))).
Axiom conjugate_to_modulus :
forall (i:t), ((modulus i) = (square_rt (infix_asdt i (conjugate i)))).
Axiom sum_conjugate :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> t),
((conjugate (sum s f)) = (sum s (fun (x:a) => (conjugate (f x))))).
Axiom conjugate_module_one :
forall (i:t), ((modulus i) = tone) -> ((conjugate i) = (inv i)).
Axiom conjugate_module_one_rev :
forall (i:t), ~ (i = tzero) -> ((conjugate i) = (inv i)) ->
((modulus i) = tone).
Axiom conjugate_real : forall (i:t), (real_ i) -> ((conjugate i) = i).
Axiom conjugate_real_gen : forall (i:t), (real_ i) -> ((conjugate i) = i).
Axiom conjugate_one : forall (x:t), (x = tone) -> ((conjugate x) = tone).
Axiom conjugate_tzero : forall (x:t), (x = tzero) -> ((conjugate x) = tzero).
Axiom conjugate_indic :
forall {a:Type} {a_WT:WhyType a},
forall (i:a) (j:a), ((conjugate (indic i j)) = (indic i j)).
Axiom conjugate_indic_rev :
forall {a:Type} {a_WT:WhyType a},
forall (i:a) (j:a), ((indic i j) = (conjugate (indic i j))).
Axiom conjugate_indic_gen_int :
forall (i:Z) (j:Z), ((conjugate (indic i j)) = (indic i j)).
Axiom conjugate_pure_im :
forall (i:t), (pure_im_ i) -> ((conjugate i) = (prefix_mndt i)).
Axiom conjugate_im : ((conjugate im) = (prefix_mndt im)).
Axiom conjugate_value :
forall (c:t) (a:t) (b:t), (real_ a) -> (real_ b) ->
(c = (infix_pldt a (infix_asdt im b))) ->
((conjugate c) = (infix_mndt a (infix_asdt im b))).
Axiom conjugate_minus_value :
forall (c:t) (a:t) (b:t), (real_ a) -> (real_ b) ->
(c = (infix_mndt a (infix_asdt im b))) ->
((conjugate c) = (infix_pldt a (infix_asdt im b))).
Axiom prod_conjugate :
forall (a:t) (b:t),
((infix_asdt a (conjugate b)) =
(infix_pldt
(infix_pldt (infix_asdt (t_real_part a) (t_real_part b))
(infix_asdt (t_im_part a) (t_im_part b)))
(infix_asdt im
(infix_mndt (infix_asdt (t_real_part b) (t_im_part a))
(infix_asdt (t_im_part b) (t_real_part a)))))).
Axiom mult_conjugate :
forall (a:t) (b:t),
((conjugate (infix_asdt a b)) = (infix_asdt (conjugate a) (conjugate b))).
Axiom conjugate_prod :
forall (a:t) (b:t),
((infix_asdt (conjugate a) b) =
(infix_pldt
(infix_pldt (infix_asdt (t_real_part a) (t_real_part b))
(infix_asdt (t_im_part a) (t_im_part b)))
(infix_asdt im
(infix_mndt (infix_asdt (t_real_part a) (t_im_part b))
(infix_asdt (t_real_part b) (t_im_part a)))))).
Axiom conj_conj_prod :
forall (a:t) (b:t),
((conjugate (infix_asdt (conjugate a) b)) = (infix_asdt a (conjugate b))).
Axiom conj_prod_conj :
forall (a:t) (b:t),
((conjugate (infix_asdt a (conjugate b))) = (infix_asdt (conjugate a) b)).
Axiom itself_prod_conjugate_modulus_one :
forall (a:t), ((modulus a) = tone) -> ((infix_asdt a (conjugate a)) = tone).
Axiom conjugate_prod_itself_modulus_one :
forall (a:t), ((modulus a) = tone) -> ((infix_asdt a (conjugate a)) = tone).
Axiom modulus_opposite :
forall (a:t), (real_ a) -> (infix_lseqdt tzero a) ->
((modulus a) = (modulus (prefix_mndt a))).
Axiom modulus_pos1 :
forall (a:t), (real_ a) -> (infix_lseqdt tzero a) -> ((modulus a) = a).
Axiom modulus_neg :
forall (a:t), (real_ a) -> (infix_lseqdt a tzero) ->
((modulus a) = (prefix_mndt a)).
Parameter real_to_ang: t -> angle.
Axiom real_to_ang_eq :
forall (phi:t) (phi':t), (real_ phi) -> (phi = phi') ->
((real_to_ang phi) = (real_to_ang phi')).
Axiom Real_To_Ang_value :
forall (phi:t), (real_ phi) ->
((ang_exp (real_to_ang phi)) = (exp (infix_asdt two_pi_i phi))).
Axiom Real_To_Ang_inv :
forall (phi:t), ~ (phi = tzero) -> (real_ phi) ->
((ang_inv (real_to_ang phi)) = (real_to_ang (prefix_mndt phi))).
Axiom Real_To_Ang_add :
forall (phi:t) (phi':t), (real_ phi) -> (real_ phi') ->
((ang_add (real_to_ang phi) (real_to_ang phi')) =
(real_to_ang (infix_pldt phi phi'))).
Parameter int_to_ang: Z -> Z -> angle.
Axiom int_to_ang_def :
forall (k:Z) (n:Z), (n >= 0%Z)%Z ->
((int_to_ang k n) =
(real_to_ang (infix_sldt (i_to_t k) (i_to_t (power 2%Z n))))).
Axiom real_to_ang_tone : ((real_to_ang tone) = ang_zero).
Axiom Real_To_Ang_inv_add :
forall (phi:t), (real_ phi) ->
((ang_add (real_to_ang phi) (real_to_ang (prefix_mndt phi))) = ang_zero).
Axiom Real_To_Ang_up :
forall (phi:t), (real_ phi) ->
((real_to_ang phi) = (real_to_ang (infix_pldt tone phi))).
Axiom real_To_Ang_cyclic_pos :
forall (phi:t) (k:Z), (real_ phi) -> (0%Z <= k)%Z ->
((real_to_ang phi) = (real_to_ang (infix_pldt (i_to_t k) phi))).
Axiom Real_zero_n : ((real_to_ang tzero) = ang_zero).
Axiom Real_ang_mult :
forall (phi:t), forall (i:Z),
((ang_mult_int (real_to_ang phi) i) =
(real_to_ang (infix_asdt phi (i_to_t i)))).
Axiom real_to_ang_down_cucles :
forall (phi:t) (x:t), (real_ phi) -> (x = tone) ->
((real_to_ang (infix_mndt phi x)) = (real_to_ang phi)).
Parameter odd: Z -> bool.
Axiom odd_def :
forall (n:Z),
(((int.EuclideanDivision.mod1 n 2%Z) = 1%Z) -> ((odd n) = true)) /\
(~ ((int.EuclideanDivision.mod1 n 2%Z) = 1%Z) -> ((odd n) = false)).
Axiom odd_spec :
forall (n:Z),
(((odd n) = true) ->
(n = ((2%Z * (int.EuclideanDivision.div n 2%Z))%Z + 1%Z)%Z)) /\
(((odd n) = false) -> (n = (2%Z * (int.EuclideanDivision.div n 2%Z))%Z)).
Parameter even: Z -> bool.
Axiom even_def :
forall (n:Z),
(((int.EuclideanDivision.mod1 n 2%Z) = 0%Z) -> ((even n) = true)) /\
(~ ((int.EuclideanDivision.mod1 n 2%Z) = 0%Z) -> ((even n) = false)).
Axiom even_spec : forall (n:Z), ((even n) = true) <-> ~ ((odd n) = true).
Axiom even_to_mod :
forall (n:Z), ((even n) = true) ->
((int.EuclideanDivision.mod1 n 2%Z) = 0%Z).
Axiom even_minus_one :
forall (n:Z), (0%Z < n)%Z -> ((even n) = true) ->
((odd (n - 1%Z)%Z) = true).
Axiom odd_minus_one :
forall (n:Z), (0%Z < n)%Z -> ((odd n) = true) ->
((even (n - 1%Z)%Z) = true).
Axiom odd_to_mod :
forall (n:Z), ((odd n) = true) ->
((int.EuclideanDivision.mod1 n 2%Z) = 1%Z).
Axiom even_or_odd : forall (n:Z), ((even n) = true) \/ ((odd n) = true).
Axiom cpower_minus_tone :
forall (n:Z), (0%Z <= n)%Z ->
(((even n) = true) -> ((cpower (prefix_mndt tone) n) = tone)) /\
(((odd n) = true) -> ((cpower (prefix_mndt tone) n) = (prefix_mndt tone))).
Axiom cpower_minus_tone_even :
forall (n:Z), (0%Z <= n)%Z -> ((even n) = true) ->
((cpower (prefix_mndt tone) n) = tone).
Axiom cpower_minus_tone_odd :
forall (n:Z), (0%Z <= n)%Z -> ((odd n) = true) ->
((cpower (prefix_mndt tone) n) = (prefix_mndt tone)).
Axiom not_null_powers_squarert_two :
forall (i:Z), (0%Z <= i)%Z -> ~ ((cpower squarert_two i) = tzero).
Parameter pos_coeff: t.
Axiom pos_coeff_def : (pos_coeff = (infix_sldt tone squarert_two)).
Axiom real_pos_coeff : real_ pos_coeff.
Parameter neg_coeff: t.
Axiom neg_coeff_def :
(neg_coeff = (infix_sldt (prefix_mndt tone) squarert_two)).
Axiom coeffs : (neg_coeff = (prefix_mndt pos_coeff)).
Parameter mop: Z -> t.
Axiom mop_def :
forall (i:Z), (0%Z <= i)%Z -> ((mop i) = (cpower (prefix_mndt tone) i)).
Axiom minus_one_power_values :
forall (i:Z), (0%Z <= i)%Z ->
(((even i) = true) -> ((mop i) = tone)) /\
(((odd i) = true) -> ((mop i) = (prefix_mndt tone))).
Axiom factors_mop :
forall (i:Z) (j:Z), (0%Z <= i)%Z -> (0%Z <= j)%Z ->
((mop (i + j)%Z) = (infix_asdt (mop i) (mop j))).
Axiom factors_mop_rev :
forall (i:Z) (j:Z), (0%Z <= i)%Z -> (0%Z <= j)%Z ->
((infix_asdt (mop i) (mop j)) = (mop (i + j)%Z)).
Parameter pow_inv_sqrt_2: Z -> t.
Axiom pow_inv_sqrt_2_def :
forall (i:Z), (0%Z <= i)%Z -> ((pow_inv_sqrt_2 i) = (cpower pos_coeff i)).
Axiom pow_inv_sqrt_2_spec :
forall (i:Z), (0%Z <= i)%Z ->
(real_ (pow_inv_sqrt_2 i)) /\
((pow_inv_sqrt_2 i) = (infix_sldt tone (square_rt (i_to_t (power 2%Z i))))).
Axiom pow_inv_sqrt_2_add :
forall (i:Z) (j:Z), (0%Z <= i)%Z -> (0%Z <= j)%Z ->
((pow_inv_sqrt_2 (i + j)%Z) =
(infix_asdt (pow_inv_sqrt_2 i) (pow_inv_sqrt_2 j))).
Parameter pow_inv_2: Z -> t.
Axiom pow_inv_2_def :
forall (i:Z), (0%Z <= i)%Z ->
((pow_inv_2 i) = (infix_sldt tone (i_to_t (power 2%Z i)))).
Axiom pow_inv_2_spec :
forall (i:Z), (0%Z <= i)%Z ->
(real_ (pow_inv_2 i)) /\
((infix_gtdt (pow_inv_2 i) tzero) /\
(((pow_inv_2 i) = (pow_inv_sqrt_2 (2%Z * i)%Z)) /\
((pow_inv_2 i) = (infix_asdt (pow_inv_sqrt_2 i) (pow_inv_sqrt_2 i))))).
Axiom pow_inv_2_subst :
forall (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i <= j)%Z) ->
((infix_asdt (pow_inv_2 i) (cpower ttwo j)) = (cpower ttwo (j - i)%Z)).
Axiom pow_inv_2_ :
forall (i:Z), (0%Z <= i)%Z ->
((pow_inv_2 i) = (infix_sldt tone (i_to_t (power_ 2%Z i)))).
Axiom pow_inv_2_cpower :
forall (i:Z), (0%Z <= i)%Z ->
((pow_inv_2 i) = (infix_sldt tone (cpower ttwo i))).
Axiom matrix : forall (a:Type), Type.
Parameter matrix_WhyType :
forall (a:Type) {a_WT:WhyType a}, WhyType (matrix a).
Existing Instance matrix_WhyType.
Parameter elts: forall {a:Type} {a_WT:WhyType a}, (matrix a) -> Z -> Z -> a.
Parameter rows: forall {a:Type} {a_WT:WhyType a}, (matrix a) -> Z.
Parameter columns: forall {a:Type} {a_WT:WhyType a}, (matrix a) -> Z.
Axiom matrix'invariant :
forall {a:Type} {a_WT:WhyType a},
forall (self:matrix a), (0%Z < (rows self))%Z /\ (0%Z < (columns self))%Z.
Parameter valid_index:
forall {a:Type} {a_WT:WhyType a}, (matrix a) -> Z -> Z -> Prop.
Axiom valid_index_def :
forall {a:Type} {a_WT:WhyType a},
forall (a1:matrix a) (r:Z) (c:Z),
(valid_index a1 r c) <->
(((0%Z <= r)%Z /\ (r < (rows a1))%Z) /\
((0%Z <= c)%Z /\ (c < (columns a1))%Z)).
Parameter equal_size:
forall {a:Type} {a_WT:WhyType a}, (matrix a) -> (matrix a) -> Prop.
Axiom equal_size_def :
forall {a:Type} {a_WT:WhyType a},
forall (a1:matrix a) (b:matrix a),
(equal_size a1 b) <->
(((rows a1) = (rows b)) /\ ((columns a1) = (columns b))).
Parameter get: forall {a:Type} {a_WT:WhyType a}, (matrix a) -> Z -> Z -> a.
Axiom get_def :
forall {a:Type} {a_WT:WhyType a},
forall (a1:matrix a) (r:Z) (c:Z), ((get a1 r c) = (((elts a1) r) c)).
Axiom get_spec :
forall {a:Type} {a_WT:WhyType a},
forall (a1:matrix a) (r:Z) (c:Z), ((get a1 r c) = (((elts a1) r) c)).
Parameter make: forall {a:Type} {a_WT:WhyType a}, Z -> Z -> a -> matrix a.
Axiom make_spec :
forall {a:Type} {a_WT:WhyType a},
forall (r:Z) (c:Z) (v:a), ((r > 0%Z)%Z /\ (c > 0%Z)%Z) ->
((rows (make r c v)) = r) /\
(((columns (make r c v)) = c) /\
forall (i:Z) (j:Z),
(((0%Z <= i)%Z /\ (i < r)%Z) /\ ((0%Z <= j)%Z /\ (j < c)%Z)) ->
((get (make r c v) i j) = v)).
Axiom equality :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a) (n:matrix a),
(m = n) <->
((((rows m) = (rows n)) /\ ((columns m) = (columns n))) /\
forall (i:Z) (j:Z), (valid_index m i j) -> ((get m i j) = (get n i j))).
Axiom make_value :
forall {a:Type} {a_WT:WhyType a},
forall (r:Z) (c:Z) (i:Z) (j:Z) (v:a), ((r > 0%Z)%Z /\ (c > 0%Z)%Z) ->
((0%Z <= i)%Z /\ (i < r)%Z) -> ((0%Z <= j)%Z /\ (j < c)%Z) ->
((get (make r c v) i j) = v).
Parameter mat_indices:
forall {a:Type} {a_WT:WhyType a}, (matrix a) -> set (Z* Z)%type.
Axiom mat_indices_def :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a),
((mat_indices m) =
(cartesian_product (to_fset 0%Z (rows m)) (to_fset 0%Z (columns m)))).
Axiom mat_indices_spec :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a), forall (i:Z) (j:Z),
(valid_index m i j) <-> (mem (i, j) (mat_indices m)).
Parameter set1:
forall {a:Type} {a_WT:WhyType a}, (matrix a) -> Z -> Z -> a -> matrix a.
Axiom set_spec :
forall {a:Type} {a_WT:WhyType a},
forall (a1:matrix a) (r:Z) (c:Z) (v:a), (valid_index a1 r c) ->
((rows (set1 a1 r c v)) = (rows a1)) /\
(((columns (set1 a1 r c v)) = (columns a1)) /\
((forall (i:Z) (j:Z), (valid_index a1 i j) ->
(((i = r) /\ (j = c)) -> ((get (set1 a1 r c v) i j) = v)) /\
(~ ((i = r) /\ (j = c)) -> ((get (set1 a1 r c v) i j) = (get a1 i j)))) /\
(((get (set1 a1 r c v) r c) = v) /\
((forall (i:Z) (j:Z), (valid_index (set1 a1 r c v) i j) -> ~ (i = r) ->
((get (set1 a1 r c v) i j) = (get a1 i j))) /\
forall (i:Z) (j:Z), (valid_index (set1 a1 r c v) i j) -> ~ (j = c) ->
((get (set1 a1 r c v) i j) = (get a1 i j)))))).
Axiom set_valid_index :
forall {a:Type} {a_WT:WhyType a},
forall (a1:matrix a) (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < (rows a1))%Z) ->
((0%Z <= j)%Z /\ (j < (columns a1))%Z) -> valid_index a1 i j.
Axiom get_valid_index :
forall {a:Type} {a_WT:WhyType a},
forall (a1:matrix a) (r:Z) (c:Z), ((rows a1) = r) -> ((columns a1) = c) ->
(forall (i:Z) (j:Z), (valid_index a1 i j) -> (0%Z <= i)%Z /\ (i < r)%Z) /\
forall (i:Z) (j:Z), (valid_index a1 i j) -> (0%Z <= j)%Z /\ (j < c)%Z.
Axiom get_valid_index_params :
forall {a:Type} {a_WT:WhyType a},
forall (a1:matrix a) (r:Z) (c:Z) (i:Z) (j:Z), ((rows a1) = r) ->
((columns a1) = c) -> (valid_index a1 i j) ->
((0%Z <= i)%Z /\ (i < r)%Z) /\ ((0%Z <= j)%Z /\ (j < c)%Z).
Axiom set_values :
forall {a:Type} {a_WT:WhyType a},
forall (a1:matrix a) (r:Z) (c:Z) (v:a), (valid_index a1 r c) ->
forall (i:Z) (j:Z), (valid_index a1 i j) ->
(((i = r) /\ (j = c)) -> ((get (set1 a1 r c v) i j) = v)) /\
(~ ((i = r) /\ (j = c)) -> ((get (set1 a1 r c v) i j) = (get a1 i j))).
Axiom set_rows :
forall {a:Type} {a_WT:WhyType a},
forall (a1:matrix a) (r:Z) (c:Z) (v:a), (valid_index a1 r c) ->
((rows (set1 a1 r c v)) = (rows a1)).
Axiom set_columns :
forall {a:Type} {a_WT:WhyType a},
forall (a1:matrix a) (r:Z) (c:Z) (v:a), (valid_index a1 r c) ->
((columns (set1 a1 r c v)) = (columns a1)).
Parameter make_f:
forall {a:Type} {a_WT:WhyType a}, Z -> Z -> (Z -> Z -> a) -> matrix a.
Axiom make_f_spec :
forall {a:Type} {a_WT:WhyType a},
forall (r:Z) (c:Z) (f:Z -> Z -> a), (r > 0%Z)%Z -> (c > 0%Z)%Z ->
((rows (make_f r c f)) = r) /\
(((columns (make_f r c f)) = c) /\
forall (i:Z) (j:Z), ((get (make_f r c f) i j) = ((f i) j))).
Axiom assert_make :
forall {a:Type} {a_WT:WhyType a},
forall (r:Z) (c:Z) (f:Z -> Z -> a) (i:Z) (j:Z),
((0%Z <= i)%Z /\ (i < r)%Z) -> ((0%Z <= j)%Z /\ (j < c)%Z) ->
((get (make_f r c f) i j) = ((f i) j)).
Axiom assert_make_r :
forall {a:Type} {a_WT:WhyType a},
forall (r:Z) (c:Z) (f:Z -> Z -> a), (0%Z < r)%Z -> (0%Z < c)%Z ->
((rows (make_f r c f)) = r).
Axiom assert_make_c :
forall {a:Type} {a_WT:WhyType a},
forall (r:Z) (c:Z) (f:Z -> Z -> a), (0%Z < r)%Z -> (0%Z < c)%Z ->
((columns (make_f r c f)) = c).
Parameter to_indexes:
forall {a:Type} {a_WT:WhyType a}, (matrix a) -> set (Z* Z)%type.
Axiom to_indexes_def :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a),
((to_indexes m) =
(cartesian_product (to_fset 0%Z (rows m)) (to_fset 0%Z (columns m)))).
Axiom to_indexes_spec :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a),
((cardinal (to_indexes m)) = ((rows m) * (columns m))%Z).
Axiom set_to_indexes_mem :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a) (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < (rows m))%Z) ->
((0%Z <= j)%Z /\ (j < (columns m))%Z) -> mem (i, j) (to_indexes m).
Axiom get_to_indexes_mem :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a) (o:(Z* Z)%type), (mem o (to_indexes m)) ->
((0%Z <= (fir o))%Z /\ ((fir o) < (rows m))%Z) /\
((0%Z <= (sec o))%Z /\ ((sec o) < (columns m))%Z).
Parameter equal:
forall {a:Type} {a_WT:WhyType a}, (matrix a) -> (matrix a) -> Prop.
Axiom equal_def :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a) (n:matrix a), (equal m n) <-> (infix_eqeq m n).
Axiom mat_equality :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a) (n:matrix a), ((rows m) = (rows n)) ->
((columns m) = (columns n)) ->
(forall (i:Z) (j:Z), (valid_index m i j) -> ((get m i j) = (get n i j))) ->
equal m n.
Parameter square: forall {a:Type} {a_WT:WhyType a}, (matrix a) -> Prop.
Axiom square_def :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a), (square m) <-> ((rows m) = (columns m)).
Axiom equal_sym :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a) (n:matrix a), (equal m n) <-> (equal n m).
Axiom equal_rex :
forall {a:Type} {a_WT:WhyType a}, forall (m:matrix a), equal m m.
Axiom equal_trans :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a) (n:matrix a) (o:matrix a), (equal m n) ->
(equal n o) -> equal m o.
Axiom set_equal_mat :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a) (n:matrix a), ((rows m) = (rows n)) ->
((columns m) = (columns n)) ->
(forall (i:Z) (j:Z), (valid_index m i j) -> ((get m i j) = (get n i j))) ->
(m = n).
Axiom set_equal_mat_make :
forall {a:Type} {a_WT:WhyType a},
forall (r:Z) (c:Z) (f:Z -> Z -> a) (g:Z -> Z -> a), (0%Z < r)%Z ->
(0%Z < c)%Z ->
(forall (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < r)%Z) ->
((0%Z <= j)%Z /\ (j < c)%Z) -> (((f i) j) = ((g i) j))) ->
((make_f r c f) = (make_f r c g)).
Axiom set_equal_mat_make_t :
forall {a:Type} {a_WT:WhyType a},
forall (r:Z) (r':Z) (c:Z) (c':Z) (f:Z -> Z -> a) (g:Z -> Z -> a),
(0%Z < r)%Z -> (0%Z < c)%Z -> (r = r') -> (c = c') ->
(forall (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < r)%Z) ->
((0%Z <= j)%Z /\ (j < c)%Z) -> (((f i) j) = ((g i) j))) ->
((make_f r c f) = (make_f r' c' g)).
Axiom get_equal_mat :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a) (n:matrix a), (m = n) ->
((rows m) = (rows n)) /\
(((columns m) = (columns n)) /\
forall (i:Z) (j:Z), (valid_index m i j) -> ((get m i j) = (get n i j))).
Axiom equal_functions :
forall {a:Type} {a_WT:WhyType a},
forall (r:Z) (c:Z) (f:Z -> Z -> a) (g:Z -> Z -> a), (0%Z < r)%Z ->
(0%Z < c)%Z ->
(forall (i:Z) (j:Z),
(((0%Z <= i)%Z /\ (i < r)%Z) /\ ((0%Z <= j)%Z /\ (j < c)%Z)) ->
(((f i) j) = ((g i) j))) ->
((make_f r c f) = (make_f r c g)).
Axiom equal_functions_mat :
forall {a:Type} {a_WT:WhyType a},
forall (f:Z -> Z -> a) (m:matrix a),
(forall (i:Z) (j:Z),
(((0%Z <= i)%Z /\ (i < (rows m))%Z) /\
((0%Z <= j)%Z /\ (j < (columns m))%Z)) ->
(((f i) j) = (get m i j))) ->
(m = (make_f (rows m) (columns m) f)).
Parameter null_mat: (matrix t) -> Prop.
Axiom null_mat_def :
forall (a:matrix t),
(null_mat a) <->
forall (i:Z) (j:Z), (valid_index a i j) -> ((get a i j) = tzero).
Axiom set_null_mat :
forall (a:matrix t),
(forall (i:Z) (j:Z), (valid_index a i j) -> ((get a i j) = tzero)) ->
null_mat a.
Axiom get_null_mat :
forall (a:matrix t), (null_mat a) -> forall (i:Z) (j:Z),
(valid_index a i j) -> ((get a i j) = tzero).
Parameter kronecker_neutral: matrix t.
Axiom kronecker_neutral_def : (kronecker_neutral = (make 1%Z 1%Z tone)).
Parameter identity: Z -> matrix t.
Parameter result6: Z -> Z -> t.
Axiom result_def6 :
forall (i:Z) (j:Z),
((i = j) -> (((result6 i) j) = tone)) /\
(~ (i = j) -> (((result6 i) j) = tzero)).
Axiom identity_def :
forall (n:Z), (0%Z <= n)%Z ->
((identity n) = (make_f (power 2%Z n) (power 2%Z n) result6)).
Axiom identity_spec :
forall (n:Z), (0%Z <= n)%Z ->
((rows (identity n)) = (power 2%Z n)) /\
(((columns (identity n)) = (power 2%Z n)) /\
forall (i:Z) (j:Z), (valid_index (identity n) i j) ->
((i = j) -> ((get (identity n) i j) = tone)) /\
(~ (i = j) -> ((get (identity n) i j) = tzero))).
Axiom identity_rows :
forall (n:Z), (0%Z <= n)%Z -> ((rows (identity n)) = (power 2%Z n)).
Axiom identity_columns :
forall (n:Z), (0%Z <= n)%Z -> ((columns (identity n)) = (power 2%Z n)).
Axiom identity_values :
forall (i:Z) (j:Z) (n:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((i = j) -> ((get (identity n) i j) = tone)) /\
(~ (i = j) -> ((get (identity n) i j) = tzero)).
Parameter kronecker: (matrix t) -> (matrix t) -> matrix t.
Axiom kronecker_def :
forall (m:matrix t) (n:matrix t),
((kronecker m n) =
(make_f ((rows m) * (rows n))%Z ((columns m) * (columns n))%Z
(fun (i:Z) (j:Z) =>
(infix_asdt
(get m (int.EuclideanDivision.div i (rows n))
(int.EuclideanDivision.div j (columns n)))
(get n (int.EuclideanDivision.mod1 i (rows n))
(int.EuclideanDivision.mod1 j (columns n))))))).
Axiom kronecker_spec :
forall (m:matrix t) (n:matrix t),
((rows (kronecker m n)) = ((rows m) * (rows n))%Z) /\
(((columns (kronecker m n)) = ((columns m) * (columns n))%Z) /\
forall (i:Z) (j:Z), (valid_index (kronecker m n) i j) ->
((get (kronecker m n) i j) =
(infix_asdt
(get m (int.EuclideanDivision.div i (rows n))
(int.EuclideanDivision.div j (columns n)))
(get n (int.EuclideanDivision.mod1 i (rows n))
(int.EuclideanDivision.mod1 j (columns n)))))).
Axiom kronecker_eq :
forall (m1:matrix t) (n1:matrix t) (m2:matrix t) (n2:matrix t),
(m1 = m2) -> (n1 = n2) -> ((kronecker m1 n1) = (kronecker m2 n2)).
Axiom get_kronecker :
forall (m:matrix t) (n:matrix t),
((kronecker m n) =
(make_f ((rows m) * (rows n))%Z ((columns m) * (columns n))%Z
(fun (i:Z) (j:Z) =>
(infix_asdt
(get m (int.EuclideanDivision.div i (rows n))
(int.EuclideanDivision.div j (columns n)))
(get n (int.EuclideanDivision.mod1 i (rows n))
(int.EuclideanDivision.mod1 j (columns n))))))).
Axiom kronecker_values :
forall (m:matrix t) (n:matrix t) (i:Z) (j:Z),
(valid_index (kronecker m n) i j) ->
((get (kronecker m n) i j) =
(infix_asdt
(get m (int.EuclideanDivision.div i (rows n))
(int.EuclideanDivision.div j (columns n)))
(get n (int.EuclideanDivision.mod1 i (rows n))
(int.EuclideanDivision.mod1 j (columns n))))).
Axiom kronecker_rows :
forall (m:matrix t) (n:matrix t),
((rows (kronecker m n)) = ((rows m) * (rows n))%Z).
Axiom kronecker_columns :
forall (m:matrix t) (n:matrix t),
((columns (kronecker m n)) = ((columns m) * (columns n))%Z).
Axiom kronecker_values_gen :
forall (m:matrix t) (n:matrix t), forall (i:Z) (j:Z),
(valid_index (kronecker m n) i j) ->
((get (kronecker m n) i j) =
(infix_asdt
(get m (int.EuclideanDivision.div i (rows n))
(int.EuclideanDivision.div j (columns n)))
(get n (int.EuclideanDivision.mod1 i (rows n))
(int.EuclideanDivision.mod1 j (columns n))))).
Axiom kronecker_mod_values :
forall (m:matrix t) (n:matrix t) (i:Z) (j:Z),
(valid_index (kronecker m n) i j) ->
((get (kronecker m n) i j) =
(infix_asdt
(get m
(int.EuclideanDivision.div
(int.EuclideanDivision.mod1 i (rows (kronecker m n))) (rows n))
(int.EuclideanDivision.div
(int.EuclideanDivision.mod1 j (columns (kronecker m n))) (columns n)))
(get n
(int.EuclideanDivision.mod1
(int.EuclideanDivision.mod1 i (rows (kronecker m n))) (rows n))
(int.EuclideanDivision.mod1
(int.EuclideanDivision.mod1 j (columns (kronecker m n))) (columns n))))).
Axiom kronecker_indexes :
forall (m:matrix t) (n:matrix t) (i:Z) (j:Z) (k:Z) (l:Z),
(valid_index m i j) -> (valid_index n k l) ->
valid_index (kronecker m n) ((i * (rows n))%Z + k)%Z
((j * (columns n))%Z + l)%Z.
Axiom kronecker_indexes_com :
forall (m:matrix t) (n:matrix t) (i:Z) (j:Z),
(valid_index (kronecker m n) i j) ->
(valid_index m (int.EuclideanDivision.div i (rows n))
(int.EuclideanDivision.div j (columns n))) /\
(valid_index n (int.EuclideanDivision.mod1 i (rows n))
(int.EuclideanDivision.mod1 j (columns n))).
Axiom kronecker_assoc_pre :
forall (m:matrix t) (n:matrix t) (o:matrix t) (i:Z) (j:Z),
((0%Z <= i)%Z /\ (i < (((rows m) * (rows n))%Z * (rows o))%Z)%Z) ->
((0%Z <= j)%Z /\ (j < (((columns m) * (columns n))%Z * (columns o))%Z)%Z) ->
((get (kronecker (kronecker m n) o) i j) =
(get (kronecker m (kronecker n o)) i j)).
Axiom kronecker_assoc :
op_assoc (fun (y0:matrix t) (y1:matrix t) => (kronecker y0 y1)).
Axiom kronecker_assoc_use :
forall (a:matrix t) (b:matrix t) (c:matrix t),
((kronecker a (kronecker b c)) = (kronecker (kronecker a b) c)).
Axiom kronecker_assoc_use_rev :
forall (a:matrix t) (b:matrix t) (c:matrix t),
((kronecker (kronecker a b) c) = (kronecker a (kronecker b c))).
Axiom neutral_ :
forall (m:matrix t),
((kronecker m kronecker_neutral) = m) /\
((kronecker kronecker_neutral m) = m).
Axiom neutral1 :
(kronecker_neutral =
(neutral_elt (fun (y0:matrix t) (y1:matrix t) => (kronecker y0 y1)))) /\
((has_neutral (fun (y0:matrix t) (y1:matrix t) => (kronecker y0 y1))) /\
(iterable (fun (y0:matrix t) (y1:matrix t) => (kronecker y0 y1)))).
Axiom kronecker_equal :
forall (m:matrix t) (ml:matrix t) (n:matrix t) (nl:matrix t),
(equal m ml) -> (equal n nl) -> equal (kronecker m n) (kronecker ml nl).
Axiom kron_id :
forall (m:Z) (n:Z), (0%Z <= m)%Z -> (0%Z <= n)%Z ->
((kronecker (identity m) (identity n)) = (identity (m + n)%Z)).
Parameter frows: (Z -> matrix t) -> Z -> Z.
Axiom frows_def :
forall (f:Z -> matrix t) (k:Z), ((frows f k) = (rows (f k))).
Axiom frows_spec : forall (f:Z -> matrix t) (k:Z), ((frows f k) > 0%Z)%Z.
Parameter fcolumns: (Z -> matrix t) -> Z -> Z.
Axiom fcolumns_def :
forall (f:Z -> matrix t) (k:Z), ((fcolumns f k) = (columns (f k))).
Axiom fcolumns_spec :
forall (f:Z -> matrix t) (k:Z), ((fcolumns f k) > 0%Z)%Z.
Axiom const_fcol :
forall (m:matrix t) (k:Z),
((fcolumns ((fun (y0:matrix t) (y1:Z) => (const y0 y1)) m) k) =
(columns m)).
Axiom const_frows :
forall (m:matrix t) (k:Z),
((frows ((fun (y0:matrix t) (y1:Z) => (const y0 y1)) m) k) = (rows m)).
Parameter mat_mult_no_bound: (matrix t) -> (matrix t) -> matrix t.
Axiom mat_mult_no_bound_def :
forall (m:matrix t) (n:matrix t),
(((columns m) = (rows n)) ->
((mat_mult_no_bound m n) =
(make_f (rows m) (columns n)
(fun (i:Z) (j:Z) =>
(ind_sum (fun (k:Z) => (infix_asdt (get m i k) (get n k j))) 0%Z
(columns m)))))) /\
(~ ((columns m) = (rows n)) ->
((mat_mult_no_bound m n) = (make_f 1%Z 1%Z (fun (i:Z) (j:Z) => tzero)))).
Axiom mat_mult_no_bound_spec :
forall (m:matrix t) (n:matrix t),
(((columns m) = (rows n)) -> ((rows (mat_mult_no_bound m n)) = (rows m))) /\
((((columns m) = (rows n)) ->
((columns (mat_mult_no_bound m n)) = (columns n))) /\
(((columns m) = (rows n)) -> forall (i:Z) (j:Z),
(valid_index (mat_mult_no_bound m n) i j) ->
((get (mat_mult_no_bound m n) i j) =
(ind_sum (fun (k:Z) => (infix_asdt (get m i k) (get n k j))) 0%Z
(columns m))))).
Parameter mat_mult: (matrix t) -> (matrix t) -> matrix t.
Axiom mat_mult_def :
forall (m:matrix t) (n:matrix t), ((columns m) = (rows n)) ->
((mat_mult m n) = (mat_mult_no_bound m n)).
Axiom mat_mult_spec :
forall (m:matrix t) (n:matrix t), ((columns m) = (rows n)) ->
((rows (mat_mult m n)) = (rows m)) /\
(((columns (mat_mult m n)) = (columns n)) /\
forall (i:Z) (j:Z), (valid_index (mat_mult m n) i j) ->
((get (mat_mult m n) i j) =
(ind_sum (fun (k:Z) => (infix_asdt (get m i k) (get n k j))) 0%Z
(columns m)))).
Axiom mat_mult_values :
forall (m:matrix t) (n:matrix t) (i:Z) (j:Z), ((columns m) = (rows n)) ->
(valid_index (mat_mult m n) i j) ->
((get (mat_mult m n) i j) =
(ind_sum (fun (k:Z) => (infix_asdt (get m i k) (get n k j))) 0%Z
(columns m))).
Axiom mat_mult_columns :
forall (m:matrix t) (n:matrix t), ((columns m) = (rows n)) ->
((columns (mat_mult m n)) = (columns n)).
Axiom mat_mult_rows :
forall (m:matrix t) (n:matrix t), ((columns m) = (rows n)) ->
((rows (mat_mult m n)) = (rows m)).
Axiom mat_mult_values_quant :
forall (m:matrix t) (n:matrix t), ((columns m) = (rows n)) ->
forall (i:Z) (j:Z), (valid_index (mat_mult m n) i j) ->
((get (mat_mult m n) i j) =
(ind_sum (fun (k:Z) => (infix_asdt (get m i k) (get n k j))) 0%Z
(columns m))).
Parameter int_mat_prod: (Z -> matrix t) -> Z -> Z -> matrix t.
Axiom int_mat_prod_def :
forall (f:Z -> matrix t) (i:Z) (j:Z), (i <= j)%Z ->
(forall (k:Z) (k':Z),
(((i <= k)%Z /\ (k <= j)%Z) /\ ((i <= k')%Z /\ (k' <= j)%Z)) ->
((rows (f k)) = (rows (f k'))) /\ ((rows (f k')) = (columns (f k')))) ->
(((j - i)%Z = 0%Z) -> ((int_mat_prod f i j) = (f i))) /\
(~ ((j - i)%Z = 0%Z) ->
((int_mat_prod f i j) =
(mat_mult_no_bound (int_mat_prod f i (j - 1%Z)%Z) (f j)))).
Axiom int_mat_prod_spec :
forall (f:Z -> matrix t) (i:Z) (j:Z), (i <= j)%Z ->
(forall (k:Z) (k':Z),
(((i <= k)%Z /\ (k <= j)%Z) /\ ((i <= k')%Z /\ (k' <= j)%Z)) ->
((rows (f k)) = (rows (f k'))) /\ ((rows (f k')) = (columns (f k')))) ->
((rows (int_mat_prod f i j)) = (rows (f i))) /\
(((columns (int_mat_prod f i j)) = (columns (f i))) /\
((columns (int_mat_prod f i j)) = (rows (f i)))).
Axiom int_mat_prod_zero :
forall (f:Z -> matrix t) (i:Z) (j:Z), ((rows (f i)) = (columns (f i))) ->
(i = j) -> ((int_mat_prod f i j) = (f i)).
Parameter int_mat_prod_plus_one: (Z -> matrix t) -> Z -> Z -> unit.
Axiom int_mat_prod_plus_one_def :
forall (f:Z -> matrix t) (i:Z) (j:Z), (i < j)%Z ->
(forall (k:Z) (k':Z),
(((i <= k)%Z /\ (k <= j)%Z) /\ ((i <= k')%Z /\ (k' <= j)%Z)) ->
((rows (f k)) = (rows (f k'))) /\ ((rows (f k')) = (columns (f k')))) ->
((int_mat_prod_plus_one f i j) = tt).
Axiom int_mat_prod_plus_one_spec :
forall (f:Z -> matrix t) (i:Z) (j:Z), (i < j)%Z ->
(forall (k:Z) (k':Z),
(((i <= k)%Z /\ (k <= j)%Z) /\ ((i <= k')%Z /\ (k' <= j)%Z)) ->
((rows (f k)) = (rows (f k'))) /\ ((rows (f k')) = (columns (f k')))) ->
((int_mat_prod f i j) = (mat_mult (int_mat_prod f i (j - 1%Z)%Z) (f j))).
Axiom int_mat_prod_eq :
forall (f:Z -> matrix t) (g:Z -> matrix t) (i:Z) (j:Z), (i <= j)%Z ->
(forall (k:Z) (k':Z), ((i <= k)%Z /\ (k <= j)%Z) ->
((i <= k')%Z /\ (k' <= j)%Z) ->
((rows (f k)) = (rows (f k'))) /\ ((rows (f k')) = (columns (f k')))) ->
(forall (k:Z), ((i <= k)%Z /\ (k <= j)%Z) -> ((f k) = (g k))) ->
((int_mat_prod f i j) = (int_mat_prod g i j)).
Axiom mat_mult_id :
forall (n:Z) (m:matrix t), (n >= 0%Z)%Z -> ((columns m) = (power 2%Z n)) ->
((mat_mult m (identity n)) = m).
Axiom id_mat_mult :
forall (n:Z) (m:matrix t), (n >= 0%Z)%Z -> ((rows m) = (power 2%Z n)) ->
((mat_mult (identity n) m) = m).
Axiom mat_mult_eq :
forall (m:matrix t) (n:matrix t) (m':matrix t) (n':matrix t), (m = m') ->
(n = n') -> ((columns m) = (rows n)) -> ((mat_mult m n) = (mat_mult m' n')).
Parameter add_mat: (matrix t) -> (matrix t) -> matrix t.
Axiom add_mat_def :
forall (m:matrix t) (n:matrix t), ((rows m) = (rows n)) ->
((columns m) = (columns n)) ->
((add_mat m n) =
(make_f (rows m) (columns m)
(fun (i:Z) (j:Z) => (infix_pldt (get m i j) (get n i j))))).
Axiom add_mat_spec :
forall (m:matrix t) (n:matrix t), ((rows m) = (rows n)) ->
((columns m) = (columns n)) ->
(((columns (add_mat m n)) = (columns m)) /\ ((columns m) = (columns n))) /\
((((rows (add_mat m n)) = (rows m)) /\ ((rows m) = (rows n))) /\
forall (i:Z) (j:Z),
((get (add_mat m n) i j) = (infix_pldt (get m i j) (get n i j)))).
Axiom add_mat_equal :
forall (m:matrix t) (n:matrix t) (m':matrix t) (n':matrix t),
((rows m) = (rows n)) -> ((columns m) = (columns n)) -> (m = m') ->
(n = n') -> ((add_mat m n) = (add_mat m' n')).
Axiom add_value :
forall (m:matrix t) (n:matrix t), ((columns m) = (columns n)) ->
((rows m) = (rows n)) -> ((columns m) = (columns n)) -> forall (i:Z) (j:Z),
((0%Z <= i)%Z /\ (i < (rows m))%Z) ->
((0%Z <= j)%Z /\ (j < (columns m))%Z) ->
((get (add_mat m n) i j) = (infix_pldt (get m i j) (get n i j))).
Axiom add_values :
forall (m:matrix t) (n:matrix t) (i:Z) (j:Z),
((columns m) = (columns n)) -> ((rows m) = (rows n)) ->
((get (add_mat m n) i j) = (infix_pldt (get m i j) (get n i j))).
Axiom add_mat_null_left :
forall (m:matrix t) (n:matrix t), ((columns m) = (columns n)) ->
((rows m) = (rows n)) -> (null_mat m) -> ((add_mat m n) = n).
Axiom add_mat_null_right :
forall (m:matrix t) (n:matrix t), ((columns m) = (columns n)) ->
((rows m) = (rows n)) -> (null_mat n) -> ((add_mat m n) = m).
Axiom set_equal_columns_elt :
forall (m:matrix t) (n:matrix t) (i:Z),
(((columns m) = (columns n)) /\ ((columns n) = i)) ->
((columns m) = (columns n)).
Axiom set_equal_rows_elt :
forall (m:matrix t) (n:matrix t) (i:Z),
(((rows m) = (rows n)) /\ ((rows n) = i)) -> ((rows m) = (rows n)).
Axiom add_columns :
forall (m:matrix t) (n:matrix t), ((columns m) = (columns n)) ->
((rows m) = (rows n)) -> ((columns (add_mat m n)) = (columns m)).
Axiom add_rows :
forall (m:matrix t) (n:matrix t), ((columns m) = (columns n)) ->
((rows m) = (rows n)) -> ((rows (add_mat m n)) = (rows m)).
Axiom set_equal_dim_elt :
forall (m:matrix t) (n:matrix t) (i:Z) (j:Z),
(((rows m) = (rows n)) /\ ((rows n) = i)) ->
(((columns m) = (columns n)) /\ ((columns n) = j)) ->
((columns m) = (columns n)) /\ ((rows m) = (rows n)).
Axiom set_dim_add :
forall (m:matrix t) (n:matrix t) (i:Z) (j:Z),
(((rows m) = (rows n)) /\ ((rows n) = i)) ->
(((columns m) = (columns n)) /\ ((columns n) = j)) ->
((rows (add_mat m n)) = i) /\ ((columns (add_mat m n)) = j).
Axiom add_mat_eq :
forall (m:matrix t) (m1:matrix t) (n:matrix t) (n1:matrix t),
((rows m) = (rows n)) -> ((columns m) = (columns n)) -> (m = m1) ->
(n = n1) -> ((add_mat m n) = (add_mat m1 n1)).
Axiom add_mat_comm :
forall (m:matrix t) (n:matrix t), ((rows m) = (rows n)) ->
((columns m) = (columns n)) -> ((add_mat m n) = (add_mat n m)).
Parameter add_neutral: unit -> matrix t.
Axiom add_neutral_spec :
forall (us:unit),
(forall (i:Z) (j:Z), (valid_index (add_neutral us) i j) ->
((get (add_neutral us) i j) = tzero)) /\
(((rows (add_neutral us)) > 0%Z)%Z /\ ((columns (add_neutral us)) > 0%Z)%Z).
Axiom distr_1_pre :
forall (m:matrix t) (n:matrix t) (o:matrix t) (i:Z) (j:Z),
((rows m) = (rows n)) -> ((columns m) = (columns n)) ->
((columns m) = (rows o)) -> ((0%Z <= i)%Z /\ (i < (rows m))%Z) ->
((0%Z <= j)%Z /\ (j < (columns o))%Z) ->
((get (mat_mult (add_mat m n) o) i j) =
(get (add_mat (mat_mult m o) (mat_mult n o)) i j)).
Axiom distr_l :
forall (m:matrix t) (n:matrix t) (o:matrix t), ((rows m) = (rows n)) ->
((columns m) = (columns n)) -> ((columns m) = (rows o)) ->
((mat_mult (add_mat m n) o) = (add_mat (mat_mult m o) (mat_mult n o))).
Axiom distr_2_pre :
forall (m:matrix t) (n:matrix t) (o:matrix t) (i:Z) (j:Z),
((rows n) = (rows o)) -> ((columns n) = (columns o)) ->
((columns m) = (rows n)) -> ((0%Z <= i)%Z /\ (i < (rows m))%Z) ->
((0%Z <= j)%Z /\ (j < (columns n))%Z) ->
(valid_index (mat_mult m (add_mat n o)) i j) /\
((get (mat_mult m (add_mat n o)) i j) =
(get (add_mat (mat_mult m n) (mat_mult m o)) i j)).
Axiom distr_r :
forall (m:matrix t) (n:matrix t) (o:matrix t), ((rows n) = (rows o)) ->
((columns n) = (columns o)) -> ((columns m) = (rows n)) ->
((mat_mult m (add_mat n o)) = (add_mat (mat_mult m n) (mat_mult m o))).
Parameter infix_asdtdt: t -> (matrix t) -> matrix t.
Axiom infix_asdtdt_def :
forall (s:t) (m:matrix t),
((infix_asdtdt s m) =
(make_f (rows m) (columns m)
(fun (i:Z) (j:Z) => (infix_asdt s (get m i j))))).
Axiom infix_asdtdt_spec :
forall (s:t) (m:matrix t),
((columns (infix_asdtdt s m)) = (columns m)) /\
(((rows (infix_asdtdt s m)) = (rows m)) /\
((forall (i:Z) (j:Z), (valid_index (infix_asdtdt s m) i j) ->
((get (infix_asdtdt s m) i j) = (infix_asdt s (get m i j)))) /\
forall (i:Z) (j:Z),
(valid_index (infix_asdtdt s m) i j) <-> (valid_index m i j))).
Axiom scalar_columns :
forall (m:matrix t) (a:t), ((columns (infix_asdtdt a m)) = (columns m)).
Axiom scalar_values :
forall (m:matrix t) (a:t) (i:Z) (j:Z),
((get (infix_asdtdt a m) i j) = (infix_asdt a (get m i j))).
Axiom scalar_rows :
forall (m:matrix t) (a:t), ((rows (infix_asdtdt a m)) = (rows m)).
Axiom scalar_null : forall (m:matrix t), null_mat (infix_asdtdt tzero m).
Axiom scalar_tone : forall (m:matrix t), ((infix_asdtdt tone m) = m).
Axiom scalar_tone_gen :
forall (m:matrix t) (a:t), (a = tone) -> ((infix_asdtdt a m) = m).
Axiom scalar_null_gen :
forall (m:matrix t) (a:t), (a = tzero) -> null_mat (infix_asdtdt a m).
Axiom scalar_plus :
forall (m:matrix t) (a:t) (b:t),
((infix_asdtdt (infix_pldt a b) m) =
(add_mat (infix_asdtdt a m) (infix_asdtdt b m))).
Axiom scalar_plus_rev :
forall (m:matrix t) (a:t) (b:t),
((add_mat (infix_asdtdt a m) (infix_asdtdt b m)) =
(infix_asdtdt (infix_pldt a b) m)).
Axiom add_scal :
forall (m:matrix t) (n:matrix t) (a:t), ((rows m) = (rows n)) ->
((columns m) = (columns n)) ->
((infix_asdtdt a (add_mat m n)) =
(add_mat (infix_asdtdt a m) (infix_asdtdt a n))).
Axiom mat_mult_scal_values_l :
forall (m:matrix t) (n:matrix t) (a:t) (i:Z) (j:Z),
((rows n) = (columns m)) -> ((0%Z <= i)%Z /\ (i < (rows m))%Z) ->
((0%Z <= j)%Z /\ (j < (columns n))%Z) ->
((infix_asdt a (get (mat_mult m n) i j)) =
(ind_sum
(fun (k:Z) => (infix_asdt (infix_asdt a (get m i k)) (get n k j))) 0%Z
(columns m))).
Axiom mat_mult_scal_values_r :
forall (m:matrix t) (n:matrix t) (a:t) (i:Z) (j:Z),
((rows n) = (columns m)) -> ((rows m) = (columns n)) ->
((columns m) = (columns n)) -> ((0%Z <= i)%Z /\ (i < (rows m))%Z) ->
((0%Z <= j)%Z /\ (j < (columns n))%Z) ->
((infix_asdt (get (mat_mult m n) i j) a) =
(ind_sum
(fun (k:Z) => (infix_asdt (infix_asdt a (get m i k)) (get n k j))) 0%Z
(columns m))).
Axiom mat_mut_scal :
forall (m:matrix t) (n:matrix t) (a:t), ((rows n) = (columns m)) ->
((mat_mult m (infix_asdtdt a n)) = (infix_asdtdt a (mat_mult m n))).
Axiom scal_mat_mut :
forall (m:matrix t) (n:matrix t) (a:t), ((rows n) = (columns m)) ->
((mat_mult (infix_asdtdt a m) n) = (infix_asdtdt a (mat_mult m n))).
Axiom ind_sum_commute_scal_r :
forall (f:Z -> Z -> t) (g:Z -> t) (i:Z) (j:Z) (k:Z) (l:Z), (i <= j)%Z ->
(k <= l)%Z ->
((ind_sum (fun (k1:Z) => (infix_asdt (ind_sum (f k1) k l) (g k1))) i j) =
(ind_sum
(fun (k1:Z) =>
(ind_sum (fun (k2:Z) => (infix_asdt ((f k2) k1) (g k2))) i j))
k l)).
Axiom mat_mult_assoc_pre :
forall (m:matrix t) (n:matrix t) (o:matrix t) (i:Z) (j:Z),
((columns m) = (rows n)) -> ((columns n) = (rows o)) ->
((0%Z <= i)%Z /\ (i < (rows m))%Z) ->
((0%Z <= j)%Z /\ (j < (columns o))%Z) ->
((get (mat_mult (mat_mult m n) o) i j) =
(get (mat_mult m (mat_mult n o)) i j)).
Axiom mat_mult_assoc :
forall (m:matrix t) (n:matrix t) (o:matrix t), ((columns m) = (rows n)) ->
((columns n) = (rows o)) ->
((mat_mult (mat_mult m n) o) = (mat_mult m (mat_mult n o))).
Axiom mat_mult_assoc_quant :
forall (m:matrix t) (n:matrix t), ((columns m) = (rows n)) ->
forall (o:matrix t), ((columns n) = (rows o)) ->
((mat_mult (mat_mult m n) o) = (mat_mult m (mat_mult n o))).
Axiom mat_mult_assoc_comm :
forall (m:matrix t) (n:matrix t) (o:matrix t), ((columns m) = (rows n)) ->
((columns n) = (rows o)) ->
((mat_mult m (mat_mult n o)) = (mat_mult (mat_mult m n) o)).
Axiom scalar_eq :
forall (m:matrix t) (n:matrix t) (a:t), (m = n) ->
((infix_asdtdt a m) = (infix_asdtdt a n)).
Axiom scalar_eq_gen :
forall (m:matrix t) (n:matrix t) (a:t) (b:t), (m = n) -> (a = b) ->
((infix_asdtdt a m) = (infix_asdtdt b n)).
Axiom scalar_add :
forall (m:matrix t) (a:t) (b:t),
((infix_asdtdt (infix_pldt a b) m) =
(add_mat (infix_asdtdt a m) (infix_asdtdt b m))).
Axiom scalar_assoc :
forall (m:matrix t) (a:t) (b:t),
((infix_asdtdt a (infix_asdtdt b m)) = (infix_asdtdt (infix_asdt a b) m)).
Axiom scalar_assoc_rev :
forall (m:matrix t) (a:t) (b:t),
((infix_asdtdt (infix_asdt a b) m) = (infix_asdtdt a (infix_asdtdt b m))).
Axiom eq_scalar :
forall (m:matrix t) (a:t) (b:t),
(exists i:Z, exists j:Z, (valid_index m i j) /\ ~ ((get m i j) = tzero)) ->
((infix_asdtdt a m) = (infix_asdtdt b m)) -> (a = b).
Parameter mat_substr: (matrix t) -> (matrix t) -> matrix t.
Axiom mat_substr_def :
forall (m:matrix t) (n:matrix t), ((rows m) = (rows n)) ->
((columns m) = (columns n)) ->
((mat_substr m n) = (add_mat m (infix_asdtdt (prefix_mndt tone) n))).
Axiom mat_substr_spec :
forall (m:matrix t) (n:matrix t), ((rows m) = (rows n)) ->
((columns m) = (columns n)) ->
((rows (mat_substr m n)) = (rows m)) /\
(((columns (mat_substr m n)) = (columns m)) /\
forall (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < (rows m))%Z) ->
((0%Z <= j)%Z /\ (j < (columns m))%Z) ->
((get (mat_substr m n) i j) = (infix_mndt (get m i j) (get n i j)))).
Axiom substr_rows :
forall (m:matrix t) (n:matrix t) (r:Z),
(((rows m) = (rows n)) /\ ((rows n) = r)) -> ((columns m) = (columns n)) ->
((rows (mat_substr m n)) = r).
Axiom substr_columns :
forall (m:matrix t) (n:matrix t) (c:Z), ((rows m) = (rows n)) ->
(((columns m) = (columns n)) /\ ((columns n) = c)) ->
((columns (mat_substr m n)) = c).
Axiom substr_value :
forall (m:matrix t) (n:matrix t) (i:Z) (j:Z), ((rows m) = (rows n)) ->
((columns m) = (columns n)) -> ((0%Z <= i)%Z /\ (i < (rows m))%Z) ->
((0%Z <= j)%Z /\ (j < (columns m))%Z) ->
((get (mat_substr m n) i j) = (infix_mndt (get m i j) (get n i j))).
Axiom distr_l_substr :
forall (m:matrix t) (n:matrix t) (o:matrix t), ((rows m) = (rows n)) ->
((columns m) = (columns n)) -> ((columns m) = (rows o)) ->
((mat_mult (mat_substr m n) o) =
(mat_substr (mat_mult m o) (mat_mult n o))).
Axiom distr_r_substr :
forall (m:matrix t) (n:matrix t) (o:matrix t), ((rows n) = (rows o)) ->
((columns n) = (columns o)) -> ((columns m) = (rows o)) ->
((mat_mult m (mat_substr n o)) =
(mat_substr (mat_mult m n) (mat_mult m o))).
Axiom mat_substr_eq :
forall (m:matrix t) (m':matrix t) (n:matrix t) (n':matrix t),
((rows m) = (rows n)) -> ((columns m) = (columns n)) -> (m = m') ->
(n = n') -> ((mat_substr m n) = (mat_substr m' n')).
Axiom substr_decomp :
forall (m:matrix t) (n:matrix t), ((rows m) = (rows n)) ->
((columns m) = (columns n)) -> (m = (add_mat n (mat_substr m n))).
Axiom get_equal_mat_to_substr :
forall (m:matrix t) (n:matrix t), ((rows m) = (rows n)) ->
((columns m) = (columns n)) -> (m = n) ->
((mat_substr m n) = (make (rows m) (columns m) tzero)).
Axiom set_inequal_mat_by_substr :
forall (m:matrix t) (n:matrix t), ((rows m) = (rows n)) ->
((columns m) = (columns n)) ->
~ (m = n) <-> ~ ((mat_substr m n) = (make (rows m) (columns m) tzero)).
Axiom pow_inv_2_scal :
forall (i:Z) (x:matrix t), (0%Z <= i)%Z ->
((infix_asdtdt (pow_inv_2 i) x) =
(infix_asdtdt (pow_inv_sqrt_2 i) (infix_asdtdt (pow_inv_sqrt_2 i) x))).
Axiom pow_inv_2_from_int :
forall (n:Z), (0%Z <= n)%Z ->
((pow_inv_2 n) = (infix_sldt tone (i_to_t (power 2%Z n)))).
Axiom pow_inv_2_sq_rt :
forall (n:Z), (0%Z <= n)%Z ->
((square_rt (pow_inv_2 n)) = (pow_inv_sqrt_2 n)).
Axiom pos_pow_inv_2 :
forall (i:Z), (0%Z <= i)%Z -> infix_lseqdt tzero (pow_inv_2 i).
Axiom strict_pos_pow_inv_2 :
forall (i:Z), (0%Z <= i)%Z -> infix_lsdt tzero (pow_inv_2 i).
Axiom pow_inv_2_add :
forall (i:Z) (j:Z), (0%Z <= i)%Z -> (0%Z <= j)%Z ->
((pow_inv_2 (i + j)%Z) = (infix_asdt (pow_inv_2 i) (pow_inv_2 j))).
Axiom pow_inv_2_with_ :
forall (i:Z), (0%Z <= i)%Z ->
((pow_inv_2 i) = (infix_sldt tone (i_to_t (power_ 2%Z i)))).
Axiom pow_inv_2_to_one :
forall (i:Z), (0%Z <= i)%Z ->
((infix_asdt (i_to_t (power_ 2%Z i)) (pow_inv_2 i)) = tone).
Axiom pow_inv_2_one :
forall (i:Z), (i = 1%Z) ->
((i_to_t (power_ 2%Z i)) = (infix_sldt tone ttwo)).
Axiom pow_inv_2_to_one_gen :
forall (i:Z) (x:t), (0%Z <= i)%Z -> (x = (i_to_t (power_ 2%Z i))) ->
((infix_asdt (pow_inv_2 i) x) = tone).
Axiom pow_inv_to_pow_2 :
forall (k:Z) (l:Z), (0%Z <= l)%Z -> (k >= l)%Z ->
((infix_asdt (pow_inv_2 k) (i_to_t (power_ 2%Z l))) =
(pow_inv_2 (k - l)%Z)).
Parameter neg_pow_inv_sqrt_2: Z -> t.
Axiom neg_pow_inv_sqrt_2_def :
forall (i:Z), (0%Z <= i)%Z ->
((neg_pow_inv_sqrt_2 i) = (cpower neg_coeff i)).
Axiom inv_pow_inv_sqrt_2 :
((infix_asdt (pow_inv_sqrt_2 1%Z) squarert_two) = tone).
Axiom pow_inv_sqrt_2_values :
forall (i:Z), (0%Z <= i)%Z ->
((pow_inv_sqrt_2 i) = (infix_sldt tone (cpower squarert_two i))).
Axiom neg_pow_inv_sqrt_2_values :
forall (i:Z), (0%Z <= i)%Z ->
((neg_pow_inv_sqrt_2 i) =
(infix_asdt (mop i) (infix_sldt tone (cpower squarert_two i)))).
Axiom ppos_neg_coeff_values :
forall (i:Z), (0%Z <= i)%Z ->
(((even i) = true) -> ((pow_inv_sqrt_2 i) = (neg_pow_inv_sqrt_2 i))) /\
((((odd i) = true) ->
((pow_inv_sqrt_2 i) = (prefix_mndt (neg_pow_inv_sqrt_2 i)))) /\
((neg_pow_inv_sqrt_2 i) = (infix_asdt (mop i) (pow_inv_sqrt_2 i)))).
Parameter pow_inv_sqrt_2_neg: Z -> t.
Axiom pow_inv_sqrt_2_neg_def :
forall (i:Z), (0%Z <= i)%Z ->
((pow_inv_sqrt_2_neg i) = (prefix_mndt (pow_inv_sqrt_2 i))).
Parameter min_set: (set Z) -> Z.
Axiom min_set_def :
forall (s:set Z), ((cardinal s) > 0%Z)%Z ->
(((cardinal s) = 1%Z) -> ((min_set s) = (choose s))) /\
(~ ((cardinal s) = 1%Z) ->
((min_set s) =
(ZArith.BinInt.Z.min (choose s) (min_set (remove (choose s) s))))).
Axiom min_set_spec :
forall (s:set Z), ((cardinal s) > 0%Z)%Z ->
(mem (min_set s) s) /\ forall (e1:Z), (mem e1 s) -> (e1 >= (min_set s))%Z.
Parameter max_set: (set Z) -> Z.
Axiom max_set_def :
forall (s:set Z), ((cardinal s) > 0%Z)%Z ->
(((cardinal s) = 1%Z) -> ((max_set s) = (choose s))) /\
(~ ((cardinal s) = 1%Z) ->
((max_set s) =
(ZArith.BinInt.Z.max (choose s) (max_set (remove (choose s) s))))).
Axiom max_set_spec :
forall (s:set Z), ((cardinal s) > 0%Z)%Z ->
(mem (max_set s) s) /\ forall (e1:Z), (mem e1 s) -> (e1 <= (max_set s))%Z.
Parameter max3: Z -> Z -> Z -> Z.
Axiom max3_def :
forall (a:Z) (b:Z) (c:Z),
((max3 a b c) = (ZArith.BinInt.Z.max (ZArith.BinInt.Z.max a b) c)).
Axiom max3_spec :
forall (a:Z) (b:Z) (c:Z),
((max3 a b c) = (ZArith.BinInt.Z.max a (ZArith.BinInt.Z.max b c))).
Parameter min_filter: (set Z) -> (Z -> bool) -> Z.
Axiom min_filter_def :
forall (s:set Z) (p:Z -> bool),
(exists e1:Z, (mem e1 s) /\ ((p e1) = true)) ->
(((p (min_set s)) = true) -> ((min_filter s p) = (min_set s))) /\
(~ ((p (min_set s)) = true) ->
((min_filter s p) = (min_filter (remove (min_set s) s) p))).
Axiom min_filter_spec :
forall (s:set Z) (p:Z -> bool),
(exists e1:Z, (mem e1 s) /\ ((p e1) = true)) ->
((p (min_filter s p)) = true) /\
((mem (min_filter s p) s) /\
forall (e1:Z), (mem e1 s) -> ((p e1) = true) -> (e1 >= (min_filter s p))%Z).
Parameter max_filter: (set Z) -> (Z -> bool) -> Z.
Axiom max_filter_def :
forall (s:set Z) (p:Z -> bool),
(exists e1:Z, (mem e1 s) /\ ((p e1) = true)) ->
(((p (max_set s)) = true) -> ((max_filter s p) = (max_set s))) /\
(~ ((p (max_set s)) = true) ->
((max_filter s p) = (max_filter (remove (max_set s) s) p))).
Axiom max_filter_spec :
forall (s:set Z) (p:Z -> bool),
(exists e1:Z, (mem e1 s) /\ ((p e1) = true)) ->
((p (max_filter s p)) = true) /\
((mem (max_filter s p) s) /\
forall (e1:Z), (mem e1 s) -> ((p e1) = true) -> (e1 <= (max_filter s p))%Z).
Axiom appr :
forall (theta:t) (n:Z), (0%Z < n)%Z -> (real_ theta) ->
((infix_lseqdt tzero theta) /\ (infix_lsdt theta tone)) ->
exists k:Z,
(mem k (to_fset 0%Z (n + 1%Z)%Z)) /\
(infix_lseqdt
(modulus (infix_mndt theta (infix_sldt (i_to_t k) (i_to_t n))))
(infix_sldt tone (i_to_t (n * 2%Z)%Z))).
Parameter max_dyadic: Z -> t -> Z.
Parameter result7: Z -> t -> Z -> bool.
Axiom result_def7 :
forall (n:Z) (p:t) (x:Z),
(((result7 n p) x) = true) <->
(infix_lseqdt (infix_asdt (i_to_t x) (pow_inv_2 n)) p).
Axiom max_dyadic_def :
forall (n:Z) (p:t), ((infix_lseqdt tzero p) /\ (infix_lsdt p tone)) ->
((max_dyadic n p) =
(max_filter (to_fset 0%Z (power_ 2%Z n)) (result7 n p))).
Axiom max_dyadic_spec :
forall (n:Z) (p:t), ((infix_lseqdt tzero p) /\ (infix_lsdt p tone)) ->
((0%Z <= (max_dyadic n p))%Z /\ ((max_dyadic n p) < (power_ 2%Z n))%Z) /\
((infix_lseqdt (infix_asdt (i_to_t (max_dyadic n p)) (pow_inv_2 n)) p) /\
((infix_gteqdt
(infix_asdt (i_to_t ((max_dyadic n p) + 1%Z)%Z) (pow_inv_2 n)) p) /\
forall (i:Z), ((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) ->
(infix_lseqdt (infix_asdt (i_to_t i) (pow_inv_2 n)) p) ->
(i <= (max_dyadic n p))%Z)).
Axiom int_to_ang_to_real_to_ang :
forall (theta:angle) (k:Z) (n:Z), (n >= 0%Z)%Z ->
(theta = (int_to_ang k n)) ->
(theta = (real_to_ang (infix_asdt (i_to_t k) (pow_inv_2 n)))).
Axiom real_to_ang_to_int_to_ang :
forall (k:Z) (n:Z), (n >= 0%Z)%Z ->
((real_to_ang (infix_asdt (i_to_t k) (pow_inv_2 n))) = (int_to_ang k n)).
Axiom real_to_ang_to_int_to_ang_add :
forall (k:Z) (k':Z) (n:Z), (n >= 0%Z)%Z ->
((real_to_ang
(infix_asdt (infix_pldt (i_to_t k) (i_to_t k')) (pow_inv_2 n)))
= (int_to_ang (k + k')%Z n)).
Axiom int_to_ang_to_real_to_ang_gen :
forall (k:Z) (n:Z) (kx:t), (n >= 0%Z)%Z -> (kx = (i_to_t k)) ->
((int_to_ang k n) = (real_to_ang (infix_asdt kx (pow_inv_2 n)))).
Axiom Equal_angle :
forall (o:angle) (o':angle), ((ang_exp o) = (ang_exp o')) <-> (o = o').
Axiom Int_To_Ang_inv :
forall (k:Z) (n:Z), (n >= 0%Z)%Z ->
((ang_inv (int_to_ang k n)) = (int_to_ang (-k)%Z n)).
Axiom Int_To_Ang_inv_add :
forall (k:Z) (n:Z), (n >= 0%Z)%Z ->
((ang_add (int_to_ang k n) (int_to_ang (-k)%Z n)) = ang_zero).
Axiom Int_To_Ang_add :
forall (k:Z) (k':Z) (n:Z), (n >= 0%Z)%Z ->
((ang_add (int_to_ang k n) (int_to_ang k' n)) = (int_to_ang (k + k')%Z n)).
Axiom Int_To_Ang_up :
forall (k:Z) (n:Z), (0%Z <= n)%Z ->
((int_to_ang k n) = (int_to_ang (2%Z * k)%Z (n + 1%Z)%Z)).
Axiom Int_To_Ang_cyclic :
forall (k:Z) (n:Z), (0%Z <= n)%Z ->
((int_to_ang k n) = (int_to_ang (k + (power 2%Z n))%Z n)).
Axiom Zero_n : forall (n:Z), (n >= 0%Z)%Z -> ((int_to_ang 0%Z n) = ang_zero).
Parameter ang_minus_one: angle.
Axiom ang_minus_one_def : (ang_minus_one = (int_to_ang 1%Z 1%Z)).
Axiom set_ang_minus_one_by_int :
forall (a:Z) (b:Z), (a = 1%Z) -> (b = 1%Z) ->
((int_to_ang a b) = ang_minus_one).
Axiom ang_minus_one_from_real :
(ang_minus_one = (real_to_ang (infix_sldt tone ttwo))).
Axiom ang_exp_minus_one : ((ang_exp ang_minus_one) = (prefix_mndt tone)).
Axiom set_ang_zero_by_int :
forall (a:Z) (b:Z), (a = 0%Z) -> (0%Z <= b)%Z ->
((int_to_ang a b) = ang_zero).
Axiom ang_minus_one_twice :
forall (a1:angle) (a2:angle), (a1 = ang_minus_one) ->
(a2 = ang_minus_one) -> ((ang_add a1 a2) = ang_zero).
Parameter div_two_: angle -> angle.
Axiom Div_two : forall (d:angle), ((ang_add (div_two_ d) (div_two_ d)) = d).
Axiom Div_two_int_to_ang :
forall (k:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) ->
((div_two_ (int_to_ang k n)) = (int_to_ang k (n + 1%Z)%Z)).
Axiom Add1 :
forall (d:angle) (d':angle),
((ang_exp (ang_add d d')) = (infix_asdt (ang_exp d) (ang_exp d'))).
Axiom ang_exp_mult :
forall (x:angle) (x':angle),
((infix_asdt (ang_exp x) (ang_exp x')) = (ang_exp (ang_add x x'))).
Parameter k_int_to_ang: Z -> angle.
Axiom k_int_to_ang_def :
forall (k:Z), (0%Z <= k)%Z -> ((k_int_to_ang k) = (int_to_ang 1%Z k)).
Axiom K_int_to_angplus_one :
forall (k:Z), (k > 0%Z)%Z ->
((ang_add (k_int_to_ang k) (k_int_to_ang k)) = (k_int_to_ang (k - 1%Z)%Z)).
Parameter phase_inv_: Z -> angle -> angle.
Axiom Even_phase_inv :
forall (d:angle), forall (i:Z),
((int.EuclideanDivision.mod1 i 2%Z) = 0%Z) -> ((phase_inv_ i d) = d).
Axiom Odd_phase_inv :
forall (d:angle), forall (i:Z),
((int.EuclideanDivision.mod1 i 2%Z) = 1%Z) ->
((phase_inv_ i d) = (ang_inv d)).
Axiom Gen_phase_inv :
forall (k:Z) (n:Z) (i:Z), (n >= 0%Z)%Z -> (i >= 0%Z)%Z ->
((phase_inv_ i (int_to_ang k n)) =
(int_to_ang ((power (-1%Z)%Z i) * k)%Z n)).
Axiom Gen_phase_inv_neg :
forall (k:Z) (n:Z) (i:Z), (n >= 0%Z)%Z -> (i < 0%Z)%Z ->
((phase_inv_ i (int_to_ang k n)) =
(int_to_ang ((power (-1%Z)%Z (-i)%Z) * k)%Z n)).
Axiom Ang_exp_inv :
forall (o:angle), ((ang_exp (ang_inv o)) = (infix_sldt tone (ang_exp o))).
Axiom ang_inv_to_conjugate :
forall (o:angle), ((ang_exp (ang_inv o)) = (conjugate (ang_exp o))).
Axiom conjugate_to_ang_inv :
forall (o:angle), ((conjugate (ang_exp o)) = (ang_exp (ang_inv o))).
Axiom ang_exp_zero_ : ((ang_exp ang_zero) = tone).
Axiom ang_mult_int_in :
forall (i:Z) (k:Z) (n:Z), (0%Z <= n)%Z ->
((ang_mult_int (int_to_ang k n) i) = (int_to_ang (i * k)%Z n)).
Axiom ang_mult_int_out :
forall (i:Z) (k:Z) (n:Z), (0%Z <= n)%Z ->
((int_to_ang (i * k)%Z n) = (ang_mult_int (int_to_ang k n) i)).
Axiom int_to_ang_cycles :
forall (k:Z) (n:Z) (i:Z), (0%Z <= n)%Z -> (0%Z <= i)%Z ->
((int_to_ang (k + (i * (power 2%Z n))%Z)%Z n) = (int_to_ang k n)).
Axiom int_to_ang_bin_rev :
forall (n:Z) (i:Z) (j:Z), (0%Z <= n)%Z -> (0%Z <= i)%Z ->
(j = (n - 1%Z)%Z) ->
((int_to_ang (-(i * (power 2%Z j))%Z)%Z n) =
(int_to_ang (i * (power 2%Z (n - 1%Z)%Z))%Z n)).
Axiom int_to_ang_bin_rev_ :
forall (n:Z) (i:Z) (j:Z), (0%Z <= n)%Z -> (0%Z <= i)%Z ->
(j = (n - 1%Z)%Z) ->
((int_to_ang (-(i * (power_ 2%Z j))%Z)%Z n) =
(int_to_ang (i * (power_ 2%Z (n - 1%Z)%Z))%Z n)).
Axiom int_to_ang_add_rev :
forall (i:Z) (j:Z) (n:Z), (0%Z <= n)%Z ->
((int_to_ang (i + j)%Z n) = (ang_add (int_to_ang i n) (int_to_ang j n))).
Axiom int_to_ang_ind_isum_plus_one :
forall (f:Z -> Z) (i:Z) (j:Z) (n:Z), (i < j)%Z -> (0%Z <= n)%Z ->
((int_to_ang (ind_isum f i j) n) =
(ang_add (int_to_ang (f i) n) (int_to_ang (ind_isum f (i + 1%Z)%Z j) n))).
Axiom int_to_ang_ind_isum_plus_one_rev :
forall (f:Z -> Z) (i:Z) (j:Z) (n:Z), (i < j)%Z -> (0%Z <= n)%Z ->
((int_to_ang (ind_isum f i j) n) =
(ang_add (int_to_ang (ind_isum f (i + 1%Z)%Z j) n) (int_to_ang (f i) n))).
Axiom int_to_ang_ind_isum_right_extension :
forall (f:Z -> Z) (i:Z) (j:Z) (n:Z), (i < j)%Z -> (0%Z <= n)%Z ->
((int_to_ang (ind_isum f i j) n) =
(ang_add (int_to_ang (ind_isum f i (j - 1%Z)%Z) n)
(int_to_ang (f (j - 1%Z)%Z) n))).
Axiom int_to_ang_ind_isum_right_extension_rev :
forall (f:Z -> Z) (i:Z) (j:Z) (n:Z), (i < j)%Z -> (0%Z <= n)%Z ->
((int_to_ang (ind_isum f i j) n) =
(ang_add (int_to_ang (f (j - 1%Z)%Z) n)
(int_to_ang (ind_isum f i (j - 1%Z)%Z) n))).
Axiom minus_int_to_ang_ind_isum_plus_one :
forall (f:Z -> Z) (i:Z) (j:Z) (n:Z), (i < j)%Z -> (0%Z <= n)%Z ->
((int_to_ang (-(ind_isum f i j))%Z n) =
(ang_add (int_to_ang (-(f i))%Z n)
(int_to_ang (-(ind_isum f (i + 1%Z)%Z j))%Z n))).
Axiom minus_int_to_ang_ind_isum_plus_one_rev :
forall (f:Z -> Z) (i:Z) (j:Z) (n:Z), (i < j)%Z -> (0%Z <= n)%Z ->
((int_to_ang (-(ind_isum f i j))%Z n) =
(ang_add (int_to_ang (-(ind_isum f (i + 1%Z)%Z j))%Z n)
(int_to_ang (-(f i))%Z n))).
Axiom minus_int_to_ang_ind_isum_right_extension :
forall (f:Z -> Z) (i:Z) (j:Z) (n:Z), (i < j)%Z -> (0%Z <= n)%Z ->
((int_to_ang (-(ind_isum f i j))%Z n) =
(ang_add (int_to_ang (-(ind_isum f i (j - 1%Z)%Z))%Z n)
(int_to_ang (-(f (j - 1%Z)%Z))%Z n))).
Axiom minus_int_to_ang_ind_isum_right_extension_rev :
forall (f:Z -> Z) (i:Z) (j:Z) (n:Z), (i < j)%Z -> (0%Z <= n)%Z ->
((int_to_ang (-(ind_isum f i j))%Z n) =
(ang_add (int_to_ang (-(f (j - 1%Z)%Z))%Z n)
(int_to_ang (-(ind_isum f i (j - 1%Z)%Z))%Z n))).
Axiom real_to_ang_add_rev :
forall (i:t) (j:t), (real_ i) -> (real_ j) ->
((real_to_ang (infix_pldt i j)) =
(ang_add (real_to_ang i) (real_to_ang j))).
Axiom int_to_ang_cycles_neg :
forall (k:Z) (n:Z) (i:Z), (0%Z <= n)%Z -> (0%Z >= i)%Z ->
((int_to_ang (k + (i * (power 2%Z n))%Z)%Z n) = (int_to_ang k n)).
Axiom int_to_ang_cycles_gen :
forall (k:Z) (n:Z) (i:Z), (0%Z <= n)%Z ->
((int_to_ang (k + (i * (power 2%Z n))%Z)%Z n) = (int_to_ang k n)).
Axiom int_to_ang_cycles_zero :
forall (n':Z) (n:Z), ((0%Z <= n)%Z /\ (n <= n')%Z) ->
((int_to_ang (power 2%Z n') n) = ang_zero).
Axiom int_to_ang_cycles_zero_mult :
forall (k:Z) (n':Z) (n:Z), ((0%Z <= n)%Z /\ (n <= n')%Z) ->
((int_to_ang (k * (power 2%Z n'))%Z n) = ang_zero).
Axiom int_to_ang_cycles_zero_mult_ :
forall (k:Z) (n':Z) (n:Z), ((0%Z <= n)%Z /\ (n <= n')%Z) ->
((int_to_ang (k * (power_ 2%Z n'))%Z n) = ang_zero).
Axiom int_to_ang_eq :
forall (k1:Z) (k2:Z) (n1:Z) (n2:Z), (k1 = k2) -> (n1 = n2) ->
((int_to_ang k1 n1) = (int_to_ang k2 n2)).
Axiom int_to_ang_mod :
forall (k:Z) (n:Z), (0%Z <= n)%Z ->
((int_to_ang k n) =
(int_to_ang (int.EuclideanDivision.mod1 k (power 2%Z n)) n)).
Axiom int_to_ang_equiv :
forall (k1:Z) (k2:Z) (n1:Z) (n2:Z),
((int.EuclideanDivision.mod1 k1 (power_ 2%Z n1)) =
(int.EuclideanDivision.mod1 k2 (power_ 2%Z n1))) ->
(n1 = n2) -> ((int_to_ang k1 n1) = (int_to_ang k2 n2)).
Axiom int_to_ang_red :
forall (k:Z) (n:Z), (1%Z <= n)%Z -> ~ (0%Z = k) ->
((int.EuclideanDivision.mod1 k 2%Z) = 0%Z) ->
((int_to_ang k n) =
(int_to_ang (int.EuclideanDivision.div k 2%Z) (n - 1%Z)%Z)).
Axiom int_to_ang_up :
forall (k:Z) (n:Z) (n':Z), (0%Z <= n)%Z -> (0%Z <= n')%Z ->
((int_to_ang (k * (power 2%Z n'))%Z (n + n')%Z) = (int_to_ang k n)).
Axiom int_to_ang_simpl :
forall (k:Z) (n1:Z) (n2:Z), (n1 >= 0%Z)%Z -> (n2 >= 0%Z)%Z ->
((int_to_ang (k * (power 2%Z n1))%Z (n2 + n1)%Z) = (int_to_ang k n2)).
Axiom ang_add_eq :
forall (d1:angle) (d2:angle) (e1:angle) (e2:angle), (d1 = e1) ->
(d2 = e2) -> ((ang_add d1 d2) = (ang_add e1 e2)).
Axiom ang_add_comm :
forall (d1:angle) (d2:angle), ((ang_add d1 d2) = (ang_add d2 d1)).
Axiom ang_add_eq_comm :
forall (d1:angle) (d2:angle) (d3:angle) (d4:angle), (d1 = d3) ->
(d2 = d4) -> ((ang_add d1 d2) = (ang_add d4 d3)).
Axiom ang_mult_int_zero :
forall (theta:angle), ((ang_mult_int theta 0%Z) = ang_zero).
Axiom ang_div :
forall (k:Z) (n:Z) (i:Z), (n >= 0%Z)%Z -> (i >= 0%Z)%Z ->
((int_to_ang k n) = (ang_mult_int (int_to_ang k (n + i)%Z) (power 2%Z i))).
Axiom ang_zero_add :
forall (d':angle) (d:angle), (d' = ang_zero) -> ((ang_add d' d) = d).
Axiom int_to_ang_rev :
forall (k:Z) (l:Z) (n:Z) (m:Z), (0%Z < n)%Z -> (0%Z <= k)%Z ->
(n = (m + 1%Z)%Z) ->
((int_to_ang (((-k)%Z * l)%Z * (power 2%Z m))%Z n) =
(int_to_ang ((k * l)%Z * (power 2%Z m))%Z n)).
Axiom int_to_ang_rev_ :
forall (k:Z) (l:Z) (n:Z) (m:Z), (0%Z < n)%Z -> (0%Z <= k)%Z ->
(0%Z <= l)%Z -> (n = (m + 1%Z)%Z) ->
((int_to_ang (((-k)%Z * l)%Z * (power_ 2%Z m))%Z n) =
(int_to_ang ((k * l)%Z * (power_ 2%Z m))%Z n)).
Axiom ang_add_zero_d :
forall (d':angle) (d:angle), (d' = ang_zero) -> ((ang_add d d') = d).
Parameter ang_sum: (Z -> angle) -> Z -> Z -> angle.
Axiom ang_sum_def :
forall (f:Z -> angle) (i:Z) (j:Z),
((j <= i)%Z -> ((ang_sum f i j) = ang_zero)) /\
(~ (j <= i)%Z ->
((ang_sum f i j) =
(int_iterate (fun (y0:angle) (y1:angle) => (ang_add y0 y1)) f i j))).
Axiom ang_sumto_int_iterate :
forall (f:Z -> angle) (i:Z) (j:Z), (i < j)%Z ->
((ang_sum f i j) =
(int_iterate (fun (y0:angle) (y1:angle) => (ang_add y0 y1)) f i j)).
Axiom ang_sum_plus_one :
forall (f:Z -> angle) (i:Z) (j:Z), ((i + 1%Z)%Z < j)%Z ->
((ang_sum f i j) = (ang_add (f i) (ang_sum f (i + 1%Z)%Z j))).
Axiom ang_sum_cardone :
forall (f:Z -> angle) (i:Z) (j:Z), (j = (i + 1%Z)%Z) ->
((ang_sum f i j) = (f i)).
Axiom ang_sum_cardone_p :
forall (f:Z -> angle) (i:Z) (j:Z) (r:angle), (j = (i + 1%Z)%Z) ->
((f i) = r) -> (r = (ang_sum f i j)).
Axiom ang_sum_neutral :
forall (f:Z -> angle) (i:Z) (j:Z), (i <= j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = ang_zero)) ->
((ang_sum f i j) = ang_zero).
Axiom ang_sum_def_plus_one_com :
forall (f:Z -> angle) (i:Z) (j:Z), ((i + 1%Z)%Z < j)%Z ->
((ang_add (f i) (ang_sum f (i + 1%Z)%Z j)) = (ang_sum f i j)).
Axiom ang_sum_right_extension :
forall (f:Z -> angle) (i:Z) (j:Z), ((i + 1%Z)%Z < j)%Z ->
((ang_sum f i j) = (ang_add (ang_sum f i (j - 1%Z)%Z) (f (j - 1%Z)%Z))).
Axiom ang_sum_transitivity :
forall (f:Z -> angle) (i:Z) (k:Z) (j:Z), ((i < k)%Z /\ (k < j)%Z) ->
((ang_sum f i j) = (ang_add (ang_sum f i k) (ang_sum f k j))).
Axiom ang_sum_eq :
forall (f:Z -> angle) (g:Z -> angle) (i:Z) (j:Z), (i <= j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((ang_sum f i j) = (ang_sum g i j)).
Axiom ang_sum_int_to_ang :
forall (f:Z -> angle) (g:Z -> angle) (i:Z) (j:Z), (i < j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
(exists n:Z,
forall (k:Z),
exists j1:Z, exists j':Z,
((f k) = (int_to_ang j1 n)) /\ (((g k) = (int_to_ang j' n)) /\ (j1 = j'))) ->
((ang_sum f i j) = (ang_sum g i j)).
Axiom vang_sum_eq :
forall (f:Z -> angle) (g:Z -> angle) (i:Z) (j:Z), (i < j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((ang_exp (ang_sum f i j)) = (ang_exp (ang_sum g i j))).
Axiom vang_sum_scal_eq :
forall (f:Z -> angle) (g:Z -> angle) (m:matrix t) (n:matrix t) (i:Z) (j:Z),
(i < j)%Z -> (m = n) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((infix_asdtdt (ang_exp (ang_sum f i j)) m) =
(infix_asdtdt (ang_exp (ang_sum g i j)) n)).
Axiom ang_sum_plus_one_p :
forall (f:Z -> angle) (g:Z -> angle) (i:Z) (j:Z) (l:Z) (m:Z) (r:angle),
((i + 1%Z)%Z < j)%Z -> (l = (i + 1%Z)%Z) -> (m = j) -> ((g i) = r) ->
(forall (k:Z), (((i + 1%Z)%Z <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((ang_add r (ang_sum f l m)) = (ang_sum g i j)).
Axiom vang_sum_plus_one_p :
forall (f:Z -> angle) (g:Z -> angle) (i:Z) (j:Z) (l:Z) (m:Z) (r:angle),
((i + 1%Z)%Z < j)%Z -> (l = (i + 1%Z)%Z) -> (m = j) -> ((g i) = r) ->
(forall (k:Z), (((i + 1%Z)%Z <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((infix_asdt (ang_exp r) (ang_exp (ang_sum f l m))) =
(ang_exp (ang_sum g i j))).
Axiom vang_sum_plus_one_rev :
forall (f:Z -> angle) (g:Z -> angle) (i:Z) (j:Z) (l:Z) (m:Z) (r:angle),
((i + 1%Z)%Z < j)%Z -> (l = (i + 1%Z)%Z) -> (m = j) -> ((g i) = r) ->
(forall (k:Z), (((i + 1%Z)%Z <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((ang_exp (ang_sum g i j)) =
(infix_asdt (ang_exp r) (ang_exp (ang_sum f l m)))).
Axiom ang_sum_right_extension_p :
forall (f:Z -> angle) (g:Z -> angle) (i:Z) (j:Z) (l:Z) (m:Z) (r:angle),
((i + 1%Z)%Z < j)%Z -> (m = (j - 1%Z)%Z) -> (l = i) ->
((g (j - 1%Z)%Z) = r) ->
(forall (k:Z), ((i <= k)%Z /\ (k < (j - 1%Z)%Z)%Z) -> ((f k) = (g k))) ->
((ang_add (ang_sum f l m) r) = (ang_sum g i j)).
Axiom vang_sum_right_extension_p :
forall (f:Z -> angle) (g:Z -> angle) (i:Z) (j:Z) (l:Z) (m:Z) (r:angle),
((i + 1%Z)%Z < j)%Z -> (m = (j - 1%Z)%Z) -> (l = i) ->
((g (j - 1%Z)%Z) = r) ->
(forall (k:Z), ((i <= k)%Z /\ (k < (j - 1%Z)%Z)%Z) -> ((f k) = (g k))) ->
((infix_asdt (ang_exp (ang_sum f l m)) (ang_exp r)) =
(ang_exp (ang_sum g i j))).
Axiom vang_sum_right_extension_rev :
forall (f:Z -> angle) (g:Z -> angle) (i:Z) (j:Z) (l:Z) (m:Z) (r:angle),
((i + 1%Z)%Z < j)%Z -> (m = (j - 1%Z)%Z) -> (l = i) ->
((g (j - 1%Z)%Z) = r) ->
(forall (k:Z), ((i <= k)%Z /\ (k < (j - 1%Z)%Z)%Z) -> ((f k) = (g k))) ->
((ang_exp (ang_sum g i j)) =
(infix_asdt (ang_exp (ang_sum f l m)) (ang_exp r))).
Axiom ang_sum_cardzero :
forall (f:Z -> angle) (i:Z) (j:Z), (j <= i)%Z ->
((ang_sum f i j) = ang_zero).
Axiom ang_sum_eq_gen :
forall (f:Z -> angle) (g:Z -> angle) (i:Z) (j:Z) (i':Z) (j':Z),
(i < j)%Z -> (i = i') -> (j = j') ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((ang_sum f i j) = (ang_sum g i' j')).
Axiom ang_sum_sum_eq_vl :
forall (f:Z -> Z -> angle) (g:Z -> Z -> angle) (i:Z) (j:Z) (i':Z) (j':Z)
(l:Z) (l':Z),
(i < j)%Z -> (j <= l)%Z -> (i = i') -> (j = j') -> (l = l') ->
(forall (x:Z) (x':Z), ((i <= x)%Z /\ (x < j)%Z) ->
((x <= x')%Z /\ (x' < l)%Z) -> (((f x) x') = ((g x) x'))) ->
((ang_sum (fun (x:Z) => (ang_sum (f x) x l)) i j) =
(ang_sum (fun (x:Z) => (ang_sum (g x) x l')) i' j')).
Axiom ang_sum_minus :
forall (f:Z -> Z) (i:Z) (j:Z) (n:Z), (n >= 0%Z)%Z -> (i < j)%Z ->
((ang_sum (fun (k:Z) => (int_to_ang (-(f k))%Z n)) i j) =
(int_to_ang (-(ind_isum f i j))%Z n)).
Parameter constant_size:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> matrix t) -> Prop.
Axiom constant_size_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t),
(constant_size s f) <->
forall (e1:a), (mem e1 s) ->
((rows (f e1)) = (rows (f (choose s)))) /\
((columns (f e1)) = (columns (f (choose s)))).
Axiom set_constant_size :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t),
(forall (e1:a) (e':a), (mem e1 s) -> (mem e' s) ->
((rows (f e1)) = (rows (f e')))) ->
(forall (e1:a) (e':a), (mem e1 s) -> (mem e' s) ->
((columns (f e1)) = (columns (f e')))) ->
constant_size s f.
Axiom set_constant_size_exists :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t),
(exists r:Z, forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(exists c:Z, forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
constant_size s f.
Axiom set_constant_size_t :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z),
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) -> constant_size s f.
Parameter fc5:
forall {a:Type} {a_WT:WhyType a}, (a -> matrix t) -> (a -> bool) ->
(matrix t) -> a -> matrix t.
Axiom fc_def5 :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (p:a -> bool) (m:matrix t) (j:a),
(((p j) = true) -> (((fc5 f p m) j) = (f j))) /\
(~ ((p j) = true) -> (((fc5 f p m) j) = m)).
Axiom guarded_set_constant_size :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (p:a -> bool) (m:matrix t),
(constant_size s f) -> (forall (e1:a), (mem e1 s) -> ((p e1) = true)) ->
constant_size s (fc5 f p m).
Axiom set_constant_size_set :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> t) (m:matrix t) (i:Z) (j:Z),
(valid_index m i j) -> constant_size s (fun (e1:a) => (set1 m i j (f e1))).
Axiom get_constant_size :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), (constant_size s f) ->
(forall (e1:a) (e':a), (mem e1 s) -> (mem e' s) ->
((rows (f e1)) = (rows (f e')))) /\
forall (e1:a) (e':a), (mem e1 s) -> (mem e' s) ->
((columns (f e1)) = (columns (f e'))).
Parameter s_rows:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> matrix t) -> Z.
Axiom s_rows_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), (constant_size s f) ->
((s_rows s f) = (rows (f (choose s)))).
Axiom s_rows_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), (constant_size s f) ->
(0%Z < (s_rows s f))%Z /\
((forall (e1:a), (mem e1 s) -> ((rows (f e1)) = (s_rows s f))) /\
forall (e1:a) (e':a), (mem e1 s) -> (mem e' s) ->
((rows (f e1)) = (rows (f e')))).
Parameter s_columns:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> matrix t) -> Z.
Axiom s_columns_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), (constant_size s f) ->
((s_columns s f) = (columns (f (choose s)))).
Axiom s_columns_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), (constant_size s f) ->
(0%Z < (s_columns s f))%Z /\
((forall (e1:a), (mem e1 s) -> ((columns (f e1)) = (s_columns s f))) /\
forall (e1:a) (e':a), (mem e1 s) -> (mem e' s) ->
((columns (f e1)) = (columns (f e')))).
Axiom set_s_rows :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z), (constant_size s f) ->
((rows (f (choose s))) = r) -> ((s_rows s f) = r).
Axiom set_s_rows_elt :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (elt:a), (constant_size s f) ->
(mem elt s) -> ((s_rows s f) = (rows (f elt))).
Axiom set_s_columns :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z), (constant_size s f) ->
((columns (f (choose s))) = r) -> ((s_columns s f) = r).
Axiom set_s_columns_elt :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (elt:a), (constant_size s f) ->
(mem elt s) -> ((s_columns s f) = (columns (f elt))).
Axiom s_rows_eq :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (g:a -> matrix t),
(constant_size s f) -> ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((f e1) = (g e1))) ->
((s_rows s f) = (s_rows s g)).
Axiom set_constant_size_give :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
(constant_size s f) /\
((forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) /\
((forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) /\
(((s_rows s f) = r) /\ ((s_columns s f) = c)))).
Axiom s_columns_eq :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (g:a -> matrix t),
(constant_size s f) -> ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((f e1) = (g e1))) ->
((s_columns s f) = (s_columns s g)).
Axiom subset_constant_size :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (f:a -> matrix t), (constant_size s f) ->
~ (is_empty s') -> (subset s' s) ->
(constant_size s' f) /\
(((s_rows s' f) = (s_rows s f)) /\ ((s_columns s' f) = (s_columns s f))).
Axiom set_s_rows_rem :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), ((cardinal s) > 1%Z)%Z ->
(constant_size s f) ->
(constant_size (remove (choose s) s) f) /\
((s_rows (remove (choose s) s) f) = (rows (f (choose s)))).
Axiom set_s_columns_rem :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), ((cardinal s) > 1%Z)%Z ->
(constant_size s f) ->
(constant_size (remove (choose s) s) f) /\
((s_columns (remove (choose s) s) f) = (columns (f (choose s)))).
Axiom set_s_rows_add :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (x:a), ((cardinal s) > 0%Z)%Z ->
(constant_size s f) -> ((columns (f x)) = (s_columns s f)) ->
((rows (f x)) = (s_rows s f)) -> ((s_rows (add x s) f) = (s_rows s f)).
Axiom set_s_columns_add :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (x:a), ((cardinal s) > 0%Z)%Z ->
(constant_size s f) -> ((columns (f x)) = (s_columns s f)) ->
((rows (f x)) = (s_rows s f)) ->
((s_columns (add x s) f) = (s_columns s f)).
Axiom set_s_rows_columns_add :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (x:a), ((cardinal s) > 0%Z)%Z ->
(constant_size s f) -> ((columns (f x)) = (s_columns s f)) ->
((rows (f x)) = (s_rows s f)) ->
((s_columns (add x s) f) = (s_columns s f)) /\
((s_rows (add x s) f) = (s_rows s f)).
Parameter mat_sum:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> matrix t) -> matrix t.
Axiom mat_sum_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), (constant_size s f) ->
((cardinal s) > 0%Z)%Z ->
(((cardinal s) = 1%Z) -> ((mat_sum s f) = (f (element s)))) /\
(~ ((cardinal s) = 1%Z) ->
((mat_sum s f) =
(add_mat (f (choose s)) (mat_sum (remove (choose s) s) f)))).
Axiom mat_sum_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), (constant_size s f) ->
((cardinal s) > 0%Z)%Z ->
((rows (mat_sum s f)) = (s_rows s f)) /\
(((columns (mat_sum s f)) = (s_columns s f)) /\
((forall (e1:a), (mem e1 s) -> ((rows (f e1)) = (s_rows s f))) /\
forall (e1:a), (mem e1 s) -> ((columns (f e1)) = (s_columns s f)))).
Axiom columns_mat_sum :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:Z), ~ ((cardinal s) = 0%Z) ->
(constant_size s f) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = n)) ->
((columns (mat_sum s f)) = n).
Axiom rows_mat_sum :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:Z), ~ ((cardinal s) = 0%Z) ->
(constant_size s f) ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = n)) ->
((rows (mat_sum s f)) = n).
Axiom mat_sum_cardone :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), ((cardinal s) = 1%Z) ->
((mat_sum s f) = (f (element s))).
Axiom mat_sum_to_sum_pre :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (i:Z) (j:Z), (constant_size s f) ->
((cardinal s) > 0%Z)%Z -> ((0%Z <= i)%Z /\ (i < (s_rows s f))%Z) ->
((0%Z <= j)%Z /\ (j < (s_columns s f))%Z) ->
((get (mat_sum s f) i j) = (sum s (fun (e1:a) => (get (f e1) i j)))).
Axiom mat_sum_to_sum :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), (constant_size s f) ->
((cardinal s) > 0%Z)%Z ->
((mat_sum s f) =
(make_f (s_rows s f) (s_columns s f)
(fun (i:Z) (j:Z) => (sum s (fun (e1:a) => (get (f e1) i j)))))).
Axiom mat_sum_value :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), (constant_size s f) ->
((cardinal s) > 0%Z)%Z ->
((mat_sum s f) =
(make_f (s_rows s f) (s_columns s f)
(fun (i:Z) (j:Z) => (sum s (fun (e1:a) => (get (f e1) i j)))))).
Axiom mat_sum_add :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (x:a), ((cardinal s) > 0%Z)%Z ->
(constant_size s f) -> ((rows (f x)) = (s_rows s f)) ->
((columns (f x)) = (s_columns s f)) -> ~ (mem x s) ->
((mat_sum (add x s) f) = (add_mat (f x) (mat_sum s f))).
Axiom mat_sum_plus_one :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), ((cardinal s) > 1%Z)%Z ->
(constant_size s f) ->
((mat_sum s f) =
(add_mat (f (choose s)) (mat_sum (remove (choose s) s) f))).
Axiom mat_sum_comp_pre :
forall {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> matrix t) (g:b -> matrix t) (i:Z) (j:Z),
(constant_size s f) -> (constant_size s g) ->
((0%Z <= i)%Z /\ (i < (s_rows s f))%Z) ->
((0%Z <= j)%Z /\ (j < (s_columns s f))%Z) ->
((s_rows s f) = (s_rows s g)) -> ((s_columns s f) = (s_columns s g)) ->
((cardinal s) > 0%Z)%Z ->
((get (mat_sum s (fun (k:b) => (add_mat (f k) (g k)))) i j) =
(get (add_mat (mat_sum s f) (mat_sum s g)) i j)).
Axiom mat_sum_comp :
forall {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> matrix t) (g:b -> matrix t),
(constant_size s f) -> (constant_size s g) ->
((s_rows s f) = (s_rows s g)) -> ((s_columns s f) = (s_columns s g)) ->
((cardinal s) > 0%Z)%Z ->
((mat_sum s (fun (k:b) => (add_mat (f k) (g k)))) =
(add_mat (mat_sum s f) (mat_sum s g))).
Axiom mat_sum_comp_rec :
forall {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> matrix t) (g:b -> matrix t),
(constant_size s f) -> (constant_size s g) ->
((s_rows s f) = (s_rows s g)) -> ((s_columns s f) = (s_columns s g)) ->
((cardinal s) > 0%Z)%Z ->
((add_mat (mat_sum s f) (mat_sum s g)) =
(mat_sum s (fun (k:b) => (add_mat (f k) (g k))))).
Axiom mat_sum_to_sum_fun :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s:set a) (s':set b) (f:a -> b -> matrix t) (r:Z) (c:Z) (i:Z) (j:Z),
((cardinal s) > 0%Z)%Z -> ((cardinal s') > 0%Z)%Z ->
(forall (e1:a), forall (e11:b), (mem e1 s) -> (mem e11 s') ->
((rows ((f e1) e11)) = r)) ->
(forall (e1:a), forall (e11:b), (mem e1 s) -> (mem e11 s') ->
((columns ((f e1) e11)) = c)) ->
((0%Z <= i)%Z /\ (i < r)%Z) -> ((0%Z <= j)%Z /\ (j < c)%Z) ->
((sum s (fun (e1:a) => (get (mat_sum s' (f e1)) i j))) =
(sum s (fun (e1:a) => (sum s' (fun (e11:b) => (get ((f e1) e11) i j)))))).
Axiom mat_sum_to_sum_double_pre :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s:set a) (s':set b) (f:a -> b -> matrix t) (r:Z) (c:Z) (i:Z) (j:Z),
(forall (e1:a) (e':b), (mem e1 s) -> (mem e' s') ->
((rows ((f e1) e')) = r)) ->
(forall (e1:a) (e':b), (mem e1 s) -> (mem e' s') ->
((columns ((f e1) e')) = c)) ->
((0%Z <= i)%Z /\ (i < r)%Z) -> ((0%Z <= j)%Z /\ (j < c)%Z) ->
((cardinal s) > 0%Z)%Z -> ((cardinal s') > 0%Z)%Z ->
((get (mat_sum s (fun (e1:a) => (mat_sum s' (f e1)))) i j) =
(sum s (fun (e1:a) => (sum s' (fun (e':b) => (get ((f e1) e') i j)))))).
Axiom mat_mult_sum_out_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:matrix t), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = (rows n))) ->
(exists r:Z, forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
((mat_mult (mat_sum s f) n) =
(mat_sum s (fun (e1:a) => (mat_mult (f e1) n)))).
Parameter mat_sum_dim:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> matrix t) -> Z ->
Z -> matrix t.
Axiom mat_sum_dim_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), (0%Z < r)%Z ->
(0%Z < c)%Z -> (forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
(((cardinal s) = 0%Z) -> ((mat_sum_dim s f r c) = (make r c tzero))) /\
(~ ((cardinal s) = 0%Z) -> ((mat_sum_dim s f r c) = (mat_sum s f))).
Axiom mat_sum_dim_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), (0%Z < r)%Z ->
(0%Z < c)%Z -> (forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
(((cardinal s) > 0%Z)%Z -> ((mat_sum_dim s f r c) = (mat_sum s f))) /\
((((cardinal s) = 0%Z) -> ((mat_sum_dim s f r c) = (make r c tzero))) /\
(((rows (mat_sum_dim s f r c)) = r) /\
((columns (mat_sum_dim s f r c)) = c))).
Axiom mat_sum_dim_to_mat_sum :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), ((cardinal s) > 0%Z)%Z ->
(0%Z < r)%Z -> (0%Z < c)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((mat_sum_dim s f r c) = (mat_sum s f)).
Axiom mat_sum_dim_to_make_zero :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), ((cardinal s) = 0%Z) ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) -> (0%Z < r)%Z ->
(0%Z < c)%Z -> ((mat_sum_dim s f r c) = (make r c tzero)).
Axiom mat_sum_dim_add :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (x:a) (r:Z) (c:Z),
((cardinal s) >= 0%Z)%Z -> ~ (mem x s) ->
(forall (e1:a), (mem e1 (add x s)) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 (add x s)) -> ((columns (f e1)) = c)) ->
(0%Z < r)%Z -> (0%Z < c)%Z ->
((mat_sum_dim (add x s) f r c) = (add_mat (f x) (mat_sum_dim s f r c))).
Axiom mat_sum_scalar :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (a1:t), (constant_size s f) ->
((cardinal s) > 0%Z)%Z ->
((mat_sum s (fun (k:a) => (infix_asdtdt a1 (f k)))) =
(infix_asdtdt a1 (mat_sum s f))).
Axiom mat_sum_scalar_rev :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (a1:t), (constant_size s f) ->
((cardinal s) > 0%Z)%Z ->
((infix_asdtdt a1 (mat_sum s f)) =
(mat_sum s (fun (k:a) => (infix_asdtdt a1 (f k))))).
Axiom mat_sum_const :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (x:matrix t), ((cardinal s) > 0%Z)%Z ->
((mat_sum s (fun (us:a) => x)) = (infix_asdtdt (i_to_t (cardinal s)) x)).
Axiom mat_sum_quot :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (x:matrix t), ((cardinal s) > 0%Z)%Z ->
(x =
(infix_asdtdt (infix_sldt tone (i_to_t (cardinal s)))
(mat_sum s (fun (us:a) => x)))).
Axiom mat_sum_scalar_right :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (m:matrix t) (i:Z) (j:Z),
(constant_size s f) -> ((cardinal s) > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (s_rows s f))%Z) ->
((0%Z <= j)%Z /\ (j < (s_columns s f))%Z) ->
((infix_asdtdt (get (mat_sum s f) i j) m) =
(mat_sum s (fun (k:a) => (infix_asdtdt (get (f k) i j) m)))).
Axiom mat_sum_eq :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (g:a -> matrix t),
((cardinal s) > 0%Z)%Z -> (constant_size s f) ->
(forall (a1:a), (mem a1 s) -> ((f a1) = (g a1))) ->
((mat_sum s f) = (mat_sum s g)).
Axiom mat_sum_eq_gen :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (f:a -> matrix t) (g:a -> matrix t),
((cardinal s) > 0%Z)%Z -> (s = s') -> (constant_size s f) ->
(forall (a1:a), (mem a1 s) -> ((f a1) = (g a1))) ->
((mat_sum s f) = (mat_sum s' g)).
Axiom mat_sum_eq_gen_int :
forall (i1:Z) (i2:Z) (o1:Z) (o2:Z) (f:Z -> matrix t) (g:Z -> matrix t),
(i1 < o1)%Z -> (i1 = o1) -> (i2 = o2) ->
(constant_size (to_fset i1 o1) f) ->
(forall (a:Z), (mem a (to_fset i1 o1)) -> ((f a) = (g a))) ->
((mat_sum (to_fset i1 o1) f) = (mat_sum (to_fset i2 o2) g)).
Axiom mat_sum_comp_eq :
forall {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> matrix t) (g:b -> matrix t) (h:b -> matrix t),
(constant_size s f) -> (constant_size s g) -> (constant_size s h) ->
(((s_rows s f) = (s_rows s g)) /\ ((s_rows s g) = (s_rows s h))) ->
(((s_columns s f) = (s_columns s g)) /\
((s_columns s g) = (s_columns s h))) ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:b), forall (i:Z) (j:Z), (mem e1 s) ->
((0%Z <= i)%Z /\ (i < (s_rows s f))%Z) ->
((0%Z <= j)%Z /\ (j < (s_columns s f))%Z) ->
((infix_pldt (get (f e1) i j) (get (g e1) i j)) = (get (h e1) i j))) ->
((add_mat (mat_sum s f) (mat_sum s g)) = (mat_sum s h)).
Axiom mat_sum_dim_eq :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (g:a -> matrix t) (r:Z) (c:Z),
(0%Z < r)%Z -> (0%Z < c)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
(forall (e1:a), (mem e1 s) -> ((f e1) = (g e1))) ->
((mat_sum_dim s f r c) = (mat_sum_dim s g r c)).
Axiom constant_size_map :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:b -> matrix t) (s:set a) (t1:a -> b),
(constant_size s (fun (a1:a) => (f (t1 a1)))) -> constant_size (map t1 s) f.
Axiom map_mat_sum :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:b -> matrix t) (s:set a) (t1:a -> b), ((cardinal s) > 0%Z)%Z ->
(constant_size s (fun (a1:a) => (f (t1 a1)))) -> (p_injective t1 s) ->
((mat_sum (map t1 s) f) = (mat_sum s (fun (a1:a) => (f (t1 a1))))).
Axiom map_mat_sum_rec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:b -> matrix t) (s:set a) (t1:a -> b), ((cardinal s) > 0%Z)%Z ->
(constant_size s (fun (a1:a) => (f (t1 a1)))) -> (p_injective t1 s) ->
((mat_sum s (fun (a1:a) => (f (t1 a1)))) = (mat_sum (map t1 s) f)).
Axiom mat_sum_id :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a), ((cardinal s) > 0%Z)%Z ->
(constant_size s f) ->
(constant_size (map f s) (fun (y0:matrix t) => (p_id y0))) ->
(p_injective f s) ->
((mat_sum (map f s) (fun (y0:matrix t) => (p_id y0))) = (mat_sum s f)).
Parameter nonn_mat_subset:
forall {a:Type} {a_WT:WhyType a}, (a -> matrix t) -> (set a) -> set a.
Parameter result8:
forall {a:Type} {a_WT:WhyType a}, (a -> matrix t) -> (set a) -> a -> bool.
Axiom result_def8 :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a) (e1:a),
(((result8 f s) e1) = true) <->
~ (equal (f e1) (make (s_rows s f) (s_columns s f) tzero)).
Axiom nonn_mat_subset_def :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a), (constant_size s f) ->
((nonn_mat_subset f s) = (filter (result8 f s) s)).
Axiom nonn_mat_subset_spec :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a), (constant_size s f) ->
(subset (nonn_mat_subset f s) s) /\
((forall (e1:a), (mem e1 (nonn_mat_subset f s)) -> mem e1 s) /\
((constant_size (nonn_mat_subset f s) f) /\
((~ ((nonn_mat_subset f s) = (empty : set a)) ->
((s_rows (nonn_mat_subset f s) f) = (s_rows s f))) /\
(~ ((nonn_mat_subset f s) = (empty : set a)) ->
((s_columns (nonn_mat_subset f s) f) = (s_columns s f)))))).
Axiom mat_subset_elt :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a), (constant_size s f) -> forall (e1:a),
(mem e1 (nonn_mat_subset f s)) -> mem e1 s.
Axiom mat_subset_nonn_elt :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a), (constant_size s f) -> forall (e1:a),
(mem e1 (nonn_mat_subset f s)) ->
~ ((f e1) = (make (s_rows s f) (s_columns s f) tzero)).
Axiom nonn_mat_sum_cardzero :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a) (r:Z) (c:Z), ((cardinal s) = 0%Z) ->
(r > 0%Z)%Z -> (c > 0%Z)%Z ->
((mat_sum_dim s f r c) = (mat_sum_dim (nonn_mat_subset f s) f r c)).
Axiom nonn_mat_sum_cardone :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a) (r:Z) (c:Z), ((cardinal s) = 1%Z) ->
(r > 0%Z)%Z -> (c > 0%Z)%Z -> ((rows (f (choose s))) = r) ->
((columns (f (choose s))) = c) ->
((mat_sum_dim s f r c) = (mat_sum_dim (nonn_mat_subset f s) f r c)).
Axiom mat_sum_null_but_maybe_one_elt :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a) (e1:a), ((cardinal s) > 1%Z)%Z ->
(constant_size s f) -> (mem e1 s) ->
(forall (e':a), (mem e' s) -> ~ (e1 = e') -> null_mat (f e')) ->
((mat_sum s f) = (f e1)).
Axiom nonn_mat_sum_plus_one :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a) (r:Z) (c:Z), ((cardinal s) > 1%Z)%Z ->
(r > 0%Z)%Z -> (c > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((mat_sum_dim (remove (choose s) s) f r c) =
(mat_sum_dim (nonn_mat_subset f (remove (choose s) s)) f r c)) ->
((mat_sum_dim s f r c) = (mat_sum_dim (nonn_mat_subset f s) f r c)).
Axiom nonn_mat_sum :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a) (r:Z) (c:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> (forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((mat_sum_dim s f r c) = (mat_sum_dim (nonn_mat_subset f s) f r c)).
Axiom mat_sum_map_map :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}
{c:Type} {c_WT:WhyType c},
forall (s1:set a) (s2:set b) (t1:a -> c) (t2:b -> c) (f:c -> matrix t),
((cardinal s1) > 0%Z)%Z -> (p_injective t1 s1) ->
(constant_size s1 (fun (a1:a) => (f (t1 a1)))) ->
((cardinal s2) > 0%Z)%Z -> (p_injective t2 s2) ->
(constant_size s2 (fun (a1:b) => (f (t2 a1)))) ->
((map t1 s1) = (map t2 s2)) ->
((mat_sum (map t1 s1) f) = (mat_sum (map t2 s2) f)).
Axiom mat_sum_disjoint_transitivity :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s1:set a) (s2:set a) (f:a -> matrix t),
(constant_size s f) -> ((inter s1 s2) = (empty : set a)) ->
((union s1 s2) = s) -> ((cardinal s1) > 0%Z)%Z ->
((cardinal s2) > 0%Z)%Z ->
((add_mat (mat_sum s1 f) (mat_sum s2 f)) = (mat_sum s f)).
Axiom mat_sum_null :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a), ((cardinal s) > 1%Z)%Z ->
(constant_size s f) ->
(forall (e1:a), (mem e1 s) -> forall (i:Z) (j:Z),
(valid_index (f e1) i j) -> ((get (f e1) i j) = tzero)) ->
forall (i:Z) (j:Z), (valid_index (mat_sum s f) i j) ->
((get (mat_sum s f) i j) = tzero).
Axiom mat_sum_null_b :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a) (r:Z) (c:Z), ((cardinal s) > 1%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
(forall (e1:a), (mem e1 s) -> forall (i:Z) (j:Z),
(valid_index (f e1) i j) -> ((get (f e1) i j) = tzero)) ->
forall (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < r)%Z) ->
((0%Z <= j)%Z /\ (j < c)%Z) -> ((get (mat_sum s f) i j) = tzero).
Axiom map_add_mat_sum_t :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s:set a) (s':set b) (f:b -> matrix t) (injz:a -> b) (injo:a -> b),
(constant_size s' f) -> ((cardinal s) > 0%Z)%Z ->
((inter (map injz s) (map injo s)) = (empty : set b)) ->
((union (map injz s) (map injo s)) = s') -> (p_injective injo s) ->
(p_injective injz s) ->
((mat_sum s (fun (e1:a) => (add_mat (f (injz e1)) (f (injo e1))))) =
(mat_sum s' f)).
Axiom map_add_mat_sum :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s1:set a) (s2:set a) (s':set a) (f:a -> matrix t)
(g:a -> matrix t) (h:a -> matrix t),
(constant_size s' h) -> (constant_size s f) -> (constant_size s g) ->
(((s_rows s' h) = (s_rows s f)) /\ ((s_rows s f) = (s_rows s g))) ->
(((s_columns s' h) = (s_columns s f)) /\
((s_columns s f) = (s_columns s g))) ->
((cardinal s) > 0%Z)%Z -> (p_injective f s) -> (p_injective g s) ->
(p_injective h s') -> ((map f s) = (map h s1)) ->
((map g s) = (map h s2)) -> ((inter s1 s2) = (empty : set a)) ->
((union s1 s2) = s') ->
((mat_sum s (fun (e1:a) => (add_mat (f e1) (g e1)))) =
(mat_sum s' (fun (e1:a) => (h e1)))).
Parameter inv_func:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a -> b) ->
(set a) -> (set b) -> b -> a.
Axiom inv_func_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b) (e':b), (p_bijective f s s') ->
(mem e' s') ->
((inv_func f s s' e') =
(element (filter (fun (e1:a) => (indic_bool (f e1) e')) s))).
Axiom inv_func_spec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b) (e':b), (p_bijective f s s') ->
(mem e' s') ->
(mem (inv_func f s s' e') s) /\ ((f (inv_func f s s' e')) = e').
Axiom inv_rec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b) (e1:a), (p_bijective f s s') ->
(mem e1 s) -> ((inv_func f s s' (f e1)) = e1).
Parameter inv_:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a -> b) ->
(set a) -> (set b) -> b -> a.
Axiom inv__def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b) (e1:b), (p_bijective f s s') ->
(mem e1 s') -> ((inv_ f s s' e1) = (inv_func f s s' e1)).
Axiom inv__spec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b) (e1:b), (p_bijective f s s') ->
(mem e1 s') -> (mem (inv_ f s s' e1) s) /\ ((f (inv_ f s s' e1)) = e1).
Axiom inv_bijective :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b), (p_bijective f s s') ->
p_bijective
((((fun (y0:a -> b) (y1:set a) (y2:set b) (y3:b) => (inv_ y0 y1 y2 y3)) f)
s)
s')
s' s.
Axiom set_bijective_inv :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (g:b -> a) (s:set a) (b1:b), (mem b1 (map f s)) ->
(forall (e1:a) (e':a), (mem e1 s) -> (mem e' s) -> ~ (e1 = e') ->
~ ((f e1) = (f e'))) ->
(forall (e':b), (mem e' (map f s)) -> (mem (g e') s) /\ ((f (g e')) = e')) ->
(p_bijective f s (map f s)) /\ ((inv_func f s (map f s) b1) = (g b1)).
Axiom set_bij_inv :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (g:b -> a) (s:set a),
(forall (e1:a) (e':a), (mem e1 s) -> (mem e' s) -> ~ (e1 = e') ->
~ ((f e1) = (f e'))) ->
(forall (e':b), (mem e' (map f s)) -> (mem (g e') s) /\ ((f (g e')) = e')) ->
(p_bijective f s (map f s)) /\
((p_bijective g (map f s) s) /\
forall (b1:b), (mem b1 (map f s)) ->
((inv_func f s (map f s) b1) = (g b1))).
Parameter inv_f:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a -> b) ->
(set a) -> (set b) -> b -> a.
Axiom inv_f_spec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (s:set a) (s':set b), (p_bijective f s s') ->
(forall (e1:b), (mem e1 s') -> mem ((inv_f f s s') e1) s) /\
((forall (e1:b), (mem e1 s') -> ((f ((inv_f f s s') e1)) = e1)) /\
(p_bijective (inv_f f s s') s' s)).
Axiom bitvec : Type.
Parameter bitvec_WhyType : WhyType bitvec.
Existing Instance bitvec_WhyType.
Parameter value: bitvec -> Z -> Z.
Parameter length: bitvec -> Z.
Axiom bitvec'invariant :
forall (self:bitvec),
(0%Z <= (length self))%Z /\
((forall (i:Z), ((0%Z <= i)%Z /\ (i < (length self))%Z) ->
(0%Z <= ((value self) i))%Z /\ (((value self) i) < 2%Z)%Z) /\
forall (i:Z), ~ ((0%Z <= i)%Z /\ (i < (length self))%Z) ->
(((value self) i) = 0%Z)).
Parameter bvlength: (Z -> Z) -> Z -> Prop.
Axiom bvlength_def :
forall (f:Z -> Z) (i:Z),
(bvlength f i) <->
forall (k:Z), ((0%Z <= k)%Z /\ (k < i)%Z) ->
(0%Z <= (f k))%Z /\ ((f k) < 2%Z)%Z.
Axiom binary_mult :
forall (a:Z) (b:Z),
((int.EuclideanDivision.mod1 (a * b)%Z 2%Z) =
((int.EuclideanDivision.mod1 a 2%Z) *
(int.EuclideanDivision.mod1 b 2%Z))%Z).
Parameter getbv: bitvec -> Z -> Z.
Axiom getbv_def : forall (a:bitvec), ((getbv a) = (value a)).
Axiom getbv_spec :
forall (a:bitvec),
(binary (getbv a)) /\ forall (i:Z), (((getbv a) i) = ((value a) i)).
Parameter to_bool: Z -> bool.
Axiom to_bool_def :
forall (i:Z), ((0%Z <= i)%Z /\ (i < 2%Z)%Z) ->
(~ (i = 0%Z) -> ((to_bool i) = true)) /\
((i = 0%Z) -> ((to_bool i) = false)).
Axiom getbv_bound :
forall (bv:bitvec) (i:Z),
(0%Z <= ((getbv bv) i))%Z /\ (((getbv bv) i) < 2%Z)%Z.
Axiom getbv_eq :
forall (bvx:bitvec) (bvy:bitvec) (i:Z), (bvx = bvy) ->
(((getbv bvx) i) = ((getbv bvy) i)).
Axiom getbv_eq_gen :
forall (bvx:bitvec) (bvy:bitvec) (i:Z) (j:Z), (bvx = bvy) -> (i = j) ->
(((getbv bvx) i) = ((getbv bvy) j)).
Parameter setbv: (Z -> Z) -> Z -> Z -> Z -> Z.
Axiom setbv_def :
forall (bv:Z -> Z) (i:Z) (j:Z),
let result9 := setbv bv i j in
forall (k:Z),
((k = i) -> ((result9 k) = j)) /\ (~ (k = i) -> ((result9 k) = (bv k))).
Axiom setbv_spec :
forall (bv:Z -> Z) (i:Z) (j:Z),
(forall (k:Z), ~ (k = i) -> (((setbv bv i j) k) = (bv k))) /\
(((setbv bv i j) i) = j).
Parameter setbv_int: (Z -> Z) -> (Z -> Z) -> Z -> Z -> Z -> Z.
Axiom setbv_int_def :
forall (bv1:Z -> Z) (bv2:Z -> Z) (i:Z) (j:Z),
let result9 := setbv_int bv1 bv2 i j in
forall (k:Z),
(((i < k)%Z /\ (k <= j)%Z) -> ((result9 k) = (bv2 (k - i)%Z))) /\
(~ ((i < k)%Z /\ (k <= j)%Z) -> ((result9 k) = (bv1 k))).
Axiom setbv_int_spec :
forall (bv1:Z -> Z) (bv2:Z -> Z) (i:Z) (j:Z),
(forall (k:Z), ((i < k)%Z /\ (k <= j)%Z) ->
(((setbv_int bv1 bv2 i j) k) = (bv2 (k - i)%Z))) /\
((forall (k:Z), (k <= i)%Z -> (((setbv_int bv1 bv2 i j) k) = (bv1 k))) /\
forall (k:Z), (j < k)%Z -> (((setbv_int bv1 bv2 i j) k) = (bv1 k))).
Axiom set_bvlength :
forall (bv:bitvec) (i:Z),
(forall (k:Z), ((1%Z <= k)%Z /\ (k < i)%Z) ->
(0%Z <= ((getbv bv) k))%Z /\ (((getbv bv) k) < 2%Z)%Z) ->
bvlength (getbv bv) i.
Axiom null_product_bitvec :
forall (x:bitvec) (n:Z), (n = (length x)) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) -> (((getbv x) i) = 1%Z)) ->
((ind_iproduct (getbv x) 0%Z n) = 1%Z).
Axiom non_null_product_bitvec :
forall (x:bitvec) (n:Z), (n = (length x)) ->
~ (forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) -> (((getbv x) i) = 1%Z)) ->
((ind_iproduct (getbv x) 0%Z n) = 0%Z).
Axiom null_product_bitvec_inv :
forall (x:bitvec) (n:Z), (n = (length x)) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) -> (((getbv x) i) = 0%Z)) ->
((ind_iproduct (fun (i:Z) => (1%Z - ((getbv x) i))%Z) 0%Z n) = 1%Z).
Axiom non_null_product_bitvec_inv :
forall (x:bitvec) (n:Z), (n = (length x)) ->
~ (forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) -> (((getbv x) i) = 0%Z)) ->
((ind_iproduct (fun (i:Z) => (1%Z - ((getbv x) i))%Z) 0%Z n) = 0%Z).
Axiom null_product_bitvec_rev :
forall (x:bitvec) (n:Z), (n = (length x)) ->
((ind_iproduct (getbv x) 0%Z n) = 1%Z) -> forall (i:Z),
((0%Z <= i)%Z /\ (i < n)%Z) -> (((getbv x) i) = 1%Z).
Axiom non_null_product_bitvec_rev :
forall (x:bitvec) (n:Z), (n = (length x)) ->
((ind_iproduct (getbv x) 0%Z n) = 0%Z) ->
~ (forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) -> (((getbv x) i) = 1%Z)).
Axiom null_product_bitvec_inv_rev :
forall (x:bitvec) (n:Z), (n = (length x)) ->
((ind_iproduct (fun (i:Z) => (1%Z - ((getbv x) i))%Z) 0%Z n) = 1%Z) ->
forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) -> (((getbv x) i) = 0%Z).
Axiom non_null_product_bitvec_inv_rev :
forall (x:bitvec) (n:Z), (n = (length x)) ->
((ind_iproduct (fun (i:Z) => (1%Z - ((getbv x) i))%Z) 0%Z n) = 0%Z) ->
~ (forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) -> (((getbv x) i) = 0%Z)).
Axiom set_flength :
forall (f:Z -> Z) (i:Z),
(forall (k:Z), ((0%Z <= k)%Z /\ (k < i)%Z) ->
(0%Z <= (f k))%Z /\ ((f k) < 2%Z)%Z) ->
bvlength f i.
Axiom get_bvlength :
forall (f:Z -> Z) (i:Z), (bvlength f i) -> forall (k:Z),
((0%Z <= k)%Z /\ (k < i)%Z) -> (0%Z <= (f k))%Z /\ ((f k) < 2%Z)%Z.
Axiom set_bv_to :
forall (f:Z -> Z) (i:Z), (0%Z < i)%Z ->
(forall (j:Z), ((0%Z <= j)%Z /\ (j < i)%Z) ->
(0%Z <= (f j))%Z /\ ((f j) <= 1%Z)%Z) ->
bvlength f i.
Axiom set_in_range_val :
forall (bv:bitvec) (i:Z), ((0%Z <= i)%Z /\ (i < (length bv))%Z) ->
(0%Z <= ((getbv bv) i))%Z /\ (((getbv bv) i) < 2%Z)%Z.
Axiom bvlengthm :
forall (bv:bitvec) (i:Z), ((0%Z <= i)%Z /\ (i < (length bv))%Z) ->
bvlength (getbv bv) i.
Parameter in_range: bitvec -> Z -> Prop.
Axiom in_range_def :
forall (bv:bitvec) (r:Z),
(in_range bv r) <-> ((0%Z <= r)%Z /\ (r < (length bv))%Z).
Axiom binary_bv :
forall (bv:bitvec) (i:Z), (in_range bv i) ->
(0%Z <= ((getbv bv) i))%Z /\ (((getbv bv) i) <= 1%Z)%Z.
Axiom equal_bv :
forall (m:bitvec) (n:bitvec),
(m = n) <->
(((length m) = (length n)) /\
forall (i:Z), (in_range m i) -> (((getbv m) i) = ((getbv n) i))).
Axiom set_equal_bv :
forall (bv:bitvec) (bv':bitvec), ((length bv) = (length bv')) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (length bv))%Z) ->
(((getbv bv) i) = ((getbv bv') i))) ->
(bv = bv').
Axiom get_equal_bv :
forall (bv:bitvec) (bv':bitvec), (bv = bv') ->
((length bv) = (length bv')) /\
forall (i:Z), ((0%Z <= i)%Z /\ (i < (length bv))%Z) ->
(((getbv bv) i) = ((getbv bv') i)).
Parameter make_bv: (Z -> Z) -> Z -> bitvec.
Axiom make_bv_spec :
forall (f:Z -> Z) (s:Z),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < s)%Z) ->
(0%Z <= (f i))%Z /\ ((f i) < 2%Z)%Z) ->
(s >= 0%Z)%Z ->
((length (make_bv f s)) = s) /\
((forall (i:Z), ((0%Z <= i)%Z /\ (i < s)%Z) ->
(((getbv (make_bv f s)) i) = (f i))) /\
forall (i:Z), ~ ((0%Z <= i)%Z /\ (i < s)%Z) ->
(((getbv (make_bv f s)) i) = 0%Z)).
Parameter make_bv_m: (Z -> Z) -> Z -> bitvec.
Axiom make_bv_m_def :
forall (f:Z -> Z) (s:Z), (s >= 0%Z)%Z ->
((make_bv_m f s) =
(make_bv (fun (k:Z) => (int.EuclideanDivision.mod1 (f k) 2%Z)) s)).
Axiom make_bv_m_spec :
forall (f:Z -> Z) (s:Z), (s >= 0%Z)%Z ->
((length (make_bv_m f s)) = s) /\
((forall (i:Z), bvlength (getbv (make_bv_m f s)) i) /\
((forall (k:Z), ((0%Z <= k)%Z /\ (k < s)%Z) ->
(((getbv (make_bv_m f s)) k) = (int.EuclideanDivision.mod1 (f k) 2%Z))) /\
forall (k:Z), ~ ((0%Z <= k)%Z /\ (k < s)%Z) ->
(((getbv (make_bv_m f s)) k) = 0%Z))).
Parameter bitvec_null: bitvec.
Axiom bitvec_null_def : (bitvec_null = (make_bv (fun (i:Z) => 0%Z) 0%Z)).
Axiom assert_make_bv_no_bound :
forall (f:Z -> Z) (s:Z) (i:Z),
(forall (i1:Z), ((0%Z <= i1)%Z /\ (i1 < s)%Z) ->
(0%Z <= (f i1))%Z /\ ((f i1) < 2%Z)%Z) ->
((1%Z <= i)%Z /\ (i <= s)%Z) -> (((getbv (make_bv f 0%Z)) i) = 0%Z).
Axiom make_bv_length :
forall (f:Z -> Z) (s:Z),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < s)%Z) ->
(0%Z <= (f i))%Z /\ ((f i) < 2%Z)%Z) ->
(s >= 0%Z)%Z -> ((length (make_bv f s)) = s).
Axiom assert_make_bv :
forall (f:Z -> Z) (s:Z) (i:Z),
(forall (i1:Z), ((0%Z <= i1)%Z /\ (i1 < s)%Z) ->
(0%Z <= (f i1))%Z /\ ((f i1) < 2%Z)%Z) ->
(0%Z <= s)%Z ->
(((0%Z <= i)%Z /\ (i < s)%Z) -> (((getbv (make_bv f s)) i) = (f i))) /\
(~ ((0%Z <= i)%Z /\ (i < s)%Z) -> (((getbv (make_bv f s)) i) = 0%Z)).
Axiom assert_make_m :
forall (f:Z -> Z) (s:Z) (i:Z), (s >= 0%Z)%Z ->
(((0%Z <= i)%Z /\ (i < s)%Z) ->
(((getbv (make_bv_m f s)) i) = (int.EuclideanDivision.mod1 (f i) 2%Z))) /\
(~ ((0%Z <= i)%Z /\ (i < s)%Z) -> (((getbv (make_bv_m f s)) i) = 0%Z)).
Axiom make_bv_eq :
forall (f:Z -> Z) (f':Z -> Z) (n:Z) (n':Z), (n >= 0%Z)%Z -> (n = n') ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) -> ((f i) = (f' i))) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) ->
(0%Z <= (f i))%Z /\ ((f i) < 2%Z)%Z) ->
((make_bv f n) = (make_bv f' n')).
Axiom assert_make_bv_b :
forall (f:Z -> Z) (s:Z) (i:Z),
(forall (i1:Z), ((0%Z <= i1)%Z /\ (i1 < s)%Z) ->
(0%Z <= (f i1))%Z /\ ((f i1) < 2%Z)%Z) ->
((0%Z <= i)%Z /\ (i < s)%Z) -> (((getbv (make_bv f s)) i) = (f i)).
Axiom assert_make_m_b :
forall (f:Z -> Z) (s:Z) (i:Z), ((0%Z <= i)%Z /\ (i < s)%Z) ->
(s >= 0%Z)%Z ->
(((getbv (make_bv_m f s)) i) = (int.EuclideanDivision.mod1 (f i) 2%Z)).
Axiom make_m_bv_length :
forall (f:Z -> Z) (s:Z) (i:Z), (s >= 0%Z)%Z ->
bvlength (getbv (make_bv_m f s)) i.
Axiom make_m_length :
forall (f:Z -> Z) (s:Z), (s >= 0%Z)%Z -> ((length (make_bv_m f s)) = s).
Axiom set_equal_bv_make :
forall (f:Z -> Z) (g:Z -> Z) (s:Z),
(forall (i:Z), (0%Z <= (f i))%Z /\ ((f i) < 2%Z)%Z) -> (s >= 0%Z)%Z ->
(forall (i:Z), ((f i) = (g i))) -> ((make_bv f s) = (make_bv g s)).
Axiom set_equal_bv_m_make :
forall (f:Z -> Z) (g:Z -> Z) (s:Z), (s >= 0%Z)%Z ->
(forall (i:Z),
((int.EuclideanDivision.mod1 (f i) 2%Z) =
(int.EuclideanDivision.mod1 (g i) 2%Z))) ->
((make_bv_m f s) = (make_bv_m g s)).
Axiom make_bv_itself :
forall (x:bitvec) (n:Z), ((length x) = n) ->
((make_bv (fun (i:Z) => ((getbv x) i)) n) = x).
Parameter head: bitvec -> Z.
Axiom head_def :
forall (bv:bitvec), ((length bv) >= 1%Z)%Z ->
((head bv) = ((getbv bv) 0%Z)).
Axiom head_spec :
forall (bv:bitvec), ((length bv) >= 1%Z)%Z ->
(0%Z <= (head bv))%Z /\ ((head bv) <= 1%Z)%Z.
Parameter makes_bv: (Z -> Z) -> Z -> bitvec.
Parameter result9: (Z -> Z) -> Z -> Z.
Axiom result_def9 :
forall (f:Z -> Z) (i:Z),
((let q1_ := f i in (0%Z <= q1_)%Z /\ (q1_ < 2%Z)%Z) ->
(((result9 f) i) = (f i))) /\
(~ (let q1_ := f i in (0%Z <= q1_)%Z /\ (q1_ < 2%Z)%Z) ->
(((result9 f) i) = 0%Z)).
Axiom makes_bv_def :
forall (f:Z -> Z) (s:Z), (s >= 0%Z)%Z ->
((makes_bv f s) = (make_bv (result9 f) s)).
Axiom makes_bv_spec :
forall (f:Z -> Z) (s:Z), (s >= 0%Z)%Z ->
((length (makes_bv f s)) = s) /\
((forall (i:Z), ((0%Z <= i)%Z /\ (i < s)%Z) ->
((0%Z <= (f i))%Z /\ ((f i) < 2%Z)%Z) ->
(((getbv (makes_bv f s)) i) = (f i))) /\
(((forall (i:Z), ((0%Z <= i)%Z /\ (i < s)%Z) ->
(0%Z <= (f i))%Z /\ ((f i) < 2%Z)%Z) ->
((makes_bv f s) = (make_bv f s))) /\
forall (i:Z), ~ ((0%Z <= i)%Z /\ (i < s)%Z) ->
(((getbv (makes_bv f s)) i) = 0%Z))).
Axiom assert_makes_bv_c :
forall (f:Z -> Z) (s:Z) (i:Z),
(forall (i1:Z), ((0%Z <= i1)%Z /\ (i1 < s)%Z) ->
(0%Z <= (f i1))%Z /\ ((f i1) < 2%Z)%Z) ->
(0%Z <= s)%Z ->
(((0%Z <= i)%Z /\ (i < s)%Z) -> (((getbv (makes_bv f s)) i) = (f i))) /\
(~ ((0%Z <= i)%Z /\ (i < s)%Z) -> (((getbv (makes_bv f s)) i) = 0%Z)).
Axiom assert_makes_bv_b :
forall (f:Z -> Z) (s:Z) (i:Z),
(forall (i1:Z), ((0%Z <= i1)%Z /\ (i1 < s)%Z) ->
(0%Z <= (f i1))%Z /\ ((f i1) < 2%Z)%Z) ->
(0%Z <= s)%Z -> ((0%Z <= i)%Z /\ (i < s)%Z) ->
(((getbv (makes_bv f s)) i) = (f i)).
Axiom assert_makes_bv :
forall (f:Z -> Z) (s:Z) (i:Z),
(forall (i1:Z), ((0%Z <= i1)%Z /\ (i1 < s)%Z) ->
(0%Z <= (f i1))%Z /\ ((f i1) < 2%Z)%Z) ->
(0%Z <= s)%Z ->
((((0%Z <= i)%Z /\ (i < s)%Z) /\ (0%Z <= (f i))%Z) ->
(((getbv (makes_bv f s)) i) = (f i))) /\
(~ (((0%Z <= i)%Z /\ (i < s)%Z) /\ (0%Z <= (f i))%Z) ->
(((getbv (makes_bv f s)) i) = 0%Z)).
Axiom makes_bv_length :
forall (f:Z -> Z) (s:Z), (s >= 0%Z)%Z -> ((length (makes_bv f s)) = s).
Parameter tail: bitvec -> bitvec.
Axiom tail_def :
forall (bv:bitvec), ((length bv) >= 1%Z)%Z ->
((tail bv) =
(make_bv (fun (i:Z) => ((getbv bv) (i + 1%Z)%Z)) ((length bv) - 1%Z)%Z)).
Axiom tail_spec :
forall (bv:bitvec), ((length bv) >= 1%Z)%Z ->
((length (tail bv)) = ((length bv) - 1%Z)%Z) /\
forall (i:Z), (in_range (tail bv) i) ->
(((getbv (tail bv)) i) = ((getbv bv) (i + 1%Z)%Z)).
Parameter concat_l: bitvec -> Z -> bitvec.
Parameter result10: bitvec -> Z -> Z -> Z.
Axiom result_def10 :
forall (bv:bitvec) (i:Z) (k:Z),
((k = 0%Z) -> (((result10 bv i) k) = i)) /\
(~ (k = 0%Z) -> (((result10 bv i) k) = ((getbv bv) (k - 1%Z)%Z))).
Axiom concat_l_def :
forall (bv:bitvec) (i:Z), ((0%Z <= i)%Z /\ (i <= 1%Z)%Z) ->
((concat_l bv i) = (make_bv (result10 bv i) ((length bv) + 1%Z)%Z)).
Axiom concat_l_spec :
forall (bv:bitvec) (i:Z), ((0%Z <= i)%Z /\ (i <= 1%Z)%Z) ->
((length (concat_l bv i)) = ((length bv) + 1%Z)%Z) /\
((((getbv (concat_l bv i)) 0%Z) = i) /\
forall (j:Z), (in_range bv j) ->
(((getbv (concat_l bv i)) (j + 1%Z)%Z) = ((getbv bv) j))).
Axiom concat_l_value :
forall (bv:bitvec) (i:Z) (k:Z), ((0%Z <= i)%Z /\ (i < 2%Z)%Z) ->
((k = 0%Z) -> (((getbv (concat_l bv i)) k) = i)) /\
(~ (k = 0%Z) ->
(((0%Z < k)%Z /\ (k <= ((length bv) + 1%Z)%Z)%Z) ->
(((getbv (concat_l bv i)) k) = ((getbv bv) (k - 1%Z)%Z))) /\
(~ ((0%Z < k)%Z /\ (k <= ((length bv) + 1%Z)%Z)%Z) ->
(((getbv (concat_l bv i)) k) = 0%Z))).
Axiom concat_l_value_b :
forall (bv:bitvec) (i:Z) (k:Z),
((0%Z <= k)%Z /\ (k < ((length bv) + 1%Z)%Z)%Z) ->
((0%Z <= i)%Z /\ (i < 2%Z)%Z) ->
((k = 0%Z) -> (((getbv (concat_l bv i)) k) = i)) /\
(~ (k = 0%Z) -> (((getbv (concat_l bv i)) k) = ((getbv bv) (k - 1%Z)%Z))).
Axiom concat_ht :
forall (bv:bitvec), ((length bv) >= 1%Z)%Z ->
(bv = (concat_l (tail bv) (head bv))).
Axiom concat_ht_union :
forall (bv:bitvec), ((length bv) >= 2%Z)%Z ->
~ (bv = (concat_l (tail bv) 0%Z)) -> (bv = (concat_l (tail bv) 1%Z)).
Parameter bv_to_int: bitvec -> Z.
Parameter result11: bitvec -> Z -> Z.
Axiom result_def11 :
forall (bv:bitvec) (k:Z),
((in_range bv k) ->
(((result11 bv) k) =
(((getbv bv) k) * (power 2%Z (((length bv) - 1%Z)%Z - k)%Z))%Z)) /\
(~ (in_range bv k) -> (((result11 bv) k) = 1%Z)).
Axiom bv_to_int_def :
forall (bv:bitvec),
((bv_to_int bv) = (ind_isum (result11 bv) 0%Z (length bv))).
Axiom bv_to_int_spec :
forall (bv:bitvec),
((bv_to_int bv) =
(ind_isum
(fun (k:Z) =>
(((getbv bv) k) * (power 2%Z (((length bv) - 1%Z)%Z - k)%Z))%Z)
0%Z (length bv))) /\
(0%Z <= (bv_to_int bv))%Z.
Axiom bv_to_int_eq :
forall (bv1:bitvec) (bv2:bitvec), (bv1 = bv2) ->
((bv_to_int bv1) = (bv_to_int bv2)).
Axiom bv_to_int_sum :
forall (bv:bitvec),
((bv_to_int bv) =
(ind_isum
(fun (k:Z) =>
(((getbv bv) k) * (power 2%Z (((length bv) - 1%Z)%Z - k)%Z))%Z)
0%Z (length bv))).
Axiom bv_to_int_sum_opp :
forall (bv:bitvec),
((-(bv_to_int bv))%Z =
(ind_isum
(fun (k:Z) =>
((-((getbv bv) k))%Z * (power 2%Z (((length bv) - 1%Z)%Z - k)%Z))%Z)
0%Z (length bv))).
Axiom bv_to_int_onebit :
forall (bv:bitvec), ((length bv) = 1%Z) ->
((bv_to_int bv) = ((getbv bv) 0%Z)).
Axiom ind_isum_bv_rev :
forall (bv:bitvec) (i:Z), ((0%Z <= i)%Z /\ (i <= (length bv))%Z) ->
((ind_isum
(fun (l:Z) =>
(((getbv bv) l) * (power 2%Z (((length bv) - 1%Z)%Z - l)%Z))%Z)
i (length bv))
=
(ind_isum
(fun (l:Z) =>
(((getbv bv) (((length bv) - 1%Z)%Z - l)%Z) * (power 2%Z l))%Z)
0%Z ((length bv) - i)%Z)).
Axiom ind_isum_bin_rev :
forall (f:Z -> Z) (n:Z) (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) -> (binary f) ->
((ind_isum (fun (l:Z) => ((f l) * (power 2%Z ((n - 1%Z)%Z - l)%Z))%Z) i n)
=
(ind_isum (fun (l:Z) => ((f ((n - 1%Z)%Z - l)%Z) * (power 2%Z l))%Z) 0%Z
(n - i)%Z)).
Axiom ind_isum_bin_rev_z :
forall (f:Z -> Z) (n:Z), (0%Z <= n)%Z -> (binary f) ->
((ind_isum (fun (l:Z) => ((f l) * (power 2%Z ((n - 1%Z)%Z - l)%Z))%Z) 0%Z
n)
=
(ind_isum (fun (l:Z) => ((f ((n - 1%Z)%Z - l)%Z) * (power 2%Z l))%Z) 0%Z
n)).
Axiom bv_to_int_sum_rev :
forall (bv:bitvec),
((ind_isum
(fun (k:Z) =>
(((getbv bv) (((length bv) - 1%Z)%Z - k)%Z) * (power 2%Z k))%Z)
0%Z (length bv))
= (bv_to_int bv)).
Axiom ind_isum_bv_bound_growing :
forall (bv:bitvec) (i:Z), ((0%Z < i)%Z /\ (i < (length bv))%Z) ->
((ind_isum (fun (l:Z) => (((getbv bv) l) * (power 2%Z l))%Z) 0%Z i) <
(power 2%Z i))%Z.
Axiom ind_isum_bv_bound :
forall (bv:bitvec) (i:Z), ((0%Z <= i)%Z /\ (i < (length bv))%Z) ->
((ind_isum
(fun (l:Z) =>
(((getbv bv) l) * (power 2%Z (((length bv) - 1%Z)%Z - l)%Z))%Z)
i (length bv))
< (power 2%Z ((length bv) - i)%Z))%Z.
Axiom ind_isum_bin_bound :
forall (f:Z -> Z) (n:Z) (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) -> (binary f) ->
((ind_isum (fun (l:Z) => ((f l) * (power 2%Z ((n - 1%Z)%Z - l)%Z))%Z) i n)
< (power 2%Z (n - i)%Z))%Z.
Axiom bv_to_int_bound :
forall (bv:bitvec), ((length bv) >= 1%Z)%Z ->
((bv_to_int bv) < (power 2%Z (length bv)))%Z.
Axiom multiple_control_as_ang_sum :
forall (n:Z), (0%Z < n)%Z -> forall (x:bitvec), ((length x) = n) ->
((forall (j:Z), ((0%Z <= j)%Z /\ (j < n)%Z) -> (((getbv x) j) = 1%Z)) ->
(ang_minus_one =
(ang_mult_int ang_minus_one (ind_iproduct (getbv x) 0%Z n)))) /\
(~ (forall (j:Z), ((0%Z <= j)%Z /\ (j < n)%Z) -> (((getbv x) j) = 1%Z)) ->
(ang_zero = (ang_mult_int ang_minus_one (ind_iproduct (getbv x) 0%Z n)))).
Axiom multiple_control_as_ang_sum_rev :
forall (n:Z), (0%Z < n)%Z -> forall (x:bitvec), ((length x) = n) ->
((forall (j:Z), ((0%Z <= j)%Z /\ (j < n)%Z) -> (((getbv x) j) = 1%Z)) ->
((ang_mult_int ang_minus_one (ind_iproduct (getbv x) 0%Z n)) =
ang_minus_one)) /\
(~ (forall (j:Z), ((0%Z <= j)%Z /\ (j < n)%Z) -> (((getbv x) j) = 1%Z)) ->
((ang_mult_int ang_minus_one (ind_iproduct (getbv x) 0%Z n)) = ang_zero)).
Axiom ang_sum_map :
forall (i:Z) (j:Z) (k:Z) (l:Z) (f:Z -> Z) (t1:Z -> angle), (i < j)%Z ->
(p_bijective f (to_fset i j) (to_fset k l)) ->
((ang_sum t1 k l) = (ang_sum (fun (b:Z) => (t1 (f b))) i j)).
Axiom ang_sum_break :
forall (f:Z -> angle) (i:Z) (j:Z) (y:Z), ((i <= y)%Z /\ (y <= j)%Z) ->
((ang_sum f i j) = (ang_add (ang_sum f i y) (ang_sum f y j))).
Axiom ang_sum_break_zero_l :
forall (f:Z -> angle) (i:Z) (j:Z) (y:Z), ((i <= y)%Z /\ (y <= j)%Z) ->
(forall (k:Z), ((i <= k)%Z /\ (k < y)%Z) -> ((f k) = ang_zero)) ->
((ang_sum f y j) = (ang_sum f i j)).
Axiom ang_sum_break_zero_lg :
forall (f:Z -> angle) (g:Z -> angle) (i:Z) (j:Z) (y:Z),
((i <= y)%Z /\ (y <= j)%Z) ->
(forall (k:Z), ((i <= k)%Z /\ (k < y)%Z) -> ((f k) = ang_zero)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((ang_sum f y j) = (ang_sum g i j)).
Axiom ang_sum_break_zero_lg_params :
forall (f:bitvec -> bitvec -> Z -> Z -> angle)
(g:bitvec -> bitvec -> Z -> Z -> angle) (i:Z) (j:Z) (s:Z) (r:Z),
(s >= 0%Z)%Z -> (r >= 0%Z)%Z ->
(forall (x:bitvec) (z:bitvec), forall (a:Z) (k:Z), ((length x) = s) ->
((length z) = r) -> ((i <= a)%Z /\ (a < j)%Z) ->
((i <= k)%Z /\ (k < a)%Z) -> (((((g x) z) a) k) = ang_zero)) ->
(forall (x:bitvec) (z:bitvec), forall (a:Z) (k:Z), ((length x) = s) ->
((length z) = r) -> ((i <= a)%Z /\ (a < j)%Z) ->
((a <= k)%Z /\ (k < j)%Z) -> (((((f x) z) a) k) = ((((g x) z) a) k))) ->
forall (x:bitvec) (z:bitvec), forall (a:Z), ((length x) = s) ->
((length z) = r) -> ((i <= a)%Z /\ (a < j)%Z) ->
((ang_sum (fun (k:Z) => ((((f x) z) a) k)) a j) =
(ang_sum (fun (k:Z) => ((((g x) z) a) k)) i j)).
Axiom ang_sum_break_zero_l_params :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> a -> Z -> angle) (g:a -> a -> Z -> angle) (i:Z) (j:Z) (l:Z),
((i <= l)%Z /\ (l <= j)%Z) -> forall (x:a) (y:a),
(forall (k:Z), ((i <= k)%Z /\ (k < l)%Z) -> ((((f x) y) k) = ang_zero)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) ->
((((f x) y) k) = (((g x) y) k))) ->
((ang_sum ((g x) y) i j) = (ang_sum ((f x) y) l j)).
Axiom ang_sum_break_param :
forall (f:Z -> Z -> angle) (i:Z) (j:Z), (i < j)%Z -> forall (y:Z),
((i <= y)%Z /\ (y < j)%Z) ->
((ang_sum (f y) i j) = (ang_add (ang_sum (f y) i y) (ang_sum (f y) y j))).
Axiom ang_sum_neutral_param_r :
forall (f:Z -> Z -> angle) (i:Z) (j:Z), (i < j)%Z -> forall (y:Z),
((i <= y)%Z /\ (y < j)%Z) ->
(forall (k:Z), ((y <= k)%Z /\ (k < j)%Z) -> (((f y) k) = ang_zero)) ->
((ang_sum (f y) y j) = ang_zero).
Axiom ang_sum_neutral_param_l :
forall (f:Z -> Z -> angle) (i:Z) (j:Z), (i < j)%Z -> forall (y:Z),
((i <= y)%Z /\ (y < j)%Z) ->
(forall (k:Z), ((i <= k)%Z /\ (k < y)%Z) -> (((f y) k) = ang_zero)) ->
((ang_sum (f y) i y) = ang_zero).
Axiom ang_sum_transl :
forall (f:Z -> angle) (i:Z) (j:Z) (k:Z), (i < j)%Z ->
((ang_sum f i j) =
(ang_sum (fun (b:Z) => (f (b + k)%Z)) (i - k)%Z (j - k)%Z)).
Axiom ang_sum_transl_one :
forall (f:Z -> angle) (i:Z) (j:Z), (i < j)%Z ->
((ang_sum f i j) =
(ang_sum (fun (b:Z) => (f (b - 1%Z)%Z)) (i + 1%Z)%Z (j + 1%Z)%Z)).
Axiom ang_exp_eq :
forall (o:angle) (o':angle), (o = o') -> ((ang_exp o) = (ang_exp o')).
Axiom ang_sum_to_ind_isum :
forall (f:Z -> Z) (n:Z) (i:Z) (j:Z), (0%Z <= n)%Z -> (i < j)%Z ->
((ang_sum (fun (k:Z) => (int_to_ang (f k) n)) i j) =
(int_to_ang (ind_isum f i j) n)).
Axiom ind_isum_to_d_sum :
forall (f:Z -> Z) (n:Z) (i:Z) (j:Z), (0%Z <= n)%Z -> (i < j)%Z ->
((int_to_ang (ind_isum f i j) n) =
(ang_sum (fun (k:Z) => (int_to_ang (f k) n)) i j)).
Axiom ind_isum_mod_div :
forall (bv:bitvec) (i:Z), ((0%Z <= i)%Z /\ (i < (length bv))%Z) ->
((int.EuclideanDivision.mod1
(ind_isum
(fun (k:Z) =>
(((getbv bv) k) * (power 2%Z (((length bv) - 1%Z)%Z - k)%Z))%Z)
0%Z (length bv))
(power 2%Z ((length bv) - i)%Z))
=
(ind_isum
(fun (k:Z) =>
(((getbv bv) k) * (power 2%Z (((length bv) - 1%Z)%Z - k)%Z))%Z)
i (length bv))) /\
((int.EuclideanDivision.div
(ind_isum
(fun (k:Z) =>
(((getbv bv) k) * (power 2%Z (((length bv) - 1%Z)%Z - k)%Z))%Z)
0%Z (length bv))
(power 2%Z ((length bv) - i)%Z))
=
(ind_isum
(fun (k:Z) => (((getbv bv) k) * (power 2%Z ((i - 1%Z)%Z - k)%Z))%Z) 0%Z
i)).
Axiom mod_ind_isum :
forall (f:Z -> Z) (i:Z) (l:Z), ((0%Z <= i)%Z /\ (i <= l)%Z) ->
(binary f) ->
((int.EuclideanDivision.mod1
(ind_isum (fun (k:Z) => ((f k) * (power 2%Z ((l - 1%Z)%Z - k)%Z))%Z) 0%Z
l)
(power 2%Z i))
=
(ind_isum (fun (k:Z) => ((f k) * (power 2%Z ((l - 1%Z)%Z - k)%Z))%Z)
(l - i)%Z l)).
Axiom mod_ind_isum_z :
forall (f:Z -> Z) (i:Z) (l:Z), ((0%Z <= i)%Z /\ (i <= l)%Z) ->
(binary f) ->
((int.EuclideanDivision.mod1
(ind_isum (fun (k:Z) => ((f k) * (power 2%Z ((l - 1%Z)%Z - k)%Z))%Z) 0%Z
l)
(power 2%Z i))
=
(ind_isum
(fun (k:Z) =>
((f ((k + l)%Z - i)%Z) * (power 2%Z ((i - 1%Z)%Z - k)%Z))%Z)
0%Z i)).
Axiom div_ind_isum :
forall (f:Z -> Z) (i:Z) (l:Z), ((0%Z <= i)%Z /\ (i <= l)%Z) ->
(binary f) ->
((int.EuclideanDivision.div
(ind_isum (fun (k:Z) => ((f k) * (power 2%Z ((l - 1%Z)%Z - k)%Z))%Z) 0%Z
l)
(power 2%Z i))
=
(ind_isum
(fun (k:Z) => ((f k) * (power 2%Z (((l - 1%Z)%Z - k)%Z - i)%Z))%Z) 0%Z
(l - i)%Z)).
Axiom ind_isum_mod :
forall (bv:bitvec) (i:Z), ((0%Z <= i)%Z /\ (i < (length bv))%Z) ->
((int.EuclideanDivision.mod1
(ind_isum (fun (l:Z) => (((getbv bv) l) * (power 2%Z (i - l)%Z))%Z) 0%Z
(i + 1%Z)%Z)
2%Z)
= ((getbv bv) i)).
Axiom bv_to_int_kth_pre :
forall (bv:bitvec) (k:Z),
((0%Z <= k)%Z /\ (k < ((length bv) - 1%Z)%Z)%Z) ->
(((getbv bv) k) =
(int.EuclideanDivision.mod1
(int.EuclideanDivision.div
(ind_isum
(fun (l:Z) =>
(((getbv bv) l) * (power 2%Z (((length bv) - 1%Z)%Z - l)%Z))%Z)
0%Z (length bv))
(power 2%Z (((length bv) - k)%Z - 1%Z)%Z))
2%Z)) /\
(((getbv bv) k) =
(int.EuclideanDivision.div
(int.EuclideanDivision.mod1
(ind_isum
(fun (l:Z) =>
(((getbv bv) l) * (power 2%Z (((length bv) - 1%Z)%Z - l)%Z))%Z)
0%Z (length bv))
(power 2%Z ((length bv) - k)%Z))
(power 2%Z (((length bv) - k)%Z - 1%Z)%Z))).
Parameter int_to_bv: Z -> Z -> bitvec.
Parameter result12: Z -> Z -> Z -> Z.
Axiom result_def12 :
forall (i:Z) (n:Z) (k:Z),
(((0%Z <= k)%Z /\ (k < n)%Z) ->
(((result12 i n) k) =
(int.EuclideanDivision.div
(int.EuclideanDivision.mod1 i (power 2%Z (n - k)%Z))
(power 2%Z ((n - k)%Z - 1%Z)%Z)))) /\
(~ ((0%Z <= k)%Z /\ (k < n)%Z) -> (((result12 i n) k) = 0%Z)).
Axiom int_to_bv_def :
forall (i:Z) (n:Z), (n >= 0%Z)%Z ->
((int_to_bv i n) = (make_bv (result12 i n) n)).
Axiom int_to_bv_spec :
forall (i:Z) (n:Z), (n >= 0%Z)%Z ->
((length (int_to_bv i n)) = n) /\
((int_to_bv i n) =
(make_bv
(fun (k:Z) =>
(int.EuclideanDivision.div
(int.EuclideanDivision.mod1 i (power 2%Z (n - k)%Z))
(power 2%Z ((n - k)%Z - 1%Z)%Z)))
n)).
Axiom int_to_bv_sum_pre :
forall (i:Z) (n:Z) (k:Z), ((n >= k)%Z /\ (k >= 0%Z)%Z) ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((int.EuclideanDivision.mod1 i (power 2%Z k)) =
(ind_isum
(fun (l:Z) =>
(((getbv (int_to_bv i n)) l) * (power 2%Z ((n - l)%Z - 1%Z)%Z))%Z)
(n - k)%Z n)).
Axiom int_to_bv_sum :
forall (i:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
(i =
(ind_isum
(fun (k:Z) =>
(((getbv (int_to_bv i n)) k) * (power 2%Z ((n - 1%Z)%Z - k)%Z))%Z)
0%Z n)).
Axiom int_to_bv_sum_rev :
forall (i:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((ind_isum
(fun (k:Z) =>
(((getbv (int_to_bv i n)) k) * (power_ 2%Z ((n - k)%Z - 1%Z)%Z))%Z)
0%Z n)
= i).
Axiom product_int_to_bv_inv :
forall (n:Z) (i:Z), ((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((i = 0%Z) ->
((ind_iproduct (fun (j:Z) => (1%Z - ((getbv (int_to_bv i n)) j))%Z) 0%Z n)
= 1%Z)) /\
(~ (i = 0%Z) ->
((ind_iproduct (fun (j:Z) => (1%Z - ((getbv (int_to_bv i n)) j))%Z) 0%Z n)
= 0%Z)).
Axiom int_to_bv_mod_div :
forall (i:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((int_to_bv i n) =
(make_bv
(fun (k:Z) =>
(int.EuclideanDivision.mod1
(int.EuclideanDivision.div i (power 2%Z ((n - k)%Z - 1%Z)%Z)) 2%Z))
n)).
Axiom mod_isum :
forall (i:Z) (k:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> ((0%Z <= k)%Z /\ (k < n)%Z) ->
((int.EuclideanDivision.mod1 i (power 2%Z k)) =
(ind_isum
(fun (l:Z) =>
(((getbv (int_to_bv i n)) l) * (power 2%Z ((n - 1%Z)%Z - l)%Z))%Z)
(n - k)%Z n)).
Axiom mod_isum_z :
forall (i:Z) (k:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> ((0%Z <= k)%Z /\ (k < n)%Z) ->
((int.EuclideanDivision.mod1 i (power 2%Z k)) =
(ind_isum
(fun (l:Z) =>
(((getbv (int_to_bv i n)) (l + (n - k)%Z)%Z) *
(power 2%Z ((k - l)%Z - 1%Z)%Z))%Z)
0%Z k)).
Axiom div_isum :
forall (i:Z) (k:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> ((0%Z <= k)%Z /\ (k < n)%Z) ->
((int.EuclideanDivision.div i (power 2%Z k)) =
(ind_isum
(fun (l:Z) =>
(((getbv (int_to_bv i n)) l) *
(power 2%Z (((n - 1%Z)%Z - k)%Z - l)%Z))%Z)
0%Z (n - k)%Z)).
Axiom int_to_bv_div_mod :
forall (i:Z) (k:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> ((0%Z <= k)%Z /\ (k < n)%Z) ->
((int_to_bv i n) =
(make_bv
(fun (k1:Z) =>
(int.EuclideanDivision.div
(int.EuclideanDivision.mod1 i (power 2%Z (n - k1)%Z))
(power 2%Z ((n - k1)%Z - 1%Z)%Z)))
n)).
Axiom int_to_bv_value :
forall (i:Z) (n:Z) (k:Z), (n > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> ((0%Z <= k)%Z /\ (k < n)%Z) ->
(((getbv (int_to_bv i n)) k) =
(int.EuclideanDivision.mod1
(int.EuclideanDivision.div i (power 2%Z ((n - k)%Z - 1%Z)%Z)) 2%Z)).
Axiom int_to_bv_value_zero :
forall (i:Z) (n:Z), (0%Z < n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((i < (power 2%Z (n - 1%Z)%Z))%Z -> (((getbv (int_to_bv i n)) 0%Z) = 0%Z)) /\
(~ (i < (power 2%Z (n - 1%Z)%Z))%Z ->
(((getbv (int_to_bv i n)) 0%Z) = 1%Z)).
Axiom int_to_bv_zero :
forall (n:Z), forall (k:Z), ((0%Z <= k)%Z /\ (k < n)%Z) ->
(((getbv (int_to_bv 0%Z n)) k) = 0%Z).
Axiom int_to_sum :
forall (i:Z) (n:Z), (n > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
(i =
(ind_isum
(fun (k:Z) =>
(((getbv (int_to_bv i n)) k) * (power 2%Z ((n - k)%Z - 1%Z)%Z))%Z)
0%Z n)).
Axiom int_to_bv_transl :
forall (i:Z) (k:Z) (n:Z) (t1:Z), ((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= k)%Z /\ (k < (n - t1)%Z)%Z) -> ((0%Z < t1)%Z /\ (t1 <= n)%Z) ->
(((getbv
(int_to_bv (int.EuclideanDivision.mod1 i (power 2%Z (n - t1)%Z))
(n - t1)%Z))
k)
= ((getbv (int_to_bv i n)) (k + t1)%Z)).
Parameter bin_to_int: (Z -> Z) -> Z -> Z.
Axiom bin_to_int_def :
forall (f:Z -> Z) (n:Z), (0%Z <= n)%Z -> (binary f) ->
((bin_to_int f n) = (bv_to_int (make_bv f n))).
Axiom bin_to_int_spec :
forall (f:Z -> Z) (n:Z), (0%Z <= n)%Z -> (binary f) ->
((bin_to_int f n) =
(ind_isum (fun (k:Z) => ((f k) * (power 2%Z ((n - 1%Z)%Z - k)%Z))%Z) 0%Z
n)) /\
(0%Z <= (bin_to_int f n))%Z.
Parameter int_to_bin: Z -> Z -> Z -> Z.
Axiom int_to_bin_def :
forall (i:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((int_to_bin i n) = (getbv (int_to_bv i n))).
Axiom int_to_bin_spec :
forall (i:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
(i =
(ind_isum
(fun (k:Z) => (((int_to_bin i n) k) * (power 2%Z ((n - 1%Z)%Z - k)%Z))%Z)
0%Z n)) /\
((binary (int_to_bin i n)) /\
forall (k:Z), ((0%Z <= k)%Z /\ (k < n)%Z) ->
(((int_to_bin i n) k) =
(int.EuclideanDivision.mod1
(int.EuclideanDivision.div i (power 2%Z ((n - k)%Z - 1%Z)%Z)) 2%Z))).
Axiom int_to_bv_tail :
forall (i:Z) (n:Z), (n > 1%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((int_to_bv (tail_bits i n) (n - 1%Z)%Z) = (tail (int_to_bv i n))).
Axiom bound_sum_dec :
forall (bv:bitvec) (i:Z), ((1%Z <= i)%Z /\ (i <= (length bv))%Z) ->
((ind_isum
(fun (l:Z) => (((getbv bv) l) * (power 2%Z ((length bv) - l)%Z))%Z) i
((length bv) + 1%Z)%Z)
< (power 2%Z (((length bv) - i)%Z + 1%Z)%Z))%Z.
Axiom bv_to_int_to_bv :
forall (i:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((bv_to_int (int_to_bv i n)) = i).
Axiom tail_bits_sum :
forall (i:Z) (n:Z), (1%Z < n)%Z -> (0%Z <= i)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((tail_bits i n) =
(ind_isum
(fun (l:Z) =>
(((getbv (int_to_bv i n)) l) * (power 2%Z ((n - 1%Z)%Z - l)%Z))%Z)
1%Z n)).
Axiom int_to_bv_to_int :
forall (bv:bitvec), (1%Z <= (length bv))%Z ->
((int_to_bv (bv_to_int bv) (length bv)) = bv).
Axiom concat_to_int :
forall (bv:bitvec) (i:Z), ((0%Z <= i)%Z /\ (i <= 1%Z)%Z) ->
((bv_to_int (concat_l bv i)) =
((bv_to_int bv) + (i * (power 2%Z (length bv)))%Z)%Z).
Axiom bounded_to_int :
forall (bv:bitvec), ((bv_to_int bv) < (power 2%Z (length bv)))%Z.
Axiom int_to_bv_to_int_value :
forall (bv:bitvec) (i:Z), (1%Z <= (length bv))%Z ->
(((0%Z <= i)%Z /\ (i < (length bv))%Z) ->
(((getbv (int_to_bv (bv_to_int bv) (length bv))) i) = ((getbv bv) i))) /\
(~ ((0%Z <= i)%Z /\ (i < (length bv))%Z) ->
(((getbv (int_to_bv (bv_to_int bv) (length bv))) i) = 0%Z)).
Axiom int_to_bv_to_int_gen :
forall (bv:bitvec) (n:Z), (1%Z <= (length bv))%Z -> (n = (length bv)) ->
((int_to_bv (bv_to_int bv) n) = bv).
Axiom bv_to_int_mod :
forall (bv:bitvec) (k:Z), ((0%Z <= k)%Z /\ (k < (length bv))%Z) ->
((int.EuclideanDivision.mod1 (bv_to_int bv)
(power 2%Z ((length bv) - k)%Z))
=
(ind_isum
(fun (l:Z) =>
(((getbv bv) l) * (power 2%Z (((length bv) - 1%Z)%Z - l)%Z))%Z)
k (length bv))).
Axiom bv_to_int_mod_rev :
forall (bv:bitvec) (k:Z), ((0%Z <= k)%Z /\ (k < (length bv))%Z) ->
((ind_isum
(fun (l:Z) =>
(((getbv bv) l) * (power 2%Z (((length bv) - 1%Z)%Z - l)%Z))%Z)
k (length bv))
=
(int.EuclideanDivision.mod1 (bv_to_int bv)
(power 2%Z ((length bv) - k)%Z))).
Axiom bv_to_int_mod_gen :
forall (k:Z) (n:Z), ((0%Z <= k)%Z /\ (k < n)%Z) -> forall (bv:bitvec),
((length bv) = n) ->
((int.EuclideanDivision.mod1 (bv_to_int bv)
(power 2%Z ((length bv) - k)%Z))
=
(ind_isum
(fun (l:Z) =>
(((getbv bv) l) * (power 2%Z (((length bv) - 1%Z)%Z - l)%Z))%Z)
k (length bv))).
Axiom to_int_head_tail :
forall (bv:bitvec), ((length bv) >= 1%Z)%Z ->
((bv_to_int bv) =
((bv_to_int (tail bv)) +
((head bv) * (power 2%Z ((length bv) - 1%Z)%Z))%Z)%Z) /\
((bv_to_int (tail bv)) =
(int.EuclideanDivision.mod1 (bv_to_int bv)
(power 2%Z ((length bv) - 1%Z)%Z))).
Axiom not_disj :
forall (a:bool) (b:bool), ~ (a = true) -> ~ (b = true) ->
~ ((a = true) \/ (b = true)).
Parameter my_map:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a -> b) ->
(set a) -> set b.
Axiom my_map_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (u:set a),
(((cardinal u) = 0%Z) -> ((my_map f u) = (empty : set b))) /\
(~ ((cardinal u) = 0%Z) ->
((my_map f u) = (add (f (choose u)) (my_map f (remove (choose u) u))))).
Axiom my_map_spec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (u:set a), ((my_map f u) = (map f u)).
Axiom my_map_to_map :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (u:set a), ((my_map f u) = (map f u)).
Axiom map_to_my_map :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:a -> b) (u:set a), ((map f u) = (my_map f u)).
Parameter n_bvs: Z -> set bitvec.
Axiom n_bvs_def :
forall (n:Z), (0%Z <= n)%Z ->
((n = 0%Z) -> ((n_bvs n) = (to_set (make_bv (fun (i:Z) => 0%Z) 0%Z)))) /\
(~ (n = 0%Z) ->
((n_bvs n) =
(union
(my_map (fun (bv:bitvec) => (concat_l bv 0%Z)) (n_bvs (n - 1%Z)%Z))
(my_map (fun (bv:bitvec) => (concat_l bv 1%Z)) (n_bvs (n - 1%Z)%Z))))).
Axiom n_bvs_spec :
forall (n:Z), (0%Z <= n)%Z ->
(forall (f:bitvec), (mem f (n_bvs n)) -> ((length f) = n)) /\
((forall (f:bitvec), (mem f (n_bvs n)) <-> ((length f) = n)) /\
((cardinal (n_bvs n)) > 0%Z)%Z).
Axiom n_bvs_node :
forall (n:Z), (0%Z < n)%Z ->
((inter (map (fun (bv:bitvec) => (concat_l bv 0%Z)) (n_bvs (n - 1%Z)%Z))
(map (fun (bv:bitvec) => (concat_l bv 1%Z)) (n_bvs (n - 1%Z)%Z)))
= (empty : set bitvec)) /\
((union (map (fun (bv:bitvec) => (concat_l bv 0%Z)) (n_bvs (n - 1%Z)%Z))
(map (fun (bv:bitvec) => (concat_l bv 1%Z)) (n_bvs (n - 1%Z)%Z)))
= (n_bvs n)).
Axiom injective_node :
forall (n:Z), (0%Z <= n)%Z ->
(p_injective (fun (bv:bitvec) => (concat_l bv 0%Z)) (n_bvs n)) /\
(p_injective (fun (bv:bitvec) => (concat_l bv 1%Z)) (n_bvs n)).
Axiom mat_sum_n_bvs_pos :
forall (n:Z) (f:bitvec -> matrix t), (0%Z < n)%Z ->
(constant_size (n_bvs n) f) ->
((mat_sum (n_bvs n) f) =
(add_mat
(mat_sum (n_bvs (n - 1%Z)%Z) (fun (bv:bitvec) => (f (concat_l bv 0%Z))))
(mat_sum (n_bvs (n - 1%Z)%Z) (fun (bv:bitvec) => (f (concat_l bv 1%Z)))))).
Axiom mat_sum_n_bvs_null :
forall (f:bitvec -> matrix t),
((mat_sum (n_bvs 0%Z) f) =
(f (make_bv ((fun (y0:Z) (y1:Z) => (const y0 y1)) 0%Z) 0%Z))).
Axiom mat_sum_n_bvs_null_eq :
forall (f:bitvec -> matrix t) (x:matrix t),
(x = (f (make_bv ((fun (y0:Z) (y1:Z) => (const y0 y1)) 0%Z) 0%Z))) ->
((mat_sum (n_bvs 0%Z) f) = x).
Axiom get_n_bvs : forall (bv:bitvec), mem bv (n_bvs (length bv)).
Axiom get_n_bvs_gen :
forall (bv:bitvec) (l:Z), (l = (length bv)) -> mem bv (n_bvs l).
Axiom set_n_bvs :
forall (bv:bitvec), (mem bv (n_bvs (length bv))) -> forall (i:Z),
~ ((0%Z <= i)%Z /\ (i < (length bv))%Z) -> (((getbv bv) i) = 0%Z).
Axiom int_to_bv_n_bvs :
forall (i:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> mem (int_to_bv i n) (n_bvs n).
Axiom n_bvs_def_pos :
forall (n:Z), (0%Z < n)%Z ->
((n_bvs n) =
(union (map (fun (bv:bitvec) => (concat_l bv 0%Z)) (n_bvs (n - 1%Z)%Z))
(map (fun (bv:bitvec) => (concat_l bv 1%Z)) (n_bvs (n - 1%Z)%Z)))).
Axiom map_n_bvs :
forall (n:Z), (0%Z < n)%Z ->
((to_fset 0%Z (power 2%Z n)) =
(map (fun (y0:bitvec) => (bv_to_int y0)) (n_bvs n))).
Parameter first_div: bitvec -> bitvec -> Z.
Axiom first_div_spec :
forall (bv1:bitvec) (bv2:bitvec), ((length bv1) = (length bv2)) ->
~ (bv1 = bv2) ->
(forall (j:Z), ((0%Z <= j)%Z /\ (j < (first_div bv1 bv2))%Z) ->
(((getbv bv1) j) = ((getbv bv2) j))) /\
((((first_div bv1 bv2) < (length bv1))%Z ->
~ (((getbv bv1) (first_div bv1 bv2)) = ((getbv bv2) (first_div bv1 bv2)))) /\
((0%Z <= (first_div bv1 bv2))%Z /\ ((first_div bv1 bv2) < (length bv1))%Z)).
Axiom injective_concat :
forall (i:Z) (n:Z), (0%Z <= n)%Z -> ((0%Z <= i)%Z /\ (i <= 1%Z)%Z) ->
p_injective (fun (bv:bitvec) => (concat_l bv i)) (n_bvs n).
Axiom inf_first_div :
forall (bv1:bitvec) (bv2:bitvec), ((length bv1) = (length bv2)) ->
~ (bv1 = bv2) -> forall (j:Z), (1%Z <= j)%Z ->
~ (((getbv bv1) j) = ((getbv bv2) j)) -> ((first_div bv1 bv2) <= j)%Z.
Axiom first_div_diff :
forall (bv1:bitvec) (bv2:bitvec), ((length bv1) = (length bv2)) ->
~ (bv1 = bv2) ->
~ (((getbv bv1) (first_div bv1 bv2)) = ((getbv bv2) (first_div bv1 bv2))).
Axiom exists_first_div :
forall (bv1:bitvec) (bv2:bitvec), ((length bv1) = (length bv2)) ->
~ (bv1 = bv2) ->
exists i:Z,
((0%Z <= i)%Z /\ (i < (length bv1))%Z) /\ (i = (first_div bv1 bv2)).
Axiom set_diff_length :
forall (bv1:bitvec) (bv2:bitvec), ~ ((length bv1) = (length bv2)) ->
~ (bv1 = bv2).
Axiom set_diff_val :
forall (bv1:bitvec) (bv2:bitvec) (i:Z), ((length bv1) = (length bv2)) ->
((0%Z <= i)%Z /\ (i < (length bv1))%Z) ->
~ (((getbv bv1) i) = ((getbv bv2) i)) -> ~ (bv1 = bv2).
Parameter fc6: bitvec -> Z -> Z.
Parameter fc7: bitvec -> Z -> Z.
Axiom fc_def6 :
forall (bv:bitvec) (l:Z),
((l < (length bv))%Z ->
(((fc6 bv) l) =
(((getbv bv) l) * (power 2%Z (((length bv) - 1%Z)%Z - l)%Z))%Z)) /\
(~ (l < (length bv))%Z -> (((fc6 bv) l) = 0%Z)).
Axiom fc_def7 :
forall (bv:bitvec) (l:Z),
((l < (length bv))%Z ->
(((fc7 bv) l) =
(((getbv bv) l) * (power 2%Z (((length bv) - 1%Z)%Z - l)%Z))%Z)) /\
(~ (l < (length bv))%Z -> (((fc7 bv) l) = 0%Z)).
Axiom kth_decomp :
forall (bv:bitvec) (k:Z), ((0%Z <= k)%Z /\ (k < (length bv))%Z) ->
((bv_to_int bv) =
(((ind_isum (fc6 bv) 0%Z k) +
(((getbv bv) k) * (power 2%Z (((length bv) - 1%Z)%Z - k)%Z))%Z)%Z
+ (ind_isum (fc7 bv) (k + 1%Z)%Z (length bv)))%Z) /\
((bv_to_int bv) =
(((ind_isum
(fun (l:Z) =>
(((getbv bv) l) * (power 2%Z (((length bv) - 1%Z)%Z - l)%Z))%Z)
0%Z k)
+ (((getbv bv) k) * (power 2%Z (((length bv) - 1%Z)%Z - k)%Z))%Z)%Z
+
(ind_isum
(fun (l:Z) =>
(((getbv bv) l) * (power 2%Z (((length bv) - 1%Z)%Z - l)%Z))%Z)
(k + 1%Z)%Z (length bv)))%Z).
Axiom int_to_bv_prod :
forall (i:Z) (j:Z) (n:Z), (n > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((ind_product
(fun (k:Z) =>
(indic ((getbv (int_to_bv i n)) k) ((getbv (int_to_bv j n)) k)))
0%Z n)
= (indic i j)).
Axiom int_to_bv_prod_gen :
forall (i:Z) (n:Z), (n > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> forall (j:Z),
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((ind_product
(fun (k:Z) =>
(indic ((getbv (int_to_bv i n)) k) ((getbv (int_to_bv j n)) k)))
0%Z n)
= (indic i j)).
Axiom kth_decomp_bound_zero :
forall (bv:bitvec) (k:Z), ((0%Z <= k)%Z /\ (k < (length bv))%Z) ->
(((getbv bv) k) = 0%Z) ->
((ind_isum
(fun (l:Z) =>
(((getbv bv) l) * (power 2%Z (((length bv) - 1%Z)%Z - l)%Z))%Z)
0%Z k)
<= (bv_to_int bv))%Z /\
((bv_to_int bv) <
((ind_isum
(fun (l:Z) =>
(((getbv bv) l) * (power 2%Z (((length bv) - 1%Z)%Z - l)%Z))%Z)
0%Z k)
+ (power 2%Z (((length bv) - k)%Z - 1%Z)%Z))%Z)%Z.
Axiom kth_decomp_bound_one :
forall (bv:bitvec) (k:Z), ((0%Z <= k)%Z /\ (k < (length bv))%Z) ->
(((getbv bv) k) = 1%Z) ->
(((ind_isum
(fun (l:Z) =>
(((getbv bv) l) * (power 2%Z (((length bv) - 1%Z)%Z - l)%Z))%Z)
0%Z k)
+ (power 2%Z (((length bv) - k)%Z - 1%Z)%Z))%Z
<= (bv_to_int bv))%Z /\
((bv_to_int bv) <
((ind_isum
(fun (l:Z) =>
(((getbv bv) l) * (power 2%Z (((length bv) - l)%Z - 1%Z)%Z))%Z)
0%Z k)
+ (power 2%Z ((length bv) - k)%Z))%Z)%Z.
Axiom ang_sum_int_decomp :
forall (bvx:Z -> Z) (k:Z) (n:Z), (0%Z < n)%Z -> (binary bvx) ->
((ang_sum
(fun (x:Z) =>
(int_to_ang (((bvx x) * (power 2%Z ((n - x)%Z - 1%Z)%Z))%Z * k)%Z n))
0%Z n)
= (int_to_ang ((bin_to_int bvx n) * k)%Z n)).
Axiom ang_sum_int_decomp_gen :
forall (bvx:Z -> Z) (n:Z), (0%Z < n)%Z -> (binary bvx) -> forall (k:Z),
((ang_sum
(fun (x:Z) =>
(int_to_ang (((bvx x) * (power 2%Z ((n - x)%Z - 1%Z)%Z))%Z * k)%Z n))
0%Z n)
= (int_to_ang ((bin_to_int bvx n) * k)%Z n)).
Axiom ang_sum_bv_to_int :
forall (n:Z), (0%Z < n)%Z -> forall (x:bitvec), forall (k:Z),
((length x) = n) ->
((ang_sum
(fun (i:Z) =>
(int_to_ang ((((getbv x) i) * (power 2%Z ((n - i)%Z - 1%Z)%Z))%Z * k)%Z
n))
0%Z n)
= (int_to_ang ((bv_to_int x) * k)%Z n)).
Axiom ang_sum_bv_to_int_ :
forall (n:Z), (0%Z < n)%Z -> forall (x:bitvec), forall (k:Z),
((length x) = n) ->
((ang_sum
(fun (i:Z) =>
(int_to_ang ((((getbv x) i) * (power_ 2%Z ((n - i)%Z - 1%Z)%Z))%Z * k)%Z
n))
0%Z n)
= (int_to_ang ((bv_to_int x) * k)%Z n)).
Parameter bv_inversion: bitvec -> bitvec.
Axiom bv_inversion_def :
forall (bv:bitvec),
((bv_inversion bv) =
(make_bv (fun (k:Z) => ((getbv bv) (((length bv) - k)%Z - 1%Z)%Z))
(length bv))).
Axiom bv_inversion_spec :
forall (bv:bitvec),
((length (bv_inversion bv)) = (length bv)) /\
forall (k:Z), (in_range (bv_inversion bv) k) ->
(((getbv (bv_inversion bv)) k) =
((getbv bv) (((length bv) - k)%Z - 1%Z)%Z)).
Axiom bv_inversion_value :
forall (bv:bitvec) (i:Z),
(((getbv (bv_inversion bv)) i) =
((getbv bv) (((length bv) - i)%Z - 1%Z)%Z)).
Axiom bv_inversion_invol :
forall (bv:bitvec), ((bv_inversion (bv_inversion bv)) = bv).
Parameter int_bit_inversion: Z -> Z -> Z.
Axiom int_bit_inversion_def :
forall (i:Z) (n:Z), (0%Z < n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((int_bit_inversion i n) = (bv_to_int (bv_inversion (int_to_bv i n)))).
Axiom int_bit_inversion_spec :
forall (i:Z) (n:Z), (0%Z < n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
(0%Z <= (int_bit_inversion i n))%Z /\
((int_bit_inversion i n) < (power 2%Z n))%Z.
Axiom int_bit_inversion_invol :
forall (i:Z) (n:Z), (0%Z < n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((int_bit_inversion (int_bit_inversion i n) n) = i).
Axiom int_bit_inversion_onebit :
forall (i:Z), ((0%Z <= i)%Z /\ (i < 2%Z)%Z) ->
((int_bit_inversion i 1%Z) = i).
Axiom int_bit_inversion_zero :
forall (i:Z) (n:Z), (0%Z < n)%Z -> (0%Z = i) ->
((int_bit_inversion i n) = 0%Z).
Axiom bv_to_int_sum_inversion :
forall (bv:bitvec), ((length bv) > 0%Z)%Z ->
((int_bit_inversion (bv_to_int bv) (length bv)) =
(ind_isum
(fun (k:Z) =>
(((getbv bv) (((length bv) - k)%Z - 1%Z)%Z) *
(power 2%Z (((length bv) - 1%Z)%Z - k)%Z))%Z)
0%Z (length bv))).
Axiom bv_to_int_sum_inversion_inc :
forall (bv:bitvec), ((length bv) > 0%Z)%Z ->
((int_bit_inversion (bv_to_int bv) (length bv)) =
(ind_isum (fun (k:Z) => (((getbv bv) k) * (power 2%Z k))%Z) 0%Z
(length bv))).
Axiom inversion_to_int_comm :
forall (bv:bitvec), ((length bv) > 0%Z)%Z ->
((int_to_bv (int_bit_inversion (bv_to_int bv) (length bv)) (length bv)) =
(bv_inversion bv)).
Axiom bv_inversion_sum :
forall (i:Z) (n:Z), (0%Z < n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((int_bit_inversion i n) =
(ind_isum
(fun (k:Z) =>
(((getbv (int_to_bv i n)) ((n - k)%Z - 1%Z)%Z) *
(power 2%Z ((n - 1%Z)%Z - k)%Z))%Z)
0%Z n)).
Axiom bv_to_int_inversion_sum :
forall (bv:bitvec),
((bv_to_int (bv_inversion bv)) =
(ind_isum
(fun (k:Z) =>
(((getbv bv) (((length bv) - k)%Z - 1%Z)%Z) *
(power 2%Z (((length bv) - 1%Z)%Z - k)%Z))%Z)
0%Z (length bv))).
Axiom bv_to_int_bit_inversion :
forall (bv:bitvec), ((length bv) > 0%Z)%Z ->
((bv_to_int (bv_inversion bv)) =
(int_bit_inversion (bv_to_int bv) (length bv))).
Axiom bv_to_int_inversion_sum_inc :
forall (bv:bitvec), ((length bv) > 0%Z)%Z ->
((bv_to_int (bv_inversion bv)) =
(ind_isum (fun (k:Z) => (((getbv bv) k) * (power 2%Z k))%Z) 0%Z
(length bv))).
Axiom bv_m_to_int_bit_inversion :
forall (f:Z -> Z) (n:Z), (0%Z < n)%Z ->
((bv_to_int (bv_inversion (make_bv_m f n))) =
(int_bit_inversion (bv_to_int (make_bv_m f n)) n)).
Axiom int_bit_inversion_tail_bits :
forall (i:Z) (n:Z), (1%Z < n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((int_bit_inversion (tail_bits i n) (n - 1%Z)%Z) =
(ind_isum
(fun (k:Z) =>
(((getbv (int_to_bv i n)) (n - k)%Z) *
(power 2%Z ((n - k)%Z - 1%Z)%Z))%Z)
1%Z n)).
Axiom tail_bits_int_bit_inversion :
forall (bv:Z -> Z) (n:Z), (1%Z < n)%Z ->
((tail_bits (int_bit_inversion (bv_to_int (make_bv_m bv n)) n) n) =
(ind_isum
(fun (k:Z) =>
((int.EuclideanDivision.mod1 (bv ((n - 1%Z)%Z - k)%Z) 2%Z) *
(power 2%Z ((n - k)%Z - 1%Z)%Z))%Z)
1%Z n)).
Axiom int_bit_inversion_ht :
forall (i:Z) (n:Z), (1%Z < n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((int_bit_inversion i n) =
((2%Z * (int_bit_inversion (tail_bits i n) (n - 1%Z)%Z))%Z +
(head_bit i n))%Z).
Axiom bv_inversion_ht :
forall (f:Z -> Z) (n:Z), (1%Z < n)%Z ->
((bv_to_int (bv_inversion (make_bv_m f n))) =
((head (make_bv_m f n)) +
(2%Z * (bv_to_int (bv_inversion (tail (make_bv_m f n)))))%Z)%Z).
Axiom bv_inversion_ht_bv :
forall (bv:bitvec), (1%Z < (length bv))%Z ->
((bv_to_int (bv_inversion bv)) =
((head bv) + (2%Z * (bv_to_int (bv_inversion (tail bv))))%Z)%Z).
Axiom bv_to_int_ht :
forall (f:Z -> Z) (n:Z), (1%Z < n)%Z ->
((bv_to_int (make_bv_m f n)) =
(((power 2%Z (n - 1%Z)%Z) * (head (make_bv_m f n)))%Z +
(bv_to_int (tail (make_bv_m f n))))%Z).
Axiom bv_inversion_mult_ht :
forall (fx:Z -> Z) (fy:Z -> Z) (n:Z), (1%Z < n)%Z ->
(((bv_to_int (make_bv_m fx n)) *
(bv_to_int (bv_inversion (make_bv_m fy n))))%Z
=
((((head (make_bv_m fy n)) * (bv_to_int (make_bv_m fx n)))%Z +
((bv_to_int (tail (make_bv_m fx n))) *
(2%Z * (bv_to_int (bv_inversion (tail (make_bv_m fy n)))))%Z)%Z)%Z
+
((power 2%Z n) *
((head (make_bv_m fx n)) *
(bv_to_int (bv_inversion (tail (make_bv_m fy n)))))%Z)%Z)%Z).
Axiom bv_inversion_mult_ht_bv :
forall (bvx:bitvec) (bvy:bitvec), (1%Z < (length bvx))%Z ->
((length bvx) = (length bvy)) ->
(((bv_to_int bvx) * (bv_to_int (bv_inversion bvy)))%Z =
((((head bvy) * (bv_to_int bvx))%Z +
((bv_to_int (tail bvx)) *
(2%Z * (bv_to_int (bv_inversion (tail bvy))))%Z)%Z)%Z
+
((power 2%Z (length bvx)) *
((head bvx) * (bv_to_int (bv_inversion (tail bvy))))%Z)%Z)%Z).
Axiom real_to_ang_distr_minus :
forall (x:t) (z:t) (t1:t), forall (y:Z), (real_ x) -> (real_ z) ->
(real_ t1) ->
((ang_add (real_to_ang (infix_asdt x (i_to_t y)))
(real_to_ang (infix_asdt (infix_asdt (i_to_t y) (prefix_mndt z)) t1)))
= (ang_mult_int (real_to_ang (infix_mndt x (infix_asdt z t1))) y)).
Axiom ang_sum_int_decomp_gen_rev :
forall (bvx:Z -> Z) (n:Z), (0%Z < n)%Z -> (binary bvx) -> forall (k:Z),
((int_to_ang ((bin_to_int bvx n) * k)%Z n) =
(ang_sum
(fun (x:Z) =>
(int_to_ang (((bvx x) * (power 2%Z ((n - x)%Z - 1%Z)%Z))%Z * k)%Z n))
0%Z n)).
Axiom Ang_mult_int_exp :
forall (o:angle), forall (i:Z),
((ang_exp (ang_mult_int o i)) = (cpower (ang_exp o) i)).
Axiom ang_mult_int_exp_rev :
forall (o:angle) (i:Z),
((cpower (ang_exp o) i) = (ang_exp (ang_mult_int o i))).
Axiom ang_mult_int_add :
forall (o:angle) (i:Z) (i':Z),
((ang_mult_int o (i + i')%Z) =
(ang_add (ang_mult_int o i) (ang_mult_int o i'))).
Axiom ang_mult_int_plus_one :
forall (o:angle) (i:Z),
((ang_add o (ang_mult_int o i)) = (ang_mult_int o (i + 1%Z)%Z)).
Axiom ang_mult_int_plus_one_rev :
forall (o:angle) (i:Z),
((ang_mult_int o (1%Z + i)%Z) = (ang_add o (ang_mult_int o i))).
Axiom sum_ang_mult_int_e :
forall (o:angle) (f:Z -> Z) (l:Z) (h:Z), (l < h)%Z ->
((ang_sum (fun (i:Z) => (ang_mult_int o (f i))) l h) =
(ang_mult_int o (ind_isum f l h))).
Axiom real_to_ang_sum :
forall (phi:Z -> t) (l:Z) (h:Z), (l < h)%Z ->
(forall (i:Z), ((l <= i)%Z /\ (i < h)%Z) -> real_ (phi i)) ->
((ang_sum (fun (i:Z) => (real_to_ang (phi i))) l h) =
(real_to_ang (ind_sum phi l h))).
Axiom real_to_ang_sum_int :
forall (f:Z -> Z) (l:Z) (h:Z) (x:t), (l < h)%Z -> (real_ x) ->
((ang_sum (fun (i:Z) => (real_to_ang (infix_asdt x (i_to_t (f i))))) l h) =
(real_to_ang (infix_asdt x (i_to_t (ind_isum f l h))))).
Axiom real_to_ang_sum_int_gen :
forall (f:Z -> Z) (l:Z) (h:Z), (l < h)%Z -> forall (x:t), (real_ x) ->
((ang_sum (fun (i:Z) => (real_to_ang (infix_asdt x (i_to_t (f i))))) l h) =
(real_to_ang (infix_asdt x (i_to_t (ind_isum f l h))))).
Axiom real_to_ang_bv_inversion :
forall (ft:Z) (x:t) (y:bitvec), (0%Z < ft)%Z -> (real_ x) ->
((length y) = ft) ->
((ang_sum
(fun (i:Z) =>
(real_to_ang
(infix_asdt (infix_asdt x (i_to_t (power_ 2%Z i)))
(i_to_t ((getbv y) i)))))
0%Z ft)
= (real_to_ang (infix_asdt x (i_to_t (bv_to_int (bv_inversion y)))))).
Axiom ang_mult_int_double :
forall (o:angle) (i:Z),
((ang_mult_int o (2%Z * i)%Z) =
(ang_add (ang_mult_int o i) (ang_mult_int o i))).
Axiom ang_mult_int_inv :
forall (o:angle), ((ang_mult_int o (-1%Z)%Z) = (ang_inv o)).
Axiom ang_mult_int_one :
forall (o:angle) (n:Z), (n = 1%Z) -> ((ang_mult_int o n) = o).
Axiom ang_mult_int_inv_rev :
forall (o:angle), ((ang_inv o) = (ang_mult_int o (-1%Z)%Z)).
Axiom ang_mult_int_comp :
forall (o:angle) (i:Z) (j:Z),
((ang_mult_int (ang_mult_int o i) j) = (ang_mult_int o (i * j)%Z)).
Axiom ang_mult_int_comp_rev :
forall (o:angle) (i:Z) (j:Z),
((ang_mult_int o (i * j)%Z) = (ang_mult_int (ang_mult_int o i) j)).
Axiom add_ang_mult_int :
forall (o:angle) (o':angle) (i:Z),
((ang_add (ang_mult_int o i) (ang_mult_int o' i)) =
(ang_mult_int (ang_add o o') i)).
Axiom sum_ang_mult_int :
forall (f:Z -> angle) (i:Z) (l:Z) (h:Z), (l < h)%Z ->
((ang_sum (fun (x:Z) => (ang_mult_int (f x) i)) l h) =
(ang_mult_int (ang_sum f l h) i)).
Axiom ang_sum_bv_to_int_inversion_pre :
forall (n:Z) (x:bitvec), (0%Z < n)%Z -> ((length x) = n) ->
forall (theta:t), (real_ theta) ->
((real_to_ang (infix_asdt theta (i_to_t (bv_to_int (bv_inversion x))))) =
(ang_sum
(fun (i:Z) =>
(real_to_ang
(infix_asdt (infix_asdt theta (i_to_t (power_ 2%Z i)))
(i_to_t ((getbv x) i)))))
0%Z n)).
Axiom ang_sum_bv_to_int_inversion :
forall (n:Z), (0%Z < n)%Z -> forall (x:bitvec), forall (theta:t),
((length x) = n) -> (real_ theta) ->
((real_to_ang (infix_asdt theta (i_to_t (bv_to_int (bv_inversion x))))) =
(ang_sum
(fun (i:Z) =>
(real_to_ang
(infix_asdt (infix_asdt theta (i_to_t (power_ 2%Z i)))
(i_to_t ((getbv x) i)))))
0%Z n)).
Axiom ang_sum_bv_to_int_opp_pre :
forall (n:Z) (x:bitvec), (0%Z < n)%Z -> ((length x) = n) ->
forall (theta:t), (real_ theta) ->
((real_to_ang (infix_asdt theta (i_to_t (-(bv_to_int x))%Z))) =
(ang_sum
(fun (i:Z) =>
(real_to_ang
(infix_asdt
(infix_asdt theta (i_to_t (power_ 2%Z ((n - i)%Z - 1%Z)%Z)))
(i_to_t (-((getbv x) i))%Z))))
0%Z n)).
Axiom ang_sum_bv_to_int_opp :
forall (n:Z), (0%Z < n)%Z -> forall (x:bitvec), forall (theta:t),
((length x) = n) -> (real_ theta) ->
((real_to_ang (infix_asdt theta (i_to_t (-(bv_to_int x))%Z))) =
(ang_sum
(fun (i:Z) =>
(real_to_ang
(infix_asdt
(infix_asdt theta (i_to_t (power_ 2%Z ((n - i)%Z - 1%Z)%Z)))
(i_to_t (-((getbv x) i))%Z))))
0%Z n)).
Axiom ang_sum_bv_to_int_mult_pre :
forall (n:Z) (x:bitvec), (0%Z < n)%Z -> ((length x) = n) ->
forall (theta:t), (real_ theta) ->
((real_to_ang (infix_asdt theta (i_to_t (bv_to_int x)))) =
(ang_sum
(fun (i:Z) =>
(real_to_ang
(infix_asdt
(infix_asdt theta (i_to_t (power_ 2%Z ((n - i)%Z - 1%Z)%Z)))
(i_to_t ((getbv x) i)))))
0%Z n)).
Axiom ang_sum_bv_to_int_mult :
forall (n:Z), (0%Z < n)%Z -> forall (x:bitvec), forall (theta:t),
((length x) = n) -> (real_ theta) ->
((real_to_ang (infix_asdt theta (i_to_t (bv_to_int x)))) =
(ang_sum
(fun (i:Z) =>
(real_to_ang
(infix_asdt
(infix_asdt theta (i_to_t (power_ 2%Z ((n - i)%Z - 1%Z)%Z)))
(i_to_t ((getbv x) i)))))
0%Z n)).
Axiom rewrite_ang_sum_sum_to_bv_and_inversion :
forall (n:Z) (x:bitvec) (y:bitvec), (0%Z < n)%Z -> ((length x) = n) ->
((length y) = n) ->
((ang_sum
(fun (j:Z) =>
(ang_sum
(fun (i:Z) =>
(int_to_ang
(((-((getbv x) i))%Z * ((getbv y) j))%Z *
(power_ 2%Z (((n - i)%Z - 1%Z)%Z + j)%Z))%Z
n))
j n))
0%Z n)
=
(real_to_ang
(infix_sldt
(infix_asdt (i_to_t (-(bv_to_int x))%Z)
(i_to_t (bv_to_int (bv_inversion y))))
(i_to_t (power_ 2%Z n))))).
Axiom rewrite_ang_sum_sum_to_bv_and_inversion_gen :
forall (n:Z), (0%Z < n)%Z -> forall (x:bitvec) (y:bitvec),
((length x) = n) -> ((length y) = n) ->
((ang_sum
(fun (j:Z) =>
(ang_sum
(fun (i:Z) =>
(int_to_ang
(((-((getbv x) i))%Z * ((getbv y) j))%Z *
(power_ 2%Z (((n - i)%Z - 1%Z)%Z + j)%Z))%Z
n))
j n))
0%Z n)
=
(real_to_ang
(infix_asdt
(infix_asdt (i_to_t (-(bv_to_int x))%Z)
(i_to_t (bv_to_int (bv_inversion y))))
(pow_inv_2 n)))).
Axiom int_to_ang_by_sum_mult_break :
forall (n:Z) (x:bitvec) (y:bitvec), (0%Z < n)%Z -> ((length x) = n) ->
((length y) = n) ->
((int_to_ang
(ind_isum
(fun (j:Z) =>
(ind_isum
(fun (i:Z) =>
((((getbv x) i) * ((getbv y) j))%Z *
(power_ 2%Z (((n - i)%Z - 1%Z)%Z + j)%Z))%Z)
j n))
0%Z n)
n)
= (int_to_ang ((bv_to_int x) * (bv_to_int (bv_inversion y)))%Z n)).
Axiom int_to_ang_by_sum_mult_break_gen :
forall (n:Z), (0%Z < n)%Z -> forall (x:bitvec) (y:bitvec),
((length x) = n) -> ((length y) = n) ->
((int_to_ang
(ind_isum
(fun (j:Z) =>
(ind_isum
(fun (i:Z) =>
((((getbv x) i) * ((getbv y) j))%Z *
(power_ 2%Z (((n - i)%Z - 1%Z)%Z + j)%Z))%Z)
j n))
0%Z n)
n)
= (int_to_ang ((bv_to_int x) * (bv_to_int (bv_inversion y)))%Z n)).
Axiom int_to_ang_by_sum_mult_break_gen_mod :
forall (n:Z), (1%Z < n)%Z -> forall (x:bitvec) (y:bitvec),
((length x) = n) -> ((length y) = n) ->
((int_to_ang
(ind_isum
(fun (j:Z) =>
(ind_isum
(fun (i:Z) =>
((((getbv x) i) * ((getbv y) j))%Z *
(power_ 2%Z (((n - i)%Z - 1%Z)%Z + j)%Z))%Z)
j n))
0%Z (n - 1%Z)%Z)
n)
=
(int_to_ang
((bv_to_int x) *
(int.EuclideanDivision.div (bv_to_int (bv_inversion y)) 2%Z))%Z
n)).
Parameter ang_substr: angle -> angle -> angle.
Axiom ang_substr_def :
forall (o:angle) (o':angle), ((ang_substr o o') = (ang_add o (ang_inv o'))).
Axiom ang_substr_inv :
forall (o:angle) (o':angle),
((ang_substr o (ang_mult_int o' (-1%Z)%Z)) = (ang_add o o')).
Axiom ang_mult_int_distr :
forall (o:angle) (o':angle) (n:Z),
((ang_mult_int (ang_add o o') n) =
(ang_add (ang_mult_int o n) (ang_mult_int o' n))).
Axiom ang_mult_int_distr_rev :
forall (o:angle) (o':angle) (n1:Z) (n2:Z),
((ang_add (ang_mult_int o n1) (ang_mult_int o' n2)) =
(ang_mult_int o (n1 + n2)%Z)).
Axiom ang_add_assoc :
forall (o:angle) (o':angle) (o'':angle),
((ang_add o (ang_add o' o'')) = (ang_add (ang_add o o') o'')).
Axiom ang_add_assoc_rev :
forall (o:angle) (o':angle) (o'':angle),
((ang_add (ang_add o o') o'') = (ang_add o (ang_add o' o''))).
Axiom ang_add_own_inv :
forall (o:angle), ((ang_add (ang_mult_int o (-1%Z)%Z) o) = ang_zero).
Parameter concat: bitvec -> bitvec -> bitvec.
Parameter result13: bitvec -> bitvec -> Z -> Z.
Axiom result_def13 :
forall (bv1:bitvec) (bv2:bitvec) (i:Z),
((((length bv1) <= i)%Z /\ (i < ((length bv1) + (length bv2))%Z)%Z) ->
(((result13 bv1 bv2) i) = ((getbv bv2) (i - (length bv1))%Z))) /\
(~ (((length bv1) <= i)%Z /\ (i < ((length bv1) + (length bv2))%Z)%Z) ->
(((result13 bv1 bv2) i) = ((getbv bv1) i))).
Axiom concat_def :
forall (bv1:bitvec) (bv2:bitvec),
((concat bv1 bv2) =
(make_bv (result13 bv1 bv2) ((length bv1) + (length bv2))%Z)).
Axiom concat_spec :
forall (bv1:bitvec) (bv2:bitvec),
((length (concat bv1 bv2)) = ((length bv1) + (length bv2))%Z) /\
((forall (i:Z), ((0%Z <= i)%Z /\ (i < (length bv1))%Z) ->
(((getbv (concat bv1 bv2)) i) = ((getbv bv1) i))) /\
((forall (i:Z), ((length (concat bv1 bv2)) <= i)%Z ->
(((getbv (concat bv1 bv2)) i) = ((getbv bv1) i))) /\
forall (i:Z),
(((length bv1) <= i)%Z /\ (i < (length (concat bv1 bv2)))%Z) ->
(((getbv (concat bv1 bv2)) i) = ((getbv bv2) (i - (length bv1))%Z)))).
Axiom concat_length :
forall (bv1:bitvec) (bv2:bitvec),
((length (concat bv1 bv2)) = ((length bv1) + (length bv2))%Z).
Parameter hpart: bitvec -> Z -> bitvec.
Axiom hpart_def :
forall (bv:bitvec) (m:Z), (0%Z <= m)%Z ->
((hpart bv m) = (make_bv (getbv bv) m)).
Axiom hpart_spec :
forall (bv:bitvec) (m:Z), (0%Z <= m)%Z ->
((length (hpart bv m)) = m) /\
((((length bv) = m) -> ((hpart bv m) = bv)) /\
((forall (k:Z), ((0%Z <= k)%Z /\ (k < m)%Z) ->
(((getbv (hpart bv m)) k) = ((getbv bv) k))) /\
forall (k:Z), ~ ((0%Z <= k)%Z /\ (k < m)%Z) ->
(((getbv (hpart bv m)) k) = 0%Z))).
Axiom hpart_value :
forall (bv:bitvec) (m:Z) (i:Z), (0%Z <= m)%Z ->
(((0%Z <= i)%Z /\ (i < m)%Z) ->
(((getbv (hpart bv m)) i) = ((getbv bv) i))) /\
(~ ((0%Z <= i)%Z /\ (i < m)%Z) -> (((getbv (hpart bv m)) i) = 0%Z)).
Axiom hpart_value_b :
forall (bv:bitvec) (m:Z) (i:Z), ((0%Z <= i)%Z /\ (i < m)%Z) ->
(((getbv (hpart bv m)) i) = ((getbv bv) i)).
Parameter tpart: bitvec -> Z -> bitvec.
Axiom tpart_def :
forall (bv:bitvec) (m:Z), (0%Z <= m)%Z ->
(((length bv) >= m)%Z ->
((tpart bv m) =
(make_bv (fun (k:Z) => ((getbv bv) (k + m)%Z)) ((length bv) - m)%Z))) /\
(~ ((length bv) >= m)%Z ->
((tpart bv m) = (make_bv (fun (k:Z) => ((getbv bv) (k + m)%Z)) 0%Z))).
Axiom tpart_spec :
forall (bv:bitvec) (m:Z), (0%Z <= m)%Z ->
(((length bv) >= m)%Z -> ((length (tpart bv m)) = ((length bv) - m)%Z)) /\
((((length bv) < m)%Z -> ((length (tpart bv m)) = 0%Z)) /\
forall (k:Z), ((0%Z <= k)%Z /\ (k < (length (tpart bv m)))%Z) ->
(((getbv (tpart bv m)) k) = ((getbv bv) (k + m)%Z))).
Parameter bv_tail: bitvec -> Z -> bitvec.
Axiom bv_tail_def :
forall (bv:bitvec) (m:Z), ((0%Z <= m)%Z /\ (m <= ((length bv) - m)%Z)%Z) ->
((bv_tail bv m) = (tpart bv ((length bv) - m)%Z)).
Axiom bv_tail_spec :
forall (bv:bitvec) (m:Z), ((0%Z <= m)%Z /\ (m <= ((length bv) - m)%Z)%Z) ->
((length (bv_tail bv m)) = m) /\
forall (k:Z), ((0%Z <= k)%Z /\ (k < (length (bv_tail bv m)))%Z) ->
(((getbv (bv_tail bv m)) k) = ((getbv bv) (k + ((length bv) - m)%Z)%Z)).
Parameter last: bitvec -> Z.
Axiom last_def :
forall (bv:bitvec), ((length bv) >= 1%Z)%Z ->
((last bv) = ((getbv bv) ((length bv) - 1%Z)%Z)).
Parameter bv_head: bitvec -> Z -> bitvec.
Axiom bv_head_def :
forall (bv:bitvec) (m:Z), ((0%Z <= m)%Z /\ (m <= (length bv))%Z) ->
((bv_head bv m) = (hpart bv ((length bv) - m)%Z)).
Axiom bv_head_spec :
forall (bv:bitvec) (m:Z), ((0%Z <= m)%Z /\ (m <= (length bv))%Z) ->
((length (bv_head bv m)) = ((length bv) - m)%Z) /\
forall (k:Z), ((0%Z <= k)%Z /\ (k < (length (bv_head bv m)))%Z) ->
(((getbv (bv_head bv m)) k) = ((getbv bv) k)).
Parameter htpart: bitvec -> Z -> Z -> bitvec.
Axiom htpart_def :
forall (bv:bitvec) (k:Z) (n:Z), (0%Z <= k)%Z -> (0%Z <= n)%Z ->
((htpart bv k n) = (make_bv (fun (i:Z) => ((getbv bv) (k + i)%Z)) n)).
Axiom htpart_spec :
forall (bv:bitvec) (k:Z) (n:Z), (0%Z <= k)%Z -> (0%Z <= n)%Z ->
((length (htpart bv k n)) = n) /\
forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) ->
(((getbv (htpart bv k n)) i) = ((getbv bv) (k + i)%Z)).
Axiom tpart_value :
forall (bv:bitvec) (m:Z) (i:Z), (0%Z <= m)%Z ->
(((0%Z <= i)%Z /\ (i < ((length bv) - m)%Z)%Z) ->
(((getbv (tpart bv m)) i) = ((getbv bv) (i + m)%Z))) /\
(~ ((0%Z <= i)%Z /\ (i < ((length bv) - m)%Z)%Z) ->
(((getbv (tpart bv m)) i) = 0%Z)).
Axiom tpart_value_b :
forall (bv:bitvec) (m:Z) (i:Z), (0%Z <= m)%Z ->
((0%Z <= i)%Z /\ (i < ((length bv) - m)%Z)%Z) ->
(((getbv (tpart bv m)) i) = ((getbv bv) (i + m)%Z)).
Axiom tpart_length :
forall (bv:bitvec) (m:Z), ((0%Z <= m)%Z /\ (m <= (length bv))%Z) ->
((length (tpart bv m)) = ((length bv) - m)%Z).
Axiom htpart_value :
forall (bv:bitvec) (k:Z) (n:Z) (i:Z), (0%Z <= k)%Z -> (0%Z <= n)%Z ->
(((0%Z <= i)%Z /\ (i < n)%Z) ->
(((getbv (htpart bv k n)) i) = ((getbv bv) (k + i)%Z))) /\
(~ ((0%Z <= i)%Z /\ (i < n)%Z) -> (((getbv (htpart bv k n)) i) = 0%Z)).
Axiom htpart_value_b :
forall (bv:bitvec) (k:Z) (n:Z) (i:Z), (0%Z <= k)%Z -> (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < n)%Z) ->
(((getbv (htpart bv k n)) i) = ((getbv bv) (k + i)%Z)).
Axiom htpart_product_ :
forall (x:bitvec) (k:Z) (n:Z) (n':Z), ((0%Z <= k)%Z /\ (k < n)%Z) ->
(n' = (n - k)%Z) ->
((ind_iproduct (getbv (htpart x k n')) 0%Z (n - k)%Z) =
(ind_iproduct (getbv x) k n)).
Axiom htpart_product_one :
forall (x:bitvec) (k:Z) (n:Z) (n':Z), ((0%Z <= k)%Z /\ (k < n)%Z) ->
((length x) = n) -> (n' = (n - k)%Z) ->
((ind_iproduct (getbv x) 0%Z n) = 1%Z) ->
((ind_iproduct (getbv (htpart x k n')) 0%Z (n - k)%Z) = 1%Z).
Axiom htpart_product_zero :
forall (x:bitvec) (k:Z) (n:Z) (n':Z), ((0%Z <= k)%Z /\ (k < n)%Z) ->
((length x) = n) -> (n' = (n - k)%Z) ->
(exists j:Z, ((k <= j)%Z /\ (j < n)%Z) /\ ~ (((getbv x) j) = 1%Z)) ->
((ind_iproduct (getbv (htpart x k n')) 0%Z (n - k)%Z) = 0%Z).
Axiom htpart_product :
forall (x:bitvec) (k:Z) (n:Z) (n':Z), ((0%Z <= k)%Z /\ (k < n)%Z) ->
((length x) = n) -> (n' = (n - k)%Z) ->
((forall (j:Z), ((k <= j)%Z /\ (j < n)%Z) -> (((getbv x) j) = 1%Z)) ->
((ind_iproduct (getbv (htpart x k n')) 0%Z (n - k)%Z) = 1%Z)) /\
(~ (forall (j:Z), ((k <= j)%Z /\ (j < n)%Z) -> (((getbv x) j) = 1%Z)) ->
((ind_iproduct (getbv (htpart x k n')) 0%Z (n - k)%Z) = 0%Z)).
Axiom htpart_length :
forall (bv:bitvec) (k:Z) (n:Z), (0%Z <= k)%Z -> (0%Z <= n)%Z ->
((length (htpart bv k n)) = n).
Axiom tpart_length_gen :
forall (bv:bitvec) (m:Z) (l:Z), ((0%Z <= m)%Z /\ (m <= (length bv))%Z) ->
(l = ((length bv) - m)%Z) -> ((length (tpart bv m)) = l).
Axiom concat_value_left :
forall (bv1:bitvec) (bv2:bitvec) (i:Z),
((0%Z <= i)%Z /\ (i < (length bv1))%Z) ->
(((getbv (concat bv1 bv2)) i) = ((getbv bv1) i)).
Axiom concat_value :
forall (bv1:bitvec) (bv2:bitvec) (i:Z),
((((length bv1) <= i)%Z /\ (i < ((length bv1) + (length bv2))%Z)%Z) ->
(((getbv (concat bv1 bv2)) i) = ((getbv bv2) (i - (length bv1))%Z))) /\
(~ (((length bv1) <= i)%Z /\ (i < ((length bv1) + (length bv2))%Z)%Z) ->
(((0%Z <= i)%Z /\ (i < (length bv1))%Z) ->
(((getbv (concat bv1 bv2)) i) = ((getbv bv1) i))) /\
(~ ((0%Z <= i)%Z /\ (i < (length bv1))%Z) ->
(((getbv (concat bv1 bv2)) i) = 0%Z))).
Axiom concat_value_right :
forall (bv1:bitvec) (bv2:bitvec) (i:Z),
(((length bv1) <= i)%Z /\ (i < ((length bv1) + (length bv2))%Z)%Z) ->
(((getbv (concat bv1 bv2)) i) = ((getbv bv2) (i - (length bv1))%Z)).
Axiom concat_value_out :
forall (bv1:bitvec) (bv2:bitvec) (i:Z),
(((length bv1) + (length bv2))%Z < i)%Z ->
(((getbv (concat bv1 bv2)) i) = ((getbv bv1) i)).
Axiom concat_value_tpart :
forall (bv1:bitvec) (bv2:bitvec) (i:Z),
(((length bv1) <= i)%Z /\ (i < (length bv2))%Z) ->
(((getbv (concat bv1 (tpart bv2 (length bv1)))) i) = ((getbv bv2) i)).
Axiom concat_value_ht :
forall (bv1:bitvec) (bv2:bitvec) (bv3:bitvec) (bv4:bitvec) (i:Z),
((0%Z <= i)%Z /\ (i < (length bv3))%Z) ->
(((0%Z <= i)%Z /\ (i < (length bv1))%Z) ->
(((getbv bv1) i) = ((getbv bv4) i))) ->
(((length bv1) <= i)%Z -> (((getbv bv3) i) = ((getbv bv4) i))) ->
(bv2 = (tpart bv3 (length bv1))) ->
(((getbv (concat bv1 bv2)) i) = ((getbv bv4) i)).
Axiom concat_ht1 :
forall (bv1:bitvec) (bv2:bitvec) (bv3:bitvec) (bv4:bitvec),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (length bv1))%Z) ->
(((getbv bv1) i) = ((getbv bv4) i))) ->
(forall (i:Z), ((length bv1) <= i)%Z ->
(((getbv bv3) i) = ((getbv bv4) i))) ->
((length bv4) = ((length bv1) + (length bv2))%Z) ->
((length bv3) >= ((length bv1) + (length bv2))%Z)%Z ->
(bv2 = (tpart bv3 (length bv1))) -> ((concat bv1 bv2) = bv4).
Axiom set_concat :
forall (bv1:bitvec) (bv2:bitvec) (bv4:bitvec),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (length bv1))%Z) ->
(((getbv bv1) i) = ((getbv bv4) i))) ->
(forall (i:Z), ((length bv1) <= i)%Z ->
(((getbv bv2) (i - (length bv1))%Z) = ((getbv bv4) i))) ->
((length bv4) = ((length bv1) + (length bv2))%Z) ->
((concat bv1 bv2) = bv4).
Axiom concat_m :
forall (bv1:bitvec) (bv2:bitvec) (i1:Z) (i2:Z), (i1 > 0%Z)%Z ->
(i2 > 0%Z)%Z -> ((length bv1) = i1) -> ((length bv2) = i2) ->
((concat (make_bv_m (getbv bv1) i1) (make_bv_m (getbv bv2) i2)) =
(make_bv_m (getbv (concat bv1 bv2)) (i1 + i2)%Z)).
Axiom concat_comm :
forall (bv1:bitvec) (bv2:bitvec),
((hpart (concat bv1 bv2) (length bv1)) = bv1) /\
((tpart (concat bv1 bv2) (length bv1)) = bv2).
Axiom concat_and_rec :
forall (bv:bitvec) (i:Z), ((0%Z <= i)%Z /\ (i <= (length bv))%Z) ->
((concat (hpart bv i) (tpart bv i)) = bv).
Parameter concat_int_bv: bitvec -> Z -> Z -> bitvec.
Axiom concat_int_bv_def :
forall (bv:bitvec) (i:Z) (n:Z), (n > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((concat_int_bv bv i n) = (concat bv (int_to_bv i n))).
Axiom concat_int_to_bv_value :
forall (bv:bitvec) (i:Z) (n:Z) (j:Z), (n > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (length (concat_int_bv bv i n)))%Z) ->
(j < (length bv))%Z ->
(((getbv (concat_int_bv bv i n)) j) = ((getbv bv) j)).
Axiom bv_to_int_concat :
forall (bvx:bitvec) (bvy:bitvec),
((bv_to_int (concat bvx bvy)) =
(((power 2%Z (length bvy)) * (bv_to_int bvx))%Z + (bv_to_int bvy))%Z).
Axiom concat_fin :
forall (f1:Z -> Z) (f2:Z -> Z) (l1:Z) (l2:Z), (l1 >= 0%Z)%Z ->
(l2 >= 0%Z)%Z -> (binary f1) -> (binary f2) ->
((make_bv
((((fun (y0:Z -> Z) (y1:Z -> Z) (y2:Z) (y3:Z) =>
(concat_fun y0 y1 y2 y3))
f1)
f2)
l1)
(l1 + l2)%Z)
= (concat (make_bv f1 l1) (make_bv f2 l2))).
Axiom bin_to_int_concat :
forall (f1:Z -> Z) (f2:Z -> Z) (l1:Z) (l2:Z), (l1 >= 0%Z)%Z ->
(l2 >= 0%Z)%Z -> (binary f1) -> (binary f2) ->
((bin_to_int
((((fun (y0:Z -> Z) (y1:Z -> Z) (y2:Z) (y3:Z) =>
(concat_fun y0 y1 y2 y3))
f1)
f2)
l1)
(l1 + l2)%Z)
= (((power 2%Z l2) * (bin_to_int f1 l1))%Z + (bin_to_int f2 l2))%Z).
Axiom bijective_concat :
forall (i:Z) (j:Z), (0%Z <= i)%Z -> (0%Z <= j)%Z ->
(p_bijective (fun (o:(bitvec* bitvec)%type) => (concat (fir o) (sec o)))
(cartesian_product (n_bvs i) (n_bvs j)) (n_bvs (i + j)%Z)) /\
(p_bijective (fun (x:bitvec) => (hpart x i, tpart x i)) (n_bvs (i + j)%Z)
(cartesian_product (n_bvs i) (n_bvs j))).
Axiom bv_to_int_hpart :
forall (bv:bitvec) (l:Z), ((0%Z <= l)%Z /\ (l <= (length bv))%Z) ->
((bv_to_int (hpart bv l)) =
(int.EuclideanDivision.div (bv_to_int bv) (power 2%Z ((length bv) - l)%Z))).
Axiom bv_to_int_tpart :
forall (bv:bitvec) (l:Z), ((0%Z <= l)%Z /\ (l <= (length bv))%Z) ->
((bv_to_int (tpart bv l)) =
(int.EuclideanDivision.mod1 (bv_to_int bv)
(power 2%Z ((length bv) - l)%Z))).
Parameter iter_concat:
forall {xi:Type} {xi_WT:WhyType xi} {xi1:Type} {xi1_WT:WhyType xi1},
(xi -> xi -> xi) -> (Z -> bitvec) -> (set xi1) -> (xi1 -> xi) -> xi.
Axiom iter_concat_def :
forall {xi:Type} {xi_WT:WhyType xi} {xi1:Type} {xi1_WT:WhyType xi1},
forall (concat1:xi -> xi -> xi) (f:Z -> bitvec) (i:set xi1) (j:xi1 -> xi),
((iter_concat concat1 f i j) = (iterate concat1 i j)).
Parameter is_a_ket: (matrix t) -> Prop.
Axiom Is_a_ket :
forall (m:matrix t),
(is_a_ket m) <->
(((columns m) = 1%Z) /\
exists s:Z, (s >= 0%Z)%Z /\ ((rows m) = (power 2%Z s))).
Parameter xor_i: Z -> Z -> Z.
Axiom xor_i_def :
forall (i:Z) (i':Z), ((0%Z <= i)%Z /\ (i < 2%Z)%Z) ->
((0%Z <= i')%Z /\ (i' < 2%Z)%Z) ->
((i = 0%Z) -> ((xor_i i i') = i')) /\
(~ (i = 0%Z) -> ((xor_i i i') = (1%Z - i')%Z)).
Axiom xor_i_spec :
forall (i:Z) (i':Z), ((0%Z <= i)%Z /\ (i < 2%Z)%Z) ->
((0%Z <= i')%Z /\ (i' < 2%Z)%Z) ->
((i = 0%Z) -> (i' = 0%Z) -> ((xor_i i i') = 0%Z)) /\
(((i = 0%Z) -> (i' = 1%Z) -> ((xor_i i i') = 1%Z)) /\
(((i = 1%Z) -> (i' = 0%Z) -> ((xor_i i i') = 1%Z)) /\
((i = 1%Z) -> (i' = 1%Z) -> ((xor_i i i') = 0%Z)))).
Parameter is_a_ket_l: (matrix t) -> Z -> Prop.
Axiom is_a_ket_l_def :
forall (m:matrix t) (l:Z),
(is_a_ket_l m l) <->
((l >= 0%Z)%Z /\ (((columns m) = 1%Z) /\ ((rows m) = (power 2%Z l)))).
Axiom ket_l_rows :
forall (m:matrix t) (l:Z), (is_a_ket_l m l) -> ((rows m) = (power 2%Z l)).
Axiom ket_l_columns :
forall (m:matrix t), (exists l:Z, is_a_ket_l m l) -> ((columns m) = 1%Z).
Parameter ket_valid_index: (matrix t) -> Z -> Prop.
Axiom ket_valid_index_def :
forall (m:matrix t) (i:Z), (ket_valid_index m i) <-> (valid_index m i 0%Z).
Parameter ket_length: (matrix t) -> Z.
Axiom ket_length_def :
forall (m:matrix t), (is_a_ket m) ->
((ket_length m) = ((binary_length (rows m)) - 1%Z)%Z).
Axiom ket_length_spec :
forall (m:matrix t), (is_a_ket m) ->
(0%Z <= (ket_length m))%Z /\ ((rows m) = (power 2%Z (ket_length m))).
Parameter get_ket: (matrix t) -> Z -> t.
Axiom get_ket_def :
forall (m:matrix t) (i:Z), ((get_ket m i) = (get m i 0%Z)).
Parameter get_ket_bv: (matrix t) -> bitvec -> t.
Axiom get_ket_bv_def :
forall (x:matrix t) (bv:bitvec), (is_a_ket_l x (length bv)) ->
((get_ket_bv x bv) = (get_ket x (bv_to_int bv))).
Axiom assert_make_ket :
forall (r:Z) (c:Z) (f:Z -> Z -> t) (i:Z), (c = 1%Z) ->
((0%Z <= i)%Z /\ (i < r)%Z) -> ((get_ket (make_f r c f) i) = ((f i) 0%Z)).
Axiom mat_mult_ket_l :
forall (m:matrix t) (k:matrix t) (n:Z), (is_a_ket_l k n) ->
((rows m) = (power 2%Z n)) -> ((columns m) = (power 2%Z n)) ->
is_a_ket_l (mat_mult m k) n.
Axiom ket_kronecker_values :
forall (m:matrix t) (n:matrix t) (i:Z), (is_a_ket m) -> (is_a_ket n) ->
((0%Z <= i)%Z /\ (i < ((rows m) * (rows n))%Z)%Z) ->
((get_ket (kronecker m n) i) =
(infix_asdt (get_ket m (int.EuclideanDivision.div i (rows n)))
(get_ket n (int.EuclideanDivision.mod1 i (rows n))))).
Axiom ket_l_to_ket :
forall (m:matrix t) (l:Z), (is_a_ket_l m l) ->
(is_a_ket m) /\ ((ket_length m) = l).
Axiom ket_l_to_ket_gen :
forall (m:matrix t), (exists l:Z, is_a_ket_l m l) -> is_a_ket m.
Axiom ket_to_ket_l :
forall (m:matrix t), (is_a_ket m) -> is_a_ket_l m (ket_length m).
Axiom set_ket_valid_index :
forall (m:matrix t) (i:Z), (is_a_ket m) ->
((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) -> ket_valid_index m i.
Axiom ket_to_ket_l_l :
forall (m:matrix t) (i:Z), (is_a_ket m) -> ((ket_length m) = i) ->
is_a_ket_l m i.
Axiom set_constant_size_ket :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t),
(forall (e1:a), (mem e1 s) -> is_a_ket (f e1)) ->
(forall (e1:a) (e':a), (mem e1 s) -> (mem e' s) ->
((ket_length (f e1)) = (ket_length (f e')))) ->
constant_size s f.
Parameter ket_norm_l: (matrix t) -> Z -> t.
Axiom ket_norm_l_def :
forall (x:matrix t) (n:Z), (is_a_ket_l x n) ->
((ket_norm_l x n) =
(square_rt
(sum (to_fset 0%Z (power 2%Z n))
(fun (k:Z) =>
(infix_asdt (modulus (get x k 0%Z)) (modulus (get x k 0%Z))))))).
Axiom ind_sum_ket_norm_l :
forall (x:matrix t) (n:Z), (is_a_ket_l x n) ->
((ket_norm_l x n) =
(square_rt
(ind_sum
(fun (k:Z) =>
(infix_asdt (modulus (get x k 0%Z)) (modulus (get x k 0%Z))))
0%Z (power 2%Z n)))).
Axiom ket_norm_one :
forall (x:matrix t) (n:Z), (n = 1%Z) -> (is_a_ket_l x n) ->
((ket_norm_l x n) =
(square_rt
(infix_pldt
(infix_asdt (modulus (get x 0%Z 0%Z)) (modulus (get x 0%Z 0%Z)))
(infix_asdt (modulus (get x 1%Z 0%Z)) (modulus (get x 1%Z 0%Z)))))).
Axiom ket_norm_one_tone :
forall (x:matrix t) (n:Z), (n = 1%Z) -> (is_a_ket_l x n) ->
((infix_pldt
(infix_asdt (modulus (get x 0%Z 0%Z)) (modulus (get x 0%Z 0%Z)))
(infix_asdt (modulus (get x 1%Z 0%Z)) (modulus (get x 1%Z 0%Z))))
= tone) ->
((ket_norm_l x n) = tone).
Axiom scalar_ket_norm_l :
forall (x:matrix t) (a:t) (n:Z), (is_a_ket_l x n) ->
((ket_norm_l (infix_asdtdt a x) n) = (infix_asdt a (ket_norm_l x n))).
Axiom zero_ket_norm_l :
forall (x:matrix t) (n:Z), (is_a_ket_l x n) ->
((ket_norm_l x n) = tzero) -> forall (i:Z) (j:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> (j = 0%Z) ->
((get x i j) = tzero).
Parameter normalized_l: (matrix t) -> Z -> matrix t.
Axiom normalized_l_def :
forall (x:matrix t) (n:Z), (is_a_ket_l x n) ->
((normalized_l x n) = (infix_asdtdt (infix_sldt tone (ket_norm_l x n)) x)).
Axiom normalized_l_spec :
forall (x:matrix t) (n:Z), (is_a_ket_l x n) ->
is_a_ket_l (normalized_l x n) n.
Parameter add_ket: (matrix t) -> (matrix t) -> matrix t.
Axiom add_ket_def :
forall (m:matrix t) (n:matrix t), (is_a_ket m) -> (is_a_ket n) ->
((ket_length m) = (ket_length n)) -> ((add_ket m n) = (add_mat m n)).
Axiom add_ket_spec :
forall (m:matrix t) (n:matrix t), (is_a_ket m) -> (is_a_ket n) ->
((ket_length m) = (ket_length n)) ->
(is_a_ket (add_ket m n)) /\
(((ket_length (add_ket m n)) = (ket_length m)) /\
forall (i:Z), (ket_valid_index (add_ket m n) i) ->
((get_ket (add_ket m n) i) = (infix_pldt (get_ket m i) (get_ket n i)))).
Parameter add_ket_l: (matrix t) -> (matrix t) -> Z -> matrix t.
Axiom add_ket_l_def :
forall (m:matrix t) (n:matrix t) (l:Z), (is_a_ket_l m l) ->
(is_a_ket_l n l) -> ((add_ket_l m n l) = (add_ket m n)).
Axiom add_ket_l_spec :
forall (m:matrix t) (n:matrix t) (l:Z), (is_a_ket_l m l) ->
(is_a_ket_l n l) ->
(is_a_ket_l (add_ket_l m n l) l) /\
(((ket_length (add_ket_l m n l)) = l) /\
forall (i:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length (add_ket_l m n l))))%Z) ->
((get_ket (add_ket_l m n l) i) = (infix_pldt (get_ket m i) (get_ket n i)))).
Parameter add_ket_l_eq:
(matrix t) -> (matrix t) -> (matrix t) -> (matrix t) -> Z -> unit.
Axiom add_ket_l_eq_def :
forall (m:matrix t) (m':matrix t) (n:matrix t) (n':matrix t) (l:Z),
(is_a_ket_l m l) -> (is_a_ket_l n l) -> (m = m') -> (n = n') ->
((add_ket_l_eq m m' n n' l) = tt).
Axiom add_ket_l_eq_spec :
forall (m:matrix t) (m':matrix t) (n:matrix t) (n':matrix t) (l:Z),
(is_a_ket_l m l) -> (is_a_ket_l n l) -> (m = m') -> (n = n') ->
((((fun (y0:matrix t) (y1:matrix t) (y2:Z) => (add_ket_l y0 y1 y2)) m) n) =
(((fun (y0:matrix t) (y1:matrix t) (y2:Z) => (add_ket_l y0 y1 y2)) m') n')).
Axiom add_ket_l_value :
forall (m:matrix t) (n:matrix t) (l:Z) (i:Z), (is_a_ket_l m l) ->
(is_a_ket_l n l) -> ((0%Z <= i)%Z /\ (i < (power 2%Z l))%Z) ->
((get_ket (add_ket_l m n l) i) = (infix_pldt (get_ket m i) (get_ket n i))).
Axiom set_equal_ket :
forall (m:matrix t) (n:matrix t), (is_a_ket m) -> (is_a_ket n) ->
((ket_length m) = (ket_length n)) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) ->
((get_ket m i) = (get_ket n i))) ->
(m = n).
Axiom set_equal_ket_l :
forall (m:matrix t) (n:matrix t),
(exists l:Z, (is_a_ket_l m l) /\ (is_a_ket_l n l)) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) ->
((get_ket m i) = (get_ket n i))) ->
(m = n).
Axiom get_ket_length :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z -> (is_a_ket m) ->
((rows m) = (power 2%Z n)) -> ((ket_length m) = n).
Axiom set_ket_length :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z -> (is_a_ket m) ->
((ket_length m) = n) -> ((rows m) = (power 2%Z n)).
Axiom scalar_ket :
forall (x:matrix t) (a:t), (is_a_ket x) -> is_a_ket (infix_asdtdt a x).
Axiom scalar_ket_length :
forall (m:matrix t) (a:t), (is_a_ket m) ->
((ket_length (infix_asdtdt a m)) = (ket_length m)).
Axiom scalar_ket_valid_index :
forall (m:matrix t) (a:t) (i:Z), (ket_valid_index m i) -> (is_a_ket m) ->
ket_valid_index (infix_asdtdt a m) i.
Axiom scalar_ket_l :
forall (x:matrix t) (l:Z) (a:t), (is_a_ket_l x l) ->
is_a_ket_l (infix_asdtdt a x) l.
Axiom scalar_ket_value :
forall (x:matrix t) (i:Z) (a:t), (is_a_ket x) -> (ket_valid_index x i) ->
((get_ket (infix_asdtdt a x) i) = (infix_asdt a (get_ket x i))).
Axiom scalar_ket_value_rev :
forall (x:matrix t) (i:Z) (a:t), (is_a_ket x) -> (ket_valid_index x i) ->
((infix_asdt a (get_ket x i)) = (get_ket (infix_asdtdt a x) i)).
Axiom add_ket_is_a_ket :
forall (x:matrix t) (y:matrix t), (is_a_ket x) -> (is_a_ket y) ->
((ket_length x) = (ket_length y)) -> is_a_ket (add_mat x y).
Axiom set_ket_length_gen :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z -> (is_a_ket m) ->
((power 2%Z (ket_length m)) = n) -> ((rows m) = n).
Axiom set_is_a_ket :
forall (m:matrix t), ((columns m) = 1%Z) ->
(exists s:Z, (s >= 0%Z)%Z /\ ((rows m) = (power 2%Z s))) -> is_a_ket m.
Axiom set_is_a_ket_l :
forall (m:matrix t) (l:Z), (l >= 0%Z)%Z -> ((columns m) = 1%Z) ->
((rows m) = (power 2%Z l)) -> is_a_ket_l m l.
Axiom set_is_a_ket_p :
forall (m:matrix t) (l:Z), (l >= 0%Z)%Z -> ((columns m) = 1%Z) ->
((rows m) = (power 2%Z l)) -> is_a_ket m.
Axiom get_is_a_ket :
forall (m:matrix t), (is_a_ket m) ->
((columns m) = 1%Z) /\ ((rows m) = (power 2%Z (ket_length m))).
Axiom get_ket_columns :
forall (m:matrix t), (is_a_ket m) -> ((columns m) = 1%Z).
Axiom get_ket_rows :
forall (m:matrix t), (is_a_ket m) ->
((rows m) = (power 2%Z (ket_length m))).
Axiom get_ket_rows_gen :
forall (m:matrix t) (i:Z), (is_a_ket m) ->
(i = (power 2%Z (ket_length m))) -> ((rows m) = i).
Axiom get_ket_rows_length :
forall (m:matrix t) (l:Z), (is_a_ket m) -> ((ket_length m) = l) ->
((rows m) = (power 2%Z l)).
Axiom ket_kronecker :
forall (m:matrix t) (n:matrix t), (is_a_ket m) -> (is_a_ket n) ->
(is_a_ket (kronecker m n)) /\
((ket_length (kronecker m n)) = ((ket_length m) + (ket_length n))%Z).
Axiom ket_kronecker_l :
forall (m:matrix t) (n:matrix t) (l:Z) (l':Z), (is_a_ket_l m l) ->
(is_a_ket_l n l') -> is_a_ket_l (kronecker m n) (l + l')%Z.
Axiom set_ket_kron_l :
forall (m:matrix t) (n:matrix t) (l:Z) (l':Z) (l'':Z), (is_a_ket_l m l) ->
(is_a_ket_l n l') -> (l'' = (l + l')%Z) -> is_a_ket_l (kronecker m n) l''.
Parameter ket: Z -> Z -> matrix t.
Axiom ket_def :
forall (n:Z) (i:Z), (0%Z <= n)%Z ->
(((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((ket n i) = (set1 (make (power 2%Z n) 1%Z tzero) i 0%Z tone))) /\
(~ ((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((ket n i) = (make (power 2%Z n) 1%Z tzero))).
Axiom ket_spec :
forall (n:Z) (i:Z), (0%Z <= n)%Z ->
(is_a_ket (ket n i)) /\
(((ket_length (ket n i)) = n) /\
(((columns (ket n i)) = 1%Z) /\
(((rows (ket n i)) = (power 2%Z n)) /\
((((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> forall (j:Z),
(valid_index (ket n i) j 0%Z) ->
((get (ket n i) j 0%Z) = (indic j i))) /\
((forall (j:Z), (valid_index (ket n i) j 0%Z) -> ~ (i = j) ->
((get (ket n i) j 0%Z) = tzero)) /\
(((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((get (ket n i) i 0%Z) = tone))))))).
Parameter scal_ket_zero: matrix t.
Axiom scal_ket_zero_def : (scal_ket_zero = (ket 0%Z 0%Z)).
Parameter scal_ket_one: matrix t.
Axiom scal_ket_one_def : (scal_ket_one = (ket 0%Z 1%Z)).
Parameter make_ket: Z -> (Z -> t) -> matrix t.
Axiom make_ket_def :
forall (n:Z) (f:Z -> t), (n >= 0%Z)%Z ->
((make_ket n f) = (make_f (power 2%Z n) 1%Z (fun (x:Z) (us:Z) => (f x)))).
Axiom make_ket_spec :
forall (n:Z) (f:Z -> t), (n >= 0%Z)%Z ->
(is_a_ket_l (make_ket n f) n) /\
((forall (i:Z), ((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((get_ket (make_ket n f) i) = (f i))) /\
forall (i:Z) (j:Z), (valid_index (make_ket n f) i j) ->
((get (make_ket n f) i j) = (f i))).
Axiom ket_l :
forall (n:Z) (m:Z) (i:Z), (0%Z <= n)%Z -> (n = m) -> is_a_ket_l (ket n i) m.
Axiom ket_ket_length :
forall (n:Z) (m:Z) (i:Z), (0%Z <= n)%Z -> (n = m) ->
((ket_length (ket n i)) = m).
Axiom ket_length_explicit :
forall (n:Z) (i:Z), (0%Z <= n)%Z -> ((ket_length (ket n i)) = n).
Axiom ket_eq :
forall (n1:Z) (n2:Z) (i1:Z) (i2:Z), (0%Z <= n1)%Z -> (n1 = n2) ->
(i1 = i2) -> ((ket n1 i1) = (ket n2 i2)).
Axiom ket_rows :
forall (n:Z) (i:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((rows (ket n i)) = (power 2%Z n)).
Axiom ket_columns :
forall (n:Z) (i:Z), (0%Z <= n)%Z -> ((columns (ket n i)) = 1%Z).
Axiom ket_value :
forall (n:Z) (i:Z) (j:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((i = j) -> ((get (ket n i) j 0%Z) = tone)) /\
(~ (i = j) -> ((get (ket n i) j 0%Z) = tzero)).
Axiom norm_ket_basis :
forall (n:Z) (i:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((ket_norm_l (ket n i) n) = tone).
Axiom get_ket_ :
forall (m:matrix t) (i:Z) (n:Z), (m = (ket n i)) -> (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
(is_a_ket m) /\
(((ket_length m) = n) /\
(((columns m) = 1%Z) /\
(((rows m) = (power 2%Z n)) /\
((forall (j:Z), (valid_index m j 0%Z) -> ((get m j 0%Z) = (indic j i))) /\
((forall (j:Z), (valid_index m j 0%Z) -> ~ (i = j) ->
((get m j 0%Z) = tzero)) /\
((get m i 0%Z) = tone)))))).
Axiom get_ket_value :
forall (i:Z) (n:Z) (j:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((get (ket n i) j 0%Z) = (indic j i)).
Axiom get_ket_values :
forall (i:Z) (n:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> forall (j:Z),
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((get (ket n i) j 0%Z) = (indic j i)).
Axiom get_ket_value_z :
forall (i:Z) (n:Z) (j:Z) (z:Z), (z = 0%Z) -> (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((get (ket n i) j z) = (indic j i)).
Axiom get__ket_value :
forall (i:Z) (j:Z) (n:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((get_ket (ket n i) j) = (indic j i)).
Axiom set_ket :
forall (m:matrix t) (i:Z) (n:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> ((columns m) = 1%Z) ->
((rows m) = (power 2%Z n)) ->
(forall (j:Z), (valid_index m j 0%Z) -> ((get m j 0%Z) = (indic j i))) ->
(m = (ket n i)).
Axiom kronecker_kets :
forall (i1:Z) (i2:Z) (n1:Z) (n2:Z), (0%Z <= n1)%Z -> (0%Z <= n2)%Z ->
((0%Z <= i1)%Z /\ (i1 < (power 2%Z n1))%Z) ->
((0%Z <= i2)%Z /\ (i2 < (power 2%Z n2))%Z) ->
((kronecker (ket n1 i1) (ket n2 i2)) =
(ket (n1 + n2)%Z ((i1 * (power 2%Z n2))%Z + i2)%Z)).
Axiom kronecker_ket_l :
forall (x:matrix t) (y:matrix t) (n1:Z) (n2:Z), (0%Z <= n1)%Z ->
(0%Z <= n2)%Z -> (is_a_ket_l x n1) -> (is_a_ket_l y n2) ->
is_a_ket_l (kronecker x y) (n1 + n2)%Z.
Axiom kronecker_kets_bin_to_int :
forall (f1:Z -> Z) (f2:Z -> Z) (n1:Z) (n2:Z), (binary f1) -> (binary f2) ->
(0%Z <= n1)%Z -> (0%Z <= n2)%Z ->
((kronecker (ket n1 (bin_to_int f1 n1)) (ket n2 (bin_to_int f2 n2))) =
(ket (n1 + n2)%Z
(((bin_to_int f1 n1) * (power 2%Z n2))%Z + (bin_to_int f2 n2))%Z)).
Parameter ind_basis_mat: Z -> Z -> Z -> Z -> matrix t.
Axiom ind_basis_mat_def :
forall (i:Z) (j:Z) (r:Z) (c:Z), ((0%Z <= i)%Z /\ (i < r)%Z) ->
((0%Z <= j)%Z /\ (j < c)%Z) ->
((ind_basis_mat i j r c) =
(make_f r c (fun (k:Z) (l:Z) => (indic_2 k i l j)))).
Axiom ind_basis_mat_spec :
forall (i:Z) (j:Z) (r:Z) (c:Z), ((0%Z <= i)%Z /\ (i < r)%Z) ->
((0%Z <= j)%Z /\ (j < c)%Z) ->
((rows (ind_basis_mat i j r c)) = r) /\
(((columns (ind_basis_mat i j r c)) = c) /\
((forall (k:Z) (l:Z), (valid_index (ind_basis_mat i j r c) k l) ->
((get (ind_basis_mat i j r c) k l) = (indic_2 k i l j))) /\
forall (o:(Z* Z)%type), (mem o (mat_indices (ind_basis_mat i j r c))) ->
((get (ind_basis_mat i j r c) (fir o) (sec o)) = tone) <->
(((fir o) = i) /\ ((sec o) = j)))).
Axiom ind_basis_mat_values :
forall (i:Z) (j:Z) (r:Z) (c:Z), ((0%Z <= i)%Z /\ (i < r)%Z) ->
((0%Z <= j)%Z /\ (j < c)%Z) -> forall (i1:Z) (j1:Z),
((0%Z <= i1)%Z /\ (i1 < r)%Z) -> ((0%Z <= j1)%Z /\ (j1 < c)%Z) ->
((get (ind_basis_mat i j r c) i1 j1) = (indic_2 i i1 j j1)).
Axiom unic_ind_basis_mat :
forall (i1:Z) (j1:Z) (i2:Z) (j2:Z) (r:Z) (c:Z),
((0%Z <= i1)%Z /\ (i1 < r)%Z) -> ((0%Z <= j1)%Z /\ (j1 < c)%Z) ->
((0%Z <= i2)%Z /\ (i2 < r)%Z) -> ((0%Z <= j2)%Z /\ (j2 < c)%Z) ->
((ind_basis_mat i1 j1 r c) = (ind_basis_mat i2 j2 r c)) ->
((i1, j1) = (i2, j2)).
Parameter basis_mat: Z -> Z -> set (matrix t).
Parameter result14: Z -> Z -> (Z* Z)%type -> matrix t.
Axiom result_def14 :
forall (r:Z) (c:Z) (o:(Z* Z)%type),
match o with
| (i, j) =>
((((0%Z <= i)%Z /\ (i < r)%Z) /\ ((0%Z <= j)%Z /\ (j < c)%Z)) ->
(((result14 r c) o) = (ind_basis_mat i j r c))) /\
(~ (((0%Z <= i)%Z /\ (i < r)%Z) /\ ((0%Z <= j)%Z /\ (j < c)%Z)) ->
(((result14 r c) o) = (make r c tzero)))
end.
Axiom basis_mat_def :
forall (r:Z) (c:Z), (0%Z < r)%Z -> (0%Z < c)%Z ->
((basis_mat r c) =
(map (result14 r c) (cartesian_product (to_fset 0%Z r) (to_fset 0%Z c)))).
Parameter fc8: (matrix t) -> (Z* Z)%type -> bool.
Axiom fc_def8 :
forall (m:matrix t) (x:(Z* Z)%type),
(((fc8 m) x) = true) <-> (eq_t (get m (fir x) (sec x)) tone).
Axiom basis_mat_spec :
forall (r:Z) (c:Z), (0%Z < r)%Z -> (0%Z < c)%Z ->
(forall (m:matrix t),
(mem m (basis_mat r c)) <->
exists i:Z, exists j:Z,
((0%Z <= i)%Z /\ (i < r)%Z) /\
(((0%Z <= j)%Z /\ (j < c)%Z) /\ (m = (ind_basis_mat i j r c)))) /\
(((basis_mat r c) =
(map (fun (o:(Z* Z)%type) => (ind_basis_mat (fir o) (sec o) r c))
(cartesian_product (to_fset 0%Z r) (to_fset 0%Z c)))) /\
((constant_size (basis_mat r c) (fun (y0:matrix t) => (p_id y0))) /\
(((s_columns (basis_mat r c) (fun (y0:matrix t) => (p_id y0))) = c) /\
(((s_rows (basis_mat r c) (fun (y0:matrix t) => (p_id y0))) = r) /\
forall (m:matrix t), (mem m (basis_mat r c)) ->
((cardinal (filter (fc8 m) (mat_indices m))) = 1%Z))))).
Parameter basis_mat_indexes: (matrix t) -> (Z* Z)%type.
Parameter result15: (matrix t) -> (Z* Z)%type -> bool.
Axiom result_def15 :
forall (m:matrix t) (x:(Z* Z)%type),
(((result15 m) x) = true) <->
((mem x (mat_indices m)) /\
(equal m (ind_basis_mat (fir x) (sec x) (rows m) (columns m)))).
Axiom basis_mat_indexes_def :
forall (m:matrix t), (mem m (basis_mat (rows m) (columns m))) ->
((basis_mat_indexes m) = (element (filter (result15 m) (mat_indices m)))).
Axiom basis_mat_indexes_spec :
forall (m:matrix t), (mem m (basis_mat (rows m) (columns m))) ->
(m =
(ind_basis_mat (fir (basis_mat_indexes m)) (sec (basis_mat_indexes m))
(rows m) (columns m))) /\
((m =
(make_f (rows m) (columns m)
(fun (i:Z) (j:Z) =>
(indic_2 (fir (basis_mat_indexes m)) i (sec (basis_mat_indexes m)) j)))) /\
(((get m (fir (basis_mat_indexes m)) (sec (basis_mat_indexes m))) = tone) /\
((forall (i:Z) (j:Z), (valid_index m i j) ->
(i = (fir (basis_mat_indexes m))) ->
~ (j = (sec (basis_mat_indexes m))) -> ((get m i j) = tzero)) /\
(valid_index m (fir (basis_mat_indexes m)) (sec (basis_mat_indexes m)))))).
Axiom get_basis_mat_indexes :
forall (m:matrix t), (mem m (basis_mat (rows m) (columns m))) ->
(m =
(ind_basis_mat (fir (basis_mat_indexes m)) (sec (basis_mat_indexes m))
(rows m) (columns m))) /\
((m =
(make_f (rows m) (columns m)
(fun (i:Z) (j:Z) =>
(indic_2 (fir (basis_mat_indexes m)) i (sec (basis_mat_indexes m)) j)))) /\
(((get m (fir (basis_mat_indexes m)) (sec (basis_mat_indexes m))) = tone) /\
forall (i:Z) (j:Z), (valid_index m i j) ->
~ ((basis_mat_indexes m) = (i, j)) -> ((get m i j) = tzero))).
Axiom set_basis_mat_indexes :
forall (m:matrix t) (i:Z) (j:Z), (valid_index m i j) ->
(mem m (basis_mat (rows m) (columns m))) -> ((get m i j) = tone) ->
((basis_mat_indexes m) = (i, j)) /\
((m = (ind_basis_mat i j (rows m) (columns m))) /\
((m =
(make_f (rows m) (columns m) (fun (i1:Z) (j1:Z) => (indic_2 i i1 j j1)))) /\
forall (i1:Z) (j1:Z), (valid_index m i1 j1) -> (i1 = i) -> ~ (j1 = j) ->
((get m i1 j1) = tzero))).
Parameter basis_projection: (matrix t) -> Z -> Z -> matrix t.
Axiom basis_projection_def :
forall (m:matrix t) (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < (rows m))%Z) ->
((0%Z <= j)%Z /\ (j < (columns m))%Z) ->
((basis_projection m i j) =
(infix_asdtdt (get m i j) (ind_basis_mat i j (rows m) (columns m)))).
Axiom basis_projection_spec :
forall (m:matrix t) (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < (rows m))%Z) ->
((0%Z <= j)%Z /\ (j < (columns m))%Z) ->
((rows (basis_projection m i j)) = (rows m)) /\
(((columns (basis_projection m i j)) = (columns m)) /\
(((basis_projection m i j) =
(make_f (rows m) (columns m)
(fun (k:Z) (l:Z) => (infix_asdt (get m i j) (indic_2 k i l j))))) /\
(((get (basis_projection m i j) i j) = (get m i j)) /\
((forall (i':Z) (j':Z), (valid_index (basis_projection m i j) i' j') ->
~ (i' = i) -> ((get (basis_projection m i j) i' j') = tzero)) /\
forall (i':Z) (j':Z), (valid_index (basis_projection m i j) i' j') ->
~ (j' = j) -> ((get (basis_projection m i j) i' j') = tzero))))).
Axiom basis_projection_null :
forall (m:matrix t) (i:Z) (j:Z) (k:Z) (l:Z), (valid_index m i j) ->
(valid_index m k l) -> ((i = k) -> ~ (j = l)) ->
((get (basis_projection m i j) k l) = tzero).
Parameter basis_projections: (matrix t) -> set (matrix t).
Parameter result16: (matrix t) -> (Z* Z)%type -> matrix t.
Axiom result_def16 :
forall (m:matrix t) (o:(Z* Z)%type),
((valid_index m (fir o) (sec o)) ->
(((result16 m) o) = (basis_projection m (fir o) (sec o)))) /\
(~ (valid_index m (fir o) (sec o)) -> (((result16 m) o) = m)).
Axiom basis_projections_def :
forall (m:matrix t),
((basis_projections m) = (map (result16 m) (to_indexes m))).
Axiom basis_projections_spec :
forall (m:matrix t),
((basis_projections m) =
(map
((fun (y0:Z -> Z -> matrix t) (y1:(Z* Z)%type) => (couple y0 y1))
((fun (y0:matrix t) (y1:Z) (y2:Z) => (basis_projection y0 y1 y2)) m))
(to_indexes m))) /\
((forall (e1:matrix t), (mem e1 (basis_projections m)) ->
((rows e1) = (rows m))) /\
((forall (e1:matrix t), (mem e1 (basis_projections m)) ->
((columns e1) = (columns m))) /\
(constant_size (basis_projections m) (fun (y0:matrix t) => (p_id y0))))).
Parameter fc9: (matrix t) -> (Z* Z)%type -> matrix t.
Axiom fc_def9 :
forall (m:matrix t) (o:(Z* Z)%type),
((valid_index m (fir o) (sec o)) ->
(((fc9 m) o) = (basis_projection m (fir o) (sec o)))) /\
(~ (valid_index m (fir o) (sec o)) -> (((fc9 m) o) = m)).
Axiom rewrite_basis_projections :
forall (m:matrix t), ((basis_projections m) = (map (fc9 m) (to_indexes m))).
Parameter indexes_decomp: (matrix t) -> matrix t.
Parameter result17: (matrix t) -> (Z* Z)%type -> matrix t.
Axiom result_def17 :
forall (m:matrix t) (o:(Z* Z)%type),
((mem o (to_indexes m)) ->
(((result17 m) o) = (basis_projection m (fir o) (sec o)))) /\
(~ (mem o (to_indexes m)) -> (((result17 m) o) = m)).
Axiom indexes_decomp_def :
forall (m:matrix t),
((indexes_decomp m) = (mat_sum (to_indexes m) (result17 m))).
Axiom indexes_decomp_spec :
forall (m:matrix t),
((rows (indexes_decomp m)) = (rows m)) /\
((columns (indexes_decomp m)) = (columns m)).
Axiom rewrite_indexes_decomp :
forall (m:matrix t),
((indexes_decomp m) =
(mat_sum (to_indexes m)
(fun (o:(Z* Z)%type) => (basis_projection m (fir o) (sec o))))).
Axiom indexes_decomp_pre :
forall (m:matrix t) (i:Z) (j:Z), (valid_index m i j) ->
((get m i j) =
(sum (to_indexes m)
(fun (o:(Z* Z)%type) => (get (basis_projection m (fir o) (sec o)) i j)))).
Axiom indexes_decomp_pre_gen :
forall (m:matrix t), forall (i:Z) (j:Z), (valid_index m i j) ->
((get m i j) =
(sum (to_indexes m)
(fun (o:(Z* Z)%type) => (get (basis_projection m (fir o) (sec o)) i j)))).
Axiom mat_to_indexes_decomp : forall (m:matrix t), (m = (indexes_decomp m)).
Parameter basis_decomp: (matrix t) -> matrix t.
Axiom basis_decomp_def :
forall (m:matrix t),
((basis_decomp m) =
(mat_sum (basis_projections m) (fun (y0:matrix t) => (p_id y0)))).
Axiom basis_decomp_spec :
forall (m:matrix t),
((rows (basis_decomp m)) = (rows m)) /\
((columns (basis_decomp m)) = (columns m)).
Axiom indexes_basis_decomp_equal_pre :
forall (m:matrix t) (i:Z) (j:Z), (valid_index m i j) ->
((get (indexes_decomp m) i j) = (get (basis_decomp m) i j)).
Axiom indexes_basis_decomp_equal :
forall (m:matrix t), ((indexes_decomp m) = (basis_decomp m)).
Axiom mat_to_basis_decomp : forall (m:matrix t), (m = (indexes_decomp m)).
Parameter fc10:
forall {a:Type} {a_WT:WhyType a}, (matrix t) -> (set a) ->
(a -> matrix t) -> a -> matrix t.
Axiom fc_def10 :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix t) (s:set a) (f:a -> matrix t) (a1:a),
((mem a1 s) -> (((fc10 m s f) a1) = (mat_mult m (f a1)))) /\
(~ (mem a1 s) -> (((fc10 m s f) a1) = m)).
Axiom product_mat_sum_r_pre :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix t) (s':set a) (s:set a) (f:a -> matrix t),
(constant_size s f) -> ((columns m) = (s_rows s f)) -> (subset s' s) ->
((cardinal s') > 0%Z)%Z ->
((mat_mult m (mat_sum s' f)) = (mat_sum s' (fc10 m s f))) /\
(((mat_mult m (mat_sum s' f)) =
(mat_sum s' (fun (a1:a) => (mat_mult m (f a1))))) /\
(((rows (mat_sum s' f)) = (s_rows s f)) /\
(((columns (mat_sum s' f)) = (s_columns s f)) /\
(((rows (mat_mult m (mat_sum s' f))) = (rows m)) /\
((columns (mat_mult m (mat_sum s' f))) = (s_columns s f)))))).
Axiom product_mat_sum_r :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix t) (s:set a) (f:a -> matrix t), (constant_size s f) ->
((columns m) = (s_rows s f)) -> ((cardinal s) > 0%Z)%Z ->
((mat_mult m (mat_sum s f)) =
(mat_sum s (fun (a1:a) => (mat_mult m (f a1))))).
Axiom product_mat_sum_r_rev :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix t) (s:set a) (f:a -> matrix t), (constant_size s f) ->
((columns m) = (s_rows s f)) -> ((cardinal s) > 0%Z)%Z ->
((mat_sum s (fun (a1:a) => (mat_mult m (f a1)))) =
(mat_mult m (mat_sum s f))).
Axiom p_injective_proj :
forall (m:matrix t),
p_injective
((fun (y0:Z -> Z -> matrix t) (y1:(Z* Z)%type) => (couple y0 y1))
((fun (y0:matrix t) (y1:Z) (y2:Z) => (basis_projection y0 y1 y2)) m))
(nonn_mat_subset
((fun (y0:Z -> Z -> matrix t) (y1:(Z* Z)%type) => (couple y0 y1))
((fun (y0:matrix t) (y1:Z) (y2:Z) => (basis_projection y0 y1 y2)) m))
(to_indexes m)).
Axiom mat_decomp_equal_indexes :
forall (m:matrix t), (m = (indexes_decomp m)).
Parameter ket_basis: Z -> set (matrix t).
Axiom ket_basis_def :
forall (n:Z), (0%Z <= n)%Z ->
((ket_basis n) = (basis_mat (power 2%Z n) 1%Z)).
Axiom ket_basis_spec :
forall (n:Z), (0%Z <= n)%Z ->
((ket_basis n) =
(map
(fun (o:(Z* Z)%type) =>
(ind_basis_mat (fir o) (sec o) (power 2%Z n) 1%Z))
(cartesian_product (to_fset 0%Z (power 2%Z n)) (to_fset 0%Z 1%Z)))) /\
(((ket_basis n) = (basis_mat (power 2%Z n) 1%Z)) /\
((forall (mat:matrix t), (mem mat (ket_basis n)) ->
((rows mat) = (power 2%Z n))) /\
((forall (mat:matrix t), (mem mat (ket_basis n)) ->
((columns mat) = 1%Z)) /\
forall (mat:matrix t), (mem mat (ket_basis n)) ->
((rows mat) = (power 2%Z n)) /\
(((columns mat) = 1%Z) /\
exists i:Z,
(valid_index mat i 0%Z) /\ ((basis_mat_indexes mat) = (i, 0%Z)))))).
Axiom unary_ket_basis :
forall (n:Z), (0%Z <= n)%Z ->
((ket_basis n) =
(map (fun (i:Z) => (ind_basis_mat i 0%Z (power 2%Z n) 1%Z))
(to_fset 0%Z (power 2%Z n)))).
Axiom to_ket_basis :
forall (i:Z) (n:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
mem (ind_basis_mat i 0%Z (power 2%Z n) 1%Z) (ket_basis n).
Parameter ket_basis_index: (matrix t) -> Z -> Z.
Axiom ket_basis_index_def :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z -> (mem m (ket_basis n)) ->
((ket_basis_index m n) = (fir (basis_mat_indexes m))).
Axiom ket_basis_index_spec :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z -> (mem m (ket_basis n)) ->
(mem (ind_basis_mat (ket_basis_index m n) 0%Z (power 2%Z n) 1%Z)
(ket_basis n)) /\
((m =
(make_f (rows m) 1%Z
(fun (i:Z) (us:Z) => (indic (ket_basis_index m n) i)))) /\
((forall (i:Z), (valid_index m i 0%Z) -> ~ (i = (ket_basis_index m n)) ->
((get m i 0%Z) = tzero)) /\
(valid_index m (ket_basis_index m n) 0%Z))).
Axiom set_ket_basis :
forall (m:matrix t) (n:Z) (i:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> (mem m (ket_basis n)) ->
((get m i 0%Z) = tone) ->
((ket_basis_index m n) = i) /\
((forall (i1:Z), (valid_index m i1 0%Z) -> ~ (i1 = i) ->
((get m i1 0%Z) = tzero)) /\
((mem m (ket_basis n)) /\
(m = (make_f (rows m) (columns m) (fun (i1:Z) (us:Z) => (indic i i1)))))).
Axiom from_ket_basis :
forall (n:Z) (m:matrix t), (0%Z <= n)%Z -> (mem m (ket_basis n)) ->
exists i:Z,
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) /\
(m = (ind_basis_mat i 0%Z (power 2%Z n) 1%Z)).
Axiom int_to_ket_basis :
forall (n:Z) (i:Z), (n > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> mem (ket n i) (ket_basis n).
Parameter is_a_ket_basis_elt: (matrix t) -> Prop.
Axiom is_a_ket_basis_elt_def :
forall (m:matrix t),
(is_a_ket_basis_elt m) <->
((is_a_ket m) /\ (mem m (ket_basis (ket_length m)))).
Axiom ket_basis_elt_are_kets :
forall (m:matrix t), (is_a_ket_basis_elt m) -> is_a_ket m.
Axiom get_is_a_ket_basis_elt :
forall (m:matrix t), (is_a_ket_basis_elt m) ->
(is_a_ket m) /\
((mem m (ket_basis (ket_length m))) /\
((exists i:Z,
((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) /\
(m = (ket (ket_length m) i))) /\
((exists i:Z,
((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) /\
(((get m i 0%Z) = tone) /\
forall (j:Z),
(((0%Z <= j)%Z /\ (j < (power 2%Z (ket_length m)))%Z) /\
~ ((get m j 0%Z) = tzero)) ->
(i = j))) /\
forall (i:Z),
(((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) /\
((get m i 0%Z) = tone)) ->
forall (j:Z),
(((0%Z <= j)%Z /\ (j < (power 2%Z (ket_length m)))%Z) /\
~ ((get m j 0%Z) = tzero)) ->
(i = j)))).
Axiom get_is_a_ket_basis_elt_indic :
forall (m:matrix t), (is_a_ket_basis_elt m) ->
exists i:Z,
((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) /\
forall (j:Z), ((0%Z <= j)%Z /\ (j < (power 2%Z (ket_length m)))%Z) ->
((get m j 0%Z) = (indic i j)).
Axiom set_is_a_ket_basis_elt :
forall (m:matrix t), (is_a_ket m) ->
(exists i:Z,
((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) /\
(m = (ket (ket_length m) i))) ->
is_a_ket_basis_elt m.
Axiom set_is_a_ket_basis_elt_exists :
forall (m:matrix t), (is_a_ket m) ->
(exists j:Z,
((0%Z <= j)%Z /\ (j < (power 2%Z (ket_length m)))%Z) /\
(m =
(make_f (power 2%Z (ket_length m)) 1%Z (fun (i:Z) (us:Z) => (indic i j))))) ->
is_a_ket_basis_elt m.
Axiom ket_func_sets_ket_basis_elts :
forall (n:Z) (i:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
(is_a_ket_basis_elt (ket n i)) /\ ((ket_length (ket n i)) = n).
Axiom kronecker_is_a_ket_basis_elt :
forall (x:matrix t) (y:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_basis_elt y) -> is_a_ket_basis_elt (kronecker x y).
Axiom ket_is_a_ket_basis_elt :
forall (n:Z) (i:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> is_a_ket_basis_elt (ket n i).
Axiom ket_basis_non_null_val :
forall (m:matrix t) (n:Z) (i:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> (is_a_ket_basis_elt m) ->
((ket_length m) = n) -> ~ ((get m i 0%Z) = tzero) -> (m = (ket n i)).
Parameter ket_to_int: (matrix t) -> Z.
Axiom ket_to_int_spec :
forall (m:matrix t), (is_a_ket_basis_elt m) ->
((0%Z <= (ket_to_int m))%Z /\
((ket_to_int m) < (power 2%Z (ket_length m)))%Z) /\
(((get m (ket_to_int m) 0%Z) = tone) /\
((m = (ket (ket_length m) (ket_to_int m))) /\
forall (i:Z), ((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) ->
(m = (ket (ket_length m) i)) -> (i = (ket_to_int m)))).
Axiom ket_to_int_ket :
forall (n:Z) (i:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> ((ket_to_int (ket n i)) = i).
Parameter bin_to_ket: Z -> (Z -> Z) -> matrix t.
Axiom bin_to_ket_def :
forall (n:Z) (bvx:Z -> Z), (n >= 0%Z)%Z -> (binary bvx) ->
((bin_to_ket n bvx) = (ket n (bin_to_int bvx n))).
Axiom bin_to_ket_spec :
forall (n:Z) (bvx:Z -> Z), (n >= 0%Z)%Z -> (binary bvx) ->
(is_a_ket_basis_elt (bin_to_ket n bvx)) /\
(((ket_length (bin_to_ket n bvx)) = n) /\
(((ket_to_int (bin_to_ket n bvx)) = (bin_to_int bvx n)) /\
(((rows (bin_to_ket n bvx)) = (power 2%Z n)) /\
(((columns (bin_to_ket n bvx)) = 1%Z) /\
((is_a_ket (bin_to_ket n bvx)) /\ (is_a_ket_l (bin_to_ket n bvx) n)))))).
Axiom bin_to_ket_l :
forall (n:Z) (n':Z) (bvx:Z -> Z), (n >= 0%Z)%Z -> (n = n') ->
(binary bvx) -> is_a_ket_l (bin_to_ket n bvx) n'.
Axiom bin_to_ket_eq :
forall (n1:Z) (n2:Z) (bvx1:Z -> Z) (bvx2:Z -> Z), (n1 >= 0%Z)%Z ->
(binary bvx1) -> (binary bvx2) -> (n2 = n1) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < n1)%Z) -> ((bvx1 i) = (bvx2 i))) ->
((bin_to_ket n1 bvx1) = (bin_to_ket n2 bvx2)).
Axiom kronecker_kets_bin_to_ket :
forall (f1:Z -> Z) (f2:Z -> Z) (n1:Z) (n2:Z), (binary f1) -> (binary f2) ->
(0%Z <= n1)%Z -> (0%Z <= n2)%Z ->
((kronecker (bin_to_ket n1 f1) (bin_to_ket n2 f2)) =
(bin_to_ket (n1 + n2)%Z
((((fun (y0:Z -> Z) (y1:Z -> Z) (y2:Z) (y3:Z) =>
(concat_fun y0 y1 y2 y3))
f1)
f2)
n1))).
Axiom kronecker_ket_to_int :
forall (x:matrix t) (y:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_basis_elt y) ->
(is_a_ket_basis_elt (kronecker x y)) /\
(((ket_length (kronecker x y)) = ((ket_length x) + (ket_length y))%Z) /\
(((kronecker x y) =
(ket ((ket_length x) + (ket_length y))%Z
(((ket_to_int x) * (power 2%Z (ket_length y)))%Z + (ket_to_int y))%Z)) /\
((ket_to_int (kronecker x y)) =
(((ket_to_int x) * (power 2%Z (ket_length y)))%Z + (ket_to_int y))%Z))).
Axiom ket_ket_to_int :
forall (x:matrix t), (is_a_ket_basis_elt x) ->
((ket (ket_length x) (ket_to_int x)) = x).
Axiom ket_ket_to_int_values :
forall (x:matrix t), (is_a_ket_basis_elt x) -> forall (i:Z) (j:Z),
(valid_index x i j) -> ((get x i j) = (indic i (ket_to_int x))).
Parameter ket_basis_projection: (matrix t) -> Z -> matrix t.
Axiom ket_basis_projection_def :
forall (m:matrix t) (j:Z), (is_a_ket m) ->
((0%Z <= j)%Z /\ (j < (power 2%Z (ket_length m)))%Z) ->
((ket_basis_projection m j) =
(infix_asdtdt (get m j 0%Z) (ket (ket_length m) j))).
Axiom ket_basis_projection_spec :
forall (m:matrix t) (j:Z), (is_a_ket m) ->
((0%Z <= j)%Z /\ (j < (power 2%Z (ket_length m)))%Z) ->
((ket_basis_projection m j) = (basis_projection m j 0%Z)).
Axiom ket_basis_projection_columns :
forall (m:matrix t) (j:Z), (is_a_ket m) ->
((0%Z <= j)%Z /\ (j < (power 2%Z (ket_length m)))%Z) ->
((columns (ket_basis_projection m j)) = 1%Z).
Axiom ket_basis_projection_rows :
forall (m:matrix t) (j:Z), (is_a_ket m) ->
((0%Z <= j)%Z /\ (j < (power 2%Z (ket_length m)))%Z) ->
((rows (ket_basis_projection m j)) = (rows m)).
Parameter ket_basis_projections: (matrix t) -> set (matrix t).
Parameter result18: (matrix t) -> Z -> matrix t.
Axiom result_def18 :
forall (m:matrix t) (j:Z),
((mem j (to_fset 0%Z (power 2%Z (ket_length m)))) ->
(((result18 m) j) = (ket_basis_projection m j))) /\
(~ (mem j (to_fset 0%Z (power 2%Z (ket_length m)))) ->
(((result18 m) j) = m)).
Axiom ket_basis_projections_def :
forall (m:matrix t), (is_a_ket m) ->
((ket_basis_projections m) =
(map (result18 m) (to_fset 0%Z (power 2%Z (ket_length m))))).
Axiom ket_basis_projections_spec :
forall (m:matrix t), (is_a_ket m) ->
((ket_basis_projections m) = (basis_projections m)).
Parameter ket_basis_projections_antec: (matrix t) -> unit.
Axiom ket_basis_projections_antec_def :
forall (m:matrix t), (is_a_ket m) -> ((ket_basis_projections_antec m) = tt).
Axiom ket_basis_projections_antec_spec :
forall (m:matrix t), (is_a_ket m) ->
(forall (e1:matrix t),
(mem e1 (ket_basis_projections m)) <->
exists j:Z,
((0%Z <= j)%Z /\ (j < (power 2%Z (ket_length m)))%Z) /\
(e1 = (ket_basis_projection m j))) /\
forall (e1:matrix t),
(mem e1 (ket_basis_projections m)) <->
exists j:Z, exists i:Z,
(valid_index m j i) /\ (e1 = (basis_projection m j i)).
Parameter ket_sum:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> matrix t) -> matrix t.
Axiom ket_sum_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ket (f e1)) ->
(exists l:Z, forall (e1:a), (mem e1 s) -> ((ket_length (f e1)) = l)) ->
((ket_sum s f) = (mat_sum s f)).
Axiom ket_sum_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ket (f e1)) ->
(exists l:Z, forall (e1:a), (mem e1 s) -> ((ket_length (f e1)) = l)) ->
(forall (i:Z), (ket_valid_index (ket_sum s f) i) ->
((get_ket (ket_sum s f) i) = (sum s (fun (e1:a) => (get_ket (f e1) i))))) /\
((is_a_ket (ket_sum s f)) /\
forall (e1:a), (mem e1 s) ->
((ket_length (ket_sum s f)) = (ket_length (f e1)))).
Parameter ket_sum_l:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> matrix t) -> Z ->
matrix t.
Axiom ket_sum_l_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l) ->
((ket_sum_l s f l) = (mat_sum s f)).
Axiom ket_sum_l_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l) ->
(is_a_ket (ket_sum_l s f l)) /\
((forall (i:Z), (ket_valid_index (ket_sum_l s f l) i) ->
((get_ket (ket_sum_l s f l) i) =
(sum s (fun (e1:a) => (get_ket (f e1) i))))) /\
((is_a_ket_l (ket_sum_l s f l) l) /\ ((ket_length (ket_sum_l s f l)) = l))).
Axiom ket_sum_l_rows :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l) ->
((rows (ket_sum_l s f l)) = (power 2%Z l)).
Axiom ket_sum_l_value :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z) (i:Z) (j:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z l))%Z) -> (j = 0%Z) ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l) ->
((get (ket_sum_l s f l) i j) = (sum s (fun (e1:a) => (get (f e1) i 0%Z)))).
Axiom get_ket_sum_l_value :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z) (i:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z l))%Z) -> ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l) ->
((get_ket (ket_sum_l s f l) i) =
(sum s (fun (e1:a) => (get_ket (f e1) i)))).
Axiom ket_sum_l_columns :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l) ->
((columns (ket_sum_l s f l)) = 1%Z).
Axiom ket_sum_null_but_maybe_one_elt :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a) (e1:a), ((cardinal s) > 1%Z)%Z ->
(forall (e2:a), (mem e2 s) -> is_a_ket (f e2)) -> (constant_size s f) ->
(mem e1 s) ->
(forall (e':a), (mem e' s) -> ~ (e1 = e') -> null_mat (f e')) ->
((ket_sum s f) = (f e1)).
Axiom ket_sum_null :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), ((cardinal s) > 1%Z)%Z ->
(l >= 0%Z)%Z -> (forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l) ->
(forall (e1:a), (mem e1 s) -> null_mat (f e1)) -> forall (j:Z),
((0%Z <= j)%Z /\ (j < (power 2%Z l))%Z) ->
((get_ket (ket_sum_l s f l) j) = tzero).
Axiom ket_sum_l_null_but_maybe_one_elt :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a) (e1:a) (l:Z), ((cardinal s) > 1%Z)%Z ->
(forall (e2:a), (mem e2 s) -> is_a_ket_l (f e2) l) -> (mem e1 s) ->
(forall (e':a), (mem e' s) -> ~ (e1 = e') -> null_mat (f e')) ->
((ket_sum_l s f l) = (f e1)).
Axiom ket_sum_ket_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l) ->
is_a_ket_l (ket_sum_l s f l) l.
Axiom ket_sum_comp_l :
forall {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> matrix t) (g:b -> matrix t) (l:Z),
((cardinal s) > 0%Z)%Z ->
(forall (e1:b), (mem e1 s) -> is_a_ket_l (f e1) l) ->
(forall (e1:b), (mem e1 s) -> is_a_ket_l (g e1) l) ->
((ket_sum_l s (fun (k:b) => (add_ket_l (f k) (g k) l)) l) =
(add_ket_l (ket_sum_l s f l) (ket_sum_l s g l) l)).
Axiom ket_sum_comp_l_rev :
forall {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> matrix t) (g:b -> matrix t) (l:Z),
((cardinal s) > 0%Z)%Z ->
(forall (e1:b), (mem e1 s) -> is_a_ket_l (f e1) l) ->
(forall (e1:b), (mem e1 s) -> is_a_ket_l (g e1) l) ->
((add_ket_l (ket_sum_l s f l) (ket_sum_l s g l) l) =
(ket_sum_l s (fun (k:b) => (add_ket_l (f k) (g k) l)) l)).
Axiom ket_sum_scalar_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (a1:t) (l:Z),
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l) ->
((cardinal s) > 0%Z)%Z ->
((ket_sum_l s (fun (k:a) => (infix_asdtdt a1 (f k))) l) =
(infix_asdtdt a1 (ket_sum_l s f l))).
Axiom ket_l_ket_sum_scalar :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (a1:t) (l:Z) (n:Z),
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l) ->
((cardinal s) > 0%Z)%Z -> (l = n) ->
is_a_ket_l (infix_asdtdt a1 (ket_sum_l s f l)) n.
Axiom scal_ket_sum_scalar_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (b:t) (l:Z) (l':Z),
(forall (e1:a), (mem e1 s) ->
exists a1:t,
exists k:matrix t, ((f e1) = (infix_asdtdt a1 k)) /\ (is_a_ket_l k l)) ->
((cardinal s) > 0%Z)%Z -> (l = l') ->
is_a_ket_l (infix_asdtdt b (ket_sum_l s f l)) l'.
Axiom ket_sum_scalar_rev_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (a1:t) (l:Z),
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l) ->
((cardinal s) > 0%Z)%Z ->
((infix_asdtdt a1 (ket_sum_l s f l)) =
(ket_sum_l s (fun (k:a) => (infix_asdtdt a1 (f k))) l)).
Axiom ket_sum_eq :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (f:a -> matrix t) (g:a -> matrix t) (l:Z),
((cardinal s) > 0%Z)%Z -> (s = s') ->
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l) ->
(forall (a1:a), (mem a1 s) -> ((f a1) = (g a1))) ->
((ket_sum_l s f l) = (ket_sum_l s' g l)).
Axiom ket_sum_eq_gen :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (f:a -> matrix t) (g:a -> matrix t) (l1:Z)
(l2:Z),
((cardinal s) > 0%Z)%Z -> (s = s') -> (l1 = l2) ->
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l1) ->
(forall (a1:a), (mem a1 s) -> ((f a1) = (g a1))) ->
((ket_sum_l s f l1) = (ket_sum_l s' g l2)).
Axiom ket_sum_bvs_eq :
forall (n1:Z) (n2:Z) (f:bitvec -> matrix t) (g:bitvec -> matrix t)
(l1:Z) (l2:Z),
(l1 = l2) -> (n1 = n2) -> (n1 >= 0%Z)%Z ->
(forall (e1:bitvec), (mem e1 (n_bvs n1)) -> is_a_ket_l (f e1) l1) ->
(forall (e1:bitvec), (mem e1 (n_bvs n1)) -> ((f e1) = (g e1))) ->
((ket_sum_l (n_bvs n1) f l1) = (ket_sum_l (n_bvs n2) g l2)).
Axiom ket_sum_scal_bvs_eq :
forall (n1:Z) (n2:Z) (f:bitvec -> matrix t) (g:bitvec -> matrix t)
(l1:Z) (l2:Z) (s1:t) (s2:t),
(l1 = l2) -> (n1 = n2) -> (s1 = s2) -> (n1 >= 0%Z)%Z ->
(forall (e1:bitvec), (mem e1 (n_bvs n1)) -> is_a_ket_l (f e1) l1) ->
(forall (e1:bitvec), (mem e1 (n_bvs n1)) -> ((f e1) = (g e1))) ->
((infix_asdtdt s1 (ket_sum_l (n_bvs n1) f l1)) =
(infix_asdtdt s2 (ket_sum_l (n_bvs n2) g l2))).
Axiom ket_sum_sum_bvs_eq :
forall (n1:Z) (n2:Z) (n1':Z) (n2':Z) (f:bitvec -> bitvec -> matrix t)
(g:bitvec -> bitvec -> matrix t) (l1:Z) (l2:Z) (l1':Z) (l2':Z),
((l1 = l2) /\ ((l2 = l1') /\ (l1' = l2'))) -> (n1 = n1') ->
(n1 >= 0%Z)%Z -> (n2 = n2') -> (n2 >= 0%Z)%Z ->
(forall (e1:bitvec) (e':bitvec), (mem e1 (n_bvs n1)) ->
(mem e' (n_bvs n2)) -> is_a_ket_l ((f e1) e') l1) ->
(forall (e1:bitvec) (e':bitvec), (mem e1 (n_bvs n1)) ->
(mem e' (n_bvs n2)) -> (((f e1) e') = ((g e1) e'))) ->
((ket_sum_l (n_bvs n1) (fun (k:bitvec) => (ket_sum_l (n_bvs n2) (f k) l1))
l2)
=
(ket_sum_l (n_bvs n1')
(fun (k:bitvec) => (ket_sum_l (n_bvs n2') (g k) l1')) l2')).
Axiom ket_sum_sum_scal_bvs_eq :
forall (n1:Z) (n2:Z) (n1':Z) (n2':Z) (f:bitvec -> bitvec -> matrix t)
(g:bitvec -> bitvec -> matrix t) (l1:Z) (l2:Z) (l1':Z) (l2':Z) (s1:t)
(s2:t),
((l1 = l2) /\ ((l2 = l1') /\ (l1' = l2'))) -> (n1 = n1') ->
(n1 >= 0%Z)%Z -> (n2 = n2') -> (s1 = s2) -> (n2 >= 0%Z)%Z ->
(forall (e1:bitvec) (e':bitvec), (mem e1 (n_bvs n1)) ->
(mem e' (n_bvs n2)) -> is_a_ket_l ((f e1) e') l1) ->
(forall (e1:bitvec) (e':bitvec), (mem e1 (n_bvs n1)) ->
(mem e' (n_bvs n2)) -> (((f e1) e') = ((g e1) e'))) ->
((infix_asdtdt s1
(ket_sum_l (n_bvs n1) (fun (k:bitvec) => (ket_sum_l (n_bvs n2) (f k) l1))
l2))
=
(infix_asdtdt s1
(ket_sum_l (n_bvs n1')
(fun (k:bitvec) => (ket_sum_l (n_bvs n2') (g k) l1')) l2'))).
Axiom ket_sum_sum_scal_mult_bvs_eq :
forall (n1:Z) (n2:Z) (n1':Z) (n2':Z) (f:bitvec -> bitvec -> matrix t)
(g:bitvec -> bitvec -> matrix t) (l1:Z) (l2:Z) (l1':Z) (l2':Z) (s1:t)
(s2:t) (s3:t),
((l1 = l2) /\ ((l2 = l1') /\ (l1' = l2'))) -> (n1 = n1') ->
(n1 >= 0%Z)%Z -> (s3 = (infix_asdt s1 s2)) -> (n2 = n2') ->
(n2 >= 0%Z)%Z ->
(forall (e1:bitvec) (e':bitvec), (mem e1 (n_bvs n1)) ->
(mem e' (n_bvs n2)) -> is_a_ket_l ((f e1) e') l1) ->
(forall (e1:bitvec) (e':bitvec), (mem e1 (n_bvs n1)) ->
(mem e' (n_bvs n2)) -> (((f e1) e') = ((g e1) e'))) ->
((infix_asdtdt s1
(ket_sum_l (n_bvs n1')
(fun (k:bitvec) => (infix_asdtdt s2 (ket_sum_l (n_bvs n2') (f k) l1')))
l2'))
=
(infix_asdtdt s3
(ket_sum_l (n_bvs n1) (fun (k:bitvec) => (ket_sum_l (n_bvs n2) (g k) l1))
l2))).
Axiom ket_sum_l_cardone :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), ((cardinal s) = 1%Z) ->
(is_a_ket_l (f (choose s)) l) -> ((ket_sum_l s f l) = (f (choose s))).
Axiom ket_sum_l_plus_one :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (e1:a) (f:a -> matrix t) (l:Z), ((cardinal s) > 0%Z)%Z ->
~ (mem e1 s) -> (forall (e2:a), (mem e2 s) -> is_a_ket_l (f e2) l) ->
(is_a_ket_l (f e1) l) ->
((ket_sum_l (add e1 s) f l) = (add_ket_l (ket_sum_l s f l) (f e1) l)).
Axiom ket_sum_l_valid_index :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z) (i:Z), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l) ->
(forall (e1:a), (mem e1 s) -> ket_valid_index (f e1) i) ->
ket_valid_index (ket_sum_l s f l) i.
Axiom ket_sum_const :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (x:matrix t) (l:Z), ((cardinal s) > 0%Z)%Z ->
(is_a_ket_l x l) ->
((ket_sum_l s (fun (us:a) => x) l) =
(infix_asdtdt (i_to_t (cardinal s)) x)).
Axiom ket_sum_const_w :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (x:matrix t) (l:Z), ((cardinal s) > 0%Z)%Z ->
(is_a_ket_l x l) ->
((infix_asdtdt (infix_sldt tone (i_to_t (cardinal s)))
(ket_sum_l s (fun (us:a) => x) l))
= x).
Axiom map_ket_sum_l :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (f:b -> matrix t) (s:set a) (t1:a -> b) (n:Z),
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f (t1 e1)) n) ->
(p_injective t1 s) ->
((ket_sum_l (map t1 s) f n) = (ket_sum_l s (fun (a1:a) => (f (t1 a1))) n)).
Axiom ket_norm_l_unif_sum :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (c:Z) (n:Z), (n >= 0%Z)%Z ->
((cardinal s) = c) -> (forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) n) ->
(forall (e1:a), (mem e1 s) -> ((ket_norm_l (f e1) n) = tone)) ->
((ket_norm_l
(infix_asdtdt (infix_sldt tone (square_rt (i_to_t c))) (ket_sum_l s f n))
n)
= tone).
Axiom ket_sum_partition :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s1:set a) (s2:set a) (f:a -> matrix t) (n:Z),
(0%Z <= n)%Z -> (forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) n) ->
(s = (union s1 s2)) -> ((inter s1 s2) = (empty : set a)) ->
((ket_sum_l s f n) = (add_mat (ket_sum_l s1 f n) (ket_sum_l s2 f n))).
Axiom ket_decomp :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z -> (is_a_ket m) ->
((ket_length m) = n) ->
(m =
(mat_sum (to_fset 0%Z (power 2%Z n))
(fun (j:Z) => (infix_asdtdt (get m j 0%Z) (ket n j))))).
Axiom ket_decomp_bv :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z -> (is_a_ket m) ->
((ket_length m) = n) ->
(m =
(ket_sum_l (n_bvs n)
(fun (bvx:bitvec) =>
(infix_asdtdt (get m (bv_to_int bvx) 0%Z) (ket n (bv_to_int bvx))))
n)).
Axiom ket_recomp :
forall (f:Z -> t) (n:Z), (0%Z <= n)%Z ->
((mat_sum (to_fset 0%Z (power 2%Z n))
(fun (j:Z) => (infix_asdtdt (f j) (ket n j))))
= (make_f (power 2%Z n) 1%Z (fun (x:Z) (us:Z) => (f x)))).
Axiom ket_decomp_quant :
forall (m:matrix t), (is_a_ket m) ->
(m =
(mat_sum (to_fset 0%Z (power 2%Z (ket_length m)))
(fun (j:Z) => (infix_asdtdt (get m j 0%Z) (ket (ket_length m) j))))).
Axiom mat_mult_ket_basis :
forall (m:matrix t) (x:matrix t), (is_a_ket_basis_elt x) ->
(((columns m) = (rows m)) /\ ((rows m) = (rows x))) ->
((mat_mult m x) =
(mat_sum (to_fset 0%Z (rows x))
(fun (k:Z) =>
(infix_asdtdt (get m k (ket_to_int x)) (ket (ket_length x) k))))).
Axiom ket_mult_diag :
forall (m:matrix t) (x:matrix t), ((ket_length x) >= 1%Z)%Z ->
(is_a_ket_basis_elt x) -> ((rows m) = (power 2%Z (ket_length x))) ->
((columns m) = (power 2%Z (ket_length x))) ->
(forall (i:Z) (j:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length x)))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z (ket_length x)))%Z) -> ~ (i = j) ->
((get m i j) = tzero)) ->
((mat_mult m x) =
(infix_asdtdt (get m (ket_to_int x) (ket_to_int x))
(ket (ket_length x) (ket_to_int x)))).
Axiom mat_mult_ket_basis_bv :
forall (m:matrix t) (x:matrix t) (n:Z), ((ket_length x) = n) ->
(is_a_ket_basis_elt x) ->
(((columns m) = (rows m)) /\ ((rows m) = (rows x))) ->
((mat_mult m x) =
(ket_sum_l (n_bvs n)
(fun (bvx:bitvec) =>
(infix_asdtdt (get m (bv_to_int bvx) (ket_to_int x))
(ket n (bv_to_int bvx))))
n)).
Axiom mat_mult_ket_basis_bv_gen :
forall (m:matrix t) (x:matrix t), (is_a_ket_basis_elt x) ->
(((columns m) = (rows m)) /\ ((rows m) = (rows x))) ->
((mat_mult m x) =
(ket_sum_l (n_bvs (ket_length x))
(fun (bvx:bitvec) =>
(infix_asdtdt (get m (bv_to_int bvx) (ket_to_int x))
(ket (ket_length x) (bv_to_int bvx))))
(ket_length x))).
Axiom mat_mult_ket_bv :
forall (m:matrix t) (x:matrix t) (n:Z), (is_a_ket_l x n) ->
(((columns m) = (rows m)) /\
(((rows m) = (rows x)) /\ ((rows x) = (power 2%Z n)))) ->
((mat_mult m x) =
(ket_sum_l (n_bvs n)
(fun (bvx:bitvec) =>
(infix_asdtdt (get_ket x (bv_to_int bvx))
(mat_mult m (ket n (bv_to_int bvx)))))
n)).
Axiom mat_mult_ket_bv_gen :
forall (m:matrix t) (x:matrix t), (is_a_ket x) ->
(((columns m) = (rows m)) /\ ((rows m) = (rows x))) ->
((mat_mult m x) =
(ket_sum_l (n_bvs (ket_length x))
(fun (bvx:bitvec) =>
(infix_asdtdt (get_ket x (bv_to_int bvx))
(mat_mult m (ket (ket_length x) (bv_to_int bvx)))))
(ket_length x))).
Axiom fun_inversion_pre :
forall (f:Z -> Z) (s:set Z) (s':set Z) (a:Z -> t) (n:Z), (0%Z <= n)%Z ->
((cardinal s) > 0%Z)%Z -> (p_bijective f s s') ->
(subset s (to_fset 0%Z n)) -> (subset s' (to_fset 0%Z n)) ->
((mat_sum s
(fun (j:Z) =>
(infix_asdtdt (a j) (set1 (make n 1%Z tzero) (f j) 0%Z tone))))
=
(mat_sum s'
(fun (j:Z) =>
(infix_asdtdt (a (inv_func f s s' j))
(set1 (make n 1%Z tzero) j 0%Z tone))))).
Axiom ket_fun_inversion :
forall (f:Z -> Z) (a:Z -> t) (m:matrix t) (pow_2_n:Z),
(pow_2_n = (power 2%Z (ket_length m))) -> (is_a_ket m) ->
(pow_2_n > 0%Z)%Z ->
(p_bijective f (to_fset 0%Z pow_2_n) (to_fset 0%Z pow_2_n)) ->
(m =
(mat_sum (to_fset 0%Z pow_2_n)
(fun (j:Z) => (infix_asdtdt (a j) (ket (ket_length m) (f j)))))) ->
(m =
(mat_sum (to_fset 0%Z pow_2_n)
(fun (j:Z) =>
(infix_asdtdt (a (inv_ f (to_fset 0%Z pow_2_n) (to_fset 0%Z pow_2_n) j))
(ket (ket_length m) j))))).
Parameter ket_to_bv: (matrix t) -> bitvec.
Axiom ket_to_bv_def :
forall (x:matrix t), (is_a_ket_basis_elt x) ->
((ket_to_bv x) = (int_to_bv (ket_to_int x) (ket_length x))).
Axiom ket_to_bv_spec :
forall (x:matrix t), (is_a_ket_basis_elt x) ->
((bv_to_int (ket_to_bv x)) = (ket_to_int x)) /\
(((length (ket_to_bv x)) = (ket_length x)) /\
(mem (ket_to_bv x) (n_bvs (ket_length x)))).
Axiom ket_to_bv_length :
forall (x:matrix t) (n:Z), (is_a_ket_basis_elt x) ->
((ket_length x) = n) -> ((length (ket_to_bv x)) = n).
Parameter bv_to_ket: bitvec -> matrix t.
Axiom bv_to_ket_def :
forall (bv:bitvec), ((bv_to_ket bv) = (ket (length bv) (bv_to_int bv))).
Axiom bv_to_ket_spec :
forall (bv:bitvec),
(is_a_ket_basis_elt (bv_to_ket bv)) /\
(((ket_to_int (bv_to_ket bv)) = (bv_to_int bv)) /\
(((ket_length (bv_to_ket bv)) = (length bv)) /\
(((rows (bv_to_ket bv)) = (power 2%Z (length bv))) /\
(((columns (bv_to_ket bv)) = 1%Z) /\
((bv_to_ket bv) = (bin_to_ket (length bv) (getbv bv))))))).
Axiom ket_to_bv_ket_length :
forall (i:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((length (ket_to_bv (ket n i))) = n).
Axiom is_a_ket_l_bv_to_ket :
forall (bv:bitvec) (l:Z), ((length bv) = l) -> is_a_ket_l (bv_to_ket bv) l.
Axiom bin_to_ket_to_bv_to_ket :
forall (f:Z -> Z) (n:Z), (0%Z <= n)%Z -> (binary f) ->
((bin_to_ket n f) = (bv_to_ket (make_bv f n))).
Axiom bin_to_ket_to_bv_to_ket_abs :
forall (f:Z -> Z) (n:Z) (a:bitvec), (0%Z <= n)%Z -> (a = (make_bv f n)) ->
(binary f) -> ((bin_to_ket n f) = (bv_to_ket a)).
Axiom ket_to_int_to_bv_to_ket :
forall (n:Z) (e1:bitvec), (0%Z <= n)%Z -> (mem e1 (n_bvs n)) ->
((ket n (bv_to_int e1)) = (bv_to_ket e1)).
Axiom ket_to_bv_ket :
forall (n:Z) (i:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) ->
((ket_to_bv (ket n i)) = (int_to_bv i n)).
Axiom bv_to_ket_length :
forall (bv:bitvec), ((ket_length (bv_to_ket bv)) = (length bv)).
Axiom is_a_ket_l_bvs :
forall (e1:bitvec) (n:Z), (0%Z <= n)%Z -> (mem e1 (n_bvs n)) ->
is_a_ket_l (bv_to_ket e1) n.
Axiom is_a_ket_l_scal_bvs :
forall (e1:bitvec) (n:Z) (a:t), (0%Z <= n)%Z -> (mem e1 (n_bvs n)) ->
is_a_ket_l (infix_asdtdt a (bv_to_ket e1)) n.
Axiom ket_to_bv_concat :
forall (x:bitvec) (y:bitvec),
((bv_to_ket (concat x y)) = (kronecker (bv_to_ket x) (bv_to_ket y))).
Axiom bv_to_ket_concat_rev :
forall (x:bitvec) (y:bitvec),
((kronecker (bv_to_ket x) (bv_to_ket y)) = (bv_to_ket (concat x y))).
Axiom bv_to_ket_to_bv :
forall (bv:bitvec), ((ket_to_bv (bv_to_ket bv)) = bv).
Axiom ket_to_bv_to_ket :
forall (x:matrix t), (is_a_ket_basis_elt x) ->
((bv_to_ket (ket_to_bv x)) = x).
Axiom bv_to_ket_eq :
forall (bv1:bitvec) (bv2:bitvec), ((length bv1) = (length bv2)) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (length bv1))%Z) ->
(((getbv bv1) i) = ((getbv bv2) i))) ->
((bv_to_ket bv1) = (bv_to_ket bv2)).
Axiom ket_to_bv_kronecker :
forall (x:matrix t) (y:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_basis_elt y) ->
((ket_to_bv (kronecker x y)) = (concat (ket_to_bv x) (ket_to_bv y))).
Axiom ket_decomp_bv_ket :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z -> (is_a_ket m) ->
((ket_length m) = n) ->
(m =
(ket_sum_l (n_bvs n)
(fun (bvx:bitvec) =>
(infix_asdtdt (get_ket m (bv_to_int bvx)) (ket n (bv_to_int bvx))))
n)).
Axiom ket_zero :
forall (n:Z), (n >= 0%Z)%Z ->
(is_a_ket_l (ket n 0%Z) n) /\
((is_a_ket_basis_elt (ket n 0%Z)) /\
(((ket_to_bv (ket n 0%Z)) = (make_bv (fun (us:Z) => 0%Z) n)) /\
forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) ->
(((getbv (ket_to_bv (ket n 0%Z))) i) = 0%Z))).
Axiom uniform_ket_norm_l :
forall (x:matrix t) (f:bitvec -> t) (n:Z), (is_a_ket_l x n) ->
(forall (e1:bitvec), (mem e1 (n_bvs n)) -> ((modulus (f e1)) = tone)) ->
(x =
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n)
(fun (x1:bitvec) => (infix_asdtdt (f x1) (bv_to_ket x1))) n))) ->
((ket_norm_l x n) = tone).
Axiom ket_sum_of_scalars :
forall (f:bitvec -> t) (n:Z), (n >= 0%Z)%Z ->
(is_a_ket_l
(ket_sum_l (n_bvs n)
(fun (x:bitvec) => (infix_asdtdt (f x) (bv_to_ket x))) n)
n) /\
forall (i:Z), ((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) ->
((get
(ket_sum_l (n_bvs n)
(fun (x:bitvec) => (infix_asdtdt (f x) (bv_to_ket x))) n)
i 0%Z)
= (f (int_to_bv i n))).
Axiom mat_sum_sum_cartesian_product_pre :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (s1:set a) (s2:set b) (f:a -> b -> matrix t) (r:Z) (c:Z),
(0%Z < r)%Z -> (0%Z < c)%Z ->
(forall (a1:a) (b1:b), (mem a1 s1) -> (mem b1 s2) ->
((rows ((f a1) b1)) = r)) ->
(forall (a1:a) (b1:b), (mem a1 s1) -> (mem b1 s2) ->
((columns ((f a1) b1)) = c)) ->
((cardinal s1) > 0%Z)%Z -> ((cardinal s2) > 0%Z)%Z ->
((mat_sum s1 (fun (a1:a) => (mat_sum s2 (f a1)))) =
(mat_sum (cartesian_product s1 s2)
(fun (o:(a* b)%type) => ((f (fir o)) (sec o))))).
Axiom mat_sum_comp1 :
forall (f:bitvec -> bitvec -> matrix t) (l:Z) (x:Z) (y:Z), (0%Z <= x)%Z ->
(0%Z <= y)%Z -> (0%Z <= l)%Z ->
(forall (bvx:bitvec) (bvy:bitvec), (mem bvx (n_bvs x)) ->
(mem bvy (n_bvs y)) -> is_a_ket ((f bvy) bvx)) ->
(forall (bvx:bitvec) (bvy:bitvec), (mem bvx (n_bvs x)) ->
(mem bvy (n_bvs y)) -> ((ket_length ((f bvy) bvx)) = l)) ->
((mat_sum (n_bvs y)
(fun (bvy:bitvec) =>
(mat_sum (n_bvs x) (fun (bvx:bitvec) => ((f bvy) bvx)))))
=
(mat_sum (n_bvs (x + y)%Z)
(fun (bv:bitvec) => ((f (hpart bv y)) (tpart bv y))))).
Axiom mat_sum_comp_rev :
forall (f:bitvec -> bitvec -> matrix t) (l:Z) (x:Z) (y:Z), (0%Z <= x)%Z ->
(0%Z <= y)%Z -> (0%Z <= l)%Z ->
(forall (bvx:bitvec) (bvy:bitvec), (mem bvx (n_bvs x)) ->
(mem bvy (n_bvs y)) -> is_a_ket ((f bvy) bvx)) ->
(forall (bvx:bitvec) (bvy:bitvec), (mem bvx (n_bvs x)) ->
(mem bvy (n_bvs y)) -> ((ket_length ((f bvy) bvx)) = l)) ->
((mat_sum (n_bvs (x + y)%Z)
(fun (bv:bitvec) => ((f (hpart bv y)) (tpart bv y))))
=
(mat_sum (n_bvs y)
(fun (bvy:bitvec) =>
(mat_sum (n_bvs x) (fun (bvx:bitvec) => ((f bvy) bvx)))))).
Axiom ket_sum_bin_comp_l :
forall (f:bitvec -> bitvec -> matrix t) (scal:bitvec -> t) (l:Z) (x:Z)
(y:Z),
(0%Z <= x)%Z -> (0%Z <= y)%Z ->
(forall (bvx:bitvec) (bvy:bitvec), (mem bvx (n_bvs x)) ->
(mem bvy (n_bvs y)) -> is_a_ket_l ((f bvy) bvx) l) ->
((ket_sum_l (n_bvs y)
(fun (bvy:bitvec) =>
(infix_asdtdt (scal bvy)
(ket_sum_l (n_bvs x) (fun (bvx:bitvec) => ((f bvy) bvx)) l)))
l)
=
(ket_sum_l (n_bvs (x + y)%Z)
(fun (bv:bitvec) =>
(infix_asdtdt (scal (hpart bv y)) ((f (hpart bv y)) (tpart bv y))))
l)).
Axiom ket_sum_bin_comp :
forall (f:bitvec -> bitvec -> matrix t) (l:Z) (x:Z) (y:Z), (0%Z <= x)%Z ->
(0%Z <= y)%Z ->
(forall (bvx:bitvec) (bvy:bitvec), (mem bvx (n_bvs x)) ->
(mem bvy (n_bvs y)) -> is_a_ket_l ((f bvy) bvx) l) ->
((ket_sum_l (n_bvs y)
(fun (bvy:bitvec) =>
(ket_sum_l (n_bvs x) (fun (bvx:bitvec) => ((f bvy) bvx)) l))
l)
=
(ket_sum_l (n_bvs (x + y)%Z)
(fun (bv:bitvec) => ((f (hpart bv y)) (tpart bv y))) l)).
Axiom ket_sum_bin_comp_rev :
forall (f:bitvec -> bitvec -> matrix t) (l:Z) (x:Z) (y:Z), (0%Z <= x)%Z ->
(0%Z <= y)%Z ->
(forall (bvx:bitvec) (bvy:bitvec), (mem bvx (n_bvs x)) ->
(mem bvy (n_bvs y)) -> is_a_ket_l ((f bvy) bvx) l) ->
((ket_sum_l (n_bvs (x + y)%Z)
(fun (bv:bitvec) => ((f (hpart bv y)) (tpart bv y))) l)
=
(ket_sum_l (n_bvs y)
(fun (bvy:bitvec) =>
(ket_sum_l (n_bvs x) (fun (bvx:bitvec) => ((f bvy) bvx)) l))
l)).
Axiom ket_sum_bin_comp_rev_ :
forall (f:bitvec -> bitvec -> matrix t) (l:Z) (x:Z) (y:Z), (0%Z <= x)%Z ->
(0%Z <= y)%Z ->
(forall (bvx:bitvec) (bvy:bitvec), (mem bvx (n_bvs x)) ->
(mem bvy (n_bvs y)) -> is_a_ket_l ((f bvx) bvy) l) ->
((ket_sum_l (n_bvs (x + y)%Z)
(fun (bv:bitvec) => ((f (hpart bv x)) (tpart bv x))) l)
=
(ket_sum_l (n_bvs x)
(fun (bvx:bitvec) =>
(ket_sum_l (n_bvs y) (fun (bvy:bitvec) => ((f bvx) bvy)) l))
l)).
Axiom ket_sum_bv_to_ints :
forall (n:Z) (f:bitvec -> matrix t) (g:Z -> matrix t), (n >= 0%Z)%Z ->
(forall (x:bitvec), ((length x) = n) -> ((f x) = (g (bv_to_int x)))) ->
((ket_sum_l (n_bvs n) f n) = (ket_sum_l (to_fset 0%Z (power 2%Z n)) g n)).
Axiom ket_sum_sum_rev :
forall (f:bitvec -> bitvec -> matrix t) (sx:set bitvec) (sy:set bitvec)
(l:Z),
(0%Z <= l)%Z -> (forall (x:bitvec), (mem x sx) -> ((length x) = l)) ->
(forall (y:bitvec), (mem y sy) -> ((length y) = l)) ->
(forall (x:bitvec) (y:bitvec), ((length x) = l) -> ((length y) = l) ->
is_a_ket_l ((f x) y) l) ->
((ket_sum_l sx (fun (x:bitvec) => (ket_sum_l sy (f x) l)) l) =
(ket_sum_l sy
(fun (y:bitvec) => (ket_sum_l sx (fun (x:bitvec) => ((f x) y)) l)) l)).
Axiom get_ket_sum :
forall (f:bitvec -> t) (n:Z) (i:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> (n >= 0%Z)%Z ->
((get_ket
(ket_sum_l (n_bvs n)
(fun (y:bitvec) => (infix_asdtdt (f y) (bv_to_ket y))) n)
i)
= (f (int_to_bv i n))).
Axiom get_ket_scalar :
forall (x:matrix t) (a:t) (i:Z),
((0%Z <= i)%Z /\ (i < (ket_length x))%Z) ->
((get_ket (infix_asdtdt a x) i) = (infix_asdt a (get_ket x i))).
Axiom get_ket_scalar_zero :
forall (x:matrix t) (a:t),
((get_ket (infix_asdtdt a x) 0%Z) = (infix_asdt a (get_ket x 0%Z))).
Axiom ket_sum_sum_complex :
forall (f:bitvec -> bitvec -> t) (sx:set bitvec) (sy:set bitvec) (l:Z),
(0%Z <= l)%Z -> (forall (x:bitvec), (mem x sx) -> ((length x) = l)) ->
(forall (y:bitvec), (mem y sy) -> ((length y) = l)) ->
((ket_sum_l sx
(fun (x:bitvec) =>
(ket_sum_l sy (fun (y:bitvec) => (infix_asdtdt ((f x) y) (bv_to_ket y)))
l))
l)
=
(ket_sum_l sy
(fun (y:bitvec) =>
(infix_asdtdt (sum sx (fun (x:bitvec) => ((f x) y))) (bv_to_ket y)))
l)).
Axiom circuit : Type.
Parameter circuit_WhyType : WhyType circuit.
Existing Instance circuit_WhyType.
Parameter width: circuit -> Z.
Axiom width_spec : forall (c:circuit), ((width c) >= 0%Z)%Z.
Parameter size: circuit -> Z.
Axiom size_spec : forall (c:circuit), ((size c) >= 0%Z)%Z.
Parameter ancillas: circuit -> Z.
Axiom ancillas_spec : forall (c:circuit), ((ancillas c) >= 0%Z)%Z.
Parameter range: circuit -> Z.
Axiom range_spec : forall (c:circuit), ((range c) >= 0%Z)%Z.
Parameter basis_ket: circuit -> bitvec -> bitvec -> bitvec.
Axiom basis_ket_spec :
forall (c:circuit) (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = (range c)) -> ((length (basis_ket c x y)) = (width c)).
Parameter basis_ket_i: circuit -> bitvec -> bitvec -> Z -> Z.
Axiom basis_ket_i_def :
forall (c:circuit) (x:bitvec) (y:bitvec) (i:Z),
((basis_ket_i c x y i) = ((getbv (basis_ket c x y)) i)).
Axiom basis_ket_i_spec :
forall (c:circuit) (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = (range c)) -> ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
((basis_ket_i c x y i) = ((getbv (basis_ket c x y)) i)).
Axiom basis_ket_from_i :
forall (c:circuit) (x:bitvec) (y:bitvec) (z:bitvec),
((length x) = (width c)) -> ((length y) = (range c)) ->
((length z) = (width c)) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
(((getbv z) i) = (basis_ket_i c x y i))) ->
((basis_ket c x y) = z).
Parameter ang_ind_i: circuit -> bitvec -> bitvec -> Z -> angle.
Parameter ang_ind_bound: circuit -> Z.
Parameter ang_ind: circuit -> bitvec -> bitvec -> angle.
Axiom ang_ind_def :
forall (c:circuit) (x:bitvec) (y:bitvec),
((ang_ind c x y) =
(ang_sum
((((fun (y0:circuit) (y1:bitvec) (y2:bitvec) (y3:Z) =>
(ang_ind_i y0 y1 y2 y3))
c)
x)
y)
0%Z (ang_ind_bound c))).
Parameter ang_ind_exp: circuit -> bitvec -> bitvec -> t.
Axiom ang_ind_exp_def :
forall (c:circuit) (x:bitvec) (y:bitvec),
((ang_ind_exp c x y) = (ang_exp (ang_ind c x y))).
Parameter id: circuit.
Axiom id_def :
((ancillas id) = 0%Z) /\
(((size id) = 0%Z) /\
(((range id) = 0%Z) /\
(((width id) = 1%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = 1%Z) ->
((length y) = 0%Z) -> ((basis_ket id x y) = x)) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = 1%Z) ->
((length y) = 0%Z) -> (i = 0%Z) ->
((basis_ket_i id x y i) = ((getbv x) i))) /\
(((ang_ind_bound id) = 1%Z) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = 1%Z) ->
((length y) = 0%Z) -> (i = 0%Z) ->
((ang_ind_i id x y i) = ang_zero)) /\
forall (x:bitvec) (y:bitvec), ((length x) = 1%Z) ->
((length y) = 0%Z) -> ((ang_ind id x y) = ang_zero)))))))).
Parameter swap: circuit.
Axiom swap_def :
((ancillas swap) = 0%Z) /\
(((size swap) = 0%Z) /\
(((range swap) = 0%Z) /\
(((width swap) = 2%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = 1%Z) ->
((length y) = 0%Z) ->
((basis_ket swap x y) =
(make_bv (fun (i:Z) => ((getbv x) (1%Z - i)%Z)) 2%Z))) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = 1%Z) ->
((length y) = 0%Z) -> (i = 0%Z) ->
((basis_ket_i swap x y i) = ((getbv x) (1%Z - i)%Z))) /\
(((ang_ind_bound swap) = 1%Z) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = 1%Z) ->
((length y) = 0%Z) -> (i = 0%Z) ->
((ang_ind_i swap x y i) = ang_zero)) /\
forall (x:bitvec) (y:bitvec), ((length x) = 1%Z) ->
((length y) = 0%Z) -> ((ang_ind swap x y) = ang_zero)))))))).
Parameter phase: angle -> circuit.
Axiom phase_spec :
forall (o:angle),
((ancillas (phase o)) = 0%Z) /\
(((size (phase o)) = 1%Z) /\
(((range (phase o)) = 0%Z) /\
(((width (phase o)) = 1%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = 1%Z) ->
((length y) = 0%Z) -> ((basis_ket (phase o) x y) = x)) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = 1%Z) ->
((length y) = 0%Z) -> (i = 0%Z) ->
((basis_ket_i (phase o) x y i) = ((getbv x) i))) /\
(((ang_ind_bound (phase o)) = 1%Z) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = 1%Z) ->
((length y) = 0%Z) -> (i = 0%Z) ->
((ang_ind_i (phase o) x y i) = o)) /\
forall (x:bitvec) (y:bitvec), ((length x) = 1%Z) ->
((length y) = 0%Z) -> ((ang_ind (phase o) x y) = o)))))))).
Parameter rz: angle -> circuit.
Axiom rz_spec :
forall (o:angle),
((ancillas (rz o)) = 0%Z) /\
(((size (rz o)) = 1%Z) /\
(((range (rz o)) = 0%Z) /\
(((width (rz o)) = 1%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = 1%Z) ->
((length y) = 0%Z) -> ((basis_ket (rz o) x y) = x)) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = 1%Z) ->
((length y) = 0%Z) -> (i = 0%Z) ->
((basis_ket_i (rz o) x y i) = ((getbv x) i))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = 1%Z) ->
((length y) = 0%Z) ->
((ang_ind (rz o) x y) = (phase_inv_ (1%Z - ((getbv x) 0%Z))%Z o))) /\
(((ang_ind_bound (rz o)) = 1%Z) /\
forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = 1%Z) ->
((length y) = 0%Z) -> (i = 0%Z) ->
((ang_ind_i (rz o) x y i) = (phase_inv_ (1%Z - ((getbv x) i))%Z o))))))))).
Parameter hadamard: circuit.
Axiom hadamard_def :
((ancillas hadamard) = 0%Z) /\
(((size hadamard) = 1%Z) /\
(((range hadamard) = 1%Z) /\
(((width hadamard) = 1%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = 1%Z) ->
((length y) = 1%Z) -> ((basis_ket hadamard x y) = y)) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = 1%Z) ->
((length y) = 1%Z) -> (i = 0%Z) ->
((basis_ket_i hadamard x y i) = ((getbv y) i))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = 1%Z) ->
((length y) = 1%Z) ->
((ang_ind hadamard x y) =
(int_to_ang (((getbv x) 0%Z) * ((getbv y) 0%Z))%Z 1%Z))) /\
(((ang_ind_bound hadamard) = 1%Z) /\
forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = 1%Z) ->
((length y) = 1%Z) -> (i = 0%Z) ->
((ang_ind_i hadamard x y i) =
(int_to_ang (((getbv x) i) * ((getbv y) i))%Z 1%Z))))))))).
Parameter cnot: circuit.
Axiom cnot_def :
((ancillas cnot) = 0%Z) /\
(((size cnot) = 1%Z) /\
(((range cnot) = 0%Z) /\
(((width cnot) = 2%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = 2%Z) ->
((length y) = 0%Z) ->
((((getbv x) 0%Z) = 0%Z) -> ((basis_ket cnot x y) = x)) /\
(~ (((getbv x) 0%Z) = 0%Z) ->
((((getbv x) 1%Z) = 0%Z) ->
((basis_ket cnot x y) = (int_to_bv 3%Z 2%Z))) /\
(~ (((getbv x) 1%Z) = 0%Z) ->
((basis_ket cnot x y) = (int_to_bv 2%Z 2%Z))))) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = 2%Z) ->
((length y) = 1%Z) -> (i = 0%Z) ->
((basis_ket_i cnot x y i) = ((getbv x) i))) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = 2%Z) ->
((length y) = 1%Z) -> (i = 1%Z) ->
((basis_ket_i cnot x y i) = (xor_i ((getbv x) 0%Z) ((getbv x) i)))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = 2%Z) ->
((length y) = 0%Z) -> ((ang_ind cnot x y) = ang_zero)) /\
(((ang_ind_bound cnot) = 1%Z) /\
forall (x:bitvec) (y:bitvec), ((length x) = 2%Z) ->
((length y) = 0%Z) -> ((ang_ind_i cnot x y 0%Z) = ang_zero))))))))).
Parameter parallel: circuit -> circuit -> circuit.
Axiom parallel_spec :
forall (d:circuit) (e1:circuit),
((ancillas (parallel d e1)) = ((ancillas d) + (ancillas e1))%Z) /\
(((size (parallel d e1)) = ((size d) + (size e1))%Z) /\
(((width (parallel d e1)) = ((width d) + (width e1))%Z) /\
(((range (parallel d e1)) = ((range d) + (range e1))%Z) /\
((forall (x:bitvec) (y:bitvec),
((length x) = (width (parallel d e1))) ->
((length y) = (range (parallel d e1))) ->
((basis_ket (parallel d e1) x y) =
(concat (basis_ket d (hpart x (width d)) (hpart y (range d)))
(basis_ket e1 (tpart x (width d)) (tpart y (range d)))))) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z),
((length x) = (width (parallel d e1))) ->
((length y) = (range (parallel d e1))) ->
((0%Z <= i)%Z /\ (i < ((width d) + (width e1))%Z)%Z) ->
((i < (width d))%Z ->
((basis_ket_i (parallel d e1) x y i) =
(basis_ket_i d (hpart x (width d)) (hpart y (range d)) i))) /\
(~ (i < (width d))%Z ->
((basis_ket_i (parallel d e1) x y i) =
(basis_ket_i e1 (tpart x (width d)) (tpart y (range d))
(i - (width d))%Z)))) /\
(((ang_ind_bound (parallel d e1)) =
((ang_ind_bound d) + (ang_ind_bound e1))%Z) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z),
((length x) = (width (parallel d e1))) ->
((length y) = (range (parallel d e1))) ->
((0%Z <= i)%Z /\ (i < ((range d) + (range e1))%Z)%Z) ->
((i < (ang_ind_bound d))%Z ->
((ang_ind_i (parallel d e1) x y i) =
(ang_ind_i d (hpart x (width d)) (hpart y (range d)) i))) /\
(~ (i < (ang_ind_bound d))%Z ->
((ang_ind_i (parallel d e1) x y i) =
(ang_ind_i e1 (tpart x (width d)) (tpart y (range d))
(i - (range d))%Z)))) /\
forall (x:bitvec) (y:bitvec),
((length x) = (width (parallel d e1))) ->
((length y) = (range (parallel d e1))) ->
((ang_ind (parallel d e1) x y) =
(ang_add (ang_ind d (hpart x (width d)) (hpart y (range d)))
(ang_ind e1 (tpart x (width d)) (tpart y (range d)))))))))))).
Parameter sequence: circuit -> circuit -> circuit.
Axiom sequence_spec :
forall (d:circuit) (e1:circuit), ((width d) = (width e1)) ->
((ancillas (sequence d e1)) =
(ZArith.BinInt.Z.max (ancillas d) (ancillas e1))) /\
(((size (sequence d e1)) = ((size d) + (size e1))%Z) /\
(((range (sequence d e1)) = ((range d) + (range e1))%Z) /\
(((width (sequence d e1)) = (width d)) /\
((forall (x:bitvec) (y:bitvec),
((length x) = (width (sequence d e1))) ->
((length y) = (range (sequence d e1))) ->
((basis_ket (sequence d e1) x y) =
(basis_ket e1 (basis_ket d x (hpart y (range d)))
(tpart y (range d))))) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z),
((length x) = (width (sequence d e1))) ->
((length y) = (range (sequence d e1))) ->
((0%Z <= i)%Z /\ (i < (width d))%Z) ->
((basis_ket_i (sequence d e1) x y i) =
(basis_ket_i e1 (basis_ket d x (hpart y (range d)))
(tpart y (range d)) i))) /\
(((ang_ind_bound (sequence d e1)) =
((ang_ind_bound d) + (ang_ind_bound e1))%Z) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z),
((length x) = (width (sequence d e1))) ->
((length y) = (range (sequence d e1))) ->
((0%Z <= i)%Z /\ (i < (ang_ind_bound (sequence d e1)))%Z) ->
((i < (ang_ind_bound d))%Z ->
((ang_ind_i (sequence d e1) x y i) =
(ang_ind_i d x (hpart y (range d)) i))) /\
(~ (i < (ang_ind_bound d))%Z ->
((ang_ind_i (sequence d e1) x y i) =
(ang_ind_i e1 (basis_ket d x (hpart y (range d)))
(tpart y (range d)) (i - (range d))%Z)))) /\
forall (x:bitvec) (y:bitvec),
((length x) = (width (sequence d e1))) ->
((length y) = (range (sequence d e1))) ->
((ang_ind (sequence d e1) x y) =
(ang_add (ang_ind d x (hpart y (range d)))
(ang_ind e1 (basis_ket d x (hpart y (range d)))
(tpart y (range d)))))))))))).
Axiom sequence_eq :
forall (d:circuit) (d':circuit) (e1:circuit) (e':circuit),
((width d) = (width e1)) -> (d = d') -> (e1 = e') ->
((sequence d e1) = (sequence d' e')).
Axiom parallel_eq :
forall (d:circuit) (d':circuit) (e1:circuit) (e':circuit), (d = d') ->
(e1 = e') -> ((parallel d e1) = (parallel d' e')).
Parameter sequence_iter_anc:
(Z -> circuit) -> Z -> Z -> Z -> Z -> Z -> circuit.
Axiom sequence_iter_anc_def :
forall (f:Z -> circuit) (d:Z) (i:Z) (j:Z) (anc:Z) (s:Z), (i < j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((width (f k)) = d)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((ancillas (f k)) = anc)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((size (f k)) <= s)%Z) ->
((j = (i + 1%Z)%Z) -> ((sequence_iter_anc f d i j anc s) = (f i))) /\
(~ (j = (i + 1%Z)%Z) ->
((sequence_iter_anc f d i j anc s) =
(sequence (sequence_iter_anc f d i (j - 1%Z)%Z anc s) (f (j - 1%Z)%Z)))).
Axiom sequence_iter_anc_spec :
forall (f:Z -> circuit) (d:Z) (i:Z) (j:Z) (anc:Z) (s:Z), (i < j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((width (f k)) = d)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((ancillas (f k)) = anc)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((size (f k)) <= s)%Z) ->
((width (sequence_iter_anc f d i j anc s)) = d) /\
(((ancillas (sequence_iter_anc f d i j anc s)) = anc) /\
((size (sequence_iter_anc f d i j anc s)) <= (s * (j - i)%Z)%Z)%Z).
Axiom sequence_iter_anc_one :
forall (f:Z -> circuit) (d:Z) (i:Z) (j:Z) (anc:Z) (s:Z), (i < j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((width (f k)) = d)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((ancillas (f k)) = anc)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((size (f k)) <= s)%Z) ->
(j = (i + 1%Z)%Z) -> ((sequence_iter_anc f d i j anc s) = (f i)).
Axiom sequence_iter_anc_re :
forall (f:Z -> circuit) (d:Z) (i:Z) (j:Z) (anc:Z) (s:Z), (i < j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((width (f k)) = d)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((ancillas (f k)) = anc)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((size (f k)) <= s)%Z) ->
((i + 1%Z)%Z < j)%Z ->
((sequence_iter_anc f d i j anc s) =
(sequence (sequence_iter_anc f d i (j - 1%Z)%Z anc s) (f (j - 1%Z)%Z))).
Parameter mat_sem: circuit -> matrix t.
Axiom mat_sem_spec :
forall (c:circuit),
((columns (mat_sem c)) = (power 2%Z (width c))) /\
((rows (mat_sem c)) = (power 2%Z (width c))).
Parameter path_sum_scheme_unit:
(bitvec -> bitvec -> angle) -> (bitvec -> bitvec -> bitvec) -> Z ->
Z -> bitvec -> matrix t.
Axiom path_sum_scheme_unit_def :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(width1:Z) (range1:Z) (x:bitvec),
(range1 >= 0%Z)%Z -> ((length x) = width1) ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = width1) ->
((length y) = range1) -> ((length ((k x1) y)) = width1)) ->
((path_sum_scheme_unit a k width1 range1 x) =
(infix_asdtdt (pow_inv_sqrt_2 range1)
(ket_sum_l (n_bvs range1)
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp ((a x) y)) (bv_to_ket ((k x) y))))
width1))).
Axiom path_sum_scheme_unit_spec :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(width1:Z) (range1:Z) (x:bitvec),
(range1 >= 0%Z)%Z -> ((length x) = width1) ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = width1) ->
((length y) = range1) -> ((length ((k x1) y)) = width1)) ->
is_a_ket_l (path_sum_scheme_unit a k width1 range1 x) width1.
Parameter path_sum_scheme:
(bitvec -> bitvec -> angle) -> (bitvec -> bitvec -> bitvec) -> Z ->
Z -> (matrix t) -> matrix t.
Axiom path_sum_scheme_def :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(width1:Z) (range1:Z) (x:matrix t),
(is_a_ket_l x width1) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = width1) ->
((length y) = range1) -> ((length ((k x1) y)) = width1)) ->
((path_sum_scheme a k width1 range1 x) =
(ket_sum_l (n_bvs width1)
(fun (z:bitvec) =>
(infix_asdtdt (get_ket x (bv_to_int z))
(path_sum_scheme_unit a k width1 range1 (hpart z width1))))
width1)).
Axiom path_sum_scheme_spec :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(width1:Z) (range1:Z) (x:matrix t),
(is_a_ket_l x width1) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = width1) ->
((length y) = range1) -> ((length ((k x1) y)) = width1)) ->
(is_a_ket_l (path_sum_scheme a k width1 range1 x) width1) /\
((path_sum_scheme a k width1 range1 x) =
(ket_sum_l (n_bvs width1)
(fun (z:bitvec) =>
(infix_asdtdt (get_ket x (bv_to_int z))
(path_sum_scheme_unit a k width1 range1 z)))
width1)).
Axiom path_sum_scheme_basis :
forall (a:bitvec -> bitvec -> angle),
forall (k:bitvec -> bitvec -> bitvec), forall (width1:Z) (range1:Z),
forall (x:matrix t), (is_a_ket_l x width1) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = width1) ->
((length y) = range1) -> ((length ((k x1) y)) = width1)) ->
(is_a_ket_basis_elt x) ->
((path_sum_scheme a k width1 range1 x) =
(path_sum_scheme_unit a k width1 range1 (ket_to_bv x))).
Axiom set_path_sum_basis :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(width1:Z) (range1:Z) (x:matrix t),
(is_a_ket_l x width1) -> (is_a_ket_basis_elt x) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = width1) ->
((length y) = range1) -> ((length ((k x1) y)) = width1)) ->
((path_sum_scheme a k width1 range1 x) =
(path_sum_scheme_unit a k width1 range1 (ket_to_bv x))).
Axiom mat_sem_sequence :
forall (d:circuit) (e1:circuit), ((width d) = (width e1)) ->
((mat_sem (sequence d e1)) = (mat_mult (mat_sem e1) (mat_sem d))).
Axiom mat_sem_par :
forall (d:circuit) (e1:circuit),
((mat_sem (parallel d e1)) = (kronecker (mat_sem d) (mat_sem e1))).
Axiom path_sum_decomp :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(width1:Z) (range1:Z) (x:matrix t),
(is_a_ket_l x width1) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = width1) ->
((length y) = range1) -> ((length ((k x1) y)) = width1)) ->
((path_sum_scheme a k width1 range1 x) =
(ket_sum_l (n_bvs width1)
(fun (z:bitvec) =>
(infix_asdtdt (get_ket x (bv_to_int z))
(path_sum_scheme a k width1 range1 (bv_to_ket z))))
width1)).
Axiom get_path_sum_basis :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(width1:Z) (range1:Z) (x:bitvec),
((length x) = width1) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = width1) ->
((length y) = range1) -> ((length ((k x1) y)) = width1)) ->
((path_sum_scheme_unit a k width1 range1 x) =
(path_sum_scheme a k width1 range1 (bv_to_ket x))).
Parameter correct_path_sum_unit:
circuit -> (bitvec -> bitvec -> angle) -> (bitvec -> bitvec -> bitvec) ->
Z -> bitvec -> Prop.
Axiom correct_path_sum_unit_def :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(k:bitvec -> bitvec -> bitvec) (range1:Z) (x:bitvec),
(correct_path_sum_unit c a k range1 x) <->
exists p:angle,
(forall (x1:bitvec) (y:bitvec), ((length x1) = (width c)) ->
((length y) = range1) -> ((length ((k x1) y)) = (width c))) /\
((range1 >= 0%Z)%Z /\
(((length x) = (width c)) /\
((mat_mult (mat_sem c) (bv_to_ket x)) =
(infix_asdtdt (ang_exp p) (path_sum_scheme_unit a k (width c) range1 x))))).
Parameter correct_path_sum:
circuit -> (bitvec -> bitvec -> angle) -> (bitvec -> bitvec -> bitvec) ->
Z -> Prop.
Axiom correct_path_sum_def :
exists p:angle,
forall (c:circuit), forall (a:bitvec -> bitvec -> angle),
forall (k:bitvec -> bitvec -> bitvec), forall (range1:Z),
(correct_path_sum c a k range1) <->
((forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = range1) -> ((length ((k x) y)) = (width c))) /\
((range1 >= 0%Z)%Z /\
forall (x:matrix t), (is_a_ket_l x (width c)) ->
((mat_mult (mat_sem c) x) =
(infix_asdtdt (ang_exp p) (path_sum_scheme a k (width c) range1 x))))).
Axiom correct_path_sum_basis :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(k:bitvec -> bitvec -> bitvec) (range1:Z) (x:bitvec),
((length x) = (width c)) -> (correct_path_sum c a k range1) ->
correct_path_sum_unit c a k range1 x.
Axiom correct_main_path_sum :
forall (c:circuit),
correct_path_sum c
((fun (y0:circuit) (y1:bitvec) (y2:bitvec) => (ang_ind y0 y1 y2)) c)
((fun (y0:circuit) (y1:bitvec) (y2:bitvec) => (basis_ket y0 y1 y2)) c)
(range c).
Axiom set_correct_main_path_sum :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(b:bitvec -> bitvec -> bitvec) (r:Z),
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = r) -> (((a x) y) = (ang_ind c x y))) ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = r) -> (((b x) y) = (basis_ket c x y))) ->
(r = (range c)) -> correct_path_sum c a b r.
Parameter pat_sem: circuit -> (matrix t) -> matrix t.
Axiom pat_sem_def :
forall (c:circuit) (x:matrix t), (is_a_ket_l x (width c)) ->
((pat_sem c x) =
(path_sum_scheme
((fun (y0:circuit) (y1:bitvec) (y2:bitvec) => (ang_ind y0 y1 y2)) c)
((fun (y0:circuit) (y1:bitvec) (y2:bitvec) => (basis_ket y0 y1 y2)) c)
(width c) (range c) x)).
Axiom pat_sem_spec :
forall (c:circuit) (x:matrix t), (is_a_ket_l x (width c)) ->
is_a_ket_l (pat_sem c x) (width c).
Axiom pat_sem_decomp :
forall (c:circuit) (x:matrix t), (is_a_ket_l x (width c)) ->
((pat_sem c x) =
(ket_sum_l (n_bvs (width c))
(fun (z:bitvec) =>
(infix_asdtdt (get_ket x (bv_to_int z)) (pat_sem c (bv_to_ket z))))
(width c))).
Axiom pat_sem_unit :
forall (c:circuit) (x:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_l x (width c)) ->
((pat_sem c x) =
(infix_asdtdt (pow_inv_sqrt_2 (range c))
(ket_sum_l (n_bvs (range c))
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp (ang_ind c (ket_to_bv x) y))
(bv_to_ket (basis_ket c (ket_to_bv x) y))))
(width c)))).
Parameter sem: circuit -> (matrix t) -> (matrix t) -> Prop.
Axiom sem_def :
forall (c:circuit) (x:matrix t) (y:matrix t),
(sem c x y) <-> ((is_a_ket_l x (width c)) /\ (infix_eqeq (pat_sem c x) y)).
Parameter circuit_equiv: circuit -> circuit -> Prop.
Axiom circuit_equiv_def :
forall (c:circuit) (c':circuit),
(circuit_equiv c c') <->
(((width c) = (width c')) /\
forall (x:bitvec), ((length x) = (width c)) ->
((pat_sem c (bv_to_ket x)) = (pat_sem c' (bv_to_ket x)))).
Axiom sem_ket_l :
forall (c:circuit) (x:matrix t) (y:matrix t), (sem c x y) ->
is_a_ket_l y (width c).
Axiom pat_sem_ket_l :
forall (c:circuit) (x:matrix t) (n:Z), (is_a_ket_l x (width c)) ->
((width c) = n) -> is_a_ket_l (pat_sem c x) n.
Axiom pat_to_mat_sem :
forall (c:circuit) (x:matrix t) (y:matrix t), (is_a_ket_l x (width c)) ->
((pat_sem c x) = y) -> ((mat_mult (mat_sem c) x) = y).
Axiom mat_to_pat_sem :
forall (c:circuit) (x:matrix t) (y:matrix t), (is_a_ket_l x (width c)) ->
((mat_mult (mat_sem c) x) = y) -> ((pat_sem c x) = y).
Axiom sem_to_mat :
forall (c:circuit) (x:matrix t) (y:matrix t), (sem c x y) ->
((mat_mult (mat_sem c) x) = y).
Axiom sem_to_pat :
forall (c:circuit) (x:matrix t) (y:matrix t), (sem c x y) ->
((pat_sem c x) = y).
Axiom mat_to_sem :
forall (c:circuit) (x:matrix t) (y:matrix t), (is_a_ket_l x (width c)) ->
((mat_mult (mat_sem c) x) = y) -> sem c x y.
Axiom pat_to_sem :
forall (c:circuit) (x:matrix t) (y:matrix t), (is_a_ket_l x (width c)) ->
((pat_sem c x) = y) -> sem c x y.
Axiom add_sem :
forall (c:circuit) (x:matrix t) (x':matrix t) (y:matrix t) (y':matrix t),
(sem c x y) -> (sem c x' y') -> sem c (add_mat x x') (add_mat y y').
Axiom pat_sem_add :
forall (c:circuit) (x:matrix t) (x':matrix t) (y:matrix t) (y':matrix t),
((pat_sem c x) = y) -> ((pat_sem c x') = y') ->
((pat_sem c (add_mat x x')) = (add_mat y y')).
Axiom scal_sem :
forall (c:circuit) (x:matrix t) (y:matrix t) (sc:t), (sem c x y) ->
sem c (infix_asdtdt sc x) (infix_asdtdt sc y).
Axiom pat_sem_scal_ :
forall (c:circuit) (x:matrix t) (y:matrix t) (sc:t),
(is_a_ket_l x (width c)) -> ((pat_sem c x) = y) ->
((pat_sem c (infix_asdtdt sc x)) = (infix_asdtdt sc y)).
Axiom pat_sem_scal :
forall (c:circuit) (x:matrix t) (sc:t), (is_a_ket_l x (width c)) ->
((pat_sem c (infix_asdtdt sc x)) = (infix_asdtdt sc (pat_sem c x))).
Axiom comp_sem :
forall (c:circuit) (c':circuit) (x:matrix t) (y:matrix t) (z:matrix t),
((width c) = (width c')) -> (sem c x y) -> (sem c' y z) ->
sem (sequence c c') x z.
Axiom pat_sem_comp :
forall (c:circuit) (c':circuit) (x:matrix t) (y:matrix t) (z:matrix t),
((width c) = (width c')) -> ((pat_sem c x) = y) -> ((pat_sem c' y) = z) ->
((pat_sem (sequence c c') x) = z).
Axiom par_sem :
forall (c:circuit) (c':circuit) (x:matrix t) (y:matrix t) (z:matrix t)
(t1:matrix t),
(sem c x y) -> (sem c' z t1) ->
sem (parallel c c') (kronecker x z) (kronecker y t1).
Axiom sum_sem :
forall {a:Type} {a_WT:WhyType a},
forall (c:circuit) (s:set a) (f:a -> matrix t) (g:a -> matrix t),
((cardinal s) >= 1%Z)%Z ->
(forall (e1:a), (mem e1 s) -> sem c (f e1) (g e1)) ->
sem c (ket_sum_l s f (width c)) (ket_sum_l s g (width c)).
Axiom sum_sem_gen :
forall {a:Type} {a_WT:WhyType a},
forall (c:circuit) (s:set a) (f:a -> matrix t) (g:a -> matrix t) (l1:Z)
(l2:Z),
((cardinal s) >= 1%Z)%Z ->
(forall (e1:a), (mem e1 s) -> sem c (f e1) (g e1)) -> (l1 = (width c)) ->
(l2 = (width c)) -> sem c (ket_sum_l s f l1) (ket_sum_l s g l2).
Axiom sum_scal_sem :
forall {a:Type} {a_WT:WhyType a},
forall (c:circuit) (s:set a) (f:a -> matrix t) (h:a -> matrix t) (g:a -> t),
((cardinal s) >= 1%Z)%Z ->
(forall (e1:a), (mem e1 s) -> sem c (f e1) (h e1)) ->
sem c (ket_sum_l s (fun (e1:a) => (infix_asdtdt (g e1) (f e1))) (width c))
(ket_sum_l s (fun (e1:a) => (infix_asdtdt (g e1) (h e1))) (width c)).
Axiom scal_pat_sem :
forall (c:circuit) (x:matrix t) (sc:t),
((pat_sem c (infix_asdtdt sc x)) = (infix_asdtdt sc (pat_sem c x))).
Axiom comp_sem_scal :
forall (c:circuit) (c':circuit) (x:matrix t) (y:matrix t) (z:matrix t)
(a:t),
((width c) = (width c')) -> (sem c x y) -> (sem c' y z) ->
sem (sequence c c') (infix_asdtdt a x) (infix_asdtdt a z).
Axiom comp_sem_add :
forall (c:circuit) (c':circuit) (x:matrix t) (x':matrix t) (y:matrix t)
(y':matrix t) (z:matrix t) (z':matrix t),
((width c) = (width c')) -> (sem c x y) -> (sem c x' y') -> (sem c' y z) ->
(sem c' y' z') -> sem (sequence c c') (add_mat x x') (add_mat z z').
Axiom comp_sem_sum :
forall {a:Type} {a_WT:WhyType a},
forall (c:circuit) (c':circuit) (f:a -> matrix t) (g:a -> matrix t)
(h:a -> matrix t) (s:set a),
((cardinal s) > 0%Z)%Z -> ((width c) = (width c')) ->
(forall (e1:a), (mem e1 s) -> sem c (f e1) (g e1)) ->
(forall (e1:a), (mem e1 s) -> sem c' (g e1) (h e1)) ->
sem (sequence c c') (ket_sum_l s f (width c)) (ket_sum_l s h (width c)).
Axiom comp_sem_basis :
forall {a:Type} {a_WT:WhyType a},
forall (c:circuit) (c':circuit) (g:a -> matrix t) (h:a -> matrix t)
(s:set a) (x:matrix t),
((cardinal s) > 0%Z)%Z -> ((width c) = (width c')) ->
(sem c x (ket_sum_l s g (width c))) ->
(forall (e1:a), (mem e1 s) -> sem c' (g e1) (h e1)) ->
sem (sequence c c') x (ket_sum_l s h (width c)).
Axiom sem_decomp :
forall (c:circuit) (f:bitvec -> matrix t) (x:matrix t),
(forall (x1:bitvec), ((length x1) = (width c)) ->
sem c (bv_to_ket x1) (f x1)) ->
sem c x
(ket_sum_l (n_bvs (width c))
(fun (j:bitvec) => (infix_asdtdt (get_ket_bv x j) (f j))) (width c)).
Axiom pat_sem_sum :
forall {a:Type} {a_WT:WhyType a},
forall (c:circuit) (s:set a) (f:a -> matrix t) (g:a -> matrix t) (n:Z),
((cardinal s) >= 1%Z)%Z -> (n = (width c)) ->
(forall (x:a), (mem x s) -> is_a_ket_l (f x) (width c)) ->
(forall (x:a), (mem x s) -> ((pat_sem c (f x)) = (g x))) ->
((pat_sem c (ket_sum_l s f n)) = (ket_sum_l s g n)).
Axiom pat_sem_sum_ :
forall {a:Type} {a_WT:WhyType a},
forall (c:circuit) (s:set a) (f:a -> matrix t) (n:Z),
((cardinal s) >= 1%Z)%Z -> (n = (width c)) ->
(forall (x:a), (mem x s) -> is_a_ket_l (f x) (width c)) ->
((pat_sem c (ket_sum_l s f n)) =
(ket_sum_l s (fun (x:a) => (pat_sem c (f x))) n)).
Axiom set_correct_path_sum :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(k:bitvec -> bitvec -> bitvec) (r:Z),
(r >= 0%Z)%Z ->
(forall (x:bitvec), ((length x) = (width c)) ->
correct_path_sum_unit c a k r x) ->
correct_path_sum c a k r.
Axiom get_correct_path_sum :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(k:bitvec -> bitvec -> bitvec) (r:Z),
(correct_path_sum c a k r) ->
(r >= 0%Z)%Z /\
((forall (x:bitvec), ((length x) = (width c)) ->
correct_path_sum_unit c a k r x) /\
((forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = r) -> ((length ((k x) y)) = (width c))) /\
((forall (x:bitvec), ((length x) = (width c)) ->
((mat_mult (mat_sem c) (bv_to_ket x)) =
(path_sum_scheme_unit a k (width c) r x))) /\
forall (x:bitvec), ((length x) = (width c)) ->
((mat_mult (mat_sem c) (bv_to_ket x)) =
(infix_asdtdt (pow_inv_sqrt_2 r)
(ket_sum_l (n_bvs r)
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp ((a x) y)) (bv_to_ket ((k x) y))))
(width c))))))).
Axiom set_sem_by_correct_ps :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(b:bitvec -> bitvec -> bitvec) (r:Z) (s:Z) (x:matrix t),
(correct_path_sum c a b r) -> (is_a_ket_l x s) -> (is_a_ket_basis_elt x) ->
(s = (width c)) ->
sem c x
(infix_asdtdt (pow_inv_sqrt_2 r)
(ket_sum_l (n_bvs r)
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp ((a (ket_to_bv x)) y))
(bv_to_ket ((b (ket_to_bv x)) y))))
s)).
Axiom pat_set_sem_by_correct_ps :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(b:bitvec -> bitvec -> bitvec) (r:Z) (s:Z) (x:matrix t),
(correct_path_sum c a b r) -> (is_a_ket_l x s) -> (is_a_ket_basis_elt x) ->
(s = (width c)) ->
((pat_sem c x) =
(infix_asdtdt (pow_inv_sqrt_2 r)
(ket_sum_l (n_bvs r)
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp ((a (ket_to_bv x)) y))
(bv_to_ket ((b (ket_to_bv x)) y))))
s))).
Axiom set_sem_by_main_basis :
forall (c:circuit) (f:bitvec -> matrix t) (r:Z) (s:Z) (x:matrix t),
(is_a_ket_l x s) -> (is_a_ket_basis_elt x) ->
(forall (y:bitvec), ((length y) = r) ->
((f y) =
(infix_asdtdt (ang_exp (ang_ind c (ket_to_bv x) y))
(bv_to_ket (basis_ket c (ket_to_bv x) y))))) ->
(r = (range c)) -> (s = (width c)) ->
sem c x (infix_asdtdt (pow_inv_sqrt_2 r) (ket_sum_l (n_bvs r) f s)).
Axiom set_correct_path_sum_sim :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(a':bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(k':bitvec -> bitvec -> bitvec) (range1:Z) (range':Z),
(range1 >= 0%Z)%Z -> (range1 = range') ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = range1) -> (((a x) y) = ((a' x) y))) ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = range1) -> ((length ((k' x) y)) = (width c))) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = (width c)) ->
((length y) = range1) -> ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
(((getbv ((k x) y)) i) = ((getbv ((k' x) y)) i))) ->
(correct_path_sum c a k range1) -> correct_path_sum c a' k' range'.
Axiom path_sum_equiv :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(a':bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(k':bitvec -> bitvec -> bitvec) (range1:Z) (range':Z),
(range1 >= 0%Z)%Z -> (range1 = range') ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = range1) -> (((a x) y) = ((a' x) y))) ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = range1) -> (((k x) y) = ((k' x) y))) ->
(correct_path_sum c a k range1) <-> (correct_path_sum c a' k' range').
Axiom correct_seq :
forall (c:circuit) (c':circuit),
forall (a:bitvec -> bitvec -> angle) (a':bitvec -> bitvec -> angle),
forall (k:bitvec -> bitvec -> bitvec) (k':bitvec -> bitvec -> bitvec),
forall (range1:Z) (range':Z), (correct_path_sum c a k range1) ->
(correct_path_sum c' a' k' range') ->
correct_path_sum (sequence c c')
(fun (x:bitvec) (y:bitvec) =>
(ang_add ((a x) (hpart y range1))
((a' ((k x) (hpart y range1))) (tpart y range1))))
(fun (x:bitvec) (y:bitvec) =>
((k' ((k x) (hpart y range1))) (tpart y range1)))
(range1 + range')%Z.
Axiom set_correct_seq :
forall (c:circuit) (c':circuit) (ase:bitvec -> bitvec -> angle)
(a:bitvec -> bitvec -> angle) (a':bitvec -> bitvec -> angle)
(bse:bitvec -> bitvec -> bitvec) (b:bitvec -> bitvec -> bitvec)
(b':bitvec -> bitvec -> bitvec) (s:Z) (rse:Z) (r:Z) (r':Z),
(0%Z <= r)%Z -> (0%Z <= r')%Z ->
(((width c) = (width c')) /\ ((width c') = s)) ->
(correct_path_sum c a b r) -> (correct_path_sum c' a' b' r') ->
(forall (x:bitvec) (y:bitvec), ((length x) = s) -> ((length y) = rse) ->
(((ase x) y) =
(ang_add ((a x) (hpart y r)) ((a' ((b x) (hpart y r))) (tpart y r))))) ->
(forall (x:bitvec) (y:bitvec), ((length x) = s) -> ((length y) = rse) ->
(((bse x) y) = ((b' ((b x) (hpart y r))) (tpart y r)))) ->
(rse = (r + r')%Z) -> correct_path_sum (sequence c c') ase bse rse.
Axiom correct_par :
forall (c:circuit) (c':circuit),
forall (a:bitvec -> bitvec -> angle) (a':bitvec -> bitvec -> angle),
forall (k:bitvec -> bitvec -> bitvec) (k':bitvec -> bitvec -> bitvec),
forall (range1:Z) (range':Z), (correct_path_sum c a k range1) ->
(correct_path_sum c' a' k' range') ->
correct_path_sum (parallel c c')
(fun (x:bitvec) (y:bitvec) =>
(ang_add ((a (hpart x (width c))) (hpart y range1))
((a' (tpart x (width c))) (tpart y range1))))
(fun (x:bitvec) (y:bitvec) =>
(concat ((k (hpart x (width c))) (hpart y range1))
((k' (tpart x (width c))) (tpart y range1))))
(range1 + range')%Z.
Axiom set_correct_par :
forall (c:circuit) (c':circuit) (ase:bitvec -> bitvec -> angle)
(a:bitvec -> bitvec -> angle) (a':bitvec -> bitvec -> angle)
(bse:bitvec -> bitvec -> bitvec) (b:bitvec -> bitvec -> bitvec)
(b':bitvec -> bitvec -> bitvec) (s:Z) (rse:Z) (r:Z) (r':Z),
(0%Z <= r)%Z -> (0%Z <= r')%Z -> (correct_path_sum c a b r) ->
(correct_path_sum c' a' b' r') ->
(forall (x:bitvec) (y:bitvec), ((length x) = s) -> ((length y) = rse) ->
(((ase x) y) =
(ang_add ((a (hpart x (width c))) (hpart y r))
((a' (tpart x (width c))) (tpart y r))))) ->
(forall (x:bitvec) (y:bitvec), ((length x) = s) -> ((length y) = rse) ->
(((bse x) y) =
(concat ((b (hpart x (width c))) (hpart y r))
((b' (tpart x (width c))) (tpart y r))))) ->
(rse = (r + r')%Z) -> (s = ((width c) + (width c'))%Z) ->
correct_path_sum (parallel c c') ase bse rse.
Axiom correct_to_pat_sem :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(k:bitvec -> bitvec -> bitvec) (r:Z),
(correct_path_sum c a k r) -> forall (x:matrix t),
(is_a_ket_l x (width c)) ->
((path_sum_scheme a k (width c) r x) = (pat_sem c x)).
Axiom correct_to_mat_sem :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(k:bitvec -> bitvec -> bitvec) (r:Z),
(correct_path_sum c a k r) -> forall (x:matrix t),
(is_a_ket_l x (width c)) ->
((path_sum_scheme a k (width c) r x) = (mat_mult (mat_sem c) x)).
Axiom correct_to_sem :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(k:bitvec -> bitvec -> bitvec) (r:Z),
(correct_path_sum c a k r) -> forall (x:matrix t) (y:matrix t),
(is_a_ket_l x (width c)) -> ((path_sum_scheme a k (width c) r x) = y) ->
sem c x y.
Axiom mat_sem_to_correct :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(k:bitvec -> bitvec -> bitvec) (r:Z),
(r >= 0%Z)%Z ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = r) -> ((length ((k x) y)) = (width c))) ->
(forall (x:matrix t), (is_a_ket_l x (width c)) -> (is_a_ket_basis_elt x) ->
((path_sum_scheme a k (width c) r x) = (mat_mult (mat_sem c) x))) ->
correct_path_sum c a k r.
Axiom pat_sem_to_correct :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(k:bitvec -> bitvec -> bitvec) (r:Z),
(r >= 0%Z)%Z ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = r) -> ((length ((k x) y)) = (width c))) ->
(forall (x:matrix t), (is_a_ket_l x (width c)) -> (is_a_ket_basis_elt x) ->
((path_sum_scheme a k (width c) r x) = (pat_sem c x))) ->
correct_path_sum c a k r.
Axiom sem_to_correct :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(k:bitvec -> bitvec -> bitvec) (r:Z),
(r >= 0%Z)%Z ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = r) -> ((length ((k x) y)) = (width c))) ->
(forall (x:matrix t) (y:matrix t), (is_a_ket_l x (width c)) ->
(is_a_ket_basis_elt x) -> ((path_sum_scheme a k (width c) r x) = y) ->
sem c x y) ->
correct_path_sum c a k r.
Axiom hadamard_comp :
forall (x:bitvec), ((length x) = 1%Z) ->
((pat_sem hadamard (pat_sem hadamard (bv_to_ket x))) = (bv_to_ket x)).
Parameter aux: Z -> bitvec -> circuit.
Axiom aux_def :
forall (k:Z) (x:bitvec), ((length x) = 1%Z) -> (1%Z <= k)%Z ->
((k = 1%Z) -> ((aux k x) = hadamard)) /\
(~ (k = 1%Z) -> ((aux k x) = (sequence (aux (k - 1%Z)%Z x) hadamard))).
Axiom aux_spec :
forall (k:Z) (x:bitvec), ((length x) = 1%Z) -> (1%Z <= k)%Z ->
((width (aux k x)) = 1%Z) /\
((((odd k) = true) ->
((pat_sem (aux k x) (bv_to_ket x)) = (pat_sem hadamard (bv_to_ket x)))) /\
(((even k) = true) -> ((pat_sem (aux k x) (bv_to_ket x)) = (bv_to_ket x)))).
Parameter eigen: circuit -> (matrix t) -> angle -> Prop.
Axiom eigen_def :
forall (c:circuit) (x:matrix t) (o:angle),
(eigen c x o) <-> (sem c x (infix_asdtdt (ang_exp o) x)).
Axiom eigen_depth :
forall (c:circuit) (x:matrix t) (o:angle), (eigen c x o) ->
((width c) = (ket_length x)).
Axiom is_a_ket_l_eigen :
forall (c:circuit) (x:matrix t), (exists o:angle, eigen c x o) ->
is_a_ket_l x (width c).
Axiom eigen_scal :
forall (c:circuit) (a:angle) (x:matrix t) (o:angle), (eigen c x o) ->
eigen c (infix_asdtdt (ang_exp a) x) o.
Parameter eigen_comp:
circuit -> circuit -> (matrix t) -> angle -> angle -> circuit.
Axiom eigen_comp_def :
forall (c:circuit) (c':circuit) (x:matrix t) (o:angle) (o':angle),
((width c) = (width c')) -> (eigen c x o) -> (eigen c' x o') ->
((eigen_comp c c' x o o') = (sequence c c')).
Axiom eigen_comp_spec :
forall (c:circuit) (c':circuit) (x:matrix t) (o:angle) (o':angle),
((width c) = (width c')) -> (eigen c x o) -> (eigen c' x o') ->
((width (eigen_comp c c' x o o')) = (width c)) /\
(eigen (eigen_comp c c' x o o') x (ang_add o o')).
Parameter eigen_square: circuit -> (matrix t) -> angle -> circuit.
Axiom eigen_square_def :
forall (c:circuit) (x:matrix t) (o:angle), (eigen c x o) ->
((eigen_square c x o) = (eigen_comp c c x o o)).
Axiom eigen_square_spec :
forall (c:circuit) (x:matrix t) (o:angle), (eigen c x o) ->
((width (eigen_square c x o)) = (width c)) /\
((eigen (eigen_square c x o) x (ang_add o o)) /\
((eigen_square c x o) = (sequence c c))).
Parameter pow_pow_2: circuit -> Z -> (matrix t) -> angle -> circuit.
Axiom pow_pow_2_def :
forall (c:circuit) (p:Z) (x:matrix t) (o:angle), (0%Z <= p)%Z ->
(eigen c x o) ->
((p = 0%Z) -> ((pow_pow_2 c p x o) = c)) /\
(~ (p = 0%Z) ->
((pow_pow_2 c p x o) =
(eigen_square (pow_pow_2 c (p - 1%Z)%Z x o) x
(ang_mult_int o (power 2%Z (p - 1%Z)%Z))))).
Axiom pow_pow_2_spec :
forall (c:circuit) (p:Z) (x:matrix t) (o:angle), (0%Z <= p)%Z ->
(eigen c x o) ->
((width (pow_pow_2 c p x o)) = (width c)) /\
(eigen (pow_pow_2 c p x o) x (ang_mult_int o (power 2%Z p))).
Parameter correct_path_sum_i:
circuit -> (bitvec -> bitvec -> Z -> angle) -> Z -> Z ->
(bitvec -> bitvec -> Z -> Z) -> Z -> Prop.
Axiom correct_path_sum_i_spec :
forall (c:circuit) (a:bitvec -> bitvec -> Z -> angle) (l:Z) (h:Z)
(k:bitvec -> bitvec -> Z -> Z) (range1:Z),
(correct_path_sum_i c a l h k range1) <->
((forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = range1) -> ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
(0%Z <= (((k x) y) i))%Z /\ ((((k x) y) i) < 2%Z)%Z) /\
(correct_path_sum c
(fun (x:bitvec) (y:bitvec) => (ang_sum (fun (i:Z) => (((a x) y) i)) l h))
(fun (x:bitvec) (y:bitvec) =>
(make_bv (fun (i:Z) => (((k x) y) i)) (width c)))
range1)).
Axiom set_correct_path_sum_i :
forall (c:circuit) (a:bitvec -> bitvec -> Z -> angle) (l:Z) (h:Z)
(k:bitvec -> bitvec -> Z -> Z) (range1:Z),
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = range1) -> ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
(0%Z <= (((k x) y) i))%Z /\ ((((k x) y) i) < 2%Z)%Z) ->
(correct_path_sum c
(fun (x:bitvec) (y:bitvec) => (ang_sum (fun (i:Z) => (((a x) y) i)) l h))
(fun (x:bitvec) (y:bitvec) =>
(make_bv (fun (i:Z) => (((k x) y) i)) (width c)))
range1) ->
correct_path_sum_i c a l h k range1.
Axiom correct_path_sum_i_main :
forall (c:circuit) (h':Z) (r':Z), (h' = (ang_ind_bound c)) ->
(r' = (range c)) ->
correct_path_sum_i c
((fun (y0:circuit) (y1:bitvec) (y2:bitvec) (y3:Z) =>
(ang_ind_i y0 y1 y2 y3))
c)
0%Z h'
((fun (y0:circuit) (y1:bitvec) (y2:bitvec) (y3:Z) =>
(basis_ket_i y0 y1 y2 y3))
c)
r'.
Axiom correct_path_sum_i_to_sem_basis :
forall (c:circuit) (a:bitvec -> bitvec -> Z -> angle) (l:Z) (h:Z)
(k:bitvec -> bitvec -> Z -> Z) (range1:Z) (x:matrix t)
(f:bitvec -> matrix t),
(correct_path_sum_i c a l h k range1) -> (is_a_ket_l x (width c)) ->
(is_a_ket_basis_elt x) ->
(forall (y:bitvec), ((length y) = range1) ->
((f y) =
(infix_asdtdt (ang_exp (ang_sum ((a (ket_to_bv x)) y) l h))
(bv_to_ket (make_bv ((k (ket_to_bv x)) y) (width c)))))) ->
sem c x
(infix_asdtdt (pow_inv_sqrt_2 range1)
(ket_sum_l (n_bvs range1) f (width c))).
Axiom correct_path_sum_i_to_sem_basis_gen :
forall (c:circuit) (a:bitvec -> bitvec -> Z -> angle) (l:Z) (h:Z)
(k:bitvec -> bitvec -> Z -> Z) (range1:Z)
(f:bitvec -> bitvec -> matrix t),
(correct_path_sum_i c a l h k range1) ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = range1) ->
(((f x) y) =
(infix_asdtdt (ang_exp (ang_sum ((a x) y) l h))
(bv_to_ket (make_bv ((k x) y) (width c)))))) ->
forall (x:matrix t), (is_a_ket_l x (width c)) -> (is_a_ket_basis_elt x) ->
sem c x
(infix_asdtdt (pow_inv_sqrt_2 range1)
(ket_sum_l (n_bvs range1) (f (ket_to_bv x)) (width c))).
Axiom get_correct_path_sum_i :
forall (c:circuit) (a:bitvec -> bitvec -> Z -> angle) (l:Z) (h:Z)
(k:bitvec -> bitvec -> Z -> Z) (range1:Z),
(correct_path_sum_i c a l h k range1) ->
(range1 >= 0%Z)%Z /\
((forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = range1) -> ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
(0%Z <= (((k x) y) i))%Z /\ ((((k x) y) i) < 2%Z)%Z) /\
((correct_path_sum c
(fun (x:bitvec) (y:bitvec) =>
(ang_sum (fun (i:Z) => (((a x) y) i)) l h))
(fun (x:bitvec) (y:bitvec) =>
(make_bv (fun (i:Z) => (((k x) y) i)) (width c)))
range1) /\
(correct_path_sum c
(fun (x:bitvec) (y:bitvec) =>
(ang_sum (fun (i:Z) => (((a x) y) i)) l h))
(fun (x:bitvec) (y:bitvec) =>
(makes_bv (fun (i:Z) => (((k x) y) i)) (width c)))
range1))).
Parameter sequence_spec_i:
circuit -> circuit -> (bitvec -> bitvec -> Z -> angle) ->
(bitvec -> bitvec -> Z -> angle) -> (bitvec -> bitvec -> Z -> angle) ->
Z -> Z -> Z -> (bitvec -> bitvec -> Z -> Z) ->
(bitvec -> bitvec -> Z -> Z) -> (bitvec -> bitvec -> Z -> Z) -> Z ->
Z -> Z -> circuit.
Axiom sequence_spec_i_def :
forall (c:circuit) (c':circuit) (ase:bitvec -> bitvec -> Z -> angle)
(a:bitvec -> bitvec -> Z -> angle) (a':bitvec -> bitvec -> Z -> angle)
(l:Z) (z:Z) (h:Z) (bse:bitvec -> bitvec -> Z -> Z)
(b:bitvec -> bitvec -> Z -> Z) (b':bitvec -> bitvec -> Z -> Z) (rse:Z)
(r:Z) (r':Z),
((width c) = (width c')) -> (correct_path_sum_i c a l z b r) ->
(correct_path_sum_i c' a' z h b' r') ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = rse) -> ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
((((bse x) y) i) =
(((b' (make_bv ((b x) (hpart y r)) (width c))) (tpart y r)) i))) ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = rse) -> ((l <= i)%Z /\ (i < z)%Z) ->
((((ase x) y) i) = (((a x) (hpart y r)) i))) ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = rse) -> ((z <= i)%Z /\ (i < h)%Z) ->
((((ase x) y) i) =
(((a' (make_bv ((b x) (hpart y r)) (width c))) (tpart y r)) i))) ->
(rse = (r + r')%Z) -> ((l <= z)%Z /\ (z <= h)%Z) ->
((sequence_spec_i c c' ase a a' l z h bse b b' rse r r') = (sequence c c')).
Axiom sequence_spec_i_spec :
forall (c:circuit) (c':circuit) (ase:bitvec -> bitvec -> Z -> angle)
(a:bitvec -> bitvec -> Z -> angle) (a':bitvec -> bitvec -> Z -> angle)
(l:Z) (z:Z) (h:Z) (bse:bitvec -> bitvec -> Z -> Z)
(b:bitvec -> bitvec -> Z -> Z) (b':bitvec -> bitvec -> Z -> Z) (rse:Z)
(r:Z) (r':Z),
((width c) = (width c')) -> (correct_path_sum_i c a l z b r) ->
(correct_path_sum_i c' a' z h b' r') ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = rse) -> ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
((((bse x) y) i) =
(((b' (make_bv ((b x) (hpart y r)) (width c))) (tpart y r)) i))) ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = rse) -> ((l <= i)%Z /\ (i < z)%Z) ->
((((ase x) y) i) = (((a x) (hpart y r)) i))) ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = rse) -> ((z <= i)%Z /\ (i < h)%Z) ->
((((ase x) y) i) =
(((a' (make_bv ((b x) (hpart y r)) (width c))) (tpart y r)) i))) ->
(rse = (r + r')%Z) -> ((l <= z)%Z /\ (z <= h)%Z) ->
(correct_path_sum_i (sequence_spec_i c c' ase a a' l z h bse b b' rse r r')
ase l h bse rse) /\
(((width (sequence_spec_i c c' ase a a' l z h bse b b' rse r r')) =
(width c)) /\
((sequence_spec_i c c' ase a a' l z h bse b b' rse r r') =
(sequence c c'))).
Parameter sequence_spec_i_r:
circuit -> circuit -> (bitvec -> bitvec -> Z -> angle) ->
(bitvec -> bitvec -> Z -> angle) -> (bitvec -> bitvec -> angle) ->
Z -> Z -> (bitvec -> bitvec -> Z -> Z) -> (bitvec -> bitvec -> Z -> Z) ->
(bitvec -> bitvec -> bitvec) -> Z -> Z -> Z -> circuit.
Axiom sequence_spec_i_r_def :
forall (c:circuit) (c':circuit) (ase:bitvec -> bitvec -> Z -> angle)
(a':bitvec -> bitvec -> Z -> angle) (a:bitvec -> bitvec -> angle)
(l:Z) (h:Z) (bse:bitvec -> bitvec -> Z -> Z)
(b':bitvec -> bitvec -> Z -> Z) (b:bitvec -> bitvec -> bitvec) (rse:Z)
(r:Z) (r':Z),
((width c) = (width c')) -> (correct_path_sum c a b r) ->
(correct_path_sum_i c' a' (l + 1%Z)%Z h b' r') ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = rse) -> ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
((((bse x) y) i) = (((b' ((b x) (hpart y r))) (tpart y r)) i))) ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = rse) -> ((((ase x) y) l) = ((a x) (hpart y r)))) ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = rse) -> (((l + 1%Z)%Z <= i)%Z /\ (i < h)%Z) ->
((((ase x) y) i) = (((a' ((b x) (hpart y r))) (tpart y r)) i))) ->
(rse = (r + r')%Z) -> (l < h)%Z ->
((sequence_spec_i_r c c' ase a' a l h bse b' b rse r r') =
(sequence_spec_i c c' ase (fun (x:bitvec) (y:bitvec) (i:Z) => ((a x) y))
a' l (l + 1%Z)%Z h bse
(fun (x:bitvec) (y:bitvec) (i:Z) => ((getbv ((b x) y)) i)) b' rse r r')).
Axiom sequence_spec_i_r_spec :
forall (c:circuit) (c':circuit) (ase:bitvec -> bitvec -> Z -> angle)
(a':bitvec -> bitvec -> Z -> angle) (a:bitvec -> bitvec -> angle)
(l:Z) (h:Z) (bse:bitvec -> bitvec -> Z -> Z)
(b':bitvec -> bitvec -> Z -> Z) (b:bitvec -> bitvec -> bitvec) (rse:Z)
(r:Z) (r':Z),
((width c) = (width c')) -> (correct_path_sum c a b r) ->
(correct_path_sum_i c' a' (l + 1%Z)%Z h b' r') ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = rse) -> ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
((((bse x) y) i) = (((b' ((b x) (hpart y r))) (tpart y r)) i))) ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = rse) -> ((((ase x) y) l) = ((a x) (hpart y r)))) ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = rse) -> (((l + 1%Z)%Z <= i)%Z /\ (i < h)%Z) ->
((((ase x) y) i) = (((a' ((b x) (hpart y r))) (tpart y r)) i))) ->
(rse = (r + r')%Z) -> (l < h)%Z ->
(correct_path_sum_i (sequence_spec_i_r c c' ase a' a l h bse b' b rse r r')
ase l h bse rse) /\
(((width (sequence_spec_i_r c c' ase a' a l h bse b' b rse r r')) =
(width c)) /\
((sequence_spec_i_r c c' ase a' a l h bse b' b rse r r') =
(sequence c c'))).
Parameter sequence_spec_i_l:
circuit -> circuit -> (bitvec -> bitvec -> Z -> angle) ->
(bitvec -> bitvec -> Z -> angle) -> (bitvec -> bitvec -> angle) ->
Z -> Z -> (bitvec -> bitvec -> Z -> Z) -> (bitvec -> bitvec -> Z -> Z) ->
(bitvec -> bitvec -> bitvec) -> Z -> Z -> Z -> circuit.
Axiom sequence_spec_i_l_def :
forall (c:circuit) (c':circuit) (ase:bitvec -> bitvec -> Z -> angle)
(a:bitvec -> bitvec -> Z -> angle) (a':bitvec -> bitvec -> angle)
(l:Z) (h:Z) (bse:bitvec -> bitvec -> Z -> Z)
(b:bitvec -> bitvec -> Z -> Z) (b':bitvec -> bitvec -> bitvec) (rse:Z)
(r:Z) (r':Z),
((width c) = (width c')) -> (correct_path_sum_i c a l (h - 1%Z)%Z b r) ->
(correct_path_sum c' a' b' r') ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = rse) -> ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
((((bse x) y) i) =
((getbv ((b' (make_bv ((b x) (hpart y r)) (width c))) (tpart y r))) i))) ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = rse) -> ((l <= i)%Z /\ (i < (h - 1%Z)%Z)%Z) ->
((((ase x) y) i) = (((a x) (hpart y r)) i))) ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = rse) ->
((((ase x) y) (h - 1%Z)%Z) =
((a' (make_bv (fun (i:Z) => (((b x) (hpart y r)) i)) (width c)))
(tpart y r)))) ->
(rse = (r + r')%Z) -> (l < h)%Z ->
((sequence_spec_i_l c c' ase a a' l h bse b b' rse r r') =
(sequence_spec_i c c' ase a
(fun (x:bitvec) (y:bitvec) (i:Z) => ((a' x) y)) l (h - 1%Z)%Z h bse b
(fun (x:bitvec) (y:bitvec) (i:Z) => ((getbv ((b' x) y)) i)) rse r r')).
Axiom sequence_spec_i_l_spec :
forall (c:circuit) (c':circuit) (ase:bitvec -> bitvec -> Z -> angle)
(a:bitvec -> bitvec -> Z -> angle) (a':bitvec -> bitvec -> angle)
(l:Z) (h:Z) (bse:bitvec -> bitvec -> Z -> Z)
(b:bitvec -> bitvec -> Z -> Z) (b':bitvec -> bitvec -> bitvec) (rse:Z)
(r:Z) (r':Z),
((width c) = (width c')) -> (correct_path_sum_i c a l (h - 1%Z)%Z b r) ->
(correct_path_sum c' a' b' r') ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = rse) -> ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
((((bse x) y) i) =
((getbv ((b' (make_bv ((b x) (hpart y r)) (width c))) (tpart y r))) i))) ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = rse) -> ((l <= i)%Z /\ (i < (h - 1%Z)%Z)%Z) ->
((((ase x) y) i) = (((a x) (hpart y r)) i))) ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = rse) ->
((((ase x) y) (h - 1%Z)%Z) =
((a' (make_bv (fun (i:Z) => (((b x) (hpart y r)) i)) (width c)))
(tpart y r)))) ->
(rse = (r + r')%Z) -> (l < h)%Z ->
(correct_path_sum_i (sequence_spec_i_l c c' ase a a' l h bse b b' rse r r')
ase l h bse rse) /\
(((width (sequence_spec_i_l c c' ase a a' l h bse b b' rse r r')) =
(width c)) /\
((sequence_spec_i_l c c' ase a a' l h bse b b' rse r r') =
(sequence c c'))).
Parameter parallel_spec_i:
circuit -> circuit -> (bitvec -> bitvec -> Z -> angle) ->
(bitvec -> bitvec -> Z -> angle) -> (bitvec -> bitvec -> Z -> angle) ->
Z -> Z -> Z -> (bitvec -> bitvec -> Z -> Z) ->
(bitvec -> bitvec -> Z -> Z) -> (bitvec -> bitvec -> Z -> Z) -> Z ->
Z -> Z -> circuit.
Axiom parallel_spec_i_def :
forall (c:circuit) (c':circuit) (ase:bitvec -> bitvec -> Z -> angle)
(a:bitvec -> bitvec -> Z -> angle) (a':bitvec -> bitvec -> Z -> angle)
(l:Z) (z:Z) (h:Z) (bse:bitvec -> bitvec -> Z -> Z)
(b:bitvec -> bitvec -> Z -> Z) (b':bitvec -> bitvec -> Z -> Z) (rse:Z)
(r:Z) (r':Z),
(correct_path_sum_i c a l z b r) -> (correct_path_sum_i c' a' z h b' r') ->
(forall (x:bitvec) (y:bitvec) (i:Z),
((length x) = ((width c) + (width c'))%Z) -> ((length y) = rse) ->
((l <= i)%Z /\ (i < z)%Z) ->
((((ase x) y) i) = (((a (hpart x (width c))) (hpart y r)) i))) ->
(forall (x:bitvec) (y:bitvec) (i:Z),
((length x) = ((width c) + (width c'))%Z) -> ((length y) = rse) ->
((z <= i)%Z /\ (i < h)%Z) ->
((((ase x) y) i) = (((a' (tpart x (width c))) (tpart y r)) i))) ->
(forall (x:bitvec) (y:bitvec) (i:Z),
((length x) = ((width c) + (width c'))%Z) -> ((length y) = rse) ->
((0%Z <= i)%Z /\ (i < (width c))%Z) ->
((((bse x) y) i) = (((b (hpart x (width c))) (hpart y r)) i))) ->
(forall (x:bitvec) (y:bitvec) (i:Z),
((length x) = ((width c) + (width c'))%Z) -> ((length y) = rse) ->
(((width c) <= i)%Z /\ (i < ((width c) + (width c'))%Z)%Z) ->
((((bse x) y) i) =
(((b' (tpart x (width c))) (tpart y r)) (i - (width c))%Z))) ->
(rse = (r + r')%Z) -> ((l <= z)%Z /\ (z <= h)%Z) ->
((parallel_spec_i c c' ase a a' l z h bse b b' rse r r') = (parallel c c')).
Axiom parallel_spec_i_spec :
forall (c:circuit) (c':circuit) (ase:bitvec -> bitvec -> Z -> angle)
(a:bitvec -> bitvec -> Z -> angle) (a':bitvec -> bitvec -> Z -> angle)
(l:Z) (z:Z) (h:Z) (bse:bitvec -> bitvec -> Z -> Z)
(b:bitvec -> bitvec -> Z -> Z) (b':bitvec -> bitvec -> Z -> Z) (rse:Z)
(r:Z) (r':Z),
(correct_path_sum_i c a l z b r) -> (correct_path_sum_i c' a' z h b' r') ->
(forall (x:bitvec) (y:bitvec) (i:Z),
((length x) = ((width c) + (width c'))%Z) -> ((length y) = rse) ->
((l <= i)%Z /\ (i < z)%Z) ->
((((ase x) y) i) = (((a (hpart x (width c))) (hpart y r)) i))) ->
(forall (x:bitvec) (y:bitvec) (i:Z),
((length x) = ((width c) + (width c'))%Z) -> ((length y) = rse) ->
((z <= i)%Z /\ (i < h)%Z) ->
((((ase x) y) i) = (((a' (tpart x (width c))) (tpart y r)) i))) ->
(forall (x:bitvec) (y:bitvec) (i:Z),
((length x) = ((width c) + (width c'))%Z) -> ((length y) = rse) ->
((0%Z <= i)%Z /\ (i < (width c))%Z) ->
((((bse x) y) i) = (((b (hpart x (width c))) (hpart y r)) i))) ->
(forall (x:bitvec) (y:bitvec) (i:Z),
((length x) = ((width c) + (width c'))%Z) -> ((length y) = rse) ->
(((width c) <= i)%Z /\ (i < ((width c) + (width c'))%Z)%Z) ->
((((bse x) y) i) =
(((b' (tpart x (width c))) (tpart y r)) (i - (width c))%Z))) ->
(rse = (r + r')%Z) -> ((l <= z)%Z /\ (z <= h)%Z) ->
(correct_path_sum_i (parallel c c') ase l h bse rse) /\
((width (parallel_spec_i c c' ase a a' l z h bse b b' rse r r')) =
((width c) + (width c'))%Z).
Axiom replace_ang_ind_i :
forall (c:circuit) (a:bitvec -> bitvec -> Z -> angle)
(a':bitvec -> bitvec -> Z -> angle) (l:Z) (h:Z) (l':Z) (h':Z)
(b:bitvec -> bitvec -> Z -> Z) (r:Z),
(correct_path_sum_i c a l h b r) ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = r) ->
((ang_sum ((a x) y) l h) = (ang_sum ((a' x) y) l' h'))) ->
correct_path_sum_i c a' l' h' b r.
Axiom replace_ang_ind_i_eq :
forall (c:circuit) (a:bitvec -> bitvec -> Z -> angle)
(a':bitvec -> bitvec -> Z -> angle) (l:Z) (h:Z)
(b:bitvec -> bitvec -> Z -> Z) (r:Z),
(correct_path_sum_i c a l h b r) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = (width c)) ->
((length y) = r) -> ((l <= i)%Z /\ (i < h)%Z) ->
((((a x) y) i) = (((a' x) y) i))) ->
correct_path_sum_i c a' l h b r.
Axiom replace_ket_i :
forall (c:circuit) (a:bitvec -> bitvec -> Z -> angle) (l:Z) (h:Z)
(b:bitvec -> bitvec -> Z -> Z) (b':bitvec -> bitvec -> Z -> Z) (r:Z),
(correct_path_sum_i c a l h b r) ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = r) -> ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
((((b x) y) i) = (((b' x) y) i))) ->
correct_path_sum_i c a l h b' r.
Axiom set_sum_i_sim :
forall (c:circuit) (a:bitvec -> bitvec -> Z -> angle)
(a':bitvec -> bitvec -> Z -> angle) (l:Z) (h:Z) (l':Z) (h':Z)
(b:bitvec -> bitvec -> Z -> Z) (b':bitvec -> bitvec -> Z -> Z) (r:Z)
(r':Z),
(correct_path_sum_i c a l h b r) ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
((length y) = r) ->
((ang_sum ((a x) y) l h) = (ang_sum ((a' x) y) l' h'))) ->
(forall (x:bitvec) (y:bitvec) (i:Z), ((length x) = (width c)) ->
((length y) = r) -> ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
((((b x) y) i) = (((b' x) y) i))) ->
(r = r') -> correct_path_sum_i c a' l' h' b' r'.
Axiom set_correct_path_sum_i_cardone :
forall (c:circuit) (a:bitvec -> bitvec -> Z -> angle) (l:Z) (h:Z) (l':Z)
(h':Z) (b:bitvec -> bitvec -> Z -> Z) (r:Z),
(correct_path_sum_i c a l h b r) -> ((l' + 1%Z)%Z = h') ->
correct_path_sum_i c
(fun (x:bitvec) (y:bitvec) (us:Z) =>
(ang_sum (fun (j:Z) => (((a x) y) j)) l h))
l' h' b r.
Axiom set_sem_by_sim_i :
forall (c:circuit) (a:bitvec -> bitvec -> Z -> angle) (bound:Z)
(k:bitvec -> bitvec -> Z -> Z) (x:matrix t) (f:bitvec -> matrix t),
(is_a_ket_basis_elt x) -> (is_a_ket_l x (width c)) ->
(bound = (ang_ind_bound c)) ->
(forall (x1:bitvec) (y:bitvec), forall (i:Z), ((length x1) = (width c)) ->
((length y) = (range c)) -> ((0%Z <= i)%Z /\ (i < bound)%Z) ->
((ang_ind_i c x1 y i) = (((a x1) y) i))) ->
(forall (x1:bitvec) (y:bitvec) (i:Z), ((length x1) = (width c)) ->
((length y) = (range c)) -> ((0%Z <= i)%Z /\ (i < (width c))%Z) ->
((((k x1) y) i) = (basis_ket_i c x1 y i))) ->
(forall (y:bitvec), ((length y) = (range c)) ->
((f y) =
(infix_asdtdt (ang_exp (ang_sum ((a (ket_to_bv x)) y) 0%Z bound))
(bv_to_ket (make_bv ((k (ket_to_bv x)) y) (width c)))))) ->
sem c x
(infix_asdtdt (pow_inv_sqrt_2 (range c))
(ket_sum_l (n_bvs (range c)) f (width c))).
Axiom set_correct_path_sum_by_i :
forall (c:circuit) (a:bitvec -> bitvec -> Z -> angle) (l:Z) (h:Z)
(k:bitvec -> bitvec -> Z -> Z) (range1:Z),
(correct_path_sum_i c a l h k range1) ->
correct_path_sum c
(fun (x:bitvec) (y:bitvec) => (ang_sum (fun (i:Z) => (((a x) y) i)) l h))
(fun (x:bitvec) (y:bitvec) =>
(make_bv (fun (i:Z) => (((k x) y) i)) (width c)))
range1.
Parameter place: circuit -> Z -> Z -> circuit.
Parameter fc11: circuit -> Z -> bitvec -> bitvec -> Z -> Z.
Axiom fc_def11 :
forall (c:circuit) (k:Z) (x:bitvec) (y:bitvec) (i:Z),
(((k <= i)%Z /\ (i < (k + (width c))%Z)%Z) ->
(((fc11 c k x y) i) = (basis_ket_i c (htpart x k (width c)) y (i - k)%Z))) /\
(~ ((k <= i)%Z /\ (i < (k + (width c))%Z)%Z) ->
(((fc11 c k x y) i) = ((getbv x) i))).
Axiom place_spec :
forall (c:circuit) (k:Z) (n:Z), (k >= 0%Z)%Z ->
(n >= ((width c) + k)%Z)%Z ->
((ancillas (place c k n)) = (ancillas c)) /\
(((size (place c k n)) = (size c)) /\
(((range (place c k n)) = (range c)) /\
(((width (place c k n)) = n) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = n) ->
((length y) = (range c)) -> ((0%Z <= i)%Z /\ (i < n)%Z) ->
(((k <= i)%Z /\ (i < (k + (width c))%Z)%Z) ->
((basis_ket_i (place c k n) x y i) =
(basis_ket_i c (htpart x k (width c)) y (i - k)%Z))) /\
(~ ((k <= i)%Z /\ (i < (k + (width c))%Z)%Z) ->
((basis_ket_i (place c k n) x y i) = ((getbv x) i)))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = (range c)) ->
((basis_ket (place c k n) x y) = (make_bv (fc11 c k x y) n))) /\
forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = (ang_ind_bound c)) ->
((ang_ind (place c k n) x y) = (ang_ind c (htpart x k (width c)) y))))))).
Parameter place_i:
circuit -> Z -> Z -> (bitvec -> bitvec -> Z -> angle) -> Z -> Z ->
(bitvec -> bitvec -> Z -> Z) -> Z -> circuit.
Parameter fc12:
circuit -> Z -> (bitvec -> bitvec -> Z -> Z) -> bitvec -> bitvec -> Z -> Z.
Axiom fc_def12 :
forall (c:circuit) (k:Z) (b:bitvec -> bitvec -> Z -> Z) (x:bitvec)
(y:bitvec) (i:Z),
(((k <= i)%Z /\ (i < (k + (width c))%Z)%Z) ->
(((((fc12 c k b) x) y) i) = (((b (htpart x k (width c))) y) (i - k)%Z))) /\
(~ ((k <= i)%Z /\ (i < (k + (width c))%Z)%Z) ->
(((((fc12 c k b) x) y) i) = ((getbv x) i))).
Axiom place_i_spec :
forall (c:circuit) (k:Z) (n:Z) (a:bitvec -> bitvec -> Z -> angle) (l:Z)
(h:Z) (b:bitvec -> bitvec -> Z -> Z) (r:Z),
(k >= 0%Z)%Z -> (n >= ((width c) + k)%Z)%Z -> (l < h)%Z ->
(correct_path_sum_i c a l h b r) ->
((width (place_i c k n a l h b r)) = n) /\
((correct_path_sum_i (place_i c k n a l h b r)
(fun (x:bitvec) (y:bitvec) (i:Z) => (((a (htpart x k (width c))) y) i)) l
h (fc12 c k b) r) /\
((place_i c k n a l h b r) = (place c k n))).
Parameter place_spec_i:
circuit -> Z -> Z -> (bitvec -> bitvec -> Z -> angle) ->
(bitvec -> bitvec -> Z -> angle) -> Z -> Z ->
(bitvec -> bitvec -> Z -> Z) -> (bitvec -> bitvec -> Z -> Z) -> Z ->
Z -> circuit.
Axiom place_spec_i_def :
forall (c:circuit) (k:Z) (n:Z) (ase:bitvec -> bitvec -> Z -> angle)
(a:bitvec -> bitvec -> Z -> angle) (l:Z) (h:Z)
(bse:bitvec -> bitvec -> Z -> Z) (b:bitvec -> bitvec -> Z -> Z) (rse:Z)
(r:Z),
(k >= 0%Z)%Z -> (n >= ((width c) + k)%Z)%Z -> (l < h)%Z -> (rse = r) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = n) ->
((length y) = rse) -> ((k <= i)%Z /\ (i < (k + (width c))%Z)%Z) ->
((((bse x) y) i) = (((b (htpart x k (width c))) y) (i - k)%Z))) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = n) ->
((length y) = rse) -> ((0%Z <= i)%Z /\ (i < k)%Z) ->
((((bse x) y) i) = ((getbv x) i))) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = n) ->
((length y) = rse) -> (((k + (width c))%Z <= i)%Z /\ (i < n)%Z) ->
((((bse x) y) i) = ((getbv x) i))) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = n) ->
((length y) = rse) -> ((l <= i)%Z /\ (i < h)%Z) ->
((((ase x) y) i) = (((a (htpart x k (width c))) y) i))) ->
(correct_path_sum_i c a l h b r) ->
((place_spec_i c k n ase a l h bse b rse r) = (place_i c k n a l h b r)).
Axiom place_spec_i_spec :
forall (c:circuit) (k:Z) (n:Z) (ase:bitvec -> bitvec -> Z -> angle)
(a:bitvec -> bitvec -> Z -> angle) (l:Z) (h:Z)
(bse:bitvec -> bitvec -> Z -> Z) (b:bitvec -> bitvec -> Z -> Z) (rse:Z)
(r:Z),
(k >= 0%Z)%Z -> (n >= ((width c) + k)%Z)%Z -> (l < h)%Z -> (rse = r) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = n) ->
((length y) = rse) -> ((k <= i)%Z /\ (i < (k + (width c))%Z)%Z) ->
((((bse x) y) i) = (((b (htpart x k (width c))) y) (i - k)%Z))) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = n) ->
((length y) = rse) -> ((0%Z <= i)%Z /\ (i < k)%Z) ->
((((bse x) y) i) = ((getbv x) i))) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = n) ->
((length y) = rse) -> (((k + (width c))%Z <= i)%Z /\ (i < n)%Z) ->
((((bse x) y) i) = ((getbv x) i))) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = n) ->
((length y) = rse) -> ((l <= i)%Z /\ (i < h)%Z) ->
((((ase x) y) i) = (((a (htpart x k (width c))) y) i))) ->
(correct_path_sum_i c a l h b r) ->
((width (place_spec_i c k n ase a l h bse b rse r)) = n) /\
(((place_spec_i c k n ase a l h bse b rse r) = (place c k n)) /\
(correct_path_sum_i (place_spec_i c k n ase a l h bse b rse r) ase l h bse
rse)).
Parameter fc13:
circuit -> Z -> (bitvec -> bitvec -> bitvec) -> bitvec -> bitvec -> Z -> Z.
Axiom fc_def13 :
forall (c:circuit) (k:Z) (b:bitvec -> bitvec -> bitvec) (x:bitvec)
(y:bitvec) (i:Z),
(((k <= i)%Z /\ (i < (k + (width c))%Z)%Z) ->
(((fc13 c k b x y) i) =
((getbv ((b (htpart x k (width c))) y)) (i - k)%Z))) /\
(~ ((k <= i)%Z /\ (i < (k + (width c))%Z)%Z) ->
(((fc13 c k b x y) i) = ((getbv x) i))).
Axiom place_comp_scheme :
forall (c:circuit) (k:Z) (n:Z) (a:bitvec -> bitvec -> angle)
(b:bitvec -> bitvec -> bitvec) (r:Z),
(k >= 0%Z)%Z -> (n >= ((width c) + k)%Z)%Z -> (correct_path_sum c a b r) ->
correct_path_sum (place c k n)
(fun (x:bitvec) (y:bitvec) => ((a (htpart x k (width c))) y))
(fun (x:bitvec) (y:bitvec) => (make_bv (fc13 c k b x y) n)) r.
Axiom place_kron :
forall (c:circuit) (k:Z) (n:Z) (x:matrix t) (y:matrix t) (y':matrix t)
(z:matrix t),
(k >= 0%Z)%Z -> (n >= ((width c) + k)%Z)%Z -> (is_a_ket_l x k) ->
(is_a_ket_l y (width c)) -> (is_a_ket_l z ((n - (width c))%Z - k)%Z) ->
(sem c y y') ->
sem (place c k n) (kronecker x (kronecker y z))
(kronecker x (kronecker y' z)).
Axiom place_kron_pat :
forall (c:circuit) (k:Z) (n:Z) (x:matrix t) (y:matrix t) (y':matrix t)
(z:matrix t),
(k >= 0%Z)%Z -> (n >= ((width c) + k)%Z)%Z -> (is_a_ket_l x k) ->
(is_a_ket_l y (width c)) -> (is_a_ket_l z ((n - (width c))%Z - k)%Z) ->
((pat_sem c y) = y') ->
((pat_sem (place c k n) (kronecker x (kronecker y z))) =
(kronecker x (kronecker y' z))).
Axiom place_kron_left :
forall (c:circuit) (n:Z) (y:matrix t) (y':matrix t) (z:matrix t),
(n >= (width c))%Z -> (is_a_ket_l y (width c)) ->
(is_a_ket_l z (n - (width c))%Z) -> (sem c y y') ->
sem (place c 0%Z n) (kronecker y z) (kronecker y' z).
Axiom place_kron_left_inst :
forall (c:circuit) (n:Z) (y:matrix t) (y':matrix t) (z:matrix t),
(n >= (width c))%Z -> (is_a_ket_l y (width c)) ->
(is_a_ket_l z (n - (width c))%Z) -> ((pat_sem c y) = y') ->
((pat_sem (place c 0%Z n) (kronecker y z)) = (kronecker y' z)).
Axiom place_kron_left_basis_gen :
forall (c:circuit) (n:Z), (n >= (width c))%Z ->
forall (y:matrix t) (y':matrix t) (z:matrix t), (is_a_ket_l y (width c)) ->
(is_a_ket_basis_elt y) -> (is_a_ket_l z (n - (width c))%Z) ->
(sem c y y') -> sem (place c 0%Z n) (kronecker y z) (kronecker y' z).
Axiom place_kron_right :
forall (c:circuit) (k:Z) (n:Z) (x:matrix t) (y:matrix t) (y':matrix t),
(n = ((width c) + k)%Z) -> (is_a_ket_l x k) -> (is_a_ket_l y (width c)) ->
(sem c y y') -> sem (place c k n) (kronecker x y) (kronecker x y').
Axiom place_kron_left_gen :
forall (c:circuit) (n:Z), (n >= (width c))%Z ->
forall (y:matrix t) (y':matrix t) (z:matrix t),
(is_a_ket_l z (n - (width c))%Z) -> (sem c y y') ->
sem (place c 0%Z n) (kronecker y z) (kronecker y' z).
Axiom place_kron_right_gen :
forall (c:circuit) (k:Z) (n:Z), (n = ((width c) + k)%Z) ->
forall (y:matrix t) (y':matrix t) (x:matrix t), (is_a_ket_l x k) ->
(sem c y y') -> sem (place c k n) (kronecker x y) (kronecker x y').
Axiom place_kron_right_pat :
forall (c:circuit) (k:Z) (n:Z), (n = ((width c) + k)%Z) ->
forall (y:matrix t) (x:matrix t), (is_a_ket_l x k) ->
(is_a_ket_l y (n - k)%Z) ->
((pat_sem (place c k n) (kronecker x y)) = (kronecker x (pat_sem c y))).
Parameter cont_size: Z.
Axiom cont_size_def : (0%Z < cont_size)%Z.
Parameter cont: circuit -> Z -> Z -> Z -> circuit.
Axiom cont_spec :
forall (c:circuit) (co:Z) (ft:Z) (n:Z), ((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) ->
((size (cont c co ft n)) <= ((size c) * cont_size)%Z)%Z /\
(((ancillas (cont c co ft n)) = (ancillas c)) /\
(((range (cont c co ft n)) = (range c)) /\
(((width (cont c co ft n)) = n) /\
(((ancillas (cont c co ft n)) = (ancillas c)) /\
((forall (bv:bitvec) (y:bitvec), ((length bv) = n) ->
((length y) = (range c)) -> (((getbv bv) co) = 0%Z) ->
((basis_ket (cont c co ft n) bv y) = bv)) /\
((forall (bv:bitvec) (y:bitvec), ((length bv) = n) ->
((length y) = (range c)) -> (((getbv bv) co) = 0%Z) ->
((ang_ind (cont c co ft n) bv y) = ang_zero)) /\
((forall (bv:bitvec) (y:bitvec), forall (i:Z), ((length bv) = n) ->
((length y) = (range c)) -> ((0%Z <= i)%Z /\ (i < n)%Z) ->
(((getbv bv) co) = 1%Z) ->
(((ft <= i)%Z /\ (i < (ft + (width c))%Z)%Z) ->
((basis_ket_i (cont c co ft n) bv y i) =
(basis_ket_i c (htpart bv ft (width c)) y (i - ft)%Z))) /\
(~ ((ft <= i)%Z /\ (i < (ft + (width c))%Z)%Z) ->
((basis_ket_i (cont c co ft n) bv y i) = ((getbv bv) i)))) /\
((forall (bv:bitvec) (y:bitvec), ((length bv) = n) ->
((length y) = (range c)) -> (((getbv bv) co) = 1%Z) ->
((ang_ind (cont c co ft n) bv y) =
(ang_ind c (htpart bv ft (width c)) y))) /\
((forall (bv:bitvec), ((length bv) = n) -> ((length bv) = n) ->
(((getbv bv) co) = 0%Z) ->
sem (cont c co ft n) (bv_to_ket bv) (bv_to_ket bv)) /\
((forall (bv:bitvec), ((length bv) = n) ->
(((getbv bv) co) = 1%Z) ->
sem (cont c co ft n) (bv_to_ket bv)
(pat_sem (place c ft n) (bv_to_ket bv))) /\
((width (cont c co ft n)) = n))))))))))).
Axiom size_cont :
forall (c:circuit) (co:Z) (ft:Z) (n:Z) (s:Z),
((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) -> ((size c) <= s)%Z ->
((size (cont c co ft n)) <= (cont_size * s)%Z)%Z.
Axiom mat_cont :
forall (c:circuit) (co:Z) (ft:Z) (n:Z), ((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) ->
(forall (x:matrix t), (is_a_ket_l x n) -> (is_a_ket_basis_elt x) ->
(((getbv (ket_to_bv x)) co) = 0%Z) -> sem (cont c co ft n) x x) /\
forall (x:matrix t), (is_a_ket_l x n) -> (is_a_ket_basis_elt x) ->
(((getbv (ket_to_bv x)) co) = 1%Z) ->
sem (cont c co ft n) x (pat_sem (place c ft n) x).
Axiom pat_cont :
forall (c:circuit) (co:Z) (ft:Z) (n:Z), ((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) ->
(forall (bv:bitvec), ((length bv) = n) -> (((getbv bv) co) = 0%Z) ->
((pat_sem (cont c co ft n) (bv_to_ket bv)) = (bv_to_ket bv))) /\
forall (bv:bitvec), ((length bv) = n) -> (((getbv bv) co) = 1%Z) ->
((pat_sem (cont c co ft n) (bv_to_ket bv)) =
(pat_sem (place c ft n) (bv_to_ket bv))).
Axiom pat_cont_ketz :
forall (c:circuit) (co:Z) (ft:Z) (n:Z) (x:matrix t),
((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) -> (is_a_ket_l x n) ->
(is_a_ket_basis_elt x) -> (((getbv (ket_to_bv x)) co) = 0%Z) ->
((pat_sem (cont c co ft n) x) = x).
Axiom pat_cont_keto :
forall (c:circuit) (co:Z) (ft:Z) (n:Z) (x:matrix t),
((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) -> (is_a_ket_l x n) ->
(is_a_ket_basis_elt x) -> (((getbv (ket_to_bv x)) co) = 1%Z) ->
((pat_sem (cont c co ft n) x) = (pat_sem (place c ft n) x)).
Axiom pat_cont_ketz_gen :
forall (c:circuit) (co:Z) (ft:Z) (n:Z), ((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) -> forall (x:matrix t),
(is_a_ket_l x n) -> (is_a_ket_basis_elt x) ->
(((getbv (ket_to_bv x)) co) = 0%Z) -> ((pat_sem (cont c co ft n) x) = x).
Axiom pat_cont_keto_gen :
forall (c:circuit) (co:Z) (ft:Z) (n:Z), ((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) -> forall (x:matrix t),
(is_a_ket_l x n) -> (is_a_ket_basis_elt x) ->
(((getbv (ket_to_bv x)) co) = 1%Z) ->
((pat_sem (cont c co ft n) x) = (pat_sem (place c ft n) x)).
Axiom cont_ketz_gen :
forall (c:circuit) (co:Z) (ft:Z) (n:Z), ((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) -> forall (x:matrix t),
(is_a_ket_l x n) -> (is_a_ket_basis_elt x) ->
(((getbv (ket_to_bv x)) co) = 0%Z) -> sem (cont c co ft n) x x.
Axiom cont_keto_gen :
forall (c:circuit) (co:Z) (ft:Z) (n:Z) (f:bitvec -> matrix t),
((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
(forall (x:bitvec), ((length x) = n) ->
sem (place c ft n) (bv_to_ket x) (f x)) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) -> forall (x:bitvec),
((length x) = n) -> (((getbv x) co) = 1%Z) ->
sem (cont c co ft n) (bv_to_ket x) (f x).
Parameter diag_mat: Z -> (Z -> t) -> matrix t.
Axiom diag_mat_def :
forall (n:Z) (f:Z -> t), (n > 0%Z)%Z ->
((diag_mat n f) =
(make_f n n (fun (i:Z) (j:Z) => (infix_asdt (f i) (indic i j))))).
Axiom diag_mat_spec :
forall (n:Z) (f:Z -> t), (n > 0%Z)%Z ->
(forall (i:Z) (j:Z),
(((0%Z <= i)%Z /\ (i < n)%Z) /\ ((0%Z <= j)%Z /\ (j < n)%Z)) ->
~ (i = j) -> ((get (diag_mat n f) i j) = tzero)) /\
forall (i:Z) (j:Z),
(((0%Z <= i)%Z /\ (i < n)%Z) /\ ((0%Z <= j)%Z /\ (j < n)%Z)) -> (i = j) ->
((get (diag_mat n f) i j) = (f i)).
Axiom diag_mat_values :
forall (n:Z) (f:Z -> t) (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < n)%Z) ->
((0%Z <= j)%Z /\ (j < n)%Z) ->
((get (diag_mat n f) i j) = (infix_asdt (f i) (indic i j))).
Axiom diag_mat_eq :
forall (f:Z -> t) (g:Z -> t) (n:Z), (n > 0%Z)%Z ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) -> ((f i) = (g i))) ->
((diag_mat n f) = (diag_mat n g)).
Axiom mat_mult_diag :
forall (m:matrix t) (f:Z -> t),
((mat_mult m (diag_mat (columns m) f)) =
(make_f (rows m) (columns m)
(fun (i:Z) (j:Z) => (infix_asdt (get m i j) (f j))))).
Axiom diag_mult_mat :
forall (m:matrix t) (f:Z -> t),
((mat_mult (diag_mat (rows m) f) m) =
(make_f (rows m) (columns m)
(fun (i:Z) (j:Z) => (infix_asdt (get m i j) (f i))))).
Axiom diag_mult_diag :
forall (f:Z -> t) (g:Z -> t) (n:Z), (n > 0%Z)%Z ->
((mat_mult (diag_mat n f) (diag_mat n g)) =
(diag_mat n (fun (i:Z) => (infix_asdt (f i) (g i))))).
Axiom ind_product_re :
forall (f:Z -> Z -> t) (i:Z) (j:Z) (n:Z), (i < j)%Z -> forall (k:Z),
((0%Z <= k)%Z /\ (k < n)%Z) ->
((ind_product (fun (i1:Z) => ((f i1) k)) i (j + 1%Z)%Z) =
(infix_asdt (ind_product (fun (i1:Z) => ((f i1) k)) i j) ((f j) k))).
Axiom int_mat_diag_prod :
forall (f:Z -> Z -> t) (i:Z) (j:Z) (n:Z), (n > 0%Z)%Z -> (i <= j)%Z ->
((int_mat_prod (fun (k:Z) => (diag_mat n (f k))) i j) =
(diag_mat n
(fun (k:Z) => (ind_product (fun (l:Z) => ((f l) k)) i (j + 1%Z)%Z)))).
Parameter diag_two_mat: Z -> (Z -> Z -> Z -> t) -> matrix t.
Parameter result19: Z -> (Z -> Z -> Z -> t) -> Z -> Z -> t.
Axiom result_def19 :
forall (n:Z) (f:Z -> Z -> Z -> t) (i:Z) (j:Z),
((((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) /\
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z)) ->
((((result19 n f) i) j) =
(infix_asdt (indic (tail_bits i n) (tail_bits j n))
(((f (head_bit i n)) (head_bit j n)) (tail_bits i n))))) /\
(~ (((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) /\
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z)) ->
((((result19 n f) i) j) = tzero)).
Axiom diag_two_mat_def :
forall (n:Z) (f:Z -> Z -> Z -> t), (n >= 2%Z)%Z ->
((diag_two_mat n f) = (make_f (power 2%Z n) (power 2%Z n) (result19 n f))).
Axiom diag_two_mat_spec :
forall (n:Z) (f:Z -> Z -> Z -> t), (n >= 2%Z)%Z ->
((rows (diag_two_mat n f)) = (power 2%Z n)) /\
(((columns (diag_two_mat n f)) = (power 2%Z n)) /\
((diag_two_mat n f) =
(make_f (power 2%Z n) (power 2%Z n)
(fun (i:Z) (j:Z) =>
(infix_asdt (indic (tail_bits i n) (tail_bits j n))
(((f (head_bit i n)) (head_bit j n)) (tail_bits i n))))))).
Parameter two_bloc_diag_mat: Z -> (Z -> Z -> Z -> t) -> matrix t.
Parameter result20: Z -> (Z -> Z -> Z -> t) -> Z -> Z -> t.
Axiom result_def20 :
forall (n:Z) (f:Z -> Z -> Z -> t) (i:Z) (j:Z),
((((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) /\
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z)) ->
((((result20 n f) i) j) =
(infix_asdt (indic (head_bit i n) (head_bit j n))
(((f (head_bit i n)) (tail_bits i n)) (tail_bits j n))))) /\
(~ (((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) /\
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z)) ->
((((result20 n f) i) j) = tzero)).
Axiom two_bloc_diag_mat_def :
forall (n:Z) (f:Z -> Z -> Z -> t), (n >= 2%Z)%Z ->
((two_bloc_diag_mat n f) =
(make_f (power 2%Z n) (power 2%Z n) (result20 n f))).
Axiom two_bloc_diag_mat_spec :
forall (n:Z) (f:Z -> Z -> Z -> t), (n >= 2%Z)%Z ->
((rows (two_bloc_diag_mat n f)) = (power 2%Z n)) /\
(((columns (two_bloc_diag_mat n f)) = (power 2%Z n)) /\
((two_bloc_diag_mat n f) =
(make_f (power 2%Z n) (power 2%Z n)
(fun (i:Z) (j:Z) =>
(infix_asdt (indic (head_bit i n) (head_bit j n))
(((f (head_bit i n)) (tail_bits i n)) (tail_bits j n))))))).
Axiom two_bloc_diag_two_val :
forall (n:Z) (f:Z -> Z -> Z -> t) (g:Z -> Z -> Z -> t) (i:Z) (j:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) -> (n >= 2%Z)%Z ->
((get (mat_mult (two_bloc_diag_mat n f) (diag_two_mat n g)) i j) =
(infix_asdt (((f (head_bit i n)) (tail_bits i n)) (tail_bits j n))
(((g (head_bit i n)) (head_bit j n)) (tail_bits j n)))).
Axiom two_bloc_diag_two :
forall (n:Z) (f:Z -> Z -> Z -> t) (g:Z -> Z -> Z -> t), (n >= 2%Z)%Z ->
((mat_mult (two_bloc_diag_mat n f) (diag_two_mat n g)) =
(make_f (power 2%Z n) (power 2%Z n)
(fun (i:Z) (j:Z) =>
(infix_asdt (((f (head_bit i n)) (tail_bits i n)) (tail_bits j n))
(((g (head_bit i n)) (head_bit j n)) (tail_bits j n)))))).
Axiom two_bloc_mult_diag :
forall (n:Z) (f:Z -> Z -> Z -> t) (g:Z -> t), (n >= 2%Z)%Z ->
((mat_mult (two_bloc_diag_mat n f) (diag_mat (power 2%Z n) g)) =
(two_bloc_diag_mat n
(fun (hi:Z) (ti:Z) (tj:Z) =>
(infix_asdt (((f hi) ti) tj) (g (ht_to_int hi tj n)))))).
Axiom kronecker_scalar_distr :
forall (m:matrix t) (n:matrix t) (a:t),
((kronecker (infix_asdtdt a m) n) = (infix_asdtdt a (kronecker m n))).
Axiom kronecker_scalar_distr_r :
forall (m:matrix t) (n:matrix t) (a:t),
((kronecker m (infix_asdtdt a n)) = (infix_asdtdt a (kronecker m n))).
Axiom kronecker_scalars :
forall (m:matrix t) (n:matrix t) (a:t) (b:t),
((kronecker (infix_asdtdt a m) (infix_asdtdt b n)) =
(infix_asdtdt (infix_asdt a b) (kronecker m n))).
Parameter mat_k_id: (matrix t) -> Z -> matrix t.
Axiom mat_k_id_def :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z ->
((mat_k_id m n) = (kronecker m (identity n))).
Axiom mat_k_id_spec :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z ->
((mat_k_id m n) =
(make_f ((rows m) * (power 2%Z n))%Z ((columns m) * (power 2%Z n))%Z
(fun (i:Z) (j:Z) =>
(infix_asdt
(indic (int.EuclideanDivision.mod1 i (power 2%Z n))
(int.EuclideanDivision.mod1 j (power 2%Z n)))
(get m (int.EuclideanDivision.div i (power 2%Z n))
(int.EuclideanDivision.div j (power 2%Z n))))))).
Axiom mat_k_id_values :
forall (m:matrix t) (n:Z) (i:Z) (j:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < ((rows m) * (power 2%Z n))%Z)%Z) ->
((0%Z <= j)%Z /\ (j < ((columns m) * (power 2%Z n))%Z)%Z) ->
((get (mat_k_id m n) i j) =
(infix_asdt
(indic (int.EuclideanDivision.mod1 i (power 2%Z n))
(int.EuclideanDivision.mod1 j (power 2%Z n)))
(get m (int.EuclideanDivision.div i (power 2%Z n))
(int.EuclideanDivision.div j (power 2%Z n))))).
Axiom mat_k_id_rows :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z ->
((rows (mat_k_id m n)) = ((rows m) * (power 2%Z n))%Z).
Axiom mat_k_id_columns :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z ->
((columns (mat_k_id m n)) = ((columns m) * (power 2%Z n))%Z).
Parameter id_k_mat: (matrix t) -> Z -> matrix t.
Axiom id_k_mat_def :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z ->
((id_k_mat m n) = (kronecker (identity n) m)).
Axiom id_k_mat_spec :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z ->
((id_k_mat m n) =
(make_f ((rows m) * (power 2%Z n))%Z ((columns m) * (power 2%Z n))%Z
(fun (i:Z) (j:Z) =>
(infix_asdt
(indic (int.EuclideanDivision.div i (rows m))
(int.EuclideanDivision.div j (columns m)))
(get m (int.EuclideanDivision.mod1 i (rows m))
(int.EuclideanDivision.mod1 j (columns m))))))).
Axiom id_k_mat_values :
forall (m:matrix t) (n:Z) (i:Z) (j:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < ((rows m) * (power 2%Z n))%Z)%Z) ->
((0%Z <= j)%Z /\ (j < ((columns m) * (power 2%Z n))%Z)%Z) ->
((get (id_k_mat m n) i j) =
(infix_asdt
(indic (int.EuclideanDivision.div i (rows m))
(int.EuclideanDivision.div j (columns m)))
(get m (int.EuclideanDivision.mod1 i (rows m))
(int.EuclideanDivision.mod1 j (columns m))))).
Axiom id_k_mat_rows :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z ->
((rows (id_k_mat m n)) = ((rows m) * (power 2%Z n))%Z).
Axiom id_k_mat_columns :
forall (m:matrix t) (n:Z), (0%Z < n)%Z ->
((columns (id_k_mat m n)) = ((columns m) * (power 2%Z n))%Z).
Parameter mat_prod_k_id: (matrix t) -> (matrix t) -> Z -> matrix t.
Axiom mat_prod_k_id_def :
forall (m:matrix t) (o:matrix t) (n:Z), (0%Z <= n)%Z ->
((columns m) = (rows o)) ->
((mat_prod_k_id m o n) = (kronecker (mat_mult m o) (identity n))).
Axiom mat_prod_k_id_spec :
forall (m:matrix t) (o:matrix t) (n:Z), (0%Z <= n)%Z ->
((columns m) = (rows o)) ->
((mat_prod_k_id m o n) =
(make_f ((rows m) * (power 2%Z n))%Z ((columns o) * (power 2%Z n))%Z
(fun (i:Z) (j:Z) =>
(infix_asdt
(indic (int.EuclideanDivision.mod1 i (power 2%Z n))
(int.EuclideanDivision.mod1 j (power 2%Z n)))
(ind_sum
(fun (k:Z) =>
(infix_asdt (get m (int.EuclideanDivision.div i (power 2%Z n)) k)
(get o k (int.EuclideanDivision.div j (power 2%Z n)))))
0%Z (columns m)))))).
Parameter id_k_mat_prod: (matrix t) -> (matrix t) -> Z -> matrix t.
Axiom id_k_mat_prod_def :
forall (m:matrix t) (o:matrix t) (n:Z), (0%Z <= n)%Z ->
((columns m) = (rows o)) ->
((id_k_mat_prod m o n) = (kronecker (identity n) (mat_mult m o))).
Axiom id_k_mat_prod_spec :
forall (m:matrix t) (o:matrix t) (n:Z), (0%Z <= n)%Z ->
((columns m) = (rows o)) ->
((id_k_mat_prod m o n) =
(make_f ((rows m) * (power 2%Z n))%Z ((columns o) * (power 2%Z n))%Z
(fun (i:Z) (j:Z) =>
(infix_asdt
(indic (int.EuclideanDivision.div i (rows m))
(int.EuclideanDivision.div j (columns o)))
(ind_sum
(fun (k:Z) =>
(infix_asdt (get m (int.EuclideanDivision.mod1 i (rows m)) k)
(get o k (int.EuclideanDivision.mod1 j (columns o)))))
0%Z (columns m)))))).
Axiom filter_sum_mod_indic :
forall (v:Z) (n:Z) (p:Z) (g:Z -> t), (n > 0%Z)%Z -> (v > 0%Z)%Z ->
((0%Z <= p)%Z /\ (p < v)%Z) ->
((sum (to_fset 0%Z (v * n)%Z)
(fun (k:Z) =>
(infix_asdt (indic (int.EuclideanDivision.mod1 k v) p)
(g (int.EuclideanDivision.div k v)))))
= (sum (to_fset 0%Z n) g)).
Axiom filter_sum_indic_div :
forall (v:Z) (n:Z) (p:Z) (g:Z -> t), (n > 0%Z)%Z -> (v > 0%Z)%Z ->
((0%Z <= p)%Z /\ (p < n)%Z) ->
((sum (to_fset 0%Z (v * n)%Z)
(fun (k:Z) =>
(infix_asdt (g (int.EuclideanDivision.mod1 k v))
(indic (int.EuclideanDivision.div k v) p))))
= (sum (to_fset 0%Z v) g)).
Axiom filtered_ind_sum_mod_indic :
forall (v:Z) (n:Z) (p:Z) (g:Z -> t), (n > 0%Z)%Z -> (v > 0%Z)%Z ->
((0%Z <= p)%Z /\ (p < v)%Z) ->
((ind_sum
(fun (k:Z) =>
(infix_asdt (indic (int.EuclideanDivision.mod1 k v) p)
(g (int.EuclideanDivision.div k v))))
0%Z (v * n)%Z)
= (ind_sum g 0%Z n)).
Axiom filtered_ind_sum_indic_div :
forall (v:Z) (n:Z) (p:Z) (g:Z -> t), (n > 0%Z)%Z -> (v > 0%Z)%Z ->
((0%Z <= p)%Z /\ (p < n)%Z) ->
((ind_sum
(fun (k:Z) =>
(infix_asdt (g (int.EuclideanDivision.mod1 k v))
(indic (int.EuclideanDivision.div k v) p)))
0%Z (v * n)%Z)
= (ind_sum g 0%Z v)).
Axiom prod_mat_k_id_pre :
forall (m:matrix t) (o:matrix t) (i:Z) (j:Z) (n:Z), (0%Z <= n)%Z ->
((columns m) = (rows o)) ->
((0%Z <= i)%Z /\ (i < ((rows m) * (power 2%Z n))%Z)%Z) ->
((0%Z <= j)%Z /\ (j < ((columns o) * (power 2%Z n))%Z)%Z) ->
((get (mat_mult (mat_k_id m n) (mat_k_id o n)) i j) =
(infix_asdt
(indic (int.EuclideanDivision.mod1 i (power 2%Z n))
(int.EuclideanDivision.mod1 j (power 2%Z n)))
(ind_sum
(fun (k:Z) =>
(infix_asdt (get m (int.EuclideanDivision.div i (power 2%Z n)) k)
(get o k (int.EuclideanDivision.div j (power 2%Z n)))))
0%Z (columns m)))).
Parameter prod_mat_k_id: (matrix t) -> (matrix t) -> Z -> matrix t.
Axiom prod_mat_k_id_def :
forall (m:matrix t) (o:matrix t) (n:Z), (0%Z <= n)%Z ->
((columns m) = (rows o)) ->
((prod_mat_k_id m o n) = (mat_mult (mat_k_id m n) (mat_k_id o n))).
Axiom prod_mat_k_id_spec :
forall (m:matrix t) (o:matrix t) (n:Z), (0%Z <= n)%Z ->
((columns m) = (rows o)) ->
((prod_mat_k_id m o n) =
(make_f ((rows m) * (power 2%Z n))%Z ((columns o) * (power 2%Z n))%Z
(fun (i:Z) (j:Z) =>
(infix_asdt
(indic (int.EuclideanDivision.mod1 i (power 2%Z n))
(int.EuclideanDivision.mod1 j (power 2%Z n)))
(ind_sum
(fun (k:Z) =>
(infix_asdt (get m (int.EuclideanDivision.div i (power 2%Z n)) k)
(get o k (int.EuclideanDivision.div j (power 2%Z n)))))
0%Z (columns m)))))).
Axiom prod_mat_k_id_dec :
forall (m:matrix t) (o:matrix t) (n:Z), (0%Z <= n)%Z ->
((columns m) = (rows o)) -> ((prod_mat_k_id m o n) = (mat_prod_k_id m o n)).
Axiom k_id_prod_mat_pre :
forall (m:matrix t) (o:matrix t) (i:Z) (j:Z) (n:Z), (0%Z <= n)%Z ->
((columns m) = (rows o)) ->
((0%Z <= i)%Z /\ (i < ((rows m) * (power 2%Z n))%Z)%Z) ->
((0%Z <= j)%Z /\ (j < ((columns o) * (power 2%Z n))%Z)%Z) ->
((get (mat_mult (id_k_mat m n) (id_k_mat o n)) i j) =
(infix_asdt
(indic (int.EuclideanDivision.div i (rows m))
(int.EuclideanDivision.div j (columns o)))
(ind_sum
(fun (k:Z) =>
(infix_asdt (get m (int.EuclideanDivision.mod1 i (rows m)) k)
(get o k (int.EuclideanDivision.mod1 j (columns o)))))
0%Z (columns m)))).
Parameter k_id_prod_mat: (matrix t) -> (matrix t) -> Z -> matrix t.
Axiom k_id_prod_mat_def :
forall (m:matrix t) (o:matrix t) (n:Z), (0%Z <= n)%Z ->
((columns m) = (rows o)) ->
((k_id_prod_mat m o n) = (mat_mult (id_k_mat m n) (id_k_mat o n))).
Axiom k_id_prod_mat_spec :
forall (m:matrix t) (o:matrix t) (n:Z), (0%Z <= n)%Z ->
((columns m) = (rows o)) ->
((k_id_prod_mat m o n) =
(make_f ((rows m) * (power 2%Z n))%Z ((columns o) * (power 2%Z n))%Z
(fun (i:Z) (j:Z) =>
(infix_asdt
(indic (int.EuclideanDivision.div i (rows m))
(int.EuclideanDivision.div j (columns o)))
(ind_sum
(fun (k:Z) =>
(infix_asdt (get m (int.EuclideanDivision.mod1 i (rows m)) k)
(get o k (int.EuclideanDivision.mod1 j (columns o)))))
0%Z (columns m)))))).
Axiom k_id_prod_mat_dec :
forall (m:matrix t) (o:matrix t) (n:Z), (0%Z <= n)%Z ->
((columns m) = (rows o)) -> ((k_id_prod_mat m o n) = (id_k_mat_prod m o n)).
Axiom split_ne_pre :
forall (m1:matrix t) (m2:matrix t) (nc1:Z) (nc2:Z) (nr1:Z) (nr2:Z)
(i:Z) (j:Z),
(0%Z <= nr1)%Z -> (0%Z <= nr2)%Z -> (0%Z <= nc1)%Z -> (0%Z <= nc2)%Z ->
((columns m1) = (power 2%Z nc1)) -> ((columns m2) = (power 2%Z nc2)) ->
((rows m1) = (power 2%Z nr1)) -> ((rows m2) = (power 2%Z nr2)) ->
((0%Z <= i)%Z /\ (i < ((power 2%Z nr1) * (power 2%Z nr2))%Z)%Z) ->
((0%Z <= j)%Z /\ (j < ((power 2%Z nc1) * (power 2%Z nc2))%Z)%Z) ->
((get (mat_mult (id_k_mat m1 nr2) (mat_k_id m2 nc1)) i j) =
(get (kronecker m2 m1) i j)).
Axiom split_nw_pre :
forall (m1:matrix t) (m2:matrix t) (nc1:Z) (nc2:Z) (nr1:Z) (nr2:Z)
(i:Z) (j:Z),
(0%Z <= nr1)%Z -> (0%Z <= nr2)%Z -> (0%Z <= nc1)%Z -> (0%Z <= nc2)%Z ->
((columns m1) = (power 2%Z nc1)) -> ((columns m2) = (power 2%Z nc2)) ->
((rows m1) = (power 2%Z nr1)) -> ((rows m2) = (power 2%Z nr2)) ->
((0%Z <= i)%Z /\ (i < ((power 2%Z nr1) * (power 2%Z nr2))%Z)%Z) ->
((0%Z <= j)%Z /\ (j < ((power 2%Z nc1) * (power 2%Z nc2))%Z)%Z) ->
((get (mat_mult (mat_k_id m1 nr2) (id_k_mat m2 nc1)) i j) =
(get (kronecker m1 m2) i j)).
Axiom split_ne :
forall (m1:matrix t) (m2:matrix t) (nc1:Z) (nc2:Z) (nr1:Z) (nr2:Z),
(0%Z <= nr1)%Z -> (0%Z <= nr2)%Z -> (0%Z <= nc1)%Z -> (0%Z <= nc2)%Z ->
((columns m1) = (power 2%Z nc1)) -> ((columns m2) = (power 2%Z nc2)) ->
((rows m1) = (power 2%Z nr1)) -> ((rows m2) = (power 2%Z nr2)) ->
((mat_mult (id_k_mat m1 nr2) (mat_k_id m2 nc1)) = (kronecker m2 m1)).
Axiom split_nw :
forall (m1:matrix t) (m2:matrix t) (nc1:Z) (nc2:Z) (nr1:Z) (nr2:Z),
(0%Z <= nr1)%Z -> (0%Z <= nr2)%Z -> (0%Z <= nc1)%Z -> (0%Z <= nc2)%Z ->
((columns m1) = (power 2%Z nc1)) -> ((columns m2) = (power 2%Z nc2)) ->
((rows m1) = (power 2%Z nr1)) -> ((rows m2) = (power 2%Z nr2)) ->
((mat_mult (mat_k_id m1 nr2) (id_k_mat m2 nc1)) = (kronecker m1 m2)).
Axiom shift_k_id :
forall (m1:matrix t) (m2:matrix t) (nc1:Z) (nc2:Z) (nr1:Z) (nr2:Z),
(0%Z <= nr1)%Z -> (0%Z <= nr2)%Z -> (0%Z <= nc1)%Z -> (0%Z <= nc2)%Z ->
((columns m1) = (power 2%Z nc1)) -> ((columns m2) = (power 2%Z nc2)) ->
((rows m1) = (power 2%Z nr1)) -> ((rows m2) = (power 2%Z nr2)) ->
((mat_mult (mat_k_id m1 nr2) (id_k_mat m2 nc1)) =
(mat_mult (id_k_mat m2 nr1) (mat_k_id m1 nc2))).
Axiom kronecker_mult_commut :
forall (a:matrix t) (b:matrix t) (c:matrix t) (d:matrix t) (ra:Z) (ca:Z)
(cc:Z) (rb:Z) (cb:Z) (cd:Z),
(0%Z <= ra)%Z -> (0%Z <= ca)%Z -> (0%Z <= cc)%Z -> (0%Z <= rb)%Z ->
(0%Z <= cb)%Z -> (0%Z <= cd)%Z -> ((rows a) = (power 2%Z ra)) ->
((columns a) = (power 2%Z ca)) -> ((rows c) = (power 2%Z ca)) ->
((columns c) = (power 2%Z cc)) -> ((rows b) = (power 2%Z rb)) ->
((columns b) = (power 2%Z cb)) -> ((rows d) = (power 2%Z cb)) ->
((columns d) = (power 2%Z cd)) ->
((mat_mult (kronecker a b) (kronecker c d)) =
(kronecker (mat_mult a c) (mat_mult b d))).
Parameter isa_square: (matrix t) -> Prop.
Axiom isa_square_def :
forall (m:matrix t), (isa_square m) <-> ((rows m) = (columns m)).
Parameter pow2dim: (matrix t) -> Prop.
Axiom pow2dim_def :
forall (m:matrix t),
(pow2dim m) <->
exists i:Z, exists j:Z,
((rows m) = (power 2%Z i)) /\ ((columns m) = (power 2%Z j)).
Parameter pow2dim_square: (matrix t) -> Prop.
Axiom pow2dim_square_def :
forall (m:matrix t),
(pow2dim_square m) <->
exists i:Z, ((rows m) = (power 2%Z i)) /\ ((columns m) = (power 2%Z i)).
Axiom pow_2dim_kets : forall (m:matrix t), (is_a_ket m) -> pow2dim m.
Parameter lnr: (matrix t) -> Z.
Axiom lnr_spec :
forall (m:matrix t), (pow2dim m) ->
((rows m) = (power 2%Z (lnr m))) /\ ((lnr m) >= 0%Z)%Z.
Parameter lnc: (matrix t) -> Z.
Axiom lnc_spec :
forall (m:matrix t), (pow2dim m) ->
((columns m) = (power 2%Z (lnc m))) /\ ((lnc m) >= 0%Z)%Z.
Axiom get_pow2dim :
forall (m:matrix t), (pow2dim m) ->
exists i:Z, exists j:Z,
((rows m) = (power 2%Z i)) /\ ((columns m) = (power 2%Z j)).
Axiom set_pow2dim :
forall (m:matrix t),
(exists i:Z, exists j:Z,
((rows m) = (power 2%Z i)) /\ ((columns m) = (power 2%Z j))) ->
pow2dim m.
Axiom get_pow2dim_elt :
forall (m:matrix t) (i:Z) (j:Z), (pow2dim m) -> ((lnr m) = i) ->
((lnc m) = j) ->
((rows m) = (power 2%Z i)) /\ ((columns m) = (power 2%Z j)).
Axiom set_pow2dim_elt :
forall (m:matrix t) (i:Z) (j:Z), (0%Z <= i)%Z -> (0%Z <= j)%Z ->
((rows m) = (power 2%Z i)) -> ((columns m) = (power 2%Z j)) ->
(pow2dim m) /\ (((lnr m) = i) /\ ((lnc m) = j)).
Parameter mat_size: (matrix t) -> Z.
Axiom mat_size_def :
forall (m:matrix t), (isa_square m) -> ((mat_size m) = (rows m)).
Axiom mat_size_spec :
forall (m:matrix t), (isa_square m) ->
((mat_size m) = (rows m)) /\ ((mat_size m) = (columns m)).
Axiom get_square :
forall (m:matrix t), (isa_square m) -> ((rows m) = (columns m)).
Axiom set_square :
forall (m:matrix t), ((rows m) = (columns m)) -> isa_square m.
Axiom set_square_elt :
forall (m:matrix t) (i:Z), ((rows m) = i) -> ((columns m) = i) ->
(isa_square m) /\ ((mat_size m) = i).
Axiom get_square_elt :
forall (m:matrix t) (i:Z), (isa_square m) -> ((mat_size m) = i) ->
((rows m) = i) /\ ((columns m) = i).
Axiom pow2dim_square_dec :
forall (m:matrix t), (isa_square m) -> (pow2dim m) -> pow2dim_square m.
Axiom dec_pow2dim_square :
forall (m:matrix t), (pow2dim_square m) -> (isa_square m) /\ (pow2dim m).
Parameter ln_size: (matrix t) -> Z.
Axiom ln_size_def :
forall (m:matrix t), (pow2dim_square m) -> ((ln_size m) = (lnr m)).
Axiom ln_size_spec :
forall (m:matrix t), (pow2dim_square m) ->
((ln_size m) = (lnc m)) /\
(((rows m) = (power 2%Z (ln_size m))) /\
((columns m) = (power 2%Z (ln_size m)))).
Axiom set_ln_size_lnc :
forall (m:matrix t) (i:Z), (pow2dim_square m) -> ((lnc m) = i) ->
((ln_size m) = i).
Axiom set_ln_size_lnr :
forall (m:matrix t) (i:Z), (pow2dim_square m) -> ((lnr m) = i) ->
((ln_size m) = i).
Axiom set_ln_size_columns :
forall (m:matrix t) (i:Z), (0%Z <= i)%Z -> (pow2dim_square m) ->
((columns m) = (power 2%Z i)) -> ((ln_size m) = i).
Axiom set_ln_size_rows :
forall (m:matrix t) (i:Z), (0%Z <= i)%Z -> (pow2dim_square m) ->
((rows m) = (power 2%Z i)) -> ((ln_size m) = i).
Axiom set_pow2dim_square :
forall (m:matrix t),
(exists i:Z, ((rows m) = (columns m)) /\ ((columns m) = (power 2%Z i))) ->
pow2dim_square m.
Axiom set_pow2dim_square_elt :
forall (m:matrix t) (i:Z), (0%Z <= i)%Z ->
(((rows m) = (columns m)) /\ ((columns m) = (power 2%Z i))) ->
(pow2dim_square m) /\ ((ln_size m) = i).
Axiom get_pow2dim_square_elt :
forall (m:matrix t) (i:Z), (pow2dim_square m) -> ((ln_size m) = i) ->
((rows m) = (power 2%Z i)) /\ ((columns m) = (power 2%Z i)).
Axiom kronecker_mult_commut_p :
forall (a:matrix t) (b:matrix t) (c:matrix t) (d:matrix t),
((columns a) = (rows c)) -> ((columns b) = (rows d)) -> (pow2dim a) ->
(pow2dim b) -> (pow2dim c) -> (pow2dim d) ->
((mat_mult (kronecker a b) (kronecker c d)) =
(kronecker (mat_mult a c) (mat_mult b d))).
Axiom kronecker_mult_commut_p_quant :
forall (a:matrix t) (b:matrix t), (pow2dim a) -> (pow2dim b) ->
forall (c:matrix t) (d:matrix t), ((columns a) = (rows c)) ->
((columns b) = (rows d)) -> (pow2dim c) -> (pow2dim d) ->
((mat_mult (kronecker a b) (kronecker c d)) =
(kronecker (mat_mult a c) (mat_mult b d))).
Axiom kronecker_add_distr_l :
forall (m:matrix t) (n:matrix t) (o:matrix t), ((rows m) = (rows n)) ->
((columns m) = (columns n)) ->
((rows (kronecker (add_mat m n) o)) = ((rows m) * (rows o))%Z) /\
(((columns (kronecker (add_mat m n) o)) = ((columns m) * (columns o))%Z) /\
((kronecker (add_mat m n) o) = (add_mat (kronecker m o) (kronecker n o)))).
Axiom kronecker_add_distr_r :
forall (m:matrix t) (n:matrix t) (o:matrix t), ((rows m) = (rows n)) ->
((columns m) = (columns n)) ->
((kronecker o (add_mat m n)) = (add_mat (kronecker o m) (kronecker o n))) /\
(((rows (kronecker o (add_mat m n))) = ((rows m) * (rows o))%Z) /\
((columns (kronecker o (add_mat m n))) = ((columns m) * (columns o))%Z)).
Axiom kronecker_sum_distr_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (m:matrix t), (constant_size s f) ->
((cardinal s) > 0%Z)%Z ->
(((columns (mat_sum s (fun (k:a) => (kronecker (f k) m)))) =
(columns ((fun (k:a) => (kronecker (f k) m)) (choose s)))) /\
((columns ((fun (k:a) => (kronecker (f k) m)) (choose s))) =
((columns m) * (columns (f (choose s))))%Z)) /\
((((rows (mat_sum s (fun (k:a) => (kronecker (f k) m)))) =
(rows ((fun (k:a) => (kronecker (f k) m)) (choose s)))) /\
((rows ((fun (k:a) => (kronecker (f k) m)) (choose s))) =
((rows m) * (rows (f (choose s))))%Z)) /\
((kronecker (mat_sum s f) m) =
(mat_sum s (fun (k:a) => (kronecker (f k) m))))).
Axiom kronecker_sum_distr_r :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (m:matrix t), (constant_size s f) ->
((cardinal s) > 0%Z)%Z ->
(((columns (mat_sum s (fun (k:a) => (kronecker m (f k))))) =
(columns ((fun (k:a) => (kronecker m (f k))) (choose s)))) /\
((columns ((fun (k:a) => (kronecker m (f k))) (choose s))) =
((columns m) * (columns (f (choose s))))%Z)) /\
((((rows (mat_sum s (fun (k:a) => (kronecker m (f k))))) =
(rows ((fun (k:a) => (kronecker m (f k))) (choose s)))) /\
((rows ((fun (k:a) => (kronecker m (f k))) (choose s))) =
((rows m) * (rows (f (choose s))))%Z)) /\
((kronecker m (mat_sum s f)) =
(mat_sum s (fun (k:a) => (kronecker m (f k)))))).
Axiom mat_sum_scalar1 :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (a1:t), (constant_size s f) ->
((cardinal s) > 0%Z)%Z ->
((mat_sum s (fun (k:a) => (infix_asdtdt a1 (f k)))) =
(infix_asdtdt a1 (mat_sum s f))).
Axiom kronecker_sum_distr_sc :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (m:matrix t) (a1:t),
(constant_size s f) -> ((cardinal s) > 0%Z)%Z ->
((mat_sum s (fun (k:a) => (kronecker (infix_asdtdt a1 (f k)) m))) =
(infix_asdtdt a1 (mat_sum s (fun (k:a) => (kronecker (f k) m))))).
Axiom kronecker_ket_sum_distr_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (m:matrix t) (l1:Z) (l2:Z),
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l1) -> (is_a_ket_l m l2) ->
((cardinal s) > 0%Z)%Z ->
(is_a_ket_l (ket_sum_l s (fun (k:a) => (kronecker (f k) m)) (l1 + l2)%Z)
(l1 + l2)%Z) /\
((kronecker (ket_sum_l s f l1) m) =
(ket_sum_l s (fun (k:a) => (kronecker (f k) m)) (l1 + l2)%Z)).
Axiom kronecker_ket_sum_distr_l_nol :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (m:matrix t) (l1:Z),
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l1) -> (is_a_ket m) ->
((cardinal s) > 0%Z)%Z ->
(is_a_ket_l
(ket_sum_l s (fun (k:a) => (kronecker (f k) m)) (l1 + (ket_length m))%Z)
(l1 + (ket_length m))%Z) /\
((kronecker (ket_sum_l s f l1) m) =
(ket_sum_l s (fun (k:a) => (kronecker (f k) m)) (l1 + (ket_length m))%Z)).
Axiom kronecker_ket_sum_distr_l_rew :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (m:matrix t) (l1:Z),
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l1) -> (is_a_ket m) ->
((cardinal s) > 0%Z)%Z ->
((kronecker (ket_sum_l s f l1) m) =
(ket_sum_l s (fun (k:a) => (kronecker (f k) m)) (l1 + (ket_length m))%Z)).
Axiom kronecker_ket_sum_distr_r :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (m:matrix t) (l1:Z) (l2:Z),
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l1) -> (is_a_ket_l m l2) ->
((cardinal s) > 0%Z)%Z ->
(is_a_ket_l (ket_sum_l s (fun (k:a) => (kronecker m (f k))) (l1 + l2)%Z)
(l1 + l2)%Z) /\
((kronecker m (ket_sum_l s f l1)) =
(ket_sum_l s (fun (k:a) => (kronecker m (f k))) (l1 + l2)%Z)).
Axiom kronecker_ket_sum_distr_l_rev :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (m:matrix t) (l1:Z) (l2:Z),
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l1) -> (is_a_ket_l m l2) ->
((cardinal s) > 0%Z)%Z ->
(is_a_ket_l (ket_sum_l s (fun (k:a) => (kronecker (f k) m)) (l1 + l2)%Z)
(l1 + l2)%Z) /\
((ket_sum_l s (fun (k:a) => (kronecker (f k) m)) (l1 + l2)%Z) =
(kronecker (ket_sum_l s f l1) m)).
Axiom kronecker_ket_sum_distr_r_rev :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (m:matrix t) (l1:Z) (l2:Z),
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l1) -> (is_a_ket_l m l2) ->
((cardinal s) > 0%Z)%Z ->
(is_a_ket_l (ket_sum_l s (fun (k:a) => (kronecker m (f k))) (l1 + l2)%Z)
(l1 + l2)%Z) /\
((ket_sum_l s (fun (k:a) => (kronecker m (f k))) (l1 + l2)%Z) =
(kronecker m (ket_sum_l s f l1))).
Axiom kronecker_ket_sum_distr_r_rew :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (m:matrix t) (l1:Z),
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l1) -> (is_a_ket m) ->
((cardinal s) > 0%Z)%Z ->
((kronecker m (ket_sum_l s f l1)) =
(ket_sum_l s (fun (k:a) => (kronecker m (f k))) (l1 + (ket_length m))%Z)).
Axiom ket_sum_scalar :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (a1:t) (l:Z),
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l) ->
((cardinal s) > 0%Z)%Z ->
((ket_sum_l s (fun (k:a) => (infix_asdtdt a1 (f k))) l) =
(infix_asdtdt a1 (ket_sum_l s f l))).
Axiom kronecker_ket_sum_distr_sc :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (m:matrix t) (a1:t) (l1:Z) (l2:Z),
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) l1) -> (is_a_ket_l m l2) ->
((cardinal s) > 0%Z)%Z ->
((ket_sum_l s (fun (k:a) => (kronecker (infix_asdtdt a1 (f k)) m))
(l1 + l2)%Z)
=
(infix_asdtdt a1
(ket_sum_l s (fun (k:a) => (kronecker (f k) m)) (l1 + l2)%Z))).
Axiom kronecker_decomp_r :
forall (m:matrix t) (n:matrix t) (lm:Z) (ln:Z), (is_a_ket_l m lm) ->
(is_a_ket_l n ln) ->
((kronecker m n) =
(ket_sum_l (n_bvs ln)
(fun (x:bitvec) =>
(infix_asdtdt (get_ket n (bv_to_int x)) (kronecker m (bv_to_ket x))))
(lm + ln)%Z)).
Axiom kronecker_decomp_l :
forall (m:matrix t) (n:matrix t) (lm:Z) (ln:Z), (is_a_ket_l m lm) ->
(is_a_ket_l n ln) ->
((kronecker m n) =
(ket_sum_l (n_bvs lm)
(fun (x:bitvec) =>
(infix_asdtdt (get_ket m (bv_to_int x)) (kronecker (bv_to_ket x) n)))
(lm + ln)%Z)).
Axiom kronecker_ket_sum_distr_double :
forall (i:Z) (j:Z) (f:bitvec -> matrix t) (g:bitvec -> matrix t) (l1:Z)
(l2:Z),
(0%Z <= i)%Z -> (0%Z <= j)%Z ->
(forall (bv:bitvec), (mem bv (n_bvs i)) -> is_a_ket_l (f bv) l1) ->
(forall (bv:bitvec), (mem bv (n_bvs j)) -> is_a_ket_l (g bv) l2) ->
((kronecker (ket_sum_l (n_bvs i) f l1) (ket_sum_l (n_bvs j) g l2)) =
(ket_sum_l (n_bvs (i + j)%Z)
(fun (k:bitvec) => (kronecker (f (hpart k i)) (g (tpart k i))))
(l1 + l2)%Z)).
Axiom kronecker_sem_decomp_r :
forall (c:circuit) (m1:matrix t) (m2:matrix t) (f:bitvec -> matrix t)
(s2:Z),
(is_a_ket_l m1 ((width c) - s2)%Z) ->
(forall (x:bitvec), ((length x) = s2) ->
sem c (kronecker m1 (bv_to_ket x)) (f x)) ->
(is_a_ket_l m2 s2) ->
(sem c (kronecker m1 m2)
(ket_sum_l (n_bvs s2)
(fun (x:bitvec) => (infix_asdtdt (get_ket m2 (bv_to_int x)) (f x)))
(width c))) /\
(sem c (kronecker m1 m2)
(ket_sum_l (n_bvs s2)
(fun (x:bitvec) =>
(infix_asdtdt (get_ket m2 (bv_to_int x))
(pat_sem c (kronecker m1 (bv_to_ket x)))))
(width c))).
Axiom kronecker_sem_decomp_l :
forall (c:circuit) (m1:matrix t) (m2:matrix t) (f:bitvec -> matrix t)
(s1:Z),
(is_a_ket_l m2 ((width c) - s1)%Z) ->
(forall (x:bitvec), ((length x) = s1) ->
sem c (kronecker (bv_to_ket x) m2) (f x)) ->
(is_a_ket_l m1 s1) ->
(sem c (kronecker m1 m2)
(ket_sum_l (n_bvs s1)
(fun (x:bitvec) => (infix_asdtdt (get_ket m1 (bv_to_int x)) (f x)))
(width c))) /\
(sem c (kronecker m1 m2)
(ket_sum_l (n_bvs s1)
(fun (x:bitvec) =>
(infix_asdtdt (get_ket m1 (bv_to_int x))
(pat_sem c (kronecker (bv_to_ket x) m2))))
(width c))).
Axiom sem_kronecker_decomp_l :
forall (c:circuit) (m1:matrix t) (m2:matrix t) (y:matrix t)
(f:bitvec -> matrix t) (s2:Z),
(forall (x:bitvec), ((length x) = (width c)) -> sem c (bv_to_ket x) (f x)) ->
(sem c m1 y) -> (is_a_ket_l m2 s2) ->
((kronecker y m2) =
(ket_sum_l (n_bvs (width c))
(fun (x:bitvec) =>
(infix_asdtdt (get_ket m1 (bv_to_int x)) (kronecker (f x) m2)))
((width c) + s2)%Z)).
Axiom sem_kronecker_decomp_r :
forall (c:circuit) (m1:matrix t) (m2:matrix t) (y:matrix t)
(f:bitvec -> matrix t) (s1:Z),
(forall (x:bitvec), ((length x) = (width c)) -> sem c (bv_to_ket x) (f x)) ->
(sem c m2 y) -> (is_a_ket_l m1 s1) ->
((kronecker m1 y) =
(ket_sum_l (n_bvs (width c))
(fun (x:bitvec) =>
(infix_asdtdt (get_ket m2 (bv_to_int x)) (kronecker m1 (f x))))
((width c) + s1)%Z)).
Axiom cont_kron_left_contz :
forall (c:circuit) (co:Z) (n:Z) (x:matrix t) (y:matrix t),
(((width c) <= co)%Z /\ (co < n)%Z) -> (is_a_ket_l x (width c)) ->
(is_a_ket_l y (n - (width c))%Z) -> (is_a_ket_basis_elt y) ->
(((getbv (ket_to_bv y)) (co - (width c))%Z) = 0%Z) ->
sem (cont c co 0%Z n) (kronecker x y) (kronecker x y).
Axiom cont_kron_left_conto :
forall (c:circuit) (co:Z) (n:Z) (f:bitvec -> matrix t) (x:matrix t)
(y:matrix t),
(((width c) <= co)%Z /\ (co < n)%Z) -> (is_a_ket_l x (width c)) ->
(is_a_ket_l y (n - (width c))%Z) -> (is_a_ket_basis_elt y) ->
(((getbv (ket_to_bv y)) (co - (width c))%Z) = 1%Z) ->
(forall (z:bitvec), ((length z) = (width c)) -> sem c (bv_to_ket z) (f z)) ->
sem (cont c co 0%Z n) (kronecker x y) (kronecker (pat_sem c x) y).
Axiom cont_kron_left_bv_to_ket :
forall (c:circuit) (n:Z) (x:matrix t),
((0%Z <= (width c))%Z /\ ((width c) = (n - 1%Z)%Z)) ->
(is_a_ket_l x (width c)) ->
(forall (y:bitvec), ((length y) = 1%Z) -> (((getbv y) 0%Z) = 0%Z) ->
((pat_sem (cont c (n - 1%Z)%Z 0%Z n) (kronecker x (bv_to_ket y))) =
(kronecker x (bv_to_ket y)))) /\
forall (y:bitvec), ((length y) = 1%Z) -> (((getbv y) 0%Z) = 1%Z) ->
((pat_sem (cont c (n - 1%Z)%Z 0%Z n) (kronecker x (bv_to_ket y))) =
(kronecker (pat_sem c x) (bv_to_ket y))).
Axiom place_kron_left_pat :
forall (c:circuit) (n:Z), ((width c) < n)%Z ->
forall (x:matrix t) (y:matrix t), (is_a_ket_l x (width c)) ->
(is_a_ket_l y (n - (width c))%Z) ->
((pat_sem (place c 0%Z n) (kronecker x y)) = (kronecker (pat_sem c x) y)).
Axiom cont_kron_right_contz :
forall (c:circuit) (co:Z) (n:Z) (x:matrix t) (y:matrix t),
((0%Z <= co)%Z /\ (co < (n - (width c))%Z)%Z) ->
(is_a_ket_l x (n - (width c))%Z) -> (is_a_ket_l y (width c)) ->
(is_a_ket_basis_elt x) -> (((getbv (ket_to_bv x)) co) = 0%Z) ->
sem (cont c co (n - (width c))%Z n) (kronecker x y) (kronecker x y).
Axiom cont_kron_right_conto :
forall (c:circuit) (co:Z) (n:Z) (f:bitvec -> matrix t) (x:matrix t)
(y:matrix t),
((0%Z <= co)%Z /\ (co < (n - (width c))%Z)%Z) ->
(is_a_ket_l x (n - (width c))%Z) -> (is_a_ket_l y (width c)) ->
(is_a_ket_basis_elt x) -> (((getbv (ket_to_bv x)) co) = 1%Z) ->
(forall (z:bitvec), ((length z) = (width c)) -> sem c (bv_to_ket z) (f z)) ->
sem (cont c co (n - (width c))%Z n) (kronecker x y)
(kronecker x (pat_sem c y)).
Axiom cont_kron_gen_right :
forall (circ:circuit) (c:Z) (ft:Z) (n:Z) (y:matrix t) (z:matrix t),
((0%Z <= c)%Z /\ (c < ft)%Z) -> (n = (ft + (width circ))%Z) ->
(sem circ y z) ->
(forall (x:matrix t), (is_a_ket_basis_elt x) -> (is_a_ket_l x ft) ->
(((getbv (ket_to_bv x)) c) = 0%Z) ->
sem (cont circ c ft n) (kronecker x y) (kronecker x y)) /\
forall (x:matrix t), (is_a_ket_basis_elt x) -> (is_a_ket_l x ft) ->
(((getbv (ket_to_bv x)) c) = 1%Z) ->
sem (cont circ c ft n) (kronecker x y) (kronecker x z).
Axiom cont_kron_pat_right :
forall (circ:circuit) (c:Z) (ft:Z) (n:Z) (y:matrix t),
((0%Z <= c)%Z /\ (c < ft)%Z) -> (n = (ft + (width circ))%Z) ->
(is_a_ket_l y (width circ)) ->
(forall (x:matrix t), (is_a_ket_basis_elt x) -> (is_a_ket_l x ft) ->
(((getbv (ket_to_bv x)) c) = 0%Z) ->
((pat_sem (cont circ c ft n) (kronecker x y)) = (kronecker x y))) /\
forall (x:matrix t), (is_a_ket_basis_elt x) -> (is_a_ket_l x ft) ->
(((getbv (ket_to_bv x)) c) = 1%Z) ->
((pat_sem (cont circ c ft n) (kronecker x y)) =
(kronecker x (pat_sem circ y))).
Axiom cont_kron_pat_right_gen :
forall (circ:circuit) (c:Z) (ft:Z) (n:Z), ((0%Z <= c)%Z /\ (c < ft)%Z) ->
(n = (ft + (width circ))%Z) ->
(forall (y:matrix t), forall (x:bitvec), (is_a_ket_l y (width circ)) ->
((length x) = ft) -> (((getbv x) c) = 0%Z) ->
((pat_sem (cont circ c ft n) (kronecker (bv_to_ket x) y)) =
(kronecker (bv_to_ket x) y))) /\
forall (y:matrix t), forall (x:bitvec), (is_a_ket_l y (width circ)) ->
((length x) = ft) -> (((getbv x) c) = 1%Z) ->
((pat_sem (cont circ c ft n) (kronecker (bv_to_ket x) y)) =
(kronecker (bv_to_ket x) (pat_sem circ y))).
Parameter place_hadamard: Z -> Z -> circuit.
Axiom place_hadamard_def :
forall (k:Z) (n:Z), ((0%Z <= k)%Z /\ (k < n)%Z) ->
((place_hadamard k n) = (place hadamard k n)).
Parameter fc14: Z -> bitvec -> bitvec -> Z -> Z.
Axiom fc_def14 :
forall (k:Z) (x:bitvec) (y:bitvec) (i:Z),
((i = k) -> (((fc14 k x y) i) = ((getbv y) 0%Z))) /\
(~ (i = k) -> (((fc14 k x y) i) = ((getbv x) i))).
Axiom place_hadamard_spec :
forall (k:Z) (n:Z), ((0%Z <= k)%Z /\ (k < n)%Z) ->
((range (place_hadamard k n)) = 1%Z) /\
(((width (place_hadamard k n)) = n) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = n) ->
((length y) = 1%Z) -> ((0%Z <= i)%Z /\ (i < n)%Z) ->
((i = k) ->
((basis_ket_i (place_hadamard k n) x y i) = ((getbv y) 0%Z))) /\
(~ (i = k) ->
((basis_ket_i (place_hadamard k n) x y i) = ((getbv x) i)))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) -> ((length y) = 1%Z) ->
((basis_ket (place_hadamard k n) x y) = (make_bv (fc14 k x y) n))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 1%Z) ->
((ang_ind (place_hadamard k n) x y) =
(int_to_ang (((getbv x) k) * ((getbv y) 0%Z))%Z 1%Z))) /\
forall (x:bitvec) (y:bitvec), forall (m:Z), (m >= 1%Z)%Z ->
((length x) = n) -> ((length y) = 1%Z) ->
((ang_ind (place_hadamard k n) x y) =
(int_to_ang
((((getbv x) k) * ((getbv y) 0%Z))%Z * (power_ 2%Z (m - 1%Z)%Z))%Z m)))))).
Parameter control_eigen:
circuit -> (matrix t) -> angle -> Z -> Z -> Z -> circuit.
Axiom control_eigen_def :
forall (circ:circuit) (y:matrix t) (o:angle) (c:Z) (ft:Z) (n:Z),
((0%Z <= c)%Z /\ (c < ft)%Z) -> (n = (ft + (width circ))%Z) ->
(eigen circ y o) -> ((control_eigen circ y o c ft n) = (cont circ c ft n)).
Axiom control_eigen_spec :
forall (circ:circuit) (y:matrix t) (o:angle) (c:Z) (ft:Z) (n:Z),
((0%Z <= c)%Z /\ (c < ft)%Z) -> (n = (ft + (width circ))%Z) ->
(eigen circ y o) ->
((width (control_eigen circ y o c ft n)) = n) /\
((forall (x:matrix t), (is_a_ket_l x ft) -> (is_a_ket_basis_elt x) ->
(((getbv (ket_to_bv x)) c) = 0%Z) ->
sem (control_eigen circ y o c ft n) (kronecker x y) (kronecker x y)) /\
((forall (x:matrix t), (is_a_ket_l x ft) -> (is_a_ket_basis_elt x) ->
(((getbv (ket_to_bv x)) c) = 1%Z) ->
sem (control_eigen circ y o c ft n) (kronecker x y)
(kronecker x (infix_asdtdt (ang_exp o) y))) /\
forall (x:bitvec), ((length x) = ft) ->
sem (control_eigen circ y o c ft n) (kronecker (bv_to_ket x) y)
(kronecker (bv_to_ket x)
(infix_asdtdt (ang_exp (ang_mult_int o ((getbv x) c))) y)))).
Parameter control_eigen_scal:
circuit -> (matrix t) -> Z -> Z -> Z -> angle -> angle -> circuit.
Axiom control_eigen_scal_def :
forall (circ:circuit) (y:matrix t) (c:Z) (ft:Z) (n:Z) (o:angle) (o':angle),
((0%Z <= c)%Z /\ (c < ft)%Z) -> (n = (ft + (width circ))%Z) ->
(n >= 0%Z)%Z -> (eigen circ y o') ->
((control_eigen_scal circ y c ft n o o') =
(control_eigen circ (infix_asdtdt (ang_exp o) y) o' c ft n)).
Axiom control_eigen_scal_spec :
forall (circ:circuit) (y:matrix t) (c:Z) (ft:Z) (n:Z) (o:angle) (o':angle),
((0%Z <= c)%Z /\ (c < ft)%Z) -> (n = (ft + (width circ))%Z) ->
(n >= 0%Z)%Z -> (eigen circ y o') ->
((width (control_eigen_scal circ y c ft n o o')) = (ft + (width circ))%Z) /\
(((control_eigen_scal circ y c ft n o o') = (cont circ c ft n)) /\
forall (x:bitvec), ((length x) = ft) ->
sem (control_eigen_scal circ y c ft n o o')
(kronecker (infix_asdtdt (ang_exp o) (bv_to_ket x)) y)
(kronecker
(infix_asdtdt (ang_exp (ang_add o (ang_mult_int o' ((getbv x) c))))
(bv_to_ket x))
y)).
Parameter control_eigen_seq_test:
(Z -> circuit) -> (Z -> Z) -> Z -> Z -> Z -> Z -> circuit.
Axiom control_eigen_seq_test_def :
forall (fcirc:Z -> circuit) (fc15:Z -> Z) (ft:Z) (bound:Z) (s:Z) (n:Z),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) ->
(0%Z <= (fc15 i))%Z /\ ((fc15 i) < ft)%Z) ->
((0%Z < bound)%Z /\ (bound <= ft)%Z) -> (s >= 0%Z)%Z -> (n = (ft + s)%Z) ->
(0%Z <= n)%Z -> (forall (i:Z), ((width (fcirc i)) = s)) ->
((bound = 1%Z) ->
((control_eigen_seq_test fcirc fc15 ft bound s n) =
(cont (fcirc 0%Z) (fc15 0%Z) ft (ft + s)%Z))) /\
(~ (bound = 1%Z) ->
((control_eigen_seq_test fcirc fc15 ft bound s n) =
(sequence (control_eigen_seq_test fcirc fc15 ft (bound - 1%Z)%Z s n)
(cont (fcirc (bound - 1%Z)%Z) (fc15 (bound - 1%Z)%Z) ft n)))).
Axiom control_eigen_seq_test_spec :
forall (fcirc:Z -> circuit) (fc15:Z -> Z) (ft:Z) (bound:Z) (s:Z) (n:Z),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) ->
(0%Z <= (fc15 i))%Z /\ ((fc15 i) < ft)%Z) ->
((0%Z < bound)%Z /\ (bound <= ft)%Z) -> (s >= 0%Z)%Z -> (n = (ft + s)%Z) ->
(0%Z <= n)%Z -> (forall (i:Z), ((width (fcirc i)) = s)) ->
((width (control_eigen_seq_test fcirc fc15 ft bound s n)) = (ft + s)%Z).
Parameter control_eigen_seq_pre:
(Z -> circuit) -> (matrix t) -> (Z -> angle) -> (Z -> Z) -> Z -> Z ->
Z -> Z -> bitvec -> circuit.
Axiom control_eigen_seq_pre_def :
forall (fcirc:Z -> circuit) (y:matrix t) (fk:Z -> angle) (fc15:Z -> Z)
(ft:Z) (bound:Z) (s:Z) (n:Z) (x:bitvec),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) ->
(0%Z <= (fc15 i))%Z /\ ((fc15 i) < ft)%Z) ->
((0%Z < bound)%Z /\ (bound <= ft)%Z) -> (s >= 0%Z)%Z -> (n = (ft + s)%Z) ->
(0%Z <= n)%Z ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) -> eigen (fcirc i) y (fk i)) ->
(forall (i:Z), ((width (fcirc i)) = s)) -> (is_a_ket_l y s) ->
((length x) = ft) ->
((bound = 1%Z) ->
((control_eigen_seq_pre fcirc y fk fc15 ft bound s n x) =
(control_eigen (fcirc 0%Z) y (fk 0%Z) (fc15 0%Z) ft (ft + s)%Z))) /\
(~ (bound = 1%Z) ->
((control_eigen_seq_pre fcirc y fk fc15 ft bound s n x) =
(sequence
(control_eigen_seq_pre fcirc y fk fc15 ft (bound - 1%Z)%Z s n x)
(control_eigen_scal (fcirc (bound - 1%Z)%Z) y (fc15 (bound - 1%Z)%Z) ft
n
(ang_sum (fun (i:Z) => (ang_mult_int (fk i) ((getbv x) (fc15 i)))) 0%Z
(bound - 1%Z)%Z)
(fk (bound - 1%Z)%Z))))).
Axiom control_eigen_seq_pre_spec :
forall (fcirc:Z -> circuit) (y:matrix t) (fk:Z -> angle) (fc15:Z -> Z)
(ft:Z) (bound:Z) (s:Z) (n:Z) (x:bitvec),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) ->
(0%Z <= (fc15 i))%Z /\ ((fc15 i) < ft)%Z) ->
((0%Z < bound)%Z /\ (bound <= ft)%Z) -> (s >= 0%Z)%Z -> (n = (ft + s)%Z) ->
(0%Z <= n)%Z ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) -> eigen (fcirc i) y (fk i)) ->
(forall (i:Z), ((width (fcirc i)) = s)) -> (is_a_ket_l y s) ->
((length x) = ft) ->
((width (control_eigen_seq_pre fcirc y fk fc15 ft bound s n x)) =
(ft + s)%Z) /\
((sem (control_eigen_seq_pre fcirc y fk fc15 ft bound s n x)
(kronecker (bv_to_ket x) y)
(kronecker
(infix_asdtdt
(ang_exp
(ang_sum (fun (i:Z) => (ang_mult_int (fk i) ((getbv x) (fc15 i)))) 0%Z
bound))
(bv_to_ket x))
y)) /\
((control_eigen_seq_pre fcirc y fk fc15 ft bound s n x) =
(control_eigen_seq_test fcirc fc15 ft bound s n))).
Parameter control_eigen_seq:
(Z -> circuit) -> (matrix t) -> (Z -> angle) -> (Z -> Z) -> Z -> Z ->
Z -> Z -> circuit.
Axiom control_eigen_seq_def :
forall (fcirc:Z -> circuit) (y:matrix t) (fk:Z -> angle) (fc15:Z -> Z)
(ft:Z) (bound:Z) (s:Z) (n:Z),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) ->
(0%Z <= (fc15 i))%Z /\ ((fc15 i) < ft)%Z) ->
((0%Z < bound)%Z /\ (bound <= ft)%Z) -> (s >= 0%Z)%Z -> (n = (ft + s)%Z) ->
(0%Z <= n)%Z ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) -> eigen (fcirc i) y (fk i)) ->
(forall (i:Z), ((width (fcirc i)) = s)) -> (is_a_ket_l y s) ->
((control_eigen_seq fcirc y fk fc15 ft bound s n) =
(control_eigen_seq_test fcirc fc15 ft bound s n)).
Axiom control_eigen_seq_spec :
forall (fcirc:Z -> circuit) (y:matrix t) (fk:Z -> angle) (fc15:Z -> Z)
(ft:Z) (bound:Z) (s:Z) (n:Z),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) ->
(0%Z <= (fc15 i))%Z /\ ((fc15 i) < ft)%Z) ->
((0%Z < bound)%Z /\ (bound <= ft)%Z) -> (s >= 0%Z)%Z -> (n = (ft + s)%Z) ->
(0%Z <= n)%Z ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) -> eigen (fcirc i) y (fk i)) ->
(forall (i:Z), ((width (fcirc i)) = s)) -> (is_a_ket_l y s) ->
(forall (x:bitvec), ((length x) = ft) ->
((control_eigen_seq fcirc y fk fc15 ft bound s n) =
(control_eigen_seq_pre fcirc y fk fc15 ft bound s n x))) /\
(((width (control_eigen_seq fcirc y fk fc15 ft bound s n)) = (ft + s)%Z) /\
forall (x:bitvec), ((length x) = ft) ->
sem (control_eigen_seq fcirc y fk fc15 ft bound s n)
(kronecker (bv_to_ket x) y)
(kronecker
(infix_asdtdt
(ang_exp
(ang_sum (fun (i:Z) => (ang_mult_int (fk i) ((getbv x) (fc15 i)))) 0%Z
bound))
(bv_to_ket x))
y)).
Parameter control_eigen_seq_real:
(Z -> circuit) -> (matrix t) -> (Z -> t) -> (Z -> Z) -> Z -> Z -> Z ->
Z -> circuit.
Parameter result21: (Z -> t) -> Z -> angle.
Axiom result_def21 :
forall (fk:Z -> t) (k:Z),
((real_ (fk k)) -> (((result21 fk) k) = (real_to_ang (fk k)))) /\
(~ (real_ (fk k)) -> (((result21 fk) k) = ang_zero)).
Axiom control_eigen_seq_real_def :
forall (fcirc:Z -> circuit) (y:matrix t) (fk:Z -> t) (fc15:Z -> Z)
(ft:Z) (bound:Z) (s:Z) (n:Z),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) ->
(0%Z <= (fc15 i))%Z /\ ((fc15 i) < ft)%Z) ->
((0%Z < bound)%Z /\ (bound <= ft)%Z) -> (s >= 0%Z)%Z -> (n = (ft + s)%Z) ->
(0%Z <= n)%Z ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) -> real_ (fk i)) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) ->
eigen (fcirc i) y (real_to_ang (fk i))) ->
(forall (i:Z), ((width (fcirc i)) = s)) -> (is_a_ket_l y s) ->
((control_eigen_seq_real fcirc y fk fc15 ft bound s n) =
(control_eigen_seq fcirc y (result21 fk) fc15 ft bound s n)).
Axiom control_eigen_seq_real_spec :
forall (fcirc:Z -> circuit) (y:matrix t) (fk:Z -> t) (fc15:Z -> Z)
(ft:Z) (bound:Z) (s:Z) (n:Z),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) ->
(0%Z <= (fc15 i))%Z /\ ((fc15 i) < ft)%Z) ->
((0%Z < bound)%Z /\ (bound <= ft)%Z) -> (s >= 0%Z)%Z -> (n = (ft + s)%Z) ->
(0%Z <= n)%Z ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) -> real_ (fk i)) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < bound)%Z) ->
eigen (fcirc i) y (real_to_ang (fk i))) ->
(forall (i:Z), ((width (fcirc i)) = s)) -> (is_a_ket_l y s) ->
((width (control_eigen_seq_real fcirc y fk fc15 ft bound s n)) =
(ft + s)%Z) /\
forall (x:bitvec), ((length x) = ft) ->
sem (control_eigen_seq_real fcirc y fk fc15 ft bound s n)
(kronecker (bv_to_ket x) y)
(kronecker
(infix_asdtdt
(ang_exp
(ang_sum
(fun (i:Z) =>
(real_to_ang (infix_asdt (fk i) (i_to_t ((getbv x) (fc15 i))))))
0%Z bound))
(bv_to_ket x))
y).
Parameter bv_get:
forall {a:Type} {a_WT:WhyType a}, (matrix a) -> bitvec -> bitvec -> a.
Axiom bv_get_def :
forall {a:Type} {a_WT:WhyType a},
forall (m:matrix a) (x:bitvec) (y:bitvec),
((bv_get m x y) = (get m (bv_to_int x) (bv_to_int y))).
Parameter bv_make:
forall {a:Type} {a_WT:WhyType a}, (bitvec -> bitvec -> a) -> Z -> Z ->
matrix a.
Axiom bv_make_def :
forall {a:Type} {a_WT:WhyType a},
forall (f:bitvec -> bitvec -> a) (size1:Z) (range1:Z), (0%Z <= size1)%Z ->
(0%Z <= range1)%Z ->
((bv_make f size1 range1) =
(make_f (power 2%Z size1) (power 2%Z range1)
(fun (i:Z) (j:Z) => ((f (int_to_bv i size1)) (int_to_bv j range1))))).
Axiom bv_make_spec :
forall {a:Type} {a_WT:WhyType a},
forall (f:bitvec -> bitvec -> a) (size1:Z) (range1:Z), (0%Z <= size1)%Z ->
(0%Z <= range1)%Z ->
(forall (x:bitvec) (y:bitvec), ((length x) = size1) ->
((length y) = range1) ->
((bv_get (bv_make f size1 range1) x y) = ((f x) y))) /\
(((rows (bv_make f size1 range1)) = (power 2%Z size1)) /\
((columns (bv_make f size1 range1)) = (power 2%Z range1))).
Axiom bk_func : Type.
Parameter bk_func_WhyType : WhyType bk_func.
Existing Instance bk_func_WhyType.
Parameter mat_k: bk_func -> matrix bitvec.
Parameter size_k: bk_func -> Z.
Parameter range_k: bk_func -> Z.
Axiom bk_func'invariant :
forall (self:bk_func),
((size_k self) >= 0%Z)%Z /\
(((range_k self) >= 0%Z)%Z /\
(((rows (mat_k self)) = (power 2%Z (size_k self))) /\
(((columns (mat_k self)) = (power 2%Z (range_k self))) /\
forall (x:bitvec) (y:bitvec), ((length x) = (size_k self)) ->
((length y) = (range_k self)) ->
((length (bv_get (mat_k self) x y)) = (size_k self))))).
Parameter get_k: bk_func -> bitvec -> bitvec -> bitvec.
Axiom get_k_def :
forall (k:bk_func) (x:bitvec) (y:bitvec),
((get_k k x y) = (bv_get (mat_k k) x y)).
Axiom get_k_spec :
forall (k:bk_func) (x:bitvec) (y:bitvec), ((length x) = (size_k k)) ->
((length y) = (range_k k)) -> ((length (get_k k x y)) = (size_k k)).
Parameter get_k_int: bk_func -> bitvec -> bitvec -> Z.
Axiom get_k_int_def :
forall (k:bk_func) (x:bitvec) (y:bitvec),
((get_k_int k x y) = (bv_to_int (get_k k x y))).
Axiom get_k_int_spec :
forall (k:bk_func) (x:bitvec) (y:bitvec),
((get_k_int k x y) = (bv_to_int (bv_get (mat_k k) x y))) /\
(((length x) = (size_k k)) -> ((length y) = (range_k k)) ->
(0%Z <= (get_k_int k x y))%Z /\
((get_k_int k x y) < (power 2%Z (size_k k)))%Z).
Parameter get_k_ket: bk_func -> bitvec -> bitvec -> matrix t.
Axiom get_k_ket_def :
forall (k:bk_func) (x:bitvec) (y:bitvec),
((get_k_ket k x y) = (bv_to_ket (get_k k x y))).
Axiom get_k_ket_spec :
forall (k:bk_func) (x:bitvec) (y:bitvec),
((get_k_ket k x y) = (bv_to_ket (bv_get (mat_k k) x y))) /\
((((length x) = (size_k k)) -> ((length y) = (range_k k)) ->
is_a_ket_l (get_k_ket k x y) (size_k k)) /\
((is_a_ket_basis_elt (get_k_ket k x y)) /\
(((length x) = (size_k k)) -> ((length y) = (range_k k)) ->
((get_k_ket k x y) = (ket (size_k k) (get_k_int k x y)))))).
Axiom get_k_ket_is_a_ket_l :
forall (k:bk_func) (x:bitvec) (y:bitvec) (l:Z), ((length x) = l) ->
((length y) = (range_k k)) -> (l = (size_k k)) ->
is_a_ket_l (get_k_ket k x y) l.
Axiom get_k_length :
forall (k:bk_func) (x:bitvec) (y:bitvec), ((length x) = (size_k k)) ->
((length y) = (range_k k)) -> ((length (get_k k x y)) = (size_k k)).
Parameter get_ki: bk_func -> bitvec -> bitvec -> Z -> Z.
Axiom get_ki_def :
forall (k:bk_func) (x:bitvec) (y:bitvec) (i:Z),
((get_ki k x y i) = ((getbv (get_k k x y)) i)).
Axiom get_ki_spec :
forall (k:bk_func) (x:bitvec) (y:bitvec) (i:Z),
((get_ki k x y i) = ((getbv (bv_get (mat_k k) x y)) i)).
Axiom length_bk :
forall (k:bk_func) (x:bitvec) (y:bitvec), ((length x) = (size_k k)) ->
((length y) = (range_k k)) -> ((length (get_k k x y)) = (size_k k)).
Parameter make_k: (bitvec -> bitvec -> bitvec) -> Z -> Z -> bk_func.
Axiom make_k_spec :
forall (f:bitvec -> bitvec -> bitvec) (size1:Z) (range1:Z),
(size1 >= 0%Z)%Z -> (range1 >= 0%Z)%Z ->
(forall (x:bitvec) (y:bitvec), ((length x) = size1) ->
((length y) = range1) -> ((length ((f x) y)) = size1)) ->
(forall (x:bitvec) (y:bitvec), ((length x) = size1) ->
((length y) = range1) ->
((get_k (make_k f size1 range1) x y) = ((f x) y))) /\
(((mat_k (make_k f size1 range1)) = (bv_make f size1 range1)) /\
(((size_k (make_k f size1 range1)) = size1) /\
((range_k (make_k f size1 range1)) = range1))).
Axiom angle_func : Type.
Parameter angle_func_WhyType : WhyType angle_func.
Existing Instance angle_func_WhyType.
Parameter mat_a: angle_func -> matrix angle.
Parameter size_a: angle_func -> Z.
Parameter range_a: angle_func -> Z.
Axiom angle_func'invariant :
forall (self:angle_func),
((size_a self) >= 0%Z)%Z /\
(((range_a self) >= 0%Z)%Z /\
(((rows (mat_a self)) = (power 2%Z (size_a self))) /\
((columns (mat_a self)) = (power 2%Z (range_a self))))).
Parameter get_a: angle_func -> bitvec -> bitvec -> angle.
Axiom get_a_def :
forall (k:angle_func) (x:bitvec) (y:bitvec),
((get_a k x y) = (bv_get (mat_a k) x y)).
Parameter get_ac: angle_func -> bitvec -> bitvec -> t.
Axiom get_ac_def :
forall (k:angle_func) (x:bitvec) (y:bitvec),
((get_ac k x y) = (ang_exp (bv_get (mat_a k) x y))).
Parameter gen_ket: angle_func -> Prop.
Axiom gen_ket_def :
forall (a:angle_func), (gen_ket a) <-> ((range_a a) = 0%Z).
Parameter make_a: (bitvec -> bitvec -> angle) -> Z -> Z -> angle_func.
Axiom make_a_spec :
forall (f:bitvec -> bitvec -> angle) (size1:Z) (range1:Z),
(size1 >= 0%Z)%Z -> (range1 >= 0%Z)%Z ->
(forall (x:bitvec) (y:bitvec), ((length x) = size1) ->
((length y) = range1) ->
((get_a (make_a f size1 range1) x y) = ((f x) y))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = size1) ->
((length y) = range1) ->
((get_ac (make_a f size1 range1) x y) = (ang_exp ((f x) y)))) /\
(((mat_a (make_a f size1 range1)) = (bv_make f size1 range1)) /\
(((size_a (make_a f size1 range1)) = size1) /\
((range_a (make_a f size1 range1)) = range1)))).
Parameter k_seq: bk_func -> bk_func -> bk_func.
Axiom k_seq_def :
forall (k1:bk_func) (k2:bk_func), ((size_k k1) = (size_k k2)) ->
((k_seq k1 k2) =
(make_k
(fun (x:bitvec) (y:bitvec) =>
(get_k k2 (get_k k1 x (hpart y (range_k k1))) (tpart y (range_k k1))))
(size_k k1) ((range_k k1) + (range_k k2))%Z)).
Axiom k_seq_spec :
forall (k1:bk_func) (k2:bk_func), ((size_k k1) = (size_k k2)) ->
(forall (x:bitvec) (y:bitvec), ((length x) = (size_k k1)) ->
((length y) = ((range_k k1) + (range_k k2))%Z) ->
((get_k (k_seq k1 k2) x y) =
(get_k k2 (get_k k1 x (hpart y (range_k k1))) (tpart y (range_k k1))))) /\
(((size_k (k_seq k1 k2)) = (size_k k1)) /\
(((range_k (k_seq k1 k2)) = ((range_k k1) + (range_k k2))%Z) /\
forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = (size_k k1)) ->
((length y) = ((range_k k1) + (range_k k2))%Z) ->
((0%Z <= i)%Z /\ (i < ((range_k k1) + (range_k k2))%Z)%Z) ->
((get_ki (k_seq k1 k2) x y i) =
(get_ki k2 (get_k k1 x (hpart y (range_k k1))) (tpart y (range_k k1)) i)))).
Parameter k_par: bk_func -> bk_func -> bk_func.
Axiom k_par_def :
forall (k1:bk_func) (k2:bk_func),
((k_par k1 k2) =
(make_k
(fun (x:bitvec) (y:bitvec) =>
(concat (get_k k1 (hpart x (size_k k1)) (hpart y (range_k k1)))
(get_k k2 (tpart x (size_k k1)) (tpart y (range_k k1)))))
((size_k k1) + (size_k k2))%Z ((range_k k1) + (range_k k2))%Z)).
Axiom k_par_spec :
forall (k1:bk_func) (k2:bk_func),
((size_k (k_par k1 k2)) = ((size_k k1) + (size_k k2))%Z) /\
(((range_k (k_par k1 k2)) = ((range_k k1) + (range_k k2))%Z) /\
((forall (x:bitvec) (y:bitvec),
((length x) = ((size_k k1) + (size_k k2))%Z) ->
((length y) = ((range_k k1) + (range_k k2))%Z) ->
((get_k (k_par k1 k2) x y) =
(concat (get_k k1 (hpart x (size_k k1)) (hpart y (range_k k1)))
(get_k k2 (tpart x (size_k k1)) (tpart y (range_k k1)))))) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z),
((length x) = ((size_k k1) + (size_k k2))%Z) ->
((length y) = ((range_k k1) + (range_k k2))%Z) ->
((0%Z <= i)%Z /\ (i < (size_k k1))%Z) ->
((get_ki (k_par k1 k2) x y i) =
(get_ki k1 (hpart x (size_k k1)) (hpart y (range_k k1)) i))) /\
forall (x:bitvec) (y:bitvec), forall (i:Z),
((length x) = ((size_k k1) + (size_k k2))%Z) ->
((length y) = ((range_k k1) + (range_k k2))%Z) ->
(((size_k k1) <= i)%Z /\ (i < ((size_k k1) + (size_k k2))%Z)%Z) ->
((get_ki (k_par k1 k2) x y i) =
(get_ki k2 (tpart x (size_k k1)) (tpart y (range_k k1))
(i - (size_k k1))%Z))))).
Parameter a_seq: angle_func -> angle_func -> bk_func -> angle_func.
Axiom a_seq_def :
forall (a1:angle_func) (a2:angle_func) (k1:bk_func),
(((size_a a1) = (size_a a2)) /\ ((size_a a2) = (size_k k1))) ->
((range_a a1) = (range_k k1)) ->
((a_seq a1 a2 k1) =
(make_a
(fun (x:bitvec) (y:bitvec) =>
(ang_add (get_a a1 x (hpart y (range_a a1)))
(get_a a2 (get_k k1 x (hpart y (range_a a1))) (tpart y (range_a a1)))))
(size_a a1) ((range_a a1) + (range_a a2))%Z)).
Axiom a_seq_spec :
forall (a1:angle_func) (a2:angle_func) (k1:bk_func),
(((size_a a1) = (size_a a2)) /\ ((size_a a2) = (size_k k1))) ->
((range_a a1) = (range_k k1)) ->
((size_a (a_seq a1 a2 k1)) = (size_a a1)) /\
(((range_a (a_seq a1 a2 k1)) = ((range_a a1) + (range_a a2))%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = (size_a a1)) ->
((length y) = ((range_a a1) + (range_a a2))%Z) ->
((get_a (a_seq a1 a2 k1) x y) =
(ang_add (get_a a1 x (hpart y (range_a a1)))
(get_a a2 (get_k k1 x (hpart y (range_a a1))) (tpart y (range_a a1)))))) /\
forall (x:bitvec) (y:bitvec), ((length x) = (size_a a1)) ->
((length y) = ((range_a a1) + (range_a a2))%Z) ->
((get_ac (a_seq a1 a2 k1) x y) =
(infix_asdt (get_ac a1 x (hpart y (range_a a1)))
(get_ac a2 (get_k k1 x (hpart y (range_a a1))) (tpart y (range_a a1))))))).
Parameter a_par: angle_func -> angle_func -> angle_func.
Axiom a_par_def :
forall (a1:angle_func) (a2:angle_func),
((a_par a1 a2) =
(make_a
(fun (x:bitvec) (y:bitvec) =>
(ang_add (get_a a1 (hpart x (size_a a1)) (hpart y (range_a a1)))
(get_a a2 (tpart x (size_a a1)) (tpart y (range_a a1)))))
((size_a a1) + (size_a a2))%Z ((range_a a1) + (range_a a2))%Z)).
Axiom a_par_spec :
forall (a1:angle_func) (a2:angle_func),
((size_a (a_par a1 a2)) = ((size_a a1) + (size_a a2))%Z) /\
(((range_a (a_par a1 a2)) = ((range_a a1) + (range_a a2))%Z) /\
((forall (x:bitvec) (y:bitvec),
((length x) = ((size_a a1) + (size_a a2))%Z) ->
((length y) = ((range_a a1) + (range_a a2))%Z) ->
((get_a (a_par a1 a2) x y) =
(ang_add (get_a a1 (hpart x (size_a a1)) (hpart y (range_a a1)))
(get_a a2 (tpart x (size_a a1)) (tpart y (range_a a1)))))) /\
forall (x:bitvec) (y:bitvec),
((length x) = ((size_a a1) + (size_a a2))%Z) ->
((length y) = ((range_a a1) + (range_a a2))%Z) ->
((get_ac (a_par a1 a2) x y) =
(infix_asdt (get_ac a1 (hpart x (size_a a1)) (hpart y (range_a a1)))
(get_ac a2 (tpart x (size_a a1)) (tpart y (range_a a1))))))).
Parameter flat: circuit -> Prop.
Axiom flat_def :
forall (c:circuit),
(flat c) <->
exists a:bitvec -> angle, exists b:bitvec -> bitvec,
correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => (b x)) 0%Z.
Axiom set_flat :
forall (c:circuit) (a:bitvec -> angle) (b:bitvec -> bitvec),
(correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => (b x)) 0%Z) ->
flat c.
Axiom get_flat :
forall (c:circuit), (flat c) ->
exists a:bitvec -> angle, exists b:bitvec -> bitvec,
correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => (b x)) 0%Z.
Axiom flat_phase : forall (o:angle), flat (phase o).
Axiom flat_rz : forall (o:angle), flat (rz o).
Axiom flat_cnot : flat cnot.
Axiom seq_pres_flat_pre :
forall (c:circuit) (c':circuit) (a:bitvec -> angle) (a':bitvec -> angle)
(b:bitvec -> bitvec) (b':bitvec -> bitvec),
((width c) = (width c')) ->
(correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => (b x)) 0%Z) ->
(correct_path_sum c' (fun (x:bitvec) (us:bitvec) => (a' x))
(fun (x:bitvec) (us:bitvec) => (b' x)) 0%Z) ->
(correct_path_sum (sequence c c')
(fun (x:bitvec) (us:bitvec) => (ang_add (a x) (a' (b x))))
(fun (x:bitvec) (us:bitvec) => (b' (b x))) 0%Z) /\
(flat (sequence c c')).
Axiom par_pres_flat_pre :
forall (c:circuit) (c':circuit) (a:bitvec -> angle) (a':bitvec -> angle)
(b:bitvec -> bitvec) (b':bitvec -> bitvec),
(correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => (b x)) 0%Z) ->
(correct_path_sum c' (fun (x:bitvec) (us:bitvec) => (a' x))
(fun (x:bitvec) (us:bitvec) => (b' x)) 0%Z) ->
(correct_path_sum (parallel c c')
(fun (x:bitvec) (us:bitvec) =>
(ang_add (a (hpart x (width c))) (a' (tpart x (width c)))))
(fun (x:bitvec) (us:bitvec) =>
(concat (b (hpart x (width c))) (b' (tpart x (width c)))))
0%Z) /\
(flat (parallel c c')).
Parameter flat_ang: circuit -> bitvec -> angle.
Parameter flat_ket: circuit -> bitvec -> bitvec.
Axiom flat_ket_spec :
forall (c:circuit), (flat c) -> forall (x:bitvec),
((length x) = (width c)) -> ((length ((flat_ket c) x)) = (width c)).
Parameter flat_ket_i: circuit -> bitvec -> Z -> Z.
Axiom flat_ket_i_def :
forall (c:circuit) (x:bitvec) (i:Z), (flat c) ->
((length x) = (width c)) -> ((0%Z <= i)%Z /\ (i < (length x))%Z) ->
((flat_ket_i c x i) = ((getbv ((flat_ket c) x)) i)).
Axiom flat_correct :
forall (c:circuit), (flat c) ->
correct_path_sum c (fun (x:bitvec) (us:bitvec) => ((flat_ang c) x))
(fun (x:bitvec) (us:bitvec) => ((flat_ket c) x)) 0%Z.
Axiom unic_flat_correct_pre :
forall (c:circuit) (a:bitvec -> angle) (b:bitvec -> bitvec) (x:bitvec),
(correct_path_sum c (fun (x1:bitvec) (us:bitvec) => (a x1))
(fun (x1:bitvec) (us:bitvec) => (b x1)) 0%Z) ->
((length x) = (width c)) ->
(((flat_ang c) x) = (a x)) /\ (((flat_ket c) x) = (b x)).
Axiom unic_flat_correct :
forall (c:circuit) (a:bitvec -> angle) (b:bitvec -> bitvec),
(correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => (b x)) 0%Z) ->
(forall (x:bitvec), ((length x) = (width c)) -> (((flat_ang c) x) = (a x))) /\
forall (x:bitvec), ((length x) = (width c)) -> (((flat_ket c) x) = (b x)).
Axiom seq_pres_flat :
forall (c:circuit) (c':circuit), ((width c) = (width c')) -> (flat c) ->
(flat c') -> flat (sequence c c').
Axiom diag_pres_flat :
forall (c:circuit) (c':circuit), (flat c) -> (flat c') ->
flat (parallel c c').
Axiom flat_ang_phase :
forall (o:angle), ((flat_ang (phase o)) = (fun (us:bitvec) => o)).
Axiom flat_ang_rz :
forall (o:angle),
((flat_ang (rz o)) =
(fun (x:bitvec) => (phase_inv_ (1%Z - ((getbv x) 0%Z))%Z o))).
Axiom flat_ang_cnot : ((flat_ang cnot) = (fun (us:bitvec) => ang_zero)).
Axiom flat_ang_sequence :
forall (c:circuit) (c':circuit), (flat c) -> (flat c') ->
((flat_ang (sequence c c')) =
(fun (x:bitvec) =>
(ang_add ((flat_ang c) x) ((flat_ang c') ((flat_ket c') x))))).
Axiom flat_ang_parallel :
forall (c:circuit) (c':circuit), (flat c) -> (flat c') ->
((flat_ang (parallel c c')) =
(fun (x:bitvec) =>
(ang_add ((flat_ang c) (hpart x (width c)))
((flat_ang c') (tpart x (width c)))))).
Axiom flat_ket_phase :
forall (o:angle), ((flat_ket (phase o)) = (fun (i:bitvec) => i)).
Axiom flat_ket_rz :
forall (o:angle), ((flat_ket (rz o)) = (fun (i:bitvec) => i)).
Axiom flat_ket_cnot :
let fc15 := flat_ket cnot in
forall (x:bitvec),
(((0%Z <= (bv_to_int x))%Z /\ ((bv_to_int x) < 2%Z)%Z) -> ((fc15 x) = x)) /\
(~ ((0%Z <= (bv_to_int x))%Z /\ ((bv_to_int x) < 2%Z)%Z) ->
(((bv_to_int x) = 2%Z) -> ((fc15 x) = (int_to_bv 3%Z 2%Z))) /\
(~ ((bv_to_int x) = 2%Z) -> ((fc15 x) = (int_to_bv 2%Z 2%Z)))).
Axiom flat_ket_sequence :
forall (c:circuit) (c':circuit), (flat c) -> (flat c') ->
((flat_ket (sequence c c')) =
(fun (x:bitvec) => ((flat_ket c') ((flat_ket c) x)))).
Axiom flat_ket_parallel :
forall (c:circuit) (c':circuit), (flat c) -> (flat c') ->
((flat_ket (parallel c c')) =
(fun (x:bitvec) =>
(concat ((flat_ket c) (hpart x (width c)))
((flat_ket c') (tpart x (width c)))))).
Parameter f_sequence: circuit -> circuit -> circuit.
Axiom f_sequence_def :
forall (c:circuit) (c':circuit), (flat c) -> (flat c') ->
((width c) = (width c')) -> ((f_sequence c c') = (sequence c c')).
Axiom f_sequence_spec :
forall (c:circuit) (c':circuit), (flat c) -> (flat c') ->
((width c) = (width c')) ->
((width (f_sequence c c')) = (width c)) /\
(((size (f_sequence c c')) = ((size c) + (size c'))%Z) /\
(((ancillas (f_sequence c c')) =
(ZArith.BinInt.Z.max (ancillas c) (ancillas c'))) /\
((flat (f_sequence c c')) /\
(((flat_ang (f_sequence c c')) =
(fun (x:bitvec) =>
(ang_add ((flat_ang c) x) ((flat_ang c') ((flat_ket c') x))))) /\
((flat_ket (f_sequence c c')) =
(fun (x:bitvec) => ((flat_ket c') ((flat_ket c) x)))))))).
Parameter f_parallel: circuit -> circuit -> circuit.
Axiom f_parallel_def :
forall (c:circuit) (c':circuit), (flat c) -> (flat c') ->
((f_parallel c c') = (parallel c c')).
Axiom f_parallel_spec :
forall (c:circuit) (c':circuit), (flat c) -> (flat c') ->
((width (f_parallel c c')) = ((width c) + (width c'))%Z) /\
(((size (f_parallel c c')) = ((size c) + (size c'))%Z) /\
(((ancillas (f_parallel c c')) = ((ancillas c) + (ancillas c'))%Z) /\
((flat (f_parallel c c')) /\
(((flat_ang (f_parallel c c')) =
(fun (x:bitvec) =>
(ang_add ((flat_ang c) (hpart x (width c)))
((flat_ang c') (tpart x (width c)))))) /\
((flat_ket (f_parallel c c')) =
(fun (x:bitvec) =>
(concat ((flat_ket c) (hpart x (width c)))
((flat_ket c') (tpart x (width c)))))))))).
Axiom set_correct_path_sum_flat_pat :
forall (c:circuit) (a:bitvec -> angle) (k:bitvec -> bitvec),
(forall (x:bitvec), ((length x) = (size c)) ->
((pat_sem c (bv_to_ket x)) =
(infix_asdtdt (ang_exp (a x)) (bv_to_ket (k x))))) ->
correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => (k x)) 0%Z.
Axiom get_flat_pat_sem :
forall (c:circuit), (flat c) -> forall (x:bitvec),
((pat_sem c (bv_to_ket x)) =
(infix_asdtdt (ang_exp ((flat_ang c) x)) (bv_to_ket ((flat_ket c) x)))).
Parameter f_place: circuit -> Z -> Z -> circuit.
Axiom f_place_def :
forall (c:circuit) (k:Z) (n:Z), (flat c) -> ((0%Z <= k)%Z /\ (k < n)%Z) ->
((0%Z <= k)%Z /\ (k <= (n - (width c))%Z)%Z) ->
((f_place c k n) = (place c k n)).
Axiom f_place_spec :
forall (c:circuit) (k:Z) (n:Z), (flat c) -> ((0%Z <= k)%Z /\ (k < n)%Z) ->
((0%Z <= k)%Z /\ (k <= (n - (width c))%Z)%Z) ->
(flat (f_place c k n)) /\
(((range (f_place c k n)) = (range c)) /\
(((width (f_place c k n)) = n) /\
(((ancillas (f_place c k n)) = (ancillas c)) /\
((forall (x:bitvec), forall (i:Z), ((length x) = n) ->
((0%Z <= i)%Z /\ (i < n)%Z) ->
(((k <= i)%Z /\ (i < (k + (width c))%Z)%Z) ->
((flat_ket_i (f_place c k n) x i) =
(flat_ket_i c (htpart x k (width c)) (i - k)%Z))) /\
(~ ((k <= i)%Z /\ (i < (k + (width c))%Z)%Z) ->
((flat_ket_i (f_place c k n) x i) = ((getbv x) i)))) /\
((forall (x:bitvec), ((length x) = n) ->
(((flat_ang (f_place c k n)) x) =
((flat_ang c) (htpart x k (width c))))) /\
((width (f_place c k n)) = n)))))).
Parameter f_cont: circuit -> Z -> Z -> Z -> circuit.
Axiom f_cont_def :
forall (c:circuit) (co:Z) (ft:Z) (n:Z), (flat c) ->
((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) ->
((f_cont c co ft n) = (cont c co ft n)).
Parameter fc15: circuit -> Z -> bitvec -> Z -> Z.
Axiom fc_def15 :
forall (c:circuit) (ft:Z) (x:bitvec) (i:Z),
(((ft <= i)%Z /\ (i < (ft + (width c))%Z)%Z) ->
(((fc15 c ft x) i) = (flat_ket_i c (htpart x ft (width c)) (i - ft)%Z))) /\
(~ ((ft <= i)%Z /\ (i < (ft + (width c))%Z)%Z) ->
(((fc15 c ft x) i) = ((getbv x) i))).
Axiom f_cont_spec :
forall (c:circuit) (co:Z) (ft:Z) (n:Z), (flat c) ->
((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) ->
(flat (f_cont c co ft n)) /\
(((width (f_cont c co ft n)) = n) /\
(((range (f_cont c co ft n)) = (range c)) /\
(((ancillas (f_cont c co ft n)) = (ancillas c)) /\
((forall (x:bitvec), ((length x) = n) -> (((getbv x) co) = 0%Z) ->
(((flat_ket (f_cont c co ft n)) x) = x)) /\
((forall (x:bitvec), ((length x) = n) -> (((getbv x) co) = 0%Z) ->
(((flat_ang (f_cont c co ft n)) x) = ang_zero)) /\
((forall (x:bitvec), forall (i:Z), ((length x) = n) ->
((0%Z <= i)%Z /\ (i < n)%Z) -> (((getbv x) co) = 1%Z) ->
(((ft <= i)%Z /\ (i < (ft + (width c))%Z)%Z) ->
((flat_ket_i (f_cont c co ft n) x i) =
(flat_ket_i c (htpart x ft (width c)) (i - ft)%Z))) /\
(~ ((ft <= i)%Z /\ (i < (ft + (width c))%Z)%Z) ->
((flat_ket_i (f_cont c co ft n) x i) = ((getbv x) i)))) /\
((forall (x:bitvec), ((length x) = n) -> (((getbv x) co) = 1%Z) ->
(((flat_ket (f_cont c co ft n)) x) = (make_bv (fc15 c ft x) n))) /\
((forall (x:bitvec), ((length x) = n) -> (((getbv x) co) = 1%Z) ->
(((flat_ang (f_cont c co ft n)) x) =
((flat_ang c) (htpart x ft (width c))))) /\
((forall (x:bitvec), ((length x) = n) -> ((length x) = n) ->
(((getbv x) co) = 0%Z) ->
((pat_sem (f_cont c co ft n) (bv_to_ket x)) = (bv_to_ket x))) /\
((forall (x:bitvec), ((length x) = n) -> (((getbv x) co) = 1%Z) ->
((pat_sem (f_cont c co ft n) (bv_to_ket x)) =
(pat_sem (place c ft n) (bv_to_ket x)))) /\
((size (f_cont c co ft n)) = (cont_size * (size c))%Z))))))))))).
Parameter diag: circuit -> Prop.
Axiom diag_def :
forall (c:circuit),
(diag c) <->
exists a:bitvec -> angle,
correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => x) 0%Z.
Axiom set_diag :
forall (c:circuit) (a:bitvec -> angle),
(correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => x) 0%Z) ->
diag c.
Axiom get_diag :
forall (c:circuit), (diag c) ->
exists a:bitvec -> angle,
correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => x) 0%Z.
Axiom get_diag_sem :
forall (c:circuit), (diag c) ->
exists a:bitvec -> angle,
forall (x:matrix t), (is_a_ket_l x (width c)) -> (is_a_ket_basis_elt x) ->
sem c x (infix_asdtdt (ang_exp (a (ket_to_bv x))) x).
Axiom set_diag_sem :
forall (c:circuit),
(exists a:bitvec -> angle,
forall (x:matrix t), (is_a_ket_l x (width c)) -> (is_a_ket_basis_elt x) ->
sem c x (infix_asdtdt (ang_exp (a (ket_to_bv x))) x)) ->
diag c.
Axiom set_diag_sem_elt :
forall (c:circuit) (a:bitvec -> angle),
(forall (x:matrix t), (is_a_ket_l x (width c)) -> (is_a_ket_basis_elt x) ->
sem c x (infix_asdtdt (ang_exp (a (ket_to_bv x))) x)) ->
diag c.
Parameter diag_ang: circuit -> bitvec -> angle.
Axiom diag_correct :
forall (c:circuit), (diag c) ->
correct_path_sum c (fun (x:bitvec) (us:bitvec) => ((diag_ang c) x))
(fun (x:bitvec) (us:bitvec) => x) 0%Z.
Axiom diag_sem :
forall (c:circuit), (diag c) -> forall (x:bitvec),
((length x) = (width c)) ->
sem c (bv_to_ket x) (infix_asdtdt (ang_exp ((diag_ang c) x)) (bv_to_ket x)).
Axiom set_correct_diag_sim :
forall (c:circuit) (a:bitvec -> angle), (diag c) ->
(forall (x:bitvec), ((length x) = (width c)) -> (((diag_ang c) x) = (a x))) ->
correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => x) 0%Z.
Axiom set_correct_diag_sim_i :
forall (c:circuit) (a:bitvec -> Z -> angle) (l:Z) (h:Z), (diag c) ->
(l <= h)%Z ->
(forall (x:bitvec), ((length x) = (width c)) ->
(((diag_ang c) x) = (ang_sum (a x) l h))) ->
correct_path_sum_i c (fun (x:bitvec) (us:bitvec) (i:Z) => ((a x) i)) l h
(fun (x:bitvec) (us:bitvec) (i:Z) => ((getbv x) i)) 0%Z.
Axiom set_correct_diag_sim_ :
forall (c:circuit) (a:bitvec -> bitvec -> angle), (diag c) ->
(forall (x:bitvec) (y:bitvec) (y':bitvec), (((a x) y) = ((a x) y'))) ->
(forall (x:bitvec) (y:bitvec), ((length x) = (width c)) ->
(((diag_ang c) x) = ((a x) y))) ->
correct_path_sum c a (fun (x:bitvec) (us:bitvec) => x) 0%Z.
Axiom correct_to_diag :
forall (c:circuit) (a:bitvec -> angle),
(correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => x) 0%Z) ->
(diag c) /\
forall (x:bitvec), ((length x) = (width c)) ->
sem c (bv_to_ket x) (infix_asdtdt (ang_exp (a x)) (bv_to_ket x)).
Axiom flat_correct_to_diag :
forall (c:circuit) (a:bitvec -> angle),
(correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => x) 0%Z) ->
(diag c) /\
forall (x:bitvec), ((length x) = (width c)) -> (((diag_ang c) x) = (a x)).
Axiom diag_sem_inst :
forall (c:circuit) (x:bitvec) (a:angle), (diag c) ->
((length x) = (width c)) ->
(sem c (bv_to_ket x) (infix_asdtdt (ang_exp a) (bv_to_ket x))) ->
(a = ((diag_ang c) x)).
Axiom set_diag_eq :
forall (c:circuit) (a:bitvec -> angle),
(forall (x:bitvec), ((length x) = (width c)) ->
sem c (bv_to_ket x) (infix_asdtdt (ang_exp (a x)) (bv_to_ket x))) ->
(diag c) /\
((correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => x) 0%Z) /\
forall (x:bitvec), ((length x) = (width c)) -> ((a x) = ((diag_ang c) x))).
Axiom diag_sem_inst_rev :
forall (c:circuit) (x:bitvec) (a:angle), (diag c) ->
((length x) = (width c)) -> (a = ((diag_ang c) x)) ->
sem c (bv_to_ket x) (infix_asdtdt (ang_exp a) (bv_to_ket x)).
Axiom diag_is_flat : forall (c:circuit), (diag c) -> flat c.
Axiom diag_phase : forall (o:angle), diag (phase o).
Axiom diag_rz : forall (o:angle), diag (rz o).
Axiom seq_pres_diag_pre :
forall (c:circuit) (c':circuit) (a:bitvec -> angle) (a':bitvec -> angle),
((width c) = (width c')) ->
(correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => x) 0%Z) ->
(correct_path_sum c' (fun (x:bitvec) (us:bitvec) => (a' x))
(fun (x:bitvec) (us:bitvec) => x) 0%Z) ->
(correct_path_sum (sequence c c')
(fun (x:bitvec) (us:bitvec) => (ang_add (a x) (a' x)))
(fun (x:bitvec) (us:bitvec) => x) 0%Z) /\
((diag (sequence c c')) /\
forall (x:bitvec), ((length x) = (width (sequence c c'))) ->
(((diag_ang (sequence c c')) x) = (ang_add (a x) (a' x)))).
Axiom par_pres_diag_pre :
forall (c:circuit) (c':circuit) (a:bitvec -> angle) (a':bitvec -> angle),
(correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => x) 0%Z) ->
(correct_path_sum c' (fun (x:bitvec) (us:bitvec) => (a' x))
(fun (x:bitvec) (us:bitvec) => x) 0%Z) ->
(correct_path_sum (parallel c c')
(fun (x:bitvec) (us:bitvec) =>
(ang_add (a (hpart x (width c))) (a' (tpart x (width c)))))
(fun (x:bitvec) (us:bitvec) => x) 0%Z) /\
((diag (parallel c c')) /\
forall (x:bitvec), ((length x) = (width (parallel c c'))) ->
(((diag_ang (parallel c c')) x) =
(ang_add (a (hpart x (width c))) (a' (tpart x (width c)))))).
Parameter diag_sum_scheme_unit: circuit -> (matrix t) -> matrix t.
Axiom diag_sum_scheme_unit_def :
forall (c:circuit) (x:matrix t), (is_a_ket_l x (width c)) ->
(is_a_ket_basis_elt x) -> (diag c) ->
((diag_sum_scheme_unit c x) =
(infix_asdtdt (ang_exp ((diag_ang c) (ket_to_bv x))) x)).
Axiom diag_sum_scheme_unit_spec :
forall (c:circuit) (x:matrix t), (is_a_ket_l x (width c)) ->
(is_a_ket_basis_elt x) -> (diag c) ->
(is_a_ket_l (diag_sum_scheme_unit c x) (width c)) /\
(((diag_sum_scheme_unit c x) =
(path_sum_scheme_unit (fun (x1:bitvec) (us:bitvec) => ((diag_ang c) x1))
(fun (x1:bitvec) (us:bitvec) => x1) (width c) 0%Z (ket_to_bv x))) /\
(is_a_ket_l (diag_sum_scheme_unit c x) (width c))).
Parameter diag_sum_scheme: circuit -> (matrix t) -> matrix t.
Axiom diag_sum_scheme_def :
forall (c:circuit) (x:matrix t), (is_a_ket_l x (width c)) -> (diag c) ->
((diag_sum_scheme c x) =
(ket_sum_l (n_bvs (width c))
(fun (z:bitvec) =>
(infix_asdtdt (get_ket x (bv_to_int z))
(diag_sum_scheme_unit c (bv_to_ket (hpart z (width c))))))
(width c))).
Axiom diag_sum_scheme_spec :
forall (c:circuit) (x:matrix t), (is_a_ket_l x (width c)) -> (diag c) ->
(is_a_ket_l (diag_sum_scheme c x) (width c)) /\
(((diag_sum_scheme c x) =
(ket_sum_l (n_bvs (width c))
(fun (z:bitvec) =>
(infix_asdtdt (get_ket x (bv_to_int z))
(diag_sum_scheme_unit c (bv_to_ket z))))
(width c))) /\
((diag_sum_scheme c x) =
(path_sum_scheme (fun (x1:bitvec) (us:bitvec) => ((diag_ang c) x1))
(fun (x1:bitvec) (us:bitvec) => x1) (width c) 0%Z x))).
Axiom seq_pres_diag :
forall (c:circuit) (c':circuit), ((width c) = (width c')) -> (diag c) ->
(diag c') -> diag (sequence c c').
Axiom par_pres_diag :
forall (c:circuit) (c':circuit), (diag c) -> (diag c') ->
diag (parallel c c').
Axiom pat_sem_diag_basis :
forall (c:circuit) (x:bitvec), (diag c) -> ((length x) = (width c)) ->
((pat_sem c (bv_to_ket x)) =
(infix_asdtdt (ang_exp ((diag_ang c) x)) (bv_to_ket x))).
Axiom sem_diag_basis :
forall (c:circuit) (x:bitvec), (diag c) -> ((length x) = (width c)) ->
sem c (bv_to_ket x) (infix_asdtdt (ang_exp ((diag_ang c) x)) (bv_to_ket x)).
Axiom sem_diag_basis_gen :
forall (c:circuit), (diag c) -> forall (x:bitvec),
((length x) = (width c)) ->
sem c (bv_to_ket x) (infix_asdtdt (ang_exp ((diag_ang c) x)) (bv_to_ket x)).
Axiom set_diag_ang :
forall (c:circuit) (f:bitvec -> angle),
(forall (x:bitvec), ((length x) = (width c)) ->
((pat_sem c (bv_to_ket x)) = (infix_asdtdt (ang_exp (f x)) (bv_to_ket x)))) ->
(diag c) /\
forall (x:bitvec), ((length x) = (width c)) -> (((diag_ang c) x) = (f x)).
Axiom set_diag_ang_sem :
forall (c:circuit) (f:bitvec -> angle),
(forall (x:matrix t), (is_a_ket_l x (width c)) -> (is_a_ket_basis_elt x) ->
sem c x (infix_asdtdt (ang_exp (f (ket_to_bv x))) x)) ->
(diag c) /\
forall (x:bitvec), ((length x) = (width c)) -> (((diag_ang c) x) = (f x)).
Axiom diag_ang_phase :
forall (o:angle), ((diag_ang (phase o)) = (fun (us:bitvec) => o)).
Axiom diag_ang_rz :
forall (o:angle),
((diag_ang (rz o)) =
(fun (x:bitvec) => (phase_inv_ (1%Z - ((getbv x) 0%Z))%Z o))).
Axiom diag_ang_cnot : ((diag_ang cnot) = (fun (us:bitvec) => ang_zero)).
Axiom diag_ang_sequence :
forall (c:circuit) (c':circuit), (diag c) -> (diag c') ->
((diag_ang (sequence c c')) =
(fun (x:bitvec) => (ang_add ((diag_ang c) x) ((diag_ang c') x)))).
Axiom diag_ang_parallel :
forall (c:circuit) (c':circuit), (diag c) -> (diag c') ->
((diag_ang (parallel c c')) =
(fun (x:bitvec) =>
(ang_add ((diag_ang c) (hpart x (width c)))
((diag_ang c') (tpart x (width c)))))).
Parameter d_sequence: circuit -> circuit -> circuit.
Axiom d_sequence_def :
forall (c:circuit) (c':circuit), (diag c) -> (diag c') ->
((width c) = (width c')) -> ((d_sequence c c') = (sequence c c')).
Axiom d_sequence_spec :
forall (c:circuit) (c':circuit), (diag c) -> (diag c') ->
((width c) = (width c')) ->
((size (d_sequence c c')) = ((size c) + (size c'))%Z) /\
(((ancillas (d_sequence c c')) =
(ZArith.BinInt.Z.max (ancillas c) (ancillas c'))) /\
(((width (d_sequence c c')) = (width c)) /\
((diag (d_sequence c c')) /\
((diag_ang (d_sequence c c')) =
(fun (x:bitvec) => (ang_add ((diag_ang c) x) ((diag_ang c') x))))))).
Axiom d_sequence_eq :
forall (d:circuit) (d':circuit) (e1:circuit) (e':circuit), (diag d) ->
(diag e1) -> ((width d) = (width e1)) -> (d = d') -> (e1 = e') ->
((d_sequence d e1) = (d_sequence d' e')).
Parameter d_parallel: circuit -> circuit -> circuit.
Axiom d_parallel_def :
forall (c:circuit) (c':circuit), (diag c) -> (diag c') ->
((d_parallel c c') = (parallel c c')).
Axiom d_parallel_spec :
forall (c:circuit) (c':circuit), (diag c) -> (diag c') ->
((size (d_parallel c c')) = ((size c) + (size c'))%Z) /\
(((ancillas (d_parallel c c')) = ((ancillas c) + (ancillas c'))%Z) /\
(((width (d_parallel c c')) = ((width c) + (width c'))%Z) /\
((diag (d_parallel c c')) /\
((diag_ang (d_parallel c c')) =
(fun (x:bitvec) =>
(ang_add ((diag_ang c) (hpart x (width c)))
((diag_ang c') (tpart x (width c))))))))).
Axiom d_parallel_eq :
forall (d:circuit) (d':circuit) (e1:circuit) (e':circuit), (diag d) ->
(diag e1) -> (d = d') -> (e1 = e') ->
((d_parallel d e1) = (d_parallel d' e')).
Parameter d_place: circuit -> Z -> Z -> circuit.
Axiom d_place_def :
forall (c:circuit) (k:Z) (n:Z), (diag c) -> ((0%Z <= k)%Z /\ (k < n)%Z) ->
((0%Z <= k)%Z /\ (k <= (n - (width c))%Z)%Z) ->
((d_place c k n) = (place c k n)).
Axiom d_place_spec :
forall (c:circuit) (k:Z) (n:Z), (diag c) -> ((0%Z <= k)%Z /\ (k < n)%Z) ->
((0%Z <= k)%Z /\ (k <= (n - (width c))%Z)%Z) ->
(diag (d_place c k n)) /\
(((width (d_place c k n)) = n) /\
(((ancillas (d_place c k n)) = (ancillas c)) /\
forall (x:bitvec), ((length x) = n) ->
(((diag_ang (d_place c k n)) x) = ((diag_ang c) (htpart x k (width c)))))).
Parameter d_seq_iter: (Z -> circuit) -> Z -> Z -> Z -> circuit.
Axiom d_seq_iter_def :
forall (f:Z -> circuit) (d:Z) (i:Z) (j:Z), (i < j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((width (f k)) = d)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> diag (f k)) ->
((j = (i + 1%Z)%Z) -> ((d_seq_iter f d i j) = (f i))) /\
(~ (j = (i + 1%Z)%Z) ->
((d_seq_iter f d i j) =
(d_sequence (d_seq_iter f d i (j - 1%Z)%Z) (f (j - 1%Z)%Z)))).
Axiom d_seq_iter_spec :
forall (f:Z -> circuit) (d:Z) (i:Z) (j:Z), (i < j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((width (f k)) = d)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> diag (f k)) ->
(diag (d_seq_iter f d i j)) /\
(((width (d_seq_iter f d i j)) = d) /\
forall (x:bitvec), ((length x) = d) ->
(((diag_ang (d_seq_iter f d i j)) x) =
(ang_sum (fun (k:Z) => ((diag_ang (f k)) x)) i j))).
Axiom d_seq_iter_one :
forall (f:Z -> circuit) (d:Z) (i:Z) (j:Z), ((i + 1%Z)%Z = j) ->
((width (f i)) = d) -> (diag (f i)) -> ((d_seq_iter f d i j) = (f i)).
Axiom d_seq_iter_plus_one :
forall (f:Z -> circuit) (d:Z) (i:Z) (j:Z), ((i + 1%Z)%Z < j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((width (f k)) = d)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> diag (f k)) ->
((d_seq_iter f d i j) =
(d_sequence (d_seq_iter f d i (j - 1%Z)%Z) (f (j - 1%Z)%Z))).
Axiom d_seq_iter_eq :
forall (f:Z -> circuit) (g:Z -> circuit) (d:Z) (i:Z) (j:Z), (i < j)%Z ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((width (f k)) = d)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> diag (f k)) ->
(forall (k:Z), ((i <= k)%Z /\ (k < j)%Z) -> ((f k) = (g k))) ->
((d_seq_iter g d i j) = (d_seq_iter f d i j)).
Parameter rzp: Z -> circuit.
Axiom rzp_def :
forall (n:Z), (n >= 0%Z)%Z ->
((rzp n) =
(d_sequence (phase (int_to_ang 1%Z (n + 1%Z)%Z))
(rz (int_to_ang 1%Z (n + 1%Z)%Z)))).
Axiom rzp_spec :
forall (n:Z), (n >= 0%Z)%Z ->
((size (rzp n)) = 2%Z) /\
(((ancillas (rzp n)) = 0%Z) /\
(((width (rzp n)) = 1%Z) /\
((diag (rzp n)) /\
forall (x:bitvec), ((length x) = 1%Z) ->
(((diag_ang (rzp n)) x) = (int_to_ang ((getbv x) 0%Z) n))))).
Parameter przp: Z -> Z -> Z -> circuit.
Axiom przp_def :
forall (i:Z) (k:Z) (n:Z), (0%Z <= i)%Z -> (n >= 0%Z)%Z ->
((0%Z <= k)%Z /\ (k < n)%Z) -> ((przp i k n) = (d_place (rzp i) k n)).
Axiom przp_spec :
forall (i:Z) (k:Z) (n:Z), (0%Z <= i)%Z -> (n >= 0%Z)%Z ->
((0%Z <= k)%Z /\ (k < n)%Z) ->
((size (przp i k n)) = 2%Z) /\
(((ancillas (przp i k n)) = 0%Z) /\
(((width (przp i k n)) = n) /\
((diag (przp i k n)) /\
((forall (x:bitvec), ((length x) = n) ->
(((diag_ang (przp i k n)) x) = (int_to_ang ((getbv x) k) i))) /\
((i <= n)%Z -> forall (x:bitvec), ((length x) = n) ->
(((diag_ang (przp i k n)) x) =
(int_to_ang (((getbv x) k) * (power_ 2%Z (n - i)%Z))%Z n))))))).
Parameter rzp_neg: Z -> circuit.
Axiom rzp_neg_def :
forall (n:Z), (n >= 0%Z)%Z ->
((rzp_neg n) =
(d_sequence (phase (int_to_ang (-1%Z)%Z (n + 1%Z)%Z))
(rz (int_to_ang (-1%Z)%Z (n + 1%Z)%Z)))).
Axiom rzp_neg_spec :
forall (n:Z), (n >= 0%Z)%Z ->
((width (rzp_neg n)) = 1%Z) /\
((diag (rzp_neg n)) /\
forall (x:bitvec), ((length x) = 1%Z) ->
(((diag_ang (rzp_neg n)) x) = (int_to_ang (-((getbv x) 0%Z))%Z n))).
Parameter dplace: circuit -> Z -> Z -> circuit.
Axiom dplace_def :
forall (c:circuit) (k:Z) (n:Z), (k >= 0%Z)%Z ->
(n >= ((width c) + k)%Z)%Z -> (diag c) -> ((dplace c k n) = (place c k n)).
Axiom dplace_spec :
forall (c:circuit) (k:Z) (n:Z), (k >= 0%Z)%Z ->
(n >= ((width c) + k)%Z)%Z -> (diag c) ->
(diag (dplace c k n)) /\
(((width (dplace c k n)) = n) /\
forall (x:bitvec), ((length x) = n) ->
(((diag_ang (dplace c k n)) x) = ((diag_ang c) (htpart x k (width c))))).
Parameter dcont: circuit -> Z -> Z -> Z -> circuit.
Axiom dcont_def :
forall (c:circuit) (co:Z) (ft:Z) (n:Z), ((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) -> (diag c) ->
((dcont c co ft n) = (cont c co ft n)).
Axiom dcont_spec :
forall (c:circuit) (co:Z) (ft:Z) (n:Z), ((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) -> (diag c) ->
((ancillas (dcont c co ft n)) = (ancillas c)) /\
(((size (dcont c co ft n)) <= (cont_size * (size c))%Z)%Z /\
((diag (dcont c co ft n)) /\
(((width (dcont c co ft n)) = n) /\
forall (x:bitvec), ((length x) = n) ->
(((diag_ang (dcont c co ft n)) x) =
(ang_mult_int ((diag_ang c) (htpart x ft (width c))) ((getbv x) co)))))).
Parameter d_cont: circuit -> Z -> Z -> Z -> circuit.
Axiom d_cont_def :
forall (c:circuit) (co:Z) (ft:Z) (n:Z), ((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) -> (diag c) ->
((d_cont c co ft n) = (dcont c co ft n)).
Axiom d_cont_spec :
forall (c:circuit) (co:Z) (ft:Z) (n:Z), ((0%Z <= co)%Z /\ (co < n)%Z) ->
((0%Z <= ft)%Z /\ (ft <= (n - (width c))%Z)%Z) ->
((ft <= co)%Z -> ((ft + (width c))%Z <= co)%Z) -> (diag c) ->
(diag (d_cont c co ft n)) /\
(((width (d_cont c co ft n)) = n) /\
forall (x:bitvec), ((length x) = n) ->
((((getbv x) co) = 1%Z) ->
(((diag_ang (d_cont c co ft n)) x) =
((diag_ang c) (htpart x ft (width c))))) /\
(~ (((getbv x) co) = 1%Z) ->
(((diag_ang (d_cont c co ft n)) x) = ang_zero))).
Parameter c_rzp_pos: Z -> Z -> Z -> Z -> circuit.
Axiom c_rzp_pos_def :
forall (k:Z) (co:Z) (ft:Z) (n:Z), (k >= 0%Z)%Z -> (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= ft)%Z /\ (ft < n)%Z) ->
((ft <= co)%Z -> (ft < co)%Z) ->
((c_rzp_pos k co ft n) = (dcont (rzp k) co ft n)).
Axiom c_rzp_pos_spec :
forall (k:Z) (co:Z) (ft:Z) (n:Z), (k >= 0%Z)%Z -> (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= ft)%Z /\ (ft < n)%Z) ->
((ft <= co)%Z -> (ft < co)%Z) ->
((width (c_rzp_pos k co ft n)) = n) /\
(((ancillas (c_rzp_pos k co ft n)) = 0%Z) /\
(((size (c_rzp_pos k co ft n)) <= (cont_size * 2%Z)%Z)%Z /\
((diag (c_rzp_pos k co ft n)) /\
((forall (x:bitvec), ((length x) = n) ->
(((diag_ang (c_rzp_pos k co ft n)) x) =
(int_to_ang (((getbv x) co) * ((getbv x) ft))%Z k))) /\
((forall (x:bitvec), forall (m:Z), (m >= k)%Z -> ((length x) = n) ->
(((diag_ang (c_rzp_pos k co ft n)) x) =
(int_to_ang
((((getbv x) co) * ((getbv x) ft))%Z * (power 2%Z (m - k)%Z))%Z m))) /\
forall (x:bitvec), forall (m:Z), (m >= k)%Z -> ((length x) = n) ->
(((diag_ang (c_rzp_pos k co ft n)) x) =
(int_to_ang
((((getbv x) co) * ((getbv x) ft))%Z * (power_ 2%Z (m - k)%Z))%Z m))))))).
Parameter c_rzp_neg: Z -> Z -> Z -> Z -> circuit.
Axiom c_rzp_neg_def :
forall (k:Z) (co:Z) (ft:Z) (n:Z), (k >= 0%Z)%Z -> (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= ft)%Z /\ (ft < n)%Z) ->
((ft <= co)%Z -> (ft < co)%Z) ->
((c_rzp_neg k co ft n) = (dcont (rzp_neg k) co ft n)).
Axiom c_rzp_neg_spec :
forall (k:Z) (co:Z) (ft:Z) (n:Z), (k >= 0%Z)%Z -> (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= ft)%Z /\ (ft < n)%Z) ->
((ft <= co)%Z -> (ft < co)%Z) ->
((ancillas (c_rzp_neg k co ft n)) = 0%Z) /\
(((size (c_rzp_neg k co ft n)) <= (cont_size * 2%Z)%Z)%Z /\
(((width (c_rzp_neg k co ft n)) = n) /\
((diag (c_rzp_neg k co ft n)) /\
((forall (x:bitvec), ((length x) = n) ->
(((diag_ang (c_rzp_neg k co ft n)) x) =
(int_to_ang ((-((getbv x) co))%Z * ((getbv x) ft))%Z k))) /\
((forall (x:bitvec), forall (m:Z), (m >= k)%Z -> ((length x) = n) ->
(((diag_ang (c_rzp_neg k co ft n)) x) =
(int_to_ang
(((-((getbv x) co))%Z * ((getbv x) ft))%Z *
(power 2%Z (m - k)%Z))%Z
m))) /\
forall (x:bitvec), forall (m:Z), (m >= k)%Z -> ((length x) = n) ->
(((diag_ang (c_rzp_neg k co ft n)) x) =
(int_to_ang
(((-((getbv x) co))%Z * ((getbv x) ft))%Z *
(power_ 2%Z (m - k)%Z))%Z
m))))))).
Parameter c_rzp: Z -> Z -> Z -> Z -> circuit.
Axiom c_rzp_def :
forall (k:Z) (co:Z) (ft:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= ft)%Z /\ (ft < n)%Z) ->
((ft <= co)%Z -> (ft < co)%Z) ->
((k >= 0%Z)%Z -> ((c_rzp k co ft n) = (c_rzp_pos k co ft n))) /\
(~ (k >= 0%Z)%Z -> ((c_rzp k co ft n) = (c_rzp_neg (-k)%Z co ft n))).
Axiom c_rzp_spec :
forall (k:Z) (co:Z) (ft:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= ft)%Z /\ (ft < n)%Z) ->
((ft <= co)%Z -> (ft < co)%Z) ->
((width (c_rzp k co ft n)) = n) /\
(((ancillas (c_rzp k co ft n)) = 0%Z) /\
(((size (c_rzp k co ft n)) <= (cont_size * 2%Z)%Z)%Z /\
((diag (c_rzp k co ft n)) /\
((forall (x:bitvec), ((length x) = n) ->
(((diag_ang (c_rzp k co ft n)) x) =
(int_to_ang (((getbv x) co) * ((getbv x) ft))%Z k))) /\
((forall (x:bitvec), forall (m:Z), (m >= k)%Z -> ((length x) = n) ->
(((diag_ang (c_rzp k co ft n)) x) =
(int_to_ang
((((getbv x) co) * ((getbv x) ft))%Z * (power 2%Z (m - k)%Z))%Z m))) /\
forall (x:bitvec), forall (m:Z), (m >= k)%Z -> ((length x) = n) ->
(((diag_ang (c_rzp k co ft n)) x) =
(int_to_ang
((((getbv x) co) * ((getbv x) ft))%Z * (power_ 2%Z (m - k)%Z))%Z m))))))).
Parameter xx: unit -> circuit.
Axiom xx_def :
forall (us:unit),
((xx us) = (sequence hadamard (sequence (rzp 1%Z) hadamard))).
Axiom xx_spec :
forall (us:unit),
(flat (xx us)) /\
(((size (xx us)) = 4%Z) /\
(((ancillas (xx us)) = 0%Z) /\
(((width (xx us)) = 1%Z) /\
((forall (x:bitvec), ((length x) = 1%Z) ->
(((flat_ang (xx us)) x) = ang_zero)) /\
forall (x:bitvec), ((length x) = 1%Z) ->
(((getbv ((flat_ket (xx us)) x)) 0%Z) = (1%Z - ((getbv x) 0%Z))%Z))))).
Parameter place_xx: Z -> Z -> circuit.
Axiom place_xx_def :
forall (c:Z) (n:Z), ((0%Z <= c)%Z /\ (c < n)%Z) ->
((place_xx c n) = (place (xx tt) c n)).
Parameter fc16: Z -> bitvec -> Z -> Z.
Axiom fc_def16 :
forall (c:Z) (x:bitvec) (i:Z),
((i = c) -> (((fc16 c x) i) = (1%Z - ((getbv x) c))%Z)) /\
(~ (i = c) -> (((fc16 c x) i) = ((getbv x) i))).
Axiom place_xx_spec :
forall (c:Z) (n:Z), ((0%Z <= c)%Z /\ (c < n)%Z) ->
(flat (place_xx c n)) /\
(((size (place_xx c n)) = 4%Z) /\
(((ancillas (place_xx c n)) = 0%Z) /\
(((width (place_xx c n)) = n) /\
((forall (x:bitvec), ((length x) = n) ->
(((flat_ang (place_xx c n)) x) = ang_zero)) /\
((forall (x:bitvec), ((length x) = n) ->
((flat_ket_i (place_xx c n) x c) = (1%Z - ((getbv x) c))%Z)) /\
((forall (x:bitvec), forall (i:Z), ((length x) = n) ->
((0%Z <= i)%Z /\ (i < n)%Z) -> ~ (i = c) ->
((flat_ket_i (place_xx c n) x i) = ((getbv x) i))) /\
forall (x:bitvec), ((length x) = n) ->
(((flat_ket (place_xx c n)) x) = (make_bv (fc16 c x) n)))))))).
Parameter x_kron: Z -> circuit.
Axiom x_kron_def :
forall (n:Z), (0%Z < n)%Z ->
((n = 1%Z) -> ((x_kron n) = (xx tt))) /\
(~ (n = 1%Z) -> ((x_kron n) = (f_parallel (x_kron (n - 1%Z)%Z) (xx tt)))).
Axiom x_kron_spec :
forall (n:Z), (0%Z < n)%Z ->
(flat (x_kron n)) /\
(((width (x_kron n)) = n) /\
((forall (x:bitvec), ((length x) = n) ->
(((flat_ang (x_kron n)) x) = ang_zero)) /\
((forall (x:bitvec), ((length x) = n) ->
(((flat_ket (x_kron n)) x) =
(make_bv (fun (i:Z) => (1%Z - ((getbv x) i))%Z) n))) /\
forall (x:bitvec), forall (i:Z), ((length x) = n) ->
((0%Z <= i)%Z /\ (i < n)%Z) ->
(((getbv ((flat_ket (x_kron n)) x)) i) = (1%Z - ((getbv x) i))%Z)))).
Parameter gen_phase: angle -> Z -> circuit.
Axiom gen_phase_def :
forall (o:angle) (n:Z), (0%Z < n)%Z ->
((gen_phase o n) = (dplace (phase o) 0%Z n)).
Axiom gen_phase_spec :
forall (o:angle) (n:Z), (0%Z < n)%Z ->
(diag (gen_phase o n)) /\
(((width (gen_phase o n)) = n) /\
forall (x:bitvec), ((length x) = n) ->
(((diag_ang (gen_phase o n)) x) = o)).
Parameter correct_flat:
circuit -> (bitvec -> angle) -> (bitvec -> bitvec) -> Prop.
Axiom correct_flat_def :
forall (c:circuit) (a:bitvec -> angle) (b:bitvec -> bitvec),
(correct_flat c a b) <->
(correct_path_sum c (fun (x:bitvec) (us:bitvec) => (a x))
(fun (x:bitvec) (us:bitvec) => (b x)) 0%Z).
Axiom correct_flat_spec : forall (c:circuit), flat c.
Axiom set_correct_flat :
forall (c:circuit), (flat c) -> correct_flat c (flat_ang c) (flat_ket c).
Axiom set_correct_flat_sim_diag :
forall (c:circuit) (a:bitvec -> angle) (b:bitvec -> bitvec), (diag c) ->
(forall (x:bitvec), ((length x) = (width c)) -> (((diag_ang c) x) = (a x))) ->
(forall (x:bitvec), ((length x) = (width c)) -> ((b x) = x)) ->
correct_flat c a b.
Axiom set_correct_diag :
forall (c:circuit), (diag c) ->
correct_flat c (diag_ang c) (fun (y:bitvec) => y).
Axiom get_diag_from_correct_flat :
forall (c:circuit) (a:bitvec -> angle),
(correct_flat c (diag_ang c) (fun (y:bitvec) => y)) ->
(diag c) /\
forall (x:bitvec), ((length x) = (width c)) -> (((diag_ang c) x) = (a x)).
Parameter flat_sequ:
circuit -> circuit -> (bitvec -> angle) -> (bitvec -> angle) ->
(bitvec -> angle) -> (bitvec -> bitvec) -> (bitvec -> bitvec) ->
(bitvec -> bitvec) -> Z -> circuit.
Axiom flat_sequ_def :
forall (c:circuit) (c':circuit) (ase:bitvec -> angle) (a:bitvec -> angle)
(a':bitvec -> angle) (bse:bitvec -> bitvec) (b:bitvec -> bitvec)
(b':bitvec -> bitvec) (s:Z),
(flat c) -> (flat c') -> (((width c) = (width c')) /\ ((width c') = s)) ->
(correct_flat c a b) -> (correct_flat c' a' b') ->
(forall (x:bitvec), ((length x) = s) ->
((ase x) = (ang_add (a x) (a' (b x))))) ->
(forall (x:bitvec), ((length x) = s) -> ((bse x) = (b' (b x)))) ->
((flat_sequ c c' ase a a' bse b b' s) = (sequence c c')).
Axiom flat_sequ_spec :
forall (c:circuit) (c':circuit) (ase:bitvec -> angle) (a:bitvec -> angle)
(a':bitvec -> angle) (bse:bitvec -> bitvec) (b:bitvec -> bitvec)
(b':bitvec -> bitvec) (s:Z),
(flat c) -> (flat c') -> (((width c) = (width c')) /\ ((width c') = s)) ->
(correct_flat c a b) -> (correct_flat c' a' b') ->
(forall (x:bitvec), ((length x) = s) ->
((ase x) = (ang_add (a x) (a' (b x))))) ->
(forall (x:bitvec), ((length x) = s) -> ((bse x) = (b' (b x)))) ->
(correct_flat (flat_sequ c c' ase a a' bse b b' s) ase bse) /\
(((width (flat_sequ c c' ase a a' bse b b' s)) = s) /\
(correct_path_sum (flat_sequ c c' ase a a' bse b b' s)
(fun (x:bitvec) (us:bitvec) => (ase x))
(fun (x:bitvec) (us:bitvec) => (bse x)) 0%Z)).
Parameter choose_filter:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> bool) -> a.
Axiom choose_filter_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (p:a -> bool),
(exists e1:a, (mem e1 s) /\ ((p e1) = true)) ->
(((p (choose s)) = true) -> ((choose_filter s p) = (choose s))) /\
(~ ((p (choose s)) = true) ->
((choose_filter s p) = (choose_filter (remove (choose s) s) p))).
Axiom choose_filter_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (p:a -> bool),
(exists e1:a, (mem e1 s) /\ ((p e1) = true)) ->
((p (choose_filter s p)) = true) /\ (mem (choose_filter s p) s).
Parameter my_filter:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> bool) -> set a.
Axiom my_filter_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (p:a -> bool),
((is_empty s) -> ((my_filter s p) = (empty : set a))) /\
(~ (is_empty s) ->
(((p (choose s)) = true) ->
((my_filter s p) = (add (choose s) (my_filter (remove (choose s) s) p)))) /\
(~ ((p (choose s)) = true) ->
((my_filter s p) = (my_filter (remove (choose s) s) p)))).
Axiom my_filter_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (p:a -> bool),
(forall (e1:a), (mem e1 s) -> ((p e1) = true) <-> (mem e1 (my_filter s p))) /\
((forall (e1:a), (mem e1 (my_filter s p)) -> mem e1 s) /\
((0%Z <= (cardinal (my_filter s p)))%Z /\
((cardinal (my_filter s p)) <= (cardinal s))%Z)).
Axiom in_my_filter :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (p:a -> bool) (e1:a), (mem e1 s) -> ((p e1) = true) ->
mem e1 (my_filter s p).
Axiom my_filter_inter :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (p1:a -> bool) (p2:a -> bool),
(forall (e1:a), (mem e1 s) -> ((p1 e1) = true) -> ~ ((p2 e1) = true)) ->
((inter (my_filter s p1) (my_filter s p2)) = (empty : set a)).
Axiom my_filter_union :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (p1:a -> bool) (p2:a -> bool),
(forall (e1:a), (mem e1 s) -> ~ ((p1 e1) = true) -> ((p2 e1) = true)) ->
((union (my_filter s p1) (my_filter s p2)) = s).
Parameter adjoint: (matrix t) -> matrix t.
Axiom adjoint_def :
forall (m:matrix t),
((adjoint m) =
(make_f (columns m) (rows m) (fun (x:Z) (y:Z) => (conjugate (get m y x))))).
Axiom adjoint_spec :
forall (m:matrix t),
((rows (adjoint m)) = (columns m)) /\
(((columns (adjoint m)) = (rows m)) /\
((forall (i:Z) (j:Z),
(valid_index (adjoint m) i j) <-> (valid_index m j i)) /\
forall (i:Z) (j:Z), (valid_index (adjoint m) i j) ->
((get (adjoint m) i j) = (conjugate (get m j i))))).
Axiom adjoint_rows : forall (m:matrix t), ((rows (adjoint m)) = (columns m)).
Axiom adjoint_columns :
forall (m:matrix t), ((columns (adjoint m)) = (rows m)).
Axiom adjoint_value :
forall (m:matrix t) (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < (columns m))%Z) ->
((0%Z <= j)%Z /\ (j < (rows m))%Z) ->
((get (adjoint m) i j) = (conjugate (get m j i))).
Axiom adjoint_values :
forall (m:matrix t), forall (i:Z) (j:Z),
((0%Z <= i)%Z /\ (i < (columns m))%Z) ->
((0%Z <= j)%Z /\ (j < (rows m))%Z) ->
((get (adjoint m) i j) = (conjugate (get m j i))).
Axiom adjoint_invol : forall (m:matrix t), ((adjoint (adjoint m)) = m).
Axiom get_adjoint :
forall (m:matrix t) (n:matrix t), ((rows m) = (columns n)) ->
((columns m) = (rows n)) ->
(forall (i:Z) (j:Z), (valid_index m i j) ->
((get m i j) = (conjugate (get n j i)))) ->
((adjoint m) = n).
Axiom set_adjoint :
forall (m:matrix t) (n:matrix t), ((rows m) = (columns n)) ->
((columns m) = (rows n)) ->
(forall (i:Z) (j:Z), (valid_index m i j) ->
((get m i j) = (conjugate (get n j i)))) ->
(m = (adjoint n)).
Parameter is_a_bra: (matrix t) -> Prop.
Axiom is_a_bra_def :
forall (m:matrix t),
(is_a_bra m) <->
(((rows m) = 1%Z) /\
exists s:Z, (s >= 0%Z)%Z /\ ((columns m) = (power 2%Z s))).
Parameter is_a_bra_l: (matrix t) -> Z -> Prop.
Axiom is_a_bra_l_def :
forall (m:matrix t) (l:Z),
(is_a_bra_l m l) <->
((l >= 0%Z)%Z /\ (((rows m) = 1%Z) /\ ((columns m) = (power 2%Z l)))).
Axiom bra_l_is_a_bra :
forall (m:matrix t), (exists l:Z, (l >= 0%Z)%Z /\ (is_a_bra_l m l)) ->
is_a_bra m.
Axiom set_is_a_bra :
forall (m:matrix t), ((rows m) = 1%Z) ->
(exists s:Z, (s >= 0%Z)%Z /\ ((columns m) = (power 2%Z s))) -> is_a_bra m.
Axiom set_is_a_bra_l :
forall (m:matrix t) (l:Z), (l >= 0%Z)%Z -> ((rows m) = 1%Z) ->
((columns m) = (power 2%Z l)) -> is_a_bra_l m l.
Axiom set_is_a_bra_p :
forall (m:matrix t) (l:Z), (l >= 0%Z)%Z -> ((rows m) = 1%Z) ->
((columns m) = (power 2%Z l)) -> is_a_bra m.
Parameter bra_to_ket_pre: (matrix t) -> matrix t.
Axiom bra_to_ket_pre_def :
forall (m:matrix t), (is_a_bra m) -> ((bra_to_ket_pre m) = (adjoint m)).
Axiom bra_to_ket_pre_spec :
forall (m:matrix t), (is_a_bra m) -> is_a_ket (bra_to_ket_pre m).
Parameter bra_length: (matrix t) -> Z.
Axiom bra_length_def :
forall (m:matrix t), (is_a_bra m) ->
((bra_length m) = (ket_length (bra_to_ket_pre m))).
Axiom bra_length_spec :
forall (m:matrix t), (is_a_bra m) ->
((bra_length m) >= 0%Z)%Z /\
(((columns m) = (power 2%Z (bra_length m))) /\
(is_a_bra_l m (bra_length m))).
Axiom bra_l_length :
forall (m:matrix t) (l:Z), (l >= 0%Z)%Z -> (is_a_bra_l m l) ->
((bra_length m) = l).
Axiom get_bra_rows : forall (m:matrix t), (is_a_bra m) -> ((rows m) = 1%Z).
Axiom get_bra_columns :
forall (m:matrix t), (is_a_bra m) ->
((columns m) = (power 2%Z (bra_length m))).
Axiom get_is_a_bra :
forall (m:matrix t), (is_a_bra m) ->
((rows m) = 1%Z) /\ ((columns m) = (power 2%Z (bra_length m))).
Axiom get_bra_length :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z -> (is_a_bra m) ->
((columns m) = (power 2%Z n)) -> ((bra_length m) = n).
Axiom set_bra_length :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z -> (is_a_bra m) ->
((bra_length m) = n) -> ((columns m) = (power 2%Z n)).
Parameter get_bra: (matrix t) -> Z -> t.
Axiom get_bra_def :
forall (m:matrix t) (i:Z), (is_a_bra m) ->
((0%Z <= i)%Z /\ (i < (power 2%Z (bra_length m)))%Z) ->
((get_bra m i) = (get m 0%Z i)).
Axiom get_to_get_bra :
forall (m:matrix t) (i:Z) (j:Z), (is_a_bra m) ->
((0%Z <= j)%Z /\ (j < (power 2%Z (bra_length m)))%Z) -> (i = 0%Z) ->
((get m i j) = (get_bra m j)).
Axiom get_to_get_ket :
forall (m:matrix t) (i:Z) (j:Z), (is_a_ket m) ->
((0%Z <= i)%Z /\ (i < (power 2%Z (bra_length m)))%Z) -> (j = 0%Z) ->
((get m i j) = (get_ket m i)).
Axiom get_to_get_bra_gen :
forall (m:matrix t), (is_a_bra m) -> forall (i:Z) (j:Z), (i = 0%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z (bra_length m)))%Z) ->
((get m i j) = (get_bra m j)).
Axiom get_to_get_ket_gen :
forall (m:matrix t), (is_a_ket m) -> forall (i:Z) (j:Z), (j = 0%Z) ->
((0%Z <= i)%Z /\ (i < (power 2%Z (bra_length m)))%Z) ->
((get m i j) = (get_ket m i)).
Parameter bra_to_ket: (matrix t) -> matrix t.
Axiom bra_to_ket_def :
forall (m:matrix t), (is_a_bra m) -> ((bra_to_ket m) = (adjoint m)).
Axiom bra_to_ket_spec :
forall (m:matrix t), (is_a_bra m) ->
((rows (bra_to_ket m)) = (columns m)) /\
(((columns (bra_to_ket m)) = 1%Z) /\
(((bra_to_ket m) = (bra_to_ket_pre m)) /\
((is_a_ket (bra_to_ket m)) /\
(((ket_length (bra_to_ket m)) = (bra_length m)) /\
forall (i:Z), ((0%Z <= i)%Z /\ (i < (power 2%Z (bra_length m)))%Z) ->
((get_ket (bra_to_ket m) i) = (conjugate (get_bra m i))))))).
Axiom get_bra_to_get_ket :
forall (m:matrix t) (i:Z), (is_a_bra m) ->
((0%Z <= i)%Z /\ (i < (power 2%Z (bra_length m)))%Z) ->
((get_bra m i) = (conjugate (get_ket (adjoint m) i))).
Axiom bra_length_to_ket_length :
forall (m:matrix t), (is_a_bra m) ->
((bra_length m) = (ket_length (adjoint m))).
Axiom bra_to_ket_to_adjoint :
forall (m:matrix t), (is_a_bra m) -> ((adjoint m) = (bra_to_ket m)).
Parameter is_a_bra_basis_elt: (matrix t) -> Prop.
Axiom is_a_bra_basis_elt_def :
forall (m:matrix t),
(is_a_bra_basis_elt m) <->
((is_a_bra m) /\ (is_a_ket_basis_elt (bra_to_ket m))).
Axiom set_is_a_bra_basis_elt_p :
forall (m:matrix t) (j:Z), (is_a_bra m) ->
((0%Z <= j)%Z /\ (j < (power 2%Z (bra_length m)))%Z) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (power 2%Z (bra_length m)))%Z) ->
((get_bra m i) = (indic i j))) ->
is_a_bra_basis_elt m.
Axiom set_is_a_bra_basis_elt :
forall (m:matrix t), (is_a_bra m) ->
(exists j:Z,
((0%Z <= j)%Z /\ (j < (power 2%Z (bra_length m)))%Z) /\
forall (i:Z), ((0%Z <= j)%Z /\ (j < (power 2%Z (bra_length m)))%Z) ->
((get_bra m i) = (indic i j))) ->
is_a_bra_basis_elt m.
Axiom get_is_a_bra_basis_elt :
forall (m:matrix t), (is_a_bra m) -> (is_a_bra_basis_elt m) ->
exists j:Z,
((0%Z <= j)%Z /\ (j < (power 2%Z (bra_length m)))%Z) /\
forall (i:Z), ((0%Z <= i)%Z /\ (i < (power 2%Z (bra_length m)))%Z) ->
((get_bra m i) = (indic i j)).
Parameter bra: Z -> Z -> matrix t.
Axiom bra_def :
forall (n:Z) (i:Z), (0%Z <= n)%Z -> ((bra n i) = (adjoint (ket n i))).
Axiom bra_spec :
forall (n:Z) (i:Z), (0%Z <= n)%Z ->
(is_a_bra (bra n i)) /\
((((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> is_a_bra_l (bra n i) n) /\
((((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> ((bra_length (bra n i)) = n)) /\
((((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((columns (bra n i)) = (power 2%Z n))) /\
(((rows (bra n i)) = 1%Z) /\
((forall (j:Z), (valid_index (bra n i) 0%Z j) ->
((get (bra n i) 0%Z j) = (indic j i))) /\
((((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> forall (j:Z),
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((get_bra (bra n i) j) = (indic j i))) /\
((((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> forall (j:Z),
(valid_index (bra n i) 0%Z j) -> ~ (i = j) ->
((get_bra (bra n i) j) = tzero)) /\
((((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((get_bra (bra n i) i) = tone)) /\
((((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
is_a_bra_l (bra n i) n) /\
(((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
is_a_bra_basis_elt (bra n i))))))))))).
Axiom bra_is_a_bra_basis_elt :
forall (m:matrix t) (n:Z) (i:Z), ((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
(n >= 0%Z)%Z -> (m = (bra n i)) -> is_a_bra_basis_elt m.
Axiom bra_rows :
forall (n:Z) (i:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> ((rows (bra n i)) = 1%Z).
Axiom bra_columns :
forall (n:Z) (i:Z), (0%Z <= n)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((columns (bra n i)) = (power 2%Z n)).
Axiom bra_value :
forall (n:Z) (i:Z) (j:Z), (0%Z <= n)%Z ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((i = j) -> ((get (bra n i) 0%Z j) = tone)) /\
(~ (i = j) -> ((get (bra n i) 0%Z j) = tzero)).
Axiom real_values_ket_basis_elt :
forall (m:matrix t), (is_a_ket_basis_elt m) -> forall (i:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) -> real_ (get_ket m i).
Axiom real_values_bra_basis_elt :
forall (m:matrix t), (is_a_bra_basis_elt m) -> forall (i:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z (bra_length m)))%Z) -> real_ (get_bra m i).
Axiom get_bra_to_get_ket_basis :
forall (m:matrix t) (i:Z), (is_a_bra_basis_elt m) ->
((0%Z <= i)%Z /\ (i < (power 2%Z (bra_length m)))%Z) ->
((get_bra m i) = (get_ket (adjoint m) i)).
Axiom bra_to_ket_basis :
forall (m:matrix t), (is_a_bra_basis_elt m) -> forall (i:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z (bra_length m)))%Z) ->
((get_ket (bra_to_ket m) i) = (get_bra m i)).
Parameter bra_valid_index: (matrix t) -> Z -> Prop.
Axiom bra_valid_index_def :
forall (m:matrix t) (j:Z),
(bra_valid_index m j) <->
((is_a_bra m) /\ ((0%Z <= j)%Z /\ (j < (power 2%Z (bra_length m)))%Z)).
Axiom set_bra_valid_index :
forall (m:matrix t) (j:Z), (is_a_bra m) ->
((0%Z <= j)%Z /\ (j < (power 2%Z (bra_length m)))%Z) -> bra_valid_index m j.
Axiom get_bra_valid_index :
forall (m:matrix t) (j:Z), (bra_valid_index m j) ->
(is_a_bra m) /\ ((0%Z <= j)%Z /\ (j < (power 2%Z (bra_length m)))%Z).
Axiom bra_valid_index_to_valid_index :
forall (m:matrix t) (j:Z), (is_a_bra m) -> (bra_valid_index m j) ->
valid_index m 0%Z j.
Axiom valid_index_to_bra_valid_index :
forall (m:matrix t) (j:Z), (is_a_bra m) -> (valid_index m 0%Z j) ->
bra_valid_index m j.
Parameter bra_to_int: (matrix t) -> Z.
Axiom bra_to_int_def :
forall (m:matrix t), (is_a_bra m) -> (is_a_bra_basis_elt m) ->
((bra_to_int m) = (ket_to_int (bra_to_ket m))).
Axiom bra_to_int_spec :
forall (m:matrix t), (is_a_bra m) -> (is_a_bra_basis_elt m) ->
(m = (bra (bra_length m) (bra_to_int m))).
Axiom bra_to_int_to_ket_to_int :
forall (m:matrix t), (is_a_bra m) -> (is_a_bra_basis_elt m) ->
((bra_to_int m) = (ket_to_int (bra_to_ket m))).
Parameter ket_to_bra: (matrix t) -> matrix t.
Axiom ket_to_bra_def :
forall (m:matrix t), (is_a_ket m) -> ((ket_to_bra m) = (adjoint m)).
Axiom ket_to_bra_spec :
forall (m:matrix t), (is_a_ket m) ->
(is_a_bra_l (ket_to_bra m) (ket_length m)) /\
(((bra_length (ket_to_bra m)) = (ket_length m)) /\
(((rows (ket_to_bra m)) = 1%Z) /\
(((columns (ket_to_bra m)) = (rows m)) /\
forall (i:Z), ((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) ->
((get_bra (ket_to_bra m) i) = (conjugate (get_ket m i)))))).
Axiom ket_to_bra_value :
forall (m:matrix t) (i:Z) (j:Z), (is_a_ket m) ->
((get (ket_to_bra m) i j) = (conjugate (get m j i))).
Axiom ket_to_bra_to_adjoint :
forall (m:matrix t), (is_a_ket m) -> ((adjoint m) = (ket_to_bra m)).
Axiom get_ket_to_get_bra :
forall (m:matrix t) (i:Z), (is_a_ket m) ->
((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) ->
((get_ket m i) = (conjugate (get_bra (adjoint m) i))).
Axiom ket_length_to_bra_length :
forall (m:matrix t), (is_a_ket m) ->
((ket_length m) = (bra_length (adjoint m))).
Axiom get_ket_to_get_bra_basis :
forall (m:matrix t) (i:Z), (is_a_ket_basis_elt m) ->
((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) ->
((get_ket m i) = (get_bra (adjoint m) i)).
Axiom ket_to_int_to_bra_to_int :
forall (m:matrix t), (is_a_ket m) -> (is_a_ket_basis_elt m) ->
((ket_to_int m) = (bra_to_int (ket_to_bra m))).
Axiom ket_to_bra_basis :
forall (m:matrix t), (is_a_ket_basis_elt m) -> forall (i:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) ->
((get_bra (ket_to_bra m) i) = (get_ket m i)).
Axiom ket_to_bra_to_ket :
forall (m:matrix t), (is_a_ket m) -> ((bra_to_ket (ket_to_bra m)) = m).
Axiom bra_to_ket_to_bra :
forall (m:matrix t), (is_a_bra m) -> ((ket_to_bra (bra_to_ket m)) = m).
Axiom scalar_bra :
forall (x:matrix t) (a:t), (is_a_bra x) -> is_a_bra (infix_asdtdt a x).
Axiom scalar_bra_length :
forall (m:matrix t) (a:t), (is_a_bra m) ->
((bra_length (infix_asdtdt a m)) = (bra_length m)).
Axiom scalar_bra_valid_index :
forall (m:matrix t) (a:t) (i:Z), (bra_valid_index m i) -> (is_a_bra m) ->
bra_valid_index (infix_asdtdt a m) i.
Parameter bra_to_bv: (matrix t) -> bitvec.
Axiom bra_to_bv_def :
forall (x:matrix t), (is_a_bra_basis_elt x) ->
((bra_to_bv x) = (ket_to_bv (bra_to_ket x))).
Axiom bra_to_bv_spec :
forall (x:matrix t), (is_a_bra_basis_elt x) ->
((bv_to_int (bra_to_bv x)) = (bra_to_int x)) /\
((length (bra_to_bv x)) = (bra_length x)).
Parameter bv_to_bra: bitvec -> matrix t.
Axiom bv_to_bra_def :
forall (bv:bitvec), ((bv_to_bra bv) = (ket_to_bra (bv_to_ket bv))).
Axiom bv_to_bra_spec :
forall (bv:bitvec),
(is_a_bra_basis_elt (bv_to_bra bv)) /\
(((bra_to_int (bv_to_bra bv)) = (bv_to_int bv)) /\
(((bra_length (bv_to_bra bv)) = (length bv)) /\
(((columns (bv_to_bra bv)) = (power 2%Z (length bv))) /\
((rows (bv_to_bra bv)) = 1%Z)))).
Axiom scalar_bra_l :
forall (x:matrix t) (l:Z) (a:t), (is_a_bra_l x l) ->
is_a_bra_l (infix_asdtdt a x) l.
Parameter bra_sum:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> matrix t) -> matrix t.
Axiom bra_sum_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_bra (f e1)) ->
(exists l:Z,
(l >= 0%Z)%Z /\ forall (e1:a), (mem e1 s) -> ((bra_length (f e1)) = l)) ->
((bra_sum s f) = (mat_sum s f)).
Axiom bra_sum_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_bra (f e1)) ->
(exists l:Z,
(l >= 0%Z)%Z /\ forall (e1:a), (mem e1 s) -> ((bra_length (f e1)) = l)) ->
(is_a_bra (bra_sum s f)) /\
((forall (e1:a), (mem e1 s) ->
((bra_length (bra_sum s f)) = (bra_length (f e1)))) /\
forall (i:Z), (bra_valid_index (bra_sum s f) i) ->
((get_bra (bra_sum s f) i) = (sum s (fun (e1:a) => (get_bra (f e1) i))))).
Parameter bra_sum_l:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> matrix t) -> Z ->
matrix t.
Axiom bra_sum_l_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), (l >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_bra_l (f e1) l) ->
((bra_sum_l s f l) = (mat_sum s f)).
Axiom bra_sum_l_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), (l >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_bra_l (f e1) l) ->
((bra_sum_l s f l) = (bra_sum s f)) /\
((forall (i:Z), (bra_valid_index (bra_sum_l s f l) i) ->
((get_bra (bra_sum_l s f l) i) =
(sum s (fun (e1:a) => (get_bra (f e1) i))))) /\
((is_a_bra_l (bra_sum_l s f l) l) /\ ((bra_length (bra_sum_l s f l)) = l))).
Axiom bra_sum_null_but_maybe_one_elt :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a) (e1:a), ((cardinal s) > 1%Z)%Z ->
(forall (e2:a), (mem e2 s) -> is_a_bra (f e2)) -> (constant_size s f) ->
(mem e1 s) ->
(forall (e':a), (mem e' s) -> ~ (e1 = e') -> null_mat (f e')) ->
((bra_sum s f) = (f e1)).
Axiom bra_sum_null :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), (l >= 0%Z)%Z ->
((cardinal s) > 1%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_bra_l (f e1) l) ->
(forall (e1:a), (mem e1 s) -> null_mat (f e1)) -> forall (j:Z),
((0%Z <= j)%Z /\ (j < (power 2%Z l))%Z) ->
((get_bra (bra_sum_l s f l) j) = tzero).
Axiom bra_sum_l_null_but_maybe_one_elt :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a) (e1:a) (l:Z), (l >= 0%Z)%Z ->
((cardinal s) > 1%Z)%Z ->
(forall (e2:a), (mem e2 s) -> is_a_bra_l (f e2) l) -> (mem e1 s) ->
(forall (e':a), (mem e' s) -> ~ (e1 = e') -> null_mat (f e')) ->
((bra_sum_l s f l) = (f e1)).
Axiom bra_sum_bra_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), (l >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_bra_l (f e1) l) ->
is_a_bra_l (bra_sum_l s f l) l.
Parameter add_bra: (matrix t) -> (matrix t) -> matrix t.
Axiom add_bra_def :
forall (m:matrix t) (n:matrix t), (is_a_bra m) -> (is_a_bra n) ->
((bra_length m) = (bra_length n)) -> ((add_bra m n) = (add_mat m n)).
Axiom add_bra_spec :
forall (m:matrix t) (n:matrix t), (is_a_bra m) -> (is_a_bra n) ->
((bra_length m) = (bra_length n)) ->
(is_a_bra (add_bra m n)) /\
(((bra_length (add_bra m n)) = (bra_length m)) /\
forall (i:Z), (bra_valid_index (add_bra m n) i) ->
((get_bra (add_bra m n) i) = (infix_pldt (get_bra m i) (get_bra n i)))).
Parameter add_bra_l: (matrix t) -> (matrix t) -> Z -> matrix t.
Axiom add_bra_l_def :
forall (m:matrix t) (n:matrix t) (l:Z), (is_a_bra_l m l) ->
(is_a_bra_l n l) -> ((add_bra_l m n l) = (add_mat m n)).
Axiom add_bra_l_spec :
forall (m:matrix t) (n:matrix t) (l:Z), (is_a_bra_l m l) ->
(is_a_bra_l n l) ->
(is_a_bra_l (add_bra_l m n l) l) /\
(((bra_length (add_bra_l m n l)) = l) /\
((forall (i:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z (bra_length (add_bra_l m n l))))%Z) ->
((get_bra (add_bra_l m n l) i) =
(infix_pldt (get_bra m i) (get_bra n i)))) /\
((add_bra_l m n l) = (add_bra m n)))).
Axiom bra_sum_comp_l :
forall {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> matrix t) (g:b -> matrix t) (l:Z), (l >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:b), (mem e1 s) -> is_a_bra_l (f e1) l) ->
(forall (e1:b), (mem e1 s) -> is_a_bra_l (g e1) l) ->
((bra_sum_l s (fun (k:b) => (add_bra_l (f k) (g k) l)) l) =
(add_bra_l (bra_sum_l s f l) (bra_sum_l s g l) l)).
Axiom bra_sum_comp_l_rev :
forall {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> matrix t) (g:b -> matrix t) (l:Z), (l >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:b), (mem e1 s) -> is_a_bra_l (f e1) l) ->
(forall (e1:b), (mem e1 s) -> is_a_bra_l (g e1) l) ->
((add_bra_l (bra_sum_l s f l) (bra_sum_l s g l) l) =
(bra_sum_l s (fun (k:b) => (add_bra_l (f k) (g k) l)) l)).
Axiom bra_sum_scalar_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (a1:t) (l:Z), (l >= 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_bra_l (f e1) l) ->
((cardinal s) > 0%Z)%Z ->
((bra_sum_l s (fun (k:a) => (infix_asdtdt a1 (f k))) l) =
(infix_asdtdt a1 (bra_sum_l s f l))).
Axiom scal_bra_sum_scalar_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (b:t) (l:Z) (l':Z), (l >= 0%Z)%Z ->
(forall (e1:a), (mem e1 s) ->
exists a1:t,
exists k:matrix t, ((f e1) = (infix_asdtdt a1 k)) /\ (is_a_bra_l k l)) ->
((cardinal s) > 0%Z)%Z -> (l = l') ->
is_a_bra_l (infix_asdtdt b (bra_sum_l s f l)) l'.
Axiom bra_sum_scalar_rev_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (a1:t) (l:Z), (l >= 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_bra_l (f e1) l) ->
((cardinal s) > 0%Z)%Z ->
((infix_asdtdt a1 (bra_sum_l s f l)) =
(bra_sum_l s (fun (k:a) => (infix_asdtdt a1 (f k))) l)).
Axiom bra_sum_eq :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (f:a -> matrix t) (g:a -> matrix t) (l:Z),
(l >= 0%Z)%Z -> ((cardinal s) > 0%Z)%Z -> (s = s') ->
(forall (e1:a), (mem e1 s) -> is_a_bra_l (f e1) l) ->
(forall (a1:a), (mem a1 s) -> ((f a1) = (g a1))) ->
((bra_sum_l s f l) = (bra_sum_l s' g l)).
Axiom bra_sum_eq_gen :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (f:a -> matrix t) (g:a -> matrix t) (l1:Z)
(l2:Z),
(l1 >= 0%Z)%Z -> ((cardinal s) > 0%Z)%Z -> (s = s') -> (l1 = l2) ->
(forall (e1:a), (mem e1 s) -> is_a_bra_l (f e1) l1) ->
(forall (a1:a), (mem a1 s) -> ((f a1) = (g a1))) ->
((bra_sum_l s f l1) = (bra_sum_l s' g l2)).
Axiom bra_sum_l_cardone :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), ((cardinal s) = 1%Z) ->
(is_a_bra_l (f (choose s)) l) -> ((bra_sum_l s f l) = (f (choose s))).
Axiom bra_sum_l_plus_one :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (e1:a) (f:a -> matrix t) (l:Z), ((cardinal s) > 1%Z)%Z ->
~ (mem e1 s) -> (forall (e2:a), (mem e2 s) -> is_a_bra_l (f e2) l) ->
(is_a_bra_l (f e1) l) ->
((bra_sum_l (add e1 s) f l) = (add_bra_l (bra_sum_l s f l) (f e1) l)).
Axiom bra_sum_l_valid_index :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z) (i:Z), (l >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_bra_l (f e1) l) ->
(forall (e1:a), (mem e1 s) -> bra_valid_index (f e1) i) ->
bra_valid_index (bra_sum_l s f l) i.
Parameter is_a_ketbra_n: (matrix t) -> Z -> Prop.
Axiom is_a_ketbra_n_def :
forall (m:matrix t) (n:Z),
(is_a_ketbra_n m n) <->
((n >= 0%Z)%Z /\
(((columns m) = (power 2%Z n)) /\ ((rows m) = (power 2%Z n)))).
Parameter is_a_ketbra: (matrix t) -> Prop.
Axiom is_a_ketbra_def :
forall (m:matrix t),
(is_a_ketbra m) <-> exists s:Z, (s >= 0%Z)%Z /\ (is_a_ketbra_n m s).
Parameter ketbra_size: (matrix t) -> Z.
Axiom ketbra_size_def :
forall (m:matrix t), (is_a_ketbra m) ->
((ketbra_size m) = (ket_length (make (rows m) 1%Z tzero))).
Axiom ketbra_size_spec :
forall (m:matrix t), (is_a_ketbra m) ->
((ketbra_size m) = ((binary_length (rows m)) - 1%Z)%Z) /\
(((ketbra_size m) >= 0%Z)%Z /\
(((columns m) = (power 2%Z (ketbra_size m))) /\
(((rows m) = (power 2%Z (ketbra_size m))) /\
(is_a_ketbra_n m (ketbra_size m))))).
Axiom get_ketbra_size :
forall (m:matrix t) (n:Z), (is_a_ketbra m) -> (n >= 0%Z)%Z ->
((ketbra_size m) = n) ->
((columns m) = (power 2%Z n)) /\ ((rows m) = (power 2%Z n)).
Axiom ketbra_n_to_ket_size :
forall (m:matrix t) (n:Z), (is_a_ketbra_n m n) -> (n >= 0%Z)%Z ->
((ketbra_size m) = n).
Axiom set_ketbra_size :
forall (m:matrix t) (n:Z), (n >= 0%Z)%Z -> ((columns m) = (power 2%Z n)) ->
((rows m) = (power 2%Z n)) -> ((ketbra_size m) = n).
Axiom set_columns_ketbra :
forall (m:matrix t) (n:Z), (is_a_ketbra m) -> ((ketbra_size m) = n) ->
((columns m) = (power 2%Z n)).
Axiom set_rows_ketbra :
forall (m:matrix t) (n:Z), (is_a_ketbra m) -> ((ketbra_size m) = n) ->
((rows m) = (power 2%Z n)).
Axiom set_columns_ketbra_n :
forall (m:matrix t) (n:Z), (is_a_ketbra_n m n) ->
((columns m) = (power 2%Z n)).
Axiom set_rows_ketbra_n :
forall (m:matrix t) (n:Z), (is_a_ketbra_n m n) ->
((rows m) = (power 2%Z n)).
Axiom get_ketbra_n :
forall (m:matrix t) (n:Z), (is_a_ketbra_n m n) ->
(is_a_ketbra m) /\
((n >= 0%Z)%Z /\
(((columns m) = (power 2%Z n)) /\ ((rows m) = (power 2%Z n)))).
Axiom set_ketbra_n :
forall (m:matrix t) (n:Z), (n >= 0%Z)%Z -> ((columns m) = (power 2%Z n)) ->
((rows m) = (power 2%Z n)) -> is_a_ketbra_n m n.
Axiom get_ketbra :
forall (m:matrix t), (is_a_ketbra m) ->
(is_a_ketbra_n m (ketbra_size m)) /\
((exists n:Z,
(n >= 0%Z)%Z /\
(((columns m) = (power 2%Z n)) /\ ((rows m) = (power 2%Z n)))) /\
(is_a_ketbra_n m (ketbra_size m))).
Axiom set_ketbra :
forall (m:matrix t),
(((ketbra_size m) >= 0%Z)%Z /\
(((columns m) = (power 2%Z (ketbra_size m))) /\
((rows m) = (power 2%Z (ketbra_size m))))) ->
is_a_ketbra m.
Axiom ketbra_n_is_a_ketbra :
forall (m:matrix t) (n:Z), (is_a_ketbra_n m n) -> is_a_ketbra m.
Parameter is_a_ketbra_basis_elt_n: (matrix t) -> Z -> Prop.
Axiom is_a_ketbra_basis_elt_n_def :
forall (m:matrix t) (n:Z),
((is_a_ketbra_basis_elt_n m n) ->
(is_a_ketbra_n m n) /\
exists i:Z, exists j:Z,
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) /\
(((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) /\
forall (k:Z) (l:Z),
(((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) /\
((0%Z <= l)%Z /\ (l < (power 2%Z n))%Z)) ->
(((i = k) /\ (j = l)) -> ((get m k l) = tone)) /\
(~ ((i = k) /\ (j = l)) -> ((get m k l) = tzero)))) /\
(((is_a_ketbra_n m n) /\
exists i:Z, exists j:Z,
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) /\
(((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) /\
forall (k:Z) (l:Z),
(((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) /\
((0%Z <= l)%Z /\ (l < (power 2%Z n))%Z)) ->
(((i = k) /\ (j = l)) /\ ((get m k l) = tone)) \/
(~ ((i = k) /\ (j = l)) /\ ((get m k l) = tzero)))) ->
is_a_ketbra_basis_elt_n m n).
Parameter is_a_ketbra_basis_elt: (matrix t) -> Prop.
Axiom is_a_ketbra_basis_elt_def :
forall (m:matrix t),
(is_a_ketbra_basis_elt m) <-> exists n:Z, is_a_ketbra_basis_elt_n m n.
Axiom get_ketbra_basis_elt_n :
forall (m:matrix t) (n:Z), (is_a_ketbra_basis_elt_n m n) ->
(n >= 0%Z)%Z /\
((exists i:Z, exists j:Z,
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) /\
(((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) /\
forall (k:Z) (l:Z),
(((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) /\
((0%Z <= l)%Z /\ (l < (power 2%Z n))%Z)) ->
(((i = k) /\ (j = l)) -> ((get m k l) = tone)) /\
(~ ((i = k) /\ (j = l)) -> ((get m k l) = tzero)))) /\
(((rows m) = (power 2%Z n)) /\
(((columns m) = (power 2%Z n)) /\
((is_a_ketbra_n m n) /\
((is_a_ketbra m) /\
((is_a_ketbra_basis_elt m) /\ ((ketbra_size m) = n))))))).
Axiom set_ketbra_basis_elt_n :
forall (m:matrix t) (n:Z), (n >= 0%Z)%Z ->
(((rows m) = (power 2%Z n)) /\
(((columns m) = (power 2%Z n)) /\
exists i:Z, exists j:Z,
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) /\
(((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) /\
forall (k:Z) (l:Z),
(((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) /\
((0%Z <= l)%Z /\ (l < (power 2%Z n))%Z)) ->
(((i = k) /\ (j = l)) /\ ((get m k l) = tone)) \/
(~ ((i = k) /\ (j = l)) /\ ((get m k l) = tzero))))) ->
is_a_ketbra_basis_elt_n m n.
Axiom get_ketbra_basis_elt :
forall (m:matrix t), (is_a_ketbra_basis_elt m) ->
(is_a_ketbra_n m (ketbra_size m)) /\
((exists n:Z,
((columns m) = (power 2%Z n)) /\
(((rows m) = (power 2%Z n)) /\
exists i:Z, exists j:Z,
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) /\
(((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) /\
forall (k:Z) (l:Z),
(((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) /\
((0%Z <= l)%Z /\ (l < (power 2%Z n))%Z)) ->
(((i = k) /\ (j = l)) -> ((get m k l) = tone)) /\
(~ ((i = k) /\ (j = l)) -> ((get m k l) = tzero))))) /\
(is_a_ketbra m)).
Axiom set_ketbra_basis_elt :
forall (m:matrix t),
(((ketbra_size m) >= 0%Z)%Z /\
(((columns m) = (power 2%Z (ketbra_size m))) /\
(((rows m) = (power 2%Z (ketbra_size m))) /\
exists i:Z, exists j:Z,
((0%Z <= i)%Z /\ (i < (power 2%Z (ketbra_size m)))%Z) /\
(((0%Z <= j)%Z /\ (j < (power 2%Z (ketbra_size m)))%Z) /\
forall (k:Z) (l:Z),
(((0%Z <= k)%Z /\ (k < (power 2%Z (ketbra_size m)))%Z) /\
((0%Z <= l)%Z /\ (l < (power 2%Z (ketbra_size m)))%Z)) ->
(((i = k) /\ (j = l)) /\ ((get m k l) = tone)) \/
(~ ((i = k) /\ (j = l)) /\ ((get m k l) = tzero)))))) ->
is_a_ketbra_basis_elt m.
Axiom ketbra_basis_elt_n_is_a_ketbra_basis_element :
forall (m:matrix t) (n:Z), (is_a_ketbra_basis_elt_n m n) ->
(is_a_ketbra_basis_elt m) /\ (n = (ketbra_size m)).
Axiom ketbra_basis_elt_is_a_ketbra_basis_element_n :
forall (m:matrix t), (is_a_ketbra_basis_elt m) ->
is_a_ketbra_basis_elt_n m (ketbra_size m).
Axiom ketbra_basis_elt_n_is_a_ketbra_n :
forall (m:matrix t) (n:Z), (is_a_ketbra_basis_elt_n m n) ->
is_a_ketbra_n m n.
Axiom ketbra_basis_elt_n_is_a_ketbra :
forall (m:matrix t) (n:Z), (is_a_ketbra_basis_elt_n m n) -> is_a_ketbra m.
Axiom ketbra_basis_elt_is_a_ketbra :
forall (m:matrix t), (is_a_ketbra_basis_elt m) -> is_a_ketbra m.
Axiom rows_ketbra_n :
forall (m:matrix t) (n:Z), (is_a_ketbra_n m n) ->
((rows m) = (power 2%Z n)).
Axiom columns_ketbra_n :
forall (m:matrix t) (n:Z), (is_a_ketbra_n m n) ->
((columns m) = (power 2%Z n)).
Axiom ketbra_basis_element_has_decomp :
forall (m:matrix t) (n:Z), (is_a_ketbra_basis_elt_n m n) ->
(is_a_ketbra_n m n) ->
(exists i:Z, exists j:Z,
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) /\
(((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) /\
(m = (kronecker (ket n i) (bra n j))))) /\
((exists k:matrix t, exists b:matrix t,
(is_a_bra_l b n) /\
((is_a_bra_basis_elt b) /\
((is_a_ket_l k n) /\ ((is_a_ket_basis_elt k) /\ (m = (kronecker k b)))))) /\
exists o:(Z* Z)%type,
(mem o
(cartesian_product (to_fset 0%Z (power 2%Z (ketbra_size m)))
(to_fset 0%Z (power 2%Z (ketbra_size m))))) /\
(equal m
(kronecker (ket (ketbra_size m) (fir o)) (bra (ketbra_size m) (sec o))))).
Axiom pre_injective_bv_to_int :
forall (bv1:bitvec) (bv2:bitvec), ((length bv1) = (length bv2)) ->
~ (bv1 = bv2) -> ~ ((bv_to_int bv1) = (bv_to_int bv2)).
Axiom injective_bv_to_int :
forall (n:Z), (0%Z <= n)%Z ->
p_injective (fun (y0:bitvec) => (bv_to_int y0)) (n_bvs n).
Axiom bijective_to_int :
forall (n:Z), (0%Z < n)%Z ->
p_bijective (fun (y0:bitvec) => (bv_to_int y0)) (n_bvs n)
(to_fset 0%Z (power 2%Z n)).
Axiom n_bvs_card :
forall (n:Z), (0%Z <= n)%Z -> ((cardinal (n_bvs n)) = (power 2%Z n)).
Axiom concat_first_term_zero :
forall (e1:bitvec) (i:Z), (0%Z <= i)%Z ->
(mem e1 (map (fun (bv:bitvec) => (concat_l bv 0%Z)) (n_bvs i))) ->
(((getbv e1) 0%Z) = 0%Z).
Axiom concat_first_term_one :
forall (e1:bitvec) (i:Z), (0%Z <= i)%Z ->
(mem e1 (map (fun (bv:bitvec) => (concat_l bv 1%Z)) (n_bvs i))) ->
(((getbv e1) 0%Z) = 1%Z).
Axiom geometric_series_bv :
forall (a:t) (q:t) (n:Z), (n >= 1%Z)%Z ->
((sum (n_bvs n)
(fun (i:bitvec) => (infix_asdt a (cpower q (bv_to_int i)))))
=
(infix_sldt (infix_asdt a (infix_mndt tone (cpower q (power_ 2%Z n))))
(infix_mndt tone q))).
Axiom geometric_series_bv_init_one :
forall (q:t) (n:Z), (n >= 1%Z)%Z ->
((sum (n_bvs n) (fun (i:bitvec) => (cpower q (bv_to_int i)))) =
(infix_sldt (infix_mndt tone (cpower q (power_ 2%Z n)))
(infix_mndt tone q))).
Axiom bv_sum_to_int_sum :
forall (n:Z) (f:Z -> t) (g:bitvec -> t),
(forall (x:bitvec), ((length x) = n) -> ((g x) = (f (bv_to_int x)))) ->
((sum (n_bvs n) g) = (sum (to_fset 0%Z (power 2%Z n)) f)).
Axiom sum_concat :
forall (f:bitvec -> matrix t) (i:Z) (r:Z) (c:Z), (i > 0%Z)%Z ->
(forall (bv:bitvec), ((rows (f bv)) = r)) ->
(forall (bv:bitvec), ((columns (f bv)) = c)) ->
((mat_sum (n_bvs i)
(fun (bv:bitvec) =>
(add_mat (f (concat_l bv 0%Z)) (f (concat_l bv 1%Z)))))
= (mat_sum (n_bvs (i + 1%Z)%Z) f)).
Parameter ketbra_pre: Z -> Z -> Z -> matrix t.
Axiom ketbra_pre_spec :
forall (n:Z) (i:Z) (j:Z), (n > 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((ketbra_size (ketbra_pre n i j)) = n) /\
((forall (k:Z) (l:Z), ((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) ->
((0%Z <= l)%Z /\ (l < (power 2%Z n))%Z) ->
(((i = k) /\ (j = l)) -> ((get (ketbra_pre n i j) k l) = tone)) /\
(~ ((i = k) /\ (j = l)) -> ((get (ketbra_pre n i j) k l) = tzero))) /\
(((ketbra_pre n i j) = (ind_basis_mat i j (power 2%Z n) (power 2%Z n))) /\
((forall (y:matrix t), (is_a_ket_l y n) ->
((mat_mult (ketbra_pre n i j) y) =
(infix_asdtdt (get_ket y j) (ket n i)))) /\
((ketbra_pre n i j) = (kronecker (ket n i) (bra n j)))))).
Parameter ketbra: Z -> Z -> Z -> matrix t.
Axiom ketbra_def :
forall (n:Z) (i:Z) (j:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((ketbra n i j) = (kronecker (ket n i) (bra n j))).
Axiom ketbra_spec :
forall (n:Z) (i:Z) (j:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((ketbra_size (ketbra n i j)) = n) /\
(((rows (ketbra n i j)) = (power 2%Z n)) /\
(((columns (ketbra n i j)) = (power 2%Z n)) /\
((forall (k:Z) (l:Z), ((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) ->
((0%Z <= l)%Z /\ (l < (power 2%Z n))%Z) ->
(((i = k) /\ (j = l)) -> ((get (ketbra n i j) k l) = tone)) /\
(~ ((i = k) /\ (j = l)) -> ((get (ketbra n i j) k l) = tzero))) /\
(((ketbra n i j) = (ind_basis_mat i j (power 2%Z n) (power 2%Z n))) /\
forall (y:matrix t), (is_a_ket_l y n) ->
((mat_mult (ketbra n i j) y) = (infix_asdtdt (get_ket y j) (ket n i))))))).
Axiom ketbra_rows :
forall (n:Z) (i:Z) (j:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((rows (ketbra n i j)) = (power 2%Z n)).
Axiom ketbra_columns :
forall (n:Z) (i:Z) (j:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((columns (ketbra n i j)) = (power 2%Z n)).
Axiom ketbra_is_a_ketbra_n :
forall (n:Z) (i:Z) (j:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) -> is_a_ketbra_n (ketbra n i j) n.
Axiom ketbra_value :
forall (n:Z) (i:Z) (j:Z) (k:Z) (l:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) ->
((0%Z <= l)%Z /\ (l < (power 2%Z n))%Z) ->
(((i = k) /\ (j = l)) -> ((get (ketbra n i j) k l) = tone)) /\
(~ ((i = k) /\ (j = l)) -> ((get (ketbra n i j) k l) = tzero)).
Axiom ketbra_values :
forall (n:Z) (i:Z) (j:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) -> forall (k:Z) (l:Z),
((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) ->
((0%Z <= l)%Z /\ (l < (power 2%Z n))%Z) ->
(((i = k) /\ (j = l)) -> ((get (ketbra n i j) k l) = tone)) /\
(~ ((i = k) /\ (j = l)) -> ((get (ketbra n i j) k l) = tzero)).
Axiom ketbra_adjoint :
forall (n:Z) (i:Z) (j:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((adjoint (ketbra n i j)) = (ketbra n j i)).
Parameter ketbra_to_int_couple: (matrix t) -> (Z* Z)%type.
Parameter result22: (matrix t) -> (Z* Z)%type -> bool.
Axiom result_def22 :
forall (m:matrix t) (x:(Z* Z)%type),
(((result22 m) x) = true) <->
(equal m
(kronecker (ket (ketbra_size m) (fir x)) (bra (ketbra_size m) (sec x)))).
Axiom ketbra_to_int_couple_def :
forall (m:matrix t), (is_a_ketbra_basis_elt m) ->
((ketbra_to_int_couple m) =
(choose_filter
(cartesian_product (to_fset 0%Z (power 2%Z (ketbra_size m)))
(to_fset 0%Z (power 2%Z (ketbra_size m))))
(result22 m))).
Axiom ketbra_to_int_couple_spec :
forall (m:matrix t), (is_a_ketbra_basis_elt m) ->
(m =
(kronecker (ket (ketbra_size m) (fir (ketbra_to_int_couple m)))
(bra (ketbra_size m) (sec (ketbra_to_int_couple m))))) /\
(((0%Z <= (fir (ketbra_to_int_couple m)))%Z /\
((fir (ketbra_to_int_couple m)) < (power 2%Z (ketbra_size m)))%Z) /\
((0%Z <= (sec (ketbra_to_int_couple m)))%Z /\
((sec (ketbra_to_int_couple m)) < (power 2%Z (ketbra_size m)))%Z)).
Parameter ketbra_to_int_rows: (matrix t) -> Z.
Axiom ketbra_to_int_rows_def :
forall (m:matrix t), (is_a_ketbra_basis_elt m) ->
((ketbra_to_int_rows m) = (fir (ketbra_to_int_couple m))).
Axiom ketbra_to_int_rows_spec :
forall (m:matrix t), (is_a_ketbra_basis_elt m) ->
((0%Z <= (ketbra_to_int_rows m))%Z /\
((ketbra_to_int_rows m) < (power 2%Z (ketbra_size m)))%Z) /\
exists j:Z,
((0%Z <= j)%Z /\ (j < (power 2%Z (ketbra_size m)))%Z) /\
(m =
(kronecker (ket (ketbra_size m) (ketbra_to_int_rows m))
(bra (ketbra_size m) j))).
Parameter ketbra_to_int_col: (matrix t) -> Z.
Axiom ketbra_to_int_col_def :
forall (m:matrix t), (is_a_ketbra_basis_elt m) ->
((ketbra_to_int_col m) = (sec (ketbra_to_int_couple m))).
Axiom ketbra_to_int_col_spec :
forall (m:matrix t), (is_a_ketbra_basis_elt m) ->
((0%Z <= (ketbra_to_int_col m))%Z /\
((ketbra_to_int_col m) < (power 2%Z (ketbra_size m)))%Z) /\
(m =
(kronecker (ket (ketbra_size m) (ketbra_to_int_rows m))
(bra (ketbra_size m) (ketbra_to_int_col m)))).
Axiom correct_ketbra_basis_decomp :
forall (m:matrix t) (n:Z), (0%Z <= n)%Z -> (is_a_ketbra_basis_elt_n m n) ->
(m = (ketbra n (ketbra_to_int_rows m) (ketbra_to_int_col m))).
Axiom ketbra_diff_r :
forall (n:Z) (i:Z) (j:Z) (k:Z) (l:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) ->
((0%Z <= l)%Z /\ (l < (power 2%Z n))%Z) -> (n >= 0%Z)%Z -> ~ (i = k) ->
((get (ketbra n i j) k l) = tzero).
Axiom ketbra_diff_c :
forall (n:Z) (i:Z) (j:Z) (k:Z) (l:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) ->
((0%Z <= l)%Z /\ (l < (power 2%Z n))%Z) -> (n >= 0%Z)%Z -> ~ (j = l) ->
((get (ketbra n i j) k l) = tzero).
Axiom ketbra_eq :
forall (n:Z) (i:Z) (j:Z) (k:Z) (l:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) ->
((0%Z <= l)%Z /\ (l < (power 2%Z n))%Z) -> (n >= 0%Z)%Z -> (i = k) ->
(j = l) -> ((get (ketbra n i j) k l) = tone).
Axiom ketbra_to_ind_basis :
forall (n:Z) (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) -> (n >= 0%Z)%Z ->
((ketbra n i j) = (ind_basis_mat i j (power 2%Z n) (power 2%Z n))).
Parameter projection: (matrix t) -> matrix t.
Axiom projection_def :
forall (m:matrix t), (is_a_ket m) ->
((projection m) = (kronecker m (adjoint m))).
Axiom projection_spec :
forall (m:matrix t), (is_a_ket m) ->
(is_a_ketbra_n (projection m) (ket_length m)) /\
((forall (i:Z) (j:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z (ket_length m)))%Z) ->
((get (projection m) i j) =
(infix_asdt (get_ket m i) (conjugate (get_ket m j))))) /\
(((rows (projection m)) = (power 2%Z (ket_length m))) /\
((columns (projection m)) = (power 2%Z (ket_length m))))).
Axiom projection_decomp :
forall (m:matrix t), (is_a_ket m) ->
((projection m) = (kronecker m (adjoint m))).
Axiom projection_value :
forall (m:matrix t) (i:Z) (j:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z (ket_length m)))%Z) -> (is_a_ket m) ->
((get (projection m) i j) =
(infix_asdt (get_ket m i) (conjugate (get_ket m j)))).
Axiom auto_adjoint_proj :
forall (m:matrix t), (is_a_ket m) ->
((adjoint (projection m)) = (projection m)).
Parameter projection_n: (matrix t) -> Z -> matrix t.
Axiom projection_n_def :
forall (m:matrix t) (l:Z), (0%Z <= l)%Z -> (is_a_ket_l m l) ->
((projection_n m l) = (projection m)).
Axiom projection_n_spec :
forall (m:matrix t) (l:Z), (0%Z <= l)%Z -> (is_a_ket_l m l) ->
(is_a_ketbra_n (projection_n m l) l) /\
forall (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < (power 2%Z (ket_length m)))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z (ket_length m)))%Z) ->
((get (projection_n m l) i j) =
(infix_asdt (get_ket m i) (conjugate (get_ket m j)))).
Parameter projection_basis: (matrix t) -> matrix t.
Axiom projection_basis_def :
forall (m:matrix t), (is_a_ket_basis_elt m) ->
((projection_basis m) = (projection m)).
Axiom projection_basis_spec :
forall (m:matrix t), (is_a_ket_basis_elt m) ->
((projection_basis m) = (kronecker m (adjoint m))) /\
(((projection_basis m) =
(ketbra (ket_length m) (ket_to_int m) (ket_to_int m))) /\
((is_a_ketbra_n (projection_basis m) (ket_length m)) /\
((is_a_ketbra_basis_elt (projection_basis m)) /\
((forall (i:Z) (j:Z), (valid_index (projection_basis m) i j) ->
(((i = (ket_to_int m)) /\ (j = (ket_to_int m))) ->
((get (projection_basis m) i j) = tone)) /\
(~ ((i = (ket_to_int m)) /\ (j = (ket_to_int m))) ->
((get (projection_basis m) i j) = tzero))) /\
forall (y:matrix t), (is_a_ket_l y (ket_length m)) ->
((mat_mult (projection_basis m) y) =
(infix_asdtdt (get_ket y (ket_to_int m))
(ket (ket_length m) (ket_to_int m)))))))).
Parameter is_diagonal: (matrix t) -> Prop.
Parameter fc17: (Z -> t) -> Z -> Z -> t.
Axiom fc_def17 :
forall (f:Z -> t) (i:Z) (j:Z),
((i = j) -> ((((fc17 f) i) j) = (f i))) /\
(~ (i = j) -> ((((fc17 f) i) j) = tzero)).
Axiom is_diagonal_def :
forall (m:matrix t),
(is_diagonal m) <->
exists f:Z -> t, (m = (make_f (rows m) (rows m) (fc17 f))).
Parameter diag_mat1: (Z -> t) -> Z -> matrix t.
Parameter result23: (Z -> t) -> Z -> Z -> t.
Axiom result_def23 :
forall (f:Z -> t) (i:Z) (j:Z),
((i = j) -> ((((result23 f) i) j) = (f i))) /\
(~ (i = j) -> ((((result23 f) i) j) = tzero)).
Axiom diag_mat_def1 :
forall (f:Z -> t) (s:Z), (0%Z < s)%Z ->
((diag_mat1 f s) = (make_f s s (result23 f))).
Axiom diag_mat_spec1 :
forall (f:Z -> t) (s:Z), (0%Z < s)%Z ->
(is_diagonal (diag_mat1 f s)) /\
(((rows (diag_mat1 f s)) = s) /\ ((columns (diag_mat1 f s)) = s)).
Parameter diagonal: (matrix t) -> Z -> t.
Axiom diagonal_def :
forall (m:matrix t) (i:Z), ((0%Z <= i)%Z /\ (i < (rows m))%Z) ->
(is_diagonal m) -> ((diagonal m i) = (get m i i)).
Axiom diag_mat_add :
forall (f:Z -> t) (g:Z -> t) (h:Z -> t) (s:Z),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < s)%Z) ->
((infix_pldt (f i) (g i)) = (h i))) ->
((add_mat (diag_mat1 f s) (diag_mat1 g s)) = (diag_mat1 h s)).
Axiom diag_mat_subst :
forall (f:Z -> t) (g:Z -> t) (h:Z -> t) (s:Z),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < s)%Z) ->
((infix_mndt (f i) (g i)) = (h i))) ->
((diag_mat1 h s) = (mat_substr (diag_mat1 f s) (diag_mat1 g s))).
Axiom diag_mat_scal :
forall (f:Z -> t) (g:Z -> t) (s:Z) (a:t),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < s)%Z) ->
((g i) = (infix_asdt a (f i)))) ->
((diag_mat1 g s) = (infix_asdtdt a (diag_mat1 f s))).
Axiom diag_mat_eq1 :
forall (f:Z -> t) (g:Z -> t) (s:Z) (s':Z),
(forall (i:Z), ((0%Z <= i)%Z /\ (i < s)%Z) -> ((f i) = (g i))) ->
(s = s') -> ((diag_mat1 f s) = (diag_mat1 g s')).
Parameter id_mat: Z -> matrix t.
Axiom id_mat_def :
forall (n:Z), (n >= 1%Z)%Z ->
((id_mat n) = (diag_mat1 (fun (i:Z) => tone) n)).
Axiom id_mat_spec :
forall (n:Z), (n >= 1%Z)%Z ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) ->
((diagonal (id_mat n) i) = tone)) /\
(((rows (id_mat n)) = n) /\ ((columns (id_mat n)) = n)).
Axiom set_id_mat :
forall (n:Z) (f:Z -> t), (n >= 0%Z)%Z ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) -> ((f i) = tone)) ->
((diag_mat1 f n) = (id_mat n)).
Axiom id_mat_prod_r :
forall (n:Z) (m:matrix t), (n >= 1%Z)%Z -> ((rows m) = n) ->
((mat_mult (id_mat n) m) = m).
Axiom id_mat_prod_l :
forall (n:Z) (m:matrix t), (n >= 1%Z)%Z -> ((columns m) = n) ->
((mat_mult m (id_mat n)) = m).
Parameter projection_basis_l: (matrix t) -> Z -> Z -> matrix t.
Axiom projection_basis_l_def :
forall (m:matrix t) (i:Z) (l:Z), (l >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z l))%Z) -> (m = (ket l i)) ->
(is_a_ket_l m l) -> ((projection_basis_l m i l) = (projection m)).
Parameter fc18: Z -> Z -> t.
Axiom fc_def18 :
forall (i:Z) (j:Z),
((j = i) -> (((fc18 i) j) = tone)) /\ (~ (j = i) -> (((fc18 i) j) = tzero)).
Axiom projection_basis_l_spec :
forall (m:matrix t) (i:Z) (l:Z), (l >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z l))%Z) -> (m = (ket l i)) ->
(is_a_ket_l m l) ->
((projection_basis_l m i l) = (projection_basis m)) /\
(((projection_basis_l m i l) = (ketbra l (ket_to_int m) (ket_to_int m))) /\
(((projection_basis_l m i l) = (kronecker m (adjoint m))) /\
(((projection_basis_l m i l) = (kronecker (ket l i) (bra l i))) /\
(((projection_basis_l m i l) = (projection_n m l)) /\
(((projection_basis_l m i l) = (projection_basis m)) /\
((is_a_ketbra_basis_elt (projection_basis_l m i l)) /\
(((projection_basis_l m i l) = (ketbra l i i)) /\
((forall (i1:Z) (j:Z),
(valid_index (projection_basis_l m i l) i1 j) ->
(((i1 = (ket_to_int m)) /\ (j = (ket_to_int m))) ->
((get (projection_basis_l m i l) i1 j) = tone)) /\
(~ ((i1 = (ket_to_int m)) /\ (j = (ket_to_int m))) ->
((get (projection_basis_l m i l) i1 j) = tzero))) /\
((forall (y:matrix t), (is_a_ket_l y l) ->
((mat_mult (projection_basis_l m i l) y) =
(infix_asdtdt (get_ket y i) (ket l i)))) /\
((projection_basis_l m i l) = (diag_mat1 (fc18 i) (power 2%Z l)))))))))))).
Parameter ket_projection_basis: Z -> Z -> matrix t.
Axiom ket_projection_basis_def :
forall (l:Z) (i:Z), (l >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z l))%Z) ->
((ket_projection_basis l i) = (projection_basis_l (ket l i) i l)).
Parameter fc19: Z -> Z -> t.
Axiom fc_def19 :
forall (i:Z) (j:Z),
((j = i) -> (((fc19 i) j) = tone)) /\ (~ (j = i) -> (((fc19 i) j) = tzero)).
Axiom ket_projection_basis_spec :
forall (l:Z) (i:Z), (l >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z l))%Z) ->
((ket_projection_basis l i) = (projection_basis (ket l i))) /\
(((ket_projection_basis l i) = (kronecker (ket l i) (bra l i))) /\
((is_a_ketbra_basis_elt (ket_projection_basis l i)) /\
(((ket_projection_basis l i) = (ketbra l i i)) /\
(((ket_projection_basis l i) = (projection (ket l i))) /\
(((rows (ket_projection_basis l i)) = (power 2%Z l)) /\
(((columns (ket_projection_basis l i)) = (power 2%Z l)) /\
((forall (y:matrix t), (is_a_ket_l y l) ->
((mat_mult (ket_projection_basis l i) y) =
(infix_asdtdt (get_ket y i) (ket l i)))) /\
((ket_projection_basis l i) = (diag_mat1 (fc19 i) (power 2%Z l)))))))))).
Parameter projection_bv: bitvec -> matrix t.
Axiom projection_bv_def :
forall (x:bitvec),
((projection_bv x) = (ket_projection_basis (length x) (bv_to_int x))).
Parameter fc20: bitvec -> Z -> t.
Axiom fc_def20 :
forall (x:bitvec) (j:Z),
((j = (bv_to_int x)) -> (((fc20 x) j) = tone)) /\
(~ (j = (bv_to_int x)) -> (((fc20 x) j) = tzero)).
Axiom projection_bv_spec :
forall (x:bitvec),
((projection_bv x) = (projection_basis (bv_to_ket x))) /\
(((projection_bv x) = (kronecker (bv_to_ket x) (bv_to_bra x))) /\
((is_a_ketbra_basis_elt (projection_bv x)) /\
(((projection_bv x) = (ketbra (length x) (bv_to_int x) (bv_to_int x))) /\
(((projection_bv x) = (projection (bv_to_ket x))) /\
(((rows (projection_bv x)) = (power 2%Z (length x))) /\
(((columns (projection_bv x)) = (power 2%Z (length x))) /\
((forall (y:matrix t), (is_a_ket_l y (length x)) ->
((mat_mult (projection_bv x) y) =
(infix_asdtdt (get_ket y (bv_to_int x))
(ket (length x) (bv_to_int x))))) /\
((projection_bv x) = (diag_mat1 (fc20 x) (power 2%Z (length x))))))))))).
Parameter partial_projection_bv: bitvec -> Z -> matrix t.
Axiom partial_projection_bv_def :
forall (x:bitvec) (n:Z), (0%Z <= n)%Z ->
((partial_projection_bv x n) = (kronecker (projection_bv x) (identity n))).
Parameter fc21: bitvec -> Z -> Z -> t.
Axiom fc_def21 :
forall (x:bitvec) (n:Z) (j:Z),
((exists y:bitvec, ((length y) = n) /\ (j = (bv_to_int (concat x y)))) ->
(((fc21 x n) j) = tone)) /\
(~ (exists y:bitvec, ((length y) = n) /\ (j = (bv_to_int (concat x y)))) ->
(((fc21 x n) j) = tzero)).
Axiom partial_projection_bv_spec :
forall (x:bitvec) (n:Z), (0%Z <= n)%Z ->
((partial_projection_bv x n) =
(kronecker (kronecker (bv_to_ket x) (bv_to_bra x)) (identity n))) /\
((is_a_ketbra_basis_elt (partial_projection_bv x n)) /\
(((partial_projection_bv x n) =
(kronecker (ketbra (length x) (bv_to_int x) (bv_to_int x)) (identity n))) /\
(((partial_projection_bv x n) =
(kronecker (projection (bv_to_ket x)) (identity n))) /\
(((rows (partial_projection_bv x n)) = (power 2%Z ((length x) + n)%Z)) /\
(((columns (partial_projection_bv x n)) =
(power 2%Z ((length x) + n)%Z)) /\
((forall (y:matrix t), (is_a_ket_l y (length x)) ->
((mat_mult (partial_projection_bv x n) y) =
(ket_sum_l (n_bvs n)
(fun (z:bitvec) =>
(infix_asdtdt (get_ket y (bv_to_int (concat x z)))
(bv_to_ket (concat x z))))
((length x) + n)%Z))) /\
((partial_projection_bv x n) =
(diag_mat1 (fc21 x n) (power 2%Z ((length x) + n)%Z))))))))).
Parameter apply_part_proj: bitvec -> (matrix t) -> Z -> matrix t.
Axiom apply_part_proj_def :
forall (x:bitvec) (y:matrix t) (n:Z), (0%Z <= n)%Z ->
(is_a_ket_l y ((length x) + n)%Z) ->
((apply_part_proj x y n) = (kronecker (projection_bv x) (identity n))).
Axiom apply_part_proj_spec :
forall (x:bitvec) (y:matrix t) (n:Z), (0%Z <= n)%Z ->
(is_a_ket_l y ((length x) + n)%Z) ->
(is_a_ket_l (apply_part_proj x y n) n) /\
(((kronecker (bv_to_ket x) (apply_part_proj x y n)) =
(mat_mult (partial_projection_bv x n) y)) /\
((apply_part_proj x y n) =
(ket_sum_l (n_bvs n)
(fun (z:bitvec) =>
(infix_asdtdt (get_ket y (bv_to_int (concat x z))) (bv_to_ket z)))
n))).
Parameter braket: Z -> Z -> Z -> matrix t.
Axiom braket_def :
forall (n:Z) (i:Z) (j:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((braket n i j) = (mat_mult (bra n i) (ket n j))).
Axiom braket_spec :
forall (n:Z) (i:Z) (j:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((i = j) -> ((braket n i j) = (make 1%Z 1%Z tone))) /\
(~ (i = j) -> ((braket n i j) = (make 1%Z 1%Z tzero))).
Axiom braket_rows :
forall (n:Z) (i:Z) (j:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) -> ((rows (braket n i j)) = 1%Z).
Axiom braket_columns :
forall (n:Z) (i:Z) (j:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) -> ((columns (braket n i j)) = 1%Z).
Axiom braket_value :
forall (n:Z) (i:Z) (j:Z) (k:Z) (l:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < 1%Z)%Z) -> ((0%Z <= j)%Z /\ (j < 1%Z)%Z) ->
((0%Z <= k)%Z /\ (k < 1%Z)%Z) -> ((0%Z <= l)%Z /\ (l < 1%Z)%Z) ->
((i = j) -> ((get (braket n i j) k l) = tone)) /\
(~ (i = j) -> ((get (braket n i j) k l) = tzero)).
Axiom ketbraket_b :
forall (n:Z) (i:Z) (j:Z) (k:Z), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) ->
((k = j) -> ((mat_mult (ketbra n i j) (ket n k)) = (ket n i))) /\
(~ (k = j) ->
((mat_mult (ketbra n i j) (ket n k)) = (make (power 2%Z n) 1%Z tzero))).
Axiom ketbraket :
forall (n:Z) (i:Z) (j:Z) (y:matrix t), (n >= 0%Z)%Z ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) -> (is_a_ket_l y n) ->
((mat_mult (ketbra n i j) y) = (infix_asdtdt (get y j 0%Z) (ket n i))).
Axiom ketbraket_b_gen :
forall (n:Z), (n >= 0%Z)%Z -> forall (i:Z) (j:Z) (k:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z n))%Z) ->
((0%Z <= k)%Z /\ (k < (power 2%Z n))%Z) ->
((k = j) -> ((mat_mult (ketbra n i j) (ket n k)) = (ket n i))) /\
(~ (k = j) ->
((mat_mult (ketbra n i j) (ket n k)) = (make (power 2%Z n) 1%Z tzero))).
Axiom scalar_ketbra :
forall (x:matrix t) (a:t), (is_a_ketbra x) ->
is_a_ketbra (infix_asdtdt a x).
Axiom scalar_ketbra_n :
forall (x:matrix t) (a:t) (n:Z), (n >= 0%Z)%Z -> (is_a_ketbra_n x n) ->
is_a_ketbra_n (infix_asdtdt a x) n.
Axiom scalar_ketbra_size :
forall (m:matrix t) (a:t), (is_a_ketbra m) ->
((ketbra_size (infix_asdtdt a m)) = (ketbra_size m)).
Axiom scalar_valid_index :
forall (m:matrix t) (a:t) (i:Z) (j:Z), (valid_index m i j) ->
(is_a_ketbra m) -> valid_index (infix_asdtdt a m) i j.
Axiom scalar_ketbra_l :
forall (x:matrix t) (l:Z) (a:t), (is_a_ketbra_n x l) ->
is_a_ketbra_n (infix_asdtdt a x) l.
Parameter ketbra_sum:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> matrix t) -> matrix t.
Axiom ketbra_sum_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra (f e1)) ->
(exists l:Z, forall (e1:a), (mem e1 s) -> ((ketbra_size (f e1)) = l)) ->
((ketbra_sum s f) = (mat_sum s f)).
Axiom ketbra_sum_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra (f e1)) ->
(exists l:Z, forall (e1:a), (mem e1 s) -> ((ketbra_size (f e1)) = l)) ->
(forall (i:Z) (j:Z), (valid_index (ketbra_sum s f) i j) ->
((get (ketbra_sum s f) i j) = (sum s (fun (e1:a) => (get (f e1) i j))))) /\
((is_a_ketbra (ketbra_sum s f)) /\
forall (e1:a), (mem e1 s) ->
((ketbra_size (ketbra_sum s f)) = (ketbra_size (f e1)))).
Axiom mat_sum_to_ketbra_sum :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (a1:matrix t), ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra (f e1)) ->
(exists l:Z, forall (e1:a), (mem e1 s) -> ((ketbra_size (f e1)) = l)) ->
(a1 = (mat_sum s f)) -> (a1 = (ketbra_sum s f)).
Parameter ketbra_sum_l:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> matrix t) -> Z ->
matrix t.
Axiom ketbra_sum_l_def :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), (l >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) l) ->
((ketbra_sum_l s f l) = (mat_sum s f)).
Axiom ketbra_sum_l_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), (l >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) l) ->
(forall (i:Z) (j:Z), (valid_index (ketbra_sum_l s f l) i j) ->
((get (ketbra_sum_l s f l) i j) =
(sum s (fun (e1:a) => (get (f e1) i j))))) /\
((is_a_ketbra_n (ketbra_sum_l s f l) l) /\
(((ketbra_size (ketbra_sum_l s f l)) = l) /\
(((columns (ketbra_sum_l s f l)) = (power 2%Z l)) /\
((rows (ketbra_sum_l s f l)) = (power 2%Z l))))).
Axiom ketbra_sum_l_rows :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), (l >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) l) ->
((rows (ketbra_sum_l s f l)) = (power 2%Z l)).
Axiom ketbra_sum_l_value :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z) (i:Z) (j:Z), (l >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) l) ->
((0%Z <= i)%Z /\ (i < (power 2%Z l))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z l))%Z) ->
((get (ketbra_sum_l s f l) i j) = (sum s (fun (e1:a) => (get (f e1) i j)))).
Axiom ketbra_sum_l_columns :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), (l >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) l) ->
((columns (ketbra_sum_l s f l)) = (power 2%Z l)).
Axiom mat_sum_to_ketbra_sum_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (a1:matrix t) (l:Z),
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) l) ->
(a1 = (mat_sum s f)) -> (a1 = (ketbra_sum s f)).
Axiom ketbra_sum_null_but_maybe_one_elt :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a) (e1:a), ((cardinal s) > 1%Z)%Z ->
(forall (e2:a), (mem e2 s) -> is_a_ketbra (f e2)) -> (constant_size s f) ->
(mem e1 s) ->
(forall (e':a), (mem e' s) -> ~ (e1 = e') -> null_mat (f e')) ->
((ketbra_sum s f) = (f e1)).
Axiom ketbra_sum_null :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), (l >= 0%Z)%Z ->
((cardinal s) > 1%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) l) ->
(forall (e1:a), (mem e1 s) -> null_mat (f e1)) -> forall (i:Z) (j:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z l))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z l))%Z) ->
((get (ketbra_sum_l s f l) i j) = tzero).
Axiom ketbra_sum_l_null_but_maybe_one_elt :
forall {a:Type} {a_WT:WhyType a},
forall (f:a -> matrix t) (s:set a) (e1:a) (l:Z), ((cardinal s) > 1%Z)%Z ->
(l >= 0%Z)%Z -> (forall (e2:a), (mem e2 s) -> is_a_ketbra_n (f e2) l) ->
(mem e1 s) ->
(forall (e':a), (mem e' s) -> ~ (e1 = e') -> forall (i:Z) (j:Z),
((0%Z <= i)%Z /\ (i < (power 2%Z l))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z l))%Z) -> ((get (f e') i j) = tzero)) ->
((ketbra_sum_l s f l) = (f e1)).
Axiom mat_mult_ketbra_sum_out :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (y:matrix t) (n:Z), (0%Z <= n)%Z ->
((cardinal s) > 0%Z)%Z -> (is_a_ket_l y n) ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) n) ->
((mat_mult (ketbra_sum_l s f n) y) =
(ket_sum_l s (fun (e1:a) => (mat_mult (f e1) y)) n)).
Axiom ketbra_sum_ketbra_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), ((cardinal s) > 0%Z)%Z ->
(l >= 0%Z)%Z -> (forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) l) ->
is_a_ketbra_n (ketbra_sum_l s f l) l.
Parameter add_ketbra: (matrix t) -> (matrix t) -> matrix t.
Axiom add_ketbra_def :
forall (m:matrix t) (n:matrix t), (is_a_ketbra m) -> (is_a_ketbra n) ->
((ketbra_size m) = (ketbra_size n)) -> ((add_ketbra m n) = (add_mat m n)).
Axiom add_ketbra_spec :
forall (m:matrix t) (n:matrix t), (is_a_ketbra m) -> (is_a_ketbra n) ->
((ketbra_size m) = (ketbra_size n)) ->
(is_a_ketbra (add_ketbra m n)) /\
(((ketbra_size (add_ketbra m n)) = (ketbra_size m)) /\
forall (i:Z) (j:Z), (valid_index (add_ketbra m n) i j) ->
((get (add_ketbra m n) i j) = (infix_pldt (get m i j) (get n i j)))).
Parameter add_ketbra_l: (matrix t) -> (matrix t) -> Z -> matrix t.
Axiom add_ketbra_l_def :
forall (m:matrix t) (n:matrix t) (l:Z), (is_a_ketbra_n m l) ->
(is_a_ketbra_n n l) -> ((add_ketbra_l m n l) = (add_mat m n)).
Axiom add_ketbra_l_spec :
forall (m:matrix t) (n:matrix t) (l:Z), (is_a_ketbra_n m l) ->
(is_a_ketbra_n n l) ->
((add_ketbra_l m n l) = (add_ketbra m n)) /\
((is_a_ketbra_n (add_ketbra_l m n l) l) /\
(((ketbra_size (add_ketbra_l m n l)) = l) /\
forall (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < (power 2%Z l))%Z) ->
((0%Z <= j)%Z /\ (j < (power 2%Z l))%Z) ->
((get (add_ketbra_l m n l) i j) = (infix_pldt (get m i j) (get n i j))))).
Axiom ketbra_sum_comp_l :
forall {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> matrix t) (g:b -> matrix t) (l:Z),
((cardinal s) > 0%Z)%Z -> (l >= 0%Z)%Z ->
(forall (e1:b), (mem e1 s) -> is_a_ketbra_n (f e1) l) ->
(forall (e1:b), (mem e1 s) -> is_a_ketbra_n (g e1) l) ->
((ketbra_sum_l s (fun (k:b) => (add_ketbra_l (f k) (g k) l)) l) =
(add_ketbra_l (ketbra_sum_l s f l) (ketbra_sum_l s g l) l)).
Axiom ketbra_sum_comp_l_rev :
forall {b:Type} {b_WT:WhyType b},
forall (s:set b) (f:b -> matrix t) (g:b -> matrix t) (l:Z),
((cardinal s) > 0%Z)%Z -> (l >= 0%Z)%Z ->
(forall (e1:b), (mem e1 s) -> is_a_ketbra_n (f e1) l) ->
(forall (e1:b), (mem e1 s) -> is_a_ketbra_n (g e1) l) ->
((add_ketbra_l (ketbra_sum_l s f l) (ketbra_sum_l s g l) l) =
(ketbra_sum_l s (fun (k:b) => (add_ketbra_l (f k) (g k) l)) l)).
Axiom ketbra_sum_scalar_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (a1:t) (l:Z), (l >= 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) l) ->
((cardinal s) > 0%Z)%Z ->
((ketbra_sum_l s (fun (k:a) => (infix_asdtdt a1 (f k))) l) =
(infix_asdtdt a1 (ketbra_sum_l s f l))).
Axiom scal_ketbra_sum_scalar_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (b:t) (l:Z) (l':Z), (l >= 0%Z)%Z ->
(forall (e1:a), (mem e1 s) ->
exists a1:t,
exists k:matrix t, ((f e1) = (infix_asdtdt a1 k)) /\ (is_a_ketbra_n k l)) ->
((cardinal s) > 0%Z)%Z -> (l = l') ->
is_a_ketbra_n (infix_asdtdt b (ketbra_sum_l s f l)) l'.
Axiom ketbra_sum_scalar_rev_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (a1:t) (l:Z), (l >= 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) l) ->
((cardinal s) > 0%Z)%Z ->
((infix_asdtdt a1 (ketbra_sum_l s f l)) =
(ketbra_sum_l s (fun (k:a) => (infix_asdtdt a1 (f k))) l)).
Axiom ketbra_sum_eq :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (f:a -> matrix t) (g:a -> matrix t) (l:Z),
(l >= 0%Z)%Z -> ((cardinal s) > 0%Z)%Z -> (s = s') ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) l) ->
(forall (a1:a), (mem a1 s) -> ((f a1) = (g a1))) ->
((ketbra_sum_l s f l) = (ketbra_sum_l s' g l)).
Axiom ketbra_sum_eq_gen :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (s':set a) (f:a -> matrix t) (g:a -> matrix t) (l1:Z)
(l2:Z),
(l1 >= 0%Z)%Z -> ((cardinal s) > 0%Z)%Z -> (s = s') -> (l1 = l2) ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) l1) ->
(forall (a1:a), (mem a1 s) -> ((f a1) = (g a1))) ->
((ketbra_sum_l s f l1) = (ketbra_sum_l s' g l2)).
Axiom ketbra_sum_l_cardone :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (l:Z), (l >= 0%Z)%Z ->
((cardinal s) = 1%Z) -> (is_a_ketbra_n (f (choose s)) l) ->
((ketbra_sum_l s f l) = (f (choose s))).
Axiom ketbra_sum_l_plus_one :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (e1:a) (f:a -> matrix t) (l:Z), ((cardinal s) > 0%Z)%Z ->
~ (mem e1 s) -> (forall (e2:a), (mem e2 s) -> is_a_ketbra_n (f e2) l) ->
(is_a_ketbra_n (f e1) l) ->
((ketbra_sum_l (add e1 s) f l) =
(add_ketbra_l (ketbra_sum_l s f l) (f e1) l)).
Parameter mat_sum_d:
forall {a:Type} {a_WT:WhyType a}, (set a) -> (a -> matrix t) -> Z ->
Z -> matrix t.
Axiom mat_sum_d_spec :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> (forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((rows (mat_sum_d s f r c)) = r) /\
(((columns (mat_sum_d s f r c)) = c) /\
((forall (i:Z) (j:Z), (valid_index (mat_sum_d s f r c) i j) ->
((get (mat_sum_d s f r c) i j) = (sum s (fun (k:a) => (get (f k) i j))))) /\
((forall (i:Z) (j:Z), (valid_index (mat_sum_d s f r c) i j) ->
((0%Z <= i)%Z /\ (i < r)%Z) /\ ((0%Z <= j)%Z /\ (j < c)%Z)) /\
(((cardinal s) > 0%Z)%Z -> ((mat_sum_d s f r c) = (mat_sum s f)))))).
Axiom mat_sum_d_rows :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> (forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((rows (mat_sum_d s f r c)) = r).
Axiom mat_sum_d_columns :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> (forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((columns (mat_sum_d s f r c)) = c).
Axiom mat_sum_d_valid_index :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z) (i:Z) (j:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> (forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
(valid_index (mat_sum_d s f r c) i j) ->
((0%Z <= i)%Z /\ (i < r)%Z) /\ ((0%Z <= j)%Z /\ (j < c)%Z).
Axiom mat_sum_d_valid_i :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z) (i:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> (forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
(exists j:Z, valid_index (mat_sum_d s f r c) i j) ->
(0%Z <= i)%Z /\ (i < (rows (mat_sum_d s f r c)))%Z.
Axiom mat_sum_d_valid_j :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z) (j:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> (forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
(exists i:Z, valid_index (mat_sum_d s f r c) i j) ->
(0%Z <= j)%Z /\ (j < (columns (mat_sum_d s f r c)))%Z.
Axiom mat_sum_d_value :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z) (i:Z) (j:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> ((cardinal s) >= 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((0%Z <= i)%Z /\ (i < r)%Z) -> ((0%Z <= j)%Z /\ (j < c)%Z) ->
((get (mat_sum_d s f r c) i j) = (sum s (fun (k:a) => (get (f k) i j)))).
Axiom mat_sum_to_d :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((mat_sum s f) = (mat_sum_d s f r c)).
Axiom mat_sum_no_d :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> ((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((mat_sum_d s f r c) = (mat_sum s f)).
Axiom mat_sum_d_to_ket_sum_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:Z), ((cardinal s) > 0%Z)%Z ->
(n >= 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = (power 2%Z n))) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = 1%Z)) ->
((mat_sum_d s f (power 2%Z n) 1%Z) = (ket_sum_l s f n)).
Axiom mat_sum_d_to_ketbra_sum_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:Z), (n >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = (power 2%Z n))) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = (power 2%Z n))) ->
((mat_sum_d s f (power 2%Z n) (power 2%Z n)) = (ketbra_sum_l s f n)).
Axiom ket_sum_l_to_mat_sum_d :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:Z), (n >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = (power 2%Z n))) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = 1%Z)) ->
((ket_sum_l s f n) = (mat_sum_d s f (power 2%Z n) 1%Z)).
Axiom bra_sum_l_to_mat_sum_d :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:Z), (n >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = 1%Z)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = (power 2%Z n))) ->
((bra_sum_l s f n) = (mat_sum_d s f 1%Z (power 2%Z n))).
Axiom mat_sum_d_to_bra_sum_l :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:Z), (n >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = 1%Z)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = (power 2%Z n))) ->
((bra_sum_l s f n) = (mat_sum_d s f 1%Z (power 2%Z n))).
Axiom ketbra_sum_l_to_mat_sum_d :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:Z), (n >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = (power 2%Z n))) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = (power 2%Z n))) ->
((ketbra_sum_l s f n) = (mat_sum_d s f (power 2%Z n) (power 2%Z n))).
Axiom mat_sum_d_cardone :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> ((cardinal s) = 1%Z) -> ((rows (f (choose s))) = r) ->
((columns (f (choose s))) = c) -> ((mat_sum_d s f r c) = (f (choose s))).
Axiom mat_sum_d_cardzero :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> ((cardinal s) = 0%Z) ->
((mat_sum_d s f r c) = (make r c tzero)).
Axiom mat_sum_d_eq :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (g:a -> matrix t) (r:Z) (c:Z) (r':Z)
(c':Z),
(r > 0%Z)%Z -> (c > 0%Z)%Z -> ((cardinal s) >= 0%Z)%Z -> (r = r') ->
(c = c') -> (forall (e1:a), (mem e1 s) -> ((f e1) = (g e1))) ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((mat_sum_d s f r c) = (mat_sum_d s g r' c')).
Axiom mat_sum_d_plus_one :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> ((cardinal s) >= 1%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((mat_sum_d s f r c) =
(add_mat (f (choose s)) (mat_sum_d (remove (choose s) s) f r c))).
Axiom sum_sum_switch :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (sa:set a) (sb:set b) (f:a -> b -> t), ((cardinal sa) > 0%Z)%Z ->
((cardinal sb) > 0%Z)%Z ->
((sum sa (fun (a1:a) => (sum sb (f a1)))) =
(sum sb (fun (b1:b) => (sum sa (fun (a1:a) => ((f a1) b1)))))).
Parameter mat_sum_sum_d:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (set a) ->
(set b) -> (a -> b -> matrix t) -> Z -> Z -> matrix t.
Parameter result24:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (set a) ->
(set b) -> (a -> b -> matrix t) -> Z -> Z -> a -> matrix t.
Axiom result_def24 :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (sa:set a) (sb:set b) (f:a -> b -> matrix t) (r:Z) (c:Z) (a1:a),
((mem a1 sa) -> (((result24 sa sb f r c) a1) = (mat_sum_d sb (f a1) r c))) /\
(~ (mem a1 sa) -> (((result24 sa sb f r c) a1) = (make r c tzero))).
Axiom mat_sum_sum_d_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (sa:set a) (sb:set b) (f:a -> b -> matrix t) (r:Z) (c:Z),
(r > 0%Z)%Z -> (c > 0%Z)%Z -> ((cardinal sa) > 0%Z)%Z ->
((cardinal sb) > 0%Z)%Z ->
(forall (a1:a), forall (b1:b), (mem a1 sa) -> (mem b1 sb) ->
((rows ((f a1) b1)) = r)) ->
(forall (a1:a), forall (b1:b), (mem a1 sa) -> (mem b1 sb) ->
((columns ((f a1) b1)) = c)) ->
((mat_sum_sum_d sa sb f r c) = (mat_sum_d sa (result24 sa sb f r c) r c)).
Axiom mat_sum_sum_d_spec :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (sa:set a) (sb:set b) (f:a -> b -> matrix t) (r:Z) (c:Z),
(r > 0%Z)%Z -> (c > 0%Z)%Z -> ((cardinal sa) > 0%Z)%Z ->
((cardinal sb) > 0%Z)%Z ->
(forall (a1:a), forall (b1:b), (mem a1 sa) -> (mem b1 sb) ->
((rows ((f a1) b1)) = r)) ->
(forall (a1:a), forall (b1:b), (mem a1 sa) -> (mem b1 sb) ->
((columns ((f a1) b1)) = c)) ->
((mat_sum_sum_d sa sb f r c) =
(mat_sum_d sa (fun (a1:a) => (mat_sum_d sb (f a1) r c)) r c)) /\
(((rows (mat_sum_sum_d sa sb f r c)) = r) /\
(((columns (mat_sum_sum_d sa sb f r c)) = c) /\
forall (i:Z) (j:Z), ((0%Z <= i)%Z /\ (i < r)%Z) ->
((0%Z <= j)%Z /\ (j < c)%Z) ->
((get (mat_sum_sum_d sa sb f r c) i j) =
(sum sa (fun (a1:a) => (sum sb (fun (b1:b) => (get ((f a1) b1) i j)))))))).
Axiom mat_sum_sum_d_switch :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (sa:set a) (sb:set b) (f:a -> b -> matrix t) (r:Z) (c:Z),
(r > 0%Z)%Z -> (c > 0%Z)%Z -> ((cardinal sa) > 0%Z)%Z ->
((cardinal sb) > 0%Z)%Z ->
(forall (a1:a), forall (b1:b), (mem a1 sa) -> (mem b1 sb) ->
((rows ((f a1) b1)) = r)) ->
(forall (a1:a), forall (b1:b), (mem a1 sa) -> (mem b1 sb) ->
((columns ((f a1) b1)) = c)) ->
((mat_sum_d sa
(fun (a1:a) => (mat_sum_d sb (fun (b1:b) => ((f a1) b1)) r c)) r c)
=
(mat_sum_d sb
(fun (b1:b) => (mat_sum_d sa (fun (a1:a) => ((f a1) b1)) r c)) r c)).
Axiom kron_assoc_mult :
forall (a:matrix t) (b:matrix t) (c:matrix t),
(((rows a) = (columns b)) /\
(((columns b) = (rows c)) /\ ((rows c) = (columns c)))) ->
(((columns a) = (rows b)) /\ ((rows b) = 1%Z)) ->
((kronecker a (mat_mult b c)) = (mat_mult (kronecker a b) c)).
Axiom mult_assoc_kron :
forall (a:matrix t) (b:matrix t) (c:matrix t),
(((rows b) = (columns c)) /\
(((columns c) = (rows a)) /\ ((rows a) = (columns a)))) ->
(((columns b) = (rows c)) /\ ((rows c) = 1%Z)) ->
((mat_mult a (kronecker b c)) = (kronecker (mat_mult a b) c)).
Axiom mat_sum_d_to_ket_sum_l1 :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:Z),
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) n) -> (0%Z <= n)%Z ->
((cardinal s) > 0%Z)%Z ->
((mat_sum_d s f (power 2%Z n) 1%Z) = (ket_sum_l s f n)).
Axiom mat_sum_d_to_ketbra_sum_l1 :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:Z),
(forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) n) -> (0%Z <= n)%Z ->
((cardinal s) > 0%Z)%Z ->
((mat_sum_d s f (power 2%Z n) (power 2%Z n)) = (ketbra_sum_l s f n)).
Parameter get_ket_bv1: (matrix t) -> bitvec -> t.
Axiom get_ket_bv_def1 :
forall (k:matrix t) (x:bitvec), (is_a_ket k) ->
((length x) = (ket_length k)) -> ((length x) = (ket_length k)) ->
((get_ket_bv1 k x) = (get_ket k (bv_to_int x))).
Axiom get_ket_to_get_ket_bv :
forall (k:matrix t) (i:Z) (n:Z), (is_a_ket_l k n) ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) ->
((get_ket k i) = (get_ket_bv1 k (int_to_bv i n))).
Axiom get_to_get_ket_bv :
forall (k:matrix t) (i:Z) (j:Z) (n:Z), (is_a_ket_l k n) ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> (j = 0%Z) ->
((get k i j) = (get_ket_bv1 k (int_to_bv i n))).
Axiom get_ket_bv_to_get :
forall (k:matrix t) (i:Z) (j:Z) (n:Z), (is_a_ket_l k n) ->
((0%Z <= i)%Z /\ (i < (power 2%Z n))%Z) -> (j = 0%Z) ->
((get_ket_bv1 k (int_to_bv i n)) = (get k i j)).
Axiom ket_sum_l_to_mat_sum_d1 :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:Z), ((cardinal s) > 0%Z)%Z ->
(0%Z <= n)%Z -> (forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) n) ->
((ket_sum_l s f n) = (mat_sum_d s f (power 2%Z n) 1%Z)).
Axiom ketbra_sum_l_to_mat_sum_d1 :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:Z), ((cardinal s) > 0%Z)%Z ->
(0%Z <= n)%Z -> (forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) n) ->
((ketbra_sum_l s f n) = (mat_sum_d s f (power 2%Z n) (power 2%Z n))).
Axiom ket_sum_sum_as_mat :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (sa:set a) (sb:set b) (f:a -> b -> matrix t) (n:Z), (n >= 0%Z)%Z ->
((cardinal sa) > 0%Z)%Z -> ((cardinal sb) > 0%Z)%Z ->
(forall (a1:a), forall (b1:b), (mem a1 sa) -> (mem b1 sb) ->
is_a_ket_l ((f a1) b1) n) ->
((ket_sum_l sa (fun (a1:a) => (ket_sum_l sb (f a1) n)) n) =
(mat_sum_d sa (fun (a1:a) => (mat_sum_d sb (f a1) (power 2%Z n) 1%Z))
(power 2%Z n) 1%Z)).
Axiom ket_sum_sum_d_switch :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (sa:set a) (sb:set b) (f:a -> b -> matrix t) (n:Z), (n >= 0%Z)%Z ->
((cardinal sa) > 0%Z)%Z -> ((cardinal sb) > 0%Z)%Z ->
(forall (a1:a), forall (b1:b), (mem a1 sa) -> (mem b1 sb) ->
is_a_ket_l ((f a1) b1) n) ->
((ket_sum_l sa (fun (a1:a) => (ket_sum_l sb (f a1) n)) n) =
(ket_sum_l sb (fun (b1:b) => (ket_sum_l sa (fun (a1:a) => ((f a1) b1)) n))
n)).
Axiom ketbra_sum_sum_as_mat :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (sa:set a) (sb:set b) (f:a -> b -> matrix t) (n:Z), (n >= 0%Z)%Z ->
((cardinal sa) > 0%Z)%Z -> ((cardinal sb) > 0%Z)%Z ->
(forall (a1:a), forall (b1:b), (mem a1 sa) -> (mem b1 sb) ->
is_a_ketbra_n ((f a1) b1) n) ->
((ketbra_sum_l sa (fun (a1:a) => (ketbra_sum_l sb (f a1) n)) n) =
(mat_sum_d sa
(fun (a1:a) => (mat_sum_d sb (f a1) (power 2%Z n) (power 2%Z n)))
(power 2%Z n) (power 2%Z n))).
Axiom ketbra_sum_sum_d_switch :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (sa:set a) (sb:set b) (f:a -> b -> matrix t) (n:Z), (n >= 0%Z)%Z ->
((cardinal sa) > 0%Z)%Z -> ((cardinal sb) > 0%Z)%Z ->
(forall (a1:a), forall (b1:b), (mem a1 sa) -> (mem b1 sb) ->
is_a_ketbra_n ((f a1) b1) n) ->
((ketbra_sum_l sa (fun (a1:a) => (ketbra_sum_l sb (f a1) n)) n) =
(ketbra_sum_l sb
(fun (b1:b) => (ketbra_sum_l sa (fun (a1:a) => ((f a1) b1)) n)) n)).
Axiom pre_reqs_of_size_range :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z) (x:matrix t),
(is_a_ket_l x size1) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = size1) ->
((length y) = range1) -> ((length ((k x1) y)) = size1)) ->
(forall (e1:bitvec) (y:bitvec), (mem e1 (n_bvs size1)) ->
(mem y (n_bvs range1)) ->
is_a_ket_l (infix_asdtdt (ang_exp ((a e1) y)) (bv_to_ket ((k e1) y)))
size1) /\
((forall (e1:bitvec) (y:bitvec), (mem e1 (n_bvs size1)) ->
(mem y (n_bvs range1)) ->
is_a_ket_l
(infix_asdtdt (get x (bv_to_int e1) 0%Z)
(infix_asdtdt (ang_exp ((a e1) y)) (bv_to_ket ((k e1) y))))
size1) /\
forall (e1:bitvec) (y:bitvec), (mem e1 (n_bvs size1)) ->
(mem y (n_bvs range1)) ->
is_a_ket_l
(infix_asdtdt (get x (bv_to_int e1) 0%Z)
(infix_asdtdt (pow_inv_sqrt_2 range1)
(infix_asdtdt (ang_exp ((a e1) y)) (bv_to_ket ((k e1) y)))))
size1).
Axiom pre_reqs_of_size :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z) (x:matrix t),
(is_a_ket_l x size1) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = size1) ->
((length y) = range1) -> ((length ((k x1) y)) = size1)) ->
(forall (e1:bitvec), (mem e1 (n_bvs size1)) ->
is_a_ket_l
(ket_sum_l (n_bvs range1)
(fun (y:bitvec) =>
(infix_asdtdt (get x (bv_to_int e1) 0%Z)
(infix_asdtdt (pow_inv_sqrt_2 range1)
(infix_asdtdt (ang_exp ((a e1) y)) (bv_to_ket ((k e1) y))))))
size1)
size1) /\
((forall (e1:bitvec), (mem e1 (n_bvs size1)) ->
is_a_ket_l
(infix_asdtdt (get x (bv_to_int e1) 0%Z)
(ket_sum_l (n_bvs range1)
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp ((a e1) y)) (bv_to_ket ((k e1) y))))
size1))
size1) /\
((forall (e1:bitvec), (mem e1 (n_bvs size1)) ->
is_a_ket_l
(ket_sum_l (n_bvs range1)
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp ((a e1) y)) (bv_to_ket ((k e1) y))))
size1)
size1) /\
forall (e1:bitvec), (mem e1 (n_bvs size1)) ->
is_a_ket_l
(infix_asdtdt (get x (bv_to_int e1) 0%Z)
(ket_sum_l (n_bvs range1)
(fun (y:bitvec) =>
(infix_asdtdt (pow_inv_sqrt_2 range1)
(infix_asdtdt (ang_exp ((a e1) y)) (bv_to_ket ((k e1) y)))))
size1))
size1)).
Axiom pre_reqs_of_range :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z) (x:matrix t),
(is_a_ket_l x size1) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = size1) ->
((length y) = range1) -> ((length ((k x1) y)) = size1)) ->
(forall (y:bitvec), (mem y (n_bvs range1)) ->
is_a_ket_l
(ket_sum_l (n_bvs size1)
(fun (e1:bitvec) =>
(infix_asdtdt (ang_exp ((a e1) y)) (bv_to_ket ((k e1) y))))
size1)
size1) /\
forall (y:bitvec), (mem y (n_bvs range1)) ->
is_a_ket_l
(infix_asdtdt (get x (bv_to_int y) 0%Z)
(ket_sum_l (n_bvs size1)
(fun (e1:bitvec) =>
(infix_asdtdt (ang_exp ((a e1) y)) (bv_to_ket ((k e1) y))))
size1))
size1.
Axiom sop_angle_in :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z) (x:matrix t),
(is_a_ket_l x size1) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = size1) ->
((length y) = range1) -> ((length ((k x1) y)) = size1)) ->
((path_sum_scheme a k size1 range1 x) =
(ket_sum_l (n_bvs size1)
(fun (z:bitvec) =>
(ket_sum_l (n_bvs range1)
(fun (y:bitvec) =>
(infix_asdtdt (get x (bv_to_int z) 0%Z)
(infix_asdtdt (pow_inv_sqrt_2 range1)
(infix_asdtdt (ang_exp ((a z) y)) (bv_to_ket ((k z) y))))))
size1))
size1)).
Axiom sop_size_range :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z) (x:matrix t),
(is_a_ket_l x size1) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = size1) ->
((length y) = range1) -> ((length ((k x1) y)) = size1)) ->
((path_sum_scheme a k size1 range1 x) =
(infix_asdtdt (pow_inv_sqrt_2 range1)
(ket_sum_l (n_bvs size1)
(fun (z:bitvec) =>
(infix_asdtdt (get x (bv_to_int z) 0%Z)
(ket_sum_l (n_bvs range1)
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp ((a z) y)) (bv_to_ket ((k z) y))))
size1)))
size1))).
Axiom sop_range_size :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z) (x:matrix t),
(is_a_ket_l x size1) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = size1) ->
((length y) = range1) -> ((length ((k x1) y)) = size1)) ->
((path_sum_scheme a k size1 range1 x) =
(infix_asdtdt (pow_inv_sqrt_2 range1)
(ket_sum_l (n_bvs range1)
(fun (y:bitvec) =>
(ket_sum_l (n_bvs size1)
(fun (z:bitvec) =>
(infix_asdtdt (get x (bv_to_int z) 0%Z)
(infix_asdtdt (ang_exp ((a z) y)) (bv_to_ket ((k z) y)))))
size1))
size1))).
Axiom sop_ketbra_in :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z) (x:matrix t),
(is_a_ket_l x size1) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = size1) ->
((length y) = range1) -> ((length ((k x1) y)) = size1)) ->
((path_sum_scheme a k size1 range1 x) =
(infix_asdtdt (pow_inv_sqrt_2 range1)
(ket_sum_l (n_bvs size1)
(fun (z:bitvec) =>
(ket_sum_l (n_bvs range1)
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp ((a z) y))
(mat_mult (ketbra size1 (bv_to_int ((k z) y)) (bv_to_int z)) x)))
size1))
size1))).
Axiom sop_ketbra_range_size_pre :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z) (x:matrix t),
(is_a_ket_l x size1) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = size1) ->
((length y) = range1) -> ((length ((k x1) y)) = size1)) ->
((path_sum_scheme a k size1 range1 x) =
(infix_asdtdt (pow_inv_sqrt_2 range1)
(ket_sum_l (n_bvs range1)
(fun (y:bitvec) =>
(ket_sum_l (n_bvs size1)
(fun (z:bitvec) =>
(infix_asdtdt (ang_exp ((a z) y))
(mat_mult (ketbra size1 (bv_to_int ((k z) y)) (bv_to_int z)) x)))
size1))
size1))).
Axiom sop_ketbra_range_size :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z) (x:matrix t),
(is_a_ket_l x size1) -> (range1 >= 0%Z)%Z ->
(forall (x1:bitvec) (y:bitvec), ((length x1) = size1) ->
((length y) = range1) -> ((length ((k x1) y)) = size1)) ->
((path_sum_scheme a k size1 range1 x) =
(infix_asdtdt (pow_inv_sqrt_2 range1)
(ket_sum_l (n_bvs range1)
(fun (y:bitvec) =>
(ket_sum_l (n_bvs size1)
(fun (z:bitvec) =>
(mat_mult
(infix_asdtdt (ang_exp ((a z) y))
(ketbra size1 (bv_to_int ((k z) y)) (bv_to_int z)))
x))
size1))
size1))).
Parameter ketbra_sop:
(bitvec -> bitvec -> angle) -> (bitvec -> bitvec -> bitvec) -> Z ->
Z -> matrix t.
Parameter result25:
(bitvec -> bitvec -> angle) -> (bitvec -> bitvec -> bitvec) -> Z ->
Z -> bitvec -> bitvec -> matrix t.
Parameter result26:
(bitvec -> bitvec -> angle) -> (bitvec -> bitvec -> bitvec) -> Z ->
Z -> bitvec -> matrix t.
Axiom result_def25 :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z) (z:bitvec) (y:bitvec),
(((length y) = range1) ->
(((result25 a k size1 range1 z) y) =
(infix_asdtdt (ang_exp ((a z) y))
(ketbra size1 (bv_to_int ((k z) y)) (bv_to_int z))))) /\
(~ ((length y) = range1) ->
(((result25 a k size1 range1 z) y) = (ket size1 0%Z))).
Axiom result_def26 :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z) (z:bitvec),
(((length z) = size1) ->
(((result26 a k size1 range1) z) =
(ketbra_sum_l (n_bvs range1) (result25 a k size1 range1 z) size1))) /\
(~ ((length z) = size1) ->
(((result26 a k size1 range1) z) = (ket size1 0%Z))).
Axiom ketbra_sop_def :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z),
(size1 >= 0%Z)%Z -> (range1 >= 0%Z)%Z ->
(forall (x:bitvec) (y:bitvec), ((length x) = size1) ->
((length y) = range1) -> ((length ((k x) y)) = size1)) ->
((ketbra_sop a k size1 range1) =
(infix_asdtdt (pow_inv_sqrt_2 range1)
(ketbra_sum_l (n_bvs size1) (result26 a k size1 range1) size1))).
Axiom ketbra_sop_spec :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z),
(size1 >= 0%Z)%Z -> (range1 >= 0%Z)%Z ->
(forall (x:bitvec) (y:bitvec), ((length x) = size1) ->
((length y) = range1) -> ((length ((k x) y)) = size1)) ->
(is_a_ketbra_n (ketbra_sop a k size1 range1) size1) /\
(((rows (ketbra_sop a k size1 range1)) = (power 2%Z size1)) /\
(((columns (ketbra_sop a k size1 range1)) = (power 2%Z size1)) /\
(((ketbra_sop a k size1 range1) =
(infix_asdtdt (pow_inv_sqrt_2 range1)
(ketbra_sum_l (n_bvs size1)
(fun (z:bitvec) =>
(ketbra_sum_l (n_bvs range1)
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp ((a z) y))
(ketbra size1 (bv_to_int ((k z) y)) (bv_to_int z))))
size1))
size1))) /\
forall (x:matrix t), (is_a_ket_l x size1) ->
((mat_mult (ketbra_sop a k size1 range1) x) =
(path_sum_scheme a k size1 range1 x))))).
Parameter ketbra_sop_rs:
(bitvec -> bitvec -> angle) -> (bitvec -> bitvec -> bitvec) -> Z ->
Z -> matrix t.
Parameter result27:
(bitvec -> bitvec -> angle) -> (bitvec -> bitvec -> bitvec) -> Z ->
bitvec -> bitvec -> matrix t.
Parameter result28:
(bitvec -> bitvec -> angle) -> (bitvec -> bitvec -> bitvec) -> Z ->
Z -> bitvec -> matrix t.
Axiom result_def27 :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (y:bitvec) (z:bitvec),
(((length z) = size1) ->
(((result27 a k size1 y) z) =
(infix_asdtdt (ang_exp ((a z) y))
(ketbra size1 (bv_to_int ((k z) y)) (bv_to_int z))))) /\
(~ ((length z) = size1) -> (((result27 a k size1 y) z) = (ket size1 0%Z))).
Axiom result_def28 :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z) (y:bitvec),
(((length y) = range1) ->
(((result28 a k size1 range1) y) =
(ketbra_sum_l (n_bvs size1) (result27 a k size1 y) size1))) /\
(~ ((length y) = range1) ->
(((result28 a k size1 range1) y) = (ket size1 0%Z))).
Axiom ketbra_sop_rs_def :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z),
(size1 >= 0%Z)%Z -> (range1 >= 0%Z)%Z ->
(forall (x:bitvec) (y:bitvec), ((length x) = size1) ->
((length y) = range1) -> ((length ((k x) y)) = size1)) ->
((ketbra_sop_rs a k size1 range1) =
(infix_asdtdt (pow_inv_sqrt_2 range1)
(ketbra_sum_l (n_bvs range1) (result28 a k size1 range1) size1))).
Axiom ketbra_sop_rs_spec :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z),
(size1 >= 0%Z)%Z -> (range1 >= 0%Z)%Z ->
(forall (x:bitvec) (y:bitvec), ((length x) = size1) ->
((length y) = range1) -> ((length ((k x) y)) = size1)) ->
((ketbra_sop_rs a k size1 range1) =
(infix_asdtdt (pow_inv_sqrt_2 range1)
(ketbra_sum_l (n_bvs range1)
(fun (y:bitvec) =>
(ketbra_sum_l (n_bvs size1)
(fun (z:bitvec) =>
(infix_asdtdt (ang_exp ((a z) y))
(ketbra size1 (bv_to_int ((k z) y)) (bv_to_int z))))
size1))
size1))) /\
(((ketbra_sop_rs a k size1 range1) = (ketbra_sop a k size1 range1)) /\
forall (x:matrix t), (is_a_ket_l x size1) ->
((mat_mult (ketbra_sop_rs a k size1 range1) x) =
(path_sum_scheme a k size1 range1 x))).
Axiom ketbra_sop_mult :
forall (a:bitvec -> bitvec -> angle) (k:bitvec -> bitvec -> bitvec)
(size1:Z) (range1:Z),
(size1 >= 0%Z)%Z -> (range1 >= 0%Z)%Z ->
(forall (x:bitvec) (y:bitvec), ((length x) = size1) ->
((length y) = range1) -> ((length ((k x) y)) = size1)) ->
forall (x:matrix t), (is_a_ket_l x size1) ->
((mat_mult (ketbra_sop a k size1 range1) x) =
(infix_asdtdt (pow_inv_sqrt_2 range1)
(ket_sum_l (n_bvs size1)
(fun (z:bitvec) =>
(ket_sum_l (n_bvs range1)
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp ((a z) y))
(mat_mult (ketbra size1 (bv_to_int ((k z) y)) (bv_to_int z)) x)))
size1))
size1))).
Axiom correct_ketbra_sop :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(k:bitvec -> bitvec -> bitvec) (range1:Z) (x:matrix t),
(is_a_ket_l x (width c)) -> (correct_path_sum c a k range1) ->
sem c x (mat_mult (ketbra_sop a k (width c) range1) x).
Axiom correct_ketbra_sop_rs :
forall (c:circuit) (a:bitvec -> bitvec -> angle)
(k:bitvec -> bitvec -> bitvec) (range1:Z) (x:matrix t),
(is_a_ket_l x (width c)) -> (correct_path_sum c a k range1) ->
sem c x (mat_mult (ketbra_sop_rs a k (width c) range1) x).
Parameter discard:
(matrix t) -> (matrix t) -> (matrix t) -> Z -> Z -> matrix t.
Axiom discard_def :
forall (x:matrix t) (y:matrix t) (z:matrix t) (k:Z) (n:Z),
(is_a_ket_l x k) -> (is_a_ket_l y (n - k)%Z) -> (z = (kronecker x y)) ->
((discard x y z k n) = x).
Axiom discard_spec :
forall (x:matrix t) (y:matrix t) (z:matrix t) (k:Z) (n:Z),
(is_a_ket_l x k) -> (is_a_ket_l y (n - k)%Z) -> (z = (kronecker x y)) ->
is_a_ket_l (discard x y z k n) k.
Parameter proba_measure: (matrix t) -> Z -> Z -> t.
Axiom proba_measure_def :
forall (x:matrix t) (i:Z) (n:Z), (is_a_ket_l x n) ->
((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) ->
((proba_measure x i n) = (cpower (modulus (get x i 0%Z)) 2%Z)).
Axiom proba_measure_spec :
forall (x:matrix t) (i:Z) (n:Z), (is_a_ket_l x n) ->
((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) ->
((proba_measure x i n) = (cpower (modulus (get_ket x i)) 2%Z)).
Parameter proba_measure_sat_p: (matrix t) -> Z -> (Z -> bool) -> t.
Parameter result29: (matrix t) -> Z -> Z -> t.
Axiom result_def29 :
forall (x:matrix t) (n:Z) (k:Z),
(((0%Z <= k)%Z /\ (k < (power_ 2%Z n))%Z) ->
(((result29 x n) k) = (proba_measure x k n))) /\
(~ ((0%Z <= k)%Z /\ (k < (power_ 2%Z n))%Z) ->
(((result29 x n) k) = tzero)).
Axiom proba_measure_sat_p_def :
forall (x:matrix t) (n:Z) (f:Z -> bool), (is_a_ket_l x n) ->
((proba_measure_sat_p x n f) =
(sum (my_filter (to_fset 0%Z (power_ 2%Z n)) f) (result29 x n))).
Axiom proba_measure_sat_p_spec :
forall (x:matrix t) (n:Z) (f:Z -> bool), (is_a_ket_l x n) ->
((proba_measure_sat_p x n f) =
(sum (my_filter (to_fset 0%Z (power_ 2%Z n)) f)
(fun (k:Z) => (proba_measure x k n)))).
Axiom proba_measure_from_sum :
forall (x:matrix t) (i:Z) (n:Z) (f:bitvec -> t), (is_a_ket_l x n) ->
((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) ->
(x =
(ket_sum_l (n_bvs n)
(fun (k:bitvec) => (infix_asdtdt (f k) (bv_to_ket k))) n)) ->
((proba_measure x i n) = (cpower (modulus (f (int_to_bv i n))) 2%Z)).
Axiom proba_measure_sat_p_const :
forall (x:matrix t) (n:Z) (f:Z -> bool) (t1:t) (t':t), (is_a_ket_l x n) ->
(t' =
(infix_asdt t1
(i_to_t (cardinal (my_filter (to_fset 0%Z (power_ 2%Z n)) f))))) ->
(forall (i:Z), ((f i) = true) ->
((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) -> ((proba_measure x i n) = t1)) ->
((proba_measure_sat_p x n f) = t').
Axiom proba_measure_from_sum_partition :
forall (x:matrix t) (s1:set Z) (s2:set Z) (i:Z) (n:Z) (scal1:t) (scal2:t)
(f1:Z -> t) (f2:Z -> t),
((union s1 s2) = (to_fset 0%Z (power 2%Z n))) ->
((inter s1 s2) = (empty : set Z)) -> (real_ scal1) -> (real_ scal2) ->
(is_a_ket_l x n) -> ((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) ->
(x =
(add_mat
(infix_asdtdt scal1
(ket_sum_l s1 (fun (k:Z) => (infix_asdtdt (f1 k) (ket n k))) n))
(infix_asdtdt scal2
(ket_sum_l s2 (fun (k:Z) => (infix_asdtdt (f2 k) (ket n k))) n)))) ->
((mem i s1) ->
((proba_measure x i n) = (cpower (infix_asdt scal1 (f1 i)) 2%Z))) /\
(~ (mem i s1) ->
((proba_measure x i n) = (cpower (infix_asdt scal2 (f2 i)) 2%Z))).
Axiom proba_measure_from_sum_partition_gen :
forall (x:matrix t) (s1:set Z) (s2:set Z) (n:Z) (scal1:t) (scal2:t),
((union s1 s2) = (to_fset 0%Z (power 2%Z n))) ->
((inter s1 s2) = (empty : set Z)) -> (real_ scal1) -> (real_ scal2) ->
(is_a_ket_l x n) ->
(x =
(add_mat
(infix_asdtdt scal1
(ket_sum_l s1 ((fun (y0:Z) (y1:Z) => (ket y0 y1)) n) n))
(infix_asdtdt scal2
(ket_sum_l s2 ((fun (y0:Z) (y1:Z) => (ket y0 y1)) n) n)))) ->
forall (i:Z), ((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) ->
((mem i s1) -> ((proba_measure x i n) = (cpower scal1 2%Z))) /\
(~ (mem i s1) -> ((proba_measure x i n) = (cpower scal2 2%Z))).
Axiom proba_measure_from_sum_sum :
forall (x:matrix t) (l:Z) (n:Z) (f:bitvec -> bitvec -> t),
(is_a_ket_l x n) -> ((0%Z <= l)%Z /\ (l < (power_ 2%Z n))%Z) ->
(x =
(ket_sum_l (n_bvs n)
(fun (k:bitvec) =>
(ket_sum_l (n_bvs n)
(fun (l1:bitvec) => (infix_asdtdt ((f k) l1) (bv_to_ket l1))) n))
n)) ->
((proba_measure x l n) =
(cpower
(modulus (sum (n_bvs n) (fun (k:bitvec) => ((f k) (int_to_bv l n)))))
2%Z)).
Axiom proba_measure_from_scal_sum_sum :
forall (x:matrix t) (i:Z) (n:Z) (f:bitvec -> bitvec -> t) (s:t) (s2:t),
(is_a_ket_l x n) -> ((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) ->
(real_ s) ->
(x =
(infix_asdtdt s
(ket_sum_l (n_bvs n)
(fun (k:bitvec) =>
(ket_sum_l (n_bvs n)
(fun (l:bitvec) => (infix_asdtdt ((f k) l) (bv_to_ket l))) n))
n))) ->
(s2 = (cpower s 2%Z)) ->
((proba_measure x i n) =
(infix_asdt s2
(cpower
(modulus (sum (n_bvs n) (fun (k:bitvec) => ((f k) (int_to_bv i n)))))
2%Z))).
Axiom proba_measure_from_scal_ind_sum :
forall (x:matrix t) (i:Z) (n:Z) (f:Z -> Z -> t) (s:t) (s2:t),
(is_a_ket_l x n) -> ((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) ->
(real_ s) ->
(x =
(infix_asdtdt s
(ket_sum_l (n_bvs n)
(fun (k:bitvec) =>
(ket_sum_l (n_bvs n)
(fun (l:bitvec) =>
(infix_asdtdt ((f (bv_to_int k)) (bv_to_int l)) (bv_to_ket l)))
n))
n))) ->
(s2 = (cpower s 2%Z)) ->
((proba_measure x i n) =
(infix_asdt s2
(cpower (modulus (ind_sum (fun (k:Z) => ((f k) i)) 0%Z (power_ 2%Z n)))
2%Z))).
Axiom proba_measure_from_scal_sum_sum_gen :
forall (x:matrix t) (n:Z) (f:bitvec -> bitvec -> t) (s:t) (s2:t),
(real_ s) ->
(x =
(infix_asdtdt s
(ket_sum_l (n_bvs n)
(fun (k:bitvec) =>
(ket_sum_l (n_bvs n)
(fun (l:bitvec) => (infix_asdtdt ((f k) l) (bv_to_ket l))) n))
n))) ->
(s2 = (cpower s 2%Z)) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) ->
((proba_measure x i n) =
(infix_asdt s2
(cpower
(modulus (sum (n_bvs n) (fun (k:bitvec) => ((f k) (int_to_bv i n)))))
2%Z)))) /\
forall (i:Z), ((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) ->
((proba_measure x i n) =
(infix_asdt s2
(cpower
(modulus
(sum (to_fset 0%Z (power_ 2%Z n))
(fun (k:Z) => ((f (int_to_bv k n)) (int_to_bv i n)))))
2%Z))).
Parameter qbit_zero: unit -> matrix t.
Axiom qbit_zero_def : forall (us:unit), ((qbit_zero us) = (ket 1%Z 0%Z)).
Axiom qbit_zero_spec :
forall (us:unit),
(is_a_ket_l (qbit_zero us) 1%Z) /\
(((rows (qbit_zero us)) = 2%Z) /\
(((columns (qbit_zero us)) = 1%Z) /\
(((get (qbit_zero us) 0%Z 0%Z) = tone) /\
((get (qbit_zero us) 1%Z 0%Z) = tzero)))).
Parameter qbit_one: unit -> matrix t.
Axiom qbit_one_def : forall (us:unit), ((qbit_one us) = (ket 1%Z 1%Z)).
Axiom qbit_one_spec :
forall (us:unit),
(is_a_ket_l (qbit_one us) 1%Z) /\
(((rows (qbit_one us)) = 2%Z) /\
(((columns (qbit_one us)) = 1%Z) /\
(((get (qbit_one us) 0%Z 0%Z) = tzero) /\
((get (qbit_one us) 1%Z 0%Z) = tone)))).
Parameter qbit_plus: unit -> matrix t.
Axiom qbit_plus_def :
forall (us:unit), ((qbit_plus us) = (pat_sem hadamard (qbit_zero tt))).
Axiom qbit_plus_spec :
forall (us:unit),
(is_a_ket_l (qbit_plus us) 1%Z) /\
(((rows (qbit_plus us)) = 2%Z) /\
(((columns (qbit_plus us)) = 1%Z) /\
(((get_ket (qbit_plus us) 0%Z) = (infix_sldt tone squarert_two)) /\
(((get_ket (qbit_plus us) 1%Z) =
(prefix_mndt (infix_sldt tone squarert_two))) /\
((qbit_plus us) =
(infix_asdtdt (infix_sldt tone squarert_two)
(add_mat (ket 0%Z 1%Z) (ket 1%Z 1%Z)))))))).
Parameter qbit_minus: unit -> matrix t.
Axiom qbit_minus_def :
forall (us:unit), ((qbit_minus us) = (pat_sem hadamard (qbit_one tt))).
Axiom qbit_minus_spec :
forall (us:unit),
(is_a_ket_l (qbit_minus us) 1%Z) /\
(((rows (qbit_minus us)) = 2%Z) /\
(((columns (qbit_minus us)) = 1%Z) /\
(((get_ket (qbit_minus us) 0%Z) = (infix_sldt tone squarert_two)) /\
(((get_ket (qbit_minus us) 1%Z) =
(prefix_mndt (infix_sldt tone squarert_two))) /\
((qbit_minus us) =
(infix_asdtdt (infix_sldt tone squarert_two)
(mat_substr (ket 0%Z 1%Z) (ket 1%Z 1%Z)))))))).
Axiom set_equal_qbit :
forall (a:matrix t) (b:matrix t), (is_a_ket_l a 1%Z) ->
(is_a_ket_l b 1%Z) -> ((get_ket a 0%Z) = (get_ket b 0%Z)) ->
((get_ket a 1%Z) = (get_ket b 1%Z)) -> (a = b).
Parameter xor_qbits: (matrix t) -> (matrix t) -> matrix t.
Parameter result30: (matrix t) -> (matrix t) -> Z -> t.
Axiom result_def30 :
forall (x:matrix t) (y:matrix t) (i:Z),
((i = 0%Z) ->
(((result30 x y) i) =
(infix_pldt (infix_asdt (get_ket x 0%Z) (get_ket y 0%Z))
(infix_asdt (get_ket x 1%Z) (get_ket y 1%Z))))) /\
(~ (i = 0%Z) ->
(((result30 x y) i) =
(infix_pldt (infix_asdt (get_ket x 0%Z) (get_ket y 1%Z))
(infix_asdt (get_ket x 1%Z) (get_ket y 0%Z))))).
Axiom xor_qbits_def :
forall (x:matrix t) (y:matrix t), (is_a_ket_l x 1%Z) ->
(is_a_ket_l y 1%Z) -> ((xor_qbits x y) = (make_ket 1%Z (result30 x y))).
Axiom xor_qbits_spec :
forall (x:matrix t) (y:matrix t), (is_a_ket_l x 1%Z) ->
(is_a_ket_l y 1%Z) ->
(is_a_ket_l (xor_qbits x y) 1%Z) /\
(((is_a_ket_basis_elt x) -> (is_a_ket_basis_elt y) ->
((xor_qbits x y) = (ket 1%Z (xor_i (ket_to_int x) (ket_to_int y))))) /\
(((get_ket (xor_qbits x y) 0%Z) =
(infix_pldt (infix_asdt (get_ket x 0%Z) (get_ket y 0%Z))
(infix_asdt (get_ket x 1%Z) (get_ket y 1%Z)))) /\
((get_ket (xor_qbits x y) 1%Z) =
(infix_pldt (infix_asdt (get_ket x 0%Z) (get_ket y 1%Z))
(infix_asdt (get_ket x 1%Z) (get_ket y 0%Z)))))).
Axiom xor_int_to_ket :
forall (x:matrix t) (i:Z), (is_a_ket_l x 1%Z) ->
is_a_ket_l (xor_qbits (ket 1%Z i) x) 1%Z.
Axiom xor_qbit_minus :
forall (i:Z), ((0%Z <= i)%Z /\ (i < 2%Z)%Z) ->
((xor_qbits (ket 1%Z i) (qbit_minus tt)) =
(infix_asdtdt (cpower (prefix_mndt tone) i) (qbit_minus tt))).
Axiom ket_sum_xor_qbit_minus :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> Z),
(forall (e1:a), (mem e1 s) -> (0%Z <= (f e1))%Z /\ ((f e1) < 2%Z)%Z) ->
((ket_sum_l s (fun (e1:a) => (xor_qbits (ket 1%Z (f e1)) (qbit_minus tt)))
1%Z)
=
(ket_sum_l s
(fun (e1:a) =>
(infix_asdtdt (cpower (prefix_mndt tone) (f e1)) (qbit_minus tt)))
1%Z)).
Axiom superposition_xor_qbit_minus :
forall (f:bitvec -> Z) (n:Z),
(forall (e1:bitvec), ((length e1) = n) ->
(0%Z <= (f e1))%Z /\ ((f e1) < 2%Z)%Z) ->
(0%Z <= n)%Z ->
((kronecker
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n)
(fun (x:bitvec) =>
(infix_asdtdt (cpower (prefix_mndt tone) (f x)) (bv_to_ket x)))
n))
(qbit_minus tt))
=
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n)
(fun (e1:bitvec) =>
(kronecker (bv_to_ket e1) (xor_qbits (ket 1%Z (f e1)) (qbit_minus tt))))
(n + 1%Z)%Z))).
Axiom adjoint_scalar :
forall (m:matrix t) (a:t),
((adjoint (infix_asdtdt a m)) = (infix_asdtdt (conjugate a) (adjoint m))).
Axiom adjoint_real_scalar :
forall (m:matrix t) (a:t), (real_ a) ->
((adjoint (infix_asdtdt a m)) = (infix_asdtdt a (adjoint m))).
Axiom adjoint_eq :
forall (m:matrix t) (n:matrix t), (m = n) -> ((adjoint m) = (adjoint n)).
Parameter real_mat: (matrix t) -> Prop.
Axiom real_mat_def :
forall (m:matrix t),
(real_mat m) <->
forall (i:Z) (j:Z), (valid_index m i j) -> real_ (get m i j).
Axiom real_value :
forall (m:matrix t) (i:Z) (j:Z), (real_mat m) -> (valid_index m i j) ->
real_ (get m i j).
Axiom add_adjoint :
forall (m:matrix t) (n:matrix t), ((rows m) = (rows n)) ->
((columns m) = (columns n)) ->
((adjoint (add_mat m n)) = (add_mat (adjoint m) (adjoint n))).
Axiom sum_d_adjoint :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> (forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((mat_sum_d s (fun (e1:a) => (adjoint (f e1))) c r) =
(adjoint (mat_sum_d s f r c))).
Axiom sum_d_adjoint_rev :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (r:Z) (c:Z), (r > 0%Z)%Z ->
(c > 0%Z)%Z -> (forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((adjoint (mat_sum_d s f r c)) =
(mat_sum_d s (fun (e1:a) => (adjoint (f e1))) c r)).
Axiom ketbra_sum_l_adjoint :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:Z), (n >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ketbra_n (f e1) n) ->
((adjoint (ketbra_sum_l s f n)) =
(ketbra_sum_l s (fun (e1:a) => (adjoint (f e1))) n)).
Axiom ket_sum_l_adjoint :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (f:a -> matrix t) (n:Z), (n >= 0%Z)%Z ->
((cardinal s) > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> is_a_ket_l (f e1) n) ->
((adjoint (ket_sum_l s f n)) =
(bra_sum_l s (fun (e1:a) => (adjoint (f e1))) n)).
Axiom sum_d_scal_adjoint :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (scal:a -> t) (f:a -> matrix t) (r:Z) (c:Z),
(r > 0%Z)%Z -> (c > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((mat_sum_d s (fun (e1:a) => (infix_asdtdt (scal e1) (adjoint (f e1)))) c
r)
=
(adjoint
(mat_sum_d s (fun (e1:a) => (infix_asdtdt (conjugate (scal e1)) (f e1)))
r c))).
Axiom sum_d_scal_adjoint_ :
forall {a:Type} {a_WT:WhyType a},
forall (s:set a) (scal:a -> t) (f:a -> matrix t) (r:Z) (c:Z),
(r > 0%Z)%Z -> (c > 0%Z)%Z ->
(forall (e1:a), (mem e1 s) -> ((rows (f e1)) = r)) ->
(forall (e1:a), (mem e1 s) -> ((columns (f e1)) = c)) ->
((mat_sum_d s
(fun (e1:a) => (infix_asdtdt (conjugate (scal e1)) (adjoint (f e1)))) c
r)
=
(adjoint
(mat_sum_d s (fun (e1:a) => (infix_asdtdt (scal e1) (f e1))) r c))).
Axiom mat_mult_adjoint :
forall (m:matrix t) (n:matrix t), ((columns n) = (rows m)) ->
((mat_mult (adjoint m) (adjoint n)) = (adjoint (mat_mult n m))).
Axiom kronecker_adjoint :
forall (m:matrix t) (n:matrix t),
((kronecker (adjoint m) (adjoint n)) = (adjoint (kronecker m n))).
Axiom had_adjoint : ((adjoint (mat_sem hadamard)) = (mat_sem hadamard)).
Axiom projector_transformation :
forall (a:matrix t) (k:matrix t) (l:Z), (l >= 0%Z)%Z -> (is_a_ket_l k l) ->
(is_a_ketbra_n a l) ->
((projection (mat_mult a k)) =
(mat_mult a (mat_mult (projection k) (adjoint a)))).
Axiom prod_own_adjoint :
forall (m:matrix t), ((mat_mult m (adjoint m)) = (id_mat (rows m))).
Axiom sum_ket_zero :
forall (n:Z), (n >= 0%Z)%Z -> forall (y:bitvec),
((ang_sum
(fun (i:Z) =>
(int_to_ang (((getbv (ket_to_bv (ket n 0%Z))) i) * ((getbv y) i))%Z 1%Z))
0%Z n)
= ang_zero).
Parameter repeat_had: Z -> circuit.
Axiom repeat_had_def :
forall (n:Z), (n >= 1%Z)%Z ->
((n = 1%Z) -> ((repeat_had n) = hadamard)) /\
(~ (n = 1%Z) ->
((repeat_had n) = (parallel (repeat_had (n - 1%Z)%Z) hadamard))).
Axiom repeat_had_spec :
forall (n:Z), (n >= 1%Z)%Z ->
((width (repeat_had n)) = n) /\
(((ancillas (repeat_had n)) = 0%Z) /\
(((size (repeat_had n)) = n) /\
(((range (repeat_had n)) = n) /\
(((adjoint (mat_sem (repeat_had n))) = (mat_sem (repeat_had n))) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = n) ->
((length y) = n) -> ((0%Z <= i)%Z /\ (i < n)%Z) ->
((basis_ket_i (repeat_had n) x y i) = ((getbv y) i))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = n) -> ((basis_ket (repeat_had n) x y) = y)) /\
(((ang_ind_bound (repeat_had n)) = n) /\
((forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = n) ->
((length y) = n) -> ((0%Z <= i)%Z /\ (i < n)%Z) ->
((ang_ind_i (repeat_had n) x y i) =
(int_to_ang (((getbv x) i) * ((getbv y) i))%Z 1%Z))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = n) ->
((ang_ind (repeat_had n) x y) =
(ang_sum
(fun (i:Z) =>
(int_to_ang (((getbv x) i) * ((getbv y) i))%Z 1%Z))
0%Z n))) /\
((sem (repeat_had n) (ket n 0%Z)
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n) (fun (y0:bitvec) => (bv_to_ket y0)) n))) /\
((ang_ind_bound (repeat_had n)) = n))))))))))).
Axiom ket_sum_bv_to_ints1 :
forall (n:Z) (f:bitvec -> matrix t) (g:Z -> matrix t), (n >= 0%Z)%Z ->
(forall (x:bitvec), ((length x) = n) -> ((f x) = (g (bv_to_int x)))) ->
((ket_sum_l (n_bvs n) f n) = (ket_sum_l (to_fset 0%Z (power 2%Z n)) g n)).
Parameter superposition_state: Z -> matrix t.
Axiom superposition_state_def :
forall (n:Z), (n >= 1%Z)%Z ->
((superposition_state n) = (pat_sem (repeat_had n) (ket n 0%Z))).
Axiom superposition_state_spec :
forall (n:Z), (n >= 1%Z)%Z ->
((superposition_state n) = (mat_mult (mat_sem (repeat_had n)) (ket n 0%Z))) /\
(((superposition_state n) =
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n) (fun (y0:bitvec) => (bv_to_ket y0)) n))) /\
(((superposition_state n) =
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (to_fset 0%Z (power 2%Z n))
((fun (y0:Z) (y1:Z) => (ket y0 y1)) n) n))) /\
(is_a_ket_l (superposition_state n) n))).
Axiom repeat_had_hops :
forall (n:Z), (n >= 1%Z)%Z ->
((width (repeat_had n)) = n) /\
(((range (repeat_had n)) = n) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) -> ((length y) = n) ->
((basis_ket (repeat_had n) x y) = y)) /\
forall (x:bitvec) (y:bitvec), ((length x) = n) -> ((length y) = n) ->
((ang_ind (repeat_had n) x y) =
(int_to_ang
(ind_isum (fun (i:Z) => (((getbv x) i) * ((getbv y) i))%Z) 0%Z n) 1%Z)))).
Axiom repeat_had_basis :
forall (n:Z) (x:matrix t), (n >= 1%Z)%Z -> (is_a_ket_basis_elt x) ->
((ket_length x) = n) ->
sem (repeat_had n) x
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n)
(fun (y:bitvec) =>
(infix_asdtdt
(cpower (prefix_mndt tone)
(ind_isum (fun (i:Z) => (((getbv (ket_to_bv x)) i) * ((getbv y) i))%Z)
0%Z n))
(bv_to_ket y)))
n)).
Axiom repeat_had_bv :
forall (n:Z) (x:bitvec), (n >= 1%Z)%Z -> ((length x) = n) ->
sem (repeat_had n) (bv_to_ket x)
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n)
(fun (y:bitvec) =>
(infix_asdtdt
(cpower (prefix_mndt tone)
(ind_isum (fun (i:Z) => (((getbv x) i) * ((getbv y) i))%Z) 0%Z n))
(bv_to_ket y)))
n)).
Axiom repeat_had_bv_gen :
forall (n:Z), (n >= 1%Z)%Z -> forall (x:bitvec), ((length x) = n) ->
sem (repeat_had n) (bv_to_ket x)
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n)
(fun (y:bitvec) =>
(infix_asdtdt
(cpower (prefix_mndt tone)
(ind_isum (fun (i:Z) => (((getbv x) i) * ((getbv y) i))%Z) 0%Z n))
(bv_to_ket y)))
n)).
Axiom repeat_had_superposition :
forall (f:bitvec -> t) (n:Z), (n >= 1%Z)%Z ->
sem (repeat_had n)
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n)
(fun (k:bitvec) => (infix_asdtdt (f k) (bv_to_ket k))) n))
(infix_asdtdt (pow_inv_2 n)
(ket_sum_l (n_bvs n)
(fun (x:bitvec) =>
(infix_asdtdt (f x)
(ket_sum_l (n_bvs n)
(fun (y:bitvec) =>
(infix_asdtdt
(cpower (prefix_mndt tone)
(ind_isum (fun (i:Z) => (((getbv x) i) * ((getbv y) i))%Z) 0%Z n))
(bv_to_ket y)))
n)))
n)).
Axiom ket_sum_power_minus_one :
forall (f:bitvec -> Z) (g:bitvec -> bitvec -> Z) (n:Z), (n >= 0%Z)%Z ->
((ket_sum_l (n_bvs n)
(fun (x:bitvec) =>
(infix_asdtdt (cpower (prefix_mndt tone) (f x))
(ket_sum_l (n_bvs n)
(fun (y:bitvec) =>
(infix_asdtdt (cpower (prefix_mndt tone) ((g x) y)) (bv_to_ket y)))
n)))
n)
=
(ket_sum_l (n_bvs n)
(fun (y:bitvec) =>
(infix_asdtdt
(sum (n_bvs n)
(fun (x:bitvec) => (cpower (prefix_mndt tone) (((g x) y) + (f x))%Z)))
(bv_to_ket y)))
n)).
Parameter c_rzp_zh_: Z -> Z -> Z -> Z -> circuit.
Axiom c_rzp_zh__def :
forall (k:Z) (co:Z) (t1:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
~ (t1 = co) -> ((c_rzp_zh_ k co t1 n) = (c_rzp k co t1 n)).
Axiom c_rzp_zh__spec :
forall (k:Z) (co:Z) (t1:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
~ (t1 = co) ->
((ancillas (c_rzp_zh_ k co t1 n)) = 0%Z) /\
((size (c_rzp_zh_ k co t1 n)) <= (cont_size * 2%Z)%Z)%Z.
Parameter had_zh_: Z -> Z -> circuit.
Axiom had_zh__def :
forall (t1:Z) (n:Z), (n >= 0%Z)%Z -> ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
((had_zh_ t1 n) = (place hadamard t1 n)).
Axiom had_zh__spec :
forall (t1:Z) (n:Z), (n >= 0%Z)%Z -> ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
((width (had_zh_ t1 n)) = n) /\
(((size (had_zh_ t1 n)) = 1%Z) /\ ((ancillas (had_zh_ t1 n)) = 0%Z)).
Parameter cont_zh: circuit -> Prop.
Axiom zh_had :
forall (t1:Z) (n:Z), (n >= 0%Z)%Z -> ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
cont_zh (had_zh_ t1 n).
Axiom zh_cont_rzp :
forall (k:Z) (co:Z) (ft:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= ft)%Z /\ (ft < n)%Z) ->
~ (ft = co) -> cont_zh (c_rzp_zh_ k co ft n).
Axiom seq_pres_zh :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((width d) = (width e1)) -> cont_zh (sequence d e1).
Axiom par_pres_zh :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((width d) = (width e1)) -> cont_zh (parallel d e1).
Parameter zh_range: circuit -> Z.
Axiom zh_range_spec :
forall (g:circuit), (cont_zh g) -> ((zh_range g) >= 0%Z)%Z.
Axiom had_zh_range :
forall (t1:Z) (n:Z), ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
((zh_range (had_zh_ t1 n)) = 1%Z).
Axiom cont_zh_range :
forall (k:Z) (co:Z) (ft:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= ft)%Z /\ (ft < n)%Z) ->
~ (ft = co) -> ((zh_range (c_rzp_zh_ k co ft n)) = 0%Z).
Axiom seq_zh_range :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((width d) = (width e1)) ->
((zh_range (sequence d e1)) = ((zh_range d) + (zh_range e1))%Z).
Axiom par_zh_range :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((zh_range (parallel d e1)) = ((zh_range d) + (zh_range e1))%Z).
Axiom zh_range_eq :
forall (g:circuit) (g':circuit), (g = g') -> ((zh_range g) = (zh_range g')).
Parameter zh_ket: circuit -> bitvec -> bitvec -> bitvec.
Axiom zh_ket_spec :
forall (c:circuit) (x:bitvec) (y:bitvec), (cont_zh c) -> forall (n:Z),
(n = (width c)) -> ((length x) = (width c)) ->
((length y) = (zh_range c)) -> ((length (zh_ket c x y)) = n).
Parameter fc22: Z -> bitvec -> bitvec -> Z -> Z.
Axiom fc_def22 :
forall (t1:Z) (x:bitvec) (y:bitvec) (i:Z),
((i = t1) -> (((fc22 t1 x y) i) = ((getbv y) 0%Z))) /\
(~ (i = t1) -> (((fc22 t1 x y) i) = ((getbv x) i))).
Axiom had_zh_ket :
forall (t1:Z) (n:Z), ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
forall (x:bitvec) (y:bitvec), ((length x) = n) -> ((length y) = 1%Z) ->
((zh_ket (had_zh_ t1 n) x y) = (make_bv (fc22 t1 x y) n)).
Axiom cont_zh_ket :
forall (k:Z) (co:Z) (ft:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= ft)%Z /\ (ft < n)%Z) ->
~ (ft = co) -> forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) -> ((zh_ket (c_rzp_zh_ k co ft n) x y) = x).
Axiom seq_zh_ket :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((width d) = (width e1)) -> forall (x:bitvec) (y:bitvec),
((length x) = (width d)) ->
((length y) = ((zh_range d) + (zh_range e1))%Z) ->
((zh_ket (sequence d e1) x y) =
(zh_ket e1 (zh_ket d x (hpart y (zh_range d))) (tpart y (zh_range d)))).
Axiom par_zh_ket :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((width d) = (width e1)) -> forall (x:bitvec) (y:bitvec),
((length x) = ((width d) + (width e1))%Z) ->
((length y) = ((zh_range d) + (zh_range e1))%Z) ->
((zh_ket (parallel d e1) x y) =
(concat (zh_ket d (hpart x (width d)) (hpart y (zh_range d)))
(zh_ket e1 (tpart x (width d)) (tpart y (zh_range d))))).
Axiom zh_ket_eq :
forall (g:circuit) (g':circuit) (x:bitvec) (x':bitvec) (y:bitvec)
(y':bitvec),
(g = g') -> ((length x) = (width g)) -> (x = x') ->
((length y) = (zh_range g)) -> (y = y') ->
((zh_ket g x y) = (zh_ket g' x' y')).
Axiom zh_ket_eq_bv :
forall (g:circuit) (g':circuit) (x:bitvec) (x':bitvec) (y:bitvec)
(y':bitvec),
(g = g') -> (((length x) = (length x')) /\ ((length x') = (width g))) ->
(((length y) = (length y')) /\ ((length y') = (zh_range g))) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (length x))%Z) ->
(((getbv x) i) = ((getbv x') i))) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (length y))%Z) ->
(((getbv y) i) = ((getbv y') i))) ->
((zh_ket g x y) = (zh_ket g' x' y')).
Parameter zh_ket_i: circuit -> bitvec -> bitvec -> Z -> Z.
Axiom zh_ket_i_def :
forall (c:circuit) (x:bitvec) (y:bitvec) (i:Z), (cont_zh c) ->
((zh_ket_i c x y i) = ((getbv (zh_ket c x y)) i)).
Axiom zh_ket_i_spec :
forall (c:circuit) (x:bitvec) (y:bitvec) (i:Z), (cont_zh c) ->
((length x) = (width c)) -> ((length y) = (zh_range c)) ->
((0%Z <= i)%Z /\ (i < (width c))%Z) ->
(0%Z <= (zh_ket_i c x y i))%Z /\ ((zh_ket_i c x y i) < 2%Z)%Z.
Axiom zh_ket_value :
forall (g:circuit) (x:bitvec) (y:bitvec) (i:Z) (j:Z), (cont_zh g) ->
((length x) = (width g)) -> ((length y) = (zh_range g)) ->
((0%Z <= i)%Z /\ (i < (width g))%Z) -> ((zh_ket_i g x y i) = j) ->
(((getbv (zh_ket g x y)) i) = j).
Axiom had_zh_ket_i :
forall (t1:Z) (n:Z), ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
forall (x:bitvec) (y:bitvec), ((length x) = n) -> ((length y) = 1%Z) ->
((zh_ket_i (had_zh_ t1 n) x y t1) = ((getbv y) 0%Z)).
Axiom had_zh_ket_i' :
forall (t1:Z) (n:Z), ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
forall (x:bitvec) (y:bitvec), ((length x) = n) -> ((length y) = 1%Z) ->
forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) -> ~ (i = t1) ->
((zh_ket_i (had_zh_ t1 n) x y i) = ((getbv x) i)).
Axiom cont_zh_ket_i :
forall (k:Z) (co:Z) (ft:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= ft)%Z /\ (ft < n)%Z) ->
~ (ft = co) -> forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) -> forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) ->
((zh_ket_i (c_rzp_zh_ k co ft n) x y i) = ((getbv x) i)).
Axiom seq_zh_ket_i :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((width d) = (width e1)) -> forall (x:bitvec) (y:bitvec),
((length x) = (width d)) ->
((length y) = ((zh_range d) + (zh_range e1))%Z) -> forall (i:Z),
((0%Z <= i)%Z /\ (i < (width d))%Z) ->
((zh_ket_i (sequence d e1) x y i) =
(zh_ket_i e1 (zh_ket d x (hpart y (zh_range d))) (tpart y (zh_range d)) i)).
Axiom par_zh_ket_i :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((width d) = (width e1)) -> forall (x:bitvec) (y:bitvec),
((length x) = ((width d) + (width e1))%Z) ->
((length y) = ((zh_range d) + (zh_range e1))%Z) -> forall (i:Z),
((0%Z <= i)%Z /\ (i < (width d))%Z) ->
((zh_ket_i (parallel d e1) x y i) =
(zh_ket_i d (hpart x (width d)) (hpart y (zh_range d)) i)).
Axiom par_zh_ket_i' :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((width d) = (width e1)) -> forall (x:bitvec) (y:bitvec),
((length x) = ((width d) + (width e1))%Z) ->
((length y) = ((zh_range d) + (zh_range e1))%Z) -> forall (i:Z),
(((width d) <= i)%Z /\ (i < ((width d) + (width e1))%Z)%Z) ->
((zh_ket_i (parallel d e1) x y i) =
(zh_ket_i e1 (tpart x (width d)) (tpart y (zh_range d)) (i - (width d))%Z)).
Axiom zh_ket_i_eq :
forall (g:circuit) (g':circuit) (x:bitvec) (x':bitvec) (y:bitvec)
(y':bitvec) (i:Z) (i':Z),
(g = g') -> ((length x) = (width g)) -> (x = x') ->
((length y) = (zh_range g)) -> (y = y') -> (i = i') ->
((0%Z <= i)%Z /\ (i < (width g))%Z) ->
((zh_ket_i g x y i) = (zh_ket_i g' x' y' i')).
Axiom zh_ket_i_eq_bv :
forall (g:circuit) (g':circuit) (x:bitvec) (x':bitvec) (y:bitvec)
(y':bitvec) (i:Z) (i':Z),
(g = g') -> (((length x) = (length x')) /\ ((length x') = (width g))) ->
(((length y) = (length y')) /\ ((length y') = (zh_range g))) ->
(forall (j:Z), ((0%Z <= j)%Z /\ (j < (length x))%Z) ->
(((getbv x) j) = ((getbv x') j))) ->
(forall (j:Z), ((0%Z <= j)%Z /\ (j < (length y))%Z) ->
(((getbv y) j) = ((getbv y') j))) ->
(i = i') -> ((0%Z <= i)%Z /\ (i < (width g))%Z) ->
((zh_ket_i g x y i) = (zh_ket_i g' x' y' i')).
Parameter zh_ang_coeff: circuit -> bitvec -> bitvec -> Z.
Axiom had_zh_ang_coeff :
forall (t1:Z) (n:Z), ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
forall (x:bitvec) (y:bitvec), ((length x) = n) -> ((length y) = 1%Z) ->
((zh_ang_coeff (had_zh_ t1 n) x y) =
((((getbv x) t1) * ((getbv y) 0%Z))%Z * (power_ 2%Z (n - 1%Z)%Z))%Z).
Axiom cont_zh_ang_coeff :
forall (k:Z) (co:Z) (ft:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= ft)%Z /\ (ft < n)%Z) ->
~ (ft = co) -> (0%Z <= k)%Z -> forall (x:bitvec) (y:bitvec),
((length x) = n) -> ((length y) = 0%Z) ->
((zh_ang_coeff (c_rzp_zh_ k co ft n) x y) =
((((getbv x) ft) * ((getbv x) co))%Z * (power_ 2%Z (n - k)%Z))%Z).
Axiom seq_zh_ang_coeff :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((width d) = (width e1)) -> forall (x:bitvec) (y:bitvec),
((length x) = (width d)) ->
((length y) = ((zh_range d) + (zh_range e1))%Z) ->
((zh_ang_coeff (sequence d e1) x y) =
((zh_ang_coeff d x (hpart y (zh_range d))) +
(zh_ang_coeff e1 (zh_ket d x (hpart y (zh_range d)))
(tpart y (zh_range d))))%Z).
Axiom par_zh_ang_coeff :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((width d) = (width e1)) -> forall (x:bitvec) (y:bitvec),
((length x) = ((width d) + (width e1))%Z) ->
((length y) = ((zh_range d) + (zh_range e1))%Z) ->
((zh_ang_coeff (parallel d e1) x y) =
((zh_ang_coeff d (hpart x (width d)) (hpart y (zh_range d))) +
(zh_ang_coeff e1 (tpart x (width d)) (tpart y (zh_range d))))%Z).
Axiom zh_ang_coeff_eq :
forall (g:circuit) (g':circuit) (x:bitvec) (x':bitvec) (y:bitvec)
(y':bitvec),
(g = g') -> ((length x) = (width g)) -> (x = x') ->
((length y) = (zh_range g)) -> (y = y') ->
((zh_ang_coeff g x y) = (zh_ang_coeff g' x' y')).
Axiom zh_ang_coeff_eq_bv :
forall (g:circuit) (g':circuit) (x:bitvec) (x':bitvec) (y:bitvec)
(y':bitvec),
(g = g') -> (((length x) = (length x')) /\ ((length x') = (width g))) ->
(((length y) = (length y')) /\ ((length y') = (zh_range g))) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (length x))%Z) ->
(((getbv x) i) = ((getbv x') i))) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (length y))%Z) ->
(((getbv y) i) = ((getbv y') i))) ->
((zh_ang_coeff g x y) = (zh_ang_coeff g' x' y')).
Parameter zh_ang_coeff_neg: circuit -> bitvec -> bitvec -> Z.
Axiom had_zh_ang_coeff_neg :
forall (t1:Z) (n:Z), ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
forall (x:bitvec) (y:bitvec), ((length x) = n) -> ((length y) = 1%Z) ->
((zh_ang_coeff_neg (had_zh_ t1 n) x y) =
((((getbv x) t1) * ((getbv y) 0%Z))%Z * (power_ 2%Z (n - 1%Z)%Z))%Z).
Axiom cont_zh_ang_coeff_neg :
forall (k:Z) (co:Z) (ft:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= ft)%Z /\ (ft < n)%Z) ->
~ (ft = co) -> forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) -> (k <= 0%Z)%Z ->
((zh_ang_coeff_neg (c_rzp_zh_ k co ft n) x y) =
((((getbv x) ft) * ((getbv x) co))%Z * (power_ 2%Z (n + k)%Z))%Z).
Axiom seq_zh_ang_coeff_neg :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((width d) = (width e1)) -> forall (x:bitvec) (y:bitvec),
((length x) = (width d)) ->
((length y) = ((zh_range d) + (zh_range e1))%Z) ->
((zh_ang_coeff_neg (sequence d e1) x y) =
((zh_ang_coeff_neg d x (hpart y (zh_range d))) +
(zh_ang_coeff_neg e1 (zh_ket d x (hpart y (zh_range d)))
(tpart y (zh_range d))))%Z).
Axiom par_zh_ang_coeff_neg :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((width d) = (width e1)) -> forall (x:bitvec) (y:bitvec),
((length x) = ((width d) + (width e1))%Z) ->
((length y) = ((zh_range d) + (zh_range e1))%Z) ->
((zh_ang_coeff_neg (parallel d e1) x y) =
((zh_ang_coeff_neg d (hpart x (width d)) (hpart y (zh_range d))) +
(zh_ang_coeff_neg e1 (tpart x (width d)) (tpart y (zh_range d))))%Z).
Axiom zh_ang_coeff_neg_eq :
forall (g:circuit) (g':circuit) (x:bitvec) (x':bitvec) (y:bitvec)
(y':bitvec),
(g = g') -> ((length x) = (width g)) -> (x = x') ->
((length y) = (zh_range g)) -> (y = y') ->
((zh_ang_coeff_neg g x y) = (zh_ang_coeff_neg g' x' y')).
Axiom zh_ang_coeff_neg_eq_bv :
forall (g:circuit) (g':circuit) (x:bitvec) (x':bitvec) (y:bitvec)
(y':bitvec),
(g = g') -> (((length x) = (length x')) /\ ((length x') = (width g))) ->
(((length y) = (length y')) /\ ((length y') = (zh_range g))) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (length x))%Z) ->
(((getbv x) i) = ((getbv x') i))) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (length y))%Z) ->
(((getbv y) i) = ((getbv y') i))) ->
((zh_ang_coeff_neg g x y) = (zh_ang_coeff_neg g' x' y')).
Parameter zh_ang: circuit -> bitvec -> bitvec -> angle.
Axiom had_zh_ang :
forall (t1:Z) (n:Z), ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
forall (x:bitvec) (y:bitvec), ((length x) = n) -> ((length y) = 1%Z) ->
((zh_ang (had_zh_ t1 n) x y) =
(int_to_ang (((getbv x) t1) * ((getbv y) 0%Z))%Z 1%Z)).
Axiom cont_zh_ang :
forall (k:Z) (co:Z) (ft:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= ft)%Z /\ (ft < n)%Z) ->
~ (ft = co) -> (0%Z <= k)%Z -> forall (x:bitvec) (y:bitvec),
((length x) = n) -> ((length y) = 0%Z) ->
((zh_ang (c_rzp_zh_ k co ft n) x y) =
(int_to_ang (((getbv x) ft) * ((getbv x) co))%Z k)).
Axiom cont_zh_ang_n :
forall (k:Z) (co:Z) (ft:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= ft)%Z /\ (ft < n)%Z) ->
~ (ft = co) -> (k <= 0%Z)%Z -> forall (x:bitvec) (y:bitvec),
((length x) = n) -> ((length y) = 0%Z) ->
((zh_ang (c_rzp_zh_ k co ft n) x y) =
(int_to_ang (-(((getbv x) ft) * ((getbv x) co))%Z)%Z (-k)%Z)).
Axiom seq_zh_ang :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((width d) = (width e1)) -> forall (x:bitvec) (y:bitvec),
((length x) = (width d)) ->
((length y) = ((zh_range d) + (zh_range e1))%Z) ->
((zh_ang (sequence d e1) x y) =
(ang_add (zh_ang d x (hpart y (zh_range d)))
(zh_ang e1 (zh_ket d x (hpart y (zh_range d))) (tpart y (zh_range d))))).
Axiom par_zh_ang :
forall (d:circuit) (e1:circuit), (cont_zh d) -> (cont_zh e1) ->
((width d) = (width e1)) -> forall (x:bitvec) (y:bitvec),
((length x) = 1%Z) -> ((length y) = 1%Z) ->
((zh_ang (parallel d e1) x y) =
(ang_add (zh_ang d (hpart x (width d)) (hpart y (zh_range d)))
(zh_ang e1 (tpart x (width d)) (tpart y (zh_range d))))).
Axiom zh_ang_from_coeff :
forall (g:circuit), (cont_zh g) -> forall (x:bitvec) (y:bitvec),
((length x) = (width g)) -> ((length y) = (zh_range g)) ->
((zh_ang g x y) = (int_to_ang (zh_ang_coeff g x y) (width g))).
Axiom zh_ang_from_coeff_neg :
forall (g:circuit), (cont_zh g) -> forall (x:bitvec) (y:bitvec),
((length x) = (width g)) -> ((length y) = (zh_range g)) ->
((zh_ang g x y) = (int_to_ang (-(zh_ang_coeff_neg g x y))%Z (width g))).
Axiom zh_ket_from_i :
forall (g:circuit), (cont_zh g) -> forall (x:bitvec) (y:bitvec),
((length x) = (width g)) -> ((length y) = (zh_range g)) ->
((zh_ket g x y) =
(make_bv
((((fun (y0:circuit) (y1:bitvec) (y2:bitvec) (y3:Z) =>
(zh_ket_i y0 y1 y2 y3))
g)
x)
y)
(width g))).
Axiom zh_ang_eq :
forall (g:circuit) (g':circuit) (x:bitvec) (x':bitvec) (y:bitvec)
(y':bitvec),
(g = g') -> ((length x) = (width g)) -> (x = x') ->
((length y) = (zh_range g)) -> (y = y') ->
((zh_ang g x y) = (zh_ang g' x' y')).
Axiom zh_ang_eq_bv :
forall (g:circuit) (g':circuit) (x:bitvec) (x':bitvec) (y:bitvec)
(y':bitvec),
(g = g') -> (((length x) = (length x')) /\ ((length x') = (width g))) ->
(((length y) = (length y')) /\ ((length y') = (zh_range g))) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (length x))%Z) ->
(((getbv x) i) = ((getbv x') i))) ->
(forall (i:Z), ((0%Z <= i)%Z /\ (i < (length y))%Z) ->
(((getbv y) i) = ((getbv y') i))) ->
((zh_ang g x y) = (zh_ang g' x' y')).
Axiom get_zh_ang :
forall (g:circuit) (x:bitvec) (y:bitvec) (k:Z) (n:Z), (cont_zh g) ->
(n = (width g)) -> ((length x) = (width g)) ->
((length y) = (zh_range g)) -> ((zh_ang_coeff g x y) = k) ->
((zh_ang g x y) = (int_to_ang k n)).
Axiom get_zh_ang_by_neg :
forall (g:circuit) (x:bitvec) (y:bitvec) (k:Z) (n:Z), (cont_zh g) ->
(n = (width g)) -> ((length x) = (width g)) ->
((length y) = (zh_range g)) ->
((int_to_ang (zh_ang_coeff_neg g x y) n) = (int_to_ang k n)) ->
((zh_ang g x y) = (int_to_ang (-k)%Z n)).
Axiom get_zh_ang_by :
forall (g:circuit) (x:bitvec) (y:bitvec) (k:Z) (n:Z), (cont_zh g) ->
(n = (width g)) -> ((length x) = (width g)) ->
((length y) = (zh_range g)) ->
((int_to_ang (zh_ang_coeff g x y) n) = (int_to_ang k n)) ->
((zh_ang g x y) = (int_to_ang k n)).
Axiom get_zh_ket_i :
forall (g:circuit) (x:bitvec) (y:bitvec) (i:Z), (cont_zh g) ->
((length x) = (width g)) -> ((length y) = (zh_range g)) ->
((0%Z <= i)%Z /\ (i < (width g))%Z) ->
((zh_ket_i g x y i) = ((getbv (zh_ket g x y)) i)).
Axiom get_bv_zh_ket :
forall (g:circuit) (x:bitvec) (y:bitvec) (i:Z), (cont_zh g) ->
((length x) = (width g)) -> ((length y) = (zh_range g)) ->
((0%Z <= i)%Z /\ (i < (width g))%Z) ->
(((getbv (zh_ket g x y)) i) = (zh_ket_i g x y i)).
Parameter c_rzp_zh: Z -> Z -> Z -> Z -> circuit.
Axiom c_rzp_zh_def :
forall (k:Z) (co:Z) (t1:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
~ (t1 = co) -> ((c_rzp_zh k co t1 n) = (c_rzp k co t1 n)).
Axiom c_rzp_zh_spec :
forall (k:Z) (co:Z) (t1:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= co)%Z /\ (co < n)%Z) -> ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
~ (t1 = co) ->
((c_rzp_zh k co t1 n) = (c_rzp_zh_ k co t1 n)) /\
((cont_zh (c_rzp_zh k co t1 n)) /\
(((ancillas (c_rzp_zh k co t1 n)) = 0%Z) /\
(((size (c_rzp_zh k co t1 n)) <= (cont_size * 2%Z)%Z)%Z /\
(((width (c_rzp_zh k co t1 n)) = n) /\
(((zh_range (c_rzp_zh k co t1 n)) = 0%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) -> ((zh_ket (c_rzp_zh k co t1 n) x y) = x)) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) -> forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) ->
((zh_ket_i (c_rzp_zh k co t1 n) x y i) = ((getbv x) i))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) -> (0%Z <= k)%Z ->
((zh_ang (c_rzp_zh k co t1 n) x y) =
(int_to_ang (((getbv x) t1) * ((getbv x) co))%Z k))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) -> (k <= 0%Z)%Z ->
((zh_ang (c_rzp_zh k co t1 n) x y) =
(int_to_ang (-(((getbv x) t1) * ((getbv x) co))%Z)%Z (-k)%Z))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) -> (0%Z <= k)%Z ->
((zh_ang_coeff (c_rzp_zh k co t1 n) x y) =
((((getbv x) t1) * ((getbv x) co))%Z *
(power_ 2%Z (n - k)%Z))%Z)) /\
forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) -> (k <= 0%Z)%Z ->
((zh_ang_coeff_neg (c_rzp_zh k co t1 n) x y) =
((((getbv x) t1) * ((getbv x) co))%Z * (power_ 2%Z (n + k)%Z))%Z))))))))))).
Parameter had_zh: Z -> Z -> circuit.
Axiom had_zh_def :
forall (t1:Z) (n:Z), (n >= 0%Z)%Z -> ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
((had_zh t1 n) = (place hadamard t1 n)).
Parameter fc23: Z -> bitvec -> bitvec -> Z -> Z.
Axiom fc_def23 :
forall (t1:Z) (x:bitvec) (y:bitvec) (i:Z),
((i = t1) -> (((fc23 t1 x y) i) = ((getbv y) 0%Z))) /\
(~ (i = t1) -> (((fc23 t1 x y) i) = ((getbv x) i))).
Axiom had_zh_spec :
forall (t1:Z) (n:Z), (n >= 0%Z)%Z -> ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
((had_zh t1 n) = (had_zh_ t1 n)) /\
((cont_zh (had_zh t1 n)) /\
(((size (had_zh t1 n)) = 1%Z) /\
(((ancillas (had_zh t1 n)) = 0%Z) /\
(((width (had_zh t1 n)) = n) /\
(((zh_range (had_zh t1 n)) = 1%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 1%Z) ->
((zh_ket_i (had_zh t1 n) x y t1) = ((getbv y) 0%Z))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 1%Z) -> forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) ->
~ (i = t1) -> ((zh_ket_i (had_zh t1 n) x y i) = ((getbv x) i))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 1%Z) ->
((zh_ket (had_zh t1 n) x y) = (make_bv (fc23 t1 x y) n))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 1%Z) ->
((zh_ang_coeff (had_zh t1 n) x y) =
((((getbv x) t1) * ((getbv y) 0%Z))%Z *
(power_ 2%Z (n - 1%Z)%Z))%Z)) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 1%Z) ->
((zh_ang_coeff_neg (had_zh t1 n) x y) =
((((getbv x) t1) * ((getbv y) 0%Z))%Z *
(power_ 2%Z (n - 1%Z)%Z))%Z)) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 1%Z) ->
((zh_ang (had_zh t1 n) x y) =
(int_to_ang (((getbv x) t1) * ((getbv y) 0%Z))%Z 1%Z))) /\
((forall (k:Z) (j:Z) (a:Z) (b:Z), (0%Z < k)%Z ->
(j = (k - 1%Z)%Z) -> forall (x:bitvec) (y:bitvec),
((length x) = n) -> ((length y) = 1%Z) ->
(a = ((getbv x) t1)) -> (b = ((getbv y) 0%Z)) ->
((zh_ang (had_zh t1 n) x y) =
(int_to_ang ((a * b)%Z * (power_ 2%Z j))%Z k))) /\
forall (k:Z) (j:Z) (a:Z) (b:Z), (0%Z < k)%Z ->
(j = (k - 1%Z)%Z) -> forall (x:bitvec) (y:bitvec),
((length x) = n) -> ((length y) = 1%Z) ->
(a = ((getbv x) t1)) -> (b = ((getbv y) 0%Z)) ->
((zh_ang (had_zh t1 n) x y) =
(int_to_ang (-((a * b)%Z * (power_ 2%Z j))%Z)%Z k)))))))))))))).
Parameter sequence_zh: circuit -> circuit -> circuit.
Axiom sequence_zh_def :
forall (d:circuit) (e1:circuit), ((width d) = (width e1)) -> (cont_zh d) ->
(cont_zh e1) -> ((sequence_zh d e1) = (sequence d e1)).
Axiom sequence_zh_spec :
forall (d:circuit) (e1:circuit), ((width d) = (width e1)) -> (cont_zh d) ->
(cont_zh e1) ->
(cont_zh (sequence_zh d e1)) /\
(((ancillas (sequence_zh d e1)) =
(ZArith.BinInt.Z.max (ancillas d) (ancillas e1))) /\
(((size (sequence_zh d e1)) = ((size d) + (size e1))%Z) /\
(((width (sequence_zh d e1)) = (width d)) /\
(((zh_range (sequence_zh d e1)) = ((zh_range d) + (zh_range e1))%Z) /\
((forall (x:bitvec) (y:bitvec),
((length x) = (width (sequence_zh d e1))) ->
((length y) = (zh_range (sequence_zh d e1))) -> forall (i:Z),
((0%Z <= i)%Z /\ (i < (width d))%Z) ->
((zh_ket_i (sequence_zh d e1) x y i) =
(zh_ket_i e1 (zh_ket d x (hpart y (zh_range d)))
(tpart y (zh_range d)) i))) /\
((forall (x:bitvec) (y:bitvec),
((length x) = (width (sequence_zh d e1))) ->
((length y) = (zh_range (sequence_zh d e1))) ->
((zh_ket (sequence_zh d e1) x y) =
(zh_ket e1 (zh_ket d x (hpart y (zh_range d)))
(tpart y (zh_range d))))) /\
((forall (x:bitvec) (y:bitvec),
((length x) = (width (sequence_zh d e1))) ->
((length y) = (zh_range (sequence_zh d e1))) ->
((zh_ang_coeff (sequence_zh d e1) x y) =
((zh_ang_coeff d x (hpart y (zh_range d))) +
(zh_ang_coeff e1 (zh_ket d x (hpart y (zh_range d)))
(tpart y (zh_range d))))%Z)) /\
((forall (x:bitvec) (y:bitvec),
((length x) = (width (sequence_zh d e1))) ->
((length y) = (zh_range (sequence_zh d e1))) ->
((zh_ang_coeff_neg (sequence_zh d e1) x y) =
((zh_ang_coeff_neg d x (hpart y (zh_range d))) +
(zh_ang_coeff_neg e1 (zh_ket d x (hpart y (zh_range d)))
(tpart y (zh_range d))))%Z)) /\
forall (x:bitvec) (y:bitvec),
((length x) = (width (sequence_zh d e1))) ->
((length y) = (zh_range (sequence_zh d e1))) ->
((zh_ang (sequence_zh d e1) x y) =
(ang_add (zh_ang d x (hpart y (zh_range d)))
(zh_ang e1 (zh_ket d x (hpart y (zh_range d)))
(tpart y (zh_range d))))))))))))).
Parameter parallel_zh: circuit -> circuit -> circuit.
Axiom parallel_zh_def :
forall (d:circuit) (e1:circuit), ((width d) = (width e1)) -> (cont_zh d) ->
(cont_zh e1) -> ((parallel_zh d e1) = (parallel d e1)).
Axiom parallel_zh_spec :
forall (d:circuit) (e1:circuit), ((width d) = (width e1)) -> (cont_zh d) ->
(cont_zh e1) ->
(cont_zh (parallel_zh d e1)) /\
(((width (parallel_zh d e1)) = ((width d) + (width e1))%Z) /\
(((zh_range (parallel_zh d e1)) = ((zh_range d) + (zh_range e1))%Z) /\
((forall (x:bitvec) (y:bitvec),
((length x) = (width (parallel_zh d e1))) ->
((length y) = (zh_range (parallel_zh d e1))) -> forall (i:Z),
((0%Z <= i)%Z /\ (i < (width d))%Z) ->
((zh_ket_i (parallel_zh d e1) x y i) =
(zh_ket_i d (hpart x (width d)) (hpart y (zh_range d)) i))) /\
((forall (x:bitvec) (y:bitvec),
((length x) = (width (parallel_zh d e1))) ->
((length y) = (zh_range (parallel_zh d e1))) -> forall (i:Z),
(((width d) <= i)%Z /\ (i < ((width d) + (width e1))%Z)%Z) ->
((zh_ket_i (parallel_zh d e1) x y i) =
(zh_ket_i e1 (tpart x (width d)) (tpart y (zh_range d))
(i - (width d))%Z))) /\
((forall (x:bitvec) (y:bitvec),
((length x) = (width (parallel_zh d e1))) ->
((length y) = (zh_range (parallel_zh d e1))) ->
((zh_ket (parallel_zh d e1) x y) =
(concat (zh_ket d (hpart x (width d)) (hpart y (zh_range d)))
(zh_ket e1 (tpart x (width d)) (tpart y (zh_range d)))))) /\
forall (x:bitvec) (y:bitvec),
((length x) = (width (parallel_zh d e1))) ->
((length y) = (zh_range (parallel_zh d e1))) ->
((zh_ang_coeff (parallel_zh d e1) x y) =
((zh_ang_coeff d (hpart x (width d)) (hpart y (zh_range d))) +
(zh_ang_coeff e1 (tpart x (width d)) (tpart y (zh_range d))))%Z)))))).
Axiom correct_path_sum_zh :
forall (g:circuit), (cont_zh g) ->
correct_path_sum g
((fun (y0:circuit) (y1:bitvec) (y2:bitvec) => (zh_ang y0 y1 y2)) g)
((fun (y0:circuit) (y1:bitvec) (y2:bitvec) => (zh_ket y0 y1 y2)) g)
(zh_range g).
Axiom correct_ps_ket_i :
forall (g:circuit), (cont_zh g) ->
correct_path_sum g
((fun (y0:circuit) (y1:bitvec) (y2:bitvec) => (zh_ang y0 y1 y2)) g)
(fun (x:bitvec) (y:bitvec) =>
(make_bv
((((fun (y0:circuit) (y1:bitvec) (y2:bitvec) (y3:Z) =>
(zh_ket_i y0 y1 y2 y3))
g)
x)
y)
(width g)))
(zh_range g).
Axiom correct_ps_coeff :
forall (g:circuit), (cont_zh g) ->
correct_path_sum g
(fun (x:bitvec) (y:bitvec) => (int_to_ang (zh_ang_coeff g x y) (width g)))
((fun (y0:circuit) (y1:bitvec) (y2:bitvec) => (zh_ket y0 y1 y2)) g)
(zh_range g).
Axiom correct_ps_neg_coeff :
forall (g:circuit), (cont_zh g) ->
correct_path_sum g
(fun (x:bitvec) (y:bitvec) =>
(int_to_ang (-(zh_ang_coeff_neg g x y))%Z (width g)))
((fun (y0:circuit) (y1:bitvec) (y2:bitvec) => (zh_ket y0 y1 y2)) g)
(zh_range g).
Axiom correct_ps_coeff_ket_i :
forall (g:circuit), (cont_zh g) ->
correct_path_sum g
(fun (x:bitvec) (y:bitvec) => (int_to_ang (zh_ang_coeff g x y) (width g)))
(fun (x:bitvec) (y:bitvec) =>
(make_bv
((((fun (y0:circuit) (y1:bitvec) (y2:bitvec) (y3:Z) =>
(zh_ket_i y0 y1 y2 y3))
g)
x)
y)
(width g)))
(zh_range g).
Axiom correct_ps_neg_coeff_ket_i :
forall (g:circuit), (cont_zh g) ->
correct_path_sum g
(fun (x:bitvec) (y:bitvec) =>
(int_to_ang (-(zh_ang_coeff_neg g x y))%Z (width g)))
(fun (x:bitvec) (y:bitvec) =>
(make_bv
((((fun (y0:circuit) (y1:bitvec) (y2:bitvec) (y3:Z) =>
(zh_ket_i y0 y1 y2 y3))
g)
x)
y)
(width g)))
(zh_range g).
Axiom pat_sem_unit_zh :
forall (g:circuit) (x:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_l x (width g)) -> (cont_zh g) ->
((pat_sem g x) =
(infix_asdtdt (pow_inv_sqrt_2 (zh_range g))
(ket_sum_l (n_bvs (zh_range g))
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp (zh_ang g (ket_to_bv x) y))
(bv_to_ket (zh_ket g (ket_to_bv x) y))))
(width g)))).
Axiom pat_sem_unit_zh_ket_i :
forall (g:circuit) (x:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_l x (width g)) -> (cont_zh g) ->
((pat_sem g x) =
(infix_asdtdt (pow_inv_sqrt_2 (zh_range g))
(ket_sum_l (n_bvs (zh_range g))
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp (zh_ang g (ket_to_bv x) y))
(bv_to_ket
(make_bv
((((fun (y0:circuit) (y1:bitvec) (y2:bitvec) (y3:Z) =>
(zh_ket_i y0 y1 y2 y3))
g)
(ket_to_bv x))
y)
(width g)))))
(width g)))).
Axiom pat_sem_unit_zh_coeff :
forall (g:circuit) (x:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_l x (width g)) -> (cont_zh g) ->
((pat_sem g x) =
(infix_asdtdt (pow_inv_sqrt_2 (zh_range g))
(ket_sum_l (n_bvs (zh_range g))
(fun (y:bitvec) =>
(infix_asdtdt
(ang_exp (int_to_ang (zh_ang_coeff g (ket_to_bv x) y) (width g)))
(bv_to_ket (zh_ket g (ket_to_bv x) y))))
(width g)))).
Axiom pat_sem_unit_zh_coeff_neg :
forall (g:circuit) (x:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_l x (width g)) -> (cont_zh g) ->
((pat_sem g x) =
(infix_asdtdt (pow_inv_sqrt_2 (zh_range g))
(ket_sum_l (n_bvs (zh_range g))
(fun (y:bitvec) =>
(infix_asdtdt
(ang_exp
(int_to_ang (-(zh_ang_coeff_neg g (ket_to_bv x) y))%Z (width g)))
(bv_to_ket (zh_ket g (ket_to_bv x) y))))
(width g)))).
Axiom pat_sem_unit_zh_coeff_ket_i :
forall (g:circuit) (x:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_l x (width g)) -> (cont_zh g) ->
((pat_sem g x) =
(infix_asdtdt (pow_inv_sqrt_2 (zh_range g))
(ket_sum_l (n_bvs (zh_range g))
(fun (y:bitvec) =>
(infix_asdtdt
(ang_exp (int_to_ang (zh_ang_coeff g (ket_to_bv x) y) (width g)))
(bv_to_ket
(make_bv
((((fun (y0:circuit) (y1:bitvec) (y2:bitvec) (y3:Z) =>
(zh_ket_i y0 y1 y2 y3))
g)
(ket_to_bv x))
y)
(width g)))))
(width g)))).
Axiom pat_sem_unit_zh_coeff_neg_ket_i :
forall (g:circuit) (x:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_l x (width g)) -> (cont_zh g) ->
((pat_sem g x) =
(infix_asdtdt (pow_inv_sqrt_2 (zh_range g))
(ket_sum_l (n_bvs (zh_range g))
(fun (y:bitvec) =>
(infix_asdtdt
(ang_exp
(int_to_ang (-(zh_ang_coeff_neg g (ket_to_bv x) y))%Z (width g)))
(bv_to_ket
(make_bv
((((fun (y0:circuit) (y1:bitvec) (y2:bitvec) (y3:Z) =>
(zh_ket_i y0 y1 y2 y3))
g)
(ket_to_bv x))
y)
(width g)))))
(width g)))).
Axiom sem_unit_zh :
forall (g:circuit) (x:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_l x (width g)) -> (cont_zh g) ->
sem g x
(infix_asdtdt (pow_inv_sqrt_2 (zh_range g))
(ket_sum_l (n_bvs (zh_range g))
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp (zh_ang g (ket_to_bv x) y))
(bv_to_ket (zh_ket g (ket_to_bv x) y))))
(width g))).
Axiom sem_unit_zh_ket_i :
forall (g:circuit) (x:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_l x (width g)) -> (cont_zh g) ->
sem g x
(infix_asdtdt (pow_inv_sqrt_2 (zh_range g))
(ket_sum_l (n_bvs (zh_range g))
(fun (y:bitvec) =>
(infix_asdtdt (ang_exp (zh_ang g (ket_to_bv x) y))
(bv_to_ket
(make_bv
((((fun (y0:circuit) (y1:bitvec) (y2:bitvec) (y3:Z) =>
(zh_ket_i y0 y1 y2 y3))
g)
(ket_to_bv x))
y)
(width g)))))
(width g))).
Axiom sem_unit_zh_coeff :
forall (g:circuit) (x:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_l x (width g)) -> (cont_zh g) ->
sem g x
(infix_asdtdt (pow_inv_sqrt_2 (zh_range g))
(ket_sum_l (n_bvs (zh_range g))
(fun (y:bitvec) =>
(infix_asdtdt
(ang_exp (int_to_ang (zh_ang_coeff g (ket_to_bv x) y) (width g)))
(bv_to_ket (zh_ket g (ket_to_bv x) y))))
(width g))).
Axiom sem_unit_zh_coeff_neg :
forall (g:circuit) (x:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_l x (width g)) -> (cont_zh g) ->
sem g x
(infix_asdtdt (pow_inv_sqrt_2 (zh_range g))
(ket_sum_l (n_bvs (zh_range g))
(fun (y:bitvec) =>
(infix_asdtdt
(ang_exp
(int_to_ang (-(zh_ang_coeff_neg g (ket_to_bv x) y))%Z (width g)))
(bv_to_ket (zh_ket g (ket_to_bv x) y))))
(width g))).
Axiom sem_unit_zh_coeff_ket_i :
forall (g:circuit) (x:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_l x (width g)) -> (cont_zh g) ->
sem g x
(infix_asdtdt (pow_inv_sqrt_2 (zh_range g))
(ket_sum_l (n_bvs (zh_range g))
(fun (y:bitvec) =>
(infix_asdtdt
(ang_exp (int_to_ang (zh_ang_coeff g (ket_to_bv x) y) (width g)))
(bv_to_ket
(make_bv
((((fun (y0:circuit) (y1:bitvec) (y2:bitvec) (y3:Z) =>
(zh_ket_i y0 y1 y2 y3))
g)
(ket_to_bv x))
y)
(width g)))))
(width g))).
Axiom sem_unit_zh_coeff_neg_ket_i :
forall (g:circuit) (x:matrix t), (is_a_ket_basis_elt x) ->
(is_a_ket_l x (width g)) -> (cont_zh g) ->
sem g x
(infix_asdtdt (pow_inv_sqrt_2 (zh_range g))
(ket_sum_l (n_bvs (zh_range g))
(fun (y:bitvec) =>
(infix_asdtdt
(ang_exp
(int_to_ang (-(zh_ang_coeff_neg g (ket_to_bv x) y))%Z (width g)))
(bv_to_ket
(make_bv
((((fun (y0:circuit) (y1:bitvec) (y2:bitvec) (y3:Z) =>
(zh_ket_i y0 y1 y2 y3))
g)
(ket_to_bv x))
y)
(width g)))))
(width g))).
Parameter cascade_cont_rz: Z -> Z -> Z -> Z -> Z -> circuit.
Axiom cascade_cont_rz_def :
forall (first_k:Z) (first_c:Z) (t1:Z) (l:Z) (n:Z),
((0%Z <= l)%Z /\ (l < n)%Z) -> ((0%Z <= first_c)%Z /\ (first_c < n)%Z) ->
((0%Z <= t1)%Z /\ (t1 < n)%Z) -> ((first_c + l)%Z < n)%Z ->
(0%Z <= first_k)%Z -> ((t1 <= (first_c + l)%Z)%Z -> (t1 < first_c)%Z) ->
((l = 0%Z) ->
((cascade_cont_rz first_k first_c t1 l n) =
(c_rzp_zh first_k first_c t1 n))) /\
(~ (l = 0%Z) ->
((cascade_cont_rz first_k first_c t1 l n) =
(sequence_zh (cascade_cont_rz first_k first_c t1 (l - 1%Z)%Z n)
(c_rzp_zh (first_k + l)%Z (first_c + l)%Z t1 n)))).
Axiom cascade_cont_rz_spec :
forall (first_k:Z) (first_c:Z) (t1:Z) (l:Z) (n:Z),
((0%Z <= l)%Z /\ (l < n)%Z) -> ((0%Z <= first_c)%Z /\ (first_c < n)%Z) ->
((0%Z <= t1)%Z /\ (t1 < n)%Z) -> ((first_c + l)%Z < n)%Z ->
(0%Z <= first_k)%Z -> ((t1 <= (first_c + l)%Z)%Z -> (t1 < first_c)%Z) ->
((width (cascade_cont_rz first_k first_c t1 l n)) = n) /\
(((ancillas (cascade_cont_rz first_k first_c t1 l n)) = 0%Z) /\
(((size (cascade_cont_rz first_k first_c t1 l n)) <=
((cont_size * 2%Z)%Z * (l + 1%Z)%Z)%Z)%Z /\
((cont_zh (cascade_cont_rz first_k first_c t1 l n)) /\
(((zh_range (cascade_cont_rz first_k first_c t1 l n)) = 0%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) ->
((zh_ang_coeff (cascade_cont_rz first_k first_c t1 l n) x y) =
(ind_isum
(fun (k:Z) =>
((((getbv x) t1) * ((getbv x) (first_c + k)%Z))%Z *
(power_ 2%Z (n - (k + first_k)%Z)%Z))%Z)
0%Z (l + 1%Z)%Z))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) ->
((zh_ang_coeff (cascade_cont_rz first_k first_c t1 l n) x y) =
(ind_isum
(fun (k:Z) =>
((((getbv x) t1) *
((getbv x) (first_c + (((k - n)%Z + l)%Z + 1%Z)%Z)%Z))%Z
*
(power_ 2%Z (((((n + n)%Z - k)%Z - l)%Z - 1%Z)%Z - first_k)%Z))%Z)
(n - (l + 1%Z)%Z)%Z n))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) ->
((zh_ket (cascade_cont_rz first_k first_c t1 l n) x y) = x)) /\
forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) -> forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) ->
((zh_ket_i (cascade_cont_rz first_k first_c t1 l n) x y i) =
((getbv x) i))))))))).
Parameter cascade_cont_rz_neg: Z -> Z -> Z -> Z -> Z -> circuit.
Axiom cascade_cont_rz_neg_def :
forall (first_k:Z) (first_c:Z) (t1:Z) (l:Z) (n:Z),
((0%Z <= l)%Z /\ (l < n)%Z) -> ((0%Z <= first_c)%Z /\ (first_c < n)%Z) ->
((0%Z <= t1)%Z /\ (t1 < n)%Z) -> ((first_c + l)%Z < n)%Z ->
(0%Z <= first_k)%Z -> ((t1 <= (first_c + l)%Z)%Z -> (t1 < first_c)%Z) ->
((l = 0%Z) ->
((cascade_cont_rz_neg first_k first_c t1 l n) =
(c_rzp_zh (-first_k)%Z first_c t1 n))) /\
(~ (l = 0%Z) ->
((cascade_cont_rz_neg first_k first_c t1 l n) =
(sequence_zh (cascade_cont_rz_neg first_k first_c t1 (l - 1%Z)%Z n)
(c_rzp_zh (-(first_k + l)%Z)%Z (first_c + l)%Z t1 n)))).
Axiom cascade_cont_rz_neg_spec :
forall (first_k:Z) (first_c:Z) (t1:Z) (l:Z) (n:Z),
((0%Z <= l)%Z /\ (l < n)%Z) -> ((0%Z <= first_c)%Z /\ (first_c < n)%Z) ->
((0%Z <= t1)%Z /\ (t1 < n)%Z) -> ((first_c + l)%Z < n)%Z ->
(0%Z <= first_k)%Z -> ((t1 <= (first_c + l)%Z)%Z -> (t1 < first_c)%Z) ->
((width (cascade_cont_rz_neg first_k first_c t1 l n)) = n) /\
(((ancillas (cascade_cont_rz_neg first_k first_c t1 l n)) = 0%Z) /\
(((size (cascade_cont_rz_neg first_k first_c t1 l n)) <=
((cont_size * 2%Z)%Z * (l + 1%Z)%Z)%Z)%Z /\
((cont_zh (cascade_cont_rz_neg first_k first_c t1 l n)) /\
(((zh_range (cascade_cont_rz_neg first_k first_c t1 l n)) = 0%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) ->
((zh_ang_coeff_neg (cascade_cont_rz_neg first_k first_c t1 l n) x y)
=
(ind_isum
(fun (k:Z) =>
((((getbv x) t1) * ((getbv x) (first_c + k)%Z))%Z *
(power_ 2%Z (n - (k + first_k)%Z)%Z))%Z)
0%Z (l + 1%Z)%Z))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) ->
((zh_ang_coeff_neg (cascade_cont_rz_neg first_k first_c t1 l n) x y)
=
(ind_isum
(fun (k:Z) =>
((((getbv x) t1) *
((getbv x) (first_c + (((k - n)%Z + l)%Z + 1%Z)%Z)%Z))%Z
*
(power_ 2%Z (((((n + n)%Z - k)%Z - l)%Z - 1%Z)%Z - first_k)%Z))%Z)
(n - (l + 1%Z)%Z)%Z n))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) ->
((zh_ang (cascade_cont_rz_neg first_k first_c t1 l n) x y) =
(int_to_ang
(-(ind_isum
(fun (k:Z) =>
((((getbv x) t1) *
((getbv x) (first_c + (((k - n)%Z + l)%Z + 1%Z)%Z)%Z))%Z
*
(power_ 2%Z
(((((n + n)%Z - k)%Z - l)%Z - 1%Z)%Z - first_k)%Z))%Z)
(n - (l + 1%Z)%Z)%Z n))%Z
n))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) ->
((zh_ket (cascade_cont_rz_neg first_k first_c t1 l n) x y) = x)) /\
forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) -> forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) ->
((zh_ket_i (cascade_cont_rz_neg first_k first_c t1 l n) x y i) =
((getbv x) i)))))))))).
Axiom set_had_zh_ang :
forall (a:Z) (b:Z) (c:Z) (t1:Z) (n:Z) (x:bitvec) (y:bitvec),
(n >= 0%Z)%Z -> ((0%Z <= t1)%Z /\ (t1 < n)%Z) -> (a = ((getbv x) t1)) ->
(b = ((getbv y) 0%Z)) -> (c = (n - 1%Z)%Z) -> ((length x) = n) ->
((length y) = 1%Z) ->
((zh_ang (had_zh t1 n) x y) =
(int_to_ang (-((a * b)%Z * (power_ 2%Z c))%Z)%Z n)) /\
(((zh_ang (had_zh t1 n) x y) =
(int_to_ang ((a * b)%Z * (power_ 2%Z c))%Z n)) /\
(((zh_ang_coeff_neg (had_zh t1 n) x y) = ((a * b)%Z * (power_ 2%Z c))%Z) /\
((zh_ang_coeff (had_zh t1 n) x y) = ((a * b)%Z * (power_ 2%Z c))%Z))).
Parameter had_seq_zh: circuit -> Z -> Z -> circuit.
Axiom had_seq_zh_def :
forall (g:circuit) (t1:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= t1)%Z /\ (t1 < n)%Z) -> (cont_zh g) -> ((width g) = n) ->
((had_seq_zh g t1 n) = (sequence_zh (had_zh t1 n) g)).
Parameter fc24: Z -> bitvec -> bitvec -> Z -> Z.
Parameter fc25: Z -> bitvec -> bitvec -> Z -> Z.
Parameter fc26: Z -> bitvec -> bitvec -> Z -> Z.
Parameter fc27: Z -> bitvec -> bitvec -> Z -> Z.
Axiom fc_def24 :
forall (t1:Z) (x:bitvec) (y:bitvec) (i:Z),
((i = t1) -> (((fc24 t1 x y) i) = ((getbv y) 0%Z))) /\
(~ (i = t1) -> (((fc24 t1 x y) i) = ((getbv x) i))).
Axiom fc_def25 :
forall (t1:Z) (x:bitvec) (y:bitvec) (i:Z),
((i = t1) -> (((fc25 t1 x y) i) = ((getbv y) 0%Z))) /\
(~ (i = t1) -> (((fc25 t1 x y) i) = ((getbv x) i))).
Axiom fc_def26 :
forall (t1:Z) (x:bitvec) (y:bitvec) (i:Z),
((i = t1) -> (((fc26 t1 x y) i) = ((getbv y) 0%Z))) /\
(~ (i = t1) -> (((fc26 t1 x y) i) = ((getbv x) i))).
Axiom fc_def27 :
forall (t1:Z) (x:bitvec) (y:bitvec) (i:Z),
((i = t1) -> (((fc27 t1 x y) i) = ((getbv y) 0%Z))) /\
(~ (i = t1) -> (((fc27 t1 x y) i) = ((getbv x) i))).
Axiom had_seq_zh_spec :
forall (g:circuit) (t1:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= t1)%Z /\ (t1 < n)%Z) -> (cont_zh g) -> ((width g) = n) ->
(cont_zh (had_seq_zh g t1 n)) /\
(((width (had_seq_zh g t1 n)) = n) /\
(((size (had_seq_zh g t1 n)) = (1%Z + (size g))%Z) /\
(((ancillas (had_seq_zh g t1 n)) = (ancillas g)) /\
(((zh_range (had_seq_zh g t1 n)) = ((zh_range g) + 1%Z)%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = ((zh_range g) + 1%Z)%Z) ->
((zh_ang (had_seq_zh g t1 n) x y) =
(ang_add (int_to_ang (((getbv x) t1) * ((getbv y) 0%Z))%Z 1%Z)
(zh_ang g (make_bv (fc24 t1 x y) n) (tpart y 1%Z))))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = ((zh_range g) + 1%Z)%Z) ->
((zh_ang_coeff_neg (had_seq_zh g t1 n) x y) =
(((((getbv x) t1) * ((getbv y) 0%Z))%Z *
(power_ 2%Z (n - 1%Z)%Z))%Z
+ (zh_ang_coeff_neg g (make_bv (fc25 t1 x y) n) (tpart y 1%Z)))%Z)) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = ((zh_range g) + 1%Z)%Z) ->
((zh_ang_coeff (had_seq_zh g t1 n) x y) =
(((((getbv x) t1) * ((getbv y) 0%Z))%Z *
(power_ 2%Z (n - 1%Z)%Z))%Z
+ (zh_ang_coeff g (make_bv (fc26 t1 x y) n) (tpart y 1%Z)))%Z)) /\
forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = ((zh_range g) + 1%Z)%Z) -> forall (i:Z),
((0%Z <= i)%Z /\ (i < n)%Z) ->
((zh_ket_i (had_seq_zh g t1 n) x y i) =
(zh_ket_i g (make_bv (fc27 t1 x y) n) (tpart y 1%Z) i))))))))).
Parameter had_seq_diag_zh: circuit -> Z -> Z -> circuit.
Axiom had_seq_diag_zh_def :
forall (g:circuit) (t1:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= t1)%Z /\ (t1 < n)%Z) -> (cont_zh g) -> ((width g) = n) ->
((zh_range g) = 0%Z) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = n) ->
((length y) = 0%Z) -> ((0%Z <= i)%Z /\ (i < n)%Z) ->
((zh_ket_i g x y i) = ((getbv x) i))) ->
((had_seq_diag_zh g t1 n) = (had_seq_zh g t1 n)).
Parameter fc28: Z -> bitvec -> bitvec -> Z -> Z.
Parameter fc29: Z -> bitvec -> bitvec -> Z -> Z.
Parameter fc30: Z -> bitvec -> bitvec -> Z -> Z.
Axiom fc_def28 :
forall (t1:Z) (x:bitvec) (y:bitvec) (i:Z),
((i = t1) -> (((fc28 t1 x y) i) = ((getbv y) 0%Z))) /\
(~ (i = t1) -> (((fc28 t1 x y) i) = ((getbv x) i))).
Axiom fc_def29 :
forall (t1:Z) (x:bitvec) (y:bitvec) (i:Z),
((i = t1) -> (((fc29 t1 x y) i) = ((getbv y) 0%Z))) /\
(~ (i = t1) -> (((fc29 t1 x y) i) = ((getbv x) i))).
Axiom fc_def30 :
forall (t1:Z) (x:bitvec) (y:bitvec) (i:Z),
((i = t1) -> (((fc30 t1 x y) i) = ((getbv y) 0%Z))) /\
(~ (i = t1) -> (((fc30 t1 x y) i) = ((getbv x) i))).
Axiom had_seq_diag_zh_spec :
forall (g:circuit) (t1:Z) (n:Z), (n >= 0%Z)%Z ->
((0%Z <= t1)%Z /\ (t1 < n)%Z) -> (cont_zh g) -> ((width g) = n) ->
((zh_range g) = 0%Z) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = n) ->
((length y) = 0%Z) -> ((0%Z <= i)%Z /\ (i < n)%Z) ->
((zh_ket_i g x y i) = ((getbv x) i))) ->
(cont_zh (had_seq_diag_zh g t1 n)) /\
(((size (had_seq_diag_zh g t1 n)) = (1%Z + (size g))%Z) /\
(((ancillas (had_seq_diag_zh g t1 n)) = (ancillas g)) /\
(((width (had_seq_diag_zh g t1 n)) = n) /\
(((zh_range (had_seq_diag_zh g t1 n)) = 1%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = ((zh_range g) + 1%Z)%Z) ->
((zh_ang (had_seq_diag_zh g t1 n) x y) =
(ang_add (int_to_ang (((getbv x) t1) * ((getbv y) 0%Z))%Z 1%Z)
(zh_ang g (make_bv (fc28 t1 x y) n) (tpart y 1%Z))))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = ((zh_range g) + 1%Z)%Z) ->
((zh_ang_coeff (had_seq_diag_zh g t1 n) x y) =
(((((getbv x) t1) * ((getbv y) 0%Z))%Z *
(power_ 2%Z (n - 1%Z)%Z))%Z
+ (zh_ang_coeff g (make_bv (fc29 t1 x y) n) (tpart y 1%Z)))%Z)) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = ((zh_range g) + 1%Z)%Z) ->
((zh_ang_coeff_neg (had_seq_diag_zh g t1 n) x y) =
(((((getbv x) t1) * ((getbv y) 0%Z))%Z *
(power_ 2%Z (n - 1%Z)%Z))%Z
+ (zh_ang_coeff_neg g (make_bv (fc30 t1 x y) n) (tpart y 1%Z)))%Z)) /\
forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = ((zh_range g) + 1%Z)%Z) -> forall (i:Z),
((0%Z <= i)%Z /\ (i < n)%Z) ->
((i = t1) ->
((zh_ket_i (had_seq_diag_zh g t1 n) x y i) = ((getbv y) 0%Z))) /\
(~ (i = t1) ->
((zh_ket_i (had_seq_diag_zh g t1 n) x y i) = ((getbv x) i)))))))))).
Parameter seq_diag_zh: circuit -> circuit -> circuit.
Axiom seq_diag_zh_def :
forall (g:circuit) (g':circuit), (cont_zh g) -> (cont_zh g') ->
((width g) = (width g')) -> ((zh_range g) = 0%Z) ->
((zh_range g') = 0%Z) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = (width g)) ->
((length y) = 0%Z) -> ((0%Z <= i)%Z /\ (i < (width g))%Z) ->
((zh_ket_i g x y i) = ((getbv x) i))) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = (width g)) ->
((length y) = 0%Z) -> ((0%Z <= i)%Z /\ (i < (width g))%Z) ->
((zh_ket_i g' x y i) = ((getbv x) i))) ->
((seq_diag_zh g g') = (sequence_zh g g')).
Axiom seq_diag_zh_spec :
forall (g:circuit) (g':circuit), (cont_zh g) -> (cont_zh g') ->
((width g) = (width g')) -> ((zh_range g) = 0%Z) ->
((zh_range g') = 0%Z) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = (width g)) ->
((length y) = 0%Z) -> ((0%Z <= i)%Z /\ (i < (width g))%Z) ->
((zh_ket_i g x y i) = ((getbv x) i))) ->
(forall (x:bitvec) (y:bitvec), forall (i:Z), ((length x) = (width g)) ->
((length y) = 0%Z) -> ((0%Z <= i)%Z /\ (i < (width g))%Z) ->
((zh_ket_i g' x y i) = ((getbv x) i))) ->
(cont_zh (seq_diag_zh g g')) /\
(((zh_range (seq_diag_zh g g')) = 0%Z) /\
(((width (seq_diag_zh g g')) = (width g)) /\
((forall (x:bitvec) (y:bitvec), ((length x) = (width g)) ->
((length y) = 0%Z) ->
((zh_ang (seq_diag_zh g g') x y) =
(ang_add (zh_ang g x y) (zh_ang g' x y)))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = (width g)) ->
((length y) = 0%Z) ->
((zh_ang_coeff (seq_diag_zh g g') x y) =
((zh_ang_coeff g x y) + (zh_ang_coeff g' x y))%Z)) /\
((forall (x:bitvec) (y:bitvec), ((length x) = (width g)) ->
((length y) = 0%Z) ->
((zh_ang_coeff_neg (seq_diag_zh g g') x y) =
((zh_ang_coeff_neg g x y) + (zh_ang_coeff_neg g' x y))%Z)) /\
forall (x:bitvec) (y:bitvec), ((length x) = (width g)) ->
((length y) = 0%Z) -> forall (i:Z),
((0%Z <= i)%Z /\ (i < (width g))%Z) ->
((zh_ket_i (seq_diag_zh g g') x y i) = ((getbv x) i))))))).
Parameter cascade_cont_qft: Z -> Z -> circuit.
Axiom cascade_cont_qft_def :
forall (t1:Z) (n:Z), ((0%Z <= t1)%Z /\ (t1 < (n - 1%Z)%Z)%Z) ->
((cascade_cont_qft t1 n) =
(cascade_cont_rz_neg 2%Z (t1 + 1%Z)%Z t1 (n - (t1 + 2%Z)%Z)%Z n)).
Axiom cascade_cont_qft_spec :
forall (t1:Z) (n:Z), ((0%Z <= t1)%Z /\ (t1 < (n - 1%Z)%Z)%Z) ->
((width (cascade_cont_qft t1 n)) = n) /\
(((size (cascade_cont_qft t1 n)) <=
((cont_size * 2%Z)%Z * ((n - t1)%Z - 1%Z)%Z)%Z)%Z /\
(((ancillas (cascade_cont_qft t1 n)) = 0%Z) /\
((cont_zh (cascade_cont_qft t1 n)) /\
(((zh_range (cascade_cont_qft t1 n)) = 0%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) ->
((zh_ang_coeff_neg (cascade_cont_qft t1 n) x y) =
(ind_isum
(fun (k:Z) =>
((((getbv x) t1) * ((getbv x) k))%Z *
(power_ 2%Z (((n - k)%Z - 1%Z)%Z + t1)%Z))%Z)
(t1 + 1%Z)%Z n))) /\
forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 0%Z) -> forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) ->
((zh_ket_i (cascade_cont_qft t1 n) x y i) = ((getbv x) i))))))).
Parameter qft_rev_line: Z -> Z -> circuit.
Axiom qft_rev_line_def :
forall (t1:Z) (n:Z), ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
((t1 = (n - 1%Z)%Z) -> ((qft_rev_line t1 n) = (had_zh t1 n))) /\
(~ (t1 = (n - 1%Z)%Z) ->
((qft_rev_line t1 n) = (had_seq_diag_zh (cascade_cont_qft t1 n) t1 n))).
Axiom qft_rev_line_spec :
forall (t1:Z) (n:Z), ((0%Z <= t1)%Z /\ (t1 < n)%Z) ->
((size (qft_rev_line t1 n)) <= ((cont_size * 2%Z)%Z * n)%Z)%Z /\
(((ancillas (qft_rev_line t1 n)) = 0%Z) /\
(((width (qft_rev_line t1 n)) = n) /\
((cont_zh (qft_rev_line t1 n)) /\
(((zh_range (qft_rev_line t1 n)) = 1%Z) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 1%Z) ->
((zh_ang_coeff_neg (qft_rev_line t1 n) x y) =
(ind_isum
(fun (k:Z) =>
((((getbv x) k) * ((getbv y) 0%Z))%Z *
(power_ 2%Z (((n - k)%Z - 1%Z)%Z + t1)%Z))%Z)
t1 n))) /\
forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = 1%Z) -> forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) ->
((i = t1) -> ((zh_ket_i (qft_rev_line t1 n) x y i) = ((getbv y) 0%Z))) /\
(~ (i = t1) -> ((zh_ket_i (qft_rev_line t1 n) x y i) = ((getbv x) i)))))))).
Parameter qft_rev: Z -> circuit.
Axiom qft_rev_spec :
forall (n:Z), (0%Z < n)%Z ->
((size (qft_rev n)) <= (polysquare n (2%Z * cont_size)%Z 0%Z 0%Z))%Z /\
(((ancillas (qft_rev n)) = 0%Z) /\
(((ancillas (qft_rev n)) = 0%Z) /\
(((width (qft_rev n)) = n) /\
((cont_zh (qft_rev n)) /\
(((zh_range (qft_rev n)) = n) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = n) ->
((zh_ang_coeff_neg (qft_rev n) x y) =
(ind_isum
(fun (l:Z) =>
(ind_isum
(fun (k:Z) =>
((((getbv x) k) * ((getbv y) l))%Z *
(power_ 2%Z (((n - k)%Z - 1%Z)%Z + l)%Z))%Z)
l n))
0%Z n))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = n) ->
((zh_ang (qft_rev n) x y) =
(int_to_ang (-((bv_to_int x) * (bv_to_int (bv_inversion y)))%Z)%Z
n))) /\
((forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = n) ->
((zh_ang (qft_rev n) x y) =
(real_to_ang
(infix_asdt
(infix_asdt (i_to_t (bv_to_int x))
(i_to_t (-(bv_to_int (bv_inversion y)))%Z))
(pow_inv_2 n))))) /\
forall (x:bitvec) (y:bitvec), ((length x) = n) ->
((length y) = n) -> forall (i:Z), ((0%Z <= i)%Z /\ (i < n)%Z) ->
((zh_ket_i (qft_rev n) x y i) = ((getbv y) i)))))))))).
Parameter qft_rev_coeff: bitvec -> bitvec -> Z -> t.
Axiom qft_rev_coeff_def :
forall (x:bitvec) (y:bitvec) (n:Z), (0%Z < n)%Z -> ((length x) = n) ->
((length y) = n) ->
((qft_rev_coeff x y n) =
(ang_exp
(real_to_ang
(infix_asdt
(infix_asdt (i_to_t (-(bv_to_int x))%Z)
(i_to_t (bv_to_int (bv_inversion y))))
(pow_inv_2 n))))).
Axiom qft_rev_coeff_spec :
forall (x:bitvec) (y:bitvec) (n:Z), (0%Z < n)%Z -> ((length x) = n) ->
((length y) = n) ->
((qft_rev_coeff x y n) = (ang_exp (zh_ang (qft_rev n) x y))).
Parameter int_qft_rev_coeff: Z -> Z -> Z -> t.
Axiom int_qft_rev_coeff_def :
forall (i:Z) (j:Z) (n:Z), (0%Z < n)%Z ->
((int_qft_rev_coeff i j n) =
(ang_exp
(real_to_ang
(infix_asdt
(infix_asdt (i_to_t (int.EuclideanDivision.mod1 (-i)%Z (power_ 2%Z n)))
(i_to_t
(int_bit_inversion (int.EuclideanDivision.mod1 j (power_ 2%Z n)) n)))
(pow_inv_2 n))))).
Axiom int_qft_rev_coeff_spec :
forall (i:Z) (j:Z) (n:Z), (0%Z < n)%Z ->
((int_qft_rev_coeff i j n) =
(qft_rev_coeff (int_to_bv (int.EuclideanDivision.mod1 i (power_ 2%Z n)) n)
(int_to_bv (int.EuclideanDivision.mod1 j (power_ 2%Z n)) n) n)).
Axiom qft_rev_ket :
forall (x:bitvec) (y:bitvec) (n:Z), (0%Z < n)%Z -> ((length x) = n) ->
((length y) = n) -> ((zh_ket (qft_rev n) x y) = y).
Axiom sem_rev_qft_unit :
forall (n:Z), (0%Z < n)%Z -> forall (x:matrix t), (is_a_ket_l x n) ->
(is_a_ket_basis_elt x) ->
sem (qft_rev n) x
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n)
(fun (y:bitvec) =>
(infix_asdtdt (qft_rev_coeff (ket_to_bv x) y n) (bv_to_ket y)))
n)).
Axiom pat_sem_rev_qft_unit :
forall (n:Z), (0%Z < n)%Z -> forall (x:matrix t), (is_a_ket_l x n) ->
(is_a_ket_basis_elt x) ->
((pat_sem (qft_rev n) x) =
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n)
(fun (y:bitvec) =>
(infix_asdtdt (qft_rev_coeff (ket_to_bv x) y n) (bv_to_ket y)))
n))).
Axiom pat_sem_rev_qft_ket :
forall (i:Z) (n:Z), (0%Z < n)%Z ->
((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) ->
((pat_sem (qft_rev n) (ket n i)) =
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n)
(fun (y:bitvec) =>
(infix_asdtdt (qft_rev_coeff (int_to_bv i n) y n) (bv_to_ket y)))
n))).
Axiom pat_sem_rev_qft_ket_ind :
forall (i:Z) (n:Z), (0%Z < n)%Z ->
((0%Z <= i)%Z /\ (i < (power_ 2%Z n))%Z) ->
((pat_sem (qft_rev n) (ket n i)) =
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n)
(fun (y:bitvec) =>
(infix_asdtdt (int_qft_rev_coeff i (bv_to_int y) n) (bv_to_ket y)))
n))).
Axiom pat_sem_rev_qft_bv :
forall (n:Z), (0%Z < n)%Z -> forall (x:bitvec), ((length x) = n) ->
((pat_sem (qft_rev n) (bv_to_ket x)) =
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n)
(fun (y:bitvec) => (infix_asdtdt (qft_rev_coeff x y n) (bv_to_ket y)))
n))).
Axiom sem_rev_qft_bv :
forall (n:Z), (0%Z < n)%Z -> forall (x:bitvec), ((length x) = n) ->
sem (qft_rev n) (bv_to_ket x)
(infix_asdtdt (pow_inv_sqrt_2 n)
(ket_sum_l (n_bvs n)
(fun (y:bitvec) => (infix_asdtdt (qft_rev_coeff x y n) (bv_to_ket y))) n)).
Parameter apply_qft_rev: Z -> Z -> (matrix t) -> circuit.
Axiom apply_qft_rev_def :
forall (k:Z) (n:Z) (y:matrix t), ((0%Z < k)%Z /\ (k < n)%Z) ->
(is_a_ket_l y (n - k)%Z) ->
((apply_qft_rev k n y) = (place (qft_rev k) 0%Z n)).
Axiom apply_qft_rev_spec :
forall (k:Z) (n:Z) (y:matrix t), ((0%Z < k)%Z /\ (k < n)%Z) ->
(is_a_ket_l y (n - k)%Z) ->
((width (apply_qft_rev k n y)) = n) /\
forall (x:matrix t) (x':matrix t), (is_a_ket_l x k) ->
((pat_sem (qft_rev k) x) = x') ->
((pat_sem (apply_qft_rev k n y) (kronecker x y)) = (kronecker x' y)).
Parameter create_superposition: Z -> Z -> (matrix t) -> circuit.
Axiom create_superposition_def :
forall (k:Z) (n:Z) (y:matrix t), ((0%Z < k)%Z /\ (k < n)%Z) ->
(is_a_ket_l y (n - k)%Z) ->
((create_superposition k n y) = (place (repeat_had k) 0%Z n)).
Axiom create_superposition_spec :
forall (k:Z) (n:Z) (y:matrix t), ((0%Z < k)%Z /\ (k < n)%Z) ->
(is_a_ket_l y (n - k)%Z) ->
((width (create_superposition k n y)) = n) /\
(((ancillas (create_superposition k n y)) = 0%Z) /\
(((size (create_superposition k n y)) = k) /\
((pat_sem (create_superposition k n y) (kronecker (ket k 0%Z) y)) =
(kronecker
(infix_asdtdt (pow_inv_sqrt_2 k)
(ket_sum_l (n_bvs k) (fun (x:bitvec) => (bv_to_ket x)) k))
y)))).
Parameter cascade_cont_pow: circuit -> Z -> (matrix t) -> t -> circuit.
Parameter result31: circuit -> Z -> (matrix t) -> t -> Z -> circuit.
Axiom result_def31 :
forall (circ:circuit) (ft:Z) (y:matrix t) (theta:t) (i:Z),
((((ft - i)%Z - 1%Z)%Z >= 0%Z)%Z ->
(((result31 circ ft y theta) i) =
(pow_pow_2 circ ((ft - i)%Z - 1%Z)%Z y (real_to_ang theta)))) /\
(~ (((ft - i)%Z - 1%Z)%Z >= 0%Z)%Z ->
(((result31 circ ft y theta) i) =
(pow_pow_2 circ 0%Z y (real_to_ang theta)))).
Axiom cascade_cont_pow_def :
forall (circ:circuit) (ft:Z) (y:matrix t) (theta:t), (1%Z <= ft)%Z ->
(real_ theta) -> (eigen circ y (real_to_ang theta)) ->
(is_a_ket_l y (width circ)) ->
((cascade_cont_pow circ ft y theta) =
(control_eigen_seq_real (result31 circ ft y theta) y
(fun (i:Z) =>
(infix_asdt theta (i_to_t (power_ 2%Z ((ft - i)%Z - 1%Z)%Z))))
(fun (i:Z) => i) ft ft (width circ) (ft + (width circ))%Z)).
Axiom cascade_cont_pow_spec :
forall (circ:circuit) (ft:Z) (y:matrix t) (theta:t), (1%Z <= ft)%Z ->
(real_ theta) -> (eigen circ y (real_to_ang theta)) ->
(is_a_ket_l y (width circ)) ->
((width (cascade_cont_pow circ ft y theta)) = (ft + (width circ))%Z) /\
forall (x:bitvec), ((length x) = ft) ->
((pat_sem (cascade_cont_pow circ ft y theta) (kronecker (bv_to_ket x) y)) =
(kronecker
(infix_asdtdt
(ang_exp (real_to_ang (infix_asdt theta (i_to_t (bv_to_int x)))))
(bv_to_ket x))
y)).
Parameter apply_black_box: circuit -> Z -> Z -> (matrix t) -> t -> circuit.
Axiom apply_black_box_def :
forall (circ:circuit) (k:Z) (n:Z) (y:matrix t) (theta:t),
(n = (k + (width circ))%Z) -> (real_ theta) ->
((0%Z < k)%Z /\ (k < n)%Z) -> (is_a_ket_l y (n - k)%Z) ->
(eigen circ y (real_to_ang theta)) ->
((apply_black_box circ k n y theta) =
(sequence (create_superposition k n y) (cascade_cont_pow circ k y theta))).
Axiom apply_black_box_spec :
forall (circ:circuit) (k:Z) (n:Z) (y:matrix t) (theta:t),
(n = (k + (width circ))%Z) -> (real_ theta) ->
((0%Z < k)%Z /\ (k < n)%Z) -> (is_a_ket_l y (n - k)%Z) ->
(eigen circ y (real_to_ang theta)) ->
((width (apply_black_box circ k n y theta)) = n) /\
((pat_sem (apply_black_box circ k n y theta) (kronecker (ket k 0%Z) y)) =
(kronecker
(infix_asdtdt (pow_inv_sqrt_2 k)
(ket_sum_l (n_bvs k)
(fun (x:bitvec) =>
(infix_asdtdt
(ang_exp (real_to_ang (infix_asdt theta (i_to_t (bv_to_int x)))))
(bv_to_ket x)))
k))
y)).
Parameter discard_black_box:
circuit -> Z -> Z -> (matrix t) -> t -> matrix t.
Axiom discard_black_box_def :
forall (circ:circuit) (k:Z) (n:Z) (y:matrix t) (theta:t),
(n = (k + (width circ))%Z) -> (real_ theta) ->
((0%Z < k)%Z /\ (k < n)%Z) -> (is_a_ket_l y (n - k)%Z) ->
(eigen circ y (real_to_ang theta)) ->
((discard_black_box circ k n y theta) =
(discard
(infix_asdtdt (pow_inv_sqrt_2 k)
(ket_sum_l (n_bvs k)
(fun (x:bitvec) =>
(infix_asdtdt
(ang_exp (real_to_ang (infix_asdt theta (i_to_t (bv_to_int x)))))
(bv_to_ket x)))
k))
y (pat_sem (apply_black_box circ k n y theta) (kronecker (ket k 0%Z) y))
k n)).
Axiom discard_black_box_spec :
forall (circ:circuit) (k:Z) (n:Z) (y:matrix t) (theta:t),
(n = (k + (width circ))%Z) -> (real_ theta) ->
((0%Z < k)%Z /\ (k < n)%Z) -> (is_a_ket_l y (n - k)%Z) ->
(eigen circ y (real_to_ang theta)) ->
((discard_black_box circ k n y theta) =
(infix_asdtdt (pow_inv_sqrt_2 k)
(ket_sum_l (n_bvs k)
(fun (x:bitvec) =>
(infix_asdtdt
(ang_exp (real_to_ang (infix_asdt theta (i_to_t (bv_to_int x)))))
(bv_to_ket x)))
k))) /\
((is_a_ket_l (discard_black_box circ k n y theta) k) /\
((pat_sem (apply_black_box circ k n y theta) (kronecker (ket k 0%Z) y)) =
(kronecker (discard_black_box circ k n y theta) y))).
Parameter circ: circuit.
Parameter k: Z.
Parameter n: Z.
Parameter y: matrix t.
Parameter theta: t.
Axiom H : (n = (k + (width circ))%Z).
Axiom H1 : real_ theta.
Axiom H2 : (0%Z < k)%Z.
Axiom H3 : (k < n)%Z.
Axiom H4 : eigen circ y (real_to_ang theta).
Axiom H5 :
forall (x:t) (z:t) (t1:t), forall (y1:Z), (real_ x) -> (real_ z) ->
(real_ t1) ->
((ang_add (real_to_ang (infix_asdt x (i_to_t y1)))
(real_to_ang (infix_asdt (infix_asdt (i_to_t y1) (prefix_mndt z)) t1)))
= (ang_mult_int (real_to_ang (infix_mndt x (infix_asdt z t1))) y1)).
Axiom H6 :
((discard_black_box circ k n y theta) =
(infix_asdtdt (pow_inv_sqrt_2 k)
(ket_sum_l (n_bvs k)
(fun (x:bitvec) =>
(infix_asdtdt
(ang_exp (real_to_ang (infix_asdt theta (i_to_t (bv_to_int x)))))
(bv_to_ket x)))
k))).
Axiom H7 : is_a_ket_l (discard_black_box circ k n y theta) k.
Axiom H8 :
((pat_sem (apply_black_box circ k n y theta) (kronecker (ket k 0%Z) y)) =
(kronecker (discard_black_box circ k n y theta) y)).
Axiom H9 :
((size (qft_rev k)) <= (polysquare k (2%Z * cont_size)%Z 0%Z 0%Z))%Z.
Axiom H10 : ((ancillas (qft_rev k)) = 0%Z).
Axiom H11 : ((ancillas (qft_rev k)) = 0%Z).
Axiom H12 : ((width (qft_rev k)) = k).
Axiom H13 : cont_zh (qft_rev k).
Axiom H14 : ((zh_range (qft_rev k)) = k).
Axiom H15 :
forall (x:bitvec) (y1:bitvec), ((length x) = k) -> ((length y1) = k) ->
((zh_ang_coeff_neg (qft_rev k) x y1) =
(ind_isum
(fun (l:Z) =>
(ind_isum
(fun (k1:Z) =>
((((getbv x) k1) * ((getbv y1) l))%Z *
(power_ 2%Z (((k - k1)%Z - 1%Z)%Z + l)%Z))%Z)
l k))
0%Z k)).
Axiom H16 :
forall (x:bitvec) (y1:bitvec), ((length x) = k) -> ((length y1) = k) ->
((zh_ang (qft_rev k) x y1) =
(int_to_ang (-((bv_to_int x) * (bv_to_int (bv_inversion y1)))%Z)%Z k)).
Axiom H17 :
forall (x:bitvec) (y1:bitvec), ((length x) = k) -> ((length y1) = k) ->
((zh_ang (qft_rev k) x y1) =
(real_to_ang
(infix_asdt
(infix_asdt (i_to_t (bv_to_int x))
(i_to_t (-(bv_to_int (bv_inversion y1)))%Z))
(pow_inv_2 k)))).
Axiom H18 :
forall (x:bitvec) (y1:bitvec), ((length x) = k) -> ((length y1) = k) ->
forall (i:Z), ((0%Z <= i)%Z /\ (i < k)%Z) ->
((zh_ket_i (qft_rev k) x y1 i) = ((getbv y1) i)).
Parameter result32: matrix t.
Axiom result_def32 :
(result32 = (pat_sem (qft_rev k) (discard_black_box circ k n y theta))).
Axiom H19 : is_a_ket_l result32 (width (qft_rev k)).
Axiom H20 : is_a_ket_l result32 k.
Parameter e1: bitvec.
Axiom H21 : mem e1 (n_bvs k).
Parameter e2: bitvec.
Axiom H22 : mem e2 (n_bvs k).
(* Why3 goal *)
Theorem G :
is_a_ket_l
(infix_asdtdt
(infix_asdt
(ang_exp (real_to_ang (infix_asdt theta (i_to_t (bv_to_int e1)))))
(qft_rev_coeff e1 e2 k))
(bv_to_ket e2))
k.
Proof.
Qed.
|
(* Andrew W. Appel and Stephen Yi-Hsien Lin,
May 2013, October 2013, March 2014 *)
Require Recdef.
Require Import Integers.
Require Import Coqlib.
Require Import Coq.Strings.String.
Require Import Coq.Strings.Ascii.
Require Import List.
Notation "[ ]" := nil.
Notation "[ x , .. , y ]" := (cons x .. (cons y []) ..).
Transparent Int.repr.
Check skipn.
Print skipn.
Eval compute in skipn 2 [1, 2, 3, 4].
Lemma skipn_length:
forall {A} n (al: list A),
(length al >= n)%nat ->
(length (skipn n al) = length al - n)%nat.
Proof.
induction n; destruct al; simpl; intros; auto.
apply IHn; omega.
Qed.
Lemma skipn_length_short:
forall {A} n (al: list A),
(length al < n)%nat ->
(length (skipn n al) = 0)%nat.
Proof.
induction n; destruct al; simpl; intros; auto.
omega.
apply IHn. omega.
Qed.
(* PREPROCESSING: CONVERTING STRINGS TO PADDED MESSAGE BLOCKS *)
Print string.
Print Z.of_N.
(*converting a string to a list of Z *)
Fixpoint str_to_Z (str : string) : list Z :=
match str with
|EmptyString => nil
|String c s => Z.of_N (N_of_ascii c) :: str_to_Z s
end.
Eval compute in str_to_Z "abc".
Print Int.repr.
Print Int.shl.
(*combining four Z into a Integer*)
(* list nl of byte values -- if length nl is a multiple of 4, easy to define corresponding list of bid-endian 32-bit integers *)
(* ?!?! TODO *)
Transparent Int.repr Int.or Int.shl.
(* is there a bitstring rep? that might make things clearer *)
Definition Z_to_Int (a b c d : Z) : Int.int :=
Int.or
(Int.or (Int.or
(Int.shl (Int.repr a) (Int.repr 24))
(Int.shl (Int.repr b) (Int.repr 16))
)
(Int.shl (Int.repr c) (Int.repr 8))
)
(Int.repr d).
(* TODO prove lemma about Z_to_int? *)
Transparent Z_to_Int.
Eval compute in Int.repr 24.
Eval compute in Int.or (Int.repr 24) (Int.repr 10).
Check Int.shl.
Eval compute in Int.shl (Int.repr 4) (Int.repr 1). (* 8 *)
Eval compute in Int.shl (Int.repr 4) (Int.repr 8). (* 8 *)
(* Eval compute in Z_to_Int 0. *)
Eval compute in
Int.or (Int.or (Int.or (Int.shl (Int.repr 0) (Int.repr 24)) (Int.shl (Int.repr 0) (Int.repr 16)))
(Int.shl (Int.repr 0) (Int.repr 8))) (Int.repr 900). (* ??? but generate_and_pad works fine *)
Print Int.repr.
Print Int.Z_mod_modulus.
Print Int.wordsize. Print Wordsize_32.wordsize. (* 32 *)
Print Int.P_mod_two_p. (* ??? *)
Print positive.
Goal Int.repr 5 = Z_to_Int 2 0 0 0.
unfold Z_to_Int.
unfold Int.repr.
simpl.
unfold Int.or.
simpl.
unfold Int.repr.
unfold Int.shl.
simpl. (* this can eval Z_to_Int just fine... *)
(* is it actually an error for one of these to be > 8 bytes? (256 bits) *)
(*
1 0 0 0 = 16777216
0 1 0 0 = 65526
0 0 257 0 = 65792
0 0 1 0 = 256
0 0 0 257 = 257
0 0 0 2 = 2
0 0 0 1 = 1
*)
(* TODO maybe better with coq bitstrings?? *)
(* takes 4 big-endian bytes (each byte is 8 bits -> 32 bits -> 1 32-bit int, or 1 word)
so anyway, the result is (len nl) / 4 (int division)
*)
(* so is nl always a multiple of 4? yes, but ... you assumed that msg was a multiple of 4
TODO: prove
InWords (msg ++ [128%Z] (* 1 *) ++ list_repeat (Z.to_nat (-(n + 9) mod 64)) 0)
(is multiple of 4)
*)
Fixpoint Zlist_to_intlist (nl: list Z) : list int :=
match nl with
| h1::h2::h3::h4::t => Z_to_Int h1 h2 h3 h4 :: Zlist_to_intlist t
| _ => nil
end.
Eval compute in Int.repr (2^24).
Eval compute in Int.intval (Int.repr (2^24)).
Eval compute in Zlist_to_intlist [2, 0, 0, 0, 0, 0, 0, 1].
Print Z.to_nat.
Eval compute in (-5) mod 64.
(* TODO: figure out length of list_repeat *)
Definition generate_and_pad msg :=
let n := Zlength msg in
Zlist_to_intlist (msg ++ [128%Z] (* 1 *)
++ list_repeat (Z.to_nat (-(n + 9) mod 64)) 0) (* 00...0 *)
++ [Int.repr (n * 8 / Int.modulus), Int.repr (n * 8)]. (* length? in bytes *)
Eval compute in generate_and_pad [1].
Check generate_and_pad.
Definition lenint (n : Z) : list int :=
[Int.repr (n * 8 / Int.modulus), Int.repr (n * 8)]
.
Eval compute in lenint 4.
Eval compute in map Int.unsigned (lenint 4).
Print Int.unsigned.
Print Int.intval.
(* TODO is there an Int_to_Z... *)
Lemma length_pad_z_int :
(* forall (n : Z), *)
[Int.repr (5 * 8 / Int.modulus), Int.repr (5 * 8)]
= Zlist_to_intlist [0, 0, 0, 0, 0, 0, 0, 0].
(* TODO figure out -- mult of 4? *)
Proof.
simpl.
unfold Z_to_Int.
unfold Int.repr.
simpl.
unfold Int.or.
simpl.
unfold Int.repr.
simpl.
Admitted.
Definition gap_nolen (msg : list Z) : list Z :=
let n := Zlength msg in
(msg ++ [128%Z] (* 1 *)
++ list_repeat (Z.to_nat (-(n + 9) mod 64)) 0) (* 00...0 *)
.
Check gap_nolen.
Definition gap_len (msg : list Z) : list int :=
let n := Zlength msg in
[Int.repr (n * 8 / Int.modulus), Int.repr (n * 8)]. (* length? in bytes *)
(* no length attached *)
Eval compute in gap_nolen [9, 9, 9].
(* 128%Z = ? *)
Fixpoint rep_helper {A : Type} (n : nat) (a : A) (l : list A) : list A :=
match n with
| 0%nat => l
| S n' => rep_helper n' a (a :: l)
end.
Definition rep {A : Type} (n : nat) (a : A) := rep_helper n a [].
Eval compute in rep_helper 10 5 [].
Eval compute in gap_len [1, 1, 1, 1].
(* if n * 8 > 2^32, then make it the first bit?? *)
Definition modl : nat := Z.to_nat Int.modulus.
Eval compute in gap_len (rep 200 2).
(* try doing rep modl 2, and Coq shuts down, even though rep_helper is tail-recursive *)
Print Zpos.
Check Zpos 5.
Print Z.
(* Inductive Z : Set := Z0 : Z | Zpos : positive -> Z | Zneg : positive -> Z *)
Print nat_iter.
Check (1%positive).
Print positive. (* ??? *)
Print Int.modulus. (* 2^32 *)
Print Int.wordsize.
Goal 2^32 = Int.modulus. (* neat! *)
unfold Int.modulus.
unfold Int.wordsize.
unfold Wordsize_32.wordsize.
(* stop here? *)
unfold two_power_nat.
unfold shift_nat.
(* unfold Zpos. *)
unfold nat_iter. (* ?? *)
reflexivity.
Qed.
Print Zlength_aux.
Transparent Int.repr.
Print Int.modulus.
Check Int.modulus.
Print Int.repr.
Check Int.repr.
(* block length? how to run? *)
(* can I change the spec? *)
Check generate_and_pad.
Eval compute in generate_and_pad nil.
Eval compute in map Int.unsigned (generate_and_pad nil).
Eval compute in length(map Int.unsigned (generate_and_pad [0])).
Eval compute in map Int.unsigned (generate_and_pad [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 999999, 99999, 99999, 9999]).
(* how do I make the resulting length change?? *)
Eval compute in generate_and_pad [0].
(* list Z -> list int *)
(* Zlength? *)
Theorem equal_pad_length : forall (msg1 : list Z) (msg2 : list Z),
msg1 = msg2 -> Zlength (generate_and_pad msg1) = Zlength (generate_and_pad msg2).
Proof.
intros m1 m2 H.
rewrite -> H.
reflexivity.
Qed.
(* might need to rephrase this theorem,
e.g. len m1 = a -> len m2 = a -> len (gap m1) = b -> len (gap m2) = b... etc *)
(* What is the actual length of the padded message *)
(* Would be very if msg were inductively defined as a :: b :: c :: d :: list...
nice induction on evidence (here we know msg % 4 = 0....)
*)
Theorem length_padded : forall (msg : list Z) (n : Z), (* or type nat? *)
Zlength msg = n -> Zlength (Zlist_to_intlist msg) = n / 4.
Proof.
Abort.
(* What is the actual length of the padded message *)
Theorem length_padded : forall (msg : list Z) (n : Z), (* or type nat? *)
Zlength msg = n -> Zlength (generate_and_pad msg) = n.
Proof.
Abort.
(* Theorem: length msg + 1 + length (repeat whatever -- TODO) + 2 *)
SearchAbout Zlength.
Lemma zlength_out : forall (l1 : list Z) (l2 : list Z),
Zlength (l1 ++ l2) = Zlength l1 + Zlength l2.
Proof.
intros l1 l2.
rewrite -> Zlength_correct.
rewrite -> Zlength_correct.
rewrite -> Zlength_correct.
induction l1 as [ | x xs].
(* l1 = nil *)
simpl. reflexivity.
(* l1 = x :: xs *)
simpl.
unfold Zlength.
simpl.
unfold Zlength in IHxs.
Admitted. (* ??? *)
(* i don't think InWords msg is actually a necessary implication
but it might make the proof a lot easier
*)
Inductive InWords : list Z -> Prop :=
| words_nil : InWords []
| words_word : forall (a b c d : Z) (msg : list Z),
InWords msg -> InWords (a :: b :: c :: d :: msg).
Lemma pad_inwords :
forall (msg : list Z),
InWords (msg ++ [128]
++ list_repeat (Z.to_nat (- (Zlength msg + 9) mod 64)) 0).
Proof.
intros msg.
Admitted.
Lemma zlength_intlist_zlist' :
forall (msg1 : list Z) (msg2 : list Z) (pad : list Z),
Zlength msg1 = Zlength msg2 ->
Zlength (Zlist_to_intlist (msg1 ++ pad)) =
Zlength (Zlist_to_intlist (msg2 ++ pad)).
Proof.
intros msg1 msg2 pad Hlen.
unfold Zlength.
unfold Zlist_to_intlist.
(* stuck *)
Admitted.
(* there are problems with Zlength too, especially the aux business *)
Lemma zlength_intlist_zlist :
forall (msg1 : list Z) (msg2 : list Z) (pad : list Z),
InWords (msg1 ++ pad) -> InWords (msg2 ++ pad) (* messy, fix *) ->
Zlength msg1 = Zlength msg2 ->
Zlength (Zlist_to_intlist (msg1 ++ pad)) =
Zlength (Zlist_to_intlist (msg2 ++ pad)).
Proof.
intros msg1 msg2 pad Hi1 Hi2 Hlen.
generalize dependent msg2.
induction Hi1.
intros msg2 Hi2 Hlen. induction Hi2. (* hmm, may have messed up double ind *)
reflexivity.
simpl. unfold Zlength. simpl. admit. (* contradiction *)
intros msg2 Hi2 Hlen. induction Hi2.
simpl. unfold Zlength. simpl. admit. (* contra *)
simpl.
unfold Zlength. simpl. unfold Zlength in IHHi2. simpl in IHHi2.
Admitted.
SearchAbout Zlength.
Print Zlength_aux.
(* TODO: would this lemma be easier if I rewrote generate and pad?
probably not
gap' =
Zlist_to_intlist
(msg ++ [128] ++ list_repeat (...) 0 ++ [lengthb1, lengthb2])
*)
Theorem length_equal_pad_length : forall (msg1 : list Z) (msg2 : list Z),
Zlength msg1 = Zlength msg2 ->
Zlength (generate_and_pad msg1) = Zlength (generate_and_pad msg2).
Proof.
intros m1 m2 H.
unfold generate_and_pad.
(* But Zlist_to_intlist is in the way :( *)
rewrite -> H.
Abort.
(* ------ *)
(* Lemma 1 *)
(* maybe prefix is easier... *)
(* but message is *not* a prefix of the padded list, since it's Z list?
or, ok, intlist msg = Prefix (generate_and_pad msg)?
*)
Inductive Prefix {X : Type} : list X -> list X -> Prop :=
| p_nil : forall (l : list X), Prefix [] l
| p_self : forall (l : list X), Prefix l l
| p_cons : forall (l1 l2 : list X) (x : X), Prefix l1 l2 -> Prefix (x :: l1) (x :: l2)
| p_append : forall (l1 l2 : list X) (l3 : list X), Prefix l1 l2 -> Prefix l1 (l2 ++ l3)
| p_trans : forall (l1 l2 l3 : list X), Prefix l1 l2 -> Prefix l2 l3 -> Prefix l1 l2.
(* might want to prove some of these... too powerful *)
(* TODO *)
(* computational... (++) is not a constructor *)
Inductive Msg {X : Type} : Type :=
| Empty : Msg
| Word : X -> X -> X -> X -> Msg -> Msg.
(* not [Msg X -> Msg X]? *)
(* is this less efficient than list Z? nah *)
(* this is true for all msgs of type 4-block message, but not in general,
since Zlist_to_intlist throws away trailing chunkc % 4 *)
(* TODO: define a 4-block message? *)
Theorem Zlist_to_intlist_dist : forall (l1 l2 : list Z),
InWords l1
-> Zlist_to_intlist (l1 ++ l2) = Zlist_to_intlist l1 ++ Zlist_to_intlist l2.
(* Prefix (Zlist_to_intlist l1) (Zlist_to_intlist l1 ++ l2) instead?? *)
Proof.
intros l1 l2 Ewords.
induction Ewords.
(* words_nil *)
reflexivity.
(* words_word *)
simpl.
rewrite -> IHEwords.
reflexivity.
Qed.
Lemma Zlist_to_intlist_prefix : forall (l1 l2 : list Z),
InWords l1 ->
Prefix (Zlist_to_intlist l1) (Zlist_to_intlist (l1 ++ l2)).
Proof.
intros l1 l2 Ewords.
induction Ewords.
(* words_nil *)
simpl. apply p_nil.
(* words_word *)
simpl. apply p_cons. apply IHEwords.
Qed.
(* TODO add case ltac *)
Theorem message_prefix_padded' : forall (msg : list Z),
InWords msg -> Prefix (Zlist_to_intlist msg) (generate_and_pad msg).
Proof.
intros msg Ewords.
induction Ewords. (* fix names *)
(* words_nil *)
simpl. apply p_nil.
(* words_word *)
unfold generate_and_pad.
simpl.
apply p_cons.
apply p_append.
apply Zlist_to_intlist_prefix.
apply Ewords.
Qed.
(* TODO rewrite with implication? *)
(* OK, the premise is flawed, because we never do Zlist_to_intlist msg.
so we don't need InWords msg technically. But then how can we prove prefix?
is this good enough?
*)
Theorem message_prefix_padded : forall (msg : list Z),
Prefix (Zlist_to_intlist msg) (generate_and_pad msg).
Proof.
intro msg.
unfold generate_and_pad.
apply p_append.
induction msg as [ | x xs].
(* msg = [] *)
apply p_nil.
(* msg = x :: xs *)
simpl.
Admitted.
(* TODO: separate generate_and_pad function to generate . pad *)
(*ROUND FUNCTION*)
(*hardcoding the constants, first 32 bits of the fractional parts of the cube roots of the first 64 prime numbers*)
Print Int.repr.
Print Int.int.
Definition K256 := map Int.repr
[1116352408 , 1899447441, 3049323471, 3921009573,
961987163 , 1508970993, 2453635748, 2870763221,
3624381080, 310598401 , 607225278 , 1426881987,
1925078388, 2162078206, 2614888103, 3248222580,
3835390401, 4022224774, 264347078 , 604807628,
770255983 , 1249150122, 1555081692, 1996064986,
2554220882, 2821834349, 2952996808, 3210313671,
3336571891, 3584528711, 113926993 , 338241895,
666307205 , 773529912 , 1294757372, 1396182291,
1695183700, 1986661051, 2177026350, 2456956037,
2730485921, 2820302411, 3259730800, 3345764771,
3516065817, 3600352804, 4094571909, 275423344,
430227734 , 506948616 , 659060556 , 883997877,
958139571 , 1322822218, 1537002063, 1747873779,
1955562222, 2024104815, 2227730452, 2361852424,
2428436474, 2756734187, 3204031479, 3329325298].
Eval compute in Int.repr 1116352408.
(*functions used for round function*)
Definition Ch (x y z : int) : int :=
Int.xor (Int.and x y) (Int.and (Int.not x) z).
Definition Maj (x y z : int) : int :=
Int.xor (Int.xor (Int.and x z) (Int.and y z) ) (Int.and x y).
Definition Rotr b x := Int.ror x (Int.repr b).
Definition Shr b x := Int.shru x (Int.repr b).
Definition Sigma_0 (x : int) : int :=
Int.xor (Int.xor (Rotr 2 x) (Rotr 13 x)) (Rotr 22 x).
Definition Sigma_1 (x : int) : int :=
Int.xor (Int.xor (Rotr 6 x) (Rotr 11 x)) (Rotr 25 x).
Definition sigma_0 (x : int) : int :=
Int.xor (Int.xor (Rotr 7 x) (Rotr 18 x)) (Shr 3 x).
Definition sigma_1 (x : int) : int :=
Int.xor (Int.xor (Rotr 17 x) (Rotr 19 x)) (Shr 10 x).
(* word function *)
Function W (M: Z -> int) (t: Z) {measure Z.to_nat t} : int :=
if zlt t 16
then M t
else (Int.add (Int.add (sigma_1 (W M (t-2))) (W M (t-7)))
(Int.add (sigma_0 (W M (t-15))) (W M (t-16)))).
Proof.
intros; apply Z2Nat.inj_lt; omega.
intros; apply Z2Nat.inj_lt; omega.
intros; apply Z2Nat.inj_lt; omega.
intros; apply Z2Nat.inj_lt; omega.
Qed.
(*registers that represent intermediate and final hash values*)
Definition registers := list int.
Fixpoint map2 {A B C: Type} (f: A -> B -> C) (al: list A) (bl: list B) : list C :=
match al, bl with
| a::al', b::bl' => f a b :: map2 f al' bl'
| _, _ => nil
end.
(*initializing the values of registers, first thirty-two bits of the fractional
parts of the square roots of the first eight prime numbers*)
Definition init_registers : registers :=
map Int.repr [1779033703, 3144134277, 1013904242, 2773480762,
1359893119, 2600822924, 528734635, 1541459225].
Definition nthi (il: list int) (t: Z) := nth (Z.to_nat t) il Int.zero.
Definition rnd_function (x : registers) (k : int) (w : int) : registers:=
match x with
| [a, b, c, d, e, f, g, h] =>
let T1 := Int.add (Int.add (Int.add (Int.add h (Sigma_1 e)) (Ch e f g)) k) w in
let T2 := Int.add (Sigma_0 a) (Maj a b c) in
[Int.add T1 T2, a, b, c, Int.add d T1, e, f, g]
| _ => nil (* impossible *)
end.
Function Round (regs: registers) (M: Z ->int) (t: Z)
{measure (fun t => Z.to_nat(t+1)) t} : registers :=
if zlt t 0 then regs
else rnd_function (Round regs M (t-1)) (nthi K256 t) (W M t).
Proof. intros; apply Z2Nat.inj_lt; omega.
Qed.
Definition hash_block (r: registers) (block: list int) : registers :=
map2 Int.add r (Round r (nthi block) 63).
Function hash_blocks (r: registers) (msg: list int) {measure length msg} : registers :=
match msg with
| nil => r
| _ => hash_blocks (hash_block r (firstn 16 msg)) (skipn 16 msg)
end.
Proof. intros.
destruct (lt_dec (length msg) 16).
rewrite skipn_length_short. simpl; omega. rewrite <- teq; auto.
rewrite skipn_length. simpl; omega. rewrite <- teq; omega.
Qed.
Fixpoint intlist_to_Zlist (l: list int) : list Z :=
match l with
| nil => nil
| i::r =>
Int.unsigned (Shr 24 i) ::
Int.unsigned (Int.and (Shr 16 i) (Int.repr 255)) ::
Int.unsigned (Int.and (Shr 8 i) (Int.repr 255)) ::
Int.unsigned (Int.and i (Int.repr 255)) ::
intlist_to_Zlist r
end.
(* ---------- Lemma 2 *)
Eval compute in intlist_to_Zlist [Int.repr 256].
Eval compute in intlist_to_Zlist [Int.repr 512].
Eval compute in intlist_to_Zlist [Int.repr 1024].
Eval compute in intlist_to_Zlist [Int.repr 2048].
Eval compute in intlist_to_Zlist [Int.repr 4096].
Definition g_a_p msg :=
let n := Zlength msg in
Zlist_to_intlist (msg ++ [128%Z] (* 1 *)
++ list_repeat (Z.to_nat (-(n + 9) mod 64)) 0) (* 00...0 *)
++ [Int.repr (n * 8 / Int.modulus), Int.repr (n * 8)]. (* length? in bytes *)
Eval compute in length (g_a_p [1]). (* 16 32 bit ints * 32 = 512 bits = 2 blocks *)
Eval compute in map Int.unsigned (g_a_p [1]). (* 16 32 bit ints * 32 = 512 bits = 2 blocks *)
(* TODO types *)
Definition pad (msg : list Z) : list Z :=
let n := Zlength msg in
msg ++ [128%Z]
++ list_repeat (Z.to_nat (-(n + 9) mod 64)) 0
++ intlist_to_Zlist ([Int.repr (n * 8 / Int.modulus), Int.repr (n * 8)]).
Definition g_a_p' (msg : list Z) : list int :=
Zlist_to_intlist (pad msg).
Transparent Int.repr Int.or Int.shl Int.and.
SearchAbout app. (* app_assoc, app_assoc_reverse *)
Lemma app_left : forall (a b c d : list Z),
a ++ b ++ c ++ d = (a ++ b ++ c) ++ d.
Proof.
intros a b c d.
(* rewrite -> app_assoc. do later*)
Admitted.
Definition fulllen (len : Z) :=
len + 1%Z + (- (len + 9) mod 64). (* = -8 mod 64 = 56 mod 64??? not quite *)
Eval compute in fulllen 10. (* + 8 = 64 *)
Eval compute in fulllen 1.
Eval compute in fulllen 0.
Eval compute in fulllen 100. (* + 8 = 128 *)
Eval compute in fulllen 200. (* + 8 = 256 *)
(* SHA-256 = block size 256 bits = 32 bit words (256 bits / (8 bits / byte) = 32 bytes?*)
(* Zlist to intlist: each Z is a byte; 4 bytes = 32 bit integer *)
Eval compute in
Theorem gap_compose_equal : forall (msg : list Z),
g_a_p' msg = generate_and_pad msg.
Proof.
intros msg.
unfold g_a_p'. unfold pad.
unfold generate_and_pad.
(* simpl. *) (* TODO doesn't work *)
pose proof pad_inwords as pad_inwords.
specialize (pad_inwords msg).
remember (msg ++
[128] ++
list_repeat (Z.to_nat (- (Zlength msg + 9) mod 64)) 0) as pad_nolen.
rewrite -> app_left.
rewrite <- Heqpad_nolen.
induction pad_inwords.
(* case none *)
(* simpl. *) (* ? *)
inversion Heqpad_nolen. (* ? *)
(* x : list int
InWords (a ++ b ++ ... ++ c) ->
Zlist_to_intlist (a ++ b ++ ... ++ c ++ intlist_to_Zlist x)
= Zlist_to_intilst (a ++ b ++ ... ++ c) ++ x *)
(* see pad_inwords *)
Admitted.
Eval compute in g_a_p' [1].
Check g_a_p'.
Theorem prefix : forall (msg : list Z),
Prefix msg (pad msg).
Proof.
intros msg.
unfold pad.
apply p_append.
apply p_self.
Qed.
(* --------- Lemma 2 ^ *)
Definition SHA_256 (str : list Z) : list Z :=
intlist_to_Zlist (hash_blocks init_registers (generate_and_pad str)).
|
-- TODO: Move some of the proofs from Function.Iteration.Proofs to here so that (_^_) on functions, natural numbers and integers can be generalised.
-- TODO: Maybe something like this
record Iteration(f)(id)(repeat : I → Y) where
field
𝟎 : I
repeat-𝟎 : repeat 𝟎 ≡ id
record Successor(𝐒 : I → I) where
field proof : repeat(𝐒(i)) ≡ f(repeat(i))
record Predecessor(𝐏 : I → I) where
field proof : f(repeat(𝐏(i))) ≡ repeat(i)
|
\section{Introduction}\label{introduction}
In the literature review there is a previous discussion about how three meteorological factors (radiation, temperature, and water) limit photosynthesis, however as already discussed, LSMs treat limiting regimes of photosynthesis based on the Farquhar model \citep{Farquhar1980}, which assumes photosynthesis is given by the co-limitation of three regimes: carbon, light, and electron transport. So, the first research question to be adressed by this chapter is: how photosynthesis limiting regimes are distributed around the globe according to the Farquhar model in JULES? This question will be addressed in different perspectives: first, the total photosynthetic limiting regime, or the integrated limiting regime of photosynthesis through the multilayered vertical canopy. This first analysis gives a spatial and temporal perspective of Farquhar limiting regimes distribution around the world, however it does not tell us much about total values of carbon assimilation because the model does not calculate GPP as the integrated limitation of different regimes, but it does calculates the limiting regimes per layer. This first approximation to the question is analytical and it shows how the inclusion of vegetation canopy architecture in the radiative transfer scheme impacts photosynthetic limiting regimes. Furthermore, what are the regions on the planet where these impacts occur and when?
`One interesting approach to this question is to relate how the meteorological variables limit photosynthesis and how the Farquhar model limits photosynthesis. Are they related anyhow? Where are they related and where aren't they related? Why? My point is that the Farquhar limiting regime is analogous to the limitation by meteorological variables: carbon - water, light - radiation, and transport - temperature.'
It is interesting to evaluate how the distribution of limiting regimes varies through the year. The first proprosition of how to tackle this point is by making a three month average (MAM,JJA,SON, and DJF) and show the differences. Discuss how the limitation changes through the seasons.
Secondly, to understand the real impact of canopy structure on the different limiting regimes is to look at the vertical profile of limiting regimes. The fisrt section shows how JULES is seeing the impact of canopy architecture on the 3D spatial and temporal Farquhar limiting regimes around the globe.
The second section might go to chapter 5 or might stay in chapter 6. Well, we are looking at photosynthesis limiting regimes distribution spatialy, horizontaly and verticaly, and temporaly around the whole globe within a 0.5$^{\circ}$ resolution over land, but now we are going to compare these gridboxes with 12 sites with fluxnet data to verify if that is a valid approximation. You will have to get the 2008 flux tower data for each one of your study sites and run JULES with the same configuration (GL4.0) with 5 spiun up cycles for the whole year, and compare with the global data set. After that you are going to pick up on latitude and longitude of each specific site. Probably you will have to drop off one canopy radiation scheme in JULES, and as previously discussed in monitoring committee, it will be option mainly because is less sensitive to canopy structure and we know why. It is less sensitive because it does not treat different leaf types (sunlit vs. shaded) in distinct ways and in reality we know that these two types of leaves behave significantly different when assimilating carbon.
In this part you compare clumping index and structure factor from DHP, and global data with clumping map from MODIS and WFDEI and comparing with FLUXNET GPP to answer the question: which one has the best agreement? Are the agreement dependent on LAI? PFT? And what else? Is using only a is a good approximation for these sites? Is clumping index from DHPs comparable to the ones obtained from MODIS? Where is it valid? Where is not valid? What is the magnitude of error associated with a non zenith variant global clumping index map? The importance of performing these evaluation at site level is related to the determination of how applicable is the use of a global index map to calculate photosynthesis, and wether or not should the results be less trusted. This section presents an uncertainty analysis.
Now, with the uncertainty analysis performed in the previous section we have a good understanding of wether or not we should trust the model outputs from global JULES driven with MODIS clumping index global map. Even though all evaluated sites are located in the northern hemisphere, they cover a variety of PFTs and present different associate values of LAI. We know that over sparser areas, a non-zenith variant clumping index is usually a good representation of canopy architecture heterogeneities for shortwave radiation propagation, but if LAI is high than the parameter $b$ is more important, and then it is important to think about how to consider the results over Amazon, for example, because over tropical forest LAI is so high and we consider the impact of structure we need to be more careful.
So, basically in the third section I am going to create a map of clumping globally (?)
Finally, we want to validate the new results of global GPP with clumping globally with the MTE dataset, how is it improving the results? Three months period, it is important to talk about PFTs.
The conclusions of this chapter should indicate the regions in the world where canopy architectural variability is most impacting on carbon assimilation. what is the PFT who suffer most variations? is there any relation with LAI? How does seasonality impact the results? How does LAI impact these results? and How does diffuse radiation impact the results? Should we consider diffuse radiation as well? Or not? That is the general idea of chapter 6.
\section{The distribution of Farquhar limiting regimes around the globe}\label{section:limiting_regimes}
\subsection{The spatial distribution of Farquhar limiting regimes}
Previous studies have shown the geographic distribution of potential climatic constraints to global GPP derived from long-term climate statistics \citep{nemani2003}, or even these representations in LSMs \citep{anav2015}, but there is no studies looking at spatial-temporal distribution of the Farquhar limiting regimes of photosynthesis throughout the globe or its linkage to the Farquhar limiting regimes. This section presents the results of a global evaluation of the distribution of photosynthesis limiting regimes according to the Farquhar model and the impacts of including a parameterisation of vegetation canopy structure in JULES.
Figure~\ref{f:limiting_regimes_spatial_global} shows the verticaly integrated limiting regime of photosynthesis according to the Farquhar model averaged for the year of 2008. It is difficult to realise the differences between Figure~\ref{f:limiting_regimes_spatial_global}a and b because they present roughly the same spatial distribution of vertically integrated photosynthesis limiting regimes.
In both figures it is possible to notice that the tropics are mostly limited by light because temperature and humidity are higher, with few exceptions over drier areas, e.g., the West of the Andes in South America, the `caatinga' ecoregion in Northeast Brazil, the Namib desert in Southwest Africa and parts of the Somali desert also in Africa, as well as in sparse regions of Australia. Mid-latitudes are mostly limited by carbon, which indicates stronger dependence of photosynthesis on precipitation and temperature, with exceptions for the Eastern USA and the boreal forest over Canada and North Europe and Asia, which have photosynthesis mostly limited by light in the default version of JULES, but change the limiting regime to mostly carbon limited when vegetation canopy structure is considered through the inclusion of a global clumping map. Very high latitudes are limited by electron export, which is an indication of photosynthesis mostly controled by temperature.
In the default version of JULES for the integrated vertical limiting regimes averaged for the year of 2008, 52.15\% of the gridboxes over the globe are light limited, 43.32\% of them are carbon limited, and the remaining 4.53\% are limited by electron export. When the structure parameterisation is applied on the two-stream radiative transfer scheme of the model driven by the global MODIS clumping index map \citep{He2012} isolated per PFTs, there is a shift of average Farquhar limiting regimes for photosynthesis, where 42.87\% of the gridboxes over the globe are now limited by light, 51.54\% are carbon limited, and 5.59\% are limited by temperature.
The consideration of vegetation canopy structure on the radiative transfer scheme in JULES gives a difference answer for the total distribution of Farquhar limiting regimes of photosynthesis through the planet with major impact in the Northern Hemisphere, especially over the boreal forests. The consideration of forest architecture predicts that 9.28\% of the gridboxes over the world are not limited by light but from those and extra 8.22\% are limited by carbon and 1.06\% are limited by electron transport (Figure~\ref{f:limiting_regimes_spatial_global}c).
\begin{figure}[ht!]
\centering
\begin{tabular}{ll}
\subfloat[Opt 5]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/Farquhar_year_total_opt5_integral.png}}
\subfloat[Opt 5 clump]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/Farquhar_year_total_opt5_clump_integral.png}}
\end{tabular}
\subfloat[Difference]{\includegraphics[width=1.0\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/Farquhar_year_total_opt5_clump_integral_diff.png}}
\caption{Spatial distribution of the Farquhar limiting regimes of photosynthesis for the year of 2008 according to a. the default JULES, and b. JULES with clumping; c. shows the regions where the limiting regimes changed from the default version to the version with clumping in JULES. The actual limiting regimes of difference are associated with the version considering canopuy structure.}
\label{f:limiting_regimes_spatial_global}
\end{figure}
%These comments below were adapted from http://globalforestatlas.yale.edu/boreal-forest/boreal-ecoregions-ecology/boreal-forest-ecology
Boreal forests must withstand very harsh conditions, which include long winters and short summers. Also these forests are located in very high latitudes which means very high Sun zenith angles all over the year, which can be translated to very limited amounts of total radiation. Therefore tree species that inhabit boreal forests have adaptations that help them to maximise photosynthesis under such a naturally light limited enviroment. Boreal forests are mostly dominated by needle-leaved species and most of them are evergreen conifers, allowing these trees to begin photosynthesizing early in the spring when temperatures are favorable, rather than wasting valuable time to grow new leaves. These needled coniferous species also display more leaves per unit area than deciduous broadleaved species do. The needles tend to be angled to the Sun, allowing them to use light for photosynthesis more efficiently, which is beneficial where cold temperatures already constrain photosynthesis. Most conifers are cone-shaped, which allows branches and needles to receive more direct sunlight without shading other branches. Having a conical shape is especially useful for receiving sunlight that comes from a steep angle at these high boreal latitudes.
In fact, it is well documented that needle-leaf trees evolved under inhospitable climate conditions with low availability of radiation, and therefore they way they assimilate carbon should not be limited by light availabilty, but other conditions, e.g., extreme cold temperatures, or very dry summers. Of course the adaptations of the boreal forests are not only constrained to lower light availability. For example, the narrowness of the needles reduces the surface area of water loss, which is important where cold and dry conditions prevent trees from replenishing their water from the ground. Needle-leaves also have a thick waxy coating called a cuticle that helps prevent water loss and protects inner leaf architecture from desiccation and abrasive winds. Other adaptations are reflected in their wood anatomy and water transport system, which is well suited to withstand cold and dry conditions. In fact, broadleaf species tend to outcompete conifers on more favorable sites, thus relegating conifers to the more inhospitable sites. Also its shape prevents snow from piling on branches and it helps to keep these shallow-rooted trees sturdy in windy conditions.
Althought it is hard to say what is the average photosynthesis limiting regime according to the Farquhar model for Boreal forests, it is unlikely that these ecosystems would be light limited given their evolutionary characteristics of canopy and leaf architecture. Perhaps most importantly, it is not straighforward the relation between climatic variables and the Farquhar limiting regimes of photosynthesis.
In order to estimate the consistency between the limiting regimes according to the Farquhar model and the climatic variables constratining photosynthesis, the MTE-GPP product together with the WFDEI reanalysis dataset of shortwave incident radiation, air temperature, and the CRU precipitation products were monthly correlated at 0.5$^{\circ}$ gridbox level for the year of 2008 over the globe. The variability caused by each climatic factor (i.e., radiation, temperature, and precipitation) is assessed through the square of monthly temporal correlation coefficients between the MTE-GPP product and the climatic controls. Figure~\ref{f:climatic_control_spatial_global} indicates the areas of maximum $r^2$ related to climatic drivers.
\begin{figure}[ht!]
\centering
\begin{tabular}{lll}
\subfloat[Radiation]{\includegraphics[width=0.33\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/r2_gpp_mte_radiation.png}}
\subfloat[Temperature]{\includegraphics[width=0.33\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/r2_gpp_mte_temp.png}}
\subfloat[Precipitation]{\includegraphics[width=0.33\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/r2_gpp_mte_precip.png}}
\end{tabular}
{\includegraphics[width=1.0\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/Climatic_year_total_mte.png}}
\caption{Spatial distribution of climatic controls on interannual variation of GPP for the year of 2008.}
\label{f:climatic_control_spatial_global}
\end{figure}
The interannual variability of MTE-GPP over Boreal forests is mostly controlled by temperature and precipitation, and not radiation. Even though climatic factors cannot be directly translated to Farquhar limiting regimes, that is an indicator that Northern latitudes occupied by Boreal forests present photosynthesis limited by other factor than light.
\section{The impacts of clumping map on GPP}\label{section:gpp_distribution}
\begin{figure}[ht!]
\centering
\subfloat[MTE]{\includegraphics[width=0.8\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/mte_0_MR_year.png}}
\begin{tabular}{ll}
\subfloat[Opt 4]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_opt4_year.png}}
\subfloat[Opt 4 clump]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_opt4_clump_year.png}}
\end{tabular}
\begin{tabular}{ll}
\subfloat[Opt 5]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_opt5_year.png}}
\subfloat[Opt 5 clump]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_opt5_clump_year.png}}
\end{tabular}
\begin{tabular}{ll}
\subfloat[Opt 4 - MTE]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_diff_opt4_MTE_year.png}}
\subfloat[Opt 4 clump - MTE]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_diff_opt4_clump_MTE_year.png}}
\end{tabular}
\begin{tabular}{ll}
\subfloat[Opt 5 - MTE]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_diff_opt5_MTE_year.png}}
\subfloat[Opt 5 clump - MTE]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_diff_opt5_clump_MTE_year.png}}
\end{tabular}
\caption{Total average GPP for the year of 2008.}
\label{f:pgap}
\end{figure}
\begin{figure}[ht!]
\centering
\begin{tabular}{ll}
\subfloat[Opt 4 - clump]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_improve_opt4_clump_MTE_year.png}}
\subfloat[Opt 5 - clump]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_improve_opt5_clump_MTE_year.png}}
\end{tabular}
\begin{tabular}{l}
\subfloat[GL4.0 - Opt 5 - clump]{\includegraphics[width=1.0\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_improve_GL4_opt5_clump_MTE_year.png}}
\end{tabular}
\caption{Green areas represent more agreement with the MTE dataset by considering clumping.}
\label{f:improve}
\end{figure}
The red areas on Figure~\ref{f:improve}b are related to a higher presence of C4 plants over South America and Africa, and with a minor impact over Australia.
\begin{figure}[ht!]
\centering
\begin{tabular}{ll}
\subfloat[BL]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/PFT_0.png}}
\subfloat[NL]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/PFT_1.png}}
\end{tabular}
\begin{tabular}{ll}
\subfloat[C3]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/PFT_2.png}}
\subfloat[C4]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/PFT_3.png}}
\end{tabular}
\subfloat[SH]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/PFT_4.png}}
\caption{Distribution of PFTs acording to frac file with global JULES.}
\label{f:pgap}
\end{figure}
\begin{figure}[ht!]
\centering
\subfloat[Gridbox]{\includegraphics[width=1.0\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/clump_PFT_5.png}}
\begin{tabular}{ll}
\subfloat[BL]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/clump_PFT_0.png}}
\subfloat[NL]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/clump_PFT_1.png}}
\end{tabular}
\begin{tabular}{ll}
\subfloat[C3]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/clump_PFT_2.png}}
\subfloat[C4]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/clump_PFT_3.png}}
\end{tabular}
\subfloat[SH]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/clump_PFT_4.png}}
\caption{Distribution of clumping index through PFTs acording to GLC2000 file with global JULES.}
\label{f:pgap}
\end{figure}
\begin{threeparttable}[ht!]
\centering
\caption{GLC-2000 land cover type to JULES Plant Functional type for clumping index map.}
%\begin{tabular*}{\textwidth}{ l@{\extracolsep{\fill}}*{4}{c}}
\begin{tabular}{l{0.25\textwidth} l{0.75\textwidth}}
%\begin{tabular}{\textwidth}{|p{\textwidth/4}|p{\textwidth/4}|p{\textwidth/4}|p{\textwidth/4}|}
%\begin{tabular*}
\hline
\hline
\textbf{GLC-2000 land cover} & \textbf{JULES PFT}\\
\noalign{\smallskip}\hline
Tree Cover, broadleaved, evergreen & Broadleaf\\
Tree Cover, broadleaved, deciduous, closed & Broadleaf\\
Tree Cover, broadleaved, deciduous, open & Broadleaf\\
Tree Cover, needle-leaved, evergreen & Needle-leaf\\
Tree Cover, needle-leaved, deciduous & Needle-leaf\\
Tree Cover, mixed leaf type & Broadleaf\\
Tree Cover, regularly flooded, fresh water & Broadleaf\\
Tree Cover, regularly flooded, saline water & Broadleaf\\
Mosaic: Tree cover / Other natural vegetation & Broadleaf\\
Tree Cover, burnt & Broadleaf\\
Shrub Cover, closed-open, evergreen & Shrub\\
Shrub Cover, closed-open, deciduous & Shrub\\
Herbaceous Cover, closed-open & C3\\
Sparse Herbaceous or sparse Shrub Cover & C3\\
Regularly flooded Shrub and/or Herbaceous Cover & C3\\
Cultivated and managed areas & C4\\
Mosaic: Cropland / Tree Cover / Other natural vegetation & C4\\
Mosaic: Cropland / Shrub or Grass Cover & C4\\
Bare Areas & \textit{NA}\\
Water Bodies & \textit{NA}\\
Snow and Ice & \textit{NA}\\
Artificial surfaces and associated areas & \textit{NA}\\
No data & \textit{NA}\\
\hline
\hline%\noalign{\bigskip}
%\end{tabular*}
\end{tabular}
\begin{tablenotes}
\small
\item \textit{NA}: Not applicable.
\end{tablenotes}
\label{tab:RAMI4PILPS}
\end{threeparttable}
\bigskip
\begin{figure}[ht!]
\centering
\begin{tabular}{ll}
\subfloat[Opt 4 - MTE]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_4_mte_filtered_2.png}}
\subfloat[Opt 4 clump - MTE]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_4_clump_mte_filtered_2.png}}
\end{tabular}
\begin{tabular}{ll}
\subfloat[Opt 4 - BL]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt4_pft_0_filtered_3.png}}
\subfloat[Opt 4 clump - BL]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt4_clump_pft_0_filtered_3.png}}
\end{tabular}
\begin{tabular}{ll}
\subfloat[Opt 4 - NL]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt4_pft_1_filtered_3.png}}
\subfloat[Opt 4 clump - NL]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt4_clump_pft_1_filtered_3.png}}
\end{tabular}
\caption{Comparison of JULES GPP through option 5 and the version with structure versus MTE applied only where the fraction of each gridbox is higher than 50\% for the year of 2008.}
\label{f:pgap}
\end{figure}
\begin{figure}[ht!]
\centering
\begin{tabular}{ll}
\subfloat[Opt 4 - C3]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt4_pft_2_filtered_3.png}}
\subfloat[Opt 4 clump - C3]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt4_clump_pft_2_filtered_3.png}}
\end{tabular}
\begin{tabular}{ll}
\subfloat[Opt 4 - C4]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt4_pft_3_filtered_3.png}}
\subfloat[Opt 4 clump - C4]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt4_clump_pft_3_filtered_3.png}}
\end{tabular}
\begin{tabular}{ll}
\subfloat[Opt 4 - SH]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt4_pft_4_filtered_3.png}}
\subfloat[Opt 4 clump - SH]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt4_clump_pft_4_filtered_3.png}}
\end{tabular}
\caption{Comparison of JULES GPP through option 5 and the version with structure versus MTE applied only where the fraction of each gridbox is higher than 50\% for the year of 2008.}
\label{f:pgap}
\end{figure}
\begin{figure}[ht!]
\centering
\begin{tabular}{ll}
\subfloat[Opt 5 - MTE]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_5_mte_filtered_2.png}}
\subfloat[Opt 5 clump - MTE]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_5_clump_mte_filtered_2.png}}
\end{tabular}
\begin{tabular}{ll}
\subfloat[Opt 5 - BL]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt5_pft_0_filtered_3.png}}
\subfloat[Opt 5 clump - BL]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt5_clump_pft_0_filtered_3.png}}
\end{tabular}
\begin{tabular}{ll}
\subfloat[Opt 5 - NL]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt5_pft_1_filtered_3.png}}
\subfloat[Opt 5 clump - NL]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt5_clump_pft_1_filtered_3.png}}
\end{tabular}
\caption{Comparison of JULES GPP through option 5 and the version with structure versus MTE applied only where the fraction of each gridbox is higher than 50\% for the year of 2008.}
\label{f:pgap}
\end{figure}
\begin{figure}[ht!]
\centering
\begin{tabular}{ll}
\subfloat[Opt 5 - C3]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt5_pft_2_filtered_3.png}}
\subfloat[Opt 5 clump - C3]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt5_clump_pft_2_filtered_3.png}}
\end{tabular}
\begin{tabular}{ll}
\subfloat[Opt 5 - C4]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt5_pft_3_filtered_3.png}}
\subfloat[Opt 5 clump - C4]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt5_clump_pft_3_filtered_3.png}}
\end{tabular}
\begin{tabular}{ll}
\subfloat[Opt 5 - SH]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt5_pft_4_filtered_3.png}}
\subfloat[Opt 5 clump - SH]{\includegraphics[width=0.5\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/adjust_opt5_clump_pft_4_filtered_3.png}}
\end{tabular}
\caption{Comparison of JULES GPP through option 5 and the version with structure versus MTE applied only where the fraction of each gridbox is higher than 50\% for the year of 2008.}
\label{f:pgap}
\end{figure}
\begin{figure}[ht!]
\centering\hspace*{-1.9in}
\begin{tabular}{ll}
\subfloat[Diff Opt 4 clump - 4]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_anom_opt4_clump_MR_year.png}}
\subfloat[Diff Opt 5 clump - 5]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_anom_opt5_clump_MR_year.png}}
\end{tabular}
\centering\hspace*{-1.9in}
\begin{tabular}{ll}
\subfloat[Opt 4 BL]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_anom_opt4_pft_0_clump_MR_year.png}}
\subfloat[Opt 5 BL]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_anom_opt5_pft_0_clump_MR_year.png}}
\end{tabular}
\centering\hspace*{-1.9in}
\begin{tabular}{ll}
\subfloat[Opt 4 NL]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_anom_opt4_pft_1_clump_MR_year.png}}
\subfloat[Opt 5 NL]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_anom_opt5_pft_1_clump_MR_year.png}}
\end{tabular}
\caption{Spatial impact of clumping per PFT for two radiative transfer modules in JULES.}
\label{f:pgap}
\end{figure}
\begin{figure}[ht!]
\centering\hspace*{-1.9in}
\begin{tabular}{ll}
\subfloat[Opt 4 C3]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_anom_opt4_pft_2_clump_MR_year.png}}
\subfloat[Opt 5 C3]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_anom_opt5_pft_2_clump_MR_year.png}}
\end{tabular}
\centering\hspace*{-1.9in}
\begin{tabular}{ll}
\subfloat[Opt 4 C4]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_anom_opt4_pft_3_clump_MR_year.png}}
\subfloat[Opt 5 C4]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_anom_opt5_pft_3_clump_MR_year.png}}
\end{tabular}
\centering\hspace*{-1.9in}
\begin{tabular}{ll}
\subfloat[Opt 4 SH]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_anom_opt4_pft_4_clump_MR_year.png}}
\subfloat[Opt 5 SH]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_anom_opt5_pft_4_clump_MR_year.png}}
\end{tabular}
\caption{Spatial impact of clumping on absolute GPP per PFT for two radiative transfer modules in JULES.}
\label{f:pgap}
\end{figure}
\begin{figure}[ht!]
\centering\hspace*{-1.9in}
\begin{tabular}{ll}
\subfloat[Diff Opt 4 clump - 4]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_perc_anom_opt4_clump_MR_year.png}}
\subfloat[Diff Opt 5 clump - 5]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_perc_anom_opt5_clump_MR_year.png}}
\end{tabular}
\centering\hspace*{-1.9in}
\begin{tabular}{ll}
\subfloat[Opt 4 BL]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_perc_anom_opt4_pft_0_clump_MR_year.png}}
\subfloat[Opt 5 BL]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_perc_anom_opt5_pft_0_clump_MR_year.png}}
\end{tabular}
\centering\hspace*{-1.9in}
\begin{tabular}{ll}
\subfloat[Opt 4 NL]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_perc_anom_opt4_pft_1_clump_MR_year.png}}
\subfloat[Opt 5 NL]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_perc_anom_opt5_pft_1_clump_MR_year.png}}
\end{tabular}
\caption{Spatial impact of clumping per PFT for two radiative transfer modules in JULES.}
\label{f:pgap}
\end{figure}
\begin{figure}[ht!]
\centering\hspace*{-1.9in}
\begin{tabular}{ll}
\subfloat[Opt 4 C3]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_perc_anom_opt4_pft_2_clump_MR_year.png}}
\subfloat[Opt 5 C3]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_perc_anom_opt5_pft_2_clump_MR_year.png}}
\end{tabular}
\centering\hspace*{-1.9in}
\begin{tabular}{ll}
\subfloat[Opt 4 C4]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_perc_anom_opt4_pft_3_clump_MR_year.png}}
\subfloat[Opt 5 C4]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_perc_anom_opt5_pft_3_clump_MR_year.png}}
\end{tabular}
\centering\hspace*{-1.9in}
\begin{tabular}{ll}
\subfloat[Opt 4 SH]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_perc_anom_opt4_pft_4_clump_MR_year.png}}
\subfloat[Opt 5 SH]{\includegraphics[width=0.7\textwidth]{/home/mn811042/Thesis/chapter6/figures_ofi/jules_perc_anom_opt5_pft_4_clump_MR_year.png}}
\end{tabular}
\caption{Spatial impact of clumping on relative GPP per PFT for two radiative transfer modules in JULES.}
\label{f:pgap}
\end{figure}
|
#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/InetAddress.h>
#include <boost/bind.hpp>
#include <stdio.h>
using namespace muduo;
using namespace muduo::net;
class TestServer
{
public:
TestServer(EventLoop* loop,
const InetAddress& listenAddr)
: loop_(loop),
server_(loop, listenAddr, "TestServer")
{
server_.setConnectionCallback(
boost::bind(&TestServer::onConnection, this, _1));
server_.setMessageCallback(
boost::bind(&TestServer::onMessage, this, _1, _2, _3));
}
void start()
{
server_.start();
}
private:
void onConnection(const TcpConnectionPtr& conn)
{
if (conn->connected())
{
printf("onConnection(): new connection [%s] from %s\n",
conn->name().c_str(),
conn->peerAddress().toIpPort().c_str());
}
else
{
printf("onConnection(): connection [%s] is down\n",
conn->name().c_str());
}
}
void onMessage(const TcpConnectionPtr& conn,
const char* data,
ssize_t len)
{
printf("onMessage(): received %zd bytes from connection [%s]\n",
len, conn->name().c_str());
}
EventLoop* loop_;
TcpServer server_;
};
int main()
{
printf("main(): pid = %d\n", getpid());
InetAddress listenAddr(8888);
EventLoop loop;
TestServer server(&loop, listenAddr);
server.start();
loop.loop();
} |
(*vars_to_clique attaches each v_i and v_i' to x_i. If in the boolean formula,
**u_i is set to true in a satisfiable environment, then v_i gets assigned the color u_i
**and v_i' gets assigned the color C*)
Require Export ThreeSatReduction.
(*attaching v_i to x_j for i <> j preserves coloring*)
Theorem connectXColorable : forall Gamma Delta G C eta eta' u,
~In u Delta -> setVertices Gamma C 0 eta' eta -> In (u,3*u,3*u+1,3*u+2) Gamma ->
connectX Gamma Delta (3*u) G -> coloring eta' G C.
Proof.
intros. genDeps {{ eta; C; eta'}}. remember (3*u). induction H2; intros.
{constructor. }
{subst. destruct(eq_nat_dec u u0).
{subst. exfalso. apply H. simpl. auto. }
{copy H3. copy H1. eapply V_V'MapToUOrC in H1; eauto. eapply XMapsToU in H0; eauto.
inv H1. invertHyp. econstructor; eauto. omega. omega. eapply IHconnectX; eauto.
intros c. apply H. simpl; auto. invertHyp. econstructor; eauto. omega.
omega. eapply IHconnectX; eauto. intros c. apply H. simpl; auto. }
}
Qed.
(*attaching v_i' to x_j for i <> j preserves coloring*)
Theorem connectXColorable' : forall Gamma Delta G C eta eta' u,
~In u Delta -> setVertices Gamma C 0 eta' eta -> In (u,3*u,3*u+1,3*u+2) Gamma ->
connectX Gamma Delta (3*u+1) G -> coloring eta' G C.
Proof.
intros. genDeps {{ eta; C; eta'}}. remember (3*u+1). induction H2; intros.
{constructor. }
{subst. destruct(eq_nat_dec u u0).
{subst. exfalso. apply H. simpl. auto. }
{copy H3. copy H1. eapply V_V'MapToUOrC in H1; eauto. eapply XMapsToU in H0; eauto.
inv H1. invertHyp. econstructor; eauto. omega. omega. eapply IHconnectX; eauto.
intros c. apply H. simpl; auto. invertHyp. econstructor; eauto. omega.
omega. eapply IHconnectX; eauto. intros c. apply H. simpl; auto. }
}
Qed.
(*attaching x_i to v_i and v_i' for i <> j preserves coloring*)
Theorem connectVColorable : forall Gamma Delta G C eta eta' u,
~In u Delta -> setVertices Gamma C 0 eta' eta -> In (u,3*u,3*u+1,3*u+2) Gamma ->
connectV Gamma Delta (3*u+2) G -> coloring eta' G C.
Proof.
intros. genDeps {{ eta; C; eta'}}. remember (3*u+2). induction H2; intros.
{constructor. }
{subst. destruct(eq_nat_dec u u0).
{subst. exfalso. apply H. simpl. auto. }
{copy H3. copy H1. eapply XMapsToU in H1; eauto. eapply V_V'MapToUOrC in H0; eauto.
inv H0.
{invertHyp. econstructor; eauto; try omega. econstructor; eauto; try omega.
eapply IHconnectV; eauto. intros contra. apply H. simpl. auto. }
{invertHyp. econstructor; eauto; try omega. econstructor; eauto; try omega.
eapply IHconnectV; eauto. intros contra. apply H. simpl; auto. }
}
}
Qed.
Theorem varsToCliqueColorable : forall Gamma eta Delta C G eta' U,
setVertices Gamma C 0 eta' eta ->
unique U Delta ->
vars_to_clique Gamma Delta G -> coloring eta' G C.
Proof.
intros. genDeps {{ U; eta'; eta; C }}. induction H1; intros.
{constructor. }
{inv H5. constructor. eapply IHvars_to_clique; eauto. constructor.
eapply connectXColorable; eauto. eapply uniqueNotIn; eauto. apply Union_intror.
constructor. constructor. eapply connectXColorable'; eauto.
eapply uniqueNotIn; eauto. apply Union_intror. constructor.
eapply connectVColorable; eauto. eapply uniqueNotIn; eauto.
apply Union_intror. constructor. }
Qed.
|
Not all condos in the Keys are created alike . . .
One of the biggest downside I hear from condo buyers is that many units feel like a box, with limited floorplans.
Not so at Ocean Harbour. These units have unique floorplans, and are some of the most spacious units in the Upper Keys. With two bedroom, three bedroom and even four bedroom units, these units break the norm and feel like a luxury home.
But it's not just the units that are so attractive. The grounds are immaculate. The grounds consist of beautiful, lush green spaces, a large free-form swimming pool, a marina and boat ramp, an oceanfront clubhouse, a private gym, large oceanfront tiki with BBQ area and covered parking.
Tucked away in a private and gated community off The Old Road, these units all have endless Ocean views and views of the grounds. They feature large kitchens and master bedrooms with ocean views, a private master bath and a dressing are with walk-in closet.
Located in Islamorada, Ocean Harbour is close to everything you'll need in terms of restaurants, shopping, medical needs, etc.
Learn more about Ocean Harbour at www.OceanHarbourIslamorada.com.
What Can You Purchase in the Florida Keys for Under $250,000?
The Florida Keys have long been known as an ideal destination in South Florida, either as a place to vacation or a place to live full-time.
The perception is that most places to live in the Keys are out of reach for many buyers. While it is true that the Keys are home to some of the most expensive real estate in South Florida, there are also places you can find for under $250,000.
Here is a list of all the properties in the Keys, from Key West to Key Largo. Many of them are condos, but there are also some single family homes. |
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
⊢ AddCommGroup (Cotangent I)
[PROOFSTEP]
delta Cotangent
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
⊢ AddCommGroup ({ x // x ∈ I } ⧸ I • ⊤)
[PROOFSTEP]
infer_instance
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
⊢ Module (R ⧸ I) (Cotangent I)
[PROOFSTEP]
delta Cotangent
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
⊢ Module (R ⧸ I) ({ x // x ∈ I } ⧸ I • ⊤)
[PROOFSTEP]
infer_instance
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
⊢ Submodule.map (Submodule.subtype I) (LinearMap.ker (toCotangent I)) = I ^ 2
[PROOFSTEP]
rw [Ideal.toCotangent, Submodule.ker_mkQ, pow_two, Submodule.map_smul'' I ⊤ (Submodule.subtype I),
Algebra.id.smul_eq_mul, Submodule.map_subtype_top]
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
x : { x // x ∈ I }
⊢ x ∈ LinearMap.ker (toCotangent I) ↔ ↑x ∈ I ^ 2
[PROOFSTEP]
rw [← I.map_toCotangent_ker]
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
x : { x // x ∈ I }
⊢ x ∈ LinearMap.ker (toCotangent I) ↔ ↑x ∈ Submodule.map (Submodule.subtype I) (LinearMap.ker (toCotangent I))
[PROOFSTEP]
simp
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
x y : { x // x ∈ I }
⊢ ↑(toCotangent I) x = ↑(toCotangent I) y ↔ ↑x - ↑y ∈ I ^ 2
[PROOFSTEP]
rw [← sub_eq_zero]
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
x y : { x // x ∈ I }
⊢ ↑(toCotangent I) x - ↑(toCotangent I) y = 0 ↔ ↑x - ↑y ∈ I ^ 2
[PROOFSTEP]
exact I.mem_toCotangent_ker
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
⊢ Subsingleton (Cotangent I) ↔ IsIdempotentElem I
[PROOFSTEP]
constructor
[GOAL]
case mp
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
⊢ Subsingleton (Cotangent I) → IsIdempotentElem I
[PROOFSTEP]
intro H
[GOAL]
case mp
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
H : Subsingleton (Cotangent I)
⊢ IsIdempotentElem I
[PROOFSTEP]
refine' (pow_two I).symm.trans (le_antisymm (Ideal.pow_le_self two_ne_zero) _)
[GOAL]
case mp
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
H : Subsingleton (Cotangent I)
⊢ I ≤ I ^ 2
[PROOFSTEP]
exact fun x hx => (I.toCotangent_eq_zero ⟨x, hx⟩).mp (Subsingleton.elim _ _)
[GOAL]
case mpr
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
⊢ IsIdempotentElem I → Subsingleton (Cotangent I)
[PROOFSTEP]
exact fun e =>
⟨fun x y =>
Quotient.inductionOn₂' x y fun x y => I.toCotangent_eq.mpr <| ((pow_two I).trans e).symm ▸ I.sub_mem x.prop y.prop⟩
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
⊢ I • ⊤ ≤ Submodule.comap (Submodule.subtype I) (I ^ 2)
[PROOFSTEP]
rw [← Submodule.map_le_iff_le_comap, Submodule.map_smul'', Submodule.map_top, Submodule.range_subtype, smul_eq_mul,
pow_two]
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I✝ I : Ideal R
⊢ cotangentIdeal I ^ 2 = ⊥
[PROOFSTEP]
rw [eq_bot_iff, pow_two I.cotangentIdeal, ← smul_eq_mul]
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I✝ I : Ideal R
⊢ cotangentIdeal I • cotangentIdeal I ≤ ⊥
[PROOFSTEP]
intro x hx
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I✝ I : Ideal R
x : R ⧸ I ^ 2
hx : x ∈ cotangentIdeal I • cotangentIdeal I
⊢ x ∈ ⊥
[PROOFSTEP]
refine Submodule.smul_induction_on hx ?_ ?_
[GOAL]
case refine_1
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I✝ I : Ideal R
x : R ⧸ I ^ 2
hx : x ∈ cotangentIdeal I • cotangentIdeal I
⊢ ∀ (r : R ⧸ I ^ 2), r ∈ cotangentIdeal I → ∀ (n : R ⧸ I ^ 2), n ∈ cotangentIdeal I → r • n ∈ ⊥
[PROOFSTEP]
rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩
[GOAL]
case refine_1.intro.intro.intro.intro
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I✝ I : Ideal R
x✝ : R ⧸ I ^ 2
hx✝ : x✝ ∈ cotangentIdeal I • cotangentIdeal I
x : R
hx : x ∈ ↑I
y : R
hy : y ∈ ↑I
⊢ ↑(RingHom.toSemilinearMap (Quotient.mk (I ^ 2))) x • ↑(RingHom.toSemilinearMap (Quotient.mk (I ^ 2))) y ∈ ⊥
[PROOFSTEP]
apply (Submodule.Quotient.eq _).mpr _
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I✝ I : Ideal R
x✝ : R ⧸ I ^ 2
hx✝ : x✝ ∈ cotangentIdeal I • cotangentIdeal I
x : R
hx : x ∈ ↑I
y : R
hy : y ∈ ↑I
⊢ (fun x x_1 => x * x_1) x y - 0 ∈ I ^ 2
[PROOFSTEP]
rw [sub_zero, pow_two]
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I✝ I : Ideal R
x✝ : R ⧸ I ^ 2
hx✝ : x✝ ∈ cotangentIdeal I • cotangentIdeal I
x : R
hx : x ∈ ↑I
y : R
hy : y ∈ ↑I
⊢ (fun x x_1 => x * x_1) x y ∈ I * I
[PROOFSTEP]
exact Ideal.mul_mem_mul hx hy
[GOAL]
case refine_2
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I✝ I : Ideal R
x : R ⧸ I ^ 2
hx : x ∈ cotangentIdeal I • cotangentIdeal I
⊢ ∀ (x y : R ⧸ I ^ 2), x ∈ ⊥ → y ∈ ⊥ → x + y ∈ ⊥
[PROOFSTEP]
intro x y hx hy
[GOAL]
case refine_2
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I✝ I : Ideal R
x✝ : R ⧸ I ^ 2
hx✝ : x✝ ∈ cotangentIdeal I • cotangentIdeal I
x y : R ⧸ I ^ 2
hx : x ∈ ⊥
hy : y ∈ ⊥
⊢ x + y ∈ ⊥
[PROOFSTEP]
exact add_mem hx hy
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
⊢ LinearMap.range (cotangentToQuotientSquare I) = Submodule.restrictScalars R (cotangentIdeal I)
[PROOFSTEP]
trans LinearMap.range (I.cotangentToQuotientSquare.comp I.toCotangent)
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
⊢ LinearMap.range (cotangentToQuotientSquare I) =
LinearMap.range (LinearMap.comp (cotangentToQuotientSquare I) (toCotangent I))
[PROOFSTEP]
rw [LinearMap.range_comp, I.toCotangent_range, Submodule.map_top]
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
⊢ LinearMap.range (LinearMap.comp (cotangentToQuotientSquare I) (toCotangent I)) =
Submodule.restrictScalars R (cotangentIdeal I)
[PROOFSTEP]
rw [to_quotient_square_comp_toCotangent, LinearMap.range_comp, I.range_subtype]
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
⊢ Submodule.map (Submodule.mkQ (I ^ 2)) I = Submodule.restrictScalars R (cotangentIdeal I)
[PROOFSTEP]
ext
[GOAL]
case h
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
x✝ : R ⧸ I ^ 2
⊢ x✝ ∈ Submodule.map (Submodule.mkQ (I ^ 2)) I ↔ x✝ ∈ Submodule.restrictScalars R (cotangentIdeal I)
[PROOFSTEP]
rfl
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
⊢ Cotangent I ≃ₗ[R] { x // x ∈ cotangentIdeal I }
[PROOFSTEP]
refine
{
LinearMap.codRestrict (I.cotangentIdeal.restrictScalars R) I.cotangentToQuotientSquare fun x => by
{rw [← to_quotient_square_range]; exact LinearMap.mem_range_self _ _
},
Equiv.ofBijective _ ⟨?_, ?_⟩ with }
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
x : Cotangent I
⊢ ↑(cotangentToQuotientSquare I) x ∈ Submodule.restrictScalars R (cotangentIdeal I)
[PROOFSTEP]
{rw [← to_quotient_square_range]; exact LinearMap.mem_range_self _ _
}
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
x : Cotangent I
⊢ ↑(cotangentToQuotientSquare I) x ∈ Submodule.restrictScalars R (cotangentIdeal I)
[PROOFSTEP]
rw [← to_quotient_square_range]
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
x : Cotangent I
⊢ ↑(cotangentToQuotientSquare I) x ∈ LinearMap.range (cotangentToQuotientSquare I)
[PROOFSTEP]
exact LinearMap.mem_range_self _ _
[GOAL]
case refine_1
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
src✝ : Cotangent I →ₗ[R] { x // x ∈ Submodule.restrictScalars R (cotangentIdeal I) } :=
LinearMap.codRestrict (Submodule.restrictScalars R (cotangentIdeal I)) (cotangentToQuotientSquare I)
(_ : ∀ (x : Cotangent I), ↑(cotangentToQuotientSquare I) x ∈ Submodule.restrictScalars R (cotangentIdeal I))
⊢ Function.Injective fun c =>
{ val := ↑(cotangentToQuotientSquare I) c,
property := (_ : ↑(cotangentToQuotientSquare I) c ∈ Submodule.restrictScalars R (cotangentIdeal I)) }
[PROOFSTEP]
rintro x y e
[GOAL]
case refine_1
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
src✝ : Cotangent I →ₗ[R] { x // x ∈ Submodule.restrictScalars R (cotangentIdeal I) } :=
LinearMap.codRestrict (Submodule.restrictScalars R (cotangentIdeal I)) (cotangentToQuotientSquare I)
(_ : ∀ (x : Cotangent I), ↑(cotangentToQuotientSquare I) x ∈ Submodule.restrictScalars R (cotangentIdeal I))
x y : Cotangent I
e :
(fun c =>
{ val := ↑(cotangentToQuotientSquare I) c,
property := (_ : ↑(cotangentToQuotientSquare I) c ∈ Submodule.restrictScalars R (cotangentIdeal I)) })
x =
(fun c =>
{ val := ↑(cotangentToQuotientSquare I) c,
property := (_ : ↑(cotangentToQuotientSquare I) c ∈ Submodule.restrictScalars R (cotangentIdeal I)) })
y
⊢ x = y
[PROOFSTEP]
replace e := congr_arg Subtype.val e
[GOAL]
case refine_1
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
src✝ : Cotangent I →ₗ[R] { x // x ∈ Submodule.restrictScalars R (cotangentIdeal I) } :=
LinearMap.codRestrict (Submodule.restrictScalars R (cotangentIdeal I)) (cotangentToQuotientSquare I)
(_ : ∀ (x : Cotangent I), ↑(cotangentToQuotientSquare I) x ∈ Submodule.restrictScalars R (cotangentIdeal I))
x y : Cotangent I
e :
↑((fun c =>
{ val := ↑(cotangentToQuotientSquare I) c,
property := (_ : ↑(cotangentToQuotientSquare I) c ∈ Submodule.restrictScalars R (cotangentIdeal I)) })
x) =
↑((fun c =>
{ val := ↑(cotangentToQuotientSquare I) c,
property := (_ : ↑(cotangentToQuotientSquare I) c ∈ Submodule.restrictScalars R (cotangentIdeal I)) })
y)
⊢ x = y
[PROOFSTEP]
obtain ⟨x, rfl⟩ := I.toCotangent_surjective x
[GOAL]
case refine_1.intro
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
src✝ : Cotangent I →ₗ[R] { x // x ∈ Submodule.restrictScalars R (cotangentIdeal I) } :=
LinearMap.codRestrict (Submodule.restrictScalars R (cotangentIdeal I)) (cotangentToQuotientSquare I)
(_ : ∀ (x : Cotangent I), ↑(cotangentToQuotientSquare I) x ∈ Submodule.restrictScalars R (cotangentIdeal I))
y : Cotangent I
x : { x // x ∈ I }
e :
↑((fun c =>
{ val := ↑(cotangentToQuotientSquare I) c,
property := (_ : ↑(cotangentToQuotientSquare I) c ∈ Submodule.restrictScalars R (cotangentIdeal I)) })
(↑(toCotangent I) x)) =
↑((fun c =>
{ val := ↑(cotangentToQuotientSquare I) c,
property := (_ : ↑(cotangentToQuotientSquare I) c ∈ Submodule.restrictScalars R (cotangentIdeal I)) })
y)
⊢ ↑(toCotangent I) x = y
[PROOFSTEP]
obtain ⟨y, rfl⟩ := I.toCotangent_surjective y
[GOAL]
case refine_1.intro.intro
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
src✝ : Cotangent I →ₗ[R] { x // x ∈ Submodule.restrictScalars R (cotangentIdeal I) } :=
LinearMap.codRestrict (Submodule.restrictScalars R (cotangentIdeal I)) (cotangentToQuotientSquare I)
(_ : ∀ (x : Cotangent I), ↑(cotangentToQuotientSquare I) x ∈ Submodule.restrictScalars R (cotangentIdeal I))
x y : { x // x ∈ I }
e :
↑((fun c =>
{ val := ↑(cotangentToQuotientSquare I) c,
property := (_ : ↑(cotangentToQuotientSquare I) c ∈ Submodule.restrictScalars R (cotangentIdeal I)) })
(↑(toCotangent I) x)) =
↑((fun c =>
{ val := ↑(cotangentToQuotientSquare I) c,
property := (_ : ↑(cotangentToQuotientSquare I) c ∈ Submodule.restrictScalars R (cotangentIdeal I)) })
(↑(toCotangent I) y))
⊢ ↑(toCotangent I) x = ↑(toCotangent I) y
[PROOFSTEP]
rw [I.toCotangent_eq]
[GOAL]
case refine_1.intro.intro
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
src✝ : Cotangent I →ₗ[R] { x // x ∈ Submodule.restrictScalars R (cotangentIdeal I) } :=
LinearMap.codRestrict (Submodule.restrictScalars R (cotangentIdeal I)) (cotangentToQuotientSquare I)
(_ : ∀ (x : Cotangent I), ↑(cotangentToQuotientSquare I) x ∈ Submodule.restrictScalars R (cotangentIdeal I))
x y : { x // x ∈ I }
e :
↑((fun c =>
{ val := ↑(cotangentToQuotientSquare I) c,
property := (_ : ↑(cotangentToQuotientSquare I) c ∈ Submodule.restrictScalars R (cotangentIdeal I)) })
(↑(toCotangent I) x)) =
↑((fun c =>
{ val := ↑(cotangentToQuotientSquare I) c,
property := (_ : ↑(cotangentToQuotientSquare I) c ∈ Submodule.restrictScalars R (cotangentIdeal I)) })
(↑(toCotangent I) y))
⊢ ↑x - ↑y ∈ I ^ 2
[PROOFSTEP]
dsimp only [toCotangent_to_quotient_square, Submodule.mkQ_apply] at e
[GOAL]
case refine_1.intro.intro
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
src✝ : Cotangent I →ₗ[R] { x // x ∈ Submodule.restrictScalars R (cotangentIdeal I) } :=
LinearMap.codRestrict (Submodule.restrictScalars R (cotangentIdeal I)) (cotangentToQuotientSquare I)
(_ : ∀ (x : Cotangent I), ↑(cotangentToQuotientSquare I) x ∈ Submodule.restrictScalars R (cotangentIdeal I))
x y : { x // x ∈ I }
e : Submodule.Quotient.mk ↑x = Submodule.Quotient.mk ↑y
⊢ ↑x - ↑y ∈ I ^ 2
[PROOFSTEP]
rwa [Submodule.Quotient.eq] at e
[GOAL]
case refine_2
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
src✝ : Cotangent I →ₗ[R] { x // x ∈ Submodule.restrictScalars R (cotangentIdeal I) } :=
LinearMap.codRestrict (Submodule.restrictScalars R (cotangentIdeal I)) (cotangentToQuotientSquare I)
(_ : ∀ (x : Cotangent I), ↑(cotangentToQuotientSquare I) x ∈ Submodule.restrictScalars R (cotangentIdeal I))
⊢ Function.Surjective fun c =>
{ val := ↑(cotangentToQuotientSquare I) c,
property := (_ : ↑(cotangentToQuotientSquare I) c ∈ Submodule.restrictScalars R (cotangentIdeal I)) }
[PROOFSTEP]
rintro ⟨_, x, hx, rfl⟩
[GOAL]
case refine_2.mk.intro.intro
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
src✝ : Cotangent I →ₗ[R] { x // x ∈ Submodule.restrictScalars R (cotangentIdeal I) } :=
LinearMap.codRestrict (Submodule.restrictScalars R (cotangentIdeal I)) (cotangentToQuotientSquare I)
(_ : ∀ (x : Cotangent I), ↑(cotangentToQuotientSquare I) x ∈ Submodule.restrictScalars R (cotangentIdeal I))
x : R
hx : x ∈ ↑I
⊢ ∃ a,
(fun c =>
{ val := ↑(cotangentToQuotientSquare I) c,
property := (_ : ↑(cotangentToQuotientSquare I) c ∈ Submodule.restrictScalars R (cotangentIdeal I)) })
a =
{ val := ↑(RingHom.toSemilinearMap (Quotient.mk (I ^ 2))) x,
property :=
(_ :
∃ a,
a ∈ ↑I ∧
↑(RingHom.toSemilinearMap (Quotient.mk (I ^ 2))) a =
↑(RingHom.toSemilinearMap (Quotient.mk (I ^ 2))) x) }
[PROOFSTEP]
exact ⟨I.toCotangent ⟨x, hx⟩, Subtype.ext rfl⟩
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
x : R
hx : x ∈ I
⊢ ↑(LinearEquiv.symm (cotangentEquivIdeal I))
{ val := ↑(Submodule.mkQ (I ^ 2)) x,
property := (_ : ↑(Submodule.mkQ (I ^ 2)) x ∈ Submodule.map (Submodule.mkQ (I ^ 2)) I) } =
↑(toCotangent I) { val := x, property := hx }
[PROOFSTEP]
apply I.cotangentEquivIdeal.injective
[GOAL]
case a
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
x : R
hx : x ∈ I
⊢ ↑(cotangentEquivIdeal I)
(↑(LinearEquiv.symm (cotangentEquivIdeal I))
{ val := ↑(Submodule.mkQ (I ^ 2)) x,
property := (_ : ↑(Submodule.mkQ (I ^ 2)) x ∈ Submodule.map (Submodule.mkQ (I ^ 2)) I) }) =
↑(cotangentEquivIdeal I) (↑(toCotangent I) { val := x, property := hx })
[PROOFSTEP]
rw [I.cotangentEquivIdeal.apply_symm_apply]
[GOAL]
case a
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
x : R
hx : x ∈ I
⊢ { val := ↑(Submodule.mkQ (I ^ 2)) x,
property := (_ : ↑(Submodule.mkQ (I ^ 2)) x ∈ Submodule.map (Submodule.mkQ (I ^ 2)) I) } =
↑(cotangentEquivIdeal I) (↑(toCotangent I) { val := x, property := hx })
[PROOFSTEP]
ext
[GOAL]
case a.a
R : Type u
S : Type v
S' : Type w
inst✝⁶ : CommRing R
inst✝⁵ : CommSemiring S
inst✝⁴ : Algebra S R
inst✝³ : CommSemiring S'
inst✝² : Algebra S' R
inst✝¹ : Algebra S S'
inst✝ : IsScalarTower S S' R
I : Ideal R
x : R
hx : x ∈ I
⊢ ↑{ val := ↑(Submodule.mkQ (I ^ 2)) x,
property := (_ : ↑(Submodule.mkQ (I ^ 2)) x ∈ Submodule.map (Submodule.mkQ (I ^ 2)) I) } =
↑(↑(cotangentEquivIdeal I) (↑(toCotangent I) { val := x, property := hx }))
[PROOFSTEP]
rfl
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
f : A →ₐ[R] B
⊢ A ⧸ RingHom.ker ↑f ^ 2 →ₐ[R] B
[PROOFSTEP]
refine { Ideal.Quotient.lift (RingHom.ker f.toRingHom ^ 2) f.toRingHom ?_ with commutes' := ?_ }
[GOAL]
case refine_1
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
f : A →ₐ[R] B
⊢ ∀ (a : A), a ∈ RingHom.ker ↑f ^ 2 → ↑↑f a = 0
[PROOFSTEP]
intro a ha
[GOAL]
case refine_1
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
f : A →ₐ[R] B
a : A
ha : a ∈ RingHom.ker ↑f ^ 2
⊢ ↑↑f a = 0
[PROOFSTEP]
exact Ideal.pow_le_self two_ne_zero ha
[GOAL]
case refine_2
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
f : A →ₐ[R] B
src✝ : A ⧸ RingHom.ker ↑f ^ 2 →+* B :=
Quotient.lift (RingHom.ker ↑f ^ 2) ↑f (_ : ∀ (a : A), a ∈ RingHom.ker ↑f ^ 2 → a ∈ RingHom.ker ↑f)
⊢ ∀ (r : R),
OneHom.toFun
(↑↑{ toMonoidHom := ↑src✝, map_zero' := (_ : OneHom.toFun (↑↑src✝) 0 = 0),
map_add' :=
(_ :
∀ (x y : A ⧸ RingHom.ker ↑f ^ 2),
OneHom.toFun (↑↑src✝) (x + y) = OneHom.toFun (↑↑src✝) x + OneHom.toFun (↑↑src✝) y) })
(↑(algebraMap R (A ⧸ RingHom.ker ↑f ^ 2)) r) =
↑(algebraMap R B) r
[PROOFSTEP]
intro r
[GOAL]
case refine_2
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
f : A →ₐ[R] B
src✝ : A ⧸ RingHom.ker ↑f ^ 2 →+* B :=
Quotient.lift (RingHom.ker ↑f ^ 2) ↑f (_ : ∀ (a : A), a ∈ RingHom.ker ↑f ^ 2 → a ∈ RingHom.ker ↑f)
r : R
⊢ OneHom.toFun
(↑↑{ toMonoidHom := ↑src✝, map_zero' := (_ : OneHom.toFun (↑↑src✝) 0 = 0),
map_add' :=
(_ :
∀ (x y : A ⧸ RingHom.ker ↑f ^ 2),
OneHom.toFun (↑↑src✝) (x + y) = OneHom.toFun (↑↑src✝) x + OneHom.toFun (↑↑src✝) y) })
(↑(algebraMap R (A ⧸ RingHom.ker ↑f ^ 2)) r) =
↑(algebraMap R B) r
[PROOFSTEP]
rw [IsScalarTower.algebraMap_apply R A, RingHom.toFun_eq_coe, Ideal.Quotient.algebraMap_eq, Ideal.Quotient.lift_mk]
[GOAL]
case refine_2
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
f : A →ₐ[R] B
src✝ : A ⧸ RingHom.ker ↑f ^ 2 →+* B :=
Quotient.lift (RingHom.ker ↑f ^ 2) ↑f (_ : ∀ (a : A), a ∈ RingHom.ker ↑f ^ 2 → a ∈ RingHom.ker ↑f)
r : R
⊢ ↑↑f (↑(algebraMap R A) r) = ↑(algebraMap R B) r
[PROOFSTEP]
exact f.map_algebraMap r
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
f : A →ₐ[R] B
⊢ RingHom.ker ↑(AlgHom.kerSquareLift f) = cotangentIdeal (RingHom.ker ↑f)
[PROOFSTEP]
apply le_antisymm
[GOAL]
case a
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
f : A →ₐ[R] B
⊢ RingHom.ker ↑(AlgHom.kerSquareLift f) ≤ cotangentIdeal (RingHom.ker ↑f)
[PROOFSTEP]
intro x hx
[GOAL]
case a
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
f : A →ₐ[R] B
x : A ⧸ RingHom.ker ↑f ^ 2
hx : x ∈ RingHom.ker ↑(AlgHom.kerSquareLift f)
⊢ x ∈ cotangentIdeal (RingHom.ker ↑f)
[PROOFSTEP]
obtain ⟨x, rfl⟩ := Ideal.Quotient.mk_surjective x
[GOAL]
case a.intro
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
f : A →ₐ[R] B
x : A
hx : ↑(Quotient.mk (RingHom.ker ↑f ^ 2)) x ∈ RingHom.ker ↑(AlgHom.kerSquareLift f)
⊢ ↑(Quotient.mk (RingHom.ker ↑f ^ 2)) x ∈ cotangentIdeal (RingHom.ker ↑f)
[PROOFSTEP]
exact ⟨x, hx, rfl⟩
[GOAL]
case a
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
f : A →ₐ[R] B
⊢ cotangentIdeal (RingHom.ker ↑f) ≤ RingHom.ker ↑(AlgHom.kerSquareLift f)
[PROOFSTEP]
rintro _ ⟨x, hx, rfl⟩
[GOAL]
case a.intro.intro
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
f : A →ₐ[R] B
x : A
hx : x ∈ ↑(RingHom.ker ↑f)
⊢ ↑(RingHom.toSemilinearMap (Quotient.mk (RingHom.ker ↑f ^ 2))) x ∈ RingHom.ker ↑(AlgHom.kerSquareLift f)
[PROOFSTEP]
exact hx
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
⊢ (R ⧸ I ^ 2) ⧸ cotangentIdeal I ≃+* R ⧸ I
[PROOFSTEP]
refine (Ideal.quotEquivOfEq (Ideal.map_eq_submodule_map _ _).symm).trans ?_
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
⊢ (R ⧸ I ^ 2) ⧸ map (Quotient.mk (I ^ 2)) I ≃+* R ⧸ I
[PROOFSTEP]
refine (DoubleQuot.quotQuotEquivQuotSup _ _).trans ?_
[GOAL]
R : Type u
S : Type v
S' : Type w
inst✝¹⁰ : CommRing R
inst✝⁹ : CommSemiring S
inst✝⁸ : Algebra S R
inst✝⁷ : CommSemiring S'
inst✝⁶ : Algebra S' R
inst✝⁵ : Algebra S S'
inst✝⁴ : IsScalarTower S S' R
I : Ideal R
A : Type u_1
B : Type u_2
inst✝³ : CommRing A
inst✝² : CommRing B
inst✝¹ : Algebra R A
inst✝ : Algebra R B
⊢ R ⧸ I ^ 2 ⊔ I ≃+* R ⧸ I
[PROOFSTEP]
exact Ideal.quotEquivOfEq (sup_eq_right.mpr <| Ideal.pow_le_self two_ne_zero)
|
State Before: C : Type u₁
inst✝² : Category C
D : Type u₂
inst✝¹ : Category D
F : C ⥤ D
inst✝ : IsEquivalence F
X Y : D
f : X ⟶ Y
⊢ F.map ((Functor.inv F).map f) =
(Equivalence.counit (asEquivalence F)).app X ≫ f ≫ (Equivalence.counitInv (asEquivalence F)).app Y State After: C : Type u₁
inst✝² : Category C
D : Type u₂
inst✝¹ : Category D
F : C ⥤ D
inst✝ : IsEquivalence F
X Y : D
f : X ⟶ Y
⊢ F.map ((Functor.inv F).map f) = ((asEquivalence F).inverse ⋙ (asEquivalence F).functor).map f Tactic: erw [NatIso.naturality_2] State Before: C : Type u₁
inst✝² : Category C
D : Type u₂
inst✝¹ : Category D
F : C ⥤ D
inst✝ : IsEquivalence F
X Y : D
f : X ⟶ Y
⊢ F.map ((Functor.inv F).map f) = ((asEquivalence F).inverse ⋙ (asEquivalence F).functor).map f State After: no goals Tactic: rfl |
Require Import Ascii.
Require Import String.
Require Import MetaCoq.Template.All.
Require Import Coquedille.DenoteCoq.
Require Import Coquedille.PrettyPrinter.
Require Coq.extraction.Extraction.
Extraction Language Haskell.
(* Controlling extraction of specific types *)
Extract Inductive bool => "GHC.Base.Bool" ["GHC.Base.True" "GHC.Base.False"]. (* enumeration types *)
Extract Inductive sumbool => "GHC.Base.Bool" ["GHC.Base.True" "GHC.Base.False"]
.
(* types that require parameters on their constructors *)
(* type, [constructors], recursor *)
Extract Inductive nat => "GHC.Base.Int" ["0" "(\ x -> x Prelude.+ 1)"]
"(\ zero succ n -> if n GHC.Base.== 0 then zero () else succ (n Prelude.- 1))".
Extract Constant plus => "(Prelude.+)".
Extract Constant mult => "(Prelude.*)".
Extract Constant PeanoNat.Nat.eqb => "( Prelude.== )".
(* Properly extract the unicode tokens *)
Extract Constant TkStar => "['★']".
Extract Constant TkArrow => "['➔']".
Extract Constant TkPi => "['Π']".
Extract Constant TkAll => "['∀']".
Extract Constant TkTDot => "['·']".
Extract Constant TkULam => "['Λ']".
Extract Constant TkLam => "['λ']".
Extract Constant TkMu => "['μ']".
Extract Constant TkDelta => "['δ']".
Extract Constant TkBeta => "['β']".
Extract Constant TkEq => "['≃']".
Extract Constant TkSigma => "['σ']".
Extract Inductive ascii => "Prelude.Char"
[ "(\b0 b1 b2 b3 b4 b5 b6 b7 -> Data.Char.chr ( (if b0 then Data.Bits.shiftL 1 0 else 0) Prelude.+ (if b1 then Data.Bits.shiftL 1 1 else 0) Prelude.+ (if b2 then Data.Bits.shiftL 1 2 else 0) Prelude.+ (if b3 then Data.Bits.shiftL 1 3 else 0) Prelude.+ (if b4 then Data.Bits.shiftL 1 4 else 0) Prelude.+ (if b5 then Data.Bits.shiftL 1 5 else 0) Prelude.+ (if b6 then Data.Bits.shiftL 1 6 else 0) Prelude.+ (if b7 then Data.Bits.shiftL 1 7 else 0)))" ]
"(\f a -> f (Data.Bits.testBit (Data.Char.ord a) 0) (Data.Bits.testBit (Data.Char.ord a) 1) (Data.Bits.testBit (Data.Char.ord a) 2) (Data.Bits.testBit (Data.Char.ord a) 3) (Data.Bits.testBit (Data.Char.ord a) 4) (Data.Bits.testBit (Data.Char.ord a) 5) (Data.Bits.testBit (Data.Char.ord a) 6) (Data.Bits.testBit (Data.Char.ord a) 7))".
Extract Inlined Constant Ascii.ascii_dec => "(Prelude.==)".
Extract Inductive string => "Prelude.String" [ "([])" "(:)" ].
Extract Inlined Constant String.string_dec => "(Prelude.==)".
Extract Inlined Constant String.eqb => "(Prelude.==)".
(* Adds Everything we will test here *)
(* THISISIMPORTS *)
Quote Recursively Definition _syntax := .
(* Require Import THISISLIBRARY. *)
Corollary ident : type.
(* Quote Recursively Definition p := THISISPROGRAM. *)
(* We are finally ready to extract the programs we want *)
Extraction "main.hs" PrettySum PrettyProgram denoteCoq p.
|
@testset "976.largest-perimeter-triangle.jl" begin
@test largest_perimeter([2, 1, 2]) == 5
@test largest_perimeter([1, 2, 1]) == 0
@test largest_perimeter([3, 2, 3, 4]) == 10
@test largest_perimeter([3, 6, 2, 3]) == 8
end |
module WebAssembly.Structure.Instructions.Memory
import WebAssembly.Structure.Values
import Decidable.Equality
-- Definition
-- Hint: Actual control-instructions are defined in
-- WebAssembly.Structure.Instructions.Definition
public export
record MemArg where
constructor MkMemArg
offset : U32
align : U32
-- Equality
total public export
lemma_memarg__offset_injective: ((o1 = o2) -> Void) -> (MkMemArg o1 a1 = MkMemArg o2 a2) -> Void
lemma_memarg__offset_injective o1_not_o2 Refl = o1_not_o2 Refl
total public export
lemma_memarg__align_injective: ((a1 = a2) -> Void) -> (MkMemArg o1 a1 = MkMemArg o2 a2) -> Void
lemma_memarg__align_injective a1_not_a2 Refl = a1_not_a2 Refl
-- Decidable Equality
public export
implementation DecEq MemArg where
decEq (MkMemArg o1 a1) (MkMemArg o2 a2) = case decEq o1 o2 of
No o1_not_o2 => No $ lemma_memarg__offset_injective o1_not_o2
Yes Refl => case decEq a1 a2 of
No a1_not_a2 => No $ lemma_memarg__align_injective a1_not_a2
Yes Refl => Yes Refl
|
# Set up local module environment to test against.
# Note that we override the normal path here.
options(import.path = 'modules',
import.attach = FALSE)
#' Opposite of \code{is_identical_to}
is_not_identical_to = function (expected, label = NULL) {
label = if (is.null(label)) testthat:::find_expr('expected') else
if (! is.character(label) || length(label) != 1) deparse(label) else label
function (actual)
expectation(! identical(actual, expected),
paste('is identical to', label),
paste('is not identical to', label))
}
|
import tactic.basic
import .uwyo_aux
import analysis.calculus.local_extr
noncomputable theory
open_locale classical topological_space
open filter
-- For examples, see mathlib/src/analysis/specific_limits.lean
-- Main business: Newton's method sequence of approximations
-- Working first with a sequence of rationals for the approximations themselves
def x : ℕ → ℚ
| 0 := (2 : ℚ)
| (n+1) := ( x n * x n + 2) / ( 2 * x n)
-- Now pretend otherwise
def s (n : ℕ) : ℝ := real.sqrt 2 - x n
lemma newton_seq_positive : ∀ n : ℕ, 0 < x n :=
begin
intro n,
induction n with d hd,
{ -- base case n = 0
have h1 : x 0 = 2, refl,
rw h1, linarith,
},
{ -- induction step
have h2 : x d.succ = ( x d * x d + 2) / ( 2 * x d), refl,
set X := x d with hX,
have h3 : 0 < X * X, nlinarith,
have h4 : 0 < X * X + 2, linarith,
have h5 : 0 < 2 * X, linarith,
exact div_pos h4 h5,
},
done
end
lemma newton_seq_bounded_below : ∀ n : ℕ, 2 < (x n) * (x n) :=
begin
intro n,
induction n with d hd,
{ -- base case n= 0
have h0 : x 0 =2 , refl,
rw h0, linarith,
},
{ -- induction step, kind of ugly so far
have h1 : x d.succ = ( x d * x d + 2) / ( 2 * x d), refl,
rw h1,
have H := newton_seq_positive d,
set X := x d with hX,
have G : X ≠ 0, linarith,
set Y := X * X with hY,
have G1 : Y ≠ 0, nlinarith,
have g1 : (Y + 2) * (Y + 2) = Y * Y + 4 * Y + 4, ring,
set V := 2 * X with hV,
have F : V ≠ 0, linarith,
have E : V * V ≠ 0, nlinarith,
have g2 : (Y + 2) * (Y + 2) / ( V * V) = (Y + 2) / V * ((Y + 2) / V),
field_simp,
-- this needs some polishing
have h21 := aux_1 X Y V G hY hV G1,
have h201 : (1/4) * (4 * (Y + 2) / V * ((Y + 2) / (V))) = (1/4) * (Y + 2 * 2 + (2*2/(X * X)) ),
rw h21,
have h202 : (1/4) * (4 * (Y + 2) / V * ((Y + 2) / (V))) = (Y + 2) / V * ((Y + 2) / (V)),
ring,
have h2 : (Y + 2) / V * ((Y + 2) / (V)) = (1/4) * (Y + 2 * 2 + (2*2/(X * X)) ),
rw h202 at h201, exact h201,
have h3 :
2 - (1/4) * ( X * X + 2 * 2 + (2*2/(X*X)) ) = (1/4) * ( - X * X + 2 * 2 - (2*2/(X*X)) ),
ring,
have h4 : (1/4) * ( - X * X + 2 * 2 - (2*2/(X*X)) ) = - (1/4) * ( 2 / X - X ) ^ 2,
have h41 : ( 2 / X - X ) ^ 2 = ( 2 / X - X ) * ( 2 / X - X ), ring,
rw h41,
have h42 := aux_2 X G,
rw h42, ring,
have h51 : 0 ≤ ( 2 / X - X ) ^ 2, exact pow_two_nonneg _,
have h52 : 0 ≠ ( 2 / X - X ), exact no_rat_sq_eq_two X G,
have h53 : 0 ≠ ( 2 / X - X ) ^ 2, exact ne.symm (pow_ne_zero 2 (ne.symm h52)),
have h54 : 0 < ( 2 / X - X ) ^ 2, exact lt_of_le_of_ne h51 h53,
have h6 : - (1/4) * ( 2 / X - X ) ^ 2 < 0, linarith,
rw h2,
apply sub_lt_zero.mp,
rw h3, rw h4, exact h6,
},
done
end
lemma newton_seq_decreasing : ∀ n : ℕ, x (n+1) < x n :=
begin
intro n,
have h1 : x (n+1) = ( x n * x n + 2) / ( 2 * x n), refl,
have h2 : x (n+1) - x n = ( x n * x n + 2) / ( 2 * x n) - x n, rw h1,
have h21 := newton_seq_positive n,
set X := x n with hX,
have h3 := aux_0 X h21,
have h4 : 2 - X * X < 0,
have h41 := newton_seq_bounded_below n,
rw ← hX at h41,
linarith,
have h5 : 0 < 2 * X, linarith,
have h6 := div_neg_of_neg_of_pos h4 h5,
rw ← h3 at h6, rw ← h2 at h6, linarith,
done
end
theorem sqrt_sub_newton_monotone : monotone s :=
begin
apply monotone_of_monotone_nat,
intro n,
unfold s,
have h1 := newton_seq_decreasing n,
have h2 : ((x (n + 1)) : ℝ) ≤ ((x n) : ℝ),
norm_cast, linarith,
exact (sub_le_sub_iff_left (real.sqrt 2)).mpr h2,
done
end
theorem sqrt_sub_newton_below_zero : ∀ n : ℕ, s n < (0 : ℝ) :=
begin
unfold s,
intro n,
rw sub_lt, rw sub_zero,
have h1 := newton_seq_bounded_below n,
have h2 := newton_seq_positive n,
set X := x n with hX,
have h3 : 0 ≤ (2 : ℝ), linarith,
have h4 : 0 ≤ X, linarith,
have h41 : 0 ≤ ((X * X) : ℝ), nlinarith,
have h42 : 2 < ((X * X) : ℝ), norm_cast, exact h1,
have h5 := (real.sqrt_lt h3 h41).mpr h42,
rw ← pow_two at h5,
rw real.sqrt_sqr at h5, exact h5,
norm_cast, exact h4,
end
lemma sqrt_sub_newton_range_subset : set.range s ⊆ set.Iic (0:ℝ) :=
begin
unfold set.range,
have h := sqrt_sub_newton_below_zero,
intros x hx,
cases hx with m hm,
have h1 := h m,
rw hm at h1,
rw set.mem_Iic,
linarith,
end
theorem sqrt_sub_newton_bounded_above : bdd_above (set.range s) :=
begin
have h1 := sqrt_sub_newton_range_subset,
have h2 : ∃ a : ℝ, (set.range s) ⊆ set.Iic a,
use [0, h1],
exact bdd_above_iff_subset_Iic.mpr h2,
end
theorem sqrt_sub_newton_tendsto_finite_limit : ∃ L0 : ℝ, tendsto s at_top (𝓝 L0) :=
begin
have h1 := tendsto_of_monotone sqrt_sub_newton_monotone,
cases h1 with hf ht,
have h2 := unbounded_of_tendsto_at_top hf,
have h3 := sqrt_sub_newton_bounded_above,
exfalso, -- this sequence doesn't go to infinity; it is bounded above
exact h2 h3,
exact ht, done
end
theorem sqrt_sub_newton_tendsto_finite_limit_v1 : ∃ L0 : ℝ, tendsto s at_top (𝓝 L0) :=
begin
have h1 := tendsto_of_monotone sqrt_sub_newton_monotone,
cases h1 with hf ht,
have h2 := unbounded_of_tendsto_at_top hf,
have h3 := sqrt_sub_newton_bounded_above,
exfalso, -- this sequence doesn't go to infinity; it is bounded above
exact h2 h3,
exact ht, done
end
-- This is due to Yuri Kudryashov
example (s : ℕ → ℝ) (L : ℝ) (h : ∀ n : ℕ, s n < L) : ¬ (tendsto s at_top at_top) :=
begin
intro H,
--have h0 := H.eventually,
have h1 : ∃ n, L ≤ s n := (H.eventually (eventually_ge_at_top L)).exists,
cases h1 with n hn,
have h2 := h n,
linarith, done
end
-- This is the sequence of Newton approximations, viewed as real numbers
def xR (n : ℕ) : ℝ := real.sqrt 2 - s n
-- We can actually prove `xR` and `x` generate the same values
theorem xR_same_as_x (n : ℕ) : ((x n): ℝ) = xR n :=
begin
have h1 : xR n = real.sqrt 2 - s n, refl,
have h2 : s n = real.sqrt 2 - x n, refl,
rw h2 at h1,
have h3 : real.sqrt 2 - (real.sqrt 2 - ↑(x n)) = ↑(x n),
linarith,
rw h3 at h1,
exact h1.symm, done
end
-- Rewrite the recursive formula as a function application
--def f (x : ℝ) : ℝ := (1/2) * (x + 2 / x)
def f (x : ℝ) : ℝ := ( x * x + 2) / ( 2 * x)
-- This is needed in the limit calculation result
lemma rw_recursion : ∀ n : ℕ, xR (n+1) = f (xR n) :=
begin
intro n,
have h1 := xR_same_as_x n,
have h2 := xR_same_as_x (n+1),
rw [← h1, ← h2],
unfold f,
have h3 : x (n+1) = ( x n * x n + 2) / ( 2 * x n), refl,
rw h3,
norm_cast, done
end
lemma f_contin_at_L (L : ℝ) (h : L ≠ 0) : continuous_at f L :=
begin
apply continuous_at.div,
swap 3, { norm_num, exact h, },
apply continuous_at.add,
apply continuous_at.mul,
apply continuous_at_id,
apply continuous_at_id,
apply continuous_at_const,
apply continuous_at.mul,
apply continuous_at_const,
exact continuous_at_id, done
end
-- So now the final push
-- The sequence `xR` has a finite limit:
theorem newton_tendsto_finite_limit : ∃ L : ℝ, tendsto xR at_top (𝓝 L) :=
begin
have h1 := sqrt_sub_newton_tendsto_finite_limit,
cases h1 with l0 hl0,
use real.sqrt 2 - l0,
apply tendsto.sub,
exact tendsto_const_nhds,
exact hl0, done
end
-- The limit can't be zero:
theorem newton_tendsto_nonzero_limit (L : ℝ) : tendsto xR at_top (𝓝 L) → L ≠ 0 :=
begin
have h2 := xR_same_as_x,
have h0 : ∀ n : ℕ, 0 < xR n,
intro n,
have g0 := newton_seq_positive n,
have h21 := h2 n,
rw ← h21, norm_cast, exact g0,
have h1 := newton_seq_bounded_below,
have h3 : ∀ n : ℕ, real.sqrt 2 < xR n,
intro n,
have h30 := h1 n,
have h31 := h2 n,
have h00 := h0 n,
have h32 : 0 ≤ (2:ℝ), linarith,
have h33 : 0 ≤ (xR n) * (xR n), nlinarith,
have h34 : 2 < (xR n) * (xR n), rw ← h31, norm_cast, exact h30,
have h35 := (real.sqrt_lt h32 h33).mpr h34,
have h01 : 0 ≤ xR n, linarith,
have h36 : real.sqrt ((xR n) * (xR n)) = xR n, exact real.sqrt_mul_self h01,
rw h36 at h35,
exact h35,
intros H hL,
have G := aux_3 xR h3,
rw hL at H,
exact G H, done
end
-- And this limit satisfies a specific equation
theorem newton_limit_satisfies (L : ℝ) (H : tendsto xR at_top ((𝓝 L) )) :
f L = L :=
begin
have h1 : tendsto (xR ∘ nat.succ) at_top (𝓝 L) := (tendsto_add_at_top_iff_nat 1).mpr H,
have h2 := (tendsto_add_at_top_iff_nat 1).mpr H,
rw show xR ∘ nat.succ = f ∘ xR, from funext rw_recursion at h1,
have hL : L ≠ 0, exact newton_tendsto_nonzero_limit L H,
have hf : continuous_at f L, exact f_contin_at_L L hL,
exact tendsto_nhds_unique (tendsto.comp hf H) h1,
done
end
-- The equation for the limit `L` can be solved to get `L = real.sqrt 2`
-- Courtesy Patrick Massot
lemma solve_limit_eqn {L : ℝ} (h : L = (2 + L * L)/(2*L)) (hL : 0 < L) : L = real.sqrt 2 :=
begin
apply_fun (λ x, 2*L*x) at h,
simp_rw mul_div_cancel' _ (ne_of_gt (by linarith) : 2*L ≠ 0) at h,
apply_fun (λ x, x - L*L) at h,
ring at h,
symmetry,
rwa real.sqrt_eq_iff_sqr_eq; linarith,
end
--------- Scratch space below here:
-- This slick proof due to Patrick Massot:
lemma dan_limit {u : ℕ → ℝ} {L : ℝ} {f : ℝ → ℝ} (hu : tendsto u at_top $ 𝓝 L)
(hf : continuous_at f L) (huf : ∀ n, u (n+1) = f (u n)) : f L = L :=
begin
have lim : tendsto (u ∘ nat.succ) at_top (𝓝 L) :=
(tendsto_add_at_top_iff_nat 1).mpr hu,
rw show u ∘ nat.succ = f ∘ u, from funext huf at lim,
exact tendsto_nhds_unique (tendsto.comp hf hu) lim
end
-- This one is due to Mario Carneiro:
example (s : ℕ → ℝ) (hs : ∀ n : ℕ, 2 < s n) : ¬ (tendsto s at_top (𝓝 0)) :=
begin
have : (0:ℝ) ∉ set.Ici (2 : ℝ), { simp, norm_num },
rw ← closure_Ioi at this,
exact λ h, this (mem_closure_of_tendsto h (eventually_of_forall hs)),
done
end
|
(* Title: Glued Codes
File: CoW_Graph_Lemma.Glued_Codes
Author: Štěpán Holub, Charles University
Author: Martin Raška, Charles University
Part of Combinatorics on Words Formalized. See https://gitlab.com/formalcow/combinatorics-on-words-formalized/
*)
theory Glued_Codes
imports Combinatorics_Words.Submonoids
begin
chapter "Glued codes"
section \<open>Lists that do not end with a fixed letter\<close>
lemma append_last_neq:
"us = \<epsilon> \<or> last us \<noteq> w \<Longrightarrow> vs = \<epsilon> \<or> last vs \<noteq> w \<Longrightarrow> us \<cdot> vs = \<epsilon> \<or> last (us \<cdot> vs) \<noteq> w"
by (auto simp only: last_append split: if_split)
lemma last_neq_induct [consumes 1, case_names emp hd_eq hd_neq]:
assumes invariant: "us = \<epsilon> \<or> last us \<noteq> w"
and emp: "P \<epsilon>"
and hd_eq: "\<And>us. us \<noteq> \<epsilon> \<Longrightarrow> last us \<noteq> w \<Longrightarrow> P us \<Longrightarrow> P (w # us)"
and hd_neq: "\<And>u us. u \<noteq> w \<Longrightarrow> us = \<epsilon> \<or> last us \<noteq> w \<Longrightarrow> P us \<Longrightarrow> P (u # us)"
shows "P us"
using invariant proof (induction us)
case (Cons u us)
have inv: "us = \<epsilon> \<or> last us \<noteq> w"
using Cons.prems by (intro disjI) simp
show "P (u # us)"
proof (cases)
assume "u = w"
have *: "us \<noteq> \<epsilon>" and "last us \<noteq> w"
using Cons.prems unfolding \<open>u = w\<close> by auto
then show "P (u # us)" unfolding \<open>u = w\<close> using Cons.IH[OF inv] by (fact hd_eq)
qed (use inv Cons.IH[OF inv] in \<open>fact hd_neq\<close>)
qed (rule \<open>P \<epsilon>\<close>)
lemma last_neq_blockE:
assumes last_neq: "us \<noteq> \<epsilon>" and "last us \<noteq> w"
obtains k u us' where "u \<noteq> w" and "us' = \<epsilon> \<or> last us' \<noteq> w" and "[w] \<^sup>@ k \<cdot> u # us' = us"
using disjI2[OF \<open>last us \<noteq> w\<close>] \<open>us \<noteq> \<epsilon>\<close> proof (induction us rule: last_neq_induct)
case (hd_eq us)
from \<open>us \<noteq> \<epsilon>\<close> show ?case
by (rule hd_eq.IH[rotated]) (intro hd_eq.prems(1)[of _ _ "Suc _"], assumption+, simp)
next
case (hd_neq u us)
from hd_neq.hyps show ?case
by (rule hd_neq.prems(1)[of _ _ 0]) simp
qed blast
lemma last_neq_block_induct [consumes 1, case_names emp block]:
assumes last_neq: "us = \<epsilon> \<or> last us \<noteq> w"
and emp: "P \<epsilon>"
and block: "\<And>k u us. u \<noteq> w \<Longrightarrow> us = \<epsilon> \<or> last us \<noteq> w \<Longrightarrow> P us \<Longrightarrow> P ([w] \<^sup>@ k \<cdot> (u # us))"
shows "P us"
using last_neq proof (induction us rule: ssuf_induct)
case (ssuf us)
show ?case proof (cases "us = \<epsilon>")
assume "us \<noteq> \<epsilon>"
obtain k u us' where "u \<noteq> w" and "us' = \<epsilon> \<or> last us' \<noteq> w" and "[w] \<^sup>@ k \<cdot> u # us' = us"
using \<open>us \<noteq> \<epsilon>\<close> \<open>us = \<epsilon> \<or> last us \<noteq> w\<close> by (elim last_neq_blockE) (simp add: \<open>us \<noteq> \<epsilon>\<close>)
have "us' <s us" and "us' = \<epsilon> \<or> last us' \<noteq> w"
using \<open>us = \<epsilon> \<or> last us \<noteq> w\<close> by (auto simp flip: \<open>[w] \<^sup>@ k \<cdot> u # us' = us\<close>)
from \<open>u \<noteq> w\<close> \<open>us' = \<epsilon> \<or> last us' \<noteq> w\<close> ssuf.IH[OF this]
show "P us" unfolding \<open>[w] \<^sup>@ k \<cdot> u # us' = us\<close>[symmetric] by (fact block)
qed (simp only: emp)
qed
section \<open>Glue a list element with its successors/predecessors\<close>
function glue :: "'a list \<Rightarrow> 'a list list \<Rightarrow> 'a list list" where
glue_emp: "glue w \<epsilon> = \<epsilon>" |
glue_Cons: "glue w (u # us) =
(let glue_tl = glue w us in
if u = w then (u \<cdot> hd glue_tl) # tl glue_tl
else u # glue_tl)"
unfolding prod_eq_iff prod.sel by (cases rule: list.exhaust[of "snd _"]) blast+
termination by (relation "measure (length \<circ> snd)") simp_all
lemma no_gluing: "w \<notin> set us \<Longrightarrow> glue w us = us"
by (induction us) auto
lemma glue_nemp [simp, intro!]: "us \<noteq> \<epsilon> \<Longrightarrow> glue w us \<noteq> \<epsilon>"
by (elim hd_tlE) (auto simp only: glue.simps Let_def split!: if_split)
lemma glue_is_emp_iff [simp]: "glue w us = \<epsilon> \<longleftrightarrow> us = \<epsilon>"
using glue_nemp glue_emp by blast
lemma len_glue: "us = \<epsilon> \<or> last us \<noteq> w \<Longrightarrow> \<^bold>|glue w us\<^bold>| + count_list us w = \<^bold>|us\<^bold>|"
by (induction rule: last_neq_induct) (auto simp add: Let_def)
lemma len_glue_le: assumes "us = \<epsilon> \<or> last us \<noteq> w" shows "\<^bold>|glue w us\<^bold>| \<le> \<^bold>|us\<^bold>|"
using len_glue[OF assms] unfolding nat_le_iff_add eq_commute[of "\<^bold>|us\<^bold>|"] by blast
lemma len_glue_less []: "us = \<epsilon> \<or> last us \<noteq> w \<Longrightarrow> w \<in> set us \<Longrightarrow> \<^bold>|glue w us\<^bold>| < \<^bold>|us\<^bold>|"
by (simp add: count_list_gr_0_iff flip: len_glue[of us])
lemma assumes "us = \<epsilon> \<or> last us \<noteq> w" and "\<epsilon> \<notin> set us"
shows emp_not_in_glue: "\<epsilon> \<notin> set (glue w us)"
and glued_not_in_glue: "w \<notin> set (glue w us)"
unfolding atomize_conj using assms by (induction us rule: last_neq_induct)
(auto simp: Let_def dest!: tl_set lists_hd_in_set[OF glue_nemp[of _ w]])
lemma glue_glue: "us = \<epsilon> \<or> last us \<noteq> w \<Longrightarrow> \<epsilon> \<notin> set us \<Longrightarrow> glue w (glue w us) = glue w us"
using no_gluing[OF glued_not_in_glue].
lemma glue_block_append: assumes "u \<noteq> w"
shows "glue w ([w] \<^sup>@ k \<cdot> (u # us)) = (w \<^sup>@ k \<cdot> u) # glue w us"
by (induction k) (simp_all add: \<open>u \<noteq> w\<close>)
lemma concat_glue [simp]: "us = \<epsilon> \<or> last us \<noteq> w \<Longrightarrow> concat (glue w us) = concat us"
by (induction us rule: last_neq_block_induct) (simp_all add: glue_block_append)
lemma glue_append:
"us = \<epsilon> \<or> last us \<noteq> w \<Longrightarrow> glue w (us \<cdot> vs) = glue w us \<cdot> glue w vs"
by (induction us rule: last_neq_block_induct) (simp_all add: glue_block_append)
lemma glue_pow:
assumes "us = \<epsilon> \<or> last us \<noteq> w"
shows "glue w (us \<^sup>@ k) = (glue w us) \<^sup>@ k"
by (induction k) (simp_all add: assms glue_append)
lemma glue_in_lists_hull [intro]:
"us = \<epsilon> \<or> last us \<noteq> w \<Longrightarrow> us \<in> lists G \<Longrightarrow> glue w us \<in> lists \<langle>G\<rangle>"
by (induction rule: last_neq_induct) (simp_all add: Let_def tl_in_lists prod_cl gen_in)
\<comment> \<open>Gluing from the right (gluing a letter with its predecessor)\<close>
function gluer :: "'a list \<Rightarrow> 'a list list \<Rightarrow> 'a list list" where
gluer_emp: "gluer w \<epsilon> = \<epsilon>" |
gluer_Cons: "gluer w (u # us) =
(let gluer_butlast = gluer w (butlast (u # us)) in
if last (u # us) = w then (butlast gluer_butlast) \<cdot> [last gluer_butlast \<cdot> last (u # us)]
else gluer_butlast \<cdot> [last (u # us)])"
unfolding prod_eq_iff prod.sel by (cases rule: list.exhaust[of "snd _"]) blast+
termination by (relation "measure (length \<circ> snd)") simp_all
lemma gluer_nemp_def: assumes "us \<noteq> \<epsilon>"
shows "gluer w us =
(let gluer_butlast = gluer w (butlast us) in
if last us = w then (butlast gluer_butlast) \<cdot> [last gluer_butlast \<cdot> last us]
else gluer_butlast \<cdot> [last us])"
using gluer_Cons[of w "hd us" "tl us"] unfolding hd_Cons_tl[OF \<open>us \<noteq> \<epsilon>\<close>].
lemma gluer_nemp: assumes "us \<noteq> \<epsilon>" shows "gluer w us \<noteq> \<epsilon>"
unfolding gluer_nemp_def[OF \<open>us \<noteq> \<epsilon>\<close>]
by (simp only: Let_def split!: if_split)
lemma hd_neq_induct [consumes 1, case_names emp snoc_eq snoc_neq]:
assumes invariant: "us = \<epsilon> \<or> hd us \<noteq> w"
and emp: "P \<epsilon>"
and snoc_eq: "\<And>us. us \<noteq> \<epsilon> \<Longrightarrow> hd us \<noteq> w \<Longrightarrow> P us \<Longrightarrow> P (us \<cdot> [w])"
and snoc_neq: "\<And>u us. u \<noteq> w \<Longrightarrow> us = \<epsilon> \<or> hd us \<noteq> w \<Longrightarrow> P us \<Longrightarrow> P (us \<cdot> [u])"
shows "P us"
using last_neq_induct[where P="\<lambda>x. P (rev x)" for P, reversed, unfolded rev_rev_ident, OF assms].
lemma gluer_rev [reversal_rule]: assumes "us = \<epsilon> \<or> last us \<noteq> w"
shows "gluer (rev w) (rev (map rev us)) = rev (map rev (glue w us))"
using assms by (induction us rule: last_neq_induct)
(simp_all add: gluer_nemp_def Let_def map_tl last_rev hd_map)
lemma glue_rev [reversal_rule]: assumes "us = \<epsilon> \<or> hd us \<noteq> w"
shows "glue (rev w) (rev (map rev us)) = rev (map rev (gluer w us))"
using assms by (induction us rule: hd_neq_induct)
(simp_all add: gluer_nemp_def Let_def map_tl last_rev hd_map)
section \<open>Generators with glued element\<close>
text \<open>The following set will turn out to be the generating set of all words whose
decomposition into a generating code does not end with w\<close>
inductive_set glued_gens :: "'a list \<Rightarrow> 'a list set \<Rightarrow> 'a list set"
for w G where
other_gen: "g \<in> G \<Longrightarrow> g \<noteq> w \<Longrightarrow> g \<in> glued_gens w G"
| glued [intro!]: "u \<in> glued_gens w G \<Longrightarrow> w \<cdot> u \<in> glued_gens w G"
lemma in_glued_gensI: assumes "g \<in> G" "g \<noteq> w"
shows "w \<^sup>@ k \<cdot> g = u \<Longrightarrow> u \<in> glued_gens w G"
by (induction k arbitrary: u) (auto simp: other_gen[OF \<open>g \<in> G\<close> \<open>g \<noteq> w\<close>])
lemma in_glued_gensE:
assumes "u \<in> glued_gens w G"
obtains k g where "g \<in> G" and "g \<noteq> w" and "w \<^sup>@ k \<cdot> g = u"
using assms proof (induction)
case (glued u)
show ?case by (auto intro!: glued.IH[OF glued.prems[of _ "Suc _"]])
qed (use pow_zero in blast)
lemma glued_gens_alt_def: "glued_gens w C = {w \<^sup>@ k \<cdot> g | k g. g \<in> C \<and> g \<noteq> w}"
by (blast elim!: in_glued_gensE intro: in_glued_gensI)
lemma glued_hull_sub_hull [simp, intro!]: "w \<in> G \<Longrightarrow> \<langle>glued_gens w G\<rangle> \<subseteq> \<langle>G\<rangle>"
by (rule hull_mono') (auto elim!: in_glued_gensE)
lemma glued_hull_sub_hull': "w \<in> G \<Longrightarrow> u \<in> \<langle>glued_gens w G\<rangle> \<Longrightarrow> u \<in> \<langle>G\<rangle>"
using set_mp[OF glued_hull_sub_hull].
lemma in_glued_hullE:
assumes "w \<in> G" and "u \<in> \<langle>glued_gens w G\<rangle>"
obtains us where "concat us = u" and "us \<in> lists G" and "us = \<epsilon> \<or> last us \<noteq> w"
using \<open>u \<in> \<langle>glued_gens w G\<rangle>\<close> proof (induction arbitrary: thesis)
case (prod_cl v u)
obtain k g where "g \<in> G" and "g \<noteq> w" and "concat ([w] \<^sup>@ k \<cdot> [g]) = v"
using \<open>v \<in> glued_gens w G\<close> by (simp add: concat_pow) (elim in_glued_gensE)
obtain us where u: "concat us = u" and "us \<in> lists G" and "(us = \<epsilon> \<or> last us \<noteq> w)" by fact
have "concat ([w] \<^sup>@ k \<cdot> [g] \<cdot> us) = v \<cdot> u"
by (simp flip: \<open>concat ([w] \<^sup>@ k \<cdot> [g]) = v\<close> \<open>concat us = u\<close>)
with \<open>(us = \<epsilon> \<or> last us \<noteq> w)\<close> show thesis
by (elim prod_cl.prems, intro lists.intros
append_in_lists pow_in_lists \<open>w \<in> G\<close> \<open>g \<in> G\<close> \<open>us \<in> lists G\<close>)
(auto simp: \<open>g \<noteq> w\<close>)
qed (use concat.simps(1) in blast)
lemma glue_in_lists [simp, intro!]:
assumes "us = \<epsilon> \<or> last us \<noteq> w"
shows "us \<in> lists G \<Longrightarrow> glue w us \<in> lists (glued_gens w G)"
using assms by (induction rule: last_neq_block_induct)
(auto simp: glue_block_append intro: in_glued_gensI)
lemma concat_in_glued_hull[intro]:
"us \<in> lists G \<Longrightarrow> us = \<epsilon> \<or> last us \<noteq> w \<Longrightarrow> concat us \<in> \<langle>glued_gens w G\<rangle>"
unfolding concat_glue[symmetric] by (intro concat_in_hull' glue_in_lists)
lemma glued_hull_conv: assumes "w \<in> G"
shows "\<langle>glued_gens w G\<rangle> = {concat us | us. us \<in> lists G \<and> (us = \<epsilon> \<or> last us \<noteq> w)}"
by (blast elim!: in_glued_hullE[OF \<open>w \<in> G\<close>])
section \<open>Bounded gluing\<close>
lemma bounded_glue_in_lists:
assumes "us = \<epsilon> \<or> last us \<noteq> w" and "\<not> [w] \<^sup>@ n \<le>f us"
shows "us \<in> lists G \<Longrightarrow> glue w us \<in> lists {w \<^sup>@ k \<cdot> g | k g. g \<in> G \<and> g \<noteq> w \<and> k < n}"
using assms proof (induction us rule: last_neq_block_induct)
case (block k u us)
have "k < n" and "\<not> [w] \<^sup>@ n \<le>f us"
using \<open>\<not> [w] \<^sup>@ n \<le>f [w] \<^sup>@ k \<cdot> u # us\<close>
by (blast intro!: not_le_imp_less pref_ext le_exps_pref, blast intro!: fac_ext_pref fac_ext_hd)
then show ?case
using \<open>[w] \<^sup>@ k \<cdot> u # us \<in> lists G\<close> \<open>u \<noteq> w\<close> unfolding glue_block_append[OF \<open>u \<noteq> w\<close>]
by (blast intro!: block.IH del: in_listsD in_listsI)
qed simp
subsection \<open>Gluing on binary alphabet\<close>
lemma bounded_bin_glue_in_lists: \<comment> \<open>meaning: a binary code\<close>
assumes "us = \<epsilon> \<or> last us \<noteq> x"
and "\<not> [x] \<^sup>@ n \<le>f us"
and "us \<in> lists {x, y}"
shows "glue x us \<in> lists {x \<^sup>@ k \<cdot> y | k. k < n}"
using bounded_glue_in_lists[OF assms] by blast
lemma single_bin_glue_in_lists: \<comment> \<open>meaning: a single occurrence\<close>
assumes "us = \<epsilon> \<or> last us \<noteq> x"
and "\<not> [x,x] \<le>f us"
and "us \<in> lists {x, y}"
shows "glue x us \<in> lists {x \<cdot> y, y}"
using bounded_bin_glue_in_lists[of _ _ 2, simplified, OF assms] unfolding numeral_nat
by (auto elim!: sub_lists_mono[rotated] less_SucE)
lemma count_list_single_bin_glue:
assumes "x \<noteq> \<epsilon>" and "x \<noteq> y"
and "us = \<epsilon> \<or> last us \<noteq> x"
and "us \<in> lists {x,y}"
and "\<not> [x,x] \<le>f us"
shows "count_list (glue x us) (x \<cdot> y) = count_list us x"
and "count_list (glue x us) y + count_list us x = count_list us y"
using assms(3-5) unfolding atomize_conj pow_Suc[symmetric]
proof (induction us rule: last_neq_block_induct)
case (block k u us)
have "u = y" using \<open>[x] \<^sup>@ k \<cdot> u # us \<in> lists {x, y}\<close> \<open>u \<noteq> x\<close> by simp
have IH: "count_list (glue x us) (x \<cdot> y) = count_list us x \<and>
count_list (glue x us) y + count_list us x = count_list us y"
using block.prems by (intro block.IH) (simp, blast intro!: fac_ext_pref fac_ext_hd)
have "\<not> [x] \<^sup>@ Suc (Suc 0) \<le>f [x] \<^sup>@ k \<cdot> u # us"
using block.prems(2) by auto
then have "k < Suc (Suc 0)"
by (blast intro!: not_le_imp_less pref_ext le_exps_pref)
then show ?case unfolding \<open>u = y\<close> glue_block_append[OF \<open>x \<noteq> y\<close>[symmetric]]
by (elim less_SucE less_zeroE) (simp_all add: \<open>x \<noteq> y\<close> \<open>x \<noteq> y\<close>[symmetric] \<open>x \<noteq> \<epsilon>\<close> IH)
qed simp
section \<open>Code with glued element\<close>
context code
begin
text \<open>If the original generating set is a code, then also the glued generators form a code\<close>
lemma glued_hull_last_dec: assumes "w \<in> \<C>" and "u \<in> \<langle>glued_gens w \<C>\<rangle>" and "u \<noteq> \<epsilon>"
shows "last (Dec \<C> u) \<noteq> w"
using \<open>u \<in> \<langle>glued_gens w \<C>\<rangle>\<close>
by (elim in_glued_hullE[OF \<open>w \<in> \<C>\<close>]) (auto simp: code_unique_dec \<open>u \<noteq> \<epsilon>\<close>)
lemma in_glued_hullI [intro]:
assumes "u \<in> \<langle>\<C>\<rangle>" and "(u = \<epsilon> \<or> last (Dec \<C> u) \<noteq> w)"
shows "u \<in> \<langle>glued_gens w \<C>\<rangle>"
using concat_in_glued_hull[OF dec_in_lists[OF \<open>u \<in> \<langle>\<C>\<rangle>\<close>], of w]
by (simp add: \<open>u \<in> \<langle>\<C>\<rangle>\<close> \<open>u = \<epsilon> \<or> last (Dec \<C> u) \<noteq> w\<close>)
lemma code_glued_hull_conv: assumes "w \<in> \<C>"
shows "\<langle>glued_gens w \<C>\<rangle> = {u \<in> \<langle>\<C>\<rangle>. u = \<epsilon> \<or> last (Dec \<C> u) \<noteq> w}"
proof
show "\<langle>glued_gens w \<C>\<rangle> \<subseteq> {u \<in> \<langle>\<C>\<rangle>. u = \<epsilon> \<or> last (Dec \<C> u) \<noteq> w}"
using glued_hull_sub_hull'[OF \<open>w \<in> \<C>\<close>] glued_hull_last_dec[OF \<open>w \<in> \<C>\<close>] by blast
show "{u \<in> \<langle>\<C>\<rangle>. u = \<epsilon> \<or> last (Dec \<C> u) \<noteq> w} \<subseteq> \<langle>glued_gens w \<C>\<rangle>"
using in_glued_hullI by blast
qed
lemma in_glued_hull_iff:
assumes "w \<in> \<C>" and "u \<in> \<langle>\<C>\<rangle>"
shows "u \<in> \<langle>glued_gens w \<C>\<rangle> \<longleftrightarrow> u = \<epsilon> \<or> last (Dec \<C> u) \<noteq> w"
by (simp add: \<open>w \<in> \<C>\<close> \<open>u \<in> \<langle>\<C>\<rangle>\<close> code_glued_hull_conv)
lemma glued_not_in_glued_hull: "w \<in> \<C> \<Longrightarrow> w \<notin> \<langle>glued_gens w \<C>\<rangle>"
unfolding in_glued_hull_iff[OF _ gen_in] code_el_dec
by (simp add: in_code_nemp)
lemma glued_gens_nemp: assumes "u \<in> glued_gens w \<C>" shows "u \<noteq> \<epsilon>"
using assms by (induction) (auto simp add: in_code_nemp)
lemma glued_gens_code: assumes "w \<in> \<C>" shows "code (glued_gens w \<C>)"
proof
show "us = vs" if "us \<in> lists (glued_gens w \<C>)" and "vs \<in> lists (glued_gens w \<C>)"
and "concat us = concat vs" for us vs
using that proof (induction rule: list_induct2')
case (4 u us v vs)
have *: "us \<in> lists (glued_gens w \<C>) \<Longrightarrow> us \<in> lists \<langle>\<C>\<rangle>" for us
using sub_lists_mono[OF subset_trans[OF genset_sub glued_hull_sub_hull[OF \<open>w \<in> \<C>\<close>]]].
obtain k u' l v'
where "u' \<in> \<C>" "u' \<noteq> w" "w \<^sup>@ k \<cdot> u' = u"
and "v' \<in> \<C>" "v' \<noteq> w" "w \<^sup>@ l \<cdot> v' = v"
using "4.prems"(1-2) by simp (elim conjE in_glued_gensE)
from this(3, 6) "4.prems" \<open>w \<in> \<C>\<close>
have "concat (([w] \<^sup>@ k \<cdot> [u']) \<cdot> (Ref \<C> us)) = concat (([w] \<^sup>@ l \<cdot> [v']) \<cdot> (Ref \<C> vs))"
by (simp add: concat_ref * concat_pow lassoc)
with \<open>w \<in> \<C>\<close> \<open>u' \<in> \<C>\<close> \<open>v' \<in> \<C>\<close> "4.prems"(1-2)
have "[w] \<^sup>@ k \<cdot> [u'] \<bowtie> [w] \<^sup>@ l \<cdot> [v']"
by (elim eqd_comp[OF is_code, rotated 2])
(simp_all add: "*" pow_in_lists ref_in')
with \<open>u' \<noteq> w\<close> \<open>v' \<noteq> w\<close> \<open>w \<^sup>@ k \<cdot> u' = u\<close> \<open>w \<^sup>@ l \<cdot> v' = v\<close>
have "u = v"
by (elim sing_pref_comp_mismatch[rotated 2, elim_format]) blast+
then show "u # us = v # vs"
using "4.IH" "4.prems"(1-3) by simp
qed (auto dest!: glued_gens_nemp)
qed
text \<open>A crucial lemma showing the relation between gluing and the decomposition into generators\<close>
lemma dec_glued_gens: assumes "w \<in> \<C>" and "u \<in> \<langle>glued_gens w \<C>\<rangle>"
shows "Dec (glued_gens w \<C>) u = glue w (Dec \<C> u)"
using \<open>u \<in> \<langle>glued_gens w \<C>\<rangle>\<close> glued_hull_sub_hull'[OF \<open>w \<in> \<C>\<close> \<open>u \<in> \<langle>glued_gens w \<C>\<rangle>\<close>]
by (intro code.code_unique_dec glued_gens_code)
(simp_all add: in_glued_hull_iff \<open>w \<in> \<C>\<close>)
lemma ref_glue: "us = \<epsilon> \<or> last us \<noteq> w \<Longrightarrow> us \<in> lists \<C> \<Longrightarrow> Ref \<C> (glue w us) = us"
by (intro refI glue_in_lists_hull) simp_all
end (* end of context code *)
theorem glued_code:
assumes "code C" and "w \<in> C"
shows "code {w \<^sup>@ k \<cdot> u |k u. u \<in> C \<and> u \<noteq> w}"
using code.glued_gens_code[OF \<open>code C\<close> \<open>w \<in> C\<close>] unfolding glued_gens_alt_def.
section \<open>Gluing is primitivity preserving\<close>
text \<open>It is easy to obtain that gluing lists of code elements preserves primitivity.
We provide the result under weaker condition where glue blocks of the list
have unique concatenation.\<close>
lemma (in code) code_prim_glue:
assumes last_neq: "us = \<epsilon> \<or> last us \<noteq> w"
and "us \<in> lists \<C>"
shows "primitive us \<Longrightarrow> primitive (glue w us)"
using prim_map_prim[OF prim_concat_prim, of "decompose \<C>" "glue w us"]
unfolding refine_def[symmetric] ref_glue[OF assms].
\<comment> \<open>In the context of code the inverse to the glue function is the @{const refine} function,
i.e. @{term "\<lambda>vs. concat (map (decompose \<C>) vs)"}, see @{thm code.ref_glue}.
The role of the @{const decompose} function outside the code context supply the 'unglue' function,
which maps glued blocks to its unique preimages (see below).\<close>
definition glue_block :: "'a list \<Rightarrow>'a list list \<Rightarrow> 'a list list \<Rightarrow> bool"
where "glue_block w us bs =
(\<exists>ps k u ss. (ps = \<epsilon> \<or> last ps \<noteq> w) \<and> u \<noteq> w \<and> ps \<cdot> [w] \<^sup>@ k \<cdot> u # ss = us \<and> [w] \<^sup>@ k \<cdot> [u] = bs)"
lemma glue_blockI [intro]:
"ps = \<epsilon> \<or> last ps \<noteq> w \<Longrightarrow> u \<noteq> w \<Longrightarrow> ps \<cdot> [w] \<^sup>@ k \<cdot> u # ss = us \<Longrightarrow> [w] \<^sup>@ k \<cdot> [u] = bs
\<Longrightarrow> glue_block w us bs"
unfolding glue_block_def by (intro exI conjI)
lemma glue_blockE:
assumes "glue_block w us bs"
obtains ps k u ss where "ps = \<epsilon> \<or> last ps \<noteq> w" and "u \<noteq> w" "ps \<cdot> [w] \<^sup>@ k \<cdot> u # ss = us"
and "[w] \<^sup>@ k \<cdot> [u] = bs"
using assms unfolding glue_block_def by (elim exE conjE)
lemma assumes "glue_block w us bs"
shows glue_block_of_appendL: "glue_block w (us \<cdot> vs) bs"
and glue_block_of_appendR: "vs = \<epsilon> \<or> last vs \<noteq> w \<Longrightarrow> glue_block w (vs \<cdot> us) bs"
using \<open>glue_block w us bs\<close> by (elim glue_blockE, use nothing in \<open>
intro glue_blockI[of _ w _ _ "_ \<cdot> vs" "us \<cdot> vs" bs]
glue_blockI[OF append_last_neq, of "vs" w _ _ _ _ "vs \<cdot> us" bs],
simp_all only: eq_commute[of _ us] rassoc append_Cons refl not_False_eq_True\<close>)+
lemma glue_block_of_block_append:
"u \<noteq> w \<Longrightarrow> glue_block w us bs \<Longrightarrow> glue_block w ([w] \<^sup>@ k \<cdot> u # us) bs"
by (simp only: hd_word[of _ us] lassoc) (elim glue_block_of_appendR, simp_all)
lemma in_set_glueE:
assumes last_neq: "us = \<epsilon> \<or> last us \<noteq> w"
and "b \<in> set (glue w us)"
obtains bs where "glue_block w us bs" and "concat bs = b"
using assms proof (induction us rule: last_neq_block_induct)
case (block k u us)
show thesis using \<open>b \<in> set (glue w ([w] \<^sup>@ k \<cdot> u # us))\<close>
proof (auto simp add: glue_block_append \<open>u \<noteq> w\<close>)
show "b = w \<^sup>@ k \<cdot> u \<Longrightarrow> thesis"
by (auto simp add: concat_pow intro!: block.prems(1) glue_blockI[OF _ \<open>u \<noteq> w\<close> _ refl])
show "b \<in> set (glue w us) \<Longrightarrow> thesis"
by (auto intro!: block.IH[OF block.prems(1)] glue_block_of_block_append \<open>u \<noteq> w\<close>)
qed
qed simp
definition unglue :: "'a list \<Rightarrow> 'a list list \<Rightarrow> 'a list \<Rightarrow> 'a list list"
where "unglue w us b = (THE bs. glue_block w us bs \<and> concat bs = b)"
lemma unglueI:
assumes unique_blocks: "\<And>bs\<^sub>1 bs\<^sub>2. glue_block w us bs\<^sub>1 \<Longrightarrow> glue_block w us bs\<^sub>2
\<Longrightarrow> concat bs\<^sub>1 = concat bs\<^sub>2 \<Longrightarrow> bs\<^sub>1 = bs\<^sub>2"
shows "glue_block w us bs \<Longrightarrow> concat bs = b \<Longrightarrow> unglue w us b = bs"
unfolding unglue_def by (blast intro: unique_blocks)
lemma concat_map_unglue_glue:
assumes last_neq: "us = \<epsilon> \<or> last us \<noteq> w"
and unique_blocks: "\<And>vs\<^sub>1 vs\<^sub>2. glue_block w us vs\<^sub>1 \<Longrightarrow> glue_block w us vs\<^sub>2
\<Longrightarrow> concat vs\<^sub>1 = concat vs\<^sub>2 \<Longrightarrow> vs\<^sub>1 = vs\<^sub>2"
shows "concat (map (unglue w us) (glue w us)) = us"
using assms proof (induction us rule: last_neq_block_induct)
case (block k u us)
have IH: "concat (map (unglue w us) (glue w us)) = us"
using block.IH[OF block.prems] by (blast intro!: glue_block_of_block_append \<open>u \<noteq> w\<close>)
have *: "map (unglue w ([w] \<^sup>@ k \<cdot> u # us)) (glue w us) = map (unglue w us) (glue w us)"
by (auto simp only: map_eq_conv unglue_def del: the_equality
elim!: in_set_glueE[OF \<open>us = \<epsilon> \<or> last us \<noteq> w\<close>], intro the_equality)
(simp_all only: the_equality block.prems glue_block_of_block_append[OF \<open>u \<noteq> w\<close>])
show "concat (map (unglue w ([w] \<^sup>@ k \<cdot> u # us)) (glue w ([w] \<^sup>@ k \<cdot> u # us))) = [w] \<^sup>@ k \<cdot> u # us"
by (auto simp add: concat_pow glue_block_append[OF \<open>u \<noteq> w\<close>] * IH
intro!: unglueI intro: glue_blockI[OF _ \<open>u \<noteq> w\<close>] block.prems)
qed simp
lemma prim_glue:
assumes last_neq: "us = \<epsilon> \<or> last us \<noteq> w"
and unique_blocks: "\<And>bs\<^sub>1 bs\<^sub>2. glue_block w us bs\<^sub>1 \<Longrightarrow> glue_block w us bs\<^sub>2
\<Longrightarrow> concat bs\<^sub>1 = concat bs\<^sub>2 \<Longrightarrow> bs\<^sub>1 = bs\<^sub>2"
shows "primitive us \<Longrightarrow> primitive (glue w us)"
using prim_map_prim[OF prim_concat_prim, of "unglue w us" "glue w us"]
by (simp only: concat_map_unglue_glue assms)
subsection \<open>Gluing on binary alphabet\<close>
lemma bin_glue_blockE:
assumes "us \<in> lists {x, y}"
and "glue_block x us bs"
obtains k where "[x] \<^sup>@ k \<cdot> [y] = bs"
using assms by (auto simp only: glue_block_def del: in_listsD)
lemma unique_bin_glue_blocks:
assumes "us \<in> lists {x, y}" and "x \<noteq> \<epsilon>"
shows "glue_block x us bs\<^sub>1 \<Longrightarrow> glue_block x us bs\<^sub>2 \<Longrightarrow> concat bs\<^sub>1 = concat bs\<^sub>2 \<Longrightarrow> bs\<^sub>1 = bs\<^sub>2"
by (auto simp: concat_pow eq_pow_exp[OF \<open>x \<noteq> \<epsilon>\<close>] elim!: bin_glue_blockE[OF \<open>us \<in> lists {x, y}\<close>])
lemma prim_bin_glue:
assumes "us \<in> lists {x, y}" and "x \<noteq> \<epsilon>"
and "us = \<epsilon> \<or> last us \<noteq> x"
shows "primitive us \<Longrightarrow> primitive (glue x us)"
using prim_glue[OF \<open>us = \<epsilon> \<or> last us \<noteq> x\<close> unique_bin_glue_blocks[OF assms(1-2)]].
end
|
# Databricks notebook source
print("Hello World!", quote = FALSE)
# COMMAND ----------
print(paste("How","are","you?"))
# COMMAND ----------
|
[STATEMENT]
lemma types_conf_smaller_types:
"\<And>es Ts. \<lbrakk>length es = length Ts'; types_conf P E h es Ts'; P \<turnstile> Ts' [\<le>] Ts \<rbrakk>
\<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
proof(induct Ts')
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>es Ts. \<lbrakk>length es = length []; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> []; P \<turnstile> [] [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
2. \<And>a Ts' es Ts. \<lbrakk>\<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts; length es = length (a # Ts'); P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> a # Ts'; P \<turnstile> (a # Ts') [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
case Nil
[PROOF STATE]
proof (state)
this:
length es = length []
P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> []
P \<turnstile> [] [\<le>] Ts
goal (2 subgoals):
1. \<And>es Ts. \<lbrakk>length es = length []; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> []; P \<turnstile> [] [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
2. \<And>a Ts' es Ts. \<lbrakk>\<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts; length es = length (a # Ts'); P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> a # Ts'; P \<turnstile> (a # Ts') [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
thus ?case
[PROOF STATE]
proof (prove)
using this:
length es = length []
P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> []
P \<turnstile> [] [\<le>] Ts
goal (1 subgoal):
1. \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
goal (1 subgoal):
1. \<And>a Ts' es Ts. \<lbrakk>\<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts; length es = length (a # Ts'); P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> a # Ts'; P \<turnstile> (a # Ts') [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>a Ts' es Ts. \<lbrakk>\<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts; length es = length (a # Ts'); P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> a # Ts'; P \<turnstile> (a # Ts') [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
case (Cons S Ss)
[PROOF STATE]
proof (state)
this:
\<lbrakk>length ?es = length Ss; P,E,h \<turnstile> ?es [:]\<^bsub>NT\<^esub> Ss; P \<turnstile> Ss [\<le>] ?Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> ?es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] ?Ts
length es = length (S # Ss)
P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> S # Ss
P \<turnstile> (S # Ss) [\<le>] Ts
goal (1 subgoal):
1. \<And>a Ts' es Ts. \<lbrakk>\<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts; length es = length (a # Ts'); P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> a # Ts'; P \<turnstile> (a # Ts') [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
have length:"length es = length(S#Ss)"
and types_conf:"types_conf P E h es (S#Ss)"
and subs:"P \<turnstile> (S#Ss) [\<le>] Ts"
and IH:"\<And>es Ts. \<lbrakk>length es = length Ss; types_conf P E h es Ss; P \<turnstile> Ss [\<le>] Ts\<rbrakk>
\<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (length es = length (S # Ss) &&& P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> S # Ss) &&& P \<turnstile> (S # Ss) [\<le>] Ts &&& (\<And>es Ts. \<lbrakk>length es = length Ss; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ss; P \<turnstile> Ss [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts)
[PROOF STEP]
by fact+
[PROOF STATE]
proof (state)
this:
length es = length (S # Ss)
P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> S # Ss
P \<turnstile> (S # Ss) [\<le>] Ts
\<lbrakk>length ?es = length Ss; P,E,h \<turnstile> ?es [:]\<^bsub>NT\<^esub> Ss; P \<turnstile> Ss [\<le>] ?Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> ?es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] ?Ts
goal (1 subgoal):
1. \<And>a Ts' es Ts. \<lbrakk>\<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts; length es = length (a # Ts'); P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> a # Ts'; P \<turnstile> (a # Ts') [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
from subs
[PROOF STATE]
proof (chain)
picking this:
P \<turnstile> (S # Ss) [\<le>] Ts
[PROOF STEP]
obtain U Us where Ts:"Ts = U#Us"
[PROOF STATE]
proof (prove)
using this:
P \<turnstile> (S # Ss) [\<le>] Ts
goal (1 subgoal):
1. (\<And>U Us. Ts = U # Us \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by(cases Ts) auto
[PROOF STATE]
proof (state)
this:
Ts = U # Us
goal (1 subgoal):
1. \<And>a Ts' es Ts. \<lbrakk>\<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts; length es = length (a # Ts'); P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> a # Ts'; P \<turnstile> (a # Ts') [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
from length
[PROOF STATE]
proof (chain)
picking this:
length es = length (S # Ss)
[PROOF STEP]
obtain e' es' where es:"es = e'#es'"
[PROOF STATE]
proof (prove)
using this:
length es = length (S # Ss)
goal (1 subgoal):
1. (\<And>e' es'. es = e' # es' \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by(cases es) auto
[PROOF STATE]
proof (state)
this:
es = e' # es'
goal (1 subgoal):
1. \<And>a Ts' es Ts. \<lbrakk>\<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts; length es = length (a # Ts'); P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> a # Ts'; P \<turnstile> (a # Ts') [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
with types_conf
[PROOF STATE]
proof (chain)
picking this:
P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> S # Ss
es = e' # es'
[PROOF STEP]
have type:"P,E,h \<turnstile> e' :\<^bsub>NT\<^esub> S"
and type':"types_conf P E h es' Ss"
[PROOF STATE]
proof (prove)
using this:
P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> S # Ss
es = e' # es'
goal (1 subgoal):
1. P,E,h \<turnstile> e' :\<^bsub>NT\<^esub> S &&& P,E,h \<turnstile> es' [:]\<^bsub>NT\<^esub> Ss
[PROOF STEP]
by simp_all
[PROOF STATE]
proof (state)
this:
P,E,h \<turnstile> e' :\<^bsub>NT\<^esub> S
P,E,h \<turnstile> es' [:]\<^bsub>NT\<^esub> Ss
goal (1 subgoal):
1. \<And>a Ts' es Ts. \<lbrakk>\<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts; length es = length (a # Ts'); P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> a # Ts'; P \<turnstile> (a # Ts') [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
from subs Ts
[PROOF STATE]
proof (chain)
picking this:
P \<turnstile> (S # Ss) [\<le>] Ts
Ts = U # Us
[PROOF STEP]
have subs':"P \<turnstile> Ss [\<le>] Us" and sub:"P \<turnstile> S \<le> U"
[PROOF STATE]
proof (prove)
using this:
P \<turnstile> (S # Ss) [\<le>] Ts
Ts = U # Us
goal (1 subgoal):
1. P \<turnstile> Ss [\<le>] Us &&& P \<turnstile> S \<le> U
[PROOF STEP]
by (simp_all add:fun_of_def)
[PROOF STATE]
proof (state)
this:
P \<turnstile> Ss [\<le>] Us
P \<turnstile> S \<le> U
goal (1 subgoal):
1. \<And>a Ts' es Ts. \<lbrakk>\<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts; length es = length (a # Ts'); P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> a # Ts'; P \<turnstile> (a # Ts') [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
from sub type
[PROOF STATE]
proof (chain)
picking this:
P \<turnstile> S \<le> U
P,E,h \<turnstile> e' :\<^bsub>NT\<^esub> S
[PROOF STEP]
obtain T'' where step:"P,E,h \<turnstile> e' : T'' \<and> P \<turnstile> T'' \<le> U"
[PROOF STATE]
proof (prove)
using this:
P \<turnstile> S \<le> U
P,E,h \<turnstile> e' :\<^bsub>NT\<^esub> S
goal (1 subgoal):
1. (\<And>T''. P,E,h \<turnstile> e' : T'' \<and> P \<turnstile> T'' \<le> U \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by(cases S,auto,cases U,auto)
[PROOF STATE]
proof (state)
this:
P,E,h \<turnstile> e' : T'' \<and> P \<turnstile> T'' \<le> U
goal (1 subgoal):
1. \<And>a Ts' es Ts. \<lbrakk>\<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts; length es = length (a # Ts'); P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> a # Ts'; P \<turnstile> (a # Ts') [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
from length es
[PROOF STATE]
proof (chain)
picking this:
length es = length (S # Ss)
es = e' # es'
[PROOF STEP]
have "length es' = length Ss"
[PROOF STATE]
proof (prove)
using this:
length es = length (S # Ss)
es = e' # es'
goal (1 subgoal):
1. length es' = length Ss
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
length es' = length Ss
goal (1 subgoal):
1. \<And>a Ts' es Ts. \<lbrakk>\<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts; length es = length (a # Ts'); P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> a # Ts'; P \<turnstile> (a # Ts') [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
from IH[OF this type' subs']
[PROOF STATE]
proof (chain)
picking this:
\<exists>Ts''. P,E,h \<turnstile> es' [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Us
[PROOF STEP]
obtain Ts''
where "P,E,h \<turnstile> es' [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Us"
[PROOF STATE]
proof (prove)
using this:
\<exists>Ts''. P,E,h \<turnstile> es' [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Us
goal (1 subgoal):
1. (\<And>Ts''. P,E,h \<turnstile> es' [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Us \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
P,E,h \<turnstile> es' [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Us
goal (1 subgoal):
1. \<And>a Ts' es Ts. \<lbrakk>\<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts; length es = length (a # Ts'); P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> a # Ts'; P \<turnstile> (a # Ts') [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
with step
[PROOF STATE]
proof (chain)
picking this:
P,E,h \<turnstile> e' : T'' \<and> P \<turnstile> T'' \<le> U
P,E,h \<turnstile> es' [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Us
[PROOF STEP]
have "P,E,h \<turnstile> (e'#es') [:] (T''#Ts'') \<and> P \<turnstile> (T''#Ts'') [\<le>] (U#Us)"
[PROOF STATE]
proof (prove)
using this:
P,E,h \<turnstile> e' : T'' \<and> P \<turnstile> T'' \<le> U
P,E,h \<turnstile> es' [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Us
goal (1 subgoal):
1. P,E,h \<turnstile> e' # es' [:] T'' # Ts'' \<and> P \<turnstile> (T'' # Ts'') [\<le>] (U # Us)
[PROOF STEP]
by (auto simp:fun_of_def)
[PROOF STATE]
proof (state)
this:
P,E,h \<turnstile> e' # es' [:] T'' # Ts'' \<and> P \<turnstile> (T'' # Ts'') [\<le>] (U # Us)
goal (1 subgoal):
1. \<And>a Ts' es Ts. \<lbrakk>\<And>es Ts. \<lbrakk>length es = length Ts'; P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> Ts'; P \<turnstile> Ts' [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts; length es = length (a # Ts'); P,E,h \<turnstile> es [:]\<^bsub>NT\<^esub> a # Ts'; P \<turnstile> (a # Ts') [\<le>] Ts\<rbrakk> \<Longrightarrow> \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
with es Ts
[PROOF STATE]
proof (chain)
picking this:
es = e' # es'
Ts = U # Us
P,E,h \<turnstile> e' # es' [:] T'' # Ts'' \<and> P \<turnstile> (T'' # Ts'') [\<le>] (U # Us)
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
es = e' # es'
Ts = U # Us
P,E,h \<turnstile> e' # es' [:] T'' # Ts'' \<and> P \<turnstile> (T'' # Ts'') [\<le>] (U # Us)
goal (1 subgoal):
1. \<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
\<exists>Ts''. P,E,h \<turnstile> es [:] Ts'' \<and> P \<turnstile> Ts'' [\<le>] Ts
goal:
No subgoals!
[PROOF STEP]
qed |
[STATEMENT]
theorem f0_alg_correct:
assumes "\<epsilon> \<in> {0<..<1}"
assumes "\<delta> \<in> {0<..<1}"
assumes "set as \<subseteq> {..<n}"
defines "\<Omega> \<equiv> fold (\<lambda>a state. state \<bind> f0_update a) as (f0_init \<delta> \<epsilon> n) \<bind> f0_result"
shows "\<P>(\<omega> in measure_pmf \<Omega>. \<bar>\<omega> - F 0 as\<bar> \<le> \<delta> * F 0 as) \<ge> 1 - of_rat \<epsilon>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. 1 - real_of_rat \<epsilon> \<le> measure_pmf.prob \<Omega> {\<omega> \<in> space (measure_pmf \<Omega>). \<bar>\<omega> - F 0 as\<bar> \<le> \<delta> * F 0 as}
[PROOF STEP]
using f0_alg_correct'[OF assms(1-3)]
[PROOF STATE]
proof (prove)
using this:
1 - real_of_rat \<epsilon> \<le> measure_pmf.prob (fold (\<lambda>a state. state \<bind> f0_update a) as (f0_init \<delta> \<epsilon> n) \<bind> f0_result) {\<omega> \<in> space (measure_pmf (fold (\<lambda>a state. state \<bind> f0_update a) as (f0_init \<delta> \<epsilon> n) \<bind> f0_result)). \<bar>\<omega> - F 0 as\<bar> \<le> \<delta> * F 0 as}
goal (1 subgoal):
1. 1 - real_of_rat \<epsilon> \<le> measure_pmf.prob \<Omega> {\<omega> \<in> space (measure_pmf \<Omega>). \<bar>\<omega> - F 0 as\<bar> \<le> \<delta> * F 0 as}
[PROOF STEP]
unfolding \<Omega>_def
[PROOF STATE]
proof (prove)
using this:
1 - real_of_rat \<epsilon> \<le> measure_pmf.prob (fold (\<lambda>a state. state \<bind> f0_update a) as (f0_init \<delta> \<epsilon> n) \<bind> f0_result) {\<omega> \<in> space (measure_pmf (fold (\<lambda>a state. state \<bind> f0_update a) as (f0_init \<delta> \<epsilon> n) \<bind> f0_result)). \<bar>\<omega> - F 0 as\<bar> \<le> \<delta> * F 0 as}
goal (1 subgoal):
1. 1 - real_of_rat \<epsilon> \<le> measure_pmf.prob (fold (\<lambda>a state. state \<bind> f0_update a) as (f0_init \<delta> \<epsilon> n) \<bind> f0_result) {\<omega> \<in> space (measure_pmf (fold (\<lambda>a state. state \<bind> f0_update a) as (f0_init \<delta> \<epsilon> n) \<bind> f0_result)). \<bar>\<omega> - F 0 as\<bar> \<le> \<delta> * F 0 as}
[PROOF STEP]
by blast |
[STATEMENT]
lemma list_of_vec_vec [simp]: "list_of_vec (vec n f) = map f [0..<n]"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. list_of_vec (vec n f) = map f [0..<n]
[PROOF STEP]
by (transfer, auto simp: mk_vec_def) |
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
⊢ Function.Injective fun A => ↑A.toSubring
[PROOFSTEP]
intro ⟨_, _⟩ ⟨_, _⟩ h
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
toSubring✝¹ : Subring K
mem_or_inv_mem'✝¹ : ∀ (x : K), x ∈ toSubring✝¹.carrier ∨ x⁻¹ ∈ toSubring✝¹.carrier
toSubring✝ : Subring K
mem_or_inv_mem'✝ : ∀ (x : K), x ∈ toSubring✝.carrier ∨ x⁻¹ ∈ toSubring✝.carrier
h :
(fun A => ↑A.toSubring) { toSubring := toSubring✝¹, mem_or_inv_mem' := mem_or_inv_mem'✝¹ } =
(fun A => ↑A.toSubring) { toSubring := toSubring✝, mem_or_inv_mem' := mem_or_inv_mem'✝ }
⊢ { toSubring := toSubring✝¹, mem_or_inv_mem' := mem_or_inv_mem'✝¹ } =
{ toSubring := toSubring✝, mem_or_inv_mem' := mem_or_inv_mem'✝ }
[PROOFSTEP]
replace h := SetLike.coe_injective' h
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
toSubring✝¹ : Subring K
mem_or_inv_mem'✝¹ : ∀ (x : K), x ∈ toSubring✝¹.carrier ∨ x⁻¹ ∈ toSubring✝¹.carrier
toSubring✝ : Subring K
mem_or_inv_mem'✝ : ∀ (x : K), x ∈ toSubring✝.carrier ∨ x⁻¹ ∈ toSubring✝.carrier
h :
{ toSubring := toSubring✝¹, mem_or_inv_mem' := mem_or_inv_mem'✝¹ }.toSubring =
{ toSubring := toSubring✝, mem_or_inv_mem' := mem_or_inv_mem'✝ }.toSubring
⊢ { toSubring := toSubring✝¹, mem_or_inv_mem' := mem_or_inv_mem'✝¹ } =
{ toSubring := toSubring✝, mem_or_inv_mem' := mem_or_inv_mem'✝ }
[PROOFSTEP]
congr
[GOAL]
K : Type u
inst✝ : Field K
A x y : ValuationSubring K
h : x.toSubring = y.toSubring
⊢ x = y
[PROOFSTEP]
cases x
[GOAL]
case mk
K : Type u
inst✝ : Field K
A y : ValuationSubring K
toSubring✝ : Subring K
mem_or_inv_mem'✝ : ∀ (x : K), x ∈ toSubring✝.carrier ∨ x⁻¹ ∈ toSubring✝.carrier
h : { toSubring := toSubring✝, mem_or_inv_mem' := mem_or_inv_mem'✝ }.toSubring = y.toSubring
⊢ { toSubring := toSubring✝, mem_or_inv_mem' := mem_or_inv_mem'✝ } = y
[PROOFSTEP]
cases y
[GOAL]
case mk.mk
K : Type u
inst✝ : Field K
A : ValuationSubring K
toSubring✝¹ : Subring K
mem_or_inv_mem'✝¹ : ∀ (x : K), x ∈ toSubring✝¹.carrier ∨ x⁻¹ ∈ toSubring✝¹.carrier
toSubring✝ : Subring K
mem_or_inv_mem'✝ : ∀ (x : K), x ∈ toSubring✝.carrier ∨ x⁻¹ ∈ toSubring✝.carrier
h :
{ toSubring := toSubring✝¹, mem_or_inv_mem' := mem_or_inv_mem'✝¹ }.toSubring =
{ toSubring := toSubring✝, mem_or_inv_mem' := mem_or_inv_mem'✝ }.toSubring
⊢ { toSubring := toSubring✝¹, mem_or_inv_mem' := mem_or_inv_mem'✝¹ } =
{ toSubring := toSubring✝, mem_or_inv_mem' := mem_or_inv_mem'✝ }
[PROOFSTEP]
congr
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
⊢ CommRing { x // x ∈ A.toSubring }
[PROOFSTEP]
infer_instance
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
⊢ IsDomain { x // x ∈ A.toSubring }
[PROOFSTEP]
infer_instance
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
⊢ ∃ c, a * c = b ∨ b * c = a
[PROOFSTEP]
by_cases (b : K) = 0
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
⊢ ∃ c, a * c = b ∨ b * c = a
[PROOFSTEP]
by_cases (b : K) = 0
[GOAL]
case pos
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h : ↑b = 0
⊢ ∃ c, a * c = b ∨ b * c = a
[PROOFSTEP]
use 0
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h : ↑b = 0
⊢ a * 0 = b ∨ b * 0 = a
[PROOFSTEP]
left
[GOAL]
case h.h
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h : ↑b = 0
⊢ a * 0 = b
[PROOFSTEP]
ext
[GOAL]
case h.h.a
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h : ↑b = 0
⊢ ↑(a * 0) = ↑b
[PROOFSTEP]
simp [h]
[GOAL]
case neg
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h : ¬↑b = 0
⊢ ∃ c, a * c = b ∨ b * c = a
[PROOFSTEP]
by_cases (a : K) = 0
[GOAL]
case neg
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h : ¬↑b = 0
⊢ ∃ c, a * c = b ∨ b * c = a
[PROOFSTEP]
by_cases (a : K) = 0
[GOAL]
case pos
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ↑a = 0
⊢ ∃ c, a * c = b ∨ b * c = a
[PROOFSTEP]
use 0
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ↑a = 0
⊢ a * 0 = b ∨ b * 0 = a
[PROOFSTEP]
right
[GOAL]
case h.h
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ↑a = 0
⊢ b * 0 = a
[PROOFSTEP]
ext
[GOAL]
case h.h.a
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ↑a = 0
⊢ ↑(b * 0) = ↑a
[PROOFSTEP]
simp [h]
[GOAL]
case neg
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ¬↑a = 0
⊢ ∃ c, a * c = b ∨ b * c = a
[PROOFSTEP]
cases' A.mem_or_inv_mem (a / b) with hh hh
[GOAL]
case neg.inl
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ¬↑a = 0
hh : ↑a / ↑b ∈ A
⊢ ∃ c, a * c = b ∨ b * c = a
[PROOFSTEP]
use⟨a / b, hh⟩
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ¬↑a = 0
hh : ↑a / ↑b ∈ A
⊢ a * { val := ↑a / ↑b, property := hh } = b ∨ b * { val := ↑a / ↑b, property := hh } = a
[PROOFSTEP]
right
[GOAL]
case h.h
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ¬↑a = 0
hh : ↑a / ↑b ∈ A
⊢ b * { val := ↑a / ↑b, property := hh } = a
[PROOFSTEP]
ext
[GOAL]
case h.h.a
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ¬↑a = 0
hh : ↑a / ↑b ∈ A
⊢ ↑(b * { val := ↑a / ↑b, property := hh }) = ↑a
[PROOFSTEP]
field_simp
[GOAL]
case h.h.a
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ¬↑a = 0
hh : ↑a / ↑b ∈ A
⊢ ↑b * ↑a = ↑a * ↑b
[PROOFSTEP]
ring
[GOAL]
case neg.inr
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ¬↑a = 0
hh : (↑a / ↑b)⁻¹ ∈ A
⊢ ∃ c, a * c = b ∨ b * c = a
[PROOFSTEP]
rw [show (a / b : K)⁻¹ = b / a by field_simp] at hh
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ¬↑a = 0
hh : (↑a / ↑b)⁻¹ ∈ A
⊢ (↑a / ↑b)⁻¹ = ↑b / ↑a
[PROOFSTEP]
field_simp
[GOAL]
case neg.inr
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ¬↑a = 0
hh : ↑b / ↑a ∈ A
⊢ ∃ c, a * c = b ∨ b * c = a
[PROOFSTEP]
use⟨b / a, hh⟩
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ¬↑a = 0
hh : ↑b / ↑a ∈ A
⊢ a * { val := ↑b / ↑a, property := hh } = b ∨ b * { val := ↑b / ↑a, property := hh } = a
[PROOFSTEP]
left
[GOAL]
case h.h
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ¬↑a = 0
hh : ↑b / ↑a ∈ A
⊢ a * { val := ↑b / ↑a, property := hh } = b
[PROOFSTEP]
ext
[GOAL]
case h.h.a
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ¬↑a = 0
hh : ↑b / ↑a ∈ A
⊢ ↑(a * { val := ↑b / ↑a, property := hh }) = ↑b
[PROOFSTEP]
field_simp
[GOAL]
case h.h.a
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h✝ : ¬↑b = 0
h : ¬↑a = 0
hh : ↑b / ↑a ∈ A
⊢ ↑a * ↑b = ↑b * ↑a
[PROOFSTEP]
ring
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
⊢ Algebra { x // x ∈ A.toSubring } K
[PROOFSTEP]
infer_instance
-- Porting note: Somehow it cannot find this instance and I'm too lazy to debug. wrong prio?
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
z : K
⊢ ∃ x, z * ↑(algebraMap { x // x ∈ A } K) ↑x.snd = ↑(algebraMap { x // x ∈ A } K) x.fst
[PROOFSTEP]
by_cases z = 0
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
z : K
⊢ ∃ x, z * ↑(algebraMap { x // x ∈ A } K) ↑x.snd = ↑(algebraMap { x // x ∈ A } K) x.fst
[PROOFSTEP]
by_cases z = 0
[GOAL]
case pos
K : Type u
inst✝ : Field K
A : ValuationSubring K
z : K
h : z = 0
⊢ ∃ x, z * ↑(algebraMap { x // x ∈ A } K) ↑x.snd = ↑(algebraMap { x // x ∈ A } K) x.fst
[PROOFSTEP]
use(0, 1)
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
z : K
h : z = 0
⊢ z * ↑(algebraMap { x // x ∈ A } K) ↑(0, 1).snd = ↑(algebraMap { x // x ∈ A } K) (0, 1).fst
[PROOFSTEP]
simp [h]
[GOAL]
case neg
K : Type u
inst✝ : Field K
A : ValuationSubring K
z : K
h : ¬z = 0
⊢ ∃ x, z * ↑(algebraMap { x // x ∈ A } K) ↑x.snd = ↑(algebraMap { x // x ∈ A } K) x.fst
[PROOFSTEP]
cases' A.mem_or_inv_mem z with hh hh
[GOAL]
case neg.inl
K : Type u
inst✝ : Field K
A : ValuationSubring K
z : K
h : ¬z = 0
hh : z ∈ A
⊢ ∃ x, z * ↑(algebraMap { x // x ∈ A } K) ↑x.snd = ↑(algebraMap { x // x ∈ A } K) x.fst
[PROOFSTEP]
use(⟨z, hh⟩, 1)
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
z : K
h : ¬z = 0
hh : z ∈ A
⊢ z * ↑(algebraMap { x // x ∈ A } K) ↑({ val := z, property := hh }, 1).snd =
↑(algebraMap { x // x ∈ A } K) ({ val := z, property := hh }, 1).fst
[PROOFSTEP]
simp
[GOAL]
case neg.inr
K : Type u
inst✝ : Field K
A : ValuationSubring K
z : K
h : ¬z = 0
hh : z⁻¹ ∈ A
⊢ ∃ x, z * ↑(algebraMap { x // x ∈ A } K) ↑x.snd = ↑(algebraMap { x // x ∈ A } K) x.fst
[PROOFSTEP]
refine ⟨⟨1, ⟨⟨_, hh⟩, ?_⟩⟩, mul_inv_cancel h⟩
[GOAL]
case neg.inr
K : Type u
inst✝ : Field K
A : ValuationSubring K
z : K
h : ¬z = 0
hh : z⁻¹ ∈ A
⊢ { val := z⁻¹, property := hh } ∈ nonZeroDivisors { x // x ∈ A }
[PROOFSTEP]
exact mem_nonZeroDivisors_iff_ne_zero.2 fun c => h (inv_eq_zero.mp (congr_arg Subtype.val c))
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h : ↑(algebraMap { x // x ∈ A } K) a = ↑(algebraMap { x // x ∈ A } K) b
⊢ ↑1 * a = ↑1 * b
[PROOFSTEP]
ext
[GOAL]
case a
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ A }
h : ↑(algebraMap { x // x ∈ A } K) a = ↑(algebraMap { x // x ∈ A } K) b
⊢ ↑(↑1 * a) = ↑(↑1 * b)
[PROOFSTEP]
simpa using h
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
⊢ LinearOrderedCommGroupWithZero (ValueGroup A)
[PROOFSTEP]
unfold ValueGroup
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
⊢ LinearOrderedCommGroupWithZero (ValuationRing.ValueGroup { x // x ∈ A } K)
[PROOFSTEP]
infer_instance
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }ˣ
⊢ ↑(valuation A) ↑↑a = 1
[PROOFSTEP]
rw [← A.valuation.map_one, valuation_eq_iff]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }ˣ
⊢ ∃ a_1, ↑↑a_1 * 1 = ↑↑a
[PROOFSTEP]
use a
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }ˣ
⊢ ↑↑a * 1 = ↑↑a
[PROOFSTEP]
simp
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }
h : ↑(valuation A) ↑a = 1
⊢ IsUnit a
[PROOFSTEP]
have ha : (a : K) ≠ 0
[GOAL]
case ha
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }
h : ↑(valuation A) ↑a = 1
⊢ ↑a ≠ 0
[PROOFSTEP]
intro c
[GOAL]
case ha
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }
h : ↑(valuation A) ↑a = 1
c : ↑a = 0
⊢ False
[PROOFSTEP]
rw [c, A.valuation.map_zero] at h
[GOAL]
case ha
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }
h : 0 = 1
c : ↑a = 0
⊢ False
[PROOFSTEP]
exact zero_ne_one h
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }
h : ↑(valuation A) ↑a = 1
ha : ↑a ≠ 0
⊢ IsUnit a
[PROOFSTEP]
have ha' : (a : K)⁻¹ ∈ A := by rw [← valuation_le_one_iff, map_inv₀, h, inv_one]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }
h : ↑(valuation A) ↑a = 1
ha : ↑a ≠ 0
⊢ (↑a)⁻¹ ∈ A
[PROOFSTEP]
rw [← valuation_le_one_iff, map_inv₀, h, inv_one]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }
h : ↑(valuation A) ↑a = 1
ha : ↑a ≠ 0
ha' : (↑a)⁻¹ ∈ A
⊢ IsUnit a
[PROOFSTEP]
apply isUnit_of_mul_eq_one a ⟨a⁻¹, ha'⟩
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }
h : ↑(valuation A) ↑a = 1
ha : ↑a ≠ 0
ha' : (↑a)⁻¹ ∈ A
⊢ a * { val := (↑a)⁻¹, property := ha' } = 1
[PROOFSTEP]
ext
[GOAL]
case a
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }
h : ↑(valuation A) ↑a = 1
ha : ↑a ≠ 0
ha' : (↑a)⁻¹ ∈ A
⊢ ↑(a * { val := (↑a)⁻¹, property := ha' }) = ↑1
[PROOFSTEP]
field_simp
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }
⊢ a ∈ LocalRing.maximalIdeal { x // x ∈ A } ↔ ↑(valuation A) ↑a < 1
[PROOFSTEP]
rw [LocalRing.mem_maximalIdeal]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }
⊢ a ∈ nonunits { x // x ∈ A } ↔ ↑(valuation A) ↑a < 1
[PROOFSTEP]
dsimp [nonunits]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }
⊢ ¬IsUnit a ↔ ↑(valuation A) ↑a < 1
[PROOFSTEP]
rw [valuation_eq_one_iff]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }
⊢ ¬↑(valuation A) ↑a = 1 ↔ ↑(valuation A) ↑a < 1
[PROOFSTEP]
exact (A.valuation_le_one a).lt_iff_ne.symm
[GOAL]
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
⊢ ∀ (x y : ValueGroup R),
ZeroHom.toFun
{ toFun := Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)),
map_zero' :=
(_ :
Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)) 0 =
Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)) 0) }
(x * y) =
ZeroHom.toFun
{ toFun := Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)),
map_zero' :=
(_ :
Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)) 0 =
Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)) 0) }
x *
ZeroHom.toFun
{ toFun := Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)),
map_zero' :=
(_ :
Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)) 0 =
Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)) 0) }
y
[PROOFSTEP]
rintro ⟨⟩ ⟨⟩
[GOAL]
case mk.mk
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x✝ : ValueGroup R
a✝¹ : K
y✝ : ValueGroup R
a✝ : K
⊢ ZeroHom.toFun
{ toFun := Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)),
map_zero' :=
(_ :
Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)) 0 =
Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)) 0) }
(Quot.mk Setoid.r a✝¹ * Quot.mk Setoid.r a✝) =
ZeroHom.toFun
{ toFun := Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)),
map_zero' :=
(_ :
Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)) 0 =
Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)) 0) }
(Quot.mk Setoid.r a✝¹) *
ZeroHom.toFun
{ toFun := Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)),
map_zero' :=
(_ :
Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)) 0 =
Quotient.map' id (_ : ∀ (x y : K), Setoid.r x y → Setoid.r (id x) (id y)) 0) }
(Quot.mk Setoid.r a✝)
[PROOFSTEP]
rfl
[GOAL]
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
⊢ Monotone ↑(mapOfLE R S h)
[PROOFSTEP]
rintro ⟨⟩ ⟨⟩ ⟨a, ha⟩
[GOAL]
case mk.mk.intro
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
a✝² : ValueGroup R
a✝¹ : K
b✝ : ValueGroup R
a✝ : K
a : { x // x ∈ R }
ha : a • a✝ = a✝¹
⊢ ↑(mapOfLE R S h) (Quot.mk Setoid.r a✝¹) ≤ ↑(mapOfLE R S h) (Quot.mk Setoid.r a✝)
[PROOFSTEP]
exact ⟨R.inclusion S h a, ha⟩
[GOAL]
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
⊢ ↑(mapOfLE R S h) ∘ ↑(valuation R) = ↑(valuation S)
[PROOFSTEP]
ext
[GOAL]
case h
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x✝ : K
⊢ (↑(mapOfLE R S h) ∘ ↑(valuation R)) x✝ = ↑(valuation S) x✝
[PROOFSTEP]
rfl
[GOAL]
K : Type u
inst✝¹ : Field K
A✝ A : ValuationSubring K
P : Ideal { x // x ∈ A }
inst✝ : Ideal.IsPrime P
⊢ IsLocalization.AtPrime { x // x ∈ ofPrime A P } P
[PROOFSTEP]
apply Localization.subalgebra.isLocalization_ofField K P.primeCompl P.primeCompl_le_nonZeroDivisors
[GOAL]
K : Type u
inst✝¹ : Field K
A✝ A : ValuationSubring K
P : Ideal { x // x ∈ A }
inst✝ : Ideal.IsPrime P
x : { x // x ∈ A }
⊢ ↑(valuation (ofPrime A P)) ↑x = 1 ↔ x ∈ Ideal.primeCompl P
[PROOFSTEP]
rw [← IsLocalization.AtPrime.isUnit_to_map_iff (A.ofPrime P) P x, valuation_eq_one_iff]
[GOAL]
K : Type u
inst✝¹ : Field K
A✝ A : ValuationSubring K
P : Ideal { x // x ∈ A }
inst✝ : Ideal.IsPrime P
x : { x // x ∈ A }
⊢ ↑(valuation (ofPrime A P)) ↑x = 1 ↔
↑(valuation (ofPrime A P)) ↑(↑(algebraMap { x // x ∈ A } { x // x ∈ ofPrime A P }) x) = 1
[PROOFSTEP]
rfl
[GOAL]
K : Type u
inst✝¹ : Field K
A✝ A : ValuationSubring K
P : Ideal { x // x ∈ A }
inst✝ : Ideal.IsPrime P
⊢ idealOfLE A (ofPrime A P) (_ : A ≤ ofPrime A P) = P
[PROOFSTEP]
refine Ideal.ext (fun x => ?_)
[GOAL]
K : Type u
inst✝¹ : Field K
A✝ A : ValuationSubring K
P : Ideal { x // x ∈ A }
inst✝ : Ideal.IsPrime P
x : { x // x ∈ A }
⊢ x ∈ idealOfLE A (ofPrime A P) (_ : A ≤ ofPrime A P) ↔ x ∈ P
[PROOFSTEP]
apply IsLocalization.AtPrime.to_map_mem_maximal_iff
[GOAL]
case h
K : Type u
inst✝¹ : Field K
A✝ A : ValuationSubring K
P : Ideal { x // x ∈ A }
inst✝ : Ideal.IsPrime P
x : { x // x ∈ A }
⊢ optParam (LocalRing { x // x ∈ ofPrime A P }) (_ : LocalRing { x // x ∈ ofPrime A P })
[PROOFSTEP]
exact localRing (ofPrime A P)
[GOAL]
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
⊢ ofPrime R (idealOfLE R S h) = S
[PROOFSTEP]
ext x
[GOAL]
case h
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
⊢ x ∈ ofPrime R (idealOfLE R S h) ↔ x ∈ S
[PROOFSTEP]
constructor
[GOAL]
case h.mp
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
⊢ x ∈ ofPrime R (idealOfLE R S h) → x ∈ S
[PROOFSTEP]
rintro ⟨a, r, hr, rfl⟩
[GOAL]
case h.mp.intro.intro.intro
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
a r : { x // x ∈ R }
hr : r ∈ Ideal.primeCompl (idealOfLE R S h)
⊢ ↑(algebraMap { x // x ∈ R } K) a * (↑(algebraMap { x // x ∈ R } K) r)⁻¹ ∈ S
[PROOFSTEP]
apply mul_mem
[GOAL]
case h.mp.intro.intro.intro.a
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
a r : { x // x ∈ R }
hr : r ∈ Ideal.primeCompl (idealOfLE R S h)
⊢ ↑(algebraMap { x // x ∈ R } K) a ∈ S
[PROOFSTEP]
exact h a.2
[GOAL]
case h.mp.intro.intro.intro.a
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
a r : { x // x ∈ R }
hr : r ∈ Ideal.primeCompl (idealOfLE R S h)
⊢ (↑(algebraMap { x // x ∈ R } K) r)⁻¹ ∈ S
[PROOFSTEP]
rw [← valuation_le_one_iff, map_inv₀, ← inv_one, inv_le_inv₀]
[GOAL]
case h.mp.intro.intro.intro.a
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
a r : { x // x ∈ R }
hr : r ∈ Ideal.primeCompl (idealOfLE R S h)
⊢ 1 ≤ ↑(valuation S) (↑(algebraMap { x // x ∈ R } K) r)
[PROOFSTEP]
exact not_lt.1 ((not_iff_not.2 <| valuation_lt_one_iff S _).1 hr)
[GOAL]
case h.mp.intro.intro.intro.a.ha
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
a r : { x // x ∈ R }
hr : r ∈ Ideal.primeCompl (idealOfLE R S h)
⊢ ↑(valuation S) (↑(algebraMap { x // x ∈ R } K) r) ≠ 0
[PROOFSTEP]
intro hh
[GOAL]
case h.mp.intro.intro.intro.a.ha
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
a r : { x // x ∈ R }
hr : r ∈ Ideal.primeCompl (idealOfLE R S h)
hh : ↑(valuation S) (↑(algebraMap { x // x ∈ R } K) r) = 0
⊢ False
[PROOFSTEP]
erw [Valuation.zero_iff, Subring.coe_eq_zero_iff] at hh
[GOAL]
case h.mp.intro.intro.intro.a.ha
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
a r : { x // x ∈ R }
hr : r ∈ Ideal.primeCompl (idealOfLE R S h)
hh : r = 0
⊢ False
[PROOFSTEP]
apply hr
[GOAL]
case h.mp.intro.intro.intro.a.ha
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
a r : { x // x ∈ R }
hr : r ∈ Ideal.primeCompl (idealOfLE R S h)
hh : r = 0
⊢ r ∈ ↑(idealOfLE R S h)
[PROOFSTEP]
rw [hh]
[GOAL]
case h.mp.intro.intro.intro.a.ha
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
a r : { x // x ∈ R }
hr : r ∈ Ideal.primeCompl (idealOfLE R S h)
hh : r = 0
⊢ 0 ∈ ↑(idealOfLE R S h)
[PROOFSTEP]
apply Ideal.zero_mem (R.idealOfLE S h)
[GOAL]
case h.mp.intro.intro.intro.a.hb
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
a r : { x // x ∈ R }
hr : r ∈ Ideal.primeCompl (idealOfLE R S h)
⊢ 1 ≠ 0
[PROOFSTEP]
exact one_ne_zero
[GOAL]
case h.mpr
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
⊢ x ∈ S → x ∈ ofPrime R (idealOfLE R S h)
[PROOFSTEP]
intro hx
[GOAL]
case h.mpr
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
hx : x ∈ S
⊢ x ∈ ofPrime R (idealOfLE R S h)
[PROOFSTEP]
by_cases hr : x ∈ R
[GOAL]
case pos
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
hx : x ∈ S
hr : x ∈ R
⊢ x ∈ ofPrime R (idealOfLE R S h)
[PROOFSTEP]
exact R.le_ofPrime _ hr
[GOAL]
case neg
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
hx : x ∈ S
hr : ¬x ∈ R
⊢ x ∈ ofPrime R (idealOfLE R S h)
[PROOFSTEP]
have : x ≠ 0 := fun h => hr (by rw [h]; exact R.zero_mem)
[GOAL]
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h✝ : R ≤ S
x : K
hx : x ∈ S
hr : ¬x ∈ R
h : x = 0
⊢ x ∈ R
[PROOFSTEP]
rw [h]
[GOAL]
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h✝ : R ≤ S
x : K
hx : x ∈ S
hr : ¬x ∈ R
h : x = 0
⊢ 0 ∈ R
[PROOFSTEP]
exact R.zero_mem
[GOAL]
case neg
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
hx : x ∈ S
hr : ¬x ∈ R
this : x ≠ 0
⊢ x ∈ ofPrime R (idealOfLE R S h)
[PROOFSTEP]
replace hr := (R.mem_or_inv_mem x).resolve_left hr
[GOAL]
case neg
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
hx : x ∈ S
this : x ≠ 0
hr : x⁻¹ ∈ R
⊢ x ∈ ofPrime R (idealOfLE R S h)
[PROOFSTEP]
use 1, ⟨x⁻¹, hr⟩
[GOAL]
case h
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
hx : x ∈ S
this : x ≠ 0
hr : x⁻¹ ∈ R
⊢ ∃ x_1, x = ↑(algebraMap { x // x ∈ R } K) 1 * (↑(algebraMap { x // x ∈ R } K) { val := x⁻¹, property := hr })⁻¹
[PROOFSTEP]
constructor
[GOAL]
case h.h
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
hx : x ∈ S
this : x ≠ 0
hr : x⁻¹ ∈ R
⊢ x = ↑(algebraMap { x // x ∈ R } K) 1 * (↑(algebraMap { x // x ∈ R } K) { val := x⁻¹, property := hr })⁻¹
[PROOFSTEP]
field_simp
[GOAL]
case h.w
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
hx : x ∈ S
this : x ≠ 0
hr : x⁻¹ ∈ R
⊢ { val := x⁻¹, property := hr } ∈ Ideal.primeCompl (idealOfLE R S h)
[PROOFSTEP]
change (⟨x⁻¹, h hr⟩ : S) ∉ nonunits S
[GOAL]
case h.w
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
hx : x ∈ S
this : x ≠ 0
hr : x⁻¹ ∈ R
⊢ ¬{ val := x⁻¹, property := (_ : x⁻¹ ∈ S) } ∈ nonunits { x // x ∈ S }
[PROOFSTEP]
rw [mem_nonunits_iff, Classical.not_not]
[GOAL]
case h.w
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
hx : x ∈ S
this : x ≠ 0
hr : x⁻¹ ∈ R
⊢ IsUnit { val := x⁻¹, property := (_ : x⁻¹ ∈ S) }
[PROOFSTEP]
apply isUnit_of_mul_eq_one _ (⟨x, hx⟩ : S)
[GOAL]
case h.w
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
hx : x ∈ S
this : x ≠ 0
hr : x⁻¹ ∈ R
⊢ { val := x⁻¹, property := (_ : x⁻¹ ∈ S) } * { val := x, property := hx } = 1
[PROOFSTEP]
ext
[GOAL]
case h.w.a
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
h : R ≤ S
x : K
hx : x ∈ S
this : x ≠ 0
hr : x⁻¹ ∈ R
⊢ ↑({ val := x⁻¹, property := (_ : x⁻¹ ∈ S) } * { val := x, property := hx }) = ↑1
[PROOFSTEP]
field_simp
[GOAL]
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
hR : A ≤ R
hS : A ≤ S
h : R ≤ S
x : { x // x ∈ A }
hx : x ∈ idealOfLE A S hS
⊢ ↑(valuation R) ↑(↑(inclusion A R hR) x) < 1
[PROOFSTEP]
by_contra c
[GOAL]
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
hR : A ≤ R
hS : A ≤ S
h : R ≤ S
x : { x // x ∈ A }
hx : x ∈ idealOfLE A S hS
c : ¬↑(valuation R) ↑(↑(inclusion A R hR) x) < 1
⊢ False
[PROOFSTEP]
push_neg at c
[GOAL]
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
hR : A ≤ R
hS : A ≤ S
h : R ≤ S
x : { x // x ∈ A }
hx : x ∈ idealOfLE A S hS
c : 1 ≤ ↑(valuation R) ↑(↑(inclusion A R hR) x)
⊢ False
[PROOFSTEP]
replace c := monotone_mapOfLE R S h c
[GOAL]
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
hR : A ≤ R
hS : A ≤ S
h : R ≤ S
x : { x // x ∈ A }
hx : x ∈ idealOfLE A S hS
c : ↑(mapOfLE R S h) 1 ≤ ↑(mapOfLE R S h) (↑(valuation R) ↑(↑(inclusion A R hR) x))
⊢ False
[PROOFSTEP]
rw [(mapOfLE _ _ _).map_one, mapOfLE_valuation_apply] at c
[GOAL]
K : Type u
inst✝ : Field K
A R S : ValuationSubring K
hR : A ≤ R
hS : A ≤ S
h : R ≤ S
x : { x // x ∈ A }
hx : x ∈ idealOfLE A S hS
c : 1 ≤ ↑(valuation S) ↑(↑(inclusion A R hR) x)
⊢ False
[PROOFSTEP]
apply not_le_of_lt ((valuation_lt_one_iff S _).1 hx) c
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
P : PrimeSpectrum { x // x ∈ A }
⊢ (fun S =>
{ asIdeal := idealOfLE A ↑S (_ : ↑S ∈ {S | A ≤ S}),
IsPrime := (_ : Ideal.IsPrime (idealOfLE A ↑S (_ : ↑S ∈ {S | A ≤ S}))) })
((fun P => { val := ofPrime A P.asIdeal, property := (_ : A ≤ ofPrime A P.asIdeal) }) P) =
P
[PROOFSTEP]
ext1
[GOAL]
case asIdeal
K : Type u
inst✝ : Field K
A : ValuationSubring K
P : PrimeSpectrum { x // x ∈ A }
⊢ ((fun S =>
{ asIdeal := idealOfLE A ↑S (_ : ↑S ∈ {S | A ≤ S}),
IsPrime := (_ : Ideal.IsPrime (idealOfLE A ↑S (_ : ↑S ∈ {S | A ≤ S}))) })
((fun P => { val := ofPrime A P.asIdeal, property := (_ : A ≤ ofPrime A P.asIdeal) }) P)).asIdeal =
P.asIdeal
[PROOFSTEP]
simp
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
S : ↑{S | A ≤ S}
⊢ (fun P => { val := ofPrime A P.asIdeal, property := (_ : A ≤ ofPrime A P.asIdeal) })
((fun S =>
{ asIdeal := idealOfLE A ↑S (_ : ↑S ∈ {S | A ≤ S}),
IsPrime := (_ : Ideal.IsPrime (idealOfLE A ↑S (_ : ↑S ∈ {S | A ≤ S}))) })
S) =
S
[PROOFSTEP]
ext1
[GOAL]
case a
K : Type u
inst✝ : Field K
A : ValuationSubring K
S : ↑{S | A ≤ S}
⊢ ↑((fun P => { val := ofPrime A P.asIdeal, property := (_ : A ≤ ofPrime A P.asIdeal) })
((fun S =>
{ asIdeal := idealOfLE A ↑S (_ : ↑S ∈ {S | A ≤ S}),
IsPrime := (_ : Ideal.IsPrime (idealOfLE A ↑S (_ : ↑S ∈ {S | A ≤ S}))) })
S)) =
↑S
[PROOFSTEP]
simp
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h :
↑{ toFun := src✝.toFun, invFun := src✝.invFun, left_inv := (_ : Function.LeftInverse src✝.invFun src✝.toFun),
right_inv := (_ : Function.RightInverse src✝.invFun src✝.toFun) }
a✝ ≤
↑{ toFun := src✝.toFun, invFun := src✝.invFun, left_inv := (_ : Function.LeftInverse src✝.invFun src✝.toFun),
right_inv := (_ : Function.RightInverse src✝.invFun src✝.toFun) }
b✝
⊢ a✝ ≤ b✝
[PROOFSTEP]
dsimp at h
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ a✝ ≤ b✝
[PROOFSTEP]
have := idealOfLE_le_of_le A _ _ ?_ ?_ h
[GOAL]
case refine_3
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
this : idealOfLE A ↑(↑(primeSpectrumEquiv A) b✝) ?refine_2 ≤ idealOfLE A ↑(↑(primeSpectrumEquiv A) a✝) ?refine_1
⊢ a✝ ≤ b✝
case refine_1
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) a✝)
case refine_2
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) b✝)
[PROOFSTEP]
iterate 2 erw [idealOfLE_ofPrime] at this
[GOAL]
case refine_3
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
this : idealOfLE A ↑(↑(primeSpectrumEquiv A) b✝) ?refine_2 ≤ idealOfLE A ↑(↑(primeSpectrumEquiv A) a✝) ?refine_1
⊢ a✝ ≤ b✝
case refine_1
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) a✝)
case refine_2
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) b✝)
[PROOFSTEP]
erw [idealOfLE_ofPrime] at this
[GOAL]
case refine_3
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
this : b✝.asIdeal ≤ idealOfLE A ↑(↑(primeSpectrumEquiv A) a✝) ?refine_1
⊢ a✝ ≤ b✝
case refine_2
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) b✝)
case refine_1
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) a✝)
case refine_1
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) a✝)
case refine_2
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) b✝)
[PROOFSTEP]
erw [idealOfLE_ofPrime] at this
[GOAL]
case refine_3
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
this : b✝.asIdeal ≤ a✝.asIdeal
⊢ a✝ ≤ b✝
case refine_1
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) a✝)
case refine_2
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) b✝)
case refine_1
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) a✝)
case refine_1
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) a✝)
case refine_2
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) b✝)
[PROOFSTEP]
exact this
[GOAL]
case refine_1
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) a✝)
case refine_2
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) b✝)
case refine_1
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) a✝)
case refine_1
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) a✝)
case refine_2
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) b✝)
[PROOFSTEP]
all_goals exact le_ofPrime A (PrimeSpectrum.asIdeal _)
[GOAL]
case refine_1
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) a✝)
[PROOFSTEP]
exact le_ofPrime A (PrimeSpectrum.asIdeal _)
[GOAL]
case refine_2
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : ↑(primeSpectrumEquiv A) a✝ ≤ ↑(primeSpectrumEquiv A) b✝
⊢ A ≤ ↑(↑(primeSpectrumEquiv A) b✝)
[PROOFSTEP]
exact le_ofPrime A (PrimeSpectrum.asIdeal _)
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : a✝ ≤ b✝
⊢ ↑{ toFun := src✝.toFun, invFun := src✝.invFun, left_inv := (_ : Function.LeftInverse src✝.invFun src✝.toFun),
right_inv := (_ : Function.RightInverse src✝.invFun src✝.toFun) }
a✝ ≤
↑{ toFun := src✝.toFun, invFun := src✝.invFun, left_inv := (_ : Function.LeftInverse src✝.invFun src✝.toFun),
right_inv := (_ : Function.RightInverse src✝.invFun src✝.toFun) }
b✝
[PROOFSTEP]
apply ofPrime_le_of_le
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
src✝ : PrimeSpectrum { x // x ∈ A } ≃ ↑{S | A ≤ S} := primeSpectrumEquiv A
a✝ b✝ : (PrimeSpectrum { x // x ∈ A })ᵒᵈ
h : a✝ ≤ b✝
⊢ b✝.asIdeal ≤ a✝.asIdeal
[PROOFSTEP]
exact h
[GOAL]
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
src✝ : Subring K := integer v
⊢ ∀ (x : K),
x ∈
{ toSubsemiring := src✝.toSubsemiring,
neg_mem' :=
(_ :
∀ {x : K},
x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier ∨
x⁻¹ ∈
{ toSubsemiring := src✝.toSubsemiring,
neg_mem' :=
(_ :
∀ {x : K},
x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier
[PROOFSTEP]
intro x
[GOAL]
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
src✝ : Subring K := integer v
x : K
⊢ x ∈
{ toSubsemiring := src✝.toSubsemiring,
neg_mem' :=
(_ :
∀ {x : K},
x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier ∨
x⁻¹ ∈
{ toSubsemiring := src✝.toSubsemiring,
neg_mem' :=
(_ :
∀ {x : K}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier
[PROOFSTEP]
cases' le_or_lt (v x) 1 with h h
[GOAL]
case inl
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
src✝ : Subring K := integer v
x : K
h : ↑v x ≤ 1
⊢ x ∈
{ toSubsemiring := src✝.toSubsemiring,
neg_mem' :=
(_ :
∀ {x : K},
x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier ∨
x⁻¹ ∈
{ toSubsemiring := src✝.toSubsemiring,
neg_mem' :=
(_ :
∀ {x : K}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier
[PROOFSTEP]
left
[GOAL]
case inl.h
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
src✝ : Subring K := integer v
x : K
h : ↑v x ≤ 1
⊢ x ∈
{ toSubsemiring := src✝.toSubsemiring,
neg_mem' :=
(_ : ∀ {x : K}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier
[PROOFSTEP]
exact h
[GOAL]
case inr
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
src✝ : Subring K := integer v
x : K
h : 1 < ↑v x
⊢ x ∈
{ toSubsemiring := src✝.toSubsemiring,
neg_mem' :=
(_ :
∀ {x : K},
x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier ∨
x⁻¹ ∈
{ toSubsemiring := src✝.toSubsemiring,
neg_mem' :=
(_ :
∀ {x : K}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier
[PROOFSTEP]
right
[GOAL]
case inr.h
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
src✝ : Subring K := integer v
x : K
h : 1 < ↑v x
⊢ x⁻¹ ∈
{ toSubsemiring := src✝.toSubsemiring,
neg_mem' :=
(_ : ∀ {x : K}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier
[PROOFSTEP]
change v x⁻¹ ≤ 1
[GOAL]
case inr.h
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
src✝ : Subring K := integer v
x : K
h : 1 < ↑v x
⊢ ↑v x⁻¹ ≤ 1
[PROOFSTEP]
rw [map_inv₀ v, ← inv_one, inv_le_inv₀]
[GOAL]
case inr.h
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
src✝ : Subring K := integer v
x : K
h : 1 < ↑v x
⊢ 1 ≤ ↑v x
[PROOFSTEP]
exact le_of_lt h
[GOAL]
case inr.h.ha
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
src✝ : Subring K := integer v
x : K
h : 1 < ↑v x
⊢ ↑v x ≠ 0
[PROOFSTEP]
intro c
[GOAL]
case inr.h.ha
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
src✝ : Subring K := integer v
x : K
h : 1 < ↑v x
c : ↑v x = 0
⊢ False
[PROOFSTEP]
simp [c] at h
[GOAL]
case inr.h.hb
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
src✝ : Subring K := integer v
x : K
h : 1 < ↑v x
⊢ 1 ≠ 0
[PROOFSTEP]
exact one_ne_zero
[GOAL]
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
⊢ IsEquiv v₁ v₂ ↔ valuationSubring v₁ = valuationSubring v₂
[PROOFSTEP]
constructor
[GOAL]
case mp
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
⊢ IsEquiv v₁ v₂ → valuationSubring v₁ = valuationSubring v₂
[PROOFSTEP]
intro h
[GOAL]
case mp
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
h : IsEquiv v₁ v₂
⊢ valuationSubring v₁ = valuationSubring v₂
[PROOFSTEP]
ext x
[GOAL]
case mp.h
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
h : IsEquiv v₁ v₂
x : K
⊢ x ∈ valuationSubring v₁ ↔ x ∈ valuationSubring v₂
[PROOFSTEP]
specialize h x 1
[GOAL]
case mp.h
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
x : K
h : ↑v₁ x ≤ ↑v₁ 1 ↔ ↑v₂ x ≤ ↑v₂ 1
⊢ x ∈ valuationSubring v₁ ↔ x ∈ valuationSubring v₂
[PROOFSTEP]
simpa using h
[GOAL]
case mpr
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
⊢ valuationSubring v₁ = valuationSubring v₂ → IsEquiv v₁ v₂
[PROOFSTEP]
intro h
[GOAL]
case mpr
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
h : valuationSubring v₁ = valuationSubring v₂
⊢ IsEquiv v₁ v₂
[PROOFSTEP]
apply isEquiv_of_val_le_one
[GOAL]
case mpr.h
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
h : valuationSubring v₁ = valuationSubring v₂
⊢ ∀ {x : K}, ↑v₁ x ≤ 1 ↔ ↑v₂ x ≤ 1
[PROOFSTEP]
intro x
[GOAL]
case mpr.h
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
h : valuationSubring v₁ = valuationSubring v₂
x : K
⊢ ↑v₁ x ≤ 1 ↔ ↑v₂ x ≤ 1
[PROOFSTEP]
have : x ∈ v₁.valuationSubring ↔ x ∈ v₂.valuationSubring := by rw [h]
[GOAL]
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
h : valuationSubring v₁ = valuationSubring v₂
x : K
⊢ x ∈ valuationSubring v₁ ↔ x ∈ valuationSubring v₂
[PROOFSTEP]
rw [h]
[GOAL]
case mpr.h
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
h : valuationSubring v₁ = valuationSubring v₂
x : K
this : x ∈ valuationSubring v₁ ↔ x ∈ valuationSubring v₂
⊢ ↑v₁ x ≤ 1 ↔ ↑v₂ x ≤ 1
[PROOFSTEP]
simpa using this
[GOAL]
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
⊢ IsEquiv v (ValuationSubring.valuation (valuationSubring v))
[PROOFSTEP]
rw [isEquiv_iff_val_le_one]
[GOAL]
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
⊢ ∀ {x : K}, ↑v x ≤ 1 ↔ ↑(ValuationSubring.valuation (valuationSubring v)) x ≤ 1
[PROOFSTEP]
intro x
[GOAL]
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
x : K
⊢ ↑v x ≤ 1 ↔ ↑(ValuationSubring.valuation (valuationSubring v)) x ≤ 1
[PROOFSTEP]
rw [ValuationSubring.valuation_le_one_iff]
[GOAL]
K : Type u
inst✝³ : Field K
Γ : Type u_1
Γ₁ : Type u_2
Γ₂ : Type u_3
inst✝² : LinearOrderedCommGroupWithZero Γ
inst✝¹ : LinearOrderedCommGroupWithZero Γ₁
inst✝ : LinearOrderedCommGroupWithZero Γ₂
v : Valuation K Γ
v₁ : Valuation K Γ₁
v₂ : Valuation K Γ₂
x : K
⊢ ↑v x ≤ 1 ↔ x ∈ valuationSubring v
[PROOFSTEP]
rfl
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
⊢ Valuation.valuationSubring (valuation A) = A
[PROOFSTEP]
ext
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
x✝ : K
⊢ x✝ ∈ Valuation.valuationSubring (valuation A) ↔ x✝ ∈ A
[PROOFSTEP]
rw [← A.valuation_le_one_iff]
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
x✝ : K
⊢ x✝ ∈ Valuation.valuationSubring (valuation A) ↔ ↑(valuation A) x✝ ≤ 1
[PROOFSTEP]
rfl
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
x : { x // x ∈ unitGroup A }
⊢ ↑({ val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) }) = ↑1
[PROOFSTEP]
simp
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
x : { x // x ∈ unitGroup A }
⊢ ↑({ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) }) = ↑1
[PROOFSTEP]
simp
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ unitGroup A }
⊢ (fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) })
((fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) }, inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ : { val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } = 1),
inv_val :=
(_ : { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) } = 1) })
a) =
a
[PROOFSTEP]
ext
[GOAL]
case a.a
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ unitGroup A }
⊢ ↑↑((fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) })
((fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) }, inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ : { val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } = 1),
inv_val :=
(_ : { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) } = 1) })
a)) =
↑↑a
[PROOFSTEP]
rfl
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }ˣ
⊢ (fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) }, inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ : { val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } = 1),
inv_val :=
(_ : { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) } = 1) })
((fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) }) a) =
a
[PROOFSTEP]
ext
[GOAL]
case a.a
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : { x // x ∈ A }ˣ
⊢ ↑↑((fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) }, inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ : { val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } = 1),
inv_val :=
(_ : { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) } = 1) })
((fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) }) a)) =
↑↑a
[PROOFSTEP]
rfl
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ unitGroup A }
⊢ Equiv.toFun
{
toFun := fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) }, inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ : { val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } = 1),
inv_val :=
(_ : { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) } = 1) },
invFun := fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) },
left_inv :=
(_ :
∀ (a : { x // x ∈ unitGroup A }),
(fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) })
((fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) },
inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ :
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } =
1),
inv_val :=
(_ :
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) } =
1) })
a) =
a),
right_inv :=
(_ :
∀ (a : { x // x ∈ A }ˣ),
(fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) },
inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ :
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } =
1),
inv_val :=
(_ :
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) } =
1) })
((fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) }) a) =
a) }
(a * b) =
Equiv.toFun
{
toFun := fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) }, inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ : { val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } = 1),
inv_val :=
(_ : { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) } = 1) },
invFun := fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) },
left_inv :=
(_ :
∀ (a : { x // x ∈ unitGroup A }),
(fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) })
((fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) },
inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ :
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } *
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } =
1),
inv_val :=
(_ :
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } *
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } =
1) })
a) =
a),
right_inv :=
(_ :
∀ (a : { x // x ∈ A }ˣ),
(fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) },
inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ :
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } =
1),
inv_val :=
(_ :
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) } =
1) })
((fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) }) a) =
a) }
a *
Equiv.toFun
{
toFun := fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) }, inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ : { val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } = 1),
inv_val :=
(_ : { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) } = 1) },
invFun := fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) },
left_inv :=
(_ :
∀ (a : { x // x ∈ unitGroup A }),
(fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) })
((fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) },
inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ :
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } *
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } =
1),
inv_val :=
(_ :
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } *
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } =
1) })
a) =
a),
right_inv :=
(_ :
∀ (a : { x // x ∈ A }ˣ),
(fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) },
inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ :
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } =
1),
inv_val :=
(_ :
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) } =
1) })
((fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) }) a) =
a) }
b
[PROOFSTEP]
ext
[GOAL]
case a.a
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : { x // x ∈ unitGroup A }
⊢ ↑↑(Equiv.toFun
{
toFun := fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) }, inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ : { val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } = 1),
inv_val :=
(_ : { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) } = 1) },
invFun := fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) },
left_inv :=
(_ :
∀ (a : { x // x ∈ unitGroup A }),
(fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) })
((fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) },
inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ :
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } *
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } =
1),
inv_val :=
(_ :
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } *
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } =
1) })
a) =
a),
right_inv :=
(_ :
∀ (a : { x // x ∈ A }ˣ),
(fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) },
inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ :
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } *
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } =
1),
inv_val :=
(_ :
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } *
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } =
1) })
((fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) }) a) =
a) }
(a * b)) =
↑↑(Equiv.toFun
{
toFun := fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) },
inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ : { val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } = 1),
inv_val :=
(_ :
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) } = 1) },
invFun := fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) },
left_inv :=
(_ :
∀ (a : { x // x ∈ unitGroup A }),
(fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) })
((fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) },
inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ :
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } *
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } =
1),
inv_val :=
(_ :
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } *
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } =
1) })
a) =
a),
right_inv :=
(_ :
∀ (a : { x // x ∈ A }ˣ),
(fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) },
inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ :
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } *
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } =
1),
inv_val :=
(_ :
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } *
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } =
1) })
((fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) })
a) =
a) }
a *
Equiv.toFun
{
toFun := fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) },
inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ : { val := ↑↑x, property := (_ : ↑↑x ∈ A) } * { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } = 1),
inv_val :=
(_ :
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } * { val := ↑↑x, property := (_ : ↑↑x ∈ A) } = 1) },
invFun := fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) },
left_inv :=
(_ :
∀ (a : { x // x ∈ unitGroup A }),
(fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) })
((fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) },
inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ :
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } *
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } =
1),
inv_val :=
(_ :
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } *
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } =
1) })
a) =
a),
right_inv :=
(_ :
∀ (a : { x // x ∈ A }ˣ),
(fun x =>
{ val := { val := ↑↑x, property := (_ : ↑↑x ∈ A) },
inv := { val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) },
val_inv :=
(_ :
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } *
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } =
1),
inv_val :=
(_ :
{ val := ↑↑x⁻¹, property := (_ : ↑↑x⁻¹ ∈ A) } *
{ val := ↑↑x, property := (_ : ↑↑x ∈ A) } =
1) })
((fun x => { val := ↑(Units.map ↑(subtype A)) x, property := (_ : ↑(valuation A) ↑↑x = 1) })
a) =
a) }
b)
[PROOFSTEP]
rfl
[GOAL]
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
⊢ unitGroup A ≤ unitGroup B ↔ A ≤ B
[PROOFSTEP]
constructor
[GOAL]
case mp
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
⊢ unitGroup A ≤ unitGroup B → A ≤ B
[PROOFSTEP]
intro h x hx
[GOAL]
case mp
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : unitGroup A ≤ unitGroup B
x : K
hx : x ∈ A
⊢ x ∈ B
[PROOFSTEP]
rw [← A.valuation_le_one_iff x, le_iff_lt_or_eq] at hx
[GOAL]
case mp
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : unitGroup A ≤ unitGroup B
x : K
hx : ↑(valuation A) x < 1 ∨ ↑(valuation A) x = 1
⊢ x ∈ B
[PROOFSTEP]
by_cases h_1 : x = 0
[GOAL]
case pos
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : unitGroup A ≤ unitGroup B
x : K
hx : ↑(valuation A) x < 1 ∨ ↑(valuation A) x = 1
h_1 : x = 0
⊢ x ∈ B
[PROOFSTEP]
simp only [h_1, zero_mem]
[GOAL]
case neg
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : unitGroup A ≤ unitGroup B
x : K
hx : ↑(valuation A) x < 1 ∨ ↑(valuation A) x = 1
h_1 : ¬x = 0
⊢ x ∈ B
[PROOFSTEP]
by_cases h_2 : 1 + x = 0
[GOAL]
case pos
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : unitGroup A ≤ unitGroup B
x : K
hx : ↑(valuation A) x < 1 ∨ ↑(valuation A) x = 1
h_1 : ¬x = 0
h_2 : 1 + x = 0
⊢ x ∈ B
[PROOFSTEP]
simp only [← add_eq_zero_iff_neg_eq.1 h_2, neg_mem _ _ (one_mem _)]
[GOAL]
case neg
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : unitGroup A ≤ unitGroup B
x : K
hx : ↑(valuation A) x < 1 ∨ ↑(valuation A) x = 1
h_1 : ¬x = 0
h_2 : ¬1 + x = 0
⊢ x ∈ B
[PROOFSTEP]
cases' hx with hx hx
[GOAL]
case neg.inl
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : unitGroup A ≤ unitGroup B
x : K
h_1 : ¬x = 0
h_2 : ¬1 + x = 0
hx : ↑(valuation A) x < 1
⊢ x ∈ B
[PROOFSTEP]
have := h (show Units.mk0 _ h_2 ∈ A.unitGroup from A.valuation.map_one_add_of_lt hx)
[GOAL]
case neg.inl
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : unitGroup A ≤ unitGroup B
x : K
h_1 : ¬x = 0
h_2 : ¬1 + x = 0
hx : ↑(valuation A) x < 1
this : Units.mk0 (1 + x) h_2 ∈ unitGroup B
⊢ x ∈ B
[PROOFSTEP]
simpa using
B.add_mem _ _ (show 1 + x ∈ B from SetLike.coe_mem (B.unitGroupMulEquiv ⟨_, this⟩ : B)) (B.neg_mem _ B.one_mem)
[GOAL]
case neg.inr
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : unitGroup A ≤ unitGroup B
x : K
h_1 : ¬x = 0
h_2 : ¬1 + x = 0
hx : ↑(valuation A) x = 1
⊢ x ∈ B
[PROOFSTEP]
have := h (show Units.mk0 x h_1 ∈ A.unitGroup from hx)
[GOAL]
case neg.inr
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : unitGroup A ≤ unitGroup B
x : K
h_1 : ¬x = 0
h_2 : ¬1 + x = 0
hx : ↑(valuation A) x = 1
this : Units.mk0 x h_1 ∈ unitGroup B
⊢ x ∈ B
[PROOFSTEP]
refine' SetLike.coe_mem (B.unitGroupMulEquiv ⟨_, this⟩ : B)
[GOAL]
case mpr
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
⊢ A ≤ B → unitGroup A ≤ unitGroup B
[PROOFSTEP]
rintro h x (hx : A.valuation x = 1)
[GOAL]
case mpr
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : A ≤ B
x : Kˣ
hx : ↑(valuation A) ↑x = 1
⊢ x ∈ unitGroup B
[PROOFSTEP]
apply_fun A.mapOfLE B h at hx
[GOAL]
case mpr
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : A ≤ B
x : Kˣ
hx : ↑(mapOfLE A B h) (↑(valuation A) ↑x) = ↑(mapOfLE A B h) 1
⊢ x ∈ unitGroup B
[PROOFSTEP]
simpa using hx
[GOAL]
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : unitGroup A = unitGroup B
⊢ A = B
[PROOFSTEP]
simpa only [le_antisymm_iff, unitGroup_le_unitGroup] using h
[GOAL]
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
⊢ nonunits B ≤ nonunits A ↔ A ≤ B
[PROOFSTEP]
constructor
[GOAL]
case mp
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
⊢ nonunits B ≤ nonunits A → A ≤ B
[PROOFSTEP]
intro h x hx
[GOAL]
case mp
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : nonunits B ≤ nonunits A
x : K
hx : x ∈ A
⊢ x ∈ B
[PROOFSTEP]
by_cases h_1 : x = 0
[GOAL]
case pos
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : nonunits B ≤ nonunits A
x : K
hx : x ∈ A
h_1 : x = 0
⊢ x ∈ B
[PROOFSTEP]
simp only [h_1, zero_mem]
[GOAL]
case neg
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : nonunits B ≤ nonunits A
x : K
hx : x ∈ A
h_1 : ¬x = 0
⊢ x ∈ B
[PROOFSTEP]
rw [← valuation_le_one_iff, ← not_lt, Valuation.one_lt_val_iff _ h_1] at hx ⊢
[GOAL]
case neg
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : nonunits B ≤ nonunits A
x : K
hx : ¬↑(valuation A) x⁻¹ < 1
h_1 : ¬x = 0
⊢ ¬↑(valuation B) x⁻¹ < 1
[PROOFSTEP]
by_contra h_2
[GOAL]
case neg
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : nonunits B ≤ nonunits A
x : K
hx : ¬↑(valuation A) x⁻¹ < 1
h_1 : ¬x = 0
h_2 : ↑(valuation B) x⁻¹ < 1
⊢ False
[PROOFSTEP]
exact hx (h h_2)
[GOAL]
case mpr
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
⊢ A ≤ B → nonunits B ≤ nonunits A
[PROOFSTEP]
intro h x hx
[GOAL]
case mpr
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : A ≤ B
x : K
hx : x ∈ nonunits B
⊢ x ∈ nonunits A
[PROOFSTEP]
by_contra h_1
[GOAL]
case mpr
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : A ≤ B
x : K
hx : x ∈ nonunits B
h_1 : ¬x ∈ nonunits A
⊢ False
[PROOFSTEP]
exact not_lt.2 (monotone_mapOfLE _ _ h (not_lt.1 h_1)) hx
[GOAL]
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : nonunits A = nonunits B
⊢ A = B
[PROOFSTEP]
simpa only [le_antisymm_iff, nonunits_le_nonunits] using h.symm
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
⊢ Subtype.val '' ↑(LocalRing.maximalIdeal { x // x ∈ A }) = ↑(nonunits A)
[PROOFSTEP]
ext a
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : K
⊢ a ∈ Subtype.val '' ↑(LocalRing.maximalIdeal { x // x ∈ A }) ↔ a ∈ ↑(nonunits A)
[PROOFSTEP]
simp only [Set.mem_image, SetLike.mem_coe, mem_nonunits_iff_exists_mem_maximalIdeal]
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : K
⊢ (∃ x, x ∈ LocalRing.maximalIdeal { x // x ∈ A } ∧ ↑x = a) ↔
∃ ha, { val := a, property := ha } ∈ LocalRing.maximalIdeal { x // x ∈ A }
[PROOFSTEP]
erw [Subtype.exists]
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : K
⊢ (∃ a_1 b,
{ val := a_1, property := b } ∈ LocalRing.maximalIdeal { x // x ∈ A } ∧ ↑{ val := a_1, property := b } = a) ↔
∃ ha, { val := a, property := ha } ∈ LocalRing.maximalIdeal { x // x ∈ A }
[PROOFSTEP]
simp_rw [exists_and_right, exists_eq_right]
-- Porting note: added
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : K
⊢ (∃ x, { val := a, property := (_ : a ∈ ↑A) } ∈ LocalRing.maximalIdeal { x // x ∈ A }) ↔
∃ ha, { val := a, property := ha } ∈ LocalRing.maximalIdeal { x // x ∈ A }
[PROOFSTEP]
simp
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
⊢ ∀ {a b : Kˣ},
a ∈ {x | ↑(valuation A) (↑x - 1) < 1} →
b ∈ {x | ↑(valuation A) (↑x - 1) < 1} → a * b ∈ {x | ↑(valuation A) (↑x - 1) < 1}
[PROOFSTEP]
intro a b ha hb
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : Kˣ
ha : a ∈ {x | ↑(valuation A) (↑x - 1) < 1}
hb : b ∈ {x | ↑(valuation A) (↑x - 1) < 1}
⊢ a * b ∈ {x | ↑(valuation A) (↑x - 1) < 1}
[PROOFSTEP]
rw [Set.mem_setOf] at ha hb
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : Kˣ
ha : ↑(valuation A) (↑a - 1) < 1
hb : ↑(valuation A) (↑b - 1) < 1
⊢ a * b ∈ {x | ↑(valuation A) (↑x - 1) < 1}
[PROOFSTEP]
refine'
lt_of_le_of_lt _
(max_lt hb ha)
-- Porting note: `sub_add_sub_cancel` needed some help
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : Kˣ
ha : ↑(valuation A) (↑a - 1) < 1
hb : ↑(valuation A) (↑b - 1) < 1
⊢ ↑(valuation A) (↑(a * b) - 1) ≤ max (↑(valuation A) (↑b - 1)) (↑(valuation A) (↑a - 1))
[PROOFSTEP]
rw [← one_mul (A.valuation (b - 1)), ← A.valuation.map_one_add_of_lt ha, add_sub_cancel'_right, ← Valuation.map_mul,
mul_sub_one, ← sub_add_sub_cancel (↑(a * b) : K) _ 1]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : Kˣ
ha : ↑(valuation A) (↑a - 1) < 1
hb : ↑(valuation A) (↑b - 1) < 1
⊢ ↑(valuation A) (↑(a * b) - ?m.1681005 + (?m.1681005 - 1)) ≤
max (↑(valuation A) (↑a * ↑b - ↑a)) (↑(valuation A) (↑a - 1))
K : Type u
inst✝ : Field K
A : ValuationSubring K
a b : Kˣ
ha : ↑(valuation A) (↑a - 1) < 1
hb : ↑(valuation A) (↑b - 1) < 1
⊢ K
[PROOFSTEP]
exact A.valuation.map_add _ _
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
⊢ 1 ∈
{ carrier := {x | ↑(valuation A) (↑x - 1) < 1},
mul_mem' :=
(_ :
∀ {a b : Kˣ},
a ∈ {x | ↑(valuation A) (↑x - 1) < 1} →
b ∈ {x | ↑(valuation A) (↑x - 1) < 1} → ↑(valuation A) (↑(a * b) - 1) < 1) }.carrier
[PROOFSTEP]
simp
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
⊢ ∀ {x : Kˣ},
x ∈
{
toSubsemigroup :=
{ carrier := {x | ↑(valuation A) (↑x - 1) < 1},
mul_mem' :=
(_ :
∀ {a b : Kˣ},
a ∈ {x | ↑(valuation A) (↑x - 1) < 1} →
b ∈ {x | ↑(valuation A) (↑x - 1) < 1} → ↑(valuation A) (↑(a * b) - 1) < 1) },
one_mem' := (_ : ↑(valuation A) (1 - 1) < 1) }.toSubsemigroup.carrier →
x⁻¹ ∈
{
toSubsemigroup :=
{ carrier := {x | ↑(valuation A) (↑x - 1) < 1},
mul_mem' :=
(_ :
∀ {a b : Kˣ},
a ∈ {x | ↑(valuation A) (↑x - 1) < 1} →
b ∈ {x | ↑(valuation A) (↑x - 1) < 1} → ↑(valuation A) (↑(a * b) - 1) < 1) },
one_mem' := (_ : ↑(valuation A) (1 - 1) < 1) }.toSubsemigroup.carrier
[PROOFSTEP]
dsimp
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
⊢ ∀ {x : Kˣ}, ↑(valuation A) (↑x - 1) < 1 → ↑(valuation A) (↑x⁻¹ - 1) < 1
[PROOFSTEP]
intro a ha
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : Kˣ
ha : ↑(valuation A) (↑a - 1) < 1
⊢ ↑(valuation A) (↑a⁻¹ - 1) < 1
[PROOFSTEP]
conv =>
lhs
rw [← mul_one (A.valuation _), ← A.valuation.map_one_add_of_lt ha]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : Kˣ
ha : ↑(valuation A) (↑a - 1) < 1
| ↑(valuation A) (↑a⁻¹ - 1) < 1
[PROOFSTEP]
lhs
rw [← mul_one (A.valuation _), ← A.valuation.map_one_add_of_lt ha]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : Kˣ
ha : ↑(valuation A) (↑a - 1) < 1
| ↑(valuation A) (↑a⁻¹ - 1) < 1
[PROOFSTEP]
lhs
rw [← mul_one (A.valuation _), ← A.valuation.map_one_add_of_lt ha]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : Kˣ
ha : ↑(valuation A) (↑a - 1) < 1
| ↑(valuation A) (↑a⁻¹ - 1) < 1
[PROOFSTEP]
lhs
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : Kˣ
ha : ↑(valuation A) (↑a - 1) < 1
| ↑(valuation A) (↑a⁻¹ - 1)
[PROOFSTEP]
rw [← mul_one (A.valuation _), ← A.valuation.map_one_add_of_lt ha]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : Kˣ
ha : ↑(valuation A) (↑a - 1) < 1
⊢ ↑(valuation A) (↑a⁻¹ - 1) * ↑(valuation A) (1 + (↑a - 1)) < 1
[PROOFSTEP]
rwa [add_sub_cancel'_right, ← Valuation.map_mul, sub_mul, Units.inv_mul, ← neg_sub, one_mul, Valuation.map_neg]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
a : Kˣ
h : a ∈ principalUnitGroup A
⊢ a ∈ unitGroup A
[PROOFSTEP]
simpa only [add_sub_cancel'_right] using A.valuation.map_one_add_of_lt h
[GOAL]
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
⊢ principalUnitGroup B ≤ principalUnitGroup A ↔ A ≤ B
[PROOFSTEP]
constructor
[GOAL]
case mp
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
⊢ principalUnitGroup B ≤ principalUnitGroup A → A ≤ B
[PROOFSTEP]
intro h x hx
[GOAL]
case mp
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : principalUnitGroup B ≤ principalUnitGroup A
x : K
hx : x ∈ A
⊢ x ∈ B
[PROOFSTEP]
by_cases h_1 : x = 0
[GOAL]
case pos
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : principalUnitGroup B ≤ principalUnitGroup A
x : K
hx : x ∈ A
h_1 : x = 0
⊢ x ∈ B
[PROOFSTEP]
simp only [h_1, zero_mem]
[GOAL]
case neg
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : principalUnitGroup B ≤ principalUnitGroup A
x : K
hx : x ∈ A
h_1 : ¬x = 0
⊢ x ∈ B
[PROOFSTEP]
by_cases h_2 : x⁻¹ + 1 = 0
[GOAL]
case pos
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : principalUnitGroup B ≤ principalUnitGroup A
x : K
hx : x ∈ A
h_1 : ¬x = 0
h_2 : x⁻¹ + 1 = 0
⊢ x ∈ B
[PROOFSTEP]
rw [add_eq_zero_iff_eq_neg, inv_eq_iff_eq_inv, inv_neg, inv_one] at h_2
[GOAL]
case pos
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : principalUnitGroup B ≤ principalUnitGroup A
x : K
hx : x ∈ A
h_1 : ¬x = 0
h_2 : x = -1
⊢ x ∈ B
[PROOFSTEP]
simpa only [h_2] using B.neg_mem _ B.one_mem
[GOAL]
case neg
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : principalUnitGroup B ≤ principalUnitGroup A
x : K
hx : x ∈ A
h_1 : ¬x = 0
h_2 : ¬x⁻¹ + 1 = 0
⊢ x ∈ B
[PROOFSTEP]
rw [← valuation_le_one_iff, ← not_lt, Valuation.one_lt_val_iff _ h_1, ← add_sub_cancel x⁻¹, ← Units.val_mk0 h_2, ←
mem_principalUnitGroup_iff] at hx ⊢
[GOAL]
case neg
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : principalUnitGroup B ≤ principalUnitGroup A
x : K
hx✝¹ : ¬↑(valuation A) x⁻¹ < 1
hx✝ : ¬↑(valuation A) (x⁻¹ + 1 - 1) < 1
h_1 : ¬x = 0
h_2 : ¬x⁻¹ + 1 = 0
hx : ¬Units.mk0 (x⁻¹ + 1) h_2 ∈ principalUnitGroup A
⊢ ¬Units.mk0 (x⁻¹ + 1) h_2 ∈ principalUnitGroup B
[PROOFSTEP]
simpa only [hx] using @h (Units.mk0 (x⁻¹ + 1) h_2)
[GOAL]
case mpr
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
⊢ A ≤ B → principalUnitGroup B ≤ principalUnitGroup A
[PROOFSTEP]
intro h x hx
[GOAL]
case mpr
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : A ≤ B
x : Kˣ
hx : x ∈ principalUnitGroup B
⊢ x ∈ principalUnitGroup A
[PROOFSTEP]
by_contra h_1
[GOAL]
case mpr
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : A ≤ B
x : Kˣ
hx : x ∈ principalUnitGroup B
h_1 : ¬x ∈ principalUnitGroup A
⊢ False
[PROOFSTEP]
exact not_lt.2 (monotone_mapOfLE _ _ h (not_lt.1 h_1)) hx
[GOAL]
K : Type u
inst✝ : Field K
A✝ A B : ValuationSubring K
h : principalUnitGroup A = principalUnitGroup B
⊢ A = B
[PROOFSTEP]
simpa [le_antisymm_iff, principalUnitGroup_le_principalUnitGroup] using h.symm
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
x : { x // x ∈ unitGroup A }
⊢ ↑x ∈ principalUnitGroup A ↔ ↑(unitGroupMulEquiv A) x ∈ MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))
[PROOFSTEP]
rw [MonoidHom.mem_ker, Units.ext_iff]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
x : { x // x ∈ unitGroup A }
⊢ ↑x ∈ principalUnitGroup A ↔ ↑(↑(Units.map ↑(LocalRing.residue { x // x ∈ A })) (↑(unitGroupMulEquiv A) x)) = ↑1
[PROOFSTEP]
let π := Ideal.Quotient.mk (LocalRing.maximalIdeal A)
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
x : { x // x ∈ unitGroup A }
π : { x // x ∈ A } →+* { x // x ∈ A } ⧸ LocalRing.maximalIdeal { x // x ∈ A } :=
Ideal.Quotient.mk (LocalRing.maximalIdeal { x // x ∈ A })
⊢ ↑x ∈ principalUnitGroup A ↔ ↑(↑(Units.map ↑(LocalRing.residue { x // x ∈ A })) (↑(unitGroupMulEquiv A) x)) = ↑1
[PROOFSTEP]
convert_to _ ↔ π _ = 1
[GOAL]
case convert_3
K : Type u
inst✝ : Field K
A : ValuationSubring K
x : { x // x ∈ unitGroup A }
π : { x // x ∈ A } →+* { x // x ∈ A } ⧸ LocalRing.maximalIdeal { x // x ∈ A } :=
Ideal.Quotient.mk (LocalRing.maximalIdeal { x // x ∈ A })
⊢ ↑x ∈ principalUnitGroup A ↔ ↑π ↑(↑(unitGroupMulEquiv A) x) = 1
[PROOFSTEP]
rw [← π.map_one, ← sub_eq_zero, ← π.map_sub, Ideal.Quotient.eq_zero_iff_mem, valuation_lt_one_iff]
[GOAL]
case convert_3
K : Type u
inst✝ : Field K
A : ValuationSubring K
x : { x // x ∈ unitGroup A }
π : { x // x ∈ A } →+* { x // x ∈ A } ⧸ LocalRing.maximalIdeal { x // x ∈ A } :=
Ideal.Quotient.mk (LocalRing.maximalIdeal { x // x ∈ A })
⊢ ↑x ∈ principalUnitGroup A ↔ ↑(valuation A) ↑(↑(↑(unitGroupMulEquiv A) x) - 1) < 1
[PROOFSTEP]
simp [mem_principalUnitGroup_iff]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
x : { x // x ∈ MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A })) }
⊢ ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A
[PROOFSTEP]
rw [A.coe_mem_principalUnitGroup_iff]
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
x : { x // x ∈ MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A })) }
⊢ ↑(unitGroupMulEquiv A) (↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))
[PROOFSTEP]
simpa using SetLike.coe_mem x
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
x : { x // x ∈ principalUnitGroup A }
⊢ (fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property := (_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) })
((fun x =>
{ val := ↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) },
property :=
(_ :
↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) } ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))) })
x) =
x
[PROOFSTEP]
simp
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
x : { x // x ∈ MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A })) }
⊢ (fun x =>
{ val := ↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) },
property :=
(_ :
↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) } ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))) })
((fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property := (_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) })
x) =
x
[PROOFSTEP]
simp
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
x y : { x // x ∈ principalUnitGroup A }
⊢ Equiv.toFun
{
toFun := fun x =>
{ val := ↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) },
property :=
(_ :
↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) } ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))) },
invFun := fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property := (_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) },
left_inv :=
(_ :
∀ (x : { x // x ∈ principalUnitGroup A }),
{
val :=
↑(↑(MulEquiv.symm (unitGroupMulEquiv A))
↑((fun x =>
{ val := ↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) },
property :=
(_ :
↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) } ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))) })
x)),
property :=
(_ :
↑(↑(MulEquiv.symm (unitGroupMulEquiv A))
↑((fun x =>
{ val := ↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) },
property :=
(_ :
↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) } ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))) })
x)) ∈
principalUnitGroup A) } =
x),
right_inv :=
(_ :
∀ (x : { x // x ∈ MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A })) }),
{
val :=
↑(unitGroupMulEquiv A)
{
val :=
↑((fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property :=
(_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) })
x),
property :=
(_ :
↑((fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property :=
(_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) })
x) ∈
unitGroup A) },
property :=
(_ :
↑(unitGroupMulEquiv A)
{
val :=
↑((fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property :=
(_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) })
x),
property :=
(_ :
↑((fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property :=
(_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) })
x) ∈
unitGroup A) } ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))) } =
x) }
(x * y) =
Equiv.toFun
{
toFun := fun x =>
{ val := ↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) },
property :=
(_ :
↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) } ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))) },
invFun := fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property := (_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) },
left_inv :=
(_ :
∀ (x : { x // x ∈ principalUnitGroup A }),
{
val :=
↑(↑(MulEquiv.symm (unitGroupMulEquiv A))
↑((fun x =>
{ val := ↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) },
property :=
(_ :
↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) } ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))) })
x)),
property :=
(_ :
↑(↑(MulEquiv.symm (unitGroupMulEquiv A))
↑((fun x =>
{ val := ↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) },
property :=
(_ :
↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) } ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))) })
x)) ∈
principalUnitGroup A) } =
x),
right_inv :=
(_ :
∀ (x : { x // x ∈ MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A })) }),
{
val :=
↑(unitGroupMulEquiv A)
{
val :=
↑((fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property :=
(_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) })
x),
property :=
(_ :
↑((fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property :=
(_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) })
x) ∈
unitGroup A) },
property :=
(_ :
↑(unitGroupMulEquiv A)
{
val :=
↑((fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property :=
(_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) })
x),
property :=
(_ :
↑((fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property :=
(_ :
↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) })
x) ∈
unitGroup A) } ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))) } =
x) }
x *
Equiv.toFun
{
toFun := fun x =>
{ val := ↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) },
property :=
(_ :
↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) } ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))) },
invFun := fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property := (_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) },
left_inv :=
(_ :
∀ (x : { x // x ∈ principalUnitGroup A }),
{
val :=
↑(↑(MulEquiv.symm (unitGroupMulEquiv A))
↑((fun x =>
{ val := ↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) },
property :=
(_ :
↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) } ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))) })
x)),
property :=
(_ :
↑(↑(MulEquiv.symm (unitGroupMulEquiv A))
↑((fun x =>
{ val := ↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) },
property :=
(_ :
↑(unitGroupMulEquiv A) { val := ↑x, property := (_ : ↑x ∈ unitGroup A) } ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))) })
x)) ∈
principalUnitGroup A) } =
x),
right_inv :=
(_ :
∀ (x : { x // x ∈ MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A })) }),
{
val :=
↑(unitGroupMulEquiv A)
{
val :=
↑((fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property :=
(_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) })
x),
property :=
(_ :
↑((fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property :=
(_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) })
x) ∈
unitGroup A) },
property :=
(_ :
↑(unitGroupMulEquiv A)
{
val :=
↑((fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property :=
(_ : ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) })
x),
property :=
(_ :
↑((fun x =>
{ val := ↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x),
property :=
(_ :
↑(↑(MulEquiv.symm (unitGroupMulEquiv A)) ↑x) ∈ principalUnitGroup A) })
x) ∈
unitGroup A) } ∈
MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))) } =
x) }
y
[PROOFSTEP]
rfl
[GOAL]
K : Type u
inst✝ : Field K
A : ValuationSubring K
⊢ MonoidHom.ker (unitGroupToResidueFieldUnits A) =
Subgroup.comap (Subgroup.subtype (unitGroup A)) (principalUnitGroup A)
[PROOFSTEP]
ext
-- Porting note: simp fails but rw works
-- See https://github.com/leanprover-community/mathlib4/issues/5026
-- simp [Subgroup.mem_comap, Subgroup.coeSubtype, coe_mem_principalUnitGroup_iff]
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
x✝ : { x // x ∈ unitGroup A }
⊢ x✝ ∈ MonoidHom.ker (unitGroupToResidueFieldUnits A) ↔
x✝ ∈ Subgroup.comap (Subgroup.subtype (unitGroup A)) (principalUnitGroup A)
[PROOFSTEP]
rw [Subgroup.mem_comap, Subgroup.coeSubtype, coe_mem_principalUnitGroup_iff]
[GOAL]
case h
K : Type u
inst✝ : Field K
A : ValuationSubring K
x✝ : { x // x ∈ unitGroup A }
⊢ x✝ ∈ MonoidHom.ker (unitGroupToResidueFieldUnits A) ↔
↑(unitGroupMulEquiv A) x✝ ∈ MonoidHom.ker (Units.map ↑(LocalRing.residue { x // x ∈ A }))
[PROOFSTEP]
rfl
-- simp [Subgroup.mem_comap, Subgroup.coeSubtype, coe_mem_principalUnitGroup_iff]
[GOAL]
K : Type u
inst✝² : Field K
A : ValuationSubring K
G : Type u_1
inst✝¹ : Group G
inst✝ : MulSemiringAction G K
g : G
S : ValuationSubring K
src✝ : Subring K := g • S.toSubring
x : K
h : (g⁻¹ • x)⁻¹ ∈ S
⊢ g⁻¹ • x⁻¹ ∈ S.toSubring
[PROOFSTEP]
rwa [smul_inv'']
[GOAL]
K : Type u
inst✝² : Field K
A✝ : ValuationSubring K
L : Type u_1
J : Type u_2
inst✝¹ : Field L
inst✝ : Field J
A : ValuationSubring L
f : K →+* L
src✝ : Subring K := Subring.comap f A.toSubring
k : K
⊢ k ∈
{ toSubsemiring := src✝.toSubsemiring,
neg_mem' :=
(_ :
∀ {x : K},
x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier ∨
k⁻¹ ∈
{ toSubsemiring := src✝.toSubsemiring,
neg_mem' :=
(_ :
∀ {x : K}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier
[PROOFSTEP]
simp [ValuationSubring.mem_or_inv_mem]
|
DK1 schwarz,1,Projekt //creates kone
S(1,1,2) //rediefine edges as (r,r,h)
|
/-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Mario Carneiro
-/
import data.prod
import data.subtype
/-!
# Basic definitions about `≤` and `<`
This file proves basic results about orders, provides extensive dot notation, defines useful order
classes and allows to transfer order instances.
## Type synonyms
* `order_dual α` : A type synonym reversing the meaning of all inequalities.
* `as_linear_order α`: A type synonym to promote `partial_order α` to `linear_order α` using
`is_total α (≤)`.
### Transfering orders
- `order.preimage`, `preorder.lift`: Transfers a (pre)order on `β` to an order on `α`
using a function `f : α → β`.
- `partial_order.lift`, `linear_order.lift`: Transfers a partial (resp., linear) order on `β` to a
partial (resp., linear) order on `α` using an injective function `f`.
### Extra class
- `densely_ordered`: An order with no gap, i.e. for any two elements `a < b` there exists `c` such
that `a < c < b`.
## Notes
`≤` and `<` are highly favored over `≥` and `>` in mathlib. The reason is that we can formulate all
lemmas using `≤`/`<`, and `rw` has trouble unifying `≤` and `≥`. Hence choosing one direction spares
us useless duplication. This is enforced by a linter. See Note [nolint_ge] for more infos.
Dot notation is particularly useful on `≤` (`has_le.le`) and `<` (`has_lt.lt`). To that end, we
provide many aliases to dot notation-less lemmas. For example, `le_trans` is aliased with
`has_le.le.trans` and can be used to construct `hab.trans hbc : a ≤ c` when `hab : a ≤ b`,
`hbc : b ≤ c`, `lt_of_le_of_lt` is aliased as `has_le.le.trans_lt` and can be used to construct
`hab.trans hbc : a < c` when `hab : a ≤ b`, `hbc : b < c`.
## TODO
- expand module docs
- automatic construction of dual definitions / theorems
## Tags
preorder, order, partial order, poset, linear order, chain
-/
open function
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop}
lemma ge_antisymm [partial_order α] {a b : α} (hab : a ≤ b) (hba : b ≤ a) : b = a :=
le_antisymm hba hab
attribute [simp] le_refl
attribute [ext] has_le
alias le_trans ← has_le.le.trans
alias lt_of_le_of_lt ← has_le.le.trans_lt
alias le_antisymm ← has_le.le.antisymm
alias ge_antisymm ← has_le.le.antisymm'
alias lt_of_le_of_ne ← has_le.le.lt_of_ne
alias lt_of_le_not_le ← has_le.le.lt_of_not_le
alias lt_or_eq_of_le ← has_le.le.lt_or_eq
alias decidable.lt_or_eq_of_le ← has_le.le.lt_or_eq_dec
alias le_of_lt ← has_lt.lt.le
alias lt_trans ← has_lt.lt.trans
alias lt_of_lt_of_le ← has_lt.lt.trans_le
alias ne_of_lt ← has_lt.lt.ne
alias lt_asymm ← has_lt.lt.asymm has_lt.lt.not_lt
alias le_of_eq ← eq.le
attribute [nolint decidable_classical] has_le.le.lt_or_eq_dec
/-- A version of `le_refl` where the argument is implicit -/
lemma le_rfl [preorder α] {x : α} : x ≤ x := le_refl x
@[simp] lemma lt_self_iff_false [preorder α] (x : α) : x < x ↔ false :=
⟨lt_irrefl x, false.elim⟩
namespace eq
/-- If `x = y` then `y ≤ x`. Note: this lemma uses `y ≤ x` instead of `x ≥ y`, because `le` is used
almost exclusively in mathlib. -/
protected
lemma trans_le [preorder α] {x y z : α} (h1 : x = y) (h2 : y ≤ z) : x ≤ z := h1.le.trans h2
lemma not_lt [partial_order α] {x y : α} (h : x = y) : ¬(x < y) := λ h', h'.ne h
lemma not_gt [partial_order α] {x y : α} (h : x = y) : ¬(y < x) := h.symm.not_lt
end eq
namespace has_le.le
@[nolint ge_or_gt] -- see Note [nolint_ge]
protected lemma ge [has_le α] {x y : α} (h : x ≤ y) : y ≥ x := h
lemma trans_eq [preorder α] {x y z : α} (h1 : x ≤ y) (h2 : y = z) : x ≤ z := h1.trans h2.le
lemma lt_iff_ne [partial_order α] {x y : α} (h : x ≤ y) : x < y ↔ x ≠ y := ⟨λ h, h.ne, h.lt_of_ne⟩
lemma le_iff_eq [partial_order α] {x y : α} (h : x ≤ y) : y ≤ x ↔ y = x :=
⟨λ h', h'.antisymm h, eq.le⟩
lemma lt_or_le [linear_order α] {a b : α} (h : a ≤ b) (c : α) : a < c ∨ c ≤ b :=
(lt_or_ge a c).imp id $ λ hc, le_trans hc h
lemma le_or_lt [linear_order α] {a b : α} (h : a ≤ b) (c : α) : a ≤ c ∨ c < b :=
(le_or_gt a c).imp id $ λ hc, lt_of_lt_of_le hc h
lemma le_or_le [linear_order α] {a b : α} (h : a ≤ b) (c : α) : a ≤ c ∨ c ≤ b :=
(h.le_or_lt c).elim or.inl (λ h, or.inr $ le_of_lt h)
end has_le.le
namespace has_lt.lt
@[nolint ge_or_gt] -- see Note [nolint_ge]
protected lemma gt [has_lt α] {x y : α} (h : x < y) : y > x := h
protected lemma false [preorder α] {x : α} : x < x → false := lt_irrefl x
lemma ne' [preorder α] {x y : α} (h : x < y) : y ≠ x := h.ne.symm
lemma lt_or_lt [linear_order α] {x y : α} (h : x < y) (z : α) : x < z ∨ z < y :=
(lt_or_ge z y).elim or.inr (λ hz, or.inl $ h.trans_le hz)
end has_lt.lt
@[nolint ge_or_gt] -- see Note [nolint_ge]
protected lemma ge.le [has_le α] {x y : α} (h : x ≥ y) : y ≤ x := h
@[nolint ge_or_gt] -- see Note [nolint_ge]
protected lemma gt.lt [has_lt α] {x y : α} (h : x > y) : y < x := h
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem ge_of_eq [preorder α] {a b : α} (h : a = b) : a ≥ b := h.ge
@[simp, nolint ge_or_gt] -- see Note [nolint_ge]
lemma ge_iff_le [preorder α] {a b : α} : a ≥ b ↔ b ≤ a := iff.rfl
@[simp, nolint ge_or_gt] -- see Note [nolint_ge]
lemma gt_iff_lt [preorder α] {a b : α} : a > b ↔ b < a := iff.rfl
lemma not_le_of_lt [preorder α] {a b : α} (h : a < b) : ¬ b ≤ a := (le_not_le_of_lt h).right
alias not_le_of_lt ← has_lt.lt.not_le
lemma not_lt_of_le [preorder α] {a b : α} (h : a ≤ b) : ¬ b < a := λ hba, hba.not_le h
alias not_lt_of_le ← has_le.le.not_lt
lemma ne_of_not_le [preorder α] {a b : α} (h : ¬ a ≤ b) : a ≠ b :=
λ hab, h (le_of_eq hab)
-- See Note [decidable namespace]
protected lemma decidable.le_iff_eq_or_lt [partial_order α] [@decidable_rel α (≤)]
{a b : α} : a ≤ b ↔ a = b ∨ a < b := decidable.le_iff_lt_or_eq.trans or.comm
lemma le_iff_eq_or_lt [partial_order α] {a b : α} : a ≤ b ↔ a = b ∨ a < b :=
le_iff_lt_or_eq.trans or.comm
lemma lt_iff_le_and_ne [partial_order α] {a b : α} : a < b ↔ a ≤ b ∧ a ≠ b :=
⟨λ h, ⟨le_of_lt h, ne_of_lt h⟩, λ ⟨h1, h2⟩, h1.lt_of_ne h2⟩
-- See Note [decidable namespace]
protected lemma decidable.eq_iff_le_not_lt [partial_order α] [@decidable_rel α (≤)]
{a b : α} : a = b ↔ a ≤ b ∧ ¬ a < b :=
⟨λ h, ⟨h.le, h ▸ lt_irrefl _⟩, λ ⟨h₁, h₂⟩, h₁.antisymm $
decidable.by_contradiction $ λ h₃, h₂ (h₁.lt_of_not_le h₃)⟩
lemma eq_iff_le_not_lt [partial_order α] {a b : α} : a = b ↔ a ≤ b ∧ ¬ a < b :=
by haveI := classical.dec; exact decidable.eq_iff_le_not_lt
lemma eq_or_lt_of_le [partial_order α] {a b : α} (h : a ≤ b) : a = b ∨ a < b := h.lt_or_eq.symm
lemma eq_or_gt_of_le [partial_order α] {a b : α} (h : a ≤ b) : b = a ∨ a < b :=
h.lt_or_eq.symm.imp eq.symm id
alias decidable.eq_or_lt_of_le ← has_le.le.eq_or_lt_dec
alias eq_or_lt_of_le ← has_le.le.eq_or_lt
alias eq_or_gt_of_le ← has_le.le.eq_or_gt
attribute [nolint decidable_classical] has_le.le.eq_or_lt_dec
lemma eq_of_le_of_not_lt [partial_order α] {a b : α} (hab : a ≤ b) (hba : ¬ a < b) : a = b :=
hab.eq_or_lt.resolve_right hba
lemma eq_of_ge_of_not_gt [partial_order α] {a b : α} (hab : a ≤ b) (hba : ¬ a < b) : b = a :=
(hab.eq_or_lt.resolve_right hba).symm
alias eq_of_le_of_not_lt ← has_le.le.eq_of_not_lt
alias eq_of_ge_of_not_gt ← has_le.le.eq_of_not_gt
lemma ne.le_iff_lt [partial_order α] {a b : α} (h : a ≠ b) : a ≤ b ↔ a < b :=
⟨λ h', lt_of_le_of_ne h' h, λ h, h.le⟩
-- See Note [decidable namespace]
protected lemma decidable.ne_iff_lt_iff_le [partial_order α] [@decidable_rel α (≤)]
{a b : α} : (a ≠ b ↔ a < b) ↔ a ≤ b :=
⟨λ h, decidable.by_cases le_of_eq (le_of_lt ∘ h.mp), λ h, ⟨lt_of_le_of_ne h, ne_of_lt⟩⟩
@[simp] lemma ne_iff_lt_iff_le [partial_order α] {a b : α} : (a ≠ b ↔ a < b) ↔ a ≤ b :=
by haveI := classical.dec; exact decidable.ne_iff_lt_iff_le
lemma lt_of_not_ge' [linear_order α] {a b : α} (h : ¬ b ≤ a) : a < b :=
((le_total _ _).resolve_right h).lt_of_not_le h
lemma lt_iff_not_ge' [linear_order α] {x y : α} : x < y ↔ ¬ y ≤ x := ⟨not_le_of_gt, lt_of_not_ge'⟩
lemma ne.lt_or_lt [linear_order α] {x y : α} (h : x ≠ y) : x < y ∨ y < x := lt_or_gt_of_ne h
/-- A version of `ne_iff_lt_or_gt` with LHS and RHS reversed. -/
@[simp] lemma lt_or_lt_iff_ne [linear_order α] {x y : α} : x < y ∨ y < x ↔ x ≠ y :=
ne_iff_lt_or_gt.symm
lemma not_lt_iff_eq_or_lt [linear_order α] {a b : α} : ¬ a < b ↔ a = b ∨ b < a :=
not_lt.trans $ decidable.le_iff_eq_or_lt.trans $ or_congr eq_comm iff.rfl
lemma exists_ge_of_linear [linear_order α] (a b : α) : ∃ c, a ≤ c ∧ b ≤ c :=
match le_total a b with
| or.inl h := ⟨_, h, le_rfl⟩
| or.inr h := ⟨_, le_rfl, h⟩
end
lemma lt_imp_lt_of_le_imp_le {β} [linear_order α] [preorder β] {a b : α} {c d : β}
(H : a ≤ b → c ≤ d) (h : d < c) : b < a :=
lt_of_not_ge' $ λ h', (H h').not_lt h
lemma le_imp_le_iff_lt_imp_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} :
(a ≤ b → c ≤ d) ↔ (d < c → b < a) :=
⟨lt_imp_lt_of_le_imp_le, le_imp_le_of_lt_imp_lt⟩
lemma lt_iff_lt_of_le_iff_le' {β} [preorder α] [preorder β] {a b : α} {c d : β}
(H : a ≤ b ↔ c ≤ d) (H' : b ≤ a ↔ d ≤ c) : b < a ↔ d < c :=
lt_iff_le_not_le.trans $ (and_congr H' (not_congr H)).trans lt_iff_le_not_le.symm
lemma lt_iff_lt_of_le_iff_le {β} [linear_order α] [linear_order β] {a b : α} {c d : β}
(H : a ≤ b ↔ c ≤ d) : b < a ↔ d < c :=
not_le.symm.trans $ (not_congr H).trans $ not_le
lemma le_iff_le_iff_lt_iff_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} :
(a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) :=
⟨lt_iff_lt_of_le_iff_le, λ H, not_lt.symm.trans $ (not_congr H).trans $ not_lt⟩
lemma eq_of_forall_le_iff [partial_order α] {a b : α}
(H : ∀ c, c ≤ a ↔ c ≤ b) : a = b :=
((H _).1 le_rfl).antisymm ((H _).2 le_rfl)
lemma le_of_forall_le [preorder α] {a b : α}
(H : ∀ c, c ≤ a → c ≤ b) : a ≤ b :=
H _ le_rfl
lemma le_of_forall_le' [preorder α] {a b : α}
(H : ∀ c, a ≤ c → b ≤ c) : b ≤ a :=
H _ le_rfl
lemma le_of_forall_lt [linear_order α] {a b : α}
(H : ∀ c, c < a → c < b) : a ≤ b :=
le_of_not_lt $ λ h, lt_irrefl _ (H _ h)
lemma forall_lt_iff_le [linear_order α] {a b : α} :
(∀ ⦃c⦄, c < a → c < b) ↔ a ≤ b :=
⟨le_of_forall_lt, λ h c hca, lt_of_lt_of_le hca h⟩
lemma le_of_forall_lt' [linear_order α] {a b : α}
(H : ∀ c, a < c → b < c) : b ≤ a :=
le_of_not_lt $ λ h, lt_irrefl _ (H _ h)
lemma forall_lt_iff_le' [linear_order α] {a b : α} :
(∀ ⦃c⦄, a < c → b < c) ↔ b ≤ a :=
⟨le_of_forall_lt', λ h c hac, lt_of_le_of_lt h hac⟩
lemma eq_of_forall_ge_iff [partial_order α] {a b : α}
(H : ∀ c, a ≤ c ↔ b ≤ c) : a = b :=
((H _).2 le_rfl).antisymm ((H _).1 le_rfl)
/-- monotonicity of `≤` with respect to `→` -/
lemma le_implies_le_of_le_of_le {a b c d : α} [preorder α] (hca : c ≤ a) (hbd : b ≤ d) :
a ≤ b → c ≤ d :=
λ hab, (hca.trans hab).trans hbd
@[ext]
lemma preorder.to_has_le_injective {α : Type*} :
function.injective (@preorder.to_has_le α) :=
λ A B h, begin
cases A, cases B,
injection h with h_le,
have : A_lt = B_lt,
{ funext a b,
dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le h_le,
simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, h_le], },
congr',
end
@[ext]
lemma partial_order.to_preorder_injective {α : Type*} :
function.injective (@partial_order.to_preorder α) :=
λ A B h, by { cases A, cases B, injection h, congr' }
@[ext]
lemma linear_order.to_partial_order_injective {α : Type*} :
function.injective (@linear_order.to_partial_order α) :=
begin
intros A B h,
cases A, cases B, injection h,
obtain rfl : A_le = B_le := ‹_›, obtain rfl : A_lt = B_lt := ‹_›,
obtain rfl : A_decidable_le = B_decidable_le := subsingleton.elim _ _,
obtain rfl : A_max = B_max := A_max_def.trans B_max_def.symm,
obtain rfl : A_min = B_min := A_min_def.trans B_min_def.symm,
congr
end
theorem preorder.ext {α} {A B : preorder α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
by { ext x y, exact H x y }
theorem partial_order.ext {α} {A B : partial_order α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
by { ext x y, exact H x y }
theorem linear_order.ext {α} {A B : linear_order α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
by { ext x y, exact H x y }
/-- Given a relation `R` on `β` and a function `f : α → β`, the preimage relation on `α` is defined
by `x ≤ y ↔ f x ≤ f y`. It is the unique relation on `α` making `f` a `rel_embedding` (assuming `f`
is injective). -/
@[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) : Prop := s (f x) (f y)
infix ` ⁻¹'o `:80 := order.preimage
/-- The preimage of a decidable order is decidable. -/
instance order.preimage.decidable {α β} (f : α → β) (s : β → β → Prop) [H : decidable_rel s] :
decidable_rel (f ⁻¹'o s) :=
λ x y, H _ _
/-! ### Order dual -/
/-- Type synonym to equip a type with the dual order: `≤` means `≥` and `<` means `>`. -/
def order_dual (α : Type*) : Type* := α
namespace order_dual
instance (α : Type*) [h : nonempty α] : nonempty (order_dual α) := h
instance (α : Type*) [h : subsingleton α] : subsingleton (order_dual α) := h
instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λ x y : α, y ≤ x⟩
instance (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λ x y : α, y < x⟩
instance (α : Type*) [has_zero α] : has_zero (order_dual α) := ⟨(0 : α)⟩
-- `dual_le` and `dual_lt` should not be simp lemmas:
-- they cause a loop since `α` and `order_dual α` are definitionally equal
lemma dual_le [has_le α] {a b : α} :
@has_le.le (order_dual α) _ a b ↔ @has_le.le α _ b a := iff.rfl
lemma dual_lt [has_lt α] {a b : α} :
@has_lt.lt (order_dual α) _ a b ↔ @has_lt.lt α _ b a := iff.rfl
instance (α : Type*) [preorder α] : preorder (order_dual α) :=
{ le_refl := le_refl,
le_trans := λ a b c hab hbc, hbc.trans hab,
lt_iff_le_not_le := λ _ _, lt_iff_le_not_le,
.. order_dual.has_le α,
.. order_dual.has_lt α }
instance (α : Type*) [partial_order α] : partial_order (order_dual α) :=
{ le_antisymm := λ a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α }
instance (α : Type*) [linear_order α] : linear_order (order_dual α) :=
{ le_total := λ a b : α, le_total b a,
decidable_le := (infer_instance : decidable_rel (λ a b : α, b ≤ a)),
decidable_lt := (infer_instance : decidable_rel (λ a b : α, b < a)),
min := @max α _,
max := @min α _,
min_def := @linear_order.max_def α _,
max_def := @linear_order.min_def α _,
.. order_dual.partial_order α }
instance : Π [inhabited α], inhabited (order_dual α) := id
theorem preorder.dual_dual (α : Type*) [H : preorder α] :
order_dual.preorder (order_dual α) = H :=
preorder.ext $ λ _ _, iff.rfl
theorem partial_order.dual_dual (α : Type*) [H : partial_order α] :
order_dual.partial_order (order_dual α) = H :=
partial_order.ext $ λ _ _, iff.rfl
theorem linear_order.dual_dual (α : Type*) [H : linear_order α] :
order_dual.linear_order (order_dual α) = H :=
linear_order.ext $ λ _ _, iff.rfl
end order_dual
/-! ### Order instances on the function space -/
instance pi.has_le {ι : Type u} {α : ι → Type v} [∀ i, has_le (α i)] : has_le (Π i, α i) :=
{ le := λ x y, ∀ i, x i ≤ y i }
lemma pi.le_def {ι : Type u} {α : ι → Type v} [∀ i, has_le (α i)] {x y : Π i, α i} :
x ≤ y ↔ ∀ i, x i ≤ y i :=
iff.rfl
instance pi.preorder {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] : preorder (Π i, α i) :=
{ le_refl := λ a i, le_refl (a i),
le_trans := λ a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i),
..pi.has_le }
lemma pi.lt_def {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] {x y : Π i, α i} :
x < y ↔ x ≤ y ∧ ∃ i, x i < y i :=
by simp [lt_iff_le_not_le, pi.le_def] {contextual := tt}
lemma le_update_iff {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] [decidable_eq ι]
{x y : Π i, α i} {i : ι} {a : α i} :
x ≤ function.update y i a ↔ x i ≤ a ∧ ∀ j ≠ i, x j ≤ y j :=
function.forall_update_iff _ (λ j z, x j ≤ z)
lemma update_le_iff {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] [decidable_eq ι]
{x y : Π i, α i} {i : ι} {a : α i} :
function.update x i a ≤ y ↔ a ≤ y i ∧ ∀ j ≠ i, x j ≤ y j :=
function.forall_update_iff _ (λ j z, z ≤ y j)
lemma update_le_update_iff {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] [decidable_eq ι]
{x y : Π i, α i} {i : ι} {a b : α i} :
function.update x i a ≤ function.update y i b ↔ a ≤ b ∧ ∀ j ≠ i, x j ≤ y j :=
by simp [update_le_iff] {contextual := tt}
instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀ i, partial_order (α i)] :
partial_order (Π i, α i) :=
{ le_antisymm := λ f g h1 h2, funext (λ b, (h1 b).antisymm (h2 b)),
..pi.preorder }
/-! ### Lifts of order instances -/
/-- Transfer a `preorder` on `β` to a `preorder` on `α` using a function `f : α → β`.
See note [reducible non-instances]. -/
@[reducible] def preorder.lift {α β} [preorder β] (f : α → β) : preorder α :=
{ le := λ x y, f x ≤ f y,
le_refl := λ a, le_rfl,
le_trans := λ a b c, le_trans,
lt := λ x y, f x < f y,
lt_iff_le_not_le := λ a b, lt_iff_le_not_le }
/-- Transfer a `partial_order` on `β` to a `partial_order` on `α` using an injective
function `f : α → β`. See note [reducible non-instances]. -/
@[reducible] def partial_order.lift {α β} [partial_order β] (f : α → β) (inj : injective f) :
partial_order α :=
{ le_antisymm := λ a b h₁ h₂, inj (h₁.antisymm h₂), .. preorder.lift f }
/-- Transfer a `linear_order` on `β` to a `linear_order` on `α` using an injective
function `f : α → β`. See note [reducible non-instances]. -/
@[reducible] def linear_order.lift {α β} [linear_order β] (f : α → β) (inj : injective f) :
linear_order α :=
{ le_total := λ x y, le_total (f x) (f y),
decidable_le := λ x y, (infer_instance : decidable (f x ≤ f y)),
decidable_lt := λ x y, (infer_instance : decidable (f x < f y)),
decidable_eq := λ x y, decidable_of_iff _ inj.eq_iff,
.. partial_order.lift f inj }
instance subtype.preorder {α} [preorder α] (p : α → Prop) : preorder (subtype p) :=
preorder.lift (coe : subtype p → α)
@[simp] lemma subtype.mk_le_mk {α} [preorder α] {p : α → Prop} {x y : α} {hx : p x} {hy : p y} :
(⟨x, hx⟩ : subtype p) ≤ ⟨y, hy⟩ ↔ x ≤ y :=
iff.rfl
@[simp] lemma subtype.mk_lt_mk {α} [preorder α] {p : α → Prop} {x y : α} {hx : p x} {hy : p y} :
(⟨x, hx⟩ : subtype p) < ⟨y, hy⟩ ↔ x < y :=
iff.rfl
@[simp, norm_cast] lemma subtype.coe_le_coe {α} [preorder α] {p : α → Prop} {x y : subtype p} :
(x : α) ≤ y ↔ x ≤ y :=
iff.rfl
@[simp, norm_cast] lemma subtype.coe_lt_coe {α} [preorder α] {p : α → Prop} {x y : subtype p} :
(x : α) < y ↔ x < y :=
iff.rfl
instance subtype.partial_order {α} [partial_order α] (p : α → Prop) :
partial_order (subtype p) :=
partial_order.lift coe subtype.coe_injective
/-- A subtype of a linear order is a linear order. We explicitly give the proof of decidable
equality as the existing instance, in order to not have two instances of decidable equality that
are not definitionally equal. -/
instance subtype.linear_order {α} [linear_order α] (p : α → Prop) : linear_order (subtype p) :=
{ decidable_eq := subtype.decidable_eq,
.. linear_order.lift coe subtype.coe_injective }
/-!
### Pointwise order on `α × β`
The lexicographic order is defined in `order.lexicographic`, and the instances are available via the
type synonym `α ×ₗ β = α × β`.
-/
namespace prod
instance (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) :=
⟨λ p q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩
lemma le_def [has_le α] [has_le β] {x y : α × β} : x ≤ y ↔ x.1 ≤ y.1 ∧ x.2 ≤ y.2 := iff.rfl
@[simp] lemma mk_le_mk [has_le α] [has_le β] {x₁ x₂ : α} {y₁ y₂ : β} :
(x₁, y₁) ≤ (x₂, y₂) ↔ x₁ ≤ x₂ ∧ y₁ ≤ y₂ :=
iff.rfl
instance (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) :=
{ le_refl := λ ⟨a, b⟩, ⟨le_refl a, le_refl b⟩,
le_trans := λ ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩,
⟨le_trans hac hce, le_trans hbd hdf⟩,
.. prod.has_le α β }
lemma lt_iff [preorder α] [preorder β] {a b : α × β} :
a < b ↔ a.1 < b.1 ∧ a.2 ≤ b.2 ∨ a.1 ≤ b.1 ∧ a.2 < b.2 :=
begin
refine ⟨λ h, _, _⟩,
{ by_cases h₁ : b.1 ≤ a.1,
{ exact or.inr ⟨h.1.1, h.1.2.lt_of_not_le $ λ h₂, h.2 ⟨h₁, h₂⟩⟩ },
{ exact or.inl ⟨h.1.1.lt_of_not_le h₁, h.1.2⟩ } },
{ rintro (⟨h₁, h₂⟩ | ⟨h₁, h₂⟩),
{ exact ⟨⟨h₁.le, h₂⟩, λ h, h₁.not_le h.1⟩ },
{ exact ⟨⟨h₁, h₂.le⟩, λ h, h₂.not_le h.2⟩ } }
end
@[simp] lemma mk_lt_mk [preorder α] [preorder β] {x₁ x₂ : α} {y₁ y₂ : β} :
(x₁, y₁) < (x₂, y₂) ↔ x₁ < x₂ ∧ y₁ ≤ y₂ ∨ x₁ ≤ x₂ ∧ y₁ < y₂ :=
lt_iff
/-- The pointwise partial order on a product.
(The lexicographic ordering is defined in order/lexicographic.lean, and the instances are
available via the type synonym `α ×ₗ β = α × β`.) -/
instance (α : Type u) (β : Type v) [partial_order α] [partial_order β] :
partial_order (α × β) :=
{ le_antisymm := λ ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩,
prod.ext (hac.antisymm hca) (hbd.antisymm hdb),
.. prod.preorder α β }
end prod
/-! ### Additional order classes -/
/-- An order is dense if there is an element between any pair of distinct elements. -/
class densely_ordered (α : Type u) [has_lt α] : Prop :=
(dense : ∀ a₁ a₂ : α, a₁ < a₂ → ∃ a, a₁ < a ∧ a < a₂)
lemma exists_between [has_lt α] [densely_ordered α] :
∀ {a₁ a₂ : α}, a₁ < a₂ → ∃ a, a₁ < a ∧ a < a₂ :=
densely_ordered.dense
instance order_dual.densely_ordered (α : Type u) [has_lt α] [densely_ordered α] :
densely_ordered (order_dual α) :=
⟨λ a₁ a₂ ha, (@exists_between α _ _ _ _ ha).imp $ λ a, and.symm⟩
lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h : ∀ a, a₂ < a → a₁ ≤ a) :
a₁ ≤ a₂ :=
le_of_not_gt $ λ ha,
let ⟨a, ha₁, ha₂⟩ := exists_between ha in
lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›)
lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h₁ : a₂ ≤ a₁) (h₂ : ∀ a, a₂ < a → a₁ ≤ a) : a₁ = a₂ :=
le_antisymm (le_of_forall_le_of_dense h₂) h₁
lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h : ∀ a₃ < a₁, a₃ ≤ a₂) :
a₁ ≤ a₂ :=
le_of_not_gt $ λ ha,
let ⟨a, ha₁, ha₂⟩ := exists_between ha in
lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a›
lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h₁ : a₂ ≤ a₁) (h₂ : ∀ a₃ < a₁, a₃ ≤ a₂) : a₁ = a₂ :=
(le_of_forall_ge_of_dense h₂).antisymm h₁
lemma dense_or_discrete [linear_order α] (a₁ a₂ : α) :
(∃ a, a₁ < a ∧ a < a₂) ∨ ((∀ a, a₁ < a → a₂ ≤ a) ∧ (∀ a < a₂, a ≤ a₁)) :=
or_iff_not_imp_left.2 $ λ h,
⟨λ a ha₁, le_of_not_gt $ λ ha₂, h ⟨a, ha₁, ha₂⟩,
λ a ha₂, le_of_not_gt $ λ ha₁, h ⟨a, ha₁, ha₂⟩⟩
variables {s : β → β → Prop} {t : γ → γ → Prop}
/-! ### Linear order from a total partial order -/
/-- Type synonym to create an instance of `linear_order` from a `partial_order` and
`is_total α (≤)` -/
def as_linear_order (α : Type u) := α
instance {α} [inhabited α] : inhabited (as_linear_order α) :=
⟨ (default : α) ⟩
noncomputable instance as_linear_order.linear_order {α} [partial_order α] [is_total α (≤)] :
linear_order (as_linear_order α) :=
{ le_total := @total_of α (≤) _,
decidable_le := classical.dec_rel _,
.. (_ : partial_order α) }
|
```python
from IPython.display import Image
Image('../../Python_probability_statistics_machine_learning_2E.png',width=200)
```
It is sometimes very difficult to unequivocally attribute outcomes to causal
factors. For example, did your experiment generate the outcome you were hoping
for or not? Maybe something did happen, but the effect is not pronounced
enough
to separate it from inescapable measurement errors or other
factors in the
ambient environment? Hypothesis testing is a powerful
statistical method to
address these questions. Let's begin by again
considering our coin-tossing
experiment with unknown parameter $p$. Recall
that the individual coin-flips
are Bernoulli distributed. The first step is
to establish separate hypotheses.
First, $H_0$ is the so-called null
hypothesis. In our case this can be
$$
H_0 \colon \theta < \frac{1}{2}
$$
and the alternative hypothesis is then
$$
H_1 \colon \theta \geq \frac{1}{2}
$$
With this set up, the question now boils down to figuring out which
hypothesis
the data is most consistent with. To choose between these, we need
a
statistical test that is a function, $G$, of the sample set
$\mathbf{X}_n=\left\{ X_i \right\}_n $ into the real line, where $X_i$ is the
heads or tails outcome ($X_i \in \lbrace 0,1 \rbrace$). In other words, we
compute $G(\mathbf{X}_n)$ and check if it exceeds a threshold $c$. If not, then
we declare $H_0$ (otherwise, declare $H_1$). Notationally, this is the
following:
$$
\begin{align*}
G(\mathbf{X}_n) < c & \Rightarrow H_0 \\\
G(\mathbf{X}_n)
\geq c & \Rightarrow H_1
\end{align*}
$$
In summary, we have the observed data $\mathbf{X}_n$ and a function
$G$ that
maps that data onto the real line. Then, using the
constant $c$ as a threshold,
the inequality effectively divides the real line
into two parts, one
corresponding to each of the hypotheses.
Whatever this test $G$ is, it will
make mistakes of two types --- false
negatives and false positives. The false
positives arise from the case where we
declare $H_0$ when the test says we
should declare $H_1$. This is
summarized in the Table [1](#tbl:decision).
<!-- Equation labels as ordinary links -->
<div id="tbl:decision"></div>
$$
\begin{table}
\footnotesize
\centering
\begin{tabular}{l|p{1.3in}|p{1.3in}}
\multicolumn{1}{c}{ } & \multicolumn{1}{c}{Declare $H_0$ } & \multicolumn{1}{c}{
Declare $H_1$ } \\
\hline
$H_0\:$ True & Correct & False
positive (Type I error) \\
\hline
$H_1\:$ True & False negative (Type II error)
& Correct (true-detect) \\
\hline
\end{tabular}
\caption{Truth table for
hypotheses testing.}
\label{tbl:decision} \tag{1}
\end{table}
$$
For this example, here are the false positives (aka false alarms):
$$
P_{FA} = \mathbb{P}\left( G(\mathbf{X}_n) > c \mid \theta \leq \frac{1}{2}
\right)
$$
Or, equivalently,
$$
P_{FA} = \mathbb{P}\left( G(\mathbf{X}_n) > c \mid H_0 \right)
$$
Likewise, the other error is a false negative, which we can write
analogously
as
$$
P_{FN} = \mathbb{P}\left( G(\mathbf{X}_n) < c \vert H_1\right)
$$
By choosing some acceptable values for either of these errors,
we can solve for
the other one. The practice is usually to pick a value of
$P_{FA}$ and then
find the corresponding value of $P_{FN}$. Note that it is
traditional in
engineering to speak about *detection probability*, which is
defined as
$$
P_{D} = 1- P_{FN} = \mathbb{P}\left( G(\mathbf{X}_n) > c \mid H_1\right)
$$
In other words, this is the probability of declaring $H_1$ when the
test
exceeds the threshold. This is otherwise known as the *probability of a
true
detection* or *true-detect*.
## Back to the Coin Flipping Example
In our
previous maximum likelihood discussion, we wanted to derive an
estimator for the
*value* of the probability of heads for the coin
flipping experiment. For
hypthesis testing, we want to ask a softer
question: is the probability of heads
greater or less than $\nicefrac{1}{2}$? As we
just established, this leads to
the two hypotheses:
$$
H_0 \colon \theta < \frac{1}{2}
$$
versus,
$$
H_1 \colon \theta > \frac{1}{2}
$$
Let's assume we have five observations. Now we need the $G$ function
and a
threshold $c$ to help pick between the two hypotheses. Let's count the
number of
heads observed in five observations as our
criterion. Thus, we have
$$
G(\mathbf{X}_5) := \sum_{i=1}^5 X_i
$$
and, suppose further that we pick $H_1$ only if exactly five out of
five
observations are heads. We'll call this the *all-heads* test.
Now, because all
of the $X_i$ are random variables, so is $G$ and we must
find the corresponding
probability mass function for $G$. Assuming the
individual coin tosses are
independent, the probability of five heads is $\theta^5$.
This means that the
probability of rejecting the $H_0$ hypothesis (and choosing
$H_1$, because there
are only two choices here) based on the unknown underlying
probability is
$\theta^5$. In the parlance, this is known and the *power function*
as in
denoted by $\beta$ as in
$$
\beta(\theta) = \theta^5
$$
Let's get a quick plot this in [Figure](#fig:Hypothesis_testing_001).
<!--
@@@CODE src-statistics/Hypothesis_Testing.py fromto: import numpy as
[email protected] -->
```python
%matplotlib inline
from matplotlib.pylab import subplots
import numpy as np
fig,ax=subplots()
fig.set_size_inches((6,3))
xi = np.linspace(0,1,50)
_=ax.plot(xi, (xi)**5,'-k',label='all heads')
_=ax.set_xlabel(r'$\theta$',fontsize=22)
_=ax.plot(0.5,(0.5)**5,'ko')
fig.tight_layout()
fig.savefig('fig-statistics/Hypothesis_Testing_001.png')
```
<!-- dom:FIGURE: [fig-statistics/Hypothesis_Testing_001.png, width=500
frac=0.85] Power function for the all-heads test. The dark circle indicates the
value of the function indicating $\alpha$. <div
id="fig:Hypothesis_testing_001"></div> -->
<!-- begin figure -->
<div
id="fig:Hypothesis_testing_001"></div>
<p>Power function for the all-heads
test. The dark circle indicates the value of the function indicating
$\alpha$.</p>
<!-- end figure -->
Now, we have the following false alarm probability,
$$
P_{FA} = \mathbb{P}( G(\mathbf{X}_n)= 5 \vert H_0) =\mathbb{P}( \theta^5
\vert H_0)
$$
Notice that this is a function of $\theta$, which means there are
many false
alarm probability values that correspond to this test. To be on the
conservative
side, we'll pick the supremum (i.e., maximum) of this function,
which is known
as the *size* of the test, traditionally denoted by $\alpha$,
$$
\alpha = \sup_{\theta \in \Theta_0} \beta(\theta)
$$
with domain $\Theta_0 = \lbrace \theta < 1/2 \rbrace$ which in our case is
$$
\alpha = \sup_{\theta < \frac{1}{2}} \theta^5 = \left(\frac{1}{2}\right)^5 =
0.03125
$$
Likewise, for the detection probability,
$$
\mathbb{P}_{D}(\theta) = \mathbb{P}( \theta^5 \vert H_1)
$$
which is again a function of the parameter $\theta$. The problem with
this test
is that the $P_{D}$ is pretty low for most of the domain of
$\theta$. For
instance, values in the nineties for $P_{D}$
only happen when $\theta > 0.98$.
In other words, if the coin produces
heads 98 times out of 100, then we can
detect $H_1$ reliably. Ideally, we want
a test that is zero for the domain
corresponding to $H_0$ (i.e., $\Theta_0$) and
equal to one otherwise.
Unfortunately, even if we increase the length of the
observed sequence, we
cannot escape this effect with this test. You can try
plotting $\theta^n$ for
larger and larger values of $n$ to see this.
### Majority Vote Test
Due to the
problems with the detection probability in the all-heads test, maybe
we can
think of another test that will have the performance we want? Suppose we
reject
$H_0$ if the majority of the observations are heads. Then, using the
same
reasoning as above, we have
$$
\beta(\theta) = \sum_{k=3}^5 \binom{5}{k} \theta^k(1-\theta)^{5-k}
$$
[Figure](#fig:Hypothesis_testing_002) shows the power function
for both the
majority vote and the all-heads tests.
```python
fig,ax=subplots()
fig.set_size_inches((6,3))
from sympy.abc import theta,k # get some variable symbols
import sympy as S
xi = np.linspace(0,1,50)
expr=S.Sum(S.binomial(5,k)*theta**(k)*(1-theta)**(5-k),(k,3,5)).doit()
_=ax.plot(xi, (xi)**5,'-k',label='all heads')
_=ax.plot(xi, S.lambdify(theta,expr)(xi),'--k',label='majority vote')
_=ax.plot(0.5, (0.5)**5,'ko')
_=ax.plot(0.5, S.lambdify(theta,expr)(0.5),'ko')
_=ax.set_xlabel(r'$\theta$',fontsize=22)
_=ax.legend(loc=0)
fig.tight_layout()
fig.savefig('fig-statistics/Hypothesis_Testing_002.png')
```
<!-- dom:FIGURE: [fig-statistics/Hypothesis_Testing_002.png, width=500
frac=0.85] Compares the power function for the all-heads test with that of the
majority-vote test. <div id="fig:Hypothesis_testing_002"></div> -->
<!-- begin
figure -->
<div id="fig:Hypothesis_testing_002"></div>
<p>Compares the power
function for the all-heads test with that of the majority-vote test.</p>
<!-- end figure -->
In this case, the new test has *size*
$$
\alpha = \sup_{\theta < \frac{1}{2}} \theta^{5} + 5 \theta^{4} \left(- \theta
+ 1\right) + 10 \theta^{3} \left(- \theta + 1\right)^{2} = \frac{1}{2}
$$
As before we only get to upwards of 90% for detection
probability only when the
underlying parameter $\theta > 0.75$.
Let's see what happens when we consider
more than five samples. For
example, let's suppose that we have $n=100$ samples
and we want to
vary the threshold for the majority vote test. For example, let's
have
a new test where we declare $H_1$ when $k=60$ out of the 100 trials
turns
out to be heads. What is the $\beta$ function in this case?
$$
\beta(\theta) = \sum_{k=60}^{100} \binom{100}{k} \theta^k(1-\theta)^{100-k}
$$
This is too complicated to write by hand, but the statistics module
in Sympy
has all the tools we need to compute this.
```python
from sympy.stats import P, Binomial
theta = S.symbols('theta',real=True)
X = Binomial('x',100,theta)
beta_function = P(X>60)
print (beta_function.subs(theta,0.5)) # alpha
print (beta_function.subs(theta,0.70))
```
0.0176001001088524
0.979011423996075
These results are much better than before because the $\beta$
function is much
steeper. If we declare $H_1$ when we observe 60 out of 100
trials are heads,
then we wrongly declare heads approximately 1.8% of the
time. Otherwise, if it
happens that the true value for $p>0.7$, we will
conclude correctly
approximately 97% of the time. A quick simulation can sanity
check these results
as shown below:
```python
from scipy import stats
rv=stats.bernoulli(0.5) # true p = 0.5
# number of false alarms ~ 0.018
print (sum(rv.rvs((1000,100)).sum(axis=1)>60)/1000.)
```
0.015
The above code is pretty dense so let's unpack it. In the first line, we use
the `scipy.stats` module to define the
Bernoulli random variable for the coin
flip. Then, we use the `rvs` method of
the variable to generate 1000 trials of
the experiment where each trial
consists of 100 coin flips. This generates a
$1000 \times 100$ matrix where the
rows are the individual trials and the
columns are the outcomes of each
respective set of 100 coin flips. The
`sum(axis=1)` part computes the sum across the
columns. Because the values of
the embedded matrix are only `1` or `0` this
gives us the count of flips that
are heads per row. The next `>60` part
computes the boolean 1000-long vector of
values that are bigger than 60. The
final `sum` adds these up. Again, because
the entries in the array are `True`
or `False` the `sum` computes the count of
times the number of heads has
exceeded 60 per 100 coin flips in each of 1000
trials. Then, dividing this
number by 1000 gives a quick approximation of false
alarm probability we
computed above for this case where the true value of
$p=0.5$.
## Receiver Operating Characteristic
Because the majority vote test
is a binary test, we can compute the *Receiver
Operating Characteristic* (ROC)
which is the graph of the $(P_{FA},
P_D)$. The term comes from radar systems but
is a very general method for
consolidating all of these issues into a single
graph. Let's consider a typical
signal processing example with two hypotheses.
In $H_0$, there is noise but no
signal present at the receiver,
$$
H_0 \colon X = \epsilon
$$
where $\epsilon \sim \mathcal{N}(0,\sigma^2)$ represents additive
noise. In the
alternative hypothesis, there is a deterministic signal at the receiver,
$$
H_1 \colon X = \mu + \epsilon
$$
Again, the problem is to choose between these two hypotheses. For
$H_0$, we
have $X \sim \mathcal{N}(0,\sigma^2)$ and for $H_1$, we have $ X \sim
\mathcal{N}(\mu,\sigma^2)$. Recall that we only observe values for $x$ and
must
pick either $H_0$ or $H_1$ from these observations. Thus, we need a
threshold,
$c$, to compare $x$ against in order to distinguish the two
hypotheses.
[Figure](#fig:Hypothesis_testing_003) shows the probability density
functions
under each of the hypotheses. The dark vertical line is the threshold
$c$. The
gray shaded area is the probability of detection, $P_D$ and the shaded
area is
the probability of false alarm, $P_{FA}$. The test evaluates every
observation
of $x$ and concludes $H_0$ if $x<c$ and $H_1$ otherwise.
<!-- dom:FIGURE: [fig-
statistics/Hypothesis_Testing_003.png, width=500 frac=0.85] The two density
functions for the $H_0$ and $H_1$ hypotheses. The shaded gray area is the
detection probability and the shaded dark gray area is the probability of false
alarm. The vertical line is the decision threshold. <div
id="fig:Hypothesis_testing_003"></div> -->
<!-- begin figure -->
<div
id="fig:Hypothesis_testing_003"></div>
<p>The two density functions for the
$H_0$ and $H_1$ hypotheses. The shaded gray area is the detection probability
and the shaded dark gray area is the probability of false alarm. The vertical
line is the decision threshold.</p>
<!-- end figure -->
**Programming Tip.**
The shading shown in [Figure](#fig:Hypothesis_testing_003)
comes from
Matplotlib's `fill_between` function. This function has a `where`
keyword
argument to specify which part of the plot to apply shading with
specified
`color` keyword argument. Note there is also a `fill_betweenx`
function that
fills horizontally. The `text` function can place formatted
text
anywhere in the plot and can utilize basic \LaTeX{} formatting.
As we slide
the threshold left and right along the horizontal axis, we naturally change the
corresponding areas under
each of the curves shown in
[Figure](#fig:Hypothesis_testing_003) and thereby
change the values of $P_D$ and
$P_{FA}$. The contour that emerges from sweeping
the threshold this way is the
ROC as shown in [Figure](#fig:Hypothesis_testing_004). This figure also shows
the diagonal line which
corresponds to making decisions based on the flip of a
fair coin. Any
meaningful test must do better than coin flipping so the more the
ROC bows up
to the top left corner of the graph, the better. Sometimes ROCs are
quantified
into a single number called the *area under the curve* (AUC), which
varies from
0.5 to 1.0 as shown. In our example, what separates the two
probability density
functions is the value of $\mu$. In a real situation, this
would be determined
by signal processing methods that include many complicated
trade-offs. The key
idea is that whatever those trade-offs are, the test itself
boils down to the
separation between these two density functions --- good tests
separate the two
density functions and bad tests do not. Indeed, when there is
no separation, we
arrive at the diagonal-line coin-flipping situation we just
discussed.
What values for $P_D$ and $P_{FA}$ are considered *acceptable*
depends on the
application. For example, suppose you are testing for a fatal
disease. It could
be that you are willing to except a relatively high $P_{FA}$
value if that
corresponds to a good $P_D$ because the test is relatively cheap
to administer
compared to the alternative of missing a detection. On the other
hand,
may be a false alarm triggers an expensive response, so that minimizing
these alarms is more important than potentially missing a detection. These
trade-offs can only be determined by the application and design factors.
<!--
dom:FIGURE: [fig-statistics/Hypothesis_Testing_004.png, width=500 frac=0.65] The
Receiver Operating Characteristic (ROC) corresponding to
[Figure](#fig:Hypothesis_testing_003). <div
id="fig:Hypothesis_testing_004"></div> -->
<!-- begin figure -->
<div
id="fig:Hypothesis_testing_004"></div>
<p>The Receiver Operating Characteristic
(ROC) corresponding to [Figure](#fig:Hypothesis_testing_003).</p>
<!-- end figure -->
##
P-Values
There are a lot of moving parts in hypothesis testing. What we need
is
a way to consolidate the findings. The idea is that we want to find
the minimum
level at which the test rejects $H_0$. Thus, the p-value
is the probability,
under $H_0$, that the test-statistic is at least
as extreme as what was actually
observed. Informally, this means
that smaller values imply that $H_0$ should be
rejected, although
this doesn't mean that large values imply that $H_0$ should
be
retained. This is because a large p-value can arise from either $H_0$
being
true or the test having low statistical power.
If $H_0$ is true, the p-value is
uniformly distributed in the interval $(0,1)$.
If $H_1$ is true, the
distribution of the p-value will concentrate closer to
zero. For continuous
distributions, this can be proven rigorously and implies
that if we reject $H_0$
when the corresponding p-value is less than $\alpha$,
then the probability of a
false alarm is $\alpha$. Perhaps it helps to
formalize this a bit before
computing it. Suppose $\tau(X)$ is a test
statistic that rejects $H_0$ as it
gets bigger. Then, for each sample $x$,
corresponding to the data we actually
have on-hand, we define
$$
p(x) = \sup_{\theta \in \Theta_0} \mathbb{P}_{\theta}(\tau(X) > \tau(x))
$$
This equation states that the supremum (i.e., maximum)
probability that the
test statistic, $\tau(X)$, exceeds the value for
the test statistic on this
particular data ($\tau(x)$) over the
domain $\Theta_0$ is defined as the
p-value. Thus, this embodies a
worst-case scenario over all values of $\theta$.
Here's one way to think about this. Suppose you rejected $H_0$, and someone
says
that you just got *lucky* and somehow just drew data that happened to
correspond
to a rejection of $H_0$. What p-values provide is a way to address
this by
capturing the odds of just a favorable data-draw. Thus, suppose that
your
p-value is 0.05. Then, what you are showing is that the odds of just
drawing
that data sample, given $H_0$ is in force, is just 5%. This means that
there's a
5% chance that you somehow lucked out and got a favorable draw of
data.
Let's
make this concrete with an example. Given, the majority-vote rule above,
suppose
we actually do observe three of five heads. Given the $H_0$, the
probability of
observing this event is the following:
$$
p(x) =\sup_{\theta \in \Theta_0} \sum_{k=3}^5\binom{5}{k}
\theta^k(1-\theta)^{5-k} = \frac{1}{2}
$$
For the all-heads test, the corresponding computation is the following:
$$
p(x) =\sup_{\theta \in \Theta_0} \theta^5 = \frac{1}{2^5} = 0.03125
$$
From just looking at these p-values, you might get the feeling that the second
test is better, but we still have the same detection probability issues we
discussed above; so, p-values help in summarizing some aspects of our
hypothesis
testing, but they do *not* summarize all the salient aspects of the
*entire*
situation.
## Test Statistics
As we have seen, it is difficult to derive good
test statistics for hypothesis
testing without a systematic process. The
Neyman-Pearson Test is derived from
fixing a false-alarm value ($\alpha$) and
then maximizing the detection
probability. This results in the Neyman-Pearson
Test,
$$
L(\mathbf{x}) = \frac{f_{X|H_1}(\mathbf{x})}{f_{X|H_0}(\mathbf{x})}
\stackrel[H_0]{H_1}{\gtrless} \gamma
$$
where $L$ is the likelihood ratio and where the threshold
$\gamma$ is chosen
such that
$$
\int_{x:L(\mathbf{x})>\gamma} f_{X|H_0}(\mathbf{x}) d\mathbf{x}=\alpha
$$
The Neyman-Pearson Test is one of a family of tests that use
the likelihood
ratio.
**Example.** Suppose we have a receiver and we want to distinguish
whether just noise ($H_0$) or signal pluse noise ($H_1$) is received.
For the
noise-only case, we have $x\sim \mathcal{N}(0,1)$ and for the
signal pluse
noise case we have $x\sim \mathcal{N}(1,1)$. In other
words, the mean of the
distribution shifts in the presence of the
signal. This is a very common problem
in signal processing and
communications. The Neyman-Pearson Test then boils down
to the
following,
$$
L(x)= e^{-\frac{1}{2}+x}\stackrel[H_0]{H_1}{\gtrless}\gamma
$$
Now we have to find the threshold $\gamma$ that solves the
maximization problem
that characterizes the Neyman-Pearson Test. Taking
the natural logarithm and
re-arranging gives,
$$
x\stackrel[H_0]{H_1}{\gtrless} \frac{1}{2}+\log\gamma
$$
The next step is find $\gamma$ corresponding to the desired
$\alpha$ by
computing it from the following,
$$
\int_{1/2+\log\gamma}^{\infty} f_{X|H_0}(x)dx = \alpha
$$
For example, taking $\alpha=1/100$, gives
$\gamma\approx 6.21$. To summarize
the test in this case, we have,
$$
x\stackrel[H_0]{H_1}{\gtrless} 2.32
$$
Thus, if we measure $X$ and see that its value
exceeds the threshold above, we
declare $H_1$ and otherwise
declare $H_0$. The following code shows how to
solve
this example using Sympy and Scipy. First, we
set up the likelihood ratio,
```python
import sympy as S
from sympy import stats
s = stats.Normal('s',1,1) # signal+noise
n = stats.Normal('n',0,1) # noise
x = S.symbols('x',real=True)
L = stats.density(s)(x)/stats.density(n)(x)
```
Next, to find the $\gamma$ value,
```python
g = S.symbols('g',positive=True) # define gamma
v=S.integrate(stats.density(n)(x),
(x,S.Rational(1,2)+S.log(g),S.oo))
```
**Programming Tip.**
Providing additional information regarding the Sympy
variable by using the
keyword argument `positive=True` helps the internal
simplification algorithms
work faster and better. This is especially useful when
dealing with complicated
integrals that involve special functions. Furthermore,
note that we used the
`Rational` function to define the `1/2` fraction, which is
another way of
providing hints to Sympy. Otherwise, it's possible that the
floating-point
representation of the fraction could disguise the simple
fraction and
thereby miss internal simplification opportunities.
We want to
solve for `g` in the above expression. Sympy has some
built-in numerical solvers
as in the following,
```python
print (S.nsolve(v-0.01,3.0)) # approx 6.21
```
6.21116124253284
Note that in this situation it is better to use the numerical
solvers because
Sympy `solve` may grind along for a long time to
resolve this.
### Generalized
Likelihood Ratio Test
The likelihood ratio test can be generalized using the
following statistic,
$$
\Lambda(\mathbf{x})= \frac{\sup_{\theta\in\Theta_0}
L(\theta)}{\sup_{\theta\in\Theta}
L(\theta)}=\frac{L(\hat{\theta}_0)}{L(\hat{\theta})}
$$
where $\hat{\theta}_0$ maximizes $L(\theta)$ subject to
$\theta\in\Theta_0$ and
$\hat{\theta}$ is the maximum likelihood estimator.
The intuition behind this
generalization of the Likelihood Ratio Test is that
the denomimator is the usual
maximum likelihood estimator and the numerator is
the maximum likelihood
estimator, but over a restricted domain ($\Theta_0$).
This means that the ratio
is always less than unity because the maximum
likelihood estimator over the
entire space will always be at least as maximal
as that over the more restricted
space. When this $\Lambda$ ratio gets small
enough, it means that the maximum
likelihood estimator over the entire domain
($\Theta$) is larger which means
that it is safe to reject the null hypothesis
$H_0$. The tricky part is that
the statistical distribution of $\Lambda$ is
usually eye-wateringly difficult.
Fortunately, Wilks Theorem says that with
sufficiently large $n$, the
distribution of $-2\log\Lambda$ is approximately
chi-square with $r-r_0$ degrees
of freedom, where $r$ is the number of free
parameters for $\Theta$ and $r_0$ is
the number of free parameters in
$\Theta_0$. With this result, if we want an
approximate test at level
$\alpha$, we can reject $H_0$ when $-2\log\Lambda \ge
\chi^2_{r-r_0}(\alpha)$
where $\chi^2_{r-r_0}(\alpha)$ denotes the $1-\alpha$
quantile of the
$\chi^2_{r-r_0}$ chi-square distribution. However, the problem
with this
result is that there is no definite way of knowing how big $n$ should
be. The
advantage of this generalized likelihood ratio test is that it
can test
multiple hypotheses simultaneously, as illustrated
in the following example.
**Example.** Let's return to our coin-flipping example, except now we have
three
different coins. The likelihood function is then,
$$
L(p_1,p_2,p_3) =
\texttt{binom}(k_1;n_1,p_1)\texttt{binom}(k_2;n_2,p_2)\texttt{binom}(k_3;n_3,p_3)
$$
where $\texttt{binom}$ is the binomial distribution with
the given parameters.
For example,
$$
\texttt{binom}(k;n,p) =\sum_{k=0}^n \binom{n}{k} p^k(1-p)^{n-k}
$$
The null hypothesis is that all three coins have the
same probability of
heads, $H_0:p=p_1=p_2=p_3$. The alternative hypothesis is
that at least one of
these probabilites is different. Let's consider the
numerator of the $\Lambda$
first, which will give us the maximum likelihood
estimator of $p$. Because the
null hypothesis is that all the $p$ values are
equal, we can just treat this as
one big binomial distribution with
$n=n_1+n_2+n_3$ and $k=k_1+k_2+k_3$ is the
total number of heads observed for
any coin. Thus, under the null hypothesis,
the distribution of $k$ is binomial
with parameters $n$ and $p$. Now, what is
the maximum likelihood estimator for
this distribution? We have worked this
problem before and have the following,
$$
\hat{p}_0= \frac{k}{n}
$$
In other words, the maximum likelihood estimator under the null
hypothesis is
the proportion of ones observed in the sequence of $n$ trials
total. Now, we
have to substitute this in for the likelihood under the null
hypothesis to
finish the numerator of $\Lambda$,
$$
L(\hat{p}_0,\hat{p}_0,\hat{p}_0) =
\texttt{binom}(k_1;n_1,\hat{p}_0)\texttt{binom}(k_2;n_2,\hat{p}_0)\texttt{binom}(k_3;n_3,\hat{p}_0)
$$
For the denomimator of $\Lambda$, which represents the case of maximizing over
the entire space, the maximum likelihood estimator for each separate binomial
distribution is likewise,
$$
\hat{p}_i= \frac{k_i}{n_i}
$$
which makes the likelihood in the denominator the following,
$$
L(\hat{p}_1,\hat{p}_2,\hat{p}_3) =
\texttt{binom}(k_1;n_1,\hat{p}_1)\texttt{binom}(k_2;n_2,\hat{p}_2)\texttt{binom}(k_3;n_3,\hat{p}_3)
$$
for each of the $i\in \lbrace 1,2,3 \rbrace$ binomial distributions. Then, the
$\Lambda$ statistic is then the following,
$$
\Lambda(k_1,k_2,k_3) =
\frac{L(\hat{p}_0,\hat{p}_0,\hat{p}_0)}{L(\hat{p}_1,\hat{p}_2,\hat{p}_3)}
$$
Wilks theorems states that $-2\log\Lambda$ is chi-square
distributed. We can
compute this example with the statistics tools in Sympy and
Scipy.
```python
from scipy.stats import binom, chi2
import numpy as np
# some sample parameters
p0,p1,p2 = 0.3,0.4,0.5
n0,n1,n2 = 50,180,200
brvs= [ binom(i,j) for i,j in zip((n0,n1,n2),(p0,p1,p2))]
def gen_sample(n=1):
'generate samples from separate binomial distributions'
if n==1:
return [i.rvs() for i in brvs]
else:
return [gen_sample() for k in range(n)]
```
**Programming Tip.**
Note the recursion in the definition of the `gen_sample`
function where a
conditional clause of the function calls itself. This is a
quick way to reusing
code and generating vectorized output. Using `np.vectorize`
is another way, but
the code is simple enough in this case to use the
conditional clause. In
Python, it is generally bad for performance to have code
with nested recursion
because of how the stack frames are managed. However,
here we are only
recursing once so this is not an issue.
Next, we compute
the logarithm of the numerator of the $\Lambda$
statistic,
```python
np.random.seed(1234)
```
```python
k0,k1,k2 = gen_sample()
print (k0,k1,k2)
pH0 = sum((k0,k1,k2))/sum((n0,n1,n2))
numer = np.sum([np.log(binom(ni,pH0).pmf(ki))
for ni,ki in
zip((n0,n1,n2),(k0,k1,k2))])
print (numer)
```
12 68 103
-15.545863836567879
Note that we used the null hypothesis estimate for the $\hat{p}_0$.
Likewise,
for the logarithm of the denominator we have the following,
```python
denom = np.sum([np.log(binom(ni,pi).pmf(ki))
for ni,ki,pi in
zip((n0,n1,n2),(k0,k1,k2),(p0,p1,p2))])
print (denom)
```
-8.424106480792402
Now, we can compute the logarithm of the $\Lambda$ statistic as
follows and see
what the corresponding value is according to Wilks theorem,
```python
chsq=chi2(2)
logLambda =-2*(numer-denom)
print (logLambda)
print (1- chsq.cdf(logLambda))
```
14.243514711550954
0.0008073467083287156
Because the value reported above is less than the 5% significance
level, we
reject the null hypothesis that all the coins have the same
probability of
heads. Note that there are two degrees of freedom because the
difference in the
number of parameters between the null hypothesis ($p$) and
the alternative
($p_1,p_2,p_3$) is two. We can build a quick Monte
Carlo simulation to check the
probability of detection for this example using
the following code, which is
just a combination of the last few code blocks,
```python
c= chsq.isf(.05) # 5% significance level
out = []
for k0,k1,k2 in gen_sample(100):
pH0 = sum((k0,k1,k2))/sum((n0,n1,n2))
numer = np.sum([np.log(binom(ni,pH0).pmf(ki))
for ni,ki in
zip((n0,n1,n2),(k0,k1,k2))])
denom = np.sum([np.log(binom(ni,pi).pmf(ki))
for ni,ki,pi in
zip((n0,n1,n2),(k0,k1,k2),(p0,p1,p2))])
out.append(-2*(numer-denom)>c)
print (np.mean(out)) # estimated probability of detection
```
0.59
The above simulation shows the estimated probability of
detection, for this set
of example parameters. This relative low
probability of detection means that
while the test is unlikely (i.e.,
at the 5% significance level) to mistakenly
pick the null hypothesis,
it is likewise missing many of the $H_1$ cases (i.e.,
low probability
of detection). The trade-off between which is more important is
up to
the particular context of the problem. In some situations, we may
prefer
additional false alarms in exchange for missing fewer $H_1$
cases.
###
Permutation Test
<!-- p 475, Essential_Statistical_Inference_Boos.pdf -->
<!--
p. 35, Applied_adaptive_statistical_methods_OGorman.pdf -->
<!-- p. 80,
Introduction_to_Statistics_Through_Resampling_Methods_and_R_Good.pdf -->
<!-- p.
104, Statistical_inference_for_data_science_Caffo.pdf -->
<!-- p. 178, All of
statistics -->
The Permutation Test is good way to test whether or not
samples
samples come from the same distribution. For example, suppose that
$$
X_1, X_2, \ldots, X_m \sim F
$$
and also,
$$
Y_1, Y_2, \ldots, Y_n \sim G
$$
That is, $Y_i$ and $X_i$ come from different distributions. Suppose
we have
some test statistic, for example
$$
T(X_1,\ldots,X_m,Y_1,\ldots,Y_n) = \vert\overline{X}-\overline{Y}\vert
$$
Under the null hypothesis for which $F=G$, any of the
$(n+m)!$ permutations are
equally likely. Thus, suppose for
each of the $(n+m)!$ permutations, we have the
computed
statistic,
$$
\lbrace T_1,T_2,\ldots,T_{(n+m)!} \rbrace
$$
Then, under the null hypothesis, each of these values is equally
likely. The
distribution of $T$ under the null hypothesis is the *permutation
distribution*
that puts weight $1/(n+m)!$ on each $T$-value. Suppose $t_o$ is
the observed
value of the test statistic and assume that large $T$ rejects the
null
hypothesis, then the p-value for the permutation test is the following,
$$
P(T>t_o)= \frac{1}{(n+m)!} \sum_{j=1}^{(n+m)!} I(T_j>t_o)
$$
where $I()$ is the indicator function. For large $(n+m)!$, we can
sample
randomly from the set of all permutations to estimate this p-value.
**Example.** Let's return to our coin-flipping example from last time, but
now
we have only two coins. The hypothesis is that both coins
have the same
probability of heads. We can use the built-in
function in Numpy to compute the
random permutations.
```python
x=binom(10,0.3).rvs(5) # p=0.3
y=binom(10,0.5).rvs(3) # p=0.5
z = np.hstack([x,y]) # combine into one array
t_o = abs(x.mean()-y.mean())
out = [] # output container
for k in range(1000):
perm = np.random.permutation(z)
T=abs(perm[:len(x)].mean()-perm[len(x):].mean())
out.append((T>t_o))
print ('p-value = ', np.mean(out))
```
p-value = 0.0
Note that the size of total permutation space is
$8!=40320$ so we are taking
relatively few (i.e., 100) random
permutations from this space.
### Wald Test
The Wald Test is an asympotic test. Suppose we have $H_0:\theta=\theta_0$ and
otherwise $H_1:\theta\ne\theta_0$, the corresponding statistic is defined as
the
following,
$$
W=\frac{\hat{\theta}_n-\theta_0}{\texttt{se}}
$$
where $\hat{\theta}$ is the maximum likelihood estimator and
$\texttt{se}$ is
the standard error,
$$
\texttt{se} = \sqrt{\mathbb{V}(\hat{\theta}_n)}
$$
Under general conditions, $W\overset{d}{\to} \mathcal{N}(0,1)$.
Thus, an
asympotic test at level $\alpha$ rejects when $\vert W\vert>
z_{\alpha/2}$ where
$z_{\alpha/2}$ corresponds to $\mathbb{P}(\vert
Z\vert>z_{\alpha/2})=\alpha$
with $Z \sim \mathcal{N}(0,1)$. For our favorite
coin-flipping example, if
$H_0:\theta=\theta_0$, then
$$
W = \frac{\hat{\theta}-\theta_0}{\sqrt{\hat{\theta}(1-\hat{\theta})/n}}
$$
We can simulate this using the following code at the usual
5% significance
level,
```python
from scipy import stats
theta0 = 0.5 # H0
k=np.random.binomial(1000,0.3)
theta_hat = k/1000. # MLE
W = (theta_hat-theta0)/np.sqrt(theta_hat*(1-theta_hat)/1000)
c = stats.norm().isf(0.05/2) # z_{alpha/2}
print (abs(W)>c) # if true, reject H0
```
True
This rejects $H_0$ because the true $\theta=0.3$ and the null hypothesis
is
that $\theta=0.5$. Note that $n=1000$ in this case which puts us well inside
the
asympotic range of the result. We can re-do this example to estimate
the
detection probability for this example as in the following code,
```python
theta0 = 0.5 # H0
c = stats.norm().isf(0.05/2.) # z_{alpha/2}
out = []
for i in range(100):
k=np.random.binomial(1000,0.3)
theta_hat = k/1000. # MLE
W = (theta_hat-theta0)/np.sqrt(theta_hat*(1-theta_hat)/1000.)
out.append(abs(W)>c) # if true, reject H0
print (np.mean(out)) # detection probability
```
1.0
## Testing Multiple Hypotheses
Thus far, we have focused primarily on two
competing hypotheses. Now, we
consider multiple comparisons. The general
situation is the following. We test
the null hypothesis against a sequence of
$n$ competing hypotheses $H_k$. We
obtain p-values for each hypothesis so now
we have multiple p-values to
consider $\lbrace p_k \rbrace$. To boil this
sequence down to a single
criterion, we can make the following argument. Given
$n$ independent hypotheses
that are all untrue, the probability of getting at
least one false alarm is the
following,
$$
P_{FA} = 1-(1-p_0)^n
$$
where $p_0$ is the individual p-value threshold (say, 0.05). The
problem here
is that $P_{FA}\rightarrow 1$ as $n\rightarrow\infty$. If we want
to make many
comparisons at once and control the overall false alarm rate the
overall p-value
should be computed under the assumption that none of the
competing hypotheses is
valid. The most common way to address this is with the
Bonferroni correction
which says that the individual significance level should
be reduced to $p/n$.
Obviously, this makes it much harder to declare
significance for any particular
hypothesis. The natural consequence of this
conservative restriction is to
reduce the statistical power of the experiment,
thus making it more likely the
true effects will be missed.
In 1995, Benjamini and Hochberg devised a simple
method that tells which
p-values are statistically significant. The procedure is
to sort the list of
p-values in ascending order, choose a false-discovery rate
(say, $q$), and then
find the largest p-value in the sorted list such that $p_k
\le k q/n$, where
$k$ is the p-value's position in the sorted list. Finally,
declare that $p_k$
value and all the others less than it statistically
significant. This procedure
guarantees that the proportion of false-positives is
less than $q$ (on
average). The Benjamini-Hochberg procedure (and its
derivatives) is fast and
effective and is widely used for testing hundreds of
primarily false hypotheses
when studying genetics or diseases. Additionally,
this
procedure provides better statistical power than the Bonferroni correction.
<!-- TODO: Fisher transformation -->
<!-- TODO: Cohen's D test for effect size
-->
<!-- TODO: add log-linear transform -->
<!-- TODO: add Fisher transform -->
<!-- TODO: Log-Linear Models -->
## Fisher Exact Test
<!-- # #ifdef SINGLE -->
<!-- TITLE: Fisher Exact Test -->
<!-- AUTHOR: Jose Unpingco -->
<!-- DATE:
today -->
<!-- # #endif -->
<!-- References -->
<!-- ------------ -->
<!-- ..
[freeman-halton] Freeman, G. H., and John H. Halton. "Note on an exact -->
<!--
treatment of contingency, goodness of fit and other problems of -->
<!--
significance." Biometrika (1951): 141-149. -->
<!-- Equation labels as ordinary links -->
<div id="tab:contingencyTable"></div>
$$
\begin{table}[]
\centering
\caption{Example Contingency Table}
\label{tab:contingencyTable} \tag{2}
\begin{tabular}{lllll}
\cline{1-4}
\multicolumn{1}{|l|}{} & \multicolumn{1}{l|}{Infection} &
\multicolumn{1}{l|}{No infection} & \multicolumn{1}{l|}{Total} & \\ \cline{1-4}
\multicolumn{1}{|l|}{Male} & \multicolumn{1}{c|}{13} &
\multicolumn{1}{c|}{11} & \multicolumn{1}{c|}{24} & \\ \cline{1-4}
\multicolumn{1}{|l|}{Female} & \multicolumn{1}{c|}{12} &
\multicolumn{1}{c|}{1} & \multicolumn{1}{c|}{13} & \\ \cline{1-4}
\multicolumn{1}{|l|}{Total} & \multicolumn{1}{c|}{25} &
\multicolumn{1}{c|}{12} & \multicolumn{1}{c|}{37} & \\ \cline{1-4}
\end{tabular}
\end{table}
$$
Contingency tables represent the partitioning of a sample population of two
categories between two different classifications as shown in the following
Table
[2](#tab:contingencyTable). The question is whether or not the observed
table
corresponds to a random partition of the sample population, constrained
by the
marginal sums. Note that because this is a two-by-two table, a change in
any of
the table entries automatically affects all of the other terms because
of the
row and column sum constraints. This means that equivalent questions
like "Under
a random partition, what is the probability that a particular
table entry is at
least as large as a given value?" can be meaningfully posed.
<!-- #`` -->
The Fisher Exact Test addresses this question. The idea is to compute the
probability of a particular entry of the table, conditioned upon the marginal
row and column sums,
$$
\mathbb{P}(X_{i,j}\vert r_1,r_2,c_1,c_2)
$$
where $X_{i,j}$ is $(i,j)$ table entry, $r_1$ represents the sum of
the first
row, $r_2$ represents the sum of the second row, $c_1$ represents the
sum of the
first column, and $c_2$ is the sum of the second column. This
probability is
given by the *hypergeometric distribution*. Recall that the
hypergeometric
distribution gives the probability of sampling (without
replacement) $k$ items
from a population of $N$ items consisting of exactly two
different kinds of
items,
$$
\mathbb{P}(X=k) = \frac{\binom{K}{k}\binom{N-K}{n-k}}{\binom{N}{n}}
$$
where $N$ is the population size, $K$ is the total number of possible
favorable
draws, $n$ is the number of draws, and $k$ is the number of observed
favorable
draws. With the corresponding identification of variables, the
hypergeometric
distribution gives the desired conditional probability: $K=r_1,
k=x, n= c_1,
N=r_1+r_2$.
In the example of the Table [2](#tab:contingencyTable), the
probability for
$x=13$ male infections among a population of $r_1=24$ males in a
total
population of $c_1=25$ infected persons, including $r_2=13$ females. The
`scipy.stats` module has the Fisher Exact Test implemented as shown below,
```python
import scipy.stats
table = [[13,11],[12,1]]
odds_ratio, p_value=scipy.stats.fisher_exact(table)
print(p_value)
```
0.02718387758955712
The default for `scipy.stats.fisher_exact` is the two-sided
test. The following
result is for the `less` option,
```python
import scipy.stats
odds_ratio, p_value=scipy.stats.fisher_exact(table,alternative='less')
print(p_value)
```
0.018976707519532877
This means that the p-value is computed by summing over the
probabilities of
contingency tables that are *less* extreme than the
given table. To undertand
what this means, we can use
the `scipy.stats.hypergeom` function to compute the
probabilities of
these with the number of infected men is less than or equal to
13.
```python
hg = scipy.stats.hypergeom(37, 24, 25)
probs = [(hg.pmf(i)) for i in range(14)]
print (probs)
print(sum(probs))
```
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0014597467322717626, 0.017516960787261115]
0.018976707519532877
This is the same as the prior p-value result we obtained from
`scipy.stats.fisher_exact`. Another option is `greater` which derives from the
following analogous summation,
```python
odds_ratio, p_value=scipy.stats.fisher_exact(table,alternative='greater')
probs = [hg.pmf(i) for i in range(13,25)]
print(probs)
print(p_value)
print(sum(probs))
```
[0.017516960787261115, 0.08257995799708828, 0.2018621195484381, 0.28386860561499044, 0.24045340710916852, 0.12467954442697629, 0.039372487713781906, 0.00738234144633414, 0.0007812001530512284, 4.261091743915799e-05, 1.0105355914424832e-06, 7.017608273906114e-09]
0.9985402532677288
0.9985402532677288
Finally, the two-sided version excludes those individual
table probabilities
that are less that of the given table
```python
_,p_value=scipy.stats.fisher_exact(table)
probs = [ hg.pmf(i) for i in range(25) ]
print(sum(i for i in probs if i<= hg.pmf(13)))
print(p_value)
```
0.027183877589557117
0.02718387758955712
Thus, for this particular contingency table, we
could reasonably conclude that
13 infected males in this total
population is statistically significant with a
p-value less than
five percent.
Performing this kind of analysis for tables
larger than `2x2` easily becomes
computationally challenging due to the nature
of the underlying combinatorics and
usually requires specialized
approximations.
In this section, we discussed the structure of statistical
hypothesis testing
and defined the various terms that are commonly used for
this process, along
with the illustrations of what they mean in our running
coin-flipping example.
From an engineering standpoint, hypothesis testing is not
as common as
confidence-intervals and point estimates. On the other hand,
hypothesis testing
is very common in social and medical science, where one must
deal with
practical constraints that may limit the sample size or other aspects
of the
hypothesis testing rubric. In engineering, we can usually have much more
control over the samples and models we employ because they are typically
inanimate objects that can be measured repeatedly and consistently. This is
obviously not so with human studies, which generally have other ethical and
legal considerations.
|
lemma homeomorphism_compose: assumes "homeomorphism S T f g" "homeomorphism T U h k" shows "homeomorphism S U (h o f) (g o k)" |
lemma fract_poly_mult [simp]: "fract_poly (p * q) = fract_poly p * fract_poly q" |
State Before: B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) State After: B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) Tactic: let f₁ : TotalSpace (E₁ ×ᵇ E₂) → TotalSpace E₁ × TotalSpace E₂ :=
fun p ↦ ((⟨p.1, p.2.1⟩ : TotalSpace E₁), (⟨p.1, p.2.2⟩ : TotalSpace E₂)) State Before: B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) State After: B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) Tactic: let f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p ↦ ⟨e₁ p.1, e₂ p.2⟩ State Before: B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) State After: B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) Tactic: let f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p ↦ ⟨p.1.1, p.1.2, p.2.2⟩ State Before: B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) State After: B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) Tactic: have hf₁ : Continuous f₁ := (Prod.inducing_diag E₁ E₂).continuous State Before: B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) State After: B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) Tactic: have hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source) :=
e₁.toLocalHomeomorph.continuousOn.prod_map e₂.toLocalHomeomorph.continuousOn State Before: B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) State After: B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) Tactic: have hf₃ : Continuous f₃ :=
(continuous_fst.comp continuous_fst).prod_mk (continuous_snd.prod_map continuous_snd) State Before: B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) State After: case refine'_1
B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
⊢ MapsTo f₁ (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) (e₁.source ×ˢ e₂.source)
case refine'_2
B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
⊢ EqOn (toFun' e₁ e₂) ((f₃ ∘ f₂) ∘ f₁) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) Tactic: refine' ((hf₃.comp_continuousOn hf₂).comp hf₁.continuousOn _).congr _ State Before: case refine'_2
B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
⊢ EqOn (toFun' e₁ e₂) ((f₃ ∘ f₂) ∘ f₁) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) State After: case refine'_2.mk.mk.intro
B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
b : B
v₁ : E₁ b
v₂ : E₂ b
hb₁ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₁.baseSet
right✝ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₂.baseSet
⊢ toFun' e₁ e₂ { fst := b, snd := (v₁, v₂) } = ((f₃ ∘ f₂) ∘ f₁) { fst := b, snd := (v₁, v₂) } Tactic: rintro ⟨b, v₁, v₂⟩ ⟨hb₁, _⟩ State Before: case refine'_2.mk.mk.intro
B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
b : B
v₁ : E₁ b
v₂ : E₂ b
hb₁ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₁.baseSet
right✝ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₂.baseSet
⊢ toFun' e₁ e₂ { fst := b, snd := (v₁, v₂) } = ((f₃ ∘ f₂) ∘ f₁) { fst := b, snd := (v₁, v₂) } State After: case refine'_2.mk.mk.intro
B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
b : B
v₁ : E₁ b
v₂ : E₂ b
hb₁ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₁.baseSet
right✝ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₂.baseSet
⊢ b = (↑e₁ { fst := b, snd := v₁ }).fst Tactic: simp only [Prod.toFun', Prod.mk.inj_iff, Function.comp_apply, and_true_iff] State Before: case refine'_2.mk.mk.intro
B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
b : B
v₁ : E₁ b
v₂ : E₂ b
hb₁ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₁.baseSet
right✝ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₂.baseSet
⊢ b = (↑e₁ { fst := b, snd := v₁ }).fst State After: case refine'_2.mk.mk.intro
B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
b : B
v₁ : E₁ b
v₂ : E₂ b
hb₁ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₁.baseSet
right✝ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₂.baseSet
⊢ { fst := b, snd := v₁ } ∈ e₁.source Tactic: rw [e₁.coe_fst] State Before: case refine'_2.mk.mk.intro
B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
b : B
v₁ : E₁ b
v₂ : E₂ b
hb₁ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₁.baseSet
right✝ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₂.baseSet
⊢ { fst := b, snd := v₁ } ∈ e₁.source State After: case refine'_2.mk.mk.intro
B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
b : B
v₁ : E₁ b
v₂ : E₂ b
hb₁ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₁.baseSet
right✝ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₂.baseSet
⊢ TotalSpace.proj { fst := b, snd := v₁ } ∈ e₁.baseSet Tactic: rw [e₁.source_eq, mem_preimage] State Before: case refine'_2.mk.mk.intro
B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
b : B
v₁ : E₁ b
v₂ : E₂ b
hb₁ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₁.baseSet
right✝ : TotalSpace.proj { fst := b, snd := (v₁, v₂) } ∈ e₂.baseSet
⊢ TotalSpace.proj { fst := b, snd := v₁ } ∈ e₁.baseSet State After: no goals Tactic: exact hb₁ State Before: case refine'_1
B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
⊢ MapsTo f₁ (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) (e₁.source ×ˢ e₂.source) State After: case refine'_1
B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
⊢ MapsTo f₁ (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet))
((TotalSpace.proj ⁻¹' e₁.baseSet) ×ˢ (TotalSpace.proj ⁻¹' e₂.baseSet)) Tactic: rw [e₁.source_eq, e₂.source_eq] State Before: case refine'_1
B : Type u_3
inst✝⁴ : TopologicalSpace B
F₁ : Type u_5
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_2
inst✝² : TopologicalSpace (TotalSpace E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_1
inst✝ : TopologicalSpace (TotalSpace E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace fun x => E₁ x × E₂ x) → TotalSpace E₁ × TotalSpace E₂ :=
fun p => ({ fst := p.fst, snd := p.snd.fst }, { fst := p.fst, snd := p.snd.snd })
f₂ : TotalSpace E₁ × TotalSpace E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
⊢ MapsTo f₁ (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet))
((TotalSpace.proj ⁻¹' e₁.baseSet) ×ˢ (TotalSpace.proj ⁻¹' e₂.baseSet)) State After: no goals Tactic: exact mapsTo_preimage _ _ |
import Data.Either
import Data.List
import Data.Maybe
import Data.String
import System.File
increases : List Int -> Int
increases [] = 0
increases (x :: []) = 0
increases (x :: (y :: xs)) = (if x < y then 1 else 0) + increases (y ::xs)
parseLines : (String -> Maybe a) -> String -> List a
parseLines f s = catMaybes $ f <$> lines s
run : String -> IO ()
run s = do let l = parseLines parseInteger {a=Int} s
putStrLn $ show $ increases l
main : IO ()
main = do Right s <- readFile "input.txt"
| Left err => putStrLn $ show err
run s
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.