text
stringlengths 0
3.34M
|
---|
(*|
################################################
Local ``Inductive`` definitions and ``Theorems``
################################################
:Link: https://stackoverflow.com/q/36235244
|*)
(*|
Question
********
I'm using a couple of ``Inductive`` definitions as counter examples in
some proofs. I would however like to encapsulate these definitions by
enclosing them in a ``Section``. Regular ``Definitions`` can be hidden
using ``Let``, but is this also possible for ``Inductive``
definitions? And how about ``Theorem``\ s?
Let me give the actual thing I'm trying to achieve, as I may be going
about it totally the wrong way in the first place. I want to formalize
all the proofs and exercises of the excellent book "Logics of Time and
Computation" by Robert Goldblatt into Coq.
For starters we take classical logic as that is what the book does as
well.
|*)
Require Import Classical_Prop.
Require Import Classical_Pred_Type.
(*|
Next we define identifiers the same way it is done in Software
Foundations.
|*)
Inductive id : Type := Id : nat -> id.
(*| Definition of the syntax. |*)
Inductive modal : Type :=
| Bottom : modal
| V : id -> modal
| Imp : modal -> modal -> modal
| Box : modal -> modal.
Definition Not (f : modal) : modal := Imp f Bottom.
(*| Definition of the semantics using Kripke frames. |*)
(* Inspired by: www.cs.vu.nl/~tcs/mt/dewind.ps.gz *)
Record frame : Type :=
{ Worlds : Type
; WorldsExist : exists w : Worlds, True
; Rel : Worlds -> Worlds -> Prop }.
Record kripke : Type :=
{ Frame : frame
; Label : (Worlds Frame) -> id -> Prop }.
Fixpoint satisfies (M : kripke) (x : Worlds (Frame M)) (f : modal) : Prop :=
match f with
| Bottom => False
| V v => Label M x v
| Imp f1 f2 => satisfies M x f1 -> satisfies M x f2
| Box f => forall y : Worlds (Frame M), Rel (Frame M) x y -> satisfies M y f
end.
(*| The first lemma relates the modal ``Not`` to the one of Coq. |*)
Lemma satisfies_Not : forall M x f, satisfies M x (Not f) = ~ satisfies M x f.
Proof. auto. Qed.
(*| Next we lift the semantics to complete models. |*)
Definition M_satisfies (M : kripke) (f : modal) : Prop :=
forall w : Worlds (Frame M), satisfies M w f.
(*| And we show what it means for the ``Not`` connective. |*)
Lemma M_satisfies_Not : forall M f, M_satisfies M (Not f) -> ~ M_satisfies M f.
Proof.
unfold M_satisfies.
intros M f Hn Hcontra.
destruct (WorldsExist (Frame M)).
specialize (Hn x). clear H.
rewrite satisfies_Not in Hn.
specialize (Hcontra x). auto.
Qed.
(*|
Here comes the thing. The reverse of the above lemma does not hold and
I want to show this by a counter example, exhibiting a model for which
it doesn't hold.
|*)
Inductive Wcounter : Set := x1 : Wcounter | x2 : Wcounter | x3 : Wcounter.
Lemma Wcounter_not_empty : exists w : Wcounter, True.
Proof. exists x1. constructor. Qed.
Inductive Rcounter (x : Wcounter) (y : Wcounter) : Prop :=
| E1 : x = x1 -> y = x2 -> Rcounter x y
| E2 : x = x2 -> y = x3 -> Rcounter x y.
Definition Lcounter : Wcounter -> id -> Prop :=
fun x i => match x with
| x1 => match i with | Id 0 => True | _ => False end
| x2 => match i with | Id 1 => True | _ => False end
| x3 => match i with | Id 0 => True | _ => False end
end.
Definition Fcounter : frame := Build_frame Wcounter Wcounter_not_empty Rcounter.
Definition Kcounter : kripke := Build_kripke Fcounter Lcounter.
(*|
Next an ``Ltac`` that relieves me from typing verbose ``assert``\ s.
|*)
Ltac counter_example H Hc :=
match type of H with
| ?P -> ~ ?Q => assert (Hc: Q)
| ?P -> (?Q -> False) => assert (Hc: Q)
| ?P -> ?Q => assert (Hc: ~Q)
end.
(*|
Finally I use this counter example to prove the following ``Lemma``.
|*)
Lemma M_not_satisfies_Not :
~ forall M f, ~ M_satisfies M f -> M_satisfies M (Not f).
Proof.
apply ex_not_not_all. exists Kcounter.
apply ex_not_not_all. exists (V (Id 0)).
unfold M_satisfies. simpl.
intro Hcontra. unfold not in Hcontra.
counter_example Hcontra Hn2.
- apply ex_not_not_all. exists x1. simpl. auto.
- apply Hn2. apply Hcontra. apply ex_not_not_all; exists x2. simpl. auto.
Qed.
(*|
Preferably I would have used the ``remember`` tactic to define the
counter example inside the proof, but I don't think it can be used for
the ``Inductive`` definitions. All the definitions relating to the
counter example are exported as part of my theory, which I prefer not
to do. It is only used in the proof of ``M_not_satisfies_Not``.
Actually I would not even want to export this ``Lemma`` either as it
is not very useful. I only put it there to argue that
``M_satisfies_Not`` can not be an equivalence.
|*)
(*|
Answer
******
``Section`` doesn't hide definitions, use ``Module`` instead. For
example put the counter example in a module.
.. code-block:: coq
Module CounterExample.
Import Definitions.
Inductive Wcounter : Set := x1 | x2 | x3.
...
Lemma M_not_satisfies_Not : ...
End CounterExample.
At this stage, only ``CounterExample`` is defined at the top level.
If you don't want that either, then you could just put the definitions
in one ``.v`` file and the counter example in another file that
imports the definitions. Actually, the way it works is that ``.v``
files are turned into individual modules.
|*)
|
The AoT board also granted 200 million baht to the Army , which had requested a financial donation . AoT also lent some of its explosives detectors to the Army for use in the South Thailand insurrection .
|
Foam Flower (Tiarella cordifolia), is one of nearly 700 members of the Saxifragaceae family whose members are native to the moist shady woodlands of North American and eastern Asia; this clumpforming perennial herb blooms from April to June when it reaches its maximum height of 612 inches. The genus name Tiarella is derived from the Greek Tiara, a term for a turban worn by ancient Persians and is reminiscent of the shape of the pistil.
It is an attractive perennial with leafy stems from 612 inches high and numerous mapleshaped basal leaves. The basal leaves are up to 12 cm wide and 8 cm long with a heartshaped base. The upper leaves are similar but smaller with shorter petioles and only 3 lobes. The single or clustered stems are erect or spreading. The inflorescence is an open raceme grouped in a foamlike cluster of tiny starry white or pink flowers. The shallow root system of this plant makes a happy companion of deep rooted plants. Propagation is by division or cuttings.
This plant has a high tannin content making it a natural astringent. Native Americans made leaf tea to cure mouth sores and eye ailments. Root tea was used to treat diarrhea, as well as made into a poultice for topical wounds.
For a listing of other plants found growing in Davis, visit our Town Flora.
|
(* Title: HOL/Auth/n_flash_lemma_on_inv__127.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_flash Protocol Case Study*}
theory n_flash_lemma_on_inv__127 imports n_flash_base
begin
section{*All lemmas on causal relation between inv__127 and some rule r*}
lemma n_PI_Remote_PutXVsinv__127:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_PI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_ReplaceVsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Replace src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_HeadVsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_PutVsinv__127:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_Put_HomeVsinv__127:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_1Vsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_2Vsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_3Vsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_4Vsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_5Vsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_6Vsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__127:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__127:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__127:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutXVsinv__127:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutX_HomeVsinv__127:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutVsinv__127:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "((formEval (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true)) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (neg (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutXVsinv__127:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv3)) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_InvVsinv__127:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Inv dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_ReplaceVsinv__127:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Replace src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Replace src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) s))"
have "?P2 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__127:
assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__0 N )" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__127:
assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__1 N )" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_ShWbVsinv__127:
assumes a1: "(r=n_NI_ShWb N )" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4" apply fastforce done
have "((formEval (andForm (eqn (Const (index p__Inv3)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc''))) (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) s))\<or>((formEval (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv3)) (Const true)) s))\<or>((formEval (andForm (neg (eqn (Const (index p__Inv3)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc'')))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv3)) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv3)) (Const true)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (Const (index p__Inv3)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc''))) (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) s))"
have "?P3 s"
apply (cut_tac a1 a2 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Cmd'')) (Const SHWB_ShWb))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv3)) (Const true)) s))"
have "?P3 s"
apply (cut_tac a1 a2 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv3)) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (neg (eqn (Const (index p__Inv3)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc'')))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv3)) (Const true)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv3)) (Const true)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_GetVsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__0Vsinv__127:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_WbVsinv__127:
assumes a1: "r=n_NI_Wb " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_StoreVsinv__127:
assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_GetX__part__1Vsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__1Vsinv__127:
assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__0Vsinv__127:
assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_Store_HomeVsinv__127:
assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__127:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__1Vsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__1Vsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Get__part__0Vsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__127:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__2Vsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__127:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__2Vsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_GetX__part__0Vsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__127:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_Nak_HomeVsinv__127:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutXAcksDoneVsinv__127:
assumes a1: "r=n_NI_Local_PutXAcksDone " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_NakVsinv__127:
assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_NakVsinv__127:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_GetXVsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__1Vsinv__127:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Nak_HomeVsinv__127:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_PutVsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__0Vsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__127:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutVsinv__127:
assumes a1: "r=n_NI_Local_Put " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_NakVsinv__127:
assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__127:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Put_DirtyVsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__0Vsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_GetVsinv__127:
assumes a1: "r=n_PI_Local_Get_Get " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_HomeVsinv__127:
assumes a1: "r=n_NI_Nak_Home " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__127:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_FAckVsinv__127:
assumes a1: "r=n_NI_FAck " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__127 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
% !TeX spellcheck = en_GB
\documentclass[11pt]{article}
\usepackage[OT1]{fontenc}
\usepackage[british]{babel}
\usepackage{../easyformat}
\usepackage{a4wide, amsmath}
\title{\textsf{easyformat}, _tests_\\$$ \int_a^b \mathrm{d}x = b - a $$}
\author{Evert Provoost}
\date{14th July 2017 (v1.5.0)}
\begin{document}
\maketitle
\tableofcontents
\section{Main test}
These two should be identical and have the---a pixel or two error is possible---same length:
$|$ \textit{Lorem \textbf{ipsum}}\textbf{ totalem} \textsc{da} \textbf{givea \textit{zin} doram}
\textit{zet}tim, liefkan. $|$\par
$|$ _Lorem __ipsum_ totalem__ ^da^ __givea _zin_ doram__ _zet_tim, liefkan. $|$\par
\noindent This test has had a consistent and correct result since v1.0.0~(2017/04/07) and has been fixed for \TeX~Live 2017 in v1.5.0~(2017/06/23).
\section{_Math_, $\_ u_nd_er_sc_or_es$ and $\cir c^ir^co^nf^le^xe^s$\dots}
This ($\uparrow$ \textsf{easyformat}-syntax inside subtitles) is possible without some extra code
since v1.1.0~(2017/04/09) and having a \cir\ (using \verb|\cir|) in mathmode since
v1.3.0~(2017/05/28) a possibility of which the kerning was fixed in v1.4.0~(2017/06/03).
$$ \int_a^b x\,\mathrm{d}x = \frac{b^2 - a^2}{2} $$
\section{Mixing _styles_}
^Yeah, _yeah?,_ yeah!!!^
$\leftarrow$ do you notice how we go from ^smallcaps^ to _italics_ and back to ^smallcaps^? This
is possible since v1.2.0~(2017/04/17).
\end{document}
|
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
NewRulesFor(DFT, rec(
DFT_PD := rec(
forTransposition := false,
maxSize := 13,
core := meth(self, N, k, root, is_real)
local coeffs, l1, l2, n, circ, toep;
coeffs := List([0..N-2], x->E(N)^(k*root^(-x) mod N));
n := N-1;
l1 := coeffs{[1..n/2]};
l2 := coeffs{[n/2+1..n]};
circ := 1/2 * (l1 + l2);
toep := Reversed(1/2 * Concat(Drop(l2 - l1, 1), l1 - l2));
if is_real then toep := toep / E(4); fi;
return
DirectSum(I(1),
transforms.filtering.Circulant(circ).terminate(),
transforms.filtering.Toeplitz(toep).terminate());
end,
A := N -> let(nn := (N-1)/2, ones := m -> fConst(m, 1),
VStack(HStack(RowVec(ones(nn+1)), O(1, nn)),
HStack(VStack(-2*ColVec(ones(nn)), O(nn, 1)), I(2*nn)))),
applicable := (self, nt) >> nt.params[1] > 2 and nt.params[1] <= self.maxSize and IsPrime(nt.params[1]) and not nt.hasTags(),
apply := (self,nt,C,cnt) >> let(N := nt.params[1], k := nt.params[2], root := PrimitiveRootMod(N),
Scat(RR(N, 1, root)) *
DirectSum(I(1), Tensor(F(2), I((N-1)/2))) *
Mat(MatSPL(
self.core(N, k, root, false) *
self.A(N))) *
DirectSum(I(1), Tensor(F(2), I((N-1)/2))) *
# DirectSum(I(1), OS(N-1, -1)) *
Gath(RR(N, 1, 1/root mod N))
)
#D isApplicable := (self, P) >> P[1] > 2 and P[1] <= self.maxSize and IsPrime(P[1]) and P[3] = [],
#D
#D rule := (self,P,C) >> let(N := P[1], k := P[2], root := PrimitiveRootMod(N),
#D Scat(RR(N, 1, root)) *
#D DirectSum(I(1), Tensor(F(2), I((N-1)/2))) *
#D Mat(MatSPL(
#D self.core(N, k, root, false) *
#D self.A(N))) *
#D DirectSum(I(1), Tensor(F(2), I((N-1)/2))) *
#D# DirectSum(I(1), OS(N-1, -1)) *
#D Gath(RR(N, 1, 1/root mod N))
#D )
)
));
|
function add1 = cfg_example_add1
% Example script that creates an cfg_exbranch to sum two numbers. The
% inputs are entered as two single numbers, the output is just a single
% number.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_example_add1.m 1716 2008-05-23 08:18:45Z volkmar $
rev = '$Rev: 1716 $'; %#ok
%% Input Items
% Input a
input1 = cfg_entry; % This is the generic data entry item
input1.name = 'Input a'; % The displayed name
input1.tag = 'a'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
input1.strtype = 'e'; % No restriction on what type of data is entered. This could be used to restrict input to real numbers, integers ...
input1.num = [1 1]; % Number of inputs required (2D-array with exactly one row and one column)
input1.help = {'This is input a.','This input will be added to the other input.'}; % help text displayed
% Input b
input2 = cfg_entry; % This is the generic data entry item
input2.name = 'Input b'; % The displayed name
input2.tag = 'b'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
input2.strtype = 'e'; % No restriction on what type of data is entered. This could be used to restrict input to real numbers, integers ...
input2.num = [1 1]; % Number of inputs required (2D-array with exactly one row and one column)
input2.help = {'This is input b.','This input will be added to the other input.'}; % help text displayed
%% Executable Branch
add1 = cfg_exbranch; % This is the branch that has information about how to run this module
add1.name = 'Add1'; % The display name
add1.tag = 'cfg_example_add1'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
add1.val = {input1 input2}; % The items that belong to this branch. All items must be filled before this branch can run or produce virtual outputs
add1.prog = @cfg_example_run_add1; % A function handle that will be called with the harvested job to run the computation
add1.vout = @cfg_example_vout_add1; % A function handle that will be called with the harvested job to determine virtual outputs
add1.help = {'Add two numbers.'};
%% Local Functions
% The cfg_example_vout_add1 function can go here, it is not useful outside
% the batch environment.
function vout = cfg_example_vout_add1(job)
% Determine what outputs will be present if this job is run. In this case,
% the structure of the inputs is fixed, and the output is always a single
% number. Note that input items may not be numbers, they can also be
% dependencies.
vout = cfg_dep; % The dependency object
vout.sname = 'Add1: a + b'; % Displayed dependency name
vout.src_output = substruct('()',{1}); % The output subscript reference. This could be any reference into the output variable created during computation
|
theory WelltypedSubst
imports ExecMessage
begin
subsection{* Well-typed Ground Atomic Substitutions *}
text{*
TODO: Revamp proofs and tool setup, because the current setup is too ad-hoc.
*}
definition groundSubst :: "(execlit \<Rightarrow> execmsg) \<Rightarrow> bool"
where "groundSubst s \<equiv> \<forall> l. s l \<noteq> Lit l \<longrightarrow> ground (s l)"
definition welltyped :: "(execlit \<Rightarrow> execmsg) \<Rightarrow> bool"
where
"welltyped s \<equiv> \<forall> l. s l \<noteq> Lit l \<longrightarrow>
(\<exists> varid tid. l = EVar varid tid \<and>
(
(\<exists> a. varid = (AVar a) \<and>
(s l = Lit Eve \<or> (\<exists> n. s l = Lit (EHonest n)))
) \<or>
(\<exists> v. varid = (MVar v) \<and>
((\<exists> n tid'. s l = Lit (ENonce n tid')) \<or>
(\<exists> n. s l = Lit (EveNonce n)))
)
)
)"
typedef wt_subst = "\<lambda> s. s \<in> welltyped \<and> s \<in> groundSubst"
by(auto simp: mem_def welltyped_def groundSubst_def ran_def)
fun subst :: "wt_subst \<Rightarrow> execmsg \<Rightarrow> execmsg"
where
"subst s (Lit l) = Rep_wt_subst s l"
| "subst s (Tup x y) = Tup (subst s x) (subst s y)"
| "subst s (Enc m k) = Enc (subst s m) (subst s k)"
| "subst s (Hash m) = Hash (subst s m)"
| "subst s (K a b) = K (subst s a) (subst s b)"
| "subst s (PK a) = PK (subst s a)"
| "subst s (SK a) = SK (subst s a)"
definition empty_wts :: "wt_subst"
where "empty_wts \<equiv> Abs_wt_subst Lit"
definition extend_wts :: "wt_subst \<Rightarrow> wt_subst \<Rightarrow> wt_subst"
where "extend_wts s1 s2 \<equiv> Abs_wt_subst (subst s2 o Rep_wt_subst s1)"
definition dom_wts :: "wt_subst \<Rightarrow> execlit set"
where "dom_wts s \<equiv> { l. Rep_wt_subst s l \<noteq> Lit l }"
definition ran_wts :: "wt_subst \<Rightarrow> execmsg set"
where "ran_wts s \<equiv> { Rep_wt_subst s l | l. Rep_wt_subst s l \<noteq> Lit l }"
subsubsection{* Properties *}
lemma Rep_wt_subst_welltyped: "welltyped (Rep_wt_subst s)"
by(insert Rep_wt_subst, simp add: wt_subst_def mem_def)
lemma Rep_wt_subst_groundSubst: "groundSubst (Rep_wt_subst s)"
by(insert Rep_wt_subst, simp add: wt_subst_def mem_def)
lemma Rep_wt_subst_ground [simp]:
"l \<in> dom_wts s \<Longrightarrow> ground (Rep_wt_subst s l)"
apply(insert Rep_wt_subst_groundSubst[of s])
by(auto simp: dom_wts_def groundSubst_def)
lemma Rep_wt_subst_EVar_notin_dom [simp]:
"EVar v tid \<notin> dom_wts s \<Longrightarrow>
Rep_wt_subst s (EVar v tid) = Lit (EVar v tid)"
apply(insert Rep_wt_subst_groundSubst[of s])
by(auto simp: dom_wts_def groundSubst_def)
lemma Rep_wt_subst_simps [simp]:
"Rep_wt_subst s (EConst c) = Lit (EConst c)"
"Rep_wt_subst s (EHonest a) = Lit (EHonest a)"
"Rep_wt_subst s (ENonce n tid) = Lit (ENonce n tid)"
"Rep_wt_subst s (Eve) = Lit (Eve)"
"Rep_wt_subst s (EveNonce n) = Lit (EveNonce n)"
by(insert Rep_wt_subst_welltyped[of s], auto simp: welltyped_def)
lemma Rep_wt_subst_MVar_splits:
"P (Rep_wt_subst s (EVar (MVar v) tid)) = (
( Rep_wt_subst s (EVar (MVar v) tid) = (Lit (EVar (MVar v) tid)) \<longrightarrow> P (Lit (EVar (MVar v) tid))) \<and>
(\<forall> n tid'. Rep_wt_subst s (EVar (MVar v) tid) = (Lit (ENonce n tid')) \<longrightarrow> P (Lit (ENonce n tid'))) \<and>
(\<forall> n. Rep_wt_subst s (EVar (MVar v) tid) = (Lit (EveNonce n)) \<longrightarrow> P (Lit (EveNonce n))))"
apply(insert Rep_wt_subst_welltyped[of s])
apply(simp add: welltyped_def)
apply(drule_tac x="EVar (MVar v) tid" in spec)
by(auto)
lemma Rep_wt_subst_AVar_splits:
"P (Rep_wt_subst s (EVar (AVar a) tid)) = (
( Rep_wt_subst s (EVar (AVar a) tid) = (Lit (EVar (AVar a) tid)) \<longrightarrow> P (Lit (EVar (AVar a) tid))) \<and>
(\<forall> n. Rep_wt_subst s (EVar (AVar a) tid) = (Lit (EHonest n)) \<longrightarrow> P (Lit (EHonest n))) \<and>
(\<forall> n. Rep_wt_subst s (EVar (AVar a) tid) = (Lit Eve) \<longrightarrow> P (Lit Eve)))"
apply(insert Rep_wt_subst_welltyped[of s])
apply(simp add: welltyped_def)
apply(drule_tac x="EVar (AVar a) tid" in spec)
by(auto)
lemma Rep_wt_subst_AVar_cases:
"( Rep_wt_subst s (EVar (AVar a) tid) = (Lit (EVar (AVar a) tid))) \<or>
(\<exists> n. Rep_wt_subst s (EVar (AVar a) tid) = (Lit (EHonest n))) \<or>
(Rep_wt_subst s (EVar (AVar a) tid) = (Lit Eve))"
apply(insert Rep_wt_subst_welltyped[of s])
by(auto simp: welltyped_def)
lemma subst_ground_msg [simp]: "ground m \<Longrightarrow> subst s m = m"
by(induct m, case_tac lit, auto)
lemma subst_idem [simp]: "subst s (subst s m) = subst s m"
apply(induct m, case_tac lit, simp_all)
apply(case_tac "EVar varid nat \<in> dom_wts s", simp+)
done
lemma subst_Rep_wt_subst_idem [simp]:
"subst s (Rep_wt_subst s l) = Rep_wt_subst s l"
apply(rule_tac s="subst s (Lit l)" in subst)
apply(simp, rule subst_idem)
done
lemma Abs_wt_subst_extend_wts_inverse [simp]:
"Rep_wt_subst (Abs_wt_subst (subst s' o Rep_wt_subst s)) = subst s' o Rep_wt_subst s"
apply(subst Abs_wt_subst_inverse)
apply(insert Rep_wt_subst_welltyped[of s])
apply(insert Rep_wt_subst_welltyped[of s'])
apply(simp add: welltyped_def groundSubst_def o_def wt_subst_def mem_def)
apply(safe)
apply(drule_tac x=l in spec)+
defer 1
apply(drule_tac x=l in spec)+
apply(auto)
done
lemma extend_wts_conv_subst:
"subst (extend_wts s s') m = subst s' (subst s m)"
by(induct m, induct_tac lit, auto simp: extend_wts_def)
lemma dom_wts_empty_wts [simp]: "dom_wts empty_wts = {}"
by(simp add: dom_wts_def empty_wts_def wt_subst_def
Abs_wt_subst_inverse welltyped_def groundSubst_def mem_def)
lemma dom_wts_extend_wts [simp]: "dom_wts (extend_wts s s') = dom_wts s \<union> dom_wts s'"
apply(auto simp: dom_wts_def extend_wts_def)
apply(insert Rep_wt_subst_welltyped[of s])
apply(insert Rep_wt_subst_welltyped[of s'])
apply(simp add: welltyped_def groundSubst_def o_def wt_subst_def mem_def)
apply(drule_tac x=x in spec)+
apply(auto)
done
lemma Abs_wt_subst_empty_wts_inverse [simp]:
"Rep_wt_subst (Abs_wt_subst Lit) = Lit"
by(simp add: mem_def welltyped_def wt_subst_def
groundSubst_def Abs_wt_subst_inverse)
lemma subst_empty_wts [simp]: "subst empty_wts m = m"
by(induct m, auto simp: empty_wts_def)
lemma unpair_subst_distr: "x \<in> unpair m \<Longrightarrow> subst s x \<in> unpair (subst s m)"
apply(induct m rule: subst.induct, auto)
apply(subgoal_tac "welltyped (Rep_wt_subst s)") defer 1
apply(rule Rep_wt_subst_welltyped)
apply(simp add: welltyped_def)
apply(drule_tac x=l in spec)
apply(auto)
done
lemma inv_subst_comm [simp]:
"subst s (inv m) = inv (subst s m)"
apply(induct m rule: subst.induct, auto)
apply(subgoal_tac "welltyped (Rep_wt_subst s)")
apply(simp add: welltyped_def)
apply(drule_tac x=l in spec)
apply(auto simp: Rep_wt_subst_welltyped)
done
lemma ground_subst_s2e_conv_FV:
"ground (subst s (s2e msg tid)) = (\<forall> v \<in> FV msg. EVar v tid \<in> dom_wts s)"
apply(induct msg, induct_tac lit)
apply(simp_all)
apply(case_tac "EVar varid tid \<in> dom_wts s")
apply(auto)
done
lemma subst_subdomain:
"dom_wts s' \<subseteq> dom_wts s \<Longrightarrow> subst s' (subst s m) = subst s m"
apply(induct m rule: subst.induct, simp_all)
apply(case_tac "l \<in> dom_wts s")
apply(auto simp: dom_wts_def)
done
lemma Rep_wt_subst_atomic: "\<exists> l'. Rep_wt_subst s l = Lit l'"
apply(insert Rep_wt_subst_welltyped[of s])
apply(simp add: welltyped_def)
apply(drule_tac x=l in spec, auto)
done
lemma Rep_wt_subst_noteq_simps [simp]:
"Rep_wt_subst s l \<noteq> Hash m"
"Rep_wt_subst s l \<noteq> Enc m k"
"Rep_wt_subst s l \<noteq> Tup x y"
"Rep_wt_subst s l \<noteq> PK a"
"Rep_wt_subst s l \<noteq> SK a"
"Rep_wt_subst s l \<noteq> K a b"
by(insert Rep_wt_subst_atomic[of s l], auto)
lemma Rep_wt_subst_AV_noteq [simp]:
"Rep_wt_subst s (EVar (AVar a) tid) \<noteq> Lit (EConst c)"
"Rep_wt_subst s (EVar (AVar a) tid) \<noteq> Lit (ENonce n' tid')"
apply(insert Rep_wt_subst_AVar_cases[of "s" a tid])
apply(auto)
done
lemma subst_notin_dom_wts [iff]:
"(Rep_wt_subst s x = Lit x) = (x \<notin> dom_wts s)"
by(auto simp: dom_wts_def)
(* NOTE: makes unfolding dom_wts using simp loop *)
lemma subst_in_dom_wts [iff]:
"(Rep_wt_subst s x \<noteq> Lit x) = (x \<in> dom_wts s)"
by(simp)
lemma Rep_wt_subst_AVar_in_IK0 [intro!, simp]:
"EVar (AVar a) tid \<in> dom_wts s \<Longrightarrow>
Rep_wt_subst s (EVar (AVar a) tid) \<in> IK0"
by(insert Rep_wt_subst_AVar_cases[of s a tid], auto)
lemma EVar_ground_imp_in_dom_wts [iff]:
"(ground (Rep_wt_subst s (EVar v tid))) = (EVar v tid \<in> dom_wts s)"
apply(case_tac "(Rep_wt_subst s (EVar v tid)) = Lit ( (EVar v tid))")
apply(auto)
done
lemma unpair_Rep_wt_subst_AVar [simp]:
"unpair (Rep_wt_subst s (EVar (AVar a) tid))=
{Rep_wt_subst s (EVar (AVar a) tid)}"
by(insert Rep_wt_subst_atomic[of s "EVar (AVar a) tid"], auto)
lemma unpair_Rep_wt_subst_MVar [simp]:
"unpair (Rep_wt_subst s (EVar (MVar n) tid))=
{Rep_wt_subst s (EVar (MVar n) tid)}"
by(insert Rep_wt_subst_atomic[of s "EVar (MVar n) tid"], auto)
declare Rep_wt_subst_noteq_simps[THEN neq_commute[THEN iffD1], iff]
lemma Rep_wt_subst_reorient_Lit [iff]:
"(Lit l = Rep_wt_subst s l') = (Rep_wt_subst s l' = Lit l)"
by(auto)
lemma pairParts_Rep_wt_subst_AVar [simp]:
"pairParts (Rep_wt_subst s (EVar (AVar a) tid))=
{Rep_wt_subst s (EVar (AVar a) tid)}"
by(insert Rep_wt_subst_atomic[of s "EVar (AVar a) tid"], auto)
lemma pairParts_Rep_wt_subst_MVar [simp]:
"pairParts (Rep_wt_subst s (EVar (MVar n) tid))=
{Rep_wt_subst s (EVar (MVar n) tid)}"
by(insert Rep_wt_subst_atomic[of s "EVar (MVar n) tid"], auto)
end |
{-# LANGUAGE FlexibleContexts #-}
module Geometry where
import Graphics.Gloss as G
import Graphics.Gloss.Data.ViewPort as G
import Graphics.Gloss.Data.ViewState as G
import Data.Array.Accelerate as A
import Data.Array.Accelerate.Data.Complex as A
import qualified Prelude as P
import qualified GHC.Float as P
import qualified Data.Complex as C
type FractalPoint = Complex Double
-- TODO: phantom types
width :: Int
width = 400
height :: Int
height = 400
blWorldByWidthHeight :: (Int, Int) -> Point
blWorldByWidthHeight (w, h) = (-P.fromIntegral w P./ 2.0, -P.fromIntegral h P./ 2.0)
urWorldByWidthHeight :: (Int, Int) -> Point
urWorldByWidthHeight (w, h) = (P.fromIntegral w P./ 2.0, P.fromIntegral h P./ 2.0)
blWorldInit :: Point
blWorldInit = blWorldByWidthHeight (width, height)
urWorldInit :: Point
urWorldInit = urWorldByWidthHeight (width, height)
blComplexInit :: FractalPoint
blComplexInit = (-1) :+ (-1)
urComplexInit :: FractalPoint
urComplexInit = (1) :+ (1)
convertWorldToComplex :: Point -> FractalPoint -> Point -> FractalPoint
convertWorldToComplex w_ur c_ur (x, y) = xComplex C.:+ yComplex
where xRel = x P./ P.fst w_ur
yRel = y P./ P.snd w_ur
xComplex = P.float2Double xRel P.* C.realPart c_ur
yComplex = P.float2Double yRel P.* C.imagPart c_ur
makeComplexGrid :: Int -> Int -> FractalPoint -> FractalPoint -> Acc (A.Matrix FractalPoint)
makeComplexGrid w h bl ur = use $ A.fromList (Z:.h :. w) $ do
imag <- P.reverse $ make1DComplexGrid h (C.imagPart bl) (C.imagPart ur)
real <- make1DComplexGrid w (C.realPart bl) (C.realPart ur)
P.return (real :+ imag)
where
make1DComplexGrid n l r = (P.+l) . (P./ P.fromIntegral n) . (P.*(r P.- l)) . P.fromIntegral P.<$> [0..n - 1] |
(*
This file is part of the verified smart contract project of SECBIT Labs.
Copyright 2018 SECBIT Labs
This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*)
Require Import Mapping.
Require Import ElemTypes.
Require Import Types.
Module Import A2B := Mapping (Address_as_DT) (BoolElem).
Definition a2b: Type := A2B.t.
Notation "$0" := (A2B.empty) (only parsing) : a2b_scope.
Notation "m '$' k" :=
(A2B.get m k)
(at level 50, left associativity, only parsing) : a2b_scope.
Notation "m '$' '{' k '<~' v '}'" :=
(A2B.upd m k v)
(at level 50, left associativity, only parsing) : a2b_scope.
Notation "m '~' m'" :=
(A2B.equal m m')
(at level 70, no associativity, only parsing) : a2b_scope.
|
# 行列表示の導出
吉田勝俊(宇都宮大学)
## 参考情報
- [SymPyで代数演算してみる - Qiita](https://qiita.com/zawawahoge/items/1be137a8147902a5e6cb)
- [Matrices (linear algebra) — SymPy 1.6.2 documentation](https://docs.sympy.org/latest/modules/matrices/matrices.html)
```python
import sympy as sym #数式処理ライブラリ
sym.init_printing() #数式を綺麗に表示する設定
```
## Sympy 変数・関数
```python
x1, x2, x3 = sym.symbols('x_1 x_2 x_3')
a1, a2, a3 = sym.symbols('a_1 a_2 a_3')
th = sym.Symbol(r'\theta') #\t が予約後なので,rをつけてraw文字列とした.
xx = sym.Matrix([x1,x2,x3]) #xベクトル
aa = sym.Matrix([a1,a2,a3]) #aベクトル
```
```python
display(xx) #printの代わりにdisplayを使うと,数式を綺麗に表示してくれる.
display(aa)
display(th)
```
```python
#数ベクトル空間の標準基底ベクトル
ee1 = sym.Matrix([1,0,0])
ee2 = sym.Matrix([0,1,0])
ee3 = sym.Matrix([0,0,1])
ee1,ee2,ee3
```
## 算法4.2 (外積の行列表示)
外積で作った関数
```python
def F(xx):
return aa.cross(xx)
display(F(xx))
```
標準基底を代入した値
```python
F(ee1), F(ee2), F(ee3)
```
行列表示(以上を列ベクトルとする行列)
```python
CrossMatrix = sym.Matrix([[F(ee1),F(ee2),F(ee3)]])
CrossMatrix
```
## 算法4.5 (正射影の行列表示)
正射影ベクトルを求める関数
```python
def F(xx):
return ( aa.dot(xx) )*aa
display(F(xx))
```
標準基底を代入した値
```python
F(ee1), F(ee2), F(ee3)
```
行列表示(以上を列ベクトルとする行列)
```python
ProjMatrix = sym.Matrix([[F(ee1),F(ee2),F(ee3)]])
ProjMatrix
```
テンソル積$\boldsymbol{a}\boldsymbol{a}^T$に一致するか
```python
aaT = aa*( aa.transpose() )
aaT
```
```python
sym.simplify(ProjMatrix - aaT) #テンソル積との差をチェック
```
## 算法4.7 (回転行列)
回転変換を表す関数
```python
def R(xx):
axa = ( aa.dot(xx) )*aa
return axa + sym.cos(th)*(xx - axa) + sym.sin(th)*( aa.cross(xx) )
display(R(xx))
```
標準基底を代入した値
```python
R(ee1), R(ee2), R(ee3)
```
行列表示(以上を列ベクトルとする行列)
```python
RotMatrix = sym.Matrix([[R(ee1),R(ee2),R(ee3)]])
RotMatrix
```
|
using TheNumberLine
using Test
#using Luxor
#using Pluto
@testset "TheNumberLine.jl" begin
pth=pathof(TheNumberLine)
include(joinpath(pth,"..","standard_number_line.jl"))
push!(ii,-2.0)
plt=NumberLinePlot(ii)
@test NumberLineExpression(ii)=="Expression : 0-2.0"
tmp=aSlider(-10:10; default=0)
@test isa(tmp,aSlider)
(a,p,c)=arrows(collect(1:3))
@test a[1]==">"
(a,p,c)=markers(collect(1:3))
@test a[1]==:rtriangle
end
|
module Core.Options.Log
import Data.List
import Data.List1
import Data.Maybe
import Data.StringMap
import Data.StringTrie
import Data.Strings
import Data.These
import Text.PrettyPrint.Prettyprinter
%default total
||| Log levels are characterised by two things:
||| * a dot-separated path of ever finer topics of interest e.g. scope.let
||| * a natural number corresponding to the verbosity level e.g. 5
|||
||| If the user asks for some logs by writing
|||
||| %log scope 5
|||
||| they will get all of the logs whose path starts with `scope` and whose
||| verbosity level is less or equal to `5`. By combining different logging
||| directives, users can request information about everything (with a low
||| level of details) and at the same time focus on a particular subsystem
||| they want to get a lot of information about. For instance:
|||
||| %log 1
||| %log scope.let 10
|||
||| will deliver basic information about the various phases the compiler goes
||| through and deliver a lot of information about scope-checking let binders.
----------------------------------------------------------------------------------
-- INDIVIDUAL LOG LEVEL
||| An individual log level is a pair of a list of non-empty strings and a number.
||| We keep the representation opaque to force users to call the smart constructor
export
data LogLevel : Type where
MkLogLevel : List String -> Nat -> LogLevel
||| If we have already processed the input string into (maybe) a non-empty list of
||| non-empty topics we can safely make a `LogLevel`.
export
mkLogLevel' : Maybe (List1 String) -> Nat -> LogLevel
mkLogLevel' ps n = MkLogLevel (maybe [] forget ps) n
||| The smart constructor makes sure that the empty string is mapped to the empty
||| list. This bypasses the fact that the function `split` returns a non-empty
||| list no matter what.
export
mkLogLevel : String -> Nat -> LogLevel
mkLogLevel "" = mkLogLevel' Nothing
mkLogLevel ps = mkLogLevel' (Just (split (== '.') ps))
||| The unsafe constructor should only be used in places where the topic has already
||| been appropriately processed.
export
unsafeMkLogLevel : List String -> Nat -> LogLevel
unsafeMkLogLevel = MkLogLevel
||| The topics attached to a `LogLevel` can be reconstructed from the list of strings.
export
topics : LogLevel -> List String
topics (MkLogLevel ps _) = ps
||| The verbosity is provided by the natural number
export
verbosity : LogLevel -> Nat
verbosity (MkLogLevel _ n) = n
||| When writing generic functions we sometimes want to keep the same topic but
||| change the verbosity.
export
withVerbosity : Nat -> LogLevel -> LogLevel
withVerbosity n (MkLogLevel ps _) = MkLogLevel ps n
||| A log level is show as `P.Q.R:N` where `P`, `Q` and `R` are topics and `N` is
||| a verbosity level. If there are no topics then we simply print `N`.
export
Show LogLevel where
show (MkLogLevel ps n) = case ps of
[] => show n
_ => fastAppend (intersperse "." ps) ++ ":" ++ show n
export
Pretty LogLevel where
pretty = pretty . show
export
parseLogLevel : String -> Maybe LogLevel
parseLogLevel str = do
(c, n) <- case split (== ':') str of
n ::: [] => pure (MkLogLevel [], n)
ps ::: [n] => pure (mkLogLevel ps, n)
_ => Nothing
lvl <- parsePositive n
pure $ c (fromInteger lvl)
----------------------------------------------------------------------------------
-- COLLECTION OF LOG LEVELS
||| We store the requested log levels in a Trie which makes it easy to check
||| whether a given log level is captured by the user's request for information.
export
LogLevels : Type
LogLevels = StringTrie Nat
||| By default we log everything but with very few details (i.e. next to nothing)
export
defaultLogLevel : LogLevels
defaultLogLevel = singleton [] 0
export
insertLogLevel : LogLevel -> LogLevels -> LogLevels
insertLogLevel (MkLogLevel ps n) = insertWith ps (maybe n (max n))
----------------------------------------------------------------------------------
-- CHECKING WHETHER TO LOG
||| We keep a log if there is a prefix of its path associated to a larger number
||| in the LogLevels.
export
keepLog : LogLevel -> LogLevels -> Bool
keepLog (MkLogLevel path n) levels = go path levels where
go : List String -> StringTrie Nat -> Bool
go path (MkStringTrie current) = here || there where
here : Bool
here = case fromThis current of
Nothing => False
Just m => n <= m
there : Bool
there = case path of
[] => False
(p :: rest) => fromMaybe False $ do
assoc <- fromThat current
next <- lookup p assoc
pure $ go rest next
|
module Common.Pedersen
import Common
public export
%foreign
"apStable:True"
"linear_implicits:pedersen_ptr"
"""
code:
func Common_Pedersen_pedersenHash(pedersen_ptr, x, y) -> (result, pedersen_ptr):
assert [pedersen_ptr] = x
assert [pedersen_ptr + 1] = y
return ([pedersen_ptr + 2], pedersen_ptr + 3)
end
"""
pedersenHash : Felt -> Felt -> Felt |
/******************************************************************************
CosmoLike Configuration Space Covariances for Projected Galaxy 2-Point Statistics
https://github.com/CosmoLike/CosmoCov
by CosmoLike developers
******************************************************************************/
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
// #include "../class/include/class.h"
#include <gsl/gsl_odeiv.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_errno.h>
//void omega_a(double aa,double *om_m,double *om_v);
double omv_vareos(double a);
static inline double hoverh0(double a);
double growfac(double a);
//int func_for_growfac(double a,const double y[],double f[],void *params);
double Tsqr_EH_wiggle(double khoverMPC);
//double int_for_sigma_r_sqr(double k, void * args);
double sigma_r_sqr();
//double Delta_L_wiggle(double k);
//double Delta_lin_wiggle(double k,double a);
double p_lin(double k,double a);
//double int_sig_R_knl(double logk, void *args);
//double int_neff(double lnk, void *args);
//double int_cur(double lnk, void *args);
//void nonlin_scale(double amp, double *R_NL, double *neff, double *Curv);
//double Halofit(double k, double amp, double omm, double omv,double w_z, double R_NL, double neff,double Curv, double P_delta_Lin);
//void Delta_halofit(double **table_P_NL,double logkmin, double logkmax, double dk, double da);
//double Delta_NL_Halofit(double k_NL, double a); //k in h/Mpc
double Pdelta(double k_NL,double a); //k in coverH0 units
//double int_for_chi(double a,void * args);
double f_K(double chi);
double chi(double a);
double a_chi(double chi1);
// extern void emu(double *xstar, double *ystar, double *kstar);
//c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//variable Omega_v
//c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double omv_vareos(double a)
{
return(cosmology.Omega_v*exp(-3.*((cosmology.w0+cosmology.wa+1.)*log(a)+cosmology.wa*(1.-a))));
}
//c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//c evolution of omega matter and omega lamda with expansion factor
void omega_a(double aa,double *om_m,double *om_v)
{
double a2,omega_curv;
a2=aa*aa;
omega_curv=1.0-cosmology.Omega_m- cosmology.Omega_v;
*om_m=cosmology.Omega_m /(cosmology.Omega_m +aa*(omv_vareos(aa) *a2 +omega_curv));
*om_v=omv_vareos(aa)*a2*aa/(cosmology.Omega_m+aa*(a2*omv_vareos(aa) +omega_curv));
}
//c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//growth factor including Dark energy parameters w0, wa
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//function for growfac (DGL)
int func_for_growfac(double a,const double y[],double f[],void *params)
{
//double *p=(double *)params;
if (a == 0) {
printf("a=0 in function 'func_for_growfac'!\n");
exit(1);
}
double aa=a*a;
double omegam=cosmology.Omega_m/(aa*a);
double omegav=omv_vareos(a);
double hub = hoverh0(a);
double one_plus_mg_mu = 1.;
hub = hub*hub;
f[0]=y[1];
if(cosmology.MGmu != 0){
one_plus_mg_mu += cosmology.MGmu*omegav/hub/cosmology.Omega_v;
}
f[1]=y[0]*3.*cosmology.Omega_m/(2.*hub*aa*aa*a)*one_plus_mg_mu-y[1]/a*(2.-(omegam+(3.*(cosmology.w0+cosmology.wa*(1.-a))+1)*omegav)/(2.*hub));
return GSL_SUCCESS;
}
static inline double hoverh0(double a){
return sqrt(cosmology.Omega_m /(a*a*a) + (1.-cosmology.Omega_m -cosmology.Omega_v )/(a*a) + omv_vareos(a) );
}
double growfac(double a)
{
const double MINA=1.e-8;
static cosmopara C;
static double *ai;
static double *table;
double res;
gsl_interp *intf=gsl_interp_alloc(gsl_interp_linear,Ntable.N_a);
gsl_interp_accel *acc=gsl_interp_accel_alloc();
if (recompute_expansion(C))
{
if(table!=0) free_double_vector(table,0, Ntable.N_a-1);
if(ai!=0) free_double_vector(ai,0, Ntable.N_a-1);
ai=create_double_vector(0, Ntable.N_a-1);
table=create_double_vector(0, Ntable.N_a-1);
int i;
const gsl_odeiv_step_type *T=gsl_odeiv_step_rkf45;
gsl_odeiv_step *s=gsl_odeiv_step_alloc(T,2);
gsl_odeiv_control *c=gsl_odeiv_control_y_new(1.e-6,0.0);
gsl_odeiv_evolve *e=gsl_odeiv_evolve_alloc(2);
double t=MINA; //start a
double t1=1.1; //final a
double h=1.e-6; //initial step size
double y[2]={MINA,MINA}; //initial conditions
double norm;
double par[0]={};
gsl_odeiv_system sys={func_for_growfac,NULL,2,&par};
for (i=1;i<=Ntable.N_a;i++) {
ai[i-1]=i*t1/(1.*Ntable.N_a);
while(t<ai[i-1])
gsl_odeiv_evolve_apply(e,c,s,&sys,&t,ai[i-1],&h,y);
if (i==1) norm=y[0]/ai[i-1];
table[i-1]=y[0]/norm;
}
gsl_odeiv_evolve_free(e);
gsl_odeiv_control_free(c);
gsl_odeiv_step_free(s);
update_cosmopara(&C);
}
gsl_interp_init(intf,ai,table,Ntable.N_a);
res=gsl_interp_eval(intf,ai,table,a,acc);
gsl_interp_accel_free(acc);
gsl_interp_free(intf);
return(res);
}
// ---------------------------- Transfer Function from EH98 ----------------------
//Input: k -- Wavenumber at which to calculate transfer function, in Mpc^-1. Output: Returns the value of the full transfer function fitting formula. This is the form given in Section 3 of Eisenstein & Hu (1997). Notes: Units are Mpc, not h^-1 Mpc.
double Tsqr_EH_wiggle(double khoverMPC)
{
static double omhh=-123.;
static double obhh=-123.;
static double OMEGA_V = -123.;
static double f_baryon;
static double k_equality;
static double sound_horizon;
static double beta_c;
static double alpha_c;
static double beta_node;
static double alpha_b;
static double beta_b;
static double k_silk;
//if (omhh != cosmology.Omega_m*cosmology.h0*cosmology.h0 || obhh != cosmology.omb*cosmology.h0*cosmology.h0|| OMEGA_V != cosmology.Omega_v){
double theta_cmb,z_equality,z_drag,R_drag,R_equality;
double z_drag_b1, z_drag_b2;
double alpha_c_a1, alpha_c_a2, beta_c_b1, beta_c_b2, alpha_b_G, y;
omhh = cosmology.Omega_m*cosmology.h0*cosmology.h0;
obhh = cosmology.omb*cosmology.h0*cosmology.h0;
OMEGA_V = cosmology.Omega_v;
f_baryon = obhh/omhh;
//printf("%le\n",f_baryon);
theta_cmb=2.728/2.7;// Tcmb in units of 2.7 K
z_equality= 2.50e4*omhh/POW4(theta_cmb);//Redshift of matter-radiation equality, really 1+z
k_equality=0.0746*omhh/SQR(theta_cmb);//Scale of equality, in Mpc^-1
z_drag_b1 = 0.313*pow(omhh,-0.419)*(1+0.607*pow(omhh,0.674));
z_drag_b2 = 0.238*pow(omhh,0.223);
z_drag=1291*pow(omhh,0.251)/(1+0.659*pow(omhh,0.828))*(1+z_drag_b1*pow(obhh,z_drag_b2));//Redshift of drag epoch
R_drag=31.5*obhh/POW4(theta_cmb)*(1000/(1+z_drag));//Photon-baryon ratio at drag epoch
R_equality= 31.5*obhh/POW4(theta_cmb)*(1000/z_equality);//Photon-baryon ratio at equality epoch
sound_horizon=2./3./k_equality*sqrt(6./R_equality)*log((sqrt(1+R_drag)+sqrt(R_drag+R_equality))/(1+sqrt(R_equality)));//Sound horizon at drag epoch, in Mpc
k_silk= 1.6*pow(obhh,0.52)*pow(omhh,0.73)*(1+pow(10.4*omhh,-0.95));//Silk damping scale, in Mpc^-1
alpha_c_a1 = pow(46.9*omhh,0.670)*(1+pow(32.1*omhh,-0.532));
alpha_c_a2 = pow(12.0*omhh,0.424)*(1+pow(45.0*omhh,-0.582));
alpha_c=pow(alpha_c_a1,-f_baryon)*pow(alpha_c_a2,-CUBE(f_baryon)); //CDM suppression
beta_c_b1 = 0.944/(1+pow(458*omhh,-0.708));
beta_c_b2 = pow(0.395*omhh, -0.0266);
beta_c=1.0/(1+beta_c_b1*(pow(1-f_baryon, beta_c_b2)-1));//CDM log shift
y = z_equality/(1+z_drag);
alpha_b_G = y*(-6.*sqrt(1+y)+(2.+3.*y)*log((sqrt(1+y)+1)/(sqrt(1+y)-1)));
alpha_b=2.07*k_equality*sound_horizon*pow(1+R_drag,-0.75)*alpha_b_G;//Baryon suppression
beta_node = 8.41*pow(omhh, 0.435);//Sound horizon shift
beta_b= 0.5+f_baryon+(3.-2.*f_baryon)*sqrt(pow(17.2*omhh,2.0)+1);//Baryon envelope shift
//}
// Start of TFfit_onek from the original tf_fit.c at http://background.uchicago.edu/~whu/transfer/transferpage.html
double T_c_ln_beta,T_c_ln_nobeta , T_c_C_alpha, T_c_C_noalpha;
double q,qsqr, xx, xx_tilde;
double T_c_f, T_c, s_tilde, T_b_T0, T_b;
double k=khoverMPC*cosmology.h0; //internally this routine uses Mpc^-1 not h/Mpc
q = k/13.41/k_equality;
qsqr =SQR(q);
xx = k*sound_horizon;
T_c_ln_beta = log(2.718282+1.8*beta_c*q);
T_c_ln_nobeta = log(2.718282+1.8*q);
T_c_ln_beta = log(2.718282+1.8*beta_c*q);
T_c_C_alpha = 14.2/alpha_c + 386.0/(1+69.9*pow(q,1.08));
T_c_C_noalpha = 14.2 + 386.0/(1+69.9*pow(q,1.08));
T_c_f = 1.0/(1.0+POW4(xx/5.4));
T_c = T_c_f*T_c_ln_beta/(T_c_ln_beta+T_c_C_noalpha*qsqr) +(1-T_c_f)*T_c_ln_beta/(T_c_ln_beta+T_c_C_alpha*qsqr);
s_tilde = sound_horizon*pow(1+CUBE(beta_node/xx),-1./3.);
xx_tilde = k*s_tilde;
T_b_T0 = T_c_ln_nobeta/(T_c_ln_nobeta+T_c_C_noalpha*qsqr);
T_b = sin(xx_tilde)/(xx_tilde)*(T_b_T0/(1+SQR(xx/5.2))+alpha_b/(1+CUBE(beta_b/xx))*exp(-pow(k/k_silk,1.4)));
return SQR(f_baryon*T_b + (1-f_baryon)*T_c);
}
//Calculate Normalization see Cosmology Notes 8.105
double int_for_sigma_r_sqr(double k, void * args)
{
double kR, res, x;
kR = k*8.; // r=8 Mpc/h
x = (sin(kR) - kR*cos(kR))/(kR*kR*kR);
res = pow(k,2.+cosmology.n_spec+ 0.5*cosmology.alpha_s*log(k/0.05))*Tsqr_EH_wiggle(k)*x*x;
return res;
}
double sigma_r_sqr()
{
static double res = -123.;
static cosmopara C;
double integral,array[1];
if (recompute_Delta(C)) //strictly speaking, this is recomputed unnecessarily if only sigma_8 changes
{
integral = int_gsl_integrate_medium_precision(int_for_sigma_r_sqr,(void*)array,1e-4,1e6,NULL,512);
res = 9.0*integral; //see Peackock97, eq. 29
update_cosmopara(&C);
}
if (!(res>0.0)){
fprintf(stderr,"failed with sigma_r_sqr = %le\n", res);
}
assert(res>0.0);
return res;
}
double Delta_L_wiggle(double k)
{
static cosmopara C;
static double *table_P;
static double dk = .0, logkmin = .0, logkmax = .0;
double klog,f1,norm;
int i;
if (k < limits.k_min_mpc || k > limits.k_max_mpc){
norm=cosmology.sigma_8*cosmology.sigma_8/sigma_r_sqr();
return norm*pow(k,cosmology.n_spec+ 0.5*cosmology.alpha_s*log(k/0.05)+3.0)*Tsqr_EH_wiggle(k);
//printf("outside Delta_L_tab\n");
}
else{
if (recompute_Delta(C))
{
if (cosmology.M_nu > 0){
printf("Implementation of EH transfer function does not support massive neutrinos\n EXIT\n");
}
update_cosmopara(&C);
norm=cosmology.sigma_8*cosmology.sigma_8/sigma_r_sqr();
if(table_P!=0) free_double_vector(table_P,0, Ntable.N_k_lin-1);
table_P=create_double_vector(0, Ntable.N_k_lin-1);
logkmin = log(limits.k_min_mpc);
logkmax = log(limits.k_max_mpc);
dk = (logkmax - logkmin)/(Ntable.N_k_lin-1.);
klog = logkmin;
for (i=0; i<Ntable.N_k_lin; i++, klog += dk) {
table_P[i]=log(norm*pow(exp(klog),cosmology.n_spec+ 0.5*cosmology.alpha_s*log(k/0.05)+3.0)*Tsqr_EH_wiggle(exp(klog)));
}
//printf("finished Delta_L_wiggle\n");
}
}
klog=log(k);
f1=interpol(table_P, Ntable.N_k_lin, logkmin, logkmax, dk,klog, 1.0,1.0 );
return exp(f1);
}
// linear power spectrum routine with k in units H_0/c; used in covariances.c for beat coupling and in halo.c
double p_lin(double k,double a)
{
static cosmopara C;
static double **table_P_Lz = 0;
static double logkmin = 0., logkmax = 0., dk = 0., da = 0.;
int status;
// if (strcmp(pdeltaparams.runmode,"CLASS")==0 || strcmp(pdeltaparams.runmode,"class")==0) return p_class(k,a,0, &status);
double amp,ampsqr,grow0,aa,klog,val;
int i,j;
if (a >= 0.99999){a =0.99999;}
if (recompute_cosmo3D(C)){
update_cosmopara(&C);
if (table_P_Lz!=0) free_double_matrix(table_P_Lz,0, Ntable.N_a-1, 0, Ntable.N_k_lin-1);
table_P_Lz = create_double_matrix(0, Ntable.N_a-1, 0, Ntable.N_k_lin-1);
grow0=growfac(1.);
da = (1. - limits.a_min)/(Ntable.N_a-1.);
aa = limits.a_min;
for (i=0; i<Ntable.N_a; i++, aa +=da) {
if(aa>1.0) aa=1.0;
amp=growfac(aa)/grow0;
ampsqr=amp*amp;
logkmin = log(limits.k_min_mpc);
logkmax = log(limits.k_max_mpc);
dk = (logkmax - logkmin)/(Ntable.N_k_lin-1.);
klog = logkmin;
for (j=0; j<Ntable.N_k_lin; j++, klog += dk) {
table_P_Lz[i][j] = log(ampsqr*Delta_L_wiggle(exp(klog)));
//printf("%le %le",exp(klog),Delta_L_wiggle(exp(klog));
}
}
}
if (k/cosmology.coverH0 > exp(logkmax)) return 0.0;
klog = log(k/cosmology.coverH0);
val = interpol2d(table_P_Lz, Ntable.N_a, limits.a_min, 1., da, a, Ntable.N_k_lin, logkmin, logkmax, dk, klog, 3.0+cosmology.n_spec, 0.0);
if(isnan(val) || (k==0)) return 0.0;
return 2.0*constants.pi_sqr*exp(val)/k/k/k;
}
double int_sig_R_knl(double lnk, void *args) // tak12 A4
{
double krsqr;
double *params= (double *) args;
double Rscale=params[0];
//printf("Rscale %le k %le\n",Rscale,exp(lnk));
krsqr= SQR(exp(lnk)*Rscale);
return Delta_L_wiggle(exp(lnk))*exp(-krsqr);
}
double int_neff(double lnk, void *args) //tak12 A5
{
double krsqr;
double *params= (double *) args;
double Rscale=params[0];
krsqr= SQR(exp(lnk)*Rscale);
return Delta_L_wiggle(exp(lnk))*2.0*krsqr*exp(-krsqr); //see S03 eq. 59
}
double int_cur(double lnk, void *args) //tak12 A5
{
double krsqr;
double *params= (double *) args;
double Rscale=params[0];
krsqr= SQR(exp(lnk)*Rscale);
return Delta_L_wiggle(exp(lnk))*4.0*krsqr*(1.0-krsqr)*exp(-krsqr); // S03 eq.60
}
//iterative calculation of the nonlinear scale as defined in tak12 A4
void nonlin_scale(double amp, double *R_NL, double *neff, double *Curv)
{
double sig_R,kmax,logkmax,sig_R_noamp,neffplus3;
int iterstep;
const int itermax = 40;
int converged=0;
double array[1];
double logRmin = -3.0;
double logRmax = 4.0;
iterstep=0;
while(converged==0)
{
array[0]=pow(10.,(logRmin+logRmax)/2.0);
//flexible upper limit of integration depending on drop-off of filter function
kmax = sqrt(5.*log(10.))/array[0];
if (kmax<8000.0) logkmax = log(8000.0);
sig_R_noamp=sqrt(int_gsl_integrate_medium_precision(int_sig_R_knl,(void*)array,-4.5,logkmax,NULL,512)); //integral goes over ln k exponent correspond to k_min~0.011
sig_R=amp*sig_R_noamp;
if (sig_R>1.0) logRmin=log10(array[0]);
if (sig_R<1.0) logRmax=log10(array[0]);
iterstep=iterstep+1;
if(fabs(sig_R-1.0) < 0.0001 || iterstep>itermax) converged=1;
}
*R_NL=array[0]; //R where sig_R==1
neffplus3=int_gsl_integrate_medium_precision(int_neff,(void*)array,-4.5,logkmax,NULL,512)/sig_R_noamp/sig_R_noamp;
*neff= neffplus3 - 3.0;
*Curv= int_gsl_integrate_medium_precision(int_cur,(void*)array,-4.5,logkmax,NULL,512)/sig_R_noamp/sig_R_noamp + SQR(neffplus3);
//printf("%d %le\n",iterstep,amp);
}
double Halofit(double k, double amp, double omm, double omv,double w_z, double R_NL, double neff,double Curv, double P_delta_Lin)
{
double y_scale,n2eff,n3eff,n4eff;
double a_n,b_n,c_n,gamma_n,alpha_n,beta_n,nu_n,f1,f2,f3;
double Delta_H,Delta_H_Prime,Delta_Q;
//determine nonlinear scale, neff and curvature, see tak12 A4, A5
y_scale=k*R_NL;
n2eff=neff*neff;
n3eff=n2eff*neff;
n4eff=n2eff*n2eff;
//calculate coefficients
a_n = pow(10.,1.5222+2.8553*neff + 2.3706*n2eff+0.9903*n3eff+0.2250*n4eff-0.6038*Curv+0.1749*omv*(1.0+w_z));
b_n = pow(10., -0.5642+0.5864*neff + 0.5716*n2eff-1.5474*Curv +0.2279*omv*(1.0+w_z));
c_n = pow(10., 0.3698+ 2.0404*neff + 0.8161*n2eff+0.5869*Curv);
gamma_n = 0.1971-0.0843*neff + 0.8460*Curv;
alpha_n = fabs(6.0835 + 1.3373*neff - 0.1959*n2eff - 5.5274*Curv);
beta_n = 2.0379 - 0.7354*neff + 0.3157*n2eff + 1.2490*n3eff + 0.3980*n4eff - 0.1682*Curv;
nu_n = pow(10,5.2105+3.6902*neff);
f1 = pow(omm,(-0.0307));
f2 = pow(omm,(-0.0585));
f3 = pow(omm,(0.0743));
//TwoHaloTerm
Delta_Q=P_delta_Lin*(pow((1.0+P_delta_Lin),beta_n)/(1.0+alpha_n*P_delta_Lin))*exp(-(y_scale/4.0+y_scale*y_scale/8.0));
//OneHaloterm
Delta_H_Prime=(a_n*pow(y_scale,3.0*f1))/(1.0+b_n*pow(y_scale,f2)+pow(c_n*f3*y_scale,3.0-gamma_n));
Delta_H=Delta_H_Prime/(1.0+nu_n*pow(y_scale,-2.0)); // using mu=0.0 Tak A12
//printf("Delta_Q %le Delta_H %le\n",Delta_Q,Delta_H);
return Delta_H+Delta_Q;
}
void Delta_halofit(double **table_P_NL,double logkmin, double logkmax, double dk, double da)
{
double rk,omm,omv,w_z,amp,grow0,aa,klog;
double R_NL,Curv,neff,P_delta,P_delta_Lin;
int i,j;
grow0=growfac(1.);
aa = limits.a_min;
//binning in k and a must be the same as in emu
for (i=0; i<Ntable.N_a; i++, aa +=da) {
if(aa>1.0) aa=1.0;
omega_a(aa,&omm,&omv);
w_z=cosmology.w0+cosmology.wa*(1.-aa);
amp=growfac(aa)/grow0;
nonlin_scale(amp, &R_NL, &neff, &Curv);
//printf("%le %le %le %le\n",aa,R_NL,neff,Curv);
klog = logkmin;
for (j=0; j<Ntable.N_k_nlin; j++, klog += dk) {
rk=exp(klog);
P_delta_Lin=amp*amp*Delta_L_wiggle(rk);
P_delta=Halofit(rk, amp, omm, omv, w_z, R_NL, neff, Curv, P_delta_Lin);
table_P_NL[i][j]=log(P_delta);
}
}
}
double Delta_NL_Halofit(double k_NL, double a)
{
static cosmopara C;
static double logkmin = 0., logkmax = 0., dk = 0., da = 0.;
static double **table_P_NL=0;
double klog,val;
if (recompute_cosmo3D(C)){
update_cosmopara(&C);
if (table_P_NL!=0) free_double_matrix(table_P_NL,0, Ntable.N_a-1, 0, Ntable.N_k_nlin-1);
table_P_NL = create_double_matrix(0, Ntable.N_a-1, 0, Ntable.N_k_nlin-1);
da = (1. - limits.a_min)/(Ntable.N_a-1.);
logkmin = log(limits.k_min_mpc);
logkmax = log(limits.k_max_mpc);
dk = (logkmax - logkmin)/(Ntable.N_k_nlin-1.);
Delta_halofit(table_P_NL,logkmin, logkmax, dk, da);
}
klog = log(k_NL);
val = interpol2d(table_P_NL, Ntable.N_a, limits.a_min, 1., da, a, Ntable.N_k_nlin, logkmin, logkmax, dk, klog, cosmology.n_spec, 0.0);
return exp(val);
// returns the dimensionless power spectrum as a function of scale factor a and k
}
double nonlinear_scale_computation(double a)
{
static cosmopara C;
static double da = 0.;
static double *table=0;
double omm,omv,amp,grow0,aa,res;
double R_NL,Curv,neff;
int i;
if (recompute_cosmo3D(C)){
update_cosmopara(&C);
grow0=growfac(1.);
da = (1.-limits.a_min)/(Ntable.N_a-1.);
aa = limits.a_min;
if (table!=0) free_double_vector(table, 0, Ntable.N_a-1);
table = create_double_vector(0, Ntable.N_a-1);
for (i=0; i<Ntable.N_a; i++, aa+=da) {
if(aa>1.0) aa=1.0;
omega_a(aa,&omm,&omv);
amp=growfac(aa)/grow0;
nonlin_scale(amp, &R_NL, &neff, &Curv);
table[i] = 1./R_NL;
}
}
res = interpol(table, Ntable.N_a, limits.a_min, 1., da, a, 0.0, 0.0);
return res;
}
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
//Pdelta is called with k in units H0/c since the comoving distance chi is in units c/H0. Upstream Pdelta all routines are in h/mpc
double Pdelta(double k_NL,double a)
{
static int P_type = -1;
if (P_type == -1){
if (strcmp(pdeltaparams.runmode,"Halofit")==0) P_type = 0;
if (strcmp(pdeltaparams.runmode,"halofit")==0) P_type = 0;
// if (strcmp(pdeltaparams.runmode,"emu")==0) P_type = 1;
// if (strcmp(pdeltaparams.runmode,"emu_only")==0) P_type = 2;
if (strcmp(pdeltaparams.runmode,"linear")==0) P_type = 3;
// if (strcmp(pdeltaparams.runmode,"CLASS")==0) P_type = 4;
// if (strcmp(pdeltaparams.runmode,"class")==0) P_type = 4;
if (strcmp(pdeltaparams.runmode,"cosmo_sim_test") ==0) P_type = 5;
}
//printf("%s set\n",pdeltaparams.runmode);
double pdelta = 0.,kintern=k_NL/cosmology.coverH0,error,k_nonlin,res;
int status;
switch (P_type){
case 0: pdelta=2.0*constants.pi_sqr*Delta_NL_Halofit(kintern,a)/k_NL/k_NL/k_NL; break;
// case 1: pdelta=2.0*constants.pi_sqr*Delta_NL_emu(kintern,a)/k_NL/k_NL/k_NL; break;
// case 2: pdelta=2.0*constants.pi_sqr*Delta_NL_emu_only(kintern,a)/k_NL/k_NL/k_NL; break;
case 3: pdelta=p_lin(k_NL,a); break;
// case 4: pdelta=p_class(k_NL,a,1, &status); break;
case 5: k_nonlin=nonlinear_scale_computation(a);
if (kintern<0.01) pdelta=2.0*constants.pi_sqr*Delta_NL_Halofit(kintern,a)/k_NL/k_NL/k_NL;
else{
error=0.01*pow((pdeltaparams.DIFF_A*kintern/k_nonlin),pdeltaparams.DIFF_n);
pdelta=2.0*constants.pi_sqr*Delta_NL_Halofit(kintern,a)*(1.0+error)/k_NL/k_NL/k_NL;
}
break;
default:
printf("cosmo3D:Pdelta: %s Pdelta runmode not defined\n",pdeltaparams.runmode);
printf("using Halofit (standard)\n");
pdelta=2.0*constants.pi_sqr*Delta_NL_Halofit(kintern,a)/k_NL/k_NL/k_NL;
break;
}
// double z = 1./a -1 ;
// if (z > 4.) {
// printf(" z:%lf a:%lf k_Mpc:%lf PkRatio:%lf \n",z,a,kintern,PkRatio_baryons(kintern, a));
// }
// if (bary.isPkbary==1) pdelta = pdelta*PkRatio_baryons(kintern, a);
return pdelta;
}
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*============================================================
*see BS 2.41 bzw Logbook for detailed calculation of chi from a.*/
double int_for_chi(double a, void * args){
//double res,asqr;
//asqr=a*a;
//res= 1./sqrt(a*cosmology.Omega_m + asqr*(1.-cosmology.Omega_m -cosmology.Omega_v ) + asqr*asqr*omv_vareos(a));
//return res;
return 1./(a*a*hoverh0(a)); //changed to call of hoverh0 to be ready for other parametrizations
}
/*for the calculation of chi we have to integrate from a(z2)=a up to a(z1)=1, which means todays expansion factor*/
double chi(double a)
{
static cosmopara C;
static double *table;
static double da = 0.;
double aa,res;
int i;
double array[1];
if (recompute_expansion(C)){
update_cosmopara(&C);
da = (1.-limits.a_min)/(Ntable.N_a-1.);
aa = limits.a_min;
if (table!=0) free_double_vector(table, 0, Ntable.N_a-1);
table = create_double_vector(0, Ntable.N_a-1);
for (i=0; i<Ntable.N_a-1; i++, aa+=da) {
table[i] = int_gsl_integrate_medium_precision(int_for_chi,(void*)array, aa, 1.,NULL,1000);
}
table[Ntable.N_a-1] =.0;
}
res = interpol(table, Ntable.N_a, limits.a_min, 1., da, a, 0.0, 0.0); // comoving distance in c/H_0
if (res < 0){printf ("interpolation error in chi(%e)\n",a); res=0.01;}
return res;
}
//auxilary function to look up a(chi)
double a_chi(double chi1){
static gsl_spline * a_spline = NULL;
static gsl_interp_accel * a_accel = NULL;
static cosmopara C;
static double chi_max =-1.;
if (!a_spline){
a_spline = gsl_spline_alloc(gsl_interp_cspline, Ntable.N_a);
a_accel = gsl_interp_accel_alloc();
}
if (recompute_cosmo3D(C)){
update_cosmopara(&C);
double *table_a,*table_chi;
table_a = create_double_vector(0, Ntable.N_a-1);
table_chi = create_double_vector(0, Ntable.N_a-1);
for (int i = 0; i < Ntable.N_a; i++){
table_a[i] = 1.0 - (1.0 - 0.99*limits.a_min)/(Ntable.N_a-1.)*(double)i;
table_chi[i] = int_gsl_integrate_medium_precision(int_for_chi,NULL, table_a[i], 1.,NULL,1000);
// printf("%d %e %e\n",i,table_a[i],table_chi[i]);
}
chi_max = int_gsl_integrate_medium_precision(int_for_chi,NULL, limits.a_min, 1.,NULL,1000);
gsl_spline_init(a_spline, table_chi, table_a, Ntable.N_a);
free_double_vector(table_a,0, Ntable.N_a-1);
free_double_vector(table_chi,0, Ntable.N_a-1);
}
if (chi1 <=0.0){return 1.0;}
if (chi1 > chi_max){printf("called a_chi(chi) with chi > chi(limits.a_min\nEXIT\n");exit(1);}
return gsl_spline_eval(a_spline,chi1,a_accel);
}
/*===============================calculating the angular diameter distance f_K BS01 2.4, 2.30: f_K is a radial function that, depending on the curvature of the Universe, is a trigonometric, linear, or hyperbolic function of chi */
double f_K(double chi)
{
double K, K_h, f;
K = (cosmology.Omega_m + cosmology.Omega_v - 1.);
if (K > precision.medium) { /* open */
K_h = sqrt(K); // K in units H0/c see BS eq. 2.30
f = 1./K_h*sin(K_h*chi);
//printf("open\n");
} else if (K < -precision.medium) { /* closed */
K_h = sqrt(-K);
f = 1./K_h*sinh(K_h*chi);
//printf("closed K=%le %le %le\n",K,cosmology.Omega_m,cosmology.Omega_v);
} else { /* flat */
f = chi;
//printf("flatK=%le %le %le\n",K,cosmology.Omega_m,cosmology.Omega_v);
}
return f;
}
|
Don't know much about this. A friend got me some bud wood after describing a Hass seedling planted by a friend. The tree is now 10 years old and bears heavily, large pound size fruit, with Hass like taste. I don't even have a picture but this friend is a reliable source of information. If I'm not mistaken it matures around March in California.
I Just hope one of these seedlings may like our So. Florida weather. I have top worked a tree in the grove on February 14. I also I have a back up in 3 gal. which seems to be doing well. In 3 years we may have a fruit to taste. In the mean time we'll see how it likes it here.
May 18, 2013. Top worked tree is doing well, also 2 potted grafts doing well.
November 1, 2013: The tree survived the heat and rain this summer. Seems to be growing well.
December 31, 2013: The tree is looking good, building flower buds. See today's pictures. Curiously this tree is ahead of the Hass in the Flowering process.
February 27, 2014: Expanding inflorescence, should have open flowers in 3-4 days ans we will see flower type. The tree is only one year post grafting. The top of the tree has no flowers because I pruned it a few months ago and is just pushing vegetation with force. Some location on the side only pushing vegetation. Typical first year, with some luck we could see fruit.
April 4, 2014: I see a couple of very small fruit. Let's hope they set and grow. Does not seem likely.
November 8, 2014: Seems like the few fruit it set still is hanging in, a little larger than Hass. Not sure when to pick this. In Cal. the fruit stays in the tree over 12 months. I don't know if it would do that here.
December 26, 2014: Picked one of the two fruit on the tree. They seemed to be getting dull. It came in at 8.5 oz. Nice size for a Hass growing in Florida. Let see how it ripens.
January 13, 2015: The two fruits did not ripened properly. The tree is building flower buds will give it one more year.
February 3, 2015: The tree has a few open flowers.
March 3, 2015: Has a lot of open flowers seems to be going slow at it. I see fruit set in the top flowers.
May 21, 2015: The tree has set quite a bit of fruit and its growing it well, seem to be ahead than regular Hass. No fruit drop.
June 14, 2015: The tree is holding the fruit well, good fruit set for its second flowering. Seems to be earlier than Hass sightly bigger.
September 19, 2015: The fruit does not seem to be growing a lot from the observation in June. Rare, because the heat is up and has rained a lot in the last 6 weeks. Some fruit is small others larger....Dwarfism ? Like Hass?
October 18, 2015: A lot of small fruit has dropped. What is in the tree seem to be growing very little. I picked the fruit in today's picture, came in at 7.8 oz this is like a larger supermarket Hass. It does have larger fruit than my regular Hass, but the Hass is more prolific.
October 26, 2015: The fruit picked did not ripen well, typical problems of small Guatemalan fruit in this area. All sorts of flesh deterioration, uneven ripening, watery, sub cutaneous watery spots or rot. Reminds me of the Florida Hass problems, See today's pictures. |
As you can see in the quality/durability guidelines here ... quilting layers that aren't more than "about an inch or so" thick won't have a meaningful effect on the durability or useful life of a mattress. The BestMattressEver uses all high quality high quality and durable materials and as you can also see in my comments in post #2 in the topic we are posting in (and unlike some of the other simplified choice mattresses) there are no lower quality materials or weak links in the mattress that would compromise the durability or useful life of the mattress even relative to higher weight ranges than yours.
Last edit: 01 Nov 2015 19:07 by Phoenix.
Appreciate the comprehensive summary of the disruptor mattresses! I'm leaning towards T&N as it seems is the most firm of all of these options. Certainly doesn't hurt that it's priced more competitively (esp. with the Amex + underground discount). Given the free trial periods, I'm wondering if anyone has actually ordered from several vendors and, assuming you have the bedroom space, tested them all over the same ~100 day period?
I'm leaning towards T&N as it seems is the most firm of all of these options.
Based on general feedback it's probably among the firmer options out of the single firmness mattresses and may be firmer than some of the "medium" firmness options for mattresses that have multiple firmness options but it probably isn't as firm as some of the "firm" options that are available.
Different people can also have very different perceptions of firmness and softness compared to others as well and a mattress that feels firm for one person can feel like "medium" for someone else or even "soft" for someone else (or vice versa) depending on their body type, sleeping style, physiology, their frame of reference based on what they are used to, and their individual sensitivity and perceptions. There are also different types of firmness and softness that different people may be sensitive to that can affect how they "rate" a mattress as well (see post #15 here ) so different people can have very different opinions on how two mattresses compare in terms of firmness and some people may rate one mattress as being firmer than another and someone else may rate them the other way around. This is all relative and very subjective and is as much an art as a science.
Last edit: 09 Nov 2015 00:16 by Phoenix.
Phoenix, I am so grateful to have found your website and the wealth of knowledge it contains. Thank you so much for bringing this much-needed information together in such a cohesive and useful way! I am looking at both the Love Bed from Nest Bedding and the Sedona Sleep base mattress and topper from Sedona Sleep. I would be interested in your thoughts regarding how to compare these two mattress systems, as well as how the discount code works.
There is more information about the 3 most important parts of "value" of a mattress purchase in post #13 here which can help you make more meaningful quality/value comparisons between mattresses in terms of suitability (how well you will sleep), durability (how long you will sleep well), and the overall value of a mattress compared to your other finalists based on suitability, durability, and all the other parts of your personal value equation that are most important to you (including the price of course and the options you have available after a purchase if your choice doesn't turn out as well as you hoped for).
The most important part of the "value" of a mattress purchase is how well you will sleep on it and whether a mattress is a good "match" for you in terms of PPP (Posture and alignment, Pressure relief, and your Personal preferences. While your own careful testing or personal experience is the only way to know for certain whether any mattress or combination of layers and components is a good "match" for you in terms of comfort, firmness, and PPP (Posture and alignment, Pressure relief, and your Personal preferences) ... when you can't test a mattress in person then the most reliable source of guidance is always a more detailed phone conversation with a knowledgeable and experienced retailer or manufacturer that has your best interests at heart and who can help "talk you through" the specifics of their mattresses and the properties and "feel" of the materials they are using (fast or slow response, resilience, firmness etc) and the options they have available that may be the best "match" for you based on the information you provide them, any local testing you have done or mattresses you have slept on and liked or other mattresses you are considering that they are familiar with, and the "averages" of other customers that are similar to you. They will know more about "matching" their specific mattress designs and firmness levels to different body types, sleeping positions, and preferences (or to other mattresses that they are familiar with) than anyone else.
Outside of PPP ... the most important part of the value of a mattress purchase is durability which is all about how long you will sleep well on a mattress. This is the part of your research that you can't "feel" and assessing the durability and useful life of a mattress depends on knowing the type and quality of all the materials inside it regardless of the name of the manufacturer on the label so I would always make sure that you are able to find out the information listed here so you can compare the materials and components in a mattress to the quality/durability guidelines here so you can confirm that there are no lower quality materials or obvious weak links in a mattress that would compromise the durability and useful life of a mattress before making any purchase.
Both of these manufacturers are completely transparent about their materials and both of them use high quality materials and there are no lower quality materials or weak links in either design that would compromise the durability or useful life of either mattress.
Having said that ... they are both very different designs. The topper that goes with Sedona Sleep is a solid layer of blended Talalay latex which would be a little bit more resilient than the convoluted continuous pour synthetic Dunlop in the Love bed and is also a more costly material (Talalay latex is more costly than synthetic Dunlop and solid layers are also more costly than solid layers). There is more about convoluted layers in post #2 here . There is also more about the different types and blends of latex in post #6 here .
Both of them offer multiple firmness options.
The Love Bed has a cover that is quilted with polyfoam and the Sedona Sleep topper uses an unquilted stretch knit cover so you would be sleeping more directly on the latex itself. Which type of cover you prefer would be a preference issue and there is more about the pros and cons of quilted covers vs a thinner stretch knit cover in post #12 here .
The Love Bed has a 100 night free return/exchange policy and trial period. Sedona Sleep also has a 100 night trial period but there will be a small shipping cost involved to either exchange the topper for a different firmness or return the mattress for a refund.
A mattress/topper combination also has the advantage of being able to replace just the topper after the trial period without having to replace the entire mattress if your needs or preferences change down the road or if the topper softens or breaks down before the rest of the mattress (the top layers of a mattress are generally the weakest link of any sleeping system whether they are inside the mattress cover or outside it).
You are certainly looking at two great quality/value choices and once you have narrowed down your options to a list of finalists that are all choices between "good and good" (which you have) and none of them have any lower quality materials or "weak links" in their design relative to your weight range (which they don't) and if there are no clear winners between them (which is usually a good indication that you have done some good research) then you are in the fortunate position that any of them would likely be a suitable choice and post #2 here can help you make a final choice based on your local testing or mattresses you have slept well on, your more detailed conversations about each of them, your confidence about PPP and the suitability of each one, their prices, your preferences for different types of materials or types and blends of latex, the options you have after a purchase to fine tune the mattress or exchange or return the mattress or individual layers, any additional extras that are part of each purchase, and on "informed best judgement" based on all the other objective, subjective, and intangible parts of your personal value equation that are most important to you.
Last edit: 18 Dec 2015 12:25 by Phoenix.
We ended up returning our BME as the Latex feel wasn't for us. Working with them was a pleasure and they even gave a topper to try, but we spent nights in our guest room as we just didn't like the feel of the BME. We went mattress shopping again today and really liked memory foam (temper-cloud elite mattress was our favorite after 30 minutes of laying) .
However, as a 240 lb male these simplified choices are all listed as cautionary or recommended against. I have read many of your posts and the cross references but it is almost burying me in information. We are willing to spend up to a temperpedic but after becoming so knowledgeable from your site (thanks again!), I recognize this is not worth it.
In terms of my specific interests, I could even consider going firm and putting a topper on the mattress so it supports my weight and is extra plush for myself and my bride-to-be (120lb). I narrowed it down to the Novosbed and Nest Alexander Medium. Is this smart or should I go a different route? If so do you recommend a coil core with memory foam on top for heavier individuals?
The third post in this topic is being "reserved" for a different purpose.
There are a number of the "simplified choice" mattresses that are already described in post #2 in this topic as being suitable for any weight range in terms of the quality and durability of the materials.
If you tend to prefer more traditional memory foam mattresses and if you are looking at online options then outside of the simplified choice list the mattress shopping tutorial also includes several other links to lists of many of the better online options I'm aware of (in the optional online step) that include many different types and categories of mattresses in a wide range of budgets, firmness levels, and with different return/exchange policies that may also be worth considering including a list of the better online memory foam options I'm aware of.
While the process of how to choose a mattress would involve the same steps that are listed in the mattress shopping tutorial ... most people in higher weight ranges will generally need or prefer firmer mattresses (firmer materials will feel softer because you will sink into them more) and materials and components that are higher quality and more durable than those that are in lower weight ranges (the materials and components in a mattress will soften and break down faster for those in higher weight ranges than they will for someone that is in a lower weight range that doesn't compress the mattress as much). I would be particularly cautious about mattresses that use more than "about an inch or so" of memory foam that is less than about 5 lb density or polyfoam that is less than about 2 lb density ... particularly in the upper layers of the mattress.
You can also see my comments about choosing a mattress first with the intention of adding a topper later in post #2 here .
In most cases I would avoid this approach because of the uncertainty involved with two purchase choices instead of only one and choosing a topper that would be suitable in terms of PPP (Posture and alignment, Pressure relief, and your Personal preferences) for a specific person on a specific mattress can sometimes be almost as difficult as choosing a mattress that doesn't need a topper in the first place. I would generally focus on choosing a mattress that is likely to be a suitable match without a topper (unless you can test the combination in person or you are purchasing both online as a "set" that is designed to work together and they both have a good return/exchange policy) and then use the option to add a topper as a "backup" strategy in case your initial choice doesn't turn out as well as you hoped for rather than a "primary" strategy.
It can also be more costly than just buying a mattress which includes the same materials as the topper as a layer inside the mattress itself and you would be avoiding the risk of having additional materials in your base mattress that you may not need or that may be lower quality foam (that can soften or break down more quickly) or that may be softer than what would be ideal for a transition layer under a softer topper. I would also make sure that you can find out all the specifics of the materials inside the base mattress so you can make sure it meets the quality/durability guidelines here and that there are no lower quality materials or weak links in any of the materials or components in your sleeping system that could compromise the durability and useful life of the mattress.
Having said that ... if you do choose a suitable mattress/topper combination which turns out to be a good "match" for you in terms of PPP (and there are no lower quality materials or "weak links" in the mattress/topper combination) then it would have the advantage of being able to replace just the topper without replacing the entire mattress if it softens or breaks down before the upper foam layers in the mattress (which is likely because a sleeping system will tend to soften or break down from the top layers down) or if your needs or preferences change over time and a topper can also help extend the useful life of a mattress underneath it as well.
1. Careful testing (hopefully using the testing guidelines in the tutorial) to make sure that a mattress is a good match for you in terms of "comfort", firmness, and PPP ... and/or that you are comfortable with the options you have available to return, exchange, or "fine tune" the mattress and any costs involved if you can't test a mattress in person or aren't confident that your mattress is a suitable choice.
2. Checking to make sure that there are no lower quality materials or weak links in a mattress you are considering relative to your weight range that could compromise the durability and useful life of the mattress.
Last edit: 17 Mar 2016 19:26 by Phoenix.
I'm knew to this forum and interested in purchasing a new mattress in the next couple of months. My wife and I have been sleeping on a King size tripedic memory foam mattress from select-a-bed.com for about eight years now. I find that the support and pressure relief has been insufficient for some time time now (I'm about 185lbs) though my wife still finds it okay. We both find that it sleeps hot. I think I'm done with memory foam.
I've spent a lot of time trying to research on the internet about mattress buying and quality components. I must admit that the bed-in-a-box category is appealing, perhaps due to the very vigorous and clever on line marketing campaigns that make their product appear more 'authentic' than traditional mattress manufacturers/retailers. One bed-in-a-box company that I'm surprised not to see mentioned in this thread that seems to be everywhere in the online world now is the new Purple mattress with their new hyper-elastic polymer comfort layer (collapsing gel). I must admit that I am intrigued by their message and the 'raw egg test', though I realize the real test would by my wife and I seeing if a mattress meets our PPP's. I wonder if their polyfoam support layers layers are a 'weak link' in the bed construction underneath this wonder gel layer (side note: the product and company used to be called WonderGel and you can buy seat cushions under this brand at Bed Bath & Beyond, I have one and it works really well).
The tripedic mattress you own is a good quality/value mattress but if you are no longer sleeping well on it and it has lost its "comfort" and/or support then after 8 years it's very likely that it's time for a new mattress.
Two of the most important links in the tutorial that I would especially make sure you've read are post #2 here which has more about the different ways to choose a suitable mattress (either locally or online) that is the best "match" for you in terms of "comfort", firmness, and PPP (Posture and alignment, Pressure relief, and your own Personal preferences) that can help you assess and minimize the risks of making a choice that doesn't turn out as well as you hoped for and post #13 here which has more about the most important parts of the "value" of a mattress purchase which can help you make more meaningful quality/value comparisons between mattresses in terms of suitability (how well you will sleep), durability (how long you will sleep well), and the overall value of a mattress compared to your other finalists based on all the parts of your personal value equation that are most important to you.
I've spent a lot of time trying to research on the internet about mattress buying and quality components. I must admit that the bed-in-a-box category is appealing, perhaps due to the very vigorous and clever on line marketing campaigns that make their product appear more 'authentic' than traditional mattress manufacturers/retailers.
I would keep in mind that "marketing campaigns" are just that and don't necessarily relate to the suitability, quality, or durability of a mattress. You've probably read this already as well but you can read more about what I call "simplified choice" mattresses in the first post in this topic.
I would also keep in mind that there are many other good quality/value online mattress choices that are shipped directly to consumers that don't fit the "simplified choice" category (in many cases because they have more than one mattress available on their site).
Outside of the simplified choice list ... if you are looking at online options then the mattress shopping tutorial also includes several other links to lists of many of the better online options I'm aware of (in the optional online step) that include many different types and categories of mattresses in a wide range of budgets, firmness levels, and with a range of different return/exchange policies that may also be worth considering.
There may also be some good options available to you locally and if you let me know your city or zip code I'd be happy to let you know about the better options or possibilities I'm aware of in your area.
One bed-in-a-box company that I'm surprised not to see mentioned in this thread that seems to be everywhere in the online world now is the new Purple mattress with their new hyper-elastic polymer comfort layer (collapsing gel). I must admit that I am intrigued by their message and the 'raw egg test', though I realize the real test would by my wife and I seeing if a mattress meets our PPP's. I wonder if their polyfoam support layers layers are a 'weak link' in the bed construction underneath this wonder gel layer (side note: the product and company used to be called WonderGel and you can buy seat cushions under this brand at Bed Bath & Beyond, I have one and it works really well).
Outside of the 23 mattresses that are already listed in the simplified choice list ... there are currently 23 more that I'm aware of that have been launched more recently that I haven't added to the list yet (and more are being launched on a regular basis). Some of them have been mentioned on the forum (and some haven't yet) but I will likely add some or most of them to the list over the coming weeks although some of them will be included in the "avoid until complete specs are known" section of the list.
Because the list has so many options available I wouldn't consider it to be as much of a "simplified choice" list any longer because there really isn't much difference between choosing between 46 mattresses that are offered by 46 different companies or 46 mattresses (or less) that are offered by a single company and when you are purchasing online it's not possible to make "real time" comparisons between many different mattresses to see if you like one better than another which you can in a local store. Because most of them have good trial periods and refund policies though, you can at least try them with little risk to find out if they are "good enough" in terms of comfort, firmness, and PPP even though you can't know if another one would have been a better choice unless you try it as well.
Purple certainly has a very aggressive advertising campaign (their ads show up everywhere once you have been to their site especially) and until they are listed in the simplified choice list you can see some comments about the Purple mattress and the buckling column gel they use in post #2 here and the posts it links to.
Last edit: 20 Apr 2016 11:07 by Phoenix. |
(*
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/.
*)
(* One should be able to simplify this by evaluating explicitly the Stoll
decomposition of the exchange functional *)
$define lda_c_pw_params
$define lda_c_pw_modified_params
$include "lda_c_pw.mpl"
b97mv_ux := (mgamma, x) -> mgamma*x^2/(1 + mgamma*x^2):
(* article uses t = 2 tau convention *)
b97mv_wx_ss := (t, dummy) -> (K_FACTOR_C - t)/(K_FACTOR_C + t):
b97mv_wx_os := (ts0, ts1) -> (K_FACTOR_C*(ts0 + ts1) - 2*ts0*ts1)/(K_FACTOR_C*(ts0 + ts1) + 2*ts0*ts1):
b97mv_g := (mgamma, wx, cc, n, xs, ts0, ts1) ->
add(cc[i][1]*wx(ts0, ts1)^cc[i][2]*b97mv_ux(mgamma, xs)^cc[i][3], i=1..n):
b97mv_fpar := (rs, z, xs0, xs1, ts0, ts1) ->
+ lda_stoll_par(f_pw , rs, z, 1) * b97mv_g(b97mv_gamma_ss, b97mv_wx_ss, b97mv_par_ss, b97mv_par_n, xs0, ts0, 0)
+ lda_stoll_par(f_pw , rs, -z, -1) * b97mv_g(b97mv_gamma_ss, b97mv_wx_ss, b97mv_par_ss, b97mv_par_n, xs1, ts1, 0):
b97mv_fos := (rs, z, xs0, xs1, ts0, ts1) ->
lda_stoll_perp(f_pw, rs, z)
* b97mv_g(b97mv_gamma_os, b97mv_wx_os, b97mv_par_os, b97mv_par_n, sqrt(xs0^2 + xs1^2)/sqrt(2), ts0, ts1):
b97mv_f := (rs, z, xs0, xs1, ts0, ts1) ->
+ b97mv_fpar(rs, z, xs0, xs1, ts0, ts1)
+ b97mv_fos(rs, z, xs0, xs1, ts0, ts1):
|
-- ------------------------------------------------------------- [ Forward.idr ]
-- Module : Forward.idr
-- Copyright : (c) Jan de Muijnck-Hughes
-- License : see LICENSE
-- --------------------------------------------------------------------- [ EOH ]
module GRL.Eval.Forward
import Data.AVL.Dict
import Data.AVL.Graph
import Data.Stack
import Data.Queue
import Data.Vect
import GRL.Common
import GRL.Model
import GRL.Eval.Qualitative
import GRL.Eval.Strategy
import GRL.Eval.Common
%default partial
%access private
-- ----------------------------------------------------- [ Forward Propagation ]
private
getSat' : NodeID -> GModel -> Maybe SValue
getSat' id g =
case getValueByID id g of
Nothing => Nothing
Just v => getSValue v
calcDecomp : NodeID -> GModel -> Maybe SValue
calcDecomp id g =
case getValueByID id g of
Nothing => Nothing
Just val =>
case getStructTy val of
Nothing => Nothing
Just dval =>
case dval of
ANDty => Just $ getDecompAnd csat
XORty => Just $ getDecompXOR csat
IORty => Just $ getDecompIOR csat
where
children : List NodeID
children = map fst $ getDeCompEdges id g
csat : List SValue
csat = catMaybes $ map (\x => getSat' x g) children
getWeightedContrib : NodeID -> CValue -> GModel -> Maybe SValue
getWeightedContrib id y g = case getSat' id g of
Nothing => Nothing
Just x => Just $ weightedContrib x y
calcWeightedContrib : DemiEdge GoalEdge -> GModel -> Maybe SValue
calcWeightedContrib (id, Just (Contribution x)) g = getWeightedContrib id x g
calcWeightedContrib (id, Just (Correlation x)) g = getWeightedContrib id x g
calcWeightedContrib _ _ = Nothing
calcContrib : Maybe SValue -> NodeID -> GModel -> SValue
calcContrib dval id g =
if (noUndec count > 0)
then UNDECIDED
else combineContribs count
where
children : List (DemiEdge GoalEdge)
children = getIntentEdges id g
wsat : List SValue
wsat = catMaybes $ map (\e => calcWeightedContrib e g) children
vals : List SValue
vals = case dval of {Nothing => wsat; Just x => x :: wsat}
count : ContribCount
count = adjustCounts vals
evalElem : NodeID -> GModel -> SValue
evalElem e g = calcContrib dVal e g
where
dVal : Maybe SValue
dVal = (calcDecomp e g)
-- -------------------------------------------------------------- [ Init Check ]
validityCheck : GModel -> Bool
validityCheck g = allLeafsValid && not gTy
where
allLeafsValid : Bool
allLeafsValid = and $ map (\x => isJust (getSValue x)) (getValuesByID (leafNodes g) g)
gTy : Bool
gTy = isDisconnected g
initGraph : GModel -> GModel
initGraph g = foldl (doUp) g (leaves)
where
leaves : List GoalNode
leaves = map (\x => if isJust (getSValue x) then x else record {getSValue = Just NONE} x) (getValuesByID (leafNodes g) g)
doUp : GModel -> GoalNode -> GModel
doUp m n = updateGoalNode (\x => getNodeTitle n == getNodeTitle x)
(\x => n)
m
-- ------------------------------------------------------- [ Forward Algorithm ]
partial
export
doEval : GModel -> (Queue NodeID) -> GModel
doEval g q =
case popQ' q of
Nothing => g
Just (c, newQ) => -- TODO
case getValueByID c g of --- if node doesn't exist
Nothing => g
Just c' =>
if isJust $ getSValue c' --- if satisfied then move on
then doEval g newQ
else let cs = children c in
if isNil cs --- if leaf node
then g
else do
if and $ map (\x => isJust $ getSValue x) cs
then doEval (newG c) newQ
else doEval g (pushQ c newQ)
where
childrenIDs : NodeID -> List (DemiEdge GoalEdge)
childrenIDs n = (getEdgesByID n g)
children : NodeID -> List GoalNode
children n = getValuesByID (map fst $ childrenIDs n) g
newG : NodeID -> GModel
newG n = updateNodeValueByIDUsing
n
(\x => record {getSValue = Just (evalElem n g)} x)
g
private
partial
runEval : GModel -> EvalResult
runEval g =
if validityCheck g
then Result (vertices (doEval g (defQueue g)))
else let newG = getNewG g in
let theQ = defQueue newG in
if validityCheck newG
then Result (vertices (doEval newG theQ))
else BadModel
where
getNewG : GModel -> GModel
getNewG m = initGraph m
defQueue : GModel -> Queue NodeID
defQueue m = (pushQThings (verticesID m) mkQueue)
||| Evaluate a model with or without a given strategy.
|||
||| This function will deploy the strategy if it is given. Using this
||| code with a predeployed strategy may give unexpected results.
partial
export
forwardEval : Maybe Strategy -> GModel -> EvalResult
forwardEval Nothing g = runEval g
forwardEval (Just s) g = runEval $ fst (deployStrategy g s)
-- --------------------------------------------------------------------- [ EOF ]
|
/-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen
! This file was ported from Lean 3 source module ring_theory.localization.inv_submonoid
! leanprover-community/mathlib commit 6e7ca692c98bbf8a64868f61a67fb9c33b10770d
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.GroupTheory.Submonoid.Inverses
import Mathbin.RingTheory.FiniteType
import Mathbin.RingTheory.Localization.Basic
import Mathbin.Tactic.RingExp
/-!
# Submonoid of inverses
## Main definitions
* `is_localization.inv_submonoid M S` is the submonoid of `S = M⁻¹R` consisting of inverses of
each element `x ∈ M`
## Implementation notes
See `src/ring_theory/localization/basic.lean` for a design overview.
## Tags
localization, ring localization, commutative ring localization, characteristic predicate,
commutative ring, field of fractions
-/
variable {R : Type _} [CommRing R] (M : Submonoid R) (S : Type _) [CommRing S]
variable [Algebra R S] {P : Type _} [CommRing P]
open Function
open BigOperators
namespace IsLocalization
section InvSubmonoid
variable (M S)
/-- The submonoid of `S = M⁻¹R` consisting of `{ 1 / x | x ∈ M }`. -/
def invSubmonoid : Submonoid S :=
(M.map (algebraMap R S)).left_inv
#align is_localization.inv_submonoid IsLocalization.invSubmonoid
variable [IsLocalization M S]
theorem submonoid_map_le_is_unit : M.map (algebraMap R S) ≤ IsUnit.submonoid S :=
by
rintro _ ⟨a, ha, rfl⟩
exact IsLocalization.map_units S ⟨_, ha⟩
#align is_localization.submonoid_map_le_is_unit IsLocalization.submonoid_map_le_is_unit
/-- There is an equivalence of monoids between the image of `M` and `inv_submonoid`. -/
noncomputable abbrev equivInvSubmonoid : M.map (algebraMap R S) ≃* invSubmonoid M S :=
((M.map (algebraMap R S)).leftInvEquiv (submonoid_map_le_is_unit M S)).symm
#align is_localization.equiv_inv_submonoid IsLocalization.equivInvSubmonoid
/-- There is a canonical map from `M` to `inv_submonoid` sending `x` to `1 / x`. -/
noncomputable def toInvSubmonoid : M →* invSubmonoid M S :=
(equivInvSubmonoid M S).toMonoidHom.comp ((algebraMap R S : R →* S).submonoidMap M)
#align is_localization.to_inv_submonoid IsLocalization.toInvSubmonoid
theorem toInvSubmonoid_surjective : Function.Surjective (toInvSubmonoid M S) :=
Function.Surjective.comp (Equiv.surjective _) (MonoidHom.submonoidMap_surjective _ _)
#align is_localization.to_inv_submonoid_surjective IsLocalization.toInvSubmonoid_surjective
@[simp]
theorem toInvSubmonoid_mul (m : M) : (toInvSubmonoid M S m : S) * algebraMap R S m = 1 :=
Submonoid.leftInvEquiv_symm_mul _ _ _
#align is_localization.to_inv_submonoid_mul IsLocalization.toInvSubmonoid_mul
@[simp]
theorem mul_toInvSubmonoid (m : M) : algebraMap R S m * (toInvSubmonoid M S m : S) = 1 :=
Submonoid.mul_leftInvEquiv_symm _ _ ⟨_, _⟩
#align is_localization.mul_to_inv_submonoid IsLocalization.mul_toInvSubmonoid
@[simp]
theorem smul_toInvSubmonoid (m : M) : m • (toInvSubmonoid M S m : S) = 1 :=
by
convert mul_to_inv_submonoid M S m
rw [← Algebra.smul_def]
rfl
#align is_localization.smul_to_inv_submonoid IsLocalization.smul_toInvSubmonoid
variable {S}
/- warning: is_localization.surj' -> IsLocalization.surj' is a dubious translation:
lean 3 declaration is
forall {R : Type.{u1}} [_inst_1 : CommRing.{u1} R] (M : Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))))) {S : Type.{u2}} [_inst_2 : CommRing.{u2} S] [_inst_3 : Algebra.{u1, u2} R S (CommRing.toCommSemiring.{u1} R _inst_1) (Ring.toSemiring.{u2} S (CommRing.toRing.{u2} S _inst_2))] [_inst_5 : IsLocalization.{u1, u2} R (CommRing.toCommSemiring.{u1} R _inst_1) M S (CommRing.toCommSemiring.{u2} S _inst_2) _inst_3] (z : S), Exists.{succ u1} R (fun (r : R) => Exists.{succ u1} (coeSort.{succ u1, succ (succ u1)} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))))) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))))) R (Submonoid.setLike.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))))))) M) (fun (m : coeSort.{succ u1, succ (succ u1)} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))))) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))))) R (Submonoid.setLike.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))))))) M) => Eq.{succ u2} S z (SMul.smul.{u1, u2} R S (SMulZeroClass.toHasSmul.{u1, u2} R S (AddZeroClass.toHasZero.{u2} S (AddMonoid.toAddZeroClass.{u2} S (AddCommMonoid.toAddMonoid.{u2} S (NonUnitalNonAssocSemiring.toAddCommMonoid.{u2} S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (Ring.toSemiring.{u2} S (CommRing.toRing.{u2} S _inst_2)))))))) (SMulWithZero.toSmulZeroClass.{u1, u2} R S (MulZeroClass.toHasZero.{u1} R (MulZeroOneClass.toMulZeroClass.{u1} R (MonoidWithZero.toMulZeroOneClass.{u1} R (Semiring.toMonoidWithZero.{u1} R (CommSemiring.toSemiring.{u1} R (CommRing.toCommSemiring.{u1} R _inst_1)))))) (AddZeroClass.toHasZero.{u2} S (AddMonoid.toAddZeroClass.{u2} S (AddCommMonoid.toAddMonoid.{u2} S (NonUnitalNonAssocSemiring.toAddCommMonoid.{u2} S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (Ring.toSemiring.{u2} S (CommRing.toRing.{u2} S _inst_2)))))))) (MulActionWithZero.toSMulWithZero.{u1, u2} R S (Semiring.toMonoidWithZero.{u1} R (CommSemiring.toSemiring.{u1} R (CommRing.toCommSemiring.{u1} R _inst_1))) (AddZeroClass.toHasZero.{u2} S (AddMonoid.toAddZeroClass.{u2} S (AddCommMonoid.toAddMonoid.{u2} S (NonUnitalNonAssocSemiring.toAddCommMonoid.{u2} S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (Ring.toSemiring.{u2} S (CommRing.toRing.{u2} S _inst_2)))))))) (Module.toMulActionWithZero.{u1, u2} R S (CommSemiring.toSemiring.{u1} R (CommRing.toCommSemiring.{u1} R _inst_1)) (NonUnitalNonAssocSemiring.toAddCommMonoid.{u2} S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (Ring.toSemiring.{u2} S (CommRing.toRing.{u2} S _inst_2))))) (Algebra.toModule.{u1, u2} R S (CommRing.toCommSemiring.{u1} R _inst_1) (Ring.toSemiring.{u2} S (CommRing.toRing.{u2} S _inst_2)) _inst_3))))) r ((fun (a : Type.{u2}) (b : Type.{u2}) [self : HasLiftT.{succ u2, succ u2} a b] => self.0) (coeSort.{succ u2, succ (succ u2)} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) Type.{u2} (SetLike.hasCoeToSort.{u2, u2} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) S (Submonoid.setLike.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2))))))) (IsLocalization.invSubmonoid.{u1, u2} R _inst_1 M S _inst_2 _inst_3)) S (HasLiftT.mk.{succ u2, succ u2} (coeSort.{succ u2, succ (succ u2)} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) Type.{u2} (SetLike.hasCoeToSort.{u2, u2} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) S (Submonoid.setLike.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2))))))) (IsLocalization.invSubmonoid.{u1, u2} R _inst_1 M S _inst_2 _inst_3)) S (CoeTCₓ.coe.{succ u2, succ u2} (coeSort.{succ u2, succ (succ u2)} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) Type.{u2} (SetLike.hasCoeToSort.{u2, u2} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) S (Submonoid.setLike.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2))))))) (IsLocalization.invSubmonoid.{u1, u2} R _inst_1 M S _inst_2 _inst_3)) S (coeBase.{succ u2, succ u2} (coeSort.{succ u2, succ (succ u2)} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) Type.{u2} (SetLike.hasCoeToSort.{u2, u2} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) S (Submonoid.setLike.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2))))))) (IsLocalization.invSubmonoid.{u1, u2} R _inst_1 M S _inst_2 _inst_3)) S (coeSubtype.{succ u2} S (fun (x : S) => Membership.Mem.{u2, u2} S (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) (SetLike.hasMem.{u2, u2} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) S (Submonoid.setLike.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2))))))) x (IsLocalization.invSubmonoid.{u1, u2} R _inst_1 M S _inst_2 _inst_3)))))) (coeFn.{max (succ u2) (succ u1), max (succ u1) (succ u2)} (MonoidHom.{u1, u2} (coeSort.{succ u1, succ (succ u1)} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))))) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))))) R (Submonoid.setLike.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))))))) M) (coeSort.{succ u2, succ (succ u2)} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) Type.{u2} (SetLike.hasCoeToSort.{u2, u2} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) S (Submonoid.setLike.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2))))))) (IsLocalization.invSubmonoid.{u1, u2} R _inst_1 M S _inst_2 _inst_3)) (Submonoid.toMulOneClass.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))))) M) (Submonoid.toMulOneClass.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2))))) (IsLocalization.invSubmonoid.{u1, u2} R _inst_1 M S _inst_2 _inst_3))) (fun (_x : MonoidHom.{u1, u2} (coeSort.{succ u1, succ (succ u1)} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))))) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))))) R (Submonoid.setLike.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))))))) M) (coeSort.{succ u2, succ (succ u2)} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) Type.{u2} (SetLike.hasCoeToSort.{u2, u2} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) S (Submonoid.setLike.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2))))))) (IsLocalization.invSubmonoid.{u1, u2} R _inst_1 M S _inst_2 _inst_3)) (Submonoid.toMulOneClass.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))))) M) (Submonoid.toMulOneClass.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2))))) (IsLocalization.invSubmonoid.{u1, u2} R _inst_1 M S _inst_2 _inst_3))) => (coeSort.{succ u1, succ (succ u1)} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))))) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))))) R (Submonoid.setLike.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))))))) M) -> (coeSort.{succ u2, succ (succ u2)} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) Type.{u2} (SetLike.hasCoeToSort.{u2, u2} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) S (Submonoid.setLike.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2))))))) (IsLocalization.invSubmonoid.{u1, u2} R _inst_1 M S _inst_2 _inst_3))) (MonoidHom.hasCoeToFun.{u1, u2} (coeSort.{succ u1, succ (succ u1)} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))))) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1)))))) R (Submonoid.setLike.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))))))) M) (coeSort.{succ u2, succ (succ u2)} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) Type.{u2} (SetLike.hasCoeToSort.{u2, u2} (Submonoid.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2)))))) S (Submonoid.setLike.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2))))))) (IsLocalization.invSubmonoid.{u1, u2} R _inst_1 M S _inst_2 _inst_3)) (Submonoid.toMulOneClass.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (NonAssocRing.toNonAssocSemiring.{u1} R (Ring.toNonAssocRing.{u1} R (CommRing.toRing.{u1} R _inst_1))))) M) (Submonoid.toMulOneClass.{u2} S (MulZeroOneClass.toMulOneClass.{u2} S (NonAssocSemiring.toMulZeroOneClass.{u2} S (NonAssocRing.toNonAssocSemiring.{u2} S (Ring.toNonAssocRing.{u2} S (CommRing.toRing.{u2} S _inst_2))))) (IsLocalization.invSubmonoid.{u1, u2} R _inst_1 M S _inst_2 _inst_3))) (IsLocalization.toInvSubmonoid.{u1, u2} R _inst_1 M S _inst_2 _inst_3 _inst_5) m)))))
but is expected to have type
forall {R : Type.{u1}} [_inst_1 : CommSemiring.{u1} R] {M : Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))} {S : Type.{u2}} [_inst_2 : CommSemiring.{u2} S] [_inst_3 : Algebra.{u1, u2} R S _inst_1 (CommSemiring.toSemiring.{u2} S _inst_2)] [_inst_5 : IsLocalization.{u1, u2} R _inst_1 M S _inst_2 _inst_3] (z : S), Exists.{succ u1} (Prod.{u1, u1} R (Subtype.{succ u1} R (fun (x : R) => Membership.mem.{u1, u1} R (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))) (SetLike.instMembership.{u1, u1} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))) R (Submonoid.instSetLikeSubmonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)))))) x M))) (fun (r : Prod.{u1, u1} R (Subtype.{succ u1} R (fun (x : R) => Membership.mem.{u1, u1} R (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))) (SetLike.instMembership.{u1, u1} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))) R (Submonoid.instSetLikeSubmonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)))))) x M))) => Eq.{succ u2} S (HMul.hMul.{u2, u2, u2} S ((fun ([email protected]._hyg.2391 : R) => S) (Subtype.val.{succ u1} R (fun (x : R) => Membership.mem.{u1, u1} R (Set.{u1} R) (Set.instMembershipSet.{u1} R) x (SetLike.coe.{u1, u1} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))) R (Submonoid.instSetLikeSubmonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))) M)) (Prod.snd.{u1, u1} R (Subtype.{succ u1} R (fun (x : R) => Membership.mem.{u1, u1} R (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))) (SetLike.instMembership.{u1, u1} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))) R (Submonoid.instSetLikeSubmonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)))))) x M)) r))) S (instHMul.{u2} S (NonUnitalNonAssocSemiring.toMul.{u2} S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2))))) z (FunLike.coe.{max (succ u1) (succ u2), succ u1, succ u2} (RingHom.{u1, u2} R S (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2))) R (fun (a : R) => (fun ([email protected]._hyg.2391 : R) => S) a) (MulHomClass.toFunLike.{max u1 u2, u1, u2} (RingHom.{u1, u2} R S (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2))) R S (NonUnitalNonAssocSemiring.toMul.{u1} R (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)))) (NonUnitalNonAssocSemiring.toMul.{u2} S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2)))) (NonUnitalRingHomClass.toMulHomClass.{max u1 u2, u1, u2} (RingHom.{u1, u2} R S (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2))) R S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))) (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2))) (RingHomClass.toNonUnitalRingHomClass.{max u1 u2, u1, u2} (RingHom.{u1, u2} R S (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2))) R S (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2)) (RingHom.instRingHomClassRingHom.{u1, u2} R S (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2)))))) (algebraMap.{u1, u2} R S _inst_1 (CommSemiring.toSemiring.{u2} S _inst_2) _inst_3) (Subtype.val.{succ u1} R (fun (x : R) => Membership.mem.{u1, u1} R (Set.{u1} R) (Set.instMembershipSet.{u1} R) x (SetLike.coe.{u1, u1} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))) R (Submonoid.instSetLikeSubmonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))) M)) (Prod.snd.{u1, u1} R (Subtype.{succ u1} R (fun (x : R) => Membership.mem.{u1, u1} R (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))) (SetLike.instMembership.{u1, u1} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))) R (Submonoid.instSetLikeSubmonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)))))) x M)) r)))) (FunLike.coe.{max (succ u1) (succ u2), succ u1, succ u2} (RingHom.{u1, u2} R S (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2))) R (fun (a : R) => (fun ([email protected]._hyg.2391 : R) => S) a) (MulHomClass.toFunLike.{max u1 u2, u1, u2} (RingHom.{u1, u2} R S (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2))) R S (NonUnitalNonAssocSemiring.toMul.{u1} R (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)))) (NonUnitalNonAssocSemiring.toMul.{u2} S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2)))) (NonUnitalRingHomClass.toMulHomClass.{max u1 u2, u1, u2} (RingHom.{u1, u2} R S (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2))) R S (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))) (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} S (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2))) (RingHomClass.toNonUnitalRingHomClass.{max u1 u2, u1, u2} (RingHom.{u1, u2} R S (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2))) R S (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2)) (RingHom.instRingHomClassRingHom.{u1, u2} R S (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)) (Semiring.toNonAssocSemiring.{u2} S (CommSemiring.toSemiring.{u2} S _inst_2)))))) (algebraMap.{u1, u2} R S _inst_1 (CommSemiring.toSemiring.{u2} S _inst_2) _inst_3) (Prod.fst.{u1, u1} R (Subtype.{succ u1} R (fun (x : R) => Membership.mem.{u1, u1} R (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))) (SetLike.instMembership.{u1, u1} (Submonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1))))) R (Submonoid.instSetLikeSubmonoid.{u1} R (MulZeroOneClass.toMulOneClass.{u1} R (NonAssocSemiring.toMulZeroOneClass.{u1} R (Semiring.toNonAssocSemiring.{u1} R (CommSemiring.toSemiring.{u1} R _inst_1)))))) x M)) r)))
Case conversion may be inaccurate. Consider using '#align is_localization.surj' IsLocalization.surj'ₓ'. -/
theorem surj' (z : S) : ∃ (r : R)(m : M), z = r • toInvSubmonoid M S m :=
by
rcases IsLocalization.surj M z with ⟨⟨r, m⟩, e : z * _ = algebraMap R S r⟩
refine' ⟨r, m, _⟩
rw [Algebra.smul_def, ← e, mul_assoc]
simp
#align is_localization.surj' IsLocalization.surj'
theorem toInvSubmonoid_eq_mk' (x : M) : (toInvSubmonoid M S x : S) = mk' S 1 x :=
by
rw [← (IsLocalization.map_units S x).mul_left_inj]
simp
#align is_localization.to_inv_submonoid_eq_mk' IsLocalization.toInvSubmonoid_eq_mk'
theorem mem_invSubmonoid_iff_exists_mk' (x : S) : x ∈ invSubmonoid M S ↔ ∃ m : M, mk' S 1 m = x :=
by
simp_rw [← to_inv_submonoid_eq_mk']
exact
⟨fun h => ⟨_, congr_arg Subtype.val (to_inv_submonoid_surjective M S ⟨x, h⟩).choose_spec⟩,
fun h => h.choose_spec ▸ (to_inv_submonoid M S h.some).Prop⟩
#align is_localization.mem_inv_submonoid_iff_exists_mk' IsLocalization.mem_invSubmonoid_iff_exists_mk'
variable (S)
theorem span_invSubmonoid : Submodule.span R (invSubmonoid M S : Set S) = ⊤ :=
by
rw [eq_top_iff]
rintro x -
rcases IsLocalization.surj' M x with ⟨r, m, rfl⟩
exact Submodule.smul_mem _ _ (Submodule.subset_span (to_inv_submonoid M S m).Prop)
#align is_localization.span_inv_submonoid IsLocalization.span_invSubmonoid
theorem finiteType_of_monoid_fg [Monoid.Fg M] : Algebra.FiniteType R S :=
by
have := Monoid.fg_of_surjective _ (to_inv_submonoid_surjective M S)
rw [Monoid.fg_iff_submonoid_fg] at this
rcases this with ⟨s, hs⟩
refine' ⟨⟨s, _⟩⟩
rw [eq_top_iff]
rintro x -
change x ∈ ((Algebra.adjoin R _ : Subalgebra R S).toSubmodule : Set S)
rw [Algebra.adjoin_eq_span, hs, span_inv_submonoid]
trivial
#align is_localization.finite_type_of_monoid_fg IsLocalization.finiteType_of_monoid_fg
end InvSubmonoid
end IsLocalization
|
% !TEX root = Documentation.tex
\chapter{Database}
The database for the projects are API-compatible, SQL databases, which run on freely available linux systems. Eventually the used and tested MySQL or MariaDB databases could be
replaced by other systems, such as MSSQL. Nevertheless, a full compatibility of other databases with the source code provided can not be guaranteed. To ensure safe operation of the
server, databases, which are not directly linked to the project data, are separated from the main database. As a result, the login database and the external logging database are
separated from the main database. Therefore, three different databases exist for the purpose of the project.\\
To increase the security of the database and to limit the risk of damage in case of SQL-injections, all databases are accessed by non-privileged users.
These users are created, using the following syntax:
\begin{lstlisting}[language=sql]
CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';
\end{lstlisting}
To grant rights on specific databases to the users, the following syntax is used:
\begin{lstlisting}[language=sql]
GRANT SELECT, INSERT, DELETE, UPDATE, INDEX ON `table`.* TO 'username'@'localhost';
\end{lstlisting}
Furthermore, there is a
separation in the users, regarding the function of the database invoked, to limit access to sensitive data in the database. As the project does not require external programm access
to the database, the network access to the database is limited to localhost.
\section{agri\_star\_001}
The agri\_star\_001 database is the main productive database in the whole project, as it serves as the major saving space for data gathered in the project. In the project's initial
shape, the agri\_star\_001 should have been the only database in the project, but during the development of the web frontend, further databases have been added for several
reasons.\\
As already indicated in the introduction, the database uses a star schemed structure, to allow quick access to all data in the different tables. The tables are the following:
\begin{itemize}
\item \textbf{Dim\_Animal} → contains information related to an individual animal
\item \textbf{Dim\_Country} → contains the ISO abbreviations for the countries, where the contributing institutions come from
\item \textbf{Dim\_Farm} → contains information on the farm level
\item \textbf{Dim\_Gage} → contains information on the applied measuring methods in the project
\item \textbf{Dim\_Group} → group related information, such as the address, the responsible person and the country. As already mentioned in the
\hyperref[create_institution_script.php]{create\_institution\_script.php}, the group table includes the information for each department individually. Therefore, an institution
with multiple departments, taking part in the project, has multiple entries in the Dim\_Group table.
\item \textbf{Dim\_Time} →
\item \textbf{Dim\_Timezone} → table to keep the timezones for the different partners in the project
\item \textbf{Dim\_Trait} →
\item \textbf{Dim\_User} → user related information, such as related institution, etc.
\item \textbf{Search} → Important to save the searches of users, to allow multiple search requests with the same settings
\item \textbf{dates} →
\item \textbf{files} → table to save files for the import into the database. Mainly used by the interface scripts of the web frontend and the database scripts
\item \textbf{grants} → Translation table to implement an access control list (ACL) system. This table stores all possible connections between groups, to allow foreign access on
data
\item \textbf{numbers} →
\item \textbf{numbers\_kl} →
\item \textbf{numbers\_small} →
\end{itemize}
\begin{figure}[h!]
\centering
\includegraphics[width=10cm,keepaspectratio=true]{./agri_star_001-structure.png}
% agri_star_001-structure.png: 0x0 pixel, 300dpi, 0.00x0.00 cm, bb=
\caption{Original Structure of the agri\_star\_001 Database}
\end{figure}
\noindent For data access during operation, the sql requests might be combined, if the required data are spread on different tables. This might lead to JOIN requests, combining
different sql queries in one go. Further connection of the tables happens over the interface software, which usually treats the tables as single units, but can also connect them.\\
In many tables, the primary key is set automatically as auto increment, to ensure that all datasets have unique keys. Manual setting of the keys might under certain circumstances
lead to multiple data sets, having the same primary key, as the random function to generate the key number might output the same number under different circumstances.
\section{user\_auth}
The user\_auth database is an auxiliary database to the agri\_star\_001 database. It is required to allow logins to the web frontend, as it saves the authentication information
for the users. Unlike agri\_star\_001 database, user\_auth just contains one table (auth), which includes all required information, basically the username, the password hash and the
ID\_User. For security reasons, these information have been separated from the Dim\_User table in agri\_star\_001. The ID\_User in the user\_auth database matches the ID\_User
value in the Dim\_User table, as it is taken over from the transaction id of the user creation in the Dim\_User table. During login process, the first requests are all the
user\_auth database, to prevent external attacks on the main database. Furthermore, the user\_auth database has an own dedicated user, which does not have any rights on other
databases, to access the database.
\section{logdb}
For security reasons, the web frontend includes some logging, which writes the results into a designated database. This database consists of three tables, which are not depending
on any other frontend solution, except for the traffic.php page. If a browser hits the login.php page, the access IP, the user agent of the browser invoked and the time of access
are logged. To comply with the requirement not to store unnecessary individual data, the IP address is shortened to three blocks.\\
In case the user logs in, the same data, including the ID\_User are stored, whereas failed login attempts are logged with time, username, user agent and IP address. The use of
this data is just for internal issues, such as preventing brute force attacks. It is not part of the project, to collect user data.\\
To avoid the aggregation of old logdata into the database, an event is created to ensure the frequent deletion of old log entries on the access database. Therefore, the
following SQL command is used:
\begin{lstlisting}[language=sql]
CREATE EVENT logrotate ON SCHEDULE EVERY 1 WEEK DO DELETE FROM Log_Table WHERE time < NOW() - 60*60*24*7;
\end{lstlisting}
\section{sessions}\label{sessions_database}
In order to allow scalability of the whole user interface and to improve the quality of the sessions, session data are stored in a separate database, which is called sessions.
The database has only one table, which is called sessions aswell and consists of three columns: \textbf{ID}, \textbf{last\_activity} and \textbf{data}. The first column contains the
\texttt{session\_id()}, the second one a timestamp with the most recent activity in the session and the last column contains all session data for the individual session.
All entries are administrated by the \hyperref[session-handler]{\textit{session handler}} for php.
\section{credentials}
To store credentials for external webservices and further information required to establish the connection to these services, a special database is prepared. This database has a similar structure as the user\_auth database, which also just consists of one table. Unlike the user\_auth table, the database provides more columns, which include the ID\_User, the service for which the information is stored, the username to the service, the password to the service, eventually the token to access the service and further information to access the service.
|
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 1998-2011, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
// clang-format off
#include "PyImathConfigInternal.h"
#include "PyImathFrustum.h"
#include "PyImathDecorators.h"
#include "PyImathExport.h"
#include <Python.h>
#include <boost/python.hpp>
#include <boost/format.hpp>
#include "PyImath.h"
#include "PyImathMathExc.h"
#include "PyImathVec.h"
namespace PyImath{
using namespace boost::python;
using namespace IMATH_NAMESPACE;
template <class T> struct FrustumName {static const char *value;};
template <> const char *FrustumName<float>::value = "Frustumf";
template <> const char *FrustumName<double>::value = "Frustumd";
template <class T> struct FrustumTestName {static const char *value;};
template <> const char *FrustumTestName<float>::value = "FrustumTestf";
template <> const char *FrustumTestName<double>::value = "FrustumTestd";
template <class T>
static std::string Frustum_repr(const Frustum<T> &f)
{
std::stringstream stream;
stream << FrustumName<T>::value << "(" << f.nearPlane() << ", " << f.farPlane() << ", "
<< f.left() << ", " << f.right() << ", " << f.top() << ", "
<< f.bottom() << ", " << f.orthographic() << ")";
return stream.str();
}
template <class T>
static void
modifyNearAndFar(Frustum<T> &f, T nearPlane, T farPlane)
{
MATH_EXC_ON;
f.modifyNearAndFar (nearPlane, farPlane);
}
template <class T>
static T
fovx(Frustum<T> &f)
{
MATH_EXC_ON;
return f.fovx();
}
template <class T>
static T
fovy(Frustum<T> &f)
{
MATH_EXC_ON;
return f.fovy();
}
template <class T>
static T
aspect(Frustum<T> &f)
{
MATH_EXC_ON;
return f.aspect();
}
template <class T>
static Matrix44<T>
projectionMatrix(Frustum<T> &f)
{
MATH_EXC_ON;
return f.projectionMatrix();
}
template <class T>
static Frustum<T>
window (Frustum<T> &f, T l, T r, T b, T t)
{
MATH_EXC_ON;
return f.window(l, r, b, t);
}
template <class T>
static Line3<T>
projectScreenToRay (Frustum<T> &f, const Vec2<T> &p)
{
MATH_EXC_ON;
return f.projectScreenToRay(p);
}
template <class T>
static Line3<T>
projectScreenToRayTuple(Frustum<T> &f, const tuple &t)
{
MATH_EXC_ON;
if(t.attr("__len__")() == 2)
{
Vec2<T> point;
point.x = extract<T>(t[0]);
point.y = extract<T>(t[1]);
return f.projectScreenToRay(point);
}
else
throw std::invalid_argument ( "projectScreenToRay expects tuple of length 2");
}
template <class T>
static Vec2<T>
projectPointToScreen (Frustum<T> &f, const Vec3<T> &p)
{
MATH_EXC_ON;
return f.projectPointToScreen(p);
}
template <class T>
static Vec2<T>
projectPointToScreenTuple(Frustum<T> &f, const tuple &t)
{
MATH_EXC_ON;
if(t.attr("__len__")() == 3)
{
Vec3<T> point;
point.x = extract<T>(t[0]);
point.y = extract<T>(t[1]);
point.z = extract<T>(t[2]);
return f.projectPointToScreen(point);
}
else
throw std::invalid_argument ( "projectPointToScreen expects tuple of length 3");
}
template <class T>
static Vec2<T>
projectPointToScreenObj(Frustum<T> &f, const object &o)
{
MATH_EXC_ON;
Vec3<T> v;
if (PyImath::V3<T>::convert (o.ptr(), &v))
return f.projectPointToScreen(v);
else
throw std::invalid_argument ( "projectPointToScreen expects tuple of length 3");
}
template <class T>
static T
ZToDepth(Frustum<T> &f, long z, long min, long max)
{
MATH_EXC_ON;
return f.ZToDepth(z, min, max);
}
template <class T>
static T
normalizedZToDepth(Frustum<T> &f, T z)
{
MATH_EXC_ON;
return f.normalizedZToDepth(z);
}
template <class T>
static long
DepthToZ(Frustum<T> &f, T depth, long min, long max)
{
MATH_EXC_ON;
return f.DepthToZ(depth, min, max);
}
template <class T>
static T
worldRadius(Frustum<T> &f, const Vec3<T> &p, T radius)
{
MATH_EXC_ON;
return f.worldRadius(p, radius);
}
template <class T>
static T
worldRadiusTuple(Frustum<T> &f, const tuple &t, T radius)
{
MATH_EXC_ON;
if(t.attr("__len__")() == 3)
{
Vec3<T> point;
point.x = extract<T>(t[0]);
point.y = extract<T>(t[1]);
point.z = extract<T>(t[2]);
return f.worldRadius(point, radius);
}
else
throw std::invalid_argument ( "worldRadius expects tuple of length 3");
}
template <class T>
static T
screenRadius(Frustum<T> &f, const Vec3<T> &p, T radius)
{
MATH_EXC_ON;
return f.screenRadius(p, radius);
}
template <class T>
static T
screenRadiusTuple(Frustum<T> &f, const tuple &t, T radius)
{
MATH_EXC_ON;
if(t.attr("__len__")() == 3)
{
Vec3<T> point;
point.x = extract<T>(t[0]);
point.y = extract<T>(t[1]);
point.z = extract<T>(t[2]);
return f.screenRadius(point, radius);
}
else
throw std::invalid_argument ("screenRadius expects tuple of length 3");
}
template <class T>
static void
planes1(Frustum<T> &f, Plane3<T> *p)
{
MATH_EXC_ON;
f.planes(p);
}
template <class T>
static void
planes2(Frustum<T> &f, Plane3<T> *p, const Matrix44<T> &m)
{
MATH_EXC_ON;
f.planes(p, m);
}
template <class T>
static tuple
planes3(Frustum<T> &f, const Matrix44<T> &mat)
{
MATH_EXC_ON;
IMATH_NAMESPACE::Plane3<T> p[6];
f.planes(p,mat);
tuple t = make_tuple(p[0],p[1],p[2],p[3],p[4],p[5]);
return t;
}
template <class T>
static tuple
planes4(Frustum<T> &f)
{
MATH_EXC_ON;
IMATH_NAMESPACE::Plane3<T> p[6];
f.planes(p);
tuple t = make_tuple(p[0],p[1],p[2],p[3],p[4],p[5]);
return t;
}
template <class T>
class_<Frustum<T> >
register_Frustum()
{
void (IMATH_NAMESPACE::Frustum<T>::*set1)(T,T,T,T,T,T,bool) = &IMATH_NAMESPACE::Frustum<T>::set;
void (IMATH_NAMESPACE::Frustum<T>::*set2)(T,T,T,T,T) = &IMATH_NAMESPACE::Frustum<T>::set;
const char *name = FrustumName<T>::value;
class_< Frustum<T> > frustum_class(name,name,init<Frustum<T> >("copy construction"));
frustum_class
.def(init<>("Frustum() default construction"))
.def(init<T,T,T,T,T,T,bool>("Frustum(nearPlane,farPlane,left,right,top,bottom,ortho) construction"))
.def(init<T,T,T,T,T>("Frustum(nearPlane,farPlane,fovx,fovy,aspect) construction"))
.def(self == self) // NOSONAR - suppress SonarCloud bug report.
.def(self != self) // NOSONAR - suppress SonarCloud bug report.
.def("__repr__",&Frustum_repr<T>)
.def("set", set1,
"F.set(nearPlane, farPlane, left, right, top, bottom, "
"[ortho])\n"
"F.set(nearPlane, farPlane, fovx, fovy, aspect) "
" -- sets the entire state of "
"frustum F as specified. Only one of "
"fovx or fovy may be non-zero.")
.def("set", set2)
.def("modifyNearAndFar", &modifyNearAndFar<T>,
"F.modifyNearAndFar(nearPlane, farPlane) -- modifies "
"the already-valid frustum F as specified")
.def("setOrthographic", &Frustum<T>::setOrthographic,
"F.setOrthographic(b) -- modifies the "
"already-valid frustum F to be orthographic "
"or not")
.def("nearPlane", &Frustum<T>::nearPlane,
"F.nearPlane() -- returns the coordinate of the "
"near clipping plane of frustum F")
.def("farPlane", &Frustum<T>::farPlane,
"F.farPlane() -- returns the coordinate of the "
"far clipping plane of frustum F")
// The following two functions provide backwards compatibility
// with the previous API for this class.
.def("near", &Frustum<T>::nearPlane,
"F.near() -- returns the coordinate of the "
"near clipping plane of frustum F")
.def("far", &Frustum<T>::farPlane,
"F.far() -- returns the coordinate of the "
"far clipping plane of frustum F")
.def("left", &Frustum<T>::left,
"F.left() -- returns the left coordinate of "
"the near clipping window of frustum F")
.def("right", &Frustum<T>::right,
"F.right() -- returns the right coordinate of "
"the near clipping window of frustum F")
.def("top", &Frustum<T>::top,
"F.top() -- returns the top coordinate of "
"the near clipping window of frustum F")
.def("bottom", &Frustum<T>::bottom,
"F.bottom() -- returns the bottom coordinate "
"of the near clipping window of frustum F")
.def("orthographic", &Frustum<T>::orthographic,
"F.orthographic() -- returns whether frustum "
"F is orthographic or not")
.def("planes", planes1<T>,
"F.planes([M]) -- returns a sequence of 6 "
"Plane3s, the sides of the frustum F "
"(top, right, bottom, left, nearPlane, farPlane), "
"optionally transformed by the matrix M "
"if specified")
.def("planes", planes2<T>)
.def("planes", planes3<T>)
.def("planes", planes4<T>)
.def("fovx", &fovx<T>,
"F.fovx() -- derives and returns the "
"x field of view (in radians) for frustum F")
.def("fovy", &fovy<T>,
"F.fovy() -- derives and returns the "
"y field of view (in radians) for frustum F")
.def("aspect", &aspect<T>,
"F.aspect() -- derives and returns the "
"aspect ratio for frustum F")
.def("projectionMatrix", &projectionMatrix<T>,
"F.projectionMatrix() -- derives and returns "
"the projection matrix for frustum F")
.def("window", &window<T>,
"F.window(l,r,b,t) -- takes a rectangle in "
"the screen space (i.e., -1 <= l <= r <= 1, "
"-1 <= b <= t <= 1) of F and returns a new "
"Frustum whose near clipping-plane window "
"is that rectangle in local space")
.def("projectScreenToRay", &projectScreenToRay<T>,
"F.projectScreenToRay(V) -- returns a Line3 "
"through V, a V2 point in screen space")
.def("projectScreenToRay", &projectScreenToRayTuple<T>)
.def("projectPointToScreen", &projectPointToScreen<T>,
"F.projectPointToScreen(V) -- returns the "
"projection of V3 V into screen space")
.def("projectPointToScreen", &projectPointToScreenTuple<T>)
.def("projectPointToScreen", &projectPointToScreenObj<T>)
.def("ZToDepth", &ZToDepth<T>,
"F.ZToDepth(z, zMin, zMax) -- returns the "
"depth (Z in the local space of the "
"frustum F) corresponding to z (a result of "
"transformation by F's projection matrix) "
"after normalizing z to be between zMin "
"and zMax")
.def("normalizedZToDepth", &normalizedZToDepth<T>,
"F.normalizedZToDepth(z) -- returns the "
"depth (Z in the local space of the "
"frustum F) corresponding to z (a result of "
"transformation by F's projection matrix), "
"which is assumed to have been normalized "
"to [-1, 1]")
.def("DepthToZ", &DepthToZ<T>,
"F.DepthToZ(depth, zMin, zMax) -- converts "
"depth (Z in the local space of the frustum "
"F) to z (a result of transformation by F's "
"projection matrix) which is normalized to "
"[zMin, zMax]")
.def("worldRadius", &worldRadius<T>,
"F.worldRadius(V, r) -- returns the radius "
"in F's local space corresponding to the "
"point V and radius r in screen space")
.def("worldRadius", &worldRadiusTuple<T>)
.def("screenRadius", &screenRadius<T>,
"F.screenRadius(V, r) -- returns the radius "
"in screen space corresponding to "
"the point V and radius r in F's local "
"space")
.def("screenRadius", &screenRadiusTuple<T>)
;
decoratecopy(frustum_class);
return frustum_class;
}
template <class T,class T2>
struct IsVisibleTask : public Task
{
const IMATH_NAMESPACE::FrustumTest<T>& frustumTest;
const PyImath::FixedArray<T2>& points;
PyImath::FixedArray<int>& results;
IsVisibleTask(const IMATH_NAMESPACE::FrustumTest<T>& ft, const PyImath::FixedArray<T2> &p, PyImath::FixedArray<int> &r)
: frustumTest(ft), points(p), results(r) {}
void execute(size_t start, size_t end)
{
for(size_t p = start; p < end; ++p)
results[p] = frustumTest.isVisible(IMATH_NAMESPACE::Vec3<T>(points[p]));
}
};
template <class T,class T2>
PyImath::FixedArray<int>
frustumTest_isVisible(IMATH_NAMESPACE::FrustumTest<T>& ft, const PyImath::FixedArray<T2>& points)
{
size_t numPoints = points.len();
PyImath::FixedArray<int> mask(numPoints);
IsVisibleTask<T,T2> task(ft,points,mask);
dispatchTask(task,numPoints);
return mask;
}
template <class T>
class_<FrustumTest<T> >
register_FrustumTest()
{
const char *name = FrustumTestName<T>::value;
bool (FrustumTest<T>::*isVisibleS)(const Sphere3<T> &) const = &FrustumTest<T>::isVisible;
bool (FrustumTest<T>::*isVisibleB)(const Box<Vec3<T> > &) const = &FrustumTest<T>::isVisible;
bool (FrustumTest<T>::*isVisibleV)(const Vec3<T> &) const = &FrustumTest<T>::isVisible;
bool (FrustumTest<T>::*completelyContainsS)(const Sphere3<T> &) const = &FrustumTest<T>::completelyContains;
bool (FrustumTest<T>::*completelyContainsB)(const Box<Vec3<T> > &) const = &FrustumTest<T>::completelyContains;
class_< FrustumTest<T> > frustumtest_class(name,name,init<const IMATH_NAMESPACE::Frustum<T>&,const IMATH_NAMESPACE::Matrix44<T>&>("create a frustum test object from a frustum and transform"));
frustumtest_class
.def("isVisible",isVisibleS)
.def("isVisible",isVisibleB)
.def("isVisible",isVisibleV)
.def("isVisible",&frustumTest_isVisible<T,IMATH_NAMESPACE::V3f>)
.def("completelyContains",completelyContainsS)
.def("completelyContains",completelyContainsB)
;
decoratecopy(frustumtest_class);
return frustumtest_class;
}
template PYIMATH_EXPORT class_<Frustum<float> > register_Frustum<float>();
template PYIMATH_EXPORT class_<Frustum<double> > register_Frustum<double>();
template PYIMATH_EXPORT class_<FrustumTest<float> > register_FrustumTest<float>();
template PYIMATH_EXPORT class_<FrustumTest<double> > register_FrustumTest<double>();
}
|
The former Fifth Harmony has everything ready for her great solo debut.
Lauren Jauregui continues to fine-tune the preparations for the release of her first solo album, she confirmed in an interview with LA Times . The 21-year-old singer has a very special adjective for this album: Liberador. “It has been an incredibly liberating process, I really let myself be guided by not having any inhibition about what I was going to say or how I was going to get out,” he said, “you have really been therapeutic, (because it has allowed you) to immerse yourself in my mind”. |
C Copyright(C) 1999-2020 National Technology & Engineering Solutions
C of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
C NTESS, the U.S. Government retains certain rights in this software.
C
C See packages/seacas/LICENSE for details
SUBROUTINE LTADD (MDIM, MDIMO, N, LINK, IHOLD)
C***********************************************************************
C SUBROUTINE LTADD = LOOKUP TABLE REINSURTION FOR DATA POINTER ARRAYS
C***********************************************************************
C VARIABLES USED:
C MDIM = DIMENSION OF LINK ARRAY, AND BASE FOR LOOKUP START
C LINK = LOOKUP TABLE ARRAY OF ID'S AND POINTERS
C LINK(1,I) = ID VALUE STORED IN I'TH ROW (0 IF EMPTY)
C LINK(2,I) = DATA POINTER ASSOCIATED W/THIS I'TH ID VALUE
C IHOLD = TEMPORARY LINK ARRAY TO BE USED FOR REINSURRTION
C***********************************************************************
DIMENSION LINK(2,MDIM), IHOLD(2,MDIM)
LOGICAL ADDLNK
ADDLNK=.TRUE.
C SORT THROUGH THE ORIGINAL LINK LIST AND LINK VALID ENTRIES IN THE
C IHOLD LIST
DO 100 I = 1, MDIMO
IF ( (LINK(1,I) .NE. 0) .AND. (LINK(2,I) .LE. N) )
& CALL LTSORT (MDIM, IHOLD, IABS(LINK(1,I)), LINK(2,I),
& ADDLNK)
100 CONTINUE
C TRANSFER THE IHOLD LIST BACK TO THE LINK LIST
DO 120 I = 1, MDIM
DO 110 J = 1, 2
LINK(J,I) = IHOLD (J, I)
110 CONTINUE
120 CONTINUE
RETURN
END
|
! Objetivo: Usar pares ordenados a partir de um gerador aleatorio do
! tipo rapido e "sujo" para obter coordenadas de pontos em
! um espaço bidimensional.
PROGRAM aleatorio_sujo_xy
IMPLICIT none
INTEGER, PARAMETER :: im = 6075, ia = 106, ic = 1283
REAL, PARAMETER :: im_real = REAL(im)
REAL :: ran_x, ran_y
INTEGER, PARAMETER :: dados_aleatorio_xy = 7
INTEGER :: num_repeticoes, jran = 1
! Abrir arquivo.dat de saida de dados
OPEN(dados_aleatorio_xy,FILE="dados_aleatorio_xy.dat")
! Essas constantes dao um periodo de comprimento máximo im. Por isso im eh a
! quantidade de numeros aleatorios gerados diferentes. O gerador produz 2*im numeros
! aleatorios pois im eh impar. O primeiro numero a repetir sera na coordenada y, pois
! im eh impar e estamos distribuindo aos pares. O primeiro numero a se repetir na
! coordenada x sera apos 2im numeros gerados.
DO num_repeticoes = 1, im
jran = MOD(jran*ia+ic,im)
ran_x = REAL(jran)/im_real
jran = MOD(jran*ia+ic,im)
ran_y = REAL(jran)/im_real
! Escrever as coordenadas no arquivo de dados
WRITE(dados_aleatorio_xy,*) ran_x,ran_y
END DO
! Fechar arquivo.dat de saida de dados
CLOSE(dados_aleatorio_xy)
END PROGRAM aleatorio_sujo_xy
|
\title{Reference}
{{navbar}}
There are four modules in Edward:
\texttt{ed.criticisms},
\texttt{ed.inferences},
\texttt{ed.models},
and
\texttt{ed.util}.
\subsubsection{Criticism}
\texttt{ed.criticisms} is comprised of functions. They operate on
random variables in a model or they operate on NumPy arrays
representing values drawn from the random variables.
\begin{itemize}
\item {{criticisms}}
\end{itemize}
\subsubsection{Inference}
\texttt{ed.inferences} is mostly comprised of classes. They are
organized in a class hierarchy, where methods are shared via parent
classes and \texttt{Inference} is the top-most base class.
\begin{itemize}
\item @{ed.inferences.Inference}
\item @{ed.inferences.VariationalInference}
\begin{itemize}
\item @{ed.inferences.KLqp}
\begin{itemize}
\item @{ed.inferences.ReparameterizationKLqp}
\item @{ed.inferences.ReparameterizationKLKLqp}
\item @{ed.inferences.ReparameterizationEntropyKLqp}
\item @{ed.inferences.ScoreKLqp}
\item @{ed.inferences.ScoreKLKLqp}
\item @{ed.inferences.ScoreEntropyKLqp}
\end{itemize}
\item @{ed.inferences.KLpq}
\item @{ed.inferences.GANInference}
\begin{itemize}
\item @{ed.inferences.BiGANInference}
\item @{ed.inferences.ImplicitKLqp}
\item @{ed.inferences.WGANInference}
\end{itemize}
\item @{ed.inferences.MAP}
\begin{itemize}
\item @{ed.inferences.Laplace}
\end{itemize}
\end{itemize}
\item @{ed.inferences.MonteCarlo}
\begin{itemize}
\item @{ed.inferences.Gibbs}
\item @{ed.inferences.MetropolisHastings}
\item @{ed.inferences.HMC}
\item @{ed.inferences.SGLD}
\item @{ed.inferences.SGHMC}
\end{itemize}
\item @{ed.inferences.complete_conditional}
\end{itemize}
\subsubsection{Models}
\texttt{ed.models} is comprised of random variables.
The list of available random variables depends on the TensorFlow
version installed. For TensorFlow {{tensorflow_version}}, the
following are available:
\begin{itemize}
\item @{ed.models.RandomVariable}
\item {{models}}
\end{itemize}
\subsubsection{Utilities}
\texttt{ed.util} is comprised of functions for miscellaneous usage.
\begin{itemize}
\item {{util}}
\item @{ed.VERSION}
\item @{ed.__version__}
\end{itemize}
|
import torch
from torch import optim
import os
from copy import deepcopy
import torch.nn.functional as F
from utils import TrainingArgs
import logging
from nn import Net
from torch import nn
from vat import VATLoss
import numpy as np
logger = logging.getLogger()
logger.setLevel(logging.CRITICAL)
os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
seed_value = 123
config = TrainingArgs()
class MAML(nn.Module):
"""
MAML meta learner
"""
def __init__(self, args):
super(MAML, self).__init__()
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.update_lr = args.update_lr
self.meta_lr = args.meta_lr
self.update_step = args.update_step
self.update_step_test = args.update_step_test
self.bert_model = args.bert_model.to(self.device)
self.alpha1 = args.alpha1
self.alpha2 = args.alpha2
self.alpha3 = args.alpha3
self.xi = args.xi
self.eps = args.eps
self.net = Net(768, args.neurons).to(self.device)
self.meta_optim = optim.Adam(self.net.parameters(), lr=self.meta_lr)
def forward(self, x_spt, y_spt, x_qry, y_qry, vat_flag1=False, vat_flag2=False, vat_flag3=False, qry_num=5):
task_num = 1
querysz = qry_num
losses_q = [0 for _ in range(self.update_step + 1)] # losses_q[i] is the loss on step i
corrects = [0 for _ in range(self.update_step + 1)]
input_ids, attention_mask, _ = (elt.to(self.device) for elt in x_spt)
with torch.no_grad():
x = self.bert_model(input_ids=input_ids, attention_mask=attention_mask)[1]
q_input_ids, q_attention_mask, _ = (elt.to(self.device) for elt in x_qry)
q_input_ids, q_attention_mask = q_input_ids[:qry_num], q_attention_mask[:qry_num]
x_q = self.bert_model(input_ids=q_input_ids, attention_mask=q_attention_mask)[1]
vat_input_ids, vat_attention_mask = q_input_ids[:], q_attention_mask[:]
x_vat = self.bert_model(input_ids=vat_input_ids, attention_mask=vat_attention_mask)[1]
y_qry, y_vat = y_qry[:qry_num], y_qry[:]
y_spt = y_spt.to(self.device)
y_qry = y_qry.to(self.device)
y_vat = y_vat.to(self.device)
for i in range(task_num):
if vat_flag1:
vat_loss1 = VATLoss(xi=10.0, eps=1.0, ip=1)
lds1 = vat_loss1(self.net, x)
# 1. run the i-th task and compute loss for k=0
logits = self.net(x, bn_training=True)
loss = F.cross_entropy(logits, y_spt)
if vat_flag1:
loss += lds1 * self.alpha1
grad = torch.autograd.grad(loss, self.net.parameters(), allow_unused=True)
fast_weights = list(map(lambda p: (p[1] - self.update_lr * p[0]) if p[0] is not None else p[1],
zip(grad, self.net.parameters())))
# this is the loss and accuracy before first update
with torch.no_grad():
# [setsz, nway]
logits_q = self.net(x_q, bn_training=True)
loss_q = F.cross_entropy(logits_q, y_qry)
losses_q[0] += loss_q
pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)
correct = torch.eq(pred_q, y_qry).sum().item()
corrects[0] = corrects[0] + correct
for j, p in enumerate(self.net.parameters()):
p.data = fast_weights[j]
# this is the loss and accuracy after the first update
with torch.no_grad():
# [setsz, nway]
logits_q = self.net(x_q, bn_training=True)
loss_q = F.cross_entropy(logits_q, y_qry)
losses_q[1] += loss_q
# [setsz]
pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)
correct = torch.eq(pred_q, y_qry).sum().item()
corrects[1] = corrects[1] + correct
for k in range(1, self.update_step):
if vat_flag2:
vat_loss2 = VATLoss(xi=10.0, eps=1.0, ip=1)
lds2 = vat_loss2(self.net, x)
# 1. run the i-th task and compute loss for k=1~K-1
logits = self.net(x, bn_training=True)
loss = F.cross_entropy(logits, y_spt)
if vat_flag2:
loss += lds2 * self.alpha2
# 2. compute grad on theta_pi
grad = torch.autograd.grad(loss, fast_weights, allow_unused=True)
# 3. theta_pi = theta_pi - train_lr * grad
fast_weights = list(map(lambda p: (p[1] - self.update_lr * p[0]) if p[0] is not None else p[1],
zip(grad, fast_weights)))
for j, p in enumerate(self.net.parameters()):
p.data = fast_weights[j]
# VAT LOSS 3
if vat_flag3:
vat_loss3 = VATLoss(xi=self.xi, eps=self.eps, ip=1)
lds3 = vat_loss3(self.net, x_vat)
logits_q = self.net(x_q, bn_training=True)
# loss_q will be overwritten and just keep the loss_q on last update step.
loss_q = F.cross_entropy(logits_q, y_qry)
if vat_flag3:
loss_q += lds3 * self.alpha3
losses_q[k + 1] += loss_q
with torch.no_grad():
pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)
correct = torch.eq(pred_q, y_qry).sum().item() # convert to numpy
corrects[k + 1] = corrects[k + 1] + correct
# end of all tasks
# sum over all losses on query set across all tasks
loss_q = losses_q[-1] / task_num
# optimize theta parameters
self.meta_optim.zero_grad()
loss_q.backward()
self.meta_optim.step()
accs = np.array(corrects) / (querysz * task_num)
return accs
def finetuning(self, x_spt, y_spt, x_qry, y_qry, vat_flag2=False, vat_flag3=False):
"""
:param x_spt: [setsz, c_, h, w]
:param y_spt: [setsz]
:param x_qry: [querysz, c_, h, w]
:param y_qry: [querysz]
:return:
"""
querysz = len(y_qry)
corrects = [0 for _ in range(self.update_step_test + 1)]
net = deepcopy(self.net)
with torch.no_grad():
input_ids, attention_mask, _ = (elt.squeeze(0).to(self.device) for elt in x_spt)
x = self.bert_model(input_ids=input_ids, attention_mask=attention_mask)[1]
q_input_ids, q_attention_mask, _ = (elt.squeeze(0).to(self.device) for elt in x_qry)
x_q = self.bert_model(input_ids=q_input_ids, attention_mask=q_attention_mask)[1]
y_spt = y_spt.squeeze(0).to(self.device)
y_qry = y_qry.squeeze(0).to(self.device)
# 1. run the i-th task and compute loss for k=0
logits = net(x)
loss = F.cross_entropy(logits, y_spt)
grad = torch.autograd.grad(loss, net.parameters(), allow_unused=True)
fast_weights = list(
map(lambda p: (p[1] - self.update_lr * p[0]) if p[0] is not None else p[1], zip(grad, net.parameters())))
with torch.no_grad():
# [setsz, nway]
logits_q = net(x_q, bn_training=True)
# [setsz]
pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)
# scalar
correct = torch.eq(pred_q, y_qry).sum().item()
corrects[0] = corrects[0] + correct
for i, p in enumerate(net.parameters()):
p.data = fast_weights[i]
with torch.no_grad():
# [setsz, nway]
logits_q = net(x_q, bn_training=True)
# [setsz]
pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)
# scalar
correct = torch.eq(pred_q, y_qry).sum().item()
corrects[1] = corrects[1] + correct
for k in range(1, self.update_step_test):
vat_loss2 = VATLoss(xi=self.xi, eps=self.eps, ip=1)
lds2 = vat_loss2(net, x)
vat_loss3 = VATLoss(xi=self.xi, eps=self.eps, ip=1)
lds3 = vat_loss3(net, x_q)
# 1. run the i-th task and compute loss for k=1~K-1
logits = net(x, bn_training=True)
loss = F.cross_entropy(logits, y_spt)
if vat_flag3:
loss += lds3 * self.alpha3
if vat_flag2:
loss += lds2 * self.alpha2
# 2. compute grad on theta_pi
grad = torch.autograd.grad(loss, fast_weights, allow_unused=True)
# 3. theta_pi = theta_pi - train_lr * grad
fast_weights = list(
map(lambda p: (p[1] - self.update_lr * p[0]) if p[0] is not None else p[1], zip(grad, fast_weights)))
for i, p in enumerate(net.parameters()):
p.data = fast_weights[i]
logits_q = net(x_q, bn_training=True)
with torch.no_grad():
pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)
correct = torch.eq(pred_q, y_qry).sum().item() # convert to numpy
corrects[k + 1] = corrects[k + 1] + correct
del net
accs = np.array(corrects) / querysz
return accs, lds3
|
Kody has 18 children :
|
\graphicspath{{Pics/}}
\newpage\section{Circles and Radical Axises}
\prob{}{}{E}{In $\triangle ABC$, $H$ is the orthocenter, and $AD, BE$ are arbitrary cevians. Let $\omega_1, \omega_2$ denote the circles with diameters $AD, BE$ resp. $HD, HE$ meet $\omega_1, \omega_2$ again at $F,G$. $DE$ meet $\omega_1, \omega_2$ again at $P_1,P_2$. $FG$ meet $\omega_1, \omega_2$ again at $Q_1,Q_2$. $P_1H, P_2H$ meet $\omega_1, \omega_2$ at $R_1,R_2$ and $Q_1H, Q_2H$ meet $\omega_1, \omega_2$ at $S_1, S_2$. $P_1Q_1\cap P_2Q_2\equiv X$ and $R_1S_1\cap R_2S_2\equiv Y$. Prove that $X,Y,H$ are collinear.}
\solu{Too much info...}
\lem{Pseudo Miquel's Theorem}{In a $\triangle ABC$ let $E,F$ be points on $AC,AB$ and $D$ be a point on $\odot (ABC)$. Let $X=\odot (BFD)\cap \odot (CED)$ then $E,F,X$ are collinear.}
\fig{.5}{PseudoMiquel}{Notice the collinearity}
\prob{https://artofproblemsolving.com/community/c74453h1225408_some_geometric_problems}{buratinogigle's proposed problems for Arab Saudi team 2015}{E}{Let $ABC$ be a triangle and $(K)$ is a circle that touches segments $CA, AB$ at $E, F$, reps. $M, N$ lie on $(K)$ such that $BM, CN$ are tangent to $(K)$. $G, H$ are symmetric of $A$ through $E, F$. The circle passes through $G$ and touches to $(K)$ at $N$ that cuts $CA$ again at $S$. The circle passes through $H$ and touches $(K)$ at $M$ that cuts $AB$ again at $T$. Prove that the line passes through $K$ and perpendicular to $ST$ always passes through a fixed point when $(K)$ changes.}
\fig{.7}{SATST2015proposed_by_bura/derakynay1134-3}{}
\prob{https://artofproblemsolving.com/community/c6h17322p118681}{ISL 2002 G8}{M}{Let two circles $S_{1}$ and $S_{2}$ meet at the points $A$ and $B$. A line through $A$ meets $S_{1}$ again at $C$ and $S_{2}$ again at $D$. Let $M$, $N$, $K$ be three points on the line segments $CD$, $BC$, $BD$ respectively, with $MN$ parallel to $BD$ and $MK$ parallel to $BC$. Let $E$ and $F$ be points on those arcs $BC$ of $S_{1}$ and $BD$ of $S_{2}$ respectively that do not contain $A$. Given that $EN$ is perpendicular to $BC$ and $FK$ is perpendicular to $BD$ prove that $\angle EMF=90^{\circ}$.}
\solu{When one single property can produce a lot others, and we need to prove this property, assume the property to be true and work backwards.}
\prob{https://artofproblemsolving.com/community/c6h79788p456609}{APMO 1999 P3}{E}{Let $\Gamma_1$ and $\Gamma_2$ be two circles intersecting at $P$ and $Q$. The common tangent, closer to $P$, of $\Gamma_1$ and $\Gamma_2$ touches $\Gamma_1$ at $A$ and $\Gamma_2$ at $B$. The tangent of $\Gamma_1$ at $P$ meets $\Gamma_2$ at $C$, which is different from $P$, and the extension of $AP$ meets $BC$ at $R$. Prove that the circumcircle of triangle $PQR$ is tangent to $BP$ and $BR$.}
\prob{https://artofproblemsolving.com/community/c6h1751587p11419585}{USA TST 2019 P1}{E}{Let $ABC$ be a triangle and let $M$ and $N$ denote the midpoints of $\overline{AB}$ and $\overline{AC}$, respectively. Let $X$ be a point such that $\overline{AX}$ is tangent to the circumcircle of triangle $ABC$. Denote by $\omega_B$ the circle through $M$ and $B$ tangent to $\overline{MX}$, and by $\omega_C$ the circle through $N$ and $C$ tangent to $\overline{NX}$. Show that $\omega_B$ and $\omega_C$ intersect on line $BC$.}\label{problem:usatst2019p1}
\solu{[Spiral Similarity]
Let $ \omega_C \cap BC = P $. If we extend $ NP $ to meet $ AB $ at $ R $, we get $ XANR $ cyclic. Similarly, if $ \odot XAM\cap AC = Q $, then we have to prove $ QM\cap NR = P $.\\
Suppose $ QM\cap NR = P' $. Then by spiral similarity, $ X $ takes $ Q\to M $ and $ N\to R $. It also takes $ Q\to N $ and $ M\to R $. So $ XMP'R $ is cyclic. We now show that $ XMPR $ is also cyclic, which will prove $ P=P' $.\\
Let $ T = \odot ABC \cap \odot XAN $. By spiral similarity, $ T $ takes $ R\to B $ and $ N\to C $. It also takes $ R\to N $ and $ B\to C $, which means $ RBPT $ is cyclic. \\
\begin{minipage}{.45\linewidth}
By spiral similarity, we have, $ \triangle TXA \sim \triangle TNC,\ \triangle TXN \sim \triangle TAC,\ \triangle TBA \sim \triangle TPN $
Which implies,
\begin{align*}
\frac{XN}{TN} = \frac{AC}{TC},\ & \frac{XA}{TA} = \frac{NC}{TC}\\[.5em]
\implies \frac{XN}{XA} &= 2\frac{TN}{TA}
\end{align*}
And so,
\begin{align*}
\frac{AB}{TA}=\frac{NP}{TN}\quad \implies\frac{2AM}{NP} &= \frac{TA}{TN} = \frac{XA}{XN}2\\[.5em]
\implies \frac{AM}{NP} &= \frac{XA}{XN}
\end{align*}
\end{minipage}\hfill%
\begin{minipage}{.55\linewidth}
\figdf{}{USATST2019P1_new}{}
\end{minipage}
\vspace{1.5em}
Which means $ \triangle XAM \sim \triangle XNP $ since $ \angle XAM = \angle XNP $, which concludes the proof.
}
\solu{[Clever Observation]
Reflect $ A $ over $ X $ to $ A' $. Draw the circle with center $ X $ with radius $ XA $. Call it $ \omega $. Let $ P=\omega\cap\odot ABC $. Let $ Q=A'B\cap \omega $.
\begin{minipage}{.45\linewidth}
We will show that $ M, P, B, Q $ are cyclic, and $ XM $ is tangent to the circle.\\
First, we have $ AQ\perp A'B $. So $ MB=MQ $. Now,
\begin{align*}
\measuredangle MPQ &= \measuredangle APQ - \measuredangle APM\\
&=\measuredangle AA'Q - \measuredangle ANM \\
&= \measuredangle AXM - \measuredangle XAM\\
&=\measuredangle AMX \\
&= \measuredangle MBQ
\end{align*}
So $ M, Q, P, B $ is cyclic. Also since $ MQ=MB $, and $ XM\parallel BQ $, $ XM $ is tangent to $ \odot MPBQ $, and $ \odot MPBQ = \omega_B $.
\end{minipage}\hfill %
\begin{minipage}{.5\linewidth}
\figdf{}{USATST2019P1_1}{}
\end{minipage}
\vspace{1em}
Similarly $ \omega_C $ passes through $ P $, and by Miquel's theorem, their intersection lies on $ BC $.
}
\prob{http://artofproblemsolving.com/community/c6h1751587p11419916}{USA TST 2019 P1 parallel problem}{E}{Pick a point $X$ such that $AX$ is parallel to $BC$. Let $M,N$ be the midpoints of $AB,AC$. Let $w_b$ be the circle passing through $M$ and $B$ tangent to $(AXB)$ and define $w_c$ similarly. Show that $w_b, w_c$ intersect on $(AMN)$.}
\solu{Doing a $ \sqrt{\frac{bc}{2}} $ inversion in \autoref{problem:usatst2019p1} one ends up with this parallel problem.}
\prob{https://artofproblemsolving.com/community/c6h374251p2066133}{Sharygin 2010 P3}{E}{Points $A', B', C'$ lie on sides $BC, CA, AB$ of triangle $ABC.$ for a point $X$ one has $\angle AXB =\angle A'C'B' + \angle ACB$ and $\angle BXC = \angle B'A'C' +\angle BAC.$ Prove that the quadrilateral $XA'BC'$ is cyclic.}
\fig{.8}{sharygin_2010_3}{}
\prob{https://artofproblemsolving.com/community/c6h1671293p10632360}{IMO 2018 P6}{M}{A convex quadrilateral $ABCD$ satisfies $AB\cdot CD = BC\cdot DA$. Point $X$ lies inside $ABCD$ so that \[\angle{XAB} = \angle{XCD}\quad\,\,\text{and}\quad\,\,\angle{XBC} = \angle{XDA}.\]Prove that $\angle{BXA} + \angle{DXC} = 180^\circ$.}
\proof{Let $ P = AB\cap CD,\ Q = AD\cap BC $\\
From the first condition, we get that $ \dfrac{AB}{BC} = \dfrac{AD}{DC} $, implying that the angle bisectors of $ \angle DAB, \angle DCB $ meet on $ BD $.\\
And from the second condition, we have $ X = \odot QBD \cap \odot PAC $\\
\figdf{1}{imo2018p6}{IMO 2018 P6, Simple Angle-Chase proof.}
Let us define the point $ R $ such that $ AR, CR $ are isogonal to $ AC $ wrt to $ \angle DAB, \angle DCB $ respectively. In $ \triangle RAC $, we have, the bisectors of $ \angle RAC, \angle RCA $ meet on the line $ BRD $, meaning that $ RB $ bisects $ \angle ARC $.\\
Let $ \odot ARM \cap \odot DRC = Y $. We have,
\begin{align*}
\measuredangle AYC &= \measuredangle AYR + \measuredangle RYC\\
&= \measuredangle ABR + \measuredangle RDP\\
&= \measuredangle BPD\\
\implies \square PAYC &\text{ is cyclic.}
\end{align*}
And,
\begin{align*}
\measuredangle BYD &= \measuredangle BYR + \measuredangle RYD\\
&= \measuredangle BAR + \measuredangle RCD\\
&= \measuredangle CAD + \measuredangle BCA\\
&= \measuredangle CQD\\
\implies \square QBYD &\text{ is cyclic.}
\end{align*}
So, $ Y \equiv X $. So,
\[\measuredangle BYA + \measuredangle DYC = \measuredangle BRA + \measuredangle DRC = \measuredangle BRA + \measuredangle ARD = 180^\circ \]
}
\prob{}{Sharygin 2010}{E}{In $\triangle ABC$, let $ AL_a, AM_a $ be the external and internal bisectors of $ \angle A $ with $ L_a, M_a $ lying on $ BC $. Let $ \omega_a $ be the reflection of the circumcircle of $ \triangle AL_aM_a $wrt the midpoint of $ BC $. Let $ \omega_a $ be defined similarly. Prove that $ \omega_a, \omega_b $ are tangent to each other iff $ \triangle ABC $ is a right-angled triangle.} |
Require Import VST.veric.rmaps.
Require Import VST.veric.compcert_rmaps.
Require Import VST.progs.ghosts.
Require Import VST.progs.conclib.
Require Export VST.progs.invariants.
Require Export VST.progs.fupd.
Require Export atomics.general_atomics.
Require Import VST.floyd.library.
Require Import VST.floyd.sublist.
Set Bullet Behavior "Strict Subproofs".
(* Warning: it is UNSOUND to use both this file and acq_rel_atomics.v in the same proof! There is
not yet an operational model that can validate the use of both SC and RA atomics. *)
Section SC_atomics.
Context {CS : compspecs}.
Definition AL_type := ProdType (ProdType (ProdType (ProdType (ProdType (ProdType (ConstType val) Mpred)
(ArrowType (ConstType iname) (ConstType Prop))) (ArrowType (ConstType iname) (ConstType Prop)))
(ArrowType (ConstType share) (ArrowType (ConstType Z) Mpred))) (ArrowType (ConstType Z) Mpred))
(ConstType invG).
(* SEP (|={Eo,Ei}=> EX sh : share, EX v : Z, !!(readable_share sh /\ repable_signed v) &&
data_at sh tint (vint v) p * (data_at sh tint (vint v) p -* |={Ei,Eo}=> Q v)) *)
(* SEP (|={Eo,Ei}=> EX sh : share, EX v : Z, !!(readable_share sh /\ repable_signed v) &&
data_at sh tint (vint v) p * (data_at sh tint (vint v') p -* |={Ei,Eo}=> Q)) *)
Program Definition load_SC_spec := TYPE AL_type
WITH p : val, P : mpred, Eo : Ensemble iname, Ei : Ensemble iname,
P' : share -> Z -> mpred, Q : Z -> mpred, inv_names : invG
PRE [ 1%positive OF tptr tint ]
PROP (Included Ei Eo)
LOCAL (temp 1%positive p)
SEP (P -* |={Eo,Ei}=> EX sh : share, EX v : Z, !!(readable_share sh /\ repable_signed v) &&
data_at sh tint (vint v) p * P' sh v;
ALL sh : _, ALL v : _, (!!(readable_share sh /\ repable_signed v) &&
data_at sh tint (vint v) p * P' sh v) -* |={Ei,Eo}=> Q v;
P)
POST [ tint ]
EX v : Z,
PROP (repable_signed v)
LOCAL (temp ret_temp (vint v))
SEP (Q v).
Next Obligation.
Proof.
repeat intro.
destruct x as ((((((?, ?), ?), ?), ?), ?), ?); simpl.
unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; f_equal;
f_equal; rewrite !sepcon_emp, ?approx_sepcon, ?approx_idem.
f_equal.
- setoid_rewrite fview_shift_nonexpansive; rewrite approx_idem; do 3 apply f_equal.
rewrite !approx_exp; apply f_equal; extensionality sh.
rewrite !approx_exp; apply f_equal; extensionality v.
rewrite !approx_sepcon, approx_idem; auto.
- f_equal.
rewrite !(approx_allp _ _ _ Share.bot); apply f_equal; extensionality sh.
rewrite !(approx_allp _ _ _ 0); apply f_equal; extensionality v.
setoid_rewrite fview_shift_nonexpansive; rewrite approx_idem; apply f_equal; f_equal.
rewrite !approx_sepcon, approx_idem; auto.
Qed.
Next Obligation.
Proof.
repeat intro.
destruct x as ((((((?, ?), ?), ?), ?), ?), ?); simpl.
rewrite !approx_exp; apply f_equal; extensionality v.
unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; do 2 apply f_equal;
rewrite !sepcon_emp, ?approx_sepcon, ?approx_idem; auto.
Qed.
Definition AS_type := ProdType (ProdType (ProdType (ProdType (ProdType (ProdType (ConstType (val * Z)) Mpred)
(ArrowType (ConstType iname) (ConstType Prop))) (ArrowType (ConstType iname) (ConstType Prop)))
(ArrowType (ConstType share) Mpred)) Mpred)
(ConstType invG).
Program Definition store_SC_spec := TYPE AS_type
WITH p : val, v : Z, P : mpred, Eo : Ensemble iname, Ei : Ensemble iname,
P' : share -> mpred, Q : mpred, inv_names : invG
PRE [ 1%positive OF tptr tint, 2%positive OF tint ]
PROP (repable_signed v)
LOCAL (temp 1%positive p; temp 2%positive (vint v))
SEP (P -* |={Eo,Ei}=> EX sh : share, !!(writable_share sh) && data_at_ sh tint p * P' sh;
ALL sh : _, (!!(writable_share sh) && data_at sh tint (vint v) p * P' sh) -* |={Ei,Eo}=> Q; P)
POST [ tvoid ]
PROP ()
LOCAL ()
SEP (Q).
Next Obligation.
Proof.
repeat intro.
destruct x as (((((((?, ?), ?), ?), ?), ?), ?), ?); simpl.
unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; f_equal;
f_equal; rewrite !sepcon_emp, ?approx_sepcon, ?approx_idem.
f_equal.
- setoid_rewrite fview_shift_nonexpansive; rewrite approx_idem; do 3 apply f_equal.
rewrite !approx_exp; apply f_equal; extensionality sh.
rewrite !approx_sepcon, approx_idem; auto.
- f_equal.
rewrite !(approx_allp _ _ _ Share.bot); apply f_equal; extensionality sh.
setoid_rewrite fview_shift_nonexpansive; rewrite approx_idem; apply f_equal; f_equal.
rewrite !approx_sepcon, approx_idem; auto.
Qed.
Next Obligation.
Proof.
repeat intro.
destruct x as (((((((?, ?), ?), ?), ?), ?), ?), ?); simpl.
unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; do 2 apply f_equal;
rewrite !sepcon_emp, ?approx_sepcon, ?approx_idem; auto.
Qed.
Definition ACAS_type := ProdType (ProdType (ProdType (ProdType (ProdType (ProdType (ConstType (val * Z * Z)) Mpred)
(ArrowType (ConstType iname) (ConstType Prop))) (ArrowType (ConstType iname) (ConstType Prop)))
(ArrowType (ConstType share) (ArrowType (ConstType Z) Mpred))) (ArrowType (ConstType Z) Mpred))
(ConstType invG).
(* |={Eo,Ei}=> EX sh : share, EX v0 : Z, !!(writable_share sh /\ repable_signed v0) &&
data_at sh tint (vint v0) p *
(data_at sh tint (vint (if eq_dec v0 c then v else v0)) p -* |={Ei,Eo}=> Q v0) *)
Program Definition CAS_SC_spec := TYPE ACAS_type
WITH p : val, c : Z, v : Z, P : mpred, Eo : Ensemble iname, Ei : Ensemble iname,
P' : share -> Z -> mpred, Q : Z -> mpred, inv_names : invG
PRE [ 1%positive OF tptr tint, 2%positive OF tint, 3%positive OF tint ]
PROP (repable_signed c; repable_signed v)
LOCAL (temp 1%positive p; temp 2%positive (vint c); temp 3%positive (vint v))
SEP (P -* |={Eo,Ei}=> EX sh : share, EX v0 : Z, !!(writable_share sh /\ repable_signed v0) &&
data_at sh tint (vint v0) p * P' sh v0;
ALL sh : _, ALL v0 : _, (!!(writable_share sh /\ repable_signed v0) &&
data_at sh tint (vint (if eq_dec v0 c then v else v0)) p * P' sh v0) -* |={Ei,Eo}=> Q v0; P)
POST [ tint ]
EX v' : Z,
PROP (repable_signed v')
LOCAL (temp ret_temp (vint (if eq_dec v' c then 1 else 0)))
SEP (Q v').
Next Obligation.
Proof.
repeat intro.
destruct x as ((((((((?, ?), ?), ?), ?), ?), ?), ?), ?); simpl.
unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; f_equal;
f_equal; rewrite !sepcon_emp, ?approx_sepcon, ?approx_idem.
f_equal.
- setoid_rewrite fview_shift_nonexpansive; rewrite approx_idem; do 3 apply f_equal.
rewrite !approx_exp; apply f_equal; extensionality sh.
rewrite !approx_exp; apply f_equal; extensionality v0.
rewrite !approx_sepcon, approx_idem; auto.
- f_equal.
rewrite !(approx_allp _ _ _ Share.bot); apply f_equal; extensionality sh.
rewrite !(approx_allp _ _ _ 0); apply f_equal; extensionality v0.
setoid_rewrite fview_shift_nonexpansive; rewrite approx_idem; apply f_equal; f_equal.
rewrite !approx_sepcon, approx_idem; auto.
Qed.
Next Obligation.
Proof.
repeat intro.
destruct x as ((((((((?, ?), ?), ?), ?), ?), ?), ?), ?); simpl.
rewrite !approx_exp; apply f_equal; extensionality vr.
unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; do 2 apply f_equal;
rewrite !sepcon_emp, ?approx_sepcon, ?approx_idem; auto.
Qed.
Definition AEX_type := ProdType (ProdType (ProdType (ProdType (ProdType (ProdType (ConstType (val * Z)) Mpred)
(ArrowType (ConstType iname) (ConstType Prop))) (ArrowType (ConstType iname) (ConstType Prop)))
(ArrowType (ConstType share) (ArrowType (ConstType Z) Mpred))) (ArrowType (ConstType Z) Mpred))
(ConstType invG).
Program Definition AEX_SC_spec := TYPE AEX_type
WITH p : val, v : Z, P : mpred, Eo : Ensemble iname, Ei : Ensemble iname,
P' : share -> Z -> mpred, Q : Z -> mpred, inv_names : invG
PRE [ 1%positive OF tptr tint, 2%positive OF tint ]
PROP (repable_signed v)
LOCAL (temp 1%positive p; temp 2%positive (vint v))
SEP (P -* |={Eo,Ei}=> EX sh : share, EX v0 : Z, !!(writable_share sh /\ repable_signed v0) &&
data_at sh tint (vint v0) p * P' sh v0;
ALL sh : _, ALL v0 : _, (!!(writable_share sh /\ repable_signed v0) &&
data_at sh tint (vint v) p * P' sh v0) -* |={Ei,Eo}=> Q v0; P)
POST [ tint ]
EX v' : Z,
PROP (repable_signed v')
LOCAL (temp ret_temp (vint v'))
SEP (Q v').
Next Obligation.
Proof.
repeat intro.
destruct x as (((((((?, ?), ?), ?), ?), ?), ?), ?); simpl.
unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; f_equal;
f_equal; rewrite !sepcon_emp, ?approx_sepcon, ?approx_idem.
f_equal.
- setoid_rewrite fview_shift_nonexpansive; rewrite approx_idem; do 3 apply f_equal.
rewrite !approx_exp; apply f_equal; extensionality sh.
rewrite !approx_exp; apply f_equal; extensionality v0.
rewrite !approx_sepcon, approx_idem; auto.
- f_equal.
rewrite !(approx_allp _ _ _ Share.bot); apply f_equal; extensionality sh.
rewrite !(approx_allp _ _ _ 0); apply f_equal; extensionality v0.
setoid_rewrite fview_shift_nonexpansive; rewrite approx_idem; apply f_equal; f_equal.
rewrite !approx_sepcon, approx_idem; auto.
Qed.
Next Obligation.
Proof.
repeat intro.
destruct x as (((((((?, ?), ?), ?), ?), ?), ?), ?); simpl.
rewrite !approx_exp; apply f_equal; extensionality vr.
unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; do 2 apply f_equal;
rewrite !sepcon_emp, ?approx_sepcon, ?approx_idem; auto.
Qed.
End SC_atomics.
Notation store_SC_witness p v P Eo Ei Q invG := (p, v%Z, P, Eo, Ei,
fun sh => !!(writable_share sh) && data_at sh tint (vint v) p -* Q, Q, invG).
Notation AEX_SC_witness p v P Eo Ei Q invG := (p, v%Z, P, Eo, Ei,
fun sh v0 => !!(writable_share sh /\ repable_signed v0) && data_at sh tint (vint v) p -* Q v0, Q, invG).
Notation load_SC_witness p P Eo Ei Q invG := (p, P, Eo, Ei,
fun sh v => !!(readable_share sh /\ repable_signed v) && data_at sh tint (vint v) p -* Q v, Q, invG).
Notation CAS_SC_witness p c v P Eo Ei Q invG := (p, c, v%Z, P, Eo, Ei,
fun sh v0 => !!(writable_share sh /\ repable_signed v0) &&
data_at sh tint (vint (if eq_dec v0 c then v else v0)) p -* Q v0, Q, invG).
|
// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef RPC_DIRECTORY_READ_MANAGER_HPP_
#define RPC_DIRECTORY_READ_MANAGER_HPP_
#include <map>
#include "errors.hpp"
#include <boost/shared_ptr.hpp>
#include "concurrency/auto_drainer.hpp"
#include "concurrency/fifo_enforcer.hpp"
#include "concurrency/one_per_thread.hpp"
#include "concurrency/watchable.hpp"
#include "concurrency/watchable_map.hpp"
#include "containers/scoped.hpp"
#include "rpc/connectivity/cluster.hpp"
#include "containers/incremental_lenses.hpp"
template<class metadata_t>
class directory_read_manager_t :
public home_thread_mixin_t,
public cluster_message_handler_t {
public:
directory_read_manager_t(connectivity_cluster_t *cm,
connectivity_cluster_t::message_tag_t tag) THROWS_NOTHING;
~directory_read_manager_t() THROWS_NOTHING;
watchable_map_t<peer_id_t, metadata_t> *get_root_map_view() {
return &map_variable;
}
/* This is deprecated. Use `get_root_map_view()` instead. */
clone_ptr_t<watchable_t<change_tracking_map_t<peer_id_t, metadata_t> > >
get_root_view() THROWS_NOTHING {
return variable.get_watchable();
}
private:
/* Note that connection and initialization are different things. Connection
means that we can send messages to the peer. Initialization means that we
have received initial metadata from the peer. Peers only show up in the
`watchable_t` once initialization is complete. */
/* This will be called by `connectivity_cluster_t`. It mustn't block. */
void on_message(
connectivity_cluster_t::connection_t *connection,
auto_drainer_t::lock_t connection_keepalive,
read_stream_t *stream)
THROWS_ONLY(fake_archive_exc_t);
/* `on_message()` will spawn `handle_connection()` in a new coroutine in response to
the initialization message, and `propagate_update()` in response to all messages
after that.
They assume ownership of `new_value`. Semantically, the argument here is `metadata_t
&&new_value` but we cannot easily pass that through to the coroutine call, which is
why we use `boost::shared_ptr` instead. */
void handle_connection(
connectivity_cluster_t::connection_t *connection,
auto_drainer_t::lock_t connection_keepalive,
const boost::shared_ptr<metadata_t> &new_value,
fifo_enforcer_state_t metadata_fifo_state,
auto_drainer_t::lock_t per_thread_keepalive)
THROWS_NOTHING;
void propagate_update(
connectivity_cluster_t::connection_t *connection,
auto_drainer_t::lock_t connection_keepalive,
const boost::shared_ptr<metadata_t> &new_value,
fifo_enforcer_write_token_t metadata_fifo_token,
auto_drainer_t::lock_t per_thread_keepalive)
THROWS_NOTHING;
watchable_variable_t<change_tracking_map_t<peer_id_t, metadata_t> > variable;
watchable_map_var_t<peer_id_t, metadata_t> map_variable;
class connection_info_t {
public:
fifo_enforcer_sink_t *fifo_sink;
/* Destruction order is important here; the `auto_drainer_t` must be destroyed
before the `fifo_sink` pointer goes out of scope. */
auto_drainer_t drainer;
};
std::map<connectivity_cluster_t::connection_t *, connection_info_t *> connection_map;
/* It's possible that messages can be reordered so that a `propagate_update()`
reaches the home thread before the corresponding `handle_connection`. If this
happens, the `propagate_update()` will put an entry in `waiting_for_initialization`
and wait for `handle_connection()` to signal it. */
std::multimap<connectivity_cluster_t::connection_t *, cond_t *>
waiting_for_initialization;
/* This protects `variable`, `fifo_sinks`, and `waiting_for_initialization` */
mutex_assertion_t mutex_assertion;
/* Instances of `propagate_initialization()` and `propagate_update()` hold
a lock on one of these drainers. */
one_per_thread_t<auto_drainer_t> per_thread_drainers;
};
#endif /* RPC_DIRECTORY_READ_MANAGER_HPP_ */
|
[STATEMENT]
lemma [autoref_rel_intf]: "REL_INTF frgv_impl_rel_ext i_g_ext"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. REL_INTF frgv_impl_rel_ext i_g_ext
[PROOF STEP]
by (rule REL_INTFI) |
\documentclass[../main.tex]{subfiles}
\begin{document}
\subsection{Depth-first Search}
The following search algorithm is how we will determine the connected components of a disconnected graph. We do this by selecting an arbitrary vertex of the graph as the "root". And then exploring along the branches from the vertex as far as possible until we need to backtrack, at which point we choose a new undiscovered arbitrary root and repeat. Labeling each vertex discovered along that exploration as discovered. The aim is to discover all the vertices of the graph.
\begin{algorithm}[H]
\caption{DFS\cite{wiki}}\label{dfs}
Let $G$ be a graph with vertex set $V = \{1,...,n\}$
\begin{algorithmic}[1]
\Procedure{DFS}{$G,V$}
\State label $v$ as discovered
\ForAll{edges from $v$ to $w$ \textbf{in} $G.$adjacentEdges$(V)$}
\If{(vertex w is not labelled as discovered)}
\State recursively call DFS$(G,w)$
\EndIf
\EndFor
\EndProcedure
\end{algorithmic}
\end{algorithm}
\noindent This algorithm will allow you to find the connected components of a disconnected graph. Then using the following algorithm we can check if our forest at each step of our algorithm is acyclic. We do this by counting the number of edges that each component has since we know a tree can have at most $n-1$ edges by \textit{lemma 3.7}. This procedure is invoked in \textit{algorithm 3}.
\begin{algorithm}[H]
\caption{Acyclic Check}\label{acyclic}
Let $G$ be a graph with the set of connected components $C$ as found by DFS(G,v) where v is an arbitrary vertex in G.
\begin{algorithmic}[1]
\Procedure{ACYCLIC}{$G,C$}
\ForAll{$i$ \textbf{in} $C$}
\If{$i.$edgeCount() $> n-1$}
\Return False
\EndIf
\EndFor
\Return True
\EndProcedure
\end{algorithmic}
\end{algorithm}
\end{document} |
############################################################
# Generic conformal 3 metric for BSSN in spherical symmetry
# See: BSSN_Spher.mw or BSSN_Spher.mpl
############################################################
Ndim_ := 3:
x1_ := x:
x2_ := theta:
x3_ := phi:
complex_ := {}:
g11_ := (A(t,x)):
g12_ := 0:
g13_ := 0:
g22_ := x^2*(B(t,x)):
g23_ := 0:
g33_ := x^2*(B(t,x))*(sin(theta))^2:
|
module Sixel.Dither
import Data.Buffer
import System.FFI
import Sixel.Library
import Sixel.Symbols
import Sixel.Allocator
public export
PrimDither : Type
PrimDither = GCAnyPtr
export
data Dither : (0 n : Nat) -> Type where
PointDither : PrimDither -> Dither Z
RootDither : Dither n -> Dither (S n)
%foreign (sixelutils "sixel_utils_dither_ptr_new")
sixel_utils_dither_ptr_new : PrimIO (Ptr AnyPtr)
%foreign (sixelutils "sixel_utils_dither_ptr_deref")
sixel_utils_dither_ptr_deref : Ptr AnyPtr -> AnyPtr
%foreign (sixel "sixel_dither_new")
sixel_dither_new : Ptr AnyPtr -> (ncolors : Int) -> PrimAllocator -> PrimIO Int
%foreign (sixel "sixel_dither_get")
sixel_dither_get : (builtin : Int) -> PrimIO AnyPtr
%foreign (sixel "sixel_dither_ref")
sixel_dither_ref : PrimDither -> ()
%foreign (sixel "sixel_dither_unref")
sixel_dither_unref : PrimDither -> ()
%foreign (sixel "sixel_dither_unref")
sixel_dither_destroy : AnyPtr -> PrimIO ()
%foreign (sixel "sixel_dither_initialize")
sixel_dither_initialize :
PrimDither -> (pixels : Buffer) -> (w : Int) -> (h : Int) ->
(pixelFormat : Int) -> (large : Int) -> (rep : Int) -> (quality : Int) ->
PrimIO Int
%foreign (sixel "sixel_dither_set_diffusion_type")
sixel_dither_set_diffusion_type : PrimDither -> (diffuse : Int) -> ()
%foreign (sixel "sixel_dither_get_num_of_palette_colors")
sixel_dither_get_num_of_palette_colors : PrimDither -> Int
%foreign (sixel "sixel_dither_get_num_of_histogram_colors")
sixel_dither_get_num_of_histogram_colors : PrimDither -> Int
%foreign (sixel "sixel_dither_get_palette")
sixel_dither_get_palette : PrimDither -> String
%foreign (sixel "sixel_dither_set_palette")
sixel_dither_set_palette : PrimDither -> (palette : String) -> ()
%foreign (sixel "sixel_dither_set_complexion_score")
sixel_dither_set_complexion_score : PrimDither -> (score : Int) -> ()
%foreign (sixel "sixel_dither_set_body_only")
sixel_dither_set_body_only : PrimDither -> (setting : Int) -> ()
%foreign (sixel "sixel_dither_set_optimize_palette")
sixel_dither_set_optimize_palette : PrimDither -> (setting : Int) -> ()
%foreign (sixel "sixel_dither_set_pixelformat")
sixel_dither_set_pixelformat : PrimDither -> (pixelFormat : Int) -> ()
%foreign (sixel "sixel_dither_set_transparent")
sixel_dither_set_transparent : PrimDither -> (index : Int) -> ()
export
MkDither : {auto n : Nat} ->
{default (-1) ncolors : Int} ->
{default (getNullAllocator n) alloc : Allocator n} ->
IO (Either Status (Dither Z))
MkDither {ncolors} {alloc} = do
ppdither <- fromPrim sixel_utils_dither_ptr_new
status <- MkStatus <$> fromPrim (sixel_dither_new ppdither ncolors (toPrim alloc))
pdither <- onCollectAny (sixel_utils_dither_ptr_deref ppdither) (\pd => fromPrim $ sixel_dither_destroy pd)
pure $ if succeeded status then Right (PointDither pdither) else Left status
export
getDither : BuiltinDither -> IO (Maybe (Dither Z))
getDither builtin = do
ptr <- fromPrim $ sixel_dither_get $ binding builtin
pdither <- onCollectAny ptr (\pd => fromPrim $ sixel_dither_destroy pd)
pure $ if prim__isConcreteAny ptr
then Just (PointDither pdither)
else Nothing
export
ref : Dither n -> IO (Dither (S n))
ref (RootDither dither) = RootDither <$> ref dither
ref dither@(PointDither pdither) = let _ = sixel_dither_ref pdither in pure $ RootDither dither
export
unref : Dither (S n) -> IO (Dither n)
unref (RootDither dither@(RootDither _)) = RootDither <$> unref dither
unref (RootDither dither@(PointDither pdither)) = let _ = sixel_dither_unref pdither in pure dither
export
refs : Dither n -> Nat
refs (RootDither dither) = S (refs dither)
refs (PointDither _) = Z
export
toPrim : Dither n -> PrimDither
toPrim (RootDither dither) = toPrim dither
toPrim (PointDither pdither) = pdither
export
initialize :
Dither n -> (image : Buffer) -> (w : Int) -> (h : Int) ->
PixelFormat -> MethodForLargest -> MethodForRep -> QualityMode ->
IO (Either Status ())
initialize dither pixels w h pixelformat large rep quality = let pdither = toPrim dither in do
status <- MkStatus <$> fromPrim (sixel_dither_initialize
(toPrim dither) pixels w h (binding pixelformat) (binding large) (binding rep) (binding quality))
pure $ if succeeded status then Right () else Left status
export %inline
setDiffusionType : Dither n -> MethodForDiffuse -> IO ()
setDiffusionType dither methodForDiffuse =
pure $ sixel_dither_set_diffusion_type (toPrim dither) (binding methodForDiffuse)
export %inline
getNumOfPaletteColors : Dither n -> IO Int
getNumOfPaletteColors dither = pure $ sixel_dither_get_num_of_palette_colors (toPrim dither)
export %inline
getNumOfHistogramColors : Dither n -> IO Int
getNumOfHistogramColors dither = pure $ sixel_dither_get_num_of_histogram_colors (toPrim dither)
export %inline
setComplexionScore : Dither n -> (score : Int) -> IO ()
setComplexionScore dither score = pure $ sixel_dither_set_complexion_score (toPrim dither) score
export %inline
setBodyOnly : Dither n -> (setting : Bool) -> IO ()
setBodyOnly dither setting = pure $ sixel_dither_set_body_only (toPrim dither) (ifThenElse setting 1 0)
export %inline
setOptimizePalette : Dither n -> (setting : Bool) -> IO ()
setOptimizePalette dither setting = pure $ sixel_dither_set_optimize_palette (toPrim dither) (ifThenElse setting 1 0)
export %inline
setPixelFormat : Dither n -> PixelFormat -> IO ()
setPixelFormat dither pixelformat = pure $ sixel_dither_set_pixelformat (toPrim dither) (binding pixelformat)
export %inline
setTransparent : Dither n -> (index : Int) -> IO ()
setTransparent dither setting = pure $ sixel_dither_set_transparent (toPrim dither) setting
|
# Intro
Want to know how much we should charge now for the future payment. There are two uncertainties:
1. When will it be paid
2. Whether it will be paid
***
## Introduction to life insurance (self-learning)
### Summary
### Background
*Earliest life insurance policy*:
The **policyholder投保人** pay **premium保费** to the **insurer保险公司**. If the named life insured died during the year that the contract was in force, the insurer would pay a predetermined lump sum, the **sum insured**, to the policyholder or his or her estate.
*Life Table*:
It summurizes a **survival model** by specifying the proportion of lives that are expected to survive to each age.
>**e.g.**
>each new life had a probability of 40% of surviving to age 16
>and a probability of 1% of surviving to age 76
### Life insurance and annuity contracts
#### Intro
#### Traditional insurance contracts
##### Term insurance定期寿险
The insurer pays a lump sum benefit on the death of the policyholder, if death occurs before the end of a specified term.
- *Level term insurance定期定额寿险*: a level sum insured and regular, level premiums.
死亡保险金在整个保险期间保持不变。
>**e.g.**
>张三投保了一份保额为10万元的10年期定额定期保单,如果张三在未来10年内死亡,且保单仍然属于有效保单,则保险人将支付保单受益人10万元的死亡保险金。
- *Decreasing term insurance递减定期寿险*: a decreasing sum insured, (usually) as well as the premiums.
保险金缴纳金额随着年份的增大而减少,死亡保险金也不断减少。
话说递增的去哪里了
- *Renewable term insurance可续保定期寿险*: without further evidence of the policyholder’s health status, an option to renew the policy at the end of the original term.
一个term结束之后可以重新开始一个一样的。
- *Convertible term insurance可转换定期寿险*: without further evidence of the policyholder’s health status, an option to convert to a whole life or endowment insurance at the end of the original term.
一个term结束之后可以换成终身寿险。
##### Whole life insurance终身寿险
The insurer pays a lump sum benefit on the death of the policyholder whenever it occurs.
>**Note**
>Regularly, the premium is payable up to some maximum age, such as 80, in case that the older lives may be less able to pay the premiums.
##### Endowment insurance定期人寿保险
The insurer pays a lump sum benefit either on the death of the policyholder or at the end of a specified term, whichever occurs first.
#### Modern insurance contracts
- *Universal life insurance万能险*: investment + life insurance.
1. The policyholder determines the premium and the level of life insurance cover.
2. The premium is used to fund the life insurance and the rest is paid into an investment fund.
3. The premium is flexible but at least to cover the designated sum insured.
- *Unitized with-profit*:
1. Premiums are used to purchase units (shares) of an investment fund, called the **with-profit fund**.
2. The fund earns investment return, and the shares increase in value.
- *Equity-linked insurance权益连结保险,投资连结保险*: benefit linked to the performance of an investment fund.
- Form A: the premiums are invested in an open-ended investment company style account.
1. At maturity, the benefit is the accumulated value of the premiums.
2. If the policyholder dies before the contract matures, there is a minimum death benefit.
3. Other cases, there is a minimum maturity benefit.
- Form B: *Equity-Indexed Annuity* (EIA): with guaranteed minimum return on the premium.
1. At maturity, the policyholder receives a proportion of the return on a specified stock index, if that is greater than the guaranteed minimum return.
2. But at least the guaranteed amount.
#### Distribution methods
**Broker保险代理人**, are often remunerated through a commission system, and the commission is a percentage of the premium paid. Normally they get more on the first premium, referred as a **front-end load**.
卖多少,拿提成。
Another way is **direct marketing**, that insurers sell via telemarketing method (TV...) directly to the public.
电视卖保险。
Another insurance is **loan or credit insurance**. The insurer covers loan or credit card payments in the event of the borrower’s death, disability or unemployment.
我炸了你就替我还债。
#### Underwriting
**Premium rates**: how much we charge, depending on the size of the policy and **rating factors**, which are assessed by **proposal form投保单**, generally including age, gender, smoking habits, occupation, any dangerous hobbies, and personal and family health history.
Then to evaluate this infomation, is underwriting. Purpose:
- classify potential policyholders
- assess additional premium
Categories
- preferred lives
- normal lives
- rated lives: with one or more risk factors, additional premium may be charged.
- uninsurable lives: the insurer will not enter an insurance contract at any price.
#### Premiums
1. One single premium, at the outset of the contract
2. A regular series of premium if the policyholder survives, may go with a end date.
**An important feature**:
All premiums is paid at the *START* of each period.
>**e.g.**
>A policyholder contracts to pay annual premiums for a 10-year insurance contract. The premiums will be paid at the start of the contract, and then at the start of each subsequent year provided the policyholder is alive. Thus he should pay at $t=0,1, \dots 9$.
#### Life annuities终身年金
when an annuity depends on the survival of the recipient, **annuitant**.
- whole life annuity: annuity continues until the death of the annuitant.
- term life annuity: annuity is paid for some maximum period, provided that the annuitant survives.
- *Single Premium Deferred Annuity* (SPDA)
1. policyholder pays a single premium for an annuity in a specified future date.
买保险,之后过几年领钱。
2. the annuity is paid only if the policyholder survives to the payment dates, **life contingent**.
不过你得活着才能领。
3. policyholder dies before the annuity commences, then there's a death benefit.
没开始领就挂了,补偿一点。
4. policyholder dies soon after the annuity commences, then there's a guaranteed period, annuity will be paid to its estate.
领了一会就挂了,后代还能再领几年。
- *Single Premium Immediate Annuity* (SPIA)
Same with SPDA, except that, the annuity commences as soon as the contract is effected.
买保险之后就可以一直领钱。
- *Regular Premium DeferredAnnuity* (RPDA)
Same with SPDA, except that, the premium is paid through the deferred period.
分期买保险。
- *Joint life annuity*
No matter it is single premium or regular premium, immediate or deferred period, it is issued to *TWO* people. It ceases on the first death of the couple.
- *Last survivor annuity*
Same with Joint life annuity but ceases on the second death of the couple.
- *Reversionary annuity*
Still a couple, one as the annuitant, the other as the insured. On the death of the insured life, if the annuitant is still alive, the annuitant receives an annuity for the remainder of his or her life.
### Other insurance contracts
- *Income protection insurance*: Income protection policies replace at least some income during periods of sickness. They usually cease at retirement age.
- *Critical illness insurance*: Critical illness insurance pays a benefit on diagnosis of one of a number of severe conditions. The benefit is usually in the form of a lump sum.
- *Long-term care insurance*: to cover the costs of care in old age, when the insured life is unable to continue living independently. As an annuity benefit, the benefit is in the form of long-term care costs.
### Pension benefits退休金
usually sponsored by an employer
#### Defined benefit and defined contribution pensions
*Defined Benefit* (DB) *pensions*: a defined formula based on service and salary with an employer.
> **e.g.**
> An employee reaches retirement age with $n$ years of service, $i.e.$, the membership of the pension plan, with pensionable salary averaging $S$.
> Then the **final salary** plan offer an annual pension at retirement of $B = Sn\alpha$, where $\alpha$ is called the **accrual rate**, usually around $1\%-2\%$.
The contributions are invested and accumulated. But it must be enough to pay the pensions when they become due.
*Defined Contribution* (DC) *pensions*: more like a bank account. The employee and employer pay a predetermined contribution (usually a fixed percentage of salary) into a fund, and the fund earns interest. When the employee leaves or retires, the proceeds are available to provide income throughout retirement.
#### Defined benefit pension design
*Career average salary* plans: with benefit formula same with the final salary formula above, except that the average salary over the employee’s entire career is used in place of the final salary.
*Withdrawal benefit*: if employees leave their jobs before retirement, a pension based on the same formula as the age retirement benefit, but with the start date deferred until the employee reaches the normal retirement age.
*death-in-service benefit*: if employees die during the employment, a lump sum might be paid, often based on salary or service.
### Mutual and proprietary insurers
*Mutual insurance company*: one that has no shareholders. The insurer is owned by the with-profit policyholders. All profits are distributed to the with-profit policyholders through dividends or bonuses.
*proprietary insurance company*: with shareholders and usually with-profit policyholders. Participating policyholders are not owners, but have a specified right to some of the profits. Thus, the profits must be shared in some predetermined proportion, between the shareholders and the with-profit policyholders.
### Typical problems
---
# Survival Models
## Summary
## The future lifetime random variable
$Def$
*Future Life Time*: time elapsed from now to death
$Def$
*Life Insurance*: A policy that pays benefit upon death of the insured, initiated when bought.
$Def$
*Pure Endowment*: A policy that pays benefit at certain date if the insured is ALIVE on that date.
$\dagger$
现实中Pure Endowment不多
$Def$
*Endowment Insurance* (Endowment): A policy that pays benefit upon death of the insured or at the end of a specified term, whichever occurs first.
$Def$
*Life Annuities*: Anniuty whose payments are contingent on the annuitant being alive on payment date.
***
$Def$
For $x \geq 0$, life aged $x$ is denoted as $(x)$, individual who is insured. And $T_x$ is for that currently aged $x$ life, its *future life time **continuous** **random** variable*, with cumulative distribution function (cdf) $F_x(t)$ and probability density function (pdf) $f_x(t)$.
$\odot$
$T_x \geq 0$, and $T_x$ is a continuous variable.$\square$
$Def$
*Survival Function*: $S_x (t) = 1 - F_x (t)= \mathrm{Pr} [T_x > t]$
$\odot$
$\{T_x\}_{x \geq 0}$ is an infinite collection of $r.v.$.$\square$
$Assumption$
In order to finder the inner relationship between $\{T_x\}_{x \geq 0}$, we want they all are related to $T_0$, which is the future life time for a newborn. Thus:
$$\boxed{ \mathrm{Pr}[ T_x \leq t ] = \mathrm{Pr} [ T_0 \leq x + t \mid T_0 > x ]}$$
$\dagger$
Condition $T_0 > x$ is necessary! Or $T_x$ would not even exist.
$Conclusion$
From the fomula of conditional probability:
$$\mathrm{Pr}[A \mid B] = \frac{\mathrm{Pr}[A\cup B]} {\mathrm{Pr}[B]},$$
thus from this very basic assumption:
$$\mathrm{Pr}[T_x \leq t] = \frac{ \mathrm{Pr} [x < T_0 \leq x+t]} {\mathrm{Pr} [T_0 > x]} \Rightarrow F_x(t) = \frac {F_0 (x+t) - F_0 (t)} {1-F_0(x)} \Rightarrow 1 - S_x (t) = \frac {S_0(x) - S_0(x+t)} {S_0(x)} \\ \Rightarrow \boxed { S_x(t) = \frac {S_0(x+t)} {S_0(x)}}$$
$Conclusion$
**Factorization property**:
$$S_x(t+d) = \frac{S_0(x+t+d)} {S_0(x)} = \frac{S_0(x+t)} {S_0(x)} \cdot \frac{S_0(x+t+d)} {S_0(x+t)} = S_x(t) \cdot S_{x+t}(d)$$
$i.e.,$
$$\boxed { S_x(t+d) = S_x(t) \cdot S_{x+t}(d)}$$
$\dagger$
上面的性质就$S_x(t)$有,$F_x(t)$啥的都没有这种性质。
$Conclusion$
Any survival func must satisfy the following:
1. $S_x(0) = 1$, the probability that a life currently aged $x$ survives $0$ years is $1$.
2. $\lim_{t \to \infty} S_x(t) = 0$, all lives eventually die.
3. The survival function must be a *non-increasing* function of $t$.
$\dagger$
可以从Conclusion中得到证明。
$Assumption$
Other assumptions needed:
1. $S_x(t)$ is differentiable for all $t >0$.
2. Sometimes, $\displaystyle \lim_{t \to \infty} tS_x(t) = 0$
3. Sometimes, $\displaystyle \lim_{t \to \infty} t^2S_x(t) = 0$
$\odot$
1. Assumption1 and conclusion 3, we can see that $\frac{\mathrm{d} }{\mathrm{d} t} S_x(t) \leq 0$ for all $t >0$.
2. Assumption2 and 3 is used to make sure that mean and variance exist.$\square$
>**e.g.**:
>$$F_0(t) = \left\{\begin{matrix}
1-(1-\frac{t}{120})^{\frac{1}{6}} & 0 \leq t \leq 120\\
1 & t>120
\end{matrix}\right.$$
> **(a)** $(0)$ survives beyond age 20
>> (a) $S_0(20)$
> **(b)** $(20)$ dies before age 35
>> (b) $F_{20}(15)= 1-S_{20}(15) = \displaystyle 1-\frac{S_{0}(35)} {S_{0}(20)}$
> **(c)** $(30)$ survives beyond age 50
>> (c) $S_{30}(20)=\displaystyle \frac{S_{0}(50)}{S_{0}(30)}$
$\dagger$
Write the $S_x(t)$ *FIRST* then do the calculation
## Force of Mortality
$Conclusion$
$f_x(t) = \frac{\mathrm{d} }{\mathrm{d} t} F_x(t)$, specifically for a newborn:
$$\begin{align}
f_0(t) &= \lim_{\mathrm{d}t \to 0^+} \frac{F_0(t+\mathrm{d}t) - F_0(t)}{\mathrm{d}t}\\
&=\lim_{\mathrm{d}t \to 0^+} \frac{\mathrm{Pr}[t\leq T_0 \leq t+\mathrm{d}t]}{\mathrm{d}t}
\end{align}$$
$Def$
**Force of Mortality**:
$$\begin{align*}
\mu_{x} &= \lim_{\mathrm{d}t \to 0^{+}} \frac {\mathrm{Pr} [ T_0 \leq x + \mathrm{d}t \mid T_0 > x ]} {\mathrm{d}t} \\
&= \lim_{\mathrm{d}t \to 0^{+}} \frac {\mathrm{Pr} [ T_x \leq \mathrm{d}t ]} {\mathrm{d}t} \\
&= \lim_{\mathrm{d}t \to 0^{+}} \frac {F_{x} (\mathrm{d}t)} {\mathrm{d}t} \\
&= \lim_{\, \mathrm{d} x \to 0^{+}} \frac {1 - S_{x} ( \mathrm{d} x)} {\, \mathrm{d} x} \\
\end{align*}$$
Since $S_0 (x + \mathrm{d} x) = S_{0} (x) \cdot S_{x} ( \mathrm{d} x)$,
$$\begin{align*}
\mu_{x} &= \lim_{\, \mathrm{d} x \to 0^{+}} \frac {S_{0} (x) - S_0 (x + \mathrm{d} x)} {S_{0} (x) \cdot \, \mathrm{d} x} \\
&= \frac {-1} {S_{0} (x)} \cdot \frac{\mathrm{d} }{\, \mathrm{d} x} S_{0} (x) \\
&= \boxed{ - \frac {\frac{\mathrm{d} }{\, \mathrm{d} x} S_{0} (x)} {S_{0} (x)} = \frac {\frac{\mathrm{d} }{\, \mathrm{d} x} F_{0}(x)} {S_{0} (x)} = \frac {f_{0} (x)} {S_{0} (x)} }\\
&= \boxed{ - \frac{\mathrm{d} }{\, \mathrm{d} x} \log S_{0} (x) }
\end{align*}$$
$\dagger$
那里可以把分式提出极限号出来是因为我们是对$\, \mathrm{d} x$求的极限,不是$x$。
这里的求导也不是正常的求导,而是右导数就好了。
$Conclusion$
Now we fix $x$ at $x^{*}$ and see what's $\mu_{x^{*} + t}$
$$\begin{align*}
\mu_{x^{*} + t} &= \frac {-1} {S_{0} (x^{*} + t)} \cdot \frac{\mathrm{d} }{\mathrm{d} \left( x^{*} + t \right)} S_{0} (x^{*} + t) \\
&= \frac {-1} {S_{0} (x^{*} + t)} \cdot \frac{\mathrm{d} }{\mathrm{d} t} \left( S_{0} (x^{*}) \cdot S_{x^{*}} (t) \right) \\
&= - \frac{S_{0} (x^{*})} {S_{0} (x^{*} + t)} \cdot \frac{\mathrm{d} }{\mathrm{d} t} S_{x^{*}} (t) \\
&= \frac {-1} {S_{x^{*}} (t)} \cdot \frac{\mathrm{d} }{\mathrm{d} t} S_{x^{*}} (t) \\
&= \boxed{ - \frac {\frac{\mathrm{d} }{\mathrm{d} t} S_{x^{*}} (t)} {S_{x^{*}} (t)} = \frac {\frac{\mathrm{d} }{\mathrm{d} t} F_{x^{*}}(t)} {S_{x^{*}} (t)} = \frac {f_{x^{*}} (t)} {S_{x^{*}} (t)} } \\
&= \boxed{ - \frac{\mathrm{d} }{\mathrm{d} t} \log S_{x^{*}} (t) }
\end{align*}$$
$\dagger$
注意都对什么求的导。$\mu_{x}$那里都是导$x$,而这里的$\mu_{x^{*} + t}$都是导$t$.
$Conclusion$
Now we start from $\mu_{x}$ and see what can we get.
Since $\mu_{x} = - \frac{\mathrm{d} }{\mathrm{d} x} \log S_{0} (x)$,
$$\begin{align*}
\int _{0} ^{y} \mu_{x} \, \mathrm{d} x &= \int _{0} ^{y} - \frac{\mathrm{d} }{\mathrm{d} t} \log S_{0} (x) \,\mathrm{d} x \\
&= -\log S_{0} (x) \mid_{0}^{y} \\
&= -\log S_{0} (y) + \log S_{0} (0)
\end{align*}$$
Remember that $\forall x > 0, S_{x} (0) = 1$ and $\log(1) = 0$, so that:
$$\int _{0} ^{y} \mu_{x} \,\mathrm{d} x = -\log S_{0} (y) \Rightarrow \boxed {S_{0} (y) = e^{-\int_{0}^y \mu_{x} \, \mathrm{d} x}}$$
$\dagger$
For the fomula above, those two zeros may not be changed to others. See another conclusion below.
$Conclusion$
$$\begin{align*}
S_{x^{*}} (t) &= \frac{S_{0}(x^{*} + t)} {S_{0}(x^{*})} \\
&= \frac{e^{-\int_{0}^{x^{*} + t} \mu_{x} \, \mathrm{d} x}} {e^{-\int_{0}^{x^{*}} \mu_{x} \, \mathrm{d} x}} \\
&= e^{-\int_{x^{*}}^{x^{*} + t} \mu_{x} \, \mathrm{d} x}
\end{align*}$$
$i.e.,$
$$\boxed{ S_{x^{*}} (t) = \exp \left\{ -\int_{0}^{t} \mu_{x+x^{*}} \, \mathrm{d} x \right\}, or,S_{x} (t) = \exp \left\{ -\int_{0}^{t} \mu_{x+s} \, \mathrm{d} s \right\} }$$
>**e.g.**
> Suppose that $F_{0}(x) = 1-(1-x/120)^{1/6}$, for $0 \leq x \leq 120$. Derive an expression for $\mu_x$.
>
>$Answer$
>
>First we see that $S_{0}(x) = (1-x/120)^{1/6}$, then
>
>$$\frac{\mathrm{d} }{\, \mathrm{d} x}S_{0}\left( x \right )= \frac{1} {6} (1-x/120)^{-5/6}(-\frac{1}{120})$$
>
>and so
>$$\mu_x=\frac{-1} {S_{0}\left( x \right )} \frac{\mathrm{d} }{\, \mathrm{d} x}S_{0}\left( x \right ) = \frac{1} {720}(1-x/120)^{-1} = \frac{1} {720-6x}$$
### Gompertz’ law of mortality.
Let $\mu_x = Bc^{x}$, here $x > 0$, $B$ and $c$ are constants such that $0 < B < 1$ and $c > 1$. Then,
$$\begin{align*}
S_{x}\left( t \right) &= \exp \left\{ - \int_{x}^{x+t} \mu_r \; \mathrm{d}r \right\} \\
&= \exp \left\{ - \int_{x}^{x+t} Bc^{r} \; \mathrm{d}r \right\} \\
&= \exp \left\{ - \frac{B}{\log c} c^{r} \left| \right. _{x}^{x+t} \right\} \\
&= \boxed{\exp \left\{ - \frac{B}{\log c} c^{x}\left( c^{t} - 1 \right ) \right\}}
\end{align*}$$
>**e.g.**: Calculate the survival function and probability density function for $T_x$ using *Gompertz’ law of mortality*, with $B = 0.0003$ and $c = 1.07$, for $x = 20$, $x = 50$ and $x = 80$. Plot the results and comment on the features of the graphs.
>$Answer$
>For $x = 20$, the force of mortality is $\mu_{20 + t} = Bc^{20 + t}$, and the survival function is:
>
>$$S_{20} \left( t \right) = \exp \left\{ - \frac{B}{\log c} c^{20}\left( c^{t} - 1 \right ) \right\}$$
>Then the probability density function is:
>
>$$\mu_{20 + t} = \frac{f_{20} \left( t \right)} {S_{20} \left( t \right)} \Rightarrow f_{20} \left( t \right) = \mu_{20 + t} S_{20} \left( t \right) = Bc^{20 + t} \exp \left\{ - \frac{B}{\log c} c^{20}\left( c^{t} - 1 \right ) \right\}$$
>
>|$S_{x}(t)$|$f_{x}(t)$|
|:---------:|:--------:|
|||
## Actuarial notation
IAN: International Actuarial Notaion
### $_{t}p_{x}$
Survival Function for $T_{x}$, the Probability of $\left( x \right)$ survives $t$ years.
$$_{t}p_{x}=\mathrm{Pr} \left[ T_{x} > t \right] = S_{x}\left( t \right )$$
Further, we use $p_{x}$ with default $t=1$;
### $_{t}q_{x}$
$\mathrm{cdf}$ for $T_{x}$, the Probability of $\left( x \right)$ dies within $t$ years.
$$_{t}q_{x}=\mathrm{Pr} \left[ T_{x} \leq t \right] = F_{x}\left( t \right )$$
Further, we use $q_{x}$ with default $t=1$;
### ${_{u \mid t}}q_{x}$
A deferred mortality probability, that $\left( x \right)$ survives $u$ years and dies within $t$ years after that.
$$_{u \mid t}q_{x}=\mathrm{Pr} \left[ u < T_{x} \leq u + t \right] = S_{x}\left( u \right ) - S_{x}\left( u + t \right )$$
Further, we use ${_{u \mid}}q_{x}$ with default $t=1$, and we never use $_{u \mid t}p_{x}$;
$Conclusion$
1. $\boxed{_{t}p_{x} + _{t}q_{x} = 1}$
2. $\boxed{{_{u \mid t}}q_{x} = {_{u}}p_{x} - {_{u + t}}p_{x}}$
3. Factorization Formula:
$$\boxed{{_{t + u}}p_{x} = {_{t}}p_{x} \cdot {_{u}}p_{ x + t }}$$
4. Force of Mortality:
$$\boxed{\mu_{x} = - \frac{\frac{\mathrm{d}}{\, \mathrm{d} x} S_{0}\left( x \right )} {S_{0}\left( x \right )} = - \frac{1}{{_{x}}p_{0}} \cdot \frac{\mathrm{d}}{\, \mathrm{d} x} \left( {_{x}}p_{0} \right )}$$
$$\boxed{\mu_{x + t} = - \frac{\frac{\mathrm{d}}{\mathrm{d} t} S_{x}\left( t \right )} {S_{x}\left( t \right )} = - \frac{1}{{_{t}}p_{x}} \cdot \frac{\mathrm{d}}{\mathrm{d} t} \left( {_{t}}p_{x} \right )} \Rightarrow \boxed{\frac{\mathrm{d}}{\mathrm{d} t} \left( {_{t}}p_{x} \right ) = - {_{t}}p_{x} \cdot \mu_{x + t}}$$
5. $\mathrm{pdf}$
$$\mu_{x + t} = \frac{ \frac{\mathrm{d}}{\mathrm{d} t} \left( {_{t}}q_{x} \right)} {{_{t}}p_{x}} \Rightarrow \boxed{f_{x} \left( t \right) = {_{t}}p_{x} \cdot \mu_{x + t}}$$
6. Survival Function
$$\boxed{ {_{t}}p_{x} = \exp \left \{ - \int _{0} ^{t} \mu_{x+s} \, \mathrm{d}s \right \}}$$
7. $\mathrm{cdf}$
$$F_{x} \left( t \right) = \int _{0} ^{t} f_{x} \left( s \right) \, \mathrm{d}s \Rightarrow \boxed{ {_{t}}q_{x} = \int _{0} ^{t} {_{s}}p_{x} \mu_{ x + s } \, \mathrm{d}s}$$
An explanation on the formula above:
Consider time $s$, where $0 \leq s < t$. The probability that $\left( x \right)$ is alive at time $s$ is ${_{s}}p_{x}$, and the probability that $\left( x \right)$ dies between ages $x + s$ and $x + s + \mathrm{d}s$, having survived to age $x + s$, is (loosely) $\mu_{x + s} \, \mathrm{d}s$, provided that $\mathrm{d}s$ is very small. Thus ${_{s}}p_{x} \cdot \mu_{x + s} \, \mathrm{d}s$ can be interpreted as the probability that $\left( x \right)$ dies between ages $x + s$
and $x + s + \mathrm{d}s$. Now, we can sum over all the possible death intervals $s$ to $s + \mathrm{d}s$, which requires integrating because these are infinitesimal intervals, to obtain the probability of death before age $x + t$, $i.e.$, ${_{t}}q_{x} = F_{x} \left( t \right)$
An special case is when $x =1$, we have:
$${_{t}}q_{x} \!\mid_{t=1} = {_{1}q_{x}} = \boxed{ q_{x} = \int _{0} ^{1} {_{s}}p_{x} \mu_{ x + s } \, \mathrm{d}s}$$
When $q_{x}$ is small, it follows that $p_{x}$ is close to $1$, and hence ${_{s}}p_{x}$ is close to $1$ for $0 \leq s < 1$. Thus
$$\boxed{q_{x}\approx \int_{0}^{1} \mu _{x+s} \, \mathrm{d}s \approx \mu _{x+\frac{1}{2}}}$$
And another special case is that:
$$\boxed{p_{x} = \frac{S_{0} \left( x + 1 \right)} {S_{0} \left( x \right)}}$$
## Mean and standard deviation of $T_x$
$\overset{\circ}{e}_{x} = \mathbb{E}\left[ \,T_{x} \,\right]$, as the **complete expection of life**. Remember we still have $x \geq 0$.
$$
\begin{align*}
\overset{\circ}{e}_{x} &= \int_{-\infty} ^{\infty} t \cdot f_{x} \left( t \right) \, \mathrm{d}t \\
&= \int_{0} ^{\infty} t \cdot {_{t}p_{x}} \cdot \mu_{x + t} \, \mathrm{d}t \\
&= \int_{0} ^{\infty} t \cdot \left( -\frac{\mathrm{d}} {\mathrm{d}t} {_{t}q_{x}} \right) \, \mathrm{d}t \\
&= -\int_{0} ^{\infty} t \,{\mathrm{d} \left( {_{t}q_{x}} \right)} \\
&= -\left( t \cdot {_{t}p_{x}} \! \mid _{0} ^{\infty} - \int_{0} ^{\infty} {_{t}p_{x}} \, \mathrm{d}t \right)
\end{align*}
$$
And since we have assumed that $\lim_{t \to \infty}t \cdot {_{t}p_{x}} = 0$, so finally:
$$\boxed{ \overset{\circ}{e}_{x} = \int_{0} ^{\infty} {_{t}p_{x}} \, \mathrm{d}t \,}$$
Without the assumption before, $\overset{\circ}{e}_{x}$ won't exist. And with similar method and a stronger assumption, $\lim_{t \to \infty}t^2 \! \cdot \! {_{t}p_{x}} = 0$, we can find that:
$$
\begin{align*}
\mathbb{E}\left[ \,T_{x}^{2} \,\right] &= -\left( t^2 \! \cdot \! {_{t}p_{x}} \! \mid _{0} ^{\infty} - \int_{0} ^{\infty} {_{t}p_{x}} \, \mathrm{d}t^2 \right) \\
&= - \left( \lim_{t \to \infty} t^2 \! \cdot \! {_{t}p_{x}} - \int_{0} ^{\infty} 2t \, {_{t}p_{x}} \, \mathrm{d}t \right) \\
&= \boxed{ \int_{0} ^{\infty} 2t \, {_{t}p_{x}} \, \mathrm{d}t \,}
\end{align*}
$$
>**e.g.**
>
>$\displaystyle F_{0}\left( x \right) = 1 - \left( 1 - \frac{x} {120} \right)^{1/6}$
>
>First with survival function, which is $\displaystyle S_{0}\left( x \right) = 1 - F_{0}\left( x \right) = \left( 1 - \frac{x} {120} \right)^{1/6}$
>
>Then the $\displaystyle S_{x} \left( t \right) = {_{t}p_{x}} = \frac{S_{0}\left( x + t \right)} {S_{0}\left( x \right)} = \left( 1 - \frac{t} {120 - x} \right)^{1/6}$, for $t \in \left[ \, 0, 120-x \right)$.
>
>$\begin{align*}
\overset{\circ}{e}_{x} &= \int_{0} ^{120 - x} \left( 1 - \frac{t} {120 - x} \right)^{1/6} \, \mathrm{d}t \\
&= \left( 120 - x \right) \cdot \frac{6} {7} \left( 1 - \frac{t} {120 - x} \right)^{7/6}
\bigg|_{0}^{120 - x} = \frac{6} {7} \left( 120 - x \right)
\end{align*}$
>
>$\begin{align*}
\mathbb{E}\left[ \,T_{x}^{2} \,\right] &= 2 \int_{0} ^{\infty} t \, {_{t}p_{x}} \, \mathrm{d}t \\
&= 2 \int_{0} ^{120 - x} t \, \left( 1 - \frac{t} {120 - x} \right)^{1/6} \, \mathrm{d}t \\
\end{align*}$
***
>Then we are stuck here!!! One way it to let $\boxed{ u = 1 - \frac{t} {120 - x} \Rightarrow \mathrm{d}u = - \frac{1} {120 - x} \mathrm{d}t }$, and when $t$ goes from $0$ to $120 - x$, $u$ goes from $1$ to $0$. After this we can write:
>
>$\begin{align*}
\mathbb{E}\left[ \,T_{x}^{2} \,\right] &= 2 \int_{1} ^{0} \left( 1 - u \right) \cdot \left( 120 - x \right) \cdot u^{1/6} \cdot - \left( 120 - x \right) \, \mathrm{d}u \\
&= 2 \left( 120 - x \right)^2 \int_{0} ^{1} \left( 1 - u \right) \cdot u^{1/6} \, \mathrm{d}u = 2 \left( 120 - x \right)^2 \left( \frac{6} {7} - \frac{6} {13} \right)
\end{align*}$
## Curtate future lifetime
$Def$
**Curtate future lifetime**: the integer part of future lifetime, denoted as $K_{x} = \left \lfloor T_{x} \right \rfloor$
Then we have:
$$\begin{align*}
\mathrm{Pr} \left[ K_{x} = k \right] &= \mathrm{Pr} \left[ k \leq T_{x} < k+1 \right] \\
&= \boxed{ {_{k \mid 1}}q_{x} = {_{k \mid}}q_{x} } \\
&= {_k}p_{x} - {_{k + 1}}p_{x} \\
&= {_k}p_{x} - {_k}p_{x} \cdot {_1}p_{x + k} \\
&= {_k}p_{x} \left( 1 - p_{x + k} \right) \\
&= {_k}p_{x} \cdot q_{x + k}
\end{align*}$$
$i.e.$,
$$\boxed{\mathrm{Pr} \left[ K_{x} = k \right] = {_k}p_{x} \cdot q_{x + k} = {_k}p_{x} \cdot {_1}q_{x + k}}$$
And its expectation is $e_{x}$, without a halo on the top like $\overset{\circ}{e}_{x}$.
$$\begin{align*}
e_{x} &= \mathbb{E}\left[ \,K_{x} \,\right] \\
&= \sum _{k = 0} ^{\infty} k \cdot \mathrm{Pr} \left[ K_{x} = k \right] \\
&= \sum _{k = 0} ^{\infty} k \cdot \Big( {_k}p_{x} - {_{k + 1}}p_{x} \Big) \\
&= 0 + 1\left( {_1}p_{x} - {_{2}}p_{x} \right) + 2\left( {_2}p_{x} - {_3}p_{x} \right) + 3\left( {_3}p_{x} - {_4}p_{x} \right) + \cdots
\end{align*}$$
$i.e.$,
$$\boxed{ e_{x}= \mathbb{E}\left[ \,K_{x} \,\right] = \sum _{k = \mathbf{1}} ^{\infty} {_k}p_{x}}$$
Similarly we can acquire:
$$\boxed{ \mathbb{E}\left[ \,K_{x}^{2} \,\right] = \sum _{k = \mathbf{1}} ^{\infty} \left( 2k-1 \right) \cdot {_k}p_{x} = 2\left( \sum _{k = \mathbf{1}} ^{\infty} k \cdot {_k}p_{x} \right) - e_{x}}$$
$Compare$
$$\boxed{\overset{\circ}{e}_{x} = \mathbb{E}\left[ \, T_{x} \,\right]= \int_{\mathbf{0}}^{\infty} {_t}p_{x} \, \mathrm{d}t \,}, \boxed{ \mathbb{E}\left[ \, T_{x}^{2} \,\right] = \int_{\mathbf{0}}^{\infty} 2t \cdot {_t}p_{x} \, \mathrm{d}t \,}$$
Finally we will derive the relationship between $\overset{\circ}{e}_{x}$ and ${e}_{x}$
$$\begin{align*}
\overset{\circ}{e}_{x} &= \int_{0}^{\infty} {_t}p_{x} \, \mathrm{d}t \\
&= \sum _{j=0} ^{\infty} \int_{j}^{j+1} {_t}p_{x} \, \mathrm{d}t \\
&\approx \sum _{j=0} ^{\infty} \left( 1 \times {_{j+1}}p_{x} + \frac{1} {2} \times 1 \times \left( {_j}p_{x} - {_{j+1}}p_{x} \right) \right) \\
&= \sum _{j=0} ^{\infty} \left( \frac{1} {2} \left( {_j}p_{x} + {_{j+1}}p_{x} \right) \right) \\
&= \frac{1} {2} + \sum _{j=1} ^{\infty} {_j}p_{x}
\end{align*}$$
$i.e.$,
$$\boxed{\overset{\circ}{e}_{x} = \frac{1} {2} + e_{x}}$$
***
Another expectation, about $n\textrm{-year}$ annual term curtate expectation of life, denoted as $e_{{x:\overline {n|}}}$, which is the expected life year of $(x)$ given the
$Def$
$L_{x} = \min\left( K_{x},n \right)$
$$\begin{align*}
e_{x:\overline {n|}} &= \mathbb{E} \left[ \, \min\left( K_{x},n \right) \, \right] \\
&= \sum _{l=0} ^{n} l \cdot \mathrm{Pr} \left[ L_{x} = l \right] \\
&= \left( \sum _{l=0} ^{n - 1} l \cdot \Big( {_l}p_{x} - {_{l + 1}}p_{x} \Big) \right) + n \cdot {_n}p_{x} \\
&= \boxed{ \sum _{\mathbf{l=1}} ^{n} {_l}p_{x}}
\end{align*}$$
And similarly, $ \boxed{ \overset{\circ}{e}_{x:\overline {n|}} = \mathbb{E}\left[ \, \min\left( T_{x},n \right) \,\right]= \int_{\mathbf{0}}^{n} {_t}p_{x} \, \mathrm{d}t \,}$
# Life tables and selection
## Summary
General polulation, select a part of population, like at specific age, or with same level
Deterministic point of view
## Life Tables
Given a survivol model, with survival probability ${_{t}}p_{x}$, we can construct a **life table** for the model from some initial age $x_0$ to a maximum age $\omega$.
$Def$
$\{l_{x}\}_{x \, \in \,\left[ x_0, \omega \right)}$, a function as follows: Let $l_{x_{0}}$ be an *arbitrary positive* number, called the **radix**. Then, for $0 \leq t \leq \omega − x_0$, define:
$$l_{x_0 + t} = l_{x_0} \cdot {_{t}}p_{x}$$
Then easily we can see that, for fixed $x^*$, $x_0 \leq x^* \leq x^* + t \leq \omega$
$$\begin{align*}
l_{x^* + t} &= l_{x_0 + \left( x^* + t - x_0 \right)} \\
&= l_{x_0} \cdot {_{x^* + t - x_0}}p_{x_0} \\
&= l_{x_0} \cdot {_{x^* - x_0}}p_{x_0} \cdot {_{t}}p_{x^*} \\
&= l_{x^*} \cdot {_{t}}p_{x^*}
\end{align*}$$
$i.e.$,
$$\boxed{l_{x+t} = l_{x} \cdot {_{t}}p_{x} } \Rightarrow \boxed{{_{t}}p_{x} = \frac{l_{x+t}} {l_{x}}}$$
And actually we can interpret this relationship into another *binomial random variable*, $\mathfrak{L}_t$. That is suppose we have $l_x$ independent lives aged $x$, and each life has a probability ${_{t}}p_{x}$ of surviving to age $x + t$. Then the number of survivors to age $x + t$ is $\mathfrak{L}_t \sim \mathrm{B}\left( l_x, {_{t}}p_{x} \right )$. So that its expectation is:
$$\boxed{\mathbb{E}\left[ \, \mathfrak{L}_t \, \right] = l_x \cdot {_{t}}p_{x} = l_{x+t} }$$
$Conclusion$
$$\boxed{ {_{t}}p_{x} = \frac{l_{x+t}} {l_{x}}, {_{t}}q_{x} = \frac{l_{x} - l_{x+t}} {l_{x}} }$$
$$\begin{align*}
{_{u \mid t}}q_{x} &= {_{u}}p_{x} \cdot {_{t}}q_{x + u} \\
&= \frac{l_{x+u}} {l_{x}} \cdot \left( 1 - {_{t}}p_{x + u} \right) \\
&= \frac{l_{x+u} - l_{x+u+t}} {l_{x}} \\
&\text{or} \\
&= {_{u}}p_{x} - {_{u + t}}p_{x} \\
&= \frac{l_{x + u}} {l_{x}} - \frac{l_{x + u + t}} {l_{x}} \\
&= \frac{l_{x + u} - l_{x + u + t}} {l_{x}}
\end{align*} \\
\boxed{ {_{u \mid t}}q_{x} = \frac{l_{x + u} - l_{x + u + t}} {l_{x}} }
$$
Then we let $d_{x} = l_{x} - l_{x+1}$, death of life in the next year, and we can get that,
$$\begin{align*}
d_{x} &= l_{x} - l_{x+1} \\
&= l_{x} \cdot \left( 1- \frac{l_{x+1}} {l_{x}} \right) \\
&= \boxed{ l_{x} \cdot \left( 1- p_{x} \right) = l_{x} \cdot q_{x} = l_{x} \cdot {_{1}}q_{x} }
\end{align*} \\
\boxed{ l_{x} = \frac{d_{x}} {{_{1}}q_{x}}, q_{x} = \frac{d_{x}} {l_{x}} }$$
>**e.g.**: Given life table
>
>
| $x$| $l_x$ | $d_x$ |
|:--:|:--------:|:-----:|
| 30 | 10000.00 | 34.78 |
| 31 | 9965.22 | 38.10 |
| 32 | 9927.12 | 41.76 |
| 33 | 9885.35 | 45.81 |
| 34 | 9839.55 | 50.26 |
| 35 | 9789.29 | 55.17 |
| 36 | 9734.12 | 60.56 |
| 37 | 9673.56 | 66.49 |
| 38 | 9607.07 | 72.99 |
| 39 | 9534.08 | 80.11 |
>
>$l_{40} = l_{39} - d_{39} = 9453.97$
>
>${_10}p_{30} = \frac{l_{40}} {l_{30}} = 0.94540$
>
>$q_{35} = \frac{d_{35}} {l_{35}} = 0.00564$
>
>${_5}q_{30} = \frac{l_{30} - l_{35}} {l_{30}} = 0.02107$
>
>${_{5\mid}}q_{30} = {_{5\mid1}}q_{30} = \frac{l_{35} - l_{36}} {l_{30}} = \frac{d_{35}} {l_{30}} = 0.00552$
## Fractional age assumptions
Linear interpolation between ages, other skills ...
### Uniform distribution of deaths
$Assumption$
**UDD**, the uniform distribution of deaths, most common one.
1. For integer $x$, and for $0 \leq s < 1$, assume that ${_{s}}q_{x} = s \cdot q_{x} = s \cdot {_{1}}q_{x}$.
>**e.g.**
> ${_{1/4}}q_{25} = \frac{1} {4} \cdot q_{25} = \frac{1} {4} \cdot {_{1}}q_{25}$
2. From $K_x = \left \lfloor T_x \right \rfloor$, we define a new variable by $T_x = K_x + R_x$, and here $R_x$ is the fractional point of $T_x$. And we assume that: for integer $x$, $R_x \sim \mathrm{U} \left( 0, 1 \right)$ , and $R_x$ is independent of $K_x$.
$Claim$
**UDD1** $\Leftrightarrow$ **UDD2**
$Proof$
($\Rightarrow$) Suppose that for all integer $x \geq 0, x \in \left[ 0 , 1 \right)$, we have ${_{s}}q_{x} = s \cdot q_{x}$.
Then this means, for $0 \leq s < 1$:
$$\begin{align*}
\mathrm{Pr}\left[ R_x \leq s \right] &= \sum_{k = 0}^{\infty} \mathrm{Pr}\left[ R_x \leq s \mathrm{ AND } K_x = k \right] \\
&= \sum_{k = 0}^{\infty} \mathrm{Pr}\left[ k \leq T_x \leq k+s \right] \\
&= \sum_{k = 0}^{\infty} {_{k}}p_{x} \cdot {_{s}}q_{x+k} \\
&\stackrel{\textbf{UDD1}}= \sum_{k = 0}^{\infty} {_{k}}p_{x} \cdot s \cdot q_{x+k} \\
&= s \sum_{k = 0}^{\infty} {_{k}}p_{x} \cdot q_{x+k} \\
&= s \sum_{k = 0}^{\infty} \mathrm{Pr}\left[ K_x = k \right] \\
&= s \cdot 1 = s
\end{align*}$$
Thus it is uniformly distributed, and now the rest is to prove the independency. Note that
$$\begin{align*}
\mathrm{Pr}\left[ R_x \leq s \mathrm{ AND } K_x = k \right] &= \mathrm{Pr}\left[ k \leq T_x \leq k+s \right]\\
&= {_{k}}p_{x} \cdot {_s}q_{x+k} \\
&\stackrel{\textbf{UDD1}}= {_{k}}p_{x} \cdot s \cdot q_{x+k} \\
&= \mathrm{Pr}\left[ K_x = k \right] \cdot \mathrm{Pr}\left[ R_x \leq s \right]\\
\end{align*}$$
Half done, let's see the opposite direction.
($\Leftarrow$) Suppose $R_x \sim \mathrm{U} \left( 0, 1 \right)$, $R_x$ and $K_x$ are independent. Let $x$ be an integer and for $0 \leq s < 1$, we have
$$\begin{align*}
s \cdot q_{x+k} &= \mathrm{Pr}\left[ T_x \leq s \right]\\
&= \mathrm{Pr}\left[ K_x = 0 \; \textrm{and}\; R_x \leq s \right] \\
&\stackrel{\textbf{UDD2}}= \mathrm{Pr}\left[ K_x = 0 \right] \cdot \mathrm{Pr}\left[ R_x \leq s \right] \\
&= q_{x} \cdot \int_0^s 1 \, \mathrm{d} x = s \cdot q_{x}
\end{align*}$$
All done. We normally will use **UDD** as $\boxed{{_{s}}q_{x} = s \cdot q_{x} }$
***
$Conclusion$
$$\begin{align*}
{_{s}}q_{x} &= 1 - {_{s}}p_{x} \\
s \cdot q_{x} &= 1 - \frac{l_{x+s}} {l_x} = \frac{l_{x} - l_{x+s}} {l_x} \\
s \cdot \frac{d_x} {l_x} &= \frac{l_{x} - l_{x+s}} {l_x} \\
\end{align*}$$
$i.e.$,
$$\boxed{l_{x+s} = l_{x} - s \cdot d_{x}}$$
>**e.g.** Given $P_{40} = 0.999473$,
>
>$$\begin{align*}
{_{0.4}}q_{40.2} &= 1 - {_{0.4}}p_{40.2} \\
&= 1- \frac{l_{40.6}} {l_{40.2}} \\
&= 1- \frac{{_{0.6}}p_{40}} {{_{0.2}}p_{40}} \\
&= 1- \frac{1 - {_{0.6}}q_{40}} {1 - {_{0.2}}q_{40}} \\
&\stackrel{\textbf{UDD}}= 1- \frac{1 - {0.6} q_{40}} {1 - {0.2} q_{40}} \\
&= 1- \frac{1 - 0.6 (0.00527)} {1 - 0.2(0.00527)} \\
& \approx 2.108 \times 10^{-4}
\end{align*}$$
>
>Another example is to calculate ${_{1.7}}q_{33.5}$
>
>$$\begin{align*}
{_{1.7}}q_{33.5} &= 1 - {_{1.7}}p_{33.5} \\
&= 1 - \frac{l_{35.2}} {l_{33.5}} \\
&= 1 - \frac{l_{35} - 0.2 d_{35}} {l_{33} - 0.5 d_{33}}
\end{align*}$$
>
>Using the life table, we can find the final answer, another way is like when we calculate ${_{1.7}}q_{33}$
>
>${_{1.7}}q_{33} = 1 - {_{1.7}}p_{33} = 1 - p_{33} \cdot {_{0.7}}p_{34} = 1 - \displaystyle \frac{l_{34}} {l_{33}} (1 - 0.7 \times q_{34})$
but what if there's no such table, we can then do like above.
>
>
$Conclusion$
We can also differentiate $\boxed{{_{s}}q_{x} = s \cdot q_{x} }$ with $s$ on both side, easily we can get:
$$\frac{ \mathrm{d}} {\mathrm{d}s} {_s}q_x = q_x,\; 0 \leq s \leq 1$$
Left-hand side is the derivative of culmulative density function, so we finally can see that:
$$\boxed{ q_{x} = f_{x} \left( s \right) = {_s}p_x \cdot \mu_{x+s} }, 0 \leq s < 1$$
$\odot$
And this also demonstrate that density function is a constant, $i.e.$, the variable $R_x$ is uniformly distributed.$\square$
>**e.g.**
>
>So we have $\mu_{x + t} = \displaystyle \frac{q_x} {{_{t}}p_{x}}$, then $\displaystyle \lim_{t \to 1^-} \mu_{40 + t} = \frac{q_{40}} {p_{40}}$ and $\displaystyle \lim_{t \to 0^+} \mu_{41 + t} = q_{41}$
### Constant Force of Mortality (CFM)
Assume that the force of mortality $\mu_x$ is constant between integer ages. Thus for integer $x \geq 0$ and $0 \leq s < 1$, we have $\mu_{x+s} = \mu_x ^*$, a **CONSTANT**.Then how to get that?
From the fact that ${_{t}}p_{x} = \displaystyle \exp{ \left\{ -\int_{0} ^{t} \mu_{x+s} \mathrm{d}s \right\}}$, we can see that
$$\begin{align}
p_x &= \exp{ \left\{ -\int_{0} ^{1} \mu_{x+s} \mathrm{d}s \right\}} \\
&\stackrel{\mathbf{CFM}}{=} \exp{ \left\{ -\int_{0} ^{1} \mu_{x}^* \mathrm{d}s \right\}} \\
&= e^{-\mu_{x}^*}
\end{align} \Rightarrow \mu_{x}^* = - \log p_x $$
Then we have
$$\begin{align}
{_{s}}p_{x} &= \exp{ \left\{ -\int_{0} ^{s} \mu_{x}^* \mathrm{d}s \right\}} \\
&= e^{-\mu_{x}^* \cdot s} = (p_x)^s
\end{align}$$
And similarly for $\boxed{t, s > 0, t + s \leq 1}$, we get a general formula
$$\boxed{{_{s}}p_{x+t} = (p_{x})^s}$$
>**e.g.**: Given $p_{40} = 0.999473$, calculate ${_{0.4}}q_{40.2}$ under the CFM.
>
>${_{0.4}}q_{40.2} = 1- {_{0.4}}p_{40.2} = 1 - (p_{40})^{0.2} = 2.108 \times 10^{-4}$
>
>**e.g.**: Given $q_{70} = 0.010413, q_{71} = 0.011670$, calculate ${_{0.7}}q_{70.6}$ under the CFM.
>
> Here since the time range include an integer value so that we have to calculate separately, and DO NOT forget the conditional probability in the later part because you've already survived the former part!
>
>And we have to do that because of the blockhead CFM **only apply to those inside one integer age interval***!*!*!*!
>
>$$\begin{align*}
{_{0.7}}q_{70.6} =& \text{die before the next integer} \\ &+ \text{survive the next} \cdot \text{die between the next and the last one} \\ &+ \text{survive until the last integer} \cdot \text{die after the last one} \\
=& {_{0.4}}q_{70.6} + (1 - {_{0.7}}q_{70.6}) {_{0.3}}q_{71} \\
=& ( 1 - (p_{70})^{0.4}) + (1 - {_{0.7}}q_{70.6})( 1 - (p_{71})^{0.3})
\end{align*}$$
Why the difference using two different assumption is always very small?
$\dagger$
Because when $\mu^*t$ is small and $0 < t < 1$, we have ${_{t}}q_x \stackrel{\mathbf{CFM}}= 1 - e^{-\mu^*t} \approx \mu^*t \stackrel{\mathbf{CFM}}= t(-\log p_{x}) \approx t(1 - p_{x}) = t \cdot q_{x}$, which means **CFM** and **UDD** are close under such conditions.
## National life tables
## Survival models for life insurance policyholders
## Life insurance underwriting
## Select and ultimate survival models
This section defines **select survival model**, when
1. Future survival probabilities for an individual in the group depend on the individual’s current age and on the age at which the individual joined the group.
2. There is a positive number (generally an integer), which we denote by $d$, such that if an individual joined the group more than $d$ years ago, future survival probabilities depend only on current age.The initial selection effect is assumed to have worn off after $d$ years.
An individual who enters the group at age $x$, is said to be selected at age $x$; the period $d$ after which the age at selection has no effect on future survival probabilities is called the **select period** for the model; the *mortality* that applies to lives after the select period is complete is called the **ultimate mortality**.
But actually you only need to multiply a probability belongs to the group of people with same features.
>**e.g.**: Consider men who need to undergo surgery and there is a probability of only $50\%$ that they will survive for **a year** (meaning *select period* is $1$) following surgery.
>
> 1. the probability that a man aged $60$ who is just about to have surgery (meaning selected at $x = 60$) will be alive at age $70$, would be
$$0.5 \times \frac{l_{70}} {l_{\mathbf{61}}}$$
2. the probability that a man aged $60$ who had surgery at age $59$ (meaning selected at $x = 59$) will be alive at age $70$ would be
$$\frac{l_{70}} {l_{\mathbf{60}}}$$
## Notation and formulae for select survival models
$Def$
$S_{[ x ]+ s} ( t ) = \mathrm{Pr}[\text{a life aged } (x + s) \text{ selected at age } x \text{ survives to age } (x + s + t)]$
$Def$
${_{t}}q_{[ x ]+ s} = \mathrm{Pr}[\text{ a life aged } (x + s) \text{ selected at age } x \text{ dies before age } (x + s + t)]$
$Def$
$\mu_{[ x ]+ s}$ is the force of mortality at age $x + s$ for an individual who was select at age $x$
And with these we can acquire the following
$${_{t}}p_{[ x ]+ s} = 1 - {_{t}}q_{[ x ]+ s} \equiv S_{[ x ]+ s} ( t ) \\
+ \\
\mu_{[ x ]+ s} = \lim_{h \to 0^+} \left( \frac{ 1 - S_{[ x ]+ s} ( h )} {h} \right) \\
\Downarrow \\
\boxed{ {_{t}}p_{[ x ]+ s} = \exp \left\{ - \int _{0} ^{t} \mu_{[ x ]+ s + u} \, \mathrm{d}u \right\}}
$$
## Select life tables
Construct select life table for a select survival model for ages at selection from $x_0 \geq 0$. Let $d$ denote the select period, assumed to be an integer number of years.
Let $l_{x_0 + d}$ be an arbitrary positive number. For $y \geq x_0 + d$ since the life was select at least $d$ years ago, the probability of future survival depends only on the current age, ${x_0 + d}$. Then we define:
$$l_y = {_{(y - x_0 -d)}}p_{x_0 + d}l_{x_0 + d}$$
Then for $y > x \geq x_0 + d$, we can define like
$$l_y = {_{(y-x)}}p_{x} l_x$$
The reason is
$$\begin{align*}
l_y &= ({_{(y - x_0 - d)}}p_{x_0 + d}) l_{x_0 + d} \\
&= ({_{(y - x)}}p_{[x_0] + x - x_0})({_{(x - x_0 -d)}}p_{[x_0] + d}) l_{x_0 + d} \\
&= ({_{(y - x)}}p_{x})({_{(x - x_0 -d)}}p_{x_0 + d}) l_{x_0 + d} \\
&= {_{(y - x)}}p_{x}l_x
\end{align*}$$
And at last we define for $x \geq x_0, 0 \leq t \leq d$:
$$l_{[x] + t} = \frac{l_{x + d}} {{_{(d - t)}}p_{[x] + t}}$$
$\dagger$
Similar to **CFM**, you need a break at the end of *selected period*, no matter the time reaches that or not. If exceed, then tear that apart, if not exceed, then use the inverse version with a division from the end of the period.
>**e.g.** for $y \geq x + d > x + s > x + t \geq x \geq x_0$, show that
>
>$$\begin{align*}
{_{(y − x − t)}}p_{[ x ]+ t} &= {_{(d − t)}}p_{[ x ]+ t} \cdot {_{(y - x - d)}}p_{\mathbf{[x]}+ d} \\
&= {_{(d − t)}}p_{[ x ]+ t} \cdot {_{(y - x - d)}}p_{\mathbf{x} + d} \\
&= \frac{l_{x+d}} {l_{[ x ]+ t}} \cdot \frac{l_y} {l_{x+d}} = \frac{l_y} {l_{[ x ]+ t}}
\end{align*}$$
>
>And we also have a no-exceed one (using the inverse formula)
>
>$$\begin{align*}
{_{(s − t)}}p_{[ x ]+ t} &= \frac{{_{(d − t)}}p_{[ x ]+ t}} {{_{(d - s)}}p_{[ x ]+ s}} \\
&= \frac{l_{x + d}} {l_{[ x ]+ t}} \cdot \frac{l_{[ x ]+ s}} {l_{x + d}} = \frac{l_{[ x ]+ s}} {l_{[ x ]+ t}}
\end{align*}$$
>
>more complex one, ${_{2 | 6}}q_{[ 30 ]+ 2 }$
>
>$$\begin{align*}
{_{2 | 6}}q_{[ 30 ]+ 2 } &= \mathrm{Pr}[\text{a life aged }32 \text{, who was select at age }30 \text{, will survive to age 34}] \times \mathrm{Pr}[\text{a life aged }34 \text{, who was select at age }30 \text{, will die before age 40}] \\
&= {_{2}}q_{[ 30 ]+ 2 } \cdot {_{6}}q_{[ 30 ]+ 4 } \\
&= \frac{l_{[ 30 ]+ 4 }} {l_{[ 30 ]+ 2 }} \left( 1 - \frac{l_{[ 30 ]+ 10}} {l_{[ 30 ]+ 4 }} \right) = \frac{l_{[ 30 ]+ 4 } - l_{40}} {l_{[ 30 ]+ 2 }}
\end{align*}$$
>
>$\dagger$
>Note that $l_{[ 30 ]+ 10} \equiv l_{40}$ since $10$ years is longer than the select period for this survival model.
***
>**e.g.** Example 3.12 Selected period of $2$ years
>
>| Age<br/> $x$ | Duration $0$ <br/> $q_{[x]}$ | Duration $1$ <br/> $q_{[x-1]+1}$ | Duration $2+$ <br/> $q_{x}$ |
|:------------:|:----------------------------:|:--------------------------------:|:---------------------------:|
| $60$ | $0.003469$ | $0.004539$ | $0.004760$ |
| $61$ | $0.003856$ | $0.005059$ | $0.005351$ |
| $62$ | $0.004291$ | $0.005644$ | $0.006021$ |
| $63$ | $0.004779$ | $0.006304$ | $0.006781$ |
| $\dots$ | $\dots$ | $\dots$ | $\dots$ |
| $70$ | $0.010519$ | $0.014068$ | $0.015786$ |
| $71$ | $0.011858$ | $0.015868$ | $0.017832$ |
| $72$ | $0.013401$ | $0.017931$ | $0.020145$ |
| $73$ | $0.015184$ | $0.020302$ | $0.022759$ |
| $74$ | $0.017253$ | $0.023034$ | $0.025712$ |
| $75$ | $0.019664$ | $0.026196$ | $0.029048$ |
>
>$(\text{a})$ ${_{4}}p_{[70]}$
>
>$$\begin{align}
{_{4}}p_{[70]} &= p_{[70]} \cdot p_{[70]+1} \cdot p_{[70]+2} \cdot p_{[70]+3} \\
&= p_{[70]} \cdot p_{[70]+1} \cdot p_{72} \cdot p_{73} \\
&= (1-q_{[70]})(1-q_{[70]+1})(1-q_{72})(1-q_{73})
\end{align}$$
>
>$(\text{b})$ ${_{3}}q_{[60]+1}$
>
>$$\begin{align}
{_{3}}q_{[60]+1} &= 1 - {_{3}}p_{[60]+1} \\
&= 1 - {_{1}}p_{[60]+1} \cdot {_{2}}p_{62} \\
&= 1 - (1 - {_{1}}q_{[60]+1}) (1 - {_{1}}q_{62}) (1 - {_{1}}q_{63})
\end{align}$$
***
***
>**e.g.** Exercise 3.2, given the life table and find some values.
>
>| Age, $x$ | $52$ | $53$ | $54$ | $55$ | $56$ | $57$ | $58$ | $59$ | $60$ |
|:--------:|:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|
| $l_x$ | $89948$ | $89089$ | $88176$ | $87208$ | $86181$ | $85093$ | $83940$ | $82719$ | $81429$ |
>
>$(\text{a})$ ${_{0.2}}q_{52.4}$ under **UDD**.
>
>$$\begin{align}
{_{0.2}}q_{52.4} &= 1 - {_{0.2}}p_{52.4} \\
&= 1 - \frac{l_{52.6}} {l_{52.4}} \\
&= 1 - \frac{l_{52} - 0.6 \cdot d_{52}} {l_{52} - 0.4 \cdot d_{52}} \\
&= 1 - \frac{89948 - 0.6 \left( 89948 - 89089 \right)} {89948 - 0.4 \left( 89948 - 89089 \right)} \;= 0.0019173165603473263
\end{align}$$
>
>$(\text{b})$ ${_{0.2}}q_{52.4}$ under **CFM**.
>
>$$\begin{align}
{_{0.2}}q_{52.4} &= 1 - {_{0.2}}p_{52.4} \\
&= 1 - \left( p_{52} \right)^{0.2} \\
&= 1 - \left( \frac{l_{53}} {l_{52}} \right)^{0.2} \\
&= 1 - \left( \frac{89089} {89948} \right)^{0.2} = 0.0019173306705693172
\end{align}$$
>
>$(\text{c})$ ${_{5.7}}p_{52.4}$ under **UDD**.
>
>$$\begin{align}
{_{5.7}}p_{52.4} &= \frac{l_{58.1}} {l_{52.4}} \\
&= \frac{l_{58} - 0.1 \cdot d_{58}} {l_{52} - 0.4 \cdot d_{52}} \\
&= \frac{83940 - 0.1\left( 83940 - 82719 \right)} {89948 - 0.4 \left( 89948 - 89089 \right)} \;= 0.935421698041614
\end{align}$$
>
>$(\text{d})$ ${_{5.7}}p_{52.4}$ under **CFM**.
>
>$\begin{align}
{_{5.7}}p_{52.4} &= 1 - {_{5.7}}q_{52.4} \\
&= 1 - \Big( {_{0.6}}q_{52.4} + \big(1 - {_{0.6}}q_{52.4}\big){_{5}}q_{53} + \big(1 - {_{0.6}}q_{52.4}\big) \big(1 - {_{5}}q_{53}\big) \cdot {_{0.1}}q_{58} \Big) \\
&= 1 - \Bigg( \! \bigg[ 1 - \bigg( \frac{l_{53}} {l_{52}} \bigg)^{0.6}\bigg] + \bigg( \frac{l_{53}} {l_{52}} \bigg)^{0.6} \frac{ l_{53} - l_{58}} {l_{53}} + \bigg( \frac{l_{53}} {l_{52}} \bigg)^{0.6} \frac{ l_{58}} {l_{53}} \bigg[ 1 - \Big( \frac{l_{59}} {l_{58}} \Big)^{0.1}\bigg] \! \Bigg) \\
&= 0.9354230247854776
\end{align}$
>
>$(\text{e})$ ${_{3.2 \mid 2.5}}\,q_{52.4}$ under **UDD**.
>
>$$\begin{align}
{_{3.2 \mid 2.5}}\,q_{52.4} &= {_{3.2}}p_{52.4} - {_{5.7}}p_{52.4} \\
&= \frac{l_{55.6}} {l_{52.4}} - \frac{l_{58.1}} {l_{52.4}} \\
&= \frac{\left(l_{55} - 0.6 \cdot d_{55}\right) - \left(l_{58} - 0.1 \cdot d_{58}\right)} {l_{52} - 0.4 \cdot d_{52}} \\
&= 0.03095718513822992
\end{align}$$
>$(\text{f})$ ${_{3.2 \mid 2.5}}\,q_{52.4}$ under **CFM**.
>
>$\begin{align}
{_{3.2 \mid 2.5}}\,q_{52.4} =&\, {_{3.2}}p_{52.4} - {_{5.7}}p_{52.4} \\
=& \, {_{5.7}}q_{52.4} - {_{3.2}}q_{52.4} \\
=&\, \Big( {_{0.6}}q_{52.4} + \big(1 - {_{0.6}}q_{52.4}\big){_{5}}q_{53} + \big(1 - {_{0.6}}q_{52.4}\big) \big(1 - {_{5}}q_{53}\big) \cdot {_{0.1}}q_{58} \Big) \\
&- \Big( {_{0.6}}q_{52.4} + \big(1 - {_{0.6}}q_{52.4}\big){_{2}}q_{53} + \big(1 - {_{0.6}}q_{52.4}\big) \big(1 - {_{2}}q_{53}\big) \cdot {_{0.6}}q_{55} \Big) \\
=&\, \Bigg( \! \bigg[ 1 - \bigg( \frac{l_{53}} {l_{52}} \bigg)^{0.6}\bigg] + \bigg( \frac{l_{53}} {l_{52}} \bigg)^{0.6} \frac{ l_{53} - l_{58}} {l_{53}} + \bigg( \frac{l_{53}} {l_{52}} \bigg)^{0.6} \frac{ l_{58}} {l_{53}} \bigg[ 1 - \Big( \frac{l_{59}} {l_{58}} \Big)^{0.1}\bigg] \! \Bigg) \\
&- \Bigg( \! \bigg[ 1 - \bigg( \frac{l_{53}} {l_{52}} \bigg)^{0.6}\bigg] + \bigg( \frac{l_{53}} {l_{52}} \bigg)^{0.6} \frac{ l_{53} - l_{55}} {l_{53}} + \bigg( \frac{l_{53}} {l_{52}} \bigg)^{0.6} \frac{ l_{55}} {l_{53}} \bigg[ 1 - \Big( \frac{l_{56}} {l_{55}} \Big)^{0.6}\bigg] \! \Bigg) \\
=& \, 0.030950242839582684
\end{align}$
>
>And actually you did the problem $(\text{d})$ and $(\text{f})$ a terrible way. Here's a better one
>
>$(\text{d})$
>
>$\begin{align}
{_{5.7}}p_{52.4} &= {_{0.6}}p_{52.4} \cdot {_{5}}p_{53} \cdot {_{0.1}}p_{58}\\
&= \Big( \frac{l_{53}} {l_{52}} \Big)^{0.6} \cdot \frac{ l_{58}} {l_{53}} \cdot \Big( \frac{l_{59}} {l_{58}} \Big)^{0.1} \\
&= 0.9354230247854776
\end{align}$
***
***
<center>**Summary Table**</center>
| Probability | International Actuarial Notation (IAN) | Meaning | Note |
|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:------------------------------------------:|:-----------------------------------------------------------------------------------------------------------------------------------:|
| $(x)$ | $(x)$ | a Life aged $x$ | $x \geq 0$ |
| $T_x(t)$ | $T_x(t)$ | Future Lifetime | continuous $r.v.$ |
| $F_x(t)$ | ${_{t}\,}q_{x}$ | Distribution Function of $T_x(t)$ | the probability of $(x)$ dies within $t$ years |
| $S_x(t) = 1 - F_x(t)$ | ${_{t}\,}p_{x} = 1 - {_{t}\,}q_{x}$ | Survival Function of $T_x(t)$ | the probability of $(x)$ survives $t$ years |
| $\mathrm{Pr} \left[ u < T_{x} \leq u + t \right] = S_{x}(u) - S_{x}(u + t)=F_{x}(u + t) - F_{x}(u)$ | ${_{u \mid t}\;}q_{x} = {_{u}\,}p_{x} - {_{u + t}\;\,}p_{x}$ | Deferred Mortality Probability of $T_x(t)$ | the probability of $(x)$ survives $\mathbf{u}$ years and dies within $\mathbf{t}$ years after that; no such ${_{u \mid t}\;\,}p_{x}$. |
| $S_x(t+d) = S_x(t) \cdot S_{x+t}\;(d)$ | ${_{t + u}\;\,}p_{x} = {_{t}\,}p_{x} \cdot {_{u}\;}p_{ x + t }$ | Factorization Formula | |
***
<center>**After** $\mu_{x}$</center>
| Probability | International Actuarial Notation (IAN) |
|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|
| $\displaystyle \mu_{x} = - \frac {\frac{\mathrm{d} }{\mathrm{d} x} S_{0} (x)} {S_{0} (x)} = \frac {\frac{\mathrm{d} }{\mathrm{d} x} F_{0}(x)} {S_{0} (x)} = \frac {f_{0} (x)} {S_{0} (x)} = - \frac{\mathrm{d} }{\mathrm{d} x} \log S_{0} (x) $ | $\displaystyle \mu_{x} = - \frac{\frac{\mathrm{d}}{\mathrm{d} x} \,S_{0}\left( x \right )} {S_{0}\left( x \right )} = - \frac{1}{{_{x} \, }p_{0}} \frac{\mathrm{d}}{\mathrm{d} x} \, \left( {_{x}\,}p_{0} \right )$ |
| $\displaystyle \mu_{x^{*} + t} = - \frac {\frac{\mathrm{d} }{\mathrm{d} t} S_{x^{*}} (t)} {S_{x^{*}} (t)} = \frac {\frac{\mathrm{d} }{\mathrm{d} t} F_{x^{*}}(t)} {S_{x^{*}} (t)} = \frac {f_{x^{*}} (t)} {S_{x^{*}} (t)}= - \frac{\mathrm{d} }{\mathrm{d} t} \log S_{x^{*}} (t)$ | $\displaystyle \mu_{x + t} \, = - \frac{\frac{\mathrm{d}}{\mathrm{d} t} \, S_{x}\left( t \right )} {S_{x}\left( t \right )} = - \frac{1}{{_{t}\,}p_{x}} \frac{\mathrm{d}}{\mathrm{d} t} \, \left( {_{t}\,}p_{x} \right ) $ |
| $f_{x}(t)$ | $\frac{\mathrm{d}}{\mathrm{d} t} \left( {_{t}}q_{x} \right ) = {_{t}\,}p_{x} \cdot \mu_{x + t}$ |
| $F_{x}(t)$ | ${_{t} \, }q_{x} = \int _{0} ^{t}\, {_{s}\,}p_{x} \, \mu_{ x + s } \;\; \mathrm{d}s$ |
| $S_{x} (t) = \exp \left\{ -\int_{0}^{t} \, \mu_{x+s} \;\;\mathrm{d} s \right\}$ | ${_{t} \, }p_{x}$ |
| | |
***
<center>**Mean and standard deviation for curtate and complete future life time, ** $T_x$ </center>
- **complete expection of life** for $x \geq 0$
$$
\begin{align*}
\overset{\circ}{e}_{x} &= \int_{-\infty} ^{\infty} t \cdot f_{x} \left( t \right) \mathrm{d}t \\
&= \int_{0} ^{\infty} t \cdot {_{t}p_{x}} \cdot \mu_{x + t} \mathrm{d}t \\
&= \int_{0} ^{\infty} t \cdot \left( -\frac{\mathrm{d}} {\mathrm{d}t} {_{t}q_{x}} \right) \mathrm{d}t \\
&= -\int_{0} ^{\infty} t \,{\mathrm{d} \left( {_{t}q_{x}} \right)} \\
&= -\left( t \cdot {_{t}p_{x}} \mid _{0} ^{\infty} - \int_{0} ^{\infty} {_{t}p_{x}} \, \mathrm{d}t \right) \\
&= \int_{0} ^{\infty} {_{t}p_{x}} \, \mathrm{d}t = \mathbb{E}\left[ \,T_{x} \,\right]
\end{align*}
$$
- **Second order complete expectation of life**
$$
\begin{align*}
\mathbb{E}\left[ \,T_{x}^{2} \,\right] &= -\left( t^2 \! \cdot \! {_{t}p_{x}} \mid _{0} ^{\infty} - \int_{0} ^{\infty} {_{t}p_{x}} \, \mathrm{d}t^2 \right) \\
&= - \left( \lim_{t \to \infty} t^2 \! \cdot \! {_{t}p_{x}} - \int_{0} ^{\infty} 2t \, {_{t}p_{x}} \, \mathrm{d}t \right) \\
&= \int_{0} ^{\infty} 2t \, {_{t}p_{x}} \, \mathrm{d}t
\end{align*}
$$
- **Curtate future lifetime**: $K_{x} = \left \lfloor T_{x} \right \rfloor$
$$\begin{align*}
\mathrm{Pr} \left[ K_{x} = k \right] &= \mathrm{Pr} \left[ k \leq T_{x} < k+1 \right] \\
&= {_{k \mid 1}}q_{x} \\
&= {_k}p_{x} - {_{k + 1}}p_{x} \\
&= {_k}p_{x} - {_k}p_{x} \cdot {_1}p_{x + k} \\
&= {_k}p_{x} \left( 1 - p_{x + k} \right) \\
&= {_k}p_{x} \cdot q_{x + k}
\end{align*}$$
- **Curtate expection of life**
$$\begin{align*}
e_{x} &= \mathbb{E}\left[ \,K_{x} \,\right] \\
&= \sum _{k = 0} ^{\infty} k \cdot \mathrm{Pr} \left[ K_{x} = k \right] \\
&= \sum _{k = 0} ^{\infty} k \cdot \Big( {_k}p_{x} - {_{k + 1}}p_{x} \Big) \\
&= 0 + 1\left( {_1}p_{x} - {_{2}}p_{x} \right) + 2\left( {_2}p_{x} - {_3}p_{x} \right) + 3\left( {_3}p_{x} - {_4}p_{x} \right) + \cdots \\
&= \sum _{k = \mathbf{1}} ^{\infty} {_k}p_{x}
\end{align*}$$
- **Second order curtate expectation of life**
$$\mathbb{E}\left[ \,K_{x}^{2} \,\right] = \sum _{k = \mathbf{1}} ^{\infty} \left( 2k-1 \right) \cdot {_k}p_{x} = 2\left( \sum _{k = \mathbf{1}} ^{\infty} k \cdot {_k}p_{x} \right) - e_{x}$$
- **RELATIONSHIP BETWEEN**
$$\begin{align*}
\overset{\circ}{e}_{x} &= \int_{0}^{\infty} {_t}p_{x} \mathrm{d}t \\
&= \sum _{j=0} ^{\infty} \int_{j}^{j+1} {_t}p_{x} \mathrm{d}t \\
&\approx \sum _{j=0} ^{\infty} \left( 1 \times {_{j+1}}p_{x} + \frac{1} {2} \times 1 \times \left( {_j}p_{x} - {_{j+1}}p_{x} \right) \right) \\
&= \sum _{j=0} ^{\infty} \left( \frac{1} {2} \left( {_j}p_{x} + {_{j+1}}p_{x} \right) \right) \\
&= \frac{1} {2} + \sum _{j=1} ^{\infty} {_j}p_{x} = \frac{1} {2} + e_{x}
\end{align*}$$
- **n-year annual term curtate expectation of life**: $L_{x} = \min\left( K_{x},n \right)$
$$\begin{align*}
e_{x:\overline {n|}} &= \mathbb{E} \left[ \, \min\left( K_{x},n \right) \, \right] \\
&= \sum _{l=0} ^{n} l \cdot \mathrm{Pr} \left[ L_{x} = l \right] \\
&= \left( \sum _{l=0} ^{n - 1} l \cdot \Big( {_l}p_{x} - {_{l + 1}}p_{x} \Big) \right) + n \cdot {_n}p_{x} \\
&= \sum _{\mathbf{l=1}} ^{n} {_l}p_{x}
\end{align*}$$
- **n-year annual term complete expectation of life**
$$\overset{\circ}{e}_{x:\overline {n|}} = \mathbb{E}\left[ \, \min\left( T_{x},n \right) \,\right]= \int_{\mathbf{0}}^{n} {_t}p_{x} \mathrm{d}t$$
***
<center>**After **$l_x$</center>
$\{l_{x}\}_{x \, \in \,\left[ x_{0}, \omega \right]}$, a function as follows: Let $l_{x_{0}}$ be an *arbitrary positive* number, called the **radix**. Then, for $0 \leq t \leq \omega − x_0$, define:
$$l_{x_0 + t} = l_{x_0} \cdot {_{t}}p_{x}$$
$${_{t}}p_{x} = \frac{l_{x+t}} {l_{x}}, {_{t}}q_{x} = \frac{l_{x} - l_{x+t}} {l_{x}}, {_{u \mid t}}q_{x} = \frac{l_{x + u} - l_{x + u + t}} {l_{x}}$$
***
<center>**UDD & CFM** after $d_{x} = l_{x} - l_{x+1}$</center>
- **UDD**
$${_{s}}q_{x} = s \cdot q_{x} = s \cdot {_{1}}q_{x} \Rightarrow l_{x+s} = l_{x} - s \cdot d_{x}$$
- After differentiate:
$$q_{x} = f_{x} \left( s \right) = {_s}p_x \cdot \mu_{x+s}, 0 \leq s < 1$$
- **CFM**
$${_{s}}p_{x+t} = (p_{x})^s, t, s > 0, t + s \leq 1$$
>**e.g.** Exercise 3.4 The given data are $q_{[x]}$, $q_{[x-1]+1}$, $q_{[x-2]+2}$, $q_{[x-3]+3}$, $q_{[x-4]+4}$, for duration more than $5$, it's just $q_{[x]}$.
>
>$(\text{a})$ ${_{2}}p_{[72]}$
>
>$$\begin{align}
{_{2}}p_{[72]} &= p_{[72]} \cdot p_{[72]+1} \\
&= \left(1 - q_{[72]}\right)\left(1 - q_{[72]+1}\right)
\end{align}$$
>
>$(\text{b})$ ${_{3}}q_{[73]+2}$
>
>$$\begin{align}
{_{3}}q_{[73]+2} &= 1 - \left(p_{[73]+2} \cdot p_{[73]+3} \cdot p_{[73]+4}\right)\\
&= 1 - \big( \left( 1 - q_{[73]+2} \right) \left( 1 - q_{[73]+3} \right) \left( 1 - q_{[73]+4} \right)\big)
\end{align}$$
>
>$(\text{c})$ ${_{1\mid}}q_{[65]+4}$
>
>$$\begin{align}
{_{1\mid}}q_{[65]+4} &= p_{[65]+4} - {_{2}}p_{[65]+4} \\
&= \left( 1 - q_{[65]+4} \right) - \left( 1 - q_{[65]+4} \right) \left( 1 - q_{[65]+5} \right) \\
&= \left( 1 - q_{[65]+4} \right) \times q_{65+5}
\end{align}$$
>
>$(\text{d})$ ${_{7}}p_{[70]}$
>
>$$\begin{align}
{_{7}}p_{[70]} &= p_{[70]}p_{[70]+1}p_{[70]+2}p_{[70]+3}p_{[70]+4}p_{[70]+5}p_{[70]+6} \\
&= \left( 1 - q_{[70]} \right) \left( 1 - q_{[70]+1} \right) \cdots \left( 1 - q_{[70]+4} \right) \left( 1 - q_{70+5} \right) \left( 1 - q_{70+6} \right)
\end{align}$$
>**e.g.** Exercise 3.5 The given data are $q_{[x]}$, $q_{[x-1]+1}$, $q_{[x-2]+2}$, $q_{[x-3]+3}$, $q_{[x-4]+4}$, for duration more than $5$, it's just $q_{[x]}$.
>
>$(\text{c})$ ${_{3.8}}q_{[70]+0.2}$, under *UDD*
>
>$$\begin{align*}
{_{3.8}}q_{[70]+0.2} &= 1 - {_{0.8}}p_{[70]+0.2}p_{[70]+1}p_{[70]+2}p_{[70]+3} \\
&= 1 - \left( \frac{p_{[70]}} {{_{0.2}}p_{[70]}} \right)p_{[70]+1}p_{[70]+2}p_{[70]+3} \\
&\stackrel{\mathbf{UDD}}{=} 1 - \left( \frac{1 - q_{[70]}} {0.2 \times \left( 1 - q_{[70]} \right)} \right) \left( 1 - q_{[70]+1} \right) \left( 1 - q_{[70]+2} \right)\left( 1 - q_{[70]+3} \right)
\end{align*}$$
|
Fey 's father had English , German , and Northern Irish ancestry ; one of Fey 's paternal great @-@ great @-@ great @-@ great @-@ great @-@ grandfathers was John Hewson ( 1744 – 1821 ) , a textile manufacturer who immigrated to America with the support of Benjamin Franklin , enabling Hewson to quickly open a quilting factory in the Kensington neighborhood of Philadelphia , Pennsylvania . According to a genealogical DNA test arranged by the television series Finding Your Roots , Fey 's ancestry is 94 % European , 3 % Middle Eastern , and 3 % from the Caucasus .
|
{-# OPTIONS --without-K --rewriting #-}
open import HoTT
module experimental.CubicalTypes where
data access : ℕ → ℕ → Type₀ where
[] : access O O
_#up : ∀ {n} {k} → access n k → access (S n) k
_#down : ∀ {n} {k} → access n k → access (S n) k
_#keep : ∀ {n} {k} → access n k → access (S n) (S k)
_a∙_ : ∀ {n k l} → access n k → access k l → access n l
_a∙_ [] a₂ = a₂
_a∙_ (a₁ #up) a₂ = (a₁ a∙ a₂) #up
_a∙_ (a₁ #down) a₂ = (a₁ a∙ a₂) #down
_a∙_ (a₁ #keep) (a₂ #up) = (a₁ a∙ a₂) #up
_a∙_ (a₁ #keep) (a₂ #down) = (a₁ a∙ a₂) #down
_a∙_ (a₁ #keep) (a₂ #keep) = (a₁ a∙ a₂) #keep
|
! Copyright (C) 2011
! Free Software Foundation, Inc.
! This file is part of the gtk-fortran GTK+ Fortran Interface library.
! This 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, or (at your option)
! any later version.
! This software 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.
! Under Section 7 of GPL version 3, you are granted additional
! permissions described in the GCC Runtime Library Exception, version
! 3.1, as published by the Free Software Foundation.
! You should have received a copy of the GNU General Public License along with
! this program; see the files COPYING3 and COPYING.RUNTIME respectively.
! If not, see <http://www.gnu.org/licenses/>.
!
! Contributed by Vincent Magnin, Jerry DeLisle, "jtappin" and Tobias Burnus, 01-23-2011
! Last modification: 03-15-2011
module gtk
!use iso_c_binding, only: c_null_char, c_null_ptr, c_null_funptr, c_ptr, c_funptr, c_char, c_int, c_long
use iso_c_binding
implicit none
include "gtkenums-auto.f90"
interface
!**************************************************************************
! You can add your own additional interfaces here:
!**************************************************************************
subroutine gtk_init_real(argc,argv) bind(c,name='gtk_init')
use iso_c_binding, only: c_int, c_ptr
integer(c_int) :: argc
type(c_ptr) :: argv
end subroutine
!**************************************************************************
! The interfaces automatically generated by cfwrapper.py are included here.
! Do not modify.
include "gtk-auto.f90"
!**************************************************************************
end interface
! Some useful parameters to ease coding:
! character(kind=c_char), parameter :: CNULL = c_null_char
! type(c_ptr), parameter :: NULL = c_null_ptr
! type(c_funptr), parameter :: FNULL = c_null_funptr
! In GTK+ gboolean is int:
integer(c_int), parameter :: FALSE = 0
integer(c_int), parameter :: TRUE = 1
contains
subroutine g_signal_connect (instance, detailed_signal, c_handler, data0)
use iso_c_binding, only: c_ptr, c_char, c_funptr
use g, only: g_signal_connect_data
character(kind=c_char):: detailed_signal(*)
type(c_ptr) :: instance
type(c_funptr) :: c_handler
type(c_ptr), optional :: data0
integer(c_long) :: handler_id
if (present(data0)) then
handler_id = g_signal_connect_data (instance, detailed_signal, c_handler, &
& data0, c_null_funptr, 0_c_int)
else
handler_id = g_signal_connect_data (instance, detailed_signal, c_handler, &
& c_null_ptr, c_null_funptr, 0_c_int)
end if
end subroutine
subroutine gtk_init()
use iso_c_binding, only: c_ptr, c_char, c_int, c_null_char, c_loc
character(len=256,kind=c_char) :: arg
character(len=1,kind=c_char), dimension(:),pointer :: carg
type(c_ptr), allocatable, target :: argv(:)
integer(c_int) :: argc, j
integer :: i, strlen
argc = command_argument_count()
allocate(argv(0:argc))
do i = 0, argc
call get_command_argument (i,arg,strlen)
allocate(carg(0:strlen))
do j = 0, strlen-1
carg(j) = arg(j+1:j+1)
end do
carg(strlen) = c_null_char
argv(i) = c_loc (carg(0))
end do
argc = argc + 1
! This is a workaround to prevent locales with decimal comma
! from behaving wrongly reading reals after gtk_init is called
! when the code is compiled using gfortran.
call gtk_disable_setlocale()
call gtk_init_real (argc, c_loc(argv))
!deallocate(argv)
!deallocate(carg)
end subroutine gtk_init
end module gtk
|
module FluxExtra
using Flux, Statistics
include("layers.jl")
include("Normalizations.jl")
export Join, Split, Addition, Activation, Flatten, Identity
export Normalizations
end
|
theory Exe3p1
imports Main
begin
datatype 'a tree = Tip | Node "'a tree" 'a "'a tree"
fun set :: "'a tree \<Rightarrow> 'a set" where
"set Tip = {}" |
"set (Node l n r) = {n} \<union> set l \<union> set r"
fun ord :: "int tree \<Rightarrow> bool" where
"ord Tip = True" |
"ord (Node l n r) = (\<not>(\<exists>x. x \<in> set l \<and> x > n) \<and> \<not>(\<exists>x. x \<in> set r \<and> x < n))"
fun ins :: "int \<Rightarrow> int tree \<Rightarrow> int tree" where
"ins x Tip = Node Tip x Tip" |
"ins x (Node l n r) = (
if x = n then (Node l n r)
else (if x < n then (Node (ins x l) n r)
else (Node l n (ins x r))))"
lemma ins_correctness_1 [simp]: "set (ins x t) = {x} \<union> set t"
apply(induction t)
apply(auto)
done
lemma ins_correctness_2: "ord t \<Longrightarrow> ord (ins i t)"
apply(induction t)
apply(auto)
done
thm conjI
thm conjI[of "a=b" "False"]
thm conjI[OF refl[of "a"] refl[of "b"]]
|
[STATEMENT]
lemma sub_lists_mono: "A \<subseteq> B \<Longrightarrow> x \<in> lists A \<Longrightarrow> x \<in> lists B"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>A \<subseteq> B; x \<in> lists A\<rbrakk> \<Longrightarrow> x \<in> lists B
[PROOF STEP]
by auto |
{-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor #-}
{-# LANGUAGE FlexibleInstances, DefaultSignatures #-}
{-# LANGUAGE ScopedTypeVariables, BangPatterns, ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module: Data.Configurator.FromValue.Implementation
-- Copyright: (c) 2016 Leon P Smith
-- License: BSD3
-- Maintainer: Leon P Smith <[email protected]>
module Data.Configurator.FromValue.Implementation where
import Prelude
import Control.Applicative
import Control.Arrow (first, second)
import Control.Monad (ap)
import qualified Control.Monad.Fail as Fail
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as LB
import Data.Complex (Complex((:+)))
import Data.Configurator.Types
( Value(..)
, ConversionError(..)
, ConversionErrorWhy(..)
, defaultConversionError
)
import Data.Configurator.Types.Internal
( MultiErrors
, singleError
, toErrors
)
import Data.Fixed (Fixed, HasResolution)
import Data.Int(Int8, Int16, Int32, Int64)
-- import Data.Monoid
import Data.Ratio ( Ratio, (%) )
import Data.Scientific
( Scientific, coefficient, base10Exponent, normalize
, floatingOrInteger, toRealFloat, toBoundedInteger )
import Data.Text(Text)
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
import Data.Text.Encoding(encodeUtf8)
import Data.Typeable(Typeable, TypeRep, typeOf)
#if !(MIN_VERSION_base(4,8,0))
import Data.Word(Word)
#endif
import Data.Word(Word8, Word16, Word32, Word64)
import Foreign.C.Types(CFloat, CDouble)
type ConversionErrors = MultiErrors ConversionError
-- | An action to turn a 'Maybe' 'Value' into zero or one values of type @a@,
-- and possibly report errors/warnings.
newtype MaybeParser a = MaybeParser {
unMaybeParser :: Maybe Value -> (Maybe a, ConversionErrors)
} deriving (Functor, Typeable)
-- | An action to turn a 'Value' into zero or one values of type @a@,
-- and possibly report errors/warnings.
newtype ValueParser a = ValueParser {
unValueParser :: Value -> (Maybe a, ConversionErrors)
} deriving (Functor, Typeable)
data ListParserResult a =
NonListError
| ListError
| ListOk a [Value]
deriving (Functor, Typeable)
-- | An action to turn a @['Value']@ into zero or one values of type @a@,
-- and possibly report errors/warnings.
newtype ListParser a = ListParser {
unListParser :: [Value] -> (ListParserResult a, ConversionErrors)
} deriving (Functor, Typeable)
instance Applicative MaybeParser where
pure a = MaybeParser $ \_v -> (Just a, mempty)
(<*>) ff fa =
MaybeParser $ \v ->
case unMaybeParser ff v of
(Nothing, w) -> (Nothing, w)
(Just f , w) ->
case unMaybeParser fa v of
(Nothing, w') -> (Nothing , w <> w')
(Just a , w') -> (Just (f a), w <> w')
instance Applicative ValueParser where
pure a = ValueParser $ \_v -> (Just a, mempty)
(<*>) ff fa =
ValueParser $ \v ->
case unValueParser ff v of
(Nothing, w) -> (Nothing, w)
(Just f , w) ->
case unValueParser fa v of
(Nothing, w') -> (Nothing , w <> w')
(Just a , w') -> (Just (f a), w <> w')
instance Alternative ValueParser where
empty = ValueParser $ \_v -> (Nothing, mempty)
f <|> g = ValueParser $ \v ->
case unValueParser f v of
(Nothing, Nothing) -> unValueParser g v
(Nothing, w) ->
case unValueParser g v of
(Nothing, w') -> (Nothing, w <> w')
res -> res
res -> res
some v = repeat <$> v
many v = some v <|> pure []
instance Alternative MaybeParser where
empty = MaybeParser $ \_v -> (Nothing, mempty)
f <|> g = MaybeParser $ \v ->
case unMaybeParser f v of
(Nothing, Nothing) -> unMaybeParser g v
(Nothing, w) ->
case unMaybeParser g v of
(Nothing, w') -> (Nothing, w <> w')
res -> res
res -> res
some v = repeat <$> v
many v = some v <|> pure []
instance Monad MaybeParser where
#if !(MIN_VERSION_base(4,8,0))
return = pure
#endif
m >>= k = MaybeParser $ \v ->
case unMaybeParser m v of
(Just a, w) ->
case w of
Nothing -> unMaybeParser (k a) v
Just _ -> let (mb, w') = unMaybeParser (k a) v
in (mb, w <> w')
(Nothing, w) -> (Nothing, w)
fail = Fail.fail
instance Monad ValueParser where
#if !(MIN_VERSION_base(4,8,0))
return = pure
#endif
m >>= k = ValueParser $ \v ->
case unValueParser m v of
(Just a, w) ->
case w of
Nothing -> unValueParser (k a) v
Just _ -> let (mb, w') = unValueParser (k a) v
in (mb, w <> w')
(Nothing, w) -> (Nothing, w)
fail = Fail.fail
instance Fail.MonadFail MaybeParser where
fail msg = MaybeParser $ \_v -> (Nothing, singleError (failError msg))
instance Fail.MonadFail ValueParser where
fail msg = ValueParser $ \_v -> (Nothing, singleError (failError msg))
failError :: String -> ConversionError
failError msg = defaultConversionError {
conversionErrorLoc = "fail",
conversionErrorWhy = MonadFail,
conversionErrorMsg = Just (T.pack msg)
}
runMaybeParser :: MaybeParser a -> Maybe Value -> (Maybe a, [ConversionError])
runMaybeParser p = second toErrors . unMaybeParser p
runValueParser :: ValueParser a -> Value -> (Maybe a, [ConversionError])
runValueParser p = second toErrors . unValueParser p
instance Applicative ListParser where
pure a = ListParser $ \vs -> (ListOk a vs, mempty)
(<*>) = ap
instance Alternative ListParser where
empty = ListParser $ \_v -> (ListError, mempty)
f <|> g = ListParser $ \v ->
case unListParser f v of
(ListError, Nothing) -> unListParser g v
(ListError, w) ->
case unListParser g v of
(ListError, w') -> (ListError, w <> w')
res -> res
res -> res
instance Monad ListParser where
#if !(MIN_VERSION_base(4,8,0))
return = pure
#endif
m >>= k = ListParser $ \v ->
case unListParser m v of
(ListOk a v', w) ->
case w of
Nothing -> unListParser (k a) v'
Just _ -> let (mb, w') = unListParser (k a) v'
in (mb, w <> w')
(ListError, w) ->
(ListError, w)
(NonListError, w) ->
(NonListError, w)
fail = Fail.fail
instance Fail.MonadFail ListParser where
fail msg = ListParser $ \_v -> (NonListError, singleError (failError msg))
-- | Turns a 'ValueParser' into a 'MaybeParser'. If the 'Maybe' 'Value' the
-- parser is passed is 'Nothing' (which normally means a key was not found),
-- then this returns the @Nothing@ value with no errors or warnings.
-- Otherwise, it passes the 'Value' to the subparser. If the
-- subparser returns a result value, then this returns 'Just' the value.
-- Otherwise, if the subparser does not return a value, then this does
-- not return a value.
--
-- Any errors/warnings returned by the subparser are returned exactly as-is.
optionalValue :: ValueParser a -> MaybeParser (Maybe a)
optionalValue p =
MaybeParser $ \mv ->
case mv of
Nothing -> (Just Nothing, mempty)
Just v -> first (Just <$>) (unValueParser p v)
-- | Turns a 'ValueParser' into a 'MaybeParser'. If the 'Maybe' 'Value' the
-- parser is passed is 'Nothing' (which normally means a key was not found),
-- then this does not return a value and also returns a 'missingValueError'.
-- Otherwise, the 'Value' is passed to the subparser, and the result
-- and any errors/warnings are returned as-is.
requiredValue :: forall a. Typeable a => ValueParser a -> MaybeParser a
requiredValue p =
MaybeParser $ \mv ->
case mv of
Nothing -> (Nothing, err)
Just v -> unValueParser p v
where
funcName = "requiredValue"
err = singleError $ missingValueError funcName (typeOf (undefined :: a))
missingValueError :: Text -> TypeRep -> ConversionError
missingValueError funcName typ = defaultConversionError {
conversionErrorLoc = funcName,
conversionErrorWhy = MissingValue,
conversionErrorType = Just typ
}
-- | Turns a 'ListParser' into a 'ValueParser'. It first checks that the
-- 'Value' the 'ValueParser' is passed is a 'List' Value. If it's not,
-- this returns no result as well as a 'typeError'. Otherwise, it passes
-- the list of results to the 'ListParser' subparser.
--
-- If the subparser consumes all of the list elements, this returns the
-- value and errors as-is. If there are leftover list elements, this
-- returns the value, and adds a message warning of the extra elements
-- to the list of errors.
--
-- The difference from 'listValue\'' is that this returns values with
-- unconsumed list elements (discarding the list elements).
listValue :: forall a. Typeable a => ListParser a -> ValueParser a
listValue p =
ValueParser $ \v ->
case v of
List vs ->
case unListParser p vs of
(ListOk a vs', errs) ->
case vs' of
[] -> (Just a, errs)
(_:_) -> (,) (Just a) $! errs <> extraErr vs
(_, errs) -> (Nothing, errs)
_ -> (Nothing, typeErr v)
where
fn = "listValue"
extraErr vs = singleError $ extraValuesError fn vs (typeOf (undefined :: a))
typeErr v = singleError $ typeError fn v (typeOf (undefined :: a))
-- | Turns a 'ListParser' into a 'ValueParser'. It first checks that the
-- 'Value' the 'ValueParser' is passed is a 'List' Value. If it's not,
-- this returns no result as well as a 'typeError'. Otherwise, it passes
-- the list of results to the 'ListParser' subparser.
--
-- If the subparser consumes all of the list elements, this returns the
-- value and errors as-is. If there are leftover list elements, this
-- returns no value, and adds a message warning of the extra elements
-- to the list of errors.
--
-- The difference from 'listValue' is that this never returns a value if
-- there are unconsumed list elements. (discarding both the value returned
-- and the list element.)
listValue' :: forall a. Typeable a => ListParser a -> ValueParser a
listValue' p =
ValueParser $ \v ->
case v of
List vs ->
case unListParser p vs of
(ListOk a vs', errs) ->
case vs' of
[] -> (Just a, errs)
(_:_) -> (,) Nothing $! errs <> extraErr vs
(_, errs) -> (Nothing, errs)
_ -> (Nothing, typeErr v)
where
fn = "listValue'"
extraErr vs = singleError $ extraValuesError fn vs (typeOf (undefined :: a))
typeErr v = singleError $ typeError fn v (typeOf (undefined :: a))
-- | Turns a 'ValueParser' into a 'ListParser' that consumes a single element.
--
-- If there are no list elements left, this returns list error value and an
-- 'ExhaustedValues' error.
--
-- If there is an element left, it is passed to the value parser. If the
-- value parser returns a value, it is returned along with the errors as-is.
-- If the value parser returns no value, then this returns a non-list error
-- value and the list of errors returned by the value parser.
--
-- The difference between a "list error value" and a "non-list error value",
-- is that the 'Alternative' instance for 'ListParser' recovers from "list
-- error" values but does not recover from "non-list error" values. This
-- behavior was chosen so that the 'optional', 'some', and 'many' combinators
-- work on 'ListParser's in a way that is hopefully least surprising.
listElem :: forall a. (Typeable a) => ValueParser a -> ListParser a
listElem p =
ListParser $ \vs ->
case vs of
[] -> (ListError, exhaustedError)
(v:vs') -> case unValueParser p v of
(Nothing, errs) -> (NonListError, errs)
(Just a, errs) -> (ListOk a vs', errs)
where
exhaustedError = singleError defaultConversionError {
conversionErrorLoc = "listElem",
conversionErrorWhy = ExhaustedValues,
conversionErrorType = Just (typeOf (undefined :: a))
}
extraValuesError :: Text -> [Value] -> TypeRep -> ConversionError
extraValuesError funcName vals typ
= defaultConversionError {
conversionErrorLoc = funcName,
conversionErrorWhy = ExtraValues,
conversionErrorVal = Just (List vals),
conversionErrorType = Just typ
}
typeError :: Text -> Value -> TypeRep -> ConversionError
typeError funcName val typ
= defaultConversionError {
conversionErrorLoc = funcName,
conversionErrorWhy = TypeError,
conversionErrorVal = Just val,
conversionErrorType = Just typ
}
boundedIntegerValue :: forall a. (Typeable a, Integral a, Bounded a)
=> ValueParser a
boundedIntegerValue =
ValueParser $ \v ->
case v of
(Number r) ->
case toBoundedInteger r of
ja@(Just _) -> (ja , mempty)
Nothing -> (Nothing, overflowErr r)
_ -> (Nothing, typeErr v)
where
fn = "boundedIntegerValue"
overflowErr v = singleError (overflowError fn v (typeOf (undefined :: a)))
typeErr v = singleError (typeError fn v (typeOf (undefined :: a)))
overflowError :: Text -> Scientific -> TypeRep -> ConversionError
overflowError fn val typ = valueError fn (Number val) typ "overflow"
valueError :: Text -> Value -> TypeRep -> Text -> ConversionError
valueError funcName val typ msg
= defaultConversionError {
conversionErrorLoc = funcName,
conversionErrorWhy = ValueError,
conversionErrorVal = Just val,
conversionErrorType = Just typ,
conversionErrorMsg = Just msg
}
integralValue :: forall a. (Typeable a, Integral a) => ValueParser a
integralValue =
ValueParser $ \v ->
case v of
Number r ->
if base10Exponent r >= 0
then toIntegral r
else let r' = normalize r
in if base10Exponent r' >= 0
then toIntegral r'
else (Nothing, intErr r)
_ -> (Nothing, typeErr v)
where
fn = "integralValue"
intErr r = singleError (notAnIntegerError fn r (typeOf (undefined :: a)))
typeErr v = singleError (typeError fn v (typeOf (undefined :: a)))
toIntegral r =
case floatingOrInteger r of
Right a -> (Just a, mempty)
-- This case should be impossible:
Left (_::Float) -> (Nothing, intErr r)
notAnIntegerError :: Text -> Scientific -> TypeRep -> ConversionError
notAnIntegerError fn val typ = valueError fn (Number val) typ "not an integer"
fractionalValue :: forall a. (Typeable a, Fractional a) => ValueParser a
fractionalValue =
ValueParser $ \v ->
case v of
Number r ->
let !c = coefficient r
!e = base10Exponent r
!r' = fromRational $! if e >= 0
then (c * 10^e) % 1
else c % (10^(- e))
in (Just r', mempty)
_ -> (Nothing, typeErr v)
where
fn = "fractionalValue"
typeErr v = singleError (typeError fn v (typeOf (undefined :: a)))
realFloatValue :: forall a. (Typeable a, RealFloat a) => ValueParser a
realFloatValue = realFloatValue_ (typeOf (undefined :: a))
realFloatValue_ :: (RealFloat a) => TypeRep -> ValueParser a
realFloatValue_ typ =
ValueParser $ \v ->
case v of
Number (toRealFloat -> !r) -> (Just r, mempty)
_ -> (Nothing, typeErr v)
where
fn = "realFloatValue"
typeErr v = singleError (typeError fn v typ)
fixedValue :: forall a. (Typeable a, HasResolution a) => ValueParser (Fixed a)
fixedValue = fractionalValue
-- FIXME: optimize fixedValue and/or Data.Fixed
class FromMaybeValue a where
fromMaybeValue :: MaybeParser a
default fromMaybeValue :: (Typeable a, FromValue a) => MaybeParser a
fromMaybeValue = requiredValue fromValue
class FromValue a where
fromValue :: ValueParser a
class FromListValue a where
fromListValue :: ListParser a
instance FromValue a => FromMaybeValue (Maybe a) where
fromMaybeValue = optionalValue fromValue
instance FromMaybeValue Bool
instance FromValue Bool where
fromValue = boolValue
boolValue :: ValueParser Bool
boolValue =
ValueParser $ \v ->
case v of
Bool b -> (Just b, mempty)
_ -> (Nothing, typeErr v (typeOf True))
where
fn = "boolValue"
typeErr v t = singleError (typeError fn v t)
instance FromMaybeValue Value where
fromMaybeValue = MaybeParser $ \mv -> (mv, mempty)
instance FromValue Value where
fromValue = ValueParser $ \v -> (Just v, mempty)
instance FromMaybeValue Int
instance FromValue Int where
fromValue = boundedIntegerValue
instance FromMaybeValue Integer
instance FromValue Integer where
fromValue = integralValue
instance FromMaybeValue Int8
instance FromValue Int8 where
fromValue = boundedIntegerValue
instance FromMaybeValue Int16
instance FromValue Int16 where
fromValue = boundedIntegerValue
instance FromMaybeValue Int32
instance FromValue Int32 where
fromValue = boundedIntegerValue
instance FromMaybeValue Int64
instance FromValue Int64 where
fromValue = boundedIntegerValue
instance FromMaybeValue Word
instance FromValue Word where
fromValue = boundedIntegerValue
instance FromMaybeValue Word8
instance FromValue Word8 where
fromValue = boundedIntegerValue
instance FromMaybeValue Word16
instance FromValue Word16 where
fromValue = boundedIntegerValue
instance FromMaybeValue Word32
instance FromValue Word32 where
fromValue = boundedIntegerValue
instance FromMaybeValue Word64
instance FromValue Word64 where
fromValue = boundedIntegerValue
instance FromMaybeValue Double
instance FromValue Double where
fromValue = realFloatValue
instance FromMaybeValue Float
instance FromValue Float where
fromValue = realFloatValue
instance FromMaybeValue CDouble
instance FromValue CDouble where
fromValue = realFloatValue
instance FromMaybeValue CFloat
instance FromValue CFloat where
fromValue = realFloatValue
instance (Typeable a, Integral a) => FromMaybeValue (Ratio a)
instance (Typeable a, Integral a) => FromValue (Ratio a) where
fromValue = fractionalValue
instance FromMaybeValue Scientific
instance FromValue Scientific where
fromValue = scientificValue
scientificValue :: ValueParser Scientific
scientificValue =
ValueParser $ \v ->
case v of
Number r -> (Just r, mempty)
_ -> (Nothing, typeErr v)
where
fn = "scientificValue"
typeErr v = singleError (typeError fn v (typeOf (undefined :: Scientific)))
instance (Typeable a, RealFloat a) => FromMaybeValue (Complex a)
instance (Typeable a, RealFloat a) => FromValue (Complex a) where
fromValue = (:+ 0) <$> realFloatValue_ (typeOf (undefined :: Complex a))
instance (Typeable a, HasResolution a) => FromMaybeValue (Fixed a)
instance (Typeable a, HasResolution a) => FromValue (Fixed a) where
fromValue = fixedValue
instance FromMaybeValue Text
instance FromValue Text where
fromValue = textValue
textValue :: ValueParser Text
textValue = textValue_ (typeOf (undefined :: Text))
textValue_ :: TypeRep -> ValueParser Text
textValue_ typ =
ValueParser $ \v ->
case v of
String r -> (Just r, mempty)
_ -> (Nothing, typeErr v typ)
where
fn = "textValue"
typeErr v t = singleError (typeError fn v t)
instance FromMaybeValue Char
instance FromValue Char where
fromValue = charValue
charValue :: ValueParser Char
charValue =
ValueParser $ \v ->
case v of
String txt ->
case T.uncons txt of
Nothing -> (Nothing, charErr txt)
Just (c,txt')
| T.null txt' -> (Just c, mempty)
| otherwise -> (Nothing, charErr txt)
_ -> (Nothing, typeErr v)
where
fn = "charValue"
typ = typeOf (undefined :: Char)
msg = "expecting exactly one character"
charErr v = singleError (valueError fn (String v) typ msg)
typeErr v = singleError (typeError fn v typ)
instance FromMaybeValue L.Text
instance FromValue L.Text where
fromValue = L.fromStrict <$> textValue_ (typeOf (undefined :: L.Text))
instance FromMaybeValue B.ByteString
instance FromValue B.ByteString where
fromValue = encodeUtf8 <$> textValue_ (typeOf (undefined :: B.ByteString))
instance FromMaybeValue LB.ByteString
instance FromValue LB.ByteString where
fromValue = convert <$> textValue_ (typeOf (undefined :: LB.ByteString))
where convert = LB.fromStrict . encodeUtf8
-- AJ
-- instance FromMaybeValue String
-- instance FromValue String where
-- fromValue = T.unpack <$> textValue_ (typeOf (undefined :: String))
instance ( Typeable a, FromValue a
, Typeable b, FromValue b ) => FromMaybeValue (a,b)
instance ( Typeable a, FromValue a
, Typeable b, FromValue b ) => FromValue (a,b) where
fromValue = listValue fromListValue
instance ( Typeable a, FromValue a
, Typeable b, FromValue b ) => FromListValue (a,b) where
fromListValue = (,) <$> listElem fromValue <*> listElem fromValue
instance ( Typeable a, FromValue a
, Typeable b, FromValue b
, Typeable c, FromValue c ) => FromMaybeValue (a,b,c)
instance ( Typeable a, FromValue a
, Typeable b, FromValue b
, Typeable c, FromValue c ) => FromValue (a,b,c) where
fromValue = listValue fromListValue
instance ( Typeable a, FromValue a
, Typeable b, FromValue b
, Typeable c, FromValue c ) => FromListValue (a,b,c) where
fromListValue = (,,) <$> listElem fromValue <*> listElem fromValue
<*> listElem fromValue
instance (Typeable a, FromValue a) => FromMaybeValue [a]
instance (Typeable a, FromValue a) => FromValue [a] where
fromValue = listValue (many (listElem fromValue))
instance ( Typeable a, FromValue a
, Typeable b, FromValue b
, Typeable c, FromValue c
, Typeable d, FromValue d ) => FromMaybeValue (a,b,c,d)
instance ( Typeable a, FromValue a
, Typeable b, FromValue b
, Typeable c, FromValue c
, Typeable d, FromValue d ) => FromValue (a,b,c,d) where
fromValue = listValue fromListValue
instance ( Typeable a, FromValue a
, Typeable b, FromValue b
, Typeable c, FromValue c
, Typeable d, FromValue d ) => FromListValue (a,b,c,d) where
fromListValue = (,,,) <$> listElem fromValue <*> listElem fromValue
<*> listElem fromValue <*> listElem fromValue
{--
parserFail :: forall a. Typeable a => T.Text -> Maybe T.Text -> ValueParser a
parserFail loc msg = ValueParser $ \st -> (Nothing, failError, st)
where
failError = singleError defaultConversionError {
conversionErrorLoc = loc
conversionErrorWhy = MonadFail,
conversionErrorType = Just (typeRep (undefined :: a)),
conversionErrorMsg = msg
}
--}
{--
defaultValue :: Typeable a => a -> ValueParser a -> ValueParser a
defaultValue def m =
ValueParser $ \vs ->
case vs of
(Nothing:vs') -> (Just def, mempty, vs')
_
--}
|
```
#@title Copyright 2020 The Cirq Developers
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
```
# QAOA: Max-Cut
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://quantumai.google/cirq/tutorials/qaoa">View on QuantumAI</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/tutorials/qaoa.ipynb">Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/qaoa.ipynb">View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/Cirq/docs/tutorials/qaoa.ipynb">Download notebook</a>
</td>
</table>
In this tutorial, we implement the quantum approximate optimization algorithm (QAOA) for determining the Max-Cut of the Sycamore processor's hardware graph (with random edge weights). To do so, we will:
1. Define a random set of weights over the hardware graph.
2. Construct a QAOA circuit using Cirq.
3. Calculate the expected value of the QAOA cost function.
4. Create an outer loop optimization to minimize the cost function.
5. Compare cuts found from QAOA with random cuts.
```
try:
import cirq
except ImportError:
print("installing cirq...")
!pip install --quiet cirq
import cirq
print("installed cirq.")
```
## 1. Defining a random set of weights over the hardware graph
In order to make the problem easily embeddable on a quantum device, we will look at the problem of Max-Cut on the same graph that the device's qubit connectivity defines, but with random valued edge weights.
```
import cirq_google
import sympy
import numpy as np
import matplotlib.pyplot as plt
working_device = cirq_google.Sycamore
print(working_device)
```
Since a circuit covering the entire Sycamore device cannot be easily simulated, a small subset of the device graph will be used instead.
```
import networkx as nx
# Set the seed to determine the problem instance.
np.random.seed(seed=11)
# Identify working qubits from the device.
device_qubits = working_device.qubits
working_qubits = sorted(device_qubits)[:12]
# Populate a networkx graph with working_qubits as nodes.
working_graph = working_device.metadata.nx_graph.subgraph(working_qubits)
# Add random weights to edges of the graph. Each weight is a 2 decimal floating point between 0 and 5.
nx.set_edge_attributes(working_graph, {e: {'weight': np.random.randint(0, 500) / 100} for e in working_graph.edges})
# Draw the working_graph on a 2d grid
pos = {q:(q.col, -q.row) for q in working_graph.nodes()}
nx.draw(working_graph, pos=pos, with_labels=True, node_size=1000)
plt.show()
```
## 2. Construct the QAOA circuit
Now that we have created a Max-Cut problem graph, it's time to generate the QAOA circuit following [Farhi et al.](https://arxiv.org/abs/1411.4028). For simplicity $p = 1$ is chosen.
```
from cirq.contrib.svg import SVGCircuit
# Symbols for the rotation angles in the QAOA circuit.
alpha = sympy.Symbol('alpha')
beta = sympy.Symbol('beta')
qaoa_circuit = cirq.Circuit(
# Prepare uniform superposition on working_qubits == working_graph.nodes
cirq.H.on_each(working_graph.nodes()),
# Do ZZ operations between neighbors u, v in the graph. Here, u is a qubit,
# v is its neighboring qubit, and w is the weight between these qubits.
(cirq.ZZ(u, v) ** (alpha * w['weight']) for (u, v, w) in working_graph.edges(data=True)),
# Apply X operations along all nodes of the graph. Again working_graph's
# nodes are the working_qubits. Note here we use a moment
# which will force all of the gates into the same line.
cirq.Moment(cirq.X(qubit) ** beta for qubit in working_graph.nodes()),
# All relevant things can be computed in the computational basis.
(cirq.measure(qubit) for qubit in working_graph.nodes()),
)
SVGCircuit(qaoa_circuit)
```
## 3. Calculating the expected value of the QAOA cost Hamiltonian
Now that we have created a parameterized QAOA circuit, we need a way to calculate expectation values of the cost Hamiltonian. For Max-Cut, the cost Hamiltonian is
$$
H_C = \frac{1}{2} \sum_{\langle i, j\rangle} w_{ij} (1 - Z_i Z_j )
$$
where $\langle i, j \rangle$ denotes neighboring qubits, $w_{ij}$ is the weight of edge $ij$, and $Z$ is the usual Pauli-$Z$ matrix. The expectation value of this cost Hamiltonian is $\langle \alpha, \beta | H_C | \alpha, \beta \rangle$ where $|\alpha, \beta\rangle$ is the quantum state prepared by our `qaoa_circuit`. This is the cost function we need to estimate.
> Pauli-$Z$ has eigenvalues $\pm 1$. If qubits $i$ and $j$ are in the same eigenspace, then $\langle Z_i Z_j \rangle = 1$ and so $\frac{1}{2} w_{ij} \langle 1 - Z_i Z_j \rangle = 0$. In the Max-Cut language, this means that edge $ij$ does not contribute to the cost. If qubits $i$ and $j$ are in the opposite eigenspace, then $\langle Z_i Z_j \rangle = -1$ and so $\frac{1}{2} w_{ij} \langle 1 - Z_i Z_j \rangle = w_{ij}$. In the Max-Cut language, this means that edge $ij$ contributes its weight $w_{ij}$ to the cost.
To estimate the cost function, we need to estimate the (weighted) sum of all $ZZ$ pairs in the graph. Since these terms are diagonal in the same basis (namely, the computational basis), they can measured simultaneously. Given a set of measurements (samples), the function below estimates the cost function.
> *Note*: We say "estimate the cost" instead of "compute the cost" since we are sampling from the circuit. This is how the cost would be evaluated when running QAOA on a real quantum processor.
```
def estimate_cost(graph, samples):
"""Estimate the cost function of the QAOA on the given graph using the
provided computational basis bitstrings."""
cost_value = 0.0
# Loop over edge pairs and compute contribution.
for u, v, w in graph.edges(data=True):
u_samples = samples[str(u)]
v_samples = samples[str(v)]
# Determine if it was a +1 or -1 eigenvalue.
u_signs = (-1)**u_samples
v_signs = (-1)**v_samples
term_signs = u_signs * v_signs
# Add scaled term to total cost.
term_val = np.mean(term_signs) * w['weight']
cost_value += term_val
return -cost_value
```
Now we can sample from the `qaoa_circuit` and use `estimate_expectation` to calculate the expectation value of the cost function for the circuit. Below, we use arbitrary values for $\alpha$ and $\beta$.
```
alpha_value = np.pi / 4
beta_value = np.pi / 2
sim = cirq.Simulator()
sample_results = sim.sample(
qaoa_circuit,
params={alpha: alpha_value, beta: beta_value},
repetitions=20_000
)
print(f'Alpha = {round(alpha_value, 3)} Beta = {round(beta_value, 3)}')
print(f'Estimated cost: {estimate_cost(working_graph, sample_results)}')
```
## 4. Outer loop optimization
Now that we can compute the cost function, we want to find the optimal cost. There are lots of different techniques to choose optimal parameters for the `qaoa_circuit`. Since there are only two parameters here ($\alpha$ and $\beta$), we can keep things simple and sweep over incremental pairings using `np.linspace` and track the minimum value found along the way.
```
# Set the grid size = number of points in the interval [0, 2π).
grid_size = 5
exp_values = np.empty((grid_size, grid_size))
par_values = np.empty((grid_size, grid_size, 2))
for i, alpha_value in enumerate(np.linspace(0, 2 * np.pi, grid_size)):
for j, beta_value in enumerate(np.linspace(0, 2 * np.pi, grid_size)):
samples = sim.sample(
qaoa_circuit,
params={alpha: alpha_value, beta: beta_value},
repetitions=20000
)
exp_values[i][j] = estimate_cost(working_graph, samples)
par_values[i][j] = alpha_value, beta_value
```
We can now visualize the cost as a function of $\alpha$ and $\beta$.
```
plt.title('Heatmap of QAOA Cost Function Value')
plt.xlabel(r'$\alpha$')
plt.ylabel(r'$\beta$')
plt.imshow(exp_values)
plt.show()
```
This heatmap is coarse because we selected a small `grid_size`. To see more detail in the heatmap, one can increase the `grid_size`.
## 5. Compare cuts
We now compare the optimal cut found by QAOA to a randomly selected cut. The helper function draws the `working_graph` and colors nodes in different sets different colors. Additionally, we print out the cost function for the given cut.
```
def output_cut(S_partition):
"""Plot and output the graph cut information."""
# Generate the colors.
coloring = []
for node in working_graph:
if node in S_partition:
coloring.append('blue')
else:
coloring.append('red')
# Get the weights
edges = working_graph.edges(data=True)
weights = [w['weight'] for (u,v, w) in edges]
nx.draw_circular(
working_graph,
node_color=coloring,
node_size=1000,
with_labels=True,
width=weights)
plt.show()
size = nx.cut_size(working_graph, S_partition, weight='weight')
print(f'Cut size: {size}')
```
As an example, we can test this function with all nodes in the same set, for which the cut size should be zero.
```
# Test with the empty S and all nodes placed in T.
output_cut([])
```
To get cuts using the QAOA we will first need to extract the best control parameters found during the sweep:
```
best_exp_index = np.unravel_index(np.argmax(exp_values), exp_values.shape)
best_parameters = par_values[best_exp_index]
print(f'Best control parameters: {best_parameters}')
```
Each bitstring can be seen as a candidate cut in the graph. The qubits that measured 0 correspond to that qubit being in one cut partition and a qubit that measured to 1 corresponds to that qubit being in the other cut partition. Now that we've found good parameters for the `qaoa_circuit`, we can just sample some bistrings, iterate over them and pick the one that gives the best cut:
```
# Number of candidate cuts to sample.
num_cuts = 100
candidate_cuts = sim.sample(
qaoa_circuit,
params={alpha: best_parameters[0], beta: best_parameters[1]},
repetitions=num_cuts
)
# Variables to store best cut partitions and cut size.
best_qaoa_S_partition = set()
best_qaoa_T_partition = set()
best_qaoa_cut_size = -np.inf
# Analyze each candidate cut.
for i in range(num_cuts):
candidate = candidate_cuts.iloc[i]
one_qubits = set(candidate[candidate==1].index)
S_partition = set()
T_partition = set()
for node in working_graph:
if str(node) in one_qubits:
# If a one was measured add node to S partition.
S_partition.add(node)
else:
# Otherwise a zero was measured so add to T partition.
T_partition.add(node)
cut_size = nx.cut_size(
working_graph, S_partition, T_partition, weight='weight')
# If you found a better cut update best_qaoa_cut variables.
if cut_size > best_qaoa_cut_size:
best_qaoa_cut_size = cut_size
best_qaoa_S_partition = S_partition
best_qaoa_T_partition = T_partition
```
The QAOA is known to do just a little better than random guessing for Max-Cut on 3-regular graphs at `p=1`. You can use very similar logic to the code above, but now instead of relying on the QAOA to decide your `S_partition` and `T_partition` you can just pick then randomly:
```
import random
best_random_S_partition = set()
best_random_T_partition = set()
best_random_cut_size = -9999
# Randomly build candidate sets.
for i in range(num_cuts):
S_partition = set()
T_partition = set()
for node in working_graph:
if random.random() > 0.5:
# If we flip heads add to S.
S_partition.add(node)
else:
# Otherwise add to T.
T_partition.add(node)
cut_size = nx.cut_size(
working_graph, S_partition, T_partition, weight='weight')
# If you found a better cut update best_random_cut variables.
if cut_size > best_random_cut_size:
best_random_cut_size = cut_size
best_random_S_partition = S_partition
best_random_T_partition = T_partition
```
```
print('-----QAOA-----')
output_cut(best_qaoa_S_partition)
print('\n\n-----RANDOM-----')
output_cut(best_random_S_partition)
```
For this problem instance, one should see that $p = 1$ QAOA performs better, on average, than randomly guessing.
|
\name{KeeneSOC}
\alias{KeeneSOC}
\title{Sample trained caret model output for soil carbon}
|
f : {default 1 0 x : Nat} -> Nat
f = 0
|
import category_theory.monoidal.functor
open category_theory
variables {C D : Type*} [category C] [category D]
[monoidal_category C] [monoidal_category D]
namespace category_theory.monoidal_functor
variables (F : monoidal_functor C D)
lemma map_associator_hom
{X Y Z : C} : F.map (α_ X Y Z).hom =
inv (F.μ (X ⊗ Y) Z) ≫
inv (F.μ X Y ⊗ 𝟙 (F.obj Z)) ≫
(α_ (F.obj X) (F.obj Y) (F.obj Z)).hom ≫
(𝟙 (F.obj X) ⊗ F.μ Y Z) ≫
F.μ X (Y ⊗ Z) :=
begin
rw [is_iso.eq_inv_comp, is_iso.eq_inv_comp],
exact (F.to_lax_monoidal_functor.associativity X Y Z),
end
lemma map_associator_inv
{X Y Z : C} : F.map (α_ X Y Z).inv =
inv (F.μ X (Y ⊗ Z)) ≫
inv (𝟙 (F.obj X) ⊗ F.μ Y Z) ≫
(α_ (F.obj X) (F.obj Y) (F.obj Z)).inv ≫
(F.μ X Y ⊗ 𝟙 (F.obj Z)) ≫
(F.μ (X ⊗ Y) Z) :=
begin
rw [is_iso.eq_inv_comp, is_iso.eq_inv_comp],
exact (F.to_lax_monoidal_functor.associativity_inv X Y Z),
end
end category_theory.monoidal_functor
|
function handle = xyzhumanevaVisualise3d(pos,fid)
% XYZHUMANEVAVISUALISE3D
%
% COPYRIGHT : Carl Henrik Ek and Neil Lawrence, 2008
% MOCAP
if(nargin<2)
fid = 2;
end
figure(fid);
% determine parametrization
if(max(max(abs(pos)))<100)
type = 'jon';
else
type = 'raquel';
end
joint = xyzhumaneva2joint(pos);
figure(fid);
handle = xyzhumanevaDraw(joint);axis equal;view([1 1 1]);
switch type
case 'raquel'
set(gca,'XLim',[-300 300],'YLim',[-300 300],'ZLim',[-800 800]);
case 'jon'
set(gca,'XLim',[-0.35 0.35],'YLim',[-0.35 0.35],'ZLim',[-1 0.3]);
end
return
|
[GOAL]
K : Type u_1
inst✝¹ : LinearOrderedField K
inst✝ : FloorRing K
v : K
⊢ Stream'.IsSeq (IntFractPair.stream v)
[PROOFSTEP]
intro _ hyp
[GOAL]
K : Type u_1
inst✝¹ : LinearOrderedField K
inst✝ : FloorRing K
v : K
n✝ : ℕ
hyp : IntFractPair.stream v n✝ = none
⊢ IntFractPair.stream v (n✝ + 1) = none
[PROOFSTEP]
simp [IntFractPair.stream, hyp]
|
function uid = root(tree)
% XMLTREE/ROOT Root Method
% FORMAT uid = root(tree)
%
% tree - XMLTree object
% uid - UID of the root element of tree
%__________________________________________________________________________
%
% Return the uid of the root element of the tree.
%__________________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin
% $Id: root.m 4460 2011-09-05 14:52:16Z guillaume $
% Actually root is necessarily the element whos UID is 1, by
% construction. However, xml_parser should return a tree with a ROOT
% element with as many children as needed but only ONE *element* child
% who would be the real root (and this method should return the UID of
% this element).
uid = 1;
% Update:
% xml_parser has been modified (not as explained above) to handle the
% case when several nodes are at the top level of the XML.
% Example: <!-- beginning --><root>blah blah</root><!-- end -->
% Now root is the first element node of the tree.
% Look for the first element in the XML Tree
for i=1:length(tree)
if strcmp(get(tree,i,'type'),'element')
uid = i;
break
end
end
|
{-
Technical results about elementary transformations
-}
{-# OPTIONS --safe #-}
module Cubical.Algebra.Matrix.Elementaries where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Function
open import Cubical.Data.Nat hiding (_+_ ; _·_)
open import Cubical.Data.Nat.Order
open import Cubical.Data.Empty as Empty
open import Cubical.Data.Bool
open import Cubical.Data.FinData renaming (znots to znotsFin ; snotz to snotzFin)
open import Cubical.Relation.Nullary
open import Cubical.Algebra.RingSolver.Reflection
open import Cubical.Algebra.Ring.BigOps
open import Cubical.Algebra.CommRing
open import Cubical.Algebra.Matrix
open import Cubical.Algebra.Matrix.CommRingCoefficient
open import Cubical.Algebra.Matrix.RowTransformation
private
variable
ℓ : Level
A : Type ℓ
m n k l : ℕ
module ElemTransformation (𝓡 : CommRing ℓ) where
private
R = 𝓡 .fst
open CommRingStr (𝓡 .snd) renaming ( is-set to isSetR )
open KroneckerDelta (CommRing→Ring 𝓡)
open Sum (CommRing→Ring 𝓡)
open Coefficient 𝓡
open LinearTransformation 𝓡
open SimRel
open Sim
open isLinear
open isLinear2×2
-- Swapping the first row with another
swapMat : Mat 2 2
swapMat zero zero = 0r
swapMat zero one = 1r
swapMat one zero = 1r
swapMat one one = 0r
uniSwapMat : swapMat ⋆ swapMat ≡ 𝟙
uniSwapMat t zero zero =
(mul2 swapMat swapMat zero zero ∙ helper) t
where helper : 0r · 0r + 1r · 1r ≡ 1r
helper = solve 𝓡
uniSwapMat t zero one =
(mul2 swapMat swapMat zero one ∙ helper) t
where helper : 0r · 1r + 1r · 0r ≡ 0r
helper = solve 𝓡
uniSwapMat t one zero =
(mul2 swapMat swapMat one zero ∙ helper) t
where helper : 1r · 0r + 0r · 1r ≡ 0r
helper = solve 𝓡
uniSwapMat t one one =
(mul2 swapMat swapMat one one ∙ helper) t
where helper : 1r · 1r + 0r · 0r ≡ 1r
helper = solve 𝓡
isInvSwapMat2 : isInv swapMat
isInvSwapMat2 .fst = swapMat
isInvSwapMat2 .snd .fst = uniSwapMat
isInvSwapMat2 .snd .snd = uniSwapMat
swapRow2 : Mat 2 n → Mat 2 n
swapRow2 M zero = M one
swapRow2 M one = M zero
isLinear2×2SwapRow2 : isLinear2×2 {n = n} swapRow2
isLinear2×2SwapRow2 .transMat _ = swapMat
isLinear2×2SwapRow2 .transEq M t zero j =
((mul2 swapMat M zero j) ∙ helper _ _) (~ t)
where helper : (a b : R) → 0r · a + 1r · b ≡ b
helper = solve 𝓡
isLinear2×2SwapRow2 .transEq M t one j =
((mul2 swapMat M one j) ∙ helper _ _) (~ t)
where helper : (a b : R) → 1r · a + 0r · b ≡ a
helper = solve 𝓡
swapRow : (i₀ : Fin m)(M : Mat (suc m) n) → Mat (suc m) n
swapRow i M zero = M (suc i)
swapRow zero M one = M zero
swapRow zero M (suc (suc i)) = M (suc (suc i))
swapRow (suc i₀) M one = M one
swapRow (suc i₀) M (suc (suc i)) = swapRow i₀ (takeRowsᶜ M) (suc i)
swapRowMat : (i₀ : Fin m) → Mat (suc m) (suc m)
swapRowMat = trans2RowsMat swapMat
swapRowEq : (i₀ : Fin m)(M : Mat (suc m) n) → swapRow i₀ M ≡ swapRowMat i₀ ⋆ M
swapRowEq {m = suc m} zero M t zero j =
(helper1 _ _
∙ (λ t → 0r · M zero j + ∑Mulr1 _ (λ i → M (suc i) j) zero (~ t))
∙ (λ t → 0r · M zero j + ∑ (λ i → helper2 (δ i zero) (M (suc i) j) t))) t
where helper1 : (a b : R) → b ≡ 0r · a + b
helper1 = solve 𝓡
helper2 : (a b : R) → b · a ≡ (1r · a) · b
helper2 = solve 𝓡
swapRowEq {m = suc m} zero M t one j =
(helper _
∙ (λ t → (1r · 1r) · M zero j + ∑Mul0r (λ i → M (suc i) j) (~ t))) t
where helper : (a : R) → a ≡ (1r · 1r) · a + 0r
helper = solve 𝓡
swapRowEq {m = suc m} zero M t (suc (suc i)) j =
(helper _ _
∙ (λ t → (1r · 0r) · M zero j + ∑Mul1r _ (λ l → M (suc l) j) (suc i) (~ t))) t
where helper : (a b : R) → b ≡ (1r · 0r) · a + b
helper = solve 𝓡
swapRowEq {m = suc m} (suc i₀) M t zero j =
(helper1 _ _
∙ (λ t → 0r · M zero j + ∑Mul1r _ (λ i → M (suc i) j) (suc i₀) (~ t))
∙ (λ t → 0r · M zero j + ∑ (λ l → helper2 (δ (suc i₀) l) (M (suc l) j) t))) t
where helper1 : (a b : R) → b ≡ 0r · a + b
helper1 = solve 𝓡
helper2 : (a b : R) → a · b ≡ (1r · a) · b
helper2 = solve 𝓡
swapRowEq {m = suc m} (suc i₀) M t one j =
(helper _ _ --helper1 _ _
∙ (λ t → (1r · 0r) · M zero j + ∑Mul1r _ (λ i → M (suc i) j) zero (~ t))) t
where helper : (a b : R) → b ≡ (1r · 0r) · a + b
helper = solve 𝓡
swapRowEq {m = suc m} (suc i₀) M t (suc (suc i)) j =
((λ t → swapRowEq i₀ (takeRowsᶜ M) t (suc i) j)
∙ helper _ (M one j) _) t
where helper : (a b c : R) → a + c ≡ a + (0r · b + c)
helper = solve 𝓡
isLinearSwapRow : (i : Fin m) → isLinear (swapRow {n = n} i)
isLinearSwapRow i .transMat _ = swapRowMat i
isLinearSwapRow i .transEq = swapRowEq i
isInvSwapMat : (i : Fin m)(M : Mat (suc m) (suc n)) → isInv (isLinearSwapRow i .transMat M)
isInvSwapMat i _ = isInvTrans2RowsMat _ i isInvSwapMat2
-- Similarity defined by swapping
record SwapFirstRow (i : Fin m)(M : Mat (suc m) (suc n)) : Type ℓ where
field
sim : Sim M
swapEq : (j : Fin (suc n)) → M (suc i) j ≡ sim .result zero j
record SwapFirstCol (j : Fin n)(M : Mat (suc m) (suc n)) : Type ℓ where
field
sim : Sim M
swapEq : (i : Fin (suc m)) → M i (suc j) ≡ sim .result i zero
record SwapPivot (i : Fin (suc m))(j : Fin (suc n))(M : Mat (suc m) (suc n)) : Type ℓ where
field
sim : Sim M
swapEq : M i j ≡ sim .result zero zero
open SwapFirstRow
open SwapFirstCol
open SwapPivot
swapFirstRow : (i : Fin m)(M : Mat (suc m) (suc n)) → SwapFirstRow i M
swapFirstRow i M .sim .result = swapRow i M
swapFirstRow i M .sim .simrel .transMatL = isLinearSwapRow i .transMat M
swapFirstRow i M .sim .simrel .transMatR = 𝟙
swapFirstRow i M .sim .simrel .transEq = isLinearSwapRow i .transEq _ ∙ sym (⋆rUnit _)
swapFirstRow i M .sim .simrel .isInvTransL = isInvSwapMat i M
swapFirstRow i M .sim .simrel .isInvTransR = isInv𝟙
swapFirstRow i M .swapEq j = refl
swapFirstCol : (j : Fin n)(M : Mat (suc m) (suc n)) → SwapFirstCol j M
swapFirstCol j M .sim .result = (swapRow j (M ᵗ))ᵗ
swapFirstCol j M .sim .simrel .transMatL = 𝟙
swapFirstCol j M .sim .simrel .transMatR = (isLinearSwapRow j .transMat (M ᵗ))ᵗ
swapFirstCol j M .sim .simrel .transEq =
let P = isLinearSwapRow j .transMat (M ᵗ) in
(λ t → (isLinearSwapRow j .transEq (M ᵗ) t)ᵗ)
∙ compᵗ P (M ᵗ)
∙ (λ t → idemᵗ M t ⋆ P ᵗ)
∙ (λ t → ⋆lUnit M (~ t) ⋆ P ᵗ)
swapFirstCol j M .sim .simrel .isInvTransL = isInv𝟙
swapFirstCol j M .sim .simrel .isInvTransR =
isInvᵗ {M = isLinearSwapRow j .transMat (M ᵗ)} (isInvSwapMat j (M ᵗ))
swapFirstCol j M .swapEq i t = M i (suc j)
swapPivot : (i : Fin (suc m))(j : Fin (suc n))(M : Mat (suc m) (suc n)) → SwapPivot i j M
swapPivot zero zero M .sim = idSim M
swapPivot zero zero M .swapEq = refl
swapPivot (suc i) zero M .sim = swapFirstRow i M .sim
swapPivot (suc i) zero M .swapEq = refl
swapPivot zero (suc j) M .sim = swapFirstCol j M .sim
swapPivot zero (suc j) M .swapEq = refl
swapPivot (suc i) (suc j) M .sim = compSim (swapFirstRow i M .sim) (swapFirstCol j _ .sim)
swapPivot (suc i) (suc j) M .swapEq = refl
-- Add the first row to another
addMat : Mat 2 2
addMat zero zero = 1r
addMat zero one = 0r
addMat one zero = 1r
addMat one one = 1r
subMat : Mat 2 2
subMat zero zero = 1r
subMat zero one = 0r
subMat one zero = - 1r
subMat one one = 1r
add⋆subMat : addMat ⋆ subMat ≡ 𝟙
add⋆subMat t zero zero =
(mul2 addMat subMat zero zero ∙ helper) t
where helper : 1r · 1r + 0r · - 1r ≡ 1r
helper = solve 𝓡
add⋆subMat t zero one =
(mul2 addMat subMat zero one ∙ helper) t
where helper : 1r · 0r + 0r · 1r ≡ 0r
helper = solve 𝓡
add⋆subMat t one zero =
(mul2 addMat subMat one zero ∙ helper) t
where helper : 1r · 1r + 1r · - 1r ≡ 0r
helper = solve 𝓡
add⋆subMat t one one =
(mul2 addMat subMat one one ∙ helper) t
where helper : 1r · 0r + 1r · 1r ≡ 1r
helper = solve 𝓡
sub⋆addMat : subMat ⋆ addMat ≡ 𝟙
sub⋆addMat t zero zero =
(mul2 subMat addMat zero zero ∙ helper) t
where helper : 1r · 1r + 0r · 1r ≡ 1r
helper = solve 𝓡
sub⋆addMat t zero one =
(mul2 subMat addMat zero one ∙ helper) t
where helper : 1r · 0r + 0r · 1r ≡ 0r
helper = solve 𝓡
sub⋆addMat t one zero =
(mul2 subMat addMat one zero ∙ helper) t
where helper : - 1r · 1r + 1r · 1r ≡ 0r
helper = solve 𝓡
sub⋆addMat t one one =
(mul2 subMat addMat one one ∙ helper) t
where helper : - 1r · 0r + 1r · 1r ≡ 1r
helper = solve 𝓡
isInvAddMat2 : isInv addMat
isInvAddMat2 .fst = subMat
isInvAddMat2 .snd .fst = add⋆subMat
isInvAddMat2 .snd .snd = sub⋆addMat
addRow2 : Mat 2 n → Mat 2 n
addRow2 M zero = M zero
addRow2 M one j = M zero j + M one j
isLinear2AddRow2 : isLinear2×2 {n = n} addRow2
isLinear2AddRow2 .transMat _ = addMat
isLinear2AddRow2 .transEq M t zero j =
((mul2 addMat M zero j) ∙ helper _ _) (~ t)
where helper : (a b : R) → 1r · a + 0r · b ≡ a
helper = solve 𝓡
isLinear2AddRow2 .transEq M t one j =
((mul2 addMat M one j) ∙ helper _ _) (~ t)
where helper : (a b : R) → 1r · a + 1r · b ≡ a + b
helper = solve 𝓡
-- Add the first row to all other rows
addRows : Mat (suc m) n → Mat (suc m) n
addRows M zero = M zero
addRows M (suc i) j = M zero j + M (suc i) j
private
firstRowStayInvariant : (M : Mat (suc m) n) → M zero ≡ transRows addRow2 M zero
firstRowStayInvariant = invRow₀ _ (λ _ → refl)
addRowsEq : (M : Mat (suc m) n) → transRows addRow2 M ≡ addRows M
addRowsEq M t zero = firstRowStayInvariant M (~ t)
addRowsEq M t one j = M zero j + M one j
addRowsEq M t (suc (suc i)) j = takeCombShufRows addRow2 (λ N → addRowsEq N t) M (suc (suc i)) j
isLinearAddRows : isLinear (addRows {m = m} {n = suc n})
isLinearAddRows =
let isLinear = isLinearTransRows _ isLinear2AddRow2 _
in record
{ transMat = isLinear .transMat
; transEq = (λ M → sym (addRowsEq M) ∙ isLinear .transEq M) }
isInvAddRows : (M : Mat (suc m) (suc n)) → isInv (isLinearAddRows .transMat M)
isInvAddRows = isInvTransRows _ _ (λ _ → isInvAddMat2)
-- Similarity defined by adding rows
record AddFirstRow (M : Mat (suc m) (suc n)) : Type ℓ where
field
sim : Sim M
inv₀ : M zero ≡ sim .result zero
addEq : (i : Fin m)(j : Fin (suc n)) → M zero j + M (suc i) j ≡ sim .result (suc i) j
open AddFirstRow
addFirstRow : (M : Mat (suc m) (suc n)) → AddFirstRow M
addFirstRow M .sim .result = addRows M
addFirstRow M .sim .simrel .transMatL = isLinearAddRows .transMat M
addFirstRow M .sim .simrel .transMatR = 𝟙
addFirstRow M .sim .simrel .transEq = isLinearAddRows .transEq _ ∙ sym (⋆rUnit _)
addFirstRow M .sim .simrel .isInvTransL = isInvAddRows M
addFirstRow M .sim .simrel .isInvTransR = isInv𝟙
addFirstRow M .inv₀ = refl
addFirstRow M .addEq i j = refl
|
Do not compromise on style or comfort as the Eden caters for every member of your family as it offers 3 different sized recliners – standard, Large and XL for the taller members of your family. Match any of the recliners with a 2 & 3 seat sofa or 2 & 3 seat sofa with end seats moving independently for individual relaxation. The Eden standard recliner is available as a non rock recliner, reclinaway – the recliner reclines into the the room for those in smaller living spaces. See also the 2 seater entertainment love seat with centre console perfect for retirement homes. Offered in both fabric and leather. PowerRecliner XR and Power Recline XR+ now available on the Eden standard Recliner. |
{-# LANGUAGE ConstraintKinds #-}
module Quadrature
( getGaussPoints
, numGaussPoints
, integrate
, integrateFunc
) where
import qualified Numeric.LinearAlgebra.HMatrix as HMat
type FrElNuFi a = (Fractional a,HMat.Element a,HMat.Numeric a,HMat.Field a)
type FlElNuFi a = (Floating a,HMat.Element a,HMat.Numeric a,HMat.Field a)
-- Function for computing the required number of Gauss points for a polynomial
numGaussPoints :: Integral a => a -> a
numGaussPoints order = ceiling (0.5 * (fromIntegral order + 1.0))
-- Function for getting Gauss points for integration
-- Given the number of points it returns a list of the points and the weights
getGaussPoints :: Floating a => Int -> ([a], [a])
getGaussPoints 1 = ([0.0], [2.0])
getGaussPoints 2 = ([-1.0/sqrt 3.0, 1.0/sqrt 3.0], [1.0, 1.0])
getGaussPoints 3 = ([-sqrt (3.0/5.0), 0.0, sqrt (3.0/5.0)], [5.0/9.0, 8.0/9.0, 5.0/9.0])
getGaussPoints 4 = ([-0.861136311594053,-0.339981043584856,0.339981043584856,0.861136311594053],[0.347854845137454,0.652145154862546,0.652145154862546,0.347854845137454])
getGaussPoints _ = error "Gauss points only up to 4 point quadrature available."
-- Function for integrating some integrand over an element
-- Usage: integrate dim ngpts integrand
integrate :: FrElNuFi a => Int -> Int -> ([a] -> HMat.Matrix a) -> HMat.Matrix a
integrate 1 ngpts integrand = foldl1 HMat.add $ zipWith HMat.scale wts (map (\x -> integrand [x]) xi)
where
gpts = getGaussPoints ngpts
xi = fst gpts
wts = snd gpts
integrate _ _ _ = error "Integration only works in 1d for now."
-- Function for integrating a function from -1 to 1
integrateFunc :: Floating a => Int -> (a -> a) -> a
integrateFunc ngpts func = sum $ zipWith (*) wts (map func pts)
where
gpts = getGaussPoints ngpts
pts = fst gpts
wts = snd gpts
|
[STATEMENT]
lemma left_treeI [intro]: "\<lbrakk> u \<in> V; s \<in> set (u \<leadsto> t) \<rbrakk> \<Longrightarrow> u \<in> left_tree s t"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>u \<in> V; s \<in> set (u \<leadsto> t)\<rbrakk> \<Longrightarrow> u \<in> left_tree s t
[PROOF STEP]
unfolding left_tree_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>u \<in> V; s \<in> set (u \<leadsto> t)\<rbrakk> \<Longrightarrow> u \<in> {u \<in> V. s \<in> set (u \<leadsto> t)}
[PROOF STEP]
by blast |
lemma smallI: "(\<And>c. c > 0 \<Longrightarrow> eventually (\<lambda>x. R (norm (f x)) (c * (norm (g x)))) F) \<Longrightarrow> f \<in> l F (g)" |
module Schema
import SQLiteTypes
import Decidable.Equality
import Language.Reflection
%access public export
%default total
%auto_implicits on
infix 5 :::
data Attribute = (:::) String SQLiteType
%name Attribute attr,attr'
getName : Attribute -> String
getName (c:::_) = c
getTy : Attribute -> SQLiteType
getTy (_:::t) = t
attrEta : (attr : Attribute) -> (getName attr ::: getTy attr) = attr
attrEta (x ::: y) = Refl
attrInj : (c ::: t = c' ::: t') -> (c=c', t=t')
attrInj Refl = (Refl, Refl)
-- the first case forces it to get stuck if the constants are not in canonical form
foo : (x : String) -> (y : String) -> Dec (x = y)
foo "" "" = Yes Refl
foo x y with (decEq x y)
foo x y | Yes _ = Yes (really_believe_me (Refl {x}))
foo x y | No urgh = No urgh
implementation DecEq Attribute where
decEq (x ::: y) (z ::: w) with (foo x z, decEq y w)
decEq (x ::: y) (x ::: y) | (Yes Refl, Yes Refl) = Yes Refl
decEq (x ::: y) (x ::: w) | (Yes Refl, No prf) = No $ prf . snd . attrInj
decEq (x ::: y) (z ::: w) | (No prf, _) = No $ prf . fst . attrInj
data Schema = Nil | (::) Attribute Schema
%name Schema s,s'
append : (s1, s2 : Schema) -> Schema
append [] s2 = s2
append (attr :: s) s2 = attr :: (append s s2)
names : Schema -> List String
names [] = []
names ((n ::: _) :: s) = n :: names s
data HasCol : Schema -> Attribute -> Type where
Here : HasCol (attr::s) attr
There : HasCol s attr -> HasCol (attr'::s) attr
HasColNotEmpty : HasCol [] a -> Void
HasColNotEmpty Here impossible
HasColNotEmpty (There _) impossible
implementation Uninhabited (HasCol [] a) where
uninhabited x = HasColNotEmpty x
decHasColLemma : (HasCol s attr -> Void) ->
(attr' = attr -> Void) ->
HasCol (attr' :: s) attr -> Void
decHasColLemma h1 h2 Here = h2 Refl
decHasColLemma h1 h2 (There x) = h1 x
decHasCol : (s : Schema) -> (attr : Attribute) -> Dec (HasCol s attr)
decHasCol [] attr = No HasColNotEmpty
decHasCol (attr' :: s) attr with (decEq attr' attr)
decHasCol (attr' :: s) attr' | (Yes Refl) = Yes Here
decHasCol (attr' :: s) attr | (No f) with (decHasCol s attr)
decHasCol (attr' :: s) attr | (No f) | (Yes x) = Yes (There x)
decHasCol (attr' :: s) attr | (No f) | (No g) = No $ \h => decHasColLemma g f h
data SubSchema : Schema -> Schema -> Type where
Empty : SubSchema [] s
Head : (tailSub : SubSchema small large) ->
(alsoThere : HasCol large attr) ->
SubSchema (attr :: small) large
HasColNamed : Schema -> String -> Type
HasColNamed s col = (t : SQLiteType ** HasCol s (col ::: t))
decHasColNamed_lemma : ((HasColNamed s col) -> Void) -> ((col' = col) -> Void) ->
(t ** HasCol ((col' ::: ty) :: s) (col ::: t)) -> Void
decHasColNamed_lemma notThere notHere (ty ** Here) = notHere Refl
decHasColNamed_lemma notThere notHere (ty ** (There more)) = notThere (ty ** more)
decHasColNamed : (s : Schema) -> (col : String) -> Dec (HasColNamed s col)
decHasColNamed [] col = No $ \h => HasColNotEmpty (snd h)
decHasColNamed ((col' ::: ty) :: s) col with (decEq col' col)
decHasColNamed ((col ::: ty) :: s) col | (Yes Refl) = Yes (ty ** Here)
decHasColNamed ((col' ::: ty) :: s) col | (No f) with (decHasColNamed s col)
decHasColNamed ((col' ::: ty) :: s) col | (No f) | (Yes x) =
Yes (fst x ** There (snd x))
decHasColNamed ((col' ::: ty) :: s) col | (No f) | (No g) = No (decHasColNamed_lemma g f)
colNames : Schema -> List String
colNames [] = []
colNames ((col ::: _) :: s) = col :: colNames s
data Disjointness : Type where
Disjoint : Disjointness
Overlap : (attr : Attribute) -> Disjointness
isDisjoint : (s1, s2 : Schema) -> Disjointness
isDisjoint [] s2 = Disjoint
isDisjoint (attr :: s) s2 with (decHasColNamed s2 (getName attr))
isDisjoint (attr :: s) s2 | (Yes x) = Overlap attr
isDisjoint (attr :: s) s2 | (No f) = isDisjoint s s2
|
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
⊢ Perm.Disjoint (formPerm l) (formPerm l') ↔ Disjoint l l'
[PROOFSTEP]
rw [disjoint_iff_eq_or_eq, List.Disjoint]
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
⊢ (∀ (x : α), ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x) ↔ ∀ ⦃a : α⦄, a ∈ l → a ∈ l' → False
[PROOFSTEP]
constructor
[GOAL]
case mp
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
⊢ (∀ (x : α), ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x) → ∀ ⦃a : α⦄, a ∈ l → a ∈ l' → False
[PROOFSTEP]
rintro h x hx hx'
[GOAL]
case mp
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
h : ∀ (x : α), ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x
x : α
hx : x ∈ l
hx' : x ∈ l'
⊢ False
[PROOFSTEP]
specialize h x
[GOAL]
case mp
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
x : α
hx : x ∈ l
hx' : x ∈ l'
h : ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x
⊢ False
[PROOFSTEP]
rw [formPerm_apply_mem_eq_self_iff _ hl _ hx, formPerm_apply_mem_eq_self_iff _ hl' _ hx'] at h
[GOAL]
case mp
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
x : α
hx : x ∈ l
hx' : x ∈ l'
h : length l ≤ 1 ∨ length l' ≤ 1
⊢ False
[PROOFSTEP]
rcases h with (hl | hl')
[GOAL]
case mp.inl
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl✝ : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
x : α
hx : x ∈ l
hx' : x ∈ l'
hl : length l ≤ 1
⊢ False
[PROOFSTEP]
linarith
[GOAL]
case mp.inr
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl'✝ : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
x : α
hx : x ∈ l
hx' : x ∈ l'
hl' : length l' ≤ 1
⊢ False
[PROOFSTEP]
linarith
[GOAL]
case mpr
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
⊢ (∀ ⦃a : α⦄, a ∈ l → a ∈ l' → False) → ∀ (x : α), ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x
[PROOFSTEP]
intro h x
[GOAL]
case mpr
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
h : ∀ ⦃a : α⦄, a ∈ l → a ∈ l' → False
x : α
⊢ ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x
[PROOFSTEP]
by_cases hx : x ∈ l
[GOAL]
case pos
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
h : ∀ ⦃a : α⦄, a ∈ l → a ∈ l' → False
x : α
hx : x ∈ l
⊢ ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x
case neg
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
h : ∀ ⦃a : α⦄, a ∈ l → a ∈ l' → False
x : α
hx : ¬x ∈ l
⊢ ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x
[PROOFSTEP]
by_cases hx' : x ∈ l'
[GOAL]
case pos
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
h : ∀ ⦃a : α⦄, a ∈ l → a ∈ l' → False
x : α
hx : x ∈ l
hx' : x ∈ l'
⊢ ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x
[PROOFSTEP]
exact (h hx hx').elim
[GOAL]
case neg
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
h : ∀ ⦃a : α⦄, a ∈ l → a ∈ l' → False
x : α
hx : x ∈ l
hx' : ¬x ∈ l'
⊢ ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x
case neg
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
h : ∀ ⦃a : α⦄, a ∈ l → a ∈ l' → False
x : α
hx : ¬x ∈ l
⊢ ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x
[PROOFSTEP]
all_goals have := formPerm_eq_self_of_not_mem _ _ ‹_›; tauto
[GOAL]
case neg
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
h : ∀ ⦃a : α⦄, a ∈ l → a ∈ l' → False
x : α
hx : x ∈ l
hx' : ¬x ∈ l'
⊢ ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x
[PROOFSTEP]
have := formPerm_eq_self_of_not_mem _ _ ‹_›
[GOAL]
case neg
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
h : ∀ ⦃a : α⦄, a ∈ l → a ∈ l' → False
x : α
hx : x ∈ l
hx' : ¬x ∈ l'
this : ↑(formPerm l') x = x
⊢ ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x
[PROOFSTEP]
tauto
[GOAL]
case neg
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
h : ∀ ⦃a : α⦄, a ∈ l → a ∈ l' → False
x : α
hx : ¬x ∈ l
⊢ ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x
[PROOFSTEP]
have := formPerm_eq_self_of_not_mem _ _ ‹_›
[GOAL]
case neg
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hl' : Nodup l'
hn : 2 ≤ length l
hn' : 2 ≤ length l'
h : ∀ ⦃a : α⦄, a ∈ l → a ∈ l' → False
x : α
hx : ¬x ∈ l
this : ↑(formPerm l) x = x
⊢ ↑(formPerm l) x = x ∨ ↑(formPerm l') x = x
[PROOFSTEP]
tauto
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hn : 2 ≤ length l
⊢ IsCycle (formPerm l)
[PROOFSTEP]
cases' l with x l
[GOAL]
case nil
α : Type u_1
inst✝ : DecidableEq α
l' : List α
hl : Nodup []
hn : 2 ≤ length []
⊢ IsCycle (formPerm [])
[PROOFSTEP]
norm_num at hn
[GOAL]
case cons
α : Type u_1
inst✝ : DecidableEq α
l' : List α
x : α
l : List α
hl : Nodup (x :: l)
hn : 2 ≤ length (x :: l)
⊢ IsCycle (formPerm (x :: l))
[PROOFSTEP]
induction' l with y l generalizing x
[GOAL]
case cons.nil
α : Type u_1
inst✝ : DecidableEq α
l' : List α
x✝ : α
l : List α
hl✝ : Nodup (x✝ :: l)
hn✝ : 2 ≤ length (x✝ :: l)
x : α
hl : Nodup [x]
hn : 2 ≤ length [x]
⊢ IsCycle (formPerm [x])
[PROOFSTEP]
norm_num at hn
[GOAL]
case cons.cons
α : Type u_1
inst✝ : DecidableEq α
l' : List α
x✝ : α
l✝ : List α
hl✝ : Nodup (x✝ :: l✝)
hn✝ : 2 ≤ length (x✝ :: l✝)
y : α
l : List α
tail_ih✝ : ∀ (x : α), Nodup (x :: l) → 2 ≤ length (x :: l) → IsCycle (formPerm (x :: l))
x : α
hl : Nodup (x :: y :: l)
hn : 2 ≤ length (x :: y :: l)
⊢ IsCycle (formPerm (x :: y :: l))
[PROOFSTEP]
use x
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
l' : List α
x✝ : α
l✝ : List α
hl✝ : Nodup (x✝ :: l✝)
hn✝ : 2 ≤ length (x✝ :: l✝)
y : α
l : List α
tail_ih✝ : ∀ (x : α), Nodup (x :: l) → 2 ≤ length (x :: l) → IsCycle (formPerm (x :: l))
x : α
hl : Nodup (x :: y :: l)
hn : 2 ≤ length (x :: y :: l)
⊢ ↑(formPerm (x :: y :: l)) x ≠ x ∧
∀ ⦃y_1 : α⦄, ↑(formPerm (x :: y :: l)) y_1 ≠ y_1 → SameCycle (formPerm (x :: y :: l)) x y_1
[PROOFSTEP]
constructor
[GOAL]
case h.left
α : Type u_1
inst✝ : DecidableEq α
l' : List α
x✝ : α
l✝ : List α
hl✝ : Nodup (x✝ :: l✝)
hn✝ : 2 ≤ length (x✝ :: l✝)
y : α
l : List α
tail_ih✝ : ∀ (x : α), Nodup (x :: l) → 2 ≤ length (x :: l) → IsCycle (formPerm (x :: l))
x : α
hl : Nodup (x :: y :: l)
hn : 2 ≤ length (x :: y :: l)
⊢ ↑(formPerm (x :: y :: l)) x ≠ x
[PROOFSTEP]
rwa [formPerm_apply_mem_ne_self_iff _ hl _ (mem_cons_self _ _)]
[GOAL]
case h.right
α : Type u_1
inst✝ : DecidableEq α
l' : List α
x✝ : α
l✝ : List α
hl✝ : Nodup (x✝ :: l✝)
hn✝ : 2 ≤ length (x✝ :: l✝)
y : α
l : List α
tail_ih✝ : ∀ (x : α), Nodup (x :: l) → 2 ≤ length (x :: l) → IsCycle (formPerm (x :: l))
x : α
hl : Nodup (x :: y :: l)
hn : 2 ≤ length (x :: y :: l)
⊢ ∀ ⦃y_1 : α⦄, ↑(formPerm (x :: y :: l)) y_1 ≠ y_1 → SameCycle (formPerm (x :: y :: l)) x y_1
[PROOFSTEP]
intro w hw
[GOAL]
case h.right
α : Type u_1
inst✝ : DecidableEq α
l' : List α
x✝ : α
l✝ : List α
hl✝ : Nodup (x✝ :: l✝)
hn✝ : 2 ≤ length (x✝ :: l✝)
y : α
l : List α
tail_ih✝ : ∀ (x : α), Nodup (x :: l) → 2 ≤ length (x :: l) → IsCycle (formPerm (x :: l))
x : α
hl : Nodup (x :: y :: l)
hn : 2 ≤ length (x :: y :: l)
w : α
hw : ↑(formPerm (x :: y :: l)) w ≠ w
⊢ SameCycle (formPerm (x :: y :: l)) x w
[PROOFSTEP]
have : w ∈ x :: y :: l := mem_of_formPerm_ne_self _ _ hw
[GOAL]
case h.right
α : Type u_1
inst✝ : DecidableEq α
l' : List α
x✝ : α
l✝ : List α
hl✝ : Nodup (x✝ :: l✝)
hn✝ : 2 ≤ length (x✝ :: l✝)
y : α
l : List α
tail_ih✝ : ∀ (x : α), Nodup (x :: l) → 2 ≤ length (x :: l) → IsCycle (formPerm (x :: l))
x : α
hl : Nodup (x :: y :: l)
hn : 2 ≤ length (x :: y :: l)
w : α
hw : ↑(formPerm (x :: y :: l)) w ≠ w
this : w ∈ x :: y :: l
⊢ SameCycle (formPerm (x :: y :: l)) x w
[PROOFSTEP]
obtain ⟨k, hk, rfl⟩ := nthLe_of_mem this
[GOAL]
case h.right.intro.intro
α : Type u_1
inst✝ : DecidableEq α
l' : List α
x✝ : α
l✝ : List α
hl✝ : Nodup (x✝ :: l✝)
hn✝ : 2 ≤ length (x✝ :: l✝)
y : α
l : List α
tail_ih✝ : ∀ (x : α), Nodup (x :: l) → 2 ≤ length (x :: l) → IsCycle (formPerm (x :: l))
x : α
hl : Nodup (x :: y :: l)
hn : 2 ≤ length (x :: y :: l)
k : ℕ
hk : k < length (x :: y :: l)
hw : ↑(formPerm (x :: y :: l)) (nthLe (x :: y :: l) k hk) ≠ nthLe (x :: y :: l) k hk
this : nthLe (x :: y :: l) k hk ∈ x :: y :: l
⊢ SameCycle (formPerm (x :: y :: l)) x (nthLe (x :: y :: l) k hk)
[PROOFSTEP]
use k
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
l' : List α
x✝ : α
l✝ : List α
hl✝ : Nodup (x✝ :: l✝)
hn✝ : 2 ≤ length (x✝ :: l✝)
y : α
l : List α
tail_ih✝ : ∀ (x : α), Nodup (x :: l) → 2 ≤ length (x :: l) → IsCycle (formPerm (x :: l))
x : α
hl : Nodup (x :: y :: l)
hn : 2 ≤ length (x :: y :: l)
k : ℕ
hk : k < length (x :: y :: l)
hw : ↑(formPerm (x :: y :: l)) (nthLe (x :: y :: l) k hk) ≠ nthLe (x :: y :: l) k hk
this : nthLe (x :: y :: l) k hk ∈ x :: y :: l
⊢ ↑(formPerm (x :: y :: l) ^ ↑k) x = nthLe (x :: y :: l) k hk
[PROOFSTEP]
simp only [zpow_ofNat, formPerm_pow_apply_head _ _ hl k, Nat.mod_eq_of_lt hk]
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hn : 2 ≤ length l
x : { x // x ∈ l }
⊢ 2 ≤ length (attach l)
[PROOFSTEP]
rwa [← length_attach] at hn
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hn✝ : 2 ≤ length l
x : { x // x ∈ l }
hn : 2 ≤ length (attach l)
⊢ Nodup (attach l)
[PROOFSTEP]
rwa [← nodup_attach] at hl
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hn : 2 ≤ length l
⊢ cycleType (formPerm (attach l)) = {length l}
[PROOFSTEP]
rw [← length_attach] at hn
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
hn : 2 ≤ length (attach l)
⊢ cycleType (formPerm (attach l)) = {length l}
[PROOFSTEP]
rw [← nodup_attach] at hl
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup (attach l)
hn : 2 ≤ length (attach l)
⊢ cycleType (formPerm (attach l)) = {length l}
[PROOFSTEP]
rw [cycleType_eq [l.attach.formPerm]]
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup (attach l)
hn : 2 ≤ length (attach l)
⊢ ↑(map (Finset.card ∘ support) [formPerm (attach l)]) = {length l}
[PROOFSTEP]
simp only [map, Function.comp_apply]
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup (attach l)
hn : 2 ≤ length (attach l)
⊢ ↑[Finset.card (support (formPerm (attach l)))] = {length l}
[PROOFSTEP]
rw [support_formPerm_of_nodup _ hl, card_toFinset, dedup_eq_self.mpr hl]
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup (attach l)
hn : 2 ≤ length (attach l)
⊢ ↑[length (attach l)] = {length l}
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup (attach l)
hn : 2 ≤ length (attach l)
⊢ ∀ (x : { x // x ∈ l }), attach l ≠ [x]
[PROOFSTEP]
intro x h
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup (attach l)
hn : 2 ≤ length (attach l)
x : { x // x ∈ l }
h : attach l = [x]
⊢ False
[PROOFSTEP]
simp [h, Nat.succ_le_succ_iff] at hn
[GOAL]
case h0
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup (attach l)
hn : 2 ≤ length (attach l)
⊢ prod [formPerm (attach l)] = formPerm (attach l)
[PROOFSTEP]
simp
[GOAL]
case h1
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup (attach l)
hn : 2 ≤ length (attach l)
⊢ ∀ (σ : Equiv.Perm { x // x ∈ l }), σ ∈ [formPerm (attach l)] → IsCycle σ
[PROOFSTEP]
simpa using isCycle_formPerm hl hn
[GOAL]
case h2
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup (attach l)
hn : 2 ≤ length (attach l)
⊢ Pairwise Perm.Disjoint [formPerm (attach l)]
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
x : α
hx : x ∈ l
⊢ ↑(formPerm l) x = next l x hx
[PROOFSTEP]
obtain ⟨k, hk, rfl⟩ := nthLe_of_mem hx
[GOAL]
case intro.intro
α : Type u_1
inst✝ : DecidableEq α
l l' : List α
hl : Nodup l
k : ℕ
hk : k < length l
hx : nthLe l k hk ∈ l
⊢ ↑(formPerm l) (nthLe l k hk) = next l (nthLe l k hk) hx
[PROOFSTEP]
rw [next_nthLe _ hl, formPerm_apply_nthLe _ hl]
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
l₁ l₂ : List α
h : l₁ ~r l₂
⊢ HEq (fun x => List.formPerm l₁) fun x => List.formPerm l₂
[PROOFSTEP]
apply Function.hfunext
[GOAL]
case hα
α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
l₁ l₂ : List α
h : l₁ ~r l₂
⊢ Nodup (Quotient.mk (IsRotated.setoid α) l₁) = Nodup (Quotient.mk (IsRotated.setoid α) l₂)
case h
α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
l₁ l₂ : List α
h : l₁ ~r l₂
⊢ ∀ (a : Nodup (Quotient.mk (IsRotated.setoid α) l₁)) (a' : Nodup (Quotient.mk (IsRotated.setoid α) l₂)),
HEq a a' → HEq (List.formPerm l₁) (List.formPerm l₂)
[PROOFSTEP]
ext
[GOAL]
case hα.a
α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
l₁ l₂ : List α
h : l₁ ~r l₂
⊢ Nodup (Quotient.mk (IsRotated.setoid α) l₁) ↔ Nodup (Quotient.mk (IsRotated.setoid α) l₂)
[PROOFSTEP]
exact h.nodup_iff
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
l₁ l₂ : List α
h : l₁ ~r l₂
⊢ ∀ (a : Nodup (Quotient.mk (IsRotated.setoid α) l₁)) (a' : Nodup (Quotient.mk (IsRotated.setoid α) l₂)),
HEq a a' → HEq (List.formPerm l₁) (List.formPerm l₂)
[PROOFSTEP]
intro h₁ h₂ _
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
l₁ l₂ : List α
h : l₁ ~r l₂
h₁ : Nodup (Quotient.mk (IsRotated.setoid α) l₁)
h₂ : Nodup (Quotient.mk (IsRotated.setoid α) l₂)
a✝ : HEq h₁ h₂
⊢ HEq (List.formPerm l₁) (List.formPerm l₂)
[PROOFSTEP]
exact heq_of_eq (formPerm_eq_of_isRotated h₁ h)
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
h : Subsingleton s
⊢ formPerm s (_ : Nodup s) = 1
[PROOFSTEP]
induction' s using Quot.inductionOn with s
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
s✝¹ s' s✝ : Cycle α
h✝ : Subsingleton s✝
s : List α
h : Subsingleton (Quot.mk Setoid.r s)
⊢ formPerm (Quot.mk Setoid.r s) (_ : Nodup (Quot.mk Setoid.r s)) = 1
[PROOFSTEP]
simp only [formPerm_coe, mk_eq_coe]
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
s✝¹ s' s✝ : Cycle α
h✝ : Subsingleton s✝
s : List α
h : Subsingleton (Quot.mk Setoid.r s)
⊢ List.formPerm s = 1
[PROOFSTEP]
simp only [length_subsingleton_iff, length_coe, mk_eq_coe] at h
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
s✝¹ s' s✝ : Cycle α
h✝ : Subsingleton s✝
s : List α
h : List.length s ≤ 1
⊢ List.formPerm s = 1
[PROOFSTEP]
cases' s with hd tl
[GOAL]
case h.nil
α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
h✝ : Subsingleton s
h : List.length [] ≤ 1
⊢ List.formPerm [] = 1
[PROOFSTEP]
simp
[GOAL]
case h.cons
α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
h✝ : Subsingleton s
hd : α
tl : List α
h : List.length (hd :: tl) ≤ 1
⊢ List.formPerm (hd :: tl) = 1
[PROOFSTEP]
simp only [length_eq_zero, add_le_iff_nonpos_left, List.length, nonpos_iff_eq_zero] at h
[GOAL]
case h.cons
α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
h✝ : Subsingleton s
hd : α
tl : List α
h : tl = []
⊢ List.formPerm (hd :: tl) = 1
[PROOFSTEP]
simp [h]
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
h : Nodup s
hn : Nontrivial s
⊢ IsCycle (formPerm s h)
[PROOFSTEP]
induction s using Quot.inductionOn
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
s s' : Cycle α
a✝ : List α
h : Nodup (Quot.mk Setoid.r a✝)
hn : Nontrivial (Quot.mk Setoid.r a✝)
⊢ IsCycle (formPerm (Quot.mk Setoid.r a✝) h)
[PROOFSTEP]
exact List.isCycle_formPerm h (length_nontrivial hn)
[GOAL]
α : Type u_1
inst✝¹ : DecidableEq α
s✝ s' : Cycle α
inst✝ : Fintype α
s : Cycle α
h : Nodup s
hn : Nontrivial s
⊢ support (formPerm s h) = toFinset s
[PROOFSTEP]
induction' s using Quot.inductionOn with s
[GOAL]
case h
α : Type u_1
inst✝¹ : DecidableEq α
s✝¹ s' : Cycle α
inst✝ : Fintype α
s✝ : Cycle α
h✝ : Nodup s✝
hn✝ : Nontrivial s✝
s : List α
h : Nodup (Quot.mk Setoid.r s)
hn : Nontrivial (Quot.mk Setoid.r s)
⊢ support (formPerm (Quot.mk Setoid.r s) h) = toFinset (Quot.mk Setoid.r s)
[PROOFSTEP]
refine' support_formPerm_of_nodup s h _
[GOAL]
case h
α : Type u_1
inst✝¹ : DecidableEq α
s✝¹ s' : Cycle α
inst✝ : Fintype α
s✝ : Cycle α
h✝ : Nodup s✝
hn✝ : Nontrivial s✝
s : List α
h : Nodup (Quot.mk Setoid.r s)
hn : Nontrivial (Quot.mk Setoid.r s)
⊢ ∀ (x : α), s ≠ [x]
[PROOFSTEP]
rintro _ rfl
[GOAL]
case h
α : Type u_1
inst✝¹ : DecidableEq α
s✝ s' : Cycle α
inst✝ : Fintype α
s : Cycle α
h✝ : Nodup s
hn✝ : Nontrivial s
x✝ : α
h : Nodup (Quot.mk Setoid.r [x✝])
hn : Nontrivial (Quot.mk Setoid.r [x✝])
⊢ False
[PROOFSTEP]
simpa [Nat.succ_le_succ_iff] using length_nontrivial hn
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
h : Nodup s
x : α
hx : ¬x ∈ s
⊢ ↑(formPerm s h) x = x
[PROOFSTEP]
induction s using Quot.inductionOn
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
s s' : Cycle α
x : α
a✝ : List α
h : Nodup (Quot.mk Setoid.r a✝)
hx : ¬x ∈ Quot.mk Setoid.r a✝
⊢ ↑(formPerm (Quot.mk Setoid.r a✝) h) x = x
[PROOFSTEP]
simpa using List.formPerm_eq_self_of_not_mem _ _ hx
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
h : Nodup s
x : α
hx : x ∈ s
⊢ ↑(formPerm s h) x = next s h x hx
[PROOFSTEP]
induction s using Quot.inductionOn
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
s s' : Cycle α
x : α
a✝ : List α
h : Nodup (Quot.mk Setoid.r a✝)
hx : x ∈ Quot.mk Setoid.r a✝
⊢ ↑(formPerm (Quot.mk Setoid.r a✝) h) x = next (Quot.mk Setoid.r a✝) h x hx
[PROOFSTEP]
simpa using List.formPerm_apply_mem_eq_next h _ (by simp_all)
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s s' : Cycle α
x : α
a✝ : List α
h : Nodup (Quot.mk Setoid.r a✝)
hx : x ∈ Quot.mk Setoid.r a✝
⊢ x ∈ a✝
[PROOFSTEP]
simp_all
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ s' s : Cycle α
h : Nodup s
⊢ formPerm (reverse s) (_ : Nodup (reverse s)) = (formPerm s h)⁻¹
[PROOFSTEP]
induction s using Quot.inductionOn
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
s s' : Cycle α
a✝ : List α
h : Nodup (Quot.mk Setoid.r a✝)
⊢ formPerm (reverse (Quot.mk Setoid.r a✝)) (_ : Nodup (reverse (Quot.mk Setoid.r a✝))) =
(formPerm (Quot.mk Setoid.r a✝) h)⁻¹
[PROOFSTEP]
simpa using formPerm_reverse _ h
[GOAL]
α✝ : Type u_1
inst✝¹ : DecidableEq α✝
s✝ s'✝ : Cycle α✝
α : Type u_2
inst✝ : DecidableEq α
s s' : Cycle α
hs : Nodup s
hs' : Nodup s'
⊢ formPerm s hs = formPerm s' hs' ↔ s = s' ∨ Subsingleton s ∧ Subsingleton s'
[PROOFSTEP]
rw [Cycle.length_subsingleton_iff, Cycle.length_subsingleton_iff]
[GOAL]
α✝ : Type u_1
inst✝¹ : DecidableEq α✝
s✝ s'✝ : Cycle α✝
α : Type u_2
inst✝ : DecidableEq α
s s' : Cycle α
hs : Nodup s
hs' : Nodup s'
⊢ formPerm s hs = formPerm s' hs' ↔ s = s' ∨ length s ≤ 1 ∧ length s' ≤ 1
[PROOFSTEP]
revert s s'
[GOAL]
α✝ : Type u_1
inst✝¹ : DecidableEq α✝
s s' : Cycle α✝
α : Type u_2
inst✝ : DecidableEq α
⊢ ∀ {s s' : Cycle α} {hs : Nodup s} {hs' : Nodup s'},
formPerm s hs = formPerm s' hs' ↔ s = s' ∨ length s ≤ 1 ∧ length s' ≤ 1
[PROOFSTEP]
intro s s'
[GOAL]
α✝ : Type u_1
inst✝¹ : DecidableEq α✝
s✝ s'✝ : Cycle α✝
α : Type u_2
inst✝ : DecidableEq α
s s' : Cycle α
⊢ ∀ {hs : Nodup s} {hs' : Nodup s'}, formPerm s hs = formPerm s' hs' ↔ s = s' ∨ length s ≤ 1 ∧ length s' ≤ 1
[PROOFSTEP]
apply @Quotient.inductionOn₂' _ _ _ _ _ s s'
[GOAL]
α✝ : Type u_1
inst✝¹ : DecidableEq α✝
s✝ s'✝ : Cycle α✝
α : Type u_2
inst✝ : DecidableEq α
s s' : Cycle α
⊢ ∀ (a₁ a₂ : List α) {hs : Nodup (Quotient.mk'' a₁)} {hs' : Nodup (Quotient.mk'' a₂)},
formPerm (Quotient.mk'' a₁) hs = formPerm (Quotient.mk'' a₂) hs' ↔
Quotient.mk'' a₁ = Quotient.mk'' a₂ ∨ length (Quotient.mk'' a₁) ≤ 1 ∧ length (Quotient.mk'' a₂) ≤ 1
[PROOFSTEP]
intro l l'
[GOAL]
α✝ : Type u_1
inst✝¹ : DecidableEq α✝
s✝ s'✝ : Cycle α✝
α : Type u_2
inst✝ : DecidableEq α
s s' : Cycle α
l l' : List α
⊢ ∀ {hs : Nodup (Quotient.mk'' l)} {hs' : Nodup (Quotient.mk'' l')},
formPerm (Quotient.mk'' l) hs = formPerm (Quotient.mk'' l') hs' ↔
Quotient.mk'' l = Quotient.mk'' l' ∨ length (Quotient.mk'' l) ≤ 1 ∧ length (Quotient.mk'' l') ≤ 1
[PROOFSTEP]
simp_all
[GOAL]
α✝ : Type u_1
inst✝¹ : DecidableEq α✝
s✝ s'✝ : Cycle α✝
α : Type u_2
inst✝ : DecidableEq α
s s' : Cycle α
l l' : List α
⊢ ∀ {hs : List.Nodup l} {hs' : List.Nodup l'},
List.formPerm l = List.formPerm l' ↔ l ~r l' ∨ List.length l ≤ 1 ∧ List.length l' ≤ 1
[PROOFSTEP]
intro hs hs'
[GOAL]
α✝ : Type u_1
inst✝¹ : DecidableEq α✝
s✝ s'✝ : Cycle α✝
α : Type u_2
inst✝ : DecidableEq α
s s' : Cycle α
l l' : List α
hs : List.Nodup l
hs' : List.Nodup l'
⊢ List.formPerm l = List.formPerm l' ↔ l ~r l' ∨ List.length l ≤ 1 ∧ List.length l' ≤ 1
[PROOFSTEP]
constructor
[GOAL]
case mp
α✝ : Type u_1
inst✝¹ : DecidableEq α✝
s✝ s'✝ : Cycle α✝
α : Type u_2
inst✝ : DecidableEq α
s s' : Cycle α
l l' : List α
hs : List.Nodup l
hs' : List.Nodup l'
⊢ List.formPerm l = List.formPerm l' → l ~r l' ∨ List.length l ≤ 1 ∧ List.length l' ≤ 1
[PROOFSTEP]
intro h
[GOAL]
case mpr
α✝ : Type u_1
inst✝¹ : DecidableEq α✝
s✝ s'✝ : Cycle α✝
α : Type u_2
inst✝ : DecidableEq α
s s' : Cycle α
l l' : List α
hs : List.Nodup l
hs' : List.Nodup l'
⊢ l ~r l' ∨ List.length l ≤ 1 ∧ List.length l' ≤ 1 → List.formPerm l = List.formPerm l'
[PROOFSTEP]
intro h
[GOAL]
case mp
α✝ : Type u_1
inst✝¹ : DecidableEq α✝
s✝ s'✝ : Cycle α✝
α : Type u_2
inst✝ : DecidableEq α
s s' : Cycle α
l l' : List α
hs : List.Nodup l
hs' : List.Nodup l'
h : List.formPerm l = List.formPerm l'
⊢ l ~r l' ∨ List.length l ≤ 1 ∧ List.length l' ≤ 1
[PROOFSTEP]
simp_all only [formPerm_eq_formPerm_iff]
[GOAL]
case mpr
α✝ : Type u_1
inst✝¹ : DecidableEq α✝
s✝ s'✝ : Cycle α✝
α : Type u_2
inst✝ : DecidableEq α
s s' : Cycle α
l l' : List α
hs : List.Nodup l
hs' : List.Nodup l'
h : l ~r l' ∨ List.length l ≤ 1 ∧ List.length l' ≤ 1
⊢ List.formPerm l = List.formPerm l'
[PROOFSTEP]
simp_all only [formPerm_eq_formPerm_iff]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
⊢ toList 1 x = []
[PROOFSTEP]
simp [toList, cycleOf_one]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
⊢ toList p x = [] ↔ ¬x ∈ support p
[PROOFSTEP]
simp [toList]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
⊢ length (toList p x) = Finset.card (support (cycleOf p x))
[PROOFSTEP]
simp [toList]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x y : α
⊢ toList p x ≠ [y]
[PROOFSTEP]
intro H
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x y : α
H : toList p x = [y]
⊢ False
[PROOFSTEP]
simpa [card_support_ne_one] using congr_arg length H
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
⊢ 2 ≤ length (toList p x) ↔ x ∈ support p
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
n : ℕ
hn : n < length (toList p x)
⊢ nthLe (toList p x) n hn = ↑(p ^ n) x
[PROOFSTEP]
simp [toList]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
h : x ∈ support p
⊢ nthLe (toList p x) 0 (_ : 0 < length (toList p x)) = x
[PROOFSTEP]
simp [toList]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x y : α
⊢ y ∈ toList p x ↔ SameCycle p x y ∧ x ∈ support p
[PROOFSTEP]
simp only [toList, mem_range, mem_map]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x y : α
⊢ (∃ a, a < Finset.card (support (cycleOf p x)) ∧ ↑(p ^ a) x = y) ↔ SameCycle p x y ∧ x ∈ support p
[PROOFSTEP]
constructor
[GOAL]
case mp
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x y : α
⊢ (∃ a, a < Finset.card (support (cycleOf p x)) ∧ ↑(p ^ a) x = y) → SameCycle p x y ∧ x ∈ support p
[PROOFSTEP]
rintro ⟨n, hx, rfl⟩
[GOAL]
case mp.intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
n : ℕ
hx : n < Finset.card (support (cycleOf p x))
⊢ SameCycle p x (↑(p ^ n) x) ∧ x ∈ support p
[PROOFSTEP]
refine' ⟨⟨n, rfl⟩, _⟩
[GOAL]
case mp.intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
n : ℕ
hx : n < Finset.card (support (cycleOf p x))
⊢ x ∈ support p
[PROOFSTEP]
contrapose! hx
[GOAL]
case mp.intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
n : ℕ
hx : ¬x ∈ support p
⊢ Finset.card (support (cycleOf p x)) ≤ n
[PROOFSTEP]
rw [← support_cycleOf_eq_nil_iff] at hx
[GOAL]
case mp.intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
n : ℕ
hx : support (cycleOf p x) = ∅
⊢ Finset.card (support (cycleOf p x)) ≤ n
[PROOFSTEP]
simp [hx]
[GOAL]
case mpr
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x y : α
⊢ SameCycle p x y ∧ x ∈ support p → ∃ a, a < Finset.card (support (cycleOf p x)) ∧ ↑(p ^ a) x = y
[PROOFSTEP]
rintro ⟨h, hx⟩
[GOAL]
case mpr.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x y : α
h : SameCycle p x y
hx : x ∈ support p
⊢ ∃ a, a < Finset.card (support (cycleOf p x)) ∧ ↑(p ^ a) x = y
[PROOFSTEP]
simpa using h.exists_pow_eq_of_mem_support hx
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
⊢ Nodup (toList p x)
[PROOFSTEP]
by_cases hx : p x = x
[GOAL]
case pos
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx : ↑p x = x
⊢ Nodup (toList p x)
[PROOFSTEP]
rw [← not_mem_support, ← toList_eq_nil_iff] at hx
[GOAL]
case pos
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝ : ↑p x = x
hx : toList p x = []
⊢ Nodup (toList p x)
[PROOFSTEP]
simp [hx]
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx : ¬↑p x = x
⊢ Nodup (toList p x)
[PROOFSTEP]
have hc : IsCycle (cycleOf p x) := isCycle_cycleOf p hx
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx : ¬↑p x = x
hc : IsCycle (cycleOf p x)
⊢ Nodup (toList p x)
[PROOFSTEP]
rw [nodup_iff_nthLe_inj]
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx : ¬↑p x = x
hc : IsCycle (cycleOf p x)
⊢ ∀ (i j : ℕ) (h₁ : i < length (toList p x)) (h₂ : j < length (toList p x)),
nthLe (toList p x) i h₁ = nthLe (toList p x) j h₂ → i = j
[PROOFSTEP]
rintro n m hn hm
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx : ¬↑p x = x
hc : IsCycle (cycleOf p x)
n m : ℕ
hn : n < length (toList p x)
hm : m < length (toList p x)
⊢ nthLe (toList p x) n hn = nthLe (toList p x) m hm → n = m
[PROOFSTEP]
rw [length_toList, ← hc.orderOf] at hm hn
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx : ¬↑p x = x
hc : IsCycle (cycleOf p x)
n m : ℕ
hn✝ : n < length (toList p x)
hn : n < orderOf (cycleOf p x)
hm✝ : m < length (toList p x)
hm : m < orderOf (cycleOf p x)
⊢ nthLe (toList p x) n hn✝ = nthLe (toList p x) m hm✝ → n = m
[PROOFSTEP]
rw [← cycleOf_apply_self, ← Ne.def, ← mem_support] at hx
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
n m : ℕ
hn✝ : n < length (toList p x)
hn : n < orderOf (cycleOf p x)
hm✝ : m < length (toList p x)
hm : m < orderOf (cycleOf p x)
⊢ nthLe (toList p x) n hn✝ = nthLe (toList p x) m hm✝ → n = m
[PROOFSTEP]
rw [nthLe_toList, nthLe_toList, ← cycleOf_pow_apply_self p x n, ← cycleOf_pow_apply_self p x m]
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
n m : ℕ
hn✝ : n < length (toList p x)
hn : n < orderOf (cycleOf p x)
hm✝ : m < length (toList p x)
hm : m < orderOf (cycleOf p x)
⊢ ↑(cycleOf p x ^ n) x = ↑(cycleOf p x ^ m) x → n = m
[PROOFSTEP]
cases' n with n
[GOAL]
case neg.zero
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
m : ℕ
hm✝ : m < length (toList p x)
hm : m < orderOf (cycleOf p x)
hn✝ : Nat.zero < length (toList p x)
hn : Nat.zero < orderOf (cycleOf p x)
⊢ ↑(cycleOf p x ^ Nat.zero) x = ↑(cycleOf p x ^ m) x → Nat.zero = m
[PROOFSTEP]
cases' m with m
[GOAL]
case neg.succ
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
m : ℕ
hm✝ : m < length (toList p x)
hm : m < orderOf (cycleOf p x)
n : ℕ
hn✝ : Nat.succ n < length (toList p x)
hn : Nat.succ n < orderOf (cycleOf p x)
⊢ ↑(cycleOf p x ^ Nat.succ n) x = ↑(cycleOf p x ^ m) x → Nat.succ n = m
[PROOFSTEP]
cases' m with m
[GOAL]
case neg.zero.zero
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
hn✝ : Nat.zero < length (toList p x)
hn : Nat.zero < orderOf (cycleOf p x)
hm✝ : Nat.zero < length (toList p x)
hm : Nat.zero < orderOf (cycleOf p x)
⊢ ↑(cycleOf p x ^ Nat.zero) x = ↑(cycleOf p x ^ Nat.zero) x → Nat.zero = Nat.zero
[PROOFSTEP]
simp
[GOAL]
case neg.zero.succ
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
hn✝ : Nat.zero < length (toList p x)
hn : Nat.zero < orderOf (cycleOf p x)
m : ℕ
hm✝ : Nat.succ m < length (toList p x)
hm : Nat.succ m < orderOf (cycleOf p x)
⊢ ↑(cycleOf p x ^ Nat.zero) x = ↑(cycleOf p x ^ Nat.succ m) x → Nat.zero = Nat.succ m
[PROOFSTEP]
rw [← hc.support_pow_of_pos_of_lt_orderOf m.zero_lt_succ hm, mem_support, cycleOf_pow_apply_self] at hx
[GOAL]
case neg.zero.succ
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hc : IsCycle (cycleOf p x)
hn✝ : Nat.zero < length (toList p x)
hn : Nat.zero < orderOf (cycleOf p x)
m : ℕ
hx : ↑(p ^ Nat.succ m) x ≠ x
hm✝ : Nat.succ m < length (toList p x)
hm : Nat.succ m < orderOf (cycleOf p x)
⊢ ↑(cycleOf p x ^ Nat.zero) x = ↑(cycleOf p x ^ Nat.succ m) x → Nat.zero = Nat.succ m
[PROOFSTEP]
simp [hx.symm]
[GOAL]
case neg.succ.zero
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
n : ℕ
hn✝ : Nat.succ n < length (toList p x)
hn : Nat.succ n < orderOf (cycleOf p x)
hm✝ : Nat.zero < length (toList p x)
hm : Nat.zero < orderOf (cycleOf p x)
⊢ ↑(cycleOf p x ^ Nat.succ n) x = ↑(cycleOf p x ^ Nat.zero) x → Nat.succ n = Nat.zero
[PROOFSTEP]
rw [← hc.support_pow_of_pos_of_lt_orderOf n.zero_lt_succ hn, mem_support, cycleOf_pow_apply_self] at hx
[GOAL]
case neg.succ.zero
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hc : IsCycle (cycleOf p x)
n : ℕ
hx : ↑(p ^ Nat.succ n) x ≠ x
hn✝ : Nat.succ n < length (toList p x)
hn : Nat.succ n < orderOf (cycleOf p x)
hm✝ : Nat.zero < length (toList p x)
hm : Nat.zero < orderOf (cycleOf p x)
⊢ ↑(cycleOf p x ^ Nat.succ n) x = ↑(cycleOf p x ^ Nat.zero) x → Nat.succ n = Nat.zero
[PROOFSTEP]
simp [hx]
[GOAL]
case neg.succ.succ
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
n : ℕ
hn✝ : Nat.succ n < length (toList p x)
hn : Nat.succ n < orderOf (cycleOf p x)
m : ℕ
hm✝ : Nat.succ m < length (toList p x)
hm : Nat.succ m < orderOf (cycleOf p x)
⊢ ↑(cycleOf p x ^ Nat.succ n) x = ↑(cycleOf p x ^ Nat.succ m) x → Nat.succ n = Nat.succ m
[PROOFSTEP]
intro h
[GOAL]
case neg.succ.succ
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
n : ℕ
hn✝ : Nat.succ n < length (toList p x)
hn : Nat.succ n < orderOf (cycleOf p x)
m : ℕ
hm✝ : Nat.succ m < length (toList p x)
hm : Nat.succ m < orderOf (cycleOf p x)
h : ↑(cycleOf p x ^ Nat.succ n) x = ↑(cycleOf p x ^ Nat.succ m) x
⊢ Nat.succ n = Nat.succ m
[PROOFSTEP]
have hn' : ¬orderOf (p.cycleOf x) ∣ n.succ := Nat.not_dvd_of_pos_of_lt n.zero_lt_succ hn
[GOAL]
case neg.succ.succ
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
n : ℕ
hn✝ : Nat.succ n < length (toList p x)
hn : Nat.succ n < orderOf (cycleOf p x)
m : ℕ
hm✝ : Nat.succ m < length (toList p x)
hm : Nat.succ m < orderOf (cycleOf p x)
h : ↑(cycleOf p x ^ Nat.succ n) x = ↑(cycleOf p x ^ Nat.succ m) x
hn' : ¬orderOf (cycleOf p x) ∣ Nat.succ n
⊢ Nat.succ n = Nat.succ m
[PROOFSTEP]
have hm' : ¬orderOf (p.cycleOf x) ∣ m.succ := Nat.not_dvd_of_pos_of_lt m.zero_lt_succ hm
[GOAL]
case neg.succ.succ
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
n : ℕ
hn✝ : Nat.succ n < length (toList p x)
hn : Nat.succ n < orderOf (cycleOf p x)
m : ℕ
hm✝ : Nat.succ m < length (toList p x)
hm : Nat.succ m < orderOf (cycleOf p x)
h : ↑(cycleOf p x ^ Nat.succ n) x = ↑(cycleOf p x ^ Nat.succ m) x
hn' : ¬orderOf (cycleOf p x) ∣ Nat.succ n
hm' : ¬orderOf (cycleOf p x) ∣ Nat.succ m
⊢ Nat.succ n = Nat.succ m
[PROOFSTEP]
rw [← hc.support_pow_eq_iff] at hn' hm'
[GOAL]
case neg.succ.succ
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
n : ℕ
hn✝ : Nat.succ n < length (toList p x)
hn : Nat.succ n < orderOf (cycleOf p x)
m : ℕ
hm✝ : Nat.succ m < length (toList p x)
hm : Nat.succ m < orderOf (cycleOf p x)
h : ↑(cycleOf p x ^ Nat.succ n) x = ↑(cycleOf p x ^ Nat.succ m) x
hn' : support (cycleOf p x ^ Nat.succ n) = support (cycleOf p x)
hm' : support (cycleOf p x ^ Nat.succ m) = support (cycleOf p x)
⊢ Nat.succ n = Nat.succ m
[PROOFSTEP]
rw [← Nat.mod_eq_of_lt hn, ← Nat.mod_eq_of_lt hm, ← pow_inj_mod]
[GOAL]
case neg.succ.succ
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
n : ℕ
hn✝ : Nat.succ n < length (toList p x)
hn : Nat.succ n < orderOf (cycleOf p x)
m : ℕ
hm✝ : Nat.succ m < length (toList p x)
hm : Nat.succ m < orderOf (cycleOf p x)
h : ↑(cycleOf p x ^ Nat.succ n) x = ↑(cycleOf p x ^ Nat.succ m) x
hn' : support (cycleOf p x ^ Nat.succ n) = support (cycleOf p x)
hm' : support (cycleOf p x ^ Nat.succ m) = support (cycleOf p x)
⊢ cycleOf p x ^ Nat.succ n = cycleOf p x ^ Nat.succ m
[PROOFSTEP]
refine' support_congr _ _
[GOAL]
case neg.succ.succ.refine'_1
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
n : ℕ
hn✝ : Nat.succ n < length (toList p x)
hn : Nat.succ n < orderOf (cycleOf p x)
m : ℕ
hm✝ : Nat.succ m < length (toList p x)
hm : Nat.succ m < orderOf (cycleOf p x)
h : ↑(cycleOf p x ^ Nat.succ n) x = ↑(cycleOf p x ^ Nat.succ m) x
hn' : support (cycleOf p x ^ Nat.succ n) = support (cycleOf p x)
hm' : support (cycleOf p x ^ Nat.succ m) = support (cycleOf p x)
⊢ support (cycleOf p x ^ Nat.succ n) ⊆ support (cycleOf p x ^ Nat.succ m)
[PROOFSTEP]
rw [hm', hn']
[GOAL]
case neg.succ.succ.refine'_2
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
n : ℕ
hn✝ : Nat.succ n < length (toList p x)
hn : Nat.succ n < orderOf (cycleOf p x)
m : ℕ
hm✝ : Nat.succ m < length (toList p x)
hm : Nat.succ m < orderOf (cycleOf p x)
h : ↑(cycleOf p x ^ Nat.succ n) x = ↑(cycleOf p x ^ Nat.succ m) x
hn' : support (cycleOf p x ^ Nat.succ n) = support (cycleOf p x)
hm' : support (cycleOf p x ^ Nat.succ m) = support (cycleOf p x)
⊢ ∀ (x_1 : α),
x_1 ∈ support (cycleOf p x ^ Nat.succ m) → ↑(cycleOf p x ^ Nat.succ n) x_1 = ↑(cycleOf p x ^ Nat.succ m) x_1
[PROOFSTEP]
rw [hm']
[GOAL]
case neg.succ.succ.refine'_2
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
n : ℕ
hn✝ : Nat.succ n < length (toList p x)
hn : Nat.succ n < orderOf (cycleOf p x)
m : ℕ
hm✝ : Nat.succ m < length (toList p x)
hm : Nat.succ m < orderOf (cycleOf p x)
h : ↑(cycleOf p x ^ Nat.succ n) x = ↑(cycleOf p x ^ Nat.succ m) x
hn' : support (cycleOf p x ^ Nat.succ n) = support (cycleOf p x)
hm' : support (cycleOf p x ^ Nat.succ m) = support (cycleOf p x)
⊢ ∀ (x_1 : α), x_1 ∈ support (cycleOf p x) → ↑(cycleOf p x ^ Nat.succ n) x_1 = ↑(cycleOf p x ^ Nat.succ m) x_1
[PROOFSTEP]
intro y hy
[GOAL]
case neg.succ.succ.refine'_2
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
n : ℕ
hn✝ : Nat.succ n < length (toList p x)
hn : Nat.succ n < orderOf (cycleOf p x)
m : ℕ
hm✝ : Nat.succ m < length (toList p x)
hm : Nat.succ m < orderOf (cycleOf p x)
h : ↑(cycleOf p x ^ Nat.succ n) x = ↑(cycleOf p x ^ Nat.succ m) x
hn' : support (cycleOf p x ^ Nat.succ n) = support (cycleOf p x)
hm' : support (cycleOf p x ^ Nat.succ m) = support (cycleOf p x)
y : α
hy : y ∈ support (cycleOf p x)
⊢ ↑(cycleOf p x ^ Nat.succ n) y = ↑(cycleOf p x ^ Nat.succ m) y
[PROOFSTEP]
obtain ⟨k, rfl⟩ := hc.exists_pow_eq (mem_support.mp hx) (mem_support.mp hy)
[GOAL]
case neg.succ.succ.refine'_2.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
hx✝¹ : ¬↑p x = x
hx✝ : ↑(cycleOf p x) x ≠ x
hx : x ∈ support (cycleOf p x)
hc : IsCycle (cycleOf p x)
n : ℕ
hn✝ : Nat.succ n < length (toList p x)
hn : Nat.succ n < orderOf (cycleOf p x)
m : ℕ
hm✝ : Nat.succ m < length (toList p x)
hm : Nat.succ m < orderOf (cycleOf p x)
h : ↑(cycleOf p x ^ Nat.succ n) x = ↑(cycleOf p x ^ Nat.succ m) x
hn' : support (cycleOf p x ^ Nat.succ n) = support (cycleOf p x)
hm' : support (cycleOf p x ^ Nat.succ m) = support (cycleOf p x)
k : ℕ
hy : ↑(cycleOf p x ^ k) x ∈ support (cycleOf p x)
⊢ ↑(cycleOf p x ^ Nat.succ n) (↑(cycleOf p x ^ k) x) = ↑(cycleOf p x ^ Nat.succ m) (↑(cycleOf p x ^ k) x)
[PROOFSTEP]
rw [← mul_apply, (Commute.pow_pow_self _ _ _).eq, mul_apply, h, ← mul_apply, ← mul_apply,
(Commute.pow_pow_self _ _ _).eq]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x y : α
hy : y ∈ toList p x
⊢ next (toList p x) y hy = ↑p y
[PROOFSTEP]
rw [mem_toList_iff] at hy
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x y : α
hy✝ : y ∈ toList p x
hy : SameCycle p x y ∧ x ∈ support p
⊢ next (toList p x) y hy✝ = ↑p y
[PROOFSTEP]
obtain ⟨k, hk, hk'⟩ := hy.left.exists_pow_eq_of_mem_support hy.right
[GOAL]
case intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x y : α
hy✝ : y ∈ toList p x
hy : SameCycle p x y ∧ x ∈ support p
k : ℕ
hk : k < Finset.card (support (cycleOf p x))
hk' : ↑(p ^ k) x = y
⊢ next (toList p x) y hy✝ = ↑p y
[PROOFSTEP]
rw [← nthLe_toList p x k (by simpa using hk)] at hk'
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x y : α
hy✝ : y ∈ toList p x
hy : SameCycle p x y ∧ x ∈ support p
k : ℕ
hk : k < Finset.card (support (cycleOf p x))
hk' : ↑(p ^ k) x = y
⊢ k < length (toList p x)
[PROOFSTEP]
simpa using hk
[GOAL]
case intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x y : α
hy✝ : y ∈ toList p x
hy : SameCycle p x y ∧ x ∈ support p
k : ℕ
hk : k < Finset.card (support (cycleOf p x))
hk'✝ : ↑(p ^ k) x = y
hk' : nthLe (toList p x) k (_ : k < length (toList p x)) = y
⊢ next (toList p x) y hy✝ = ↑p y
[PROOFSTEP]
simp_rw [← hk']
[GOAL]
case intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x y : α
hy✝ : y ∈ toList p x
hy : SameCycle p x y ∧ x ∈ support p
k : ℕ
hk : k < Finset.card (support (cycleOf p x))
hk'✝ : ↑(p ^ k) x = y
hk' : nthLe (toList p x) k (_ : k < length (toList p x)) = y
⊢ next (toList p x) (nthLe (toList p x) k (_ : k < length (toList p x)))
(_ : nthLe (toList p x) k (_ : k < length (toList p x)) ∈ toList p x) =
↑p (nthLe (toList p x) k (_ : k < length (toList p x)))
[PROOFSTEP]
rw [next_nthLe _ (nodup_toList _ _), nthLe_toList, nthLe_toList, ← mul_apply, ← pow_succ, length_toList,
pow_apply_eq_pow_mod_orderOf_cycleOf_apply p (k + 1), IsCycle.orderOf]
[GOAL]
case intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x y : α
hy✝ : y ∈ toList p x
hy : SameCycle p x y ∧ x ∈ support p
k : ℕ
hk : k < Finset.card (support (cycleOf p x))
hk'✝ : ↑(p ^ k) x = y
hk' : nthLe (toList p x) k (_ : k < length (toList p x)) = y
⊢ IsCycle (cycleOf p x)
[PROOFSTEP]
exact isCycle_cycleOf _ (mem_support.mp hy.right)
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
k : ℕ
⊢ toList p (↑(p ^ k) x) = rotate (toList p x) k
[PROOFSTEP]
apply ext_nthLe
[GOAL]
case hl
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
k : ℕ
⊢ length (toList p (↑(p ^ k) x)) = length (rotate (toList p x) k)
[PROOFSTEP]
simp only [length_toList, cycleOf_self_apply_pow, length_rotate]
[GOAL]
case h
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
k : ℕ
⊢ ∀ (n : ℕ) (h₁ : n < length (toList p (↑(p ^ k) x))) (h₂ : n < length (rotate (toList p x) k)),
nthLe (toList p (↑(p ^ k) x)) n h₁ = nthLe (rotate (toList p x) k) n h₂
[PROOFSTEP]
intro n hn hn'
[GOAL]
case h
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p✝ : Perm α
x✝ : α
p : Perm α
x : α
k n : ℕ
hn : n < length (toList p (↑(p ^ k) x))
hn' : n < length (rotate (toList p x) k)
⊢ nthLe (toList p (↑(p ^ k) x)) n hn = nthLe (rotate (toList p x) k) n hn'
[PROOFSTEP]
rw [nthLe_toList, nthLe_rotate, nthLe_toList, length_toList, pow_mod_card_support_cycleOf_self_apply, pow_add,
mul_apply]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x y : α
h : SameCycle f x y
⊢ toList f x ~r toList f y
[PROOFSTEP]
by_cases hx : x ∈ f.support
[GOAL]
case pos
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x y : α
h : SameCycle f x y
hx : x ∈ support f
⊢ toList f x ~r toList f y
[PROOFSTEP]
obtain ⟨_ | k, _, hy⟩ := h.exists_pow_eq_of_mem_support hx
[GOAL]
case pos.intro.zero.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x y : α
h : SameCycle f x y
hx : x ∈ support f
w✝ : Nat.zero < Finset.card (support (cycleOf f x))
hy : ↑(f ^ Nat.zero) x = y
⊢ toList f x ~r toList f y
[PROOFSTEP]
simp only [coe_one, id.def, pow_zero, Nat.zero_eq] at hy
[GOAL]
case pos.intro.zero.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x y : α
h : SameCycle f x y
hx : x ∈ support f
w✝ : Nat.zero < Finset.card (support (cycleOf f x))
hy : x = y
⊢ toList f x ~r toList f y
[PROOFSTEP]
simp [hy, IsRotated.refl]
[GOAL]
case pos.intro.succ.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x y : α
h : SameCycle f x y
hx : x ∈ support f
k : ℕ
w✝ : Nat.succ k < Finset.card (support (cycleOf f x))
hy : ↑(f ^ Nat.succ k) x = y
⊢ toList f x ~r toList f y
[PROOFSTEP]
use k.succ
[GOAL]
case h
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x y : α
h : SameCycle f x y
hx : x ∈ support f
k : ℕ
w✝ : Nat.succ k < Finset.card (support (cycleOf f x))
hy : ↑(f ^ Nat.succ k) x = y
⊢ rotate (toList f x) (Nat.succ k) = toList f y
[PROOFSTEP]
rw [← toList_pow_apply_eq_rotate, hy]
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x y : α
h : SameCycle f x y
hx : ¬x ∈ support f
⊢ toList f x ~r toList f y
[PROOFSTEP]
rw [toList_eq_nil_iff.mpr hx, isRotated_nil_iff', eq_comm, toList_eq_nil_iff]
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x y : α
h : SameCycle f x y
hx : ¬x ∈ support f
⊢ ¬y ∈ support f
[PROOFSTEP]
rwa [← h.mem_support_iff]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
n : ℕ
⊢ ↑(p ^ n) x ∈ toList p x ↔ x ∈ support p
[PROOFSTEP]
rw [mem_toList_iff, and_iff_right_iff_imp]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
n : ℕ
⊢ x ∈ support p → SameCycle p x (↑(p ^ n) x)
[PROOFSTEP]
refine' fun _ => SameCycle.symm _
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
n : ℕ
x✝ : x ∈ support p
⊢ SameCycle p (↑(p ^ n) x) x
[PROOFSTEP]
rw [sameCycle_pow_left]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ x : α
⊢ toList (formPerm []) x = []
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ x y : α
⊢ toList (formPerm [x]) y = []
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
⊢ toList (formPerm l) (nthLe l 0 (_ : 0 < length l)) = l
[PROOFSTEP]
have hc : l.formPerm.IsCycle := List.isCycle_formPerm hn hl
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
hc : IsCycle (formPerm l)
⊢ toList (formPerm l) (nthLe l 0 (_ : 0 < length l)) = l
[PROOFSTEP]
have hs : l.formPerm.support = l.toFinset :=
by
refine' support_formPerm_of_nodup _ hn _
rintro _ rfl
simp [Nat.succ_le_succ_iff] at hl
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
hc : IsCycle (formPerm l)
⊢ support (formPerm l) = toFinset l
[PROOFSTEP]
refine' support_formPerm_of_nodup _ hn _
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
hc : IsCycle (formPerm l)
⊢ ∀ (x : α), l ≠ [x]
[PROOFSTEP]
rintro _ rfl
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x x✝ : α
hl : 2 ≤ length [x✝]
hn : Nodup [x✝]
hc : IsCycle (formPerm [x✝])
⊢ False
[PROOFSTEP]
simp [Nat.succ_le_succ_iff] at hl
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
hc : IsCycle (formPerm l)
hs : support (formPerm l) = toFinset l
⊢ toList (formPerm l) (nthLe l 0 (_ : 0 < length l)) = l
[PROOFSTEP]
rw [toList, hc.cycleOf_eq (mem_support.mp _), hs, card_toFinset, dedup_eq_self.mpr hn]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
hc : IsCycle (formPerm l)
hs : support (formPerm l) = toFinset l
⊢ map (fun k => ↑(formPerm l ^ k) (nthLe l 0 (_ : 0 < length l))) (range (length l)) = l
[PROOFSTEP]
refine' ext_get (by simp) fun k hk hk' => _
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
hc : IsCycle (formPerm l)
hs : support (formPerm l) = toFinset l
⊢ length (map (fun k => ↑(formPerm l ^ k) (nthLe l 0 (_ : 0 < length l))) (range (length l))) = length l
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
hc : IsCycle (formPerm l)
hs : support (formPerm l) = toFinset l
k : ℕ
hk : k < length (map (fun k => ↑(formPerm l ^ k) (nthLe l 0 (_ : 0 < length l))) (range (length l)))
hk' : k < length l
⊢ List.get (map (fun k => ↑(formPerm l ^ k) (nthLe l 0 (_ : 0 < length l))) (range (length l)))
{ val := k, isLt := hk } =
List.get l { val := k, isLt := hk' }
[PROOFSTEP]
simp [formPerm_pow_apply_nthLe _ hn, Nat.mod_eq_of_lt hk']
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
hc : IsCycle (formPerm l)
hs : support (formPerm l) = toFinset l
k : ℕ
hk : k < length (map (fun k => ↑(formPerm l ^ k) (nthLe l 0 (_ : 0 < length l))) (range (length l)))
hk' : k < length l
⊢ nthLe l k (_ : k < length l) = List.get l { val := k, isLt := hk' }
[PROOFSTEP]
rw [nthLe_eq]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
hc : IsCycle (formPerm l)
hs : support (formPerm l) = toFinset l
⊢ nthLe l 0 (_ : 0 < length l) ∈ support (formPerm l)
[PROOFSTEP]
simpa [hs] using get_mem _ _ _
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
x : α
hx : x ∈ l
⊢ toList (formPerm l) x ~r l
[PROOFSTEP]
obtain ⟨k, hk, rfl⟩ := get_of_mem hx
[GOAL]
case intro.refl
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
k : Fin (length l)
hx : List.get l k ∈ l
⊢ toList (formPerm l) (List.get l k) ~r l
[PROOFSTEP]
have hr : l ~r l.rotate k := ⟨k, rfl⟩
[GOAL]
case intro.refl
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
k : Fin (length l)
hx : List.get l k ∈ l
hr : l ~r rotate l ↑k
⊢ toList (formPerm l) (List.get l k) ~r l
[PROOFSTEP]
rw [formPerm_eq_of_isRotated hn hr]
[GOAL]
case intro.refl
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
k : Fin (length l)
hx : List.get l k ∈ l
hr : l ~r rotate l ↑k
⊢ toList (formPerm (rotate l ↑k)) (List.get l k) ~r l
[PROOFSTEP]
rw [get_eq_get_rotate l k k]
[GOAL]
case intro.refl
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
k : Fin (length l)
hx : List.get l k ∈ l
hr : l ~r rotate l ↑k
⊢ toList (formPerm (rotate l ↑k))
(List.get (rotate l ↑k)
{ val := (length l - ↑k % length l + ↑k) % length l,
isLt := (_ : (length l - ↑k % length l + ↑k) % length l < length (rotate l ↑k)) }) ~r
l
[PROOFSTEP]
simp only [Nat.mod_eq_of_lt k.2, tsub_add_cancel_of_le (le_of_lt k.2), Nat.mod_self]
[GOAL]
case intro.refl
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
k : Fin (length l)
hx : List.get l k ∈ l
hr : l ~r rotate l ↑k
⊢ toList (formPerm (rotate l ↑k)) (List.get (rotate l ↑k) { val := 0, isLt := (_ : 0 < length (rotate l ↑k)) }) ~r l
[PROOFSTEP]
erw [toList_formPerm_nontrivial]
[GOAL]
case intro.refl
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
k : Fin (length l)
hx : List.get l k ∈ l
hr : l ~r rotate l ↑k
⊢ rotate l ↑k ~r l
[PROOFSTEP]
simp
[GOAL]
case intro.refl.hl
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
k : Fin (length l)
hx : List.get l k ∈ l
hr : l ~r rotate l ↑k
⊢ 2 ≤ length (rotate l ↑k)
[PROOFSTEP]
simpa using hl
[GOAL]
case intro.refl.hn
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
l : List α
hl : 2 ≤ length l
hn : Nodup l
k : Fin (length l)
hx : List.get l k ∈ l
hr : l ~r rotate l ↑k
⊢ Nodup (rotate l ↑k)
[PROOFSTEP]
simpa using hn
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x : α
⊢ formPerm (toList f x) = cycleOf f x
[PROOFSTEP]
by_cases hx : f x = x
[GOAL]
case pos
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x : α
hx : ↑f x = x
⊢ formPerm (toList f x) = cycleOf f x
[PROOFSTEP]
rw [(cycleOf_eq_one_iff f).mpr hx, toList_eq_nil_iff.mpr (not_mem_support.mpr hx), formPerm_nil]
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x : α
hx : ¬↑f x = x
⊢ formPerm (toList f x) = cycleOf f x
[PROOFSTEP]
ext y
[GOAL]
case neg.H
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x : α
hx : ¬↑f x = x
y : α
⊢ ↑(formPerm (toList f x)) y = ↑(cycleOf f x) y
[PROOFSTEP]
by_cases hy : SameCycle f x y
[GOAL]
case pos
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x : α
hx : ¬↑f x = x
y : α
hy : SameCycle f x y
⊢ ↑(formPerm (toList f x)) y = ↑(cycleOf f x) y
[PROOFSTEP]
obtain ⟨k, _, rfl⟩ := hy.exists_pow_eq_of_mem_support (mem_support.mpr hx)
[GOAL]
case pos.intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x : α
hx : ¬↑f x = x
k : ℕ
w✝ : k < Finset.card (support (cycleOf f x))
hy : SameCycle f x (↑(f ^ k) x)
⊢ ↑(formPerm (toList f x)) (↑(f ^ k) x) = ↑(cycleOf f x) (↑(f ^ k) x)
[PROOFSTEP]
rw [cycleOf_apply_apply_pow_self, List.formPerm_apply_mem_eq_next (nodup_toList f x), next_toList_eq_apply, pow_succ,
mul_apply]
[GOAL]
case pos.intro.intro.hy
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x : α
hx : ¬↑f x = x
k : ℕ
w✝ : k < Finset.card (support (cycleOf f x))
hy : SameCycle f x (↑(f ^ k) x)
⊢ ↑(f ^ k) x ∈ toList f x
[PROOFSTEP]
rw [mem_toList_iff]
[GOAL]
case pos.intro.intro.hy
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x : α
hx : ¬↑f x = x
k : ℕ
w✝ : k < Finset.card (support (cycleOf f x))
hy : SameCycle f x (↑(f ^ k) x)
⊢ SameCycle f x (↑(f ^ k) x) ∧ x ∈ support f
[PROOFSTEP]
exact ⟨⟨k, rfl⟩, mem_support.mpr hx⟩
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x : α
hx : ¬↑f x = x
y : α
hy : ¬SameCycle f x y
⊢ ↑(formPerm (toList f x)) y = ↑(cycleOf f x) y
[PROOFSTEP]
rw [cycleOf_apply_of_not_sameCycle hy, formPerm_apply_of_not_mem]
[GOAL]
case neg.h
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
x : α
hx : ¬↑f x = x
y : α
hy : ¬SameCycle f x y
⊢ ¬y ∈ toList f x
[PROOFSTEP]
simp [mem_toList_iff, hy]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
f : Perm α
hf : IsCycle f
⊢ ∀ (a a' : α),
Multiset α →
∀ (b : Cycle α),
HEq (if ↑f a = a then if ↑f a' = a' then b else ↑(toList f a') else ↑(toList f a))
(if ↑f a' = a' then if ↑f a = a then b else ↑(toList f a) else ↑(toList f a'))
[PROOFSTEP]
intro x y _ s
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x y : α
m✝ : Multiset α
s : Cycle α
⊢ HEq (if ↑f x = x then if ↑f y = y then s else ↑(toList f y) else ↑(toList f x))
(if ↑f y = y then if ↑f x = x then s else ↑(toList f x) else ↑(toList f y))
[PROOFSTEP]
refine' heq_of_eq _
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x y : α
m✝ : Multiset α
s : Cycle α
⊢ (if ↑f x = x then if ↑f y = y then s else ↑(toList f y) else ↑(toList f x)) =
if ↑f y = y then if ↑f x = x then s else ↑(toList f x) else ↑(toList f y)
[PROOFSTEP]
split_ifs with hx hy hy
[GOAL]
case pos
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x y : α
m✝ : Multiset α
s : Cycle α
hx : ↑f x = x
hy : ↑f y = y
⊢ s = s
[PROOFSTEP]
try rfl
[GOAL]
case pos
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x y : α
m✝ : Multiset α
s : Cycle α
hx : ↑f x = x
hy : ↑f y = y
⊢ s = s
[PROOFSTEP]
rfl
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x y : α
m✝ : Multiset α
s : Cycle α
hx : ↑f x = x
hy : ¬↑f y = y
⊢ ↑(toList f y) = ↑(toList f y)
[PROOFSTEP]
try rfl
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x y : α
m✝ : Multiset α
s : Cycle α
hx : ↑f x = x
hy : ¬↑f y = y
⊢ ↑(toList f y) = ↑(toList f y)
[PROOFSTEP]
rfl
[GOAL]
case pos
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x y : α
m✝ : Multiset α
s : Cycle α
hx : ¬↑f x = x
hy : ↑f y = y
⊢ ↑(toList f x) = ↑(toList f x)
[PROOFSTEP]
try rfl
[GOAL]
case pos
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x y : α
m✝ : Multiset α
s : Cycle α
hx : ¬↑f x = x
hy : ↑f y = y
⊢ ↑(toList f x) = ↑(toList f x)
[PROOFSTEP]
rfl
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x y : α
m✝ : Multiset α
s : Cycle α
hx : ¬↑f x = x
hy : ¬↑f y = y
⊢ ↑(toList f x) = ↑(toList f y)
[PROOFSTEP]
try rfl
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x y : α
m✝ : Multiset α
s : Cycle α
hx : ¬↑f x = x
hy : ¬↑f y = y
⊢ ↑(toList f x) = ↑(toList f y)
[PROOFSTEP]
rfl
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x y : α
m✝ : Multiset α
s : Cycle α
hx : ¬↑f x = x
hy : ¬↑f y = y
⊢ ↑(toList f x) = ↑(toList f y)
[PROOFSTEP]
have hc : SameCycle f x y := IsCycle.sameCycle hf hx hy
[GOAL]
case neg
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x y : α
m✝ : Multiset α
s : Cycle α
hx : ¬↑f x = x
hy : ¬↑f y = y
hc : SameCycle f x y
⊢ ↑(toList f x) = ↑(toList f y)
[PROOFSTEP]
exact Quotient.sound' hc.toList_isRotated
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x
⊢ toCycle f hf = ↑(toList f x)
[PROOFSTEP]
have key : (Finset.univ : Finset α).val = x ::ₘ Finset.univ.val.erase x := by simp
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x
⊢ Finset.univ.val = x ::ₘ Multiset.erase Finset.univ.val x
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x
key : Finset.univ.val = x ::ₘ Multiset.erase Finset.univ.val x
⊢ toCycle f hf = ↑(toList f x)
[PROOFSTEP]
rw [toCycle, key]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x
key : Finset.univ.val = x ::ₘ Multiset.erase Finset.univ.val x
⊢ Multiset.recOn (x ::ₘ Multiset.erase Finset.univ.val x) (Quot.mk Setoid.r [])
(fun x x_1 l => if ↑f x = x then l else ↑(toList f x))
(_ :
∀ (x y : α),
Multiset α →
∀ (s : Cycle α),
HEq (if ↑f x = x then if ↑f y = y then s else ↑(toList f y) else ↑(toList f x))
(if ↑f y = y then if ↑f x = x then s else ↑(toList f x) else ↑(toList f y))) =
↑(toList f x)
[PROOFSTEP]
simp [hx]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
f : Perm α
hf : IsCycle f
⊢ Cycle.Nodup (toCycle f hf)
[PROOFSTEP]
obtain ⟨x, hx, -⟩ := id hf
[GOAL]
case intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x
⊢ Cycle.Nodup (toCycle f hf)
[PROOFSTEP]
simpa [toCycle_eq_toList f hf x hx] using nodup_toList _ _
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
f : Perm α
hf : IsCycle f
⊢ Cycle.Nontrivial (toCycle f hf)
[PROOFSTEP]
obtain ⟨x, hx, -⟩ := id hf
[GOAL]
case intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x
⊢ Cycle.Nontrivial (toCycle f hf)
[PROOFSTEP]
simp [toCycle_eq_toList f hf x hx, hx, Cycle.nontrivial_coe_nodup_iff (nodup_toList _ _)]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
f : { f // IsCycle f }
⊢ (fun s =>
{ val := Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s),
property := (_ : IsCycle (Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s))) })
((fun f =>
{ val := toCycle ↑f (_ : IsCycle ↑f),
property :=
(_ : Cycle.Nodup (toCycle ↑f (_ : IsCycle ↑f)) ∧ Cycle.Nontrivial (toCycle ↑f (_ : IsCycle ↑f))) })
f) =
f
[PROOFSTEP]
obtain ⟨x, hx, -⟩ := id f.prop
[GOAL]
case intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
f : { f // IsCycle f }
x : α
hx : ↑↑f x ≠ x
⊢ (fun s =>
{ val := Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s),
property := (_ : IsCycle (Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s))) })
((fun f =>
{ val := toCycle ↑f (_ : IsCycle ↑f),
property :=
(_ : Cycle.Nodup (toCycle ↑f (_ : IsCycle ↑f)) ∧ Cycle.Nontrivial (toCycle ↑f (_ : IsCycle ↑f))) })
f) =
f
[PROOFSTEP]
simpa [toCycle_eq_toList (f : Perm α) f.prop x hx, formPerm_toList, Subtype.ext_iff] using f.prop.cycleOf_eq hx
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
s : { s // Cycle.Nodup s ∧ Cycle.Nontrivial s }
⊢ (fun f =>
{ val := toCycle ↑f (_ : IsCycle ↑f),
property :=
(_ : Cycle.Nodup (toCycle ↑f (_ : IsCycle ↑f)) ∧ Cycle.Nontrivial (toCycle ↑f (_ : IsCycle ↑f))) })
((fun s =>
{ val := Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s),
property := (_ : IsCycle (Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s))) })
s) =
s
[PROOFSTEP]
rcases s with ⟨⟨s⟩, hn, ht⟩
[GOAL]
case mk.mk.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x : α
val✝ : Cycle α
s : List α
hn : Cycle.Nodup (Quot.mk Setoid.r s)
ht : Cycle.Nontrivial (Quot.mk Setoid.r s)
⊢ (fun f =>
{ val := toCycle ↑f (_ : IsCycle ↑f),
property :=
(_ : Cycle.Nodup (toCycle ↑f (_ : IsCycle ↑f)) ∧ Cycle.Nontrivial (toCycle ↑f (_ : IsCycle ↑f))) })
((fun s =>
{ val := Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s),
property := (_ : IsCycle (Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s))) })
{ val := Quot.mk Setoid.r s,
property := (_ : Cycle.Nodup (Quot.mk Setoid.r s) ∧ Cycle.Nontrivial (Quot.mk Setoid.r s)) }) =
{ val := Quot.mk Setoid.r s,
property := (_ : Cycle.Nodup (Quot.mk Setoid.r s) ∧ Cycle.Nontrivial (Quot.mk Setoid.r s)) }
[PROOFSTEP]
obtain ⟨x, -, -, hx, -⟩ := id ht
[GOAL]
case mk.mk.intro.intro.intro.intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
val✝ : Cycle α
s : List α
hn : Cycle.Nodup (Quot.mk Setoid.r s)
ht : Cycle.Nontrivial (Quot.mk Setoid.r s)
x : α
hx : x ∈ Quot.mk Setoid.r s
⊢ (fun f =>
{ val := toCycle ↑f (_ : IsCycle ↑f),
property :=
(_ : Cycle.Nodup (toCycle ↑f (_ : IsCycle ↑f)) ∧ Cycle.Nontrivial (toCycle ↑f (_ : IsCycle ↑f))) })
((fun s =>
{ val := Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s),
property := (_ : IsCycle (Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s))) })
{ val := Quot.mk Setoid.r s,
property := (_ : Cycle.Nodup (Quot.mk Setoid.r s) ∧ Cycle.Nontrivial (Quot.mk Setoid.r s)) }) =
{ val := Quot.mk Setoid.r s,
property := (_ : Cycle.Nodup (Quot.mk Setoid.r s) ∧ Cycle.Nontrivial (Quot.mk Setoid.r s)) }
[PROOFSTEP]
have hl : 2 ≤ s.length := by simpa using Cycle.length_nontrivial ht
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
val✝ : Cycle α
s : List α
hn : Cycle.Nodup (Quot.mk Setoid.r s)
ht : Cycle.Nontrivial (Quot.mk Setoid.r s)
x : α
hx : x ∈ Quot.mk Setoid.r s
⊢ 2 ≤ length s
[PROOFSTEP]
simpa using Cycle.length_nontrivial ht
[GOAL]
case mk.mk.intro.intro.intro.intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
val✝ : Cycle α
s : List α
hn : Cycle.Nodup (Quot.mk Setoid.r s)
ht : Cycle.Nontrivial (Quot.mk Setoid.r s)
x : α
hx : x ∈ Quot.mk Setoid.r s
hl : 2 ≤ length s
⊢ (fun f =>
{ val := toCycle ↑f (_ : IsCycle ↑f),
property :=
(_ : Cycle.Nodup (toCycle ↑f (_ : IsCycle ↑f)) ∧ Cycle.Nontrivial (toCycle ↑f (_ : IsCycle ↑f))) })
((fun s =>
{ val := Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s),
property := (_ : IsCycle (Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s))) })
{ val := Quot.mk Setoid.r s,
property := (_ : Cycle.Nodup (Quot.mk Setoid.r s) ∧ Cycle.Nontrivial (Quot.mk Setoid.r s)) }) =
{ val := Quot.mk Setoid.r s,
property := (_ : Cycle.Nodup (Quot.mk Setoid.r s) ∧ Cycle.Nontrivial (Quot.mk Setoid.r s)) }
[PROOFSTEP]
simp only [Cycle.mk_eq_coe, Cycle.nodup_coe_iff, Cycle.mem_coe_iff, Subtype.coe_mk, Cycle.formPerm_coe] at hn hx ⊢
[GOAL]
case mk.mk.intro.intro.intro.intro.intro
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
val✝ : Cycle α
s : List α
hn✝ : Cycle.Nodup (Quot.mk Setoid.r s)
ht : Cycle.Nontrivial (Quot.mk Setoid.r s)
x : α
hl : 2 ≤ length s
hn : Nodup s
hx : x ∈ s
⊢ { val := toCycle (formPerm s) (_ : IsCycle (formPerm s)),
property :=
(_ : (fun s => Cycle.Nodup s ∧ Cycle.Nontrivial s) (toCycle (formPerm s) (_ : IsCycle (formPerm s)))) } =
{ val := ↑s, property := (_ : (fun s => Cycle.Nodup s ∧ Cycle.Nontrivial s) ↑s) }
[PROOFSTEP]
apply Subtype.ext
[GOAL]
case mk.mk.intro.intro.intro.intro.intro.a
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
val✝ : Cycle α
s : List α
hn✝ : Cycle.Nodup (Quot.mk Setoid.r s)
ht : Cycle.Nontrivial (Quot.mk Setoid.r s)
x : α
hl : 2 ≤ length s
hn : Nodup s
hx : x ∈ s
⊢ ↑{ val := toCycle (formPerm s) (_ : IsCycle (formPerm s)),
property :=
(_ : (fun s => Cycle.Nodup s ∧ Cycle.Nontrivial s) (toCycle (formPerm s) (_ : IsCycle (formPerm s)))) } =
↑{ val := ↑s, property := (_ : (fun s => Cycle.Nodup s ∧ Cycle.Nontrivial s) ↑s) }
[PROOFSTEP]
dsimp
[GOAL]
case mk.mk.intro.intro.intro.intro.intro.a
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
val✝ : Cycle α
s : List α
hn✝ : Cycle.Nodup (Quot.mk Setoid.r s)
ht : Cycle.Nontrivial (Quot.mk Setoid.r s)
x : α
hl : 2 ≤ length s
hn : Nodup s
hx : x ∈ s
⊢ toCycle (formPerm s)
(_ : IsCycle ↑{ val := formPerm s, property := (_ : IsCycle (Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s))) }) =
↑s
[PROOFSTEP]
rw [toCycle_eq_toList _ _ x]
[GOAL]
case mk.mk.intro.intro.intro.intro.intro.a
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
val✝ : Cycle α
s : List α
hn✝ : Cycle.Nodup (Quot.mk Setoid.r s)
ht : Cycle.Nontrivial (Quot.mk Setoid.r s)
x : α
hl : 2 ≤ length s
hn : Nodup s
hx : x ∈ s
⊢ ↑(toList (formPerm s) x) = ↑s
[PROOFSTEP]
refine' Quotient.sound' _
[GOAL]
case mk.mk.intro.intro.intro.intro.intro.a
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
val✝ : Cycle α
s : List α
hn✝ : Cycle.Nodup (Quot.mk Setoid.r s)
ht : Cycle.Nontrivial (Quot.mk Setoid.r s)
x : α
hl : 2 ≤ length s
hn : Nodup s
hx : x ∈ s
⊢ Setoid.r (toList (formPerm s) x) s
[PROOFSTEP]
exact toList_formPerm_isRotated_self _ hl hn _ hx
[GOAL]
case mk.mk.intro.intro.intro.intro.intro.a
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
val✝ : Cycle α
s : List α
hn✝ : Cycle.Nodup (Quot.mk Setoid.r s)
ht : Cycle.Nontrivial (Quot.mk Setoid.r s)
x : α
hl : 2 ≤ length s
hn : Nodup s
hx : x ∈ s
⊢ ↑(formPerm s) x ≠ x
[PROOFSTEP]
rw [← mem_support, support_formPerm_of_nodup _ hn]
[GOAL]
case mk.mk.intro.intro.intro.intro.intro.a
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
val✝ : Cycle α
s : List α
hn✝ : Cycle.Nodup (Quot.mk Setoid.r s)
ht : Cycle.Nontrivial (Quot.mk Setoid.r s)
x : α
hl : 2 ≤ length s
hn : Nodup s
hx : x ∈ s
⊢ x ∈ toFinset s
[PROOFSTEP]
simpa using hx
[GOAL]
case mk.mk.intro.intro.intro.intro.intro.a
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝ : α
val✝ : Cycle α
s : List α
hn✝ : Cycle.Nodup (Quot.mk Setoid.r s)
ht : Cycle.Nontrivial (Quot.mk Setoid.r s)
x : α
hl : 2 ≤ length s
hn : Nodup s
hx : x ∈ s
⊢ ∀ (x : α), s ≠ [x]
[PROOFSTEP]
rintro _ rfl
[GOAL]
case mk.mk.intro.intro.intro.intro.intro.a
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
p : Perm α
x✝¹ : α
val✝ : Cycle α
x x✝ : α
hn✝ : Cycle.Nodup (Quot.mk Setoid.r [x✝])
ht : Cycle.Nontrivial (Quot.mk Setoid.r [x✝])
hl : 2 ≤ length [x✝]
hn : Nodup [x✝]
hx : x ∈ [x✝]
⊢ False
[PROOFSTEP]
simp [Nat.succ_le_succ_iff] at hl
[GOAL]
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
⊢ ∃! s, ∃ h, Cycle.formPerm s h = f
[PROOFSTEP]
cases nonempty_fintype α
[GOAL]
case intro
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
val✝ : Fintype α
⊢ ∃! s, ∃ h, Cycle.formPerm s h = f
[PROOFSTEP]
obtain ⟨x, hx, hy⟩ := id hf
[GOAL]
case intro.intro.intro
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
val✝ : Fintype α
x : α
hx : ↑f x ≠ x
hy : ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
⊢ ∃! s, ∃ h, Cycle.formPerm s h = f
[PROOFSTEP]
refine' ⟨f.toList x, ⟨nodup_toList f x, _⟩, _⟩
[GOAL]
case intro.intro.intro.refine'_1
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
val✝ : Fintype α
x : α
hx : ↑f x ≠ x
hy : ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
⊢ Cycle.formPerm ↑(toList f x) (_ : Nodup (toList f x)) = f
[PROOFSTEP]
simp [formPerm_toList, hf.cycleOf_eq hx]
[GOAL]
case intro.intro.intro.refine'_2
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
val✝ : Fintype α
x : α
hx : ↑f x ≠ x
hy : ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
⊢ ∀ (y : Cycle α), (fun s => ∃ h, Cycle.formPerm s h = f) y → y = ↑(toList f x)
[PROOFSTEP]
rintro ⟨l⟩ ⟨hn, rfl⟩
[GOAL]
case intro.intro.intro.refine'_2.mk.intro
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
val✝ : Fintype α
x : α
y✝ : Cycle α
l : List α
hn : Cycle.Nodup (Quot.mk Setoid.r l)
hf : IsCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn)
hx : ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) x ≠ x
hy : ∀ ⦃y : α⦄, ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) y ≠ y → SameCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn) x y
⊢ Quot.mk Setoid.r l = ↑(toList (Cycle.formPerm (Quot.mk Setoid.r l) hn) x)
[PROOFSTEP]
simp only [Cycle.mk_eq_coe, Cycle.coe_eq_coe, Subtype.coe_mk, Cycle.formPerm_coe]
[GOAL]
case intro.intro.intro.refine'_2.mk.intro
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
val✝ : Fintype α
x : α
y✝ : Cycle α
l : List α
hn : Cycle.Nodup (Quot.mk Setoid.r l)
hf : IsCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn)
hx : ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) x ≠ x
hy : ∀ ⦃y : α⦄, ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) y ≠ y → SameCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn) x y
⊢ l ~r toList (formPerm l) x
[PROOFSTEP]
refine' (toList_formPerm_isRotated_self _ _ hn _ _).symm
[GOAL]
case intro.intro.intro.refine'_2.mk.intro.refine'_1
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
val✝ : Fintype α
x : α
y✝ : Cycle α
l : List α
hn : Cycle.Nodup (Quot.mk Setoid.r l)
hf : IsCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn)
hx : ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) x ≠ x
hy : ∀ ⦃y : α⦄, ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) y ≠ y → SameCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn) x y
⊢ 2 ≤ length l
[PROOFSTEP]
contrapose! hx
[GOAL]
case intro.intro.intro.refine'_2.mk.intro.refine'_1
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
val✝ : Fintype α
x : α
y✝ : Cycle α
l : List α
hn : Cycle.Nodup (Quot.mk Setoid.r l)
hf : IsCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn)
hy : ∀ ⦃y : α⦄, ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) y ≠ y → SameCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn) x y
hx : length l < 2
⊢ ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) x = x
[PROOFSTEP]
suffices formPerm l = 1 by simp [this]
[GOAL]
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
val✝ : Fintype α
x : α
y✝ : Cycle α
l : List α
hn : Cycle.Nodup (Quot.mk Setoid.r l)
hf : IsCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn)
hy : ∀ ⦃y : α⦄, ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) y ≠ y → SameCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn) x y
hx : length l < 2
this : formPerm l = 1
⊢ ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) x = x
[PROOFSTEP]
simp [this]
[GOAL]
case intro.intro.intro.refine'_2.mk.intro.refine'_1
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
val✝ : Fintype α
x : α
y✝ : Cycle α
l : List α
hn : Cycle.Nodup (Quot.mk Setoid.r l)
hf : IsCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn)
hy : ∀ ⦃y : α⦄, ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) y ≠ y → SameCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn) x y
hx : length l < 2
⊢ formPerm l = 1
[PROOFSTEP]
rw [formPerm_eq_one_iff _ hn]
[GOAL]
case intro.intro.intro.refine'_2.mk.intro.refine'_1
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
val✝ : Fintype α
x : α
y✝ : Cycle α
l : List α
hn : Cycle.Nodup (Quot.mk Setoid.r l)
hf : IsCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn)
hy : ∀ ⦃y : α⦄, ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) y ≠ y → SameCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn) x y
hx : length l < 2
⊢ length l ≤ 1
[PROOFSTEP]
exact Nat.le_of_lt_succ hx
[GOAL]
case intro.intro.intro.refine'_2.mk.intro.refine'_2
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
val✝ : Fintype α
x : α
y✝ : Cycle α
l : List α
hn : Cycle.Nodup (Quot.mk Setoid.r l)
hf : IsCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn)
hx : ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) x ≠ x
hy : ∀ ⦃y : α⦄, ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) y ≠ y → SameCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn) x y
⊢ x ∈ l
[PROOFSTEP]
rw [← mem_toFinset]
[GOAL]
case intro.intro.intro.refine'_2.mk.intro.refine'_2
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
val✝ : Fintype α
x : α
y✝ : Cycle α
l : List α
hn : Cycle.Nodup (Quot.mk Setoid.r l)
hf : IsCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn)
hx : ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) x ≠ x
hy : ∀ ⦃y : α⦄, ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) y ≠ y → SameCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn) x y
⊢ x ∈ toFinset l
[PROOFSTEP]
refine' support_formPerm_le l _
[GOAL]
case intro.intro.intro.refine'_2.mk.intro.refine'_2
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
val✝ : Fintype α
x : α
y✝ : Cycle α
l : List α
hn : Cycle.Nodup (Quot.mk Setoid.r l)
hf : IsCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn)
hx : ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) x ≠ x
hy : ∀ ⦃y : α⦄, ↑(Cycle.formPerm (Quot.mk Setoid.r l) hn) y ≠ y → SameCycle (Cycle.formPerm (Quot.mk Setoid.r l) hn) x y
⊢ x ∈ support (formPerm l)
[PROOFSTEP]
simpa using hx
[GOAL]
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
⊢ ∃! s, Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s) = f
[PROOFSTEP]
obtain ⟨s, ⟨hs, rfl⟩, hs'⟩ := hf.existsUnique_cycle
[GOAL]
case intro.intro.intro
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
s : Cycle α
hs : Cycle.Nodup s
hf : IsCycle (Cycle.formPerm s hs)
hs' : ∀ (y : Cycle α), (fun s_1 => ∃ h, Cycle.formPerm s_1 h = Cycle.formPerm s hs) y → y = s
⊢ ∃! s_1, Cycle.formPerm ↑s_1 (_ : Cycle.Nodup ↑s_1) = Cycle.formPerm s hs
[PROOFSTEP]
refine' ⟨⟨s, hs⟩, rfl, _⟩
[GOAL]
case intro.intro.intro
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
s : Cycle α
hs : Cycle.Nodup s
hf : IsCycle (Cycle.formPerm s hs)
hs' : ∀ (y : Cycle α), (fun s_1 => ∃ h, Cycle.formPerm s_1 h = Cycle.formPerm s hs) y → y = s
⊢ ∀ (y : { s // Cycle.Nodup s }),
(fun s_1 => Cycle.formPerm ↑s_1 (_ : Cycle.Nodup ↑s_1) = Cycle.formPerm s hs) y → y = { val := s, property := hs }
[PROOFSTEP]
rintro ⟨t, ht⟩ ht'
[GOAL]
case intro.intro.intro.mk
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
s : Cycle α
hs : Cycle.Nodup s
hf : IsCycle (Cycle.formPerm s hs)
hs' : ∀ (y : Cycle α), (fun s_1 => ∃ h, Cycle.formPerm s_1 h = Cycle.formPerm s hs) y → y = s
t : Cycle α
ht : Cycle.Nodup t
ht' : Cycle.formPerm ↑{ val := t, property := ht } (_ : Cycle.Nodup ↑{ val := t, property := ht }) = Cycle.formPerm s hs
⊢ { val := t, property := ht } = { val := s, property := hs }
[PROOFSTEP]
simpa using hs' _ ⟨ht, ht'⟩
[GOAL]
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
⊢ ∃! s, Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s) = f
[PROOFSTEP]
obtain ⟨⟨s, hn⟩, hs, hs'⟩ := hf.existsUnique_cycle_subtype
[GOAL]
case intro.mk.intro
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
s : Cycle α
hn : Cycle.Nodup s
hs : Cycle.formPerm ↑{ val := s, property := hn } (_ : Cycle.Nodup ↑{ val := s, property := hn }) = f
hs' :
∀ (y : { s // Cycle.Nodup s }),
(fun s => Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s) = f) y → y = { val := s, property := hn }
⊢ ∃! s, Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s) = f
[PROOFSTEP]
refine' ⟨⟨s, hn, _⟩, _, _⟩
[GOAL]
case intro.mk.intro.refine'_1
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
s : Cycle α
hn : Cycle.Nodup s
hs : Cycle.formPerm ↑{ val := s, property := hn } (_ : Cycle.Nodup ↑{ val := s, property := hn }) = f
hs' :
∀ (y : { s // Cycle.Nodup s }),
(fun s => Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s) = f) y → y = { val := s, property := hn }
⊢ Cycle.Nontrivial s
[PROOFSTEP]
rw [hn.nontrivial_iff]
[GOAL]
case intro.mk.intro.refine'_1
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
s : Cycle α
hn : Cycle.Nodup s
hs : Cycle.formPerm ↑{ val := s, property := hn } (_ : Cycle.Nodup ↑{ val := s, property := hn }) = f
hs' :
∀ (y : { s // Cycle.Nodup s }),
(fun s => Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s) = f) y → y = { val := s, property := hn }
⊢ ¬Cycle.Subsingleton s
[PROOFSTEP]
subst f
[GOAL]
case intro.mk.intro.refine'_1
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
s : Cycle α
hn : Cycle.Nodup s
hf : IsCycle (Cycle.formPerm ↑{ val := s, property := hn } (_ : Cycle.Nodup ↑{ val := s, property := hn }))
hs' :
∀ (y : { s // Cycle.Nodup s }),
(fun s_1 =>
Cycle.formPerm ↑s_1 (_ : Cycle.Nodup ↑s_1) =
Cycle.formPerm ↑{ val := s, property := hn } (_ : Cycle.Nodup ↑{ val := s, property := hn }))
y →
y = { val := s, property := hn }
⊢ ¬Cycle.Subsingleton s
[PROOFSTEP]
intro H
[GOAL]
case intro.mk.intro.refine'_1
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
s : Cycle α
hn : Cycle.Nodup s
hf : IsCycle (Cycle.formPerm ↑{ val := s, property := hn } (_ : Cycle.Nodup ↑{ val := s, property := hn }))
hs' :
∀ (y : { s // Cycle.Nodup s }),
(fun s_1 =>
Cycle.formPerm ↑s_1 (_ : Cycle.Nodup ↑s_1) =
Cycle.formPerm ↑{ val := s, property := hn } (_ : Cycle.Nodup ↑{ val := s, property := hn }))
y →
y = { val := s, property := hn }
H : Cycle.Subsingleton s
⊢ False
[PROOFSTEP]
refine' hf.ne_one _
[GOAL]
case intro.mk.intro.refine'_1
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
s : Cycle α
hn : Cycle.Nodup s
hf : IsCycle (Cycle.formPerm ↑{ val := s, property := hn } (_ : Cycle.Nodup ↑{ val := s, property := hn }))
hs' :
∀ (y : { s // Cycle.Nodup s }),
(fun s_1 =>
Cycle.formPerm ↑s_1 (_ : Cycle.Nodup ↑s_1) =
Cycle.formPerm ↑{ val := s, property := hn } (_ : Cycle.Nodup ↑{ val := s, property := hn }))
y →
y = { val := s, property := hn }
H : Cycle.Subsingleton s
⊢ Cycle.formPerm ↑{ val := s, property := hn } (_ : Cycle.Nodup ↑{ val := s, property := hn }) = 1
[PROOFSTEP]
simpa using Cycle.formPerm_subsingleton _ H
[GOAL]
case intro.mk.intro.refine'_2
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
s : Cycle α
hn : Cycle.Nodup s
hs : Cycle.formPerm ↑{ val := s, property := hn } (_ : Cycle.Nodup ↑{ val := s, property := hn }) = f
hs' :
∀ (y : { s // Cycle.Nodup s }),
(fun s => Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s) = f) y → y = { val := s, property := hn }
⊢ (fun s => Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s) = f)
{ val := s, property := (_ : Cycle.Nodup s ∧ Cycle.Nontrivial s) }
[PROOFSTEP]
simpa using hs
[GOAL]
case intro.mk.intro.refine'_3
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
s : Cycle α
hn : Cycle.Nodup s
hs : Cycle.formPerm ↑{ val := s, property := hn } (_ : Cycle.Nodup ↑{ val := s, property := hn }) = f
hs' :
∀ (y : { s // Cycle.Nodup s }),
(fun s => Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s) = f) y → y = { val := s, property := hn }
⊢ ∀ (y : { s // Cycle.Nodup s ∧ Cycle.Nontrivial s }),
(fun s => Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s) = f) y →
y = { val := s, property := (_ : Cycle.Nodup s ∧ Cycle.Nontrivial s) }
[PROOFSTEP]
rintro ⟨t, ht, ht'⟩ ht''
[GOAL]
case intro.mk.intro.refine'_3.mk.intro
α : Type u_1
inst✝¹ : Finite α
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
s : Cycle α
hn : Cycle.Nodup s
hs : Cycle.formPerm ↑{ val := s, property := hn } (_ : Cycle.Nodup ↑{ val := s, property := hn }) = f
hs' :
∀ (y : { s // Cycle.Nodup s }),
(fun s => Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s) = f) y → y = { val := s, property := hn }
t : Cycle α
ht : Cycle.Nodup t
ht' : Cycle.Nontrivial t
ht'' :
Cycle.formPerm ↑{ val := t, property := (_ : Cycle.Nodup t ∧ Cycle.Nontrivial t) }
(_ : Cycle.Nodup ↑{ val := t, property := (_ : Cycle.Nodup t ∧ Cycle.Nontrivial t) }) =
f
⊢ { val := t, property := (_ : Cycle.Nodup t ∧ Cycle.Nontrivial t) } =
{ val := s, property := (_ : Cycle.Nodup s ∧ Cycle.Nontrivial s) }
[PROOFSTEP]
simpa using hs' ⟨t, ht⟩ ht''
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
f : { s // Cycle.Nodup s ∧ Cycle.Nontrivial s } → { f // IsCycle f } :=
fun s =>
{ val := Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s),
property := (_ : IsCycle (Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s))) }
⊢ Function.Bijective f
[PROOFSTEP]
rw [Function.bijective_iff_existsUnique]
[GOAL]
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
f : { s // Cycle.Nodup s ∧ Cycle.Nontrivial s } → { f // IsCycle f } :=
fun s =>
{ val := Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s),
property := (_ : IsCycle (Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s))) }
⊢ ∀ (b : { f // IsCycle f }), ∃! a, f a = b
[PROOFSTEP]
rintro ⟨f, hf⟩
[GOAL]
case mk
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
f✝ : { s // Cycle.Nodup s ∧ Cycle.Nontrivial s } → { f // IsCycle f } :=
fun s =>
{ val := Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s),
property := (_ : IsCycle (Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s))) }
f : Perm α
hf : IsCycle f
⊢ ∃! a, f✝ a = { val := f, property := hf }
[PROOFSTEP]
simp only [Subtype.ext_iff]
[GOAL]
case mk
α : Type u_1
inst✝¹ : Fintype α
inst✝ : DecidableEq α
f✝ : { s // Cycle.Nodup s ∧ Cycle.Nontrivial s } → { f // IsCycle f } :=
fun s =>
{ val := Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s),
property := (_ : IsCycle (Cycle.formPerm ↑s (_ : Cycle.Nodup ↑s))) }
f : Perm α
hf : IsCycle f
⊢ ∃! a, Cycle.formPerm ↑a (_ : Cycle.Nodup ↑a) = f
[PROOFSTEP]
exact hf.existsUnique_cycle_nontrivial_subtype
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#@created: 07.09.2010
#@author: Aleksey Komissarov
#@contact: [email protected]
""" Edit distance functions.
- _delta(a,b) -> True/False
- get_pos(L,d) -> [positions]
- get_ed_similarity(s1,s2, monomer_mode=False, full_info=False, verbose=False) -> %sim
- get_edit_distance_info(s1,s2, verbose=False, monomer_mode=False) -> (r_str, pos, d, d*100/len1, n, len1, len2)
"""
import numpy
import re
def _delta(a, b):
''' Compare two elements, if one element equal "-", than return False.'''
if a == "-" or b == "-":
return False
elif a == b:
return True
else:
return False
def get_pos(L, d):
''' Return list of element (*d*) positions in given list.'''
l = L[:]
pos = []
i = 0
while d in l:
pos.append(l.index(d) + i)
l.remove(d)
i += 1
return pos
def get_ed_similarity(s1, s2, monomer_mode=False, full_info=False, verbose=False):
''' Return edit distance between two given strings.
Edit distance dynamic programming implementation
Length of second sequence does not change similarity value.
- monomer mode: double short monomer sequence if len2/len1 < 2
- full_info: boolean, return full information
Return: percent of ED similarity, or if full_info (distance, number of d, positions of d, S matrix)
'''
len1 = len(s1)
len2 = len(s2)
if len1 == 0 or len2 == 0:
return 0.0
if len1 > len2:
(s1, s2) = (s2, s1)
(len1, len2) = (len2, len1)
if monomer_mode:
r = len2 / float(len1)
if r < 2:
s2 = s2 * 2
len2 = len2 * 2
S = numpy.zeros(shape=(len1 + 1, len2 + 1))
for j in range(1, len2 + 1):
S[0, j] = S[0, j - 1] + _delta("-", s2[j - 1])
for i in range(1, len1 + 1):
if verbose:
print("%.2f" % (float(i) / len1))
S[i, 0] = S[i - 1, 0] + _delta(s1[i - 1], "-")
for j in range(1, len2 + 1):
S[i, j] = max(S[i - 1, j - 1] + _delta(s1[i - 1], s2[j - 1]),
S[i - 1, j] + _delta(s1[i - 1], "-"),
S[i - 1, j - 1] + _delta("-", s2[j - 1])
)
result = [ S[len1, j] for j in range(1, len2 + 1) ]
d = max(result)
if full_info:
n = result.count(d)
pos = get_pos(result, d)
for i in range(0, len(pos)):
pos[i] = pos[i] + 1 - len1
return (d, n, pos, S)
return float(d) * 100 / len1
def get_edit_distance_info(s1, s2, verbose=False, monomer_mode=False):
''' Return two sequences edit distance full information.
- s1: sequence of tandem repeat monomer
- s2: sequence of tandem repeat monomer
- verbose: boolean
- monomer mode: double short monomer sequence if len2/len1 < 2
Return: ("max_sim Nmax_sim %sim pos_list", pos_list, all_result, length seq1, length seq2)
'''
len1 = len(s1)
len2 = len(s2)
if len1 == 0 or len2 == 0:
return ("", [], 0, 0.0, 0, 0, 0)
if len1 > len2:
(s1, s2) = (s2, s1)
(len1, len2) = (len2, len1)
(d, n, pos, S) = get_ed_similarity(s1, s2, full_info=True, verbose=verbose)
# Create output string
# (max_sim, N max_sim, %sim, pos_list)
r_str = "%s\t%s\t%s\t%s\t" % (d, n, d * 100 / len1, str(pos))
# Return ("max_sim\tNmax_sim\t%sim\tpos_list", pos_list, sim, %sim, n, length seq1, length seq2)
return (r_str, pos, d, d * 100 / len1, n, len1, len2)
def get_edit_distance(s1, s2):
''' Return ED valie for two sequences.'''
return int(get_ed_similarity(s1, s2, monomer_mode=False, full_info=True)[0])
def get_edit_distance_row(s1, s2):
''' Get last row of ED matrix between two strings.'''
return get_ed_similarity(s1, s2, monomer_mode=False, full_info=True)[-1][-1]
def hamming_distance(s1, s2):
""" Get Hamming distance: the number of corresponding symbols that differs in given strings.
"""
return sum(i != j for i, j in zip(s1, s2))
|
[STATEMENT]
lemma multpw_mult1_commute:
assumes compat: "s O ns \<subseteq> s" and reflns: "refl ns"
shows "mult1 s O multpw ns \<subseteq> multpw ns O mult1 s"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. mult1 s O multpw ns \<subseteq> multpw ns O mult1 s
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. mult1 s O multpw ns \<subseteq> multpw ns O mult1 s
[PROOF STEP]
{
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. mult1 s O multpw ns \<subseteq> multpw ns O mult1 s
[PROOF STEP]
fix X Y Z
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. mult1 s O multpw ns \<subseteq> multpw ns O mult1 s
[PROOF STEP]
assume 1: "(X, Y) \<in> mult1 s" "(Y, Z) \<in> multpw ns"
[PROOF STATE]
proof (state)
this:
(X, Y) \<in> mult1 s
(Y, Z) \<in> multpw ns
goal (1 subgoal):
1. mult1 s O multpw ns \<subseteq> multpw ns O mult1 s
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
(X, Y) \<in> mult1 s
(Y, Z) \<in> multpw ns
[PROOF STEP]
obtain X' Y' y where 2: "X = Y' + X'" "Y = add_mset y Y'" "\<forall>x. x \<in># X' \<longrightarrow> (x, y) \<in> s"
[PROOF STATE]
proof (prove)
using this:
(X, Y) \<in> mult1 s
(Y, Z) \<in> multpw ns
goal (1 subgoal):
1. (\<And>Y' X' y. \<lbrakk>X = Y' + X'; Y = add_mset y Y'; \<forall>x. x \<in># X' \<longrightarrow> (x, y) \<in> s\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (auto simp: mult1_def)
[PROOF STATE]
proof (state)
this:
X = Y' + X'
Y = add_mset y Y'
\<forall>x. x \<in># X' \<longrightarrow> (x, y) \<in> s
goal (1 subgoal):
1. mult1 s O multpw ns \<subseteq> multpw ns O mult1 s
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
X = Y' + X'
Y = add_mset y Y'
\<forall>x. x \<in># X' \<longrightarrow> (x, y) \<in> s
goal (1 subgoal):
1. mult1 s O multpw ns \<subseteq> multpw ns O mult1 s
[PROOF STEP]
obtain Z' z where 3: "Z = add_mset z Z'" "(y, z) \<in> ns" "(Y', Z') \<in> multpw ns"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>z Z'. \<lbrakk>Z = add_mset z Z'; (y, z) \<in> ns; (Y', Z') \<in> multpw ns\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using 1(2) 2(2)
[PROOF STATE]
proof (prove)
using this:
(Y, Z) \<in> multpw ns
Y = add_mset y Y'
goal (1 subgoal):
1. (\<And>z Z'. \<lbrakk>Z = add_mset z Z'; (y, z) \<in> ns; (Y', Z') \<in> multpw ns\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (auto elim: multpw_split1R)
[PROOF STATE]
proof (state)
this:
Z = add_mset z Z'
(y, z) \<in> ns
(Y', Z') \<in> multpw ns
goal (1 subgoal):
1. mult1 s O multpw ns \<subseteq> multpw ns O mult1 s
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
Z = add_mset z Z'
(y, z) \<in> ns
(Y', Z') \<in> multpw ns
goal (1 subgoal):
1. mult1 s O multpw ns \<subseteq> multpw ns O mult1 s
[PROOF STEP]
have "\<forall>x. x \<in># X' \<longrightarrow> (x, z) \<in> s"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x. x \<in># X' \<longrightarrow> (x, z) \<in> s
[PROOF STEP]
using 2(3) 3(2) compat
[PROOF STATE]
proof (prove)
using this:
\<forall>x. x \<in># X' \<longrightarrow> (x, y) \<in> s
(y, z) \<in> ns
s O ns \<subseteq> s
goal (1 subgoal):
1. \<forall>x. x \<in># X' \<longrightarrow> (x, z) \<in> s
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
\<forall>x. x \<in># X' \<longrightarrow> (x, z) \<in> s
goal (1 subgoal):
1. mult1 s O multpw ns \<subseteq> multpw ns O mult1 s
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
X = Y' + X'
Y = add_mset y Y'
\<forall>x. x \<in># X' \<longrightarrow> (x, y) \<in> s
Z = add_mset z Z'
(y, z) \<in> ns
(Y', Z') \<in> multpw ns
\<forall>x. x \<in># X' \<longrightarrow> (x, z) \<in> s
[PROOF STEP]
have "\<exists>Y'. (X, Y') \<in> multpw ns \<and> (Y', Z) \<in> mult1 s"
[PROOF STATE]
proof (prove)
using this:
X = Y' + X'
Y = add_mset y Y'
\<forall>x. x \<in># X' \<longrightarrow> (x, y) \<in> s
Z = add_mset z Z'
(y, z) \<in> ns
(Y', Z') \<in> multpw ns
\<forall>x. x \<in># X' \<longrightarrow> (x, z) \<in> s
goal (1 subgoal):
1. \<exists>Y'. (X, Y') \<in> multpw ns \<and> (Y', Z) \<in> mult1 s
[PROOF STEP]
unfolding mult1_def
[PROOF STATE]
proof (prove)
using this:
X = Y' + X'
Y = add_mset y Y'
\<forall>x. x \<in># X' \<longrightarrow> (x, y) \<in> s
Z = add_mset z Z'
(y, z) \<in> ns
(Y', Z') \<in> multpw ns
\<forall>x. x \<in># X' \<longrightarrow> (x, z) \<in> s
goal (1 subgoal):
1. \<exists>Y'. (X, Y') \<in> multpw ns \<and> (Y', Z) \<in> {(N, M). \<exists>a M0 K. M = add_mset a M0 \<and> N = M0 + K \<and> (\<forall>b. b \<in># K \<longrightarrow> (b, a) \<in> s)}
[PROOF STEP]
using refl_multpw[OF reflns]
[PROOF STATE]
proof (prove)
using this:
X = Y' + X'
Y = add_mset y Y'
\<forall>x. x \<in># X' \<longrightarrow> (x, y) \<in> s
Z = add_mset z Z'
(y, z) \<in> ns
(Y', Z') \<in> multpw ns
\<forall>x. x \<in># X' \<longrightarrow> (x, z) \<in> s
refl (multpw ns)
goal (1 subgoal):
1. \<exists>Y'. (X, Y') \<in> multpw ns \<and> (Y', Z) \<in> {(N, M). \<exists>a M0 K. M = add_mset a M0 \<and> N = M0 + K \<and> (\<forall>b. b \<in># K \<longrightarrow> (b, a) \<in> s)}
[PROOF STEP]
by (intro exI[of _ "Z' + X'"]) (auto intro: multpw_add simp: refl_on_def)
[PROOF STATE]
proof (state)
this:
\<exists>Y'. (X, Y') \<in> multpw ns \<and> (Y', Z) \<in> mult1 s
goal (1 subgoal):
1. mult1 s O multpw ns \<subseteq> multpw ns O mult1 s
[PROOF STEP]
}
[PROOF STATE]
proof (state)
this:
\<lbrakk>(?X2, ?Y2) \<in> mult1 s; (?Y2, ?Z2) \<in> multpw ns\<rbrakk> \<Longrightarrow> \<exists>Y'. (?X2, Y') \<in> multpw ns \<and> (Y', ?Z2) \<in> mult1 s
goal (1 subgoal):
1. mult1 s O multpw ns \<subseteq> multpw ns O mult1 s
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<lbrakk>(?X2, ?Y2) \<in> mult1 s; (?Y2, ?Z2) \<in> multpw ns\<rbrakk> \<Longrightarrow> \<exists>Y'. (?X2, Y') \<in> multpw ns \<and> (Y', ?Z2) \<in> mult1 s
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>(?X2, ?Y2) \<in> mult1 s; (?Y2, ?Z2) \<in> multpw ns\<rbrakk> \<Longrightarrow> \<exists>Y'. (?X2, Y') \<in> multpw ns \<and> (Y', ?Z2) \<in> mult1 s
goal (1 subgoal):
1. mult1 s O multpw ns \<subseteq> multpw ns O mult1 s
[PROOF STEP]
by fast
[PROOF STATE]
proof (state)
this:
mult1 s O multpw ns \<subseteq> multpw ns O mult1 s
goal:
No subgoals!
[PROOF STEP]
qed |
/* rng/lecuyer21.c
*
* 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.
*/
/*
* This generator is taken from
*
* Donald E. Knuth
* The Art of Computer Programming
* Volume 2
* Third Edition
* Addison-Wesley
* Page 108
*
* This implementation copyright (C) 2001 Brian Gough, Carlo Perassi
* and (C) 2003 Heiko Bauke.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#define AAA 40692
#define MMM 2147483399UL
#define QQQ 52774
#define RRR 3791
static inline unsigned long int ran_get (void *vstate);
static double ran_get_double (void *vstate);
static void ran_set (void *state, unsigned long int s);
typedef struct
{
unsigned long int x;
}
ran_state_t;
static inline unsigned long int
ran_get (void *vstate)
{
ran_state_t *state = (ran_state_t *) vstate;
long int y = state->x;
long int r = RRR * (y / QQQ);
y = AAA * (y % QQQ) - r;
if (y < 0)
y += MMM;
state->x = y;
return state->x;
}
static double
ran_get_double (void *vstate)
{
ran_state_t *state = (ran_state_t *) vstate;
return ran_get (state) / 2147483399.0;
}
static void
ran_set (void *vstate, unsigned long int s)
{
ran_state_t *state = (ran_state_t *) vstate;
if ((s%MMM) == 0)
s = 1; /* default seed is 1 */
state->x = s % MMM;
return;
}
static const gsl_rng_type ran_type = {
"lecuyer21", /* name */
MMM-1, /* RAND_MAX */
1, /* RAND_MIN */
sizeof (ran_state_t),
&ran_set,
&ran_get,
&ran_get_double
};
const gsl_rng_type *gsl_rng_lecuyer21 = &ran_type;
|
[STATEMENT]
lemma frontier_cbox:
fixes a b :: "'a::euclidean_space"
shows "frontier (cbox a b) = cbox a b - box a b"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. frontier (cbox a b) = cbox a b - box a b
[PROOF STEP]
unfolding frontier_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. closure (cbox a b) - interior (cbox a b) = cbox a b - box a b
[PROOF STEP]
unfolding interior_cbox and closure_closed[OF closed_cbox]
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cbox a b - box a b = cbox a b - box a b
[PROOF STEP]
.. |
[GOAL]
C : Type u_1
D : Type u_2
inst✝⁵ : Category.{?u.129, u_1} C
inst✝⁴ : Category.{?u.133, u_2} D
inst✝³ : MonoidalCategory C
inst✝² : MonoidalCategory D
F : MonoidalFunctor C D
inst✝¹ : Faithful F.toFunctor
X Y : C
eval : Y ⊗ X ⟶ 𝟙_ C
coeval : 𝟙_ C ⟶ X ⊗ Y
inst✝ : ExactPairing (F.obj X) (F.obj Y)
map_eval : F.map eval = inv (LaxMonoidalFunctor.μ F.toLaxMonoidalFunctor Y X) ≫ ε_ (F.obj X) (F.obj Y) ≫ F.ε
map_coeval : F.map coeval = inv F.ε ≫ η_ (F.obj X) (F.obj Y) ≫ LaxMonoidalFunctor.μ F.toLaxMonoidalFunctor X Y
⊢ F.map ((𝟙 Y ⊗ coeval) ≫ (α_ Y X Y).inv ≫ (eval ⊗ 𝟙 Y)) = F.map ((ρ_ Y).hom ≫ (λ_ Y).inv)
[PROOFSTEP]
simp [map_eval, map_coeval, MonoidalFunctor.map_tensor]
[GOAL]
C : Type u_1
D : Type u_2
inst✝⁵ : Category.{?u.129, u_1} C
inst✝⁴ : Category.{?u.133, u_2} D
inst✝³ : MonoidalCategory C
inst✝² : MonoidalCategory D
F : MonoidalFunctor C D
inst✝¹ : Faithful F.toFunctor
X Y : C
eval : Y ⊗ X ⟶ 𝟙_ C
coeval : 𝟙_ C ⟶ X ⊗ Y
inst✝ : ExactPairing (F.obj X) (F.obj Y)
map_eval : F.map eval = inv (LaxMonoidalFunctor.μ F.toLaxMonoidalFunctor Y X) ≫ ε_ (F.obj X) (F.obj Y) ≫ F.ε
map_coeval : F.map coeval = inv F.ε ≫ η_ (F.obj X) (F.obj Y) ≫ LaxMonoidalFunctor.μ F.toLaxMonoidalFunctor X Y
⊢ F.map ((coeval ⊗ 𝟙 X) ≫ (α_ X Y X).hom ≫ (𝟙 X ⊗ eval)) = F.map ((λ_ X).hom ≫ (ρ_ X).inv)
[PROOFSTEP]
simp [map_eval, map_coeval, MonoidalFunctor.map_tensor]
[GOAL]
C : Type u_1
D : Type u_2
inst✝⁶ : Category.{?u.23115, u_1} C
inst✝⁵ : Category.{?u.23119, u_2} D
inst✝⁴ : MonoidalCategory C
inst✝³ : MonoidalCategory D
F : MonoidalFunctor C D
inst✝² : Full F.toFunctor
inst✝¹ : Faithful F.toFunctor
X Y : C
inst✝ : ExactPairing (F.obj X) (F.obj Y)
⊢ F.map (F.preimage (inv (LaxMonoidalFunctor.μ F.toLaxMonoidalFunctor Y X) ≫ ε_ (F.obj X) (F.obj Y) ≫ F.ε)) =
inv (LaxMonoidalFunctor.μ F.toLaxMonoidalFunctor Y X) ≫ ε_ (F.obj X) (F.obj Y) ≫ F.ε
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
D : Type u_2
inst✝⁶ : Category.{?u.23115, u_1} C
inst✝⁵ : Category.{?u.23119, u_2} D
inst✝⁴ : MonoidalCategory C
inst✝³ : MonoidalCategory D
F : MonoidalFunctor C D
inst✝² : Full F.toFunctor
inst✝¹ : Faithful F.toFunctor
X Y : C
inst✝ : ExactPairing (F.obj X) (F.obj Y)
⊢ F.map (F.preimage (inv F.ε ≫ η_ (F.obj X) (F.obj Y) ≫ LaxMonoidalFunctor.μ F.toLaxMonoidalFunctor X Y)) =
inv F.ε ≫ η_ (F.obj X) (F.obj Y) ≫ LaxMonoidalFunctor.μ F.toLaxMonoidalFunctor X Y
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
D : Type u_2
inst✝⁵ : Category.{?u.27280, u_1} C
inst✝⁴ : Category.{?u.27284, u_2} D
inst✝³ : MonoidalCategory C
inst✝² : MonoidalCategory D
F : MonoidalFunctor C D
inst✝¹ : IsEquivalence F.toFunctor
X : C
inst✝ : HasLeftDual (F.obj X)
⊢ ExactPairing ((Functor.inv F.toFunctor).obj ᘁ(F.obj X)) X
[PROOFSTEP]
refine @exactPairingOfFullyFaithful _ _ _ _ _ _ F _ _ _ _ ?_
[GOAL]
C : Type u_1
D : Type u_2
inst✝⁵ : Category.{?u.27280, u_1} C
inst✝⁴ : Category.{?u.27284, u_2} D
inst✝³ : MonoidalCategory C
inst✝² : MonoidalCategory D
F : MonoidalFunctor C D
inst✝¹ : IsEquivalence F.toFunctor
X : C
inst✝ : HasLeftDual (F.obj X)
⊢ ExactPairing (F.obj ((Functor.inv F.toFunctor).obj ᘁ(F.obj X))) (F.obj X)
[PROOFSTEP]
refine @exactPairingCongrLeft _ _ _ _ _ _ ?_ (F.toFunctor.asEquivalence.counitIso.app _)
[GOAL]
C : Type u_1
D : Type u_2
inst✝⁵ : Category.{?u.27280, u_1} C
inst✝⁴ : Category.{?u.27284, u_2} D
inst✝³ : MonoidalCategory C
inst✝² : MonoidalCategory D
F : MonoidalFunctor C D
inst✝¹ : IsEquivalence F.toFunctor
X : C
inst✝ : HasLeftDual (F.obj X)
⊢ ExactPairing ((𝟭 D).obj ᘁ(F.obj X)) (F.obj X)
[PROOFSTEP]
dsimp
[GOAL]
C : Type u_1
D : Type u_2
inst✝⁵ : Category.{?u.27280, u_1} C
inst✝⁴ : Category.{?u.27284, u_2} D
inst✝³ : MonoidalCategory C
inst✝² : MonoidalCategory D
F : MonoidalFunctor C D
inst✝¹ : IsEquivalence F.toFunctor
X : C
inst✝ : HasLeftDual (F.obj X)
⊢ ExactPairing (ᘁ(F.obj X)) (F.obj X)
[PROOFSTEP]
infer_instance
[GOAL]
C : Type u_1
D : Type u_2
inst✝⁵ : Category.{?u.30444, u_1} C
inst✝⁴ : Category.{?u.30448, u_2} D
inst✝³ : MonoidalCategory C
inst✝² : MonoidalCategory D
F : MonoidalFunctor C D
inst✝¹ : IsEquivalence F.toFunctor
X : C
inst✝ : HasRightDual (F.obj X)
⊢ ExactPairing X ((Functor.inv F.toFunctor).obj (F.obj X)ᘁ)
[PROOFSTEP]
refine @exactPairingOfFullyFaithful _ _ _ _ _ _ F _ _ _ _ ?_
[GOAL]
C : Type u_1
D : Type u_2
inst✝⁵ : Category.{?u.30444, u_1} C
inst✝⁴ : Category.{?u.30448, u_2} D
inst✝³ : MonoidalCategory C
inst✝² : MonoidalCategory D
F : MonoidalFunctor C D
inst✝¹ : IsEquivalence F.toFunctor
X : C
inst✝ : HasRightDual (F.obj X)
⊢ ExactPairing (F.obj X) (F.obj ((Functor.inv F.toFunctor).obj (F.obj X)ᘁ))
[PROOFSTEP]
refine @exactPairingCongrRight _ _ _ _ _ _ ?_ (F.toFunctor.asEquivalence.counitIso.app _)
[GOAL]
C : Type u_1
D : Type u_2
inst✝⁵ : Category.{?u.30444, u_1} C
inst✝⁴ : Category.{?u.30448, u_2} D
inst✝³ : MonoidalCategory C
inst✝² : MonoidalCategory D
F : MonoidalFunctor C D
inst✝¹ : IsEquivalence F.toFunctor
X : C
inst✝ : HasRightDual (F.obj X)
⊢ ExactPairing (F.obj X) ((𝟭 D).obj (F.obj X)ᘁ)
[PROOFSTEP]
dsimp
[GOAL]
C : Type u_1
D : Type u_2
inst✝⁵ : Category.{?u.30444, u_1} C
inst✝⁴ : Category.{?u.30448, u_2} D
inst✝³ : MonoidalCategory C
inst✝² : MonoidalCategory D
F : MonoidalFunctor C D
inst✝¹ : IsEquivalence F.toFunctor
X : C
inst✝ : HasRightDual (F.obj X)
⊢ ExactPairing (F.obj X) (F.obj X)ᘁ
[PROOFSTEP]
infer_instance
|
Working with you, we will design your dream kitchen.
At GarLen kitchens, we will also install kitchens and appliances from the high street retailer.
Click here to see our gallery of completed kitchens!
See what we can offer you for your dream kitchen. |
mars <- function(line, trainingData, testData){
#Build MARS model
marsMod <- train(
form = reformulate(".", line),
data = trainingData,
method = "earth",
preProcess= c("center", "scale")
)
#Make predictions
Pred <- predict(marsMod, testData)
#Evaluate predictions
results = rmse(Pred, testData[ ,line])
return(results)
}
lin_reg <- function(line, trainingData, testData){
#Build linear regression model
lmMod <- train(
form = reformulate(".", line),
data = trainingData,
method = "lm",
preProcess= c("center", "scale")
)
#Make predictions
Pred <- predict(lmMod, testData)
#Evaluate predictions
results = rmse(Pred, testData[ ,line])
return(results)
}
ran_forest <- function(line, trainingData, testData){
#Build random forest model
rfMod <- train(
form = reformulate(".", line),
data = trainingData,
method = "ranger",
importance = 'impurity'
)
#Make predictions
Pred <- predict(rfMod, testData)
#Evaluate predictions
results = rmse(Pred, testData[ ,line])
return(results)
}
kNN <- function(line, trainingData, testData){
#Build kNN model
knnMod <- train(
form = reformulate(".", line),
data = trainingData,
method = "knn",
preProcess= c("center", "scale")
)
#Make predictions
Pred <- predict(knnMod, testData)
#Evaluate predictions
results = rmse(Pred, testData[ ,line])
return(results)
}
SVR <- function(line, trainingData, testData){
#Build MARS model
svrMod <- train(
form = reformulate(".", line),
data = trainingData
# method = , # seems to be missing here!
)
#Make predictions
Pred <- predict(svrMod, testData)
#Evaluate predictions
results = rmse(Pred, testData[ ,line])
return(results)
}
# fill in other methods here...
#----------------------------------
#help functions
#Introducing lagged values (default is 24h time lag)
lagged <- function(df, lag=24){
# lag needs to be specified in hours timelag
lagged_data <- df
colnames(lagged_data) <- paste(colnames(lagged_data), ".lag", sep="")
names(lagged_data)[names(lagged_data) == "Time.lag"] <- "Time"
lagged_data$Time <- lagged_data$Time + 60*60 * lag
return(lagged_data)
}
|
## Центральная предельная теорема
```python
import math
import numpy as np
from scipy import stats as sts
from scipy.stats import pareto
import matplotlib.pyplot as plt
%matplotlib inline
```
### Распределение Парето
#### Функция распределения:
\begin{align}
F(x) & = 1-\frac{1}{x^a} , если x >= 1\\
F(x) & = 0 , если x < 1
\end{align}
#### Плотность распределения:
\begin{align}
f(x) & = \frac{a}{x^{a+1}} , если {x >= 1}\\
f(x) & = 0 , если x < 1
\end{align}
#### Генерация выборки объемом 1000
```python
b = 2.62
function = pareto(b)
sample = function.rvs(1000)
#Массив точек для плотности
massive = np.linspace(1,10,1000)
#Плотность
density = function.pdf(massive)
```
#### Гистрограмма выборки и теоретической функции распределения
```python
plt.hist(sample, bins=100, range=(0,10), normed=True)
plt.plot(massive, density, label='density')
plt.xlabel('$X$')
plt.ylabel('$F(x)$/samples')
plt.legend(loc='best')
```
#### Расчет вспомогающих параметров
```python
x_min = 1.0
#Математическое ожидание (среднее)
M = (x_min * b) / (b - 1)
#Дисперсия
D = (M ** 2) * (b / (b - 2))
```
#### При выборках объема 5, 10, 50, 100, 500
```python
numbers = [5, 10, 50, 100, 500]
sample_means_list = {}
D_new_list = {}
sigma_list = {}
norm_list = {}
density_list = {}
for number in numbers:
sample_means_list[number] = np.array([])
index = 1
while index <= 1000:
sample_means = function.rvs(number)
mean = sum(sample_means)/number
sample_means_list[number] = np.append(sample_means_list[number], mean)
index += 1
D_new_list[number] = D / number
sigma_list[number] = math.sqrt(D_new_list[number])
norm_list[number] = sts.norm(M, sigma_list[number])
density_list[number] = norm_list[number].pdf(massive[:500])
```
#### Гистрограммы выборки и теоретической функции распределения при выборке 5, 10, 50, 100, 500
```python
#для выборки 5
number = numbers[0]
plt.hist(sample_means_list[number], bins =100, range=(1,6), normed=True)
plt.plot(massive[:500], density_list[number], label='density n={}'.format(number))
plt.ylabel('samples')
plt.xlabel('$X$')
plt.legend(loc='best')
```
```python
#для выборки 10
number = numbers[1]
plt.hist(sample_means_list[number], bins =200, range=(1,6), normed=True)
plt.plot(massive[:500], density_list[number], label='density n={}'.format(number))
plt.ylabel('samples')
plt.xlabel('$X$')
plt.legend(loc='best')
```
```python
#для выборки 50
number = numbers[2]
plt.hist(sample_means_list[number], bins =500, range=(1,6), normed=True)
plt.plot(massive[:500], density_list[number], label='density n={}'.format(number))
plt.ylabel('samples')
plt.xlabel('$X$')
plt.legend(loc='best')
```
```python
#для выборки 100
number = numbers[3]
plt.hist(sample_means_list[number], bins =1000, range=(1,6), normed=True)
plt.plot(massive[:500], density_list[number], label='density n={}'.format(number))
plt.ylabel('samples')
plt.xlabel('$X$')
plt.legend(loc='best')
```
```python
#для выборки 500
number = numbers[4]
plt.hist(sample_means_list[number], bins =1500, range=(1,6), normed=True)
plt.plot(massive[:500], density_list[number], label='density n={}'.format(number))
plt.ylabel('samples')
plt.xlabel('$X$')
plt.legend(loc='best')
```
#### Параметры
```python
print('Дисперсии: ', D_new_list)
print('Сигмы: ', sigma_list)
print('Нормы: ', norm_list)
#print('Плотности: ', density_list)
```
Дисперсии: {5: 2.2106101056585588, 10: 1.1053050528292794, 50: 0.22106101056585586, 100: 0.11053050528292793, 500: 0.022106101056585586}
Сигмы: {5: 1.4868120613105609, 10: 1.0513348909026463, 50: 0.4701712566351285, 100: 0.3324612838856999, 500: 0.14868120613105607}
Нормы: {5: <scipy.stats._distn_infrastructure.rv_frozen object at 0x7f8d42b6c2e8>, 10: <scipy.stats._distn_infrastructure.rv_frozen object at 0x7f8d42b6c860>, 50: <scipy.stats._distn_infrastructure.rv_frozen object at 0x7f8d42b6ca58>, 100: <scipy.stats._distn_infrastructure.rv_frozen object at 0x7f8d4338cb70>, 500: <scipy.stats._distn_infrastructure.rv_frozen object at 0x7f8d42b6c278>}
#### Выводы
Из информации, представленной на данных графиках, описывающих распределение Парето, видно что с увеличением размера выборки функция сходится и увеличивается точность аппроксимации распределения выборочных средних нормальным. Наиболее точную картину плотности мы можем наблюдать при большей выборке, в нашем случае это размер выборки 500.
|
"""Functional Data Boxplot Module.
This module contains the classes to construct the functional data boxplot and
visualize it.
"""
from abc import ABC, abstractmethod
import math
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from ..depth import ModifiedBandDepth
from ..outliers import _envelopes
from ._utils import (_figure_to_svg, _get_figure_and_axes,
_set_figure_layout_for_fdata, _set_labels)
__author__ = "Amanda Hernando Bernabé"
__email__ = "[email protected]"
class FDataBoxplot(ABC):
"""Abstract class inherited by the Boxplot and SurfaceBoxplot classes.
It the data of the functional boxplot or surface boxplot of a FDataGrid
object, depending on the dimensions of the domain, 1 or 2 respectively.
It forces to both classes, Boxplot and SurfaceBoxplot to conain at least
the median, central and outlying envelopes and a colormap for their
graphical representation, obtained calling the plot method.
"""
@abstractmethod
def __init__(self, factor=1.5):
if factor < 0:
raise ValueError("The number used to calculate the "
"outlying envelope must be positive.")
self._factor = factor
@property
def factor(self):
return self._factor
@property
def fdatagrid(self):
pass
@property
def median(self):
pass
@property
def central_envelope(self):
pass
@property
def non_outlying_envelope(self):
pass
@property
def colormap(self):
return self._colormap
@colormap.setter
def colormap(self, value):
if not isinstance(value, matplotlib.colors.LinearSegmentedColormap):
raise ValueError("colormap must be of type "
"matplotlib.colors.LinearSegmentedColormap")
self._colormap = value
@abstractmethod
def plot(self, chart=None, *, fig=None, axes=None,
n_rows=None, n_cols=None):
pass
def _repr_svg_(self):
fig = self.plot()
plt.close(fig)
return _figure_to_svg(fig)
class Boxplot(FDataBoxplot):
r"""Representation of the functional boxplot.
Class implementing the functionl boxplot which is an informative
exploratory tool for visualizing functional data, as well as its
generalization, the enhanced functional boxplot. Only supports 1
dimensional domain functional data.
Based on the center outward ordering induced by a :ref:`depth measure
<depth-measures>` for functional data, the descriptive statistics of a
functional boxplot are: the envelope of the 50% central region, the median
curve,and the maximum non-outlying envelope. In addition, outliers can be
detected in a functional boxplot by the 1.5 times the 50% central region
empirical rule, analogous to the rule for classical boxplots.
Args:
fdatagrid (FDataGrid): Object containing the data.
depth_method (:ref:`depth measure <depth-measures>`, optional):
Method used to order the data. Defaults to :func:`modified
band depth
<skfda.exploratory.depth.ModifiedBandDepth>`.
prob (list of float, optional): List with float numbers (in the
range from 1 to 0) that indicate which central regions to
represent.
Defaults to [0.5] which represents the 50% central region.
factor (double): Number used to calculate the outlying envelope.
Attributes:
fdatagrid (FDataGrid): Object containing the data.
median (array, (fdatagrid.dim_codomain, ngrid_points)): contains
the median/s.
central_envelope (array, (fdatagrid.dim_codomain, 2, ngrid_points)):
contains the central envelope/s.
non_outlying_envelope (array, (fdatagrid.dim_codomain, 2,
ngrid_points)):
contains the non-outlying envelope/s.
colormap (matplotlib.colors.LinearSegmentedColormap): Colormap from
which the colors to represent the central regions are selected.
envelopes (array, (fdatagrid.dim_codomain * ncentral_regions, 2,
ngrid_points)): contains the region envelopes.
outliers (array, (fdatagrid.dim_codomain, fdatagrid.n_samples)):
contains the outliers.
barcol (string): Color of the envelopes and vertical lines.
outliercol (string): Color of the ouliers.
mediancol (string): Color of the median.
show_full_outliers (boolean): If False (the default) then only the part
outside the box is plotted. If True, complete outling curves are
plotted.
Representation in a Jupyter notebook:
.. jupyter-execute::
from skfda.datasets import make_gaussian_process
from skfda.misc.covariances import Exponential
from skfda.exploratory.visualization import Boxplot
fd = make_gaussian_process(
n_samples=20, cov=Exponential(), random_state=3)
Boxplot(fd)
Examples:
Function :math:`f : \mathbb{R}\longmapsto\mathbb{R}`.
>>> from skfda import FDataGrid
>>> from skfda.exploratory.visualization import Boxplot
>>>
>>> data_matrix = [[1, 1, 2, 3, 2.5, 2],
... [0.5, 0.5, 1, 2, 1.5, 1],
... [-1, -1, -0.5, 1, 1, 0.5],
... [-0.5, -0.5, -0.5, -1, -1, -1]]
>>> grid_points = [0, 2, 4, 6, 8, 10]
>>> fd = FDataGrid(data_matrix, grid_points, dataset_name="dataset",
... argument_names=["x_label"],
... coordinate_names=["y_label"])
>>> Boxplot(fd)
Boxplot(
FDataGrid=FDataGrid(
array([[[ 1. ],
[ 1. ],
[ 2. ],
[ 3. ],
[ 2.5],
[ 2. ]],
[[ 0.5],
[ 0.5],
[ 1. ],
[ 2. ],
[ 1.5],
[ 1. ]],
[[-1. ],
[-1. ],
[-0.5],
[ 1. ],
[ 1. ],
[ 0.5]],
[[-0.5],
[-0.5],
[-0.5],
[-1. ],
[-1. ],
[-1. ]]]),
grid_points=(array([ 0., 2., 4., 6., 8., 10.]),),
domain_range=((0.0, 10.0),),
dataset_name='dataset',
argument_names=('x_label',),
coordinate_names=('y_label',),
...),
median=array([[ 0.5],
[ 0.5],
[ 1. ],
[ 2. ],
[ 1.5],
[ 1. ]]),
central envelope=(array([[-1. ],
[-1. ],
[-0.5],
[ 1. ],
[ 1. ],
[ 0.5]]), array([[ 0.5],
[ 0.5],
[ 1. ],
[ 2. ],
[ 1.5],
[ 1. ]])),
non-outlying envelope=(array([[-1. ],
[-1. ],
[-0.5],
[ 1. ],
[ 1. ],
[ 0.5]]), array([[ 0.5],
[ 0.5],
[ 1. ],
[ 2. ],
[ 1.5],
[ 1. ]])),
envelopes=[(array([[-1. ],
[-1. ],
[-0.5],
[ 1. ],
[ 1. ],
[ 0.5]]), array([[ 0.5],
[ 0.5],
[ 1. ],
[ 2. ],
[ 1.5],
[ 1. ]]))],
outliers=array([ True, False, False, True]))
References:
Sun, Y., & Genton, M. G. (2011). Functional Boxplots. Journal of
Computational and Graphical Statistics, 20(2), 316-334.
https://doi.org/10.1198/jcgs.2011.09224
"""
def __init__(self, fdatagrid, depth_method=ModifiedBandDepth(), prob=[0.5],
factor=1.5):
"""Initialization of the Boxplot class.
Args:
fdatagrid (FDataGrid): Object containing the data.
depth_method (:ref:`depth measure <depth-measures>`, optional):
Method used to order the data. Defaults to :func:`modified
band depth
<skfda.exploratory.depth.ModifiedBandDepth>`.
prob (list of float, optional): List with float numbers (in the
range from 1 to 0) that indicate which central regions to
represent.
Defaults to [0.5] which represents the 50% central region.
factor (double): Number used to calculate the outlying envelope.
"""
FDataBoxplot.__init__(self, factor)
if fdatagrid.dim_domain != 1:
raise ValueError(
"Function only supports FDataGrid with domain dimension 1.")
if sorted(prob, reverse=True) != prob:
raise ValueError(
"Probabilities required to be in descending order.")
if min(prob) < 0 or max(prob) > 1:
raise ValueError("Probabilities must be between 0 and 1.")
self._envelopes = [None] * len(prob)
depth = depth_method(fdatagrid)
indices_descending_depth = (-depth).argsort(axis=0)
# The median is the deepest curve
self._median = fdatagrid[indices_descending_depth[0]
].data_matrix[0, ...]
# Central region and envelope must be computed for outlier detection
central_region = _envelopes._compute_region(
fdatagrid, indices_descending_depth, 0.5)
self._central_envelope = _envelopes._compute_envelope(central_region)
# Non-outlying envelope
non_outlying_threshold = _envelopes._non_outlying_threshold(
self._central_envelope, factor)
predicted_outliers = _envelopes._predict_outliers(
fdatagrid, non_outlying_threshold)
inliers = fdatagrid[predicted_outliers == 0]
self._non_outlying_envelope = _envelopes._compute_envelope(inliers)
# Outliers
self._outliers = _envelopes._predict_outliers(
fdatagrid, self._non_outlying_envelope)
for i, p in enumerate(prob):
region = _envelopes._compute_region(
fdatagrid, indices_descending_depth, p)
self._envelopes[i] = _envelopes._compute_envelope(region)
self._fdatagrid = fdatagrid
self._prob = prob
self._colormap = plt.cm.get_cmap('RdPu')
self.barcol = "blue"
self.outliercol = "red"
self.mediancol = "black"
self._show_full_outliers = False
@property
def fdatagrid(self):
return self._fdatagrid
@property
def median(self):
return self._median
@property
def central_envelope(self):
return self._central_envelope
@property
def non_outlying_envelope(self):
return self._non_outlying_envelope
@property
def envelopes(self):
return self._envelopes
@property
def outliers(self):
return self._outliers
@property
def show_full_outliers(self):
return self._show_full_outliers
@show_full_outliers.setter
def show_full_outliers(self, boolean):
if not isinstance(boolean, bool):
raise ValueError("show_full_outliers must be boolean type")
self._show_full_outliers = boolean
def plot(self, chart=None, *, fig=None, axes=None,
n_rows=None, n_cols=None):
"""Visualization of the functional boxplot of the fdatagrid
(dim_domain=1).
Args:
fig (figure object, optional): figure over with the graphs are
plotted in case ax is not specified. If None and ax is also
None, the figure is initialized.
axes (list of axis objects, optional): axis over where the graphs
are plotted. If None, see param fig.
n_rows(int, optional): designates the number of rows of the figure
to plot the different dimensions of the image. Only specified
if fig and ax are None.
n_cols(int, optional): designates the number of columns of the
figure to plot the different dimensions of the image. Only
specified if fig and ax are None.
Returns:
fig (figure): figure object in which the graphs are plotted.
"""
fig, axes = _get_figure_and_axes(chart, fig, axes)
fig, axes = _set_figure_layout_for_fdata(
self.fdatagrid, fig, axes, n_rows, n_cols)
tones = np.linspace(0.1, 1.0, len(self._prob) + 1, endpoint=False)[1:]
color = self.colormap(tones)
if self.show_full_outliers:
var_zorder = 1
else:
var_zorder = 4
outliers = self.fdatagrid[self.outliers]
for m in range(self.fdatagrid.dim_codomain):
# Outliers
for o in outliers:
axes[m].plot(o.grid_points[0],
o.data_matrix[0, :, m],
color=self.outliercol,
linestyle='--', zorder=1)
for i in range(len(self._prob)):
# central regions
axes[m].fill_between(self.fdatagrid.grid_points[0],
self.envelopes[i][0][..., m],
self.envelopes[i][1][..., m],
facecolor=color[i], zorder=var_zorder)
# outlying envelope
axes[m].plot(self.fdatagrid.grid_points[0],
self.non_outlying_envelope[0][..., m],
self.fdatagrid.grid_points[0],
self.non_outlying_envelope[1][..., m],
color=self.barcol, zorder=4)
# central envelope
axes[m].plot(self.fdatagrid.grid_points[0],
self.central_envelope[0][..., m],
self.fdatagrid.grid_points[0],
self.central_envelope[1][..., m],
color=self.barcol, zorder=4)
# vertical lines
index = math.ceil(self.fdatagrid.ncol / 2)
x = self.fdatagrid.grid_points[0][index]
axes[m].plot([x, x],
[self.non_outlying_envelope[0][..., m][index],
self.central_envelope[0][..., m][index]],
color=self.barcol,
zorder=4)
axes[m].plot([x, x],
[self.non_outlying_envelope[1][..., m][index],
self.central_envelope[1][..., m][index]],
color=self.barcol, zorder=4)
# median sample
axes[m].plot(self.fdatagrid.grid_points[0], self.median[..., m],
color=self.mediancol, zorder=5)
_set_labels(self.fdatagrid, fig, axes)
return fig
def __repr__(self):
"""Return repr(self)."""
return (f"Boxplot("
f"\nFDataGrid={repr(self.fdatagrid)},"
f"\nmedian={repr(self.median)},"
f"\ncentral envelope={repr(self.central_envelope)},"
f"\nnon-outlying envelope={repr(self.non_outlying_envelope)},"
f"\nenvelopes={repr(self.envelopes)},"
f"\noutliers={repr(self.outliers)})").replace('\n', '\n ')
class SurfaceBoxplot(FDataBoxplot):
r"""Representation of the surface boxplot.
Class implementing the surface boxplot. Analogously to the functional
boxplot, it is an informative exploratory tool for visualizing functional
data with domain dimension 2. Nevertheless, it does not implement the
enhanced surface boxplot.
Based on the center outward ordering induced by a
:ref:`depth measure <depth-measures>`
for functional data, it represents the envelope of the
50% central region, the median curve, and the maximum non-outlying
envelope.
Args:
fdatagrid (FDataGrid): Object containing the data.
method (:ref:`depth measure <depth-measures>`, optional): Method
used to order the data. Defaults to :class:`modified band depth
<skfda.exploratory.depth.ModifiedBandDepth>`.
prob (list of float, optional): List with float numbers (in the
range from 1 to 0) that indicate which central regions to
represent.
Defaults to [0.5] which represents the 50% central region.
factor (double): Number used to calculate the outlying envelope.
Attributes:
fdatagrid (FDataGrid): Object containing the data.
median (array, (fdatagrid.dim_codomain, lx, ly)): contains
the median/s.
central_envelope (array, (fdatagrid.dim_codomain, 2, lx, ly)):
contains the central envelope/s.
non_outlying_envelope (array,(fdatagrid.dim_codomain, 2, lx, ly)):
contains the non-outlying envelope/s.
colormap (matplotlib.colors.LinearSegmentedColormap): Colormap from
which the colors to represent the central regions are selected.
boxcol (string): Color of the box, which includes median and central
envelope.
outcol (string): Color of the outlying envelope.
Examples:
Function :math:`f : \mathbb{R^2}\longmapsto\mathbb{R}`.
>>> from skfda import FDataGrid
>>> data_matrix = [[[[1], [0.7], [1]],
... [[4], [0.4], [5]]],
... [[[2], [0.5], [2]],
... [[3], [0.6], [3]]]]
>>> grid_points = [[2, 4], [3, 6, 8]]
>>> fd = FDataGrid(data_matrix, grid_points, dataset_name="dataset",
... argument_names=["x1_label", "x2_label"],
... coordinate_names=["y_label"])
>>> SurfaceBoxplot(fd)
SurfaceBoxplot(
FDataGrid=FDataGrid(
array([[[[ 1. ],
[ 0.7],
[ 1. ]],
[[ 4. ],
[ 0.4],
[ 5. ]]],
[[[ 2. ],
[ 0.5],
[ 2. ]],
[[ 3. ],
[ 0.6],
[ 3. ]]]]),
grid_points=(array([ 2., 4.]), array([ 3., 6., 8.])),
domain_range=((2.0, 4.0), (3.0, 8.0)),
dataset_name='dataset',
argument_names=('x1_label', 'x2_label'),
coordinate_names=('y_label',),
extrapolation=None,
...),
median=array([[[ 1. ],
[ 0.7],
[ 1. ]],
[[ 4. ],
[ 0.4],
[ 5. ]]]),
central envelope=(array([[[ 1. ],
[ 0.7],
[ 1. ]],
[[ 4. ],
[ 0.4],
[ 5. ]]]),
array([[[ 1. ],
[ 0.7],
[ 1. ]],
[[ 4. ],
[ 0.4],
[ 5. ]]])),
outlying envelope=(array([[[ 1. ],
[ 0.7],
[ 1. ]],
[[ 4. ],
[ 0.4],
[ 5. ]]]),
array([[[ 1. ],
[ 0.7],
[ 1. ]],
[[ 4. ],
[ 0.4],
[ 5. ]]])))
References:
Sun, Y., & Genton, M. G. (2011). Functional Boxplots. Journal of
Computational and Graphical Statistics, 20(2), 316-334.
https://doi.org/10.1198/jcgs.2011.09224
"""
def __init__(self, fdatagrid, method=ModifiedBandDepth(), factor=1.5):
"""Initialization of the functional boxplot.
Args:
fdatagrid (FDataGrid): Object containing the data.
method (:ref:`depth measure <depth-measures>`, optional): Method
used to order the data. Defaults to :class:`modified band depth
<skfda.exploratory.depth.ModifiedBandDepth>`.
prob (list of float, optional): List with float numbers (in the
range from 1 to 0) that indicate which central regions to
represent.
Defaults to [0.5] which represents the 50% central region.
factor (double): Number used to calculate the outlying envelope.
"""
FDataBoxplot.__init__(self, factor)
if fdatagrid.dim_domain != 2:
raise ValueError(
"Class only supports FDataGrid with domain dimension 2.")
depth = method(fdatagrid)
indices_descending_depth = (-depth).argsort(axis=0)
# The mean is the deepest curve
self._median = fdatagrid.data_matrix[indices_descending_depth[0]]
# Central region and envelope must be computed for outlier detection
central_region = _envelopes._compute_region(
fdatagrid, indices_descending_depth, 0.5)
self._central_envelope = _envelopes._compute_envelope(central_region)
# Non-outlying envelope
non_outlying_threshold = _envelopes._non_outlying_threshold(
self._central_envelope, factor)
predicted_outliers = _envelopes._predict_outliers(
fdatagrid, non_outlying_threshold)
inliers = fdatagrid[predicted_outliers == 0]
self._non_outlying_envelope = _envelopes._compute_envelope(inliers)
self._fdatagrid = fdatagrid
self.colormap = plt.cm.get_cmap('Greys')
self._boxcol = 1.0
self._outcol = 0.7
@property
def fdatagrid(self):
return self._fdatagrid
@property
def median(self):
return self._median
@property
def central_envelope(self):
return self._central_envelope
@property
def non_outlying_envelope(self):
return self._non_outlying_envelope
@property
def boxcol(self):
return self._boxcol
@boxcol.setter
def boxcol(self, value):
if value < 0 or value > 1:
raise ValueError(
"boxcol must be a number between 0 and 1.")
self._boxcol = value
@property
def outcol(self):
return self._outcol
@outcol.setter
def outcol(self, value):
if value < 0 or value > 1:
raise ValueError(
"outcol must be a number between 0 and 1.")
self._outcol = value
def plot(self, chart=None, *, fig=None, axes=None,
n_rows=None, n_cols=None):
"""Visualization of the surface boxplot of the fdatagrid (dim_domain=2).
Args:
fig (figure object, optional): figure over with the graphs are
plotted in case ax is not specified. If None and ax is also
None, the figure is initialized.
axes (list of axis objects, optional): axis over where the graphs
are plotted. If None, see param fig.
n_rows(int, optional): designates the number of rows of the figure
to plot the different dimensions of the image. Only specified
if fig and ax are None.
n_cols(int, optional): designates the number of columns of the
figure to plot the different dimensions of the image. Only
specified if fig and ax are None.
Returns:
fig (figure): figure object in which the graphs are plotted.
"""
fig, axes = _get_figure_and_axes(chart, fig, axes)
fig, axes = _set_figure_layout_for_fdata(
self.fdatagrid, fig, axes, n_rows, n_cols)
x = self.fdatagrid.grid_points[0]
lx = len(x)
y = self.fdatagrid.grid_points[1]
ly = len(y)
X, Y = np.meshgrid(x, y)
for m in range(self.fdatagrid.dim_codomain):
# mean sample
axes[m].plot_wireframe(X, Y, np.squeeze(self.median[..., m]).T,
rstride=ly, cstride=lx,
color=self.colormap(self.boxcol))
axes[m].plot_surface(X, Y, np.squeeze(self.median[..., m]).T,
color=self.colormap(self.boxcol), alpha=0.8)
# central envelope
axes[m].plot_surface(
X, Y, np.squeeze(self.central_envelope[0][..., m]).T,
color=self.colormap(self.boxcol), alpha=0.5)
axes[m].plot_wireframe(
X, Y, np.squeeze(self.central_envelope[0][..., m]).T,
rstride=ly, cstride=lx,
color=self.colormap(self.boxcol))
axes[m].plot_surface(
X, Y, np.squeeze(self.central_envelope[1][..., m]).T,
color=self.colormap(self.boxcol), alpha=0.5)
axes[m].plot_wireframe(
X, Y, np.squeeze(self.central_envelope[1][..., m]).T,
rstride=ly, cstride=lx,
color=self.colormap(self.boxcol))
# box vertical lines
for indices in [(0, 0), (0, ly - 1), (lx - 1, 0),
(lx - 1, ly - 1)]:
x_corner = x[indices[0]]
y_corner = y[indices[1]]
axes[m].plot(
[x_corner, x_corner], [y_corner, y_corner],
[
self.central_envelope[1][..., m][indices[0],
indices[1]],
self.central_envelope[0][..., m][indices[0],
indices[1]]],
color=self.colormap(self.boxcol))
# outlying envelope
axes[m].plot_surface(
X, Y,
np.squeeze(self.non_outlying_envelope[0][..., m]).T,
color=self.colormap(self.outcol), alpha=0.3)
axes[m].plot_wireframe(
X, Y,
np.squeeze(self.non_outlying_envelope[0][..., m]).T,
rstride=ly, cstride=lx,
color=self.colormap(self.outcol))
axes[m].plot_surface(
X, Y,
np.squeeze(self.non_outlying_envelope[1][..., m]).T,
color=self.colormap(self.outcol), alpha=0.3)
axes[m].plot_wireframe(
X, Y,
np.squeeze(self.non_outlying_envelope[1][..., m]).T,
rstride=ly, cstride=lx,
color=self.colormap(self.outcol))
# vertical lines from central to outlying envelope
x_index = math.floor(lx / 2)
x_central = x[x_index]
y_index = math.floor(ly / 2)
y_central = y[y_index]
axes[m].plot(
[x_central, x_central], [y_central, y_central],
[self.non_outlying_envelope[1][..., m][x_index, y_index],
self.central_envelope[1][..., m][x_index, y_index]],
color=self.colormap(self.boxcol))
axes[m].plot(
[x_central, x_central], [y_central, y_central],
[self.non_outlying_envelope[0][..., m][x_index, y_index],
self.central_envelope[0][..., m][x_index, y_index]],
color=self.colormap(self.boxcol))
_set_labels(self.fdatagrid, fig, axes)
return fig
def __repr__(self):
"""Return repr(self)."""
return ((f"SurfaceBoxplot("
f"\nFDataGrid={repr(self.fdatagrid)},"
f"\nmedian={repr(self.median)},"
f"\ncentral envelope={repr(self.central_envelope)},"
f"\noutlying envelope={repr(self.non_outlying_envelope)})")
.replace('\n', '\n '))
|
Floyd , who broke up with Liz in the episode " Hiatus " , calls Liz to ask if he can have a place to stay , as he has come to visit New York on business . Liz tries to win Floyd back , only for him to lie to her about going home to Cleveland , Ohio . Floyd eventually travels home , and the pair agree to remain friends .
|
-----------------------------------------------------------------------------
-- |
-- Module : Numeric.LinearAlgebra.Vector.Statistics
-- Copyright : Copyright (c) 2010, Patrick Perry <[email protected]>
-- License : BSD3
-- Maintainer : Patrick Perry <[email protected]>
-- Stability : experimental
--
-- Basic multivariate statistics.
--
module Numeric.LinearAlgebra.Vector.Statistics (
-- * Immutable interface
sum,
mean,
weightedSum,
weightedMean,
-- * Mutable interface
addSumTo,
meanTo,
addWeightedSumTo,
weightedMeanTo,
) where
import Prelude hiding ( sum )
import Control.Monad( forM_ )
import Control.Monad.ST( ST )
import Numeric.LinearAlgebra.Types
import Numeric.LinearAlgebra.Vector.Base( Vector )
import Numeric.LinearAlgebra.Vector.STBase( RVector, STVector )
import qualified Numeric.LinearAlgebra.Vector.STBase as V
-- | Returns the sum of the vectors. The first argument gives the dimension
-- of the vectors.
sum :: (BLAS1 e) => Int -> [Vector e] -> Vector e
sum p xs = V.create $ do
s <- V.new_ p
V.clear s
addSumTo s xs
return s
-- | Returns the mean of the vectors. The first argument gives the dimension
-- of the vectors.
mean :: (BLAS1 e) => Int -> [Vector e] -> Vector e
mean p xs = V.create $ do
m <- V.new_ p
meanTo m xs
return m
-- | Returns the weighted sum of the vectors. The first argument gives the
-- dimension of the vectors.
weightedSum :: (BLAS1 e) => Int -> [(e, Vector e)] -> Vector e
weightedSum p wxs = V.create $ do
s <- V.new_ p
V.clear s
addWeightedSumTo s wxs
return s
-- | Returns the weighted mean of the vectors. The first argument gives the
-- dimension of the vectors.
weightedMean :: (BLAS1 e)
=> Int -> [(Double, Vector e)] -> Vector e
weightedMean p wxs = V.create $ do
m <- V.new_ p
weightedMeanTo m wxs
return m
-- | Adds the sum of the vectors to the target vector.
addSumTo :: (RVector v, BLAS1 e) => STVector s e -> [v e] -> ST s ()
addSumTo dst = addWeightedSumTo dst . zip (repeat 1)
-- | Sets the target vector to the mean of the vectors.
meanTo :: (RVector v, BLAS1 e)
=> STVector s e -> [v e] -> ST s()
meanTo dst = weightedMeanTo dst . zip (repeat 1)
-- | Adds the weigthed sum of the vectors to the target vector.
addWeightedSumTo :: (RVector v, BLAS1 e)
=> STVector s e -> [(e, v e)] -> ST s ()
addWeightedSumTo s wxs = do
n <- V.getDim s
err <- V.new n 0
old_s <- V.new_ n
diff <- V.new_ n
val <- V.new_ n
forM_ wxs $ \(w,x) -> do
V.unsafeCopyTo old_s s -- old_s := s
V.unsafeCopyTo val x -- val := w * x
V.scaleM_ w val
V.addTo err err val -- err := err + val
V.addTo s s err -- s := s + err
V.subTo diff old_s s -- diff := old_s - s
V.addTo err diff val -- err := diff + val
-- | Sets the target vector to the weighted mean of the vectors.
weightedMeanTo :: (RVector v, BLAS1 e)
=> STVector s e -> [(Double, v e)] -> ST s ()
weightedMeanTo m wxs = let
go _ _ [] = return ()
go diff w_sum ((w,x):wxs') | w == 0 = go diff w_sum wxs'
| otherwise = let w_sum' = w_sum + w
in do
V.subTo diff x m
V.addWithScaleM_
(realToFrac $ w/w_sum') diff m
go diff w_sum' wxs'
in do
n <- V.getDim m
diff <- V.new_ n
V.clear m
go diff 0 wxs
|
From stdpp Require Export vector.
From iris.algebra Require Export ofe.
From iris.algebra Require Import list.
Set Default Proof Using "Type".
Section ofe.
Context {A : ofeT}.
Instance vec_equiv m : Equiv (vec A m) := equiv (A:=list A).
Instance vec_dist m : Dist (vec A m) := dist (A:=list A).
Definition vec_ofe_mixin m : OfeMixin (vec A m).
Proof. by apply (iso_ofe_mixin vec_to_list). Qed.
Canonical Structure vecC m : ofeT := OfeT (vec A m) (vec_ofe_mixin m).
Global Instance list_cofe `{Cofe A} m : Cofe (vecC m).
Proof.
apply: (iso_cofe_subtype (λ l : list A, length l = m)
(λ l, eq_rect _ (vec A) (list_to_vec l) m) vec_to_list)=> //.
- intros v []. by rewrite /= vec_to_list_of_list.
- intros c. by rewrite (conv_compl 0 (chain_map _ c)) /= vec_to_list_length.
Qed.
Global Instance vnil_discrete : Discrete (@vnil A).
Proof. intros v _. by inv_vec v. Qed.
Global Instance vcons_discrete n x (v : vec A n) :
Discrete x → Discrete v → Discrete (x ::: v).
Proof.
intros ?? v' ?. inv_vec v'=>x' v'. inversion_clear 1.
constructor. by apply discrete. change (v ≡ v'). by apply discrete.
Qed.
Global Instance vec_ofe_discrete m : OfeDiscrete A → OfeDiscrete (vecC m).
Proof. intros ? v. induction v; apply _. Qed.
End ofe.
Arguments vecC : clear implicits.
Typeclasses Opaque vec_dist.
Section proper.
Context {A : ofeT}.
Global Instance vcons_ne n :
Proper (dist n ==> forall_relation (λ x, dist n ==> dist n)) (@vcons A).
Proof. by constructor. Qed.
Global Instance vcons_proper :
Proper (equiv ==> forall_relation (λ x, equiv ==> equiv)) (@vcons A).
Proof. by constructor. Qed.
Global Instance vlookup_ne n m :
Proper (dist n ==> eq ==> dist n) (@Vector.nth A m).
Proof.
intros v. induction v as [|x m v IH]; intros v'; inv_vec v'.
- intros _ x. inv_fin x.
- intros x' v' EQ i ? <-. inversion_clear EQ. inv_fin i=> // i. by apply IH.
Qed.
Global Instance vlookup_proper m :
Proper (equiv ==> eq ==> equiv) (@Vector.nth A m).
Proof.
intros v v' ? x x' ->. apply equiv_dist=> n. f_equiv. by apply equiv_dist.
Qed.
Global Instance vec_to_list_ne m : NonExpansive (@vec_to_list A m).
Proof. by intros v v'. Qed.
Global Instance vec_to_list_proper m : Proper ((≡) ==> (≡)) (@vec_to_list A m).
Proof. by intros v v'. Qed.
End proper.
(** Functor *)
Definition vec_map {A B : ofeT} m (f : A → B) : vecC A m → vecC B m :=
@vmap A B f m.
Lemma vec_map_ext_ne {A B : ofeT} m (f g : A → B) (v : vec A m) n :
(∀ x, f x ≡{n}≡ g x) → vec_map m f v ≡{n}≡ vec_map m g v.
Proof.
intros Hf. eapply (list_fmap_ext_ne f g v) in Hf.
by rewrite -!vec_to_list_map in Hf.
Qed.
Instance vec_map_ne {A B : ofeT} m f n :
Proper (dist n ==> dist n) f →
Proper (dist n ==> dist n) (@vec_map A B m f).
Proof.
intros ? v v' H. eapply list_fmap_ne in H; last done.
by rewrite -!vec_to_list_map in H.
Qed.
Definition vecC_map {A B : ofeT} m (f : A -n> B) : vecC A m -n> vecC B m :=
CofeMor (vec_map m f).
Instance vecC_map_ne {A A'} m :
NonExpansive (@vecC_map A A' m).
Proof. intros n f g ? v. by apply vec_map_ext_ne. Qed.
Program Definition vecCF (F : cFunctor) m : cFunctor := {|
cFunctor_car A B := vecC (cFunctor_car F A B) m;
cFunctor_map A1 A2 B1 B2 fg := vecC_map m (cFunctor_map F fg)
|}.
Next Obligation.
intros F A1 A2 B1 B2 n m f g Hfg. by apply vecC_map_ne, cFunctor_ne.
Qed.
Next Obligation.
intros F m A B l.
change (vec_to_list (vec_map m (cFunctor_map F (cid, cid)) l) ≡ l).
rewrite vec_to_list_map. apply listCF.
Qed.
Next Obligation.
intros F m A1 A2 A3 B1 B2 B3 f g f' g' l.
change (vec_to_list (vec_map m (cFunctor_map F (f ◎ g, g' ◎ f')) l)
≡ vec_map m (cFunctor_map F (g, g')) (vec_map m (cFunctor_map F (f, f')) l)).
rewrite !vec_to_list_map. by apply (cFunctor_compose (listCF F) f g f' g').
Qed.
Instance vecCF_contractive F m :
cFunctorContractive F → cFunctorContractive (vecCF F m).
Proof.
by intros ?? A1 A2 B1 B2 n ???; apply vecC_map_ne; first apply cFunctor_contractive.
Qed.
|
__precompile__(true)
module RationalExtensions
import Base.convert,
Base.promote_rule,
Base.show,
Base.norm,
Base.conj,
Base.*,
Base.//,
Base./,
Base.+,
Base.-,
Base.==
import Primes
export Rad,
Sqrt,
AbstractRational
AbstractRational = Union{Rational,Integer}
immutable Rad{S<:AbstractRational,T<:Integer} <: Real
a::S
b::S
n::T
function Rad{S,T}(a::S,b::S,n::T) where {S,T}
if b == 0 || n == 0
return new(a,convert(S,0),convert(T,1))
end
sgn = sign(n)
d = Primes.factor(abs(n))
for p in keys(d)
b *= p^div(d[p],2)
d[p] = mod(d[p],2)
end
n = isempty(d) ? 1 : prod(p^(d[p]) for p in keys(d))
if sgn * n != 1
return new(a,b,sgn * n)
else
return new(a+b,0,1)
end
end
end
Rad{S<:AbstractRational,T<:Integer}(a::S,b::S,n::T) = Rad{S,T}(a,b,n)
Rad{S<:AbstractRational,U<:AbstractRational,T<:Integer}(a::S,b::U,n::T) = Rad(promote(a,b)...,n)
Rad{S<:AbstractRational,T<:Integer}(a::S,b::S,r::Rational{T}) =
Rad(a,b//denominator(r),numerator(r)*denominator(r))
Sqrt{T<:Integer}(n::T) = Rad{T,T}(zero(n),one(n),n)
Sqrt(r::Rational) = Rad(0,1,r)
Sqrt(x::Rad) = (x.n == 1 ? Sqrt(b(x)) : throw(InexactError()))
Sqrt(x::AbstractFloat) = sqrt(x)
==(x::Rad{S,T},y::Rad{S,T}) where {S,T} = (x.a,x.b,x.n) == (y.a,y.b,y.n)
function *(x::Rad,y::Rad)
if x.n == y.n
return Rad(x.a * y.a + x.b * y.b * x.n, y.a * x.b + y.b * x.a, x.n)
elseif x.a == y.a == 0
return Rad(zero(x.a), x.b * y.b, x.n * y.n)
else
error("Error multiplying radicals: radicands must mutiply to give a perfect square")
end
end
*(x::Bool,y::Rad) = Rad( x * y.a, x * y.b, y.n)
*{T<:AbstractRational}(x::T,y::Rad) = Rad(x * y.a, x * y.b, y.n)
*(x::Rad,y::Bool) = y * x
*{T<:AbstractRational}(x::Rad,y::T) = y * x
function //(x::Rad,y::Rad)
if x.n == y.n || x.b == 0 || y.b == 0
return (x.a * y.a + y.a * x.b * Sqrt(x.n) - x.a * y.b * Sqrt(y.n)
- x.b * y.b * Sqrt(x.n * y.n))//(y.a^2 - y.n * y.b^2)
else
error("Division with different radicands not supported")
end
end
//{T<:AbstractRational}(x::T,y::Rad) = Rad(x,zero(x),one(x)) // y
//{T<:AbstractRational}(x::Rad,y::T) = Rad(x.a//y, x.b//y,x.n)
/(x::Rad,y::Rad) = float(x)/float(y)
/(x::Rad,y::AbstractRational) = convert(typeof(float(y)),x)/float(y)
/{T<:Real}(x::Rad,y::T) = /(promote(x,y)...)
/{T<:Real}(x::T,y::Rad) = /(promote(x,y)...)
function +(x::Rad,y::Rad)
if x.n == y.n || x.b == 0
return Rad(x.a + y.a, x.b+y.b, y.n)
elseif y.b == 0
return Rad(x.a + y.a, x.b, x.n)
else
error("Addition with different radicands not supported")
end
end
-(x::Rad) = Rad(-x.a,-x.b,x.n)
-(x::Rad,y::Rad) = x + (-y)
+{T<:AbstractRational}(x::Rad,y::T) = Rad(x.a + y, x.b, x.n)
+{T<:AbstractRational}(x::T,y::Rad) = y + x
-{T<:AbstractRational}(x::Rad,y::T) = x + (-y)
-{T<:AbstractRational}(x::T,y::Rad) = x + (-y)
convert{S<:AbstractRational,T<:Integer}(::Type{Rad{S,T}},n::Integer) = Rad(n,zero(n),one(n))
convert{S<:AbstractRational,T<:Integer}(::Type{Rad{S,T}},r::Rational) = Rad(r,zero(r),one(r))
convert(::Type{AbstractFloat}, x::Rad) = float(x.a) + float(x.b) * (sqrt∘float)(x.n)
convert{S,T}(::Type{BigFloat},x::Rad{S,T}) = big(x.a) + big(x.b) * (sqrt∘float)(big(x.n))
convert{S<:AbstractFloat,T,U}(::Type{S},x::Rad{T,U}) =
((a,b,n) -> a + b*(sqrt∘float)(n))(promote(x.a,x.b,x.n)...)
convert(::Type{Bool},x::Rad) = (x.b != 0)
convert{T<:Integer}(::Type{T}, x::Rad) = (x.n == 1 ? convert(T,x.a + x.b) : throw(InexactError()))
convert{S<:AbstractRational,T<:Integer}(::Type{Rad{S,T}},x::Rad) =
Rad(convert(S,x.a),convert(S,x.b),convert(T,x.n))
promote_rule{S<:AbstractRational,T<:Integer,U<:Integer}(::Type{Rad{S,T}}, ::Type{U}) =
Rad{S,promote_type(T,U)}
promote_rule{S<:AbstractRational,T<:Integer,U<:Integer}(::Type{Rad{S,T}}, ::Type{Rational{U}}) =
Rad{promote_type(S,U),T}
promote_rule{S<:AbstractRational,T<:Integer,U<:AbstractRational,V<:Integer}(::Type{Rad{S,T}},
::Type{Rad{U,V}}) = Rad{promote_type(S,U),promote_type(T,V)}
promote_rule{T<:Rad}(::Type{BigFloat},::Type{T}) = BigFloat
promote_rule{S<:AbstractFloat,T<:Rad}(::Type{S},::Type{T}) = S
convert(::Type{Rad}, x::Rad) = x
convert(::Type{Rad}, r::AbstractRational) = Rad(r,zero(r),one(r))
conj(x::Rad) = Rad(x.a,-x.b,x.n)
norm(x::Rad) = x * conj(x)
function show(io::IO,x::Rad)
if x == 0
show(io,0)
elseif isa(x.b,Rational)
if x.a != 0
if x.a != 1
show(io,x.a)
else
show(io,numerator(x.a))
end
if sign(x.b) == 1
print(io," + ")
elseif sign(x.b) == -1
print(io," - ")
end
end
if ~in(numerator(x.b),[-1,0,1])
show(io,abs(numerator(x.b)))
end
if x.n != 1
print(io,"√(")
show(io,x.n)
print(io,")")
end
if denominator(x.b) != 1
print(io,"//")
show(io,denominator(x.b))
end
else
if x.a != 0
show(io,x.a)
if sign(x.b) == 1
print(io," + ")
elseif sign(x.b) == -1
print(io," - ")
end
elseif sign(x.b) == -1
print(io,"-")
end
if x.b != 0
if abs(x.b) != 1
show(io,abs(x.b))
end
if x.n != 1
print(io,"√(")
show(io,x.n)
print(io,")")
end
if x.n == 1 && x.b == 1
show(io,1)
end
end
end
end
end # module
|
NY 368 was assigned in the 1930s as a connector between NY 321 and NY 5 in the town of Elbridge by way of the hamlet of Halfway . It remained unchanged until April 1 , 1980 , when ownership and maintenance of the route was transferred from the state of New York to Onondaga County as part of a highway maintenance swap between the two levels of government . The county also assumed ownership and maintenance of the Onondaga County portion of NY 31B as part of the exchange . NY 368 was redesignated as County Route 107 ( CR 107 ) following the swap .
|
{-
This file contains:
- Definition of set quotients
-}
{-# OPTIONS --cubical --no-import-sorts --safe #-}
module Cubical.HITs.SetQuotients.Base where
open import Cubical.Core.Primitives
-- Set quotients as a higher inductive type:
data _/_ {ℓ ℓ'} (A : Type ℓ) (R : A → A → Type ℓ') : Type (ℓ-max ℓ ℓ') where
[_] : (a : A) → A / R
eq/ : (a b : A) → (r : R a b) → [ a ] ≡ [ b ]
squash/ : (x y : A / R) → (p q : x ≡ y) → p ≡ q
|
If $x$ is a point in a perfect metric space, then for every positive real number $r$, there exists a point $a$ such that $a \neq x$ and $d(a,x) < r$. |
Sabrina Simonton was born and raised in Davis, California. She Graduates of the Davis Joint Unified School District graduated from Davis Senior High School Davis High School in 2006 and received a B.A. in Liberal Arts from San Francisco State University in 2010. She enjoys bicycling, playing music, taking photos, and soaking up the sun. She currently works as a Specialist at the Apple Store in downtown San Francisco and earns a little extra on the side as a bike courier for Postmates. When shes not working shes snuggling her adorable mutt, Muenster.
Her music can be found at http://www.soundcloud.com/ponyskull
20051003 23:01:05 nbsp sabrina<3 Users/JoannaSwan
20051017 23:47:40 nbsp hooray for comment boxes!! i dont see you enough YOURE RAD Users/AndresRuiz
20060130 23:29:55 nbsp oh no you didnnt just say that about pump it up nuhtuh Users/TravisGrathwell
20061024 18:08:22 nbsp you graduated from DHS and go to SFSU now Users/StevenDaubert
20070108 21:12:47 nbsp Sara O graduated and is back in davis. girl needs a friend, hooked up with a methhead tattoo loser. she can do better. Even bro and sis made off with her bucks. Glad to see youre makin music... Users/BarbaraClowers
20071103 20:17:52 nbsp I love your music! Just thought I should add that.... Users/StephanieCarlson
20080414 22:27:03 nbsp nice Users/StevenDaubert
20080416 01:26:16 nbsp ....many a horror story....
Does that include OzzFest? Users/DonShor
20080417 21:30:11 nbsp Its ok, I promise I wont post the pictures from that day. What was it, 110 degrees? + 13 hours or so of heavy metal! Da boy is working at Asian Auto now. Users/DonShor
20090916 13:46:23 nbsp is that henna on the legs? Users/StevenDaubert
|
FUNCTION B4000(X,Y,N)
c Returns 4000 A break amplitude for sed in (x,y)
c The break is defined as the ratio of the average Fnu flux densities:
c (4050-4250)/(3750-3950) (Bruzual (1983), Hamilton 1985 ApJ 297, 371).
real x(n),y(n),w(10000),z(10000)
data icall/0/
save i1,i2,i3,i4,j1,j2
b4000=0.
IF (N.EQ.1206.or.N.EQ.1977) THEN
c BC93 (G+S) wavelength scale
if (icall.eq.0) then
icall=1
do i=1,n
c if (x(i).eq.3770.) i1=i
c if (x(i).eq.3800.) i2=i
c if (x(i).eq.3890.) i3=i
c if (x(i).eq.3920.) i4=i
if (x(i).le.3761.) i1=i
if (x(i).eq.3810.) i2=i
if (x(i).eq.3850.) i3=i
if (x(i).eq.3920.) i4=i
if (x(i).eq.4050.) j1=i
if (x(i).eq.4250.) then
j2=i
goto 1
endif
enddo
endif
c Transform to Fnu units
1 i=0
do j=j1,j2
i=i+1
w(i)=x(j)
z(i)=y(j)*x(j)**2
enddo
fr=trapz1(w,z,i)/(x(j2)-x(j1))
i=0
do j=i1,i2
i=i+1
w(i)=x(j)
z(i)=y(j)*x(j)**2
enddo
fl1=trapz1(w,z,i)/(x(i2)-x(i1))
i=0
do j=i3,i4
i=i+1
w(i)=x(j)
z(i)=y(j)*x(j)**2
enddo
fl2=trapz1(w,z,i)/(x(i4)-x(i3))
fl=(fl1+fl2)/2.
b4000=fr/fl
ELSE
c General procedure
if (icall.eq.0) then
c To allow different wavelength scales in same code always locate
c icall=1
call locate (x,n,4050.,i1)
call locate (x,n,4250.,i2)
call locate (x,n,3750.,i3)
call locate (x,n,3950.,i4)
i2=i2+1
i4=i4+1
endif
c Transform to Fnu units
i=0
do j=i1,i2
i=i+1
w(i)=x(j)
z(i)=y(j)*x(j)**2
enddo
fr=trapz1(w,z,i)/(x(i2)-x(i1))
i=0
do j=i3,i4
i=i+1
w(i)=x(j)
z(i)=y(j)*x(j)**2
enddo
fl=trapz1(w,z,i)/(x(i4)-x(i3))
b4000=fr/fl
ENDIF
return
end
FUNCTION B4000VN(X,Y,N)
c MPA definition, via S Charlot
c Returns 4000 A break amplitude for sed in (x,y)
c The break is defined as the ratio of the average Fnu flux densities:
c (4050-4250)/(3750-3950) (Bruzual (1983), Hamilton 1985 ApJ 297, 371).
parameter (jid=35)
real x(n),y(n),w(10000),z(10000)
save i1,i2,i3,i4,j1,j2
c Common to store fluxes
integer iim(jid)
real ffb(jid),ffr(jid),ffc(jid),ffl(jid)
common /fluxes/ iim,ffb,ffr,ffc,ffl
data icall/0/
b4000vn=0.
IF (N.EQ.1206.or.N.EQ.1977) THEN
c BC93 (G+S) wavelength scale
if (icall.eq.0) then
icall=1
do i=1,n
c if (x(i).eq.3770.) i1=i
c if (x(i).eq.3800.) i2=i
c if (x(i).eq.3890.) i3=i
c if (x(i).eq.3920.) i4=i
if (x(i).le.3761.) i1=i
if (x(i).eq.3810.) i2=i
if (x(i).eq.3850.) i3=i
if (x(i).eq.3920.) i4=i
if (x(i).eq.4050.) j1=i
if (x(i).eq.4250.) then
j2=i
goto 1
endif
enddo
endif
c Transform to Fnu units
1 i=0
do j=j1,j2
i=i+1
w(i)=x(j)
z(i)=y(j)*x(j)**2
enddo
fr=trapz1(w,z,i)/(x(j2)-x(j1))
i=0
do j=i1,i2
i=i+1
w(i)=x(j)
z(i)=y(j)*x(j)**2
enddo
fl1=trapz1(w,z,i)/(x(i2)-x(i1))
i=0
do j=i3,i4
i=i+1
w(i)=x(j)
z(i)=y(j)*x(j)**2
enddo
fl2=trapz1(w,z,i)/(x(i4)-x(i3))
fl=(fl1+fl2)/2.
b4000vn=fr/fl
ELSE
c General procedure
if (icall.eq.0) then
c To allow different wavelength scales in same code always locate
c icall=1
call locate (x,n,4000.,i1)
call locate (x,n,4100.,i2)
call locate (x,n,3850.,i3)
call locate (x,n,3950.,i4)
i2=i2+1
i4=i4+1
endif
c Transform to Fnu units
i=0
do j=i1,i2
i=i+1
w(i)=x(j)
z(i)=y(j)*x(j)**2
enddo
fr=trapz1(w,z,i)/(x(i2)-x(i1))
i=0
do j=i3,i4
i=i+1
w(i)=x(j)
z(i)=y(j)*x(j)**2
enddo
fl=trapz1(w,z,i)/(x(i4)-x(i3))
b4000vn=fr/fl
c Store fluxes for future use
iim(31)=-1
ffb(31)=fl
ffr(31)=fr
ffc(31)=b4000vn
ffl(31)=b4000vn
ENDIF
return
end
FUNCTION B4000_SDSS(X,Y,N)
c Returns 4000 A break amplitude for sed in (x,y)
c Uses definition by Stoughton et al. (Ap. J), for SDSS data
real x(n),y(n),w(10000),z(10000)
save i1,i2,i3,i4,j1,j2
data icall/0/
b4000_sdss=0.
IF (N.EQ.1206.or.N.EQ.1977) THEN
c BC93 (G+S) wavelength scale
if (icall.eq.0) then
icall=1
do i=1,n
c if (x(i).eq.3770.) i1=i
c if (x(i).eq.3800.) i2=i
c if (x(i).eq.3890.) i3=i
c if (x(i).eq.3920.) i4=i
if (x(i).le.3761.) i1=i
if (x(i).eq.3810.) i2=i
if (x(i).eq.3850.) i3=i
if (x(i).eq.3920.) i4=i
if (x(i).eq.4050.) j1=i
if (x(i).eq.4250.) then
j2=i
goto 1
endif
enddo
endif
c Transform to Fnu units
1 i=0
do j=j1,j2
i=i+1
w(i)=x(j)
z(i)=y(j)*x(j)**2
enddo
fr=trapz1(w,z,i)/(x(j2)-x(j1))
i=0
do j=i1,i2
i=i+1
w(i)=x(j)
z(i)=y(j)*x(j)**2
enddo
fl1=trapz1(w,z,i)/(x(i2)-x(i1))
i=0
do j=i3,i4
i=i+1
w(i)=x(j)
z(i)=y(j)*x(j)**2
enddo
fl2=trapz1(w,z,i)/(x(i4)-x(i3))
fl=(fl1+fl2)/2.
b4000_sdss=fr/fl
ELSE
c General procedure
if (icall.eq.0) then
c To allow different wavelength scales in same code always locate
c icall=1
call locate (x,n,4051.,i1)
call locate (x,n,4251.,i2)
call locate (x,n,3751.,i3)
call locate (x,n,3951.,i4)
i2=i2+1
i4=i4+1
endif
c Store in new array
i=0
do j=i1,i2
i=i+1
w(i)=x(j)
c Transform to Fnu units
c z(i)=y(j)*x(j)**2
z(i)=y(j)
enddo
fr=trapz1(w,z,i)/(x(i2)-x(i1))
i=0
do j=i3,i4
i=i+1
w(i)=x(j)
c Transform to Fnu units
c z(i)=y(j)*x(j)**2
z(i)=y(j)
enddo
fl=trapz1(w,z,i)/(x(i4)-x(i3))
b4000_sdss=fr/fl
ENDIF
return
end
FUNCTION B4000VN3(X,Y,N)
c Returns 4000 A break amplitude for sed in (x,y)
c The break is defined as the ratio of the average Fnu flux densities:
c (4050-4250)/(3750-3950) (Bruzual (1983), Hamilton 1985 ApJ 297, 371).
c Narrow definition from MPA: the break is defined as the ratio of the
c average Fnu flux densities: (4000-4100)/(3850-3950)
c Array declaration
real x(n),y(n),w(10000),z(10000)
b4000vn=0.
c Find length of sed to be transformed to Fnu
call locate (x,n,3850.,i1)
call locate (x,n,4100.,i2)
c Transform to Fnu units
i=0
do j=i1-10,i2+10
i=i+1
w(i)=x(j)
z(i)=y(j)*x(j)**2
write (21,*) w(i),z(i),y(j)
enddo
c Compute average flux on the red side
x1=4000.
x2=4100.
fr = trapz2(w,z,i,x1,x2,ierr)/(x2-x1)
c Compute average flux on the blue side
x1=3850.
x2=3950.
fb = trapz2(w,z,i,x1,x2,ierr)/(x2-x1)
c Compute b4000
b4000vn3=fr/fb
write (6,*) fr,fb,b4000vn3
write (21,*) fr,fb,b4000vn3
return
end
|
[STATEMENT]
lemma expands_to_max_lt:
assumes "(g expands_to G) basis" "eventually (\<lambda>x. f x < g x) at_top"
shows "((\<lambda>x. max (f x) (g x)) expands_to G) basis"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ((\<lambda>x. max (f x) (g x)) expands_to G) basis
[PROOF STEP]
using assms(1)
[PROOF STATE]
proof (prove)
using this:
(g expands_to G) basis
goal (1 subgoal):
1. ((\<lambda>x. max (f x) (g x)) expands_to G) basis
[PROOF STEP]
by (rule expands_to_cong) (insert assms(2), auto simp: max_def elim: eventually_mono) |
/-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import ring_theory.integrally_closed
import ring_theory.valuation.integers
/-!
# Integral elements over the ring of integers of a valution
The ring of integers is integrally closed inside the original ring.
-/
universes u v w
open_locale big_operators
namespace valuation
namespace integers
section comm_ring
variables {R : Type u} {Γ₀ : Type v} [comm_ring R] [linear_ordered_comm_group_with_zero Γ₀]
variables {v : valuation R Γ₀} {O : Type w} [comm_ring O] [algebra O R] (hv : integers v O)
include hv
open polynomial
lemma mem_of_integral {x : R} (hx : is_integral O x) : x ∈ v.integer :=
let ⟨p, hpm, hpx⟩ := hx in le_of_not_lt $ λ (hvx : 1 < v x), begin
rw [hpm.as_sum, eval₂_add, eval₂_pow, eval₂_X, eval₂_finset_sum, add_eq_zero_iff_eq_neg] at hpx,
replace hpx := congr_arg v hpx, refine ne_of_gt _ hpx,
rw [v.map_neg, v.map_pow],
refine v.map_sum_lt' (zero_lt_one₀.trans_le (one_le_pow_of_one_le' hvx.le _)) (λ i hi, _),
rw [eval₂_mul, eval₂_pow, eval₂_C, eval₂_X, v.map_mul, v.map_pow, ← one_mul (v x ^ p.nat_degree)],
cases (hv.2 $ p.coeff i).lt_or_eq with hvpi hvpi,
{ exact mul_lt_mul₀ hvpi (pow_lt_pow₀ hvx $ finset.mem_range.1 hi) },
{ erw hvpi, rw [one_mul, one_mul], exact pow_lt_pow₀ hvx (finset.mem_range.1 hi) }
end
protected lemma integral_closure : integral_closure O R = ⊥ :=
bot_unique $ λ r hr, let ⟨x, hx⟩ := hv.3 (hv.mem_of_integral hr) in algebra.mem_bot.2 ⟨x, hx⟩
end comm_ring
section fraction_field
variables {K : Type u} {Γ₀ : Type v} [field K] [linear_ordered_comm_group_with_zero Γ₀]
variables {v : valuation K Γ₀} {O : Type w} [comm_ring O] [is_domain O]
variables [algebra O K] [is_fraction_ring O K]
variables (hv : integers v O)
lemma integrally_closed : is_integrally_closed O :=
(is_integrally_closed.integral_closure_eq_bot_iff K).mp (valuation.integers.integral_closure hv)
end fraction_field
end integers
end valuation
|
# Sample program to write raster-format data.
# Create our file:
from osgeo import gdal
driver = gdal.GetDriverByName("GTiff")
dstFile = driver.Create("Example Raster.tiff", 360, 180, 1, gdal.GDT_Int16)
# Define the projection:
from osgeo import osr
spatialReference = osr.SpatialReference()
spatialReference.SetWellKnownGeogCS("WGS84")
dstFile.SetProjection(spatialReference.ExportToWkt())
# Set the georeferencing transform:
originX = -180
originY = 90
cellWidth = 1.0
cellHeight = 1.0
dstFile.SetGeoTransform([originX, cellWidth, 0,
originY, 0, -cellHeight])
# Get the raster band:
band = dstFile.GetRasterBand(1)
# Generate the random values to store:
import random
values = []
for row in range(180):
row_data = []
for col in range(360):
row_data.append(random.randint(1, 100))
values.append(row_data)
# Write our data using "struct":
import struct
fmt = "<" + ("h" * band.XSize)
for row in range(180):
scanline = struct.pack(fmt, *values[row])
band.WriteRaster(0, row, 360, 1, scanline)
# Alternatively, write our data using NumPy:
#import numpy
#
#array = numpy.array(values, dtype=numpy.int16)
#band.WriteArray(array)
|
and supporting others in reaching their dreams is the best way of life.
Sebastian is an international presenter and co-founder of fitnessschool.tv. He inspires people with his spirited, thrilling and humorous way. He is a graduate of Physiotherapy at the Krakow Sports Academy in Poland and lives in Berlin today. “Unusual” – that’s how we can describe his personality and talent. In 2003 he received the title of “The Best IFAA Master Instructor.” Since then he collects experience on the biggest stages in over 35 countries. He trains and advises instructors worldwide on their way to success.
Since 2018 he is involved in Network Marketing. He promotes best products, leads growing team and helps others become as successful in this business as he is.
I am a person of many talents. Grateful to be able do so many wonderful things in my life. with love for every detail.
Every fitness instructor or presenter need some good inspiration. And that’s what fitnessschool.tv has been created for. To inspire, motivate and help each member get better and more professional in his group fitness classes.
We love fitness and we love to give our knowledge and experience to others. Here at fitnessschool.tv, we believe in lifelong learning. We believe that education is power and that knowledge creates opportunities. Good fitness should be accessible to everyone. Our goal is to make everything we know available to you so that you can reach for your creative and career goals. |
function F = diff(F, dim, n)
%DIFF Componentwise derivative of a SPHEREFUNV.
% DIFF(F) is the tangetial derivative of each component of F in
% x-direction.
%
% DIFF(F, DIM) is the first tangential derivative of F along the
% dimension DIM.
% DIM = 1 (default) is the derivative in the x-direction.
% DIM = 2 is the derivative in the y-direction.
% DIM = 3 is the derivative in the z-direction.
%
% DIFF(F, DIM, N) is the Nth tangential derivative of each component of F
% along the dimension specified.
%
% See also SPHEREFUNV/CURL and SPHEREFUNV/DIV.
% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.
% Empty check:
if ( isempty(F) )
return
end
% Defaults:
if ( nargin == 1 || isempty(dim) )
dim = 1;
end
if ( nargin < 3 )
n = 1;
end
% Diff each component.
for j = 1:F.nComponents
F.components{j} = diff(F.components{j}, dim, n);
end
end
|
# Additive Secret Sharing
Author:
- Carlos Salgado - [email](mailto:[email protected]) - [linkedin](https://www.linkedin.com/in/eng-socd/) - [github](https://github.com/socd06)
## Additive Secret Sharing
Additive Secret Sharing is a mechanism to share data among parties and to perform computation on it.
## Sharing
A secret `s` is uniformly split into `n` shares, one per shareholder (also known as worker, node, user or party) using some randomness `r`, also known as some **very high random prime** number `Q`.
$ F_s (s, r, n) = ( s_1, s_2, ..., s_n ) $
## Reconstruction
`s` can be reconstructed (decrypted) by adding up **all the shares** and taking the [*modulo*](https://en.wikipedia.org/wiki/Modulo_operation) of the random prime number `Q`, used to encrypt the shares originally.
$ s = ( \: \sum \limits _{i=1} ^n s_i \: ) \; mod \; Q $
## 32-bit Integer Secrets
A secret is the data or message that a party wants to secure. In additive secret sharing, secrets (and therefore, shares) must be members of a fixed [finite field](https://en.wikipedia.org/wiki/Finite_field). Particularly, the literature mentions shares should be members of the $ {\mathbb{Z}_{2^{32}}} $ [ring](https://en.wikipedia.org/wiki/Ring_(mathematics)), which is the [ring of integers](https://en.wikipedia.org/wiki/Ring_of_integers) that fit within [32-bits](https://en.wikipedia.org/wiki/32-bit_computing).
Rings are [sets](https://en.wikipedia.org/wiki/Set_(mathematics)) with two operations, addition and multiplication, which allow the rationale of secret sharing and reconstruction to work.
Plainly, secrets and secret shares **must** be integers within -2,147,483,647 to +2,147,483,647
## Governance
Additive secret sharing provides shared governance. The threshold `t` to reconstruct `s` is equal to `n`, which means **no party can recover the data** alone because all the shares are required to decrypt the secret *(t = n)*. This scheme allows us to do computation on the shares while each shareholder is only aware of their **own** share.
### [Quiz] Find the secret `s`
In practice, we use a **very high prime number** Q to add a **big deal of uniform randomness** to our shares. Here we will use a very small Q, so you can try to solve the quiz without programming yet.
Let $ s_1 = 10 \; and \; s_2 = 74 \; and \; Q = 59 $
What is the original secret `s`? Fill the ____ space below with your answer.
Try **not** to use a calculator or programming.
```python
# Run this cell to import the quizzes
from quiz import q0, q1, q2
```
```python
# run to check your answer
q0.check(___)
```
```python
# Uncomment the line below to see a hint
# q0.hint
```
```python
# Uncomment the line below to see the solution
# q0.solution
```
### [Quiz] Find the final share s<sub>2</sub>
Using a small `Q` to facilitate calculation (it needs to be a **very high prime number** in production), let
$ s = 7, n = 2 $ with $ Q = 59 $ and $ s_1 = 9 $
plugged in on the secret reconstruction equation, find the final share s<sub>2</sub>.
Fill the ____ space below with your answer. Feel free to implement the equation in a new cell or use whatever tool you'd like (e.g. a calculator), it's your call.
```python
# Fill the ____ space below with your answer
final_share =
# run to check your answer
q1.check(final_share)
```
```python
# Uncomment the line below to see a hint
# q1.hint
```
```python
# Uncomment the line below to see the solution
# q1.solution
```
## In Practice
Just as an educational example, we can generate a list of prime numbers using [sympy](https://www.sympy.org/en/index.html)
```python
# Verify we have all the tools we need to run the notebook
!pip install -r requirements.txt
```
```python
import sympy
# An arbitrary constant, feel free to play with it
CONST = 999
BIT_DEPTH = 31
# Range start
start = 2**BIT_DEPTH-CONST
# Maximum in Z2**32 ring
end = 2**BIT_DEPTH
prime_lst = list(sympy.primerange(start,end+1))
print("Prime numbers in range: " , prime_lst)
```
And **randomly** choose one every time using [NumPy](https://numpy.org/devdocs/contents.html)'s [randint](https://numpy.org/doc/stable/reference/random/generated/numpy.random.randint.html)
```python
from numpy.random import randint
Q = prime_lst[randint(len(prime_lst))]
Q
```
As an additional note, the [Secrets module](https://docs.python.org/3/library/secrets.html), introduced in Python 3.6, provides randomness as secure as your operating system.
```python
import secrets
Q = secrets.choice(prime_lst)
Q
```
## The Final Share and 2-party Additive Secret Sharing
Knowing that $ s_n = Q - (\; \sum \limits _{i=1} ^{n-1} s_i \; mod \; Q \; ) + s $
How do we implement 2-party ($ n=2 $) additive secret sharing using Python?
Keep reading and fing out!
```python
def dual_share(s, r):
'''
s = secret
r = randomness
'''
share_lst = list()
share_lst.append(randint(0,r))
final_share = r - (share_lst[0] % r) + s
share_lst.append(final_share)
return share_lst
```
```python
# Let's generate a couple of shares
secret = 5
dual_shares = dual_share(secret, Q)
dual_shares
```
Now go back to the previous cell and **run it again**. Notice anything?
...
...
...
See it yet? The shares are never the same because they are **randomly generated**.
Now let's implement the reconstruction (or decryption) function.
```python
def decrypt(shares, r):
'''
shares = iterable made of additive secret shares
r = randomness
'''
return sum(shares) % r
```
```python
# And let's decrypt our secret for the first time
decrypt(dual_shares, Q)
```
## Exercise: Implement n-party additive secret sharing
Fill the function below with your code.
```python
def n_share(s, r, n):
'''
s = secret
r = randomness
n = number of nodes, workers or participants
returns a tuple of n-shares
'''
# replace with your code
pass
```
```python
five_shares = n_share(s=686,r=Q,n=5)
five_shares
# run this cell to check your solution
q2.check(decrypt(five_shares, Q))
```
```python
# Uncomment the line below to see a hint
# q2.hint
```
```python
# Uncomment the line below to see the solution
# q2.solution
```
## Addition
Given two shared values $a$ and $b$, a party $P_i$ can compute the added shares as:
$ c_i = ( a_i + b_i ) \; mod \; Q$
In Python, we can implement this type of addition like this:
```python
def addition(a, b, r):
'''
a = iterable of the same length of b
b = iterable of the same length of a
r = randomness AKA randomly generated very high prime number
'''
c = list()
for i in range(len(a)):
c.append((a[i] + b[i]) % r)
return tuple(c)
```
Considering Alice and Bob are our parties, with secrets $s_a$ and $s_b$ to be shared (2-way) and wanting to compute addition.
Let $s_a = 5 $ and $s_b = 11 $
Alice's shares would be something like:
```python
# Alice's secret
sa = 5
alice_shares = dual_share(sa, Q)
alice_shares
```
While Bob's shares would be
```python
# Bob's secret
sb = 11
bob_shares = dual_share(sb, Q)
bob_shares
```
```python
secret_sum = addition(alice_shares, bob_shares, Q)
secret_sum
```
Doesn't make a lot of sense, does it?
Secret shares must only reveal information about their secrets when they are all combined. Otherwise all data must be hidden, which defines the **privacy** property.
These are still secret shares so there is one more step to get the sum of the original secrets.
```python
decrypt(secret_sum, Q)
```
Et Voilà!
## Public (scalar) Multiplication
Given a list of shared values $a$ and a **scalar** $b$, a party $P_i$ can compute the multiplied shares as:
$ c_i = a_i \times b \; mod \; Q$
In Python, we can implement this type of multiplication like this:
```python
def public_mul(a, b, r):
'''
a = iterable of the same length of b
b = scalar to multiply a by
r = randomness AKA randomly generated very high prime number
'''
c = list()
for i in range(len(a)):
c.append((a[i] * b) % r)
return tuple(c)
```
Let's say another party wants to multiply Alice's shares by the **scalar** value of 3.
```python
alice_times3 = public_mul(alice_shares, 3, Q)
```
Then we can decrypt (with Alice's permission) to double check we did multiply what we intended.
```python
decrypt(alice_times3,Q)
```
And this is `True` because Alice's secret $sa = 5$, remember?
```python
decrypt(alice_times3,Q) == sa * 3
```
## PyTorch + PySyft implementation
Now that you know how additive secret sharing works under the hood, let's see how we can leverage PyTorch and PySyft to do it for us.
```python
import torch
import syft as sy
hook = sy.TorchHook(torch)
```
Let's say Alice, Bob and Charlie are all enrolled on the **Foundations of Privacy** course and we, as instructors, want to know on average, how far in the course they are. We don't want to breach their privacy so each percentage of completion will be their own secret (a, b and c).
For educational purposes, we will define our parties (nodes, workers, etc) using `VirtualWorker` PySyft objects.
```python
alice = sy.VirtualWorker(hook, id="alice")
bob = sy.VirtualWorker(hook, id="bob")
charlie = sy.VirtualWorker(hook, id="charlie")
```
We also need a "secure worker", also known as the `Crypto Provider` to provide us with random prime numbers.
```python
secure_worker = sy.VirtualWorker(hook, "secure_worker")
```
We define our secrets using `torch.tensor` PyTorch tensor objects and we `Additive Share` them with our fellow workers.
```python
# Let a, b and c be our students' completion percentage
a = torch.tensor([35])
b = torch.tensor([77])
c = torch.tensor([10])
```
```python
# And we additive share with our parties
a = a.share(alice, bob, charlie, crypto_provider=secure_worker)
b = b.share(alice, bob, charlie, crypto_provider=secure_worker)
c = c.share(alice, bob, charlie, crypto_provider=secure_worker)
```
```python
# And we compute the mean of our tensor
mean = torch.mean(torch.stack(list([a,b,c])))
mean
```
Also, see that the object type is **[AdditiveSharingTensor]**.
For this example, we can decrypt our computation result using the get() method
```python
decrypted_mean = mean.get()
decrypted_mean
```
And get the scalar using the item() method (Only works for 1-dimensional tensors).
```python
scalar_mean = decrypted_mean.item()
scalar_mean
```
Now, the average completion should actually be 40 and $ \frac{1}{3} $ (or 40.6666666666... ) but this is something we will learn about in the next lessons.
Let’s now tackle private multiplication!
|
data DoorState = DoorOpen | DoorClosed
data DoorCmd : Type ->
DoorState -> DoorState ->
Type where
Open : DoorCmd () DoorClosed DoorOpen
Close : DoorCmd () DoorOpen DoorClosed
RingBell : DoorCmd () DoorClosed DoorClosed
Pure : ty -> DoorCmd ty state state
(>>=) : DoorCmd a state1 state2 ->
(a -> DoorCmd b state2 state3) ->
DoorCmd b state1 state3
doorProg : DoorCmd () DoorClosed DoorClosed
doorProg = do RingBell
Open
Close
|
theory Analyze_Containern
imports
"../../Primitive_Matchers/Parser"
begin
parse_iptables_save docker_fw="iptables-save.topos4.1.established"
thm docker_fw_def
thm docker_fw_FORWARD_default_policy_def
definition "unfolded_FORWARD = unfold_ruleset_FORWARD docker_fw_FORWARD_default_policy (map_of_string_ipv4 (docker_fw))"
value[code] "map (quote_rewrite \<circ> common_primitive_rule_toString) (unfolded_FORWARD)"
value[code] "map (quote_rewrite \<circ> common_primitive_rule_toString) (upper_closure unfolded_FORWARD)"
value[code] "upper_closure (packet_assume_new unfolded_FORWARD)"
lemma "check_simple_fw_preconditions (upper_closure (optimize_matches abstract_for_simple_firewall
(upper_closure (packet_assume_new unfolded_FORWARD))))" by eval
lemma "simple_fw_valid (to_simple_firewall (upper_closure
(optimize_matches abstract_for_simple_firewall (upper_closure (packet_assume_new unfolded_FORWARD)))))"
by eval
lemma "simple_fw_valid (to_simple_firewall (lower_closure
(optimize_matches abstract_for_simple_firewall (lower_closure (packet_assume_new unfolded_FORWARD)))))"
by eval
value[code] "map simple_rule_ipv4_toString (to_simple_firewall (upper_closure
(optimize_matches abstract_for_simple_firewall (upper_closure (packet_assume_new unfolded_FORWARD)))))"
value[code] "map simple_rule_ipv4_toString (to_simple_firewall (lower_closure
(optimize_matches abstract_for_simple_firewall (lower_closure (packet_assume_new unfolded_FORWARD)))))"
(*Interfaces be gone! necessary for ip partition!*)
definition preprocess where
"preprocess unfold closure ipassmt def fw \<equiv> to_simple_firewall (closure
(optimize_matches (abstract_primitive (\<lambda>r. case r of Pos a \<Rightarrow> is_Iiface a \<or> is_Oiface a \<or> is_L4_Flags a
| Neg a \<Rightarrow> is_Iiface a \<or> is_Oiface a \<or> is_Prot a \<or> is_L4_Flags a))
(closure
(iface_try_rewrite ipassmt None
(closure
(packet_assume_new
(unfold def (map_of fw))))))))"
definition preprocess_ESTABLISHED where
"preprocess_ESTABLISHED unfold closure ipassmt def fw \<equiv> to_simple_firewall (closure
(optimize_matches (abstract_primitive (\<lambda>r. case r of Pos a \<Rightarrow> is_Iiface a \<or> is_Oiface a \<or> is_L4_Flags a
| Neg a \<Rightarrow> is_Iiface a \<or> is_Oiface a \<or> is_Prot a \<or> is_L4_Flags a))
(closure
(iface_try_rewrite ipassmt None
(closure
(optimize_matches (ctstate_assume_state CT_Established)
(unfold def (map_of fw))))))))"
(*incomplete, but we won't need it anyway*)
definition ipassmt :: "(iface \<times> (32 word \<times> nat) list) list" where
"ipassmt = [(Iface ''lo'', [(ipv4addr_of_dotdecimal (127,0,0,0),8)]),
(Iface ''br-b74b417b331f'', [(ipv4addr_of_dotdecimal (10,0,0,0),8)])
]"
lemma "distinct (map fst ipassmt)" by eval
lemma "ipassmt_sanity_nowildcards (map_of ipassmt)" by eval
value[code] "map_of_ipassmt ipassmt"
value[code] "access_matrix_pretty_ipv4 parts_connection_ssh
(preprocess unfold_ruleset_FORWARD upper_closure ipassmt docker_fw_FORWARD_default_policy docker_fw)"
value[code] "access_matrix_pretty_ipv4 parts_connection_ssh
(preprocess_ESTABLISHED unfold_ruleset_FORWARD upper_closure ipassmt docker_fw_FORWARD_default_policy docker_fw)"
value[code] "access_matrix_pretty_ipv4 parts_connection_http
(preprocess unfold_ruleset_FORWARD upper_closure ipassmt docker_fw_FORWARD_default_policy docker_fw)"
value[code] "access_matrix_pretty_ipv4 parts_connection_http
(preprocess_ESTABLISHED unfold_ruleset_FORWARD upper_closure ipassmt docker_fw_FORWARD_default_policy docker_fw)"
parse_iptables_save docker_fw2="iptables-save.topos4.1"
thm docker_fw2_def
thm docker_fw2_FORWARD_default_policy_def
value[code] "access_matrix_pretty_ipv4 parts_connection_ssh
(preprocess unfold_ruleset_FORWARD upper_closure ipassmt docker_fw2_FORWARD_default_policy docker_fw2)"
value[code] "access_matrix_pretty_ipv4 parts_connection_ssh
(preprocess_ESTABLISHED unfold_ruleset_FORWARD upper_closure ipassmt docker_fw2_FORWARD_default_policy docker_fw2)"
value[code] "access_matrix_pretty_ipv4 parts_connection_http
(preprocess unfold_ruleset_FORWARD upper_closure ipassmt docker_fw2_FORWARD_default_policy docker_fw2)"
value[code] "access_matrix_pretty_ipv4 parts_connection_http
(preprocess_ESTABLISHED unfold_ruleset_FORWARD upper_closure ipassmt docker_fw2_FORWARD_default_policy docker_fw2)"
text{*Only one of the flows additionally allows answers for ESTABLISHED connections*}
lemma "let new = access_matrix_pretty_ipv4 parts_connection_http
(preprocess unfold_ruleset_FORWARD upper_closure ipassmt docker_fw2_FORWARD_default_policy docker_fw2);
est = access_matrix_pretty_ipv4 parts_connection_http
(preprocess_ESTABLISHED unfold_ruleset_FORWARD upper_closure ipassmt docker_fw2_FORWARD_default_policy docker_fw2)
in fst est = fst new \<and>
set (snd est) - set (snd new) = {(''0.0.0.0'', ''10.0.0.4'')}" by eval
parse_iptables_save docker_fw_initial="iptables-save.topos1"
thm docker_fw_initial_def
thm docker_fw_initial_FORWARD_default_policy_def
(*The original docker0 bridge is still in this dump. We need some information about it.*)
definition ipassmt_initial :: "(iface \<times> (32 word \<times> nat) list) list" where
"ipassmt_initial = (Iface ''docker0'', [(ipv4addr_of_dotdecimal (172,17,0,1),16)])#ipassmt"
lemma "distinct (map fst ipassmt_initial)" by eval
lemma "ipassmt_sanity_nowildcards (map_of ipassmt_initial)" by eval
value[code] "access_matrix_pretty_ipv4 parts_connection_ssh
(preprocess unfold_ruleset_FORWARD upper_closure ipassmt_initial docker_fw_initial_FORWARD_default_policy docker_fw_initial)"
value[code] "access_matrix_pretty_ipv4 parts_connection_ssh
(preprocess_ESTABLISHED unfold_ruleset_FORWARD upper_closure ipassmt_initial docker_fw_initial_FORWARD_default_policy docker_fw_initial)"
value[code] "access_matrix_pretty_ipv4 parts_connection_http
(preprocess unfold_ruleset_FORWARD upper_closure ipassmt_initial docker_fw_initial_FORWARD_default_policy docker_fw_initial)"
value[code] "access_matrix_pretty_ipv4 parts_connection_http
(preprocess_ESTABLISHED unfold_ruleset_FORWARD upper_closure ipassmt_initial docker_fw_initial_FORWARD_default_policy docker_fw_initial)"
end |
(*
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: gga_exc *)
(* prefix:
gga_x_pw86_params *params;
assert(p->params != NULL);
params = (gga_x_pw86_params * )(p->params);
*)
$ifdef gga_x_rpw86_params
params_a_aa := 15*0.1234:
params_a_bb := 17.33:
params_a_cc := 0.163:
$endif
pw86_f0 := s -> (1 + params_a_aa*s^2 + params_a_bb*s^4 + params_a_cc*s^6)^(1/15):
pw86_f := x -> pw86_f0(X2S*x):
f := (rs, z, xt, xs0, xs1) -> gga_exchange(pw86_f, rs, z, xs0, xs1):
|
proposition homotopic_paths_reversepath: "homotopic_paths s (reversepath p) (reversepath q) \<longleftrightarrow> homotopic_paths s p q" |
[STATEMENT]
lemma simple_integral_nonneg:
assumes f: "simple_function M f" and ae: "AE x in M. 0 \<le> f x"
shows "0 \<le> integral\<^sup>S M f"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. 0 \<le> integral\<^sup>S M f
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. 0 \<le> integral\<^sup>S M f
[PROOF STEP]
have "integral\<^sup>S M (\<lambda>x. 0) \<le> integral\<^sup>S M f"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<integral>\<^sup>S x. 0 \<partial>M \<le> integral\<^sup>S M f
[PROOF STEP]
using simple_integral_mono_AE[OF _ f ae]
[PROOF STATE]
proof (prove)
using this:
simple_function M (\<lambda>x. 0) \<Longrightarrow> \<integral>\<^sup>S x. 0 \<partial>M \<le> integral\<^sup>S M f
goal (1 subgoal):
1. \<integral>\<^sup>S x. 0 \<partial>M \<le> integral\<^sup>S M f
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<integral>\<^sup>S x. 0 \<partial>M \<le> integral\<^sup>S M f
goal (1 subgoal):
1. 0 \<le> integral\<^sup>S M f
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<integral>\<^sup>S x. 0 \<partial>M \<le> integral\<^sup>S M f
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
\<integral>\<^sup>S x. 0 \<partial>M \<le> integral\<^sup>S M f
goal (1 subgoal):
1. 0 \<le> integral\<^sup>S M f
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
0 \<le> integral\<^sup>S M f
goal:
No subgoals!
[PROOF STEP]
qed |
/*
* This file is part of MXE. See LICENSE.md for licensing information.
*/
// Boost.Context Example
// Copyright Oliver Kowalke 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <cstdlib>
#include <iostream>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/tss.hpp>
boost::thread_specific_ptr<int> ptr;
#include <boost/context/fiber.hpp>
namespace ctx = boost::context;
class moveable {
public:
int value;
moveable() :
value( -1) {
}
moveable( int v) :
value( v) {
}
moveable( moveable && other) {
std::swap( value, other.value);
}
moveable & operator=( moveable && other) {
if ( this == & other) return * this;
value = other.value;
other.value = -1;
return * this;
}
moveable( moveable const& other) = delete;
moveable & operator=( moveable const& other) = delete;
};
void test_thread()
{
if (ptr.get() == 0) {
ptr.reset(new int(0));
}
std::cout << "Hello, World! from thread" << std::endl;
}
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
boost::archive::xml_oarchive oa(std::cout);
std::string s = "\n\n Hello, World!\n\n";
oa << BOOST_SERIALIZATION_NVP(s);
boost::thread thrd(test_thread);
thrd.join();
moveable data{ 1 };
ctx::fiber f{ std::allocator_arg, ctx::fixedsize_stack{},
[&data](ctx::fiber && f){
std::cout << "entered first time: " << data.value << std::endl;
data = std::move( moveable{ 3 });
f = std::move( f).resume();
std::cout << "entered second time: " << data.value << std::endl;
data = std::move( moveable{});
return std::move( f);
}};
f = std::move( f).resume();
std::cout << "returned first time: " << data.value << std::endl;
data.value = 5;
f = std::move( f).resume();
std::cout << "returned second time: " << data.value << std::endl;
std::cout << "main: done" << std::endl;
return EXIT_SUCCESS;
}
|
function vw = drawROIsMontage(vw)
%
% vw = drawROIsMontage(vw)
%
% Draw the ROIs on a montage view (e.g. several
% flat levels / inplane slices at once).
%
% This function should be called only if
% vw.showROIs is non-zero. If showROIs=1, draw only the
% selected ROI. If showROIs=2, draw all the ROIs.
% 09/04 ras, off drawROIs.
% clear line handles for all ROIs (ras 06/06, see selectROI)
for r=1:length(vw.ROIs), vw.ROIs(r).lineHandles = []; end
% set line width parameter
w = 0.5;
s = vw.selectedROI;
n = length(vw.ROIs);
%%%%% get order of ROIs to display
if s
order = [1:s-1,s+1:n,s];
else
order = 1:n;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Main loop: draw ROIs according to prefs %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for r = order % loop through ROIs that are selected for display
if (r==vw.selectedROI)
% Selected ROI: now a settable param, ras 05/05
coords = vw.ROIs(r).coords;
color = viewGet(vw,'selRoiColor');
else
% Non-selected ROI, color from ROIs substruct
% If showROIs~=2, then set coords=[] so that nothing will be
% drawn.
if (vw.ui.showROIs==-2)
coords = vw.ROIs(r).coords;
else
coords = [];
end
thisCol=vw.ROIs(r).color;
% If it's a 'text' color, translate it...
if (ischar(thisCol))
nColEntries=length(thisCol);
for thisColEntry=1:nColEntries
thisColValue=thisCol(thisColEntry);
colRGB=[0 0 0];
switch (thisColValue)
case 'y', colorRGB = colRGB+[1 1 0];
case 'm', colorRGB = colRGB+[1 0 1];
case 'c', colorRGB = colRGB+[0 1 1];
case 'r', colorRGB = colRGB+[1 0 0];
case 'g', colorRGB = colRGB+[0 1 0];
case 'b', colorRGB = colRGB+[0 0 1];
case 'w', colorRGB = colRGB+[1 1 1];
case 'k', colorRGB = colRGB+[0 0 0];
otherwise, colorRGB = [1 1 1];
end % end switch statement
end % end loop
color=colorRGB./nColEntries;
else
color=thisCol;
end
end
% Draw the lines around each pixel, w=1/2 because you don't
% want to connect the centers of the pixels, rather you want to
% draw around each pixel, e.g, from (x-.5,y-.5) to (x+.5,y-.5).
if ~isempty(coords)
% The FLAT view can have a 'rotateImageDegrees' field that
% specifies a rotation angle for L and R.
% If this is set, then we have to transform the ROIs by this amount as
% well to make them register with the anatomy and functional data
if (strcmp(vw.viewType,'Flat'))
coords=rotateCoords(vw,coords);
end
% convert to coordinates of the montage image
coords = coords2Montage(vw,coords);
x = coords(1,:);
y = coords(2,:);
% draw boxes around the voxels
hold on
% if the view is set to flip the image, then we need to
% flip the ROI too
if viewGet(vw, 'flip up down'),
height = size(vw.ui.image, 1);
x = height - x + 1;
end
for i=1:size(coords,2);
l(i) = line([y(i)-w, y(i)+w, y(i)+w, y(i)-w, y(i)-w],...
[x(i)-w, x(i)-w, x(i)+w, x(i)+w, x(i)-w], ...
'Color',color);
end
hold off
% % remember line handles for quick refreshing
% vw.ROIs(r).lineHandles = l;
end
end
return;
|
The Lebesgue measure on $\mathbb{R}^n$ is the product measure of the Lebesgue measure on $\mathbb{R}$ with itself $n$ times. |
HANSARD REVISE * NUMERO 43
Le mercredi 3 decembre 1997
Mme Karen Kraft Sloan
LA JOURNEE INTERNATIONALE DES PERSONNES HANDICAPEES
Mme Madeleine Dalphond-Guiral
LE COMITE PERMANENT DES FINANCES
LE DECES DE M. MICHEL BELANGER
L'hon. Pierre S. Pettigrew
L'hon. Pierre S. Pettigrew
L'hon. Jean J. Charest
L'hon. Jean J. Charest
L'hon. Ralph E. Goodale
L'hon. Ralph E. Goodale
L'hon. David M. Collenette
L'hon. David M. Collenette
L'hon. Ralph E. Goodale
L'hon. David M. Collenette
L'hon. David M. Collenette
LA COUR SUPREME DU CANADA
L'hon. Ronald J. Duhamel
Le decorum a la Chambre des communes
M. Guy St-Julien
Le ministre des Peches et des Oceans
Le decorum a la Chambre des communes
Certains propos tenus au cours de la periode des questions
Le decorum a la Chambre des communes
Le ministre des Peches et des Oceans
LES DECRETS DE NOMINATION
REPONSE DU GOUVERNEMENT A DES PETITIONS
COMITES DE LA CHAMBRE
Mme Judy Wasylycia-Leis
Mme Rose-Marie Ur
L'hon. Ralph E. Goodale
Mme Judy Wasyl ycia-Leis
Motions nos 1, 2, 3 et 12
L'hon. David M. Collenette
L'hon. David M. Collenette
Motions nos 4, 10, 11 et 20
Motions nos 5 a 9, 13 a 17.
L'hon. David M. Collenette
M. Ovid L. Jackson
M. Leon E. Benoit
LES TRAVAUX DE LA CHAMBRE
M. Ovid L. Jackson
M. Ovid L. Jackson
M. Ovid L. Jackson
HANSARD REVISE * NUMERO 43
Le mercredi 3 decembre 1997
La seance est ouverte a 14 heures.
Mme Karen Kraft Sloan (York-Nord, Lib.):
Monsieur le President, c'est aujourd'hui la Journee internationale des personnes handicapees.
M. John Cummins (Delta-South Richmond, Ref.):
Je lui demande de s'excuser aupres d'eux.
Mme Aileen Carroll (Barrie-Simcoe-Bradford, Lib.):
LA JOURNEE INTERNATIONALE DES PERSONNES HANDICAPEES
Mme Madeleine Dalphond-Guiral (Laval-Centre, BQ):
Garantir l'acces, c'est une obligation collective.
Puisse la Semaine des personnes handicapees nous sensibiliser a cette realite.
LE COMITE PERMANENT DES FINANCES
M. Maurizio Bevilacqua (Vaughan-King-Aurora, Lib.):
Les Canadiens exigent des comptes du gouvernement et veulent assumer leurs responsabilites.
Mme Jean Augustine (Etobicoke-Lakeshore, Lib.):
Monsieur le President, nous celebrons aujourd'hui une date historique de la politique etrangere canadienne.
Nous avons pris part a un remarquable effort mondial.
M. Jim Pankiw (Saskatoon-Humboldt, Ref.):
Faut-il y voir une tendance?
C'est la devise des liberaux.
Mme Marlene Jennings (Notre-Dame-de-Grace-Lachine, Lib.):
Mme Christiane Gagnon (Quebec, BQ):
LE DECES DE M. MICHEL BELANGER
Mme Raymonde Folco (Laval-Ouest, Lib.):
Par son depart, le Canada perd un allie et un batisseur de taille.
Je regrette d'interrompre la deputee.
La parole est maintenant au depute d'Acadie-Bathurst.
M. Yvon Godin (Acadie-Bathurst, NPD):
Cette tendance vers l'assimilation des francophones est inacceptable.
Je suis un fier Acadien du Nouveau-Brunswick.
M. Ken Epp (Elk Island, Ref.):
Pour ces gens et des milliers d'autres, ce privilege inappreciable n'existe pas.
Ils sont prisonniers d'un corps qui ne leur obeit pas.
M. Rick Borotsik (Brandon-Souris, PC):
M. Pierre Brien (Temiscamingue, BQ):
Ce comportement est indigne de la part...
Nous procedons maintenant a la periode des questions orales.
Le chef de l'opposition officielle a la parole.
M. Preston Manning (chef de l'opposition, Ref.):
L'hon. Herb Gray (vice-premier ministre, Lib.):
M. Preston Manning (chef de l'opposition, Ref.):
Le ministere de l'Industrie cherche comment octroyer des subventions aux amis du gouvernement.
Le vice-premier ministre.
L'hon. Herb Gray (vice-premier ministre, Lib.):
Le chef de l'opposition.
M. Preston Manning (chef de l'opposition, Ref.):
Le gouvernement est cense exceller lorsqu'il s'agit de fixer des objectifs.
Le premier ministre dit qu'il a un objectif a propos des emissions de CO2.
En fait, il en a eu trois depuis trois semaines.
L'hon. Herb Gray (vice-premier ministre, Lib.):
M. Monte Solberg (Medicine Hat, Ref.):
Il n'y a meme pas l'ombre d'un veritable allegement fiscal.
Les Canadiens exigent que l'on reduise la dette.
Ils exigent que l'on abaisse leurs impots.
L'hon. Herb Gray (vice-premier ministre, Lib.):
M. Monte Solberg (Medicine Hat, Ref.):
Il s'agit de 143 000 $ pour un emploi de 30 000 $ par annee.
L'hon. Herb Gray (vice-premier ministre, Lib.):
Nous sommes tres conscients qu'il faut adopter une approche equilibree.
Nous nous interessons aux reductions d'impots.
M. Louis Plamondon (Richelieu, BQ):
Que repond la ministre du Patrimoine a l'appel lance par cette Federation?
L'hon. Sheila Copps (ministre du Patrimoine canadien, Lib.):
En effet, il n'y a pas une baisse nette, il y a une augmentation.
M. Louis Plamondon (Richelieu, BQ):
L'hon. Sheila Copps (ministre du Patrimoine canadien, Lib.):
Qu'est-ce que cela dit de son gouvernement?
Mme Suzanne Tremblay (Rimouski-Mitis, BQ):
Et on pourrait citer des exemples identiques a la grandeur du Canada.
L'hon. Sheila Copps (ministre du Patrimoine canadien, Lib.):
Mme Suzanne Tremblay (Rimouski-Mitis, BQ):
Je demande a la deputee d'etre tres judicieuse dans son choix de mots.
L'hon. Sheila Copps (ministre du Patrimoine canadien, Lib.):
Elle a dit: En etant Canadienne francaise, je suis une citoyenne de deuxieme classe.
En etant Quebecoise, je suis une citoyenne de premiere classe.
C'est ca, la difference.
Mme Alexa McDonough (Halifax, NPD):
Monsieur le President, ma question s'adresse a la ministre chargee de la jeunesse canadienne.
L'hon. Pierre S. Pettigrew (ministre du Developpement des ressources humaines, Lib.):
Environ 110 000 jeunes Canadiens beneficient chaque annee de notre strategie actuelle.
Mme Alexa McDonough (Halifax, NPD):
L'hon. Pierre S. Pettigrew (ministre du Developpement des ressources humaines, Lib.):
Monsieur le President, le chef du NPD cite des chiffres completement errones.
Cette augmentation est attribuable a notre strategie.
L'hon. Jean J. Charest (Sherbrooke, PC):
La collecte de fonds saisonniere...
Je demanderais au depute de Sherbrooke de poser sa question.
L'hon. Jean J. Charest:
Le vice-premier ministre.
L'hon. Herb Gray (vice-premier ministre, Lib.):
L'hon. Jean J. Charest (Sherbrooke, PC):
L'hon. Herb Gray (vice-premier ministre, Lib.):
Franchement, je n'ai pas entendu la question du depute.
M. Gary Lunn (Saanich-Gulf Islands, Ref.):
Le ministre est aux Etats-Unis en train de donner nos quotas aux Americains.
Quand va-t-il nous defendre et faire quelque chose?
M. Ted McWhinney (secretaire parlementaire du ministre des Affaires etrangeres, Lib.):
M. Gary Lunn (Saanich-Gulf Islands, Ref.):
Qui le gouvernement defend-il, les Canadiens ou les Americains?
Quand le gouvernement va-t-il reagir et faire quelque chose pour le Canada?
M. Wayne Easter (secretaire parlementaire du ministre des Peches et des Oceans, Lib.):
Monsieur le President, le ministre des Peches n'a rien annonce de semblable.
Mme Pauline Picard (Drummond, BQ):
L'hon. Allan Rock (ministre de la Sante, Lib.):
Mme Pauline Picard (Drummond, BQ):
L'hon. Allan Rock (ministre de la Sante, Lib.):
Comme je l'ai dit, j'espere avoir bientot l'occasion de le faire.
M. Grant McNally (Dewdney-Alouette, Ref.):
Il se rendait peut-etre a Paris pour dejeuner avec Ted.
On ne m'a rien signale qui indique quelque irregularite que ce soit.
M. Grant McNally (Dewdney-Alouette, Ref.):
Mme Helene Alarie (Louis-Hebert, BQ):
Monsieur le President, ma question s'adresse au ministre de l'Industrie.
L'hon. John Manley (ministre de l'Industrie, Lib.):
Le gouvernement a ensuite nomme les directeurs et directrices.
Mme Helene Alarie (Louis-Hebert, BQ):
L'hon. John Manley (ministre de l'Industrie, Lib.):
La majorite de ses membres ne sont pas nommes par le gouvernement.
M. Lee Morrison (Cypress Hills-Grasslands, Ref.):
Le ministre des Transports.
L'hon. David M. Collenette (ministre des Transports, Lib.):
La reglementation n'a pas ete modifiee.
L'application du reglement n'a pas non plus ete modifiee.
N'alarmons pas les Canadiens pour rien.
M. Lee Morrison (Cypress Hills-Grasslands, Ref.):
L'hon. David M. Collenette (ministre des Transports, Lib.):
Pas un seul Canadien ne sera touche a Noel de cette annee.
M. Benoit Sauvageau (Repentigny, BQ):
Monsieur le President, ma question s'adresse au ministre du Commerce international.
L'hon. Sergio Marchi (ministre du Commerce international, Lib.):
M. Gar Knutson (Elgin-Middlesex-London, Lib.):
Monsieur le President, ma question s'adresse au ministre des Ressources naturelles.
Tout cela est a 100 p. 100 conforme aux suggestions des provinces.
M. Art Hanger (Calgary-Nord-Est, Ref.):
M. John Richardson (secretaire parlementaire du ministre de la Defense nationale, Lib.):
M. Art Hanger (Calgary-Nord-Est, Ref.):
Il s'agit d'une question hypothetique.
Si le secretaire parlementaire veut y repondre, libre a lui.
M. John Richardson (secretaire parlementaire du ministre de la Defense nationale, Lib.):
M. Chris Axworthy (Saskatoon-Rosetown-Biggar, NPD):
Monsieur le President, ma question s'adresse au ministre de l'Industrie.
L'hon. John Manley (ministre de l'Industrie, Lib.):
M. Chris Axworthy (Saskatoon-Rosetown-Biggar, NPD):
L'hon. John Manley (ministre de l'Industrie, Lib.):
Dans une foule de domaines, nous sommes a la fine pointe.
M. Bill Casey (Cumberland-Colchester, PC):
Monsieur le President, ma question s'adresse au ministre des Transports.
Cela cree manifestement une situation tres dangereuse et met des vies en danger.
L'hon. David M. Collenette (ministre des Transports, Lib.):
C'est quelque chose dont les gestionnaires de Nav Canada sont tres fiers.
Je demanderais au depute de ne pas alarmer indument la population.
M. Bill Casey (Cumberland-Colchester, PC):
Monsieur le President, cette situation m'inquiete.
Je crois comprendre qu'il y a actuellement 27 controleurs aeriens a Vancouver.
NavCan a etabli le nombre minimum a 36.
C'est extremement dangereux.
L'hon. David M. Collenette (ministre des Transports, Lib.):
Ils respectent ces normes et le font extremement bien.
L'hon. Charles Caccia (Davenport, Lib.):
LA COUR SUPREME DU CANADA
M. Paul Forseth (New Westminster-Coquitlam-Burnaby, Ref.):
L'hon. Anne McLellan (ministre de la Justice et procureur general du Canada, Lib.):
M. Daniel Turp (Beauharnois-Salaberry, BQ):
Monsieur le President, ma question s'adresse au ministre des Affaires etrangeres.
Comment le ministre envisage-t-il l'appui canadien a cette demarche des parlementaires europeens?
L'hon. David Kilgour (secretaire d'Etat (Amerique latine et Afrique), Lib.):
Monsieur le President, les Canadiens sont tres preoccupes par la situation en Algerie.
Il reste a determiner qui participera et dans quelle situation.
Je remercie le depute de m'avoir pose cette question.
M. Gordon Earle (Halifax-Ouest, NPD):
L'hon. Lucienne Robillard (ministre de la Citoyennete et de l'Immigration, Lib.):
M. Gerald Keddy (South Shore, PC):
On dit que les diamants sont le meilleur ami des femmes.
L'hon. Jane Stewart (ministre des Affaires indiennes et du Nord canadien, Lib.):
Mme Sophia Leung (Vancouver Kingsway, Lib.):
Comment s'attaque-t-on a ces questions dans l'ouest du pays?
L'un des meilleurs programmes est le Programme d'aide au developpement des collectivites.
Et il fonctionne, monsieur le President.
Je vais les traiter dans cet ordre.
LE DECORUM A LA CHAMBRE DES COMMUNES
M. Guy St-Julien (Abitibi, Lib.):
Je me suis retourne et j'ai vu qu'il y avait deux personnes.
Mes interventions ont ete precises pour la population d'Abitibi et envers les postiers.
C'est regrettable, a la suite de ces gestes...
Mes collegues, je ne peux pas entendre la question de privilege.
J'aimerais entendre la question de privilege.
La parole est a l'honorable depute d'Abitibi.
M. Guy St-Julien:
En terminant, je pardonne au negociateur national du syndicat des postiers...
Tu es drolement culotte, mon gars.
M. Guy St-Julien: ...pour ses gestes a mon endroit.
M. Guy St-Julien:
C'est une declaration, ca, monsieur le President.
Je remercie mes collegues.
Mon collegue, ce n'est pas une question de privilege.
Je donne maintenant la parole a l'honorable depute de Burin-St.
LE MINISTRE DES PECHES ET DES OCEANS
M. Bill Matthews (Burin-St.
Je m'eleve contre les propos du ministre.
Je fais par consequent valoir a Votre Honneur que le ministre des Peches...
Je remercie le depute d'avoir souleve ce point.
J'ai juge qu'il ne s'agissait pas d'une question de privilege.
Il se peut cependant qu'il y ait matiere a grief.
LE DECORUM A LA CHAMBRE DES COMMUNES
M. Pierre Brien (Temiscamingue, BQ):
Monsieur le President, je desire invoquer le Reglement.
L'article 16 des Reglements de la Chambre des communes stipule ceci:
Si j'ai bien compris, les deputes ont eu une prise de bec.
C'est monnaie courante a la Chambre des communes.
Mes chers collegues, je vais relire les bleus.
Non, il ne l'a pas fait.
Je vous en prie, chers collegues.
Le depute s'est excuse aupres des personnes qui etaient dans la tribune.
M. Grant McNally (Dewdney-Alouette, Ref.):
J'aimerais deposer le document qui fournit ces renseignements pour la ministre.
Le depute peut deposer le document s'il y a consentement unanime de la Chambre.
Le depute souhaite deposer un document.
Y a-t-il consentement unanime?
Il n'y a pas consentement unanime.
LE DECORUM A LA CHAMBRE DES COMMUNES
M. Stephane Bergeron (Vercheres, BQ):
Je demande a tous les deputes de se comporter de facon honorable.
Nous sommes les parlementaires du Canada.
J'aimerais maintenant qu'on s'en tienne a cela.
Je crois qu'on en a parle assez, mon cher collegue.
M. Louis Plamondon (Richelieu, BQ):
J'invoque le Reglement, monsieur le President.
Est-ce que ce recours au Reglement porte sur quelque chose d'autre?
S'agit-il d'un autre recours au Reglement?
Je m'adresse directement au depute de Richelieu.
La question est simplement: s'agit-il d'un nouveau recours au Reglement?
Monsieur le President, je voudrais simplement rappeler au President qu'on peut regler le probleme.
Donc, cela confirme qu'il s'excuse aupres de la Chambre.
S'excuse-t-il?
M. Bob Kilger (Stormont-Dundas, Lib.):
Y a-t-il un nouveau recours au Reglement?
Ecoutez, ca devient un grand debat.
On a du travail a faire.
Cette tradition veut qu'on respecte une decision de la Presidence, et j'en suis.
Mais cette tradition exige egalement un decorum en cette Chambre.
Le point est fait et il est accepte.
Alors, on en reste la pour le moment.
LE MINISTRE DES PECHES ET DES OCEANS
M. Yvan Bernier (Bonaventure-Gaspe-Iles-de-la-Madeleine-Pabok, BQ):
Monsieur le President, je remercie la Presidence de m'accorder la parole.
La courte reponse est oui.
LES DECRETS DE NOMINATION
REPONSE DU GOUVERNEMENT A DES PETITIONS
COMITES DE LA CHAMBRE
M. Clifford Lincoln (Lac-Saint-Louis, Lib.):
Sur la foi de ces observations et d'autres, le comite recommande ce qui suit:
M. Paul Szabo (Mississauga-Sud, Lib.):
Mme Judy Wasylycia-Leis (Winnipeg-Centre-Nord, NPD):
M. Murray Calder (Dufferin-Peel-Wellington-Grey, Lib.):
M. Murray Calder (Dufferin-Peel-Wellington-Grey, Lib.):
Mme Bev Desjarlais (Churchill, NPD):
Mme Rose-Marie Ur (Lambton-Kent-Middlesex, Lib.):
M. Dick Proctor (Palliser, NPD):
Monsieur le President, nous repondons aujourd'hui a la question no 23.
La mine d'amiante Cassiar, situee en Colombie-Britannique, n'a pas ete rouverte.
Il n'existe a ce jour aucune production industrielle.
Le projet pilote en cours est entierement finance par des fonds prives.
Monsieur le President, je demande que les autres questions restent au Feuilleton.
Mme Judy Wasyl ycia-Leis (Winnipeg-Centre-Nord, NPD):
Monsieur le President, j'invoque le Reglement.
Les autres questions restent-elles au Feuilleton ?
Les motions seront regroupees pour les fins du debat de la facon suivante:
Les motions nos 1, 2, 3 et 12.
Les motions nos 18 et 19.
On peut consulter au bureau les modalites du vote sur les motions de chaque groupe.
Au moment du vote, la presidence va en informer les deputes.
On peut se procurer la version corrigee au bureau.
Le whip en chef du gouvernement invoque le Reglement.
M. Bob Kilger (Stormont-Dundas, Lib.):
M. Stan Keyes (secretaire parlementaire du ministre des Transports, Lib.):
Monsieur le President, j'invoque le Reglement.
Je ferai faire des copies de cet amendement, qui est disponible immediatement au bureau.
Je remercie les deputes d'en face de leur cooperation.
Monsieur le President, j'invoque le Reglement.
La Presidence fera cela aussitot que possible.
Vous nous demandez de commencer par les amendements.
Nous sommes a l'etape du rapport.
Cette etape a pour objet de discuter les amendements au projet de loi.
Nous abordons maintenant le groupe no 1.
Nous allons debattre les motions nos 1, 2, 3 et 12.
M. Michel Guimond (Beauport-Montmorency-Orleans, BQ) propose:
(ii) un administrateur est nomme par chacune des
tal applicables et des reglements de zonage qui s'appliquent aux sols avoisinants.
L'hon. David M. Collenette (ministre des Transports, Lib.):
Premierement, les services et l'infrastructure maritimes repondront aux besoins des usagers.
Sixiemement, les subventions directes et indirectes seront considerablement reduites ou eliminees.
Cet aspect est extremement important dans le contexte global de la gestion des sols.
C'est extremement important dans tout le pays.
C'est maintenant prevu dans le projet de loi s'il est adopte.
Le second niveau de controle institutionnel est d'une importance primordiale.
Nous avons apporte certaines modifications.
Nous avons realise des progres bien reels dans certains cas.
J'ai parle de Toronto tout a l'heure.
Tout semble indiquer qu'elles vont etre reglees.
Il ne semble que juste d'inclure Hamilton dans le projet de loi.
J'exhorte mes collegues a permettre l'adoption de ce projet de loi.
M. Lee Morrison (Cypress Hills-Grasslands, Ref.):
Ce projet de loi est imparfait.
Il etait tres prometteur.
Malheureusement, les batisseurs manquent de competences en finition.
Le toit de l'edifice fuit et ses portes ferment plutot mal.
Les defauts que recele ce projet de loi ne sont pas vraiment excusables.
Je proposerai des amendements a ce projet de loi.
M. Michel Guimond (Beauport-Montmorency-Orleans, BQ):
Dans cet esprit, je ne reprendrai pas les propos de mon collegue du Parti reformiste.
Cette flexibilite accrue que nous demandons par nos amendements est necessaire quant aux elements suivants.
Premierement, nous devons discuter de la delimitation des territoires geres par les administrations portuaires locales.
C'est le sens d'un de nos amendements.
Nous aurons l'occasion d'y revenir.
C'est le sens de notre motion no 12 que le gouvernement appuiera.
On parle d'y faire du recreotouristique.
Alors, que faire lorsque plusieurs municipalites sont touchees par des operations portuaires?
On sait que cela entraine souvent des problemes plus complexes d'integration au milieu.
En terminant, j'aimerais prendre quelque temps pour vous entretenir de la motion no 3.
Il est donc pertinent de lire le sous-alinea 14(1) d) :
D'un cote, le gouvernement se desaisit.
Le gouvernement se dessaisit, mais garde quand meme la mainmise sur la nomination des administrateurs.
On a voulu cibler nos interventions sur des points capitaux.
M. Bill Casey (Cumberland-Colchester, PC):
J'estime par consequent que le comite et le Parlement ont vraiment ete mal servis.
Ce serait une erreur.
Nous en avons vu des exemples tres passionnants dernierement.
Cet amendement leur refuserait cependant le droit de grandir.
Il reduirait la flexibilite et creerait un obstacle a la croissance des administrations portuaires florissantes.
Cela imposerait des contraintes a des administrations portuaires innovatrices, prosperes et rentables.
Cette idee nous semble bien meilleure que l'idee originale.
Elle donne plus de souplesse et ecarte la politique du conseil d'administration.
L'amendement attenue ce probleme et c'est pourquoi nous l'appuyons.
Cet amendement est un bon element de solution.
Pour ce qui est de la motion no 12, nous allons voter contre.
A notre avis, cet amendement est trop vague.
Il donne un controle excessif aux administrations publiques voisines.
Nous n'appuyons donc pas cette motion.
Mme Bev Desjarlais (Churchill, NPD):
Je ne cherche pas a cacher mes antecedents.
Je suis tres a l'aise avec ma position a l'egard des syndicats ouvriers.
Cela etant dit, je veux faire quelques remarques au sujet des motions.
Je recommanderai a la Chambre d'appuyer la motion no 1.
Par consequent, je recommanderai aussi l'adoption de la motion qui traite de cette question.
Il ne fait aucun doute que la motion no 3 reduira le favoritisme.
J'exhorte le gouvernement a appuyer egalement cette motion.
Je vais recommander l'adoption de toutes ces motions.
M. Paul Crete (Kamouraska-Riviere-du-Loup-Temiscouata-Les Basques, BQ):
C'est un projet de loi qui nous oblige a une attention soutenue.
Il y a donc un equilibre a assurer dans les amendements.
Je pense que c'etait un geste dans le bon sens.
Donc, il faut que l'amendement et la loi soient clairs.
C'est dans ce sens-la que va l'amendement qu'on a propose.
C'est aussi important au niveau des reglements de zonage.
Je donne un exemple qui, malheureusement, nous laisse songeurs presentement.
Juste dans ma circonscription, il y a trois traversiers differents.
Cela en fera une loi encore plus interessante.
Probablement que vendredi nous en serons a la troisieme lecture.
A ce moment-la on doit se poser la question.
Voyons donc a ce qu'elle puisse se faire dans les meilleures conditions possible.
M. Roy Bailey (Souris-Moose Mountain, Ref.):
J'ai quelques observations a formuler sur la modernisation des ports.
J'ai toutefois quelques reserves sur un aspect du projet de loi.
Ce n'est pas le but du projet de loi.
Par consequent, il m'est impossible d'appuyer la motion no 1.
Les lettres patentes peuvent varier disons entre Port Alberni et un autre port.
Cet amendement semble vouloir restreindre la croissance.
M. Greg Thompson (Charlotte, PC):
Il y a, dans ma circonscription, un port dont je veux parler.
Son emplacement est ideal et il beneficie d'une bonne geographie.
Il est grand, extremement grand.
C'est un secteur industriel d'acces a peu pres impossible pour une entreprise canadienne.
Les Americains ont un oeil sur ce port.
Voila qui est interessant.
Je prie le secretaire parlementaire de bien ecouter.
De quel parti etait-il membre?
C'etait de toute evidence le Parti liberal.
Il etait ministre au sein du gouvernement McKenna.
Il s'agit de M. Al Lacey.
Parce que son groupe engage les meilleurs consultants qui savent quoi faire.
C'est pourquoi ce projet de loi est vicie.
Le groupe americain sait comment brasser des affaires.
C'est un conglomerat.
Voici quelques unes des compagnies dans lesquelles Randy Waterman a des interets:
Est-ce que ca ne sonne pas mieux, Charlotte County Ports?
Mais ce n'est pas tout.
Ce n'est pas tout.
Ils le font par l'intermediaire d'une societe appelee Trapp Hill Holdings.
Il n'y a pas moyen pour un depute de correspondre avec ces gens.
Ils se refusent a correspondre avec qui que ce soit.
Il est absolument ridicule de penser que le gouvernement songerait a faire cela.
Qui a-t-on achete?
Je ne pense pas que ce soit moi.
Qui d'autre a la Chambre l'aurait?
Nous n'avons pas besoin de personnes de ce genre au Canada.
Nous ne voulons pas que ces gens s'emparent de nos ports.
C'est pourquoi nous devons renforcer ce projet de loi.
J'espere revenir plus tard sur la meme question.
M. Paul Mercier (Terrebonne-Blainville, BQ):
Nous veillerons, par nos amendements, a obtenir que cette somme soit amelioree.
En ce qui concerne la gestion des ports, il ne paiera plus rien.
Que dit l'article 14?
c) la ou les provinces [...]
M. Stan Keyes (secretaire parlementaire du ministre des Transports, Lib.):
C'est un grand port.
Je suis entierement d'accord avec le depute.
Il connait bien sa circonscription.
Tant mieux pour eux.
Qu'elles se manifestent.
Nous accueillons la participation de tous les interesses dans ce processus.
Le depute a parle de M. Waterman.
Il veut la pierre qui se trouve a proximite.
M. Greg Thompson (Charlotte, PC):
Monsieur le President, j'invoque le Reglement.
J'ai ici un document qui prouve le contraire.
Le depute doit ecouter le debat.
Son analyse de la motion no 12 etait tres exhaustive.
Nous voulons rendre les ports rentables.
C'est enorme comme representation gouvernementale.
Ca se trouve aux alineas 8.2c), d) et e).
Voulons-nous qu'un port soit administre uniquement par un groupe d'avocats?
Vous en avez quelques-uns de votre cote.
Le President est avocat, et je respecte le President.
Toutefois, nous ne pouvons appuyer cette motion.
C'est possible si la liste des noms est presentee d'avance.
Cette liste ne devrait pas etre limitee a quatre noms.
(Les votes par appel nominal sont demandes et reportes.)
L'hon. David M. Collenette (ministre des Transports, Lib.) propose:
Que le projet de loi C-9, a l'article 31, soit modifie:
a) par substitution, a la ligne 17, page 22, de ce qui suit:
(3) Sous reserve du paragraphe (4), l'administration portuaire ne peut gre-
b) par substitution, aux lignes 21 a 29, de ce qui suit:
egale au revenu qu'elle en retire.
Que le projet de loi C-9, a l'article 46, soit modifie
a) par substitution, aux lignes 4 a 10, page 29, de ce qui suit:
confiee; elle peut toutefois:
b) dans la mesure ou ses lettres patentes l'y autorisent:
(ii) aliener les accessoires fixes a demeure sur ces immeubles.
195.1 L'article 589 de la meme loi est remplace par ce qui suit:
M. Stan Keyes (secretaire parlementaire du ministre des Transports, Lib.):
Le projet de loi cree les conditions pour que les ports puissent etre exploites commercialement.
Il permet au ministre des Transports de commercialiser les operations de la voie maritime.
Il ameliore le fonctionnement des administrations de pilotage.
Les administrations portuaires seront constituees ou prorogees par lettres patentes.
Nous rectifions egalement les renvois errones a la Loi sur la marine marchande au Canada.
Dans certains cas, dans certaines municipalites, on n'a jamais rien verse.
Le statut d'agent protege les administrations des taxes et reglementations provinciales.
La Couronne ne garantira pas leurs prets.
Le gouverneur en conseil fixera des limites au pouvoir d'emprunt des administrations de pilotage.
J'exhorte donc les deputes a appuyer le projet de loi C-9.
M. Lee Morrison (Cypress Hills-Grasslands, Ref.):
Il nous reste a peine une demi-heure.
M. Stan Keyes (secretaire parlementaire du ministre des Transports, Lib.):
Je suis certain que la Chambre le lui permettra.
Y a-t-il consentement pour passer maintenant au groupe no 3?
(Les votes sont demandes et differes d'office.)
Les motions sont reputees avoir ete proposees, appuyees et lues.
et methodes visees aux paragraphes 38(1) et (1.1)
Que le projet de loi C-9 soit modifie par suppression de l'article 43.
85(1) et (1.1)
ont ete tenus ou appliques, pendant la
-Monsieur le President, je remercie la Chambre qui a gracieusement accepte d'accelerer la procedure.
Ceux-ci portent sur le probleme de conflit d'interets.
Fait etonnant, Transports Canada n'a pas denonce ce conflit manifeste.
Voila le genre de choses que nous voulons eviter.
Voila l'objet du projet de loi.
Sa decision serait ensuite renvoyee au comite des transports.
Enfin, les motions nos 9 et 17 sont consecutives aux autres huit motions.
M. Greg Thompson (Charlotte, PC):
C'est un type du nom de Al Lacey.
Qui est Al Lacey?
Al Lacey est le proprietaire de Lacey and Associates.
C'est l'ancien ministre du Developpement economique de la province du Nouveau-Brunswick.
Du Parti liberal avec un L majuscule.
M. Paul Zed est en affaire avec M. Doug Young, l'ancien ministre des Transports.
Se pourrait-il qu'il y ait conflit d'interets?
Doug Young, l'ancien ministre des Transports charge de superviser ce projet de loi.
C'etait le ministre.
Ce document s'intitule Proposition de developpement et d'acquisition du port de Bayside.
Ces gens veulent prendre possession de ce port.
C'est pourquoi la composition et l'integrite de cet organisme sont si importantes.
Le secretaire parlementaire a parle d'un certain Fred Nicholson.
C'est un homme honorable.
C'est un avocat.
Il est tres intelligent.
Je tiens a le signaler...
Monsieur le President, j'invoque le Reglement.
Le depute a parfaitement raison.
J'avais prevenu le depute de Charlotte.
Par consequent, il voudra bien ne pas utiliser d'accessoires.
Je l'invite a poursuivre son discours sans aides.
Je voulais faire une remarque a propos de M. Nicholson.
Celui-ci est une personne honorable.
Il represente bien la collectivite.
La n'est pas la question.
Et ce n'est pas tout.
C'est incroyable, monsieur le President.
Il est absolument ridicule qu'il envisage une telle chose.
Ce n'est pas correct du tout.
M. Stan Keyes (secretaire parlementaire du ministre des Transports, Lib.):
Voila un autre point que le depute de Charlotte voudra peut-etre reconnaitre.
Les ports ne peuvent disposer des terres federales.
Le statut de mandataire se limitera aux activites portuaires de base.
Il ne visera pas les autres activites.
Le gouvernement devra approuver les autres activites qu'un port peut entreprendre.
Les ports ne pourront emprunter a titre de mandataires.
Ils devront convaincre des preteurs commerciaux des merites des investissements qu'ils proposent.
La Couronne ne cautionnera pas les prets consentis aux ports.
Des limites d'emprunt seront fixees pour chaque port.
Le ministre des Transports determinera la duree maximale des baux.
Les aspirations au developpement portuaire seront soumises aux criteres ordinaires du risque commercial.
Le port a-t-il suivi les regles?
Les dossiers divulguent-ils pleinement et equitablement la maniere dont le port a ete exploite?
Le port suit-il le bon ensemble de regles?
Ce sont des dispositions appropriees a la commercialisation de nos ports.
M. Bill Casey (Cumberland-Colchester, PC):
Monsieur le President, je veux discuter du groupe de motions no 3.
J'appuie la demarche du depute de Charlotte.
Pourquoi la compagnie doit-elle recruter un ancien depute federal pour l'appuyer?
Pourquoi la compagnie doit-elle recruter une telle equipe?
La motion no 5 me semble raisonnable.
Celle-ci se lit en partie comme suit:
Les administrations portuaires veillent a etablir un code de conduite et des regimes de pratiques...
ce qui est tout a fait normal et nous l'appuyons.
La motion no 7 dit notamment ce qui suit:
Telle est, d'une facon generale, notre position sur ces motions.
Nous en arrivons ensuite a la motion no 13 et aux motions suivantes.
La motion no 13 dit notamment:
La motion no 15 dit notamment:
C'est encore la meme chose.
La motion no 16 dit notamment:
Nous rejetons cette motion.
Nous nous opposons a la motion no 16.
La motion no 17 eliminerait l'article 89.
Nous nous opposons egalement a cette motion.
La Chambre est-elle prete a se prononcer?
(Demande et report d'office des votes par appel nominal.)
Nous passons aux motions du groupe no 4, soit les motions nos 18 et 19.
M. Michel Guimond (Beauport-Montmorency-Orleans, BQ) propose:
L'hon. David M. Collenette (ministre des Transports, Lib.) propose:
Que le projet de loi C-9 soit modifie:
b) par adjonction, apres la ligne 9, page 79, de ce qui suit:
Cette position est tout a fait conforme aux pratiques passees.
Cela correspond a ce qui s'est fait dans le passe.
Les commissions portuaires constituent le seul groupe qui ne figure pas sur la liste.
M. Lee Morrison (Cypress Hills-Grasslands, Ref.):
Ils sont passes au travers des mailles du filet.
Leurs pensions ne sont pas transferables et le projet de loi les laisse litteralement tomber.
Ces gens ne sont pas nombreux, neanmoins ce sont de vraies personnes.
On aurait du tenir compte d'eux.
Je fais le meme reproche a la motion no 18.
La motion no 18 veille tellement a leur sort que nous ne l'appuierons pas.
M. Michel Guimond (Beauport-Montmorency-Orleans, BQ):
Et je m'explique.
Donc, la motion no 19 du gouvernement ne nous satisfait pas plus.
M. Bill Casey (Cumberland-Colchester, PC):
Madame la Presidente, j'interviens au sujet du dernier groupe de motions.
Je suis un peu inquiet.
Nous preferons la motion no 19.
Mme Bev Desjarlais (Churchill, NPD):
Elle n'a eu aucune discussion ou presque avec ses employes.
L'argent s'ajoute aux gains assurables.
Elle n'aurait meme pas le droit de l'utiliser aux fins de sa retraite.
M. Rob Anders (Calgary-Ouest, Ref.):
Madame la Presidente, j'invoque le Reglement.
La presidente suppleante (Mme Thibeault):
Le depute de Churchill sera le dernier a intervenir.
C'est une modification importante.
Cette situation ne touchera pas seulement la Societe canadienne des ports.
La question se posera de nouveau.
J'appuierai la motion no 18, parce que sa portee est plus vaste.
M. Stan Keyes (secretaire parlementaire du ministre des Transports, Lib.):
Madame la Presidente, j'invoque le Reglement.
La presidente suppleante (Mme Thibeault):
Le depute de Souris-Moose Mountain.
M. Roy Bailey (Souris-Moose Mountain, Ref.):
C'etait la teneur de ses propos.
Puis-je fournir l'exemple suivant au ministre?
Voila les deux points que je voulais faire valoir.
La presidente suppleante (Mme Thibeault):
(Les votes sont reputes avoir ete demandes et differes.)
La presidente suppleante (Mme Thibeault):
Je vais commencer par une citation du rapport de 1993 du verificateur general, qui disait:
Il ajoute, plus loin:
Selon nous c'est un cas de taxation sans representation.
De toute evidence, nous ne sommes pas les seuls a etre de cet avis.
Cela devrait nous mettre la puce a l'oreille.
Le gouvernement eprouvait de serieuses difficultes financieres en 1995.
Et ce, au moyen des frais d'utilisation.
Et puis il y a la question de l'equite.
Je peux vous dire que les gens sont tres preoccupes par cette question.
Elle doit faire concurrence aux Americains et a d'autres entreprises du monde entier.
Ces droits d'utilisation lui rend la tache extremement difficile.
Il s'agit la de 3,8 milliards de dollars par annee.
M. Ovid L. Jackson (secretaire parlementaire du president du Conseil du Tresor, Lib.):
Ce n'est pas tout.
Ces societes seraient en fait paralysees face au secteur prive.
Cela rendrait l'application des programmes de frais d'utilisation pratiquement impossible.
La notion de frais d'utilisation n'est pas nouvelle.
Les Canadiens paient des frais depuis les annees 1800 pour obtenir leur passeport.
C'est une facon rentable, administrativement sensee et equitable de fournir des services gouvernementaux.
En 1992-1993, les depenses de programmes se chiffraient a 122,6 milliards de dollars.
Nous avons reussi a maitriser nos depenses de programmes.
Nous avons gere efficacement en maintenant la qualite des services offerts aux Canadiens.
Le projet de loi C-205 ne contribuerait pas a ce succes.
Au contraire, il le compromettrait.
Les objectifs du projet de loi C-205 sont impraticables.
Je ne puis donc pas accorder mon appui au projet de loi.
M. Odina Desrochers (Lotbiniere, BQ):
Le projet de loi reformiste repond a cette preoccupation legitime du verificateur general.
Qui paie la note de cette nouvelle facon de faire?
Les campings nationaux, maintenant, coutent plus cher que les campings prives.
Le projet de loi C-205 arrive a point pour demasquer le jeu des liberaux.
Ou va cet argent?
La encore, le ministre des Finances est silencieux.
Chaque fois que ce gouvernement doit rendre des comptes a la population, il s'esquive.
Les exemples sont nombreux.
Qu'a-t-il donc a cacher a la population?
Qui ecope dans ce debat economique?
Les travailleuses et travailleurs qui sont lourdement penalises par le gouvernement liberal.
Avec ce projet, la democratie pourrait marquer un pas important.
On voit bien encore le jeu du ministre des Finances.
Il est temps de mettre fin a ces taxes deguisees.
Mme Bev Desjarlais (Churchill, NPD):
Le rapport du comite devra etre adopte par la Chambre.
L'organisme de reglementation est lie par la decision de la Chambre.
Il y a absence d'examen.
Des frais d'utilisation sont de plus en plus imposes pour les services du gouvernement.
C'est facile de parler d'excedent lorsque des services sont supprimes.
Les gens auxquels on impose ces frais d'utilisation en subissent les contrecoups.
Ces frais nous assaillent de toutes parts.
Au fil des ans, la liste s'est allongee.
La meme situation se produit avec le gouvernement du Canada.
Le projet de loi a l'etude serait un debut.
Ils pourraient discuter publiquement de l'augmentation des frais d'utilisation.
Voila pourquoi je vais appuyer le projet de loi a l'etude.
M. Leon E. Benoit (Lakeland, Ref.):
D'autres diront qu'il devrait plutot etre brule sur le bucher.
C'est un sujet tres serieux.
Je vais parler de certains de ces frais d'utilisation.
Or, ces droits ne sont pas necessairement etablis de cette facon.
Certains droits sont beaucoup plus eleves que le cout de prestation du service.
Deuxiemement, ces services doivent etre fournis de facon rentable.
C'est un point important.
Cela ne s'est que trop vu par le passe.
Il ne doit pas y avoir interfinancement.
Les agriculteurs ont exprime quelques preoccupations generales.
Ce sont parfois de nombreux groupes differents qui m'ont fait part de ces preoccupations.
Il y a egalement l'Institut canadien pour la protection des cultures.
Il faut voir leur effet cumulatif sur l'industrie.
Voila ce qui me preoccupe.
Je constate que mon temps de parole est termine.
M. Nick Discepola (secretaire parlementaire du solliciteur general du Canada, Lib.):
Je dois dire que je cherche encore.
Que cherche a accomplir ce projet de loi?
C'est la question que je me suis posee.
La definition de ces frais aux usagers y est tres large.
Je pense que trop c'est trop.
L'utilisation des frais aux usagers est une bonne forme de gouvernement.
Nous pourrions egalement assister au meme phenomene dans le cas des programmes.
La presidente suppleante (Mme Thibeault):
Le depute de Medicine Hat veut-il cinq minutes pour conclure?
Je crois que mes vis-a-vis cherchent tout simplement de faux pretextes.
Il devait leur donner un role utile.
Cela devait attirer plus d'attention sur les travaux des comites.
Ce qui se serait certainement produit.
C'est quelque chose qui est propre au tiers monde.
Cela nous expose a la corruption et a ce genre de pratiques.
Nous ne voulons pas de cela dans notre pays.
Ce serait une merveilleuse occasion pour le gouvernement de faire cela.
Les gens ne contesteront pas le prix du bois de chauffage s'il semble raisonnable.
C'est probablement bon.
Nous devons avoir ce genre de mecanisme aux comites.
Nous ne l'avons pas a la Chambre des communes.
Nous ne sommes pas contre les frais d'utilisation.
Les impots ont augmente aussi.
La presidente suppleante (Mme Thibeault):
LES TRAVAUX DE LA CHAMBRE
L'hon. Don Boudria (leader du gouvernement a la Chambre des communes, Lib.):
La presidente suppleante (Mme Thibeault):
Le depute a-t-il le consentement unanime de la Chambre?
M. Gordon Earle (Halifax-Ouest, NPD):
Les statistiques de Sante Canada montrent l'ampleur de cette tragedie.
Ces chiffres ne representent que la pointe de l'iceberg.
Que fait le gouvernement face a cette crise?
Le gouvernement espere-t-il ameliorer la situation en reduisant des ressources deja rares?
M. Ovid L. Jackson (secretaire parlementaire du president du Conseil du Tresor, Lib.):
On n'exerce aucune pression sur les collectivites pour qu'elles acceptent ce transfert.
Je tiens a garantir au depute...
La presidente suppleante (Mme Thibeault):
La parole est a la deputee de Dartmouth.
Mme Wendy Lill (Dartmouth, NPD):
Un an apres le depot du rapport, ou en sommes-nous?
Les personnes handicapees et les services qui leur sont destines sont plus que jamais menaces.
Les pensions d'invalidite seront plus difficiles a obtenir et moins elevees.
Comment ces gens sont-ils censes se rendre au travail?
Comment font-ils pour rendre visite a leur mere?
Les services d'auxiliaires disparaissent.
Les gens doivent se battre pour avoir le droit de prendre un bain par semaine.
Que dire de la protection assuree par la loi?
Il est temps de sauvegarder la qualite de vie de nos concitoyens les plus vulnerables.
M. Ovid L. Jackson (secretaire parlementaire du president du Conseil du Tresor, Lib.):
Le Forum national nous a aussi dit que nous devions preserver ce que nous avons.
Nous pouvons faire mieux, sur le plan des services.
Nous pouvons faire mieux, sur le plan des medicaments, de la conformite et des ordonnances.
Ils sont assez importants, comparativement aux autres elements des soins de sante.
M. Greg Thompson (Charlotte, PC):
Cette reponse est loin d'etre satisfaisante.
Au Canada, nous depensons actuellement 10,8 milliards de dollars par annee en medicaments.
Sur ces 10,8 milliards, environ 5 milliards sont depenses en medicaments d'ordonnance.
Il ne s'est pas arrete la.
M. Ovid L. Jackson (secretaire parlementaire du president du Conseil du Tresor, Lib.):
Leur importance relative a augmente par rapport a d'autres secteurs des soins de sante.
Ce dialogue est a peine amorce.
Un nouveau groupe de travail, federal-provincial-territorial entame ce processus.
Tous les interesses doivent se joindre a ce dialogue.
Cette approche nationale se caracterisera par la collaboration.
Cela doit se faire...
La presidente suppleante (Mme Thibeault):
Le depute de Waterloo-Wellington.
M. Lynn Myers (Waterloo-Wellington, Lib.):
Je me suis demande ou cela nous laissait.
Il y a un potentiel commercial considerable pour le Canada sur ce continent.
M. Julian Reed (secretaire parlementaire du ministre du Commerce international, Lib.):
Les representants des entreprises canadiennes sont extremement optimistes par rapport a cette region.
La procedure acceleree n'est pas essentielle a l'amorce des negociations.
Nous esperons qu'elle y parviendra a temps pour la rencontre de Santiago.
La presidente suppleante (Mme Thibeault):
(La seance est suspendue a 19 h 3.)
La seance reprend a 22 h 15.
Le huissier du baton noir apporte le message suivant:
En consequence, le President et les deputes se rendent au Senat.
(La seance est levee a 22 h 27.)
|
(sec:LDs)=
# The Method of Lagrangian Descriptors
## Introduction
One of the biggest challenges of dynamical systems theory or nonlinear dynamics is the development of mathematical techniques that provide us with the capability of exploring transport in phase space. Since the early 1900, the idea of pursuing a qualitative description of the solutions of differential equations, which emerged from the pioneering work carried out by Henri Poincaré on the three body problem of celestial mechanics {cite}`hp1890`, has had a profound impact on our understanding of the nonlinear character of natural phenomena. The qualitative theory of dynamical systems has now been widely embraced by the scientific community.
The goal of this section is to describe the details behind the method of Lagrangian descriptors. This simple and powerful technique unveils regions with qualitatively distinct dynamical behavior, the boundaries of which consist of invariant manifolds. In a procedure that is best characterised as *phase space tomography*, we can use low-dimensional slices we are able to completely reconstruct the intricate geometry of underlying invariant manifolds that governs phase space transport.
Consider a general time-dependent dynamical system given by the equation:
```{math}
---
label: eq:gtp_dynSys
---
\begin{equation}
\dfrac{d\mathbf{x}}{dt} = \mathbf{f}(\mathbf{x},t) \;,\quad \mathbf{x} \in \mathbb{R}^{n} \;,\; t \in \mathbb{R} \;,
\label{eq:gtp_dynSys}
\end{equation}
```
where the vector field $\mathbf{f}(\mathbf{x},t)$ is assumed to be sufficiently smooth both in space and time. The vector field $\mathbf{f}$ can be prescribed by an analytical model or given from numerical simulations as a discrete spatio-temporal data set. For instance, the vector field could represent the velocity field of oceanic or atmospheric currents obtained from satellite measurements or from the numerical solution of geophysical models. In the context of chemical reaction dynamics, the vector field could be the result of molecular dynamics simulations. For any initial condition $\mathbf{x}(t_0) = \mathbf{x}_0$, the system of first order nonlinear differential equations given in Eq. {eq}`eq:gtp_dynSys` has a unique solution represented by the trajectory that starts from that initial point $\mathbf{x}_0$ at time $t_0$.
Since all the information that determines the behavior and fate of the trajectories for the dynamical system is encoded in the initial conditions (ICs) from which they are generated, we are interested in the development of a mathematical technique with the capability of revealing the underlying geometrical structures that govern the transport in phase space.
Lagrangian descriptors (LDs) provide us with a simple and effective way of addressing this challenging task, because it is formulated as a scalar trajectory-diagnostic tool based on trajectories. The elegant idea behind this methodology is that it assigns to each initial condition selected in the phase space a positive number, which is calculated by accumulating the values taken by a predefined positive function along the trajectory when the system is evolved forward and backward for some time interval. The positive function of the phase space variables that is used to define different types of LD might have some geometrical or physical relevance, but this is not a necessary requirement for the implementation of the method. This approach is remarkably similar to the visualization techniques used in laboratory experiments to uncover the beautiful patterns of fluid flow structures with the help of drops of dye injected into the moving fluid {cite}`chien1986`. In fact, the development of LDs was originally inspired by the desire to explain the intricate geometrical flow patterns that are responsible for governing transport and mixing processes in Geophysical flows. The method was first introduced a decade ago based on the arclength of fluid parcel trajectories {cite}`madrid2009,mendoza2010`. Regions displaying qualitatively distinct dynamics will frequently contain trajectories with distinct arclengths and a large variation of the arclength indicate the presence of separatrices consisting of invariant manifolds {cite}`mancho2013lagrangian`.
Lagrangian descriptors have advantages in comparison with other methodologies for the exploration of phase space structures. A notable advantage is that they are straightforward to implement.
Since its proposal as a nonlinear dynamics tool to explore phase space, this technique has found a myriad of applications in different scientific areas. For instance, it has been used in oceanography to plan transoceanic autonomous underwater vehicle missions by taking advantage of the underlying dynamical structure of ocean currents {cite}`ramos2018`. Also, it has been shown to provide relevant information for the effective management of marine oil spills {cite}`gg2016`. LDs have been used to analyze the structure of the Stratospheric Polar Vortex and its relation to sudden stratospheric warmings and also to ozone hole formation {cite}`alvaro1,alvaro2,curbelo2019a,curbelo2019b`. In all these problems, the vector field defining the dynamical system is a discrete spatio-temporal dataset obtained from the numerical simulation of geophysical models. Recently, this tool has also received recognition in the field of chemistry, for instance in transition state theory {cite}`craven2015lagrangian,craven2016deconstructing,craven2017lagrangian,revuelta2019unveiling`, where the computation of chemical reaction rates relies on the know\-ledge of the phase space structures. These high-dimensional structures characterizing reaction dynamics are typically related to Normally Hyperbolic Invariant Manifolds (NHIMs) and their stable and unstable manifolds that occur in Hamiltonian systems. Other applications of LDs to chemical problems include the analysis of isomerization reactions {cite}`naik2020,GG2020b`, roaming {cite}`krajnak2019,gonzalez2020`, the study of the influence of bifurcations on the manifolds that control chemical reactions {cite}`GG2020a`, and also the explanation of the dynamical matching mechanism in terms of the existence of heteroclinic connections in a Hamiltonian system defined by Caldera-type potential energy surfaces {cite}`katsanikas2020a`.
### Lagrangian Descriptors versus Poincaré Maps
Poincaré maps have been a standard and traditional technique for understanding the global phase space structure of dynamical systems. However, Lagrangian descriptors offer substantial advantages over Poincaré maps. We will describe these advantages in the context of the most common settings in which they are applied. However, we note that Lagrangian descriptors can be applied in exactly the same way to both Hamiltonian and non-Hamiltonian vector fields. In keeping with the spirit of this book, we will frame our discussion and description in the Hamiltonian setting.
### Autonomous Hamiltonian vector fields
The consideration of the dimension of different geometric objects is crucial to understanding the advantages of Lagrangian descriptors over Poincaré maps. Therefore we will first consider the "simplest" situation in which these arise — the autonomous Hamiltonian systems with two degrees of freedom.
A two degree-of-freedom Hamiltonian system is described by a four dimensional phase space described by coordinates $(q_1, q_2, p_1, p_2)$. Moreover, we have seen in Section REF that trajectories are restricted to a three dimensional energy surface ("energy conservation in autonomous Hamiltonian systems"). We choose a two dimensional surface within the energy surface that is transverse to the Hamiltonian vector field. This means that at no point on the two dimensional surface is the Hamiltonian vector field tangent to the surface and that at every point on the surface the Hamiltonian vector field has the same directional sense (this is defined more precisely in REF). This two dimensional surface is referred to as a surface of section (SOS) or a Poincaré section, and it is the domain of the Poincaré map. The image of a point under the Poincaré map is the point on the trajectory, starting from that point, that first returns to the surface (and this leads to the fact that the Poincaré map is sometimes referred to as a "first return map").
The practical implementation of this procedure gives rise to several questions. Given a specific two degree-of-freedom Hamiltonian system can we find a two dimensional surface in the three dimensional energy surface having the property that it is transverse to the Hamiltonian vector field and "most" trajectories with initial conditions on the surface return to the surface? In general, the answer is "no" (unless we have some useful a priori knowledge of the phase space structure of the system). The advantage of the method of Lagrangian descriptors is that none of these features are required for its implementation, and it gives essentially the same information as Poincaré maps.
However, the real advantage comes in considering higher dimensions, e.g autonomous Hamiltonian systems with more than two degrees-of-freedom. For definiteness, we will consider a three degree-of-freedom autonomous Hamiltonian system. In this case the phase space is six dimensional and the energy surface is five dimensional. A cross section to the energy surface, in the sense described above, would be four dimensional (if an appropriate cross-section could be found). Solely on dimensionality considerations, we can see the difficulty. Choosing "enough" initial conditions on this four dimensional surface so that we can determine the phase space structures that are mapped out by the points that return to the cross-section is "non-trivial" (to say the least), and the situation only gets more difficult when we go to more than three degrees-of-freedom. One might imagine that you could start by considering lower dimensional subsets of the cross section. However, the probability that a trajectory would return to a lower dimensional subset is zero. Examples where Lagrangian descriptors have been used to analyse phase space structures in two and three degree-of-freedom Hamiltonian systems with this approach are given in {cite}`demian2017,naik2019a,naik2019b,GG2019`.
Lagrangian descriptors avoid all of these difficulties. In particular, they can be computed on any subset of the phase space since there is no requirement for trajectories to return to that subset. Since phase space structure is encoded in the initial conditions (not the final state) of trajectories a dense grid of initial conditions can be placed on any subset of the phase space and a "Lagrangian descriptor field" can be computed for that subset with high resolution and accuracy. Such computations are generally not possible using the Poincaré map approach.
### Nonautonomous Hamiltonian vector fields
Nonautonomous vector fields are fundamentally different than autonomous vector fields, and even more so for Hamiltonian vector fields. For example, one degree-of-freedom autonomous Hamiltonian vector fields are integrable. One degree-of-freedom autonomous Hamiltonian vector fields may exhibit chaos. Regardless of the dimension, a very significant difference is that energy is not conserved for nonautonomous Hamiltonian vector fields. Nevertheless, Lagrangian descriptors can be applied in exactly the same way as for autonomous Hamiltonian vector fields, *regardless of the nature of the time dependence. We add this last remark since the concept of Poincaré maps is not applicable unless the time dependence is periodic.*
## Formulations for Lagrangian Descriptors
### The Arclength Definition
In order to build some intuition on how the method works and understand its very simple and straightforward implementation, we start with the arclength definition mentioned in the previous section. This version of LDs is also known in the literature as function $M$. Consider any region of the phase space where one would like to reveal structures at time $t = t_0$, and create a uniformly-spaced grid of ICs $\mathbf{x}_0 = \mathbf{x}(t_0)$ on it. Select a fixed integration time $\tau$ that will be used to evolve all the trajectories generated from these ICs forward and backward in time for the time intervals $[t_0,t_0+\tau]$ and $[t_0-\tau,t_0]$ respectively. This covers a temporal range of $2\tau$ centered at $t = t_0$, marking the time at which we want to take a snapshot of the underlying structures in phase space. The arclength of a trajectory in forward time can be easily calculated by solving he integral:
```{math}
---
label: eq:M_function_fw
---
\begin{equation}
\mathcal{L}^{f}(\mathbf{x}_{0},t_0,\tau) = \int^{t_0+\tau}_{t_0} ||\dot{\mathbf{x}}|| \; dt \;,
\label{eq:M_function_fw}
\end{equation}
```
where
$\dot{\mathbf{x}} = \mathbf{f}(\mathbf{x}(t;\mathbf{x}_0),t)$ and
$||\cdot||$ is the Euclidean norm applied to the vector field defining the dynamical system in Eq. {eq}`eq:gtp_dynSys` . Similarly, one can define the arclength when the trajectory evolves in backward time as:
```{math}
---
label: eq:M_function_bw
---
\begin{equation}
\mathcal{L}^{b}(\mathbf{x}_{0},t_0,\tau) = \int^{t_0}_{t_0-\tau} ||\dot{\mathbf{x}}|| \; dt \;,
\label{eq:M_function_bw}
\end{equation}
```
It is common practice to combine these two quantities into one scalar value so that:
```{math}
---
label: eq:M_function
---
\begin{equation}
\mathcal{L}(\mathbf{x}_{0},t_0,\tau) = \mathcal{L}^{b}(\mathbf{x}_{0},t_0,\tau) + \mathcal{L}^{f}(\mathbf{x}_{0},t_0,\tau) \;,
\label{eq:M_function}
\end{equation}
```
and in this way the scalar field provided by the method will simultaneously reveal the location of the stable and unstable manifolds in the same picture. However, if one only considers the output obtained from the forward or backward contributions, we can separately depict the stable and unstable manifolds respectively.
We illustrate the logic behind the capabilities of this technique to display the stable and unstable manifolds of hyperbolic points with a very simple example, the one degree-of-freedom (DoF) linear Hamiltonian saddle system given by:
```{math}
---
label: eq:1dof_saddle
---
\begin{equation}
H(q,p) = \dfrac{1}{2} \left(p^2 - q^2\right) \quad \Leftrightarrow \quad
\begin{cases}
\dot{q} = \dfrac{\partial H}{\partial p} = p \\[.4cm]
\dot{p} = -\dfrac{\partial H}{\partial q} = q
\end{cases}
\label{eq:1dof_saddle}
\end{equation}
```
```{figure} figures/1d_saddle_ld.png
---
name: fig:1d_saddle
---
Forward {eq}`eq:M_function_bw`, backward {eq}`eq:M_function_fw` and combined {eq}`eq:M_function` Lagrangian descriptors for system {eq}`eq:1dof_saddle` respectively.
```
We know that this dynamical system has a hyperbolic equilibrium point at the origin and that its stable and unstable invariant manifolds correspond to the lines $p = \pm q$ respectively (refer to hyperbolic section). Outside of these lines, the trajectories are hyperbolas. What happens when we apply LDs to this system? Why does the method pick up the manifolds? Notice first that in {numref}`fig:1d_saddle` the value attained by LDs at the origin is zero, because it is an equilibrium point and hence it is not moving. Therefore, the arclength of its trajectory is zero. Next, let's consider the forward time evolution term of LDs, that is, $\mathcal{L}^f$. Take two neighboring ICs, one lying on the line that corresponds to the stable manifold and another slightly off it. If we integrate them for a time $\tau$, the initial condition that is on the manifold converges to the origin, while the other initial condition follows the arc of a hyperbola. If $\tau$ is small, both segments of trajectory are comparable in length, so that the value obtained from LDs for both ICs is almost equal. However, if we integrate the system for a larger $\tau$, the arclengths of the two trajectories become very different, because one converges while the other one diverges. Therefore, we can clearly see in {numref}`fig:1d_saddle` that the LD values vary significantly near the stable manifold in comparison to those elsewhere. Moreover, if we consider a curve of initial conditions that crosses transversely the stable manifold, the LD value along it attains a minimum on the manifold. Notice also that by the same argument we gave above, but constructing the backward time evolution term of LDs, $\mathcal{L}^b$, we can arrive to the conclusion that backward integration of initial conditions will highlight the unstable manifold of the hyperbolic equilibrium point at the origin. It is important to remark here that, although we have used above the simple linear saddle system as an example to illustrate how the method recovers phase space structure, this argument also applies to a nonlinear system with an hyperbolic point, whose stable and unstable manifolds are convoluted curves.
The sharp transitions obtained for the LD values across the stable and unstable manifolds, which imply large values of its gradient in the vicinity of them, are known in the literature as "singular features". These features present in the LD scalar field are very easy to visualize and detect when plotting the output provided by the method. We will see shortly that there exists a rigorous mathematical connection between the "singular features" displayed by the LD output and the stable and unstable manifolds of hyperbolic points. This result was first proved in {cite}`lopesino2017` for two-dimensional flows, it was extended to 3D dynamical systems in {cite}`gg2018`, and it has also been recently established for the stable and unstable manifolds of normally hyperbolic invariant manifolds in Hamiltonian systems with two or more degrees of freedom in {cite}`demian2017,naik2019a`. In fact, the derivation of this relationship relies on an alternative definition for LDs, where the positive scalar function accumulated along the trajectories of the system is the $p$-norm of the vector field that determines the flow. Considering this approach, the LD scalar field becomes now non-differentiable at the phase space points that belong to a stable or unstable manifold, and consequently the gradient at these locations is unbounded. This property is crucial in many ways, since it allows us to easily recover the location of the stable and unstable manifolds in the LD plot as if they were the edges of objects that appear in a digital photograph.
One key aspect that needs to be accounted for when setting up LDs for revealing the invariant manifolds in phase space, is the crucial role that the integration time $\tau$ plays in the definition of the method itself. It is very important to appreciate this point, since $\tau$ is the parameter responsible for controlling the complexity and intricate geometry of the phase space structures revealed in the scalar field displayed from the LD computation. A natural consequence of increasing the value for $\tau$ is that richer details of the underlying structures are unveiled, since this implies that we are incorporating more information about the past and future dynamical history of trajectories in the computation of LDs. This means that $\tau$ in some sense is intimately related to the time scales of the dynamical phenomena that occur in the model under consideration. This connection makes the integration time a problem-dependent parameter, and hence, there is no general "golden rule" for selecting its value for exploring phase space. Consequently, it is usually selected from the dynamical information obtained by performing beforehand several numerical experiments, and one needs to bear in mind the compromise that exists between the complexity of the structures revealed by the method to explain a certain dynamical mechanism, and the interpretation of the intricate manifolds displayed in the LD scalar output.
To finish this part on the arclength definition of LDs we show that the method is also capable of revealing other invariant sets in phase space such as KAM tori, by means of studying the convergence of the time averages of LDs. We illustrate this property with the 1 DoF linear Hamiltonian with a center equilibrium at the origin:
```{math}
---
label:
---
\begin{equation}
H(q,p) = \dfrac{\omega}{2} \left(p^2 + q^2\right) \quad \Leftrightarrow \quad
\begin{cases}
\dot{q} = \dfrac{\partial H}{\partial p} = \omega \, p \\[.4cm]
\dot{p} = -\dfrac{\partial H}{\partial q} = -\omega \, q
\end{cases}
\end{equation}
```
From the definition of the Hamiltonian we can see that the solutions to this system form a family of concentric circles about the origin with radius $R = \sqrt{2H/\omega}$. Moreover, each of this circles encloses an area of $A(H) = 2\pi H / \omega$. Using the definition of the Hamiltonian and the information provided by Hamilton's equations of motion we can easily evaluate the arclength LD for this system:
```{math}
---
label:
---
\begin{equation}
\mathcal{L}(q_0,p_0,\tau) = \int^{\tau}_{-\tau} \sqrt{\left(\dot{q}\right)^2 + \left(\dot{p}\right)^2} \; dt = \omega \int^{\tau}_{-\tau} \sqrt{q^2 + p^2} \; dt = 2 \tau \sqrt{2 \omega H_0}
\end{equation}
```
where the initial condition $(q_0,p_0)$ has energy $H = H_0$ and therefore it lies on a circular trajectory with radius $\sqrt{2H_0/\omega}$. Hence, in this case all trajectories constructed from initial conditions on that circle share the same LD value. Moreover, if we consider the convergence of the time average of LD, this yields:
```{math}
---
label:
---
\begin{equation}
\lim_{\tau \to \infty} \langle \, \mathcal{L}(\tau) \, \rangle = \dfrac{1}{2\tau} \int^{\tau}_{-\tau} \sqrt{\left(\dot{q}\right)^2 + \left(\dot{p}\right)^2} \; dt = \sqrt{2 \omega H_0} = \omega \sqrt{\frac{A}{\pi}}
\end{equation}
```
### The $p$-norm Definition
Besides the arclength definition of Lagrangian descriptors introduced in the previous subsection, there are many other versions used throughout the literature. An alternative definition of LDs, which is inspired by the $p$-norm of the vector field describing the dynamical system. We remark that we use the expression for $p\in(0,1]$, while the $p$-norm is only a norm for $p\geq 1$. For the sake of consistency with literature we retain the name $p$-norm even for $p<1$. The LD is defined as:
```{math}
---
label: eq:Mp_function
---
\begin{equation}
\mathcal{L}_p(\mathbf{x}_{0},t_0,\tau) = \int^{t_0+\tau}_{t_0-\tau} \, \sum_{k=1}^{n} \vert f_{k}(\mathbf{x}(t;\mathbf{x}_0),t) \vert^p \; dt \;, \quad p \in (0,1]
\label{eq:Mp_function}
\end{equation}
```
where $f_{k}$ is the $k$-th component of the vector field in Eq. {eq}`eq:gtp_dynSys` . Typically, the value used for the parameter $p$ in this version of the method is $p = 1/2$. Recall that all the variants of LDs can be split into its forward and backward time integration components in order to detect the stable and unstable manifolds separately. Hence, we can write:
```{math}
---
label:
---
\begin{equation}
\mathcal{L}_p(\mathbf{x}_{0},t_0,\tau) = \mathcal{L}^{b}_p(\mathbf{x}_{0},t_0,\tau) + \mathcal{L}^{f}_p(\mathbf{x}_{0},t_0,\tau)
\end{equation}
```
where we have that:
```{math}
---
label:
---
\begin{equation}
\begin{split}
\mathcal{L}_p^{b}(\mathbf{x}_{0},t_0,\tau) & = \int^{t_0}_{t_0-\tau} \sum_{k=1}^{n} |f_{k}(\mathbf{x}(t;\mathbf{x}_0),t)|^p \; dt \\[.2cm]
\mathcal{L}_p^{f}(\mathbf{x}_{0},t_0,\tau) & = \int^{t_0+\tau}_{t_0} \sum_{k=1}^{n} |f_{k}(\mathbf{x}(t;\mathbf{x}_0),t)|^p \; dt
\end{split}
\end{equation}
```
Although this alternative definition of LDs does not have such an intuitive physical interpretation as that of arclength, it has been shown to provide many advantages. For example, it allows for a rigorous analysis of the notion of "singular features" and to establish the mathematical connection of this notion to stable and unstable invariant manifolds in phase space. Another important aspect of the $p$-norm of LDs is that, since in the definition all the vector field components contribute separately, one can naturally decompose the LD in a way that allows to isolate individual degrees of freedom. This was used in {cite}`demian2017,naik2019a` to show that the method can be used to successfully detect NHIMs and their stable and unstable manifolds in Hamiltonian systems. Using the $p-$norm definition, it has been shown that the points on the LD contour map with non-differentiability identifies the invariant manifolds' intersections with the section on which the LD is computed, for specific systems {cite}`lopesino2017,demian2017,naik2019a`. In this context, where a fixed integration time is used, it has also been shown that the LD scalar field attains a minimum value at the locations of the stable and unstable manifolds, and hence:
```{math}
---
label: eq:min_LD_manifolds
---
\begin{equation}
\mathcal{W}^u(\mathbf{x}_{0},t_0) = \textrm{argmin } \mathcal{L}_p^{b}(\mathbf{x}_{0},t_0,\tau) \quad,\quad \mathcal{W}^s(\mathbf{x}_{0},t_0) = \textrm{argmin } \mathcal{L}_p^{f}(\mathbf{x}_{0},t_0,\tau) \;,
\label{eq:min_LD_manifolds}
\end{equation}
```
where $\mathcal{W}^u$ and $\mathcal{W}^s$ are, respectively, the unstable and stable manifolds calculated at time $t_0$ and $\textrm{argmin}(\cdot)$ denotes the phase space coordinates $\mathbf{x}_0$ that minimize the corresponding function. In addition, NHIMs at time $t_0$ can be calculated as the intersection of the stable and unstable manifolds:
```{math}
---
label: eq:min_NHIM_LD
---
\begin{equation}
\mathcal{N}(\mathbf{x}_{0},t_0) = \mathcal{W}^u(\mathbf{x}_{0},t_0) \cap \mathcal{W}^s(\mathbf{x}_{0},t_0) = \textrm{argmin } \mathcal{L}_p(\mathbf{x}_{0},t_0,\tau)
\label{eq:min_NHIM_LD}
\end{equation}
```
As we have pointed out, the location of the stable and unstable manifolds on the slice can be obtained by extracting them from the ridges of the gradient field, $\Vert \nabla \mathcal{L}^{f}_p \Vert$ or $\Vert \nabla \mathcal{L}^{b}_p \Vert$, respectively, since manifolds are located at points where the the forward and backward components of the function $\mathcal{L}_p$ are non-differentiable. Once the manifolds are known one can compute their intersection by means of a root search algorithm. In specific examples we have been able to extract NHIMs from the intersections. An alternative method to recover the manifolds and their associated NHIM is by minimizing the functions $\mathcal{L}^{f}_p$ and $\mathcal{L}^{b}_p$ using a search optimization algorithm. This second procedure and some interesting variations are described in {cite}`feldmaier2019`.
We finish the description of the $p$-norm version of LDs by showing that this definition recovers the stable and unstable manifolds of hyperbolic equilibria at phase space points where the scalar field is non-differentiable. We demonstrate this statement for the 1 DoF linear Hamiltonian introduced in Eq. {eq}`eq:Mp_function` that has a saddle equilibrium point at the origin. The general solution to this dynamical system can be written as:
```{math}
---
label:
---
\begin{equation}
q(t) = \dfrac{1}{2} \left(A e^{t} + B e^{-t}\right) \quad,\quad p(t) = \dfrac{1}{2} \left(A e^{t} - B e^{-t}\right)
\end{equation}
```
where $\mathbf{x}_0 = (q_0,p_0)$ is the initial condition and $A = q_0 + p_0$ and $B = q_0 - p_0$. If we compute the forward plus backward contribution of the LD function, we get that for $\tau$ sufficiently large the scalar field behaves asymptotically as:
```{math}
---
label: eq:M_hyp_asymp
---
\begin{equation}
\mathcal{L}_{p}\left(\mathbf{x}_0,\tau\right) \sim \left(|A|^{p} + |B|^{p}\right) e^{p \tau}
\label{eq:M_hyp_asymp}
\end{equation}
```
(sec:LDaction)=
### Lagrangian Descriptors Based on the Classical Action
In this section we discuss a formulation of Lagrangian descriptors that has a direct connection to classical Hamiltonian mechanics, namely the principle of least action. The principle of least action is treated in most advanced books on classical mechanics; see, for example, {cite}`arnol2013mathematical,goldstein2002classical,landau2013mechanics`. An intuitive and elementary discussion of the principle of least action is given by Richard Feynman in the following lecture <https://www.feynmanlectures.caltech.edu/II_19.html>,
To begin, we note that the general form of Lagrangian descriptors are as follows:
```{math}
---
label:
---
\begin{equation}
\mathcal{L}(\text{initial condition}) = \int_{t_0 - \tau}^{t_0 + \tau} \text{PositiveFunction} \, (\text{trajectory}) \; dt
\end{equation}
```
The positivity of the integrand is often imposed via an absolute value. In our discussion below we show that this is not necessary for the action.
#### One Degree-of-Freedom Autonomous Hamiltonian Systems
We consider a Hamiltonian of the form:
```{math}
---
label:
---
\begin{equation}
H(q, p) = \frac{p^2}{2m} + V(q) \;, \quad (q,p) \in \mathbb{R}^2.
\end{equation}
```
The integrand for the action integral is the following:
```{math}
---
label:
---
\begin{equation}
p \, dq \;,
\end{equation}
```
Using the chain rule and the definition of momentum, the following calculations are straightforward:
```{math}
---
label:
---
\begin{eqnarray}
p \, dq = p \frac{dq}{dt} dt = \frac{p^2}{m} dt \;.
\end{eqnarray}
```
The quantity $\frac{p^2}{m}$ is twice the kinetic energy and is known as the *vis viva*. It is the integrand for the integral that defines Maupertuis principle, which is very closely related to the principle of least action. We can also write $p \, dq$ slightly differently using Hamilton's equations:
```{math}
---
label:
---
\begin{equation}
\dfrac{p^2}{m}= 2 (H - V(q) ),
\end{equation}
```
from which it follows that:
```{math}
---
label:
---
\begin{equation}
p \, dq = \dfrac{p^2}{m} \, dt = 2 (H-V(q)) \, dt.
\end{equation}
```
Therefore, the positive quantities that appear multiplying the $dt$ are candidates for the integrand of Lagrangian descriptors {cite}`montoya2020phase`.
We will illustrate next how the action-based LDs successfully detects the stable invariant manifold of the hyperbolic equilibrium point in system introduced in Eq. {eq}`eq:1dof_saddle`. We know that the solutions to this dynamical system are given by the expressions:
```{math}
---
label:
---
\begin{equation}
q(t) = q_0 \cosh(t) + p_0 \sinh(t) \quad,\quad p(t) = p_0 \cosh(t) + q_0 \sinh(t)
\end{equation}
```
where $(q_0,p_0)$ represents any initial condition. We know from (refer to hyperbolic section) that the stable invariant manifold is given by $q = -p$. We compute the forward LD:
```{math}
---
label:
---
\begin{equation}
\begin{split}
\mathcal{A}^{f}(q_0,p_0,\tau) & = \int_{0}^{\tau} p \, \dfrac{dq}{dt} \, dt = \int_{0}^{\tau} p^2 \, dt = \\[.2cm]
& = \dfrac{1}{2} \left(p_0^2 - q_0^2\right) \tau + \dfrac{1}{4}\left(q_0^2 + p_0^2\right) \sinh(2\tau) + \dfrac{1}{2} q_0 \, p_0 \left(\cosh(2\tau) - 1\right)
\end{split}
\end{equation}
```
It is a simple exercise to check that $\mathcal{A}^{f}$ attains a local minimum at the points:
```{math}
---
label:
---
\begin{equation}
q_0 = - \dfrac{\cosh(2\tau) - 1}{\sinh(2\tau) - 2 \tau} \, p_0
\end{equation}
```
#### $n$ Degree-of-Freedom Autonomous Hamiltonian Systems
The above calculations for one DoF are easily generalized to $n$ degrees-of-freedom. We begin with a Hamiltonian of the form:
```{math}
---
label:
---
\begin{equation}
H(q_1, \ldots, q_n, p_1, \ldots, p_n) = \sum_{i=1}^n \dfrac{p_i^2}{2m_i} + V(q_1, \ldots, q_n) \;, \quad (q_1, \ldots, q_n, p_1, \ldots, p_n) \in \mathbb{R}^{2n}.
\end{equation}
```
The integrand for the action integral is the following:
```{math}
---
label:
---
\begin{equation}
p_1dq_1 + \cdots + p_n dq_n \quad , \quad p_i\equiv m_i \frac{dq_i}{dt} \;, \quad i \in \lbrace 1,\ldots,n \rbrace
\end{equation}
```
As above, using the chain rule and the definition of the momentum, we get:
```{math}
---
label:
---
\begin{equation}
p_1dq_1 + \cdots + p_n dq_n = \sum_{i=1}^n p_i \frac{dq_i}{dt} dt = \sum_{i=1}^n \dfrac{p_i^2}{m_i} dt
\end{equation}
```
where the quantity $\sum_{i=1}^n \dfrac{p_i^2}{m_i}$ is twice the kinetic energy and is the vis-viva in the $n$ degree-of-freedom setting. We can write $p_1dq_1 + \cdots + p_n dq_n $ slightly differently using Hamilton's equations,
```{math}
---
label:
---
\begin{equation}
\sum_{i=1}^n \frac{p_i ^2}{2m_i} = 2 (H - V(q_1, \ldots, q_n) )
\end{equation}
```
from which it follows that
```{math}
---
label:
---
\begin{equation}
p_1dq_1 + \cdots + p_n dq_n = \sum_{i=1}^n \frac{p_i ^2}{2m_i} dt = 2 (H-V(q_1, \ldots, q_n)) dt
\end{equation}
```
## Variable Integration Time Lagrangian Descriptors
At this point, we would like to discuss the issues that might arise from the definitions of LDs provided in Eqs. {eq}`eq:M_function` and {eq}`eq:Mp_function` when they are applied to analyze the dynamics in open Hamiltonian systems, that is, those for which phase space dynamics occurs in unbounded energy hypersurfaces. Notice that in both definitions, all the initial conditions considered by the method are integrated forward and backward for the same time $\tau$. Recent studies have revealed {cite}`junginger2017chemical,naik2019b,GG2020a` issues with trajectories that escape to infinity in finite time or at an increasing rate. The trajectories that show this behavior will give NaN (not-a-number) values in the LD scalar field, hiding some regions of the phase space, and therefore obscuring the detection of invariant manifolds. In order to circumvent this problem we explain here the approach that has been recently adopted in the literature {cite}`junginger2017chemical,naik2019b,GG2020a` known as variable integration time Lagrangian descriptors. In this methodology, LDs at any initial condition are calculated for a fixed initial integration time $\tau_0$ or until the trajectory corresponding to that initial condition leaves a certain phase space region $\mathcal{R}$ that we call the *interaction region*, whichever happens first. Therefore the total integration time depends on the initial conditions, that is $\tau(\mathbf{x}_0)$. In this variable-time formulation, given a fixed integration time $\tau_0 > 0$, the $p$-norm definition of LDs with $p \in (0,1]$ will take the form:
```{math}
---
label: eq:Mp_vt
---
\begin{equation}
\mathcal{L}_p(\mathbf{x}_{0},t_0,\tau_0) = \int^{t_0 + \tau^{+}_{\mathbf{x}_0}}_{t_0 - \tau^{-}_{\mathbf{x}_0}} \sum_{k=1}^{n} |f_{k}(\mathbf{x}(t;\mathbf{x}_0),t)|^p \; dt = \mathcal{L}^{f}_p(\mathbf{x}_{0},t_0,\tau) + \mathcal{L}^{b}_p(\mathbf{x}_{0},t_0,\tau)
\label{eq:Mp_vt}
\end{equation}
```
where the total integration time used for each initial condition is defined as:
```{math}
\begin{equation*}
\tau^{\pm}_{\mathbf{x}_{0}}(\tau_0,\mathcal{R}) = \min \left\lbrace \tau_0 \, , \, |t^{\pm}| \right\rbrace \; ,
\end{equation*}
```
and $t^{+}$, $t^{-}$ represent the times for which the trajectory leaves the interaction region $\mathcal{R}$ in forward and backward time respectively.
It is important to highlight that the variable time integration LD has also the capability of capturing the locations of the stable and unstable manifolds present in the phase space slice used for the computation, and it will do so at points where the LD values vary significantly. Moreover, KAM tori will also be detected by the contour values of the time-averaged LD. Therefore, the variable integration time LDs provides us with a suitable methodology to study the phase space structures that characterize escaping dynamics in open Hamiltonians, since it avoids the issue of trajectories escaping to infinity very fast. It is important to remark here that this alternative approach for computing LDs can be adapted to other definitions of the method, where a different positive and bounded function is integrated along the trajectories of the dynamical system. For example, going back to the arclength definition of LDs, the variable integration time strategy would yield the formulation:
```{math}
---
label: eq:M_vt
---
\begin{equation}
\mathcal{L}(\mathbf{x}_{0},t_0,\tau_0) = \int^{t_0 + \tau^{+}_{\mathbf{x}_0}}_{t_0 - \tau^{-}_{\mathbf{x}_0}} \Vert \mathbf{f}(\mathbf{x}(t;\mathbf{x}_0),t) \Vert \, dt
\label{eq:M_vt}
\end{equation}
```
## Examples
### The Duffing Oscillator
In the next example, we illustrate how the arclength and the function $M$ LDs capture the stable and unstable manifolds that determine the phase portrait of the forced and undamped Duffing oscillator. The Duffing equation arises when studying the motion of a particle on a line, i.e. a one DoF system, subjected to the influence of a symmetric double well potential and an external forcing. The second order ODE that describes this oscillator is given by:
```{math}
---
label:
---
\begin{equation}
\ddot{x} + x^3 - x = \varepsilon f(t)
\end{equation}
```
where $\varepsilon$ represents the strength of the forcing term $f(t)$, and we choose for this example a sinusoidal force $f(t) = \sin(\omega t + \phi)$, where $\omega$ the angular frequency and $\phi$ the phase of the forcing. Reformulated using a Hamiltonian function $H$, this system can be written as:
```{math}
---
label:
---
\begin{equation}
H(x,y) = \dfrac{1}{2} y^2 + \dfrac{1}{4} x^4 - \dfrac{1}{2} x^2 - \varepsilon f(t) x \quad \Leftrightarrow \quad
\begin{cases}
\dot{x} = y \\
\dot{y} = x - x^3 + \varepsilon f(t) \\
\end{cases}
\end{equation}
```
In the autonomous case, i.e. $\varepsilon = 0$, the system has three equilibrium points: a saddle located at the origin and two diametrically opposed centers at the points $(\pm 1,0)$. The stable and unstable manifolds that emerge from the saddle point form two homoclininc orbits in the form of a figure eight around the two center equilibria:
```{math}
---
label: eq:duff_homocMani
---
\begin{equation}
\mathcal{W}^{s} = \mathcal{W}^{u} = \left\{(x,y) \in \mathbb{R}^2 \; \Big| \; 2y^2 + x^4 - 2x^2 = 0 \right\}
\label{eq:duff_homocMani}
\end{equation}
```
```{figure} figures/duffing_tau_2.png
---
name:
---
Phase portrait of the autonomous and undamped Duffing oscillator obtained by applying the arclength definition of LDs in Eq. {eq}`eq:M_function` . A) LDs with $\tau = 2$
```
```{figure} figures/duffing_tau_10.png
---
name:
---
Phase portrait of the autonomous and undamped Duffing oscillator obtained by applying the arclength definition of LDs in Eq. {eq}`eq:M_function` . B) LDs with $\tau = 10$
```
```{figure} figures/duffing_maniDetect.png
---
name: fig:duffing1_lds
---
Phase portrait of the autonomous and undamped Duffing oscillator obtained by applying the arclength definition of LDs in Eq. {eq}`eq:M_function` . C) Value of LDs along the line $y = 0.5$ depicted in panel B) illustrating how the method detects the stable and unstable manifolds at points where the scalar field changes abruptly.
```
\label{fig:duffing1_lds}
\caption{Phase portrait of the autonomous and undamped Duffing oscillator obtained by applying the arclength definition of LDs in Eq. {eq}`eq:M_function`. A) LDs with $\tau = 2$; B) LDs with $\tau = 10$; C) Value of LDs along the line $y = 0.5$ depicted in panel B) illustrating how the method detects the stable and unstable manifolds at points where the scalar field changes abruptly.}
We move on to compute LDs for the forced Duffing oscillator. In this situation, the vector field is time-dependent and thus the dynamical system is nonautonomous. The consequence is that the homoclinic connection breaks up and the stable and unstable manifolds intersect, forming an intricate tangle that gives rise to chaos. We illustrate this phenomenon by computing LDs with $\tau = 10$ to reconstruct the phase portrait at the initial time $t_0 = 0$. For the forcing, we use a perturbation strength $\varepsilon = 0.1$, an angular frequency of $\omega = 1$ and a phase $\phi = 0$. This result is shown in {numref}`fig:duffing2_lds` C), and we also depict the forward $(\mathcal{L}^f)$ and backward $(\mathcal{L}^b)$ contributions of LDs in {numref}`fig:duffing2_lds` A) and B) respectively, demonstrating that the method can be used to recover the stable and unstable manifolds separately. Furthermore, by taking the value of LDs along the line $y = 0.5$, the location of the invariant manifolds are highlighted at points corresponding to sharp changes (and local minima) in the scalar field values of LDs.
```{figure} figures/duffing_stbl_tau_10_pert_01.png
---
name:
---
Phase portrait of the nonautonomous and undamped Duffing oscillator obtained at time $t = 0$ by applying the arclength definition of LDs in Eq. {eq}`eq:M_function` with an integration time $\tau = 10$. A) Forward LDs detect stable manifolds
```
```{figure} figures/duffing_unstbl_tau_10_pert_01.png
---
name:
---
Phase portrait of the nonautonomous and undamped Duffing oscillator obtained at time $t = 0$ by applying the arclength definition of LDs in Eq. {eq}`eq:M_function` with an integration time $\tau = 10$. B) Backward LDs highlight unstable manifolds of the system
```
```{figure} figures/duffing_tau_10_pert_01.png
---
name:
---
Phase portrait of the nonautonomous and undamped Duffing oscillator obtained at time $t = 0$ by applying the arclength definition of LDs in Eq. {eq}`eq:M_function` with an integration time $\tau = 10$. C) Total LDs (forward $+$ backward) showing that all invariant manifolds are recovered simultaneously.
```
```{figure} figures/duffing_maniDetect_pert_01.png
---
name: fig:duffing2_lds
---
Phase portrait of the nonautonomous and undamped Duffing oscillator obtained at time $t = 0$ by applying the arclength definition of LDs in Eq. {eq}`eq:M_function` with an integration time $\tau = 10$. D) Value taken by LDs along the line $y = 0.5$ in panel C) to illustrate how the method detects the stable and unstable manifolds at points where the scalar field changes abruptly.
```
\label{fig:duffing2_lds}
\caption{Phase portrait of the nonautonomous and undamped Duffing oscillator obtained at time $t = 0$ by applying the arclength definition of LDs in Eq. {eq}`eq:M_function` with an integration time $\tau = 10$. A) Forward LDs detect stable manifolds; B) Backward LDs highlight unstable manifolds of the system; C) Total LDs (forward $+$ backward) showing that all invariant manifolds are recovered simultaneously. D) Value taken by LDs along the line $y = 0.5$ in panel C) to illustrate how the method detects the stable and unstable manifolds at points where the scalar field changes abruptly.}
### The linear Hamiltonian saddle with 2 DoF
Consider the two DoF system given by the linear quadratic Hamiltonian associated to an index-1 saddle at the origin. This Hamiltonian and the equations of motion are given by the expressions:
```{math}
---
label: eq:index1_Ham
---
\begin{eqnarray}
H(x,y,p_x,p_y) = \dfrac{\lambda}{2}\left(p_x^2 - x^2\right) + \dfrac{\omega}{2} \left(p_y^2 + y^2 \right) \quad,\quad \begin{cases}
\dot{x} = \lambda \, p_x \\
\dot{p}_{x} = \lambda \, x \\
\dot{y} = \omega \, p_y \\
\dot{p}_{y} = -\omega \, y
\end{cases}
\label{eq:index1_Ham}
\end{eqnarray}
```
```{figure} figures/LD_p_05_Saddle_tau_10.png
---
name:
---
Phase portrait in the saddle space of the linear Hamiltonian given in Eq. {eq}`eq:index1_Ham`. A) Application of the $p$-norm definition of LDs in Eq. {eq}`eq:Mp_function` using $p = 1/2$ with $\tau = 10$.
```
```{figure} figures/manifolds_Saddle_tau_10.png
---
name:
---
B) Stable (blue) and unstable (red) invariant manifolds of the unstable periodic orbit at the origin extracted from the gradient of the $M_p$ function.
```
```{figure} figures/detectMani_Saddle_tau_10.png
---
name: eq:index1_lds
---
C) Value of LDs along the line $p_x = 0.5$ depicted in panel A) to illustrate how the method detects the stable and unstable manifolds at points where the scalar field is singular or non-differentiable and attains a local minimum.
```
\label{fig:index1_lds}
\caption{Phase portrait in the saddle space of the linear Hamiltonian given in Eq. {eq}`eq:index1_Ham` . A) Application of the $p$-norm definition of LDs in Eq. {eq}`eq:Mp_function` using $p = 1/2$ with $\tau = 10$; B) Stable (blue) and unstable (red) invariant manifolds of the unstable periodic orbit at the origin extracted from the gradient of the $M_p$ function; C) Value of LDs along the line $p_x = 0.5$ depicted in panel A) to illustrate how the method detects the stable and unstable manifolds at points where the scalar field is singular or non-differentiable and attains a local minimum.}
### The Cubic Potential
In order to illustrate the issues encountered by the fixed integration time LDs and how the variable integration approach resolves them, we apply the method to a basic one degree-of-freedom Hamiltonian known as the "fish potential", which is given by the formula:
```{math}
---
label: eq:fish_Ham
---
\begin{equation}
H = \dfrac{1}{2} p_x^2 + \dfrac{1}{2} x^2 + \dfrac{1}{3} x^3 \quad \Leftrightarrow \quad
\begin{cases}
\dot{x} = p_x \\
\dot{p}_{x} = - x - x^2
\end{cases} \;.
\label{eq:fish_Ham}
\end{equation}
```
```{figure} figures/LDfixTime_p_05_fishPot_tau_3.png
---
name:
---
Phase portrait of the "fish potential" Hamiltonian in Eq. {eq}`eq:fish_Ham` revealed by the $p$-norm LDs with $p = 1/2$. A) Fixed-time integration LDs in Eq. {eq}`eq:Mp_function` with $\tau = 3$
```
```{figure} figures/LD_p_05_fishPot_tau_8.png
---
name:
---
Phase portrait of the "fish potential" Hamiltonian in Eq. {eq}`eq:fish_Ham` revealed by the $p$-norm LDs with $p = 1/2$. B) Variable-time integration definition of LDs in Eq. {eq}`eq:Mp_vt` with $\tau = 8$
```
```{figure} figures/manifolds_fishPot_tau_8.png
---
name: eq:fish_lds
---
Phase portrait of the "fish potential" Hamiltonian in Eq. {eq}`eq:fish_Ham` revealed by the $p$-norm LDs with $p = 1/2$. C) Invariant stable (blue) and unstable (red) manifolds of the saddle fixed point extracted from the gradient of the variable time $M_p$ function.
```
\label{fig:fish_lds}
\caption{Phase portrait of the "fish potential" Hamiltonian in Eq. {eq}`eq:fish_Ham` revealed by the $p$-norm LDs with $p = 1/2$. A) Fixed-time integration LDs in Eq. {eq}`eq:Mp_function` with $\tau = 3$; B) Variable-time integration definition of LDs in Eq. {eq}`eq:Mp_vt` with $\tau = 8$; C) Invariant stable (blue) and unstable (red) manifolds of the saddle fixed point extracted from the gradient of the variable time $M_p$ function.}
### The Hénon-Heiles Hamiltonian System
We continue illustrating how to apply the method of Lagrangian descriptors to unveil the dynamical skeleton in systems with a high-dimensional phase space by applying this tool to a hallmark Hamiltonian of nonlinear dynamics, the Hénon-Heiles Hamiltonian. This model was introduced in 1964 to study the motion of stars in galaxies {cite}`henon1964` and is described by:
```{math}
---
label: eq:henon_system
---
\begin{equation}
H = \dfrac{1}{2} \left(p_x^2 + p_y^2\right) + \dfrac{1}{2}\left(x^2 + y^2\right) + x^2y - \dfrac{1}{3} y^3 \quad \Leftrightarrow \quad
\begin{cases}
\dot{x} = p_x \\
\dot{p}_{x} = - x - 2xy \\
\dot{y} = p_y \\
\dot{p}_{y} = - y - x^2 + y^2
\end{cases} \;.
\label{eq:henon_system}
\end{equation}
```
which has four equilibrium points: one minimum located at the origin and three saddle-center points at $(0,1)$ and $(\pm \sqrt{3}/2,-1/2)$. The potential energy surface is
$${
V(x,y) = x^2/2 + y^2/2 + x^2y - y^3/3
}$$
which has a $\pi/3$ rotational symmetry and is characterized by a central scattering region about the origin and three escape channels, see {numref}`fig:henonHeiles_pes` below for details.
In order to analyze the phase space of the Hénon-Heiles Hamiltonian by means of the variable integration time LDs, we fix an energy $H = H_0$ of the system and choose an interaction region $\mathcal{R}$ defined in configuration space by a circle of radius $15$ centered at the origin. For our analysis we consider the following phase space slices:
```{math}
---
label: eq:psos
---
\begin{eqnarray}
\mathcal{U}^{+}_{y,p_y} & = \left\{(x,y,p_x,p_y) \in \mathbb{R}^4 \;|\; H = H_0 \;,\; x = 0 \;,\; p_x > 0\right\} \\[.1cm]
\mathcal{V}^{+}_{x,p_x} &= \left\{(x,y,p_x,p_y) \in \mathbb{R}^4 \;|\; H = H_0 \;,\; y = 0 \;,\; p_y > 0\right\}
\label{eq:psos}
\end{eqnarray}
```
```{figure} figures/henonheiles_pot.png
---
name:
---
Potential energy surface for the Hénon-Heiles system.
```
```{figure} figures/hen_conts.png
---
name: fig:henonHeiles_pes
---
Potential energy surface projected onto XY plane for the Hénon-Heiles system.
```
\label{fig:henonHeiles_pes}
\caption{Potential energy surface for the Hénon-Heiles system.}
```{figure} figures/LDs_Henon_tau_50_x_0_E_1div12.png
---
name:
---
Phase space structures of the Hénon-Heiles Hamiltonian as revealed by the $p$-norm variable integration time LDs with $p = 1/2$. A) LDs computed for $\tau = 50$ in the SOS $\mathcal{U}^{+}_{y,p_y}$ with energy $H = 1/12$
```
```{figure} figures/Mani_Henon_tau_50_x_0_E_1div12.png
---
name:
---
Gradient of the LD function showing stable and unstable manifold intersections in blue and red respectively.
```
```{figure} figures/LDs_Henon_tau_10_x_0_E_1div3.png
---
name:
---
Phase space structures of the Hénon-Heiles Hamiltonian as revealed by the $p$-norm variable integration time LDs with $p = 1/2$. B) LDs for $\tau = 10$ in the SOS $\mathcal{U}^{+}_{y,p_y}$ with energy $H = 1/3$
```
```{figure} figures/Mani_Henon_tau_10_x_0_E_1div3.png
---
name:
---
Gradient of the LD function showing stable and unstable manifold intersections in blue and red respectively.
```
```{figure} figures/LDs_Henon_tau_10_y_0_E_1div3.png
---
name:
---
Phase space structures of the Hénon-Heiles Hamiltonian as revealed by the $p$-norm variable integration time LDs with $p = 1/2$. C) LDs for $\tau = 10$ in the SOS $\mathcal{V}^{+}_{x,p_x}$ with energy $H = 1/3$
```
```{figure} figures/Mani_Henon_tau_10_y_0_E_1div3.png
---
name: fig:henonHeiles_lds
---
Gradient of the LD function showing stable and unstable manifold intersections in blue and red respectively.
```
\label{fig:henonHeiles_lds}
\caption{Phase space structures of the Hénon-Heiles Hamiltonian as revealed by the $p$-norm variable integration time LDs with $p = 1/2$. A) LDs computed for $\tau = 50$ in the SOS $\mathcal{U}^{+}_{y,p_y}$ with energy $H = 1/12$; C) LDs for $\tau = 10$ in the SOS $\mathcal{U}^{+}_{y,p_y}$ with energy $H = 1/3$; E) LDs for $\tau = 10$ in the SOS $\mathcal{V}^{+}_{x,p_x}$ with energy $H = 1/3$;. In the right panels we have extracted the invariant stable (blue) and unstable (red) manifolds from the gradient of LDs.}
## Stochastic Lagrangian Descriptors
Lagrangian descriptors were extended to stochastic dynamical systems in {cite}`balibrea2016lagrangian`, and our discussion here is taken from this source, where the reader can also find more details. A basic introduction to stochastic differential equations is in the book {cite}`Oksendal2003`.
(sec:pc)=
### Preliminary concepts
Lagrangian descriptors are a trajectory based diagnostic. Therefore we first need to develop the concepts required to
describe the nature of trajectories of stochastic differential equations (SDEs). We begin by
considering a general system of SDEs expressed in differential form as follows:
```{math}
---
label: eq:SDE
---
\begin{equation}
\label{eq:SDE}
dX_{t} = b(X_{t},t)dt + \sigma (X_{t},t)dW_{t}, \quad t \in \mathbb{R},
\end{equation}
```
where $b(\cdot) \in C^{1}(\mathbb{R}^{n}\times \mathbb{R})$ is the deterministic part, $\sigma (\cdot) \in C^{1}(\mathbb{R}^{n}\times \mathbb{R})$ is the random forcing, $W_{t}$ is a Wiener process (also referred to as Brownian motion) whose definition we give later, and $X_{t}$ is the solution of the equation. All these functions take values in $\mathbb{R}^{n}$.
As the notion of solution of a SDE is closely related with the Wiener process, we state what is meant by $W(\cdot )$. This definition is given in {cite}`duan15`, and this reference serves to provide the background for all of the notions in this section. Also, throughout we will use $\Omega$ to denote the probability space where the Wiener process is defined.
(def:Wiener)=
__Definition__ _Wiener/Brownian process_
A real valued stochastic Wiener or Brownian process $W(\cdot)$ is a stochastic process defined in a probability space $(\Omega , {\cal F},{\cal P})$ which satisfies
1. $W_0 = 0$ (standard Brownian motion),
2. $W_t - W_s$ follows a Normal distribution $N(0,t-s)$ for all $t\geq s \geq 0$,
3. for all time $0 < t_1 < t_2 < ... < t_n$, the random variables $W_{t_1}, W_{t_2} - W_{t_1},... , W_{t_n} - W_{t_{n-1}}$ are independent (independent increments).
Moreover, $W(\cdot)$ is a real valued two-sided Wiener process if conditions (ii) and (iii) change into
2. $W_t - W_s$ follows a Normal distribution $N(0,|t-s|)$ for all $t, s \in \mathbb{R}$,
3. for all time $t_1 , t_2 , ... , t_{2n} \in \mathbb{R}$ such that the intervals $\lbrace (t_{2i-1},t_{2i}) \rbrace_{i=1}^{n}$ are non-intersecting between them (_Note_), the random variables $W_{t_1}-W_{t_2}, W_{t_3} - W_{t_4},... , W_{t_{2n-1}} - W_{t_{2n}}$ are independent.
````{margin}
```{note}
With the notation $(t_{2i-1},t_{2i})$ we refer to the interval of points between the values $t_{2i-1}$ and $t_{2i}$, regardless the order of the two extreme values. Also with the assertion we impose that every pair of intervals of the family $\lbrace (t_{2i-1},t_{2i}) \rbrace_{i=1}^{n}$ has an empty intersection, or alternatively that the union $\bigcup_{i=1}^{n}(t_{2i-1},t_{2i})$ is conformed by $n$ distinct intervals over $\mathbb{R}$.
```
````
This method of Lagrangian descriptors has been developed for deterministic differential equations whose temporal domain is $\mathbb{R}$. In this sense it is natural to work with two-sided solutions as well as two-sided Wiener processes. Henceforth, every Wiener process $W(\cdot )$ considered in the this article will be of this form.
Given that any Wiener process $W(\cdot )$ is a stochastic process, by definition this is a family of random real variables $\lbrace W_{t}, t\in \mathbb{R} \rbrace$ in such a way that for each $\omega \in \Omega$ there exists a mapping, $ t \longmapsto W_{t}(\omega )$, known as the trajectory of a Wiener process.
Analogously to the Wiener process, the solution $X_{t}$ of the SDE {eq}`eq:SDE` is also a stochastic process. In particular, it is a family of random variables $\lbrace X_{t}, t\in \mathbb{R} \rbrace$ such that for each $\omega \in \Omega$, the trajectory of $X_{t}$ satisfies
```{math}
---
label: eq:Xt
---
\begin{equation}
\label{Xt}
t \longmapsto X_{t}(\omega ) = X_{0}(\omega ) + \int_{0}^{t} b(X_{s}(\omega ), s)ds + \int_{0}^{t} \sigma (X_{s}(\omega ), s)dW_{s}(\omega ),
\end{equation}
```
where $X_{0}:\Omega \rightarrow \mathbb{R}^{n}$ is the initial condition. In addition, as $b(\cdot)$ and $\sigma(\cdot)$ are smooth functions, they are locally Lipschitz and this leads to existence and pathwise uniqueness of a local, continuous solution (see {cite}`duan15`). That is if any two stochastic processes $X^1$ and $X^2$ are local solutions in time of SDE {eq}`eq:SDE` , then $X^1_t(\omega) = X^2_t(\omega)$ over a time interval $t \in (t_{i},t_{f})$ and for almost every $\omega \in \Omega$.
At each instant of time $t$, the deterministic integral $\int_{0}^{t} b(X_{s}(\omega ))ds$ is defined by the usual Riemann integration scheme since $b$ is assumed to be a differentiable function. However, the stochastic integral term is chosen to be defined by the It\^{o} integral scheme:
```{math}
---
label: eq:Ito
---
\begin{equation}
\label{Ito}
\int_{0}^{t} \sigma (X_{s}(\omega ),s)dW_{s}(\omega ) = \lim_{N \rightarrow \infty} \sum_{i=0}^{N-1} \sigma (X_{i\frac{t}{N}}(\omega ), it/N) \cdot \left[ W_{(i+1)\frac{t}{N}}(\omega ) - W_{i\frac{t}{N}}(\omega ) \right].
\end{equation}
```
This scheme will also facilitate the implementation of a numerical method for computing approximations for the solution $X_{t}$ in the next section.
Once the notion of solution, $X_{t}$, of a SDE {eq}`eq:SDE` is established, it is natural to ask if the same notions and ideas familiar from the study of deterministic differential equations from the dynamical systems point of view are still valid for SDEs. In particular, we want to consider the notion of hyperbolic trajectory and its stable and unstable manifolds in the context of SDEs. We also want to consider how such notions would manifest themselves in the context of *phase space transport* for SDEs, and the stochastic Lagrangian descriptor will play a key role in considering these questions from a practical point of view.
We first discuss the notion of an invariant set for a SDE.
In the deterministic case the simplest possible invariant set is a single trajectory of the differential equation. More precisely, it is the set of points through which a solution passes. Building on this construction, an invariant set is a collection of trajectories of different solutions. This is the most basic way to characterize the invariant sets with respect to a deterministic differential equation of the form
```{math}
---
label: eq:deterministic_system
---
\begin{equation}
\label{deterministic_system}
\dot{x} = f(x,t), \quad x \in \mathbb{R}^{n}, \quad t \in \mathbb{R}.
\end{equation}
```
For verifying the invariance of such sets the solution mapping generated by the vector field is used. For deterministic autonomous systems these are referred to as *flows* (or "dynamical systems") and for deterministic nonautonomous systems they are referred to as *processes*. The formal definitions can be found in {cite}`kloe11`.
A similar notion of solution mapping for SDEs is introduced using the notion of a random dynamical system $\varphi$ (henceforth referred to as RDS) in the context of SDEs. This function $\varphi$ is also a solution mapping of a SDE that satisfies several conditions, but compared with the solution mappings in the deterministic case, this RDS depends on an extra argument which is the random variable $\omega \in \Omega$. Furthermore the random variable $\omega$ evolves with respect to $t$ by means of a dynamical system $\lbrace \theta_{t} \rbrace_{t \in \mathbb{R}}$ defined over the probability space $\Omega$.
(rds)=
__Definition__ _Random Dynamical System_
````{margin}
```{note}
Given the probability measure $\mathcal{P}$ associated with the space $(\Omega , \mathcal{F},\mathcal{P})$, this remains invariant under the dynamical system $\lbrace \theta_{t} \rbrace_{t \in \mathbb{R}}$. Formally, $\theta_{t}\mathcal{P} = \mathcal{P}$ for every $t \in \mathbb{R}$. This statement means that $\mathcal{P}(B)=\mathcal{P}(\theta_{t}(B))$ for every $t \in \mathbb{R}$ and every subset $B \in \mathcal{F}$. Indeed for any dynamical system $\lbrace \theta_{t} \rbrace_{t \in \mathbb{R}}$ defined over the same probability space $\Omega$ as a Wiener process $W(\cdot )$, we have the equality $W_{s}(\theta_{t}\omega ) = W_{t+s}(\omega )-W_{t}(\omega )$ which implies that $dW_{s}(\theta_{t}\omega ) = dW_{t+s}(\omega )$ for every $s,t \in \mathbb{R}$ (see {cite}`duan15` for a detailed explanation).
```
````
Let $\lbrace \theta_{t} \rbrace_{t \in \mathbb{R}}$ be a measure-preserving (_Note_) dynamical system defined over $\Omega$, and let $\varphi : \mathbb{R} \times \Omega \times \mathbb{R}^{n} \rightarrow \mathbb{R}^{n}$ be a measurable mapping such that $(t,\cdot , x) \mapsto \varphi (t,\omega ,x)$ is continuous for all $\omega \in \Omega$, and the family of functions $\lbrace \varphi (t,\omega ,\cdot ): \mathbb{R}^{n} \rightarrow \mathbb{R}^{n} \rbrace$ has the cocycle property:
$$ \varphi (0,\omega ,x)=x \quad \text{and} \quad \varphi (t+s,\omega ,x) = \varphi(t,\theta_{s}\omega,\varphi (s,\omega ,x)) \quad \text{for all } t,s \in \mathbb{R}, \text{ } x \in \mathbb{R}^{n} \text{ and } \omega \in \Omega .$$
Then the mapping $\varphi$ is a random dynamical system with respect to the stochastic differential equation
\begin{equation*}
dX_{t} = b(X_{t})dt + \sigma (X_{t})dW_{t}
\end{equation*}
if $\varphi (t,\omega ,x)$ is a solution of the equation.
Analogous to the deterministic case, the definition of invariance with respect to a SDE can be characterized in terms of a RDS. This is an important topic in our consideration of stochastic Lagrangian descriptors. Now we introduce an example of a SDE for which the analytical expression of the RDS is obtained. This will be a benchmark example in our development of stochastic Lagrangian descriptors their relation to stochastic invariant manifolds.
**Noisy saddle point**
For the stochastic differential equation
```{math}
---
label: eq:noisy_saddle
---
\begin{equation}
\label{noisy_saddle}
\begin{cases} dX_{t} = X_{t}dt + dW_{t}^{1} \\ dY_{t} = -Y_{t}dt + dW_{t}^{2} \end{cases}
\end{equation}
```
where $W_{t}^{1}$ and $W_{t}^{2}$ are two different Wiener processes, the solutions take the expressions
```{math}
---
label: eq:noisy_saddle_solutions
---
\begin{equation}
\label{noisy_saddle_solutions}
X_{t} = e^{t} \left( X_{0}(\omega ) + \int_{0}^{t}e^{-s}dW_{s}^{1}(\omega ) \right) \quad , \quad Y_{t} = e^{-t} \left( Y_{0}(\omega ) + \int_{0}^{t}e^{s}dW_{s}^{2}(\omega ) \right)
\end{equation}
```
and therefore the random dynamical system $\varphi$ takes the form
```{math}
---
label: eq:noisy_saddle_RDS
---
\begin{equation}
\label{noisy_saddle_RDS}
\begin{array}{ccccccccc}
\varphi : & & \mathbb{R} \times \Omega \times \mathbb{R}^{2} & & \longrightarrow & & \mathbb{R}^{2} & & \\ & & (t,\omega ,(x,y)) & & \longmapsto & & \left( \varphi_{1}(t,\omega ,x),\varphi_{2}(t,\omega ,y) \right) & = & \left( e^{t} \left( x + \int_{0}^{t}e^{-s}dW_{s}^{1}(\omega ) \right) , e^{-t} \left( y + \int_{0}^{t}e^{s}dW_{s}^{2}(\omega ) \right) \right) . \end{array}
\end{equation}
```
Notice that this last definition {ref}`Random Dynamical System<rds>` is expressed in terms of SDEs with time-independent coefficients $b,\sigma$. For more general SDEs a definition of nonautonomous RDS is developed in {cite}`duan15`. However, for the remaining examples considered in this article we make use of the already given definition of RDS.
Once we have the notion of RDS, it can be used to describe and detect geometrical structures and determine their influence on the dynamics of trajectories. Specifically, in clear analogy with the deterministic case, we focus on those trajectories whose expressions do not depend explicitly on time $t$, which are referred as *random fixed points*. Moreover, their stable and unstable manifolds, which may also depend on the random variable $\omega$, are also objects of interest due to their influence on the dynamical behavior of nearby trajectories. Both types of objects are invariant. Therefore we describe a characterization of invariant sets with respect to a SDE by means of an associated RDS.
(invariant_set)=
__Definition__ _Invariant Set_
A non empty collection $M : \Omega \rightarrow \mathcal{P}(\mathbb{R}^{n})$, where $M(\omega ) \subseteq \mathbb{R}^{n}$ is a closed subset for every $\omega \in \Omega$, is called an invariant set for a random dynamical system $\varphi$ if
```{math}
---
label: eq:invariance
---
\begin{equation}
\label{invariance}
\varphi (t,\omega ,M(\omega )) = M(\theta_{t}\omega ) \quad \text{for every } t \in \mathbb{R} \text{ and every } \omega \in \Omega.
\end{equation}
```
Again, we return to the noisy saddle {eq}`eq:noisy_saddle` , which is an example of a SDE for which several invariant sets can be easily characterized by means of its corresponding RDS.
__Noisy saddle point__
For the stochastic differential equations
```{math}
---
label:
---
\begin{equation}
\begin{cases} dX_{t} = X_{t}dt + dW_{t}^{1} \\ dY_{t} = -Y_{t}dt + dW_{t}^{2} \end{cases}
\end{equation}
```
where $W_{t}^{1}$ and $W_{t}^{2}$ are two different Wiener processes, the solution mapping $\varphi$ is given by the following expression
```{math}
---
label:
---
\begin{equation}
\begin{array}{ccccccccc}
\varphi : & & \mathbb{R} \times \Omega \times \mathbb{R}^{2} & & \longrightarrow & & \mathbb{R}^{2} & & \\
& & (t,\omega ,(x,y)) & & \longmapsto & & (\varphi_{1}(t,\omega ,x),\varphi_{2}(t,\omega ,y)) & = & \left( e^{t} \left( x + \int_{0}^{t}e^{-s}dW_{s}^{1}(\omega ) \right) , e^{-t} \left( y + \int_{0}^{t}e^{s}dW_{s}^{2}(\omega ) \right) \right) . \end{array}
\end{equation}
```
Notice that this is a decoupled random dynamical system. There exists a solution whose components do not depend on variable $t$ and are convergent for almost every $\omega \in \Omega$ as a consequence of the properties of Wiener processes (see {cite}`duan15`). This solution has the form:
$$\tilde{X}(\omega) = (\tilde{x}(\omega ),\tilde{y}(\omega )) = \left( - \int_{0}^{\infty}e^{-s}dW_{s}^{1}(\omega ) , \int_{-\infty}^{0}e^{s}dW_{s}^{2}(\omega ) \right) .$$
Actually, $\tilde{X}(\omega )$ is a solution because it satisfies the invariance property that we now verify:
```{math}
---
label: eq:invariance_x
---
\begin{equation}
\label{invariance_x}
\begin{array}{ccl}
\varphi_{1} (t,\omega ,\tilde{x}(\omega )) & = & \displaystyle{e^{t}\left( -\int_{0}^{+\infty}e^{-s}dW^{1}_{s}(\omega )
+ \int_{0}^{t}e^{-s}dW^{1}_{s}(\omega ) \right) } = \displaystyle{-\int_{t}^{+\infty}e^{-(s-t)}dW^{1}_{s}(\omega ) }\\
& = & \displaystyle{-\int_{0}^{+\infty}e^{-t'}dW^{1}_{t'+t}(\omega) = -
\int_{0}^{+\infty}e^{-t'}dW^{1}_{t'}(\theta_{t}\omega ) = \tilde{x}(\theta_{t}\omega )} \quad \text{by means of }
t'=s-t,
\end{array}
\end{equation}
```
```{math}
---
label: eq:invariance_y
---
\begin{equation}
\label{invariance_y}
\begin{array}{lll}
\varphi_{2} (t,\omega ,\tilde{y}(\omega )) & = & \displaystyle{e^{-t}\left( \int_{-\infty}^{0}e^{s}dW^{2}_{s}(\omega ) +
\int_{0}^{t}e^{s}dW^{2}_{s}(\omega ) \right) = \int_{-\infty}^{t}e^{s-t}dW^{2}_{s}(\omega ) =
\int_{-\infty}^{0}e^{t'}dW^{2}_{t'+t}(\omega )} \\ & = & \displaystyle{
\int_{-\infty}^{0}e^{t'}dW^{2}_{t'}(\theta_{t}\omega ) = \tilde{y}(\theta_{t}\omega )} \quad \text{by means of } t'=s-t.
\end{array}
\end{equation}
```
This implies that $\varphi (t,\omega ,\tilde{X}(\omega )) = \tilde{X}(\theta_{t} \omega)$ for every $t \in \mathbb{R}$ and every $\omega \in \Omega$. Therefore $\tilde{X}(\omega )$ satisfies the invariance property {eq}`eq:invariance`. This conclusion comes from the fact that $\tilde{x}(\omega )$ and $\tilde{y}(\omega )$ are also invariant under the components $\varphi_{1}$ and $\varphi_{2}$, in case these are seen as separate RDSs defined over $\mathbb{R}$ (see {eq}`eq:invariance_x` and {ref}`eq:invariance_y`, respectively).
Due to its independence with respect to the time variable $t$, it is said that $\tilde{X}(\omega )$ is a random fixed point of the SDE {eq}`eq:noisy_saddle`, or more commonly a stationary orbit. As the trajectory of $\tilde{X}(\omega )$ (and separately its components $\tilde{x}(\omega )$ and $\tilde{y}(\omega )$) is proved to be an invariant set, it is straightforward to check that the two following subsets of $\mathbb{R}^{2}$,
$$\mathcal{S}(\omega ) = \lbrace (x,y) \in \mathbb{R}^{2} : x = \tilde{x}(\omega ) \rbrace \quad , \quad \mathcal{U}(\omega ) = \lbrace (x,y) \in \mathbb{R}^{2} : y = \tilde{y}(\omega ) \rbrace $$
are also invariant with respect to the RDS $\varphi$. Similarly to the deterministic setting, these are referred to as the stable and unstable manifolds of the stationary orbit respectively. Additionally, in order to prove the separating nature of these two manifolds and the stationary orbit with respect to their nearby trajectories, let's consider any other solution $(\overline{x}_{t},\overline{y}_{t})$ of the noisy saddle with initial conditions at time $t=0$,
```{math}
---
label:
---
\begin{equation}
\overline{x}_{0} = \tilde{x}(\omega ) + \epsilon_{1}(\omega ) , \quad \overline{y}_{0} = \tilde{y}(\omega ) + \epsilon_{2}(\omega ), \quad \text{being } \epsilon_{1}(\omega ), \epsilon_{2}(\omega ) \text{ two random variables.}
\end{equation}
```
If the corresponding RDS $\varphi$ is applied to compare the evolution of this solution $(\overline{x}_{t},\overline{y}_{t})$ and the stationary orbit, there arises an exponential dichotomy:
$$ (\overline{x}_{t},\overline{y}_{t}) - (\tilde{x}(\theta_{t}\omega ),\tilde{y}(\theta_{t}\omega )) = \varphi (t,\omega ,(\overline{x}_{0},\overline{y}_{0})) - \varphi (t,\omega ,(\tilde{x}(\omega ),\tilde{y}(\omega ))) $$
$$= \left( e^{t}\left[ \overline{x}_{0} + \int_{0}^{t}e^{-s}dW_{s}^{1}(\omega ) - \tilde{x}(\omega ) - \int_{0}^{t}e^{-s}dW_{s}^{1}(\omega ) \right] , e^{-t}\left[ \overline{y}_{0} + \int_{0}^{t}e^{s}dW_{s}^{2}(\omega ) - \tilde{y}(\omega ) - \int_{0}^{t}e^{s}dW_{s}^{2}(\omega ) \right] \right) $$
```{math}
---
label: eq:dichotomy
---
\begin{equation}
= \left( e^{t} \left( \tilde{x}(\omega )+\epsilon_{1}(\omega )-\tilde{x}(\omega ) \right) ,e^{-t} \left( \tilde{y}(\omega )+\epsilon_{2}(\omega )-\tilde{y}(\omega ) \right) \right) = \left( \epsilon_{1}(\omega )e^{t},\epsilon_{2}(\omega )e^{-t} \right) .
\end{equation}
```
Considering that $(\overline{x}_{t},\overline{y}_{t})$ is different from $(\tilde{x}(\omega ),\tilde{y}(\omega ))$ then one of the two cases $\epsilon_{1} \not \equiv 0$ or $\epsilon_{2} \not \equiv 0$ holds, let say $\epsilon_{1} \not = 0$ or $\epsilon_{2} \not = 0$ for almost every $\omega \in \Omega$. In the first case, the distance between both trajectories $(\overline{x}_{t},\overline{y}_{t})$ and $(\tilde{x},\tilde{y})$ increases at an exponential rate in positive time:
```{math}
---
label: eq:eq_1
---
\begin{equation}
\label{eq:eq_1}
\Vert \varphi (t,\omega ,(\overline{x}_{t},\overline{y}_{t}))-\varphi (t,\omega ,(\tilde{x},\tilde{y})) \Vert \geq |\epsilon_{1}(\omega )e^{t} | \longrightarrow + \infty \quad \text{when } t \rightarrow + \infty \text{ and for a.e. } \omega \in \Omega .
\end{equation}
```
Similarly to this case, when the second option holds the distance between both trajectories increases at a exponential rate in negative time. It does not matter how close the initial condition $(\overline{x}_{0},\overline{x}_{0})$ is from $(\tilde{x}(\omega ),\tilde{y}(\omega ))$ at the initial time $t=0$. Actually this same exponentially growing separation can be achieved for any other initial time $t \not = 0$. Following these arguments, one can check that the two manifolds $\mathcal{S}(\omega )$ and $\mathcal{U}(\omega )$ also exhibit this same separating behaviour as the stationary orbit. Moreover, we remark that almost surely the stationary orbit is the only solution whose components are bounded.
These facts highlight the distinguished nature of the stationary orbit (and its manifolds) in the sense that it is an isolated solution from the others. Apart from the fact that $(\tilde{x},\tilde{y})$ "moves" in a bounded domain for every $t \in \mathbb{R}$, any other trajectory eventually passing through an arbitrary neighborhood of $(\tilde{x},\tilde{y})$ at any given instant of time $t$, leaves the neighborhood and then separates from the stationary orbit in either positive or negative time. Specifically, this separation rate is exponential for the noisy saddle, just in the same way as for the deterministic saddle.
These features are also observed for the trajectories within the stable and unstable manifolds of the stationary orbit, but in a more restrictive manner than $(\tilde{x},\tilde{y})$. Taking for instance an arbitrary trajectory $(x^{s},y^{s})$ located at $\mathcal{S}(\omega )$ for every $t \in \mathbb{R}$, its first component $x^{s}_{t}=\tilde{x}(\omega )$ remains bounded for almost every $\omega \in \Omega$. In contrast, any other solution passing arbitrarily closed to $(x^{s},y^{s})$ neither being part of $\mathcal{S}(\omega )$ nor being the stationary orbit, satisfies the previous inequality {eq}`eq:eq_1` and therefore separates from $\mathcal{S}(\omega )$ at an exponential rate for increasing time. With this framework we can now introduce the formal definitions of stationary orbit and invariant manifold.
(stationary_orbit)=
__Definition__ _Stationary Orbit_
A random variable $\tilde{X}: \Omega \rightarrow \mathbb{R}^{n}$ is called a stationary orbit (random fixed point) for a random dynamical system $\varphi$ if
$$\varphi(t, \omega, \tilde{X}(\omega)) = \tilde{X}(\theta_t\omega), \quad \text{for every } t \in \mathbb{R} \text{ and every } \omega \in \Omega .$$
Obviously every stationary orbit $\tilde{X}(\omega )$ is an invariant set with respect to a RDS as it satisfies Definition {ref}`Invariant Set<invariant_set>`. Among several definitions of invariant manifolds given in the bibliography (for example {cite}`arno98`, {cite}`boxl89`, {cite}`duan15`), which have different formalisms but share the same philosophy, we choose the one given in {cite}`duan15` because it adapts to our example in a very direct way.
__Definition__
A random invariant set $M: \Omega \rightarrow \mathcal{P}(\mathbb{R}^{n})$ for a random dynamical system $\varphi$ is called a $C^{k}$-Lipschitz invariant manifold if it can be represented by a graph of a $C^{k}$ Lipschitz mapping ($k \geq 1$)
```{math}
\begin{equation*}
\gamma (\omega , \cdot ):H^{+} \to H^{-}, \quad \text{with direct sum decomposition } H^{+} \oplus H^{-} = \mathbb{R}^{n}
\end{equation*}
```
such that
```{math}
\begin{equation*}
\quad M(\omega ) = \lbrace x^{+} \oplus \gamma(\omega ,x^{+}) : x^{+} \in H^{+} \rbrace \quad \text{for every } \omega \in \Omega.
\end{equation*}
```
This is a very limited notion of invariant manifold as its formal definition requires the set to be represented by a Lipschitz graph. Anyway, it is consistent with the already established manifolds $\mathcal{S}(\omega )$ and $\mathcal{U}(\omega )$ as these can be represented as the graphs of two functions $\gamma_{s}$ and $\gamma_{u}$ respectively,
```{math}
\begin{align*}
\begin{array}{ccccc}
\gamma_{s} (\omega , \cdot ) & : & span \lbrace \left( \begin{array}{c} 0 \\ 1 \end{array} \right) \rbrace & \longrightarrow & span \lbrace \left( \begin{array}{c} 1 \\ 0 \end{array} \right) \rbrace \\
& & \left( \begin{array}{c} 0 \\ t \end{array} \right) & \longmapsto & \left( \begin{array}{c} \tilde{x}(\omega ) \\ 0 \end{array} \right) \end{array}
\; \text{and} \;
\begin{array}{ccccc} \gamma_{u} (\omega , \cdot ) & : & span \lbrace \left( \begin{array}{c} 1 \\ 0 \end{array} \right) \rbrace & \longrightarrow & span \lbrace \left( \begin{array}{c} 0 \\ 1 \end{array} \right) \rbrace \\
& & \left( \begin{array}{c} t \\ 0 \end{array} \right) & \longmapsto & \left( \begin{array}{c} 0 \\ \tilde{y}(\omega ) \end{array} \right) \quad .
\end{array}
\end{align*}
```
Actually the domains of such functions $\gamma_{s}$ and $\gamma_{u}$ are the linear subspaces $E^{s}(\omega )$ and $E^{u}(\omega )$, known as the stable and unstable subspaces of the random dynamical system $\Phi (t,\omega )$. This last mapping is obtained from linearizing the original RDS $\varphi$ over the stationary orbit $(\tilde{x},\tilde{y})$. This result serves as an argument to denote $\mathcal{S}(\omega )$ and $\mathcal{U}(\omega )$ as the stable and unstable manifolds of the stationary orbit, not only because these two subsets are invariant under $\varphi$, as one can deduce from {eq}`eq:invariance_x` and {eq}`eq:invariance_x`, but also due to the dynamical behaviour of their trajectories in a neighborhood of the stationary orbit $\tilde{X}(\omega )$. Hence the important characteristic of $\tilde{X}(\omega )=(\tilde{x},\tilde{y})$ is not only its independence with respect to the time variable $t$; but also the fact that it exhibits hyperbolic behaviour with respect to its neighboring trajectories. Considering the hyperbolicity of a given solution, as well as in the deterministic context, means considering the hyperbolicity of the RDS $\varphi$ linearized over such solution. Specifically, the Oseledets' multiplicative ergodic theorem for random dynamical systems ({cite}`arno98` and {cite}`duan15`) ensures the existence of a Lyapunov spectrum which is necessary to determine whether the stationary orbit $\tilde{X}(\omega )$ is hyperbolic or not. All these issues are well reported in {cite}`duan15`, including the proof that the noisy saddle {eq}`eq:noisy_saddle` satisfies the Oseledets' multiplicative ergodic theorem conditions.
Before implementing the numerical method of Lagrangian descriptors to several examples of SDEs, it is important to remark why random fixed points and their respective stable and unstable manifolds govern the nearby trajectories, and furthermore, how they may influence the dynamics throughout the rest of the domain. These are essential issues in order to describe the global phase space motion of solutions of SDEs. However, these questions do not have a simple answer. For instance, in the noisy saddle example {eq}`eq:noisy_saddle` the geometrical structures arising from the dynamics generated around the stationary orbit are quite similar to the dynamics corresponding to the deterministic saddle point $\lbrace \dot{x}=x,\dot{y}=-y \rbrace$. Significantly, the manifolds $\mathcal{S}(\omega )$ and $\mathcal{U}(\omega )$ of the noisy saddle form two dynamical barriers for other trajectories in the same way that the manifolds $\lbrace x = 0 \rbrace$ and $\lbrace y = 0 \rbrace$ of the deterministic saddle work. This means that for any particular experiment, i.e., for any given $\omega \in \Omega$, the manifolds $\mathcal{S}(\omega )$ and $\mathcal{U}(\omega )$ are determined and cannot be "crossed" by other trajectories due to the uniqueness of solutions (remember that the manifolds are invariant under the RDS {eq}`eq:noisy_saddle_RDS` and are comprised of an infinite family of solutions). Also by considering the exponential separation rates reported in {eq}`eq:eq_1` with the rest of trajectories, the manifolds $\mathcal{S}(\omega )$ and $\mathcal{U}(\omega )$ divide the plane $\mathbb{R}^{2}$ of initial conditions into four qualitatively distinct dynamical regions; therefore providing a phase portrait representation.
````{margin}
```{note}
Otherwise, if nonlinearity is dominating the behavior of the terms in equation {eq}`eq:SDE` then the correspondence between the manifolds for $\Phi (t, \omega )$ to the manifolds for $\varphi$ needs to be made by means of the local stable and unstable manifold theorem (see {cite}`moham99`, Theorem 3.1). Therein it is considered a homeomorphism $H(\omega )$ which establishes the equivalence of the geometrical structures arising for both sets of manifolds, and as a consequence the manifolds for $\varphi$ inherit the same dynamics as the ones for $\Phi (t, \omega )$ but only in a neighborhood of the stationary orbit. In this sense the existence of such manifolds for a nonlinear RDS $\varphi$ is only ensured locally. Anyway this result provides a very good approximation to the stochastic dynamics of a system, and enables us to discuss the different patterns of behavior of the solutions in the following examples.
```
````
Nevertheless it remains to show that such analogy can be found between other SDEs and their corresponding non-noisy deterministic differential equations (_Note_). In this direction there is a recent result ({cite}`cheng16`, Theorem 2.1) which ensures the equivalence in the dynamics of both kinds of equations when the noisy term $\sigma$ is additive (i.e., $\sigma$ does not depend on the solution $X_{t}$). Although this was done by means of the most probable phase portrait, a technique that closely resembles the ordinary phase space for deterministic systems, this fact might indicate that such analogy in the dynamics cannot be achieved when the noise does depend explicitly on the solution $X_{t}$. Actually any additive noise affects all the particles together at the same magnitude.
Anyway the noisy saddle serves to establish an analogy to the dynamics with the deterministic saddle. One of its features is the contrast between the growth of the components $X_{t}$ and $Y_{t}$, which mainly have a positive and negative exponential growth respectively. We will see that this is graphically captured when applying the stochastic Lagrangian descriptors method to the SDE {eq}`eq:noisy_saddle` over a domain of the stationary orbit. Moreover when representing the stochastic Lagrangian descriptor values for the noisy saddle, one can observe that the lowest values are precisely located on the manifolds $\mathcal{S}(\omega )$ and $\mathcal{U}(\omega )$. These are manifested as sharp features indicating a rapid change of the values that the stochastic Lagrangian descriptor assumes. This geometrical structure formed by "local minimums" has a very marked crossed form and it is straightforward to think that the stationary orbit is located at the intersection of the two cross-sections. These statements are supported afterwards by numerical simulations and analytical results.
(sec:SLD)=
### The stochastic Lagrangian descriptor
The definition of stochastic Lagrangian descriptors that we introduce here is based on the discretization of the continuous time definition given in Eq. {eq}`eq:Mp_function` that relies on the computation of the $p$-norm of trajectories. In fact, this discretization gave rise to a version of LDs that can be used to analyze discrete time dynamical systems (maps), see {cite}`carlos2015`. Let $\{x_i\}^{N}_{i =
-N}$ denote an orbit of $(2N + 1)$ points, where $x_i \in \mathbb{R}^n$ and $N \in \mathbb{N}$ is the number of iterations of the map. Considering the space of orbits as a sequence space, the discrete Lagrangian descriptor was defined in terms of the $\ell^p$-norm of an orbit as follows:
```{math}
---
label:
---
\begin{equation}
\displaystyle{MD_p(x_0, N) = \sum^{N-1}_{i = -N}\Vert x_{i+1} - x_i \Vert_p, \quad p \leq 1.}
\end{equation}
```
This alternative definition allows us to prove formally the non-differentiability of the $MD_p$ function through points that belong to invariant manifolds of a hyperbolic trajectory. This fact implies a better visualization of the invariant manifolds as they are detected over areas where the $MD_p$ function presents abrupt changes in its values.
Now we extend these ideas to the context of stochastic differential equations. For this purpose we consider a general SDE of the form:
```{math}
---
label: eq:stochastic_lagrangian_system
---
\begin{equation}
dX_t = b(X_t, t)dt + \sigma(X_t, t)dW_t, \quad X_{t_0} = x_0,
\label{eq:stochastic_lagrangian_system}
\end{equation}
```
where $X_t$ denotes the solution of the system, $b(\cdot)$ and $\sigma(\cdot)$ are Lipschitz functions which ensure uniqueness of solutions and $W_t$ is a two-sided Wiener process. Henceforth, we make use of the following notation
```{math}
---
label:
---
\begin{equation}
X_{t_j} := X_{t_0+j\Delta t},
\end{equation}
```
for a given $\Delta t>0$ small enough and $j=-N,\cdots ,-1,0,1, \cdots ,N$.
__Definition__
The stochastic Lagrangian descriptor evaluated for SDE {eq}`eq:stochastic_lagrangian_system` with general solution
$\textbf{X}_{t}(\omega )$ is given by
```{math}
---
label: eq:MS
---
\begin{equation}
MS_p(\textbf{x}_0, t_0, \tau, \omega) = \sum^{N-1}_{i = -N} \Vert \textbf{X}_{t_{i+1}} -
\textbf{X}_{t_i} \Vert_p
\label{eq:MS}
\end{equation}
```
where $\lbrace \textbf{X}_{t_{j}} \rbrace_{j=-N}^{N}$ is a discretization of the solution such that
$\textbf{X}_{t_{-N}} = \textbf{X}_{-\tau}$, $\textbf{X}_{t_N} = \textbf{X}_{\tau}$, $\textbf{X}_{t_0} = \textbf{x}_{0}$, for a given $\omega \in \Omega$.
__Definition__
Obviously every output of the $MS_p$ function highly depends on the experiment $\omega \in \Omega$ where $\Omega$ is the probability space that includes all the possible outcomes of a given phenomena. Therefore in order to analyze the homogeneity of a given set of outputs, we consider a sequence of results of the $MS_p$ function for the same stochastic equation {eq}`eq:stochastic_lagrangian_system` : $MS_p(\cdot, \omega_1)$, $MS_p(\cdot, \omega_2)$,
$\cdots$, $MS_p(\cdot, \omega_M)$. It is feasible that the following relation holds
```{math}
---
label: eq:deterministic_tol
---
\begin{equation}
d(MS_p(\cdot, \omega_i), MS_p(\cdot, \omega_j)) < \delta, \quad \text{for all } i,j,
\label{eq:deterministic_tol}
\end{equation}
```
where $d$ is a metric that measures the similarity between two matrices (for instance the Frobenius norm $\Vert A-B \Vert_F =
\sqrt{Tr((A-B)\cdot (A-B)^T)}$) and $\delta$ is a positive tolerance. Nevertheless for general stochastic differential equations, expression {eq}`eq:deterministic_tol` does not usually hold. Alternatively if the elements of the sequence of matrices $MS_p(\cdot, \omega_1)$, $MS_p(\cdot, \omega_2)$, $\cdots$, $MS_p(\cdot, \omega_M)$ do not have much similarity to each other, it may be of more use to define the mean of the outputs
```{math}
---
label: eq:mean_MSp_value
---
\begin{equation}
\displaystyle{\mathbb{E} \left[ MS_p(\cdot, \omega) \right] = \left(
\frac{MS_p(\cdot, \omega_1) + MS_p(\cdot, \omega_2) + \cdots +
MS_p(\cdot, \omega_M)}{M}\right) ,}
\label{eq:mean_MSp_value}
\end{equation}
```
(sec:num)=
## Numerical Simulation of the Stochastic Lagrangian Descriptor
In this section we describe the stochastic Lagrangian descriptor method that can be used to numerically solve and visualize the geometrical structures of SDEs. Consider a general $n$-dimensional SDE of the form
```{math}
---
label:
---
\begin{equation}
dX^j_t = b^j(X_t, t)dt + \sum^m_{k=1}\sigma^j_k(X_t, t)dW^k_t, \quad X_{t_0} = x_0 \in \mathbb{R}^n, \quad j=1,\cdots ,n
\end{equation}
```
where $X_t = (X^1_t, \cdots , X^n_t)$ and $W^1_t, \cdots, W^m_t$ are $m$ independent Wiener processes.
If the time step $\Delta t$ is firstly fixed, then the temporal grid $t_p = t_0 + p\Delta t$ ($p \in \mathbb{Z}$) is already determined and we arrive to the difference equation
```{math}
---
label:
---
\begin{equation}
X^j_{t+\Delta t} = X^j_t + b^j(X_t, t)\Delta t + \sum^m_{k=1} \sigma^j_k(X_t, t)dW^k_t.
\end{equation}
```
This scheme is referred to as the Euler-Marayuma method for solving a single path of the SDE. If the stochastic part is removed from the equation, then we obtain the classical Euler method. Suppose $X_{t_p}$ is the solution of the SDE and
$\tilde{X}_{t_p}$ its numerical approximation at any time $t_p$. Since both of them are random variables, the accuracy of the method must be determined in probabilistic terms. With this aim, the following definition is introduced.
__Definition__
A stochastic numerical method has an order of convergence equal to $\gamma$ if there exists a constant $C>0$ such that
```{math}
---
label:
---
\begin{equation}
\mathbb{E} \left[ X_{t_p} - \tilde{X}_{t_p} \right] \leq C \Delta t^{\gamma},
\end{equation}
```
for any arbitrary $t_p = t_0 + p\Delta t$ and $\Delta t$ small enough.
Indeed, the Euler-Maruyama method has an order of convergence equal to $1/2$ (see {cite}`kloeden2013numerical` for further details).
### The noisy saddle
The noisy saddle is a fundamental benchmark for assessing numerical methods for revealing phase space structures. Its main value is in the simplicity of the expressions taken by the components of the stationary orbit and its corresponding stable and unstable manifolds. From these one clearly observes the exponential separation rates between particles passing
near the manifolds. Now for the stochastic differential equations
```{math}
---
label: eq:general_noisy
---
\begin{equation}
\label{eq:general_noisy}
\begin{cases}
dX_t = a_1X_t dt + b_1dW^1_t \\
dY_t = -a_2Y_t dt + b_2dW^2_t
\end{cases}
\end{equation}
```
it is straightforward to check that the only stationary orbit takes the expression
```{math}
---
label:
---
\begin{equation}
\widetilde{X}(\omega ) = \left( \tilde{x}(\omega ), \tilde{y}(\omega ) \right) = \left(
-\int_{0}^{\infty}e^{-a_{1}s} b_1dW^1_t(\omega ) , \int_{-\infty}^{0}e^{b_{1}s}
b_2dW^2_t(\omega ) \right)
\end{equation}
```
where $a_{1},a_{2},b_{1},b_{2} \in \mathbb{R}$ are constants and $a_{1},a_{2}>0$. Its corresponding stable and unstable manifolds are
```{math}
---
label:
---
\begin{equation}
\mathcal{S}(\omega ) = \lbrace (x,y) \in \mathbb{R}^{2} : x = \tilde{x}(\omega ) \rbrace , \quad
\mathcal{U}(\omega ) = \lbrace (x,y) \in \mathbb{R}^{2} : y = \tilde{y}(\omega ) \rbrace .
\end{equation}
```
These play a very relevant role as dynamical barriers for the particles tracked by the RDS, which is generated by the SDE {eq}`eq:general_noisy`. This fact has been justified in the previous section, but can be analytically demonstrated when computing the stochastic Lagrangian descriptor {eq}`eq:MS` for the solution of the noisy saddle.
According to the notation used for the definition of SLD
$${
MS_p (\mathbf{x}_0, t_0, \tau, \omega) = \sum_{i = -N}^{N-1} \Vert \mathbf{X}_{t_{i+1}} - \mathbf{X}_{t_i} \Vert_p
}$$
at which the components of the solution satisfy the initial conditions $\textbf{X}_{t_{0}}= \left( X_{t_{0}},Y_{t_{0}}
\right) = (x_{0},y_{0}) = \textbf{x}_{0}$, these take the expressions
```{math}
---
label: eq:general_noisy_saddle_solutions
---
\begin{equation}
\label{general_noisy_saddle_solutions}
X_{t} = e^{a_{1}t} \left( x_{0} + \int_{0}^{t}e^{-a_{1}s}b_{1}dW_{s}^{1} \right) \quad , \quad Y_{t} = e^{-a_{2}t}
\left( y_{0} + \int_{0}^{t}e^{a_{2}s}b_{2}dW_{s}^{2}(\omega ) \right)
\end{equation}
```
and the temporal nodes satisfy the rule $t_{i} = t_{0} + i\Delta t$ with $t_{0}$ and $\Delta t$ already given. Now it is possible to compute analytically the increments $\Vert \textbf{X}_{t_{i+1}} - \mathbf{X}_{t_i} \Vert_p = \vert X_{t_{i+1}} - X_{t_i} \vert^{p} + \vert Y_{t_{i+1}} - Y_{t_i} \vert^{p}$:
$$\left| X_{t_{i+1}} - X_{t_i} \right|^{p} = \left| e^{a_{1}t_{i+1}} \left( x_{0} +
\int_{0}^{t_{i+1}}e^{-a_{1}s}b_{1}dW_{s}^{1} \right) - e^{a_{1}t_{i}} \left( x_{0} +
\int_{0}^{t_{i}}e^{-a_{1}s}b_{1}dW_{s}^{1} \right) \right|^{p}$$
$$= \left| e^{a_{1}t_{i}}\left( e^{a_{1}\Delta t} - 1 \right) \left[ x_{0} + \int_{0}^{t_{i}}e^{-a_{1}s}b_{1}dW_{s}^{1}
\right] + e^{a_{1}(t_{i}+\Delta t)} \int_{t_{i}}^{t_{i}+\Delta t}e^{-a_{1}s}b_{1}dW_{s}^{1} \right|^{p}$$
$$= \left| e^{a_{1}t_{i}}\left( e^{a_{1}\Delta t} - 1 \right) \left[ x_{0} +
\int_{0}^{t_{i}}e^{-a_{1}s}b_{1}dW_{s}^{1} \right] + e^{a_{1}\Delta t}b_{1}dW_{t_{i}}^{1} \right|^{p} $$
The last expression is obtained using Itô formula {eq}`eq:Ito` .
Moreover for large values of $t_{i}$ such that $e^{a_{1}t_{i}} \gg e^{a_{1}\Delta t}$ and taking into account that $dW_{t_{i}}^{1}$ is finite almost surely, we can consider the following approximation
```{math}
---
label: eq:x_increments
---
\begin{equation}
\label{x_increments}
\left| X_{t_{i+1}} - X_{t_i} \right|^{p} \hspace{0.1cm} \approx \hspace{0.1cm} e^{a_{1}t_{i}\cdot p}\left|
e^{a_{1}\Delta t} - 1 \right|^{p} \left| x_{0} + \int_{0}^{t_{i}}e^{-a_{1}s}b_{1}dW_{s}^{1} \right|^{p}.
\end{equation}
```
By following these arguments, one can get an analogous result for the second component $Y_{t}$:
$$\left| Y_{t_{i+1}} - Y_{t_i} \right|^{p} = \left| e^{-a_{2}t_{i}}\left( e^{-a_{2}\Delta t} - 1 \right) \left[
y_{0} + \int_{0}^{t_{i}}e^{a_{2}s}b_{2}dW_{s}^{2} \right] + e^{-a_{2}\Delta t}b_{2}dW_{t_{i}}^{2} \right|^{p},$$
which for small values of $t_{i}$, such that $e^{-a_{2}t_{i}} \gg e^{-a_{2}\Delta t}$, this approximation can be further simplified as follows
```{math}
---
label: eq:y_increments
---
\begin{equation}
\label{y_increments}
\left| Y_{t_{i+1}} - Y_{t_i} \right|^{p} \hspace{0.1cm} \approx \hspace{0.1cm} e^{-a_{2}t_{i}\cdot p}\left|
e^{-a_{2}\Delta t} - 1 \right|^{p} \left| y_{0} + \int_{0}^{t_{i}}e^{a_{2}s}b_{2}dW_{s}^{2} \right|^{p}.
\end{equation}
```
Once the analytic expression of the SLD applied to the noisy saddle {eq}`eq:general_noisy` is known, it can be proved that the stable and unstable manifolds of the stationary orbit are manifested as singularities of the SLD function over any given domain of initial conditions containing the stationary orbit. This fact implies that the SLD method realizes a procedure to detect these geometrical objects and, consequently, provides a phase portrait representation of the dynamics generated by the noisy saddle. In the same way as described in {cite}`mancho2013lagrangian`, we refer to singularities as points of the domain of spatial initial conditions where the derivative of the SLD is not defined. The paradigm example of the mathematical manifestation of singularities of the LD on stable and unstable manifolds of hyperbolic trajectories is provided by the scalar function $|\cdot |^{p}$ with $p \in (0,1]$. This function is singular, alternatively non-differentiable, at those points where its argument is zero. Graphically this feature is observed as sharp changes in the representation of the SLD values, where the contour lines concentrate in a very narrow space.
In this particular example we are able to explicitly identify within the expression of the SLD the terms that are largest in magnitude. In other words, we are able to identify the terms whose particular singularities determine the non-differentiability of the entire sum (_Note_). This is better understandable if the expression of the SLD is divided into two sums
````{margin}
```{note}
Note that the differentiability of the SLD is analyzed with respect to the components of the initial conditions $(x_{0},y_{0})$, as the experiment $\omega \in \Omega$ and the starting point $t_{0}$ are previously fixed.
```
````
```{math}
---
label: eq:higher_order_x
---
MS_p(\mathbf{x}_0, t_0, \tau, \omega) = \sum_{i = -N}^{N-1} \Vert \mathbf{X}_{t_{i+1}} -
\mathbf{X}_{t_i} \Vert_p = \sum^{N-1}_{i = -N} \vert X_{t_{i+1}} - X_{t_i} \vert^{p} + \sum^{N-1}_{i = -N} \vert
Y_{t_{i+1}} - Y_{t_i} \vert^{p}
```
The highest order term within the first sum is $\left| X_{t_{N}} - X_{t_{N-1}} \right|^{p} = \left| X_{\tau } - X_{\tau - \Delta t} \right|^{p}$, which according to {eq}`eq:x_increments` is approximated by
```{math}
---
label: eq:higher_order_x
---
\begin{equation}
\label{higher_order_x}
\left| X_{\tau } - X_{\tau - \Delta t} \right|^{p} \hspace{0.1cm} \approx \hspace{0.1cm} e^{a_{1}(\tau - \Delta
t)\cdot p}\left| e^{a_{1}\Delta t} - 1 \right|^{p} \left| x_{0} + \int_{0}^{\tau - \Delta t}e^{-a_{1}s}b_{1}dW_{s}^{1}
\right|^{p} \quad \text{for enough large values of } \tau .
\end{equation}
```
Similarly the highest order term within the second sum is $\left| Y_{t_{-N+1}} - Y_{t_{-N}} \right|^{p} = \left|
Y_{-\tau +\Delta t} - Y_{-\tau } \right|^{p}$, approximated by
```{math}
---
label: eq:higher_order_y
---
\begin{equation}
\label{higher_order_y}
\left| Y_{-\tau +\Delta t} - Y_{-\tau } \right|^{p} \hspace{0.1cm}
\approx \hspace{0.1cm} e^{a_{2}\tau \cdot p}\left| e^{-a_{2}\Delta t} - 1 \right|^{p} \left| y_{0} -
\int_{-\tau}^{0}e^{a_{2}s}b_{2}dW_{s}^{2} \right|^{p} \quad \text{for enough large values of } \tau .
\end{equation}
```
Consequently, it is evident that the sharper features will be located closed to the points where these two last
quantities {eq}`eq:higher_order_x`, {eq}`eq:higher_order_y` are zero. In other words where the initial condition
$(x_{0},y_{0})$ satisfies one of the two following
```{math}
---
label:
---
x_{0} = - \int_{0}^{\tau - \Delta t}e^{-a_{1}s}b_{1}dW_{s}^{1} \quad \text{or} \quad y_{0} =
\int_{-\tau}^{0}e^{a_{2}s}b_{2}dW_{s}^{2} \quad \text{for enough large values of } \tau .
```
This statement is in agreement with the distinguished nature of the manifolds of the stationary orbit discussed in the previous section. Note also that the two quantities for $x_{0}$ and $y_{0}$ converge to the coordinates of the stationary orbit $(\tilde{x}(\omega ),\tilde{y}(\omega ))$ with $\tau$ tending to infinity. These features are observed in {numref}`fig:saddle`, where the sharpness of the SLD representation highlights the location of the stable and unstable manifolds.
```{figure} figures/fig1a.png
---
---
Figure A) from {cite}`balibrea2016lagrangian` showing two different experiments representing contours of $MS_p$ for $p=0.1$ and $\tau=15$. The contours of $MS_p$ are computed on a 1200$\times$1200 points grid of initial conditions and the time step for integration of the vector field is chosen to be $\Delta t= 0.05$. The magenta colored point corresponds to the location of the stationary orbit for each experiment. The chosen parameters are $a_1 = a_2 = b_2 = 1$ and $b_1 = -1$.
```
```{figure} figures/fig1b.png
---
name: fig:saddle
---
Figure B) from {cite}`balibrea2016lagrangian` showing two different experiments representing contours of $MS_p$ for $p=0.1$ and $\tau=15$. The contours of $MS_p$ are computed on a 1200$\times$1200 points grid of initial conditions and the time step for integration of the vector field is chosen to be $\Delta t= 0.05$. The magenta colored point corresponds to the location of the stationary orbit for each experiment. The chosen parameters are $a_1 = a_2 = b_2 = 1$ and $b_1 = -1$.
```
\label{fig:saddle}
\caption{Figures from {cite}`balibrea2016lagrangian` showing two different experiments representing contours of $MS_p$ for $p=0.1$ and $\tau=15$. The contours of $MS_p$ are computed on a 1200$\times$1200 points grid of initial conditions and the time step for integration of the vector field is chosen to be $\Delta t= 0.05$. The magenta colored point corresponds to the location of the stationary orbit for each experiment. The chosen parameters are $a_1 = a_2 = b_2 = 1$ and $b_1 = -1$.}
> __Remark__
> Due to the properties of Itô integrals, see for instance {cite}`duan15`, the components of the stationary orbit satisfy
```{math}
---
label:
---
\mathbb{E} \left[ \tilde{x}(\omega ) \right] = \mathbb{E} \left[ - \int_{0}^{\infty}e^{-s}dW_{s}^{1} \right] = 0
\quad , \quad \mathbb{E} \left[ \tilde{y}(\omega ) \right] = \mathbb{E} \left[ \int_{-\infty}^{0}e^{s}dW_{s}^{2} \right]
= 0
```
```{math}
---
label:
---
\mathbb{V} \left[ \tilde{x}(\omega ) \right] = \mathbb{E} \left[ \tilde{x}(\omega )^{2} \right] = \mathbb{E} \left[
\int_{0}^{\infty}e^{-2s}ds \right] = \frac{1}{2} \quad , \quad \mathbb{V} \left[ \tilde{y}(\omega ) \right] = \mathbb{E}
\left[ \tilde{y}(\omega )^{2} \right] = \mathbb{E} \left[ \int_{-\infty}^{0}e^{2s}ds \right] = \frac{1}{2}.
```
>This means that the stationary orbit $(\tilde{x}(\omega ),\tilde{y}(\omega ))$ is highly probable to be located closed to the origin of coordinates $(0,0)$, and this feature is displayed in {numref}`fig:saddle`. This result gives more evidences and supports the similarities between the stochastic differential equation {eq}`eq:noisy_saddle` and the deterministic analogue system $\lbrace \dot{x}=x, \hspace{0.1cm} \dot{y}=-y \rbrace$ whose only fixed point is $(0,0)$.
Therefore we can assert that the stochastic Lagrangian descriptor is a technique that provides a phase portrait representation of the dynamics generated by the noisy saddle equation {eq}`eq:general_noisy`. Next we apply this same technique to further examples.
(sec:examp)=
### The Stochastically forced Duffing Oscillator
Another classical problem is that of the Duffing oscillator. The deterministic version is given by
```{math}
---
label: eq:duffing_determ
---
\begin{equation}
\label{eq:duffing_determ}
\ddot{x} = \alpha \dot{x} + \beta x + \gamma x^3 + \epsilon \cos(t).
\end{equation}
```
If $\epsilon = 0$ the Duffing equation becomes time-independent, meanwhile for $\epsilon \neq 0$ the oscillator is a time-dependent system, where $\alpha$ is the damping parameter, $\beta$ controls the rigidity of the system and $\gamma$ controls the size of the nonlinearity of the restoring force. The stochastically forced Duffing
equation is studied in {cite}`datta01` and can be written as follows:
```{math}
---
label:
---
\begin{equation}
\begin{cases}
dX_t = \alpha Y_t, \\
dY_t = (\beta X_t + \gamma X^3_t)dt + \epsilon dW_t.
\end{cases}
\end{equation}
```
```{figure} figures/fig2a.png
---
name:
---
Figure A) from {cite}`balibrea2016lagrangian` showing three different experiments representing $MS_p$ contours for $p=0.5$ over a grid of initial conditions.
```
```{figure} figures/fig2b.png
---
name:
---
Figure B) from {cite}`balibrea2016lagrangian` showing three different experiments representing $MS_p$ contours for $p=0.5$ over a grid of initial conditions.
```
```{figure} figures/fig2c.png
---
name:
---
Figure C) from {cite}`balibrea2016lagrangian` showing three different experiments representing $MS_p$ contours for $p=0.5$ over a grid of initial conditions. d) The last image corresponds to the $M_p$ function for equation {eq}`eq:duffing_determ` and $p=0.75$. All these pictures were computed for $\tau=15$, and over a $1200 \times 1200$ points grid. The time step for integration of the vector field was chosen to be $\Delta t = 0.05$.
```
\label{fig:duffing}
\caption{a), b), c) Figures from {cite}`balibrea2016lagrangian` showing three different experiments representing $MS_p$ contours for $p=0.5$ over a grid of initial conditions. d) The last image corresponds to the $M_p$ function for equation {eq}`eq:duffing_determ` and $p=0.75$. All these pictures were computed for $\tau=15$, and over a $1200 \times 1200$ points grid. The time step for integration of the vector field was chosen to be $\Delta t = 0.05$.}
# References
```{bibliography} bibliography/chapter3.bib
```
|
```python
from IPython.display import Image
from IPython.core.display import HTML
from sympy import *; x,h,y = symbols("x h y")
Image(url= "https://i.imgur.com/XQ0PRkp.png")
```
```python
expr = 2.3 + 0.5*sin((2*pi*x)/5.4)
def F(x):
return expr
F(x)
#first step is to find dF(x)
#then we do slope point form with dF(x) as m so y = y0 + dF(x)(x-x0)
```
$\displaystyle 0.5 \sin{\left(0.37037037037037 \pi x \right)} + 2.3$
```python
dF = diff(F(x))
print(dF)
```
0.185185185185185*pi*cos(0.37037037037037*pi*x)
```python
dF = diff(F(x))
print(dF.subs(x,1))
```
0.185185185185185*pi*cos(0.37037037037037*pi)
```python
Image(url= "https://i.imgur.com/irlVBK2.png")
```
|
[STATEMENT]
lemma shrK_in_used [iff]: "Key (shrK A) \<in> used evs"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Key (shrK A) \<in> used evs
[PROOF STEP]
by (rule initState_into_used, blast) |
foo : List Char -> ()
foo cs = case cs of
"bar" => ()
_ => ()
|
Formal statement is: lemma div_pCons_eq: "pCons a p div q = (if q = 0 then 0 else pCons (coeff (pCons a (p mod q)) (degree q) / lead_coeff q) (p div q))" Informal statement is: If $p$ and $q$ are polynomials, then $p(x) = a + xq(x) + r(x)$ where $r$ is the remainder of $p$ divided by $q$. |
(* Title: HOL/MicroJava/DFA/Err.thy
Author: Tobias Nipkow
Copyright 2000 TUM
*)
section \<open>The Error Type\<close>
theory Err
imports Semilat
begin
datatype 'a err = Err | OK 'a
type_synonym 'a ebinop = "'a \<Rightarrow> 'a \<Rightarrow> 'a err"
type_synonym 'a esl = "'a set * 'a ord * 'a ebinop"
primrec ok_val :: "'a err \<Rightarrow> 'a" where
"ok_val (OK x) = x"
definition lift :: "('a \<Rightarrow> 'b err) \<Rightarrow> ('a err \<Rightarrow> 'b err)" where
"lift f e == case e of Err \<Rightarrow> Err | OK x \<Rightarrow> f x"
definition lift2 :: "('a \<Rightarrow> 'b \<Rightarrow> 'c err) \<Rightarrow> 'a err \<Rightarrow> 'b err \<Rightarrow> 'c err" where
"lift2 f e1 e2 ==
case e1 of Err \<Rightarrow> Err
| OK x \<Rightarrow> (case e2 of Err \<Rightarrow> Err | OK y \<Rightarrow> f x y)"
definition le :: "'a ord \<Rightarrow> 'a err ord" where
"le r e1 e2 ==
case e2 of Err \<Rightarrow> True |
OK y \<Rightarrow> (case e1 of Err \<Rightarrow> False | OK x \<Rightarrow> x <=_r y)"
definition sup :: "('a \<Rightarrow> 'b \<Rightarrow> 'c) \<Rightarrow> ('a err \<Rightarrow> 'b err \<Rightarrow> 'c err)" where
"sup f == lift2(%x y. OK(x +_f y))"
definition err :: "'a set \<Rightarrow> 'a err set" where
"err A == insert Err {x . \<exists>y\<in>A. x = OK y}"
definition esl :: "'a sl \<Rightarrow> 'a esl" where
"esl == %(A,r,f). (A,r, %x y. OK(f x y))"
definition sl :: "'a esl \<Rightarrow> 'a err sl" where
"sl == %(A,r,f). (err A, le r, lift2 f)"
abbreviation
err_semilat :: "'a esl \<Rightarrow> bool"
where "err_semilat L == semilat(Err.sl L)"
primrec strict :: "('a \<Rightarrow> 'b err) \<Rightarrow> ('a err \<Rightarrow> 'b err)" where
"strict f Err = Err"
| "strict f (OK x) = f x"
lemma strict_Some [simp]:
"(strict f x = OK y) = (\<exists> z. x = OK z \<and> f z = OK y)"
by (cases x, auto)
lemma not_Err_eq:
"(x \<noteq> Err) = (\<exists>a. x = OK a)"
by (cases x) auto
lemma not_OK_eq:
"(\<forall>y. x \<noteq> OK y) = (x = Err)"
by (cases x) auto
lemma unfold_lesub_err:
"e1 <=_(le r) e2 == le r e1 e2"
by (simp add: lesub_def)
lemma le_err_refl:
"\<forall>x. x <=_r x \<Longrightarrow> e <=_(Err.le r) e"
apply (unfold lesub_def Err.le_def)
apply (simp split: err.split)
done
lemma le_err_trans [rule_format]:
"order r \<Longrightarrow> e1 <=_(le r) e2 \<longrightarrow> e2 <=_(le r) e3 \<longrightarrow> e1 <=_(le r) e3"
apply (unfold unfold_lesub_err le_def)
apply (simp split: err.split)
apply (blast intro: order_trans)
done
lemma le_err_antisym [rule_format]:
"order r \<Longrightarrow> e1 <=_(le r) e2 \<longrightarrow> e2 <=_(le r) e1 \<longrightarrow> e1=e2"
apply (unfold unfold_lesub_err le_def)
apply (simp split: err.split)
apply (blast intro: order_antisym)
done
lemma OK_le_err_OK:
"(OK x <=_(le r) OK y) = (x <=_r y)"
by (simp add: unfold_lesub_err le_def)
lemma order_le_err [iff]:
"order(le r) = order r"
apply (rule iffI)
apply (subst Semilat.order_def)
apply (blast dest: order_antisym OK_le_err_OK [THEN iffD2]
intro: order_trans OK_le_err_OK [THEN iffD1])
apply (subst Semilat.order_def)
apply (blast intro: le_err_refl le_err_trans le_err_antisym
dest: order_refl)
done
lemma le_Err [iff]: "e <=_(le r) Err"
by (simp add: unfold_lesub_err le_def)
lemma Err_le_conv [iff]:
"Err <=_(le r) e = (e = Err)"
by (simp add: unfold_lesub_err le_def split: err.split)
lemma le_OK_conv [iff]:
"e <=_(le r) OK x = (\<exists>y. e = OK y & y <=_r x)"
by (simp add: unfold_lesub_err le_def split: err.split)
lemma OK_le_conv:
"OK x <=_(le r) e = (e = Err | (\<exists>y. e = OK y & x <=_r y))"
by (simp add: unfold_lesub_err le_def split: err.split)
lemma top_Err [iff]: "top (le r) Err"
by (simp add: top_def)
lemma OK_less_conv [rule_format, iff]:
"OK x <_(le r) e = (e=Err | (\<exists>y. e = OK y & x <_r y))"
by (simp add: lesssub_def lesub_def le_def split: err.split)
lemma not_Err_less [rule_format, iff]:
"~(Err <_(le r) x)"
by (simp add: lesssub_def lesub_def le_def split: err.split)
lemma semilat_errI [intro]:
assumes semilat: "semilat (A, r, f)"
shows "semilat(err A, Err.le r, lift2(%x y. OK(f x y)))"
using semilat
apply (simp only: semilat_Def closed_def plussub_def lesub_def
lift2_def Err.le_def err_def)
apply (simp split: err.split)
done
lemma err_semilat_eslI_aux:
assumes semilat: "semilat (A, r, f)"
shows "err_semilat(esl(A,r,f))"
apply (unfold sl_def esl_def)
apply (simp add: semilat_errI[OF semilat])
done
lemma err_semilat_eslI [intro, simp]:
"\<And>L. semilat L \<Longrightarrow> err_semilat(esl L)"
by(simp add: err_semilat_eslI_aux split_tupled_all)
lemma acc_err [simp, intro!]: "acc r \<Longrightarrow> acc(le r)"
apply (unfold acc_def lesub_def le_def lesssub_def)
apply (simp add: wf_eq_minimal split: err.split)
apply clarify
apply (case_tac "Err \<in> Q")
apply blast
apply (erule_tac x = "{a . OK a \<in> Q}" in allE)
apply (case_tac "x")
apply fast
apply blast
done
lemma Err_in_err [iff]: "Err \<in> err A"
by (simp add: err_def)
lemma Ok_in_err [iff]: "(OK x \<in> err A) = (x\<in>A)"
by (auto simp add: err_def)
subsection \<open>lift\<close>
lemma lift_in_errI:
"\<lbrakk> e \<in> err S; \<forall>x\<in>S. e = OK x \<longrightarrow> f x \<in> err S \<rbrakk> \<Longrightarrow> lift f e \<in> err S"
apply (unfold lift_def)
apply (simp split: err.split)
apply blast
done
lemma Err_lift2 [simp]:
"Err +_(lift2 f) x = Err"
by (simp add: lift2_def plussub_def)
lemma lift2_Err [simp]:
"x +_(lift2 f) Err = Err"
by (simp add: lift2_def plussub_def split: err.split)
lemma OK_lift2_OK [simp]:
"OK x +_(lift2 f) OK y = x +_f y"
by (simp add: lift2_def plussub_def split: err.split)
subsection \<open>sup\<close>
lemma Err_sup_Err [simp]:
"Err +_(Err.sup f) x = Err"
by (simp add: plussub_def Err.sup_def Err.lift2_def)
lemma Err_sup_Err2 [simp]:
"x +_(Err.sup f) Err = Err"
by (simp add: plussub_def Err.sup_def Err.lift2_def split: err.split)
lemma Err_sup_OK [simp]:
"OK x +_(Err.sup f) OK y = OK(x +_f y)"
by (simp add: plussub_def Err.sup_def Err.lift2_def)
lemma Err_sup_eq_OK_conv [iff]:
"(Err.sup f ex ey = OK z) = (\<exists>x y. ex = OK x & ey = OK y & f x y = z)"
apply (unfold Err.sup_def lift2_def plussub_def)
apply (rule iffI)
apply (simp split: err.split_asm)
apply clarify
apply simp
done
lemma Err_sup_eq_Err [iff]:
"(Err.sup f ex ey = Err) = (ex=Err | ey=Err)"
apply (unfold Err.sup_def lift2_def plussub_def)
apply (simp split: err.split)
done
subsection \<open>semilat (err A) (le r) f\<close>
lemma semilat_le_err_Err_plus [simp]:
"\<lbrakk> x \<in> err A; semilat(err A, le r, f) \<rbrakk> \<Longrightarrow> Err +_f x = Err"
by (blast intro: Semilat.le_iff_plus_unchanged [OF Semilat.intro, THEN iffD1]
Semilat.le_iff_plus_unchanged2 [OF Semilat.intro, THEN iffD1])
lemma semilat_le_err_plus_Err [simp]:
"\<lbrakk> x \<in> err A; semilat(err A, le r, f) \<rbrakk> \<Longrightarrow> x +_f Err = Err"
by (blast intro: Semilat.le_iff_plus_unchanged [OF Semilat.intro, THEN iffD1]
Semilat.le_iff_plus_unchanged2 [OF Semilat.intro, THEN iffD1])
lemma semilat_le_err_OK1:
"\<lbrakk> x \<in> A; y \<in> A; semilat(err A, le r, f); OK x +_f OK y = OK z \<rbrakk>
\<Longrightarrow> x <=_r z"
apply (rule OK_le_err_OK [THEN iffD1])
apply (erule subst)
apply (simp add: Semilat.ub1 [OF Semilat.intro])
done
lemma semilat_le_err_OK2:
"\<lbrakk> x \<in> A; y \<in> A; semilat(err A, le r, f); OK x +_f OK y = OK z \<rbrakk>
\<Longrightarrow> y <=_r z"
apply (rule OK_le_err_OK [THEN iffD1])
apply (erule subst)
apply (simp add: Semilat.ub2 [OF Semilat.intro])
done
lemma eq_order_le:
"\<lbrakk> x=y; order r \<rbrakk> \<Longrightarrow> x <=_r y"
apply (unfold Semilat.order_def)
apply blast
done
lemma OK_plus_OK_eq_Err_conv [simp]:
assumes "x \<in> A" and "y \<in> A" and "semilat(err A, le r, fe)"
shows "((OK x) +_fe (OK y) = Err) = (\<not>(\<exists>z\<in>A. x <=_r z & y <=_r z))"
proof -
have plus_le_conv3: "\<And>A x y z f r.
\<lbrakk> semilat (A,r,f); x +_f y <=_r z; x \<in> A; y \<in> A; z \<in> A \<rbrakk>
\<Longrightarrow> x <=_r z \<and> y <=_r z"
by (rule Semilat.plus_le_conv [OF Semilat.intro, THEN iffD1])
from assms show ?thesis
apply (rule_tac iffI)
apply clarify
apply (drule OK_le_err_OK [THEN iffD2])
apply (drule OK_le_err_OK [THEN iffD2])
apply (drule Semilat.lub [OF Semilat.intro, of _ _ _ "OK x" _ "OK y"])
apply assumption
apply assumption
apply simp
apply simp
apply simp
apply simp
apply (case_tac "(OK x) +_fe (OK y)")
apply assumption
apply (rename_tac z)
apply (subgoal_tac "OK z \<in> err A")
apply (drule eq_order_le)
apply (erule Semilat.orderI [OF Semilat.intro])
apply (blast dest: plus_le_conv3)
apply (erule subst)
apply (blast intro: Semilat.closedI [OF Semilat.intro] closedD)
done
qed
subsection \<open>semilat (err (Union AS))\<close>
(* FIXME? *)
lemma all_bex_swap_
text \<open>
If \<^term>\<open>AS = {}\<close> the thm collapses to
\<^prop>\<open>order r & closed {Err} f & Err +_f Err = Err\<close>
which may not hold
\<close>
lemma err_semilat_UnionI:
"\<lbrakk> \<forall>A\<in>AS. err_semilat(A, r, f); AS \<noteq> {};
\<forall>A\<in>AS. \<forall>B\<in>AS. A\<noteq>B \<longrightarrow> (\<forall>a\<in>A. \<forall>b\<in>B. \<not> a <=_r b & a +_f b = Err) \<rbrakk>
\<Longrightarrow> err_semilat (\<Union>AS, r, f)"
apply (unfold semilat_def sl_def)
apply (simp add: closed_err_Union_lift2I)
apply (rule conjI)
apply blast
apply (simp add: err_def)
apply (rule conjI)
apply clarify
apply (rename_tac A a u B b)
apply (case_tac "A = B")
apply simp
apply simp
apply (rule conjI)
apply clarify
apply (rename_tac A a u B b)
apply (case_tac "A = B")
apply simp
apply simp
apply clarify
apply (rename_tac A ya yb B yd z C c a b)
apply (case_tac "A = B")
apply (case_tac "A = C")
apply simp
apply (rotate_tac -1)
apply simp
apply (rotate_tac -1)
apply (case_tac "B = C")
apply simp
apply (rotate_tac -1)
apply simp
done
end
|
lemma head_minus_poly_rev_list: "length d \<le> length r \<Longrightarrow> d \<noteq> [] \<Longrightarrow> hd (minus_poly_rev_list (map ((*) (last d)) r) (map ((*) (hd r)) (rev d))) = 0" for d r :: "'a::comm_ring list" |
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <gsl/gsl_vector.h>
#define MAX(A,B) (((A)>(B))?(A):(B))
void reoshift(gsl_vector *v, int h)
{
if ( h > 0 ) {
gsl_vector *temp = gsl_vector_alloc(v->size);
gsl_vector_view p = gsl_vector_subvector(v, 0, v->size - h);
gsl_vector_view p1 = gsl_vector_subvector(temp, h, v->size - h);
gsl_vector_memcpy(&p1.vector, &p.vector);
p = gsl_vector_subvector(temp, 0, h);
gsl_vector_set_zero(&p.vector);
gsl_vector_memcpy(v, temp);
gsl_vector_free(temp);
}
}
gsl_vector *poly_long_div(gsl_vector *n, gsl_vector *d, gsl_vector **r)
{
gsl_vector *nt = NULL, *dt = NULL, *rt = NULL, *d2 = NULL, *q = NULL;
int gn, gt, gd;
if ( (n->size >= d->size) && (d->size > 0) && (n->size > 0) ) {
nt = gsl_vector_alloc(n->size); assert(nt != NULL);
dt = gsl_vector_alloc(n->size); assert(dt != NULL);
rt = gsl_vector_alloc(n->size); assert(rt != NULL);
d2 = gsl_vector_alloc(n->size); assert(d2 != NULL);
gsl_vector_memcpy(nt, n);
gsl_vector_set_zero(dt); gsl_vector_set_zero(rt);
gsl_vector_view p = gsl_vector_subvector(dt, 0, d->size);
gsl_vector_memcpy(&p.vector, d);
gsl_vector_memcpy(d2, dt);
gn = n->size - 1;
gd = d->size - 1;
gt = 0;
while( gsl_vector_get(d, gd) == 0 ) gd--;
while ( gn >= gd ) {
reoshift(dt, gn-gd);
double v = gsl_vector_get(nt, gn)/gsl_vector_get(dt, gn);
gsl_vector_set(rt, gn-gd, v);
gsl_vector_scale(dt, v);
gsl_vector_sub(nt, dt);
gt = MAX(gt, gn-gd);
while( (gn>=0) && (gsl_vector_get(nt, gn) == 0.0) ) gn--;
gsl_vector_memcpy(dt, d2);
}
q = gsl_vector_alloc(gt+1); assert(q != NULL);
p = gsl_vector_subvector(rt, 0, gt+1);
gsl_vector_memcpy(q, &p.vector);
if ( r != NULL ) {
if ( (gn+1) > 0 ) {
*r = gsl_vector_alloc(gn+1); assert( *r != NULL );
p = gsl_vector_subvector(nt, 0, gn+1);
gsl_vector_memcpy(*r, &p.vector);
} else {
*r = gsl_vector_alloc(1); assert( *r != NULL );
gsl_vector_set_zero(*r);
}
}
gsl_vector_free(nt); gsl_vector_free(dt);
gsl_vector_free(rt); gsl_vector_free(d2);
return q;
} else {
q = gsl_vector_alloc(1); assert( q != NULL );
gsl_vector_set_zero(q);
if ( r != NULL ) {
*r = gsl_vector_alloc(n->size); assert( *r != NULL );
gsl_vector_memcpy(*r, n);
}
return q;
}
}
void poly_print(gsl_vector *p)
{
int i;
for(i=p->size-1; i >= 0; i--) {
if ( i > 0 )
printf("%lfx^%d + ",
gsl_vector_get(p, i), i);
else
printf("%lf\n", gsl_vector_get(p, i));
}
}
gsl_vector *create_poly(int d, ...)
{
va_list al;
int i;
gsl_vector *r = NULL;
va_start(al, d);
r = gsl_vector_alloc(d); assert( r != NULL );
for(i=0; i < d; i++)
gsl_vector_set(r, i, va_arg(al, double));
return r;
}
|
import h5py
import numpy as np
import qpost
class object:
def __init__(self, filename, group_name, name):
self.filename = filename
self.group_name = group_name
self.name = name
self.path = "/objects/{0}/{1}".format(group_name, name)
self.position = qpost.vec.load_vec(filename, self.path, "position")
self.theta = qpost.vec.load_scalar(filename, self.path, "theta")
with h5py.File(filename, 'r') as f:
ref = f[self.path + "/material"][...].tolist()
material_path = f[ref].name
material_name = material_path[material_path.rfind("/")+1:]
self.material = qpost.materials.load_material(filename, material_name)
class cylinder(object):
def __init__(self, filename, name):
super().__init__(filename, "cylinders", name)
with h5py.File(filename, 'r') as f:
self.radius = f[self.path]["radius"][...]
class ellipse(object):
def __init__(self, filename, name):
super().__init__(filename, "ellipses", name)
with h5py.File(filename, 'r') as f:
self.rx = f[self.path]["rx"][...]
self.ry = f[self.path]["ry"][...]
class block(object):
def __init__(self, filename, name):
super().__init__(filename, "blocks", name)
with h5py.File(filename, 'r') as f:
self.dimensions = f[self.path]["dimensions"][...]
|
The whole space is convex. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.