text
stringlengths 0
3.34M
|
---|
State Before: V : Type (u + 1)
inst✝ : LargeCategory V
G : MonCat
A : Action V G
⊢ ↑A.ρ 1 = 𝟙 A.V State After: V : Type (u + 1)
inst✝ : LargeCategory V
G : MonCat
A : Action V G
⊢ 1 = 𝟙 A.V Tactic: rw [MonoidHom.map_one] State Before: V : Type (u + 1)
inst✝ : LargeCategory V
G : MonCat
A : Action V G
⊢ 1 = 𝟙 A.V State After: no goals Tactic: rfl |
Require Import Essentials.Notations.
Require Import Essentials.Types.
Require Import Essentials.Facts_Tactics.
Require Import Category.Main.
Require Import Basic_Cons.CCC Basic_Cons.PullBack.
Require Import Coq_Cats.Type_Cat.Type_Cat.
(** Type_Cat has pullbacks. The pullback of two functions f : a → b and g : c → b is
{(x, y) | f x = g y} *)
Section PullBack.
Context {A B C : Type} (f : A → C) (g : B → C).
Local Hint Extern 1 =>
match goal with
[x : sig _ |- _ ] =>
let H := fresh "H" in
destruct x as [x H]
end.
Program Definition Type_Cat_PullBack : @PullBack Type_Cat _ _ _ f g :=
{|
pullback := {x : A * B| f (fst x) = g (snd x)};
pullback_morph_1 := fun z => (fst (proj1_sig z));
pullback_morph_2 := fun z => (snd (proj1_sig z));
pullback_morph_ex := fun x p1 p2 H x' => (exist _ (p1 x', p2 x') _)
|}.
Next Obligation.
Proof.
match goal with
[|- ?A1 (?A2 ?x) = ?B1 (?B2 ?x)] =>
match goal with
[H : (fun w => A1 (A2 w)) = (fun w' => B1 (B2 w')) |- _] =>
apply (equal_f H)
end
end.
Qed.
Local Obligation Tactic := idtac.
Next Obligation.
Proof.
intros X p1 p2 H u u' H1 H2 H3 H4.
destruct H3; destruct H4.
extensionality x.
set (H1x := equal_f H1 x); clearbody H1x; clear H1.
set (H2x := equal_f H2 x); clearbody H2x; clear H2.
cbn in *.
match goal with
[|- ?A = ?B] => destruct A as [[a1 a2] Ha]; destruct B as [[b1 b2] Hb]
end.
cbn in *.
apply sig_proof_irrelevance; cbn.
rewrite H1x; rewrite H2x; trivial.
Qed.
End PullBack.
Instance Type_Cat_Has_PullBacks : Has_PullBacks Type_Cat := fun a b c f g => Type_Cat_PullBack f g. |
[GOAL]
α : Type u_1
β : Type u_2
f : α → β
⊢ classes (ker f) ⊆ Set.range fun y => {x | f x = y}
[PROOFSTEP]
rintro s ⟨x, rfl⟩
[GOAL]
case intro
α : Type u_1
β : Type u_2
f : α → β
x : α
⊢ {x_1 | Rel (ker f) x_1 x} ∈ Set.range fun y => {x | f x = y}
[PROOFSTEP]
rw [Set.mem_range]
[GOAL]
case intro
α : Type u_1
β : Type u_2
f : α → β
x : α
⊢ ∃ y, {x | f x = y} = {x_1 | Rel (ker f) x_1 x}
[PROOFSTEP]
exact ⟨f x, rfl⟩
[GOAL]
α✝ : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : Fintype β
f : α → β
inst✝ : Fintype ↑(classes (ker f))
⊢ Fintype.card ↑(classes (ker f)) ≤ Fintype.card β
[PROOFSTEP]
classical exact le_trans (Set.card_le_of_subset (classes_ker_subset_fiber_set f)) (Fintype.card_range_le _)
[GOAL]
α✝ : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : Fintype β
f : α → β
inst✝ : Fintype ↑(classes (ker f))
⊢ Fintype.card ↑(classes (ker f)) ≤ Fintype.card β
[PROOFSTEP]
exact le_trans (Set.card_le_of_subset (classes_ker_subset_fiber_set f)) (Fintype.card_range_le _)
[GOAL]
α : Type u_1
r : Setoid α
x y : α
x✝ : ∃ c, c ∈ classes r ∧ x ∈ c ∧ y ∈ c
c : Set α
z : α
hz : c = {x | Rel r x z}
hx : x ∈ c
hy : y ∈ c
⊢ Rel r x y
[PROOFSTEP]
subst c
[GOAL]
α : Type u_1
r : Setoid α
x y : α
x✝ : ∃ c, c ∈ classes r ∧ x ∈ c ∧ y ∈ c
z : α
hx : x ∈ {x | Rel r x z}
hy : y ∈ {x | Rel r x z}
⊢ Rel r x y
[PROOFSTEP]
exact r.trans' hx (r.symm' hy)
[GOAL]
α : Type u_1
r₁ r₂ : Setoid α
h : classes r₁ = classes r₂
a b : α
⊢ Rel r₁ a b ↔ Rel r₂ a b
[PROOFSTEP]
simp only [rel_iff_exists_classes, exists_prop, h]
[GOAL]
α : Type u_1
r : Setoid α
a : α
⊢ ∀ (y : Set α), y ∈ classes r → a ∈ y → y = {x | Rel r x a}
[PROOFSTEP]
rintro _ ⟨y, rfl⟩ ha
[GOAL]
case intro
α : Type u_1
r : Setoid α
a y : α
ha : a ∈ {x | Rel r x y}
⊢ {x | Rel r x y} = {x | Rel r x a}
[PROOFSTEP]
ext x
[GOAL]
case intro.h
α : Type u_1
r : Setoid α
a y : α
ha : a ∈ {x | Rel r x y}
x : α
⊢ x ∈ {x | Rel r x y} ↔ x ∈ {x | Rel r x a}
[PROOFSTEP]
exact ⟨fun hx => r.trans' hx (r.symm' ha), fun hx => r.trans' hx ha⟩
[GOAL]
α : Type u_1
c : Set (Set α)
H : ∀ (a : α), ∃! b x, a ∈ b
x : α
⊢ {y | Rel (mkClasses c H) x y} ∈ c
[PROOFSTEP]
convert @Setoid.eqv_class_mem _ _ H x using 3
[GOAL]
case h.e'_4.h.e'_2.h.a
α : Type u_1
c : Set (Set α)
H : ∀ (a : α), ∃! b x, a ∈ b
x x✝ : α
⊢ Rel (mkClasses c H) x x✝ ↔ Rel (mkClasses c H) x✝ x
[PROOFSTEP]
rw [Setoid.comm']
[GOAL]
α : Type u_1
c : Set (Set α)
hu : ⋃₀ c = Set.univ
H : Set.PairwiseDisjoint c id
a : α
⊢ a ∈ ⋃₀ c
[PROOFSTEP]
rw [hu]
[GOAL]
α : Type u_1
c : Set (Set α)
hu : ⋃₀ c = Set.univ
H : Set.PairwiseDisjoint c id
a : α
⊢ a ∈ Set.univ
[PROOFSTEP]
exact Set.mem_univ a
[GOAL]
α : Type u_1
c : Set (Set α)
hc : IsPartition c
x : α
t : Set α
ht : (fun b => ∃! x_1, x ∈ b) t ∧ ∀ (y : Set α), (fun b => ∃! x_1, x ∈ b) y → y = t
⊢ t ∈ c ∧ x ∈ t
[PROOFSTEP]
simp only [exists_unique_iff_exists] at ht
[GOAL]
α : Type u_1
c : Set (Set α)
hc : IsPartition c
x : α
t : Set α
ht : (∃ x_1, x ∈ t) ∧ ∀ (y : Set α), (∃ x_1, x ∈ y) → y = t
⊢ t ∈ c ∧ x ∈ t
[PROOFSTEP]
tauto
[GOAL]
α : Type u_1
c : Set (Set α)
hc : IsPartition c
s : Set α
x✝ : s ∈ classes (mkClasses c (_ : ∀ (a : α), ∃! b x, a ∈ b))
y : α
hs : s = {x | Rel (mkClasses c (_ : ∀ (a : α), ∃! b x, a ∈ b)) x y}
b : Set α
hm : b ∈ c
hb : y ∈ b
_hy : ∀ (y_1 : Set α), y_1 ∈ c → y ∈ y_1 → y_1 = b
⊢ s ∈ c
[PROOFSTEP]
rwa [show s = b from
hs.symm ▸
Set.ext fun x =>
⟨fun hx => symm' (mkClasses c hc.2) hx b hm hb, fun hx b' hc' hx' =>
eq_of_mem_eqv_class hc.2 hm hx hc' hx' ▸ hb⟩]
[GOAL]
α : Type u_1
x y : Subtype IsPartition
hx : x ≤ y
hy : y ≤ x
⊢ x = y
[PROOFSTEP]
let h := @le_antisymm (Setoid α) _ _ _ hx hy
[GOAL]
α : Type u_1
x y : Subtype IsPartition
hx : x ≤ y
hy : y ≤ x
h : mkClasses ↑x (_ : ∀ (a : α), ∃! b x, a ∈ b) = mkClasses ↑y (_ : ∀ (a : α), ∃! b x, a ∈ b) := le_antisymm hx hy
⊢ x = y
[PROOFSTEP]
rw [Subtype.ext_iff_val, ← classes_mkClasses x.1 x.2, ← classes_mkClasses y.1 y.2, h]
[GOAL]
α : Type u_1
C : { C // IsPartition C }
⊢ (fun r => { val := classes r, property := (_ : ¬∅ ∈ classes r ∧ ∀ (a : α), ∃! b x, a ∈ b) })
((fun C => mkClasses ↑C (_ : ∀ (a : α), ∃! b x, a ∈ b)) C) =
C
[PROOFSTEP]
rw [Subtype.ext_iff_val, ← classes_mkClasses C.1 C.2]
[GOAL]
α : Type u_1
r s : Setoid α
⊢ ↑{ toFun := fun r => { val := classes r, property := (_ : ¬∅ ∈ classes r ∧ ∀ (a : α), ∃! b x, a ∈ b) },
invFun := fun C => mkClasses ↑C (_ : ∀ (a : α), ∃! b x, a ∈ b),
left_inv := (_ : ∀ (r : Setoid α), mkClasses (classes r) (_ : ∀ (a : α), ∃! b x, a ∈ b) = r),
right_inv :=
(_ :
∀ (C : { C // IsPartition C }),
(fun r => { val := classes r, property := (_ : ¬∅ ∈ classes r ∧ ∀ (a : α), ∃! b x, a ∈ b) })
((fun C => mkClasses ↑C (_ : ∀ (a : α), ∃! b x, a ∈ b)) C) =
C) }
r ≤
↑{ toFun := fun r => { val := classes r, property := (_ : ¬∅ ∈ classes r ∧ ∀ (a : α), ∃! b x, a ∈ b) },
invFun := fun C => mkClasses ↑C (_ : ∀ (a : α), ∃! b x, a ∈ b),
left_inv := (_ : ∀ (r : Setoid α), mkClasses (classes r) (_ : ∀ (a : α), ∃! b x, a ∈ b) = r),
right_inv :=
(_ :
∀ (C : { C // IsPartition C }),
(fun r => { val := classes r, property := (_ : ¬∅ ∈ classes r ∧ ∀ (a : α), ∃! b x, a ∈ b) })
((fun C => mkClasses ↑C (_ : ∀ (a : α), ∃! b x, a ∈ b)) C) =
C) }
s ↔
r ≤ s
[PROOFSTEP]
conv_rhs => rw [← mkClasses_classes r, ← mkClasses_classes s]
[GOAL]
α : Type u_1
r s : Setoid α
| r ≤ s
[PROOFSTEP]
rw [← mkClasses_classes r, ← mkClasses_classes s]
[GOAL]
α : Type u_1
r s : Setoid α
| r ≤ s
[PROOFSTEP]
rw [← mkClasses_classes r, ← mkClasses_classes s]
[GOAL]
α : Type u_1
r s : Setoid α
| r ≤ s
[PROOFSTEP]
rw [← mkClasses_classes r, ← mkClasses_classes s]
[GOAL]
ι : Type u_1
α : Type u_2
s : ι → Set α
hs : IndexedPartition s
⊢ ⋃ (i : ι), s i = univ
[PROOFSTEP]
ext x
[GOAL]
case h
ι : Type u_1
α : Type u_2
s : ι → Set α
hs : IndexedPartition s
x : α
⊢ x ∈ ⋃ (i : ι), s i ↔ x ∈ univ
[PROOFSTEP]
simp [hs.exists_mem x]
[GOAL]
ι : Type u_1
α : Type u_2
s : ι → Set α
hs : IndexedPartition s
x✝ : IndexedPartition.Quotient hs
x : α
⊢ proj hs ⁻¹' {Quotient.mk'' x} = s (↑(equivQuotient hs).symm (Quotient.mk'' x))
[PROOFSTEP]
ext y
[GOAL]
case h
ι : Type u_1
α : Type u_2
s : ι → Set α
hs : IndexedPartition s
x✝ : IndexedPartition.Quotient hs
x y : α
⊢ y ∈ proj hs ⁻¹' {Quotient.mk'' x} ↔ y ∈ s (↑(equivQuotient hs).symm (Quotient.mk'' x))
[PROOFSTEP]
simp only [Set.mem_preimage, Set.mem_singleton_iff, hs.mem_iff_index_eq]
[GOAL]
case h
ι : Type u_1
α : Type u_2
s : ι → Set α
hs : IndexedPartition s
x✝ : IndexedPartition.Quotient hs
x y : α
⊢ proj hs y = Quotient.mk'' x ↔ index hs y = ↑(equivQuotient hs).symm (Quotient.mk'' x)
[PROOFSTEP]
exact Quotient.eq''
|
import Aoc
import Data.Fin
import Data.List
import Data.Vect
%default total
data FB = F | B
parseFB : Char -> Maybe FB
parseFB 'F' = Just F
parseFB 'B' = Just B
parseFB _ = Nothing
data LR = L | R
parseLR : Char -> Maybe LR
parseLR 'L' = Just L
parseLR 'R' = Just R
parseLR _ = Nothing
data Seat = MkSeat (Vect 7 FB) (Vect 3 LR)
parseSeat : String -> Maybe Seat
parseSeat s =
case unpack s of
[a,b,c,d,e,f,g,x,y,z] =>
MkSeat <$> traverse parseFB [a,b,c,d,e,f,g]
<*> traverse parseLR [x,y,z]
_ => Nothing
interface ToBit a where toBit : a -> Fin 2
ToBit FB where toBit F = 0; toBit B = 1
ToBit LR where toBit L = 0; toBit R = 1
fromBits : (ToBit a, Traversable t) => t a -> Nat
fromBits = foldl (\acc, a => 2*acc + finToNat (toBit a)) 0
seatID : Seat -> Nat
seatID (MkSeat row col) = fromBits {a=FB} row * 8 + fromBits {a=LR} col
||| Given a range [a..b] with one number deleted, find that number.
findGap : List Nat -> Maybe Nat
findGap [] = Nothing
findGap [x] = Nothing
findGap (x::y::xs) =
-- The totality checker wants this "let", but I don't understand why ;v;
let rest = findGap (y::xs) in if S x == y then rest else Just (S x)
partial
main : IO ()
main = do
seats <- parseLines parseSeat
case map seatID seats of
[] => putStrLn "no seats!"
ids@(_::_) => do
-- ^ This @ pattern helps "foldl1" find a proof that "ids" is non-empty.
putStr "* "; printLn (foldl1 max ids)
putStr "** "; printLn (findGap $ sort ids)
|
import
data.nat.prime
algebra.big_operators.intervals
extra.periodic.big_operators
ring_theory.int.basic
/-! # IMO 2017 N3 -/
namespace IMOSL
namespace IMO2017N3
open function finset extra
def good (n : ℕ) := ∀ x : ℕ → ℤ, periodic x n → ¬(n : ℤ) ∣ (range n).sum x →
∃ i : ℕ, ∀ j : ℕ, 0 < j → j ≤ n → ¬(n : ℤ) ∣ (Ico i (i + j)).sum x
section dvd_indicator
variables {M : Type*} [add_comm_monoid M]
private def dvd_seq (n : ℕ) (c : M) (i : ℕ) := ite (n ∣ i.succ) c 0
private lemma dvd_seq_dvd (n : ℕ) (c : M) {i : ℕ} (h : n ∣ i.succ) : dvd_seq n c i = c :=
by rw [dvd_seq, if_pos h]
private lemma dvd_seq_not_dvd (n : ℕ) (c : M) {i : ℕ} (h : ¬n ∣ i.succ) : dvd_seq n c i = 0 :=
by rw [dvd_seq, if_neg h]
private lemma dvd_seq_add_self (n : ℕ) (c : M) (i : ℕ) : dvd_seq n c (i + n) = dvd_seq n c i :=
begin
unfold dvd_seq; congr' 1,
rw [nat.succ_eq_add_one, add_right_comm, nat.dvd_add_self_right]
end
private lemma dvd_seq_mod_self (n : ℕ) (c : M) (i : ℕ) : dvd_seq n c (i % n) = dvd_seq n c i :=
begin
unfold dvd_seq; congr' 1,
rw [nat.succ_eq_add_one, nat.dvd_iff_mod_eq_zero, nat.mod_add_mod, nat.dvd_iff_mod_eq_zero]
end
private lemma dvd_seq_sum (n : ℕ) (c : M) (k : ℕ) :
(range k).sum (dvd_seq n c) = (k / n) • c :=
begin
induction k with k k_ih,
rw [sum_range_zero, nat.zero_div, zero_smul],
rw [sum_range_succ, k_ih, dvd_seq, nat.succ_div, add_smul, ite_smul, one_smul, zero_smul]
end
end dvd_indicator
/-- For `n ≥ 2`, if `n` is good, then `n` is prime. -/
private lemma good_is_prime {n : ℕ} (hn : 2 ≤ n) (h : good n) : n.prime :=
begin
rw [nat.prime_def_lt'', and_iff_right hn],
unfold good at h; contrapose! h,
rcases h with ⟨a, ⟨b, rfl⟩, h, h0⟩,
rw [ne.def, eq_comm, mul_right_eq_self₀, not_or_distrib, ← ne.def] at h0,
rw [ne_iff_lt_or_gt, nat.lt_succ_iff, gt_iff_lt, nonpos_iff_eq_zero] at h h0,
rw or_iff_right h0.2 at h; rcases h0 with ⟨h0, -⟩,
rcases h0 with rfl | h0,
rw mul_zero at hn,
exfalso; exact not_lt_of_le hn two_pos,
replace hn := lt_of_lt_of_le two_pos hn,
-- The sequence is x_n = a - a = 0 if ab ∣ n and x_n = a - 0 = a otherwise
refine ⟨λ i, a - dvd_seq (a * b) a i, λ i, by simp only [dvd_seq_add_self], _, λ i, _⟩,
-- ab ∤ x_0 + x_1 + ... + x_{ab - 1} since the sum is a^2 b - a
{ rintros ⟨c, h1⟩,
rw [sum_sub_distrib, sum_const, dvd_seq_sum, card_range, nsmul_eq_mul, nat.div_self hn,
one_smul, sub_eq_iff_eq_add, ← sub_eq_iff_eq_add', ← mul_sub, nat.cast_mul, mul_assoc,
mul_right_eq_self₀, nat.cast_eq_zero, or_iff_left (ne_of_gt (lt_trans one_pos h))] at h1,
refine ne_of_gt h0 _,
rw ← nat.dvd_one; use ((a : ℤ) - c).nat_abs,
rw [← int.nat_abs_of_nat b, ← int.nat_abs_mul, h1, int.nat_abs_one] },
cases lt_or_le (i % (a * b)) ((a - 1) * b) with h1 h1,
-- If i % ab < (a - 1)b, pick j = b
{ refine ⟨b, lt_trans one_pos h0, nat.le_mul_of_pos_left (lt_trans one_pos h), 1, _⟩,
rw [mul_one, sum_sub_distrib, sum_const, nat.card_Ico, nsmul_eq_mul,
nat.add_sub_cancel_left, mul_comm, nat.cast_mul, sub_eq_self,
finset.sum_Ico_eq_add_neg _ le_self_add, dvd_seq_sum, add_neg_eq_zero, dvd_seq_sum],
generalize hr : i % (a * b) = r,
rw hr at h1,
obtain ⟨q, rfl⟩ : ∃ q : ℕ, r + q * (a * b) = i :=
⟨i / (a * b), by rw ← hr; exact nat.mod_add_div' i (a * b)⟩,
suffices : r + b < a * b,
{ rw [add_right_comm, nat.add_mul_div_right _ _ hn, nat.div_eq_of_lt this,
nat.add_mul_div_right _ _ hn, nat.div_eq_of_lt (lt_trans _ this)],
rw lt_add_iff_pos_right; exact lt_trans one_pos h0 },
convert nat.add_lt_add_right h1 b,
rw [← add_one_mul, nat.sub_add_cancel (le_of_lt h)] },
-- If i % ab ≥ (a - 1)b, pick j = b + 1
{ have h2 : b.succ < a * b :=
begin
cases a with a a,
exfalso; exact lt_asymm h one_pos,
rw [nat.succ_mul, nat.succ_eq_one_add, add_lt_add_iff_right],
exact lt_of_lt_of_le h0 (le_mul_of_one_le_left' (nat.lt_succ_iff.mp h))
end,
refine ⟨b.succ, b.succ_pos, le_of_lt h2, 1, _⟩,
rw [mul_one, sum_sub_distrib, sum_const, nat.card_Ico, nat.add_sub_cancel_left,
succ_nsmul', nsmul_eq_mul, mul_comm, nat.cast_mul, sub_eq_iff_eq_add,
add_right_inj, finset.sum_Ico_eq_add_neg _ le_self_add, dvd_seq_sum,
dvd_seq_sum, nat.add_div_eq_of_le_mod_add_mod _ hn, nat.div_eq_of_lt h2,
add_zero, succ_nsmul, add_neg_cancel_right],
rw nat.mod_eq_of_lt h2,
convert add_le_add h1 (le_of_lt b.lt_succ_self),
rw [← add_one_mul, nat.sub_add_cancel (le_of_lt h)] }
end
section cycle_sum
variables {n : ℕ} {s : ℕ → ℕ} (h : ∀ i : ℕ, i < s i)
include h
private lemma cycle_sum1 (k : ℕ) : strict_mono (λ i, s^[i] k) :=
begin
intros i j h0; dsimp only [],
rw [← nat.succ_le_iff, le_iff_exists_add] at h0,
rcases h0 with ⟨c, rfl⟩,
induction c with c c_ih,
rw [add_zero, iterate_succ', comp_app]; exact h _,
rw [nat.add_succ, iterate_succ', comp_app],
exact lt_trans c_ih (h _)
end
variable (h0 : ∀ i : ℕ, s i < i + n)
include h0
private lemma cycle_sum2 (k i : ℕ) {c : ℕ} (h1 : 0 < c) : s^[i + c] k < (s^[i]) k + n * c :=
begin
induction c with c c_ih,
exfalso; exact lt_irrefl 0 h1,
rcases c.eq_zero_or_pos with rfl | h2,
rw [iterate_succ', comp_app, mul_one]; exact h0 _,
rw [nat.add_succ, iterate_succ', comp_app, nat.mul_succ, ← add_assoc],
refine lt_trans (h0 _) _,
rw add_lt_add_iff_right; exact c_ih h2
end
private lemma cycle_sum3 (k : ℕ) : ∃ i j c : ℕ, 0 < c ∧ c < n ∧ (s^[j]) k = (s^[i]) k + n * c :=
begin
have hn := lt_of_le_of_lt (nat.succ_le_iff.mpr (h 0)) (h0 0),
rw [zero_add, ← nat.succ_le_iff] at hn,
obtain ⟨i, j, h2, h3, h4⟩ : ∃ i j : ℕ, i < j ∧ j ≤ n ∧ (s^[i] k) % n = (s^[j] k) % n :=
begin
obtain ⟨i, h2, j, h3, h4, h5⟩ : ∃ (i : ℕ) (H : i ∈ range n.succ)
(j : ℕ) (H : j ∈ range n.succ), i ≠ j ∧ (s^[i] k) % n = (s^[j] k) % n :=
begin
have h2 : (range n).card < (range n.succ).card :=
by rw [card_range, card_range]; exact n.lt_succ_self,
have h3 : ∀ i : ℕ, i ∈ range n.succ → (s^[i] k) % n ∈ range n :=
λ i _, by rw mem_range; exact nat.mod_lt _ (lt_of_lt_of_le two_pos hn),
exact exists_ne_map_eq_of_card_lt_of_maps_to h2 h3
end,
rw [mem_range, nat.lt_succ_iff] at h2 h3,
rw ne_iff_lt_or_gt at h4,
cases h4 with h4 h4,
exacts [⟨i, j, h4, h3, h5⟩, ⟨j, i, h4, h2, eq_comm.mp h5⟩]
end,
have h5 := cycle_sum1 h k h2,
rw [← nat.modeq, nat.modeq_iff_dvd' (le_of_lt h5)] at h4,
cases h4 with c h4,
rw [nat.sub_eq_iff_eq_add (le_of_lt h5), add_comm] at h4,
refine ⟨i, j, c, _, _, h4⟩,
{ rw pos_iff_ne_zero; rintros rfl,
rw [mul_zero, add_zero] at h4,
exact ne_of_gt h5 h4 },
{ obtain ⟨d, rfl⟩ : ∃ d : ℕ, j = i + d := le_iff_exists_add.mp (le_of_lt h2),
rw lt_add_iff_pos_right at h2,
replace h5 := cycle_sum2 h h0 k i h2,
dsimp only [] at h4 h5,
rw [h4, add_lt_add_iff_left, mul_lt_mul_left (lt_of_lt_of_le two_pos hn)] at h5,
exact lt_of_lt_of_le h5 (le_trans le_add_self h3) }
end
variables {x : ℕ → ℤ} (h1 : ∀ i : ℕ, (n : ℤ) ∣ (Ico i (s i)).sum x)
include h1
private lemma cycle_sum4 : ∃ m c : ℕ, 0 < c ∧ c < n ∧ (n : ℤ) ∣ (Ico m (m + n * c)).sum x :=
begin
rcases cycle_sum3 h h0 0 with ⟨i, j, c, h2, h3, h4⟩,
refine ⟨s^[i] 0, c, h2, h3, _⟩,
dsimp only [] at h4; rw ← h4; clear h4 h3 h2 c,
cases lt_or_le j i with h2 h2,
rw [Ico_eq_empty_of_le (le_of_lt (cycle_sum1 h 0 h2)), sum_empty]; exact dvd_zero (n : ℤ),
rw le_iff_exists_add at h2; rcases h2 with ⟨c, rfl⟩,
induction c with c c_ih,
rw [add_zero, Ico_self, sum_empty]; exact dvd_zero (n : ℤ),
rw [nat.add_succ, iterate_succ', comp_app, ← finset.sum_Ico_consecutive x _ (le_of_lt (h _))],
exacts [dvd_add c_ih (h1 _), (cycle_sum1 h 0).monotone le_self_add]
end
variable (h2 : periodic x n)
include h2
private lemma cycle_sum5 : ∃ c : ℕ, 0 < c ∧ c < n ∧ (n : ℤ) ∣ c * (range n).sum x :=
begin
rcases cycle_sum4 h h0 h1 with ⟨m, c, h3, h4, h5⟩,
refine ⟨c, h3, h4, _⟩,
rw [finset.sum_Ico_eq_sum_range, nat.add_sub_cancel_left] at h5,
convert h5; clear h3 h4 h5,
induction c with c c_ih,
rw [nat.cast_zero, zero_mul, mul_zero, sum_range_zero],
rw [nat.cast_succ, add_one_mul, c_ih, nat.mul_succ, sum_range_add, add_right_inj],
conv_rhs { congr, skip, funext, rw [← add_assoc, add_comm] },
rw periodic_sum_const h2
end
end cycle_sum
/-- For `n ≥ 2`, if `n` is prime, then `n` is good. -/
private lemma prime_is_good {n : ℕ} (hn : 2 ≤ n) (h : n.prime) : good n :=
begin
intros x hx h0; by_contra' h1,
-- Using AOC, replace h0 with a special indexing sequence with a good property
replace h1 := classical.axiom_of_choice h1,
replace h1 : ∃ s : ℕ → ℕ, ∀ i : ℕ, i < s i ∧ s i < i + n ∧ (n : ℤ) ∣ (Ico i (s i)).sum x :=
begin
cases h1 with t h1,
refine ⟨λ i, i + t i, λ i, ⟨_, _, (h1 i).2.2⟩⟩,
rw lt_add_iff_pos_right; exact (h1 i).1,
rw add_lt_add_iff_left; refine lt_of_le_of_ne (h1 i).2.1 (λ h2, _),
replace h1 := (h1 i).2.2,
rw [finset.sum_Ico_eq_sum_range, nat.add_sub_cancel_left] at h1,
conv at h1 { find (_ + _) { rw add_comm } },
rw [h2, periodic_sum_const hx] at h1,
exact h0 h1
end,
-- Now just use the result given in the `cycle_sum` section to proceed
replace h1 : ∃ c : ℕ, 0 < c ∧ c < n ∧ (n : ℤ) ∣ c * (range n).sum x :=
by cases h1 with s h1; exact cycle_sum5 (λ i, (h1 i).1) (λ i, (h1 i).2.1) (λ i, (h1 i).2.2) hx,
rcases h1 with ⟨c, h1, h2, h3⟩,
replace h3 := int.prime.dvd_mul' h h3,
rw [or_iff_left h0, int.coe_nat_dvd] at h3,
exact nat.not_dvd_of_pos_of_lt h1 h2 h3
end
theorem final_solution {n : ℕ} (hn : 2 ≤ n) : good n ↔ n.prime :=
⟨good_is_prime hn, prime_is_good hn⟩
end IMO2017N3
end IMOSL
|
#
# Definitions to move to NDTensors
#
storage(T::Tensor) = store(T)
#function NDTensors.blockdims(inds::IndexSet, block::Tuple)
# return ntuple(i -> blockdim(inds,block,i), ValLength(block))
#end
|
from functools import reduce
from typing import List
import operator
import numpy as np
from .genome import Genome
class GeneticAlgorithm:
def __init__(self, **kwargs):
"""Creates a genetic algorithm.
Keyword Arguments:
selection {callable} -- Selection function used
fitness {callable} -- Fitness function used
mutation {callable} -- Mutation function used
genomes {Genomes} -- First generation of genomes
termCon {callable} -- Termination condition
callback {callable} -- Callback at the end of an iteration
elitism {float} -- Elitism percentage
pressure {float} -- EXPERIMENTAL: Pressure factor for fitness values (default: {1})
mutationChance {float} -- Chance a genome is selected for mutation (default: {0.03})
mutationChanceGene {float} -- Chance a gene is mutated (default: {0.03})
"""
if(kwargs is not None):
self.selection = kwargs.pop("selection", None)
self.fitness = kwargs.pop("fitness", None)
self.mutation = kwargs.pop("mutation", None)
self.crossover = kwargs.pop("crossover", None)
self.genomes = kwargs.pop("genomes", None)
self.termCon = kwargs.pop("termCon", None)
self.callback = kwargs.pop("callback", None)
self.elitism = kwargs.pop("elitism", 0.1)
self.pressureFactor = kwargs.pop("pressure", 1)
self.genomeMutationChance = kwargs.pop("mutationChance", 0.03)
self.geneMutationChance = kwargs.pop("mutationChanceGene", 0.03)
self.evolving = False
self.generation = 0
self.fitness_val = None
def evolve(self, generation=0) -> np.ndarray:
"""Evolve until the termination condition is met
Keyword Arguments:
generation {int} -- Starting generation (default: {0})
Returns:
numpy.ndarray[Genome] -- Last iteration genomes
"""
self.evolving = True
self.generation = generation
local_genomes = self.genomes
while not self.termCon(self):
local_genomes = self.evoStep(local_genomes)
self.evolving = False
self.fitness_val = None
return local_genomes
def evoStep(self, local_genomes=None) -> List[Genome]:
"""Single evolution step
Keyword Arguments:
local_genomes {List[Genome]} -- Genomes that will be evolved. If None self.genomes will be used (default: {None})
Returns:
numpy.ndarray[Genome] -- Genomes evolved in this evolution step
"""
# evolutionary steps
if local_genomes is not None:
self.genomes = local_genomes
arr = np.empty(len(self.genomes), dtype=object)
arr[:] = self.genomes[:]
self.fitness_val = self.fitness(self.genomes)
elite, crossover_candidates = self.selection(
self, self.genomes, self.fitness_val, self.elitism
)
children = [
self.crossover(self.genomes[parent1], self.genomes[parent2])
for parent1, parent2 in crossover_candidates
]
children = reduce(operator.concat, children)
arr_children = np.empty(len(children), dtype=object)
arr_children[:] = children[:]
elites = np.empty(len(elite), dtype=object)
elites[:] = [genome.carry_in_next() for genome in arr[elite]]
if self.mutation is not None:
self.mutation(arr_children, self.genomeMutationChance, self.geneMutationChance)
local_genomes = np.hstack([elites, arr_children])
until = np.min([local_genomes.size, self.genomes.size])
self.genomes = local_genomes[:until]
self.fitness_val = self.fitness(self.genomes)
if callable(self.callback):
self.callback(self)
self.generation += 1
return self.genomes
|
!
! Copyright 2018 SALMON developers
!
! Licensed under the Apache License, Version 2.0 (the "License");
! you may not use this file except in compliance with the License.
! You may obtain a copy of the License at
!
! http://www.apache.org/licenses/LICENSE-2.0
!
! Unless required by applicable law or agreed to in writing, software
! distributed under the License is distributed on an "AS IS" BASIS,
! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
! See the License for the specific language governing permissions and
! limitations under the License.
!
!-----------------------------------------------------------------------------------------
module salmon_maxwell
implicit none
type fdtd_grid
integer :: ng_sta(3), ng_end(3) ! Size of Local Grid System
integer :: lg_sta(3), lg_end(3) ! Size of Global Grid System
integer :: no_sta(3), no_end(3) ! Size of Entire (Allocated) Variables
real(8) :: dt ! Delta t
integer :: iter_now ! Present iteration Number
real(8) :: rlsize(3) ! Size of Cell
real(8) :: hgs(3) ! Grid Spacing
real(8) :: origin(3) ! Coordinate of Origin Point (TBA)
integer :: i_bc(3, 2) ! Boundary Condition for 1:x, 2:y, 3:z and 1:bottom and 2:top
character(16) :: gauge ! Gauge Condition (TBD)
integer, allocatable :: imedia(:,:,:) ! Material information
end type fdtd_grid
type fdtd_field
real(8), allocatable :: vec_e(:,:,:,:) ! E
real(8), allocatable :: vec_h(:,:,:,:) ! H
real(8), allocatable :: vec_a(:,:,:,:), phi(:,:,:) ! Vector and Scalar Potential
real(8), allocatable :: vec_j_em(:,:,:,:) ! Electromagnetic Current
real(8), allocatable :: rho_em(:,:,:,:) ! Electromagnetic Charge
end type fdtd_field
type fdtd_tmp
!weyl
!coulomb
!eh
real(8) :: c_0 !light speed
integer :: Nd !number of additional grid in mpi
integer :: iter_sta !start of time-iteration
integer :: iter_end !end of time-iteration
integer :: ifn !file number for inputing or saving data
integer :: ipml_l !pml parameter
real(8) :: pml_m !pml parameter
real(8) :: pml_r !pml parameter
real(8) :: e_max !maximum e for observation
real(8) :: h_max !maximum e for observation
real(8) :: uVperm_from_au !convert parameter for V/m
real(8) :: uAperm_from_au !convert parameter for A/m
real(8),allocatable :: rep(:) !relative permittivity(non-dispersion)
real(8),allocatable :: rmu(:) !relative permeability(non-dispersion)
real(8),allocatable :: sig(:) !conductivity(non-dispersion)
real(8),allocatable :: coo(:,:) !grid coordinate
integer,allocatable :: iobs_po_pe(:) !processor element at observation point
integer,allocatable :: iobs_li_pe(:,:) !processor element at observation line
integer,allocatable :: iobs_pl_pe(:,:) !processor element at observation plane
integer,allocatable :: iobs_po_id(:,:) !id at observation point
integer :: inc_num !number of incident current source
integer,allocatable :: inc_po_pe(:) !processor element at incident current source point
integer,allocatable :: inc_li_pe(:,:) !processor element at incident current source line
integer,allocatable :: inc_pl_pe(:,:) !processor element at incident current source plane
integer,allocatable :: inc_po_id(:,:) !id at incident current source point
character(16) :: inc_dist1 !spatial distribution type of inc.
character(16) :: inc_dist2 !spatial distribution type of inc.
real(8) :: c2_inc_xyz(3) !coeff. for inc., xyz(1:3) means propa. direc. of the inc.
real(8),allocatable :: ex_y(:,:,:),c1_ex_y(:,:,:),c2_ex_y(:,:,:),ex_z(:,:,:),c1_ex_z(:,:,:),c2_ex_z(:,:,:) !e
real(8),allocatable :: ey_z(:,:,:),c1_ey_z(:,:,:),c2_ey_z(:,:,:),ey_x(:,:,:),c1_ey_x(:,:,:),c2_ey_x(:,:,:) !e
real(8),allocatable :: ez_x(:,:,:),c1_ez_x(:,:,:),c2_ez_x(:,:,:),ez_y(:,:,:),c1_ez_y(:,:,:),c2_ez_y(:,:,:) !e
integer :: iex_y_sta(3),iex_y_end(3),iex_z_sta(3),iex_z_end(3) !e
integer :: iey_z_sta(3),iey_z_end(3),iey_x_sta(3),iey_x_end(3) !e
integer :: iez_x_sta(3),iez_x_end(3),iez_y_sta(3),iez_y_end(3) !e
real(8),allocatable :: hx_y(:,:,:),c1_hx_y(:,:,:),c2_hx_y(:,:,:),hx_z(:,:,:),c1_hx_z(:,:,:),c2_hx_z(:,:,:) !h
real(8),allocatable :: hy_z(:,:,:),c1_hy_z(:,:,:),c2_hy_z(:,:,:),hy_x(:,:,:),c1_hy_x(:,:,:),c2_hy_x(:,:,:) !h
real(8),allocatable :: hz_x(:,:,:),c1_hz_x(:,:,:),c2_hz_x(:,:,:),hz_y(:,:,:),c1_hz_y(:,:,:),c2_hz_y(:,:,:) !h
integer :: ihx_y_sta(3),ihx_y_end(3),ihx_z_sta(3),ihx_z_end(3) !h
integer :: ihy_z_sta(3),ihy_z_end(3),ihy_x_sta(3),ihy_x_end(3) !h
integer :: ihz_x_sta(3),ihz_x_end(3),ihz_y_sta(3),ihz_y_end(3) !h
real(8),allocatable :: ex_s(:,:,:),ey_s(:,:,:),ez_s(:,:,:) !e for save
real(8),allocatable :: hx_s(:,:,:),hy_s(:,:,:),hz_s(:,:,:) !h for save
real(8),allocatable :: c2_jx(:,:,:),c2_jy(:,:,:),c2_jz(:,:,:) !coeff. for general curr. dens.
integer :: inum_d !Drude: number of media
integer,allocatable :: imedia_d(:) !Drude: imedia number for drude model
integer,allocatable :: idx_d(:,:,:,:),idy_d(:,:,:,:),idz_d(:,:,:,:) !Drude: id for each component
real(8),allocatable :: rjx_d(:,:,:,:),rjy_d(:,:,:,:),rjz_d(:,:,:,:) !Drude: poparization current density
real(8),allocatable :: rjx_sum_d(:,:,:),rjy_sum_d(:,:,:),& !Drude: sum of poparization current density
rjz_sum_d(:,:,:)
real(8),allocatable :: wex_d(:,:,:,:),wey_d(:,:,:,:),wez_d(:,:,:,:) !Drude: weight function for smoothing
real(8),allocatable :: c1_j_d(:),c2_j_d(:) !Drude: coefficient for j
integer :: iwk_size_eh !tmporary variable for sendrecvh
real(8),allocatable :: rmedia(:,:,:) !Material information for tmp.
real(8),allocatable :: time_lr(:) !LR: time
integer :: iter_lr !LR: time iteration for save
real(8),allocatable :: fr_lr(:,:) !LR: Re[f]
real(8),allocatable :: fi_lr(:,:) !LR: Im[f]
real(8),allocatable :: rjx_lr(:,:,:),rjy_lr(:,:,:),rjz_lr(:,:,:) !LR: poparization current density
real(8),allocatable :: px_lr(:,:,:), py_lr(:,:,:), pz_lr(:,:,:) !LR: poparization vector
real(8),allocatable :: curr_lr(:,:) !LR: current
real(8),allocatable :: dip_lr(:,:) !LR: dipolemoment
end type fdtd_tmp
contains
subroutine init_maxwell(grid,field,tmp)
use inputoutput, only: theory, use_ms_maxwell
implicit none
type(fdtd_grid) :: grid
type(fdtd_field) :: field
type(fdtd_tmp) :: tmp
select case(theory)
case('Maxwell+TDDFT')
!this selection is temporary.
!After removing use_ms_maxwell, this selection is revised.
select case(use_ms_maxwell)
case('y')
grid%gauge = 'weyl'
case('s')
grid%gauge = 'coulomb'
end select
case('Maxwell')
grid%gauge = 'eh'
case default
stop 'invalid theory'
end select
select case(grid%gauge)
case('weyl')
call weyl_init(grid,field,tmp)
case('coulomb')
call coulomb_init(grid,field,tmp)
case('eh')
call eh_init(grid,tmp)
end select
end subroutine init_maxwell
subroutine finalize_maxwell(grid,field,tmp)
implicit none
type(fdtd_grid) :: grid
type(fdtd_field) :: field
type(fdtd_tmp) :: tmp
select case(grid%gauge)
case('weyl')
call weyl_finalize(grid,field,tmp)
case('coulomb')
call coulomb_finalize(grid,field,tmp)
case('eh')
call eh_finalize(grid,tmp)
end select
end subroutine finalize_maxwell
subroutine calc_maxwell(grid,field,tmp)
implicit none
type(fdtd_grid) :: grid
type(fdtd_field) :: field
type(fdtd_tmp) :: tmp
select case(grid%gauge)
case('weyl')
call weyl_calc(grid,field,tmp)
case('coulomb')
call coulomb_calc(grid,field,tmp)
case('eh')
call eh_calc(grid,tmp)
end select
end subroutine calc_maxwell
end module salmon_maxwell
|
theory IMO_1959_Q1
imports Main
begin
lemma foo: "2 + 2 = 4"
by auto
end |
function LU = extract_bounds_from_milpsubsref_operator(LU,extstruct,extvariables,i)
arg = extstruct(i).arg{1};
epi = getvariables(extstruct(i).var);
[M,m] = derivebounds(reshape(arg,[],1),LU);
LU(epi,1) = min(m);
LU(epi,2) = max(M);
for j = 1:length(extstruct(i).arg{2}.subs)
index = extstruct(i).arg{2}.subs{j};
if isa(index,'sdpvar')
if isequal(getbase(index),[0 1])
LU(getvariables(index),1) = max(LU(getvariables(index),1),1);
LU(getvariables(index),2) = min(LU(getvariables(index),2),numel(arg));
end
end
end
|
#pragma once
#include "global.hpp"
#include "message.hpp"
#include <belt.pp/ilog.hpp>
#include <belt.pp/isocket.hpp>
#include <mesh.pp/cryptoutility.hpp>
#include <boost/filesystem/path.hpp>
#include <memory>
#include <string>
#include <chrono>
#include <map>
namespace publiqpp
{
class storage_node;
class coin;
namespace detail
{
using fp_counts_per_channel_views =
uint64_t (*)(std::map<uint64_t, std::map<std::string, std::map<std::string, uint64_t>>> const& item_per_owner,
uint64_t block_number,
bool is_testnet);
class node_internals;
}
class BLOCKCHAINSHARED_EXPORT node
{
public:
node(std::string const& genesis_signed_block,
beltpp::ip_address const& public_address,
beltpp::ip_address const& public_ssl_address,
beltpp::ip_address const& rpc_bind_to_address,
beltpp::ip_address const& p2p_bind_to_address,
std::vector<beltpp::ip_address> const& p2p_connect_to_addresses,
boost::filesystem::path const& fs_blockchain,
boost::filesystem::path const& fs_action_log,
boost::filesystem::path const& fs_transaction_pool,
boost::filesystem::path const& fs_state,
boost::filesystem::path const& fs_documents,
boost::filesystem::path const& fs_storages,
boost::filesystem::path const& fs_storage,
beltpp::ilog* plogger_p2p,
beltpp::ilog* plogger_node,
meshpp::private_key const& pv_key,
BlockchainMessage::NodeType& n_type,
uint64_t fractions,
uint64_t freeze_before_block,
bool log_enabled,
bool transfer_only,
bool testnet,
bool resync,
bool revert_blocks,
coin const& mine_amount_threshhold,
std::vector<coin> const& block_reward_array,
detail::fp_counts_per_channel_views p_counts_per_channel_views);
node(node&& other) noexcept;
~node();
void wake();
std::string name() const;
void run(bool& stop);
void set_slave_node(storage_node& slave_node);
private:
std::unique_ptr<detail::node_internals> m_pimpl;
};
}
|
using Roofline
@noinline function experiment(A)
acc = zero(eltype(A))
@simd for i in eachindex(A)
@inbounds acc += A[i]
end
acc
end
function setup(N)
data = rand(Float32, N)
return (data,)
end
bench = Roofline.benchmark(experiment, setup, 2^27) |
/* modulo-bias - test for modulo bias in poor random number generation;
* the bias does not appear where RAND_MAX is much larger than m. for a
* three-sided dice roll, the last RAND_MAX to fail what I think is a
* chi-squared 0.05 test is 257; given a system RAND_MAX of a much
* larger value, this would likely only be of concern if the modulo m is
* very, very large, or if an 8-bit system is being used. better results
* are obtained where m evenly divides RAND_MAX; RAND_MAX of 100000 and
* m = 4 only fails at 62 and below (assuming no errors on my part)
*
* actually, the exact numbers depend on the rand() implementation and
* the seed; Mac OS X rand() produced the 257 for an arbitrary seed;
* this version tries out multiple seeds (TRIALS) and emits what is
* likely the maximum failure of the fitness test for that seed.
* However! it still remains that if RAND_MAX is much larger than the
* range, there is no (statistically significant) modulo bias */
#include <err.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <gsl/gsl_cdf.h>
/* how many results to generate (3 == (0,1,2)) and how many tests to
* run; TESTNUM will need to be high enough to distinguish signal from
* the noise, but not too long that too much CPU is wasted */
#define RANGE 3
#define TESTNUM 99999
/* CHI^2 test foo, assuming uniform distribution of the RANGE values
* over the TESTNUM runs, and 95% confidence */
#define EXPECTED TESTNUM / (double) RANGE
#define DEG_OF_FREE RANGE - 1
#define FITNESS 0.05
/* this may have to go up if larger RANGE are being tested, e.g. some
* huge prime vs. some other huge prime, or otherwise scale in some
* relation to RANGE and randmax */
#define NOBIAS_RUN 100
/* how many (hopefully) different random seeds to do the test under */
#define TRIALS 500
#define randof(x) ((rand() % x) % RANGE)
unsigned int results[RANGE];
int main(void)
{
unsigned int i, maxfail, nobias, randmax, testnum, trialnum;
double sq;
#ifdef __OpenBSD__
if (pledge("stdio", NULL) == -1)
err(1, "pledge failed");
#endif
//setvbuf(stdout, (char *)NULL, _IOLBF, (size_t) 0);
for (trialnum = 0; trialnum < TRIALS; trialnum++) {
/* pseudorandom within pseudorandom, per Dune */
srand(arc4random());
nobias = 0;
for (randmax = RANGE; randmax < UINT_MAX; randmax += 1) {
for (testnum = 0; testnum < TESTNUM; testnum++) {
results[randof(randmax)]++;
}
sq = 0.0;
for (i = 0; i < RANGE; i++) {
sq += pow((double) results[i] - EXPECTED, 2) / EXPECTED;
results[i] = 0; // reset for the next test
}
if (gsl_cdf_chisq_Q(sq, DEG_OF_FREE) <= FITNESS) {
maxfail = randmax;
nobias = 0;
} else {
if (nobias++ >= NOBIAS_RUN) {
break;
}
}
}
printf("%d\n", maxfail);
}
exit(EXIT_SUCCESS);
}
|
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Patrick Tullmann, John McCorquodale, Ajay Chitturi,
% Jeff Turner, and Godmar Back
%
% Fluke Verification Project
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Document setup info
\documentclass{article}
\usepackage{times}
%%%%%%%
%%%%%%% Some standard \def's
\long\def\com#1{}
\long\def\xxx#1{{\em {\bf Fix: } #1}}
% We don't need no steenkin' equations - just gimme a working underscore!
\catcode`\_=\active
\def\psinc(#1,#2)#3{
\setlength{\unitlength}{1in}
{\unitlength =1pt
\centering\begin{picture}(#1,#2)
\put(0,0){\special{psfile=#3.eps}}
\end{picture}}}
\def\psfig(#1,#2)#3#4{
\begin{figure}[t] % XXX fix this, don't want at top
\psinc(#1,#2){#3}
\caption{\footnotesize #4}
\label{#3}
\end{figure}}
%%%%%%%
%%%%%%%
\topmargin 0pt
\advance \topmargin by -\headheight
\advance \topmargin by -\headsep
\textheight 8.9in
\oddsidemargin 0.3in
\evensidemargin \oddsidemargin
\marginparwidth 0.5in
\textwidth 6in
%% I'm going to try to structure this like a paper, to
%% minimize re-writing if things go well and this becomes
%% a real paper.
\title{\Large Verifying the Fluke $\mu$kernel IPC path}
\author{Ajay Chitturi~~~~John McCorquodale~~~~Patrick Tullmann~~~~\\
Jeff Turner~~~~Godmar Back \\[2ex]
{\sc CS 611--Formal Methods for System Design}
}
%\date{October 14, 1996}
\date{November 12, 1996}
%BEGIN DOCUMENT--------------------
\begin{document}
\maketitle
{\it We propose to model Fluke reliable Interprocess Communication (IPC)
and verify
first, that under normal execution the threads involved
will not deadlock. Also, we will verify
that any IPC can be canceled at arbitrary points, without
leaving the threads involved deadlocked or lost.
We will also generate a descriptive formal model of the IPC
implementation in Fluke and the objects related to it.
}
\section*{Introduction}
Fluke~\cite{Flukedocs:96} is a microkernel in the tradition of Mach, QNX, and KeyKOS.
Internally, most operations in fluke are implemented as operations
on distinct kernel objects. For example, in an IPC
operation between two threads (client \& sever), when
the client decides to send some data to the server it will
find the server thread kernel object, lock part of it,
copy the data, adjust state in the server object to
reflect the copied state, and then restart the server
on its way.
%% XXX this is _way_ too detailed.
One of the key properties of Fluke is that the state of all
kernel-mediated objects is extractable at any time. This
extracted state is guaranteed to be consistent, requiring
that all operations on these objects appear to be atomic.
The kernel accomplishes this by cleanly ``rolling back''
non-atomic operations that get interrupted.
% XXX Flesh this example out more, make it real.
For example, a thread in Fluke may attempt to acquire the
``state'' of another thread (the current register values,
communication connection information, etc.) This action
implicitly stops the targeted thread, and extracts the
required information.
If the target thread is involved in a complex operation
(i.e. a large IPC data transfer,) the kernel may
have arbitrary internal state to keep track of the
transfer. Instead of trying to store this arbitrary state
in the thread, it can roll the operation back to a ``clean''
point in the execution.
At this point, the state can be taken and given to the
requesting thread.
\section*{Related Work}
\subsubsection*{Cancelable IPC operations}
The fact that Fluke claims to be able to cancel IPC operations at any
arbitrary point is non-trivial.
In Mach, certain IPC operations are not cancelable at arbitrary points
(despite hard work to the contrary). In Mach, a message send containing
multi-page out-of-line data cannot be interrupted and safely restarted.
Amoeba has similar restrictions.
\subsubsection*{Modeling Operating Systems in Promela}
The Harmony operating system is a ``portable real-time multitasking
multiprocessor operating system'', developed by the Canadian National
Research Council in the 1980's and early 1990's. It is
microkernel-based, and provides interrupt management, scheduling, IPC,
memory management, and I/O management~\cite{Harmony-verify}.
The Harmony verification effort performed an exhaustive verification
of the IPC features of Harmony, focusing on deadlock and livelock.
The Harmony effort is similar to our own in that they developed their
detailed models through study of the Harmony code, resulting in very
low-level models that accurately reflect the details of the kernel.
We will be able to use many of the lessons learned from the Harmony
effort. For example, they concluded that an abstract model was not
particularly useful, because there was not enough detail to prove
absence of deadlock. The paper also contains several tips for
managing the state space problem.
\com{
Our effort differs from that of the Harmony modeling in the extent to
which we model the interaction of the IPC system with other parts of
the Fluke kernel. In particular, instead of a complete model of the
IPC subsystem, we choose only one of the types of IPC, and examine the
guarantees that can be made about operations on thread objects.
}
The RUBIS operating system is another microkernel-based operating
system, developed by a company called TELEMAT in Switzerland. The
paper~\cite{RUBIS-verify}
claims to have performed an exhaustive verification of the IPC
features of RUBIS. However, they are vague about what
properties are actually verified (e.g., ``Different kinds of errors
have been detected''), and the claim is not substantiated.
\com{
As with the Harmony effort, our project differs from the RUBIS
verification in that we intend to do more than just prove that there
are no errors in the IPC system.
}
It is important to note that both of these efforts used Promela and
SPIN to model their system.
\section*{Fluke Interprocess Communication}
This section gives the basics of the reliable Fluke IPC mechanism.
Two other forms of IPC in Fluke, One-way and Idempotent, are
described in the glossary.
{\em Reliable IPC} is the mechanism Fluke provides
for general, high-performance, reliable, protected communication.
Reliable IPC in Fluke operates in a stream-oriented model,
in which two threads connect to each other directly
and can send data to each other as if through a pipe.
These connections are symmetrical but half-duplex,
meaning that data can only flow in one direction at a time.
However, the direction of data flow can be reversed
without destroying the connection.
Any Fluke thread can be involved in two reliable IPC connections at once:
any thread may have both a connection to a {\em client} thread,
or a thread that ``called'' it (its {\em caller}),
as well as a connection to a {\em server} thread,
or a thread that it has ``called'' (its {\em callee}).
\com{
These two connections are typically used to form a chain of threads
representing a {\em call stack}.
When a thread makes an invocation to a server,
the server thread is added to the top of the call stack;
when the server thread completes its work and breaks the connection,
it is removed once again from the call stack.
}
Either side of a reliable IPC connection
may be held up arbitrarily long while waiting for the other side.
%e.g. because of page faults in the other task that need to be handled.
Thus, there are no guarantees regarding the ``promptness''
with which a server thread can perform its work and disconnect;
the server thread is essentially dedicated to a particular client thread
for the duration of the IPC operation.
There are two objects supported by the Fluke kernel
which are used to establish IPC connections, {\bf Ports}
and {\bf Port Sets}.
Ports are Fluke objects representing targets for IPC requests.
Ports might represent CORBA or MOM objects, for example,
or in Fluke implementations implementing full protection,
they may be used as secure capabilities.
A single server may maintain a number of ports,
each distinguishing a particular object, client,
or object/client pair.
Port sets are objects that act as a rendezvous point
between client threads attempting to perform IPC to a port
and server threads waiting for incoming IPC requests on one or more ports.
Multiple ports can be attached to a single port set,
and multiple server threads can wait for incoming requests
on a single port set at once.
This allows a single ``pool'' of service threads
to service incoming IPC requests from many ports
(i.e. requests associated with many ``objects'' the server exports).
Note that our model assumes that threads to connect to for IPC
have been ``found'' (the purpose of ports, port sets, and references).
Thus, we will not be implementing models of ports or port sets.
\section*{Modeling}
To accurately model the Fluke IPC implementation we propose
to develop Promela code that will follow Fluke's {\em implementation}
of IPC.
The Fluke implementation is decomposed into layers and
objects. Layers start from the user-level kernel interface and
proceed downward to more and more machine-oriented interfaces.
The objects encapsulate implementation details and provide
interfaces at the various layers. This clean code layout
should make our job much simpler.
There are several ``primitive'' objects that are used
extensively throughout the IPC implementation.
We plan to model and test each independent of the IPC
tests. In addition to supporting our proposal,
this should provide a foundation for
modeling and verification of other parts of the Fluke kernel.
Part of our verification effort will be devoted to
formally describing these objects.
This will facilitate generation of Promela code
modeling these objects.
\com{
Things to model
- Mutex
- Condition variables
- Links (inter-object references)
- Ports/Port Sets
- Thread objects
}%com
The two most basic objects are the {\bf mutex} and
{\bf condition variable}.
Both have very clean, small,
well defined interfaces;
both objects are used throughout the kernel
to synchronize threads and protect kernel data.
The kernel provides {\bf links} which represent
inter-object references. They are used for
encapsulating pointers and for reference counting.
Initially we will model
these as simply as possible; we may add
verification of the reference counting later.
Two objects, {\bf ports} and {\bf port sets} are
used as rendezvous-points in the IPC
(as described above). We will assume that
a thread has a direct handle on the thread it
is communicating with, as such ports and port
sets will not be modeled in our project.
The most important object in our model will be
the {\bf thread} objects. These are the
initiators of all IPC and cancel operations that
we will be interested in. Again, we will only
model the portion of a thread object that is
relevant to IPC. This distinction should be
quite simple because the Fluke thread objects
are compartmentalized quite well already.
To successfully model the
IPC implementation, we will have to come up with
a scaled-down model of the actual code path.
We plan to generate logical control flows directly
from the C source using existing tools.
These flows will help us determine exactly what
we want to model.
%The Setup
In order to verify the cancelability of Fluke IPC
operations we intend to simulate three running
kernel threads involved in a reliable IPC connection.
One thread will be a ``client'' another the ``server''
and the third thread will interpose on the connection.
\psfig(421,224){threads}{
Three threads communicating as client, server, and
interposer. The fourth thread issues
{\tt fluke_thread_cancel()} operations on
the others
at arbitrary times.
}
A fourth thread, the ``rogue canceler'', will issue
{\tt fluke_thread_cancel()} operations to any
of the threads involved in the IPC at arbitrary points
in time (see Figure~\ref{threads}.)
We intend to show that despite the fact that the cancel
thread is canceling complex IPC operations, the thread
state and internal kernel state stay consistent and
none of the involved threads deadlock.
\section*{Verification}
While the descriptive model-generation phase of this project is sure
to generate many fine-grained verifiable properties, we
specify four high-level properties that the Fluke Reliable
IPC system should exhibit.
First, and of most importance to the user, the IPC system should
be proven to provide reliable, correct data delivery to user processes,
or to fail in a well-defined and expected way, under all circumstances.
No allowed "successful" execution path should result in delivery of
partial, out-of-order, or otherwise corrupted data. Furthermore,
no execution path defined in the descriptive phase to be "safe" (ie:
that does not require special user-guarantees) should result in
deadlock or lack of progress.
Second, thread state as visible to the user via the {\tt fluke_thread_get_state()}
function should be consistent and appropriate under all "safe" execution
paths. These paths will include cancellations of IPC operations at
arbitrary points. What constitutes "consistent and appropriate state"
will be defined during the descriptive model-generation process.
If the set of primitive thread operations can be
shown to exhibit "correct" behavior under all circumstances, it
should follow that higher-level functionality is also correct.
For example, we propose that if {\tt fluke_thread_cancel()} can be shown
to be correct, we can conclude that {\tt fluke_thread_get_state()}
is also correct.
Proof of any such propositions will be provided.
Third, thread cancellations occurring at arbitrary points must
not only preserve liveness properties, but also in some circumstances
promptness properties, as determined in the descriptive modeling
phase.
Lastly, thread cancellations must be shown to provide semantically
proper behavior whenever they can legally be applied.
\section*{Results}
We hope to accomplish several things with this project (beyond passing
the course, that is.)
\begin{itemize}
\item We will have a model of the IPC system. In addition to having five more
Flux
team members who are intimately familiar with the Fluke reliable IPC
mechanism, this effort will provide clear documentation for new team
members.
\item We will probably be able to add stronger assertions to the
kernel code, derived from invariants we come up with during
the verification process.
\item We will be able to precisely define what Fluke guarantees
in terms of IPC.
\item We will have a strong infrastructure for verifying other
parts of the kernel implementation.
\end{itemize}
Lastly, there should be five more people with a comprehensive
understanding of formal verification methods as applied to
existing systems.
\com{
\section*{Future Work}
Interaction of Fluke Reliable IPC and DSM protocols.
Verification of memory management.
User-level server/nester verification.
Integration of the verification code/doc with the
kernel source.
}
\section*{Glossary}
\begin{description}
\item[One-Way IPC] An unreliable one-way message send. No
guarantees are made about the delivery of the message, and the sender
does not wait for any type of reply.
\item[Idempotent IPC] Two-way communication, with ``at-least-once''
semantics. The sender waits for a reply, and may have to resend until
a reply is received. Duplicate messages must be tolerable at the
receiver side.
\item[Reliable IPC] Two-way communication, with ``exactly-once''
semantics. In Fluke, reliable IPC connections are half-duplex,
meaning that messages can be sent in only one direction at a time.
\item[Cancel (a.k.a. ``stun'')] A cancel or stun operation is an
interruption of one thread by another, usually done using
the {\tt fluke_thread_cancel()}
call. The Fluke kernel will either allow the stunned thread to
continue execution to the end of an atomic block, or will roll the
stunned thread back to an appropriate (clean and consistent) point.
\item[Rollback] In order to maintain consistent state when an
operation is interrupted, the Fluke kernel sometimes ``undoes'' the
operation, back to a point at which it can be safely restarted at a
later time.
\item[Livelock] A system state in which no meaningful progress
is taking place.
\item[Thread] A thread is the basic unit of execution in the Fluke
model. It executes a particular flow of control for an application.
Multiple threads can be active at once in an application.
% XXX atomic
% XXX ``state''
\end{description}
\bibliography{sys,formal}
\bibliographystyle{abbrv}
\end{document}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 2 19:24:30 2019
@author: ishan
"""
# =============================================================================
# import sys,os
# try:
# sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
# except:
# pass
# =============================================================================
import numpy as np
import cv2
import matplotlib.pyplot as plt
import random
from UndistortImage import UndistortImage
from ReadCameraModel import ReadCameraModel
import math
import glob
def getFundamentalMatrix(x1,x2):
n = x1.shape[1]
A = np.zeros((n,9))
for i in range(n):
A[i] = [x1[0,i]*x2[0,i], x1[0,i]*x2[1,i], x1[0,i],
x1[1,i]*x2[0,i], x1[1,i]*x2[1,i], x1[1,i],
x2[0,i], x2[1,i], 1 ]
U,S,V = np.linalg.svd(A)
F = V[-1].reshape(3,3)
U,S,V = np.linalg.svd(F)
S[2] = 0
F = np.dot(U,np.dot(np.diag(S),V))
return F
def get_R_T(F):
E = np.dot(K.T,np.dot(F,K))
U,S,V = np.linalg.svd(E)
E = np.dot(U,np.dot(np.diag([1,1,0]),V))
U,S,V = np.linalg.svd(E)
W = np.array([[0, -1, 0],
[1, 0, 0],
[0, 0, 1]])
t1 = U[:,2]
t2 = -U[:,2]
t3 = U[:,2]
t4 = -U[:,2]
R1 = np.dot(U,np.dot(W,V))
R2 = np.dot(U,np.dot(W,V))
R3 = np.dot(U,np.dot(W.T,V))
R4 = np.dot(U,np.dot(W.T,V))
# =============================================================================
# R1 = U * W * V
# R2 = U * W * V
# R3 = U * W.T * V
# R4 = U * W.T * V
# =============================================================================
if np.linalg.det(R1)<0:
R1 = -R1
t1 = -t1
elif np.linalg.det(R2)<0:
R2 = -R2
t2 = -t2
elif np.linalg.det(R3)<0:
R3 = -R3
t3 = -t3
elif np.linalg.det(R4)<0:
R4 = -R4
t4 = -t4
P = [np.vstack((R1,t1)).T,
np.vstack((R2,t2)).T,
np.vstack((R3,t3)).T,
np.vstack((R4,t4)).T]
return P
def triangulate(x1,x2,P1,P2):
M = np.zeros((6,6))
M[:3,:4] = P1
M[:2,4] = -x1
M[2,4] = 1
M[3:,:4] = P2
M[3:5,5] = -x2
M[5,5] = 1
U,S,V = np.linalg.svd(M)
X = V[-1,:4]
return X / X[3]
def tri_pts(x1,x2,P1,P2):
n = x1.shape[1]
X = [triangulate(x1[:,i],x2[:,i],P1,P2) for i in range(n)]
return np.array(X).T
x_plot = []
z_plot = []
# =============================================================================
#
# cap = cv2.VideoCapture('road.avi')
# while(True):
# # Capture frame-by-frame
# ret, frame1 = cap.read()
# ret, frame2 = cap.read()
# =============================================================================
# =============================================================================
# path = Path(__file__).parent
# path /= "Oxford_dataset/stereo/centre/*.png"
# for f in path.iterdir():
# print(f) # <--- type: <class 'pathlib.PosixPath'>
# f = str(f) # <--- convert to string
# img=cv2.imread(f)
#
# =============================================================================
car = glob.glob("Oxford_dataset/stereo/centre/*.png")
car.sort()
car_images = [cv2.imread(img, cv2.IMREAD_GRAYSCALE | cv2.IMREAD_ANYDEPTH) for img in car]
print(len(car_images))
a = 0
N = np.zeros((4,4))
h = np.eye(4)
current_pos = np.zeros((3, 1))
current_rot = np.eye(3)
while a < (len(car_images) - 1):
# for i in range(len(car_images)):
#imageRaw1 = cv2.imread(images[i], cv2.IMREAD_GRAYSCALE | cv2.IMREAD_ANYDEPTH)
#rgb1 = cv2.cvtColor(imageRaw1, cv2.COLOR_BAYER_GR2BGR)
rgb1 = cv2.cvtColor(car_images[a], cv2.COLOR_BAYER_GR2BGR)
#imageRaw2 = cv2.imread(frame2, cv2.IMREAD_GRAYSCALE | cv2.IMREAD_ANYDEPTH)
#rgb2 = cv2.cvtColor(imageRaw2, cv2.COLOR_BAYER_GR2BGR)
rgb2 = cv2.cvtColor(car_images[a + 1], cv2.COLOR_BAYER_GR2BGR)
fx, fy, cx, cy, G_camera_image1, LUT1 = ReadCameraModel('Oxford_dataset/model')
undistorted_image1 = UndistortImage(rgb1, LUT1)
undistorted_image1 = cv2.cvtColor(undistorted_image1, cv2.COLOR_BGR2GRAY)
eqimage1= cv2.equalizeHist(undistorted_image1)
fx, fy, cx, cy, G_camera_image2, LUT2 = ReadCameraModel('Oxford_dataset/model')
undistorted_image2 = UndistortImage(rgb2, LUT2)
undistorted_image2 = cv2.cvtColor(undistorted_image2, cv2.COLOR_BGR2GRAY)
eqimage2 = cv2.equalizeHist(undistorted_image2)
K = np.array([[fx, 0, cx],[0, fy, cy],[0, 0, 1]])
# Initiate STAR detector
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(eqimage1,None)
kp2, des2 = orb.detectAndCompute(eqimage2,None)
# create BFMatcher object
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
# Match descriptors.
matches = bf.match(des1,des2)
# Sort them in the order of their distance.
matches = sorted(matches, key = lambda x:x.distance)
good_points = []
for match in matches:
good_points.append(match)
pts1 = np.float32([kp1[match.queryIdx].pt for match in good_points])
pts2 = np.float32([kp2[match.trainIdx].pt for match in good_points])
E,mask = cv2.findEssentialMat(pts2, pts1, K, cv2.FM_RANSAC, 0.999, 1.0, None)
#pts1 = pts1[mask.ravel()==1]
#pts2 = pts2[mask.ravel()==1]
points, R, t, mask = cv2.recoverPose(E, pts2, pts1, K)
# =============================================================================
# s = 0.0
# count = 0
# for i in range(len(pts2) - 1):
# for j in range(i+1,len(pts2)):
# s = np.norm(pts2[i] - pts2[j]) / np.norm(pts1[i] - pts1[j])
#
# s += s
# count += 1
# s /= count
#
# =============================================================================
# =============================================================================
# P1 = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0]])
# P2 = get_R_T(F)
#
# indices = 0
# max_res = 0
# for i in range(4):
# X = tri_pts(pts1.T,pts2.T,P1,P2[i])
# d1 = np.dot(P1,X)[2]
# d2 = np.dot(P2[i],X)[2]
# if np.sum(d1>0) + np.sum(d2>0) > max_res:
# max_res = np.sum(d1>0) + np.sum(d2>0)
# indices = i
# infront = (d1>0) & (d2>0)
#
# X = tri_pts(pts1.T,pts2.T,P1,P2[indices])
# #print(np.dot(P2[indices],X[:,infront])[2])
#
#
#
# P = P2[indices]
# =============================================================================
# =============================================================================
# Rot = P[:3,:3]
# print(Rot)
# Trans = P[:3,3]
# print(Trans)
# current_pos += current_rot.dot(Trans)
# current_rot = np.dot(Rot,current_rot)
# =============================================================================
current_pos += current_rot.dot(t)
current_rot = R.dot(current_rot)
#print('cp',current_pos)
# =============================================================================
# x1 = P[0,3]
# z1 = P[2,3]
# #print(P)
#
# N[:3,:] = P2[indices]
# N[3,:] = [0,0,0,1]
#
#
# h = np.dot(h,N)
# x = h[0,3]
# z = h[2,3]
# =============================================================================
#print(h)
x_plot.append(current_pos[0,0])
z_plot.append(current_pos[2,0])
# =============================================================================
# x_plot.append(-x)
# z_plot.append(z)
# =============================================================================
print(a)
a+= 1
# =============================================================================
# x_plot = np.array(x_plot).reshape(x_plot.shape[0],-1)
# z_plot = np.array(z_plot).reshape(z_plot.shape[0],-1)
# final_array = np.vstack((x_plot,z_plot))
#
# =============================================================================
final_array = []
for i in range(len(x_plot)):
final_array.append((x_plot[i],z_plot[i]))
#print(final_array)
plt.scatter(x_plot,z_plot)
plt.show()
# =============================================================================
# if cv2.waitKey(0) & 0xFF == ord('q'):
# break
#
# =============================================================================
|
module Examples
import Hezarfen
import Hezarfen.Hint
import Hezarfen.Prover
import Hezarfen.Definitions
%language ElabReflection
%default total
-- You can generate proofs as expressions, but it's better to
-- generate definitions instead since they are more readable.
f1 : (a -> b) -> (b -> c) -> a -> c
f1 = %runElab hezarfenExpr
-- `f1` is generated as an expression, the rest will be definitions.
f1' : (a -> b) -> (b -> c) -> a -> c
%runElab (hezarfen `{f1'})
-- You can also use the `derive` syntax.
f2 : (a -> b) -> (b -> c) -> (c -> d) -> a -> d
derive f2
f3 : Either a (Either b c) -> Either (Either a b) c
derive f3
f4 : (a, b, c) -> (c, b, a)
derive f4
f5 : (p -> q, p -> r) -> p -> (q, r)
derive f5
f6 : (((a -> b) -> c) -> d) -> ((a -> b) -> c) -> (a -> b) -> d
derive f6
myFst : (a, b) -> a
derive myFst
mySnd : (a, b) -> b
derive mySnd
demorgan1 : Not (Either p q) -> (Not p, Not q)
derive demorgan1
demorgan2 : (Not p, Not q) -> Not (Either p q)
derive demorgan2
demorgan3 : Either (Not p) (Not q) -> Not (p, q)
derive demorgan3
-- This one is classical so it cannot be proved by Hezarfen
-- demorgan4 : Not (p, q) -> Either (Not p) (Not q)
-- demorgan4 = %runElab hezarfen
noContradiction : Not (p , Not p)
derive noContradiction
contrapositive : (p -> q) -> (Not q -> Not p)
derive contrapositive
-- Examples with default values for some types
nat : Nat
%runElab (hezarfen' `{nat} !(add [`{Z}]))
-- Using the more readable syntax
bool : (Bool, a -> a)
obtain bool from [`{True}]
-- Using a lemma
data Even : Nat -> Type where
EvenZ : Even Z
EvenSS : Even n -> Even (S (S n))
data Odd : Nat -> Type where
Odd1 : Odd 1
OddSS : Odd n -> Odd (S (S n))
evenOrOdd : (n : Nat) -> Either (Even n) (Odd n)
evenOrOdd Z = Left EvenZ
evenOrOdd (S Z) = Right Odd1
evenOrOdd (S (S n)) = case evenOrOdd n of
Left ev => Left $ EvenSS ev
Right o => Right $ OddSS o
-- You can also use a hint database
hint evenOrOdd
hint EvenSS
hint OddSS
oddOrEven : (n : Nat) -> Either (Odd n) (Even n)
derive' oddOrEven -- derive using hints
evenOrOddSS : (n : Nat) -> Either (Even (S (S n))) (Odd (S (S n)))
derive' evenOrOddSS
decUnit : Dec Unit
derive decUnit
decVoid : Dec Void
derive decVoid
swapEither : Either a b -> Either b a
derive swapEither
swapDec : Dec a -> Dec (Not a)
derive swapDec
notDec : Not a -> Dec a
derive notDec
decNotNot : Dec p -> (Not p -> Void) -> p
derive decNotNot
-- Equalities
eq1 : x = x
derive eq1
eq2 : True = True
derive eq2
-- Treat equalities as an atom if it's not obviously solvable
eq3 : (x = y) -> (x = y)
derive eq3
eq4 : True = False -> False = True
derive eq4
eq5 : x = y -> y = x
derive eq5
eqDec : x = y -> Dec (y = x)
derive eqDec
eqEither : Either (x = y) (y = z) -> Either (z = y) (y = x)
derive eqEither
congS : x = y -> S x = S y
derive congS
decCongB : x = y -> Dec (not x = not y)
derive decCongB
twoToThree : (x = y, y = z) -> (z = y, y = y, y = x)
derive twoToThree
doesntLoop : (a -> b) -> (b -> a) -> a -> b
derive doesntLoop
|
#include <boost/hana/minimum.hpp>
|
/*
Copyright 2014 Glen Joseph Fernandes
([email protected])
Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_ALIGN_DETAIL_IS_ALIGNMENT_CONSTANT_HPP
#define BOOST_ALIGN_DETAIL_IS_ALIGNMENT_CONSTANT_HPP
#include <boost/align/detail/integral_constant.hpp>
#include <cstddef>
namespace boost {
namespace alignment {
namespace detail {
template<std::size_t N>
struct is_alignment_constant
: integral_constant<bool, (N > 0) && ((N & (N - 1)) == 0)> { };
} /* detail */
} /* alignment */
} /* boost */
#endif
|
# libpurex:
# oracle computations
# a Pure Exploration problem (pep) is parameterised by
# - a domain, \mathcal M, representing the prior knowledge about the structure
# - a query, as embodied by a correct-answer function istar
#
# To specify a PE problem here, we need to compute the following things:
# - nanswers: number of possible answers
# - istar: correct answer for feasible μ
# - glrt: value and best response (λ and ξ) to (N, ̂μ) or (w, μ)
# - oracle: characteristic time and oracle weights at μ
struct BestArm
expfam; # common exponential family
end
nanswers(pep::BestArm, μ) = length(μ);
istar(pep::BestArm, μ) = argmax(μ);
getexpfam(pep::BestArm, k) = pep.expfam;
function glrt(pep::BestArm, w, μ)
@assert length(size(μ)) == 1
⋆ = argmax(μ); # index of best arm among μ
val, k, θ = minimum(
begin
# transport ⋆ and k to weighted midpoint
θ = (w[⋆]*μ[⋆]+w[k]*μ[k])/(w[⋆]+w[k]);
w[⋆]*d(pep.expfam, μ[⋆], θ) + w[k]*d(pep.expfam, μ[k], θ), k, θ
end
for k in eachindex(μ)
if k != ⋆
);
λ = copy(μ);
λ[⋆] = θ;
λ[k] = θ;
# note: ξs = μ here
val, (k, λ), (⋆, μ);
end
# solve for x such that d(μ1, μx) + x*d(μi, μx) == v
# where μx = (μ1+x*μi)/(1+x)
function X(expfam, μ1, μi, v)
kl1i = d(expfam, μ1, μi); # range of V(x) is [0, kl1i]
@assert 0 ≤ v ≤ kl1i "0 ≤ $v ≤ $kl1i";
α = binary_search(
z -> let μz = (1-z)*μ1+z*μi
(1-z)*d(expfam, μ1, μz) + z*d(expfam, μi, μz) - (1-z)*v
end,
0, 1);
α/(1-α);
end
# oracle problem
function oracle(pep::BestArm, μs)
μstar = maximum(μs);
if all(μs .== μstar) # yes, this happens
return Inf, ones(length(μs))/length(μs);
end
# determine upper range for subsequent binary search
hi = minimum(
d(pep.expfam, μstar, μ)
for μ in μs
if μ != μstar
);
val = binary_search(
z -> sum(
let x = X(pep.expfam, μstar, μ, z),
μx = (μstar + x*μ)/(1+x);
d(pep.expfam, μstar, μx) / d(pep.expfam, μ, μx)
end
for μ in μs
if μ != μstar
) - 1,
0, hi);
ws = [(μ == μstar) ? 1. : X(pep.expfam, μstar, μ, val) for μ in μs];
Σ = sum(ws);
Σ/val, ws ./ Σ;
end
# oracle problem for best μ in confidence interval
function optimistic_oracle(pep::BestArm, hμ, N)
t = sum(N);
μdn = [ddn(pep.expfam, hμ[k], log(t)/N[k]) for k in eachindex(hμ)];
μup = [dup(pep.expfam, hμ[k], log(t)/N[k]) for k in eachindex(hμ)];
# try to make each arm the best-looking arm so far,
# then move everybody else down as far as possible
minimum(oracle(pep,
((k == j) ? μup[k] : μdn[k]
for k in eachindex(hμ)))
for j in eachindex(hμ)
if μup[j] > maximum(μdn)
);
end
struct LargestProfit
expfam;
end
nanswers(pep::LargestProfit, μ) = length(μ)/2;
function istar(pep::LargestProfit, _μs)
μs = reshape(_μs, 2, :);
argmax(μs[1,:]-μs[2,:]); # current best
end
getexpfam(pep::LargestProfit, k) = pep.expfam;
# NOTE this does NOT work for divergences that are non-convex in the
# second argument. Moreover, the problem here seems fundamental.
function glrt(pep::LargestProfit, _ws, _μs)
# convert to 2×K indexing
ws = reshape(_ws, 2, :);
μs = reshape(_μs, 2, :);
K = size(ws, 2);
⋆ = argmax(μs[1,:]-μs[2,:]); # current best
val, k, λ1k, λ2k, λ1s, λ2s = minimum(
begin
# arm k needs to be the best
xmax = 1000; # voodoo
x = binary_search(x ->
+ invh(pep.expfam, μs[1,k], +x/ws[1,k])
- invh(pep.expfam, μs[2,k], -x/ws[2,k])
- invh(pep.expfam, μs[1,⋆], -x/ws[1,⋆])
+ invh(pep.expfam, μs[2,⋆], +x/ws[2,⋆]), 0, xmax);
λ1k = invh(pep.expfam, μs[1,k], +x/ws[1,k]);
λ2k = invh(pep.expfam, μs[2,k], -x/ws[2,k]);
λ1s = invh(pep.expfam, μs[1,⋆], -x/ws[1,⋆]);
λ2s = invh(pep.expfam, μs[2,⋆], +x/ws[2,⋆]);
ws[1,⋆]*d(pep.expfam, μs[1,⋆], λ1s) +
ws[2,⋆]*d(pep.expfam, μs[2,⋆], λ2s) +
ws[1,k]*d(pep.expfam, μs[1,k], λ1k) +
ws[2,k]*d(pep.expfam, μs[2,k], λ2k), k, λ1k, λ2k, λ1s, λ2s
end
for k in 1:K
if k != ⋆
);
_λs = copy(_μs);
λs = reshape(_λs, 2, :);
λs[1,⋆] = λ1s;
λs[2,⋆] = λ2s;
λs[1,k] = λ1k;
λs[2,k] = λ2k;
# note: ξs = μs here
val, (k, _λs), (⋆, _μs);
end
function oracle(pep::LargestProfit, μs)
@warn "oracle for LargestProfit not yet implemented";
nothing, nothing;
end
struct MinimumThreshold
expfam;
γ;
end
nanswers(pep::MinimumThreshold, μ) = 2;
istar(pep::MinimumThreshold, μs) = 1+(minimum(μs) > pep.γ);
getexpfam(pep::MinimumThreshold, k) = pep.expfam;
# answers are encoded as 1 = "<", 2 = ">"
function glrt(pep::MinimumThreshold, ws, μs)
if minimum(μs) < pep.γ
#everybody moves up
λs = max.(μs, pep.γ);
val = sum(k -> ws[k]*d(pep.expfam, μs[k], λs[k]), eachindex(ws));
val, (2, λs), (1, μs);
else
#someone moves down
val, k = minimum(
(ws[k]*d(pep.expfam, μs[k], pep.γ), k)
for k in eachindex(ws));
λs = copy(μs);
λs[k] = pep.γ;
val, (1, λs), (2, μs);
end
end
function oracle(pep::MinimumThreshold, μs)
μstar = minimum(μs);
if μstar < pep.γ
# everything on lowest arm
ws = Float64.(μs .== μstar);
Tstar = 1/d(pep.expfam, μstar, pep.γ);
else
ws = [1/d(pep.expfam, μ, pep.γ) for μ in μs];
Tstar = sum(ws);
end
Tstar, ws ./ sum(ws);
end
# oracle problem for best μ in confidence interval
function optimistic_oracle(pep::MinimumThreshold, hμ, N)
t = sum(N);
μdn = (ddn(pep.expfam, hμ[k], log(t)/N[k]) for k in eachindex(hμ));
μup = (dup(pep.expfam, hμ[k], log(t)/N[k]) for k in eachindex(hμ));
if minimum(μup) < pep.γ
# entire conf. interval below
oracle(pep, μdn);
elseif minimum(μdn) > pep.γ
# entire conf. interval above
oracle(pep, μup);
else
# both options in conf. interval. Take best
min(oracle(pep, μup),
oracle(pep, μdn));
end
end
# Best arm with a simplex constraint on μ
struct BestArmSimplex
end
# all arms on same side of threshold
# interesting because ̂μ can be outside
struct SameSign
expfam;
γ; # threshold
end
nanswers(pep::SameSign, μ) = 2;
# answer 1 is everyone below,
# answer 2 is everyone above
function istar(pep::SameSign, μ)
if all(μ .≤ pep.γ)
1
elseif all(μ .≥ pep.γ)
2
else
@assert false "infeasible bandit model $μ";
end
end
getexpfam(pep::SameSign, k) = pep.expfam;
function glrt(pep::SameSign, w, μ)
μlo = min.(pep.γ, μ); # lower everyone
μhi = max.(pep.γ, μ); # raise everyone
dlo = sum(k -> w[k]*d(pep.expfam, μ[k], μlo[k]), eachindex(μ));
dhi = sum(k -> w[k]*d(pep.expfam, μ[k], μhi[k]), eachindex(μ));
if dlo < dhi
dhi-dlo, (2, μhi), (1, μlo);
else
dlo-dhi, (1, μlo), (2, μhi);
end
end
function oracle(pep::SameSign, μ)
@assert all(μ .≤ pep.γ) || all(μ .≥ pep.γ) "infeasible bandit model $μ";
v, i = findmax([d(pep.expfam, μ[k], pep.γ) for k in eachindex(μ)]);
1/v, Float64.(eachindex(μ).==i)
end
# two arms with equal means but different exponential family (e.g. variance).
# question if they are above/below the threshold γ
# do algorithms pull the low variance one too often?
struct HeteroSkedastic
expfams; # two(!) exponential families
γ;
end
nanswers(pep::HeteroSkedastic, μ) = 2;
function istar(pep::HeteroSkedastic, μ)
@assert length(μ) == 2;
@assert abs(μ[1] - μ[2]) < 1e-4 "unequal $μ";
1 + (μ[1] > pep.γ);
end
getexpfam(pep::HeteroSkedastic, k) = pep.expfams[k];
function glrt(pep::HeteroSkedastic, w, μ)
# compute ξ
xmax = 400; # voodoo
if minimum(w) > 1e-5
x = binary_search(x ->
+ invh(pep.expfams[1], μ[1], +x/w[1])
- invh(pep.expfams[2], μ[2], -x/w[2]), -xmax, xmax);
ξ = [invh(pep.expfams[1], μ[1], +x/w[1]),
invh(pep.expfams[2], μ[2], -x/w[2])];
else
ξ = [w'μ, w'μ]; # two copies of the average
end
⋆ = istar(pep, ξ);
λ = [pep.γ, pep.γ];
val = sum(k -> w[k]*(d(pep.expfams[k], μ[k], λ[k]) -
d(pep.expfams[k], μ[k], ξ[k])), 1:2);
val, (3-⋆, λ), (⋆, ξ);
end
function oracle(pep::HeteroSkedastic, μ)
v, i = findmax([d(pep.expfams[k], μ[k], pep.γ) for k in eachindex(μ)]);
1/v, Float64.(eachindex(μ).==i)
end
|
# Date functions for parsing like: mdy, ymd, ydm, dmy, mdy
month_seq <- seq(as.Date("2000-01-01"), as.Date("2000-12-31"), "month")
months <- factor(months(month_seq), levels = months(month_seq))
months_abbr <- factor(months(month_seq, TRUE), levels = months(month_seq, TRUE))
wday_seq <- seq(as.Date("2000-01-02"), as.Date("2000-01-08"), "day")
wdays <- factor(weekdays(wday_seq), levels = weekdays(wday_seq))
wdays_abbr <- factor(weekdays(wday_seq, TRUE), levels = weekdays(wday_seq, TRUE))
second <- function(x) as.POSIXlt(x)$sec
minute <- function(x) as.POSIXlt(x)$min
hour <- function(x) as.POSIXlt(x)$hour
yday <- function(x) as.POSIXlt(x)$yday + 1
wday <- function(x) as.POSIXlt(x)$wday + 1
mday <- function(x) as.POSIXlt(x)$mday
week <- function(x) yday(x) %/% 7 + 1
month <- function(x) as.POSIXlt(x)$mon + 1
year <- function(x) as.POSIXlt(x)$year + 1900
tz <- function(x) {
tzs <- attr(as.POSIXlt(x),"tzone")
tzs[length(tzs)]
}
"second<-" <- function(x, value) as.POSIXlt(x) - (second(x) - value)
"minute<-" <- function(x, value) as.POSIXlt(x) - (minute(x) - value) * 60
"hour<-" <- function(x, value) as.POSIXlt(x) - (hour(x) - value) * 3600
"yday<-" <- function(x, value) as.POSIXlt(x) - (yday(x) - value) * 3600 * 24
"wday<-" <- function(x, value) as.POSIXlt(x) - (wday(x) - value) * 3600 * 24
"mday<-" <- function(x, value) as.POSIXlt(x) - (mday(x) - value) * 3600 * 24
"week<-" <- function(x, value) as.POSIXlt(x) - (week(x) - value) * 3600 * 24 * 7
"month<-" <- function(x, value) {
ISOdatetime(year(x) + (value - 1) %/% 12, (value - 1) %% 12 + 1, mday(x), hour(x), minute(x), second(x), tz(x))
}
"year<-" <- function(x, value) {
ISOdatetime(value, month(x), mday(x), hour(x), minute(x), second(x), tz(x))
}
"tz<-" <- function(x, value) {
ISOdatetime(year(x), month(x), mday(x), hour(x), minute(x), second(x), value)
}
|
using TensorKit
using statmech_tm_solver
#log(1+sqrt(2))/2
#T = mpo_square_ising(log(1+sqrt(2))/2)
T = mpo_triangular_AF_ising_alternative()
#T = mpo_triangular_AF_ising()
psi = bimps(rand, 12, 4)
for ix in 1:50
global psi
λA, psi = A_canonical(T, psi)
λB, psi = B_canonical(T, psi)
print("$ix, $λA $λB ")
println(' ', free_energy(T, psi.B), ' ', free_energy(T, psi.A))
end |
= = Modern perspectives = =
|
Require Import Coq.Strings.String.
Require Import Coq.Lists.List.
Require Import Coq.Init.Datatypes.
Require Import Coq.Arith.PeanoNat.
Require Export SystemFR.FVLemmas.
Lemma fv_close:
forall t k x y,
y ∈ pfv (close k t x) term_var ->
y <> x /\ y ∈ pfv t term_var.
Proof.
induction t;
repeat step || list_utils || instantiate_any;
eauto 3 using fv_close1;
eauto with eapply_any.
Qed.
Lemma fv_tclose:
forall t k x y,
y ∈ pfv (tclose k t x) term_var ->
y ∈ pfv t term_var.
Proof.
induction t;
repeat step || list_utils || instantiate_any;
eauto with eapply_any.
Qed.
Lemma fv_close_same:
forall t k x,
x ∈ pfv (close k t x) term_var ->
False.
Proof.
intros; apply_anywhere fv_close; steps.
Qed.
Lemma tfv_tclose:
forall t k x y,
y ∈ pfv (tclose k t x) type_var ->
y <> x /\ y ∈ pfv t type_var.
Proof.
induction t;
repeat step || list_utils || instantiate_any;
eauto 3 using tfv_close1;
eauto with eapply_any.
Qed.
Lemma tfv_close:
forall t k x y,
y ∈ pfv (close k t x) type_var ->
y ∈ pfv t type_var.
Proof.
induction t;
repeat step || list_utils || instantiate_any;
eauto with eapply_any.
Qed.
Lemma tfv_tclose_same:
forall t k x,
x ∈ pfv (tclose k t x) type_var ->
False.
Proof.
induction t;
repeat step || list_utils; eauto.
Qed.
Ltac fv_close :=
match goal with
| H: _ ∈ pfv (close _ _ _) term_var |- _ =>
poseNew (Mark H "fv_close");
unshelve epose proof (fv_close _ _ _ _ H)
| H: _ ∈ pfv (tclose _ _ _) term_var |- _ =>
poseNew (Mark H "fv_close");
unshelve epose proof (fv_tclose _ _ _ _ H)
| H: _ ∈ pfv (close _ _ _) type_var |- _ =>
poseNew (Mark H "fv_close");
unshelve epose proof (tfv_close _ _ _ _ H)
| H: _ ∈ pfv (tclose _ _ _) type_var |- _ =>
poseNew (Mark H "fv_close");
unshelve epose proof (tfv_tclose _ _ _ _ H)
end.
Lemma fv_close_nil:
forall t k X,
pfv t term_var = nil ->
pfv (tclose k t X) term_var = nil.
Proof.
induction t;
repeat step || list_utils.
Qed.
Lemma fv_close_nil2:
forall t k x,
subset (pfv t term_var) (x :: nil) ->
pfv (close k t x) term_var = nil.
Proof.
induction t; repeat step || list_utils || sets.
Qed.
Lemma pfv_close: forall x nf t tag i,
x <> nf -> x ∈ (pfv t tag) -> x ∈ (pfv (close i t nf) tag).
Proof.
induction t; repeat light || destruct_match || list_utils.
Qed.
|
# Regression model—sound exposure level
This notebook explores and models the data collected from recordings of the natural acoustic environment over the urban-rural gradient near Innsbruck, Austria. The models are implemented as Bayesian models with the PyMC3 probabilistic programming library.
References:<br />
https://github.com/fonnesbeck/multilevel_modeling<br />
Gelman, A., & Hill, J. (2006). Data Analysis Using Regression and Multilevel/Hierarchical Models (1st ed.). Cambridge University Press.
#### Import statements
```python
import warnings
warnings.filterwarnings('ignore')
```
```python
import pandas
import numpy
from os import path
```
```python
%matplotlib inline
from matplotlib import pyplot
from matplotlib.patches import Rectangle
import seaborn
```
```python
from pymc3 import glm, Model, NUTS, sample, stats, \
forestplot, traceplot, plot_posterior, summary, \
Normal, Uniform, Deterministic, StudentT
from pymc3.backends import SQLite
```
#### Plot settings
```python
from matplotlib import rcParams
```
```python
rcParams['font.sans-serif']
```
['DejaVu Sans',
'Bitstream Vera Sans',
'Computer Modern Sans Serif',
'Lucida Grande',
'Verdana',
'Geneva',
'Lucid',
'Arial',
'Helvetica',
'Avant Garde',
'sans-serif']
```python
rcParams['font.sans-serif'] = ['Helvetica',
'Arial',
'Bitstream Vera Sans',
'DejaVu Sans',
'Lucida Grande',
'Verdana',
'Geneva',
'Lucid',
'Avant Garde',
'sans-serif']
```
#### Variable definitions
```python
data_filepath = "/Users/Jake/OneDrive/Documents/alpine soundscapes/data/dataset.csv"
```
```python
trace_output_path = "/Users/Jake/OneDrive/Documents/alpine soundscapes/data/model traces/sel"
```
```python
seaborn_blue = seaborn.color_palette()[0]
```
## Load data
```python
data = pandas.read_csv(data_filepath)
data = data.loc[data.site<=30]
```
sort data by site and then by visit
```python
data_sorted = data.sort_values(by=['site', 'sound']).reset_index(drop=True)
```
transform variables (mean center)
```python
column_list = ['sel', 'sel_anthrophony', 'sel_biophony', 'biophony', 'week',
'building_50m', 'pavement_50m', 'forest_50m', 'field_50m',
'building_100m', 'pavement_100m', 'forest_100m', 'field_100m',
'building_200m', 'pavement_200m', 'forest_200m', 'field_200m',
'building_500m', 'pavement_500m', 'forest_500m', 'field_500m',
'd2n_50m', 'd2n_100m', 'd2n_200m', 'd2n_500m',
'temperature', 'wind_speed', 'pressure', 'bus_stop',
'construction', 'crossing', 'cycleway', 'elevator', 'escape', 'footway',
'living_street', 'motorway', 'motorway_link', 'path', 'pedestrian',
'platform', 'primary_road', 'primary_link', 'proposed', 'residential',
'rest_area', 'secondary', 'secondary_link', 'service', 'services',
'steps', 'tertiary', 'tertiary_link', 'track', 'unclassified', 'combo']
data_centered = data_sorted.copy()
for column in column_list:
data_centered[column] = data_sorted[column] - data_sorted[column].mean()
```
create sites variable for PyMC3 models
```python
sites = numpy.copy(data_sorted.site.values) - 1
```
## Model 0 - emtpy model
$$
\begin{align}
y_{ts} \sim \mathcal{N}(\alpha_s + \epsilon_t, \sigma_y^2) \\
\alpha_s \sim \mathcal{N}(M + \epsilon_s, \sigma_\alpha^2) \\
\end{align}
$$
```python
with Model() as model0:
# Priors
mu_grand = Normal('mu_grand', mu=0., tau=0.0001)
sigma_a = Uniform('sigma_a', lower=0, upper=100)
tau_a = sigma_a**-2
# Random intercepts
a = Normal('a', mu=mu_grand, tau=tau_a, shape=len(set(sites)))
# Model error
sigma_y = Uniform('sigma_y', lower=0, upper=100)
tau_y = sigma_y**-2
# Expected value
y_hat = a[sites]
# Data likelihood
y_like = Normal('y_like', mu=y_hat, tau=tau_y, observed=data_centered.sel)
# sample model
backend = SQLite(path.join(trace_output_path, "model0.sqlite"))
model0_samples = sample(draws=10000, step=NUTS(), random_seed=1, trace=backend)
```
100%|██████████| 10500/10500 [00:20<00:00, 511.43it/s]
```python
fig, ax = pyplot.subplots()
# organize results
model0_data = pandas.DataFrame({'site': data_sorted.site.unique(),
'site_name': data_sorted.site_name.unique()}).set_index('site')
model0_data['forest_200m'] = data.groupby('site')['forest_200m'].mean()
model0_data['quantiles'] = [stats.quantiles(model0_samples.a[:5000, i]) for i in range(len(set(sites)))]
# plot quantiles
for i, row in model0_data.sort_values(by='forest_200m').iterrows():
x = row['forest_200m']
ax.plot([x, x], [row['quantiles'][2.5], row['quantiles'][97.5]], color='black', linewidth=0.5)
ax.plot([x, x], [row['quantiles'][25], row['quantiles'][75]], color='black', linewidth=1)
ax.scatter([x], [row['quantiles'][50]], color='black', marker='o')
# format plot
l1 = ax.set_xlim([0, 100])
xl = ax.set_xlabel("forest land cover within 200 meters (percent area)")
yl = ax.set_ylabel("SEL (difference from grand mean)")
```
```python
fig, ax = pyplot.subplots()
# organize results
model0_data = pandas.DataFrame({'site': data_sorted.site.unique(),
'site_name': data_sorted.site_name.unique()}).set_index('site')
model0_data['d2n_200m'] = data.groupby('site')['d2n_200m'].mean()
model0_data['quantiles'] = [stats.quantiles(model0_samples.a[:5000, i]) for i in range(len(set(sites)))]
# plot quantiles
for i, row in model0_data.sort_values(by='d2n_200m').iterrows():
x = row['d2n_200m']
ax.plot([x, x], [row['quantiles'][2.5], row['quantiles'][97.5]], color='black', linewidth=0.5)
ax.plot([x, x], [row['quantiles'][25], row['quantiles'][75]], color='black', linewidth=1)
ax.scatter([x], [row['quantiles'][50]], color='black', marker='o')
# format plot
l1 = ax.set_xlim([0, 100])
xl = ax.set_xlabel("d2n within 200 meters (percent area)")
yl = ax.set_ylabel("SEL (difference from grand mean)")
```
## Model 1—time and site predictors
$$
\begin{align}
\text{level 1} \\
y_{ts} \sim \mathcal{N}(\alpha_s + \beta_s T_t, \sigma_y^2) \\
\text{level 2} \\
\alpha_s \sim \mathcal{N}(\gamma_\alpha + \gamma_{\alpha s} L_s, \sigma_\alpha^2) \\
\beta_s \sim \mathcal{N}(\gamma_\beta + \gamma_{\beta s} L_s, \sigma_\beta^2) \\
\end{align}
$$
```python
site_predictors = [
# 'building_50m', 'pavement_50m', 'forest_50m', 'field_50m',
# 'building_100m', 'pavement_100m', 'forest_100m', 'field_100m',
# 'building_200m', 'pavement_200m', 'forest_200m', 'field_200m',
# 'building_500m', 'pavement_500m', 'forest_500m', 'field_500m',
'd2n_50m', 'd2n_100m', 'd2n_200m', 'd2n_500m',
]
for predictor in site_predictors:
with Model() as model_1:
# intercept
g_a = Normal('g_a', mu=0, tau=0.001)
g_as = Normal('g_as', mu=0, tau=0.001)
sigma_a = Uniform('sigma_a', lower=0, upper=100)
tau_a = sigma_a**-2
mu_a = g_a + (g_as * data_centered.groupby('site')[predictor].mean())
a = Normal('a', mu=mu_a, tau=tau_a, shape=len(set(sites)))
# slope
g_b = Normal('g_b', mu=0, tau=0.001)
g_bs = Normal('g_bs', mu=0, tau=0.001)
sigma_b = Uniform('sigma_b', lower=0, upper=100)
tau_b = sigma_b**-2
mu_b = g_b + (g_bs * data_centered.groupby('site')[predictor].mean())
b = Normal('b', mu=mu_b, tau=tau_b, shape=len(set(sites)))
# model error (data-level)
sigma_y = Uniform('sigma_y', lower=0, upper=100)
tau_y = sigma_y**-2
# expected values
y_hat = a[sites] + (b[sites] * data_centered.week)
# likelihood
y_like = Normal('y_like', mu=y_hat, tau=tau_y, observed=data_centered.sel)
# simulated
#y_sim = Normal('y_sim', mu=y_hat, tau=tau_y, shape=y_hat.tag.test_value.shape)
# sample model
backend = SQLite(path.join(trace_output_path, "model1_{}.sqlite".format(predictor)))
model_1_samples = sample(draws=10000, step=NUTS(), random_seed=1, trace=backend)
```
100%|██████████| 10500/10500 [02:37<00:00, 66.46it/s]
100%|██████████| 10500/10500 [04:49<00:00, 36.27it/s]
100%|██████████| 10500/10500 [01:18<00:00, 133.27it/s]
100%|██████████| 10500/10500 [01:18<00:00, 134.29it/s]
```python
fig = pyplot.figure()
fig.set_figwidth(6.85)
fig.set_figheight(6.85/2)
ax_a = pyplot.subplot2grid((1, 2), (0, 0), rowspan=1, colspan=1)
ax_b = pyplot.subplot2grid((1, 2), (0, 1), rowspan=1, colspan=1, sharex=ax_a)
fig.subplots_adjust(left=0, bottom=0, right=1, top=1)
# organize results
model_1_data = pandas.DataFrame({'site': data_sorted.site.unique(),
'site_name': data_sorted.site_name.unique()})
model_1_data['forest_200m'] = data_sorted.forest_200m.unique()
model_1_data['quantiles_a'] = [stats.quantiles(model_1_samples['a'][:5000][:, i]) for i in range(len(set(sites)))]
model_1_data['quantiles_b'] = [stats.quantiles(model_1_samples['b'][:5000][:, i]) for i in range(len(set(sites)))]
# plot quantiles
for i, row in model_1_data.sort_values(by='forest_200m').iterrows():
x = row['forest_200m']
#ax_a.plot([x, x], [row['quantiles_a'][2.5], row['quantiles_a'][97.5]], color='black', linewidth=0.5)
ax_a.plot([x, x], [row['quantiles_a'][25], row['quantiles_a'][75]], color='black', linewidth=1)
ax_a.scatter([x], [row['quantiles_a'][50]], color='black', marker='o')
# format plot
l1 = ax_a.set_xlim([0, 100])
xl = ax_a.set_xlabel("forest land cover within 200 meters (percent area)")
yl = ax_a.set_ylabel("sel (decibel difference from grand mean)")
# plot quantiles
for i, row in model_1_data.sort_values(by='forest_200m').iterrows():
x = row['forest_200m']
#ax_b.plot([x, x], [row['quantiles_b'][2.5], row['quantiles_b'][97.5]], color='black', linewidth=0.5)
ax_b.plot([x, x], [row['quantiles_b'][25], row['quantiles_b'][75]], color='black', linewidth=1)
ax_b.scatter([x], [row['quantiles_b'][50]], color='black', marker='o')
# format plot
l1 = ax_b.set_xlim([0, 100])
l2 = ax_b.set_ylim((-2, 2))
xl = ax_b.set_xlabel("forest land cover within 200 meters (percent area)")
yl = ax_b.set_ylabel("rate of change of sel (dB/week)")
```
```python
fig = pyplot.figure()
fig.set_figwidth(6.85)
fig.set_figheight(6.85/2)
ax_a = pyplot.subplot2grid((1, 2), (0, 0), rowspan=1, colspan=1)
ax_b = pyplot.subplot2grid((1, 2), (0, 1), rowspan=1, colspan=1, sharex=ax_a)
fig.subplots_adjust(left=0, bottom=0, right=1, top=1)
# organize results
model_1_data = pandas.DataFrame({'site': data_sorted.site.unique(),
'site_name': data_sorted.site_name.unique()})
model_1_data['d2n_500m'] = data_sorted.d2n_500m.unique()
model_1_data['quantiles_a'] = [stats.quantiles(model_1_samples['a'][:5000][:, i]) for i in range(len(set(sites)))]
model_1_data['quantiles_b'] = [stats.quantiles(model_1_samples['b'][:5000][:, i]) for i in range(len(set(sites)))]
# plot quantiles
for i, row in model_1_data.sort_values(by='d2n_500m').iterrows():
x = row['d2n_500m']
#ax_a.plot([x, x], [row['quantiles_a'][2.5], row['quantiles_a'][97.5]], color='black', linewidth=0.5)
ax_a.plot([x, x], [row['quantiles_a'][25], row['quantiles_a'][75]], color='black', linewidth=1)
ax_a.scatter([x], [row['quantiles_a'][50]], color='black', marker='o')
# format plot
l1 = ax_a.set_xlim([0, 0.6])
xl = ax_a.set_xlabel("d2n within 500 meters (percent area)")
yl = ax_a.set_ylabel("sel (decibel difference from grand mean)")
# plot quantiles
for i, row in model_1_data.sort_values(by='d2n_500m').iterrows():
x = row['d2n_500m']
#ax_b.plot([x, x], [row['quantiles_b'][2.5], row['quantiles_b'][97.5]], color='black', linewidth=0.5)
ax_b.plot([x, x], [row['quantiles_b'][25], row['quantiles_b'][75]], color='black', linewidth=1)
ax_b.scatter([x], [row['quantiles_b'][50]], color='black', marker='o')
# format plot
l1 = ax_b.set_xlim([0, 0.6])
l2 = ax_b.set_ylim((-2, 2))
xl = ax_b.set_xlabel("d2n within 500 meters (percent area)")
yl = ax_b.set_ylabel("rate of change of sel (dB/week)")
```
## Model 2—environmental predictors
$$
\begin{align}
\text{level 1} \\
y_{ts} \sim \mathcal{N}(\alpha_s + \beta_s T_t, \sigma_y^2) \\
\text{level 2} \\
\alpha_s \sim \mathcal{N}(\gamma_\alpha + \gamma_{\alpha s} L_s, \sigma_\alpha^2) \\
\beta_s \sim \mathcal{N}(\gamma_\beta + \gamma_{\beta s} L_s, \sigma_\beta^2) \\
\end{align}
$$
```python
measurement_predictors = [
'temperature', 'wind_speed', 'precipitation', 'pressure',
]
for predictor in measurement_predictors:
with Model() as model2a:
# intercept
g_a = Normal('g_a', mu=0, tau=0.001)
g_as = Normal('g_as', mu=0, tau=0.001)
sigma_a = Uniform('sigma_a', lower=0, upper=100)
tau_a = sigma_a**-2
mu_a = g_a + (g_as * data_centered.groupby('site')['forest_200m'].mean())
a = Normal('a', mu=mu_a, tau=tau_a, shape=len(set(sites)))
# time slope
g_b = Normal('g_b', mu=0, tau=0.001)
g_bs = Normal('g_bs', mu=0, tau=0.001)
sigma_b = Uniform('sigma_b', lower=0, upper=100)
tau_b = sigma_b**-2
mu_b = g_b + (g_bs * data_centered.groupby('site')['forest_200m'].mean())
b = Normal('b', mu=mu_b, tau=tau_b, shape=len(set(sites)))
# temp slope
#g_c = Normal('g_c', mu=0, tau=0.001)
#g_cs = Normal('g_cs', mu=0, tau=0.001)
#sigma_c = Uniform('sigma_c', lower=0, upper=100)
#tau_c = sigma_c**-2
#mu_c = g_c + (g_cs * data_centered.groupby('site')['forest_200m'].mean())
#c = Normal('c', mu=mu_c, tau=tau_c, shape=len(set(sites)))
c = Uniform('c', lower=-100, upper=100)
# model error (data-level)
sigma_y = Uniform('sigma_y', lower=0, upper=100)
tau_y = sigma_y**-2
# expected values
y_hat = a[sites] + (b[sites] * data_centered.week) + (c * data_centered[predictor])
# likelihood
y_like = Normal('y_like', mu=y_hat, tau=tau_y, observed=data_centered.sel)
# simulated
#y_sim = Normal('y_sim', mu=y_hat, tau=tau_y, shape=y_hat.tag.test_value.shape)
# sample model
backend = SQLite(path.join(trace_output_path, "model2a_{0}.sqlite".format(predictor)))
model_2_samples = sample(draws=10000, step=NUTS(), random_seed=1, trace=backend)
```
100%|██████████| 10000/10000 [08:59<00:00, 18.53it/s]
100%|██████████| 10000/10000 [08:49<00:00, 18.90it/s]
100%|██████████| 10000/10000 [11:56<00:00, 44.45it/s]
100%|██████████| 10000/10000 [17:43<00:00, 9.41it/s]
```python
measurement_predictors = [
'temperature', 'wind_speed', 'precipitation', 'pressure',
]
for predictor in measurement_predictors:
with Model() as model2b:
# intercept
g_a = Normal('g_a', mu=0, tau=0.001)
g_as = Normal('g_as', mu=0, tau=0.001)
sigma_a = Uniform('sigma_a', lower=0, upper=100)
tau_a = sigma_a**-2
mu_a = g_a + (g_as * data_centered.groupby('site')['forest_200m'].mean())
a = Normal('a', mu=mu_a, tau=tau_a, shape=len(set(sites)))
# time slope
g_b = Normal('g_b', mu=0, tau=0.001)
g_bs = Normal('g_bs', mu=0, tau=0.001)
sigma_b = Uniform('sigma_b', lower=0, upper=100)
tau_b = sigma_b**-2
mu_b = g_b + (g_bs * data_centered.groupby('site')['forest_200m'].mean())
b = Normal('b', mu=mu_b, tau=tau_b, shape=len(set(sites)))
# predictor slope
g_c = Normal('g_c', mu=0, tau=0.001)
g_cs = Normal('g_cs', mu=0, tau=0.001)
sigma_c = Uniform('sigma_c', lower=0, upper=100)
tau_c = sigma_c**-2
mu_c = g_c + (g_cs * data_centered.groupby('site')['forest_200m'].mean())
c = Normal('c', mu=mu_c, tau=tau_c, shape=len(set(sites)))
# model error (data-level)
sigma_y = Uniform('sigma_y', lower=0, upper=100)
tau_y = sigma_y**-2
# expected values
y_hat = a[sites] + (b[sites] * data_centered.week) + (c[sites] * data_centered[predictor])
# likelihood
y_like = Normal('y_like', mu=y_hat, tau=tau_y, observed=data_centered.sel)
# simulated
#y_sim = Normal('y_sim', mu=y_hat, tau=tau_y, shape=y_hat.tag.test_value.shape)
# sample model
backend = SQLite(path.join(trace_output_path, "model2b_{0}.sqlite".format(predictor)))
model_2_samples = sample(draws=10000, step=NUTS(), random_seed=1, trace=backend)
```
INFO (theano.gof.compilelock): Waiting for existing lock by process '29643' (I am process '29703')
INFO (theano.gof.compilelock): To manually release the lock, delete /Users/Jake/.theano/compiledir_Darwin-16.6.0-x86_64-i386-64bit-i386-3.5.2-64/lock_dir
100%|██████████| 10000/10000 [18:10<00:00, 9.17it/s]
100%|██████████| 10000/10000 [17:21<00:00, 9.60it/s]
100%|██████████| 10000/10000 [1:17:41<00:00, 2.60it/s]
100%|██████████| 10000/10000 [19:32<00:00, 8.53it/s]
```python
fig, ax = pyplot.subplots()
# organize results
model_2_data = pandas.DataFrame({'site': data_sorted.site.unique(),
'site_name': data_sorted.site_name.unique()})
model_2_data['forest_200m'] = data_sorted.forest_200m.unique()
model_2_data['quantiles'] = [stats.quantiles(model_2_samples['c'][:1000][:, i]) for i in range(len(set(sites)))]
# plot quantiles
for i, row in model_2_data.sort_values(by='forest_200m').iterrows():
x = row['forest_200m']
ax.plot([x, x], [row['quantiles'][2.5], row['quantiles'][97.5]], color='black', linewidth=0.5)
ax.plot([x, x], [row['quantiles'][25], row['quantiles'][75]], color='black', linewidth=1)
ax.scatter([x], [row['quantiles'][50]], color='black', marker='o')
# format plot
l1 = ax.set_xlim([0, 100])
xl = ax.set_xlabel("forest land cover within 200 meters (percent area)")
yl = ax.set_ylabel("percent biophony (difference from grand mean)")
```
|
# This is the user-interface definition of a Shiny web application.
# You can find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com
#
library(shiny)
shinyUI(fluidPage(
titlePanel("Using Geolocation"),
tags$script('
$(document).ready(function () {
function getLocation(callback){
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
navigator.geolocation.getCurrentPosition(onSuccess, onError);
function onError (err) {
Shiny.onInputChange("geolocation", false);
}
function onSuccess (position) {
setTimeout(function () {
var coords = position.coords;
var timestamp = new Date();
console.log(coords.latitude + ", " + coords.longitude, "," + coords.accuracy);
Shiny.onInputChange("geolocation", true);
Shiny.onInputChange("lat", coords.latitude);
Shiny.onInputChange("long", coords.longitude);
Shiny.onInputChange("accuracy", coords.accuracy);
Shiny.onInputChange("time", timestamp)
console.log(timestamp);
if (callback) {
callback();
}
}, 1100)
}
}
var TIMEOUT = 1000; //SPECIFY
var started = false;
function getLocationRepeat(){
//first time only - no delay needed
if (!started) {
started = true;
getLocation(getLocationRepeat);
return;
}
setTimeout(function () {
getLocation(getLocationRepeat);
}, TIMEOUT);
};
getLocationRepeat();
});
'),
# Show a plot of the generated distribution
fluidRow(column(width = 5,
verbatimTextOutput("lat"),
verbatimTextOutput("long"),
verbatimTextOutput("geolocation"),
verbatimTextOutput("accuracy"),
verbatimTextOutput("time"))
)
)
)
|
subroutine potrdf (ia)
c this programm uses akeato(bkeato),aprdev,multrk,yzkrdf
implicit double precision (a-h,o-z)
common cg(251,30), cp(251,30), bg(10,30), bp(10,30),
1 fl(30), fix(30), ibgp
common/comdir/cl,dz,dg(251),ag(10),dp(251),ap(10),dv(251),av(10),
2 eg(251),ceg(10),ep(251),cep(10)
c dg,dp to get data from yzkrdf, dv,eg,ep -output for soldir
dimension at(251),bt(251)
common/itescf/testy,rap(2),teste,nz,norb,norbsc
common/ratom1/xnel(30),en(30),scc(30),scw(30),sce(30),
1nq(30),kap(30),nmax(30)
common/scrhf1/eps(435),nre(30),ipl
common/snoyau/dvn(251),anoy(10),nuc
common/tabtes/hx,dr(251),test1,test2,ndor,np,nes,method,idim
dimension bgj(10),bpj(10)
c#mn
external akeato, bkeato, aprdev
do i=1,ndor
cep(i)=0.0d 00
ceg(i)=0.0d 00
av(i)=anoy(i)
enddo
do i=1,idim
at(i)=0.0d 00
bt(i)=0.0d 00
ep(i)=0.0d 00
eg(i)=0.0d 00
dv(i)=0.0d 00
enddo
c coulomb terms
jia=2* abs(kap(ia))-1
k=0
21 continue
do i=1,idim
dg(i)=0.0d 00
enddo
do i=1,ndor
ag(i)=0.0d 00
enddo
max0=0
do j=1,norb
do i = 1,10
bgj(i) = bg(i,j)
bpj(i) = bp(i,j)
enddo
m=2* abs(kap(j))-1
if (k.le.m) then
a=akeato(ia,j,k)/xnel(ia)
if (a.ne.0.0d 00) then
m=nmax(j)
do i=1,m
dg(i)=dg(i)+a*(cg(i,j)*cg(i,j)+cp(i,j)*cp(i,j))
enddo
n=2* abs(kap(j))-k
l=ndor+2-n
if (l.gt.0) then
c quick fix of development coefficients
a = a * fix(j)**2
do i=1,l
m=n-2+i
ag(m)=ag(m)+a*(aprdev(bgj,bgj,i)+
1 aprdev(bpj,bpj,i))
enddo
endif
endif
endif
max0= max(max0,nmax(j))
enddo
call yzkrdf (0,max0,k)
do i=1,ndor
l=k+i+3
if (l.le.ndor) then
av(l)=av(l)-ag(i)
endif
enddo
do i=1,idim
dv(i)=dv(i)+dg(i)
enddo
k=k+2
if (k.le.ndor) av(k)=av(k)+ap(1)
if (k.lt.jia) go to 21
c exchange terms
if (method.ne.0) then
do j=1,norb
if (j.ne.ia) then
max0=nmax(j)
jj=2* abs(kap(j))-1
kma=(jj+jia)/2
k= abs(jj-kma)
if ((kap(j)*kap(ia)).lt.0) k=k+1
111 continue
a=bkeato(j,ia,k)/xnel(ia)
if (a.ne.0.0d 00) then
call yzkrdf (j,ia,k)
do i=1,max0
eg(i)=eg(i)+a*dg(i)*cg(i,j)
ep(i)=ep(i)+a*dg(i)*cp(i,j)
enddo
n=k+1+ abs(kap(j))- abs(kap(ia))
if (n.le.ndor) then
do i=n,ndor
ceg(i)=ceg(i)+bg(i+1-n,j)*a*ap(1)*fix(j)/fix(ia)
cep(i)=cep(i)+bp(i+1-n,j)*a*ap(1)*fix(j)/fix(ia)
enddo
endif
i=2* abs(kap(j))+1
if (i.le.ndor) then
do ix = 1,10
bgj(ix) = bg(ix,j)
bpj(ix) = bp(ix,j)
enddo
do n=i,ndor
ceg(n)=ceg(n)-a*aprdev(ag,bgj,n+1-i)*fix(j)**2
cep(n)=cep(n)-a*aprdev(ag,bpj,n+1-i)*fix(j)**2
enddo
endif
endif
k=k+2
if (k.le.kma) go to 111
endif
enddo
endif
if (ipl.ne.0) then
do j=1,norbsc
if (kap(j).ne.kap(ia).or.j.eq.ia) go to 481
if (nre(j).lt.0.and.nre(ia).lt.0) go to 481
m= max(j,ia)
i= min(j,ia)+((m-1)*(m-2))/2
a=eps(i)*xnel(j)
max0=nmax(j)
do i=1,max0
at(i)=at(i)+a*cg(i,j)
bt(i)=bt(i)+a*cp(i,j)
enddo
do i=1,ndor
ceg(i)=ceg(i)+bg(i,j)*a
cep(i)=cep(i)+bp(i,j)*a
enddo
481 continue
enddo
endif
c addition of nuclear potential and division of potentials and
c their development limits by speed of light
do i=1,ndor
av(i)=av(i)/cl
cep(i)=cep(i)/cl
ceg(i)=ceg(i)/cl
enddo
do i=1,idim
dv(i)=(dv(i)/dr(i)+dvn(i))/cl
ep(i)=(ep(i)+bt(i)*dr(i))/cl
eg(i)=(eg(i)+at(i)*dr(i))/cl
enddo
return
end
|
module Main
import Data.ZZ
import Data.Matrix
import Data.Matrix.RowEchelon
import Data.Matrix.ZZModuleSpan
import Data.Matrix.ZZGaussianElimination
%flag C "-O3"
-- 1s & 0s only, please.
testmat : Matrix 3 2 ZZ
testmat = map (map Pos) [[0,1],[1,1],[1,0]]
-- 1s & 0s only, please.
testmat2 : Matrix 2 2 ZZ
testmat2 = map (map Pos) [[1,0],[0,1]]
-- 1s & 0s only, please.
testmat3 : Matrix 1 2 ZZ
testmat3 = [[Pos 1, Pos 0]]
-- 1s & 0s only, please.
testmat4 : Matrix 1 2 ZZ
testmat4 = [[Pos 0, Pos 1]]
testmat5 : Matrix 2 1 ZZ
testmat5 = [[Pos 2],[Pos 3]]
testelim : (n' : Nat ** (gexs : Matrix n' 2 ZZ
** (rowEchelon gexs, bispanslz gexs Main.testmat)))
testelim = gaussElimlz testmat
{-
testelim2 : (n' : Nat ** (gexs : Matrix n' 2 ZZ
** (rowEchelon gexs, bispanslz gexs Main.testmat2)))
testelim2 = gaussElimlz testmat2
testelim2' : Matrix (getWitness Main.testelim2) 2 ZZ
testelim2' = getWitness $ getProof $ gaussElimlz testmat2
-}
testelim2_ : (n' : Nat ** Matrix n' 2 ZZ)
testelim2_ = (_ ** getWitness $ getProof $ gaussElimlz testmat2)
testelim4_ : (n' : Nat ** Matrix n' 2 ZZ)
testelim4_ = (_ ** getWitness $ getProof $ gaussElimlz testmat4)
testelim5_ : (n' : Nat ** Matrix n' 1 ZZ)
testelim5_ = (_ ** getWitness $ getProof $ gaussElimlz testmat5)
main : IO ()
main = putStrLn $ show $ getProof testelim4_
|
module Regularizers
import PyCall: PyObject, pycall, PyAny
import ..Keras
import ..Keras: PyDoc
const keras_regularizer_classes = [ "Regularizer", "L1L2"]
const keras_regularizer_aliases = [
"l1",
"l2",
"l1_l2",
]
for r in keras_regularizer_classes
reg_name = Symbol(r)
@eval begin
struct $reg_name
obj::PyObject
@doc PyDoc(Keras._regularizers, Symbol($r)) function $reg_name(args...; kwargs...)
new(Keras._regularizers[Symbol($r)](args...; kwargs...))
end
end
# convert(::Type{$(reg_name)}, obj::PyObject) = $reg_name(obj)
PyObject(reg::$(reg_name)) = reg.obj
pycall(reg::$(reg_name), args...; kws...) = pycall(reg.obj, args...; kws...)
end
end
for r in keras_regularizer_aliases
rf = Symbol(r)
@eval begin
@doc PyDoc(Keras._regularizers, Symbol($r)) function $rf(args...; kwargs...)
return pycall(Keras._regularizers[Symbol($r)], PyAny, args...; kwargs...)
end
end
end
end
|
Require Import GenericVerifierIface.
Require Import GenericVerifier.
Require Import ClassDatatypesIface.
Require Import ILLInterfaces.
Require Import BasicMachineTypes.
Require Import OptionMonad.
Require Import OptionExt.
Require Import ClasspoolIface.
Require Import CertRuntimeTypesIface.
Require Import List.
Require Import Execution.
Require Import ResInstructionVerifier.
Require Import Certificates.
Module ResourceVerifier
(B : BASICS)
(SYN : ILL_SYNTAX with Module SYN.B := B)
(CERT : CERTIFICATE with Definition asn := SYN.SYN.formula)
(ANN : ILLANNOTATIONS with Module B:= B with Module SYN := SYN with Module CERT := CERT)
(RA : RESOURCE_ALGEBRA with Module B := B)
(C : CLASSDATATYPES with Module B := B with Module A := ANN)
(CP : CLASSPOOL with Module B := B with Module C := C)
(RT : CERTRUNTIMETYPES with Module B := B with Module C := C with Module CP := CP)
(RSEM : ILL_SEMANTICS with Module RA := RA with Module SYN := SYN).
Module E := Execution.Execution B RA C CP RT.
Module RIV := ResInstructionVerifier.ResInstructionVerifier B SYN CERT C.
Module RCV := MkCodeVerifier B SYN CERT ANN C RIV.
Import SYN.
Import CERT.
Import RCV.
Import RSEM.
Import RA.
|
open import Nat
open import Prelude
open import dynamics-core
open import contexts
open import lemmas-consistency
open import type-assignment-unicity
open import lemmas-progress-checks
-- taken together, the theorems in this file argue that for any expression
-- d, at most one summand of the labeled sum that results from progress may
-- be true at any time: that boxed values, indeterminates, and expressions
-- that step are pairwise disjoint.
--
-- note that as a consequence of currying and comutativity of products,
-- this means that there are three theorems to prove. in addition to those,
-- we also prove several convenince forms that combine theorems about
-- indeterminate and boxed value forms into the same statement about final
-- forms, which mirrors the mutual definition of indeterminate and final
-- and saves some redundant argumentation.
module progress-checks where
-- boxed values are not indeterminates
boxedval-not-indet : ∀{d} → d boxedval → d indet → ⊥
boxedval-not-indet (BVVal VNum) ()
boxedval-not-indet (BVVal VLam) ()
boxedval-not-indet (BVArrCast x bv) (ICastArr x₁ ind) = boxedval-not-indet bv ind
boxedval-not-indet (BVHoleCast x bv) (ICastGroundHole x₁ ind) = boxedval-not-indet bv ind
boxedval-not-indet (BVHoleCast x bv) (ICastHoleGround x₁ ind x₂) = boxedval-not-indet bv ind
boxedval-not-indet (BVVal (VInl x)) (IInl ind) = boxedval-not-indet (BVVal x) ind
boxedval-not-indet (BVVal (VInr x)) (IInr ind) = boxedval-not-indet (BVVal x) ind
boxedval-not-indet (BVInl bv) (IInl ind) = boxedval-not-indet bv ind
boxedval-not-indet (BVInr bv) (IInr ind) = boxedval-not-indet bv ind
boxedval-not-indet (BVSumCast x bv) (ICastSum x₁ ind) = boxedval-not-indet bv ind
boxedval-not-indet (BVVal (VPair x x₂)) (IPair1 ind x₁) = boxedval-not-indet (BVVal x) ind
boxedval-not-indet (BVVal (VPair x x₂)) (IPair2 x₁ ind) = boxedval-not-indet (BVVal x₂) ind
boxedval-not-indet (BVPair bv bv₁) (IPair1 ind x) = boxedval-not-indet bv ind
boxedval-not-indet (BVPair bv bv₁) (IPair2 x ind) = boxedval-not-indet bv₁ ind
boxedval-not-indet (BVProdCast x bv) (ICastProd x₁ ind) = boxedval-not-indet bv ind
-- boxed values don't step
boxedval-not-step : ∀{d} → d boxedval → (Σ[ d' ∈ ihexp ] (d ↦ d')) → ⊥
boxedval-not-step (BVVal VNum) (d' , Step FHOuter () x₃)
boxedval-not-step (BVVal VLam) (d' , Step FHOuter () x₃)
boxedval-not-step (BVArrCast x bv) (d0' , Step FHOuter (ITCastID) FHOuter) = x refl
boxedval-not-step (BVArrCast x bv) (_ , Step (FHCast x₁) x₂ (FHCast x₃)) = boxedval-not-step bv (_ , Step x₁ x₂ x₃)
boxedval-not-step (BVHoleCast () bv) (d' , Step FHOuter (ITCastID) FHOuter)
boxedval-not-step (BVHoleCast x bv) (d' , Step FHOuter (ITCastSucceed ()) FHOuter)
boxedval-not-step (BVHoleCast GArrHole bv) (_ , Step FHOuter (ITGround (MGArr x)) FHOuter) = x refl
boxedval-not-step (BVHoleCast x bv) (_ , Step (FHCast x₁) x₂ (FHCast x₃)) = boxedval-not-step bv (_ , Step x₁ x₂ x₃)
boxedval-not-step (BVHoleCast x x₁) (_ , Step FHOuter (ITExpand ()) FHOuter)
boxedval-not-step (BVHoleCast x x₁) (_ , Step FHOuter (ITCastFail x₂ () x₄) FHOuter)
boxedval-not-step (BVVal (VInl x)) (_ , Step FHOuter () x₃)
boxedval-not-step (BVVal (VInr x)) (_ , Step FHOuter () x₃)
boxedval-not-step (BVInl bv) (_ , Step FHOuter () x₂)
boxedval-not-step (BVInr bv) (_ , Step FHOuter () x₂)
boxedval-not-step (BVSumCast x bv) (_ , Step FHOuter ITCastID FHOuter) = x refl
boxedval-not-step (BVSumCast x bv) (_ , Step (FHCast x₁) x₂ (FHCast x₃)) = boxedval-not-step bv (_ , Step x₁ x₂ x₃)
boxedval-not-step (BVHoleCast GNum bv) (_ , Step FHOuter (ITGround ()) FHOuter)
boxedval-not-step (BVHoleCast GSumHole bv) (_ , Step FHOuter (ITGround (MGSum x)) FHOuter) = x refl
boxedval-not-step (BVVal (VInl x)) (_ , Step (FHInl x₁) x₂ (FHInl x₃)) = boxedval-not-step (BVVal x) (_ , Step x₁ x₂ x₃)
boxedval-not-step (BVVal (VInr x)) (_ , Step (FHInr x₁) x₂ (FHInr x₃)) = boxedval-not-step (BVVal x) (_ , Step x₁ x₂ x₃)
boxedval-not-step (BVInl bv) (_ , Step (FHInl x) x₁ (FHInl x₂)) = boxedval-not-step bv (_ , Step x x₁ x₂)
boxedval-not-step (BVInr bv) (_ , Step (FHInr x) x₁ (FHInr x₂)) = boxedval-not-step bv (_ , Step x x₁ x₂)
boxedval-not-step (BVVal (VPair x x₁)) (_ , Step (FHPair1 x₂) x₃ (FHPair1 x₄)) = boxedval-not-step (BVVal x) (_ , Step x₂ x₃ x₄)
boxedval-not-step (BVVal (VPair x x₁)) (_ , Step (FHPair2 x₂) x₃ (FHPair2 x₄)) = boxedval-not-step (BVVal x₁) (_ , (Step x₂ x₃ x₄))
boxedval-not-step (BVPair bv bv₁) (_ , Step (FHPair1 x) x₁ (FHPair1 x₂)) = boxedval-not-step bv (_ , Step x x₁ x₂)
boxedval-not-step (BVPair bv bv₁) (_ , Step (FHPair2 x) x₁ (FHPair2 x₂)) = boxedval-not-step bv₁ (_ , Step x x₁ x₂)
boxedval-not-step (BVProdCast x bv) (_ , Step FHOuter ITCastID FHOuter) = x refl
boxedval-not-step (BVProdCast x bv) (_ , Step (FHCast x₁) x₂ (FHCast x₃)) = boxedval-not-step bv (_ , Step x₁ x₂ x₃)
boxedval-not-step (BVHoleCast GProdHole bv) (_ , Step FHOuter (ITGround (MGProd x)) FHOut\er) = x refl
mutual
-- indeterminates don't step
indet-not-step : ∀{d} → d indet → (Σ[ d' ∈ ihexp ] (d ↦ d')) → ⊥
indet-not-step IEHole (d' , Step FHOuter () FHOuter)
indet-not-step (INEHole x) (d' , Step FHOuter () FHOuter)
indet-not-step (INEHole x) (_ , Step (FHNEHole x₁) x₂ (FHNEHole x₃)) = final-sub-not-trans x x₁ x₂
indet-not-step (IAp x₁ () x₂) (_ , Step FHOuter (ITLam) FHOuter)
indet-not-step (IAp x (ICastArr x₁ ind) x₂) (_ , Step FHOuter (ITApCast) FHOuter) = x _ _ _ _ _ refl
indet-not-step (IAp x ind _) (_ , Step (FHAp1 x₂) x₃ (FHAp1 x₄)) = indet-not-step ind (_ , Step x₂ x₃ x₄)
indet-not-step (IAp x ind f) (_ , Step (FHAp2 x₃) x₄ (FHAp2 x₆)) = final-not-step f (_ , Step x₃ x₄ x₆)
indet-not-step (ICastArr x ind) (d0' , Step FHOuter (ITCastID) FHOuter) = x refl
indet-not-step (ICastArr x ind) (_ , Step (FHCast x₁) x₂ (FHCast x₃)) = indet-not-step ind (_ , Step x₁ x₂ x₃)
indet-not-step (ICastGroundHole () ind) (d' , Step FHOuter (ITCastID) FHOuter)
indet-not-step (ICastGroundHole x ind) (d' , Step FHOuter (ITCastSucceed ()) FHOuter)
indet-not-step (ICastGroundHole GArrHole ind) (_ , Step FHOuter (ITGround (MGArr x₁)) FHOuter) = x₁ refl
indet-not-step (ICastGroundHole x ind) (_ , Step (FHCast x₁) x₂ (FHCast x₃)) = indet-not-step ind (_ , Step x₁ x₂ x₃)
indet-not-step (ICastHoleGround x ind ()) (d' , Step FHOuter (ITCastID ) FHOuter)
indet-not-step (ICastHoleGround x ind g) (d' , Step FHOuter (ITCastSucceed x₂) FHOuter) = x _ _ refl
indet-not-step (ICastHoleGround x ind GArrHole) (_ , Step FHOuter (ITExpand (MGArr x₂)) FHOuter) = x₂ refl
indet-not-step (ICastHoleGround x ind g) (_ , Step (FHCast x₁) x₂ (FHCast x₃)) = indet-not-step ind (_ , Step x₁ x₂ x₃)
indet-not-step (ICastGroundHole x x₁) (_ , Step FHOuter (ITExpand ()) FHOuter)
indet-not-step (ICastHoleGround x x₁ x₂) (_ , Step FHOuter (ITGround ()) FHOuter)
indet-not-step (ICastGroundHole x x₁) (_ , Step FHOuter (ITCastFail x₂ () x₄) FHOuter)
indet-not-step (ICastHoleGround x x₁ x₂) (_ , Step FHOuter (ITCastFail x₃ x₄ x₅) FHOuter) = x _ _ refl
indet-not-step (IFailedCast x x₁ x₂ x₃) (d' , Step FHOuter () FHOuter)
indet-not-step (IFailedCast x x₁ x₂ x₃) (_ , Step (FHFailedCast x₄) x₅ (FHFailedCast x₆)) = final-not-step x (_ , Step x₄ x₅ x₆)
indet-not-step (IPlus1 () x₄) (_ , Step FHOuter (ITPlus x₁) FHOuter)
indet-not-step (IPlus1 x x₄) (_ , Step (FHPlus1 x₁) x₂ (FHPlus1 x₃)) = indet-not-step x (_ , Step x₁ x₂ x₃)
indet-not-step (IPlus1 x x₄) (.(_ ·+ _) , Step (FHPlus2 x₁) x₂ (FHPlus2 x₃)) = final-not-step x₄ (_ , Step x₁ x₂ x₃)
indet-not-step (IPlus2 x ()) (_ , Step FHOuter (ITPlus x₁) FHOuter)
indet-not-step (IPlus2 x x₄) (_ , Step (FHPlus1 x₁) x₂ (FHPlus1 x₃)) = final-not-step x (_ , Step x₁ x₂ x₃)
indet-not-step (IPlus2 x x₄) (_ , Step (FHPlus2 x₁) x₂ (FHPlus2 x₃)) = indet-not-step x₄ (_ , Step x₁ x₂ x₃)
indet-not-step (IInl ind) (_ , Step FHOuter () x₂)
indet-not-step (IInl ind) (_ , Step (FHInl x) x₁ (FHInl x₂)) = indet-not-step ind (_ , Step x x₁ x₂)
indet-not-step (IInr ind) (_ , Step FHOuter () x₂)
indet-not-step (IInr ind) (_ , Step (FHInr x) x₁ (FHInr x₂)) = indet-not-step ind (_ , Step x x₁ x₂)
indet-not-step (ICase x x₁ x₂ ind) (_ , Step FHOuter ITCaseInl x₅) = x _ _ refl
indet-not-step (ICase x x₁ x₂ ind) (_ , Step FHOuter ITCaseInr x₅) = x₁ _ _ refl
indet-not-step (ICase x x₁ x₂ ind) (_ , Step FHOuter ITCaseCast x₅) = x₂ _ _ _ _ _ refl
indet-not-step (ICase x x₁ x₂ ind) (_ , Step (FHCase x₃) x₄ (FHCase x₅)) = indet-not-step ind (_ , Step x₃ x₄ x₅)
indet-not-step (ICastSum x ind) (_ , Step FHOuter ITCastID FHOuter) = x refl
indet-not-step (ICastSum x ind) (_ , Step (FHCast x₁) x₂ (FHCast x₃)) = indet-not-step ind (_ , Step x₁ x₂ x₃)
indet-not-step (ICastGroundHole GNum ind) (_ , Step FHOuter (ITGround ()) FHOuter)
indet-not-step (ICastGroundHole GSumHole ind) (_ , Step FHOuter (ITGround (MGSum x)) FHOuter) = x refl
indet-not-step (ICastHoleGround x ind GNum) (_ , Step FHOuter (ITExpand ()) FHOuter)
indet-not-step (ICastHoleGround x ind GSumHole) (_ , Step FHOuter (ITExpand (MGSum x₁)) FHOuter) = x₁ refl
indet-not-step (IPair1 ind x) (_ , Step (FHPair1 x₁) x₂ (FHPair1 x₃)) = indet-not-step ind (_ , Step x₁ x₂ x₃)
indet-not-step (IPair1 ind x) (_ , Step (FHPair2 x₁) x₂ (FHPair2 x₃)) = final-not-step x (_ , Step x₁ x₂ x₃)
indet-not-step (IPair2 x ind) (_ , Step (FHPair1 x₁) x₂ (FHPair1 x₃)) = final-not-step x (_ , Step x₁ x₂ x₃)
indet-not-step (IPair2 x ind) (_ , Step (FHPair2 x₁) x₂ (FHPair2 x₃)) = indet-not-step ind (_ , Step x₁ x₂ x₃)
indet-not-step (IFst x x₁ ind) (_ , Step FHOuter ITFstPair FHOuter) = x _ _ refl
indet-not-step (IFst x x₁ ind) (_ , Step (FHFst x₂) x₃ (FHFst x₄)) = indet-not-step ind (_ , Step x₂ x₃ x₄)
indet-not-step (ISnd x x₁ ind) (_ , Step FHOuter ITSndPair FHOuter) = x _ _ refl
indet-not-step (ISnd x x₁ ind) (_ , Step (FHSnd x₂) x₃ (FHSnd x₄)) = indet-not-step ind (_ , Step x₂ x₃ x₄)
indet-not-step (ICastGroundHole GProdHole ind) (_ , Step FHOuter (ITGround (MGProd x)) FHOuter) = x refl
indet-not-step (ICastHoleGround x ind GProdHole) (_ , Step FHOuter (ITExpand (MGProd x₁)) FHOuter) = x₁ refl
indet-not-step (IPair1 ind x) (_ , Step FHOuter () FHOuter)
indet-not-step (IPair2 x ind) (_ , Step FHOuter () FHOuter)
indet-not-step (IFst x x₁ ind) (_ , Step FHOuter ITFstCast FHOuter) = x₁ _ _ _ _ _ refl
indet-not-step (ISnd x x₁ ind) (_ , Step FHOuter ITSndCast FHOuter) = x₁ _ _ _ _ _ refl
indet-not-step (ICastProd x ind) (_ , Step FHOuter ITCastID FHOuter) = x refl
indet-not-step (ICastProd x ind) (_ , Step (FHCast x₁) x₂ (FHCast x₃)) = indet-not-step ind (_ , Step x₁ x₂ x₃)
-- final expressions don't step
final-not-step : ∀{d} → d final → Σ[ d' ∈ ihexp ] (d ↦ d') → ⊥
final-not-step (FBoxedVal x) stp = boxedval-not-step x stp
final-not-step (FIndet x) stp = indet-not-step x stp
|
/*
NAME:
logsum
PURPOSE:
calculate the log of the sum of numbers which are given as logs using as much of the dynamic range as possible
CALLING SEQUENCE:
logsum(gsl_matrix * q, int row, bool isrow,bool partial, int partial_indx[3])
INPUT:
q - matrix of which we will sum a row/column
row - row/column number
isrow - are we summing a row or a column
OUTPUT:
log of the sum
REVISION HISTORY:
2008-09-21 - Written Bovy
*/
#include <stdbool.h>
#include <math.h>
#include <float.h>
#include <gsl/gsl_matrix.h>
#include <proj_gauss_mixtures.h>
double logsum(gsl_matrix * q, int row, bool isrow){
double logxmin = log(DBL_MIN);
double logxmax = log(DBL_MAX);
int l = (isrow) ? q->size2 : q->size1;
/* First find the maximum and mininum */
double max, min;
minmax(q,row,isrow,&min,&max);//,allfixed);
min *= -1.;
min += logxmin;
max *= -1.;
max += logxmax - log(l);
(min > max) ? (max=max) : (max=min);
double loglike=0.0;
int dd;
if (isrow)
for (dd = 0; dd != q->size2; ++dd)
loglike += exp(gsl_matrix_get(q,row,dd)+max);
else
for (dd = 0; dd != q->size1; ++dd)
loglike += exp(gsl_matrix_get(q,dd,row)+max);
return log(loglike)-max;
}
|
theory Projective_Space_Axioms
imports Main
begin
(* Author: Anthony Bordg, University of Cambridge, [email protected] *)
text \<open>
Contents:
\<^item> We introduce the types @{typ 'point} of points and @{typ 'line} of lines and an incidence relation
between them.
\<^item> A set of axioms for the (3-dimensional) projective space.
An alternative set of axioms could use planes as basic objects in addition to points and lines
\<close>
section \<open>The axioms of the Projective Space\<close>
lemma distinct4_def:
"distinct [A,B,C,D] = ((A \<noteq> B) \<and> (A \<noteq> C) \<and> (A \<noteq> D)\<and> (B \<noteq> C) \<and> (B \<noteq> D) \<and> (C \<noteq> D))"
by auto
lemma distinct3_def:
"distinct [A, B, C] = (A \<noteq> B \<and> A \<noteq> C \<and> B \<noteq> C)"
by auto
locale projective_space =
(* One has a type of 'point *)
(* We don't need an axiom for the existence of at least one point,
since we know that the type "'point" is not empty
TODO: why would that be true? *)
(* One has a type of 'line *)
(* There is a relation of incidence between 'point and 'line *)
fixes incid :: "'point \<Rightarrow> 'line \<Rightarrow> bool"
fixes meet :: "'line \<Rightarrow> 'line \<Rightarrow> 'point"
assumes meet_def: "(incid (meet l m) l \<and> incid (meet l m) m)"
(* The relation of incidence is decidable *)
assumes incid_dec: "(incid P l) \<or> \<not>(incid P l)"
(* Ax1: Any two distinct 'point are incident with just one line *)
assumes ax1_existence: "\<exists>l. (incid P l) \<and> (incid M l)"
assumes ax1_uniqueness: "(incid P k) \<longrightarrow> (incid M k) \<longrightarrow> (incid P l) \<longrightarrow> (incid M l) \<longrightarrow> (P = M) \<or> (k = l)"
(* Ax2: If A B C D are four distinct 'point such that AB meets CD then AC meets BD.
Sometimes this is called Pasch's axiom, but according to Wikipedia it is misleading
since Pasch's axiom refers to something else. *)
assumes ax2: "distinct [A,B,C,D] \<longrightarrow> (incid A lAB \<and> incid B lAB)
\<longrightarrow> (incid C lCD \<and> incid D lCD) \<longrightarrow> (incid A lAC \<and> incid C lAC) \<longrightarrow>
(incid B lBD \<and> incid D lBD) \<longrightarrow> (\<exists>I.(incid I lAB \<and> incid I lCD)) \<longrightarrow>
(\<exists>J.(incid J lAC \<and> incid J lBD))"
(** Dimension-related axioms **)
(* Ax3: Every line is incident with at least three Points.
As I understand it, this axiom makes sure that Lines are not degenerated into 'point
and since it asks for three distinct Points, not only 2, it captures the idea that
Lines are continuous, i.e. there is always a point between two distinct Points. *)
assumes ax3: "\<exists>A B C. distinct3 A B C \<and> (incid A l) \<and> (incid B l) \<and> (incid C l)"
(* Ax4: There exists two Lines that do not meet,
hence the geometry is at least 3-dimensional *)
assumes ax4: "\<exists>l m.\<forall>P. \<not>(incid P l \<and> incid P m)"
(* Ax5: The geometry is not 4-dimensional, hence it is exactly 3-dimensional *)
assumes ax5: "distinct [l1,l2,l3] \<longrightarrow> (\<exists>l4 J1 J2 J3. distinct [J1,J2,J3] \<and>
meet l1 l4 = J1 \<and> meet l2 l4 = J2 \<and> meet l3 l4 = J3)"
end |
import ground_zero.proto ground_zero.meta.hott_theory
namespace ground_zero.types
universes u v
theorem K {α : Sort u} {a b : α} (p q : a = b) : p = q :=
by trivial
inductive eq {α : Sort u} (a : α) : α → Sort u
| refl : eq a
attribute [refl] eq.refl
hott theory
notation a ` = ` b ` :> ` α := @eq α a b
/- fails!
theorem K₁ {α : Sort u} {a b : α} (p q : a = b :> α) :
p = q :> (a = b :> α) :=
by trivial
-/
namespace eq
@[inline] def rfl {α : Sort u} {a : α} : a = a :> α :=
eq.refl a
@[trans] def trans {α : Sort u} {a b c : α}
(p : a = b :> α) (q : b = c :> α) : a = c :> α :=
begin induction p, assumption end
@[symm] def symm {α : Sort u} {a b : α} (p : a = b :> α) :
b = a :> α :=
begin induction p, reflexivity end
infixr ` ⬝ ` := trans
postfix ⁻¹ := symm
def comp_inv {α : Sort u} {a b : α} (p : a = b :> α) :
p ⬝ p⁻¹ = eq.refl a :> a = a :> α :=
begin induction p, trivial end
def inv_comp {α : Sort u} {a b : α} (p : a = b :> α) :
p⁻¹ ⬝ p = eq.refl b :> b = b :> α :=
begin induction p, trivial end
def refl_left {α : Sort u} {a b : α} (p : a = b :> α) :
eq.refl a ⬝ p = p :> a = b :> α :=
begin induction p, trivial end
def refl_right {α : Sort u} {a b : α} (p : a = b :> α) :
p ⬝ eq.refl b = p :> a = b :> α :=
begin induction p, trivial end
def refl_twice {α : Sort u} {a b : α} (p : a = b :> α) :
rfl ⬝ p ⬝ rfl = p :> a = b :> α :=
begin induction p, trivial end
def explode_inv {α : Sort u} {a b c : α}
(p : a = b :> α) (q : b = c :> α) :
(p ⬝ q)⁻¹ = q⁻¹ ⬝ p⁻¹ :> c = a :> α :=
begin induction p, induction q, trivial end
def inv_inv {α : Sort u} {a b : α}
(p : a = b :> α) : (p⁻¹)⁻¹ = p :> a = b :> α :=
begin induction p, trivial end
def assoc {α : Sort u} {a b c d : α}
(p : a = b :> α) (q : b = c :> α) (r : c = d :> α) :
p ⬝ (q ⬝ r) = (p ⬝ q) ⬝ r := begin
induction p, induction q, induction r,
trivial
end
def mpr {α β : Sort u} (p : α = β) : β → α :=
begin induction p, intro x, exact x end
def map {α : Sort u} {β : Sort v} {a b : α}
(f : α → β) (p : a = b :> α) : f a = f b :> β :=
begin induction p, reflexivity end
infix [parsing_only] ` # ` := map
section
variables {α : Sort u} {β : Sort v} {a b : α}
(f : α → β) (p : a = b :> α)
abbreviation cong := map f p
abbreviation ap := map f p
end
def ap₂ {α : Sort u} {β : Sort v} {a b : α}
{p q : a = b :> α} (f : α → β)
(r : p = q :> a = b :> α) :
f # p = f # q :> f a = f b :> β :=
begin induction r, reflexivity end
class dotted (space : Sort u) :=
(point : space)
structure pointed :=
(space : Sort u) (point : space)
def loop_space (X : pointed) : pointed :=
⟨X.point = X.point :> X.space, eq.refl X.point⟩
def iterated_loop_space : pointed → ℕ → pointed
| X 0 := X
| X (n + 1) := iterated_loop_space (loop_space X) n
def loop_pointed_space (α : Sort u) [h : dotted α] :=
iterated_loop_space ⟨α, dotted.point α⟩
notation `Ω` `[` n `]` `, ` X := (iterated_loop_space X n).space
notation `Θ` `[` n `]` `, ` X := (iterated_loop_space X n).point
notation `Ω¹` X := (loop_pointed_space X 1).space
end eq
namespace not
notation `¬` a := a → empty
notation a ` ≠ ` b := ¬(a = b :> _)
end not
namespace whiskering
variables {α : Sort u} {a b c : α}
variables {p q : a = b :> α} {r s : b = c :> α}
variables {ν : p = q} {κ : r = s}
def right_whs (ν : p = q) (r : b = c) : p ⬝ r = q ⬝ r := begin
induction r,
exact (eq.refl_right p) ⬝ ν ⬝ (eq.refl_right q)⁻¹
end
infix ` ⬝ᵣ `:60 := right_whs
def left_whs (q : a = b) (κ : r = s) : q ⬝ r = q ⬝ s := begin
induction q,
exact (eq.refl_left r) ⬝ κ ⬝ (eq.refl_left s)⁻¹
end
infix ` ⬝ₗ `:60 := left_whs
def horizontal_comp₁ (ν : p = q) (κ : r = s) :=
(ν ⬝ᵣ r) ⬝ (q ⬝ₗ κ)
infix ` ⋆ `:65 := horizontal_comp₁
def horizontal_comp₂ (ν : p = q) (κ : r = s) :=
(p ⬝ₗ κ) ⬝ (ν ⬝ᵣ s)
infix ` ⋆′ `:65 := horizontal_comp₂
lemma comp_uniq : ν ⋆ κ = ν ⋆′ κ := begin
induction p, induction r, induction ν, induction κ,
reflexivity
end
lemma loop₁ {α : Sort u} {a : α}
{ν κ : eq.refl a = eq.refl a} :
ν ⬝ κ = ν ⋆ κ := begin
symmetry, unfold horizontal_comp₁,
unfold right_whs, unfold left_whs,
transitivity,
{ apply eq.map, apply eq.refl_twice },
apply eq.map (λ p, p ⬝ κ), apply eq.refl_twice
end
lemma loop₂ {α : Sort u} {a : α}
{ν κ : eq.refl a = eq.refl a} :
ν ⋆′ κ = κ ⬝ ν := begin
unfold horizontal_comp₂,
unfold right_whs, unfold left_whs,
transitivity,
{ apply eq.map, apply eq.refl_twice },
apply eq.map (λ p, p ⬝ ν), apply eq.refl_twice
end
theorem «Eckmann–Hilton argument» {α : Sort u} {a : α}
(ν κ : eq.refl a = eq.refl a) : ν ⬝ κ = κ ⬝ ν :=
loop₁ ⬝ comp_uniq ⬝ loop₂
end whiskering
end ground_zero.types |
function result = is_symmetric_matrix(A)
%
% Symmetric Matrices
%
% is_symmetric_matrix(A) determines if the matrix A is a symmetric
% matrix. An error is returned if a matrix that is not square is attempted
% to be determined for symmetry.
matrix_size = size(A);
m = matrix_size(1,1);
n = matrix_size(1,2);
if m ~= n
error('Only square matrices can be symmetric.');
else
if A == A'
result = 1;
else
result = 0;
end
end |
[STATEMENT]
lemma no_rotate_prim: assumes "w \<noteq> \<epsilon>" and "\<And> n. 0 < n \<Longrightarrow> n < \<^bold>|w\<^bold>| \<Longrightarrow> rotate n w \<noteq> w"
shows "primitive w"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. primitive w
[PROOF STEP]
proof (rule ccontr)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<not> primitive w \<Longrightarrow> False
[PROOF STEP]
assume "\<not> primitive w"
[PROOF STATE]
proof (state)
this:
\<not> primitive w
goal (1 subgoal):
1. \<not> primitive w \<Longrightarrow> False
[PROOF STEP]
from non_prim[OF this \<open>w \<noteq> \<epsilon>\<close>]
[PROOF STATE]
proof (chain)
picking this:
(\<And>r k. \<lbrakk>r \<noteq> \<epsilon>; 1 < k; r \<^sup>@ k = w; w \<noteq> r\<rbrakk> \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis
[PROOF STEP]
obtain r l where "r \<noteq> \<epsilon>" and "1 < l" and "r\<^sup>@l = w" and "w \<noteq> r"
[PROOF STATE]
proof (prove)
using this:
(\<And>r k. \<lbrakk>r \<noteq> \<epsilon>; 1 < k; r \<^sup>@ k = w; w \<noteq> r\<rbrakk> \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis
goal (1 subgoal):
1. (\<And>r l. \<lbrakk>r \<noteq> \<epsilon>; 1 < l; r \<^sup>@ l = w; w \<noteq> r\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
r \<noteq> \<epsilon>
1 < l
r \<^sup>@ l = w
w \<noteq> r
goal (1 subgoal):
1. \<not> primitive w \<Longrightarrow> False
[PROOF STEP]
have "rotate \<^bold>|r\<^bold>| w = w"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. rotate \<^bold>|r\<^bold>| w = w
[PROOF STEP]
using rotate_root_self[of r l, unfolded \<open>r\<^sup>@l = w\<close>]
[PROOF STATE]
proof (prove)
using this:
rotate \<^bold>|r\<^bold>| w = w
goal (1 subgoal):
1. rotate \<^bold>|r\<^bold>| w = w
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
rotate \<^bold>|r\<^bold>| w = w
goal (1 subgoal):
1. \<not> primitive w \<Longrightarrow> False
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
rotate \<^bold>|r\<^bold>| w = w
goal (1 subgoal):
1. \<not> primitive w \<Longrightarrow> False
[PROOF STEP]
have "0 < \<^bold>|r\<^bold>|"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. 0 < \<^bold>|r\<^bold>|
[PROOF STEP]
by (simp add: \<open>r \<noteq> \<epsilon>\<close>)
[PROOF STATE]
proof (state)
this:
0 < \<^bold>|r\<^bold>|
goal (1 subgoal):
1. \<not> primitive w \<Longrightarrow> False
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
0 < \<^bold>|r\<^bold>|
goal (1 subgoal):
1. \<not> primitive w \<Longrightarrow> False
[PROOF STEP]
have "\<^bold>|r\<^bold>| < \<^bold>|w\<^bold>|"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<^bold>|r\<^bold>| < \<^bold>|w\<^bold>|
[PROOF STEP]
unfolding pow_len[of r l, unfolded \<open>r\<^sup>@l = w\<close>]
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<^bold>|r\<^bold>| < l * \<^bold>|r\<^bold>|
[PROOF STEP]
using \<open>1 < l\<close> \<open>0 < \<^bold>|r\<^bold>|\<close>
[PROOF STATE]
proof (prove)
using this:
1 < l
0 < \<^bold>|r\<^bold>|
goal (1 subgoal):
1. \<^bold>|r\<^bold>| < l * \<^bold>|r\<^bold>|
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<^bold>|r\<^bold>| < \<^bold>|w\<^bold>|
goal (1 subgoal):
1. \<not> primitive w \<Longrightarrow> False
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
rotate \<^bold>|r\<^bold>| w = w
0 < \<^bold>|r\<^bold>|
\<^bold>|r\<^bold>| < \<^bold>|w\<^bold>|
[PROOF STEP]
show False
[PROOF STATE]
proof (prove)
using this:
rotate \<^bold>|r\<^bold>| w = w
0 < \<^bold>|r\<^bold>|
\<^bold>|r\<^bold>| < \<^bold>|w\<^bold>|
goal (1 subgoal):
1. False
[PROOF STEP]
using assms(2)
[PROOF STATE]
proof (prove)
using this:
rotate \<^bold>|r\<^bold>| w = w
0 < \<^bold>|r\<^bold>|
\<^bold>|r\<^bold>| < \<^bold>|w\<^bold>|
\<lbrakk>0 < ?n; ?n < \<^bold>|w\<^bold>|\<rbrakk> \<Longrightarrow> rotate ?n w \<noteq> w
goal (1 subgoal):
1. False
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
False
goal:
No subgoals!
[PROOF STEP]
qed |
lemma smult_0_right [simp]: "smult a 0 = 0" |
State Before: case nil
V : Type u
V' : Type v
V'' : Type w
G : SimpleGraph V
G' : SimpleGraph V'
G'' : SimpleGraph V''
u v u✝ : V
i : ℕ
hi : i < length nil
⊢ Adj G (getVert nil i) (getVert nil (i + 1)) State After: no goals Tactic: cases hi State Before: case cons
V : Type u
V' : Type v
V'' : Type w
G : SimpleGraph V
G' : SimpleGraph V'
G'' : SimpleGraph V''
u v u✝ v✝ w✝ : V
hxy : Adj G u✝ v✝
p✝ : Walk G v✝ w✝
ih : ∀ {i : ℕ}, i < length p✝ → Adj G (getVert p✝ i) (getVert p✝ (i + 1))
i : ℕ
hi : i < length (cons hxy p✝)
⊢ Adj G (getVert (cons hxy p✝) i) (getVert (cons hxy p✝) (i + 1)) State After: case cons.zero
V : Type u
V' : Type v
V'' : Type w
G : SimpleGraph V
G' : SimpleGraph V'
G'' : SimpleGraph V''
u v u✝ v✝ w✝ : V
hxy : Adj G u✝ v✝
p✝ : Walk G v✝ w✝
ih : ∀ {i : ℕ}, i < length p✝ → Adj G (getVert p✝ i) (getVert p✝ (i + 1))
hi : Nat.zero < length (cons hxy p✝)
⊢ Adj G (getVert (cons hxy p✝) Nat.zero) (getVert (cons hxy p✝) (Nat.zero + 1))
case cons.succ
V : Type u
V' : Type v
V'' : Type w
G : SimpleGraph V
G' : SimpleGraph V'
G'' : SimpleGraph V''
u v u✝ v✝ w✝ : V
hxy : Adj G u✝ v✝
p✝ : Walk G v✝ w✝
ih : ∀ {i : ℕ}, i < length p✝ → Adj G (getVert p✝ i) (getVert p✝ (i + 1))
n✝ : ℕ
hi : Nat.succ n✝ < length (cons hxy p✝)
⊢ Adj G (getVert (cons hxy p✝) (Nat.succ n✝)) (getVert (cons hxy p✝) (Nat.succ n✝ + 1)) Tactic: cases i State Before: case cons.zero
V : Type u
V' : Type v
V'' : Type w
G : SimpleGraph V
G' : SimpleGraph V'
G'' : SimpleGraph V''
u v u✝ v✝ w✝ : V
hxy : Adj G u✝ v✝
p✝ : Walk G v✝ w✝
ih : ∀ {i : ℕ}, i < length p✝ → Adj G (getVert p✝ i) (getVert p✝ (i + 1))
hi : Nat.zero < length (cons hxy p✝)
⊢ Adj G (getVert (cons hxy p✝) Nat.zero) (getVert (cons hxy p✝) (Nat.zero + 1)) State After: no goals Tactic: simp [getVert, hxy] State Before: case cons.succ
V : Type u
V' : Type v
V'' : Type w
G : SimpleGraph V
G' : SimpleGraph V'
G'' : SimpleGraph V''
u v u✝ v✝ w✝ : V
hxy : Adj G u✝ v✝
p✝ : Walk G v✝ w✝
ih : ∀ {i : ℕ}, i < length p✝ → Adj G (getVert p✝ i) (getVert p✝ (i + 1))
n✝ : ℕ
hi : Nat.succ n✝ < length (cons hxy p✝)
⊢ Adj G (getVert (cons hxy p✝) (Nat.succ n✝)) (getVert (cons hxy p✝) (Nat.succ n✝ + 1)) State After: no goals Tactic: exact ih (Nat.succ_lt_succ_iff.1 hi) |
function [dt6, xformToAcpc, mmPerVoxel, fileName, desc, intentName] = dtiLoadTensorsFromNifti(ni)
%Load a dt6 (tensor) data file in mrDiffusion format from NIFTI format.
%
% [dt6, xformToAcpc, mmPerVox, fileName, desc, intentName] = dtiLoadTensorsFromNifti(niFile)
%
% The six entries are the diffusion tensor values, derived from the raw
% data. The raw data can be in many different directions. The diffusion
% tensor is a 3x3 positive-definite matrix, D. The entries in the matrix
% are stored in a vector:
%
% Dxx Dyy Dzz Dxy Dxz Dyz
%
% or equivalently
%
% D(1,1), D(2,2), D(3,3), D(1,2), D(1,3), D(2,3)
%
% HISTORY:
% 2007.10.04 AJS: Wrote it.
%
% (c) Stanford VISTA Team
if(~exist('ni','var')||isempty(ni))
[f,p] = uigetfile({'*.nii.gz';'*.*'},'Select a NIFTI tensor file...');
if(isnumeric(f)), disp('User canceled.'); return; end
ni = fullfile(p,f);
end
if(ischar(ni))
if exist(ni,'file'), ni = niftiRead(ni);
else error('Can not find file %s\n',ni);
end
end
fileName = ni.fname;
% We convert from the 5d, lower-tri row order NIFTI tensor format used by
% other groups, such as FSL, which stores (x,y,z,1,directions)
% direction ordering: (Dxx Dxy Dyy Dxz Dyz Dzz)
%
% to our 4d tensor format, (x,y,z,directions)
% direction ordering: (Dxx Dyy Dzz Dxy Dxz Dyz).
%
dt6 = double(squeeze(ni.data(:,:,:,1,[1 3 6 2 4 5])));
xformToAcpc = ni.qto_xyz;
mmPerVoxel = ni.pixdim(1:3);
desc = ni.descrip;
intentName = ni.intent_name;
return
|
Require Import Logic.FunctionalExtensionality.
Require Import List.
Require Import Functor.
Import ListNotations.
Module List.
Import Functor.
Section List.
Global Instance list_functor: (Functor list) :=
{ fmap A B f a := map f a }.
Proof.
{ intros A; extensionality xs.
induction xs.
- reflexivity.
- simpl; rewrite IHxs; compute; reflexivity.
}
{ intros ? ? ? ? ?; apply functional_extensionality; intros xs.
induction xs.
- reflexivity.
- simpl; rewrite IHxs; compute; reflexivity.
}
Defined.
End List.
End List. |
Bavarian with Hat was introduced in 1991 by Inge-Glas of Germany® for Old World Christmas® as part of the Clowns & Characters Collection and features the exclusive 5-Point Star Crown.
This unique glass Christmas ornament has been lovingly handcrafted by the talented Inge-Glas® artisans in Neustadt near Coburg in Northern Bavaria using centuries-old glassblowing techniques. Bavarian with Hat was mouth-blown with clear crystal glass, coated inside with a layer of fine sterling silver, and hand painted using only the finest lead-free paints, glitters, and decorative materials.
Bavarian with Hat was retired in 1996 so availability is limited. |
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function [A, rhs] = sp_weak_drchlt_bc (varargin)
warning ('Using the function sp_weak_drchlt_bc_stokes')
[A, rhs] = sp_weak_drchlt_bc_stokes (varargin{:});
end
|
(* Title: ZF/AC/AC17_AC1.thy
Author: Krzysztof Grabczewski
The equivalence of AC0, AC1 and AC17
Also, the proofs needed to show that each of AC2, AC3, ..., AC6 is equivalent
to AC0 and AC1.
*)
theory AC17_AC1
imports HH
begin
(** AC0 is equivalent to AC1.
AC0 comes from Suppes, AC1 from Rubin & Rubin **)
lemma AC0_AC1_lemma: "\<lbrakk>f:(\<Prod>X \<in> A. X); D \<subseteq> A\<rbrakk> \<Longrightarrow> \<exists>g. g:(\<Prod>X \<in> D. X)"
by (fast intro!: lam_type apply_type)
lemma AC0_AC1: "AC0 \<Longrightarrow> AC1"
unfolding AC0_def AC1_def
apply (blast intro: AC0_AC1_lemma)
done
lemma AC1_AC0: "AC1 \<Longrightarrow> AC0"
by (unfold AC0_def AC1_def, blast)
(**** The proof of AC1 \<Longrightarrow> AC17 ****)
lemma AC1_AC17_lemma: "f \<in> (\<Prod>X \<in> Pow(A) - {0}. X) \<Longrightarrow> f \<in> (Pow(A) - {0} -> A)"
apply (rule Pi_type, assumption)
apply (drule apply_type, assumption, fast)
done
lemma AC1_AC17: "AC1 \<Longrightarrow> AC17"
unfolding AC1_def AC17_def
apply (rule allI)
apply (rule ballI)
apply (erule_tac x = "Pow (A) -{0}" in allE)
apply (erule impE, fast)
apply (erule exE)
apply (rule bexI)
apply (erule_tac [2] AC1_AC17_lemma)
apply (rule apply_type, assumption)
apply (fast dest!: AC1_AC17_lemma elim!: apply_type)
done
(**** The proof of AC17 \<Longrightarrow> AC1 ****)
(* *********************************************************************** *)
(* more properties of HH *)
(* *********************************************************************** *)
lemma UN_eq_imp_well_ord:
"\<lbrakk>x - (\<Union>j \<in> \<mu> i. HH(\<lambda>X \<in> Pow(x)-{0}. {f`X}, x, i) = {x}.
HH(\<lambda>X \<in> Pow(x)-{0}. {f`X}, x, j)) = 0;
f \<in> Pow(x)-{0} -> x\<rbrakk>
\<Longrightarrow> \<exists>r. well_ord(x,r)"
apply (rule exI)
apply (erule well_ord_rvimage
[OF bij_Least_HH_x [THEN bij_converse_bij, THEN bij_is_inj]
Ord_Least [THEN well_ord_Memrel]], assumption)
done
(* *********************************************************************** *)
(* theorems closer to the proof *)
(* *********************************************************************** *)
lemma not_AC1_imp_ex:
"\<not>AC1 \<Longrightarrow> \<exists>A. \<forall>f \<in> Pow(A)-{0} -> A. \<exists>u \<in> Pow(A)-{0}. f`u \<notin> u"
unfolding AC1_def
apply (erule swap)
apply (rule allI)
apply (erule swap)
apply (rule_tac x = "\<Union>(A)" in exI)
apply (blast intro: lam_type)
done
lemma AC17_AC1_aux1:
"\<lbrakk>\<forall>f \<in> Pow(x) - {0} -> x. \<exists>u \<in> Pow(x) - {0}. f`u\<notin>u;
\<exists>f \<in> Pow(x)-{0}->x.
x - (\<Union>a \<in> (\<mu> i. HH(\<lambda>X \<in> Pow(x)-{0}. {f`X},x,i)={x}).
HH(\<lambda>X \<in> Pow(x)-{0}. {f`X},x,a)) = 0\<rbrakk>
\<Longrightarrow> P"
apply (erule bexE)
apply (erule UN_eq_imp_well_ord [THEN exE], assumption)
apply (erule ex_choice_fun_Pow [THEN exE])
apply (erule ballE)
apply (fast intro: apply_type del: DiffE)
apply (erule notE)
apply (rule Pi_type, assumption)
apply (blast dest: apply_type)
done
lemma AC17_AC1_aux2:
"\<not> (\<exists>f \<in> Pow(x)-{0}->x. x - F(f) = 0)
\<Longrightarrow> (\<lambda>f \<in> Pow(x)-{0}->x . x - F(f))
\<in> (Pow(x) -{0} -> x) -> Pow(x) - {0}"
by (fast intro!: lam_type dest!: Diff_eq_0_iff [THEN iffD1])
lemma AC17_AC1_aux3:
"\<lbrakk>f`Z \<in> Z; Z \<in> Pow(x)-{0}\<rbrakk>
\<Longrightarrow> (\<lambda>X \<in> Pow(x)-{0}. {f`X})`Z \<in> Pow(Z)-{0}"
by auto
lemma AC17_AC1_aux4:
"\<exists>f \<in> F. f`((\<lambda>f \<in> F. Q(f))`f) \<in> (\<lambda>f \<in> F. Q(f))`f
\<Longrightarrow> \<exists>f \<in> F. f`Q(f) \<in> Q(f)"
by simp
lemma AC17_AC1: "AC17 \<Longrightarrow> AC1"
unfolding AC17_def
apply (rule classical)
apply (erule not_AC1_imp_ex [THEN exE])
apply (case_tac
"\<exists>f \<in> Pow(x)-{0} -> x.
x - (\<Union>a \<in> (\<mu> i. HH (\<lambda>X \<in> Pow (x) -{0}. {f`X},x,i) ={x}) . HH (\<lambda>X \<in> Pow (x) -{0}. {f`X},x,a)) = 0")
apply (erule AC17_AC1_aux1, assumption)
apply (drule AC17_AC1_aux2)
apply (erule allE)
apply (drule bspec, assumption)
apply (drule AC17_AC1_aux4)
apply (erule bexE)
apply (drule apply_type, assumption)
apply (simp add: HH_Least_eq_x del: Diff_iff )
apply (drule AC17_AC1_aux3, assumption)
apply (fast dest!: subst_elem [OF _ HH_Least_eq_x [symmetric]]
f_subset_imp_HH_subset elim!: mem_irrefl)
done
(* **********************************************************************
AC1 \<Longrightarrow> AC2 \<Longrightarrow> AC1
AC1 \<Longrightarrow> AC4 \<Longrightarrow> AC3 \<Longrightarrow> AC1
AC4 \<Longrightarrow> AC5 \<Longrightarrow> AC4
AC1 \<longleftrightarrow> AC6
************************************************************************* *)
(* ********************************************************************** *)
(* AC1 \<Longrightarrow> AC2 *)
(* ********************************************************************** *)
lemma AC1_AC2_aux1:
"\<lbrakk>f:(\<Prod>X \<in> A. X); B \<in> A; 0\<notin>A\<rbrakk> \<Longrightarrow> {f`B} \<subseteq> B \<inter> {f`C. C \<in> A}"
by (fast elim!: apply_type)
lemma AC1_AC2_aux2:
"\<lbrakk>pairwise_disjoint(A); B \<in> A; C \<in> A; D \<in> B; D \<in> C\<rbrakk> \<Longrightarrow> f`B = f`C"
by (unfold pairwise_disjoint_def, fast)
lemma AC1_AC2: "AC1 \<Longrightarrow> AC2"
unfolding AC1_def AC2_def
apply (rule allI)
apply (rule impI)
apply (elim asm_rl conjE allE exE impE, assumption)
apply (intro exI ballI equalityI)
prefer 2 apply (rule AC1_AC2_aux1, assumption+)
apply (fast elim!: AC1_AC2_aux2 elim: apply_type)
done
(* ********************************************************************** *)
(* AC2 \<Longrightarrow> AC1 *)
(* ********************************************************************** *)
lemma AC2_AC1_aux1: "0\<notin>A \<Longrightarrow> 0 \<notin> {B*{B}. B \<in> A}"
by (fast dest!: sym [THEN Sigma_empty_iff [THEN iffD1]])
lemma AC2_AC1_aux2: "\<lbrakk>X*{X} \<inter> C = {y}; X \<in> A\<rbrakk>
\<Longrightarrow> (THE y. X*{X} \<inter> C = {y}): X*A"
apply (rule subst_elem [of y])
apply (blast elim!: equalityE)
apply (auto simp add: singleton_eq_iff)
done
lemma AC2_AC1_aux3:
"\<forall>D \<in> {E*{E}. E \<in> A}. \<exists>y. D \<inter> C = {y}
\<Longrightarrow> (\<lambda>x \<in> A. fst(THE z. (x*{x} \<inter> C = {z}))) \<in> (\<Prod>X \<in> A. X)"
apply (rule lam_type)
apply (drule bspec, blast)
apply (blast intro: AC2_AC1_aux2 fst_type)
done
lemma AC2_AC1: "AC2 \<Longrightarrow> AC1"
unfolding AC1_def AC2_def pairwise_disjoint_def
apply (intro allI impI)
apply (elim allE impE)
prefer 2 apply (fast elim!: AC2_AC1_aux3)
apply (blast intro!: AC2_AC1_aux1)
done
(* ********************************************************************** *)
(* AC1 \<Longrightarrow> AC4 *)
(* ********************************************************************** *)
lemma empty_notin_images: "0 \<notin> {R``{x}. x \<in> domain(R)}"
by blast
lemma AC1_AC4: "AC1 \<Longrightarrow> AC4"
unfolding AC1_def AC4_def
apply (intro allI impI)
apply (drule spec, drule mp [OF _ empty_notin_images])
apply (best intro!: lam_type elim!: apply_type)
done
(* ********************************************************************** *)
(* AC4 \<Longrightarrow> AC3 *)
(* ********************************************************************** *)
lemma AC4_AC3_aux1: "f \<in> A->B \<Longrightarrow> (\<Union>z \<in> A. {z}*f`z) \<subseteq> A*\<Union>(B)"
by (fast dest!: apply_type)
lemma AC4_AC3_aux2: "domain(\<Union>z \<in> A. {z}*f(z)) = {a \<in> A. f(a)\<noteq>0}"
by blast
lemma AC4_AC3_aux3: "x \<in> A \<Longrightarrow> (\<Union>z \<in> A. {z}*f(z))``{x} = f(x)"
by fast
lemma AC4_AC3: "AC4 \<Longrightarrow> AC3"
unfolding AC3_def AC4_def
apply (intro allI ballI)
apply (elim allE impE)
apply (erule AC4_AC3_aux1)
apply (simp add: AC4_AC3_aux2 AC4_AC3_aux3 cong add: Pi_cong)
done
(* ********************************************************************** *)
(* AC3 \<Longrightarrow> AC1 *)
(* ********************************************************************** *)
lemma AC3_AC1_lemma:
"b\<notin>A \<Longrightarrow> (\<Prod>x \<in> {a \<in> A. id(A)`a\<noteq>b}. id(A)`x) = (\<Prod>x \<in> A. x)"
apply (simp add: id_def cong add: Pi_cong)
apply (rule_tac b = A in subst_context, fast)
done
lemma AC3_AC1: "AC3 \<Longrightarrow> AC1"
unfolding AC1_def AC3_def
apply (fast intro!: id_type elim: AC3_AC1_lemma [THEN subst])
done
(* ********************************************************************** *)
(* AC4 \<Longrightarrow> AC5 *)
(* ********************************************************************** *)
lemma AC4_AC5: "AC4 \<Longrightarrow> AC5"
unfolding range_def AC4_def AC5_def
apply (intro allI ballI)
apply (elim allE impE)
apply (erule fun_is_rel [THEN converse_type])
apply (erule exE)
apply (rename_tac g)
apply (rule_tac x=g in bexI)
apply (blast dest: apply_equality range_type)
apply (blast intro: Pi_type dest: apply_type fun_is_rel)
done
(* ********************************************************************** *)
(* AC5 \<Longrightarrow> AC4, Rubin & Rubin, p. 11 *)
(* ********************************************************************** *)
lemma AC5_AC4_aux1: "R \<subseteq> A*B \<Longrightarrow> (\<lambda>x \<in> R. fst(x)) \<in> R -> A"
by (fast intro!: lam_type fst_type)
lemma AC5_AC4_aux2: "R \<subseteq> A*B \<Longrightarrow> range(\<lambda>x \<in> R. fst(x)) = domain(R)"
by (unfold lam_def, force)
lemma AC5_AC4_aux3: "\<lbrakk>\<exists>f \<in> A->C. P(f,domain(f)); A=B\<rbrakk> \<Longrightarrow> \<exists>f \<in> B->C. P(f,B)"
apply (erule bexE)
apply (frule domain_of_fun, fast)
done
lemma AC5_AC4_aux4: "\<lbrakk>R \<subseteq> A*B; g \<in> C->R; \<forall>x \<in> C. (\<lambda>z \<in> R. fst(z))` (g`x) = x\<rbrakk>
\<Longrightarrow> (\<lambda>x \<in> C. snd(g`x)): (\<Prod>x \<in> C. R``{x})"
apply (rule lam_type)
apply (force dest: apply_type)
done
lemma AC5_AC4: "AC5 \<Longrightarrow> AC4"
apply (unfold AC4_def AC5_def, clarify)
apply (elim allE ballE)
apply (drule AC5_AC4_aux3 [OF _ AC5_AC4_aux2], assumption)
apply (fast elim!: AC5_AC4_aux4)
apply (blast intro: AC5_AC4_aux1)
done
(* ********************************************************************** *)
(* AC1 \<longleftrightarrow> AC6 *)
(* ********************************************************************** *)
lemma AC1_iff_AC6: "AC1 \<longleftrightarrow> AC6"
by (unfold AC1_def AC6_def, blast)
end
|
From iris.heap_lang Require Export lang.
From stdpp Require Import gmap.
(* This file contains some metatheory about the heap_lang language,
which is not needed for verifying programs. *)
(* Closed expressions and values. *)
Fixpoint is_closed_expr (X : list string) (e : expr) : bool :=
match e with
| Val v => is_closed_val v
| Var x => bool_decide (x ∈ X)
| Rec f x e => is_closed_expr (f :b: x :b: X) e
| UnOp _ e | Fst e | Snd e | InjL e | InjR e | Fork e | Alloc e | Load e =>
is_closed_expr X e
| App e1 e2 | BinOp _ e1 e2 | Pair e1 e2 | Store e1 e2 | FAA e1 e2
| ResolveProph e1 e2 =>
is_closed_expr X e1 && is_closed_expr X e2
| If e0 e1 e2 | Case e0 e1 e2 | CAS e0 e1 e2 =>
is_closed_expr X e0 && is_closed_expr X e1 && is_closed_expr X e2
| NewProph => true
end
with is_closed_val (v : val) : bool :=
match v with
| LitV _ => true
| RecV f x e => is_closed_expr (f :b: x :b: []) e
| PairV v1 v2 => is_closed_val v1 && is_closed_val v2
| InjLV v | InjRV v => is_closed_val v
end.
Lemma is_closed_weaken X Y e : is_closed_expr X e → X ⊆ Y → is_closed_expr Y e.
Proof. revert X Y; induction e; naive_solver (eauto; set_solver). Qed.
Lemma is_closed_weaken_nil X e : is_closed_expr [] e → is_closed_expr X e.
Proof. intros. by apply is_closed_weaken with [], list_subseteq_nil. Qed.
Lemma is_closed_subst X e x v :
is_closed_val v → is_closed_expr (x :: X) e → is_closed_expr X (subst x v e).
Proof.
intros Hv. revert X.
induction e=> X /= ?; destruct_and?; split_and?; simplify_option_eq;
try match goal with
| H : ¬(_ ∧ _) |- _ => apply not_and_l in H as [?%dec_stable|?%dec_stable]
end; eauto using is_closed_weaken with set_solver.
Qed.
Lemma is_closed_subst' X e x v :
is_closed_val v → is_closed_expr (x :b: X) e → is_closed_expr X (subst' x v e).
Proof. destruct x; eauto using is_closed_subst. Qed.
(* Substitution *)
Lemma subst_is_closed X e x es : is_closed_expr X e → x ∉ X → subst x es e = e.
Proof.
revert X. induction e=> X /=; rewrite ?bool_decide_spec ?andb_True=> ??;
repeat case_decide; simplify_eq/=; f_equal; intuition eauto with set_solver.
Qed.
Lemma subst_is_closed_nil e x v : is_closed_expr [] e → subst x v e = e.
Proof. intros. apply subst_is_closed with []; set_solver. Qed.
Lemma subst_subst e x v v' :
subst x v (subst x v' e) = subst x v' e.
Proof.
intros. induction e; simpl; try (f_equal; by auto);
simplify_option_eq; auto using subst_is_closed_nil with f_equal.
Qed.
Lemma subst_subst' e x v v' :
subst' x v (subst' x v' e) = subst' x v' e.
Proof. destruct x; simpl; auto using subst_subst. Qed.
Lemma subst_subst_ne e x y v v' :
x ≠ y → subst x v (subst y v' e) = subst y v' (subst x v e).
Proof.
intros. induction e; simpl; try (f_equal; by auto);
simplify_option_eq; auto using eq_sym, subst_is_closed_nil with f_equal.
Qed.
Lemma subst_subst_ne' e x y v v' :
x ≠ y → subst' x v (subst' y v' e) = subst' y v' (subst' x v e).
Proof. destruct x, y; simpl; auto using subst_subst_ne with congruence. Qed.
Lemma subst_rec' f y e x v :
x = f ∨ x = y ∨ x = BAnon →
subst' x v (Rec f y e) = Rec f y e.
Proof. intros. destruct x; simplify_option_eq; naive_solver. Qed.
Lemma subst_rec_ne' f y e x v :
(x ≠ f ∨ f = BAnon) → (x ≠ y ∨ y = BAnon) →
subst' x v (Rec f y e) = Rec f y (subst' x v e).
Proof. intros. destruct x; simplify_option_eq; naive_solver. Qed.
(* The stepping relation preserves closedness *)
Lemma head_step_is_closed e1 σ1 obs e2 σ2 es :
is_closed_expr [] e1 →
map_Forall (λ _ v, is_closed_val v) σ1.(heap) →
head_step e1 σ1 obs e2 σ2 es →
is_closed_expr [] e2 ∧ Forall (is_closed_expr []) es ∧
map_Forall (λ _ v, is_closed_val v) σ2.(heap).
Proof.
intros Cl1 Clσ1 STEP.
destruct STEP; simpl in *; split_and!;
try apply map_Forall_insert_2; try by naive_solver.
- subst. repeat apply is_closed_subst'; naive_solver.
- unfold un_op_eval in *. repeat case_match; naive_solver.
- unfold bin_op_eval, bin_op_eval_bool in *. repeat case_match; naive_solver.
Qed.
|
vast new areas of the Earth.
cut off the icy Arctic current to the North, while the warm Japan current played upon the South coast.
the New World, perhaps originally more than 100 thousands of years ago (ka) and probably on several excursions.
oceanic channel 0.9 to 0.8 Ma [1, 2]. We have no evidence to suggest that they knew how to make boats so early.
kilometers wide nearly a million years ago [3-6]. Morwood et al. [1, 2] have concluded that Homo erectus was capable of repeated water crossings using water-craft, by the beginning of the middle Pleistocene, 0.7-0.9 Ma.
Some 6 million years ago we split from a common ancestor with chimps. Fossils found at the key sites shown on the map below reveal that hominins then diversified into many species and spread far from their ancestral home in Africa. Click on each site to learn more about what we've found there.
resource use & coastal settlements by Hs.
Here, we provide a long-term & evolutionary perspective of these behaviors.
dates to MIS-5 & -4.
Africa during this time frame.
particularly often in (near)coastal MSA sites.
- more formal evolutionary models & research strategies. |
-- ---------------------------------------------------------------------
-- Ejercicio. Inportar las teoría de los números reales, filtros y
-- topología.
-- ---------------------------------------------------------------------
import data.real.basic
import order.filter.at_top_bot
import topology.instances.real
-- ---------------------------------------------------------------------
-- Ejercicio. Definir localmente |x| como el valor absoluto de x.
-- ---------------------------------------------------------------------
local notation `|` x `|` := abs x
-- ---------------------------------------------------------------------
-- Ejercicio. Definir la función
-- is_limit : (ℕ → ℝ) → ℝ → Prop
-- tal que (is_limit a l) expresa que l es el límite de la sucesión a.
-- ---------------------------------------------------------------------
definition is_limit : (ℕ → ℝ) → ℝ → Prop :=
λ a l, ∀ ε > 0, ∃ N, ∀ n ≥ N, | a n - l | < ε
-- Nota: Anteriormente vimos pruebas de propiedades de límites. A
-- continuación las volveremos a demostrar usando propiedades de filtros
-- utilizando hechos de mathlib sobre filtros.
-- ---------------------------------------------------------------------
-- Ejercicio. Abrir el espacio de nombre de filtros.
-- ---------------------------------------------------------------------
open filter
-- ---------------------------------------------------------------------
-- Ejercicio. Abrir localmente el espacio de nombre de espacios topógicos.
-- ---------------------------------------------------------------------
open_locale topological_space
-- ---------------------------------------------------------------------
-- Ejercicio. Abrir el espacio de nombre de espacios métricos.
-- ---------------------------------------------------------------------
open metric
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que
-- is_limit a l ↔ tendsto a at_top (𝓝 l)
-- ---------------------------------------------------------------------
theorem is_limit_iff_tendsto
(a : ℕ → ℝ)
(l : ℝ)
: is_limit a l ↔ tendsto a at_top (𝓝 l) :=
begin
rw metric.tendsto_at_top,
refl,
end
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que el límite de un producto es el producto de
-- los límites.
-- ---------------------------------------------------------------------
theorem is_limit_mul
(a b : ℕ → ℝ)
(l m : ℝ)
(ha : is_limit a l)
(hb : is_limit b m)
: is_limit (a * b) (l * m) :=
begin
rw is_limit_iff_tendsto at *,
exact tendsto.mul ha hb,
end
-- ¡Esta es mucho menos trabajosoa que la que vimos en la semana 3!
-- Entonces, ¿en qué dónde está el trabajo?
--
-- Las siguientes 120 líneas de este archivo discuten la primera prueba,
-- a saber `es_limit_iff_tendsto`. Está claro que los ingredientes clave
-- son `metric.tendsto_at_top`. No hay ejercicios aquí, sólo voy a
-- explicar lo que está pasando, y hablar de las definiciones (por
-- ejemplo, `es_limit`) y su coste.
--
-- La segunda prueba utiliza `is_limit_iff_tendsto` para reducir
-- `is_limit_mul` a un teorema sobre filtros, y lo demuestra con
-- `tendsto.mul`. Nosotros probaremos nuestra propia versión de
-- `tendsto.mul` en este archivo. Así que si quieres seguir con la
-- demostración puedes pasar directamente a la sección `tendsto.mul`
-- en la línea 177 más o menos.
-- =====================================================================
-- § Definiciones en Lean --
-- =====================================================================
-- Cada *definición* que haces en Lean tiene un coste. Por ejemplo mira
-- la definición de Lean de `finset`, el tipo de conjuntos finitos. Haz
-- clic con el botón derecho del ratón en `finset` y haz clic en "ir a
-- la definición". Ves una definición, y luego más de 2000 líneas de
-- teoremas sobre esta definición. No olvides cerrar el archivo después.
-- #check finset
-- Los teoremas son necesarios porque no sirve sólo definir algún
-- concepto de conjunto finito, hay que hacerlo intuitivo para el
-- usuario final, por lo que hay que demostrar que un subconjunto de un
-- conjunto finito es finito, la unión de dos conjuntos finitos es
-- finita, la imagen de un conjunto finito bajo una aplicación mapa es
-- finita, el producto de dos conjuntos finitos es finito, un producto
-- finito de conjuntos finitos indexados por un conjunto finito es
-- finito, etc. Cada uno de esos lemas de ese archivo es completamente
-- obvio para un matemático, pero necesita ser demostrado en Lean para
-- que los matemáticos puedan usar los conjuntos de la forma en que
-- intuitivamente quieren hacerlo. Mira si puedes entender algunas de
-- las afirmaciones demostradas sobre conjuntos finitos en ese
-- archivo. Ten mucho cuidado de no editarlo. Si accidentalmente lo
-- cambias, simplemente cierra el archivo archivo sin guardarlo, o usa
-- ctrl-Z para deshacer los cambios.
--
-- Cuando desarrollamos la teoría de los límites de las secuencias en la
-- semana 3, escribimos la definición `is_limit`. Esta definición tiene
-- un coste; para que sea útil para el usuario final, tenemos que
-- demostrar una tonelada de teoremas sobre `is_limit`. Esto es lo que
-- sucede en una clase de análisis de licenciatura: ves la definición y
-- luego haces lo que los informáticos llaman la "API" o la "interfaz"
-- (un montón de lemas y teoremas sobre "is_limit"); por ejemplo,
-- "is_limit_add", que dice que `aₙ → l` y `bₙ → m` implica `a_n + b_n →
-- l + m`, y también `is_limit_neg`, `es_limit_sub`, `es_limit_mul` y
-- así sucesivamente.
--
-- Pero resulta que `is_limit` es sólo un caso muy especial de
-- `tendsto`, y como `tendsto` ya está en mathlib, ya hay una gran API
-- para `tendsto` que se ha desarrollado en los últimos años. Fue
-- iniciada por el autor original de `tendsto` y luego creció a medida
-- que otras personas usaron más `tendsto`, y añadieron a la lista de
-- lemas útiles más lemas útiles a medida que usaban `tendsto` para
-- hacer otras cosas y luego abstraían propiedades que descubrieron que
-- eran útiles. Por ejemplo, esta semana (escribo esto en febrero de
-- 2021) Heather Macbeth estaba trabajando en formas modulares en Lean y
-- descubrió que necesitaba un lema sobre `tendsto`, que, después de
-- algunas discusión en el chat de Zulip Lean, Heather y yo nos dimos
-- cuenta de que era una declaración sobre cómo `tendsto` conmuta con un
-- cierto tipo de coproducto. Lo demostramos y Heather está ahora mismo
-- en proceso de añadirlo (`tendsto.prod_map_coprod`) a `mathlib`, la
-- biblioteca de matemáticas de Lean.
--
-- Debo señalar que nunca habría trabajado en ese problema con Heather
-- si no hubiera sido por el hecho de que le había estado enseñando
-- sobre filtros y, por lo tanto, ¡tenía que aprender sobre ellos como
-- es debido!
--
-- Volvamos a ver nuestra nueva prueba de `tendsto_mul`. La prueba se
-- desprende de dos lemas de 2 líneas. Yo te explicaré el primero, y tú
-- puedes experimentar con el segundo. Veamos el primero.
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que
-- is_limit a l ↔ tendsto a at_top (𝓝 l) :=
-- ---------------------------------------------------------------------
example
(a : ℕ → ℝ)
(l : ℝ)
: is_limit a l ↔ tendsto a at_top (𝓝 l) :=
begin
rw metric.tendsto_at_top,
refl,
end
-- Las tripas de la primera es `metric.tendsto_at_top`, que es en
-- realidad una declaración sobre los espacios métricos. Dice que en
-- cualquier espacio métrico, la definición estándar del espacio métrico
-- épsilon-N de un límite de una secuencia es un caso especial de este
-- predicado de filtro `tendsto`. Aquí hay una prueba con más detalles
-- (`simp_rw` es sólo una versión ligeramente más versión de `rw` que
-- necesitamos por razones técnicas, porque `rw` no se ve bajo una
-- sentencia `∀`):
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que
-- is_limit a l ↔ tendsto a at_top (𝓝 l)
-- ---------------------------------------------------------------------
-- Esta prueba más explícita utiliza la siguiente notación elegante
-- llamada "filter.eventually" :
-- `(∀ᶠ (x : α) en F, P x) ↔ {x : α | P x} ∈ F`
-- y entonces sólo se reduce a los siguientes dos hechos matemáticos
-- (aquí `ball l ε` es la bola abierta de radio `ε` centro `l` ), el
-- primero es `metric.tendsto_nhds` y el segundo `mem_at_top_sets`:
-- 1) Si `a` está en un espacio métrico, entonces
-- `S ∈ 𝓝 l ↔ ∃ ε > 0, bola l ε ⊆ S`
-- 2) Si `at_top` es el filtro sobre `ℕ` que vimos la última vez,
-- entonces `T ∈ at_top ↔ ∃ N : ℕ, {n : ℕ | N ≤ n} ⊆ T``
--
-- El resto es fácil, porque `tendsto a at_top (𝓝 l)` significa,
-- por definición de `tendsto`,
-- `∀ S : set ℝ, S ∈ 𝓝 l → a -¹' S ∈ at_top`
-- que se traduce en
-- `∀ S : set ℝ, (∃ ε > 0, ball l ⊆ S) → (∃ N, n ≥ N → a n ∈ S)`.
-- y si se despliega el envoltorio lógico se verá que esto no es más que
-- la definición habitual de `is_limit` (nótese que `a n ∈ ball l ε` es
-- definición es igual a `dist (a n) l < ε` que, para los reales, es
-- es igual a `|a n - l| < ε`).
-- Demostración:
-- is_limit a l
-- ↔ ∀ ε, ε > 0 → (∃ c, ∀ b , b ≥ c → b ∈ {x : ℕ | dist (a x) l < ε})
-- [por def. de límite]
-- ↔ ∀ ε, ε > 0 → {x | dist (a x) l < ε} ∈ at_top
-- [por mem_at_top_sets]
-- ↔ ∀ ε, ε > 0 → (∀ᶠ x in at_top, dist (a x) l < ε)
-- [por eventually_iff]
-- ↔ tendsto a at_top (𝓝 l)
example
(a : ℕ → ℝ)
(l : ℝ)
: is_limit a l ↔ tendsto a at_top (𝓝 l) :=
begin
simp_rw [metric.tendsto_nhds, eventually_iff, mem_at_top_sets],
refl,
end
-- =====================================================================
-- § tendsto.mul --
-- =====================================================================
-- Veamos ahora el segundo ejemplo.
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que el límite del producto es el producto de los
-- límites.
-- ---------------------------------------------------------------------
example
(a b : ℕ → ℝ)
(l m : ℝ)
(ha : is_limit a l)
(hb : is_limit b m)
: is_limit (a * b) (l * m) :=
begin
rw is_limit_iff_tendsto at *,
exact tendsto.mul ha hb,
end
-- Si pasas el ratón por encima de `tendsto.mul` en esa prueba, quizás
-- puedas distinguir que dice lo siguiente: si tenemos un espacio
-- topológico `M` con una multiplicación continua en él, y si `F` es un
-- filtro en `α` y `f` y `g` son aplicaciones `α → M`, entonces `tendsto
-- f F (𝓝 l)` y `tendsto g F (𝓝 m)` implica `tendsto a (f * g) F 𝓝 (l *
-- m)`. Aplicamos esto con `F` el filtro cofinito y ya hemos terminado,
-- usando que la multiplicación en ℝ es una función continua. ¿Cómo
-- sabía Lean esto? Pues, `[has_continuous_mul M]` estaba entre
-- corchetes así que eso significa que el sistema de inferencia de
-- clases de tipo se supone que se ocupa de ello. Vamos ver cómo se las
-- arregla con la afirmación de que la multiplicación es continua en los
-- reales.
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que la multiplicación es los reales es continua.
-- ---------------------------------------------------------------------
example : has_continuous_mul ℝ :=
begin
apply_instance
end
-- La gente que definió `ℝ` en Lean hizo una definición, y el precio que
-- tuvieron que pagar para hacerla utilizable fue que tuvieron que hacer
-- una gran API para para demostrar que un conjunto acotado no vacío de
-- reales tiene un límite superior mínimo y que los reales eran un
-- anillo topológico (y por lo tanto la multiplicación era
-- continua). Pero este precio se pagó en 2018 por lo que los
-- matemáticos podemos ahora utilizar estos hechos de forma gratuita.
--
-- Todo lo que queda entonces, si queremos ver los detalles, es
-- demostrar `tendsto.mul`, y esto es una afirmación sobre filtros en
-- espacios topológicos, así que hagámoslo. Primero ¿qué significa
-- `continuo`?
-- =====================================================================
-- § Continuidad --
-- =====================================================================
-- ---------------------------------------------------------------------
-- Ejercicio. Declarar X e Y como espacios topológicos y f : X → Y
-- ---------------------------------------------------------------------
variables (X Y : Type) [topological_space X] [topological_space Y]
variable (f : X → Y)
-- Si `x : X`, ¿qué significa que `f` sea continua en `x`?
-- Intuitivamente, significa que si se mueve `x` una pequeña cantidad,
-- entonces `f x` se mueve en una pequeña cantidad. En otras palabras,
-- "f" envía un pequeño entorno de `x` a un pequeño entorno de `f x`.
--
-- Si nuestro modelo mental del filtro de entorno `𝓝 x` es una especie
-- de conjunto generalizado que corresponde a un entorno infinitesimal
-- de `x`, veremos por qué Lean tiene la siguiente definición de
-- "continuo":
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que
-- continuous_at f x ↔ tendsto f (𝓝 x) (𝓝 (f x))
-- ---------------------------------------------------------------------
lemma continuous_at_def
(x : X)
: continuous_at f x ↔ tendsto f (𝓝 x) (𝓝 (f x)) :=
begin
refl,
end
-- Es probable que te hayan dicho lo que significa que una función `f :
-- X → Y` entre espacios *métricos* sea continua en `x`. ¿Te han dicho
-- alguna vez lo que significa que una función entre espacios
-- "topológicos" sea continua en "x", en lugar de ser continua en todo
-- "X"? Este es lo que significa.
--
-- Ahora vamos a empezar con la prueba de `tendsto.mul`, construyendo
-- una API para la definición de `continuous_at`. No olvides cosas como
-- `tendsto_id : tendsto id x x`
-- ` tendsto.comp : tendsto g G H → tendsto f F G → tendsto (g ∘ f) F H`
-- de la orimera parte de este tema.
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que la identidad es continua en todos los
-- puntos.
-- ---------------------------------------------------------------------
example
(x : X)
: continuous_at id x :=
begin
exact tendsto_id,
end
-- ---------------------------------------------------------------------
-- Ejercicio. Declarar Z como espacio topológico y g : Y → Z
-- ---------------------------------------------------------------------
variables (Z : Type) [topological_space Z]
variable (g : Y → Z)
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que la composición de funciones continuas es
-- continua.
-- ---------------------------------------------------------------------
example
(x : X)
(hf : continuous_at f x)
(hg : continuous_at g (f x))
: continuous_at (g ∘ f) x :=
begin
exact tendsto.comp hg hf,
end
-- Ahora demostramos un resultado clave, llamado `tendsto.prod_mk_nhds`.
--
-- Notación para el producto de tipos: si `Y` y `Z` son tipos, entonces
-- `Y × Z` es el producto de tipos, y la notación para un término
-- general es `(y, z) : Y × Z` con `y : Y` y `z : Z`.
--
-- Un caso especial del teorema siguiente es que si las aplicaciones
-- `f : X → Y` y `g : X → Z` son continuas en `x` entonces el producto
-- `f × g : X → Y × Z` es también continua en `x`. Vamos a demostrar
-- algo más general: si `α` es un tipo cualquiera y `F : filtro α` es
-- cualquier filtro, `y : Y`, `z : Z` y `f : α → Y` y `g : α → Z`
-- satisfacen `tendsto f F (𝓝 y)` y `tendsto g F (𝓝 z)`, entonces
-- `tendsto a (f × g) F (𝓝 (y,z))`, donde "f × g" es la 1a aplicación
-- `λ x, (f x, g x)`.
-- El dato clave que necesitarás de la API de topología del producto es
-- mem_nhds_prod_iff :
-- S ∈ 𝓝 ((a, b) : X × Y) ↔`
-- ∃ (U : set X) (H : U ∈ 𝓝 a) (V :set Y) (H : V ∈ 𝓝 b), U.prod V ⊆ S
-- Esto es todo lo que deberías necesitar sobre la topología del
-- producto (no vamos a entrar en cómo está definida la topología del
-- producto, pero el hecho clave dice matemáticamente que un entorno
-- de `(a,b) : X × Y` contiene un producto de entornos de `X` y de
-- `Y`).
--
-- También necesitarás saber
-- mk_mem_prod : a ∈ U → b ∈ V → (a, b) ∈ U.prod V
-- donde para `U : set X` y `V : set Y`, `U.prod V = prod U V` es el
-- subconjunto obvio de `X × Y`.
--
-- Recordemos también de primera la parte del tema:
-- mem_map : S ∈ map φ F ↔ {x : α | φ x ∈ S} ∈ F
-- tendsto_def : tendsto f F G ↔ ∀ (S : conjunto Y), S ∈ G → f -¹' S ∈ F
-- (aunque aquí hay una trampa: la definición real de
-- `tendsto f F G` es `∀ {S : set Y}, S ∈ G ...` )
-- #check tendsto_def
-- this is called `tendsto.prod_mk_nhds` in Lean but try proving it yourself.
example {α : Type} (f : α → Y) (g : α → Z) (x : X) (F : filter α) (y : Y) (z : Z)
(hf : tendsto f F (𝓝 y)) (hg : tendsto g F (𝓝 z)) :
tendsto (λ x, (f x, g x)) F (𝓝 (y, z)) :=
begin
-- say `S` is a neighbourhood of `(y, z)`.
rintro S hS,
-- use the given fact about neighbourhoods of point in a product of top spaces
rw mem_nhds_prod_iff at hS,
-- to get neighbourhoods of `y` and `z`.
rcases hS with ⟨U, hU, V, hV, h⟩,
-- The goal is `S ∈ map ...` so use `mem_map`.
rw mem_map,
-- I claim {x : α | f x ∈ U} ∈ F
have hfxU : {x : α | f x ∈ U} ∈ F := hf hU, -- technical note: I didn't
-- rewrite `tendsto_def` so I don't supply `U`
-- I claim {x : α | g x ∈ V} ∈ F
have hgxV : {x : α | g x ∈ V} ∈ F := hg hV,
-- so their intersection is in F
have hfg := inter_mem_sets hfxU hgxV,
-- and so it suffices to show that their intersection contains `{x : α | (f x, g x) ∈ S}`
refine mem_sets_of_superset hfg _,
-- but we just now take everything apart
rintro x ⟨(hxf : f x ∈ U), (hxg : g x ∈ V)⟩,
apply h,
-- and apply mk_mem_prod
exact set.mk_mem_prod hxf hxg,
end
-- Armed with `tendsto.prod_mk_nhds`, let's prove the version of `tendsto.mul`
-- which we need
lemma key_lemma {α M : Type} [topological_space M] [has_mul M]
{f g : α → M} {F : filter α} {a b : M} (hf : tendsto f F (𝓝 a))
(hg : tendsto g F (𝓝 b))
(hcontinuous : continuous_at (λ (mn : M × M), mn.1 * mn.2) (a,b)) :
tendsto (f * g) F (𝓝 (a * b)) :=
begin
set f1 : M × M → M := λ mn, mn.1 * mn.2 with hf1,
set f2 : α → M × M := λ x, (f x, g x) with hf2,
have h1 : f1 ∘ f2 = f * g,
{ ext x,
refl },
have h2 : tendsto f2 F (𝓝 (a, b)) := tendsto.prod_mk_nhds hf hg,
rw ← h1,
apply tendsto.comp _ h2,
apply hcontinuous,
end
-- The final ingredient is that multiplication is continuous on ℝ, which we
-- just take from the real API:
lemma real.continuous_mul_at (a b : ℝ) :
continuous_at (λ xy : ℝ × ℝ, xy.1 * xy.2) (a, b) :=
begin
-- it's in the library
exact continuous.continuous_at real.continuous_mul,
end
-- and now we have all the ingredients we need for our own proof of `is_limit_mul`!
example (a b : ℕ → ℝ) (l m : ℝ)
(ha : is_limit a l) (hb : is_limit b m) :
is_limit (a * b) (l * m) :=
begin
rw is_limit_iff_tendsto at *,
apply key_lemma ha hb,
apply real.continuous_mul_at,
end
|
------------------------------------------------------------------------
-- The Agda standard library
--
-- Automatic solver for equations over product and sum types
--
-- See examples at the bottom of the file for how to use this solver
------------------------------------------------------------------------
{-# OPTIONS --without-K --safe #-}
module Function.Related.TypeIsomorphisms.Solver where
open import Algebra using (CommutativeSemiring)
import Algebra.Solver.Ring.NaturalCoefficients.Default
open import Data.Empty using (⊥)
open import Data.Product using (_×_)
open import Data.Sum using (_⊎_)
open import Data.Unit using (⊤)
open import Level using (Level; Lift)
open import Function.Inverse as Inv using (_↔_)
open import Function.Related as Related
open import Function.Related.TypeIsomorphisms
------------------------------------------------------------------------
-- The solver
module ×-⊎-Solver (k : Symmetric-kind) {ℓ} =
Algebra.Solver.Ring.NaturalCoefficients.Default
(×-⊎-commutativeSemiring k ℓ)
------------------------------------------------------------------------
-- Tests
private
-- A test of the solver above.
test : {ℓ : Level} (A B C : Set ℓ) →
(Lift ℓ ⊤ × A × (B ⊎ C)) ↔ (A × B ⊎ C × (Lift ℓ ⊥ ⊎ A))
test = solve 3 (λ A B C → con 1 :* (A :* (B :+ C)) :=
A :* B :+ C :* (con 0 :+ A))
Inv.id
where open ×-⊎-Solver bijection
|
[GOAL]
y : ℝ
hy : 0 < y
⊢ Tendsto (fun x => x ^ y) atTop atTop
[PROOFSTEP]
rw [tendsto_atTop_atTop]
[GOAL]
y : ℝ
hy : 0 < y
⊢ ∀ (b : ℝ), ∃ i, ∀ (a : ℝ), i ≤ a → b ≤ a ^ y
[PROOFSTEP]
intro b
[GOAL]
y : ℝ
hy : 0 < y
b : ℝ
⊢ ∃ i, ∀ (a : ℝ), i ≤ a → b ≤ a ^ y
[PROOFSTEP]
use max b 0 ^ (1 / y)
[GOAL]
case h
y : ℝ
hy : 0 < y
b : ℝ
⊢ ∀ (a : ℝ), max b 0 ^ (1 / y) ≤ a → b ≤ a ^ y
[PROOFSTEP]
intro x hx
[GOAL]
case h
y : ℝ
hy : 0 < y
b x : ℝ
hx : max b 0 ^ (1 / y) ≤ x
⊢ b ≤ x ^ y
[PROOFSTEP]
exact
le_of_max_le_left
(by
convert rpow_le_rpow (rpow_nonneg_of_nonneg (le_max_right b 0) (1 / y)) hx (le_of_lt hy) using 1
rw [← rpow_mul (le_max_right b 0), (eq_div_iff (ne_of_gt hy)).mp rfl, Real.rpow_one])
[GOAL]
y : ℝ
hy : 0 < y
b x : ℝ
hx : max b 0 ^ (1 / y) ≤ x
⊢ max b ?m.773 ≤ x ^ y
[PROOFSTEP]
convert rpow_le_rpow (rpow_nonneg_of_nonneg (le_max_right b 0) (1 / y)) hx (le_of_lt hy) using 1
[GOAL]
case h.e'_3
y : ℝ
hy : 0 < y
b x : ℝ
hx : max b 0 ^ (1 / y) ≤ x
⊢ max b ?m.773 = (max b 0 ^ (1 / y)) ^ y
[PROOFSTEP]
rw [← rpow_mul (le_max_right b 0), (eq_div_iff (ne_of_gt hy)).mp rfl, Real.rpow_one]
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
⊢ Tendsto (Real.rpow b) atTop (𝓝 0)
[PROOFSTEP]
show Tendsto (fun z => b ^ z) atTop (𝓝 0)
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
⊢ Tendsto (fun z => b ^ z) atTop (𝓝 0)
[PROOFSTEP]
rcases lt_trichotomy b 0 with hb | rfl | hb
[GOAL]
case inl
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ Tendsto (fun z => b ^ z) atTop (𝓝 0)
case inr.inl
hb₀ : -1 < 0
hb₁ : 0 < 1
⊢ Tendsto (fun z => 0 ^ z) atTop (𝓝 0)
case inr.inr b : ℝ hb₀ : -1 < b hb₁ : b < 1 hb : 0 < b ⊢ Tendsto (fun z => b ^ z) atTop (𝓝 0)
[PROOFSTEP]
case inl =>
-- b < 0
simp_rw [Real.rpow_def_of_nonpos hb.le, hb.ne, ite_false]
rw [← isLittleO_const_iff (c := (1 : ℝ)) one_ne_zero, (one_mul (1 : ℝ)).symm]
refine IsLittleO.mul_isBigO ?exp ?cos
case exp =>
rw [isLittleO_const_iff one_ne_zero]
refine tendsto_exp_atBot.comp <| (tendsto_const_mul_atBot_of_neg ?_).mpr tendsto_id
rw [← log_neg_eq_log, log_neg_iff (by linarith)]
linarith
case cos =>
rw [isBigO_iff]
exact ⟨1, eventually_of_forall fun x => by simp [Real.abs_cos_le_one]⟩
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ Tendsto (fun z => b ^ z) atTop (𝓝 0)
[PROOFSTEP]
case inl =>
-- b < 0
simp_rw [Real.rpow_def_of_nonpos hb.le, hb.ne, ite_false]
rw [← isLittleO_const_iff (c := (1 : ℝ)) one_ne_zero, (one_mul (1 : ℝ)).symm]
refine IsLittleO.mul_isBigO ?exp ?cos
case exp =>
rw [isLittleO_const_iff one_ne_zero]
refine tendsto_exp_atBot.comp <| (tendsto_const_mul_atBot_of_neg ?_).mpr tendsto_id
rw [← log_neg_eq_log, log_neg_iff (by linarith)]
linarith
case cos =>
rw [isBigO_iff]
exact ⟨1, eventually_of_forall fun x => by simp [Real.abs_cos_le_one]⟩
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ Tendsto (fun z => b ^ z) atTop (𝓝 0)
[PROOFSTEP]
simp_rw [Real.rpow_def_of_nonpos hb.le, hb.ne, ite_false]
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ Tendsto (fun z => exp (log b * z) * cos (z * π)) atTop (𝓝 0)
[PROOFSTEP]
rw [← isLittleO_const_iff (c := (1 : ℝ)) one_ne_zero, (one_mul (1 : ℝ)).symm]
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ (fun z => exp (log b * z) * cos (z * π)) =o[atTop] fun _x => 1 * 1
[PROOFSTEP]
refine IsLittleO.mul_isBigO ?exp ?cos
[GOAL]
case exp
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ (fun z => exp (log b * z)) =o[atTop] fun _x => 1
case cos b : ℝ hb₀ : -1 < b hb₁ : b < 1 hb : b < 0 ⊢ (fun z => cos (z * π)) =O[atTop] fun _x => 1
[PROOFSTEP]
case exp =>
rw [isLittleO_const_iff one_ne_zero]
refine tendsto_exp_atBot.comp <| (tendsto_const_mul_atBot_of_neg ?_).mpr tendsto_id
rw [← log_neg_eq_log, log_neg_iff (by linarith)]
linarith
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ (fun z => exp (log b * z)) =o[atTop] fun _x => 1
[PROOFSTEP]
case exp =>
rw [isLittleO_const_iff one_ne_zero]
refine tendsto_exp_atBot.comp <| (tendsto_const_mul_atBot_of_neg ?_).mpr tendsto_id
rw [← log_neg_eq_log, log_neg_iff (by linarith)]
linarith
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ (fun z => exp (log b * z)) =o[atTop] fun _x => 1
[PROOFSTEP]
rw [isLittleO_const_iff one_ne_zero]
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ Tendsto (fun z => exp (log b * z)) atTop (𝓝 0)
[PROOFSTEP]
refine tendsto_exp_atBot.comp <| (tendsto_const_mul_atBot_of_neg ?_).mpr tendsto_id
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ log b < 0
[PROOFSTEP]
rw [← log_neg_eq_log, log_neg_iff (by linarith)]
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ 0 < -b
[PROOFSTEP]
linarith
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ -b < 1
[PROOFSTEP]
linarith
[GOAL]
case cos
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ (fun z => cos (z * π)) =O[atTop] fun _x => 1
[PROOFSTEP]
case cos =>
rw [isBigO_iff]
exact ⟨1, eventually_of_forall fun x => by simp [Real.abs_cos_le_one]⟩
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ (fun z => cos (z * π)) =O[atTop] fun _x => 1
[PROOFSTEP]
case cos =>
rw [isBigO_iff]
exact ⟨1, eventually_of_forall fun x => by simp [Real.abs_cos_le_one]⟩
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ (fun z => cos (z * π)) =O[atTop] fun _x => 1
[PROOFSTEP]
rw [isBigO_iff]
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
⊢ ∃ c, ∀ᶠ (x : ℝ) in atTop, ‖cos (x * π)‖ ≤ c * ‖1‖
[PROOFSTEP]
exact ⟨1, eventually_of_forall fun x => by simp [Real.abs_cos_le_one]⟩
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : b < 0
x : ℝ
⊢ ‖cos (x * π)‖ ≤ 1 * ‖1‖
[PROOFSTEP]
simp [Real.abs_cos_le_one]
[GOAL]
case inr.inl
hb₀ : -1 < 0
hb₁ : 0 < 1
⊢ Tendsto (fun z => 0 ^ z) atTop (𝓝 0)
case inr.inr b : ℝ hb₀ : -1 < b hb₁ : b < 1 hb : 0 < b ⊢ Tendsto (fun z => b ^ z) atTop (𝓝 0)
[PROOFSTEP]
case inr.inl =>
-- b = 0
refine Tendsto.mono_right ?_ (Iff.mpr pure_le_nhds_iff rfl)
rw [tendsto_pure]
filter_upwards [eventually_ne_atTop 0] with _ hx
simp [hx]
[GOAL]
hb₀ : -1 < 0
hb₁ : 0 < 1
⊢ Tendsto (fun z => 0 ^ z) atTop (𝓝 0)
[PROOFSTEP]
case inr.inl =>
-- b = 0
refine Tendsto.mono_right ?_ (Iff.mpr pure_le_nhds_iff rfl)
rw [tendsto_pure]
filter_upwards [eventually_ne_atTop 0] with _ hx
simp [hx]
[GOAL]
hb₀ : -1 < 0
hb₁ : 0 < 1
⊢ Tendsto (fun z => 0 ^ z) atTop (𝓝 0)
[PROOFSTEP]
refine Tendsto.mono_right ?_ (Iff.mpr pure_le_nhds_iff rfl)
[GOAL]
hb₀ : -1 < 0
hb₁ : 0 < 1
⊢ Tendsto (fun z => 0 ^ z) atTop (pure 0)
[PROOFSTEP]
rw [tendsto_pure]
[GOAL]
hb₀ : -1 < 0
hb₁ : 0 < 1
⊢ ∀ᶠ (x : ℝ) in atTop, 0 ^ x = 0
[PROOFSTEP]
filter_upwards [eventually_ne_atTop 0] with _ hx
[GOAL]
case h
hb₀ : -1 < 0
hb₁ : 0 < 1
a✝ : ℝ
hx : a✝ ≠ 0
⊢ 0 ^ a✝ = 0
[PROOFSTEP]
simp [hx]
[GOAL]
case inr.inr
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : 0 < b
⊢ Tendsto (fun z => b ^ z) atTop (𝓝 0)
[PROOFSTEP]
case inr.inr =>
-- b > 0
simp_rw [Real.rpow_def_of_pos hb]
refine tendsto_exp_atBot.comp <| (tendsto_const_mul_atBot_of_neg ?_).mpr tendsto_id
exact (log_neg_iff hb).mpr hb₁
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : 0 < b
⊢ Tendsto (fun z => b ^ z) atTop (𝓝 0)
[PROOFSTEP]
case inr.inr =>
-- b > 0
simp_rw [Real.rpow_def_of_pos hb]
refine tendsto_exp_atBot.comp <| (tendsto_const_mul_atBot_of_neg ?_).mpr tendsto_id
exact (log_neg_iff hb).mpr hb₁
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : 0 < b
⊢ Tendsto (fun z => b ^ z) atTop (𝓝 0)
[PROOFSTEP]
simp_rw [Real.rpow_def_of_pos hb]
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : 0 < b
⊢ Tendsto (fun z => exp (log b * z)) atTop (𝓝 0)
[PROOFSTEP]
refine tendsto_exp_atBot.comp <| (tendsto_const_mul_atBot_of_neg ?_).mpr tendsto_id
[GOAL]
b : ℝ
hb₀ : -1 < b
hb₁ : b < 1
hb : 0 < b
⊢ log b < 0
[PROOFSTEP]
exact (log_neg_iff hb).mpr hb₁
[GOAL]
b : ℝ
hb : 1 < b
⊢ Tendsto (Real.rpow b) atBot (𝓝 0)
[PROOFSTEP]
show Tendsto (fun z => b ^ z) atBot (nhds 0)
[GOAL]
b : ℝ
hb : 1 < b
⊢ Tendsto (fun z => b ^ z) atBot (𝓝 0)
[PROOFSTEP]
simp_rw [Real.rpow_def_of_pos (by positivity : 0 < b)]
[GOAL]
b : ℝ
hb : 1 < b
⊢ 0 < b
[PROOFSTEP]
positivity
[GOAL]
b : ℝ
hb : 1 < b
⊢ Tendsto (fun z => exp (log b * z)) atBot (𝓝 0)
[PROOFSTEP]
refine tendsto_exp_atBot.comp <| (tendsto_const_mul_atBot_of_pos ?_).mpr tendsto_id
[GOAL]
b : ℝ
hb : 1 < b
⊢ 0 < log b
[PROOFSTEP]
exact (log_pos_iff (by positivity)).mpr <| by aesop
[GOAL]
b : ℝ
hb : 1 < b
⊢ 0 < b
[PROOFSTEP]
positivity
[GOAL]
b : ℝ
hb : 1 < b
⊢ 1 < b
[PROOFSTEP]
aesop
[GOAL]
b : ℝ
hb₀ : 0 < b
hb₁ : b < 1
⊢ Tendsto (Real.rpow b) atBot atTop
[PROOFSTEP]
show Tendsto (fun z => b ^ z) atBot atTop
[GOAL]
b : ℝ
hb₀ : 0 < b
hb₁ : b < 1
⊢ Tendsto (fun z => b ^ z) atBot atTop
[PROOFSTEP]
simp_rw [Real.rpow_def_of_pos (by positivity : 0 < b)]
[GOAL]
b : ℝ
hb₀ : 0 < b
hb₁ : b < 1
⊢ 0 < b
[PROOFSTEP]
positivity
[GOAL]
b : ℝ
hb₀ : 0 < b
hb₁ : b < 1
⊢ Tendsto (fun z => exp (log b * z)) atBot atTop
[PROOFSTEP]
refine tendsto_exp_atTop.comp <| (tendsto_const_mul_atTop_iff_neg <| tendsto_id (α := ℝ)).mpr ?_
[GOAL]
b : ℝ
hb₀ : 0 < b
hb₁ : b < 1
⊢ log b < 0
[PROOFSTEP]
exact (log_neg_iff hb₀).mpr hb₁
[GOAL]
b : ℝ
hb : 1 < b
⊢ Tendsto (Real.rpow b) atBot (𝓝 0)
[PROOFSTEP]
show Tendsto (fun z => b ^ z) atBot (𝓝 0)
[GOAL]
b : ℝ
hb : 1 < b
⊢ Tendsto (fun z => b ^ z) atBot (𝓝 0)
[PROOFSTEP]
simp_rw [Real.rpow_def_of_pos (by positivity : 0 < b)]
[GOAL]
b : ℝ
hb : 1 < b
⊢ 0 < b
[PROOFSTEP]
positivity
[GOAL]
b : ℝ
hb : 1 < b
⊢ Tendsto (fun z => exp (log b * z)) atBot (𝓝 0)
[PROOFSTEP]
refine tendsto_exp_atBot.comp <| (tendsto_const_mul_atBot_iff_pos <| tendsto_id (α := ℝ)).mpr ?_
[GOAL]
b : ℝ
hb : 1 < b
⊢ 0 < log b
[PROOFSTEP]
exact (log_pos_iff (by positivity)).mpr <| by aesop
[GOAL]
b : ℝ
hb : 1 < b
⊢ 0 < b
[PROOFSTEP]
positivity
[GOAL]
b : ℝ
hb : 1 < b
⊢ 1 < b
[PROOFSTEP]
aesop
[GOAL]
a b c : ℝ
hb : 0 ≠ b
⊢ Tendsto (fun x => x ^ (a / (b * x + c))) atTop (𝓝 1)
[PROOFSTEP]
refine'
Tendsto.congr' _
((tendsto_exp_nhds_0_nhds_1.comp
(by
simpa only [mul_zero, pow_one] using
(@tendsto_const_nhds _ _ _ a _).mul (tendsto_div_pow_mul_exp_add_atTop b c 1 hb))).comp
tendsto_log_atTop)
[GOAL]
a b c : ℝ
hb : 0 ≠ b
⊢ Tendsto ?m.296219 atTop (𝓝 0)
[PROOFSTEP]
simpa only [mul_zero, pow_one] using (@tendsto_const_nhds _ _ _ a _).mul (tendsto_div_pow_mul_exp_add_atTop b c 1 hb)
[GOAL]
a b c : ℝ
hb : 0 ≠ b
⊢ (exp ∘ fun x => a * (x / (b * exp x + c))) ∘ log =ᶠ[atTop] fun x => x ^ (a / (b * x + c))
[PROOFSTEP]
apply eventuallyEq_of_mem (Ioi_mem_atTop (0 : ℝ))
[GOAL]
a b c : ℝ
hb : 0 ≠ b
⊢ EqOn ((exp ∘ fun x => a * (x / (b * exp x + c))) ∘ log) (fun x => x ^ (a / (b * x + c))) (Set.Ioi 0)
[PROOFSTEP]
intro x hx
[GOAL]
a b c : ℝ
hb : 0 ≠ b
x : ℝ
hx : x ∈ Set.Ioi 0
⊢ ((exp ∘ fun x => a * (x / (b * exp x + c))) ∘ log) x = (fun x => x ^ (a / (b * x + c))) x
[PROOFSTEP]
simp only [Set.mem_Ioi, Function.comp_apply] at hx ⊢
[GOAL]
a b c : ℝ
hb : 0 ≠ b
x : ℝ
hx : 0 < x
⊢ exp (a * (log x / (b * exp (log x) + c))) = x ^ (a / (b * x + c))
[PROOFSTEP]
rw [exp_log hx, ← exp_log (rpow_pos_of_pos hx (a / (b * x + c))), log_rpow hx (a / (b * x + c))]
[GOAL]
a b c : ℝ
hb : 0 ≠ b
x : ℝ
hx : 0 < x
⊢ exp (a * (log x / (b * x + c))) = exp (a / (b * x + c) * log x)
[PROOFSTEP]
field_simp
[GOAL]
⊢ Tendsto (fun x => x ^ (1 / x)) atTop (𝓝 1)
[PROOFSTEP]
convert tendsto_rpow_div_mul_add (1 : ℝ) _ (0 : ℝ) zero_ne_one
[GOAL]
case h.e'_3.h.h.e'_6.h.e'_6
x✝ : ℝ
⊢ x✝ = 1 * x✝ + 0
[PROOFSTEP]
funext
[GOAL]
case h.e'_3.h.h.e'_6.h.e'_6
x✝ : ℝ
⊢ x✝ = 1 * x✝ + 0
[PROOFSTEP]
congr 2
[GOAL]
case h.e'_3.h.h.e'_6.h.e'_6
x✝ : ℝ
⊢ x✝ = 1 * x✝ + 0
[PROOFSTEP]
ring
[GOAL]
⊢ Tendsto (fun x => x ^ (-1 / x)) atTop (𝓝 1)
[PROOFSTEP]
convert tendsto_rpow_div_mul_add (-(1 : ℝ)) _ (0 : ℝ) zero_ne_one
[GOAL]
case h.e'_3.h.h.e'_6.h.e'_6
x✝ : ℝ
⊢ x✝ = 1 * x✝ + 0
[PROOFSTEP]
funext
[GOAL]
case h.e'_3.h.h.e'_6.h.e'_6
x✝ : ℝ
⊢ x✝ = 1 * x✝ + 0
[PROOFSTEP]
congr 2
[GOAL]
case h.e'_3.h.h.e'_6.h.e'_6
x✝ : ℝ
⊢ x✝ = 1 * x✝ + 0
[PROOFSTEP]
ring
[GOAL]
s : ℝ
⊢ Tendsto (fun x => exp x / x ^ s) atTop atTop
[PROOFSTEP]
cases' archimedean_iff_nat_lt.1 Real.instArchimedean s with n hn
[GOAL]
case intro
s : ℝ
n : ℕ
hn : s < ↑n
⊢ Tendsto (fun x => exp x / x ^ s) atTop atTop
[PROOFSTEP]
refine' tendsto_atTop_mono' _ _ (tendsto_exp_div_pow_atTop n)
[GOAL]
case intro
s : ℝ
n : ℕ
hn : s < ↑n
⊢ (fun x => exp x / x ^ n) ≤ᶠ[atTop] fun x => exp x / x ^ s
[PROOFSTEP]
filter_upwards [eventually_gt_atTop (0 : ℝ), eventually_ge_atTop (1 : ℝ)] with x hx₀ hx₁
[GOAL]
case h
s : ℝ
n : ℕ
hn : s < ↑n
x : ℝ
hx₀ : 0 < x
hx₁ : 1 ≤ x
⊢ exp x / x ^ n ≤ exp x / x ^ s
[PROOFSTEP]
rw [div_le_div_left (exp_pos _) (pow_pos hx₀ _) (rpow_pos_of_pos hx₀ _), ← Real.rpow_nat_cast]
[GOAL]
case h
s : ℝ
n : ℕ
hn : s < ↑n
x : ℝ
hx₀ : 0 < x
hx₁ : 1 ≤ x
⊢ x ^ s ≤ x ^ ↑n
[PROOFSTEP]
exact rpow_le_rpow_of_exponent_le hx₁ hn.le
[GOAL]
s b : ℝ
hb : 0 < b
⊢ Tendsto (fun x => exp (b * x) / x ^ s) atTop atTop
[PROOFSTEP]
refine' ((tendsto_rpow_atTop hb).comp (tendsto_exp_div_rpow_atTop (s / b))).congr' _
[GOAL]
s b : ℝ
hb : 0 < b
⊢ ((fun x => x ^ b) ∘ fun x => exp x / x ^ (s / b)) =ᶠ[atTop] fun x => exp (b * x) / x ^ s
[PROOFSTEP]
filter_upwards [eventually_ge_atTop (0 : ℝ)] with x hx₀
[GOAL]
case h
s b : ℝ
hb : 0 < b
x : ℝ
hx₀ : 0 ≤ x
⊢ ((fun x => x ^ b) ∘ fun x => exp x / x ^ (s / b)) x = exp (b * x) / x ^ s
[PROOFSTEP]
simp [Real.div_rpow, (exp_pos x).le, rpow_nonneg_of_nonneg, ← Real.rpow_mul, ← exp_mul, mul_comm x, hb.ne', *]
[GOAL]
s b : ℝ
hb : 0 < b
⊢ Tendsto (fun x => x ^ s * exp (-b * x)) atTop (𝓝 0)
[PROOFSTEP]
refine' (tendsto_exp_mul_div_rpow_atTop s b hb).inv_tendsto_atTop.congr' _
[GOAL]
s b : ℝ
hb : 0 < b
⊢ (fun x => exp (b * x) / x ^ s)⁻¹ =ᶠ[atTop] fun x => x ^ s * exp (-b * x)
[PROOFSTEP]
filter_upwards with x using by simp [exp_neg, inv_div, div_eq_mul_inv _ (exp _)]
[GOAL]
s b : ℝ
hb : 0 < b
x : ℝ
⊢ (fun x => exp (b * x) / x ^ s)⁻¹ x = x ^ s * exp (-b * x)
[PROOFSTEP]
simp [exp_neg, inv_div, div_eq_mul_inv _ (exp _)]
[GOAL]
y : ℝ
hy : 0 < y
⊢ Tendsto (fun x => ↑x ^ y) atTop atTop
[PROOFSTEP]
rw [Filter.tendsto_atTop_atTop]
[GOAL]
y : ℝ
hy : 0 < y
⊢ ∀ (b : ℝ), ∃ i, ∀ (a : ℝ≥0), i ≤ a → b ≤ ↑a ^ y
[PROOFSTEP]
intro b
[GOAL]
y : ℝ
hy : 0 < y
b : ℝ
⊢ ∃ i, ∀ (a : ℝ≥0), i ≤ a → b ≤ ↑a ^ y
[PROOFSTEP]
obtain ⟨c, hc⟩ := tendsto_atTop_atTop.mp (tendsto_rpow_atTop hy) b
[GOAL]
case intro
y : ℝ
hy : 0 < y
b c : ℝ
hc : ∀ (a : ℝ), c ≤ a → b ≤ a ^ y
⊢ ∃ i, ∀ (a : ℝ≥0), i ≤ a → b ≤ ↑a ^ y
[PROOFSTEP]
use c.toNNReal
[GOAL]
case h
y : ℝ
hy : 0 < y
b c : ℝ
hc : ∀ (a : ℝ), c ≤ a → b ≤ a ^ y
⊢ ∀ (a : ℝ≥0), toNNReal c ≤ a → b ≤ ↑a ^ y
[PROOFSTEP]
intro a ha
[GOAL]
case h
y : ℝ
hy : 0 < y
b c : ℝ
hc : ∀ (a : ℝ), c ≤ a → b ≤ a ^ y
a : ℝ≥0
ha : toNNReal c ≤ a
⊢ b ≤ ↑a ^ y
[PROOFSTEP]
exact_mod_cast hc a (Real.toNNReal_le_iff_le_coe.mp ha)
[GOAL]
y : ℝ
hy : 0 < y
⊢ Tendsto (fun x => x ^ y) (𝓝 ⊤) (𝓝 ⊤)
[PROOFSTEP]
rw [ENNReal.tendsto_nhds_top_iff_nnreal]
[GOAL]
y : ℝ
hy : 0 < y
⊢ ∀ (x : ℝ≥0), ∀ᶠ (a : ℝ≥0∞) in 𝓝 ⊤, ↑x < a ^ y
[PROOFSTEP]
intro x
[GOAL]
y : ℝ
hy : 0 < y
x : ℝ≥0
⊢ ∀ᶠ (a : ℝ≥0∞) in 𝓝 ⊤, ↑x < a ^ y
[PROOFSTEP]
obtain ⟨c, _, hc⟩ := (atTop_basis_Ioi.tendsto_iff atTop_basis_Ioi).mp (NNReal.tendsto_rpow_atTop hy) x trivial
[GOAL]
case intro.intro
y : ℝ
hy : 0 < y
x c : ℝ≥0
left✝ : True
hc : ∀ (x_1 : ℝ≥0), x_1 ∈ Set.Ioi c → ↑x_1 ^ y ∈ Set.Ioi ↑x
⊢ ∀ᶠ (a : ℝ≥0∞) in 𝓝 ⊤, ↑x < a ^ y
[PROOFSTEP]
have hc' : Set.Ioi ↑c ∈ 𝓝 (⊤ : ℝ≥0∞) := Ioi_mem_nhds ENNReal.coe_lt_top
[GOAL]
case intro.intro
y : ℝ
hy : 0 < y
x c : ℝ≥0
left✝ : True
hc : ∀ (x_1 : ℝ≥0), x_1 ∈ Set.Ioi c → ↑x_1 ^ y ∈ Set.Ioi ↑x
hc' : Set.Ioi ↑c ∈ 𝓝 ⊤
⊢ ∀ᶠ (a : ℝ≥0∞) in 𝓝 ⊤, ↑x < a ^ y
[PROOFSTEP]
refine' eventually_of_mem hc' _
[GOAL]
case intro.intro
y : ℝ
hy : 0 < y
x c : ℝ≥0
left✝ : True
hc : ∀ (x_1 : ℝ≥0), x_1 ∈ Set.Ioi c → ↑x_1 ^ y ∈ Set.Ioi ↑x
hc' : Set.Ioi ↑c ∈ 𝓝 ⊤
⊢ ∀ (x_1 : ℝ≥0∞), x_1 ∈ Set.Ioi ↑c → ↑x < x_1 ^ y
[PROOFSTEP]
intro a ha
[GOAL]
case intro.intro
y : ℝ
hy : 0 < y
x c : ℝ≥0
left✝ : True
hc : ∀ (x_1 : ℝ≥0), x_1 ∈ Set.Ioi c → ↑x_1 ^ y ∈ Set.Ioi ↑x
hc' : Set.Ioi ↑c ∈ 𝓝 ⊤
a : ℝ≥0∞
ha : a ∈ Set.Ioi ↑c
⊢ ↑x < a ^ y
[PROOFSTEP]
by_cases ha' : a = ⊤
[GOAL]
case pos
y : ℝ
hy : 0 < y
x c : ℝ≥0
left✝ : True
hc : ∀ (x_1 : ℝ≥0), x_1 ∈ Set.Ioi c → ↑x_1 ^ y ∈ Set.Ioi ↑x
hc' : Set.Ioi ↑c ∈ 𝓝 ⊤
a : ℝ≥0∞
ha : a ∈ Set.Ioi ↑c
ha' : a = ⊤
⊢ ↑x < a ^ y
[PROOFSTEP]
simp [ha', hy]
[GOAL]
case neg
y : ℝ
hy : 0 < y
x c : ℝ≥0
left✝ : True
hc : ∀ (x_1 : ℝ≥0), x_1 ∈ Set.Ioi c → ↑x_1 ^ y ∈ Set.Ioi ↑x
hc' : Set.Ioi ↑c ∈ 𝓝 ⊤
a : ℝ≥0∞
ha : a ∈ Set.Ioi ↑c
ha' : ¬a = ⊤
⊢ ↑x < a ^ y
[PROOFSTEP]
lift a to ℝ≥0 using ha'
[GOAL]
case neg.intro
y : ℝ
hy : 0 < y
x c : ℝ≥0
left✝ : True
hc : ∀ (x_1 : ℝ≥0), x_1 ∈ Set.Ioi c → ↑x_1 ^ y ∈ Set.Ioi ↑x
hc' : Set.Ioi ↑c ∈ 𝓝 ⊤
a : ℝ≥0
ha : ↑a ∈ Set.Ioi ↑c
⊢ ↑x < ↑a ^ y
[PROOFSTEP]
simp only [Set.mem_Ioi, coe_lt_coe] at ha hc
[GOAL]
case neg.intro
y : ℝ
hy : 0 < y
x c : ℝ≥0
left✝ : True
hc' : Set.Ioi ↑c ∈ 𝓝 ⊤
a : ℝ≥0
ha : c < a
hc : ∀ (x_1 : ℝ≥0), c < x_1 → ↑x < ↑x_1 ^ y
⊢ ↑x < ↑a ^ y
[PROOFSTEP]
rw [ENNReal.coe_rpow_of_nonneg _ hy.le]
[GOAL]
case neg.intro
y : ℝ
hy : 0 < y
x c : ℝ≥0
left✝ : True
hc' : Set.Ioi ↑c ∈ 𝓝 ⊤
a : ℝ≥0
ha : c < a
hc : ∀ (x_1 : ℝ≥0), c < x_1 → ↑x < ↑x_1 ^ y
⊢ ↑x < ↑(a ^ y)
[PROOFSTEP]
exact_mod_cast hc a ha
[GOAL]
α : Type u_1
l : Filter α
f g : α → ℂ
hl : IsBoundedUnder (fun x x_1 => x ≤ x_1) l fun x => |(g x).im|
⊢ (fun x => Real.exp (arg (f x) * (g x).im)) =Θ[l] fun x => 1
[PROOFSTEP]
rcases hl with ⟨b, hb⟩
[GOAL]
case intro
α : Type u_1
l : Filter α
f g : α → ℂ
b : ℝ
hb : ∀ᶠ (x : ℝ) in Filter.map (fun x => |(g x).im|) l, (fun x x_1 => x ≤ x_1) x b
⊢ (fun x => Real.exp (arg (f x) * (g x).im)) =Θ[l] fun x => 1
[PROOFSTEP]
refine' Real.isTheta_exp_comp_one.2 ⟨π * b, _⟩
[GOAL]
case intro
α : Type u_1
l : Filter α
f g : α → ℂ
b : ℝ
hb : ∀ᶠ (x : ℝ) in Filter.map (fun x => |(g x).im|) l, (fun x x_1 => x ≤ x_1) x b
⊢ ∀ᶠ (x : ℝ) in Filter.map (fun x => |arg (f x) * (g x).im|) l, (fun x x_1 => x ≤ x_1) x (π * b)
[PROOFSTEP]
rw [eventually_map] at hb ⊢
[GOAL]
case intro
α : Type u_1
l : Filter α
f g : α → ℂ
b : ℝ
hb : ∀ᶠ (a : α) in l, (fun x x_1 => x ≤ x_1) |(g a).im| b
⊢ ∀ᶠ (a : α) in l, (fun x x_1 => x ≤ x_1) |arg (f a) * (g a).im| (π * b)
[PROOFSTEP]
refine' hb.mono fun x hx => _
[GOAL]
case intro
α : Type u_1
l : Filter α
f g : α → ℂ
b : ℝ
hb : ∀ᶠ (a : α) in l, (fun x x_1 => x ≤ x_1) |(g a).im| b
x : α
hx : (fun x x_1 => x ≤ x_1) |(g x).im| b
⊢ (fun x x_1 => x ≤ x_1) |arg (f x) * (g x).im| (π * b)
[PROOFSTEP]
erw [abs_mul]
[GOAL]
case intro
α : Type u_1
l : Filter α
f g : α → ℂ
b : ℝ
hb : ∀ᶠ (a : α) in l, (fun x x_1 => x ≤ x_1) |(g a).im| b
x : α
hx : (fun x x_1 => x ≤ x_1) |(g x).im| b
⊢ (fun x x_1 => x ≤ x_1) (|arg (f x)| * |(g x).im|) (π * b)
[PROOFSTEP]
exact mul_le_mul (abs_arg_le_pi _) hx (abs_nonneg _) Real.pi_pos.le
[GOAL]
α : Type u_1
l : Filter α
f g : α → ℂ
hl : IsBoundedUnder (fun x x_1 => x ≤ x_1) l fun x => |(g x).im|
⊢ (let_fun this := fun x => ↑abs (f x) ^ (g x).re / 1;
this) =ᶠ[l]
let_fun this := fun x => ↑abs (f x) ^ (g x).re;
this
[PROOFSTEP]
simp only [ofReal_one, div_one]
[GOAL]
α : Type u_1
l : Filter α
f g : α → ℂ
hl : IsBoundedUnder (fun x x_1 => x ≤ x_1) l fun x => |(g x).im|
⊢ (fun x => ↑abs (f x) ^ (g x).re) =ᶠ[l] fun x => ↑abs (f x) ^ (g x).re
[PROOFSTEP]
rfl
[GOAL]
α : Type u_1
l : Filter α
f g : α → ℂ
hl_im : IsBoundedUnder (fun x x_1 => x ≤ x_1) l fun x => |(g x).im|
hl : ∀ᶠ (x : α) in l, f x = 0 → (g x).re = 0 → g x = 0
⊢ (let_fun this := fun x => ↑abs (f x) ^ (g x).re / 1;
this) =ᶠ[l]
let_fun this := fun x => ↑abs (f x) ^ (g x).re;
this
[PROOFSTEP]
simp only [ofReal_one, div_one]
[GOAL]
α : Type u_1
l : Filter α
f g : α → ℂ
hl_im : IsBoundedUnder (fun x x_1 => x ≤ x_1) l fun x => |(g x).im|
hl : ∀ᶠ (x : α) in l, f x = 0 → (g x).re = 0 → g x = 0
⊢ (fun x => ↑abs (f x) ^ (g x).re) =ᶠ[l] fun x => ↑abs (f x) ^ (g x).re
[PROOFSTEP]
rfl
[GOAL]
α : Type u_1
l : Filter α
f g : α → ℂ
b : ℂ
hl : b.re = 0 → b ≠ 0 → ∀ᶠ (x : α) in l, f x ≠ 0
⊢ ∀ᶠ (x : α) in l, f x = 0 → b.re = 0 → b = 0
[PROOFSTEP]
convert hl
[GOAL]
case a
α : Type u_1
l : Filter α
f g : α → ℂ
b : ℂ
hl : b.re = 0 → b ≠ 0 → ∀ᶠ (x : α) in l, f x ≠ 0
⊢ (∀ᶠ (x : α) in l, f x = 0 → b.re = 0 → b = 0) ↔ b.re = 0 → b ≠ 0 → ∀ᶠ (x : α) in l, f x ≠ 0
[PROOFSTEP]
rw [eventually_imp_distrib_right]
[GOAL]
case a
α : Type u_1
l : Filter α
f g : α → ℂ
b : ℂ
hl : b.re = 0 → b ≠ 0 → ∀ᶠ (x : α) in l, f x ≠ 0
⊢ (∃ᶠ (x : α) in l, f x = 0) → b.re = 0 → b = 0 ↔ b.re = 0 → b ≠ 0 → ∀ᶠ (x : α) in l, f x ≠ 0
[PROOFSTEP]
tauto
[GOAL]
α : Type u_1
r c : ℝ
l : Filter α
f g : α → ℝ
h : IsBigOWith c l f g
hc : 0 ≤ c
hr : 0 ≤ r
hg : 0 ≤ᶠ[l] g
⊢ IsBigOWith (c ^ r) l (fun x => f x ^ r) fun x => g x ^ r
[PROOFSTEP]
apply IsBigOWith.of_bound
[GOAL]
case a
α : Type u_1
r c : ℝ
l : Filter α
f g : α → ℝ
h : IsBigOWith c l f g
hc : 0 ≤ c
hr : 0 ≤ r
hg : 0 ≤ᶠ[l] g
⊢ ∀ᶠ (x : α) in l, ‖f x ^ r‖ ≤ c ^ r * ‖g x ^ r‖
[PROOFSTEP]
filter_upwards [hg, h.bound] with x hgx hx
[GOAL]
case h
α : Type u_1
r c : ℝ
l : Filter α
f g : α → ℝ
h : IsBigOWith c l f g
hc : 0 ≤ c
hr : 0 ≤ r
hg : 0 ≤ᶠ[l] g
x : α
hgx : OfNat.ofNat 0 x ≤ g x
hx : ‖f x‖ ≤ c * ‖g x‖
⊢ ‖f x ^ r‖ ≤ c ^ r * ‖g x ^ r‖
[PROOFSTEP]
calc
|f x ^ r| ≤ |f x| ^ r := abs_rpow_le_abs_rpow _ _
_ ≤ (c * |g x|) ^ r := (rpow_le_rpow (abs_nonneg _) hx hr)
_ = c ^ r * |g x ^ r| := by rw [mul_rpow hc (abs_nonneg _), abs_rpow_of_nonneg hgx]
[GOAL]
α : Type u_1
r c : ℝ
l : Filter α
f g : α → ℝ
h : IsBigOWith c l f g
hc : 0 ≤ c
hr : 0 ≤ r
hg : 0 ≤ᶠ[l] g
x : α
hgx : OfNat.ofNat 0 x ≤ g x
hx : ‖f x‖ ≤ c * ‖g x‖
⊢ (c * |g x|) ^ r = c ^ r * |g x ^ r|
[PROOFSTEP]
rw [mul_rpow hc (abs_nonneg _), abs_rpow_of_nonneg hgx]
[GOAL]
α : Type u_1
r c✝ : ℝ
l : Filter α
f g : α → ℝ
hr : 0 < r
hg : 0 ≤ᶠ[l] g
h : f =o[l] g
c : ℝ
hc : 0 < c
⊢ (c ^ r⁻¹) ^ r = c
[PROOFSTEP]
rw [← rpow_mul hc.le, inv_mul_cancel hr.ne', Real.rpow_one]
[GOAL]
s b : ℝ
hb : 0 < b
⊢ Tendsto (fun x => x ^ s / exp (b * x)) atTop (𝓝 0)
[PROOFSTEP]
simpa only [div_eq_mul_inv, exp_neg, neg_mul] using tendsto_rpow_mul_exp_neg_mul_atTop_nhds_0 s b hb
[GOAL]
k : ℤ
b : ℝ
hb : 0 < b
⊢ (fun x => x ^ ↑k) =o[atTop] fun x => exp (b * x)
[PROOFSTEP]
simpa only [rpow_int_cast] using isLittleO_rpow_exp_pos_mul_atTop k hb
[GOAL]
k : ℕ
b : ℝ
hb : 0 < b
⊢ (fun x => x ^ ↑k) =o[atTop] fun x => exp (b * x)
[PROOFSTEP]
simpa using isLittleO_zpow_exp_pos_mul_atTop k hb
[GOAL]
s : ℝ
⊢ (fun x => x ^ s) =o[atTop] exp
[PROOFSTEP]
simpa only [one_mul] using isLittleO_rpow_exp_pos_mul_atTop s one_pos
[GOAL]
a : ℝ
ha : 0 < a
b : ℝ
⊢ (fun x => exp (-a * x)) =o[atTop] fun x => x ^ b
[PROOFSTEP]
apply isLittleO_of_tendsto'
[GOAL]
case hgf
a : ℝ
ha : 0 < a
b : ℝ
⊢ ∀ᶠ (x : ℝ) in atTop, x ^ b = 0 → exp (-a * x) = 0
[PROOFSTEP]
refine' (eventually_gt_atTop 0).mp (eventually_of_forall fun t ht h => _)
[GOAL]
case hgf
a : ℝ
ha : 0 < a
b t : ℝ
ht : 0 < t
h : t ^ b = 0
⊢ exp (-a * t) = 0
[PROOFSTEP]
rw [rpow_eq_zero_iff_of_nonneg ht.le] at h
[GOAL]
case hgf
a : ℝ
ha : 0 < a
b t : ℝ
ht : 0 < t
h : t = 0 ∧ b ≠ 0
⊢ exp (-a * t) = 0
[PROOFSTEP]
exact (ht.ne' h.1).elim
[GOAL]
case a
a : ℝ
ha : 0 < a
b : ℝ
⊢ Tendsto (fun x => exp (-a * x) / x ^ b) atTop (𝓝 0)
[PROOFSTEP]
refine' (tendsto_exp_mul_div_rpow_atTop (-b) a ha).inv_tendsto_atTop.congr' _
[GOAL]
case a
a : ℝ
ha : 0 < a
b : ℝ
⊢ (fun x => exp (a * x) / x ^ (-b))⁻¹ =ᶠ[atTop] fun x => exp (-a * x) / x ^ b
[PROOFSTEP]
refine' (eventually_ge_atTop 0).mp (eventually_of_forall fun t ht => _)
[GOAL]
case a
a : ℝ
ha : 0 < a
b t : ℝ
ht : 0 ≤ t
⊢ (fun x => exp (a * x) / x ^ (-b))⁻¹ t = (fun x => exp (-a * x) / x ^ b) t
[PROOFSTEP]
dsimp only
[GOAL]
case a
a : ℝ
ha : 0 < a
b t : ℝ
ht : 0 ≤ t
⊢ (fun x => exp (a * x) / x ^ (-b))⁻¹ t = exp (-a * t) / t ^ b
[PROOFSTEP]
rw [Pi.inv_apply, inv_div, ← inv_div_inv, neg_mul, Real.exp_neg, rpow_neg ht, inv_inv]
[GOAL]
s r : ℝ
hs : 0 < s
r' : ℝ := max r 1
hr : 0 < r'
H : 0 < s / r'
x : ℝ
hx : 1 ≤ log x
⊢ ‖log x ^ r‖ ≤ 1 * ‖log x ^ r'‖
[PROOFSTEP]
have hx₀ : 0 ≤ log x := zero_le_one.trans hx
[GOAL]
s r : ℝ
hs : 0 < s
r' : ℝ := max r 1
hr : 0 < r'
H : 0 < s / r'
x : ℝ
hx : 1 ≤ log x
hx₀ : 0 ≤ log x
⊢ ‖log x ^ r‖ ≤ 1 * ‖log x ^ r'‖
[PROOFSTEP]
simp [norm_eq_abs, abs_rpow_of_nonneg, abs_rpow_of_nonneg hx₀, rpow_le_rpow_of_exponent_le (hx.trans (le_abs_self _))]
[GOAL]
s r : ℝ
hs : 0 < s
r' : ℝ := max r 1
hr : 0 < r'
H : 0 < s / r'
x : ℝ
hx : 0 ≤ x
⊢ (fun x => (x ^ (s / r')) ^ r') x = (fun x => x ^ s) x
[PROOFSTEP]
simp only [← rpow_mul hx, div_mul_cancel _ hr.ne']
[GOAL]
s r : ℝ
hs : s < 0
x : ℝ
hx : x ∈ Set.Icc 0 1
⊢ x ∈ {x | (fun x => ((fun x => log x ^ r) ∘ fun x => x⁻¹) x = (fun x => |log x| ^ r) x) x}
[PROOFSTEP]
simp [abs_of_nonpos, log_nonpos hx.1 hx.2]
[GOAL]
s r : ℝ
hs : s < 0
x : ℝ
hx : x ∈ Set.Ioi 0
⊢ ((fun x => x ^ (-s)) ∘ fun x => x⁻¹) x = (fun x => x ^ s) x
[PROOFSTEP]
rw [Function.comp_apply, inv_rpow hx.out.le, rpow_neg hx.out.le, inv_inv]
[GOAL]
r : ℝ
hr : r < 0
x : ℝ
hx : x ∈ Set.Icc 0 1
⊢ x ∈ {x | (fun x => (fun x => -|log x| ^ 1) x = log x) x}
[PROOFSTEP]
simp [abs_of_nonpos (log_nonpos hx.1 hx.2)]
[GOAL]
r : ℝ
hr : 0 < r
x : ℝ
hx : x ∈ Set.Ioi 0
⊢ log x / x ^ (-r) = (fun x => log x * x ^ r) x
[PROOFSTEP]
rw [rpow_neg hx.out.le, div_inv_eq_mul]
|
if (!require(testthat)) install.packages("testthat")
pacman::p_load(testthat)
context("Variable check")
test_that("Check whether instructor variable is setup correctly", {
instructors <- c("Jae", "Nick")
expect_equal(class(instructors), "character")
}
)
|
# import BuildExecutable
|
[STATEMENT]
lemma \<tau>red1r_Throw:
"\<tau>red1gr uf P t h (Throw a, xs) s' \<longleftrightarrow> s' = (Throw a, xs)" (is "?lhs \<longleftrightarrow> ?rhs")
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<tau>red1gr uf P t h (Throw a, xs) s' = (s' = (Throw a, xs))
[PROOF STEP]
proof
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<tau>red1gr uf P t h (Throw a, xs) s' \<Longrightarrow> s' = (Throw a, xs)
2. s' = (Throw a, xs) \<Longrightarrow> \<tau>red1gr uf P t h (Throw a, xs) s'
[PROOF STEP]
assume ?lhs
[PROOF STATE]
proof (state)
this:
\<tau>red1gr uf P t h (Throw a, xs) s'
goal (2 subgoals):
1. \<tau>red1gr uf P t h (Throw a, xs) s' \<Longrightarrow> s' = (Throw a, xs)
2. s' = (Throw a, xs) \<Longrightarrow> \<tau>red1gr uf P t h (Throw a, xs) s'
[PROOF STEP]
thus ?rhs
[PROOF STATE]
proof (prove)
using this:
\<tau>red1gr uf P t h (Throw a, xs) s'
goal (1 subgoal):
1. s' = (Throw a, xs)
[PROOF STEP]
by induct auto
[PROOF STATE]
proof (state)
this:
s' = (Throw a, xs)
goal (1 subgoal):
1. s' = (Throw a, xs) \<Longrightarrow> \<tau>red1gr uf P t h (Throw a, xs) s'
[PROOF STEP]
qed simp |
\documentclass[a4paper]{scrreprt}
%% Language and font encodings and page settings
\usepackage[english]{babel}
\usepackage[utf8x]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[a4paper,top=2cm,bottom=2cm,left=3cm,right=3cm,marginparwidth=2cm]{geometry}
\usepackage{float}
%% Packages
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage[colorinlistoftodos]{todonotes}
\usepackage[allcolors=blue]{hyperref}
\usepackage{wrapfig}
\graphicspath{{./img/}}
%% BibLaTeX settings
\usepackage[backend=biber]{biblatex}
\addbibresource{main.bib}
%% Header page information
\title{\href{https://github.com/cian2009/GestureReview}{Gesture Based User Interface Experience – Evolution and Challenges}}
\subtitle{"Gesture controls and the challenges of creating intuitive controls"}
\author{\href{https://github.com/cian2009}{Cian Gannon},~\IEEEmembership{Software Development (Honours),~GMIT}}
\author{
\href{https://github.com/cian2009}{Gannon, Cian}\\
\texttt{[email protected]}
%%\and
%%\href{https://github.com/cian2009}{Gannon, Cian}\\
%%\texttt{[email protected]}
}
\titlehead{\centering\includegraphics[width=10cm]{img/gesture}}
\begin{document}
%% Create title using header page information above
\maketitle
%% Table of Contents
\tableofcontents
%% List of Figures
%%\listoffigures
\pagebreak
\paragraph{Abstract}
Gesture-based UI has come a long way in the last 10 years. Gesture technology continues to grow slowly year over year with new technologies like Myo and Alexa taking the user interaction with the machine to the next logical solution. In this research paper, I will look into the history of user interaction with computers. Review gestures in everyday life and how gestures are used, and the modern age of gesture-based UI and the challenges faced by developers.
%% Section imports
\input{sections/1.tex}
\input{sections/2.tex}
\input{sections/3.tex}
\input{sections/4.tex}
\input{sections/5.tex}
\printbibliography
\end{document} |
/*
* freelan - An open, multi-platform software to establish peer-to-peer virtual
* private networks.
*
* Copyright (C) 2010-2011 Julien KAUFFMANN <[email protected]>
*
* This file is part of freelan.
*
* freelan is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* freelan is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*
* If you intend to use freelan in a commercial software, please
* contact me : we may arrange this for a small fee or no fee at all,
* depending on the nature of your project.
*/
/**
* \file configuration_helper.cpp
* \author Julien KAUFFMANN <[email protected]>
* \brief A configuration helper.
*/
#include "configuration_helper.hpp"
#include <vector>
#include <boost/asio.hpp>
#include <boost/foreach.hpp>
#include "configuration_types.hpp"
#include <cryptoplus/hash/pbkdf2.hpp>
#include <cryptoplus/hash/message_digest_algorithm.hpp>
// This file is generated locally.
#include <defines.hpp>
namespace po = boost::program_options;
namespace fs = boost::filesystem;
namespace fl = freelan;
namespace
{
struct trusted_cert_type
{
typedef fl::security_configuration::cert_type cert_type;
trusted_cert_type() {}
trusted_cert_type(cert_type& c) : cert(c) {}
operator cert_type() const { return cert; }
cert_type cert;
};
void from_file(fl::security_configuration::cert_type& value, const cryptoplus::file& file)
{
value = fl::security_configuration::cert_type::from_certificate(file);
}
void from_file(cryptoplus::pkey::pkey& value, const cryptoplus::file& file)
{
value = cryptoplus::pkey::pkey::from_private_key(file);
}
void from_file(trusted_cert_type& value, const cryptoplus::file& file)
{
value.cert = fl::security_configuration::cert_type::from_trusted_certificate(file);
}
void from_file(fl::security_configuration::crl_type& value, const cryptoplus::file& file)
{
value = fl::security_configuration::crl_type::from_certificate_revocation_list(file);
}
template <typename ValueType>
bool load_file(const std::string& file_type, ValueType& value, const std::string& name, const fs::path& filename)
{
try
{
const cryptoplus::file file = cryptoplus::file::open(filename.native());
from_file(value, file);
}
catch (const std::exception& ex)
{
po::error_with_option_name error("in %canonical_option%: unable to load %file_type% at \"%filename%\" (%error%)", name, filename.string());
error.set_substitute("file_type", file_type);
error.set_substitute("filename", filename.string());
error.set_substitute("error", ex.what());
throw error;
}
return true;
}
template <typename ValueType>
bool load_file(const std::string& file_type, ValueType& value, const std::string& name, const po::variables_map& vm)
{
if (!vm.count(name))
{
return false;
}
const fs::path path = vm[name].as<fs::path>();
if (path.native().empty())
{
return false;
}
return load_file(file_type, value, name, path);
}
template <typename ValueType>
bool load_file_list(const std::string& file_type, std::vector<ValueType>& values, const std::string& name, const po::variables_map& vm)
{
values.clear();
const auto paths = vm[name].as<std::vector<fs::path> >();
for (auto&& path : paths)
{
if (path.native().empty())
{
continue;
}
ValueType value;
if (load_file(file_type, value, name, path))
{
values.push_back(value);
}
}
return !values.empty();
}
bool load_certificate(fl::security_configuration::cert_type& value, const std::string& name, const po::variables_map& vm)
{
return load_file("certificate", value, name, vm);
}
bool load_private_key(cryptoplus::pkey::pkey& value, const std::string& name, const po::variables_map& vm)
{
return load_file("private key", value, name, vm);
}
bool load_trusted_certificate(fl::security_configuration::cert_type& value, const std::string& name, const po::variables_map& vm)
{
trusted_cert_type xvalue;
const bool result = load_file("trusted certificate", xvalue, name, vm);
value = xvalue;
return result;
}
bool load_certificate_list(std::vector<fl::security_configuration::cert_type>& value, const std::string& name, const po::variables_map& vm)
{
return load_file_list("certificate", value, name, vm);
}
bool load_trusted_certificate_list(std::vector<fl::security_configuration::cert_type>& value, const std::string& name, const po::variables_map& vm)
{
std::vector<trusted_cert_type> xvalue;
const bool result = load_file_list("trusted certificate", xvalue, name, vm);
value.assign(xvalue.begin(), xvalue.end());
return result;
}
bool load_crl_list(std::vector<fl::security_configuration::crl_type>& value, const std::string& name, const po::variables_map& vm)
{
return load_file_list("certificate revocation list", value, name, vm);
}
void make_path_absolute(const std::string& name, po::variables_map& vm, const fs::path& root)
{
if (vm.count(name) > 0)
{
const auto path = vm[name].as<fs::path>();
if (!path.empty())
{
vm.at(name).value() = fs::absolute(path, root);
}
}
}
void make_path_list_absolute(const std::string& name, po::variables_map& vm, const fs::path& root)
{
if (vm.count(name) > 0)
{
const auto paths = vm[name].as<std::vector<fs::path> >();
std::vector<fs::path> new_paths;
for (auto& path : paths)
{
if (path.empty())
{
new_paths.push_back(path);
}
else
{
new_paths.push_back(fs::absolute(path, root));
}
}
vm.at(name).value() = new_paths;
}
}
}
po::options_description get_server_options()
{
po::options_description result("FreeLAN Server options");
result.add_options()
("server.enabled", po::value<bool>()->default_value(false, "no"), "Whether to enable the server mechanism.")
("server.listen_on", po::value<asiotap::endpoint>()->default_value(asiotap::ipv4_endpoint(boost::asio::ip::address_v4::any(), 443)), "The endpoint to listen on.")
("server.protocol", po::value<fl::server_configuration::server_protocol_type>()->default_value(fl::server_configuration::server_protocol_type::https), "The protocol to use for clients to contact the server.")
("server.server_certificate_file", po::value<fs::path>()->default_value(""), "The server certificate file.")
("server.server_private_key_file", po::value<fs::path>()->default_value(""), "The server private key file.")
("server.certification_authority_certificate_file", po::value<fs::path>()->default_value(""), "The certification authority certificate file.")
("server.certification_authority_private_key_file", po::value<fs::path>()->default_value(""), "The certification authority private key file.")
("server.authentication_script", po::value<fs::path>()->default_value(""), "The authentication script to use.")
;
return result;
}
po::options_description get_client_options()
{
po::options_description result("FreeLAN Client options");
result.add_options()
("client.enabled", po::value<bool>()->default_value(false, "no"), "Whether to enable the client mechanism.")
("client.server_endpoint", po::value<asiotap::endpoint>()->default_value(asiotap::ipv4_endpoint(boost::asio::ip::address_v4::from_string("127.0.0.1"), 443)), "The endpoint to connect to.")
("client.protocol", po::value<fl::client_configuration::client_protocol_type>()->default_value(fl::client_configuration::client_protocol_type::https), "The protocol to use to contact the server.")
("client.disable_peer_verification", po::value<bool>()->default_value(false, "no"), "Whether to disable peer verification.")
("client.disable_host_verification", po::value<bool>()->default_value(false, "no"), "Whether to disable host verification.")
("client.username", po::value<std::string>()->default_value(""), "The client username.")
("client.password", po::value<std::string>()->default_value(""), "The client password.")
("client.public_endpoint", po::value<std::vector<asiotap::endpoint> >()->multitoken()->zero_tokens()->default_value(std::vector<asiotap::endpoint>(), ""), "A hostname or IP address to advertise.")
;
return result;
}
po::options_description get_fscp_options()
{
po::options_description result("FreeLAN Secure Channel Protocol (FSCP) options");
result.add_options()
("fscp.hostname_resolution_protocol", po::value<fl::fscp_configuration::hostname_resolution_protocol_type>()->default_value(fl::fscp_configuration::HRP_IPV4), "The hostname resolution protocol to use.")
("fscp.listen_on", po::value<asiotap::endpoint>()->default_value(asiotap::ipv4_endpoint(boost::asio::ip::address_v4::any(), 12000)), "The endpoint to listen on.")
("fscp.listen_on_device", po::value<std::string>()->default_value(std::string()), "The endpoint to listen on.")
("fscp.hello_timeout", po::value<millisecond_duration>()->default_value(3000), "The default timeout for HELLO messages, in milliseconds.")
("fscp.contact", po::value<std::vector<asiotap::endpoint> >()->multitoken()->zero_tokens()->default_value(std::vector<asiotap::endpoint>(), ""), "The address of an host to contact.")
("fscp.accept_contact_requests", po::value<bool>()->default_value(true, "yes"), "Whether to accept CONTACT-REQUEST messages.")
("fscp.accept_contacts", po::value<bool>()->default_value(true, "yes"), "Whether to accept CONTACT messages.")
("fscp.dynamic_contact_file", po::value<std::vector<fs::path> >()->multitoken()->zero_tokens()->default_value(std::vector<fs::path>(), ""), "The certificate of an host to dynamically contact.")
("fscp.never_contact", po::value<std::vector<asiotap::ip_network_address> >()->multitoken()->zero_tokens()->default_value(std::vector<asiotap::ip_network_address>(), ""), "A network address to avoid when dynamically contacting hosts.")
("fscp.cipher_suite_capability", po::value<std::vector<fscp::cipher_suite_type> >()->multitoken()->zero_tokens()->default_value(fscp::get_default_cipher_suites(), ""), "A cipher suite to allow.")
("fscp.elliptic_curve_capability", po::value<std::vector<fscp::elliptic_curve_type> >()->multitoken()->zero_tokens()->default_value(fscp::get_default_elliptic_curves(), ""), "A elliptic curve to allow.")
;
return result;
}
po::options_description get_security_options()
{
po::options_description result("Security options");
result.add_options()
("security.passphrase", po::value<std::string>()->default_value(""), "A passphrase to generate the pre - shared key from.")
("security.passphrase_salt", po::value<std::string>()->default_value("freelan"), "The salt to use during the pre-shared key derivation.")
("security.passphrase_iterations_count", po::value<unsigned int>()->default_value(2000, "2000"), "The number of iterations to use during the pre-shared key derivation.")
("security.signature_certificate_file", po::value<fs::path>(), "The certificate file to use for signing.")
("security.signature_private_key_file", po::value<fs::path>(), "The private key file to use for signing.")
("security.certificate_validation_method", po::value<fl::security_configuration::certificate_validation_method_type>()->default_value(fl::security_configuration::CVM_DEFAULT), "The certificate validation method.")
("security.certificate_validation_script", po::value<fs::path>()->default_value(""), "The certificate validation script to use.")
("security.authority_certificate_file", po::value<std::vector<fs::path> >()->multitoken()->zero_tokens()->default_value(std::vector<fs::path>(), ""), "An authority certificate file to use.")
("security.certificate_revocation_validation_method", po::value<fl::security_configuration::certificate_revocation_validation_method_type>()->default_value(fl::security_configuration::CRVM_NONE), "The certificate revocation validation method.")
("security.certificate_revocation_list_file", po::value<std::vector<fs::path> >()->multitoken()->zero_tokens()->default_value(std::vector<fs::path>(), ""), "A certificate revocation list file to use.")
;
return result;
}
po::options_description get_tap_adapter_options()
{
po::options_description result("Tap adapter options");
const asiotap::ipv4_network_address default_ipv4_network_address(boost::asio::ip::address_v4::from_string("9.0.0.1"), 24);
const asiotap::ipv6_network_address default_ipv6_network_address(boost::asio::ip::address_v6::from_string("fe80::1"), 10);
const asiotap::ipv4_network_address default_dhcp_ipv4_network_address(boost::asio::ip::address_v4::from_string("9.0.0.0"), 24);
const asiotap::ipv6_network_address default_dhcp_ipv6_network_address(boost::asio::ip::address_v6::from_string("fe80::"), 10);
result.add_options()
("tap_adapter.type", po::value<fl::tap_adapter_configuration::tap_adapter_type>()->default_value(fl::tap_adapter_configuration::tap_adapter_type::tap, "tap"), "The TAP adapter type.")
("tap_adapter.enabled", po::value<bool>()->default_value(true, "yes"), "Whether to enable the tap adapter.")
("tap_adapter.name", po::value<std::string>(), "The name of the tap adapter to use or create.")
("tap_adapter.mtu", po::value<fl::mtu_type>()->default_value(fl::auto_mtu_type()), "The MTU of the tap adapter.")
("tap_adapter.mss_override", po::value<fl::mss_type>()->default_value(fl::mss_type()), "The MSS override.")
("tap_adapter.metric", po::value<fl::metric_type>()->default_value(fl::auto_metric_type()), "The metric of the tap adapter.")
("tap_adapter.ipv4_address_prefix_length", po::value<asiotap::ipv4_network_address>(), "The tap adapter IPv4 address and prefix length.")
("tap_adapter.ipv6_address_prefix_length", po::value<asiotap::ipv6_network_address>(), "The tap adapter IPv6 address and prefix length.")
("tap_adapter.remote_ipv4_address", po::value<asiotap::ipv4_network_address>(), "The tap adapter IPv4 remote address.")
("tap_adapter.arp_proxy_enabled", po::value<bool>()->default_value(false), "Whether to enable the ARP proxy.")
("tap_adapter.arp_proxy_fake_ethernet_address", po::value<fl::tap_adapter_configuration::ethernet_address_type>()->default_value(boost::lexical_cast<fl::tap_adapter_configuration::ethernet_address_type>("00:aa:bb:cc:dd:ee")), "The ARP proxy fake ethernet address.")
("tap_adapter.dhcp_proxy_enabled", po::value<bool>()->default_value(true), "Whether to enable the DHCP proxy.")
("tap_adapter.dhcp_server_ipv4_address_prefix_length", po::value<asiotap::ipv4_network_address>()->default_value(default_dhcp_ipv4_network_address), "The DHCP proxy server IPv4 address and prefix length.")
("tap_adapter.dhcp_server_ipv6_address_prefix_length", po::value<asiotap::ipv6_network_address>()->default_value(default_dhcp_ipv6_network_address), "The DHCP proxy server IPv6 address and prefix length.")
("tap_adapter.up_script", po::value<fs::path>()->default_value(""), "The tap adapter up script.")
("tap_adapter.down_script", po::value<fs::path>()->default_value(""), "The tap adapter down script.")
;
return result;
}
po::options_description get_switch_options()
{
po::options_description result("Switch options");
result.add_options()
("switch.routing_method", po::value<fl::switch_configuration::routing_method_type>()->default_value(fl::switch_configuration::RM_SWITCH), "The routing method for messages.")
("switch.relay_mode_enabled", po::value<bool>()->default_value(false, "no"), "Whether to enable the relay mode.")
;
return result;
}
po::options_description get_router_options()
{
po::options_description result("Router options");
result.add_options()
("router.local_ip_route", po::value<std::vector<freelan::ip_route> >()->multitoken()->zero_tokens()->default_value(std::vector<freelan::ip_route>(), ""), "A route to advertise to the other peers.")
("router.local_dns_server", po::value<std::vector<asiotap::ip_address> >()->multitoken()->zero_tokens()->default_value(std::vector<asiotap::ip_address>(), ""), "A DNS server to advertise to the other peers.")
("router.client_routing_enabled", po::value<bool>()->default_value(true, "yes"), "Whether to enable client routing.")
("router.accept_routes_requests", po::value<bool>()->default_value(true, "yes"), "Whether to accept routes requests.")
("router.internal_route_acceptance_policy", po::value<fl::router_configuration::internal_route_scope_type>()->default_value(fl::router_configuration::internal_route_scope_type::unicast_in_network), "The internal route acceptance policy.")
("router.system_route_acceptance_policy", po::value<fl::router_configuration::system_route_scope_type>()->default_value(fl::router_configuration::system_route_scope_type::none), "The system route acceptance policy.")
("router.maximum_routes_limit", po::value<unsigned int>()->default_value(1), "The maximum count of routes to accept for a given host.")
("router.dns_servers_acceptance_policy", po::value<fl::router_configuration::dns_servers_scope_type>()->default_value(fl::router_configuration::dns_servers_scope_type::in_network), "The DNS servers acceptance policy.")
("router.dns_script", po::value<fs::path>()->default_value(""), "The DNS script.")
;
return result;
}
void make_paths_absolute(boost::program_options::variables_map& vm, const boost::filesystem::path& root)
{
make_path_absolute("server.server_certificate_file", vm, root);
make_path_absolute("server.server_private_key_file", vm, root);
make_path_absolute("server.certification_authority_certificate_file", vm, root);
make_path_absolute("server.certification_authority_private_key_file", vm, root);
make_path_absolute("server.authentication_script", vm, root);
make_path_list_absolute("fscp.dynamic_contact_file", vm, root);
make_path_absolute("security.signature_certificate_file", vm, root);
make_path_absolute("security.signature_private_key_file", vm, root);
make_path_absolute("security.certificate_validation_script", vm, root);
make_path_list_absolute("security.authority_certificate_file", vm, root);
make_path_list_absolute("security.certificate_revocation_list_file", vm, root);
make_path_absolute("tap_adapter.up_script", vm, root);
make_path_absolute("tap_adapter.down_script", vm, root);
}
void setup_configuration(const fscp::logger& logger, fl::configuration& configuration, const po::variables_map& vm)
{
typedef fl::security_configuration::cert_type cert_type;
typedef cryptoplus::pkey::pkey pkey;
// Server options
configuration.server.enabled = vm["server.enabled"].as<bool>();
configuration.server.listen_on = vm["server.listen_on"].as<asiotap::endpoint>();
configuration.server.protocol = vm["server.protocol"].as<fl::server_configuration::server_protocol_type>();
if (load_certificate(configuration.server.server_certificate, "server.server_certificate_file", vm))
{
logger(fscp::log_level::information) << "Loaded server certificate from: " << vm["server.server_certificate_file"].as<fs::path>();
}
if (load_private_key(configuration.server.server_private_key, "server.server_private_key_file", vm))
{
logger(fscp::log_level::information) << "Loaded server private key from: " << vm["server.server_private_key_file"].as<fs::path>();
}
if (load_trusted_certificate(configuration.server.certification_authority_certificate, "server.certification_authority_certificate_file", vm))
{
logger(fscp::log_level::information) << "Loaded server CA certificate from: " << vm["server.certification_authority_certificate_file"].as<fs::path>();
}
if (load_private_key(configuration.server.certification_authority_private_key, "server.certification_authority_private_key_file", vm))
{
logger(fscp::log_level::information) << "Loaded server CA private key from: " << vm["server.certification_authority_private_key_file"].as<fs::path>();
}
configuration.server.authentication_script = vm["server.authentication_script"].as<fs::path>();
// Client options
configuration.client.enabled = vm["client.enabled"].as<bool>();
configuration.client.server_endpoint = vm["client.server_endpoint"].as<asiotap::endpoint>();
configuration.client.protocol = vm["client.protocol"].as<fl::client_configuration::client_protocol_type>();
configuration.client.disable_peer_verification = vm["client.disable_peer_verification"].as<bool>();
configuration.client.disable_host_verification = vm["client.disable_host_verification"].as<bool>();
configuration.client.username = vm["client.username"].as<std::string>();
configuration.client.password = vm["client.password"].as<std::string>();
const std::vector<asiotap::endpoint> public_endpoint = vm["client.public_endpoint"].as<std::vector<asiotap::endpoint> >();
configuration.client.public_endpoint_list.insert(public_endpoint.begin(), public_endpoint.end());
// FSCP options
configuration.fscp.hostname_resolution_protocol = vm["fscp.hostname_resolution_protocol"].as<fl::fscp_configuration::hostname_resolution_protocol_type>();
configuration.fscp.listen_on = vm["fscp.listen_on"].as<asiotap::endpoint>();
configuration.fscp.listen_on_device = vm["fscp.listen_on_device"].as<std::string>();
configuration.fscp.hello_timeout = vm["fscp.hello_timeout"].as<millisecond_duration>().to_time_duration();
const std::vector<asiotap::endpoint> contact = vm["fscp.contact"].as<std::vector<asiotap::endpoint> >();
configuration.fscp.contact_list.insert(contact.begin(), contact.end());
configuration.fscp.accept_contact_requests = vm["fscp.accept_contact_requests"].as<bool>();
configuration.fscp.accept_contacts = vm["fscp.accept_contacts"].as<bool>();
if (load_certificate_list(configuration.fscp.dynamic_contact_list, "fscp.dynamic_contact_file", vm))
{
for (auto _file : vm["fscp.dynamic_contact_file"].as<std::vector<fs::path>>())
{
logger(fscp::log_level::information) << "Loaded dynamic contact certificate from: " << _file;
}
}
configuration.fscp.never_contact_list = vm["fscp.never_contact"].as<std::vector<asiotap::ip_network_address>>();
configuration.fscp.cipher_suite_capabilities = vm["fscp.cipher_suite_capability"].as<std::vector<fscp::cipher_suite_type>>();
configuration.fscp.elliptic_curve_capabilities = vm["fscp.elliptic_curve_capability"].as<std::vector<fscp::elliptic_curve_type>>();
// Security options
const std::string passphrase = vm["security.passphrase"].as<std::string>();
const std::string passphrase_salt = vm["security.passphrase_salt"].as<std::string>();
const unsigned int passphrase_iterations_count = vm["security.passphrase_iterations_count"].as<unsigned int>();
cryptoplus::buffer pre_shared_key;
if (!passphrase.empty())
{
logger(fscp::log_level::information) << "Deriving pre-shared key from passphrase...";
const auto mdalg = cryptoplus::hash::message_digest_algorithm(NID_sha256);
pre_shared_key = cryptoplus::hash::pbkdf2(&passphrase[0], passphrase.size(), &passphrase_salt[0], passphrase_salt.size(), mdalg, passphrase_iterations_count);
}
cert_type signature_certificate;
pkey signature_private_key;
if (load_certificate(signature_certificate, "security.signature_certificate_file", vm))
{
logger(fscp::log_level::information) << "Loaded signature certificate from: " << vm["security.signature_certificate_file"].as<fs::path>();
}
if (load_private_key(signature_private_key, "security.signature_private_key_file", vm))
{
logger(fscp::log_level::information) << "Loaded signature private key from: " << vm["security.signature_private_key_file"].as<fs::path>();
}
if ((!!signature_certificate && !!signature_private_key) || !!pre_shared_key)
{
configuration.security.identity = fscp::identity_store(signature_certificate, signature_private_key, pre_shared_key);
}
configuration.security.certificate_validation_method = vm["security.certificate_validation_method"].as<fl::security_configuration::certificate_validation_method_type>();
configuration.security.certificate_validation_script = vm["security.certificate_validation_script"].as<fs::path>();
if (load_trusted_certificate_list(configuration.security.certificate_authority_list, "security.authority_certificate_file", vm))
{
for (auto _file : vm["security.authority_certificate_file"].as<std::vector<fs::path>>())
{
logger(fscp::log_level::information) << "Loaded authority certificate from: " << _file;
}
}
configuration.security.certificate_revocation_validation_method = vm["security.certificate_revocation_validation_method"].as<fl::security_configuration::certificate_revocation_validation_method_type>();
if (load_crl_list(configuration.security.certificate_revocation_list_list, "security.certificate_revocation_list_file", vm))
{
for (auto _file : vm["security.certificate_revocation_list_file"].as<std::vector<fs::path>>())
{
logger(fscp::log_level::information) << "Loaded certificate revocation file from: " << _file;
}
}
// Tap adapter options
configuration.tap_adapter.type = vm["tap_adapter.type"].as<fl::tap_adapter_configuration::tap_adapter_type>();
configuration.tap_adapter.enabled = vm["tap_adapter.enabled"].as<bool>();
if (vm.count("tap_adapter.name"))
{
configuration.tap_adapter.name = vm["tap_adapter.name"].as<std::string>();
}
configuration.tap_adapter.mtu = vm["tap_adapter.mtu"].as<fl::mtu_type>();
configuration.tap_adapter.mss_override = vm["tap_adapter.mss_override"].as<fl::mss_type>();
configuration.tap_adapter.metric = vm["tap_adapter.metric"].as<fl::metric_type>();
if (vm.count("tap_adapter.ipv4_address_prefix_length"))
{
configuration.tap_adapter.ipv4_address_prefix_length = vm["tap_adapter.ipv4_address_prefix_length"].as<asiotap::ipv4_network_address>();
}
if (vm.count("tap_adapter.ipv6_address_prefix_length"))
{
configuration.tap_adapter.ipv6_address_prefix_length = vm["tap_adapter.ipv6_address_prefix_length"].as<asiotap::ipv6_network_address>();
}
if (vm.count("tap_adapter.remote_ipv4_address"))
{
configuration.tap_adapter.remote_ipv4_address = vm["tap_adapter.remote_ipv4_address"].as<asiotap::ipv4_network_address>().address();
}
configuration.tap_adapter.arp_proxy_enabled = vm["tap_adapter.arp_proxy_enabled"].as<bool>();
configuration.tap_adapter.arp_proxy_fake_ethernet_address = vm["tap_adapter.arp_proxy_fake_ethernet_address"].as<fl::tap_adapter_configuration::ethernet_address_type>();
configuration.tap_adapter.dhcp_proxy_enabled = vm["tap_adapter.dhcp_proxy_enabled"].as<bool>();
configuration.tap_adapter.dhcp_server_ipv4_address_prefix_length = vm["tap_adapter.dhcp_server_ipv4_address_prefix_length"].as<asiotap::ipv4_network_address>();
configuration.tap_adapter.dhcp_server_ipv6_address_prefix_length = vm["tap_adapter.dhcp_server_ipv6_address_prefix_length"].as<asiotap::ipv6_network_address>();
configuration.tap_adapter.up_script = vm["tap_adapter.up_script"].as<fs::path>();
configuration.tap_adapter.down_script = vm["tap_adapter.down_script"].as<fs::path>();
// Switch options
configuration.switch_.routing_method = vm["switch.routing_method"].as<fl::switch_configuration::routing_method_type>();
configuration.switch_.relay_mode_enabled = vm["switch.relay_mode_enabled"].as<bool>();
// Router
const auto local_ip_routes = vm["router.local_ip_route"].as<std::vector<freelan::ip_route> >();
configuration.router.local_ip_routes.insert(local_ip_routes.begin(), local_ip_routes.end());
const auto local_ip_dns_servers = vm["router.local_dns_server"].as<std::vector<asiotap::ip_address> >();
configuration.router.local_dns_servers.insert(local_ip_dns_servers.begin(), local_ip_dns_servers.end());
configuration.router.client_routing_enabled = vm["router.client_routing_enabled"].as<bool>();
configuration.router.accept_routes_requests = vm["router.accept_routes_requests"].as<bool>();
configuration.router.internal_route_acceptance_policy = vm["router.internal_route_acceptance_policy"].as<fl::router_configuration::internal_route_scope_type>();
configuration.router.system_route_acceptance_policy = vm["router.system_route_acceptance_policy"].as<fl::router_configuration::system_route_scope_type>();
configuration.router.maximum_routes_limit = vm["router.maximum_routes_limit"].as<unsigned int>();
configuration.router.dns_servers_acceptance_policy = vm["router.dns_servers_acceptance_policy"].as<fl::router_configuration::dns_servers_scope_type>();
configuration.router.dns_script = vm["router.dns_script"].as<fs::path>();
}
|
A well-balanced, clean, geometric theme makes this office space inspire confidence. The brand colours used wisely through the walls, partitions and furniture are a strong reflection of the corporate look and feel. Glass and fabric across elements of acrylic & lacquer on the walls have been judiciously used to a project a cohesive design. |
import tactic -- hide
import data.real.basic -- hide
/-
## The `have` tactic
It is common in proofs to introduce auxiliary results, or claims, that help towards the goal. *Lean*
allows for this kind of structure, by allowing you to insert new hypotheses (as long as you prove them,
of course). This is done with the `have` tactic. The syntax is `have h : P,` where `h` is the name
you want to give to the new hypothesis (check that it doesn't exist already or you will run intro problems)
and `P` is a predicate like `x + 3 = 5`. You will get two goals, the first one will be to prove `P`,
and the second one will be the original goal. In the second one, you will have `h` available.
The next lemma cannot be proven by `ring` directly, since it involves an arbitrary exponent. There
are tactics that work with these kind of equations, but we will do something easier. If we can prove
first that $x+y=y+x$, then replacing that equality on the left-hand side will immediately finish the
goal. So start with `have h : x + y = y + x,` and work from there.
-/
/- Symbol:
ℝ : \R
-/
/- Lemma : no-side-bar
For all $n$, we have $(x+y)^n=(y+x)^n$.
-/
lemma h0 (x y : ℝ) (n : ℕ) : (x + y)^n = (y + x)^n :=
begin
have h : x + y = y + x,
{
ring,
},
rw h,
end
|
\chapter{Implementation}
\label{chap:impl}
The implementation is divided into several modules: \textit{core} (code for computing different equilibria), \textit{web} (a backend engine that allows to play games and stores the results in a database), \textit{console} (a console client for the web API), \textit{structures} (common structures for \textit{web} and \textit{console}), and \textit{analysis} (Spark code to analyze large datasets of games).
Each module is described in a separate section below.
There are several services ready to be used via Docker Compose, and can simply be run without the need of installing any additional software:
\textit{web} (the web API server), \textit{postgres} (a PostgreSQL database; is started automatically when running \textit{web}), \textit{console} (the console interface), \textit{analysis} (Apache Spark with commands from the \textit{analysis} module made available), and \textit{sbt} (the building tool; can be used to compile modules and to run tests).
\section{Core Module}
While the core module does not contain much code, it is the heart of this project.
It defines the following entities:
\begin{itemize}
\item \textsc{Game}: a case class that represents a game in normal form for two players.
\item \textsc{BestResponse}: a trait that describes a best response, given a game and the opponent's strategy.
It provides a method \textit{equilibria} which automatically computes all equilibria induced by the respective best response.
It is implemented by the following objects:
\begin{itemize}
\item \textsc{NashianBestResponse.Weak}
\item \textsc{NashianBestResponse.Strict}
\item \textsc{PerfectlyTransparentBestResponse.Weak}
\item \textsc{PerfectlyTransparentBestResponse.Strict}
\end{itemize}
\item \textsc{Eliminator}: a trait that describes an elimination process used for computing equilibria.
It defines method \textit{eliminate} which represents one round of elimination.
It implements method \textit{all} which performs the loop of elimination as long as the set of non-eliminated profiles keeps changing.
It is implemmented by the following objects:
\begin{itemize}
\item \textsc{IndividualRationality}
\item \textsc{MinimaxRationalizability}
\end{itemize}
\item In the theoretical part of this work, we also define some other equilibria: PTBPE and PTOPE.
These are not induced by best response definitions.
Instead, they are defined as strategy profiles where the \textit{perfectly transparent $i$-best profiles} and \textit{perfectly transparent $i$-optimal profiles} coincide for all players $i$.
These are implemented by the following objects:
\begin{itemize}
\item \textsc{PerfectlyTransparentRowBestProfile.Weak}
\item \textsc{PerfectlyTransparentRowBestProfile.Strict}
\item \textsc{PerfectlyTransparentColOptimalProfile.Weak}
\item \textsc{PerfectlyTransparentColOptimalProfile.Strict}
\end{itemize}
\item \textsc{GameGenerator}: an object for generating random games.
\end{itemize}
\section{Web Module}
\label{sec:impl-web-module}
The web module is a web server that provides a REST API for playing games in normal form against a computer.
Every time a game is played, the result is stored in a PostgreSQL database (see \autoref{fig:db-schema}).
The API exposes the following endpoints:
\begin{itemize}
\item \textsc{NewUser}: Creates a new user and returns the user's ID.
\item \textsc{NewGame}: Starts a new game; returns the game matrix and ID.
\item \textsc{Play}: For a game with a given ID, accepts the human player's (row) strategy and returns the computer's (column) strategy.
\item \textsc{Stats}: Returns statistics for a user with a given ID: number of games played and the average payoff.
\end{itemize}
Play Framework is used to implement the server.
For communicating with the database, we use Slick library.
\begin{figure}
\hspace{-1cm}
\includegraphics[width=14cm]{fig/schema.pdf}
\caption{The database schema.}
\label{fig:db-schema}
\end{figure}
\section{Console Module}
The console module is a sample client for the REST API described in \autoref{sec:impl-web-module}.
It allows the user to play a series of games of chosen dimensions.
For each game, the game matrix is displayed, and the user is asked to choose a strategy.
After choosing a strategy, the computer's strategy and the resulting payoff is displayed.
Then, the user is asked whether she wants to play another game.
At the end, statistics over all games are displayed.
\begin{figure}
\centering
\includegraphics[width=12cm]{fig/console.png}
\caption{The console interface.}
\label{fig:console-screen}
\end{figure}
\section{Analysis Module}
The analysis module is used for computing statistics about large datasets of games using Apache Spark.
It loads the datasets and computes the PTBPE, PTBRE, individually rational and minimax rationalizable strategy profiles, and stores them as a new dataset.
Searching through this dataset was useful to find counterexamples and form conjectures about inclusions of these equilibria (see \autoref{chap:game-theory}).
|
/*
Copyright (c) 2015 Siyu Lei, Silviu Maniu, Luyi Mo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef __oim__HighestDegreeEvaluator__
#define __oim__HighestDegreeEvaluator__
#include "common.hpp"
#include "Evaluator.hpp"
#include <boost/heap/fibonacci_heap.hpp>
class HighestDegreeEvaluator : public Evaluator {
private:
std::unordered_set<unode_int> seed_sets_;
std::unordered_set<unode_int> select(
const Graph& graph, Sampler&,
const std::unordered_set<unode_int>&, unsigned int k) {
std::unordered_set<unode_int> set;
boost::heap::fibonacci_heap<NodeType> queue;
for (unode_int node : graph.get_nodes()) {
NodeType nstruct;
nstruct.id = node;
nstruct.deg = 0;
if(graph.has_neighbours(node))
nstruct.deg = graph.get_neighbours(node).size();
queue.push(nstruct);
}
while (set.size() < k && !queue.empty()) {
NodeType nstruct = queue.top();
if (seed_sets_.find(nstruct.id) == seed_sets_.end()) {
// Guarantee no duplicate nodes in the seed set for all trials
set.insert(nstruct.id);
seed_sets_.insert(nstruct.id);
}
queue.pop();
}
return set;
}
};
#endif /* defined(__oim__HighestDegreeEvaluator__) */
|
From mathcomp Require Import all_ssreflect all_algebra all_field.
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Import GRing.Theory Num.Theory UnityRootTheory.
Open Scope ring_scope.
Section PreliminaryLemmas.
(** -------------------------------------------- *)
(** #<div class='slide'>#
* Preliminaries
Let's extend the library on rings and algebraic numbers
with some easy lemmas first.
** Question -2: prove that if a sum of natural numbers is 1 then one of its term is 0 and the other is 1
Note that we do not consider nat but the copy of nat which is embeded
in the algebraic numbers algC. The theorem is easy to prove for nat, so
we suggest you use a compatibility lemma numbers between nat and Cnat
*)
Lemma Cnat_add_eq1 : {in Cnat &, forall x y,
(x + y == 1) = ((x == 1) && (y == 0)) || ((x == 0) && (y == 1))}.
Proof.
(*D*)move=> x y /CnatP [n ->] /CnatP [m ->]; rewrite -natrD !pnatr_eq1 ?pnatr_eq0.
(*D*)by move: n m => [|[|?]] [|[|?]].
(*A*)Qed.
(**
** Question -1: The real part of product
*)
Lemma algReM (x y : algC) : 'Re (x * y) = 'Re x * 'Re y - 'Im x * 'Im y.
Proof.
(*D*)rewrite {1}[x]algCrect {1}[y]algCrect mulC_rect algRe_rect //;
(*D*)by rewrite rpredD ?rpredN // rpredM // ?Creal_Re ?Creal_Im.
(*A*)Qed.
(**
** Question 0: The imaginary part of product
(it's the same, don't do it if takes more than 5s
*)
Lemma algImM (x y : algC) : 'Im (x * y) = 'Re x * 'Im y + 'Re y * 'Im x.
Proof.
(*D*)rewrite {1}[x]algCrect {1}[y]algCrect mulC_rect algIm_rect //;
(*D*)by rewrite rpredD ?rpredN // rpredM // ?Creal_Re ?Creal_Im.
(*A*)Qed.
End PreliminaryLemmas.
(** #</div># *)
(** -------------------------------------------- *)
(** #<div class='slide'>#
* The ring of Gauss integers
- Ref: exercices de mathematiques oraux X-ENS algebre 1
- Exercice 3.10. ENS Lyon
*)
Section GaussIntegers.
(**
First we define a predicate for the algebraic numbers which are gauss integers.
*)
Definition gaussInteger := [qualify a x | ('Re x \in Cint) && ('Im x \in Cint)].
(**
** Question 1: Prove that integers are gauss integers
*)
Lemma Cint_GI (x : algC) : x \in Cint -> x \is a gaussInteger.
Proof.
(*D*)move=> x_int; rewrite qualifE (Creal_ReP _ _) ?(Creal_ImP _ _) ?Creal_Cint //.
(*D*)by rewrite x_int rpred0.
(*A*)Qed.
(** #</div># *)
(** -------------------------------------------- *)
(** #<div class='slide'>#
** Question 2: Prove that gauss integers form a subfield
*)
Lemma GI_subring : subring_closed gaussInteger.
Proof.
(*D*)split => [|x y /andP[??] /andP[??]|x y /andP[??] /andP[??]].
(*D*)- by rewrite Cint_GI.
(*D*)- by rewrite qualifE !raddfB /= ?rpredB.
(*D*)by rewrite qualifE algReM algImM rpredB ?rpredD // rpredM.
(*A*)Qed.
(**
There follows the boilerplate to use the proof GI_subring in order to
canonically provide a subring structure to the predicate gaussInteger.
*)
Fact GI_key : pred_key gaussInteger. Proof. by []. Qed.
Canonical GI_keyed := KeyedQualifier GI_key.
Canonical GI_opprPred := OpprPred GI_subring.
Canonical GI_addrPred := AddrPred GI_subring.
Canonical GI_mulrPred := MulrPred GI_subring.
Canonical GI_zmodPred := ZmodPred GI_subring.
Canonical GI_semiringPred := SemiringPred GI_subring.
Canonical GI_smulrPred := SmulrPred GI_subring.
Canonical GI_subringPred := SubringPred GI_subring.
(**
Finally, we define the type of Gauss Integer, as a sigma type of
algebraic numbers. We soon prove that this is in fact a sub type.
*)
Record GI := GIof {
algGI : algC;
algGIP : algGI \is a gaussInteger }.
(** We make the defining property of GI a Hint *)
Hint Resolve algGIP.
(**
We provide the subtype property.
- This makes it possible to use the generic operator "val" to get an
algC from a Gauss Integer.
*)
Canonical GI_subType := [subType for algGI].
(**
We deduce that the real and imaginary parts of a GI are integers
*)
Lemma GIRe (x : GI) : 'Re (val x) \in Cint.
Proof. by have /andP [] := algGIP x. Qed.
Lemma GIIm (x : GI) : 'Im (val x) \in Cint.
Proof. by have /andP [] := algGIP x. Qed.
Hint Resolve GIRe GIIm.
Canonical ReGI x := GIof (Cint_GI (GIRe x)).
Canonical ImGI x := GIof (Cint_GI (GIIm x)).
(**
We provide a ring structure to the type GI, using the subring
canonical property for the predicate gaussInteger
*)
Definition GI_eqMixin := [eqMixin of GI by <:].
Canonical GI_eqType := EqType GI GI_eqMixin.
Definition GI_choiceMixin := [choiceMixin of GI by <:].
Canonical GI_choiceType := ChoiceType GI GI_choiceMixin.
Definition GI_countMixin := [countMixin of GI by <:].
Canonical GI_countType := CountType GI GI_countMixin.
Definition GI_zmodMixin := [zmodMixin of GI by <:].
Canonical GI_zmodType := ZmodType GI GI_zmodMixin.
Definition GI_ringMixin := [ringMixin of GI by <:].
Canonical GI_ringType := RingType GI GI_ringMixin.
Definition GI_comRingMixin := [comRingMixin of GI by <:].
Canonical GI_comRingType := ComRingType GI GI_comRingMixin.
(* Definition GI_unitRingMixin := [unitRingMixin of GI by <:]. *)
(* Canonical GI_unitRingType := UnitRingType GI GI_unitRingMixin. *)
(**
- Now we build the unitRing and comUnitRing structure of gauss
integers. Contrarily to the previous structures, the operator is
not the same as on algebraics. Indeed the invertible algebraics are
not necessarily invertible gauss integers.
- Hence, we define the inverse of gauss integers as follow : if the
algebraic inverse happens to be a gauss integer we recover the
proof and package it together with the element and get a gauss
integer, otherwise, we default to the identity.
- A gauss integer is invertible if the algbraic inverse is a gauss
integer.
*)
Definition invGI (x : GI) := insubd x (val x)^-1.
Definition unitGI := [pred x : GI | (x != 0) && ((val x)^-1 \is a gaussInteger)].
(** #</div># *)
(** -------------------------------------------- *)
(** #<div class='slide'>#
** Question 3: prove a few facts in order to find a comUnitRingMixin
for GI, and then instantiate the interfaces of unitRingType and
comUnitRingType.
Do only one of the following proofs.
*)
Fact mulGIr : {in unitGI, left_inverse 1 invGI *%R}.
Proof.
(*D*)move=> x /andP [x_neq0 xVGI]; rewrite /invGI.
(*D*)by apply: val_inj; rewrite /= insubdK // mulVr ?unitfE.
(*A*)Qed.
Fact unitGIP (x y : GI) : y * x = 1 -> unitGI x.
Proof.
(*D*)rewrite /unitGI => /(congr1 val) /=.
(*D*)have [-> /eqP|x_neq0] := altP (x =P 0); first by rewrite mulr0 eq_sym oner_eq0.
(*D*)by move=> /(canRL (mulfK x_neq0)); rewrite mul1r => <- /=.
(*A*)Qed.
Fact unitGI_out : {in [predC unitGI], invGI =1 id}.
Proof.
move=> x.
(*D*)rewrite !inE /= /unitGI.
(*D*)rewrite negb_and negbK => /predU1P [->|/negPf xGIF];
(*D*)by apply: val_inj; rewrite /invGI ?val_insubd /= ?xGIF // invr0 if_same.
(*A*)Qed.
(*D*)
Definition GI_comUnitRingMixin := ComUnitRingMixin mulGIr unitGIP unitGI_out.
Canonical GI_unitRingType := UnitRingType GI GI_comUnitRingMixin.
Canonical GI_comUnitRingType := [comUnitRingType of GI].
(** #</div># *)
(** -------------------------------------------- *)
(** #<div class='slide'>#
** Question 4: Show that gauss integers are stable by conjugation.
*)
Lemma conjGIE x : (x^* \is a gaussInteger) = (x \is a gaussInteger).
(*A*)Proof. by rewrite ![_ \is a _]qualifE algRe_conj algIm_conj rpredN. Qed.
(**
We use this fact to build the conjugation of a gauss Integers
*)
Fact conjGI_subproof (x : GI) : (val x)^* \is a gaussInteger.
Proof. by rewrite conjGIE. Qed.
Canonical conjGI x := GIof (conjGI_subproof x).
(**
We now define the norm (stasm) for gauss integer, we don't need to
specialize it to gauss integer so we define it over algebraic numbers
instead.
*)
Definition gaussNorm (x : algC) := x * x^*.
Lemma gaussNorm_val (x : GI) : gaussNorm (val x) = val (x * conjGI x).
Proof. by []. Qed.
(**
** Question 4: Show that the gaussNorm of x is the square of the complex modulus of x
Hint: only one rewrite with the right theorem.
*)
Lemma gaussNormE x : gaussNorm x = `|x| ^+ 2.
(*A*)Proof. by rewrite normCK. Qed.
(** #</div># *)
(** -------------------------------------------- *)
(** #<div class='slide'>#
** Question 5: Show that the gaussNorm of an gauss integer is a natural number.
*)
Lemma gaussNormCnat (x : GI) : gaussNorm (val x) \in Cnat.
(*A*)Proof. by rewrite /gaussNorm -normCK normC2_Re_Im rpredD // Cnat_exp_even. Qed.
Hint Resolve gaussNormCnat.
(** #</div># *)
(** -------------------------------------------- *)
(** #<div class='slide'>#
** Question 6: Show that gaussNorm is multiplicative (on all algC).
Hint: use morphism lemmas #<code>rmorph1</code># and #<code>rmorphM</code>#
*)
Lemma gaussNorm1 : gaussNorm 1 = 1.
(*A*)Proof. by rewrite /gaussNorm rmorph1 mulr1. Qed.
Lemma gaussNormM : {morph gaussNorm : x y / x * y}.
(*A*)Proof. by move=> x y; rewrite /gaussNorm rmorphM mulrACA. Qed.
(** #</div># *)
(** -------------------------------------------- *)
(** #<div class='slide'>#
** Question 7 (hard): Find the invertible elements of GI
- This is question 1 of the CPGE exercice
Do unitGI_norm1 first, and come back to side lemmas later.
*)
Lemma rev_unitrPr (R : comUnitRingType) (x y : R) : x * y = 1 -> x \is a GRing.unit.
Proof. by move=> ?; apply/unitrPr; exists y. Qed.
Lemma eq_algC a b : (a == b :> algC) = ('Re a == 'Re b) && ('Im a == 'Im b).
Proof.
rewrite -subr_eq0 [a - b]algCrect -normr_eq0 -sqrf_eq0.
rewrite normC2_rect ?paddr_eq0 ?sqr_ge0 -?realEsqr ?Creal_Re ?Creal_Im //.
by rewrite !sqrf_eq0 !raddfB ?subr_eq0.
Qed.
Lemma primitive_root_i : 4.-primitive_root 'i.
Proof.
(*D*)have : 'i ^+ 4 = 1 by rewrite [_ ^+ (2 * 2)]exprM sqrCi -signr_odd expr0.
(*D*)move=> /prim_order_exists [] // [//|[|[|[//|[//|//]]]]] /prim_expr_order.
(*D*) rewrite expr1 => /(congr1 (fun x => 'Im x)) /eqP.
(*D*) by rewrite algIm_i (Creal_ImP _ _) ?oner_eq0 ?rpred1.
(*D*)by move/eqP; rewrite sqrCi eq_sym -addr_eq0 paddr_eq0 ?ler01 ?oner_eq0.
(*A*)Qed.
Lemma primitive_rootX_unity (C: fieldType) n (x : C) :
n.-primitive_root x -> n.-unity_root =i [seq x ^+ (val k) | k <- enum 'I_n].
Proof.
(*D*)move=> x_p y; rewrite -topredE /= unity_rootE; apply/idP/idP; last first.
(*D*) by move=> /mapP [k _ ->]; rewrite exprAC [x ^+ _]prim_expr_order // expr1n.
(*D*)by move=> /eqP/(prim_rootP x_p)[k ->]; apply/mapP; exists k; rewrite ?mem_enum.
(*A*)Qed.
Lemma unitGI_norm1 (a : GI) : (a \in GRing.unit) = (val a \in 4.-unity_root).
(*D*)Proof. (*give trace*)
transitivity (gaussNorm (val a) == 1).
apply/idP/idP; last first.
(*a*) by rewrite gaussNorm_val (val_eqE _ (1 : GI)) => /eqP /rev_unitrPr.
(*D*) move=> /unitrPr [b /(congr1 (gaussNorm \o val)) /=] /eqP.
(*a*) by rewrite gaussNormM gaussNorm1 Cnat_mul_eq1 // => /andP [].
rewrite (primitive_rootX_unity primitive_root_i).
rewrite (map_comp (GRing.exp 'i) val) val_enum_ord /=.
rewrite /= expr0 expr1 sqrCi exprSr sqrCi mulN1r.
rewrite !in_cons in_nil ?orbF orbA orbAC !orbA orbAC -!orbA.
(*D*)rewrite [val a in LHS]algCrect gaussNormE normC2_rect ?Creal_Re ?Creal_Im //.
(*D*)rewrite Cnat_add_eq1 ?Cnat_exp_even // !sqrf_eq0 !sqrf_eq1.
(*D*)rewrite andb_orr andb_orl -!orbA.
(*D*)rewrite ?[val _ == _]eq_algC !raddfN /=.
(*a*)by rewrite algRe_i algIm_i ?(Creal_ReP 1 _) ?(Creal_ImP 1 _) ?oppr0.
(*A*)Qed.
End GaussIntegers.
(* End of exercices *)
|
(** Sharpened ADT for an expression grammar with parentheses *)
Require Import Fiat.Parsers.Refinement.Tactics.
Require Import Fiat.Parsers.Grammars.ExpressionParen.
Section IndexedImpl.
Lemma ComputationalSplitter'
: FullySharpened (string_spec paren_expr_grammar string_stringlike).
Proof.
splitter_start; splitter_finish.
Defined.
Lemma ComputationalSplitter
: FullySharpened (string_spec paren_expr_grammar string_stringlike).
Proof.
make_simplified_splitter ComputationalSplitter'.
Defined.
End IndexedImpl.
Require Import Fiat.Parsers.ParserFromParserADT.
Require Import Fiat.Parsers.ExtrOcamlParsers.
Import Fiat.Parsers.ExtrOcamlParsers.HideProofs.
Definition paren_expr_parser (str : String.string) : bool.
Proof.
Time make_parser ComputationalSplitter. (* 13 s *)
Defined.
Print paren_expr_parser.
Recursive Extraction paren_expr_parser.
|
import numpy as np
import os
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
from numpy.fft import ifftshift
import math
from .utils import abs, real, imag, spatial_normalize, downsample, prepare_image
eps = 1e-12
def logGabor(rows,cols,omega0,sigmaF):
u1, u2 = np.meshgrid(np.linspace(-0.5, 0.5, cols, endpoint=(cols % 2)),
np.linspace(-0.5, 0.5, rows, endpoint=(rows % 2)))
mask = u1**2+u2**2<0.25
# Quadrant shift to put 0 frequency at the top left corner
u1 = ifftshift(u1*mask)
u2 = ifftshift(u2*mask)
# Compute frequency values as a radius from centre (but quadrant shifted)
radius = np.sqrt(u1 * u1 + u2 * u2+eps)
radius[0,0]=1
logGaborDenom = 2. * sigmaF ** 2.
logRadOverFo = (np.log(radius / omega0))
log_Gabor = np.exp(-(logRadOverFo * logRadOverFo) / logGaborDenom)
log_Gabor[0, 0] = 0. # Undo the radius fudge
return log_Gabor
def rgb_to_lab_NCHW(srgb):
srgb.clamp_(min=0,max=1)
device = srgb.device
B, C, rows, cols = srgb.shape
srgb_pixels = torch.reshape(srgb.permute(0,2,3,1), [B, -1, 3])
linear_mask = (srgb_pixels <= 0.04045).type(torch.FloatTensor).to(device)
exponential_mask = (srgb_pixels > 0.04045).type(torch.FloatTensor).to(device)
rgb_pixels = (srgb_pixels / 12.92 * linear_mask) + (((srgb_pixels + 0.055) / 1.055) ** 2.4) * exponential_mask
rgb_to_xyz = torch.tensor([
# X Y Z
[0.412453, 0.212671, 0.019334], # R
[0.357580, 0.715160, 0.119193], # G
[0.180423, 0.072169, 0.950227], # B
]).type(torch.FloatTensor).to(device)#.unsqueeze(0).repeat(B,1,1)
xyz_pixels = torch.matmul(rgb_pixels, rgb_to_xyz)
# XYZ to Lab
t = torch.tensor([1/0.950456, 1.0, 1/1.088754]).type(torch.FloatTensor).to(device)
xyz_normalized_pixels = (xyz_pixels / t)
epsilon = 6.0/29.0
linear_mask = (xyz_normalized_pixels <= (epsilon**3)).type(torch.FloatTensor).to(device)
exponential_mask = (xyz_normalized_pixels > (epsilon**3)).type(torch.FloatTensor).to(device)
fxfyfz_pixels = (xyz_normalized_pixels / (3 * epsilon**2) + 4.0/29.0) * linear_mask + ((xyz_normalized_pixels).clamp_(min=eps).pow(1/3)) * exponential_mask
# convert to lab
fxfyfz_to_lab = torch.tensor([
# l a b
[ 0.0, 500.0, 0.0], # fx
[116.0, -500.0, 200.0], # fy
[ 0.0, 0.0, -200.0], # fz
]).type(torch.FloatTensor).to(device)#.unsqueeze(0).repeat(B,1,1)
lab_pixels = torch.matmul(fxfyfz_pixels, fxfyfz_to_lab) + torch.tensor([-16.0, 0.0, 0.0]).type(torch.FloatTensor).to(device)
return torch.reshape(lab_pixels.permute(0,2,1), srgb.shape)
def SDSP(img,sigmaF,omega0,sigmaD,sigmaC):
B, C, rows, cols = img.shape
lab = rgb_to_lab_NCHW(img/255)
LChannel, AChannel, BChannel = lab[:,0,:,:].unsqueeze(1),lab[:,1,:,:].unsqueeze(1),lab[:,2,:,:].unsqueeze(1)
LFFT = torch.rfft(LChannel,2,onesided=False)
AFFT = torch.rfft(AChannel,2,onesided=False)
BFFT = torch.rfft(BChannel,2,onesided=False)
LG = logGabor(rows,cols,omega0,sigmaF)
LG = torch.from_numpy(LG).reshape(1, 1, rows,cols,1).repeat(B,1,1,1,2).float().to(img.device)
FinalLResult = real(torch.ifft(LFFT*LG,2))
FinalAResult = real(torch.ifft(AFFT*LG,2))
FinalBResult = real(torch.ifft(BFFT*LG,2))
SFMap = torch.sqrt(FinalLResult**2 + FinalAResult**2 + FinalBResult**2+eps)
coordinateMtx = torch.from_numpy(np.arange(0,rows)).float().reshape(1,1,rows,1).repeat(B,1,1,cols).to(img.device)
centerMtx = torch.ones_like(coordinateMtx)*rows/2
coordinateMty = torch.from_numpy(np.arange(0,cols)).float().reshape(1,1,1,cols).repeat(B,1,rows,1).to(img.device)
centerMty = torch.ones_like(coordinateMty)*cols/2
SDMap = torch.exp(-((coordinateMtx - centerMtx)**2+(coordinateMty - centerMty)**2)/(sigmaD**2))
normalizedA = spatial_normalize(AChannel)
normalizedB = spatial_normalize(BChannel)
labDistSquare = normalizedA**2 + normalizedB**2
SCMap = 1 - torch.exp(-labDistSquare / (sigmaC**2))
VSMap = SFMap * SDMap * SCMap
normalizedVSMap = spatial_normalize(VSMap)
return normalizedVSMap
def vsi(image1,image2):
constForVS = 1.27
constForGM = 386
constForChrom = 130
alpha = 0.40
lamda = 0.020
sigmaF = 1.34
omega0 = 0.0210
sigmaD = 145
sigmaC = 0.001
saliencyMap1 = SDSP(image1,sigmaF,omega0,sigmaD,sigmaC)
saliencyMap2 = SDSP(image2,sigmaF,omega0,sigmaD,sigmaC)
L1 = (0.06 * image1[:,0,:,:] + 0.63 * image1[:,1,:,:] + 0.27 * image1[:,2,:,:]).unsqueeze(1)
L2 = (0.06 * image2[:,0,:,:] + 0.63 * image2[:,1,:,:] + 0.27 * image2[:,2,:,:]).unsqueeze(1)
M1 = (0.30 * image1[:,0,:,:] + 0.04 * image1[:,1,:,:] - 0.35 * image1[:,2,:,:]).unsqueeze(1)
M2 = (0.30 * image2[:,0,:,:] + 0.04 * image2[:,1,:,:] - 0.35 * image2[:,2,:,:]).unsqueeze(1)
N1 = (0.34 * image1[:,0,:,:] - 0.60 * image1[:,1,:,:] + 0.17 * image1[:,2,:,:]).unsqueeze(1)
N2 = (0.34 * image2[:,0,:,:] - 0.60 * image2[:,1,:,:] + 0.17 * image2[:,2,:,:]).unsqueeze(1)
L1, L2 = downsample(L1, L2)
M1, M2 = downsample(M1, M2)
N1, N2 = downsample(N1, N2)
saliencyMap1, saliencyMap2 = downsample(saliencyMap1, saliencyMap2)
dx = torch.Tensor([[3, 0, -3], [10, 0, -10], [3, 0, -3]]).float()/16
dy = torch.Tensor([[3, 10, 3], [0, 0, 0], [-3, -10, -3]]).float()/16
dx = dx.reshape(1,1,3,3).to(image1.device)
dy = dy.reshape(1,1,3,3).to(image1.device)
IxY1 = F.conv2d(L1, dx, stride=1, padding =1)
IyY1 = F.conv2d(L1, dy, stride=1, padding =1)
gradientMap1 = torch.sqrt(IxY1**2 + IyY1**2+eps)
IxY2 = F.conv2d(L2, dx, stride=1, padding =1)
IyY2 = F.conv2d(L2, dy, stride=1, padding =1)
gradientMap2 = torch.sqrt(IxY2**2 + IyY2**2+eps)
VSSimMatrix = (2 * saliencyMap1 * saliencyMap2 + constForVS) / (saliencyMap1**2 + saliencyMap2**2 + constForVS)
gradientSimMatrix = (2*gradientMap1*gradientMap2 + constForGM) /(gradientMap1**2 + gradientMap2**2 + constForGM)
weight = torch.max(saliencyMap1, saliencyMap2)
ISimMatrix = (2 * M1 * M2 + constForChrom) / (M1**2 + M2**2 + constForChrom)
QSimMatrix = (2 * N1 * N2 + constForChrom) / (N1**2 + N2**2 + constForChrom)
# SimMatrixC = (torch.sign(gradientSimMatrix) * (torch.abs(gradientSimMatrix)+eps) ** alpha) * VSSimMatrix * \
# (torch.sign(ISimMatrix * QSimMatrix)*(torch.abs(ISimMatrix * QSimMatrix)+eps) ** lamda) * weight
SimMatrixC = ((torch.abs(gradientSimMatrix)+eps) ** alpha) * VSSimMatrix * \
((torch.abs(ISimMatrix * QSimMatrix)+eps) ** lamda) * weight
return torch.sum(SimMatrixC,dim=[1,2,3]) / torch.sum(weight,dim=[1,2,3])
class VSI(torch.nn.Module):
# Refer to https://sse.tongji.edu.cn/linzhang/IQA/VSI/VSI.htm
def __init__(self, channels=3):
super(VSI, self).__init__()
assert channels == 3
def forward(self, y, x, as_loss=True):
assert x.shape == y.shape
x = x * 255
y = y * 255
if as_loss:
score = vsi(x, y)
return 1 - score.mean()
else:
with torch.no_grad():
score = vsi(x, y)
return score
if __name__ == '__main__':
from PIL import Image
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--ref', type=str, default='images/r0.png')
parser.add_argument('--dist', type=str, default='images/r1.png')
args = parser.parse_args()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
ref = prepare_image(Image.open(args.ref).convert("RGB")).to(device)
dist = prepare_image(Image.open(args.dist).convert("RGB")).to(device)
model = VSI().to(device)
score = model(dist, ref, as_loss=False)
print('score: %.4f' % score.item())
# score: 0.9322
|
subroutine upper (token)
integer token (100)
integer cupper
integer i
i = 1
23000 if (.not.(token (i) .ne. -2))goto 23002
token (i) = cupper (token (i))
23001 i = i + 1
goto 23000
23002 continue
return
end
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-|
Module : Grenade.Layers.Logit
Description : Exponential linear unit layer
Copyright : (c) Huw Campbell, 2016-2017
License : BSD2
Stability : experimental
-}
module Grenade.Layers.Elu
( Elu(..)
, SpecElu (..)
, specElu1D
, specElu2D
, specElu3D
, elu
) where
import Control.DeepSeq (NFData)
import Data.Constraint (Dict (..))
import Data.Reflection (reifyNat)
import Data.Serialize
import Data.Singletons
import GHC.Generics (Generic)
import GHC.TypeLits
import qualified Numeric.LinearAlgebra.Static as LAS
import Unsafe.Coerce (unsafeCoerce)
import Grenade.Core
import Grenade.Dynamic
import Grenade.Dynamic.Internal.Build
-- | An exponential linear unit.
-- A layer which can act between any shape of the same dimension, acting as a
-- diode on every neuron individually.
data Elu = Elu
deriving (Generic, NFData, Show)
instance UpdateLayer Elu where
type Gradient Elu = ()
runUpdate _ _ _ = Elu
instance RandomLayer Elu where
createRandomWith _ _ = return Elu
instance Serialize Elu where
put _ = return ()
get = return Elu
instance ( KnownNat i) => Layer Elu ('D1 i) ('D1 i) where
type Tape Elu ('D1 i) ('D1 i) = LAS.R i
runForwards _ (S1D y) = (y, S1D (elu y))
where
elu = LAS.dvmap (\a -> if a <= 0 then exp a - 1 else a)
runBackwards _ y (S1D dEdy) = ((), S1D (elu' y * dEdy))
where
elu' = LAS.dvmap (\a -> if a <= 0 then exp a else 1)
instance (KnownNat i, KnownNat j) => Layer Elu ('D2 i j) ('D2 i j) where
type Tape Elu ('D2 i j) ('D2 i j) = S ('D2 i j)
runForwards _ (S2D y) = (S2D y, S2D (elu y))
where
elu = LAS.dmmap (\a -> if a <= 0 then exp a - 1 else a)
runBackwards _ (S2D y) (S2D dEdy) = ((), S2D (elu' y * dEdy))
where
elu' = LAS.dmmap (\a -> if a <= 0 then exp a else 1)
instance (KnownNat i, KnownNat j, KnownNat k) => Layer Elu ('D3 i j k) ('D3 i j k) where
type Tape Elu ('D3 i j k) ('D3 i j k) = S ('D3 i j k)
runForwards _ (S3D y) = (S3D y, S3D (elu y))
where
elu = LAS.dmmap (\a -> if a <= 0 then exp a - 1 else a)
runBackwards _ (S3D y) (S3D dEdy) = ((), S3D (elu' y * dEdy))
where
elu' = LAS.dmmap (\a -> if a <= 0 then exp a else 1)
-------------------- DynamicNetwork instance --------------------
instance FromDynamicLayer Elu where
fromDynamicLayer inp _ _ = SpecNetLayer $ SpecElu (tripleFromSomeShape inp)
instance ToDynamicLayer SpecElu where
toDynamicLayer _ _ (SpecElu (rows, cols, depth)) =
reifyNat rows $ \(_ :: (KnownNat rows) => Proxy rows) ->
reifyNat cols $ \(_ :: (KnownNat cols) => Proxy cols) ->
reifyNat depth $ \(_ :: (KnownNat depth) => Proxy depth) ->
case (rows, cols, depth) of
(_, 1, 1) -> return $ SpecLayer Elu (sing :: Sing ('D1 rows)) (sing :: Sing ('D1 rows))
(_, _, 1) -> return $ SpecLayer Elu (sing :: Sing ('D2 rows cols)) (sing :: Sing ('D2 rows cols))
_ -> case (unsafeCoerce (Dict :: Dict()) :: Dict (KnownNat (rows GHC.TypeLits.* depth))) of
Dict -> return $ SpecLayer Elu (sing :: Sing ('D3 rows cols depth)) (sing :: Sing ('D3 rows cols depth))
-- | Create a specification for a elu layer.
specElu1D :: Integer -> SpecNet
specElu1D i = specElu3D (i, 1, 1)
-- | Create a specification for a elu layer.
specElu2D :: (Integer, Integer) -> SpecNet
specElu2D (i,j) = specElu3D (i,j,1)
-- | Create a specification for a elu layer.
specElu3D :: (Integer, Integer, Integer) -> SpecNet
specElu3D = SpecNetLayer . SpecElu
-- | Add a Elu layer to your build.
elu :: BuildM ()
elu = buildGetLastLayerOut >>= buildAddSpec . SpecNetLayer . SpecElu
-------------------- GNum instances --------------------
instance GNum Elu where
_ |* Elu = Elu
_ |+ Elu = Elu
|
(* Following http://adam.chlipala.net/theses/andreser.pdf chapter 3 *)
Require Import Coq.ZArith.ZArith Coq.micromega.Lia.
Require Import Coq.Structures.Orders.
Require Import Coq.Lists.List.
Require Import Crypto.Algebra.Nsatz.
Require Import Crypto.Arithmetic.ModularArithmeticTheorems.
Require Import Crypto.Util.Decidable.
Require Import Crypto.Util.LetIn.
Require Import Crypto.Util.ListUtil.
Require Import Crypto.Util.NatUtil.
Require Import Crypto.Util.Prod.
Require Import Crypto.Util.Decidable.Bool2Prop.
Require Import Crypto.Util.Tactics.SpecializeBy.
Require Import Crypto.Util.Tactics.UniquePose.
Require Import Crypto.Util.CPSUtil.
Require Import Crypto.Util.CPSNotations.
Require Import Crypto.Util.ZUtil.Definitions.
Require Import Crypto.Util.ZUtil.EquivModulo.
Require Import Crypto.Util.ZUtil.Modulo Crypto.Util.ZUtil.Div.
Require Import Crypto.Util.ZUtil.Zselect.
Require Import Crypto.Util.ZUtil.Hints.Core.
Require Import Crypto.Util.ZUtil.Modulo.PullPush.
Require Import Crypto.Util.ZUtil.Tactics.LtbToLt.
Require Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.
Require Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.
Require Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.
Require Import Crypto.Util.Notations.
Import ListNotations. Local Open Scope Z_scope.
Reserved Notation "'dlet_list_pair_only_snd' x := v 'in' f"
(at level 200, f at level 200, format "'dlet_list_pair_only_snd' x := v 'in' '//' f").
Reserved Notation "'dlet_list_pair' x := v 'in' f"
(at level 200, f at level 200, format "'dlet_list_pair' x := v 'in' '//' f").
Reserved Notation "'dlet_list' x := v 'in' f"
(at level 200, f at level 200, format "'dlet_list' x := v 'in' '//' f").
Declare Scope runtime_scope.
Delimit Scope runtime_scope with RT.
Import CPSBindNotations.
Local Open Scope cps_scope.
Module Type Runtime.
Parameter Let_In : forall {A P} (x : A) (f : forall a : A, P a), P x.
Parameter runtime_nth_default : forall {A}, A -> list A -> nat -> A.
Parameter runtime_add : Z -> Z -> Z.
Parameter runtime_sub : Z -> Z -> Z.
Parameter runtime_mul : Z -> Z -> Z.
Parameter runtime_div : Z -> Z -> Z.
Parameter runtime_modulo : Z -> Z -> Z.
Parameter runtime_opp : Z -> Z.
Arguments runtime_add (_ _)%RT.
Arguments runtime_sub (_ _)%RT.
Arguments runtime_mul (_ _)%RT.
Arguments runtime_div _%RT _%Z.
Arguments runtime_modulo _%RT _%Z.
Arguments runtime_opp _%RT.
Infix "*" := runtime_mul : runtime_scope.
Infix "+" := runtime_add : runtime_scope.
Infix "-" := runtime_sub : runtime_scope.
Infix "/" := runtime_div : runtime_scope.
Notation "x 'mod' y" := (runtime_modulo x y) : runtime_scope.
Notation "- x" := (runtime_opp x) : runtime_scope.
Notation "'dlet_nd' x .. y := v 'in' f" := (Let_In (P:=fun _ => _) v (fun x => .. (fun y => f) .. )) (only parsing).
Notation "'dlet' x .. y := v 'in' f" := (Let_In v (fun x => .. (fun y => f) .. )).
Module RT_Z.
Parameter zselect : Z -> Z -> Z -> Z.
Parameter add_get_carry_full : Z -> Z -> Z -> Z * Z.
Parameter add_with_get_carry_full : Z -> Z -> Z -> Z -> Z * Z.
Parameter mul_split : Z -> Z -> Z -> Z * Z.
Parameter land : Z -> Z -> Z.
End RT_Z.
End Runtime.
Module RuntimeDefinitions <: Runtime.
Definition Let_In := @LetIn.Let_In.
Definition runtime_nth_default := List.nth_default.
Definition runtime_add := Z.add.
Definition runtime_sub := Z.sub.
Definition runtime_mul := Z.mul.
Definition runtime_opp := Z.opp.
Definition runtime_div := Z.div.
Definition runtime_modulo := Z.modulo.
Module RT_Z.
Definition zselect := Z.zselect.
Definition add_get_carry_full := Z.add_get_carry_full.
Definition add_with_get_carry_full := Z.add_with_get_carry_full.
Definition mul_split := Z.mul_split.
Definition land := Z.land.
End RT_Z.
End RuntimeDefinitions.
Module RuntimeAxioms : Runtime.
Include RuntimeDefinitions.
End RuntimeAxioms.
Module Export RuntimeDefinitionsCbv.
Import RuntimeDefinitions.
Declare Reduction cbv_no_rt
:= cbv -[Let_In
runtime_nth_default
runtime_add
runtime_sub
runtime_mul
runtime_opp
runtime_div
runtime_modulo
RT_Z.add_get_carry_full
RT_Z.add_with_get_carry_full
RT_Z.mul_split].
Declare Reduction lazy_no_rt
:= lazy -[Let_In
runtime_nth_default
runtime_add
runtime_sub
runtime_mul
runtime_opp
runtime_div
runtime_modulo
RT_Z.add_get_carry_full
RT_Z.add_with_get_carry_full
RT_Z.mul_split].
Declare Reduction pattern_rt
:= pattern Let_In,
runtime_nth_default,
runtime_add,
runtime_sub,
runtime_mul,
runtime_opp,
runtime_div,
runtime_modulo,
RT_Z.add_get_carry_full,
RT_Z.add_with_get_carry_full,
RT_Z.mul_split.
Import RuntimeAxioms.
Declare Reduction pattern_ax_rt
:= pattern (@Let_In),
(@runtime_nth_default),
runtime_add,
runtime_sub,
runtime_mul,
runtime_opp,
runtime_div,
runtime_modulo,
RT_Z.add_get_carry_full,
RT_Z.add_with_get_carry_full,
RT_Z.mul_split.
End RuntimeDefinitionsCbv.
Module RT_Extra (Import RT : Runtime).
Fixpoint dlet_nd_list_pair {A B} (ls : list (A * B)) {T} (f : list (A * B) -> T) : T
:= match ls with
| nil => f nil
| cons x xs
=> dlet_nd x1 := fst x in dlet_nd x2 := snd x in @dlet_nd_list_pair A B xs T (fun xs => f ((x1, x2) :: xs))
end.
Fixpoint dlet_nd_list {A} (ls : list A) {T} (f : list A -> T) : T
:= match ls with
| nil => f nil
| cons x xs
=> dlet_nd x := x in @dlet_nd_list A xs T (fun xs => f (x :: xs))
end.
Fixpoint dlet_nd_list_pair_only_snd {A B} (ls : list (A * B)) {T} (f : list (A * B) -> T) : T
:= match ls with
| nil => f nil
| cons x xs
=> dlet_nd x2 := snd x in @dlet_nd_list_pair_only_snd A B xs T (fun xs => f ((fst x, x2) :: xs))
end.
Notation "'dlet_list_pair_only_snd' x := v 'in' f" := (dlet_nd_list_pair_only_snd v (fun x => f)).
Notation "'dlet_list_pair' x := v 'in' f" := (dlet_nd_list_pair v (fun x => f)).
Notation "'dlet_list' x := v 'in' f" := (dlet_nd_list v (fun x => f)).
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 (runtime_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.
End RT_Extra.
Module Associational (Import RT : Runtime).
Module Import Deps.
Module Export RT_Extra := RT_Extra RT.
End Deps.
Definition eval (p:list (Z*Z)) : Z :=
fold_right (fun x y => x + y) 0%Z (map (fun t => fst t * snd t) p).
Definition mul (p q:list (Z*Z)) : list (Z*Z) :=
flat_map (fun t =>
map (fun t' =>
(fst t * fst t', (snd t * snd t')%RT))
q) p.
Definition square_cps (p:list (Z*Z)) : ~> list (Z*Z) :=
list_rect
_
(return nil)
(fun t ts acc T k
=> (dlet two_t2 := (2 * snd t)%RT in
acc
_
(fun acc
=> k (((fst t * fst t, (snd t * snd t)%RT)
:: (map (fun t'
=> (fst t * fst t', (two_t2 * snd t')%RT))
ts))
++ acc))))
p.
Definition negate_snd (p:list (Z*Z)) : list (Z*Z) :=
map (fun cx => (fst cx, (-snd cx)%RT)) p.
Definition split (s:Z) (p:list (Z*Z)) : list (Z*Z) * list (Z*Z)
:= let hi_lo := partition (fun t => fst t mod s =? 0) p in
(snd hi_lo, map (fun t => (fst t / s, snd t)) (fst hi_lo)).
Definition reduce (s:Z) (c:list _) (p:list _) : list (Z*Z) :=
let lo_hi := split s p in fst lo_hi ++ mul c (snd lo_hi).
(* reduce at most [n] times, stopping early if the high list is nil at any point *)
Definition repeat_reduce (n : nat) (s:Z) (c:list _) (p:list _) : list (Z * Z)
:= nat_rect
_
(fun p => p)
(fun n' repeat_reduce_n' p
=> let lo_hi := split s p in
if (length (snd lo_hi) =? 0)%nat
then p
else let p := fst lo_hi ++ mul c (snd lo_hi) in
repeat_reduce_n' p)
n
p.
(* rough template (we actually have to do things a bit differently to account for duplicate weights):
[ dlet fi_c := c * fi in
let (fj_high, fj_low) := split fj at s/fi.weight in
dlet fi_2 := 2 * fi in
dlet fi_2_c := 2 * fi_c in
(if fi.weight^2 >= s then fi_c * fi else fi * fi)
++ fi_2_c * fj_high
++ fi_2 * fj_low
| fi <- f , fj := (f weight less than i) ]
*)
(** N.B. We take advantage of dead code elimination to allow us to
let-bind partial products that we don't end up using *)
(** [v] -> [(v, v*c, v*c*2, v*2)] *)
Definition let_bind_for_reduce_square_cps (c:list (Z*Z)) (p:list (Z*Z)) : ~> list ((Z*Z) * list(Z*Z) * list(Z*Z) * list(Z*Z)) :=
fun T
=> let two := [(1,2)] (* (weight, value) *) in
map_cps2 (fun t T k => dlet_list_pair_only_snd c_t := mul [t] c in dlet_list_pair_only_snd two_c_t := mul c_t two in dlet_list_pair_only_snd two_t := mul [t] two in k (t, c_t, two_c_t, two_t)) p.
Definition reduce_square_cps (s:Z) (c:list (Z*Z)) (p:list (Z*Z)) : ~>list (Z*Z) :=
(p <- let_bind_for_reduce_square_cps c p;
let div_s := map (fun t => (fst t / s, snd t)) in
return (list_rect
_
nil
(fun t ts acc
=> (let '(t, c_t, two_c_t, two_t) := t in
(if ((fst t * fst t) mod s =? 0)
then div_s (mul [t] c_t)
else mul [t] [t])
++ (flat_map
(fun '(t', c_t', two_c_t', two_t')
=> if ((fst t * fst t') mod s =? 0)
then div_s
(if fst t' <=? fst t
then mul [t'] two_c_t
else mul [t] two_c_t')
else (if fst t' <=? fst t
then mul [t'] two_t
else mul [t] two_t'))
ts))
++ acc)
p)).
Definition bind_snd_cps (p : list (Z*Z)) : ~>list (Z * Z) :=
@dlet_nd_list_pair_only_snd _ _ p.
Section Carries.
Definition carryterm_cps (w fw:Z) (t:Z * Z) : ~> list (Z * Z) :=
fun T k
=> if (Z.eqb (fst t) w)
then dlet_nd t2 := snd t in
dlet_nd d2 := (t2 / fw)%RT in
dlet_nd m2 := (t2 mod fw)%RT in
k [(w * fw, d2);(w,m2)]
else k [t].
Definition carry_cps (w fw:Z) (p:list (Z * Z)) : ~> list (Z * Z):=
fun T => flat_map_cps (carryterm_cps w fw) p.
End Carries.
End Associational.
Module Positional (Import RT : Runtime).
Module Import Deps.
Module Associational := Associational RT.
End Deps.
Section Positional.
Context (weight : nat -> Z).
Definition to_associational (n:nat) (xs:list Z) : list (Z*Z)
:= combine (map weight (List.seq 0 n)) xs.
Definition eval n x := Associational.eval (@to_associational n x).
Definition zeros n : list Z := repeat 0 n.
Definition add_to_nth i x (ls : list Z) : list Z
:= ListUtil.update_nth i (fun y => (x + y)%RT) ls.
Definition place (t:Z*Z) (i:nat) : nat * Z :=
nat_rect
(fun _ => unit -> (nat * Z)%type)
(fun _ => (O, if fst t =? 1 then snd t else (fst t * snd t)%RT))
(fun i' place_i' _
=> let i := S i' in
if (fst t mod weight i =? 0)
then (i, let c := fst t / weight i in if c =? 1 then snd t else (c * snd t)%RT)
else place_i' tt)
i
tt.
Definition from_associational_cps n (p:list (Z*Z)) : ~> list Z :=
fun T => fold_right_cps2 (fun t ls T k =>
let '(p1, p2) := place t (pred n) in
dlet_nd p2 := p2 in
k (add_to_nth p1 p2 ls)) (zeros n) p.
Definition extend_to_length (n_in n_out : nat) (p:list Z) : list Z :=
p ++ zeros (n_out - n_in).
Definition drop_high_to_length (n : nat) (p:list Z) : list Z :=
firstn n p.
Section mulmod.
Context (s:Z)
(c:list (Z*Z)).
Definition mulmod_cps (n:nat) (a b:list Z) : ~> list Z
:= let a_a := to_associational n a in
let b_a := to_associational n b in
let ab_a := Associational.mul a_a b_a in
let abm_a := Associational.repeat_reduce n s c ab_a in
from_associational_cps n abm_a.
Definition squaremod_cps (n:nat) (a:list Z) : ~> list Z
:= (let a_a := to_associational n a in
aa_a <- Associational.reduce_square_cps s c a_a;
let aam_a := Associational.repeat_reduce (pred n) s c aa_a in
from_associational_cps n aam_a).
End mulmod.
Definition add_cps (n:nat) (a b:list Z) : ~> list Z
:= let a_a := to_associational n a in
let b_a := to_associational n b in
from_associational_cps n (a_a ++ b_a).
Section Carries.
Definition carry_cps n m (index:nat) (p:list Z) : ~> list Z :=
(p <- @Associational.carry_cps (weight index)
(weight (S index) / weight index)
(to_associational n p);
from_associational_cps
m p).
Definition carry_reduce_cps n (s:Z) (c:list (Z * Z))
(index:nat) (p : list Z) : ~> list Z :=
(p <- @carry_cps n (S n) index p;
p <- from_associational_cps
n (Associational.reduce
s c (to_associational (S n) p));
return p).
(* N.B. It is important to reverse [idxs] here, because fold_right is
written such that the first terms in the list are actually used
last in the computation. For example, running:
`Eval cbv - [Z.add] in (fun a b c d => fold_right Z.add d [a;b;c]).`
will produce [fun a b c d => (a + (b + (c + d)))].*)
Definition chained_carries_cps n s c p (idxs : list nat) : ~> _ :=
fun T => fold_right_cps2 (fun a b => carry_reduce_cps n s c a b) p (rev idxs).
(* carries without modular reduction; useful for converting between bases *)
Definition chained_carries_no_reduce_cps n p (idxs : list nat) : ~> _ :=
fun T => fold_right_cps2 (fun a b => carry_cps n n a b) p (rev idxs).
(* Reverse of [eval]; translate from Z to basesystem by putting
everything in first digit and then carrying. *)
Definition encode_cps n s c (x : Z) : ~> list Z :=
(p <- from_associational_cps n [(1,x)]; chained_carries_cps n s c p (seq 0 n)).
(* Reverse of [eval]; translate from Z to basesystem by putting
everything in first digit and then carrying, but without reduction. *)
Definition encode_no_reduce_cps n (x : Z) : ~> list Z :=
(p <- from_associational_cps n [(1,x)]; chained_carries_no_reduce_cps n p (seq 0 n)).
End Carries.
Section sub.
Context (n:nat)
(s:Z)
(c:list (Z * Z))
(coef:Z).
Definition negate_snd_cps (a:list Z) : ~> list Z
:= let A := to_associational n a in
let negA := Associational.negate_snd A in
from_associational_cps n negA.
Definition scmul_cps (x:Z) (a:list Z) : ~> list Z
:= let A := to_associational n a in
let R := Associational.mul A [(1, x)] in
from_associational_cps n R.
Definition balance_cps : ~> list Z
:= (sc <- encode_cps n s c (s - Associational.eval c); v <- scmul_cps coef sc; return v).
Definition sub_cps (a b:list Z) : ~> list Z
:= (balance <- balance_cps;
ca <- add_cps n balance a;
_b <- negate_snd_cps b;
camb <- add_cps n ca _b;
return camb).
Definition opp_cps (a:list Z) : ~> list Z
:= sub_cps (zeros n) a.
End sub.
Section select.
Definition zselect_cps (mask cond:Z) (p:list Z) : ~> _ :=
fun T k => dlet t := RT_Z.zselect cond 0 mask in k (List.map (RT_Z.land t) p).
Definition select (cond:Z) (if_zero if_nonzero:list Z) :=
List.map (fun '(p, q) => RT_Z.zselect cond p q) (List.combine if_zero if_nonzero).
End select.
End Positional.
End Positional.
|
Require Import Coq.Arith.Arith.
Require Import Coq.omega.Omega.
Definition even (n: nat) := exists k, n = 2 * k.
Definition odd (n: nat) := exists k, n = 2 * k + 1.
Axiom classic : forall P:Prop, P \/ ~ P.
Theorem easy: forall (p q: Prop),
p -> ((p->q) -> p). (*Question 1*)
Proof.
intro p.
intro q.
intro p_lhs.
firstorder.
Qed.
Theorem Conversion: forall (p q: Prop),
(p -> q) -> (~ p \/ q). (*Question 2*)
Proof.
intros p q.
intros p_implies_q.
destruct (classic p) as [p_true | p_false].
pose (p_implies_q p_true) as l.
right.
exact l.
left.
exact p_false.
Qed.
Theorem NotNotAImpA : forall A: Prop, ~~A -> A. (*Question 3*)
Proof.
intro A.
intro double_neg.
destruct (classic A) as [p_true | p_false].
exact p_true.
contradiction.
Qed.
Theorem PeirceContra: forall (p q:Prop),
~ p -> ~((p -> q) -> p). (*Question 4*)
Proof.
intro p.
intro q.
intro H.
destruct (classic p) as [p_true | p_false].
intro r.
pose(H p_true)as d.
exact d.
intro k.
apply H.
intuition.
Qed.
Theorem Peirce: forall (p q: Prop),
((p -> q) -> p) -> p. (*Question 5*)
Proof.
intro p.
intro q.
intro r.
destruct (classic p) as [p_true | p_false].
exact p_true.
firstorder.
Qed.
|
// Copyright 2019 The Beam Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "local_private_key_keeper.h"
#include "mnemonic/mnemonic.h"
#include "wasm_key_keeper.h"
#include "wallet/core/wallet_db.h"
#include <boost/algorithm/string.hpp>
#include "utility/string_helpers.cpp"
#include "nlohmann/json.hpp"
#include <emscripten/bind.h>
using namespace emscripten;
using namespace beam;
using namespace beam::wallet;
using json = nlohmann::json;
// #define PRINT_TEST_DATA 1
namespace beam
{
char* to_hex(char* dst, const void* bytes, size_t size) {
static const char digits[] = "0123456789abcdef";
char* d = dst;
const uint8_t* ptr = (const uint8_t*)bytes;
const uint8_t* end = ptr + size;
while (ptr < end) {
uint8_t c = *ptr++;
*d++ = digits[c >> 4];
*d++ = digits[c & 0xF];
}
*d = '\0';
return dst;
}
std::string to_hex(const void* bytes, size_t size) {
char* buf = (char*)alloca(2 * size + 1);
return std::string(to_hex(buf, bytes, size));
}
}
struct KeyKeeper
{
KeyKeeper(const std::string& phrase)
: _impl2(CreateKdfFromSeed(phrase))
{
static_assert(sizeof(uint64_t) == sizeof(unsigned long long));
}
std::string GetOwnerKey(const std::string& pass)
{
IPrivateKeyKeeper2::Method::get_Kdf method;
method.m_Root = true;
method.m_iChild = 0;
_impl2.InvokeSync(method);
beam::KeyString ks;
ks.SetPassword(Blob(pass.data(), static_cast<uint32_t>(pass.size())));
ks.m_sMeta = std::to_string(0);
ks.ExportP(*method.m_pPKdf);
return ks.m_sRes;
}
std::string GetWalletID()
{
return _impl2.GetWalletID();
}
std::string GetSbbsAddress(int ownID)
{
return _impl2.GetSbbsAddress(uint64_t(ownID));
}
std::string GetSbbsAddressPrivate(int ownID)
{
return _impl2.GetSbbsAddressPrivate(uint64_t(ownID));
}
std::string get_Kdf(bool root, Key::Index keyIndex)
{
IPrivateKeyKeeper2::Method::get_Kdf method;
method.m_Root = root;
method.m_iChild = keyIndex;
auto status = _impl2.InvokeSync(method);
json res =
{
{JsonFields::Status, status}
};
if (status == IPrivateKeyKeeper2::Status::Success)
{
ByteBuffer buf(sizeof(ECC::HKdfPub::Packed), 0);
method.m_pPKdf->ExportP(&buf[0]);
res.push_back({ JsonFields::PublicKdf, to_base64(buf) });
}
return res.dump();
}
std::string get_NumSlots()
{
IPrivateKeyKeeper2::Method::get_NumSlots method;
auto status = _impl2.InvokeSync(method);
json res =
{
{JsonFields::Status, status}
};
if (status == IPrivateKeyKeeper2::Status::Success)
{
res.push_back({ JsonFields::Count, method.m_Count });
}
return res.dump();
}
std::string CreateOutput(const std::string& scheme, const std::string& cid)
{
IPrivateKeyKeeper2::Method::CreateOutput method;
method.m_hScheme = from_base64<Height>(scheme);
method.m_Cid = from_base64<CoinID>(cid);
auto status = _impl2.InvokeSync(method);
json res =
{
{JsonFields::Status, status}
};
if (status == IPrivateKeyKeeper2::Status::Success)
{
res.push_back({ JsonFields::Result, to_base64(method.m_pResult) });
}
return res.dump();
}
std::string SignReceiver(const std::string& inputs
, const std::string& outputs
, const std::string& kernel
, bool nonConventional
, const std::string& peerID
, const std::string& myIDKey)
{
IPrivateKeyKeeper2::Method::SignReceiver method;
method.m_vInputs = from_base64<std::vector<CoinID>>(inputs);
method.m_vOutputs = from_base64<std::vector<CoinID>>(outputs);
method.m_pKernel = from_base64<TxKernelStd::Ptr>(kernel);
method.m_NonConventional = nonConventional;
method.m_Peer = from_base64<PeerID>(peerID);
method.m_MyIDKey = from_base64<WalletIDKey>(myIDKey);
auto status = _impl2.InvokeSync(method);
json res =
{
{JsonFields::Status, status}
};
if (status == IPrivateKeyKeeper2::Status::Success)
{
res.push_back({ JsonFields::PaymentProofSig, to_base64(method.m_PaymentProofSignature) });
FillCommonSignatureResult(res, method);
}
return res.dump();
}
std::string SignSender(const std::string& inputs
, const std::string& outputs
, const std::string& kernel
, bool nonConventional
, const std::string& peerID
, const std::string& myIDKey
, uint32_t slot
, const std::string& userAgreement
, const std::string& myID
, const std::string& paymentProof)
{
IPrivateKeyKeeper2::Method::SignSender method;
method.m_vInputs = from_base64<std::vector<CoinID>>(inputs);
method.m_vOutputs = from_base64<std::vector<CoinID>>(outputs);
method.m_pKernel = from_base64<TxKernelStd::Ptr>(kernel);
method.m_NonConventional = nonConventional;
method.m_Peer = from_base64<PeerID>(peerID);
method.m_MyIDKey = from_base64<WalletIDKey>(myIDKey);
method.m_Slot = slot;
method.m_UserAgreement = from_base64<ECC::Hash::Value>(userAgreement);
method.m_MyID = from_base64<PeerID>(myID);
method.m_PaymentProofSignature = from_base64<ECC::Signature>(paymentProof);
bool zeroAgreement = method.m_UserAgreement == Zero;
auto status = _impl2.InvokeSync(method);
json res =
{
{JsonFields::Status, status}
};
if (status == IPrivateKeyKeeper2::Status::Success)
{
if (zeroAgreement)
{
res.push_back({ JsonFields::UserAgreement, to_base64(method.m_UserAgreement) });
res.push_back({ JsonFields::Commitment, to_base64(method.m_pKernel->m_Commitment) });
res.push_back({ JsonFields::PublicNonce, to_base64(method.m_pKernel->m_Signature.m_NoncePub) });
}
else
{
FillCommonSignatureResult(res, method);
}
}
return res.dump();
}
std::string SignSplit(const std::string& inputs
, const std::string& outputs
, const std::string& kernel
, bool nonConventional)
{
IPrivateKeyKeeper2::Method::SignSplit method;
method.m_vInputs = from_base64<std::vector<CoinID>>(inputs);
method.m_vOutputs = from_base64<std::vector<CoinID>>(outputs);
method.m_pKernel = from_base64<TxKernelStd::Ptr>(kernel);
method.m_NonConventional = nonConventional;
auto status = _impl2.InvokeSync(method);
json res =
{
{JsonFields::Status, status}
};
if (status == IPrivateKeyKeeper2::Status::Success)
{
FillCommonSignatureResult(res, method);
}
return res.dump();
}
void FillCommonSignatureResult(json& res, const IPrivateKeyKeeper2::Method::TxCommon& method)
{
res.push_back({ JsonFields::Offset, to_base64(ECC::Scalar(method.m_kOffset)) });
res.push_back({ JsonFields::Kernel, to_base64(method.m_pKernel) });
}
static std::string GeneratePhrase()
{
return boost::join(createMnemonic(getEntropy(), language::en), " ");
}
static bool IsAllowedWord(const std::string& word)
{
return isAllowedWord(word, language::en);
}
static bool IsValidPhrase(const std::string& words)
{
return isValidMnemonic(string_helpers::split(words, ' '), language::en);
}
// TODO: move to common place
static ECC::Key::IKdf::Ptr CreateKdfFromSeed(const std::string& phrase)
{
if (!IsValidPhrase(phrase))
throw "Invalid seed phrase";
Key::IKdf::Ptr kdf;
ECC::NoLeak<ECC::uintBig> seed;
auto buf = beam::decodeMnemonic(string_helpers::split(phrase, ' '));
ECC::Hash::Processor() << beam::Blob(buf.data(), (uint32_t)buf.size()) >> seed.V;
ECC::HKdf::Create(kdf, seed.V);
return kdf;
}
private:
struct MyKeeKeeper
: public LocalPrivateKeyKeeperStd
{
using LocalPrivateKeyKeeperStd::LocalPrivateKeyKeeperStd;
bool IsTrustless() override { return true; }
std::string GetWalletID() const
{
Key::ID kid(Zero);
kid.m_Type = ECC::Key::Type::WalletID;
ECC::Scalar::Native sk;
m_pKdf->DeriveKey(sk, kid);
PeerID pid;
pid.FromSk(sk);
return pid.str();
}
std::string GetSbbsAddress(uint64_t ownID)
{
WalletID walletID;
get_SbbsWalletID(walletID, ownID);
return std::to_string(walletID);
}
std::string GetSbbsAddressPrivate(uint64_t ownID)
{
ECC::Scalar::Native sk;
WalletID walletID;
get_SbbsWalletID(sk, walletID, ownID);
return ECC::Scalar(sk).m_Value.str();
}
Key::IKdf::Ptr CreateSbbsKdf()
{
IPrivateKeyKeeper2::Method::get_Kdf m;
// trustless mode. create SBBS Kdf from a child PKdf. It won't be directly accessible from the owner key
m.m_Root = false;
m.m_iChild = Key::Index(-1); // definitely won't collude with a coin child Kdf (for coins high byte is reserved for scheme)
InvokeSync(m);
ECC::Scalar::Native sk;
m.m_pPKdf->DerivePKey(sk, Zero);
ECC::NoLeak<ECC::Scalar> s;
s.V = sk;
Key::IKdf::Ptr kdf;
ECC::HKdf::Create(kdf, s.V.m_Value);
return kdf;
}
// copied from wallet_db.cpp
// TODO move to common place
Key::IKdf::Ptr get_SbbsKdf()// const
{
if (!m_pKdfSbbs)
{
m_pKdfSbbs = CreateSbbsKdf();
}
return m_pKdfSbbs;
}
void get_SbbsPeerID(ECC::Scalar::Native& sk, PeerID& pid, uint64_t ownID)
{
Key::IKdf::Ptr pKdfSbbs = get_SbbsKdf();
// if (!pKdfSbbs)
// throw CannotGenerateSecretException();
ECC::Hash::Value hv;
Key::ID(ownID, Key::Type::Bbs).get_Hash(hv);
pKdfSbbs->DeriveKey(sk, hv);
pid.FromSk(sk);
}
void get_SbbsWalletID(ECC::Scalar::Native& sk, WalletID& wid, uint64_t ownID)
{
get_SbbsPeerID(sk, wid.m_Pk, ownID);
// derive the channel from the address
BbsChannel ch;
wid.m_Pk.ExportWord<0>(ch);
ch %= proto::Bbs::s_MaxWalletChannels;
wid.m_Channel = ch;
}
void get_SbbsWalletID(WalletID& wid, uint64_t ownID)
{
ECC::Scalar::Native sk;
get_SbbsWalletID(sk, wid, ownID);
}
//void get_Identity(PeerID& pid, uint64_t ownID)// const
//{
// ECC::Hash::Value hv;
// Key::ID(ownID, Key::Type::WalletID).get_Hash(hv);
// ECC::Point::Native pt;
// get_OwnerKdf()->DerivePKeyG(pt, hv);
// pid = ECC::Point(pt).m_X;
//}
/*mutable*/ ECC::Key::IKdf::Ptr m_pKdfSbbs;
};
MyKeeKeeper _impl2;
};
// Binding code
EMSCRIPTEN_BINDINGS()
{
class_<KeyKeeper>("KeyKeeper")
.constructor<const std::string&>()
.function("getOwnerKey", &KeyKeeper::GetOwnerKey)
.function("getWalletID", &KeyKeeper::GetWalletID)
.function("getSbbsAddress", &KeyKeeper::GetSbbsAddress)
.function("getSbbsAddressPrivate", &KeyKeeper::GetSbbsAddressPrivate)
#define THE_MACRO(method) \
.function(#method, &KeyKeeper::method)\
KEY_KEEPER_METHODS(THE_MACRO)
#undef THE_MACRO
.class_function("GeneratePhrase", &KeyKeeper::GeneratePhrase)
.class_function("IsAllowedWord", &KeyKeeper::IsAllowedWord)
.class_function("IsValidPhrase", &KeyKeeper::IsValidPhrase)
// .function("func", &KeyKeeper::func)
// .property("prop", &KeyKeeper::getProp, &KeyKeeper::setProp)
// .class_function("StaticFunc", &KeyKeeper::StaticFunc)
;
}
|
<a href="https://colab.research.google.com/github/kalz2q/mycolabnotebooks/blob/master/chainer15chaineradvanced.ipynb" target="_parent"></a>
# Chainer の応用
[前章](https://tutorials.chainer.org/ja/src/14_Basics_of_Chainer.html#Chainerによる訓練)で説明した Chainer を用いてネットワークを訓練するまでに必要なステップは、以下の 5 つでした。
- Step 1:データセットの準備
- Step 2:ネットワークを決める
- Step 3:目的関数を決める
- Step 4:最適化手法を選択する
- Step 5:ネットワークを訓練する
本章では、これらの各ステップに対して Chainer の機能を活用した工夫を加え、結果を改善する方法を解説します。
## Step 1 : データセットの準備(応用編)
[前章](https://tutorials.chainer.org/ja/src/14_Basics_of_Chainer.html#Step-1-:-データセットの準備)で用いた Iris データセットは、ndarray のままスライスを用いてミニバッチに分割し、ネットワークに入力したり、誤差の計算に用いたりしていました。
ここでは、Chainer が提供するいくつかのデータセットを扱うためのクラスを用いて同様のことを行ってみます。
まずはデータセットを scikit-learn を用いて取得しておきます。
```python
from sklearn.datasets import load_iris
x, t = load_iris(return_X_y=True)
x = x.astype('float32')
t = t.astype('int32')
```
### TupleDataset
Chainer は `chainer.datasets` モジュール以下に色々なデータセットに対して用いられる便利なクラスが用意されています。
その一つが `TupleDataset` で、これは上で取得したような入力値を並べた配列と目標値を並べた配列を与えると、1 つ 1 つを取り出して対応するペアを作って返してくれるものです。
```python
from chainer.datasets import TupleDataset
dataset = TupleDataset(x, t)
```
Chainer が提供する汎用のデータセットクラスは、ndarray をデータセットとして扱う場合と同様にして使えるよう、`[]` を使ったインデックスによる各データ(入力値と目標値のペタ)へのアクセスを可能としています。
それでは、1 つ目の入力値と目標値のペアを取り出してみます。
```python
dataset[0]
```
(array([5.1, 3.5, 1.4, 0.2], dtype=float32), 0)
入力値と目標値を 1 つずつ持つタプルが返されました。
それでは、2 つのデータを取り出してみます。
```python
dataset[:2]
```
[(array([5.1, 3.5, 1.4, 0.2], dtype=float32), 0),
(array([4.9, 3. , 1.4, 0.2], dtype=float32), 0)]
`(入力値, 目標値)` というタプルを 2 つ持つリストが返されました。
このように、Python のリストで用いることができるスライスと同様の表記を Chainer のデータセットオブジェクトに対して用いることができます。
例えば、先頭から 1 つおきに 5 つのデータを取り出したい場合、
```python
dataset[:10:2]
```
[(array([5.1, 3.5, 1.4, 0.2], dtype=float32), 0),
(array([4.7, 3.2, 1.3, 0.2], dtype=float32), 0),
(array([5. , 3.6, 1.4, 0.2], dtype=float32), 0),
(array([4.6, 3.4, 1.4, 0.3], dtype=float32), 0),
(array([4.4, 2.9, 1.4, 0.2], dtype=float32), 0)]
のような記述が可能です。
### データセットの分割
データセットを訓練用・検証用・テスト用に分割するのに便利な関数が Chainer にも用意されています。
これを用いて先程読み込んだ Iris データセットを 3 つに分割してみます。
```python
from chainer.datasets import split_dataset_random
train_val, test = split_dataset_random(dataset, int(len(dataset) * 0.7), seed=0)
train, valid = split_dataset_random(train_val, int(len(train_val) * 0.7), seed=0)
```
`dataset` の中のデータのうち 70% を `train_val` に、残りを `test` にランダムに振り分け、さらに `train_val` のうち 70% を `train` に、残りを `valid` にランダムに振り分けています。
### SerialIterator
[前章](https://tutorials.chainer.org/ja/src/14_Basics_of_Chainer.html#訓練の実行)では、訓練データセットの順番を毎エポックシャッフルする方法として `np.random.permutation()` 関数が用いられていましたが、Chainer ではこのようなネットワークの訓練に際してよく行われるデータセットへの操作を抽象化したイテレータ(iterator)が提供されています。
イテレータは、データセットオブジェクトを与えると、順番のシャッフルやバッチサイズ個だけデータをまとめて返すなどの操作を自動的に行なってくれるものです。
Python のイテレータと似たインターフェースを持ち、`next()` メソッドで順番にミニバッチを返してくれ、1 エポックが終了したら自動的にデータの順番をシャッフルしなおしてくれる便利なものです。
ここでは最もシンプルなイテレータである `SerialIterator` を紹介します。
```python
from chainer.iterators import SerialIterator
train_iter = SerialIterator(train, batch_size=4, repeat=True, shuffle=True)
minibatch = train_iter.next()
minibatch
```
[(array([5.7, 3. , 4.2, 1.2], dtype=float32), 1),
(array([6.4, 3.1, 5.5, 1.8], dtype=float32), 2),
(array([4.8, 3. , 1.4, 0.3], dtype=float32), 0),
(array([6. , 2.2, 5. , 1.5], dtype=float32), 2)]
上のコードは、Iris データセットを分割して作成した訓練用データセット `train` を渡して作成した `SerialIterator` から、最初のミニバッチを取り出す例です。
インスタンス化の際に引数として `batchsize=4` を指定しているため、返ってきたミニバッチには 4 つのデータが格納されていることが分かります。
`repeat` 引数には、`next()` を繰り返し実行してデータセット内の全てのデータを取り出し終えたあとに、次の `next()` の呼び出しに対してまたデータセットの先頭からデータを取り出して次のミニバッチを返すかどうかを指定します。
1 エポック以上訓練を行う場合は訓練データセット内のデータを複数回用いるので、これを `True` にします。
`shuffle` 引数には、データセット内のデータの順番をエポックごとに自動的にシャッフルするかどうかを指定します。
## Step 2 : ネットワークを決める(応用編)
[前章](https://tutorials.chainer.org/ja/src/14_Basics_of_Chainer.html#Step-2-:-ネットワークを決める)ではネットワークを `Sequential` クラスを用いて定義しました。
ここでは `Chain` クラスを継承してネットワークを定義する方法を説明します。
### Chain
リンクを複数まとめてチェイン(`Chain` クラス)というまとまりを作ることが出来ます。
`Chain` クラスは `Link` クラスを継承しており、[前章](https://tutorials.chainer.org/ja/src/14_Basics_of_Chainer.html#Step-2-:-ネットワークを決める)で解説したリンクと同様に扱うことができます。
ただし、内部に複数のリンクを保持しておくことができ、呼び出されたときに実行される巡伝播計算を `forward()` メソッドに記述しておくことで、複数のリンクやファンクションを組み合わせた独自の層を作るのに使うことができます。
また、ネットワークの部分構造を記述したり、それ自体で 1 つのネットワークの定義とすることもできます。
それでは、[前章](https://tutorials.chainer.org/ja/src/14_Basics_of_Chainer.html#Sequentialによるネットワーク定義)で定義した `L.Linear` 層を 3 つ持つネットワークと同じものを `Chain` クラスを継承した `Net` というクラスを作って定義してみましょう。
```python
import chainer
import chainer.links as L
import chainer.functions as F
class Net(chainer.Chain):
def __init__(self, n_in=4, n_hidden=3, n_out=3):
super().__init__()
with self.init_scope():
self.l1 = L.Linear(n_in, n_hidden)
self.l2 = L.Linear(n_hidden, n_hidden)
self.l3 = L.Linear(n_hidden, n_out)
def forward(self, x):
h = F.relu(self.l1(x))
h = F.relu(self.l2(h))
h = self.l3(h)
return h
net = Net()
```
この `Net` クラスは 3 層の全結合型ニューラルネットワークを表しています。
`__init__()` メソッドでは、`init_scope()` によって作られるコンテキストの中で `L.Linear` 層 を 3 つ作成し、それぞれ別々の名前の属性に代入しています。
このコンテキストの中で属性に代入されたリンクが持つパラメータは、オプティマイザによるパラメータ更新の対象として登録されます。
このコンテキストの外でリンクを作成し属性に代入を行っても、そのリンクが持つパラメータはオプティマイザによるパラメータ更新の対象にならないため、注意が必要です。
`init_scope()` コンテキストの中で定義されている `L.Linear` クラスのインスタンス化の際には `n_in`、`n_hidden`、`n_out` などの `Net` クラスの `__init__()` メソッドがとる引数が使われています。
こうすることで `Net` クラスをインスタンス化する際に内部の `L.Linear` 層のパラメータ数などを変更することができます。
例えば、`self.l1` の出力ノード数を 100 にするには、以下のようにします。
```python
net = Net(n_hidden=100)
```
このように、`Chain` を継承したクラスを用いてネットワークを定義すると、インスタンス化の際に各層の出力ノード数などを変更することができ、より柔軟性とコードの再利用性が高まります。
## Step 3 : 目的関数を決める(応用編)
[前章](https://tutorials.chainer.org/ja/src/14_Basics_of_Chainer.html#Step-3-:-目的関数を決める)では、分類問題を解くために `F.softmax_cross_entorpy` という目的関数を使用しました。
これはネットワークの出力を ${\bf y}$ とおくと、以下のような式で表される計算を行っています。
$$
\begin{align}
\hat{\bf y} &= {\rm softmax}({\bf y}) \\
L(\boldsymbol\Theta) &= \sum_{k=1}^K \hat{y}_k \log t_k
\end{align}
$$
ただし、$\hat{y}_k, t_k$ はそれぞれ $\hat{\bf y}$ の $k$ 番目の要素と、1-hotベクトル表現されたクラスラベルを表す目的変数 ${\bf t}$ の $k$ 番目の要素をそれぞれ表しています。
また、$\boldsymbol\Theta$ はネットワークが持つ全パラメータを指します。
ここで、この目的関数に**正則化項 (regularization term)** を追加してみましょう。
**正則化 (regularization)** とは、過学習を防ぐために、目的関数に新たな項を追加して、モデルの複雑さに罰則を科したり、パラメータのノルムの大きさに罰則をかけたりすることを指します。
そのために目的関数に追加される項が正則化項です。
ここでは、**重み減衰 (weight decay)** と呼ばれる正則化を適用してみましょう。
これは、**L2正則化 (L2 regularization)** とも呼ばれます。
重み減衰を行う場合、最適化する目的関数は以下になります。
$$
L(\boldsymbol\Theta) + \lambda \frac{1}{2} \sum_w || w ||^2
$$
ここで、$w$ はネットワークのパラメータを指し、上式の第 2 項は全てのパラメータの値を二乗したものの総和を取り、2 で割るという計算を意味します。
この項を目的関数に加えると、ネットワークの重みの絶対値が大きくなりすぎないようにする効果があり、過学習を防ぐために役立ちます。
$\lambda$ は正則化の強さをコントロールします。
新しい目的関数を用いる場合のパラメータの更新式は一般に以下となります。
$$
w \leftarrow w - \eta \left( \frac{\partial L(\boldsymbol\Theta)}{\partial w} + \lambda w \right)
$$
ここで、$\eta$ は学習率を表します。
この式から、パラメータ更新の際にパラメータ自身の更新前の値に $\lambda$ を乗じたものを更新量に加えればよいということが分かります。
重み減衰はバイアスの更新式には通常適用しないことに注意してください([注釈1](#note1))。
Chainer は、パラメータを更新する際に更新計算をカスタマイズする方法を 2 種類提供しています。
1 つは、ネットワークが持つパラメータ全てに対して一様に、更新時にある処理を行いたい場合に使える、オプティマイザフック(optimizer hook)という機能です。
これは、`Optimizer` オブジェクトの `add_hook()` メソッドに更新時に全パラメータに対して行いたい処理を記述した関数を渡して使用します。
もう 1 つは、パラメータごとに別々に処理を行いたい場合に使える方法で、ネットワークのパラメータが持っている `UpdateRule` というオブジェクトにフック関数を追加します。
全ての訓練可能なパラメータは、`Optimizer` オブジェクトの `setup()` メソッドに渡された際に `update_rule` という属性に `UpdateRule` オブジェクトがセットされます。
この `UpdateRule` オブジェクトは、最適化手法によって異なる更新ルールが記述されたもので、`add_hook()` メソッドを持ち、ここにオプティマイザフックまたは任意の関数を追加することができます。
これを用いると、更新時にパラメータごとに別の関数を読んで更新計算をカスタマイズすることができます。
重み減衰は、前述のようにバイアスには適用しないため、今回は `UpdateRule` に対してフック関数を追加します。
Chainer では、`chainer.optimizer_hooks` モジュール以下に数種類の正則化手法が定義されており、重み減衰は `WeightDecay` というクラスとして定義されています。それでは、これを用いて[前章](https://tutorials.chainer.org/ja/src/14_Basics_of_Chainer.html#Step-4-:-最適化手法を選択する)と同様に最適化手法として SGD を採用しつつ、新たに重み減衰を適用するような オプティマイザを定義しましょう。
```python
from chainer import optimizers
from chainer.optimizer_hooks import WeightDecay
optimizer = optimizers.SGD(lr=0.001) # 学習率を 0.01 に設定
optimizer.setup(net)
for param in net.params():
if param.name != 'b': # バイアス以外だったら
param.update_rule.add_hook(WeightDecay(0.0001)) # 重み減衰を適用
```
ネットワークの持つパラメータは、`Chain` クラスの `params()` メソッドを使って取得することができます。
また、`L.Linear` クラスの中でバイアスは `b` という名前で定義されているため、各パラメータの名前をチェックして `b` という名前**でない**場合にだけ `WeightDecay` を `UpdateRule` にフック関数として追加しています。
`WeightDecay` クラスはインスタンス化時に引数を 1 つとり、前述の $\lambda$ に対応する係数を指定することができます。
ここでは、`0.0001` を指定しています。
## Step 4 : 最適化手法を選択する(応用編)
[前章](https://tutorials.chainer.org/ja/src/14_Basics_of_Chainer.html#Step-4-:-最適化手法を選択する)では、Chainer が提供している最もシンプルな最適化手法の一つである SGD を用いていました。
Chainer は SGD の他にも多くの最適化手法を提供しています。
ここでは、その中でも代表的な手法の一つである MomentumSGD という手法を用いるように変更を加えてみましょう。
MomentumSGD は SGD の改良版で、パラメータ更新の際に**前回の勾配**を使って更新方向がスムーズになるように工夫するもので、更新式は以下になります。
$$
\Delta w_t = \frac{\partial L(\boldsymbol\Theta)}{\partial w^{(t)}} \\
w \leftarrow w - \eta \Delta w_{t} + \mu \Delta w_{t - 1}
$$
ここで、$t$ 回目の更新で用いられた勾配を $\Delta w_t$ とおいています。
また、$\mu$ は前回の勾配に掛ける係数で、多くの場合 $0.9$ 程度が用いられます。
これを前節で解説した重み減衰と合わせて用いると、更新式は以下のようになります。
$$
w \leftarrow w - \eta \Delta w_{t} + \mu \Delta w_{t - 1} - \eta \lambda w
$$
それでは、MomentumSGD に加えて重み減衰を用いるオプティマイザを定義してみましょう。
```python
from chainer import optimizers
from chainer.optimizer_hooks import WeightDecay
optimizer = optimizers.MomentumSGD(lr=0.001, momentum=0.9)
optimizer.setup(net)
for param in net.params():
if param.name != 'b': # バイアス以外だったら
param.update_rule.add_hook(WeightDecay(0.0001)) # 重み減衰を適用
```
## Step 5 : ネットワークを訓練する(応用編)
最後に、ネットワークの訓練を高速化するために GPU を用いる方法を紹介します。
Iris データセットはデータ数が少なく、各データの次元数も小さい上に、[前章](https://tutorials.chainer.org/ja/src/14_Basics_of_Chainer.html#Sequentialによるネットワーク定義)では訓練したニューラルネットワークのパラメータ数も多くありませんでした。
そのため、CPU を使ってもそこまで長く待たされることなく訓練が終了しました。
しかし、より大きなデータセットを使い、より多くの層を持つニューラルネットワークを訓練しようとすると、CPU だけでは膨大な時間がかかってしまいます。
そこで、GPU を使って計算を高速化する必要が出てきます。
まず、GPU が使える環境であることを確認しましょう。
こちらを参考に GPU を有効にしてください。参考:[GPU を使用する](https://tutorials.chainer.org/ja/src/01_Welcome_to_Chainer_Tutorial.html#GPU-%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%99%E3%82%8B)
また、一台のマシンに複数の GPU を挿して用いる場合もあるため、GPU を用いる際はデバイス ID というものを意識する必要がありますが、Google Colaboratory では利用できる GPU が 1 枚だけなので、このデバイス ID としては基本的に 0 を指定すれば良いことになります。
GPU を利用したい場合、ネットワークの訓練を開始する前に気をつけることは主に以下の 2 つです。
- ネットワークを `to_gpu()` を用いて GPU メモリ上に転送しておく
- ネットワークに入力するデータを CuPy の ndarray に変換しておく
それでは、訓練ループを GPU を使用する形に変更してみましょう。
```python
gpu_id = 0 # 使用する GPU 番号
n_batch = 64 # バッチサイズ
n_epoch = 50 # エポック数
# ネットワークを GPU メモリ上に転送
net.to_gpu(gpu_id)
# ログ
results_train, results_valid = {}, {}
results_train['loss'], results_train['accuracy'] = [], []
results_valid['loss'], results_valid['accuracy'] = [], []
train_iter.reset() # 上で一度 next() が呼ばれているため
count = 1
for epoch in range(n_epoch):
while True:
# ミニバッチの取得
train_batch = train_iter.next()
# x と t に分割
# データを GPU に転送するために、concat_examples に gpu_id を渡す
x_train, t_train = chainer.dataset.concat_examples(train_batch, gpu_id)
# 予測値と目的関数の計算
y_train = net(x_train)
loss_train = F.softmax_cross_entropy(y_train, t_train)
acc_train = F.accuracy(y_train, t_train)
# 勾配の初期化と勾配の計算
net.cleargrads()
loss_train.backward()
# パラメータの更新
optimizer.update()
# カウントアップ
count += 1
# 1エポック終えたら、valid データで評価する
if train_iter.is_new_epoch:
# 検証用データに対する結果の確認
with chainer.using_config('train', False), chainer.using_config('enable_backprop', False):
x_valid, t_valid = chainer.dataset.concat_examples(valid, gpu_id)
y_valid = net(x_valid)
loss_valid = F.softmax_cross_entropy(y_valid, t_valid)
acc_valid = F.accuracy(y_valid, t_valid)
# 注意:GPU で計算した結果はGPU上に存在するため、CPU上に転送します
loss_train.to_cpu()
loss_valid.to_cpu()
acc_train.to_cpu()
acc_valid.to_cpu()
# 結果の表示
print('epoch: {}, iteration: {}, loss (train): {:.4f}, loss (valid): {:.4f}'
'acc (train): {:.4f}, acc (valid): {:.4f}'.format(
epoch, count, loss_train.array.mean(), loss_valid.array.mean(),
acc_train.array.mean(), acc_valid.array.mean()))
# 可視化用に保存
results_train['loss'] .append(loss_train.array)
results_train['accuracy'] .append(acc_train.array)
results_valid['loss'].append(loss_valid.array)
results_valid['accuracy'].append(acc_valid.array)
break
```
epoch: 0, iteration: 20, loss (train): 0.5593, loss (valid): 1.1641acc (train): 0.7500, acc (valid): 0.2812
epoch: 1, iteration: 38, loss (train): 0.5643, loss (valid): 0.6651acc (train): 0.7500, acc (valid): 0.6562
epoch: 2, iteration: 56, loss (train): 0.6048, loss (valid): 0.4401acc (train): 0.5000, acc (valid): 0.9375
epoch: 3, iteration: 74, loss (train): 0.4558, loss (valid): 0.3911acc (train): 1.0000, acc (valid): 0.9062
epoch: 4, iteration: 93, loss (train): 0.5761, loss (valid): 0.3446acc (train): 0.7500, acc (valid): 0.9375
epoch: 5, iteration: 111, loss (train): 0.3042, loss (valid): 0.3256acc (train): 0.7500, acc (valid): 0.9062
epoch: 6, iteration: 129, loss (train): 0.5116, loss (valid): 0.2832acc (train): 0.7500, acc (valid): 0.9688
epoch: 7, iteration: 147, loss (train): 0.2061, loss (valid): 0.2661acc (train): 1.0000, acc (valid): 0.9688
epoch: 8, iteration: 166, loss (train): 0.2615, loss (valid): 0.2774acc (train): 1.0000, acc (valid): 0.9062
epoch: 9, iteration: 184, loss (train): 0.1087, loss (valid): 0.2717acc (train): 1.0000, acc (valid): 0.9062
epoch: 10, iteration: 202, loss (train): 0.4066, loss (valid): 0.2312acc (train): 0.7500, acc (valid): 0.9062
epoch: 11, iteration: 220, loss (train): 0.3363, loss (valid): 0.2006acc (train): 1.0000, acc (valid): 0.9688
epoch: 12, iteration: 239, loss (train): 0.0416, loss (valid): 0.1949acc (train): 1.0000, acc (valid): 0.9688
epoch: 13, iteration: 257, loss (train): 0.2825, loss (valid): 0.1808acc (train): 1.0000, acc (valid): 0.9688
epoch: 14, iteration: 275, loss (train): 0.1560, loss (valid): 0.1756acc (train): 1.0000, acc (valid): 0.9688
epoch: 15, iteration: 293, loss (train): 0.1390, loss (valid): 0.1652acc (train): 1.0000, acc (valid): 0.9688
epoch: 16, iteration: 312, loss (train): 0.1830, loss (valid): 0.1681acc (train): 1.0000, acc (valid): 0.9688
epoch: 17, iteration: 330, loss (train): 0.2390, loss (valid): 0.2024acc (train): 0.7500, acc (valid): 0.9375
epoch: 18, iteration: 348, loss (train): 0.3004, loss (valid): 0.2069acc (train): 0.7500, acc (valid): 0.9375
epoch: 19, iteration: 366, loss (train): 0.2484, loss (valid): 0.2422acc (train): 1.0000, acc (valid): 0.9062
epoch: 20, iteration: 385, loss (train): 0.1464, loss (valid): 0.1604acc (train): 1.0000, acc (valid): 0.9688
epoch: 21, iteration: 403, loss (train): 0.0658, loss (valid): 0.1955acc (train): 1.0000, acc (valid): 0.9375
epoch: 22, iteration: 421, loss (train): 0.0356, loss (valid): 0.1353acc (train): 1.0000, acc (valid): 0.9688
epoch: 23, iteration: 439, loss (train): 0.0311, loss (valid): 0.1364acc (train): 1.0000, acc (valid): 0.9688
epoch: 24, iteration: 458, loss (train): 0.1637, loss (valid): 0.2239acc (train): 1.0000, acc (valid): 0.9375
epoch: 25, iteration: 476, loss (train): 0.2006, loss (valid): 0.1916acc (train): 0.7500, acc (valid): 0.9375
epoch: 26, iteration: 494, loss (train): 0.0653, loss (valid): 0.1236acc (train): 1.0000, acc (valid): 0.9688
epoch: 27, iteration: 512, loss (train): 0.0439, loss (valid): 0.1450acc (train): 1.0000, acc (valid): 0.9688
epoch: 28, iteration: 531, loss (train): 0.1530, loss (valid): 0.1344acc (train): 1.0000, acc (valid): 0.9688
epoch: 29, iteration: 549, loss (train): 0.0254, loss (valid): 0.1868acc (train): 1.0000, acc (valid): 0.9375
epoch: 30, iteration: 567, loss (train): 0.0116, loss (valid): 0.1161acc (train): 1.0000, acc (valid): 0.9688
epoch: 31, iteration: 585, loss (train): 0.4323, loss (valid): 0.1480acc (train): 0.7500, acc (valid): 0.9688
epoch: 32, iteration: 604, loss (train): 0.1224, loss (valid): 0.1690acc (train): 1.0000, acc (valid): 0.9375
epoch: 33, iteration: 622, loss (train): 0.0210, loss (valid): 0.1609acc (train): 1.0000, acc (valid): 0.9688
epoch: 34, iteration: 640, loss (train): 0.1189, loss (valid): 0.1293acc (train): 1.0000, acc (valid): 0.9688
epoch: 35, iteration: 658, loss (train): 0.0847, loss (valid): 0.2146acc (train): 1.0000, acc (valid): 0.9375
epoch: 36, iteration: 677, loss (train): 0.0386, loss (valid): 0.1923acc (train): 1.0000, acc (valid): 0.9375
epoch: 37, iteration: 695, loss (train): 0.0031, loss (valid): 0.1275acc (train): 1.0000, acc (valid): 0.9688
epoch: 38, iteration: 713, loss (train): 0.0507, loss (valid): 0.1597acc (train): 1.0000, acc (valid): 0.9688
epoch: 39, iteration: 731, loss (train): 0.4128, loss (valid): 0.1880acc (train): 0.7500, acc (valid): 0.9375
epoch: 40, iteration: 750, loss (train): 0.1969, loss (valid): 0.2146acc (train): 0.7500, acc (valid): 0.9375
epoch: 41, iteration: 768, loss (train): 0.2036, loss (valid): 0.1166acc (train): 0.7500, acc (valid): 0.9688
epoch: 42, iteration: 786, loss (train): 0.0283, loss (valid): 0.1864acc (train): 1.0000, acc (valid): 0.9375
epoch: 43, iteration: 804, loss (train): 0.1069, loss (valid): 0.1909acc (train): 1.0000, acc (valid): 0.9375
epoch: 44, iteration: 823, loss (train): 0.7707, loss (valid): 0.5453acc (train): 0.7500, acc (valid): 0.8125
epoch: 45, iteration: 841, loss (train): 1.0361, loss (valid): 0.2338acc (train): 0.5000, acc (valid): 0.9375
epoch: 46, iteration: 859, loss (train): 0.0143, loss (valid): 0.1414acc (train): 1.0000, acc (valid): 0.9688
epoch: 47, iteration: 877, loss (train): 0.0228, loss (valid): 0.1150acc (train): 1.0000, acc (valid): 0.9688
epoch: 48, iteration: 896, loss (train): 0.0280, loss (valid): 0.1984acc (train): 1.0000, acc (valid): 0.9375
epoch: 49, iteration: 914, loss (train): 0.0225, loss (valid): 0.4470acc (train): 1.0000, acc (valid): 0.8438
GPU を用いて訓練することができました。
[前章](https://tutorials.chainer.org/ja/src/14_Basics_of_Chainer.html#訓練の実行)で CPU を用いて訓練を行ったとき同様に、損失と精度が訓練が進むにつれてどのように変化していったかを確認してみましょう。
```python
import matplotlib.pyplot as plt
# 損失 (loss)
plt.plot(results_train['loss'], label='train') # label で凡例の設定
plt.plot(results_valid['loss'], label='valid') # label で凡例の設定
plt.legend() # 凡例の表示
plt.show()
# 精度 (accuracy)
plt.plot(results_train['accuracy'], label='train') # label で凡例の設定
plt.plot(results_valid['accuracy'], label='valid') # label で凡例の設定
plt.legend() # 凡例の表示
plt.show()
```
テストデータに対する評価も行ってみましょう。
```python
# テストデータに対する損失と精度を計算
x_test, t_test = chainer.dataset.concat_examples(test, device=gpu_id)
with chainer.using_config('train', False), chainer.using_config('enable_backprop', False):
y_test = net(x_test)
loss_test = F.softmax_cross_entropy(y_test, t_test)
acc_test = F.accuracy(y_test, t_test)
print('test loss: {:.4f}'.format(loss_test.array.get()))
print('test accuracy: {:.4f}'.format(acc_test.array.get()))
```
test loss: 0.3595
test accuracy: 0.8889
### GPU を用いて訓練したネットワークの保存
訓練に GPU を用いた場合は、`save_npz()` 関数を使ったネットワーク重みの保存の際に、まずネットワークのパラメータを CPU メモリ上に転送することを忘れないでください。
```python
from chainer.serializers import save_npz
net.to_cpu()
save_npz('net.npz', net)
```
正常に保存できているかどうか、読み込んで確認してみます。
```python
import numpy as np
params = np.load('net.npz')
for key, param in params.items():
print(key, ':\t', param.shape)
```
l2/W : (100, 100)
l2/b : (100,)
l3/W : (3, 100)
l3/b : (3,)
l1/W : (100, 4)
l1/b : (100,)
<hr />
<div class="alert alert-info">
**注釈 1**
重み減衰をバイアスに適用することは、大抵最終的なネットワークの訓練結果に小さな違いしかもたらしません。(参考:[Backpropagation Algorithm](http://deeplearning.stanford.edu/wiki/index.php/Backpropagation_Algorithm))
[▲上へ戻る](#ref_note1)
</div>
|
Formal statement is: lemma closed_nonpos_Reals_complex [simp]: "closed (\<real>\<^sub>\<le>\<^sub>0 :: complex set)" Informal statement is: The set of complex numbers with non-positive real part is closed. |
# import cv2
import os,glob
import os
import sys
import tensorflow as tf
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import seaborn as sn
from mrcnn import utils
from mrcnn import visualize
from mrcnn.visualize import display_images
import mrcnn.model as modellib
from mrcnn.model import log
# Root directory of the project
ROOT_DIR = os.path.abspath("../")
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
cwd = os.getcwd()
print(cwd)
print(ROOT_DIR)
modelFile = "mask_rcnn_ship_0499.h5"
current_dir = "./test"
modelfile_list = modelFile.split("_")
dirs = os.listdir(current_dir)
mainFolder ="./Test_Sonuçları/"
# os.mkdir(mainFolder)
mapScoresFile = "mapScores.csv"
confMatrixFile = "confMatrixCounts"
confMatrixNormalizedFile= "confMatrixNormalized"
confMatrixImageFileNorm = mainFolder +"confMatrixImageNorm.png"
confMatrixImageFile = mainFolder+ "confMatrixImage.png"
import ShipClassification
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
config = ShipClassification.ShipClassificationConfig()
# Override the training configurations with a few
# changes for inferencing.
class InferenceConfig(config.__class__):
# Run detection on one image at a time
GPU_COUNT = 1
IMAGES_PER_GPU = 1
DETECTION_MIN_CONFIDENCE =0.3
NUM_CLASSES = 1 + 12
BACKBONE ="resnet101"
config = InferenceConfig()
config.display()
# Device to load the neural network on.
# Useful if you're training a model on the same
# machine, in which case use CPU and leave the
# GPU for training.
DEVICE = "/gpu:0" # /cpu:0 or /gpu:0
# Inspect the model in training or inference modes
# values: 'inference' or 'training'
# TODO: code for 'training' test mode not ready yet
TEST_MODE = "inference"
def get_ax(rows=1, cols=1, size=16):
"""Return a Matplotlib Axes array to be used in
all visualizations in the notebook. Provide a
central point to control graph sizes.
Adjust the size attribute to control how big to render images
"""
_, ax = plt.subplots(rows, cols, figsize=(size * cols, size * rows))
return ax
# Create model in inference mode
print(MODEL_DIR)
with tf.device(DEVICE):
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR,
config=config)
import numpy as np
import skimage.draw
classNames = {}
classNames[1] = "Balıkçı"
classNames[2] = "Askeri Tip-1"
classNames[3] = "Askeri Tip-2"
classNames[4] = "Askeri Tip-3"
classNames[5] = "Tanker"
classNames[6] = "Destek_Gemisi"
classNames[7] = "Askeri Tip-4"
classNames[8] = "Askeri Tip-5"
classNames[9] = "Askeri Tip-6"
classNames[10] = "Askeri Tip-7"
classNames[11] = "Konteyner"
classNames[12] = "Askeri Tip-8"
def get_colors_for_class_ids(class_ids):
colors = []
for class_id in class_ids:
if (class_id == 1):
colors.append((.904, .204, .204))
elif (class_id == 2):
colors.append((.164, .196, .0))
elif (class_id == 3):
colors.append((.250, .104, .0))
elif (class_id == 4):
colors.append((.122, .59, .63))
elif (class_id == 5):
colors.append((.229, .20, .0))
elif (class_id == 6):
colors.append((.27, .61, .226))
elif (class_id == 7):
colors.append((.0, .0, .0))
elif (class_id == 8):
colors.append((.130, .90, .44))
elif (class_id == 9):
colors.append((.229, .20, .0))
elif (class_id == 10):
colors.append((.0, .71, .169))
elif (class_id == 11):
colors.append((.96, .169, .23))
elif (class_id == 12):
colors.append((.0, .71, .169))
return colors
WEIGHTS_PATH = modelFile # TODO: update this path
weights_path = WEIGHTS_PATH
# Load weights
print("Loading weights ", weights_path)
with tf.device(DEVICE):
model.load_weights(weights_path, by_name=True)
listOfValues=[]
"""
Klasörler ve isimler yazılıyor.
"""
labels = {}
classes =[]
f = open("labels.txt", "r")
index=0
for x in f:
labels.update({x.replace("\n",""):index})
index=index+1
classes.append(x.replace("\n",""))
def plot_confusion_matrix(frmt,title,filename,cm, classes,
normalize=False,
cmap=plt.cm.Blues):
plt.figure(figsize=(10, 10),dpi=500)
sn.set(font_scale=1)
cm_df_decisionRatesWOConfMetrics = pd.DataFrame(cm, index=classes, columns=classes)
p = sn.heatmap(cm_df_decisionRatesWOConfMetrics, annot=True, cmap='Blues', annot_kws={"size":10}, linewidths=0.01, cbar=False, fmt=frmt)
p.set_xticklabels(p.get_xticklabels(),rotation=45,va="top", ha="right")
# plt.text(12, -0.8, title, fontsize=10, color='Black', fontstyle='italic', va="bottom", ha="center")
plt.tight_layout()
plt.savefig(filename)
return plt
conf_matrix = np.zeros((12,12))
def add_To_Conf_Matrix(result,classNo):
if (len(result)>0):
valueOfPredict = r['class_ids'][0]
conf_matrix[classNo-1][valueOfPredict-1] = conf_matrix[classNo-1][valueOfPredict-1] +1
returnVal= True
else:
returnVal= False
return returnVal
totalFile= 0
totalLoss =0
for folderName in range (1,13):
tempdir =current_dir+"/"+str(folderName)
dir_len = len([f for f in glob.glob(tempdir + "**/*.jpg", recursive=True)])
for pathAndFilename in glob.iglob(os.path.join(tempdir, "*.jpg")):
title, ext = os.path.splitext(os.path.basename(pathAndFilename))
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
image = skimage.io.imread(pathAndFilename)
results = model.detect([image]) # , verbose=1)
r = results[0]
visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'],
classNames, r['scores'],
colors=get_colors_for_class_ids(r['class_ids']), ax=fig.axes[-1])
print("Sınıflar: ", r['class_ids'], " Scores:", r['scores'])
# plt.show()
plt.savefig(current_dir+"/Sonuç_resimler/"+str(folderName)+"/"+title+".png")
# print(result)
returnValue = add_To_Conf_Matrix(r['class_ids'],folderName)
if (returnValue==True):
totalFile=totalFile +1
else:
totalLoss = totalLoss +1
#Confusion matrix normalize ediliyor.
row_sums = conf_matrix.sum(axis=1)
conf_matrix_normed = (conf_matrix / row_sums[:, np.newaxis]) *100
#Accuracy Computing
sumsTotal = conf_matrix.sum(axis=0)
for i in range(0,12):
temp_dict={}
temp_TP = (conf_matrix[i][i])
temp_FP = (sumsTotal[i]-temp_TP)
temp_Precision = temp_TP/(temp_FP+temp_TP)
# temp_dict.update({"ClassLabel":classes[i]})
temp_dict.update({'TP':temp_TP})
temp_dict.update({'FP':temp_FP})
temp_dict.update({'mAP':temp_Precision})
listOfValues.append(temp_dict)
sumOfPR = 0
index = 0;
np.save(mainFolder+confMatrixFile,conf_matrix,True,True)
np.save(mainFolder+confMatrixNormalizedFile,conf_matrix_normed,True,True)
########################### Avg mAp hesaplanıp yazılıyor###############3333333
import math
for i in range(0, len(listOfValues)):
if (math.isnan(listOfValues[i]['mAP'])):
continue
else:
sumOfPR = sumOfPR + listOfValues[i]['mAP']
index= index +1
dictAvgMap={}
mAP = sumOfPR /index
dictAvgMap.update({"avgMap":mAP})
listOfValues.append(dictAvgMap)
############################ değerler dosyaya yazılıyor #############3
import pandas as pd
df = pd.DataFrame(listOfValues)
print(df)
df.to_csv(mainFolder+mapScoresFile)
##################3 confusion matrix çizdiriliyor ve kaydediliyor ######################
np.save(mainFolder+confMatrixFile,conf_matrix,True,True)
np.save(mainFolder+confMatrixNormalizedFile,conf_matrix_normed,True,True)
#
plot_confusion_matrix(frmt=".0f",cm=conf_matrix,classes=classes,filename=confMatrixImageFile,title="Total File: "+str(totalFile))
plot_confusion_matrix(frmt='.2f',cm=conf_matrix_normed,classes=classes,filename=confMatrixImageFileNorm,title="Total File: "+str(totalFile) )
print("Prediction Finished...")
os._exit(0)
|
Goal forall A B C (p : forall (x : A) (y : B), C x y) (x : A) (y : B), True.
Proof.
intros A B C p x y.
match type of p with
| forall x y, @?F x y => pose F as C1
end.
match type of p with
| forall x y, @?F y x => pose F as C2
end.
assert (C1 x y) as ?.
assert (C2 y x) as ?.
Abort.
Goal forall A B C D (p : forall (x : A) (y : B) (z : C), D x y) (x : A) (y : B), True.
Proof.
intros A B C D p x y.
match type of p with
| forall x y z, @?F x y => pose F as C1
end.
assert (C1 x y) as ?.
Abort.
Goal forall A B C D (p : forall (z : C) (x : A) (y : B), D x y) (x : A) (y : B), True.
Proof.
intros A B C D p x y.
match type of p with
| forall z x y, @?F x y => pose F as C1
end.
assert (C1 x y) as ?.
Abort.
(** Those should fail *)
Goal forall A B C (p : forall (x : A) (y : B), C x y) (x : A) (y : B), True.
Proof.
intros A B C p x y.
Fail match type of p with
| forall x, @?F x y => pose F as C1
end.
Fail match type of p with
| forall x y, @?F x x y => pose F as C1
end.
Fail match type of p with
| forall x y, @?F x => pose F as C1
end.
Abort.
(** This one is badly typed *)
Goal forall A (B : A -> Type) (C : forall x, B x -> Type), (forall x y, C x y) -> True.
Proof.
intros A B C p.
Fail match type of p with
| forall x y, @?F y x => idtac
end.
Abort.
Goal forall A (B : A -> Type) (C : Type) (D : forall x, B x -> Type), (forall x (z : C) y, D x y) -> True.
Proof.
intros A B C D p.
match type of p with
| forall x z y, @?F x y => idtac
end.
Abort.
|
/-
Copyright (c) 2021 Ashvni Narayanan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ashvni Narayanan
-/
import number_theory.bernoulli_polynomials
import dirichlet_character.basic
import general_bernoulli_number.bernoulli_polynomial_mul
/-!
# General Bernoulli Numbers
This file defines the generalized Bernoulli numbers related to Dirichlet characters
and gives its properties.
## Main definitions
* `general_bernoulli_number`
## Implementation notes
TODO (optional)
## References
Introduction to Cyclotomic Fields, Washington (Chapter 12, Section 2)
## Tags
p-adic, L-function, Bernoulli measure, Dirichlet character
-/
variables {S : Type*} [comm_semiring S] [algebra ℚ S] {n : ℕ} (ψ : dirichlet_character S n)
open dirichlet_character
open_locale big_operators
/-- The generalized Bernoulli number
`B_{m, ψ} = f^{m - 1} * ∑_{a = 0}^{f - 1} ψ(a) * B_m(a+1/f)`,
where `f` is the conductor of the Dirichlet character `ψ`. -/
noncomputable def general_bernoulli_number (m : ℕ) : S :=
(algebra_map ℚ S ((ψ.conductor)^(m - 1 : ℤ))) * (∑ a in finset.range ψ.conductor,
asso_dirichlet_character (asso_primitive_character ψ) a.succ * algebra_map ℚ S
((polynomial.bernoulli m).eval (a.succ / ψ.conductor : ℚ)))
-- def is ind of F
namespace general_bernoulli_number
lemma general_bernoulli_number_def (m : ℕ) : general_bernoulli_number ψ m =
(algebra_map ℚ S ((ψ.conductor)^(m - 1 : ℤ))) * (∑ a in finset.range ψ.conductor,
asso_dirichlet_character (asso_primitive_character ψ) a.succ *
algebra_map ℚ S ((polynomial.bernoulli m).eval (a.succ / ψ.conductor : ℚ))) := rfl
/-- B_{n,1} = B_n, where 1 is the trivial Dirichlet character of level 1. -/
lemma general_bernoulli_number_one_eval {n : ℕ} :
general_bernoulli_number (1 : dirichlet_character S 1) n = algebra_map ℚ S (bernoulli' n) :=
begin
rw general_bernoulli_number_def, simp_rw [conductor.one nat.one_pos],
simp only [one_pow, one_mul, nat.cast_zero, polynomial.bernoulli_eval_one,
nat.cast_one, div_one, finset.sum_singleton, finset.range_one, monoid_hom.coe_mk],
rw extend_eq_char _ is_unit_one,
rw asso_primitive_character_one nat.one_pos,
convert one_mul _,
{ simp only [one_zpow, ring_hom.map_one], },
{ convert (one_mul _).symm, },
end
lemma general_bernoulli_number_one_eval_one :
general_bernoulli_number (1 : dirichlet_character S 1) 1 = algebra_map ℚ S (1/2 : ℚ) :=
begin
rw general_bernoulli_number_def, simp_rw [conductor.one nat.one_pos],
simp only [one_div, one_pow, one_mul, bernoulli'_one, nat.cast_zero,
polynomial.bernoulli_eval_one, nat.cast_one, div_one, finset.sum_singleton,
finset.range_one, monoid_hom.coe_mk],
rw extend_eq_char _ is_unit_one,
rw asso_primitive_character_one nat.one_pos,
convert one_mul _,
{ simp only [one_zpow, ring_hom.map_one], },
{ convert (one_mul _).symm, },
end
--revise proof using above lemma
/-- `∑_{a = 0}^{m*n - 1} f a = ∑_{i = 0}^{n - 1} (∑_{a = m*i}^{m*(i + 1)} fa)`. -/
lemma finset.sum_range_mul_eq_sum_Ico {m n : ℕ} (f : ℕ → S) :
∑ a in finset.range (m * n), f a =
∑ i in finset.range n, (∑ a in finset.Ico (m * i) (m * i.succ), f a) :=
begin
induction n with d hd,
{ simp only [finset.sum_empty, finset.range_zero, mul_zero], },
{ rw [finset.sum_range_succ, ←hd], rw [finset.range_eq_Ico,
finset.sum_Ico_consecutive _ (nat.zero_le _) (mul_le_mul (le_refl _) (nat.le_succ _)
(nat.zero_le _) (nat.zero_le _))], },
end
/-- Showing that the definition of general_bernoulli_number is independent of F,
where F is a multiple of the conductor. -/
lemma eq_sum_bernoulli_of_conductor_dvd {F : ℕ} [hF : fact (0 < F)] (m : ℕ) (h : ψ.conductor ∣ F) :
general_bernoulli_number ψ m = (algebra_map ℚ S) (F^(m - 1 : ℤ)) *
(∑ a in finset.range F, asso_dirichlet_character ψ.asso_primitive_character a.succ *
algebra_map ℚ S ((polynomial.bernoulli m).eval (a.succ / F : ℚ))) :=
begin
cases h with k h, rw h,
rw finset.sum_range_mul_eq_sum_Ico,
simp_rw [finset.sum_Ico_eq_sum_range],
simp_rw [←nat.mul_sub_left_distrib],
simp_rw [norm_num.sub_nat_pos (nat.succ _) _ 1 rfl],
simp_rw [mul_one],
rw general_bernoulli_number_def,
have hF : F ≠ 0 := ne_of_gt (fact_iff.1 hF),
have hk1 : k ≠ 0,
{ intro h1, apply hF, rw [h, h1, mul_zero], },
have hk2 : (k : ℚ) ≠ 0, { norm_cast, apply hk1, },
conv_lhs { congr, skip, apply_congr, skip,
rw [←mul_div_mul_left _ _ hk2, ←mul_div_assoc', polynomial.bernoulli_eval_mul' _ hk1,
(algebra_map _ _).map_mul, (algebra_map _ _).map_sum, ←mul_assoc,
mul_comm ((asso_dirichlet_character ψ.asso_primitive_character) ↑(x.succ)) _, mul_assoc,
finset.mul_sum], },
rw [←finset.mul_sum, ←mul_assoc],
apply congr_arg2,
{ rw [nat.cast_mul, mul_zpow, ring_hom.map_mul], },
{ rw finset.sum_comm,
apply finset.sum_congr rfl (λ i hi, _),
apply finset.sum_congr rfl (λ j hj, _),
apply congr_arg2,
{ apply congr_arg, rw ←nat.add_succ,
simp only [zero_mul, nat.cast_add, zmod.nat_cast_self, zero_add, nat.cast_mul], },
{ apply congr_arg, congr,
rw ←nat.add_succ, rw nat.cast_add,
rw add_div, rw add_comm, rw mul_comm,
repeat { rw nat.cast_mul, },
rw mul_div_mul_left _ _ _,
norm_cast, intro h1, apply hF, rw [h, h1, zero_mul], }, },
end
end general_bernoulli_number
|
// Copyright (c) 2011 Thomas Heller
// Copyright (c) 2013 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !BOOST_PP_IS_ITERATING
#ifndef HPX_FUNCTION_DETAIL_VTABLE_PTR_BASE_HPP
#define HPX_FUNCTION_DETAIL_VTABLE_PTR_BASE_HPP
#include <hpx/config.hpp>
#include <hpx/util/detail/vtable_ptr_base_fwd.hpp>
#include <hpx/util/add_rvalue_reference.hpp>
#include <hpx/util/polymorphic_factory.hpp>
#include <hpx/util/demangle_helper.hpp>
#include <hpx/util/move.hpp>
#include <boost/detail/sp_typeinfo.hpp>
#include <boost/preprocessor/iteration/iterate.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/assert.hpp>
namespace hpx { namespace util { namespace detail {
/////////////////////////////////////////////////////////////////////////////
template <
typename IArchive
, typename OArchive
>
struct vtable_ptr_virtbase
{
virtual ~vtable_ptr_virtbase() {}
virtual vtable_ptr_virtbase* get_ptr() = 0;
virtual char const* get_function_name() const = 0;
virtual bool empty() const = 0;
virtual void save_object(void *const*, OArchive & ar, unsigned) = 0;
virtual void load_object(void **, IArchive & ar, unsigned) = 0;
};
/////////////////////////////////////////////////////////////////////////////
template <typename Function>
char const* get_function_name()
#ifdef HPX_DISABLE_AUTOMATIC_SERIALIZATION_REGISTRATION
;
#else
{
// If you encounter this assert while compiling code, that means that
// you have a HPX_UTIL_REGISTER_FUNCTION macro somewhere in a
// source file, but the header in which the continuation is defined
// misses a HPX_UTIL_REGISTER_FUNCTION_DECLARATION
BOOST_MPL_ASSERT_MSG(
traits::needs_automatic_registration<Function>::value
, HPX_UTIL_REGISTER_FUNCTION_DECLARATION_MISSING
, (Function)
);
return util::type_id<Function>::typeid_.type_id();
}
#endif
/////////////////////////////////////////////////////////////////////////////
template <typename Function>
struct function_registration
{
typedef
typename Function::vtable_ptr_virtbase_type
vtable_ptr_virtbase_type;
static boost::shared_ptr<vtable_ptr_virtbase_type> create()
{
return boost::shared_ptr<vtable_ptr_virtbase_type>(new Function());
}
function_registration()
{
util::polymorphic_factory<vtable_ptr_virtbase_type>::get_instance().
add_factory_function(
detail::get_function_name<Function>()
, &function_registration::create
);
}
};
template <typename Function, typename Enable =
typename traits::needs_automatic_registration<Function>::type>
struct automatic_function_registration
{
automatic_function_registration()
{
function_registration<Function> auto_register;
}
automatic_function_registration& register_function()
{
return *this;
}
};
template <typename Function>
struct automatic_function_registration<Function, boost::mpl::false_>
{
automatic_function_registration()
{
}
automatic_function_registration& register_function()
{
return *this;
}
};
}}}
namespace boost { namespace serialization {
template <
typename IArchive
, typename OArchive
>
struct tracking_level<hpx::util::detail::vtable_ptr_virtbase<
IArchive, OArchive
> >
: boost::mpl::int_<boost::serialization::track_never>
{};
}}
#define BOOST_UTIL_DETAIL_VTABLE_PTR_BASE_ADD_RVALUE_REF(Z, N, D) \
typename util::add_rvalue_reference<BOOST_PP_CAT(D, N)>::type \
/**/
#if !defined(HPX_USE_PREPROCESSOR_LIMIT_EXPANSION)
# include <hpx/util/detail/preprocessed/vtable_ptr_base.hpp>
#else
#if defined(__WAVE__) && defined(HPX_CREATE_PREPROCESSED_FILES)
# pragma wave option(preserve: 1, line: 0, output: "preprocessed/vtable_ptr_base_" HPX_LIMIT_STR ".hpp")
#endif
#define BOOST_PP_ITERATION_PARAMS_1 \
( \
3 \
, ( \
0 \
, HPX_FUNCTION_ARGUMENT_LIMIT \
, <hpx/util/detail/vtable_ptr_base.hpp> \
) \
) \
/**/
#include BOOST_PP_ITERATE()
#if defined(__WAVE__) && defined (HPX_CREATE_PREPROCESSED_FILES)
# pragma wave option(output: null)
#endif
#endif // !defined(HPX_USE_PREPROCESSOR_LIMIT_EXPANSION)
#undef BOOST_UTIL_DETAIL_VTABLE_PTR_BASE_ADD_RVALUE_REF
#endif
#else
#define N BOOST_PP_ITERATION()
namespace hpx { namespace util { namespace detail {
template <
typename R
BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)
, typename IArchive
, typename OArchive
>
struct vtable_ptr_base<
R(BOOST_PP_ENUM_PARAMS(N, A))
, IArchive
, OArchive
>
: vtable_ptr_virtbase<IArchive, OArchive>
{
virtual ~vtable_ptr_base() {}
std::type_info const& (*get_type)();
void (*static_delete)(void**);
void (*destruct)(void**);
void (*clone)(void * const*, void **);
void (*copy)(void * const*, void **);
R (*invoke)(void **
BOOST_PP_ENUM_TRAILING(N, BOOST_UTIL_DETAIL_VTABLE_PTR_BASE_ADD_RVALUE_REF, A));
};
///////////////////////////////////////////////////////////////////////////
template <
typename R
BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)
>
struct vtable_ptr_base<
R(BOOST_PP_ENUM_PARAMS(N, A))
, void
, void
>
{
virtual ~vtable_ptr_base() {}
virtual bool empty() const = 0;
std::type_info const& (*get_type)();
void (*static_delete)(void**);
void (*destruct)(void**);
void (*clone)(void * const*, void **);
void (*copy)(void * const*, void **);
R (*invoke)(void **
BOOST_PP_ENUM_TRAILING(N, BOOST_UTIL_DETAIL_VTABLE_PTR_BASE_ADD_RVALUE_REF, A));
};
}}}
namespace boost { namespace serialization {
template <
typename R
BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)
, typename IArchive
, typename OArchive
>
struct tracking_level<hpx::util::detail::vtable_ptr_base<
R(BOOST_PP_ENUM_PARAMS(N, A)), IArchive, OArchive
> >
: boost::mpl::int_<boost::serialization::track_never>
{};
}}
#undef N
#endif
|
#include "Arduino.h"
#include <thread>
#include <boost/algorithm/string.hpp>
void ArduinoBoard::Run(){
return Run2();
std::string resp;
while (!stop_thread){
std::chrono::milliseconds dura(120);
writeString("snr1\n");
std::this_thread::sleep_for(dura);
resp = readLineAsync(800).c_str();
sonars.x = atoi(resp.c_str());
//std::cout << "snr0: " << sonars.x << std::endl;
std::this_thread::sleep_for(dura);
writeString("snr2\n");
std::this_thread::sleep_for(dura);
sonars.y = atoi(readLineAsync(800).c_str());
//std::cout << "snr2: " << sonars.y << std::endl;
sonars.z = -1;
std::this_thread::sleep_for(dura);
writeString("strt\n");
std::this_thread::sleep_for(dura);
start = atoi(readLineAsync(800).c_str());
std::this_thread::sleep_for(dura);
writeString("gte\n");
std::this_thread::sleep_for(dura);
gte = atoi(readLineAsync(800).c_str());
std::this_thread::sleep_for(dura);
}
}
void ArduinoBoard::Run2(){
std::string resp;
std::chrono::milliseconds dura(60);
std::vector<std::string> items;
std::vector<std::string> item;
while (!stop_thread){
//writeString("info\n");
//std::this_thread::sleep_for(dura);
//resp = readLineAsync(60).c_str();
resp = readLine().c_str();
//std::cout << "Arduino, resp='"<< resp <<"'"<<std::endl;
//"<start:"+strt+">"+"<gate:"+gate+">"+"<s1:"+distance0+">"+"<s2:"+distance1+">"+"<s3:"+distance2+">"
resp = ">" + resp;
boost::split(items, resp, boost::is_any_of(">"));
for(auto i : items) {
if(i.empty()) continue;
boost::split(item, i, boost::is_any_of(":"));
if (item.size()==2) {
if(item[0] == "<start") {
int res = atoi(item[1].c_str());
// set start off if change from arduino 1 -> 0
if (res == 0 && old_start == 1) {
old_start = 0;
} else if(res == 1) {
start = 1;
old_start = 1;
} else /* 0 && 0*/ {
old_start = 0;
}
}
if(item[0] == "<gate") gte = atoi(item[1].c_str());
if(item[0] == "<s1") sonars.x = atoi(item[1].c_str());
if(item[0] == "<s2") sonars.y = atoi(item[1].c_str());
if(item[0] == "<s3") sonars.z = atoi(item[1].c_str());
} else {
//std::cout << "Arduino, invalid responce item: '" << i << "', " << ", res2p: '" << resp << "'" << std::endl;
}
}
//std::this_thread::sleep_for(dura);
}
}
std::string Arduino::GetDebugInfo(){
std::ostringstream oss;
oss << "[Arduino] left: " << sonars.x;
oss << ", right: " << sonars.z;
oss << ", back " << sonars.y;
oss << ", start " << start << " ("<< old_start <<")";
oss << ", gate " << gte;
return oss.str();
}
|
[STATEMENT]
lemma "(domainNameDeptChopOne^^2) (''d1''--''d2''--''d3''--Leaf) = ''d1''--Leaf"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (domainNameDeptChopOne ^^ 2) (''d1'' -- ''d2'' -- ''d3'' -- Leaf) = ''d1'' -- Leaf
[PROOF STEP]
by eval |
[STATEMENT]
lemma nall_tuples_rec_filter:
assumes "xs \<in> nall_tuples_rec AD n (length xs)" "ys = filter (\<lambda>x. \<not>isl x) xs"
shows "ys \<in> nall_tuples_rec {} n (length ys)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
xs \<in> nall_tuples_rec AD n (length xs)
ys = filter (\<lambda>x. \<not> isl x) xs
goal (1 subgoal):
1. ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
proof (induction xs arbitrary: n ys)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>n ys. \<lbrakk>[] \<in> nall_tuples_rec AD n (length []); ys = filter (\<lambda>x. \<not> isl x) []\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
2. \<And>a xs n ys. \<lbrakk>\<And>n ys. \<lbrakk>xs \<in> nall_tuples_rec AD n (length xs); ys = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys); a # xs \<in> nall_tuples_rec AD n (length (a # xs)); ys = filter (\<lambda>x. \<not> isl x) (a # xs)\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
case (Cons x xs)
[PROOF STATE]
proof (state)
this:
\<lbrakk>xs \<in> nall_tuples_rec AD ?n (length xs); ?ys = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> ?ys \<in> nall_tuples_rec {} ?n (length ?ys)
x # xs \<in> nall_tuples_rec AD n (length (x # xs))
ys = filter (\<lambda>x. \<not> isl x) (x # xs)
goal (2 subgoals):
1. \<And>n ys. \<lbrakk>[] \<in> nall_tuples_rec AD n (length []); ys = filter (\<lambda>x. \<not> isl x) []\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
2. \<And>a xs n ys. \<lbrakk>\<And>n ys. \<lbrakk>xs \<in> nall_tuples_rec AD n (length xs); ys = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys); a # xs \<in> nall_tuples_rec AD n (length (a # xs)); ys = filter (\<lambda>x. \<not> isl x) (a # xs)\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<lbrakk>xs \<in> nall_tuples_rec AD ?n (length xs); ?ys = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> ?ys \<in> nall_tuples_rec {} ?n (length ?ys)
x # xs \<in> nall_tuples_rec AD n (length (x # xs))
ys = filter (\<lambda>x. \<not> isl x) (x # xs)
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>xs \<in> nall_tuples_rec AD ?n (length xs); ?ys = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> ?ys \<in> nall_tuples_rec {} ?n (length ?ys)
x # xs \<in> nall_tuples_rec AD n (length (x # xs))
ys = filter (\<lambda>x. \<not> isl x) (x # xs)
goal (1 subgoal):
1. ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
proof (cases x)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>a. \<lbrakk>\<And>n ys. \<lbrakk>xs \<in> nall_tuples_rec AD n (length xs); ys = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys); x # xs \<in> nall_tuples_rec AD n (length (x # xs)); ys = filter (\<lambda>x. \<not> isl x) (x # xs); x = Inl a\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
2. \<And>b. \<lbrakk>\<And>n ys. \<lbrakk>xs \<in> nall_tuples_rec AD n (length xs); ys = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys); x # xs \<in> nall_tuples_rec AD n (length (x # xs)); ys = filter (\<lambda>x. \<not> isl x) (x # xs); x = Inr b\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
case (Inr b)
[PROOF STATE]
proof (state)
this:
x = Inr b
goal (2 subgoals):
1. \<And>a. \<lbrakk>\<And>n ys. \<lbrakk>xs \<in> nall_tuples_rec AD n (length xs); ys = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys); x # xs \<in> nall_tuples_rec AD n (length (x # xs)); ys = filter (\<lambda>x. \<not> isl x) (x # xs); x = Inl a\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
2. \<And>b. \<lbrakk>\<And>n ys. \<lbrakk>xs \<in> nall_tuples_rec AD n (length xs); ys = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys); x # xs \<in> nall_tuples_rec AD n (length (x # xs)); ys = filter (\<lambda>x. \<not> isl x) (x # xs); x = Inr b\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
have b_le_i: "b \<le> n"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. b \<le> n
[PROOF STEP]
using Cons(2)
[PROOF STATE]
proof (prove)
using this:
x # xs \<in> nall_tuples_rec AD n (length (x # xs))
goal (1 subgoal):
1. b \<le> n
[PROOF STEP]
by (auto simp: Inr)
[PROOF STATE]
proof (state)
this:
b \<le> n
goal (2 subgoals):
1. \<And>a. \<lbrakk>\<And>n ys. \<lbrakk>xs \<in> nall_tuples_rec AD n (length xs); ys = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys); x # xs \<in> nall_tuples_rec AD n (length (x # xs)); ys = filter (\<lambda>x. \<not> isl x) (x # xs); x = Inl a\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
2. \<And>b. \<lbrakk>\<And>n ys. \<lbrakk>xs \<in> nall_tuples_rec AD n (length xs); ys = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys); x # xs \<in> nall_tuples_rec AD n (length (x # xs)); ys = filter (\<lambda>x. \<not> isl x) (x # xs); x = Inr b\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
obtain zs where ys_def: "ys = Inr b # zs" "zs = filter (\<lambda>x. \<not> isl x) xs"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>zs. \<lbrakk>ys = Inr b # zs; zs = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using Cons(3)
[PROOF STATE]
proof (prove)
using this:
ys = filter (\<lambda>x. \<not> isl x) (x # xs)
goal (1 subgoal):
1. (\<And>zs. \<lbrakk>ys = Inr b # zs; zs = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (auto simp: Inr)
[PROOF STATE]
proof (state)
this:
ys = Inr b # zs
zs = filter (\<lambda>x. \<not> isl x) xs
goal (2 subgoals):
1. \<And>a. \<lbrakk>\<And>n ys. \<lbrakk>xs \<in> nall_tuples_rec AD n (length xs); ys = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys); x # xs \<in> nall_tuples_rec AD n (length (x # xs)); ys = filter (\<lambda>x. \<not> isl x) (x # xs); x = Inl a\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
2. \<And>b. \<lbrakk>\<And>n ys. \<lbrakk>xs \<in> nall_tuples_rec AD n (length xs); ys = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys); x # xs \<in> nall_tuples_rec AD n (length (x # xs)); ys = filter (\<lambda>x. \<not> isl x) (x # xs); x = Inr b\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
proof (cases "b < n")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. b < n \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
2. \<not> b < n \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
b < n
goal (2 subgoals):
1. b < n \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
2. \<not> b < n \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
b < n
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
b < n
goal (1 subgoal):
1. ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
using Cons(1)[OF _ ys_def(2), of n] Cons(2)
[PROOF STATE]
proof (prove)
using this:
b < n
xs \<in> nall_tuples_rec AD n (length xs) \<Longrightarrow> zs \<in> nall_tuples_rec {} n (length zs)
x # xs \<in> nall_tuples_rec AD n (length (x # xs))
goal (1 subgoal):
1. ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
by (auto simp: Inr ys_def(1))
[PROOF STATE]
proof (state)
this:
ys \<in> nall_tuples_rec {} n (length ys)
goal (1 subgoal):
1. \<not> b < n \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<not> b < n \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
case False
[PROOF STATE]
proof (state)
this:
\<not> b < n
goal (1 subgoal):
1. \<not> b < n \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<not> b < n
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
\<not> b < n
goal (1 subgoal):
1. ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
using Cons(1)[OF _ ys_def(2), of "Suc n"] Cons(2)
[PROOF STATE]
proof (prove)
using this:
\<not> b < n
xs \<in> nall_tuples_rec AD (Suc n) (length xs) \<Longrightarrow> zs \<in> nall_tuples_rec {} (Suc n) (length zs)
x # xs \<in> nall_tuples_rec AD n (length (x # xs))
goal (1 subgoal):
1. ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
by (auto simp: Inr ys_def(1))
[PROOF STATE]
proof (state)
this:
ys \<in> nall_tuples_rec {} n (length ys)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
ys \<in> nall_tuples_rec {} n (length ys)
goal (1 subgoal):
1. \<And>a. \<lbrakk>\<And>n ys. \<lbrakk>xs \<in> nall_tuples_rec AD n (length xs); ys = filter (\<lambda>x. \<not> isl x) xs\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys); x # xs \<in> nall_tuples_rec AD n (length (x # xs)); ys = filter (\<lambda>x. \<not> isl x) (x # xs); x = Inl a\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
qed auto
[PROOF STATE]
proof (state)
this:
ys \<in> nall_tuples_rec {} n (length ys)
goal (1 subgoal):
1. \<And>n ys. \<lbrakk>[] \<in> nall_tuples_rec AD n (length []); ys = filter (\<lambda>x. \<not> isl x) []\<rbrakk> \<Longrightarrow> ys \<in> nall_tuples_rec {} n (length ys)
[PROOF STEP]
qed auto |
module Structure.Operator.Ring.Rings where
import Lvl
open import Structure.Operator.Ring
open import Structure.Setoid
open import Type
open import Type.Properties.Singleton
private variable ℓ ℓₑ : Lvl.Level
private variable T U : Type{ℓ}
postulate trivialRing : ∀{_+_ _⋅_ : U → U → U} → ⦃ equiv : Equiv{ℓₑ}(U) ⦄ ⦃ singleton : IsUnit(U) ⦄ → Ring(_+_)(_⋅_)
{-Ring.[+]-commutative-group trivialRing = {!!}
Ring.[⋅]-binary-operator trivialRing = {!!}
Ring.[⋅]-associativity trivialRing = {!!}
Ring.[⋅][+]-distributivityₗ trivialRing = {!!}
Ring.[⋅][+]-distributivityᵣ trivialRing = {!!}
-}
|
Stepping into a garden filled with beautiful flowers creates an exciting table setting. Break resistant Melamine Plates by plateshoppe.com.Dishwasher safe. Handmade in the USA.
HAPPY BIRTHDAY, GRAB A SLICE OF CAKE AND JOIN THE FUN.
Have a party using these colorful break resistant Melamine Plates and Platters by plateshoppe.com. Dishwasher safe. Handmade in the USA.
Butterfly Dinner Plate made of break resistant Melamine by plateshoppe.com. Dishwasher safe, Perfect for indoor and outdoor entertaining all year round. Handmade in the USA.
Set a beautiful table with these colorful Melamine Dinner Plates by plateshoppe.com. Dishwasher safe. Handmade in the USA. |
It was this trend that proved to be most in demand at the fashion shows of the end of spring. At the demonstrations of fashion houses Lacoste and Chanel, it was possible to observe new trends. They consist in the fact that the police woman fancy dress hat is simply sewn from the same material as the clothes. For example, a linen dress is combined with a panama of the same color and the same fabric. This move adds elegance to the image of any lady, regardless of the style of the costume.
This year, designers remembered about the trends that a few years ago went into the background. Among them were police woman fancy dress hat, scarves of all kinds of colors and hats-pies. The latter were demonstrated in the collections of Chanel and Mother of Pearl and will surely become favorites this summer. Wide-brimmed hats stylists advised to wear slightly pulled over their eyes, as it was presented in the Giorgio Armani show.
This summer Tommy Hilfiger and Gucci have identified the second important trend of the upcoming season for police woman fancy dress hat. The essence of it in a new approach to the classics. At the recent past, you could see, for example, a classic panama-bucket made in patchwork style, or a French beret, bound from a stiff string.
The police woman fancy dress hat of different colors and styles, lavishly decorated with beads, rhinestones, colored ribbons are another trend this summer. |
[GOAL]
n : ℕ
⊢ ∀ (a : ℕ), a ∈ toFinset (factors n) ↔ (fun p => if Prime p then padicValNat p n else 0) a ≠ 0
[PROOFSTEP]
rcases eq_or_ne n 0 with (rfl | hn0)
[GOAL]
case inl
⊢ ∀ (a : ℕ), a ∈ toFinset (factors 0) ↔ (fun p => if Prime p then padicValNat p 0 else 0) a ≠ 0
[PROOFSTEP]
simp
[GOAL]
case inr
n : ℕ
hn0 : n ≠ 0
⊢ ∀ (a : ℕ), a ∈ toFinset (factors n) ↔ (fun p => if Prime p then padicValNat p n else 0) a ≠ 0
[PROOFSTEP]
simp only [mem_factors hn0, mem_toFinset, Ne.def, ite_eq_right_iff, not_forall, exists_prop, and_congr_right_iff]
[GOAL]
case inr
n : ℕ
hn0 : n ≠ 0
⊢ ∀ (a : ℕ), Prime a → (a ∣ n ↔ ¬padicValNat a n = 0)
[PROOFSTEP]
rintro p hp
[GOAL]
case inr
n : ℕ
hn0 : n ≠ 0
p : ℕ
hp : Prime p
⊢ p ∣ n ↔ ¬padicValNat p n = 0
[PROOFSTEP]
haveI := fact_iff.mpr hp
[GOAL]
case inr
n : ℕ
hn0 : n ≠ 0
p : ℕ
hp : Prime p
this : Fact (Prime p)
⊢ p ∣ n ↔ ¬padicValNat p n = 0
[PROOFSTEP]
exact dvd_iff_padicValNat_ne_zero hn0
[GOAL]
n p : ℕ
pp : Prime p
⊢ ↑(factorization n) p = padicValNat p n
[PROOFSTEP]
simpa [factorization] using absurd pp
[GOAL]
n p : ℕ
⊢ count p (factors n) = ↑(factorization n) p
[PROOFSTEP]
rcases n.eq_zero_or_pos with (rfl | hn0)
[GOAL]
case inl
p : ℕ
⊢ count p (factors 0) = ↑(factorization 0) p
[PROOFSTEP]
simp [factorization, count]
[GOAL]
case inr
n p : ℕ
hn0 : n > 0
⊢ count p (factors n) = ↑(factorization n) p
[PROOFSTEP]
by_cases pp : p.Prime
[GOAL]
case pos
n p : ℕ
hn0 : n > 0
pp : Prime p
⊢ count p (factors n) = ↑(factorization n) p
case neg n p : ℕ hn0 : n > 0 pp : ¬Prime p ⊢ count p (factors n) = ↑(factorization n) p
[PROOFSTEP]
case neg =>
rw [count_eq_zero_of_not_mem (mt prime_of_mem_factors pp)]
simp [factorization, pp]
[GOAL]
n p : ℕ
hn0 : n > 0
pp : ¬Prime p
⊢ count p (factors n) = ↑(factorization n) p
[PROOFSTEP]
case neg =>
rw [count_eq_zero_of_not_mem (mt prime_of_mem_factors pp)]
simp [factorization, pp]
[GOAL]
n p : ℕ
hn0 : n > 0
pp : ¬Prime p
⊢ count p (factors n) = ↑(factorization n) p
[PROOFSTEP]
rw [count_eq_zero_of_not_mem (mt prime_of_mem_factors pp)]
[GOAL]
n p : ℕ
hn0 : n > 0
pp : ¬Prime p
⊢ 0 = ↑(factorization n) p
[PROOFSTEP]
simp [factorization, pp]
[GOAL]
case pos
n p : ℕ
hn0 : n > 0
pp : Prime p
⊢ count p (factors n) = ↑(factorization n) p
[PROOFSTEP]
simp only [factorization, coe_mk, pp, if_true]
[GOAL]
case pos
n p : ℕ
hn0 : n > 0
pp : Prime p
⊢ count p (factors n) = padicValNat p n
[PROOFSTEP]
rw [← PartENat.natCast_inj, padicValNat_def' pp.ne_one hn0,
UniqueFactorizationMonoid.multiplicity_eq_count_normalizedFactors pp hn0.ne']
[GOAL]
case pos
n p : ℕ
hn0 : n > 0
pp : Prime p
⊢ ↑(count p (factors n)) = ↑(Multiset.count (↑normalize p) (UniqueFactorizationMonoid.normalizedFactors n))
[PROOFSTEP]
simp [factors_eq]
[GOAL]
n : ℕ
⊢ factorization n = ↑Multiset.toFinsupp ↑(factors n)
[PROOFSTEP]
ext p
[GOAL]
case h
n p : ℕ
⊢ ↑(factorization n) p = ↑(↑Multiset.toFinsupp ↑(factors n)) p
[PROOFSTEP]
simp
[GOAL]
n p : ℕ
pp : Prime p
hn : n ≠ 0
⊢ multiplicity p n = ↑(↑(factorization n) p)
[PROOFSTEP]
simp [factorization, pp, padicValNat_def' pp.ne_one hn.bot_lt]
[GOAL]
n : ℕ
hn : n ≠ 0
⊢ (Finsupp.prod (factorization n) fun x x_1 => x ^ x_1) = n
[PROOFSTEP]
rw [factorization_eq_factors_multiset n]
[GOAL]
n : ℕ
hn : n ≠ 0
⊢ (Finsupp.prod (↑Multiset.toFinsupp ↑(factors n)) fun x x_1 => x ^ x_1) = n
[PROOFSTEP]
simp only [← prod_toMultiset, factorization, Multiset.coe_prod, Multiset.toFinsupp_toMultiset]
[GOAL]
n : ℕ
hn : n ≠ 0
⊢ List.prod (factors n) = n
[PROOFSTEP]
exact prod_factors hn
[GOAL]
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
h : ∀ (p : ℕ), ↑(factorization a) p = ↑(factorization b) p
⊢ factors a ~ factors b
[PROOFSTEP]
simpa only [List.perm_iff_count, factors_count_eq] using h
[GOAL]
a : ℕ
ha : a ∈ {x | x ≠ 0}
b : ℕ
hb : b ∈ {x | x ≠ 0}
h : factorization a = factorization b
p : ℕ
⊢ ↑(factorization a) p = ↑(factorization b) p
[PROOFSTEP]
simp [h]
[GOAL]
⊢ factorization 0 = 0
[PROOFSTEP]
simp [factorization]
[GOAL]
⊢ factorization 1 = 0
[PROOFSTEP]
simp [factorization]
[GOAL]
n : ℕ
⊢ (factorization n).support = toFinset (factors n)
[PROOFSTEP]
simp [factorization]
[GOAL]
n p : ℕ
⊢ p ∈ (factorization n).support ↔ p ∈ factors n
[PROOFSTEP]
simp only [support_factorization, List.mem_toFinset]
[GOAL]
n p : ℕ
⊢ ↑(factorization n) p = 0 ↔ ¬Prime p ∨ ¬p ∣ n ∨ n = 0
[PROOFSTEP]
rw [← not_mem_support_iff, support_factorization, mem_toFinset]
[GOAL]
n p : ℕ
⊢ ¬p ∈ factors n ↔ ¬Prime p ∨ ¬p ∣ n ∨ n = 0
[PROOFSTEP]
rcases eq_or_ne n 0 with (rfl | hn)
[GOAL]
case inl
p : ℕ
⊢ ¬p ∈ factors 0 ↔ ¬Prime p ∨ ¬p ∣ 0 ∨ 0 = 0
[PROOFSTEP]
simp
[GOAL]
case inr
n p : ℕ
hn : n ≠ 0
⊢ ¬p ∈ factors n ↔ ¬Prime p ∨ ¬p ∣ n ∨ n = 0
[PROOFSTEP]
simp [hn, Nat.mem_factors, not_and_or, -not_and]
[GOAL]
n p : ℕ
hp : ¬Prime p
⊢ ↑(factorization n) p = 0
[PROOFSTEP]
simp [factorization_eq_zero_iff, hp]
[GOAL]
n p : ℕ
h : ¬p ∣ n
⊢ ↑(factorization n) p = 0
[PROOFSTEP]
simp [factorization_eq_zero_iff, h]
[GOAL]
n p : ℕ
hp : Prime p
hn : n ≠ 0
h : p ∣ n
⊢ 0 < ↑(factorization n) p
[PROOFSTEP]
rwa [← factors_count_eq, count_pos, mem_factors_iff_dvd hn hp]
[GOAL]
p r i : ℕ
hr : ¬p ∣ r
⊢ ↑(factorization (p * i + r)) p = 0
[PROOFSTEP]
apply factorization_eq_zero_of_not_dvd
[GOAL]
case h
p r i : ℕ
hr : ¬p ∣ r
⊢ ¬p ∣ p * i + r
[PROOFSTEP]
rwa [← Nat.dvd_add_iff_right (Dvd.intro i rfl)]
[GOAL]
p r i : ℕ
pp : Prime p
hr0 : r ≠ 0
⊢ ¬p ∣ r ↔ ↑(factorization (p * i + r)) p = 0
[PROOFSTEP]
refine' ⟨factorization_eq_zero_of_remainder i, fun h => _⟩
[GOAL]
p r i : ℕ
pp : Prime p
hr0 : r ≠ 0
h : ↑(factorization (p * i + r)) p = 0
⊢ ¬p ∣ r
[PROOFSTEP]
rw [factorization_eq_zero_iff] at h
[GOAL]
p r i : ℕ
pp : Prime p
hr0 : r ≠ 0
h : ¬Prime p ∨ ¬p ∣ p * i + r ∨ p * i + r = 0
⊢ ¬p ∣ r
[PROOFSTEP]
contrapose! h
[GOAL]
p r i : ℕ
pp : Prime p
hr0 : r ≠ 0
h : p ∣ r
⊢ Prime p ∧ p ∣ p * i + r ∧ p * i + r ≠ 0
[PROOFSTEP]
refine' ⟨pp, _, _⟩
[GOAL]
case refine'_1
p r i : ℕ
pp : Prime p
hr0 : r ≠ 0
h : p ∣ r
⊢ p ∣ p * i + r
[PROOFSTEP]
rwa [← Nat.dvd_add_iff_right (dvd_mul_right p i)]
[GOAL]
case refine'_2
p r i : ℕ
pp : Prime p
hr0 : r ≠ 0
h : p ∣ r
⊢ p * i + r ≠ 0
[PROOFSTEP]
contrapose! hr0
[GOAL]
case refine'_2
p r i : ℕ
pp : Prime p
h : p ∣ r
hr0 : p * i + r = 0
⊢ r = 0
[PROOFSTEP]
exact (add_eq_zero_iff.mp hr0).2
[GOAL]
n : ℕ
⊢ factorization n = 0 ↔ n = 0 ∨ n = 1
[PROOFSTEP]
rw [factorization_eq_factors_multiset n]
[GOAL]
n : ℕ
⊢ ↑Multiset.toFinsupp ↑(factors n) = 0 ↔ n = 0 ∨ n = 1
[PROOFSTEP]
simp [factorization, AddEquiv.map_eq_zero_iff, Multiset.coe_eq_zero]
[GOAL]
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
⊢ factorization (a * b) = factorization a + factorization b
[PROOFSTEP]
ext p
[GOAL]
case h
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
p : ℕ
⊢ ↑(factorization (a * b)) p = ↑(factorization a + factorization b) p
[PROOFSTEP]
simp only [add_apply, ← factors_count_eq, perm_iff_count.mp (perm_factors_mul ha hb) p, count_append]
[GOAL]
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
⊢ (factorization (a * b)).support = (factorization a).support ∪ (factorization b).support
[PROOFSTEP]
ext q
[GOAL]
case a
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
q : ℕ
⊢ q ∈ (factorization (a * b)).support ↔ q ∈ (factorization a).support ∪ (factorization b).support
[PROOFSTEP]
simp only [Finset.mem_union, factor_iff_mem_factorization]
[GOAL]
case a
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
q : ℕ
⊢ q ∈ factors (a * b) ↔ q ∈ factors a ∨ q ∈ factors b
[PROOFSTEP]
exact mem_factors_mul ha hb
[GOAL]
n : ℕ
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
⊢ (Finsupp.prod (factorization n) fun p x => f p) = ∏ p in toFinset (factors n), f p
[PROOFSTEP]
apply prod_congr support_factorization
[GOAL]
n : ℕ
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
⊢ ∀ (x : ℕ), x ∈ toFinset (factors n) → (fun p x => f p) x (↑(factorization n) x) = f x
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
S : Finset α
g : α → ℕ
hS : ∀ (x : α), x ∈ S → g x ≠ 0
⊢ factorization (Finset.prod S g) = ∑ x in S, factorization (g x)
[PROOFSTEP]
classical
ext p
refine' Finset.induction_on' S ?_ ?_
· simp
· intro x T hxS hTS hxT IH
have hT : T.prod g ≠ 0 := prod_ne_zero_iff.mpr fun x hx => hS x (hTS hx)
simp [prod_insert hxT, sum_insert hxT, ← IH, factorization_mul (hS x hxS) hT]
[GOAL]
α : Type u_1
S : Finset α
g : α → ℕ
hS : ∀ (x : α), x ∈ S → g x ≠ 0
⊢ factorization (Finset.prod S g) = ∑ x in S, factorization (g x)
[PROOFSTEP]
ext p
[GOAL]
case h
α : Type u_1
S : Finset α
g : α → ℕ
hS : ∀ (x : α), x ∈ S → g x ≠ 0
p : ℕ
⊢ ↑(factorization (Finset.prod S g)) p = ↑(∑ x in S, factorization (g x)) p
[PROOFSTEP]
refine' Finset.induction_on' S ?_ ?_
[GOAL]
case h.refine'_1
α : Type u_1
S : Finset α
g : α → ℕ
hS : ∀ (x : α), x ∈ S → g x ≠ 0
p : ℕ
⊢ ↑(factorization (Finset.prod ∅ g)) p = ↑(∑ x in ∅, factorization (g x)) p
[PROOFSTEP]
simp
[GOAL]
case h.refine'_2
α : Type u_1
S : Finset α
g : α → ℕ
hS : ∀ (x : α), x ∈ S → g x ≠ 0
p : ℕ
⊢ ∀ {a : α} {s : Finset α},
a ∈ S →
s ⊆ S →
¬a ∈ s →
↑(factorization (Finset.prod s g)) p = ↑(∑ x in s, factorization (g x)) p →
↑(factorization (Finset.prod (insert a s) g)) p = ↑(∑ x in insert a s, factorization (g x)) p
[PROOFSTEP]
intro x T hxS hTS hxT IH
[GOAL]
case h.refine'_2
α : Type u_1
S : Finset α
g : α → ℕ
hS : ∀ (x : α), x ∈ S → g x ≠ 0
p : ℕ
x : α
T : Finset α
hxS : x ∈ S
hTS : T ⊆ S
hxT : ¬x ∈ T
IH : ↑(factorization (Finset.prod T g)) p = ↑(∑ x in T, factorization (g x)) p
⊢ ↑(factorization (Finset.prod (insert x T) g)) p = ↑(∑ x in insert x T, factorization (g x)) p
[PROOFSTEP]
have hT : T.prod g ≠ 0 := prod_ne_zero_iff.mpr fun x hx => hS x (hTS hx)
[GOAL]
case h.refine'_2
α : Type u_1
S : Finset α
g : α → ℕ
hS : ∀ (x : α), x ∈ S → g x ≠ 0
p : ℕ
x : α
T : Finset α
hxS : x ∈ S
hTS : T ⊆ S
hxT : ¬x ∈ T
IH : ↑(factorization (Finset.prod T g)) p = ↑(∑ x in T, factorization (g x)) p
hT : Finset.prod T g ≠ 0
⊢ ↑(factorization (Finset.prod (insert x T) g)) p = ↑(∑ x in insert x T, factorization (g x)) p
[PROOFSTEP]
simp [prod_insert hxT, sum_insert hxT, ← IH, factorization_mul (hS x hxS) hT]
[GOAL]
n k : ℕ
⊢ factorization (n ^ k) = k • factorization n
[PROOFSTEP]
induction' k with k ih
[GOAL]
case zero
n : ℕ
⊢ factorization (n ^ zero) = zero • factorization n
[PROOFSTEP]
simp
[GOAL]
case succ
n k : ℕ
ih : factorization (n ^ k) = k • factorization n
⊢ factorization (n ^ succ k) = succ k • factorization n
[PROOFSTEP]
rcases eq_or_ne n 0 with (rfl | hn)
[GOAL]
case succ.inl
k : ℕ
ih : factorization (0 ^ k) = k • factorization 0
⊢ factorization (0 ^ succ k) = succ k • factorization 0
[PROOFSTEP]
simp
[GOAL]
case succ.inr
n k : ℕ
ih : factorization (n ^ k) = k • factorization n
hn : n ≠ 0
⊢ factorization (n ^ succ k) = succ k • factorization n
[PROOFSTEP]
rw [pow_succ, mul_comm, factorization_mul hn (pow_ne_zero _ hn), ih, succ_eq_one_add, add_smul, one_smul]
[GOAL]
p : ℕ
hp : Prime p
⊢ Nat.factorization p = single p 1
[PROOFSTEP]
ext q
[GOAL]
case h
p : ℕ
hp : Prime p
q : ℕ
⊢ ↑(Nat.factorization p) q = ↑(single p 1) q
[PROOFSTEP]
rw [← factors_count_eq, factors_prime hp, single_apply, count_singleton', if_congr eq_comm]
[GOAL]
case h.h_t
p : ℕ
hp : Prime p
q : ℕ
⊢ 1 = 1
[PROOFSTEP]
rfl
[GOAL]
case h.h_e
p : ℕ
hp : Prime p
q : ℕ
⊢ 0 = 0
[PROOFSTEP]
rfl
[GOAL]
p : ℕ
hp : Prime p
⊢ ↑(Nat.factorization p) p = 1
[PROOFSTEP]
simp [hp]
[GOAL]
p k : ℕ
hp : Prime p
⊢ Nat.factorization (p ^ k) = single p k
[PROOFSTEP]
simp [hp]
[GOAL]
n p k : ℕ
hn : n ≠ 0
h : factorization n = single p k
⊢ n = p ^ k
[PROOFSTEP]
rw [← Nat.factorization_prod_pow_eq_self hn, h, Finsupp.prod_single_index]
[GOAL]
n p k : ℕ
hn : n ≠ 0
h : factorization n = single p k
⊢ p ^ 0 = 1
[PROOFSTEP]
simp
[GOAL]
p q : ℕ
hp : Prime p
h : ↑(Nat.factorization p) q ≠ 0
⊢ p = q
[PROOFSTEP]
simpa [hp.factorization, single_apply] using h
[GOAL]
f : ℕ →₀ ℕ
hf : ∀ (p : ℕ), p ∈ f.support → Prime p
⊢ factorization (Finsupp.prod f fun x x_1 => x ^ x_1) = f
[PROOFSTEP]
have h : ∀ x : ℕ, x ∈ f.support → x ^ f x ≠ 0 := fun p hp => pow_ne_zero _ (Prime.ne_zero (hf p hp))
[GOAL]
f : ℕ →₀ ℕ
hf : ∀ (p : ℕ), p ∈ f.support → Prime p
h : ∀ (x : ℕ), x ∈ f.support → x ^ ↑f x ≠ 0
⊢ factorization (Finsupp.prod f fun x x_1 => x ^ x_1) = f
[PROOFSTEP]
simp only [Finsupp.prod, factorization_prod h]
[GOAL]
f : ℕ →₀ ℕ
hf : ∀ (p : ℕ), p ∈ f.support → Prime p
h : ∀ (x : ℕ), x ∈ f.support → x ^ ↑f x ≠ 0
⊢ ∑ x in f.support, factorization (x ^ ↑f x) = f
[PROOFSTEP]
conv =>
rhs
rw [(sum_single f).symm]
[GOAL]
f : ℕ →₀ ℕ
hf : ∀ (p : ℕ), p ∈ f.support → Prime p
h : ∀ (x : ℕ), x ∈ f.support → x ^ ↑f x ≠ 0
| ∑ x in f.support, factorization (x ^ ↑f x) = f
[PROOFSTEP]
rhs
rw [(sum_single f).symm]
[GOAL]
f : ℕ →₀ ℕ
hf : ∀ (p : ℕ), p ∈ f.support → Prime p
h : ∀ (x : ℕ), x ∈ f.support → x ^ ↑f x ≠ 0
| ∑ x in f.support, factorization (x ^ ↑f x) = f
[PROOFSTEP]
rhs
rw [(sum_single f).symm]
[GOAL]
f : ℕ →₀ ℕ
hf : ∀ (p : ℕ), p ∈ f.support → Prime p
h : ∀ (x : ℕ), x ∈ f.support → x ^ ↑f x ≠ 0
| ∑ x in f.support, factorization (x ^ ↑f x) = f
[PROOFSTEP]
rhs
[GOAL]
f : ℕ →₀ ℕ
hf : ∀ (p : ℕ), p ∈ f.support → Prime p
h : ∀ (x : ℕ), x ∈ f.support → x ^ ↑f x ≠ 0
| f
[PROOFSTEP]
rw [(sum_single f).symm]
[GOAL]
f : ℕ →₀ ℕ
hf : ∀ (p : ℕ), p ∈ f.support → Prime p
h : ∀ (x : ℕ), x ∈ f.support → x ^ ↑f x ≠ 0
⊢ ∑ x in f.support, factorization (x ^ ↑f x) = Finsupp.sum f single
[PROOFSTEP]
exact sum_congr rfl fun p hp => Prime.factorization_pow (hf p hp)
[GOAL]
n : ℕ
f : ℕ →₀ ℕ
hn : n ≠ 0
hf : ∀ (p : ℕ), p ∈ f.support → Prime p
h : f = factorization n
⊢ (Finsupp.prod f fun x x_1 => x ^ x_1) = n
[PROOFSTEP]
rw [h, factorization_prod_pow_eq_self hn]
[GOAL]
n : ℕ
f : ℕ →₀ ℕ
hn : n ≠ 0
hf : ∀ (p : ℕ), p ∈ f.support → Prime p
h : (Finsupp.prod f fun x x_1 => x ^ x_1) = n
⊢ f = factorization n
[PROOFSTEP]
rw [← h, prod_pow_factorization_eq_self hf]
[GOAL]
n : ℕ+
⊢ ↑(↑factorizationEquiv n) = factorization ↑n
[PROOFSTEP]
cases n
[GOAL]
case mk
val✝ : ℕ
property✝ : 0 < val✝
⊢ ↑(↑factorizationEquiv { val := val✝, property := property✝ }) = factorization ↑{ val := val✝, property := property✝ }
[PROOFSTEP]
rfl
[GOAL]
n p : ℕ
hp : ¬Prime p
⊢ p ^ ↑(factorization n) p = 1
[PROOFSTEP]
simp [factorization_eq_zero_of_non_prime n hp]
[GOAL]
n p : ℕ
hp : ¬Prime p
⊢ n / p ^ ↑(factorization n) p = n
[PROOFSTEP]
simp [factorization_eq_zero_of_non_prime n hp]
[GOAL]
n p : ℕ
⊢ p ^ ↑(factorization n) p ∣ n
[PROOFSTEP]
by_cases hp : p.Prime
[GOAL]
case pos
n p : ℕ
hp : Prime p
⊢ p ^ ↑(factorization n) p ∣ n
case neg n p : ℕ hp : ¬Prime p ⊢ p ^ ↑(factorization n) p ∣ n
[PROOFSTEP]
case neg => simp [hp]
[GOAL]
n p : ℕ
hp : ¬Prime p
⊢ p ^ ↑(factorization n) p ∣ n
[PROOFSTEP]
case neg => simp [hp]
[GOAL]
n p : ℕ
hp : ¬Prime p
⊢ p ^ ↑(factorization n) p ∣ n
[PROOFSTEP]
simp [hp]
[GOAL]
case pos
n p : ℕ
hp : Prime p
⊢ p ^ ↑(factorization n) p ∣ n
[PROOFSTEP]
rw [← factors_count_eq]
[GOAL]
case pos
n p : ℕ
hp : Prime p
⊢ p ^ count p (factors n) ∣ n
[PROOFSTEP]
apply dvd_of_factors_subperm (pow_ne_zero _ hp.ne_zero)
[GOAL]
case pos
n p : ℕ
hp : Prime p
⊢ factors (p ^ count p (factors n)) <+~ factors n
[PROOFSTEP]
rw [hp.factors_pow, List.subperm_ext_iff]
[GOAL]
case pos
n p : ℕ
hp : Prime p
⊢ ∀ (x : ℕ), x ∈ replicate (count p (factors n)) p → count x (replicate (count p (factors n)) p) ≤ count x (factors n)
[PROOFSTEP]
intro q hq
[GOAL]
case pos
n p : ℕ
hp : Prime p
q : ℕ
hq : q ∈ replicate (count p (factors n)) p
⊢ count q (replicate (count p (factors n)) p) ≤ count q (factors n)
[PROOFSTEP]
simp [List.eq_of_mem_replicate hq]
[GOAL]
n p : ℕ
⊢ 0 < p ^ ↑(factorization n) p
[PROOFSTEP]
by_cases pp : p.Prime
[GOAL]
case pos
n p : ℕ
pp : Prime p
⊢ 0 < p ^ ↑(factorization n) p
[PROOFSTEP]
simp [pow_pos pp.pos]
[GOAL]
case neg
n p : ℕ
pp : ¬Prime p
⊢ 0 < p ^ ↑(factorization n) p
[PROOFSTEP]
simp [pp]
[GOAL]
n p : ℕ
hn : n ≠ 0
⊢ 0 < n / p ^ ↑(factorization n) p
[PROOFSTEP]
cases' em' p.Prime with pp pp
[GOAL]
case inl
n p : ℕ
hn : n ≠ 0
pp : ¬Prime p
⊢ 0 < n / p ^ ↑(factorization n) p
[PROOFSTEP]
simpa [Nat.factorization_eq_zero_of_non_prime n pp] using hn.bot_lt
[GOAL]
case inr
n p : ℕ
hn : n ≠ 0
pp : Prime p
⊢ 0 < n / p ^ ↑(factorization n) p
[PROOFSTEP]
exact Nat.div_pos (ord_proj_le p hn) (ord_proj_pos n p)
[GOAL]
a b p : ℕ
ha : a ≠ 0
hb : b ≠ 0
⊢ p ^ ↑(factorization (a * b)) p = p ^ ↑(factorization a) p * p ^ ↑(factorization b) p
[PROOFSTEP]
simp [factorization_mul ha hb, pow_add]
[GOAL]
a b p : ℕ
⊢ a * b / p ^ ↑(factorization (a * b)) p = a / p ^ ↑(factorization a) p * (b / p ^ ↑(factorization b) p)
[PROOFSTEP]
rcases eq_or_ne a 0 with (rfl | ha)
[GOAL]
case inl
b p : ℕ
⊢ 0 * b / p ^ ↑(factorization (0 * b)) p = 0 / p ^ ↑(factorization 0) p * (b / p ^ ↑(factorization b) p)
[PROOFSTEP]
simp
[GOAL]
case inr
a b p : ℕ
ha : a ≠ 0
⊢ a * b / p ^ ↑(factorization (a * b)) p = a / p ^ ↑(factorization a) p * (b / p ^ ↑(factorization b) p)
[PROOFSTEP]
rcases eq_or_ne b 0 with (rfl | hb)
[GOAL]
case inr.inl
a p : ℕ
ha : a ≠ 0
⊢ a * 0 / p ^ ↑(factorization (a * 0)) p = a / p ^ ↑(factorization a) p * (0 / p ^ ↑(factorization 0) p)
[PROOFSTEP]
simp
[GOAL]
case inr.inr
a b p : ℕ
ha : a ≠ 0
hb : b ≠ 0
⊢ a * b / p ^ ↑(factorization (a * b)) p = a / p ^ ↑(factorization a) p * (b / p ^ ↑(factorization b) p)
[PROOFSTEP]
simp only [ord_proj_mul p ha hb]
[GOAL]
case inr.inr
a b p : ℕ
ha : a ≠ 0
hb : b ≠ 0
⊢ a * b / (p ^ ↑(factorization a) p * p ^ ↑(factorization b) p) =
a / p ^ ↑(factorization a) p * (b / p ^ ↑(factorization b) p)
[PROOFSTEP]
rw [mul_div_mul_comm_of_dvd_dvd (ord_proj_dvd a p) (ord_proj_dvd b p)]
[GOAL]
n p : ℕ
h : p ∈ (factorization n).support
⊢ p ∣ n
[PROOFSTEP]
rcases eq_or_ne n 0 with (rfl | hn)
[GOAL]
case inl
p : ℕ
h : p ∈ (factorization 0).support
⊢ p ∣ 0
[PROOFSTEP]
simp
[GOAL]
case inr
n p : ℕ
h : p ∈ (factorization n).support
hn : n ≠ 0
⊢ p ∣ n
[PROOFSTEP]
simp [← mem_factors_iff_dvd hn (prime_of_mem_factorization h), factor_iff_mem_factorization.mp h]
[GOAL]
n p : ℕ
hn : n ≠ 0
⊢ ↑(factorization n) p < n
[PROOFSTEP]
by_cases pp : p.Prime
[GOAL]
case pos
n p : ℕ
hn : n ≠ 0
pp : Prime p
⊢ ↑(factorization n) p < n
case neg n p : ℕ hn : n ≠ 0 pp : ¬Prime p ⊢ ↑(factorization n) p < n
[PROOFSTEP]
case neg =>
simp [factorization_eq_zero_of_non_prime n pp]
exact hn.bot_lt
[GOAL]
n p : ℕ
hn : n ≠ 0
pp : ¬Prime p
⊢ ↑(factorization n) p < n
[PROOFSTEP]
case neg =>
simp [factorization_eq_zero_of_non_prime n pp]
exact hn.bot_lt
[GOAL]
n p : ℕ
hn : n ≠ 0
pp : ¬Prime p
⊢ ↑(factorization n) p < n
[PROOFSTEP]
simp [factorization_eq_zero_of_non_prime n pp]
[GOAL]
n p : ℕ
hn : n ≠ 0
pp : ¬Prime p
⊢ 0 < n
[PROOFSTEP]
exact hn.bot_lt
[GOAL]
case pos
n p : ℕ
hn : n ≠ 0
pp : Prime p
⊢ ↑(factorization n) p < n
[PROOFSTEP]
rw [← pow_lt_iff_lt_right pp.two_le]
[GOAL]
case pos
n p : ℕ
hn : n ≠ 0
pp : Prime p
⊢ p ^ ↑(factorization n) p < p ^ n
[PROOFSTEP]
apply lt_of_le_of_lt (ord_proj_le p hn)
[GOAL]
case pos
n p : ℕ
hn : n ≠ 0
pp : Prime p
⊢ n < p ^ n
[PROOFSTEP]
exact lt_of_lt_of_le (lt_two_pow n) (pow_le_pow_of_le_left pp.two_le n)
[GOAL]
n p b : ℕ
hb : n ≤ p ^ b
⊢ ↑(factorization n) p ≤ b
[PROOFSTEP]
rcases eq_or_ne n 0 with (rfl | hn)
[GOAL]
case inl
p b : ℕ
hb : 0 ≤ p ^ b
⊢ ↑(factorization 0) p ≤ b
[PROOFSTEP]
simp
[GOAL]
case inr
n p b : ℕ
hb : n ≤ p ^ b
hn : n ≠ 0
⊢ ↑(factorization n) p ≤ b
[PROOFSTEP]
by_cases pp : p.Prime
[GOAL]
case pos
n p b : ℕ
hb : n ≤ p ^ b
hn : n ≠ 0
pp : Prime p
⊢ ↑(factorization n) p ≤ b
[PROOFSTEP]
exact (pow_le_iff_le_right pp.two_le).1 (le_trans (ord_proj_le p hn) hb)
[GOAL]
case neg
n p b : ℕ
hb : n ≤ p ^ b
hn : n ≠ 0
pp : ¬Prime p
⊢ ↑(factorization n) p ≤ b
[PROOFSTEP]
simp [factorization_eq_zero_of_non_prime n pp]
[GOAL]
d n : ℕ
hd : d ≠ 0
hn : n ≠ 0
⊢ factorization d ≤ factorization n ↔ d ∣ n
[PROOFSTEP]
constructor
[GOAL]
case mp
d n : ℕ
hd : d ≠ 0
hn : n ≠ 0
⊢ factorization d ≤ factorization n → d ∣ n
[PROOFSTEP]
intro hdn
[GOAL]
case mp
d n : ℕ
hd : d ≠ 0
hn : n ≠ 0
hdn : factorization d ≤ factorization n
⊢ d ∣ n
[PROOFSTEP]
set K := n.factorization - d.factorization with hK
[GOAL]
case mp
d n : ℕ
hd : d ≠ 0
hn : n ≠ 0
hdn : factorization d ≤ factorization n
K : ℕ →₀ ℕ := factorization n - factorization d
hK : K = factorization n - factorization d
⊢ d ∣ n
[PROOFSTEP]
use K.prod (· ^ ·)
[GOAL]
case h
d n : ℕ
hd : d ≠ 0
hn : n ≠ 0
hdn : factorization d ≤ factorization n
K : ℕ →₀ ℕ := factorization n - factorization d
hK : K = factorization n - factorization d
⊢ n = d * Finsupp.prod K fun x x_1 => x ^ x_1
[PROOFSTEP]
rw [← factorization_prod_pow_eq_self hn, ← factorization_prod_pow_eq_self hd, ←
Finsupp.prod_add_index' pow_zero pow_add, hK, add_tsub_cancel_of_le hdn]
[GOAL]
case mpr
d n : ℕ
hd : d ≠ 0
hn : n ≠ 0
⊢ d ∣ n → factorization d ≤ factorization n
[PROOFSTEP]
rintro ⟨c, rfl⟩
[GOAL]
case mpr.intro
d : ℕ
hd : d ≠ 0
c : ℕ
hn : d * c ≠ 0
⊢ factorization d ≤ factorization (d * c)
[PROOFSTEP]
rw [factorization_mul hd (right_ne_zero_of_mul hn)]
[GOAL]
case mpr.intro
d : ℕ
hd : d ≠ 0
c : ℕ
hn : d * c ≠ 0
⊢ factorization d ≤ factorization d + factorization c
[PROOFSTEP]
simp
[GOAL]
d n : ℕ
hd : d ≠ 0
hn : n ≠ 0
⊢ (∀ (p : ℕ), Prime p → ↑(factorization d) p ≤ ↑(factorization n) p) ↔ d ∣ n
[PROOFSTEP]
rw [← factorization_le_iff_dvd hd hn]
[GOAL]
d n : ℕ
hd : d ≠ 0
hn : n ≠ 0
⊢ (∀ (p : ℕ), Prime p → ↑(factorization d) p ≤ ↑(factorization n) p) ↔ factorization d ≤ factorization n
[PROOFSTEP]
refine' ⟨fun h p => (em p.Prime).elim (h p) fun hp => _, fun h p _ => h p⟩
[GOAL]
d n : ℕ
hd : d ≠ 0
hn : n ≠ 0
h : ∀ (p : ℕ), Prime p → ↑(factorization d) p ≤ ↑(factorization n) p
p : ℕ
hp : ¬Prime p
⊢ ↑(factorization d) p ≤ ↑(factorization n) p
[PROOFSTEP]
simp_rw [factorization_eq_zero_of_non_prime _ hp, le_refl]
[GOAL]
n p : ℕ
hn : n ≠ 0
hp : Prime p
⊢ ¬p ^ (↑(factorization n) p + 1) ∣ n
[PROOFSTEP]
intro h
[GOAL]
n p : ℕ
hn : n ≠ 0
hp : Prime p
h : p ^ (↑(factorization n) p + 1) ∣ n
⊢ False
[PROOFSTEP]
rw [← factorization_le_iff_dvd (pow_pos hp.pos _).ne' hn] at h
[GOAL]
n p : ℕ
hn : n ≠ 0
hp : Prime p
h : factorization (p ^ (↑(factorization n) p + 1)) ≤ factorization n
⊢ False
[PROOFSTEP]
simpa [hp.factorization] using h p
[GOAL]
a b : ℕ
hb : b ≠ 0
⊢ factorization a ≤ factorization (a * b)
[PROOFSTEP]
rcases eq_or_ne a 0 with (rfl | ha)
[GOAL]
case inl
b : ℕ
hb : b ≠ 0
⊢ factorization 0 ≤ factorization (0 * b)
[PROOFSTEP]
simp
[GOAL]
case inr
a b : ℕ
hb : b ≠ 0
ha : a ≠ 0
⊢ factorization a ≤ factorization (a * b)
[PROOFSTEP]
rw [factorization_le_iff_dvd ha <| mul_ne_zero ha hb]
[GOAL]
case inr
a b : ℕ
hb : b ≠ 0
ha : a ≠ 0
⊢ a ∣ a * b
[PROOFSTEP]
exact Dvd.intro b rfl
[GOAL]
a b : ℕ
ha : a ≠ 0
⊢ factorization b ≤ factorization (a * b)
[PROOFSTEP]
rw [mul_comm]
[GOAL]
a b : ℕ
ha : a ≠ 0
⊢ factorization b ≤ factorization (b * a)
[PROOFSTEP]
apply factorization_le_factorization_mul_left ha
[GOAL]
p k n : ℕ
pp : Prime p
hn : n ≠ 0
⊢ p ^ k ∣ n ↔ k ≤ ↑(Nat.factorization n) p
[PROOFSTEP]
rw [← factorization_le_iff_dvd (pow_pos pp.pos k).ne' hn, pp.factorization_pow, single_le_iff]
[GOAL]
p k n : ℕ
pp : Prime p
hn : n ≠ 0
⊢ p ^ k ∣ n ↔ p ^ k ∣ p ^ ↑(Nat.factorization n) p
[PROOFSTEP]
rw [pow_dvd_pow_iff_le_right pp.one_lt, pp.pow_dvd_iff_le_factorization hn]
[GOAL]
p n : ℕ
pp : Prime p
hn : n ≠ 0
⊢ p ∣ n ↔ p ^ 1 ∣ n
[PROOFSTEP]
simp
[GOAL]
a b : ℕ
ha : a ≠ 0
hab : a < b
⊢ ∃ p, ↑(factorization a) p < ↑(factorization b) p
[PROOFSTEP]
have hb : b ≠ 0 := (ha.bot_lt.trans hab).ne'
[GOAL]
a b : ℕ
ha : a ≠ 0
hab : a < b
hb : b ≠ 0
⊢ ∃ p, ↑(factorization a) p < ↑(factorization b) p
[PROOFSTEP]
contrapose! hab
[GOAL]
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
hab : ∀ (p : ℕ), ↑(factorization b) p ≤ ↑(factorization a) p
⊢ b ≤ a
[PROOFSTEP]
rw [← Finsupp.le_def, factorization_le_iff_dvd hb ha] at hab
[GOAL]
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
hab : b ∣ a
⊢ b ≤ a
[PROOFSTEP]
exact le_of_dvd ha.bot_lt hab
[GOAL]
d n : ℕ
h : d ∣ n
⊢ factorization (n / d) = factorization n - factorization d
[PROOFSTEP]
rcases eq_or_ne d 0 with (rfl | hd)
[GOAL]
case inl
n : ℕ
h : 0 ∣ n
⊢ factorization (n / 0) = factorization n - factorization 0
[PROOFSTEP]
simp [zero_dvd_iff.mp h]
[GOAL]
case inr
d n : ℕ
h : d ∣ n
hd : d ≠ 0
⊢ factorization (n / d) = factorization n - factorization d
[PROOFSTEP]
rcases eq_or_ne n 0 with (rfl | hn)
[GOAL]
case inr.inl
d : ℕ
hd : d ≠ 0
h : d ∣ 0
⊢ factorization (0 / d) = factorization 0 - factorization d
[PROOFSTEP]
simp
[GOAL]
case inr.inr
d n : ℕ
h : d ∣ n
hd : d ≠ 0
hn : n ≠ 0
⊢ factorization (n / d) = factorization n - factorization d
[PROOFSTEP]
apply add_left_injective d.factorization
[GOAL]
case inr.inr.a
d n : ℕ
h : d ∣ n
hd : d ≠ 0
hn : n ≠ 0
⊢ (fun x => x + factorization d) (factorization (n / d)) =
(fun x => x + factorization d) (factorization n - factorization d)
[PROOFSTEP]
simp only
[GOAL]
case inr.inr.a
d n : ℕ
h : d ∣ n
hd : d ≠ 0
hn : n ≠ 0
⊢ factorization (n / d) + factorization d = factorization n - factorization d + factorization d
[PROOFSTEP]
rw [tsub_add_cancel_of_le <| (Nat.factorization_le_iff_dvd hd hn).mpr h, ←
Nat.factorization_mul (Nat.div_pos (Nat.le_of_dvd hn.bot_lt h) hd.bot_lt).ne' hd, Nat.div_mul_cancel h]
[GOAL]
n p : ℕ
hp : Prime p
hn : n ≠ 0
⊢ ¬p ∣ n / p ^ ↑(factorization n) p
[PROOFSTEP]
rw [Nat.Prime.dvd_iff_one_le_factorization hp (ord_compl_pos p hn).ne']
[GOAL]
n p : ℕ
hp : Prime p
hn : n ≠ 0
⊢ ¬1 ≤ ↑(factorization (n / p ^ ↑(factorization n) p)) p
[PROOFSTEP]
rw [Nat.factorization_div (Nat.ord_proj_dvd n p)]
[GOAL]
n p : ℕ
hp : Prime p
hn : n ≠ 0
⊢ ¬1 ≤ ↑(factorization n - factorization (p ^ ↑(factorization n) p)) p
[PROOFSTEP]
simp [hp.factorization]
[GOAL]
n p : ℕ
⊢ factorization (n / p ^ ↑(factorization n) p) = Finsupp.erase p (factorization n)
[PROOFSTEP]
rcases eq_or_ne n 0 with (rfl | hn)
[GOAL]
case inl
p : ℕ
⊢ factorization (0 / p ^ ↑(factorization 0) p) = Finsupp.erase p (factorization 0)
[PROOFSTEP]
simp
[GOAL]
case inr
n p : ℕ
hn : n ≠ 0
⊢ factorization (n / p ^ ↑(factorization n) p) = Finsupp.erase p (factorization n)
[PROOFSTEP]
by_cases pp : p.Prime
[GOAL]
case pos
n p : ℕ
hn : n ≠ 0
pp : Prime p
⊢ factorization (n / p ^ ↑(factorization n) p) = Finsupp.erase p (factorization n)
case neg
n p : ℕ
hn : n ≠ 0
pp : ¬Prime p
⊢ factorization (n / p ^ ↑(factorization n) p) = Finsupp.erase p (factorization n)
[PROOFSTEP]
case neg =>
-- porting note: needed to solve side goal explicitly
rw [Finsupp.erase_of_not_mem_support]
· simp [pp]
· simp [mt prime_of_mem_factors pp]
[GOAL]
n p : ℕ
hn : n ≠ 0
pp : ¬Prime p
⊢ factorization (n / p ^ ↑(factorization n) p) = Finsupp.erase p (factorization n)
[PROOFSTEP]
case neg =>
-- porting note: needed to solve side goal explicitly
rw [Finsupp.erase_of_not_mem_support]
· simp [pp]
· simp [mt prime_of_mem_factors pp]
[GOAL]
n p : ℕ
hn : n ≠ 0
pp : ¬Prime p
⊢ factorization (n / p ^ ↑(factorization n) p) = Finsupp.erase p (factorization n)
[PROOFSTEP]
rw [Finsupp.erase_of_not_mem_support]
[GOAL]
n p : ℕ
hn : n ≠ 0
pp : ¬Prime p
⊢ factorization (n / p ^ ↑(factorization n) p) = factorization n
[PROOFSTEP]
simp [pp]
[GOAL]
n p : ℕ
hn : n ≠ 0
pp : ¬Prime p
⊢ ¬p ∈ (factorization n).support
[PROOFSTEP]
simp [mt prime_of_mem_factors pp]
[GOAL]
case pos
n p : ℕ
hn : n ≠ 0
pp : Prime p
⊢ factorization (n / p ^ ↑(factorization n) p) = Finsupp.erase p (factorization n)
[PROOFSTEP]
ext q
[GOAL]
case pos.h
n p : ℕ
hn : n ≠ 0
pp : Prime p
q : ℕ
⊢ ↑(factorization (n / p ^ ↑(factorization n) p)) q = ↑(Finsupp.erase p (factorization n)) q
[PROOFSTEP]
rcases eq_or_ne q p with (rfl | hqp)
[GOAL]
case pos.h.inl
n : ℕ
hn : n ≠ 0
q : ℕ
pp : Prime q
⊢ ↑(factorization (n / q ^ ↑(factorization n) q)) q = ↑(Finsupp.erase q (factorization n)) q
[PROOFSTEP]
simp only [Finsupp.erase_same, factorization_eq_zero_iff, not_dvd_ord_compl pp hn]
[GOAL]
case pos.h.inl
n : ℕ
hn : n ≠ 0
q : ℕ
pp : Prime q
⊢ ¬Prime q ∨ True ∨ n / q ^ ↑(factorization n) q = 0
[PROOFSTEP]
simp
[GOAL]
case pos.h.inr
n p : ℕ
hn : n ≠ 0
pp : Prime p
q : ℕ
hqp : q ≠ p
⊢ ↑(factorization (n / p ^ ↑(factorization n) p)) q = ↑(Finsupp.erase p (factorization n)) q
[PROOFSTEP]
rw [Finsupp.erase_ne hqp, factorization_div (ord_proj_dvd n p)]
[GOAL]
case pos.h.inr
n p : ℕ
hn : n ≠ 0
pp : Prime p
q : ℕ
hqp : q ≠ p
⊢ ↑(factorization n - factorization (p ^ ↑(factorization n) p)) q = ↑(factorization n) q
[PROOFSTEP]
simp [pp.factorization, hqp.symm]
[GOAL]
p d n : ℕ
hdn : d ∣ n
hpd : ¬p ∣ d
⊢ d ∣ n / p ^ ↑(factorization n) p
[PROOFSTEP]
rcases eq_or_ne n 0 with (rfl | hn0)
[GOAL]
case inl
p d : ℕ
hpd : ¬p ∣ d
hdn : d ∣ 0
⊢ d ∣ 0 / p ^ ↑(factorization 0) p
[PROOFSTEP]
simp
[GOAL]
case inr
p d n : ℕ
hdn : d ∣ n
hpd : ¬p ∣ d
hn0 : n ≠ 0
⊢ d ∣ n / p ^ ↑(factorization n) p
[PROOFSTEP]
rcases eq_or_ne d 0 with (rfl | hd0)
[GOAL]
case inr.inl
p n : ℕ
hn0 : n ≠ 0
hdn : 0 ∣ n
hpd : ¬p ∣ 0
⊢ 0 ∣ n / p ^ ↑(factorization n) p
[PROOFSTEP]
simp at hpd
[GOAL]
case inr.inr
p d n : ℕ
hdn : d ∣ n
hpd : ¬p ∣ d
hn0 : n ≠ 0
hd0 : d ≠ 0
⊢ d ∣ n / p ^ ↑(factorization n) p
[PROOFSTEP]
rw [← factorization_le_iff_dvd hd0 (ord_compl_pos p hn0).ne', factorization_ord_compl]
[GOAL]
case inr.inr
p d n : ℕ
hdn : d ∣ n
hpd : ¬p ∣ d
hn0 : n ≠ 0
hd0 : d ≠ 0
⊢ factorization d ≤ Finsupp.erase p (factorization n)
[PROOFSTEP]
intro q
[GOAL]
case inr.inr
p d n : ℕ
hdn : d ∣ n
hpd : ¬p ∣ d
hn0 : n ≠ 0
hd0 : d ≠ 0
q : ℕ
⊢ ↑(factorization d) q ≤ ↑(Finsupp.erase p (factorization n)) q
[PROOFSTEP]
rcases eq_or_ne q p with (rfl | hqp)
[GOAL]
case inr.inr.inl
d n : ℕ
hdn : d ∣ n
hn0 : n ≠ 0
hd0 : d ≠ 0
q : ℕ
hpd : ¬q ∣ d
⊢ ↑(factorization d) q ≤ ↑(Finsupp.erase q (factorization n)) q
[PROOFSTEP]
simp [factorization_eq_zero_iff, hpd]
[GOAL]
case inr.inr.inr
p d n : ℕ
hdn : d ∣ n
hpd : ¬p ∣ d
hn0 : n ≠ 0
hd0 : d ≠ 0
q : ℕ
hqp : q ≠ p
⊢ ↑(factorization d) q ≤ ↑(Finsupp.erase p (factorization n)) q
[PROOFSTEP]
simp [hqp, (factorization_le_iff_dvd hd0 hn0).2 hdn q]
[GOAL]
d n : ℕ
hd : d ≠ 0
hdn : d ≤ n
⊢ d ∣ n ↔ factorization (n / d) = factorization n - factorization d
[PROOFSTEP]
refine' ⟨factorization_div, _⟩
[GOAL]
d n : ℕ
hd : d ≠ 0
hdn : d ≤ n
⊢ factorization (n / d) = factorization n - factorization d → d ∣ n
[PROOFSTEP]
rcases eq_or_lt_of_le hdn with (rfl | hd_lt_n)
[GOAL]
case inl
d : ℕ
hd : d ≠ 0
hdn : d ≤ d
⊢ factorization (d / d) = factorization d - factorization d → d ∣ d
[PROOFSTEP]
simp
[GOAL]
case inr
d n : ℕ
hd : d ≠ 0
hdn : d ≤ n
hd_lt_n : d < n
⊢ factorization (n / d) = factorization n - factorization d → d ∣ n
[PROOFSTEP]
have h1 : n / d ≠ 0 := fun H => Nat.lt_asymm hd_lt_n ((Nat.div_eq_zero_iff hd.bot_lt).mp H)
[GOAL]
case inr
d n : ℕ
hd : d ≠ 0
hdn : d ≤ n
hd_lt_n : d < n
h1 : n / d ≠ 0
⊢ factorization (n / d) = factorization n - factorization d → d ∣ n
[PROOFSTEP]
intro h
[GOAL]
case inr
d n : ℕ
hd : d ≠ 0
hdn : d ≤ n
hd_lt_n : d < n
h1 : n / d ≠ 0
h : factorization (n / d) = factorization n - factorization d
⊢ d ∣ n
[PROOFSTEP]
rw [dvd_iff_le_div_mul n d]
[GOAL]
case inr
d n : ℕ
hd : d ≠ 0
hdn : d ≤ n
hd_lt_n : d < n
h1 : n / d ≠ 0
h : factorization (n / d) = factorization n - factorization d
⊢ n ≤ n / d * d
[PROOFSTEP]
by_contra h2
[GOAL]
case inr
d n : ℕ
hd : d ≠ 0
hdn : d ≤ n
hd_lt_n : d < n
h1 : n / d ≠ 0
h : factorization (n / d) = factorization n - factorization d
h2 : ¬n ≤ n / d * d
⊢ False
[PROOFSTEP]
cases' exists_factorization_lt_of_lt (mul_ne_zero h1 hd) (not_le.mp h2) with p hp
[GOAL]
case inr.intro
d n : ℕ
hd : d ≠ 0
hdn : d ≤ n
hd_lt_n : d < n
h1 : n / d ≠ 0
h : factorization (n / d) = factorization n - factorization d
h2 : ¬n ≤ n / d * d
p : ℕ
hp : ↑(factorization (n / d * d)) p < ↑(factorization n) p
⊢ False
[PROOFSTEP]
rwa [factorization_mul h1 hd, add_apply, ← lt_tsub_iff_right, h, tsub_apply, lt_self_iff_false] at hp
[GOAL]
a b : ℕ
hb0 : b ≠ 0
hab : a ∣ b
p : ℕ
⊢ p ^ ↑(factorization a) p ∣ p ^ ↑(factorization b) p
[PROOFSTEP]
rcases em' p.Prime with (pp | pp)
[GOAL]
case inl
a b : ℕ
hb0 : b ≠ 0
hab : a ∣ b
p : ℕ
pp : ¬Prime p
⊢ p ^ ↑(factorization a) p ∣ p ^ ↑(factorization b) p
[PROOFSTEP]
simp [pp]
[GOAL]
case inr
a b : ℕ
hb0 : b ≠ 0
hab : a ∣ b
p : ℕ
pp : Prime p
⊢ p ^ ↑(factorization a) p ∣ p ^ ↑(factorization b) p
[PROOFSTEP]
rcases eq_or_ne a 0 with (rfl | ha0)
[GOAL]
case inr.inl
b : ℕ
hb0 : b ≠ 0
p : ℕ
pp : Prime p
hab : 0 ∣ b
⊢ p ^ ↑(factorization 0) p ∣ p ^ ↑(factorization b) p
[PROOFSTEP]
simp
[GOAL]
case inr.inr
a b : ℕ
hb0 : b ≠ 0
hab : a ∣ b
p : ℕ
pp : Prime p
ha0 : a ≠ 0
⊢ p ^ ↑(factorization a) p ∣ p ^ ↑(factorization b) p
[PROOFSTEP]
rw [pow_dvd_pow_iff_le_right pp.one_lt]
[GOAL]
case inr.inr
a b : ℕ
hb0 : b ≠ 0
hab : a ∣ b
p : ℕ
pp : Prime p
ha0 : a ≠ 0
⊢ ↑(factorization a) p ≤ ↑(factorization b) p
[PROOFSTEP]
exact (factorization_le_iff_dvd ha0 hb0).2 hab p
[GOAL]
a b : ℕ
ha0 : a ≠ 0
hb0 : b ≠ 0
⊢ (∀ (p : ℕ), p ^ ↑(factorization a) p ∣ p ^ ↑(factorization b) p) ↔ a ∣ b
[PROOFSTEP]
refine' ⟨fun h => _, fun hab p => ord_proj_dvd_ord_proj_of_dvd hb0 hab p⟩
[GOAL]
a b : ℕ
ha0 : a ≠ 0
hb0 : b ≠ 0
h : ∀ (p : ℕ), p ^ ↑(factorization a) p ∣ p ^ ↑(factorization b) p
⊢ a ∣ b
[PROOFSTEP]
rw [← factorization_le_iff_dvd ha0 hb0]
[GOAL]
a b : ℕ
ha0 : a ≠ 0
hb0 : b ≠ 0
h : ∀ (p : ℕ), p ^ ↑(factorization a) p ∣ p ^ ↑(factorization b) p
⊢ factorization a ≤ factorization b
[PROOFSTEP]
intro q
[GOAL]
a b : ℕ
ha0 : a ≠ 0
hb0 : b ≠ 0
h : ∀ (p : ℕ), p ^ ↑(factorization a) p ∣ p ^ ↑(factorization b) p
q : ℕ
⊢ ↑(factorization a) q ≤ ↑(factorization b) q
[PROOFSTEP]
rcases le_or_lt q 1 with (hq_le | hq1)
[GOAL]
case inl
a b : ℕ
ha0 : a ≠ 0
hb0 : b ≠ 0
h : ∀ (p : ℕ), p ^ ↑(factorization a) p ∣ p ^ ↑(factorization b) p
q : ℕ
hq_le : q ≤ 1
⊢ ↑(factorization a) q ≤ ↑(factorization b) q
[PROOFSTEP]
interval_cases q
[GOAL]
case inl.«0»
a b : ℕ
ha0 : a ≠ 0
hb0 : b ≠ 0
h : ∀ (p : ℕ), p ^ ↑(factorization a) p ∣ p ^ ↑(factorization b) p
q : ℕ
hq_le : 0 ≤ 1
⊢ ↑(factorization a) 0 ≤ ↑(factorization b) 0
[PROOFSTEP]
simp
[GOAL]
case inl.«1»
a b : ℕ
ha0 : a ≠ 0
hb0 : b ≠ 0
h : ∀ (p : ℕ), p ^ ↑(factorization a) p ∣ p ^ ↑(factorization b) p
q : ℕ
hq_le : 1 ≤ 1
⊢ ↑(factorization a) 1 ≤ ↑(factorization b) 1
[PROOFSTEP]
simp
[GOAL]
case inr
a b : ℕ
ha0 : a ≠ 0
hb0 : b ≠ 0
h : ∀ (p : ℕ), p ^ ↑(factorization a) p ∣ p ^ ↑(factorization b) p
q : ℕ
hq1 : 1 < q
⊢ ↑(factorization a) q ≤ ↑(factorization b) q
[PROOFSTEP]
exact (pow_dvd_pow_iff_le_right hq1).1 (h q)
[GOAL]
a b : ℕ
hab : a ∣ b
p : ℕ
⊢ a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
[PROOFSTEP]
rcases em' p.Prime with (pp | pp)
[GOAL]
case inl
a b : ℕ
hab : a ∣ b
p : ℕ
pp : ¬Prime p
⊢ a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
[PROOFSTEP]
simp [pp, hab]
[GOAL]
case inr
a b : ℕ
hab : a ∣ b
p : ℕ
pp : Prime p
⊢ a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
[PROOFSTEP]
rcases eq_or_ne b 0 with (rfl | hb0)
[GOAL]
case inr.inl
a p : ℕ
pp : Prime p
hab : a ∣ 0
⊢ a / p ^ ↑(factorization a) p ∣ 0 / p ^ ↑(factorization 0) p
[PROOFSTEP]
simp
[GOAL]
case inr.inr
a b : ℕ
hab : a ∣ b
p : ℕ
pp : Prime p
hb0 : b ≠ 0
⊢ a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
[PROOFSTEP]
rcases eq_or_ne a 0 with (rfl | ha0)
[GOAL]
case inr.inr.inl
b p : ℕ
pp : Prime p
hb0 : b ≠ 0
hab : 0 ∣ b
⊢ 0 / p ^ ↑(factorization 0) p ∣ b / p ^ ↑(factorization b) p
[PROOFSTEP]
cases hb0 (zero_dvd_iff.1 hab)
[GOAL]
case inr.inr.inr
a b : ℕ
hab : a ∣ b
p : ℕ
pp : Prime p
hb0 : b ≠ 0
ha0 : a ≠ 0
⊢ a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
[PROOFSTEP]
have ha := (Nat.div_pos (ord_proj_le p ha0) (ord_proj_pos a p)).ne'
[GOAL]
case inr.inr.inr
a b : ℕ
hab : a ∣ b
p : ℕ
pp : Prime p
hb0 : b ≠ 0
ha0 : a ≠ 0
ha : a / p ^ ↑(factorization a) p ≠ 0
⊢ a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
[PROOFSTEP]
have hb := (Nat.div_pos (ord_proj_le p hb0) (ord_proj_pos b p)).ne'
[GOAL]
case inr.inr.inr
a b : ℕ
hab : a ∣ b
p : ℕ
pp : Prime p
hb0 : b ≠ 0
ha0 : a ≠ 0
ha : a / p ^ ↑(factorization a) p ≠ 0
hb : b / p ^ ↑(factorization b) p ≠ 0
⊢ a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
[PROOFSTEP]
rw [← factorization_le_iff_dvd ha hb, factorization_ord_compl a p, factorization_ord_compl b p]
[GOAL]
case inr.inr.inr
a b : ℕ
hab : a ∣ b
p : ℕ
pp : Prime p
hb0 : b ≠ 0
ha0 : a ≠ 0
ha : a / p ^ ↑(factorization a) p ≠ 0
hb : b / p ^ ↑(factorization b) p ≠ 0
⊢ Finsupp.erase p (factorization a) ≤ Finsupp.erase p (factorization b)
[PROOFSTEP]
intro q
[GOAL]
case inr.inr.inr
a b : ℕ
hab : a ∣ b
p : ℕ
pp : Prime p
hb0 : b ≠ 0
ha0 : a ≠ 0
ha : a / p ^ ↑(factorization a) p ≠ 0
hb : b / p ^ ↑(factorization b) p ≠ 0
q : ℕ
⊢ ↑(Finsupp.erase p (factorization a)) q ≤ ↑(Finsupp.erase p (factorization b)) q
[PROOFSTEP]
rcases eq_or_ne q p with (rfl | hqp)
[GOAL]
case inr.inr.inr.inl
a b : ℕ
hab : a ∣ b
hb0 : b ≠ 0
ha0 : a ≠ 0
q : ℕ
pp : Prime q
ha : a / q ^ ↑(factorization a) q ≠ 0
hb : b / q ^ ↑(factorization b) q ≠ 0
⊢ ↑(Finsupp.erase q (factorization a)) q ≤ ↑(Finsupp.erase q (factorization b)) q
[PROOFSTEP]
simp
[GOAL]
case inr.inr.inr.inr
a b : ℕ
hab : a ∣ b
p : ℕ
pp : Prime p
hb0 : b ≠ 0
ha0 : a ≠ 0
ha : a / p ^ ↑(factorization a) p ≠ 0
hb : b / p ^ ↑(factorization b) p ≠ 0
q : ℕ
hqp : q ≠ p
⊢ ↑(Finsupp.erase p (factorization a)) q ≤ ↑(Finsupp.erase p (factorization b)) q
[PROOFSTEP]
simp_rw [erase_ne hqp]
[GOAL]
case inr.inr.inr.inr
a b : ℕ
hab : a ∣ b
p : ℕ
pp : Prime p
hb0 : b ≠ 0
ha0 : a ≠ 0
ha : a / p ^ ↑(factorization a) p ≠ 0
hb : b / p ^ ↑(factorization b) p ≠ 0
q : ℕ
hqp : q ≠ p
⊢ ↑(factorization a) q ≤ ↑(factorization b) q
[PROOFSTEP]
exact (factorization_le_iff_dvd ha0 hb0).2 hab q
[GOAL]
a b : ℕ
⊢ (∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p) ↔ a ∣ b
[PROOFSTEP]
refine' ⟨fun h => _, fun hab p => ord_compl_dvd_ord_compl_of_dvd hab p⟩
[GOAL]
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
⊢ a ∣ b
[PROOFSTEP]
rcases eq_or_ne b 0 with (rfl | hb0)
[GOAL]
case inl
a : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ 0 / p ^ ↑(factorization 0) p
⊢ a ∣ 0
[PROOFSTEP]
simp
[GOAL]
case inr
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
⊢ a ∣ b
[PROOFSTEP]
by_cases pa : a.Prime
[GOAL]
case pos
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
pa : Prime a
⊢ a ∣ b
case neg
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
pa : ¬Prime a
⊢ a ∣ b
[PROOFSTEP]
case neg => simpa [pa] using h a
[GOAL]
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
pa : ¬Prime a
⊢ a ∣ b
[PROOFSTEP]
case neg => simpa [pa] using h a
[GOAL]
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
pa : ¬Prime a
⊢ a ∣ b
[PROOFSTEP]
simpa [pa] using h a
[GOAL]
case pos
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
pa : Prime a
⊢ a ∣ b
[PROOFSTEP]
by_cases pb : b.Prime
[GOAL]
case pos
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
pa : Prime a
pb : Prime b
⊢ a ∣ b
case neg
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
pa : Prime a
pb : ¬Prime b
⊢ a ∣ b
[PROOFSTEP]
case neg => simpa [pb] using h b
[GOAL]
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
pa : Prime a
pb : ¬Prime b
⊢ a ∣ b
[PROOFSTEP]
case neg => simpa [pb] using h b
[GOAL]
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
pa : Prime a
pb : ¬Prime b
⊢ a ∣ b
[PROOFSTEP]
simpa [pb] using h b
[GOAL]
case pos
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
pa : Prime a
pb : Prime b
⊢ a ∣ b
[PROOFSTEP]
rw [prime_dvd_prime_iff_eq pa pb]
[GOAL]
case pos
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
pa : Prime a
pb : Prime b
⊢ a = b
[PROOFSTEP]
by_contra hab
[GOAL]
case pos
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
pa : Prime a
pb : Prime b
hab : ¬a = b
⊢ False
[PROOFSTEP]
apply pa.ne_one
[GOAL]
case pos
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
pa : Prime a
pb : Prime b
hab : ¬a = b
⊢ a = 1
[PROOFSTEP]
rw [← Nat.dvd_one, ← Nat.mul_dvd_mul_iff_left hb0.bot_lt, mul_one]
[GOAL]
case pos
a b : ℕ
h : ∀ (p : ℕ), a / p ^ ↑(factorization a) p ∣ b / p ^ ↑(factorization b) p
hb0 : b ≠ 0
pa : Prime a
pb : Prime b
hab : ¬a = b
⊢ b * a ∣ b
[PROOFSTEP]
simpa [Prime.factorization_self pb, Prime.factorization pa, hab] using h b
[GOAL]
n d : ℕ
⊢ d ∣ n ↔ ∀ (p k : ℕ), Prime p → p ^ k ∣ d → p ^ k ∣ n
[PROOFSTEP]
rcases eq_or_ne n 0 with (rfl | hn)
[GOAL]
case inl
d : ℕ
⊢ d ∣ 0 ↔ ∀ (p k : ℕ), Prime p → p ^ k ∣ d → p ^ k ∣ 0
[PROOFSTEP]
simp
[GOAL]
case inr
n d : ℕ
hn : n ≠ 0
⊢ d ∣ n ↔ ∀ (p k : ℕ), Prime p → p ^ k ∣ d → p ^ k ∣ n
[PROOFSTEP]
rcases eq_or_ne d 0 with (rfl | hd)
[GOAL]
case inr.inl
n : ℕ
hn : n ≠ 0
⊢ 0 ∣ n ↔ ∀ (p k : ℕ), Prime p → p ^ k ∣ 0 → p ^ k ∣ n
[PROOFSTEP]
simp only [zero_dvd_iff, hn, false_iff_iff, not_forall]
[GOAL]
case inr.inl
n : ℕ
hn : n ≠ 0
⊢ ∃ x x_1 h x_2, ¬x ^ x_1 ∣ n
[PROOFSTEP]
exact ⟨2, n, prime_two, dvd_zero _, mt (le_of_dvd hn.bot_lt) (lt_two_pow n).not_le⟩
[GOAL]
case inr.inr
n d : ℕ
hn : n ≠ 0
hd : d ≠ 0
⊢ d ∣ n ↔ ∀ (p k : ℕ), Prime p → p ^ k ∣ d → p ^ k ∣ n
[PROOFSTEP]
refine' ⟨fun h p k _ hpkd => dvd_trans hpkd h, _⟩
[GOAL]
case inr.inr
n d : ℕ
hn : n ≠ 0
hd : d ≠ 0
⊢ (∀ (p k : ℕ), Prime p → p ^ k ∣ d → p ^ k ∣ n) → d ∣ n
[PROOFSTEP]
rw [← factorization_prime_le_iff_dvd hd hn]
[GOAL]
case inr.inr
n d : ℕ
hn : n ≠ 0
hd : d ≠ 0
⊢ (∀ (p k : ℕ), Prime p → p ^ k ∣ d → p ^ k ∣ n) → ∀ (p : ℕ), Prime p → ↑(factorization d) p ≤ ↑(factorization n) p
[PROOFSTEP]
intro h p pp
[GOAL]
case inr.inr
n d : ℕ
hn : n ≠ 0
hd : d ≠ 0
h : ∀ (p k : ℕ), Prime p → p ^ k ∣ d → p ^ k ∣ n
p : ℕ
pp : Prime p
⊢ ↑(factorization d) p ≤ ↑(factorization n) p
[PROOFSTEP]
simp_rw [← pp.pow_dvd_iff_le_factorization hn]
[GOAL]
case inr.inr
n d : ℕ
hn : n ≠ 0
hd : d ≠ 0
h : ∀ (p k : ℕ), Prime p → p ^ k ∣ d → p ^ k ∣ n
p : ℕ
pp : Prime p
⊢ p ^ ↑(factorization d) p ∣ n
[PROOFSTEP]
exact h p _ pp (ord_proj_dvd _ _)
[GOAL]
n : ℕ
⊢ ∏ p in toFinset (factors n), p ∣ n
[PROOFSTEP]
by_cases hn : n = 0
[GOAL]
case pos
n : ℕ
hn : n = 0
⊢ ∏ p in toFinset (factors n), p ∣ n
[PROOFSTEP]
subst hn
[GOAL]
case pos
⊢ ∏ p in toFinset (factors 0), p ∣ 0
[PROOFSTEP]
simp
[GOAL]
case neg
n : ℕ
hn : ¬n = 0
⊢ ∏ p in toFinset (factors n), p ∣ n
[PROOFSTEP]
simpa [prod_factors hn] using Multiset.toFinset_prod_dvd_prod (n.factors : Multiset ℕ)
[GOAL]
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
⊢ factorization (gcd a b) = factorization a ⊓ factorization b
[PROOFSTEP]
let dfac := a.factorization ⊓ b.factorization
[GOAL]
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
⊢ factorization (gcd a b) = factorization a ⊓ factorization b
[PROOFSTEP]
let d := dfac.prod Nat.pow
[GOAL]
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
⊢ factorization (gcd a b) = factorization a ⊓ factorization b
[PROOFSTEP]
have dfac_prime : ∀ p : ℕ, p ∈ dfac.support → Prime p :=
by
intro p hp
have : p ∈ a.factors ∧ p ∈ b.factors := by simpa using hp
exact prime_of_mem_factors this.1
[GOAL]
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
⊢ ∀ (p : ℕ), p ∈ dfac.support → Prime p
[PROOFSTEP]
intro p hp
[GOAL]
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
p : ℕ
hp : p ∈ dfac.support
⊢ Prime p
[PROOFSTEP]
have : p ∈ a.factors ∧ p ∈ b.factors := by simpa using hp
[GOAL]
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
p : ℕ
hp : p ∈ dfac.support
⊢ p ∈ factors a ∧ p ∈ factors b
[PROOFSTEP]
simpa using hp
[GOAL]
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
p : ℕ
hp : p ∈ dfac.support
this : p ∈ factors a ∧ p ∈ factors b
⊢ Prime p
[PROOFSTEP]
exact prime_of_mem_factors this.1
[GOAL]
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
⊢ factorization (gcd a b) = factorization a ⊓ factorization b
[PROOFSTEP]
have h1 : d.factorization = dfac := prod_pow_factorization_eq_self dfac_prime
[GOAL]
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
⊢ factorization (gcd a b) = factorization a ⊓ factorization b
[PROOFSTEP]
have hd_pos : d ≠ 0 := (factorizationEquiv.invFun ⟨dfac, dfac_prime⟩).2.ne'
[GOAL]
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
hd_pos : d ≠ 0
⊢ factorization (gcd a b) = factorization a ⊓ factorization b
[PROOFSTEP]
suffices d = gcd a b by rwa [← this]
[GOAL]
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
hd_pos : d ≠ 0
this : d = gcd a b
⊢ factorization (gcd a b) = factorization a ⊓ factorization b
[PROOFSTEP]
rwa [← this]
[GOAL]
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
hd_pos : d ≠ 0
⊢ d = gcd a b
[PROOFSTEP]
apply gcd_greatest
[GOAL]
case hda
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
hd_pos : d ≠ 0
⊢ d ∣ a
[PROOFSTEP]
rw [← factorization_le_iff_dvd hd_pos ha_pos, h1]
[GOAL]
case hda
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
hd_pos : d ≠ 0
⊢ dfac ≤ factorization a
[PROOFSTEP]
exact inf_le_left
[GOAL]
case hdb
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
hd_pos : d ≠ 0
⊢ d ∣ b
[PROOFSTEP]
rw [← factorization_le_iff_dvd hd_pos hb_pos, h1]
[GOAL]
case hdb
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
hd_pos : d ≠ 0
⊢ dfac ≤ factorization b
[PROOFSTEP]
exact inf_le_right
[GOAL]
case hd
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
hd_pos : d ≠ 0
⊢ ∀ (e : ℕ), e ∣ a → e ∣ b → e ∣ d
[PROOFSTEP]
intro e hea heb
[GOAL]
case hd
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
hd_pos : d ≠ 0
e : ℕ
hea : e ∣ a
heb : e ∣ b
⊢ e ∣ d
[PROOFSTEP]
rcases Decidable.eq_or_ne e 0 with (rfl | he_pos)
[GOAL]
case hd.inl
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
hd_pos : d ≠ 0
hea : 0 ∣ a
heb : 0 ∣ b
⊢ 0 ∣ d
[PROOFSTEP]
simp only [zero_dvd_iff] at hea
[GOAL]
case hd.inl
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
hd_pos : d ≠ 0
heb : 0 ∣ b
hea : a = 0
⊢ 0 ∣ d
[PROOFSTEP]
contradiction
[GOAL]
case hd.inr
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
hd_pos : d ≠ 0
e : ℕ
hea : e ∣ a
heb : e ∣ b
he_pos : e ≠ 0
⊢ e ∣ d
[PROOFSTEP]
have hea' := (factorization_le_iff_dvd he_pos ha_pos).mpr hea
[GOAL]
case hd.inr
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
hd_pos : d ≠ 0
e : ℕ
hea : e ∣ a
heb : e ∣ b
he_pos : e ≠ 0
hea' : factorization e ≤ factorization a
⊢ e ∣ d
[PROOFSTEP]
have heb' := (factorization_le_iff_dvd he_pos hb_pos).mpr heb
[GOAL]
case hd.inr
a b : ℕ
ha_pos : a ≠ 0
hb_pos : b ≠ 0
dfac : ℕ →₀ ℕ := factorization a ⊓ factorization b
d : ℕ := Finsupp.prod dfac Nat.pow
dfac_prime : ∀ (p : ℕ), p ∈ dfac.support → Prime p
h1 : factorization d = dfac
hd_pos : d ≠ 0
e : ℕ
hea : e ∣ a
heb : e ∣ b
he_pos : e ≠ 0
hea' : factorization e ≤ factorization a
heb' : factorization e ≤ factorization b
⊢ e ∣ d
[PROOFSTEP]
simp [← factorization_le_iff_dvd he_pos hd_pos, h1, hea', heb']
[GOAL]
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
⊢ factorization (lcm a b) = factorization a ⊔ factorization b
[PROOFSTEP]
rw [← add_right_inj (a.gcd b).factorization, ←
factorization_mul (mt gcd_eq_zero_iff.1 fun h => ha h.1) (lcm_ne_zero ha hb), gcd_mul_lcm, factorization_gcd ha hb,
factorization_mul ha hb]
[GOAL]
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
⊢ factorization a + factorization b = factorization a ⊓ factorization b + factorization a ⊔ factorization b
[PROOFSTEP]
ext1
[GOAL]
case h
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
a✝ : ℕ
⊢ ↑(factorization a + factorization b) a✝ = ↑(factorization a ⊓ factorization b + factorization a ⊔ factorization b) a✝
[PROOFSTEP]
exact (min_add_max _ _).symm
[GOAL]
β : Type u_1
inst✝ : CommMonoid β
m n : ℕ
f : ℕ → β
⊢ Finset.prod (toFinset (factors (gcd m n))) f * Finset.prod (toFinset (factors (m * n))) f =
Finset.prod (toFinset (factors m)) f * Finset.prod (toFinset (factors n)) f
[PROOFSTEP]
rcases eq_or_ne n 0 with (rfl | hm0)
[GOAL]
case inl
β : Type u_1
inst✝ : CommMonoid β
m : ℕ
f : ℕ → β
⊢ Finset.prod (toFinset (factors (gcd m 0))) f * Finset.prod (toFinset (factors (m * 0))) f =
Finset.prod (toFinset (factors m)) f * Finset.prod (toFinset (factors 0)) f
[PROOFSTEP]
simp
[GOAL]
case inr
β : Type u_1
inst✝ : CommMonoid β
m n : ℕ
f : ℕ → β
hm0 : n ≠ 0
⊢ Finset.prod (toFinset (factors (gcd m n))) f * Finset.prod (toFinset (factors (m * n))) f =
Finset.prod (toFinset (factors m)) f * Finset.prod (toFinset (factors n)) f
[PROOFSTEP]
rcases eq_or_ne m 0 with (rfl | hn0)
[GOAL]
case inr.inl
β : Type u_1
inst✝ : CommMonoid β
n : ℕ
f : ℕ → β
hm0 : n ≠ 0
⊢ Finset.prod (toFinset (factors (gcd 0 n))) f * Finset.prod (toFinset (factors (0 * n))) f =
Finset.prod (toFinset (factors 0)) f * Finset.prod (toFinset (factors n)) f
[PROOFSTEP]
simp
[GOAL]
case inr.inr
β : Type u_1
inst✝ : CommMonoid β
m n : ℕ
f : ℕ → β
hm0 : n ≠ 0
hn0 : m ≠ 0
⊢ Finset.prod (toFinset (factors (gcd m n))) f * Finset.prod (toFinset (factors (m * n))) f =
Finset.prod (toFinset (factors m)) f * Finset.prod (toFinset (factors n)) f
[PROOFSTEP]
rw [← @Finset.prod_union_inter _ _ m.factors.toFinset n.factors.toFinset, mul_comm]
[GOAL]
case inr.inr
β : Type u_1
inst✝ : CommMonoid β
m n : ℕ
f : ℕ → β
hm0 : n ≠ 0
hn0 : m ≠ 0
⊢ Finset.prod (toFinset (factors (m * n))) f * Finset.prod (toFinset (factors (gcd m n))) f =
(∏ x in toFinset (factors m) ∪ toFinset (factors n), f x) * ∏ x in toFinset (factors m) ∩ toFinset (factors n), f x
[PROOFSTEP]
congr
[GOAL]
case inr.inr.e_a.e_s
β : Type u_1
inst✝ : CommMonoid β
m n : ℕ
f : ℕ → β
hm0 : n ≠ 0
hn0 : m ≠ 0
⊢ toFinset (factors (m * n)) = toFinset (factors m) ∪ toFinset (factors n)
[PROOFSTEP]
apply factors_mul_toFinset
[GOAL]
case inr.inr.e_a.e_s.ha
β : Type u_1
inst✝ : CommMonoid β
m n : ℕ
f : ℕ → β
hm0 : n ≠ 0
hn0 : m ≠ 0
⊢ m ≠ 0
[PROOFSTEP]
assumption
[GOAL]
case inr.inr.e_a.e_s.hb
β : Type u_1
inst✝ : CommMonoid β
m n : ℕ
f : ℕ → β
hm0 : n ≠ 0
hn0 : m ≠ 0
⊢ n ≠ 0
[PROOFSTEP]
assumption
[GOAL]
case inr.inr.e_a.e_s
β : Type u_1
inst✝ : CommMonoid β
m n : ℕ
f : ℕ → β
hm0 : n ≠ 0
hn0 : m ≠ 0
⊢ toFinset (factors (gcd m n)) = toFinset (factors m) ∩ toFinset (factors n)
[PROOFSTEP]
simp only [← support_factorization, factorization_gcd hn0 hm0, Finsupp.support_inf]
[GOAL]
n p : ℕ
pp : Prime p
hn : n ≠ 0
⊢ {i | i ≠ 0 ∧ p ^ i ∣ n} = Set.Icc 1 (↑(factorization n) p)
[PROOFSTEP]
ext
[GOAL]
case h
n p : ℕ
pp : Prime p
hn : n ≠ 0
x✝ : ℕ
⊢ x✝ ∈ {i | i ≠ 0 ∧ p ^ i ∣ n} ↔ x✝ ∈ Set.Icc 1 (↑(factorization n) p)
[PROOFSTEP]
simp [lt_succ_iff, one_le_iff_ne_zero, pp.pow_dvd_iff_le_factorization hn]
[GOAL]
n p : ℕ
pp : Prime p
⊢ Icc 1 (↑(factorization n) p) = Finset.filter (fun i => p ^ i ∣ n) (Ico 1 n)
[PROOFSTEP]
rcases eq_or_ne n 0 with (rfl | hn)
[GOAL]
case inl
p : ℕ
pp : Prime p
⊢ Icc 1 (↑(factorization 0) p) = Finset.filter (fun i => p ^ i ∣ 0) (Ico 1 0)
[PROOFSTEP]
simp
[GOAL]
case inr
n p : ℕ
pp : Prime p
hn : n ≠ 0
⊢ Icc 1 (↑(factorization n) p) = Finset.filter (fun i => p ^ i ∣ n) (Ico 1 n)
[PROOFSTEP]
ext x
[GOAL]
case inr.a
n p : ℕ
pp : Prime p
hn : n ≠ 0
x : (fun x => ℕ) p
⊢ x ∈ Icc 1 (↑(factorization n) p) ↔ x ∈ Finset.filter (fun i => p ^ i ∣ n) (Ico 1 n)
[PROOFSTEP]
simp only [mem_Icc, Finset.mem_filter, mem_Ico, and_assoc, and_congr_right_iff, pp.pow_dvd_iff_le_factorization hn,
iff_and_self]
[GOAL]
case inr.a
n p : ℕ
pp : Prime p
hn : n ≠ 0
x : (fun x => ℕ) p
⊢ 1 ≤ x → x ≤ ↑(factorization n) p → x < n
[PROOFSTEP]
exact fun _ H => lt_of_le_of_lt H (factorization_lt p hn)
[GOAL]
n p : ℕ
pp : Prime p
⊢ ↑(factorization n) p = card (Finset.filter (fun i => p ^ i ∣ n) (Ico 1 n))
[PROOFSTEP]
simp [← Icc_factorization_eq_pow_dvd n pp]
[GOAL]
n p b : ℕ
pp : Prime p
hn : n ≠ 0
hb : n ≤ p ^ b
⊢ Finset.filter (fun i => p ^ i ∣ n) (Ico 1 n) = Finset.filter (fun i => p ^ i ∣ n) (Icc 1 b)
[PROOFSTEP]
ext x
[GOAL]
case a
n p b : ℕ
pp : Prime p
hn : n ≠ 0
hb : n ≤ p ^ b
x : ℕ
⊢ x ∈ Finset.filter (fun i => p ^ i ∣ n) (Ico 1 n) ↔ x ∈ Finset.filter (fun i => p ^ i ∣ n) (Icc 1 b)
[PROOFSTEP]
simp only [Finset.mem_filter, mem_Ico, mem_Icc, and_congr_left_iff, and_congr_right_iff]
[GOAL]
case a
n p b : ℕ
pp : Prime p
hn : n ≠ 0
hb : n ≤ p ^ b
x : ℕ
⊢ p ^ x ∣ n → 1 ≤ x → (x < n ↔ x ≤ b)
[PROOFSTEP]
rintro h1 -
[GOAL]
case a
n p b : ℕ
pp : Prime p
hn : n ≠ 0
hb : n ≤ p ^ b
x : ℕ
h1 : p ^ x ∣ n
⊢ x < n ↔ x ≤ b
[PROOFSTEP]
simp [lt_of_pow_dvd_right hn pp.two_le h1, (pow_le_iff_le_right pp.two_le).1 ((le_of_dvd hn.bot_lt h1).trans hb)]
[GOAL]
p a b : ℕ
hab : coprime a b
⊢ ↑(factorization (a * b)) p = ↑(factorization a) p + ↑(factorization b) p
[PROOFSTEP]
simp only [← factors_count_eq, perm_iff_count.mp (perm_factors_mul_of_coprime hab), count_append]
[GOAL]
a b : ℕ
hab : coprime a b
⊢ factorization (a * b) = factorization a + factorization b
[PROOFSTEP]
ext q
[GOAL]
case h
a b : ℕ
hab : coprime a b
q : ℕ
⊢ ↑(factorization (a * b)) q = ↑(factorization a + factorization b) q
[PROOFSTEP]
rw [Finsupp.add_apply, factorization_mul_apply_of_coprime hab]
[GOAL]
p a b : ℕ
hab : coprime a b
hpa : p ∈ factors a
⊢ ↑(factorization (a * b)) p = ↑(factorization a) p
[PROOFSTEP]
rw [factorization_mul_apply_of_coprime hab, ← factors_count_eq, ← factors_count_eq,
count_eq_zero_of_not_mem (coprime_factors_disjoint hab hpa), add_zero]
[GOAL]
p a b : ℕ
hab : coprime a b
hpb : p ∈ factors b
⊢ ↑(factorization (a * b)) p = ↑(factorization b) p
[PROOFSTEP]
rw [mul_comm]
[GOAL]
p a b : ℕ
hab : coprime a b
hpb : p ∈ factors b
⊢ ↑(factorization (b * a)) p = ↑(factorization b) p
[PROOFSTEP]
exact factorization_eq_of_coprime_left (coprime_comm.mp hab) hpb
[GOAL]
a b : ℕ
hab : coprime a b
⊢ _root_.Disjoint (factorization a).support (factorization b).support
[PROOFSTEP]
simpa only [support_factorization] using disjoint_toFinset_iff_disjoint.mpr (coprime_factors_disjoint hab)
[GOAL]
a b : ℕ
hab : coprime a b
⊢ (factorization (a * b)).support = (factorization a).support ∪ (factorization b).support
[PROOFSTEP]
rw [factorization_mul_of_coprime hab]
[GOAL]
a b : ℕ
hab : coprime a b
⊢ (factorization a + factorization b).support = (factorization a).support ∪ (factorization b).support
[PROOFSTEP]
exact support_add_eq (factorization_disjoint_of_coprime hab)
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
⊢ P (k + 2)
[PROOFSTEP]
let p := (k + 2).minFac
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
⊢ P (k + 2)
[PROOFSTEP]
have hp : Prime p :=
minFac_prime
(succ_succ_ne_one k)
-- the awkward `let` stuff here is because `factorization` is noncomputable (Finsupp);
-- we get around this by using the computable `factors.count`, and rewriting when we want
-- to use the `factorization` API
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
⊢ P (k + 2)
[PROOFSTEP]
let t := (k + 2).factors.count p
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
⊢ P (k + 2)
[PROOFSTEP]
have ht : t = (k + 2).factorization p := factors_count_eq
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
ht : t = ↑(factorization (k + 2)) p
⊢ P (k + 2)
[PROOFSTEP]
have hpt : p ^ t ∣ k + 2 := by
rw [ht]
exact ord_proj_dvd _ _
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
ht : t = ↑(factorization (k + 2)) p
⊢ p ^ t ∣ k + 2
[PROOFSTEP]
rw [ht]
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
ht : t = ↑(factorization (k + 2)) p
⊢ p ^ ↑(factorization (k + 2)) p ∣ k + 2
[PROOFSTEP]
exact ord_proj_dvd _ _
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
ht : t = ↑(factorization (k + 2)) p
hpt : p ^ t ∣ k + 2
⊢ P (k + 2)
[PROOFSTEP]
have htp : 0 < t := by
rw [ht]
exact hp.factorization_pos_of_dvd (Nat.succ_ne_zero _) (minFac_dvd _)
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
ht : t = ↑(factorization (k + 2)) p
hpt : p ^ t ∣ k + 2
⊢ 0 < t
[PROOFSTEP]
rw [ht]
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
ht : t = ↑(factorization (k + 2)) p
hpt : p ^ t ∣ k + 2
⊢ 0 < ↑(factorization (k + 2)) p
[PROOFSTEP]
exact hp.factorization_pos_of_dvd (Nat.succ_ne_zero _) (minFac_dvd _)
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
ht : t = ↑(factorization (k + 2)) p
hpt : p ^ t ∣ k + 2
htp : 0 < t
⊢ P (k + 2)
[PROOFSTEP]
convert h ((k + 2) / p ^ t) p t hp _ _ _ using 1
[GOAL]
case h.e'_1
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
ht : t = ↑(factorization (k + 2)) p
hpt : p ^ t ∣ k + 2
htp : 0 < t
⊢ k + 2 = p ^ t * ((k + 2) / p ^ t)
[PROOFSTEP]
rw [Nat.mul_div_cancel' hpt]
[GOAL]
case convert_1
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
ht : t = ↑(factorization (k + 2)) p
hpt : p ^ t ∣ k + 2
htp : 0 < t
⊢ ¬p ∣ (k + 2) / p ^ t
[PROOFSTEP]
rw [Nat.dvd_div_iff hpt, ← pow_succ, ht]
[GOAL]
case convert_1
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
ht : t = ↑(factorization (k + 2)) p
hpt : p ^ t ∣ k + 2
htp : 0 < t
⊢ ¬p ^ succ (↑(factorization (k + 2)) p) ∣ k + 2
[PROOFSTEP]
exact pow_succ_factorization_not_dvd (k + 1).succ_ne_zero hp
[GOAL]
case convert_2
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
ht : t = ↑(factorization (k + 2)) p
hpt : p ^ t ∣ k + 2
htp : 0 < t
⊢ 0 < t
[PROOFSTEP]
exact htp
[GOAL]
case convert_3
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
ht : t = ↑(factorization (k + 2)) p
hpt : p ^ t ∣ k + 2
htp : 0 < t
⊢ P ((k + 2) / p ^ t)
[PROOFSTEP]
apply hk _ (Nat.div_lt_of_lt_mul _)
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
ht : t = ↑(factorization (k + 2)) p
hpt : p ^ t ∣ k + 2
htp : 0 < t
⊢ k + 2 < p ^ t * (k + 2)
[PROOFSTEP]
rw [lt_mul_iff_one_lt_left Nat.succ_pos', one_lt_pow_iff htp.ne]
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
h : (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
a n k : ℕ
hk : (m : ℕ) → m < k + 2 → P m
p : ℕ := minFac (k + 2)
hp : Prime p
t : ℕ := count p (factors (k + 2))
ht : t = ↑(factorization (k + 2)) p
hpt : p ^ t ∣ k + 2
htp : 0 < t
⊢ 1 < p
[PROOFSTEP]
exact hp.one_lt
[GOAL]
P : ℕ → Sort u_1
hp : (p n : ℕ) → Prime p → 0 < n → P (p ^ n)
h0 : P 0
h1 : P 1
h : (a b : ℕ) → 1 < a → 1 < b → coprime a b → P a → P b → P (a * b)
⊢ (a p n : ℕ) → Prime p → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)
[PROOFSTEP]
intro a p n hp' hpa hn hPa
[GOAL]
P : ℕ → Sort u_1
hp : (p n : ℕ) → Prime p → 0 < n → P (p ^ n)
h0 : P 0
h1 : P 1
h : (a b : ℕ) → 1 < a → 1 < b → coprime a b → P a → P b → P (a * b)
a p n : ℕ
hp' : Prime p
hpa : ¬p ∣ a
hn : 0 < n
hPa : P a
⊢ P (p ^ n * a)
[PROOFSTEP]
by_cases ha1 : a = 1
[GOAL]
case pos
P : ℕ → Sort u_1
hp : (p n : ℕ) → Prime p → 0 < n → P (p ^ n)
h0 : P 0
h1 : P 1
h : (a b : ℕ) → 1 < a → 1 < b → coprime a b → P a → P b → P (a * b)
a p n : ℕ
hp' : Prime p
hpa : ¬p ∣ a
hn : 0 < n
hPa : P a
ha1 : a = 1
⊢ P (p ^ n * a)
[PROOFSTEP]
rw [ha1, mul_one]
[GOAL]
case pos
P : ℕ → Sort u_1
hp : (p n : ℕ) → Prime p → 0 < n → P (p ^ n)
h0 : P 0
h1 : P 1
h : (a b : ℕ) → 1 < a → 1 < b → coprime a b → P a → P b → P (a * b)
a p n : ℕ
hp' : Prime p
hpa : ¬p ∣ a
hn : 0 < n
hPa : P a
ha1 : a = 1
⊢ P (p ^ n)
[PROOFSTEP]
exact hp p n hp' hn
[GOAL]
case neg
P : ℕ → Sort u_1
hp : (p n : ℕ) → Prime p → 0 < n → P (p ^ n)
h0 : P 0
h1 : P 1
h : (a b : ℕ) → 1 < a → 1 < b → coprime a b → P a → P b → P (a * b)
a p n : ℕ
hp' : Prime p
hpa : ¬p ∣ a
hn : 0 < n
hPa : P a
ha1 : ¬a = 1
⊢ P (p ^ n * a)
[PROOFSTEP]
refine' h (p ^ n) a (hp'.one_lt.trans_le (le_self_pow hn.ne' _)) _ _ (hp _ _ hp' hn) hPa
[GOAL]
case neg.refine'_1
P : ℕ → Sort u_1
hp : (p n : ℕ) → Prime p → 0 < n → P (p ^ n)
h0 : P 0
h1 : P 1
h : (a b : ℕ) → 1 < a → 1 < b → coprime a b → P a → P b → P (a * b)
a p n : ℕ
hp' : Prime p
hpa : ¬p ∣ a
hn : 0 < n
hPa : P a
ha1 : ¬a = 1
⊢ 1 < a
[PROOFSTEP]
contrapose! hpa
[GOAL]
case neg.refine'_1
P : ℕ → Sort u_1
hp : (p n : ℕ) → Prime p → 0 < n → P (p ^ n)
h0 : P 0
h1 : P 1
h : (a b : ℕ) → 1 < a → 1 < b → coprime a b → P a → P b → P (a * b)
a p n : ℕ
hp' : Prime p
hn : 0 < n
hPa : P a
ha1 : ¬a = 1
hpa : a ≤ 1
⊢ p ∣ a
[PROOFSTEP]
simp [lt_one_iff.1 (lt_of_le_of_ne hpa ha1)]
[GOAL]
case neg.refine'_2
P : ℕ → Sort u_1
hp : (p n : ℕ) → Prime p → 0 < n → P (p ^ n)
h0 : P 0
h1 : P 1
h : (a b : ℕ) → 1 < a → 1 < b → coprime a b → P a → P b → P (a * b)
a p n : ℕ
hp' : Prime p
hpa : ¬p ∣ a
hn : 0 < n
hPa : P a
ha1 : ¬a = 1
⊢ coprime (p ^ n) a
[PROOFSTEP]
simpa [hn, Prime.coprime_iff_not_dvd hp']
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
hp : (p : ℕ) → Prime p → P p
h : (a b : ℕ) → P a → P b → P (a * b)
p n✝ : ℕ
hp' : Prime p
n : ℕ
hn : P (p ^ n)
⊢ P (p ^ succ n)
[PROOFSTEP]
rw [pow_succ]
[GOAL]
P : ℕ → Sort u_1
h0 : P 0
h1 : P 1
hp : (p : ℕ) → Prime p → P p
h : (a b : ℕ) → P a → P b → P (a * b)
p n✝ : ℕ
hp' : Prime p
n : ℕ
hn : P (p ^ n)
⊢ P (p ^ n * p)
[PROOFSTEP]
apply h _ _ hn (hp p hp')
[GOAL]
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf : f 1 = 1
⊢ ∀ {n : ℕ}, n ≠ 0 → f n = Finsupp.prod (factorization n) fun p k => f (p ^ k)
[PROOFSTEP]
apply Nat.recOnPosPrimePosCoprime
[GOAL]
case hp
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf : f 1 = 1
⊢ ∀ (p n : ℕ), Prime p → 0 < n → p ^ n ≠ 0 → f (p ^ n) = Finsupp.prod (factorization (p ^ n)) fun p k => f (p ^ k)
[PROOFSTEP]
rintro p k hp -
-
-- Porting note: replaced `simp` with `rw`
[GOAL]
case hp
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf : f 1 = 1
p k : ℕ
hp : Prime p
⊢ f (p ^ k) = Finsupp.prod (factorization (p ^ k)) fun p k => f (p ^ k)
[PROOFSTEP]
rw [Prime.factorization_pow hp, Finsupp.prod_single_index _]
[GOAL]
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf : f 1 = 1
p k : ℕ
hp : Prime p
⊢ f (p ^ 0) = 1
[PROOFSTEP]
rwa [pow_zero]
[GOAL]
case h0
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf : f 1 = 1
⊢ 0 ≠ 0 → f 0 = Finsupp.prod (factorization 0) fun p k => f (p ^ k)
[PROOFSTEP]
simp
[GOAL]
case h1
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf : f 1 = 1
⊢ 1 ≠ 0 → f 1 = Finsupp.prod (factorization 1) fun p k => f (p ^ k)
[PROOFSTEP]
rintro -
[GOAL]
case h1
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf : f 1 = 1
⊢ f 1 = Finsupp.prod (factorization 1) fun p k => f (p ^ k)
[PROOFSTEP]
rw [factorization_one, hf]
[GOAL]
case h1
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf : f 1 = 1
⊢ 1 = Finsupp.prod 0 fun p k => f (p ^ k)
[PROOFSTEP]
simp
[GOAL]
case h
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf : f 1 = 1
⊢ ∀ (a b : ℕ),
1 < a →
1 < b →
coprime a b →
(a ≠ 0 → f a = Finsupp.prod (factorization a) fun p k => f (p ^ k)) →
(b ≠ 0 → f b = Finsupp.prod (factorization b) fun p k => f (p ^ k)) →
a * b ≠ 0 → f (a * b) = Finsupp.prod (factorization (a * b)) fun p k => f (p ^ k)
[PROOFSTEP]
intro a b _ _ hab ha hb hab_pos
[GOAL]
case h
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf : f 1 = 1
a b : ℕ
a✝¹ : 1 < a
a✝ : 1 < b
hab : coprime a b
ha : a ≠ 0 → f a = Finsupp.prod (factorization a) fun p k => f (p ^ k)
hb : b ≠ 0 → f b = Finsupp.prod (factorization b) fun p k => f (p ^ k)
hab_pos : a * b ≠ 0
⊢ f (a * b) = Finsupp.prod (factorization (a * b)) fun p k => f (p ^ k)
[PROOFSTEP]
rw [h_mult a b hab, ha (left_ne_zero_of_mul hab_pos), hb (right_ne_zero_of_mul hab_pos),
factorization_mul_of_coprime hab, ← prod_add_index_of_disjoint]
[GOAL]
case h.hd
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf : f 1 = 1
a b : ℕ
a✝¹ : 1 < a
a✝ : 1 < b
hab : coprime a b
ha : a ≠ 0 → f a = Finsupp.prod (factorization a) fun p k => f (p ^ k)
hb : b ≠ 0 → f b = Finsupp.prod (factorization b) fun p k => f (p ^ k)
hab_pos : a * b ≠ 0
⊢ _root_.Disjoint (factorization a).support (factorization b).support
[PROOFSTEP]
convert factorization_disjoint_of_coprime hab
[GOAL]
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf0 : f 0 = 1
hf1 : f 1 = 1
⊢ ∀ {n : ℕ}, f n = Finsupp.prod (factorization n) fun p k => f (p ^ k)
[PROOFSTEP]
apply Nat.recOnPosPrimePosCoprime
[GOAL]
case hp
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf0 : f 0 = 1
hf1 : f 1 = 1
⊢ ∀ (p n : ℕ), Prime p → 0 < n → f (p ^ n) = Finsupp.prod (factorization (p ^ n)) fun p k => f (p ^ k)
[PROOFSTEP]
rintro p k hp -
[GOAL]
case hp
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf0 : f 0 = 1
hf1 : f 1 = 1
p k : ℕ
hp : Prime p
⊢ f (p ^ k) = Finsupp.prod (factorization (p ^ k)) fun p k => f (p ^ k)
[PROOFSTEP]
simp only [hp.factorization_pow]
[GOAL]
case hp
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf0 : f 0 = 1
hf1 : f 1 = 1
p k : ℕ
hp : Prime p
⊢ f (p ^ k) = Finsupp.prod (single p k) fun p k => f (p ^ k)
[PROOFSTEP]
rw [prod_single_index _]
[GOAL]
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf0 : f 0 = 1
hf1 : f 1 = 1
p k : ℕ
hp : Prime p
⊢ f (p ^ 0) = 1
[PROOFSTEP]
simp [hf1]
[GOAL]
case h0
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf0 : f 0 = 1
hf1 : f 1 = 1
⊢ f 0 = Finsupp.prod (factorization 0) fun p k => f (p ^ k)
[PROOFSTEP]
simp [hf0]
[GOAL]
case h1
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf0 : f 0 = 1
hf1 : f 1 = 1
⊢ f 1 = Finsupp.prod (factorization 1) fun p k => f (p ^ k)
[PROOFSTEP]
rw [factorization_one, hf1]
[GOAL]
case h1
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf0 : f 0 = 1
hf1 : f 1 = 1
⊢ 1 = Finsupp.prod 0 fun p k => f (p ^ k)
[PROOFSTEP]
simp
[GOAL]
case h
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf0 : f 0 = 1
hf1 : f 1 = 1
⊢ ∀ (a b : ℕ),
1 < a →
1 < b →
coprime a b →
(f a = Finsupp.prod (factorization a) fun p k => f (p ^ k)) →
(f b = Finsupp.prod (factorization b) fun p k => f (p ^ k)) →
f (a * b) = Finsupp.prod (factorization (a * b)) fun p k => f (p ^ k)
[PROOFSTEP]
intro a b _ _ hab ha hb
[GOAL]
case h
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf0 : f 0 = 1
hf1 : f 1 = 1
a b : ℕ
a✝¹ : 1 < a
a✝ : 1 < b
hab : coprime a b
ha : f a = Finsupp.prod (factorization a) fun p k => f (p ^ k)
hb : f b = Finsupp.prod (factorization b) fun p k => f (p ^ k)
⊢ f (a * b) = Finsupp.prod (factorization (a * b)) fun p k => f (p ^ k)
[PROOFSTEP]
rw [h_mult a b hab, ha, hb, factorization_mul_of_coprime hab, ← prod_add_index_of_disjoint]
[GOAL]
case h.hd
β : Type u_1
inst✝ : CommMonoid β
f : ℕ → β
h_mult : ∀ (x y : ℕ), coprime x y → f (x * y) = f x * f y
hf0 : f 0 = 1
hf1 : f 1 = 1
a b : ℕ
a✝¹ : 1 < a
a✝ : 1 < b
hab : coprime a b
ha : f a = Finsupp.prod (factorization a) fun p k => f (p ^ k)
hb : f b = Finsupp.prod (factorization b) fun p k => f (p ^ k)
⊢ _root_.Disjoint (factorization a).support (factorization b).support
[PROOFSTEP]
exact factorization_disjoint_of_coprime hab
[GOAL]
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
⊢ a = b ↔ ∀ (p : ℕ), Prime p → padicValNat p a = padicValNat p b
[PROOFSTEP]
constructor
[GOAL]
case mp
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
⊢ a = b → ∀ (p : ℕ), Prime p → padicValNat p a = padicValNat p b
[PROOFSTEP]
rintro rfl
[GOAL]
case mp
a : ℕ
ha hb : a ≠ 0
⊢ ∀ (p : ℕ), Prime p → padicValNat p a = padicValNat p a
[PROOFSTEP]
simp
[GOAL]
case mpr
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
⊢ (∀ (p : ℕ), Prime p → padicValNat p a = padicValNat p b) → a = b
[PROOFSTEP]
intro h
[GOAL]
case mpr
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
h : ∀ (p : ℕ), Prime p → padicValNat p a = padicValNat p b
⊢ a = b
[PROOFSTEP]
refine' eq_of_factorization_eq ha hb fun p => _
[GOAL]
case mpr
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
h : ∀ (p : ℕ), Prime p → padicValNat p a = padicValNat p b
p : ℕ
⊢ ↑(factorization a) p = ↑(factorization b) p
[PROOFSTEP]
by_cases pp : p.Prime
[GOAL]
case pos
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
h : ∀ (p : ℕ), Prime p → padicValNat p a = padicValNat p b
p : ℕ
pp : Prime p
⊢ ↑(factorization a) p = ↑(factorization b) p
[PROOFSTEP]
simp [factorization_def, pp, h p pp]
[GOAL]
case neg
a b : ℕ
ha : a ≠ 0
hb : b ≠ 0
h : ∀ (p : ℕ), Prime p → padicValNat p a = padicValNat p b
p : ℕ
pp : ¬Prime p
⊢ ↑(factorization a) p = ↑(factorization b) p
[PROOFSTEP]
simp [factorization_eq_zero_of_non_prime, pp]
[GOAL]
n : ℕ
hn : n ≠ 0
m : ℕ
pr : n < m
⊢ ∏ p in Finset.filter Prime (Finset.range m), p ^ padicValNat p n = n
[PROOFSTEP]
conv =>
rhs
rw [← factorization_prod_pow_eq_self hn]
[GOAL]
n : ℕ
hn : n ≠ 0
m : ℕ
pr : n < m
| ∏ p in Finset.filter Prime (Finset.range m), p ^ padicValNat p n = n
[PROOFSTEP]
rhs
rw [← factorization_prod_pow_eq_self hn]
[GOAL]
n : ℕ
hn : n ≠ 0
m : ℕ
pr : n < m
| ∏ p in Finset.filter Prime (Finset.range m), p ^ padicValNat p n = n
[PROOFSTEP]
rhs
rw [← factorization_prod_pow_eq_self hn]
[GOAL]
n : ℕ
hn : n ≠ 0
m : ℕ
pr : n < m
| ∏ p in Finset.filter Prime (Finset.range m), p ^ padicValNat p n = n
[PROOFSTEP]
rhs
[GOAL]
n : ℕ
hn : n ≠ 0
m : ℕ
pr : n < m
| n
[PROOFSTEP]
rw [← factorization_prod_pow_eq_self hn]
[GOAL]
n : ℕ
hn : n ≠ 0
m : ℕ
pr : n < m
⊢ ∏ p in Finset.filter Prime (Finset.range m), p ^ padicValNat p n = Finsupp.prod (factorization n) fun x x_1 => x ^ x_1
[PROOFSTEP]
rw [eq_comm]
[GOAL]
n : ℕ
hn : n ≠ 0
m : ℕ
pr : n < m
⊢ (Finsupp.prod (factorization n) fun x x_1 => x ^ x_1) =
∏ p in Finset.filter Prime (Finset.range m), p ^ padicValNat p n
[PROOFSTEP]
apply Finset.prod_subset_one_on_sdiff
[GOAL]
case h
n : ℕ
hn : n ≠ 0
m : ℕ
pr : n < m
⊢ (factorization n).support ⊆ Finset.filter Prime (Finset.range m)
[PROOFSTEP]
exact fun p hp =>
Finset.mem_filter.mpr
⟨Finset.mem_range.mpr (gt_of_gt_of_ge pr (le_of_mem_factorization hp)), prime_of_mem_factorization hp⟩
[GOAL]
case hg
n : ℕ
hn : n ≠ 0
m : ℕ
pr : n < m
⊢ ∀ (x : ℕ), x ∈ Finset.filter Prime (Finset.range m) \ (factorization n).support → x ^ padicValNat x n = 1
[PROOFSTEP]
intro p hp
[GOAL]
case hg
n : ℕ
hn : n ≠ 0
m : ℕ
pr : n < m
p : ℕ
hp : p ∈ Finset.filter Prime (Finset.range m) \ (factorization n).support
⊢ p ^ padicValNat p n = 1
[PROOFSTEP]
cases' Finset.mem_sdiff.mp hp with hp1 hp2
[GOAL]
case hg.intro
n : ℕ
hn : n ≠ 0
m : ℕ
pr : n < m
p : ℕ
hp : p ∈ Finset.filter Prime (Finset.range m) \ (factorization n).support
hp1 : p ∈ Finset.filter Prime (Finset.range m)
hp2 : ¬p ∈ (factorization n).support
⊢ p ^ padicValNat p n = 1
[PROOFSTEP]
rw [← factorization_def n (Finset.mem_filter.mp hp1).2]
[GOAL]
case hg.intro
n : ℕ
hn : n ≠ 0
m : ℕ
pr : n < m
p : ℕ
hp : p ∈ Finset.filter Prime (Finset.range m) \ (factorization n).support
hp1 : p ∈ Finset.filter Prime (Finset.range m)
hp2 : ¬p ∈ (factorization n).support
⊢ p ^ ↑(factorization n) p = 1
[PROOFSTEP]
simp [Finsupp.not_mem_support_iff.mp hp2]
[GOAL]
case hfg
n : ℕ
hn : n ≠ 0
m : ℕ
pr : n < m
⊢ ∀ (x : ℕ), x ∈ (factorization n).support → (fun x x_1 => x ^ x_1) x (↑(factorization n) x) = x ^ padicValNat x n
[PROOFSTEP]
intro p hp
[GOAL]
case hfg
n : ℕ
hn : n ≠ 0
m : ℕ
pr : n < m
p : ℕ
hp : p ∈ (factorization n).support
⊢ (fun x x_1 => x ^ x_1) p (↑(factorization n) p) = p ^ padicValNat p n
[PROOFSTEP]
simp [factorization_def n (prime_of_mem_factorization hp)]
[GOAL]
n p : ℕ
⊢ card (Finset.filter (fun e => p ∣ e + 1) (Finset.range n)) = n / p
[PROOFSTEP]
induction' n with n hn
[GOAL]
case zero
p : ℕ
⊢ card (Finset.filter (fun e => p ∣ e + 1) (Finset.range zero)) = zero / p
[PROOFSTEP]
simp
[GOAL]
case succ
p n : ℕ
hn : card (Finset.filter (fun e => p ∣ e + 1) (Finset.range n)) = n / p
⊢ card (Finset.filter (fun e => p ∣ e + 1) (Finset.range (succ n))) = succ n / p
[PROOFSTEP]
simp [Nat.succ_div, add_ite, add_zero, Finset.range_succ, filter_insert, apply_ite card, card_insert_of_not_mem, hn]
[GOAL]
n p : ℕ
⊢ card (Finset.filter (fun x => p ∣ x) (Ioc 0 n)) = n / p
[PROOFSTEP]
induction' n with n IH
[GOAL]
case zero
p : ℕ
⊢ card (Finset.filter (fun x => p ∣ x) (Ioc 0 zero)) = zero / p
[PROOFSTEP]
simp
-- TODO: Golf away `h1` after Yaël PRs a lemma asserting this
[GOAL]
case succ
p n : ℕ
IH : card (Finset.filter (fun x => p ∣ x) (Ioc 0 n)) = n / p
⊢ card (Finset.filter (fun x => p ∣ x) (Ioc 0 (succ n))) = succ n / p
[PROOFSTEP]
have h1 : Ioc 0 n.succ = insert n.succ (Ioc 0 n) :=
by
rcases n.eq_zero_or_pos with (rfl | hn)
· simp
simp_rw [← Ico_succ_succ, Ico_insert_right (succ_le_succ hn.le), Ico_succ_right]
[GOAL]
p n : ℕ
IH : card (Finset.filter (fun x => p ∣ x) (Ioc 0 n)) = n / p
⊢ Ioc 0 (succ n) = insert (succ n) (Ioc 0 n)
[PROOFSTEP]
rcases n.eq_zero_or_pos with (rfl | hn)
[GOAL]
case inl
p : ℕ
IH : card (Finset.filter (fun x => p ∣ x) (Ioc 0 0)) = 0 / p
⊢ Ioc 0 (succ 0) = insert (succ 0) (Ioc 0 0)
[PROOFSTEP]
simp
[GOAL]
case inr
p n : ℕ
IH : card (Finset.filter (fun x => p ∣ x) (Ioc 0 n)) = n / p
hn : n > 0
⊢ Ioc 0 (succ n) = insert (succ n) (Ioc 0 n)
[PROOFSTEP]
simp_rw [← Ico_succ_succ, Ico_insert_right (succ_le_succ hn.le), Ico_succ_right]
[GOAL]
case succ
p n : ℕ
IH : card (Finset.filter (fun x => p ∣ x) (Ioc 0 n)) = n / p
h1 : Ioc 0 (succ n) = insert (succ n) (Ioc 0 n)
⊢ card (Finset.filter (fun x => p ∣ x) (Ioc 0 (succ n))) = succ n / p
[PROOFSTEP]
simp [Nat.succ_div, add_ite, add_zero, h1, filter_insert, apply_ite card, card_insert_eq_ite, IH, Finset.mem_filter,
mem_Ioc, not_le.2 (lt_add_one n), Nat.succ_eq_add_one]
|
import PropositionWorld.Level1
import PropositionWorld.Level2
import PropositionWorld.Level3
import PropositionWorld.Level4
import PropositionWorld.Level5
import PropositionWorld.Level6
import PropositionWorld.Level7
import PropositionWorld.Level8
import PropositionWorld.Level9
/-!
# Proposition world.
A Proposition is a true/false statement, like `2 + 2 = 4` or `2 + 2 = 5`.
Just like we can have concrete sets in Lean like `MyNat`, and abstract
sets called things like `X`, we can also have concrete propositions like
`2 + 2 = 5` and abstract propositions called things like `P`.
Mathematicians are very good at conflating a theorem with its proof.
They might say "now use theorem 12 and we're done". What they really
mean is "now use the proof of theorem 12..." (i.e. the fact that we proved
it already). Particularly problematic is the fact that mathematicians
use the word Proposition to mean "a relatively straightforward statement
which is true" and computer scientists use it to mean "a statement of
arbitrary complexity, which might be true or false". Computer scientists
are far more careful about distinguishing between a proposition and a proof.
For example: `x + 0 = x` is a proposition, and `add_zero x`
is its proof. The convention we'll use is capital letters for propositions
and small letters for proofs.
In this world you will see the local context in the following kind of state:
```
P : Prop
p : P
```
Here `P` is the true/false statement (the statement of proposition), and `p` is its proof.
It's like `P` being the set and `p` being the element. In fact, computer scientists
sometimes think about the following analogy: propositions are like sets,
and their proofs are like their elements.
## What's going on in this world?
We're going to learn about manipulating propositions and proofs.
Fortunately, we don't need to learn a bunch of new tactics -- the
ones we just learnt (`exact`, `intro`, `have`, `apply`) will be perfect.
The levels in proposition world are "back to normal", we're proving
theorems, not constructing elements of sets. Or are we?
In Lean, Propositions, like sets, are types, and proofs, like elements of sets, are terms.
Let's get started [Level 1](./PropositionWorld/Level1.lean.md)
-/ |
I’ve been working with several Banshee people this week and we finally got my patch committed. All this patch does is provide a managed event that acts as a PCM and spectrum data source. While simple, it is a required building block for the upcoming OpenVP extension.
Right now I am getting ready for the 0.0.1 release of OpenVP. The version number is intentionally scary; the API is far from stable and will be changing rapidly. The purpose of this release is to provide a stable target for the Banshee extension. Hopefully getting this in Banshee will generate interest in OpenVP, as well as giving Banshee some cool eye-candy. Everybody wins!
My understanding is that after OpenVP 0.0.1 is released and the Banshee.OpenVP extension is finished (it’s proof-of-concept quality right now) it will be absorbed into the Banshee source tree and maintained over there. Which means it will likely come with Banshee 1.4 by default. Awesome. |
{- Type system of the language. -}
module Syntax.Types where
-- Abstract syntax of types for the language.
data Type : Set where
-- Unit type
Unit : Type
-- Product type
_&_ : Type -> Type -> Type
-- Sum type
_+_ : Type -> Type -> Type
-- Function type
_=>_ : Type -> Type -> Type
-- Event type
Event : Type -> Type
-- Signal type
Signal : Type -> Type
infixr 65 _=>_
infixl 68 _+_
infixl 70 _&_
|
peso = 70
altura = 1.70
imc = peso/(altura*altura)
if(imc < 20) {
print("Abaixo do ideal")
} else {
if(imc >= 20 & imc < 30) {
print("Na faixa ideal")
} else {
print("Acima do ideal")
}
}
|
#include <nan.h>
#include "../CGALib/gameinterface.h"
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
using namespace v8;
extern CGA::CGAInterface *g_CGAInterface;
#include "async.h"
void NPCDialogAsyncCallBack(uv_async_t *handle);
class NPCDialogNotifyData : public CBaseNotifyData
{
public:
NPCDialogNotifyData() : CBaseNotifyData(NPCDialogAsyncCallBack)
{
}
CGA::cga_npc_dialog_t m_dlg;
};
boost::shared_mutex g_NPCDialog_Lock;
std::vector<NPCDialogNotifyData *> g_NPCDialog_Asyncs;
void NPCDialogNotify(CGA::cga_npc_dialog_t dlg)
{
boost::unique_lock<boost::shared_mutex> lock(g_NPCDialog_Lock);
for (size_t i = 0; i < g_NPCDialog_Asyncs.size(); ++i)
{
const auto data = g_NPCDialog_Asyncs[i];
data->m_dlg = dlg;
data->m_result = true;
uv_async_send(&data->m_async);
}
g_NPCDialog_Asyncs.clear();
}
void NPCDialogAsyncCallBack(uv_async_t *handle)
{
Isolate* isolate = Isolate::GetCurrent();
HandleScope handle_scope(isolate);
auto data = (NPCDialogNotifyData *)handle->data;
Handle<Value> argv[1];
if (data->m_result)
{
Local<Object> obj = Object::New(isolate);
obj->Set(String::NewFromUtf8(isolate, "type"), Integer::New(isolate, data->m_dlg.type));
obj->Set(String::NewFromUtf8(isolate, "options"), Integer::New(isolate, data->m_dlg.options));
obj->Set(String::NewFromUtf8(isolate, "dialog_id"), Integer::New(isolate, data->m_dlg.dialog_id));
obj->Set(String::NewFromUtf8(isolate, "npc_id"), Integer::New(isolate, data->m_dlg.npc_id));
obj->Set(String::NewFromUtf8(isolate, "message"), Nan::New(data->m_dlg.message).ToLocalChecked());
argv[0] = obj;
}
else
{
argv[0] = Nan::New(false);
}
Local<Function>::New(isolate, data->m_callback)->Call(isolate->GetCurrentContext()->Global(), 1, argv);
data->m_callback.Reset();
uv_timer_stop(&data->m_timer);
uv_close((uv_handle_t*)handle, NULL);
uv_close((uv_handle_t*)&data->m_timer, NULL);
delete handle->data;
}
void NPCDialogTimerCallBack(uv_timer_t *handle)
{
Isolate* isolate = Isolate::GetCurrent();
HandleScope handle_scope(isolate);
auto data = (NPCDialogNotifyData *)handle->data;
Handle<Value> argv[1];
argv[0] = Nan::TypeError("Async callback timeout.");
Local<Function>::New(isolate, data->m_callback)->Call(isolate->GetCurrentContext()->Global(), 1, argv);
data->m_callback.Reset();
{
boost::unique_lock<boost::shared_mutex> lock(g_NPCDialog_Lock);
for (size_t i = 0; i < g_NPCDialog_Asyncs.size(); ++i)
{
if (g_NPCDialog_Asyncs[i] == data)
{
g_NPCDialog_Asyncs.erase(g_NPCDialog_Asyncs.begin() + i);
break;
}
}
}
uv_timer_stop(handle);
uv_close((uv_handle_t*)&data->m_async, NULL);
uv_close((uv_handle_t*)handle, NULL);
delete handle->data;
}
void AsyncWaitNPCDialog(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
Isolate* isolate = info.GetIsolate();
HandleScope handle_scope(isolate);
int timeout = 3000;
if (info.Length() < 1 || !info[0]->IsFunction()) {
Nan::ThrowTypeError("Arg[0] must be a function.");
return;
}
if (info.Length() >= 2 && !info[1]->IsUndefined())
{
timeout = (int)info[1]->IntegerValue();
if (timeout < 0)
timeout = 0;
}
boost::unique_lock<boost::shared_mutex> lock(g_NPCDialog_Lock);
auto callback = Local<Function>::Cast(info[0]);
NPCDialogNotifyData *data = new NPCDialogNotifyData();
data->m_callback.Reset(isolate, callback);
data->m_async.data = data;
data->m_timer.data = data;
g_NPCDialog_Asyncs.push_back(data);
if(timeout)
uv_timer_start(&data->m_timer, NPCDialogTimerCallBack, timeout, 0);
}
void ClickNPCDialog(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
Isolate* isolate = info.GetIsolate();
HandleScope handle_scope(isolate);
if (info.Length() < 1) {
Nan::ThrowTypeError("Arg[0] must be option.");
return;
}
if (info.Length() < 2) {
Nan::ThrowTypeError("Arg[1] must be index.");
return;
}
int option = (int)info[0]->IntegerValue();
int index = (int)info[1]->IntegerValue();
bool bResult = false;
if (!g_CGAInterface->ClickNPCDialog(option, index, bResult))
{
Nan::ThrowError("RPC Invocation failed.");
return;
}
info.GetReturnValue().Set(bResult);
}
void SellNPCStore(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
Isolate* isolate = info.GetIsolate();
HandleScope handle_scope(isolate);
if (info.Length() < 1 || !info[0]->IsArray()) {
Nan::ThrowTypeError("Arg[0] must be an array.");
return;
}
Local<Object> objarr = Local<Object>::Cast(info[0]);
uint32_t length = objarr->Get(Nan::New("length").ToLocalChecked())->Uint32Value();
Local<Array> arr = Local<Array>::Cast(info[0]);
bool bResult = false;
CGA::cga_sell_items_t items;
for (uint32_t i = 0; i < length; ++i)
{
Local<Object> obj = Local<Object>::Cast(arr->Get(i));
Local<Value> obj_itemid = obj->Get(Nan::New("itemid").ToLocalChecked());
Local<Value> obj_itempos = obj->Get(Nan::New("itempos").ToLocalChecked());
Local<Value> obj_count = obj->Get(Nan::New("count").ToLocalChecked());
int itemid = 0;
int itempos = 0;
int count = 0;
if(!obj_itemid->IsUndefined())
itemid = (int)obj_itemid->IntegerValue();
if (!obj_itempos->IsUndefined())
itempos = (int)obj_itempos->IntegerValue();
if (!obj_count->IsUndefined())
count = (int)obj_count->IntegerValue();
if (count > 0)
items.emplace_back(itemid, itempos, count);
}
if (!g_CGAInterface->SellNPCStore(items, bResult))
{
Nan::ThrowError("RPC Invocation failed.");
return;
}
info.GetReturnValue().Set(bResult);
}
void BuyNPCStore(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
Isolate* isolate = info.GetIsolate();
HandleScope handle_scope(isolate);
if (info.Length() < 1 || !info[0]->IsArray()) {
Nan::ThrowTypeError("Arg[0] must be an array.");
return;
}
Local<Object> objarr = Local<Object>::Cast(info[0]);
uint32_t length = objarr->Get(Nan::New("length").ToLocalChecked())->Uint32Value();
Local<Array> arr = Local<Array>::Cast(info[0]);
bool bResult = false;
CGA::cga_buy_items_t items;
for (uint32_t i = 0; i < length; ++i)
{
Local<Object> obj = Local<Object>::Cast(arr->Get(i));
Local<Value> obj_index = obj->Get(Nan::New("index").ToLocalChecked());
Local<Value> obj_count = obj->Get(Nan::New("count").ToLocalChecked());
int index = 0;
int count = 0;
if (!obj_index->IsUndefined())
index = (int)obj_index->IntegerValue();
if (!obj_count->IsUndefined())
count = (int)obj_count->IntegerValue();
if (count > 0)
items.emplace_back(index, count);
}
if (!g_CGAInterface->BuyNPCStore(items, bResult))
{
Nan::ThrowError("RPC Invocation failed.");
return;
}
info.GetReturnValue().Set(bResult);
} |
With mobility making a considerable leap into the technology space in the past five years, it comes as no surprise that HR teams are now looking for software to tackle the challenges posed by increasingly complex programs and the changing business landscape. These technologies bring the traditional programs into the present day and allow mobility teams to focus on the wider business demands such as Brexit and compliance for business travellers.
Join Topia's global mobility experts Gordon Walsh, RVP Customer Success and Ellen Shipley, Customer Success Manager, as they discuss the formation of Topia and its legacy in both technology for managing assignee programs as well as tech enabled relocation management to create the 'Power Couple'. Gordon and Ellen will also be exploring the EMEA mobility market trends they are seeing.
Register now by filling out the adjacent form. |
module Main
import Effects
import Effect.File
import Package
import PackageFormat
data InstallResult = Installed (List Pkg)
| NotReady
| Error String
installable : Pkg -> Bool
installable pkg = (length $ deps pkg) == 0 -- Make an implementation for Eq (List Dep) to speed this up!
--| TODO: Require that the Pkg be proven to be in the range of a PkgConstraint
install : (p : Pkg) -> Either String (IO ())
install pkg = Right $ do putStrLn $ "Cloning package " ++ pname pkg
putStrLn $ "Compiling package " ++ pname pkg
putStrLn $ "Installing package " ++ pname pkg
handle : Either String (IO ()) -> List Pkg -> IO InstallResult
handle (Left msg) pkgs = return $ Error msg
handle (Right eff) pkgs = do eff
putStrLn "Done."
return $ Installed pkgs
prepare : Dep -> List Pkg -> List Pkg -> IO InstallResult
prepare (Dependency s c []) pkgs srcs = case queryPkg s c srcs of
Just pkg => handle (install $ record {deps = []} pkg) (record {deps = []} pkg :: pkgs)
Nothing => return $ Error $ "No package matching " ++ show (Dependency s c []) ++ " is available"
prepare (Dependency s c $ x::xs) pkgs srcs = case queryPkg' x srcs of
Nothing => return $ Error $ "No package matching " ++ show x ++ " is available"
Just pkg => if pkg `elem` pkgs then prepare (Dependency s c xs) pkgs srcs
else do case !(prepare x pkgs srcs) of
Installed pkgs' => prepare (Dependency s c xs) pkgs' srcs
Error msg => return $ Error msg
NotReady => prepare (Dependency s c $ xs ++ [x]) pkgs srcs
where queryPkg' : Dep -> List Pkg -> Maybe Pkg
queryPkg' (Dependency s v _) = queryPkg s v
main : IO ()
main = do let packages = [] -- Represents installed packages on system
let H = Dependency "H" (Up $ V 3 5 0) []
let D = Dependency "D" (Down $ V 1 7 0)
[ Dependency "F" (Exactly $ V 2 4 0) [H]
, Dependency "G" (Between (V 0 0 0) (V 1 0 0)) [H]
]
let C = Dependency "C" Any [D]
let B = Dependency "B" (Exactly $ V 1 4 1)
[ Dependency "E" (Exactly $ V 3 2 1) []
, C
]
let A = Dependency "A" (Exactly $ V 1 2 3) [B, C, D]
let sources = [ Package "H" (V 3 5 1) "" "" "" "" None [] -- Represents database of available packages
, Package "H" (V 3 5 0) "" "" "" "" None []
, Package "D" (V 1 6 7) "" "" "" "" None []
, Package "F" (V 2 4 0) "" "" "" "" None []
, Package "G" (V 0 3 7) "" "" "" "" None []
, Package "C" (V 2 4 3) "" "" "" "" None []
, Package "B" (V 1 4 1) "" "" "" "" None []
, Package "E" (V 3 2 1) "" "" "" "" None []
, Package "A" (V 1 2 3) "" "" "" "" None []]
case !(prepare A packages sources) of
Installed pkgs => putStrLn $ "Successfully installed packages:" ++ show pkgs ++ "."
Error msg => putStrLn $ "Encountered error: '" ++ msg ++ "' while installing packages."
NotReady => putStrLn $ "Could not complete the request at this time. Packages may be broken."
x <- run $ readPackage "pkg"
putStrLn $ show x
|
import os as _os
_on_rtd = _os.environ.get('READTHEDOCS', None) == 'True'
if not _on_rtd:
import numpy as _np
def frexp10(x):
"""
Finds the mantissa and exponent of a number :math:`x` such that :math:`x = m 10^e`.
Parameters
----------
x : float
Number :math:`x` such that :math:`x = m 10^e`.
Returns
-------
mantissa : float
Number :math:`m` such that :math:`x = m 10^e`.
exponent : float
Number :math:`e` such that :math:`x = m 10^e`.
"""
expon = _np.int(_np.floor(_np.log10(_np.abs(x))))
mant = x/_np.power(10, expon)
return (mant, expon)
|
function varargout = erfc(varargin)
%ERFC (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/ERFC CALLED WITH DOUBLE. Report error')
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','none','monotonicity','decreasing','definiteness','positive','model','callback');
operator.bounds = @bounds;
operator.range = [0 2];
operator.derivative =@(x)-exp(-x.^2)*2/sqrt(pi);
operator.inverse = @(x)(erfcinv(x));
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/ERF called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
L = erfc(xU);
U = erfc(xL); |
-- Andreas, 2016-08-01, issue #2125, qualified names in pragmas
{-# OPTIONS --rewriting #-}
import Common.Equality as Eq
{-# BUILTIN REWRITE Eq._≡_ #-} -- qualified name, should be accepted
postulate
A : Set
a b : A
module M where
open Eq
postulate
rule : a ≡ b
{-# REWRITE M.rule #-} -- qualified name, should be accepted
-- ERROR WAS: in the name M.rule, the part M.rule is not valid
-- NOW: works
|
Require Import Coq.Program.Equality.
Require Import Coq.Program.Tactics.
Require Export Needle.
Local Set Asymmetric Patterns.
Section Namespace.
Inductive Namespace : Type :=
| TmVar
| TyVar .
Lemma eq_namespace_dec (a : Namespace) (b : Namespace) :
(sumbool (a = b) (not (a = b))).
Proof.
decide equality .
Defined.
End Namespace.
Section HVarlist.
Inductive Hvl : Type :=
| H0
| HS (a : Namespace) (k : Hvl).
Fixpoint appendHvl (k : Hvl) (k0 : Hvl) {struct k0} :
Hvl :=
match k0 with
| (H0) => k
| (HS a k0) => (HS a (appendHvl k k0))
end.
Lemma appendHvl_assoc :
(forall (k : Hvl) (k0 : Hvl) (k1 : Hvl) ,
((appendHvl (appendHvl k k0) k1) = (appendHvl k (appendHvl k0 k1)))).
Proof.
needleGenericWeakenAppend .
Qed.
End HVarlist.
Section Index.
Inductive Index (a : Namespace) : Type :=
| I0
| IS : (Index a) -> (Index a).
Global Arguments I0 [a] .
Global Arguments IS [a] _ .
Lemma eq_index_dec {a : Namespace} (i : (Index a)) (j : (Index a)) :
(sumbool (i = j) (not (i = j))).
Proof.
decide equality .
Qed.
Fixpoint weakenIndexTmVar (x7 : (Index TmVar)) (k : Hvl) {struct k} :
(Index TmVar) :=
match k with
| (H0) => x7
| (HS a k) => match a with
| (TmVar) => (IS (weakenIndexTmVar x7 k))
| _ => (weakenIndexTmVar x7 k)
end
end.
Fixpoint weakenIndexTyVar (X7 : (Index TyVar)) (k : Hvl) {struct k} :
(Index TyVar) :=
match k with
| (H0) => X7
| (HS a k) => match a with
| (TyVar) => (IS (weakenIndexTyVar X7 k))
| _ => (weakenIndexTyVar X7 k)
end
end.
Lemma weakenIndexTmVar_append :
(forall (x7 : (Index TmVar)) (k : Hvl) (k0 : Hvl) ,
((weakenIndexTmVar (weakenIndexTmVar x7 k) k0) = (weakenIndexTmVar x7 (appendHvl k k0)))).
Proof.
needleGenericWeakenAppend .
Qed.
Lemma weakenIndexTyVar_append :
(forall (X7 : (Index TyVar)) (k : Hvl) (k0 : Hvl) ,
((weakenIndexTyVar (weakenIndexTyVar X7 k) k0) = (weakenIndexTyVar X7 (appendHvl k k0)))).
Proof.
needleGenericWeakenAppend .
Qed.
End Index.
Section Terms.
Inductive Ty : Set :=
| TVar (X : (Index TyVar))
| TArr (T1 : Ty) (T2 : Ty)
| TAll (T : Ty).
Scheme ind_Ty := Induction for Ty Sort Prop.
Inductive Decls : Set :=
| DNil
| DCons (t : Tm) (d : Decls)
with Tm : Set :=
| Var (x : (Index TmVar))
| Abs (T : Ty) (t : Tm)
| App (t1 : Tm) (t2 : Tm)
| TAbs (t : Tm)
| TApp (t : Tm) (T : Ty)
| Let (d : Decls) (t : Tm).
Scheme ind_Decls := Induction for Decls Sort Prop
with ind_Tm := Induction for Tm Sort Prop.
Combined Scheme ind_Decls_Tm from ind_Decls, ind_Tm.
End Terms.
Section Functions.
Fixpoint bind (d4 : Decls) {struct d4} :
Hvl :=
match d4 with
| (DNil) => H0
| (DCons t d) => (appendHvl (HS TmVar H0) (bind d))
end.
Scheme ind_bind_Decls := Induction for Decls Sort Prop.
End Functions.
Section Shift.
Inductive Cutoff (a : Namespace) : Type :=
| C0
| CS : (Cutoff a) -> (Cutoff a).
Global Arguments C0 {a} .
Global Arguments CS {a} _ .
Fixpoint weakenCutoffTmVar (c : (Cutoff TmVar)) (k : Hvl) {struct k} :
(Cutoff TmVar) :=
match k with
| (H0) => c
| (HS a k) => match a with
| (TmVar) => (CS (weakenCutoffTmVar c k))
| _ => (weakenCutoffTmVar c k)
end
end.
Fixpoint weakenCutoffTyVar (c : (Cutoff TyVar)) (k : Hvl) {struct k} :
(Cutoff TyVar) :=
match k with
| (H0) => c
| (HS a k) => match a with
| (TyVar) => (CS (weakenCutoffTyVar c k))
| _ => (weakenCutoffTyVar c k)
end
end.
Lemma weakenCutoffTmVar_append :
(forall (c : (Cutoff TmVar)) (k : Hvl) (k0 : Hvl) ,
((weakenCutoffTmVar (weakenCutoffTmVar c k) k0) = (weakenCutoffTmVar c (appendHvl k k0)))).
Proof.
needleGenericWeakenAppend .
Qed.
Lemma weakenCutoffTyVar_append :
(forall (c : (Cutoff TyVar)) (k : Hvl) (k0 : Hvl) ,
((weakenCutoffTyVar (weakenCutoffTyVar c k) k0) = (weakenCutoffTyVar c (appendHvl k k0)))).
Proof.
needleGenericWeakenAppend .
Qed.
Fixpoint shift_TmVar_Index (c : (Cutoff TmVar)) (x7 : (Index TmVar)) {struct c} :
(Index TmVar) :=
match c with
| (C0) => (IS x7)
| (CS c) => match x7 with
| (I0) => I0
| (IS x7) => (IS (shift_TmVar_Index c x7))
end
end.
Fixpoint shift_TyVar_Index (c : (Cutoff TyVar)) (X7 : (Index TyVar)) {struct c} :
(Index TyVar) :=
match c with
| (C0) => (IS X7)
| (CS c) => match X7 with
| (I0) => I0
| (IS X7) => (IS (shift_TyVar_Index c X7))
end
end.
Fixpoint shift_TyVar_Ty (c : (Cutoff TyVar)) (S0 : Ty) {struct S0} :
Ty :=
match S0 with
| (TVar X7) => (TVar (shift_TyVar_Index c X7))
| (TArr T5 T6) => (TArr (shift_TyVar_Ty c T5) (shift_TyVar_Ty c T6))
| (TAll T7) => (TAll (shift_TyVar_Ty (CS c) T7))
end.
Fixpoint shift_TmVar_Decls (c : (Cutoff TmVar)) (d5 : Decls) {struct d5} :
Decls :=
match d5 with
| (DNil) => (DNil)
| (DCons t7 d6) => (DCons (shift_TmVar_Tm c t7) (shift_TmVar_Decls (CS c) d6))
end
with shift_TmVar_Tm (c : (Cutoff TmVar)) (s : Tm) {struct s} :
Tm :=
match s with
| (Var x7) => (Var (shift_TmVar_Index c x7))
| (Abs T5 t7) => (Abs T5 (shift_TmVar_Tm (CS c) t7))
| (App t8 t9) => (App (shift_TmVar_Tm c t8) (shift_TmVar_Tm c t9))
| (TAbs t10) => (TAbs (shift_TmVar_Tm c t10))
| (TApp t11 T6) => (TApp (shift_TmVar_Tm c t11) T6)
| (Let d5 t12) => (Let (shift_TmVar_Decls c d5) (shift_TmVar_Tm (weakenCutoffTmVar c (appendHvl H0 (bind d5))) t12))
end.
Fixpoint shift_TyVar_Decls (c : (Cutoff TyVar)) (d5 : Decls) {struct d5} :
Decls :=
match d5 with
| (DNil) => (DNil)
| (DCons t7 d6) => (DCons (shift_TyVar_Tm c t7) (shift_TyVar_Decls c d6))
end
with shift_TyVar_Tm (c : (Cutoff TyVar)) (s : Tm) {struct s} :
Tm :=
match s with
| (Var x7) => (Var x7)
| (Abs T5 t7) => (Abs (shift_TyVar_Ty c T5) (shift_TyVar_Tm c t7))
| (App t8 t9) => (App (shift_TyVar_Tm c t8) (shift_TyVar_Tm c t9))
| (TAbs t10) => (TAbs (shift_TyVar_Tm (CS c) t10))
| (TApp t11 T6) => (TApp (shift_TyVar_Tm c t11) (shift_TyVar_Ty c T6))
| (Let d5 t12) => (Let (shift_TyVar_Decls c d5) (shift_TyVar_Tm (weakenCutoffTyVar c (appendHvl H0 (bind d5))) t12))
end.
End Shift.
Section Weaken.
Fixpoint weakenTy (S0 : Ty) (k : Hvl) {struct k} :
Ty :=
match k with
| (H0) => S0
| (HS TmVar k) => (weakenTy S0 k)
| (HS TyVar k) => (shift_TyVar_Ty C0 (weakenTy S0 k))
end.
Fixpoint weakenDecls (d5 : Decls) (k : Hvl) {struct k} :
Decls :=
match k with
| (H0) => d5
| (HS TmVar k) => (shift_TmVar_Decls C0 (weakenDecls d5 k))
| (HS TyVar k) => (shift_TyVar_Decls C0 (weakenDecls d5 k))
end.
Fixpoint weakenTm (s : Tm) (k : Hvl) {struct k} :
Tm :=
match k with
| (H0) => s
| (HS TmVar k) => (shift_TmVar_Tm C0 (weakenTm s k))
| (HS TyVar k) => (shift_TyVar_Tm C0 (weakenTm s k))
end.
End Weaken.
Section Subst.
Inductive Trace (a : Namespace) : Type :=
| X0
| XS (b : Namespace)
(T5 : (Trace a)).
Global Arguments X0 [a] .
Global Arguments XS [a] b _ .
Fixpoint weakenTrace {a : Namespace} (x7 : (Trace a)) (k : Hvl) {struct k} :
(Trace a) :=
match k with
| (H0) => x7
| (HS b k) => (XS b (weakenTrace x7 k))
end.
Lemma weakenTrace_append (a : Namespace) :
(forall (x7 : (Trace a)) (k : Hvl) (k0 : Hvl) ,
((weakenTrace (weakenTrace x7 k) k0) = (weakenTrace x7 (appendHvl k k0)))).
Proof.
needleGenericWeakenAppend .
Qed.
Fixpoint subst_TmVar_Index (d5 : (Trace TmVar)) (s : Tm) (x7 : (Index TmVar)) {struct d5} :
Tm :=
match d5 with
| (X0) => match x7 with
| (I0) => s
| (IS x7) => (Var x7)
end
| (XS TmVar d5) => match x7 with
| (I0) => (Var I0)
| (IS x7) => (shift_TmVar_Tm C0 (subst_TmVar_Index d5 s x7))
end
| (XS TyVar d5) => (shift_TyVar_Tm C0 (subst_TmVar_Index d5 s x7))
end.
Fixpoint subst_TyVar_Index (d5 : (Trace TyVar)) (S0 : Ty) (X7 : (Index TyVar)) {struct d5} :
Ty :=
match d5 with
| (X0) => match X7 with
| (I0) => S0
| (IS X7) => (TVar X7)
end
| (XS TmVar d5) => (subst_TyVar_Index d5 S0 X7)
| (XS TyVar d5) => match X7 with
| (I0) => (TVar I0)
| (IS X7) => (shift_TyVar_Ty C0 (subst_TyVar_Index d5 S0 X7))
end
end.
Fixpoint subst_TyVar_Ty (d5 : (Trace TyVar)) (S0 : Ty) (S1 : Ty) {struct S1} :
Ty :=
match S1 with
| (TVar X7) => (subst_TyVar_Index d5 S0 X7)
| (TArr T5 T6) => (TArr (subst_TyVar_Ty d5 S0 T5) (subst_TyVar_Ty d5 S0 T6))
| (TAll T7) => (TAll (subst_TyVar_Ty (weakenTrace d5 (HS TyVar H0)) S0 T7))
end.
Fixpoint subst_TmVar_Decls (d5 : (Trace TmVar)) (s : Tm) (d6 : Decls) {struct d6} :
Decls :=
match d6 with
| (DNil) => (DNil)
| (DCons t7 d7) => (DCons (subst_TmVar_Tm d5 s t7) (subst_TmVar_Decls (weakenTrace d5 (HS TmVar H0)) s d7))
end
with subst_TmVar_Tm (d5 : (Trace TmVar)) (s : Tm) (s0 : Tm) {struct s0} :
Tm :=
match s0 with
| (Var x7) => (subst_TmVar_Index d5 s x7)
| (Abs T5 t7) => (Abs T5 (subst_TmVar_Tm (weakenTrace d5 (HS TmVar H0)) s t7))
| (App t8 t9) => (App (subst_TmVar_Tm d5 s t8) (subst_TmVar_Tm d5 s t9))
| (TAbs t10) => (TAbs (subst_TmVar_Tm (weakenTrace d5 (HS TyVar H0)) s t10))
| (TApp t11 T6) => (TApp (subst_TmVar_Tm d5 s t11) T6)
| (Let d6 t12) => (Let (subst_TmVar_Decls d5 s d6) (subst_TmVar_Tm (weakenTrace d5 (appendHvl H0 (bind d6))) s t12))
end.
Fixpoint subst_TyVar_Decls (d5 : (Trace TyVar)) (S0 : Ty) (d6 : Decls) {struct d6} :
Decls :=
match d6 with
| (DNil) => (DNil)
| (DCons t7 d7) => (DCons (subst_TyVar_Tm d5 S0 t7) (subst_TyVar_Decls (weakenTrace d5 (HS TmVar H0)) S0 d7))
end
with subst_TyVar_Tm (d5 : (Trace TyVar)) (S0 : Ty) (s : Tm) {struct s} :
Tm :=
match s with
| (Var x7) => (Var x7)
| (Abs T5 t7) => (Abs (subst_TyVar_Ty d5 S0 T5) (subst_TyVar_Tm (weakenTrace d5 (HS TmVar H0)) S0 t7))
| (App t8 t9) => (App (subst_TyVar_Tm d5 S0 t8) (subst_TyVar_Tm d5 S0 t9))
| (TAbs t10) => (TAbs (subst_TyVar_Tm (weakenTrace d5 (HS TyVar H0)) S0 t10))
| (TApp t11 T6) => (TApp (subst_TyVar_Tm d5 S0 t11) (subst_TyVar_Ty d5 S0 T6))
| (Let d6 t12) => (Let (subst_TyVar_Decls d5 S0 d6) (subst_TyVar_Tm (weakenTrace d5 (appendHvl H0 (bind d6))) S0 t12))
end.
End Subst.
Global Hint Resolve (f_equal (shift_TmVar_Decls C0)) : cong_shift0.
Global Hint Resolve (f_equal (shift_TyVar_Decls C0)) : cong_shift0.
Global Hint Resolve (f_equal (shift_TmVar_Tm C0)) : cong_shift0.
Global Hint Resolve (f_equal (shift_TyVar_Tm C0)) : cong_shift0.
Global Hint Resolve (f_equal (shift_TyVar_Ty C0)) : cong_shift0.
Hint Rewrite weakenCutoffTmVar_append weakenCutoffTyVar_append : weakencutoff_append.
Hint Rewrite weakenTrace_append : weakentrace_append.
Lemma stability_shift_TmVar__bind :
(forall (d5 : Decls) ,
(forall (c : (Cutoff TmVar)) ,
((bind (shift_TmVar_Decls c d5)) = (bind d5)))).
Proof.
apply_mutual_ind (ind_bind_Decls); simpl; intros; congruence .
Qed.
Lemma stability_shift_TyVar__bind :
(forall (d6 : Decls) ,
(forall (c0 : (Cutoff TyVar)) ,
((bind (shift_TyVar_Decls c0 d6)) = (bind d6)))).
Proof.
apply_mutual_ind (ind_bind_Decls); simpl; intros; congruence .
Qed.
Hint Rewrite stability_shift_TmVar__bind stability_shift_TyVar__bind : interaction.
Hint Rewrite stability_shift_TmVar__bind stability_shift_TyVar__bind : stability_shift.
Lemma stability_weaken_bind :
(forall (k : Hvl) (d7 : Decls) ,
((bind (weakenDecls d7 k)) = (bind d7))).
Proof.
needleGenericStabilityWeaken .
Qed.
Hint Rewrite stability_weaken_bind : interaction.
Hint Rewrite stability_weaken_bind : stability_weaken.
Lemma stability_subst_TmVar__bind :
(forall (d7 : Decls) ,
(forall (d8 : (Trace TmVar)) (s : Tm) ,
((bind (subst_TmVar_Decls d8 s d7)) = (bind d7)))).
Proof.
apply_mutual_ind (ind_bind_Decls); simpl; intros; congruence .
Qed.
Lemma stability_subst_TyVar__bind :
(forall (d9 : Decls) ,
(forall (d10 : (Trace TyVar)) (S0 : Ty) ,
((bind (subst_TyVar_Decls d10 S0 d9)) = (bind d9)))).
Proof.
apply_mutual_ind (ind_bind_Decls); simpl; intros; congruence .
Qed.
Hint Rewrite stability_subst_TmVar__bind stability_subst_TyVar__bind : interaction.
Hint Rewrite stability_subst_TmVar__bind stability_subst_TyVar__bind : stability_subst.
Section SubstShiftReflection.
Lemma subst_TmVar_Index0_shift_TmVar_Index0_reflection_ind (s0 : Tm) :
(forall (k : Hvl) (x7 : (Index TmVar)) ,
((subst_TmVar_Index (weakenTrace X0 k) s0 (shift_TmVar_Index (weakenCutoffTmVar C0 k) x7)) = (Var x7))).
Proof.
needleGenericSubstIndexShiftIndexReflectionInd .
Qed.
Lemma subst_TyVar_Index0_shift_TyVar_Index0_reflection_ind (S1 : Ty) :
(forall (k : Hvl) (X7 : (Index TyVar)) ,
((subst_TyVar_Index (weakenTrace X0 k) S1 (shift_TyVar_Index (weakenCutoffTyVar C0 k) X7)) = (TVar X7))).
Proof.
needleGenericSubstIndexShiftIndexReflectionInd .
Qed.
Fixpoint subst_TyVar_0_shift_TyVar_0_Ty_reflection_ind (S2 : Ty) (k : Hvl) (S1 : Ty) {struct S2} :
((subst_TyVar_Ty (weakenTrace X0 k) S1 (shift_TyVar_Ty (weakenCutoffTyVar C0 k) S2)) = S2) :=
match S2 return ((subst_TyVar_Ty (weakenTrace X0 k) S1 (shift_TyVar_Ty (weakenCutoffTyVar C0 k) S2)) = S2) with
| (TVar X7) => (subst_TyVar_Index0_shift_TyVar_Index0_reflection_ind S1 k X7)
| (TArr T6 T7) => (f_equal2 TArr (subst_TyVar_0_shift_TyVar_0_Ty_reflection_ind T6 k S1) (subst_TyVar_0_shift_TyVar_0_Ty_reflection_ind T7 k S1))
| (TAll T5) => (f_equal TAll (eq_trans (f_equal3 subst_TyVar_Ty (weakenTrace_append TyVar X0 k (HS TyVar H0)) eq_refl eq_refl) (subst_TyVar_0_shift_TyVar_0_Ty_reflection_ind T5 (HS TyVar k) S1)))
end.
Fixpoint subst_TmVar_0_shift_TmVar_0_Decls_reflection_ind (d11 : Decls) (k : Hvl) (s0 : Tm) {struct d11} :
((subst_TmVar_Decls (weakenTrace X0 k) s0 (shift_TmVar_Decls (weakenCutoffTmVar C0 k) d11)) = d11) :=
match d11 return ((subst_TmVar_Decls (weakenTrace X0 k) s0 (shift_TmVar_Decls (weakenCutoffTmVar C0 k) d11)) = d11) with
| (DNil) => eq_refl
| (DCons t7 d12) => (f_equal2 DCons (subst_TmVar_0_shift_TmVar_0_Tm_reflection_ind t7 k s0) (eq_trans (f_equal3 subst_TmVar_Decls (weakenTrace_append TmVar X0 k (HS TmVar H0)) eq_refl eq_refl) (subst_TmVar_0_shift_TmVar_0_Decls_reflection_ind d12 (HS TmVar k) s0)))
end
with subst_TmVar_0_shift_TmVar_0_Tm_reflection_ind (s1 : Tm) (k : Hvl) (s0 : Tm) {struct s1} :
((subst_TmVar_Tm (weakenTrace X0 k) s0 (shift_TmVar_Tm (weakenCutoffTmVar C0 k) s1)) = s1) :=
match s1 return ((subst_TmVar_Tm (weakenTrace X0 k) s0 (shift_TmVar_Tm (weakenCutoffTmVar C0 k) s1)) = s1) with
| (Var x8) => (subst_TmVar_Index0_shift_TmVar_Index0_reflection_ind s0 k x8)
| (Abs T5 t8) => (f_equal2 Abs eq_refl (eq_trans (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar X0 k (HS TmVar H0)) eq_refl eq_refl) (subst_TmVar_0_shift_TmVar_0_Tm_reflection_ind t8 (HS TmVar k) s0)))
| (App t9 t10) => (f_equal2 App (subst_TmVar_0_shift_TmVar_0_Tm_reflection_ind t9 k s0) (subst_TmVar_0_shift_TmVar_0_Tm_reflection_ind t10 k s0))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar X0 k (HS TyVar H0)) eq_refl eq_refl) (subst_TmVar_0_shift_TmVar_0_Tm_reflection_ind t8 (HS TyVar k) s0)))
| (TApp t8 T5) => (f_equal2 TApp (subst_TmVar_0_shift_TmVar_0_Tm_reflection_ind t8 k s0) eq_refl)
| (Let d13 t8) => (f_equal2 Let (subst_TmVar_0_shift_TmVar_0_Decls_reflection_ind d13 k s0) (eq_trans (f_equal3 subst_TmVar_Tm (eq_trans (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (stability_shift_TmVar__bind _ _))) (weakenTrace_append TmVar X0 k (appendHvl H0 (bind d13)))) eq_refl (f_equal2 shift_TmVar_Tm (weakenCutoffTmVar_append C0 k (appendHvl H0 (bind d13))) eq_refl)) (subst_TmVar_0_shift_TmVar_0_Tm_reflection_ind t8 (appendHvl k (appendHvl H0 (bind d13))) s0)))
end.
Fixpoint subst_TyVar_0_shift_TyVar_0_Decls_reflection_ind (d11 : Decls) (k : Hvl) (S1 : Ty) {struct d11} :
((subst_TyVar_Decls (weakenTrace X0 k) S1 (shift_TyVar_Decls (weakenCutoffTyVar C0 k) d11)) = d11) :=
match d11 return ((subst_TyVar_Decls (weakenTrace X0 k) S1 (shift_TyVar_Decls (weakenCutoffTyVar C0 k) d11)) = d11) with
| (DNil) => eq_refl
| (DCons t7 d12) => (f_equal2 DCons (subst_TyVar_0_shift_TyVar_0_Tm_reflection_ind t7 k S1) (eq_trans (f_equal3 subst_TyVar_Decls (weakenTrace_append TyVar X0 k (HS TmVar H0)) eq_refl eq_refl) (subst_TyVar_0_shift_TyVar_0_Decls_reflection_ind d12 (HS TmVar k) S1)))
end
with subst_TyVar_0_shift_TyVar_0_Tm_reflection_ind (s0 : Tm) (k : Hvl) (S1 : Ty) {struct s0} :
((subst_TyVar_Tm (weakenTrace X0 k) S1 (shift_TyVar_Tm (weakenCutoffTyVar C0 k) s0)) = s0) :=
match s0 return ((subst_TyVar_Tm (weakenTrace X0 k) S1 (shift_TyVar_Tm (weakenCutoffTyVar C0 k) s0)) = s0) with
| (Var x8) => eq_refl
| (Abs T5 t8) => (f_equal2 Abs (subst_TyVar_0_shift_TyVar_0_Ty_reflection_ind T5 k S1) (eq_trans (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar X0 k (HS TmVar H0)) eq_refl eq_refl) (subst_TyVar_0_shift_TyVar_0_Tm_reflection_ind t8 (HS TmVar k) S1)))
| (App t9 t10) => (f_equal2 App (subst_TyVar_0_shift_TyVar_0_Tm_reflection_ind t9 k S1) (subst_TyVar_0_shift_TyVar_0_Tm_reflection_ind t10 k S1))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar X0 k (HS TyVar H0)) eq_refl eq_refl) (subst_TyVar_0_shift_TyVar_0_Tm_reflection_ind t8 (HS TyVar k) S1)))
| (TApp t8 T5) => (f_equal2 TApp (subst_TyVar_0_shift_TyVar_0_Tm_reflection_ind t8 k S1) (subst_TyVar_0_shift_TyVar_0_Ty_reflection_ind T5 k S1))
| (Let d13 t8) => (f_equal2 Let (subst_TyVar_0_shift_TyVar_0_Decls_reflection_ind d13 k S1) (eq_trans (f_equal3 subst_TyVar_Tm (eq_trans (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (stability_shift_TyVar__bind _ _))) (weakenTrace_append TyVar X0 k (appendHvl H0 (bind d13)))) eq_refl (f_equal2 shift_TyVar_Tm (weakenCutoffTyVar_append C0 k (appendHvl H0 (bind d13))) eq_refl)) (subst_TyVar_0_shift_TyVar_0_Tm_reflection_ind t8 (appendHvl k (appendHvl H0 (bind d13))) S1)))
end.
Definition subst_TyVar_Ty0_shift_TyVar_Ty0_reflection (S2 : Ty) : (forall (S1 : Ty) ,
((subst_TyVar_Ty X0 S1 (shift_TyVar_Ty C0 S2)) = S2)) := (subst_TyVar_0_shift_TyVar_0_Ty_reflection_ind S2 H0).
Definition subst_TmVar_Decls0_shift_TmVar_Decls0_reflection (d11 : Decls) : (forall (s0 : Tm) ,
((subst_TmVar_Decls X0 s0 (shift_TmVar_Decls C0 d11)) = d11)) := (subst_TmVar_0_shift_TmVar_0_Decls_reflection_ind d11 H0).
Definition subst_TmVar_Tm0_shift_TmVar_Tm0_reflection (s1 : Tm) : (forall (s0 : Tm) ,
((subst_TmVar_Tm X0 s0 (shift_TmVar_Tm C0 s1)) = s1)) := (subst_TmVar_0_shift_TmVar_0_Tm_reflection_ind s1 H0).
Definition subst_TyVar_Decls0_shift_TyVar_Decls0_reflection (d11 : Decls) : (forall (S1 : Ty) ,
((subst_TyVar_Decls X0 S1 (shift_TyVar_Decls C0 d11)) = d11)) := (subst_TyVar_0_shift_TyVar_0_Decls_reflection_ind d11 H0).
Definition subst_TyVar_Tm0_shift_TyVar_Tm0_reflection (s0 : Tm) : (forall (S1 : Ty) ,
((subst_TyVar_Tm X0 S1 (shift_TyVar_Tm C0 s0)) = s0)) := (subst_TyVar_0_shift_TyVar_0_Tm_reflection_ind s0 H0).
End SubstShiftReflection.
Section ShiftInteraction.
Section ShiftIndexCommInd.
Lemma shift_TmVar_Index_shift_TmVar_Index0_comm_ind :
(forall (k : Hvl) (c1 : (Cutoff TmVar)) (x7 : (Index TmVar)) ,
((shift_TmVar_Index (weakenCutoffTmVar (CS c1) k) (shift_TmVar_Index (weakenCutoffTmVar C0 k) x7)) = (shift_TmVar_Index (weakenCutoffTmVar C0 k) (shift_TmVar_Index (weakenCutoffTmVar c1 k) x7)))).
Proof.
needleGenericShiftIndexCommInd .
Qed.
Lemma shift_TyVar_Index_shift_TyVar_Index0_comm_ind :
(forall (k : Hvl) (c1 : (Cutoff TyVar)) (X7 : (Index TyVar)) ,
((shift_TyVar_Index (weakenCutoffTyVar (CS c1) k) (shift_TyVar_Index (weakenCutoffTyVar C0 k) X7)) = (shift_TyVar_Index (weakenCutoffTyVar C0 k) (shift_TyVar_Index (weakenCutoffTyVar c1 k) X7)))).
Proof.
needleGenericShiftIndexCommInd .
Qed.
End ShiftIndexCommInd.
Section ShiftCommInd.
Fixpoint shift_TyVar__shift_TyVar_0_Ty_comm_ind (S1 : Ty) (k : Hvl) (c1 : (Cutoff TyVar)) {struct S1} :
((shift_TyVar_Ty (weakenCutoffTyVar (CS c1) k) (shift_TyVar_Ty (weakenCutoffTyVar C0 k) S1)) = (shift_TyVar_Ty (weakenCutoffTyVar C0 k) (shift_TyVar_Ty (weakenCutoffTyVar c1 k) S1))) :=
match S1 return ((shift_TyVar_Ty (weakenCutoffTyVar (CS c1) k) (shift_TyVar_Ty (weakenCutoffTyVar C0 k) S1)) = (shift_TyVar_Ty (weakenCutoffTyVar C0 k) (shift_TyVar_Ty (weakenCutoffTyVar c1 k) S1))) with
| (TVar X7) => (f_equal TVar (shift_TyVar_Index_shift_TyVar_Index0_comm_ind k c1 X7))
| (TArr T6 T7) => (f_equal2 TArr (shift_TyVar__shift_TyVar_0_Ty_comm_ind T6 k c1) (shift_TyVar__shift_TyVar_0_Ty_comm_ind T7 k c1))
| (TAll T5) => (f_equal TAll (shift_TyVar__shift_TyVar_0_Ty_comm_ind T5 (HS TyVar k) c1))
end.
Fixpoint shift_TmVar__shift_TmVar_0_Decls_comm_ind (d11 : Decls) (k : Hvl) (c1 : (Cutoff TmVar)) {struct d11} :
((shift_TmVar_Decls (weakenCutoffTmVar (CS c1) k) (shift_TmVar_Decls (weakenCutoffTmVar C0 k) d11)) = (shift_TmVar_Decls (weakenCutoffTmVar C0 k) (shift_TmVar_Decls (weakenCutoffTmVar c1 k) d11))) :=
match d11 return ((shift_TmVar_Decls (weakenCutoffTmVar (CS c1) k) (shift_TmVar_Decls (weakenCutoffTmVar C0 k) d11)) = (shift_TmVar_Decls (weakenCutoffTmVar C0 k) (shift_TmVar_Decls (weakenCutoffTmVar c1 k) d11))) with
| (DNil) => eq_refl
| (DCons t7 d12) => (f_equal2 DCons (shift_TmVar__shift_TmVar_0_Tm_comm_ind t7 k c1) (shift_TmVar__shift_TmVar_0_Decls_comm_ind d12 (HS TmVar k) c1))
end
with shift_TmVar__shift_TmVar_0_Tm_comm_ind (s0 : Tm) (k : Hvl) (c1 : (Cutoff TmVar)) {struct s0} :
((shift_TmVar_Tm (weakenCutoffTmVar (CS c1) k) (shift_TmVar_Tm (weakenCutoffTmVar C0 k) s0)) = (shift_TmVar_Tm (weakenCutoffTmVar C0 k) (shift_TmVar_Tm (weakenCutoffTmVar c1 k) s0))) :=
match s0 return ((shift_TmVar_Tm (weakenCutoffTmVar (CS c1) k) (shift_TmVar_Tm (weakenCutoffTmVar C0 k) s0)) = (shift_TmVar_Tm (weakenCutoffTmVar C0 k) (shift_TmVar_Tm (weakenCutoffTmVar c1 k) s0))) with
| (Var x8) => (f_equal Var (shift_TmVar_Index_shift_TmVar_Index0_comm_ind k c1 x8))
| (Abs T5 t8) => (f_equal2 Abs eq_refl (shift_TmVar__shift_TmVar_0_Tm_comm_ind t8 (HS TmVar k) c1))
| (App t9 t10) => (f_equal2 App (shift_TmVar__shift_TmVar_0_Tm_comm_ind t9 k c1) (shift_TmVar__shift_TmVar_0_Tm_comm_ind t10 k c1))
| (TAbs t8) => (f_equal TAbs (shift_TmVar__shift_TmVar_0_Tm_comm_ind t8 (HS TyVar k) c1))
| (TApp t8 T5) => (f_equal2 TApp (shift_TmVar__shift_TmVar_0_Tm_comm_ind t8 k c1) eq_refl)
| (Let d13 t8) => (f_equal2 Let (shift_TmVar__shift_TmVar_0_Decls_comm_ind d13 k c1) (eq_trans (f_equal2 shift_TmVar_Tm (eq_trans (f_equal2 weakenCutoffTmVar eq_refl (f_equal2 appendHvl (eq_refl H0) (stability_shift_TmVar__bind _ _))) (weakenCutoffTmVar_append (CS c1) k (appendHvl H0 (bind d13)))) (f_equal2 shift_TmVar_Tm (weakenCutoffTmVar_append C0 k (appendHvl H0 (bind d13))) eq_refl)) (eq_trans (shift_TmVar__shift_TmVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d13))) c1) (f_equal2 shift_TmVar_Tm (eq_trans (eq_sym (weakenCutoffTmVar_append C0 k (appendHvl H0 (bind d13)))) (f_equal2 weakenCutoffTmVar eq_refl (f_equal2 appendHvl (eq_refl H0) (eq_sym (stability_shift_TmVar__bind _ _))))) (f_equal2 shift_TmVar_Tm (eq_sym (weakenCutoffTmVar_append c1 k (appendHvl H0 (bind d13)))) eq_refl)))))
end.
Fixpoint shift_TmVar__shift_TyVar_0_Decls_comm_ind (d11 : Decls) (k : Hvl) (c1 : (Cutoff TmVar)) {struct d11} :
((shift_TmVar_Decls (weakenCutoffTmVar c1 k) (shift_TyVar_Decls (weakenCutoffTyVar C0 k) d11)) = (shift_TyVar_Decls (weakenCutoffTyVar C0 k) (shift_TmVar_Decls (weakenCutoffTmVar c1 k) d11))) :=
match d11 return ((shift_TmVar_Decls (weakenCutoffTmVar c1 k) (shift_TyVar_Decls (weakenCutoffTyVar C0 k) d11)) = (shift_TyVar_Decls (weakenCutoffTyVar C0 k) (shift_TmVar_Decls (weakenCutoffTmVar c1 k) d11))) with
| (DNil) => eq_refl
| (DCons t7 d12) => (f_equal2 DCons (shift_TmVar__shift_TyVar_0_Tm_comm_ind t7 k c1) (shift_TmVar__shift_TyVar_0_Decls_comm_ind d12 (HS TmVar k) c1))
end
with shift_TmVar__shift_TyVar_0_Tm_comm_ind (s0 : Tm) (k : Hvl) (c1 : (Cutoff TmVar)) {struct s0} :
((shift_TmVar_Tm (weakenCutoffTmVar c1 k) (shift_TyVar_Tm (weakenCutoffTyVar C0 k) s0)) = (shift_TyVar_Tm (weakenCutoffTyVar C0 k) (shift_TmVar_Tm (weakenCutoffTmVar c1 k) s0))) :=
match s0 return ((shift_TmVar_Tm (weakenCutoffTmVar c1 k) (shift_TyVar_Tm (weakenCutoffTyVar C0 k) s0)) = (shift_TyVar_Tm (weakenCutoffTyVar C0 k) (shift_TmVar_Tm (weakenCutoffTmVar c1 k) s0))) with
| (Var x8) => eq_refl
| (Abs T5 t8) => (f_equal2 Abs eq_refl (shift_TmVar__shift_TyVar_0_Tm_comm_ind t8 (HS TmVar k) c1))
| (App t9 t10) => (f_equal2 App (shift_TmVar__shift_TyVar_0_Tm_comm_ind t9 k c1) (shift_TmVar__shift_TyVar_0_Tm_comm_ind t10 k c1))
| (TAbs t8) => (f_equal TAbs (shift_TmVar__shift_TyVar_0_Tm_comm_ind t8 (HS TyVar k) c1))
| (TApp t8 T5) => (f_equal2 TApp (shift_TmVar__shift_TyVar_0_Tm_comm_ind t8 k c1) eq_refl)
| (Let d13 t8) => (f_equal2 Let (shift_TmVar__shift_TyVar_0_Decls_comm_ind d13 k c1) (eq_trans (f_equal2 shift_TmVar_Tm (eq_trans (f_equal2 weakenCutoffTmVar eq_refl (f_equal2 appendHvl (eq_refl H0) (stability_shift_TyVar__bind _ _))) (weakenCutoffTmVar_append c1 k (appendHvl H0 (bind d13)))) (f_equal2 shift_TyVar_Tm (weakenCutoffTyVar_append C0 k (appendHvl H0 (bind d13))) eq_refl)) (eq_trans (shift_TmVar__shift_TyVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d13))) c1) (f_equal2 shift_TyVar_Tm (eq_trans (eq_sym (weakenCutoffTyVar_append C0 k (appendHvl H0 (bind d13)))) (f_equal2 weakenCutoffTyVar eq_refl (f_equal2 appendHvl (eq_refl H0) (eq_sym (stability_shift_TmVar__bind _ _))))) (f_equal2 shift_TmVar_Tm (eq_sym (weakenCutoffTmVar_append c1 k (appendHvl H0 (bind d13)))) eq_refl)))))
end.
Fixpoint shift_TyVar__shift_TmVar_0_Decls_comm_ind (d11 : Decls) (k : Hvl) (c1 : (Cutoff TyVar)) {struct d11} :
((shift_TyVar_Decls (weakenCutoffTyVar c1 k) (shift_TmVar_Decls (weakenCutoffTmVar C0 k) d11)) = (shift_TmVar_Decls (weakenCutoffTmVar C0 k) (shift_TyVar_Decls (weakenCutoffTyVar c1 k) d11))) :=
match d11 return ((shift_TyVar_Decls (weakenCutoffTyVar c1 k) (shift_TmVar_Decls (weakenCutoffTmVar C0 k) d11)) = (shift_TmVar_Decls (weakenCutoffTmVar C0 k) (shift_TyVar_Decls (weakenCutoffTyVar c1 k) d11))) with
| (DNil) => eq_refl
| (DCons t7 d12) => (f_equal2 DCons (shift_TyVar__shift_TmVar_0_Tm_comm_ind t7 k c1) (shift_TyVar__shift_TmVar_0_Decls_comm_ind d12 (HS TmVar k) c1))
end
with shift_TyVar__shift_TmVar_0_Tm_comm_ind (s0 : Tm) (k : Hvl) (c1 : (Cutoff TyVar)) {struct s0} :
((shift_TyVar_Tm (weakenCutoffTyVar c1 k) (shift_TmVar_Tm (weakenCutoffTmVar C0 k) s0)) = (shift_TmVar_Tm (weakenCutoffTmVar C0 k) (shift_TyVar_Tm (weakenCutoffTyVar c1 k) s0))) :=
match s0 return ((shift_TyVar_Tm (weakenCutoffTyVar c1 k) (shift_TmVar_Tm (weakenCutoffTmVar C0 k) s0)) = (shift_TmVar_Tm (weakenCutoffTmVar C0 k) (shift_TyVar_Tm (weakenCutoffTyVar c1 k) s0))) with
| (Var x8) => eq_refl
| (Abs T5 t8) => (f_equal2 Abs eq_refl (shift_TyVar__shift_TmVar_0_Tm_comm_ind t8 (HS TmVar k) c1))
| (App t9 t10) => (f_equal2 App (shift_TyVar__shift_TmVar_0_Tm_comm_ind t9 k c1) (shift_TyVar__shift_TmVar_0_Tm_comm_ind t10 k c1))
| (TAbs t8) => (f_equal TAbs (shift_TyVar__shift_TmVar_0_Tm_comm_ind t8 (HS TyVar k) c1))
| (TApp t8 T5) => (f_equal2 TApp (shift_TyVar__shift_TmVar_0_Tm_comm_ind t8 k c1) eq_refl)
| (Let d13 t8) => (f_equal2 Let (shift_TyVar__shift_TmVar_0_Decls_comm_ind d13 k c1) (eq_trans (f_equal2 shift_TyVar_Tm (eq_trans (f_equal2 weakenCutoffTyVar eq_refl (f_equal2 appendHvl (eq_refl H0) (stability_shift_TmVar__bind _ _))) (weakenCutoffTyVar_append c1 k (appendHvl H0 (bind d13)))) (f_equal2 shift_TmVar_Tm (weakenCutoffTmVar_append C0 k (appendHvl H0 (bind d13))) eq_refl)) (eq_trans (shift_TyVar__shift_TmVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d13))) c1) (f_equal2 shift_TmVar_Tm (eq_trans (eq_sym (weakenCutoffTmVar_append C0 k (appendHvl H0 (bind d13)))) (f_equal2 weakenCutoffTmVar eq_refl (f_equal2 appendHvl (eq_refl H0) (eq_sym (stability_shift_TyVar__bind _ _))))) (f_equal2 shift_TyVar_Tm (eq_sym (weakenCutoffTyVar_append c1 k (appendHvl H0 (bind d13)))) eq_refl)))))
end.
Fixpoint shift_TyVar__shift_TyVar_0_Decls_comm_ind (d11 : Decls) (k : Hvl) (c1 : (Cutoff TyVar)) {struct d11} :
((shift_TyVar_Decls (weakenCutoffTyVar (CS c1) k) (shift_TyVar_Decls (weakenCutoffTyVar C0 k) d11)) = (shift_TyVar_Decls (weakenCutoffTyVar C0 k) (shift_TyVar_Decls (weakenCutoffTyVar c1 k) d11))) :=
match d11 return ((shift_TyVar_Decls (weakenCutoffTyVar (CS c1) k) (shift_TyVar_Decls (weakenCutoffTyVar C0 k) d11)) = (shift_TyVar_Decls (weakenCutoffTyVar C0 k) (shift_TyVar_Decls (weakenCutoffTyVar c1 k) d11))) with
| (DNil) => eq_refl
| (DCons t7 d12) => (f_equal2 DCons (shift_TyVar__shift_TyVar_0_Tm_comm_ind t7 k c1) (shift_TyVar__shift_TyVar_0_Decls_comm_ind d12 (HS TmVar k) c1))
end
with shift_TyVar__shift_TyVar_0_Tm_comm_ind (s0 : Tm) (k : Hvl) (c1 : (Cutoff TyVar)) {struct s0} :
((shift_TyVar_Tm (weakenCutoffTyVar (CS c1) k) (shift_TyVar_Tm (weakenCutoffTyVar C0 k) s0)) = (shift_TyVar_Tm (weakenCutoffTyVar C0 k) (shift_TyVar_Tm (weakenCutoffTyVar c1 k) s0))) :=
match s0 return ((shift_TyVar_Tm (weakenCutoffTyVar (CS c1) k) (shift_TyVar_Tm (weakenCutoffTyVar C0 k) s0)) = (shift_TyVar_Tm (weakenCutoffTyVar C0 k) (shift_TyVar_Tm (weakenCutoffTyVar c1 k) s0))) with
| (Var x8) => eq_refl
| (Abs T5 t8) => (f_equal2 Abs (shift_TyVar__shift_TyVar_0_Ty_comm_ind T5 k c1) (shift_TyVar__shift_TyVar_0_Tm_comm_ind t8 (HS TmVar k) c1))
| (App t9 t10) => (f_equal2 App (shift_TyVar__shift_TyVar_0_Tm_comm_ind t9 k c1) (shift_TyVar__shift_TyVar_0_Tm_comm_ind t10 k c1))
| (TAbs t8) => (f_equal TAbs (shift_TyVar__shift_TyVar_0_Tm_comm_ind t8 (HS TyVar k) c1))
| (TApp t8 T5) => (f_equal2 TApp (shift_TyVar__shift_TyVar_0_Tm_comm_ind t8 k c1) (shift_TyVar__shift_TyVar_0_Ty_comm_ind T5 k c1))
| (Let d13 t8) => (f_equal2 Let (shift_TyVar__shift_TyVar_0_Decls_comm_ind d13 k c1) (eq_trans (f_equal2 shift_TyVar_Tm (eq_trans (f_equal2 weakenCutoffTyVar eq_refl (f_equal2 appendHvl (eq_refl H0) (stability_shift_TyVar__bind _ _))) (weakenCutoffTyVar_append (CS c1) k (appendHvl H0 (bind d13)))) (f_equal2 shift_TyVar_Tm (weakenCutoffTyVar_append C0 k (appendHvl H0 (bind d13))) eq_refl)) (eq_trans (shift_TyVar__shift_TyVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d13))) c1) (f_equal2 shift_TyVar_Tm (eq_trans (eq_sym (weakenCutoffTyVar_append C0 k (appendHvl H0 (bind d13)))) (f_equal2 weakenCutoffTyVar eq_refl (f_equal2 appendHvl (eq_refl H0) (eq_sym (stability_shift_TyVar__bind _ _))))) (f_equal2 shift_TyVar_Tm (eq_sym (weakenCutoffTyVar_append c1 k (appendHvl H0 (bind d13)))) eq_refl)))))
end.
End ShiftCommInd.
Section ShiftComm.
Definition shift_TyVar__shift_TyVar_0_Ty_comm (S1 : Ty) : (forall (c1 : (Cutoff TyVar)) ,
((shift_TyVar_Ty (CS c1) (shift_TyVar_Ty C0 S1)) = (shift_TyVar_Ty C0 (shift_TyVar_Ty c1 S1)))) := (shift_TyVar__shift_TyVar_0_Ty_comm_ind S1 H0).
Definition shift_TmVar__shift_TmVar_0_Decls_comm (d11 : Decls) : (forall (c1 : (Cutoff TmVar)) ,
((shift_TmVar_Decls (CS c1) (shift_TmVar_Decls C0 d11)) = (shift_TmVar_Decls C0 (shift_TmVar_Decls c1 d11)))) := (shift_TmVar__shift_TmVar_0_Decls_comm_ind d11 H0).
Definition shift_TmVar__shift_TmVar_0_Tm_comm (s0 : Tm) : (forall (c1 : (Cutoff TmVar)) ,
((shift_TmVar_Tm (CS c1) (shift_TmVar_Tm C0 s0)) = (shift_TmVar_Tm C0 (shift_TmVar_Tm c1 s0)))) := (shift_TmVar__shift_TmVar_0_Tm_comm_ind s0 H0).
Definition shift_TmVar__shift_TyVar_0_Decls_comm (d11 : Decls) : (forall (c1 : (Cutoff TmVar)) ,
((shift_TmVar_Decls c1 (shift_TyVar_Decls C0 d11)) = (shift_TyVar_Decls C0 (shift_TmVar_Decls c1 d11)))) := (shift_TmVar__shift_TyVar_0_Decls_comm_ind d11 H0).
Definition shift_TmVar__shift_TyVar_0_Tm_comm (s0 : Tm) : (forall (c1 : (Cutoff TmVar)) ,
((shift_TmVar_Tm c1 (shift_TyVar_Tm C0 s0)) = (shift_TyVar_Tm C0 (shift_TmVar_Tm c1 s0)))) := (shift_TmVar__shift_TyVar_0_Tm_comm_ind s0 H0).
Definition shift_TyVar__shift_TmVar_0_Decls_comm (d11 : Decls) : (forall (c1 : (Cutoff TyVar)) ,
((shift_TyVar_Decls c1 (shift_TmVar_Decls C0 d11)) = (shift_TmVar_Decls C0 (shift_TyVar_Decls c1 d11)))) := (shift_TyVar__shift_TmVar_0_Decls_comm_ind d11 H0).
Definition shift_TyVar__shift_TmVar_0_Tm_comm (s0 : Tm) : (forall (c1 : (Cutoff TyVar)) ,
((shift_TyVar_Tm c1 (shift_TmVar_Tm C0 s0)) = (shift_TmVar_Tm C0 (shift_TyVar_Tm c1 s0)))) := (shift_TyVar__shift_TmVar_0_Tm_comm_ind s0 H0).
Definition shift_TyVar__shift_TyVar_0_Decls_comm (d11 : Decls) : (forall (c1 : (Cutoff TyVar)) ,
((shift_TyVar_Decls (CS c1) (shift_TyVar_Decls C0 d11)) = (shift_TyVar_Decls C0 (shift_TyVar_Decls c1 d11)))) := (shift_TyVar__shift_TyVar_0_Decls_comm_ind d11 H0).
Definition shift_TyVar__shift_TyVar_0_Tm_comm (s0 : Tm) : (forall (c1 : (Cutoff TyVar)) ,
((shift_TyVar_Tm (CS c1) (shift_TyVar_Tm C0 s0)) = (shift_TyVar_Tm C0 (shift_TyVar_Tm c1 s0)))) := (shift_TyVar__shift_TyVar_0_Tm_comm_ind s0 H0).
End ShiftComm.
End ShiftInteraction.
Hint Rewrite shift_TmVar__shift_TmVar_0_Decls_comm shift_TmVar__shift_TyVar_0_Decls_comm shift_TyVar__shift_TmVar_0_Decls_comm shift_TyVar__shift_TyVar_0_Decls_comm shift_TmVar__shift_TmVar_0_Tm_comm shift_TmVar__shift_TyVar_0_Tm_comm shift_TyVar__shift_TmVar_0_Tm_comm shift_TyVar__shift_TyVar_0_Tm_comm shift_TyVar__shift_TyVar_0_Ty_comm : interaction.
Hint Rewrite shift_TmVar__shift_TmVar_0_Decls_comm shift_TmVar__shift_TyVar_0_Decls_comm shift_TyVar__shift_TmVar_0_Decls_comm shift_TyVar__shift_TyVar_0_Decls_comm shift_TmVar__shift_TmVar_0_Tm_comm shift_TmVar__shift_TyVar_0_Tm_comm shift_TyVar__shift_TmVar_0_Tm_comm shift_TyVar__shift_TyVar_0_Tm_comm shift_TyVar__shift_TyVar_0_Ty_comm : shift_shift0.
Section WeakenShift.
Lemma weakenTy_shift_TyVar_Ty :
(forall (k : Hvl) (c1 : (Cutoff TyVar)) (S1 : Ty) ,
((weakenTy (shift_TyVar_Ty c1 S1) k) = (shift_TyVar_Ty (weakenCutoffTyVar c1 k) (weakenTy S1 k)))).
Proof.
needleGenericWeakenShift .
Qed.
Lemma weakenDecls_shift_TmVar_Decls :
(forall (k : Hvl) (c1 : (Cutoff TmVar)) (d11 : Decls) ,
((weakenDecls (shift_TmVar_Decls c1 d11) k) = (shift_TmVar_Decls (weakenCutoffTmVar c1 k) (weakenDecls d11 k)))).
Proof.
needleGenericWeakenShift .
Qed.
Lemma weakenTm_shift_TmVar_Tm :
(forall (k : Hvl) (c1 : (Cutoff TmVar)) (s0 : Tm) ,
((weakenTm (shift_TmVar_Tm c1 s0) k) = (shift_TmVar_Tm (weakenCutoffTmVar c1 k) (weakenTm s0 k)))).
Proof.
needleGenericWeakenShift .
Qed.
Lemma weakenDecls_shift_TyVar_Decls :
(forall (k : Hvl) (c1 : (Cutoff TyVar)) (d11 : Decls) ,
((weakenDecls (shift_TyVar_Decls c1 d11) k) = (shift_TyVar_Decls (weakenCutoffTyVar c1 k) (weakenDecls d11 k)))).
Proof.
needleGenericWeakenShift .
Qed.
Lemma weakenTm_shift_TyVar_Tm :
(forall (k : Hvl) (c1 : (Cutoff TyVar)) (s0 : Tm) ,
((weakenTm (shift_TyVar_Tm c1 s0) k) = (shift_TyVar_Tm (weakenCutoffTyVar c1 k) (weakenTm s0 k)))).
Proof.
needleGenericWeakenShift .
Qed.
End WeakenShift.
Section ShiftSubstInteraction.
Section ShiftSubstIndexCommInd.
Lemma shift_TmVar_Tm_subst_TmVar_Index0_comm_ind (c1 : (Cutoff TmVar)) (s0 : Tm) :
(forall (k : Hvl) (x7 : (Index TmVar)) ,
((shift_TmVar_Tm (weakenCutoffTmVar c1 k) (subst_TmVar_Index (weakenTrace X0 k) s0 x7)) = (subst_TmVar_Index (weakenTrace X0 k) (shift_TmVar_Tm c1 s0) (shift_TmVar_Index (weakenCutoffTmVar (CS c1) k) x7)))).
Proof.
needleGenericShiftSubstIndexCommInd .
Qed.
Lemma shift_TyVar_Tm_subst_TmVar_Index0_comm_ind (c1 : (Cutoff TyVar)) (s0 : Tm) :
(forall (k : Hvl) (x7 : (Index TmVar)) ,
((shift_TyVar_Tm (weakenCutoffTyVar c1 k) (subst_TmVar_Index (weakenTrace X0 k) s0 x7)) = (subst_TmVar_Index (weakenTrace X0 k) (shift_TyVar_Tm c1 s0) x7))).
Proof.
needleGenericShiftSubstIndexCommInd .
Qed.
Lemma shift_TyVar_Ty_subst_TyVar_Index0_comm_ind (c1 : (Cutoff TyVar)) (S1 : Ty) :
(forall (k : Hvl) (X7 : (Index TyVar)) ,
((shift_TyVar_Ty (weakenCutoffTyVar c1 k) (subst_TyVar_Index (weakenTrace X0 k) S1 X7)) = (subst_TyVar_Index (weakenTrace X0 k) (shift_TyVar_Ty c1 S1) (shift_TyVar_Index (weakenCutoffTyVar (CS c1) k) X7)))).
Proof.
needleGenericShiftSubstIndexCommInd .
Qed.
End ShiftSubstIndexCommInd.
Section ShiftSubstCommInd.
Fixpoint shift_TyVar__subst_TyVar_0_Ty_comm_ind (S2 : Ty) (k : Hvl) (c1 : (Cutoff TyVar)) (S1 : Ty) {struct S2} :
((shift_TyVar_Ty (weakenCutoffTyVar c1 k) (subst_TyVar_Ty (weakenTrace X0 k) S1 S2)) = (subst_TyVar_Ty (weakenTrace X0 k) (shift_TyVar_Ty c1 S1) (shift_TyVar_Ty (weakenCutoffTyVar (CS c1) k) S2))) :=
match S2 return ((shift_TyVar_Ty (weakenCutoffTyVar c1 k) (subst_TyVar_Ty (weakenTrace X0 k) S1 S2)) = (subst_TyVar_Ty (weakenTrace X0 k) (shift_TyVar_Ty c1 S1) (shift_TyVar_Ty (weakenCutoffTyVar (CS c1) k) S2))) with
| (TVar X7) => (shift_TyVar_Ty_subst_TyVar_Index0_comm_ind c1 S1 k X7)
| (TArr T6 T7) => (f_equal2 TArr (shift_TyVar__subst_TyVar_0_Ty_comm_ind T6 k c1 S1) (shift_TyVar__subst_TyVar_0_Ty_comm_ind T7 k c1 S1))
| (TAll T5) => (f_equal TAll (eq_trans (f_equal2 shift_TyVar_Ty eq_refl (f_equal3 subst_TyVar_Ty (weakenTrace_append TyVar X0 k (HS TyVar H0)) eq_refl eq_refl)) (eq_trans (shift_TyVar__subst_TyVar_0_Ty_comm_ind T5 (HS TyVar k) c1 S1) (f_equal3 subst_TyVar_Ty (eq_sym (weakenTrace_append TyVar X0 k (HS TyVar H0))) eq_refl eq_refl))))
end.
Fixpoint shift_TmVar__subst_TmVar_0_Decls_comm_ind (d11 : Decls) (k : Hvl) (c1 : (Cutoff TmVar)) (s0 : Tm) {struct d11} :
((shift_TmVar_Decls (weakenCutoffTmVar c1 k) (subst_TmVar_Decls (weakenTrace X0 k) s0 d11)) = (subst_TmVar_Decls (weakenTrace X0 k) (shift_TmVar_Tm c1 s0) (shift_TmVar_Decls (weakenCutoffTmVar (CS c1) k) d11))) :=
match d11 return ((shift_TmVar_Decls (weakenCutoffTmVar c1 k) (subst_TmVar_Decls (weakenTrace X0 k) s0 d11)) = (subst_TmVar_Decls (weakenTrace X0 k) (shift_TmVar_Tm c1 s0) (shift_TmVar_Decls (weakenCutoffTmVar (CS c1) k) d11))) with
| (DNil) => eq_refl
| (DCons t7 d12) => (f_equal2 DCons (shift_TmVar__subst_TmVar_0_Tm_comm_ind t7 k c1 s0) (eq_trans (f_equal2 shift_TmVar_Decls eq_refl (f_equal3 subst_TmVar_Decls (weakenTrace_append TmVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (shift_TmVar__subst_TmVar_0_Decls_comm_ind d12 (HS TmVar k) c1 s0) (f_equal3 subst_TmVar_Decls (eq_sym (weakenTrace_append TmVar X0 k (HS TmVar H0))) eq_refl eq_refl))))
end
with shift_TmVar__subst_TmVar_0_Tm_comm_ind (s1 : Tm) (k : Hvl) (c1 : (Cutoff TmVar)) (s0 : Tm) {struct s1} :
((shift_TmVar_Tm (weakenCutoffTmVar c1 k) (subst_TmVar_Tm (weakenTrace X0 k) s0 s1)) = (subst_TmVar_Tm (weakenTrace X0 k) (shift_TmVar_Tm c1 s0) (shift_TmVar_Tm (weakenCutoffTmVar (CS c1) k) s1))) :=
match s1 return ((shift_TmVar_Tm (weakenCutoffTmVar c1 k) (subst_TmVar_Tm (weakenTrace X0 k) s0 s1)) = (subst_TmVar_Tm (weakenTrace X0 k) (shift_TmVar_Tm c1 s0) (shift_TmVar_Tm (weakenCutoffTmVar (CS c1) k) s1))) with
| (Var x8) => (shift_TmVar_Tm_subst_TmVar_Index0_comm_ind c1 s0 k x8)
| (Abs T5 t8) => (f_equal2 Abs eq_refl (eq_trans (f_equal2 shift_TmVar_Tm eq_refl (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (shift_TmVar__subst_TmVar_0_Tm_comm_ind t8 (HS TmVar k) c1 s0) (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar X0 k (HS TmVar H0))) eq_refl eq_refl))))
| (App t9 t10) => (f_equal2 App (shift_TmVar__subst_TmVar_0_Tm_comm_ind t9 k c1 s0) (shift_TmVar__subst_TmVar_0_Tm_comm_ind t10 k c1 s0))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal2 shift_TmVar_Tm eq_refl (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar X0 k (HS TyVar H0)) eq_refl eq_refl)) (eq_trans (shift_TmVar__subst_TmVar_0_Tm_comm_ind t8 (HS TyVar k) c1 s0) (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar X0 k (HS TyVar H0))) eq_refl eq_refl))))
| (TApp t8 T5) => (f_equal2 TApp (shift_TmVar__subst_TmVar_0_Tm_comm_ind t8 k c1 s0) eq_refl)
| (Let d13 t8) => (f_equal2 Let (shift_TmVar__subst_TmVar_0_Decls_comm_ind d13 k c1 s0) (eq_trans (f_equal2 shift_TmVar_Tm (eq_trans (f_equal2 weakenCutoffTmVar eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (stability_subst_TmVar__bind _ _ _) (eq_refl H0)))) (weakenCutoffTmVar_append c1 k (appendHvl H0 (bind d13)))) (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar X0 k (appendHvl H0 (bind d13))) eq_refl eq_refl)) (eq_trans (shift_TmVar__subst_TmVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d13))) c1 s0) (f_equal3 subst_TmVar_Tm (eq_trans (eq_sym (weakenTrace_append TmVar X0 k (appendHvl H0 (bind d13)))) (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (eq_sym (stability_shift_TmVar__bind _ _))))) eq_refl (f_equal2 shift_TmVar_Tm (eq_sym (weakenCutoffTmVar_append (CS c1) k (appendHvl H0 (bind d13)))) eq_refl)))))
end.
Fixpoint shift_TmVar__subst_TyVar_0_Decls_comm_ind (d11 : Decls) (k : Hvl) (c1 : (Cutoff TmVar)) (S1 : Ty) {struct d11} :
((shift_TmVar_Decls (weakenCutoffTmVar c1 k) (subst_TyVar_Decls (weakenTrace X0 k) S1 d11)) = (subst_TyVar_Decls (weakenTrace X0 k) S1 (shift_TmVar_Decls (weakenCutoffTmVar c1 k) d11))) :=
match d11 return ((shift_TmVar_Decls (weakenCutoffTmVar c1 k) (subst_TyVar_Decls (weakenTrace X0 k) S1 d11)) = (subst_TyVar_Decls (weakenTrace X0 k) S1 (shift_TmVar_Decls (weakenCutoffTmVar c1 k) d11))) with
| (DNil) => eq_refl
| (DCons t7 d12) => (f_equal2 DCons (shift_TmVar__subst_TyVar_0_Tm_comm_ind t7 k c1 S1) (eq_trans (f_equal2 shift_TmVar_Decls eq_refl (f_equal3 subst_TyVar_Decls (weakenTrace_append TyVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (shift_TmVar__subst_TyVar_0_Decls_comm_ind d12 (HS TmVar k) c1 S1) (f_equal3 subst_TyVar_Decls (eq_sym (weakenTrace_append TyVar X0 k (HS TmVar H0))) eq_refl eq_refl))))
end
with shift_TmVar__subst_TyVar_0_Tm_comm_ind (s0 : Tm) (k : Hvl) (c1 : (Cutoff TmVar)) (S1 : Ty) {struct s0} :
((shift_TmVar_Tm (weakenCutoffTmVar c1 k) (subst_TyVar_Tm (weakenTrace X0 k) S1 s0)) = (subst_TyVar_Tm (weakenTrace X0 k) S1 (shift_TmVar_Tm (weakenCutoffTmVar c1 k) s0))) :=
match s0 return ((shift_TmVar_Tm (weakenCutoffTmVar c1 k) (subst_TyVar_Tm (weakenTrace X0 k) S1 s0)) = (subst_TyVar_Tm (weakenTrace X0 k) S1 (shift_TmVar_Tm (weakenCutoffTmVar c1 k) s0))) with
| (Var x8) => eq_refl
| (Abs T5 t8) => (f_equal2 Abs eq_refl (eq_trans (f_equal2 shift_TmVar_Tm eq_refl (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (shift_TmVar__subst_TyVar_0_Tm_comm_ind t8 (HS TmVar k) c1 S1) (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar X0 k (HS TmVar H0))) eq_refl eq_refl))))
| (App t9 t10) => (f_equal2 App (shift_TmVar__subst_TyVar_0_Tm_comm_ind t9 k c1 S1) (shift_TmVar__subst_TyVar_0_Tm_comm_ind t10 k c1 S1))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal2 shift_TmVar_Tm eq_refl (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar X0 k (HS TyVar H0)) eq_refl eq_refl)) (eq_trans (shift_TmVar__subst_TyVar_0_Tm_comm_ind t8 (HS TyVar k) c1 S1) (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar X0 k (HS TyVar H0))) eq_refl eq_refl))))
| (TApp t8 T5) => (f_equal2 TApp (shift_TmVar__subst_TyVar_0_Tm_comm_ind t8 k c1 S1) eq_refl)
| (Let d13 t8) => (f_equal2 Let (shift_TmVar__subst_TyVar_0_Decls_comm_ind d13 k c1 S1) (eq_trans (f_equal2 shift_TmVar_Tm (eq_trans (f_equal2 weakenCutoffTmVar eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (stability_subst_TyVar__bind _ _ _) (eq_refl H0)))) (weakenCutoffTmVar_append c1 k (appendHvl H0 (bind d13)))) (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar X0 k (appendHvl H0 (bind d13))) eq_refl eq_refl)) (eq_trans (shift_TmVar__subst_TyVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d13))) c1 S1) (f_equal3 subst_TyVar_Tm (eq_trans (eq_sym (weakenTrace_append TyVar X0 k (appendHvl H0 (bind d13)))) (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (eq_sym (stability_shift_TmVar__bind _ _))))) eq_refl (f_equal2 shift_TmVar_Tm (eq_sym (weakenCutoffTmVar_append c1 k (appendHvl H0 (bind d13)))) eq_refl)))))
end.
Fixpoint shift_TyVar__subst_TmVar_0_Decls_comm_ind (d11 : Decls) (k : Hvl) (c1 : (Cutoff TyVar)) (s0 : Tm) {struct d11} :
((shift_TyVar_Decls (weakenCutoffTyVar c1 k) (subst_TmVar_Decls (weakenTrace X0 k) s0 d11)) = (subst_TmVar_Decls (weakenTrace X0 k) (shift_TyVar_Tm c1 s0) (shift_TyVar_Decls (weakenCutoffTyVar c1 k) d11))) :=
match d11 return ((shift_TyVar_Decls (weakenCutoffTyVar c1 k) (subst_TmVar_Decls (weakenTrace X0 k) s0 d11)) = (subst_TmVar_Decls (weakenTrace X0 k) (shift_TyVar_Tm c1 s0) (shift_TyVar_Decls (weakenCutoffTyVar c1 k) d11))) with
| (DNil) => eq_refl
| (DCons t7 d12) => (f_equal2 DCons (shift_TyVar__subst_TmVar_0_Tm_comm_ind t7 k c1 s0) (eq_trans (f_equal2 shift_TyVar_Decls eq_refl (f_equal3 subst_TmVar_Decls (weakenTrace_append TmVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (shift_TyVar__subst_TmVar_0_Decls_comm_ind d12 (HS TmVar k) c1 s0) (f_equal3 subst_TmVar_Decls (eq_sym (weakenTrace_append TmVar X0 k (HS TmVar H0))) eq_refl eq_refl))))
end
with shift_TyVar__subst_TmVar_0_Tm_comm_ind (s1 : Tm) (k : Hvl) (c1 : (Cutoff TyVar)) (s0 : Tm) {struct s1} :
((shift_TyVar_Tm (weakenCutoffTyVar c1 k) (subst_TmVar_Tm (weakenTrace X0 k) s0 s1)) = (subst_TmVar_Tm (weakenTrace X0 k) (shift_TyVar_Tm c1 s0) (shift_TyVar_Tm (weakenCutoffTyVar c1 k) s1))) :=
match s1 return ((shift_TyVar_Tm (weakenCutoffTyVar c1 k) (subst_TmVar_Tm (weakenTrace X0 k) s0 s1)) = (subst_TmVar_Tm (weakenTrace X0 k) (shift_TyVar_Tm c1 s0) (shift_TyVar_Tm (weakenCutoffTyVar c1 k) s1))) with
| (Var x8) => (shift_TyVar_Tm_subst_TmVar_Index0_comm_ind c1 s0 k x8)
| (Abs T5 t8) => (f_equal2 Abs eq_refl (eq_trans (f_equal2 shift_TyVar_Tm eq_refl (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (shift_TyVar__subst_TmVar_0_Tm_comm_ind t8 (HS TmVar k) c1 s0) (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar X0 k (HS TmVar H0))) eq_refl eq_refl))))
| (App t9 t10) => (f_equal2 App (shift_TyVar__subst_TmVar_0_Tm_comm_ind t9 k c1 s0) (shift_TyVar__subst_TmVar_0_Tm_comm_ind t10 k c1 s0))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal2 shift_TyVar_Tm eq_refl (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar X0 k (HS TyVar H0)) eq_refl eq_refl)) (eq_trans (shift_TyVar__subst_TmVar_0_Tm_comm_ind t8 (HS TyVar k) c1 s0) (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar X0 k (HS TyVar H0))) eq_refl eq_refl))))
| (TApp t8 T5) => (f_equal2 TApp (shift_TyVar__subst_TmVar_0_Tm_comm_ind t8 k c1 s0) eq_refl)
| (Let d13 t8) => (f_equal2 Let (shift_TyVar__subst_TmVar_0_Decls_comm_ind d13 k c1 s0) (eq_trans (f_equal2 shift_TyVar_Tm (eq_trans (f_equal2 weakenCutoffTyVar eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (stability_subst_TmVar__bind _ _ _) (eq_refl H0)))) (weakenCutoffTyVar_append c1 k (appendHvl H0 (bind d13)))) (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar X0 k (appendHvl H0 (bind d13))) eq_refl eq_refl)) (eq_trans (shift_TyVar__subst_TmVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d13))) c1 s0) (f_equal3 subst_TmVar_Tm (eq_trans (eq_sym (weakenTrace_append TmVar X0 k (appendHvl H0 (bind d13)))) (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (eq_sym (stability_shift_TyVar__bind _ _))))) eq_refl (f_equal2 shift_TyVar_Tm (eq_sym (weakenCutoffTyVar_append c1 k (appendHvl H0 (bind d13)))) eq_refl)))))
end.
Fixpoint shift_TyVar__subst_TyVar_0_Decls_comm_ind (d11 : Decls) (k : Hvl) (c1 : (Cutoff TyVar)) (S1 : Ty) {struct d11} :
((shift_TyVar_Decls (weakenCutoffTyVar c1 k) (subst_TyVar_Decls (weakenTrace X0 k) S1 d11)) = (subst_TyVar_Decls (weakenTrace X0 k) (shift_TyVar_Ty c1 S1) (shift_TyVar_Decls (weakenCutoffTyVar (CS c1) k) d11))) :=
match d11 return ((shift_TyVar_Decls (weakenCutoffTyVar c1 k) (subst_TyVar_Decls (weakenTrace X0 k) S1 d11)) = (subst_TyVar_Decls (weakenTrace X0 k) (shift_TyVar_Ty c1 S1) (shift_TyVar_Decls (weakenCutoffTyVar (CS c1) k) d11))) with
| (DNil) => eq_refl
| (DCons t7 d12) => (f_equal2 DCons (shift_TyVar__subst_TyVar_0_Tm_comm_ind t7 k c1 S1) (eq_trans (f_equal2 shift_TyVar_Decls eq_refl (f_equal3 subst_TyVar_Decls (weakenTrace_append TyVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (shift_TyVar__subst_TyVar_0_Decls_comm_ind d12 (HS TmVar k) c1 S1) (f_equal3 subst_TyVar_Decls (eq_sym (weakenTrace_append TyVar X0 k (HS TmVar H0))) eq_refl eq_refl))))
end
with shift_TyVar__subst_TyVar_0_Tm_comm_ind (s0 : Tm) (k : Hvl) (c1 : (Cutoff TyVar)) (S1 : Ty) {struct s0} :
((shift_TyVar_Tm (weakenCutoffTyVar c1 k) (subst_TyVar_Tm (weakenTrace X0 k) S1 s0)) = (subst_TyVar_Tm (weakenTrace X0 k) (shift_TyVar_Ty c1 S1) (shift_TyVar_Tm (weakenCutoffTyVar (CS c1) k) s0))) :=
match s0 return ((shift_TyVar_Tm (weakenCutoffTyVar c1 k) (subst_TyVar_Tm (weakenTrace X0 k) S1 s0)) = (subst_TyVar_Tm (weakenTrace X0 k) (shift_TyVar_Ty c1 S1) (shift_TyVar_Tm (weakenCutoffTyVar (CS c1) k) s0))) with
| (Var x8) => eq_refl
| (Abs T5 t8) => (f_equal2 Abs (shift_TyVar__subst_TyVar_0_Ty_comm_ind T5 k c1 S1) (eq_trans (f_equal2 shift_TyVar_Tm eq_refl (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (shift_TyVar__subst_TyVar_0_Tm_comm_ind t8 (HS TmVar k) c1 S1) (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar X0 k (HS TmVar H0))) eq_refl eq_refl))))
| (App t9 t10) => (f_equal2 App (shift_TyVar__subst_TyVar_0_Tm_comm_ind t9 k c1 S1) (shift_TyVar__subst_TyVar_0_Tm_comm_ind t10 k c1 S1))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal2 shift_TyVar_Tm eq_refl (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar X0 k (HS TyVar H0)) eq_refl eq_refl)) (eq_trans (shift_TyVar__subst_TyVar_0_Tm_comm_ind t8 (HS TyVar k) c1 S1) (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar X0 k (HS TyVar H0))) eq_refl eq_refl))))
| (TApp t8 T5) => (f_equal2 TApp (shift_TyVar__subst_TyVar_0_Tm_comm_ind t8 k c1 S1) (shift_TyVar__subst_TyVar_0_Ty_comm_ind T5 k c1 S1))
| (Let d13 t8) => (f_equal2 Let (shift_TyVar__subst_TyVar_0_Decls_comm_ind d13 k c1 S1) (eq_trans (f_equal2 shift_TyVar_Tm (eq_trans (f_equal2 weakenCutoffTyVar eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (stability_subst_TyVar__bind _ _ _) (eq_refl H0)))) (weakenCutoffTyVar_append c1 k (appendHvl H0 (bind d13)))) (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar X0 k (appendHvl H0 (bind d13))) eq_refl eq_refl)) (eq_trans (shift_TyVar__subst_TyVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d13))) c1 S1) (f_equal3 subst_TyVar_Tm (eq_trans (eq_sym (weakenTrace_append TyVar X0 k (appendHvl H0 (bind d13)))) (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (eq_sym (stability_shift_TyVar__bind _ _))))) eq_refl (f_equal2 shift_TyVar_Tm (eq_sym (weakenCutoffTyVar_append (CS c1) k (appendHvl H0 (bind d13)))) eq_refl)))))
end.
End ShiftSubstCommInd.
Section ShiftSubstComm.
Definition shift_TyVar_Ty_subst_TyVar_Ty0_comm (S2 : Ty) : (forall (c1 : (Cutoff TyVar)) (S1 : Ty) ,
((shift_TyVar_Ty c1 (subst_TyVar_Ty X0 S1 S2)) = (subst_TyVar_Ty X0 (shift_TyVar_Ty c1 S1) (shift_TyVar_Ty (CS c1) S2)))) := (shift_TyVar__subst_TyVar_0_Ty_comm_ind S2 H0).
Definition shift_TmVar_Decls_subst_TmVar_Decls0_comm (d11 : Decls) : (forall (c1 : (Cutoff TmVar)) (s0 : Tm) ,
((shift_TmVar_Decls c1 (subst_TmVar_Decls X0 s0 d11)) = (subst_TmVar_Decls X0 (shift_TmVar_Tm c1 s0) (shift_TmVar_Decls (CS c1) d11)))) := (shift_TmVar__subst_TmVar_0_Decls_comm_ind d11 H0).
Definition shift_TmVar_Tm_subst_TmVar_Tm0_comm (s1 : Tm) : (forall (c1 : (Cutoff TmVar)) (s0 : Tm) ,
((shift_TmVar_Tm c1 (subst_TmVar_Tm X0 s0 s1)) = (subst_TmVar_Tm X0 (shift_TmVar_Tm c1 s0) (shift_TmVar_Tm (CS c1) s1)))) := (shift_TmVar__subst_TmVar_0_Tm_comm_ind s1 H0).
Definition shift_TmVar_Decls_subst_TyVar_Decls0_comm (d11 : Decls) : (forall (c1 : (Cutoff TmVar)) (S1 : Ty) ,
((shift_TmVar_Decls c1 (subst_TyVar_Decls X0 S1 d11)) = (subst_TyVar_Decls X0 S1 (shift_TmVar_Decls c1 d11)))) := (shift_TmVar__subst_TyVar_0_Decls_comm_ind d11 H0).
Definition shift_TmVar_Tm_subst_TyVar_Tm0_comm (s0 : Tm) : (forall (c1 : (Cutoff TmVar)) (S1 : Ty) ,
((shift_TmVar_Tm c1 (subst_TyVar_Tm X0 S1 s0)) = (subst_TyVar_Tm X0 S1 (shift_TmVar_Tm c1 s0)))) := (shift_TmVar__subst_TyVar_0_Tm_comm_ind s0 H0).
Definition shift_TyVar_Decls_subst_TmVar_Decls0_comm (d11 : Decls) : (forall (c1 : (Cutoff TyVar)) (s0 : Tm) ,
((shift_TyVar_Decls c1 (subst_TmVar_Decls X0 s0 d11)) = (subst_TmVar_Decls X0 (shift_TyVar_Tm c1 s0) (shift_TyVar_Decls c1 d11)))) := (shift_TyVar__subst_TmVar_0_Decls_comm_ind d11 H0).
Definition shift_TyVar_Tm_subst_TmVar_Tm0_comm (s1 : Tm) : (forall (c1 : (Cutoff TyVar)) (s0 : Tm) ,
((shift_TyVar_Tm c1 (subst_TmVar_Tm X0 s0 s1)) = (subst_TmVar_Tm X0 (shift_TyVar_Tm c1 s0) (shift_TyVar_Tm c1 s1)))) := (shift_TyVar__subst_TmVar_0_Tm_comm_ind s1 H0).
Definition shift_TyVar_Decls_subst_TyVar_Decls0_comm (d11 : Decls) : (forall (c1 : (Cutoff TyVar)) (S1 : Ty) ,
((shift_TyVar_Decls c1 (subst_TyVar_Decls X0 S1 d11)) = (subst_TyVar_Decls X0 (shift_TyVar_Ty c1 S1) (shift_TyVar_Decls (CS c1) d11)))) := (shift_TyVar__subst_TyVar_0_Decls_comm_ind d11 H0).
Definition shift_TyVar_Tm_subst_TyVar_Tm0_comm (s0 : Tm) : (forall (c1 : (Cutoff TyVar)) (S1 : Ty) ,
((shift_TyVar_Tm c1 (subst_TyVar_Tm X0 S1 s0)) = (subst_TyVar_Tm X0 (shift_TyVar_Ty c1 S1) (shift_TyVar_Tm (CS c1) s0)))) := (shift_TyVar__subst_TyVar_0_Tm_comm_ind s0 H0).
End ShiftSubstComm.
Section SubstShiftIndexCommInd.
Lemma subst_TmVar_Index_shift_TmVar_Tm0_comm_ind (d11 : (Trace TmVar)) (s0 : Tm) :
(forall (k : Hvl) (x7 : (Index TmVar)) ,
((subst_TmVar_Index (weakenTrace (XS TmVar d11) k) s0 (shift_TmVar_Index (weakenCutoffTmVar C0 k) x7)) = (shift_TmVar_Tm (weakenCutoffTmVar C0 k) (subst_TmVar_Index (weakenTrace d11 k) s0 x7)))).
Proof.
needleGenericShiftSubstIndexCommInd .
Qed.
Lemma subst_TmVar_Index_shift_TyVar_Tm0_comm_ind (d11 : (Trace TmVar)) (s0 : Tm) :
(forall (k : Hvl) (x7 : (Index TmVar)) ,
((subst_TmVar_Index (weakenTrace (XS TyVar d11) k) s0 x7) = (shift_TyVar_Tm (weakenCutoffTyVar C0 k) (subst_TmVar_Index (weakenTrace d11 k) s0 x7)))).
Proof.
needleGenericShiftSubstIndexCommInd .
Qed.
Lemma subst_TyVar_Index_shift_TmVar_Ty0_comm_ind (d11 : (Trace TyVar)) (S1 : Ty) :
(forall (k : Hvl) (X7 : (Index TyVar)) ,
((subst_TyVar_Index (weakenTrace (XS TmVar d11) k) S1 X7) = (subst_TyVar_Index (weakenTrace d11 k) S1 X7))).
Proof.
needleGenericShiftSubstIndexCommInd .
Qed.
Lemma subst_TyVar_Index_shift_TyVar_Ty0_comm_ind (d11 : (Trace TyVar)) (S1 : Ty) :
(forall (k : Hvl) (X7 : (Index TyVar)) ,
((subst_TyVar_Index (weakenTrace (XS TyVar d11) k) S1 (shift_TyVar_Index (weakenCutoffTyVar C0 k) X7)) = (shift_TyVar_Ty (weakenCutoffTyVar C0 k) (subst_TyVar_Index (weakenTrace d11 k) S1 X7)))).
Proof.
needleGenericShiftSubstIndexCommInd .
Qed.
End SubstShiftIndexCommInd.
Section SubstShiftCommInd.
Fixpoint subst_TyVar__shift_TyVar_0_Ty_comm_ind (S2 : Ty) (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) {struct S2} :
((subst_TyVar_Ty (weakenTrace (XS TyVar d11) k) S1 (shift_TyVar_Ty (weakenCutoffTyVar C0 k) S2)) = (shift_TyVar_Ty (weakenCutoffTyVar C0 k) (subst_TyVar_Ty (weakenTrace d11 k) S1 S2))) :=
match S2 return ((subst_TyVar_Ty (weakenTrace (XS TyVar d11) k) S1 (shift_TyVar_Ty (weakenCutoffTyVar C0 k) S2)) = (shift_TyVar_Ty (weakenCutoffTyVar C0 k) (subst_TyVar_Ty (weakenTrace d11 k) S1 S2))) with
| (TVar X7) => (subst_TyVar_Index_shift_TyVar_Ty0_comm_ind d11 S1 k X7)
| (TArr T6 T7) => (f_equal2 TArr (subst_TyVar__shift_TyVar_0_Ty_comm_ind T6 k d11 S1) (subst_TyVar__shift_TyVar_0_Ty_comm_ind T7 k d11 S1))
| (TAll T5) => (f_equal TAll (eq_trans (f_equal3 subst_TyVar_Ty (weakenTrace_append TyVar (XS TyVar d11) k (HS TyVar H0)) eq_refl eq_refl) (eq_trans (subst_TyVar__shift_TyVar_0_Ty_comm_ind T5 (HS TyVar k) d11 S1) (f_equal2 shift_TyVar_Ty eq_refl (f_equal3 subst_TyVar_Ty (eq_sym (weakenTrace_append TyVar d11 k (HS TyVar H0))) eq_refl eq_refl)))))
end.
Fixpoint subst_TmVar__shift_TmVar_0_Decls_comm_ind (d12 : Decls) (k : Hvl) (d11 : (Trace TmVar)) (s0 : Tm) {struct d12} :
((subst_TmVar_Decls (weakenTrace (XS TmVar d11) k) s0 (shift_TmVar_Decls (weakenCutoffTmVar C0 k) d12)) = (shift_TmVar_Decls (weakenCutoffTmVar C0 k) (subst_TmVar_Decls (weakenTrace d11 k) s0 d12))) :=
match d12 return ((subst_TmVar_Decls (weakenTrace (XS TmVar d11) k) s0 (shift_TmVar_Decls (weakenCutoffTmVar C0 k) d12)) = (shift_TmVar_Decls (weakenCutoffTmVar C0 k) (subst_TmVar_Decls (weakenTrace d11 k) s0 d12))) with
| (DNil) => eq_refl
| (DCons t7 d13) => (f_equal2 DCons (subst_TmVar__shift_TmVar_0_Tm_comm_ind t7 k d11 s0) (eq_trans (f_equal3 subst_TmVar_Decls (weakenTrace_append TmVar (XS TmVar d11) k (HS TmVar H0)) eq_refl eq_refl) (eq_trans (subst_TmVar__shift_TmVar_0_Decls_comm_ind d13 (HS TmVar k) d11 s0) (f_equal2 shift_TmVar_Decls eq_refl (f_equal3 subst_TmVar_Decls (eq_sym (weakenTrace_append TmVar d11 k (HS TmVar H0))) eq_refl eq_refl)))))
end
with subst_TmVar__shift_TmVar_0_Tm_comm_ind (s1 : Tm) (k : Hvl) (d11 : (Trace TmVar)) (s0 : Tm) {struct s1} :
((subst_TmVar_Tm (weakenTrace (XS TmVar d11) k) s0 (shift_TmVar_Tm (weakenCutoffTmVar C0 k) s1)) = (shift_TmVar_Tm (weakenCutoffTmVar C0 k) (subst_TmVar_Tm (weakenTrace d11 k) s0 s1))) :=
match s1 return ((subst_TmVar_Tm (weakenTrace (XS TmVar d11) k) s0 (shift_TmVar_Tm (weakenCutoffTmVar C0 k) s1)) = (shift_TmVar_Tm (weakenCutoffTmVar C0 k) (subst_TmVar_Tm (weakenTrace d11 k) s0 s1))) with
| (Var x8) => (subst_TmVar_Index_shift_TmVar_Tm0_comm_ind d11 s0 k x8)
| (Abs T5 t8) => (f_equal2 Abs eq_refl (eq_trans (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar (XS TmVar d11) k (HS TmVar H0)) eq_refl eq_refl) (eq_trans (subst_TmVar__shift_TmVar_0_Tm_comm_ind t8 (HS TmVar k) d11 s0) (f_equal2 shift_TmVar_Tm eq_refl (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar d11 k (HS TmVar H0))) eq_refl eq_refl)))))
| (App t9 t10) => (f_equal2 App (subst_TmVar__shift_TmVar_0_Tm_comm_ind t9 k d11 s0) (subst_TmVar__shift_TmVar_0_Tm_comm_ind t10 k d11 s0))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar (XS TmVar d11) k (HS TyVar H0)) eq_refl eq_refl) (eq_trans (subst_TmVar__shift_TmVar_0_Tm_comm_ind t8 (HS TyVar k) d11 s0) (f_equal2 shift_TmVar_Tm eq_refl (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar d11 k (HS TyVar H0))) eq_refl eq_refl)))))
| (TApp t8 T5) => (f_equal2 TApp (subst_TmVar__shift_TmVar_0_Tm_comm_ind t8 k d11 s0) eq_refl)
| (Let d14 t8) => (f_equal2 Let (subst_TmVar__shift_TmVar_0_Decls_comm_ind d14 k d11 s0) (eq_trans (f_equal3 subst_TmVar_Tm (eq_trans (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (stability_shift_TmVar__bind _ _))) (weakenTrace_append TmVar (XS TmVar d11) k (appendHvl H0 (bind d14)))) eq_refl (f_equal2 shift_TmVar_Tm (weakenCutoffTmVar_append C0 k (appendHvl H0 (bind d14))) eq_refl)) (eq_trans (subst_TmVar__shift_TmVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d14))) d11 s0) (f_equal2 shift_TmVar_Tm (eq_trans (eq_sym (weakenCutoffTmVar_append C0 k (appendHvl H0 (bind d14)))) (f_equal2 weakenCutoffTmVar eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (eq_sym (stability_subst_TmVar__bind _ _ _)) (eq_refl H0))))) (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar d11 k (appendHvl H0 (bind d14)))) eq_refl eq_refl)))))
end.
Fixpoint subst_TmVar__shift_TyVar_0_Decls_comm_ind (d12 : Decls) (k : Hvl) (d11 : (Trace TmVar)) (s0 : Tm) {struct d12} :
((subst_TmVar_Decls (weakenTrace (XS TyVar d11) k) s0 (shift_TyVar_Decls (weakenCutoffTyVar C0 k) d12)) = (shift_TyVar_Decls (weakenCutoffTyVar C0 k) (subst_TmVar_Decls (weakenTrace d11 k) s0 d12))) :=
match d12 return ((subst_TmVar_Decls (weakenTrace (XS TyVar d11) k) s0 (shift_TyVar_Decls (weakenCutoffTyVar C0 k) d12)) = (shift_TyVar_Decls (weakenCutoffTyVar C0 k) (subst_TmVar_Decls (weakenTrace d11 k) s0 d12))) with
| (DNil) => eq_refl
| (DCons t7 d13) => (f_equal2 DCons (subst_TmVar__shift_TyVar_0_Tm_comm_ind t7 k d11 s0) (eq_trans (f_equal3 subst_TmVar_Decls (weakenTrace_append TmVar (XS TyVar d11) k (HS TmVar H0)) eq_refl eq_refl) (eq_trans (subst_TmVar__shift_TyVar_0_Decls_comm_ind d13 (HS TmVar k) d11 s0) (f_equal2 shift_TyVar_Decls eq_refl (f_equal3 subst_TmVar_Decls (eq_sym (weakenTrace_append TmVar d11 k (HS TmVar H0))) eq_refl eq_refl)))))
end
with subst_TmVar__shift_TyVar_0_Tm_comm_ind (s1 : Tm) (k : Hvl) (d11 : (Trace TmVar)) (s0 : Tm) {struct s1} :
((subst_TmVar_Tm (weakenTrace (XS TyVar d11) k) s0 (shift_TyVar_Tm (weakenCutoffTyVar C0 k) s1)) = (shift_TyVar_Tm (weakenCutoffTyVar C0 k) (subst_TmVar_Tm (weakenTrace d11 k) s0 s1))) :=
match s1 return ((subst_TmVar_Tm (weakenTrace (XS TyVar d11) k) s0 (shift_TyVar_Tm (weakenCutoffTyVar C0 k) s1)) = (shift_TyVar_Tm (weakenCutoffTyVar C0 k) (subst_TmVar_Tm (weakenTrace d11 k) s0 s1))) with
| (Var x8) => (subst_TmVar_Index_shift_TyVar_Tm0_comm_ind d11 s0 k x8)
| (Abs T5 t8) => (f_equal2 Abs eq_refl (eq_trans (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar (XS TyVar d11) k (HS TmVar H0)) eq_refl eq_refl) (eq_trans (subst_TmVar__shift_TyVar_0_Tm_comm_ind t8 (HS TmVar k) d11 s0) (f_equal2 shift_TyVar_Tm eq_refl (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar d11 k (HS TmVar H0))) eq_refl eq_refl)))))
| (App t9 t10) => (f_equal2 App (subst_TmVar__shift_TyVar_0_Tm_comm_ind t9 k d11 s0) (subst_TmVar__shift_TyVar_0_Tm_comm_ind t10 k d11 s0))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar (XS TyVar d11) k (HS TyVar H0)) eq_refl eq_refl) (eq_trans (subst_TmVar__shift_TyVar_0_Tm_comm_ind t8 (HS TyVar k) d11 s0) (f_equal2 shift_TyVar_Tm eq_refl (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar d11 k (HS TyVar H0))) eq_refl eq_refl)))))
| (TApp t8 T5) => (f_equal2 TApp (subst_TmVar__shift_TyVar_0_Tm_comm_ind t8 k d11 s0) eq_refl)
| (Let d14 t8) => (f_equal2 Let (subst_TmVar__shift_TyVar_0_Decls_comm_ind d14 k d11 s0) (eq_trans (f_equal3 subst_TmVar_Tm (eq_trans (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (stability_shift_TyVar__bind _ _))) (weakenTrace_append TmVar (XS TyVar d11) k (appendHvl H0 (bind d14)))) eq_refl (f_equal2 shift_TyVar_Tm (weakenCutoffTyVar_append C0 k (appendHvl H0 (bind d14))) eq_refl)) (eq_trans (subst_TmVar__shift_TyVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d14))) d11 s0) (f_equal2 shift_TyVar_Tm (eq_trans (eq_sym (weakenCutoffTyVar_append C0 k (appendHvl H0 (bind d14)))) (f_equal2 weakenCutoffTyVar eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (eq_sym (stability_subst_TmVar__bind _ _ _)) (eq_refl H0))))) (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar d11 k (appendHvl H0 (bind d14)))) eq_refl eq_refl)))))
end.
Fixpoint subst_TyVar__shift_TmVar_0_Decls_comm_ind (d12 : Decls) (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) {struct d12} :
((subst_TyVar_Decls (weakenTrace d11 k) S1 (shift_TmVar_Decls (weakenCutoffTmVar C0 k) d12)) = (shift_TmVar_Decls (weakenCutoffTmVar C0 k) (subst_TyVar_Decls (weakenTrace d11 k) S1 d12))) :=
match d12 return ((subst_TyVar_Decls (weakenTrace d11 k) S1 (shift_TmVar_Decls (weakenCutoffTmVar C0 k) d12)) = (shift_TmVar_Decls (weakenCutoffTmVar C0 k) (subst_TyVar_Decls (weakenTrace d11 k) S1 d12))) with
| (DNil) => eq_refl
| (DCons t7 d13) => (f_equal2 DCons (subst_TyVar__shift_TmVar_0_Tm_comm_ind t7 k d11 S1) (eq_trans (f_equal3 subst_TyVar_Decls (weakenTrace_append TyVar d11 k (HS TmVar H0)) eq_refl eq_refl) (eq_trans (subst_TyVar__shift_TmVar_0_Decls_comm_ind d13 (HS TmVar k) d11 S1) (f_equal2 shift_TmVar_Decls eq_refl (f_equal3 subst_TyVar_Decls (eq_sym (weakenTrace_append TyVar d11 k (HS TmVar H0))) eq_refl eq_refl)))))
end
with subst_TyVar__shift_TmVar_0_Tm_comm_ind (s0 : Tm) (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) {struct s0} :
((subst_TyVar_Tm (weakenTrace d11 k) S1 (shift_TmVar_Tm (weakenCutoffTmVar C0 k) s0)) = (shift_TmVar_Tm (weakenCutoffTmVar C0 k) (subst_TyVar_Tm (weakenTrace d11 k) S1 s0))) :=
match s0 return ((subst_TyVar_Tm (weakenTrace d11 k) S1 (shift_TmVar_Tm (weakenCutoffTmVar C0 k) s0)) = (shift_TmVar_Tm (weakenCutoffTmVar C0 k) (subst_TyVar_Tm (weakenTrace d11 k) S1 s0))) with
| (Var x8) => eq_refl
| (Abs T5 t8) => (f_equal2 Abs eq_refl (eq_trans (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar d11 k (HS TmVar H0)) eq_refl eq_refl) (eq_trans (subst_TyVar__shift_TmVar_0_Tm_comm_ind t8 (HS TmVar k) d11 S1) (f_equal2 shift_TmVar_Tm eq_refl (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar d11 k (HS TmVar H0))) eq_refl eq_refl)))))
| (App t9 t10) => (f_equal2 App (subst_TyVar__shift_TmVar_0_Tm_comm_ind t9 k d11 S1) (subst_TyVar__shift_TmVar_0_Tm_comm_ind t10 k d11 S1))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar d11 k (HS TyVar H0)) eq_refl eq_refl) (eq_trans (subst_TyVar__shift_TmVar_0_Tm_comm_ind t8 (HS TyVar k) d11 S1) (f_equal2 shift_TmVar_Tm eq_refl (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar d11 k (HS TyVar H0))) eq_refl eq_refl)))))
| (TApp t8 T5) => (f_equal2 TApp (subst_TyVar__shift_TmVar_0_Tm_comm_ind t8 k d11 S1) eq_refl)
| (Let d14 t8) => (f_equal2 Let (subst_TyVar__shift_TmVar_0_Decls_comm_ind d14 k d11 S1) (eq_trans (f_equal3 subst_TyVar_Tm (eq_trans (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (stability_shift_TmVar__bind _ _))) (weakenTrace_append TyVar d11 k (appendHvl H0 (bind d14)))) eq_refl (f_equal2 shift_TmVar_Tm (weakenCutoffTmVar_append C0 k (appendHvl H0 (bind d14))) eq_refl)) (eq_trans (subst_TyVar__shift_TmVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d14))) d11 S1) (f_equal2 shift_TmVar_Tm (eq_trans (eq_sym (weakenCutoffTmVar_append C0 k (appendHvl H0 (bind d14)))) (f_equal2 weakenCutoffTmVar eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (eq_sym (stability_subst_TyVar__bind _ _ _)) (eq_refl H0))))) (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar d11 k (appendHvl H0 (bind d14)))) eq_refl eq_refl)))))
end.
Fixpoint subst_TyVar__shift_TyVar_0_Decls_comm_ind (d12 : Decls) (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) {struct d12} :
((subst_TyVar_Decls (weakenTrace (XS TyVar d11) k) S1 (shift_TyVar_Decls (weakenCutoffTyVar C0 k) d12)) = (shift_TyVar_Decls (weakenCutoffTyVar C0 k) (subst_TyVar_Decls (weakenTrace d11 k) S1 d12))) :=
match d12 return ((subst_TyVar_Decls (weakenTrace (XS TyVar d11) k) S1 (shift_TyVar_Decls (weakenCutoffTyVar C0 k) d12)) = (shift_TyVar_Decls (weakenCutoffTyVar C0 k) (subst_TyVar_Decls (weakenTrace d11 k) S1 d12))) with
| (DNil) => eq_refl
| (DCons t7 d13) => (f_equal2 DCons (subst_TyVar__shift_TyVar_0_Tm_comm_ind t7 k d11 S1) (eq_trans (f_equal3 subst_TyVar_Decls (weakenTrace_append TyVar (XS TyVar d11) k (HS TmVar H0)) eq_refl eq_refl) (eq_trans (subst_TyVar__shift_TyVar_0_Decls_comm_ind d13 (HS TmVar k) d11 S1) (f_equal2 shift_TyVar_Decls eq_refl (f_equal3 subst_TyVar_Decls (eq_sym (weakenTrace_append TyVar d11 k (HS TmVar H0))) eq_refl eq_refl)))))
end
with subst_TyVar__shift_TyVar_0_Tm_comm_ind (s0 : Tm) (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) {struct s0} :
((subst_TyVar_Tm (weakenTrace (XS TyVar d11) k) S1 (shift_TyVar_Tm (weakenCutoffTyVar C0 k) s0)) = (shift_TyVar_Tm (weakenCutoffTyVar C0 k) (subst_TyVar_Tm (weakenTrace d11 k) S1 s0))) :=
match s0 return ((subst_TyVar_Tm (weakenTrace (XS TyVar d11) k) S1 (shift_TyVar_Tm (weakenCutoffTyVar C0 k) s0)) = (shift_TyVar_Tm (weakenCutoffTyVar C0 k) (subst_TyVar_Tm (weakenTrace d11 k) S1 s0))) with
| (Var x8) => eq_refl
| (Abs T5 t8) => (f_equal2 Abs (subst_TyVar__shift_TyVar_0_Ty_comm_ind T5 k d11 S1) (eq_trans (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar (XS TyVar d11) k (HS TmVar H0)) eq_refl eq_refl) (eq_trans (subst_TyVar__shift_TyVar_0_Tm_comm_ind t8 (HS TmVar k) d11 S1) (f_equal2 shift_TyVar_Tm eq_refl (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar d11 k (HS TmVar H0))) eq_refl eq_refl)))))
| (App t9 t10) => (f_equal2 App (subst_TyVar__shift_TyVar_0_Tm_comm_ind t9 k d11 S1) (subst_TyVar__shift_TyVar_0_Tm_comm_ind t10 k d11 S1))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar (XS TyVar d11) k (HS TyVar H0)) eq_refl eq_refl) (eq_trans (subst_TyVar__shift_TyVar_0_Tm_comm_ind t8 (HS TyVar k) d11 S1) (f_equal2 shift_TyVar_Tm eq_refl (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar d11 k (HS TyVar H0))) eq_refl eq_refl)))))
| (TApp t8 T5) => (f_equal2 TApp (subst_TyVar__shift_TyVar_0_Tm_comm_ind t8 k d11 S1) (subst_TyVar__shift_TyVar_0_Ty_comm_ind T5 k d11 S1))
| (Let d14 t8) => (f_equal2 Let (subst_TyVar__shift_TyVar_0_Decls_comm_ind d14 k d11 S1) (eq_trans (f_equal3 subst_TyVar_Tm (eq_trans (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (stability_shift_TyVar__bind _ _))) (weakenTrace_append TyVar (XS TyVar d11) k (appendHvl H0 (bind d14)))) eq_refl (f_equal2 shift_TyVar_Tm (weakenCutoffTyVar_append C0 k (appendHvl H0 (bind d14))) eq_refl)) (eq_trans (subst_TyVar__shift_TyVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d14))) d11 S1) (f_equal2 shift_TyVar_Tm (eq_trans (eq_sym (weakenCutoffTyVar_append C0 k (appendHvl H0 (bind d14)))) (f_equal2 weakenCutoffTyVar eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (eq_sym (stability_subst_TyVar__bind _ _ _)) (eq_refl H0))))) (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar d11 k (appendHvl H0 (bind d14)))) eq_refl eq_refl)))))
end.
End SubstShiftCommInd.
Section SubstShiftComm.
Definition subst_TyVar_Ty_shift_TyVar_Ty0_comm (S2 : Ty) : (forall (d11 : (Trace TyVar)) (S1 : Ty) ,
((subst_TyVar_Ty (XS TyVar d11) S1 (shift_TyVar_Ty C0 S2)) = (shift_TyVar_Ty C0 (subst_TyVar_Ty d11 S1 S2)))) := (subst_TyVar__shift_TyVar_0_Ty_comm_ind S2 H0).
Definition subst_TmVar_Decls_shift_TmVar_Decls0_comm (d12 : Decls) : (forall (d11 : (Trace TmVar)) (s0 : Tm) ,
((subst_TmVar_Decls (XS TmVar d11) s0 (shift_TmVar_Decls C0 d12)) = (shift_TmVar_Decls C0 (subst_TmVar_Decls d11 s0 d12)))) := (subst_TmVar__shift_TmVar_0_Decls_comm_ind d12 H0).
Definition subst_TmVar_Tm_shift_TmVar_Tm0_comm (s1 : Tm) : (forall (d11 : (Trace TmVar)) (s0 : Tm) ,
((subst_TmVar_Tm (XS TmVar d11) s0 (shift_TmVar_Tm C0 s1)) = (shift_TmVar_Tm C0 (subst_TmVar_Tm d11 s0 s1)))) := (subst_TmVar__shift_TmVar_0_Tm_comm_ind s1 H0).
Definition subst_TmVar_Decls_shift_TyVar_Decls0_comm (d12 : Decls) : (forall (d11 : (Trace TmVar)) (s0 : Tm) ,
((subst_TmVar_Decls (XS TyVar d11) s0 (shift_TyVar_Decls C0 d12)) = (shift_TyVar_Decls C0 (subst_TmVar_Decls d11 s0 d12)))) := (subst_TmVar__shift_TyVar_0_Decls_comm_ind d12 H0).
Definition subst_TmVar_Tm_shift_TyVar_Tm0_comm (s1 : Tm) : (forall (d11 : (Trace TmVar)) (s0 : Tm) ,
((subst_TmVar_Tm (XS TyVar d11) s0 (shift_TyVar_Tm C0 s1)) = (shift_TyVar_Tm C0 (subst_TmVar_Tm d11 s0 s1)))) := (subst_TmVar__shift_TyVar_0_Tm_comm_ind s1 H0).
Definition subst_TyVar_Decls_shift_TmVar_Decls0_comm (d12 : Decls) : (forall (d11 : (Trace TyVar)) (S1 : Ty) ,
((subst_TyVar_Decls d11 S1 (shift_TmVar_Decls C0 d12)) = (shift_TmVar_Decls C0 (subst_TyVar_Decls d11 S1 d12)))) := (subst_TyVar__shift_TmVar_0_Decls_comm_ind d12 H0).
Definition subst_TyVar_Tm_shift_TmVar_Tm0_comm (s0 : Tm) : (forall (d11 : (Trace TyVar)) (S1 : Ty) ,
((subst_TyVar_Tm d11 S1 (shift_TmVar_Tm C0 s0)) = (shift_TmVar_Tm C0 (subst_TyVar_Tm d11 S1 s0)))) := (subst_TyVar__shift_TmVar_0_Tm_comm_ind s0 H0).
Definition subst_TyVar_Decls_shift_TyVar_Decls0_comm (d12 : Decls) : (forall (d11 : (Trace TyVar)) (S1 : Ty) ,
((subst_TyVar_Decls (XS TyVar d11) S1 (shift_TyVar_Decls C0 d12)) = (shift_TyVar_Decls C0 (subst_TyVar_Decls d11 S1 d12)))) := (subst_TyVar__shift_TyVar_0_Decls_comm_ind d12 H0).
Definition subst_TyVar_Tm_shift_TyVar_Tm0_comm (s0 : Tm) : (forall (d11 : (Trace TyVar)) (S1 : Ty) ,
((subst_TyVar_Tm (XS TyVar d11) S1 (shift_TyVar_Tm C0 s0)) = (shift_TyVar_Tm C0 (subst_TyVar_Tm d11 S1 s0)))) := (subst_TyVar__shift_TyVar_0_Tm_comm_ind s0 H0).
End SubstShiftComm.
Section SubstSubordInd.
Fixpoint subst_TyVar__TmVar_Ty_ind (S2 : Ty) (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) {struct S2} :
((subst_TyVar_Ty (weakenTrace (XS TmVar d11) k) S1 S2) = (subst_TyVar_Ty (weakenTrace d11 k) S1 S2)) :=
match S2 return ((subst_TyVar_Ty (weakenTrace (XS TmVar d11) k) S1 S2) = (subst_TyVar_Ty (weakenTrace d11 k) S1 S2)) with
| (TVar X7) => (subst_TyVar_Index_shift_TmVar_Ty0_comm_ind d11 S1 k X7)
| (TArr T6 T7) => (f_equal2 TArr (subst_TyVar__TmVar_Ty_ind T6 k d11 S1) (subst_TyVar__TmVar_Ty_ind T7 k d11 S1))
| (TAll T5) => (f_equal TAll (eq_trans (f_equal3 subst_TyVar_Ty (weakenTrace_append TyVar (XS TmVar d11) k (HS TyVar H0)) eq_refl eq_refl) (eq_trans (subst_TyVar__TmVar_Ty_ind T5 (HS TyVar k) d11 S1) (f_equal3 subst_TyVar_Ty (eq_sym (weakenTrace_append TyVar d11 k (HS TyVar H0))) eq_refl eq_refl))))
end.
Fixpoint subst_TyVar__TmVar_Decls_ind (d12 : Decls) (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) {struct d12} :
((subst_TyVar_Decls (weakenTrace (XS TmVar d11) k) S1 d12) = (subst_TyVar_Decls (weakenTrace d11 k) S1 d12)) :=
match d12 return ((subst_TyVar_Decls (weakenTrace (XS TmVar d11) k) S1 d12) = (subst_TyVar_Decls (weakenTrace d11 k) S1 d12)) with
| (DNil) => eq_refl
| (DCons t7 d13) => (f_equal2 DCons (subst_TyVar__TmVar_Tm_ind t7 k d11 S1) (eq_trans (f_equal3 subst_TyVar_Decls (weakenTrace_append TyVar (XS TmVar d11) k (HS TmVar H0)) eq_refl eq_refl) (eq_trans (subst_TyVar__TmVar_Decls_ind d13 (HS TmVar k) d11 S1) (f_equal3 subst_TyVar_Decls (eq_sym (weakenTrace_append TyVar d11 k (HS TmVar H0))) eq_refl eq_refl))))
end
with subst_TyVar__TmVar_Tm_ind (s0 : Tm) (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) {struct s0} :
((subst_TyVar_Tm (weakenTrace (XS TmVar d11) k) S1 s0) = (subst_TyVar_Tm (weakenTrace d11 k) S1 s0)) :=
match s0 return ((subst_TyVar_Tm (weakenTrace (XS TmVar d11) k) S1 s0) = (subst_TyVar_Tm (weakenTrace d11 k) S1 s0)) with
| (Var x8) => eq_refl
| (Abs T5 t8) => (f_equal2 Abs (subst_TyVar__TmVar_Ty_ind T5 k d11 S1) (eq_trans (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar (XS TmVar d11) k (HS TmVar H0)) eq_refl eq_refl) (eq_trans (subst_TyVar__TmVar_Tm_ind t8 (HS TmVar k) d11 S1) (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar d11 k (HS TmVar H0))) eq_refl eq_refl))))
| (App t9 t10) => (f_equal2 App (subst_TyVar__TmVar_Tm_ind t9 k d11 S1) (subst_TyVar__TmVar_Tm_ind t10 k d11 S1))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar (XS TmVar d11) k (HS TyVar H0)) eq_refl eq_refl) (eq_trans (subst_TyVar__TmVar_Tm_ind t8 (HS TyVar k) d11 S1) (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar d11 k (HS TyVar H0))) eq_refl eq_refl))))
| (TApp t8 T5) => (f_equal2 TApp (subst_TyVar__TmVar_Tm_ind t8 k d11 S1) (subst_TyVar__TmVar_Ty_ind T5 k d11 S1))
| (Let d14 t8) => (f_equal2 Let (subst_TyVar__TmVar_Decls_ind d14 k d11 S1) (eq_trans (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar (XS TmVar d11) k (appendHvl H0 (bind d14))) eq_refl eq_refl) (eq_trans (subst_TyVar__TmVar_Tm_ind t8 (appendHvl k (appendHvl H0 (bind d14))) d11 S1) (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar d11 k (appendHvl H0 (bind d14)))) eq_refl eq_refl))))
end.
End SubstSubordInd.
Section SubstSubord.
Definition subst_TyVar_Ty_TmVar (S2 : Ty) : (forall (d11 : (Trace TyVar)) (S1 : Ty) ,
((subst_TyVar_Ty (XS TmVar d11) S1 S2) = (subst_TyVar_Ty d11 S1 S2))) := (subst_TyVar__TmVar_Ty_ind S2 H0).
Definition subst_TyVar_Decls_TmVar (d12 : Decls) : (forall (d11 : (Trace TyVar)) (S1 : Ty) ,
((subst_TyVar_Decls (XS TmVar d11) S1 d12) = (subst_TyVar_Decls d11 S1 d12))) := (subst_TyVar__TmVar_Decls_ind d12 H0).
Definition subst_TyVar_Tm_TmVar (s0 : Tm) : (forall (d11 : (Trace TyVar)) (S1 : Ty) ,
((subst_TyVar_Tm (XS TmVar d11) S1 s0) = (subst_TyVar_Tm d11 S1 s0))) := (subst_TyVar__TmVar_Tm_ind s0 H0).
End SubstSubord.
End ShiftSubstInteraction.
Hint Rewrite subst_TmVar_Decls0_shift_TmVar_Decls0_reflection subst_TyVar_Decls0_shift_TyVar_Decls0_reflection subst_TmVar_Tm0_shift_TmVar_Tm0_reflection subst_TyVar_Tm0_shift_TyVar_Tm0_reflection subst_TyVar_Ty0_shift_TyVar_Ty0_reflection : interaction.
Hint Rewrite subst_TmVar_Decls0_shift_TmVar_Decls0_reflection subst_TyVar_Decls0_shift_TyVar_Decls0_reflection subst_TmVar_Tm0_shift_TmVar_Tm0_reflection subst_TyVar_Tm0_shift_TyVar_Tm0_reflection subst_TyVar_Ty0_shift_TyVar_Ty0_reflection : reflection.
Hint Rewrite subst_TmVar_Decls_shift_TmVar_Decls0_comm subst_TmVar_Decls_shift_TyVar_Decls0_comm subst_TyVar_Decls_shift_TmVar_Decls0_comm subst_TyVar_Decls_shift_TyVar_Decls0_comm subst_TmVar_Tm_shift_TmVar_Tm0_comm subst_TmVar_Tm_shift_TyVar_Tm0_comm subst_TyVar_Tm_shift_TmVar_Tm0_comm subst_TyVar_Tm_shift_TyVar_Tm0_comm subst_TyVar_Ty_shift_TyVar_Ty0_comm : interaction.
Hint Rewrite subst_TmVar_Decls_shift_TmVar_Decls0_comm subst_TmVar_Decls_shift_TyVar_Decls0_comm subst_TyVar_Decls_shift_TmVar_Decls0_comm subst_TyVar_Decls_shift_TyVar_Decls0_comm subst_TmVar_Tm_shift_TmVar_Tm0_comm subst_TmVar_Tm_shift_TyVar_Tm0_comm subst_TyVar_Tm_shift_TmVar_Tm0_comm subst_TyVar_Tm_shift_TyVar_Tm0_comm subst_TyVar_Ty_shift_TyVar_Ty0_comm : subst_shift0.
Hint Rewrite subst_TyVar_Decls_TmVar subst_TyVar_Tm_TmVar subst_TyVar_Ty_TmVar : interaction.
Hint Rewrite subst_TyVar_Decls_TmVar subst_TyVar_Tm_TmVar subst_TyVar_Ty_TmVar : subst_shift0.
Hint Rewrite shift_TmVar_Decls_subst_TmVar_Decls0_comm shift_TmVar_Decls_subst_TyVar_Decls0_comm shift_TyVar_Decls_subst_TmVar_Decls0_comm shift_TyVar_Decls_subst_TyVar_Decls0_comm shift_TmVar_Tm_subst_TmVar_Tm0_comm shift_TmVar_Tm_subst_TyVar_Tm0_comm shift_TyVar_Tm_subst_TmVar_Tm0_comm shift_TyVar_Tm_subst_TyVar_Tm0_comm shift_TyVar_Ty_subst_TyVar_Ty0_comm : interaction.
Hint Rewrite shift_TmVar_Decls_subst_TmVar_Decls0_comm shift_TmVar_Decls_subst_TyVar_Decls0_comm shift_TyVar_Decls_subst_TmVar_Decls0_comm shift_TyVar_Decls_subst_TyVar_Decls0_comm shift_TmVar_Tm_subst_TmVar_Tm0_comm shift_TmVar_Tm_subst_TyVar_Tm0_comm shift_TyVar_Tm_subst_TmVar_Tm0_comm shift_TyVar_Tm_subst_TyVar_Tm0_comm shift_TyVar_Ty_subst_TyVar_Ty0_comm : shift_subst0.
Section SubstSubstInteraction.
Section SubstSubstIndexCommInd.
Lemma subst_TmVar_Tm_subst_TmVar_Index0_commright_ind (d11 : (Trace TmVar)) (s0 : Tm) (s1 : Tm) :
(forall (k : Hvl) (x7 : (Index TmVar)) ,
((subst_TmVar_Tm (weakenTrace d11 k) s0 (subst_TmVar_Index (weakenTrace X0 k) s1 x7)) = (subst_TmVar_Tm (weakenTrace X0 k) (subst_TmVar_Tm d11 s0 s1) (subst_TmVar_Index (weakenTrace (XS TmVar d11) k) s0 x7)))).
Proof.
needleGenericSubstSubstIndexCommInd .
Qed.
Lemma subst_TyVar_Tm_subst_TmVar_Index0_commright_ind (d11 : (Trace TyVar)) (S1 : Ty) (s0 : Tm) :
(forall (k : Hvl) (x7 : (Index TmVar)) ,
((subst_TyVar_Tm (weakenTrace d11 k) S1 (subst_TmVar_Index (weakenTrace X0 k) s0 x7)) = (subst_TmVar_Index (weakenTrace X0 k) (subst_TyVar_Tm d11 S1 s0) x7))).
Proof.
needleGenericSubstSubstIndexCommInd .
Qed.
Lemma subst_TyVar_Ty_subst_TyVar_Index0_commright_ind (d11 : (Trace TyVar)) (S1 : Ty) (S2 : Ty) :
(forall (k : Hvl) (X7 : (Index TyVar)) ,
((subst_TyVar_Ty (weakenTrace d11 k) S1 (subst_TyVar_Index (weakenTrace X0 k) S2 X7)) = (subst_TyVar_Ty (weakenTrace X0 k) (subst_TyVar_Ty d11 S1 S2) (subst_TyVar_Index (weakenTrace (XS TyVar d11) k) S1 X7)))).
Proof.
needleGenericSubstSubstIndexCommInd .
Qed.
Lemma subst_TmVar_Ty_subst_TyVar_Index0_commleft_ind (d11 : (Trace TmVar)) (s0 : Tm) (S1 : Ty) :
(forall (k : Hvl) (x7 : (Index TmVar)) ,
((subst_TmVar_Index (weakenTrace d11 k) s0 x7) = (subst_TyVar_Tm (weakenTrace X0 k) S1 (subst_TmVar_Index (weakenTrace (XS TyVar d11) k) s0 x7)))).
Proof.
needleGenericSubstSubstIndexCommInd .
Qed.
End SubstSubstIndexCommInd.
Section SubstSubstCommInd.
Fixpoint subst_TyVar__subst_TyVar_0_Ty_comm_ind (S3 : Ty) (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) (S2 : Ty) {struct S3} :
((subst_TyVar_Ty (weakenTrace d11 k) S1 (subst_TyVar_Ty (weakenTrace X0 k) S2 S3)) = (subst_TyVar_Ty (weakenTrace X0 k) (subst_TyVar_Ty d11 S1 S2) (subst_TyVar_Ty (weakenTrace (XS TyVar d11) k) S1 S3))) :=
match S3 return ((subst_TyVar_Ty (weakenTrace d11 k) S1 (subst_TyVar_Ty (weakenTrace X0 k) S2 S3)) = (subst_TyVar_Ty (weakenTrace X0 k) (subst_TyVar_Ty d11 S1 S2) (subst_TyVar_Ty (weakenTrace (XS TyVar d11) k) S1 S3))) with
| (TVar X7) => (subst_TyVar_Ty_subst_TyVar_Index0_commright_ind d11 S1 S2 k X7)
| (TArr T6 T7) => (f_equal2 TArr (subst_TyVar__subst_TyVar_0_Ty_comm_ind T6 k d11 S1 S2) (subst_TyVar__subst_TyVar_0_Ty_comm_ind T7 k d11 S1 S2))
| (TAll T5) => (f_equal TAll (eq_trans (f_equal3 subst_TyVar_Ty (weakenTrace_append TyVar d11 k (HS TyVar H0)) eq_refl (f_equal3 subst_TyVar_Ty (weakenTrace_append TyVar X0 k (HS TyVar H0)) eq_refl eq_refl)) (eq_trans (subst_TyVar__subst_TyVar_0_Ty_comm_ind T5 (HS TyVar k) d11 S1 S2) (f_equal3 subst_TyVar_Ty (eq_sym (weakenTrace_append TyVar X0 k (HS TyVar H0))) eq_refl (f_equal3 subst_TyVar_Ty (eq_sym (weakenTrace_append TyVar (XS TyVar d11) k (HS TyVar H0))) eq_refl eq_refl)))))
end.
Fixpoint subst_TmVar__subst_TmVar_0_Decls_comm_ind (d12 : Decls) (k : Hvl) (d11 : (Trace TmVar)) (s0 : Tm) (s1 : Tm) {struct d12} :
((subst_TmVar_Decls (weakenTrace d11 k) s0 (subst_TmVar_Decls (weakenTrace X0 k) s1 d12)) = (subst_TmVar_Decls (weakenTrace X0 k) (subst_TmVar_Tm d11 s0 s1) (subst_TmVar_Decls (weakenTrace (XS TmVar d11) k) s0 d12))) :=
match d12 return ((subst_TmVar_Decls (weakenTrace d11 k) s0 (subst_TmVar_Decls (weakenTrace X0 k) s1 d12)) = (subst_TmVar_Decls (weakenTrace X0 k) (subst_TmVar_Tm d11 s0 s1) (subst_TmVar_Decls (weakenTrace (XS TmVar d11) k) s0 d12))) with
| (DNil) => eq_refl
| (DCons t7 d13) => (f_equal2 DCons (subst_TmVar__subst_TmVar_0_Tm_comm_ind t7 k d11 s0 s1) (eq_trans (f_equal3 subst_TmVar_Decls (weakenTrace_append TmVar d11 k (HS TmVar H0)) eq_refl (f_equal3 subst_TmVar_Decls (weakenTrace_append TmVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (subst_TmVar__subst_TmVar_0_Decls_comm_ind d13 (HS TmVar k) d11 s0 s1) (f_equal3 subst_TmVar_Decls (eq_sym (weakenTrace_append TmVar X0 k (HS TmVar H0))) eq_refl (f_equal3 subst_TmVar_Decls (eq_sym (weakenTrace_append TmVar (XS TmVar d11) k (HS TmVar H0))) eq_refl eq_refl)))))
end
with subst_TmVar__subst_TmVar_0_Tm_comm_ind (s2 : Tm) (k : Hvl) (d11 : (Trace TmVar)) (s0 : Tm) (s1 : Tm) {struct s2} :
((subst_TmVar_Tm (weakenTrace d11 k) s0 (subst_TmVar_Tm (weakenTrace X0 k) s1 s2)) = (subst_TmVar_Tm (weakenTrace X0 k) (subst_TmVar_Tm d11 s0 s1) (subst_TmVar_Tm (weakenTrace (XS TmVar d11) k) s0 s2))) :=
match s2 return ((subst_TmVar_Tm (weakenTrace d11 k) s0 (subst_TmVar_Tm (weakenTrace X0 k) s1 s2)) = (subst_TmVar_Tm (weakenTrace X0 k) (subst_TmVar_Tm d11 s0 s1) (subst_TmVar_Tm (weakenTrace (XS TmVar d11) k) s0 s2))) with
| (Var x8) => (subst_TmVar_Tm_subst_TmVar_Index0_commright_ind d11 s0 s1 k x8)
| (Abs T5 t8) => (f_equal2 Abs eq_refl (eq_trans (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar d11 k (HS TmVar H0)) eq_refl (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (subst_TmVar__subst_TmVar_0_Tm_comm_ind t8 (HS TmVar k) d11 s0 s1) (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar X0 k (HS TmVar H0))) eq_refl (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar (XS TmVar d11) k (HS TmVar H0))) eq_refl eq_refl)))))
| (App t9 t10) => (f_equal2 App (subst_TmVar__subst_TmVar_0_Tm_comm_ind t9 k d11 s0 s1) (subst_TmVar__subst_TmVar_0_Tm_comm_ind t10 k d11 s0 s1))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar d11 k (HS TyVar H0)) eq_refl (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar X0 k (HS TyVar H0)) eq_refl eq_refl)) (eq_trans (subst_TmVar__subst_TmVar_0_Tm_comm_ind t8 (HS TyVar k) d11 s0 s1) (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar X0 k (HS TyVar H0))) eq_refl (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar (XS TmVar d11) k (HS TyVar H0))) eq_refl eq_refl)))))
| (TApp t8 T5) => (f_equal2 TApp (subst_TmVar__subst_TmVar_0_Tm_comm_ind t8 k d11 s0 s1) eq_refl)
| (Let d14 t8) => (f_equal2 Let (subst_TmVar__subst_TmVar_0_Decls_comm_ind d14 k d11 s0 s1) (eq_trans (f_equal3 subst_TmVar_Tm (eq_trans (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (stability_subst_TmVar__bind _ _ _) (eq_refl H0)))) (weakenTrace_append TmVar d11 k (appendHvl H0 (bind d14)))) eq_refl (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar X0 k (appendHvl H0 (bind d14))) eq_refl eq_refl)) (eq_trans (subst_TmVar__subst_TmVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d14))) d11 s0 s1) (f_equal3 subst_TmVar_Tm (eq_trans (eq_sym (weakenTrace_append TmVar X0 k (appendHvl H0 (bind d14)))) (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (eq_sym (stability_subst_TmVar__bind _ _ _)) (eq_refl H0))))) eq_refl (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar (XS TmVar d11) k (appendHvl H0 (bind d14)))) eq_refl eq_refl)))))
end.
Fixpoint subst_TmVar__subst_TyVar_0_Decls_comm_ind (d12 : Decls) (k : Hvl) (d11 : (Trace TmVar)) (s0 : Tm) (S1 : Ty) {struct d12} :
((subst_TmVar_Decls (weakenTrace d11 k) s0 (subst_TyVar_Decls (weakenTrace X0 k) S1 d12)) = (subst_TyVar_Decls (weakenTrace X0 k) S1 (subst_TmVar_Decls (weakenTrace (XS TyVar d11) k) s0 d12))) :=
match d12 return ((subst_TmVar_Decls (weakenTrace d11 k) s0 (subst_TyVar_Decls (weakenTrace X0 k) S1 d12)) = (subst_TyVar_Decls (weakenTrace X0 k) S1 (subst_TmVar_Decls (weakenTrace (XS TyVar d11) k) s0 d12))) with
| (DNil) => eq_refl
| (DCons t7 d13) => (f_equal2 DCons (subst_TmVar__subst_TyVar_0_Tm_comm_ind t7 k d11 s0 S1) (eq_trans (f_equal3 subst_TmVar_Decls (weakenTrace_append TmVar d11 k (HS TmVar H0)) eq_refl (f_equal3 subst_TyVar_Decls (weakenTrace_append TyVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (subst_TmVar__subst_TyVar_0_Decls_comm_ind d13 (HS TmVar k) d11 s0 S1) (f_equal3 subst_TyVar_Decls (eq_sym (weakenTrace_append TyVar X0 k (HS TmVar H0))) eq_refl (f_equal3 subst_TmVar_Decls (eq_sym (weakenTrace_append TmVar (XS TyVar d11) k (HS TmVar H0))) eq_refl eq_refl)))))
end
with subst_TmVar__subst_TyVar_0_Tm_comm_ind (s1 : Tm) (k : Hvl) (d11 : (Trace TmVar)) (s0 : Tm) (S1 : Ty) {struct s1} :
((subst_TmVar_Tm (weakenTrace d11 k) s0 (subst_TyVar_Tm (weakenTrace X0 k) S1 s1)) = (subst_TyVar_Tm (weakenTrace X0 k) S1 (subst_TmVar_Tm (weakenTrace (XS TyVar d11) k) s0 s1))) :=
match s1 return ((subst_TmVar_Tm (weakenTrace d11 k) s0 (subst_TyVar_Tm (weakenTrace X0 k) S1 s1)) = (subst_TyVar_Tm (weakenTrace X0 k) S1 (subst_TmVar_Tm (weakenTrace (XS TyVar d11) k) s0 s1))) with
| (Var x8) => (subst_TmVar_Ty_subst_TyVar_Index0_commleft_ind d11 s0 S1 k x8)
| (Abs T5 t8) => (f_equal2 Abs eq_refl (eq_trans (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar d11 k (HS TmVar H0)) eq_refl (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (subst_TmVar__subst_TyVar_0_Tm_comm_ind t8 (HS TmVar k) d11 s0 S1) (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar X0 k (HS TmVar H0))) eq_refl (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar (XS TyVar d11) k (HS TmVar H0))) eq_refl eq_refl)))))
| (App t9 t10) => (f_equal2 App (subst_TmVar__subst_TyVar_0_Tm_comm_ind t9 k d11 s0 S1) (subst_TmVar__subst_TyVar_0_Tm_comm_ind t10 k d11 s0 S1))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar d11 k (HS TyVar H0)) eq_refl (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar X0 k (HS TyVar H0)) eq_refl eq_refl)) (eq_trans (subst_TmVar__subst_TyVar_0_Tm_comm_ind t8 (HS TyVar k) d11 s0 S1) (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar X0 k (HS TyVar H0))) eq_refl (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar (XS TyVar d11) k (HS TyVar H0))) eq_refl eq_refl)))))
| (TApp t8 T5) => (f_equal2 TApp (subst_TmVar__subst_TyVar_0_Tm_comm_ind t8 k d11 s0 S1) eq_refl)
| (Let d14 t8) => (f_equal2 Let (subst_TmVar__subst_TyVar_0_Decls_comm_ind d14 k d11 s0 S1) (eq_trans (f_equal3 subst_TmVar_Tm (eq_trans (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (stability_subst_TyVar__bind _ _ _) (eq_refl H0)))) (weakenTrace_append TmVar d11 k (appendHvl H0 (bind d14)))) eq_refl (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar X0 k (appendHvl H0 (bind d14))) eq_refl eq_refl)) (eq_trans (subst_TmVar__subst_TyVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d14))) d11 s0 S1) (f_equal3 subst_TyVar_Tm (eq_trans (eq_sym (weakenTrace_append TyVar X0 k (appendHvl H0 (bind d14)))) (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (eq_sym (stability_subst_TmVar__bind _ _ _)) (eq_refl H0))))) eq_refl (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar (XS TyVar d11) k (appendHvl H0 (bind d14)))) eq_refl eq_refl)))))
end.
Fixpoint subst_TyVar__subst_TmVar_0_Decls_comm_ind (d12 : Decls) (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) (s0 : Tm) {struct d12} :
((subst_TyVar_Decls (weakenTrace d11 k) S1 (subst_TmVar_Decls (weakenTrace X0 k) s0 d12)) = (subst_TmVar_Decls (weakenTrace X0 k) (subst_TyVar_Tm d11 S1 s0) (subst_TyVar_Decls (weakenTrace d11 k) S1 d12))) :=
match d12 return ((subst_TyVar_Decls (weakenTrace d11 k) S1 (subst_TmVar_Decls (weakenTrace X0 k) s0 d12)) = (subst_TmVar_Decls (weakenTrace X0 k) (subst_TyVar_Tm d11 S1 s0) (subst_TyVar_Decls (weakenTrace d11 k) S1 d12))) with
| (DNil) => eq_refl
| (DCons t7 d13) => (f_equal2 DCons (subst_TyVar__subst_TmVar_0_Tm_comm_ind t7 k d11 S1 s0) (eq_trans (f_equal3 subst_TyVar_Decls (weakenTrace_append TyVar d11 k (HS TmVar H0)) eq_refl (f_equal3 subst_TmVar_Decls (weakenTrace_append TmVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (subst_TyVar__subst_TmVar_0_Decls_comm_ind d13 (HS TmVar k) d11 S1 s0) (f_equal3 subst_TmVar_Decls (eq_sym (weakenTrace_append TmVar X0 k (HS TmVar H0))) eq_refl (f_equal3 subst_TyVar_Decls (eq_sym (weakenTrace_append TyVar d11 k (HS TmVar H0))) eq_refl eq_refl)))))
end
with subst_TyVar__subst_TmVar_0_Tm_comm_ind (s1 : Tm) (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) (s0 : Tm) {struct s1} :
((subst_TyVar_Tm (weakenTrace d11 k) S1 (subst_TmVar_Tm (weakenTrace X0 k) s0 s1)) = (subst_TmVar_Tm (weakenTrace X0 k) (subst_TyVar_Tm d11 S1 s0) (subst_TyVar_Tm (weakenTrace d11 k) S1 s1))) :=
match s1 return ((subst_TyVar_Tm (weakenTrace d11 k) S1 (subst_TmVar_Tm (weakenTrace X0 k) s0 s1)) = (subst_TmVar_Tm (weakenTrace X0 k) (subst_TyVar_Tm d11 S1 s0) (subst_TyVar_Tm (weakenTrace d11 k) S1 s1))) with
| (Var x8) => (subst_TyVar_Tm_subst_TmVar_Index0_commright_ind d11 S1 s0 k x8)
| (Abs T5 t8) => (f_equal2 Abs eq_refl (eq_trans (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar d11 k (HS TmVar H0)) eq_refl (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (subst_TyVar__subst_TmVar_0_Tm_comm_ind t8 (HS TmVar k) d11 S1 s0) (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar X0 k (HS TmVar H0))) eq_refl (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar d11 k (HS TmVar H0))) eq_refl eq_refl)))))
| (App t9 t10) => (f_equal2 App (subst_TyVar__subst_TmVar_0_Tm_comm_ind t9 k d11 S1 s0) (subst_TyVar__subst_TmVar_0_Tm_comm_ind t10 k d11 S1 s0))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar d11 k (HS TyVar H0)) eq_refl (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar X0 k (HS TyVar H0)) eq_refl eq_refl)) (eq_trans (subst_TyVar__subst_TmVar_0_Tm_comm_ind t8 (HS TyVar k) d11 S1 s0) (f_equal3 subst_TmVar_Tm (eq_sym (weakenTrace_append TmVar X0 k (HS TyVar H0))) eq_refl (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar d11 k (HS TyVar H0))) eq_refl eq_refl)))))
| (TApp t8 T5) => (f_equal2 TApp (subst_TyVar__subst_TmVar_0_Tm_comm_ind t8 k d11 S1 s0) eq_refl)
| (Let d14 t8) => (f_equal2 Let (subst_TyVar__subst_TmVar_0_Decls_comm_ind d14 k d11 S1 s0) (eq_trans (f_equal3 subst_TyVar_Tm (eq_trans (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (stability_subst_TmVar__bind _ _ _) (eq_refl H0)))) (weakenTrace_append TyVar d11 k (appendHvl H0 (bind d14)))) eq_refl (f_equal3 subst_TmVar_Tm (weakenTrace_append TmVar X0 k (appendHvl H0 (bind d14))) eq_refl eq_refl)) (eq_trans (subst_TyVar__subst_TmVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d14))) d11 S1 s0) (f_equal3 subst_TmVar_Tm (eq_trans (eq_sym (weakenTrace_append TmVar X0 k (appendHvl H0 (bind d14)))) (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (eq_sym (stability_subst_TyVar__bind _ _ _)) (eq_refl H0))))) eq_refl (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar d11 k (appendHvl H0 (bind d14)))) eq_refl eq_refl)))))
end.
Fixpoint subst_TyVar__subst_TyVar_0_Decls_comm_ind (d12 : Decls) (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) (S2 : Ty) {struct d12} :
((subst_TyVar_Decls (weakenTrace d11 k) S1 (subst_TyVar_Decls (weakenTrace X0 k) S2 d12)) = (subst_TyVar_Decls (weakenTrace X0 k) (subst_TyVar_Ty d11 S1 S2) (subst_TyVar_Decls (weakenTrace (XS TyVar d11) k) S1 d12))) :=
match d12 return ((subst_TyVar_Decls (weakenTrace d11 k) S1 (subst_TyVar_Decls (weakenTrace X0 k) S2 d12)) = (subst_TyVar_Decls (weakenTrace X0 k) (subst_TyVar_Ty d11 S1 S2) (subst_TyVar_Decls (weakenTrace (XS TyVar d11) k) S1 d12))) with
| (DNil) => eq_refl
| (DCons t7 d13) => (f_equal2 DCons (subst_TyVar__subst_TyVar_0_Tm_comm_ind t7 k d11 S1 S2) (eq_trans (f_equal3 subst_TyVar_Decls (weakenTrace_append TyVar d11 k (HS TmVar H0)) eq_refl (f_equal3 subst_TyVar_Decls (weakenTrace_append TyVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (subst_TyVar__subst_TyVar_0_Decls_comm_ind d13 (HS TmVar k) d11 S1 S2) (f_equal3 subst_TyVar_Decls (eq_sym (weakenTrace_append TyVar X0 k (HS TmVar H0))) eq_refl (f_equal3 subst_TyVar_Decls (eq_sym (weakenTrace_append TyVar (XS TyVar d11) k (HS TmVar H0))) eq_refl eq_refl)))))
end
with subst_TyVar__subst_TyVar_0_Tm_comm_ind (s0 : Tm) (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) (S2 : Ty) {struct s0} :
((subst_TyVar_Tm (weakenTrace d11 k) S1 (subst_TyVar_Tm (weakenTrace X0 k) S2 s0)) = (subst_TyVar_Tm (weakenTrace X0 k) (subst_TyVar_Ty d11 S1 S2) (subst_TyVar_Tm (weakenTrace (XS TyVar d11) k) S1 s0))) :=
match s0 return ((subst_TyVar_Tm (weakenTrace d11 k) S1 (subst_TyVar_Tm (weakenTrace X0 k) S2 s0)) = (subst_TyVar_Tm (weakenTrace X0 k) (subst_TyVar_Ty d11 S1 S2) (subst_TyVar_Tm (weakenTrace (XS TyVar d11) k) S1 s0))) with
| (Var x8) => eq_refl
| (Abs T5 t8) => (f_equal2 Abs (subst_TyVar__subst_TyVar_0_Ty_comm_ind T5 k d11 S1 S2) (eq_trans (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar d11 k (HS TmVar H0)) eq_refl (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar X0 k (HS TmVar H0)) eq_refl eq_refl)) (eq_trans (subst_TyVar__subst_TyVar_0_Tm_comm_ind t8 (HS TmVar k) d11 S1 S2) (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar X0 k (HS TmVar H0))) eq_refl (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar (XS TyVar d11) k (HS TmVar H0))) eq_refl eq_refl)))))
| (App t9 t10) => (f_equal2 App (subst_TyVar__subst_TyVar_0_Tm_comm_ind t9 k d11 S1 S2) (subst_TyVar__subst_TyVar_0_Tm_comm_ind t10 k d11 S1 S2))
| (TAbs t8) => (f_equal TAbs (eq_trans (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar d11 k (HS TyVar H0)) eq_refl (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar X0 k (HS TyVar H0)) eq_refl eq_refl)) (eq_trans (subst_TyVar__subst_TyVar_0_Tm_comm_ind t8 (HS TyVar k) d11 S1 S2) (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar X0 k (HS TyVar H0))) eq_refl (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar (XS TyVar d11) k (HS TyVar H0))) eq_refl eq_refl)))))
| (TApp t8 T5) => (f_equal2 TApp (subst_TyVar__subst_TyVar_0_Tm_comm_ind t8 k d11 S1 S2) (subst_TyVar__subst_TyVar_0_Ty_comm_ind T5 k d11 S1 S2))
| (Let d14 t8) => (f_equal2 Let (subst_TyVar__subst_TyVar_0_Decls_comm_ind d14 k d11 S1 S2) (eq_trans (f_equal3 subst_TyVar_Tm (eq_trans (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (stability_subst_TyVar__bind _ _ _) (eq_refl H0)))) (weakenTrace_append TyVar d11 k (appendHvl H0 (bind d14)))) eq_refl (f_equal3 subst_TyVar_Tm (weakenTrace_append TyVar X0 k (appendHvl H0 (bind d14))) eq_refl eq_refl)) (eq_trans (subst_TyVar__subst_TyVar_0_Tm_comm_ind t8 (appendHvl k (appendHvl H0 (bind d14))) d11 S1 S2) (f_equal3 subst_TyVar_Tm (eq_trans (eq_sym (weakenTrace_append TyVar X0 k (appendHvl H0 (bind d14)))) (f_equal2 weakenTrace eq_refl (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (eq_sym (stability_subst_TyVar__bind _ _ _)) (eq_refl H0))))) eq_refl (f_equal3 subst_TyVar_Tm (eq_sym (weakenTrace_append TyVar (XS TyVar d11) k (appendHvl H0 (bind d14)))) eq_refl eq_refl)))))
end.
End SubstSubstCommInd.
Section SubstSubstComm.
Definition subst_TyVar_Ty_subst_TyVar_Ty0_comm (S3 : Ty) : (forall (d11 : (Trace TyVar)) (S1 : Ty) (S2 : Ty) ,
((subst_TyVar_Ty d11 S1 (subst_TyVar_Ty X0 S2 S3)) = (subst_TyVar_Ty X0 (subst_TyVar_Ty d11 S1 S2) (subst_TyVar_Ty (XS TyVar d11) S1 S3)))) := (subst_TyVar__subst_TyVar_0_Ty_comm_ind S3 H0).
Definition subst_TmVar_Decls_subst_TmVar_Decls0_comm (d12 : Decls) : (forall (d11 : (Trace TmVar)) (s0 : Tm) (s1 : Tm) ,
((subst_TmVar_Decls d11 s0 (subst_TmVar_Decls X0 s1 d12)) = (subst_TmVar_Decls X0 (subst_TmVar_Tm d11 s0 s1) (subst_TmVar_Decls (XS TmVar d11) s0 d12)))) := (subst_TmVar__subst_TmVar_0_Decls_comm_ind d12 H0).
Definition subst_TmVar_Tm_subst_TmVar_Tm0_comm (s2 : Tm) : (forall (d11 : (Trace TmVar)) (s0 : Tm) (s1 : Tm) ,
((subst_TmVar_Tm d11 s0 (subst_TmVar_Tm X0 s1 s2)) = (subst_TmVar_Tm X0 (subst_TmVar_Tm d11 s0 s1) (subst_TmVar_Tm (XS TmVar d11) s0 s2)))) := (subst_TmVar__subst_TmVar_0_Tm_comm_ind s2 H0).
Definition subst_TmVar_Decls_subst_TyVar_Decls0_comm (d12 : Decls) : (forall (d11 : (Trace TmVar)) (s0 : Tm) (S1 : Ty) ,
((subst_TmVar_Decls d11 s0 (subst_TyVar_Decls X0 S1 d12)) = (subst_TyVar_Decls X0 S1 (subst_TmVar_Decls (XS TyVar d11) s0 d12)))) := (subst_TmVar__subst_TyVar_0_Decls_comm_ind d12 H0).
Definition subst_TmVar_Tm_subst_TyVar_Tm0_comm (s1 : Tm) : (forall (d11 : (Trace TmVar)) (s0 : Tm) (S1 : Ty) ,
((subst_TmVar_Tm d11 s0 (subst_TyVar_Tm X0 S1 s1)) = (subst_TyVar_Tm X0 S1 (subst_TmVar_Tm (XS TyVar d11) s0 s1)))) := (subst_TmVar__subst_TyVar_0_Tm_comm_ind s1 H0).
Definition subst_TyVar_Decls_subst_TmVar_Decls0_comm (d12 : Decls) : (forall (d11 : (Trace TyVar)) (S1 : Ty) (s0 : Tm) ,
((subst_TyVar_Decls d11 S1 (subst_TmVar_Decls X0 s0 d12)) = (subst_TmVar_Decls X0 (subst_TyVar_Tm d11 S1 s0) (subst_TyVar_Decls d11 S1 d12)))) := (subst_TyVar__subst_TmVar_0_Decls_comm_ind d12 H0).
Definition subst_TyVar_Tm_subst_TmVar_Tm0_comm (s1 : Tm) : (forall (d11 : (Trace TyVar)) (S1 : Ty) (s0 : Tm) ,
((subst_TyVar_Tm d11 S1 (subst_TmVar_Tm X0 s0 s1)) = (subst_TmVar_Tm X0 (subst_TyVar_Tm d11 S1 s0) (subst_TyVar_Tm d11 S1 s1)))) := (subst_TyVar__subst_TmVar_0_Tm_comm_ind s1 H0).
Definition subst_TyVar_Decls_subst_TyVar_Decls0_comm (d12 : Decls) : (forall (d11 : (Trace TyVar)) (S1 : Ty) (S2 : Ty) ,
((subst_TyVar_Decls d11 S1 (subst_TyVar_Decls X0 S2 d12)) = (subst_TyVar_Decls X0 (subst_TyVar_Ty d11 S1 S2) (subst_TyVar_Decls (XS TyVar d11) S1 d12)))) := (subst_TyVar__subst_TyVar_0_Decls_comm_ind d12 H0).
Definition subst_TyVar_Tm_subst_TyVar_Tm0_comm (s0 : Tm) : (forall (d11 : (Trace TyVar)) (S1 : Ty) (S2 : Ty) ,
((subst_TyVar_Tm d11 S1 (subst_TyVar_Tm X0 S2 s0)) = (subst_TyVar_Tm X0 (subst_TyVar_Ty d11 S1 S2) (subst_TyVar_Tm (XS TyVar d11) S1 s0)))) := (subst_TyVar__subst_TyVar_0_Tm_comm_ind s0 H0).
End SubstSubstComm.
Section WeakenSubst.
Lemma weakenTy_subst_TyVar_Ty :
(forall (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) (S2 : Ty) ,
((weakenTy (subst_TyVar_Ty d11 S1 S2) k) = (subst_TyVar_Ty (weakenTrace d11 k) S1 (weakenTy S2 k)))).
Proof.
needleGenericWeakenSubst .
Qed.
Lemma weakenDecls_subst_TmVar_Decls :
(forall (k : Hvl) (d11 : (Trace TmVar)) (s0 : Tm) (d12 : Decls) ,
((weakenDecls (subst_TmVar_Decls d11 s0 d12) k) = (subst_TmVar_Decls (weakenTrace d11 k) s0 (weakenDecls d12 k)))).
Proof.
needleGenericWeakenSubst .
Qed.
Lemma weakenTm_subst_TmVar_Tm :
(forall (k : Hvl) (d11 : (Trace TmVar)) (s0 : Tm) (s1 : Tm) ,
((weakenTm (subst_TmVar_Tm d11 s0 s1) k) = (subst_TmVar_Tm (weakenTrace d11 k) s0 (weakenTm s1 k)))).
Proof.
needleGenericWeakenSubst .
Qed.
Lemma weakenDecls_subst_TyVar_Decls :
(forall (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) (d12 : Decls) ,
((weakenDecls (subst_TyVar_Decls d11 S1 d12) k) = (subst_TyVar_Decls (weakenTrace d11 k) S1 (weakenDecls d12 k)))).
Proof.
needleGenericWeakenSubst .
Qed.
Lemma weakenTm_subst_TyVar_Tm :
(forall (k : Hvl) (d11 : (Trace TyVar)) (S1 : Ty) (s0 : Tm) ,
((weakenTm (subst_TyVar_Tm d11 S1 s0) k) = (subst_TyVar_Tm (weakenTrace d11 k) S1 (weakenTm s0 k)))).
Proof.
needleGenericWeakenSubst .
Qed.
End WeakenSubst.
End SubstSubstInteraction.
Hint Rewrite subst_TmVar_Decls_subst_TmVar_Decls0_comm subst_TyVar_Decls_subst_TyVar_Decls0_comm subst_TmVar_Tm_subst_TmVar_Tm0_comm subst_TyVar_Tm_subst_TyVar_Tm0_comm subst_TyVar_Ty_subst_TyVar_Ty0_comm : interaction.
Hint Rewrite subst_TmVar_Decls_subst_TmVar_Decls0_comm subst_TyVar_Decls_subst_TyVar_Decls0_comm subst_TmVar_Tm_subst_TmVar_Tm0_comm subst_TyVar_Tm_subst_TyVar_Tm0_comm subst_TyVar_Ty_subst_TyVar_Ty0_comm : subst_subst0.
Hint Rewrite weakenDecls_shift_TmVar_Decls weakenDecls_shift_TyVar_Decls weakenTm_shift_TmVar_Tm weakenTm_shift_TyVar_Tm weakenTy_shift_TyVar_Ty : weaken_shift.
Hint Rewrite weakenDecls_subst_TmVar_Decls weakenDecls_subst_TyVar_Decls weakenTm_subst_TmVar_Tm weakenTm_subst_TyVar_Tm weakenTy_subst_TyVar_Ty : weaken_subst.
Section WellFormed.
Fixpoint wfindex {a : Namespace} (k : Hvl) (i : (Index a)) {struct k} :
Prop :=
match k with
| (H0) => False
| (HS b k) => match (eq_namespace_dec a b) with
| (left e) => match i with
| (I0) => True
| (IS i) => (wfindex k i)
end
| (right n) => (wfindex k i)
end
end.
Inductive wfTy (k : Hvl) : Ty -> Prop :=
| wfTy_TVar
(X7 : (Index TyVar))
(wfi : (wfindex k X7)) :
(wfTy k (TVar X7))
| wfTy_TArr {T5 : Ty}
(wf : (wfTy k T5)) {T6 : Ty}
(wf0 : (wfTy k T6)) :
(wfTy k (TArr T5 T6))
| wfTy_TAll {T7 : Ty}
(wf : (wfTy (HS TyVar k) T7)) :
(wfTy k (TAll T7)).
Inductive wfDecls (k : Hvl) : Decls -> Prop :=
| wfDecls_DNil :
(wfDecls k (DNil))
| wfDecls_DCons {t7 : Tm}
(wf : (wfTm k t7)) {d11 : Decls}
(wf0 : (wfDecls (HS TmVar k) d11))
: (wfDecls k (DCons t7 d11))
with wfTm (k : Hvl) : Tm -> Prop :=
| wfTm_Var
(x7 : (Index TmVar))
(wfi : (wfindex k x7)) :
(wfTm k (Var x7))
| wfTm_Abs {T5 : Ty}
(wf : (wfTy k T5)) {t7 : Tm}
(wf0 : (wfTm (HS TmVar k) t7)) :
(wfTm k (Abs T5 t7))
| wfTm_App {t8 : Tm}
(wf : (wfTm k t8)) {t9 : Tm}
(wf0 : (wfTm k t9)) :
(wfTm k (App t8 t9))
| wfTm_TAbs {t10 : Tm}
(wf : (wfTm (HS TyVar k) t10)) :
(wfTm k (TAbs t10))
| wfTm_TApp {t11 : Tm}
(wf : (wfTm k t11)) {T6 : Ty}
(wf0 : (wfTy k T6)) :
(wfTm k (TApp t11 T6))
| wfTm_Let {d11 : Decls}
(wf : (wfDecls k d11))
{t12 : Tm}
(wf0 : (wfTm (appendHvl k (appendHvl H0 (bind d11))) t12))
: (wfTm k (Let d11 t12)).
Definition inversion_wfTy_TVar_1 (k : Hvl) (X : (Index TyVar)) (H18 : (wfTy k (TVar X))) : (wfindex k X) := match H18 in (wfTy _ S1) return match S1 return Prop with
| (TVar X) => (wfindex k X)
| _ => True
end with
| (wfTy_TVar X H1) => H1
| _ => I
end.
Definition inversion_wfTy_TArr_0 (k0 : Hvl) (T1 : Ty) (T2 : Ty) (H19 : (wfTy k0 (TArr T1 T2))) : (wfTy k0 T1) := match H19 in (wfTy _ S2) return match S2 return Prop with
| (TArr T1 T2) => (wfTy k0 T1)
| _ => True
end with
| (wfTy_TArr T1 H2 T2 H3) => H2
| _ => I
end.
Definition inversion_wfTy_TArr_1 (k0 : Hvl) (T1 : Ty) (T2 : Ty) (H19 : (wfTy k0 (TArr T1 T2))) : (wfTy k0 T2) := match H19 in (wfTy _ S2) return match S2 return Prop with
| (TArr T1 T2) => (wfTy k0 T2)
| _ => True
end with
| (wfTy_TArr T1 H2 T2 H3) => H3
| _ => I
end.
Definition inversion_wfTy_TAll_1 (k1 : Hvl) (T : Ty) (H20 : (wfTy k1 (TAll T))) : (wfTy (HS TyVar k1) T) := match H20 in (wfTy _ S3) return match S3 return Prop with
| (TAll T) => (wfTy (HS TyVar k1) T)
| _ => True
end with
| (wfTy_TAll T H4) => H4
| _ => I
end.
Definition inversion_wfDecls_DCons_1 (k3 : Hvl) (t : Tm) (d : Decls) (H22 : (wfDecls k3 (DCons t d))) : (wfTm k3 t) := match H22 in (wfDecls _ d12) return match d12 return Prop with
| (DCons t d) => (wfTm k3 t)
| _ => True
end with
| (wfDecls_DCons t H5 d H6) => H5
| _ => I
end.
Definition inversion_wfDecls_DCons_2 (k3 : Hvl) (t : Tm) (d : Decls) (H22 : (wfDecls k3 (DCons t d))) : (wfDecls (HS TmVar k3) d) := match H22 in (wfDecls _ d12) return match d12 return Prop with
| (DCons t d) => (wfDecls (HS TmVar k3) d)
| _ => True
end with
| (wfDecls_DCons t H5 d H6) => H6
| _ => I
end.
Definition inversion_wfTm_Var_1 (k4 : Hvl) (x : (Index TmVar)) (H23 : (wfTm k4 (Var x))) : (wfindex k4 x) := match H23 in (wfTm _ s0) return match s0 return Prop with
| (Var x) => (wfindex k4 x)
| _ => True
end with
| (wfTm_Var x H7) => H7
| _ => I
end.
Definition inversion_wfTm_Abs_1 (k5 : Hvl) (T : Ty) (t : Tm) (H24 : (wfTm k5 (Abs T t))) : (wfTy k5 T) := match H24 in (wfTm _ s1) return match s1 return Prop with
| (Abs T t) => (wfTy k5 T)
| _ => True
end with
| (wfTm_Abs T H8 t H9) => H8
| _ => I
end.
Definition inversion_wfTm_Abs_2 (k5 : Hvl) (T : Ty) (t : Tm) (H24 : (wfTm k5 (Abs T t))) : (wfTm (HS TmVar k5) t) := match H24 in (wfTm _ s1) return match s1 return Prop with
| (Abs T t) => (wfTm (HS TmVar k5) t)
| _ => True
end with
| (wfTm_Abs T H8 t H9) => H9
| _ => I
end.
Definition inversion_wfTm_App_0 (k6 : Hvl) (t1 : Tm) (t2 : Tm) (H25 : (wfTm k6 (App t1 t2))) : (wfTm k6 t1) := match H25 in (wfTm _ s2) return match s2 return Prop with
| (App t1 t2) => (wfTm k6 t1)
| _ => True
end with
| (wfTm_App t1 H10 t2 H11) => H10
| _ => I
end.
Definition inversion_wfTm_App_1 (k6 : Hvl) (t1 : Tm) (t2 : Tm) (H25 : (wfTm k6 (App t1 t2))) : (wfTm k6 t2) := match H25 in (wfTm _ s2) return match s2 return Prop with
| (App t1 t2) => (wfTm k6 t2)
| _ => True
end with
| (wfTm_App t1 H10 t2 H11) => H11
| _ => I
end.
Definition inversion_wfTm_TAbs_1 (k7 : Hvl) (t : Tm) (H26 : (wfTm k7 (TAbs t))) : (wfTm (HS TyVar k7) t) := match H26 in (wfTm _ s3) return match s3 return Prop with
| (TAbs t) => (wfTm (HS TyVar k7) t)
| _ => True
end with
| (wfTm_TAbs t H12) => H12
| _ => I
end.
Definition inversion_wfTm_TApp_0 (k8 : Hvl) (t : Tm) (T : Ty) (H27 : (wfTm k8 (TApp t T))) : (wfTm k8 t) := match H27 in (wfTm _ s4) return match s4 return Prop with
| (TApp t T) => (wfTm k8 t)
| _ => True
end with
| (wfTm_TApp t H13 T H14) => H13
| _ => I
end.
Definition inversion_wfTm_TApp_1 (k8 : Hvl) (t : Tm) (T : Ty) (H27 : (wfTm k8 (TApp t T))) : (wfTy k8 T) := match H27 in (wfTm _ s4) return match s4 return Prop with
| (TApp t T) => (wfTy k8 T)
| _ => True
end with
| (wfTm_TApp t H13 T H14) => H14
| _ => I
end.
Definition inversion_wfTm_Let_0 (k9 : Hvl) (d : Decls) (t : Tm) (H28 : (wfTm k9 (Let d t))) : (wfDecls k9 d) := match H28 in (wfTm _ s5) return match s5 return Prop with
| (Let d t) => (wfDecls k9 d)
| _ => True
end with
| (wfTm_Let d H15 t H16) => H15
| _ => I
end.
Definition inversion_wfTm_Let_1 (k9 : Hvl) (d : Decls) (t : Tm) (H28 : (wfTm k9 (Let d t))) : (wfTm (appendHvl k9 (appendHvl H0 (bind d))) t) := match H28 in (wfTm _ s5) return match s5 return Prop with
| (Let d t) => (wfTm (appendHvl k9 (appendHvl H0 (bind d))) t)
| _ => True
end with
| (wfTm_Let d H15 t H16) => H16
| _ => I
end.
Scheme ind_wfTy := Induction for wfTy Sort Prop.
Scheme ind_wfDecls := Induction for wfDecls Sort Prop
with ind_wfTm := Induction for wfTm Sort Prop.
Combined Scheme ind_wfDecls_Tm from ind_wfDecls, ind_wfTm.
End WellFormed.
Section ShiftWellFormed.
Inductive shifthvl_TmVar : (forall (c1 : (Cutoff TmVar)) (k10 : Hvl) (k11 : Hvl) ,
Prop) :=
| shifthvl_TmVar_here
(k10 : Hvl) :
(shifthvl_TmVar C0 k10 (HS TmVar k10))
| shifthvl_TmVar_there_TmVar
(c1 : (Cutoff TmVar))
(k10 : Hvl) (k11 : Hvl) :
(shifthvl_TmVar c1 k10 k11) -> (shifthvl_TmVar (CS c1) (HS TmVar k10) (HS TmVar k11))
| shifthvl_TmVar_there_TyVar
(c1 : (Cutoff TmVar))
(k10 : Hvl) (k11 : Hvl) :
(shifthvl_TmVar c1 k10 k11) -> (shifthvl_TmVar c1 (HS TyVar k10) (HS TyVar k11)).
Inductive shifthvl_TyVar : (forall (c1 : (Cutoff TyVar)) (k10 : Hvl) (k11 : Hvl) ,
Prop) :=
| shifthvl_TyVar_here
(k10 : Hvl) :
(shifthvl_TyVar C0 k10 (HS TyVar k10))
| shifthvl_TyVar_there_TmVar
(c1 : (Cutoff TyVar))
(k10 : Hvl) (k11 : Hvl) :
(shifthvl_TyVar c1 k10 k11) -> (shifthvl_TyVar c1 (HS TmVar k10) (HS TmVar k11))
| shifthvl_TyVar_there_TyVar
(c1 : (Cutoff TyVar))
(k10 : Hvl) (k11 : Hvl) :
(shifthvl_TyVar c1 k10 k11) -> (shifthvl_TyVar (CS c1) (HS TyVar k10) (HS TyVar k11)).
Lemma weaken_shifthvl_TmVar :
(forall (k10 : Hvl) {c1 : (Cutoff TmVar)} {k11 : Hvl} {k12 : Hvl} ,
(shifthvl_TmVar c1 k11 k12) -> (shifthvl_TmVar (weakenCutoffTmVar c1 k10) (appendHvl k11 k10) (appendHvl k12 k10))).
Proof.
needleGenericWeakenHVarlistInsert .
Qed.
Lemma weaken_shifthvl_TyVar :
(forall (k10 : Hvl) {c1 : (Cutoff TyVar)} {k11 : Hvl} {k12 : Hvl} ,
(shifthvl_TyVar c1 k11 k12) -> (shifthvl_TyVar (weakenCutoffTyVar c1 k10) (appendHvl k11 k10) (appendHvl k12 k10))).
Proof.
needleGenericWeakenHVarlistInsert .
Qed.
Lemma shift_TmVar__wfindex_TmVar :
(forall (c1 : (Cutoff TmVar)) (k10 : Hvl) (k11 : Hvl) (ins : (shifthvl_TmVar c1 k10 k11)) (x7 : (Index TmVar)) ,
(wfindex k10 x7) -> (wfindex k11 (shift_TmVar_Index c1 x7))).
Proof.
needleGenericShiftWellFormedIndex .
Qed.
Lemma shift_TmVar__wfindex_TyVar :
(forall (c1 : (Cutoff TmVar)) (k10 : Hvl) (k11 : Hvl) (ins : (shifthvl_TmVar c1 k10 k11)) (X7 : (Index TyVar)) ,
(wfindex k10 X7) -> (wfindex k11 X7)).
Proof.
needleGenericShiftWellFormedIndex .
Qed.
Lemma shift_TyVar__wfindex_TmVar :
(forall (c1 : (Cutoff TyVar)) (k10 : Hvl) (k11 : Hvl) (ins : (shifthvl_TyVar c1 k10 k11)) (x7 : (Index TmVar)) ,
(wfindex k10 x7) -> (wfindex k11 x7)).
Proof.
needleGenericShiftWellFormedIndex .
Qed.
Lemma shift_TyVar__wfindex_TyVar :
(forall (c1 : (Cutoff TyVar)) (k10 : Hvl) (k11 : Hvl) (ins : (shifthvl_TyVar c1 k10 k11)) (X7 : (Index TyVar)) ,
(wfindex k10 X7) -> (wfindex k11 (shift_TyVar_Index c1 X7))).
Proof.
needleGenericShiftWellFormedIndex .
Qed.
Definition shift_TmVar__wfTy : (forall (k10 : Hvl) ,
(forall (S4 : Ty) (wf : (wfTy k10 S4)) ,
(forall (c1 : (Cutoff TmVar)) (k11 : Hvl) ,
(shifthvl_TmVar c1 k10 k11) -> (wfTy k11 S4)))) := (ind_wfTy (fun (k10 : Hvl) (S4 : Ty) (wf : (wfTy k10 S4)) =>
(forall (c1 : (Cutoff TmVar)) (k11 : Hvl) ,
(shifthvl_TmVar c1 k10 k11) -> (wfTy k11 S4))) (fun (k10 : Hvl) (X7 : (Index TyVar)) (wfi : (wfindex k10 X7)) (c1 : (Cutoff TmVar)) (k11 : Hvl) (ins : (shifthvl_TmVar c1 k10 k11)) =>
(wfTy_TVar k11 _ (shift_TmVar__wfindex_TyVar c1 k10 k11 ins X7 wfi))) (fun (k10 : Hvl) (T1 : Ty) (wf : (wfTy k10 T1)) IHT1 (T2 : Ty) (wf0 : (wfTy k10 T2)) IHT2 (c1 : (Cutoff TmVar)) (k11 : Hvl) (ins : (shifthvl_TmVar c1 k10 k11)) =>
(wfTy_TArr k11 (IHT1 c1 k11 (weaken_shifthvl_TmVar H0 ins)) (IHT2 c1 k11 (weaken_shifthvl_TmVar H0 ins)))) (fun (k10 : Hvl) (T : Ty) (wf : (wfTy (HS TyVar k10) T)) IHT (c1 : (Cutoff TmVar)) (k11 : Hvl) (ins : (shifthvl_TmVar c1 k10 k11)) =>
(wfTy_TAll k11 (IHT c1 (HS TyVar k11) (weaken_shifthvl_TmVar (HS TyVar H0) ins))))).
Definition shift_TyVar__wfTy : (forall (k10 : Hvl) ,
(forall (S4 : Ty) (wf : (wfTy k10 S4)) ,
(forall (c1 : (Cutoff TyVar)) (k11 : Hvl) ,
(shifthvl_TyVar c1 k10 k11) -> (wfTy k11 (shift_TyVar_Ty c1 S4))))) := (ind_wfTy (fun (k10 : Hvl) (S4 : Ty) (wf : (wfTy k10 S4)) =>
(forall (c1 : (Cutoff TyVar)) (k11 : Hvl) ,
(shifthvl_TyVar c1 k10 k11) -> (wfTy k11 (shift_TyVar_Ty c1 S4)))) (fun (k10 : Hvl) (X7 : (Index TyVar)) (wfi : (wfindex k10 X7)) (c1 : (Cutoff TyVar)) (k11 : Hvl) (ins : (shifthvl_TyVar c1 k10 k11)) =>
(wfTy_TVar k11 _ (shift_TyVar__wfindex_TyVar c1 k10 k11 ins X7 wfi))) (fun (k10 : Hvl) (T1 : Ty) (wf : (wfTy k10 T1)) IHT1 (T2 : Ty) (wf0 : (wfTy k10 T2)) IHT2 (c1 : (Cutoff TyVar)) (k11 : Hvl) (ins : (shifthvl_TyVar c1 k10 k11)) =>
(wfTy_TArr k11 (IHT1 c1 k11 (weaken_shifthvl_TyVar H0 ins)) (IHT2 c1 k11 (weaken_shifthvl_TyVar H0 ins)))) (fun (k10 : Hvl) (T : Ty) (wf : (wfTy (HS TyVar k10) T)) IHT (c1 : (Cutoff TyVar)) (k11 : Hvl) (ins : (shifthvl_TyVar c1 k10 k11)) =>
(wfTy_TAll k11 (IHT (CS c1) (HS TyVar k11) (weaken_shifthvl_TyVar (HS TyVar H0) ins))))).
Definition shift_TmVar__wfDecls_Tm : (forall (k10 : Hvl) ,
(forall (d13 : Decls) (wf : (wfDecls k10 d13)) ,
(forall (c1 : (Cutoff TmVar)) (k11 : Hvl) ,
(shifthvl_TmVar c1 k10 k11) -> (wfDecls k11 (shift_TmVar_Decls c1 d13)))) /\
(forall (s6 : Tm) (wf : (wfTm k10 s6)) ,
(forall (c1 : (Cutoff TmVar)) (k11 : Hvl) ,
(shifthvl_TmVar c1 k10 k11) -> (wfTm k11 (shift_TmVar_Tm c1 s6))))) := (ind_wfDecls_Tm (fun (k10 : Hvl) (d13 : Decls) (wf : (wfDecls k10 d13)) =>
(forall (c1 : (Cutoff TmVar)) (k11 : Hvl) ,
(shifthvl_TmVar c1 k10 k11) -> (wfDecls k11 (shift_TmVar_Decls c1 d13)))) (fun (k10 : Hvl) (s6 : Tm) (wf : (wfTm k10 s6)) =>
(forall (c1 : (Cutoff TmVar)) (k11 : Hvl) ,
(shifthvl_TmVar c1 k10 k11) -> (wfTm k11 (shift_TmVar_Tm c1 s6)))) (fun (k10 : Hvl) (c1 : (Cutoff TmVar)) (k11 : Hvl) (ins : (shifthvl_TmVar c1 k10 k11)) =>
(wfDecls_DNil k11)) (fun (k10 : Hvl) (t : Tm) (wf : (wfTm k10 t)) IHt (d : Decls) (wf0 : (wfDecls (HS TmVar k10) d)) IHd (c1 : (Cutoff TmVar)) (k11 : Hvl) (ins : (shifthvl_TmVar c1 k10 k11)) =>
(wfDecls_DCons k11 (IHt c1 k11 (weaken_shifthvl_TmVar H0 ins)) (IHd (CS c1) (HS TmVar k11) (weaken_shifthvl_TmVar (HS TmVar H0) ins)))) (fun (k10 : Hvl) (x7 : (Index TmVar)) (wfi : (wfindex k10 x7)) (c1 : (Cutoff TmVar)) (k11 : Hvl) (ins : (shifthvl_TmVar c1 k10 k11)) =>
(wfTm_Var k11 _ (shift_TmVar__wfindex_TmVar c1 k10 k11 ins x7 wfi))) (fun (k10 : Hvl) (T : Ty) (wf : (wfTy k10 T)) (t : Tm) (wf0 : (wfTm (HS TmVar k10) t)) IHt (c1 : (Cutoff TmVar)) (k11 : Hvl) (ins : (shifthvl_TmVar c1 k10 k11)) =>
(wfTm_Abs k11 (shift_TmVar__wfTy k10 T wf c1 k11 (weaken_shifthvl_TmVar H0 ins)) (IHt (CS c1) (HS TmVar k11) (weaken_shifthvl_TmVar (HS TmVar H0) ins)))) (fun (k10 : Hvl) (t1 : Tm) (wf : (wfTm k10 t1)) IHt1 (t2 : Tm) (wf0 : (wfTm k10 t2)) IHt2 (c1 : (Cutoff TmVar)) (k11 : Hvl) (ins : (shifthvl_TmVar c1 k10 k11)) =>
(wfTm_App k11 (IHt1 c1 k11 (weaken_shifthvl_TmVar H0 ins)) (IHt2 c1 k11 (weaken_shifthvl_TmVar H0 ins)))) (fun (k10 : Hvl) (t : Tm) (wf : (wfTm (HS TyVar k10) t)) IHt (c1 : (Cutoff TmVar)) (k11 : Hvl) (ins : (shifthvl_TmVar c1 k10 k11)) =>
(wfTm_TAbs k11 (IHt c1 (HS TyVar k11) (weaken_shifthvl_TmVar (HS TyVar H0) ins)))) (fun (k10 : Hvl) (t : Tm) (wf : (wfTm k10 t)) IHt (T : Ty) (wf0 : (wfTy k10 T)) (c1 : (Cutoff TmVar)) (k11 : Hvl) (ins : (shifthvl_TmVar c1 k10 k11)) =>
(wfTm_TApp k11 (IHt c1 k11 (weaken_shifthvl_TmVar H0 ins)) (shift_TmVar__wfTy k10 T wf0 c1 k11 (weaken_shifthvl_TmVar H0 ins)))) (fun (k10 : Hvl) (d : Decls) (wf : (wfDecls k10 d)) IHd (t : Tm) (wf0 : (wfTm (appendHvl k10 (appendHvl H0 (bind d))) t)) IHt (c1 : (Cutoff TmVar)) (k11 : Hvl) (ins : (shifthvl_TmVar c1 k10 k11)) =>
(wfTm_Let k11 (IHd c1 k11 (weaken_shifthvl_TmVar H0 ins)) (eq_ind2 wfTm (f_equal2 appendHvl (eq_refl k11) (f_equal2 appendHvl (eq_refl H0) (eq_sym (stability_shift_TmVar__bind _ _)))) eq_refl (IHt (weakenCutoffTmVar c1 (appendHvl H0 (bind d))) (appendHvl k11 (appendHvl H0 (bind d))) (weaken_shifthvl_TmVar (appendHvl H0 (bind d)) ins)))))).
Lemma shift_TmVar__wfDecls (k10 : Hvl) :
(forall (d13 : Decls) (wf : (wfDecls k10 d13)) ,
(forall (c1 : (Cutoff TmVar)) (k11 : Hvl) ,
(shifthvl_TmVar c1 k10 k11) -> (wfDecls k11 (shift_TmVar_Decls c1 d13)))).
Proof.
pose proof ((shift_TmVar__wfDecls_Tm k10)).
destruct_conjs .
easy .
Qed.
Lemma shift_TmVar__wfTm (k10 : Hvl) :
(forall (s6 : Tm) (wf0 : (wfTm k10 s6)) ,
(forall (c2 : (Cutoff TmVar)) (k12 : Hvl) ,
(shifthvl_TmVar c2 k10 k12) -> (wfTm k12 (shift_TmVar_Tm c2 s6)))).
Proof.
pose proof ((shift_TmVar__wfDecls_Tm k10)).
destruct_conjs .
easy .
Qed.
Definition shift_TyVar__wfDecls_Tm : (forall (k10 : Hvl) ,
(forall (d13 : Decls) (wf : (wfDecls k10 d13)) ,
(forall (c1 : (Cutoff TyVar)) (k11 : Hvl) ,
(shifthvl_TyVar c1 k10 k11) -> (wfDecls k11 (shift_TyVar_Decls c1 d13)))) /\
(forall (s6 : Tm) (wf : (wfTm k10 s6)) ,
(forall (c1 : (Cutoff TyVar)) (k11 : Hvl) ,
(shifthvl_TyVar c1 k10 k11) -> (wfTm k11 (shift_TyVar_Tm c1 s6))))) := (ind_wfDecls_Tm (fun (k10 : Hvl) (d13 : Decls) (wf : (wfDecls k10 d13)) =>
(forall (c1 : (Cutoff TyVar)) (k11 : Hvl) ,
(shifthvl_TyVar c1 k10 k11) -> (wfDecls k11 (shift_TyVar_Decls c1 d13)))) (fun (k10 : Hvl) (s6 : Tm) (wf : (wfTm k10 s6)) =>
(forall (c1 : (Cutoff TyVar)) (k11 : Hvl) ,
(shifthvl_TyVar c1 k10 k11) -> (wfTm k11 (shift_TyVar_Tm c1 s6)))) (fun (k10 : Hvl) (c1 : (Cutoff TyVar)) (k11 : Hvl) (ins : (shifthvl_TyVar c1 k10 k11)) =>
(wfDecls_DNil k11)) (fun (k10 : Hvl) (t : Tm) (wf : (wfTm k10 t)) IHt (d : Decls) (wf0 : (wfDecls (HS TmVar k10) d)) IHd (c1 : (Cutoff TyVar)) (k11 : Hvl) (ins : (shifthvl_TyVar c1 k10 k11)) =>
(wfDecls_DCons k11 (IHt c1 k11 (weaken_shifthvl_TyVar H0 ins)) (IHd c1 (HS TmVar k11) (weaken_shifthvl_TyVar (HS TmVar H0) ins)))) (fun (k10 : Hvl) (x7 : (Index TmVar)) (wfi : (wfindex k10 x7)) (c1 : (Cutoff TyVar)) (k11 : Hvl) (ins : (shifthvl_TyVar c1 k10 k11)) =>
(wfTm_Var k11 _ (shift_TyVar__wfindex_TmVar c1 k10 k11 ins x7 wfi))) (fun (k10 : Hvl) (T : Ty) (wf : (wfTy k10 T)) (t : Tm) (wf0 : (wfTm (HS TmVar k10) t)) IHt (c1 : (Cutoff TyVar)) (k11 : Hvl) (ins : (shifthvl_TyVar c1 k10 k11)) =>
(wfTm_Abs k11 (shift_TyVar__wfTy k10 T wf c1 k11 (weaken_shifthvl_TyVar H0 ins)) (IHt c1 (HS TmVar k11) (weaken_shifthvl_TyVar (HS TmVar H0) ins)))) (fun (k10 : Hvl) (t1 : Tm) (wf : (wfTm k10 t1)) IHt1 (t2 : Tm) (wf0 : (wfTm k10 t2)) IHt2 (c1 : (Cutoff TyVar)) (k11 : Hvl) (ins : (shifthvl_TyVar c1 k10 k11)) =>
(wfTm_App k11 (IHt1 c1 k11 (weaken_shifthvl_TyVar H0 ins)) (IHt2 c1 k11 (weaken_shifthvl_TyVar H0 ins)))) (fun (k10 : Hvl) (t : Tm) (wf : (wfTm (HS TyVar k10) t)) IHt (c1 : (Cutoff TyVar)) (k11 : Hvl) (ins : (shifthvl_TyVar c1 k10 k11)) =>
(wfTm_TAbs k11 (IHt (CS c1) (HS TyVar k11) (weaken_shifthvl_TyVar (HS TyVar H0) ins)))) (fun (k10 : Hvl) (t : Tm) (wf : (wfTm k10 t)) IHt (T : Ty) (wf0 : (wfTy k10 T)) (c1 : (Cutoff TyVar)) (k11 : Hvl) (ins : (shifthvl_TyVar c1 k10 k11)) =>
(wfTm_TApp k11 (IHt c1 k11 (weaken_shifthvl_TyVar H0 ins)) (shift_TyVar__wfTy k10 T wf0 c1 k11 (weaken_shifthvl_TyVar H0 ins)))) (fun (k10 : Hvl) (d : Decls) (wf : (wfDecls k10 d)) IHd (t : Tm) (wf0 : (wfTm (appendHvl k10 (appendHvl H0 (bind d))) t)) IHt (c1 : (Cutoff TyVar)) (k11 : Hvl) (ins : (shifthvl_TyVar c1 k10 k11)) =>
(wfTm_Let k11 (IHd c1 k11 (weaken_shifthvl_TyVar H0 ins)) (eq_ind2 wfTm (f_equal2 appendHvl (eq_refl k11) (f_equal2 appendHvl (eq_refl H0) (eq_sym (stability_shift_TyVar__bind _ _)))) eq_refl (IHt (weakenCutoffTyVar c1 (appendHvl H0 (bind d))) (appendHvl k11 (appendHvl H0 (bind d))) (weaken_shifthvl_TyVar (appendHvl H0 (bind d)) ins)))))).
Lemma shift_TyVar__wfDecls (k10 : Hvl) :
(forall (d13 : Decls) (wf : (wfDecls k10 d13)) ,
(forall (c1 : (Cutoff TyVar)) (k11 : Hvl) ,
(shifthvl_TyVar c1 k10 k11) -> (wfDecls k11 (shift_TyVar_Decls c1 d13)))).
Proof.
pose proof ((shift_TyVar__wfDecls_Tm k10)).
destruct_conjs .
easy .
Qed.
Lemma shift_TyVar__wfTm (k10 : Hvl) :
(forall (s6 : Tm) (wf0 : (wfTm k10 s6)) ,
(forall (c2 : (Cutoff TyVar)) (k12 : Hvl) ,
(shifthvl_TyVar c2 k10 k12) -> (wfTm k12 (shift_TyVar_Tm c2 s6)))).
Proof.
pose proof ((shift_TyVar__wfDecls_Tm k10)).
destruct_conjs .
easy .
Qed.
Fixpoint weaken_wfTy (k10 : Hvl) {struct k10} :
(forall (k11 : Hvl) (S4 : Ty) (wf : (wfTy k11 S4)) ,
(wfTy (appendHvl k11 k10) (weakenTy S4 k10))) :=
match k10 return (forall (k11 : Hvl) (S4 : Ty) (wf : (wfTy k11 S4)) ,
(wfTy (appendHvl k11 k10) (weakenTy S4 k10))) with
| (H0) => (fun (k11 : Hvl) (S4 : Ty) (wf : (wfTy k11 S4)) =>
wf)
| (HS TmVar k10) => (fun (k11 : Hvl) (S4 : Ty) (wf : (wfTy k11 S4)) =>
(shift_TmVar__wfTy (appendHvl k11 k10) (weakenTy S4 k10) (weaken_wfTy k10 k11 S4 wf) C0 (HS TmVar (appendHvl k11 k10)) (shifthvl_TmVar_here (appendHvl k11 k10))))
| (HS TyVar k10) => (fun (k11 : Hvl) (S4 : Ty) (wf : (wfTy k11 S4)) =>
(shift_TyVar__wfTy (appendHvl k11 k10) (weakenTy S4 k10) (weaken_wfTy k10 k11 S4 wf) C0 (HS TyVar (appendHvl k11 k10)) (shifthvl_TyVar_here (appendHvl k11 k10))))
end.
Fixpoint weaken_wfDecls (k10 : Hvl) {struct k10} :
(forall (k11 : Hvl) (d13 : Decls) (wf : (wfDecls k11 d13)) ,
(wfDecls (appendHvl k11 k10) (weakenDecls d13 k10))) :=
match k10 return (forall (k11 : Hvl) (d13 : Decls) (wf : (wfDecls k11 d13)) ,
(wfDecls (appendHvl k11 k10) (weakenDecls d13 k10))) with
| (H0) => (fun (k11 : Hvl) (d13 : Decls) (wf : (wfDecls k11 d13)) =>
wf)
| (HS TmVar k10) => (fun (k11 : Hvl) (d13 : Decls) (wf : (wfDecls k11 d13)) =>
(shift_TmVar__wfDecls (appendHvl k11 k10) (weakenDecls d13 k10) (weaken_wfDecls k10 k11 d13 wf) C0 (HS TmVar (appendHvl k11 k10)) (shifthvl_TmVar_here (appendHvl k11 k10))))
| (HS TyVar k10) => (fun (k11 : Hvl) (d13 : Decls) (wf : (wfDecls k11 d13)) =>
(shift_TyVar__wfDecls (appendHvl k11 k10) (weakenDecls d13 k10) (weaken_wfDecls k10 k11 d13 wf) C0 (HS TyVar (appendHvl k11 k10)) (shifthvl_TyVar_here (appendHvl k11 k10))))
end.
Fixpoint weaken_wfTm (k10 : Hvl) {struct k10} :
(forall (k11 : Hvl) (s6 : Tm) (wf : (wfTm k11 s6)) ,
(wfTm (appendHvl k11 k10) (weakenTm s6 k10))) :=
match k10 return (forall (k11 : Hvl) (s6 : Tm) (wf : (wfTm k11 s6)) ,
(wfTm (appendHvl k11 k10) (weakenTm s6 k10))) with
| (H0) => (fun (k11 : Hvl) (s6 : Tm) (wf : (wfTm k11 s6)) =>
wf)
| (HS TmVar k10) => (fun (k11 : Hvl) (s6 : Tm) (wf : (wfTm k11 s6)) =>
(shift_TmVar__wfTm (appendHvl k11 k10) (weakenTm s6 k10) (weaken_wfTm k10 k11 s6 wf) C0 (HS TmVar (appendHvl k11 k10)) (shifthvl_TmVar_here (appendHvl k11 k10))))
| (HS TyVar k10) => (fun (k11 : Hvl) (s6 : Tm) (wf : (wfTm k11 s6)) =>
(shift_TyVar__wfTm (appendHvl k11 k10) (weakenTm s6 k10) (weaken_wfTm k10 k11 s6 wf) C0 (HS TyVar (appendHvl k11 k10)) (shifthvl_TyVar_here (appendHvl k11 k10))))
end.
End ShiftWellFormed.
Lemma wfTy_cast :
(forall (k12 : Hvl) (S5 : Ty) (k13 : Hvl) (S6 : Ty) ,
(k12 = k13) -> (S5 = S6) -> (wfTy k12 S5) -> (wfTy k13 S6)).
Proof.
congruence .
Qed.
Lemma wfDecls_cast :
(forall (k12 : Hvl) (d13 : Decls) (k13 : Hvl) (d14 : Decls) ,
(k12 = k13) -> (d13 = d14) -> (wfDecls k12 d13) -> (wfDecls k13 d14)).
Proof.
congruence .
Qed.
Lemma wfTm_cast :
(forall (k12 : Hvl) (s6 : Tm) (k13 : Hvl) (s7 : Tm) ,
(k12 = k13) -> (s6 = s7) -> (wfTm k12 s6) -> (wfTm k13 s7)).
Proof.
congruence .
Qed.
Hint Resolve shift_TmVar__wfindex_TmVar shift_TmVar__wfindex_TyVar shift_TyVar__wfindex_TmVar shift_TyVar__wfindex_TyVar : infra.
Hint Resolve shift_TmVar__wfindex_TmVar shift_TmVar__wfindex_TyVar shift_TyVar__wfindex_TmVar shift_TyVar__wfindex_TyVar : shift.
Hint Resolve shift_TmVar__wfindex_TmVar shift_TmVar__wfindex_TyVar shift_TyVar__wfindex_TmVar shift_TyVar__wfindex_TyVar : shift_wf.
Hint Resolve shift_TmVar__wfindex_TmVar shift_TmVar__wfindex_TyVar shift_TyVar__wfindex_TmVar shift_TyVar__wfindex_TyVar : wf.
Hint Resolve shift_TmVar__wfDecls shift_TmVar__wfTm shift_TmVar__wfTy shift_TyVar__wfDecls shift_TyVar__wfTm shift_TyVar__wfTy : infra.
Hint Resolve shift_TmVar__wfDecls shift_TmVar__wfTm shift_TmVar__wfTy shift_TyVar__wfDecls shift_TyVar__wfTm shift_TyVar__wfTy : shift.
Hint Resolve shift_TmVar__wfDecls shift_TmVar__wfTm shift_TmVar__wfTy shift_TyVar__wfDecls shift_TyVar__wfTm shift_TyVar__wfTy : shift_wf.
Hint Resolve shift_TmVar__wfDecls shift_TmVar__wfTm shift_TmVar__wfTy shift_TyVar__wfDecls shift_TyVar__wfTm shift_TyVar__wfTy : wf.
Hint Constructors shifthvl_TmVar shifthvl_TyVar : infra.
Hint Constructors shifthvl_TmVar shifthvl_TyVar : shift.
Hint Constructors shifthvl_TmVar shifthvl_TyVar : shift_wf.
Hint Constructors shifthvl_TmVar shifthvl_TyVar : wf.
Hint Resolve weaken_shifthvl_TmVar weaken_shifthvl_TyVar : infra.
Hint Resolve weaken_shifthvl_TmVar weaken_shifthvl_TyVar : shift.
Hint Resolve weaken_shifthvl_TmVar weaken_shifthvl_TyVar : shift_wf.
Hint Resolve weaken_shifthvl_TmVar weaken_shifthvl_TyVar : weaken.
Hint Resolve weaken_shifthvl_TmVar weaken_shifthvl_TyVar : wf.
Section SubstWellFormed.
Inductive substhvl_TmVar (k10 : Hvl) : (forall (d13 : (Trace TmVar)) (k11 : Hvl) (k12 : Hvl) ,
Prop) :=
| substhvl_TmVar_here :
(substhvl_TmVar k10 X0 (HS TmVar k10) k10)
| substhvl_TmVar_there_TmVar
{d13 : (Trace TmVar)}
{k11 : Hvl} {k12 : Hvl} :
(substhvl_TmVar k10 d13 k11 k12) -> (substhvl_TmVar k10 (XS TmVar d13) (HS TmVar k11) (HS TmVar k12))
| substhvl_TmVar_there_TyVar
{d13 : (Trace TmVar)}
{k11 : Hvl} {k12 : Hvl} :
(substhvl_TmVar k10 d13 k11 k12) -> (substhvl_TmVar k10 (XS TyVar d13) (HS TyVar k11) (HS TyVar k12)).
Inductive substhvl_TyVar (k10 : Hvl) : (forall (d13 : (Trace TyVar)) (k11 : Hvl) (k12 : Hvl) ,
Prop) :=
| substhvl_TyVar_here :
(substhvl_TyVar k10 X0 (HS TyVar k10) k10)
| substhvl_TyVar_there_TmVar
{d13 : (Trace TyVar)}
{k11 : Hvl} {k12 : Hvl} :
(substhvl_TyVar k10 d13 k11 k12) -> (substhvl_TyVar k10 (XS TmVar d13) (HS TmVar k11) (HS TmVar k12))
| substhvl_TyVar_there_TyVar
{d13 : (Trace TyVar)}
{k11 : Hvl} {k12 : Hvl} :
(substhvl_TyVar k10 d13 k11 k12) -> (substhvl_TyVar k10 (XS TyVar d13) (HS TyVar k11) (HS TyVar k12)).
Lemma weaken_substhvl_TmVar :
(forall {k11 : Hvl} (k10 : Hvl) {d13 : (Trace TmVar)} {k12 : Hvl} {k13 : Hvl} ,
(substhvl_TmVar k11 d13 k12 k13) -> (substhvl_TmVar k11 (weakenTrace d13 k10) (appendHvl k12 k10) (appendHvl k13 k10))).
Proof.
needleGenericWeakenSubstHvl .
Qed.
Lemma weaken_substhvl_TyVar :
(forall {k11 : Hvl} (k10 : Hvl) {d13 : (Trace TyVar)} {k12 : Hvl} {k13 : Hvl} ,
(substhvl_TyVar k11 d13 k12 k13) -> (substhvl_TyVar k11 (weakenTrace d13 k10) (appendHvl k12 k10) (appendHvl k13 k10))).
Proof.
needleGenericWeakenSubstHvl .
Qed.
Lemma substhvl_TmVar_wfindex_TmVar {k12 : Hvl} {s6 : Tm} (wft : (wfTm k12 s6)) :
(forall {d13 : (Trace TmVar)} {k13 : Hvl} {k14 : Hvl} ,
(substhvl_TmVar k12 d13 k13 k14) -> (forall {x7 : (Index TmVar)} ,
(wfindex k13 x7) -> (wfTm k14 (subst_TmVar_Index d13 s6 x7)))).
Proof.
needleGenericSubstHvlWfIndexHom .
Qed.
Lemma substhvl_TyVar_wfindex_TyVar {k12 : Hvl} {S5 : Ty} (wft : (wfTy k12 S5)) :
(forall {d13 : (Trace TyVar)} {k13 : Hvl} {k14 : Hvl} ,
(substhvl_TyVar k12 d13 k13 k14) -> (forall {X7 : (Index TyVar)} ,
(wfindex k13 X7) -> (wfTy k14 (subst_TyVar_Index d13 S5 X7)))).
Proof.
needleGenericSubstHvlWfIndexHom .
Qed.
Lemma substhvl_TmVar_wfindex_TyVar {k12 : Hvl} :
(forall {d13 : (Trace TmVar)} {k13 : Hvl} {k14 : Hvl} ,
(substhvl_TmVar k12 d13 k13 k14) -> (forall {X7 : (Index TyVar)} ,
(wfindex k13 X7) -> (wfindex k14 X7))).
Proof.
needleGenericSubstHvlWfIndexHet .
Qed.
Lemma substhvl_TyVar_wfindex_TmVar {k12 : Hvl} :
(forall {d13 : (Trace TyVar)} {k13 : Hvl} {k14 : Hvl} ,
(substhvl_TyVar k12 d13 k13 k14) -> (forall {x7 : (Index TmVar)} ,
(wfindex k13 x7) -> (wfindex k14 x7))).
Proof.
needleGenericSubstHvlWfIndexHet .
Qed.
Definition substhvl_TmVar_wfTy {k12 : Hvl} : (forall (k13 : Hvl) ,
(forall (S5 : Ty) (wf0 : (wfTy k13 S5)) ,
(forall {d13 : (Trace TmVar)} {k14 : Hvl} ,
(substhvl_TmVar k12 d13 k13 k14) -> (wfTy k14 S5)))) := (ind_wfTy (fun (k13 : Hvl) (S5 : Ty) (wf0 : (wfTy k13 S5)) =>
(forall {d13 : (Trace TmVar)} {k14 : Hvl} ,
(substhvl_TmVar k12 d13 k13 k14) -> (wfTy k14 S5))) (fun (k13 : Hvl) {X7 : (Index TyVar)} (wfi : (wfindex k13 X7)) {d13 : (Trace TmVar)} {k14 : Hvl} (del : (substhvl_TmVar k12 d13 k13 k14)) =>
(wfTy_TVar k14 _ (substhvl_TmVar_wfindex_TyVar del wfi))) (fun (k13 : Hvl) (T1 : Ty) (wf0 : (wfTy k13 T1)) IHT1 (T2 : Ty) (wf1 : (wfTy k13 T2)) IHT2 {d13 : (Trace TmVar)} {k14 : Hvl} (del : (substhvl_TmVar k12 d13 k13 k14)) =>
(wfTy_TArr k14 (IHT1 (weakenTrace d13 H0) k14 (weaken_substhvl_TmVar H0 del)) (IHT2 (weakenTrace d13 H0) k14 (weaken_substhvl_TmVar H0 del)))) (fun (k13 : Hvl) (T : Ty) (wf0 : (wfTy (HS TyVar k13) T)) IHT {d13 : (Trace TmVar)} {k14 : Hvl} (del : (substhvl_TmVar k12 d13 k13 k14)) =>
(wfTy_TAll k14 (IHT (weakenTrace d13 (HS TyVar H0)) (HS TyVar k14) (weaken_substhvl_TmVar (HS TyVar H0) del))))).
Definition substhvl_TyVar_wfTy {k12 : Hvl} {S5 : Ty} (wf : (wfTy k12 S5)) : (forall (k13 : Hvl) ,
(forall (S6 : Ty) (wf0 : (wfTy k13 S6)) ,
(forall {d13 : (Trace TyVar)} {k14 : Hvl} ,
(substhvl_TyVar k12 d13 k13 k14) -> (wfTy k14 (subst_TyVar_Ty d13 S5 S6))))) := (ind_wfTy (fun (k13 : Hvl) (S6 : Ty) (wf0 : (wfTy k13 S6)) =>
(forall {d13 : (Trace TyVar)} {k14 : Hvl} ,
(substhvl_TyVar k12 d13 k13 k14) -> (wfTy k14 (subst_TyVar_Ty d13 S5 S6)))) (fun (k13 : Hvl) {X7 : (Index TyVar)} (wfi : (wfindex k13 X7)) {d13 : (Trace TyVar)} {k14 : Hvl} (del : (substhvl_TyVar k12 d13 k13 k14)) =>
(substhvl_TyVar_wfindex_TyVar wf del wfi)) (fun (k13 : Hvl) (T1 : Ty) (wf0 : (wfTy k13 T1)) IHT1 (T2 : Ty) (wf1 : (wfTy k13 T2)) IHT2 {d13 : (Trace TyVar)} {k14 : Hvl} (del : (substhvl_TyVar k12 d13 k13 k14)) =>
(wfTy_TArr k14 (IHT1 (weakenTrace d13 H0) k14 (weaken_substhvl_TyVar H0 del)) (IHT2 (weakenTrace d13 H0) k14 (weaken_substhvl_TyVar H0 del)))) (fun (k13 : Hvl) (T : Ty) (wf0 : (wfTy (HS TyVar k13) T)) IHT {d13 : (Trace TyVar)} {k14 : Hvl} (del : (substhvl_TyVar k12 d13 k13 k14)) =>
(wfTy_TAll k14 (IHT (weakenTrace d13 (HS TyVar H0)) (HS TyVar k14) (weaken_substhvl_TyVar (HS TyVar H0) del))))).
Definition substhvl_TmVar_wfDecls_Tm {k12 : Hvl} {s6 : Tm} (wf : (wfTm k12 s6)) : (forall (k13 : Hvl) ,
(forall (d13 : Decls) (wf0 : (wfDecls k13 d13)) ,
(forall {d14 : (Trace TmVar)} {k14 : Hvl} ,
(substhvl_TmVar k12 d14 k13 k14) -> (wfDecls k14 (subst_TmVar_Decls d14 s6 d13)))) /\
(forall (s7 : Tm) (wf0 : (wfTm k13 s7)) ,
(forall {d13 : (Trace TmVar)} {k14 : Hvl} ,
(substhvl_TmVar k12 d13 k13 k14) -> (wfTm k14 (subst_TmVar_Tm d13 s6 s7))))) := (ind_wfDecls_Tm (fun (k13 : Hvl) (d13 : Decls) (wf0 : (wfDecls k13 d13)) =>
(forall {d14 : (Trace TmVar)} {k14 : Hvl} ,
(substhvl_TmVar k12 d14 k13 k14) -> (wfDecls k14 (subst_TmVar_Decls d14 s6 d13)))) (fun (k13 : Hvl) (s7 : Tm) (wf0 : (wfTm k13 s7)) =>
(forall {d13 : (Trace TmVar)} {k14 : Hvl} ,
(substhvl_TmVar k12 d13 k13 k14) -> (wfTm k14 (subst_TmVar_Tm d13 s6 s7)))) (fun (k13 : Hvl) {d13 : (Trace TmVar)} {k14 : Hvl} (del : (substhvl_TmVar k12 d13 k13 k14)) =>
(wfDecls_DNil k14)) (fun (k13 : Hvl) (t : Tm) (wf0 : (wfTm k13 t)) IHt (d : Decls) (wf1 : (wfDecls (HS TmVar k13) d)) IHd {d13 : (Trace TmVar)} {k14 : Hvl} (del : (substhvl_TmVar k12 d13 k13 k14)) =>
(wfDecls_DCons k14 (IHt (weakenTrace d13 H0) k14 (weaken_substhvl_TmVar H0 del)) (IHd (weakenTrace d13 (HS TmVar H0)) (HS TmVar k14) (weaken_substhvl_TmVar (HS TmVar H0) del)))) (fun (k13 : Hvl) {x7 : (Index TmVar)} (wfi : (wfindex k13 x7)) {d13 : (Trace TmVar)} {k14 : Hvl} (del : (substhvl_TmVar k12 d13 k13 k14)) =>
(substhvl_TmVar_wfindex_TmVar wf del wfi)) (fun (k13 : Hvl) (T : Ty) (wf0 : (wfTy k13 T)) (t : Tm) (wf1 : (wfTm (HS TmVar k13) t)) IHt {d13 : (Trace TmVar)} {k14 : Hvl} (del : (substhvl_TmVar k12 d13 k13 k14)) =>
(wfTm_Abs k14 (substhvl_TmVar_wfTy k13 T wf0 (weaken_substhvl_TmVar H0 del)) (IHt (weakenTrace d13 (HS TmVar H0)) (HS TmVar k14) (weaken_substhvl_TmVar (HS TmVar H0) del)))) (fun (k13 : Hvl) (t1 : Tm) (wf0 : (wfTm k13 t1)) IHt1 (t2 : Tm) (wf1 : (wfTm k13 t2)) IHt2 {d13 : (Trace TmVar)} {k14 : Hvl} (del : (substhvl_TmVar k12 d13 k13 k14)) =>
(wfTm_App k14 (IHt1 (weakenTrace d13 H0) k14 (weaken_substhvl_TmVar H0 del)) (IHt2 (weakenTrace d13 H0) k14 (weaken_substhvl_TmVar H0 del)))) (fun (k13 : Hvl) (t : Tm) (wf0 : (wfTm (HS TyVar k13) t)) IHt {d13 : (Trace TmVar)} {k14 : Hvl} (del : (substhvl_TmVar k12 d13 k13 k14)) =>
(wfTm_TAbs k14 (IHt (weakenTrace d13 (HS TyVar H0)) (HS TyVar k14) (weaken_substhvl_TmVar (HS TyVar H0) del)))) (fun (k13 : Hvl) (t : Tm) (wf0 : (wfTm k13 t)) IHt (T : Ty) (wf1 : (wfTy k13 T)) {d13 : (Trace TmVar)} {k14 : Hvl} (del : (substhvl_TmVar k12 d13 k13 k14)) =>
(wfTm_TApp k14 (IHt (weakenTrace d13 H0) k14 (weaken_substhvl_TmVar H0 del)) (substhvl_TmVar_wfTy k13 T wf1 (weaken_substhvl_TmVar H0 del)))) (fun (k13 : Hvl) (d : Decls) (wf0 : (wfDecls k13 d)) IHd (t : Tm) (wf1 : (wfTm (appendHvl k13 (appendHvl H0 (bind d))) t)) IHt {d13 : (Trace TmVar)} {k14 : Hvl} (del : (substhvl_TmVar k12 d13 k13 k14)) =>
(wfTm_Let k14 (IHd (weakenTrace d13 H0) k14 (weaken_substhvl_TmVar H0 del)) (eq_ind2 wfTm (f_equal2 appendHvl (eq_refl k14) (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (eq_sym (stability_subst_TmVar__bind _ _ _)) (eq_refl H0)))) eq_refl (IHt (weakenTrace d13 (appendHvl H0 (bind d))) (appendHvl k14 (appendHvl H0 (bind d))) (weaken_substhvl_TmVar (appendHvl H0 (bind d)) del)))))).
Lemma substhvl_TmVar_wfDecls {k12 : Hvl} {s6 : Tm} (wf : (wfTm k12 s6)) (k13 : Hvl) (d13 : Decls) (wf0 : (wfDecls k13 d13)) :
(forall {d14 : (Trace TmVar)} {k14 : Hvl} ,
(substhvl_TmVar k12 d14 k13 k14) -> (wfDecls k14 (subst_TmVar_Decls d14 s6 d13))).
Proof.
apply ((substhvl_TmVar_wfDecls_Tm wf k13)).
auto .
Qed.
Lemma substhvl_TmVar_wfTm {k12 : Hvl} {s6 : Tm} (wf : (wfTm k12 s6)) (k13 : Hvl) (s7 : Tm) (wf1 : (wfTm k13 s7)) :
(forall {d15 : (Trace TmVar)} {k15 : Hvl} ,
(substhvl_TmVar k12 d15 k13 k15) -> (wfTm k15 (subst_TmVar_Tm d15 s6 s7))).
Proof.
apply ((substhvl_TmVar_wfDecls_Tm wf k13)).
auto .
Qed.
Definition substhvl_TyVar_wfDecls_Tm {k12 : Hvl} {S5 : Ty} (wf : (wfTy k12 S5)) : (forall (k13 : Hvl) ,
(forall (d13 : Decls) (wf0 : (wfDecls k13 d13)) ,
(forall {d14 : (Trace TyVar)} {k14 : Hvl} ,
(substhvl_TyVar k12 d14 k13 k14) -> (wfDecls k14 (subst_TyVar_Decls d14 S5 d13)))) /\
(forall (s6 : Tm) (wf0 : (wfTm k13 s6)) ,
(forall {d13 : (Trace TyVar)} {k14 : Hvl} ,
(substhvl_TyVar k12 d13 k13 k14) -> (wfTm k14 (subst_TyVar_Tm d13 S5 s6))))) := (ind_wfDecls_Tm (fun (k13 : Hvl) (d13 : Decls) (wf0 : (wfDecls k13 d13)) =>
(forall {d14 : (Trace TyVar)} {k14 : Hvl} ,
(substhvl_TyVar k12 d14 k13 k14) -> (wfDecls k14 (subst_TyVar_Decls d14 S5 d13)))) (fun (k13 : Hvl) (s6 : Tm) (wf0 : (wfTm k13 s6)) =>
(forall {d13 : (Trace TyVar)} {k14 : Hvl} ,
(substhvl_TyVar k12 d13 k13 k14) -> (wfTm k14 (subst_TyVar_Tm d13 S5 s6)))) (fun (k13 : Hvl) {d13 : (Trace TyVar)} {k14 : Hvl} (del : (substhvl_TyVar k12 d13 k13 k14)) =>
(wfDecls_DNil k14)) (fun (k13 : Hvl) (t : Tm) (wf0 : (wfTm k13 t)) IHt (d : Decls) (wf1 : (wfDecls (HS TmVar k13) d)) IHd {d13 : (Trace TyVar)} {k14 : Hvl} (del : (substhvl_TyVar k12 d13 k13 k14)) =>
(wfDecls_DCons k14 (IHt (weakenTrace d13 H0) k14 (weaken_substhvl_TyVar H0 del)) (IHd (weakenTrace d13 (HS TmVar H0)) (HS TmVar k14) (weaken_substhvl_TyVar (HS TmVar H0) del)))) (fun (k13 : Hvl) {x7 : (Index TmVar)} (wfi : (wfindex k13 x7)) {d13 : (Trace TyVar)} {k14 : Hvl} (del : (substhvl_TyVar k12 d13 k13 k14)) =>
(wfTm_Var k14 _ (substhvl_TyVar_wfindex_TmVar del wfi))) (fun (k13 : Hvl) (T : Ty) (wf0 : (wfTy k13 T)) (t : Tm) (wf1 : (wfTm (HS TmVar k13) t)) IHt {d13 : (Trace TyVar)} {k14 : Hvl} (del : (substhvl_TyVar k12 d13 k13 k14)) =>
(wfTm_Abs k14 (substhvl_TyVar_wfTy wf k13 T wf0 (weaken_substhvl_TyVar H0 del)) (IHt (weakenTrace d13 (HS TmVar H0)) (HS TmVar k14) (weaken_substhvl_TyVar (HS TmVar H0) del)))) (fun (k13 : Hvl) (t1 : Tm) (wf0 : (wfTm k13 t1)) IHt1 (t2 : Tm) (wf1 : (wfTm k13 t2)) IHt2 {d13 : (Trace TyVar)} {k14 : Hvl} (del : (substhvl_TyVar k12 d13 k13 k14)) =>
(wfTm_App k14 (IHt1 (weakenTrace d13 H0) k14 (weaken_substhvl_TyVar H0 del)) (IHt2 (weakenTrace d13 H0) k14 (weaken_substhvl_TyVar H0 del)))) (fun (k13 : Hvl) (t : Tm) (wf0 : (wfTm (HS TyVar k13) t)) IHt {d13 : (Trace TyVar)} {k14 : Hvl} (del : (substhvl_TyVar k12 d13 k13 k14)) =>
(wfTm_TAbs k14 (IHt (weakenTrace d13 (HS TyVar H0)) (HS TyVar k14) (weaken_substhvl_TyVar (HS TyVar H0) del)))) (fun (k13 : Hvl) (t : Tm) (wf0 : (wfTm k13 t)) IHt (T : Ty) (wf1 : (wfTy k13 T)) {d13 : (Trace TyVar)} {k14 : Hvl} (del : (substhvl_TyVar k12 d13 k13 k14)) =>
(wfTm_TApp k14 (IHt (weakenTrace d13 H0) k14 (weaken_substhvl_TyVar H0 del)) (substhvl_TyVar_wfTy wf k13 T wf1 (weaken_substhvl_TyVar H0 del)))) (fun (k13 : Hvl) (d : Decls) (wf0 : (wfDecls k13 d)) IHd (t : Tm) (wf1 : (wfTm (appendHvl k13 (appendHvl H0 (bind d))) t)) IHt {d13 : (Trace TyVar)} {k14 : Hvl} (del : (substhvl_TyVar k12 d13 k13 k14)) =>
(wfTm_Let k14 (IHd (weakenTrace d13 H0) k14 (weaken_substhvl_TyVar H0 del)) (eq_ind2 wfTm (f_equal2 appendHvl (eq_refl k14) (f_equal2 appendHvl (eq_refl H0) (f_equal2 appendHvl (eq_sym (stability_subst_TyVar__bind _ _ _)) (eq_refl H0)))) eq_refl (IHt (weakenTrace d13 (appendHvl H0 (bind d))) (appendHvl k14 (appendHvl H0 (bind d))) (weaken_substhvl_TyVar (appendHvl H0 (bind d)) del)))))).
Lemma substhvl_TyVar_wfDecls {k12 : Hvl} {S5 : Ty} (wf : (wfTy k12 S5)) (k13 : Hvl) (d13 : Decls) (wf0 : (wfDecls k13 d13)) :
(forall {d14 : (Trace TyVar)} {k14 : Hvl} ,
(substhvl_TyVar k12 d14 k13 k14) -> (wfDecls k14 (subst_TyVar_Decls d14 S5 d13))).
Proof.
apply ((substhvl_TyVar_wfDecls_Tm wf k13)).
auto .
Qed.
Lemma substhvl_TyVar_wfTm {k12 : Hvl} {S5 : Ty} (wf : (wfTy k12 S5)) (k13 : Hvl) (s6 : Tm) (wf1 : (wfTm k13 s6)) :
(forall {d15 : (Trace TyVar)} {k15 : Hvl} ,
(substhvl_TyVar k12 d15 k13 k15) -> (wfTm k15 (subst_TyVar_Tm d15 S5 s6))).
Proof.
apply ((substhvl_TyVar_wfDecls_Tm wf k13)).
auto .
Qed.
End SubstWellFormed.
Hint Resolve substhvl_TmVar_wfindex_TmVar substhvl_TmVar_wfindex_TyVar substhvl_TyVar_wfindex_TmVar substhvl_TyVar_wfindex_TyVar : infra.
Hint Resolve substhvl_TmVar_wfindex_TmVar substhvl_TmVar_wfindex_TyVar substhvl_TyVar_wfindex_TmVar substhvl_TyVar_wfindex_TyVar : subst.
Hint Resolve substhvl_TmVar_wfindex_TmVar substhvl_TmVar_wfindex_TyVar substhvl_TyVar_wfindex_TmVar substhvl_TyVar_wfindex_TyVar : subst_wf.
Hint Resolve substhvl_TmVar_wfindex_TmVar substhvl_TmVar_wfindex_TyVar substhvl_TyVar_wfindex_TmVar substhvl_TyVar_wfindex_TyVar : wf.
Hint Resolve substhvl_TmVar_wfDecls substhvl_TmVar_wfTm substhvl_TmVar_wfTy substhvl_TyVar_wfDecls substhvl_TyVar_wfTm substhvl_TyVar_wfTy : infra.
Hint Resolve substhvl_TmVar_wfDecls substhvl_TmVar_wfTm substhvl_TmVar_wfTy substhvl_TyVar_wfDecls substhvl_TyVar_wfTm substhvl_TyVar_wfTy : subst.
Hint Resolve substhvl_TmVar_wfDecls substhvl_TmVar_wfTm substhvl_TmVar_wfTy substhvl_TyVar_wfDecls substhvl_TyVar_wfTm substhvl_TyVar_wfTy : subst_wf.
Hint Resolve substhvl_TmVar_wfDecls substhvl_TmVar_wfTm substhvl_TmVar_wfTy substhvl_TyVar_wfDecls substhvl_TyVar_wfTm substhvl_TyVar_wfTy : wf.
Hint Constructors substhvl_TmVar substhvl_TyVar : infra.
Hint Constructors substhvl_TmVar substhvl_TyVar : subst.
Hint Constructors substhvl_TmVar substhvl_TyVar : subst_wf.
Hint Constructors substhvl_TmVar substhvl_TyVar : wf.
Fixpoint subhvl_TmVar (k12 : Hvl) {struct k12} :
Prop :=
match k12 with
| (H0) => True
| (HS a k12) => match a with
| (TmVar) => (subhvl_TmVar k12)
| _ => False
end
end.
Lemma subhvl_TmVar_append :
(forall (k12 : Hvl) (k13 : Hvl) ,
(subhvl_TmVar k12) -> (subhvl_TmVar k13) -> (subhvl_TmVar (appendHvl k12 k13))).
Proof.
needleGenericSubHvlAppend .
Qed.
Hint Resolve subhvl_TmVar_append : infra.
Hint Resolve subhvl_TmVar_append : wf.
Lemma wfTy_strengthen_subhvl_TmVar :
(forall (k11 : Hvl) (k10 : Hvl) (S4 : Ty) ,
(subhvl_TmVar k11) -> (wfTy (appendHvl k10 k11) (weakenTy S4 k11)) -> (wfTy k10 S4)).
Proof.
needleGenericWellformedStrengthen .
Qed.
Hint Extern 2 ((wfTy _ _)) => match goal with
| H32 : (wfTy (appendHvl _ _) (weakenTy _ _)) |- _ => apply (wfTy_strengthen_subhvl_TmVar) in H32
end : infra wf.
Section Context.
Inductive Ctx : Type :=
| empty
| evar (G : Ctx) (T : Ty)
| etvar (G : Ctx).
Fixpoint appendCtx (G : Ctx) (G0 : Ctx) :
Ctx :=
match G0 with
| (empty) => G
| (evar G1 T) => (evar (appendCtx G G1) T)
| (etvar G1) => (etvar (appendCtx G G1))
end.
Fixpoint domainCtx (G : Ctx) :
Hvl :=
match G with
| (empty) => H0
| (evar G0 T) => (HS TmVar (domainCtx G0))
| (etvar G0) => (HS TyVar (domainCtx G0))
end.
Lemma appendCtx_assoc :
(forall (G : Ctx) (G0 : Ctx) (G1 : Ctx) ,
((appendCtx G (appendCtx G0 G1)) = (appendCtx (appendCtx G G0) G1))).
Proof.
needleGenericAppendEnvAssoc .
Qed.
Lemma domainCtx_appendCtx :
(forall (G : Ctx) (G0 : Ctx) ,
((domainCtx (appendCtx G G0)) = (appendHvl (domainCtx G) (domainCtx G0)))).
Proof.
needleGenericDomainEnvAppendEnv .
Qed.
Fixpoint shift_TmVar_Ctx (c1 : (Cutoff TmVar)) (G : Ctx) :
Ctx :=
match G with
| (empty) => empty
| (evar G0 T) => (evar (shift_TmVar_Ctx c1 G0) T)
| (etvar G0) => (etvar (shift_TmVar_Ctx c1 G0))
end.
Fixpoint shift_TyVar_Ctx (c1 : (Cutoff TyVar)) (G : Ctx) :
Ctx :=
match G with
| (empty) => empty
| (evar G0 T) => (evar (shift_TyVar_Ctx c1 G0) (shift_TyVar_Ty (weakenCutoffTyVar c1 (domainCtx G0)) T))
| (etvar G0) => (etvar (shift_TyVar_Ctx c1 G0))
end.
Fixpoint weakenCtx (G : Ctx) (k12 : Hvl) {struct k12} :
Ctx :=
match k12 with
| (H0) => G
| (HS TmVar k12) => (weakenCtx G k12)
| (HS TyVar k12) => (shift_TyVar_Ctx C0 (weakenCtx G k12))
end.
Fixpoint subst_TmVar_Ctx (d13 : (Trace TmVar)) (s6 : Tm) (G : Ctx) :
Ctx :=
match G with
| (empty) => empty
| (evar G0 T) => (evar (subst_TmVar_Ctx d13 s6 G0) T)
| (etvar G0) => (etvar (subst_TmVar_Ctx d13 s6 G0))
end.
Fixpoint subst_TyVar_Ctx (d13 : (Trace TyVar)) (S5 : Ty) (G : Ctx) :
Ctx :=
match G with
| (empty) => empty
| (evar G0 T) => (evar (subst_TyVar_Ctx d13 S5 G0) (subst_TyVar_Ty (weakenTrace d13 (domainCtx G0)) S5 T))
| (etvar G0) => (etvar (subst_TyVar_Ctx d13 S5 G0))
end.
Lemma domainCtx_shift_TmVar_Ctx :
(forall (c1 : (Cutoff TmVar)) (G : Ctx) ,
((domainCtx (shift_TmVar_Ctx c1 G)) = (domainCtx G))).
Proof.
needleGenericDomainEnvShiftEnv .
Qed.
Lemma domainCtx_shift_TyVar_Ctx :
(forall (c1 : (Cutoff TyVar)) (G : Ctx) ,
((domainCtx (shift_TyVar_Ctx c1 G)) = (domainCtx G))).
Proof.
needleGenericDomainEnvShiftEnv .
Qed.
Lemma domainCtx_subst_TmVar_Ctx :
(forall (d13 : (Trace TmVar)) (s6 : Tm) (G : Ctx) ,
((domainCtx (subst_TmVar_Ctx d13 s6 G)) = (domainCtx G))).
Proof.
needleGenericDomainEnvSubstEnv .
Qed.
Lemma domainCtx_subst_TyVar_Ctx :
(forall (d13 : (Trace TyVar)) (S5 : Ty) (G : Ctx) ,
((domainCtx (subst_TyVar_Ctx d13 S5 G)) = (domainCtx G))).
Proof.
needleGenericDomainEnvSubstEnv .
Qed.
End Context.
Hint Rewrite domainCtx_appendCtx : interaction.
Hint Rewrite domainCtx_appendCtx : env_domain_append.
Section ContextStuff.
Section ShiftEnvAppendEnv.
Lemma shift_TmVar_Ctx_appendCtx :
(forall (c1 : (Cutoff TmVar)) (G : Ctx) (G0 : Ctx) ,
((shift_TmVar_Ctx c1 (appendCtx G G0)) = (appendCtx (shift_TmVar_Ctx c1 G) (shift_TmVar_Ctx (weakenCutoffTmVar c1 (domainCtx G)) G0)))).
Proof.
needleGenericShiftEnvAppendEnv .
Qed.
Lemma shift_TyVar_Ctx_appendCtx :
(forall (c1 : (Cutoff TyVar)) (G : Ctx) (G0 : Ctx) ,
((shift_TyVar_Ctx c1 (appendCtx G G0)) = (appendCtx (shift_TyVar_Ctx c1 G) (shift_TyVar_Ctx (weakenCutoffTyVar c1 (domainCtx G)) G0)))).
Proof.
needleGenericShiftEnvAppendEnv .
Qed.
End ShiftEnvAppendEnv.
Section SubstEnvAppendEnv.
Lemma subst_TmVar_Ctx_appendCtx :
(forall (d13 : (Trace TmVar)) (s6 : Tm) (G : Ctx) (G0 : Ctx) ,
((subst_TmVar_Ctx d13 s6 (appendCtx G G0)) = (appendCtx (subst_TmVar_Ctx d13 s6 G) (subst_TmVar_Ctx (weakenTrace d13 (domainCtx G)) s6 G0)))).
Proof.
needleGenericSubstEnvAppendEnv .
Qed.
Lemma subst_TyVar_Ctx_appendCtx :
(forall (d13 : (Trace TyVar)) (S5 : Ty) (G : Ctx) (G0 : Ctx) ,
((subst_TyVar_Ctx d13 S5 (appendCtx G G0)) = (appendCtx (subst_TyVar_Ctx d13 S5 G) (subst_TyVar_Ctx (weakenTrace d13 (domainCtx G)) S5 G0)))).
Proof.
needleGenericSubstEnvAppendEnv .
Qed.
End SubstEnvAppendEnv.
Lemma weakenTy_append :
(forall (S5 : Ty) (k12 : Hvl) (k13 : Hvl) ,
((weakenTy (weakenTy S5 k12) k13) = (weakenTy S5 (appendHvl k12 k13)))).
Proof.
needleGenericWeakenAppend .
Qed.
Lemma weakenDecls_append :
(forall (d13 : Decls) (k12 : Hvl) (k13 : Hvl) ,
((weakenDecls (weakenDecls d13 k12) k13) = (weakenDecls d13 (appendHvl k12 k13)))).
Proof.
needleGenericWeakenAppend .
Qed.
Lemma weakenTm_append :
(forall (s6 : Tm) (k12 : Hvl) (k13 : Hvl) ,
((weakenTm (weakenTm s6 k12) k13) = (weakenTm s6 (appendHvl k12 k13)))).
Proof.
needleGenericWeakenAppend .
Qed.
Section Lookups.
Inductive lookup_evar : Ctx -> (Index TmVar) -> Ty -> Prop :=
| lookup_evar_here {G : Ctx}
(T5 : Ty) :
(wfTy (domainCtx G) T5) -> (lookup_evar (evar G T5) I0 T5)
| lookup_evar_there_evar
{G : Ctx} {x7 : (Index TmVar)}
(T6 : Ty) (T7 : Ty) :
(lookup_evar G x7 T6) -> (lookup_evar (evar G T7) (IS x7) T6)
| lookup_evar_there_etvar
{G : Ctx} {x7 : (Index TmVar)}
(T6 : Ty) :
(lookup_evar G x7 T6) -> (lookup_evar (etvar G) x7 (shift_TyVar_Ty C0 T6)).
Inductive lookup_etvar : Ctx -> (Index TyVar) -> Prop :=
| lookup_etvar_here {G : Ctx}
: (lookup_etvar (etvar G) I0)
| lookup_etvar_there_evar
{G : Ctx} {X7 : (Index TyVar)}
(T6 : Ty) :
(lookup_etvar G X7) -> (lookup_etvar (evar G T6) X7)
| lookup_etvar_there_etvar
{G : Ctx} {X7 : (Index TyVar)} :
(lookup_etvar G X7) -> (lookup_etvar (etvar G) (IS X7)).
Lemma lookup_evar_inversion_here :
(forall (G : Ctx) (T6 : Ty) (T7 : Ty) ,
(lookup_evar (evar G T6) I0 T7) -> (T6 = T7)).
Proof.
needleGenericLookupInversion .
Qed.
Lemma lookup_evar_functional :
(forall {G : Ctx} {x7 : (Index TmVar)} ,
(forall (T6 : Ty) ,
(lookup_evar G x7 T6) -> (forall (T7 : Ty) ,
(lookup_evar G x7 T7) -> (T6 = T7)))).
Proof.
needleGenericLookupFunctional .
Qed.
Lemma lookup_evar_wf :
(forall {G : Ctx} {x7 : (Index TmVar)} (T6 : Ty) ,
(lookup_evar G x7 T6) -> (wfTy (domainCtx G) T6)).
Proof.
needleGenericLookupWellformedData .
Qed.
Lemma weaken_lookup_evar :
(forall {G : Ctx} (G0 : Ctx) {x7 : (Index TmVar)} (T6 : Ty) ,
(lookup_evar G x7 T6) -> (lookup_evar (appendCtx G G0) (weakenIndexTmVar x7 (domainCtx G0)) (weakenTy T6 (domainCtx G0)))).
Proof.
needleGenericWeakenLookup .
Qed.
Lemma weaken_lookup_etvar :
(forall {G : Ctx} (G0 : Ctx) {X7 : (Index TyVar)} ,
(lookup_etvar G X7) -> (lookup_etvar (appendCtx G G0) (weakenIndexTyVar X7 (domainCtx G0)))).
Proof.
needleGenericWeakenLookup .
Qed.
Lemma lookup_evar_wfindex :
(forall {G : Ctx} {x7 : (Index TmVar)} (T8 : Ty) ,
(lookup_evar G x7 T8) -> (wfindex (domainCtx G) x7)).
Proof.
needleGenericLookupWellformedIndex .
Qed.
Lemma lookup_etvar_wfindex :
(forall {G : Ctx} {X7 : (Index TyVar)} ,
(lookup_etvar G X7) -> (wfindex (domainCtx G) X7)).
Proof.
needleGenericLookupWellformedIndex .
Qed.
End Lookups.
Inductive shift_evar : (Cutoff TmVar) -> Ctx -> Ctx -> Prop :=
| shift_evar_here {G : Ctx}
{T6 : Ty} :
(shift_evar C0 G (evar G T6))
| shiftevar_there_evar
{c1 : (Cutoff TmVar)} {G : Ctx}
{G0 : Ctx} {T : Ty} :
(shift_evar c1 G G0) -> (shift_evar (CS c1) (evar G T) (evar G0 T))
| shiftevar_there_etvar
{c1 : (Cutoff TmVar)} {G : Ctx}
{G0 : Ctx} :
(shift_evar c1 G G0) -> (shift_evar c1 (etvar G) (etvar G0)).
Lemma weaken_shift_evar :
(forall (G : Ctx) {c1 : (Cutoff TmVar)} {G0 : Ctx} {G1 : Ctx} ,
(shift_evar c1 G0 G1) -> (shift_evar (weakenCutoffTmVar c1 (domainCtx G)) (appendCtx G0 G) (appendCtx G1 G))).
Proof.
needleGenericWeakenInsertEnv .
Qed.
Inductive shift_etvar : (Cutoff TyVar) -> Ctx -> Ctx -> Prop :=
| shift_etvar_here {G : Ctx} :
(shift_etvar C0 G (etvar G))
| shiftetvar_there_evar
{c1 : (Cutoff TyVar)} {G : Ctx}
{G0 : Ctx} {T : Ty} :
(shift_etvar c1 G G0) -> (shift_etvar c1 (evar G T) (evar G0 (shift_TyVar_Ty c1 T)))
| shiftetvar_there_etvar
{c1 : (Cutoff TyVar)} {G : Ctx}
{G0 : Ctx} :
(shift_etvar c1 G G0) -> (shift_etvar (CS c1) (etvar G) (etvar G0)).
Lemma weaken_shift_etvar :
(forall (G : Ctx) {c1 : (Cutoff TyVar)} {G0 : Ctx} {G1 : Ctx} ,
(shift_etvar c1 G0 G1) -> (shift_etvar (weakenCutoffTyVar c1 (domainCtx G)) (appendCtx G0 G) (appendCtx G1 (shift_TyVar_Ctx c1 G)))).
Proof.
needleGenericWeakenInsertEnv .
Qed.
Lemma shift_evar_shifthvl_TmVar :
(forall {c1 : (Cutoff TmVar)} {G : Ctx} {G0 : Ctx} ,
(shift_evar c1 G G0) -> (shifthvl_TmVar c1 (domainCtx G) (domainCtx G0))).
Proof.
needleGenericInsertEnvInsertHvl .
Qed.
Lemma shift_etvar_shifthvl_TyVar :
(forall {c1 : (Cutoff TyVar)} {G : Ctx} {G0 : Ctx} ,
(shift_etvar c1 G G0) -> (shifthvl_TyVar c1 (domainCtx G) (domainCtx G0))).
Proof.
needleGenericInsertEnvInsertHvl .
Qed.
Inductive subst_evar (G : Ctx) (T6 : Ty) (s6 : Tm) : (Trace TmVar) -> Ctx -> Ctx -> Prop :=
| subst_evar_here :
(subst_evar G T6 s6 X0 (evar G T6) G)
| subst_evar_there_evar
{d13 : (Trace TmVar)} {G0 : Ctx}
{G1 : Ctx} (T7 : Ty) :
(subst_evar G T6 s6 d13 G0 G1) -> (subst_evar G T6 s6 (XS TmVar d13) (evar G0 T7) (evar G1 T7))
| subst_evar_there_etvar
{d13 : (Trace TmVar)} {G0 : Ctx}
{G1 : Ctx} :
(subst_evar G T6 s6 d13 G0 G1) -> (subst_evar G T6 s6 (XS TyVar d13) (etvar G0) (etvar G1)).
Lemma weaken_subst_evar {G : Ctx} (T6 : Ty) {s6 : Tm} :
(forall (G0 : Ctx) {d13 : (Trace TmVar)} {G1 : Ctx} {G2 : Ctx} ,
(subst_evar G T6 s6 d13 G1 G2) -> (subst_evar G T6 s6 (weakenTrace d13 (domainCtx G0)) (appendCtx G1 G0) (appendCtx G2 G0))).
Proof.
needleGenericWeakenSubstEnv .
Qed.
Inductive subst_etvar (G : Ctx) (S5 : Ty) : (Trace TyVar) -> Ctx -> Ctx -> Prop :=
| subst_etvar_here :
(subst_etvar G S5 X0 (etvar G) G)
| subst_etvar_there_evar
{d13 : (Trace TyVar)} {G0 : Ctx}
{G1 : Ctx} (T6 : Ty) :
(subst_etvar G S5 d13 G0 G1) -> (subst_etvar G S5 (XS TmVar d13) (evar G0 T6) (evar G1 (subst_TyVar_Ty d13 S5 T6)))
| subst_etvar_there_etvar
{d13 : (Trace TyVar)} {G0 : Ctx}
{G1 : Ctx} :
(subst_etvar G S5 d13 G0 G1) -> (subst_etvar G S5 (XS TyVar d13) (etvar G0) (etvar G1)).
Lemma weaken_subst_etvar {G : Ctx} {S5 : Ty} :
(forall (G0 : Ctx) {d13 : (Trace TyVar)} {G1 : Ctx} {G2 : Ctx} ,
(subst_etvar G S5 d13 G1 G2) -> (subst_etvar G S5 (weakenTrace d13 (domainCtx G0)) (appendCtx G1 G0) (appendCtx G2 (subst_TyVar_Ctx d13 S5 G0)))).
Proof.
needleGenericWeakenSubstEnv .
Qed.
Lemma subst_evar_substhvl_TmVar {G : Ctx} {s6 : Tm} (T6 : Ty) :
(forall {d13 : (Trace TmVar)} {G0 : Ctx} {G1 : Ctx} ,
(subst_evar G T6 s6 d13 G0 G1) -> (substhvl_TmVar (domainCtx G) d13 (domainCtx G0) (domainCtx G1))).
Proof.
needleGenericSubstEnvSubstHvl .
Qed.
Lemma subst_etvar_substhvl_TyVar {G : Ctx} {S5 : Ty} :
(forall {d13 : (Trace TyVar)} {G0 : Ctx} {G1 : Ctx} ,
(subst_etvar G S5 d13 G0 G1) -> (substhvl_TyVar (domainCtx G) d13 (domainCtx G0) (domainCtx G1))).
Proof.
needleGenericSubstEnvSubstHvl .
Qed.
End ContextStuff.
Hint Rewrite domainCtx_shift_TyVar_Ctx : interaction.
Hint Rewrite domainCtx_shift_TyVar_Ctx : env_domain_shift.
Hint Rewrite domainCtx_subst_TyVar_Ctx : interaction.
Hint Rewrite domainCtx_subst_TyVar_Ctx : env_domain_subst.
Hint Rewrite shift_TyVar_Ctx_appendCtx : interaction.
Hint Rewrite shift_TyVar_Ctx_appendCtx : env_shift_append.
Hint Rewrite subst_TyVar_Ctx_appendCtx : interaction.
Hint Rewrite subst_TyVar_Ctx_appendCtx : env_shift_append.
Hint Constructors lookup_evar lookup_etvar : infra.
Hint Constructors lookup_evar lookup_etvar : lookup.
Hint Constructors lookup_evar lookup_etvar : shift.
Hint Constructors lookup_evar lookup_etvar : subst.
Hint Resolve weaken_lookup_evar weaken_lookup_etvar : infra.
Hint Resolve weaken_lookup_evar weaken_lookup_etvar : lookup.
Hint Resolve weaken_lookup_evar weaken_lookup_etvar : shift.
Hint Resolve weaken_lookup_evar weaken_lookup_etvar : weaken.
Lemma weaken_lookup_evar_here :
(forall {G : Ctx} (G0 : Ctx) {T6 : Ty} (wf : (wfTy (domainCtx G) T6)) ,
(lookup_evar (appendCtx (evar G T6) G0) (weakenIndexTmVar I0 (domainCtx G0)) (weakenTy T6 (domainCtx G0)))).
Proof.
eauto with lookup .
Qed.
Lemma weaken_lookup_etvar_here :
(forall {G : Ctx} (G0 : Ctx) ,
(lookup_etvar (appendCtx (etvar G) G0) (weakenIndexTyVar I0 (domainCtx G0)))).
Proof.
eauto with lookup .
Qed.
Hint Constructors wfDecls wfTm wfTy : infra.
Hint Constructors wfDecls wfTm wfTy : wf.
Hint Extern 10 ((wfDecls _ _)) => autorewrite with env_domain_append in * : infra wf.
Hint Extern 10 ((wfTm _ _)) => autorewrite with env_domain_append in * : infra wf.
Hint Extern 10 ((wfTy _ _)) => autorewrite with env_domain_append in * : infra wf.
Hint Extern 2 ((wfTy _ _)) => match goal with
| H32 : (wfTy _ (TVar _)) |- _ => inversion H32; subst; clear H32
| H32 : (wfTy _ (TArr _ _)) |- _ => inversion H32; subst; clear H32
| H32 : (wfTy _ (TAll _)) |- _ => inversion H32; subst; clear H32
end : infra wf.
Hint Extern 2 ((wfDecls _ _)) => match goal with
| H32 : (wfDecls _ (DNil)) |- _ => inversion H32; subst; clear H32
| H32 : (wfDecls _ (DCons _ _)) |- _ => inversion H32; subst; clear H32
end : infra wf.
Hint Extern 2 ((wfTm _ _)) => match goal with
| H32 : (wfTm _ (Var _)) |- _ => inversion H32; subst; clear H32
| H32 : (wfTm _ (Abs _ _)) |- _ => inversion H32; subst; clear H32
| H32 : (wfTm _ (App _ _)) |- _ => inversion H32; subst; clear H32
| H32 : (wfTm _ (TAbs _)) |- _ => inversion H32; subst; clear H32
| H32 : (wfTm _ (TApp _ _)) |- _ => inversion H32; subst; clear H32
| H32 : (wfTm _ (Let _ _)) |- _ => inversion H32; subst; clear H32
end : infra wf.
Hint Resolve lookup_evar_wf : infra.
Hint Resolve lookup_evar_wf : wf.
Hint Resolve lookup_evar_wfindex lookup_etvar_wfindex : infra.
Hint Resolve lookup_evar_wfindex lookup_etvar_wfindex : lookup.
Hint Resolve lookup_evar_wfindex lookup_etvar_wfindex : wf.
Hint Constructors shift_evar shift_etvar : infra.
Hint Constructors shift_evar shift_etvar : shift.
Hint Constructors shift_evar shift_etvar : subst.
Hint Resolve weaken_shift_evar weaken_shift_etvar : infra.
Hint Resolve weaken_shift_evar weaken_shift_etvar : shift.
Hint Resolve shift_evar_shifthvl_TmVar shift_etvar_shifthvl_TyVar : infra.
Hint Resolve shift_evar_shifthvl_TmVar shift_etvar_shifthvl_TyVar : shift.
Hint Resolve shift_evar_shifthvl_TmVar shift_etvar_shifthvl_TyVar : shift_wf.
Hint Resolve shift_evar_shifthvl_TmVar shift_etvar_shifthvl_TyVar : wf.
Hint Constructors subst_evar subst_etvar : infra.
Hint Constructors subst_evar subst_etvar : subst.
Hint Resolve weaken_subst_evar weaken_subst_etvar : infra.
Hint Resolve weaken_subst_evar weaken_subst_etvar : subst.
Hint Resolve subst_evar_substhvl_TmVar subst_etvar_substhvl_TyVar : infra.
Hint Resolve subst_evar_substhvl_TmVar subst_etvar_substhvl_TyVar : subst.
Hint Resolve subst_evar_substhvl_TmVar subst_etvar_substhvl_TyVar : subst_wf.
Hint Resolve subst_evar_substhvl_TmVar subst_etvar_substhvl_TyVar : wf.
Hint Resolve subst_evar_substhvl_TmVar subst_etvar_substhvl_TyVar : substenv_substhvl.
Lemma shift_evar_lookup_evar :
(forall {c1 : (Cutoff TmVar)} {G : Ctx} {G0 : Ctx} (ins : (shift_evar c1 G G0)) {x7 : (Index TmVar)} {T6 : Ty} ,
(lookup_evar G x7 T6) -> (lookup_evar G0 (shift_TmVar_Index c1 x7) T6)).
Proof.
needleGenericInsertLookup .
Qed.
Lemma shift_evar_lookup_etvar :
(forall {c1 : (Cutoff TmVar)} {G : Ctx} {G0 : Ctx} (ins : (shift_evar c1 G G0)) {X7 : (Index TyVar)} ,
(lookup_etvar G X7) -> (lookup_etvar G0 X7)).
Proof.
needleGenericInsertLookup .
Qed.
Lemma shift_etvar_lookup_evar :
(forall {c1 : (Cutoff TyVar)} {G : Ctx} {G0 : Ctx} (ins : (shift_etvar c1 G G0)) {x7 : (Index TmVar)} {T6 : Ty} ,
(lookup_evar G x7 T6) -> (lookup_evar G0 x7 (shift_TyVar_Ty c1 T6))).
Proof.
needleGenericInsertLookup .
Qed.
Lemma shift_etvar_lookup_etvar :
(forall {c1 : (Cutoff TyVar)} {G : Ctx} {G0 : Ctx} (ins : (shift_etvar c1 G G0)) {X7 : (Index TyVar)} ,
(lookup_etvar G X7) -> (lookup_etvar G0 (shift_TyVar_Index c1 X7))).
Proof.
needleGenericInsertLookup .
Qed.
Hint Resolve shift_evar_lookup_evar shift_evar_lookup_etvar shift_etvar_lookup_evar shift_etvar_lookup_etvar : infra.
Hint Resolve shift_evar_lookup_evar shift_evar_lookup_etvar shift_etvar_lookup_evar shift_etvar_lookup_etvar : lookup.
Hint Resolve shift_evar_lookup_evar shift_evar_lookup_etvar shift_etvar_lookup_evar shift_etvar_lookup_etvar : shift.
Lemma subst_evar_lookup_etvar {G : Ctx} (T7 : Ty) {s6 : Tm} :
(forall {d13 : (Trace TmVar)} {G0 : Ctx} {G1 : Ctx} (sub : (subst_evar G T7 s6 d13 G0 G1)) {X7 : (Index TyVar)} ,
(lookup_etvar G0 X7) -> (lookup_etvar G1 X7)).
Proof.
needleGenericSubstEnvLookup .
Qed.
Lemma subst_etvar_lookup_evar {G : Ctx} {S5 : Ty} (wf : (wfTy (domainCtx G) S5)) :
(forall {d13 : (Trace TyVar)} {G0 : Ctx} {G1 : Ctx} (sub : (subst_etvar G S5 d13 G0 G1)) {x7 : (Index TmVar)} (T7 : Ty) ,
(lookup_evar G0 x7 T7) -> (lookup_evar G1 x7 (subst_TyVar_Ty d13 S5 T7))).
Proof.
needleGenericSubstEnvLookup .
Qed.
Hint Resolve subst_evar_lookup_etvar subst_etvar_lookup_evar : infra.
Hint Resolve subst_evar_lookup_etvar subst_etvar_lookup_evar : lookup.
Hint Resolve subst_evar_lookup_etvar subst_etvar_lookup_evar : subst.
Fixpoint size_Ty (S0 : Ty) {struct S0} :
nat :=
match S0 with
| (TVar X7) => 1
| (TArr T5 T6) => (plus 1 (plus (size_Ty T5) (size_Ty T6)))
| (TAll T7) => (plus 1 (size_Ty T7))
end.
Fixpoint size_Decls (d5 : Decls) {struct d5} :
nat :=
match d5 with
| (DNil) => 1
| (DCons t7 d6) => (plus 1 (plus (size_Tm t7) (size_Decls d6)))
end
with size_Tm (s : Tm) {struct s} :
nat :=
match s with
| (Var x7) => 1
| (Abs T5 t7) => (plus 1 (plus (size_Ty T5) (size_Tm t7)))
| (App t8 t9) => (plus 1 (plus (size_Tm t8) (size_Tm t9)))
| (TAbs t10) => (plus 1 (size_Tm t10))
| (TApp t11 T6) => (plus 1 (plus (size_Tm t11) (size_Ty T6)))
| (Let d5 t12) => (plus 1 (plus (size_Decls d5) (size_Tm t12)))
end.
Fixpoint shift_TyVar__size_Ty (S1 : Ty) (c1 : (Cutoff TyVar)) {struct S1} :
((size_Ty (shift_TyVar_Ty c1 S1)) = (size_Ty S1)) :=
match S1 return ((size_Ty (shift_TyVar_Ty c1 S1)) = (size_Ty S1)) with
| (TVar _) => eq_refl
| (TArr T1 T2) => (f_equal2 plus eq_refl (f_equal2 plus (shift_TyVar__size_Ty T1 c1) (shift_TyVar__size_Ty T2 c1)))
| (TAll T) => (f_equal2 plus eq_refl (shift_TyVar__size_Ty T (CS c1)))
end.
Fixpoint shift_TmVar__size_Decls (d11 : Decls) (c1 : (Cutoff TmVar)) {struct d11} :
((size_Decls (shift_TmVar_Decls c1 d11)) = (size_Decls d11)) :=
match d11 return ((size_Decls (shift_TmVar_Decls c1 d11)) = (size_Decls d11)) with
| (DNil) => eq_refl
| (DCons t d) => (f_equal2 plus eq_refl (f_equal2 plus (shift_TmVar__size_Tm t c1) (shift_TmVar__size_Decls d (CS c1))))
end
with shift_TmVar__size_Tm (s0 : Tm) (c1 : (Cutoff TmVar)) {struct s0} :
((size_Tm (shift_TmVar_Tm c1 s0)) = (size_Tm s0)) :=
match s0 return ((size_Tm (shift_TmVar_Tm c1 s0)) = (size_Tm s0)) with
| (Var _) => eq_refl
| (Abs T t) => (f_equal2 plus eq_refl (f_equal2 plus eq_refl (shift_TmVar__size_Tm t (CS c1))))
| (App t1 t2) => (f_equal2 plus eq_refl (f_equal2 plus (shift_TmVar__size_Tm t1 c1) (shift_TmVar__size_Tm t2 c1)))
| (TAbs t) => (f_equal2 plus eq_refl (shift_TmVar__size_Tm t c1))
| (TApp t T) => (f_equal2 plus eq_refl (f_equal2 plus (shift_TmVar__size_Tm t c1) eq_refl))
| (Let d t) => (f_equal2 plus eq_refl (f_equal2 plus (shift_TmVar__size_Decls d c1) (shift_TmVar__size_Tm t (weakenCutoffTmVar c1 (appendHvl H0 (bind d))))))
end.
Fixpoint shift_TyVar__size_Decls (d11 : Decls) (c1 : (Cutoff TyVar)) {struct d11} :
((size_Decls (shift_TyVar_Decls c1 d11)) = (size_Decls d11)) :=
match d11 return ((size_Decls (shift_TyVar_Decls c1 d11)) = (size_Decls d11)) with
| (DNil) => eq_refl
| (DCons t d) => (f_equal2 plus eq_refl (f_equal2 plus (shift_TyVar__size_Tm t c1) (shift_TyVar__size_Decls d c1)))
end
with shift_TyVar__size_Tm (s0 : Tm) (c1 : (Cutoff TyVar)) {struct s0} :
((size_Tm (shift_TyVar_Tm c1 s0)) = (size_Tm s0)) :=
match s0 return ((size_Tm (shift_TyVar_Tm c1 s0)) = (size_Tm s0)) with
| (Var _) => eq_refl
| (Abs T t) => (f_equal2 plus eq_refl (f_equal2 plus (shift_TyVar__size_Ty T c1) (shift_TyVar__size_Tm t c1)))
| (App t1 t2) => (f_equal2 plus eq_refl (f_equal2 plus (shift_TyVar__size_Tm t1 c1) (shift_TyVar__size_Tm t2 c1)))
| (TAbs t) => (f_equal2 plus eq_refl (shift_TyVar__size_Tm t (CS c1)))
| (TApp t T) => (f_equal2 plus eq_refl (f_equal2 plus (shift_TyVar__size_Tm t c1) (shift_TyVar__size_Ty T c1)))
| (Let d t) => (f_equal2 plus eq_refl (f_equal2 plus (shift_TyVar__size_Decls d c1) (shift_TyVar__size_Tm t (weakenCutoffTyVar c1 (appendHvl H0 (bind d))))))
end.
Hint Rewrite shift_TmVar__size_Decls shift_TyVar__size_Decls shift_TmVar__size_Tm shift_TyVar__size_Tm shift_TyVar__size_Ty : interaction.
Hint Rewrite shift_TmVar__size_Decls shift_TyVar__size_Decls shift_TmVar__size_Tm shift_TyVar__size_Tm shift_TyVar__size_Ty : shift_size.
Lemma weaken_size_Decls :
(forall (k : Hvl) (d11 : Decls) ,
((size_Decls (weakenDecls d11 k)) = (size_Decls d11))).
Proof.
needleGenericWeakenSize .
Qed.
Lemma weaken_size_Tm :
(forall (k : Hvl) (s0 : Tm) ,
((size_Tm (weakenTm s0 k)) = (size_Tm s0))).
Proof.
needleGenericWeakenSize .
Qed.
Lemma weaken_size_Ty :
(forall (k : Hvl) (S1 : Ty) ,
((size_Ty (weakenTy S1 k)) = (size_Ty S1))).
Proof.
needleGenericWeakenSize .
Qed.
Hint Rewrite weaken_size_Decls weaken_size_Tm weaken_size_Ty : interaction.
Hint Rewrite weaken_size_Decls weaken_size_Tm weaken_size_Ty : weaken_size.
Hint Rewrite appendCtx_assoc : interaction.
Hint Rewrite <- weakenCutoffTmVar_append weakenCutoffTyVar_append weakenTrace_append weakenDecls_append weakenTm_append weakenTy_append appendHvl_assoc : interaction. |
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <math.h>
#include "cconfigspace_internal.h"
#include "distribution_internal.h"
struct _ccs_distribution_roulette_data_s {
_ccs_distribution_common_data_t common_data;
size_t num_areas;
ccs_float_t *areas;
};
typedef struct _ccs_distribution_roulette_data_s _ccs_distribution_roulette_data_t;
static ccs_result_t
_ccs_distribution_del(ccs_object_t o) {
(void)o;
return CCS_SUCCESS;
}
static ccs_result_t
_ccs_distribution_roulette_get_bounds(_ccs_distribution_data_t *data,
ccs_interval_t *interval_ret);
static ccs_result_t
_ccs_distribution_roulette_samples(_ccs_distribution_data_t *data,
ccs_rng_t rng,
size_t num_values,
ccs_numeric_t *values);
static ccs_result_t
_ccs_distribution_roulette_strided_samples(_ccs_distribution_data_t *data,
ccs_rng_t rng,
size_t num_values,
size_t stride,
ccs_numeric_t *values);
static ccs_result_t
_ccs_distribution_roulette_soa_samples(_ccs_distribution_data_t *data,
ccs_rng_t rng,
size_t num_values,
ccs_numeric_t **values);
static _ccs_distribution_ops_t _ccs_distribution_roulette_ops = {
{ &_ccs_distribution_del },
&_ccs_distribution_roulette_samples,
&_ccs_distribution_roulette_get_bounds,
&_ccs_distribution_roulette_strided_samples,
&_ccs_distribution_roulette_soa_samples
};
static ccs_result_t
_ccs_distribution_roulette_get_bounds(_ccs_distribution_data_t *data,
ccs_interval_t *interval_ret) {
_ccs_distribution_roulette_data_t *d = (_ccs_distribution_roulette_data_t *)data;
interval_ret->type = CCS_NUM_INTEGER;
interval_ret->lower = CCSI(INT64_C(0));
interval_ret->upper = CCSI((ccs_int_t)(d->num_areas));
interval_ret->lower_included = CCS_TRUE;
interval_ret->upper_included = CCS_FALSE;
return CCS_SUCCESS;
}
static ccs_result_t
_ccs_distribution_roulette_samples(_ccs_distribution_data_t *data,
ccs_rng_t rng,
size_t num_values,
ccs_numeric_t *values) {
_ccs_distribution_roulette_data_t *d = (_ccs_distribution_roulette_data_t *)data;
gsl_rng *grng;
CCS_VALIDATE(ccs_rng_get_gsl_rng(rng, &grng));
for (size_t i = 0; i < num_values; i++) {
ccs_float_t rnd = gsl_rng_uniform(grng);
ccs_int_t index = ccs_dichotomic_search(d->num_areas, d->areas, rnd);
values[i].i = index;
}
return CCS_SUCCESS;
}
static ccs_result_t
_ccs_distribution_roulette_strided_samples(_ccs_distribution_data_t *data,
ccs_rng_t rng,
size_t num_values,
size_t stride,
ccs_numeric_t *values) {
_ccs_distribution_roulette_data_t *d = (_ccs_distribution_roulette_data_t *)data;
gsl_rng *grng;
CCS_VALIDATE(ccs_rng_get_gsl_rng(rng, &grng));
for (size_t i = 0; i < num_values; i++) {
ccs_float_t rnd = gsl_rng_uniform(grng);
ccs_int_t index = ccs_dichotomic_search(d->num_areas, d->areas, rnd);
values[i*stride].i = index;
}
return CCS_SUCCESS;
}
static ccs_result_t
_ccs_distribution_roulette_soa_samples(_ccs_distribution_data_t *data,
ccs_rng_t rng,
size_t num_values,
ccs_numeric_t **values) {
if (*values)
return _ccs_distribution_roulette_samples(data, rng, num_values, *values);
return CCS_SUCCESS;
}
ccs_result_t
ccs_create_roulette_distribution(size_t num_areas,
ccs_float_t *areas,
ccs_distribution_t *distribution_ret) {
CCS_CHECK_ARY(num_areas, areas);
CCS_CHECK_PTR(distribution_ret);
if (!num_areas || num_areas > INT64_MAX)
return -CCS_INVALID_VALUE;
ccs_float_t sum = 0.0;
for(size_t i = 0; i < num_areas; i++) {
if (areas[i] < 0.0)
return -CCS_INVALID_VALUE;
sum += areas[i];
}
if (sum == 0.0)
return -CCS_INVALID_VALUE;
ccs_float_t inv_sum = 1.0/sum;
if (isnan(inv_sum) || !isfinite(inv_sum))
return -CCS_INVALID_VALUE;
uintptr_t mem = (uintptr_t)calloc(1, sizeof(struct _ccs_distribution_s) + sizeof(_ccs_distribution_roulette_data_t) + sizeof(ccs_float_t)*(num_areas + 1) + sizeof(ccs_numeric_type_t));
if (!mem)
return -CCS_OUT_OF_MEMORY;
ccs_distribution_t distrib = (ccs_distribution_t)mem;
_ccs_object_init(&(distrib->obj), CCS_DISTRIBUTION, (_ccs_object_ops_t *)&_ccs_distribution_roulette_ops);
_ccs_distribution_roulette_data_t * distrib_data = (_ccs_distribution_roulette_data_t *)(mem + sizeof(struct _ccs_distribution_s));
distrib_data->common_data.data_types = (ccs_numeric_type_t *)(mem + sizeof(struct _ccs_distribution_s) + sizeof(_ccs_distribution_roulette_data_t) + sizeof(ccs_float_t)*(num_areas + 1));
distrib_data->common_data.type = CCS_ROULETTE;
distrib_data->common_data.dimension = 1;
distrib_data->common_data.data_types[0] = CCS_NUM_INTEGER;
distrib_data->num_areas = num_areas;
distrib_data->areas = (ccs_float_t *)(mem + sizeof(struct _ccs_distribution_s) + sizeof(_ccs_distribution_roulette_data_t));
distrib_data->areas[0] = 0.0;
for(size_t i = 1; i <= num_areas; i++) {
distrib_data->areas[i] = distrib_data->areas[i-1] + areas[i-1] * inv_sum;
}
distrib_data->areas[num_areas] = 1.0;
if (distrib_data->areas[num_areas] < distrib_data->areas[num_areas-1]) {
free((void *)mem);
return -CCS_INVALID_VALUE;
}
distrib->data = (_ccs_distribution_data_t *)distrib_data;
*distribution_ret = distrib;
return CCS_SUCCESS;
}
ccs_result_t
ccs_roulette_distribution_get_num_areas(ccs_distribution_t distribution,
size_t *num_areas_ret) {
CCS_CHECK_DISTRIBUTION(distribution, CCS_ROULETTE);
CCS_CHECK_PTR(num_areas_ret);
_ccs_distribution_roulette_data_t * data = (_ccs_distribution_roulette_data_t *)distribution->data;
*num_areas_ret = data->num_areas;
return CCS_SUCCESS;
}
ccs_result_t
ccs_roulette_distribution_get_areas(ccs_distribution_t distribution,
size_t num_areas,
ccs_float_t *areas,
size_t *num_areas_ret) {
CCS_CHECK_DISTRIBUTION(distribution, CCS_ROULETTE);
CCS_CHECK_ARY(num_areas, areas);
if (!areas && !num_areas_ret)
return -CCS_INVALID_VALUE;
_ccs_distribution_roulette_data_t * data = (_ccs_distribution_roulette_data_t *)distribution->data;
if (areas) {
if (num_areas < data->num_areas)
return -CCS_INVALID_VALUE;
for (size_t i = 0; i < data->num_areas; i++)
areas[i] = data->areas[i+1] - data->areas[i];
for (size_t i = data->num_areas; i < num_areas; i++)
areas[i] = 0.0;
}
if (num_areas_ret)
*num_areas_ret = data->num_areas;
return CCS_SUCCESS;
}
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
-- | This module provides type-safe conversions from Foreign C types
-- to Haskell types, and vice versa. It is especially convenient when
-- writing code with Haskell's C FFI.
--
-- This module will not compile on non-64-bit operating systems.
module CCast
( Cast(cast)
, CComplex(CComplex)
) where
import Data.Coerce
import Data.Complex
import Data.Int
import Data.Word
import Foreign.C.Types
import Foreign.Ptr
import Foreign.Storable
import Bit64Only
-- | A typeclass for typesafe c-style casts from 'a' to 'b',
-- for use with Haskell's C FFI. This is just a convenience,
-- to prevent from having to think about numeric conversions.
-- Type inference is still weak here; I recommend two solutions:
--
-- With -XTypeApplications:
--
-- @
-- cast \@\CChar \@\Int8 x -- convert x from CChar to Int8
-- @
--
-- With explicit type annotations:
--
-- @
-- cast x :: Int8 -- convert x from CChar to Int8
-- @
--
class Cast a b where
cast :: Coercible a b => a -> b
cast = coerce;
-- | Complex number for FFI with the same memory layout as std::complex\<T\>
data CComplex a = CComplex !a !a
deriving (Eq)
instance Storable a => Storable (CComplex a) where
sizeOf _ = sizeOf (undefined :: a) * 2
alignment _ = alignment (undefined :: a)
poke p (CComplex x y) = do
pokeElemOff (castPtr p) 0 x
pokeElemOff (castPtr p) 1 y
peek p = CComplex
<$> peekElemOff (castPtr p) 0
<*> peekElemOff (castPtr p) 1
instance Cast CChar Int8 where
instance Cast Int8 CChar where
instance Cast CSChar Int8 where
instance Cast Int8 CSChar where
instance Cast CUChar Word8 where
instance Cast Word8 CUChar where
instance Cast CShort Int16 where
instance Cast Int16 CShort where
instance Cast CUShort Word16 where
instance Cast Word16 CUShort where
instance Cast CInt Int32 where
instance Cast Int32 CInt where
instance Cast CUInt Word32 where
instance Cast Word32 CUInt where
instance Cast CInt Int where; cast = fromIntegral;
-- | WARNING! This conversion is potentially lossy.
instance Cast Int CInt where; cast = fromIntegral;
instance Cast CLong Int64 where
instance Cast Int64 CLong where
instance Cast CULong Word64 where
instance Cast Word64 CULong where
instance Cast CFloat Float where
instance Cast Float CFloat where
instance Cast CDouble Double where
instance Cast Double CDouble where
instance Cast (CComplex CFloat) (Complex Float) where; cast (CComplex x y) = cast x :+ cast y; {-# INLINE cast #-}
instance Cast (Complex Float) (CComplex CFloat) where; cast (x :+ y) = CComplex (cast x) (cast y); {-# INLINE cast #-}
instance Cast (CComplex CDouble) (Complex Double) where; cast (CComplex x y) = cast x :+ cast y; {-# INLINE cast #-}
instance Cast (Complex Double) (CComplex CDouble) where; cast (x :+ y) = CComplex (cast x) (cast y); {-# INLINE cast #-}
instance Cast CPtrdiff Int64 where
instance Cast Int64 CPtrdiff where
instance Cast CSize Word64 where
instance Cast Word64 CSize where
instance Cast CWchar Int32 where
instance Cast Int32 CWchar where
instance Cast CSigAtomic Int32 where
instance Cast Int32 CSigAtomic where
instance Cast CLLong Int64 where
instance Cast CULLong Word64 where
instance Cast CBool Word8 where
instance Cast Word8 CBool where
instance Cast CIntPtr Int64 where
instance Cast Int64 CIntPtr where
instance Cast CUIntPtr Word64 where
instance Cast Word64 CUIntPtr where
instance Cast CIntMax Int64 where
instance Cast Int64 CIntMax where
instance Cast CClock Int64 where
instance Cast Int64 CClock where
instance Cast CTime Int64 where
instance Cast Int64 CTime where
instance Cast CUSeconds Word32 where
instance Cast Word32 CUSeconds where
instance Cast CSUSeconds Int64 where
instance Cast Int64 CSUSeconds where
-- Proof that we are on a 64-bit architecture.
-- This module will not compile outside of a 64-bit architecture.
myArchitecture :: Refined MustBe64 Int
myArchitecture = $$(refineTH (sizeOf (undefined :: Int)))
|
function [data] = ft_megrealign(cfg, data)
% FT_MEGREALIGN interpolates MEG data towards standard gradiometer locations by
% projecting the individual timelocked data towards a coarse source reconstructed
% representation and computing the magnetic field on the standard gradiometer
% locations.
%
% Use as
% [interp] = ft_megrealign(cfg, data)
%
% Required configuration options:
% cfg.template
% cfg.inwardshift
%
% The new gradiometer definition is obtained from a template dataset,
% or can be constructed by averaging the gradiometer positions over
% multiple datasets.
% cfg.template = single dataset that serves as template
% cfg.template(1..N) = datasets that are averaged into the standard
%
% The realignment is done by computing a minumum norm estimate using a
% large number of dipoles that are placed in the upper layer of the brain
% surface, followed by a forward computation towards the template
% gradiometer array. This requires the specification of a volume conduction
% model of the head and of a source model.
%
% A volume conduction model of the head should be specified with
% cfg.headmodel = structure, see FT_PREPARE_HEADMODEL
%
% A source model (i.e. a superficial layer with distributed sources) can be
% constructed from a headshape file, or from inner surface of the volume conduction
% model using FT_PREPARE_SOIURCEMODEL using the following options
% cfg.spheremesh = number of dipoles in the source layer (default = 642)
% cfg.inwardshift = depth of the source layer relative to the headshape
% surface or volume conduction model (no default
% supplied, see below)
% cfg.headshape = a filename containing headshape, a structure containing a
% single triangulated boundary, or a Nx3 matrix with surface
% points
%
% If you specify a headshape and it describes the skin surface, you should specify an
% inward shift of 2.5 cm.
%
% For a single-sphere or a local-spheres volume conduction model based on the skin
% surface, an inward shift of 2.5 cm is reasonable.
%
% For a single-sphere or a local-spheres volume conduction model based on the brain
% surface, you should probably use an inward shift of about 1 cm.
%
% For a realistic single-shell volume conduction model based on the brain surface, you
% should probably use an inward shift of about 1 cm.
%
% Other options are
% cfg.pruneratio = for singular values, default is 1e-3
% cfg.verify = 'yes' or 'no', show the percentage difference (default = 'yes')
% cfg.feedback = 'yes' or 'no' (default = 'no')
% cfg.channel = Nx1 cell-array with selection of channels (default = 'MEG'),
% see FT_CHANNELSELECTION for details
% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')
%
% This implements the method described by T.R. Knosche, Transformation
% of whole-head MEG recordings between different sensor positions.
% Biomed Tech (Berl). 2002 Mar;47(3):59-62. For more information and
% related methods, see Stolk et al., Online and offline tools for head
% movement compensation in MEG. NeuroImage, 2012.
%
% To facilitate data-handling and distributed computing you can use
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_PREPARE_LOCALSPHERES, FT_PREPARE_SINGLESHELL
% Copyright (C) 2004-2014, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$
% these are used by the ft_preamble/ft_postamble function and scripts
ft_revision = '$Id$';
ft_nargin = nargin;
ft_nargout = nargout;
% do the general setup of the function
ft_defaults
ft_preamble init
ft_preamble debug
ft_preamble loadvar data
ft_preamble provenance data
ft_preamble trackconfig
% the ft_abort variable is set to true or false in ft_preamble_init
if ft_abort
return
end
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'renamed', {'plot3d', 'feedback'});
cfg = ft_checkconfig(cfg, 'renamedval', {'headshape', 'headmodel', []});
cfg = ft_checkconfig(cfg, 'required', {'inwardshift', 'template'});
cfg = ft_checkconfig(cfg, 'renamed', {'hdmfile', 'headmodel'});
cfg = ft_checkconfig(cfg, 'renamed', {'vol', 'headmodel'});
cfg = ft_checkconfig(cfg, 'renamed', {'grid', 'sourcemodel'});
% set the default configuration
cfg.headshape = ft_getopt(cfg, 'headshape', []);
cfg.pruneratio = ft_getopt(cfg, 'pruneratio', 1e-3);
cfg.spheremesh = ft_getopt(cfg, 'spheremesh', 642);
cfg.verify = ft_getopt(cfg, 'verify', 'yes');
cfg.feedback = ft_getopt(cfg, 'feedback', 'yes');
cfg.trials = ft_getopt(cfg, 'trials', 'all', 1);
cfg.channel = ft_getopt(cfg, 'channel', 'MEG');
cfg.topoparam = ft_getopt(cfg, 'topoparam', 'rms');
% store original datatype
dtype = ft_datatype(data);
% check if the input data is valid for this function
data = ft_checkdata(data, 'datatype', 'raw', 'feedback', 'yes', 'hassampleinfo', 'yes', 'ismeg', 'yes');
% do realignment per trial
pertrial = all(ismember({'nasX';'nasY';'nasZ';'lpaX';'lpaY';'lpaZ';'rpaX';'rpaY';'rpaZ'}, data.label));
% put the low-level options pertaining to the dipole grid in their own field
cfg = ft_checkconfig(cfg, 'renamed', {'tightgrid', 'tight'}); % this is moved to cfg.sourcemodel.tight by the subsequent createsubcfg
cfg = ft_checkconfig(cfg, 'renamed', {'sourceunits', 'unit'}); % this is moved to cfg.sourcemodel.unit by the subsequent createsubcfg
% put the low-level options pertaining to the sourcemodel in their own field
cfg = ft_checkconfig(cfg, 'createsubcfg', {'sourcemodel'});
% move some fields from cfg.sourcemodel back to the top-level configuration
cfg = ft_checkconfig(cfg, 'createtopcfg', {'sourcemodel'});
if isstruct(cfg.template)
% this should be a cell-array
cfg.template = {cfg.template};
end
% retain only the MEG channels in the data and temporarily store
% the rest, these will be added back to the transformed data later.
% select trials and channels of interest
tmpcfg = [];
tmpcfg.trials = cfg.trials;
tmpcfg.channel = setdiff(data.label, ft_channelselection(cfg.channel, data.label));
rest = ft_selectdata(tmpcfg, data);
tmpcfg.channel = ft_channelselection(cfg.channel, data.label);
data = ft_selectdata(tmpcfg, data);
% restore the provenance information
[cfg, data] = rollback_provenance(cfg, data);
Ntrials = length(data.trial);
% cfg.channel = ft_channelselection(cfg.channel, data.label);
% dataindx = match_str(data.label, cfg.channel);
% restindx = setdiff(1:length(data.label),dataindx);
% if ~isempty(restindx)
% fprintf('removing %d non-MEG channels from the data\n', length(restindx));
% rest.label = data.label(restindx); % first remember the rest
% data.label = data.label(dataindx); % then reduce the data
% for i=1:Ntrials
% rest.trial{i} = data.trial{i}(restindx,:); % first remember the rest
% data.trial{i} = data.trial{i}(dataindx,:); % then reduce the data
% end
% else
% rest.label = {};
% rest.trial = {};
% end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% construct the average template gradiometer array
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
template = struct([]); % initialize as 0x0 empty struct array with no fields
for i=1:length(cfg.template)
if ischar(cfg.template{i})
fprintf('reading template sensor position from %s\n', cfg.template{i});
tmp = ft_read_sens(cfg.template{i}, 'senstype', 'meg');
elseif isstruct(cfg.template{i}) && isfield(cfg.template{i}, 'coilpos') && isfield(cfg.template{i}, 'coilori') && isfield(cfg.template{i}, 'tra')
tmp = cfg.template{i};
elseif isstruct(cfg.template{i}) && isfield(cfg.template{i}, 'pnt') && isfield(cfg.template{i}, 'ori') && isfield(cfg.template{i}, 'tra')
% it seems to be a pre-2011v1 type gradiometer structure, update it
tmp = ft_datatype_sens(cfg.template{i});
else
ft_error('unrecognized template input');
end
% prevent "Subscripted assignment between dissimilar structures" error
template = appendstruct(template, tmp); clear tmp
end
grad = ft_average_sens(template);
% construct the final template gradiometer definition
template = [];
template.grad = grad;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% FT_PREPARE_VOL_SENS will match the data labels, the gradiometer labels and the
% volume model labels (in case of a localspheres model) and result in a gradiometer
% definition that only contains the gradiometers that are present in the data.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
volcfg = [];
volcfg.headmodel = cfg.headmodel;
volcfg.grad = data.grad;
volcfg.channel = data.label; % this might be a subset of the MEG channels
gradorig = data.grad; % this is needed later on for plotting. As of
% yet the next step is not entirely correct, because it does not keep track
% of the balancing of the gradiometer array. FIXME this may require some
% thought because the leadfields are computed with low level functions and
% do not easily accommodate for matching the correct channels with each
% other (in order to compute the projection matrix).
[volold, data.grad] = prepare_headmodel(volcfg);
% note that it is necessary to keep the two volume conduction models
% separate, since the single-shell Nolte model contains gradiometer specific
% precomputed parameters. Note that this is not guaranteed to result in a
% good projection for local sphere models.
volcfg.grad = template.grad;
volcfg.channel = 'MEG'; % include all MEG channels
[volnew, template.grad] = prepare_headmodel(volcfg);
if strcmp(ft_senstype(data.grad), ft_senstype(template.grad))
[id, it] = match_str(data.grad.label, template.grad.label);
fprintf('mean distance towards template gradiometers is %.2f %s\n', mean(sum((data.grad.chanpos(id,:)-template.grad.chanpos(it,:)).^2, 2).^0.5), template.grad.unit);
else
% the projection is from one MEG system to another MEG system, which makes a comparison of the data difficult
cfg.feedback = 'no';
cfg.verify = 'no';
end
% copy all options that are potentially used in ft_prepare_sourcemodel
tmpcfg = keepfields(cfg, {'sourcemodel', 'mri', 'headshape', 'symmetry', 'smooth', 'threshold', 'spheremesh', 'inwardshift', 'xgrid' 'ygrid', 'zgrid', 'resolution', 'tight', 'warpmni', 'template', 'showcallinfo'});
tmpcfg.headmodel = volold;
tmpcfg.grad = data.grad;
% create the source positions on which the data will be projected
sourcemodel = ft_prepare_sourcemodel(tmpcfg);
pos = sourcemodel.pos;
% sometimes some of the dipole positions are nan, due to problems with the headsurface triangulation
% remove them to prevent problems with the forward computation
sel = find(any(isnan(pos(:,1)),2));
pos(sel,:) = [];
% compute the forward model for the new gradiometer positions
fprintf('computing forward model for %d dipoles\n', size(pos,1));
lfnew = ft_compute_leadfield(pos, template.grad, volnew);
if ~pertrial
%this needs to be done only once
lfold = ft_compute_leadfield(pos, data.grad, volold);
[realign, noalign, bkalign] = computeprojection(lfold, lfnew, cfg.pruneratio, cfg.verify);
else
%the forward model and realignment matrices have to be computed for each trial
%this also goes for the singleshell volume conductor model
%x = which('rigidbodyJM'); %this function is needed
%if isempty(x)
% ft_error('you are trying out experimental code for which you need some extra functionality which is currently not in the release version of FieldTrip. if you are interested in trying it out, contact Jan-Mathijs');
%end
end
% interpolate the data towards the template gradiometers
for i=1:Ntrials
fprintf('realigning trial %d\n', i);
if pertrial
%warp the gradiometer array according to the motiontracking data
sel = match_str(rest.label, {'nasX';'nasY';'nasZ';'lpaX';'lpaY';'lpaZ';'rpaX';'rpaY';'rpaZ'});
hmdat = rest.trial{i}(sel,:);
if ~all(hmdat==repmat(hmdat(:,1),[1 size(hmdat,2)]))
ft_error('only one position per trial is at present allowed');
else
%M = rigidbodyJM(hmdat(:,1))
M = ft_headcoordinates(hmdat(1:3,1),hmdat(4:6,1),hmdat(7:9,1));
grad = ft_transform_geometry(M, data.grad);
end
volcfg.grad = grad;
%compute volume conductor
[volold, grad] = prepare_headmodel(volcfg);
%compute forward model
lfold = ft_compute_leadfield(pos, grad, volold);
%compute projection matrix
[realign, noalign, bkalign] = computeprojection(lfold, lfnew, cfg.pruneratio, cfg.verify);
end
data.realign{i} = realign * data.trial{i};
if strcmp(cfg.verify, 'yes')
% also compute the residual variance when interpolating
[id,it] = match_str(data.grad.label, template.grad.label);
rvrealign = rv(data.trial{i}(id,:), data.realign{i}(it,:));
fprintf('original -> template RV %.2f %%\n', 100 * mean(rvrealign));
datnoalign = noalign * data.trial{i};
datbkalign = bkalign * data.trial{i};
rvnoalign = rv(data.trial{i}, datnoalign);
rvbkalign = rv(data.trial{i}, datbkalign);
fprintf('original -> original RV %.2f %%\n', 100 * mean(rvnoalign));
fprintf('original -> template -> original RV %.2f %%\n', 100 * mean(rvbkalign));
end
end
% plot the topography before and after the realignment
if strcmp(cfg.feedback, 'yes')
ft_warning('showing MEG topography (RMS value over time) in the first trial only');
Nchan = length(data.grad.label);
[id,it] = match_str(data.grad.label, template.grad.label);
pos1 = data.grad.chanpos(id,:);
pos2 = template.grad.chanpos(it,:);
prj1 = elproj(pos1); tri1 = delaunay(prj1(:,1), prj1(:,2));
prj2 = elproj(pos2); tri2 = delaunay(prj2(:,1), prj2(:,2));
switch cfg.topoparam
case 'rms'
p1 = sqrt(mean(data.trial{1}(id,:).^2, 2));
p2 = sqrt(mean(data.realign{1}(it,:).^2, 2));
case 'svd'
[u, s, v] = svd(data.trial{1}(id,:)); p1 = u(:,1);
[u, s, v] = svd(data.realign{1}(it,:)); p2 = u(:,1);
otherwise
ft_error('unsupported cfg.topoparam');
end
X = [pos1(:,1) pos2(:,1)]';
Y = [pos1(:,2) pos2(:,2)]';
Z = [pos1(:,3) pos2(:,3)]';
% show figure with old an new helmets, volume model and source positions
figure
hold on
ft_plot_headmodel(volold);
plot3(sourcemodel.pos(:,1),sourcemodel.pos(:,2),sourcemodel.pos(:,3),'b.');
plot3(pos1(:,1), pos1(:,2), pos1(:,3), 'r.') % original positions
plot3(pos2(:,1), pos2(:,2), pos2(:,3), 'g.') % template positions
line(X,Y,Z, 'color', 'black');
view(-90, 90);
% show figure with data on old helmet location
figure
hold on
plot3(pos1(:,1), pos1(:,2), pos1(:,3), 'r.') % original positions
plot3(pos2(:,1), pos2(:,2), pos2(:,3), 'g.') % template positions
line(X,Y,Z, 'color', 'black');
axis equal; axis vis3d
bnd1 = [];
bnd1.pos = pos1;
bnd1.tri = tri1;
ft_plot_mesh(bnd1,'vertexcolor',p1,'edgecolor','none')
title('RMS, before realignment')
view(-90, 90)
% show figure with data on new helmet location
figure
hold on
plot3(pos1(:,1), pos1(:,2), pos1(:,3), 'r.') % original positions
plot3(pos2(:,1), pos2(:,2), pos2(:,3), 'g.') % template positions
line(X,Y,Z, 'color', 'black');
axis equal; axis vis3d
bnd2 = [];
bnd2.pos = pos2;
bnd2.tri = tri2;
ft_plot_mesh(bnd2,'vertexcolor',p2,'edgecolor','none')
title('RMS, after realignment')
view(-90, 90)
end
% store the realigned data in a new structure
interp.label = template.grad.label;
interp.grad = template.grad; % replace with the template gradiometer array
interp.trial = data.realign; % remember the processed data
interp.fsample = data.fsample;
interp.time = data.time;
% add the rest channels back to the data, these were not interpolated
if ~isempty(rest.label)
fprintf('adding %d non-MEG channels back to the data (', length(rest.label));
fprintf('%s, ', rest.label{1:end-1});
fprintf('%s)\n', rest.label{end});
for trial=1:length(rest.trial)
interp.trial{trial} = [interp.trial{trial}; rest.trial{trial}];
end
interp.label = [interp.label; rest.label];
end
% copy the trial specific information into the output
if isfield(data, 'trialinfo')
interp.trialinfo = data.trialinfo;
end
% copy the sampleinfo field as well
if isfield(data, 'sampleinfo')
interp.sampleinfo = data.sampleinfo;
end
% convert back to input type if necessary
switch dtype
case 'timelock'
interp = ft_checkdata(interp, 'datatype', 'timelock');
otherwise
% keep the output as it is
end
% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble trackconfig
ft_postamble previous data
% rename the output variable to accomodate the savevar postamble
data = interp;
ft_postamble provenance data
ft_postamble history data
ft_postamble savevar data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction that computes the projection matrix(ces)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [realign, noalign, bkalign] = computeprojection(lfold, lfnew, pruneratio, verify)
% compute this inverse only once, although it is used twice
tmp = prunedinv(lfold, pruneratio);
% compute the three interpolation matrices
fprintf('computing interpolation matrix #1\n');
realign = lfnew * tmp;
if strcmp(verify, 'yes')
fprintf('computing interpolation matrix #2\n');
noalign = lfold * tmp;
fprintf('computing interpolation matrix #3\n');
bkalign = lfold * prunedinv(lfnew, pruneratio) * realign;
else
noalign = [];
bkalign = [];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction that computes the inverse using a pruned SVD
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [lfi] = prunedinv(lf, r)
[u, s, v] = svd(lf);
if r<1
% treat r as a ratio
p = find(s<(s(1,1)*r) & s~=0);
else
% treat r as the number of spatial components to keep
diagels = 1:(min(size(s))+1):(min(size(s)).^2);
p = diagels((r+1):end);
end
fprintf('pruning %d from %d, i.e. removing the %d smallest spatial components\n', length(p), min(size(s)), length(p));
s(p) = 0;
s(find(s~=0)) = 1./s(find(s~=0));
lfi = v * s' * u';
|
{-|
Copyright:
This file is part of the package zxcvbn-hs. It is subject to the
license terms in the LICENSE file found in the top-level directory
of this distribution and at:
https://code.devalot.com/sthenauth/zxcvbn-hs
No part of this package, including this file, may be copied,
modified, propagated, or distributed except according to the terms
contained in the LICENSE file.
License: MIT
-}
module Text.Password.Strength.Internal.Math
( variations
, variations'
, bruteForce
, caps
) where
--------------------------------------------------------------------------------
-- Library Imports:
import Control.Lens ((^.))
import Data.Char (isUpper)
import qualified Data.Text as Text
import Numeric.SpecFunctions (choose)
--------------------------------------------------------------------------------
-- Project Imports:
import Text.Password.Strength.Internal.Token
--------------------------------------------------------------------------------
-- | Equation 2, section 4, page 163 (8/18)
--
-- NOTE: The other implementations don't seem to divide the sum by two
-- but the equation in the paper clearly does.
variations :: Int -> Int -> Integer
variations 0 _ = 1
variations _ 0 = 1
variations u l = max 1 (sum (floor . choose (u+l) <$> [1 .. min u l]) `div` 2)
--------------------------------------------------------------------------------
-- | Like equation 2, but modified for l33t and keyboard variations.
--
-- This equation does not appear in the 2016 paper although it is
-- mentioned. Therefore it was adapted from the CoffeeScript and
-- Python implementations.
variations' :: Int -> Int -> Integer
variations' 0 _ = 2
variations' _ 0 = 2
variations' u l = variations u l
--------------------------------------------------------------------------------
-- | Calculate the brute force score for text with the given length.
bruteForce :: Int -> Integer
bruteForce = (10 ^)
--------------------------------------------------------------------------------
-- | Score the use of uppercase letters according to the paper. This
-- is specified in the paragraph preceding equation 2.
caps :: Token -> Integer -> Integer
caps token n =
let text = token ^. tokenChars
upper = Text.length (Text.filter isUpper text)
lower = Text.length text - upper
allLower = lower == Text.length text
allUpper = lower == 0
firstUpper = upper == 1 && Text.all isUpper (Text.take 1 text)
lastUpper = upper == 1 && Text.all isUpper (Text.takeEnd 1 text)
in case () of
() | allLower -> n
| firstUpper -> n * 2
| lastUpper -> n * 2
| allUpper -> n * 2
| otherwise -> n * variations upper lower
--------------------------------------------------------------------------------
-- NOTE: Equation 3 is in Keybaord.hs.
|
[STATEMENT]
lemma degen_acc_run_complete:
assumes AR: "is_acc_run r"
obtains r'
where "degen.is_acc_run T m r'" and "r = fst o r'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
proof (cases "num_acc = 0")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<lbrakk>\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis; num_acc = 0\<rbrakk> \<Longrightarrow> thesis
2. \<lbrakk>\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis; num_acc \<noteq> 0\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
num_acc = 0
goal (2 subgoals):
1. \<lbrakk>\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis; num_acc = 0\<rbrakk> \<Longrightarrow> thesis
2. \<lbrakk>\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis; num_acc \<noteq> 0\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
with AR degen_acc_run_complete0
[PROOF STATE]
proof (chain)
picking this:
is_acc_run r
\<lbrakk>num_acc = 0; is_acc_run ?r\<rbrakk> \<Longrightarrow> b_graph.is_acc_run (degeneralize_ext ?m) (\<lambda>i. (?r i, 0))
num_acc = 0
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
is_acc_run r
\<lbrakk>num_acc = 0; is_acc_run ?r\<rbrakk> \<Longrightarrow> b_graph.is_acc_run (degeneralize_ext ?m) (\<lambda>i. (?r i, 0))
num_acc = 0
goal (1 subgoal):
1. thesis
[PROOF STEP]
by (auto intro!: that[of "(\<lambda>i. (r i, 0))"])
[PROOF STATE]
proof (state)
this:
thesis
goal (1 subgoal):
1. \<lbrakk>\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis; num_acc \<noteq> 0\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<lbrakk>\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis; num_acc \<noteq> 0\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
case False
[PROOF STATE]
proof (state)
this:
num_acc \<noteq> 0
goal (1 subgoal):
1. \<lbrakk>\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis; num_acc \<noteq> 0\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
assume NN0[simp]: "num_acc \<noteq> 0"
[PROOF STATE]
proof (state)
this:
num_acc \<noteq> 0
goal (1 subgoal):
1. \<lbrakk>\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis; num_acc \<noteq> 0\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
from AR
[PROOF STATE]
proof (chain)
picking this:
is_acc_run r
[PROOF STEP]
have R: "is_run r" and ACC: "\<forall>n<num_acc. \<exists>\<^sub>\<infinity>i. n \<in> acc (r i)"
[PROOF STATE]
proof (prove)
using this:
is_acc_run r
goal (1 subgoal):
1. is_run r &&& \<forall>n<num_acc. \<exists>\<^sub>\<infinity>i. n \<in> acc (r i)
[PROOF STEP]
unfolding is_acc_run_def is_acc_def
[PROOF STATE]
proof (prove)
using this:
is_run r \<and> (\<forall>n<num_acc. \<exists>\<^sub>\<infinity>i. n \<in> acc (r i))
goal (1 subgoal):
1. is_run r &&& \<forall>n<num_acc. \<exists>\<^sub>\<infinity>i. n \<in> acc (r i)
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
is_run r
\<forall>n<num_acc. \<exists>\<^sub>\<infinity>i. n \<in> acc (r i)
goal (1 subgoal):
1. \<lbrakk>\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis; num_acc \<noteq> 0\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
from degen_run_complete[OF NN0 R]
[PROOF STATE]
proof (chain)
picking this:
\<exists>r'. graph_defs.is_run (degeneralize_ext ?m) r' \<and> r = fst \<circ> r'
[PROOF STEP]
obtain r' where
R': "degen.is_run T m r'"
and [simp]: "r = fst \<circ> r'"
[PROOF STATE]
proof (prove)
using this:
\<exists>r'. graph_defs.is_run (degeneralize_ext ?m) r' \<and> r = fst \<circ> r'
goal (1 subgoal):
1. (\<And>r'. \<lbrakk>graph_defs.is_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
graph_defs.is_run (degeneralize_ext m) r'
r = fst \<circ> r'
goal (1 subgoal):
1. \<lbrakk>\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis; num_acc \<noteq> 0\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
from ACC
[PROOF STATE]
proof (chain)
picking this:
\<forall>n<num_acc. \<exists>\<^sub>\<infinity>i. n \<in> acc (r i)
[PROOF STEP]
have ACC': "\<forall>n<num_acc. \<exists>\<^sub>\<infinity>i. n \<in> acc (fst (r' i))"
[PROOF STATE]
proof (prove)
using this:
\<forall>n<num_acc. \<exists>\<^sub>\<infinity>i. n \<in> acc (r i)
goal (1 subgoal):
1. \<forall>n<num_acc. \<exists>\<^sub>\<infinity>i. n \<in> acc (fst (r' i))
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<forall>n<num_acc. \<exists>\<^sub>\<infinity>i. n \<in> acc (fst (r' i))
goal (1 subgoal):
1. \<lbrakk>\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis; num_acc \<noteq> 0\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
have "\<forall>i. \<exists>j>i. r' j \<in> degen.F T m"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>i. \<exists>j>i. r' j \<in> bg_F (degeneralize_ext m)
[PROOF STEP]
proof
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>i. \<exists>j>i. r' j \<in> bg_F (degeneralize_ext m)
[PROOF STEP]
fix i
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>i. \<exists>j>i. r' j \<in> bg_F (degeneralize_ext m)
[PROOF STEP]
obtain q n where RI: "r' (Suc i) = (q,n)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>q n. r' (Suc i) = (q, n) \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (cases "r' (Suc i)")
[PROOF STATE]
proof (state)
this:
r' (Suc i) = (q, n)
goal (1 subgoal):
1. \<And>i. \<exists>j>i. r' j \<in> bg_F (degeneralize_ext m)
[PROOF STEP]
have "(n + (num_acc - n mod num_acc)) mod num_acc = 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (n + (num_acc - n mod num_acc)) mod num_acc = 0
[PROOF STEP]
apply (rule dvd_imp_mod_0)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. num_acc dvd n + (num_acc - n mod num_acc)
[PROOF STEP]
apply (metis (mono_tags, lifting) NN0 add_diff_inverse mod_0_imp_dvd
mod_add_left_eq mod_less_divisor mod_self nat_diff_split not_gr_zero zero_less_diff)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
(n + (num_acc - n mod num_acc)) mod num_acc = 0
goal (1 subgoal):
1. \<And>i. \<exists>j>i. r' j \<in> bg_F (degeneralize_ext m)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
(n + (num_acc - n mod num_acc)) mod num_acc = 0
[PROOF STEP]
obtain ofs where
OFS_LESS: "ofs<num_acc"
and [simp]: "(n + ofs) mod num_acc = 0"
[PROOF STATE]
proof (prove)
using this:
(n + (num_acc - n mod num_acc)) mod num_acc = 0
goal (1 subgoal):
1. (\<And>ofs. \<lbrakk>ofs < num_acc; (n + ofs) mod num_acc = 0\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (metis NN0 Nat.add_0_right diff_less neq0_conv)
[PROOF STATE]
proof (state)
this:
ofs < num_acc
(n + ofs) mod num_acc = 0
goal (1 subgoal):
1. \<And>i. \<exists>j>i. r' j \<in> bg_F (degeneralize_ext m)
[PROOF STEP]
with degen_acc_run_complete_aux2[OF NN0 R' ACC' RI OFS_LESS]
[PROOF STATE]
proof (chain)
picking this:
\<exists>j\<ge>Suc i. \<exists>q'. r' j = (q', (n + ofs) mod num_acc) \<and> (n + ofs) mod num_acc \<in> acc q'
ofs < num_acc
(n + ofs) mod num_acc = 0
[PROOF STEP]
obtain j q' where
"j>i" "r' j = (q',0)" and "0\<in>acc q'"
[PROOF STATE]
proof (prove)
using this:
\<exists>j\<ge>Suc i. \<exists>q'. r' j = (q', (n + ofs) mod num_acc) \<and> (n + ofs) mod num_acc \<in> acc q'
ofs < num_acc
(n + ofs) mod num_acc = 0
goal (1 subgoal):
1. (\<And>j q'. \<lbrakk>i < j; r' j = (q', 0); 0 \<in> acc q'\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (auto simp: less_eq_Suc_le)
[PROOF STATE]
proof (state)
this:
i < j
r' j = (q', 0)
0 \<in> acc q'
goal (1 subgoal):
1. \<And>i. \<exists>j>i. r' j \<in> bg_F (degeneralize_ext m)
[PROOF STEP]
thus "\<exists>j>i. r' j \<in> degen.F T m"
[PROOF STATE]
proof (prove)
using this:
i < j
r' j = (q', 0)
0 \<in> acc q'
goal (1 subgoal):
1. \<exists>j>i. r' j \<in> bg_F (degeneralize_ext m)
[PROOF STEP]
by (auto simp: degeneralize_ext_def)
[PROOF STATE]
proof (state)
this:
\<exists>j>i. r' j \<in> bg_F (degeneralize_ext m)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<forall>i. \<exists>j>i. r' j \<in> bg_F (degeneralize_ext m)
goal (1 subgoal):
1. \<lbrakk>\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis; num_acc \<noteq> 0\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
hence "\<exists>\<^sub>\<infinity>i. r' i \<in> degen.F T m"
[PROOF STATE]
proof (prove)
using this:
\<forall>i. \<exists>j>i. r' j \<in> bg_F (degeneralize_ext m)
goal (1 subgoal):
1. \<exists>\<^sub>\<infinity>i. r' i \<in> bg_F (degeneralize_ext m)
[PROOF STEP]
by (auto simp: INFM_nat)
[PROOF STATE]
proof (state)
this:
\<exists>\<^sub>\<infinity>i. r' i \<in> bg_F (degeneralize_ext m)
goal (1 subgoal):
1. \<lbrakk>\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis; num_acc \<noteq> 0\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
have "degen.is_acc_run T m r'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. b_graph.is_acc_run (degeneralize_ext m) r'
[PROOF STEP]
unfolding degen.is_acc_run_def degen.is_acc_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. graph_defs.is_run (degeneralize_ext m) r' \<and> (\<exists>\<^sub>\<infinity>i. r' i \<in> bg_F (degeneralize_ext m))
[PROOF STEP]
by rule fact+
[PROOF STATE]
proof (state)
this:
b_graph.is_acc_run (degeneralize_ext m) r'
goal (1 subgoal):
1. \<lbrakk>\<And>r'. \<lbrakk>b_graph.is_acc_run (degeneralize_ext m) r'; r = fst \<circ> r'\<rbrakk> \<Longrightarrow> thesis; num_acc \<noteq> 0\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
b_graph.is_acc_run (degeneralize_ext m) r'
goal (1 subgoal):
1. thesis
[PROOF STEP]
by (auto intro: that)
[PROOF STATE]
proof (state)
this:
thesis
goal:
No subgoals!
[PROOF STEP]
qed |
[STATEMENT]
lemma try_gpv_Fail2 [simp]: "TRY gpv ELSE Fail = gpv"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. TRY gpv ELSE Fail = gpv
[PROOF STEP]
by(coinduction arbitrary: gpv rule: gpv.coinduct_strong)
(auto simp add: spmf_rel_map generat.rel_map intro!: rel_spmf_reflI generat.rel_refl) |
module Toolkit.Options.ArgParse.Parser.API
import Data.List
import Data.String
import Text.Token
import Text.Lexer
import Text.Parser
import Toolkit.Options.ArgParse.Lexer
import public Toolkit.Text.Parser.Support
%default total
namespace ArgParse
public export
Rule : Type -> Type
Rule = Rule Unit Token
public export
RuleEmpty : Type -> Type
RuleEmpty = RuleEmpty Unit Token
-- Some basic parsers used by all the intermediate forms
export
shortFlag : Rule String
shortFlag
= terminal "Expected Short Flag"
(\x => case x of
SFlag f => Just (substr 1 (length f) f)
_ => Nothing)
export
longFlag : Rule String
longFlag
= terminal "Expected long flag"
(\x => case x of
LFlag f => Just (substr 2 (length f) f)
_ => Nothing)
export
arg : Rule String
arg = terminal "Expected arg."
(\x => case x of
Arg s => Just (trim s)
_ => Nothing)
export
equals : Rule ()
equals = terminal "Expected equals"
(\x => case x of
Equals _ => Just ()
_ => Nothing)
export
quoted : Rule String
quoted = terminal "Expected quoted input"
(\x => case x of
Quoted s => Just $ rmQuotes s
_ => Nothing)
where
rmQuotes : String -> String
rmQuotes xs = pack $ filter (not . (==) '"') (unpack xs)
-- --------------------------------------------------------------------- [ EOF ]
|
{-# OPTIONS --profile=modules --profile=internal #-}
|
In which of the following orders would the phases of a formal review usually occur?
Find the minimum power required to maintain the flow of liquid in a pipe for a pressure drop of 100 kPa.
S elect the correct statement for 50% reaction stage in a steam turbine. |
// stdafx.h
// (c) 2008-2020, Charles Lechasseur
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
// Including this header allows us to suppress C++ Core Guideline warnings more easily
#include <CppCoreCheck\warnings.h>
// Disable C++ Core checks warnings in library headers since we don't control them
#pragma warning(push)
#pragma warning(disable: ALL_CPPCORECHECK_WARNINGS)
#ifndef STRICT
#define STRICT
#endif
#include "targetver.h"
#define _ATL_APARTMENT_THREADED
#define _ATL_NO_AUTOMATIC_NAMESPACE
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
//#define PCC_NO_CONTEXT_MENU_EXT2 // For testing purposes only
#include <atlbase.h>
#include <atlcom.h>
#include <atlctl.h>
#include <atlstr.h>
#include <shlobj.h>
#include <shobjidl.h>
#include <windows.h>
// Disable some warnings in GDI+ headers
#pragma warning( push )
#pragma warning( disable : 4458 )
#include <gdiplus.h>
#pragma warning( pop )
// Undef the Windows min and max macros, since they conflict with STL
// We can't define NOMINMAX because GDI actually needs those macros :(
#undef min
#undef max
#include <algorithm>
#include <cstdint>
#include <exception>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <vector>
#include <utility>
#include <assert.h>
#include <memory.h>
#include <resource.h>
#include <PathCopyCopyLocalization_en\rsrc\resource.h>
#include <gsl/gsl>
#include <coveo/linq.h>
#pragma warning(pop) // core checks in library headers
#include "PathCopyCopyPrivateTypes.h"
|
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
Require Import List.
Require Import Setoid.
Require Import BinPos.
Require Import BinList.
Require Import Znumtheory.
Require Export Morphisms Setoid Bool.
Require Import ZArith.
Open Scope Z_scope.
Require Import Algebra_syntax.
Require Export Ring2.
Require Import Ring2_polynom.
Require Import Ring2_initial.
Set Implicit Arguments.
(* Reification with Type Classes, inspired from B.Grégoire and A.Spiewack *)
Class is_in_list_at (R:Type) (t:R) (l:list R) (i:nat) := {}.
Instance Ifind0 (R:Type) (t:R) l
: is_in_list_at t (t::l) 0.
Instance IfindS (R:Type) (t2 t1:R) l i
`{is_in_list_at R t1 l i}
: is_in_list_at t1 (t2::l) (S i) | 1.
Class reifyPE (R:Type) (e:PExpr Z) (lvar:list R) (t:R) := {}.
Instance reify_zero (R:Type) (RR:Ring R) lvar
: reifyPE (PEc 0%Z) lvar ring0.
Instance reify_one (R:Type) (RR:Ring R) lvar
: reifyPE (PEc 1%Z) lvar ring1.
Instance reify_plus (R:Type) (RR:Ring R)
e1 lvar t1 e2 t2
`{reifyPE R e1 lvar t1}
`{reifyPE R e2 lvar t2}
: reifyPE (PEadd e1 e2) lvar (ring_plus t1 t2).
Instance reify_mult (R:Type) (RR:Ring R)
e1 lvar t1 e2 t2
`{reifyPE R e1 lvar t1}
`{reifyPE R e2 lvar t2}
: reifyPE (PEmul e1 e2) lvar (ring_mult t1 t2).
Instance reify_sub (R:Type) (RR:Ring R)
e1 lvar t1 e2 t2
`{reifyPE R e1 lvar t1}
`{reifyPE R e2 lvar t2}
: reifyPE (PEsub e1 e2) lvar (ring_sub t1 t2).
Instance reify_opp (R:Type) (RR:Ring R)
e1 lvar t1
`{reifyPE R e1 lvar t1}
: reifyPE (PEopp e1) lvar (ring_opp t1).
Instance reify_var (R:Type) t lvar i
`{is_in_list_at R t lvar i}
: reifyPE (PEX Z (P_of_succ_nat i)) lvar t
| 100.
Class reifyPElist (R:Type) (lexpr:list (PExpr Z)) (lvar:list R)
(lterm:list R) := {}.
Instance reifyPE_nil (R:Type) lvar
: @reifyPElist R nil lvar (@nil R).
Instance reifyPE_cons (R:Type) e1 lvar t1 lexpr2 lterm2
`{reifyPE R e1 lvar t1} `{reifyPElist R lexpr2 lvar lterm2}
: reifyPElist (e1::lexpr2) lvar (t1::lterm2).
Class is_closed_list T (l:list T) := {}.
Instance Iclosed_nil T
: is_closed_list (T:=T) nil.
Instance Iclosed_cons T t l
`{is_closed_list (T:=T) l}
: is_closed_list (T:=T) (t::l).
Definition list_reifyl (R:Type) lexpr lvar lterm
`{reifyPElist R lexpr lvar lterm}
`{is_closed_list (T:=R) lvar} := (lvar,lexpr).
Unset Implicit Arguments.
Instance multiplication_phi_ring{R:Type}{Rr:Ring R} : Multiplication :=
{multiplication x y := ring_mult (gen_phiZ Rr x) y}.
(*
Print HintDb typeclass_instances.
*)
(* Reification *)
Ltac lterm_goal g :=
match g with
ring_eq ?t1 ?t2 => constr:(t1::t2::nil)
| ring_eq ?t1 ?t2 -> ?g => let lvar :=
lterm_goal g in constr:(t1::t2::lvar)
end.
Ltac reify_goal lvar lexpr lterm:=
(* idtac lvar; idtac lexpr; idtac lterm;*)
match lexpr with
nil => idtac
| ?e::?lexpr1 =>
match lterm with
?t::?lterm1 => (* idtac "t="; idtac t;*)
let x := fresh "T" in
set (x:= t);
change x with
(@PEeval Z Zr _ _ (@gen_phiZ_morph _ _) N
(fun n:N => n) (@Ring_theory.pow_N _ ring1 ring_mult)
lvar e);
clear x;
reify_goal lvar lexpr1 lterm1
end
end.
Existing Instance gen_phiZ_morph.
Existing Instance Zr.
Lemma comm: forall (R:Type)(Rr:Ring R)(c : Z) (x : R),
x * [c] == [c] * x.
induction c. intros. ring_simpl. gen_ring_rewrite. simpl. intros.
ring_rewrite_rev same_gen.
induction p. simpl. gen_ring_rewrite. ring_rewrite IHp. rrefl.
simpl. gen_ring_rewrite. ring_rewrite IHp. rrefl.
simpl. gen_ring_rewrite.
simpl. intros. ring_rewrite_rev same_gen.
induction p. simpl. generalize IHp. clear IHp.
gen_ring_rewrite. intro IHp. ring_rewrite IHp. rrefl.
simpl. generalize IHp. clear IHp.
gen_ring_rewrite. intro IHp. ring_rewrite IHp. rrefl.
simpl. gen_ring_rewrite. Qed.
Lemma Zeqb_ok: forall x y : Z, Zeq_bool x y = true -> x == y.
intros x y H. rewrite (Zeq_bool_eq x y H). rrefl. Qed.
Ltac ring_gen :=
match goal with
|- ?g => let lterm := lterm_goal g in (* les variables *)
match eval red in (list_reifyl (lterm:=lterm)) with
| (?fv, ?lexpr) =>
(* idtac "variables:";idtac fv;
idtac "terms:"; idtac lterm;
idtac "reifications:"; idtac lexpr;
*)
reify_goal fv lexpr lterm;
match goal with
|- ?g =>
set_ring_notations;
apply (@ring_correct Z Zr _ _ (@gen_phiZ_morph _ _)
(@comm _ _) Zeq_bool Zeqb_ok N (fun n:N => n)
(@Ring_theory.pow_N _ 1 multiplication));
[apply mkpow_th; rrefl
|vm_compute; reflexivity]
end
end
end.
(* Pierre L: these tests should be done in a section, otherwise
global axioms are generated. Ideally such tests should go in
the test-suite directory *)
Section Tests.
Ltac ring2:=
unset_ring_notations; intros;
match goal with
|- (@ring_eq ?r ?rd _ _ ) =>
simpl; ring_gen
end.
Variable R: Type.
Variable Rr: Ring R.
Existing Instance Rr.
Goal forall x y z:R, x == x .
ring2.
Qed.
Goal forall x y z:R, x * y * z == x * (y * z).
ring2.
Qed.
Goal forall x y z:R, [3]* x *([2]* y * z) == [6] * (x * y) * z.
ring2.
Qed.
Goal forall x y z:R, 3 * x * (2 * y * z) == 6 * (x * y) * z.
ring2.
Qed.
(* Fails with Multiplication: A -> B -> C.
Goal forall x:R, 2%Z * (x * x) == 3%Z * x.
Admitted.
*)
End Tests. |
lemma clamp_in_interval[simp]: assumes "\<And>i. i \<in> Basis \<Longrightarrow> a \<bullet> i \<le> b \<bullet> i" shows "clamp a b x \<in> cbox a b" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.