text
stringlengths 0
3.34M
|
---|
[STATEMENT]
lemma fun_chain_at_top_at_top:
assumes "filterlim (f :: ('a::order) \<Rightarrow> 'a) at_top at_top"
shows "filterlim (f ^^ n) at_top at_top"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. filterlim (f ^^ n) at_top at_top
[PROOF STEP]
by (induction n) (auto intro: filterlim_ident filterlim_compose[OF assms]) |
(* Author: Tobias Nipkow *)
section \<open>Pairing Heap According to Okasaki\<close>
theory Pairing_Heap_List1
imports
"HOL-Library.Multiset"
"HOL-Library.Pattern_Aliases"
"HOL-Data_Structures.Priority_Queue_Specs"
begin
subsection \<open>Definitions\<close>
text
\<open>This implementation follows Okasaki \<^cite>\<open>"Okasaki"\<close>.
It satisfies the invariant that \<open>Empty\<close> only occurs
at the root of a pairing heap. The functional correctness proof does not
require the invariant but the amortized analysis (elsewhere) makes use of it.\<close>
datatype 'a heap = Empty | Hp 'a "'a heap list"
fun get_min :: "'a heap \<Rightarrow> 'a" where
"get_min (Hp x _) = x"
hide_const (open) insert
context includes pattern_aliases
begin
fun merge :: "('a::linorder) heap \<Rightarrow> 'a heap \<Rightarrow> 'a heap" where
"merge h Empty = h" |
"merge Empty h = h" |
"merge (Hp x hsx =: hx) (Hp y hsy =: hy) =
(if x < y then Hp x (hy # hsx) else Hp y (hx # hsy))"
end
fun insert :: "('a::linorder) \<Rightarrow> 'a heap \<Rightarrow> 'a heap" where
"insert x h = merge (Hp x []) h"
fun pass\<^sub>1 :: "('a::linorder) heap list \<Rightarrow> 'a heap list" where
"pass\<^sub>1 (h1#h2#hs) = merge h1 h2 # pass\<^sub>1 hs" |
"pass\<^sub>1 hs = hs"
fun pass\<^sub>2 :: "('a::linorder) heap list \<Rightarrow> 'a heap" where
"pass\<^sub>2 [] = Empty"
| "pass\<^sub>2 (h#hs) = merge h (pass\<^sub>2 hs)"
fun merge_pairs :: "('a::linorder) heap list \<Rightarrow> 'a heap" where
"merge_pairs [] = Empty"
| "merge_pairs [h] = h"
| "merge_pairs (h1 # h2 # hs) = merge (merge h1 h2) (merge_pairs hs)"
fun del_min :: "('a::linorder) heap \<Rightarrow> 'a heap" where
"del_min Empty = Empty"
| "del_min (Hp x hs) = pass\<^sub>2 (pass\<^sub>1 hs)"
subsection \<open>Correctness Proofs\<close>
text \<open>An optimization:\<close>
lemma pass12_merge_pairs: "pass\<^sub>2 (pass\<^sub>1 hs) = merge_pairs hs"
by (induction hs rule: merge_pairs.induct) (auto split: option.split)
declare pass12_merge_pairs[code_unfold]
subsubsection \<open>Invariants\<close>
fun mset_heap :: "'a heap \<Rightarrow>'a multiset" where
"mset_heap Empty = {#}" |
"mset_heap (Hp x hs) = {#x#} + sum_mset(mset(map mset_heap hs))"
fun pheap :: "('a :: linorder) heap \<Rightarrow> bool" where
"pheap Empty = True" |
"pheap (Hp x hs) = (\<forall>h \<in> set hs. (\<forall>y \<in># mset_heap h. x \<le> y) \<and> pheap h)"
lemma pheap_merge: "pheap h1 \<Longrightarrow> pheap h2 \<Longrightarrow> pheap (merge h1 h2)"
by (induction h1 h2 rule: merge.induct) fastforce+
lemma pheap_merge_pairs: "\<forall>h \<in> set hs. pheap h \<Longrightarrow> pheap (merge_pairs hs)"
by (induction hs rule: merge_pairs.induct)(auto simp: pheap_merge)
lemma pheap_insert: "pheap h \<Longrightarrow> pheap (insert x h)"
by (auto simp: pheap_merge)
(*
lemma pheap_pass1: "\<forall>h \<in> set hs. pheap h \<Longrightarrow> \<forall>h \<in> set (pass\<^sub>1 hs). pheap h"
by(induction hs rule: pass\<^sub>1.induct) (auto simp: pheap_merge)
lemma pheap_pass2: "\<forall>h \<in> set hs. pheap h \<Longrightarrow> pheap (pass\<^sub>2 hs)"
by (induction hs)(auto simp: pheap_merge)
*)
lemma pheap_del_min: "pheap h \<Longrightarrow> pheap (del_min h)"
by(cases h) (auto simp: pass12_merge_pairs pheap_merge_pairs)
subsubsection \<open>Functional Correctness\<close>
lemma mset_heap_empty_iff: "mset_heap h = {#} \<longleftrightarrow> h = Empty"
by (cases h) auto
lemma get_min_in: "h \<noteq> Empty \<Longrightarrow> get_min h \<in># mset_heap(h)"
by(induction rule: get_min.induct)(auto)
lemma get_min_min: "\<lbrakk> h \<noteq> Empty; pheap h; x \<in># mset_heap(h) \<rbrakk> \<Longrightarrow> get_min h \<le> x"
by(induction h rule: get_min.induct)(auto)
lemma get_min: "\<lbrakk> pheap h; h \<noteq> Empty \<rbrakk> \<Longrightarrow> get_min h = Min_mset (mset_heap h)"
by (metis Min_eqI finite_set_mset get_min_in get_min_min )
lemma mset_merge: "mset_heap (merge h1 h2) = mset_heap h1 + mset_heap h2"
by(induction h1 h2 rule: merge.induct)(auto simp: add_ac)
lemma mset_insert: "mset_heap (insert a h) = {#a#} + mset_heap h"
by(cases h) (auto simp add: mset_merge insert_def add_ac)
lemma mset_merge_pairs: "mset_heap (merge_pairs hs) = sum_mset(image_mset mset_heap(mset hs))"
by(induction hs rule: merge_pairs.induct)(auto simp: mset_merge)
lemma mset_del_min: "h \<noteq> Empty \<Longrightarrow>
mset_heap (del_min h) = mset_heap h - {#get_min h#}"
by(cases h) (auto simp: pass12_merge_pairs mset_merge_pairs)
text \<open>Last step: prove all axioms of the priority queue specification:\<close>
interpretation pairing: Priority_Queue_Merge
where empty = Empty and is_empty = "\<lambda>h. h = Empty"
and merge = merge and insert = insert
and del_min = del_min and get_min = get_min
and invar = pheap and mset = mset_heap
proof(standard, goal_cases)
case 1 show ?case by simp
next
case (2 q) show ?case by (cases q) auto
next
case 3 show ?case by(simp add: mset_insert mset_merge)
next
case 4 thus ?case by(simp add: mset_del_min mset_heap_empty_iff)
next
case 5 thus ?case using get_min mset_heap.simps(1) by blast
next
case 6 thus ?case by(simp)
next
case 7 thus ?case by(rule pheap_insert)
next
case 8 thus ?case by (simp add: pheap_del_min)
next
case 9 thus ?case by (simp add: mset_merge)
next
case 10 thus ?case by (simp add: pheap_merge)
qed
end
|
function imgOut = pyrBlend(img1, img2, weight)
%
%
% imgOut = pyrBlend(img1, img2, weight)
%
%
% Input:
% -img1: an image to be blended
% -img2: an image to be blended
% -weight: the weights for img1
%
% Output:
% -imgOut: the final blended image
%
% 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/>.
%
if(~isSameImage(img1, img2) || ~isSimilarImage(img1, weight))
error('pyrBlend: input images are different!');
end
col = size(img1, 3);
p1 = pyrImg3(img1, @pyrLapGen);
p2 = pyrImg3(img2, @pyrLapGen);
g1 = pyrGaussGen(weight);
g2 = pyrGaussGen(1 - weight);
imgOut = zeros(size(img1));
for i=1:col
tpg1 = pyrLst2OP(p1(i), g1, @pyrMul);
tpg2 = pyrLst2OP(p2(i), g2, @pyrMul);
tf = pyrLst2OP(tpg1, tpg2, @pyrAdd);
imgOut(:,:,i) = pyrVal(tf);
end
end |
PDF Kingdom Hearts HD 1.5 ReMIX Guide . Share Favorite . Introduction Characters. Sora. Sora is the main character, a 14 year old boy. As a teenager, he has his share of concerns, but he manages to keep an upbeat attitude. He may be simple-minded at times, but he has a strong sense of justice. Riku. Age 15. He may seem cool and collected for his age, but he is far from the quiet type. Always... I was so excited for this guide, being a special hardcover edition with coverage for both games included in KH 1.5. It is a decent guide for first-time players, but not long-time fans of the series who are hoping to achieve 100% completion.
Journal trophy progression. - Within the game if you press and scroll down to 'Journal' you can access Jiminy's Journal and check on a variety of different collectibles. free bible study guides pdf Download PDF Coliseum Tournaments [ edit ] After clearing the Olympus Coliseum area, Sora and company can periodically go back to test their skills in the games and earn fabulous prizes.
In this Kingdom Hearts HD 1.5 Remix Keyblades Weapons Guide, we have detailed everything you need to know about finding the weapons in the game.
Journal trophy progression. - Within the game if you press and scroll down to 'Journal' you can access Jiminy's Journal and check on a variety of different collectibles. |
(** * I2: Spis przydatnych taktyk *)
(** Stare powiedzenie głosi: nie wymyślaj koła na nowo. Aby uczynić zadość
duchom przodków, którzy je wymyślili (zarówno koło, jak i powiedzenie),
w niniejszym rozdziale zapoznamy się z różnymi przydatnymi taktykami,
które prędzej czy później i tak sami byśmy wymyślili, gdyby zaszła taka
potrzeba.
Aby jednak nie popaść w inny grzech i nie posługiwać się czarami, których
nie rozumiemy, część z poniżej omówionych taktyk zaimplementujemy jako
ćwiczenie.
Omówimy kolejno:
- taktykę [refine]
- drobne taktyki służące głównie do kontrolowania tego, co dzieje się
w kontekście
- "średnie" taktyki, wcielające w życie pewien konkretny sposób
rozumowania
- taktyki służące do rozumowania na temat relacji równoważności
- taktyki służące do przeprowadzania obliczeń
- procedury decyzyjne
- ogólne taktyki służące do automatyzacji *)
(** Uwaga: przykłady użycia taktyk, których reimplementacja będzie
ćwiczeniem, zostały połączone z testami w ćwiczeniach żeby nie pisać dwa
razy tego samego. *)
(** * [refine] — matka wszystkich taktyk *)
(** Fama głosi, że w zamierzchłych czasach, gdy nie było jeszcze taktyk,
a światem Coqa rządził Chaos (objawiający się dowodzeniem przez ręczne
wpisywanie termów), jeden z Coqowych bogów imieniem He-fait-le-stos, w
przebłysku kreatywnego geniuszu wymyślił dedukcję naturalną i stworzył
pierwszą taktykę, której nadał imię [refine]. Pomysł przyjał się i od
tej pory Coqowi bogowie poczęli używać jej do tworzenia coraz to innych
taktyk. Tak [refine] stała się matką wszystkich taktyk.
Oczywiście legenda ta jest nieprawdziwa — deduckcję naturalną wymyślił
Gerhard Gentzen, a podstawowe taktyki są zaimplementowane w Ocamlu. Nie
umniejsza to jednak mocy taktyki [refine]. Jej działanie podobne jest
do taktyki [exact], z tym że term będący jej argumentem może też zawierać
dziury [_]. Jeżeli naszym celem jest [G], to taktyka [refine g] rozwiązuje
cel, jeżeli [g] jest termem typu [G], i generuje taką ilość podcelów, ile
[g] zawiera dziur, albo zawodzi, jeżeli [g] nie jest typu [G].
Zobaczmy działanie taktyki [refine] na przykładach. *)
Example refine_0 : 42 = 42.
Proof.
refine eq_refl.
Qed.
(** W powyższym przykładzie używamy [refine] tak jak użylibyśmy [exact]a.
[eq_refl] jest typu [42 = 42], gdyż Coq domyśla się, że tak naprawdę
chodzi nam o [@eq_refl nat 42]. Ponieważ [eq_refl] zawiera 0 dziur,
[refine eq_refl] rozwiązuje cel i nie generuje podcelów. *)
Example refine_1 :
forall P Q : Prop, P /\ Q -> Q /\ P.
Proof.
refine (fun P Q : Prop => _).
refine (fun H => match H with | conj p q => _ end).
refine (conj _ _ ).
refine q.
refine p.
Restart.
intros P Q. intro H. destruct H as [p q]. split.
exact q.
exact p.
Qed.
(** W tym przykładzie chcemy pokazać przemienność konunkcji. Ponieważ nasz
cel jest kwantyfikacją uniwersalną, jego dowodem musi być jakaś funkcja
zależna. Funkcję tę konstruujemy taktyką [refine (fun P Q : Prop => _)].
Nie podajemy jednak ciała funkcji, zastępując je dzurą [_], bo chcemy
podać je później. W związku z tym nasz obecny cel zostaje rozwiązany, a
w zamian dostajemy nowy cel postaci [P /\ Q -> Q /\ P], gdyż takiego
typu jest ciało naszej funkcji. To jednak nie wszystko: w kontekście
pojawiają się [P Q : Prop]. Wynika to z tego, że [P] i [Q] mogą zostać
użyte w definicji ciała naszej funkcji.
Jako, że naszym celem jest implikacja, jej dowodem musi być funkcja.
Taktyka [refine (fun H => match H with | conj p q => _ end)] pozwala
nam tę funkcję skonstruować. Ciałem naszej funkcji jest dopasowanie
zawierające dziurę. Wypełnienie jej będzie naszym kolejnym celem. Przy
jego rozwiązywaniu będziemy mogli skorzystać z [H], [p] i [q]. Pierwsza
z tych hipotez pochodzi o wiązania [fun H => ...], zaś [p] i [q] znajdą
się w kontekście dzięki temu, że zostały związane podczas dopasowania
[conj p q].
Teraz naszym celem jest [Q /\ P]. Ponieważ dowody koniunkcji są postaci
[conj l r], gdzie [l] jest dowodem pierwszego członu, a [r] drugiego,
używamy taktyki [refine (conj _ _)], by osobno skonstruować oba człony.
Tym razem nasz proofterm zawiera dwie dziury, więc wygenerowane zostaną
dwa podcele. Obydwa zachodzą na mocy założenia, a rozwiązujemy je także
za pomocą [refine].
Powyższy przykład pokazuje, że [refine] potrafi zastąpić cała gamę
przeróżnych taktyk, które dotychczas uważaliśmy za podstawowe: [intros],
[intro], [destruct], [split] oraz [exact]. Określenie "matka wszystkich
taktyk" wydaje się całkiem uzasadnione. *)
(** **** Ćwiczenie (my_exact) *)
(** Napisz taktykę [my_exact], która działa tak, jak [exact]. Użyj taktyki
[refine]. *)
(* begin hide *)
Ltac my_exact t := refine t.
(* end hide *)
Example my_exact_0 :
forall P : Prop, P -> P.
Proof.
intros. my_exact H.
Qed.
(** **** Ćwiczenie (my_intro) *)
(** Zaimplementuj taktykę [my_intro1], która działa tak, jak [intro], czyli
próbuje wprowadzić do kontekstu zmienną o domyślnej nazwie. Zaimplementuj
też taktykę [my_intro2 x], która działa tak jak [intro x], czyli próbuje
wprowadzić do kontekstu zmienną o nazwie [x]. Użyj taktyki [refine].
Bonus: przeczytaj dokumentację na temat notacji dla taktyk (komenda
[Tactic Notation]) i napisz taktykę [my_intro], która działa tak jak
[my_intro1], gdy nie dostanie argumentu, a tak jak [my_intro2], gdy
dostanie argument. *)
(* begin hide *)
Ltac my_intro1 := refine (fun _ => _).
Ltac my_intro2 x := refine (fun x => _).
Tactic Notation "my_intro" := my_intro1.
Tactic Notation "my_intro" ident(x) := my_intro2 x.
(* end hide *)
Example my_intro_0 :
forall P : Prop, P -> P.
Proof.
my_intro1. my_intro2 H. my_exact H.
Restart.
my_intro. my_intro H. my_exact H.
Qed.
(** **** Ćwiczenie (my_apply) *)
(** Napisz taktykę [my_apply H], która działa tak jak [apply H]. Użyj taktyki
[refine]. *)
(* begin hide *)
Ltac my_apply H := refine (H _).
(* end hide *)
Example my_apply_0 :
forall P Q : Prop, P -> (P -> Q) -> Q.
Proof.
my_intro P. my_intro Q. my_intro p. my_intro H.
my_apply H. my_exact p.
Qed.
(** **** Ćwiczenie (taktyki dla konstruktorów 1) *)
(** Napisz taktyki:
- [my_split], która działa tak samo jak [split]
- [my_left] i [my_right], które działają tak jak [left] i [right]
- [my_exists], która działa tak samo jak [exists] *)
(** Użyj taktyki [refine]. *)
(* begin hide *)
Ltac my_split := refine (conj _ _).
Ltac my_left := refine (or_introl _).
Ltac my_right := refine (or_intror _).
Ltac my_exists n := refine (ex_intro _ n _).
(* end hide *)
Example my_split_0 :
forall P Q : Prop, P -> Q -> P /\ Q.
Proof.
my_intro P; my_intro Q; my_intro p; my_intro q.
my_split.
my_exact p.
my_exact q.
Qed.
Example my_left_right_0 :
forall P : Prop, P -> P \/ P.
Proof.
my_intro P; my_intro p. my_left. my_exact p.
Restart.
my_intro P; my_intro p. my_right. my_exact p.
Qed.
Example my_exists_0 :
exists n : nat, n = 42.
Proof.
my_exists 42. reflexivity.
Qed.
(** * Drobne taktyki *)
(** ** [clear] *)
Goal
forall x y : nat, x = y -> y = x -> False.
Proof.
intros. clear H H0.
Restart.
intros. Fail clear x. Fail clear wut.
Restart.
intros. clear dependent x.
Restart.
intros. clear.
Restart.
intros.
pose (z := 42).
clearbody z.
Abort.
(** [clear] to niesamowicie użyteczna taktyka, dzięki której możemy zrobić
porządek w kontekście. Można używać jej na nastepujące sposoby:
- [clear x] usuwa [x] z kontekstu. Jeżeli [x] nie ma w kontekście lub są
w nim jakieś rzeczy zależne od [x], taktyka zawodzi. Można usunąć wiele
rzeczy na raz: [clear x_1 ... x_N].
- [clear -x] usuwa z kontekstu wszystko poza [x].
- [clear dependent x] usuwa z kontekstu [x] i wszystkie rzeczy, które od
niego zależą. Taktyka ta zawodzi jedynie gdy [x] nie ma w kontekście.
- [clear] usuwa z kontekstu absolutnie wszystko. Serdecznie nie polecam.
- [clearbody x] usuwa definicję [x] (jeżeli [x] jakąś posiada). *)
(** **** Ćwiczenie (tru) *)
(** Napisz taktykę [tru], która czyści kontekst z dowodów na [True] oraz
potrafi udowodnić cel [True].
Dla przykładu, taktyka ta powinna przekształcać kontekst
[a, b, c : True, p : P |- _] w [p : P |- _]. *)
(* begin hide *)
Ltac tru := intros; repeat
match goal with
| H : True |- _ => clear H
end; trivial.
(* end hide *)
Section tru.
Example tru_0 :
forall P : Prop, True -> True -> True -> P.
Proof.
tru. (* Kontekst: [P : Prop |- P] *)
Abort.
Example tru_1 : True.
Proof. tru. Qed.
End tru.
(** **** Ćwiczenie (satans_neighbour_not_even) *)
Inductive even : nat -> Prop :=
| even0 : even 0
| evenSS : forall n : nat, even n -> even (S (S n)).
(** Napisz taktykę [even], która potrafi udowodnić poniższy cel. *)
(* begin hide *)
Ltac even := unfold not; intros; repeat
match goal with
| H : even _ |- _ => inversion H; subst; clear H
end.
(* end hide *)
Lemma satans_neighbour_not_even :
~ even 667.
(* begin hide *)
(* Proof. even. Qed. *)
Abort.
(* end hide *)
(** **** Ćwiczenie (my_destruct_and) *)
(** Napisz taktykę [my_destruct H p q], która działa jak [destruct H as [p q]],
gdzie [H] jest dowodem koniunkcji. Użyj taktyk [refine] i [clear].
Bonus 1: zaimplementuj taktykę [my_destruct_and H], która działa tak jak
[destruct H], gdy [H] jest dowodem koniunkcji.
Bonus 2: zastanów się, jak (albo czy) można zaimplementować taktykę
[destruct x], gdzie [x] jest dowolnego typu induktywnego. *)
(* begin hide *)
Ltac my_destruct_and_named H p q := refine (
match H with
| conj p q => _
end); clear H.
Ltac my_destruct_and_unnamed H :=
let p := fresh in let q := fresh in my_destruct_and_named H p q.
Tactic Notation "my_destruct_and" ident(H) ident(p) ident(q) :=
my_destruct_and_named H p q.
Tactic Notation "my_destruct_and" ident(H) :=
my_destruct_and_unnamed H.
(* end hide *)
Example my_destruct_and_0 :
forall P Q : Prop, P /\ Q -> P.
Proof.
my_intro P; my_intro Q; my_intro H.
my_destruct_and H p q. my_exact p.
Restart.
my_intro P; my_intro Q; my_intro H.
my_destruct_and H. my_exact H0.
Qed.
(** ** [fold] *)
(** [fold] to taktyka służąca do zwijania definicji. Jej działanie jest
odwrotne do działania taktyki [unfold]. Niestety, z nieznanych mi
bliżej powodów bardzo często jest ona nieskuteczna. *)
(** **** Ćwiczenie (my_fold) *)
(** Napisz taktykę [my_fold x], która działa tak jak [fold x], tj. zastępuje
we wszystkich miejscach w celu term powstały po rozwinięciu [x] przez [x].
Wskazówka: zapoznaj się z konstruktem [eval] — zajrzyj do 9 rozdziału
manuala. *)
(* begin hide *)
Ltac my_fold x :=
let body := eval unfold x in x in
match goal with
| |- context [body] => change body with x
end.
(* end hide *)
Example fold_0 :
forall n m : nat, n + m = m + n.
Proof.
intros. unfold plus. fold plus.
Restart.
intros. unfold plus. my_fold plus.
Abort.
(** ** [move] *)
Example move_0 :
forall P Q R S T : Prop, P /\ Q /\ R /\ S /\ T -> T.
Proof.
destruct 1 as [p [q [r [s t]]]].
move p after t.
move p before s.
move p at top.
move p at bottom.
Abort.
(** [move] to taktyka służąca do zmieniania kolejności obiektów w kontekście.
Jej działanie jest tak ewidentnie oczywiste, ż nie ma zbytniego sensu,
aby je opisywać. *)
(** **** Ćwiczenie *)
(** Przeczytaj dokładny opis działania taktyki [move] w manualu. *)
(** ** [pose] i [remember] *)
Goal 2 + 2 = 4.
Proof.
intros.
pose (a := 2 + 2).
remember (2 + 2) as b.
Abort.
(** Taktyka [pose (x := t)] dodaje do kontekstu zmienną [x] (pod warunkiem,
że nazwa ta nie jest zajęta), która zostaje zdefiniowana za pomocą termu
[t].
Taktyka [remember t as x] zastępuje wszystkie wystąpienia termu [t]
w kontekście zmienną [x] (pod warunkiem, że nazwa ta nie jest zajęta) i
dodaje do kontekstu równanie postaci [x = t].
W powyższym przykładzie działają one następująco: [pose (a := 2 + 2)]
dodaje do kontekstu wiązanie [a := 2 + 2], zaś [remember (2 + 2) as b]
dodaje do kontekstu równanie [Heqb : b = 2 + 2] i zastępuje przez [b]
wszystkie wystąpienia [2 + 2] — także to w definicji [a].
Taktyki te przydają się w tak wielu różnych sytuacjach, że nie ma co
próbować ich tu wymieniać. Użyjesz ich jeszcze nie raz. *)
(** **** Ćwiczenie (set) *)
(** Taktyki te są jedynie wariantami bardziej ogólnej taktyki [set].
Przeczytaj jej dokumentację w manualu. *)
(** ** [rename] *)
Goal forall P : Prop, P -> P.
Proof.
intros. rename H into wut.
Abort.
(** [rename x into y] zmienia nazwę [x] na [y] lub zawodzi, gdy [x] nie ma
w kontekście albo nazwa [y] jest już zajęta *)
(** **** Ćwiczenie (satans_neighbour_not_even') *)
(** Napisz taktykę [even'], która potrafi udowodnić poniższy cel. Nie używaj
[match]a, a jedynie kombinatora [repeat]. *)
Lemma satans_neighbour_not_even' : ~ even 667.
(* begin hide *)
(* Proof.
intro.
Time repeat (inversion H; clear H H0; rename H1 into H; try (clear n0)).
Qed. *)
Abort.
(* end hide *)
(** ** [admit] *)
Module admit.
Lemma forgery :
forall P Q : Prop, P -> Q /\ P.
Proof.
intros. split.
admit.
assumption.
Admitted.
Print forgery.
(* ===> *** [[ forgery : forall P : Prop, P -> ~ P /\ P ]] *)
End admit.
(** [admit] to taktyka-oszustwo, która rozwiązuje dowolny cel. Nie jest ona
rzecz jasna wszechwiedząca i przez to rozwiązanego za jej pomocą celu
nie można zapisać za pomocą komend [Qed] ani [Defined], a jedynie za
pomocą komendy [Admitted], która oszukańczo udowodnione twierdzenie
przekształca w aksjomat.
W CoqIDE oszustwo jest dobrze widoczne, gdyż zarówno taktyka [admit]
jak i komenda [Admitted] podświetlają się na żółto, a nie na zielono,
tak jak prawdziwe dowody. Wyświetlenie [Print]em dowodu zakończonego
komendą [Admitted] również pokazuje, że ma on status aksjomatu.
Na koniec zauważmy, że komendy [Admitted] możemy użyć również bez
wczesniejszego użycia taktyki [admit]. Różnica między tymi dwoma bytami
jest taka, że taktyka [admit] służy do "udowodnienia" pojedynczego celu,
a komenda [Admitted] — całego twierdzenia. *)
(** * Średnie taktyki *)
(** ** [case_eq] *)
(** [case_eq] to taktyka podobna do taktyki [destruct], ale nieco mądrzejsza,
gdyż nie zdarza jej się "zapominać", jaka była struktura rozbitego przez
nią termu. *)
Goal
forall n : nat, n + n = 42.
Proof.
intros. destruct (n + n).
Restart.
intros. case_eq (n + n); intro.
Abort.
(** Różnice między [destruct] i [case_eq] dobrze ilustruje powyższy przykład.
[destruct] nadaje się jedynie do rozbijania termów, które są zmiennymi.
Jeżeli rozbijemy coś, co nie jest zmienną (np. term [n + n]), to utracimy
część informacji na jego temat. [case_eq] potrafi rozbijać dowolne termy,
gdyż poza samym rozbiciem dodaje też do celu dodatkową hipotezę, która
zawiera równanie "pamiętające" informacje o rozbitym termie, o których
zwykły [destruct] zapomina. *)
(** **** Ćwiczenie (my_case_eq) *)
(** Napisz taktykę [my_case_eq t Heq], która działa tak jak [case_eq t], ale
nie dodaje równania jako hipotezę na początku celu, tylko bezpośrednio
do kontekstu i nazywa je [Heq]. Użyj taktyk [remember] oraz [destruct]. *)
(* begin hide *)
Ltac my_case_eq t Heq :=
let x := fresh "x" in remember t as x;
match goal with
| H : x = t |- _ => symmetry in H; rename H into Heq
end;
destruct x.
(* end hide *)
Goal
forall n : nat, n + n = 42.
Proof.
intros. destruct (n + n).
Restart.
intros. case_eq (n + n); intro.
Restart.
intros. my_case_eq (n + n) H.
Abort.
(** ** [contradiction] *)
(** [contradiction] to taktyka, która wprowadza do kontekstu wszystko co się
da, a potem próbuje znaleźć sprzeczność. Potrafi rozpoznawać hipotezy
takie jak [False], [x <> x], [~ True]. Potrafi też znaleźć dwie hipotezy,
które są ze sobą ewidentnie sprzeczne, np. [P] oraz [~ P]. Nie potrafi
jednak wykrywać lepiej ukrytych sprzeczności, np. nie jest w stanie
odróżnić [true] od [false]. *)
(** **** Ćwiczenie (my_contradiction) *)
(** Napisz taktykę [my_contradiction], która działa tak jak standardowa
taktyka [contradiction], a do tego jest w stanie udowodnić dowolny
cel, jeżeli w kontekście jest hipoteza postaci [true = false] lub
[false = true]. *)
(* begin hide *)
Ltac my_contradiction := intros;
match goal with
| H : False |- _ => destruct H
| H : ~ True |- _ => destruct (H I)
| H : ?x <> ?x |- _ => destruct (H eq_refl)
| H : ~ ?P, H' : ?P |- _ => destruct (H H')
| H : true = false |- _ => inversion H
| H : false = true |- _ => inversion H
end.
(* end hide *)
Section my_contradiction.
Example my_contradiction_0 :
forall P : Prop, False -> P.
Proof.
contradiction.
Restart.
my_contradiction.
Qed.
Example my_contradiction_1 :
forall P : Prop, ~ True -> P.
Proof.
contradiction.
Restart.
my_contradiction.
Qed.
Example my_contradiction_2 :
forall (P : Prop) (n : nat), n <> n -> P.
Proof.
contradiction.
Restart.
my_contradiction.
Qed.
Example my_contradiction_3 :
forall P Q : Prop, P -> ~ P -> Q.
Proof.
contradiction.
Restart.
my_contradiction.
Qed.
Example my_contradiction_4 :
forall P : Prop, true = false -> P.
Proof.
try contradiction.
Restart.
my_contradiction.
Qed.
Example my_contradiction_5 :
forall P : Prop, false = true -> P.
Proof.
try contradiction.
Restart.
my_contradiction.
Qed.
End my_contradiction.
(** **** Ćwiczenie (taktyki dla sprzeczności) *)
(** Innymi taktykami, które mogą przydać się przy rozumowaniach przez
sprowadzenie do sprzeczności, są [absurd], [contradict] i [exfalso].
Przeczytaj ich opisy w manualu i zbadaj ich działanie. *)
(** ** [constructor] *)
Example constructor_0 :
forall P Q : Prop, P -> Q \/ P.
Proof.
intros. constructor 2. assumption.
Restart.
intros. constructor.
Restart.
intros. constructor; assumption.
Qed.
(** [constructor] to taktyka ułatwiająca aplikowanie konstruktorów typów
induktywnych. Jeżeli aktualnym celem jest [T], to taktyka [constructor i]
jest równoważna wywołaniu jego i-tego konstruktora, gdzie porządek
konstruktorów jest taki jak w definicji typu. *)
Print or.
(* ===> Inductive or (A B : Prop) : Prop :=
or_introl : A -> A \/ B | or_intror : B -> A \/ B *)
(** W powyższym przykładzie [constructor 2] działa tak jak [apply or_intror]
(czyli tak samo jak taktyka [right]), gdyż w definicji spójnika [or]
konstruktor [or_intror] występuje jako drugi (licząc od góry).
Użycie taktyki [constructor] bez liczby oznacza zaaplikowanie pierwszego
konstruktora, który pasuje do celu, przy czym taktyka ta może wyzwalać
backtracking. W drugim przykładzie powyżej [constructor] działa jak
[apply or_intro] (czyli jak taktyka [left]), gdyż zaaplikowanie tego
konstruktora nie zawodzi.
W trzecim przykładzie [constructor; assumption] działa tak: najpierw
aplikowany jest konstruktor [or_introl], ale wtedy [assumption] zawodzi,
więc następuje nawrót i aplikowany jest konstruktor [or_intror], a wtedy
[assumption] rozwiązuje cel. *)
(** **** Ćwiczenie (taktyki dla konstruktorów 2) *)
(** Jaki jest związek taktyki [constructor] z taktykami [split], [left],
[right] i [exists]? *)
(** ** [decompose] *)
Example decompose_0 :
forall P Q R S : nat -> Prop,
(exists n : nat, P n) /\ (exists n : nat, Q n) /\
(exists n : nat, R n) /\ (exists n : nat, S n) ->
exists n : nat, P n \/ Q n \/ R n \/ S n.
Proof.
intros. decompose [and ex] H. clear H. exists x. left. assumption.
Qed.
(** [decompose] to bardzo użyteczna taktyka, która potrafi za jednym zamachem
rozbić bardzo skomplikowane hipotezy. [decompose [t_1 ... t_n] H] rozbija
rekurencyjnie hipotezę [H] tak długo, jak jej typem jest jeden z typów
[t_i]. W powyższym przykładzie [decompose [and ex] H] najpierw rozbija [H],
gdyż jest ona koniunkcją, a następnie rozbija powstałe z niej hipotezy,
gdyż są one kwantyfikacjami egzystencjalnymi ("exists" jest notacją dla
[ex]). [decompose] nie usuwa z kontekstu hipotezy, na której działa, więc
często następuje po niej taktyka [clear]. *)
(** ** [intros] *)
(** Dotychczas używałeś taktyk [intro] i [intros] jedynie z nazwami lub
wzorcami do rozbijania elementów typów induktywnych. Taktyki te potrafią
jednak dużo więcej. *)
Example intros_0 :
forall P Q R S : Prop, P /\ Q /\ R -> S.
Proof.
intros P Q R S [p [q r]].
Restart.
intros ? ?P Q R. intros (p, (p0, q)).
Restart.
intros *.
Restart.
intros A B **.
Restart.
intros * _.
Restart.
Fail intros _.
Abort.
(** Pierwszy przykład to standardowe użycie [intros] — wprowadzamy cztery
zmienne, która nazywamy kolejno [P], [Q], [R] i [S], po czym wprowadzamy
bezimienną hipotezę typu [P /\ Q /\ R], która natychmiast rozbijamy za
pomocą wzorca [p [q r]].
W kolejnym przykładzie mamy już nowości: wzorzec [?] służy do nadania
zmiennej domyślnej nazwy. W naszym przypadku wprowadzone do kontekstu
zdanie zostaje nazwane [P], gdyż taką nazwę nosi w kwantyfikatorze,
gdy jest jeszcze w celu.
Wzorzec [?P] służy do nadania zmiennej domyślnej nazwy zaczynając się
od tego, co następuje po znaku [?]. W naszym przypadku do konteksu
wprowadzona zostaje zmienna [P0], gdyż żądamy nazwy zaczynającej się
od "P", ale samo "P" jest już zajęte. Widzimy też wzorzec [(p, (p0, q))],
który służy do rozbicia hipotezy. Wzorce tego rodzaju działają tak samo
jak wzorce w kwadratowych nawiasach, ale możemy używać ich tylko na
elementach typu induktywnego z jednym konstruktorem.
Wzorzec [*] wprowadza do kontekstu wszystkie zmienne kwantyfikowane
uniwersalnie i zatrzymuje sie na pierwszej nie-zależnej hipotezie. W
naszym przykładzie uniwersalnie kwantyfikowane są [P], [Q], [R] i [S],
więc zostają wprowadzane, ale [P /\ Q /\ R] nie jest już kwantyfikowane
uniwersalnie — jest przesłanką implikacji — więc nie zostaje wprowadzone.
Wzorzec [**] wprowadza do kontekstu wszystko. Wobec tego [intros **] jest
synonimem [intros]. Mimo tego nie jest on bezużyteczny — możemy użyć go
po innych wzorcach, kiedy nie chcemy już więcej nazywać/rozbijać naszych
zmiennych. Wtedy dużo szybciej napisać [**] niż [; intros]. W naszym
przypadku chcemy nazwać jedynie pierwsze dwie zmienne, a resztę wrzucamy
do kontekstu jak leci.
Wzorzec [_] pozwala pozbyć się zmiennej lub hipotezy. Taktyka [intros _]
jest wobec tego równoważna [intro H; clear H] (przy założeniu, że [H]
jest wolne), ale dużo bardziej zwięzła w zapisie. Nie możemy jednak
usunąć zmiennych lub hipotez, od których zależą inne zmienne lub hipotezy.
W naszym przedostatnim przykładzie bez problemu usuwamy hipotezę [P /\
Q /\ R], gdyż żaden term od niej nie zależy. Jednak w ostatnim przykładzie
nie możemy usunąć [P], gdyż zależy od niego hipoteza [P /\ Q /\ R]. *)
Example intros_1 :
forall P0 P1 P2 P3 P4 P5 : Prop,
P0 /\ P1 /\ P2 /\ P3 /\ P4 /\ P5 -> P3.
Proof.
intros * [p0 [p1 [p2 [p3 [p4 p5]]]]].
Restart.
intros * (p0 & p1 & p2 & p3 & p4 & p5).
Abort.
(** Wzorce postaci [(p_1 & ... & p_n)] pozwalają rozbijać termy zagnieżdżonych
typów induktywnych. Jak widać na przykładzie, im bardziej zagnieżdżony
jest typ, tym bardziej opłaca się użyć tego rodzaju wzorca. *)
Example intros_2 :
forall x y : nat, x = y -> y = x.
Proof.
intros * ->.
Restart.
intros * <-.
Abort.
(** Wzorców [->] oraz [<-] możemy użyć, gdy chcemy wprowadzić do kontekstu
równanie, przepisać je i natychmiast się go pozbyć. Wobec tego taktyka
[intros ->] jest równoważna czemuś w stylu [intro H; rewrite H in *;
clear H] (oczywiście pod warunkiem, że nazwa [H] nie jest zajęta). *)
Example intros_3 :
forall a b c d : nat, (a, b) = (c, d) -> a = c.
Proof.
Fail intros * [p1 p2].
Restart.
intros * [= p1 p2].
Abort.
(** Wzorzec postaci [= p_1 ... p_n] pozwala rozbić równanie między parami
(i nie tylko) na składowe. W naszym przypadu mamy równanie [(a, b) =
(c, d)] — zauważmy, że nie jest ono koniunkcją dwóch równości [a = c]
oraz [b = d], co jasno widać na przykładzie, ale można z niego ową
koniunkjcę wywnioskować. Taki właśnie efekt ma wzorzec [= p1 p2] —
dodaje on nam do kontekstu hipotezy [p1 : a = c] oraz [p2 : b = d]. *)
Example intros_4 :
forall P Q R : Prop, (P -> Q) -> (Q -> R) -> P -> R.
Proof.
intros until 2. intro p. apply H in p. apply H0 in p.
Restart.
intros until 2. intros p %H %H0.
Abort.
(** Taktyka [intros until x] wprowadza do kontekstu wszystkie zmienne jak
leci dopóki nie natknie się na taką, która nazywa się "x". Taktyka
[intros until n], gdzie [n] jest liczbą, wprowadza do kontekstu wszyskto
jak leci aż do n-tej nie-zależnej hipotezy (tj. przesłanki implikacji).
W naszym przykładzie mamy 3 przesłanki implikacji: [(P -> Q)], [(Q -> R)]
i [P], więc taktyka [intros until 2] wprowadza do kontekstu dwie pierwsze
z nich oraz wszystko, co jest poprzedza.
Wzorzec [x %H_1 ... %H_n] wprowadza do kontekstu zmienną [x], a następnie
aplikuje do niej po kolei hipotezy [H_1], ..., [H_n]. Taki sam efekt można
osiągnąć ręcznie za pomocą taktyki [intro x; apply H_1 in x; ... apply H_n
in x]. *)
(** **** Ćwiczenie (intros) *)
(** Taktyka [intros] ma jeszcze trochę różnych wariantów. Poczytaj o nich
w manualu. *)
(** ** [fix] *)
(** [fix] to taktyka służąca do dowodzenia bezpośrednio przez rekursję. W
związku z tym nadeszła dobra pora, żeby pokazać wszystkie możliwe sposoby
na użycie rekursji w Coqu. Żeby dużo nie pisać, przyjrzyjmy się przykładom:
zdefiniujemy/udowodnimy regułę indukcyjną dla liczb naturalnych, którą
powinieneś znać jak własną kieszeń (a jeżeli nie, to marsz robić zadania
z liczb naturalnych!). *)
Definition nat_ind_fix_term
(P : nat -> Prop) (H0 : P 0)
(HS : forall n : nat, P n -> P (S n))
: forall n : nat, P n :=
fix f (n : nat) : P n :=
match n with
| 0 => H0
| S n' => HS n' (f n')
end.
(** Pierwszy, najbardziej prymitywny sposób to użycie konstruktu [fix]. [fix]
to podstawowy budulec Coqowej rekursji, ale ma tę wadę, że trzeba się
trochę napisać: w powyższym przykładzie najpierw piszemy [forall n : nat,
P n], a następnie powtarzamy niemal to samo, pisząc
[fix f (n : nat) : P n]. *)
Fixpoint nat_ind_Fixpoint_term
(P : nat -> Prop) (H0 : P 0)
(HS : forall n : nat, P n -> P (S n))
(n : nat) : P n :=
match n with
| 0 => H0
| S n' => HS n' (nat_ind_Fixpoint_term P H0 HS n')
end.
(** Rozwiązaniem powyższej drobnej niedogodności jest komenda [Fixpoint],
która jest skrótem dla [fix]. Oszczędza nam ona pisania dwa razy tego
samego, dzięki czemu definicja jest o linijkę krótsza. *)
Fixpoint nat_ind_Fixpoint_tac
(P : nat -> Prop) (H0 : P 0)
(HS : forall n : nat, P n -> P (S n))
(n : nat) : P n.
Proof.
apply nat_ind_Fixpoint_tac; assumption.
Fail Guarded.
(* ===> Długi komunikat o błędzie. *)
Show Proof.
(* ===> (fix nat_ind_Fixpoint_tac
(P : nat -> Prop) (H0 : P 0)
(HS : forall n : nat, P n -> P (S n))
(n : nat) {struct n} : P n :=
nat_ind_Fixpoint_tac P H0 HS n) *)
Restart.
destruct n as [| n'].
apply H0.
apply HS. apply nat_ind_Fixpoint_tac; assumption.
Guarded.
(* ===> The condition holds up to here *)
Defined.
(** W trzecim podejściu również używamy komendy [Fixpoint], ale tym razem,
zamiast ręcznie wpisywać term, definiujemy naszą regułę za pomocą taktyk.
Sposób ten jest prawie zawsze (dużo) dłuższy niż poprzedni, ale jego
zaletą jest to, że przy skomplikowanych celach jest dużo ławiejszy do
ogarnięcia dla człowieka.
Korzystając z okazji rzućmy okiem na komendę [Guarded]. Jest ona przydatna
gdy, tak jak wyżej, dowodzimy lub definiujemy bezpośrednio przez rekursję.
Sprawdza ona, czy wszystkie dotychczasowe wywołania rekurencyjne odbyły
się na strukturalnie mniejszych podtermach. Jeżeli nie, wyświetla ona
wiadomość, która informuje nas, gdzie jest błąd. Niestety wiadomości te
nie zawsze są czytelne.
Tak właśnie jest, gdy w powyższym przykładzie używamy jej po raz pierwszy.
Na szczęście ratuje nas komenda [Show Proof], która pokazuje, jak wygląda
term, która póki co wygenerowały taktyki. Pokazuje on nam term postaci
[nat_ind_Fixpoint_tac P H0 HS n := nat_ind_Fixpoint_tac P H0 HS n], który
próbuje wywołać się rekurencyjnie na tym samym argumencie, na którym sam
został wywołany. Nie jest więc legalny.
Jeżeli z wywołaniami rekurencyjnymi jest wszystko ok, to komenda [Guarded]
wyświetla przyjazny komunikat. Tak właśnie jest, gdy używamy jej po raz
drugi — tym razem wywołanie rekurencyjne odbywa się na [n'], które jest
podtermem [n]. *)
Definition nat_ind_fix_tac :
forall (P : nat -> Prop) (H0 : P 0)
(HS : forall n : nat, P n -> P (S n)) (n : nat), P n.
Proof.
Show Proof.
(* ===> ?Goal *)
fix IH 4.
Show Proof.
(* ===> (fix nat_ind_fix_tac
(P : nat -> Prop) (H0 : P 0)
(HS : forall n : nat, P n -> P (S n))
(n : nat) {struct n} : P n := ... *)
destruct n as [| n'].
apply H0.
apply HS. apply IH; assumption.
Defined.
(** Taktyki [fix] możemy użyć w dowolnym momencie, aby rozpocząć dowodzenie/
definiowanie bezpośrednio przez rekursję. Jej argumentami są nazwa, którą
chcemy nadać hipotezie indukcyjnej oraz numer argument głównego. W
powyższym przykładzie chcemy robić rekursję po [n], który jest czwarty
z kolei (po [P], [H0] i [HS]).
Komenda [Show Proof] pozwala nam odkryć, że użycie taktyki [fix] w
trybie dowodzenia odpowiada po prostu użyciu konstruktu [fix] lub
komendy [Fixpoint].
Taktyka [fix] jest bardzo prymitywna i prawie nigdy nie jest używana,
tak samo jak konstrukt [fix] (najbardziej poręczne są sposoby, które
widzieliśmy w przykladach 2 i 3), ale była dobrym pretekstem, żeby
omówić wszystkie sposoby użycia rekursji w jednym miejscu. *)
(** ** [functional induction] i [functional inversion] *)
(** Taktyki [functional induction] i [functional inversion] są związane z
pojęciem indukcji funkcyjnej. Dość szczegółowy opis tej pierwszej jest w
#<a class='link'
href='https://wkolowski.github.io/Seminar-Program-certification-in-Coq/##lab15'>
moich notatkach na seminarium.
</a>#
Drugą z nich póki co pominiemy. Kiedyś z pewnością napiszę coś więcej
o indukcji funkcyjnej lub chociaż przetłumaczę zalinkowane notatki na
polski. *)
(** ** [generalize dependent] *)
(** [generalize dependent] to taktyka będąca przeciwieństwem [intro] — dzięki
niej możemy przerzucić rzeczy znajdujące się w kontekście z powrotem do
kontekstu. Nieformalnie odpowiada ona sposobowi rozumowania: aby pokazać,
że cel zachodzi dla pewnego konkretnego [x], wystarczy czy pokazać, że
zachodzi dla dowolnego [x].
W rozumowaniu tym z twierdzenia bardziej ogólnego wyciągamy wniosek, że
zachodzi twierdzenie bardziej szczegółowe. Nazwa [generalize] bierze się
stąd, że w dedukcji naturalnej nasze rozumowania przeprowadzamy "od tyłu".
Człon "dependent" bierze się stąd, że żeby zgeneralizować [x], musimy
najpierw zgeneralizować wszystkie obiekty, które są od niego zależne. Na
szczęście taktyka [generalize dependent] robi to za nas. *)
Example generalize_dependent_0 :
forall n m : nat, n = m -> m = n.
Proof.
intros. generalize dependent n.
Abort.
(** Użycie [intros] wprowadza do kontekstu [n], [m] i [H]. [generalize
dependent n] przenosi [n] z powrotem do celu, ale wymaga to, aby do
celu przenieść również [H], gdyż typ [H], czyli [n = m], zależy od [n]. *)
(** **** Ćwiczenie (generalize i revert) *)
(** [generalize dependent] jest wariantem taktyki [generalize]. Taktyką o
niemal identycznym działaniu jest [revert dependent], wariant taktyki
[revert]. Przeczytaj dokumentację [generalize] i [revert] w manualu i
sprawdź, jak działają. *)
(** **** Ćwiczenie (my_rec) *)
(** Zaimplementuj taktykę [rec x], która będzie pomagała przy dowodzeniu
bezpośrednio przez rekursję po [x]. Taktyka [rec x] ma działać jak
[fix IH n; destruct x], gdzie [n] to pozycja argumentu [x] w celu. Twoja
taktyka powinna działać tak, żeby poniższy dowód zadziałał bez potrzeby
wprowadzania modyfikacji.
Wskazówka: połącz taktyki [fix], [intros], [generalize dependent] i
[destruct]. *)
(* begin hide *)
Ltac rec x :=
intros until x; generalize dependent x; fix IH 1; destruct x.
(* end hide *)
Lemma add_comm_rec :
forall n : nat, n + 1 = S n.
Proof.
rec n.
reflexivity.
cbn. f_equal. rewrite IH. reflexivity.
Qed.
(** * Taktyki dla równości i równoważności *)
(** ** [reflexivity], [symmetry] i [transitivity] *)
Require Import Arith.
Example reflexivity_0 :
forall n : nat, n <= n.
Proof. reflexivity. Qed.
(** Znasz już taktykę [reflexivity]. Mogłoby się wydawać, że służy ona do
udowadniania celów postaci [x = x] i jest w zasadzie równoważna taktyce
[apply eq_refl], ale nie jest tak. Taktyka [reflexivity] potrafi rozwiązać
każdy cel postaci [R x y], gdzie [R] jest relacją zwrotną, a [x] i [y] są
konwertowalne (oczywiście pod warunkiem, że udowodnimy wcześniej, że [R]
faktycznie jest zwrotna; w powyższym przykładzie odpowiedni fakt został
zaimportowany z modułu [Arith]).
Żeby zilustrować ten fakt, zdefiniujmy nową relację zwrotną i zobaczmy,
jak użyć taktyki [reflexivity] do radzenia sobie z nią. *)
Definition eq_ext {A B : Type} (f g : A -> B) : Prop :=
forall x : A, f x = g x.
(** W tym celu definiujemy relację [eq_ext], która głosi, że funkcja
[f : A -> B] jest w relacji z funkcją [g : A -> B], jeżeli [f x]
jest równe [g x] dla dowolnego [x : A]. *)
Require Import RelationClasses.
(** Moduł [RelationClasses] zawiera definicję zwrotności [Reflexive], z której
korzysta taktyka [reflexivity]. Jeżeli udowodnimy odpowiednie twierdzenie,
będziemy mogli używać taktyki [reflexivity] z relacją [eq_ext]. *)
#[export]
Instance Reflexive_eq_ext :
forall A B : Type, Reflexive (@eq_ext A B).
Proof.
unfold Reflexive, eq_ext. intros A B f x. reflexivity.
Defined.
(** A oto i rzeczone twierdzenie oraz jego dowód. Zauważmy, że taktyki
[reflexivity] nie używamy tutaj z relacją [eq_ext], a z relacją [=],
gdyż używamy jej na celu postaci [f x = f x].
Uwaga: żeby taktyka [reflexivity] "widziała" ten dowód, musimy skorzystać
ze słowa kluczowego [Instance] zamiast z [Lemma]. *)
Example reflexivity_1 :
eq_ext (fun _ : nat => 42) (fun _ : nat => 21 + 21).
Proof. reflexivity. Defined.
(** Voilà ! Od teraz możemy używać taktyki [reflexivity] z relacją [eq_ext].
Są jeszcze dwie taktyki, które czasem przydają się przy dowodzeniu
równości (oraz równoważności). *)
Example symmetry_transitivity_0 :
forall (A : Type) (x y z : nat), x = y -> y = z -> z = x.
Proof.
intros. symmetry. transitivity y.
assumption.
assumption.
Qed.
(** Mogłoby się wydawać, że taktyka [symmetry] zamienia cel postaci [x = y]
na [y = x], zaś taktyka [transitivity y] rozwiązuje cel postaci [x = z]
i generuje w zamian dwa cele postaci [x = y] i [y = z]. Rzeczywistość
jest jednak bardziej hojna: podobnie jak w przypadku [reflexivity],
taktyki te działają z dowolnymi relacjami symetrycznymi i przechodnimi. *)
#[export]
Instance Symmetric_eq_ext :
forall A B : Type, Symmetric (@eq_ext A B).
Proof.
unfold Symmetric, eq_ext. intros A B f g H x. symmetry. apply H.
Defined.
#[export]
Instance Transitive_eq_ext :
forall A B : Type, Transitive (@eq_ext A B).
Proof.
unfold Transitive, eq_ext. intros A B f g h H H' x.
transitivity (g x); [apply H | apply H'].
Defined.
(** Użycie w dowodach taktyk [symmetry] i [transitivity] jest legalne, gdyż
nie używamy ich z relacją [eq_ext], a z relacją [=]. *)
Example symmetry_transitivity_1 :
forall (A B : Type) (f g h : A -> B),
eq_ext f g -> eq_ext g h -> eq_ext h f.
Proof.
intros. symmetry. transitivity g.
assumption.
assumption.
Qed.
(** Dzięki powyższym twierdzeniom możemy teraz posługiwać się taktykami
[symmetry] i [transitivity] dowodząc faktów na temat relacji [eq_ext].
To jednak wciąż nie wyczerpuje naszego arsenału taktyk do radzenia sobie
z relacjami równoważności. *)
(** ** [f_equal] *)
Check f_equal.
(* ===> f_equal : forall (A B : Type) (f : A -> B) (x y : A),
x = y -> f x = f y *)
(** [f_equal] to jedna z podstawowych właściwości relacji [eq], która głosi,
że wszystkie funkcje zachowują równość. Innymi słowy: aby pokazać, że
wartości zwracane przez funkcję są równe, wystarczy pokazać, że argumenty
są równe. Ten sposób rozumowania, choć nie jest ani jedyny, ani skuteczny
na wszystkie cele postaci [f x = f y], jest wystarczająco częsty, aby mieć
swoją własną taktykę, którą zresztą powinieneś już dobrze znać — jest nią
[f_equal].
Taktyka ta sprowadza się w zasadzie do jak najsprytniejszego aplikowania
faktu [f_equal]. Nie potrafi ona wprowadzać zmiennych do kontekstu, a z
wygenerowanych przez siebie podcelów rozwiązuje jedynie te postaci [x = x],
ale nie potrafi rozwiązać tych, które zachodzą na mocy założenia. *)
(** **** Ćwiczenie (my_f_equal) *)
(** Napisz taktykę [my_f_equal], która działa jak [f_equal] na sterydach, tj.
poza standardową funkcjonalnością [f_equal] potrafi też wprowadzać zmienne
do kontekstu oraz rozwiązywać cele prawdziwe na mocy założenia.
Użyj tylko jednej klauzuli [match]a. Nie używaj taktyki [subst]. Bonus:
wykorzystaj kombinator [first], ale nie wciskaj go na siłę. Z czego
łatwiej jest skorzystać: rekursji czy iteracji? *)
(* begin hide *)
(* Odp: łatwiejsza jest iteracja. *)
Ltac my_f_equal := intros; repeat (try
match goal with
| |- ?f ?x = ?g ?y =>
let H1 := fresh "H" in
let H2 := fresh "H" in
assert (H1 : f = g); assert (H2 : x = y);
rewrite ?H1, ?H2
end; first [reflexivity | assumption | idtac]).
(* end hide *)
Example f_equal_0 :
forall (A : Type) (x : A), x = x.
Proof.
intros. f_equal.
(* Nie działa, bo [x = x] nie jest podcelem
wygenerowanym przez [f_equal]. *)
Restart.
my_f_equal.
Qed.
Example f_equal_1 :
forall (A : Type) (x y : A), x = y -> x = y.
Proof.
intros. f_equal.
Restart.
my_f_equal.
Qed.
Example f_equal_2 :
forall (A B C D E : Type) (f f' : A -> B -> C -> D -> E)
(a a' : A) (b b' : B) (c c' : C) (d d' : D),
f = f' -> a = a' -> b = b' -> c = c' -> d = d' ->
f a b c d = f' a' b' c' d'.
Proof.
intros. f_equal. all: assumption.
Restart.
my_f_equal.
Qed.
(** **** Ćwiczenie (właściwości [f_equal]) *)
(** Przyjrzyj się definicjom [f_equal], [id], [compose], [eq_sym], [eq_trans],
a następnie udowodnij poniższe lematy. Ich sens na razie niech pozostanie
ukryty — kiedyś być może napiszę coś na ten temat. Jeżeli intrygują cię
one, więcej dowiesz się z
#<a class='link' href='https://homotopytypetheory.org/book/'>HoTTBooka</a>#. *)
Require Import Coq.Program.Basics.
Print f_equal.
Print eq_sym.
Print eq_trans.
Print compose.
Section f_equal_properties.
Variables
(A B C : Type)
(f : A -> B) (g : B -> C)
(x y z : A)
(p : x = y) (q : y = z).
Lemma f_equal_refl :
f_equal f (eq_refl x) = eq_refl (f x).
(* begin hide *)
Proof. reflexivity. Qed.
(* end hide *)
Lemma f_equal_id :
f_equal id p = p.
(* begin hide *)
Proof. destruct p. cbn. trivial. Qed.
(* end hide *)
Lemma f_equal_compose :
f_equal g (f_equal f p) = f_equal (compose g f) p.
(* begin hide *)
Proof. destruct p. cbn. trivial. Qed.
(* end hide *)
Lemma eq_sym_map_distr :
f_equal f (eq_sym p) = eq_sym (f_equal f p).
(* begin hide *)
Proof. destruct p. cbn. trivial. Qed.
(* end hide *)
Lemma eq_trans_map_distr :
f_equal f (eq_trans p q) = eq_trans (f_equal f p) (f_equal f q).
(* begin hide *)
Proof. destruct p, q. cbn. trivial. Qed.
(* end hide *)
End f_equal_properties.
(** Ostatnią taktyką, którą poznamy w tym podrozdziale, jest [f_equiv], czyli
pewne uogólnienie taktyki [f_equal]. Niech nie zmyli cię nazwa tej taktyki
— bynajmniej nie przydaje się ona jedynie do rozumowań dotyczących relacji
równoważności. *)
Require Import Classes.Morphisms.
(** Aby móc używać tej taktyki, musimy najpierw zaimportować moduł
[Classes.Morphisms]. *)
Definition len_eq {A : Type} (l1 l2 : list A) : Prop :=
length l1 = length l2.
(** W naszym przykładzie posłużymy się relacją [len_eq], która głosi, że
dwie listy są w relacji gdy mają taką samą długość. *)
#[export]
Instance Proper_len_eq_map {A : Type} :
Proper (@len_eq A ==> @len_eq A ==> @len_eq A) (@app A).
Proof.
Locate "==>".
unfold Proper, respectful, len_eq.
induction x as [| x xs]; destruct y; inversion 1; cbn; intros.
assumption.
f_equal. apply IHxs; assumption.
Qed.
(** Taktyka [f_equal] działa na celach postaci [f x = f y], gdzie [f] jest
dowolne, albowiem wszystkie funkcje zachowują równość. Analogicznie
taktyka [f_equiv] działa na celach postaci [R (f x) (f y)], gdzie [R]
jest dowolną relacją, ale tylko pod warunkiem, że funkcja [f] zachowuje
relację [R].
Musi tak być, bo gdyby [f] nie zachowywała [R], to mogłoby jednocześnie
zachodzić [R x y] oraz [~ R (f x) (f y)], a wtedy sposób rozumowania
analogiczny do tego z twierdzenia [f_equal] byłby niepoprawny.
Aby taktyka [f_equiv] "widziała", że [f] zachowuje [R], musimy znów
posłużyć się komendą [Instance] i użyć [Proper], które służy do
zwięzłego wyrażania, które konkretnie relacje i w jaki sposób zachowuje
dana funkcja.
W naszym przypadku będziemy chcieli pokazać, że jeżeli listy [l1] oraz
[l1'] są w relacji [len_eq] (czyli mają taką samą długość) i podobnie
dla [l2] oraz [l2'], to wtedy konkatenacja [l1] i [l2] jest w relacji
[len_eq] z konkatenacją [l1'] i [l2']. Ten właśnie fakt jest wyrażany
przez zapis [Proper (@len_eq A ==> @len_eq A ==> @len_eq A) (@app A)].
Należy też zauważyć, że strzałka [==>] jest jedynie notacją dla tworu
zwanego [respectful], co możemy łatwo sprawdzić komendą [Locate.] *)
Example f_equiv_0 :
forall (A B : Type) (f : A -> B) (l1 l1' l2 l2' : list A),
len_eq l1 l1' -> len_eq l2 l2' ->
len_eq (l1 ++ l2) (l1' ++ l2').
Proof.
intros. f_equiv.
assumption.
assumption.
Qed.
(** Voilà! Teraz możemy używać taktyki [f_equiv] z relacją [len_eq] oraz
funkcją [app] dokładnie tak, jak taktyki [f_equal] z równością oraz
dowolną funkcją.
Trzeba przyznać, że próba użycia [f_equiv] z różnymi kombinacjami
relacji i funkcji może zakończyć się nagłym i niekontrolowanym
rozmnożeniem lematów mówiących o tym, że funkcje zachowują relacje.
Niestety, nie ma na to żadnego sposobu — jak przekonaliśmy się wyżej,
udowodnienie takiego lematu to jedyny sposób, aby upewnić się, że nasz
sposób rozumowania jest poprawny. *)
(** **** Ćwiczenie (f_equiv_filter) *)
Require Import List.
Import ListNotations.
Definition stupid_id {A : Type} (l : list A) : list A :=
filter (fun _ => true) l.
(** Oto niezbyt mądry sposób na zapisanie funkcji identycznościowej na
listach typu [A]. Pokaż, że [stupid_id] zachowuje relację [len_eq],
tak aby poniższy dowód zadziałał bez wpowadzania zmian. *)
(* begin hide *)
#[export]
Instance Proper_len_eq_stupid_id {A : Type} :
Proper (@len_eq A ==> @len_eq A) (@stupid_id A).
Proof.
unfold Proper, respectful, len_eq.
induction x as [| x xs]; destruct y; inversion 1; cbn; intros.
trivial.
f_equal. apply (IHxs _ H1).
Qed.
(* end hide *)
Example f_equiv_1 :
forall (A : Type) (l l' : list A),
len_eq l l' -> len_eq (stupid_id l) (stupid_id l').
Proof.
intros. f_equiv. assumption.
Qed.
(** ** [rewrite] *)
(** Powinieneś być już nieźle wprawiony w używaniu taktyki [rewrite]. Czas
najwyższy więc opisać wszystkie jej możliwości.
Podstawowe wywołanie tej taktyki ma postać [rewrite H], gdzie [H] jest
typu [forall (x_1 : A_1) ... (x_n : A_n), R t_1 t_2], zaś [R] to [eq]
lub dowolna relacja równoważności. Przypomnijmy, że relacja równoważności
to relacja, która jest zwrotna, symetryczna i przechodnia.
[rewrite H] znajduje pierwszy podterm celu, który pasuje do [t_1] i
zamienia go na [t_2], generując podcele [A_1], ..., [A_n], z których
część (a często całość) jest rozwiązywana automatycznie. *)
Check plus_n_Sm.
(* ===> plus_n_Sm :
forall n m : nat, S (n + m) = n + S m *)
Goal 2 + 3 = 6 -> 4 + 4 = 42.
Proof.
intro.
rewrite <- plus_n_Sm.
rewrite plus_n_Sm.
rewrite <- plus_n_Sm.
rewrite -> plus_n_Sm.
rewrite <- !plus_n_Sm.
Fail rewrite <- !plus_n_Sm.
rewrite <- ?plus_n_Sm.
rewrite 4!plus_n_Sm.
rewrite <- 3?plus_n_Sm.
rewrite 2 plus_n_Sm.
Abort.
(** Powyższy skrajnie bezsensowny przykład ilustruje fakt, że działanie
taktyki [rewrite] możemy zmieniać, poprzedzając hipotezę [H] następującymi
modyfikatorami:
- [rewrite -> H] oznacza to samo, co [rewrite H]
- [rewrite <- H] zamienia pierwsze wystąpienie [t_2] na [t_1], czyli
przepisuje z prawa na lewo
- [rewrite ?H] przepisuje [H] 0 lub więcej razy
- [rewrite n?H] przepisuje [H] co najwyżej n razy
- [rewrite !H] przepisuje [H] 1 lub więcej razy
- [rewrite n!H] lub [rewrite n H] przepisuje [H] dokładnie n razy *)
(** Zauważmy, że modyfikator [<-] można łączyć z modyfikatorami określającymi
ilość przepisań. *)
Lemma rewrite_ex_1 :
forall n m : nat, 42 = 42 -> S (n + m) = n + S m.
Proof.
intros. apply plus_n_Sm.
Qed.
Goal 2 + 3 = 6 -> 5 + 5 = 12 -> (4 + 4) + ((5 + 5) + (6 + 6)) = 42.
Proof.
intros.
rewrite <- plus_n_Sm, <- plus_n_Sm.
rewrite <- plus_n_Sm in H.
rewrite <- plus_n_Sm in * |-.
rewrite !plus_n_Sm in *.
rewrite <- rewrite_ex_1. 2: reflexivity.
rewrite <- rewrite_ex_1 by reflexivity.
Abort.
(** Pozostałe warianty taktyki [rewrite] przedstawiają się następująco:
- [rewrite H_1, ..., H_n] przepisuje kolejno hipotezy [H_1], ..., [H_n].
Każdą z hipotez możemy poprzedzić osobnym zestawem modyfikatorów.
- [rewrite H in H'] przepisuje [H] nie w celu, ale w hipotezie [H']
- [rewrite H in * |-] przepisuje [H] we wszystkich hipotezach
różnych od [H]
- [rewrite H in *] przepisuje [H] we wszystkich hipotezach różnych
od [H] oraz w celu
- [rewrite H by tac] działa jak [rewrite H], ale używa taktyki [tac] do
rozwiązania tych podcelów, które nie mogły zostać rozwiązane
automatycznie *)
(** Jest jeszcze wariant [rewrite H at n] (wymagający zaimportowania modułu
[Setoid]), który zamienia n-te (licząc od lewej) wystąpienie [t_1] na
[t_2]. Zauważmy, że [rewrite H] znaczy to samo, co [rewrite H at 1]. *)
(** * Taktyki dla redukcji i obliczeń (TODO) *)
(** * Procedury decyzyjne *)
(** Procedury decyzyjne to taktyki, które potrafią zupełnie same rozwiązywać
cele należące do pewnej konkretnej klasy, np. cele dotyczące funkcji
boolowskich albo nierówności liniowych na liczbach całkowitych. W tym
podrozdziale omówimy najprzydatniejsze z nich. *)
(** ** [btauto] *)
(** [btauto] to taktyka, która potrafi rozwiązywać równania boolowskie, czyli
cele postaci [x = y], gdzie [x] i [y] są wyrażeniami mogącymi zawierać
boolowskie koniunkcje, dysjunkcje, negacje i inne rzeczy (patrz manual).
Taktykę można zaimportować komendą [Require Import Btauto]. Uwaga: nie
potrafi ona wprowadzać zmiennych do kontekstu. *)
(** **** Ćwiczenie (my_btauto) *)
(** Napisz następujące taktyki:
- [my_btauto] — taktyka podobna do [btauto]. Potrafi rozwiązywać cele,
które są kwantyfikowanymi równaniami na wyrażeniach boolowskich,
składającymi się z dowolnych funkcji boolowskich (np. [andb], [orb]).
W przeciwieństwie do [btauto] powinna umieć wprowadzać zmienne do
kontekstu.
- [my_btauto_rec] — tak samo jak [my_btauto], ale bez używana
kombinatora [repeat]. Możesz używać jedynie rekurencji.
- [my_btauto_iter] — tak samo jak [my_btauto], ale bez używania
rekurencji. Możesz używać jedynie kombinatora [repeat].
- [my_btauto_no_intros] — tak samo jak [my_btauto], ale bez używania
taktyk [intro] oraz [intros]. *)
(** Uwaga: twoja implementacja taktyki [my_btauto] będzie diametralnie różnić
się od implementacji taktyki [btauto] z biblioteki standardowej. [btauto]
jest zaimplementowana za pomocą reflekcji. Dowód przez reflekcję omówimy
później. *)
(* begin hide *)
Ltac my_btauto := intros; repeat
match goal with
| b : bool |- _ => destruct b
end; cbn; reflexivity.
Ltac my_btauto_rec := intros;
match goal with
| b : bool |- _ => destruct b; my_btauto_rec
| _ => cbn; reflexivity
end.
Ltac my_btauto_iter := my_btauto.
Ltac my_btauto_no_intros := repeat
match goal with
| |- forall b : bool, _ => destruct b
end; cbn; reflexivity.
(* end hide *)
Require Import Bool.
Require Import Btauto.
Section my_btauto.
Lemma andb_dist_orb :
forall b1 b2 b3 : bool,
b1 && (b2 || b3) = (b1 && b2) || (b1 && b3).
Proof.
intros. btauto.
Restart.
my_btauto.
Restart.
my_btauto_rec.
Restart.
my_btauto_iter.
Restart.
my_btauto_no_intros.
Qed.
Lemma negb_if :
forall b1 b2 b3 : bool,
negb (if b1 then b2 else b3) = if negb b1 then negb b3 else negb b2.
Proof.
intros. btauto.
Restart.
my_btauto.
Restart.
my_btauto_rec.
Restart.
my_btauto_iter.
Restart.
my_btauto_no_intros.
Qed.
(** Przetestuj działanie swoich taktyk na reszcie twierdzeń z rozdziału
o logice boolowskiej. *)
End my_btauto.
(** ** [congruence] *)
Example congruence_0 :
forall P : Prop, true <> false.
Proof. congruence. Qed.
Example congruence_1 :
forall (A : Type) (f : A -> A) (g : A -> A -> A) (a b : A),
a = f a -> g b (f a) = f (f a) -> g a b = f (g b a) ->
g a b = a.
Proof.
(* begin hide *)
intros. rewrite H1, H at 1. rewrite H0, <- !H. trivial.
Restart.
(* end hide *)
congruence.
Qed.
Example congruence_2 :
forall (A : Type) (f : A -> A * A) (a c d : A),
f = pair a -> Some (f c) = Some (f d) -> c = d.
Proof.
(* begin hide *)
intros. inversion H0. rewrite H in H2. inversion H2. trivial.
Restart.
(* end hide *)
congruence.
Qed.
(** [congruece] to taktyka, która potrafi rozwiązywać cele dotyczące
nieinterpretowanych równości, czyli takie, których prawdziwość zależy
jedynie od hipotez postaci [x = y] i które można udowodnić ręcznie za
pomocą mniejszej lub większej ilości [rewrite]'ów. [congruence] potrafi
też rozwiązywać cele dotyczące konstruktorów. W szczególności wie ona,
że konstruktory są injektywne i potrafi odróżnić [true] od [false]. *)
(** **** Ćwiczenie (congruence) *)
(** Udowodnij przykłady [congruence_1] i [congruence_2] ręcznie. *)
(** **** Ćwiczenie (discriminate) *)
(** Inną taktyką, która potrafi rozróżniać konstruktory, jest [discriminate].
Zbadaj, jak działa ta taktyka. Znajdź przykład celu, który [discriminate]
rozwiązuje, a na którym [congruence] zawodzi. Wskazówka: [congruence]
niebardzo potrafi odwijać definicje. *)
(* begin hide *)
Definition mytrue := true.
Goal ~ (mytrue = false).
Proof.
Fail congruence.
discriminate.
Qed.
(* end hide *)
(** **** Ćwiczenie (injection i simplify_eq) *)
(** Kolejne dwie taktyki do walki z konstruktorami typów induktywnych to
[injection] i [simplify_eq]. Przeczytaj ich opisy w manualu. Zbadaj,
czy są one w jakikolwiek sposób przydatne (wskazówka: porównaj je z
taktykami [inversion] i [congruence]. *)
(** ** [decide equality] *)
Inductive C : Type :=
| c0 : C
| c1 : C -> C
| c2 : C -> C -> C
| c3 : C -> C -> C -> C.
(** Przyjrzyjmy się powyższemu, dosć enigmatycznemu typowi. Czy posiada on
rozstrzygalną równość? Odpowiedź jest twierdząca: rozstrzygalną równość
posiada każdy typ induktywny, którego konstruktory nie biorą argumentów
będących dowodami, funkcjami ani termami typów zależnych. *)
Lemma C_eq_dec :
forall x y : C, {x = y} + {x <> y}.
(* begin hide *)
Proof.
induction x.
destruct y.
left; trivial.
1-3: right; inversion 1.
destruct y.
1, 3-4: right; inversion 1.
destruct (IHx y); subst; auto. right. congruence.
destruct y.
1-2, 4: right; congruence.
destruct (IHx1 y1), (IHx2 y2); subst; auto. 1-3: right; congruence.
destruct y.
1-3: right; congruence.
destruct (IHx1 y1), (IHx2 y2), (IHx3 y3); subst; auto. 1-7: right; congruence.
Restart.
induction x; destruct y; try (right; congruence).
left; trivial.
destruct (IHx y); firstorder congruence.
destruct (IHx1 y1), (IHx2 y2); firstorder congruence.
destruct (IHx1 y1), (IHx2 y2), (IHx3 y3); firstorder congruence.
Restart.
induction x; destruct y;
repeat match goal with
| H : forall _, {_} + {_} |- _ => edestruct H; clear H
| H : _ = _ |- _ => rewrite H in *; clear H
end; firstorder congruence.
Unshelve. all: auto.
Defined.
(* end hide *)
(** Zanim przejdziesz dalej, udowodnij ręcznie powyższe twierdzenie. Przyznasz,
że dowód nie jest zbyt przyjemny, prawda? Na szczęście nie musimy robić go
ręcznie. Na ratunek przychodzi nam taktyka [decide equality], która umie
udowadniać cele postaci [forall x y : T, {x = y} + {x <> y}], gdzie [T]
spełnia warunki wymienione powyżej. *)
Lemma C_eq_dec' :
forall x y : C, {x = y} + {x <> y}.
Proof. decide equality. Defined.
(** **** Ćwiczenie *)
(** Pokrewną taktyce [decide equality] jest taktyka [compare]. Przeczytaj
w manualu, co robi i jak działa. *)
(** ** [lia] *)
(** TODO: opisć taktykę [lia] *)
Require Import Arith Lia.
Example lia_0 :
forall n : nat, n + n = 2 * n.
Proof. intro. lia. Qed.
Example lia_1 :
forall n m : nat, 2 * n + 1 <> 2 * m.
Proof. intros. lia. Qed.
Example lia_2 :
forall n m : nat, n * m = m * n.
Proof. intros. lia. Qed.
Lemma filter_length :
forall (A : Type) (f : A -> bool) (l : list A),
length (filter f l) <= length l.
Proof.
induction l; cbn; try destruct (f a); cbn; lia.
Qed.
Print filter_length.
Lemma filter_length' :
forall (A : Type) (f : A -> bool) (l : list A),
length (filter f l) <= length l.
Proof.
induction l; cbn; try destruct (f a); cbn.
trivial.
apply le_n_S. assumption.
apply Nat.le_trans with (length l).
assumption.
apply le_S. apply le_n.
Qed.
Print filter_length'.
(* ===> Proofterm o długości 14 linijek. *)
(** ** Procedury decyzyjne dla logiki *)
Example tauto_0 :
forall A B C D : Prop,
~ A \/ ~ B \/ ~ C \/ ~ D -> ~ (A /\ B /\ C /\ D).
Proof. tauto. Qed.
Example tauto_1 :
forall (P : nat -> Prop) (n : nat),
n = 0 \/ P n -> n <> 0 -> P n.
Proof. auto. tauto. Qed.
(** [tauto] to taktyka, która potrafi udowodnić każdą tautologię
konstruktywnego rachunku zdań. Taktyka ta radzi sobie także z niektórymi
nieco bardziej skomplikowanymi celami, w tym takimi, których nie potrafi
udowodnić [auto]. [tauto] zawodzi, gdy nie potrafi udowodnić celu. *)
Example intuition_0 :
forall (A : Prop) (P : nat -> Prop),
A \/ (forall n : nat, ~ A -> P n) -> forall n : nat, ~ ~ (A \/ P n).
Proof.
Fail tauto. intuition.
Qed.
(** [intuition] to [tauto] na sterydach — potrafi rozwiązać nieco więcej
celów, a poza tym nigdy nie zawodzi. Jeżeli nie potrafi rozwiązać celu,
upraszcza go.
Może też przyjmować argument: [intuition t] najpierw upraszcza cel, a
później próbuje go rozwiązać taktyką [t]. Tak naprawdę [tauto] jest
jedynie synonimem dla [intuition fail], zaś samo [intuition] to synonim
[intuition auto with *], co też tłumaczy, dlaczego [intuition] potrafi
więcej niż [tauto]. *)
Record and3 (P Q R : Prop) : Prop :=
{
left : P;
mid : Q;
right : R;
}.
Example firstorder_0 :
forall (B : Prop) (P : nat -> Prop),
and3 (forall x : nat, P x) B B ->
and3 (forall y : nat, P y) (P 0) (P 0) \/ B /\ P 0.
Proof.
Fail tauto.
intuition.
Restart.
firstorder.
Qed.
Example firstorder_1 :
forall (A : Type) (P : A -> Prop),
(exists x : A, ~ P x) -> ~ forall x : A, P x.
Proof.
Fail tauto. intuition.
Restart.
firstorder.
Qed.
(** Jednak nawet [intuition] nie jest w stanie sprostać niektórym prostym
dla człowieka celom — powyższy przykład pokazuje, że nie potrafi ona
posługiwać się niestandardowymi spójnikami logicznymi, takimi jak
potrójna koniunkcja [and3].
Najpotężniejszą taktyką potrafiącą dowodzić tautologii jest [firstorder].
Nie tylko rozumie ona niestandardowe spójniki (co i tak nie ma większego
praktycznego znaczenia), ale też świetnie radzi sobie z kwantyfikatorami.
Drugi z powyższych przykładów pokazuje, że potrafi ona dowodzić tautologii
konstruktywnego rachunku predykatów, z którymi problem ma [intuition]. *)
(** **** Ćwiczenie (my_tauto) *)
(** Napisz taktykę [my_tauto], która będzie potrafiła rozwiązać jak najwięcej
tautologii konstruktywnego rachunku zdań.
Wskazówka: połącz taktyki z poprzednich ćwiczeń. Przetestuj swoją taktykę
na ćwiczeniach z rozdziału pierwszego — być może ujawni to problemy, o
których nie pomyślałeś.
Nie używaj żadnej zaawansowanej automatyzacji. Użyj jedynie [unfold],
[intro], [repeat], [match], [destruct], [clear], [exact], [split],
[specialize] i [apply]. *)
(* begin hide *)
Ltac my_tauto :=
unfold not in *; repeat
multimatch goal with
| H : ?P |- ?P => exact H
| H : False |- _ => destruct H
| H : True |- _ => clear H
| |- True => exact I
| H : _ /\ _ |- _ => destruct H
| |- _ /\ _ => split
| H : _ <-> _ |- _ => destruct H
| |- _ <-> _ => split
| H : _ \/ _ |- _ => destruct H
| |- _ \/ _ => (left + right); my_tauto; fail
| |- _ -> _ => intro
| H : ?P -> ?Q, H' : ?P |- _ => specialize (H H')
| H : _ -> _ |- _ => apply H
end.
Section my_tauto.
Hypotheses P Q R S : Prop.
Lemma and_comm : P /\ Q -> Q /\ P.
Proof. my_tauto. Qed.
Lemma or_comm : P \/ Q -> Q \/ P.
Proof. my_tauto. Qed.
Lemma and_assoc : P /\ (Q /\ R) <-> (P /\ Q) /\ R.
Proof. my_tauto. Qed.
Lemma or_assoc : P \/ (Q \/ R) <-> (P \/ Q) \/ R.
Proof. my_tauto. Qed.
Lemma and_dist_or : P /\ (Q \/ R) <-> (P /\ Q) \/ (P /\ R).
Proof. my_tauto. Qed.
Lemma or_dist_and : P \/ (Q /\ R) <-> (P \/ Q) /\ (P \/ R).
Proof. my_tauto. Qed.
Lemma imp_dist_imp : (P -> Q -> R) <-> ((P -> Q) -> (P -> R)).
Proof. my_tauto. Qed.
Lemma curry : (P /\ Q -> R) -> (P -> Q -> R).
Proof. intros. assert (P /\ Q). my_tauto. my_tauto. Qed.
Lemma uncurry : (P -> Q -> R) -> (P /\ Q -> R).
Proof. my_tauto. Qed.
Lemma deMorgan_1 : ~(P \/ Q) <-> ~P /\ ~Q.
Proof. my_tauto. Qed.
Lemma deMorgan_2 : ~P \/ ~Q -> ~(P /\ Q).
Proof. my_tauto. Qed.
Lemma noncontradiction' : ~(P /\ ~P).
Proof. my_tauto. Qed.
Lemma noncontradiction_v2 : ~(P <-> ~P).
Proof. my_tauto. Qed.
Lemma em_irrefutable : ~~(P \/ ~P).
Proof. my_tauto. Qed.
Lemma and_False_r : P /\ False <-> False.
Proof. my_tauto. Qed.
Lemma or_False_r : P \/ False <-> P.
Proof. my_tauto. Qed.
Lemma and_True_r : P /\ True <-> P.
Proof. my_tauto. Qed.
Lemma or_True_r : P \/ True <-> True.
Proof. my_tauto. Qed.
Lemma or_imp_and : (P \/ Q -> R) <-> (P -> R) /\ (Q -> R).
Proof. my_tauto. Qed.
Lemma and_not_imp : P /\ ~Q -> ~(P -> Q).
Proof. my_tauto. Qed.
Lemma or_not_imp : ~P \/ Q -> (P -> Q).
Proof. my_tauto. Qed.
Lemma contraposition : (P -> Q) -> (~Q -> ~P).
Proof. my_tauto. Qed.
Lemma absurd : ~P -> P -> Q.
Proof. my_tauto. Qed.
Lemma impl_and : (P -> Q /\ R) -> ((P -> Q) /\ (P -> R)).
Proof. my_tauto. Qed.
End my_tauto.
(* end hide *)
(** * Ogólne taktyki automatyzacyjne *)
(** W tym podrozdziale omówimy pozostałe taktyki przydające się przy
automatyzacji. Ich cechą wspólną jest rozszerzalność — za pomocą
specjalnych baz podpowiedzi będziemy mogli nauczyć je radzić sobie
z każdym celem. *)
(** ** [auto] i [trivial] *)
(** [auto] jest najbardziej ogólną taktyką służącą do automatyzacji. *)
Example auto_ex0 :
forall (P : Prop), P -> P.
Proof. auto. Qed.
Example auto_ex1 :
forall A B C D E : Prop,
(A -> B) -> (B -> C) -> (C -> D) -> (D -> E) -> A -> E.
Proof. auto. Qed.
Example auto_ex2 :
forall (A : Type) (x : A), x = x.
Proof. auto. Qed.
Example auto_ex3 :
forall (A : Type) (x y : A), x = y -> y = x.
Proof. auto. Qed.
(** [auto] potrafi używać założeń, aplikować hipotezy i zna podstawowe
własności równości — całkiem nieźle. Wprawdzie nie wystarczy to do
udowodnienia żadnego nietrywialnego twierdzenia, ale przyda się z
pewnością do rozwiązywania prostych podcelów generowanych przez
inne taktyki. Często spotykanym idiomem jest [t; auto] — "użyj
taktyki [t] i pozbądź się prostych podcelów za pomocą [auto]". *)
Section auto_ex4.
Parameter P : Prop.
Parameter p : P.
Example auto_ex4 : P.
Proof.
auto.
Restart.
auto using p.
Qed.
(** Jak widać na powyższym przykładzie, [auto] nie widzi aksjomatów (ani
definicji/lematów/twierdzeń etc.), nawet jeżeli zostały zadeklarowane
dwie linijki wyżej. Tej przykrej sytuacji możemy jednak łatwo zaradzić,
pisząc [auto using t_1, ..., t_n]. Ten wariant taktyki [auto]
widzi definicje termów [t_1], ..., [t_n].
Co jednak w sytuacji, gdy będziemy wielokrotnie chcieli, żeby [auto]
widziało pewne definicje? Nietrudno wyobrazić sobie ogrom pisaniny,
którą mogłoby spowodować użycie do tego celu klauzuli [using]. Na
szczęście możemy temu zaradzić za pomocą podpowiedzi, które bytują
w specjalnych bazach. *)
Hint Resolve p : core.
Example auto_ex4' : P.
Proof. auto with core. Qed.
(** Komenda [Hint Resolve ident : db_name] dodaje lemat o nazwie [ident]
do bazy podpowiedzi o nazwie [db_name]. Dzięki temu taktyka [auto with
db_1 ... db_n] widzi wszystkie lematy dodane do baz [db_1], ..., [db_n].
Domyślna baza podpowiedzi nazywa się [core] i to właśnie do niej dodajemy
naszą podpowiedź.
Jeżeli to dla ciebie wciąż zbyt wiele pisania, uszy do góry! *)
Example auto_ex4'' : P.
Proof. auto with *. Qed.
(** Taktyka [auto with *] widzi wszystkie możliwe bazy podpowiedzi. *)
Example auto_ex4''' : P.
Proof. auto. Qed.
(** Goła taktyka [auto] jest zaś równoważna taktyce [auto with core]. Dzięki
temu nie musimy pisać już nic ponad zwykłe [auto]. *)
End auto_ex4.
(** Tym oto sposobem, używając komendy [Hint Resolve], jesteśmy w stanie
zaznajomić [auto] z różnej maści lematami i twierdzeniami, które
udowodniliśmy. Komendy tej możemy używać po każdym lemacie, dzięki
czemu taktyka [auto] rośnie w siłę w miarę rozwoju naszej teorii. *)
Example auto_ex5 : even 8.
Proof.
auto.
Restart.
auto using even0, evenSS.
Qed.
(** Kolejną słabością [auto] jest fakt, że taktyka ta nie potrafi budować
wartości typów induktywnych. Na szczęście możemy temu zaradzić używając
klauzuli [using c_1 ... c_n], gdzie [c_1], ..., [c_n] są konstruktorami
naszego typu, lub dodając je jako podpowiedzi za pomocą komendy [Hint
Resolve c_1 ... c_n : db_name]. *)
#[global] Hint Constructors even : core.
Example auto_ex5' : even 8.
Proof. auto. Qed.
(** Żeby jednak za dużo nie pisać (wypisanie nazw wszystkich konstruktorów
mogłoby być bolesne), możemy posłużyć się komendą [Hint Constructors
I : db_name], która dodaje konstruktory typu induktywnego [I] do bazy
podpowiedzi [db_name]. *)
Example auto_ex6 : even 10.
Proof.
auto.
Restart.
auto 6.
Qed.
(** Kolejnym celem, wobec którego [auto] jest bezsilne, jest [even 10].
Jak widać, nie wystarczy dodać konstruktorów typu induktywnego jako
podpowiedzi, żeby wszystko było cacy. Niemoc [auto] wynika ze sposobu
działania tej taktyki. Wykonuje ona przeszukiwanie w głąb z nawrotami,
które działa mniej więcej tak:
- zrób pierwszy lepszy możliwy krok dowodu
- jeżeli nie da się nic więcej zrobić, a cel nie został udowodniony,
wykonaj nawrót i spróbuj czegoś innego
- w przeciwnym wypadku wykonaj następny krok dowodu i powtarzaj
całą procedurę *)
(** Żeby ograniczyć czas poświęcony na szukanie dowodu, który może być
potencjalnie bardzo długi, [auto] ogranicza się do wykonania jedynie
kilku kroków w głąb (domyślnie jest to 5). *)
Print auto_ex5'.
(* ===> evenSS 6 (evenSS 4 (evenSS 2 (evenSS 0 even0)))
: even 8 *)
Print auto_ex6.
(* ===> evenSS 8 (evenSS 6 (evenSS 4 (evenSS 2 (evenSS 0 even0))))
: even 10 *)
(** [auto] jest w stanie udowodnić [even 8], gdyż dowód tego faktu wymaga
jedynie 5 kroków, mianowicie czeterokrotnego zaaplikowania konstruktora
[evenSS] oraz jednokrotnego zaaplikowania [even0]. Jednak 5 kroków nie
wystarcza już, by udowodnić [even 10], gdyż tutaj dowód liczy sobie 6
kroków: 5 użyć [evenSS] oraz 1 użycie [even0].
Nie wszystko jednak stracone — możemy kontrolować głębokość, na jaką
[auto] zapuszcza się, poszukując dowodu, piząc [auto n]. Zauważmy, że
[auto] jest równoważne taktyce [auto 5]. *)
Example auto_ex7 :
forall (A : Type) (x y z : A), x = y -> y = z -> x = z.
Proof.
auto.
Restart.
Fail auto using eq_trans.
Abort.
(** Kolejnym problemem taktyki [auto] jest udowodnienie, że równość jest
relacją przechodnią. Tym razem jednak problem jest poważniejszy, gdyż
nie pomaga nawet próba użycia klauzuli [using eq_trans], czyli wskazanie
[auto] dokładnie tego samego twierdzenia, którego próbujemy dowieść!
Powód znów jest dość prozaiczny i wynika ze sposobu działania taktyki
[auto] oraz postaci naszego celu. Otóż konkluzja celu jest postaci
[x = z], czyli występują w niej zmienne [x] i [z], zaś kwantyfikujemy
nie tylko po [x] i [z], ale także po [A] i [y].
Wywnioskowanie, co wstawić za [A] nie stanowi problemu, gdyż musi to
być typ [x] i [z]. Problemem jest jednak zgadnięcie, co wstawić za [y],
gdyż w ogólności możliwości może być wiele (nawet nieskończenie wiele).
Taktyka [auto] działa w ten sposób, że nawet nie próbuje tego zgadywać. *)
#[global] Hint Extern 0 =>
match goal with
| H : ?x = ?y, H' : ?y = ?z |- ?x = ?z => apply (@eq_trans _ x y z)
end
: extern_db.
Example auto_ex7 :
forall (A : Type) (x y z : A), x = y -> y = z -> x = z.
Proof. auto with extern_db. Qed.
(** Jest jednak sposób, żeby uporać się i z tym problemem: jest nim komenda
[Hint Extern]. Jej ogólna postać to [Hint Extern n pattern => tactic : db].
W jej wyniku do bazy podpowiedzi [db] zostanie dodana podpowiedź, która
sprawi, że w dowolnym momencie dowodu taktyka [auto], jeżeli wypróbowała
już wszystkie podpowiedzi o koszcie mniejszym niż [n] i cel pasuje do
wzorca [pattern], to spróbuje użyć taktyki [tac].
W naszym przypadku koszt podpowiedzi wynosi 0, a więc podpowiedź będzie
odpalana niemal na samym początku dowodu. Wzorzec [pattern] został
pominięty, a więc [auto] użyje naszej podpowiedzi niezależnie od tego,
jak wygląda cel. Ostatecznie jeżeli w konktekście będą odpowiednie
równania, to zaaplikowany zostanie lemat [@eq_trans _ x y z], wobec
czego wygenerowane zostaną dwa podcele, [x = y] oraz [y = z], które
[auto] będzie potrafiło rozwiązać już bez naszej pomocy. *)
#[global] Hint Extern 0 (?x = ?z) =>
match goal with
| H : ?x = ?y, H' : ?y = ?z |- _ => apply (@eq_trans _ x y z)
end
: core.
Example auto_ex7' :
forall (A : Type) (x y z : A), x = y -> y = z -> x = z.
Proof. auto. Qed.
(** A tak wygląda wersja [Hint Extern], w której nie pominięto wzorca
[pattern]. Jest ona rzecz jasna równoważna z poprzednią.
Jest to dobry moment, by opisać dokładniej działanie taktyki [auto].
[auto] najpierw próbuje rozwiązać cel za pomocą taktyki [assumption].
Jeżeli się to nie powiedzie, to [auto] używa taktyki [intros], a
następnie dodaje do tymczasowej bazy podpowiedzi wszystkie hipotezy.
Następnie przeszukuje ona bazę podpowiedzi dopasowując cel do wzorca
stowarzyszonego z każdą podpowiedzią, zaczynając od podpowiedzi o
najmniejszym koszcie (podpowiedzi pochodzące od komend [Hint Resolve]
oraz [Hint Constructors] są skojarzone z pewnymi domyślnymi kosztami
i wzorcami). Następnie [auto] rekurencyjnie wywołuje się na podcelach
(chyba, że przekroczona została maksymalna głębokość przeszukiwania —
wtedy następuje nawrót). *)
Example trivial_ex0 :
forall (P : Prop), P -> P.
Proof. trivial. Qed.
Example trivial_ex1 :
forall A B C D E : Prop,
(A -> B) -> (B -> C) -> (C -> D) -> (D -> E) -> A -> E.
Proof. trivial. Abort.
Example trivial_ex2 :
forall (A : Type) (x : A), x = x.
Proof. trivial. Qed.
Example trivial_ex3 :
forall (A : Type) (x y : A), x = y -> y = x.
Proof. trivial. Abort.
Example trivial_ex5 : even 0.
Proof. trivial. Qed.
Example trivial_ex5' : even 8.
Proof. trivial. Abort.
(** Taktyka [trivial], którą już znasz, działa dokładnie tak samo jak [auto],
ale jest nierekurencyjna. To tłumaczy, dlaczego potrafi ona posługiwać
się założeniami i zna właciwości równości, ale nie umie używać implikacji
i nie radzi sobie z celami pokroju [even 8], mimo że potrafi udowodnić
[even 0]. *)
(** **** Ćwiczenie (auto i trivial) *)
(** Przeczytaj w
#<a class='link' href='https://coq.inria.fr/refman/proof-engine/tactics.html##coq:tacn.auto'>
manualu</a># dokładny opis działania taktyk [auto] oraz [trivial]. *)
(** ** [autorewrite] i [autounfold] *)
(** [autorewrite] to bardzo pożyteczna taktyka umożliwiająca zautomatyzowanie
części dowodów opierających się na przepisywaniu.
Dlaczego tylko części? Zastanówmy się, jak zazwyczaj przebiegają dowody
przez przepisywanie. W moim odczuciu są dwa rodzaje takich dowodów:
- dowody pierwszego rodzaju to te, w których wszystkie przepisania mają
charakter upraszczający i dzięki temu możemy przepisywać zupełnie
bezmyślnie
- dowody drugiego rodzaju to te, w których niektóre przepisania nie mają
charakteru upraszczającego albo muszą zostać wykonane bardzo precyzyjnie.
W takich przypadkach nie możemy przepisywać bezmyślnie, bo grozi to
zapętleniem taktyki [rewrite] lub po prostu porażką *)
(** Dowody pierwszego rodzaju ze względu na swoją bezmyślność są dobrymi
kandydatami do automatyzacji. Właśnie tutaj do gry wkracza taktyka
[autorewrite]. *)
Section autorewrite_ex.
Variable A : Type.
Variable l1 l2 l3 l4 l5 : list A.
(** Zacznijmy od przykładu (a raczej ćwiczenia): udowodnij poniższe
twierdzenie. Następnie udowodnij je w jednej linijce. *)
Example autorewrite_intro :
rev (rev (l1 ++ rev (rev l2 ++ rev l3) ++ rev l4) ++ rev (rev l5)) =
(rev (rev (rev l5 ++ l1)) ++ (l3 ++ rev (rev l2))) ++ rev l4.
(* begin hide *)
Proof.
rewrite ?rev_involutive.
rewrite <- ?app_assoc.
rewrite ?rev_app_distr.
rewrite ?rev_involutive.
rewrite <- ?app_assoc.
reflexivity.
Restart.
rewrite ?rev_app_distr, ?rev_involutive, <- ?app_assoc. reflexivity.
Qed.
(* end hide *)
(** Ten dowód nie był zbyt twórczy ani przyjemny, prawda? Wyobraź sobie
teraz, co by było, gdybyś musiał udowodnić 100 takich twierdzeń (i
to w czasach, gdy jeszcze nie można było pisać [rewrite ?t_0, ..., ?t_n]).
Jest to dość ponura wizja. *)
Hint Rewrite rev_app_distr rev_involutive : list_rw.
Hint Rewrite <- app_assoc : list_rw.
Example autorewrite_ex :
rev (rev (l1 ++ rev (rev l2 ++ rev l3) ++ rev l4) ++ rev (rev l5)) =
(rev (rev (rev l5 ++ l1)) ++ (l3 ++ rev (rev l2))) ++ rev l4.
Proof.
autorewrite with list_rw. reflexivity.
Qed.
End autorewrite_ex.
(** Komenda [Hint Rewrite [<-] ident_0 ... ident_n : db_name] dodaje
podpowiedzi [ident_0], ..., [ident_n] do bazy podpowidzi [db_nam].
Domyślnie będą one przepisywane z lewa na prawo, chyba że dodamy
przełącznik [<-] — wtedy wszystkie będą przepisywane z prawa na
lewo. W szczególności znaczy to, że jeżeli chcemy niektóre lematy
przepisywać w jedną stronę, a inne w drugą, to musimy komendy
[Hint Rewrite] użyć dwukrotnie.
Sama taktyka [autorewrite with db_0 ... db_n] przepisuje lematy ze
wszystkich baz podpowiedzi [db_0], ..., [db_n] tak długo, jak to
tylko możliwe (czyli tak długo, jak przepisywanie skutkuje dokonaniem
postępu).
Jest kilka ważnych cech, które powinna posiadać baza podpowiedzi:
- przede wszystkim nie może zawierać tego samego twierdzenia do
przepisywania w obydwie strony. Jeżeli tak się stanie, taktyka
[autorewrite] się zapętli, gdyż przepisanie tego twierdzenia w
jedną lub drugą stronę zawsze będzie możliwe
- w ogólności, nie może zawierać żadnego zbioru twierdzeń, których
przepisywanie powoduje zapętlenie
- baza powinna być deterministyczna, tzn. jedne przepisania nie
powinny blokować kolejnych
- wszystkie przepisywania powinny być upraszczające *)
(** Oczywiście dwa ostatnie kryteria nie są zbyt ścisłe — ciężko sprawdzić
determinizm systemu przepisywania, zaś samo pojęcie "uproszczenia" jest
bardzo zwodnicze i niejasne. *)
(** **** Ćwiczenie (autorewrite) *)
(** Przeczytaj opis taktyki [autorewrite] w manualu:
coq.inria.fr/refman/proof-engine/tactics.html#coq:tacn.autorewrite *)
Section autounfold_ex.
Definition wut : nat := 1.
Definition wut' : nat := 1.
Hint Unfold wut wut' : wut_db.
Example autounfold_ex : wut = wut'.
Proof.
autounfold.
autounfold with wut_db.
Restart.
auto.
Qed.
(** Na koniec omówimy taktykę [autounfold]. Działa ona na podobnej zasadzie
jak [autorewrite]. Za pomocą komendy [Hint Unfold] dodajemy definicje do
do bazy podpowiedzi, dzięki czemu taktyka [autounfold with db_0, ..., db_n]
potrafi odwinąć wszystkie definicje z baz [db_0], ..., [db_n].
Jak pokazuje nasz głupi przykład, jest ona średnio użyteczna, gdyż taktyka
[auto] potrafi (przynajmniej do pewnego stopnia) odwijać definicje. Moim
zdaniem najlepiej sprawdza się ona w zestawieniu z taktyką [autorewrite]
i kombinatorem [repeat], gdy potrzebujemy na przemian przepisywać lematy
i odwijać definicje. *)
End autounfold_ex.
(** **** Ćwiczenie (autounfold) *)
(** Przeczytaj w manualu opis taktyki [autounfold]:
coq.inria.fr/refman/proof-engine/tactics.html#coq:tacn.autounfold *)
(** **** Ćwiczenie (bazy podpowiedzi) *)
(** Przeczytaj w manualu dokładny opis działania systemu baz podpowiedzi
oraz komend pozwalających go kontrolować:
coq.inria.fr/refman/proof-engine/tactics.html#controlling-automation *)
(** * Pierścienie, ciała i arytmetyka *)
(** Pierścień (ang. ring) to struktura algebraiczna składająca się z pewnego
typu A oraz działań + i *, które zachowują się mniej więcej tak, jak
dodawanie i mnożenie liczb całkowitych. Przykładów jest sporo: liczby
wymierne i rzeczywiste z dodawaniem i mnożeniem, wartości boolowskie z
dysjunkcją i koniunkcją oraz wiele innych, których na razie nie wymienię.
Kiedyś z pewnością napiszę coś na temat algebry oraz pierścieni, ale z
taktykami do radzenia sobie z nimi możemy zapoznać się już teraz. W Coqu
dostępne są dwie taktyki do radzenia sobie z pierścieniami: taktyka
[ring_simplify] potrafi upraszczać wyrażenia w pierścieniach, zaś taktyka
[ring] potrafi rozwiązywać równania wielomianowe w pierścieniach.
Ciało (ang. field) to pierścień na sterydach, w którym poza dodawaniem,
odejmowaniem i mnożeniem jest także dzielenie. Przykładami ciał są
liczby wymierne oraz liczby rzeczywiste, ale nie liczby naturalne ani
całkowite (bo dzielenie naturalne/całkowitoliczbowe nie jest odwrotnością
mnożenia). Je też kiedyś pewnie opiszę.
W Coqu są 3 taktyki pomagające w walce z ciałami: [field_simplify]
upraszcza wyrażenia w ciałach, [field_simplify_eq] upraszcza cele,
które są równaniami w ciałach, zaś [field] rozwiązuje równania w
ciałach. *)
(** **** Ćwiczenie (pierścienie i ciała) *)
(** Przyczytaj w
#<a class='link' href='https://coq.inria.fr/refman/addendum/ring.html'>
manualu</a># opis 5 wymienionych wyżej taktyk. *)
(** * Zmienne egzystencjalne i ich taktyki (TODO) *)
(** Napisać o co chodzi ze zmiennymi egzystencjalnymi. Opisać taktykę
[evar] i wspomnieć o taktykach takich jak [eauto], [econstructor],
[eexists], [edestruct], [erewrite] etc., a także taktykę [shelve]
i komendę [Unshelve]. *)
(** * Taktyki do radzenia sobie z typami zależnymi (TODO) *)
(** Opisać taktyki [dependent induction], [dependent inversion],
[dependent destruction], [dependent rewrite] etc. *)
(** * Dodatkowe ćwiczenia *)
(** **** Ćwiczenie (assert) *)
(** Znasz już taktyki [assert], [cut] i [specialize]. Okazuje się, że dwie
ostatnie są jedynie wariantami taktyki [assert]. Przeczytaj w manualu
opis taktyki [assert] i wszystkich jej wariantów. *)
(** **** Ćwiczenie (easy i now) *)
(** Taktykami, których nie miałem nigdy okazji użyć, są [easy] i jej
wariant [now]. Przeczytaj ich opisy w manualu. Zbadaj, czy są do
czegokolwiek przydatne oraz czy są wygodne w porównaniu z innymi
taktykami służącymi do podobnych celów. *)
(** **** Ćwiczenie (inversion_sigma) *)
(** Przeczytaj w manualu o wariantach taktyki [inversion]. Szczególnie
interesująca wydaje się taktyka [inversion_sigma], która pojawiła
się w wersji 8.7 Coqa. Zbadaj ją. Wymyśl jakiś przykład jej użycia. *)
(** **** Ćwiczenie (pattern) *)
(** Przypomnijmy, że podstawą wszelkich obliczeń w Coqu jest redkucja
beta. Redukuje ona aplikację funkcji, np. [(fun n : nat => 2 * n) 42]
betaredukuje się do [2 * 42]. Jej wykonywanie jest jednym z głównych
zadań taktyk obliczeniowych.
Przeciwieństwem redukcji beta jest ekspansja beta. Pozwala ona zamienić
dowolny term na aplikację jakiejś funkcji do jakiegoś argumentu, np.
term [2 * 42] można betaekspandować do [(fun n : nat => 2 * n) 42].
O ile redukcja beta jest trywialna do automatycznego wykonania, o tyle
ekspansja beta już nie, gdyż występuje tu duża dowolność. Dla przykładu,
term [2 * 42] można też betaekspandować do [(fun n : nat => n * 42) 2].
Ekspansję beta implementuje taktyka [pattern]. Rozumowanie za jej pomocą
nie jest zbyt częstne, ale niemniej jednak kilka razy mi się przydało.
Przeczytaj opis taktyki [pattern] w manuaulu.
TODO: być może ćwiczenie to warto byłoby rozszerzyć do pełnoprawnego
podrozdziału. *)
(** **** Ćwiczenie (arytmetyka) *)
(** Poza taktykami radzącymi sobie z pierścieniami i ciałami jest też wiele
taktyk do walki z arytmetyką. Poza omówioną już taktyką [omega] są to
[lia], [nia], [lra], [nra]. Nazwy taktyk można zdekodować w następujący
sposób:
- l — linear
- n — nonlinar
- i — integer
- r — real/rational
- a — arithmetic *)
(** Przeczytaj w
#<a class='link' href='https://coq.inria.fr/refman/addendum/micromega.html'>
manualu</a>#, co one robią. *)
(** **** Ćwiczenie (wyższa magia) *)
(** Spróbuj ogarnąć, co robią taktyki [nsatz], [psatz] i [fourier]. *)
(** * Inne języki taktyk *)
(** Ltac w pewnym sensie nie jest jedynym językiem taktyk, jakiego możemy
użyć do dowodzenia w Coqu — są inne. Głównymi konkurentami Ltaca są:
- #<a class='link' href='https://gmalecha.github.io/reflections/2016/rtac-technical-overview'>
Rtac</a>#
- #<a class='link' href='https://plv.mpi-sws.org/mtac/'>Mtac</a>#
- #<a class='link' href='https://coq.inria.fr/refman/proof-engine/ssreflect-proof-language.html'>
ssreflect</a># (patrz też:
#<a class='link' href='https://math-comp.github.io/math-comp/'>
Mathematical Components Books</a>#) *)
(** Pierwsze dwa, [Rtac] i [Mtac], faktycznie są osobnymi językami taktyk,
znacznie różniącymi się od Ltaca. Nie będziemy się nimi zajmować,
gdyż ich droga do praktycznej użyteczności jest jeszcze dość długa.
ssreflect to nieco inna bajka. Nie jest on w zasadzie osobnym językiem
taktyk, lecz jest oparty na Ltacu. Różni się on od niego filozofią,
podstawowym zestawem taktyk i stylem dowodzenia. Od wersji 8.7 Coqa
język ten jet dostępny w bibliotece standardowej, mimo że nie jest z
nią w pełni kompatybilny. *)
(** **** Ćwiczenie (ssreflect) *)
(** Najbardziej wartościowym moim zdaniem elementem języka ssreflect jest
taktyka [rewrite], dużo potężniejsza od tej opisanej w tym rozdziale.
Jest ona warta uwagi, gdyż:
- daje jeszcze większą kontrolę nad przepisywaniem, niż standardowa
taktyka [rewrite]
- pozwala łączyć kroki przepisywania z odwijaniem definicji i wykonywaniem
obliczeń, a więc zastępuje taktyki [unfold], [fold], [change], [replace],
[cbn], [cbv], [simpl], etc.
- daje większe możliwości radzenia sobie z generowanymi przez siebie
podcelami *)
(** Przeczytaj rozdział manuala opisujący język ssreflect. Jeżeli nie
chce ci się tego robić, zapoznaj się chociaż z jego taktyką [rewrite]. *)
(** * Konkluzja *)
(** W niniejszym rozdziale przyjrzeliśmy się bliżej znacznej części Coqowych
taktyk. Moje ich opisanie nie jest aż tak kompletne i szczegółowe jak to
z manuala, ale nadrabia (mam nadzieję) wplecionymi w tekst przykładami i
zadaniami. Jeżeli jednak uważasz je za upośledzone, nie jesteś jeszcze
stracony! Alternatywne opisy niektórych taktyk dostępne są też tu:
- #<a class='link' href='https://pjreddie.com/coq-tactics/'>
pjreddie.com/coq-tactics/
</a>#
- #<a class='link'
href='https://cs.cornell.edu/courses/cs3110/2017fa/a5/coq-tactics-cheatsheet.html'>
cs.cornell.edu/courses/cs3110/2017fa/a5/coq-tactics-cheatsheet.html
</a>#
- #<a class='link' href='https://typesofnote.com/posts/coq-cheat-sheet.html'>
typesofnote.com/posts/coq-cheat-sheet.html
</a># *)
(** Poznawszy podstawy Ltaca oraz całe zoo przeróżnych taktyk, do zostania
pełnoprawnym inżynierem dowodu (ang. proof engineer, ukute przez analogię
do software engineer) brakuje ci jeszcze tylko umiejętności dowodzenia
przez reflekcję, którą zajmiemy się już niedługo. *)
|
myInput <- read.csv("processed_data/processed_1e3_5kingdoms.csv", stringsAsFactors = FALSE) #yours will be different
myInput <- myInput[-3] #remove SpeciesID from ML models #yours will be different
#recode 3 kingdoms (archaea, bacteria, eukaryotes) as factors
# myInput$Kingdom <- factor(myInput$Kingdom, levels = c("arc", "bct", "euk"), labels = c("archaea", "bacteria", "eukaryote"))
#recode 4 kingdoms (archaea, bacteria, eukaryotes, viruses) as factors
# myInput$Kingdom <- factor(myInput$Kingdom, levels = c("arc", "bct", "euk", "vrl"), labels = c("archaea", "bacteria", "eukaryote", "virus"))
#recode 5 kingdoms (archaea, bacteria, eukaryotes, viruses, phages) as factors
myInput$Kingdom <- factor(myInput$Kingdom, levels = c("arc", "bct", "euk", "vrl", "phg"), labels = c("archaea", "bacteria", "eukaryote", "virus", "bacteriophage"))
#inspect
#> table(myInput$Kingdom)
#archaea bacteria eukaryote
#65 1288 1036
#---------------------random sampling for training/test data---------------------
set.seed(123)
# train_sample <- sample(2389, 1911) #80% training split for 3 kingdoms
# train_sample <- sample(9937, 2485) #80% training split for 4 kingdoms
train_sample <- sample(10406, 8324) #80% training split for 5 kingdoms
myInput_train <- myInput[train_sample, ]
myInput_train_labels <- myInput[train_sample, 1] #Kingdom labels only
myInput_train <- subset(myInput_train, select = -c(Kingdom, DNAtype, Ncodons, SpeciesName))
myInput_test <- myInput[-train_sample, ]
myInput_test_labels <- myInput[-train_sample, 1] #Kingdom labels only
myInput_test <- subset(myInput_test, select = -c(Kingdom, DNAtype, Ncodons, SpeciesName))
#---------------------k-NN---------------------
#install.packages("class")
# 3 kingdoms (arc, bct, euk) [try different values of k]
myInput_test_pred <- class::knn(train = myInput_train, test = myInput_test, cl = myInput_train_labels, k = 1)
# 4 kingdoms (arc, bct, euk, vrl) [try different values of k]
myInput_test_pred <- class::knn(train = myInput_train, test = myInput_test, cl = myInput_train_labels, k = 4)
# 4 kingdoms (arc, bct, euk, vrl, phg) [try different values of k]
myInput_test_pred <- class::knn(train = myInput_train, test = myInput_test, cl = myInput_train_labels, k = 5, prob = TRUE)
prob <- attr(myInput_test_pred, "prob")
#install.packages("gmodels")
gmodels::CrossTable(x = myInput_test_labels, y = myInput_test_pred, prop.chisq = FALSE)
|
function [result coeff] = RS_PF_OLS_Wald(y,x1,x2)
% Calculates OLS Wald-Test
% H0: beta=0 in the model
% y = x1*beta+x2*gamma+eps with HAC consistent var-covar
% If want to test all coefficients, simply use (y,x1) and do not include x2
q = 0;
n = size(y,1);
p = size(x1,2);
if nargin>2;
q = size(x2,2);
x = [x1,x2];
R = [eye(p),zeros(p,q)];
else
x = x1;
R = eye(p);
end;
coeff = ((inv(x'*x))*(x'*y));
nlag = round(n^(1/4));
% Compute Newey-West adjusted heteroscedastic-serial consistent
% least-squares regression
nwresult = bear.RS_PF_nwest(y,x,nlag);
varbetahat = nwresult.vcv;
result = (R*coeff)'/(R*varbetahat*R')*R*coeff; |
module SauterSchwabQuadrature
using LinearAlgebra
using CompScienceMeshes
using StaticArrays
export sauterschwab_parameterized
export SauterSchwabStrategy, CommonFace, CommonEdge, CommonVertex, PositiveDistance
export generate_integrand_uv
"""
Compute interaction integrals using the quadrature introduced in [1].
sauterschwab_parameterized(integrand, strategy)
Here, `integrand` is the pull-back of the integrand into the barycentric
parameter domain of the two triangles that define the integration domain. Note
that here we use (for a planar triangle) the representation:
x = x[3] + u*(x[1]-x[3]) + v*(x[2]-x[3])
with `u` ranging from 0 to 1 and `v` ranging from 0 to 1-`u`. This parameter
domain and representation is different from the one used in [1].
The second argument 'strategy' is an object whose type is one of
- `CommonFace`
- `CommonEdge`
- `CommonVertex`
- `PositiveDistance`
according to the configuration of the two triangular patches defining the
domain of integration. The constructors of these classes take a single
argument `acc` that defines the number of quadrature points along each of the
four axes of the final rectangular (ξ,η) integration domain (see [1], Ch 5).
[1] Sauter. Schwwab, 'Boundary Element Methods', Springer Berlin Heidelberg, 2011
"""
function sauterschwab_parameterized end
include("pulled_back_integrands.jl")
include("sauterschwabintegral.jl")
include("reorder_vertices.jl")
include("parametric_kernel_generator.jl")
end
|
#ifndef OPENMC_TALLIES_FILTER_CELL_INSTANCE_H
#define OPENMC_TALLIES_FILTER_CELL_INSTANCE_H
#include <cstdint>
#include <unordered_map>
#include <vector>
#include <gsl/gsl>
#include "openmc/cell.h"
#include "openmc/tallies/filter.h"
namespace openmc {
//==============================================================================
//! Specifies cell instances that tally events reside in.
//==============================================================================
class CellInstanceFilter : public Filter {
public:
//----------------------------------------------------------------------------
// Constructors, destructors
CellInstanceFilter() = default;
CellInstanceFilter(gsl::span<CellInstance> instances);
~CellInstanceFilter() = default;
//----------------------------------------------------------------------------
// Methods
std::string type() const override {return "cellinstance";}
void from_xml(pugi::xml_node node) override;
void get_all_bins(const Particle* p, int estimator, FilterMatch& match)
const override;
void to_statepoint(hid_t filter_group) const override;
std::string text_label(int bin) const override;
//----------------------------------------------------------------------------
// Accessors
const std::vector<CellInstance>& cell_instances() const { return cell_instances_; }
void set_cell_instances(gsl::span<CellInstance> instances);
private:
//----------------------------------------------------------------------------
// Data members
//! The indices of the cells binned by this filter.
std::vector<CellInstance> cell_instances_;
//! A map from cell/instance indices to filter bin indices.
std::unordered_map<CellInstance, gsl::index, CellInstanceHash> map_;
};
} // namespace openmc
#endif // OPENMC_TALLIES_FILTER_CELL_INSTANCE_H
|
context("applyTbxByOverlap checks")
data(methylKit)
file.list=list( system.file("extdata", "test1.myCpG.txt", package = "methylKit"),
system.file("extdata", "test2.myCpG.txt", package = "methylKit"),
system.file("extdata", "control1.myCpG.txt", package = "methylKit"),
system.file("extdata", "control2.myCpG.txt", package = "methylKit") )
methylRawListDB.obj=methRead(file.list,
sample.id=list("test1","test2","ctrl1","ctrl2"),
assembly="hg18",treatment=c(1,1,0,0),
dbtype = "tabix",dbdir = "methylDB")
methylBaseDB.obj=unite(methylRawListDB.obj)
methylDiffDB.obj = calculateDiffMeth(methylBaseDB.obj)
# define the windows of interest as a GRanges object, this can be any set
# of genomic locations
library(GenomicRanges)
my.win=GRanges(seqnames="chr21",
ranges=IRanges(start=seq(from=9764513,by=10000,length.out=20),width=5000) )
res.df <- getTabixByOverlap(tbxFile = methylBaseDB.obj@dbpath,granges = my.win,return.type = "data.frame")
res.dt <- getTabixByOverlap(tbxFile = methylBaseDB.obj@dbpath,granges = my.win,return.type = "data.table")
f <- function(x) return(x)
tmp1=applyTbxByOverlap(tbxFile = methylBaseDB.obj@dbpath,
ranges=my.win,
chunk.size=10,
return.type="data.table",FUN = f)
tmp2=applyTbxByOverlap(tbxFile = methylBaseDB.obj@dbpath,
ranges=my.win,
chunk.size=10,
return.type="data.frame",FUN = f)
tmp3=applyTbxByOverlap(tbxFile = methylBaseDB.obj@dbpath,
ranges=my.win,
chunk.size=10,
dir = dirname(methylBaseDB.obj@dbpath),
filename = paste0(basename(methylBaseDB.obj@dbpath),".out"),
return.type="tabix",FUN = f)
test_that("check if applyTbxByOverlap returns expected results for different return types." ,{
expect_identical(tmp1,res.dt)
expect_identical(tmp2,res.df)
expect_identical(headTabix(tmp3,nrow = nrow(res.dt),return.type = "data.table"),res.dt)
})
unlink("tests/testthat/methylDB",recursive = TRUE) |
/-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import group_theory.group_action.defs
/-!
# Sigma instances for additive and multiplicative actions
This file defines instances for arbitrary sum of additive and multiplicative actions.
## See also
* `group_theory.group_action.pi`
* `group_theory.group_action.prod`
* `group_theory.group_action.sum`
-/
variables {ι : Type*} {M N : Type*} {α : ι → Type*}
namespace sigma
section has_smul
variables [Π i, has_smul M (α i)] [Π i, has_smul N (α i)] (a : M) (i : ι) (b : α i)
(x : Σ i, α i)
@[to_additive sigma.has_vadd] instance : has_smul M (Σ i, α i) := ⟨λ a, sigma.map id $ λ i, (•) a⟩
@[to_additive] lemma smul_def : a • x = x.map id (λ i, (•) a) := rfl
@[simp, to_additive] lemma smul_mk : a • mk i b = ⟨i, a • b⟩ := rfl
instance [has_smul M N] [Π i, is_scalar_tower M N (α i)] : is_scalar_tower M N (Σ i, α i) :=
⟨λ a b x, by { cases x, rw [smul_mk, smul_mk, smul_mk, smul_assoc] }⟩
@[to_additive] instance [Π i, smul_comm_class M N (α i)] : smul_comm_class M N (Σ i, α i) :=
⟨λ a b x, by { cases x, rw [smul_mk, smul_mk, smul_mk, smul_mk, smul_comm] }⟩
instance [Π i, has_smul Mᵐᵒᵖ (α i)] [Π i, is_central_scalar M (α i)] :
is_central_scalar M (Σ i, α i) :=
⟨λ a x, by { cases x, rw [smul_mk, smul_mk, op_smul_eq_smul] }⟩
/-- This is not an instance because `i` becomes a metavariable. -/
@[to_additive "This is not an instance because `i` becomes a metavariable."]
protected lemma has_faithful_smul' [has_faithful_smul M (α i)] : has_faithful_smul M (Σ i, α i) :=
⟨λ x y h, eq_of_smul_eq_smul $ λ a : α i, heq_iff_eq.1 (ext_iff.1 $ h $ mk i a).2⟩
@[to_additive] instance [nonempty ι] [Π i, has_faithful_smul M (α i)] :
has_faithful_smul M (Σ i, α i) :=
nonempty.elim ‹_› $ λ i, sigma.has_faithful_smul' i
end has_smul
@[to_additive] instance {m : monoid M} [Π i, mul_action M (α i)] : mul_action M (Σ i, α i) :=
{ mul_smul := λ a b x, by { cases x, rw [smul_mk, smul_mk, smul_mk, mul_smul] },
one_smul := λ x, by { cases x, rw [smul_mk, one_smul] } }
end sigma
|
module Open where
open import bool
open import nat
open import product
open import sum
open import functor
data Row : Set₁ where
Empty : Row
Ty : Set → Row
Prod : Row → Row → Row
infixr 19 _♯_
_′ = Ty
_♯_ = Prod
all : Row → Set
all Empty = ⊤
all (Ty x) = x
all (Prod r₁ r₂) = (all r₁) × (all r₂)
one : Row → Set
one Empty = ⊥
one (Ty x) = x
one (Prod r₁ r₂) = (one r₁) ⊎ (one r₂)
_⊗_ : {A B : Row} → all A → all B → all (A ♯ B)
_⊗_ p₁ p₂ = p₁ , p₂
_&_ : {A : Set}{B : Row} → A → all B → all (A ′ ♯ B)
_&_ {A}{B} = _⊗_ {A ′}{B}
_⊕_ : {A B : Row} → (one A) ⊎ (one B) → one (A ♯ B)
_⊕_ p = p
⊕inj₁ : {A B : Row} → one A → one (A ♯ B)
⊕inj₁ = inj₁
⊕inj₂ : {A B : Row} → one B → one (A ♯ B)
⊕inj₂ = inj₂
inj : {A : Set}{B : Row} → A → one (A ′ ♯ B)
inj {A}{B} = ⊕inj₁ {A ′}{B}
test₁ : all (ℕ ′ ♯ 𝔹 ′ ♯ Empty)
test₁ = _&_ {ℕ}{𝔹 ′ ♯ Empty} 1 (_&_ {𝔹}{Empty} tt triv)
|
[STATEMENT]
lemma even_or_odd:
fixes n :: nat
shows "\<exists>i. (n = 2*i) \<or> (n=2*i+1)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<exists>i. n = 2 * i \<or> n = 2 * i + 1
[PROOF STEP]
by (induct n) (presburger)+ |
From Paco Require Export paconotation_internal paconotation.
Set Implicit Arguments.
(** * Tactic support for [paco] library
This file defines tactics for converting the conclusion to the right form so
that the accumulation lemmas can be usefully applied. These tactics are used
in both internal and external approaches.
Our main tactic, [pcofix], is defined at the end of the file and
works for predicates of arity up to 14.
*)
(** ** Internal tactics *)
Ltac get_concl := lazymatch goal with [ |- ?G ] => G end.
Inductive _paco_mark := _paco_mark_cons.
Inductive _paco_foo := _paco_foo_cons.
Definition _paco_id {A} (a : A) : A := a.
Ltac paco_generalize_hyp mark :=
let y := fresh "_paco_rel_" in
match goal with
| [x: ?A |- _] =>
match A with
| mark => clear x
| _ => intro y;
match type of y with
| context[x] => revert x y;
match goal with [|-forall x, @?f x -> _] =>
intros x y; generalize (ex_intro f x y)
end
| _ => generalize (conj (ex_intro _ x _paco_foo_cons) y)
end; clear x y; paco_generalize_hyp mark
end
end.
Ltac paco_destruct_hyp mark :=
match goal with
| [x: ?A |- _] =>
match A with
| mark => idtac
| _paco_foo => clear x; paco_destruct_hyp mark
| exists n, ?p => let n' := fresh n in destruct x as (n', x); paco_destruct_hyp mark
| ?p /\ ?q => let x' := fresh x in destruct x as (x,x'); paco_destruct_hyp mark
end
end.
Ltac paco_revert_hyp mark :=
match goal with [x: ?A |- _] =>
match A with
| mark => clear x
| _ => revert x; paco_revert_hyp mark
end end.
Ltac paco_post_var INC pr cr := let TMP := fresh "_paco_tmp_" in
repeat (
match goal with [H: context f [pr] |-_] =>
let cih := context f [cr] in rename H into TMP;
assert(H : cih) by (repeat intro; eapply INC, TMP; eassumption); clear TMP
end);
clear INC pr.
Ltac paco_rename_last :=
let x := fresh "_paco_xxx_" in match goal with [H: _|-_] => rename H into x end.
Ltac paco_simp_hyp CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
try (reflexivity);
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_revert_hyp _paco_mark
].
Ltac paco_ren_r nr cr :=
first [rename cr into nr | let nr := fresh nr in rename cr into nr].
Ltac paco_ren_pr pr cr := rename cr into pr.
Ltac paco_revert :=
match goal with [H: _ |- _] => revert H end.
Section SIG0.
(** ** Signatures *)
Record sig0T :=
exist0T {
}.
Definition uncurry0 (R: rel0): rel1 sig0T :=
fun x => R.
Definition curry0 (R: rel1 sig0T): rel0 :=
R (@exist0T).
Lemma uncurry_map0 r0 r1 (LE : r0 <0== r1) : uncurry0 r0 <1== uncurry0 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev0 r0 r1 (LE: uncurry0 r0 <1== uncurry0 r1) : r0 <0== r1.
Proof.
red; intros. apply (LE (@exist0T) PR).
Qed.
Lemma curry_map0 r0 r1 (LE: r0 <1== r1) : curry0 r0 <0== curry0 r1.
Proof.
red; intros. apply (LE (@exist0T) PR).
Qed.
Lemma curry_map_rev0 r0 r1 (LE: curry0 r0 <0== curry0 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_0 r : curry0 (uncurry0 r) <0== r.
Proof. unfold le0. intros. apply PR. Qed.
Lemma uncurry_bij2_0 r : r <0== curry0 (uncurry0 r).
Proof. unfold le0. intros. apply PR. Qed.
Lemma curry_bij1_0 r : uncurry0 (curry0 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_0 r : r <1== uncurry0 (curry0 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_0 r0 r1 (LE: uncurry0 r0 <1== r1) : r0 <0== curry0 r1.
Proof.
apply uncurry_map_rev0. eapply le1_trans; [apply LE|]. apply curry_bij2_0.
Qed.
Lemma uncurry_adjoint2_0 r0 r1 (LE: r0 <0== curry0 r1) : uncurry0 r0 <1== r1.
Proof.
apply curry_map_rev0. eapply le0_trans; [|apply LE]. apply uncurry_bij2_0.
Qed.
Lemma curry_adjoint1_0 r0 r1 (LE: curry0 r0 <0== r1) : r0 <1== uncurry0 r1.
Proof.
apply curry_map_rev0. eapply le0_trans; [apply LE|]. apply uncurry_bij2_0.
Qed.
Lemma curry_adjoint2_0 r0 r1 (LE: r0 <1== uncurry0 r1) : curry0 r0 <0== r1.
Proof.
apply uncurry_map_rev0. eapply le1_trans; [|apply LE]. apply curry_bij1_0.
Qed.
End SIG0.
Section SIG1.
Variable T0 : Type.
(** ** Signatures *)
Record sig1T :=
exist1T {
proj1T0: @T0;
}.
Definition uncurry1 (R: rel1 T0): rel1 sig1T :=
fun x => R (proj1T0 x).
Definition curry1 (R: rel1 sig1T): rel1 T0 :=
fun x0 => R (@exist1T x0).
Lemma uncurry_map1 r0 r1 (LE : r0 <1== r1) : uncurry1 r0 <1== uncurry1 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev1 r0 r1 (LE: uncurry1 r0 <1== uncurry1 r1) : r0 <1== r1.
Proof.
red; intros. apply (LE (@exist1T x0) PR).
Qed.
Lemma curry_map1 r0 r1 (LE: r0 <1== r1) : curry1 r0 <1== curry1 r1.
Proof.
red; intros. apply (LE (@exist1T x0) PR).
Qed.
Lemma curry_map_rev1 r0 r1 (LE: curry1 r0 <1== curry1 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_1 r : curry1 (uncurry1 r) <1== r.
Proof. unfold le1. intros. apply PR. Qed.
Lemma uncurry_bij2_1 r : r <1== curry1 (uncurry1 r).
Proof. unfold le1. intros. apply PR. Qed.
Lemma curry_bij1_1 r : uncurry1 (curry1 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_1 r : r <1== uncurry1 (curry1 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_1 r0 r1 (LE: uncurry1 r0 <1== r1) : r0 <1== curry1 r1.
Proof.
apply uncurry_map_rev1. eapply le1_trans; [apply LE|]. apply curry_bij2_1.
Qed.
Lemma uncurry_adjoint2_1 r0 r1 (LE: r0 <1== curry1 r1) : uncurry1 r0 <1== r1.
Proof.
apply curry_map_rev1. eapply le1_trans; [|apply LE]. apply uncurry_bij2_1.
Qed.
Lemma curry_adjoint1_1 r0 r1 (LE: curry1 r0 <1== r1) : r0 <1== uncurry1 r1.
Proof.
apply curry_map_rev1. eapply le1_trans; [apply LE|]. apply uncurry_bij2_1.
Qed.
Lemma curry_adjoint2_1 r0 r1 (LE: r0 <1== uncurry1 r1) : curry1 r0 <1== r1.
Proof.
apply uncurry_map_rev1. eapply le1_trans; [|apply LE]. apply curry_bij1_1.
Qed.
End SIG1.
Section SIG2.
Variable T0 : Type.
Variable T1 : forall (x0: @T0), Type.
(** ** Signatures *)
Record sig2T :=
exist2T {
proj2T0: @T0;
proj2T1: @T1 proj2T0;
}.
Definition uncurry2 (R: rel2 T0 T1): rel1 sig2T :=
fun x => R (proj2T0 x) (proj2T1 x).
Definition curry2 (R: rel1 sig2T): rel2 T0 T1 :=
fun x0 x1 => R (@exist2T x0 x1).
Lemma uncurry_map2 r0 r1 (LE : r0 <2== r1) : uncurry2 r0 <1== uncurry2 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev2 r0 r1 (LE: uncurry2 r0 <1== uncurry2 r1) : r0 <2== r1.
Proof.
red; intros. apply (LE (@exist2T x0 x1) PR).
Qed.
Lemma curry_map2 r0 r1 (LE: r0 <1== r1) : curry2 r0 <2== curry2 r1.
Proof.
red; intros. apply (LE (@exist2T x0 x1) PR).
Qed.
Lemma curry_map_rev2 r0 r1 (LE: curry2 r0 <2== curry2 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_2 r : curry2 (uncurry2 r) <2== r.
Proof. unfold le2. intros. apply PR. Qed.
Lemma uncurry_bij2_2 r : r <2== curry2 (uncurry2 r).
Proof. unfold le2. intros. apply PR. Qed.
Lemma curry_bij1_2 r : uncurry2 (curry2 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_2 r : r <1== uncurry2 (curry2 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_2 r0 r1 (LE: uncurry2 r0 <1== r1) : r0 <2== curry2 r1.
Proof.
apply uncurry_map_rev2. eapply le1_trans; [apply LE|]. apply curry_bij2_2.
Qed.
Lemma uncurry_adjoint2_2 r0 r1 (LE: r0 <2== curry2 r1) : uncurry2 r0 <1== r1.
Proof.
apply curry_map_rev2. eapply le2_trans; [|apply LE]. apply uncurry_bij2_2.
Qed.
Lemma curry_adjoint1_2 r0 r1 (LE: curry2 r0 <2== r1) : r0 <1== uncurry2 r1.
Proof.
apply curry_map_rev2. eapply le2_trans; [apply LE|]. apply uncurry_bij2_2.
Qed.
Lemma curry_adjoint2_2 r0 r1 (LE: r0 <1== uncurry2 r1) : curry2 r0 <2== r1.
Proof.
apply uncurry_map_rev2. eapply le1_trans; [|apply LE]. apply curry_bij1_2.
Qed.
End SIG2.
Section SIG3.
Variable T0 : Type.
Variable T1 : forall (x0: @T0), Type.
Variable T2 : forall (x0: @T0) (x1: @T1 x0), Type.
(** ** Signatures *)
Record sig3T :=
exist3T {
proj3T0: @T0;
proj3T1: @T1 proj3T0;
proj3T2: @T2 proj3T0 proj3T1;
}.
Definition uncurry3 (R: rel3 T0 T1 T2): rel1 sig3T :=
fun x => R (proj3T0 x) (proj3T1 x) (proj3T2 x).
Definition curry3 (R: rel1 sig3T): rel3 T0 T1 T2 :=
fun x0 x1 x2 => R (@exist3T x0 x1 x2).
Lemma uncurry_map3 r0 r1 (LE : r0 <3== r1) : uncurry3 r0 <1== uncurry3 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev3 r0 r1 (LE: uncurry3 r0 <1== uncurry3 r1) : r0 <3== r1.
Proof.
red; intros. apply (LE (@exist3T x0 x1 x2) PR).
Qed.
Lemma curry_map3 r0 r1 (LE: r0 <1== r1) : curry3 r0 <3== curry3 r1.
Proof.
red; intros. apply (LE (@exist3T x0 x1 x2) PR).
Qed.
Lemma curry_map_rev3 r0 r1 (LE: curry3 r0 <3== curry3 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_3 r : curry3 (uncurry3 r) <3== r.
Proof. unfold le3. intros. apply PR. Qed.
Lemma uncurry_bij2_3 r : r <3== curry3 (uncurry3 r).
Proof. unfold le3. intros. apply PR. Qed.
Lemma curry_bij1_3 r : uncurry3 (curry3 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_3 r : r <1== uncurry3 (curry3 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_3 r0 r1 (LE: uncurry3 r0 <1== r1) : r0 <3== curry3 r1.
Proof.
apply uncurry_map_rev3. eapply le1_trans; [apply LE|]. apply curry_bij2_3.
Qed.
Lemma uncurry_adjoint2_3 r0 r1 (LE: r0 <3== curry3 r1) : uncurry3 r0 <1== r1.
Proof.
apply curry_map_rev3. eapply le3_trans; [|apply LE]. apply uncurry_bij2_3.
Qed.
Lemma curry_adjoint1_3 r0 r1 (LE: curry3 r0 <3== r1) : r0 <1== uncurry3 r1.
Proof.
apply curry_map_rev3. eapply le3_trans; [apply LE|]. apply uncurry_bij2_3.
Qed.
Lemma curry_adjoint2_3 r0 r1 (LE: r0 <1== uncurry3 r1) : curry3 r0 <3== r1.
Proof.
apply uncurry_map_rev3. eapply le1_trans; [|apply LE]. apply curry_bij1_3.
Qed.
End SIG3.
Section SIG4.
Variable T0 : Type.
Variable T1 : forall (x0: @T0), Type.
Variable T2 : forall (x0: @T0) (x1: @T1 x0), Type.
Variable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.
(** ** Signatures *)
Record sig4T :=
exist4T {
proj4T0: @T0;
proj4T1: @T1 proj4T0;
proj4T2: @T2 proj4T0 proj4T1;
proj4T3: @T3 proj4T0 proj4T1 proj4T2;
}.
Definition uncurry4 (R: rel4 T0 T1 T2 T3): rel1 sig4T :=
fun x => R (proj4T0 x) (proj4T1 x) (proj4T2 x) (proj4T3 x).
Definition curry4 (R: rel1 sig4T): rel4 T0 T1 T2 T3 :=
fun x0 x1 x2 x3 => R (@exist4T x0 x1 x2 x3).
Lemma uncurry_map4 r0 r1 (LE : r0 <4== r1) : uncurry4 r0 <1== uncurry4 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev4 r0 r1 (LE: uncurry4 r0 <1== uncurry4 r1) : r0 <4== r1.
Proof.
red; intros. apply (LE (@exist4T x0 x1 x2 x3) PR).
Qed.
Lemma curry_map4 r0 r1 (LE: r0 <1== r1) : curry4 r0 <4== curry4 r1.
Proof.
red; intros. apply (LE (@exist4T x0 x1 x2 x3) PR).
Qed.
Lemma curry_map_rev4 r0 r1 (LE: curry4 r0 <4== curry4 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_4 r : curry4 (uncurry4 r) <4== r.
Proof. unfold le4. intros. apply PR. Qed.
Lemma uncurry_bij2_4 r : r <4== curry4 (uncurry4 r).
Proof. unfold le4. intros. apply PR. Qed.
Lemma curry_bij1_4 r : uncurry4 (curry4 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_4 r : r <1== uncurry4 (curry4 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_4 r0 r1 (LE: uncurry4 r0 <1== r1) : r0 <4== curry4 r1.
Proof.
apply uncurry_map_rev4. eapply le1_trans; [apply LE|]. apply curry_bij2_4.
Qed.
Lemma uncurry_adjoint2_4 r0 r1 (LE: r0 <4== curry4 r1) : uncurry4 r0 <1== r1.
Proof.
apply curry_map_rev4. eapply le4_trans; [|apply LE]. apply uncurry_bij2_4.
Qed.
Lemma curry_adjoint1_4 r0 r1 (LE: curry4 r0 <4== r1) : r0 <1== uncurry4 r1.
Proof.
apply curry_map_rev4. eapply le4_trans; [apply LE|]. apply uncurry_bij2_4.
Qed.
Lemma curry_adjoint2_4 r0 r1 (LE: r0 <1== uncurry4 r1) : curry4 r0 <4== r1.
Proof.
apply uncurry_map_rev4. eapply le1_trans; [|apply LE]. apply curry_bij1_4.
Qed.
End SIG4.
Section SIG5.
Variable T0 : Type.
Variable T1 : forall (x0: @T0), Type.
Variable T2 : forall (x0: @T0) (x1: @T1 x0), Type.
Variable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.
Variable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.
(** ** Signatures *)
Record sig5T :=
exist5T {
proj5T0: @T0;
proj5T1: @T1 proj5T0;
proj5T2: @T2 proj5T0 proj5T1;
proj5T3: @T3 proj5T0 proj5T1 proj5T2;
proj5T4: @T4 proj5T0 proj5T1 proj5T2 proj5T3;
}.
Definition uncurry5 (R: rel5 T0 T1 T2 T3 T4): rel1 sig5T :=
fun x => R (proj5T0 x) (proj5T1 x) (proj5T2 x) (proj5T3 x) (proj5T4 x).
Definition curry5 (R: rel1 sig5T): rel5 T0 T1 T2 T3 T4 :=
fun x0 x1 x2 x3 x4 => R (@exist5T x0 x1 x2 x3 x4).
Lemma uncurry_map5 r0 r1 (LE : r0 <5== r1) : uncurry5 r0 <1== uncurry5 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev5 r0 r1 (LE: uncurry5 r0 <1== uncurry5 r1) : r0 <5== r1.
Proof.
red; intros. apply (LE (@exist5T x0 x1 x2 x3 x4) PR).
Qed.
Lemma curry_map5 r0 r1 (LE: r0 <1== r1) : curry5 r0 <5== curry5 r1.
Proof.
red; intros. apply (LE (@exist5T x0 x1 x2 x3 x4) PR).
Qed.
Lemma curry_map_rev5 r0 r1 (LE: curry5 r0 <5== curry5 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_5 r : curry5 (uncurry5 r) <5== r.
Proof. unfold le5. intros. apply PR. Qed.
Lemma uncurry_bij2_5 r : r <5== curry5 (uncurry5 r).
Proof. unfold le5. intros. apply PR. Qed.
Lemma curry_bij1_5 r : uncurry5 (curry5 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_5 r : r <1== uncurry5 (curry5 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_5 r0 r1 (LE: uncurry5 r0 <1== r1) : r0 <5== curry5 r1.
Proof.
apply uncurry_map_rev5. eapply le1_trans; [apply LE|]. apply curry_bij2_5.
Qed.
Lemma uncurry_adjoint2_5 r0 r1 (LE: r0 <5== curry5 r1) : uncurry5 r0 <1== r1.
Proof.
apply curry_map_rev5. eapply le5_trans; [|apply LE]. apply uncurry_bij2_5.
Qed.
Lemma curry_adjoint1_5 r0 r1 (LE: curry5 r0 <5== r1) : r0 <1== uncurry5 r1.
Proof.
apply curry_map_rev5. eapply le5_trans; [apply LE|]. apply uncurry_bij2_5.
Qed.
Lemma curry_adjoint2_5 r0 r1 (LE: r0 <1== uncurry5 r1) : curry5 r0 <5== r1.
Proof.
apply uncurry_map_rev5. eapply le1_trans; [|apply LE]. apply curry_bij1_5.
Qed.
End SIG5.
Section SIG6.
Variable T0 : Type.
Variable T1 : forall (x0: @T0), Type.
Variable T2 : forall (x0: @T0) (x1: @T1 x0), Type.
Variable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.
Variable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.
Variable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.
(** ** Signatures *)
Record sig6T :=
exist6T {
proj6T0: @T0;
proj6T1: @T1 proj6T0;
proj6T2: @T2 proj6T0 proj6T1;
proj6T3: @T3 proj6T0 proj6T1 proj6T2;
proj6T4: @T4 proj6T0 proj6T1 proj6T2 proj6T3;
proj6T5: @T5 proj6T0 proj6T1 proj6T2 proj6T3 proj6T4;
}.
Definition uncurry6 (R: rel6 T0 T1 T2 T3 T4 T5): rel1 sig6T :=
fun x => R (proj6T0 x) (proj6T1 x) (proj6T2 x) (proj6T3 x) (proj6T4 x) (proj6T5 x).
Definition curry6 (R: rel1 sig6T): rel6 T0 T1 T2 T3 T4 T5 :=
fun x0 x1 x2 x3 x4 x5 => R (@exist6T x0 x1 x2 x3 x4 x5).
Lemma uncurry_map6 r0 r1 (LE : r0 <6== r1) : uncurry6 r0 <1== uncurry6 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev6 r0 r1 (LE: uncurry6 r0 <1== uncurry6 r1) : r0 <6== r1.
Proof.
red; intros. apply (LE (@exist6T x0 x1 x2 x3 x4 x5) PR).
Qed.
Lemma curry_map6 r0 r1 (LE: r0 <1== r1) : curry6 r0 <6== curry6 r1.
Proof.
red; intros. apply (LE (@exist6T x0 x1 x2 x3 x4 x5) PR).
Qed.
Lemma curry_map_rev6 r0 r1 (LE: curry6 r0 <6== curry6 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_6 r : curry6 (uncurry6 r) <6== r.
Proof. unfold le6. intros. apply PR. Qed.
Lemma uncurry_bij2_6 r : r <6== curry6 (uncurry6 r).
Proof. unfold le6. intros. apply PR. Qed.
Lemma curry_bij1_6 r : uncurry6 (curry6 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_6 r : r <1== uncurry6 (curry6 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_6 r0 r1 (LE: uncurry6 r0 <1== r1) : r0 <6== curry6 r1.
Proof.
apply uncurry_map_rev6. eapply le1_trans; [apply LE|]. apply curry_bij2_6.
Qed.
Lemma uncurry_adjoint2_6 r0 r1 (LE: r0 <6== curry6 r1) : uncurry6 r0 <1== r1.
Proof.
apply curry_map_rev6. eapply le6_trans; [|apply LE]. apply uncurry_bij2_6.
Qed.
Lemma curry_adjoint1_6 r0 r1 (LE: curry6 r0 <6== r1) : r0 <1== uncurry6 r1.
Proof.
apply curry_map_rev6. eapply le6_trans; [apply LE|]. apply uncurry_bij2_6.
Qed.
Lemma curry_adjoint2_6 r0 r1 (LE: r0 <1== uncurry6 r1) : curry6 r0 <6== r1.
Proof.
apply uncurry_map_rev6. eapply le1_trans; [|apply LE]. apply curry_bij1_6.
Qed.
End SIG6.
Section SIG7.
Variable T0 : Type.
Variable T1 : forall (x0: @T0), Type.
Variable T2 : forall (x0: @T0) (x1: @T1 x0), Type.
Variable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.
Variable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.
Variable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.
Variable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.
(** ** Signatures *)
Record sig7T :=
exist7T {
proj7T0: @T0;
proj7T1: @T1 proj7T0;
proj7T2: @T2 proj7T0 proj7T1;
proj7T3: @T3 proj7T0 proj7T1 proj7T2;
proj7T4: @T4 proj7T0 proj7T1 proj7T2 proj7T3;
proj7T5: @T5 proj7T0 proj7T1 proj7T2 proj7T3 proj7T4;
proj7T6: @T6 proj7T0 proj7T1 proj7T2 proj7T3 proj7T4 proj7T5;
}.
Definition uncurry7 (R: rel7 T0 T1 T2 T3 T4 T5 T6): rel1 sig7T :=
fun x => R (proj7T0 x) (proj7T1 x) (proj7T2 x) (proj7T3 x) (proj7T4 x) (proj7T5 x) (proj7T6 x).
Definition curry7 (R: rel1 sig7T): rel7 T0 T1 T2 T3 T4 T5 T6 :=
fun x0 x1 x2 x3 x4 x5 x6 => R (@exist7T x0 x1 x2 x3 x4 x5 x6).
Lemma uncurry_map7 r0 r1 (LE : r0 <7== r1) : uncurry7 r0 <1== uncurry7 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev7 r0 r1 (LE: uncurry7 r0 <1== uncurry7 r1) : r0 <7== r1.
Proof.
red; intros. apply (LE (@exist7T x0 x1 x2 x3 x4 x5 x6) PR).
Qed.
Lemma curry_map7 r0 r1 (LE: r0 <1== r1) : curry7 r0 <7== curry7 r1.
Proof.
red; intros. apply (LE (@exist7T x0 x1 x2 x3 x4 x5 x6) PR).
Qed.
Lemma curry_map_rev7 r0 r1 (LE: curry7 r0 <7== curry7 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_7 r : curry7 (uncurry7 r) <7== r.
Proof. unfold le7. intros. apply PR. Qed.
Lemma uncurry_bij2_7 r : r <7== curry7 (uncurry7 r).
Proof. unfold le7. intros. apply PR. Qed.
Lemma curry_bij1_7 r : uncurry7 (curry7 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_7 r : r <1== uncurry7 (curry7 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_7 r0 r1 (LE: uncurry7 r0 <1== r1) : r0 <7== curry7 r1.
Proof.
apply uncurry_map_rev7. eapply le1_trans; [apply LE|]. apply curry_bij2_7.
Qed.
Lemma uncurry_adjoint2_7 r0 r1 (LE: r0 <7== curry7 r1) : uncurry7 r0 <1== r1.
Proof.
apply curry_map_rev7. eapply le7_trans; [|apply LE]. apply uncurry_bij2_7.
Qed.
Lemma curry_adjoint1_7 r0 r1 (LE: curry7 r0 <7== r1) : r0 <1== uncurry7 r1.
Proof.
apply curry_map_rev7. eapply le7_trans; [apply LE|]. apply uncurry_bij2_7.
Qed.
Lemma curry_adjoint2_7 r0 r1 (LE: r0 <1== uncurry7 r1) : curry7 r0 <7== r1.
Proof.
apply uncurry_map_rev7. eapply le1_trans; [|apply LE]. apply curry_bij1_7.
Qed.
End SIG7.
Section SIG8.
Variable T0 : Type.
Variable T1 : forall (x0: @T0), Type.
Variable T2 : forall (x0: @T0) (x1: @T1 x0), Type.
Variable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.
Variable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.
Variable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.
Variable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.
Variable T7 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5), Type.
(** ** Signatures *)
Record sig8T :=
exist8T {
proj8T0: @T0;
proj8T1: @T1 proj8T0;
proj8T2: @T2 proj8T0 proj8T1;
proj8T3: @T3 proj8T0 proj8T1 proj8T2;
proj8T4: @T4 proj8T0 proj8T1 proj8T2 proj8T3;
proj8T5: @T5 proj8T0 proj8T1 proj8T2 proj8T3 proj8T4;
proj8T6: @T6 proj8T0 proj8T1 proj8T2 proj8T3 proj8T4 proj8T5;
proj8T7: @T7 proj8T0 proj8T1 proj8T2 proj8T3 proj8T4 proj8T5 proj8T6;
}.
Definition uncurry8 (R: rel8 T0 T1 T2 T3 T4 T5 T6 T7): rel1 sig8T :=
fun x => R (proj8T0 x) (proj8T1 x) (proj8T2 x) (proj8T3 x) (proj8T4 x) (proj8T5 x) (proj8T6 x) (proj8T7 x).
Definition curry8 (R: rel1 sig8T): rel8 T0 T1 T2 T3 T4 T5 T6 T7 :=
fun x0 x1 x2 x3 x4 x5 x6 x7 => R (@exist8T x0 x1 x2 x3 x4 x5 x6 x7).
Lemma uncurry_map8 r0 r1 (LE : r0 <8== r1) : uncurry8 r0 <1== uncurry8 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev8 r0 r1 (LE: uncurry8 r0 <1== uncurry8 r1) : r0 <8== r1.
Proof.
red; intros. apply (LE (@exist8T x0 x1 x2 x3 x4 x5 x6 x7) PR).
Qed.
Lemma curry_map8 r0 r1 (LE: r0 <1== r1) : curry8 r0 <8== curry8 r1.
Proof.
red; intros. apply (LE (@exist8T x0 x1 x2 x3 x4 x5 x6 x7) PR).
Qed.
Lemma curry_map_rev8 r0 r1 (LE: curry8 r0 <8== curry8 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_8 r : curry8 (uncurry8 r) <8== r.
Proof. unfold le8. intros. apply PR. Qed.
Lemma uncurry_bij2_8 r : r <8== curry8 (uncurry8 r).
Proof. unfold le8. intros. apply PR. Qed.
Lemma curry_bij1_8 r : uncurry8 (curry8 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_8 r : r <1== uncurry8 (curry8 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_8 r0 r1 (LE: uncurry8 r0 <1== r1) : r0 <8== curry8 r1.
Proof.
apply uncurry_map_rev8. eapply le1_trans; [apply LE|]. apply curry_bij2_8.
Qed.
Lemma uncurry_adjoint2_8 r0 r1 (LE: r0 <8== curry8 r1) : uncurry8 r0 <1== r1.
Proof.
apply curry_map_rev8. eapply le8_trans; [|apply LE]. apply uncurry_bij2_8.
Qed.
Lemma curry_adjoint1_8 r0 r1 (LE: curry8 r0 <8== r1) : r0 <1== uncurry8 r1.
Proof.
apply curry_map_rev8. eapply le8_trans; [apply LE|]. apply uncurry_bij2_8.
Qed.
Lemma curry_adjoint2_8 r0 r1 (LE: r0 <1== uncurry8 r1) : curry8 r0 <8== r1.
Proof.
apply uncurry_map_rev8. eapply le1_trans; [|apply LE]. apply curry_bij1_8.
Qed.
End SIG8.
Section SIG9.
Variable T0 : Type.
Variable T1 : forall (x0: @T0), Type.
Variable T2 : forall (x0: @T0) (x1: @T1 x0), Type.
Variable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.
Variable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.
Variable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.
Variable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.
Variable T7 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5), Type.
Variable T8 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6), Type.
(** ** Signatures *)
Record sig9T :=
exist9T {
proj9T0: @T0;
proj9T1: @T1 proj9T0;
proj9T2: @T2 proj9T0 proj9T1;
proj9T3: @T3 proj9T0 proj9T1 proj9T2;
proj9T4: @T4 proj9T0 proj9T1 proj9T2 proj9T3;
proj9T5: @T5 proj9T0 proj9T1 proj9T2 proj9T3 proj9T4;
proj9T6: @T6 proj9T0 proj9T1 proj9T2 proj9T3 proj9T4 proj9T5;
proj9T7: @T7 proj9T0 proj9T1 proj9T2 proj9T3 proj9T4 proj9T5 proj9T6;
proj9T8: @T8 proj9T0 proj9T1 proj9T2 proj9T3 proj9T4 proj9T5 proj9T6 proj9T7;
}.
Definition uncurry9 (R: rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8): rel1 sig9T :=
fun x => R (proj9T0 x) (proj9T1 x) (proj9T2 x) (proj9T3 x) (proj9T4 x) (proj9T5 x) (proj9T6 x) (proj9T7 x) (proj9T8 x).
Definition curry9 (R: rel1 sig9T): rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 :=
fun x0 x1 x2 x3 x4 x5 x6 x7 x8 => R (@exist9T x0 x1 x2 x3 x4 x5 x6 x7 x8).
Lemma uncurry_map9 r0 r1 (LE : r0 <9== r1) : uncurry9 r0 <1== uncurry9 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev9 r0 r1 (LE: uncurry9 r0 <1== uncurry9 r1) : r0 <9== r1.
Proof.
red; intros. apply (LE (@exist9T x0 x1 x2 x3 x4 x5 x6 x7 x8) PR).
Qed.
Lemma curry_map9 r0 r1 (LE: r0 <1== r1) : curry9 r0 <9== curry9 r1.
Proof.
red; intros. apply (LE (@exist9T x0 x1 x2 x3 x4 x5 x6 x7 x8) PR).
Qed.
Lemma curry_map_rev9 r0 r1 (LE: curry9 r0 <9== curry9 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_9 r : curry9 (uncurry9 r) <9== r.
Proof. unfold le9. intros. apply PR. Qed.
Lemma uncurry_bij2_9 r : r <9== curry9 (uncurry9 r).
Proof. unfold le9. intros. apply PR. Qed.
Lemma curry_bij1_9 r : uncurry9 (curry9 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_9 r : r <1== uncurry9 (curry9 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_9 r0 r1 (LE: uncurry9 r0 <1== r1) : r0 <9== curry9 r1.
Proof.
apply uncurry_map_rev9. eapply le1_trans; [apply LE|]. apply curry_bij2_9.
Qed.
Lemma uncurry_adjoint2_9 r0 r1 (LE: r0 <9== curry9 r1) : uncurry9 r0 <1== r1.
Proof.
apply curry_map_rev9. eapply le9_trans; [|apply LE]. apply uncurry_bij2_9.
Qed.
Lemma curry_adjoint1_9 r0 r1 (LE: curry9 r0 <9== r1) : r0 <1== uncurry9 r1.
Proof.
apply curry_map_rev9. eapply le9_trans; [apply LE|]. apply uncurry_bij2_9.
Qed.
Lemma curry_adjoint2_9 r0 r1 (LE: r0 <1== uncurry9 r1) : curry9 r0 <9== r1.
Proof.
apply uncurry_map_rev9. eapply le1_trans; [|apply LE]. apply curry_bij1_9.
Qed.
End SIG9.
Section SIG10.
Variable T0 : Type.
Variable T1 : forall (x0: @T0), Type.
Variable T2 : forall (x0: @T0) (x1: @T1 x0), Type.
Variable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.
Variable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.
Variable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.
Variable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.
Variable T7 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5), Type.
Variable T8 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6), Type.
Variable T9 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7), Type.
(** ** Signatures *)
Record sig10T :=
exist10T {
proj10T0: @T0;
proj10T1: @T1 proj10T0;
proj10T2: @T2 proj10T0 proj10T1;
proj10T3: @T3 proj10T0 proj10T1 proj10T2;
proj10T4: @T4 proj10T0 proj10T1 proj10T2 proj10T3;
proj10T5: @T5 proj10T0 proj10T1 proj10T2 proj10T3 proj10T4;
proj10T6: @T6 proj10T0 proj10T1 proj10T2 proj10T3 proj10T4 proj10T5;
proj10T7: @T7 proj10T0 proj10T1 proj10T2 proj10T3 proj10T4 proj10T5 proj10T6;
proj10T8: @T8 proj10T0 proj10T1 proj10T2 proj10T3 proj10T4 proj10T5 proj10T6 proj10T7;
proj10T9: @T9 proj10T0 proj10T1 proj10T2 proj10T3 proj10T4 proj10T5 proj10T6 proj10T7 proj10T8;
}.
Definition uncurry10 (R: rel10 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9): rel1 sig10T :=
fun x => R (proj10T0 x) (proj10T1 x) (proj10T2 x) (proj10T3 x) (proj10T4 x) (proj10T5 x) (proj10T6 x) (proj10T7 x) (proj10T8 x) (proj10T9 x).
Definition curry10 (R: rel1 sig10T): rel10 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 :=
fun x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 => R (@exist10T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9).
Lemma uncurry_map10 r0 r1 (LE : r0 <10== r1) : uncurry10 r0 <1== uncurry10 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev10 r0 r1 (LE: uncurry10 r0 <1== uncurry10 r1) : r0 <10== r1.
Proof.
red; intros. apply (LE (@exist10T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9) PR).
Qed.
Lemma curry_map10 r0 r1 (LE: r0 <1== r1) : curry10 r0 <10== curry10 r1.
Proof.
red; intros. apply (LE (@exist10T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9) PR).
Qed.
Lemma curry_map_rev10 r0 r1 (LE: curry10 r0 <10== curry10 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_10 r : curry10 (uncurry10 r) <10== r.
Proof. unfold le10. intros. apply PR. Qed.
Lemma uncurry_bij2_10 r : r <10== curry10 (uncurry10 r).
Proof. unfold le10. intros. apply PR. Qed.
Lemma curry_bij1_10 r : uncurry10 (curry10 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_10 r : r <1== uncurry10 (curry10 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_10 r0 r1 (LE: uncurry10 r0 <1== r1) : r0 <10== curry10 r1.
Proof.
apply uncurry_map_rev10. eapply le1_trans; [apply LE|]. apply curry_bij2_10.
Qed.
Lemma uncurry_adjoint2_10 r0 r1 (LE: r0 <10== curry10 r1) : uncurry10 r0 <1== r1.
Proof.
apply curry_map_rev10. eapply le10_trans; [|apply LE]. apply uncurry_bij2_10.
Qed.
Lemma curry_adjoint1_10 r0 r1 (LE: curry10 r0 <10== r1) : r0 <1== uncurry10 r1.
Proof.
apply curry_map_rev10. eapply le10_trans; [apply LE|]. apply uncurry_bij2_10.
Qed.
Lemma curry_adjoint2_10 r0 r1 (LE: r0 <1== uncurry10 r1) : curry10 r0 <10== r1.
Proof.
apply uncurry_map_rev10. eapply le1_trans; [|apply LE]. apply curry_bij1_10.
Qed.
End SIG10.
Section SIG11.
Variable T0 : Type.
Variable T1 : forall (x0: @T0), Type.
Variable T2 : forall (x0: @T0) (x1: @T1 x0), Type.
Variable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.
Variable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.
Variable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.
Variable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.
Variable T7 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5), Type.
Variable T8 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6), Type.
Variable T9 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7), Type.
Variable T10 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8), Type.
(** ** Signatures *)
Record sig11T :=
exist11T {
proj11T0: @T0;
proj11T1: @T1 proj11T0;
proj11T2: @T2 proj11T0 proj11T1;
proj11T3: @T3 proj11T0 proj11T1 proj11T2;
proj11T4: @T4 proj11T0 proj11T1 proj11T2 proj11T3;
proj11T5: @T5 proj11T0 proj11T1 proj11T2 proj11T3 proj11T4;
proj11T6: @T6 proj11T0 proj11T1 proj11T2 proj11T3 proj11T4 proj11T5;
proj11T7: @T7 proj11T0 proj11T1 proj11T2 proj11T3 proj11T4 proj11T5 proj11T6;
proj11T8: @T8 proj11T0 proj11T1 proj11T2 proj11T3 proj11T4 proj11T5 proj11T6 proj11T7;
proj11T9: @T9 proj11T0 proj11T1 proj11T2 proj11T3 proj11T4 proj11T5 proj11T6 proj11T7 proj11T8;
proj11T10: @T10 proj11T0 proj11T1 proj11T2 proj11T3 proj11T4 proj11T5 proj11T6 proj11T7 proj11T8 proj11T9;
}.
Definition uncurry11 (R: rel11 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10): rel1 sig11T :=
fun x => R (proj11T0 x) (proj11T1 x) (proj11T2 x) (proj11T3 x) (proj11T4 x) (proj11T5 x) (proj11T6 x) (proj11T7 x) (proj11T8 x) (proj11T9 x) (proj11T10 x).
Definition curry11 (R: rel1 sig11T): rel11 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 :=
fun x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 => R (@exist11T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10).
Lemma uncurry_map11 r0 r1 (LE : r0 <11== r1) : uncurry11 r0 <1== uncurry11 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev11 r0 r1 (LE: uncurry11 r0 <1== uncurry11 r1) : r0 <11== r1.
Proof.
red; intros. apply (LE (@exist11T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10) PR).
Qed.
Lemma curry_map11 r0 r1 (LE: r0 <1== r1) : curry11 r0 <11== curry11 r1.
Proof.
red; intros. apply (LE (@exist11T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10) PR).
Qed.
Lemma curry_map_rev11 r0 r1 (LE: curry11 r0 <11== curry11 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_11 r : curry11 (uncurry11 r) <11== r.
Proof. unfold le11. intros. apply PR. Qed.
Lemma uncurry_bij2_11 r : r <11== curry11 (uncurry11 r).
Proof. unfold le11. intros. apply PR. Qed.
Lemma curry_bij1_11 r : uncurry11 (curry11 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_11 r : r <1== uncurry11 (curry11 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_11 r0 r1 (LE: uncurry11 r0 <1== r1) : r0 <11== curry11 r1.
Proof.
apply uncurry_map_rev11. eapply le1_trans; [apply LE|]. apply curry_bij2_11.
Qed.
Lemma uncurry_adjoint2_11 r0 r1 (LE: r0 <11== curry11 r1) : uncurry11 r0 <1== r1.
Proof.
apply curry_map_rev11. eapply le11_trans; [|apply LE]. apply uncurry_bij2_11.
Qed.
Lemma curry_adjoint1_11 r0 r1 (LE: curry11 r0 <11== r1) : r0 <1== uncurry11 r1.
Proof.
apply curry_map_rev11. eapply le11_trans; [apply LE|]. apply uncurry_bij2_11.
Qed.
Lemma curry_adjoint2_11 r0 r1 (LE: r0 <1== uncurry11 r1) : curry11 r0 <11== r1.
Proof.
apply uncurry_map_rev11. eapply le1_trans; [|apply LE]. apply curry_bij1_11.
Qed.
End SIG11.
Section SIG12.
Variable T0 : Type.
Variable T1 : forall (x0: @T0), Type.
Variable T2 : forall (x0: @T0) (x1: @T1 x0), Type.
Variable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.
Variable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.
Variable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.
Variable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.
Variable T7 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5), Type.
Variable T8 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6), Type.
Variable T9 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7), Type.
Variable T10 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8), Type.
Variable T11 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8) (x10: @T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9), Type.
(** ** Signatures *)
Record sig12T :=
exist12T {
proj12T0: @T0;
proj12T1: @T1 proj12T0;
proj12T2: @T2 proj12T0 proj12T1;
proj12T3: @T3 proj12T0 proj12T1 proj12T2;
proj12T4: @T4 proj12T0 proj12T1 proj12T2 proj12T3;
proj12T5: @T5 proj12T0 proj12T1 proj12T2 proj12T3 proj12T4;
proj12T6: @T6 proj12T0 proj12T1 proj12T2 proj12T3 proj12T4 proj12T5;
proj12T7: @T7 proj12T0 proj12T1 proj12T2 proj12T3 proj12T4 proj12T5 proj12T6;
proj12T8: @T8 proj12T0 proj12T1 proj12T2 proj12T3 proj12T4 proj12T5 proj12T6 proj12T7;
proj12T9: @T9 proj12T0 proj12T1 proj12T2 proj12T3 proj12T4 proj12T5 proj12T6 proj12T7 proj12T8;
proj12T10: @T10 proj12T0 proj12T1 proj12T2 proj12T3 proj12T4 proj12T5 proj12T6 proj12T7 proj12T8 proj12T9;
proj12T11: @T11 proj12T0 proj12T1 proj12T2 proj12T3 proj12T4 proj12T5 proj12T6 proj12T7 proj12T8 proj12T9 proj12T10;
}.
Definition uncurry12 (R: rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11): rel1 sig12T :=
fun x => R (proj12T0 x) (proj12T1 x) (proj12T2 x) (proj12T3 x) (proj12T4 x) (proj12T5 x) (proj12T6 x) (proj12T7 x) (proj12T8 x) (proj12T9 x) (proj12T10 x) (proj12T11 x).
Definition curry12 (R: rel1 sig12T): rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 :=
fun x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 => R (@exist12T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11).
Lemma uncurry_map12 r0 r1 (LE : r0 <12== r1) : uncurry12 r0 <1== uncurry12 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev12 r0 r1 (LE: uncurry12 r0 <1== uncurry12 r1) : r0 <12== r1.
Proof.
red; intros. apply (LE (@exist12T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11) PR).
Qed.
Lemma curry_map12 r0 r1 (LE: r0 <1== r1) : curry12 r0 <12== curry12 r1.
Proof.
red; intros. apply (LE (@exist12T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11) PR).
Qed.
Lemma curry_map_rev12 r0 r1 (LE: curry12 r0 <12== curry12 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_12 r : curry12 (uncurry12 r) <12== r.
Proof. unfold le12. intros. apply PR. Qed.
Lemma uncurry_bij2_12 r : r <12== curry12 (uncurry12 r).
Proof. unfold le12. intros. apply PR. Qed.
Lemma curry_bij1_12 r : uncurry12 (curry12 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_12 r : r <1== uncurry12 (curry12 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_12 r0 r1 (LE: uncurry12 r0 <1== r1) : r0 <12== curry12 r1.
Proof.
apply uncurry_map_rev12. eapply le1_trans; [apply LE|]. apply curry_bij2_12.
Qed.
Lemma uncurry_adjoint2_12 r0 r1 (LE: r0 <12== curry12 r1) : uncurry12 r0 <1== r1.
Proof.
apply curry_map_rev12. eapply le12_trans; [|apply LE]. apply uncurry_bij2_12.
Qed.
Lemma curry_adjoint1_12 r0 r1 (LE: curry12 r0 <12== r1) : r0 <1== uncurry12 r1.
Proof.
apply curry_map_rev12. eapply le12_trans; [apply LE|]. apply uncurry_bij2_12.
Qed.
Lemma curry_adjoint2_12 r0 r1 (LE: r0 <1== uncurry12 r1) : curry12 r0 <12== r1.
Proof.
apply uncurry_map_rev12. eapply le1_trans; [|apply LE]. apply curry_bij1_12.
Qed.
End SIG12.
Section SIG13.
Variable T0 : Type.
Variable T1 : forall (x0: @T0), Type.
Variable T2 : forall (x0: @T0) (x1: @T1 x0), Type.
Variable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.
Variable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.
Variable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.
Variable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.
Variable T7 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5), Type.
Variable T8 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6), Type.
Variable T9 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7), Type.
Variable T10 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8), Type.
Variable T11 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8) (x10: @T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9), Type.
Variable T12 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8) (x10: @T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9) (x11: @T11 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10), Type.
(** ** Signatures *)
Record sig13T :=
exist13T {
proj13T0: @T0;
proj13T1: @T1 proj13T0;
proj13T2: @T2 proj13T0 proj13T1;
proj13T3: @T3 proj13T0 proj13T1 proj13T2;
proj13T4: @T4 proj13T0 proj13T1 proj13T2 proj13T3;
proj13T5: @T5 proj13T0 proj13T1 proj13T2 proj13T3 proj13T4;
proj13T6: @T6 proj13T0 proj13T1 proj13T2 proj13T3 proj13T4 proj13T5;
proj13T7: @T7 proj13T0 proj13T1 proj13T2 proj13T3 proj13T4 proj13T5 proj13T6;
proj13T8: @T8 proj13T0 proj13T1 proj13T2 proj13T3 proj13T4 proj13T5 proj13T6 proj13T7;
proj13T9: @T9 proj13T0 proj13T1 proj13T2 proj13T3 proj13T4 proj13T5 proj13T6 proj13T7 proj13T8;
proj13T10: @T10 proj13T0 proj13T1 proj13T2 proj13T3 proj13T4 proj13T5 proj13T6 proj13T7 proj13T8 proj13T9;
proj13T11: @T11 proj13T0 proj13T1 proj13T2 proj13T3 proj13T4 proj13T5 proj13T6 proj13T7 proj13T8 proj13T9 proj13T10;
proj13T12: @T12 proj13T0 proj13T1 proj13T2 proj13T3 proj13T4 proj13T5 proj13T6 proj13T7 proj13T8 proj13T9 proj13T10 proj13T11;
}.
Definition uncurry13 (R: rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12): rel1 sig13T :=
fun x => R (proj13T0 x) (proj13T1 x) (proj13T2 x) (proj13T3 x) (proj13T4 x) (proj13T5 x) (proj13T6 x) (proj13T7 x) (proj13T8 x) (proj13T9 x) (proj13T10 x) (proj13T11 x) (proj13T12 x).
Definition curry13 (R: rel1 sig13T): rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 :=
fun x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 => R (@exist13T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12).
Lemma uncurry_map13 r0 r1 (LE : r0 <13== r1) : uncurry13 r0 <1== uncurry13 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev13 r0 r1 (LE: uncurry13 r0 <1== uncurry13 r1) : r0 <13== r1.
Proof.
red; intros. apply (LE (@exist13T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) PR).
Qed.
Lemma curry_map13 r0 r1 (LE: r0 <1== r1) : curry13 r0 <13== curry13 r1.
Proof.
red; intros. apply (LE (@exist13T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) PR).
Qed.
Lemma curry_map_rev13 r0 r1 (LE: curry13 r0 <13== curry13 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_13 r : curry13 (uncurry13 r) <13== r.
Proof. unfold le13. intros. apply PR. Qed.
Lemma uncurry_bij2_13 r : r <13== curry13 (uncurry13 r).
Proof. unfold le13. intros. apply PR. Qed.
Lemma curry_bij1_13 r : uncurry13 (curry13 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_13 r : r <1== uncurry13 (curry13 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_13 r0 r1 (LE: uncurry13 r0 <1== r1) : r0 <13== curry13 r1.
Proof.
apply uncurry_map_rev13. eapply le1_trans; [apply LE|]. apply curry_bij2_13.
Qed.
Lemma uncurry_adjoint2_13 r0 r1 (LE: r0 <13== curry13 r1) : uncurry13 r0 <1== r1.
Proof.
apply curry_map_rev13. eapply le13_trans; [|apply LE]. apply uncurry_bij2_13.
Qed.
Lemma curry_adjoint1_13 r0 r1 (LE: curry13 r0 <13== r1) : r0 <1== uncurry13 r1.
Proof.
apply curry_map_rev13. eapply le13_trans; [apply LE|]. apply uncurry_bij2_13.
Qed.
Lemma curry_adjoint2_13 r0 r1 (LE: r0 <1== uncurry13 r1) : curry13 r0 <13== r1.
Proof.
apply uncurry_map_rev13. eapply le1_trans; [|apply LE]. apply curry_bij1_13.
Qed.
End SIG13.
Section SIG14.
Variable T0 : Type.
Variable T1 : forall (x0: @T0), Type.
Variable T2 : forall (x0: @T0) (x1: @T1 x0), Type.
Variable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.
Variable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.
Variable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.
Variable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.
Variable T7 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5), Type.
Variable T8 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6), Type.
Variable T9 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7), Type.
Variable T10 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8), Type.
Variable T11 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8) (x10: @T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9), Type.
Variable T12 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8) (x10: @T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9) (x11: @T11 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10), Type.
Variable T13 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8) (x10: @T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9) (x11: @T11 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10) (x12: @T12 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11), Type.
(** ** Signatures *)
Record sig14T :=
exist14T {
proj14T0: @T0;
proj14T1: @T1 proj14T0;
proj14T2: @T2 proj14T0 proj14T1;
proj14T3: @T3 proj14T0 proj14T1 proj14T2;
proj14T4: @T4 proj14T0 proj14T1 proj14T2 proj14T3;
proj14T5: @T5 proj14T0 proj14T1 proj14T2 proj14T3 proj14T4;
proj14T6: @T6 proj14T0 proj14T1 proj14T2 proj14T3 proj14T4 proj14T5;
proj14T7: @T7 proj14T0 proj14T1 proj14T2 proj14T3 proj14T4 proj14T5 proj14T6;
proj14T8: @T8 proj14T0 proj14T1 proj14T2 proj14T3 proj14T4 proj14T5 proj14T6 proj14T7;
proj14T9: @T9 proj14T0 proj14T1 proj14T2 proj14T3 proj14T4 proj14T5 proj14T6 proj14T7 proj14T8;
proj14T10: @T10 proj14T0 proj14T1 proj14T2 proj14T3 proj14T4 proj14T5 proj14T6 proj14T7 proj14T8 proj14T9;
proj14T11: @T11 proj14T0 proj14T1 proj14T2 proj14T3 proj14T4 proj14T5 proj14T6 proj14T7 proj14T8 proj14T9 proj14T10;
proj14T12: @T12 proj14T0 proj14T1 proj14T2 proj14T3 proj14T4 proj14T5 proj14T6 proj14T7 proj14T8 proj14T9 proj14T10 proj14T11;
proj14T13: @T13 proj14T0 proj14T1 proj14T2 proj14T3 proj14T4 proj14T5 proj14T6 proj14T7 proj14T8 proj14T9 proj14T10 proj14T11 proj14T12;
}.
Definition uncurry14 (R: rel14 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13): rel1 sig14T :=
fun x => R (proj14T0 x) (proj14T1 x) (proj14T2 x) (proj14T3 x) (proj14T4 x) (proj14T5 x) (proj14T6 x) (proj14T7 x) (proj14T8 x) (proj14T9 x) (proj14T10 x) (proj14T11 x) (proj14T12 x) (proj14T13 x).
Definition curry14 (R: rel1 sig14T): rel14 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 :=
fun x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 => R (@exist14T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13).
Lemma uncurry_map14 r0 r1 (LE : r0 <14== r1) : uncurry14 r0 <1== uncurry14 r1.
Proof. intros [] H. apply LE. apply H. Qed.
Lemma uncurry_map_rev14 r0 r1 (LE: uncurry14 r0 <1== uncurry14 r1) : r0 <14== r1.
Proof.
red; intros. apply (LE (@exist14T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13) PR).
Qed.
Lemma curry_map14 r0 r1 (LE: r0 <1== r1) : curry14 r0 <14== curry14 r1.
Proof.
red; intros. apply (LE (@exist14T x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13) PR).
Qed.
Lemma curry_map_rev14 r0 r1 (LE: curry14 r0 <14== curry14 r1) : r0 <1== r1.
Proof.
intros [] H. apply LE. apply H.
Qed.
Lemma uncurry_bij1_14 r : curry14 (uncurry14 r) <14== r.
Proof. unfold le14. intros. apply PR. Qed.
Lemma uncurry_bij2_14 r : r <14== curry14 (uncurry14 r).
Proof. unfold le14. intros. apply PR. Qed.
Lemma curry_bij1_14 r : uncurry14 (curry14 r) <1== r.
Proof. intros [] H. apply H. Qed.
Lemma curry_bij2_14 r : r <1== uncurry14 (curry14 r).
Proof. intros [] H. apply H. Qed.
Lemma uncurry_adjoint1_14 r0 r1 (LE: uncurry14 r0 <1== r1) : r0 <14== curry14 r1.
Proof.
apply uncurry_map_rev14. eapply le1_trans; [apply LE|]. apply curry_bij2_14.
Qed.
Lemma uncurry_adjoint2_14 r0 r1 (LE: r0 <14== curry14 r1) : uncurry14 r0 <1== r1.
Proof.
apply curry_map_rev14. eapply le14_trans; [|apply LE]. apply uncurry_bij2_14.
Qed.
Lemma curry_adjoint1_14 r0 r1 (LE: curry14 r0 <14== r1) : r0 <1== uncurry14 r1.
Proof.
apply curry_map_rev14. eapply le14_trans; [apply LE|]. apply uncurry_bij2_14.
Qed.
Lemma curry_adjoint2_14 r0 r1 (LE: r0 <1== uncurry14 r1) : curry14 r0 <14== r1.
Proof.
apply uncurry_map_rev14. eapply le1_trans; [|apply LE]. apply curry_bij1_14.
Qed.
End SIG14.
(** *** Arity 0
*)
Ltac paco_cont0 :=
generalize _paco_foo_cons; paco_generalize_hyp _paco_mark.
Ltac paco_pre0 :=
generalize _paco_mark_cons; repeat intro; paco_cont0.
Ltac paco_post_match0 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| bot0 -> _ => clear H; tac1 cr
| ?pr -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Tactic Notation "paco_post0" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match0 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** *** Arity 1
*)
Lemma _paco_convert1: forall T0
(paco1: forall
(y0: @T0)
, Prop)
y0
(CONVERT: forall
(x0: @T0)
(EQ: _paco_id (@exist1T T0 x0 = @exist1T T0 y0))
, @paco1 x0),
@paco1 y0.
Proof. intros. apply CONVERT; reflexivity. Qed.
Lemma _paco_convert_rev1: forall T0
(paco1: forall
(y0: @T0)
, Prop)
y0
x0
(EQ: _paco_id (@exist1T T0 x0 = @exist1T T0 y0))
(PACO: @paco1 y0),
@paco1 x0.
Proof. intros.
apply (@f_equal (@sig1T T0) _ (fun x => @paco1
x.(proj1T0)
)) in EQ. simpl in EQ. rewrite EQ. apply PACO.
Qed.
Ltac paco_convert_rev1 := match goal with
| [H: _paco_id (@exist1T _ ?x0 = @exist1T _ ?y0) |- _] =>
eapply _paco_convert_rev1; [eapply H; clear H|..]; clear x0 H
end.
Ltac paco_cont1 e0 :=
let x0 := fresh "_paco_v_" in
apply _paco_convert1;
intros x0;
move x0 at top;
paco_generalize_hyp _paco_mark; revert x0.
Lemma _paco_pre1: forall T0 (gf: rel1 T0) x0
(X: let gf' := gf in gf' x0), gf x0.
Proof. intros; apply X. Defined.
Ltac paco_pre1 := let X := fresh "_paco_X_" in
generalize _paco_mark_cons; repeat intro;
apply _paco_pre1;
match goal with
| [|- let _ : _ ?T0 := _ in _ ?e0] => intro X; unfold X; clear X;
paco_cont1
(e0: T0)
end.
Ltac paco_post_match1 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| forall _, bot1 _ -> _ => clear H; tac1 cr
| forall _, ?pr _ -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Ltac paco_simp_hyp1 CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev1; paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
[..|match goal with [|-_paco_id (?a = ?b)] => unfold _paco_id; reflexivity end];
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp1 CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp1 CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev1; paco_revert_hyp _paco_mark
].
Tactic Notation "paco_post1" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match1 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp1 CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** *** Arity 2
*)
Lemma _paco_convert2: forall T0 T1
(paco2: forall
(y0: @T0)
(y1: @T1 y0)
, Prop)
y0 y1
(CONVERT: forall
(x0: @T0)
(x1: @T1 x0)
(EQ: _paco_id (@exist2T T0 T1 x0 x1 = @exist2T T0 T1 y0 y1))
, @paco2 x0 x1),
@paco2 y0 y1.
Proof. intros. apply CONVERT; reflexivity. Qed.
Lemma _paco_convert_rev2: forall T0 T1
(paco2: forall
(y0: @T0)
(y1: @T1 y0)
, Prop)
y0 y1
x0 x1
(EQ: _paco_id (@exist2T T0 T1 x0 x1 = @exist2T T0 T1 y0 y1))
(PACO: @paco2 y0 y1),
@paco2 x0 x1.
Proof. intros.
apply (@f_equal (@sig2T T0 T1) _ (fun x => @paco2
x.(proj2T0)
x.(proj2T1)
)) in EQ. simpl in EQ. rewrite EQ. apply PACO.
Qed.
Ltac paco_convert_rev2 := match goal with
| [H: _paco_id (@exist2T _ _ ?x0 ?x1 = @exist2T _ _ ?y0 ?y1) |- _] =>
eapply _paco_convert_rev2; [eapply H; clear H|..]; clear x0 x1 H
end.
Ltac paco_cont2 e0 e1 :=
let x0 := fresh "_paco_v_" in
let x1 := fresh "_paco_v_" in
apply _paco_convert2;
intros x0 x1;
move x0 at top; move x1 at top;
paco_generalize_hyp _paco_mark; revert x0 x1.
Lemma _paco_pre2: forall T0 T1 (gf: rel2 T0 T1) x0 x1
(X: let gf' := gf in gf' x0 x1), gf x0 x1.
Proof. intros; apply X. Defined.
Ltac paco_pre2 := let X := fresh "_paco_X_" in
generalize _paco_mark_cons; repeat intro;
apply _paco_pre2;
match goal with
| [|- let _ : _ ?T0 ?T1 := _ in _ ?e0 ?e1] => intro X; unfold X; clear X;
paco_cont2
(e0: T0)
(e1: T1 e0)
end.
Ltac paco_post_match2 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| forall _ _, bot2 _ _ -> _ => clear H; tac1 cr
| forall _ _, ?pr _ _ -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Ltac paco_simp_hyp2 CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev2; paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
[..|match goal with [|-_paco_id (?a = ?b)] => unfold _paco_id; reflexivity end];
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp2 CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp2 CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev2; paco_revert_hyp _paco_mark
].
Tactic Notation "paco_post2" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match2 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp2 CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** *** Arity 3
*)
Lemma _paco_convert3: forall T0 T1 T2
(paco3: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
, Prop)
y0 y1 y2
(CONVERT: forall
(x0: @T0)
(x1: @T1 x0)
(x2: @T2 x0 x1)
(EQ: _paco_id (@exist3T T0 T1 T2 x0 x1 x2 = @exist3T T0 T1 T2 y0 y1 y2))
, @paco3 x0 x1 x2),
@paco3 y0 y1 y2.
Proof. intros. apply CONVERT; reflexivity. Qed.
Lemma _paco_convert_rev3: forall T0 T1 T2
(paco3: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
, Prop)
y0 y1 y2
x0 x1 x2
(EQ: _paco_id (@exist3T T0 T1 T2 x0 x1 x2 = @exist3T T0 T1 T2 y0 y1 y2))
(PACO: @paco3 y0 y1 y2),
@paco3 x0 x1 x2.
Proof. intros.
apply (@f_equal (@sig3T T0 T1 T2) _ (fun x => @paco3
x.(proj3T0)
x.(proj3T1)
x.(proj3T2)
)) in EQ. simpl in EQ. rewrite EQ. apply PACO.
Qed.
Ltac paco_convert_rev3 := match goal with
| [H: _paco_id (@exist3T _ _ _ ?x0 ?x1 ?x2 = @exist3T _ _ _ ?y0 ?y1 ?y2) |- _] =>
eapply _paco_convert_rev3; [eapply H; clear H|..]; clear x0 x1 x2 H
end.
Ltac paco_cont3 e0 e1 e2 :=
let x0 := fresh "_paco_v_" in
let x1 := fresh "_paco_v_" in
let x2 := fresh "_paco_v_" in
apply _paco_convert3;
intros x0 x1 x2;
move x0 at top; move x1 at top; move x2 at top;
paco_generalize_hyp _paco_mark; revert x0 x1 x2.
Lemma _paco_pre3: forall T0 T1 T2 (gf: rel3 T0 T1 T2) x0 x1 x2
(X: let gf' := gf in gf' x0 x1 x2), gf x0 x1 x2.
Proof. intros; apply X. Defined.
Ltac paco_pre3 := let X := fresh "_paco_X_" in
generalize _paco_mark_cons; repeat intro;
apply _paco_pre3;
match goal with
| [|- let _ : _ ?T0 ?T1 ?T2 := _ in _ ?e0 ?e1 ?e2] => intro X; unfold X; clear X;
paco_cont3
(e0: T0)
(e1: T1 e0)
(e2: T2 e0 e1)
end.
Ltac paco_post_match3 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| forall _ _ _, bot3 _ _ _ -> _ => clear H; tac1 cr
| forall _ _ _, ?pr _ _ _ -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Ltac paco_simp_hyp3 CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev3; paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
[..|match goal with [|-_paco_id (?a = ?b)] => unfold _paco_id; reflexivity end];
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp3 CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp3 CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev3; paco_revert_hyp _paco_mark
].
Tactic Notation "paco_post3" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match3 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp3 CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** *** Arity 4
*)
Lemma _paco_convert4: forall T0 T1 T2 T3
(paco4: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
, Prop)
y0 y1 y2 y3
(CONVERT: forall
(x0: @T0)
(x1: @T1 x0)
(x2: @T2 x0 x1)
(x3: @T3 x0 x1 x2)
(EQ: _paco_id (@exist4T T0 T1 T2 T3 x0 x1 x2 x3 = @exist4T T0 T1 T2 T3 y0 y1 y2 y3))
, @paco4 x0 x1 x2 x3),
@paco4 y0 y1 y2 y3.
Proof. intros. apply CONVERT; reflexivity. Qed.
Lemma _paco_convert_rev4: forall T0 T1 T2 T3
(paco4: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
, Prop)
y0 y1 y2 y3
x0 x1 x2 x3
(EQ: _paco_id (@exist4T T0 T1 T2 T3 x0 x1 x2 x3 = @exist4T T0 T1 T2 T3 y0 y1 y2 y3))
(PACO: @paco4 y0 y1 y2 y3),
@paco4 x0 x1 x2 x3.
Proof. intros.
apply (@f_equal (@sig4T T0 T1 T2 T3) _ (fun x => @paco4
x.(proj4T0)
x.(proj4T1)
x.(proj4T2)
x.(proj4T3)
)) in EQ. simpl in EQ. rewrite EQ. apply PACO.
Qed.
Ltac paco_convert_rev4 := match goal with
| [H: _paco_id (@exist4T _ _ _ _ ?x0 ?x1 ?x2 ?x3 = @exist4T _ _ _ _ ?y0 ?y1 ?y2 ?y3) |- _] =>
eapply _paco_convert_rev4; [eapply H; clear H|..]; clear x0 x1 x2 x3 H
end.
Ltac paco_cont4 e0 e1 e2 e3 :=
let x0 := fresh "_paco_v_" in
let x1 := fresh "_paco_v_" in
let x2 := fresh "_paco_v_" in
let x3 := fresh "_paco_v_" in
apply _paco_convert4;
intros x0 x1 x2 x3;
move x0 at top; move x1 at top; move x2 at top; move x3 at top;
paco_generalize_hyp _paco_mark; revert x0 x1 x2 x3.
Lemma _paco_pre4: forall T0 T1 T2 T3 (gf: rel4 T0 T1 T2 T3) x0 x1 x2 x3
(X: let gf' := gf in gf' x0 x1 x2 x3), gf x0 x1 x2 x3.
Proof. intros; apply X. Defined.
Ltac paco_pre4 := let X := fresh "_paco_X_" in
generalize _paco_mark_cons; repeat intro;
apply _paco_pre4;
match goal with
| [|- let _ : _ ?T0 ?T1 ?T2 ?T3 := _ in _ ?e0 ?e1 ?e2 ?e3] => intro X; unfold X; clear X;
paco_cont4
(e0: T0)
(e1: T1 e0)
(e2: T2 e0 e1)
(e3: T3 e0 e1 e2)
end.
Ltac paco_post_match4 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| forall _ _ _ _, bot4 _ _ _ _ -> _ => clear H; tac1 cr
| forall _ _ _ _, ?pr _ _ _ _ -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Ltac paco_simp_hyp4 CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev4; paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
[..|match goal with [|-_paco_id (?a = ?b)] => unfold _paco_id; reflexivity end];
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp4 CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp4 CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev4; paco_revert_hyp _paco_mark
].
Tactic Notation "paco_post4" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match4 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp4 CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** *** Arity 5
*)
Lemma _paco_convert5: forall T0 T1 T2 T3 T4
(paco5: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
, Prop)
y0 y1 y2 y3 y4
(CONVERT: forall
(x0: @T0)
(x1: @T1 x0)
(x2: @T2 x0 x1)
(x3: @T3 x0 x1 x2)
(x4: @T4 x0 x1 x2 x3)
(EQ: _paco_id (@exist5T T0 T1 T2 T3 T4 x0 x1 x2 x3 x4 = @exist5T T0 T1 T2 T3 T4 y0 y1 y2 y3 y4))
, @paco5 x0 x1 x2 x3 x4),
@paco5 y0 y1 y2 y3 y4.
Proof. intros. apply CONVERT; reflexivity. Qed.
Lemma _paco_convert_rev5: forall T0 T1 T2 T3 T4
(paco5: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
, Prop)
y0 y1 y2 y3 y4
x0 x1 x2 x3 x4
(EQ: _paco_id (@exist5T T0 T1 T2 T3 T4 x0 x1 x2 x3 x4 = @exist5T T0 T1 T2 T3 T4 y0 y1 y2 y3 y4))
(PACO: @paco5 y0 y1 y2 y3 y4),
@paco5 x0 x1 x2 x3 x4.
Proof. intros.
apply (@f_equal (@sig5T T0 T1 T2 T3 T4) _ (fun x => @paco5
x.(proj5T0)
x.(proj5T1)
x.(proj5T2)
x.(proj5T3)
x.(proj5T4)
)) in EQ. simpl in EQ. rewrite EQ. apply PACO.
Qed.
Ltac paco_convert_rev5 := match goal with
| [H: _paco_id (@exist5T _ _ _ _ _ ?x0 ?x1 ?x2 ?x3 ?x4 = @exist5T _ _ _ _ _ ?y0 ?y1 ?y2 ?y3 ?y4) |- _] =>
eapply _paco_convert_rev5; [eapply H; clear H|..]; clear x0 x1 x2 x3 x4 H
end.
Ltac paco_cont5 e0 e1 e2 e3 e4 :=
let x0 := fresh "_paco_v_" in
let x1 := fresh "_paco_v_" in
let x2 := fresh "_paco_v_" in
let x3 := fresh "_paco_v_" in
let x4 := fresh "_paco_v_" in
apply _paco_convert5;
intros x0 x1 x2 x3 x4;
move x0 at top; move x1 at top; move x2 at top; move x3 at top; move x4 at top;
paco_generalize_hyp _paco_mark; revert x0 x1 x2 x3 x4.
Lemma _paco_pre5: forall T0 T1 T2 T3 T4 (gf: rel5 T0 T1 T2 T3 T4) x0 x1 x2 x3 x4
(X: let gf' := gf in gf' x0 x1 x2 x3 x4), gf x0 x1 x2 x3 x4.
Proof. intros; apply X. Defined.
Ltac paco_pre5 := let X := fresh "_paco_X_" in
generalize _paco_mark_cons; repeat intro;
apply _paco_pre5;
match goal with
| [|- let _ : _ ?T0 ?T1 ?T2 ?T3 ?T4 := _ in _ ?e0 ?e1 ?e2 ?e3 ?e4] => intro X; unfold X; clear X;
paco_cont5
(e0: T0)
(e1: T1 e0)
(e2: T2 e0 e1)
(e3: T3 e0 e1 e2)
(e4: T4 e0 e1 e2 e3)
end.
Ltac paco_post_match5 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| forall _ _ _ _ _, bot5 _ _ _ _ _ -> _ => clear H; tac1 cr
| forall _ _ _ _ _, ?pr _ _ _ _ _ -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Ltac paco_simp_hyp5 CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev5; paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
[..|match goal with [|-_paco_id (?a = ?b)] => unfold _paco_id; reflexivity end];
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp5 CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp5 CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev5; paco_revert_hyp _paco_mark
].
Tactic Notation "paco_post5" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match5 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp5 CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** *** Arity 6
*)
Lemma _paco_convert6: forall T0 T1 T2 T3 T4 T5
(paco6: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
, Prop)
y0 y1 y2 y3 y4 y5
(CONVERT: forall
(x0: @T0)
(x1: @T1 x0)
(x2: @T2 x0 x1)
(x3: @T3 x0 x1 x2)
(x4: @T4 x0 x1 x2 x3)
(x5: @T5 x0 x1 x2 x3 x4)
(EQ: _paco_id (@exist6T T0 T1 T2 T3 T4 T5 x0 x1 x2 x3 x4 x5 = @exist6T T0 T1 T2 T3 T4 T5 y0 y1 y2 y3 y4 y5))
, @paco6 x0 x1 x2 x3 x4 x5),
@paco6 y0 y1 y2 y3 y4 y5.
Proof. intros. apply CONVERT; reflexivity. Qed.
Lemma _paco_convert_rev6: forall T0 T1 T2 T3 T4 T5
(paco6: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
, Prop)
y0 y1 y2 y3 y4 y5
x0 x1 x2 x3 x4 x5
(EQ: _paco_id (@exist6T T0 T1 T2 T3 T4 T5 x0 x1 x2 x3 x4 x5 = @exist6T T0 T1 T2 T3 T4 T5 y0 y1 y2 y3 y4 y5))
(PACO: @paco6 y0 y1 y2 y3 y4 y5),
@paco6 x0 x1 x2 x3 x4 x5.
Proof. intros.
apply (@f_equal (@sig6T T0 T1 T2 T3 T4 T5) _ (fun x => @paco6
x.(proj6T0)
x.(proj6T1)
x.(proj6T2)
x.(proj6T3)
x.(proj6T4)
x.(proj6T5)
)) in EQ. simpl in EQ. rewrite EQ. apply PACO.
Qed.
Ltac paco_convert_rev6 := match goal with
| [H: _paco_id (@exist6T _ _ _ _ _ _ ?x0 ?x1 ?x2 ?x3 ?x4 ?x5 = @exist6T _ _ _ _ _ _ ?y0 ?y1 ?y2 ?y3 ?y4 ?y5) |- _] =>
eapply _paco_convert_rev6; [eapply H; clear H|..]; clear x0 x1 x2 x3 x4 x5 H
end.
Ltac paco_cont6 e0 e1 e2 e3 e4 e5 :=
let x0 := fresh "_paco_v_" in
let x1 := fresh "_paco_v_" in
let x2 := fresh "_paco_v_" in
let x3 := fresh "_paco_v_" in
let x4 := fresh "_paco_v_" in
let x5 := fresh "_paco_v_" in
apply _paco_convert6;
intros x0 x1 x2 x3 x4 x5;
move x0 at top; move x1 at top; move x2 at top; move x3 at top; move x4 at top; move x5 at top;
paco_generalize_hyp _paco_mark; revert x0 x1 x2 x3 x4 x5.
Lemma _paco_pre6: forall T0 T1 T2 T3 T4 T5 (gf: rel6 T0 T1 T2 T3 T4 T5) x0 x1 x2 x3 x4 x5
(X: let gf' := gf in gf' x0 x1 x2 x3 x4 x5), gf x0 x1 x2 x3 x4 x5.
Proof. intros; apply X. Defined.
Ltac paco_pre6 := let X := fresh "_paco_X_" in
generalize _paco_mark_cons; repeat intro;
apply _paco_pre6;
match goal with
| [|- let _ : _ ?T0 ?T1 ?T2 ?T3 ?T4 ?T5 := _ in _ ?e0 ?e1 ?e2 ?e3 ?e4 ?e5] => intro X; unfold X; clear X;
paco_cont6
(e0: T0)
(e1: T1 e0)
(e2: T2 e0 e1)
(e3: T3 e0 e1 e2)
(e4: T4 e0 e1 e2 e3)
(e5: T5 e0 e1 e2 e3 e4)
end.
Ltac paco_post_match6 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| forall _ _ _ _ _ _, bot6 _ _ _ _ _ _ -> _ => clear H; tac1 cr
| forall _ _ _ _ _ _, ?pr _ _ _ _ _ _ -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Ltac paco_simp_hyp6 CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev6; paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
[..|match goal with [|-_paco_id (?a = ?b)] => unfold _paco_id; reflexivity end];
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp6 CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp6 CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev6; paco_revert_hyp _paco_mark
].
Tactic Notation "paco_post6" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match6 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp6 CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** *** Arity 7
*)
Lemma _paco_convert7: forall T0 T1 T2 T3 T4 T5 T6
(paco7: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
, Prop)
y0 y1 y2 y3 y4 y5 y6
(CONVERT: forall
(x0: @T0)
(x1: @T1 x0)
(x2: @T2 x0 x1)
(x3: @T3 x0 x1 x2)
(x4: @T4 x0 x1 x2 x3)
(x5: @T5 x0 x1 x2 x3 x4)
(x6: @T6 x0 x1 x2 x3 x4 x5)
(EQ: _paco_id (@exist7T T0 T1 T2 T3 T4 T5 T6 x0 x1 x2 x3 x4 x5 x6 = @exist7T T0 T1 T2 T3 T4 T5 T6 y0 y1 y2 y3 y4 y5 y6))
, @paco7 x0 x1 x2 x3 x4 x5 x6),
@paco7 y0 y1 y2 y3 y4 y5 y6.
Proof. intros. apply CONVERT; reflexivity. Qed.
Lemma _paco_convert_rev7: forall T0 T1 T2 T3 T4 T5 T6
(paco7: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
, Prop)
y0 y1 y2 y3 y4 y5 y6
x0 x1 x2 x3 x4 x5 x6
(EQ: _paco_id (@exist7T T0 T1 T2 T3 T4 T5 T6 x0 x1 x2 x3 x4 x5 x6 = @exist7T T0 T1 T2 T3 T4 T5 T6 y0 y1 y2 y3 y4 y5 y6))
(PACO: @paco7 y0 y1 y2 y3 y4 y5 y6),
@paco7 x0 x1 x2 x3 x4 x5 x6.
Proof. intros.
apply (@f_equal (@sig7T T0 T1 T2 T3 T4 T5 T6) _ (fun x => @paco7
x.(proj7T0)
x.(proj7T1)
x.(proj7T2)
x.(proj7T3)
x.(proj7T4)
x.(proj7T5)
x.(proj7T6)
)) in EQ. simpl in EQ. rewrite EQ. apply PACO.
Qed.
Ltac paco_convert_rev7 := match goal with
| [H: _paco_id (@exist7T _ _ _ _ _ _ _ ?x0 ?x1 ?x2 ?x3 ?x4 ?x5 ?x6 = @exist7T _ _ _ _ _ _ _ ?y0 ?y1 ?y2 ?y3 ?y4 ?y5 ?y6) |- _] =>
eapply _paco_convert_rev7; [eapply H; clear H|..]; clear x0 x1 x2 x3 x4 x5 x6 H
end.
Ltac paco_cont7 e0 e1 e2 e3 e4 e5 e6 :=
let x0 := fresh "_paco_v_" in
let x1 := fresh "_paco_v_" in
let x2 := fresh "_paco_v_" in
let x3 := fresh "_paco_v_" in
let x4 := fresh "_paco_v_" in
let x5 := fresh "_paco_v_" in
let x6 := fresh "_paco_v_" in
apply _paco_convert7;
intros x0 x1 x2 x3 x4 x5 x6;
move x0 at top; move x1 at top; move x2 at top; move x3 at top; move x4 at top; move x5 at top; move x6 at top;
paco_generalize_hyp _paco_mark; revert x0 x1 x2 x3 x4 x5 x6.
Lemma _paco_pre7: forall T0 T1 T2 T3 T4 T5 T6 (gf: rel7 T0 T1 T2 T3 T4 T5 T6) x0 x1 x2 x3 x4 x5 x6
(X: let gf' := gf in gf' x0 x1 x2 x3 x4 x5 x6), gf x0 x1 x2 x3 x4 x5 x6.
Proof. intros; apply X. Defined.
Ltac paco_pre7 := let X := fresh "_paco_X_" in
generalize _paco_mark_cons; repeat intro;
apply _paco_pre7;
match goal with
| [|- let _ : _ ?T0 ?T1 ?T2 ?T3 ?T4 ?T5 ?T6 := _ in _ ?e0 ?e1 ?e2 ?e3 ?e4 ?e5 ?e6] => intro X; unfold X; clear X;
paco_cont7
(e0: T0)
(e1: T1 e0)
(e2: T2 e0 e1)
(e3: T3 e0 e1 e2)
(e4: T4 e0 e1 e2 e3)
(e5: T5 e0 e1 e2 e3 e4)
(e6: T6 e0 e1 e2 e3 e4 e5)
end.
Ltac paco_post_match7 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| forall _ _ _ _ _ _ _, bot7 _ _ _ _ _ _ _ -> _ => clear H; tac1 cr
| forall _ _ _ _ _ _ _, ?pr _ _ _ _ _ _ _ -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Ltac paco_simp_hyp7 CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev7; paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
[..|match goal with [|-_paco_id (?a = ?b)] => unfold _paco_id; reflexivity end];
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp7 CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp7 CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev7; paco_revert_hyp _paco_mark
].
Tactic Notation "paco_post7" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match7 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp7 CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** *** Arity 8
*)
Lemma _paco_convert8: forall T0 T1 T2 T3 T4 T5 T6 T7
(paco8: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
(y7: @T7 y0 y1 y2 y3 y4 y5 y6)
, Prop)
y0 y1 y2 y3 y4 y5 y6 y7
(CONVERT: forall
(x0: @T0)
(x1: @T1 x0)
(x2: @T2 x0 x1)
(x3: @T3 x0 x1 x2)
(x4: @T4 x0 x1 x2 x3)
(x5: @T5 x0 x1 x2 x3 x4)
(x6: @T6 x0 x1 x2 x3 x4 x5)
(x7: @T7 x0 x1 x2 x3 x4 x5 x6)
(EQ: _paco_id (@exist8T T0 T1 T2 T3 T4 T5 T6 T7 x0 x1 x2 x3 x4 x5 x6 x7 = @exist8T T0 T1 T2 T3 T4 T5 T6 T7 y0 y1 y2 y3 y4 y5 y6 y7))
, @paco8 x0 x1 x2 x3 x4 x5 x6 x7),
@paco8 y0 y1 y2 y3 y4 y5 y6 y7.
Proof. intros. apply CONVERT; reflexivity. Qed.
Lemma _paco_convert_rev8: forall T0 T1 T2 T3 T4 T5 T6 T7
(paco8: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
(y7: @T7 y0 y1 y2 y3 y4 y5 y6)
, Prop)
y0 y1 y2 y3 y4 y5 y6 y7
x0 x1 x2 x3 x4 x5 x6 x7
(EQ: _paco_id (@exist8T T0 T1 T2 T3 T4 T5 T6 T7 x0 x1 x2 x3 x4 x5 x6 x7 = @exist8T T0 T1 T2 T3 T4 T5 T6 T7 y0 y1 y2 y3 y4 y5 y6 y7))
(PACO: @paco8 y0 y1 y2 y3 y4 y5 y6 y7),
@paco8 x0 x1 x2 x3 x4 x5 x6 x7.
Proof. intros.
apply (@f_equal (@sig8T T0 T1 T2 T3 T4 T5 T6 T7) _ (fun x => @paco8
x.(proj8T0)
x.(proj8T1)
x.(proj8T2)
x.(proj8T3)
x.(proj8T4)
x.(proj8T5)
x.(proj8T6)
x.(proj8T7)
)) in EQ. simpl in EQ. rewrite EQ. apply PACO.
Qed.
Ltac paco_convert_rev8 := match goal with
| [H: _paco_id (@exist8T _ _ _ _ _ _ _ _ ?x0 ?x1 ?x2 ?x3 ?x4 ?x5 ?x6 ?x7 = @exist8T _ _ _ _ _ _ _ _ ?y0 ?y1 ?y2 ?y3 ?y4 ?y5 ?y6 ?y7) |- _] =>
eapply _paco_convert_rev8; [eapply H; clear H|..]; clear x0 x1 x2 x3 x4 x5 x6 x7 H
end.
Ltac paco_cont8 e0 e1 e2 e3 e4 e5 e6 e7 :=
let x0 := fresh "_paco_v_" in
let x1 := fresh "_paco_v_" in
let x2 := fresh "_paco_v_" in
let x3 := fresh "_paco_v_" in
let x4 := fresh "_paco_v_" in
let x5 := fresh "_paco_v_" in
let x6 := fresh "_paco_v_" in
let x7 := fresh "_paco_v_" in
apply _paco_convert8;
intros x0 x1 x2 x3 x4 x5 x6 x7;
move x0 at top; move x1 at top; move x2 at top; move x3 at top; move x4 at top; move x5 at top; move x6 at top; move x7 at top;
paco_generalize_hyp _paco_mark; revert x0 x1 x2 x3 x4 x5 x6 x7.
Lemma _paco_pre8: forall T0 T1 T2 T3 T4 T5 T6 T7 (gf: rel8 T0 T1 T2 T3 T4 T5 T6 T7) x0 x1 x2 x3 x4 x5 x6 x7
(X: let gf' := gf in gf' x0 x1 x2 x3 x4 x5 x6 x7), gf x0 x1 x2 x3 x4 x5 x6 x7.
Proof. intros; apply X. Defined.
Ltac paco_pre8 := let X := fresh "_paco_X_" in
generalize _paco_mark_cons; repeat intro;
apply _paco_pre8;
match goal with
| [|- let _ : _ ?T0 ?T1 ?T2 ?T3 ?T4 ?T5 ?T6 ?T7 := _ in _ ?e0 ?e1 ?e2 ?e3 ?e4 ?e5 ?e6 ?e7] => intro X; unfold X; clear X;
paco_cont8
(e0: T0)
(e1: T1 e0)
(e2: T2 e0 e1)
(e3: T3 e0 e1 e2)
(e4: T4 e0 e1 e2 e3)
(e5: T5 e0 e1 e2 e3 e4)
(e6: T6 e0 e1 e2 e3 e4 e5)
(e7: T7 e0 e1 e2 e3 e4 e5 e6)
end.
Ltac paco_post_match8 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| forall _ _ _ _ _ _ _ _, bot8 _ _ _ _ _ _ _ _ -> _ => clear H; tac1 cr
| forall _ _ _ _ _ _ _ _, ?pr _ _ _ _ _ _ _ _ -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Ltac paco_simp_hyp8 CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev8; paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
[..|match goal with [|-_paco_id (?a = ?b)] => unfold _paco_id; reflexivity end];
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp8 CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp8 CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev8; paco_revert_hyp _paco_mark
].
Tactic Notation "paco_post8" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match8 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp8 CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** *** Arity 9
*)
Lemma _paco_convert9: forall T0 T1 T2 T3 T4 T5 T6 T7 T8
(paco9: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
(y7: @T7 y0 y1 y2 y3 y4 y5 y6)
(y8: @T8 y0 y1 y2 y3 y4 y5 y6 y7)
, Prop)
y0 y1 y2 y3 y4 y5 y6 y7 y8
(CONVERT: forall
(x0: @T0)
(x1: @T1 x0)
(x2: @T2 x0 x1)
(x3: @T3 x0 x1 x2)
(x4: @T4 x0 x1 x2 x3)
(x5: @T5 x0 x1 x2 x3 x4)
(x6: @T6 x0 x1 x2 x3 x4 x5)
(x7: @T7 x0 x1 x2 x3 x4 x5 x6)
(x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7)
(EQ: _paco_id (@exist9T T0 T1 T2 T3 T4 T5 T6 T7 T8 x0 x1 x2 x3 x4 x5 x6 x7 x8 = @exist9T T0 T1 T2 T3 T4 T5 T6 T7 T8 y0 y1 y2 y3 y4 y5 y6 y7 y8))
, @paco9 x0 x1 x2 x3 x4 x5 x6 x7 x8),
@paco9 y0 y1 y2 y3 y4 y5 y6 y7 y8.
Proof. intros. apply CONVERT; reflexivity. Qed.
Lemma _paco_convert_rev9: forall T0 T1 T2 T3 T4 T5 T6 T7 T8
(paco9: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
(y7: @T7 y0 y1 y2 y3 y4 y5 y6)
(y8: @T8 y0 y1 y2 y3 y4 y5 y6 y7)
, Prop)
y0 y1 y2 y3 y4 y5 y6 y7 y8
x0 x1 x2 x3 x4 x5 x6 x7 x8
(EQ: _paco_id (@exist9T T0 T1 T2 T3 T4 T5 T6 T7 T8 x0 x1 x2 x3 x4 x5 x6 x7 x8 = @exist9T T0 T1 T2 T3 T4 T5 T6 T7 T8 y0 y1 y2 y3 y4 y5 y6 y7 y8))
(PACO: @paco9 y0 y1 y2 y3 y4 y5 y6 y7 y8),
@paco9 x0 x1 x2 x3 x4 x5 x6 x7 x8.
Proof. intros.
apply (@f_equal (@sig9T T0 T1 T2 T3 T4 T5 T6 T7 T8) _ (fun x => @paco9
x.(proj9T0)
x.(proj9T1)
x.(proj9T2)
x.(proj9T3)
x.(proj9T4)
x.(proj9T5)
x.(proj9T6)
x.(proj9T7)
x.(proj9T8)
)) in EQ. simpl in EQ. rewrite EQ. apply PACO.
Qed.
Ltac paco_convert_rev9 := match goal with
| [H: _paco_id (@exist9T _ _ _ _ _ _ _ _ _ ?x0 ?x1 ?x2 ?x3 ?x4 ?x5 ?x6 ?x7 ?x8 = @exist9T _ _ _ _ _ _ _ _ _ ?y0 ?y1 ?y2 ?y3 ?y4 ?y5 ?y6 ?y7 ?y8) |- _] =>
eapply _paco_convert_rev9; [eapply H; clear H|..]; clear x0 x1 x2 x3 x4 x5 x6 x7 x8 H
end.
Ltac paco_cont9 e0 e1 e2 e3 e4 e5 e6 e7 e8 :=
let x0 := fresh "_paco_v_" in
let x1 := fresh "_paco_v_" in
let x2 := fresh "_paco_v_" in
let x3 := fresh "_paco_v_" in
let x4 := fresh "_paco_v_" in
let x5 := fresh "_paco_v_" in
let x6 := fresh "_paco_v_" in
let x7 := fresh "_paco_v_" in
let x8 := fresh "_paco_v_" in
apply _paco_convert9;
intros x0 x1 x2 x3 x4 x5 x6 x7 x8;
move x0 at top; move x1 at top; move x2 at top; move x3 at top; move x4 at top; move x5 at top; move x6 at top; move x7 at top; move x8 at top;
paco_generalize_hyp _paco_mark; revert x0 x1 x2 x3 x4 x5 x6 x7 x8.
Lemma _paco_pre9: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 (gf: rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8) x0 x1 x2 x3 x4 x5 x6 x7 x8
(X: let gf' := gf in gf' x0 x1 x2 x3 x4 x5 x6 x7 x8), gf x0 x1 x2 x3 x4 x5 x6 x7 x8.
Proof. intros; apply X. Defined.
Ltac paco_pre9 := let X := fresh "_paco_X_" in
generalize _paco_mark_cons; repeat intro;
apply _paco_pre9;
match goal with
| [|- let _ : _ ?T0 ?T1 ?T2 ?T3 ?T4 ?T5 ?T6 ?T7 ?T8 := _ in _ ?e0 ?e1 ?e2 ?e3 ?e4 ?e5 ?e6 ?e7 ?e8] => intro X; unfold X; clear X;
paco_cont9
(e0: T0)
(e1: T1 e0)
(e2: T2 e0 e1)
(e3: T3 e0 e1 e2)
(e4: T4 e0 e1 e2 e3)
(e5: T5 e0 e1 e2 e3 e4)
(e6: T6 e0 e1 e2 e3 e4 e5)
(e7: T7 e0 e1 e2 e3 e4 e5 e6)
(e8: T8 e0 e1 e2 e3 e4 e5 e6 e7)
end.
Ltac paco_post_match9 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| forall _ _ _ _ _ _ _ _ _, bot9 _ _ _ _ _ _ _ _ _ -> _ => clear H; tac1 cr
| forall _ _ _ _ _ _ _ _ _, ?pr _ _ _ _ _ _ _ _ _ -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Ltac paco_simp_hyp9 CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev9; paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
[..|match goal with [|-_paco_id (?a = ?b)] => unfold _paco_id; reflexivity end];
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp9 CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp9 CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev9; paco_revert_hyp _paco_mark
].
Tactic Notation "paco_post9" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match9 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp9 CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** *** Arity 10
*)
Lemma _paco_convert10: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9
(paco10: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
(y7: @T7 y0 y1 y2 y3 y4 y5 y6)
(y8: @T8 y0 y1 y2 y3 y4 y5 y6 y7)
(y9: @T9 y0 y1 y2 y3 y4 y5 y6 y7 y8)
, Prop)
y0 y1 y2 y3 y4 y5 y6 y7 y8 y9
(CONVERT: forall
(x0: @T0)
(x1: @T1 x0)
(x2: @T2 x0 x1)
(x3: @T3 x0 x1 x2)
(x4: @T4 x0 x1 x2 x3)
(x5: @T5 x0 x1 x2 x3 x4)
(x6: @T6 x0 x1 x2 x3 x4 x5)
(x7: @T7 x0 x1 x2 x3 x4 x5 x6)
(x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7)
(x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8)
(EQ: _paco_id (@exist10T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 = @exist10T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9))
, @paco10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9),
@paco10 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9.
Proof. intros. apply CONVERT; reflexivity. Qed.
Lemma _paco_convert_rev10: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9
(paco10: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
(y7: @T7 y0 y1 y2 y3 y4 y5 y6)
(y8: @T8 y0 y1 y2 y3 y4 y5 y6 y7)
(y9: @T9 y0 y1 y2 y3 y4 y5 y6 y7 y8)
, Prop)
y0 y1 y2 y3 y4 y5 y6 y7 y8 y9
x0 x1 x2 x3 x4 x5 x6 x7 x8 x9
(EQ: _paco_id (@exist10T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 = @exist10T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9))
(PACO: @paco10 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9),
@paco10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9.
Proof. intros.
apply (@f_equal (@sig10T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9) _ (fun x => @paco10
x.(proj10T0)
x.(proj10T1)
x.(proj10T2)
x.(proj10T3)
x.(proj10T4)
x.(proj10T5)
x.(proj10T6)
x.(proj10T7)
x.(proj10T8)
x.(proj10T9)
)) in EQ. simpl in EQ. rewrite EQ. apply PACO.
Qed.
Ltac paco_convert_rev10 := match goal with
| [H: _paco_id (@exist10T _ _ _ _ _ _ _ _ _ _ ?x0 ?x1 ?x2 ?x3 ?x4 ?x5 ?x6 ?x7 ?x8 ?x9 = @exist10T _ _ _ _ _ _ _ _ _ _ ?y0 ?y1 ?y2 ?y3 ?y4 ?y5 ?y6 ?y7 ?y8 ?y9) |- _] =>
eapply _paco_convert_rev10; [eapply H; clear H|..]; clear x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 H
end.
Ltac paco_cont10 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 :=
let x0 := fresh "_paco_v_" in
let x1 := fresh "_paco_v_" in
let x2 := fresh "_paco_v_" in
let x3 := fresh "_paco_v_" in
let x4 := fresh "_paco_v_" in
let x5 := fresh "_paco_v_" in
let x6 := fresh "_paco_v_" in
let x7 := fresh "_paco_v_" in
let x8 := fresh "_paco_v_" in
let x9 := fresh "_paco_v_" in
apply _paco_convert10;
intros x0 x1 x2 x3 x4 x5 x6 x7 x8 x9;
move x0 at top; move x1 at top; move x2 at top; move x3 at top; move x4 at top; move x5 at top; move x6 at top; move x7 at top; move x8 at top; move x9 at top;
paco_generalize_hyp _paco_mark; revert x0 x1 x2 x3 x4 x5 x6 x7 x8 x9.
Lemma _paco_pre10: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 (gf: rel10 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9) x0 x1 x2 x3 x4 x5 x6 x7 x8 x9
(X: let gf' := gf in gf' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9), gf x0 x1 x2 x3 x4 x5 x6 x7 x8 x9.
Proof. intros; apply X. Defined.
Ltac paco_pre10 := let X := fresh "_paco_X_" in
generalize _paco_mark_cons; repeat intro;
apply _paco_pre10;
match goal with
| [|- let _ : _ ?T0 ?T1 ?T2 ?T3 ?T4 ?T5 ?T6 ?T7 ?T8 ?T9 := _ in _ ?e0 ?e1 ?e2 ?e3 ?e4 ?e5 ?e6 ?e7 ?e8 ?e9] => intro X; unfold X; clear X;
paco_cont10
(e0: T0)
(e1: T1 e0)
(e2: T2 e0 e1)
(e3: T3 e0 e1 e2)
(e4: T4 e0 e1 e2 e3)
(e5: T5 e0 e1 e2 e3 e4)
(e6: T6 e0 e1 e2 e3 e4 e5)
(e7: T7 e0 e1 e2 e3 e4 e5 e6)
(e8: T8 e0 e1 e2 e3 e4 e5 e6 e7)
(e9: T9 e0 e1 e2 e3 e4 e5 e6 e7 e8)
end.
Ltac paco_post_match10 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| forall _ _ _ _ _ _ _ _ _ _, bot10 _ _ _ _ _ _ _ _ _ _ -> _ => clear H; tac1 cr
| forall _ _ _ _ _ _ _ _ _ _, ?pr _ _ _ _ _ _ _ _ _ _ -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Ltac paco_simp_hyp10 CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev10; paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
[..|match goal with [|-_paco_id (?a = ?b)] => unfold _paco_id; reflexivity end];
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp10 CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp10 CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev10; paco_revert_hyp _paco_mark
].
Tactic Notation "paco_post10" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match10 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp10 CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** *** Arity 11
*)
Lemma _paco_convert11: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10
(paco11: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
(y7: @T7 y0 y1 y2 y3 y4 y5 y6)
(y8: @T8 y0 y1 y2 y3 y4 y5 y6 y7)
(y9: @T9 y0 y1 y2 y3 y4 y5 y6 y7 y8)
(y10: @T10 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9)
, Prop)
y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10
(CONVERT: forall
(x0: @T0)
(x1: @T1 x0)
(x2: @T2 x0 x1)
(x3: @T3 x0 x1 x2)
(x4: @T4 x0 x1 x2 x3)
(x5: @T5 x0 x1 x2 x3 x4)
(x6: @T6 x0 x1 x2 x3 x4 x5)
(x7: @T7 x0 x1 x2 x3 x4 x5 x6)
(x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7)
(x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8)
(x10: @T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9)
(EQ: _paco_id (@exist11T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 = @exist11T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10))
, @paco11 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10),
@paco11 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10.
Proof. intros. apply CONVERT; reflexivity. Qed.
Lemma _paco_convert_rev11: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10
(paco11: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
(y7: @T7 y0 y1 y2 y3 y4 y5 y6)
(y8: @T8 y0 y1 y2 y3 y4 y5 y6 y7)
(y9: @T9 y0 y1 y2 y3 y4 y5 y6 y7 y8)
(y10: @T10 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9)
, Prop)
y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10
x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
(EQ: _paco_id (@exist11T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 = @exist11T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10))
(PACO: @paco11 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10),
@paco11 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10.
Proof. intros.
apply (@f_equal (@sig11T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10) _ (fun x => @paco11
x.(proj11T0)
x.(proj11T1)
x.(proj11T2)
x.(proj11T3)
x.(proj11T4)
x.(proj11T5)
x.(proj11T6)
x.(proj11T7)
x.(proj11T8)
x.(proj11T9)
x.(proj11T10)
)) in EQ. simpl in EQ. rewrite EQ. apply PACO.
Qed.
Ltac paco_convert_rev11 := match goal with
| [H: _paco_id (@exist11T _ _ _ _ _ _ _ _ _ _ _ ?x0 ?x1 ?x2 ?x3 ?x4 ?x5 ?x6 ?x7 ?x8 ?x9 ?x10 = @exist11T _ _ _ _ _ _ _ _ _ _ _ ?y0 ?y1 ?y2 ?y3 ?y4 ?y5 ?y6 ?y7 ?y8 ?y9 ?y10) |- _] =>
eapply _paco_convert_rev11; [eapply H; clear H|..]; clear x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 H
end.
Ltac paco_cont11 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10 :=
let x0 := fresh "_paco_v_" in
let x1 := fresh "_paco_v_" in
let x2 := fresh "_paco_v_" in
let x3 := fresh "_paco_v_" in
let x4 := fresh "_paco_v_" in
let x5 := fresh "_paco_v_" in
let x6 := fresh "_paco_v_" in
let x7 := fresh "_paco_v_" in
let x8 := fresh "_paco_v_" in
let x9 := fresh "_paco_v_" in
let x10 := fresh "_paco_v_" in
apply _paco_convert11;
intros x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10;
move x0 at top; move x1 at top; move x2 at top; move x3 at top; move x4 at top; move x5 at top; move x6 at top; move x7 at top; move x8 at top; move x9 at top; move x10 at top;
paco_generalize_hyp _paco_mark; revert x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10.
Lemma _paco_pre11: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 (gf: rel11 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10) x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
(X: let gf' := gf in gf' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10), gf x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10.
Proof. intros; apply X. Defined.
Ltac paco_pre11 := let X := fresh "_paco_X_" in
generalize _paco_mark_cons; repeat intro;
apply _paco_pre11;
match goal with
| [|- let _ : _ ?T0 ?T1 ?T2 ?T3 ?T4 ?T5 ?T6 ?T7 ?T8 ?T9 ?T10 := _ in _ ?e0 ?e1 ?e2 ?e3 ?e4 ?e5 ?e6 ?e7 ?e8 ?e9 ?e10] => intro X; unfold X; clear X;
paco_cont11
(e0: T0)
(e1: T1 e0)
(e2: T2 e0 e1)
(e3: T3 e0 e1 e2)
(e4: T4 e0 e1 e2 e3)
(e5: T5 e0 e1 e2 e3 e4)
(e6: T6 e0 e1 e2 e3 e4 e5)
(e7: T7 e0 e1 e2 e3 e4 e5 e6)
(e8: T8 e0 e1 e2 e3 e4 e5 e6 e7)
(e9: T9 e0 e1 e2 e3 e4 e5 e6 e7 e8)
(e10: T10 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9)
end.
Ltac paco_post_match11 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| forall _ _ _ _ _ _ _ _ _ _ _, bot11 _ _ _ _ _ _ _ _ _ _ _ -> _ => clear H; tac1 cr
| forall _ _ _ _ _ _ _ _ _ _ _, ?pr _ _ _ _ _ _ _ _ _ _ _ -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Ltac paco_simp_hyp11 CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev11; paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
[..|match goal with [|-_paco_id (?a = ?b)] => unfold _paco_id; reflexivity end];
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp11 CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp11 CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev11; paco_revert_hyp _paco_mark
].
Tactic Notation "paco_post11" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match11 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp11 CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** *** Arity 12
*)
Lemma _paco_convert12: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11
(paco12: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
(y7: @T7 y0 y1 y2 y3 y4 y5 y6)
(y8: @T8 y0 y1 y2 y3 y4 y5 y6 y7)
(y9: @T9 y0 y1 y2 y3 y4 y5 y6 y7 y8)
(y10: @T10 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9)
(y11: @T11 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10)
, Prop)
y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11
(CONVERT: forall
(x0: @T0)
(x1: @T1 x0)
(x2: @T2 x0 x1)
(x3: @T3 x0 x1 x2)
(x4: @T4 x0 x1 x2 x3)
(x5: @T5 x0 x1 x2 x3 x4)
(x6: @T6 x0 x1 x2 x3 x4 x5)
(x7: @T7 x0 x1 x2 x3 x4 x5 x6)
(x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7)
(x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8)
(x10: @T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9)
(x11: @T11 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10)
(EQ: _paco_id (@exist12T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 = @exist12T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11))
, @paco12 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11),
@paco12 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11.
Proof. intros. apply CONVERT; reflexivity. Qed.
Lemma _paco_convert_rev12: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11
(paco12: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
(y7: @T7 y0 y1 y2 y3 y4 y5 y6)
(y8: @T8 y0 y1 y2 y3 y4 y5 y6 y7)
(y9: @T9 y0 y1 y2 y3 y4 y5 y6 y7 y8)
(y10: @T10 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9)
(y11: @T11 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10)
, Prop)
y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11
x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11
(EQ: _paco_id (@exist12T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 = @exist12T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11))
(PACO: @paco12 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11),
@paco12 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11.
Proof. intros.
apply (@f_equal (@sig12T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11) _ (fun x => @paco12
x.(proj12T0)
x.(proj12T1)
x.(proj12T2)
x.(proj12T3)
x.(proj12T4)
x.(proj12T5)
x.(proj12T6)
x.(proj12T7)
x.(proj12T8)
x.(proj12T9)
x.(proj12T10)
x.(proj12T11)
)) in EQ. simpl in EQ. rewrite EQ. apply PACO.
Qed.
Ltac paco_convert_rev12 := match goal with
| [H: _paco_id (@exist12T _ _ _ _ _ _ _ _ _ _ _ _ ?x0 ?x1 ?x2 ?x3 ?x4 ?x5 ?x6 ?x7 ?x8 ?x9 ?x10 ?x11 = @exist12T _ _ _ _ _ _ _ _ _ _ _ _ ?y0 ?y1 ?y2 ?y3 ?y4 ?y5 ?y6 ?y7 ?y8 ?y9 ?y10 ?y11) |- _] =>
eapply _paco_convert_rev12; [eapply H; clear H|..]; clear x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 H
end.
Ltac paco_cont12 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10 e11 :=
let x0 := fresh "_paco_v_" in
let x1 := fresh "_paco_v_" in
let x2 := fresh "_paco_v_" in
let x3 := fresh "_paco_v_" in
let x4 := fresh "_paco_v_" in
let x5 := fresh "_paco_v_" in
let x6 := fresh "_paco_v_" in
let x7 := fresh "_paco_v_" in
let x8 := fresh "_paco_v_" in
let x9 := fresh "_paco_v_" in
let x10 := fresh "_paco_v_" in
let x11 := fresh "_paco_v_" in
apply _paco_convert12;
intros x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11;
move x0 at top; move x1 at top; move x2 at top; move x3 at top; move x4 at top; move x5 at top; move x6 at top; move x7 at top; move x8 at top; move x9 at top; move x10 at top; move x11 at top;
paco_generalize_hyp _paco_mark; revert x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11.
Lemma _paco_pre12: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 (gf: rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11) x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11
(X: let gf' := gf in gf' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11), gf x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11.
Proof. intros; apply X. Defined.
Ltac paco_pre12 := let X := fresh "_paco_X_" in
generalize _paco_mark_cons; repeat intro;
apply _paco_pre12;
match goal with
| [|- let _ : _ ?T0 ?T1 ?T2 ?T3 ?T4 ?T5 ?T6 ?T7 ?T8 ?T9 ?T10 ?T11 := _ in _ ?e0 ?e1 ?e2 ?e3 ?e4 ?e5 ?e6 ?e7 ?e8 ?e9 ?e10 ?e11] => intro X; unfold X; clear X;
paco_cont12
(e0: T0)
(e1: T1 e0)
(e2: T2 e0 e1)
(e3: T3 e0 e1 e2)
(e4: T4 e0 e1 e2 e3)
(e5: T5 e0 e1 e2 e3 e4)
(e6: T6 e0 e1 e2 e3 e4 e5)
(e7: T7 e0 e1 e2 e3 e4 e5 e6)
(e8: T8 e0 e1 e2 e3 e4 e5 e6 e7)
(e9: T9 e0 e1 e2 e3 e4 e5 e6 e7 e8)
(e10: T10 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9)
(e11: T11 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10)
end.
Ltac paco_post_match12 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| forall _ _ _ _ _ _ _ _ _ _ _ _, bot12 _ _ _ _ _ _ _ _ _ _ _ _ -> _ => clear H; tac1 cr
| forall _ _ _ _ _ _ _ _ _ _ _ _, ?pr _ _ _ _ _ _ _ _ _ _ _ _ -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Ltac paco_simp_hyp12 CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev12; paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
[..|match goal with [|-_paco_id (?a = ?b)] => unfold _paco_id; reflexivity end];
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp12 CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp12 CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev12; paco_revert_hyp _paco_mark
].
Tactic Notation "paco_post12" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match12 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp12 CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** *** Arity 13
*)
Lemma _paco_convert13: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12
(paco13: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
(y7: @T7 y0 y1 y2 y3 y4 y5 y6)
(y8: @T8 y0 y1 y2 y3 y4 y5 y6 y7)
(y9: @T9 y0 y1 y2 y3 y4 y5 y6 y7 y8)
(y10: @T10 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9)
(y11: @T11 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10)
(y12: @T12 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11)
, Prop)
y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11 y12
(CONVERT: forall
(x0: @T0)
(x1: @T1 x0)
(x2: @T2 x0 x1)
(x3: @T3 x0 x1 x2)
(x4: @T4 x0 x1 x2 x3)
(x5: @T5 x0 x1 x2 x3 x4)
(x6: @T6 x0 x1 x2 x3 x4 x5)
(x7: @T7 x0 x1 x2 x3 x4 x5 x6)
(x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7)
(x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8)
(x10: @T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9)
(x11: @T11 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10)
(x12: @T12 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11)
(EQ: _paco_id (@exist13T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 = @exist13T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11 y12))
, @paco13 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12),
@paco13 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11 y12.
Proof. intros. apply CONVERT; reflexivity. Qed.
Lemma _paco_convert_rev13: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12
(paco13: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
(y7: @T7 y0 y1 y2 y3 y4 y5 y6)
(y8: @T8 y0 y1 y2 y3 y4 y5 y6 y7)
(y9: @T9 y0 y1 y2 y3 y4 y5 y6 y7 y8)
(y10: @T10 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9)
(y11: @T11 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10)
(y12: @T12 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11)
, Prop)
y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11 y12
x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12
(EQ: _paco_id (@exist13T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 = @exist13T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11 y12))
(PACO: @paco13 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11 y12),
@paco13 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12.
Proof. intros.
apply (@f_equal (@sig13T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12) _ (fun x => @paco13
x.(proj13T0)
x.(proj13T1)
x.(proj13T2)
x.(proj13T3)
x.(proj13T4)
x.(proj13T5)
x.(proj13T6)
x.(proj13T7)
x.(proj13T8)
x.(proj13T9)
x.(proj13T10)
x.(proj13T11)
x.(proj13T12)
)) in EQ. simpl in EQ. rewrite EQ. apply PACO.
Qed.
Ltac paco_convert_rev13 := match goal with
| [H: _paco_id (@exist13T _ _ _ _ _ _ _ _ _ _ _ _ _ ?x0 ?x1 ?x2 ?x3 ?x4 ?x5 ?x6 ?x7 ?x8 ?x9 ?x10 ?x11 ?x12 = @exist13T _ _ _ _ _ _ _ _ _ _ _ _ _ ?y0 ?y1 ?y2 ?y3 ?y4 ?y5 ?y6 ?y7 ?y8 ?y9 ?y10 ?y11 ?y12) |- _] =>
eapply _paco_convert_rev13; [eapply H; clear H|..]; clear x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 H
end.
Ltac paco_cont13 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10 e11 e12 :=
let x0 := fresh "_paco_v_" in
let x1 := fresh "_paco_v_" in
let x2 := fresh "_paco_v_" in
let x3 := fresh "_paco_v_" in
let x4 := fresh "_paco_v_" in
let x5 := fresh "_paco_v_" in
let x6 := fresh "_paco_v_" in
let x7 := fresh "_paco_v_" in
let x8 := fresh "_paco_v_" in
let x9 := fresh "_paco_v_" in
let x10 := fresh "_paco_v_" in
let x11 := fresh "_paco_v_" in
let x12 := fresh "_paco_v_" in
apply _paco_convert13;
intros x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12;
move x0 at top; move x1 at top; move x2 at top; move x3 at top; move x4 at top; move x5 at top; move x6 at top; move x7 at top; move x8 at top; move x9 at top; move x10 at top; move x11 at top; move x12 at top;
paco_generalize_hyp _paco_mark; revert x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12.
Lemma _paco_pre13: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 (gf: rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12) x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12
(X: let gf' := gf in gf' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12), gf x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12.
Proof. intros; apply X. Defined.
Ltac paco_pre13 := let X := fresh "_paco_X_" in
generalize _paco_mark_cons; repeat intro;
apply _paco_pre13;
match goal with
| [|- let _ : _ ?T0 ?T1 ?T2 ?T3 ?T4 ?T5 ?T6 ?T7 ?T8 ?T9 ?T10 ?T11 ?T12 := _ in _ ?e0 ?e1 ?e2 ?e3 ?e4 ?e5 ?e6 ?e7 ?e8 ?e9 ?e10 ?e11 ?e12] => intro X; unfold X; clear X;
paco_cont13
(e0: T0)
(e1: T1 e0)
(e2: T2 e0 e1)
(e3: T3 e0 e1 e2)
(e4: T4 e0 e1 e2 e3)
(e5: T5 e0 e1 e2 e3 e4)
(e6: T6 e0 e1 e2 e3 e4 e5)
(e7: T7 e0 e1 e2 e3 e4 e5 e6)
(e8: T8 e0 e1 e2 e3 e4 e5 e6 e7)
(e9: T9 e0 e1 e2 e3 e4 e5 e6 e7 e8)
(e10: T10 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9)
(e11: T11 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10)
(e12: T12 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10 e11)
end.
Ltac paco_post_match13 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| forall _ _ _ _ _ _ _ _ _ _ _ _ _, bot13 _ _ _ _ _ _ _ _ _ _ _ _ _ -> _ => clear H; tac1 cr
| forall _ _ _ _ _ _ _ _ _ _ _ _ _, ?pr _ _ _ _ _ _ _ _ _ _ _ _ _ -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Ltac paco_simp_hyp13 CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev13; paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
[..|match goal with [|-_paco_id (?a = ?b)] => unfold _paco_id; reflexivity end];
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp13 CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp13 CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev13; paco_revert_hyp _paco_mark
].
Tactic Notation "paco_post13" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match13 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp13 CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** *** Arity 14
*)
Lemma _paco_convert14: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13
(paco14: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
(y7: @T7 y0 y1 y2 y3 y4 y5 y6)
(y8: @T8 y0 y1 y2 y3 y4 y5 y6 y7)
(y9: @T9 y0 y1 y2 y3 y4 y5 y6 y7 y8)
(y10: @T10 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9)
(y11: @T11 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10)
(y12: @T12 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11)
(y13: @T13 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11 y12)
, Prop)
y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11 y12 y13
(CONVERT: forall
(x0: @T0)
(x1: @T1 x0)
(x2: @T2 x0 x1)
(x3: @T3 x0 x1 x2)
(x4: @T4 x0 x1 x2 x3)
(x5: @T5 x0 x1 x2 x3 x4)
(x6: @T6 x0 x1 x2 x3 x4 x5)
(x7: @T7 x0 x1 x2 x3 x4 x5 x6)
(x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7)
(x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8)
(x10: @T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9)
(x11: @T11 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10)
(x12: @T12 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11)
(x13: @T13 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)
(EQ: _paco_id (@exist14T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 = @exist14T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11 y12 y13))
, @paco14 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13),
@paco14 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11 y12 y13.
Proof. intros. apply CONVERT; reflexivity. Qed.
Lemma _paco_convert_rev14: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13
(paco14: forall
(y0: @T0)
(y1: @T1 y0)
(y2: @T2 y0 y1)
(y3: @T3 y0 y1 y2)
(y4: @T4 y0 y1 y2 y3)
(y5: @T5 y0 y1 y2 y3 y4)
(y6: @T6 y0 y1 y2 y3 y4 y5)
(y7: @T7 y0 y1 y2 y3 y4 y5 y6)
(y8: @T8 y0 y1 y2 y3 y4 y5 y6 y7)
(y9: @T9 y0 y1 y2 y3 y4 y5 y6 y7 y8)
(y10: @T10 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9)
(y11: @T11 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10)
(y12: @T12 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11)
(y13: @T13 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11 y12)
, Prop)
y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11 y12 y13
x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13
(EQ: _paco_id (@exist14T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 = @exist14T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11 y12 y13))
(PACO: @paco14 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 y10 y11 y12 y13),
@paco14 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13.
Proof. intros.
apply (@f_equal (@sig14T T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13) _ (fun x => @paco14
x.(proj14T0)
x.(proj14T1)
x.(proj14T2)
x.(proj14T3)
x.(proj14T4)
x.(proj14T5)
x.(proj14T6)
x.(proj14T7)
x.(proj14T8)
x.(proj14T9)
x.(proj14T10)
x.(proj14T11)
x.(proj14T12)
x.(proj14T13)
)) in EQ. simpl in EQ. rewrite EQ. apply PACO.
Qed.
Ltac paco_convert_rev14 := match goal with
| [H: _paco_id (@exist14T _ _ _ _ _ _ _ _ _ _ _ _ _ _ ?x0 ?x1 ?x2 ?x3 ?x4 ?x5 ?x6 ?x7 ?x8 ?x9 ?x10 ?x11 ?x12 ?x13 = @exist14T _ _ _ _ _ _ _ _ _ _ _ _ _ _ ?y0 ?y1 ?y2 ?y3 ?y4 ?y5 ?y6 ?y7 ?y8 ?y9 ?y10 ?y11 ?y12 ?y13) |- _] =>
eapply _paco_convert_rev14; [eapply H; clear H|..]; clear x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 H
end.
Ltac paco_cont14 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10 e11 e12 e13 :=
let x0 := fresh "_paco_v_" in
let x1 := fresh "_paco_v_" in
let x2 := fresh "_paco_v_" in
let x3 := fresh "_paco_v_" in
let x4 := fresh "_paco_v_" in
let x5 := fresh "_paco_v_" in
let x6 := fresh "_paco_v_" in
let x7 := fresh "_paco_v_" in
let x8 := fresh "_paco_v_" in
let x9 := fresh "_paco_v_" in
let x10 := fresh "_paco_v_" in
let x11 := fresh "_paco_v_" in
let x12 := fresh "_paco_v_" in
let x13 := fresh "_paco_v_" in
apply _paco_convert14;
intros x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13;
move x0 at top; move x1 at top; move x2 at top; move x3 at top; move x4 at top; move x5 at top; move x6 at top; move x7 at top; move x8 at top; move x9 at top; move x10 at top; move x11 at top; move x12 at top; move x13 at top;
paco_generalize_hyp _paco_mark; revert x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13.
Lemma _paco_pre14: forall T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 (gf: rel14 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13) x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13
(X: let gf' := gf in gf' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13), gf x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13.
Proof. intros; apply X. Defined.
Ltac paco_pre14 := let X := fresh "_paco_X_" in
generalize _paco_mark_cons; repeat intro;
apply _paco_pre14;
match goal with
| [|- let _ : _ ?T0 ?T1 ?T2 ?T3 ?T4 ?T5 ?T6 ?T7 ?T8 ?T9 ?T10 ?T11 ?T12 ?T13 := _ in _ ?e0 ?e1 ?e2 ?e3 ?e4 ?e5 ?e6 ?e7 ?e8 ?e9 ?e10 ?e11 ?e12 ?e13] => intro X; unfold X; clear X;
paco_cont14
(e0: T0)
(e1: T1 e0)
(e2: T2 e0 e1)
(e3: T3 e0 e1 e2)
(e4: T4 e0 e1 e2 e3)
(e5: T5 e0 e1 e2 e3 e4)
(e6: T6 e0 e1 e2 e3 e4 e5)
(e7: T7 e0 e1 e2 e3 e4 e5 e6)
(e8: T8 e0 e1 e2 e3 e4 e5 e6 e7)
(e9: T9 e0 e1 e2 e3 e4 e5 e6 e7 e8)
(e10: T10 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9)
(e11: T11 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10)
(e12: T12 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10 e11)
(e13: T13 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10 e11 e12)
end.
Ltac paco_post_match14 INC tac1 tac2 :=
let cr := fresh "_paco_cr_" in intros cr INC; repeat (red in INC);
match goal with [H: ?x |- _] => match x with
| forall _ _ _ _ _ _ _ _ _ _ _ _ _ _, bot14 _ _ _ _ _ _ _ _ _ _ _ _ _ _ -> _ => clear H; tac1 cr
| forall _ _ _ _ _ _ _ _ _ _ _ _ _ _, ?pr _ _ _ _ _ _ _ _ _ _ _ _ _ _ -> _ => paco_post_var INC pr cr; tac2 pr cr
| _ => tac1 cr
end end.
Ltac paco_simp_hyp14 CIH :=
let EP := fresh "_paco_EP_" in
let FP := fresh "_paco_FF_" in
let TP := fresh "_paco_TP_" in
let XP := fresh "_paco_XP_" in
let PP := type of CIH in
evar (EP: Prop);
assert (TP: False -> PP) by (
intros FP; generalize _paco_mark_cons;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev14; paco_revert_hyp _paco_mark;
let con := get_concl in set (TP:=con); revert EP; instantiate (1:= con); destruct FP);
clear TP;
assert (XP: EP) by (unfold EP; clear -CIH; repeat intro; apply CIH;
first [
(repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
[..|match goal with [|-_paco_id (?a = ?b)] => unfold _paco_id; reflexivity end];
first [eassumption|apply _paco_foo_cons]); fail
| (repeat match goal with | [ |- @ex _ _ ] => eexists | [ |- _ /\ _ ] => split end;
(try unfold _paco_id); eauto using _paco_foo_cons)]);
unfold EP in *; clear EP CIH; rename XP into CIH.
Ltac paco_post_simp14 CIH :=
let CIH := fresh CIH in
intro CIH; paco_simp_hyp14 CIH;
first [try(match goal with [ |- context[_paco_id] ] => fail 2 | [ |- context[_paco_foo] ] => fail 2 end) |
let TMP := fresh "_paco_TMP_" in
generalize _paco_mark_cons; intro TMP;
repeat intro; paco_rename_last; paco_destruct_hyp _paco_mark;
paco_convert_rev14; paco_revert_hyp _paco_mark
].
Tactic Notation "paco_post14" ident(CIH) "with" ident(nr) :=
let INC := fresh "_paco_inc_" in
paco_post_match14 INC ltac:(paco_ren_r nr) paco_ren_pr; paco_post_simp14 CIH;
let CIH' := fresh CIH in try rename INC into CIH'.
(** ** External interface *)
(** We provide our main tactics:
- [pcofix{n} ident using lemma with ident']
where [ident] is the identifier used to name the generated coinduction hypothesis,
[lemma] is an expression denoting which accumulation lemma is to be used, and
[ident'] is the identifier used to name the accumulation variable.
*)
Tactic Notation "pcofix0" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre0; eapply lem; [..|paco_post0 CIH with r].
Tactic Notation "pcofix1" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre1; eapply lem; [..|paco_post1 CIH with r].
Tactic Notation "pcofix2" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre2; eapply lem; [..|paco_post2 CIH with r].
Tactic Notation "pcofix3" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre3; eapply lem; [..|paco_post3 CIH with r].
Tactic Notation "pcofix4" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre4; eapply lem; [..|paco_post4 CIH with r].
Tactic Notation "pcofix5" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre5; eapply lem; [..|paco_post5 CIH with r].
Tactic Notation "pcofix6" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre6; eapply lem; [..|paco_post6 CIH with r].
Tactic Notation "pcofix7" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre7; eapply lem; [..|paco_post7 CIH with r].
Tactic Notation "pcofix8" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre8; eapply lem; [..|paco_post8 CIH with r].
Tactic Notation "pcofix9" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre9; eapply lem; [..|paco_post9 CIH with r].
Tactic Notation "pcofix10" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre10; eapply lem; [..|paco_post10 CIH with r].
Tactic Notation "pcofix11" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre11; eapply lem; [..|paco_post11 CIH with r].
Tactic Notation "pcofix12" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre12; eapply lem; [..|paco_post12 CIH with r].
Tactic Notation "pcofix13" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre13; eapply lem; [..|paco_post13 CIH with r].
Tactic Notation "pcofix14" ident(CIH) "using" constr(lem) "with" ident(r) :=
paco_pre14; eapply lem; [..|paco_post14 CIH with r].
(** [pcofix] automatically figures out the appropriate index [n] from
the type of the accumulation lemma [lem] and applies [pcofix{n}].
*)
Tactic Notation "pcofix" ident(CIH) "using" constr(lem) "with" ident(nr) :=
let N := fresh "_paco_N_" in let TMP := fresh "_paco_TMP_" in
evar (N : nat);
let P := type of lem in
assert (TMP: False -> P) by
(intro TMP; repeat intro; match goal with [H : _ |- _] => revert H end;
match goal with
| [|- _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ -> _] => revert N; instantiate (1 := 14)
| [|- _ _ _ _ _ _ _ _ _ _ _ _ _ _ -> _] => revert N; instantiate (1 := 13)
| [|- _ _ _ _ _ _ _ _ _ _ _ _ _ -> _] => revert N; instantiate (1 := 12)
| [|- _ _ _ _ _ _ _ _ _ _ _ _ -> _] => revert N; instantiate (1 := 11)
| [|- _ _ _ _ _ _ _ _ _ _ _ -> _] => revert N; instantiate (1 := 10)
| [|- _ _ _ _ _ _ _ _ _ _ -> _] => revert N; instantiate (1 := 9)
| [|- _ _ _ _ _ _ _ _ _ -> _] => revert N; instantiate (1 := 8)
| [|- _ _ _ _ _ _ _ _ -> _] => revert N; instantiate (1 := 7)
| [|- _ _ _ _ _ _ _ -> _] => revert N; instantiate (1 := 6)
| [|- _ _ _ _ _ _ -> _] => revert N; instantiate (1 := 5)
| [|- _ _ _ _ _ -> _] => revert N; instantiate (1 := 4)
| [|- _ _ _ _ -> _] => revert N; instantiate (1 := 3)
| [|- _ _ _ -> _] => revert N; instantiate (1 := 2)
| [|- _ _ -> _] => revert N; instantiate (1 := 1)
| [|- _ -> _] => revert N; instantiate (1 := 0)
end; destruct TMP);
clear TMP;
revert N;
match goal with
| [|- let _ := 0 in _] => intros _; pcofix0 CIH using lem with nr
| [|- let _ := 1 in _] => intros _; pcofix1 CIH using lem with nr
| [|- let _ := 2 in _] => intros _; pcofix2 CIH using lem with nr
| [|- let _ := 3 in _] => intros _; pcofix3 CIH using lem with nr
| [|- let _ := 4 in _] => intros _; pcofix4 CIH using lem with nr
| [|- let _ := 5 in _] => intros _; pcofix5 CIH using lem with nr
| [|- let _ := 6 in _] => intros _; pcofix6 CIH using lem with nr
| [|- let _ := 7 in _] => intros _; pcofix7 CIH using lem with nr
| [|- let _ := 8 in _] => intros _; pcofix8 CIH using lem with nr
| [|- let _ := 9 in _] => intros _; pcofix9 CIH using lem with nr
| [|- let _ := 10 in _] => intros _; pcofix10 CIH using lem with nr
| [|- let _ := 11 in _] => intros _; pcofix11 CIH using lem with nr
| [|- let _ := 12 in _] => intros _; pcofix12 CIH using lem with nr
| [|- let _ := 13 in _] => intros _; pcofix13 CIH using lem with nr
| [|- let _ := 14 in _] => intros _; pcofix14 CIH using lem with nr
end.
Tactic Notation "pcofix" ident(CIH) "using" constr(lem) :=
pcofix CIH using lem with r.
(** ** Type Class for acc, mult, fold and unfold
*)
Class paco_class (A : Prop) :=
{ pacoacctyp: Type
; pacoacc : pacoacctyp
; pacomulttyp: Type
; pacomult : pacomulttyp
; pacofoldtyp: Type
; pacofold : pacofoldtyp
; pacounfoldtyp: Type
; pacounfold : pacounfoldtyp
}.
Create HintDb paco.
|
/* roots/falsepos.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Reid Priedhorsky, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* falsepos.c -- falsepos root finding algorithm
The false position algorithm uses bracketing by linear interpolation.
If a linear interpolation step would decrease the size of the
bracket by less than a bisection step would then the algorithm
takes a bisection step instead.
The last linear interpolation estimate of the root is used. If a
bisection step causes it to fall outside the brackets then it is
replaced by the bisection estimate (x_upper + x_lower)/2.
*/
#include <config.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
#include "roots.h"
typedef struct
{
double f_lower, f_upper;
}
falsepos_state_t;
static int falsepos_init (void * vstate, gsl_function * f, double * root, double x_lower, double x_upper);
static int falsepos_iterate (void * vstate, gsl_function * f, double * root, double * x_lower, double * x_upper);
static int
falsepos_init (void * vstate, gsl_function * f, double * root, double x_lower, double x_upper)
{
falsepos_state_t * state = (falsepos_state_t *) vstate;
double f_lower, f_upper ;
*root = 0.5 * (x_lower + x_upper);
SAFE_FUNC_CALL (f, x_lower, &f_lower);
SAFE_FUNC_CALL (f, x_upper, &f_upper);
state->f_lower = f_lower;
state->f_upper = f_upper;
if ((f_lower < 0.0 && f_upper < 0.0) || (f_lower > 0.0 && f_upper > 0.0))
{
GSL_ERROR ("endpoints do not straddle y=0", GSL_EINVAL);
}
return GSL_SUCCESS;
}
static int
falsepos_iterate (void * vstate, gsl_function * f, double * root, double * x_lower, double * x_upper)
{
falsepos_state_t * state = (falsepos_state_t *) vstate;
double x_linear, f_linear;
double x_bisect, f_bisect;
double x_left = *x_lower ;
double x_right = *x_upper ;
double f_lower = state->f_lower;
double f_upper = state->f_upper;
double w ;
if (f_lower == 0.0)
{
*root = x_left ;
*x_upper = x_left;
return GSL_SUCCESS;
}
if (f_upper == 0.0)
{
*root = x_right ;
*x_lower = x_right;
return GSL_SUCCESS;
}
/* Draw a line between f(*lower_bound) and f(*upper_bound) and
note where it crosses the X axis; that's where we will
split the interval. */
x_linear = x_right - (f_upper * (x_left - x_right) / (f_lower - f_upper));
SAFE_FUNC_CALL (f, x_linear, &f_linear);
if (f_linear == 0.0)
{
*root = x_linear;
*x_lower = x_linear;
*x_upper = x_linear;
return GSL_SUCCESS;
}
/* Discard the half of the interval which doesn't contain the root. */
if ((f_lower > 0.0 && f_linear < 0.0) || (f_lower < 0.0 && f_linear > 0.0))
{
*root = x_linear ;
*x_upper = x_linear;
state->f_upper = f_linear;
w = x_linear - x_left ;
}
else
{
*root = x_linear ;
*x_lower = x_linear;
state->f_lower = f_linear;
w = x_right - x_linear;
}
if (w < 0.5 * (x_right - x_left))
{
return GSL_SUCCESS ;
}
x_bisect = 0.5 * (x_left + x_right);
SAFE_FUNC_CALL (f, x_bisect, &f_bisect);
if ((f_lower > 0.0 && f_bisect < 0.0) || (f_lower < 0.0 && f_bisect > 0.0))
{
*x_upper = x_bisect;
state->f_upper = f_bisect;
if (*root > x_bisect)
*root = 0.5 * (x_left + x_bisect) ;
}
else
{
*x_lower = x_bisect;
state->f_lower = f_bisect;
if (*root < x_bisect)
*root = 0.5 * (x_bisect + x_right) ;
}
return GSL_SUCCESS;
}
static const gsl_root_fsolver_type falsepos_type =
{"falsepos", /* name */
sizeof (falsepos_state_t),
&falsepos_init,
&falsepos_iterate};
const gsl_root_fsolver_type * gsl_root_fsolver_falsepos = &falsepos_type;
|
In this session, we will discuss axes and grid lines in NCSS plots. We will use the scatter plot format window as an example representing other NCSS plots with axes and grid lines. The scatter plot format window is opened by clicking the plot format button of the scatter plots procedure, or, on the plots tab of any other procedures that provide a scatter plot, such as the regression procedures.
We will use the Y axis as an example. The numeric axis is the comparable axis in some of the other plot format windows. In many of the plots there is a group axis in addition to a numeric axis. The principles outlined below generally apply to those axes as well. The default setting for the minimum and maximum boundary is ‘blank’. When these boundaries are blank, NCSS uses an algorithm to determine a suitable minimum or maximum based on the data involved. You can set a specific boundary for the minimum or maximum or both if you wish. The ‘Corners’ button is used to give axes a small shift, which, in effect, removes the sharp corners of the graph. This feature may also be useful when points are right on one of the axes.
The axis scale may be set to linear or log. The log scale number format can be shown as numbers or as powers of the base. There are two lines for each numeric axis, one for each side of the graph. The format of these lines is specified by using the drop-down of quick line format choices, or using the custom line format window. By default, these lines are located at the ends of the adjacent axis, but a specific value can be entered for their location. The lines can be further adjusted by setting a minimum or maximum for the visible part of the line of the axis. Working in tandem with the specification of the ticks can give a very specialized axis.
The tick marks and tick labels can independently be included or excluded from either side of the graph. The tick marks format button allows you to specify the fill, size, and position of the tick marks. The ‘Tick Number and Spacing’ button gives several ways to specify the location of the major and minor ticks along the axis. The number and interval options are used in conjunction with the Min and the Max values. The ‘List’ option provides a way to directly enter tick locations. The minor tick section will be grayed out if no minor ticks checkboxes are checked.
The tick labels have buttons to specify the text font, the layout, and the number format of the tick labels. The grid line locations follow the locations of the major and minor ticks. Individual grid lines or a custom series of grid lines may also be specified at custom locations. This concludes our discussion of the axes and grid lines in NCSS plots. |
= Arihant @-@ class submarine =
|
module Cats.Category.Slice where
open import Data.Product using (_,_ ; proj₁ ; proj₂)
open import Level
open import Relation.Binary using (IsEquivalence ; _Preserves₂_⟶_⟶_)
open import Cats.Category
module _ {lo la l≈} (C : Category lo la l≈) (X : Category.Obj C) where
infixr 9 _∘_
infixr 4 _≈_
private
module C = Category C
module ≈ = C.≈
record Obj : Set (lo ⊔ la) where
constructor mkObj
field
{Dom} : C.Obj
arr : Dom C.⇒ X
open Obj
record _⇒_ (f g : Obj) : Set (la ⊔ l≈) where
field
dom : Dom f C.⇒ Dom g
commute : arr f C.≈ arr g C.∘ dom
open _⇒_
record _≈_ {A B} (F G : A ⇒ B) : Set l≈ where -- [1]
constructor ≈-i
field
dom : dom F C.≈ dom G
-- [1] This could also be defined as
--
-- F ≈ G = dom F C.≈ dom G
--
-- but Agda was then giving me very strange unsolved metas in _/_ below.
id : ∀ {A} → A ⇒ A
id = record { dom = C.id ; commute = ≈.sym C.id-r }
_∘_ : ∀ {A B C} → (B ⇒ C) → (A ⇒ B) → (A ⇒ C)
_∘_ {F} {G} {H}
record { dom = F-dom ; commute = F-commute}
record { dom = G-dom ; commute = G-commute}
= record
{ dom = F-dom C.∘ G-dom
; commute
= begin
arr F
≈⟨ G-commute ⟩
arr G C.∘ G-dom
≈⟨ C.∘-resp-l F-commute ⟩
(arr H C.∘ F-dom) C.∘ G-dom
≈⟨ C.assoc ⟩
arr H C.∘ F-dom C.∘ G-dom
∎
}
where
open C.≈-Reasoning
≈-equiv : ∀ {A B} → IsEquivalence (_≈_ {A} {B})
≈-equiv = record
{ refl = ≈-i ≈.refl
; sym = λ { (≈-i eq) → ≈-i (≈.sym eq) }
; trans = λ { (≈-i eq₁) (≈-i eq₂) → ≈-i (≈.trans eq₁ eq₂) }
}
∘-preserves-≈ : ∀ {A B C} → _∘_ {A} {B} {C} Preserves₂ _≈_ ⟶ _≈_ ⟶ _≈_
∘-preserves-≈ (≈-i eq₁) (≈-i eq₂) = ≈-i (C.∘-resp eq₁ eq₂)
id-identity-r : ∀ {A B} {F : A ⇒ B} → F ∘ id ≈ F
id-identity-r = ≈-i C.id-r
id-identity-l : ∀ {A B} {F : A ⇒ B} → id ∘ F ≈ F
id-identity-l = ≈-i C.id-l
∘-assoc : ∀ {A B C D} {F : C ⇒ D} {G : B ⇒ C} {H : A ⇒ B}
→ (F ∘ G) ∘ H ≈ F ∘ (G ∘ H)
∘-assoc = ≈-i C.assoc
instance _/_ : Category (la ⊔ lo) (l≈ ⊔ la) l≈
_/_ = record
{ Obj = Obj
; _⇒_ = _⇒_
; _≈_ = _≈_
; id = id
; _∘_ = _∘_
; equiv = ≈-equiv
; ∘-resp = ∘-preserves-≈
; id-r = id-identity-r
; id-l = id-identity-l
; assoc = ∘-assoc
}
open Category _/_ using (IsTerminal ; IsUnique ; ∃!-intro)
One : Obj
One = mkObj C.id
One-Terminal : IsTerminal One
One-Terminal Y@(mkObj f)
= ∃!-intro F _ F-Unique
where
F : Y ⇒ One
F = record { dom = f ; commute = C.≈.sym C.id-l }
F-Unique : IsUnique F
F-Unique {record { dom = g ; commute = commute }} _
= ≈-i (≈.trans commute C.id-l)
|
module initial
implicit none
real :: pi, gam0
integer :: nr, nproc, nray=6
integer, private :: i, j, k
logical :: gauss = .true.
contains
subroutine lecture( nstep, imov, xp, yp, op, delta, idm, dt, nbpart )
namelist/donnees/nstep, dt, imov, amach, nray, delta
integer, parameter :: ix=0, jx=200, iy=0, jy=200
integer :: nstep, imov, idm, nbpart
real :: xp( idm ), yp( idm ), op( idm )
real :: rf( idm ), zf( idm ), gam( idm )
real :: circ, al, ur, tau, aom, u0, r0
real :: amach, gomeg, delta, dt
nstep = 1
dt = 0.01
imov = 1
amach = 0.1
nproc = 1
nray = 6
delta = 0.01
open(10, file = "input" )
read(10,donnees)
close(10)
pi = 4. * atan(1.)
r0 = 0.5
u0 = amach
gam0 = u0 * 2.0 * pi / 0.7 * r0 !gaussienne
!gam0 = 2. * pi * r0 * u0 !constant
!gam0 = 2. * pi / 10.0
aom = gam0 / ( pi * r0**2 ) !Amplitude du vortex
tau = 8.0 * pi**2 / gam0 !Periode de co-rotation
gomeg = gam0/ (4.0*pi) !Vitesse angulaire
ur = gomeg !Vitesse tangentielle du vortex
al = 0.5 * tau !Longeur d'onde
write(*,*) " iterations : ", nstep
write(*,*) " pas de temps : ", dt
write(*,*) " animation : ", imov, " steps "
write(*,*) " aom = ", aom
write(*,*) " r0 = ", r0
write(*,*) " Circulation = ", gam0
write(*,*) " Vitesse de rotation gomeg = ", gomeg
write(*,*) " ur = ", ur
write(*,*) " periode de corotation = ", tau
write(*,*) " --------------------------------------------- "
call distrib( rf, zf, gam, r0, idm )
do k = 1, nr
xp( k ) = rf( k )
yp( k ) = zf( k ) + 1.
op( k ) = gam( k )
xp( k+nr ) = rf( k )
yp( k+nr ) = zf( k ) - 1.
op( k+nr ) = gam( k )
end do
nbpart = 2 * nr
!Calcul de la vitesse de propagation du systeme
circ = sum(op(1:nr))
write(*,*) ' Nombre total de particules =',nbpart
end subroutine lecture
!---------------------------------------------------------------
subroutine distrib(rf, zf, cir, ray, idm )
integer :: kd, nsec, nsec0, idm
real :: rf( * ), zf( * ), cir( * ), ds( idm )
real :: ssurf, q, sigma, teta, dss, r1, r2, s1, s2, eps
real :: gamt, sgam, dteta, surf, ray, dray, r, dr
pi = 4.0 * atan( 1.0 )
nsec = 6
! rf,zf : position de la particule
! ds : taille de l'element de surface
! cir : circulation de la particule
! dr : pas d'espace dans la direction radiale
! nray : nb de pts ds la direction radiale.
! dray : rayon de la particule placee au centre
! ray : rayon de la section
! gam0 : circulation totale
! surf : surface de la section
! nsec : nombre de points dans la premiere couronne
dr = ray / ( nray + 0.5 )
dray = 0.5 * dr !rayon de la section centrale
surf = pi * ray * ray
dteta = 2.0 * pi / float( nsec)
gamt = gam0 / ( 1. - exp( -1.0 ) ) ! total strength of gaussian vortex
k = 1
rf( 1) = 0.0
zf( 1) = 0.0
ds( 1) = pi * dray * dray
if ( gauss ) then
cir( 1) = gamt * ( 1.-exp(-(dray/ray)**2)) !gauss
else
cir( 1) = gam0 * ds( 1 ) / surf !uniforme
end if
sgam = cir( 1 )
r1 = dray
s1 = pi * r1**2
nsec0 = nsec
nsec = 0
!cpn *** parametre de l'ellipse ***
!c eps = 0.01 ! 0.0 --> disque
eps = 0.0
!cpn ******************************
do i = 1, nray
nsec = nsec + nsec0
dteta = 2.0 * pi / float(nsec)
r = float( i ) * dr
r2 = r + 0.5 * dr
s2 = pi * r2**2
dss = s2 - s1
s1 = s2
do j = 1, nsec
k = k + 1
if( k .gt. idm ) stop ' !! idm < Nr !! '
teta = float( j ) * dteta
sigma = r * ( 1.0 + eps * cos( 2.0*teta ) )
rf( k ) = sigma * cos( teta )
zf( k ) = sigma * sin( teta )
ds( k ) = dss / float( nsec )
if ( gauss ) then
q = 0.5 * (exp(-(r1/ray)**2)-exp(-(r2/ray)**2) )
cir( k ) = gamt * dteta / pi * q ! gauss
else
cir( k ) = gam0 * ds( k ) / surf ! uniforme
end if
sgam = sgam + cir( k )
end do
r1 = r2
kd = k - nsec + 1
end do
nr = k
ssurf = 0.0
do i = 1, nr
ssurf = ssurf + ds(i)
end do
write(*,*) 'Nb de pts sur la section :', nr,'(',idm,' max )'
write(*,*) 'surface theorique - pratique :', (surf),' - ',(ssurf)
if (gauss) then
write(*,*) 'circulation theorique - pratique :',(gam0),' ; ',(sgam)
else
write(*,*) 'circulation theorique - pratique :',(gam0),' ; ',(sgam)
end if
1000 format( F11.5, 2X, F11.5, 2X, F11.5, 1X, F11.5 )
end subroutine distrib
end module initial
|
using BandedMatrices, LinearAlgebra, LazyArrays, Test
import BandedMatrices: rowstart, rowstop, colstart, colstop,
rowlength, collength, diaglength, BandedColumns
import LazyArrays: MemoryLayout, DenseColumnMajor
@testset "Indexing" begin
@testset "BandedMatrix Indexing" begin
let
for n in (10,50), m in (12,50), Al in (0,1,2,30), Au in (0,1,2,30)
A=brand(n,m,Al,Au)
kr,jr=3:10,5:12
@test Matrix(A[kr,jr]) ≈ Matrix(A)[kr,jr]
end
end
end
@testset "rowstart/rowstop" begin
A = BandedMatrix(Ones(7, 5), (1, 2))
# 1.0 1.0 1.0 0.0 0.0
# 1.0 1.0 1.0 1.0 0.0
# 0.0 1.0 1.0 1.0 1.0
# 0.0 0.0 1.0 1.0 1.0
# 0.0 0.0 0.0 1.0 1.0
# 0.0 0.0 0.0 0.0 1.0
# 0.0 0.0 0.0 0.0 0.0
@test (rowstart(A, 1), rowstop(A, 1), rowlength(A, 1)) == (1, 3, 3)
@test (rowstart(A, 2), rowstop(A, 2), rowlength(A, 2)) == (1, 4, 4)
@test (rowstart(A, 3), rowstop(A, 3), rowlength(A, 3)) == (2, 5, 4)
@test (rowstart(A, 4), rowstop(A, 4), rowlength(A, 4)) == (3, 5, 3)
@test (rowstart(A, 5), rowstop(A, 5), rowlength(A, 5)) == (4, 5, 2)
@test (rowstart(A, 6), rowstop(A, 6), rowlength(A, 6)) == (5, 5, 1)
@test (rowstart(A, 7), rowstop(A, 7), rowlength(A, 7)) == (6, 5, 0) # zero length
@test (colstart(A, 1), colstop(A, 1), collength(A, 1)) == (1, 2, 2)
@test (colstart(A, 2), colstop(A, 2), collength(A, 2)) == (1, 3, 3)
@test (colstart(A, 3), colstop(A, 3), collength(A, 3)) == (1, 4, 4)
@test (colstart(A, 4), colstop(A, 4), collength(A, 4)) == (2, 5, 4)
@test (colstart(A, 5), colstop(A, 5), collength(A, 5)) == (3, 6, 4)
A = BandedMatrix(Ones(3, 6), (1, 2))
# 1.0 1.0 1.0 0.0 0.0 0.0
# 1.0 1.0 1.0 1.0 0.0 0.0
# 0.0 1.0 1.0 1.0 1.0 0.0
@test (rowstart(A, 1), rowstop(A, 1), rowlength(A, 1)) == (1, 3, 3)
@test (rowstart(A, 2), rowstop(A, 2), rowlength(A, 2)) == (1, 4, 4)
@test (rowstart(A, 3), rowstop(A, 3), rowlength(A, 3)) == (2, 5, 4)
@test (colstart(A, 1), colstop(A, 1), collength(A, 1)) == (1, 2, 2)
@test (colstart(A, 2), colstop(A, 2), collength(A, 2)) == (1, 3, 3)
@test (colstart(A, 3), colstop(A, 3), collength(A, 3)) == (1, 3, 3)
@test (colstart(A, 4), colstop(A, 4), collength(A, 4)) == (2, 3, 2)
@test (colstart(A, 5), colstop(A, 5), collength(A, 5)) == (3, 3, 1)
@test (colstart(A, 6), colstop(A, 6), collength(A, 6)) == (4, 3, 0) # zero length
A = BandedMatrix(Ones(3, 4), (-1, 2))
# 0.0 1.0 1.0 0.0
# 0.0 0.0 1.0 1.0
# 0.0 0.0 0.0 1.0
@test rowrange(A, 1) == 2:3
@test rowrange(A, 2) == 3:4
@test rowrange(A, 3) == 4:4
@test colrange(A, 1) == 1:0
@test colrange(A, 2) == 1:1
@test colrange(A, 3) == 1:2
@test colrange(A, 4) == 2:3
end
@testset "test length of diagonal" begin
A = BandedMatrix(Ones(4, 6), (2, 3))
# 4x6 BandedMatrices.BandedMatrix{Float64}:
# 1.0 1.0 1.0 1.0
# 1.0 1.0 1.0 1.0 1.0
# 1.0 1.0 1.0 1.0 1.0 1.0
# 1.0 1.0 1.0 1.0 1.0
@test diaglength(A, -2) == 2
@test diaglength(A, -1) == 3
@test diaglength(A, 0) == 4
@test diaglength(A, 1) == 4
@test diaglength(A, 2) == 4
@test diaglength(A, 3) == 3
A = BandedMatrix(Ones(6, 5), (2, 1))
# 6x5 BandedMatrices.BandedMatrix{Float64}:
# 1.0 1.0
# 1.0 1.0 1.0
# 1.0 1.0 1.0 1.0
# 1.0 1.0 1.0 1.0
# 1.0 1.0 1.0
# 1.0 1.0
@test diaglength(A, -2) == 4
@test diaglength(A, -1) == 5
@test diaglength(A, 0) == 5
@test diaglength(A, 1) == 4
A = BandedMatrix(Ones(4, 4), (1, 1))
# 4x4 BandedMatrices.BandedMatrix{Float64}:
# 1.0 1.0
# 1.0 1.0 1.0
# 1.0 1.0 1.0
# 1.0 1.0
@test diaglength(A, -1) == 3
@test diaglength(A, 0) == 4
@test diaglength(A, 1) == 3
# test with Band type
@test diaglength(A, band(1)) == 3
end
@testset "_firstdiagrow/_firstdiagcol" begin
A = BandedMatrix(Ones(6, 5), (2, 1))
# 6x5 BandedMatrices.BandedMatrix{Float64}:
# 1.0 1.0
# 1.0 1.0 1.0
# 1.0 1.0 1.0 1.0
# 1.0 1.0 1.0 1.0
# 1.0 1.0 1.0
# 1.0 1.0
@test BandedMatrices._firstdiagrow(A, 1) == 2
@test BandedMatrices._firstdiagrow(A, 2) == 2
@test BandedMatrices._firstdiagrow(A, 3) == 2
@test BandedMatrices._firstdiagrow(A, 4) == -3
@test BandedMatrices._firstdiagrow(A, 5) == -3
@test BandedMatrices._firstdiagrow(A, 6) == -3
@test BandedMatrices._firstdiagcol(A, 1) == -3
@test BandedMatrices._firstdiagcol(A, 2) == -3
@test BandedMatrices._firstdiagcol(A, 3) == 2
@test BandedMatrices._firstdiagcol(A, 4) == 2
@test BandedMatrices._firstdiagcol(A, 5) == 2
end
@testset "scalar - integer - integer" begin
a = BandedMatrix(Ones(5, 5), (1, 1))
# 1.0 1.0 0.0 0.0 0.0
# 1.0 1.0 1.0 0.0 0.0
# 0.0 1.0 1.0 1.0 0.0
# 0.0 0.0 1.0 1.0 1.0
# in band
a[1, 1] = 2
@test a[1, 1] == 2
# out of band
@test_throws BandError a[1, 3] = 1
@test_throws BandError a[3, 1] = 1
# out of range
@test_throws BoundsError a[0, 0] = 1
@test_throws BoundsError a[0, 1] = 1
@test_throws BoundsError a[1, 0] = 1
@test_throws BoundsError a[5, 6] = 1
@test_throws BoundsError a[6, 5] = 1
@test_throws BoundsError a[6, 6] = 1
a = BandedMatrix(Ones(5, 5), (-1, 1))
a[1, 2] = 2
@test a[1, 2] == 2
@test_throws BandError a[1, 1] = 1
end
@testset "indexing along a column" begin
@testset "scalar - BandRange/Colon - integer" begin
a = BandedMatrix(Ones(5, 5), (1, 1))
# 1.0 1.0 0.0 0.0 0.0
# 1.0 1.0 1.0 0.0 0.0
# 0.0 1.0 1.0 1.0 0.0
# 0.0 0.0 1.0 1.0 1.0
# 0.0 0.0 0.0 1.0 1.0
# in band
a[BandRange, 1] .= 2
a[BandRange, 2] .= 3
a[BandRange, 3] .= 4
a[BandRange, 4] .= 5
a[BandRange, 5] .= 6
@test a == [2 3 0 0 0;
2 3 4 0 0;
0 3 4 5 0;
0 0 4 5 6;
0 0 0 5 6]
@test a[BandRange, 1] == [2, 2]
@test a[BandRange, 2] == [3, 3, 3]
@test a[BandRange, 3] == [4, 4, 4]
@test a[BandRange, 4] == [5, 5, 5]
@test a[BandRange, 5] == [6, 6]
@test_throws BoundsError a[:, 0] .= 1
@test_throws BandError a[:, 1] .= 1
@test_throws BoundsError a[BandRange, 0] .= 1
@test_throws BoundsError a[BandRange, 6] .= 1
a = BandedMatrix(Ones(3, 5), (-1, 2))
@test isempty(a[BandRange,1])
a[BandRange,2] = [1]
a[BandRange,3] = [2, 2]
a[BandRange,4] = [3, 3]
a[BandRange,5] = [4]
@test a == [0 1 2 0 0;
0 0 2 3 0;
0 0 0 3 4]
end
@testset "vector - BandRange/Colon - integer" begin
a = BandedMatrix(Ones{Int}(5, 7), (2, 1))
# 5x7 BandedMatrices.BandedMatrix{Float64}:
# 1.0 1.0 0 0 0 0 0 0
# 1.0 1.0 1.0 0 0 0 0 0
# 1.0 1.0 1.0 1.0 0 0 0 0
# 0 1.0 1.0 1.0 1.0 0 0 0
# 0 0 1.0 1.0 1.0 1.0 0 0
# in band
a[BandRange, 1] = [1, 2, 3]
a[BandRange, 2] = [4, 5, 6, 7]
a[BandRange, 3] = [8, 9, 10, 11]
a[BandRange, 4] = [12, 13, 14]
a[BandRange, 5] = [15, 16]
a[BandRange, 6] = [17]
@test a == [ 1 4 0 0 0 0 0;
2 5 8 0 0 0 0;
3 6 9 12 0 0 0;
0 7 10 13 15 0 0;
0 0 11 14 16 17 0]
@test a[BandRange, 1] == [1, 2, 3]
@test a[BandRange, 2] == [4, 5, 6, 7]
@test a[BandRange, 3] == [8, 9, 10, 11]
@test a[BandRange, 4] == [12, 13, 14]
@test a[BandRange, 5] == [15, 16]
@test a[BandRange, 6] == [17]
@test_throws BoundsError a[:, 0] = [1, 2, 3]
@test_throws DimensionMismatch a[:, 1] = [1, 2, 3]
@test_throws BoundsError a[BandRange, 0] = [1, 2, 3]
@test_throws BoundsError a[BandRange, 8] = [1, 2, 3]
@test_throws DimensionMismatch a[BandRange, 1] = [1, 2]
end
# scalar - range - integer
let
a = BandedMatrix(Ones(3, 4), (2, 1))
# 1.0 1.0 0.0 0.0
# 1.0 1.0 1.0 0.0
# 1.0 1.0 1.0 1.0
# Matrix column span
a[1:3, 1] .= 1
a[1:3, 2] .= 2
a[2:3, 3] .= 3
a[3:3, 4] .= 4
@test a == [ 1 2 0 0;
1 2 3 0;
1 2 3 4]
# partial span
a[1:1, 1] .= 3
a[2:3, 2] .= 4
a[3:3, 3] .= 5
@test a == [ 3 2 0 0;
1 4 3 0;
1 4 5 4]
a[:, 1] = [1, 1, 1]
a[:, 2] = [2, 2, 2]
a[:, 3] = [0, 3, 3]
a[:, 4] = [0, 0, 4]
@test a == [ 1 2 0 0;
1 2 3 0;
1 2 3 4]
# wrong range input
@test_throws BoundsError a[0:1, 1] .= 3
@test_throws BoundsError a[1:4, 1] .= 3
@test_throws BandError a[2:3, 4] .= 3
@test_throws BoundsError a[3:4, 4] .= 3
end
# vector - range - integer
let
a = BandedMatrix(Ones(5, 4), (1, 2))
# 1.0 1.0 1.0 0.0
# 1.0 1.0 1.0 1.0
# 0.0 1.0 1.0 1.0
# 0.0 0.0 1.0 1.0
# 0.0 0.0 0.0 1.0
# Matrix column span
a[1:2, 1] = 1:2
a[1:3, 2] = 3:5
a[1:4, 3] = 6:9
a[2:5, 4] = 10:13
@test a == [1 3 6 0;
2 4 7 10;
0 5 8 11;
0 0 9 12;
0 0 0 13]
# partial span
a[1:1, 1] = [2]
a[2:3, 2] = 1:2
a[3:4, 3] = 3:4
a[4:5, 4] = 3:4
@test a == [2 3 6 0;
2 1 7 10;
0 2 3 11;
0 0 4 3;
0 0 0 4]
# wrong range input
@test_throws BoundsError a[1:2, 0] = 1:2
@test_throws BoundsError a[0:1, 1] = 1:2
@test_throws BoundsError a[1:8, 1] = 1:8
@test_throws BoundsError a[2:6, 4] = 2:6
@test_throws BoundsError a[3:4, 5] = 3:4
a[:, 1] = [1,1,0,0,0]
a[:, 2] = [2,2,2,0,0]
a[:, 3] = [3,3,3,3,0]
a[:, 4] = [0,4,4,4,4]
@test a == [1 2 3 0;
1 2 3 4;
0 2 3 4;
0 0 3 4;
0 0 0 4]
end
end
@testset "indexing along a row" begin
# scalar - integer - BandRange/colon
let
a = BandedMatrix(Ones(5, 5), (1, 1))
# 1.0 1.0 0.0 0.0 0.0
# 1.0 1.0 1.0 0.0 0.0
# 0.0 1.0 1.0 1.0 0.0
# 0.0 0.0 1.0 1.0 1.0
# 0.0 0.0 0.0 1.0 1.0
# in band
a[1, BandRange] .= 2
a[2, BandRange] .= 3
a[3, BandRange] .= 4
a[4, BandRange] .= 5
a[5, BandRange] .= 6
@test a == [2 2 0 0 0;
3 3 3 0 0;
0 4 4 4 0;
0 0 5 5 5;
0 0 0 6 6]
@test_throws BoundsError a[0, :] .= 1
@test_throws BandError a[1, :] .= 1
@test_throws BoundsError a[0, BandRange] .= 1
@test_throws BoundsError a[6, BandRange] .= 1
a[1, :] .= 0
@test vec(a[1, :]) == [0, 0, 0, 0, 0]
end
# vector - integer - BandRange/colon
let
a = BandedMatrix(Ones(7, 5), (1, 2))
# 7x5 BandedMatrices.BandedMatrix{Float64}:
# 1.0 1.0 1.0 0.0 0.0
# 1.0 1.0 1.0 1.0 0.0
# 0.0 1.0 1.0 1.0 1.0
# 0.0 0.0 1.0 1.0 1.0
# 0.0 0.0 0.0 1.0 1.0
# 0.0 0.0 0.0 0.0 1.0
# 0.0 0.0 0.0 0.0 0.0
# in band
a[1, BandRange] = [1, 2, 3]
a[2, BandRange] = [4, 5, 6, 7]
a[3, BandRange] = [8, 9, 10, 11]
a[4, BandRange] = [12, 13, 14]
a[5, BandRange] = [15, 16]
a[6, BandRange] = [17]
@test a == [1 2 3 0 0;
4 5 6 7 0;
0 8 9 10 11;
0 0 12 13 14;
0 0 0 15 16;
0 0 0 0 17;
0 0 0 0 0]
@test_throws BoundsError a[0, :] = [1, 2, 3]
@test_throws DimensionMismatch a[1, :] = [1, 2, 3]
@test_throws BoundsError a[0, BandRange] = [1, 2, 3]
@test_throws BoundsError a[8, BandRange] = [1, 2, 3]
@test_throws DimensionMismatch a[1, BandRange] = [1, 2]
@test_throws DimensionMismatch a[7, BandRange] = [1, 2, 3]
a[7, BandRange] .= 1
@test a == [1 2 3 0 0;
4 5 6 7 0;
0 8 9 10 11;
0 0 12 13 14;
0 0 0 15 16;
0 0 0 0 17;
0 0 0 0 0]
end
# scalar - integer - range
let
a = BandedMatrix(Ones(7, 5), (1, 2))
# 7x5 BandedMatrices.BandedMatrix{Float64}:
# 1.0 1.0 1.0 0.0 0.0
# 1.0 1.0 1.0 1.0 0.0
# 0.0 1.0 1.0 1.0 1.0
# 0.0 0.0 1.0 1.0 1.0
# 0.0 0.0 0.0 1.0 1.0
# 0.0 0.0 0.0 0.0 1.0
# 0.0 0.0 0.0 0.0 0.0
# in band
a[1, 1:3] .= 2
a[2, 1:4] .= 3
a[3, 2:5] .= 4
a[4, 3:5] .= 5
a[5, 4:5] .= 6
a[6, 5:5] .= 7
@test a == [2 2 2 0 0;
3 3 3 3 0;
0 4 4 4 4;
0 0 5 5 5;
0 0 0 6 6;
0 0 0 0 7;
0 0 0 0 0]
a[1, 1:4] .= 0
@test a == [0 0 0 0 0;
3 3 3 3 0;
0 4 4 4 4;
0 0 5 5 5;
0 0 0 6 6;
0 0 0 0 7;
0 0 0 0 0]
@test_throws BoundsError a[0, 1:3] .= 1
@test_throws BoundsError a[8, 2:3] .= 1
@test_throws BoundsError a[1, 0:3] .= 1
@test_throws BoundsError a[4, 4:6] .= 1
@test_throws BandError a[1, 1:4] .= 1
end
# vector - integer - range
let
a = BandedMatrix(Ones(7, 5), (1, 2))
# 7x5 BandedMatrices.BandedMatrix{Float64}:
# 1.0 1.0 1.0 0.0 0.0
# 1.0 1.0 1.0 1.0 0.0
# 0.0 1.0 1.0 1.0 1.0
# 0.0 0.0 1.0 1.0 1.0
# 0.0 0.0 0.0 1.0 1.0
# 0.0 0.0 0.0 0.0 1.0
# 0.0 0.0 0.0 0.0 0.0
# in band
a[1, 1:3] = [1, 2, 3]
a[2, 1:4] = [1, 2, 3, 4]
a[3, 2:5] = [1, 2, 3, 4]
a[4, 3:5] = [1, 2, 3]
a[5, 4:5] = [1, 2]
a[6, 5:5] = [1]
@test a == [1 2 3 0 0;
1 2 3 4 0;
0 1 2 3 4;
0 0 1 2 3;
0 0 0 1 2;
0 0 0 0 1;
0 0 0 0 0]
@test_throws BoundsError a[0, 1:3] = [1, 2, 3]
@test_throws BoundsError a[8, 2:3] = [1, 2]
@test_throws BoundsError a[1, 0:3] = [1, 2, 3, 4]
@test_throws BoundsError a[4, 4:6] = [2, 3]
@test_throws BandError a[1, 1:4] = [1, 2, 3, 4]
@test_throws BoundsError a[7, 6:7] = [1, 2]
@test_throws DimensionMismatch a[1, 1:3] = [1, 2]
end
end
@testset "indexing along a band" begin
let
a = BandedMatrix(Zeros(5, 4), (2, 1))
# 5x4 BandedMatrices.BandedMatrix{Float64}:
# 0.0 0.0
# 0.0 0.0 0.0
# 0.0 0.0 0.0 0.0
# 0.0 0.0 0.0
# 0.0 0.0
a[band(-2)] .= 5
a[band(-1)] .= 1
a[band( 0)] .= 2
a[band( 1)] .= 3
@test Matrix(a) == [ 2 3 0 0;
1 2 3 0;
5 1 2 3;
0 5 1 2;
0 0 5 1]
@test_throws BandError a[band(-3)] .= 1
a[band(-2)] = [4, 4, 4]
a[band(-1)] = [1, 2, 3, 4]
a[band( 0)] = [5, 6, 7, 8]
a[band( 1)] = [9, 10, 11]
@test Matrix(a) == [ 5 9 0 0;
1 6 10 0;
4 2 7 11;
0 4 3 8;
0 0 4 4]
@test a[band(-2)] == [4, 4, 4]
@test a[band(-1)] == [1, 2, 3, 4]
@test a[band( 0)] == [5, 6, 7, 8]
@test a[band( 1)] == [9, 10, 11]
@test_throws BandError a[band(-3)] = [1, 2, 3]
end
let
a = BandedMatrix(Zeros(5, 4), (2, 2))
# 5x4 BandedMatrices.BandedMatrix{Float64}:
# 0.0 0.0 0.0
# 0.0 0.0 0.0 0.0
# 0.0 0.0 0.0 0.0
# 0.0 0.0 0.0
# 0.0 0.0
a[band(-2)] .= 5
a[band(-1)] .= 1
a[band( 0)] .= 2
a[band( 1)] .= 3
a[band( 2)] .= 4
@test Matrix(a) == [ 2 3 4 0;
1 2 3 4;
5 1 2 3;
0 5 1 2;
0 0 5 1]
@test_throws BandError a[band(-3)] .= 1
a[band(-2)] = [4, 4, 4]
a[band(-1)] = [1, 2, 3, 4]
a[band( 0)] = [5, 6, 7, 8]
a[band( 1)] = [9, 10, 11]
a[band( 2)] = [12, 13]
@test Matrix(a) == [ 5 9 12 0;
1 6 10 13;
4 2 7 11;
0 4 3 8;
0 0 4 4]
@test a[band(-2)] == [4, 4, 4]
@test a[band(-1)] == [1, 2, 3, 4]
@test a[band( 0)] == [5, 6, 7, 8]
@test a[band( 1)] == [9, 10, 11]
@test a[band( 2)] == [12, 13]
@test_throws BandError a[band(-3)] = [1, 2, 3]
end
end
@testset "other special indexing" begin
@testset "all elements" begin
a = BandedMatrix(Ones(3, 3), (1, 1))
a[:] .= 0
@test a == [0 0 0;
0 0 0;
0 0 0]
# all rows/cols
a.data .= 2
@test a == [2 2 0;
2 2 2;
0 2 2]
a[:, :] = [3 3 0;
3 3 3;
0 3 3]
@test a == [3 3 0;
3 3 3;
0 3 3]
@test_throws BandError a[:] .= 1
@test_throws BandError a[:,:] .= 1
@test_throws BandError a[:,:] = ones(3,3)
end
@testset "replace a block in the band" begin
a = BandedMatrix(Zeros(5, 4), (2, 1))
# 5x4 BandedMatrices.BandedMatrix{Float64}:
# 0.0 0.0
# 0.0 0.0 0.0
# 0.0 0.0 0.0 0.0
# 0.0 0.0 0.0
# 0.0 0.0
a[1:3, 1:2] .= 2
a[3:5, 3:4] = [1 2;
3 4;
5 6]
@test Matrix(a) == [2 2 0 0;
2 2 0 0;
2 2 1 2;
0 0 3 4;
0 0 5 6]
@test_throws BoundsError a[0:3, 1:2] .= 2
@test_throws BoundsError a[3:6, 3:4] .= 2
@test_throws BoundsError a[1:3, 0:2] .= 2
@test_throws BoundsError a[3:5, 3:5] .= 2
@test_throws BoundsError a[0:3, 1:2] = [1 2; 3 4]
@test_throws BoundsError a[3:6, 3:4] = [1 2; 3 4]
@test_throws BoundsError a[1:3, 0:2] = [1 2; 3 4]
@test_throws BoundsError a[3:5, 3:5] = [1 2; 3 4]
@test_throws BandError a[1:3, 1:3] .= 2
@test_throws BandError a[1:3, 1:3] = rand(3, 3)
@test_throws DimensionMismatch a[1:3, 1:2] = rand(3, 3)
s = BandedMatrix(view(a,1:3,1:2))
@test isa(s,BandedMatrix)
@test Matrix(s) == a[1:3,1:2]
end
@testset "tests bug" begin
a = BandedMatrix(Zeros(1,1), (3,-1))
@test a[band(-2)] == Float64[]
end
@testset "band views" begin
for A in (rand(11,10), brand(11,10,2,3), brand(Float32, 11,10,2,3),
brand(ComplexF64, 11,10,2,3))
for k = -5:5
V = view(A, band(k))
bs = BandedMatrices.parentindices(V)[1] # a bandslice
@test bs.indices == diagind(A, k)
@test bs.band == Band(k)
@test collect(bs) == collect(diagind(A, k))
@test Vector{eltype(A)}(V) == collect(V) == A[diagind(A,k)] == A[band(k)]
@test Vector{ComplexF64}(V) == Vector{ComplexF64}(A[diagind(A,k)]) ==
convert(AbstractVector{ComplexF64}, V) == convert(AbstractArray{ComplexF64}, V)
@test V ≡ convert(AbstractArray, V) ≡ convert(AbstractArray{eltype(A)}, V) ≡
convert(AbstractArray, V) ≡ convert(AbstractVector, V)
end
end
end
end
@testset "Sub-banded views" begin
A = brand(10,10,2,1)
V = view(A,Base.OneTo(5),Base.OneTo(6))
@test MemoryLayout(V) == BandedColumns(DenseColumnMajor())
@test A[Base.OneTo(5),Base.OneTo(6)] isa BandedMatrix
@test A[2:5,Base.OneTo(6)] isa BandedMatrix
@test A[2:2:5,Base.OneTo(6)] isa Matrix
end
end
|
// Authors: David Blei ([email protected])
// Sean Gerrish ([email protected])
//
// Copyright 2011 Sean Gerrish and David Blei
// All Rights Reserved.
//
// See the README for this package for details about modifying or
// distributing this software.
/*
* state space language model variational inference
*
*/
#ifndef SSLM_H
#define SSLM_H
#include "gsl-wrappers.h"
#include "params.h"
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <assert.h>
#include <math.h>
#include "data.h"
#define SSLM_MAX_ITER 2 // maximum number of optimization iters
#define SSLM_FIT_THRESHOLD 1e-6 // convergence criterion for fitting sslm
#define INIT_MULT 1000 // multiplier to variance for first obs
// #define OBS_NORM_CUTOFF 10 // norm cutoff after which we use all 0 obs
//#define OBS_NORM_CUTOFF 8 // norm cutoff after which we use all 0 obs
#define OBS_NORM_CUTOFF 2 // norm cutoff after which we use all 0 obs
/*
* functions for variational inference
*
*/
// allocate new state space language model variational posterior
sslm_var* sslm_var_alloc(int W, int T);
// allocate extra parameters for inference
void sslm_inference_alloc(sslm_var* var);
// free extra parameters for inference
void sslm_inference_free(sslm_var* var);
// initialize with zero observations
void sslm_zero_init(sslm_var* var,
double obs_variance,
double chain_variance);
// initialize with counts
void sslm_counts_init(sslm_var* var,
double obs_variance,
double chain_variance,
const gsl_vector* counts);
// initialize from variational observations
void sslm_obs_file_init(sslm_var* var,
double obs_variance,
double chain_variance,
const char* filename);
// compute E[\beta_{w,t}] for t = 1:T
void compute_post_mean(int w, sslm_var* var, double chain_variance);
// compute Var[\beta_{w,t}] for t = 1:T
void compute_post_variance(int w, sslm_var* var, double chain_variance);
// optimize \hat{beta}
void optimize_var_obs(sslm_var* var);
// compute dE[\beta_{w,t}]/d\obs_{w,s} for t = 1:T
void compute_mean_deriv(int word, int time, sslm_var* var,
gsl_vector* deriv);
// compute d bound/d obs_{w, t} for t=1:T.
void compute_obs_deriv(int word, gsl_vector* word_counts,
gsl_vector* total_counts, sslm_var* var,
gsl_matrix* mean_deriv_mtx, gsl_vector* deriv);
// update observations
void update_obs(gsl_matrix* word_counts, gsl_vector* totals,
sslm_var* var);
// log probability bound
double compute_bound(gsl_matrix* word_counts, gsl_vector* totals,
sslm_var* var);
// fit variational distribution
double fit_sslm(sslm_var* var, gsl_matrix* word_counts);
// read and write variational distribution
void write_sslm_var(sslm_var* var, char* out);
sslm_var* read_sslm_var(char* in);
void compute_expected_log_prob(sslm_var* var);
// !!! old function (from doc mixture...)
double expected_log_prob(int w, int t, sslm_var* var);
// update zeta
void update_zeta(sslm_var* var);
#endif
|
lemma sup_measure_F_mono': "finite J \<Longrightarrow> finite I \<Longrightarrow> sup_measure.F id I \<le> sup_measure.F id (I \<union> J)" |
State Before: α : Type u_1
β : Type ?u.1660656
E : Type u_2
F : Type ?u.1660662
inst✝¹ : MeasurableSpace α
inst✝ : NormedAddCommGroup E
f g : α → E
s t : Set α
μ ν : Measure α
l✝ l' l : Filter α
⊢ IntegrableAtFilter f (l ⊓ Measure.ae μ) ↔ IntegrableAtFilter f l State After: α : Type u_1
β : Type ?u.1660656
E : Type u_2
F : Type ?u.1660662
inst✝¹ : MeasurableSpace α
inst✝ : NormedAddCommGroup E
f g : α → E
s t : Set α
μ ν : Measure α
l✝ l' l : Filter α
⊢ IntegrableAtFilter f (l ⊓ Measure.ae μ) → IntegrableAtFilter f l Tactic: refine' ⟨_, fun h => h.filter_mono inf_le_left⟩ State Before: α : Type u_1
β : Type ?u.1660656
E : Type u_2
F : Type ?u.1660662
inst✝¹ : MeasurableSpace α
inst✝ : NormedAddCommGroup E
f g : α → E
s t : Set α
μ ν : Measure α
l✝ l' l : Filter α
⊢ IntegrableAtFilter f (l ⊓ Measure.ae μ) → IntegrableAtFilter f l State After: case intro.intro.intro.intro.intro.intro
α : Type u_1
β : Type ?u.1660656
E : Type u_2
F : Type ?u.1660662
inst✝¹ : MeasurableSpace α
inst✝ : NormedAddCommGroup E
f g : α → E
s t✝ : Set α
μ ν : Measure α
l✝ l' l : Filter α
t : Set α
ht : t ∈ l
u : Set α
hu : u ∈ Measure.ae μ
hf : IntegrableOn f (t ∩ u)
⊢ IntegrableAtFilter f l Tactic: rintro ⟨s, ⟨t, ht, u, hu, rfl⟩, hf⟩ State Before: case intro.intro.intro.intro.intro.intro
α : Type u_1
β : Type ?u.1660656
E : Type u_2
F : Type ?u.1660662
inst✝¹ : MeasurableSpace α
inst✝ : NormedAddCommGroup E
f g : α → E
s t✝ : Set α
μ ν : Measure α
l✝ l' l : Filter α
t : Set α
ht : t ∈ l
u : Set α
hu : u ∈ Measure.ae μ
hf : IntegrableOn f (t ∩ u)
⊢ IntegrableAtFilter f l State After: case intro.intro.intro.intro.intro.intro
α : Type u_1
β : Type ?u.1660656
E : Type u_2
F : Type ?u.1660662
inst✝¹ : MeasurableSpace α
inst✝ : NormedAddCommGroup E
f g : α → E
s t✝ : Set α
μ ν : Measure α
l✝ l' l : Filter α
t : Set α
ht : t ∈ l
u : Set α
hu : u ∈ Measure.ae μ
hf : IntegrableOn f (t ∩ u)
⊢ IntegrableOn f t Tactic: refine' ⟨t, ht, _⟩ State Before: case intro.intro.intro.intro.intro.intro
α : Type u_1
β : Type ?u.1660656
E : Type u_2
F : Type ?u.1660662
inst✝¹ : MeasurableSpace α
inst✝ : NormedAddCommGroup E
f g : α → E
s t✝ : Set α
μ ν : Measure α
l✝ l' l : Filter α
t : Set α
ht : t ∈ l
u : Set α
hu : u ∈ Measure.ae μ
hf : IntegrableOn f (t ∩ u)
⊢ IntegrableOn f t State After: case intro.intro.intro.intro.intro.intro
α : Type u_1
β : Type ?u.1660656
E : Type u_2
F : Type ?u.1660662
inst✝¹ : MeasurableSpace α
inst✝ : NormedAddCommGroup E
f g : α → E
s t✝ : Set α
μ ν : Measure α
l✝ l' l : Filter α
t : Set α
ht : t ∈ l
u : Set α
hu : u ∈ Measure.ae μ
hf : IntegrableOn f (t ∩ u)
v : Set α
hv : MeasurableSet v
⊢ ↑↑(Measure.restrict μ t) v ≤ ↑↑(Measure.restrict μ (t ∩ u)) v Tactic: refine' hf.integrable.mono_measure fun v hv => _ State Before: case intro.intro.intro.intro.intro.intro
α : Type u_1
β : Type ?u.1660656
E : Type u_2
F : Type ?u.1660662
inst✝¹ : MeasurableSpace α
inst✝ : NormedAddCommGroup E
f g : α → E
s t✝ : Set α
μ ν : Measure α
l✝ l' l : Filter α
t : Set α
ht : t ∈ l
u : Set α
hu : u ∈ Measure.ae μ
hf : IntegrableOn f (t ∩ u)
v : Set α
hv : MeasurableSet v
⊢ ↑↑(Measure.restrict μ t) v ≤ ↑↑(Measure.restrict μ (t ∩ u)) v State After: case intro.intro.intro.intro.intro.intro
α : Type u_1
β : Type ?u.1660656
E : Type u_2
F : Type ?u.1660662
inst✝¹ : MeasurableSpace α
inst✝ : NormedAddCommGroup E
f g : α → E
s t✝ : Set α
μ ν : Measure α
l✝ l' l : Filter α
t : Set α
ht : t ∈ l
u : Set α
hu : u ∈ Measure.ae μ
hf : IntegrableOn f (t ∩ u)
v : Set α
hv : MeasurableSet v
⊢ ↑↑μ (v ∩ t) ≤ ↑↑μ (v ∩ (t ∩ u)) Tactic: simp only [Measure.restrict_apply hv] State Before: case intro.intro.intro.intro.intro.intro
α : Type u_1
β : Type ?u.1660656
E : Type u_2
F : Type ?u.1660662
inst✝¹ : MeasurableSpace α
inst✝ : NormedAddCommGroup E
f g : α → E
s t✝ : Set α
μ ν : Measure α
l✝ l' l : Filter α
t : Set α
ht : t ∈ l
u : Set α
hu : u ∈ Measure.ae μ
hf : IntegrableOn f (t ∩ u)
v : Set α
hv : MeasurableSet v
⊢ ↑↑μ (v ∩ t) ≤ ↑↑μ (v ∩ (t ∩ u)) State After: case intro.intro.intro.intro.intro.intro
α : Type u_1
β : Type ?u.1660656
E : Type u_2
F : Type ?u.1660662
inst✝¹ : MeasurableSpace α
inst✝ : NormedAddCommGroup E
f g : α → E
s t✝ : Set α
μ ν : Measure α
l✝ l' l : Filter α
t : Set α
ht : t ∈ l
u : Set α
hu : u ∈ Measure.ae μ
hf : IntegrableOn f (t ∩ u)
v : Set α
hv : MeasurableSet v
x : α
hx : x ∈ u
⊢ x ∈ {x | (fun x => (v ∩ t) x ≤ (v ∩ (t ∩ u)) x) x} Tactic: refine' measure_mono_ae (mem_of_superset hu fun x hx => _) State Before: case intro.intro.intro.intro.intro.intro
α : Type u_1
β : Type ?u.1660656
E : Type u_2
F : Type ?u.1660662
inst✝¹ : MeasurableSpace α
inst✝ : NormedAddCommGroup E
f g : α → E
s t✝ : Set α
μ ν : Measure α
l✝ l' l : Filter α
t : Set α
ht : t ∈ l
u : Set α
hu : u ∈ Measure.ae μ
hf : IntegrableOn f (t ∩ u)
v : Set α
hv : MeasurableSet v
x : α
hx : x ∈ u
⊢ x ∈ {x | (fun x => (v ∩ t) x ≤ (v ∩ (t ∩ u)) x) x} State After: no goals Tactic: exact fun ⟨hv, ht⟩ => ⟨hv, ⟨ht, hx⟩⟩ |
module Data.Iterable
import Data.List1
import Data.SnocList
import public Control.MonadRec
--------------------------------------------------------------------------------
-- Iterable
--------------------------------------------------------------------------------
refl : {k : Nat} -> LTE k k
refl = reflexive {x = k}
public export
interface Iterable container element | container where
iterM : MonadRec m
=> (accum : element -> st -> m st)
-> (done : st -> res)
-> (ini : st)
-> (seed : container)
-> m res
export
forM_ : Iterable container element
=> MonadRec m
=> (run : element -> m ())
-> (seed : container)
-> m ()
forM_ run = iterM (\e,_ => run e) (const ()) ()
export
foldM : Iterable container element
=> MonadRec m
=> Monoid mo
=> (calc : element -> m mo)
-> (seed : container)
-> m mo
foldM calc = iterM (\e,acc => (<+> acc) <$> calc e) id neutral
--------------------------------------------------------------------------------
-- Iterable Implementations
--------------------------------------------------------------------------------
export
Iterable Nat Nat where
iterM accum done ini seed =
trSized seed ini $
\case Z => pure . Done . done
v@(S k) => map (Cont k refl) . accum v
export
Iterable (List a) a where
iterM accum done ini seed =
trSized seed ini $
\case Nil => pure . Done . done
h :: t => map (Cont t refl) . accum h
export
Iterable (List1 a) a where
iterM accum done ini = iterM accum done ini . forget
export
Iterable Fuel () where
iterM accum done ini seed =
trSized seed ini $
\case Dry => pure . Done . done
More f => map (Cont f refl) . accum ()
export
Iterable (SnocList a) a where
iterM accum done ini seed =
trSized seed ini $
\case [<] => pure . Done . done
sx :< x => map (Cont sx refl) . accum x
|
theory
Democracy
imports
MyNetwork
begin
datatype 'val msg
= Propose (prop_val:'val)
| Accept 'val
datatype ('val, 'proc) state
= Nothing (* All procs begin in state Nothing *)
| Value 'val (* Once a process receives an (Accept v) message, state changes to Value v *)
| Vote_Count \<open>('proc \<Rightarrow> 'val option)\<close> (* Acceptor's state is Vote_Count f while election is occurring *)
fun initial_vote_count where (* No votes counted yet *)
\<open>initial_vote_count p = None\<close>
fun not_every_vote_counted where (* true if there is a p in procs whose vote is not yet recorded *)
\<open>not_every_vote_counted procs f = (\<exists>p\<in>procs.(f p = None\<and> p \<noteq> 0))\<close>
fun nonzero_counter where (* counts how many p in procs voted for a given val *)
\<open>nonzero_counter procs f sval = card{p\<in> procs . f p = sval \<and> p\<noteq>0}\<close>
fun vals_with_votes where (* the set of values v for which some p in procs voted for v *)
\<open>vals_with_votes procs f = {sv.(\<exists>p\<in>procs. f p = sv \<and> p \<noteq> 0)}\<close>
lemma only_some:
assumes \<open>\<not>not_every_vote_counted procs f\<close>
shows \<open>\<forall>sv.(sv\<in>(vals_with_votes procs f) \<longrightarrow> (\<exists>v. sv = Some v))\<close>
proof
fix sv
show \<open>sv\<in>(vals_with_votes procs f) \<longrightarrow> (\<exists>v. sv = Some v)\<close>
proof
assume h1:\<open>sv\<in>(vals_with_votes procs f)\<close>
show \<open>\<exists>v. sv = Some v\<close>
proof (rule ccontr)
assume \<open>\<nexists>v. sv = Some v\<close>
hence \<open>sv=None\<close> by auto
moreover have \<open>\<exists>p\<in>procs. f p = sv \<and> p \<noteq> 0\<close>
using h1 by auto
ultimately have \<open>not_every_vote_counted procs f\<close> by auto
thus \<open>False\<close> using assms by auto
qed
qed
qed
lemma counter1:
assumes \<open>nonzero_counter procs f sv > 0\<close>
(*and \<open>finite procs\<close>*)
shows \<open> sv \<in> vals_with_votes procs f\<close>
proof -
have \<open>card {p\<in>procs. (f p = sv \<and> p \<noteq> 0)}>0\<close>
using assms by simp
hence \<open>{p\<in>procs. (f p = sv \<and> p \<noteq> 0)} \<noteq> {}\<close>
using card_gt_0_iff by blast
from this obtain p where \<open>p\<in>procs\<and> f p = sv \<and> p\<noteq>0\<close> by auto
thus ?thesis by auto
qed
lemma counter2:
assumes \<open>sv \<in> vals_with_votes procs f\<close>
assumes \<open>finite procs\<close>
shows \<open>nonzero_counter procs f sv > 0\<close>
proof -
have fin:\<open>finite {p\<in>procs. (f p = sv \<and> p \<noteq> 0)}\<close> using assms(2) by auto
have \<open>(\<exists>p\<in>procs. (f p = sv \<and> p \<noteq> 0))\<close> using assms(1) by auto
hence \<open>\<exists>sval. (sval\<in>{p\<in>procs. (f p = sv \<and> p \<noteq> 0)})\<close> by auto
hence nonempty:\<open>{p\<in>procs. (f p = sv \<and> p \<noteq> 0)} \<noteq> {}\<close> by auto
hence \<open>card{p\<in>procs. (f p = sv \<and> p \<noteq> 0)}>0\<close>
proof(cases \<open>card{p\<in>procs. (f p = sv \<and> p \<noteq> 0)}\<close>)
case 0
hence \<open>{p\<in>procs. (f p = sv \<and> p \<noteq> 0)} = {}\<close>
using card_0_eq fin by auto
then show ?thesis using nonempty by auto
next
case (Suc nat)
then show ?thesis by auto
qed
thus ?thesis by auto
qed
fun most_vote_counts where (* the highest number of votes received by any val *)
\<open>most_vote_counts procs f = (Max ((nonzero_counter procs f)`(vals_with_votes procs f)))\<close>
lemma most:
assumes \<open>\<not>(procs \<subseteq> {0})\<close>
and \<open>finite procs\<close>
shows \<open>most_vote_counts procs f > 0\<close>
proof -
from assms(1) obtain p where \<open>p\<in>procs \<and> p\<noteq>0\<close> by auto
hence fpin:\<open>f p \<in> vals_with_votes procs f\<close> by auto
hence gz:\<open>nonzero_counter procs f (f p) > 0\<close> using counter2 assms(2) by simp
have vfin:\<open>finite (vals_with_votes procs f)\<close> using assms(2) by auto
have \<open>Max ((nonzero_counter procs f)`(vals_with_votes procs f))
\<ge> nonzero_counter procs f (f p)\<close>
using fpin vfin by simp
thus \<open>most_vote_counts procs f > 0\<close> using gz by auto
qed
fun set_of_potential_winners where (* the set of values which received the highest number of votes *)
\<open>set_of_potential_winners procs f = {sv.(nonzero_counter procs f sv = most_vote_counts procs f)}\<close>
lemma potwinshavevotes:
assumes \<open>\<not>(procs \<subseteq> {0})\<close>
and \<open>finite procs\<close>
shows \<open>set_of_potential_winners procs f \<subseteq> vals_with_votes procs f\<close>
proof
fix x
assume a:\<open>x \<in> set_of_potential_winners procs f\<close>
show \<open>x \<in> vals_with_votes procs f\<close>
proof -
have \<open>nonzero_counter procs f x = most_vote_counts procs f\<close>
using a by auto
hence \<open>nonzero_counter procs f x > 0\<close>
using most assms by simp
thus \<open>x\<in>vals_with_votes procs f\<close> using counter1 by auto
qed
qed
lemma potwinsaresome:
assumes \<open>\<not>not_every_vote_counted procs f\<close>
and \<open>\<not>(procs \<subseteq> {0})\<close>
and \<open>finite procs\<close>
shows \<open>sv\<in>(set_of_potential_winners procs f) \<Longrightarrow> (\<exists>v. (sv = Some v))\<close>
proof -
assume \<open>sv\<in>(set_of_potential_winners procs f)\<close>
hence \<open>sv\<in>(vals_with_votes procs f)\<close>
using potwinshavevotes assms(2) assms(3) by (metis (mono_tags, lifting) in_mono)
thus \<open>\<exists>v. sv = Some v\<close> using only_some assms(1) by auto
qed
fun pick_winner where (* picks a random winner from the set of potential winners *)
\<open>pick_winner procs f = (SOME sv. sv \<in> (set_of_potential_winners procs f))\<close>
lemma pickerlemma:
assumes \<open>A \<noteq> {}\<close>
shows \<open>(SOME a. a \<in> A)\<in> A\<close>
using assms some_in_eq by blast
lemma winnerispotential:
assumes \<open>\<not>not_every_vote_counted procs f\<close>
and \<open>\<not>(procs \<subseteq> {0})\<close>
and \<open>finite procs\<close>
shows \<open>(pick_winner procs f)\<in> (set_of_potential_winners procs f)\<close>
proof -
from assms(2) obtain p where \<open>p\<in>procs \<and> p\<noteq>0\<close> by auto
hence fpin:\<open>f p \<in> vals_with_votes procs f\<close> by auto
hence valsnonempty:\<open>vals_with_votes procs f \<noteq> {}\<close>
by auto
have valsfinite:\<open>finite (vals_with_votes procs f)\<close>
using assms(3) by auto
hence maxin:\<open>(Max ((nonzero_counter procs f)`(vals_with_votes procs f)))
\<in> ((nonzero_counter procs f)`(vals_with_votes procs f))\<close>
using valsnonempty valsfinite by simp
moreover have \<open>(z\<in>((nonzero_counter procs f)`(vals_with_votes procs f))
\<Longrightarrow> (\<exists>x.(x\<in>(vals_with_votes procs f) \<and> (z=nonzero_counter procs f x))))\<close>
by auto
hence \<open>\<exists>x.(x\<in>(vals_with_votes procs f) \<and> ((Max ((nonzero_counter procs f)`(vals_with_votes procs f)))=nonzero_counter procs f x))\<close>
using maxin by auto
(*from this obtain sv where \<open>sv\<in>(vals_with_votes procs f)
\<and> (Max ((nonzero_counter procs f)`(vals_with_votes procs f))) = nonzero_counter procs f sv\<close>
by auto*)
hence \<open>(set_of_potential_winners procs f) \<noteq> {}\<close>
by auto
hence \<open>(SOME sv. sv \<in> (set_of_potential_winners procs f)) \<in> (set_of_potential_winners procs f)\<close>
using pickerlemma[where ?A=\<open>set_of_potential_winners procs f\<close>] by auto
thus ?thesis using pickerlemma by auto
qed
lemma winnersome:
assumes \<open>\<not>not_every_vote_counted procs f\<close>
and \<open>\<not>(procs \<subseteq> {0})\<close>
and \<open>finite procs\<close>
shows \<open>\<exists>v. (pick_winner procs f = Some v)\<close>
using potwinsaresome[where ?sv=\<open>pick_winner procs f\<close>] winnerispotential assms by blast
fun set_value_and_send_accept_all where (* sets acceptor's state to Value v and sends (Accept v) to all p in procs *)
\<open>set_value_and_send_accept_all procs v = (Value v,((\<lambda>p. (Send p (Accept v))) ` procs))\<close>
fun count_update where (* deals with incoming vote and updates acceptor's state. sends Accept messages if voting is completed *)
\<open>count_update procs f sender val =
(case (f sender) of
None \<Rightarrow> (case (not_every_vote_counted procs (f (sender := Some val))) of
True \<Rightarrow> (Vote_Count (f (sender := Some val)), {}) |
False \<Rightarrow> (set_value_and_send_accept_all (procs\<union>{sender}) (the (pick_winner (procs\<union>{sender}) (f (sender := Some val)))))) |
Some v \<Rightarrow> (Vote_Count f, {}))\<close>
(* f is the current vote count. This function is potentially called when the Acceptor receives (Propose val) from sender.
If the sender's vote has not yet been recorded, checks if there are other p in procs whose votes are not recorded either.
If there are others unrecorded, updates vote count to include sender's vote.
Otherwise, decides winner of election, sets state to Value (winner), and sends (Accept winner) to all p in procs.
(We use procs \<union> {sender} to decide election to avoid the case where procs \<subseteq> {0} which would lead to no votes.
This adjustment makes the case procs \<subseteq> {0} into the original ``first proposal received is accepted'' situation)
If the sender's vote has previously been recorded, does nothing. *)
fun acceptor_step where (* If Acceptor receives a vote, either initialize voting if it is the first vote,
Send (Accept v) if voting was already completed with winning value v,
or update Vote_Count if voting is ongoing.
For other events do nothing *)
\<open>acceptor_step procs state (Receive sender (Propose val)) =
(case state of
Nothing \<Rightarrow> (count_update procs initial_vote_count sender val) |
Value v \<Rightarrow> (Value v, {Send sender (Accept v)}) |
Vote_Count f \<Rightarrow> (count_update procs f sender val))\<close> |
\<open>acceptor_step procs state _ = (state, {})\<close>
fun proposer_step where
\<open>proposer_step procs Nothing (Request val) = (Nothing, {Send 0 (Propose val)})\<close> |
\<open>proposer_step procs Nothing (Receive _ (Accept val)) = (Value val, {})\<close> |
\<open>proposer_step procs state _ = (state, {})\<close>
fun consensus_step where
\<open>consensus_step procs proc =
(if proc = 0 then acceptor_step procs else proposer_step procs)\<close>
(* Invariant 1: for any proposer p, if p's state is ``Value val'',
then there exists a process that has sent a message
``Accept val'' to p. *)
definition inv1 where
\<open>inv1 msgs states \<longleftrightarrow>
(\<forall>proc val. proc \<noteq> 0 \<and> states proc = Value val \<longrightarrow>
(\<exists>sender. (sender, Send proc (Accept val)) \<in> msgs))\<close>
(* Invariant 2: if a message ``Accept val'' has been sent, then
the acceptor is in the state ``Value val''. *)
definition inv2 where
\<open>inv2 msgs states \<longleftrightarrow>
(\<forall>sender recpt val. (sender, Send recpt (Accept val)) \<in> msgs \<longrightarrow>
states 0 = Value val)\<close>
(* Invariant 3: if a ``Propose val'' message has been sent, then the sender is not the Acceptor *)
definition inv3 where
\<open>inv3 msgs \<longleftrightarrow>
(\<forall>sender recpt val. (sender, Send recpt (Propose val))\<in> msgs \<longrightarrow> sender\<noteq>0)\<close>
lemma invariant_propose:
assumes \<open>msgs' = msgs \<union> {(proc, Send 0 (Propose val))}\<close>
and \<open>inv1 msgs states \<and> inv2 msgs states\<close>
shows \<open>inv1 msgs' states \<and> inv2 msgs' states\<close>
proof -
have \<open>\<forall>sender proc val.
(sender, Send proc (Accept val)) \<in> msgs' \<longleftrightarrow>
(sender, Send proc (Accept val)) \<in> msgs\<close>
using assms(1) by blast
then show ?thesis
by (meson assms(2) inv1_def inv2_def)
qed
lemma invariant3_accept:
assumes \<open>msgs' = msgs \<union> {(proc, Send recpt (Accept val))}\<close>
and \<open>inv3 msgs\<close>
shows \<open>inv3 msgs'\<close>
proof -
have \<open>\<forall>sender proc val.
(sender, Send proc (Propose val)) \<in> msgs' \<longleftrightarrow>
(sender, Send proc (Propose val)) \<in> msgs\<close>
using assms(1) by blast
then show ?thesis
by (metis assms(2) inv3_def)
qed
lemma invariant3_empty: \<open>inv3 {}\<close>
proof -
have \<open>\<forall>sender proc val. \<not>((sender, Send proc (Propose val))\<in>{})\<close>
by simp
thus ?thesis
by (simp add: inv3_def)
qed
lemma invariant_decide:
assumes \<open>states' = states (0 := Value val)\<close>
and \<open>msgs' = msgs \<union> {(0, Send sender (Accept val))}\<close>
and \<open>states 0 = Nothing \<or> states 0 = Value val\<close>
and \<open>inv1 msgs states \<and> inv2 msgs states\<close>
shows \<open>inv1 msgs' states' \<and> inv2 msgs' states'\<close>
proof -
{
fix p v
assume asm: \<open>p \<noteq> 0 \<and> states' p = Value v\<close>
hence \<open>states p = Value v\<close>
by (simp add: asm assms(1))
hence \<open>\<exists>sender. (sender, Send p (Accept v)) \<in> msgs\<close>
by (meson asm assms(4) inv1_def)
hence \<open>\<exists>sender. (sender, Send p (Accept v)) \<in> msgs'\<close>
using assms(2) by blast
}
moreover {
fix p1 p2 v
assume asm: \<open>(p1, Send p2 (Accept v)) \<in> msgs'\<close>
have \<open>states' 0 = Value v\<close>
proof (cases \<open>(p1, Send p2 (Accept v)) \<in> msgs\<close>)
case True
then show ?thesis
by (metis assms(1) assms(3) assms(4) fun_upd_same inv2_def state.distinct(1))
next
case False
then show ?thesis
using asm assms(1) assms(2) by auto
qed
}
ultimately show ?thesis
by (simp add: inv1_def inv2_def)
qed
lemma invariant_learn:
assumes \<open>states' = states (proc := Value val)\<close>
and \<open>(sender, Send proc (Accept val)) \<in> msgs\<close>
and \<open>inv1 msgs states \<and> inv2 msgs states\<close>
shows \<open>inv1 msgs states' \<and> inv2 msgs states'\<close>
proof -
{
fix p v
assume asm: \<open>p \<noteq> 0 \<and> states' p = Value v\<close>
have \<open>\<exists>sender. (sender, Send p (Accept v)) \<in> msgs\<close>
proof (cases \<open>p = proc\<close>)
case True
then show ?thesis
using asm assms(1) assms(2) by auto
next
case False
then show ?thesis
by (metis asm assms(1) assms(3) fun_upd_apply inv1_def)
qed
}
moreover {
fix p1 p2 v
assume \<open>(p1, Send p2 (Accept v)) \<in> msgs\<close>
hence \<open>states' 0 = Value v\<close>
by (metis assms fun_upd_apply inv2_def)
}
ultimately show ?thesis
by (simp add: inv1_def inv2_def)
qed
lemma invariant_proposer:
assumes \<open>proposer_step procs (states proc) event = (new_state, sent)\<close>
and \<open>msgs' = msgs \<union> ((\<lambda>msg. (proc, msg)) ` sent)\<close>
and \<open>states' = states (proc := new_state)\<close>
and \<open>execute consensus_step (\<lambda>p. Nothing) procs (events @ [(proc, event)]) msgs' states'\<close>
and \<open>inv1 msgs states \<and> inv2 msgs states\<close>
shows \<open>inv1 msgs' states' \<and> inv2 msgs' states'\<close>
proof (cases event)
case (Receive sender msg)
then show ?thesis
proof (cases msg)
case (Propose val)
then show ?thesis
using Receive assms by auto
next
case (Accept val) (* proposer receives Accept message: learn the decided value *)
then show ?thesis
proof (cases \<open>states proc\<close>)
case Nothing
hence \<open>states' = states (proc := Value val) \<and> msgs' = msgs\<close>
using Accept Receive assms(1) assms(2) assms(3) by auto
then show ?thesis
by (metis Accept Receive assms(4) assms(5) execute_receive invariant_learn)
next
case (Value v)
then show ?thesis
using assms by auto
next
case (Vote_Count f) (* A proposer should never be in this state *)
then show ?thesis
using assms(1) assms(2) assms(3) assms(5) by force
qed
qed
next
(* on a Request event, proposer sends a Propose message if its state
is None, or ignores the event if already learnt a decision *)
case (Request val)
then show \<open>inv1 msgs' states' \<and> inv2 msgs' states'\<close>
proof (cases \<open>states proc\<close>)
case Nothing
hence \<open>states' = states \<and> msgs' = msgs \<union> {(proc, Send 0 (Propose val))}\<close>
using Request assms(1) assms(2) assms(3) by auto
then show ?thesis
by (simp add: assms(5) invariant_propose)
next
case (Value v)
then show ?thesis using assms by auto
next
case (Vote_Count f)
then show ?thesis
using assms(1) assms(2) assms(3) assms(5) by force
qed
next
case Timeout
then show \<open>inv1 msgs' states' \<and> inv2 msgs' states'\<close>
using assms by auto
qed
lemma flip_contrap: assumes \<open>\<not>P \<Longrightarrow> \<not> Q\<close> shows \<open>Q \<Longrightarrow> P\<close> using assms by auto
lemma invariant_acceptor:
assumes \<open>acceptor_step procs (states 0) event = (new_state, sent)\<close>
and \<open>msgs' = msgs \<union> ((\<lambda>msg. (0, msg)) ` sent)\<close>
and \<open>states' = states (0 := new_state)\<close>
and \<open>execute consensus_step (\<lambda>p. Nothing) procs (events @ [(0, event)]) msgs' states'\<close>
and \<open>inv1 msgs states \<and> inv2 msgs states \<and> inv3 msgs\<close>
shows \<open>inv1 msgs' states' \<and> inv2 msgs' states' \<and> inv3 msgs'\<close>
proof (cases event)
case (Receive sender msg)
then show \<open>inv1 msgs' states' \<and> inv2 msgs' states' \<and> inv3 msgs'\<close>
proof (cases msg)
case (Propose val)
then show ?thesis
proof (cases \<open>states 0\<close>)
case Nothing
then show ?thesis
proof (cases \<open>not_every_vote_counted procs (initial_vote_count(sender:= Some val))\<close>)
case True
hence \<open>states' = states (0 := Vote_Count (initial_vote_count(sender:= Some val))) \<and> msgs' = msgs\<close>
using Receive Propose Nothing True assms(1) assms(2) assms(3) by auto
then show ?thesis
by (smt (z3) Nothing assms(5) fun_upd_apply inv1_def inv2_def state.distinct(1))
next
case False
hence hy:\<open>not_every_vote_counted procs (initial_vote_count(sender:= Some val)) = False\<close> by auto
moreover have \<open>event = Receive sender (Propose val)\<close>
by (simp add: Propose Receive)
hence thiscase:\<open>(acceptor_step procs (states 0) event) = (acceptor_step procs Nothing (Receive sender (Propose val)))\<close>
using Nothing by simp
hence ha:\<open>sent =snd (acceptor_step procs Nothing (Receive sender (Propose val)))\<close>
using assms(1) by (smt (verit, best) sndI)
have h:\<open>acceptor_step procs Nothing (Receive sender (Propose val))
= count_update procs initial_vote_count sender val\<close> by simp
have hh:\<open>initial_vote_count sender = None\<close> by simp
let ?w=\<open>(the (pick_winner (procs\<union>{sender}) (initial_vote_count (sender := Some val))))\<close>
have hz:\<open>count_update procs initial_vote_count sender val = set_value_and_send_accept_all (procs\<union>{sender}) ?w\<close>
apply (simp only: count_update.simps hh hy)
by simp
have hw:\<open>set_value_and_send_accept_all (procs\<union>{sender}) ?w = (Value ?w,((\<lambda>p. (Send p (Accept ?w))) ` (procs\<union>{sender})))\<close>
by simp
hence sentis:\<open>sent = ((\<lambda>p. (Send p (Accept ?w))) ` (procs\<union>{sender}))\<close> using ha h hz hw by simp
hence \<open>\<forall>x\<in>sent. send_msg x = (Accept ?w)\<close>
by force
moreover have \<open>send_msg (Send 0 (Propose val))\<noteq> (Accept ?w)\<close>
by (metis msg.distinct(1) send.sel(2))
moreover have \<open>(sender, Send 0 (Propose val))\<in> msgs'\<close>
using Propose Receive assms(4) by auto
hence \<open>(sender, Send 0 (Propose val))\<in> msgs\<close>
using assms(2) calculation(2) calculation(3) by blast
hence nonzero:\<open>sender\<noteq>0\<close>
by (meson assms(5) inv3_def)
have theprocs:\<open>\<forall>p\<in>procs. p=0\<or>p=sender\<close>
using hy by fastforce
hence theprocscont:\<open>(procs\<union>{sender})\<subseteq>{0,sender}\<close> by blast
hence pexist:\<open>\<exists>p\<in>(procs\<union>{sender}). (((initial_vote_count(sender:= Some val)) p) = (Some val) \<and> p \<noteq> 0)\<close>
using nonzero by auto
hence \<open>Some val \<in> {v.\<exists>p\<in>(procs\<union>{sender}). (((initial_vote_count(sender:= Some val)) p) = v \<and> p \<noteq> 0)}\<close>
by simp
hence valin:\<open>Some val \<in> vals_with_votes (procs\<union>{sender}) (initial_vote_count(sender:= Some val))\<close>
by auto
moreover have \<open>\<exists>p\<in>(procs\<union>{sender}). (((initial_vote_count(sender:= Some val)) p) = v \<and> p \<noteq> 0)\<longrightarrow>v=Some val\<close>
by simp
hence \<open>{v.\<exists>p\<in>(procs\<union>{sender}). (((initial_vote_count(sender:= Some val)) p) = v \<and> p \<noteq> 0)}\<subseteq> {Some val}\<close>
using theprocs by auto
hence knowvalswithvotes:\<open>vals_with_votes (procs\<union>{sender}) (initial_vote_count(sender:= Some val)) = {Some val}\<close>
by (smt (z3) Collect_cong valin empty_iff subset_singleton_iff vals_with_votes.elims)
hence \<open>sender\<in>{p\<in> (procs\<union>{sender}) . ((initial_vote_count(sender:= Some val)) p = (Some val) \<and> p\<noteq>0)}\<close>
using theprocs by fastforce
hence somevalcount:\<open>nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some val)) (Some val) =1\<close>
using pexist by simp
hence \<open>(nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some val)))`(vals_with_votes (procs\<union>{sender}) (initial_vote_count(sender:= Some val))) = {1}\<close>
by (metis knowvalswithvotes image_insert image_is_empty)
hence mostvotes1:\<open>most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some val)) = 1\<close> by simp
hence \<open>nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some val)) (Some val) = most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some val))\<close>
using somevalcount by linarith
hence somevalcontainment:\<open>Some val \<in> set_of_potential_winners (procs\<union>{sender}) (initial_vote_count(sender:= Some val))\<close>
by simp
moreover have \<open>\<And>somev.(somev\<noteq> Some val \<longrightarrow> {p\<in> (procs\<union>{sender}) . ((initial_vote_count(sender:= Some val)) p = somev \<and> p\<noteq>0)} = {})\<close>
using theprocs by fastforce
hence \<open>\<And>somev.(somev\<noteq> Some val \<longrightarrow> card{p\<in> (procs\<union>{sender}) . ((initial_vote_count(sender:= Some val)) p = somev \<and> p\<noteq>0)} =0)\<close>
by (metis (no_types, lifting) card.empty)
hence \<open>\<And>somev.(somev\<noteq> Some val \<longrightarrow> nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some val)) somev =0)\<close>
by simp
hence conp:\<open>\<And>somev.(somev \<noteq> Some val \<longrightarrow> nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some val)) somev \<noteq> most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some val)))\<close>
using mostvotes1 by simp
hence conp2:\<open>\<And>somev.(\<not>(somev = Some val) \<Longrightarrow> \<not>(nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some val)) somev = most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some val))))\<close>
by auto
hence \<open>\<And>somev.((nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some val)) somev = most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some val))) \<Longrightarrow> somev=Some val)\<close>
using flip_contrap by blast
hence cont:\<open>\<And>somev.((nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some val)) somev = most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some val))) \<Longrightarrow> somev\<in>{Some val})\<close>
by blast
have \<open>set_of_potential_winners (procs\<union>{sender}) (initial_vote_count(sender:= Some val)) \<subseteq> {Some val}\<close>
proof
fix x
assume as:\<open>x\<in> set_of_potential_winners (procs\<union>{sender}) (initial_vote_count(sender:= Some val))\<close>
hence \<open>x\<in>{some.(nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some val)) some = most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some val)))}\<close>
by simp
hence \<open>(nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some val)) x = most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some val)))\<close>
by simp
thus \<open>x\<in>{Some val}\<close> using cont
by blast
qed
hence \<open>set_of_potential_winners (procs\<union>{sender}) (initial_vote_count(sender:= Some val)) = {Some val}\<close>
using somevalcontainment by fastforce
hence simper:\<open>{Some val} = set_of_potential_winners (procs\<union>{sender}) (initial_vote_count(sender:= Some val))\<close>
by auto
moreover have \<open>(SOME v. v \<in> {Some val}) = Some val\<close>
by simp
hence \<open>(SOME v. v \<in> set_of_potential_winners (procs\<union>{sender}) (initial_vote_count(sender:= Some val))) = Some val\<close>
using simper by simp
hence \<open>pick_winner (procs\<union>{sender}) (initial_vote_count(sender:= Some val)) = Some val\<close>
by simp
hence valwins:\<open>the (pick_winner (procs\<union>{sender}) (initial_vote_count(sender:= Some val))) = val\<close>
by auto
hence exactsent:\<open>sent = ((\<lambda>p. (Send p (Accept val))) ` (procs\<union>{sender}))\<close>
using sentis by simp
hence \<open>msgs' = msgs \<union> ((\<lambda>msg. (0, msg)) ` ((\<lambda>p. (Send p (Accept val))) ` (procs\<union>{sender})))\<close>
using assms(2) by simp
hence knowmsgs1:\<open>msgs' = msgs \<union> ((\<lambda>p. (0,(Send p (Accept val)))) ` (procs\<union>{sender}))\<close>
by auto
hence knowmsgs2:\<open>msgs'\<subseteq> msgs\<union> {(0, (Send sender (Accept val))),(0,(Send 0 (Accept val)))}\<close>
using theprocscont by auto
hence knowinv3:\<open>inv3 msgs'\<close>
by (metis (no_types, lifting) Un_insert_right assms(5) inv3_def invariant3_accept subsetD sup_bot_right)
moreover have knowstates:\<open>states' = states (0 := Value val)\<close>
by (metis Pair_inject thiscase valwins assms(1) assms(3) h hw hz)
hence knowinv1: \<open>inv1 msgs' states'\<close>
using knowmsgs1 knowmsgs2 by (smt (z3) Nothing assms(5) fun_upd_apply inv1_def inv2_def state.distinct(1))
have \<open>\<forall>s r v. (s, Send r (Accept v)) \<notin> msgs\<close>
using assms(5) Nothing by (simp add: inv2_def)
hence knowinv2:\<open>inv2 msgs' states'\<close>
using knowmsgs2 knowstates assms(5) Nothing inv1_def inv2_def
by (smt (verit) Pair_inject UnE fun_upd_apply insertE msg.inject(2) send.inject singletonD subset_eq)
thus ?thesis using knowinv1 knowinv2 knowinv3
by auto
qed
next
case (Value val') (* already decided previously *)
hence \<open>states' = states \<and>
msgs' = msgs \<union> {(0, Send sender (Accept val'))}\<close>
using Receive Propose assms(1) assms(2) assms(3) by auto
then show ?thesis
by (metis Value assms(3) assms(5) fun_upd_same invariant3_accept invariant_decide)
next
case (Vote_Count f)
then show ?thesis
proof (cases \<open>f sender = None\<close>)
case True
then show ?thesis
proof (cases \<open>not_every_vote_counted procs (f(sender:= Some val))\<close>)
case True
hence hy:\<open>not_every_vote_counted procs (f(sender:= Some val)) = True\<close> by auto
have thiscase:\<open>(acceptor_step procs (states 0) event) = (acceptor_step procs (Vote_Count f) (Receive sender (Propose val)))\<close>
using Vote_Count Receive Propose by simp
hence ha:\<open>sent =snd (acceptor_step procs (Vote_Count f) (Receive sender (Propose val)))\<close>
using assms(1) by (smt (verit, best) sndI)
have h:\<open>acceptor_step procs (Vote_Count f) (Receive sender (Propose val))
= count_update procs f sender val\<close> by simp
have hz:\<open>count_update procs f sender val = (Vote_Count (f(sender:=Some val)),{})\<close>
apply (simp only: count_update.simps hy \<open>f sender=None\<close>)
by simp
hence emptysent:\<open>sent={}\<close> using Vote_Count assms(1)
using ha by auto
hence knowmsgs:\<open>msgs'=msgs\<close> using assms(2)
by auto
have knowstates:\<open>states' = states (0 := Vote_Count (f(sender:= Some val)))\<close>
using Vote_Count True assms(1) assms(3) \<open>f sender=None\<close> thiscase by auto
hence \<open>states' = states (0 := Vote_Count (f(sender:= Some val))) \<and> msgs' = msgs\<close>
using knowmsgs knowstates by auto
thus ?thesis
by (metis (no_types, lifting) Vote_Count assms(5) fun_upd_other inv1_def inv2_def state.distinct(5))
next
case False
hence hy:\<open>not_every_vote_counted procs (f(sender:= Some val)) = False\<close> by auto
let ?w=\<open>(the (pick_winner (procs\<union>{sender}) (f (sender := Some val))))\<close>
have thiscase:\<open>(acceptor_step procs (states 0) event) = (acceptor_step procs (Vote_Count f) (Receive sender (Propose val)))\<close>
using Vote_Count Receive Propose by simp
hence ha:\<open>sent =snd (acceptor_step procs (Vote_Count f) (Receive sender (Propose val)))\<close>
using assms(1) by (smt (verit, best) sndI)
have h:\<open>acceptor_step procs (Vote_Count f) (Receive sender (Propose val))
= count_update procs f sender val\<close> by simp
have hz:\<open>count_update procs f sender val = set_value_and_send_accept_all (procs\<union>{sender}) ?w\<close>
apply (simp only: count_update.simps hy \<open>f sender=None\<close>)
by simp
have hw:\<open>set_value_and_send_accept_all (procs\<union>{sender}) ?w = (Value ?w,((\<lambda>p. (Send p (Accept ?w))) ` (procs\<union>{sender})))\<close>
by simp
hence sentis:\<open>sent = ((\<lambda>p. (Send p (Accept ?w))) ` (procs\<union>{sender}))\<close> using ha h hz hw by simp
hence exactsent:\<open>sent = ((\<lambda>p. (Send p (Accept ?w))) ` (procs\<union>{sender}))\<close>
using sentis by simp
hence \<open>msgs' = msgs \<union> ((\<lambda>msg. (0, msg)) ` ((\<lambda>p. (Send p (Accept ?w))) ` (procs\<union>{sender})))\<close>
using assms(2) by simp
hence knowmsgs:\<open>msgs' = msgs \<union> ((\<lambda>p. (0,(Send p (Accept ?w)))) ` (procs\<union>{sender}))\<close>
by blast
hence knowinv3:\<open>inv3 msgs'\<close>
by (smt (verit) Pair_inject UnE assms(5) image_iff inv3_def msg.distinct(1) send.inject)
moreover have knowstates:\<open>states' = states (0 := Value ?w)\<close>
using thiscase by (metis Pair_inject assms(1) assms(3) h hw hz)
hence knowinv1: \<open>inv1 msgs' states'\<close>
using knowmsgs assms(5)
by (metis (no_types, lifting) Vote_Count fun_upd_apply inv1_def inv2_def state.distinct(5))
have \<open>\<forall>s r v. (s, Send r (Accept v)) \<notin> msgs\<close>
using assms(5) Vote_Count by (simp add: inv2_def)
hence knowinv2:\<open>inv2 msgs' states'\<close>
using knowmsgs knowstates assms(5) Vote_Count inv1_def
by (simp add: image_iff inv2_def)
thus ?thesis using knowinv1 knowinv2 knowinv3
by auto
qed
next
case False
hence vexist:\<open>\<exists>v.(f sender = Some v)\<close>
by auto
have thiscase:\<open>(acceptor_step procs (states 0) event) = (acceptor_step procs (Vote_Count f) (Receive sender (Propose val)))\<close>
using Vote_Count Receive Propose by simp
hence ha:\<open>sent =snd (acceptor_step procs (Vote_Count f) (Receive sender (Propose val)))\<close>
using assms(1) by (smt (verit, best) sndI)
have h:\<open>acceptor_step procs (Vote_Count f) (Receive sender (Propose val))
= count_update procs f sender val\<close> by simp
have hz:\<open>count_update procs f sender val = (Vote_Count f,{})\<close>
apply (simp only: count_update.simps)
using vexist by auto
hence emptysent:\<open>sent={}\<close> using Vote_Count assms(1)
using ha by auto
hence knowmsgs:\<open>msgs'=msgs\<close> using assms(2)
by auto
have \<open>states' = states (0 := Vote_Count f)\<close>
using assms(1) assms(3) hz thiscase by auto
hence knowstates:\<open>states' = states\<close>
using Vote_Count by auto
hence \<open>states' = states \<and> msgs' = msgs\<close>
using knowmsgs knowstates by auto
thus ?thesis
by (metis (no_types, lifting) assms(5))
qed
qed
next
case (Accept val)
then show ?thesis
using Receive assms by auto
qed
next
case (Request val)
then show ?thesis
using assms by auto
next
case Timeout
then show ?thesis
using assms by auto
qed
lemma invariants:
assumes \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs' states'\<close>
shows \<open>inv1 msgs' states' \<and> inv2 msgs' states'\<and> inv3 msgs'\<close>
using assms proof(induction events arbitrary: msgs' states' rule: List.rev_induct)
case Nil
from this show \<open>inv1 msgs' states' \<and> inv2 msgs' states'\<and> inv3 msgs'\<close>
using execute_init inv1_def inv2_def inv3_def by fastforce
next
case (snoc x events)
obtain proc event where \<open>x = (proc, event)\<close>
by fastforce
hence exec: \<open>execute consensus_step (\<lambda>p. Nothing) procs
(events @ [(proc, event)]) msgs' states'\<close>
using snoc.prems by blast
from this obtain msgs states sent new_state
where step_rel1: \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs states\<close>
and step_rel2: \<open>consensus_step procs proc (states proc) event = (new_state, sent)\<close>
and step_rel3: \<open>msgs' = msgs \<union> ((\<lambda>msg. (proc, msg)) ` sent)\<close>
and step_rel4: \<open>states' = states (proc := new_state)\<close>
by auto
have inv_before: \<open>inv1 msgs states \<and> inv2 msgs states\<and> inv3 msgs\<close>
using snoc.IH step_rel1 by fastforce
then show \<open>inv1 msgs' states' \<and> inv2 msgs' states'\<and> inv3 msgs'\<close>
proof (cases \<open>proc = 0\<close>)
case True
then show ?thesis
by (metis consensus_step.elims exec invariant_acceptor snoc.IH step_rel1 step_rel2 step_rel3 step_rel4)
next
case False
hence h:\<open>inv1 msgs' states' \<and> inv2 msgs' states'\<close>
by (metis consensus_step.simps exec inv_before invariant_proposer
step_rel2 step_rel3 step_rel4)
have \<open>inv3 msgs'\<close>
by (smt (verit) False Un_iff exec execute_step image_iff inv3_def prod.inject snoc.IH)
thus ?thesis using h by auto
qed
qed
theorem agreement:
assumes \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs states\<close>
and \<open>states proc1 = Value val1\<close> and \<open>states proc2 = Value val2\<close>
shows \<open>val1 = val2\<close>
proof -
have \<open>states 0 = Value val1\<close>
by (metis assms(1) assms(2) inv1_def inv2_def invariants)
moreover have \<open>states 0 = Value val2\<close>
by (metis assms(1) assms(3) inv1_def inv2_def invariants)
ultimately have \<open>Value val1 = Value val2\<close>
by simp
thus \<open>val1=val2\<close> by auto
qed
(* The theorem shows that consensus_step indeed yields consensus.
Let us now verify that the election process is valid. First we define and verify a function
to identify the vote cast by each process. *)
fun is_received_vote where (* recognizes whether an event is a vote from the given proc *)
\<open>is_received_vote proc (_, (Receive p (Propose _))) = (p=proc)\<close> |
\<open>is_received_vote proc _ = False\<close>
fun find_vote where (* Tells us which value was the first vote received from the given proc *)
\<open>find_vote [] proc = None\<close> |
\<open>find_vote (x#xs) proc = (case (is_received_vote proc x) of
True \<Rightarrow> Some (prop_val (recv_msg (snd x))) |
False \<Rightarrow> find_vote xs proc)\<close>
lemma find_vote_lemma:
fixes p
assumes \<open>find_vote x p = find_vote y p\<close>
shows \<open>find_vote (a # x) p = find_vote (a # y) p\<close>
proof -
have \<open>find_vote (a # x) p = (case (is_received_vote p a) of
True \<Rightarrow> Some (prop_val (recv_msg (snd a))) |
False \<Rightarrow> find_vote x p)\<close> by auto
moreover have \<open>(case (is_received_vote p a) of
True \<Rightarrow> Some (prop_val (recv_msg (snd a))) |
False \<Rightarrow> find_vote y p) = find_vote (a # y) p\<close> by auto
ultimately show ?thesis
using assms by presburger
qed
lemma find_vote_lemma1:
fixes p
shows \<open>find_vote x p = Some val \<longrightarrow> find_vote (x @ [a]) p = Some val\<close>
proof (induct x)
case Nil
hence \<open>find_vote Nil p = None\<close>
by simp
then show ?case by auto
next
case (Cons b x)
then show ?case
proof (cases \<open>is_received_vote p b\<close>)
case True
hence \<open>find_vote (b # x) p = Some (prop_val (recv_msg (snd b)))\<close>
by auto
moreover have \<open>find_vote ((b # x)@[a]) p = Some (prop_val (recv_msg (snd b)))\<close>
by (simp add: True)
ultimately show ?thesis by auto
next
case False
hence \<open>find_vote (b # x) p = find_vote x p\<close>
by auto
moreover have \<open>find_vote ((b # x)@[a]) p = find_vote (x@[a]) p\<close>
by (simp add: False)
then show ?thesis
using calculation local.Cons by presburger
qed
qed
lemma find_vote_lemma1b:
assumes \<open>find_vote x p = Some val\<close>
shows \<open>find_vote (x @ [a]) p = Some val\<close>
using find_vote_lemma1 by (metis assms)
lemma find_vote_lemma2:
assumes \<open>find_vote x = find_vote y\<close>
shows \<open>find_vote (a # x) = find_vote (a # y)\<close>
proof
fix p
show \<open>find_vote (a # x) p = find_vote (a # y) p\<close>
using find_vote_lemma by (metis assms)
qed
lemma find_vote_lemma3pre:
assumes \<open>find_vote x p = None\<close>
shows \<open>find_vote (x @ y) p = find_vote y p\<close>
using assms
proof (induct x)
case Nil
then show ?case by auto
next
case (Cons a x)
have notvote:\<open>\<not>is_received_vote p a\<close>
proof(rule ccontr)
assume \<open>\<not>\<not>is_received_vote p a\<close>
hence \<open>is_received_vote p a\<close> by auto
hence \<open>find_vote (a # x) p = Some (prop_val (recv_msg (snd a)))\<close>
by auto
thus \<open>False\<close> using \<open>find_vote (a # x) p = None\<close> by auto
qed
hence \<open>find_vote (a # x) p = find_vote x p\<close> by auto
hence \<open>find_vote x p = None\<close>
using \<open>find_vote (a # x) p = None\<close> by simp
hence \<open>find_vote (x @ y) p = find_vote y p\<close>
using \<open>find_vote x p = None \<Longrightarrow> find_vote (x @ y) p = find_vote y p\<close> by auto
hence \<open>find_vote ((a # (x@y))) p = find_vote (a # y) p\<close>
using find_vote_lemma[where ?x=\<open>x @ y\<close> and ?y=y] by auto
moreover have \<open>find_vote (a # y) p = find_vote y p\<close> using notvote by auto
ultimately show ?case by auto
qed
lemma find_vote_lemma3wtftype:
assumes \<open>find_vote (x :: ('proc \<times> ('proc, 'val msg, 'val) event) list) (p :: 'proc) = None\<close>
shows \<open>find_vote (x @ [(a :: 'proc \<times> ('proc, 'val msg, 'val) event)]) p = find_vote [a] p\<close>
using assms find_vote_lemma3pre[where ?y=\<open>[a]\<close> and ?x = x and ?p = p] by simp
lemma find_vote_lemma3type:
assumes \<open>find_vote (x :: ('proc \<times> ('proc, 'val msg, 'val) event) list) (p :: 'proc) = None\<close>
shows \<open>find_vote (x @ [(q, event :: ('proc, 'val msg, 'val) event)]) p = find_vote [(q,event)] p\<close>
using find_vote_lemma3wtftype assms by auto
(*
lemma find_vote_lemma3:
assumes \<open>find_vote x p = None\<close>
shows \<open>find_vote (x @ [(0,event)]) p = find_vote [(0,event)] p\<close>
using find_vote_lemma3type[where ?x=x and ?p = p and ?q=0 and ?event=event] assms by metis
lemma find_vote_lemma3:
assumes \<open>find_vote x p = None\<close>
shows \<open>find_vote (x @ [(0,event)]) p = find_vote [(0,event)] p\<close>
using find_vote_lemma3wtf[where ?a=\<open>(0,event)\<close> and ?x = x and ?p = p] assms by auto
*)
(* note: find_vote events : 'proc \<Rightarrow> 'val option is the actual record of votes cast *)
(* Invariant 4: if the acceptor is in state ``Value val'' then val is a valid winner,
or procs \<subseteq> {0} (in which case there is no election) *)
definition inv4 where
\<open>inv4 procs events states \<longleftrightarrow>
((\<forall>val.(states 0 = Value val \<longrightarrow>
(Some val \<in> set_of_potential_winners procs (find_vote events))))\<or>(procs \<subseteq> {0}))\<close>
(* Invariant 5: if the acceptor is in state ``Value val'' then voting is done. *)
definition inv5 where
\<open>inv5 procs events states \<longleftrightarrow>
(\<forall>val.(states 0 = Value val \<longrightarrow>
(\<not>(not_every_vote_counted procs (find_vote events)))))\<close>
(* Invariant 6: if the acceptor is in state ``Vote_Count f'' then f = (find_vote events),
that is, f is indeed tracking the votes cast. *)
definition inv6 where
\<open>inv6 procs events states \<longleftrightarrow>
(\<forall>f.(states 0 = Vote_Count f \<longrightarrow>
(f= (find_vote events)\<and> (not_every_vote_counted procs (find_vote events)))))\<close>
(* Invariant 7: if a message (sender, Send p (Propose val)) is in msgs, then p=0 *)
definition inv7 where
\<open>inv7 msgs \<longleftrightarrow>
(\<forall>p sender val.((sender, Send p (Propose val))\<in>msgs \<longrightarrow>
(p=0)))\<close>
(* Invariant 8: if the acceptor is in state Nothing then find_vote events = initial_vote_count *)
definition inv8 where
\<open>inv8 events states \<longleftrightarrow>
(states 0 = Nothing \<longrightarrow>
(find_vote events=initial_vote_count))\<close>
lemma inv456initial:
assumes \<open>execute consensus_step (\<lambda>x. Nothing) procs [] msgs states\<close>
shows \<open>inv4 procs [] states \<and> inv5 procs [] states \<and> inv6 procs [] states\<close>
proof -
have \<open>states = (\<lambda>x. Nothing)\<close>
using assms execute_init by blast
thus ?thesis
using inv4_def inv5_def inv6_def by (metis state.distinct(1) state.distinct(3))
qed
lemma inv7initial: \<open>inv7 {}\<close>
using inv7_def by blast
lemma inv8initial: \<open>inv8 [] states\<close>
proof -
have \<open>find_vote []=initial_vote_count\<close> by auto
thus ?thesis using inv8_def by blast
qed
lemma anotherinv7:
assumes \<open>inv7 msgs\<close>
and \<open>msgs' = msgs \<union> ((\<lambda>msg. (proc, msg)) ` sent)\<close>
and \<open>execute consensus_step (\<lambda>x. Nothing) procs (events @ [(proc,event)]) msgs' states'\<close>
and \<open>consensus_step procs proc (states proc) event = (new_state, sent)\<close>
and \<open>states' = states(proc:=new_state)\<close>
shows \<open>inv7 msgs'\<close>
proof (cases event)
case (Receive sender msg)
show ?thesis
proof (cases \<open>proc=0\<close>)
case True
hence know:\<open>(new_state,sent) = acceptor_step procs (states proc) (Receive sender msg)\<close>
using assms(4) Receive acceptor_step.elims by force
hence knowsent:\<open>sent = snd (acceptor_step procs (states proc) (Receive sender msg))\<close>
by (metis eq_snd_iff)
thus ?thesis
proof (cases \<open>states 0\<close>)
case Nothing
then show ?thesis using knowsent
by (smt (verit, del_insts) True Un_def assms(1) assms(2) assms(3) image_iff inv3_def inv7_def invariants mem_Collect_eq prod.inject)
next
case (Value val)
then show ?thesis using knowsent
by (smt (verit, del_insts) True Un_def assms(1) assms(2) assms(3) image_iff inv3_def inv7_def invariants mem_Collect_eq prod.inject)
next
case (Vote_Count x3)
then show ?thesis using knowsent
by (smt (verit, del_insts) True Un_def assms(1) assms(2) assms(3) image_iff inv3_def inv7_def invariants mem_Collect_eq prod.inject)
qed
next
case False
hence \<open>sent = snd (proposer_step procs (states proc) event)\<close>
using assms(4) by auto
hence \<open>sent = snd (proposer_step procs (states proc) (Receive sender msg))\<close>
using Receive by simp (* simp works here in an almost identical situation as above *)
hence \<open>sent={}\<close>
by (metis (no_types, lifting) False Receive assms(4) consensus_step.simps msg.exhaust prod.inject proposer_step.simps(2) proposer_step.simps(5) proposer_step.simps(6) proposer_step.simps(7) state.exhaust)
then show ?thesis
using assms(1) assms(2) by auto
qed
next
case (Request val)
show ?thesis
proof (cases \<open>proc=0\<close>)
case True
hence \<open>sent={}\<close> using Request assms(4) by force
then show ?thesis
using assms(1) assms(2) by auto
next
case False
thus ?thesis
proof(cases \<open>states proc\<close>)
case Nothing
hence \<open>sent={Send 0 (Propose val)}\<close>
using Request False assms(4) by auto
then show ?thesis
by (smt (verit, best) UnE assms(1) assms(2) imageE inv7_def old.prod.inject send.inject singletonD)
next
case (Value v)
hence \<open>sent={}\<close>
using False assms(4) by auto
hence \<open>msgs'=msgs\<close> by (simp add: assms(2))
then show ?thesis by (simp add: assms(1))
next
case (Vote_Count f)
hence \<open>sent={}\<close>
using False assms(4) by auto
hence \<open>msgs'=msgs\<close> by (simp add: assms(2))
then show ?thesis by (simp add: assms(1))
qed
qed
next
case Timeout
hence \<open>sent={}\<close>
by (metis acceptor_step.simps(4) assms(4) consensus_step.simps prod.inject proposer_step.simps(8))
then show ?thesis
using assms(1) assms(2) by auto
qed
lemma invs7:
assumes \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs states\<close>
shows \<open>inv7 msgs\<close>
using assms (* USING ASSMS IS IMPORTANT HERE! *)
proof(induction events arbitrary: msgs states rule: List.rev_induct)
case Nil
hence \<open>msgs={}\<close> using execute_init by blast
thus \<open>inv7 msgs\<close>
using inv7initial by blast
next
case (snoc x events)
obtain proc event where \<open>x = (proc, event)\<close>
by fastforce
hence exec: \<open>execute consensus_step (\<lambda>p. Nothing) procs
(events @ [(proc, event)]) msgs states\<close>
using snoc.prems by blast
from this obtain msgs' states' sent new_state
where step_rel1: \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs' states'\<close>
and step_rel2: \<open>consensus_step procs proc (states' proc) event = (new_state, sent)\<close>
and step_rel3: \<open>msgs = msgs' \<union> ((\<lambda>msg. (proc, msg)) ` sent)\<close>
and step_rel4: \<open>states = states' (proc := new_state)\<close>
by auto
have inv_before: \<open>inv7 msgs'\<close>
using snoc.IH step_rel1 by fastforce
then show \<open>inv7 msgs\<close>
by (metis \<open>x=(proc,event)\<close> exec anotherinv7 inv_before step_rel4 step_rel2 step_rel3)
qed
lemma find_vote_request:\<open>find_vote (events @ [(proc, (Request val))]) = find_vote events\<close>
proof (induct events)
case Nil
then show ?case by auto
next
case (Cons a events)
then show ?case
using find_vote_lemma2 by (metis append_Cons)
qed
lemma find_vote_timeout:\<open>find_vote (events @ [(proc, Timeout)]) = find_vote events\<close>
proof (induct events)
case Nil
then show ?case by auto
next
case (Cons a events)
then show ?case
using find_vote_lemma2 by (metis append_Cons)
qed
lemma find_vote_accept:\<open>find_vote (events @ [(proc, Receive sender (Accept val))]) = find_vote events\<close>
proof (induct events)
case Nil
then show ?case by auto
next
case (Cons a events)
then show ?case
using find_vote_lemma2 by (metis append_Cons)
qed
lemma find_vote_none_elim:
assumes \<open>find_vote (a # events) p = None\<close>
shows \<open>find_vote events p = None\<close>
proof (rule ccontr)
assume as:\<open>find_vote events p \<noteq> None\<close>
then obtain v where \<open>find_vote events p = Some v\<close>
by auto
hence \<open>find_vote (a # events) p \<noteq> None\<close>
proof(cases \<open>is_received_vote p a\<close>)
case True
hence \<open>find_vote (a # events) p = Some (prop_val (recv_msg (snd a)))\<close>
using find_vote.simps by auto
then show ?thesis by auto
next
case False
hence \<open>find_vote (a # events) p = find_vote events p\<close>
using find_vote.simps by auto
then show ?thesis using as by auto
qed
thus \<open>False\<close> using \<open>find_vote (a # events) p = None\<close> by auto
qed
lemma find_vote_nonsender:
assumes \<open>p\<noteq>sender\<close>
shows \<open>find_vote (events @ [(proc, Receive sender (Propose val))]) p = find_vote events p\<close>
proof (cases \<open>find_vote events p\<close>)
case None
have key:\<open>\<not>(is_received_vote p (proc, (Receive sender (Propose val))))\<close>
using assms by auto
show ?thesis using None
proof(induct events)
case Nil
hence \<open>find_vote ([] @ [(proc, Receive sender (Propose val))]) p = None\<close>
using key find_vote.simps by auto
then show ?case by auto
next
case (Cons a events)
hence \<open>find_vote events p = None\<close>
using find_vote_none_elim by metis
thus ?case by (metis Cons.hyps append_Cons find_vote_lemma)
qed
next
case (Some v)
have key:\<open>\<not>(is_received_vote p (proc, (Receive sender (Propose val))))\<close>
using assms by auto
then show ?thesis
by (simp add: Some find_vote_lemma1)
qed
lemma only_0_receives_votes:
assumes \<open>execute consensus_step (\<lambda>x. Nothing) procs (events @ [(proc,event)]) msgs' states'\<close>
and \<open>event = Receive sender (Propose val)\<close>
shows \<open>proc=0\<close>
proof -
have \<open>valid_event event proc msgs'\<close>
using assms by auto
hence \<open>((sender, Send proc (Propose val)) \<in> msgs')\<close> by (simp add: assms(2))
moreover have \<open>inv7 msgs'\<close>
by (metis assms(1) invs7)
thus ?thesis using inv7_def
using calculation by fastforce
qed
lemma find_vote_nonzero:
assumes \<open>proc\<noteq>0\<close>
and \<open>execute consensus_step (\<lambda>x. Nothing) procs (events @ [(proc,event)]) msgs' states'\<close>
shows \<open>find_vote (events @ [(proc, event)]) = find_vote events\<close>
proof -
have \<open>\<And>sender val.(event\<noteq> Receive sender (Propose val))\<close> using assms only_0_receives_votes by metis
hence \<open>event = Timeout \<or> (\<exists> val.(event = Request val)) \<or> (\<exists> sender val.(event = Receive sender (Accept val)))\<close>
by (metis event.exhaust msg.exhaust)
thus ?thesis using find_vote_timeout find_vote_request find_vote_accept by metis
qed
lemma only0lemma:
assumes \<open>states 0 = states' 0\<close>
and \<open>inv4 procs events states \<and> inv5 procs events states \<and> inv6 procs events states\<close>
shows \<open>inv4 procs events states' \<and> inv5 procs events states' \<and> inv6 procs events states'\<close>
proof(cases \<open>procs\<subseteq>{0}\<close>)
case True
then show ?thesis by (metis assms(1) assms(2) inv4_def inv5_def inv6_def)
next
case False
hence \<open>\<forall>val. states 0 = Value val \<longrightarrow> Some val \<in> set_of_potential_winners procs (find_vote events)\<close>
using assms(2) by (metis inv4_def)
then show ?thesis by (metis assms(1) assms(2) inv4_def inv5_def inv6_def)
qed
lemma find_vote_already_done:
fixes pp
assumes \<open>states 0 = Value v\<close>
and \<open>inv4 procs events states \<and> inv5 procs events states\<close>
and \<open>pp\<noteq>0\<close>
and \<open>pp\<in> procs\<close>
shows \<open>find_vote (events @ [(p, event)]) pp = find_vote events pp\<close>
proof -
have \<open>\<not>(not_every_vote_counted procs (find_vote events))\<close>
using assms(1) assms(2) inv5_def by metis
hence h:\<open>\<forall>proc\<in>procs.(((find_vote events) proc \<noteq> None) \<or> proc=0)\<close> by auto
hence \<open>(find_vote events) pp \<noteq> None\<close> using assms(4) assms(3) by auto
then obtain val where \<open>(find_vote events) pp = Some val\<close> by auto
then show ?thesis
using find_vote_lemma1 by metis
qed
lemma potential_winners_request:\<open>set_of_potential_winners procs (find_vote (events @ [(proc, (Request val))])) = set_of_potential_winners procs (find_vote events)\<close>
using find_vote_request by metis
lemma potential_winners_timeout:\<open>set_of_potential_winners procs (find_vote (events @ [(proc, Timeout)])) = set_of_potential_winners procs (find_vote events)\<close>
using find_vote_timeout by metis
lemma anotherinv8:
assumes \<open>inv8 events states\<close>
and \<open>msgs' = msgs \<union> ((\<lambda>msg. (proc, msg)) ` sent)\<close>
and \<open>execute consensus_step (\<lambda>x. Nothing) procs (events @ [(proc,event)]) msgs' states'\<close>
and \<open>consensus_step procs proc (states proc) event = (new_state, sent)\<close>
and \<open>states' = states(proc:=new_state)\<close>
shows \<open>inv8 (events @ [(proc,event)]) states'\<close>
proof(cases event)
case (Receive sender msg)
then show ?thesis
proof(cases \<open>states 0\<close>)
case Nothing
hence kk:\<open>find_vote events = initial_vote_count\<close>
using inv8_def assms(1) by auto
then show ?thesis
proof (cases \<open>proc=0\<close>)
case True
then show ?thesis
proof (cases msg)
case (Propose val)
hence k:\<open>new_state = fst (count_update procs initial_vote_count sender val)\<close>
using assms(4) by (simp add: Receive True Nothing)
hence \<open>new_state \<noteq> Nothing\<close>
proof(cases \<open>not_every_vote_counted procs (initial_vote_count (sender := Some val))\<close>)
case True
hence \<open>count_update procs initial_vote_count sender val = (Vote_Count (initial_vote_count(sender:= Some val)), {})\<close>
using count_update.simps by auto
hence \<open>new_state = Vote_Count (initial_vote_count(sender:= Some val))\<close> by (simp add: k)
then show ?thesis by auto
next
let ?w=\<open>(the (pick_winner (procs\<union>{sender}) (initial_vote_count (sender := Some val))))\<close>
have non:\<open>initial_vote_count sender = None\<close> by auto
case False
hence \<open>count_update procs initial_vote_count sender val
= (set_value_and_send_accept_all (procs\<union>{sender}) ?w)\<close>
using non count_update.simps by (smt (verit, best) option.simps(4))
hence \<open>fst (count_update procs initial_vote_count sender val) = Value ?w\<close>
by simp
hence \<open>new_state = Value ?w\<close> by (simp add: k)
then show ?thesis by auto
qed
then show ?thesis
by (simp add: True assms(5) inv8_def)
next
case (Accept val)
hence \<open>find_vote events = find_vote (events @ [(proc,event)])\<close>
using find_vote_accept by (metis Receive)
hence \<open>find_vote (events @ [(proc,event)]) = initial_vote_count\<close>
by (simp add: kk)
then show ?thesis
using inv8_def by auto
qed
next
case False
hence \<open>find_vote events = find_vote (events @ [(proc,event)])\<close>
using find_vote_nonzero by (metis assms(3))
hence \<open>find_vote (events @ [(proc,event)]) = initial_vote_count\<close>
by (simp add: kk)
then show ?thesis
using inv8_def by auto
qed
next
case (Value val)
then show ?thesis
proof (cases \<open>proc=0\<close>)
case True
then show ?thesis
proof (cases msg)
case (Propose v)
then show ?thesis
using Receive True Value assms(4) assms(5) inv8_def by fastforce
next
case (Accept w)
then show ?thesis
using Receive True Value assms(4) assms(5) inv8_def by fastforce
qed
next
case False
then show ?thesis
by (simp add: Value assms(5) inv8_def)
qed
next
case (Vote_Count f)
then show ?thesis
proof (cases \<open>proc=0\<close>)
case True
then show ?thesis
proof (cases msg)
case (Propose val)
hence k:\<open>new_state = fst (count_update procs f sender val)\<close>
using assms(4) by (simp add: Receive True Vote_Count)
hence \<open>new_state \<noteq> Nothing\<close> using Receive True Vote_Count assms(4)
proof (cases \<open>f sender\<close>)
case None
then show ?thesis
proof(cases \<open>not_every_vote_counted procs (f (sender := Some val))\<close>)
case True
hence \<open>count_update procs f sender val = (Vote_Count (f(sender:= Some val)), {})\<close>
using None count_update.simps by auto
hence \<open>new_state = Vote_Count (f(sender:= Some val))\<close> by (simp add: k)
then show ?thesis by auto
next
let ?w=\<open>(the (pick_winner (procs\<union>{sender}) (f (sender := Some val))))\<close>
case False
hence \<open>count_update procs f sender val
= (set_value_and_send_accept_all (procs\<union>{sender}) ?w)\<close>
using None count_update.simps by (smt (verit, best) option.simps(4))
hence \<open>fst (count_update procs f sender val) = Value ?w\<close>
by simp
hence \<open>new_state = Value ?w\<close> by (simp add: k)
then show ?thesis by auto
qed
next
case (Some w)
hence \<open>count_update procs f sender val = (Vote_Count f, {})\<close>
using count_update.simps by auto
hence \<open>new_state = Vote_Count f\<close> by (simp add: k)
then show ?thesis by auto
qed
then show ?thesis
by (simp add: True assms(5) inv8_def)
next
case (Accept w)
then show ?thesis
using Receive True Vote_Count assms(4) assms(5) inv8_def by fastforce
qed
next
case False
then show ?thesis
by (simp add: Vote_Count assms(5) inv8_def)
qed
qed
next
case (Request val)
then show ?thesis
proof(cases \<open>states 0\<close>)
case Nothing
hence \<open>find_vote events=initial_vote_count\<close> using assms(1) inv8_def by blast
hence \<open>find_vote (events @ [(proc,event)]) = initial_vote_count\<close>
using find_vote_request by (metis Request)
then show ?thesis using inv8_def by blast
next
case (Value val)
hence \<open>states' 0 \<noteq> Nothing\<close>
using Request acceptor_step.simps(4) assms(4) assms(5) consensus_step.simps fun_upd_apply by auto
then show ?thesis using inv8_def by blast
next
case (Vote_Count x3)
hence \<open>states' 0 \<noteq> Nothing\<close>
using Request acceptor_step.simps(4) assms(4) assms(5) consensus_step.simps fun_upd_apply by auto
then show ?thesis using inv8_def by blast
qed
next
case Timeout
then show ?thesis
proof(cases \<open>states 0\<close>)
case Nothing
hence \<open>find_vote events=initial_vote_count\<close> using assms(1) inv8_def by blast
hence \<open>find_vote (events @ [(proc,event)]) = initial_vote_count\<close>
using find_vote_timeout by (metis Timeout)
then show ?thesis using inv8_def by blast
next
case (Value val)
hence \<open>states' 0 \<noteq> Nothing\<close>
using Timeout acceptor_step.simps(4) assms(4) assms(5) consensus_step.simps fun_upd_apply by auto
then show ?thesis using inv8_def by blast
next
case (Vote_Count x3)
hence \<open>states' 0 \<noteq> Nothing\<close>
using Timeout acceptor_step.simps(4) assms(4) assms(5) consensus_step.simps fun_upd_apply by auto
then show ?thesis using inv8_def by blast
qed
qed
lemma invs8:
assumes \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs states\<close>
shows \<open>inv8 events states\<close>
using assms (* USING ASSMS IS IMPORTANT HERE! *)
proof(induction events arbitrary: msgs states rule: List.rev_induct)
case Nil
thus \<open>inv8 [] states\<close>
using inv8initial by blast
next
case (snoc x events)
obtain proc event where \<open>x = (proc, event)\<close>
by fastforce
hence exec: \<open>execute consensus_step (\<lambda>p. Nothing) procs
(events @ [(proc, event)]) msgs states\<close>
using snoc.prems by blast
from this obtain msgs' states' sent new_state
where step_rel1: \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs' states'\<close>
and step_rel2: \<open>consensus_step procs proc (states' proc) event = (new_state, sent)\<close>
and step_rel3: \<open>msgs = msgs' \<union> ((\<lambda>msg. (proc, msg)) ` sent)\<close>
and step_rel4: \<open>states = states' (proc := new_state)\<close>
by auto
have inv_before: \<open>inv8 events states'\<close>
using snoc.IH step_rel1 by fastforce
then show \<open>inv8 (events @ [x]) states\<close>
by (metis \<open>x=(proc,event)\<close> exec anotherinv8 inv_before step_rel4 step_rel2 step_rel3)
qed
lemma inv4_request:
assumes \<open>inv4 procs events states\<close>
shows \<open>inv4 procs (events @ [(proc, (Request val))]) states\<close>
proof (cases \<open>procs \<subseteq> {0}\<close>)
case True
then show ?thesis using inv4_def by auto
next
case False
then show ?thesis
proof (cases \<open>states 0\<close>)
case Nothing
hence \<open>\<forall>v. states 0 \<noteq> Value v\<close> by auto
then show ?thesis using inv4_def by blast
next
case (Value w)
have \<open>\<And>v.(states 0 = Value v \<Longrightarrow>
(Some v \<in> set_of_potential_winners procs (find_vote (events @ [(proc, (Request val))]))))\<close>
proof -
fix v
assume a:\<open>states 0 = Value v\<close>
thus \<open>Some v \<in> set_of_potential_winners procs (find_vote (events @ [(proc, (Request val))]))\<close>
proof (cases \<open>v=w\<close>)
case True
then show ?thesis using potential_winners_request
by (metis False a assms inv4_def)
next
case False
then show ?thesis
by (metis Value a state.inject(1))
qed
qed
hence \<open>\<forall>v.(states 0 = Value v \<longrightarrow>
(Some v \<in> set_of_potential_winners procs (find_vote (events @ [(proc, (Request val))]))))\<close>
by auto
then show ?thesis by (simp add: inv4_def)
next
case (Vote_Count f)
hence \<open>\<forall>v. states 0 \<noteq> Value v\<close> by auto
then show ?thesis using inv4_def by blast
qed
qed
lemma inv4_timeout:
assumes \<open>inv4 procs events states\<close>
shows \<open>inv4 procs (events @ [(proc, Timeout)]) states\<close>
proof (cases \<open>procs \<subseteq> {0}\<close>)
case True
then show ?thesis using inv4_def by auto
next
case False
then show ?thesis
proof (cases \<open>states 0\<close>)
case Nothing
hence \<open>\<forall>v. states 0 \<noteq> Value v\<close> by auto
then show ?thesis using inv4_def by blast
next
case (Value w)
have \<open>\<And>v.(states 0 = Value v \<Longrightarrow>
(Some v \<in> set_of_potential_winners procs (find_vote (events @ [(proc, Timeout)]))))\<close>
proof -
fix v
assume a:\<open>states 0 = Value v\<close>
thus \<open>Some v \<in> set_of_potential_winners procs (find_vote (events @ [(proc, Timeout)]))\<close>
proof (cases \<open>v=w\<close>)
case True
then show ?thesis using potential_winners_timeout
by (metis False a assms inv4_def)
next
case False
then show ?thesis
by (metis Value a state.inject(1))
qed
qed
hence \<open>\<forall>v.(states 0 = Value v \<longrightarrow>
(Some v \<in> set_of_potential_winners procs (find_vote (events @ [(proc, Timeout)]))))\<close>
by auto
then show ?thesis by (simp add: inv4_def)
next
case (Vote_Count f)
hence \<open>\<forall>v. states 0 \<noteq> Value v\<close> by auto
then show ?thesis using inv4_def by blast
qed
qed
lemma inv5_request:
assumes \<open>inv5 procs events states\<close>
shows \<open>inv5 procs (events @ [(proc, (Request val))]) states\<close>
proof (cases \<open>states 0\<close>)
case Nothing
hence \<open>\<forall>v. states 0 \<noteq> Value v\<close> by auto
then show ?thesis using inv5_def by blast
next
case (Value w)
have \<open>\<And>v.(states 0 = Value v \<Longrightarrow>
(\<not>(not_every_vote_counted procs (find_vote (events @ [(proc, (Request val))])))))\<close>
by (metis assms find_vote_request inv5_def)
hence \<open>\<forall>v.(states 0 = Value v \<longrightarrow>
(\<not>(not_every_vote_counted procs (find_vote (events @ [(proc, (Request val))])))))\<close>
by auto
then show ?thesis by (simp add: inv5_def)
next
case (Vote_Count f)
hence \<open>\<forall>v. states 0 \<noteq> Value v\<close> by auto
then show ?thesis using inv5_def by blast
qed
lemma inv5_timeout:
assumes \<open>inv5 procs events states\<close>
shows \<open>inv5 procs (events @ [(proc, Timeout)]) states\<close>
proof (cases \<open>states 0\<close>)
case Nothing
hence \<open>\<forall>v. states 0 \<noteq> Value v\<close> by auto
then show ?thesis using inv5_def by blast
next
case (Value w)
have \<open>\<And>v.(states 0 = Value v \<Longrightarrow>
(\<not>(not_every_vote_counted procs (find_vote (events @ [(proc, Timeout)])))))\<close>
by (metis assms find_vote_timeout inv5_def)
hence \<open>\<forall>v.(states 0 = Value v \<longrightarrow>
(\<not>(not_every_vote_counted procs (find_vote (events @ [(proc, Timeout)])))))\<close>
by auto
then show ?thesis by (simp add: inv5_def)
next
case (Vote_Count f)
hence \<open>\<forall>v. states 0 \<noteq> Value v\<close> by auto
then show ?thesis using inv5_def by blast
qed
lemma inv6_request:
assumes \<open>inv6 procs events states\<close>
shows \<open>inv6 procs (events @ [(proc, (Request val))]) states\<close>
proof (cases \<open>states 0\<close>)
case Nothing
hence \<open>\<forall>f. states 0 \<noteq> Vote_Count f\<close> by auto
then show ?thesis using inv6_def by blast
next
case (Value w)
hence \<open>\<forall>f. states 0 \<noteq> Vote_Count f\<close> by auto
then show ?thesis using inv6_def by blast
next
case (Vote_Count f)
have \<open>find_vote events = find_vote (events @ [(proc, (Request val))])\<close>
by (simp add: find_vote_request)
moreover have \<open>not_every_vote_counted procs (find_vote events)\<close>
using Vote_Count assms inv6_def by blast
ultimately show ?thesis
by (metis (no_types, lifting) assms inv6_def)
qed
lemma inv6_timeout:
assumes \<open>inv6 procs events states\<close>
shows \<open>inv6 procs (events @ [(proc, Timeout)]) states\<close>
proof (cases \<open>states 0\<close>)
case Nothing
hence \<open>\<forall>f. states 0 \<noteq> Vote_Count f\<close> by auto
then show ?thesis using inv6_def by blast
next
case (Value w)
hence \<open>\<forall>f. states 0 \<noteq> Vote_Count f\<close> by auto
then show ?thesis using inv6_def by blast
next
case (Vote_Count f)
have \<open>find_vote events = find_vote (events @ [(proc, Timeout)])\<close>
by (simp add: find_vote_timeout)
moreover have \<open>not_every_vote_counted procs (find_vote events)\<close>
using Vote_Count assms inv6_def by blast
ultimately show ?thesis
by (metis (no_types, lifting) assms inv6_def)
qed
lemma some_lemma: \<open>Some (the (Some v)) = Some v\<close>
by auto
lemma anotherinv456pnonzero:
assumes \<open>p\<noteq>0\<close>
and \<open>inv4 procs events states \<and> inv5 procs events states \<and> inv6 procs events states\<close>
and \<open>states' 0 = states 0\<close>
and \<open>execute consensus_step (\<lambda>x. Nothing) procs (events @ [(p,event)]) msgs' states'\<close>
shows \<open>inv4 procs (events @ [(p,event)]) states' \<and> inv5 procs (events @ [(p,event)]) states'
\<and> inv6 procs (events @ [(p,event)]) states'\<close>
proof (cases \<open>states 0\<close>)
case Nothing
hence \<open>\<forall>v. states 0 \<noteq> Value v\<close> by auto
moreover have \<open>\<forall>f. states 0 \<noteq> Vote_Count f\<close> using Nothing by auto
ultimately show ?thesis using inv4_def inv5_def inv6_def
by (metis assms(3))
next
case (Value w)
hence key:\<open>\<And>pp. (pp\<in>procs\<and>pp\<noteq>0 \<Longrightarrow>find_vote (events @ [(p, event)]) pp = find_vote events pp)\<close>
using find_vote_already_done by (metis assms(2))
hence key2:\<open>\<And>pp val.((pp\<in>procs) \<Longrightarrow> ((find_vote (events @ [(p,event)])) pp = val \<and> pp\<noteq>0) \<longleftrightarrow> ((find_vote events) pp = val) \<and> pp\<noteq>0)\<close>
by auto
hence \<open>\<And> val. (\<exists>pp\<in>procs. (find_vote (events @ [(p,event)])) pp = val \<and> pp \<noteq> 0) \<longleftrightarrow> (\<exists>pp\<in>procs. (find_vote events) pp = val \<and> pp \<noteq> 0)\<close>
by auto
hence \<open>{val.(\<exists>pp\<in>procs. (find_vote (events @ [(p,event)])) pp = val \<and> pp \<noteq> 0)} = {val.(\<exists>pp\<in>procs. (find_vote events) pp = val \<and> pp \<noteq> 0)}\<close>
by auto
hence hvals:\<open>vals_with_votes procs (find_vote (events @ [(p, event)])) = vals_with_votes procs (find_vote events)\<close>
by auto
have \<open>\<And>val.({pp\<in> procs . (find_vote (events @ [(p, event)])) pp = val \<and> pp\<noteq>0}={pp\<in> procs . (find_vote events) pp = val \<and> pp\<noteq>0})\<close>
using key2 by auto
hence hh:\<open>nonzero_counter procs (find_vote (events @ [(p, event)])) = nonzero_counter procs (find_vote events)\<close>
by auto
hence \<open>most_vote_counts procs (find_vote (events @ [(p, event)])) = most_vote_counts procs (find_vote events)\<close>
using hvals by auto
hence \<open>set_of_potential_winners procs (find_vote (events @ [(p, event)]))
= set_of_potential_winners procs (find_vote events)\<close>
using hh by auto
moreover have \<open>states' 0 = states 0\<close> using assms(3) assms(1) by auto
hence \<open>inv4 procs events states' \<and> inv5 procs events states' \<and> inv6 procs events states'\<close>
using only0lemma by (metis assms(2))
ultimately have ult1:\<open>inv4 procs (events @ [(p,event)]) states'\<close>
using inv4_def by blast
have \<open>\<not>(not_every_vote_counted procs (find_vote events))\<close>
by (meson Value assms(2) inv5_def)
hence \<open>\<not>(not_every_vote_counted procs (find_vote (events @ [(p, event)])))\<close>
using key by auto
hence ult2:\<open>inv5 procs (events @ [(p,event)]) states'\<close> using inv5_def by auto
have \<open>\<forall>f. states 0 \<noteq> Vote_Count f\<close> using Value by auto
thus ?thesis using ult1 ult2
by (simp add: assms(3) inv6_def)
next
case (Vote_Count f)
hence \<open>\<forall>v. states 0 \<noteq> Value v\<close> by auto
hence h:\<open>inv4 procs (events @ [(p,event)]) states' \<and> inv5 procs (events @ [(p,event)]) states'\<close>
using inv4_def inv5_def by (metis assms(3))
have \<open>inv4 procs events states' \<and> inv5 procs events states' \<and> inv6 procs events states'\<close>
using only0lemma assms(2) by (metis assms(3))
moreover have \<open>find_vote events = find_vote (events @ [(p,event)])\<close>
using find_vote_nonzero assms(1) assms(4) by metis
moreover have \<open>not_every_vote_counted procs (find_vote events)\<close>
using Vote_Count assms inv6_def by blast
ultimately have \<open>inv6 procs (events @ [(p,event)]) states'\<close>
using inv6_def by metis
thus ?thesis using h by auto
qed
lemma state_value_does_not_change:
assumes \<open>consensus_step procs 0 (Value w) event = (new_state, sent)\<close>
shows \<open>new_state = Value w\<close>
proof (cases \<open>\<exists>sender val. (event = (Receive sender (Propose val)))\<close>)
have \<open>consensus_step procs 0 (Value w) event = acceptor_step procs (Value w) event\<close> by auto
hence h:\<open>new_state = fst (acceptor_step procs (Value w) event)\<close>
using assms by auto
case True
obtain sender where \<open>acceptor_step procs (Value w) event = (Value w, {Send sender (Accept w)})\<close>
using True by auto
thus \<open>new_state = Value w\<close> using h by auto
next
case False
hence \<open>acceptor_step procs (Value w) event = (Value w, {})\<close>
by (metis acceptor_step.simps(2) acceptor_step.simps(3) acceptor_step.simps(4) event.exhaust msg.exhaust)
then show ?thesis
using assms by auto
qed
lemma anotherinv456pzero:
assumes \<open>consensus_step procs 0 (states 0) event = (new_state, sent)\<close>
and \<open>states' = states(0:=new_state)\<close>
and \<open>inv4 procs events states \<and> inv5 procs events states \<and> inv6 procs events states\<close>
and \<open>execute consensus_step (\<lambda>x. Nothing) procs (events @ [(0,event)]) msgs' states'\<close>
and \<open>msgs' = msgs \<union> ((\<lambda>msg. (0, msg)) ` sent)\<close>
and \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs states\<close>
and \<open>finite procs\<close>
shows \<open>inv4 procs (events @ [(0,event)]) states' \<and> inv5 procs (events @ [(0,event)]) states'
\<and> inv6 procs (events @ [(0,event)]) states'\<close>
proof(cases event)
case (Receive sender msg)
then show ?thesis
proof(cases msg)
case (Propose v)
thus ?thesis
proof (cases \<open>states' 0\<close>)
case Nothing
then show ?thesis
by (simp add: inv4_def inv5_def inv6_def)
next
case (Value val)
thus ?thesis
proof(cases \<open>states 0\<close>)
case Nothing
hence \<open>new_state= Value val\<close>
using Value assms(2) by auto
hence h:\<open>(Value val,sent) = (count_update procs initial_vote_count sender v)\<close>
using assms(1) by (simp add: Propose Receive Nothing)
have knowfind:\<open>find_vote events = initial_vote_count\<close>
using Nothing invs8 assms(6) inv8_def by blast
moreover have hh:\<open>initial_vote_count sender = None\<close> by auto
moreover have hy:\<open>\<not>(not_every_vote_counted procs (initial_vote_count (sender := Some v)))\<close>
proof(rule ccontr)
assume \<open>\<not> \<not> not_every_vote_counted procs (initial_vote_count(sender \<mapsto> v))\<close>
hence \<open>not_every_vote_counted procs (initial_vote_count(sender \<mapsto> v))\<close> by auto
hence \<open>(Vote_Count (initial_vote_count(sender \<mapsto> v)), {}) = (count_update procs initial_vote_count sender v)\<close>
using hh count_update.simps by auto
hence \<open>Value val = Vote_Count (initial_vote_count(sender \<mapsto> v))\<close> using h by auto
thus False by auto
qed
(*hence \<open>Value val = fst(set_value_and_send_accept_all (procs\<union>{sender}) (the (pick_winner (procs\<union>{sender}) (initial_vote_count (sender := Some v)))))\<close>
using h hh count_update.simps *)
have \<open>event = Receive sender (Propose v)\<close>
by (simp add: Propose Receive)
hence thiscase:\<open>(consensus_step procs 0 (states 0) event) = (acceptor_step procs Nothing (Receive sender (Propose v)))\<close>
using Nothing by simp
hence ha:\<open>sent =snd (acceptor_step procs Nothing (Receive sender (Propose v)))\<close>
using assms(1) by (smt (verit, best) sndI)
have h:\<open>acceptor_step procs Nothing (Receive sender (Propose v))
= count_update procs initial_vote_count sender v\<close> by simp
let ?w=\<open>(the (pick_winner (procs\<union>{sender}) (initial_vote_count (sender := Some v))))\<close>
have hz:\<open>count_update procs initial_vote_count sender v = set_value_and_send_accept_all (procs\<union>{sender}) ?w\<close>
apply (simp only: count_update.simps hh hy)
by simp
have hw:\<open>set_value_and_send_accept_all (procs\<union>{sender}) ?w = (Value ?w,((\<lambda>p. (Send p (Accept ?w))) ` (procs\<union>{sender})))\<close>
by simp
hence sentis:\<open>sent = ((\<lambda>p. (Send p (Accept ?w))) ` (procs\<union>{sender}))\<close> using ha h hz hw by simp
hence \<open>\<forall>x\<in>sent. send_msg x = (Accept ?w)\<close>
by force
moreover have \<open>send_msg (Send 0 (Propose v))\<noteq> (Accept ?w)\<close>
by (metis msg.distinct(1) send.sel(2))
ultimately have \<open>Send 0 (Propose v) \<notin> sent\<close> by auto
hence \<open>(sender, Send 0 (Propose v))\<in> msgs\<close>
using \<open>event = Receive sender (Propose v)\<close> assms(4) assms(5) image_iff by auto
hence nonzero:\<open>sender\<noteq>0\<close>
by (metis \<open>event = Receive sender (Propose v)\<close> assms(4) execute_receive inv3_def invariants)
have theprocs:\<open>\<forall>p\<in>procs. p=0\<or>p=sender\<close>
using hy by fastforce
hence theprocscont:\<open>(procs\<union>{sender})\<subseteq>{0,sender}\<close> by blast
hence pexist:\<open>\<exists>p\<in>(procs\<union>{sender}). (((initial_vote_count(sender:= Some v)) p) = (Some v) \<and> p \<noteq> 0)\<close>
using nonzero by auto
hence \<open>Some v \<in> {u.\<exists>p\<in>(procs\<union>{sender}). (((initial_vote_count(sender:= Some v)) p) = u \<and> p \<noteq> 0)}\<close>
by simp
hence valin:\<open>Some v \<in> vals_with_votes (procs\<union>{sender}) (initial_vote_count(sender:= Some v))\<close>
by auto
have knowvotes:\<open>find_vote (events @ [(0,event)]) = initial_vote_count(sender:= Some v)\<close>
proof
fix p
show \<open>find_vote (events @ [(0, event)]) p = (initial_vote_count(sender \<mapsto> v)) p\<close>
proof(cases \<open>p=sender\<close>)
case True
have \<open>find_vote events sender = None\<close>
using knowfind by simp
hence \<open>find_vote (events @ [(0, Receive sender (Propose v))]) sender = Some v\<close>
proof(induct events)
case Nil
then show ?case by auto
next
case (Cons a events)
hence \<open>find_vote events sender = None\<close>
using find_vote_none_elim by metis
moreover have \<open>\<not>is_received_vote sender a\<close>
using \<open>find_vote (a # events) sender = None\<close> find_vote.simps by auto
hence \<open>find_vote (events @ [(0, Receive sender (Propose v))]) sender
= find_vote ((a# events) @ [(0, Receive sender (Propose v))]) sender\<close>
by auto
ultimately show ?case
using \<open>find_vote events sender = None \<Longrightarrow> find_vote (events @ [(0, Receive sender (Propose v))]) sender = Some v\<close>
by auto
qed
hence \<open>find_vote (events @ [(0, event)]) sender = Some v\<close> using Receive Propose by auto
then show ?thesis
by (simp add: True)
next
case False
hence \<open>(initial_vote_count(sender \<mapsto> v)) p = None\<close>
using nonzero by simp
moreover have \<open>find_vote (events @ [(0, event)]) p = find_vote events p\<close>
using find_vote_nonsender by (metis False \<open>event = Receive sender (Propose v)\<close>)
ultimately show ?thesis
using knowfind by auto
qed
qed
moreover have \<open>\<exists>p\<in>(procs\<union>{sender}). (((initial_vote_count(sender:= Some v)) p) = u \<and> p \<noteq> 0)\<longrightarrow>u=Some v\<close>
by simp
hence \<open>{u.\<exists>p\<in>(procs\<union>{sender}). (((initial_vote_count(sender:= Some v)) p) = u \<and> p \<noteq> 0)}\<subseteq> {Some v}\<close>
using theprocs by auto
hence knowvalswithvotes:\<open>vals_with_votes (procs\<union>{sender}) (initial_vote_count(sender:= Some v)) = {Some v}\<close>
by (smt (z3) Collect_cong \<open>Some v \<in> {u. \<exists>p\<in>procs \<union> {sender}. (initial_vote_count(sender \<mapsto> v)) p = u \<and> p \<noteq> 0}\<close> empty_iff subset_singleton_iff vals_with_votes.elims)
hence \<open>sender\<in>{p\<in> (procs\<union>{sender}) . ((initial_vote_count(sender:= Some v)) p = (Some v) \<and> p\<noteq>0)}\<close>
using theprocs by fastforce
hence somevalcount:\<open>nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some v)) (Some v) =1\<close>
using pexist by simp
hence \<open>(nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some v)))`(vals_with_votes (procs\<union>{sender}) (initial_vote_count(sender:= Some v))) = {1}\<close>
by (metis knowvalswithvotes image_insert image_is_empty)
hence mostvotes1:\<open>most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some v)) = 1\<close> by simp
hence \<open>nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some v)) (Some v) = most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some v))\<close>
using somevalcount by linarith
hence somevalcontainment:\<open>Some v \<in> set_of_potential_winners (procs\<union>{sender}) (initial_vote_count(sender:= Some v))\<close>
by simp
moreover have \<open>\<And>somev.(somev\<noteq> Some v \<longrightarrow> {p\<in> (procs\<union>{sender}) . ((initial_vote_count(sender:= Some v)) p = somev \<and> p\<noteq>0)} = {})\<close>
using theprocs by fastforce
hence \<open>\<And>somev.(somev\<noteq> Some v \<longrightarrow> card{p\<in> (procs\<union>{sender}) . ((initial_vote_count(sender:= Some v)) p = somev \<and> p\<noteq>0)} =0)\<close>
by (metis (no_types, lifting) card.empty)
hence \<open>\<And>somev.(somev\<noteq> Some v \<longrightarrow> nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some v)) somev =0)\<close>
by simp
hence conp:\<open>\<And>somev.(somev \<noteq> Some v \<longrightarrow> nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some v)) somev \<noteq> most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some v)))\<close>
using mostvotes1 by simp
hence conp2:\<open>\<And>somev.(\<not>(somev = Some v) \<Longrightarrow> \<not>(nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some v)) somev = most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some v))))\<close>
by auto
hence \<open>\<And>somev.((nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some v)) somev = most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some v))) \<Longrightarrow> somev=Some v)\<close>
using flip_contrap by blast
hence cont:\<open>\<And>somev.((nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some v)) somev = most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some v))) \<Longrightarrow> somev\<in>{Some v})\<close>
by blast
have \<open>set_of_potential_winners (procs\<union>{sender}) (initial_vote_count(sender:= Some v)) \<subseteq> {Some v}\<close>
proof
fix x
assume as:\<open>x\<in> set_of_potential_winners (procs\<union>{sender}) (initial_vote_count(sender:= Some v))\<close>
hence \<open>x\<in>{some.(nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some v)) some = most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some v)))}\<close>
by simp
hence \<open>(nonzero_counter (procs\<union>{sender}) (initial_vote_count(sender:= Some v)) x = most_vote_counts (procs\<union>{sender}) (initial_vote_count(sender:= Some v)))\<close>
by simp
thus \<open>x\<in>{Some v}\<close> using cont
by blast
qed
hence \<open>set_of_potential_winners (procs\<union>{sender}) (initial_vote_count(sender:= Some v)) = {Some v}\<close>
using somevalcontainment by fastforce
hence simper:\<open>{Some v} = set_of_potential_winners (procs\<union>{sender}) (initial_vote_count(sender:= Some v))\<close>
by auto
moreover have \<open>(SOME u. u \<in> {Some v}) = Some v\<close>
by simp
hence \<open>(SOME u. u \<in> set_of_potential_winners (procs\<union>{sender}) (initial_vote_count(sender:= Some v))) = Some v\<close>
using simper by simp
hence \<open>pick_winner (procs\<union>{sender}) (initial_vote_count(sender:= Some v)) = Some v\<close>
by simp
hence valwins:\<open>the (pick_winner (procs\<union>{sender}) (initial_vote_count(sender:= Some v))) = v\<close>
by auto
hence exactsent:\<open>sent = ((\<lambda>p. (Send p (Accept v))) ` (procs\<union>{sender}))\<close>
using sentis by simp
hence \<open>msgs' = msgs \<union> ((\<lambda>msg. (0, msg)) ` ((\<lambda>p. (Send p (Accept v))) ` (procs\<union>{sender})))\<close>
using assms(5) by simp
hence knowmsgs1:\<open>msgs' = msgs \<union> ((\<lambda>p. (0,(Send p (Accept v)))) ` (procs\<union>{sender}))\<close>
by auto
hence knowmsgs2:\<open>msgs'\<subseteq> msgs\<union> {(0, (Send sender (Accept v))),(0,(Send 0 (Accept v)))}\<close>
using theprocscont by auto
moreover have knowstates:\<open>states' = states (0 := Value v)\<close>
by (metis Pair_inject thiscase valwins assms(1) assms(2) h hw hz)
hence \<open>val=v\<close> using Value by fastforce
hence \<open>{Some val} = set_of_potential_winners (procs\<union>{sender}) (initial_vote_count(sender:= Some v))\<close>
by (simp add: simper)
hence \<open>Some val \<in> set_of_potential_winners (procs\<union>{sender}) (initial_vote_count(sender:= Some v))\<close>
by blast
hence vin2:\<open>Some val \<in> set_of_potential_winners (procs\<union>{sender}) (find_vote (events @ [(0,event)]))\<close>
by (simp add: knowvotes)
hence i4:\<open>inv4 procs (events @ [(0,event)]) states'\<close>
proof (cases \<open>procs \<subseteq> {0}\<close>)
case True
then show ?thesis using inv4_def by auto
next
case False
hence \<open>sender\<in>procs\<close> using theprocs by auto
hence \<open>procs\<union>{sender}=procs\<close> by auto
hence \<open>Some val \<in> set_of_potential_winners (procs) (find_vote (events @ [(0,event)]))\<close>
using vin2 by simp
then show ?thesis
using inv4_def by (metis Value state.inject(1))
qed
have \<open>\<not>(not_every_vote_counted procs (find_vote (events @ [(0,event)])))\<close>
using hy knowvotes by presburger
hence i5:\<open>inv5 procs (events @ [(0,event)]) states'\<close>
using inv5_def by auto
have i6:\<open>inv6 procs (events @ [(0,event)]) states'\<close>
by (simp add: Value inv6_def)
thus ?thesis using i4 i5 i6 by auto
next
case (Value w)
hence key:\<open>\<And>pp. (pp\<in>procs\<and>pp\<noteq>0 \<Longrightarrow>find_vote (events @ [(0, event)]) pp = find_vote events pp)\<close>
using find_vote_already_done by (metis assms(3))
hence key2:\<open>\<And>pp val.((pp\<in>procs) \<Longrightarrow> ((find_vote (events @ [(0,event)])) pp = val \<and> pp\<noteq>0) \<longleftrightarrow> ((find_vote events) pp = val) \<and> pp\<noteq>0)\<close>
by auto
hence \<open>\<And> val. (\<exists>pp\<in>procs. (find_vote (events @ [(0,event)])) pp = val \<and> pp \<noteq> 0) \<longleftrightarrow> (\<exists>pp\<in>procs. (find_vote events) pp = val \<and> pp \<noteq> 0)\<close>
by auto
hence \<open>{val.(\<exists>pp\<in>procs. (find_vote (events @ [(0,event)])) pp = val \<and> pp \<noteq> 0)} = {val.(\<exists>pp\<in>procs. (find_vote events) pp = val \<and> pp \<noteq> 0)}\<close>
by auto
hence hvals:\<open>vals_with_votes procs (find_vote (events @ [(0, event)])) = vals_with_votes procs (find_vote events)\<close>
by auto
have \<open>\<And>val.({pp\<in> procs . (find_vote (events @ [(0, event)])) pp = val \<and> pp\<noteq>0}={pp\<in> procs . (find_vote events) pp = val \<and> pp\<noteq>0})\<close>
using key2 by auto
hence hh:\<open>nonzero_counter procs (find_vote (events @ [(0, event)])) = nonzero_counter procs (find_vote events)\<close>
by auto
hence \<open>most_vote_counts procs (find_vote (events @ [(0, event)])) = most_vote_counts procs (find_vote events)\<close>
using hvals by auto
hence \<open>set_of_potential_winners procs (find_vote (events @ [(0, event)]))
= set_of_potential_winners procs (find_vote events)\<close>
using hh by auto
moreover have \<open>states' 0 = states 0\<close>
using \<open>states' 0 = Value val\<close> Value state_value_does_not_change assms(1) assms(2) by fastforce
ultimately have ult1:\<open>inv4 procs (events @ [(0,event)]) states'\<close>
using inv4_def by (metis assms(3))
have \<open>\<not>(not_every_vote_counted procs (find_vote events))\<close>
by (meson Value assms(3) inv5_def)
hence \<open>\<not>(not_every_vote_counted procs (find_vote (events @ [(0, event)])))\<close>
using key by auto
hence ult2:\<open>inv5 procs (events @ [(0,event)]) states'\<close> using inv5_def by auto
have \<open>inv6 procs (events @ [(0,event)]) states'\<close>
by (simp add: Value \<open>states' 0 = states 0\<close> inv6_def)
thus ?thesis using ult1 ult2 by auto
next
case (Vote_Count f) (* f decides to Value val after vote v *)
hence knowf:\<open>f = find_vote events\<close>
using assms(3) inv6_def by auto
moreover have \<open>not_every_vote_counted procs (find_vote events)\<close>
using assms(3) inv6_def Vote_Count by blast
ultimately have fdonebefore:\<open>(not_every_vote_counted procs f)\<close>
by auto
from this obtain p where \<open>p\<in>procs \<and> f p = None \<and> p \<noteq> 0\<close>
by auto
hence b:\<open>\<not> (procs \<union> {sender} \<subseteq> {0})\<close> by auto
have senderNone:\<open>find_vote events sender = None\<close>
proof (cases \<open>find_vote events sender\<close>)
case None
then show ?thesis by auto
next
case (Some uu) (* this case leads to a contradiction *)
hence \<open>f sender = Some uu\<close>
using knowf by simp
hence knowcount:\<open>count_update procs f sender v = (Vote_Count f , {})\<close>
using count_update.simps by auto
hence h:\<open>acceptor_step procs (Vote_Count f) (Receive sender (Propose v))
= (Vote_Count f, {})\<close> by simp
have \<open>event = Receive sender (Propose v)\<close>
by (simp add: Propose Receive)
hence \<open>(consensus_step procs 0 (states 0) event) = (Vote_Count f , {})\<close>
using Vote_Count h by simp
hence \<open>states' 0 = Vote_Count f\<close>
using assms(1) assms(2) by simp
hence \<open>False\<close>
using Value by auto
then show ?thesis by auto
qed
hence senderNone2: \<open>f sender = None\<close> using knowf by simp
have fdone:\<open>\<not>(not_every_vote_counted procs (f(sender := Some v)))\<close>
proof (rule ccontr)
assume \<open>\<not> \<not> not_every_vote_counted procs (f(sender := Some v))\<close>
hence \<open>not_every_vote_counted procs (f(sender := Some v))\<close> by auto
hence \<open>count_update procs f sender v = (Vote_Count (f (sender := Some v)), {})\<close>
using senderNone2 count_update.simps by auto
hence h:\<open>acceptor_step procs (Vote_Count f) (Receive sender (Propose v))
= (Vote_Count (f (sender := Some v)), {})\<close> by simp
have \<open>event = Receive sender (Propose v)\<close>
by (simp add: Propose Receive)
hence \<open>(consensus_step procs 0 (states 0) event) = (Vote_Count (f (sender := Some v)), {})\<close>
using Vote_Count h by simp
hence \<open>states' 0 = Vote_Count (f (sender := Some v))\<close>
using assms(1) assms(2) by simp
thus \<open>False\<close> using Value by auto
qed
hence isdone:\<open>\<not>(not_every_vote_counted procs ((find_vote events)(sender := Some v)))\<close>
using knowf by simp
have a1:\<open>find_vote [(0,event)] sender = Some v\<close>
using Receive Propose by auto
(*have \<open>\<exists>a.(fst a =0 \<and> snd a = event)\<close> by auto
from this obtain a where \<open>fst a =0 \<and> snd a = event\<close> by auto
have \<open>find_vote (events @ [a]) sender = find_vote [a] sender\<close>
using find_vote_lemma3wtf[where ?x = events and ?p = sender] senderNone by auto*)
have \<open>find_vote (events @ [(0,event)]) sender = find_vote [(0,event)] sender\<close>
using find_vote_lemma3type[where ?x = events and ?p = sender and ?q=0 and ?event=event]
senderNone by (metis a1)
(* have \<open>find_vote (events @ [(0,event)]) sender = find_vote [(0,event)] sender\<close>
using find_vote_lemma3[where ?x = events and ?p = sender] senderNone by auto *)
hence knowsendervote:\<open>find_vote (events @ [(0,event)]) sender = Some v\<close>
by (simp only: a1)
(*moreover have knowothervotes:\<open>p\<noteq>sender \<Longrightarrow> find_vote (events @ [(0,event)]) p = find_vote events p\<close>
using Receive find_vote_nonsender Propose by fastforce*)
have asdf:\<open>find_vote (events @ [(0,event)]) = (find_vote events) (sender:= Some v)\<close>
proof
fix p
show \<open>find_vote (events @ [(0, event)]) p = (find_vote events(sender \<mapsto> v)) p\<close>
proof(cases \<open>p=sender\<close>)
case True
then show ?thesis using knowsendervote by auto
next
case False
hence \<open>find_vote (events @ [(0,event)]) p = find_vote events p\<close>
using Receive find_vote_nonsender Propose by fastforce
moreover have \<open>find_vote events p = (find_vote events(sender \<mapsto> v)) p\<close>
using False by auto
ultimately show ?thesis by simp
qed
qed
hence finalvote:\<open>find_vote (events @ [(0,event)]) = (f(sender:= Some v))\<close>
using knowf by simp
hence votedone:\<open>\<not>(not_every_vote_counted procs (find_vote (events @ [(0,event)])))\<close>
using asdf Receive Propose isdone by auto
have i5:\<open>inv5 procs (events @ [(0,event)]) states'\<close>
using votedone inv5_def by auto
let ?somew = \<open>pick_winner (procs\<union>{sender}) (f (sender := Some v))\<close>
have b0:\<open>\<not> not_every_vote_counted (procs \<union> {sender}) (f(sender \<mapsto> v))\<close>
using fdone by auto
moreover have b2:\<open>finite (procs \<union> {sender})\<close>
using assms(7) by auto
ultimately have somewin:\<open>?somew \<in> set_of_potential_winners (procs \<union> {sender}) (f(sender := Some v))\<close>
using b winnerispotential[where ?procs=\<open>procs\<union>{sender}\<close> and ?f=\<open>f (sender := Some v)\<close>] by auto
obtain vvv where \<open>?somew = Some vvv\<close>
using b0 b b2 winnersome[where ?procs=\<open>procs\<union>{sender}\<close> and ?f=\<open>f (sender := Some v)\<close>] by auto
let ?w = \<open>the (pick_winner (procs\<union>{sender}) (f (sender := Some v)))\<close>
have \<open>vvv=?w\<close>
by (metis \<open>pick_winner (procs \<union> {sender}) (f(sender \<mapsto> v)) = Some vvv\<close> option.sel)
have valwins:\<open>val=?w\<close>
proof(rule ccontr)
assume a:\<open>val\<noteq>?w\<close>
have \<open>count_update procs f sender v = set_value_and_send_accept_all (procs\<union>{sender}) ?w\<close>
using senderNone2 fdone count_update.simps by (smt (verit, best) option.case_eq_if)
hence h:\<open>acceptor_step procs (Vote_Count f) (Receive sender (Propose v))
= set_value_and_send_accept_all (procs\<union>{sender}) ?w\<close> by simp
have \<open>event = Receive sender (Propose v)\<close>
by (simp add: Propose Receive)
hence \<open>(consensus_step procs 0 (states 0) event) = set_value_and_send_accept_all (procs\<union>{sender}) ?w\<close>
using Vote_Count h by simp
hence \<open>states' 0 = Value ?w\<close>
using assms(1) assms(2) by simp
moreover have \<open>states' 0 \<noteq> Value ?w\<close> using Value a by auto
ultimately show \<open>False\<close> by auto
qed
hence \<open>Some val = ?somew\<close>
using \<open>?somew = Some vvv\<close> \<open>vvv = ?w\<close> by simp
hence \<open>Some val \<in> set_of_potential_winners (procs \<union> {sender}) (f(sender := Some v))\<close>
by (simp only:somewin)
hence qwerty:\<open>Some val \<in> set_of_potential_winners (procs \<union> {sender}) (find_vote (events @ [(0,event)]))\<close>
using finalvote by simp
have \<open>not_every_vote_counted procs (find_vote events)\<close>
using assms(3) inv6_def Vote_Count by blast
hence \<open>sender \<in> procs\<close>
using isdone by (metis (mono_tags, lifting) fun_upd_other not_every_vote_counted.simps)
hence \<open>procs \<union> {sender} = procs\<close>
by auto
hence \<open>Some val \<in> set_of_potential_winners procs (find_vote (events @ [(0,event)]))\<close>
using qwerty by simp
hence i4:\<open>inv4 procs (events @ [(0,event)]) states'\<close>
by (metis Value inv4_def state.inject(1))
have \<open>\<forall>ff.(states' 0 \<noteq> Vote_Count ff)\<close>
using Value by auto
hence \<open>inv6 procs (events @ [(0,event)]) states'\<close>
using inv6_def by blast
then show ?thesis using i4 i5 by auto
qed
next
case vcf:(Vote_Count f) (* msg=Receive (Propose val) and states'0 = Vote_Count f *)
hence i4i5:\<open>inv4 procs (events @ [(0,event)]) states' \<and> inv5 procs (events @ [(0,event)]) states'\<close>
by (simp add: inv4_def inv5_def)
have \<open>inv6 procs (events @ [(0,event)]) states'\<close>
proof (cases \<open>states 0\<close>)
case Nothing
hence knowfind:\<open>find_vote events = initial_vote_count\<close>
using assms(6) inv8_def invs8 by blast
have n:\<open>initial_vote_count sender = None\<close> by auto
have notgafter:\<open>not_every_vote_counted procs (initial_vote_count(sender:= Some v))\<close>
proof (rule ccontr)
assume as:\<open>\<not>not_every_vote_counted procs (initial_vote_count(sender:= Some v))\<close>
let ?w = \<open>the (pick_winner (procs\<union>{sender}) (initial_vote_count (sender := Some v)))\<close>
have \<open>count_update procs initial_vote_count sender v = set_value_and_send_accept_all (procs\<union>{sender}) ?w\<close>
using as n count_update.simps by (smt (verit, best) option.case_eq_if)
hence h:\<open>acceptor_step procs (Vote_Count initial_vote_count) (Receive sender (Propose v))
= set_value_and_send_accept_all (procs\<union>{sender}) ?w\<close> by simp
have \<open>event = Receive sender (Propose v)\<close>
by (simp add: Propose Receive)
hence \<open>(consensus_step procs 0 (states 0) event) = set_value_and_send_accept_all (procs\<union>{sender}) ?w\<close>
using Nothing h by simp
hence \<open>states' 0 = Value ?w\<close>
using assms(1) assms(2) by simp
moreover have \<open>states' 0 \<noteq> Value ?w\<close> using vcf by auto
ultimately show \<open>False\<close> by auto
qed
hence \<open>count_update procs initial_vote_count sender v = (Vote_Count (initial_vote_count(sender:= Some v)) , {})\<close>
using n count_update.simps Propose Receive by auto
hence \<open>(acceptor_step procs (Vote_Count initial_vote_count) (Receive sender (Propose v))) = (Vote_Count (initial_vote_count(sender:= Some v)), {})\<close>
using Propose Receive by simp
hence \<open>(consensus_step procs 0 (states 0) (Receive sender (Propose v))) = (Vote_Count (initial_vote_count(sender:= Some v)), {})\<close>
using Nothing by auto
moreover have \<open>event = Receive sender (Propose v)\<close>
by (simp add: Propose Receive)
ultimately have \<open>new_state = Vote_Count (initial_vote_count(sender:= Some v))\<close>
using assms(1) by auto
hence \<open>states' 0 = Vote_Count (initial_vote_count(sender:= Some v))\<close>
using assms(2) by auto
hence \<open>Vote_Count f = Vote_Count (initial_vote_count(sender:= Some v))\<close>
using vcf by auto
hence gtof:\<open>f = (initial_vote_count(sender:= Some v))\<close> by auto
have hh:\<open>find_vote (events @ [(0,event)]) = (find_vote events)(sender:= Some v)\<close>
proof
fix p
show \<open>find_vote (events @ [(0,event)]) p = ((find_vote events)(sender:= Some v)) p\<close>
proof(cases \<open>p=sender\<close>)
case True
have hhh:\<open>find_vote events sender = None\<close>
using knowfind n by simp
have a1:\<open>find_vote [(0,event)] sender = Some v\<close>
using Receive Propose by auto
have \<open>find_vote (events @ [(0,event)]) sender = find_vote [(0,event)] sender\<close>
using find_vote_lemma3type[where ?x = events and ?p = sender and ?q=0 and ?event=event]
hhh by (metis a1)
hence \<open>find_vote (events @ [(0, event)]) sender = Some v\<close>
using Receive Propose by fastforce
moreover have \<open>((find_vote events)(sender:= Some v)) sender = Some v\<close>
by auto
ultimately show ?thesis
using True by simp
next
case False
then show ?thesis
by (simp add: Propose Receive find_vote_nonsender)
qed
qed
hence u1:\<open>f = find_vote (events @ [(0,event)])\<close>
using knowfind hh gtof by auto
hence u2:\<open>not_every_vote_counted procs (find_vote (events @ [(0,event)]))\<close>
using notgafter hh gtof by auto
then show \<open>inv6 procs (events @ [(0,event)]) states'\<close>
using u1 u2 inv6_def vcf by fastforce
next
case (Value u)
then show ?thesis
by (metis assms(1) assms(2) fun_upd_same state.distinct(5) state_value_does_not_change vcf)
next
case (Vote_Count g)
hence knowg:\<open>g = find_vote events\<close>
using assms(6) inv6_def assms(3) by blast
have notbefore:\<open>not_every_vote_counted procs (find_vote events)\<close>
using assms(3) inv6_def Vote_Count by blast
hence notg:\<open>not_every_vote_counted procs g\<close>
using knowg by auto
show ?thesis
proof (cases \<open>g sender\<close>)
case n:None
have notgafter:\<open>not_every_vote_counted procs (g(sender:= Some v))\<close>
proof (rule ccontr)
assume as:\<open>\<not>not_every_vote_counted procs (g(sender:= Some v))\<close>
let ?w = \<open>the (pick_winner (procs\<union>{sender}) (g (sender := Some v)))\<close>
have \<open>count_update procs g sender v = set_value_and_send_accept_all (procs\<union>{sender}) ?w\<close>
using as n count_update.simps by (smt (verit, best) option.case_eq_if)
hence h:\<open>acceptor_step procs (Vote_Count g) (Receive sender (Propose v))
= set_value_and_send_accept_all (procs\<union>{sender}) ?w\<close> by simp
have \<open>event = Receive sender (Propose v)\<close>
by (simp add: Propose Receive)
hence \<open>(consensus_step procs 0 (states 0) event) = set_value_and_send_accept_all (procs\<union>{sender}) ?w\<close>
using Vote_Count h by simp
hence \<open>states' 0 = Value ?w\<close>
using assms(1) assms(2) by simp
moreover have \<open>states' 0 \<noteq> Value ?w\<close> using vcf by auto
ultimately show \<open>False\<close> by auto
qed
hence \<open>count_update procs g sender v = (Vote_Count (g(sender:= Some v)) , {})\<close>
using n count_update.simps Propose Receive by auto
hence \<open>(acceptor_step procs (Vote_Count g) (Receive sender (Propose v))) = (Vote_Count (g(sender:= Some v)), {})\<close>
using Propose Receive by simp
hence \<open>(consensus_step procs 0 (states 0) (Receive sender (Propose v))) = (Vote_Count (g(sender:= Some v)), {})\<close>
using Vote_Count by auto
moreover have \<open>event = Receive sender (Propose v)\<close>
by (simp add: Propose Receive)
ultimately have \<open>new_state = Vote_Count (g(sender:= Some v))\<close>
using assms(1) by auto
hence \<open>states' 0 = Vote_Count (g(sender:= Some v))\<close>
using assms(2) by auto
hence \<open>Vote_Count f = Vote_Count (g(sender:= Some v))\<close>
using vcf by auto
hence gtof:\<open>f = (g(sender:= Some v))\<close> by auto
have hh:\<open>find_vote (events @ [(0,event)]) = (find_vote events)(sender:= Some v)\<close>
proof
fix p
show \<open>find_vote (events @ [(0,event)]) p = ((find_vote events)(sender:= Some v)) p\<close>
proof(cases \<open>p=sender\<close>)
case True
have hhh:\<open>find_vote events sender = None\<close>
using knowg n by simp
have a1:\<open>find_vote [(0,event)] sender = Some v\<close>
using Receive Propose by auto
have \<open>find_vote (events @ [(0,event)]) sender = find_vote [(0,event)] sender\<close>
using find_vote_lemma3type[where ?x = events and ?p = sender and ?q=0 and ?event=event]
hhh by (metis a1)
hence \<open>find_vote (events @ [(0, event)]) sender = Some v\<close>
using Receive Propose by fastforce
moreover have \<open>((find_vote events)(sender:= Some v)) sender = Some v\<close>
by auto
ultimately show ?thesis
using True by simp
next
case False
then show ?thesis
by (simp add: Propose Receive find_vote_nonsender)
qed
qed
hence u1:\<open>f = find_vote (events @ [(0,event)])\<close>
using knowg hh gtof by auto
hence u2:\<open>not_every_vote_counted procs (find_vote (events @ [(0,event)]))\<close>
using notgafter hh gtof by auto
then show \<open>inv6 procs (events @ [(0,event)]) states'\<close>
using u1 u2 inv6_def vcf by fastforce
next
case somevv:(Some vv)
hence \<open>count_update procs g sender v = (Vote_Count g , {})\<close>
using count_update.simps by auto
hence \<open>(acceptor_step procs (Vote_Count g) (Receive sender (Propose v))) = (Vote_Count g, {})\<close>
using Propose Receive by simp
hence \<open>(consensus_step procs 0 (states 0) (Receive sender (Propose v))) = (Vote_Count g, {})\<close>
using Vote_Count by auto
moreover have \<open>event = Receive sender (Propose v)\<close>
by (simp add: Propose Receive)
ultimately have \<open>new_state = Vote_Count g\<close>
using assms(1) by auto
hence \<open>states' 0 = Vote_Count g\<close>
using assms(2) by auto
hence \<open>Vote_Count f = Vote_Count g\<close>
using vcf by auto
hence \<open>f=g\<close> by auto
have hh:\<open>find_vote (events @ [(0,event)]) = find_vote events\<close>
proof
fix p
show \<open>find_vote (events @ [(0,event)]) p = find_vote events p\<close>
proof(cases \<open>p=sender\<close>)
case True
have hhh:\<open>find_vote events sender = Some vv\<close>
using knowg somevv by simp
hence \<open>find_vote (events @ [(0, event)]) sender = Some vv\<close>
using find_vote_lemma1 by fastforce
hence \<open>find_vote (events @ [(0, event)]) sender = find_vote events sender\<close>
using hhh by simp
then show ?thesis
using True by simp
next
case False
then show ?thesis
by (simp add: Propose Receive find_vote_nonsender)
qed
qed
hence u1:\<open>f = find_vote (events @ [(0,event)])\<close>
using knowg \<open>f=g\<close> by auto
have u2:\<open>not_every_vote_counted procs (find_vote (events @ [(0,event)]))\<close>
using notbefore hh by auto
then show \<open>inv6 procs (events @ [(0,event)]) states'\<close>
using u1 u2 inv6_def vcf by fastforce
qed
qed
then show ?thesis using i4i5 by auto
qed
next
case (Accept w)
thus ?thesis
proof (cases \<open>states 0\<close>)
case Nothing
hence \<open>states' 0 = Nothing\<close>
using Accept Receive assms(1) assms(2) by auto
then show ?thesis
by (simp add: inv4_def inv5_def inv6_def)
next
case (Value val)
hence key:\<open>\<And>pp. (pp\<in>procs\<and>pp\<noteq>0 \<Longrightarrow>find_vote (events @ [(0, event)]) pp = find_vote events pp)\<close>
using find_vote_already_done by (metis assms(3))
hence key2:\<open>\<And>pp val.((pp\<in>procs) \<Longrightarrow> ((find_vote (events @ [(0,event)])) pp = val \<and> pp\<noteq>0) \<longleftrightarrow> ((find_vote events) pp = val) \<and> pp\<noteq>0)\<close>
by auto
hence \<open>\<And> val. (\<exists>pp\<in>procs. (find_vote (events @ [(0,event)])) pp = val \<and> pp \<noteq> 0) \<longleftrightarrow> (\<exists>pp\<in>procs. (find_vote events) pp = val \<and> pp \<noteq> 0)\<close>
by auto
hence \<open>{val.(\<exists>pp\<in>procs. (find_vote (events @ [(0,event)])) pp = val \<and> pp \<noteq> 0)} = {val.(\<exists>pp\<in>procs. (find_vote events) pp = val \<and> pp \<noteq> 0)}\<close>
by auto
hence hvals:\<open>vals_with_votes procs (find_vote (events @ [(0, event)])) = vals_with_votes procs (find_vote events)\<close>
by auto
have \<open>\<And>val.({pp\<in> procs . (find_vote (events @ [(0, event)])) pp = val \<and> pp\<noteq>0}={pp\<in> procs . (find_vote events) pp = val \<and> pp\<noteq>0})\<close>
using key2 by auto
hence hh:\<open>nonzero_counter procs (find_vote (events @ [(0, event)])) = nonzero_counter procs (find_vote events)\<close>
by auto
hence \<open>most_vote_counts procs (find_vote (events @ [(0, event)])) = most_vote_counts procs (find_vote events)\<close>
using hvals by auto
hence \<open>set_of_potential_winners procs (find_vote (events @ [(0, event)]))
= set_of_potential_winners procs (find_vote events)\<close>
using hh by auto
moreover have \<open>states' 0 = states 0\<close> using Receive Accept assms by auto
ultimately have ult1:\<open>inv4 procs (events @ [(0,event)]) states'\<close>
using inv4_def by (metis assms(3))
have \<open>\<not>(not_every_vote_counted procs (find_vote events))\<close>
by (meson Value assms(3) inv5_def)
hence \<open>\<not>(not_every_vote_counted procs (find_vote (events @ [(0, event)])))\<close>
using key by auto
hence ult2:\<open>inv5 procs (events @ [(0,event)]) states'\<close> using inv5_def by auto
hence i4i5:\<open>inv4 procs (events @ [(0,event)]) states' \<and> inv5 procs (events @ [(0,event)]) states'\<close>
using ult1 ult2 by auto
have \<open>find_vote (events @ [(0,event)]) = find_vote events\<close>
using Receive Accept find_vote_accept by auto
hence \<open>inv6 procs (events @ [(0,event)]) states'\<close>
by (simp add: Value \<open>states' 0 = states 0\<close> inv6_def)
then show ?thesis using i4i5 by auto
next
case (Vote_Count f)
hence \<open>states' 0 = Vote_Count f\<close>
using Accept Receive assms(1) assms(2) by auto
hence i4i5:\<open>inv4 procs (events @ [(0,event)]) states' \<and> inv5 procs (events @ [(0,event)]) states'\<close>
by (simp add: inv4_def inv5_def)
have \<open>find_vote (events @ [(0,event)]) = find_vote events\<close>
using Receive Accept find_vote_accept by auto
hence \<open>inv6 procs (events @ [(0,event)]) states'\<close>
by (metis Vote_Count \<open>states' 0 = Vote_Count f\<close> assms(3) inv6_def)
then show ?thesis using i4i5 by auto
qed
qed
next
case (Request v)
then show ?thesis
using assms inv4_request inv5_request inv6_request by auto
next
case Timeout
then show ?thesis
using assms inv4_timeout inv5_timeout inv6_timeout by auto
qed
lemma invs456:
assumes \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs states\<close>
and \<open>finite procs\<close>
shows \<open>inv4 procs events states \<and> inv5 procs events states \<and> inv6 procs events states\<close>
using assms
proof(induction events arbitrary: msgs states rule: List.rev_induct)
case Nil
from this show \<open>inv4 procs [] states \<and> inv5 procs [] states \<and> inv6 procs [] states\<close>
using execute_init inv4_def inv5_def inv6_def by fastforce
next
case (snoc x events)
obtain proc event where \<open>x = (proc, event)\<close>
by fastforce
hence exec: \<open>execute consensus_step (\<lambda>p. Nothing) procs
(events @ [(proc, event)]) msgs states\<close>
using snoc.prems by blast
from this obtain msgs' states' sent new_state
where step_rel1: \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs' states'\<close>
and step_rel2: \<open>consensus_step procs proc (states' proc) event = (new_state, sent)\<close>
and step_rel3: \<open>msgs = msgs' \<union> ((\<lambda>msg. (proc, msg)) ` sent)\<close>
and step_rel4: \<open>states = states' (proc := new_state)\<close>
by auto
have inv_before: \<open>inv4 procs events states' \<and> inv5 procs events states' \<and> inv6 procs events states'\<close>
using snoc.IH step_rel1 assms(2) by fastforce
then show \<open>inv4 procs (events @ [x]) states \<and> inv5 procs (events @ [x]) states \<and> inv6 procs (events @ [x]) states\<close>
proof (cases \<open>proc = 0\<close>)
case True
then show ?thesis
by (metis assms(2) \<open>x = (proc, event)\<close> anotherinv456pzero exec inv_before step_rel1 step_rel2 step_rel3 step_rel4)
next
case False
then show ?thesis
using \<open>x = (proc, event)\<close> anotherinv456pnonzero inv_before step_rel2 step_rel4
by (metis exec fun_upd_other)
qed
qed
lemma pre_only_winners:
assumes \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs states\<close>
and \<open>finite procs\<close>
shows \<open>(\<forall>val. (states 0 = Value val \<longrightarrow> Some val \<in> set_of_potential_winners procs (find_vote events)))
\<or>(procs\<subseteq>{0})\<close>
using invs456 inv4_def by (metis assms)
lemma only_winners:
assumes \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs states\<close>
and \<open>states 0 = Value val\<close>
and \<open>finite procs\<close>
shows \<open>(Some val \<in> set_of_potential_winners procs (find_vote events))
\<or>(procs\<subseteq>{0})\<close>
using assms pre_only_winners by blast
lemma voting_done:
assumes \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs states\<close>
and \<open>states 0 = Value val\<close>
and \<open>finite procs\<close>
shows \<open>\<not>(not_every_vote_counted procs (find_vote events))\<close>
by (meson assms inv5_def invs456)
lemma acceptor_first:
assumes \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs states\<close>
and \<open>states p = Value val\<close>
shows \<open>states 0 = Value val\<close>
by (metis assms(1) assms(2) inv1_def inv2_def invariants)
theorem fairness:
assumes \<open>execute consensus_step (\<lambda>x. Nothing) procs events msgs states\<close>
and \<open>states proc = Value val\<close>
and \<open>finite procs\<close>
shows \<open>(\<not>(not_every_vote_counted procs (find_vote events))
\<and> Some val \<in> set_of_potential_winners procs (find_vote events))
\<or>(procs\<subseteq>{0})\<close>
using only_winners voting_done acceptor_first
by (metis assms)
end |
module Main
import Data.Vect
%default total
data Store : Type where
Create : (size : Nat) ->
(elems : Vect size String) ->
Store
{-
Splitting up the Commands for Processing from the strings that represent them
is what makes easier to isolate parsing and it's failure modes from the
processing.
-}
data Command = Add String
| Get Integer
| Search String
| Size
| Quit
size : Store -> Nat
size (Create size' elems') = size'
items : (store : Store) -> Vect (size store) String
items (Create size' elems') = elems'
add : (store : Store) -> String -> Store
add (Create size elems) newElem = Create _ (elems ++ [newElem])
getByIndex : (store : Store) -> (pos : Integer) -> String
getByIndex store pos = case integerToFin pos (size store) of
Nothing => "Out of Range"
Just pos' => index pos' (items store)
getIndexByElement : (store : Store) -> (el : String) -> String
getIndexByElement store el = case elemIndex el (items store) of
Just i => show (finToNat i)
Nothing => "?"
search : (store : Store) -> (query : String) -> (n : Nat ** Vect n String)
search store query = filter (isInfixOf query) (items store)
formatMatches : (store : Store) -> (results : (n : Nat ** Vect n String)) -> String
formatMatches store (_ ** []) = "No matches\n"
formatMatches store (n ** rs) = foldr (++) "" (map resultToString rs)
where
resultToString : String -> String
resultToString r = (getIndexByElement store r) ++ ": " ++ r ++ "\n"
run : Store -> Command -> Maybe (String, Store)
run store (Search query) = let results = search store query in
Just( (formatMatches store results), store )
run store (Add item) = Just ("ID: " ++ show (size store) ++ "\n", add store item)
run store (Get pos) = Just ("Result: " ++ show (getByIndex store pos) ++ "\n", store)
run store Size = Just (show (size store) ++ " item(s)\n", store)
run store Quit = Nothing
cleanInputs : String -> (String, String)
cleanInputs input = case (span (/= ' ') input) of
(cmd, args) => (toLower cmd, ltrim args)
parseCommand : (cmd : String) -> (args : String) -> Maybe Command
parseCommand "get" index = case all isDigit (unpack index) of
False => Nothing
True => Just (Get (cast index))
parseCommand "search" query = Just (Search query)
parseCommand "add" value = Just (Add value)
parseCommand "size" "" = Just Size
parseCommand "quit" "" = Just Quit
parseCommand _ _ = Nothing
parse : (input : String) -> Maybe Command
parse input = case cleanInputs input of
(cmd, args) => parseCommand cmd args
processInput : Store -> String -> Maybe (String, Store)
processInput store input
= case parse input of
Just validCommand => run store validCommand
Nothing => Just ("Invalid command\n", store)
partial main : IO ()
main = replWith (Create _ []) "Command > " processInput
|
Formal statement is: lemma filterlim_tendsto_neg_mult_at_bot: fixes c :: real assumes c: "(f \<longlongrightarrow> c) F" "c < 0" and g: "filterlim g at_top F" shows "LIM x F. f x * g x :> at_bot" Informal statement is: If $f$ tends to $c < 0$ and $g$ tends to infinity, then $f \cdot g$ tends to $-\infty$. |
Formal statement is: lemma LIMSEQ_ignore_initial_segment: "f \<longlonglongrightarrow> a \<Longrightarrow> (\<lambda>n. f (n + k)) \<longlonglongrightarrow> a" Informal statement is: If $f$ converges to $a$, then the sequence $f(n + k)$ also converges to $a$. |
module TaskDispatcher
using Dates, CSV, DataFrames, FileIO
#using JLD
include("PlatformTime.jl")
include("taskEnvironment.jl")
#include("LogFileIO.jl")
export get_time, turn_on_logging, turn_off_logging
end |
/**********************************************************\
Original Author: Richard Bateman (taxilian)
Created: Sept 17, 2009
License: Dual license model; choose one of two:
New BSD License
http://www.opensource.org/licenses/bsd-license.php
- or -
GNU Lesser General Public License, version 2.1
http://www.gnu.org/licenses/lgpl-2.1.html
Copyright 2009 Richard Bateman, Firebreath development team
\**********************************************************/
// FireBreathWin.cpp : Implementation of DLL Exports.
#include "win_common.h"
#include "global/resource.h"
#include "global/config.h"
#include "FireBreathWin_i.h"
#include "axmain.h"
#include "FBControl.h"
#include "axutil.h"
#include "PluginCore.h"
#include <boost/algorithm/string.hpp>
#include "precompiled_headers.h" // On windows, everything above this line in PCH
#include <Psapi.h>
using FB::ActiveX::isStaticInitialized;
using FB::ActiveX::flagStaticInitialized;
using FB::ActiveX::FbPerUserRegistration;
// Used to determine whether the DLL can be unloaded by OLE
STDAPI DllCanUnloadNow(void)
{
HRESULT hr = _AtlModule.DllCanUnloadNow();
if ((hr == S_OK || !FB::PluginCore::getActivePluginCount()) && isStaticInitialized()) {
// We had to change this so that if this function gets called (a sure sign that the browser
// would like to unload the DLL) and there are no active plugins it will call Deinitialize
// because some systems it never returned S_OK :-( Would love to know why and fix it correctly...
getFactoryInstance()->globalPluginDeinitialize();
FB::Log::stopLogging();
flagStaticInitialized(false);
}
return hr;
}
// Returns a class factory to create an object of the requested type
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv)
{
HRESULT hr = _AtlModule.DllGetClassObject(rclsid, riid, ppv);
if (SUCCEEDED(hr) && !isStaticInitialized()) {
FB::Log::initLogging();
FB::PluginCore::setPlatform("Windows", "IE");
getFactoryInstance()->globalPluginInitialize();
flagStaticInitialized(true);
}
return hr;
}
std::string getProcessName()
{
TCHAR szModName[MAX_PATH];
DWORD count;
HMODULE hm[1];
HANDLE proc = ::GetCurrentProcess();
BOOL success = ::EnumProcessModules(proc, hm, sizeof(HMODULE), &count);
if (::GetModuleFileNameW(hm[0], szModName, sizeof(szModName) / sizeof(TCHAR))) {
std::wstring fname(szModName);
return FB::wstring_to_utf8(fname);
} else {
return "";
}
}
extern HINSTANCE gInstance;
// DllRegisterServer - Adds entries to the system registry
STDAPI DllRegisterServer(void)
{
//Sleep(10000);
boost::scoped_ptr<FbPerUserRegistration> regHolder;
#ifndef FB_ATLREG_MACHINEWIDE
if (!boost::algorithm::ends_with(getProcessName(), "heat.exe")) {
regHolder.swap(boost::scoped_ptr<FbPerUserRegistration>(new FbPerUserRegistration(true)));
}
#endif
HRESULT hr = _AtlModule.DllRegisterServer();
if (!SUCCEEDED(hr))
hr = getFactoryInstance()->UpdateWindowsRegistry(true);
return hr;
}
// DllUnregisterServer - Removes entries from the system registry
STDAPI DllUnregisterServer(void)
{
boost::scoped_ptr<FbPerUserRegistration> regHolder;
#ifndef FB_ATLREG_MACHINEWIDE
if (!boost::algorithm::ends_with(getProcessName(), "heat.exe")) {
regHolder.swap(boost::scoped_ptr<FbPerUserRegistration>(new FbPerUserRegistration(true)));
}
#endif
HRESULT hr = _AtlModule.DllUnregisterServer();
if (!SUCCEEDED(hr))
hr = getFactoryInstance()->UpdateWindowsRegistry(false);
return hr;
}
// DllInstall - Adds/Removes entries to the system registry per user
// per machine.
STDAPI DllInstall(BOOL bInstall, LPCWSTR pszCmdLine)
{
HRESULT hr = E_FAIL;
static const wchar_t szUserSwitch[] = _T("user");
bool doPerUserRegistration = false;
if (pszCmdLine != NULL)
{
if (_wcsnicmp(pszCmdLine, szUserSwitch, _countof(szUserSwitch)) == 0)
{
doPerUserRegistration = true;
}
}
FbPerUserRegistration perUser(doPerUserRegistration);
if (bInstall)
{
hr = DllRegisterServer();
if (FAILED(hr))
{
DllUnregisterServer();
}
}
else
{
hr = DllUnregisterServer();
}
return hr;
}
|
using SafeTestsets
@safetestset "util" begin include("util.jl") end
@safetestset "tnmean" begin include("tnmean.jl") end
@safetestset "tnmom2" begin include("tnmom2.jl") end
@safetestset "tnmom1c" begin include("tnmom1c.jl") end
@safetestset "tnmom2c" begin include("tnmom2c.jl") end
@safetestset "tnvar" begin include("tnvar.jl") end
@safetestset "truncnorm" begin include("truncnorm.jl") end
@safetestset "rejection" begin include("rejection.jl") end
|
// Copyright (c) 2019-2021 LG Electronics, Inc.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
#include <string>
#include <set>
#include <utility>
#include <cmath>
#include <base/base.h>
#include <pbnjson.hpp>
#include <ResourceManagerClient.h>
#include <boost/regex.hpp>
#include "resourcefacilitator/requestor.h"
#include "log/log.h"
#define LOGTAG "ResourceRequestor"
#ifdef CMP_DEBUG_PRINT
#undef CMP_DEBUG_PRINT
#endif
#define CMP_DEBUG_PRINT CMP_INFO_PRINT
using namespace std;
using mrc::ResourceCalculator;
using namespace pbnjson;
using namespace cmp::base;
namespace cmp { namespace resource {
// FIXME : temp. set to 0 for request max
#define FAKE_WIDTH_MAX 0
#define FAKE_HEIGHT_MAX 0
#define FAKE_FRAMERATE_MAX 0
ResourceRequestor::ResourceRequestor(const std::string& appId,
const std::string& connectionId):
rc_(std::shared_ptr<MRC>(MRC::create())),
appId_(appId),
instanceId_(""),
cb_(nullptr),
planeIdCb_(nullptr),
acquiredResource_(""),
videoResData_{CMP_VIDEO_CODEC_NONE,CMP_VIDEO_CODEC_NONE,CMP_VIDEO_CODEC_NONE,0,0,0,0,0,0,0},
allowPolicy_(true) {
try {
if (connectionId.empty()) {
umsRMC_ = make_shared<uMediaServer::ResourceManagerClient> ();
CMP_DEBUG_PRINT("ResourceRequestor creation done");
umsRMC_->registerPipeline("media", appId_); // only rmc case
connectionId_ = umsRMC_->getConnectionID(); // after registerPipeline
}
else {
umsRMC_ = make_shared<uMediaServer::ResourceManagerClient> (connectionId);
connectionId_ = connectionId;
}
}
catch (const std::exception &e) {
CMP_DEBUG_PRINT("Failed to create ResourceRequestor [%s]", e.what());
exit(0);
}
if (connectionId_.empty()) {
CMPASSERT(0);
}
umsRMC_->registerPolicyActionHandler(
std::bind(&ResourceRequestor::policyActionHandler,
this,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3,
std::placeholders::_4,
std::placeholders::_5));
CMP_DEBUG_PRINT("ResourceRequestor creation done");
}
ResourceRequestor::~ResourceRequestor() {
if (!acquiredResource_.empty()) {
umsRMC_->release(acquiredResource_);
acquiredResource_ = "";
}
}
bool ResourceRequestor::acquireResources(PortResource_t& resourceMMap,
const cmp::base::source_info_t &sourceInfo,
const std::string &display_mode,
const int32_t display_path) {
mrc::ResourceListOptions finalOptions;
if (!setSourceInfo(sourceInfo)) {
CMP_DEBUG_PRINT("Failed to set source info!");
return false;
}
mrc::ResourceListOptions VResource = calcVdecResources();
if (!VResource.empty()) {
mrc::concatResourceListOptions(&finalOptions, &VResource);
CMP_DEBUG_PRINT("VResource size:%lu, %s, %d", VResource.size(),
VResource[0].front().type.c_str(),
VResource[0].front().quantity);
}
mrc::ResourceListOptions VEncResource = calcVencResources();
if (!VEncResource.empty()) {
mrc::concatResourceListOptions(&finalOptions, &VEncResource);
CMP_DEBUG_PRINT("VResource size:%lu, %s, %d", VEncResource.size(),
VEncResource[0].front().type.c_str(),
VEncResource[0].front().quantity);
}
mrc::ResourceListOptions DisplayResource = calcDisplayResource(display_mode);
if (!DisplayResource.empty()) {
mrc::concatResourceListOptions(&finalOptions, &DisplayResource);
CMP_DEBUG_PRINT("DisplayResource size:%lu, %s, %d", DisplayResource.size(),
DisplayResource[0].front().type.c_str(),
DisplayResource[0].front().quantity);
}
JSchemaFragment input_schema("{}");
JGenerator serializer(nullptr);
string payload;
string response;
JValue objArray = pbnjson::Array();
for (auto option : finalOptions) {
for (auto it : option) {
JValue obj = pbnjson::Object();
obj.put("resource", it.type + (it.type == "DISP" ? to_string(display_path) : ""));
obj.put("qty", it.quantity);
CMP_DEBUG_PRINT("calculator return : %s, %d", it.type.c_str(), it.quantity);
objArray << obj;
}
}
if (!serializer.toString(objArray, input_schema, payload)) {
CMP_DEBUG_PRINT("[%s], fail to serializer to string", __func__);
return false;
}
CMP_DEBUG_PRINT("send acquire to uMediaServer payload:%s", payload.c_str());
if (!umsRMC_->acquire(payload, response)) {
CMP_DEBUG_PRINT("fail to acquire!!! response : %s", response.c_str());
return false;
}
CMP_DEBUG_PRINT("acquire response:%s", response.c_str());
try {
parsePortInformation(response, resourceMMap);
parseResources(response, acquiredResource_);
} catch (const std::runtime_error & err) {
CMP_DEBUG_PRINT("[%s:%d] err=%s, response:%s",
__func__, __LINE__, err.what(), response.c_str());
return false;
}
CMP_DEBUG_PRINT("acquired Resource : %s", acquiredResource_.c_str());
return true;
}
mrc::ResourceListOptions ResourceRequestor::calcVdecResources() {
mrc::ResourceListOptions VResource;
CMP_DEBUG_PRINT("Codec type:%d",videoResData_.vdecode);
if (videoResData_.vdecode != CMP_VIDEO_CODEC_NONE) {
VResource = rc_->calcVdecResourceOptions((MRC::VideoCodecs)translateVideoCodec(videoResData_.vdecode),
videoResData_.width,
videoResData_.height,
videoResData_.frameRate,
(MRC::ScanType)translateScanType(videoResData_.escanType),
(MRC::_3DType)translate3DType(videoResData_.e3DType));
}
return VResource;
}
mrc::ResourceListOptions ResourceRequestor::calcVencResources() {
mrc::ResourceListOptions VResource;
CMP_DEBUG_PRINT("Codec type:%d",videoResData_.vencode);
if (videoResData_.vencode != CMP_VIDEO_CODEC_NONE) {
VResource = rc_->calcVencResourceOptions((MRC::VideoCodecs)translateVideoCodec(videoResData_.vencode),
videoResData_.width,
videoResData_.height,
videoResData_.frameRate
);
}
CMP_DEBUG_PRINT("Codec type:%d",videoResData_.vencode);
return VResource;
}
mrc::ResourceListOptions ResourceRequestor::calcDisplayResource(const std::string &display_mode) {
mrc::ResourceListOptions DisplayResource;
if (videoResData_.vcodec != CMP_VIDEO_CODEC_NONE) {
/* need to change display_mode type from string to enum */
if (display_mode.compare("PunchThrough") == 0) {
DisplayResource = rc_->calcDisplayPlaneResourceOptions(mrc::ResourceCalculator::RenderMode::kModePunchThrough);
} else if (display_mode.compare("Textured") == 0) {
DisplayResource = rc_->calcDisplayPlaneResourceOptions(mrc::ResourceCalculator::RenderMode::kModeTexture);
} else {
CMP_DEBUG_PRINT("Wrong display mode: %s", display_mode.c_str());
}
}
return DisplayResource;
}
bool ResourceRequestor::releaseResource() {
if (acquiredResource_.empty()) {
CMP_DEBUG_PRINT("[%s], resource already empty", __func__);
return true;
}
CMP_DEBUG_PRINT("send release to uMediaServer. resource : %s",
acquiredResource_.c_str());
if (!umsRMC_->release(acquiredResource_)) {
CMP_DEBUG_PRINT("release error : %s", acquiredResource_.c_str());
return false;
}
acquiredResource_ = "";
return true;
}
bool ResourceRequestor::notifyForeground() const {
return umsRMC_->notifyForeground();
}
bool ResourceRequestor::notifyBackground() const {
return umsRMC_->notifyBackground();
}
bool ResourceRequestor::notifyActivity() const {
return umsRMC_->notifyActivity();
}
bool ResourceRequestor::notifyPipelineStatus(const std::string& status) const {
umsRMC_->notifyPipelineStatus(status);
return true;
}
void ResourceRequestor::allowPolicyAction(const bool allow) {
allowPolicy_ = allow;
}
bool ResourceRequestor::policyActionHandler(const char *action,
const char *resources,
const char *requestorType,
const char *requestorName,
const char *connectionId) {
CMP_DEBUG_PRINT("action:%s, resources:%s, type:%s, name:%s, id:%s",
action, resources, requestorType, requestorName, connectionId);
if (allowPolicy_) {
if (nullptr != cb_) {
cb_();
}
if (!umsRMC_->release(acquiredResource_)) {
CMP_DEBUG_PRINT("release error : %s", acquiredResource_.c_str());
return false;
}
}
return allowPolicy_;
}
bool ResourceRequestor::parsePortInformation(const std::string& payload,
PortResource_t& resourceMMap) {
pbnjson::JDomParser parser;
pbnjson::JSchemaFragment input_schema("{}");
if (!parser.parse(payload, input_schema)) {
throw std::runtime_error(" : payload parsing failure");
}
pbnjson::JValue parsed = parser.getDom();
if (!parsed.hasKey("resources")) {
throw std::runtime_error("payload must have \"resources key\"");
}
int res_arraysize = parsed["resources"].arraySize();
for (int i=0; i < res_arraysize; ++i) {
std::string resourceName = parsed["resources"][i]["resource"].asString();
int32_t value = parsed["resources"][i]["index"].asNumber<int32_t>();
resourceMMap.insert(std::make_pair(resourceName, value));
}
for (auto& it : resourceMMap) {
CMP_DEBUG_PRINT("port Resource - %s, : [%d] ", it.first.c_str(), it.second);
}
return true;
}
bool ResourceRequestor::parseResources(const std::string& payload,
std::string& resources) {
pbnjson::JDomParser parser;
pbnjson::JSchemaFragment input_schema("{}");
pbnjson::JGenerator serializer(nullptr);
if (!parser.parse(payload, input_schema)) {
throw std::runtime_error(" : payload parsing failure");
}
pbnjson::JValue parsed = parser.getDom();
if (!parsed.hasKey("resources")) {
throw std::runtime_error("payload must have \"resources key\"");
}
pbnjson::JValue objArray = pbnjson::Array();
for (int i=0; i < parsed["resources"].arraySize(); ++i) {
pbnjson::JValue obj = pbnjson::Object();
obj.put("resource", parsed["resources"][i]["resource"].asString());
obj.put("index", parsed["resources"][i]["index"].asNumber<int32_t>());
objArray << obj;
}
if (!serializer.toString(objArray, input_schema, resources)) {
throw std::runtime_error("failed to serializer toString");
}
return true;
}
int ResourceRequestor::translateVideoCodec(const CMP_VIDEO_CODEC vcodec) const {
MRC::VideoCodec ev = MRC::kVideoEtc;
switch (vcodec) {
case CMP_VIDEO_CODEC_NONE:
ev = MRC::kVideoEtc; break;
case CMP_VIDEO_CODEC_H264:
ev = MRC::kVideoH264; break;
case CMP_VIDEO_CODEC_H265:
ev = MRC::kVideoH265; break;
case CMP_VIDEO_CODEC_MPEG2:
ev = MRC::kVideoMPEG; break;
case CMP_VIDEO_CODEC_MPEG4:
ev = MRC::kVideoMPEG4; break;
case CMP_VIDEO_CODEC_VP8:
ev = MRC::kVideoVP8; break;
case CMP_VIDEO_CODEC_VP9:
ev = MRC::kVideoVP9; break;
case CMP_VIDEO_CODEC_MJPEG:
ev = MRC::kVideoMJPEG; break;
default:
ev = MRC::kVideoH264; break;
}
CMP_DEBUG_PRINT("vcodec[%d] => ev[%d]", vcodec, ev);
return static_cast<int>(ev);
}
int ResourceRequestor::translateScanType(const int escanType) const {
MRC::ScanType scan = MRC::kScanProgressive;
switch (escanType) {
default:
break;
}
return static_cast<int>(scan);
}
int ResourceRequestor::translate3DType(const int e3DType) const {
MRC::_3DType my3d = MRC::k3DNone;
switch (e3DType) {
default:
my3d = MRC::k3DNone;
break;
}
return static_cast<int>(my3d);
}
bool ResourceRequestor::setSourceInfo(
const cmp::base::source_info_t &sourceInfo) {
if (sourceInfo.video_streams.empty()){
CMP_DEBUG_PRINT("Video/Audio streams are empty!");
return false;
}
cmp::base::video_info_t video_stream_info = sourceInfo.video_streams.front();
videoResData_.width = video_stream_info.width;
videoResData_.height = video_stream_info.height;
videoResData_.vencode = (CMP_VIDEO_CODEC)video_stream_info.encode;
videoResData_.vdecode = (CMP_VIDEO_CODEC)video_stream_info.decode;
videoResData_.frameRate =
std::round(static_cast<float>(video_stream_info.frame_rate.num) /
static_cast<float>(video_stream_info.frame_rate.den));
videoResData_.escanType = 0;
return true;
}
void ResourceRequestor::planeIdHandler(int32_t planePortIdx) {
CMP_DEBUG_PRINT("planePortIndex = %d", planePortIdx);
if (nullptr != planeIdCb_) {
bool res = planeIdCb_(planePortIdx);
CMP_DEBUG_PRINT("PlanePort[%d] register : %s",
planePortIdx, res ? "success!" : "fail!");
}
}
void ResourceRequestor::setAppId(std::string id) {
appId_ = id;
}
int32_t ResourceRequestor::getDisplayPath() {
return umsRMC_->getDisplayID();
}
} // namespace resource
} // namespace cmp
|
lemma lmeasurable_closure: "bounded S \<Longrightarrow> closure S \<in> lmeasurable" |
[GOAL]
L : Language
M : Type u_1
s : Setoid M
ps : Prestructure L s
n : ℕ
f : Functions L n
x : Fin n → M
⊢ (funMap f fun i => Quotient.mk s (x i)) = Quotient.mk s (funMap f x)
[PROOFSTEP]
change Quotient.map (@funMap L M ps.toStructure n f) Prestructure.fun_equiv (Quotient.finChoice _) = _
[GOAL]
L : Language
M : Type u_1
s : Setoid M
ps : Prestructure L s
n : ℕ
f : Functions L n
x : Fin n → M
⊢ Quotient.map (funMap f) (_ : ∀ (x y : Fin n → M), x ≈ y → funMap f x ≈ funMap f y)
(Quotient.finChoice fun i => Quotient.mk s (x i)) =
Quotient.mk s (funMap f x)
[PROOFSTEP]
rw [Quotient.finChoice_eq, Quotient.map_mk]
[GOAL]
L : Language
M : Type u_1
s : Setoid M
ps : Prestructure L s
n : ℕ
r : Relations L n
x : Fin n → M
⊢ (RelMap r fun i => Quotient.mk s (x i)) ↔ RelMap r x
[PROOFSTEP]
change Quotient.lift (@RelMap L M ps.toStructure n r) Prestructure.rel_equiv (Quotient.finChoice _) ↔ _
[GOAL]
L : Language
M : Type u_1
s : Setoid M
ps : Prestructure L s
n : ℕ
r : Relations L n
x : Fin n → M
⊢ Quotient.lift (RelMap r) (_ : ∀ (x y : Fin n → M), x ≈ y → RelMap r x = RelMap r y)
(Quotient.finChoice fun i => Quotient.mk s (x i)) ↔
RelMap r x
[PROOFSTEP]
rw [Quotient.finChoice_eq, Quotient.lift_mk]
[GOAL]
L : Language
M : Type u_1
s : Setoid M
ps : Prestructure L s
β : Type u_2
t : Term L β
x : β → M
⊢ realize (fun i => Quotient.mk s (x i)) t = Quotient.mk s (realize x t)
[PROOFSTEP]
induction' t with _ _ _ _ ih
[GOAL]
case var
L : Language
M : Type u_1
s : Setoid M
ps : Prestructure L s
β : Type u_2
x : β → M
_a✝ : β
⊢ realize (fun i => Quotient.mk s (x i)) (var _a✝) = Quotient.mk s (realize x (var _a✝))
[PROOFSTEP]
rfl
[GOAL]
case func
L : Language
M : Type u_1
s : Setoid M
ps : Prestructure L s
β : Type u_2
x : β → M
l✝ : ℕ
_f✝ : Functions L l✝
_ts✝ : Fin l✝ → Term L β
ih : ∀ (a : Fin l✝), realize (fun i => Quotient.mk s (x i)) (_ts✝ a) = Quotient.mk s (realize x (_ts✝ a))
⊢ realize (fun i => Quotient.mk s (x i)) (func _f✝ _ts✝) = Quotient.mk s (realize x (func _f✝ _ts✝))
[PROOFSTEP]
simp only [ih, funMap_quotient_mk', Term.realize]
|
/-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad, Mario Carneiro, Simon Hudon
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.fin2
import Mathlib.logic.function.basic
import Mathlib.tactic.basic
import Mathlib.PostPort
universes u_1 u u_2 u_3 u_4
namespace Mathlib
/-!
# Tuples of types, and their categorical structure.
## Features
* `typevec n` - n-tuples of types
* `α ⟹ β` - n-tuples of maps
* `f ⊚ g` - composition
Also, support functions for operating with n-tuples of types, such as:
* `append1 α β` - append type `β` to n-tuple `α` to obtain an (n+1)-tuple
* `drop α` - drops the last element of an (n+1)-tuple
* `last α` - returns the last element of an (n+1)-tuple
* `append_fun f g` - appends a function g to an n-tuple of functions
* `drop_fun f` - drops the last function from an n+1-tuple
* `last_fun f` - returns the last function of a tuple.
Since e.g. `append1 α.drop α.last` is propositionally equal to `α` but not definitionally equal
to it, we need support functions and lemmas to mediate between constructions.
-/
/--
n-tuples of types, as a category
-/
def typevec (n : ℕ) :=
fin2 n → Type u_1
protected instance typevec.inhabited {n : ℕ} : Inhabited (typevec n) :=
{ default := fun (_x : fin2 n) => PUnit }
namespace typevec
/-- arrow in the category of `typevec` -/
def arrow {n : ℕ} (α : typevec n) (β : typevec n) :=
(i : fin2 n) → α i → β i
protected instance arrow.inhabited {n : ℕ} (α : typevec n) (β : typevec n) [(i : fin2 n) → Inhabited (β i)] : Inhabited (arrow α β) :=
{ default := fun (_x : fin2 n) (_x_1 : α _x) => Inhabited.default }
/-- identity of arrow composition -/
def id {n : ℕ} {α : typevec n} : arrow α α :=
fun (i : fin2 n) (x : α i) => x
/-- arrow composition in the category of `typevec` -/
def comp {n : ℕ} {α : typevec n} {β : typevec n} {γ : typevec n} (g : arrow β γ) (f : arrow α β) : arrow α γ :=
fun (i : fin2 n) (x : α i) => g i (f i x)
@[simp] theorem id_comp {n : ℕ} {α : typevec n} {β : typevec n} (f : arrow α β) : comp id f = f :=
rfl
@[simp] theorem comp_id {n : ℕ} {α : typevec n} {β : typevec n} (f : arrow α β) : comp f id = f :=
rfl
theorem comp_assoc {n : ℕ} {α : typevec n} {β : typevec n} {γ : typevec n} {δ : typevec n} (h : arrow γ δ) (g : arrow β γ) (f : arrow α β) : comp (comp h g) f = comp h (comp g f) :=
rfl
/--
Support for extending a typevec by one element.
-/
def append1 {n : ℕ} (α : typevec n) (β : Type u_1) : typevec (n + 1) :=
sorry
infixl:67 " ::: " => Mathlib.typevec.append1
/-- retain only a `n-length` prefix of the argument -/
def drop {n : ℕ} (α : typevec (n + 1)) : typevec n :=
fun (i : fin2 n) => α (fin2.fs i)
/-- take the last value of a `(n+1)-length` vector -/
def last {n : ℕ} (α : typevec (n + 1)) :=
α fin2.fz
protected instance last.inhabited {n : ℕ} (α : typevec (n + 1)) [Inhabited (α fin2.fz)] : Inhabited (last α) :=
{ default := Inhabited.default }
theorem drop_append1 {n : ℕ} {α : typevec n} {β : Type u_1} {i : fin2 n} : drop (α ::: β) i = α i :=
rfl
@[simp] theorem drop_append1' {n : ℕ} {α : typevec n} {β : Type u_1} : drop (α ::: β) = α :=
funext fun (x : fin2 n) => drop_append1
theorem last_append1 {n : ℕ} {α : typevec n} {β : Type u_1} : last (α ::: β) = β :=
rfl
@[simp] theorem append1_drop_last {n : ℕ} (α : typevec (n + 1)) : drop α ::: last α = α := sorry
/-- cases on `(n+1)-length` vectors -/
def append1_cases {n : ℕ} {C : typevec (n + 1) → Sort u} (H : (α : typevec n) → (β : Type u_1) → C (α ::: β)) (γ : typevec (n + 1)) : C γ :=
eq.mpr sorry (H (drop γ) (last γ))
@[simp] theorem append1_cases_append1 {n : ℕ} {C : typevec (n + 1) → Sort u} (H : (α : typevec n) → (β : Type u_1) → C (α ::: β)) (α : typevec n) (β : Type u_1) : append1_cases H (α ::: β) = H α β :=
rfl
/-- append an arrow and a function for arbitrary source and target
type vectors -/
def split_fun {n : ℕ} {α : typevec (n + 1)} {α' : typevec (n + 1)} (f : arrow (drop α) (drop α')) (g : last α → last α') : arrow α α' :=
sorry
/-- append an arrow and a function as well as their respective source
and target types / typevecs -/
def append_fun {n : ℕ} {α : typevec n} {α' : typevec n} {β : Type u_1} {β' : Type u_2} (f : arrow α α') (g : β → β') : arrow (α ::: β) (α' ::: β') :=
split_fun f g
infixl:67 " ::: " => Mathlib.typevec.append_fun
/-- split off the prefix of an arrow -/
def drop_fun {n : ℕ} {α : typevec (n + 1)} {β : typevec (n + 1)} (f : arrow α β) : arrow (drop α) (drop β) :=
fun (i : fin2 n) => f (fin2.fs i)
/-- split off the last function of an arrow -/
def last_fun {n : ℕ} {α : typevec (n + 1)} {β : typevec (n + 1)} (f : arrow α β) : last α → last β :=
f fin2.fz
/-- arrow in the category of `0-length` vectors -/
def nil_fun {α : typevec 0} {β : typevec 0} : arrow α β :=
fun (i : fin2 0) => fin2.elim0 i
theorem eq_of_drop_last_eq {n : ℕ} {α : typevec (n + 1)} {β : typevec (n + 1)} {f : arrow α β} {g : arrow α β} (h₀ : drop_fun f = drop_fun g) (h₁ : last_fun f = last_fun g) : f = g := sorry
@[simp] theorem drop_fun_split_fun {n : ℕ} {α : typevec (n + 1)} {α' : typevec (n + 1)} (f : arrow (drop α) (drop α')) (g : last α → last α') : drop_fun (split_fun f g) = f :=
rfl
/-- turn an equality into an arrow -/
def arrow.mp {n : ℕ} {α : typevec n} {β : typevec n} (h : α = β) : arrow α β :=
sorry
/-- turn an equality into an arrow, with reverse direction -/
def arrow.mpr {n : ℕ} {α : typevec n} {β : typevec n} (h : α = β) : arrow β α :=
sorry
/-- decompose a vector into its prefix appended with its last element -/
def to_append1_drop_last {n : ℕ} {α : typevec (n + 1)} : arrow α (drop α ::: last α) :=
arrow.mpr (append1_drop_last α)
/-- stitch two bits of a vector back together -/
def from_append1_drop_last {n : ℕ} {α : typevec (n + 1)} : arrow (drop α ::: last α) α :=
arrow.mp (append1_drop_last α)
@[simp] theorem last_fun_split_fun {n : ℕ} {α : typevec (n + 1)} {α' : typevec (n + 1)} (f : arrow (drop α) (drop α')) (g : last α → last α') : last_fun (split_fun f g) = g :=
rfl
@[simp] theorem drop_fun_append_fun {n : ℕ} {α : typevec n} {α' : typevec n} {β : Type u_1} {β' : Type u_2} (f : arrow α α') (g : β → β') : drop_fun (f ::: g) = f :=
rfl
@[simp] theorem last_fun_append_fun {n : ℕ} {α : typevec n} {α' : typevec n} {β : Type u_1} {β' : Type u_2} (f : arrow α α') (g : β → β') : last_fun (f ::: g) = g :=
rfl
theorem split_drop_fun_last_fun {n : ℕ} {α : typevec (n + 1)} {α' : typevec (n + 1)} (f : arrow α α') : split_fun (drop_fun f) (last_fun f) = f :=
eq_of_drop_last_eq rfl rfl
theorem split_fun_inj {n : ℕ} {α : typevec (n + 1)} {α' : typevec (n + 1)} {f : arrow (drop α) (drop α')} {f' : arrow (drop α) (drop α')} {g : last α → last α'} {g' : last α → last α'} (H : split_fun f g = split_fun f' g') : f = f' ∧ g = g' := sorry
theorem append_fun_inj {n : ℕ} {α : typevec n} {α' : typevec n} {β : Type u_1} {β' : Type u_2} {f : arrow α α'} {f' : arrow α α'} {g : β → β'} {g' : β → β'} : f ::: g = f' ::: g' → f = f' ∧ g = g' :=
split_fun_inj
theorem split_fun_comp {n : ℕ} {α₀ : typevec (n + 1)} {α₁ : typevec (n + 1)} {α₂ : typevec (n + 1)} (f₀ : arrow (drop α₀) (drop α₁)) (f₁ : arrow (drop α₁) (drop α₂)) (g₀ : last α₀ → last α₁) (g₁ : last α₁ → last α₂) : split_fun (comp f₁ f₀) (g₁ ∘ g₀) = comp (split_fun f₁ g₁) (split_fun f₀ g₀) :=
eq_of_drop_last_eq rfl rfl
theorem append_fun_comp_split_fun {n : ℕ} {α : typevec n} {γ : typevec n} {β : Type u_1} {δ : Type u_2} {ε : typevec (n + 1)} (f₀ : arrow (drop ε) α) (f₁ : arrow α γ) (g₀ : last ε → β) (g₁ : β → δ) : comp (f₁ ::: g₁) (split_fun f₀ g₀) = split_fun (comp f₁ f₀) (g₁ ∘ g₀) :=
Eq.symm (split_fun_comp f₀ f₁ g₀ g₁)
theorem append_fun_comp {n : ℕ} {α₀ : typevec n} {α₁ : typevec n} {α₂ : typevec n} {β₀ : Type u_1} {β₁ : Type u_2} {β₂ : Type u_3} (f₀ : arrow α₀ α₁) (f₁ : arrow α₁ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : comp f₁ f₀ ::: g₁ ∘ g₀ = comp (f₁ ::: g₁) (f₀ ::: g₀) :=
eq_of_drop_last_eq rfl rfl
theorem append_fun_comp' {n : ℕ} {α₀ : typevec n} {α₁ : typevec n} {α₂ : typevec n} {β₀ : Type u_1} {β₁ : Type u_2} {β₂ : Type u_3} (f₀ : arrow α₀ α₁) (f₁ : arrow α₁ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : comp (f₁ ::: g₁) (f₀ ::: g₀) = comp f₁ f₀ ::: g₁ ∘ g₀ :=
eq_of_drop_last_eq rfl rfl
theorem nil_fun_comp {α₀ : typevec 0} (f₀ : arrow α₀ fin2.elim0) : comp nil_fun f₀ = f₀ :=
funext fun (x : fin2 0) => fin2.elim0 x
theorem append_fun_comp_id {n : ℕ} {α : typevec n} {β₀ : Type u_1} {β₁ : Type u_1} {β₂ : Type u_1} (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : id ::: g₁ ∘ g₀ = comp (id ::: g₁) (id ::: g₀) :=
eq_of_drop_last_eq rfl rfl
@[simp] theorem drop_fun_comp {n : ℕ} {α₀ : typevec (n + 1)} {α₁ : typevec (n + 1)} {α₂ : typevec (n + 1)} (f₀ : arrow α₀ α₁) (f₁ : arrow α₁ α₂) : drop_fun (comp f₁ f₀) = comp (drop_fun f₁) (drop_fun f₀) :=
rfl
@[simp] theorem last_fun_comp {n : ℕ} {α₀ : typevec (n + 1)} {α₁ : typevec (n + 1)} {α₂ : typevec (n + 1)} (f₀ : arrow α₀ α₁) (f₁ : arrow α₁ α₂) : last_fun (comp f₁ f₀) = last_fun f₁ ∘ last_fun f₀ :=
rfl
theorem append_fun_aux {n : ℕ} {α : typevec n} {α' : typevec n} {β : Type u_1} {β' : Type u_2} (f : arrow (α ::: β) (α' ::: β')) : drop_fun f ::: last_fun f = f :=
eq_of_drop_last_eq rfl rfl
theorem append_fun_id_id {n : ℕ} {α : typevec n} {β : Type u_1} : id ::: id = id :=
eq_of_drop_last_eq rfl rfl
protected instance subsingleton0 : subsingleton (typevec 0) :=
subsingleton.intro fun (a b : typevec 0) => funext fun (a_1 : fin2 0) => fin2.elim0 a_1
/-- cases distinction for 0-length type vector -/
protected def cases_nil {β : typevec 0 → Sort u_2} (f : β fin2.elim0) (v : typevec 0) : β v :=
cast sorry f
/-- cases distinction for (n+1)-length type vector -/
protected def cases_cons (n : ℕ) {β : typevec (n + 1) → Sort u_2} (f : (t : Type u_1) → (v : typevec n) → β (v ::: t)) (v : typevec (n + 1)) : β v :=
cast sorry (f (last v) (drop v))
protected theorem cases_nil_append1 {β : typevec 0 → Sort u_2} (f : β fin2.elim0) : typevec.cases_nil f fin2.elim0 = f :=
rfl
protected theorem cases_cons_append1 (n : ℕ) {β : typevec (n + 1) → Sort u_2} (f : (t : Type u_1) → (v : typevec n) → β (v ::: t)) (v : typevec n) (α : Type u_1) : typevec.cases_cons n f (v ::: α) = f α v :=
rfl
/-- cases distinction for an arrow in the category of 0-length type vectors -/
def typevec_cases_nil₃ {β : (v : typevec 0) → (v' : typevec 0) → arrow v v' → Sort u_3} (f : β fin2.elim0 fin2.elim0 nil_fun) (v : typevec 0) (v' : typevec 0) (fs : arrow v v') : β v v' fs :=
cast sorry f
/-- cases distinction for an arrow in the category of (n+1)-length type vectors -/
def typevec_cases_cons₃ (n : ℕ) {β : (v : typevec (n + 1)) → (v' : typevec (n + 1)) → arrow v v' → Sort u_3} (F : (t : Type u_1) →
(t' : Type u_2) →
(f : t → t') → (v : typevec n) → (v' : typevec n) → (fs : arrow v v') → β (v ::: t) (v' ::: t') (fs ::: f)) (v : typevec (n + 1)) (v' : typevec (n + 1)) (fs : arrow v v') : β v v' fs :=
eq.mpr sorry
(eq.mpr sorry
fun (fs : arrow (drop v ::: last v) (drop v' ::: last v')) =>
eq.mpr sorry (F (last v) (last v') (last_fun fs) (drop v) (drop v') (drop_fun fs)))
/-- specialized cases distinction for an arrow in the category of 0-length type vectors -/
def typevec_cases_nil₂ {β : arrow fin2.elim0 fin2.elim0 → Sort u_3} (f : β nil_fun) : (f : arrow fin2.elim0 fin2.elim0) → β f :=
fun (g : arrow fin2.elim0 fin2.elim0) => eq.mpr sorry f
/-- specialized cases distinction for an arrow in the category of (n+1)-length type vectors -/
def typevec_cases_cons₂ (n : ℕ) (t : Type u_1) (t' : Type u_2) (v : typevec n) (v' : typevec n) {β : arrow (v ::: t) (v' ::: t') → Sort u_3} (F : (f : t → t') → (fs : arrow v v') → β (fs ::: f)) (fs : arrow (v ::: t) (v' ::: t')) : β fs :=
eq.mpr sorry (F (last_fun fs) (drop_fun fs))
theorem typevec_cases_nil₂_append_fun {β : arrow fin2.elim0 fin2.elim0 → Sort u_3} (f : β nil_fun) : typevec_cases_nil₂ f nil_fun = f :=
rfl
theorem typevec_cases_cons₂_append_fun (n : ℕ) (t : Type u_1) (t' : Type u_2) (v : typevec n) (v' : typevec n) {β : arrow (v ::: t) (v' ::: t') → Sort u_3} (F : (f : t → t') → (fs : arrow v v') → β (fs ::: f)) (f : t → t') (fs : arrow v v') : typevec_cases_cons₂ n t t' v v' F (fs ::: f) = F f fs :=
rfl
/- for lifting predicates and relations -/
/-- `pred_last α p x` predicates `p` of the last element of `x : α.append1 β`. -/
def pred_last {n : ℕ} (α : typevec n) {β : Type u_1} (p : β → Prop) {i : fin2 (n + 1)} : append1 α β i → Prop :=
sorry
/-- `rel_last α r x y` says that `p` the last elements of `x y : α.append1 β` are related by `r` and
all the other elements are equal. -/
def rel_last {n : ℕ} (α : typevec n) {β : Type u_1} {γ : Type u_1} (r : β → γ → Prop) {i : fin2 (n + 1)} : append1 α β i → append1 α γ i → Prop :=
sorry
/-- `repeat n t` is a `n-length` type vector that contains `n` occurences of `t` -/
def repeat (n : ℕ) (t : Type u_1) : typevec n :=
sorry
/-- `prod α β` is the pointwise product of the components of `α` and `β` -/
def prod {n : ℕ} (α : typevec n) (β : typevec n) : typevec n :=
sorry
/-- `const x α` is an arrow that ignores its source and constructs a `typevec` that
contains nothing but `x` -/
protected def const {β : Type u_1} (x : β) {n : ℕ} (α : typevec n) : arrow α (repeat n β) :=
sorry
/-- vector of equality on a product of vectors -/
def repeat_eq {n : ℕ} (α : typevec n) : arrow (prod α α) (repeat n Prop) :=
sorry
theorem const_append1 {β : Type u_1} {γ : Type u_2} (x : γ) {n : ℕ} (α : typevec n) : typevec.const x (α ::: β) = typevec.const x α ::: fun (_x : β) => x := sorry
theorem eq_nil_fun {α : typevec 0} {β : typevec 0} (f : arrow α β) : f = nil_fun := sorry
theorem id_eq_nil_fun {α : typevec 0} : id = nil_fun := sorry
theorem const_nil {β : Type u_1} (x : β) (α : typevec 0) : typevec.const x α = nil_fun := sorry
theorem repeat_eq_append1 {β : Type u_1} {n : ℕ} (α : typevec n) : repeat_eq (α ::: β) = split_fun (repeat_eq α) (function.uncurry Eq) := sorry
theorem repeat_eq_nil (α : typevec 0) : repeat_eq α = nil_fun := sorry
/-- predicate on a type vector to constrain only the last object -/
def pred_last' {n : ℕ} (α : typevec n) {β : Type u_1} (p : β → Prop) : arrow (α ::: β) (repeat (n + 1) Prop) :=
split_fun (typevec.const True α) p
/-- predicate on the product of two type vectors to constrain only their last object -/
def rel_last' {n : ℕ} (α : typevec n) {β : Type u_1} (p : β → β → Prop) : arrow (prod (α ::: β) (α ::: β)) (repeat (n + 1) Prop) :=
split_fun (repeat_eq α) (function.uncurry p)
/-- given `F : typevec.{u} (n+1) → Type u`, `curry F : Type u → typevec.{u} → Type u`,
i.e. its first argument can be fed in separately from the rest of the vector of arguments -/
def curry {n : ℕ} (F : typevec (n + 1) → Type u_1) (α : Type u) (β : typevec n) :=
F (β ::: α)
protected instance curry.inhabited {n : ℕ} (F : typevec (n + 1) → Type u_1) (α : Type u) (β : typevec n) [I : Inhabited (F (β ::: α))] : Inhabited (curry F α β) :=
I
/-- arrow to remove one element of a `repeat` vector -/
def drop_repeat (α : Type u_1) {n : ℕ} : arrow (drop (repeat (Nat.succ n) α)) (repeat n α) :=
sorry
/-- projection for a repeat vector -/
def of_repeat {α : Type u_1} {n : ℕ} {i : fin2 n} : repeat n α i → α :=
sorry
theorem const_iff_true {n : ℕ} {α : typevec n} {i : fin2 n} {x : α i} {p : Prop} : of_repeat (typevec.const p α i x) ↔ p := sorry
-- variables {F : typevec.{u} n → Type*} [mvfunctor F]
/-- left projection of a `prod` vector -/
def prod.fst {n : ℕ} {α : typevec n} {β : typevec n} : arrow (prod α β) α :=
sorry
/-- right projection of a `prod` vector -/
def prod.snd {n : ℕ} {α : typevec n} {β : typevec n} : arrow (prod α β) β :=
sorry
/-- introduce a product where both components are the same -/
def prod.diag {n : ℕ} {α : typevec n} : arrow α (prod α α) :=
sorry
/-- constructor for `prod` -/
def prod.mk {n : ℕ} {α : typevec n} {β : typevec n} (i : fin2 n) : α i → β i → prod α β i :=
sorry
@[simp] theorem prod_fst_mk {n : ℕ} {α : typevec n} {β : typevec n} (i : fin2 n) (a : α i) (b : β i) : prod.fst i (prod.mk i a b) = a := sorry
@[simp] theorem prod_snd_mk {n : ℕ} {α : typevec n} {β : typevec n} (i : fin2 n) (a : α i) (b : β i) : prod.snd i (prod.mk i a b) = b := sorry
/-- `prod` is functorial -/
protected def prod.map {n : ℕ} {α : typevec n} {α' : typevec n} {β : typevec n} {β' : typevec n} : arrow α β → arrow α' β' → arrow (prod α α') (prod β β') :=
sorry
theorem fst_prod_mk {n : ℕ} {α : typevec n} {α' : typevec n} {β : typevec n} {β' : typevec n} (f : arrow α β) (g : arrow α' β') : comp prod.fst (prod.map f g) = comp f prod.fst := sorry
theorem snd_prod_mk {n : ℕ} {α : typevec n} {α' : typevec n} {β : typevec n} {β' : typevec n} (f : arrow α β) (g : arrow α' β') : comp prod.snd (prod.map f g) = comp g prod.snd := sorry
theorem fst_diag {n : ℕ} {α : typevec n} : comp prod.fst prod.diag = id := sorry
theorem snd_diag {n : ℕ} {α : typevec n} : comp prod.snd prod.diag = id := sorry
theorem repeat_eq_iff_eq {n : ℕ} {α : typevec n} {i : fin2 n} {x : α i} {y : α i} : of_repeat (repeat_eq α i (prod.mk i x y)) ↔ x = y := sorry
/-- given a predicate vector `p` over vector `α`, `subtype_ p` is the type of vectors
that contain an `α` that satisfies `p` -/
def subtype_ {n : ℕ} {α : typevec n} (p : arrow α (repeat n Prop)) : typevec n :=
sorry
/-- projection on `subtype_` -/
def subtype_val {n : ℕ} {α : typevec n} (p : arrow α (repeat n Prop)) : arrow (subtype_ p) α :=
sorry
/-- arrow that rearranges the type of `subtype_` to turn a subtype of vector into
a vector of subtypes -/
def to_subtype {n : ℕ} {α : typevec n} (p : arrow α (repeat n Prop)) : arrow (fun (i : fin2 n) => Subtype fun (x : α i) => of_repeat (p i x)) (subtype_ p) :=
sorry
/-- arrow that rearranges the type of `subtype_` to turn a vector of subtypes
into a subtype of vector -/
def of_subtype {n : ℕ} {α : typevec n} (p : arrow α (repeat n Prop)) : arrow (subtype_ p) fun (i : fin2 n) => Subtype fun (x : α i) => of_repeat (p i x) :=
sorry
/-- similar to `to_subtype` adapted to relations (i.e. predicate on product) -/
def to_subtype' {n : ℕ} {α : typevec n} (p : arrow (prod α α) (repeat n Prop)) : arrow (fun (i : fin2 n) => Subtype fun (x : α i × α i) => of_repeat (p i (prod.mk i (prod.fst x) (prod.snd x))))
(subtype_ p) :=
sorry
/-- similar to `of_subtype` adapted to relations (i.e. predicate on product) -/
def of_subtype' {n : ℕ} {α : typevec n} (p : arrow (prod α α) (repeat n Prop)) : arrow (subtype_ p)
fun (i : fin2 n) => Subtype fun (x : α i × α i) => of_repeat (p i (prod.mk i (prod.fst x) (prod.snd x))) :=
sorry
/-- similar to `diag` but the target vector is a `subtype_`
guaranteeing the equality of the components -/
def diag_sub {n : ℕ} {α : typevec n} : arrow α (subtype_ (repeat_eq α)) :=
sorry
theorem subtype_val_nil {α : typevec 0} (ps : arrow α (repeat 0 Prop)) : subtype_val ps = nil_fun := sorry
theorem diag_sub_val {n : ℕ} {α : typevec n} : comp (subtype_val (repeat_eq α)) diag_sub = prod.diag := sorry
theorem prod_id {n : ℕ} {α : typevec n} {β : typevec n} : prod.map id id = id := sorry
theorem append_prod_append_fun {n : ℕ} {α : typevec n} {α' : typevec n} {β : typevec n} {β' : typevec n} {φ : Type u} {φ' : Type u} {ψ : Type u} {ψ' : Type u} {f₀ : arrow α α'} {g₀ : arrow β β'} {f₁ : φ → φ'} {g₁ : ψ → ψ'} : prod.map f₀ g₀ ::: prod.map f₁ g₁ = prod.map (f₀ ::: f₁) (g₀ ::: g₁) := sorry
@[simp] theorem drop_fun_diag {n : ℕ} {α : typevec (n + 1)} : drop_fun prod.diag = prod.diag := sorry
@[simp] theorem drop_fun_subtype_val {n : ℕ} {α : typevec (n + 1)} (p : arrow α (repeat (n + 1) Prop)) : drop_fun (subtype_val p) = subtype_val (drop_fun p) :=
rfl
@[simp] theorem last_fun_subtype_val {n : ℕ} {α : typevec (n + 1)} (p : arrow α (repeat (n + 1) Prop)) : last_fun (subtype_val p) = subtype.val :=
rfl
@[simp] theorem drop_fun_to_subtype {n : ℕ} {α : typevec (n + 1)} (p : arrow α (repeat (n + 1) Prop)) : drop_fun (to_subtype p) = to_subtype fun (i : fin2 n) (x : α (fin2.fs i)) => p (fin2.fs i) x := sorry
@[simp] theorem last_fun_to_subtype {n : ℕ} {α : typevec (n + 1)} (p : arrow α (repeat (n + 1) Prop)) : last_fun (to_subtype p) = id := sorry
@[simp] theorem drop_fun_of_subtype {n : ℕ} {α : typevec (n + 1)} (p : arrow α (repeat (n + 1) Prop)) : drop_fun (of_subtype p) = of_subtype (drop_fun p) := sorry
@[simp] theorem last_fun_of_subtype {n : ℕ} {α : typevec (n + 1)} (p : arrow α (repeat (n + 1) Prop)) : last_fun (of_subtype p) = id := sorry
@[simp] theorem drop_fun_rel_last {n : ℕ} {α : typevec n} {β : Type u_1} (R : β → β → Prop) : drop_fun (rel_last' α R) = repeat_eq α :=
rfl
@[simp] theorem drop_fun_prod {n : ℕ} {α : typevec (n + 1)} {α' : typevec (n + 1)} {β : typevec (n + 1)} {β' : typevec (n + 1)} (f : arrow α β) (f' : arrow α' β') : drop_fun (prod.map f f') = prod.map (drop_fun f) (drop_fun f') := sorry
@[simp] theorem last_fun_prod {n : ℕ} {α : typevec (n + 1)} {α' : typevec (n + 1)} {β : typevec (n + 1)} {β' : typevec (n + 1)} (f : arrow α β) (f' : arrow α' β') : last_fun (prod.map f f') = prod.map (last_fun f) (last_fun f') := sorry
@[simp] theorem drop_fun_from_append1_drop_last {n : ℕ} {α : typevec (n + 1)} : drop_fun from_append1_drop_last = id :=
rfl
@[simp] theorem last_fun_from_append1_drop_last {n : ℕ} {α : typevec (n + 1)} : last_fun from_append1_drop_last = id :=
rfl
@[simp] theorem drop_fun_id {n : ℕ} {α : typevec (n + 1)} : drop_fun id = id :=
rfl
@[simp] theorem prod_map_id {n : ℕ} {α : typevec n} {β : typevec n} : prod.map id id = id := sorry
@[simp] theorem subtype_val_diag_sub {n : ℕ} {α : typevec n} : comp (subtype_val (repeat_eq α)) diag_sub = prod.diag := sorry
@[simp] theorem to_subtype_of_subtype {n : ℕ} {α : typevec n} (p : arrow α (repeat n Prop)) : comp (to_subtype p) (of_subtype p) = id := sorry
@[simp] theorem subtype_val_to_subtype {n : ℕ} {α : typevec n} (p : arrow α (repeat n Prop)) : comp (subtype_val p) (to_subtype p) = fun (_x : fin2 n) => subtype.val := sorry
@[simp] theorem to_subtype_of_subtype_assoc {n : ℕ} {α : typevec n} {β : typevec n} (p : arrow α (repeat n Prop)) (f : arrow β (subtype_ p)) : comp (to_subtype p) (comp (of_subtype fun (i : fin2 n) (x : α i) => p i x) f) = f := sorry
@[simp] theorem to_subtype'_of_subtype' {n : ℕ} {α : typevec n} (r : arrow (prod α α) (repeat n Prop)) : comp (to_subtype' r) (of_subtype' r) = id := sorry
theorem subtype_val_to_subtype' {n : ℕ} {α : typevec n} (r : arrow (prod α α) (repeat n Prop)) : comp (subtype_val r) (to_subtype' r) =
fun (i : fin2 n) (x : Subtype fun (x : α i × α i) => of_repeat (r i (prod.mk i (prod.fst x) (prod.snd x)))) =>
prod.mk i (prod.fst (subtype.val x)) (prod.snd (subtype.val x)) := sorry
|
# Import Problem Instance
We start by importing a simple problem instance to demonstrate the tsplib reader.
```python
from tsplib95 import tsplib95
import itertools
import networkx as nx
instance = tsplib95.load_problem('./tsplib/ulysses16.tsp')
instance.comment
```
'Odyssey of Ulysses (Groetschel/Padberg)'
Remember, this repository contains a small selection of TSP instances that you can use to test your algorithms.
| name | nodes | description |
|------|-------|-------------|
| ulysses16.tsp | 16 | Odyssey of Ulysses |
| ulysses7.tsp | 7 | subset of ulysses16 for testing purposes |
| bayg29.tsp | 29 | 29 Cities in Bavaria |
| bier127.tsp | 127 | 127 Biergaerten in Augsburg |
| bier20.tsp | 20 | subset of bier127 |
| brazil58.tsp | 58 | 58 cities in Brazil |
| ali535.tsp | 535 | 535 Airports around the globe |
| d18512.tsp | 18512 | 18512 places in Germany |
The following calls show the dimension = number of nodes of the problem, its node set and the edge weights. The functions `instance.get_nodes()` and `instance.get_edges()` are implemented as iterators, so you can loop over the nodes or edges. To get a list of nodes or edges, you have to explicitly construct one using `list(instance.get_nodes())`. Note that node counting may start at 1 for some instances while others use 0 as starting point. For convenience, we store the index of the first node as `first_node`.
```python
instance.dimension
instance.get_nodes()
print("List of nodes: ", list(instance.get_nodes()))
first_node = min(instance.get_nodes())
first_node
for i,j in instance.get_edges():
if i >= j:
continue
print(f"edge {{ {i:2},{j:2} }} has weight {instance.wfunc(i,j):3}.")
```
List of nodes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
edge { 1, 2 } has weight 6.
edge { 1, 3 } has weight 5.
edge { 1, 4 } has weight 3.
edge { 1, 5 } has weight 11.
edge { 1, 6 } has weight 8.
edge { 1, 7 } has weight 7.
edge { 1, 8 } has weight 1.
edge { 1, 9 } has weight 12.
edge { 1,10 } has weight 8.
edge { 1,11 } has weight 26.
edge { 1,12 } has weight 5.
edge { 1,13 } has weight 5.
edge { 1,14 } has weight 5.
edge { 1,15 } has weight 7.
edge { 1,16 } has weight 1.
edge { 2, 3 } has weight 1.
edge { 2, 4 } has weight 4.
edge { 2, 5 } has weight 17.
edge { 2, 6 } has weight 14.
edge { 2, 7 } has weight 13.
edge { 2, 8 } has weight 6.
edge { 2, 9 } has weight 17.
edge { 2,10 } has weight 13.
edge { 2,11 } has weight 32.
edge { 2,12 } has weight 11.
edge { 2,13 } has weight 11.
edge { 2,14 } has weight 11.
edge { 2,15 } has weight 13.
edge { 2,16 } has weight 7.
edge { 3, 4 } has weight 5.
edge { 3, 5 } has weight 16.
edge { 3, 6 } has weight 13.
edge { 3, 7 } has weight 12.
edge { 3, 8 } has weight 6.
edge { 3, 9 } has weight 16.
edge { 3,10 } has weight 12.
edge { 3,11 } has weight 31.
edge { 3,12 } has weight 10.
edge { 3,13 } has weight 10.
edge { 3,14 } has weight 11.
edge { 3,15 } has weight 12.
edge { 3,16 } has weight 6.
edge { 4, 5 } has weight 13.
edge { 4, 6 } has weight 11.
edge { 4, 7 } has weight 10.
edge { 4, 8 } has weight 3.
edge { 4, 9 } has weight 15.
edge { 4,10 } has weight 11.
edge { 4,11 } has weight 28.
edge { 4,12 } has weight 8.
edge { 4,13 } has weight 8.
edge { 4,14 } has weight 8.
edge { 4,15 } has weight 9.
edge { 4,16 } has weight 5.
edge { 5, 6 } has weight 4.
edge { 5, 7 } has weight 6.
edge { 5, 8 } has weight 11.
edge { 5, 9 } has weight 8.
edge { 5,10 } has weight 8.
edge { 5,11 } has weight 16.
edge { 5,12 } has weight 7.
edge { 5,13 } has weight 7.
edge { 5,14 } has weight 6.
edge { 5,15 } has weight 4.
edge { 5,16 } has weight 11.
edge { 6, 7 } has weight 1.
edge { 6, 8 } has weight 8.
edge { 6, 9 } has weight 5.
edge { 6,10 } has weight 4.
edge { 6,11 } has weight 17.
edge { 6,12 } has weight 3.
edge { 6,13 } has weight 3.
edge { 6,14 } has weight 3.
edge { 6,15 } has weight 3.
edge { 6,16 } has weight 8.
edge { 7, 8 } has weight 7.
edge { 7, 9 } has weight 5.
edge { 7,10 } has weight 3.
edge { 7,11 } has weight 18.
edge { 7,12 } has weight 2.
edge { 7,13 } has weight 2.
edge { 7,14 } has weight 2.
edge { 7,15 } has weight 3.
edge { 7,16 } has weight 7.
edge { 8, 9 } has weight 12.
edge { 8,10 } has weight 8.
edge { 8,11 } has weight 26.
edge { 8,12 } has weight 5.
edge { 8,13 } has weight 5.
edge { 8,14 } has weight 5.
edge { 8,15 } has weight 6.
edge { 8,16 } has weight 2.
edge { 9,10 } has weight 4.
edge { 9,11 } has weight 15.
edge { 9,12 } has weight 7.
edge { 9,13 } has weight 7.
edge { 9,14 } has weight 7.
edge { 9,15 } has weight 8.
edge { 9,16 } has weight 11.
edge { 10,11 } has weight 19.
edge { 10,12 } has weight 3.
edge { 10,13 } has weight 4.
edge { 10,14 } has weight 4.
edge { 10,15 } has weight 6.
edge { 10,16 } has weight 7.
edge { 11,12 } has weight 20.
edge { 11,13 } has weight 21.
edge { 11,14 } has weight 20.
edge { 11,15 } has weight 20.
edge { 11,16 } has weight 25.
edge { 12,13 } has weight 0.
edge { 12,14 } has weight 1.
edge { 12,15 } has weight 3.
edge { 12,16 } has weight 5.
edge { 13,14 } has weight 1.
edge { 13,15 } has weight 3.
edge { 13,16 } has weight 4.
edge { 14,15 } has weight 2.
edge { 14,16 } has weight 5.
edge { 15,16 } has weight 7.
You have already seen how to draw a graph, here is the relevant code again.
```python
G = instance.get_graph()
if instance.is_depictable():
pos = {i: instance.get_display(i) for i in instance.get_nodes()}
else:
pos = nx.drawing.layout.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_color='#66a3ff', node_size=200)
nx.draw_networkx_labels(G, pos, font_weight='bold' )
nx.draw_networkx_edges(G, pos, edge_color='#e6e6e6')
```
/Users/ritter/Library/Caches/pypoetry/virtualenvs/assignments-ma4502-S2019-py3.7/lib/python3.7/site-packages/networkx/drawing/nx_pylab.py:579: MatplotlibDeprecationWarning:
The iterable function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use np.iterable instead.
if not cb.iterable(width):
<matplotlib.collections.LineCollection at 0x1204a71d0>
# Implementing a multi commodity flow model in Gurobi
We will implement a multi commodity flow model using binary variables $x_{ij} \in \{0,1\}$ to indicate whether edge $\{i,j\}$ is being used in the tour. For the flow we use variables $y_{i,j,k}$ indicating the flow of commodity $k$ from node $v_0$ into node $k$ along arc $(i,j)$. Flow is only allowed on arcs that are used in the tour and the capacity of each such arc is $1$, we send $2$ units of flow from $v_0$ to $k$. For the formulation, we employ the condition that $i < j$ for any edge $\{i,j\}$ for the $x$-variables. The formulation looks like this:
\begin{align}
\min\;&\sum_{i,j \in E} c_{i,j} \cdot x_{i,j}\\
&\sum_{j \ne i} x_{i,j} = 2 \quad \text{for all nodes $i$}\\
&\sum_{j \ne k} y_{v_0,j,k} = 2 \quad \text{for all nodes $k \ne v_0$}\\
&\sum_{j \ne k} y_{j,v_0,k} = 0 \quad \text{for all nodes $k \ne v_0$}\\
&\sum_{j \ne i} y_{j,i,k} - \sum_{j \ne i} y_{i,j,k} = 0 \quad \text{for all nodes $k \ne v_0$ and all nodes $i \notin \{v_0,k\}$}\\
&y_{i,j,k} \le x_{i,j} \quad \text{for all arcs $(i,j)$ and all $k \ne v_0$}\\
&y_{j,i,k} \le x_{i,j} \quad \text{for all arcs $(i,j)$ and all $k \ne v_0$}\\
&x_{i,j} \in \{0,1\}\\
&y_{i,j,k} \ge 0 \quad \text{for all $k \ne 1$}
\end{align}
## Creating the variables
We start by creating the model and the variables and setting the objective.
```python
import gurobipy as grb
model = grb.Model(name="Multi Commodity Flow TSP Formulation")
model.reset()
x = model.addVars(filter(lambda e: e[0] < e[1], instance.get_edges()), vtype=grb.GRB.BINARY, name="x")
y = model.addVars(filter(lambda e: e[0] != e[1], instance.get_edges()), range(first_node+1, instance.dimension+1), name="y")
model.setObjective(sum(x[i,j]*instance.wfunc(i,j) for i,j in x.keys()))
```
Academic license - for non-commercial use only
## Degree Constraints
We first add the degree constraints for the $x$-variables:
\begin{align}
&\sum_{j \ne i} x_{i,j} = 2 \quad \text{for all nodes $i$}
\end{align}
```python
for i in instance.get_nodes():
model.addConstr(x.sum(i,'*') + x.sum('*',i) == 2, name=f"degree[{i}]")
```
## Flow Constraints
**Task 1:** Add the flow conservations constraints as well as the in- and out-flow constraints for $v_0$ for each commodity k:
```python
for k in itertools.islice(instance.get_nodes(), 1, None):
model.addConstr(y.sum(first_node,'*',k) == 2, name=f"v0_outflow_for_commodity_{k}")
model.addConstr(y.sum('*',first_node,k) == 0, name=f"v0_inflow_for_commodity_{k}")
for i in filter(lambda e: e not in {first_node,k}, instance.get_nodes()):
model.addConstr(y.sum('*',i,k) - y.sum(i,'*',k) == 0, name=f"{k}_flow_conservation_at_node_{i}")
```
## Capacity Constraints
**Task 2:** Add the capacity constraints:
\begin{align}
&y_{i,j,k} \le x_{i,j} \quad \text{for all arcs $(i,j)$ and all $k \ne v_0$}\\
&y_{j,i,k} \le x_{i,j} \quad \text{for all arcs $(i,j)$ and all $k \ne v_0$}
\end{align}
```python
for k in itertools.islice(instance.get_nodes(), 1, None):
model.addConstrs( (y[i,j,k] <= x[i,j] for i,j in x.keys()), name=f"flow_bound_for_commodity_{k}_on_")
model.addConstrs( (y[j,i,k] <= x[i,j] for i,j in x.keys()), name=f"reverse_flow_bound_for_commodity_{k}_on_")
```
## Starting the Optimization Process
Finally, we set the objective to minimization and call the optimizer.
```python
model.ModelSense = grb.GRB.MINIMIZE
model.reset()
model.optimize()
```
Optimize a model with 3856 rows, 3720 columns and 14190 nonzeros
Variable types: 3600 continuous, 120 integer (120 binary)
Coefficient statistics:
Matrix range [1e+00, 1e+00]
Objective range [1e+00, 3e+01]
Bounds range [1e+00, 1e+00]
RHS range [2e+00, 2e+00]
Presolve removed 240 rows and 225 columns
Presolve time: 0.02s
Presolved: 3616 rows, 3495 columns, 13305 nonzeros
Variable types: 3375 continuous, 120 integer (120 binary)
Found heuristic solution: objective 124.0000000
Root relaxation: objective 7.050000e+01, 2402 iterations, 0.07 seconds
Nodes | Current Node | Objective Bounds | Work
Expl Unexpl | Obj Depth IntInf | Incumbent BestBd Gap | It/Node Time
0 0 70.50000 0 10 124.00000 70.50000 43.1% - 0s
H 0 0 71.0000000 70.50000 0.70% - 0s
Explored 1 nodes (2512 simplex iterations) in 0.17 seconds
Thread count was 8 (of 8 available processors)
Solution count 2: 71 124
Optimal solution found (tolerance 1.00e-04)
Best objective 7.100000000000e+01, best bound 7.100000000000e+01, gap 0.0000%
## Querying and Visualizing the Solution
Before we visualize our result, let us look at a few key figures of our solution.
```python
model.ObjVal
solution_edges = [(i,j) for i,j in x.keys() if x[i,j].x > 0.9]
solution_edges
flow_edges = [f"({i},{j},{k}): {y[i,j,k].x}" for i,j,k in y.keys() if y[i,j,k].x > 0]
flow_edges
```
['(1,3,2): 1.0',
'(1,3,3): 1.0',
'(1,3,4): 1.0',
'(1,3,5): 1.0',
'(1,3,6): 1.0',
'(1,3,7): 1.0',
'(1,3,8): 1.0',
'(1,3,9): 1.0',
'(1,3,10): 1.0',
'(1,3,11): 1.0',
'(1,3,12): 1.0',
'(1,3,13): 1.0',
'(1,3,14): 1.0',
'(1,3,15): 1.0',
'(1,3,16): 1.0',
'(1,16,2): 1.0',
'(1,16,3): 1.0',
'(1,16,4): 1.0',
'(1,16,5): 1.0',
'(1,16,6): 1.0',
'(1,16,7): 1.0',
'(1,16,8): 1.0',
'(1,16,9): 1.0',
'(1,16,10): 1.0',
'(1,16,11): 1.0',
'(1,16,12): 1.0',
'(1,16,13): 1.0',
'(1,16,14): 1.0',
'(1,16,15): 1.0',
'(1,16,16): 1.0',
'(2,3,3): 1.0',
'(2,4,4): 1.0',
'(2,4,5): 1.0',
'(2,4,6): 1.0',
'(2,4,7): 1.0',
'(2,4,8): 1.0',
'(2,4,9): 1.0',
'(2,4,10): 1.0',
'(2,4,11): 1.0',
'(2,4,12): 1.0',
'(2,4,13): 1.0',
'(2,4,14): 1.0',
'(2,4,15): 1.0',
'(2,4,16): 1.0',
'(3,2,2): 1.0',
'(3,2,4): 1.0',
'(3,2,5): 1.0',
'(3,2,6): 1.0',
'(3,2,7): 1.0',
'(3,2,8): 1.0',
'(3,2,9): 1.0',
'(3,2,10): 1.0',
'(3,2,11): 1.0',
'(3,2,12): 1.0',
'(3,2,13): 1.0',
'(3,2,14): 1.0',
'(3,2,15): 1.0',
'(3,2,16): 1.0',
'(4,2,2): 1.0',
'(4,2,3): 1.0',
'(4,8,5): 1.0',
'(4,8,6): 1.0',
'(4,8,7): 1.0',
'(4,8,8): 1.0',
'(4,8,9): 1.0',
'(4,8,10): 1.0',
'(4,8,11): 1.0',
'(4,8,12): 1.0',
'(4,8,13): 1.0',
'(4,8,14): 1.0',
'(4,8,15): 1.0',
'(4,8,16): 1.0',
'(5,6,2): 1.0',
'(5,6,3): 1.0',
'(5,6,4): 1.0',
'(5,6,6): 1.0',
'(5,6,7): 1.0',
'(5,6,8): 1.0',
'(5,6,14): 1.0',
'(5,6,15): 1.0',
'(5,11,9): 1.0',
'(5,11,10): 1.0',
'(5,11,11): 1.0',
'(5,11,12): 1.0',
'(5,11,13): 1.0',
'(5,11,16): 1.0',
'(6,5,5): 1.0',
'(6,5,9): 1.0',
'(6,5,10): 1.0',
'(6,5,11): 1.0',
'(6,5,12): 1.0',
'(6,5,13): 1.0',
'(6,5,16): 1.0',
'(6,7,2): 1.0',
'(6,7,3): 1.0',
'(6,7,4): 1.0',
'(6,7,7): 1.0',
'(6,7,8): 1.0',
'(6,7,14): 1.0',
'(6,7,15): 1.0',
'(7,6,5): 1.0',
'(7,6,6): 1.0',
'(7,6,9): 1.0',
'(7,6,10): 1.0',
'(7,6,11): 1.0',
'(7,6,12): 1.0',
'(7,6,13): 1.0',
'(7,6,16): 1.0',
'(7,14,2): 1.0',
'(7,14,3): 1.0',
'(7,14,4): 1.0',
'(7,14,8): 1.0',
'(7,14,14): 1.0',
'(7,14,15): 1.0',
'(8,4,2): 1.0',
'(8,4,3): 1.0',
'(8,4,4): 1.0',
'(8,15,5): 1.0',
'(8,15,6): 1.0',
'(8,15,7): 1.0',
'(8,15,9): 1.0',
'(8,15,10): 1.0',
'(8,15,11): 1.0',
'(8,15,12): 1.0',
'(8,15,13): 1.0',
'(8,15,14): 1.0',
'(8,15,15): 1.0',
'(8,15,16): 1.0',
'(9,10,10): 1.0',
'(9,10,12): 1.0',
'(9,10,13): 1.0',
'(9,10,16): 1.0',
'(9,11,2): 1.0',
'(9,11,3): 1.0',
'(9,11,4): 1.0',
'(9,11,5): 1.0',
'(9,11,6): 1.0',
'(9,11,7): 1.0',
'(9,11,8): 1.0',
'(9,11,11): 1.0',
'(9,11,14): 1.0',
'(9,11,15): 1.0',
'(10,9,2): 1.0',
'(10,9,3): 1.0',
'(10,9,4): 1.0',
'(10,9,5): 1.0',
'(10,9,6): 1.0',
'(10,9,7): 1.0',
'(10,9,8): 1.0',
'(10,9,9): 1.0',
'(10,9,11): 1.0',
'(10,9,14): 1.0',
'(10,9,15): 1.0',
'(10,12,12): 1.0',
'(10,12,13): 1.0',
'(10,12,16): 1.0',
'(11,5,2): 1.0',
'(11,5,3): 1.0',
'(11,5,4): 1.0',
'(11,5,5): 1.0',
'(11,5,6): 1.0',
'(11,5,7): 1.0',
'(11,5,8): 1.0',
'(11,5,14): 1.0',
'(11,5,15): 1.0',
'(11,9,9): 1.0',
'(11,9,10): 1.0',
'(11,9,12): 1.0',
'(11,9,13): 1.0',
'(11,9,16): 1.0',
'(12,10,2): 1.0',
'(12,10,3): 1.0',
'(12,10,4): 1.0',
'(12,10,5): 1.0',
'(12,10,6): 1.0',
'(12,10,7): 1.0',
'(12,10,8): 1.0',
'(12,10,9): 1.0',
'(12,10,10): 1.0',
'(12,10,11): 1.0',
'(12,10,14): 1.0',
'(12,10,15): 1.0',
'(12,13,13): 1.0',
'(12,13,16): 1.0',
'(13,12,2): 1.0',
'(13,12,3): 1.0',
'(13,12,4): 1.0',
'(13,12,5): 1.0',
'(13,12,6): 1.0',
'(13,12,7): 1.0',
'(13,12,8): 1.0',
'(13,12,9): 1.0',
'(13,12,10): 1.0',
'(13,12,11): 1.0',
'(13,12,12): 1.0',
'(13,12,14): 1.0',
'(13,12,15): 1.0',
'(13,16,16): 1.0',
'(14,7,5): 1.0',
'(14,7,6): 1.0',
'(14,7,7): 1.0',
'(14,7,9): 1.0',
'(14,7,10): 1.0',
'(14,7,11): 1.0',
'(14,7,12): 1.0',
'(14,7,13): 1.0',
'(14,7,16): 1.0',
'(14,15,2): 1.0',
'(14,15,3): 1.0',
'(14,15,4): 1.0',
'(14,15,8): 1.0',
'(14,15,15): 1.0',
'(15,8,2): 1.0',
'(15,8,3): 1.0',
'(15,8,4): 1.0',
'(15,8,8): 1.0',
'(15,14,5): 1.0',
'(15,14,6): 1.0',
'(15,14,7): 1.0',
'(15,14,9): 1.0',
'(15,14,10): 1.0',
'(15,14,11): 1.0',
'(15,14,12): 1.0',
'(15,14,13): 1.0',
'(15,14,14): 1.0',
'(15,14,16): 1.0',
'(16,13,2): 1.0',
'(16,13,3): 1.0',
'(16,13,4): 1.0',
'(16,13,5): 1.0',
'(16,13,6): 1.0',
'(16,13,7): 1.0',
'(16,13,8): 1.0',
'(16,13,9): 1.0',
'(16,13,10): 1.0',
'(16,13,11): 1.0',
'(16,13,12): 1.0',
'(16,13,13): 1.0',
'(16,13,14): 1.0',
'(16,13,15): 1.0']
For debugging purposes, it might be helpful to export the model held by Gurobi into a human-readable format:
```python
model.write('test.lp')
```
Finally, let us visualize the solution using NetworkX. In this case, we need to prescribe positions and draw the nodes and two layers of edges separately.
```python
if instance.is_depictable():
pos = {i: instance.get_display(i) for i in instance.get_nodes()}
else:
pos = nx.drawing.layout.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_color='#66a3ff', node_size=500)
nx.draw_networkx_labels(G, pos, font_weight='bold' )
nx.draw_networkx_edges(G, pos, edge_color='#e6e6e6')
nx.draw_networkx_edges(G, pos, edgelist=solution_edges, edge_color='#ffa31a', width=4)
```
**Task 3:** Test the model for different instances. How does it compare to the MTZ formulation?
```python
```
|
-- ---------------------------------------------------------------- [ Test.idr ]
-- Module : Test.idr
-- Copyright : (c) Jan de Muijnck-Hughes
-- License : see LICENSE
-- --------------------------------------------------------------------- [ EOH ]
module Config.Test.JSON
import Config.JSON
import Lightyear.Testing
%access export
jsonTest1 : TestReport
jsonTest1 = parseTest "JSON Test 1"
parseJSONFile
"""{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"height_cm": 167.6,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [],
"spouse": null
}
"""
jsonTest2 : TestReport
jsonTest2 = parseTest "JSON Test 2"
parseJSONFile
"""{
"$schema": "http://json-schema.org/draft-03/schema#",
"name": "Product",
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "Product identifier",
"required": true
},
"name": {
"type": "string",
"description": "Name of the product",
"required": true
},
"price": {
"type": "number",
"minimum": 0,
"required": true
},
"tags": {
"type": "array",
"items": {
"type": "string"
}
},
"stock": {
"type": "object",
"properties": {
"warehouse": {
"type": "number"
},
"retail": {
"type": "number"
}
}
}
}
}
"""
jsonTest3 : TestReport
jsonTest3 = parseTest "JSON Test 3"
parseJSONFile
"""{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"height_cm": 167.6,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [],
"spouse": null
}
"""
runTests : IO ()
runTests = Testing.runTests [jsonTest1, jsonTest2, jsonTest3]
-- --------------------------------------------------------------------- [ EOF ]
|
[STATEMENT]
lemma C_eq_until_separated:
"DenyAll\<in>set(policy2list p) \<Longrightarrow> all_in_list(policy2list p) l \<Longrightarrow> allNetsDistinct(policy2list p) \<Longrightarrow>
Cp (list2FWpolicy (separate (sort (removeShadowRules2 (remdups (rm_MT_rules Cp
(insertDeny (removeShadowRules1 (policy2list p)))))) l))) =
Cp p"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>DenyAll \<in> set (policy2list p); all_in_list (policy2list p) l; allNetsDistinct (policy2list p)\<rbrakk> \<Longrightarrow> Cp (list2FWpolicy (separate (FWNormalisationCore.sort (removeShadowRules2 (remdups (rm_MT_rules Cp (insertDeny (removeShadowRules1 (policy2list p)))))) l))) = Cp p
[PROOF STEP]
by (simp add: C_eq_All_untilSorted_withSimps C_eq_s wellformed1_alternative_sorted wp1ID wp1n_RS2) |
lemma Bfun_inverse: fixes a :: "'a::real_normed_div_algebra" assumes f: "(f \<longlongrightarrow> a) F" assumes a: "a \<noteq> 0" shows "Bfun (\<lambda>x. inverse (f x)) F" |
Formal statement is: lemma eventually_at: "eventually P (at a within S) \<longleftrightarrow> (\<exists>d>0. \<forall>x\<in>S. x \<noteq> a \<and> dist x a < d \<longrightarrow> P x)" for a :: "'a :: metric_space" Informal statement is: A property $P$ holds eventually at $a$ within $S$ if and only if there exists a positive real number $d$ such that for all $x \in S$ with $x |
import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
from spotifyAPI import *
app = Flask(__name__)
model = pickle.load(open('models/gbt3.pkl', 'rb'))
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict',methods=['POST'])
def predict():
inputs = [x for x in request.form.values()]
track = inputs[-1]
rem_features = inputs[0:10]
client_id = '31f4904f55144d938e3a19f9f9636c4f'
client_secret = '13521108cdee48538044a625a8da963c'
spotify = SpotifyAPI(client_id, client_secret)
my_dict = spotify.search({"track": track}, search_type="track")
id = my_dict["tracks"]["items"][0]["id"]
access_token = spotify.access_token
headers = {
"Authorization": f"Bearer {access_token}"
}
endpoint = "https://api.spotify.com/v1/audio-features"
data = urlencode({"ids": id})
lookup_url = f"{endpoint}?{data}"
r = requests.get(lookup_url, headers=headers)
abc = r.json()
features = list(abc["audio_features"][0].values())[0:6]+list(abc["audio_features"][0].values())[7:11]+list(abc["audio_features"][0].values())[16:18]
#features = [np.array(features)]
final_features = [np.array(rem_features + features)]
prediction = model.predict(final_features)
def fxprediction(prediction):
if prediction > 0.5:
return(" user will skip the song")
else:
return("user will not skip the song")
return render_template('index.html', prediction_text='{}'.format(fxprediction(prediction)))
if(__name__ == "__main__"):
app.run(debug = True) |
import Data.Vect
fourInts : Vect 4 Int
fourInts = [0,1,2,3]
||| The sum of both 4D vectors is an 8D vector
eightInts : Vect 8 Int
eightInts = fourInts ++ fourInts
total allLengths : Vect len String -> Vect len Nat
allLengths [] = []
allLengths (word :: words) = length word :: allLengths words
badLengthWithList : List String -> List Nat
badLengthWithList xs = []
badLengthWithVect : Vect n String -> Vect n Nat
badLengthWithVect xs = ?replace_with_empty_list_for_type_checking_error
anotherLengths : Vect length String -> Vect length Nat
anotherLengths [] = ?anotherLengths_rhs_1
anotherLengths (x :: xs) = ?anotherLengths_rhs_2
|
[STATEMENT]
lemma nodeToDigit_list: "digitToList (nodeToDigit nd) = nodeToList nd"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. digitToList (nodeToDigit nd) = nodeToList nd
[PROOF STEP]
by (cases nd,auto) |
If $f$ is a function from a measurable space $N$ to a set $A$, then $f$ is measurable with respect to the smallest $\sigma$-algebra on $A$ that makes $f$ measurable. |
module ExponentialIntegrators
using ExponentialUtilities
import ExponentialUtilities: expv!
abstract type AbstractIntegrator{T} end
order(::AbstractIntegrator) = 1
order(::Type{AbstractIntegrator}) = 1
abstract type AbstractExponentiator{T} end
exact(::AbstractExponentiator) = false
inplace(::AbstractExponentiator) = false
order(::AbstractExponentiator) = 1
# The last argument to `expv!`, the integer, signifies if the
# exponentiation should be performed in the forward direction (1), or
# backward direction (0). This is useful if `E` split further, and is
# part of a symmetric splitting scheme. If the argument is 0, the
# order does not matter (as is the case for the middle term of a
# certain splitting).
expv!(v, E::AbstractExponentiator, Δt, u) = expv!(v, E, Δt, u, 0)
abstract type AbstractOperator{T} end
# Time-dependent operators could be of the kind A(t), A + f(t)B, etc,
# for which the different temporal integration routines would have to
# be special-cased.
checkorder(o,integrator) =
o < order(integrator) && @warn("Order of $(typeof(o)) lower than required for $(integrator)")
macro swap!(x,y)
quote
local tmp = $(esc(x))
$(esc(x)) = $(esc(y))
$(esc(y)) = tmp
end
end
# Temporal integration of operators
include("integrate.jl")
# Exponentiators for single operators
include("krylov.jl")
include("pade.jl")
# Integrators composed of multiple exponentiators
include("strang_splitting.jl")
include("exact_integrator.jl")
export step!, StrangSplitting, ExactIntegrator
end # module
|
\title{Lab 6: Altium}
\author{Engineering 100-950}
\date{Winter 2020}
\documentclass[12pt]{article}
\usepackage[margin=1in]{geometry}
\usepackage{fancyhdr}
\chead{Written \& Edited by Arun Nagpal, Lyndon Shi, Scott Smith, Sarah Redman, Kitty Ascrizzi}
\usepackage{hyperref}
\usepackage{circuitikz}
\begin{document}
\maketitle
\thispagestyle{fancy}
\section*{Calendar}
\begin{table}[h]
\begin{tabular}{lllll}
Introduction to PCBs & 2/18/20 & & & \\
PCBs due for Peer Review & 2:30pm on 2/25/20 & & & \\
Peer Reviews due after Lab & 5pm on 2/26/20 & & & \\
Final PCBs Due & 5pm on 2/27/20 & & & \\
PCBs Arrive for Assembly & 3/9/20 & & &
\end{tabular}
\end{table}
\section*{Introduction}
In this lab, you will be designing your sensor board in its totality in \textbf{Altium Designer}, a PCB design software that is an industry standard. This design will be sent directly to manufacturers for fabrication, and you'll have your completed PCBs sent back to you to start constructing your payload after Spring Break! There is no postlab for this lab. Focus on making sure your design is good, and everything about your board works. Once the PCBs are ordered, you cannot make changes. Sometimes, we can work around mistakes manually. Sometimes, teams have needed to use an old PCB from previous classes. \textbf{Upon submission, if you fail any design rule checks, you will receive a 0 for this lab. This is true even if everything else is correct. You must pass all design rule checks to get credit for this lab.}
\section*{Participation}
Working at a computer often can become a one person deal. It is important to avoid this during this lab. Our goal is for all students in this course learn the basics of Altium. When you are working on your PCBs, have at least one person spotting the person at the computer. This will help you share the work that goes into creating the PCB and eliminate mistakes that can render your finished product useless. We will be designating times in full class Altium sessions to rotate roles. Make sure all team members are involved and ready to rotate at any time! It is important that no team member works alone, even during office hours. This lab is two weeks long to allow you ample time to meet in groups of at least two and allow all members to spend some time on Altium.
\section*{Preparing your Layout and Extra Sensor}
The following are a few design specific notes you must keep in mind while laying out your Altium schematic:
\begin{enumerate}
\item All of our boards will use the same power architecture (See Figure 1). Keep the following in mind for power architecture:
\subitem We will use a 5V and a 3V3 LDO. All items that need 5V power should get it from the output of the 5V LDO, not the Arduino. Same goes for the 3V3 LDO.
\subitem Use the 5V pin on the Arduino to supply the Arduino with 5V from the output of the LDO. We use the 5V pin instead of the Vin pin because the Vin pin expects a voltage between 7-12 volts.
\item To have enough analog pins available to incorporate your extra sensor, you will have to eliminate either your TMP36 or your Thermistor. Your team should consider which is more reliable and more suited to what you hope to measure. Then choose the best fit.
\item If your extra sensor uses I2C communication protocols, you must connect it to the analog pins pre-set for I2C communications. In the Arduino Nano, these are A4 (SDA pin) and A5 (SCL pin). See more on connecting I2C devices \href{https://www.lehelmatyus.com/691/sda-scl-arduino-nano-connecting-i2c-devices-arduino-nano}{(by clicking here)} Be sure you read through your extra sensor's documentation and/or hookup guide to understand whether it is I2C and if you will need the A4 and A5 I2C hookup pins.
\end{enumerate}
\begin{figure}[h]
\begin{center}
\includegraphics[scale = .3]{Figures/Altium_pwr.PNG}
\caption{The power and voltage protection architecture of your board. The leftmost two components are LDOs, the top is 3.3V, and the bottom is 5V. D1 indicates a diode for battery protection.}
\end{center}
\end{figure}
\section*{Altium}
Altium as a software can be very complex, and as such, we have given you some tools to help simplify the process of constructing your PCB. The following pictures are taken from a free online tutorial provided by Altium: \href{http://www.altium.com/documentation/18.0/display/ADES/From+Idea+to+Manufacture+-+Driving+a+PCB+Design+through+Altium+Designer}{\underline{From Idea to Manufacture}}. You can learn more about this example there.\\
\noindent
Broadly, the workflow in Altium is divided up into three steps: Schematic, PCB, and Design Rule Check. The Schematic step is where you lay out the electrical schematic of your board. Using all the components, you define how they connect to each other, ground, and power. The PCB step is where you the physical layout of those components on the board. The electrical connections you set up in the schematic are shown for your reference, and you lay them down on your PCB physically as traces. That is, each trace you set corresponds to an electrical connection you outlined in your Schematic. The Design Rule Check step is when the software looks over your work and makes sure you aren't committing any errors or contradictions. This is inevitably the most frustrating part of using Altium, because you think you've done everything right, and the software is here to tell you that you haven't. It is important to note that design rule checks do not check whether you laid out your board the way you wanted, they will not notice if you accidentally connected your temperature sensor to your pressure sensor instead of the Arduino. You must double check this yourself. The design rule checks only check if your design is violating the physical and electrical laws associated with making a PCB.
\subsection*{Schematic}
You begin with an idea. A circuit or device that you'd like to realize in a PCB. The first thing you need to do is tell Altium the components you'll be using, and their relationships to one another. Consider the drawing of a `self-running a stable multivibrator' below.
\begin{figure}[h]
\begin{center}
\includegraphics[scale=0.5]{Figures/Altium_astable.PNG}
\caption{A drawing of a schematic, that pretty closely resembles the schematic you'd make in Altium.}
\end{center}
\end{figure}
\noindent
Fig. 3 shows Fig. 2 as an Altium schematic. The schematic is defined in a document with the extension \textbf{.SchDoc}.
\begin{figure}[h]
\begin{center}
\includegraphics[scale=0.6]{Figures/Altium_sch_Wired.png}
\caption{The schematic of an astable multivibrator as displayed through Altium.}
\end{center}
\end{figure}
Note that each component is defined with its own individual symbol. Capacitors, resistors, and transistors (Q1 and Q2), and some connectors (P1) are standardized and thus have pre-loaded symbols in the software, but for most of our components, that is not the case. We have additional libraries custom made by ENGR100 staff with our components pre-loaded, so, as we will discuss in the procedure, you can simply drag and drop them into place.
\subsection*{PCB}
The PCB is designed as a separate document with the extension \textbf{.PcbDoc}. We can create a new PCB document and correlate it to our schematic. This will import all the components to the PCB document. Then, just as in the schematic document, we can manually place each footprint. As before, the footprints will be provided via a custom library we have prepared for you. \\
\noindent
Note the white lines that connect each of the footprints in Figure 4. These represent what pins on each part that should be connected via traces. This should be done manually, similar to the way that wires were drawn in the schematic. One notable difference is that physical traces should never be drawn at right angles - instead they should be at obtuse angles. This is to minimize field leakage and reflection at corners.\\
\noindent
Finally, we have a completed board! Altium creates a cartoon (Figure 5) that we can view before moving on to the final stage: Design Rule Check.
\begin{figure}[h]
\begin{center}
\includegraphics[scale=0.4]{Figures/Altium_pcb1.PNG}
\caption{The PCB Layout in Altium.}
\end{center}
\end{figure}
\begin{figure}[h]
\begin{center}
\includegraphics[scale=0.6]{Figures/Altium_pcb2.PNG}
\caption{The completed multivibrator!}
\end{center}
\end{figure}
\subsection*{DRC}
The DRC, or Design Rule Check is a way to check the validity of your PCB with respect to the Design Rules we create. More on this in the procedure.\\
\begin{figure}[h]
\begin{center}
\includegraphics[scale=0.4]{Figures/Altium_newproj.PNG}
\caption{The Project Creation Wizard popup. It should look something like this when you're done.}
\end{center}
\end{figure}
\begin{figure}[h]
\begin{center}
\includegraphics[scale=0.5]{Figures/Altium_projtab.PNG}
\caption{The Project Tab should be on the left side of your screen}
\end{center}
\end{figure}
\begin{figure}[h]
\begin{center}
\includegraphics[scale=.7]{Figures/Altium_gpsnets.PNG}
\caption{The GPS, connected using nets instead of wires}
\end{center}
\end{figure}
\section*{Procedure: Creating Your Design}
\begin{enumerate}
\item Open Altium Designer on a CAEN computer. Navigate to File $\rightarrow$ New $\rightarrow$ Project...
\item Choose a regular PCB project using the default template.
\item Make sure the ``Create Project Folder" box is checked. This will designate a directory to save all of your project files in. The ``Location" field allows you to choose where this folder is created.
\item Name your project something related to your team name or number, and click ``OK". See Fig. 6 for an example Project Creation.
\item Now you should add two libraries we will give you. To do this, go to the Projects tab on the left side of the screen. A picture of this tab is shown in Fig. 7. If you see something else here, see if you can click the word ``Projects'' at the bottom left of the window.
\item Right click your project name in bold and click Add Existing to Project. Navigate to your saved PCB libraries and select both of them.
\item Look at the Projects Tab on the left side of the screen. Right click your project name in bold and click Add New to Project $\rightarrow$ Schematic. A blank piece of paper should appear on the screen. This is where you are to lay out your schematic drawing.
A few instructions for laying out a schematic:
\begin{itemize}
\item The 'Components: Final PCBs' spreadsheet on Canvas under Files / Labs / Lab 6 Altium Resources lists all components you might need for your system, their schematic names, and footprint names. It's important to note: all non-electrolytic capacitors, all 300 Ohm and 1 kOhm resistors and all LED's must use a C1206 capacitor footprint as indicated on this spreadsheet.
\item Go to Place $\rightarrow$ Part to place a component. Navigate to the library you would like to use with the dropdown menu. A keyboard shortcut is to simply press 'P' twice in a row.
\item Rather than connecting everything with wires, use \textbf{nets} to connect your components. Nets are a convenient way to connect two pins without explicitly drawing a wire between them. Consider this example for the GPS (Fig. 8). You can place a net using Place $\rightarrow$ Net Label.
This is a great way to make sure things don't get too messy.
\item As you can see from the picture of the GPS, there's a capacitor in there that we haven't seen before. Since your board will be relying on raw battery power as its only means of operation, we are playing it safe and smoothing out any potential high frequency noise. So, for \textbf{all sensors}, tie a 0.1$\mu$F capacitor to the $V_{in}$ or $VCC$ line, which itself should output directly to ground.
\item You must place one 3x1 header somewhere on your schematic, that connects to a 5V net, a 3.3V net, and GND. Call this header `Test Points.' It will be used to test your battery voltage.
Headers can be found in the Miscellaneous Connectors Library.
\item Your board requires significant power architecture. Lay out the the components shown in Fig. 1. The LEDs serve as status indicators and battery protection.
\item To find the properties of a given component, double click its symbol on the schematic. A component-specific properties window will open up. Here you can adjust the part label, the value of the component (such as resistance or capacitance), and the \textbf{footprint} of the component. The footprint is a representation of how the component looks in real life - e.g. what actually will be on your board.You can add a footprint by clicking the corresponding Add button in the Component Properties window.
\item Make sure to include the components and connections necessary to implement your extra sensor(s). Ask the IAs for help if you have questions on how these extra sensors should connect to your Arduino.
\end{itemize}
That's a lot to keep in mind! The path to success involves moving slowing and methodically through each component, writing out your schematic on paper beforehand, staying organized, and asking questions. If you're confused on what to do, please ask! \textbf{When you've finished your schematic, ask an IA to check it off and make sure it is correct.} Once they mark it off, you can move onto creating the PCB. It is in your best interest to have a clean and accurate schematic before moving forward. Even minor changes on the schematic can require substantial changes on your PCB to accommodate.
\end{enumerate}
\section*{Making the PCB}
\textit{Pressing 1 on your keyboard takes you to the board design view. Pressing 2 takes you to the component layout screen. Pressing 3 takes you to the cartoon mockup screen. You should do your layout work (e.g. most of the work) in mode 2.}
\begin{enumerate}
\item To create a new PCB file, right click your project name under your Projects tab, click New $\rightarrow$ Add New to Project $\rightarrow$ PCB.
\item Import your schematic components. Go to Design $\rightarrow$ Import Changes from Project name. Validate your changes, make sure you see only green check marks next to each change. Then execute them. By zooming in and out on your board (by pressing the mouse scroll button and moving around), you should see a big red box containing all of the components. You can drag and drop them onto the board, which is the black rectangle.
\item Now we should adjust the size of our board. To do this, press 1 on your keyboard. Navigate to Design $\rightarrow$ Edit Board Shape. The board should be no bigger than 4.5-in to a side. You can toggle between Imperial and Metric units by pressing Q.
\item We will add some design rules. Press 2 on your keyboard to ensure that you are on the component layout screen. Navigate to Design $\rightarrow$ Rules\dots
A PCB rules window should pop up. Set the following design rules:
\begin{itemize}
\item Electrical $\rightarrow$ Clearance = 6 mil
\item Routing $\rightarrow$ Width
\begin{itemize}
\item Minimum Width = 6 mil
\item Preferred Width = 15 mil
\item Maximum Width = 30 mil
\end{itemize}
\item Manufacturing $\rightarrow$ MinimumAnnularRing = 7 mil
\item Manufacturing $\rightarrow$ HoleSize = 13 mil
\end{itemize}
\item Layout your components neatly on the board. Be sure to place your Arduino and OpenLog in such a way that you do not obstruct the port for the uploading cable or the SD Card opening.
\item To connect traces to your different components, navigate to Route $\rightarrow$ Interactive Routing. When you are placing a trace press 3 to toggle between your min, preferred, and max trace width as set in the design rules. Recall from lecture that your board will contain two copper layers. These layers are referred to as the top and bottom layers, and are colored red and blue. Route all traces except the ground traces. We will route those later to our polygon pour ground plane, which we make last.
\item When routing, all traces should default to 15mil if you implemented the Design Rules correctly. However, you should manually make a few of the power lines thicker, to compensate for the increased current flow through them.
\begin{itemize}
\item Power lines to the Input of the LDO's = 30 mil.
\item Output of the LDO's to the electrolytic capacitors and status LEDs = 25 mil.
\end{itemize}
\item Finally, we should pour a ground plane. Using the menu at the bottom of the PCB, select the bottom layer and cover it with a grounded polygon pour. You can now connect all your ground connections directly to this by using vias (no traces involved).
\item Recall that you created a set of Design Rules before creating your PCB. The Design Rule Check (DRC) assesses your design in light of these rules, and highlights any discrepancies between your layout and those rules. Your DRC must return ZERO errors before your PCB can be considered complete.
Design Rule Check can be run by navigating to Tools $\rightarrow$ Design Rule Check. Click Run Design Rule Check to run DRC. Generally, errors are highlighted in bright green.
\item Once you have passed all design rule checks, take a screenshot of your error-free DRC screen
\end{enumerate}
\section*{Peer Review}
\href{https://drive.google.com/drive/folders/1HiCb5Kfc1rcL4PkWGpplv0pV3mDflQRK?usp=sharing}
In the second week of this lab, every student will be required to peer review the PCBs of three other teams. Each team must upload a single zip file containing all project files and a screenshot showing all DCRs passed to this designated Google Drive folder \href{https://drive.google.com/drive/folders/1HiCb5Kfc1rcL4PkWGpplv0pV3mDflQRK?usp=sharing}{(click here)} by 2:30pm on Tuesday, February 25th, 2020. Make sure that your PCB passes all design rule checks \textbf{before} submitting it to the Google Drive folder.
In lab, each student will peer review three PCBs with rubrics provided on Canvas. Peer reviews are due by the end of your lab period.
\section*{Final Deliverable}
\href{https://drive.google.com/drive/folders/1HiCb5Kfc1rcL4PkWGpplv0pV3mDflQRK?usp=sharing}
Your team will have 24 hours between 5pm on Wednesday, January 26th, 2020, and 5pm on Thursday, January 27th, to implement changes recommended by peer reviews. Then, rename your project with the ending '-FINAL' and re-upload the single zip file containing all project files and a screenshot showing all DRCs passed to this designated Google Drive folder \href{https://drive.google.com/drive/folders/1HiCb5Kfc1rcL4PkWGpplv0pV3mDflQRK?usp=sharing}{(click here)} by 5pm on Thursday, February 27th, 2020. \textbf{All design rule checks must be satisfied or you will receive a 0 on the assignment. This assignment MUST be finished on time or you will face significant difficulties completing the rest of the project.} Spend a lot of time ensuring that your design is correct. Do not hesitate to talk to the IAs or Professor Ridley.
\end{document}
|
function L = noiseExpectationLogLikelihood(noise, mu, varsigma, y);
% NOISEEXPECTATIONLOGLIKELIHOOD Return the expectation of the log likelihood.
% FORMAT
% DESC returns the expectation of the log likelihood for a gven noise model.
% ARG noise : the noise structure for which the expectation of the log
% likelihood is required.
% ARG mu : input mean locations for the likelihood.
% ARG varSigma : input variance locations for the likelihood.
% ARG y : target locations for the likelihood.
%
% SEEALSO : noiseParamInit, noiseLogLikelihood
%
% COPYRIGHT : Neil D. Lawrence, 2007
% NOISE
fhandle = str2func([noise.type 'NoiseExpectationLogLikelihood']);
L = fhandle(noise, mu, varsigma, y);
|
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
Rows := s -> Cond(
IsMat(s),
Length(s),
IsBound(s.rng) and IsBound(s.dmn),
s.dims()[1],
IsValue(s) or IsSymbolic(s),
Checked(IsArrayT(s.t), IsArrayT(s.t.t),
s.t.size),
s.dimensions[1]
);
Cols := s -> Cond(
IsMat(s),
Length(s[1]),
IsBound(s.rng) and IsBound(s.dmn),
s.dims()[2],
IsValue(s) or IsSymbolic(s),
Checked(IsArrayT(s.t), IsArrayT(s.t.t),
s.t.t.size),
s.dimensions[2]
);
olRows := s -> Flat([Rows(s)]);
olCols := s -> Flat([Cols(s)]);
#F SPL(<rec>)
#F Set operations field to SPLOps. This function should be called
#F to initialize SPL instances.
SPL := function(record)
record.operations := SPLOps;
return record;
end;
HashAsSPL := o -> Cond(
IsList(o),
List(o, HashAsSPL),
not IsRec(o) or (not IsBound(o.hashAs) and not IsBound(o.from_rChildren)),
o,
IsBound(o.hashAs),
o.hashAs(),
IsValue(o),
o.v,
o.from_rChildren(List(o.rChildren(), HashAsSPL))
);
# ==========================================================================
# ClassSPL
#
# Base class for all SPL constructs
# ==========================================================================
Class(ClassSPL, AttrMixin, rec(
isSPL := true,
transposed := false,
#DD this allows objects which are not TaggedNonTerminals to drop tags automagically
#DD and without error.
withTags := (self, t) >> self,
_short_print := false,
_newline := i -> Print("\n", Blanks(i)),
_indent := i -> Print(Blanks(i)),
_indentStr := Blanks,
__call__ := meth(arg)
local self, params, nump, A,p,res,h,lkup;
self := arg[1];
params := arg{[2..Length(arg)]};
nump := Length(params);
if not IsBound(self.new) then
Error("Constructor for this class is not implemented");
elif IsBound(self.abbrevs) and self.abbrevs <> [] then
for A in self.abbrevs do
if NumArgs(A) = -1 or NumArgs(A) = nump then
params := ApplyFunc(A, params);
fi;
od;
fi;
if NumArgs(self.new)-1 <> Length(params) then
Error("Constructor requires ", NumArgs(self.new)-1, " parameters (",
Length(arg)-1, " given): ",
ParamsMeth(self.new));
else
h := self.hash;
if h<>false then
lkup := h.objLookup(self, params);
if lkup[1] <> false then return lkup[1]; fi;
fi;
res := ApplyFunc(self.new, params);
if h<>false then return h.objAdd(res, lkup[2]);
else return res;
fi;
fi;
end,
hash := false,
checkDims := self >> DimensionsMat(MatSPL(self)) = self.dimensions,
#-----------------------------------------------------------------------
# create a new object with .<name> field set to true
setAttr := meth(self, name)
local s;
s:= Copy(self);
s.(name) := true;
return s;
end,
# ----------------------------------------------------------------------
# create a new object with .<name> field set to <val>
setAttrTo := meth(self, name, val)
local s;
s:= Copy(self);
s.(name) := val;
return s;
end,
#---------Backwards Compatibility for the new dimension system------
setDims := meth(self) self.dimensions := self.dims(); return self; end,
dims := self >> [ StripList(List(self.rng(), l -> l.size)),
StripList(List(self.dmn(), l -> l.size)) ],
advdims := (self) >> let(d := self.dims(), [ [[ d[1] ]], [[ d[2] ]] ]),
arity := (self) >> List(self.dims(), e -> Length(Flat([e]))),
TType:=TUnknown,
rng := meth(self) local d;
if IsBound(self.dims) then
d := Flat([self.dims()[1]]);
else
d := [self.dimensions[1]];
fi;
if IsBound(self.a.t_out) then
return List(TransposedMat([self.a.t_out, d]), e -> TArray(e[1], e[2]));
else
return List(d, e -> TArray(self.TType, e));
fi;
end,
dmn := meth(self) local d;
if IsBound(self.dims) then
d := Flat([self.dims()[2]]);
else
d := [self.dimensions[2]];
fi;
if IsBound(self.a.t_in) then
return List(TransposedMat([self.a.t_in, d]), e -> TArray(e[1], e[2]));
else
return List(d, e -> TArray(self.TType, e));
fi;
end,
free := self >> Union(List(self.rChildren(), FreeVars)),
equals := (self, o) >>
ObjId(self) = ObjId(o) and self.rChildren() = o.rChildren() and self.a = o.a,
lessThan := (self, o) >> Cond(
ObjId(self) <> ObjId(o), ObjId(self) < ObjId(o),
[ ObjId(self), self.rChildren(), self.a ] < [ ObjId(o), o.rChildren(), o.a ]
),
from_rChildren := (self, rch) >> ApplyFunc(ObjId(self), rch).appendAobj(self),
print := (self, i, is) >> self._print(self.rChildren(), i, is),
_print := meth(self, ch, indent, indentStep)
local s, first, newline;
if self._short_print or ForAll(ch, x->not IsRec(x) or IsSPLSym(x) or IsSPLMat(x)) then
newline := Ignore;
else
newline := self._newline;
fi;
first := true;
Print(self.__name__, "(");
for s in ch do
if(first) then first:=false;
else Print(", "); fi;
newline(indent + indentStep);
When(IsSPL(s) or (IsRec(s) and IsBound(s.print) and NumGenArgs(s.print)=2),
s.print(indent + indentStep, indentStep),
Print(s));
od;
newline(indent);
Print(")");
self.printA();
if IsBound(self._setDims) then
Print(".overrideDims(", self._setDims, ")");
fi;
end,
printlatex := meth(self)
local s, first, newline, i;
first := true;
Print("(");
i := Length(self.rChildren());
for s in self.rChildren() do
When(IsSPL(s) or (IsRec(s) and IsBound(s.printlatex) and NumGenArgs(s.printlatex)=0),
s.printlatex(),
Print(s));
if i >=2 then
Print(" ", When(IsBound(self.latexSymbol), self.latexSymbol, ""), " ");
fi;
i := i-1;
od;
Print(")");
end,
overrideDims := (self, dims) >> CopyFields(self, rec(_setDims := dims, dimensions := dims)),
terminate := self >> self.from_rChildren(List(self.rChildren(), x->When(IsSPL(x), x.terminate(), x))),
# ------------------------- Required methods ---------------------------\
transposeSymmetric := True,
dims := meth(self) Error("Not implemented"); end,
isPermutation := meth(self) Error("Not implemented"); end,
isTerminal := meth(self) Error("Not implemented"); end,
isReal := meth(self) Error("Not implemented"); end,
isInplace := self >> Rows(self)=Cols(self) and let(ch:=self.children(), Cond(Length(ch)=0, false, ForAll(ch, x->x.isInplace()))),
children := meth(self) return []; end,
numChildren := meth(self) return 0; end,
child := meth(self,n) Error("Not implemented"); end,
setChild := meth(self,n,what) Error("Not implemented"); end,
toAMat := meth(self) Error("Not implemented"); end,
transpose := meth(self) Error("Not implemented"); end,
conjTranspose := meth(self) Error("Not implemented"); end,
));
#F <SPL> * <SPL>
#F <scalar> * <SPL>
#F is equivalent to ComposeSPL and ScalarMultiple resp.
#F
SPLOps.\* := (S1, S2) ->
Cond(IsSPL(S1) and IsSPL(S2), Compose(S1, S2),
IsSPL(S2), Scale(S1, S2),
IsSPL(S1), Scale(S2, S1),
Error("do not know how to compute <S1> * <S2>"));
#F <SPL> + <SPL>
#F is equivalent to SUM(<S1>, <S2>)
#F
SPLOps.\+ := (S1, S2) ->
Cond(IsSPL(S1) and IsSPL(S2), SUM(S1, S2),
Error("do not know how to compute <S1> + <S2>"));
#F S1 ^ S2
#F is equivalent to ConjugateSPL(S1, S2).
#F
SPLOps.\^ := (S1, S2) ->
When(IsSPL(S1) and IsSPL(S2),
Conjugate(S1, S2),
Error("do not know how to compute S1 ^ S2"));
|
Require Import CoRN.algebra.RSetoid.
Require Import CoRN.metric2.Metric.
Require Import CoRN.metric2.UniformContinuity.
Require Import
Coq.QArith.QArith
MathClasses.theory.setoids (* Equiv Prop *) MathClasses.theory.products
MathClasses.implementations.stdlib_rationals (*Qinf*) (*Qpossec QposInf QnonNeg*) MathClasses.interfaces.abstract_algebra MathClasses.implementations.QType_rationals MathClasses.interfaces.additional_operations.
Require CoRN.model.structures.Qinf.
(*Import (*QnonNeg.notations*) QArith.*)
Require Import CoRN.tactics.Qauto Coq.QArith.QOrderedType.
(*Require Import orders.*)
Require Import MathClasses.theory.rings MathClasses.theory.dec_fields MathClasses.orders.rings MathClasses.orders.dec_fields MathClasses.theory.nat_pow.
Require Import MathClasses.interfaces.naturals MathClasses.interfaces.orders.
Import peano_naturals.
Require Import CoRN.reals.fast.CRGeometricSum.
Import Qround Qpower Qinf.notations Qinf.coercions.
(* Set Printing Coercions.*)
Definition ext_plus {A} `{Plus B} : Plus (A -> B) := λ f g x, f x + g x.
#[global]
Hint Extern 10 (Plus (_ -> _)) => apply @ext_plus : typeclass_instances.
Definition ext_negate {A} `{Negate B} : Negate (A -> B) := λ f x, - (f x).
#[global]
Hint Extern 10 (Negate (_ -> _)) => apply @ext_negate : typeclass_instances.
(* The definitions above replace the following.
Notation "f +1 g" := (λ x, f x + g x) (at level 50, left associativity).*)
Definition comp_inf {X Z : Type} (g : Q -> Z) (f : X -> Qinf) (inf : Z) (x : X) :=
match (f x) with
| Qinf.finite y => g y
| Qinf.infinite => inf
end.
(* [po_proper'] is useful for proving [a2 ≤ b2] from [H : a1 ≤ b1] when
[a1 = a2] and [b1 = b2]. Then [apply (po_proper' H)] generates [a1 = a2]
and [b1 = b2]. Should it be moved to MathClasses? *)
Lemma po_proper' `{PartialOrder A} {x1 x2 y1 y2 : A} :
x1 ≤ y1 -> x1 = x2 -> y1 = y2 -> x2 ≤ y2.
Proof. intros A1 A2 A3; now apply (po_proper _ _ A2 _ _ A3). Qed.
(* This is a special case of lt_ne_flip. Do we need it? *)
(*Instance pos_ne_0 : forall `{StrictSetoidOrder A} `{Zero A} (x : A),
PropHolds (0 < x) -> PropHolds (x ≠ 0).
Proof. intros; now apply lt_ne_flip. Qed.*)
Definition ext_equiv' `{Equiv A} `{Equiv B} : Equiv (A → B) :=
λ f g, ∀ x : A, f x = g x.
Infix "=1" := ext_equiv' (at level 70, no associativity) : type_scope.
Lemma ext_equiv_l `{Setoid A, Setoid B} (f g : A -> B) :
Proper ((=) ==> (=)) f -> f =1 g -> f = g.
Proof. intros P eq1_f_g x y eq_x_y; rewrite eq_x_y; apply eq1_f_g. Qed.
Lemma ext_equiv_r `{Setoid A, Setoid B} (f g : A -> B) :
Proper ((=) ==> (=)) g -> f =1 g -> f = g.
Proof. intros P eq1_f_g x y eq_x_y; rewrite <- eq_x_y; apply eq1_f_g. Qed.
(*Ltac MCQconst t :=
match t with
(*| @zero Q _ _ => constr:(Qmake Z0 xH)
| @one Q _ _ => constr:(Qmake (Zpos xH) xH)*)
| _ => Qcst t
end.
Add Field Q : (stdlib_field_theory Q)
(decidable Qeq_bool_eq,
completeness Qeq_eq_bool,
constants [MCQconst]).
Goal forall x y : Q, (1#1)%Q * x = x.
intros x y. ring.*)
(*
Local Notation Qnn := QnonNeg.T.
Instance Qnn_eq : Equiv Qnn := eq.
Instance Qnn_zero : Zero Qnn := QnonNeg.zero.
Instance Qnn_one : One Qnn := QnonNeg.one.
Instance Qnn_plus : Plus Qnn := QnonNeg.plus.
Instance Qnn_mult : Mult Qnn := QnonNeg.mult.
Instance Qnn_inv : DecRecip Qnn := QnonNeg.inv.
Instance Qpos_eq : Equiv Qpos := Qpossec.QposEq.
Instance Qpos_one : One Qpos := Qpossec.Qpos_one.
Instance Qpos_plus : Plus Qpos := Qpossec.Qpos_plus.
Instance Qpos_mult : Mult Qpos := Qpossec.Qpos_mult.
Instance Qpos_inv : DecRecip Qpos := Qpossec.Qpos_inv.
Instance Qinf_one : One Qinf := 1%Q.
*)
#[global]
Instance Qinf_le : Le Qinf := Qinf.le.
#[global]
Instance Qinf_lt : Lt Qinf := Qinf.lt.
(*
Ltac mc_simpl := unfold
equiv, zero, one, plus, negate, mult, dec_recip, le, lt.
Ltac Qsimpl' := unfold
Qnn_eq, Qnn_zero, Qnn_one, Qnn_plus, Qnn_mult, Qnn_inv,
QnonNeg.eq, QnonNeg.zero, QnonNeg.one, QnonNeg.plus, QnonNeg.mult, QnonNeg.inv,
Qpos_eq, Qpos_one, Qpos_plus, Qpos_mult, Qpos_inv,
Qpossec.QposEq, Qpossec.Qpos_one, Qpossec.Qpos_plus, Qpossec.Qpos_mult, Qpossec.Qpos_inv,
Qinf.eq, Qinf.lt, Qinf_lt, Qinf_one, Zero_instance_0 (* Zero Qinf *),
Q_eq, Q_lt, Q_le, Q_0, Q_1, Q_opp, Q_plus, Q_mult, Q_recip;
mc_simpl;
unfold to_Q, QposAsQ;
simpl.
Ltac nat_simpl := unfold
nat_equiv, nat_0, nat_1, nat_plus, nat_plus, nat_mult, nat_le, nat_lt;
mc_simpl;
simpl.
Tactic Notation "Qsimpl" hyp_list(A) := revert A; Qsimpl'; intros A.
*)
Bind Scope mc_scope with Q.
(*Section QField.*)
Add Field Q : (stdlib_field_theory Q).
Class MetricSpaceBall (X : Type) : Type := mspc_ball: Qinf → relation X.
Local Notation ball := mspc_ball.
(* In the proof of Banach fixpoint theorem we have to use arithmetic
expressions such as q^n / (1 - q) when 0 <= q < 1 as the ball radius. If
the radius is in Qnn (ie., QnonNeg.T), then we have to prove that 1 - q :
Qnn. It seems more convenient to have the radius live in Q and have the
axiom that no points are separated by a negative distance. *)
Class ExtMetricSpaceClass (X : Type) `{MetricSpaceBall X} : Prop := {
mspc_radius_proper : Proper ((=) ==> (≡) ==> (≡) ==> iff) ball;
mspc_inf: ∀ x y, ball Qinf.infinite x y;
mspc_negative: ∀ (e: Q), e < 0 → ∀ x y, ~ ball e x y;
mspc_refl:> ∀ e : Q, 0 ≤ e → Reflexive (ball e);
mspc_symm:> ∀ e, Symmetric (ball e);
mspc_triangle: ∀ (e1 e2: Q) (a b c: X),
ball e1 a b → ball e2 b c → ball (e1 + e2) a c;
mspc_closed: ∀ (e: Q) (a b: X),
(∀ d: Q, 0 < d -> ball (e + d) a b) → ball e a b
}.
Class MetricSpaceDistance (X : Type) := msd : X -> X -> Q.
Class MetricSpaceClass (X : Type) `{ExtMetricSpaceClass X} `{MetricSpaceDistance X} : Prop :=
mspc_distance : forall x1 x2 : X, ball (msd x1 x2) x1 x2.
Section ExtMetricSpace.
Context `{ExtMetricSpaceClass X}.
Global Instance mspc_equiv : Equiv X := λ x1 x2, ball 0%Q x1 x2.
Global Instance mspc_setoid : Setoid X.
Proof.
constructor.
+ now apply mspc_refl.
+ apply mspc_symm.
+ intros x1 x2 x3 eq12 eq23.
unfold mspc_equiv, equiv; change 0%Q with (0%Q + 0%Q); now apply mspc_triangle with (b := x2).
Qed.
Global Instance mspc_proper : Proper ((=) ==> (=) ==> (=) ==> iff) ball.
Proof.
assert (A := @mspc_radius_proper X _ _).
intros e1 e2 Ee1e2 x1 x2 Ex1x2 y1 y2 Ey1y2;
destruct e1 as [e1 |]; destruct e2 as [e2 |]; split; intro B; try apply mspc_inf;
try (unfold Qinf.eq, equiv in *; contradiction).
+ mc_setoid_replace e2 with (0 + (e2 + 0)) by ring.
apply mspc_triangle with (b := x1); [apply mspc_symm, Ex1x2 |].
now apply mspc_triangle with (b := y1); [rewrite <- Ee1e2 |].
+ mc_setoid_replace e1 with (0 + (e1 + 0)) by ring.
apply mspc_triangle with (b := x2); [apply Ex1x2 |].
now apply mspc_triangle with (b := y2); [rewrite Ee1e2 | apply mspc_symm].
Qed.
Lemma mspc_refl' (e : Qinf) : 0 ≤ e → Reflexive (ball e).
Proof.
intros E. destruct e as [e |].
+ apply mspc_refl, E.
+ intro x; apply mspc_inf.
Qed.
Lemma mspc_triangle' :
∀ (q1 q2 : Q) (x2 x1 x3 : X) (q : Q),
q1 + q2 = q → ball q1 x1 x2 → ball q2 x2 x3 → ball q x1 x3.
Proof.
intros q1 q2 x2 x1 x3 q A1 A2 A3. rewrite <- A1. eapply mspc_triangle; eauto.
Qed.
Lemma mspc_monotone :
∀ q1 q2 : Q, q1 ≤ q2 -> ∀ x y : X, ball q1 x y → ball q2 x y.
Proof.
intros q1 q2 A1 x y A2.
apply (mspc_triangle' q1 (q2 - q1) y); [ring | trivial |]. apply mspc_refl.
apply (order_preserving (+ (-q1))) in A1. now rewrite plus_negate_r in A1.
Qed.
Lemma mspc_monotone' :
∀ q1 q2 : Qinf, q1 ≤ q2 -> ∀ x y : X, ball q1 x y → ball q2 x y.
Proof.
intros [q1 |] [q2 |] A1 x y A2; try apply mspc_inf.
+ apply (mspc_monotone q1); trivial.
+ elim A1.
Qed.
Lemma mspc_eq : ∀ x y : X, (∀ e : Q, 0 < e -> ball e x y) ↔ x = y.
Proof.
intros x y; split; intro A.
+ apply mspc_closed; intro d. change 0%Q with (@zero Q _); rewrite plus_0_l; apply A.
+ intros e e_pos. apply (mspc_monotone 0); trivial; solve_propholds.
Qed.
Lemma radius_nonneg (x y : X) (e : Q) : ball e x y -> 0 ≤ e.
Proof.
intro A. destruct (le_or_lt 0 e) as [A1 | A1]; [trivial |].
contradict A; now apply mspc_negative.
Qed.
End ExtMetricSpace.
Section MetricSpace.
Context `{MetricSpaceClass X}.
Lemma msd_nonneg (x1 x2 : X) : 0 ≤ msd x1 x2.
Proof. apply (radius_nonneg x1 x2), mspc_distance. Qed.
End MetricSpace.
Section SubMetricSpace.
Context `{ExtMetricSpaceClass X} (P : X -> Prop).
Global Instance sig_mspc_ball : MetricSpaceBall (sig P) := λ e x y, ball e (`x) (`y).
Global Instance sig_mspc : ExtMetricSpaceClass (sig P).
Proof.
constructor.
+ repeat intro; rapply mspc_radius_proper; congruence.
+ repeat intro; rapply mspc_inf.
+ intros; now rapply mspc_negative.
+ repeat intro; now rapply mspc_refl.
+ repeat intro; now rapply mspc_symm.
+ repeat intro; rapply mspc_triangle; eauto.
+ repeat intro; now rapply mspc_closed.
Qed.
Context {d : MetricSpaceDistance X} {MSC : MetricSpaceClass X}.
Global Instance sig_msd : MetricSpaceDistance (sig P) := λ x y, msd (`x) (`y).
Global Instance sig_mspc_distance : MetricSpaceClass (sig P).
Proof. intros x1 x2; apply: mspc_distance. Qed.
End SubMetricSpace.
Section ProductMetricSpace.
Context `{ExtMetricSpaceClass X, ExtMetricSpaceClass Y}.
Global Instance Linf_product_metric_space_ball : MetricSpaceBall (X * Y) :=
λ e a b, ball e (fst a) (fst b) /\ ball e (snd a) (snd b).
Lemma product_ball_proper : Proper ((=) ==> (≡) ==> (≡) ==> iff) ball.
Proof.
intros e1 e2 A1 a1 a2 A2 b1 b2 A3.
unfold mspc_ball, Linf_product_metric_space_ball.
rewrite A1, A2, A3; reflexivity.
Qed.
Global Instance Linf_product_metric_space_class : ExtMetricSpaceClass (X * Y).
Proof.
constructor.
+ apply product_ball_proper.
+ intros x y; split; apply mspc_inf.
+ intros e e_neg x y [A _]. eapply (@mspc_negative X); eauto.
+ intros e e_nonneg x; split; apply mspc_refl; trivial.
+ intros e a b [A1 A2]; split; apply mspc_symm; trivial.
+ intros e1 e2 a b c [A1 A2] [B1 B2]; split; eapply mspc_triangle; eauto.
+ intros e a b A; split; apply mspc_closed; firstorder.
Qed.
Context {dx : MetricSpaceDistance X} {dy : MetricSpaceDistance Y}
{MSCx : MetricSpaceClass X} {MSCy : MetricSpaceClass Y}.
(* Need consistent names of instances for sig, product and func *)
Global Instance Linf_product_msd : MetricSpaceDistance (X * Y) :=
λ a b, join (msd (fst a) (fst b)) (msd (snd a) (snd b)).
Global Instance Linf_product_mspc_distance : MetricSpaceClass (X * Y).
Proof.
intros z1 z2; split.
(* Without unfolding Linf_product_msd, the following [apply join_ub_l] fails *)
+ apply (mspc_monotone (msd (fst z1) (fst z2)));
[unfold msd, Linf_product_msd; apply join_ub_l | apply mspc_distance].
+ apply (mspc_monotone (msd (snd z1) (snd z2)));
[unfold msd, Linf_product_msd; apply join_ub_r | apply mspc_distance].
Qed.
End ProductMetricSpace.
(** We define [Func T X Y] if there is a coercion func from T to (X -> Y),
i.e., T is a type of functions. It can be instatiated with (locally)
uniformly continuous function, (locally) Lipschitz functions, contractions
and so on. For instances T of [Func] we can define supremum metric ball
(i.e., L∞ metric) and prove that T is a metric space. [Func T X Y] is
similar to [Cast T (X -> Y)], but [cast] has types as explicit arguments,
so for [f : T] one would have to write [cast _ _ f x] instead of [func f x]. *)
Class Func (T X Y : Type) := func : T -> X -> Y.
Section FunctionMetricSpace.
Context {X Y T : Type} `{Func T X Y, NonEmpty X, ExtMetricSpaceClass Y}.
(* For any type that is convertible to functions we want to define the
supremum metric. This would give rise to an equality and a setoid
([mspc_equiv] and [mspc_setoid]). Thus, when Coq needs equality on any type
T at all, it may try to prove that T is a metric space by showing that T is
convertible to functions, i.e., there is an in instance of [Func T X Y] for
some types X, Y. This is why we make [Func T X Y] the first assumption
above. This way, if there is no instance of this class, the search for
[MetricSpaceBall T] fails quickly and Coq starts looking for an equality on
T using other means. If we make, for example, [ExtMetricSpaceClass Y] the
first assumption, Coq may eneter in an infinite loop: To find
[MetricSpaceBall T] it will look for [ExtMetricSpaceClass Y] for some
uninstantiated Y, for this in needs [MetricSpaceBall Y] and so on. This is
all because Coq proves assumptions (i.e., searches instances of classes) in
the order of the assumptions. *)
Global Instance Linf_func_metric_space_ball : MetricSpaceBall T :=
λ e f g, forall x, ball e (func f x) (func g x).
Lemma func_ball_proper : Proper ((=) ==> (≡) ==> (≡) ==> iff) (ball (X := T)).
Proof.
intros q1 q2 A1 f1 f2 A2 g1 g2 A3; rewrite A2, A3.
split; intros A4 x; [rewrite <- A1 | rewrite A1]; apply A4.
Qed.
Lemma Linf_func_metric_space_class : ExtMetricSpaceClass T.
Proof.
match goal with | H : NonEmpty X |- _ => destruct H as [x0] end.
constructor.
+ apply func_ball_proper.
+ intros f g x; apply mspc_inf.
+ intros e e_neg f g A. specialize (A x0). eapply mspc_negative; eauto.
+ intros e e_nonneg f x; now apply mspc_refl.
+ intros e f g A x; now apply mspc_symm.
+ intros e1 e2 f g h A1 A2 x. now apply mspc_triangle with (b := func g x).
+ intros e f g A x. apply mspc_closed; intros d A1. now apply A.
Qed.
End FunctionMetricSpace.
Section UniformContinuity.
Context `{MetricSpaceBall X, MetricSpaceBall Y}.
Class IsUniformlyContinuous (f : X -> Y) (mu : Q -> Qinf) := {
uc_pos : forall e : Q, 0 < e -> (0 < mu e);
uc_prf : ∀ (e : Q) (x1 x2: X), 0 < e -> ball (mu e) x1 x2 → ball e (f x1) (f x2)
}.
Global Arguments uc_pos f mu {_} e _.
Global Arguments uc_prf f mu {_} e x1 x2 _ _.
Record UniformlyContinuous := {
uc_func :> X -> Y;
uc_mu : Q -> Qinf;
uc_proof : IsUniformlyContinuous uc_func uc_mu
}.
(* We will prove next that IsUniformlyContinuous is a subclass of Proper,
i.e., uniformly continuous functions are morphisms. But if we have [f :
UniformlyContinuous], in order for uc_func f to be considered a morphism,
we need to declare uc_proof an instance. *)
Global Existing Instance uc_proof.
Global Instance uc_proper {H1 : ExtMetricSpaceClass X} {H2 : ExtMetricSpaceClass Y}
{f : X → Y} {mu : Q → Qinf} {_ : IsUniformlyContinuous f mu}
: Proper ((=) ==> (=)) f.
Proof.
intros x1 x2 A. apply -> mspc_eq. intros e e_pos. apply (uc_prf f mu); trivial.
pose proof (uc_pos f mu e e_pos) as ?.
destruct (mu e); [apply mspc_eq; trivial | apply mspc_inf].
Qed.
End UniformContinuity.
Global Arguments UniformlyContinuous X {_} Y {_}.
(* In [compose_uc] below, if we don't explicitly specify [Z] as an
argument, then [`{MetricSpaceBall Z}] does not generalize [Z] but rather
interprets it as integers. For symmetry we specify [X] and [Y] as well. *)
Global Instance compose_uc {X Y Z : Type}
`{MetricSpaceBall X, ExtMetricSpaceClass Y, MetricSpaceBall Z}
(f : X -> Y) (g : Y -> Z) (f_mu g_mu : Q -> Qinf)
`{!IsUniformlyContinuous f f_mu, !IsUniformlyContinuous g g_mu} :
IsUniformlyContinuous (g ∘ f) (comp_inf f_mu g_mu Qinf.infinite).
Proof.
constructor.
+ intros e e_pos. assert (0 < g_mu e) by (apply (uc_pos g); trivial).
unfold comp_inf. destruct (g_mu e); [apply (uc_pos f) |]; trivial.
+ intros e x1 x2 e_pos A. unfold compose. apply (uc_prf g g_mu); trivial.
assert (0 < g_mu e) by (apply (uc_pos g); trivial).
unfold comp_inf in A. destruct (g_mu e) as [e' |]; [| apply mspc_inf].
apply (uc_prf f f_mu); trivial.
Qed.
Global Instance uniformly_continuous_func `{MetricSpaceBall X, MetricSpaceBall Y} :
Func (UniformlyContinuous X Y) X Y := λ f, f.
#[global]
Hint Extern 10 (ExtMetricSpaceClass (UniformlyContinuous _ _)) =>
apply @Linf_func_metric_space_class : typeclass_instances.
Section LocalUniformContinuity.
Context `{MetricSpaceBall X, MetricSpaceBall Y}.
Definition restrict (f : X -> Y) (x : X) (r : Q) : sig (ball r x) -> Y :=
f ∘ @proj1_sig _ _.
(* See the remark about llip_prf below about the loop between
IsUniformlyContinuous and IsLocallyUniformlyContinuous *)
Class IsLocallyUniformlyContinuous (f : X -> Y) (lmu : X -> Q -> Q -> Qinf) :=
luc_prf :> forall (x : X) (r : Q), IsUniformlyContinuous (restrict f x r) (lmu x r).
Global Arguments luc_prf f lmu {_} x r.
Global Instance uc_ulc (f : X -> Y)
{mu : Q → Qinf} {_ : IsUniformlyContinuous f mu}
: IsLocallyUniformlyContinuous f (λ _ _, mu).
Proof.
intros x r. constructor; [now apply (uc_pos f) |].
intros e [x1 A1] [x2 A2] e_pos A. now apply (uc_prf f mu).
Qed.
Global Instance luc_proper
{_ : ExtMetricSpaceClass X} {_ : ExtMetricSpaceClass Y}
(f : X -> Y) `{!IsLocallyUniformlyContinuous f lmu} : Proper ((=) ==> (=)) f.
Proof.
intros x1 x2 A. apply -> mspc_eq. intros e e_pos.
assert (A1 : ball 1%Q x1 x1) by (apply mspc_refl; Qauto_nonneg).
assert (A2 : ball 1%Q x1 x2) by (rewrite A; apply mspc_refl; Qauto_nonneg).
change (ball e (restrict f x1 1 (exist _ x1 A1)) (restrict f x1 1 (exist _ x2 A2))).
unfold IsLocallyUniformlyContinuous in *. apply (uc_prf _ (lmu x1 1)); [easy |].
change (ball (lmu x1 1 e) x1 x2).
rewrite <- A. assert (0 < lmu x1 1 e) by now apply (uc_pos (restrict f x1 1)).
destruct (lmu x1 1 e) as [q |]; [apply mspc_refl; solve_propholds | apply mspc_inf].
Qed.
Lemma luc (f : X -> Y) `{IsLocallyUniformlyContinuous f lmu} (r e : Q) (a x y : X) :
0 < e -> ball r a x -> ball r a y -> ball (lmu a r e) x y -> ball e (f x) (f y).
Proof.
intros e_pos A1 A2 A3.
change (f x) with (restrict f a r (exist _ x A1)).
change (f y) with (restrict f a r (exist _ y A2)).
apply uc_prf with (mu := lmu a r); trivial.
(* The predicate symbol of the goal is IsUniformlyContinuous, which is a
type class. Yet, without [trivial] above, instead of solving it by [apply
H3], Coq gives it as a subgoal. *)
Qed.
End LocalUniformContinuity.
Section Lipschitz.
Context `{MetricSpaceBall X, MetricSpaceBall Y}.
Class IsLipschitz (f : X -> Y) (L : Q) := {
lip_nonneg : 0 ≤ L;
lip_prf : forall (x1 x2 : X) (e : Q), ball e x1 x2 -> ball (L * e) (f x1) (f x2)
}.
Global Arguments lip_nonneg f L {_} _.
Global Arguments lip_prf f L {_} _ _ _ _.
Record Lipschitz := {
lip_func :> X -> Y;
lip_const : Q;
lip_proof : IsLipschitz lip_func lip_const
}.
Definition lip_modulus (L e : Q) : Qinf :=
if (decide (L = 0)) then Qinf.infinite else e / L.
Lemma lip_modulus_pos (L e : Q) : 0 ≤ L -> 0 < e -> 0 < lip_modulus L e.
Proof.
intros L_nonneg e_pos. unfold lip_modulus.
destruct (decide (L = 0)) as [A1 | A1]; [apply I |].
apply not_symmetry in A1.
change (0 < e / L). (* Changes from Qinf, which is not declared as ordered ring, to Q *)
assert (0 < L) by now apply QOrder.le_neq_lt. Qauto_pos.
Qed.
(* It is nice to declare only [MetricSpaceBall X] above because this is all
we need to know about X to define [IsLipschitz]. But for the following
theorem we also need [ExtMetricSpaceClass X], [MetricSpaceDistance X] and
[MetricSpaceClass X]. How to add these assumptions? Saying
[`{MetricSpaceClass X}] would add a second copy of [MetricSpaceBall X]. We
write the names EM and m below because "Anonymous variables not allowed in
contexts" *)
Context {EM : ExtMetricSpaceClass X} {m : MetricSpaceDistance X}.
Global Instance lip_uc {_ : MetricSpaceClass X} {_ : ExtMetricSpaceClass Y}
(f : X -> Y) `{!IsLipschitz f L} :
IsUniformlyContinuous f (lip_modulus L).
Proof.
constructor.
+ intros. apply lip_modulus_pos; [| assumption]. now apply (lip_nonneg f L).
+ unfold lip_modulus. intros e x1 x2 A1 A2. destruct (decide (L = 0)) as [A | A].
- apply mspc_eq; [| easy]. unfold canonical_names.equiv, mspc_equiv. rewrite <- (Qmult_0_l (msd x1 x2)), <- A.
now apply lip_prf; [| apply mspc_distance].
- mc_setoid_replace e with (L * (e / L)) by now field.
now apply lip_prf.
Qed.
End Lipschitz.
(* To be able to say [Lipschitz X Y] instead of [@Lipschitz X _ Y _] *)
Global Arguments Lipschitz X {_} Y {_}.
(* Allows concluding [IsLipschitz f _] from [f : Lipschitz] *)
Global Existing Instance lip_proof.
(* We need [ExtMetricSpaceClass Z] because we rewrite the ball radius, so
[mspc_radius_proper] is required. See comment before [compose_uc] for why
[{X Y Z : Type}] is necessary. *)
Global Instance compose_lip {X Y Z : Type}
`{MetricSpaceBall X, MetricSpaceBall Y, ExtMetricSpaceClass Z}
(f : X -> Y) (g : Y -> Z) (Lf Lg : Q)
`{!IsLipschitz f Lf, !IsLipschitz g Lg} :
IsLipschitz (g ∘ f) (Lg * Lf).
Proof.
constructor.
+ apply nonneg_mult_compat; [apply (lip_nonneg g), _ | apply (lip_nonneg f), _].
+ intros x1 x2 e A.
(* [rewrite <- mult_assoc] does not work *)
mc_setoid_replace (Lg * Lf * e) with (Lg * (Lf * e)) by (symmetry; apply simple_associativity).
now apply (lip_prf g Lg), (lip_prf f Lf).
Qed.
(* [ExtMetricSpaceClass X] is needed for rewriting *)
Global Instance id_lip `{ExtMetricSpaceClass X} : IsLipschitz Datatypes.id 1.
Proof.
constructor; [solve_propholds |]. intros; now rewrite mult_1_l.
Qed.
Section LocallyLipschitz.
Context `{MetricSpaceBall X, MetricSpaceBall Y}.
(* Delaring llip_prf below an instance introduces a loop between
[IsLipschitz] and [IsLocallyLipschitz]. But if we are searching for a proof
of [IsLipschitz f _] for a specific term [f], then Coq should not enter an
infinite loop because that would require unifying [f] with [restrict _ _ _].
We need this instance to apply [lip_nonneg (restrict f x r) _] in order
to prove [0 ≤ Lf x r] when [IsLocallyLipschitz f Lf]. *)
(* We make an assumption [0 ≤ r] in llip_prf below to make proving that
functions are locally Lipschitz easier. As a part of such proof, one needs
to show that [0 ≤ L x r] ([lip_nonneg]). Proving this under the assumption
[0 ≤ r] may allow having simpler definitions of the uniform [L]. In
particular, integral_lipschitz in AbstractIntegration.v defines [L] as
[λ a r, abs (f a) + L' a r * r]. *)
Class IsLocallyLipschitz (f : X -> Y) (L : X -> Q -> Q) :=
llip_prf :> forall (x : X) (r : Q), PropHolds (0 ≤ r) -> IsLipschitz (restrict f x r) (L x r).
Global Arguments llip_prf f L {_} x r _.
Global Instance lip_llip (f : X -> Y) `{!IsLipschitz f L} : IsLocallyLipschitz f (λ _ _, L).
Proof.
intros x r. constructor; [now apply (lip_nonneg f) |].
intros [x1 x1b] [x2 x2b] e A. change (ball (L * e) (f x1) (f x2)). now apply lip_prf.
Qed.
Lemma llip `{!ExtMetricSpaceClass X} (f : X -> Y) `{IsLocallyLipschitz f L} (r e : Q) (a x y : X) :
ball r a x -> ball r a y -> ball e x y -> ball (L a r * e) (f x) (f y).
Proof.
intros A1 A2 A3.
change (f x) with (restrict f a r (exist _ x A1)).
change (f y) with (restrict f a r (exist _ y A2)).
assert (0 ≤ r) by now apply (radius_nonneg a x).
apply (lip_prf _ (L a r)); trivial.
Qed.
Record LocallyLipschitz := {
llip_func :> X -> Y;
llip_const : X -> Q -> Q;
llip_proof : IsLocallyLipschitz llip_func llip_const
}.
End LocallyLipschitz.
Global Arguments LocallyLipschitz X {_} Y {_}.
#[global]
Instance locally_lipschitz_func `{MetricSpaceBall X, MetricSpaceBall Y} :
Func (LocallyLipschitz X Y) X Y := λ f, f.
#[global]
Hint Extern 10 (ExtMetricSpaceClass (LocallyLipschitz _ _)) =>
apply @Linf_func_metric_space_class : typeclass_instances.
Notation "X LL-> Y" := (LocallyLipschitz X Y) (at level 55, right associativity).
Section Contractions.
Context `{MetricSpaceBall X, MetricSpaceBall Y}.
Class IsContraction (f : X -> Y) (q : Q) := {
contr_prf :> IsLipschitz f q;
contr_lt_1 : q < 1
}.
Global Arguments contr_lt_1 f q {_}.
Global Arguments contr_prf f q {_}.
Record Contraction := {
contr_func : X -> Y;
contr_const : Q;
contr_proof : IsContraction contr_func contr_const
}.
Global Instance const_contr `{!ExtMetricSpaceClass Y} (c : Y) : IsContraction (λ x : X, c) 0.
Proof.
constructor.
+ constructor.
- reflexivity.
- intros; apply mspc_refl.
rewrite mult_0_l; reflexivity.
+ solve_propholds.
Qed.
(* Do we need the following?
Global Instance contr_to_uc `(IsContraction f q) :
IsUniformlyContinuous f (λ e, if (decide (q = 0)) then Qinf.infinite else (e / q)).
Proof. apply _. Qed.*)
End Contractions.
Global Arguments Contraction X {_} Y {_}.
Global Instance : PreOrder Qinf.le.
Proof.
constructor.
+ intros [x |]; [apply Qle_refl | easy].
+ intros [x |] [y |] [z |]; solve [intros [] | intros _ [] | easy | apply Qle_trans].
Qed.
Global Instance : AntiSymmetric Qinf.le.
Proof.
intros [x |] [y |] A B; [apply Qle_antisym | elim B | elim A |]; easy.
Qed.
Global Instance : PartialOrder Qinf.le.
Proof. constructor; apply _. Qed.
Global Instance : TotalRelation Qinf.le.
Proof.
intros [x |] [y |]; [change (x ≤ y \/ y ≤ x); apply total, _ | left | right | left]; easy.
Qed.
Global Instance : TotalOrder Qinf.le.
Proof. constructor; apply _. Qed.
Global Instance : ∀ x y : Qinf, Decision (x ≤ y).
intros [x |] [y |]; [change (Decision (x ≤ y)); apply _ | left | right | left]; easy.
Defined.
Import minmax.
(* Instances above allow using min and max for Qinf *)
Section TotalOrderLattice.
Context `{TotalOrder A} `{Lt A} `{∀ x y: A, Decision (x ≤ y)}.
Lemma min_ind (P : A -> Prop) (x y : A) : P x → P y → P (min x y).
Proof. unfold min, sort. destruct (decide_rel _ x y); auto. Qed.
Lemma lt_min (x y z : A) : z < x -> z < y -> z < min x y.
Proof. apply min_ind. Qed.
End TotalOrderLattice.
Section ProductSpaceFunctions.
Definition diag {X : Type} (x : X) : X * X := (x, x).
Global Instance diag_lip `{ExtMetricSpaceClass X} : IsLipschitz (@diag X) 1.
Proof.
constructor.
+ solve_propholds.
+ intros x1 x2 e A. rewrite mult_1_l. now split.
Qed.
Definition together {X1 Y1 X2 Y2 : Type} (f1 : X1 -> Y1) (f2 : X2 -> Y2) : X1 * X2 -> Y1 * Y2 :=
λ p, (f1 (fst p), f2 (snd p)).
(*Global Instance together_lip
`{ExtMetricSpaceClass X1, ExtMetricSpaceClass Y1, ExtMetricSpaceClass X2, ExtMetricSpaceClass Y2}
(f1 : X1 -> Y1) (f2 : X2 -> Y2)
`{!IsLipschitz f1 L1, !IsLipschitz f2 L2} : IsLipschitz (together f1 f2) (join L1 L2).
(* What if we define the Lipschitz constant for [together f1 f2] to be [max
L1 L2], where [max] is the name of an instance of [Join A] in
orders.minmax? In fact, [Check _ : Join Q] returns [max]. I.e., [join x y]
for [x y : Q] reduces to [max x y]. However, it is difficult to apply
[lattices.join_le_compat_r] to the goal [0 ≤ max L1 L2]. Simple [apply]
does not work (probably because the theorem has to be reduced to match the
goal). As for [apply:] and [rapply], they invoke [refine (@join_le_compat_r
_ _ ...)]. Some of the _ are implicit arguments and type classes (e.g.,
[Equiv] [Le]), and they are instantiated with the instances found first,
which happen to be for [Qinf]. Apparently, unification does not try other
instances. So, [apply:] with type classes is problematic.
[apply: (@lattices.join_le_compat_r Q)] gives "Anomaly: Evd.define: cannot define an evar twice" *)
Proof.
constructor.
+ apply lattices.join_le_compat_r, (lip_nonneg f1 L1).
+ intros z1 z2 e [A1 A2].
(* Below we prove [0 ≤ e] using [radius_nonneg], which requires
[ExtMetricSpaceClass]. Another way is to add the assymption [0 ≤ e] to
[lip_prf], similar to [uc_prf]. *)
assert (0 ≤ e) by now apply (radius_nonneg (fst z1) (fst z2)).
split; simpl.
- apply (mspc_monotone (L1 * e)); [apply (order_preserving (.* e)); apply join_ub_l |].
(* [apply (order_preserving (.* e)), join_ub_l.] does not work *)
apply lip_prf; trivial.
- apply (mspc_monotone (L2 * e)); [apply (order_preserving (.* e)); apply join_ub_r |].
apply lip_prf; trivial.*)
Global Instance together_uc
`{ExtMetricSpaceClass X1, ExtMetricSpaceClass Y1, ExtMetricSpaceClass X2, ExtMetricSpaceClass Y2}
(f1 : X1 -> Y1) (f2 : X2 -> Y2)
`{!IsUniformlyContinuous f1 mu1, !IsUniformlyContinuous f2 mu2} :
IsUniformlyContinuous (together f1 f2) (λ e, min (mu1 e) (mu2 e)).
Proof.
constructor.
+ intros e e_pos. (* [apply min_ind] does not work if the goal has [meet] instead of [min] *)
apply lt_min; [apply (uc_pos f1) | apply (uc_pos f2)]; trivial.
(* [trivial] solves, in particular, [IsUniformlyContinuous f1 mu1], which should
have been solved automatically *)
+ intros e z z' e_pos [A1 A2]. split; simpl.
- apply (uc_prf f1 mu1); trivial.
apply (mspc_monotone' (min (mu1 e) (mu2 e))); [apply: meet_lb_l | trivial].
- apply (uc_prf f2 mu2); trivial.
apply (mspc_monotone' (min (mu1 e) (mu2 e))); [apply: meet_lb_r | trivial].
Qed.
End ProductSpaceFunctions.
Section CompleteMetricSpace.
Context `{MetricSpaceBall X}.
Class IsRegularFunction (f : Q -> X) : Prop :=
rf_prf : forall e1 e2 : Q, 0 < e1 -> 0 < e2 -> ball (e1 + e2) (f e1) (f e2).
Record RegularFunction := {
rf_func :> Q -> X;
rf_proof : IsRegularFunction rf_func
}.
Arguments Build_RegularFunction {_} _.
Global Existing Instance rf_proof.
Global Instance rf_eq : Equiv RegularFunction :=
λ f1 f2, forall e1 e2 : Q, 0 < e1 -> 0 < e2 -> ball (e1 + e2) (f1 e1) (f2 e2).
Context {EM : ExtMetricSpaceClass X}.
Global Instance rf_setoid : Setoid RegularFunction.
Proof.
constructor.
+ intros f e1 e2; apply rf_prf.
+ intros f1 f2 A e1 e2 A1 A2. rewrite plus_comm. now apply mspc_symm, A.
+ intros f1 f2 f3 A1 A2 e1 e3 A3 A4. apply mspc_closed. intros d A5.
mc_setoid_replace (e1 + e3 + d) with ((e1 + d / 2) + (e3 + d / 2))
by (field; change ((2 : Q) ≠ 0); solve_propholds).
apply mspc_triangle with (b := f2 (d / 2));
[apply A1 | rewrite plus_comm; apply A2]; try solve_propholds.
Qed.
Instance rf_msb : MetricSpaceBall RegularFunction :=
λ e f1 f2, forall e1 e2 : Q, 0 < e1 -> 0 < e2 -> ball (e + e1 + e2) (f1 e1) (f2 e2).
Lemma unit_reg (x : X) : IsRegularFunction (λ _, x).
Proof. intros e1 e2 A1 A2; apply mspc_refl; solve_propholds. Qed.
Definition reg_unit (x : X) := Build_RegularFunction (unit_reg x).
Global Instance : Setoid_Morphism reg_unit.
Proof.
constructor; [apply _ .. |].
intros x y eq_x_y e1 e2 e1_pos e2_pos. apply mspc_eq; solve_propholds.
Qed.
Class Limit := lim : RegularFunction -> X.
Class CompleteMetricSpaceClass `{Limit} := cmspc :> Surjective reg_unit (inv := lim).
Definition tends_to (f : RegularFunction) (l : X) :=
forall e : Q, 0 < e -> ball e (f e) l.
Lemma limit_def `{CompleteMetricSpaceClass} (f : RegularFunction) :
forall e : Q, 0 < e -> ball e (f e) (lim f).
Proof.
intros e2 A2. apply mspc_symm; apply mspc_closed.
(* [apply mspc_symm, mspc_closed.] does not work *)
intros e1 A1. change (lim f) with (reg_unit (lim f) e1). rewrite plus_comm.
rapply (surjective reg_unit (inv := lim)); trivial; reflexivity.
Qed.
End CompleteMetricSpace.
Global Arguments RegularFunction X {_}.
Global Arguments Limit X {_}.
Global Arguments CompleteMetricSpaceClass X {_ _ _}.
(* The exclamation mark before Limit avoids introducing a second assumption
MetricSpaceBall X *)
Lemma completeness_criterion `{ExtMetricSpaceClass X, !Limit X} :
CompleteMetricSpaceClass X <-> forall f : RegularFunction X, tends_to f (lim f).
Proof.
split; intro A.
+ intros f e2 A2. apply mspc_symm, mspc_closed.
intros e1 A1. change (lim f) with (reg_unit (lim f) e1). rewrite plus_comm.
rapply (surjective reg_unit (A := X) (inv := lim)); trivial; reflexivity.
+ constructor; [| apply _].
apply ext_equiv_r; [apply _|].
intros f e1 e2 e1_pos e2_pos.
apply (mspc_monotone e2); [apply nonneg_plus_le_compat_l; solve_propholds |].
now apply mspc_symm, A.
Qed.
Section UCFComplete.
Context `{NonEmpty X, ExtMetricSpaceClass X, CompleteMetricSpaceClass Y}.
Program Definition pointwise_regular
(F : RegularFunction (UniformlyContinuous X Y)) (x : X) : RegularFunction Y :=
Build_RegularFunction (λ e, F e x) _.
Next Obligation. intros e1 e2 e1_pos e2_pos; now apply F. Qed.
Global Program Instance ucf_limit : Limit (UniformlyContinuous X Y) :=
λ F, Build_UniformlyContinuous
(λ x, lim (pointwise_regular F x))
(λ e, uc_mu (F (e/3)) (e/3))
_.
Next Obligation.
constructor.
* intros e e_pos.
destruct (F (e/3)) as [g ? ?]; simpl; apply uc_pos with (f := g); trivial.
apply Q.Qmult_lt_0_compat; auto with qarith.
* intros e x1 x2 e_pos A.
apply (mspc_triangle' (e/3) (e/3 + e/3) (F (e/3) x1)); [field; discriminate | |].
+ apply mspc_symm. change ((F (e / 3)) x1) with (pointwise_regular F x1 (e/3)).
(* without [change], neither [apply limit_def] nor [rapply limit_def] work *)
apply completeness_criterion, Q.Qmult_lt_0_compat; auto with qarith.
+ apply mspc_triangle with (b := F (e / 3) x2).
- destruct (F (e/3)); eapply uc_prf; eauto.
apply Q.Qmult_lt_0_compat; auto with qarith.
- change ((F (e / 3)) x2) with (pointwise_regular F x2 (e/3)).
apply completeness_criterion, Q.Qmult_lt_0_compat; auto with qarith.
Qed.
Global Instance : CompleteMetricSpaceClass (UniformlyContinuous X Y).
Proof.
apply completeness_criterion. intros F e e_pos x.
change (func (lim F) x) with (lim (pointwise_regular F x)).
change (func (F e) x) with (pointwise_regular F x e).
now apply completeness_criterion.
Qed.
End UCFComplete.
Definition seq A := nat -> A.
#[global]
Hint Unfold seq : typeclass_instances.
(* This unfolds [seq X] as [nat -> X] and allows ext_equiv to find an
instance of [Equiv (seq X)] *)
Section SequenceLimits.
Context `{ExtMetricSpaceClass X}.
Definition seq_lim (x : seq X) (a : X) (N : Q -> nat) :=
forall e : Q, 0 < e -> forall n : nat, N e ≤ n -> ball e (x n) a.
(*Global Instance : Proper (((=) ==> (=)) ==> (=) ==> ((=) ==> (=)) ==> iff) seq_lim.
Proof.
intros x1 x2 A1 a1 a2 A2 N1 N2 A3; split; intros A e e_pos n A4.
+ mc_setoid_replace (x2 n) with (x1 n) by (symmetry; now apply A1).
rewrite <- A2. mc_setoid_replace (N2 e) with (N1 e) in A4 by (symmetry; now apply A3).
now apply A.
+ mc_setoid_replace (x1 n) with (x2 n) by now apply A1.
rewrite A2. mc_setoid_replace (N1 e) with (N2 e) in A4 by now apply A3.
now apply A.
Qed.*)
(* The following instance uses Leibniz equality for the third argument of
seq_lim, i.e., the modulus of type [Q -> nat]. This is because extensional
equality = is not reflexive on functions: [f = f] iff [f] is a morphism.
And we need reflexivity when we replace the first argument of seq_lim and
leave the third one unchanged. Do we need the previous instance with
extensional equality for the third argument? *)
Global Instance : Proper (((=) ==> (=)) ==> (=) ==> (≡) ==> iff) seq_lim.
Proof.
intros x1 x2 A1 a1 a2 A2 N1 N2 A3; split; intros A e e_pos n A4.
+ mc_setoid_replace (x2 n) with (x1 n) by (symmetry; now apply A1).
rewrite <- A2. rewrite <- A3 in A4. now apply A.
+ mc_setoid_replace (x1 n) with (x2 n) by now apply A1.
rewrite A2. rewrite A3 in A4. now apply A.
Qed.
Lemma seq_lim_unique : ∀ (x : seq X) (a1 a2 : X) N1 N2, seq_lim x a1 N1 → seq_lim x a2 N2 → a1 = a2.
Proof.
intros x a1 a2 N1 N2 A1 A2. apply -> mspc_eq; intros q A.
assert (A3 : 0 < q / 2) by solve_propholds.
specialize (A1 (q / 2) A3); specialize (A2 (q / 2) A3).
set (M := Peano.max (N1 (q / 2)) (N2 (q / 2))).
assert (A4 : N1 (q / 2) ≤ M) by apply le_max_l.
assert (A5 : N2 (q / 2) ≤ M) by apply le_max_r.
specialize (A1 M A4); specialize (A2 M A5).
apply mspc_symm in A1.
apply (mspc_triangle' (q / 2) (q / 2) (x M)); trivial.
field; change ((2 : Q) ≠ 0); solve_propholds.
Qed.
Lemma seq_lim_S (x : seq X) (a : X) N : seq_lim x a N -> seq_lim (x ∘ S) a N.
Proof. intros A e A1 n A2. apply A; trivial. apply le_S, A2. Qed.
Lemma seq_lim_S' (x : seq X) (a : X) N : seq_lim (x ∘ S) a N -> seq_lim x a (S ∘ N).
Proof.
intros A e A1 n A2.
destruct n as [| n].
+ contradict A2; apply le_Sn_0.
+ apply A; trivial. apply le_S_n, A2.
Qed.
End SequenceLimits.
Theorem seq_lim_cont
`{ExtMetricSpaceClass X, ExtMetricSpaceClass Y} (f : X -> Y)
{mu : Q -> Qinf} {_ : IsUniformlyContinuous f mu}
(x : seq X) (a : X) (N : Q -> nat) :
seq_lim x a N → seq_lim (f ∘ x) (f a) (comp_inf N mu 0).
Proof.
intros A e e_pos n A1. apply (uc_prf f mu); trivial.
unfold comp_inf in A1; assert (A2 := uc_pos f mu e e_pos).
now destruct (mu e); [apply A | apply mspc_inf].
Qed.
Theorem seq_lim_contr
`{MetricSpaceClass X, ExtMetricSpaceClass Y} (f : X -> Y) `{!IsContraction f q}
(x : seq X) (a : X) (N : Q -> nat) :
seq_lim x a N → seq_lim (f ∘ x) (f a) (comp_inf N (lip_modulus q) 0).
Proof. intro A; apply seq_lim_cont; [apply _ | apply A]. Qed.
Lemma iter_fixpoint
`{ExtMetricSpaceClass X, ExtMetricSpaceClass Y}
(f : X -> X) {mu : Q -> Qinf} {_ : IsUniformlyContinuous f mu}
(x : seq X) (a : X) (N : Q -> nat) :
(forall n : nat, x (S n) = f (x n)) -> seq_lim x a N -> f a = a.
Proof.
intros A1 A2; generalize A2; intro A3. apply seq_lim_S in A2. apply (seq_lim_cont f) in A3.
setoid_replace (x ∘ S) with (f ∘ x) in A2 by (intros ? ? eqmn; rewrite eqmn; apply A1).
eapply seq_lim_unique; eauto.
Qed.
Section CompleteSpaceSequenceLimits.
Context `{CompleteMetricSpaceClass X}.
Definition cauchy (x : seq X) (N : Q -> nat) :=
forall e : Q, 0 < e -> forall m n : nat, N e ≤ m -> N e ≤ n -> ball e (x m) (x n).
Definition reg_fun (x : seq X) (N : Q -> nat) (A : cauchy x N) : RegularFunction X.
refine (Build_RegularFunction (x ∘ N) _).
(* without loss of generality, N e1 ≤ N e2 *)
assert (A3 : forall e1 e2, 0 < e1 -> 0 < e2 -> N e1 ≤ N e2 -> ball (e1 + e2) ((x ∘ N) e1) ((x ∘ N) e2)).
+ intros e1 e2 A1 A2 A3.
apply (mspc_monotone e1).
- apply (strictly_order_preserving (e1 +)) in A2; rewrite plus_0_r in A2; solve_propholds.
- apply A; trivial; reflexivity.
+ intros e1 e2 A1 A2.
assert (A4 : TotalRelation (A := nat) (≤)) by apply _; destruct (A4 (N e1) (N e2)).
- now apply A3.
- rewrite plus_comm; now apply mspc_symm, A3.
Defined.
Arguments reg_fun {_} {_} _.
Lemma seq_lim_lim (x : seq X) (N : Q -> nat) (A : cauchy x N) :
seq_lim x (lim (reg_fun A)) (λ e, N (e / 2)).
Proof.
set (f := reg_fun A).
intros e A1 n A2. apply (mspc_triangle' (e / 2) (e / 2) (x (N (e / 2)))).
+ field; change ((2 : Q) ≠ 0); solve_propholds.
+ now apply mspc_symm, A; [solve_propholds | reflexivity |].
+ change (x (N (e / 2))) with (f (e / 2)).
apply completeness_criterion; solve_propholds.
Qed.
End CompleteSpaceSequenceLimits.
(*End QField.*)
|
-- Andreas, 2016-10-08, issue #2243
-- {-# OPTIONS -v tc.cover.cover:100 #-}
open import Agda.Builtin.Char
f : Char → Char
f 'x' = 'x'
f 'x' = 'y' -- should be marked as unreachable clause
f _ = 's'
|
_Note: This Python notebook assumes that this is your first time to see/work on a Python code. It also assumes that you are new to recommendation systems, but familiar with it as a high-level concept._
# VANILLA COLLABORTIVE FILTERING
_Prepared for EMBA 2022 by EF Legara_
---
Here, we use Python libraries to help us with some of our computations and data visualization. Think of them as a collection of pre-written formulae that we can utilize so we don't have to explicitly write the formulae ourselves. The following libraries are used. You can click on the link to find out more about them.
- [pandas](https://pandas.pydata.org/) - Python data analysis library
- [matplotlib](https://matplotlib.org/) - a plotting library for Python
- [seaborn](https://seaborn.pydata.org/) - for statistical visualization
- [numpy](https://numpy.org/) - for numerical computing in Python
- [sklearn](https://scikit-learn.org/stable/) - ML in Python
Below is the "code cell" that we run to load the libraries.
```python
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
import seaborn as sns
%matplotlib inline
```
---
## Loading the Data
_This data was generated from the EMBA 2019 class._
`df` is the variable we use for our dataframe or table. You may use other variable names, of course.
Here, we load the data stored in an MS in Excel file named `movie recom.xlsx` to a table that we call `df` (a dataframe).
```python
df = pd.read_excel('./data/movie recom.xlsx')
```
Let's take a look at what's inside `df`. The `.head()` function just tells Python to print the first five rows of the dataframe.
```python
df.head()
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Name</th>
<th>Matrix</th>
<th>Inception</th>
<th>Titanic</th>
<th>Amélie</th>
<th>Love Actually</th>
<th>Terminator</th>
<th>Elysium</th>
<th>Avatar</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>Person 1</td>
<td>5</td>
<td>5</td>
<td>4</td>
<td>0</td>
<td>0</td>
<td>3</td>
<td>0</td>
<td>5</td>
</tr>
<tr>
<th>1</th>
<td>Person 2</td>
<td>5</td>
<td>5</td>
<td>1</td>
<td>4</td>
<td>3</td>
<td>4</td>
<td>2</td>
<td>4</td>
</tr>
<tr>
<th>2</th>
<td>Person 3</td>
<td>0</td>
<td>0</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<th>3</th>
<td>Person 4</td>
<td>4</td>
<td>4</td>
<td>4</td>
<td>0</td>
<td>3</td>
<td>3</td>
<td>2</td>
<td>5</td>
</tr>
<tr>
<th>4</th>
<td>Person 5</td>
<td>1</td>
<td>0</td>
<td>3</td>
<td>0</td>
<td>0</td>
<td>3</td>
<td>2</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
The table above currently has nine columns which include the **Name** column and the eight other columns for the movies. For ease of analysis, we can set the _index_ of each row in the table using the **Name** of clients or users. You can think of the index as the row number or row name.
```python
df = df.set_index('Name')
```
Here's how are dataframe looks like.
```python
df.head()
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Matrix</th>
<th>Inception</th>
<th>Titanic</th>
<th>Amélie</th>
<th>Love Actually</th>
<th>Terminator</th>
<th>Elysium</th>
<th>Avatar</th>
</tr>
<tr>
<th>Name</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th>Person 1</th>
<td>5</td>
<td>5</td>
<td>4</td>
<td>0</td>
<td>0</td>
<td>3</td>
<td>0</td>
<td>5</td>
</tr>
<tr>
<th>Person 2</th>
<td>5</td>
<td>5</td>
<td>1</td>
<td>4</td>
<td>3</td>
<td>4</td>
<td>2</td>
<td>4</td>
</tr>
<tr>
<th>Person 3</th>
<td>0</td>
<td>0</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<th>Person 4</th>
<td>4</td>
<td>4</td>
<td>4</td>
<td>0</td>
<td>3</td>
<td>3</td>
<td>2</td>
<td>5</td>
</tr>
<tr>
<th>Person 5</th>
<td>1</td>
<td>0</td>
<td>3</td>
<td>0</td>
<td>0</td>
<td>3</td>
<td>2</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
As you can see above, **Name** is not a column (or variable) in the table anymore, but instead an _index_ (or a row name).
The resulting dataframe now purely consists of values that are numerical; in this case, the ratings given by each person (row name or index) to the set of movies (columns).
We can view the values of the pandas dataframe by running the code cell below.
```python
df.values
```
array([[5, 5, 4, 0, 0, 3, 0, 5],
[5, 5, 1, 4, 3, 4, 2, 4],
[0, 0, 3, 4, 5, 0, 0, 0],
[4, 4, 4, 0, 3, 3, 2, 5],
[1, 0, 3, 0, 0, 3, 2, 4],
[5, 5, 2, 3, 0, 3, 1, 4],
[5, 5, 2, 0, 1, 3, 0, 5],
[5, 5, 4, 3, 3, 4, 0, 3],
[4, 5, 4, 0, 4, 4, 5, 4],
[5, 5, 3, 0, 3, 4, 4, 5],
[5, 5, 5, 5, 0, 2, 0, 3],
[4, 5, 3, 2, 5, 3, 2, 1],
[5, 5, 5, 4, 5, 3, 3, 4],
[4, 5, 4, 0, 4, 4, 1, 4],
[4, 5, 2, 0, 1, 3, 3, 5],
[4, 3, 3, 0, 4, 3, 0, 4],
[5, 5, 4, 5, 3, 2, 0, 4],
[4, 0, 2, 0, 4, 4, 0, 3],
[1, 3, 3, 0, 3, 3, 0, 5],
[4, 0, 5, 0, 4, 4, 4, 5]])
These are essentially the numbers in our dataframe, but displayed as an $N$-by-$N$ array of numbers, where $N=20$ is the total number of users and where each `[ ... ]` lists the ratings a person has given to the movies he/she has seen. The order, of course, matters. The first element or number in the list `[ ... ]` corresponds to the movie *The Matrix*, while the last corresponds to *Avatar*.
Let's then have a look at how Person 1 (`p1`) and Person 2 (`p2`) rated the movies.
```python
p1 = list(df.loc['Person 1'])
p2 = list(df.loc['Person 2'])
print('p1 [The Matrix, Inception, ..., Elysium, Avatar]:', p1)
print('p2: ', p2)
```
p1 [The Matrix, Inception, ..., Elysium, Avatar]: [5, 5, 4, 0, 0, 3, 0, 5]
p2: [5, 5, 1, 4, 3, 4, 2, 4]
Indeed, the values reflect the ratings in our raw data for persons 1 and 2.
```python
df.head(n=2)
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Matrix</th>
<th>Inception</th>
<th>Titanic</th>
<th>Amélie</th>
<th>Love Actually</th>
<th>Terminator</th>
<th>Elysium</th>
<th>Avatar</th>
</tr>
<tr>
<th>Name</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th>Person 1</th>
<td>5</td>
<td>5</td>
<td>4</td>
<td>0</td>
<td>0</td>
<td>3</td>
<td>0</td>
<td>5</td>
</tr>
<tr>
<th>Person 2</th>
<td>5</td>
<td>5</td>
<td>1</td>
<td>4</td>
<td>3</td>
<td>4</td>
<td>2</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
---
## Matrix Visualization
Let's explore if we can also already identify some patterns by just visualizing the raw data of ratings. We can use seaborn's `heatmap` function to visualize our dataframe `df`.
```python
# the choice of colormap
cmap = sns.cm.rocket_r
# indicate figure size
plt.figure(figsize=(10,8))
# draw heatmap
g = sns.heatmap(df.values);
# set tick labes for both x & y axes
g.set_xticklabels(df.columns, rotation=90);
g.set_yticklabels(df.index, rotation=0);
```
That is actually still a bit tough to read. We cannot accurately tell yet if there are strong connections, correlations, and/or similarities between movies/users.
---
## Collaborative Filtering
### User-based CF
Now, let's implement [**collaborative filtering**](https://en.wikipedia.org/wiki/Collaborative_filtering). With collaborative filtering, we can explore how users are similar to each other based on the ratings they gave movies using the [cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity) measure. If you can recall,
\begin{equation}
\cos (X,Y) = \frac{\sum_{i=1}^{n} X_i Y_i}{\sqrt {\sum_{i=1}^{n}X_i^2}\sqrt {\sum_{i=1}^{n}Y_i^2}}.
\end{equation}
That is, the similarity of Person $X$ and Person $Y$, in terms of their taste in movies, can be computed by the ratings they gave to the movies ($1$ to $n=8$) where movie 1 corresponds to _The Matrix_, movie 2 to _Inception_, movie 3 to _Titanic_, and so on and so forth.
We define a function `compute_cosine_similarity( )` below that computes the cosine similarity given the above equation.
```python
def compute_cosine_similarity (p1, p2):
num_movies = len(p1)
sumprod = 0
for i in range(num_movies):
sumprod = sumprod + (p1[i] * p2[i])
numerator = sumprod
denominator = np.sqrt(sum([r1*r1 for r1 in p1])) * np.sqrt(sum([r2*r2 for r2 in p2]))
return numerator/denominator
```
Let's use the function above to check how similar (or not) _Person 1_ and _Person 2_ are.
```python
p1 = list(df.loc['Person 1'])
p2 = list(df.loc['Person 2'])
print ('Person 1 and Person 2 are {:.2f}% similar.'.format(compute_cosine_similarity(p1, p2)*100))
```
Person 1 and Person 2 are 81.26% similar.
Check similarity between Person 4 and Person 3.
```python
p1 = list(df.loc['Person 4'])
p2 = list(df.loc['Person 3'])
print ('Person 4 and Person 3 are {:.2f}% similar.'.format(compute_cosine_similarity(p1, p2)*100))
```
Person 4 and Person 3 are 39.18% similar.
#### Using a Python library
As mentioned at the beginning, the good news is that we don't have to manually perform this pairwise computation of cosine similarity. We didn't even need to write the function ourselves. Python has a function via the `sklearn` library that computes the cosine similarity of the whole matrix for us.
It's a one liner as you can see in the code cell below.
```python
user_similarity_matrix = cosine_similarity(df.values)
```
The result is a 20 x 20 matrix where the numbers of rows and columns correspond to the number of users (in this case, 20) in the data. The element in each cell of the matrix gives us the cosine similarity between two persons.
```python
user_similarity_matrix.size
```
400
```python
user_similarity_matrix
```
array([[1. , 0.81262362, 0.16970563, 0.92338052, 0.73658951,
0.92219816, 0.97519805, 0.89077845, 0.81566396, 0.88548292,
0.85605599, 0.7362357 , 0.80833162, 0.90329585, 0.92219816,
0.87757241, 0.83984125, 0.70420284, 0.83820084, 0.72117107],
[0.81262362, 1. , 0.45434411, 0.86281799, 0.60522753,
0.94150762, 0.87139535, 0.93221259, 0.85360419, 0.89586351,
0.84445278, 0.8916428 , 0.9258201 , 0.87188993, 0.88141139,
0.85104977, 0.92296269, 0.75009757, 0.76802458, 0.71684223],
[0.16970563, 0.45434411, 1. , 0.39175718, 0.20380987,
0.26983141, 0.16489697, 0.52828266, 0.39691115, 0.30357866,
0.46563307, 0.61591788, 0.6466323 , 0.4395538 , 0.16489697,
0.47356802, 0.60676739, 0.47078588, 0.43105272, 0.46358632],
[0.92338052, 0.86281799, 0.39175718, 1. , 0.80501129,
0.85915255, 0.92440465, 0.90409231, 0.95383309, 0.97272271,
0.78177899, 0.86175089, 0.9214786 , 0.9765879 , 0.94615534,
0.95960518, 0.85229309, 0.82758732, 0.92512561, 0.89365259],
[0.73658951, 0.60522753, 0.20380987, 0.80501129, 1. ,
0.64499491, 0.67894201, 0.62883731, 0.75838508, 0.77340406,
0.5724164 , 0.49813548, 0.66679486, 0.71543897, 0.76380977,
0.70262025, 0.57008771, 0.69707851, 0.79311554, 0.88484517],
[0.92219816, 0.94150762, 0.26983141, 0.85915255, 0.64499491,
1. , 0.93258427, 0.92391739, 0.79952449, 0.87224365,
0.92736078, 0.79139995, 0.86548464, 0.84423998, 0.91011236,
0.80782688, 0.91925919, 0.65145034, 0.74040926, 0.65523412],
[0.97519805, 0.87139535, 0.16489697, 0.92440465, 0.67894201,
0.93258427, 1. , 0.89345857, 0.82741488, 0.91016729,
0.80770132, 0.76941662, 0.81355557, 0.91630925, 0.94382022,
0.90574529, 0.84184789, 0.74645352, 0.84810515, 0.70487307],
[0.89077845, 0.93221259, 0.52828266, 0.90409231, 0.62883731,
0.92391739, 0.89345857, 1. , 0.84846992, 0.87383999,
0.91906812, 0.92369422, 0.94629488, 0.93962636, 0.84269388,
0.9179821 , 0.96180895, 0.79714108, 0.82717961, 0.7445818 ],
[0.81566396, 0.85360419, 0.39691115, 0.95383309, 0.75838508,
0.79952449, 0.82741488, 0.84846992, 1. , 0.98058068,
0.70130676, 0.90037213, 0.91662704, 0.93706146, 0.92967964,
0.88108325, 0.77662155, 0.76361125, 0.8353986 , 0.8871553 ],
[0.88548292, 0.89586351, 0.30357866, 0.97272271, 0.77340406,
0.87224365, 0.91016729, 0.87383999, 0.98058068, 1. ,
0.74043756, 0.87182912, 0.90556796, 0.94693149, 0.97653365,
0.90886009, 0.80833162, 0.7901857 , 0.85194275, 0.87121613],
[0.85605599, 0.84445278, 0.46563307, 0.78177899, 0.5724164 ,
0.92736078, 0.80770132, 0.91906812, 0.70130676, 0.74043756,
1. , 0.77063086, 0.86794777, 0.77665255, 0.75784322,
0.73865061, 0.95321997, 0.56610073, 0.66904135, 0.59912476],
[0.7362357 , 0.8916428 , 0.61591788, 0.86175089, 0.49813548,
0.79139995, 0.76941662, 0.92369422, 0.90037213, 0.87182912,
0.77063086, 1. , 0.94826761, 0.91653063, 0.79139995,
0.87407914, 0.87087481, 0.75677794, 0.75065008, 0.73810763],
[0.80833162, 0.9258201 , 0.6466323 , 0.9214786 , 0.66679486,
0.86548464, 0.81355557, 0.94629488, 0.91662704, 0.90556796,
0.86794777, 0.94826761, 1. , 0.91993984, 0.84817495,
0.89566859, 0.94660211, 0.77360839, 0.81919184, 0.83354383],
[0.90329585, 0.87188993, 0.4395538 , 0.9765879 , 0.71543897,
0.84423998, 0.91630925, 0.93962636, 0.93706146, 0.94693149,
0.77665255, 0.91653063, 0.91993984, 1. , 0.90601364,
0.97574355, 0.86005887, 0.8456508 , 0.92515071, 0.83691715],
[0.92219816, 0.88141139, 0.16489697, 0.94615534, 0.76380977,
0.91011236, 0.94382022, 0.84269388, 0.92967964, 0.97653365,
0.75784322, 0.79139995, 0.84817495, 0.90601364, 1. ,
0.85678609, 0.79346582, 0.69216599, 0.83464317, 0.78429539],
[0.87757241, 0.85104977, 0.47356802, 0.95960518, 0.70262025,
0.80782688, 0.90574529, 0.9179821 , 0.88108325, 0.90886009,
0.73865061, 0.87407914, 0.89566859, 0.97574355, 0.85678609,
1. , 0.85381497, 0.91663438, 0.92387682, 0.85436615],
[0.83984125, 0.92296269, 0.60676739, 0.85229309, 0.57008771,
0.91925919, 0.84184789, 0.96180895, 0.77662155, 0.80833162,
0.95321997, 0.87087481, 0.94660211, 0.86005887, 0.79346582,
0.85381497, 1. , 0.70128687, 0.77676265, 0.68398557],
[0.70420284, 0.75009757, 0.47078588, 0.82758732, 0.69707851,
0.65145034, 0.74645352, 0.79714108, 0.76361125, 0.7901857 ,
0.56610073, 0.75677794, 0.77360839, 0.8456508 , 0.69216599,
0.91663438, 0.70128687, 1. , 0.7967743 , 0.87539793],
[0.83820084, 0.76802458, 0.43105272, 0.92512561, 0.79311554,
0.74040926, 0.84810515, 0.82717961, 0.8353986 , 0.85194275,
0.66904135, 0.75065008, 0.81919184, 0.92515071, 0.83464317,
0.92387682, 0.77676265, 0.7967743 , 1. , 0.80883632],
[0.72117107, 0.71684223, 0.46358632, 0.89365259, 0.88484517,
0.65523412, 0.70487307, 0.7445818 , 0.8871553 , 0.87121613,
0.59912476, 0.73810763, 0.83354383, 0.83691715, 0.78429539,
0.85436615, 0.68398557, 0.87539793, 0.80883632, 1. ]])
Okay. That's a bit tough to read. We can use a heatmap instead. We may view it as a dataframe
```python
pd.DataFrame(user_similarity_matrix, index = df.index, columns = list(df.index))
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
<th>Person 4</th>
<th>Person 5</th>
<th>Person 6</th>
<th>Person 7</th>
<th>Person 8</th>
<th>Person 9</th>
<th>Person 10</th>
<th>Person 11</th>
<th>Person 12</th>
<th>Person 13</th>
<th>Person 14</th>
<th>Person 15</th>
<th>Person 16</th>
<th>Person 17</th>
<th>Person 18</th>
<th>Person 19</th>
<th>Person 20</th>
</tr>
<tr>
<th>Name</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th>Person 1</th>
<td>1.000000</td>
<td>0.812624</td>
<td>0.169706</td>
<td>0.923381</td>
<td>0.736590</td>
<td>0.922198</td>
<td>0.975198</td>
<td>0.890778</td>
<td>0.815664</td>
<td>0.885483</td>
<td>0.856056</td>
<td>0.736236</td>
<td>0.808332</td>
<td>0.903296</td>
<td>0.922198</td>
<td>0.877572</td>
<td>0.839841</td>
<td>0.704203</td>
<td>0.838201</td>
<td>0.721171</td>
</tr>
<tr>
<th>Person 2</th>
<td>0.812624</td>
<td>1.000000</td>
<td>0.454344</td>
<td>0.862818</td>
<td>0.605228</td>
<td>0.941508</td>
<td>0.871395</td>
<td>0.932213</td>
<td>0.853604</td>
<td>0.895864</td>
<td>0.844453</td>
<td>0.891643</td>
<td>0.925820</td>
<td>0.871890</td>
<td>0.881411</td>
<td>0.851050</td>
<td>0.922963</td>
<td>0.750098</td>
<td>0.768025</td>
<td>0.716842</td>
</tr>
<tr>
<th>Person 3</th>
<td>0.169706</td>
<td>0.454344</td>
<td>1.000000</td>
<td>0.391757</td>
<td>0.203810</td>
<td>0.269831</td>
<td>0.164897</td>
<td>0.528283</td>
<td>0.396911</td>
<td>0.303579</td>
<td>0.465633</td>
<td>0.615918</td>
<td>0.646632</td>
<td>0.439554</td>
<td>0.164897</td>
<td>0.473568</td>
<td>0.606767</td>
<td>0.470786</td>
<td>0.431053</td>
<td>0.463586</td>
</tr>
<tr>
<th>Person 4</th>
<td>0.923381</td>
<td>0.862818</td>
<td>0.391757</td>
<td>1.000000</td>
<td>0.805011</td>
<td>0.859153</td>
<td>0.924405</td>
<td>0.904092</td>
<td>0.953833</td>
<td>0.972723</td>
<td>0.781779</td>
<td>0.861751</td>
<td>0.921479</td>
<td>0.976588</td>
<td>0.946155</td>
<td>0.959605</td>
<td>0.852293</td>
<td>0.827587</td>
<td>0.925126</td>
<td>0.893653</td>
</tr>
<tr>
<th>Person 5</th>
<td>0.736590</td>
<td>0.605228</td>
<td>0.203810</td>
<td>0.805011</td>
<td>1.000000</td>
<td>0.644995</td>
<td>0.678942</td>
<td>0.628837</td>
<td>0.758385</td>
<td>0.773404</td>
<td>0.572416</td>
<td>0.498135</td>
<td>0.666795</td>
<td>0.715439</td>
<td>0.763810</td>
<td>0.702620</td>
<td>0.570088</td>
<td>0.697079</td>
<td>0.793116</td>
<td>0.884845</td>
</tr>
<tr>
<th>Person 6</th>
<td>0.922198</td>
<td>0.941508</td>
<td>0.269831</td>
<td>0.859153</td>
<td>0.644995</td>
<td>1.000000</td>
<td>0.932584</td>
<td>0.923917</td>
<td>0.799524</td>
<td>0.872244</td>
<td>0.927361</td>
<td>0.791400</td>
<td>0.865485</td>
<td>0.844240</td>
<td>0.910112</td>
<td>0.807827</td>
<td>0.919259</td>
<td>0.651450</td>
<td>0.740409</td>
<td>0.655234</td>
</tr>
<tr>
<th>Person 7</th>
<td>0.975198</td>
<td>0.871395</td>
<td>0.164897</td>
<td>0.924405</td>
<td>0.678942</td>
<td>0.932584</td>
<td>1.000000</td>
<td>0.893459</td>
<td>0.827415</td>
<td>0.910167</td>
<td>0.807701</td>
<td>0.769417</td>
<td>0.813556</td>
<td>0.916309</td>
<td>0.943820</td>
<td>0.905745</td>
<td>0.841848</td>
<td>0.746454</td>
<td>0.848105</td>
<td>0.704873</td>
</tr>
<tr>
<th>Person 8</th>
<td>0.890778</td>
<td>0.932213</td>
<td>0.528283</td>
<td>0.904092</td>
<td>0.628837</td>
<td>0.923917</td>
<td>0.893459</td>
<td>1.000000</td>
<td>0.848470</td>
<td>0.873840</td>
<td>0.919068</td>
<td>0.923694</td>
<td>0.946295</td>
<td>0.939626</td>
<td>0.842694</td>
<td>0.917982</td>
<td>0.961809</td>
<td>0.797141</td>
<td>0.827180</td>
<td>0.744582</td>
</tr>
<tr>
<th>Person 9</th>
<td>0.815664</td>
<td>0.853604</td>
<td>0.396911</td>
<td>0.953833</td>
<td>0.758385</td>
<td>0.799524</td>
<td>0.827415</td>
<td>0.848470</td>
<td>1.000000</td>
<td>0.980581</td>
<td>0.701307</td>
<td>0.900372</td>
<td>0.916627</td>
<td>0.937061</td>
<td>0.929680</td>
<td>0.881083</td>
<td>0.776622</td>
<td>0.763611</td>
<td>0.835399</td>
<td>0.887155</td>
</tr>
<tr>
<th>Person 10</th>
<td>0.885483</td>
<td>0.895864</td>
<td>0.303579</td>
<td>0.972723</td>
<td>0.773404</td>
<td>0.872244</td>
<td>0.910167</td>
<td>0.873840</td>
<td>0.980581</td>
<td>1.000000</td>
<td>0.740438</td>
<td>0.871829</td>
<td>0.905568</td>
<td>0.946931</td>
<td>0.976534</td>
<td>0.908860</td>
<td>0.808332</td>
<td>0.790186</td>
<td>0.851943</td>
<td>0.871216</td>
</tr>
<tr>
<th>Person 11</th>
<td>0.856056</td>
<td>0.844453</td>
<td>0.465633</td>
<td>0.781779</td>
<td>0.572416</td>
<td>0.927361</td>
<td>0.807701</td>
<td>0.919068</td>
<td>0.701307</td>
<td>0.740438</td>
<td>1.000000</td>
<td>0.770631</td>
<td>0.867948</td>
<td>0.776653</td>
<td>0.757843</td>
<td>0.738651</td>
<td>0.953220</td>
<td>0.566101</td>
<td>0.669041</td>
<td>0.599125</td>
</tr>
<tr>
<th>Person 12</th>
<td>0.736236</td>
<td>0.891643</td>
<td>0.615918</td>
<td>0.861751</td>
<td>0.498135</td>
<td>0.791400</td>
<td>0.769417</td>
<td>0.923694</td>
<td>0.900372</td>
<td>0.871829</td>
<td>0.770631</td>
<td>1.000000</td>
<td>0.948268</td>
<td>0.916531</td>
<td>0.791400</td>
<td>0.874079</td>
<td>0.870875</td>
<td>0.756778</td>
<td>0.750650</td>
<td>0.738108</td>
</tr>
<tr>
<th>Person 13</th>
<td>0.808332</td>
<td>0.925820</td>
<td>0.646632</td>
<td>0.921479</td>
<td>0.666795</td>
<td>0.865485</td>
<td>0.813556</td>
<td>0.946295</td>
<td>0.916627</td>
<td>0.905568</td>
<td>0.867948</td>
<td>0.948268</td>
<td>1.000000</td>
<td>0.919940</td>
<td>0.848175</td>
<td>0.895669</td>
<td>0.946602</td>
<td>0.773608</td>
<td>0.819192</td>
<td>0.833544</td>
</tr>
<tr>
<th>Person 14</th>
<td>0.903296</td>
<td>0.871890</td>
<td>0.439554</td>
<td>0.976588</td>
<td>0.715439</td>
<td>0.844240</td>
<td>0.916309</td>
<td>0.939626</td>
<td>0.937061</td>
<td>0.946931</td>
<td>0.776653</td>
<td>0.916531</td>
<td>0.919940</td>
<td>1.000000</td>
<td>0.906014</td>
<td>0.975744</td>
<td>0.860059</td>
<td>0.845651</td>
<td>0.925151</td>
<td>0.836917</td>
</tr>
<tr>
<th>Person 15</th>
<td>0.922198</td>
<td>0.881411</td>
<td>0.164897</td>
<td>0.946155</td>
<td>0.763810</td>
<td>0.910112</td>
<td>0.943820</td>
<td>0.842694</td>
<td>0.929680</td>
<td>0.976534</td>
<td>0.757843</td>
<td>0.791400</td>
<td>0.848175</td>
<td>0.906014</td>
<td>1.000000</td>
<td>0.856786</td>
<td>0.793466</td>
<td>0.692166</td>
<td>0.834643</td>
<td>0.784295</td>
</tr>
<tr>
<th>Person 16</th>
<td>0.877572</td>
<td>0.851050</td>
<td>0.473568</td>
<td>0.959605</td>
<td>0.702620</td>
<td>0.807827</td>
<td>0.905745</td>
<td>0.917982</td>
<td>0.881083</td>
<td>0.908860</td>
<td>0.738651</td>
<td>0.874079</td>
<td>0.895669</td>
<td>0.975744</td>
<td>0.856786</td>
<td>1.000000</td>
<td>0.853815</td>
<td>0.916634</td>
<td>0.923877</td>
<td>0.854366</td>
</tr>
<tr>
<th>Person 17</th>
<td>0.839841</td>
<td>0.922963</td>
<td>0.606767</td>
<td>0.852293</td>
<td>0.570088</td>
<td>0.919259</td>
<td>0.841848</td>
<td>0.961809</td>
<td>0.776622</td>
<td>0.808332</td>
<td>0.953220</td>
<td>0.870875</td>
<td>0.946602</td>
<td>0.860059</td>
<td>0.793466</td>
<td>0.853815</td>
<td>1.000000</td>
<td>0.701287</td>
<td>0.776763</td>
<td>0.683986</td>
</tr>
<tr>
<th>Person 18</th>
<td>0.704203</td>
<td>0.750098</td>
<td>0.470786</td>
<td>0.827587</td>
<td>0.697079</td>
<td>0.651450</td>
<td>0.746454</td>
<td>0.797141</td>
<td>0.763611</td>
<td>0.790186</td>
<td>0.566101</td>
<td>0.756778</td>
<td>0.773608</td>
<td>0.845651</td>
<td>0.692166</td>
<td>0.916634</td>
<td>0.701287</td>
<td>1.000000</td>
<td>0.796774</td>
<td>0.875398</td>
</tr>
<tr>
<th>Person 19</th>
<td>0.838201</td>
<td>0.768025</td>
<td>0.431053</td>
<td>0.925126</td>
<td>0.793116</td>
<td>0.740409</td>
<td>0.848105</td>
<td>0.827180</td>
<td>0.835399</td>
<td>0.851943</td>
<td>0.669041</td>
<td>0.750650</td>
<td>0.819192</td>
<td>0.925151</td>
<td>0.834643</td>
<td>0.923877</td>
<td>0.776763</td>
<td>0.796774</td>
<td>1.000000</td>
<td>0.808836</td>
</tr>
<tr>
<th>Person 20</th>
<td>0.721171</td>
<td>0.716842</td>
<td>0.463586</td>
<td>0.893653</td>
<td>0.884845</td>
<td>0.655234</td>
<td>0.704873</td>
<td>0.744582</td>
<td>0.887155</td>
<td>0.871216</td>
<td>0.599125</td>
<td>0.738108</td>
<td>0.833544</td>
<td>0.836917</td>
<td>0.784295</td>
<td>0.854366</td>
<td>0.683986</td>
<td>0.875398</td>
<td>0.808836</td>
<td>1.000000</td>
</tr>
</tbody>
</table>
</div>
From the dataframe above, we can see that Person 1 is 81.26% similar to Person 2 while Person 3 is only 39.18% similar to Person 4.
We can display the dataframe above as a heatmap. The darker the cell color is the more similar two persons are.
```python
plt.figure(figsize=(10,10))
g = sns.heatmap(user_similarity_matrix, cmap = cmap)
g.set_xticklabels(df.index, rotation=90);
g.set_yticklabels(df.index, rotation=0);
```
### Item-based CF
How about instead of user-based, we use item-based?
The method/approach is exactly the same. We'll just transpose our original dataframe; i.e., our rows are now the movie names, while the columns are the individual users.
```python
df_t = df.transpose()
```
```python
df_t
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th>Name</th>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
<th>Person 4</th>
<th>Person 5</th>
<th>Person 6</th>
<th>Person 7</th>
<th>Person 8</th>
<th>Person 9</th>
<th>Person 10</th>
<th>Person 11</th>
<th>Person 12</th>
<th>Person 13</th>
<th>Person 14</th>
<th>Person 15</th>
<th>Person 16</th>
<th>Person 17</th>
<th>Person 18</th>
<th>Person 19</th>
<th>Person 20</th>
</tr>
</thead>
<tbody>
<tr>
<th>Matrix</th>
<td>5</td>
<td>5</td>
<td>0</td>
<td>4</td>
<td>1</td>
<td>5</td>
<td>5</td>
<td>5</td>
<td>4</td>
<td>5</td>
<td>5</td>
<td>4</td>
<td>5</td>
<td>4</td>
<td>4</td>
<td>4</td>
<td>5</td>
<td>4</td>
<td>1</td>
<td>4</td>
</tr>
<tr>
<th>Inception</th>
<td>5</td>
<td>5</td>
<td>0</td>
<td>4</td>
<td>0</td>
<td>5</td>
<td>5</td>
<td>5</td>
<td>5</td>
<td>5</td>
<td>5</td>
<td>5</td>
<td>5</td>
<td>5</td>
<td>5</td>
<td>3</td>
<td>5</td>
<td>0</td>
<td>3</td>
<td>0</td>
</tr>
<tr>
<th>Titanic</th>
<td>4</td>
<td>1</td>
<td>3</td>
<td>4</td>
<td>3</td>
<td>2</td>
<td>2</td>
<td>4</td>
<td>4</td>
<td>3</td>
<td>5</td>
<td>3</td>
<td>5</td>
<td>4</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>2</td>
<td>3</td>
<td>5</td>
</tr>
<tr>
<th>Amélie</th>
<td>0</td>
<td>4</td>
<td>4</td>
<td>0</td>
<td>0</td>
<td>3</td>
<td>0</td>
<td>3</td>
<td>0</td>
<td>0</td>
<td>5</td>
<td>2</td>
<td>4</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>5</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<th>Love Actually</th>
<td>0</td>
<td>3</td>
<td>5</td>
<td>3</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>3</td>
<td>4</td>
<td>3</td>
<td>0</td>
<td>5</td>
<td>5</td>
<td>4</td>
<td>1</td>
<td>4</td>
<td>3</td>
<td>4</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<th>Terminator</th>
<td>3</td>
<td>4</td>
<td>0</td>
<td>3</td>
<td>3</td>
<td>3</td>
<td>3</td>
<td>4</td>
<td>4</td>
<td>4</td>
<td>2</td>
<td>3</td>
<td>3</td>
<td>4</td>
<td>3</td>
<td>3</td>
<td>2</td>
<td>4</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<th>Elysium</th>
<td>0</td>
<td>2</td>
<td>0</td>
<td>2</td>
<td>2</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>5</td>
<td>4</td>
<td>0</td>
<td>2</td>
<td>3</td>
<td>1</td>
<td>3</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>4</td>
</tr>
<tr>
<th>Avatar</th>
<td>5</td>
<td>4</td>
<td>0</td>
<td>5</td>
<td>4</td>
<td>4</td>
<td>5</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>3</td>
<td>1</td>
<td>4</td>
<td>4</td>
<td>5</td>
<td>4</td>
<td>4</td>
<td>3</td>
<td>5</td>
<td>5</td>
</tr>
</tbody>
</table>
</div>
```python
movie_similarity_matrix = cosine_similarity(df_t)
plt.figure(figsize=(10,10))
g = sns.heatmap(movie_similarity_matrix, cmap = cmap, annot=True)
g.set_xticklabels(df_t.index, rotation=90);
g.set_yticklabels(df_t.index, rotation=0);
```
See if you can confirm the following statements:
- Among the other movies in the list and according to the preferences of EMBA 2019 students, _Avatar_ is most similar to _Terminator_.
- Among the other movies in the list and according to the preferences of EMBA 2019 students, _The Matrix_ is most similar to both _Inception_ and _Terminator_.
---
## Going back to the Users
Can we maybe cluster the users instead based on the ratings they gave the eight (8) movies, at most?
Definitely. And one of the most basic methods we can use is [k-means clustering](https://en.wikipedia.org/wiki/K-means_clustering). With $k$-means, we need to indicate the number of clusters $k$ we want our users to be grouped into.
Let us once again use `sklearn` to implement k-means.
```python
from sklearn.cluster import KMeans
```
```python
# setting k = 4 means that we're expecting 4 groupings in the EMBA 2019 cohort based
# on their movie ratings.
k = 4
kmeans = KMeans(n_clusters=k).fit(df.values)
```
```python
cluster_labels = kmeans.labels_
```
Below, we print the groupings.
```python
groupings = {}
for c in range(k):
groupings[c] = []
persons = list(df.index)
i = 0
for i in range(len(persons)):
groupings[cluster_labels[i]].append(persons[i])
for group, people in groupings.items():
print ('Group #{}: {}'.format(group, people))
```
Group #0: ['Person 1', 'Person 4', 'Person 7', 'Person 9', 'Person 10', 'Person 14', 'Person 15', 'Person 16', 'Person 19']
Group #1: ['Person 2', 'Person 6', 'Person 8', 'Person 11', 'Person 12', 'Person 13', 'Person 17']
Group #2: ['Person 5', 'Person 18', 'Person 20']
Group #3: ['Person 3']
$k$-means is actually one of the most basic and (arguably) one of the more popular _unsupervised_ machine learning algorithms out there.
### Assigning _new_ users to existing groups.
With a model generated using our data, we can now assign (or "predict") new users to the generated clusters.
Say, for example, our new user has given our movies the following ratings:
- The Matrix: 0
- Inception: 0
- Titanic: 3
- Amelie: 2
- Love Actually: 5
- Terminator: 5
- Elysium: 5
- Avatar: 3
```python
kmeans.predict([[0,0,3,2,5,5,5,3]])
```
array([2], dtype=int32)
What if we have another new user?
- The Matrix: 5
- Inception: 5
- Titanic: 5
- Amelie: 2
- Love Actually: 5
- Terminator: 1
- Elysium: 1
- Avatar: 3
```python
kmeans.predict([[5,5,5,2,5,1,1,3]])
```
array([1], dtype=int32)
And another one?
```python
kmeans.predict([[1,1,5,2,5,1,1,3]])
```
array([3], dtype=int32)
---
## Summary and Some Notes
- We showed how to load a MS Excel file into a dataframe.
- We implemented collaborative filtering in Python:
- user-user
- item-item
- We introduced (for demo) $k$-means clustering, an unsupervised ML model, to cluster users based on what they've watched and their taste in movies.
- For the $k$-means clustering demo above, we explicitly chose the size of $k$. There are, of course, ways on how to systematically find the "right" number of clusters (e.g., using intertia plots), but they are beyond the scope of this intro to Python and Vanilla Collaborative Filtering method.
- Once you learn more about the math/science behind $k$-means, you'll also realize that the membership of clusters may change for every run. This is because $k$-means starts by _randomly_ creating $k$ centroids, which are the points it uses to cluster the data points, which is based on their distance from the centroids.
|
If $f$ converges to $a$ and $a \neq 0$, then $1/f$ converges to $1/a$. |
'''
This file contains functions to plot data in multiple ways. It also includes a function to run a Shapiro-Wilkinson
test on time series data and three error calculating tests for forecasting models (mse, mape, and smape).
Author: Brian Gunnarson
Group name: The Classy Coders
Most recent modification: 2/9/21
'''
import matplotlib.pyplot as plt
from preprocessing import TimeSeries
from typing import List
from scipy.stats import shapiro
from scipy.stats import probplot
def plot(ts: TimeSeries):
'''
Plots one or more time series. The time axis is adjusted to display the data according to their time indices.
Changed to just ts instead of ts_list as argument because of the operatorkeys.py file.
ARGS:
- ts_list: a list of one or more time series files to be plotted. The files will be of type str.
SIDE EFFECTS:
- produces a plot of one or more time series
'''
# Plot the ts data
ts.data.plot()
# Change the label of the x-axis and display the plot
plt.xlabel("Date")
plt.show()
def histogram(ts: TimeSeries):
'''
Computes the histogram of a given time series and then plots it. When it's plotted, the histogram is vertical
and side to side with a plot of the time series.
ARGS:
- ts: a single time series file to run operations on. Should be a string containing a csv filename.
SIDE EFFECTS:
- produces a histogram based on ts
- plots the ts
'''
# Create a subplot with 1 row and 2 columns (for formatting)
fig, axes = plt.subplots(1, 2)
# Create the histogram and plot, then display them side-by-side
ts.data.hist(ax=axes[0])
ts.data.plot(ax=axes[1])
plt.show()
def box_plot(ts: TimeSeries):
'''
Produces a Box and Whiskers plot of the given time series. Also prints the 5-number summary of the data.
ARGS:
- ts: a single time series file to run operations on. Should be a string containing a csv filename.
SIDE EFFECTS:
- prints the 5-number summary of the data; that is, it prints the minimum, maximum, first quartile, median,
and third quartile
- produces a Box and Whiskers plot of ts
'''
# Create and display the box plot
ts.data.plot.box()
plt.show()
# Print the 5-number summary (plus a little extra)
ts.data.describe()
def normality_test(ts: TimeSeries):
'''
Performs a hypothesis test about normality on the given time series data distribution using Scipy's
Shapiro-Wilkinson. Additionally, this function creates a quantile plot of the data using qqplot from matplotlib.
ARGS:
- ts: a single time series file to run operations on. Should be a string containing a csv filename.
SIDE EFFECTS:
- produces a quantile plot of the data from ts
- prints the results of the normality test by checking the p-value obtained by Shapiro-Wilkinson
'''
# Loop through each column in the dataframe
for col in ts.data:
# We want to run the shapiro test on the columns with numerical data
if ts.data[col].dtype == 'float64':
# Grab the column with the data we want
results = ts.data[col]
# Obtain the test statistics and the p-value using a Shapiro-Wilkinson test
stats, p = shapiro(results)
# Check to see if the data is normal or not
if p > .05:
print("Data is normal")
else:
print("Data is not normal")
# Create and display the quantile plot
probplot(results, plot=plt)
plt.figure()
def mse(y_test: List, y_forecast: List) -> float:
'''
Computes the Mean Squared Error (MSE) error of two time series.
RETURNS:
- the MSE as a float
ARGS:
- y_test: the time series data being tested (represented as a list)
- y_forecast: our forecasting model data (represented as a list)
'''
# Initialize a result variable
result = 0
# Calculate n
n = len(y_forecast)
# Loop through every data point in y_forecast and y_test
for i in range(n):
# Compute the difference between the actual data and our forecasting model
diff = y_test[i] - y_forecast[i]
# Square the difference and add it to result
result += (diff ** 2)
# Final multiplication step
result *= (1 / n)
if len(result) == 1:
result = result[0]
return result
def mape(y_test: List, y_forecast: List) -> float:
'''
Computes the Mean Absolute Percentage Error (MAPE) error of two time series.
RETURNS:
- the percentage error as a float
ARGS:
- y_test: the time series being tested
- y_forecast: our forecasting model
'''
# Initialize a result variable
result = 0
# Calculate n
n = len(y_forecast)
# Loop through every data point in y_forecast and y_test
for i in range(n):
# Compute the difference between the actual data and our forecasting model
diff = y_test[i] - y_forecast[i]
# Calculate the difference divided by the test data
inner = diff / y_test[i]
# Take the absolute value of the difference divided by the test data and add it to the result
result += abs(inner)
# Final multiplication step
result *= (1 / n)
# Convert to percentage
result *= 100
return result
def smape(y_test: List, y_forecast: List) -> float:
'''
Computes the Symmetric Mean Absolute Percentage Error (SMAPE) error of two time series.
RETURNS:
- the percentage error as a float
ARGS:
- y_test: the time series being tested
- y_forecast: our forecasting model
'''
# Initialize a result variable
result = 0
# Calculate n
n = len(y_forecast)
# Loop through every data point in y_forecast and y_test
for i in range(n):
# Compute the numerator of the SMAPE formula
numerator = abs(y_test[i] - y_forecast[i])
# Compute the absolute value of the test and forecast data for computational purposes
test_data = abs(y_test[i])
forecast_data = abs(y_forecast[i])
# Compute the denominator of the SMAPE formula
denominator = test_data + forecast_data
# Add the inner part of the sum to the result
result += (numerator / denominator)
# Final multiplication step
result *= (1 / n)
# Convert to percentage
result *= 100
return result
|
#include "MetaData.h"
#include <boost/assign.hpp>
MetaDataDecl gameDecls[] = {
// key, type, default, statistic, name in GuiMetaDataEd, prompt in GuiMetaDataEd
{"name", MD_STRING, "", false, "name", "enter game name"},
{"desc", MD_MULTILINE_STRING, "", false, "description", "enter description"},
{"image", MD_IMAGE_PATH, "", false, "image", "enter path to image"},
{"thumbnail", MD_IMAGE_PATH, "", false, "thumbnail", "enter path to thumbnail"},
{"rating", MD_RATING, "0.000000", false, "rating", "enter rating"},
{"releasedate", MD_DATE, "not-a-date-time", false, "release date", "enter release date"},
{"developer", MD_STRING, "unknown", false, "developer", "enter game developer"},
{"publisher", MD_STRING, "unknown", false, "publisher", "enter game publisher"},
{"genre", MD_STRING, "unknown", false, "genre", "enter game genre"},
{"players", MD_INT, "1", false, "players", "enter number of players"},
{"playcount", MD_INT, "0", true, "play count", "enter number of times played"},
{"lastplayed", MD_TIME, "0", true, "last played", "enter last played date"}
};
// because of how the GamelistDB is set up, this must be a subset of gameDecls
MetaDataDecl folderDecls[] = {
{"name", MD_STRING, "", false},
{"desc", MD_MULTILINE_STRING, "", false},
{"image", MD_IMAGE_PATH, "", false},
{"thumbnail", MD_IMAGE_PATH, "", false},
};
std::map< MetaDataListType, std::vector<MetaDataDecl> > MDD_map = boost::assign::map_list_of
(GAME_METADATA,
std::vector<MetaDataDecl>(gameDecls, gameDecls + sizeof(gameDecls) / sizeof(gameDecls[0])))
(FOLDER_METADATA,
std::vector<MetaDataDecl>(folderDecls, folderDecls + sizeof(folderDecls) / sizeof(folderDecls[0])));
const std::map<MetaDataListType, std::vector<MetaDataDecl> >& getMDDMap()
{
return MDD_map;
}
MetaDataMap::MetaDataMap(MetaDataListType type)
: mType(type)
{
const std::vector<MetaDataDecl>& mdd = getMDD();
for(auto iter = mdd.begin(); iter != mdd.end(); iter++)
set(iter->key, iter->defaultValue);
}
|
import tactic
import .tokens
namespace tactic
setup_tactic_parser
@[interactive]
meta def Posons := interactive.set
end tactic
example (a b : ℕ) : ℕ :=
begin
Posons n := max a b,
exact n,
end
|
We are proud to offer you our latest product.
The Curcumin edition is the newest member of the DNH product family. After a year of development and testing it's finally available from the webshop.
What is the reason for this product? Are the wonderful properties of CBD insufficient on their own?
As part of nature, CBD and Curcumin have a programme that is incomparable with anything else, CBD as highest in rank, but when it comes to attributed properties Curcumin is a good second. That’s exactly why we call it the best of both worlds. Curcumin and CBD are in part, as regards effect and properties, aligned with each other and therefore increase the chance of making a valuable contribution to the well-being of humans and animals.
There are also properties attributed to Curcumin that provide a great deal of extra added value independently of CBD.
We opted for 30 ml and 50 ml packaging to draw individual attention to both products and to present these in the best possible way. As a result, the ratio CBD and Curcumin is 1 : 1 and this is the ratio that has been tested as best.
The Curcumin edition is also particularly suitable for preventative use, 10 drops in cup of tea, glass of water or juice gives you a dream start to the day! Whenever you could use a little help, we recommend the use of 10 drops at breakfast and 10 drops during the day, and do please feel welcome to let us know what it does for you!
We think this is the most wonderful product of all and the best supplement ever. What do you think? |
"""
takes tree path, disease name, and similarity matrix and outputs node_df and re-done similarity_matrix
"""
import sys
sys.path.append("../")
import pandas as pd
import numpy as np
from augur.utils import json_to_tree
import json
from pathlib import Path
from Helpers import get_y_positions
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--tree_path", required=True, help="tree to convert for altair purposes")
parser.add_argument("--disease_name", required=True, help="name of disease")
args = parser.parse_args()
similarity_matrix = pd.read_csv('../Dataframes/distance_matrix_' + args.disease_name)
with open(args.tree_path) as fh:
json_tree_handle = json.load(fh)
tree = json_to_tree(json_tree_handle)
heights = get_y_positions(tree)
for node in tree.find_clades():
node.yvalue = heights[node]
node_data = [
{
"strain": node.name,
"date": node.node_attrs["num_date"]["value"],
"y": node.yvalue,
"region": node.node_attrs["region"]["value"],
"country": node.node_attrs["country"]["value"],
"parent_date": node.parent is not None and node.parent.node_attrs["num_date"]["value"] or node.node_attrs["num_date"],
"parent_y": node.parent is not None and node.parent.yvalue or node.yvalue,
"clade_membership" : node.node_attrs['clade_membership']["value"]
}
for node in tree.find_clades(terminal=True)
]
node_df = pd.DataFrame(node_data)
node_df["y"] = node_df["y"].max() - node_df["y"]
node_df["parent_y"] = node_df["parent_y"].max() - node_df["parent_y"]
# Reannotate clades that we aren't interested in as "other" to simplify color assignment in visualizations.
try:
node_df["clade_membership_color"] = node_df["clade_membership"].apply(lambda clade: clade if clade in clades_to_plot else "other")
except:
node_df["clade_membership_color"] = node_df["clade_membership"]
indices_to_drop = similarity_matrix[~similarity_matrix.index.isin(node_df["strain"])].dropna(how = 'all')
similarity_matrix = similarity_matrix[similarity_matrix.index.isin(node_df["strain"])].dropna(how = 'all')
similarity_matrix = similarity_matrix.drop(indices_to_drop.index, axis=1)
similarity_matrix.to_csv('../Dataframes/distance_matrix_' + args.disease_name + ".csv")
node_df.to_csv('../Dataframes/node_dataframe' + args.disease_name + '.csv')
|
## -------------------------------------------------------- ##
# Trab 2 IA 2019-2
#
# Rafael Belmock Pedruzzi
#
# probOneR.py: implementation of the probabilistic OneR classifier.
#
# Python version: 3.7.4
## -------------------------------------------------------- ##
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
from sklearn.utils.multiclass import unique_labels
from sklearn.metrics import euclidean_distances
from sklearn.preprocessing import KBinsDiscretizer
from sklearn.metrics.cluster import contingency_matrix
from sklearn.metrics import confusion_matrix
from itertools import product, zip_longest, accumulate
from random import random
class Prob_OneR(BaseEstimator, ClassifierMixin):
def fit(self, X, y):
# check that x and y have correct shape
X, y = check_X_y(X,y)
# store the classes seen during fit
self.classes_ = unique_labels(y)
self.y_ = y
kbd = KBinsDiscretizer(n_bins = len(np.unique(y)), encode='ordinal')
X = kbd.fit_transform(X)
self.X_ = X
self.kbd_ = kbd
cm_list = []
hits = []
for i in X.T:
cm = contingency_matrix(i, y)
cm_list.append(cm)
hits.append(sum(max(k) for k in cm))
rule = np.argmax(hits) # chosen rule
self.r_ = rule
rule_cm = cm_list[rule]
class_selector = []
for i, c in enumerate(rule_cm):
cSum = sum(c)
probRatio = [ (i/cSum) for i in c]
# Building the "partitions" of the roulette:
probRatio = list(accumulate(probRatio))
class_selector.append(probRatio)
self.class_selector = class_selector
# Return the classifier
return self
def predict(self, X):
# Check is fit had been called
check_is_fitted(self, ['X_', 'y_'])
# Input validation
X = check_array(X)
X = self.kbd_.transform(X)
y = []
for i in X[:,self.r_]:
probRatio = self.class_selector[int(i)]
# Selecting a random element:
selector = random()
for i in range(len(probRatio)):
if selector <= probRatio[i]:
y.append(self.classes_[i])
break
return y
# from sklearn import datasets
# from sklearn.model_selection import train_test_split, cross_val_score
# from sklearn.metrics import f1_score
# nn= Prob_OneR()
# iris = datasets.load_iris()
# x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target,test_size = 0.4, random_state = 0)
# nn.fit(x_train, y_train)
# y_pred = nn.predict(x_test)
# print(y_test)
# print(y_pred)
# score = cross_val_score(nn, x_train, y_train, cv = 5)
# print(score)
|
function mi = imMutualInformation(img1, img2)
%IMMUTUALINFORMATION Mutual information between two images
%
% MI = imMutualInformation(IMG1, IMG2)
% Computes the mutual information between two images.
% The mutual information can be related to entropy and joint entropy:
% MI = H1 + H2 - H12
% where H1 and H2 are the entropies computed on images IMG1 and IMG2, and
% H12 is the joint entropy of images IMG1 and IMG2.
%
% The mutual information between two independant images corresponds to
% the sum of the entropies computed for each image. The mutual
% information of an image with itself equals the entropy of this image.
%
% Example
% % compute mutual information between an image and a shifted copy of
% % itself
% img = imread('cameraman.tif');
% img2 = circshift(img, [2 3]);
% MI = imMutualInformation(img, img2)
% img3 = circshift(img, [5, 7]);
% MI3 = imMutualInformation(img, img2)
%
% % Check that we get same results by computing entropies (could be wrong
% % when computed on double images)
% img1 = imread('rice.png');
% img2 = circshift(img1, [3, 4]);
% imMutualInformation(img1, img2)
% ans =
% 1.0551
% h1 = imEntropy(img1);
% h2 = imEntropy(img2);
% h12 = imJointEntropy(img1, img2);
% h1 + h2 - h12
% ans =
% 1.0551
% See also
% imJointEntropy, imJointHistogram, imEntropy
%
% ------
% Author: David Legland
% e-mail: [email protected]
% Created: 2010-08-26, using Matlab 7.9.0.529 (R2009b)
% Copyright 2010 INRA - Cepia Software Platform.
% joint histogram, and reduced hisograms
hist12 = imJointHistogram(img1, img2);
hist1 = sum(hist12, 2);
hist2 = sum(hist12, 1);
% normalisation of histograms
hist12 = hist12(hist12 > 0) / sum(hist12(:));
hist1 = hist1(hist1 > 0) / sum(hist1(:));
hist2 = hist2(hist2 > 0) / sum(hist2(:));
% entropy of each image
h12 = -sum(hist12 .* log2(hist12));
h1 = -sum(hist1 .* log2(hist1));
h2 = -sum(hist2 .* log2(hist2));
% compute mutual information
mi = h1 + h2 - h12;
|
function [permuteMatrix, nNonRepeats, nUniqueDirs, nUniqueMeasurements] = dtiBootGetPermMatrix(bvecs, bvals)
%
% [permuteMatrix, nNonRepeats, nUniqueDirs, nUniqueMeasurements] = dtiBootGetPermMatrix(bvecs, bvals)
%
%
% HISTORY:
% 2007.06.07 RFD wrote it
n = min(size(bvals,2),size(bvecs,2));
bv = [bvecs(:,1:n).*repmat(bvals(:,1:n),[3 1])];
nMeasurements = size(bv,2);
permuteMatrix = cell(nMeasurements,1);
for(ii=1:nMeasurements)
dist1 = sqrt((bv(1,:)-bv(1,ii)).^2+(bv(2,:)-bv(2,ii)).^2+(bv(3,:)-bv(3,ii)).^2);
dist2 = sqrt((bv(1,:)+bv(1,ii)).^2+(bv(2,:)+bv(2,ii)).^2+(bv(3,:)+bv(3,ii)).^2);
permuteMatrix{ii} = unique([find(dist1<1e-3) find(dist2<1e-3)]);
end
numPerms = cellfun('length',permuteMatrix);
nNonRepeats = sum(numPerms==1);
m = zeros(nMeasurements,max(numPerms));
for(ii=1:nMeasurements)
m(ii,1:length(permuteMatrix{ii})) = permuteMatrix{ii};
end
nUniqueMeasurements = size(unique(m,'rows'),1);
if(any(bvals<max(bvals)*0.01))
nUniqueDirs = nUniqueMeasurements-1;
else
nUniqueDirs = nUniqueMeasurements;
end
return |
From Test Require Import tactic.
Section FOFProblem.
Variable Universe : Set.
Variable UniverseElement : Universe.
Variable s_ : Universe -> Universe -> Prop.
Variable notplus_ : Universe -> Universe -> Universe -> Prop.
Variable nat_ : Universe -> Prop.
Variable my_plus_ : Universe -> Universe -> Universe -> Prop.
Variable goal_ : Prop.
Variable dom_ : Universe -> Prop.
Variable x_ : Universe.
Variable num_0_ : Universe.
Variable initial_model_1 : (dom_ num_0_ /\ (dom_ x_ /\ (nat_ num_0_ /\ nat_ x_))).
Variable notplus_2 : (forall X Y Z : Universe, ((my_plus_ X Y Z /\ notplus_ X Y Z) -> goal_)).
Variable plusnull_3 : (forall X : Universe, (nat_ X -> my_plus_ X num_0_ X)).
Variable nullplus_4 : (forall X : Universe, (nat_ X -> my_plus_ num_0_ X X)).
Variable plussucc_5 : (forall X Y Z Y1 Z1 : Universe, ((my_plus_ X Y Z /\ (s_ Y Y1 /\ s_ Z Z1)) -> my_plus_ X Y1 Z1)).
Variable induction_instance_6 : (forall X : Universe, ((nat_ X /\ my_plus_ num_0_ num_0_ num_0_) -> (exists Y : Universe, (my_plus_ num_0_ X X \/ (dom_ X /\ (dom_ Y /\ (my_plus_ num_0_ X X /\ (s_ X Y /\ notplus_ num_0_ Y Y)))))))).
Variable succ_7 : (forall X : Universe, (nat_ X -> (exists Y : Universe, (dom_ Y /\ (nat_ Y /\ s_ X Y))))).
Theorem pa2_8 : goal_.
Proof.
time tac.
Qed.
End FOFProblem.
|
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(** Correctness of instruction selection for integer division *)
Require Import Coqlib.
Require Import AST.
Require Import Errors.
Require Import Integers.
Require Import Floats.
Require Import Values.
Require Import Memory.
Require Import Globalenvs.
Require Import Events.
Require Import Cminor.
Require Import Op.
Require Import CminorSel.
Require Import SelectOp.
Require Import SelectOpproof.
Require Import SelectLong.
Open Local Scope cminorsel_scope.
(** * Axiomatization of the helper functions *)
(** [CompCertX:test-compcert-param-memory] We create section [WITHMEM] and associated
contexts to parameterize the proof over the memory model. *)
(** [CompCertX:test-compcert-param-extcall] Actually, we also need to parameterize
over external functions. To this end, we created a [CompilerConfiguration] class
(cf. [Events]) which is designed to be the single class on which the whole CompCert is to be
parameterized. It includes all operations and properties on which CompCert depends:
memory model, semantics of external functions and their preservation through
compilation. *)
Section WITHCONFIG.
Context `{compiler_config: CompilerConfiguration}.
(** [CompCertX:test-compcert-protect-stack-arg] We also parameterize over a way to mark blocks writable. *)
Context `{writable_block_ops: WritableBlockOps}.
Section HELPERS.
Context {F V: Type} (ge: Genv.t (AST.fundef F) V).
Definition helper_implements (id: ident) (sg: signature) (vargs: list val) (vres: val) : Prop :=
exists b, exists ef,
Genv.find_symbol ge id = Some b
/\ Genv.find_funct_ptr ge b = Some (External ef)
/\ ef_sig ef = sg
/\ forall m, external_call ef (writable_block ge) ge vargs m E0 vres m.
Definition builtin_implements (id: ident) (sg: signature) (vargs: list val) (vres: val) : Prop :=
forall m, external_call (EF_builtin id sg) (writable_block ge) ge vargs m E0 vres m.
Definition i64_helpers_correct (hf: helper_functions) : Prop :=
(forall x z, Val.longoffloat x = Some z -> helper_implements hf.(i64_dtos) sig_f_l (x::nil) z)
/\(forall x z, Val.longuoffloat x = Some z -> helper_implements hf.(i64_dtou) sig_f_l (x::nil) z)
/\(forall x z, Val.floatoflong x = Some z -> helper_implements hf.(i64_stod) sig_l_f (x::nil) z)
/\(forall x z, Val.floatoflongu x = Some z -> helper_implements hf.(i64_utod) sig_l_f (x::nil) z)
/\(forall x z, Val.singleoflong x = Some z -> helper_implements hf.(i64_stof) sig_l_s (x::nil) z)
/\(forall x z, Val.singleoflongu x = Some z -> helper_implements hf.(i64_utof) sig_l_s (x::nil) z)
/\(forall x, builtin_implements hf.(i64_neg) sig_l_l (x::nil) (Val.negl x))
/\(forall x y, builtin_implements hf.(i64_add) sig_ll_l (x::y::nil) (Val.addl x y))
/\(forall x y, builtin_implements hf.(i64_sub) sig_ll_l (x::y::nil) (Val.subl x y))
/\(forall x y, builtin_implements hf.(i64_mul) sig_ii_l (x::y::nil) (Val.mull' x y))
/\(forall x y z, Val.divls x y = Some z -> helper_implements hf.(i64_sdiv) sig_ll_l (x::y::nil) z)
/\(forall x y z, Val.divlu x y = Some z -> helper_implements hf.(i64_udiv) sig_ll_l (x::y::nil) z)
/\(forall x y z, Val.modls x y = Some z -> helper_implements hf.(i64_smod) sig_ll_l (x::y::nil) z)
/\(forall x y z, Val.modlu x y = Some z -> helper_implements hf.(i64_umod) sig_ll_l (x::y::nil) z)
/\(forall x y, helper_implements hf.(i64_shl) sig_li_l (x::y::nil) (Val.shll x y))
/\(forall x y, helper_implements hf.(i64_shr) sig_li_l (x::y::nil) (Val.shrlu x y))
/\(forall x y, helper_implements hf.(i64_sar) sig_li_l (x::y::nil) (Val.shrl x y)).
End HELPERS.
(** * Correctness of the instruction selection functions for 64-bit operators *)
Section CMCONSTR.
Variable hf: helper_functions.
Variable ge: genv.
Hypothesis HELPERS: i64_helpers_correct ge hf.
Variable sp: val.
Variable e: env.
Variable m: mem.
Ltac UseHelper :=
red in HELPERS;
repeat (eauto; match goal with | [ H: _ /\ _ |- _ ] => destruct H end).
Lemma eval_helper:
forall le id sg args vargs vres,
eval_exprlist ge sp e m le args vargs ->
helper_implements ge id sg vargs vres ->
eval_expr ge sp e m le (Eexternal id sg args) vres.
Proof.
intros. destruct H0 as (b & ef & A & B & C & D). econstructor; eauto.
Qed.
Corollary eval_helper_1:
forall le id sg arg1 varg1 vres,
eval_expr ge sp e m le arg1 varg1 ->
helper_implements ge id sg (varg1::nil) vres ->
eval_expr ge sp e m le (Eexternal id sg (arg1 ::: Enil)) vres.
Proof.
intros. eapply eval_helper; eauto. constructor; auto. constructor.
Qed.
Corollary eval_helper_2:
forall le id sg arg1 arg2 varg1 varg2 vres,
eval_expr ge sp e m le arg1 varg1 ->
eval_expr ge sp e m le arg2 varg2 ->
helper_implements ge id sg (varg1::varg2::nil) vres ->
eval_expr ge sp e m le (Eexternal id sg (arg1 ::: arg2 ::: Enil)) vres.
Proof.
intros. eapply eval_helper; eauto. constructor; auto. constructor; auto. constructor.
Qed.
Remark eval_builtin_1:
forall le id sg arg1 varg1 vres,
eval_expr ge sp e m le arg1 varg1 ->
builtin_implements ge id sg (varg1::nil) vres ->
eval_expr ge sp e m le (Ebuiltin (EF_builtin id sg) (arg1 ::: Enil)) vres.
Proof.
intros. econstructor. econstructor. eauto. constructor. apply H0.
auto.
Qed.
Remark eval_builtin_2:
forall le id sg arg1 arg2 varg1 varg2 vres,
eval_expr ge sp e m le arg1 varg1 ->
eval_expr ge sp e m le arg2 varg2 ->
builtin_implements ge id sg (varg1::varg2::nil) vres ->
eval_expr ge sp e m le (Ebuiltin (EF_builtin id sg) (arg1 ::: arg2 ::: Enil)) vres.
Proof.
intros. econstructor. constructor; eauto. constructor; eauto. constructor. apply H1.
auto.
Qed.
Definition unary_constructor_sound (cstr: expr -> expr) (sem: val -> val) : Prop :=
forall le a x,
eval_expr ge sp e m le a x ->
exists v, eval_expr ge sp e m le (cstr a) v /\ Val.lessdef (sem x) v.
Definition binary_constructor_sound (cstr: expr -> expr -> expr) (sem: val -> val -> val) : Prop :=
forall le a x b y,
eval_expr ge sp e m le a x ->
eval_expr ge sp e m le b y ->
exists v, eval_expr ge sp e m le (cstr a b) v /\ Val.lessdef (sem x y) v.
Ltac EvalOp :=
eauto;
match goal with
| [ |- eval_exprlist _ _ _ _ _ Enil _ ] => constructor
| [ |- eval_exprlist _ _ _ _ _ (_:::_) _ ] => econstructor; EvalOp
| [ |- eval_expr _ _ _ _ _ (Eletvar _) _ ] => constructor; simpl; eauto
| [ |- eval_expr _ _ _ _ _ (Elet _ _) _ ] => econstructor; EvalOp
| [ |- eval_expr _ _ _ _ _ (lift _) _ ] => apply eval_lift; EvalOp
| [ |- eval_expr _ _ _ _ _ _ _ ] => eapply eval_Eop; [EvalOp | simpl; eauto]
| _ => idtac
end.
Lemma eval_splitlong:
forall le a f v sem,
(forall le a b x y,
eval_expr ge sp e m le a x ->
eval_expr ge sp e m le b y ->
exists v, eval_expr ge sp e m le (f a b) v /\
(forall p q, x = Vint p -> y = Vint q -> v = sem (Vlong (Int64.ofwords p q)))) ->
match v with Vlong _ => True | _ => sem v = Vundef end ->
eval_expr ge sp e m le a v ->
exists v', eval_expr ge sp e m le (splitlong a f) v' /\ Val.lessdef (sem v) v'.
Proof.
intros until sem; intros EXEC UNDEF.
unfold splitlong. case (splitlong_match a); intros.
- InvEval. subst v.
exploit EXEC. eexact H2. eexact H3. intros [v' [A B]].
exists v'; split. auto.
destruct v1; simpl in *; try (rewrite UNDEF; auto).
destruct v0; simpl in *; try (rewrite UNDEF; auto).
erewrite B; eauto.
- exploit (EXEC (v :: le) (Eop Ohighlong (Eletvar 0 ::: Enil)) (Eop Olowlong (Eletvar 0 ::: Enil))).
EvalOp. EvalOp.
intros [v' [A B]].
exists v'; split. econstructor; eauto.
destruct v; try (rewrite UNDEF; auto). erewrite B; simpl; eauto. rewrite Int64.ofwords_recompose. auto.
Qed.
Lemma eval_splitlong_strict:
forall le a f va v,
eval_expr ge sp e m le a (Vlong va) ->
(forall le a1 a2,
eval_expr ge sp e m le a1 (Vint (Int64.hiword va)) ->
eval_expr ge sp e m le a2 (Vint (Int64.loword va)) ->
eval_expr ge sp e m le (f a1 a2) v) ->
eval_expr ge sp e m le (splitlong a f) v.
Proof.
intros until v.
unfold splitlong. case (splitlong_match a); intros.
- InvEval. destruct v1; simpl in H; try discriminate. destruct v0; inv H.
apply H0. rewrite Int64.hi_ofwords; auto. rewrite Int64.lo_ofwords; auto.
- EvalOp. apply H0; EvalOp.
Qed.
Lemma eval_splitlong2:
forall le a b f va vb sem,
(forall le a1 a2 b1 b2 x1 x2 y1 y2,
eval_expr ge sp e m le a1 x1 ->
eval_expr ge sp e m le a2 x2 ->
eval_expr ge sp e m le b1 y1 ->
eval_expr ge sp e m le b2 y2 ->
exists v,
eval_expr ge sp e m le (f a1 a2 b1 b2) v /\
(forall p1 p2 q1 q2,
x1 = Vint p1 -> x2 = Vint p2 -> y1 = Vint q1 -> y2 = Vint q2 ->
v = sem (Vlong (Int64.ofwords p1 p2)) (Vlong (Int64.ofwords q1 q2)))) ->
match va, vb with Vlong _, Vlong _ => True | _, _ => sem va vb = Vundef end ->
eval_expr ge sp e m le a va ->
eval_expr ge sp e m le b vb ->
exists v, eval_expr ge sp e m le (splitlong2 a b f) v /\ Val.lessdef (sem va vb) v.
Proof.
intros until sem; intros EXEC UNDEF.
unfold splitlong2. case (splitlong2_match a b); intros.
- InvEval. subst va vb.
exploit (EXEC le h1 l1 h2 l2); eauto. intros [v [A B]].
exists v; split; auto.
destruct v1; simpl in *; try (rewrite UNDEF; auto).
destruct v0; try (rewrite UNDEF; auto).
destruct v2; simpl in *; try (rewrite UNDEF; auto).
destruct v3; try (rewrite UNDEF; auto).
erewrite B; eauto.
- InvEval. subst va.
exploit (EXEC (vb :: le) (lift h1) (lift l1)
(Eop Ohighlong (Eletvar 0 ::: Enil)) (Eop Olowlong (Eletvar 0 ::: Enil))).
EvalOp. EvalOp. EvalOp. EvalOp.
intros [v [A B]].
exists v; split.
econstructor; eauto.
destruct v1; simpl in *; try (rewrite UNDEF; auto).
destruct v0; try (rewrite UNDEF; auto).
destruct vb; try (rewrite UNDEF; auto).
erewrite B; simpl; eauto. rewrite Int64.ofwords_recompose. auto.
- InvEval. subst vb.
exploit (EXEC (va :: le)
(Eop Ohighlong (Eletvar 0 ::: Enil)) (Eop Olowlong (Eletvar 0 ::: Enil))
(lift h2) (lift l2)).
EvalOp. EvalOp. EvalOp. EvalOp.
intros [v [A B]].
exists v; split.
econstructor; eauto.
destruct va; try (rewrite UNDEF; auto).
destruct v1; simpl in *; try (rewrite UNDEF; auto).
destruct v0; try (rewrite UNDEF; auto).
erewrite B; simpl; eauto. rewrite Int64.ofwords_recompose. auto.
- exploit (EXEC (vb :: va :: le)
(Eop Ohighlong (Eletvar 1 ::: Enil)) (Eop Olowlong (Eletvar 1 ::: Enil))
(Eop Ohighlong (Eletvar 0 ::: Enil)) (Eop Olowlong (Eletvar 0 ::: Enil))).
EvalOp. EvalOp. EvalOp. EvalOp.
intros [v [A B]].
exists v; split. EvalOp.
destruct va; try (rewrite UNDEF; auto); destruct vb; try (rewrite UNDEF; auto).
erewrite B; simpl; eauto. rewrite ! Int64.ofwords_recompose; auto.
Qed.
Lemma eval_splitlong2_strict:
forall le a b f va vb v,
eval_expr ge sp e m le a (Vlong va) ->
eval_expr ge sp e m le b (Vlong vb) ->
(forall le a1 a2 b1 b2,
eval_expr ge sp e m le a1 (Vint (Int64.hiword va)) ->
eval_expr ge sp e m le a2 (Vint (Int64.loword va)) ->
eval_expr ge sp e m le b1 (Vint (Int64.hiword vb)) ->
eval_expr ge sp e m le b2 (Vint (Int64.loword vb)) ->
eval_expr ge sp e m le (f a1 a2 b1 b2) v) ->
eval_expr ge sp e m le (splitlong2 a b f) v.
Proof.
assert (INV: forall v1 v2 n,
Val.longofwords v1 v2 = Vlong n -> v1 = Vint(Int64.hiword n) /\ v2 = Vint(Int64.loword n)).
{
intros. destruct v1; simpl in H; try discriminate. destruct v2; inv H.
rewrite Int64.hi_ofwords; rewrite Int64.lo_ofwords; auto.
}
intros until v.
unfold splitlong2. case (splitlong2_match a b); intros.
- InvEval. exploit INV. eexact H. intros [EQ1 EQ2]. exploit INV. eexact H0. intros [EQ3 EQ4].
subst. auto.
- InvEval. exploit INV; eauto. intros [EQ1 EQ2]. subst.
econstructor. eauto. apply H1; EvalOp.
- InvEval. exploit INV; eauto. intros [EQ1 EQ2]. subst.
econstructor. eauto. apply H1; EvalOp.
- EvalOp. apply H1; EvalOp.
Qed.
Lemma is_longconst_sound:
forall le a x n,
is_longconst a = Some n ->
eval_expr ge sp e m le a x ->
x = Vlong n.
Proof.
unfold is_longconst; intros until n; intros LC.
destruct (is_longconst_match a); intros.
inv LC. InvEval. simpl in H5. inv H5. auto.
discriminate.
Qed.
Lemma is_longconst_zero_sound:
forall le a x,
is_longconst_zero a = true ->
eval_expr ge sp e m le a x ->
x = Vlong Int64.zero.
Proof.
unfold is_longconst_zero; intros.
destruct (is_longconst a) as [n|] eqn:E; try discriminate.
revert H. predSpec Int64.eq Int64.eq_spec n Int64.zero.
intros. subst. eapply is_longconst_sound; eauto.
congruence.
Qed.
Lemma eval_lowlong: unary_constructor_sound lowlong Val.loword.
Proof.
unfold lowlong; red. intros until x. destruct (lowlong_match a); intros.
InvEval. subst x. exists v0; split; auto.
destruct v1; simpl; auto. destruct v0; simpl; auto.
rewrite Int64.lo_ofwords. auto.
exists (Val.loword x); split; auto. EvalOp.
Qed.
Lemma eval_highlong: unary_constructor_sound highlong Val.hiword.
Proof.
unfold highlong; red. intros until x. destruct (highlong_match a); intros.
InvEval. subst x. exists v1; split; auto.
destruct v1; simpl; auto. destruct v0; simpl; auto.
rewrite Int64.hi_ofwords. auto.
exists (Val.hiword x); split; auto. EvalOp.
Qed.
Lemma eval_longconst:
forall le n, eval_expr ge sp e m le (longconst n) (Vlong n).
Proof.
intros. EvalOp. rewrite Int64.ofwords_recompose; auto.
Qed.
Theorem eval_intoflong: unary_constructor_sound intoflong Val.loword.
Proof eval_lowlong.
Theorem eval_longofintu: unary_constructor_sound longofintu Val.longofintu.
Proof.
red; intros. unfold longofintu. econstructor; split. EvalOp.
unfold Val.longofintu. destruct x; auto.
replace (Int64.repr (Int.unsigned i)) with (Int64.ofwords Int.zero i); auto.
apply Int64.same_bits_eq; intros.
rewrite Int64.testbit_repr by auto.
rewrite Int64.bits_ofwords by auto.
fold (Int.testbit i i0).
destruct (zlt i0 Int.zwordsize).
auto.
rewrite Int.bits_zero. rewrite Int.bits_above by omega. auto.
Qed.
Theorem eval_longofint: unary_constructor_sound longofint Val.longofint.
Proof.
red; intros. unfold longofint.
exploit (eval_shrimm ge sp e m (Int.repr 31) (x :: le) (Eletvar 0)). EvalOp.
intros [v1 [A B]].
econstructor; split. EvalOp.
destruct x; simpl; auto.
simpl in B. inv B. simpl.
replace (Int64.repr (Int.signed i))
with (Int64.ofwords (Int.shr i (Int.repr 31)) i); auto.
apply Int64.same_bits_eq; intros.
rewrite Int64.testbit_repr by auto.
rewrite Int64.bits_ofwords by auto.
rewrite Int.bits_signed by omega.
destruct (zlt i0 Int.zwordsize).
auto.
assert (Int64.zwordsize = 2 * Int.zwordsize) by reflexivity.
rewrite Int.bits_shr by omega.
change (Int.unsigned (Int.repr 31)) with (Int.zwordsize - 1).
f_equal. destruct (zlt (i0 - Int.zwordsize + (Int.zwordsize - 1)) Int.zwordsize); omega.
Qed.
Theorem eval_negl: unary_constructor_sound (negl hf) Val.negl.
Proof.
unfold negl; red; intros. destruct (is_longconst a) eqn:E.
econstructor; split. apply eval_longconst.
exploit is_longconst_sound; eauto. intros EQ; subst x. simpl. auto.
econstructor; split. eapply eval_builtin_1; eauto. UseHelper. auto.
Qed.
Theorem eval_notl: unary_constructor_sound notl Val.notl.
Proof.
red; intros. unfold notl. apply eval_splitlong; auto.
intros.
exploit eval_notint. eexact H0. intros [va [A B]].
exploit eval_notint. eexact H1. intros [vb [C D]].
exists (Val.longofwords va vb); split. EvalOp.
intros; subst. simpl in *. inv B; inv D.
simpl. unfold Int.not. rewrite <- Int64.decompose_xor. auto.
destruct x; auto.
Qed.
Theorem eval_longoffloat:
forall le a x y,
eval_expr ge sp e m le a x ->
Val.longoffloat x = Some y ->
exists v, eval_expr ge sp e m le (longoffloat hf a) v /\ Val.lessdef y v.
Proof.
intros; unfold longoffloat. econstructor; split.
eapply eval_helper_1; eauto. UseHelper.
auto.
Qed.
Theorem eval_longuoffloat:
forall le a x y,
eval_expr ge sp e m le a x ->
Val.longuoffloat x = Some y ->
exists v, eval_expr ge sp e m le (longuoffloat hf a) v /\ Val.lessdef y v.
Proof.
intros; unfold longuoffloat. econstructor; split.
eapply eval_helper_1; eauto. UseHelper.
auto.
Qed.
Theorem eval_floatoflong:
forall le a x y,
eval_expr ge sp e m le a x ->
Val.floatoflong x = Some y ->
exists v, eval_expr ge sp e m le (floatoflong hf a) v /\ Val.lessdef y v.
Proof.
intros; unfold floatoflong. econstructor; split.
eapply eval_helper_1; eauto. UseHelper.
auto.
Qed.
Theorem eval_floatoflongu:
forall le a x y,
eval_expr ge sp e m le a x ->
Val.floatoflongu x = Some y ->
exists v, eval_expr ge sp e m le (floatoflongu hf a) v /\ Val.lessdef y v.
Proof.
intros; unfold floatoflongu. econstructor; split.
eapply eval_helper_1; eauto. UseHelper.
auto.
Qed.
Theorem eval_singleoflong:
forall le a x y,
eval_expr ge sp e m le a x ->
Val.singleoflong x = Some y ->
exists v, eval_expr ge sp e m le (singleoflong hf a) v /\ Val.lessdef y v.
Proof.
intros; unfold singleoflong. econstructor; split.
eapply eval_helper_1; eauto. UseHelper.
auto.
Qed.
Theorem eval_singleoflongu:
forall le a x y,
eval_expr ge sp e m le a x ->
Val.singleoflongu x = Some y ->
exists v, eval_expr ge sp e m le (singleoflongu hf a) v /\ Val.lessdef y v.
Proof.
intros; unfold singleoflongu. econstructor; split.
eapply eval_helper_1; eauto. UseHelper.
auto.
Qed.
Theorem eval_andl: binary_constructor_sound andl Val.andl.
Proof.
red; intros. unfold andl. apply eval_splitlong2; auto.
intros.
exploit eval_and. eexact H1. eexact H3. intros [va [A B]].
exploit eval_and. eexact H2. eexact H4. intros [vb [C D]].
exists (Val.longofwords va vb); split. EvalOp.
intros; subst. simpl in B; inv B. simpl in D; inv D.
simpl. f_equal. rewrite Int64.decompose_and. auto.
destruct x; auto. destruct y; auto.
Qed.
Theorem eval_orl: binary_constructor_sound orl Val.orl.
Proof.
red; intros. unfold orl. apply eval_splitlong2; auto.
intros.
exploit eval_or. eexact H1. eexact H3. intros [va [A B]].
exploit eval_or. eexact H2. eexact H4. intros [vb [C D]].
exists (Val.longofwords va vb); split. EvalOp.
intros; subst. simpl in B; inv B. simpl in D; inv D.
simpl. f_equal. rewrite Int64.decompose_or. auto.
destruct x; auto. destruct y; auto.
Qed.
Theorem eval_xorl: binary_constructor_sound xorl Val.xorl.
Proof.
red; intros. unfold xorl. apply eval_splitlong2; auto.
intros.
exploit eval_xor. eexact H1. eexact H3. intros [va [A B]].
exploit eval_xor. eexact H2. eexact H4. intros [vb [C D]].
exists (Val.longofwords va vb); split. EvalOp.
intros; subst. simpl in B; inv B. simpl in D; inv D.
simpl. f_equal. rewrite Int64.decompose_xor. auto.
destruct x; auto. destruct y; auto.
Qed.
Lemma is_intconst_sound:
forall le a x n,
is_intconst a = Some n ->
eval_expr ge sp e m le a x ->
x = Vint n.
Proof.
unfold is_intconst; intros until n; intros LC.
destruct a; try discriminate. destruct o; try discriminate. destruct e0; try discriminate.
inv LC. intros. InvEval. auto.
Qed.
Remark eval_shift_imm:
forall (P: expr -> Prop) n a0 a1 a2 a3,
(n = Int.zero -> P a0) ->
(0 <= Int.unsigned n < Int.zwordsize ->
Int.ltu n Int.iwordsize = true ->
Int.ltu (Int.sub Int.iwordsize n) Int.iwordsize = true ->
Int.ltu n Int64.iwordsize' = true ->
P a1) ->
(Int.zwordsize <= Int.unsigned n < Int64.zwordsize ->
Int.ltu (Int.sub n Int.iwordsize) Int.iwordsize = true ->
P a2) ->
P a3 ->
P (if Int.eq n Int.zero then a0
else if Int.ltu n Int.iwordsize then a1
else if Int.ltu n Int64.iwordsize' then a2
else a3).
Proof.
intros until a3; intros A0 A1 A2 A3.
predSpec Int.eq Int.eq_spec n Int.zero.
apply A0; auto.
assert (NZ: Int.unsigned n <> 0).
{ red; intros. elim H. rewrite <- (Int.repr_unsigned n). rewrite H0. auto. }
destruct (Int.ltu n Int.iwordsize) eqn:LT.
exploit Int.ltu_iwordsize_inv; eauto. intros RANGE.
assert (0 <= Int.zwordsize - Int.unsigned n < Int.zwordsize) by omega.
apply A1. auto. auto.
unfold Int.ltu, Int.sub. rewrite Int.unsigned_repr_wordsize.
rewrite Int.unsigned_repr. rewrite zlt_true; auto. omega.
generalize Int.wordsize_max_unsigned; omega.
unfold Int.ltu. rewrite zlt_true; auto.
change (Int.unsigned Int64.iwordsize') with 64.
change Int.zwordsize with 32 in RANGE. omega.
destruct (Int.ltu n Int64.iwordsize') eqn:LT'.
exploit Int.ltu_inv; eauto.
change (Int.unsigned Int64.iwordsize') with (Int.zwordsize * 2).
intros RANGE.
assert (Int.zwordsize <= Int.unsigned n).
unfold Int.ltu in LT. rewrite Int.unsigned_repr_wordsize in LT.
destruct (zlt (Int.unsigned n) Int.zwordsize). discriminate. omega.
apply A2. tauto. unfold Int.ltu, Int.sub. rewrite Int.unsigned_repr_wordsize.
rewrite Int.unsigned_repr. rewrite zlt_true; auto. omega.
generalize Int.wordsize_max_unsigned; omega.
auto.
Qed.
Lemma eval_shllimm:
forall n,
unary_constructor_sound (fun e => shllimm hf e n) (fun v => Val.shll v (Vint n)).
Proof.
unfold shllimm; red; intros.
apply eval_shift_imm; intros.
+ (* n = 0 *)
subst n. exists x; split; auto. destruct x; simpl; auto.
change (Int64.shl' i Int.zero) with (Int64.shl i Int64.zero).
rewrite Int64.shl_zero. auto.
+ (* 0 < n < 32 *)
apply eval_splitlong with (sem := fun x => Val.shll x (Vint n)); auto.
intros.
exploit eval_shlimm. eexact H4. instantiate (1 := n). intros [v1 [A1 B1]].
exploit eval_shlimm. eexact H5. instantiate (1 := n). intros [v2 [A2 B2]].
exploit eval_shruimm. eexact H5. instantiate (1 := Int.sub Int.iwordsize n). intros [v3 [A3 B3]].
exploit eval_or. eexact A1. eexact A3. intros [v4 [A4 B4]].
econstructor; split. EvalOp.
intros. subst. simpl in *. rewrite H1 in *. rewrite H2 in *. rewrite H3.
inv B1; inv B2; inv B3. simpl in B4. inv B4.
simpl. rewrite Int64.decompose_shl_1; auto.
destruct x; auto.
+ (* 32 <= n < 64 *)
exploit eval_lowlong. eexact H. intros [v1 [A1 B1]].
exploit eval_shlimm. eexact A1. instantiate (1 := Int.sub n Int.iwordsize). intros [v2 [A2 B2]].
econstructor; split. EvalOp.
destruct x; simpl; auto.
destruct (Int.ltu n Int64.iwordsize'); auto.
simpl in B1; inv B1. simpl in B2. rewrite H1 in B2. inv B2.
simpl. erewrite <- Int64.decompose_shl_2. instantiate (1 := Int64.hiword i).
rewrite Int64.ofwords_recompose. auto. auto.
+ (* n >= 64 *)
econstructor; split. eapply eval_helper_2; eauto. EvalOp. UseHelper. auto.
Qed.
Theorem eval_shll: binary_constructor_sound (shll hf) Val.shll.
Proof.
unfold shll; red; intros.
destruct (is_intconst b) as [n|] eqn:IC.
- (* Immediate *)
exploit is_intconst_sound; eauto. intros EQ; subst y; clear H0.
eapply eval_shllimm; eauto.
- (* General case *)
econstructor; split. eapply eval_helper_2; eauto. UseHelper. auto.
Qed.
Lemma eval_shrluimm:
forall n,
unary_constructor_sound (fun e => shrluimm hf e n) (fun v => Val.shrlu v (Vint n)).
Proof.
unfold shrluimm; red; intros. apply eval_shift_imm; intros.
+ (* n = 0 *)
subst n. exists x; split; auto. destruct x; simpl; auto.
change (Int64.shru' i Int.zero) with (Int64.shru i Int64.zero).
rewrite Int64.shru_zero. auto.
+ (* 0 < n < 32 *)
apply eval_splitlong with (sem := fun x => Val.shrlu x (Vint n)); auto.
intros.
exploit eval_shruimm. eexact H5. instantiate (1 := n). intros [v1 [A1 B1]].
exploit eval_shruimm. eexact H4. instantiate (1 := n). intros [v2 [A2 B2]].
exploit eval_shlimm. eexact H4. instantiate (1 := Int.sub Int.iwordsize n). intros [v3 [A3 B3]].
exploit eval_or. eexact A1. eexact A3. intros [v4 [A4 B4]].
econstructor; split. EvalOp.
intros. subst. simpl in *. rewrite H1 in *. rewrite H2 in *. rewrite H3.
inv B1; inv B2; inv B3. simpl in B4. inv B4.
simpl. rewrite Int64.decompose_shru_1; auto.
destruct x; auto.
+ (* 32 <= n < 64 *)
exploit eval_highlong. eexact H. intros [v1 [A1 B1]].
exploit eval_shruimm. eexact A1. instantiate (1 := Int.sub n Int.iwordsize). intros [v2 [A2 B2]].
econstructor; split. EvalOp.
destruct x; simpl; auto.
destruct (Int.ltu n Int64.iwordsize'); auto.
simpl in B1; inv B1. simpl in B2. rewrite H1 in B2. inv B2.
simpl. erewrite <- Int64.decompose_shru_2. instantiate (1 := Int64.loword i).
rewrite Int64.ofwords_recompose. auto. auto.
+ (* n >= 64 *)
econstructor; split. eapply eval_helper_2; eauto. EvalOp. UseHelper. auto.
Qed.
Theorem eval_shrlu: binary_constructor_sound (shrlu hf) Val.shrlu.
Proof.
unfold shrlu; red; intros.
destruct (is_intconst b) as [n|] eqn:IC.
- (* Immediate *)
exploit is_intconst_sound; eauto. intros EQ; subst y; clear H0.
eapply eval_shrluimm; eauto.
- (* General case *)
econstructor; split. eapply eval_helper_2; eauto. UseHelper. auto.
Qed.
Lemma eval_shrlimm:
forall n,
unary_constructor_sound (fun e => shrlimm hf e n) (fun v => Val.shrl v (Vint n)).
Proof.
unfold shrlimm; red; intros. apply eval_shift_imm; intros.
+ (* n = 0 *)
subst n. exists x; split; auto. destruct x; simpl; auto.
change (Int64.shr' i Int.zero) with (Int64.shr i Int64.zero).
rewrite Int64.shr_zero. auto.
+ (* 0 < n < 32 *)
apply eval_splitlong with (sem := fun x => Val.shrl x (Vint n)); auto.
intros.
exploit eval_shruimm. eexact H5. instantiate (1 := n). intros [v1 [A1 B1]].
exploit eval_shrimm. eexact H4. instantiate (1 := n). intros [v2 [A2 B2]].
exploit eval_shlimm. eexact H4. instantiate (1 := Int.sub Int.iwordsize n). intros [v3 [A3 B3]].
exploit eval_or. eexact A1. eexact A3. intros [v4 [A4 B4]].
econstructor; split. EvalOp.
intros. subst. simpl in *. rewrite H1 in *. rewrite H2 in *. rewrite H3.
inv B1; inv B2; inv B3. simpl in B4. inv B4.
simpl. rewrite Int64.decompose_shr_1; auto.
destruct x; auto.
+ (* 32 <= n < 64 *)
exploit eval_highlong. eexact H. intros [v1 [A1 B1]].
assert (eval_expr ge sp e m (v1 :: le) (Eletvar 0) v1) by EvalOp.
exploit eval_shrimm. eexact H2. instantiate (1 := Int.sub n Int.iwordsize). intros [v2 [A2 B2]].
exploit eval_shrimm. eexact H2. instantiate (1 := Int.repr 31). intros [v3 [A3 B3]].
econstructor; split. EvalOp.
destruct x; simpl; auto.
destruct (Int.ltu n Int64.iwordsize'); auto.
simpl in B1; inv B1. simpl in B2. rewrite H1 in B2. inv B2.
simpl in B3. inv B3.
change (Int.ltu (Int.repr 31) Int.iwordsize) with true. simpl.
erewrite <- Int64.decompose_shr_2. instantiate (1 := Int64.loword i).
rewrite Int64.ofwords_recompose. auto. auto.
+ (* n >= 64 *)
econstructor; split. eapply eval_helper_2; eauto. EvalOp. UseHelper. auto.
Qed.
Theorem eval_shrl: binary_constructor_sound (shrl hf) Val.shrl.
Proof.
unfold shrl; red; intros.
destruct (is_intconst b) as [n|] eqn:IC.
- (* Immediate *)
exploit is_intconst_sound; eauto. intros EQ; subst y; clear H0.
eapply eval_shrlimm; eauto.
- (* General case *)
econstructor; split. eapply eval_helper_2; eauto. UseHelper. auto.
Qed.
Theorem eval_addl: binary_constructor_sound (addl hf) Val.addl.
Proof.
unfold addl; red; intros.
set (default := Ebuiltin (EF_builtin (i64_add hf) sig_ll_l) (a ::: b ::: Enil)).
assert (DEFAULT:
exists v, eval_expr ge sp e m le default v /\ Val.lessdef (Val.addl x y) v).
{
econstructor; split. eapply eval_builtin_2; eauto. UseHelper. auto.
}
destruct (is_longconst a) as [p|] eqn:LC1;
destruct (is_longconst b) as [q|] eqn:LC2.
- exploit (is_longconst_sound le a); eauto. intros EQ; subst x.
exploit (is_longconst_sound le b); eauto. intros EQ; subst y.
econstructor; split. apply eval_longconst. simpl; auto.
- predSpec Int64.eq Int64.eq_spec p Int64.zero; auto.
subst p. exploit (is_longconst_sound le a); eauto. intros EQ; subst x.
exists y; split; auto. simpl. destruct y; auto. rewrite Int64.add_zero_l; auto.
- predSpec Int64.eq Int64.eq_spec q Int64.zero; auto.
subst q. exploit (is_longconst_sound le b); eauto. intros EQ; subst y.
exists x; split; auto. destruct x; simpl; auto. rewrite Int64.add_zero; auto.
- auto.
Qed.
Theorem eval_subl: binary_constructor_sound (subl hf) Val.subl.
Proof.
unfold subl; red; intros.
set (default := Ebuiltin (EF_builtin (i64_sub hf) sig_ll_l) (a ::: b ::: Enil)).
assert (DEFAULT:
exists v, eval_expr ge sp e m le default v /\ Val.lessdef (Val.subl x y) v).
{
econstructor; split. eapply eval_builtin_2; eauto. UseHelper. auto.
}
destruct (is_longconst a) as [p|] eqn:LC1;
destruct (is_longconst b) as [q|] eqn:LC2.
- exploit (is_longconst_sound le a); eauto. intros EQ; subst x.
exploit (is_longconst_sound le b); eauto. intros EQ; subst y.
econstructor; split. apply eval_longconst. simpl; auto.
- predSpec Int64.eq Int64.eq_spec p Int64.zero; auto.
replace (Val.subl x y) with (Val.negl y). eapply eval_negl; eauto.
subst p. exploit (is_longconst_sound le a); eauto. intros EQ; subst x.
destruct y; simpl; auto.
- predSpec Int64.eq Int64.eq_spec q Int64.zero; auto.
subst q. exploit (is_longconst_sound le b); eauto. intros EQ; subst y.
exists x; split; auto. destruct x; simpl; auto. rewrite Int64.sub_zero_l; auto.
- auto.
Qed.
Lemma eval_mull_base: binary_constructor_sound (mull_base hf) Val.mull.
Proof.
unfold mull_base; red; intros. apply eval_splitlong2; auto.
- intros.
set (p := Val.mull' x2 y2). set (le1 := p :: le0).
assert (E1: eval_expr ge sp e m le1 (Eop Olowlong (Eletvar O ::: Enil)) (Val.loword p)) by EvalOp.
assert (E2: eval_expr ge sp e m le1 (Eop Ohighlong (Eletvar O ::: Enil)) (Val.hiword p)) by EvalOp.
exploit eval_mul. apply eval_lift. eexact H2. apply eval_lift. eexact H3.
instantiate (1 := p). fold le1. intros [v3 [E3 L3]].
exploit eval_mul. apply eval_lift. eexact H1. apply eval_lift. eexact H4.
instantiate (1 := p). fold le1. intros [v4 [E4 L4]].
exploit eval_add. eexact E2. eexact E3. intros [v5 [E5 L5]].
exploit eval_add. eexact E5. eexact E4. intros [v6 [E6 L6]].
exists (Val.longofwords v6 (Val.loword p)); split.
EvalOp. eapply eval_builtin_2; eauto. UseHelper.
intros. unfold le1, p in *; subst; simpl in *.
inv L3. inv L4. inv L5. simpl in L6. inv L6.
simpl. f_equal. symmetry. apply Int64.decompose_mul.
- destruct x; auto; destruct y; auto.
Qed.
Lemma eval_mullimm:
forall n, unary_constructor_sound (fun a => mullimm hf a n) (fun v => Val.mull v (Vlong n)).
Proof.
unfold mullimm; red; intros.
predSpec Int64.eq Int64.eq_spec n Int64.zero.
subst n. econstructor; split. apply eval_longconst.
destruct x; simpl; auto. rewrite Int64.mul_zero. auto.
predSpec Int64.eq Int64.eq_spec n Int64.one.
subst n. exists x; split; auto.
destruct x; simpl; auto. rewrite Int64.mul_one. auto.
destruct (Int64.is_power2 n) as [l|] eqn:P2.
exploit eval_shllimm. eauto. instantiate (1 := Int.repr (Int64.unsigned l)).
intros [v [A B]].
exists v; split; auto.
destruct x; simpl; auto.
erewrite Int64.mul_pow2 by eauto.
assert (EQ: Int.unsigned (Int.repr (Int64.unsigned l)) = Int64.unsigned l).
{ apply Int.unsigned_repr.
exploit Int64.is_power2_rng; eauto.
assert (Int64.zwordsize < Int.max_unsigned) by (compute; auto).
omega.
}
simpl in B.
replace (Int.ltu (Int.repr (Int64.unsigned l)) Int64.iwordsize')
with (Int64.ltu l Int64.iwordsize) in B.
erewrite Int64.is_power2_range in B by eauto.
unfold Int64.shl' in B. rewrite EQ in B. auto.
unfold Int64.ltu, Int.ltu. rewrite EQ. auto.
apply eval_mull_base; auto. apply eval_longconst.
Qed.
Theorem eval_mull: binary_constructor_sound (mull hf) Val.mull.
Proof.
unfold mull; red; intros.
destruct (is_longconst a) as [p|] eqn:LC1;
destruct (is_longconst b) as [q|] eqn:LC2.
- exploit (is_longconst_sound le a); eauto. intros EQ; subst x.
exploit (is_longconst_sound le b); eauto. intros EQ; subst y.
econstructor; split. apply eval_longconst. simpl; auto.
- exploit (is_longconst_sound le a); eauto. intros EQ; subst x.
replace (Val.mull (Vlong p) y) with (Val.mull y (Vlong p)) in *.
eapply eval_mullimm; eauto.
destruct y; simpl; auto. rewrite Int64.mul_commut; auto.
- exploit (is_longconst_sound le b); eauto. intros EQ; subst y.
eapply eval_mullimm; eauto.
- apply eval_mull_base; auto.
Qed.
Lemma eval_binop_long:
forall id sem le a b x y z,
(forall p q, x = Vlong p -> y = Vlong q -> z = Vlong (sem p q)) ->
helper_implements ge id sig_ll_l (x::y::nil) z ->
eval_expr ge sp e m le a x ->
eval_expr ge sp e m le b y ->
exists v, eval_expr ge sp e m le (binop_long id sem a b) v /\ Val.lessdef z v.
Proof.
intros. unfold binop_long.
destruct (is_longconst a) as [p|] eqn:LC1.
destruct (is_longconst b) as [q|] eqn:LC2.
exploit is_longconst_sound. eexact LC1. eauto. intros EQ; subst x.
exploit is_longconst_sound. eexact LC2. eauto. intros EQ; subst y.
econstructor; split. EvalOp. erewrite H by eauto. rewrite Int64.ofwords_recompose. auto.
econstructor; split. eapply eval_helper_2; eauto. auto.
econstructor; split. eapply eval_helper_2; eauto. auto.
Qed.
Theorem eval_divl:
forall le a b x y z,
eval_expr ge sp e m le a x ->
eval_expr ge sp e m le b y ->
Val.divls x y = Some z ->
exists v, eval_expr ge sp e m le (divl hf a b) v /\ Val.lessdef z v.
Proof.
intros. eapply eval_binop_long; eauto.
intros; subst; simpl in H1.
destruct (Int64.eq q Int64.zero
|| Int64.eq p (Int64.repr Int64.min_signed) && Int64.eq q Int64.mone); inv H1.
auto.
UseHelper.
Qed.
Theorem eval_modl:
forall le a b x y z,
eval_expr ge sp e m le a x ->
eval_expr ge sp e m le b y ->
Val.modls x y = Some z ->
exists v, eval_expr ge sp e m le (modl hf a b) v /\ Val.lessdef z v.
Proof.
intros. eapply eval_binop_long; eauto.
intros; subst; simpl in H1.
destruct (Int64.eq q Int64.zero
|| Int64.eq p (Int64.repr Int64.min_signed) && Int64.eq q Int64.mone); inv H1.
auto.
UseHelper.
Qed.
Theorem eval_divlu:
forall le a b x y z,
eval_expr ge sp e m le a x ->
eval_expr ge sp e m le b y ->
Val.divlu x y = Some z ->
exists v, eval_expr ge sp e m le (divlu hf a b) v /\ Val.lessdef z v.
Proof.
intros. unfold divlu.
set (default := Eexternal (i64_udiv hf) sig_ll_l (a ::: b ::: Enil)).
assert (DEFAULT:
exists v, eval_expr ge sp e m le default v /\ Val.lessdef z v).
{
econstructor; split. eapply eval_helper_2; eauto. UseHelper. auto.
}
destruct (is_longconst a) as [p|] eqn:LC1;
destruct (is_longconst b) as [q|] eqn:LC2.
- exploit (is_longconst_sound le a); eauto. intros EQ; subst x.
exploit (is_longconst_sound le b); eauto. intros EQ; subst y.
econstructor; split. apply eval_longconst.
simpl in H1. destruct (Int64.eq q Int64.zero); inv H1. auto.
- auto.
- destruct (Int64.is_power2 q) as [l|] eqn:P2; auto.
exploit (is_longconst_sound le b); eauto. intros EQ; subst y.
replace z with (Val.shrlu x (Vint (Int.repr (Int64.unsigned l)))).
apply eval_shrluimm. auto.
destruct x; simpl in H1; try discriminate.
destruct (Int64.eq q Int64.zero); inv H1.
simpl.
assert (EQ: Int.unsigned (Int.repr (Int64.unsigned l)) = Int64.unsigned l).
{ apply Int.unsigned_repr.
exploit Int64.is_power2_rng; eauto.
assert (Int64.zwordsize < Int.max_unsigned) by (compute; auto).
omega.
}
replace (Int.ltu (Int.repr (Int64.unsigned l)) Int64.iwordsize')
with (Int64.ltu l Int64.iwordsize).
erewrite Int64.is_power2_range by eauto.
erewrite Int64.divu_pow2 by eauto.
unfold Int64.shru', Int64.shru. rewrite EQ. auto.
unfold Int64.ltu, Int.ltu. rewrite EQ. auto.
- auto.
Qed.
Theorem eval_modlu:
forall le a b x y z,
eval_expr ge sp e m le a x ->
eval_expr ge sp e m le b y ->
Val.modlu x y = Some z ->
exists v, eval_expr ge sp e m le (modlu hf a b) v /\ Val.lessdef z v.
Proof.
intros. unfold modlu.
set (default := Eexternal (i64_umod hf) sig_ll_l (a ::: b ::: Enil)).
assert (DEFAULT:
exists v, eval_expr ge sp e m le default v /\ Val.lessdef z v).
{
econstructor; split. eapply eval_helper_2; eauto. UseHelper. auto.
}
destruct (is_longconst a) as [p|] eqn:LC1;
destruct (is_longconst b) as [q|] eqn:LC2.
- exploit (is_longconst_sound le a); eauto. intros EQ; subst x.
exploit (is_longconst_sound le b); eauto. intros EQ; subst y.
econstructor; split. apply eval_longconst.
simpl in H1. destruct (Int64.eq q Int64.zero); inv H1. auto.
- auto.
- destruct (Int64.is_power2 q) as [l|] eqn:P2; auto.
exploit (is_longconst_sound le b); eauto. intros EQ; subst y.
replace z with (Val.andl x (Vlong (Int64.sub q Int64.one))).
apply eval_andl. auto. apply eval_longconst.
destruct x; simpl in H1; try discriminate.
destruct (Int64.eq q Int64.zero); inv H1.
simpl.
erewrite Int64.modu_and by eauto. auto.
- auto.
Qed.
Remark decompose_cmpl_eq_zero:
forall h l,
Int64.eq (Int64.ofwords h l) Int64.zero = Int.eq (Int.or h l) Int.zero.
Proof.
intros.
assert (Int64.zwordsize = Int.zwordsize * 2) by reflexivity.
predSpec Int64.eq Int64.eq_spec (Int64.ofwords h l) Int64.zero.
replace (Int.or h l) with Int.zero. rewrite Int.eq_true. auto.
apply Int.same_bits_eq; intros.
rewrite Int.bits_zero. rewrite Int.bits_or by auto.
symmetry. apply orb_false_intro.
transitivity (Int64.testbit (Int64.ofwords h l) (i + Int.zwordsize)).
rewrite Int64.bits_ofwords by omega. rewrite zlt_false by omega. f_equal; omega.
rewrite H0. apply Int64.bits_zero.
transitivity (Int64.testbit (Int64.ofwords h l) i).
rewrite Int64.bits_ofwords by omega. rewrite zlt_true by omega. auto.
rewrite H0. apply Int64.bits_zero.
symmetry. apply Int.eq_false. red; intros; elim H0.
apply Int64.same_bits_eq; intros.
rewrite Int64.bits_zero. rewrite Int64.bits_ofwords by auto.
destruct (zlt i Int.zwordsize).
assert (Int.testbit (Int.or h l) i = false) by (rewrite H1; apply Int.bits_zero).
rewrite Int.bits_or in H3 by omega. exploit orb_false_elim; eauto. tauto.
assert (Int.testbit (Int.or h l) (i - Int.zwordsize) = false) by (rewrite H1; apply Int.bits_zero).
rewrite Int.bits_or in H3 by omega. exploit orb_false_elim; eauto. tauto.
Qed.
Lemma eval_cmpl_eq_zero:
forall le a x,
eval_expr ge sp e m le a (Vlong x) ->
eval_expr ge sp e m le (cmpl_eq_zero a) (Val.of_bool (Int64.eq x Int64.zero)).
Proof.
intros. unfold cmpl_eq_zero.
eapply eval_splitlong_strict; eauto. intros.
exploit eval_or. eexact H0. eexact H1. intros [v1 [A1 B1]]. simpl in B1; inv B1.
exploit eval_comp. eexact A1. instantiate (2 := Eop (Ointconst Int.zero) Enil). EvalOp.
instantiate (1 := Ceq). intros [v2 [A2 B2]].
unfold Val.cmp in B2; simpl in B2.
rewrite <- decompose_cmpl_eq_zero in B2.
rewrite Int64.ofwords_recompose in B2.
destruct (Int64.eq x Int64.zero); inv B2; auto.
Qed.
Lemma eval_cmpl_ne_zero:
forall le a x,
eval_expr ge sp e m le a (Vlong x) ->
eval_expr ge sp e m le (cmpl_ne_zero a) (Val.of_bool (negb (Int64.eq x Int64.zero))).
Proof.
intros. unfold cmpl_ne_zero.
eapply eval_splitlong_strict; eauto. intros.
exploit eval_or. eexact H0. eexact H1. intros [v1 [A1 B1]]. simpl in B1; inv B1.
exploit eval_comp. eexact A1. instantiate (2 := Eop (Ointconst Int.zero) Enil). EvalOp.
instantiate (1 := Cne). intros [v2 [A2 B2]].
unfold Val.cmp in B2; simpl in B2.
rewrite <- decompose_cmpl_eq_zero in B2.
rewrite Int64.ofwords_recompose in B2.
destruct (negb (Int64.eq x Int64.zero)); inv B2; auto.
Qed.
Lemma eval_cmplu_gen:
forall ch cl a b le x y,
eval_expr ge sp e m le a (Vlong x) ->
eval_expr ge sp e m le b (Vlong y) ->
eval_expr ge sp e m le (cmplu_gen ch cl a b)
(Val.of_bool (if Int.eq (Int64.hiword x) (Int64.hiword y)
then Int.cmpu cl (Int64.loword x) (Int64.loword y)
else Int.cmpu ch (Int64.hiword x) (Int64.hiword y))).
Proof.
intros. unfold cmplu_gen. eapply eval_splitlong2_strict; eauto. intros.
econstructor. econstructor. EvalOp. simpl. eauto.
destruct (Int.eq (Int64.hiword x) (Int64.hiword y)); EvalOp.
Qed.
Remark int64_eq_xor:
forall p q, Int64.eq p q = Int64.eq (Int64.xor p q) Int64.zero.
Proof.
intros.
predSpec Int64.eq Int64.eq_spec p q.
subst q. rewrite Int64.xor_idem. rewrite Int64.eq_true. auto.
predSpec Int64.eq Int64.eq_spec (Int64.xor p q) Int64.zero.
elim H. apply Int64.xor_zero_equal; auto.
auto.
Qed.
Theorem eval_cmplu:
forall c le a x b y v,
eval_expr ge sp e m le a x ->
eval_expr ge sp e m le b y ->
Val.cmplu c x y = Some v ->
eval_expr ge sp e m le (cmplu c a b) v.
Proof.
intros. unfold Val.cmplu in H1.
destruct x; simpl in H1; try discriminate. destruct y; inv H1.
rename i into x. rename i0 into y.
destruct c; simpl.
- (* Ceq *)
exploit eval_xorl. eexact H. eexact H0. intros [v1 [A B]]. simpl in B. inv B.
rewrite int64_eq_xor. apply eval_cmpl_eq_zero; auto.
- (* Cne *)
exploit eval_xorl. eexact H. eexact H0. intros [v1 [A B]]. simpl in B. inv B.
rewrite int64_eq_xor. apply eval_cmpl_ne_zero; auto.
- (* Clt *)
exploit (eval_cmplu_gen Clt Clt). eexact H. eexact H0. simpl.
rewrite <- Int64.decompose_ltu. rewrite ! Int64.ofwords_recompose. auto.
- (* Cle *)
exploit (eval_cmplu_gen Clt Cle). eexact H. eexact H0. intros.
rewrite <- (Int64.ofwords_recompose x). rewrite <- (Int64.ofwords_recompose y).
rewrite Int64.decompose_leu. auto.
- (* Cgt *)
exploit (eval_cmplu_gen Cgt Cgt). eexact H. eexact H0. simpl.
rewrite Int.eq_sym. rewrite <- Int64.decompose_ltu. rewrite ! Int64.ofwords_recompose. auto.
- (* Cge *)
exploit (eval_cmplu_gen Cgt Cge). eexact H. eexact H0. intros.
rewrite <- (Int64.ofwords_recompose x). rewrite <- (Int64.ofwords_recompose y).
rewrite Int64.decompose_leu. rewrite Int.eq_sym. auto.
Qed.
Lemma eval_cmpl_gen:
forall ch cl a b le x y,
eval_expr ge sp e m le a (Vlong x) ->
eval_expr ge sp e m le b (Vlong y) ->
eval_expr ge sp e m le (cmpl_gen ch cl a b)
(Val.of_bool (if Int.eq (Int64.hiword x) (Int64.hiword y)
then Int.cmpu cl (Int64.loword x) (Int64.loword y)
else Int.cmp ch (Int64.hiword x) (Int64.hiword y))).
Proof.
intros. unfold cmpl_gen. eapply eval_splitlong2_strict; eauto. intros.
econstructor. econstructor. EvalOp. simpl. eauto.
destruct (Int.eq (Int64.hiword x) (Int64.hiword y)); EvalOp.
Qed.
Remark decompose_cmpl_lt_zero:
forall h l,
Int64.lt (Int64.ofwords h l) Int64.zero = Int.lt h Int.zero.
Proof.
intros.
generalize (Int64.shru_lt_zero (Int64.ofwords h l)).
change (Int64.shru (Int64.ofwords h l) (Int64.repr (Int64.zwordsize - 1)))
with (Int64.shru' (Int64.ofwords h l) (Int.repr 63)).
rewrite Int64.decompose_shru_2.
change (Int.sub (Int.repr 63) Int.iwordsize)
with (Int.repr (Int.zwordsize - 1)).
rewrite Int.shru_lt_zero.
destruct (Int64.lt (Int64.ofwords h l) Int64.zero); destruct (Int.lt h Int.zero); auto; intros.
elim Int64.one_not_zero. auto.
elim Int64.one_not_zero. auto.
vm_compute. intuition congruence.
Qed.
Theorem eval_cmpl:
forall c le a x b y v,
eval_expr ge sp e m le a x ->
eval_expr ge sp e m le b y ->
Val.cmpl c x y = Some v ->
eval_expr ge sp e m le (cmpl c a b) v.
Proof.
intros. unfold Val.cmpl in H1.
destruct x; simpl in H1; try discriminate. destruct y; inv H1.
rename i into x. rename i0 into y.
destruct c; simpl.
- (* Ceq *)
exploit eval_xorl. eexact H. eexact H0. intros [v1 [A B]]. simpl in B; inv B.
rewrite int64_eq_xor. apply eval_cmpl_eq_zero; auto.
- (* Cne *)
exploit eval_xorl. eexact H. eexact H0. intros [v1 [A B]]. simpl in B; inv B.
rewrite int64_eq_xor. apply eval_cmpl_ne_zero; auto.
- (* Clt *)
destruct (is_longconst_zero b) eqn:LC.
+ exploit is_longconst_zero_sound; eauto. intros EQ; inv EQ; clear H0.
exploit eval_highlong. eexact H. intros [v1 [A1 B1]]. simpl in B1. inv B1.
exploit eval_comp. eexact A1.
instantiate (2 := Eop (Ointconst Int.zero) Enil). EvalOp.
instantiate (1 := Clt). intros [v2 [A2 B2]].
unfold Val.cmp in B2. simpl in B2.
rewrite <- (Int64.ofwords_recompose x). rewrite decompose_cmpl_lt_zero.
destruct (Int.lt (Int64.hiword x) Int.zero); inv B2; auto.
+ exploit (eval_cmpl_gen Clt Clt). eexact H. eexact H0. simpl.
rewrite <- Int64.decompose_lt. rewrite ! Int64.ofwords_recompose. auto.
- (* Cle *)
exploit (eval_cmpl_gen Clt Cle). eexact H. eexact H0. intros.
rewrite <- (Int64.ofwords_recompose x). rewrite <- (Int64.ofwords_recompose y).
rewrite Int64.decompose_le. auto.
- (* Cgt *)
exploit (eval_cmpl_gen Cgt Cgt). eexact H. eexact H0. simpl.
rewrite Int.eq_sym. rewrite <- Int64.decompose_lt. rewrite ! Int64.ofwords_recompose. auto.
- (* Cge *)
destruct (is_longconst_zero b) eqn:LC.
+ exploit is_longconst_zero_sound; eauto. intros EQ; inv EQ; clear H0.
exploit eval_highlong. eexact H. intros [v1 [A1 B1]]. simpl in B1; inv B1.
exploit eval_comp. eexact A1.
instantiate (2 := Eop (Ointconst Int.zero) Enil). EvalOp.
instantiate (1 := Cge). intros [v2 [A2 B2]].
unfold Val.cmp in B2; simpl in B2.
rewrite <- (Int64.ofwords_recompose x). rewrite decompose_cmpl_lt_zero.
destruct (negb (Int.lt (Int64.hiword x) Int.zero)); inv B2; auto.
+ exploit (eval_cmpl_gen Cgt Cge). eexact H. eexact H0. intros.
rewrite <- (Int64.ofwords_recompose x). rewrite <- (Int64.ofwords_recompose y).
rewrite Int64.decompose_le. rewrite Int.eq_sym. auto.
Qed.
End CMCONSTR.
End WITHCONFIG.
|
module Datetime
export Calendar, ISOCalendar, Offsets, TimeZone, Offset, CALENDAR, OFFSET, Period,
Date, DateTime, DateRange, DateRange1, DateTimeRange, DateTimeRange1,
Year, Month, Week, Day, Hour, Minute, Second,
year, month, week, day, hour, minute, second, millisecond,
years,months,weeks,days,hours,minutes,seconds, milliseconds,
addwrap, subwrap, date, datetime, unix2datetime, totaldays,
isleap, lastdayofmonth, dayofweek, dayofyear, isdate, isdatetime,
dayofweekinmonth, daysofweekinmonth, firstdayofweek, lastdayofweek,
recur, now, today, calendar, timezone, offset, setcalendar, settimezone,
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday,
Mon,Tue,Wed,Thu,Fri,Sat,Sun,
January, February, March, April, May, June, July,
August, September, October, November, December,
Jan,Feb,Mar,Apr,Jun,Jul,Aug,Sep,Oct,Nov,Dec
abstract AbstractTime
abstract Calendar <: AbstractTime
abstract ISOCalendar <: Calendar
#Set the default calendar to use; overriding this will affect module-wide defaults
CALENDAR = ISOCalendar
setcalendar{C<:Calendar}(cal::Type{C}) = (global CALENDAR = cal)
abstract Offsets <: AbstractTime
abstract Offset{n} <: Offsets
abstract TimeZone <: Offsets
include("Timezone.jl")
#Set the default timezone to use; overriding this will affect module-wide defaults
OFFSET = UTC
settimezone{T<:Offsets}(tz::Type{T}) = (global OFFSET = tz)
abstract TimeType <: AbstractTime
bitstype 64 Date{C <: Calendar} <: TimeType
bitstype 64 DateTime{C <: Calendar, T <: Offsets} <: TimeType
abstract Period <: AbstractTime
abstract DatePeriod <: Period
abstract TimePeriod <: Period
typealias PeriodMath Union(Real,Period)
bitstype 32 Year{C<:Calendar} <: DatePeriod
bitstype 32 Month{C<:Calendar} <: DatePeriod
bitstype 32 Week{C<:Calendar} <: DatePeriod
bitstype 32 Day{C<:Calendar} <: DatePeriod
bitstype 32 Hour{C<:Calendar} <: TimePeriod
bitstype 32 Minute{C<:Calendar} <: TimePeriod
bitstype 32 Second{C<:Calendar} <: TimePeriod
#Conversion/Promotion
Base.convert{T<:TimeType}(::Type{T},x::Int64) = reinterpret(T,x)
Base.convert{T<:TimeType}(::Type{Int64},x::T) = reinterpret(Int64,x)
Base.promote_rule{T<:TimeType,R<:Real}(::Type{T},::Type{R}) = R
Base.convert{T<:TimeType}(::Type{T},x::Real) = convert(T,int64(x))
Base.convert{R<:Real}(::Type{R}, x::TimeType) = convert(R,int64(x))
Base.promote_rule{C<:Calendar,T<:Offsets}(::Type{Date{C}},::Type{DateTime{C,T}}) = DateTime{C,T}
Base.convert{T<:Offsets}(::Type{DateTime{ISOCalendar,T}},x::Date) = convert(DateTime{ISOCalendar,T}, (secs = 86400000*int64(x); secs - setoffset(T,secs,year(x),0)))
Base.convert(::Type{Date{ISOCalendar}},x::DateTime) = convert(Date{ISOCalendar},_days(x))
date(x::DateTime) = convert(Date{CALENDAR},x)
datetime{T<:Offsets}(x::Date, tz::Type{T}=OFFSET) = convert(DateTime{CALENDAR,tz},x)
datetime(x::Date, tz::String) = datetime(x, timezone(tz))
#Date type safety
Base.promote_rule{C<:Calendar,CC<:Calendar}(::Type{Date{C}},::Type{Date{CC}}) = Date{ISOCalendar}
Base.convert(::Type{Date{ISOCalendar}},x::Date) = convert(Date{ISOCalendar},int64(x))
Base.convert(::Type{Date},x::Int64) = convert(Date{ISOCalendar},x)
#DateTime type safety
Base.promote_rule{C<:Calendar,CC<:Calendar,T<:Offsets,TT<:Offsets}(::Type{DateTime{C,T}},::Type{DateTime{CC,TT}}) = DateTime{ISOCalendar,UTC}
Base.convert(::Type{DateTime{ISOCalendar,UTC}},x::DateTime) = convert(DateTime{ISOCalendar,UTC},int64(x))
Base.convert(::Type{DateTime},x::Int64) = convert(DateTime{ISOCalendar,UTC},x)
Base.hash(x::TimeType, h::Uint) = hash(int64(x), h)
Base.length(::TimeType) = 1
Base.isless{T<:TimeType}(x::T,y::T) = isless(int64(x),int64(y))
Base.isless(x::TimeType,y::Real) = isless(int64(x),int64(y))
Base.isless(x::Real,y::TimeType) = isless(int64(x),int64(y))
Base.isless(x::TimeType,y::TimeType) = isless(promote(x,y)...)
=={T<:TimeType}(x::T,y::T) = ==(int64(x),int64(y))
==(x::TimeType,y::Real) = ==(int64(x),int64(y))
==(x::Real,y::TimeType) = ==(int64(x),int64(y))
==(x::TimeType,y::TimeType) = ==(promote(x,y)...)
Base.isequal{T<:TimeType}(x::T,y::T) = isequal(int64(x),int64(y))
Base.isequal(x::TimeType,y::Real) = isequal(int64(x),int64(y))
Base.isequal(x::Real,y::TimeType) = isequal(int64(x),int64(y))
Base.isequal(x::TimeType,y::TimeType) = isequal(promote(x,y)...)
Base.isfinite(x::TimeType) = true
#Serialization/Deserialization
Base.write(io::IO, x::TimeType) = write(io, reinterpret(Uint64, x))
Base.write(io::IO, x::Period ) = write(io, reinterpret(Uint32, x))
Base.read{T<:TimeType}(io::IO, ::Type{T}) = reinterpret(T, read(io, Uint64))
Base.read{T<:Period }(io::IO, ::Type{T}) = reinterpret(T, read(io, Uint32))
#Date algorithm implementations
#Source: Peter Baum - http://mysite.verizon.net/aesir_research/date/date0.htm
#Convert y,m,d to # of Rata Die days
yeardays(y) = 365y + fld(y,4) - fld(y,100) + fld(y,400)
const monthdays = [306, 337, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275]
totaldays(y,m,d) = d + monthdays[m] + yeardays(m<3 ? y-1 : y) - 306
#Convert # of Rata Die days to proleptic Gregorian calendar y,m,d,w
function _year(dt)
z = dt + 306; h = 100z - 25; a = fld(h,3652425)
b = a - fld(a,4); y = fld(100b+h,36525); c = b + z - 365y - fld(y,4)
m = div(5c+456,153); return m > 12 ? y+1 : y
end
function _month(dt)
z = dt + 306; h = 100z - 25; a = fld(h,3652425)
b = a - fld(a,4); y = fld(100b+h,36525); c = b + z - 365y - fld(y,4)
m = div(5c+456,153); return m > 12 ? m-12 : m
end
function _day(dt)
z = dt + 306; h = 100z - 25; a = fld(h,3652425)
b = a - fld(a,4); y = fld(100b+h,36525); c = b + z - 365y - fld(y,4)
m = div(5c+456,153); d = c - div(153m-457,5); return d
end
function _day2date(dt)
z = dt + 306; h = 100z - 25; a = fld(h,3652425)
b = a - fld(a,4); y = fld(100b+h,36525); c = b + z - 365y - fld(y,4)
m = div(5c+456,153); d = c - div(153m-457,5); return m > 12 ? (y+1,m-12,d) : (y,m,d)
end
#https://en.wikipedia.org/wiki/Talk:ISO_week_date#Algorithms
function _week(dt)
w = fld(abs(dt-1),7) % 20871
c = fld((w + (w >= 10435)),5218)
w = (w + (w >= 10435)) % 5218
w = (w*28+(15,23,3,11)[c+1]) % 1461
return fld(w,28) + 1
end
const DAYSINMONTH = [31,28,31,30,31,30,31,31,30,31,30,31]
isleap(y) = ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)
lastdayofmonth(y,m) = DAYSINMONTH[m] + (m == 2 && isleap(y))
#TimeType constructors
setoffset(tz::Type{UTC},secs,y,s) = 0 - (y < 1972 ? 0 : s == 60 ? leaps1(secs) : leaps(secs))
getoffset(tz::Type{UTC},secs) = 0 - leaps(secs)
getoffset_secs(tz::Type{UTC},secs) = 0 - leaps1(secs)
getabr(tz::Type{UTC},secs,y) = "UTC"
#DateTime constructor with timezone and/or leap seconds
ff = open(joinpath(FILEPATH,"../deps/tzdata/_leaps"))
const _leaps = deserialize(ff)
close(ff)
ff = open(joinpath(FILEPATH,"../deps/tzdata/_leaps1"))
const _leaps1 = deserialize(ff)
close(ff)
# const _leaps = [62214479999000,62230377599000,62261913599000,62293449599000,62324985599000,62356607999000,62388143999000,62419679999000,62451215999000,62498476799000,62530012799000,62561548799000,62624707199000,62703676799000,62766835199000,62798371199000,62845631999000,62877167999000,62908703999000,62956137599000,63003398399000,63050831999000,63271756799000,63366451199000,63476783999000,9223372036854775807]
# const _leaps1 = [62214480000000,62230377601000,62261913602000,62293449603000,62324985604000,62356608005000,62388144006000,62419680007000,62451216008000,62498476809000,62530012810000,62561548811000,62624707212000,62703676813000,62766835214000,62798371215000,62845632016000,62877168017000,62908704018000,62956137619000,63003398420000,63050832021000,63271756822000,63366451223000,63476784024000,9223372036854775807]
leaps(secs::Union(DateTime,Int64)) = (i = 1; while true; @inbounds (_leaps[i] >= secs && break); i+=1 end; return 1000*(i-1))
leaps1(secs::Union(DateTime,Int64)) = (i = 1; while true; @inbounds (_leaps1[i] >= secs && break); i+=1 end; return 1000*(i-1))
date{C<:Calendar}(y::Int64,m::Int64=1,d::Int64=1,cal::Type{C}=CALENDAR) = convert(Date{cal},totaldays(y,m,d))
date{C<:Calendar}(y::PeriodMath,m::PeriodMath=1,d::PeriodMath=1,cal::Type{C}=CALENDAR) = date(int64(y),int64(m),int64(d),cal)
datetime{C<:Calendar,T<:Offsets}(y::Int64,m::Int64=1,d::Int64=1,h::Int64=0,mi::Int64=0,s::Int64=0,milli::Int64=0,tz::Type{T}=OFFSET,cal::Type{C}=CALENDAR) =
(secs = milli + 1000*(s + 60mi + 3600h + 86400*totaldays(y,m,d)); return convert(DateTime{cal,tz}, secs - setoffset(tz,secs,y,s)))
datetime{C<:Calendar,T<:Offsets}(y::Real,m::Real=1,d::Real=1,h::Real=0,mi::Real=0,s::Real=0,millis::Real=0,tz::Type{T}=OFFSET,cal::Type{C}=CALENDAR) =
datetime(int64(y),int64(m),int64(d),int64(h),int64(mi),int64(s),int64(millis),tz,cal)
datetime(y,m,d,h,mi,s,milli,tz::String) = datetime(y,m,d,h,mi,s,milli,timezone(tz),CALENDAR)
function date(s::String)
if ismatch(r"[\/|\-|\.|,|\s]",s)
m = match(r"[\/|\-|\.|,|\s]",s)
a,b,c = split(s,m.match)
y = length(a) == 4 ? int64(a) : length(c) == 4 ? int64(c) : 0
a,b,c = int64(a),int64(b),int64(c)
y == 0 && (y = c > 49 ? c + 1900 : c + 2000)
m,d = y == a ? (b,c) : (a,b)
return m > 12 ? date(y,d,m) : date(y,m,d)
else
error("Can't parse Date, please use date(format,datestring)")
end
end
type DateTimeFormat
year::Range1
month::Range1
day::Range1
hour::Range1
minute::Range1
second::Range1
fraction::Range1
tz::Range1
sep::String
#ampm::Bool
end
function DateTimeFormat(f::String)
y = first(search(f,"y")):last(rsearch(f,"y"))
mon = first(search(f,"M")):last(rsearch(f,"M"))
d = first(search(f,"d")):last(rsearch(f,"d"))
h = first(search(f,"H")):last(rsearch(f,"H"))
min = first(search(f,"m")):last(rsearch(f,"m"))
s = first(search(f,"s")):last(rsearch(f,"s"))
frac = first(search(f,"S")):last(rsearch(f,"S"))
sep = ismatch(r"[\/|\-|\.|,|\s]",f) ? match(r"[\/|\-|\.|,|\s]",f).match : ""
tz = first(search(f,"z")):last(rsearch(f,"z"))
return DateTimeFormat(y,mon,d,h,min,s,frac,tz,sep) #,ampm)
end
function dt2string(format::DateTimeFormat,dt::String)
y = format.year == 0:-1 ? 1 : int(dt[format.year])
mon = format.month == 0:-1 ? 1 : int(dt[format.month])
d = format.day == 0:-1 ? 1 : int(dt[format.day])
h = format.hour == 0:-1 ? 0 : int(dt[format.hour])
min = format.minute == 0:-1 ? 0 : int(dt[format.minute])
s = format.second == 0:-1 ? 0 : int(dt[format.second])
frac = format.fraction == 0:-1 ? 0 : int(dt[format.fraction])*100
tz = format.tz == 0:-1 ? UTC : dt[format.tz]
return datetime(y,mon,d,h,min,s,frac,tz)
end
datetime(f::String,dt::String) = dt2string(DateTimeFormat(f),dt)
function datetime{T<:String}(f::T,t::Array{T})
ff = DateTimeFormat(f)
ret = DateTime{CALENDAR,OFFSET}[]
for i in t
push!(ret,dt2string(ff,i))
end
return ret
end
#Accessor/trait functions
typealias DateTimeDate Union(DateTime,Date)
_days(dt::Date) = int64(dt)
_days{C<:Calendar,T<:Offsets}(dt::DateTime{C,T}) = fld(int64(dt)+getoffset(T,dt),86400000)
year(dt::DateTimeDate) = _year(_days(dt))
month(dt::DateTimeDate) = _month(_days(dt))
week(dt::DateTimeDate) = _week(_days(dt))
day(dt::DateTimeDate) = _day(_days(dt))
hour{C<:Calendar,T<:Offsets}(dt::DateTime{C,T}) = fld(int64(dt)+getoffset(T,dt),3600000) % 24
minute{C<:Calendar,T<:Offsets}(dt::DateTime{C,T}) = fld(int64(dt)+getoffset(T,dt),60000) % 60
second{C<:Calendar,T<:Offsets}(dt::DateTime{C,T}) = (s = fld(int64(dt)+getoffset_secs(T,dt),1000) % 60; return s != 0 ? s : dt in _leaps1 ? int64(60) : int64(0))
milliseconds = (millisecond(dt::DateTime) = int64(dt) % 1000)
calendar{C<:Calendar}(dt::Date{C}) = C
Base.typemax{D<:Date}(::Type{D}) = date(252522163911149,12,31)
Base.typemin{D<:Date}(::Type{D}) = date(-252522163911150,1,1)
isdate(n) = typeof(n) <: Date
calendar{C<:Calendar,T<:Offsets}(dt::DateTime{C,T}) = C
timezone{C<:Calendar,T<:Offsets}(dt::DateTime{C,T}) = T
Base.typemax{D<:DateTime}(::Type{D}) = datetime(292277024,12,31,23,59,59)
Base.typemin{D<:DateTime}(::Type{D}) = datetime(-292277023,1,1,0,0,0)
isdatetime(x) = typeof(x) <: DateTime
#Functions to work with timezones
Base.convert{C<:Calendar,T<:Offsets,TT<:Offsets}(::Type{DateTime{C,T}},x::DateTime{C,TT}) = convert(DateTime{C,TT},int64(x))
timezone{C<:Calendar,T<:Offsets,TT<:Offsets}(dt::DateTime{C,T},tz::Type{TT}) = convert(DateTime{C,TT},int64(dt))
offset{C<:Calendar,T<:Offsets,TT<:Offsets}(dt::DateTime{C,T},tz::Type{TT}) = convert(DateTime{C,TT},int64(dt))
timezone(x::String) = get(TIMEZONES,x,Zone0)
timezone(dt::DateTime,tz::String) = timezone(dt,timezone(tz))
#String/print/show
_s(x) = @sprintf("%02d",x)
function Base.string(dt::Date)
y,m,d = _day2date(_days(dt))
y = y < 0 ? @sprintf("%05d",y) : @sprintf("%04d",y)
return string(y,"-",_s(m),"-",_s(d))
end
function Base.string{C<:Calendar,T<:Offsets}(dt::DateTime{C,T})
y,m,d = _day2date(_days(dt))
h,mi,s = hour(dt),minute(dt),second(dt)
return string(y < 0 ? @sprintf("%05d",y) : @sprintf("%04d",y),"-",
_s(m),"-",_s(d),"T",_s(h),":",_s(mi),":",_s(s)," ",getabr(T,dt,y))
end
Base.print(io::IO,x::TimeType) = print(io,string(x))
Base.show(io::IO,x::TimeType) = print(io,string(x))
#Generic date functions
isleap(dt::DateTimeDate) = isleap(year(dt))
lastdayofmonth(dt::DateTimeDate) = lastdayofmonth(year(dt),month(dt))
dayofweek(dt::DateTimeDate) = mod1(_days(dt),7)
dayofweekinmonth(dt::DateTimeDate) = (d = day(dt); return d < 8 ? 1 : d < 15 ? 2 : d < 22 ? 3 : d < 29 ? 4 : 5)
function daysofweekinmonth(dt::DateTimeDate)
d,ld = day(dt),lastdayofmonth(dt)
return ld == 28 ? 4 : ld == 29 ? ((d in (1,8,15,22,29)) ? 5 : 4) :
ld == 30 ? ((d in (1,2,8,9,15,16,22,23,29,30)) ? 5 : 4) :
(d in (1,2,3,8,9,10,15,16,17,22,23,24,29,30,31)) ? 5 : 4
end
firstdayofweek{C<:Calendar}(dt::Date{C}) = (d = dayofweek(dt); return convert(Date{C},int64(dt) - d + 1))
firstdayofweek{C<:Calendar,T<:Offsets}(dt::DateTime{C,T}) = (d = dayofweek(dt); return convert(DateTime{C,T},int64(dt) - 86400000*(d - 1)))
lastdayofweek{C<:Calendar}(dt::Date{C}) = (d = dayofweek(dt); return convert(Date{C},int64(dt) + (7-d)))
lastdayofweek{C<:Calendar,T<:Offsets}(dt::DateTime{C,T}) = (d = dayofweek(dt); return convert(DateTime{C,T},int64(dt) + 86400000*(7-d)))
dayofyear(dt::DateTimeDate) = _days(dt) - totaldays(year(dt),1,1) + 1
@vectorize_1arg DateTimeDate isleap
@vectorize_1arg DateTimeDate lastdayofmonth
@vectorize_1arg DateTimeDate dayofweek
@vectorize_1arg DateTimeDate dayofweekinmonth
@vectorize_1arg DateTimeDate daysofweekinmonth
@vectorize_1arg DateTimeDate firstdayofweek
@vectorize_1arg DateTimeDate lastdayofweek
@vectorize_1arg DateTimeDate dayofyear
#TimeType-specific functions (now, unix2datetime, today)
const UNIXEPOCH = 62135683200000 #Rata Die milliseconds for 1970-01-01T00:00:00 UTC
unix2datetime{T<:Offsets}(x::Int64,tz::Type{T}) = convert(DateTime{CALENDAR,tz},UNIXEPOCH + x + leaps(UNIXEPOCH + x))
now() = unix2datetime(int64(1000*time()),OFFSET)
now{T<:Offsets}(tz::Type{T}) = unix2datetime(int64(1000*time()),tz)
today() = date(now())
#TimeType arithmetic
(+)(x::TimeType) = x
(-)(x::Date) = date(-int64(year(x)),month(x),day(x))
(-){C<:Calendar,T<:Offsets}(x::DateTime{C,T}) = datetime(-year(x),month(x),day(x),hour(x),minute(x),second(x))
for op in (:+,:*,:/)
@eval ($op)(x::DateTimeDate,y::DateTimeDate) = Base.no_op_err($op,"Date/DateTime")
end
(-){C<:Calendar}(x::Date{C},y::Date{C}) = days(-(int64(x),int64(y)))
(-){C<:Calendar,T<:Offsets}(x::DateTime{C,T},y::DateTime{C,T}) = int64(x)-int64(y)
(-)(x::DateTimeDate,y::DateTimeDate) = (-)(promote(x,y)...)
#years
function (+){C<:Calendar}(dt::Date{C},y::Year{C})
oy,m,d = _day2date(_days(dt)); ny = oy+int64(y); ld = lastdayofmonth(ny,m)
return date(ny,m,d <= ld ? d : ld,C)
end
function (-){C<:Calendar}(dt::Date{C},y::Year{C})
oy,m,d = _day2date(_days(dt)); ny = oy-int64(y); ld = lastdayofmonth(ny,m)
return date(ny,m,d <= ld ? d : ld,C)
end
function (+){C<:Calendar,T<:Offsets}(dt::DateTime{C,T},y::Year{C})
oy,m,d = _day2date(_days(dt)); ny = oy+int64(y); ld = lastdayofmonth(ny,m)
return datetime(ny,m,d <= ld ? d : ld,hour(dt),minute(dt),second(dt))
end
function (-){C<:Calendar,T<:Offsets}(dt::DateTime{C,T},y::Year{C})
oy,m,d = _day2date(_days(dt)); ny = oy-int64(y); ld = lastdayofmonth(ny,m)
return datetime(ny,m,d <= ld ? d : ld,hour(dt),minute(dt),second(dt))
end
#months
function (+){C<:Calendar}(dt::Date{C},z::Month{C})
y,m,d = _day2date(_days(dt))
ny = yearwrap(y,m,int64(z))
mm = monthwrap(m,int64(z)); ld = lastdayofmonth(ny,mm)
return date(ny,mm,d <= ld ? d : ld)
end
function (-){C<:Calendar}(dt::Date{C},z::Month{C})
y,m,d = _day2date(_days(dt))
ny = yearwrap(y,m,-int64(z))
mm = monthwrap(m,-int64(z)); ld = lastdayofmonth(ny,mm)
return date(ny,mm,d <= ld ? d : ld)
end
function (+){C<:Calendar,T<:Offsets}(dt::DateTime{C,T},z::Month{C})
y,m,d = _day2date(_days(dt))
ny = yearwrap(y,m,int64(z))
mm = monthwrap(m,int64(z)); ld = lastdayofmonth(ny,mm)
return datetime(ny,mm,d <= ld ? d : ld,hour(dt),minute(dt),second(dt))
end
function (-){C<:Calendar,T<:Offsets}(dt::DateTime{C,T},z::Month{C})
y,m,d = _day2date(_days(dt))
ny = yearwrap(y,m,-int64(z))
mm = monthwrap(m,-int64(z)); ld = lastdayofmonth(ny,mm)
return datetime(ny,mm,d <= ld ? d : ld,hour(dt),minute(dt),second(dt))
end
#weeks,days,hours,minutes,seconds
(+){C<:Calendar}(x::Date{C},y::Week{C}) = convert(Date{C},(int64(x) + 7*int64(y)))
(-){C<:Calendar}(x::Date{C},y::Week{C}) = convert(Date{C},(int64(x) - 7*int64(y)))
(+){C<:Calendar}(x::Date{C},y::Day{C}) = convert(Date{C},(int64(x) + int64(y)))
(-){C<:Calendar}(x::Date{C},y::Day{C}) = convert(Date{C},(int64(x) - int64(y)))
(+){C<:Calendar,T<:Offsets}(x::DateTime{C,T},y::Week{C}) = (x = int64(x)+604800000*int64(y) - leaps(int64(x)); convert(DateTime{C,T},x+leaps(x)))
(-){C<:Calendar,T<:Offsets}(x::DateTime{C,T},y::Week{C}) = (x = int64(x)-604800000*int64(y) - leaps(int64(x)); convert(DateTime{C,T},x+leaps(x)))
(+){C<:Calendar,T<:Offsets}(x::DateTime{C,T},y::Day{C}) = (x = int64(x)+86400000*int64(y) - leaps(int64(x)); convert(DateTime{C,T},x+leaps(x)))
(-){C<:Calendar,T<:Offsets}(x::DateTime{C,T},y::Day{C}) = (x = int64(x)-86400000*int64(y) - leaps(int64(x)); convert(DateTime{C,T},x+leaps(x)))
(+){C<:Calendar,T<:Offsets}(x::DateTime{C,T},y::Hour{C}) = (x = int64(x)+3600000*int64(y) - leaps(int64(x)); convert(DateTime{C,T},x+leaps(x)))
(-){C<:Calendar,T<:Offsets}(x::DateTime{C,T},y::Hour{C}) = (x = int64(x)-3600000*int64(y) - leaps(int64(x)); convert(DateTime{C,T},x+leaps(x)))
(+){C<:Calendar,T<:Offsets}(x::DateTime{C,T},y::Minute{C}) = (x = int64(x)+60000*int64(y) - leaps(int64(x)); convert(DateTime{C,T},x+leaps(x)))
(-){C<:Calendar,T<:Offsets}(x::DateTime{C,T},y::Minute{C}) = (x = int64(x)-60000*int64(y) - leaps(int64(x)); convert(DateTime{C,T},x+leaps(x)))
(+){C<:Calendar,T<:Offsets}(x::DateTime{C,T},y::Second{C}) = convert(DateTime{C,T},int64(x)+1000*int64(y))
(-){C<:Calendar,T<:Offsets}(x::DateTime{C,T},y::Second{C}) = convert(DateTime{C,T},int64(x)-1000*int64(y))
(+)(y::Period,x::DateTimeDate) = x + y
(-)(y::Period,x::DateTimeDate) = x - y
typealias DateTimePeriod Union(DateTimeDate,Period)
(+){T<:DateTimePeriod}(x::DateTimePeriod, y::AbstractArray{T}) = reshape([x + y[i] for i in 1:length(y)], size(y))
(+){T<:DateTimePeriod}(x::AbstractArray{T}, y::DateTimePeriod) = reshape([x[i] + y for i in 1:length(x)], size(x))
(-){T<:DateTimePeriod}(x::DateTimePeriod, y::AbstractArray{T}) = reshape([x - y[i] for i in 1:length(y)], size(y))
(-){T<:DateTimePeriod}(x::AbstractArray{T}, y::DateTimePeriod) = reshape([x[i] - y for i in 1:length(x)], size(x))
#DateRange: for creating fixed period frequencies
immutable DateRange{C<:Calendar} <: Ranges{Date{C}}
start::Date{C}
step::DatePeriod
len::Int
end
#DateRange1: for creating recurring events/dates, takes a function as step which return true for dates to be included
immutable DateRange1{C<:Calendar} <: Ranges{Date{C}}
start::Date{C}
step::Function
len::Int
end
typealias DateRanges Union(DateRange,DateRange1)
Base.size(r::DateRanges) = (r.len,)
Base.length(r::DateRanges) = r.len
Base.step(r::DateRanges) = r.step
Base.start(r::DateRanges) = 0
Base.first(r::DateRanges) = r.start
Base.done(r::DateRanges, i) = length(r) <= i
Base.last(r::DateRange) = r.start + convert(typeof(r.step),(r.len-1)*r.step)
Base.next(r::DateRange, i) = (r.start + convert(typeof(r.step),i*r.step), i+1)
function Base.show(io::IO,r::DateRanges)
print(io, r.start, ':', r.step, ':', last(r))
end
Base.colon{C<:Calendar}(t1::Date{C}, y::Year{C}, t2::Date{C}) = DateRange{C}(t1, y, fld(year(t2) - year(t1),y) + 1)
Base.colon{C<:Calendar}(t1::Date{C}, m::Month{C}, t2::Date{C}) = DateRange{C}(t1, m, fld((year(t2)-year(t1))*12+month(t2)-month(t1),m) + 1)
Base.colon{C<:Calendar}(t1::Date{C}, w::Week{C}, t2::Date{C}) = DateRange{C}(t1, w, fld(int64(t2)-int64(t1),7w) + 1)
Base.colon{C<:Calendar}(t1::Date{C}, d::Day{C}, t2::Date{C}) = DateRange{C}(t1, d, fld(int64(t2)-int64(t1),d) + 1)
Base.colon{C<:Calendar}(t1::Date{C}, t2::Date{C}) = DateRange{C}(t1, day(1), fld(int64(t2)-int64(t1),day(1)) + 1)
(+){C<:Calendar}(r::DateRange{C},p::DatePeriod) = DateRange{C}(r.start+p,r.step,r.len)
(-){C<:Calendar}(r::DateRange{C},p::DatePeriod) = DateRange{C}(r.start-p,r.step,r.len)
function Base.last(r::DateRange1)
t = r.start
len = 0
while true
r.step(t) && (len += 1)
len == r.len && break
t += day(1)
end
return t
end
function Base.next(r::DateRange1, i)
t = r.start
len = 0
while true
r.step(t) && (len += 1)
len == i+1 && break
t += day(1)
end
return (t,i+1)
end
function Base.colon{C<:Calendar}(t1::Date{C},fun::Function,t2::Date{C})
len = 0
t = d1 = t1
while t < t2
if fun(t)
len += 1
len == 1 && (d1 = t)
end
t += day(1)
end
return DateRange1{C}(d1, fun, len)
end
(+){C<:Calendar}(r::DateRange1{C},p::DatePeriod) = DateRange1{C}(r.start+p,r.step,r.len)
(-){C<:Calendar}(r::DateRange1{C},p::DatePeriod) = DateRange1{C}(r.start-p,r.step,r.len)
recur{C<:Calendar}(fun::Function,di::DateRange{C}) = colon(di.start,fun,last(di))
const Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday = 1,2,3,4,5,6,7
const January,February,March,April,May,June,July,August,September,October,November,December = 1,2,3,4,5,6,7,8,9,10,11,12
const Mon,Tue,Wed,Thu,Fri,Sat,Sun = 1,2,3,4,5,6,7
const Jan,Feb,Mar,Apr,Jun,Jul,Aug,Sep,Oct,Nov,Dec = 1,2,3,4,5,6,7,8,9,10,11,12
immutable DateTimeRange{C<:Calendar,T<:Offsets} <: Ranges{DateTime{C,T}}
start::DateTime{C,T}
step::Period
len::Int
end
Base.size(r::DateTimeRange) = (r.len,)
Base.length(r::DateTimeRange) = r.len
Base.step(r::DateTimeRange) = r.step
Base.start(r::DateTimeRange) = 0
Base.first(r::DateTimeRange) = r.start
Base.last(r::DateTimeRange) = r.start + convert(typeof(r.step),(r.len-1)*r.step)
Base.next(r::DateTimeRange, i) = (r.start + convert(typeof(r.step),i*r.step), i+1)
Base.done(r::DateTimeRange, i) = length(r) <= i
function Base.show{C<:Calendar}(io::IO,r::DateTimeRange{C})
print(io, r.start, ':', r.step, ':', last(r))
end
Base.colon{C<:Calendar,T<:Offsets}(t1::DateTime{C,T}, y::Year{C}, t2::DateTime{C,T}) = DateTimeRange{C,T}(t1, y, fld(year(t2) - year(t1),y) + 1)
Base.colon{C<:Calendar,T<:Offsets}(t1::DateTime{C,T}, m::Month{C}, t2::DateTime{C,T}) = DateTimeRange{C,T}(t1, m, fld((year(t2)-year(t1))*12+month(t2)-month(t1),m) + 1)
Base.colon{C<:Calendar,T<:Offsets}(t1::DateTime{C,T}, w::Week{C}, t2::DateTime{C,T}) = DateTimeRange{C,T}(t1, w, fld(_days(t2)-_days(t1),7w)+1)
Base.colon{C<:Calendar,T<:Offsets}(t1::DateTime{C,T}, d::Day{C}, t2::DateTime{C,T}) = DateTimeRange{C,T}(t1, d, fld(_days(t2)-_days(t1),d)+1)
Base.colon{C<:Calendar,T<:Offsets}(t1::DateTime{C,T}, h::Hour{C}, t2::DateTime{C,T}) = DateTimeRange{C,T}(t1, h, fld(fld(int64(t2),3600000)-fld(int64(t1),3600000),h)+1)
Base.colon{C<:Calendar,T<:Offsets}(t1::DateTime{C,T}, mi::Minute{C}, t2::DateTime{C,T}) = DateTimeRange{C,T}(t1, mi, fld(fld(int64(t2),60000)-fld(int64(t1),60000),mi)+1)
Base.colon{C<:Calendar,T<:Offsets}(t1::DateTime{C,T}, s::Second{C}, t2::DateTime{C,T}) = DateTimeRange{C,T}(t1, s, fld(fld(int64(t2),1000)-fld(int64(t1),1000),s)+1)
(+){C<:Calendar,T<:Offsets}(r::DateTimeRange{C,T},p::DatePeriod) = DateTimeRange{C,T}(r.start+p,r.step,r.len)
(-){C<:Calendar,T<:Offsets}(r::DateTimeRange{C,T},p::DatePeriod) = DateTimeRange{C,T}(r.start-p,r.step,r.len)
#Period types
Base.convert{P<:Period}(::Type{P},x::Int32) = Base.box(P,Base.unbox(Int32,x))
Base.convert{P<:Period}(::Type{Int32},x::P) = Base.box(Int32,Base.unbox(P,x))
Base.convert{P<:Period}(::Type{P},x::Real) = convert(P,int32(x))
Base.convert{R<:Real}(::Type{R},x::Period) = convert(R,int32(x))
for period in (Year,Month,Week,Day,Hour,Minute,Second)
@eval Base.convert(::Type{$period},x::Int32) = convert($period{CALENDAR},int32(x))
@eval Base.promote_rule{P<:$period}(::Type{P},::Type{P}) = $period{CALENDAR}
@eval Base.promote_rule{P<:$period,PP<:$period}(::Type{P},::Type{PP}) = $period{CALENDAR}
@eval Base.convert{P<:$period}(::Type{$period{ISOCalendar}},x::P) = convert($period{ISOCalendar},int32(x))
end
Base.promote_rule{P<:Period,R<:Real}(::Type{P},::Type{R}) = R
Base.promote_rule{A<:Period,B<:Period}(::Type{A},::Type{B}) =
A == Second{CALENDAR} || B == Second{CALENDAR} ? Second{CALENDAR} :
A == Minute{CALENDAR} || B == Minute{CALENDAR} ? Minute{CALENDAR} :
A == Hour{CALENDAR} || B == Hour{CALENDAR} ? Hour{CALENDAR} :
A == Day{CALENDAR} || B == Day{CALENDAR} ? Day{CALENDAR} :
A == Week{CALENDAR} || B == Week{CALENDAR} ? Week{CALENDAR} : Month{CALENDAR}
#conversion rules between periods; ISO/Greg/Julian-specific, but we define as the catchall for all Calendars
Base.convert{C<:Calendar}(::Type{Month{C}},x::Year{C}) = convert(Month{C}, int32(12x))
Base.convert{C<:Calendar}(::Type{Week{C}},x::Year{C}) = convert(Week{C}, int32(52x))
Base.convert{C<:Calendar}(::Type{Day{C}},x::Year{C}) = convert(Day{C}, int32(365x))
Base.convert{C<:Calendar}(::Type{Day{C}},x::Week{C}) = convert(Day{C}, int32(7x))
Base.convert{C<:Calendar}(::Type{Hour{C}},x::Year{C}) = convert(Hour{C}, int32(8760x))
Base.convert{C<:Calendar}(::Type{Hour{C}},x::Week{C}) = convert(Hour{C}, int32(168x))
Base.convert{C<:Calendar}(::Type{Hour{C}},x::Day{C}) = convert(Hour{C}, int32(24x))
Base.convert{C<:Calendar}(::Type{Minute{C}},x::Year{C}) = convert(Minute{C}, int32(525600x)) #Rent anybody?
Base.convert{C<:Calendar}(::Type{Minute{C}},x::Week{C}) = convert(Minute{C}, int32(10080x))
Base.convert{C<:Calendar}(::Type{Minute{C}},x::Day{C}) = convert(Minute{C}, int32(1440x))
Base.convert{C<:Calendar}(::Type{Minute{C}},x::Hour{C}) = convert(Minute{C}, int32(60x))
Base.convert{C<:Calendar}(::Type{Second{C}},x::Year{C}) = convert(Second{C}, int32(31536000x))
Base.convert{C<:Calendar}(::Type{Second{C}},x::Week{C}) = convert(Second{C}, int32(604800x))
Base.convert{C<:Calendar}(::Type{Second{C}},x::Day{C}) = convert(Second{C}, int32(86400x))
Base.convert{C<:Calendar}(::Type{Second{C}},x::Hour{C}) = convert(Second{C}, int32(3600x))
Base.convert{C<:Calendar}(::Type{Second{C}},x::Minute{C}) = convert(Second{C}, int32(60x))
#Constructors; default to CALENDAR; with (s) too cutesy? seems natural/expected though
years = (year(x::PeriodMath) = convert(Year{CALENDAR},x))
months = (month(x::PeriodMath) = convert(Month{CALENDAR},x))
weeks = (week(x::PeriodMath) = convert(Week{CALENDAR},x))
days = (day(x::PeriodMath) = convert(Day{CALENDAR},x))
hours = (hour(x::PeriodMath) = convert(Hour{CALENDAR},x))
minutes = (minute(x::PeriodMath) = convert(Minute{CALENDAR},x))
seconds = (second(x::PeriodMath) = convert(Second{CALENDAR},x))
#Print/show/traits
_units(x::Period) = " " * lowercase(string(typeof(x).name)) * (x == 1 ? "" : "s")
Base.print(io::IO,x::Period) = print(io,int32(x),_units(x))
Base.show(io::IO,x::Period) = print(io,x)
Base.string(x::Period) = string(int32(x),_units(x))
Base.typemin{P<:Period}(::Type{P}) = convert(P,typemin(Int32))
Base.typemax{P<:Period}(::Type{P}) = convert(P,typemax(Int32))
Base.zero{P<:Period}(::Union(Type{P},P)) = convert(P,int32(0))
Base.one{P<:Period}(::Union(Type{P},P)) = convert(P,int32(1))
offset(x::Period) = return Offset{int(minutes(x))}
offset(x::Period...) = return Offset{int(minutes(sum(x...)))}
#Period Arithmetic:
Base.isless{P<:Period}(x::P,y::P) = isless(int32(x),int32(y))
Base.isless(x::PeriodMath,y::PeriodMath) = isless(promote(x,y)...)
Base.isequal{P<:Period}(x::P,y::P) = isequal(int32(x),int32(y))
Base.isequal(x::Period,y::Period) = isequal(promote(x,y)...)
Base.isequal(x::Period,y::Real) = isequal(promote(x,y)...)
Base.isequal(x::Real,y::Period) = isequal(promote(x,y)...)
=={P<:Period}(x::P,y::P) = ==(int32(x),int32(y))
==(x::Period,y::Period) = ==(promote(x,y)...)
==(x::Period,y::Real) = ==(promote(x,y)...)
==(x::Real,y::Period) = ==(promote(x,y)...)
(-){P<:Period}(x::P) = convert(P,-int32(x))
import Base.fld
for op in (:+,:-,:%,:fld)
@eval begin
($op != /) && (($op){P<:Period}(x::P,y::P) = convert(P,($op)(int32(x),int32(y))))
($op){P<:Period}(x::P,y::Real) = ($op)(promote(x,y)...)
($op){P<:Period}(x::Real,y::P) = ($op)(promote(x,y)...)
!($op in (/,%,fld)) && ( ($op)(x::Period,y::Period) = ($op)(promote(x,y)...) )
if !($op in (/,%,fld))
($op){P<:Period}(x::Period, y::AbstractArray{P}) = reshape([($op)(x, y[i]) for i in 1:length(y)], size(y))
($op){P<:Period}(x::AbstractArray{P}, y::Period) = reshape([($op)(x[i], y) for i in 1:length(x)], size(x))
end
end
end
for op in (:*, :/)
@eval begin
($op){P<:Period}(x::P,y::P) = convert(P,($op)(int32(x),int32(y)))
($op){P<:Period}(x::P,y::Real) = convert(P, ($op)(promote(x,y)...))
($op){P<:Period}(x::Real,y::P) = convert(P, ($op)(promote(x,y)...))
($op)(x::Period,y::Period) = ($op)(promote(x,y)...)
($op){P<:Period}(x::Period, y::AbstractArray{P}) = reshape([($op)(x, y[i]) for i in 1:length(y)], size(y))
($op){P<:Period}(x::AbstractArray{P}, y::Period) = reshape([($op)(x[i], y) for i in 1:length(x)], size(x))
end
end
(/){P<:Period}(x::P,y::P) = int32(x) / int32(y)
# Date/DateTime-Month arithmetic
# monthwrap adds two months with wraparound behavior (i.e. 12 + 1 == 1)
monthwrap(m1,m2) = (v = mod1(m1+m2,12); return v < 0 ? 12 + v : v)
# yearwrap takes a starting year/month and a month to add and returns
# the resulting year with wraparound behavior (i.e. 2000-12 + 1 == 2001)
yearwrap(y,m1,m2) = y + fld(m1 + m2 - 1,12)
#DateRange: for creating fixed period frequencies
immutable PeriodRange{P<:Period} <: Ranges{Period}
start::P
step::P
len::Int
end
Base.size(r::PeriodRange) = (r.len,)
Base.length(r::PeriodRange) = r.len
Base.step(r::PeriodRange) = r.step
Base.start(r::PeriodRange) = 0
Base.first(r::PeriodRange) = r.start
Base.done(r::PeriodRange, i) = length(r) <= i
Base.last(r::PeriodRange) = r.start + convert(typeof(r.step),(r.len-1)*r.step)
Base.next(r::PeriodRange, i) = (r.start + convert(typeof(r.step),i*r.step), i+1)
function Base.show(io::IO,r::PeriodRange)
print(io, r.start, ':', r.step, ':', last(r))
end
Base.colon{P<:Period}(t1::P, s::P, t2::P) = PeriodRange{P}(t1, s, fld(t2-t1,s) + int32(1))
Base.colon{P<:Period}(t1::P, t2::P) = PeriodRange{P}(t1, one(P), int32(t2)-int32(t1) + int32(1))
(+){P<:Period}(r::PeriodRange{P},p::P) = PeriodRange{P}(r.start+p,r.step,r.len)
(-){P<:Period}(r::PeriodRange{P},p::P) = PeriodRange{P}(r.start-p,r.step,r.len)
end #module
|
The core and very special thing at Ultimate is the Spirit of the Game (SOTG). The same counts for JUMP+REACH / GAIA Europe as a company. Our core value is the mutual respect for everybody we deal with based on the assumption that everybody sticks to the basic rules.
And that is the simple reason why we convey, promote and sponsor this very special and so important aspect of the game of Ultimate and the game of live with our "GAIA Spirit Sponsorship".
This way it is ensured that every player from the Spirit winning team gets his/her very own (white) GAIA Spirit Award disc. While the black GAIA Spirit Award disc from the award ceremony is mostly used to display in the club house, the school hall of fame, etc.
"name dropping" in emails before and after the tournament, on the website, during the tournament, etc. |
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# Cadishi --- CAlculation of DIStance HIstograms
#
# Copyright (c) Klaus Reuter, Juergen Koefinger
# See the file AUTHORS.rst for the full list of contributors.
#
# Released under the MIT License, see the file LICENSE.txt.
"""cudh Python interface.
Calls the c_cudh Python module.
"""
from __future__ import print_function
import subprocess as sub
from builtins import str
from builtins import zip
from builtins import range
import numpy as np
from . import common
try:
from . import c_cudh
except:
have_c_cudh = False
else:
have_c_cudh = True
from .. import pbc
def get_num_devices():
"""Get the number of available NVIDIA devices.
We do not use the function "c_cudh.get_num_devices()" because it is
not allowed to fork and use CUDA in processes after a first CUDA call,
which would be the case in <histograms.py> (and was hard to figure out).
"""
n = 0
cmd = "nvidia-smi -L".split()
try:
raw = sub.check_output(cmd).lower().split('\n')
gpus = [x for x in raw if x.startswith("gpu")]
n = len(gpus)
except:
pass
return n
def get_num_cuda_devices():
"""Get the number of available NVIDIA devices, using the CUDA API."""
if have_c_cudh:
n = c_cudh.get_num_cuda_devices()
else:
n = 0
return n
def histograms(coordinate_sets,
r_max,
n_bins,
precision="single",
gpu_id=0,
do_histo2_only=False,
thread_block_x=0,
check_input=True,
scale_factors=[],
mask_array=[],
box=[],
force_triclinic=False,
verbose=False,
algorithm=-1):
"""Distance histogram calculation on NVIDIA GPUs using CUDA.
Calculate distance histograms for sets of species coordinates by calling the
CUDA kernels that are provided by the Python module c_cudh written in CUDA.
Parameters
----------
coordinate_sets : list of numpy.ndarray
List of numpy arrays where each numpy array contains
the atom coordinates for all the atoms of a species.
r_max : float
Cutoff radius for the distance calculation.
n_bins : int
Number of histogram bins.
precision : string, optional
String specifying the implementation and/or the precision. "single" is the
default value for single precision, use "double" for double precision.
gpu_id : int, optional
The GPU to be used to calculate the histograms. 0 is the default value.
do_histo2_only : bool, optional
In case only two sets of coordinates are given, calculate only the distance
histogram between the species sets. For benchmark purposes only.
thread_block_x : int, optional
Manually set the CUDA thread block size (x), overrides the internal default
if set to a value larger than zero. For benchmark and debugging purposes.
Returns
-------
numpy.ndarray
Two-dimensional numpy array containing the distance histograms.
"""
if not have_c_cudh:
raise RuntimeError(common.import_cudh_error_msg)
for cs in coordinate_sets:
assert(cs.dtype == np.float64)
assert(r_max > 0.0)
assert(n_bins > 0)
n_El = len(coordinate_sets)
n_Hij = (n_El * (n_El + 1)) // 2
if do_histo2_only and (n_El != 2):
raise ValueError(common.histo2_error_msg)
# Reorder coordinate sets by size to maximize the performance of the CUDA
# smem kernels, this is most advantageous when small and large sets are mixed.
do_reorder = True
if do_histo2_only:
np_mask = np.zeros(3, dtype=np.int32)
np_mask[1] = 1
do_reorder = False
else:
if (n_Hij == len(mask_array)):
np_mask = np.asarray(mask_array, dtype=np.int32)
# TODO : implement reordering of mask_array for the general case
if (np.sum(np.where(np_mask <= 0)) > 0):
do_reorder = False
else:
np_mask = np.ones(n_Hij, dtype=np.int32)
if do_reorder:
# --- create lists containing (indices,sizes) sorted by size
el_idx = list(range(n_El))
el_siz = []
for i in el_idx:
el_siz.append(coordinate_sets[i].shape[0])
idx_siz = list(zip(el_idx, el_siz))
idx_siz.sort(key=lambda tup: tup[1])
el_idx_srt, el_siz_srt = list(zip(*idx_siz))
# --- create reordered concatenated numpy arrays
n_coord = sum(el_siz)
np_coord = np.zeros((n_coord, 3))
np_nelem = np.zeros((n_El,), dtype=np.int32)
jc = 0 # coordinate array offset
jn = 0 # nelem array offset
for tup in idx_siz:
idx, siz = tup
np_coord[jc:jc + siz, :] = coordinate_sets[idx]
np_nelem[jn] = siz
jc += siz
jn += 1
# --- create a hash, mapping (i,j) to the linear index used in
# the histograms array
idx = {}
count = 1
for i in range(n_El):
ii = el_idx_srt[i]
for j in range(i, n_El):
jj = el_idx_srt[j]
tup = (ii, jj)
idx[tup] = count
tup = (jj, ii)
idx[tup] = count
count += 1
else:
# --- concatenate list of numpy arrays into a single numpy array
np_coord = np.concatenate(coordinate_sets, axis=0)
np_nelem = np.zeros((n_El), dtype=np.int32)
for i in range(n_El):
np_nelem[i] = coordinate_sets[i].shape[0]
# --- To see the bins contiguously in memory from C, we use the following layout:
histos = np.zeros((n_bins, n_Hij + 1), dtype=np.uint64, order='F')
np_box, box_type_id, box_type = pbc.get_standard_box(box,
force_triclinic=force_triclinic, verbose=False)
if (box_type is not None):
print(common.indent + "cudh box_type: " + str(box_type))
precision = common.precision_to_enum(precision)
# --- run the CUDH distance histogram kernel
exit_status = c_cudh.histograms(np_coord, np_nelem, histos, r_max, np_mask, np_box, box_type_id,
precision, check_input, verbose, gpu_id, thread_block_x, algorithm)
if (exit_status == 1):
#c_cudh.free()
raise ValueError(common.overflow_error_msg)
elif (exit_status >= 2):
#c_cudh.free()
raise RuntimeError(common.general_error_msg)
if do_reorder:
# --- restore the expected order
histo_ret = np.zeros_like(histos)
count = 1
for i in el_idx:
for j in range(i, n_El):
histo_ret[:, count] = histos[:, idx[(i, j)]]
count += 1
else:
histo_ret = histos
# --- re-scale histograms in case an appropriately sized scale factor array is passed
if (n_Hij == len(scale_factors)):
np_scales = np.asarray(scale_factors)
histo_ret = common.scale_histograms(histo_ret, np_scales)
return histo_ret
|
If $f$ is holomorphic on an open set $S$, and $\gamma$ is a closed path in $S$ that does not pass through $z$, then the integral of $f(w)/(w-z)$ along $\gamma$ is $2\pi i$ times the winding number of $\gamma$ around $z$ times $f(z)$. |
Suryagarh Jaisalmer (India) | FROM $74 - SAVE ON AGODA!
"Beautiful property with exceptional service."
Have a question for Suryagarh Jaisalmer?
"The staff were fantastic, each and everyone of them."
Whether you're a tourist or traveling on business, Suryagarh Jaisalmer is a great choice for accommodation when visiting Jaisalmer. From here, guests can enjoy easy access to all that the lively city has to offer. No less exceptional is the hotel's easy access to the city's myriad attractions and landmarks, such as Kuldhara Abandoned Village.
The facilities and services provided by Suryagarh Jaisalmer ensure a pleasant stay for guests. A selection of top-class facilities such as 24-hour room service, free Wi-Fi in all rooms, 24-hour front desk, facilities for disabled guests, express check-in/check-out can be enjoyed at the hotel.
In addition, all guestrooms feature a variety of comforts. Many rooms even provide television LCD/plasma screen, clothes rack, mirror, towels, internet access – wireless to please the most discerning guest. The hotel offers wonderful recreational facilities such as hot tub, fitness center, indoor pool, spa, massage to make your stay truly unforgettable. With an ideal location and facilities to match, Suryagarh Jaisalmer hits the spot in many ways.
"The hotel is located 15km from the city."
excellent Location, Tasty and Varieties of food. Totally different experience. As food professional i always suggest to keep local dishes which only you people has served. Dal pakwan/Bajra khichdi were excellent and services in restaurant as well. Thanks for everything. Keep it up.
Absolutely fabulous hotel. The staff were fantastic, each and everyone of them. The location for us was wonderful as it was out of the hustle of the city and yet close enough to do anything in the city. The rooms were spacious, clean and well appointed. The property was nice.
I wish Jaisalmer had a direct flight, just so that I can visit Suraygarh again. Beautiful property with exceptional service. Specially the buffet and the serving staff. Property was full, still there was enough space and service was good. Seems like good service is build into the culture and everyone was really good. Staff brought out breakfast items that were not on the menu, which was great. Would like to call out Manjeet for great seevice. Only thing that was lacking is giving us info on activities provided by Suraygarh. Like safari or dinner at dunes, I asked for infor repeatedly but no one reached out. Rest was great and I will definitely recommend anyone who is going to Jaisalmer.
We spent 2 wonderful nights at Suryegarh. It is a little outside of city center of Jaisalmer in the middle of the desert. A charming renovated fort, you arrive there and never want to leave. Service is great, breakfast is a highlight, the rest of the food was good but way overpriced. Pool is under renovation but overall the hotel is still an amazing experience!
This hotel was absolutely amazing, perfect for our family. From the numerous reading nooks and gorgeous old artifacts to sublime gardens and exceptional service, we loved every minute of our stay. The animals at breakfast enchanted our 11 and 9 year old kids. The only disappointing thing was that the main pool was out of service having repairs, so there was only a very small (but nice) pool to dip in (it was very hot, so the pool was necessary). I would highly recommend it to anyone. Note that it’s 15 minutes drive outside the craziness of the main town but this was a good thing!
The facilities are immaculate. The staff caters towards all your needs, but sometimes it felt that someone is babysitting you. Some personal space without interruption during meals would be a welcome change. Overall, I would recommend the stay at this location.
To visit Suryagarh Jaisalmer is atleast once in a lifetime place to visit. We were here for our first anniversary and it was a experience to remember. They have given the feel of Old traditional fort with modern touch. The peace, joy and serenity you feel and absorb at thai place is just beyond words. I will for sure come here many more times in near future.
We stayed at the signature suite at suryagarh which were very comfortable and retained the perfect heritage charm. Despite a few glitches here and there the overall experience at the hotel was great. The personalized service at the hotel made us feel at home. Special mention for the staff. They are pros at taking really good care of their guests. Food quality was good.
Great stay in a lovely hotel away from the pollution in the city, yet close enough since it's just a 20 minute drive to the fort. The property is beautifully laid out, the colours are restful, there's nothing that jars and the 'chudail trail' late at night is great fun - you mightn't see any ghosts but it's a delightfully spooky experience, and of course, the desert stars are awesome.
The hotel is spread over vast property and have all the amenities. The highlight is the breakfast time when you have peacock, dove, tortoise running around in the lobby and you can even feed them. The children will definitely have great time playing with animals and listening to live folk songs. Staff are courteous and will ensure that you have pleasant stay. I would like to thank Mr Sagar for helping us to plan our stay and also upgrading our rooms to ensure children have direct access to lobby. A definite place to stay.
impressive building and extensive grounds 6 stars service and attention to detail encountered only in other few 5 starsL world-famous hotels massage to die for think I went to heaven and back a few times in only 75 minutes would have gladly stayed another few days just mooching around well done guys!
Loved the entire property and the food preparations by Chef Megh Singh Rathore.
excellent property and ambience. loved it!
The hotel is beautiful, the food is amazing and overall we had an excellent stay. Highly recommend it.
its a fantastic hotel with best off beat location. one can easily spend about two days just enjoying hostel amenities. staff is so profession al and coperative.
Great staff, sublime hotel, delicious food! We will go back. |
!##############################################################################
!# Tutorial 004b: Datastructures - linked lists
!##############################################################################
module tutorial004b
! Include basic Feat-2 modules
use fsystem
use genoutput
use listInt
implicit none
private
public :: start_tutorial004b
contains
! ***************************************************************************
subroutine start_tutorial004b
! Declare some variables
type(t_listInt) :: rlist
type(it_listInt) :: riterator
integer :: i
! Print a message
call output_lbrk()
call output_separator (OU_SEP_STAR)
call output_line ("This is FEAT-2. Tutorial 004b")
call output_separator (OU_SEP_MINUS)
! =================================
! Create linked list with initial space for 10 items
! =================================
call list_create(rlist, 10)
! =================================
! Insert new items at the end of the list
! =================================
call list_push_back(rlist, 5)
call list_push_back(rlist, 23)
call list_push_back(rlist, 2)
call list_push_back(rlist, 76)
! =================================
! Insert new items at the beginning of the list
! =================================
call list_push_front(rlist, 9)
call list_push_front(rlist, -2)
call list_push_front(rlist, -52)
call list_push_front(rlist, -4)
! =================================
! Check size and content of the list
! =================================
i = list_size(rlist)
call output_line ("Size of the list: " // trim(sys_siL(i,10)))
i = list_max_size(rlist)
call output_line ("Maximum size of the list (before internal data is reallocated): "&
// trim(sys_siL(i,10)))
if (list_empty(rlist)) then
call output_line ("List is empty!")
else
call output_line ("List is not empty!")
end if
! =================================
! Perform forward iteration through list items
! =================================
riterator = list_begin(rlist)
do while (riterator .ne. list_end(rlist))
i = list_get(rlist, riterator)
call output_line (" " // trim(sys_siL(i,10)), bnolinebreak=.true.)
call list_next(riterator)
end do
call output_lbrk()
! =================================
! Perform backward iteration through list items
! =================================
riterator = list_rbegin(rlist)
do while (riterator .ne. list_rend(rlist))
i = list_get(rlist, riterator)
call output_line (" " // trim(sys_siL(i,10)), bnolinebreak=.true.)
call list_next(riterator)
end do
call output_lbrk()
! =================================
! Reverse list items
! =================================
call list_reverse(rlist)
! =================================
! Perform forward iteration through list items
! =================================
riterator = list_begin(rlist)
do while (riterator .ne. list_end(rlist))
i = list_get(rlist, riterator)
call output_line (" " // trim(sys_siL(i,10)), bnolinebreak=.true.)
call list_next(riterator)
end do
call output_lbrk()
! =================================
! Sort list items
! =================================
call list_sort(rlist)
! =================================
! Perform forward iteration through list items
! =================================
riterator = list_begin(rlist)
do while (riterator .ne. list_end(rlist))
i = list_get(rlist, riterator)
call output_line (" " // trim(sys_siL(i,10)), bnolinebreak=.true.)
call list_next(riterator)
end do
call output_lbrk()
! =================================
! Remove first and last item from list
! =================================
call list_pop_front(rlist)
call list_pop_back(rlist)
! =================================
! Perform forward iteration through list items
! =================================
riterator = list_begin(rlist)
do while (riterator .ne. list_end(rlist))
i = list_get(rlist, riterator)
call output_line (" " // trim(sys_siL(i,10)), bnolinebreak=.true.)
call list_next(riterator)
end do
call output_lbrk()
! =================================
! Find item by key value and erase it
! =================================
riterator = list_find(rlist, 9)
if (.not.list_isNull(riterator)) then
riterator = list_erase(rlist, riterator)
end if
! =================================
! Insert item at position
! =================================
riterator = list_insert(rlist, riterator, 47)
! =================================
! Perform forward iteration through list items
! =================================
riterator = list_begin(rlist)
do while (riterator .ne. list_end(rlist))
i = list_get(rlist, riterator)
call output_line (" " // trim(sys_siL(i,10)), bnolinebreak=.true.)
call list_next(riterator)
end do
call output_lbrk()
! =================================
! Release linked list
! =================================
call list_release(rlist)
end subroutine
end module
|
Formal statement is: lemma Sup_lim: fixes a :: "'a::{complete_linorder,linorder_topology}" assumes "\<And>n. b n \<in> s" and "b \<longlonglongrightarrow> a" shows "a \<le> Sup s" Informal statement is: If $b_n$ is a sequence of elements of a set $s$ that converges to $a$, then $a$ is less than or equal to the supremum of $s$. |
Surat Lamaran Kerja Bahasa Inggris Singkat is just about the image we ascertained on the internet from reliable imagination. We constitute one head to discourse this Surat Lamaran Kerja Bahasa Inggris Singkat picture on this webpage because predicated on conception coming from Google Image, Its one of the very best reted concerns keyword on Yahoo INTERNET SEARCH ENGINE. And that people also consider you arrived here were looking because of this information, are not You? From many options on the internet were sure this pictures is actually a good image for you, and we sincerely hopefully you are proud of with what we present. |
module Evens
% access public export
public export
data IsEven : Nat -> Type where
ZEven : IsEven 0
SSEven : (n: Nat) -> IsEven n -> IsEven (S (S n))
twoEven : IsEven 2
twoEven = SSEven 0 ZEven
fourEven : IsEven 4
fourEven = SSEven 2 twoEven
half : (n: Nat) -> IsEven n -> Nat
half Z ZEven = 0
half (S (S k)) (SSEven k x) = S (half k x)
double: Nat -> Nat
double Z = Z
double (S k) = S (S (double k))
doubleEven : (n: Nat) -> IsEven (double n)
doubleEven Z = ZEven
doubleEven (S k) = SSEven (double k) (doubleEven k)
halfDouble: Nat -> Nat
halfDouble n = half (double n) (doubleEven n)
oneOdd: IsEven 1 -> Void
oneOdd ZEven impossible
oneOdd (SSEven _ _) impossible
threeOdd : IsEven 3 -> Void
threeOdd (SSEven (S Z) ZEven) impossible
threeOdd (SSEven (S Z) (SSEven _ _)) impossible
nOrSnEven: (n: Nat) -> Either (IsEven n) (IsEven (S n))
nOrSnEven Z = Left ZEven
nOrSnEven (S k) = case (nOrSnEven k) of
(Left l) => Right (SSEven k l)
(Right r) => Left r
halfRoof: Nat -> Nat
halfRoof n = case (nOrSnEven n) of
(Left nEven) => half n nEven
(Right snEven) => half (S n) snEven
nSnNotBothEven: (n: Nat) -> (IsEven n) -> IsEven (S n) -> Void
nSnNotBothEven Z ZEven ZEven impossible
nSnNotBothEven Z ZEven (SSEven _ _) impossible
nSnNotBothEven (S (S k)) (SSEven k x) (SSEven (S k) y) = nSnNotBothEven k x y
notNandSnEven : (n: Nat) -> (IsEven n , IsEven (S n)) -> Void
notNandSnEven n (a, b) = nSnNotBothEven n a b
apNat : (f: Nat -> Nat) -> (n: Nat) -> (m: Nat) -> n = m -> f n = f m
apNat f m m Refl = Refl
byTwo : (n: Nat) -> IsEven n -> (k: Nat ** double k = n)
byTwo Z ZEven = (0 ** Refl)
byTwo (S (S k)) (SSEven k x) = step where
step = case (byTwo k x) of
(m ** pf) => ((S m) ** apNat (\l => S (S l)) (double m) k pf)
oneOddFamily : Nat -> Type
oneOddFamily Z = ()
oneOddFamily (S Z) = Void
oneOddFamily (S (S k)) = ()
oneOddProof : (n : Nat) -> IsEven n -> oneOddFamily n
oneOddProof Z ZEven = ()
oneOddProof (S (S k)) (SSEven k x) = ()
-- Examples
halfRoof3 : Nat
halfRoof3 = halfRoof 3 -- 2 : Nat
-- Equality added
thmAdd : (a: Nat) -> (b: Nat) -> (a = 0) -> (b = 0) -> (a + b = 0)
thmAdd Z Z Refl Refl = Refl
symmEq : (x : Type) -> (a: x) -> (b: x) -> (a = b) -> (b = a)
symmEq x b b Refl = Refl
|
/*
* This file is part of the DUDS project. It is subject to the BSD-style
* license terms in the LICENSE file found in the top-level directory of this
* distribution and at https://github.com/jjackowski/duds/blob/master/LICENSE.
* No part of DUDS, including this file, may be copied, modified, propagated,
* or distributed except according to the terms contained in the LICENSE file.
*
* Copyright (C) 2017 Jeff Jackowski
*/
#ifndef INSTRUMENT_HPP
#define INSTRUMENT_HPP
#include <duds/Something.hpp>
#include <duds/data/Measurement.hpp>
#include <duds/general/Errors.hpp>
#include <duds/hardware/MeasurementSignalSource.hpp>
//#include <boost/signals2/signal.hpp>
//#include <boost/uuid/uuid.hpp>
#include <boost/uuid/nil_generator.hpp>
namespace duds { namespace hardware {
struct InstrumentDriverAlreadySet : virtual std::exception, virtual boost::exception { };
template<class SVT, class SQT, class TVT, class TQT>
class GenericInstrumentDriver;
template<class SVT, class SQT, class TVT, class TQT>
class GenericInstrumentAdapter;
// maybe send sample events, know nothing of the set, and allow use of multiple
// sets with the same object?
// *MUST* derive from std::enable_shared_from_this ?
/**
* Represents a specific instrument on a specific device.
*
* Instruments are handled in three parts: the instrument, driver, and adapter.
* The GenericInstrument class represnts the hardware that can measure
* something. Some devices have hardware to measure multiple things, like
* temperature and pressure, and require multiple GenericInstrument objects
* to be fully and properly represnted. The GenericInstrumentDriver class is
* an interface to the code that communicates with the hardware or otherwise
* obtains data from the instrument. The GenericInstrumentAdapter class allows
* a single GenericInstrumentDriver object to update a single GenericInstrument
* object, however a driver could gather multiple adapters to update multiple
* instruments. This separation allows multiple driver implementations for
* the same kind of hardware, and for an abstraction that prevents the code
* using the input from being tied to the code that provides the input.
* The plan is to use this feature to allow updates for a GenericInstrument
* to either come from the local hardware or to travel over a network, and
* allow code that uses the input from the instrument to be unaware of the
* difference and able to function without a hardware driver for the
* instrument.
*
* @sa Instrument
* @sa InstrumentDriver
* @sa InstrumentAdapter
*
* @todo derive from std::enable_shared_from_this ???
*
* @tparam SVT Sample value type
* @tparam SQT Sample quality type
* @tparam TVT Time value type
* @tparam TQT Time quality type
*
* Have a reference clock. Maybe pass it in to functions that produce a
* measurement. Maybe make it a static. Maybe do both.
*
* @author Jeff Jackowski
*/
template <class SVT, class SQT, class TVT, class TQT>
class GenericInstrument :
public Something,
public GenericMeasurementSignalSource<SVT, SQT, TVT, TQT>
{
public:
/**
* The measurement type used by this instrument.
*/
typedef duds::data::GenericMeasurement<SVT, SQT, TVT, TQT> Measurement;
/**
* The base driver class used for this instrument.
*/
typedef GenericInstrumentDriver<SVT, SQT, TVT, TQT> Driver;
/**
* The base adapter class used for this instrument.
*/
typedef GenericInstrumentAdapter<SVT, SQT, TVT, TQT> Adapter;
private:
friend Adapter;
/**
* The UUID for the part, the specific component that contains the
* instrument. The only link to the part is an UUID rather than some
* pointer so that the part object need not exist. Not all programs will
* have need of the part object.
*/
boost::uuids::uuid pid;
/**
* The most current measurement from the insturment. It will be empty
* until the first measurement is receieved.
* @note Declared as mutable to allow changes to this member when the
* object is stored in containers like std::set that keep const
* elements.
*/
mutable std::shared_ptr<const Measurement> currmeas;
mutable Adapter *adp; // like an access object
/**
* The units of the instrument's samples.
*/
duds::data::Unit u;
/**
* Removes the adapter object when that object is destroyed.
*/
void retireAdapter(Adapter *ia) noexcept{
// these really should match
if (ia == adp) {
adp = NULL;
}
}
/**
* Provide a measurement to the signal listeners. The measurement does not
* have to be the most recent.
* @pre Neither signalMeasurement() nor signalSample() are called for the
* same instrument object on another thread. The operation is @b not
* thread-safe.
* @param measure The measurement object to be recorded.
*/
void signalMeasurement(
const std::shared_ptr<const Measurement> &measure
) {
/** @todo Check units - assure match */
// time check -- newer measurement?
if (measure->timestamp.value > currmeas->timestamp.value) {
// assign current measurement
currmeas = measure;
// send new measurement signal
this->newMeasure(sharedPtr(), measure);
} else {
// send old measurement signal
this->oldMeasure(sharedPtr(), measure);
}
}
/**
* Sends a signal with the given sample along with the current time using
* the default clock (?!?).
* @pre Neither signalMeasurement() nor signalSample() are called for the
* same instrument object on another thread. The operation is @b not
* thread-safe.
* @param samp The sample value to record.
* @post The data in @a samp will be swapped into a Measurement object
* created by this function. This is done to avoid a potentially
* expensive copy operation, but means the value of @a samp will
* change and should be considered uninitalized after the call.
*/
void signalSample(
typename Measurement::Sample &samp
) {
/** @todo Record the time. */
typename Measurement::TimeSample t;
// make a new measurement
std::shared_ptr<Measurement> m = std::make_shared<Measurement>(
std::move(t), std::move(samp));
/* Or maybe record time here directly to m->timestamp. */
// swap the samples
//std::swap(m->measured, samp);
// record the measurement
signalMeasurement(m);
}
public:
/**
* @post The units will be reported as unitless. The part ID will be zero.
* @param uid The UUID for this specific instrument.
*/
GenericInstrument(const boost::uuids::uuid &uid) : Something(uid),
pid(boost::uuids::nil_uuid()), adp(nullptr), u(0) { }
/**
* @post The units will be reported as unitless.
* @param uid The UUID for this specific instrument.
* @param partId The UUID identifying the type of gizmo that has the
* instrument.
*/
GenericInstrument(const boost::uuids::uuid &uid,
const boost::uuids::uuid &partId) : Something(uid),
pid(partId), adp(nullptr), u(0) { }
/**
* @post The units will be reported as unitless unless the driver sets
* the units. The part ID will be zero.
* @param uid The UUID for this specific instrument.
* @param driver The instrument driver object.
*/
GenericInstrument(const boost::uuids::uuid &uid,
const std::shared_ptr<Driver> &driver) : Something(uid),
pid(boost::uuids::nil_uuid()), adp(nullptr), u(0)
{
setDriver(driver);
}
/**
* @post The units will be reported as unitless unless the driver sets
* the units.
* @param uid The UUID for this specific instrument.
* @param partId The UUID identifying the type of gizmo that has the
* instrument.
* @param driver The instrument driver object.
*/
GenericInstrument(const boost::uuids::uuid &uid,
const boost::uuids::uuid &partId,
const std::shared_ptr<Driver> &driver) : Something(uid), pid(partId),
adp(nullptr), u(0)
{
setDriver(driver);
}
/**
* Severs the link from the adapter object to this object should an adapter
* still exist. Ideally, an adapter should not exist or should no longer
* be in active use.
*/
~GenericInstrument() {
// if an adpater still exists . . .
if (adp) {
assert(adp->inst.get() == this);
// . . . destroy its link back to this object
adp->inst.reset();
}
}
std::shared_ptr<GenericInstrument> sharedPtr() {
return std::static_pointer_cast<GenericInstrument>(shared_from_this());
}
/**
* Sets the driver object for this instrument.
* @pre A driver has not been set for this instrument, or it has lost
* its reference to the InstrumentAdapter.
* @param driver The driver object that will communicate with the
* instrument. It must @b not be an empty std::shared_ptr.
* @throw InstrumentDriverAlreadySet Destroy all shared pointer
* references to the Adapter object
* before setting a new driver.
* @throw std::exception An error thrown from
* Driver::setAdapter(). The driver
* will not be used.
*/
void setDriver(const std::shared_ptr<Driver> &driver) const {
// there must not already be an adapter object
if (adp) {
/** @todo Add an attribute, either UUID or std::shared_ptr. */
DUDS_THROW_EXCEPTION(InstrumentDriverAlreadySet());
}
std::shared_ptr<Adapter> iadapt = std::make_shared<Adapter>(driver);
// give the driver its adapter object; may throw
driver->setAdapter(iadapt);
// record the adapter's address
adp = iadapt.get();
}
/**
* Makes an adapter object without an associated driver object.
* This may make it a little easier to use, but will block any requests
* made of the instrument through this class.
* @pre A driver has not been set for this instrument, or it has lost
* its reference to the InstrumentAdapter.
* @throw InstrumentDriverAlreadySet Destroy all shared pointer
* references to the Adapter object
* before setting a new driver.
*/
std::shared_ptr<Adapter> makeAdapter() const {
// there must not already be an adapter object
if (adp) {
/** @todo Add an attribute, either UUID or std::shared_ptr. */
DUDS_THROW_EXCEPTION(InstrumentDriverAlreadySet());
}
std::shared_ptr<Adapter> iadapt =
std::make_shared<Adapter>(std::shared_ptr<Driver>());
// record the adapter's address
adp = iadapt.get();
return iadapt;
}
/* Needs some global store of parts to work, so maybe not a good idea.
std::shared_ptr<Part> part() const {
return adp.part(); // or find from a UUID
}
*/
/**
* Returns the UUID of the part, the component that provides the
* instrument. If the UUID has not been provided, a nil UUID (all zeros)
* will be returned.
*/
const boost::uuids::uuid &partId() const noexcept {
return pid;
}
// status -- see Instance.hpp from old duds
/* incomplete
status() const {
return adp->status();
}
changeStatus() const {
if (adp) {
adp->changeStatus();
} else {
throw 1;
}
}
*/
/**
* Returns the units of the samples provided by this instrument.
* The units should be set by the driver through the adapter. Any units
* other than unitless should have a non-zero numeric value. Other types
* and more complex values must be reported as unitless.
*/
duds::data::Unit unit() const noexcept {
return u;
}
// measured property? relative humidity won't show up in units
/**
* Returns the most current measurement.
* @note This function returns a copy of the std::shared_ptr managing the
* measurement object. This is required to avoid further
* synchronization while working properly should another thread
* update the current measurement. Hold and use a local copy of
* the std::shared_ptr for the best performance.
* @warning Successive calls to this function may return a std::shared_ptr
* with a different measurement object. If the measurement
* object needs to be accessed multiple times without changing,
* a copy of the shared pointer must be retained and used to
* access the measurement.
*/
std::shared_ptr<const Measurement> currentMeasurement() const noexcept {
return currmeas;
}
//currentSample() const; // ???
// future?: optional data on accuracy, precision, resolution
// get & set status
//status() const;
//changeStatus(); // requests change of status
};
/**
* An easy and shorter way to use GenericInstrument with the best generally
* applicable template arguments.
* @bug Doxygen is not automatically making links to typedefs of templates.
*/
typedef GenericInstrument<
duds::data::GenericValue,
double,
duds::time::interstellar::NanoTime,
float
> Instrument;
typedef std::shared_ptr<Instrument> InstrumentSptr;
typedef std::weak_ptr<Instrument> InstrumentWptr;
} }
#endif // #ifndef INSTRUMENT_HPP
|
[STATEMENT]
lemma fresh_fun_simp_ImpR:
assumes a: "a'\<sharp>P" "a'\<sharp>M" "a'\<sharp>b"
shows "fresh_fun (\<lambda>a'. Cut <a'>.(ImpR (y).<b>.M a') (x).P) = Cut <a'>.(ImpR (y).<b>.M a') (x).P"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. fresh_fun (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P) = Cut <a'>.ImpR y.<b>.M a' x.P
[PROOF STEP]
using a
[PROOF STATE]
proof (prove)
using this:
a' \<sharp> P
a' \<sharp> M
a' \<sharp> b
goal (1 subgoal):
1. fresh_fun (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P) = Cut <a'>.ImpR y.<b>.M a' x.P
[PROOF STEP]
apply -
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> fresh_fun (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P) = Cut <a'>.ImpR y.<b>.M a' x.P
[PROOF STEP]
apply(rule fresh_fun_app)
[PROOF STATE]
proof (prove)
goal (5 subgoals):
1. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> pt TYPE(trm) TYPE(coname)
2. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> at TYPE(coname)
3. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> finite (supp (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P))
4. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> \<exists>a. a \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P, Cut <a>.ImpR y.<b>.M a x.P)
5. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> a' \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P)
[PROOF STEP]
apply(rule pt_coname_inst)
[PROOF STATE]
proof (prove)
goal (4 subgoals):
1. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> at TYPE(coname)
2. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> finite (supp (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P))
3. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> \<exists>a. a \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P, Cut <a>.ImpR y.<b>.M a x.P)
4. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> a' \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P)
[PROOF STEP]
apply(rule at_coname_inst)
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> finite (supp (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P))
2. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> \<exists>a. a \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P, Cut <a>.ImpR y.<b>.M a x.P)
3. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> a' \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P)
[PROOF STEP]
apply(finite_guess)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> \<exists>a. a \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P, Cut <a>.ImpR y.<b>.M a x.P)
2. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> a' \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P)
[PROOF STEP]
apply(subgoal_tac "\<exists>n::coname. n\<sharp>(x,P,y,b,M)")
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b; \<exists>n. n \<sharp> (x, P, y, b, M)\<rbrakk> \<Longrightarrow> \<exists>a. a \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P, Cut <a>.ImpR y.<b>.M a x.P)
2. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> \<exists>n. n \<sharp> (x, P, y, b, M)
3. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> a' \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P)
[PROOF STEP]
apply(erule exE)
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<And>n. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b; n \<sharp> (x, P, y, b, M)\<rbrakk> \<Longrightarrow> \<exists>a. a \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P, Cut <a>.ImpR y.<b>.M a x.P)
2. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> \<exists>n. n \<sharp> (x, P, y, b, M)
3. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> a' \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P)
[PROOF STEP]
apply(rule_tac x="n" in exI)
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<And>n. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b; n \<sharp> (x, P, y, b, M)\<rbrakk> \<Longrightarrow> n \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P, Cut <n>.ImpR y.<b>.M n x.P)
2. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> \<exists>n. n \<sharp> (x, P, y, b, M)
3. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> a' \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P)
[PROOF STEP]
apply(simp add: fresh_prod abs_fresh)
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<And>n. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b; n \<sharp> x \<and> n \<sharp> P \<and> n \<sharp> y \<and> n \<sharp> b \<and> n \<sharp> M\<rbrakk> \<Longrightarrow> n \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P)
2. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> \<exists>n. n \<sharp> (x, P, y, b, M)
3. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> a' \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P)
[PROOF STEP]
apply(fresh_guess)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> \<exists>n. n \<sharp> (x, P, y, b, M)
2. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> a' \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P)
[PROOF STEP]
apply(rule exists_fresh')
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> finite (supp (x, P, y, b, M))
2. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> a' \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P)
[PROOF STEP]
apply(simp add: fin_supp)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>a' \<sharp> P; a' \<sharp> M; a' \<sharp> b\<rbrakk> \<Longrightarrow> a' \<sharp> (\<lambda>a'. Cut <a'>.ImpR y.<b>.M a' x.P)
[PROOF STEP]
apply(fresh_guess)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
#include <iostream>
#include <opencv2/opencv.hpp>
#include <Eigen/Core>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
int main(int argc, char **argv)
{
double ar = 1.0, br = 2.0, cr = 1.0;
double ae = 2.0, be = -1.0, ce = 5.0;
int N = 100;
double w_sigma = 1.0;
double inv_sigma = 1.0 / w_sigma;
cv::RNG rng; // Opencv随机数产生器
// 生成数据
vector<double> x_data, y_data;
for (int i=0; i<N; i++)
{
double x = i / 100.0;
x_data.push_back(x);
double y = exp(ar*x*x + br*x + cr) + rng.gaussian(w_sigma*w_sigma);
y_data.push_back(y);
}
// 开始Gauss-Newton迭代
int iter;
double cost=0, lastCost = 0;
chrono::steady_clock::time_point t1 = chrono::steady_clock::now();
while(1)
{
Matrix3d H = Matrix3d::Zero();
Vector3d b = Vector3d::Zero();
cost = 0;
for (int i=0; i<N; i++)
{
double x = x_data[i];
double y = y_data[i];
double error = y - exp(ae*x*x + be*x + ce);
double de_da = - x*x*exp(ae*x*x + be*x +ce);
double de_db = - x*exp(ae*x*x + be*x +ce);
double de_dc = - exp(ae*x*x + be*x +ce);
Vector3d J;
J[0] = de_da;
J[1] = de_db;
J[2] = de_dc;
H = H + J * J.transpose();
b = b - J * error;
cost = cost + error*error;
}
// 求解线性方程 Hx=b
Vector3d dx= H.ldlt().solve(b);
if(isnan(dx[0]))
{
cout << "result is nan!" << endl;
break;
}
if (iter > 0 && cost >= lastCost)
{
cout << "cost >= lastCost, break!" << endl;
break;
}
ae += dx[0];
be += dx[1];
ce += dx[2];
cout << "iter = " << iter << ", total cost = " << cost << ", \t\t update = " << dx.transpose()
<< ", \t\t estimated paras = " << ae << ", " << be << ", " << ce << endl;
if (fabs(cost - lastCost) < 1e-8)
{
break;
}
lastCost = cost;
iter += 1;
}
chrono::steady_clock::time_point t2 = chrono::steady_clock::now();
chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>> (t2-t1);
cout << endl << "Estimated paras a, b, c = " << ae << ", " << be << ", " << ce << endl;
cout << endl << "Solve time cost = " << time_used.count() << "s" << endl;
return 0;
} |
\documentclass[letterpaper,11pt]{article}
\usepackage{afterpage}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{bm}
\usepackage[hmargin=1.25in,vmargin=1in]{geometry}
\usepackage{booktabs}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{lmodern}
\usepackage{microtype}
\usepackage{pdflscape}
\usepackage{subcaption}
\title{Coursework 7: STAT 570}
\author{Philip Pham}
\date{\today}
\begin{document}
\maketitle
\begin{enumerate}
\item Create a binary variable $Z_i$, with $Z_i = 0$ corresponding to
$Y_i \in \{0,1\}$ and $Z_i = 1$ corresponding to $Y_i \in \{2,3\}$. Let
$q\left(x_i\right) = \mathbb{P}(Z_i = 1 \mid x_i)$, with
$\mathbf{x}_i = \begin{pmatrix} 1 & x_{1i} & x_{2i}
\end{pmatrix}^\intercal$, represent the probability of mental impairment being
\emph{Moderate} or \emph{Impaired}, given covariates $\mathbf{x}_i$,
$i = 1,\ldots,n = 40$. Provide a single plot that shows the association
between $q\left(x_i\right)$ and $x_{1i}$ and $x_{2i}$, on a response scale
you feel is appropriate. Comment on the plot.
\begin{figure}[h]
\centering
\includegraphics{p1_descriptive.pdf}
\caption{Orange denotes $Z_i = 1$ and blue denotes $Z_i = 0$.}
\label{fig:p1_descriptive}
\end{figure}
\begin{description}
\item[Solution:] See Figure \ref{fig:p1_descriptive}. Conditioned on SES,
those that are impaired ($Z_i = 1$) have a greater number of life events on
average.
\end{description}
\item Suppose $Z_i \mid q_i \sim \operatorname{Binomial}\left(1, q_i\right)$
independently for $i = 1,\ldots, n = 40$, where $q_i =
q\left(x_i\right)$. Consider the logistic regression model,
\begin{equation}
q\left(x_i\right) = \log\left(
\frac{q\left(\mathbf{x}_i\right)}{1 - q\left(\mathbf{x}_i\right)}
\right)
=
\mathbf{x}_i^\intercal \bm{\gamma}
= \gamma_0 + \gamma_1 x_{1i} + \gamma_2 x_{2i},
\label{eqn:p2_model}
\end{equation}
where $\bm{\gamma} = \begin{pmatrix}\gamma_0 & \gamma_1 & \gamma_2
\end{pmatrix}^\intercal$. Write down the log-likelihood
$l\left(\bm{\gamma}\right)$ for the sample $z_i$, $i = 1,\ldots, n$.
\begin{description}
\item[Solution:] Solving for $q\left(\mathbf{x}_i\right)$ in Equation
\ref{eqn:p2_model}, we find
\begin{equation}
q\left(\mathbf{x}_i\right)
= \frac{\exp\left(\mathbf{x}_i^\intercal \bm{\gamma}\right)}
{1 + \exp\left(\mathbf{x}_i^\intercal \bm{\gamma}\right)}
= \frac{1}
{1 + \exp\left(-\mathbf{x}_i^\intercal \bm{\gamma}\right)}.
\label{eqn:p2_qi}
\end{equation}
The likelihood function is
$L\left( \bm{\gamma} \right) = \prod_{i=1}^n
\left(q\left(\mathbf{x}_i\right)\right)^{z_i} \left(1 -
q\left(\mathbf{x}_i\right)\right)^{1 - z_i}$, so the log-likelihood
function becomes
\begin{align}
l\left(\bm{\gamma}\right)
&= \log L\left( \bm{\gamma} \right)
= \sum_{i=1}^n \left(
z_i \log q\left(\mathbf{x}_i\right)
+
\left(1 - z_i \right) \log\left(1 - q\left(\mathbf{x}_i\right)\right)
\right)
\label{eqn:p2_log_likelihood}\\
&= \sum_{i=1}^n\left(
z_i\log\frac{q\left(\mathbf{x}_i\right)}{1 -q\left(\mathbf{x}_i\right)}
+ \log\left(1 -q\left(\mathbf{x}_i\right)\right)
\right) \nonumber\\
&= \sum_{i=1}^n
\left(
z_i\mathbf{x}_i^\intercal\bm{\gamma} +
\log\frac{1}{1 + \exp\left(\mathbf{x}_i^\intercal\bm{\gamma}\right)}
\right)
= \sum_{i=1}^n
-\log\left(
1 + \exp\left(\left(1 - 2z_i\right)\mathbf{x}_i^\intercal\bm{\gamma}\right)
\right). \nonumber
\end{align}
\end{description}
\item Fit the model described in the previous part, and give confidence
intervals for the odds ratios.
Carefully interpret these odds ratios.
\begin{table}[!h]
\centering
\input{p3_gamma_hat.tex}
\caption{Estimates and confidence intervals for $\hat{\bm\gamma}$ using
maximum likelihood estimation.}
\label{tab:p3_gamma_hat}
\end{table}
\begin{description}
\item[Solution:] Taking the derivative of Equation
\ref{eqn:p2_log_likelihood}, we have the score function:
\begin{align}
S\left(\bm\gamma\right)
= \nabla^\intercal l\left(\bm\gamma\right)
&= \sum_{i=1}^n \frac{2z_i - 1}{1 + \exp\left(
\left(1 - 2z_i\right)\mathbf{x}_i^\intercal\bm{\gamma}
\right)}\exp\left(
\left(1 - 2z_i\right)\mathbf{x}_i^\intercal\bm{\gamma}
\right)\mathbf{x}_i.
\nonumber\\
&= \sum_{i=1}^n \frac{2z_i - 1}{1 + \exp\left(
\left(2z_i - 1\right)\mathbf{x}_i^\intercal\bm{\gamma}
\right)}\mathbf{x}_i
= X^\intercal\left(
\mathbf{z} - \mathbf{q}\left(X\right)
\right),
\label{eqn:p3_score_function}
\end{align}
where
$\mathbf{z} = \begin{pmatrix}z_1 & z_2 & \cdots & z_n\end{pmatrix}^\intercal$ and
$\mathbf{q}\left(X\right) = \begin{pmatrix}q_1 & q_2 &
\cdots & q_n\end{pmatrix}^\intercal$.
From Equation \ref{eqn:p3_score_function}, we have the Fisher information
matrix:
\begin{align}
I_n\left(\bm\gamma\right)
&= \operatorname{var}\left(S\left(\bm\gamma\right) \mid \bm\gamma\right)
= \mathbb{E}\left[
S\left(\bm\gamma\right)
S\left(\bm\gamma\right)^\intercal
\mid \bm\gamma
\right] \nonumber\\
&= \mathbb{E}\left[
X^\intercal\left(
\mathbf{z} - \mathbf{q}\left(X\right)
\right)
\left(
\mathbf{z} - \mathbf{q}\left(X\right)
\right)^\intercal
X \mid \bm\gamma
\right] \nonumber \\
&= X^\intercal\mathbb{E}\left[
\left(
\mathbf{z} - \mathbf{q}\left(X\right)
\right)
\left(
\mathbf{z} - \mathbf{q}\left(X\right)
\right)^\intercal
\mid \bm\gamma
\right]X \nonumber\\
&= \sum_{i=1}^n
q\left(\mathbf{x}_i\right)
\left(1 - q\left(\mathbf{x}_i\right)\right)
\mathbf{x}_i\mathbf{x}_i^\intercal
=
\sum_{i=1}^n
\frac{1}{2 + \exp\left(
-\mathbf{x}_i^\intercal \bm\gamma
\right) + \exp\left(
\mathbf{x}_i^\intercal \bm\gamma
\right)}
\mathbf{x}_i\mathbf{x}_i^\intercal
,
\label{eqn:p3_fisher_information}
\end{align}
where we have used independence of the observations and variance of the
binomial distribution to get the last line.
We solve Equation \ref{eqn:p3_score_function},
$S\left(\hat{\bm{\gamma}}\right) = \mathbf{0}$, to get an estimate for
$\bm\gamma$. Using Equation \ref{eqn:p3_fisher_information}, we have that
\begin{equation}
\hat{\bm\gamma}
\xrightarrow{\mathcal{D}}
\mathcal{N}\left(
\gamma,
I_n^{-1}\left(\hat{\bm\gamma}\right)
\right),
\label{eqn:p3_gamma_hat_dist}
\end{equation}
that is, $\hat{\bm\gamma}$ is asymptotically normal.
Using Equation \ref{eqn:p3_gamma_hat_dist}, we obtain the estimates and
intervals in Table \ref{tab:p3_gamma_hat}.
The predicted log odds ratio given some $\mathbf{x}_i$ is
\begin{equation}
\hat\theta_i = \mathbf{x}_i^\intercal\hat{\bm\gamma},
\label{eqn:p3_prediction}
\end{equation}
which will have variance
\begin{equation}
\operatorname{var}\left(\hat\theta_i\right)
= \mathbf{x}_i^\intercal\operatorname{var}\left(\hat{\bm\gamma}\right)
\mathbf{x}_i
\approx \mathbf{x}_i^\intercal I_n^{-1}\left(\hat{\bm\gamma}\right)
\mathbf{x}_i,
\label{eqn:p3_prediction_variance}
\end{equation}
using Equation \ref{eqn:p3_gamma_hat_dist}.
From Equation \ref{eqn:p3_prediction_variance}, we can compute confidence
intervals for the log odds ratio and exponentiate to get confidence
intervals for the odds ratio since $\log$ is a monotonic
transformation. Doing so results in the estimates in Table
\ref{tab:p3_odds_ratios}.
The odds ratio is how much more likely one is to have \emph{Moderate} or
\emph{Impaired} mental impairment. Exponentiating Equation
\ref{eqn:p3_prediction}, we have
\begin{equation}
\exp\left(\theta_i\right) =
\exp\left(\gamma_0\right)
\exp\left(\gamma_1x_{1i}\right)
\exp\left(\gamma_2x_{2i}\right).
\end{equation}
$\exp\left(\gamma_0\right)$ is the expected odds ratio for a subject with
$0$ SES and no life events. $\exp\left(\gamma_1\right)$ is the expected odds
ratio between a subject with SES 1 and SES 0.
$\exp\left(\hat{\gamma}_1\right) < 1$, so SES is associated with less mental
impairment. $\exp\left(\gamma_2\right)$ is the expected odds ratio for a
subject with an additional life event.
$\exp\left(\hat{\gamma}_2\right) > 1$, so life events are associated with
more severe mental impairment.
\end{description}
\begin{table}
\scriptsize
\centering
\input{p3_odds_ratios.tex}
\caption{Estimates for the odds ratios given $\mathbf{x}_i$ with
$\hat{\bm\gamma}$.}
\label{tab:p3_odds_ratios}
\end{table}
\item We will now consider analyses that do not coarsen the data. We begin by
defining notation in a generic situation. Suppose the random variable, $Y_i$,
for individual $i$, $i = 1,\ldots,n$, can take values $0,1,2,\ldots,J-1$ (so
that that there are $J$ levels). Assume that for individual $i$, the data
follow a multinomial distribution,
$Y_i \mid p_i \sim \operatorname{Multinomial}\left(1,\mathbf{p}_i\right)$
independently, where $p_i = \begin{pmatrix}p_{i0} & \cdots & p_{i,J-1}
\end{pmatrix}^\intercal$, and $p_{ij}$ represents the probability
\begin{equation}
p_{ij} = \mathbb{P}\left(Y_i = j \mid \mathbf{x}_i\right),
~\text{for}~j=0,1,\ldots,J-1,
\label{eqn:p4_pij}
\end{equation}
where $\mathbf{x}_i = \begin{pmatrix} 1 & x_{1i} & x_{2i} & \cdots & x_{ki}
\end{pmatrix}^\intercal$ for $i = 1,\ldots,n$.
Suppose the response categories re nominal, that is, have no ordering. In this
case, we may consider the \emph{generalized logit model}:
\begin{equation}
p_{ij} = \frac{\exp\left(\mathbf{x}_i^\intercal\bm\beta_j\right)}{
\sum_{l=0}^{J-1}\exp\left(\mathbf{x}_i^\intercal\bm\beta_l\right)
},~\text{for}~j=0,\ldots,J-1,
\end{equation}
where
$\bm\beta_j = \begin{pmatrix} \beta_{j0} & \beta_{j1} & \cdots & \beta_{jk}
\end{pmatrix}^\intercal$.
Identifiability may be enforced by taking $\bm\beta_{J-1} = \mathbf{0}$, to
give
\begin{equation}
\log\frac{p_{ij}}{p_{i,J-1}} = \mathbf{x}_i^\intercal\bm\beta_j,
~\text{for}~j=0,\ldots,J-2,
\label{eqn:p4_log_odds_ratio}
\end{equation}
with $p_{i,J-1} = 1 - \sum_{j=0}^{J-2} p_{ij}$. Consider the case of $j = 3$
levels and a single binary covariate $x$ so that that
$\mathbf{x}_i = \begin{pmatrix} 1 & x_i \end{pmatrix}^\intercal$. Give a
$3 \times 2$ table containing the probabilities of
$\mathbb{P}\left(Y = j \mid x\right)$ in terms the $\beta_{jx}$ coefficients
for rows $j = 0,1,2$ and columns $x=0,1$. Hence, give interpretations of
$\exp\left(\beta_{jx}\right)$ for $j = 0,1,2$ and $x = 0,1$.
Is the generalized logit model suitable for ordinal data?
\begin{table}[h]
\small
\centering
\begin{tabular}{lcc}
\toprule
$j$ & $x = 0$ & $x = 1$ \\
\midrule
$0$ & $\displaystyle\frac{\exp\left(\beta_{00}\right)}{1 + \exp\left(\beta_{00}\right) + \exp\left(\beta_{10}\right)}$ & $\displaystyle\frac{\exp\left(\beta_{00} + \beta_{01}\right)}{1 + \exp\left(\beta_{00} + \beta_{01}\right) + \exp\left(\beta_{10} + \beta_{11}\right)}$ \\
$1$ & $\displaystyle\frac{\exp\left(\beta_{10}\right)}{1 + \exp\left(\beta_{00}\right) + \exp\left(\beta_{10}\right)}$ & $\displaystyle\frac{\exp\left(\beta_{10} + \beta_{11}\right)}{1 + \exp\left(\beta_{00} + \beta_{01}\right) + \exp\left(\beta_{10} + \beta_{11}\right)}$ \\
$2$ & $\displaystyle\frac{1}{1 + \exp\left(\beta_{00}\right) + \exp\left(\beta_{10}\right)}$ & $\displaystyle\frac{1}{1 + \exp\left(\beta_{00} + \beta_{01}\right) + \exp\left(\beta_{10} + \beta_{11}\right)}$ \\
\bottomrule
\end{tabular}
\caption{Multinomial probabilities for various $j$ and $x$.}
\label{tab:p4_multinomial_probability}
\end{table}
\begin{description}
\item[Solution:] See Table \ref{tab:p4_multinomial_probability} for the table
of probabilities.
Equation \ref{eqn:p4_log_odds_ratio} provides a way to interpret the
$\beta_{jx}$. Let $p_{0j}$ and $p_{1j}$ denote the probabilities when
$x = 0$ and $x = 1$, respectively. In this case, we have the odds ratios:
\begin{align*}
\frac{p_{0j}}{p_{02}} &= \exp\left(\beta_{j0}\right) \\
\frac{p_{1j}}{p_{12}} &= \exp\left(\beta_{j0}\right)\exp\left(\beta_{j1}\right).
\end{align*}
Thus, the coefficients $\beta_{j0}$ are the expected log odds ratio for
level $j$ relative to level $J - 1 = 2$ when the $x = 0$. $\beta_{j1}$ is
the expected increase in this log odds ratio when $x = 1$. In this sense, we
can consider the level $J - 1$ the default case, and the
$\exp\left(\beta_{jx}\right)$ express how much more likely we are to
observe level $j$.
This model isn't suitable for ordinal data, for it is agnostic to the order
of the data. From the above interpretation, it's more similar to fitting
$J - 1$ individual logisitic regression models. For an ordinal model, we
might want behavior like the most probable level varies monotonically with
some covariate. There's no way to model such behavior with the
\emph{generalized logit model} since each class has separate paramters.
\end{description}
\item Let
\begin{equation}
\pi_{ij} = \mathbb{P}\left(Y_i \leq j \mid \mathbf{x}_i\right),
\label{eqn:p5_pi_ij}
\end{equation}
for $j=0,\ldots,J-2$ and with $\mathbf{x}_i = \begin{pmatrix}
1 & x_{1i} & x_{2i} & \cdots & x_{ki}
\end{pmatrix}^\intercal$. Consider the proportional odds model
\begin{equation}
\log\frac{\pi_{ij}}{1 - \pi_{ij}} = \alpha_j - \mathbf{x}_i^\intercal\bm\beta,
\end{equation}
for $j = 0,1,J - 2$, and where $\bm\beta = \begin{pmatrix}
\beta_0 & \beta_1 & \cdots & \beta_k
\end{pmatrix}^\intercal$. Write down, in as simplified a form as possible, the
log-likelihood $l\left(\bm\alpha,\bm\beta\right)$ where
$\bm\alpha = \begin{pmatrix}
\alpha_0 & \alpha_1 & \cdots & \alpha_{J - 2}
\end{pmatrix}^\intercal$, for the sample $y_i$, $i = 1,\ldots,n$.
\begin{description}
\item[Solution:] Let $\alpha_{J-1} = \infty$ and
$\alpha_{-1} = -\infty$. In this case, we have that
\begin{align}
p_{ij}
&= \pi_{i,j} - \pi_{i,j-1}
= \frac{1}{1 + \exp\left(\mathbf{x}_i^\intercal\bm\beta - \alpha_j\right)} -
\frac{1}{1 + \exp\left(\mathbf{x}_i^\intercal\bm\beta - \alpha_{j-1}\right)}
\label{eqn:p5_pij}\\
&= \begin{cases}
\frac{
\exp\left(\alpha_{j}\right) - \exp\left(\alpha_{j - 1}\right)
}{
\exp\left(-\mathbf{x}_i^\intercal\bm\beta + \alpha_{j-1} + \alpha_j\right) +
\exp\left(\alpha_{j-1}\right) + \exp\left(\alpha_{j}\right) +
\exp\left(\mathbf{x}_i^\intercal\bm\beta\right)
}, &j=0,1,\ldots,J-2; \\
\frac{1}{1 + \exp\left(\alpha_{J-2} - \mathbf{x}_i^\intercal\bm\beta\right)}, &j=J-1.
\end{cases}\nonumber
\end{align}
Note that we must have
$\alpha_0 \leq \alpha_1 \leq \cdots \leq \alpha_{J-2}$ for each class to
have nonnegative probability.
Then, likelihood function is
\begin{equation}
L\left(\bm\alpha, \bm\beta\right)
= \prod_{i=1}^n \prod_{j=0}^{J-1} p_{ij}^{\mathbf{1}_{\{j\}}\left(y_i\right)},
\label{eqn:p5_likelihood}
\end{equation}
where
\begin{equation}
\mathbf{1}_A\left(x\right) = \begin{cases}
1,&x \in A; \\
0,&\text{otherwise}.
\end{cases}
\label{eqn:p5_indicator}
\end{equation}
Taking the $\log$ of Equation \ref{eqn:p5_likelihood}, we have the
log-likelihood function
\begin{equation}
l\left(\bm\alpha,\bm\beta\right)
= \sum_{i=1}^n\sum_{j=0}^{J-1}\mathbf{1}_{\{j\}}\left(y_i\right) \log p_{ij}.
\end{equation}
\end{description}
\item For the data in Table \ref{tab:p1_data}, provide a single plot that shows
the association between $\mathbf{p}\left(\mathbf{x}_i\right)$ and $x_{1i}$ and
$x_{2i}$, on a scale you feel is appropriate.
\label{part:p6}
\begin{figure}
\centering
\includegraphics{p6_descriptive.pdf}
\caption{Boxplots showing the relationship between mental impairment, SES
and life events.}
\label{fig:p6_descriptive}
\end{figure}
\begin{description}
\item[Solution:] See Figure \ref{fig:p6_descriptive}. Conditioned on SES, the
expected probability of having a more severe form of mental impairment
increases with life events.
The effect of SES on observed mental impairment is more ambiguous. When
looking at the \emph{Well} and \emph{Moderate} levels, it seems that SES
may have a slight protective effect against mental impairment, for we
observe many subjects with a high number of life events but no mental
impairment or less severe impairment. There doesn't seem to be much evidence
of this phenomenon in the \emph{Mild} level. Ultimately, there's probably
not enough data to come to any conclusion about SES.
\end{description}
\item \label{part:p7} Fit the proportional odds models:
\begin{align}
\log\frac{\pi_{ij}}{1 - \pi_{ij}}
&= \alpha_j^{(0)}
\label{eqn:p7_model_1} \\
\log\frac{\pi_{ij}}{1 - \pi_{ij}}
&= \alpha_j^{(1)} - x_{1i}\beta_1^{(1)}
\label{eqn:p7_model_2} \\
\log\frac{\pi_{ij}}{1 - \pi_{ij}}
&= \alpha_j^{(2)} - x_{2i}\beta_2^{(2)}
\label{eqn:p7_model_3} \\
\log\frac{\pi_{ij}}{1 - \pi_{ij}}
&= \alpha_j^{(12)} - x_{1i}\beta_1^{(12)} - x_{2i}\beta_2^{(12)}.
\label{eqn:p7_model_4}
\end{align}
Compare models using likelihood ratio statistics, and summarize the
association between mental impairment, SES and life events, using your favored
model.
\input{p7_model_summary.tex}
\begin{description}
\item[Solution:] The results of fitting the models can be seen in Table
\ref{tab:p7_model_summary}. The coefficient estimates agree with what we saw
in Figure \ref{fig:p6_descriptive} and the discussion in the solution of
Part \ref{part:p6}: positive $\beta_2$ indicate that observed severity of
mental impairment increases with life events, and negative $\beta_1$
indicate that SES lessens the observed severity of mental impairment.
Wilks' theorem tells us how to compute a test statistic for a log-likelihood
ratio test:
\begin{equation}
D = 2\left(
l\left(\bm\alpha^{(p)}, \bm\beta^{(p)}\right) -
l\left(\bm\alpha^{(q)}, \bm\beta^{(q)}\right)
\right) \xrightarrow{\mathcal{D}} \chi^2_{p - q},
\label{eqn:p7_deviance}
\end{equation}
where $p > q$ and $\bm\beta^{(p)}$ and $\bm\beta^{(q)}$ each have
dimensionality $p$ and $q$, respectively. That is, the deviance converges
asymptotically to a chi-squared distribution with $p-q$ degrees of freedom.
The test statistic in Equation \ref{eqn:p7_deviance} can be computed for
various pairs of models with the last column of Table
\ref{tab:p7_model_summary} when the two models are nested.
Results of the tests on pairs of nested models can be seen in Table
\ref{tab:p7_likelihood_ratio_test}. Since we are testing multiple
hypotheses, we might consider apply the Bonferroni correction and rejecting
at significance level $\alpha/m$, where $m$ is the number of tests and
$\alpha$ is the desired familywise error rate (FWER). In this case, for
$\alpha = 0.05$, we would reject the null hypothesis in tests with a
$p$-value of less than $0.01$.
\input{p7_likelihood_ratio_test.tex}
From the first test that compares the model in Equation \ref{eqn:p7_model_2}
against the null model in Equation \ref{eqn:p7_model_1}, SES alone does not
improve the fit very much. From the second test that tests the model in
Equation \ref{eqn:p7_model_3} against the null model, we see that life
events improves fit more: the $p$-value of 0.01070 is the on the border of
statistical significance. The improved fit from the model in Equation
\ref{eqn:p7_model_4} that incorporates both SES and life events is found to
be statistically significant when compared against the null model and the
model only containing SES. However, when tested against the model containing
only life events, it doesn't quite meet statistical significance.
Despite the last test not rejecting the model in Equation
\ref{eqn:p7_model_3}, I'd still favor the model in Equation
\ref{eqn:p7_model_4} that includes both SES and life events with the caveat
that an additional experiment should be done. If possible, an additional
experiment should be done with higher power (more subjects) that tests the
null model in Equation \ref{eqn:p7_model_3} against the alternate model in
Equation \ref{eqn:p7_model_4}.
\end{description}
\item Provide a plot of fitted probabilities under the model in Equation
\ref{eqn:p7_model_4}, as a function of $x_1$ and $x_2$.
\begin{figure}[h]
\centering
\caption{Fitted probabilities of mental impairment levels using the model
described in Equation \ref{eqn:p7_model_4}.}
\includegraphics{p8_fitted_probabilities.pdf}
\label{fig:p8_fitted_probabilities}
\end{figure}
\begin{description}
\item[Solution:] See Figure \ref{fig:p8_fitted_probabilities}. As described in
the solution of Part \ref{part:p7}, life events increases the expected
observed level of mental impairment. SES lessens the severity so curves of
the same color are shifted downward.
\end{description}
\end{enumerate}
\clearpage
\section*{Appendix}
\subsection*{Code}
Code for the logistic regression model and boxplots can be found in
\href{http://nbviewer.jupyter.org/github/ppham27/stat570/blob/master/hw7/mental_impairment.ipynb}{\texttt{mental\_impairment.ipynb}}. Code
for the proportional odds models and Figure \ref{fig:p8_fitted_probabilities}
can be found in
\href{http://nbviewer.jupyter.org/github/ppham27/stat570/blob/master/hw7/proportional\_odds.ipynb}{\texttt{proportional\_odds.ipynb}}.
\subsection*{Data}
The raw mental impairment data is in Table \ref{tab:p1_data}.
\begin{table}[h]
\scriptsize
\centering
\input{p1_data.tex}
\caption{Data on mental impairment, socioeconomic status (SES) and life
events, for 40 subjects.}
\label{tab:p1_data}
\end{table}
\end{document}
|
module Lambdapants.Term.Reduction
import Lambdapants.Term
%default total
public export
data Strategy = Normal | Applicative
export
Eq Strategy where
Normal == Normal = True
Applicative == Applicative = True
_ == _ = False
export
Show Strategy where
show Normal = "Normal"
show Applicative = "Applicative"
rename : String -> String -> Term -> Term
rename fr to = translate where
translate (Var v) = Var (if v == fr then to else v)
translate (App e1 e2) = App (translate e1) (translate e2)
translate (Lam x e) = Lam (if x == fr then to else x) (translate e)
nextSuffix : List String -> Nat
nextSuffix xs = case last' (sort (map trailingDigits xs)) of
Nothing => 0
Just x => succ (cast x)
where
trailingDigits : String -> String
trailingDigits = reverse . pack . takeWhile isDigit . unpack . reverse
export
substitute : String -> Term -> Term -> Term
substitute var expr = translate . sanitized where
vars : List String
vars = freeVars expr
suffix : String
suffix = "_" ++ show (nextSuffix vars)
sanitized : Term -> Term
sanitized (Var v) = Var v
sanitized (App e1 e2) = App (sanitized e1) (sanitized e2)
sanitized (Lam x e) = if elem x vars
then let x' = x ++ suffix in
Lam x' (rename x x' (sanitized e))
else Lam x (sanitized e)
translate : Term -> Term
translate (Var v) = if var == v then expr else Var v
translate (App e1 e2) = App (translate e1) (translate e2)
translate (Lam x e) = Lam x (if x == var then e else translate e)
export
normal : Term -> Bool
normal (App (Lam _ _) _) = False
normal (App e1 e2) = normal e1 && normal e2
normal (Lam _ e) = normal e
normal _ = True
export
whnf : Term -> Bool
whnf (App e1 _) = case e1 of
Lam _ _ => False
otherwise => whnf e1
whnf _ = True
export
cbn : Term -> Term
cbn (Var x) = Var x
cbn (Lam x e) = Lam x e
cbn (App (Lam x e) e2) = substitute x e2 e
cbn (App e1 e2) = App (cbn e1) e2
export
nor : Term -> Term
nor (Var x) = Var x
nor (Lam x e) = Lam x (nor e)
nor (App (Lam x e) e2) = substitute x e2 e
nor (App e1 e2) = if normal e1 then App e1 (nor e2) else App (nor e1) e2
export
aor : Term -> Term
aor (Var x) = Var x
aor (Lam x e) = Lam x (aor e)
aor (App e1 e2) with (normal e2)
| False = App e1 (aor e2)
| True = case e1 of
Lam x e => substitute x e2 e
otherwise => App (aor e1) e2
export
evaluate : Strategy -> Term -> Term
evaluate Normal = nor
evaluate Applicative = aor
export
stream : Strategy -> Term -> Stream Term
stream strategy = iterate (evaluate strategy)
|
#ifndef BOOST_CONTRACT_OLD_HPP_
#define BOOST_CONTRACT_OLD_HPP_
// Copyright (C) 2008-2018 Lorenzo Caminiti
// Distributed under the Boost Software License, Version 1.0 (see accompanying
// file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
// See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html
/** @file
Handle old values.
*/
#include <boost/contract/core/config.hpp>
#include <boost/contract/core/virtual.hpp>
#ifndef BOOST_CONTRACT_ALL_DISABLE_NO_ASSERTION
#include <boost/contract/detail/checking.hpp>
#endif
#include <boost/contract/detail/debug.hpp>
#include <boost/contract/detail/declspec.hpp>
#include <boost/contract/detail/operator_safe_bool.hpp>
#include <boost/make_shared.hpp>
#include <boost/preprocessor/config/config.hpp>
#include <boost/preprocessor/control/expr_iif.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_copy_constructible.hpp>
#include <boost/utility/enable_if.hpp>
#include <queue>
#if !BOOST_PP_VARIADICS
#define BOOST_CONTRACT_OLDOF \
BOOST_CONTRACT_ERROR_macro_OLDOF_requires_variadic_macros_otherwise_manually_program_old_values
#else // variadics
#include <boost/config.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/facilities/empty.hpp>
#include <boost/preprocessor/facilities/overload.hpp>
/* PRIVATE */
/** @cond */
#ifdef BOOST_NO_CXX11_AUTO_DECLARATIONS
#define BOOST_CONTRACT_OLDOF_AUTO_TYPEOF_(value) /* nothing */
#else
#include <boost/typeof/typeof.hpp>
// Explicitly force old_ptr<...> conversion to allow for C++11 auto decl.
#define BOOST_CONTRACT_OLDOF_AUTO_TYPEOF_(value) \
boost::contract::old_ptr<BOOST_TYPEOF(value)>
#endif
#define BOOST_CONTRACT_ERROR_macro_OLDOF_has_invalid_number_of_arguments_2( \
v, value) \
BOOST_CONTRACT_OLDOF_AUTO_TYPEOF_(value) \
(boost::contract::make_old(v, boost::contract::copy_old(v) \
? (value) \
: boost::contract::null_old()))
#define BOOST_CONTRACT_ERROR_macro_OLDOF_has_invalid_number_of_arguments_1( \
value) \
BOOST_CONTRACT_OLDOF_AUTO_TYPEOF_(value) \
(boost::contract::make_old( \
boost::contract::copy_old() ? (value) : boost::contract::null_old()))
/** @endcond */
/* PUBLIC */
// NOTE: Leave this #defined the same regardless of ..._NO_OLDS.
/**
Macro typically used to copy an old value expression and assign it to an old
value pointer.
The expression expanded by this macro should be assigned to an old value
pointer of type @RefClass{boost::contract::old_ptr} or
@RefClass{boost::contract::old_ptr_if_copyable}.
This is an overloaded variadic macro and it can be used in the following
different ways.
1\. From within virtual public functions and public functions overrides:
@code
BOOST_CONTRACT_OLDOF(v, old_expr)
@endcode
2\. From all other operations:
@code
BOOST_CONTRACT_OLDOF(old_expr)
@endcode
Where:
@arg <c><b>v</b></c> is the extra parameter of type
@RefClass{boost::contract::virtual_}<c>*</c> and default value @c 0
from the enclosing virtual public function or public function
overrides declaring the contract.
@arg <c><b>old_expr</b></c> is the expression to be evaluated and copied to
the old value pointer.
(This is not a variadic macro parameter so any comma it might contain
must be protected by round parenthesis,
<c>BOOST_CONTRACT_OLDOF(v, (old_expr))</c> will always work.)
On compilers that do not support variadic macros, programmers can manually copy
old value expressions without using this macro (see
@RefSect{extras.no_macros__and_no_variadic_macros_, No Macros}).
@see @RefSect{tutorial.old_values, Old Values}
*/
#define BOOST_CONTRACT_OLDOF(...) \
BOOST_PP_CAT(/* CAT(..., EMTPY()) required on MSVC */ \
BOOST_PP_OVERLOAD( \
BOOST_CONTRACT_ERROR_macro_OLDOF_has_invalid_number_of_arguments_, \
__VA_ARGS__)(__VA_ARGS__), \
BOOST_PP_EMPTY())
#endif // variadics
/* CODE */
namespace boost
{
namespace contract
{
/**
Trait to check if an old value type can be copied or not.
By default, this unary boolean meta-function is equivalent to
@c boost::is_copy_constructible<T> but programmers can chose to specialize it
for user-defined types (in general some kind of specialization is needed on
compilers that do not support C++11, see
<a
href="http://www.boost.org/doc/libs/release/libs/type_traits/doc/html/boost_typetraits/reference/is_copy_constructible.html">
<c>boost::is_copy_constructible</c></a>):
@code
class u; // Some user-defined type.
namespace boost { namespace contract {
template<> // Specialization.
struct is_old_value_copyable<u> : boost::false_type {};
} } // namespace
@endcode
In summary, a given old value type @c T is copied only if
@c boost::contract::is_old_value_copyable<T>::value is @c true.
Copyable old value types are always copied using
@c boost::contract::old_value_copy<T>.
Non-copyable old value types generate a compile-time error when
@c boost::contract::old_ptr<T> is dereferenced, but instead leave
@c boost::contract::old_ptr_if_copyable<T> always null (without generating
compile-time errors).
@see @RefSect{extras.old_value_requirements__templates_,
Old Value Requirements}
*/
template <typename T>
struct is_old_value_copyable : boost::is_copy_constructible<T>
{
};
/** @cond */
class old_value;
template <> // Needed because `old_value` incomplete type when trait first used.
struct is_old_value_copyable<old_value> : boost::true_type
{
};
/** @endcond */
/**
Trait to copy an old value.
By default, the implementation of this trait uses @c T's copy constructor to
make one single copy of the specified @p value.
However, programmers can specialize this trait to copy old values using
user-specific operations different from @c T's copy constructor.
The default implementation of this trait is equivalent to:
@code
template<typename T>
class old_value_copy {
public:
explicit old_value_copy(T const& old) :
old_(value) // One single copy of value using T's copy constructor.
{}
T const& old() const { return old_; }
private:
T const old_; // The old value copy.
};
@endcode
This library will instantiate and use this trait only on old value types @c T
that are copyable (i.e., for which
<c>boost::contract::is_old_value_copyable<T>::value</c> is @c true).
@see @RefSect{extras.old_value_requirements__templates_,
Old Value Requirements}
*/
template <typename T> // Used only if is_old_value_copyable<T>.
struct old_value_copy
{
/**
Construct this object by making one single copy of the specified old value.
This is the only operation within this library that actually copies old
values.
This ensures this library makes one and only one copy of old values (if they
actually need to be copied).
@param old The old value to copy.
*/
explicit old_value_copy(T const& old) : old_(old)
{
} // This makes the one single copy of T.
/**
Return a (constant) reference to the old value that was copied.
Contract assertions should not change the state of the program so the old
value copy is returned as @c const (see
@RefSect{contract_programming_overview.constant_correctness,
Constant Correctness}).
*/
T const& old() const
{
return old_;
}
private:
T const old_;
};
template <typename T>
class old_ptr_if_copyable;
/**
Old value pointer that requires the pointed old value type to be copyable.
This is set to point to an actual old value copy using either
@RefMacro{BOOST_CONTRACT_OLDOF} or @RefFunc{boost::contract::make_old} (that is
why this class does not have public non-default constructors):
@code
class u {
public:
virtual void f(..., boost::contract::virtual_* v = 0) {
boost::contract::old_ptr<old_type> old_var =
BOOST_CONTRACT_OLDOF(v, old_expr);
...
}
...
};
@endcode
@see @RefSect{tutorial.old_values, Old Values}
@tparam T Type of the pointed old value.
This type must be copyable (i.e.,
<c>boost::contract::is_old_value_copyable<T>::value</c> is @c true),
otherwise this pointer will always be null and this library will
generate a compile-time error when the pointer is dereferenced.
*/
template <typename T>
class old_ptr
{ /* copyable (as *) */
public:
/** Pointed old value type. */
typedef T element_type;
/** Construct this old value pointer as null. */
old_ptr()
{
}
/**
Dereference this old value pointer.
This will generate a run-time error if this pointer is null and a
compile-time error if the pointed type @c T is not copyable (i.e., if
@c boost::contract::is_old_value_copyable<T>::value is @c false).
@return The pointed old value.
Contract assertions should not change the state of the program so
this member function is @c const and it returns the old value as a
reference to a constant object (see
@RefSect{contract_programming_overview.constant_correctness,
Constant Correctness}).
*/
T const& operator*() const
{
BOOST_STATIC_ASSERT_MSG(
boost::contract::is_old_value_copyable<T>::value,
"old_ptr<T> requires T copyable (see is_old_value_copyable<T>), "
"otherwise use old_ptr_if_copyable<T>");
BOOST_CONTRACT_DETAIL_DEBUG(typed_copy_);
return typed_copy_->old();
}
/**
Structure-dereference this old value pointer.
This will generate a compile-time error if the pointed type @c T is not
copyable (i.e., if @c boost::contract::is_old_value_copyable<T>::value is
@c false).
@return A pointer to the old value (null if this old value pointer is null).
Contract assertions should not change the state of the program so
this member function is @c const and it returns the old value as a
constant pointer to a constant object (see
@RefSect{contract_programming_overview.constant_correctness,
Constant Correctness}).
*/
T const* const operator->() const
{
BOOST_STATIC_ASSERT_MSG(
boost::contract::is_old_value_copyable<T>::value,
"old_ptr<T> requires T copyble (see is_old_value_copyable<T>), "
"otherwise use old_ptr_if_copyable<T>");
if (typed_copy_)
return &typed_copy_->old();
return 0;
}
#ifndef BOOST_CONTRACT_DETAIL_DOXYGEN
BOOST_CONTRACT_DETAIL_OPERATOR_SAFE_BOOL(old_ptr<T>, !!typed_copy_)
#else
/**
Check if this old value pointer is null or not.
(This is implemented using safe-bool emulation on compilers that do not
support C++11 explicit type conversion operators.)
@return True if this pointer is not null, false otherwise.
*/
explicit operator bool() const;
#endif
/** @cond */
private:
#ifndef BOOST_CONTRACT_NO_OLDS
explicit old_ptr(boost::shared_ptr<old_value_copy<T>> old) :
typed_copy_(old)
{
}
#endif
boost::shared_ptr<old_value_copy<T>> typed_copy_;
friend class old_pointer;
friend class old_ptr_if_copyable<T>;
/** @endcond */
};
/**
Old value pointer that does not require the pointed old value type to be
copyable.
This is set to point to an actual old value copy using either
@RefMacro{BOOST_CONTRACT_OLDOF} or @RefFunc{boost::contract::make_old}:
@code
template<typename T> // Type `T` might or not be copyable.
class u {
public:
virtual void f(..., boost::contract::virtual_* v = 0) {
boost::contract::old_ptr_if_copyable<T> old_var =
BOOST_CONTRACT_OLDOF(v, old_expr);
...
if(old_var) ... // Always null for non-copyable types.
...
}
...
};
@endcode
@see @RefSect{extras.old_value_requirements__templates_,
Old Value Requirements}
@tparam T Type of the pointed old value.
If this type is not copyable (i.e.,
<c>boost::contract::is_old_value_copyable<T>::value</c> is @c false),
this pointer will always be null (but this library will not generate a
compile-time error when this pointer is dereferenced).
*/
template <typename T>
class old_ptr_if_copyable
{ /* copyable (as *) */
public:
/** Pointed old value type. */
typedef T element_type;
/** Construct this old value pointer as null. */
old_ptr_if_copyable()
{
}
/**
Construct this old value pointer from an old value pointer that requires
the old value type to be copyable.
This constructor is implicitly called by this library when assigning an
object of this type using @RefMacro{BOOST_CONTRACT_OLDOF} (this constructor
is usually not explicitly called by user code).
@param other Old value pointer that requires the old value type to be
copyable.
*/
/* implicit */ old_ptr_if_copyable(old_ptr<T> const& other) :
typed_copy_(other.typed_copy_)
{
}
/**
Dereference this old value pointer.
This will generate a run-time error if this pointer is null, but no
compile-time error is generated if the pointed type @c T is not copyable
(i.e., if @c boost::contract::is_old_value_copyable<T>::value is @c false).
@return The pointed old value.
Contract assertions should not change the state of the program so
this member function is @c const and it returns the old value as a
reference to a constant object (see
@RefSect{contract_programming_overview.constant_correctness,
Constant Correctness}).
*/
T const& operator*() const
{
BOOST_CONTRACT_DETAIL_DEBUG(typed_copy_);
return typed_copy_->old();
}
/**
Structure-dereference this old value pointer.
This will return null but will not generate a compile-time error if the
pointed type @c T is not copyable (i.e., if
@c boost::contract::is_old_value_copyable<T>::value is @c false).
@return A pointer to the old value (null if this old value pointer is null).
Contract assertions should not change the state of the program so
this member function is @c const and it returns the old value as a
constant pointer to a constant object (see
@RefSect{contract_programming_overview.constant_correctness,
Constant Correctness}).
*/
T const* const operator->() const
{
if (typed_copy_)
return &typed_copy_->old();
return 0;
}
#ifndef BOOST_CONTRACT_DETAIL_DOXYGEN
BOOST_CONTRACT_DETAIL_OPERATOR_SAFE_BOOL(old_ptr_if_copyable<T>,
!!typed_copy_)
#else
/**
Check if this old value pointer is null or not (safe-bool operator).
(This is implemented using safe-bool emulation on compilers that do not
support C++11 explicit type conversion operators.)
@return True if this pointer is not null, false otherwise.
*/
explicit operator bool() const;
#endif
/** @cond */
private:
#ifndef BOOST_CONTRACT_NO_OLDS
explicit old_ptr_if_copyable(boost::shared_ptr<old_value_copy<T>> old) :
typed_copy_(old)
{
}
#endif
boost::shared_ptr<old_value_copy<T>> typed_copy_;
friend class old_pointer;
/** @endcond */
};
/**
Convert user-specified expressions to old values.
This class is often only implicitly used by this library and it does not
explicitly appear in user code.
On older compilers that cannot correctly deduce the
@c boost::contract::is_old_value_copyable trait, programmers can manually
specialize that trait to make sure that only old value types that are copyable
are actually copied.
@see @RefSect{extras.old_value_requirements__templates_,
Old Value Requirements}
*/
class old_value
{ // Copyable (as *).
public:
// Following implicitly called by ternary operator `... ? ... : null_old()`.
/**
Construct this object from the specified old value when the old value type
is copy constructible.
The specified old value is copied (one time only) using
@c boost::contract::old_value_copy, in which case related old value pointer
will not be null (no copy is made if postconditions and exception guarantees
are not being checked, see @RefMacro{BOOST_CONTRACT_NO_OLDS}).
@param old Old value to be copied.
@tparam T Old value type.
*/
template <typename T>
/* implicit */ old_value(
T const& old, typename boost::enable_if<
boost::contract::is_old_value_copyable<T>>::type* = 0)
#ifndef BOOST_CONTRACT_NO_OLDS
:
untyped_copy_(new old_value_copy<T>(old))
#endif // Else, leave ptr_ null (thus no copy of T).
{
}
/**
Construct this object from the specified old value when the old value type
is not copyable.
The specified old value cannot be copied in this case so it is not copied
and the related old value pointer will always be null (thus a call to this
constructor has no effect and it will likely be optimized away by most
compilers).
@param old Old value (that will not be copied in this case).
@tparam T Old value type.
*/
template <typename T>
/* implicit */ old_value(
T const& old, typename boost::disable_if<
boost::contract::is_old_value_copyable<T>>::type* = 0)
{
} // Leave ptr_ null (thus no copy of T).
/** @cond */
private:
explicit old_value()
{
}
#ifndef BOOST_CONTRACT_NO_OLDS
boost::shared_ptr<void> untyped_copy_; // Type erasure.
#endif
friend class old_pointer;
friend BOOST_CONTRACT_DETAIL_DECLSPEC old_value null_old();
/** @endcond */
};
/**
Convert old value copies to old value pointers.
This class is often only implicitly used by this library and it does not
explicitly appear in user code (that is why this class does not have public
constructors, etc.).
*/
class old_pointer
{ // Copyable (as *).
public:
/**
Convert this object to an actual old value pointer for which the old value
type @c T might or not be copyable.
For example, this is implicitly called when assigning or initializing old
value pointers.
@tparam T Type of the pointed old value.
The old value pointer will always be null if this type is not
copyable (see
@c boost::contract::is_old_value_copyable), but this library
will not generate a compile-time error.
*/
template <typename T>
/* implicit */ operator old_ptr_if_copyable<T>()
{
return get<old_ptr_if_copyable<T>>();
}
/**
Convert this object to an actual old value pointer for which the old value
type @c T must be copyable.
For example, this is implicitly called when assigning or initializing old
value pointers.
@tparam T Type of the pointed old value. This type must be copyable
(see @c boost::contract::is_old_value_copyable),
otherwise this library will generate a compile-time error when
the old value pointer is dereferenced.
*/
template <typename T>
/* implicit */ operator old_ptr<T>()
{
return get<old_ptr<T>>();
}
/** @cond */
private:
explicit old_pointer(virtual_* v, old_value const& old)
#ifndef BOOST_CONTRACT_NO_OLDS
:
v_(v),
untyped_copy_(old.untyped_copy_)
#endif
{
}
template <typename Ptr>
Ptr get()
{
#ifndef BOOST_CONTRACT_NO_OLDS
if (!boost::contract::is_old_value_copyable<
typename Ptr::element_type>::value)
{
BOOST_CONTRACT_DETAIL_DEBUG(!untyped_copy_);
return Ptr(); // Non-copyable so no old value and return null.
#ifndef BOOST_CONTRACT_ALL_DISABLE_NO_ASSERTION
}
else if (!v_ && boost::contract::detail::checking::already())
{
return Ptr(); // Not checking (so return null).
#endif
}
else if (!v_)
{
BOOST_CONTRACT_DETAIL_DEBUG(untyped_copy_);
typedef old_value_copy<typename Ptr::element_type> copied_type;
boost::shared_ptr<copied_type> typed_copy = // Un-erase type.
boost::static_pointer_cast<copied_type>(untyped_copy_);
BOOST_CONTRACT_DETAIL_DEBUG(typed_copy);
return Ptr(typed_copy);
}
else if (v_->action_ == boost::contract::virtual_::push_old_init_copy ||
v_->action_ == boost::contract::virtual_::push_old_ftor_copy)
{
BOOST_CONTRACT_DETAIL_DEBUG(untyped_copy_);
std::queue<boost::shared_ptr<void>>& copies =
v_->action_ == boost::contract::virtual_::push_old_ftor_copy
? v_->old_ftor_copies_
: v_->old_init_copies_;
copies.push(untyped_copy_);
return Ptr(); // Pushed (so return null).
}
else if (boost::contract::virtual_::pop_old_init_copy(v_->action_) ||
v_->action_ == boost::contract::virtual_::pop_old_ftor_copy)
{
// Copy not null, but still pop it from the queue.
BOOST_CONTRACT_DETAIL_DEBUG(!untyped_copy_);
std::queue<boost::shared_ptr<void>>& copies =
v_->action_ == boost::contract::virtual_::pop_old_ftor_copy
? v_->old_ftor_copies_
: v_->old_init_copies_;
boost::shared_ptr<void> untyped_copy = copies.front();
BOOST_CONTRACT_DETAIL_DEBUG(untyped_copy);
copies.pop();
typedef old_value_copy<typename Ptr::element_type> copied_type;
boost::shared_ptr<copied_type> typed_copy = // Un-erase type.
boost::static_pointer_cast<copied_type>(untyped_copy);
BOOST_CONTRACT_DETAIL_DEBUG(typed_copy);
return Ptr(typed_copy);
}
BOOST_CONTRACT_DETAIL_DEBUG(!untyped_copy_);
#endif
return Ptr();
}
#ifndef BOOST_CONTRACT_NO_OLDS
virtual_* v_;
boost::shared_ptr<void> untyped_copy_; // Type erasure.
#endif
friend BOOST_CONTRACT_DETAIL_DECLSPEC old_pointer
make_old(old_value const&);
friend BOOST_CONTRACT_DETAIL_DECLSPEC old_pointer
make_old(virtual_*, old_value const&);
/** @endcond */
};
/**
Return a null old value.
The related old value pointer will also be null.
This function is often only used by the code expanded by
@RefMacro{BOOST_CONTRACT_OLDOF}.
@see @RefSect{extras.no_macros__and_no_variadic_macros_, No Macros}
@return Null old value.
*/
/** @cond */ BOOST_CONTRACT_DETAIL_DECLSPEC /** @endcond */
old_value
null_old();
/**
Make an old value pointer (but not for virtual public functions and public
functions overrides).
The related old value pointer will not be null if the specified old value was
actually copied.
This function is often only used by code expanded by
@c BOOST_CONTRACT_OLDOF(old_expr):
@code
boost::contract::make_old(boost::contract::copy_old() ? old_expr :
boost::contract::null_old())
@endcode
@see @RefSect{extras.no_macros__and_no_variadic_macros_, No Macros}
@param old Old value which is usually implicitly constructed from the user old
value expression to be copied (use the ternary operator <c>?:</c>
to avoid evaluating the old value expression all together when
@c boost::contract::copy_old() is @c false).
@return Old value pointer (usually implicitly converted to either
@RefClass{boost::contract::old_ptr} or
@RefClass{boost::contract::old_ptr_if_copyable} in user code).
*/
/** @cond */ BOOST_CONTRACT_DETAIL_DECLSPEC /** @endcond */
old_pointer
make_old(old_value const& old);
/**
Make an old value pointer (for virtual public functions and public functions
overrides).
The related old value pointer will not be null if the specified old value was
actually copied.
This function is often only used by code expanded by
@c BOOST_CONTRACT_OLDOF(v, old_expr):
@code
boost::contract::make_old(v, boost::contract::copy_old(v) ? old_expr :
boost::contract::null_old())
@endcode
@see @RefSect{extras.no_macros__and_no_variadic_macros_, No Macros}
@param v The trailing parameter of type
@RefClass{boost::contract::virtual_}<c>*</c> and default value @c 0
from the enclosing virtual or overriding public function declaring
the contract.
@param old Old value which is usually implicitly constructed from the user old
value expression to be copied (use the ternary operator <c>?:</c>
to avoid evaluating the old value expression all together when
@c boost::contract::copy_old(v) is @c false).
@return Old value pointer (usually implicitly converted to either
@RefClass{boost::contract::old_ptr} or
@RefClass{boost::contract::old_ptr_if_copyable} in user code).
*/
/** @cond */ BOOST_CONTRACT_DETAIL_DECLSPEC /** @endcond */
old_pointer
make_old(virtual_* v, old_value const& old);
/**
Check if old values need to be copied (but not for virtual public functions and
public function overrides).
For example, this function always returns false when both postconditions and
exception guarantees are not being checked (see
@RefMacro{BOOST_CONTRACT_NO_OLDS}).
This function is often only used by the code expanded by
@RefMacro{BOOST_CONTRACT_OLDOF}.
@see @RefSect{extras.no_macros__and_no_variadic_macros_, No Macros}
@return True if old values need to be copied, false otherwise.
*/
inline bool copy_old()
{
#ifndef BOOST_CONTRACT_NO_OLDS
#ifndef BOOST_CONTRACT_ALL_DISABLE_NO_ASSERTION
return !boost::contract::detail::checking::already();
#else
return true;
#endif
#else
return false; // No post checking, so never copy old values.
#endif
}
/**
Check if old values need to be copied (for virtual public functions and public
function overrides).
For example, this function always returns false when both postconditions and
exception guarantees are not being checked (see
@RefMacro{BOOST_CONTRACT_NO_OLDS}).
In addition, this function returns false when overridden functions are being
called subsequent times by this library to support subcontracting.
This function is often only used by the code expanded by
@RefMacro{BOOST_CONTRACT_OLDOF}.
@see @RefSect{extras.no_macros__and_no_variadic_macros_, No Macros}
@param v The trailing parameter of type
@RefClass{boost::contract::virtual_}<c>*</c> and default value @c 0
from the enclosing virtual or overriding public function declaring
the contract.
@return True if old values need to be copied, false otherwise.
*/
inline bool copy_old(virtual_* v)
{
#ifndef BOOST_CONTRACT_NO_OLDS
if (!v)
{
#ifndef BOOST_CONTRACT_ALL_DISABLE_NO_ASSERTION
return !boost::contract::detail::checking::already();
#else
return true;
#endif
}
return v->action_ == boost::contract::virtual_::push_old_init_copy ||
v->action_ == boost::contract::virtual_::push_old_ftor_copy;
#else
return false; // No post checking, so never copy old values.
#endif
}
} // namespace contract
} // namespace boost
#ifdef BOOST_CONTRACT_HEADER_ONLY
#include <boost/contract/detail/inlined/old.hpp>
#endif
#endif // #include guard
|
# Bayesian Hierarchical Linear Regression
Author: [Carlos Souza](mailto:[email protected])
Probabilistic Machine Learning models can not only make predictions about future data, but also **model uncertainty**. In areas such as **personalized medicine**, there might be a large amount of data, but there is still a relatively **small amount of data for each patient**. To customize predictions for each person it becomes necessary to **build a model for each person** — with its inherent **uncertainties** — and to couple these models together in a **hierarchy** so that information can be borrowed from other **similar people** [1].
The purpose of this tutorial is to demonstrate how to **implement a Bayesian Hierarchical Linear Regression model using NumPyro**. To motivate the tutorial, I will use [OSIC Pulmonary Fibrosis Progression](https://www.kaggle.com/c/osic-pulmonary-fibrosis-progression) competition, hosted at Kaggle.
## 1. Understanding the task
Pulmonary fibrosis is a disorder with no known cause and no known cure, created by scarring of the lungs. In this competition, we were asked to predict a patient’s severity of decline in lung function. Lung function is assessed based on output from a spirometer, which measures the forced vital capacity (FVC), i.e. the volume of air exhaled.
In medical applications, it is useful to **evaluate a model's confidence in its decisions**. Accordingly, the metric used to rank the teams was designed to reflect **both the accuracy and certainty of each prediction**. It's a modified version of the Laplace Log Likelihood (more details on that later).
Let's explore the data and see what's that all about:
```python
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
```
```python
train = pd.read_csv('https://gist.githubusercontent.com/ucals/'
'2cf9d101992cb1b78c2cdd6e3bac6a4b/raw/'
'43034c39052dcf97d4b894d2ec1bc3f90f3623d9/'
'osic_pulmonary_fibrosis.csv')
train.head()
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Patient</th>
<th>Weeks</th>
<th>FVC</th>
<th>Percent</th>
<th>Age</th>
<th>Sex</th>
<th>SmokingStatus</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>ID00007637202177411956430</td>
<td>-4</td>
<td>2315</td>
<td>58.253649</td>
<td>79</td>
<td>Male</td>
<td>Ex-smoker</td>
</tr>
<tr>
<th>1</th>
<td>ID00007637202177411956430</td>
<td>5</td>
<td>2214</td>
<td>55.712129</td>
<td>79</td>
<td>Male</td>
<td>Ex-smoker</td>
</tr>
<tr>
<th>2</th>
<td>ID00007637202177411956430</td>
<td>7</td>
<td>2061</td>
<td>51.862104</td>
<td>79</td>
<td>Male</td>
<td>Ex-smoker</td>
</tr>
<tr>
<th>3</th>
<td>ID00007637202177411956430</td>
<td>9</td>
<td>2144</td>
<td>53.950679</td>
<td>79</td>
<td>Male</td>
<td>Ex-smoker</td>
</tr>
<tr>
<th>4</th>
<td>ID00007637202177411956430</td>
<td>11</td>
<td>2069</td>
<td>52.063412</td>
<td>79</td>
<td>Male</td>
<td>Ex-smoker</td>
</tr>
</tbody>
</table>
</div>
In the dataset, we were provided with a baseline chest CT scan and associated clinical information for a set of patients. A patient has an image acquired at time Week = 0 and has numerous follow up visits over the course of approximately 1-2 years, at which time their FVC is measured. For this tutorial, I will use only the Patient ID, the weeks and the FVC measurements, discarding all the rest. Using only these columns enabled our team to achieve a competitive score, which shows the power of Bayesian hierarchical linear regression models especially when gauging uncertainty is an important part of the problem.
Since this is real medical data, the relative timing of FVC measurements varies widely, as shown in the 3 sample patients below:
```python
def chart(patient_id, ax):
data = train[train['Patient'] == patient_id]
x = data['Weeks']
y = data['FVC']
ax.set_title(patient_id)
ax = sns.regplot(x, y, ax=ax, ci=None, line_kws={'color':'red'})
f, axes = plt.subplots(1, 3, figsize=(15, 5))
chart('ID00007637202177411956430', axes[0])
chart('ID00009637202177434476278', axes[1])
chart('ID00010637202177584971671', axes[2])
```
On average, each of the 176 provided patients made 9 visits, when FVC was measured. The visits happened in specific weeks in the [-12, 133] interval. The decline in lung capacity is very clear. We see, though, they are very different from patient to patient.
We were are asked to predict every patient's FVC measurement for every possible week in the [-12, 133] interval, and the confidence for each prediction. In other words: we were asked fill a matrix like the one below, and provide a confidence score for each prediction:
The task was perfect to apply Bayesian inference. However, the vast majority of solutions shared by Kaggle community used discriminative machine learning models, disconsidering the fact that most discriminative methods are very poor at providing realistic uncertainty estimates. Because they are typically trained in a manner that optimizes the parameters to minimize some loss criterion (e.g. the predictive error), they do not, in general, encode any uncertainty in either their parameters or the subsequent predictions. Though many methods can produce uncertainty estimates either as a by-product or from a post-processing step, these are typically heuristic based, rather than stemming naturally from a statistically principled estimate of the target uncertainty distribution [2].
## 2. Modelling: Bayesian Hierarchical Linear Regression with Partial Pooling
The simplest possible linear regression, not hierarchical, would assume all FVC decline curves have the same $\alpha$ and $\beta$. That's the **pooled model**. In the other extreme, we could assume a model where each patient has a personalized FVC decline curve, and **these curves are completely unrelated**. That's the **unpooled model**, where each patient has completely separate regressions.
Here, I'll use the middle ground: **Partial pooling**. Specifically, I'll assume that while $\alpha$'s and $\beta$'s are different for each patient as in the unpooled case, **the coefficients all share similarity**. We can model this by assuming that each individual coefficient comes from a common group distribution. The image below represents this model graphically:
Mathematically, the model is described by the following equations:
$$
\begin{align}
\mu_{\alpha} &\sim \mathcal{N}(0, 100) \\
\sigma_{\alpha} &\sim |\mathcal{N}(0, 100)| \\
\mu_{\beta} &\sim \mathcal{N}(0, 100) \\
\sigma_{\beta} &\sim |\mathcal{N}(0, 100)| \\
\alpha_i &\sim \mathcal{N}(\mu_{\alpha}, \sigma_{\alpha}) \\
\beta_i &\sim \mathcal{N}(\mu_{\beta}, \sigma_{\beta}) \\
\sigma &\sim \mathcal{N}(0, 100) \\
FVC_{ij} &\sim \mathcal{N}(\alpha_i + t \beta_i, \sigma)
\end{align}
$$
where *t* is the time in weeks. Those are very uninformative priors, but that's ok: our model will converge!
Implementing this model in NumPyro is pretty straightforward:
```python
import numpyro
from numpyro.infer import MCMC, NUTS, Predictive
import numpyro.distributions as dist
from jax import random
```
```python
def model(PatientID, Weeks, FVC_obs=None):
μ_α = numpyro.sample("μ_α", dist.Normal(0., 100.))
σ_α = numpyro.sample("σ_α", dist.HalfNormal(100.))
μ_β = numpyro.sample("μ_β", dist.Normal(0., 100.))
σ_β = numpyro.sample("σ_β", dist.HalfNormal(100.))
unique_patient_IDs = np.unique(PatientID)
n_patients = len(unique_patient_IDs)
with numpyro.plate("plate_i", n_patients):
α = numpyro.sample("α", dist.Normal(μ_α, σ_α))
β = numpyro.sample("β", dist.Normal(μ_β, σ_β))
σ = numpyro.sample("σ", dist.HalfNormal(100.))
FVC_est = α[PatientID] + β[PatientID] * Weeks
with numpyro.plate("data", len(PatientID)):
numpyro.sample("obs", dist.Normal(FVC_est, σ), obs=FVC_obs)
```
That's all for modelling!
## 3. Fitting the model
A great achievement of Probabilistic Programming Languages such as NumPyro is to decouple model specification and inference. After specifying my generative model, with priors, condition statements and data likelihood, I can leave the hard work to NumPyro's inference engine.
Calling it requires just a few lines. Before we do it, let's add a numerical Patient ID for each patient code. That can be easily done with scikit-learn's LabelEncoder:
```python
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
train['PatientID'] = le.fit_transform(train['Patient'].values)
FVC_obs = train['FVC'].values
Weeks = train['Weeks'].values
PatientID = train['PatientID'].values
```
Now, calling NumPyro's inference engine:
```python
nuts_kernel = NUTS(model)
mcmc = MCMC(nuts_kernel, num_samples=2000, num_warmup=2000)
rng_key = random.PRNGKey(0)
mcmc.run(rng_key, PatientID, Weeks, FVC_obs=FVC_obs)
posterior_samples = mcmc.get_samples()
```
sample: 100%|██████████| 4000/4000 [00:28<00:00, 142.85it/s, 63 steps of size 1.08e-01. acc. prob=0.88]
## 4. Checking the model
### 4.1. Inspecting the learned parameters
First, let's inspect the parameters learned. To do that, I will use [ArviZ](https://arviz-devs.github.io/arviz/), which perfectly integrates with NumPyro:
```python
import arviz as az
data = az.from_numpyro(mcmc)
az.plot_trace(data, compact=True);
```
Looks like our model learned personalized alphas and betas for each patient!
### 4.2. Visualizing FVC decline curves for some patients
Now, let's visually inspect FVC decline curves predicted by our model. We will completely fill in the FVC table, predicting all missing values. The first step is to create a table to fill:
```python
pred_template = []
for i in range(train['Patient'].nunique()):
df = pd.DataFrame(columns=['PatientID', 'Weeks'])
df['Weeks'] = np.arange(-12, 134)
df['PatientID'] = i
pred_template.append(df)
pred_template = pd.concat(pred_template, ignore_index=True)
```
Predicting the missing values in the FVC table and confidence (sigma) for each value becomes really easy:
```python
PatientID = pred_template['PatientID'].values
Weeks = pred_template['Weeks'].values
predictive = Predictive(model, posterior_samples,
return_sites=['σ', 'obs'])
samples_predictive = predictive(random.PRNGKey(0),
PatientID, Weeks, None)
```
Let's now put the predictions together with the true values, to visualize them:
```python
df = pd.DataFrame(columns=['Patient', 'Weeks', 'FVC_pred', 'sigma'])
df['Patient'] = le.inverse_transform(pred_template['PatientID'])
df['Weeks'] = pred_template['Weeks']
df['FVC_pred'] = samples_predictive['obs'].T.mean(axis=1)
df['sigma'] = samples_predictive['obs'].T.std(axis=1)
df['FVC_inf'] = df['FVC_pred'] - df['sigma']
df['FVC_sup'] = df['FVC_pred'] + df['sigma']
df = pd.merge(df, train[['Patient', 'Weeks', 'FVC']],
how='left', on=['Patient', 'Weeks'])
df = df.rename(columns={'FVC': 'FVC_true'})
df.head()
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Patient</th>
<th>Weeks</th>
<th>FVC_pred</th>
<th>sigma</th>
<th>FVC_inf</th>
<th>FVC_sup</th>
<th>FVC_true</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>ID00007637202177411956430</td>
<td>-12</td>
<td>2215.250488</td>
<td>156.240250</td>
<td>2059.010254</td>
<td>2371.490723</td>
<td>NaN</td>
</tr>
<tr>
<th>1</th>
<td>ID00007637202177411956430</td>
<td>-11</td>
<td>2216.876465</td>
<td>161.742844</td>
<td>2055.133545</td>
<td>2378.619385</td>
<td>NaN</td>
</tr>
<tr>
<th>2</th>
<td>ID00007637202177411956430</td>
<td>-10</td>
<td>2217.119385</td>
<td>152.493393</td>
<td>2064.625977</td>
<td>2369.612793</td>
<td>NaN</td>
</tr>
<tr>
<th>3</th>
<td>ID00007637202177411956430</td>
<td>-9</td>
<td>2210.115479</td>
<td>159.417191</td>
<td>2050.698242</td>
<td>2369.532715</td>
<td>NaN</td>
</tr>
<tr>
<th>4</th>
<td>ID00007637202177411956430</td>
<td>-8</td>
<td>2198.447510</td>
<td>153.805420</td>
<td>2044.642090</td>
<td>2352.252930</td>
<td>NaN</td>
</tr>
</tbody>
</table>
</div>
Finally, let's see our predictions for 3 patients:
```python
def chart(patient_id, ax):
data = df[df['Patient'] == patient_id]
x = data['Weeks']
ax.set_title(patient_id)
ax.plot(x, data['FVC_true'], 'o')
ax.plot(x, data['FVC_pred'])
ax = sns.regplot(x, data['FVC_true'], ax=ax, ci=None,
line_kws={'color':'red'})
ax.fill_between(x, data["FVC_inf"], data["FVC_sup"],
alpha=0.5, color='#ffcd3c')
ax.set_ylabel('FVC')
f, axes = plt.subplots(1, 3, figsize=(15, 5))
chart('ID00007637202177411956430', axes[0])
chart('ID00009637202177434476278', axes[1])
chart('ID00011637202177653955184', axes[2])
```
The results are exactly what we expected to see! Highlight observations:
- The model adequately learned Bayesian Linear Regressions! The orange line (learned predicted FVC mean) is very inline with the red line (deterministic linear regression). But most important: it learned to predict uncertainty, showed in the light orange region (one sigma above and below the mean FVC line)
- The model predicts a higher uncertainty where the data points are more disperse (1st and 3rd patients). Conversely, where the points are closely grouped together (2nd patient), the model predicts a higher confidence (narrower light orange region)
- Finally, in all patients, we can see that the uncertainty grows as the look more into the future: the light orange region widens as the # of weeks grow!
## 4.3. Computing the modified Laplace Log Likelihood and RMSE
As mentioned earlier, the competition was evaluated on a modified version of the Laplace Log Likelihood. In medical applications, it is useful to evaluate a model's confidence in its decisions. Accordingly, the metric is designed to reflect both the accuracy and certainty of each prediction.
For each true FVC measurement, we predicted both an FVC and a confidence measure (standard deviation $\sigma$). The metric was computed as:
$$
\begin{align}
\sigma_{clipped} &= max(\sigma, 70) \\
\delta &= min(|FVC_{true} - FVC_{pred}|, 1000) \\
metric &= -\dfrac{\sqrt{2}\delta}{\sigma_{clipped}} - \ln(\sqrt{2} \sigma_{clipped})
\end{align}
$$
The error was thresholded at 1000 ml to avoid large errors adversely penalizing results, while the confidence values were clipped at 70 ml to reflect the approximate measurement uncertainty in FVC. The final score was calculated by averaging the metric across all (Patient, Week) pairs. Note that metric values will be negative and higher is better.
Next, we calculate the metric and RMSE:
```python
y = df.dropna()
rmse = ((y['FVC_pred'] - y['FVC_true']) ** 2).mean() ** (1/2)
print(f'RMSE: {rmse:.1f} ml')
sigma_c = y['sigma'].values
sigma_c[sigma_c < 70] = 70
delta = (y['FVC_pred'] - y['FVC_true']).abs()
delta[delta > 1000] = 1000
lll = - np.sqrt(2) * delta / sigma_c - np.log(np.sqrt(2) * sigma_c)
print(f'Laplace Log Likelihood: {lll.mean():.4f}')
```
RMSE: 122.2 ml
Laplace Log Likelihood: -6.1376
What do these numbers mean? It means if you adopted this approach, you would **outperform most of the public solutions** in the competition. Curiously, the vast majority of public solutions adopt a standard deterministic Neural Network, modelling uncertainty through a quantile loss. **Most of the people still adopt a frequentist approach**.
**Uncertainty** for single predictions becomes more and more important in machine learning and is often a requirement. **Especially when the consequenses of a wrong prediction are high**, we need to know what the probability distribution of an individual prediction is. For perspective, Kaggle just launched a new competition sponsored by Lyft, to build motion prediction models for self-driving vehicles. "We ask that you predict a few trajectories for every agent **and provide a confidence score for each of them**."
Finally, I hope the great work done by Pyro/NumPyro developers help democratize Bayesian methods, empowering an ever growing community of researchers and practitioners to create models that can not only generate predictions, but also assess uncertainty in their predictions.
# References
1. Ghahramani, Z. Probabilistic machine learning and artificial intelligence. Nature 521, 452–459 (2015). https://doi.org/10.1038/nature14541
2. Rainforth, Thomas William Gamlen. Automating Inference, Learning, and Design Using Probabilistic Programming. University of Oxford, 2017.
```python
```
|
module PencilFFTs
import AbstractFFTs
import FFTW
import MPI
using LinearAlgebra
using Reexport
using TimerOutputs
@reexport using PencilArrays
include("Transforms/Transforms.jl")
@reexport using .Transforms
import PencilArrays.Transpositions: AbstractTransposeMethod
import .Transforms: AbstractTransform, FFTReal, scale_factor
export PencilFFTPlan
export allocate_input, allocate_output, scale_factor
# Deprecated in v0.10
@deprecate get_scale_factor scale_factor
# Functions to be extended for PencilFFTs types.
import PencilArrays: get_comm, timer, topology, extra_dims
const AbstractTransformList{N} = NTuple{N, AbstractTransform} where N
include("global_params.jl")
include("plans.jl")
include("allocate.jl")
include("operations.jl")
end # module
|
(*
Copyright (C) 2017 M.A.L. Marques
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)
(* type: work_gga_c *)
$include "gga_c_pw91.mpl"
c1 := 1.1015:
c2 := 0.6625:
f := (rs, z, xt, xs0, xs1) ->
+ c1*f_pw91(rs, z, xt, xs0, xs1) + (c2 - c1)*(
+ f_pw91(rs*(2*(1 + z))^(1/3), 1, xs0, xs0, 0)
+ f_pw91(rs*(2*(1 - z))^(1/3), -1, xs1, 0, xs1)
): |
\section{\sc Programming Languages}
\textbf{Languages}{: \textit{Python, C/C++, Java SE, VHDL, ARM Assembly, AVR Assembly, Racket, ML, Scheme, HTML/CSS, Javascript, Latex.}}
\hfill
\textbf{Frameworks and Environments}{: \textit{Keras, Tensorflow, Numpy, Matplotlib, Pandas, RapidMiner, Weka, OpenMP, CUDA, React Native, Node.js, Laravel.}}
\hfill
\textbf{Databases}{: \textit{MongoDB, MySQL, PostgreSQL.}}
\hfill
\endinput |
/-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
! This file was ported from Lean 3 source module data.fintype.perm
! leanprover-community/mathlib commit 0a0ec35061ed9960bf0e7ffb0335f44447b58977
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Data.Fintype.Card
import Mathbin.GroupTheory.Perm.Basic
/-!
# fintype instances for `equiv` and `perm`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Main declarations:
* `perms_of_finset s`: The finset of permutations of the finset `s`.
-/
open Function
open Nat
universe u v
variable {α β γ : Type _}
open Finset Function List Equiv Equiv.Perm
variable [DecidableEq α] [DecidableEq β]
#print permsOfList /-
/-- Given a list, produce a list of all permutations of its elements. -/
def permsOfList : List α → List (Perm α)
| [] => [1]
| a :: l => permsOfList l ++ l.bind fun b => (permsOfList l).map fun f => swap a b * f
#align perms_of_list permsOfList
-/
#print length_permsOfList /-
theorem length_permsOfList : ∀ l : List α, length (permsOfList l) = l.length !
| [] => rfl
| a :: l => by
rw [length_cons, Nat.factorial_succ]
simp [permsOfList, length_bind, length_permsOfList, Function.comp, Nat.succ_mul]
cc
#align length_perms_of_list length_permsOfList
-/
#print mem_permsOfList_of_mem /-
theorem mem_permsOfList_of_mem {l : List α} {f : Perm α} (h : ∀ x, f x ≠ x → x ∈ l) :
f ∈ permsOfList l := by
induction' l with a l IH generalizing f h
· exact List.mem_singleton.2 (Equiv.ext fun x => Decidable.by_contradiction <| h _)
by_cases hfa : f a = a
· refine' mem_append_left _ (IH fun x hx => mem_of_ne_of_mem _ (h x hx))
rintro rfl
exact hx hfa
have hfa' : f (f a) ≠ f a := mt (fun h => f.injective h) hfa
have : ∀ x : α, (swap a (f a) * f) x ≠ x → x ∈ l :=
by
intro x hx
have hxa : x ≠ a := by
rintro rfl
apply hx
simp only [mul_apply, swap_apply_right]
refine' List.mem_of_ne_of_mem hxa (h x fun h => _)
simp only [h, mul_apply, swap_apply_def, mul_apply, Ne.def, apply_eq_iff_eq] at hx <;>
split_ifs at hx
exacts[hxa (h.symm.trans h_1), hx h]
suffices f ∈ permsOfList l ∨ ∃ b ∈ l, ∃ g ∈ permsOfList l, swap a b * g = f by
simpa only [permsOfList, exists_prop, List.mem_map, mem_append, List.mem_bind]
refine' or_iff_not_imp_left.2 fun hfl => ⟨f a, _, swap a (f a) * f, IH this, _⟩
· exact mem_of_ne_of_mem hfa (h _ hfa')
· rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← perm.one_def, one_mul]
#align mem_perms_of_list_of_mem mem_permsOfList_of_mem
-/
#print mem_of_mem_permsOfList /-
theorem mem_of_mem_permsOfList :
∀ {l : List α} {f : Perm α}, f ∈ permsOfList l → ∀ {x}, f x ≠ x → x ∈ l
| [], f, h => by
have : f = 1 := by simpa [permsOfList] using h
rw [this] <;> simp
| a :: l, f, h =>
(mem_append.1 h).elim (fun h x hx => mem_cons_of_mem _ (mem_of_mem_permsOfList h hx))
fun h x hx =>
let ⟨y, hy, hy'⟩ := List.mem_bind.1 h
let ⟨g, hg₁, hg₂⟩ := List.mem_map.1 hy'
if hxa : x = a then by simp [hxa]
else
if hxy : x = y then mem_cons_of_mem _ <| by rwa [hxy]
else
mem_cons_of_mem _ <|
mem_of_mem_permsOfList hg₁ <| by
rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def] <;>
split_ifs <;>
[exact Ne.symm hxy, exact Ne.symm hxa, exact hx]
#align mem_of_mem_perms_of_list mem_of_mem_permsOfList
-/
#print mem_permsOfList_iff /-
theorem mem_permsOfList_iff {l : List α} {f : Perm α} :
f ∈ permsOfList l ↔ ∀ {x}, f x ≠ x → x ∈ l :=
⟨mem_of_mem_permsOfList, mem_permsOfList_of_mem⟩
#align mem_perms_of_list_iff mem_permsOfList_iff
-/
#print nodup_permsOfList /-
theorem nodup_permsOfList : ∀ {l : List α} (hl : l.Nodup), (permsOfList l).Nodup
| [], hl => by simp [permsOfList]
| a :: l, hl => by
have hl' : l.Nodup := hl.of_cons
have hln' : (permsOfList l).Nodup := nodup_permsOfList hl'
have hmeml : ∀ {f : Perm α}, f ∈ permsOfList l → f a = a := fun f hf =>
Classical.not_not.1 (mt (mem_of_mem_permsOfList hf) (nodup_cons.1 hl).1)
rw [permsOfList, List.nodup_append, List.nodup_bind, pairwise_iff_nth_le] <;>
exact
⟨hln',
⟨fun _ _ => hln'.map fun _ _ => mul_left_cancel, fun i j hj hij x hx₁ hx₂ =>
let ⟨f, hf⟩ := List.mem_map.1 hx₁
let ⟨g, hg⟩ := List.mem_map.1 hx₂
have hix : x a = nth_le l i (lt_trans hij hj) := by
rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left]
have hiy : x a = nth_le l j hj := by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left]
absurd (hf.2.trans hg.2.symm) fun h =>
ne_of_lt hij <|
nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj <| by rw [← hix, hiy]⟩,
fun f hf₁ hf₂ =>
let ⟨x, hx, hx'⟩ := List.mem_bind.1 hf₂
let ⟨g, hg⟩ := List.mem_map.1 hx'
have hgxa : g⁻¹ x = a := f.Injective <| by rw [hmeml hf₁, ← hg.2] <;> simp
have hxa : x ≠ a := fun h => (List.nodup_cons.1 hl).1 (h ▸ hx)
(List.nodup_cons.1 hl).1 <|
hgxa ▸ mem_of_mem_permsOfList hg.1 (by rwa [apply_inv_self, hgxa])⟩
#align nodup_perms_of_list nodup_permsOfList
-/
#print permsOfFinset /-
/-- Given a finset, produce the finset of all permutations of its elements. -/
def permsOfFinset (s : Finset α) : Finset (Perm α) :=
Quotient.hrecOn s.1 (fun l hl => ⟨permsOfList l, nodup_permsOfList hl⟩)
(fun a b hab =>
hfunext (congr_arg _ (Quotient.sound hab)) fun ha hb _ =>
hEq_of_eq <| Finset.ext <| by simp [mem_permsOfList_iff, hab.mem_iff])
s.2
#align perms_of_finset permsOfFinset
-/
#print mem_perms_of_finset_iff /-
theorem mem_perms_of_finset_iff :
∀ {s : Finset α} {f : Perm α}, f ∈ permsOfFinset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by
rintro ⟨⟨l⟩, hs⟩ f <;> exact mem_permsOfList_iff
#align mem_perms_of_finset_iff mem_perms_of_finset_iff
-/
#print card_perms_of_finset /-
theorem card_perms_of_finset : ∀ s : Finset α, (permsOfFinset s).card = s.card ! := by
rintro ⟨⟨l⟩, hs⟩ <;> exact length_permsOfList l
#align card_perms_of_finset card_perms_of_finset
-/
#print fintypePerm /-
/-- The collection of permutations of a fintype is a fintype. -/
def fintypePerm [Fintype α] : Fintype (Perm α) :=
⟨permsOfFinset (@Finset.univ α _), by simp [mem_perms_of_finset_iff]⟩
#align fintype_perm fintypePerm
-/
instance [Fintype α] [Fintype β] : Fintype (α ≃ β) :=
if h : Fintype.card β = Fintype.card α then
Trunc.recOnSubsingleton (Fintype.truncEquivFin α) fun eα =>
Trunc.recOnSubsingleton (Fintype.truncEquivFin β) fun eβ =>
@Fintype.ofEquiv _ (Perm α) fintypePerm
(equivCongr (Equiv.refl α) (eα.trans (Eq.recOn h eβ.symm)) : α ≃ α ≃ (α ≃ β))
else ⟨∅, fun x => False.elim (h (Fintype.card_eq.2 ⟨x.symm⟩))⟩
/- warning: fintype.card_perm -> Fintype.card_perm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} [_inst_1 : DecidableEq.{succ u1} α] [_inst_3 : Fintype.{u1} α], Eq.{1} Nat (Fintype.card.{u1} (Equiv.Perm.{succ u1} α) (Equiv.fintype.{u1, u1} α α (fun (a : α) (b : α) => _inst_1 a b) (fun (a : α) (b : α) => _inst_1 a b) _inst_3 _inst_3)) (Nat.factorial (Fintype.card.{u1} α _inst_3))
but is expected to have type
forall {α : Type.{u1}} [_inst_1 : DecidableEq.{succ u1} α] [_inst_3 : Fintype.{u1} α], Eq.{1} Nat (Fintype.card.{u1} (Equiv.Perm.{succ u1} α) (equivFintype.{u1, u1} α α (fun (a : α) (b : α) => _inst_1 a b) (fun (a : α) (b : α) => _inst_1 a b) _inst_3 _inst_3)) (Nat.factorial (Fintype.card.{u1} α _inst_3))
Case conversion may be inaccurate. Consider using '#align fintype.card_perm Fintype.card_permₓ'. -/
theorem Fintype.card_perm [Fintype α] : Fintype.card (Perm α) = (Fintype.card α)! :=
Subsingleton.elim (@fintypePerm α _ _) (@Equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _
#align fintype.card_perm Fintype.card_perm
/- warning: fintype.card_equiv -> Fintype.card_equiv is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : DecidableEq.{succ u1} α] [_inst_2 : DecidableEq.{succ u2} β] [_inst_3 : Fintype.{u1} α] [_inst_4 : Fintype.{u2} β], (Equiv.{succ u1, succ u2} α β) -> (Eq.{1} Nat (Fintype.card.{max (max u1 u2) u2 u1} (Equiv.{succ u1, succ u2} α β) (Equiv.fintype.{u1, u2} α β (fun (a : α) (b : α) => _inst_1 a b) (fun (a : β) (b : β) => _inst_2 a b) _inst_3 _inst_4)) (Nat.factorial (Fintype.card.{u1} α _inst_3)))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : DecidableEq.{succ u2} α] [_inst_2 : DecidableEq.{succ u1} β] [_inst_3 : Fintype.{u2} α] [_inst_4 : Fintype.{u1} β], (Equiv.{succ u2, succ u1} α β) -> (Eq.{1} Nat (Fintype.card.{max u2 u1} (Equiv.{succ u2, succ u1} α β) (equivFintype.{u2, u1} α β (fun (a : α) (b : α) => _inst_1 a b) (fun (a : β) (b : β) => _inst_2 a b) _inst_3 _inst_4)) (Nat.factorial (Fintype.card.{u2} α _inst_3)))
Case conversion may be inaccurate. Consider using '#align fintype.card_equiv Fintype.card_equivₓ'. -/
theorem Fintype.card_equiv [Fintype α] [Fintype β] (e : α ≃ β) :
Fintype.card (α ≃ β) = (Fintype.card α)! :=
Fintype.card_congr (equivCongr (Equiv.refl α) e) ▸ Fintype.card_perm
#align fintype.card_equiv Fintype.card_equiv
|
from __future__ import division
import os
import json
import urllib2
import numpy as np
url1 = "http://acceldatacollect.appspot.com/sample/6281948016148480/.json"
url2 = "http://localhost:8080/sample/4984842122952704/.json"
DEBUG = 0
def d_print(*arguments):
if DEBUG == 1:
for arg in arguments: print arg
class TickMovV1():
def __init__(self):
self.mov_duration = 1
# x
self.neg_x_thr = -0.15
self.score_perc_high = 0.6
self.score_perc_low = 0.4
# y
self.len_of_average = 0.2
self.y_diff_thr = 0.7
#z
self.neg_z_thr = -0.2
self.z_score_perc = 0.4
self.z_trigger_delay = 0.4 # in seconds
self.version = "tickMov_v1"
def getData(self, url):
d = json.load(
urllib2.urlopen(url, timeout=5))
self.t = np.array(d["dataPoints"]["tRel"])
self.x = np.array(d["dataPoints"]["x"])
self.y = np.array(d["dataPoints"]["y"])
self.z = np.array(d["dataPoints"]["z"])
def passData(self, dataPoints):
self.t = np.array(dataPoints["tRel"])
self.x = np.array(dataPoints["x"])
self.y = np.array(dataPoints["y"])
self.z = np.array(dataPoints["z"])
def general(self):
self.f_sample = len(self.t)/self.t[-1]
self.b_len = 2*round(self.mov_duration * self.f_sample/2)
d_print("f_sample: ", self.f_sample)
d_print("b_len: ", self.b_len)
def x_analyse(self):
pos_x_thr = - self.neg_x_thr
neg = (self.x < self.neg_x_thr) * -1
pos = self.x > pos_x_thr
x_simple = neg + pos
# too long
#x_criteria = np.concatenate((np.ones((1, b_len/2)), np.ones((1, b_len/2)) *-1), axis = 1)
# better
x_criteria = [1]* int(self.b_len/2) + [-1] * int(self.b_len/2)
d_print( "x_criteria", x_criteria)
# the filter function in matlab treats the edges differently, hence the
# selector at the back of the convolve statement
x_scores = np.convolve(x_simple, x_criteria, 'full')[0:x_simple.shape[0]]
score_thr = self.score_perc_high * self.b_len;
self.x_ind_high = x_scores > score_thr;
score_thr = self.score_perc_low * self.b_len;
self.x_ind_low = x_scores > score_thr;
d_print( "Dimensions x simple, x_scores: ", x_simple.shape, x_scores.shape)
def y_analyse(self):
y_plus_one = self.y + 1
# this line can cause a zero division error if f_sample is too small
l_a = int(round(self.len_of_average * self.f_sample))
tmp = [-1] * l_a + [0] * int(self.b_len - 2 * l_a) + [1] * l_a
y_criteria = [ i / l_a for i in tmp]
y_scores = np.convolve(y_plus_one, y_criteria, 'full')[0:self.y.shape[0]]
self.y_ind = y_scores > self.y_diff_thr
d_print( 'y_criteria', y_criteria)
d_print( "Dimensions self.y, y_scores: ", self.y.shape, y_scores.shape)
def z_analyse(self):
# remove gravity. Only works if screen of phone faces up.
z_plus_one = self.z + 1;
pos_z_thr = - self.neg_z_thr
neg = (z_plus_one < self.neg_z_thr) * -1
pos = z_plus_one > pos_z_thr
z_simple = neg + pos
# in contrast to matlab version, the z_criteria is calculated dynamically based on fs
# example for 20Hz and mov_duration = 1;
# z_criteria = [1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 1 1 ];
perc = [0.3, 0.4, 0.3]
tot = [int(round(i * self.f_sample * self.mov_duration)) for i in perc]
b0_cr = [1] * tot[0] + [0] * tot[1] + [0] * tot[2]
b1_cr = [0] * tot[0] + [-1] * tot[1] + [0] * tot[2]
b2_cr = [0] * tot[0] + [0] * tot[1] + [1] * tot[2]
b0 = np.convolve(z_simple, b0_cr, 'full')[0:self.z.shape[0]]
b1 = np.convolve(z_simple, b1_cr, 'full')[0:self.z.shape[0]]
b2 = np.convolve(z_simple, b2_cr, 'full')[0:self.z.shape[0]]
# do not use b0 & b1 & b2 -> somhow it takes the modolo 2 of each number and ands them
z_cond1 = np.logical_and(b0, np.logical_and(b1, b2))
z_score2 = b0 + b1 + b2
d_print( "Dimensions self.z, z_score2: ", self.z.shape, z_score2.shape)
d_print( 'b0_cr', b0_cr)
d_print( 'b1_cr', b1_cr)
d_print( 'b2_cr', b2_cr)
z_ind_orig = np.logical_and(z_cond1,( z_score2 > self.b_len * self.z_score_perc))
# delay the trigger by self.z_trigger_delay seconds
delay = [1] * int(round(self.z_trigger_delay * self.f_sample))
d_print( "delay", delay)
z_ind_broad = np.convolve(z_ind_orig, delay, 'full')[0:self.z.shape[0]]
self.z_ind = np.logical_and(z_ind_broad, 1)
def result(self):
self.general()
self.x_analyse()
self.y_analyse()
self.z_analyse()
# here one can use the &, as *_ind are ones and zeors only
self.cond1 = self.x_ind_high & self.z_ind
self.cond2 = self.x_ind_low & self.y_ind & self.z_ind
self.cond_all = self.cond1 | self.cond2
# prepare the return lise
return [int(i) for i in self.cond_all]
#self.report()
def report(self, mode):
""" mode can be debug or html. In case of debug it is printed to the console,
in case of html, a string is returned"""
len = self.t.shape[0]
li = [[self.x_ind_high, "self.x_ind_high"],
[self.x_ind_low, "self.x_ind_low"],
[self.y_ind, "self.y_ind"],
[self.z_ind, "self.z_ind"],
[self.cond1, "self.cond1"],
[self.cond2, "self.cond2"],
[self.cond_all, "self.cond_all"],
]
perc_list = []
for i in li:
perc_list.append(i[1][5:] + " triggered: %.2f" %(sum(i[0])/len*100) +
"%, " + str(sum(i[0])))
t_events = []
for i in range(len):
if self.cond_all[i] == 1:
t_events.append("Trigger at %.2f s."%self.t[i])
params = [[self.mov_duration,"self.mov_duration"],
[self.neg_x_thr,"self.neg_x_thr"],
[self.score_perc_high,"self.score_perc_high"],
[self.score_perc_low,"self.score_perc_low"],
[self.len_of_average,"self.len_of_average"],
[self.y_diff_thr,"self.y_diff_thr"],
[self.neg_z_thr,"self.neg_z_thr"],
[self.z_score_perc,"self.z_score_perc"],
[self.z_trigger_delay,"self.z_trigger_delay"]
]
params_list = ["%s: %.2f"%(i[1][5:], i[0]) for i in params]
if mode == "debug":
print "VERSION: ", self.version
print "percentages:"
print "\n".join(perc_list)
print "\n\nevents:"
print "\n".join(t_events)
print " \n \n parameters:"
print "\n".join(params_list)
else:
return "VERSION: " + self.version + \
"<p><b>Percentages</b></p>" + "<br> - ".join(perc_list) + \
"<p><b>Events</b></p>" + "<br> - ".join(t_events) + \
"<p><b>Params</b></p>" + "<br> - ".join(params_list)
if __name__ == '__main__':
B = TickMovV1()
B.getData(url1)
B.result()
print B.report("html")
|
\name{set_name}
\alias{set_name}
\title{
Set Names
}
\description{
Set Names
}
\usage{
set_name(m)
}
\arguments{
\item{m}{A combination matrix returned by \code{\link{make_comb_mat}}.}
}
\value{
A vector of set names.
}
\examples{
set.seed(123)
lt = list(a = sample(letters, 10),
b = sample(letters, 15),
c = sample(letters, 20))
m = make_comb_mat(lt)
set_name(m)
}
|
(* This Isabelle theory is produced using the TIP tool offered at the following website:
https://github.com/tip-org/tools
This file was originally provided as part of TIP benchmark at the following website:
https://github.com/tip-org/benchmarks
Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
to make it compatible with Isabelle2017.*)
theory TIP_list_nat_PairEvens
imports "../../Test_Base"
begin
datatype ('a, 'b) pair = pair2 "'a" "'b"
datatype 'a list = nil2 | cons2 "'a" "'a list"
datatype Nat = Z | S "Nat"
fun plus :: "Nat => Nat => Nat" where
"plus (Z) y = y"
| "plus (S z) y = S (plus z y)"
fun pairs :: "'t list => (('t, 't) pair) list" where
"pairs (nil2) = nil2"
| "pairs (cons2 y (nil2)) = nil2"
| "pairs (cons2 y (cons2 y2 xs)) = cons2 (pair2 y y2) (pairs xs)"
fun minus :: "Nat => Nat => Nat" where
"minus (Z) y = Z"
| "minus (S z) (S y2) = minus z y2"
fun map :: "('a => 'b) => 'a list => 'b list" where
"map f (nil2) = nil2"
| "map f (cons2 y xs) = cons2 (f y) (map f xs)"
fun lt :: "Nat => Nat => bool" where
"lt x (Z) = False"
| "lt (Z) (S z) = True"
| "lt (S n) (S z) = lt n z"
fun length :: "'a list => Nat" where
"length (nil2) = Z"
| "length (cons2 y l) = plus (S Z) (length l)"
fun le :: "Nat => Nat => bool" where
"le (Z) y = True"
| "le (S z) (Z) = False"
| "le (S z) (S x2) = le z x2"
(*fun did not finish the proof*)
function imod :: "Nat => Nat => Nat" where
"imod x y = (if lt x y then x else imod (minus x y) y)"
by pat_completeness auto
function evens :: "'a list => 'a list"
and odds :: "'a list => 'a list" where
"evens (nil2) = nil2"
| "evens (cons2 y xs) = cons2 y (odds xs)"
| "odds (nil2) = nil2"
| "odds (cons2 y xs) = evens xs"
by pat_completeness auto
theorem property0 :
"((let eta :: Nat = length xs
in ((let md :: Nat = imod eta (S (S Z))
in (if
((case eta of
Z => Z
| S x => (if le eta Z then (case Z of S y => p Z) else S Z) =
(if le (S (S Z)) Z then (case Z of S z => minus Z (p Z)) else
(case Z of S x2 => p Z))) &
(md ~= Z))
then
minus md (S (S Z))
else
md)) =
Z)) ==>
((map
(% (x3 :: ('a, 'a) pair) => (case x3 of pair2 y2 z2 => y2))
(pairs xs)) =
(evens xs)))"
oops
end
|
# plotting half-deep intervals and depth along an assembly
read_scaffold_lengths <- function(lengthsFilename,scaffoldsOfInterest=NULL)
#
# Read a file containing scaffold names and lengths. Result is either
# (a) reduced to scaffolds of interest, in order or (b) sorted by
# decreasing length. A column is added, giving offsets for which the
# scaffolds can be arranged along a number line.
#
# typical input:
# scaffold_100_arrow_ctg1 29829
# scaffold_101_arrow_ctg1 29808
# scaffold_102_arrow_ctg1 28782
# scaffold_103_arrow_ctg1 27584
# scaffold_104_arrow_ctg1 27050
# ...
#
# returns, e.g.
# name length offset
# super_scaffold_1 215872496 0
# super_scaffold_2 165051286 215872496
# scaffold_2_arrow_ctg1 125510139 380923782
# super_scaffold_Z 84526827 506433921
# scaffold_5_arrow_ctg1 82438829 590960748
# ...
#
{
scaffolds = read.table(lengthsFilename,header=F,colClasses=c("character","integer"))
colnames(scaffolds) <- c("name","length")
if (!is.null(scaffoldsOfInterest))
{
# pick ordered subset
scaffolds = scaffolds[scaffolds$name %in% scaffoldsOfInterest,]
scaffoldsToNumber = 1:length(scaffoldsOfInterest)
names(scaffoldsToNumber) = scaffoldsOfInterest
scaffolds = scaffolds[order(scaffoldsToNumber[scaffolds$name]),]
}
else
{
# sort by decreasing length
scaffolds = scaffolds[order(-scaffolds$length),]
}
scaffolds[,"offset"] = rev(sum(as.numeric(scaffolds$length))-cumsum(rev(as.numeric(scaffolds$length))))
scaffolds;
}
linearized_scaffolds <- function(scaffolds)
#
# Create scaffold-to-number-line mapping; input is of the form returned by
# read_scaffold_lengths().
#
{
scaffoldToOffset <- scaffolds$offset
names(scaffoldToOffset) <- scaffolds$name
scaffoldToOffset
}
read_depth <- function(depthFilename,scaffoldToOffset=NULL)
#
# Read a file containing coverage depth. Typically the depth has been
# averaged over non-overlapping windows, with each window represented by
# a single location. Genomic locations are origin-1, and intervals are
# closed.
#
# A scaffold-to-offset can be provided, as would be produced by
# linearized_scaffolds(). Two columns are added, converting each interval
# to positions along a number line.
#
# typical input:
# scaffold_100_arrow_ctg1 1 1 16.727
# scaffold_100_arrow_ctg1 1001 1001 19.365
# scaffold_100_arrow_ctg1 2001 2001 20.701
# scaffold_100_arrow_ctg1 3001 3001 22.764
# scaffold_100_arrow_ctg1 4001 4001 20.971
# ...
#
# returns, e.g.
# scaffold start end depth s e
# scaffold_100_arrow_ctg1 1 1 16.727 1177990031 1177990031
# scaffold_100_arrow_ctg1 1001 1001 19.365 1177991031 1177991031
# scaffold_100_arrow_ctg1 2001 2001 20.701 1177992031 1177992031
# scaffold_100_arrow_ctg1 3001 3001 22.764 1177993031 1177993031
# scaffold_100_arrow_ctg1 4001 4001 20.971 1177994031 1177994031
# ...
#
{
depth = read.table(depthFilename,header=F,colClasses=c("character","integer","integer","numeric"))
colnames(depth) <- c("scaffold","start","end","depth")
if (!is.null(scaffoldToOffset))
{
depth = depth[depth$scaffold %in% names(scaffoldToOffset),]
depth[,"s"] = scaffoldToOffset[depth$scaffold] + depth$start
depth[,"e"] = scaffoldToOffset[depth$scaffold] + depth$end
}
depth
}
read_halfdeep <- function(halfDeepFilename,scaffoldToOffset=NULL)
#
# Read a file containing a list of genomic intervals. The intervals are
# origin-1 and closed.
#
# A scaffold-to-offset can be provided, as would be produced by
# linearized_scaffolds(). Two columns are added, converting each interval
# to positions along a number line.
#
# typical input:
# scaffold_100_arrow_ctg1 9001 10000
# scaffold_101_arrow_ctg1 12001 14000
# scaffold_103_arrow_ctg1 2001 14000
# scaffold_106_arrow_ctg1 1 3000
# scaffold_106_arrow_ctg1 19001 20000
# ...
#
# returns, e.g.
# scaffold start end s e
# scaffold_100_arrow_ctg1 9001 10000 1177999031 1178000030
# scaffold_101_arrow_ctg1 12001 14000 1178031860 1178033859
# scaffold_103_arrow_ctg1 2001 14000 1178110244 1178122243
# scaffold_106_arrow_ctg1 1 3000 1178189381 1178192380
# scaffold_106_arrow_ctg1 19001 20000 1178208381 1178209380
# ...
#
{
halfDeep = read.table(halfDeepFilename,header=F,colClasses=c("character","integer","integer"))
colnames(halfDeep) <- c("scaffold","start","end")
if (!is.null(scaffoldToOffset))
{
halfDeep = halfDeep[halfDeep$scaffold %in% names(scaffoldToOffset),]
halfDeep[,"s"] = scaffoldToOffset[halfDeep$scaffold] + halfDeep$start
halfDeep[,"e"] = scaffoldToOffset[halfDeep$scaffold] + halfDeep$end
}
halfDeep
}
read_percentiles <- function(percentilesFilename)
#
# Extract percentile values from a shell script.
#
# typical input:
# export percentile40=52.698
# export percentile50=54.818
# export percentile60=56.938
# export halfPercentile40=26.349
# export halfPercentile50=27.409
# export halfPercentile60=28.469
#
# returns, e.g.
# percentile40 percentile50 percentile60
# 52.698 54.818 56.938
# halfPercentile40 halfPercentile50 halfPercentile60
# 26.349 27.409 28.469
#
{
percentilesCommand = paste("cat",percentilesFilename,'| sed "s/^export //" | tr "=" " "')
percentiles = read.table(pipe(percentilesCommand),header=F,colClasses=c("character","numeric"))
colnames(percentiles) <- c("name","value")
percentileToValue <- percentiles$value
names(percentileToValue) <- percentiles$name
percentileToValue
}
halfdeep_plot <- function(scaffolds,depth,halfDeep,percentileToValue,
assemblyName="",
scaffoldsToPlot=NULL,
plotFilename=NULL,
tickSpacing=10000000,
width=17,height=7,pointsize=18,
yLabelSpace=7,
maxDepth=NA,
scaffoldInterval=NULL)
#
# Plot half-deep intervals and depth along an assembly
#
# scaffolds: As returned by read_scaffold_lengths().
# depth: As returned by read_depth().
# halfDeep: As returned by read_halfdeep(). If this is NULL,
# no half-deep information is displayed.
# percentileToValue: As returned by read_percentiles()
# assemblyName: Name of the assembly. This contributes to the
# plain title, and can contribute to the plot
# file name.
# Example: "bAlcTor1.pri.cur.20190613"
# scaffoldsToPlot=NULL: A vector of scaffolds to restrict the plot to.
# By default, everything in scaffolds[] is
# plotted.
# plotFilename=NULL: File to plot the data to. If this is NULL, the
# data is plotted on the screen.
# tickSpacing: Spacing of evenly-spaced ticks along the
# horizontal axis. If this is zero, these ticks
# are inhibited. The default is 10Mbp.
# width,height,pointsize: These are passed through to whatever function
# creates the plot window.
# yLabelSpace: Space below the plot. This can be increased to
# accommodate longer scaffold names.
# maxDepth: Depth greater than this is not shown in the plot;
# i.e. the vertical axis stops at this value. By
# default this is 1.5*median depth.
# scaffoldInterval subinterval to restrict the plot to. Typically
# this would only be used when only one scaffold
# is to be plotted. This is a (start,end) pair,
# origin-zero, half-open.
#
{
# if we have a scaffold subset, reduce our copy of the data to that subset
if (!is.null(scaffoldInterval))
stop("scaffoldInterval is not implemented yet")
showHalfDeep = !is.null(halfDeep)
if (!is.null(scaffoldsToPlot))
{
# validate the names in the subset
badNames = scaffoldsToPlot[!(scaffoldsToPlot %in% scaffolds$name)]
if (length(badNames) > 0)
stop(paste("bad scaffold name(s):",paste(scaffoldsToPlot,collapse=", ")))
# pick ordered subset
scaffolds = scaffolds[scaffolds$name %in% scaffoldsToPlot,]
scaffoldsToNumber = 1:length(scaffoldsToPlot)
names(scaffoldsToNumber) = scaffoldsToPlot
scaffolds = scaffolds[order(scaffoldsToNumber[scaffolds$name]),]
scaffolds[,"offset"] = rev(sum(as.numeric(scaffolds$length))-cumsum(rev(as.numeric(scaffolds$length))))
scaffoldToOffset = linearized_scaffolds(scaffolds)
# reduce to ordered subset
depth = depth[depth$scaffold %in% names(scaffoldToOffset),]
depth[,"s"] = scaffoldToOffset[depth$scaffold] + depth$start
depth[,"e"] = scaffoldToOffset[depth$scaffold] + depth$end
if (showHalfDeep)
{
halfDeep = halfDeep[halfDeep$scaffold %in% names(scaffoldToOffset),]
halfDeep[,"s"] = scaffoldToOffset[halfDeep$scaffold] + halfDeep$start
halfDeep[,"e"] = scaffoldToOffset[halfDeep$scaffold] + halfDeep$end
}
}
# fetch percentile values (used only for drawing and labeling)
depth50 = percentileToValue["percentile50"]
halfDepthLo = percentileToValue["halfPercentile40"]
halfDepthHi = percentileToValue["halfPercentile60"]
depthClip = ifelse(is.na(maxDepth),1.5*depth50,maxDepth)
depth50Str = sprintf("%.1f",depth50)
halfDepthLoStr = sprintf("%.1f",halfDepthLo)
halfDepthHiStr = sprintf("%.1f",halfDepthHi)
depthClipStr = sprintf("%.1f",depthClip)
# (housekeeping)
scaffoldTicks = 1 + c(scaffolds$offset,sum(as.numeric(scaffolds$length)))
scaffoldCenters = (as.numeric(scaffoldTicks[1:nrow(scaffolds)])+as.numeric(scaffoldTicks[2:(nrow(scaffolds)+1)])) / 2
if (showHalfDeep)
halfDeepCenters = (as.numeric(halfDeep$s)+as.numeric(halfDeep$e))/2
xlim = c(1,max(scaffoldTicks))
ylim = c(0,depthClip)
depthColor = if (showHalfDeep) rgb(.6,.6,.6) else "black"
halfDepthColor = "black"
halfDeepMarkerColor = "red"
depthLimitsColor = "blue"
guns = col2rgb(halfDeepMarkerColor) / 255
halfDeepOverlayColor = rgb(guns[1],guns[2],guns[3],alpha=.3)
# open plot window or file
turnDeviceOff = F
if (is.null(plotFilename))
{
quartz(width=width,height=height)
}
else
{
print(paste("drawing to",plotFilename))
pdf(file=plotFilename,width=width,height=height,pointsize=pointsize)
turnDeviceOff = T
}
# create empty plot
if (showHalfDeep)
{
title = paste("half-deep intervals (red overlay) in ",assemblyName,
"\nmedian=",depth50Str,
" 40%ile/2=",halfDepthLoStr,
" 60%ile/2=",halfDepthHiStr,
sep="")
ylab = paste("aligned read depth in 1Kbp windows (gray, clipped at ",depthClipStr,")",sep="")
}
else
{
title = paste("coverage depth in ",assemblyName,"\nmedian=",depth50Str,sep="")
ylab = paste("aligned read depth in 1Kbp windows (clipped at ",depthClipStr,")",sep="")
}
par(mar=c(yLabelSpace,4,2.5,0.2)+0.1) # BLTR
options(scipen=10)
plot(NA,xlim=xlim,ylim=ylim,main=title,xaxt="n",xlab="",ylab=ylab)
# add horizontal axis
if ((showHalfDeep) && (nrow(halfDeep) > 0))
{
axis(1,at=halfDeepCenters,labels=F,line=-0.5,col=halfDeepMarkerColor) # interval markers
axis(1,at=c(-0.2*max(scaffoldTicks),1.2*max(scaffoldTicks)),labels=F,line=-0.5,col="white") # erase unwanted horizonal 'axis'
}
if ((tickSpacing > 0) & (xlim[2]>=tickSpacing)) # equal-spaced ticks
axis(1,at=seq(tickSpacing,xlim[2],by=tickSpacing),labels=F,col="gray")
axis(1,at=scaffoldTicks,labels=F,tck=-0.04) # scaffold ticks
axis(1,at=scaffoldCenters,tick=F,labels=scaffolds$name, # scaffold labels
las=2,cex.axis=0.7)
# draw depth as gray, and depth in half-deep intervals as black
points(depth$s,depth$depth,col=depthColor,pch=19,cex=0.3)
if (showHalfDeep)
{
halfsies = (depth$depth>=halfDepthLo) & (depth$depth<=halfDepthHi)
points(depth$s[halfsies],depth$depth[halfsies],col=halfDepthColor,pch=19,cex=0.1)
}
# draw half-deep intervals as red overlay rectangles; note that R often
# does a poor job at filling narrow rectangles, so we also draw each
# rectangle as a centered line; and, because the depth plot will overshoot
# the upper limit, we multiply that limit by 1.2 here
if ((showHalfDeep) && (nrow(halfDeep) > 0))
{
rect(halfDeep$s,ylim[1],halfDeep$e,ylim[2]*1.2,border=NA,col=halfDeepOverlayColor) # LBRT
halfDeepCentersX = matrix(nrow=3,ncol=length(halfDeepCenters))
halfDeepCentersX[1,] = halfDeepCenters
halfDeepCentersX[2,] = halfDeepCenters
halfDeepCentersX[3,] = NA
dim(halfDeepCentersX) = NULL
halfDeepCentersY = matrix(nrow=3,ncol=length(halfDeepCenters))
halfDeepCentersY[1,] = ylim[1]
halfDeepCentersY[2,] = ylim[2]*1.2
halfDeepCentersY[3,] = NA
dim(halfDeepCentersY) = NULL
lines(halfDeepCentersX,halfDeepCentersY,col=halfDeepOverlayColor)
}
# add horizontal lines to show median and half-deep limits
lines(xlim,c(depth50,depth50),col=depthLimitsColor,lwd=2,lty=2)
if (showHalfDeep)
{
lines(xlim,c(halfDepthHi,halfDepthHi),col=depthLimitsColor,lwd=2,lty=2)
lines(xlim,c(halfDepthLo,halfDepthLo),col=depthLimitsColor,lwd=2,lty=2)
}
text(0,depth50,"median ",adj=1,cex=0.7,col=depthLimitsColor)
if (showHalfDeep)
{
text(0,halfDepthLo,"half-40th ",adj=1,cex=0.7,col=depthLimitsColor)
text(0,halfDepthHi,"half-60th ",adj=1,cex=0.7,col=depthLimitsColor)
}
# close the plot
if (turnDeviceOff) dev.off()
}
halfdeep_read_and_plot <- function(lengthsFilename,depthFilename,halfDeepFilename,
percentilesFilename,
plotFilenameTemplate=NULL,
tickSpacing=10000000,
width=17,height=7,pointsize=18,
yLabelSpace=7)
#
# Plot half-deep intervals and depth, for several assemblies
#
{
scaffolds = read_scaffold_lengths(lengthsFilename)
scaffoldToOffset = linearized_scaffolds(scaffolds)
depth = read_depth(depthFilename,scaffoldToOffset)
halfDeep = read_halfdeep(halfDeepFilename,scaffoldToOffset)
percentileToValue = read_percentiles(percentilesFilename)
halfdeep_plot(scaffolds,depth,halfDeep,percentileToValue,assembly,
plotFilenameTemplate=plotFilenameTemplate,
tickSpacing=tickSpacing,
width=width,height=height,pointsize=pointsize,
yLabelSpace=yLabelSpace)
}
read_control_freec <- function(controlFreecFilename,scaffoldToOffset=NULL)
#
# Read a file containing the copy number ouput from ControlFREEC.
#
# A scaffold-to-offset can be provided, as would be produced by
# linearized_scaffolds(). One columns are added, converting each window's
# on-scaffold position to a position along a number line.
#
# typical input:
# Chromosome Start Ratio MedianRatio CopyNumber
# SUPER_2 1 42.2814 22.2608 45
# SUPER_2 1001 31.0994 22.2608 45
# SUPER_2 2001 30.5009 22.2608 45
# SUPER_2 3001 26.9936 22.2608 45
# SUPER_2 4001 33.8109 22.2608 45
# SUPER_2 5001 27.2106 22.2608 45
# ...
#
# returns, e.g.
# scaffold start Ratio MedianRatio CopyNumber s
# SUPER_2 1 42.2814 22.2608 45 200529156
# SUPER_2 1001 31.0994 22.2608 45 200530156
# SUPER_2 2001 30.5009 22.2608 45 200531156
# SUPER_2 3001 26.9936 22.2608 45 200532156
# SUPER_2 4001 33.8109 22.2608 45 200533156
# SUPER_2 5001 27.2106 22.2608 45 200534156
# ...
#
{
controlFreec = read.table(controlFreecFilename,header=T,colClasses=c("character","numeric","numeric","numeric","numeric"))
colnames(controlFreec) <- c("scaffold","start","Ratio","MedianRatio","CopyNumber")
if (!is.null(scaffoldToOffset))
{
controlFreec = controlFreec[controlFreec$scaffold %in% names(scaffoldToOffset),]
controlFreec[,"s"] = scaffoldToOffset[controlFreec$scaffold] + controlFreec$start
}
controlFreec
}
control_freec_plot <- function(scaffolds,depth,controlFreec,percentileToValue,
assemblyName="",
scaffoldsToPlot=NULL,
plotFilename=NULL,
tickSpacing=10000000,
tickLabels=F,
width=17,height=7,pointsize=18,
yLabelSpace=7,
maxDepth=NA,
scaffoldInterval=NULL)
#
# Plot half-deep intervals and depth along an assembly
#
# scaffolds: As returned by read_scaffold_lengths().
# depth: As returned by read_depth().
# controlFreec: As returned by read_control_freec(). If this is
# NULL, no controlFreec copy number information is
# displayed.
# percentileToValue: As returned by read_percentiles()
# assemblyName: Name of the assembly. This contributes to the
# plain title, and can contribute to the plot
# file name.
# Example: "bAlcTor1.pri.cur.20190613"
# scaffoldsToPlot=NULL: A vector of scaffolds to restrict the plot to.
# By default, everything in scaffolds[] is
# plotted.
# plotFilename=NULL: File to plot the data to. If this is NULL, the
# data is plotted on the screen.
# tickSpacing: Spacing of evenly-spaced ticks along the
# horizontal axis. If this is zero, these ticks
# are inhibited. The default is 10Mbp.
# tickLabels: If true, add numeric labels to the horizontal
# axis.
# width,height,pointsize: These are passed through to whatever function
# creates the plot window.
# yLabelSpace: Space below the plot. This can be increased to
# accommodate longer scaffold names.
# maxDepth: Depth greater than this is not shown in the plot;
# i.e. the vertical axis stops at this value. By
# default this is 1.5*median depth.
# scaffoldInterval subinterval to restrict the plot to. Typically
# this would only be used when only one scaffold
# is to be plotted. This is a (start,end) pair,
# origin-zero, half-open.
#
{
# if we have a scaffold subset, reduce our copy of the data to that subset
if (!is.null(scaffoldInterval))
{
if (is.null(scaffoldsToPlot))
{
if (length(scaffoldsToPlot) > 1)
stop("scaffoldInterval cannot be used with more than one scaffold")
}
else
{
if (length(unique(scaffolds$name)) > 1)
stop("scaffoldInterval cannot be used with more than one scaffold")
}
}
showControlFreec = !is.null(controlFreec)
if (is.null(scaffoldsToPlot))
{
scaffoldLen = sum(scaffolds$length)
}
else
{
# validate the names in the subset
badNames = scaffoldsToPlot[!(scaffoldsToPlot %in% scaffolds$name)]
if (length(badNames) > 0)
stop(paste("bad scaffold name(s):",paste(scaffoldsToPlot,collapse=", ")))
# pick ordered subset
scaffolds = scaffolds[scaffolds$name %in% scaffoldsToPlot,]
scaffoldsToNumber = 1:length(scaffoldsToPlot)
names(scaffoldsToNumber) = scaffoldsToPlot
scaffolds = scaffolds[order(scaffoldsToNumber[scaffolds$name]),]
scaffolds[,"offset"] = rev(sum(as.numeric(scaffolds$length))-cumsum(rev(as.numeric(scaffolds$length))))
scaffoldToOffset = linearized_scaffolds(scaffolds)
# reduce to ordered subset
depth = depth[depth$scaffold %in% names(scaffoldToOffset),]
depth[,"s"] = scaffoldToOffset[depth$scaffold] + depth$start
depth[,"e"] = scaffoldToOffset[depth$scaffold] + depth$end
if (showControlFreec)
{
controlFreec = controlFreec[controlFreec$scaffold %in% names(scaffoldToOffset),]
controlFreec[,"s"] = scaffoldToOffset[controlFreec$scaffold] + controlFreec$start
}
scaffoldLen = sum(scaffolds$length[scaffolds$name==scaffoldsToPlot])
}
# fetch percentile values (used only for drawing and labeling)
depth50 = percentileToValue["percentile50"]
halfDepthLo = percentileToValue["halfPercentile40"]
halfDepthHi = percentileToValue["halfPercentile60"]
depthClip = ifelse(is.na(maxDepth),1.5*depth50,maxDepth)
depth50Str = sprintf("%.1f",depth50)
halfDepthLoStr = sprintf("%.1f",halfDepthLo)
halfDepthHiStr = sprintf("%.1f",halfDepthHi)
depthClipStr = sprintf("%.1f",depthClip)
# (housekeeping)
scaffoldTicks = 1 + c(scaffolds$offset,sum(as.numeric(scaffolds$length)))
scaffoldCenters = (as.numeric(scaffoldTicks[1:nrow(scaffolds)])+as.numeric(scaffoldTicks[2:(nrow(scaffolds)+1)])) / 2
CNSpacing = depthClip / 32
if (!is.null(scaffoldInterval))
{
xlim = scaffoldInterval
depth = depth[(depth$s>=xlim[1])&(depth$s<=xlim[2]),]
controlFreec = controlFreec[(controlFreec$s>=xlim[1])&(controlFreec$s<=xlim[2]),]
scaffoldCenters = (scaffoldInterval[1]+scaffoldInterval[2])/2
}
else
{
xlim = c(1,max(scaffoldTicks))
}
ylim = if (showControlFreec) c(-5*CNSpacing,depthClip) else c(0,depthClip)
ylimLong = ylim
ylimLong[1] = ylimLong[1] - CNSpacing
depthColor = rgb(.6,.6,.6)
halfDepthColor = "black"
depthLimitsColor = "blue"
clippedColor = "red"
# clipping
depth$clipped = ifelse(depth$depth<=depthClip,depth$depth,depthClip)
depth$color = ifelse(depth$depth<=depthClip,depthColor,clippedColor)
controlFreec$CNclipped = ifelse(controlFreec$CopyNumber<=2,controlFreec$CopyNumber,3)
# open plot window or file
turnDeviceOff = F
if (is.null(plotFilename))
{
quartz(width=width,height=height,pointsize=pointsize)
}
else
{
print(paste("drawing to",plotFilename))
pdf(file=plotFilename,width=width,height=height,pointsize=pointsize)
turnDeviceOff = T
}
# create empty plot
if (assemblyName == "")
title = paste("Copy Number\n(per ControlFREEC)",sep="")
else
title = paste("Copy Number on ",assemblyName,"\n(per ControlFREEC)",sep="")
ylab = "depth (black/gray) and CN (blue/red)"
par(mar=c(yLabelSpace,4,2.5,0.2)+0.1) # BLTR
options(scipen=10)
plot(NA,xlim=xlim,ylim=ylim,main=title,xaxt="n",xlab="",ylab=ylab)
# add horizontal axis
if ((tickSpacing > 0) & (xlim[2]>=tickSpacing)) # equal-spaced ticks
{
leftTick = xlim[1] + (tickSpacing-1) - ((xlim[1] + (tickSpacing-1)) %% tickSpacing)
ticks = seq(leftTick,xlim[2],by=tickSpacing)
axis(1,at=ticks,labels=F,col="gray")
if (tickLabels)
{
labeledTicks = ticks[abs(scaffoldCenters-ticks)>=tickSpacing/4]
axis(1,at=labeledTicks,tick=F, # tick labels
labels=prettyNum(labeledTicks,big.mark=",",scientific=FALSE),
las=2,pos=ylim[1]-0.5,cex.axis=0.5)
}
}
axis(1,at=scaffoldTicks,labels=F,tck=-0.08) # scaffold ticks
axis(1,at=scaffoldCenters,tick=F,labels=scaffolds$name, # scaffold labels
las=2,cex.axis=0.7)
# draw depth as gray, and depth in half-deep intervals as black
points(depth$s,depth$clipped,col=depth$color,pch=19,cex=0.3)
halfsies = (depth$depth>=halfDepthLo) & (depth$depth<=halfDepthHi)
points(depth$s[halfsies],depth$depth[halfsies],col=halfDepthColor,pch=19,cex=0.1)
for (ix in 1:length(scaffoldTicks))
lines(c(scaffoldTicks[ix],scaffoldTicks[ix]),ylimLong,col="black",lwd=1,lty=2)
# add horizontal lines to show median and half-deep limits
lines(xlim,c(depth50,depth50),col=depthLimitsColor,lwd=2,lty=2)
lines(xlim,c(halfDepthHi,halfDepthHi),col=depthLimitsColor,lwd=2,lty=2)
lines(xlim,c(halfDepthLo,halfDepthLo),col=depthLimitsColor,lwd=2,lty=2)
text(xlim[1],depth50, "median ", adj=1,cex=0.5,col=depthLimitsColor)
text(xlim[1],halfDepthLo,"half-40th ",adj=1,cex=0.5,col=depthLimitsColor)
text(xlim[1],halfDepthHi,"half-60th ",adj=1,cex=0.5,col=depthLimitsColor)
# add controlFreec copy number information
# from bottom up, rows are copy number = 0, 1, 2, >2
if (showControlFreec)
{
for (cn in -2:-5)
{
lines(xlim,c(cn*CNSpacing,cn*CNSpacing),col="red",lty=1)
text(xlim[1]-0.005*(xlim[2]-xlim[1]),cn*CNSpacing,cex=0.4,adj=1,
ifelse(cn==-2,"CN>2",paste("CN=",cn+5,sep="")))
}
points(controlFreec$s,(controlFreec$CNclipped-5)*CNSpacing,pch=16,cex=0.5,
col=ifelse(controlFreec$CNclipped==1,"blue","red"))
}
# close the plot
if (turnDeviceOff) dev.off()
}
|
[STATEMENT]
lemma cf_lcomp_ArrMap_vdomain[cat_cs_simps]:
assumes "category \<alpha> \<CC>" and "\<FF> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<BB>"
shows "\<D>\<^sub>\<circ> (cf_lcomp \<CC> \<SS> \<FF>\<lparr>ArrMap\<rparr>) = (\<AA> \<times>\<^sub>C \<CC>)\<lparr>Arr\<rparr>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<D>\<^sub>\<circ> (cf_lcomp \<CC> \<SS> \<FF>\<lparr>ArrMap\<rparr>) = (\<AA> \<times>\<^sub>C \<CC>)\<lparr>Arr\<rparr>
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
category \<alpha> \<CC>
\<FF> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<BB>
goal (1 subgoal):
1. \<D>\<^sub>\<circ> (cf_lcomp \<CC> \<SS> \<FF>\<lparr>ArrMap\<rparr>) = (\<AA> \<times>\<^sub>C \<CC>)\<lparr>Arr\<rparr>
[PROOF STEP]
unfolding cf_lcomp_def
[PROOF STATE]
proof (prove)
using this:
category \<alpha> \<CC>
\<FF> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<BB>
goal (1 subgoal):
1. \<D>\<^sub>\<circ> (cf_bcomp \<SS> \<FF> (dghm_id \<CC>)\<lparr>ArrMap\<rparr>) = (\<AA> \<times>\<^sub>C \<CC>)\<lparr>Arr\<rparr>
[PROOF STEP]
by (cs_concl cs_simp: cat_cs_simps cs_intro: cat_cs_intros) |
lemma homotopic_loops_linear: fixes g h :: "real \<Rightarrow> 'a::real_normed_vector" assumes "path g" "path h" "pathfinish g = pathstart g" "pathfinish h = pathstart h" "\<And>t x. t \<in> {0..1} \<Longrightarrow> closed_segment (g t) (h t) \<subseteq> S" shows "homotopic_loops S g h" |
{-# OPTIONS --cubical --safe --postfix-projections #-}
module Relation.Nullary.Decidable.Logic where
open import Prelude
open import Data.Sum
infixl 7 _&&_
_&&_ : Dec A → Dec B → Dec (A × B)
(x && y) .does = x .does and y .does
(yes x && yes y) .why = ofʸ (x , y)
(yes x && no y) .why = ofⁿ (y ∘ snd)
(no x && y) .why = ofⁿ (x ∘ fst)
infixl 6 _||_
_||_ : Dec A → Dec B → Dec (A ⊎ B)
(x || y) .does = x .does or y .does
(yes x || y) .why = ofʸ (inl x)
(no x || yes y) .why = ofʸ (inr y)
(no x || no y) .why = ofⁿ (either x y)
! : Dec A → Dec (¬ A)
! x .does = not (x .does)
! (yes x) .why = ofⁿ (λ z → z x)
! (no x) .why = ofʸ x
|
__author__ = 'sibirrer'
import numpy as np
import pytest
import numpy.testing as npt
class TestCSP(object):
"""
tests the cored steep ellipsoid (CSE)
"""
def setup(self):
from lenstronomy.LensModel.Profiles.cored_steep_ellipsoid import CSE
self.CSP = CSE()
def test_function(self):
kwargs = {'a': 2, 's': 1, 'e1': 0., 'e2': 0., 'center_x': 0, 'center_y': 0}
x = np.array([1., 2])
y = np.array([2, 0])
f_ = self.CSP.function(x, y, **kwargs)
npt.assert_almost_equal(f_, [1.09016, 0.96242], decimal=5)
def test_derivatives(self):
kwargs = {'a': 2, 's': 1, 'e1': 0., 'e2': 0., 'center_x': 0, 'center_y': 0}
x = np.array([1., 2])
y = np.array([2, 0])
f_x, f_y = self.CSP.derivatives(x, y, **kwargs)
npt.assert_almost_equal(f_x, [0.2367, 0.55279], decimal=5)
npt.assert_almost_equal(f_y, [0.4734, 0.], decimal=5)
def test_hessian(self):
kwargs = {'a': 2, 's': 1, 'e1': 0., 'e2': 0., 'center_x': 0, 'center_y': 0}
x = np.array([1., 2])
y = np.array([2, 0])
f_xx, f_xy, f_yx, f_yy = self.CSP.hessian(x, y, **kwargs)
npt.assert_almost_equal(f_xy, f_yx, decimal=5)
npt.assert_almost_equal(f_xx, [0.16924, -0.09751], decimal=5)
npt.assert_almost_equal(f_xy, [-0.13493, -0.], decimal=5)
npt.assert_almost_equal(f_yy, [-0.03315, 0.27639], decimal=5)
if __name__ == '__main__':
pytest.main()
|
[STATEMENT]
lemma sdistinct_coinduct[case_names sdistinct, coinduct pred: sdistinct]:
assumes "P xs"
assumes "\<And> x xs. P (x ## xs) \<Longrightarrow> x \<notin> sset xs \<and> P xs"
shows "sdistinct xs"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sdistinct xs
[PROOF STEP]
using stream.collapse sdistinct.coinduct assms
[PROOF STATE]
proof (prove)
using this:
shd ?stream ## stl ?stream = ?stream
\<lbrakk>?X ?x; \<And>x. ?X x \<Longrightarrow> \<exists>xa xs. x = xa ## xs \<and> xa \<notin> sset xs \<and> (?X xs \<or> sdistinct xs)\<rbrakk> \<Longrightarrow> sdistinct ?x
P xs
P (?x ## ?xs) \<Longrightarrow> ?x \<notin> sset ?xs \<and> P ?xs
goal (1 subgoal):
1. sdistinct xs
[PROOF STEP]
by metis |
Describe Users/LissaVadnais here.
20101025 15:40:59 nbsp Hi Lissa, and Welcome to the Wiki! Are you an owner/employee of Lamppost Pizza? If so, its worth having a look at the Welcome to the Wiki/Business Owner business owner welcome page for useful information on wiki norms relating to business pages.
The standard welcome rigmarole out of the way, Im excited to hear about breakfast. Is there a separate breakfast menu at Lamppost, or is it the usual fare with expanded hours? Users/TomGarberson
20101025 16:29:57 nbsp Wooo, thats exciting! Ill have to check it out. Users/TomGarberson
|
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
Class(RulesSMP, RuleSet);
RewriteRules(RulesSMP, rec(
PSD_SMPSumRight := ARule(Compose, [ @(1, [RCDiag, Diag, Prm, Scat, FormatPrm]), @(2, SMPSum) ],
e -> let(s:=@(2).val, [ SMPSum(s.nthreads, s.tid, s.var, s.domain, @(1).val * s.child(1)) ])),
PGD_SMPSumLeft := ARule(Compose, [ @(1, SMPSum), @(2, [Prm, Gath, Diag, RCDiag, FormatPrm]) ],
e -> let(s:=@(1).val, [ SMPSum(s.nthreads, s.tid, s.var, s.domain, s.child(1) * @(2).val) ])),
PSD_SMPBarrierRight := ARule(Compose, [ @(1, [RCDiag, Diag, Prm, Scat, FormatPrm]), @(2, SMPBarrier) ],
e -> let(s:=@(2).val, [ SMPBarrier(s.nthreads, s.tid, @(1).val * s.child(1)) ])),
PGD_SMPBarrierLeft := ARule(Compose, [ @(1, SMPBarrier), @(2, [Prm, Gath, Diag, RCDiag, FormatPrm]) ],
e -> let(s:=@(1).val, [ SMPBarrier(s.nthreads, s.tid, s.child(1) * @(2).val) ])),
Drop_GrpSPSum := Rule([Grp, @(1, SMPSum)], e -> @(1).val),
Drop_GrpISum := Rule([Grp, @(1, ISum)], e -> @(1).val),
SMP_ISum := Rule([SMP, @(1), @(2), @(3, ISum)], e ->
SMPSum(@(1).val, @(2).val, @(3).val.var, @(3).val.domain, @(3).val.child(1))),
));
RewriteRules(RulesRC, rec(
RC_SMPSum := Rule([RC, @(1, SMPSum)],
e -> let(s:=@(1).val, SMPSum(s.nthreads, s.tid, s.var, s.domain, RC(s.child(1))))),
RC_SMPBarrier := Rule([RC, @(1, SMPBarrier)],
e -> let(s:=@(1).val, SMPBarrier(s.nthreads, s.tid, RC(s.child(1))))),
));
|
The factory where the incident took place is the <unk> ( " Early Light " ) Toy Factory ( <unk> ) , owned by Hong Kong @-@ based Early Light International ( Holdings ) Ltd . , the largest toy manufacturer in the world . The company 's Shaoguan factory in the <unk> district employs some 16 @,@ 000 workers . At the behest of the Guangdong authorities , it hired 800 workers from Kashgar , in Xinjiang as part of an ethnic program which relocated 200 @,@ 000 young Uyghurs since the start of 2008 . According to The Guardian , most workers sign a one- to three @-@ year contract then travel to factory dormitories in the south ; in addition to their salaries ranging from 1 @,@ 000 yuan to 1 @,@ 400 yuan a month , many get free board and lodging . Most of these <unk> are away from home to work for the first time . The Far Eastern Economic Review said Guangdong authorities initiated a controversial plan to ship [ Uyghur ] workers to Guangdong factories amid continuing labour shortages . The young workers , whose families have charged that they were forced to send their children south , often lack even basic Chinese language skills and find it difficult to fit in with the dominant Han culture . " The New York Times quoted Xinjiang Daily saying in May that 70 percent of the young Uyghurs had " signed up for employment voluntarily . " However , Kashgar residents say the families of those who refuse to go are threatened with fines of up to six months ' worth of a villager 's income .
|
function [lat, lon, gam, k] = tranmerc_inv(lat0, lon0, x, y, ellipsoid)
%TRANMERC_INV Inverse transverse Mercator projection
%
% [LAT, LON] = TRANMERC_INV(LAT0, LON0, X, Y)
% [LAT, LON, GAM, K] = TRANMERC_INV(LAT0, LON0, X, Y, ELLIPSOID)
%
% performs the inverse transverse Mercator projection of points (X,Y) to
% (LAT,LON) using (LAT0,LON0) as the center of projection. These input
% arguments can be scalars or arrays of equal size. The ELLIPSOID vector
% is of the form [a, e], where a is the equatorial radius in meters, e is
% the eccentricity. If ellipsoid is omitted, the WGS84 ellipsoid (more
% precisely, the value returned by DEFAULTELLIPSOID) is used. GEODPROJ
% defines the projection and gives the restrictions on the allowed ranges
% of the arguments. The forward projection is given by TRANMERC_FWD.
%
% GAM and K give metric properties of the projection at (LAT,LON); GAM is
% the meridian convergence at the point and K is the scale.
%
% LAT0, LON0, LAT, LON, GAM are in degrees. The projected coordinates X,
% Y are in meters (more precisely the units used for the equatorial
% radius). K is dimensionless.
%
% This implementation of the projection is based on the series method
% described in
%
% C. F. F. Karney, Transverse Mercator with an accuracy of a few
% nanometers, J. Geodesy 85(8), 475-485 (Aug. 2011);
% Addenda: http://geographiclib.sf.net/tm-addenda.html
%
% This extends the series given by Krueger (1912) to sixth order in the
% flattening. This is a substantially better series than that used by
% the MATLAB mapping toolbox. In particular the errors in the projection
% are less than 5 nanometers withing 3900 km of the central meridian (and
% less than 1 mm within 7600 km of the central meridian). The mapping
% can be continued accurately over the poles to the opposite meridian.
%
% This routine depends on the MATLAB File Exchange package "Geodesics on
% an ellipsoid of revolution":
%
% http://www.mathworks.com/matlabcentral/fileexchange/39108
%
% See also GEODPROJ, TRANMERC_FWD, GEODRECKON, DEFAULTELLIPSOID.
% Copyright (c) Charles Karney (2012) <[email protected]>.
%
% This file was distributed with GeographicLib 1.29.
if nargin < 4, error('Too few input arguments'), end
if nargin < 5, ellipsoid = defaultellipsoid; end
try
Z = lat0 + lon0 + x + y;
Z = zeros(size(Z));
catch err
error('lat0, lon0, x, y have incompatible sizes')
end
if length(ellipsoid(:)) ~= 2
error('ellipsoid must be a vector of size 2')
end
degree = pi/180;
maxpow = 6;
a = ellipsoid(1);
f = ecc2flat(ellipsoid(2));
e2 = f * (2 - f);
e2m = 1 - e2;
cc = sqrt(e2m) * exp(e2 * atanhee(1, e2));
n = f / (2 -f);
bet = betf(n);
b1 = (1 - f) * (A1m1f(n) + 1);
a1 = b1 * a;
if isscalar(lat0) && lat0 == 0
y0 = 0;
else
[sbet0, cbet0] = SinCosNorm((1-f) * sind(lat0), cosd(lat0));
y0 = a1 * (atan2(sbet0, cbet0) + ...
SinCosSeries(true, sbet0, cbet0, C1f(n)));
end
y = y + y0;
xi = y / a1;
eta = x / a1;
xisign = 1 - 2 * (xi < 0 );
etasign = 1 - 2 * (eta < 0 );
xi = xi .* xisign;
eta = eta .* etasign;
backside = xi > pi/2;
xi(backside) = pi - xi(backside);
c0 = cos(2 * xi); ch0 = cosh(2 * eta);
s0 = sin(2 * xi); sh0 = sinh(2 * eta);
ar = 2 * c0 .* ch0; ai = -2 * s0 .* sh0;
j = maxpow;
xip0 = Z; yr0 = Z;
if mod(j, 2)
xip0 = xip0 + bet(j);
yr0 = yr0 - 2 * maxpow * bet(j);
j = j - 1;
end
xip1 = Z; etap0 = Z; etap1 = Z;
yi0 = Z; yr1 = Z; yi1 = Z;
for j = j : -2 : 1
xip1 = ar .* xip0 - ai .* etap0 - xip1 - bet(j);
etap1 = ai .* xip0 + ar .* etap0 - etap1;
yr1 = ar .* yr0 - ai .* yi0 - yr1 - 2 * j * bet(j);
yi1 = ai .* yr0 + ar .* yi0 - yi1;
xip0 = ar .* xip1 - ai .* etap1 - xip0 - bet(j-1);
etap0 = ai .* xip1 + ar .* etap1 - etap0;
yr0 = ar .* yr1 - ai .* yi1 - yr0 - 2 * (j-1) * bet(j-1);
yi0 = ai .* yr1 + ar .* yi1 - yi0;
end
ar = ar/2; ai = ai/2;
yr1 = 1 - yr1 + ar .* yr0 - ai .* yi0;
yi1 = - yi1 + ai .* yr0 + ar .* yi0;
ar = s0 .* ch0; ai = c0 .* sh0;
xip = xi + ar .* xip0 - ai .* etap0;
etap = eta + ai .* xip0 + ar .* etap0;
gam = atan2(yi1, yr1);
k = b1 ./ hypot(yr1, yi1);
s = sinh(etap);
c = max(0, cos(xip));
r = hypot(s, c);
lam = atan2(s, c);
taup = sin(xip)./r;
tau = tauf(taup, e2);
phi = atan(tau);
gam = gam + atan(tan(xip) .* tanh(etap));
c = r ~= 0;
k(c) = k(c) .* sqrt(e2m + e2 * cos(phi(c)).^2) .* ...
hypot(1, tau(c)) .* r(c);
c = ~c;
if any(c)
phi(c) = pi/2;
lam(c) = 0;
k(c) = k(c) * cc;
end
lat = phi / degree .* xisign;
lon = lam / degree;
lon(backside) = 180 - lon(backside);
lon = lon .* etasign;
lon = AngNormalize(lon + AngNormalize(lon0));
gam = gam/degree;
gam(backside) = 180 - gam(backside);
gam = gam .* xisign .* etasign;
end
function bet = betf(n)
bet = zeros(1,6);
nx = n^2;
bet(1) = n*(n*(n*(n*(n*(384796*n-382725)-6720)+932400)-1612800)+ ...
1209600)/2419200;
bet(2) = nx*(n*(n*((1695744-1118711*n)*n-1174656)+258048)+80640)/ ...
3870720;
nx = nx * n;
bet(3) = nx*(n*(n*(22276*n-16929)-15984)+12852)/362880;
nx = nx * n;
bet(4) = nx*((-830251*n-158400)*n+197865)/7257600;
nx = nx * n;
bet(5) = (453717-435388*n)*nx/15966720;
nx = nx * n;
bet(6) = 20648693*nx/638668800;
end
function tau = tauf(taup, e2)
overflow = 1/eps^2;
tol = 0.1 * sqrt(eps);
numit = 5;
e2m = 1 - e2;
tau = taup / e2m;
stol = tol * max(1, abs(taup));
g = ~(abs(taup) < overflow);
tau(g) = taup(g);
g = ~g;
for i = 1 : numit
if ~any(g), break, end
tau1 = hypot(1, tau);
sig = sinh(e2 * atanhee( tau ./ tau1, e2 ) );
taupa = hypot(1, sig) .* tau - sig .* tau1;
dtau = (taup - taupa) .* (1 + e2m .* tau.^2) ./ ...
(e2m * tau1 .* hypot(1, taupa));
tau(g) = tau(g) + dtau(g);
g = g & abs(dtau) >= stol;
end
end
|
(* Title: HOL/Auth/n_germanSymIndex_lemma_inv__14_on_rules.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_germanSymIndex Protocol Case Study*}
theory n_germanSymIndex_lemma_inv__14_on_rules imports n_germanSymIndex_lemma_on_inv__14
begin
section{*All lemmas on causal relation between inv__14*}
lemma lemma_inv__14_on_rules:
assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__14 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_StoreVsinv__14) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqSVsinv__14) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqE__part__0Vsinv__14) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqE__part__1Vsinv__14) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqSVsinv__14) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqEVsinv__14) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__14) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__14) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInvAckVsinv__14) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__14) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntSVsinv__14) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntEVsinv__14) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntSVsinv__14) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntEVsinv__14) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
|
State Before: α : Type u
β : Type v
δ : Type w
x y : α
s t : Stream' α
h : x :: s = y :: t
⊢ x = y State After: no goals Tactic: rw [← nth_zero_cons x s, h, nth_zero_cons] State Before: α : Type u
β : Type v
δ : Type w
x y : α
s t : Stream' α
h : x :: s = y :: t
n : ℕ
⊢ nth s n = nth t n State After: no goals Tactic: rw [← nth_succ_cons n _ x, h, nth_succ_cons] |
import math
import numpy as np
import sys
import time
from dime import DimeClient
d = DimeClient("ipc", sys.argv[1]);
d.join("python");
while "matlab" not in d.devices():
time.sleep(0.05)
time.sleep(1)
d.sync()
assert d["nothing"] is None
assert d["boolean"] is True
assert d["float"] == math.pi
assert d["int"] == 0xDEADBEEF
assert d["complexfloat"] == complex(math.sqrt(0.75), 0.5)
assert np.array_equal(d["matrix"], np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9.01]]))
assert d["string"] == "Hello world!"
assert d["sequence"] == [-1, ":)", False, None]
assert d["mapping"] == {"foo": 2, "bar": "Green eggs and spam"}
d.send("matlab", "nothing", "boolean", "int", "float", "complexfloat", "matrix", "string", "sequence", "mapping");
|
module Prelude.Basics
import Builtin
import Prelude.Ops
%default total
public export
Not : Type -> Type
Not x = x -> Void
-----------------------
-- UTILITY FUNCTIONS --
-----------------------
||| Manually assign a type to an expression.
||| @ a the type to assign
||| @ x the element to get the type
public export %inline
the : (0 a : Type) -> (x : a) -> a
the _ x = x
||| Identity function.
public export %inline
id : (x : a) -> a
id x = x
||| Function that duplicates its input
public export
dup : a -> (a, a)
dup x = (x, x)
||| Constant function. Ignores its second argument.
public export %inline
const : a -> b -> a
const x = \value => x
||| Function composition.
public export %inline
(.) : (b -> c) -> (a -> b) -> a -> c
(.) f g = \x => f (g x)
||| Composition of a two-argument function with a single-argument one.
||| `(.:)` is like `(.)` but the second argument and the result are two-argument functions.
||| This operator is also known as "blackbird operator".
public export %inline
(.:) : (c -> d) -> (a -> b -> c) -> a -> b -> d
(.:) = (.) . (.)
||| `on b u x y` runs the binary function b on the results of applying
||| unary function u to two arguments x and y. From the opposite perspective,
||| it transforms two inputs and combines the outputs.
|||
||| ```idris example
||| ((+) `on` f) x y = f x + f y
||| ```
|||
||| Typical usage:
|||
||| ```idris example
||| sortBy (compare `on` fst).
||| ```
public export
on : (b -> b -> c) -> (a -> b) -> a -> a -> c
on f g = \x, y => g x `f` g y
infixl 0 `on`
||| Takes in the first two arguments in reverse order.
||| @ f the function to flip
public export
flip : (f : a -> b -> c) -> b -> a -> c
flip f x y = f y x
||| Function application.
public export
apply : (a -> b) -> a -> b
apply f a = f a
public export
curry : ((a, b) -> c) -> a -> b -> c
curry f a b = f (a, b)
public export
uncurry : (a -> b -> c) -> (a, b) -> c
uncurry f (a, b) = f a b
-- $ is compiled specially to shortcut any tricky unification issues, but if
-- it did have a type this is what it would be, and it might be useful to
-- use directly sometimes (e.g. in higher order functions)
public export
($) : forall a, b . ((x : a) -> b x) -> (x : a) -> b x
($) f a = f a
-------------------
-- PROOF HELPERS --
-------------------
||| Equality is a congruence.
public export
cong : (0 f : t -> u) -> (p : a = b) -> f a = f b
cong f Refl = Refl
||| Two-holed congruence.
export
-- These are natural in equational reasoning.
cong2 : (0 f : t1 -> t2 -> u) -> (p1 : a = b) -> (p2 : c = d) -> f a c = f b d
cong2 f Refl Refl = Refl
||| Irrelevant equalities can always be made relevant
export
irrelevantEq : (0 _ : a === b) -> a === b
irrelevantEq Refl = Refl
--------------
-- BOOLEANS --
--------------
||| Boolean Data Type.
public export
data Bool = False | True
||| Boolean NOT.
%inline
public export
not : (b : Bool) -> Bool
not True = False
not False = True
||| Boolean AND only evaluates the second argument if the first is `True`.
%inline
public export
(&&) : (b : Bool) -> Lazy Bool -> Bool
(&&) True x = x
(&&) False x = False
||| Boolean OR only evaluates the second argument if the first is `False`.
%inline
public export
(||) : (b : Bool) -> Lazy Bool -> Bool
(||) True x = True
(||) False x = x
||| Non-dependent if-then-else
%inline
public export
ifThenElse : (b : Bool) -> Lazy a -> Lazy a -> a
ifThenElse True l r = l
ifThenElse False l r = r
%inline
public export
intToBool : Int -> Bool
intToBool 0 = False
intToBool x = True
--------------
-- LISTS --
--------------
||| Generic lists.
public export
data List a =
||| Empty list
Nil
| ||| A non-empty list, consisting of a head element and the rest of the list.
(::) a (List a)
%name List xs, ys, zs
||| Snoc lists.
public export
data SnocList a =
||| Empty snoc-list
Lin
| ||| A non-empty snoc-list, consisting of the rest of the snoc-list and the final element.
(:<) (SnocList a) a
%name SnocList sx, sy, sz
|
lemma Bseq_conv_Bfun: "Bseq X \<longleftrightarrow> Bfun X sequentially" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.