Datasets:
AI4M
/

text
stringlengths
0
3.34M
(* ================================ *) (* ========== CH01_ccw.v ========== *) (* ================================ *) Require Export Del13. Open Scope R_scope. (* ================================ *) (* ========== ########## ========== *) (* ================================ *) Definition det (p q r : point) : R := (fst p * snd q) - (fst q * snd p) - (fst p * snd r) + (fst r * snd p) + (fst q * snd r) - (fst r * snd q). Lemma eq_det : forall (p q r : point), det p q r = det q r p. Proof. intros p q r. unfold det; ring. Qed. Lemma neq_det : forall (p q r : point), det p q r = - det p r q. Proof. intros p q r. unfold det; ring. Qed. (* ================================ *) (* ========== ########## ========== *) (* ================================ *) Definition ccw (p q r : point) : Prop := (det p q r > 0). Lemma ccw_dec : forall (p q r : point), {ccw p q r} + {~ ccw p q r}. Proof. intros p q r. unfold ccw; apply Rgt_dec. Qed. (* ================================ *) Definition align (p q r : point) : Prop := (det p q r = 0). Lemma align_dec : forall (p q r : point), {align p q r} + {~align p q r}. Proof. intros p q r. unfold align. generalize (total_order_T (det p q r) 0). generalize (Rlt_dichotomy_converse (det p q r) 0). tauto. Qed. (* ================================ *) (* ========== ########## ========== *) (* ================================ *) Lemma Rle_neq_lt : forall (r1 r2 : R), r1 <= r2 -> r1 <> r2 -> r1 < r2. Proof. intros r1 r2 H1 H2. elim (Rdichotomy r1 r2). trivial. generalize (Rle_not_lt r2 r1). tauto. assumption. Qed. Lemma R_gt_0_plus : forall (r1 r2 : R), r1 > 0 -> r2 > 0 -> r1 + r2 > 0. Proof. intros r1 r2 H1 H2. apply Rgt_trans with r1. pattern r1 at 2; rewrite <- (Rplus_0_r r1). apply Rplus_gt_compat_l; assumption. assumption. Qed. Lemma R_gt_0_mult : forall (r1 r2 : R), r1 > 0 -> r2 > 0 -> r1 * r2 > 0. Proof. apply Rmult_gt_0_compat. Qed. Lemma R_gt_0_div : forall (r1 r2 : R), r1 > 0 -> r2 > 0 -> r1 * / r2 > 0. Proof. intros r1 r2 H1 H2. apply R_gt_0_mult. assumption. unfold Rgt in *; auto with real. Qed. Lemma R_mult_div : forall (r1 r2 r3 : R), r1 = r2 * r3 -> r2 > 0 -> r1 * / r2 = r3. Proof. intros r1 r2 r3 H1 H2. subst r1; auto with real. Qed. (* ================================ *) (* ========== ########## ========== *) (* ================================ *) Lemma axiom_orientation_1 : forall (A:point)(B:point)(C:point), ccw A B C -> ccw B C A. Proof. intros A B C. unfold ccw; rewrite eq_det; trivial. Qed. Lemma axiom_orientation_2 : forall (A:point)(B:point)(C:point), align A B C -> align B C A. Proof. intros A B C. unfold align; rewrite eq_det; trivial. Qed. Lemma axiom_orientation_3 : forall (A:point)(B:point)(C:point), align A B C -> align A C B. Proof. intros A B C. unfold align; rewrite neq_det. generalize (Rplus_opp_r (det A C B)). generalize (Rplus_0_l (det A C B)). intros H1 H2 H3. rewrite H3 in H2; clear H3. rewrite Rplus_comm in H1. rewrite H1 in H2; clear H1. assumption. Qed. Hint Resolve axiom_orientation_1 axiom_orientation_2 axiom_orientation_3 : myorientation. (* ================================ *) Lemma axiom_orientation_4 : forall (A:point)(B:point)(C:point), ccw A B C -> ~ ccw A C B. Proof. intros A B C. unfold ccw; rewrite neq_det. generalize (Ropp_gt_lt_contravar (- det A C B) 0). rewrite Ropp_involutive; rewrite Ropp_0. intro H1; generalize (Rlt_le (det A C B) 0). intro H2; generalize (Rle_not_lt 0 (det A C B)). intro H3; tauto. Qed. Lemma axiom_orientation_5 : forall (A:point)(B:point)(C:point), ccw A B C -> ~ align A B C. Proof. intros A B C. unfold ccw, align in *. apply Rgt_not_eq; assumption. Qed. Lemma axiom_orientation_6 : forall (A:point)(B:point)(C:point), align A B C -> ~ ccw A B C. Proof. intros A B C. unfold ccw, align in *. intro H1; rewrite H1. unfold not; intro H2. apply Rgt_not_eq in H2; tauto. Qed. Hint Resolve axiom_orientation_4 axiom_orientation_5 axiom_orientation_6 : myorientation. (* ================================ *) Lemma axiom_orientation_7 : forall (A:point)(B:point)(C:point), ~ ccw A B C -> ccw A C B \/ align A B C. Proof. intros A B C H. elim (ccw_dec A C B). intro H1; left; assumption. intro H1; right. unfold ccw, align in *. rewrite neq_det in H1. apply Rle_antisym. apply Rnot_gt_le; assumption. apply Rnot_gt_le; auto with real. Qed. Lemma axiom_orientation_8 : forall (A:point)(B:point)(C:point), ~ align A B C -> ccw A B C \/ ccw A C B. Proof. intros A B C H. elim (ccw_dec A B C). intro H0; left; assumption. intro H0; right. apply axiom_orientation_7 in H0. elim H0; [trivial|contradiction]. Qed. Hint Resolve axiom_orientation_7 axiom_orientation_8 : myorientation. (* ================================ *) (* ========== ########## ========== *) (* ================================ *) Lemma ccw_axiom_1 : forall (p q r : point), ccw p q r -> ccw q r p. Proof. auto with myorientation. Qed. Lemma ccw_axiom_2 : forall (p q r : point), ccw p q r -> ~ ccw p r q. Proof. auto with myorientation. Qed. Lemma ccw_axiom_3 : forall (p q r : point), ~ align p q r -> (ccw p q r) \/ (ccw p r q). Proof. auto with myorientation. Qed. Lemma ccw_axiom_4 : forall (p q r t : point), (ccw t q r) -> (ccw p t r) -> (ccw p q t) -> (ccw p q r). Proof. intros p q r t H1 H2 H3. unfold ccw in *. assert (det t q r + det p t r + det p q t = det p q r). unfold det; ring. rewrite <- H. apply R_gt_0_plus; [apply R_gt_0_plus; assumption | assumption]. Qed. Lemma ccw_axiom_5 : forall (p q r s t : point), (ccw t s p) -> (ccw t s q) -> (ccw t s r) -> (ccw t p q) -> (ccw t q r) -> (ccw t p r). Proof. intros p q r s t H1 H2 H3 H4 H5. unfold ccw in *. replace (det t p r) with ((det t p q * det t s r + det t q r * det t s p) * / (det t s q)). apply R_gt_0_div. apply R_gt_0_plus. apply R_gt_0_mult; assumption. apply R_gt_0_mult; assumption. assumption. apply R_mult_div. unfold det; ring. assumption. Qed. Lemma ccw_axiom_5_bis : forall (p q r s t : point), (ccw s t p) -> (ccw s t q) -> (ccw s t r) -> (ccw t p q) -> (ccw t q r) -> (ccw t p r). Proof. intros p q r s t H1 H2 H3 H4 H5. unfold ccw in *. replace (det t p r) with ((det t p q * det s t r + det t q r * det s t p) * / (det s t q)). apply R_gt_0_div. apply R_gt_0_plus. apply R_gt_0_mult; assumption. apply R_gt_0_mult; assumption. assumption. apply R_mult_div. unfold det; ring. assumption. Qed.
[STATEMENT] lemma gcd_diff_dvd_left1: "a dvd b \<Longrightarrow> gcd (b - c) a = gcd c a" [PROOF STATE] proof (prove) goal (1 subgoal): 1. a dvd b \<Longrightarrow> gcd (b - c) a = gcd c a [PROOF STEP] using gcd_add_dvd_left1[of a b "-c"] [PROOF STATE] proof (prove) using this: a dvd b \<Longrightarrow> gcd (b + - c) a = gcd (- c) a goal (1 subgoal): 1. a dvd b \<Longrightarrow> gcd (b - c) a = gcd c a [PROOF STEP] by simp
module Issue784.Context where open import Data.List using (List; []; _∷_; _++_; [_]; filter) renaming (map to mapL) import Level open import Issue784.Values record Context ℓ : Set (Level.suc ℓ) where constructor context field get : Values ℓ signature : ∀ {ℓ} → Context ℓ → Types ℓ signature = types ∘ Context.get ctxnames : ∀ {ℓ} → Context ℓ → Names ctxnames = names ∘ Context.get NonRepetitiveContext : ∀ {ℓ} → Context ℓ → _ NonRepetitiveContext = NonRepetitiveNames ∘ Context.get getBySignature : ∀ {ℓ} {n : String} {A : Set ℓ} {x : Context ℓ} → (n , A) ∈ signature x → A getBySignature {x = x} = getBySignature′ {x = Context.get x} where getBySignature′ : ∀ {ℓ} {n : String} {A : Set ℓ} {x : Values ℓ} → (n , A) ∈ types x → A getBySignature′ {x = []} () getBySignature′ {x = (_ , _ , à) ∷ _} (here {x = ._} {xs = ._} p) = ≡-elim′ proj₂ (≡-sym p) à getBySignature′ {x = _ ∷ _} (there {x = ._} {xs = ._} p) = getBySignature′ p
open import Prelude open import Nat open import core open import contexts open import disjointness -- this module contains lemmas and properties about the holes-disjoint -- judgement that double check that it acts as we would expect module holes-disjoint-checks where -- these lemmas are all structurally recursive and quite -- mechanical. morally, they establish the properties about reduction -- that would be obvious / baked into Agda if holes-disjoint was defined -- as a function rather than a judgement (datatype), or if we had defined -- all the O(n^2) cases rather than relying on a little indirection to -- only have O(n) cases. that work has to go somewhwere, and we prefer -- that it goes here. ds-lem-asc : ∀{e1 e2 τ} → holes-disjoint e2 e1 → holes-disjoint e2 (e1 ·: τ) ds-lem-asc HDConst = HDConst ds-lem-asc (HDAsc hd) = HDAsc (ds-lem-asc hd) ds-lem-asc HDVar = HDVar ds-lem-asc (HDLam1 hd) = HDLam1 (ds-lem-asc hd) ds-lem-asc (HDLam2 hd) = HDLam2 (ds-lem-asc hd) ds-lem-asc (HDHole x) = HDHole (HNAsc x) ds-lem-asc (HDNEHole x hd) = HDNEHole (HNAsc x) (ds-lem-asc hd) ds-lem-asc (HDAp hd hd₁) = HDAp (ds-lem-asc hd) (ds-lem-asc hd₁) ds-lem-lam1 : ∀{e1 e2 x} → holes-disjoint e2 e1 → holes-disjoint e2 (·λ x e1) ds-lem-lam1 HDConst = HDConst ds-lem-lam1 (HDAsc hd) = HDAsc (ds-lem-lam1 hd) ds-lem-lam1 HDVar = HDVar ds-lem-lam1 (HDLam1 hd) = HDLam1 (ds-lem-lam1 hd) ds-lem-lam1 (HDLam2 hd) = HDLam2 (ds-lem-lam1 hd) ds-lem-lam1 (HDHole x₁) = HDHole (HNLam1 x₁) ds-lem-lam1 (HDNEHole x₁ hd) = HDNEHole (HNLam1 x₁) (ds-lem-lam1 hd) ds-lem-lam1 (HDAp hd hd₁) = HDAp (ds-lem-lam1 hd) (ds-lem-lam1 hd₁) ds-lem-lam2 : ∀{e1 e2 x τ} → holes-disjoint e2 e1 → holes-disjoint e2 (·λ x [ τ ] e1) ds-lem-lam2 HDConst = HDConst ds-lem-lam2 (HDAsc hd) = HDAsc (ds-lem-lam2 hd) ds-lem-lam2 HDVar = HDVar ds-lem-lam2 (HDLam1 hd) = HDLam1 (ds-lem-lam2 hd) ds-lem-lam2 (HDLam2 hd) = HDLam2 (ds-lem-lam2 hd) ds-lem-lam2 (HDHole x₁) = HDHole (HNLam2 x₁) ds-lem-lam2 (HDNEHole x₁ hd) = HDNEHole (HNLam2 x₁) (ds-lem-lam2 hd) ds-lem-lam2 (HDAp hd hd₁) = HDAp (ds-lem-lam2 hd) (ds-lem-lam2 hd₁) ds-lem-nehole : ∀{e e1 u} → holes-disjoint e e1 → hole-name-new e u → holes-disjoint e ⦇⌜ e1 ⌟⦈[ u ] ds-lem-nehole HDConst ν = HDConst ds-lem-nehole (HDAsc hd) (HNAsc ν) = HDAsc (ds-lem-nehole hd ν) ds-lem-nehole HDVar ν = HDVar ds-lem-nehole (HDLam1 hd) (HNLam1 ν) = HDLam1 (ds-lem-nehole hd ν) ds-lem-nehole (HDLam2 hd) (HNLam2 ν) = HDLam2 (ds-lem-nehole hd ν) ds-lem-nehole (HDHole x) (HNHole x₁) = HDHole (HNNEHole (flip x₁) x) ds-lem-nehole (HDNEHole x hd) (HNNEHole x₁ ν) = HDNEHole (HNNEHole (flip x₁) x) (ds-lem-nehole hd ν) ds-lem-nehole (HDAp hd hd₁) (HNAp ν ν₁) = HDAp (ds-lem-nehole hd ν) (ds-lem-nehole hd₁ ν₁) ds-lem-ap : ∀{e1 e2 e3} → holes-disjoint e3 e1 → holes-disjoint e3 e2 → holes-disjoint e3 (e1 ∘ e2) ds-lem-ap HDConst hd2 = HDConst ds-lem-ap (HDAsc hd1) (HDAsc hd2) = HDAsc (ds-lem-ap hd1 hd2) ds-lem-ap HDVar hd2 = HDVar ds-lem-ap (HDLam1 hd1) (HDLam1 hd2) = HDLam1 (ds-lem-ap hd1 hd2) ds-lem-ap (HDLam2 hd1) (HDLam2 hd2) = HDLam2 (ds-lem-ap hd1 hd2) ds-lem-ap (HDHole x) (HDHole x₁) = HDHole (HNAp x x₁) ds-lem-ap (HDNEHole x hd1) (HDNEHole x₁ hd2) = HDNEHole (HNAp x x₁) (ds-lem-ap hd1 hd2) ds-lem-ap (HDAp hd1 hd2) (HDAp hd3 hd4) = HDAp (ds-lem-ap hd1 hd3) (ds-lem-ap hd2 hd4) -- holes-disjoint is symmetric disjoint-sym : (e1 e2 : hexp) → holes-disjoint e1 e2 → holes-disjoint e2 e1 disjoint-sym .c c HDConst = HDConst disjoint-sym .c (e2 ·: x) HDConst = HDAsc (disjoint-sym _ _ HDConst) disjoint-sym .c (X x) HDConst = HDVar disjoint-sym .c (·λ x e2) HDConst = HDLam1 (disjoint-sym c e2 HDConst) disjoint-sym .c (·λ x [ x₁ ] e2) HDConst = HDLam2 (disjoint-sym c e2 HDConst) disjoint-sym .c ⦇-⦈[ x ] HDConst = HDHole HNConst disjoint-sym .c ⦇⌜ e2 ⌟⦈[ x ] HDConst = HDNEHole HNConst (disjoint-sym c e2 HDConst) disjoint-sym .c (e2 ∘ e3) HDConst = HDAp (disjoint-sym c e2 HDConst) (disjoint-sym c e3 HDConst) disjoint-sym _ c (HDAsc hd) = HDConst disjoint-sym _ (e2 ·: x) (HDAsc hd) with disjoint-sym _ _ hd disjoint-sym _ (e2 ·: x) (HDAsc hd) | HDAsc ih = HDAsc (ds-lem-asc ih) disjoint-sym _ (X x) (HDAsc hd) = HDVar disjoint-sym _ (·λ x e2) (HDAsc hd) with disjoint-sym _ _ hd disjoint-sym _ (·λ x e2) (HDAsc hd) | HDLam1 ih = HDLam1 (ds-lem-asc ih) disjoint-sym _ (·λ x [ x₁ ] e2) (HDAsc hd) with disjoint-sym _ _ hd disjoint-sym _ (·λ x [ x₁ ] e2) (HDAsc hd) | HDLam2 ih = HDLam2 (ds-lem-asc ih) disjoint-sym _ ⦇-⦈[ x ] (HDAsc hd) with disjoint-sym _ _ hd disjoint-sym _ ⦇-⦈[ x ] (HDAsc hd) | HDHole x₁ = HDHole (HNAsc x₁) disjoint-sym _ ⦇⌜ e2 ⌟⦈[ x ] (HDAsc hd) with disjoint-sym _ _ hd disjoint-sym _ ⦇⌜ e2 ⌟⦈[ x ] (HDAsc hd) | HDNEHole x₁ ih = HDNEHole (HNAsc x₁) (ds-lem-asc ih) disjoint-sym _ (e2 ∘ e3) (HDAsc hd) with disjoint-sym _ _ hd disjoint-sym _ (e2 ∘ e3) (HDAsc hd) | HDAp ih ih₁ = HDAp (ds-lem-asc ih) (ds-lem-asc ih₁) disjoint-sym _ c HDVar = HDConst disjoint-sym _ (e2 ·: x₁) HDVar = HDAsc (disjoint-sym _ e2 HDVar) disjoint-sym _ (X x₁) HDVar = HDVar disjoint-sym _ (·λ x₁ e2) HDVar = HDLam1 (disjoint-sym _ e2 HDVar) disjoint-sym _ (·λ x₁ [ x₂ ] e2) HDVar = HDLam2 (disjoint-sym _ e2 HDVar) disjoint-sym _ ⦇-⦈[ x₁ ] HDVar = HDHole HNVar disjoint-sym _ ⦇⌜ e2 ⌟⦈[ x₁ ] HDVar = HDNEHole HNVar (disjoint-sym _ e2 HDVar) disjoint-sym _ (e2 ∘ e3) HDVar = HDAp (disjoint-sym _ e2 HDVar) (disjoint-sym _ e3 HDVar) disjoint-sym _ c (HDLam1 hd) = HDConst disjoint-sym _ (e2 ·: x₁) (HDLam1 hd) with disjoint-sym _ _ hd disjoint-sym _ (e2 ·: x₁) (HDLam1 hd) | HDAsc ih = HDAsc (ds-lem-lam1 ih) disjoint-sym _ (X x₁) (HDLam1 hd) = HDVar disjoint-sym _ (·λ x₁ e2) (HDLam1 hd) with disjoint-sym _ _ hd disjoint-sym _ (·λ x₁ e2) (HDLam1 hd) | HDLam1 ih = HDLam1 (ds-lem-lam1 ih) disjoint-sym _ (·λ x₁ [ x₂ ] e2) (HDLam1 hd) with disjoint-sym _ _ hd disjoint-sym _ (·λ x₁ [ x₂ ] e2) (HDLam1 hd) | HDLam2 ih = HDLam2 (ds-lem-lam1 ih) disjoint-sym _ ⦇-⦈[ x₁ ] (HDLam1 hd) with disjoint-sym _ _ hd disjoint-sym _ ⦇-⦈[ x₁ ] (HDLam1 hd) | HDHole x = HDHole (HNLam1 x) disjoint-sym _ ⦇⌜ e2 ⌟⦈[ x₁ ] (HDLam1 hd) with disjoint-sym _ _ hd disjoint-sym _ ⦇⌜ e2 ⌟⦈[ x₁ ] (HDLam1 hd) | HDNEHole x ih = HDNEHole (HNLam1 x) (ds-lem-lam1 ih) disjoint-sym _ (e2 ∘ e3) (HDLam1 hd) with disjoint-sym _ _ hd disjoint-sym _ (e2 ∘ e3) (HDLam1 hd) | HDAp ih ih₁ = HDAp (ds-lem-lam1 ih) (ds-lem-lam1 ih₁) disjoint-sym _ c (HDLam2 hd) = HDConst disjoint-sym _ (e2 ·: x₁) (HDLam2 hd) with disjoint-sym _ _ hd disjoint-sym _ (e2 ·: x₁) (HDLam2 hd) | HDAsc ih = HDAsc (ds-lem-lam2 ih) disjoint-sym _ (X x₁) (HDLam2 hd) = HDVar disjoint-sym _ (·λ x₁ e2) (HDLam2 hd) with disjoint-sym _ _ hd disjoint-sym _ (·λ x₁ e2) (HDLam2 hd) | HDLam1 ih = HDLam1 (ds-lem-lam2 ih) disjoint-sym _ (·λ x₁ [ x₂ ] e2) (HDLam2 hd) with disjoint-sym _ _ hd disjoint-sym _ (·λ x₁ [ x₂ ] e2) (HDLam2 hd) | HDLam2 ih = HDLam2 (ds-lem-lam2 ih) disjoint-sym _ ⦇-⦈[ x₁ ] (HDLam2 hd) with disjoint-sym _ _ hd disjoint-sym _ ⦇-⦈[ x₁ ] (HDLam2 hd) | HDHole x = HDHole (HNLam2 x) disjoint-sym _ ⦇⌜ e2 ⌟⦈[ x₁ ] (HDLam2 hd) with disjoint-sym _ _ hd disjoint-sym _ ⦇⌜ e2 ⌟⦈[ x₁ ] (HDLam2 hd) | HDNEHole x ih = HDNEHole (HNLam2 x) (ds-lem-lam2 ih) disjoint-sym _ (e2 ∘ e3) (HDLam2 hd) with disjoint-sym _ _ hd disjoint-sym _ (e2 ∘ e3) (HDLam2 hd) | HDAp ih ih₁ = HDAp (ds-lem-lam2 ih) (ds-lem-lam2 ih₁) disjoint-sym _ c (HDHole x) = HDConst disjoint-sym _ (e2 ·: x) (HDHole (HNAsc x₁)) = HDAsc (disjoint-sym ⦇-⦈[ _ ] e2 (HDHole x₁)) disjoint-sym _ (X x) (HDHole x₁) = HDVar disjoint-sym _ (·λ x e2) (HDHole (HNLam1 x₁)) = HDLam1 (disjoint-sym ⦇-⦈[ _ ] e2 (HDHole x₁)) disjoint-sym _ (·λ x [ x₁ ] e2) (HDHole (HNLam2 x₂)) = HDLam2 (disjoint-sym ⦇-⦈[ _ ] e2 (HDHole x₂)) disjoint-sym _ ⦇-⦈[ x ] (HDHole (HNHole x₁)) = HDHole (HNHole (flip x₁)) disjoint-sym _ ⦇⌜ e2 ⌟⦈[ u' ] (HDHole (HNNEHole x x₁)) = HDNEHole (HNHole (flip x)) (disjoint-sym ⦇-⦈[ _ ] e2 (HDHole x₁)) disjoint-sym _ (e2 ∘ e3) (HDHole (HNAp x x₁)) = HDAp (disjoint-sym ⦇-⦈[ _ ] e2 (HDHole x)) (disjoint-sym ⦇-⦈[ _ ] e3 (HDHole x₁)) disjoint-sym _ c (HDNEHole x hd) = HDConst disjoint-sym _ (e2 ·: x) (HDNEHole x₁ hd) with disjoint-sym _ _ hd disjoint-sym _ (e ·: x) (HDNEHole (HNAsc x₁) hd) | HDAsc ih = HDAsc (ds-lem-nehole ih x₁) disjoint-sym _ (X x) (HDNEHole x₁ hd) = HDVar disjoint-sym _ (·λ x e2) (HDNEHole x₁ hd) with disjoint-sym _ _ hd disjoint-sym _ (·λ x e2) (HDNEHole (HNLam1 x₁) hd) | HDLam1 ih = HDLam1 (ds-lem-nehole ih x₁) disjoint-sym _ (·λ x [ x₁ ] e2) (HDNEHole x₂ hd) with disjoint-sym _ _ hd disjoint-sym _ (·λ x [ x₁ ] e2) (HDNEHole (HNLam2 x₂) hd) | HDLam2 ih = HDLam2 (ds-lem-nehole ih x₂) disjoint-sym _ ⦇-⦈[ x ] (HDNEHole x₁ hd) with disjoint-sym _ _ hd disjoint-sym _ ⦇-⦈[ x ] (HDNEHole (HNHole x₂) hd) | HDHole x₁ = HDHole (HNNEHole (flip x₂) x₁) disjoint-sym _ ⦇⌜ e2 ⌟⦈[ x ] (HDNEHole x₁ hd) with disjoint-sym _ _ hd disjoint-sym _ ⦇⌜ e2 ⌟⦈[ x ] (HDNEHole (HNNEHole x₂ x₃) hd) | HDNEHole x₁ ih = HDNEHole (HNNEHole (flip x₂) x₁) (ds-lem-nehole ih x₃) disjoint-sym _ (e2 ∘ e3) (HDNEHole x hd) with disjoint-sym _ _ hd disjoint-sym _ (e1 ∘ e3) (HDNEHole (HNAp x x₁) hd) | HDAp ih ih₁ = HDAp (ds-lem-nehole ih x) (ds-lem-nehole ih₁ x₁) disjoint-sym _ c (HDAp hd hd₁) = HDConst disjoint-sym _ (e3 ·: x) (HDAp hd hd₁) with disjoint-sym _ _ hd | disjoint-sym _ _ hd₁ disjoint-sym _ (e3 ·: x) (HDAp hd hd₁) | HDAsc ih | HDAsc ih1 = HDAsc (ds-lem-ap ih ih1) disjoint-sym _ (X x) (HDAp hd hd₁) = HDVar disjoint-sym _ (·λ x e3) (HDAp hd hd₁) with disjoint-sym _ _ hd | disjoint-sym _ _ hd₁ disjoint-sym _ (·λ x e3) (HDAp hd hd₁) | HDLam1 ih | HDLam1 ih1 = HDLam1 (ds-lem-ap ih ih1) disjoint-sym _ (·λ x [ x₁ ] e3) (HDAp hd hd₁) with disjoint-sym _ _ hd | disjoint-sym _ _ hd₁ disjoint-sym _ (·λ x [ x₁ ] e3) (HDAp hd hd₁) | HDLam2 ih | HDLam2 ih1 = HDLam2 (ds-lem-ap ih ih1) disjoint-sym _ ⦇-⦈[ x ] (HDAp hd hd₁) with disjoint-sym _ _ hd | disjoint-sym _ _ hd₁ disjoint-sym _ ⦇-⦈[ x ] (HDAp hd hd₁) | HDHole x₁ | HDHole x₂ = HDHole (HNAp x₁ x₂) disjoint-sym _ ⦇⌜ e3 ⌟⦈[ x ] (HDAp hd hd₁) with disjoint-sym _ _ hd | disjoint-sym _ _ hd₁ disjoint-sym _ ⦇⌜ e3 ⌟⦈[ x ] (HDAp hd hd₁) | HDNEHole x₁ ih | HDNEHole x₂ ih1 = HDNEHole (HNAp x₁ x₂) (ds-lem-ap ih ih1) disjoint-sym _ (e3 ∘ e4) (HDAp hd hd₁) with disjoint-sym _ _ hd | disjoint-sym _ _ hd₁ disjoint-sym _ (e3 ∘ e4) (HDAp hd hd₁) | HDAp ih ih₁ | HDAp ih1 ih2 = HDAp (ds-lem-ap ih ih1) (ds-lem-ap ih₁ ih2) -- note that this is false, so holes-disjoint isn't transitive -- disjoint-new : ∀{e1 e2 u} → holes-disjoint e1 e2 → hole-name-new e1 u → hole-name-new e2 u -- it's also not reflexive, because ⦇-⦈[ u ] isn't hole-disjoint with -- itself since refl : u == u; it's also not anti-reflexive, because the -- expression c *is* hole-disjoint with itself (albeit vacuously)
Formal statement is: lemma Zfun_ssubst: "eventually (\<lambda>x. f x = g x) F \<Longrightarrow> Zfun g F \<Longrightarrow> Zfun f F" Informal statement is: If $f$ and $g$ are two functions such that $f(x) = g(x)$ for all $x$ in some set $F$, then $f$ is a zero function on $F$ if and only if $g$ is a zero function on $F$.
(* *********************************************************************) (* *) (* The Compcert verified compiler *) (* *) (* Xavier Leroy, INRIA Paris-Rocquencourt *) (* *) (* Copyright Institut National de Recherche en Informatique et en *) (* Automatique. All rights reserved. This file is distributed *) (* under the terms of the 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 file is also distributed *) (* under the terms of the INRIA Non-Commercial License Agreement. *) (* *) (* *********************************************************************) (** Tools for small-step operational semantics *) (** This module defines generic operations and theorems over the one-step transition relations that are used to specify operational semantics in small-step style. *) Require Import Relations. Require Import Wellfounded. Require Import Coqlib. Require Import Events. Require Import Globalenvs. Require Import Integers. (*NEW*) Require Import AST. (*NEW*) Require Import Values. (*NEW*) Require Import Memory. (* To specify injections*) Set Implicit Arguments. (** * Closures of transitions relations *) Section CLOSURES. Variable genv: Type. Variable state: Type. (** A one-step transition relation has the following signature. It is parameterized by a global environment, which does not change during the transition. It relates the initial state of the transition with its final state. The [trace] parameter captures the observable events possibly generated during the transition. *) Variable step: state -> trace -> state -> Prop. (** No transitions: stuck state *) Definition nostep (s: state) : Prop := forall t s', ~(step s t s'). (** Zero, one or several transitions. Also known as Kleene closure, or reflexive transitive closure. *) Inductive star : state -> trace -> state -> Prop := | star_refl: forall s, star s E0 s | star_step: forall s1 t1 s2 t2 s3 t, step s1 t1 s2 -> star s2 t2 s3 -> t = t1 ** t2 -> star s1 t s3. Lemma star_one: forall s1 t s2, step s1 t s2 -> star s1 t s2. Proof. intros. eapply star_step; eauto. apply star_refl. traceEq. Qed. Lemma star_two: forall s1 t1 s2 t2 s3 t, step s1 t1 s2 -> step s2 t2 s3 -> t = t1 ** t2 -> star s1 t s3. Proof. intros. eapply star_step; eauto. apply star_one; auto. Qed. Lemma star_three: forall s1 t1 s2 t2 s3 t3 s4 t, step s1 t1 s2 -> step s2 t2 s3 -> step s3 t3 s4 -> t = t1 ** t2 ** t3 -> star s1 t s4. Proof. intros. eapply star_step; eauto. eapply star_two; eauto. Qed. Lemma star_four: forall s1 t1 s2 t2 s3 t3 s4 t4 s5 t, step s1 t1 s2 -> step s2 t2 s3 -> step s3 t3 s4 -> step s4 t4 s5 -> t = t1 ** t2 ** t3 ** t4 -> star s1 t s5. Proof. intros. eapply star_step; eauto. eapply star_three; eauto. Qed. Lemma star_trans: forall s1 t1 s2, star s1 t1 s2 -> forall t2 s3 t, star s2 t2 s3 -> t = t1 ** t2 -> star s1 t s3. Proof. induction 1; intros. rewrite H0. simpl. auto. eapply star_step; eauto. traceEq. Qed. Lemma star_left: forall s1 t1 s2 t2 s3 t, step s1 t1 s2 -> star s2 t2 s3 -> t = t1 ** t2 -> star s1 t s3. Proof star_step. Lemma star_right: forall s1 t1 s2 t2 s3 t, star s1 t1 s2 -> step s2 t2 s3 -> t = t1 ** t2 -> star s1 t s3. Proof. intros. eapply star_trans. eauto. apply star_one. eauto. auto. Qed. Lemma star_E0_ind: forall (P: state -> state -> Prop), (forall s, P s s) -> (forall s1 s2 s3, step s1 E0 s2 -> P s2 s3 -> P s1 s3) -> forall s1 s2, star s1 E0 s2 -> P s1 s2. Proof. intros P BASE REC. assert (forall s1 t s2, star s1 t s2 -> t = E0 -> P s1 s2). induction 1; intros; subst. auto. destruct (Eapp_E0_inv _ _ H2). subst. eauto. eauto. Qed. (** One or several transitions. Also known as the transitive closure. *) Inductive plus : state -> trace -> state -> Prop := | plus_left: forall s1 t1 s2 t2 s3 t, step s1 t1 s2 -> star s2 t2 s3 -> t = t1 ** t2 -> plus s1 t s3. Lemma plus_one: forall s1 t s2, step s1 t s2 -> plus s1 t s2. Proof. intros. econstructor; eauto. apply star_refl. traceEq. Qed. Lemma plus_two: forall s1 t1 s2 t2 s3 t, step s1 t1 s2 -> step s2 t2 s3 -> t = t1 ** t2 -> plus s1 t s3. Proof. intros. eapply plus_left; eauto. apply star_one; auto. Qed. Lemma plus_three: forall s1 t1 s2 t2 s3 t3 s4 t, step s1 t1 s2 -> step s2 t2 s3 -> step s3 t3 s4 -> t = t1 ** t2 ** t3 -> plus s1 t s4. Proof. intros. eapply plus_left; eauto. eapply star_two; eauto. Qed. Lemma plus_four: forall s1 t1 s2 t2 s3 t3 s4 t4 s5 t, step s1 t1 s2 -> step s2 t2 s3 -> step s3 t3 s4 -> step s4 t4 s5 -> t = t1 ** t2 ** t3 ** t4 -> plus s1 t s5. Proof. intros. eapply plus_left; eauto. eapply star_three; eauto. Qed. Lemma plus_star: forall s1 t s2, plus s1 t s2 -> star s1 t s2. Proof. intros. inversion H; subst. eapply star_step; eauto. Qed. Lemma plus_right: forall s1 t1 s2 t2 s3 t, star s1 t1 s2 -> step s2 t2 s3 -> t = t1 ** t2 -> plus s1 t s3. Proof. intros. inversion H; subst. simpl. apply plus_one. auto. rewrite Eapp_assoc. eapply plus_left; eauto. eapply star_right; eauto. Qed. Lemma plus_left': forall s1 t1 s2 t2 s3 t, step s1 t1 s2 -> plus s2 t2 s3 -> t = t1 ** t2 -> plus s1 t s3. Proof. intros. eapply plus_left; eauto. apply plus_star; auto. Qed. Lemma plus_right': forall s1 t1 s2 t2 s3 t, plus s1 t1 s2 -> step s2 t2 s3 -> t = t1 ** t2 -> plus s1 t s3. Proof. intros. eapply plus_right; eauto. apply plus_star; auto. Qed. Lemma plus_star_trans: forall s1 t1 s2 t2 s3 t, plus s1 t1 s2 -> star s2 t2 s3 -> t = t1 ** t2 -> plus s1 t s3. Proof. intros. inversion H; subst. econstructor; eauto. eapply star_trans; eauto. traceEq. Qed. Lemma star_plus_trans: forall s1 t1 s2 t2 s3 t, star s1 t1 s2 -> plus s2 t2 s3 -> t = t1 ** t2 -> plus s1 t s3. Proof. intros. inversion H; subst. simpl; auto. rewrite Eapp_assoc. econstructor. eauto. eapply star_trans. eauto. apply plus_star. eauto. eauto. auto. Qed. Lemma plus_trans: forall s1 t1 s2 t2 s3 t, plus s1 t1 s2 -> plus s2 t2 s3 -> t = t1 ** t2 -> plus s1 t s3. Proof. intros. eapply plus_star_trans. eauto. apply plus_star. eauto. auto. Qed. Lemma plus_inv: forall s1 t s2, plus s1 t s2 -> step s1 t s2 \/ exists s', exists t1, exists t2, step s1 t1 s' /\ plus s' t2 s2 /\ t = t1 ** t2. Proof. intros. inversion H; subst. inversion H1; subst. left. rewrite E0_right. auto. right. exists s3; exists t1; exists (t0 ** t3); split. auto. split. econstructor; eauto. auto. Qed. Lemma star_inv: forall s1 t s2, star s1 t s2 -> (s2 = s1 /\ t = E0) \/ plus s1 t s2. Proof. intros. inv H. left; auto. right; econstructor; eauto. Qed. Lemma plus_ind2: forall (P: state -> trace -> state -> Prop), (forall s1 t s2, step s1 t s2 -> P s1 t s2) -> (forall s1 t1 s2 t2 s3 t, step s1 t1 s2 -> plus s2 t2 s3 -> P s2 t2 s3 -> t = t1 ** t2 -> P s1 t s3) -> forall s1 t s2, plus s1 t s2 -> P s1 t s2. Proof. intros P BASE IND. assert (forall s1 t s2, star s1 t s2 -> forall s0 t0, step s0 t0 s1 -> P s0 (t0 ** t) s2). induction 1; intros. rewrite E0_right. apply BASE; auto. eapply IND. eauto. econstructor; eauto. subst t. eapply IHstar; eauto. auto. intros. inv H0. eauto. Qed. Lemma plus_E0_ind: forall (P: state -> state -> Prop), (forall s1 s2 s3, step s1 E0 s2 -> star s2 E0 s3 -> P s1 s3) -> forall s1 s2, plus s1 E0 s2 -> P s1 s2. Proof. intros. inv H0. exploit Eapp_E0_inv; eauto. intros [A B]; subst. eauto. Qed. (** Counted sequences of transitions *) Inductive starN : nat -> state -> trace -> state -> Prop := | starN_refl: forall s, starN O s E0 s | starN_step: forall n s t t1 s' t2 s'', step s t1 s' -> starN n s' t2 s'' -> t = t1 ** t2 -> starN (S n) s t s''. Remark starN_star: forall n s t s', starN n s t s' -> star s t s'. Proof. induction 1; econstructor; eauto. Qed. Remark star_starN: forall s t s', star s t s' -> exists n, starN n s t s'. Proof. induction 1. exists O; constructor. destruct IHstar as [n P]. exists (S n); econstructor; eauto. Qed. (** Infinitely many transitions *) CoInductive forever : state -> traceinf -> Prop := | forever_intro: forall s1 t s2 T, step s1 t s2 -> forever s2 T -> forever s1 (t *** T). Lemma star_forever: forall s1 t s2, star s1 t s2 -> forall T, forever s2 T -> forever s1 (t *** T). Proof. induction 1; intros. simpl. auto. subst t. rewrite Eappinf_assoc. econstructor; eauto. Qed. (** An alternate, equivalent definition of [forever] that is useful for coinductive reasoning. *) Variable A: Type. Variable order: A -> A -> Prop. CoInductive forever_N : A -> state -> traceinf -> Prop := | forever_N_star: forall s1 t s2 a1 a2 T1 T2, star s1 t s2 -> order a2 a1 -> forever_N a2 s2 T2 -> T1 = t *** T2 -> forever_N a1 s1 T1 | forever_N_plus: forall s1 t s2 a1 a2 T1 T2, plus s1 t s2 -> forever_N a2 s2 T2 -> T1 = t *** T2 -> forever_N a1 s1 T1. Hypothesis order_wf: well_founded order. Lemma forever_N_inv: forall a s T, forever_N a s T -> exists t, exists s', exists a', exists T', step s t s' /\ forever_N a' s' T' /\ T = t *** T'. Proof. intros a0. pattern a0. apply (well_founded_ind order_wf). intros. inv H0. (* star case *) inv H1. (* no transition *) change (E0 *** T2) with T2. apply H with a2. auto. auto. (* at least one transition *) exists t1; exists s0; exists x; exists (t2 *** T2). split. auto. split. eapply forever_N_star; eauto. apply Eappinf_assoc. (* plus case *) inv H1. exists t1; exists s0; exists a2; exists (t2 *** T2). split. auto. split. inv H3. auto. eapply forever_N_plus. econstructor; eauto. eauto. auto. apply Eappinf_assoc. Qed. Lemma forever_N_forever: forall a s T, forever_N a s T -> forever s T. Proof. cofix COINDHYP; intros. destruct (forever_N_inv H) as [t [s' [a' [T' [P [Q R]]]]]]. rewrite R. apply forever_intro with s'. auto. apply COINDHYP with a'; auto. Qed. (** Yet another alternative definition of [forever]. *) CoInductive forever_plus : state -> traceinf -> Prop := | forever_plus_intro: forall s1 t s2 T1 T2, plus s1 t s2 -> forever_plus s2 T2 -> T1 = t *** T2 -> forever_plus s1 T1. Lemma forever_plus_inv: forall s T, forever_plus s T -> exists s', exists t, exists T', step s t s' /\ forever_plus s' T' /\ T = t *** T'. Proof. intros. inv H. inv H0. exists s0; exists t1; exists (t2 *** T2). split. auto. split. exploit star_inv; eauto. intros [[P Q] | R]. subst. simpl. auto. econstructor; eauto. traceEq. Qed. Lemma forever_plus_forever: forall s T, forever_plus s T -> forever s T. Proof. cofix COINDHYP; intros. destruct (forever_plus_inv H) as [s' [t [T' [P [Q R]]]]]. subst. econstructor; eauto. Qed. (** Infinitely many silent transitions *) CoInductive forever_silent : state -> Prop := | forever_silent_intro: forall s1 s2, step s1 E0 s2 -> forever_silent s2 -> forever_silent s1. (** An alternate definition. *) CoInductive forever_silent_N : A -> state -> Prop := | forever_silent_N_star: forall s1 s2 a1 a2, star s1 E0 s2 -> order a2 a1 -> forever_silent_N a2 s2 -> forever_silent_N a1 s1 | forever_silent_N_plus: forall s1 s2 a1 a2, plus s1 E0 s2 -> forever_silent_N a2 s2 -> forever_silent_N a1 s1. Lemma forever_silent_N_inv: forall a s, forever_silent_N a s -> exists s', exists a', step s E0 s' /\ forever_silent_N a' s'. Proof. intros a0. pattern a0. apply (well_founded_ind order_wf). intros. inv H0. (* star case *) inv H1. (* no transition *) apply H with a2. auto. auto. (* at least one transition *) exploit Eapp_E0_inv; eauto. intros [P Q]. subst. exists s0; exists x. split. auto. eapply forever_silent_N_star; eauto. (* plus case *) inv H1. exploit Eapp_E0_inv; eauto. intros [P Q]. subst. exists s0; exists a2. split. auto. inv H3. auto. eapply forever_silent_N_plus. econstructor; eauto. eauto. Qed. Lemma forever_silent_N_forever: forall a s, forever_silent_N a s -> forever_silent s. Proof. cofix COINDHYP; intros. destruct (forever_silent_N_inv H) as [s' [a' [P Q]]]. apply forever_silent_intro with s'. auto. apply COINDHYP with a'; auto. Qed. (** Infinitely many non-silent transitions *) CoInductive forever_reactive : state -> traceinf -> Prop := | forever_reactive_intro: forall s1 s2 t T, star s1 t s2 -> t <> E0 -> forever_reactive s2 T -> forever_reactive s1 (t *** T). Lemma star_forever_reactive: forall s1 t s2 T, star s1 t s2 -> forever_reactive s2 T -> forever_reactive s1 (t *** T). Proof. intros. inv H0. rewrite <- Eappinf_assoc. econstructor. eapply star_trans; eauto. red; intro. exploit Eapp_E0_inv; eauto. intros [P Q]. contradiction. auto. Qed. End CLOSURES. (** * Transition semantics *) (** The general form of a transition semantics. *) Record part_semantics : Type := { state: Type; genvtype: Type; get_mem: state -> Memory.mem; set_mem: state -> Memory.mem -> state; step : state -> trace -> state -> Prop; entry_point: Memory.mem -> state -> val -> list val -> Prop; at_external : state -> option (external_function * list val); after_external : option val -> state -> Memory.mem -> option state; final_state: state -> int -> Prop; globalenv: genvtype; symbolenv: Senv.t (*TODO: External call states must exectue the function in one step*) (* Need to see what the hybrid machine needs. *) (*external_step_lemma: forall g s1 ef args t s2, at_external g s1 = Some (ef, args) -> step sem g s1 t s2 -> exists vr, external_call ef (symbolenv sem) args (get_mem s1) t (Val.maketotal vr) (get_mem s2) /\ after_external g vr (set_mem s1 (get_mem s2)) = Some s2 *) }. Arguments get_mem {_} _. Arguments set_mem {_} _ _. (* Full semantics are for closed, complete programs. *) (* It contains a main function and an inital_mem *) Record semantics : Type := { part_sem:> part_semantics; main_block: option block; (*location of main.*) init_mem: option Memory.mem }. (*We can recover initial_states from entry_point *) Inductive initial_state (sem:semantics): state sem -> Prop := | initial_state_derived_intro': forall st0 m0 b, init_mem sem = Some m0 -> (main_block sem) = Some b -> entry_point sem m0 st0 (Vptr b (Ptrofs.zero)) nil -> initial_state sem st0. (** The form used in earlier CompCert versions, for backward compatibility. *) Definition Semantics {state funtype vartype: Type} (get_mem: state -> Memory.mem) (set_mem: state -> Memory.mem -> state) (step: state -> trace -> state -> Prop) (entry_point: Memory.mem -> state -> val -> list val -> Prop) (at_external : state -> option (external_function * list val)) (after_external : option val -> state -> Memory.mem -> option state) (final_state: state -> int -> Prop) (globalenv: Genv.t funtype vartype) (main_block: option block) (init_mem: option Memory.mem):= Build_semantics {| state := state; genvtype := Genv.t funtype vartype; get_mem:= get_mem; set_mem:= set_mem; step := step; entry_point := entry_point; at_external := at_external; after_external := after_external; final_state := final_state; globalenv := globalenv; symbolenv := Genv.to_senv globalenv |} main_block init_mem. Definition Semantics_gen (state genvtype: Type) (get_mem: state -> Memory.mem) (set_mem: state -> Memory.mem -> state) (step: state -> trace -> state -> Prop) (entry_point: Memory.mem -> state -> val -> list val -> Prop) (at_external : state -> option (external_function * list val)) (after_external : option val -> state -> Memory.mem -> option state) (final_state: state -> int -> Prop) (globalenv: genvtype) (main_block: option block) (init_mem: option Memory.mem) (symbolenv: Senv.t):= Build_semantics {| state := state; genvtype := genvtype; get_mem:= get_mem; set_mem:= set_mem; step := step; entry_point := entry_point; at_external := at_external; after_external := after_external; final_state := final_state; globalenv := globalenv; symbolenv := symbolenv |} main_block init_mem. (** Handy notations. *) Notation " 'Step' L " := (step L) (at level 1) : smallstep_scope. Notation " 'Star' L " := (star (step L)) (at level 1) : smallstep_scope. Notation " 'Plus' L " := (plus (step L)) (at level 1) : smallstep_scope. Notation " 'Forever_silent' L " := (forever_silent (step L)) (at level 1) : smallstep_scope. Notation " 'Forever_reactive' L " := (forever_reactive (step L)) (at level 1) : smallstep_scope. Notation " 'Nostep' L " := (nostep (step L)) (at level 1) : smallstep_scope. Open Scope smallstep_scope. (** * Forward simulations between two transition semantics. *) (*Following definition mimics *_not_fresh lemmas from common/Globalenvs.v*) (* genv_next bounds all global blocks *) (* This should be part of GENV file? *) Definition globals_not_fresh {F V} (ge:Genv.t F V) m:= Ple (Genv.genv_next ge) (Mem.nextblock m). Lemma len_defs_genv_next: forall {F1 V1 F2 V2} (p1:AST.program F1 V1) (p2:AST.program F2 V2), length (AST.prog_defs p1) =length (AST.prog_defs p2) -> Genv.genv_next (Genv.globalenv p1) = Genv.genv_next (Genv.globalenv p2). Proof. intros. unfold Genv.globalenv. do 2 rewrite Genv.genv_next_add_globals. remember (Genv.empty_genv F1 V1 (AST.prog_public p1)) as base1. remember (Genv.empty_genv F2 V2 (AST.prog_public p2)) as base2. replace (Genv.genv_next base1) with (Genv.genv_next base2) by (subst; reflexivity). remember (Genv.genv_next base2) as X. remember (AST.prog_defs p1) as ls1. remember (AST.prog_defs p2) as ls2. generalize X ls2 H. clear. induction ls1. - intros; destruct ls2; inversion H; auto. - intros. destruct ls2; inversion H; auto. simpl. eapply IHls1; auto. Qed. Lemma globals_not_fresh_preserve: forall {F1 V1 F2 V2} (p1:AST.program F1 V1) (p2:AST.program F2 V2), length (AST.prog_defs p1) = length (AST.prog_defs p2) -> forall m0, globals_not_fresh (Genv.globalenv p1) m0 -> globals_not_fresh (Genv.globalenv p2) m0. Proof. unfold globals_not_fresh; intros until m0. erewrite len_defs_genv_next; eauto. Qed. Section ForwardSimulations. Context (L1 L2: semantics). (** The general form of a forward simulation. *) (** NEW: I will tolerate the duplication of entry_points/initial_states, while we find a better abstraction. *) Record fsim_properties (index: Type) (order: index -> index -> Prop) (match_states: index -> state L1 -> state L2 -> Prop) : Prop := { fsim_order_wf: well_founded order; fsim_match_entry_points: forall s1 f arg m0, entry_point L1 m0 s1 f arg -> exists i, exists s2, entry_point L2 m0 s2 f arg /\ match_states i s1 s2; fsim_match_initial_states: forall s1, initial_state L1 s1 -> exists i, exists s2, initial_state L2 s2 /\ match_states i s1 s2; fsim_match_final_states: forall i s1 s2 r, match_states i s1 s2 -> final_state L1 s1 r -> final_state L2 s2 r; fsim_simulation: forall s1 t s1', Step L1 s1 t s1' -> forall i s2, match_states i s1 s2 -> exists i', exists s2', (Plus L2 s2 t s2' \/ (Star L2 s2 t s2' /\ order i' i)) /\ match_states i' s1' s2'; fsim_public_preserved: forall id, Senv.public_symbol (symbolenv L2) id = Senv.public_symbol (symbolenv L1) id }. (*In the case where initial_memories are equal, initial_states follows from entry_points. *) Lemma init_states_from_entry_index: forall (INIT_MEM: forall m, init_mem L1 = Some m -> init_mem L2 = Some m) (INIT_BLOCK: main_block L1 = main_block L2), forall index match_states (fsim_match_entry_points: forall (s1:state L1) f arg m0, entry_point L1 m0 s1 f arg -> exists i, exists s2, entry_point L2 m0 s2 f arg /\ match_states i s1 s2), forall s1, initial_state L1 s1 -> exists (i:index), exists s2, initial_state L2 s2 /\ match_states i s1 s2. Proof. intros. inv H. rewrite INIT_BLOCK in *. eapply fsim_match_entry_points0 in H2. destruct H2 as (i&s2&init_core&MATCH). exists i, s2; split; eauto. econstructor; eauto. Qed. Lemma init_states_from_entry: forall (INIT_MEM: forall m, init_mem L1 = Some m -> init_mem L2 = Some m) (INIT_BLOCK: main_block L1 = main_block L2), forall match_states (fsim_match_entry_points: forall (s1:state L1) f arg m0, entry_point L1 m0 s1 f arg -> exists s2, entry_point L2 m0 s2 f arg /\ match_states s1 s2), forall s1, initial_state L1 s1 -> exists s2, initial_state L2 s2 /\ match_states s1 s2. Proof. intros. inv H. rewrite INIT_BLOCK in *. eapply fsim_match_entry_points0 in H2. destruct H2 as (s2&init_core&MATCH). exists s2; split; eauto. econstructor; eauto. Qed. End ForwardSimulations. Arguments fsim_properties: clear implicits. Inductive forward_simulation (L1 L2: semantics) : Prop := Forward_simulation (index: Type) (order: index -> index -> Prop) (match_states: index -> state L1 -> state L2 -> Prop) (props: fsim_properties L1 L2 index order match_states). Arguments Forward_simulation {L1 L2 index} order match_states props. (** An alternate form of the simulation diagram *) Lemma fsim_simulation': forall L1 L2 index order match_states, fsim_properties L1 L2 index order match_states -> forall i s1 t s1', Step L1 s1 t s1' -> forall s2, match_states i s1 s2 -> (exists i', exists s2', Plus L2 s2 t s2' /\ match_states i' s1' s2') \/ (exists i', order i' i /\ t = E0 /\ match_states i' s1' s2). Proof. intros. exploit fsim_simulation; eauto. intros [i' [s2' [A B]]]. intuition. left; exists i'; exists s2'; auto. inv H3. right; exists i'; auto. left; exists i'; exists s2'; split; auto. econstructor; eauto. Qed. (** ** Forward simulation diagrams. *) (** Various simulation diagrams that imply forward simulation *) Section FORWARD_SIMU_DIAGRAMS. Variable L1: semantics. Variable L2: semantics. Hypothesis public_preserved: forall id, Senv.public_symbol (symbolenv L2) id = Senv.public_symbol (symbolenv L1) id. Variable match_states: state L1 -> state L2 -> Prop. Hypothesis match_entry_points: forall s1 f arg m0, entry_point L1 m0 s1 f arg -> exists s2, entry_point L2 m0 s2 f arg /\ match_states s1 s2. Hypothesis match_initial_states: forall s1, initial_state L1 s1 -> exists s2, initial_state L2 s2 /\ match_states s1 s2. Hypothesis match_final_states: forall s1 s2 r, match_states s1 s2 -> final_state L1 s1 r -> final_state L2 s2 r. (** Simulation when one transition in the first program corresponds to zero, one or several transitions in the second program. However, there is no stuttering: infinitely many transitions in the source program must correspond to infinitely many transitions in the second program. *) Section SIMULATION_STAR_WF. (** [order] is a well-founded ordering associated with states of the first semantics. Stuttering steps must correspond to states that decrease w.r.t. [order]. *) Variable order: state L1 -> state L1 -> Prop. Hypothesis order_wf: well_founded order. Hypothesis simulation: forall s1 t s1', Step L1 s1 t s1' -> forall s2, match_states s1 s2 -> exists s2', (Plus L2 s2 t s2' \/ (Star L2 s2 t s2' /\ order s1' s1)) /\ match_states s1' s2'. Lemma forward_simulation_star_wf: forward_simulation L1 L2. Proof. apply Forward_simulation with order (fun idx s1 s2 => idx = s1 /\ match_states s1 s2); constructor. - auto. - intros. exploit match_entry_points; eauto. intros [s2 [A B]]. exists s1; exists s2; repeat (split; auto). - intros. exploit match_initial_states; eauto. intros [s2 [A B]]. exists s1; exists s2; repeat (split; auto). - intros. destruct H. eapply match_final_states; eauto. - intros. destruct H0. subst i. exploit simulation; eauto. intros [s2' [A B]]. exists s1'; exists s2'; intuition auto. - auto. Qed. Notation match_states':= (fun (idx s1 : state L1) (s2 : state L2) => idx = s1 /\ match_states s1 s2). Lemma fsim_properties_star_wf: fsim_properties L1 L2 _ order match_states'. Proof. constructor. - auto. - intros. exploit match_entry_points; eauto. intros [s2 [A B]]. exists s1; exists s2; auto. - intros. exploit match_initial_states; eauto. intros [s2 [A B]]. exists s1; exists s2; auto. - intros. destruct H. eapply match_final_states; eauto. - intros. destruct H0. subst i. exploit simulation; eauto. intros [s2' [A B]]. exists s1'; exists s2'; intuition auto. - auto. Qed. End SIMULATION_STAR_WF. Section SIMULATION_STAR. (** We now consider the case where we have a nonnegative integer measure associated with states of the first semantics. It must decrease when we take a stuttering step. *) Variable measure: state L1 -> nat. Hypothesis simulation: forall s1 t s1', Step L1 s1 t s1' -> forall s2, match_states s1 s2 -> (exists s2', Plus L2 s2 t s2' /\ match_states s1' s2') \/ (measure s1' < measure s1 /\ t = E0 /\ match_states s1' s2)%nat. Lemma forward_simulation_star: forward_simulation L1 L2. Proof. apply forward_simulation_star_wf with (ltof _ measure). apply well_founded_ltof. intros. exploit simulation; eauto. intros [[s2' [A B]] | [A [B C]]]. exists s2'; auto. exists s2; split. right; split. rewrite B. apply star_refl. auto. auto. Qed. Lemma fsim_properties_star: fsim_properties L1 L2 _ (ltof _ measure) (fun (idx s1 : state L1) (s2 : state L2) => idx = s1 /\ match_states s1 s2). Proof. apply fsim_properties_star_wf. apply well_founded_ltof. intros. exploit simulation; eauto. intros [[s2' [A B]] | [A [B C]]]. exists s2'; auto. exists s2; split. right; split. rewrite B. apply star_refl. auto. auto. Qed. End SIMULATION_STAR. (** Simulation when one transition in the first program corresponds to one or several transitions in the second program. *) Section SIMULATION_PLUS. Hypothesis simulation: forall s1 t s1', Step L1 s1 t s1' -> forall s2, match_states s1 s2 -> exists s2', Plus L2 s2 t s2' /\ match_states s1' s2'. Lemma forward_simulation_plus: forward_simulation L1 L2. Proof. apply forward_simulation_star with (measure := fun _ => O). intros. exploit simulation; eauto. Qed. Lemma fsim_properties_plus: fsim_properties L1 L2 _ (ltof _ ( fun _ => O)) (fun (idx s1 : state L1) (s2 : state L2) => idx = s1 /\ match_states s1 s2). Proof. apply fsim_properties_star with (measure := fun _ => O). intros. exploit simulation; eauto. Qed. End SIMULATION_PLUS. (** Lock-step simulation: each transition in the first semantics corresponds to exactly one transition in the second semantics. *) Section SIMULATION_STEP. Hypothesis simulation: forall s1 t s1', Step L1 s1 t s1' -> forall s2, match_states s1 s2 -> exists s2', Step L2 s2 t s2' /\ match_states s1' s2'. Lemma forward_simulation_step: forward_simulation L1 L2. Proof. apply forward_simulation_plus. intros. exploit simulation; eauto. intros [s2' [A B]]. exists s2'; split; auto. apply plus_one; auto. Qed. Lemma fsim_properties_step: fsim_properties L1 L2 _ (ltof _ ( fun _ => O)) (fun (idx s1 : state L1) (s2 : state L2) => idx = s1 /\ match_states s1 s2). Proof. apply fsim_properties_plus. intros. exploit simulation; eauto. intros [s2' [A B]]. exists s2'; split; auto. apply plus_one; auto. Qed. End SIMULATION_STEP. (** Simulation when one transition in the first program corresponds to zero or one transitions in the second program. However, there is no stuttering: infinitely many transitions in the source program must correspond to infinitely many transitions in the second program. *) Section SIMULATION_OPT. Variable measure: state L1 -> nat. Hypothesis simulation: forall s1 t s1', Step L1 s1 t s1' -> forall s2, match_states s1 s2 -> (exists s2', Step L2 s2 t s2' /\ match_states s1' s2') \/ (measure s1' < measure s1 /\ t = E0 /\ match_states s1' s2)%nat. Lemma forward_simulation_opt: forward_simulation L1 L2. Proof. apply forward_simulation_star with measure. intros. exploit simulation; eauto. intros [[s2' [A B]] | [A [B C]]]. left; exists s2'; split; auto. apply plus_one; auto. right; auto. Qed. Lemma fsim_properties_opt: fsim_properties L1 L2 _ (ltof _ measure) (fun (idx s1 : state L1) (s2 : state L2) => idx = s1 /\ match_states s1 s2). Proof. apply fsim_properties_star. intros. exploit simulation; eauto. intros [[s2' [A B]] | [A [B C]]]. left; exists s2'; split; auto. apply plus_one; auto. right; auto. Qed. End SIMULATION_OPT. End FORWARD_SIMU_DIAGRAMS. (** ** Forward simulation of transition sequences *) Section SIMULATION_SEQUENCES. Context L1 L2 index order match_states (S: fsim_properties L1 L2 index order match_states). Lemma simulation_star: forall s1 t s1', Star L1 s1 t s1' -> forall i s2, match_states i s1 s2 -> exists i', exists s2', Star L2 s2 t s2' /\ match_states i' s1' s2'. Proof. induction 1; intros. exists i; exists s2; split; auto. apply star_refl. exploit fsim_simulation; eauto. intros [i' [s2' [A B]]]. exploit IHstar; eauto. intros [i'' [s2'' [C D]]]. exists i''; exists s2''; split; auto. eapply star_trans; eauto. intuition auto. apply plus_star; auto. Qed. Lemma simulation_plus: forall s1 t s1', Plus L1 s1 t s1' -> forall i s2, match_states i s1 s2 -> (exists i', exists s2', Plus L2 s2 t s2' /\ match_states i' s1' s2') \/ (exists i', clos_trans _ order i' i /\ t = E0 /\ match_states i' s1' s2). Proof. induction 1 using plus_ind2; intros. (* base case *) exploit fsim_simulation'; eauto. intros [A | [i' A]]. left; auto. right; exists i'; intuition. (* inductive case *) exploit fsim_simulation'; eauto. intros [[i' [s2' [A B]]] | [i' [A [B C]]]]. exploit simulation_star. apply plus_star; eauto. eauto. intros [i'' [s2'' [P Q]]]. left; exists i''; exists s2''; split; auto. eapply plus_star_trans; eauto. exploit IHplus; eauto. intros [[i'' [s2'' [P Q]]] | [i'' [P [Q R]]]]. subst. simpl. left; exists i''; exists s2''; auto. subst. simpl. right; exists i''; intuition auto. eapply t_trans; eauto. eapply t_step; eauto. Qed. Lemma simulation_forever_silent: forall i s1 s2, Forever_silent L1 s1 -> match_states i s1 s2 -> Forever_silent L2 s2. Proof. assert (forall i s1 s2, Forever_silent L1 s1 -> match_states i s1 s2 -> forever_silent_N (step L2) order i s2). cofix COINDHYP; intros. inv H. destruct (fsim_simulation S _ _ _ H1 _ _ H0) as [i' [s2' [A B]]]. destruct A as [C | [C D]]. eapply forever_silent_N_plus; eauto. eapply forever_silent_N_star; eauto. intros. eapply forever_silent_N_forever; eauto. eapply fsim_order_wf; eauto. Qed. Lemma simulation_forever_reactive: forall i s1 s2 T, Forever_reactive L1 s1 T -> match_states i s1 s2 -> Forever_reactive L2 s2 T. Proof. cofix COINDHYP; intros. inv H. edestruct simulation_star as [i' [st2' [A B]]]; eauto. econstructor; eauto. Qed. End SIMULATION_SEQUENCES. (** ** Composing two forward simulations *) Ltac supertransitivity:= repeat match goal with |[|- ?x = ?y] => match goal with | [|- x = x] => reflexivity | [ H: x = _ |- _ ] => rewrite H in *; clear H | [ H: _ = x |- _ ] => rewrite H in *; clear H end end. Lemma compose_forward_simulations: forall L1 L2 L3, forward_simulation L1 L2 -> forward_simulation L2 L3 -> forward_simulation L1 L3. Proof. intros L1 L2 L3 S12 S23. destruct S12 as [index order match_states props]. destruct S23 as [index' order' match_states' props']. set (ff_index := (index' * index)%type). set (ff_order := lex_ord (clos_trans _ order') order). set (ff_match_states := fun (i: ff_index) (s1: state L1) (s3: state L3) => exists s2, match_states (snd i) s1 s2 /\ match_states' (fst i) s2 s3). apply Forward_simulation with ff_order ff_match_states; constructor. - (* well founded *) unfold ff_order. apply wf_lex_ord. apply wf_clos_trans. eapply fsim_order_wf; eauto. eapply fsim_order_wf; eauto. - (* initial cores *) intros. exploit (fsim_match_entry_points props); eauto. intros [i [s2 [A B]]]. exploit (fsim_match_entry_points props'); eauto. intros [i' [s3 [C D]]]. exists (i', i); exists s3; repeat(split; auto). supertransitivity. exists s2; auto. - (* initial states *) intros. exploit (fsim_match_initial_states props); eauto. intros [i [s2 [A B]]]. exploit (fsim_match_initial_states props'); eauto. intros [i' [s3 [C D]]]. exists (i', i); exists s3; repeat(split; auto). exists s2; auto. - (* final states *) intros. destruct H as [s3 [A B]]. eapply (fsim_match_final_states props'); eauto. eapply (fsim_match_final_states props); eauto. - (* simulation *) intros. destruct H0 as [s3 [A B]]. destruct i as [i2 i1]; simpl in *. exploit (fsim_simulation' props); eauto. intros [[i1' [s3' [C D]]] | [i1' [C [D E]]]]. + (* L2 makes one or several steps. *) exploit simulation_plus; eauto. intros [[i2' [s2' [P Q]]] | [i2' [P [Q R]]]]. * (* L3 makes one or several steps *) exists (i2', i1'); exists s2'; split. auto. exists s3'; auto. * (* L3 makes no step *) exists (i2', i1'); exists s2; split. right; split. subst t; apply star_refl. red. left. auto. exists s3'; auto. + (* L2 makes no step *) exists (i2, i1'); exists s2; split. right; split. subst t; apply star_refl. red. right. auto. exists s3; auto. - (* symbols *) intros. transitivity (Senv.public_symbol (symbolenv L2) id); eapply fsim_public_preserved; eauto. Qed. (** * Receptiveness and determinacy *) Definition single_events (L: semantics) : Prop := forall s t s', Step L s t s' -> (length t <= 1)%nat. Record receptive (L: semantics) : Prop := Receptive { sr_receptive: forall s t1 s1 t2, Step L s t1 s1 -> match_traces (symbolenv L) t1 t2 -> exists s2, Step L s t2 s2; sr_traces: single_events L }. Record determinate (L: semantics) : Prop := Determinate { sd_determ: forall s t1 s1 t2 s2, Step L s t1 s1 -> Step L s t2 s2 -> match_traces (symbolenv L) t1 t2 /\ (t1 = t2 -> s1 = s2); sd_traces: single_events L; sd_initial_determ: forall s1 s2 f arg m0, entry_point L m0 s1 f arg -> entry_point L m0 s2 f arg -> s1 = s2; sd_final_nostep: forall s r, final_state L s r -> Nostep L s; sd_final_determ: forall s r1 r2, final_state L s r1 -> final_state L s r2 -> r1 = r2 }. Lemma sd_initial_state_determ: forall L, determinate L -> forall s1 s2, initial_state L s1 -> initial_state L s2 -> s1 = s2. Proof. intros. inv H0; inv H1. eapply sd_initial_determ; eauto. rewrite H3 in H5; inv H5. rewrite H2 in H0; inv H0; auto. Qed. Section DETERMINACY. Variable L: semantics. Hypothesis DET: determinate L. Lemma sd_determ_1: forall s t1 s1 t2 s2, Step L s t1 s1 -> Step L s t2 s2 -> match_traces (symbolenv L) t1 t2. Proof. intros. eapply sd_determ; eauto. Qed. Lemma sd_determ_2: forall s t s1 s2, Step L s t s1 -> Step L s t s2 -> s1 = s2. Proof. intros. eapply sd_determ; eauto. Qed. Lemma star_determinacy: forall s t s', Star L s t s' -> forall s'', Star L s t s'' -> Star L s' E0 s'' \/ Star L s'' E0 s'. Proof. induction 1; intros. auto. inv H2. right. eapply star_step; eauto. exploit sd_determ_1. eexact H. eexact H3. intros MT. exploit (sd_traces DET). eexact H. intros L1. exploit (sd_traces DET). eexact H3. intros L2. assert (t1 = t0 /\ t2 = t3). destruct t1. inv MT. auto. destruct t1; simpl in L1; try omegaContradiction. destruct t0. inv MT. destruct t0; simpl in L2; try omegaContradiction. simpl in H5. split. congruence. congruence. destruct H1; subst. assert (s2 = s4) by (eapply sd_determ_2; eauto). subst s4. auto. Qed. End DETERMINACY. (** * Backward simulations between two transition semantics. *) Definition safe (L: semantics) (s: state L) : Prop := forall s', Star L s E0 s' -> (exists r, final_state L s' r) \/ (exists t, exists s'', Step L s' t s''). Lemma star_safe: forall (L: semantics) s s', Star L s E0 s' -> safe L s -> safe L s'. Proof. intros; red; intros. apply H0. eapply star_trans; eauto. Qed. (** The general form of a backward simulation. *) Record bsim_properties (L1 L2: semantics) (index: Type) (order: index -> index -> Prop) (match_states: index -> state L1 -> state L2 -> Prop) : Prop := { bsim_order_wf: well_founded order; bsim_entry_points_exist: forall s1 f arg m0, entry_point L1 m0 s1 f arg -> exists s2, entry_point L2 m0 s2 f arg; bsim_initial_states_exist: forall s1, initial_state L1 s1 -> exists s2, initial_state L2 s2; bsim_match_entry_points: forall s1 s2 f arg m0, entry_point L1 m0 s1 f arg -> entry_point L2 m0 s2 f arg -> exists i, exists s1', entry_point L1 m0 s1' f arg /\ match_states i s1' s2; bsim_match_initial_states: forall s1 s2, initial_state L1 s1 -> initial_state L2 s2 -> exists i, exists s1', initial_state L1 s1' /\ match_states i s1' s2; bsim_match_final_states: forall i s1 s2 r, match_states i s1 s2 -> safe L1 s1 -> final_state L2 s2 r -> exists s1', Star L1 s1 E0 s1' /\ final_state L1 s1' r; bsim_progress: forall i s1 s2, match_states i s1 s2 -> safe L1 s1 -> (exists r, final_state L2 s2 r) \/ (exists t, exists s2', Step L2 s2 t s2'); bsim_simulation: forall s2 t s2', Step L2 s2 t s2' -> forall i s1, match_states i s1 s2 -> safe L1 s1 -> exists i', exists s1', (Plus L1 s1 t s1' \/ (Star L1 s1 t s1' /\ order i' i)) /\ match_states i' s1' s2'; bsim_public_preserved: forall id, Senv.public_symbol (symbolenv L2) id = Senv.public_symbol (symbolenv L1) id }. Arguments bsim_properties: clear implicits. Inductive backward_simulation (L1 L2: semantics) : Prop := Backward_simulation (index: Type) (order: index -> index -> Prop) (match_states: index -> state L1 -> state L2 -> Prop) (props: bsim_properties L1 L2 index order match_states). Arguments Backward_simulation {L1 L2 index} order match_states props. (** An alternate form of the simulation diagram *) Lemma bsim_simulation': forall L1 L2 index order match_states, bsim_properties L1 L2 index order match_states -> forall i s2 t s2', Step L2 s2 t s2' -> forall s1, match_states i s1 s2 -> safe L1 s1 -> (exists i', exists s1', Plus L1 s1 t s1' /\ match_states i' s1' s2') \/ (exists i', order i' i /\ t = E0 /\ match_states i' s1 s2'). Proof. intros. exploit bsim_simulation; eauto. intros [i' [s1' [A B]]]. intuition. left; exists i'; exists s1'; auto. inv H4. right; exists i'; auto. left; exists i'; exists s1'; split; auto. econstructor; eauto. Qed. (** ** Backward simulation diagrams. *) (** Various simulation diagrams that imply backward simulation. *) Section BACKWARD_SIMU_DIAGRAMS. Variable L1: semantics. Variable L2: semantics. Hypothesis public_preserved: forall id, Senv.public_symbol (symbolenv L2) id = Senv.public_symbol (symbolenv L1) id. Variable match_states: state L1 -> state L2 -> Prop. Hypothesis entry_points_exist: forall s1 f arg m0, entry_point L1 m0 s1 f arg -> exists s2, entry_point L2 m0 s2 f arg. Hypothesis initial_states_exist: forall s1, initial_state L1 s1 -> exists s2, initial_state L2 s2. Hypothesis match_entry_points: forall s1 s2 f arg m0, entry_point L1 m0 s1 f arg -> entry_point L2 m0 s2 f arg -> exists s1', entry_point L1 m0 s1' f arg /\ match_states s1' s2. Hypothesis match_initial_state: forall s1 s2, initial_state L1 s1 -> initial_state L2 s2 -> exists s1', initial_state L1 s1' /\ match_states s1' s2. Hypothesis match_final_states: forall s1 s2 r, match_states s1 s2 -> final_state L2 s2 r -> final_state L1 s1 r. Hypothesis progress: forall s1 s2, match_states s1 s2 -> safe L1 s1 -> (exists r, final_state L2 s2 r) \/ (exists t, exists s2', Step L2 s2 t s2'). Section BACKWARD_SIMULATION_PLUS. Hypothesis simulation: forall s2 t s2', Step L2 s2 t s2' -> forall s1, match_states s1 s2 -> safe L1 s1 -> exists s1', Plus L1 s1 t s1' /\ match_states s1' s2'. Lemma backward_simulation_plus: backward_simulation L1 L2. Proof. apply Backward_simulation with (fun (x y: unit) => False) (fun (i: unit) s1 s2 => match_states s1 s2); constructor; auto. - red; intros; constructor; intros. contradiction. - intros. exists tt; eauto. - intros. exists tt; eauto. - intros. exists s1; split. apply star_refl. eauto. - intros. exploit simulation; eauto. intros [s1' [A B]]. exists tt; exists s1'; auto. Qed. End BACKWARD_SIMULATION_PLUS. End BACKWARD_SIMU_DIAGRAMS. (** ** Backward simulation of transition sequences *) Section BACKWARD_SIMULATION_SEQUENCES. Context L1 L2 index order match_states (S: bsim_properties L1 L2 index order match_states). Lemma bsim_E0_star: forall s2 s2', Star L2 s2 E0 s2' -> forall i s1, match_states i s1 s2 -> safe L1 s1 -> exists i', exists s1', Star L1 s1 E0 s1' /\ match_states i' s1' s2'. Proof. intros s20 s20' STAR0. pattern s20, s20'. eapply star_E0_ind; eauto. - (* base case *) intros. exists i; exists s1; split; auto. apply star_refl. - (* inductive case *) intros. exploit bsim_simulation; eauto. intros [i' [s1' [A B]]]. assert (Star L1 s0 E0 s1'). intuition. apply plus_star; auto. exploit H0. eauto. eapply star_safe; eauto. intros [i'' [s1'' [C D]]]. exists i''; exists s1''; split; auto. eapply star_trans; eauto. Qed. Lemma bsim_safe: forall i s1 s2, match_states i s1 s2 -> safe L1 s1 -> safe L2 s2. Proof. intros; red; intros. exploit bsim_E0_star; eauto. intros [i' [s1' [A B]]]. eapply bsim_progress; eauto. eapply star_safe; eauto. Qed. Lemma bsim_E0_plus: forall s2 t s2', Plus L2 s2 t s2' -> t = E0 -> forall i s1, match_states i s1 s2 -> safe L1 s1 -> (exists i', exists s1', Plus L1 s1 E0 s1' /\ match_states i' s1' s2') \/ (exists i', clos_trans _ order i' i /\ match_states i' s1 s2'). Proof. induction 1 using plus_ind2; intros; subst t. - (* base case *) exploit bsim_simulation'; eauto. intros [[i' [s1' [A B]]] | [i' [A [B C]]]]. + left; exists i'; exists s1'; auto. + right; exists i'; intuition. - (* inductive case *) exploit Eapp_E0_inv; eauto. intros [EQ1 EQ2]; subst. exploit bsim_simulation'; eauto. intros [[i' [s1' [A B]]] | [i' [A [B C]]]]. + exploit bsim_E0_star. apply plus_star; eauto. eauto. eapply star_safe; eauto. apply plus_star; auto. intros [i'' [s1'' [P Q]]]. left; exists i''; exists s1''; intuition. eapply plus_star_trans; eauto. + exploit IHplus; eauto. intros [P | [i'' [P Q]]]. left; auto. right; exists i''; intuition. eapply t_trans; eauto. apply t_step; auto. Qed. Lemma star_non_E0_split: forall s2 t s2', Star L2 s2 t s2' -> (length t = 1)%nat -> exists s2x, exists s2y, Star L2 s2 E0 s2x /\ Step L2 s2x t s2y /\ Star L2 s2y E0 s2'. Proof. induction 1; intros. simpl in H; discriminate. subst t. assert (EITHER: t1 = E0 \/ t2 = E0). unfold Eapp in H2; rewrite app_length in H2. destruct t1; auto. destruct t2; auto. simpl in H2; omegaContradiction. destruct EITHER; subst. exploit IHstar; eauto. intros [s2x [s2y [A [B C]]]]. exists s2x; exists s2y; intuition. eapply star_left; eauto. rewrite E0_right. exists s1; exists s2; intuition. apply star_refl. Qed. End BACKWARD_SIMULATION_SEQUENCES. (** ** Composing two backward simulations *) Section COMPOSE_BACKWARD_SIMULATIONS. Variable L1: semantics. Variable L2: semantics. Variable L3: semantics. Hypothesis L3_single_events: single_events L3. Context index order match_states (S12: bsim_properties L1 L2 index order match_states). Context index' order' match_states' (S23: bsim_properties L2 L3 index' order' match_states'). Let bb_index : Type := (index * index')%type. Definition bb_order : bb_index -> bb_index -> Prop := lex_ord (clos_trans _ order) order'. Inductive bb_match_states: bb_index -> state L1 -> state L3 -> Prop := | bb_match_later: forall i1 i2 s1 s3 s2x s2y, match_states i1 s1 s2x -> Star L2 s2x E0 s2y -> match_states' i2 s2y s3 -> bb_match_states (i1, i2) s1 s3. Lemma bb_match_at: forall i1 i2 s1 s3 s2, match_states i1 s1 s2 -> match_states' i2 s2 s3 -> bb_match_states (i1, i2) s1 s3. Proof. intros. econstructor; eauto. apply star_refl. Qed. Lemma bb_simulation_base: forall s3 t s3', Step L3 s3 t s3' -> forall i1 s1 i2 s2, match_states i1 s1 s2 -> match_states' i2 s2 s3 -> safe L1 s1 -> exists i', exists s1', (Plus L1 s1 t s1' \/ (Star L1 s1 t s1' /\ bb_order i' (i1, i2))) /\ bb_match_states i' s1' s3'. Proof. intros. exploit (bsim_simulation' S23); eauto. eapply bsim_safe; eauto. intros [ [i2' [s2' [PLUS2 MATCH2]]] | [i2' [ORD2 [EQ MATCH2]]]]. - (* 1 L2 makes one or several transitions *) assert (EITHER: t = E0 \/ (length t = 1)%nat). { exploit L3_single_events; eauto. destruct t; auto. destruct t; auto. simpl. intros. omegaContradiction. } destruct EITHER. + (* 1.1 these are silent transitions *) subst t. exploit (bsim_E0_plus S12); eauto. intros [ [i1' [s1' [PLUS1 MATCH1]]] | [i1' [ORD1 MATCH1]]]. * (* 1.1.1 L1 makes one or several transitions *) exists (i1', i2'); exists s1'; split. auto. eapply bb_match_at; eauto. * (* 1.1.2 L1 makes no transitions *) exists (i1', i2'); exists s1; split. right; split. apply star_refl. left; auto. eapply bb_match_at; eauto. + (* 1.2 non-silent transitions *) exploit star_non_E0_split. apply plus_star; eauto. auto. intros [s2x [s2y [P [Q R]]]]. exploit (bsim_E0_star S12). eexact P. eauto. auto. intros [i1' [s1x [X Y]]]. exploit (bsim_simulation' S12). eexact Q. eauto. eapply star_safe; eauto. intros [[i1'' [s1y [U V]]] | [i1'' [U [V W]]]]; try (subst t; discriminate). exists (i1'', i2'); exists s1y; split. left. eapply star_plus_trans; eauto. eapply bb_match_later; eauto. - (* 2. L2 makes no transitions *) subst. exists (i1, i2'); exists s1; split. right; split. apply star_refl. right; auto. eapply bb_match_at; eauto. Qed. Lemma bb_simulation: forall s3 t s3', Step L3 s3 t s3' -> forall i s1, bb_match_states i s1 s3 -> safe L1 s1 -> exists i', exists s1', (Plus L1 s1 t s1' \/ (Star L1 s1 t s1' /\ bb_order i' i)) /\ bb_match_states i' s1' s3'. Proof. intros. inv H0. exploit star_inv; eauto. intros [[EQ1 EQ2] | PLUS]. - (* 1. match at *) subst. eapply bb_simulation_base; eauto. - (* 2. match later *) exploit (bsim_E0_plus S12); eauto. intros [[i1' [s1' [A B]]] | [i1' [A B]]]. + (* 2.1 one or several silent transitions *) exploit bb_simulation_base. eauto. auto. eexact B. eauto. eapply star_safe; eauto. eapply plus_star; eauto. intros [i'' [s1'' [C D]]]. exists i''; exists s1''; split; auto. left. eapply plus_star_trans; eauto. destruct C as [P | [P Q]]. apply plus_star; eauto. eauto. traceEq. + (* 2.2 no silent transition *) exploit bb_simulation_base. eauto. auto. eexact B. eauto. auto. intros [i'' [s1'' [C D]]]. exists i''; exists s1''; split; auto. intuition. right; intuition. inv H6. left. eapply t_trans; eauto. left; auto. Qed. End COMPOSE_BACKWARD_SIMULATIONS. Lemma compose_backward_simulation: forall L1 L2 L3, single_events L3 -> backward_simulation L1 L2 -> backward_simulation L2 L3 -> backward_simulation L1 L3. Proof. intros L1 L2 L3 L3single S12 S23. destruct S12 as [index order match_states props]. destruct S23 as [index' order' match_states' props']. apply Backward_simulation with (bb_order order order') (bb_match_states L1 L2 L3 match_states match_states'); constructor. - (* well founded *) unfold bb_order. apply wf_lex_ord. apply wf_clos_trans. eapply bsim_order_wf; eauto. eapply bsim_order_wf; eauto. - (* initial cores exist *) intros. exploit (bsim_entry_points_exist props); eauto. intros [s2 ]. exploit (bsim_entry_points_exist props'); eauto; intros (s3&?&?). - (* initial states exist *) intros. exploit (bsim_initial_states_exist props); eauto. intros [s2 ]. exploit (bsim_initial_states_exist props'); eauto; intros (s3&?&?). - (* match entry points *) intros s1 s3 f arg m0 INIT1 INIT3. exploit (bsim_entry_points_exist props); eauto. intros [s2 INIT2]. exploit (bsim_match_entry_points props'); eauto. intros [i2 [s2' [INIT2' M2]]]. exploit (bsim_match_entry_points props); eauto; supertransitivity. intros [i1 [s1' [INIT1' M1]]]. exists (i1, i2); exists s1'; intuition auto. eapply bb_match_at; eauto. - (* match initial states *) intros s1 s3 INIT1 INIT3. exploit (bsim_initial_states_exist props); eauto. intros [s2 INIT2]. exploit (bsim_match_initial_states props'); eauto. supertransitivity. intros [i2 [s2' [INIT2' M2]]]. exploit (bsim_match_initial_states props); eauto; supertransitivity. intros [i1 [s1' [INIT1' M1]]]. exists (i1, i2); exists s1'; intuition auto. supertransitivity. eapply bb_match_at; eauto. - (* match final states *) intros i s1 s3 r MS SAFE FIN. inv MS. exploit (bsim_match_final_states props'); eauto. eapply star_safe; eauto. eapply bsim_safe; eauto. intros [s2' [A B]]. exploit (bsim_E0_star props). eapply star_trans. eexact H0. eexact A. auto. eauto. auto. intros [i1' [s1' [C D]]]. exploit (bsim_match_final_states props); eauto. eapply star_safe; eauto. intros [s1'' [P Q]]. exists s1''; split; auto. eapply star_trans; eauto. - (* progress *) intros i s1 s3 MS SAFE. inv MS. eapply (bsim_progress props'). eauto. eapply star_safe; eauto. eapply bsim_safe; eauto. - (* simulation *) apply bb_simulation; auto. - (* symbols *) intros. transitivity (Senv.public_symbol (symbolenv L2) id); eapply bsim_public_preserved; eauto. Qed. (** ** Converting a forward simulation to a backward simulation *) Section FORWARD_TO_BACKWARD. Context L1 L2 index order match_states (FS: fsim_properties L1 L2 index order match_states). Hypothesis L1_receptive: receptive L1. Hypothesis L2_determinate: determinate L2. (** Exploiting forward simulation *) Inductive f2b_transitions: state L1 -> state L2 -> Prop := | f2b_trans_final: forall s1 s2 s1' r, Star L1 s1 E0 s1' -> final_state L1 s1' r -> final_state L2 s2 r -> f2b_transitions s1 s2 | f2b_trans_step: forall s1 s2 s1' t s1'' s2' i' i'', Star L1 s1 E0 s1' -> Step L1 s1' t s1'' -> Plus L2 s2 t s2' -> match_states i' s1' s2 -> match_states i'' s1'' s2' -> f2b_transitions s1 s2. Lemma f2b_progress: forall i s1 s2, match_states i s1 s2 -> safe L1 s1 -> f2b_transitions s1 s2. Proof. intros i0; pattern i0. apply well_founded_ind with (R := order). eapply fsim_order_wf; eauto. intros i REC s1 s2 MATCH SAFE. destruct (SAFE s1) as [[r FINAL] | [t [s1' STEP1]]]. apply star_refl. - (* final state reached *) eapply f2b_trans_final; eauto. apply star_refl. eapply fsim_match_final_states; eauto. - (* L1 can make one step *) exploit (fsim_simulation FS); eauto. intros [i' [s2' [A MATCH']]]. assert (B: Plus L2 s2 t s2' \/ (s2' = s2 /\ t = E0 /\ order i' i)). intuition auto. destruct (star_inv H0); intuition auto. clear A. destruct B as [PLUS2 | [EQ1 [EQ2 ORDER]]]. + eapply f2b_trans_step; eauto. apply star_refl. + subst. exploit REC; eauto. eapply star_safe; eauto. apply star_one; auto. intros TRANS; inv TRANS. * eapply f2b_trans_final; eauto. eapply star_left; eauto. * eapply f2b_trans_step; eauto. eapply star_left; eauto. Qed. Lemma fsim_simulation_not_E0: forall s1 t s1', Step L1 s1 t s1' -> t <> E0 -> forall i s2, match_states i s1 s2 -> exists i', exists s2', Plus L2 s2 t s2' /\ match_states i' s1' s2'. Proof. intros. exploit (fsim_simulation FS); eauto. intros [i' [s2' [A B]]]. exists i'; exists s2'; split; auto. destruct A. auto. destruct H2. exploit star_inv; eauto. intros [[EQ1 EQ2] | P]; auto. congruence. Qed. (** Exploiting determinacy *) Remark silent_or_not_silent: forall t, t = E0 \/ t <> E0. Proof. intros; unfold E0; destruct t; auto; right; congruence. Qed. Remark not_silent_length: forall t1 t2, (length (t1 ** t2) <= 1)%nat -> t1 = E0 \/ t2 = E0. Proof. unfold Eapp, E0; intros. rewrite app_length in H. destruct t1; destruct t2; auto. simpl in H. omegaContradiction. Qed. Lemma f2b_determinacy_inv: forall s2 t' s2' t'' s2'', Step L2 s2 t' s2' -> Step L2 s2 t'' s2'' -> (t' = E0 /\ t'' = E0 /\ s2' = s2'') \/ (t' <> E0 /\ t'' <> E0 /\ match_traces (symbolenv L1) t' t''). Proof. intros. assert (match_traces (symbolenv L2) t' t''). eapply sd_determ_1; eauto. destruct (silent_or_not_silent t'). subst. inv H1. left; intuition. eapply sd_determ_2; eauto. destruct (silent_or_not_silent t''). subst. inv H1. elim H2; auto. right; intuition. eapply match_traces_preserved with (ge1 := (symbolenv L2)); auto. intros; symmetry; apply (fsim_public_preserved FS). Qed. Lemma f2b_determinacy_star: forall s s1, Star L2 s E0 s1 -> forall t s2 s3, Step L2 s1 t s2 -> t <> E0 -> Star L2 s t s3 -> Star L2 s1 t s3. Proof. intros s0 s01 ST0. pattern s0, s01. eapply star_E0_ind; eauto. intros. inv H3. congruence. exploit f2b_determinacy_inv. eexact H. eexact H4. intros [[EQ1 [EQ2 EQ3]] | [NEQ1 [NEQ2 MT]]]. subst. simpl in *. eauto. congruence. Qed. (** Orders *) Inductive f2b_index : Type := | F2BI_before (n: nat) | F2BI_after (n: nat). Inductive f2b_order: f2b_index -> f2b_index -> Prop := | f2b_order_before: forall n n', (n' < n)%nat -> f2b_order (F2BI_before n') (F2BI_before n) | f2b_order_after: forall n n', (n' < n)%nat -> f2b_order (F2BI_after n') (F2BI_after n) | f2b_order_switch: forall n n', f2b_order (F2BI_before n') (F2BI_after n). Lemma wf_f2b_order: well_founded f2b_order. Proof. assert (ACC1: forall n, Acc f2b_order (F2BI_before n)). intros n0; pattern n0; apply lt_wf_ind; intros. constructor; intros. inv H0. auto. assert (ACC2: forall n, Acc f2b_order (F2BI_after n)). intros n0; pattern n0; apply lt_wf_ind; intros. constructor; intros. inv H0. auto. auto. red; intros. destruct a; auto. Qed. (** Constructing the backward simulation *) Inductive f2b_match_states: f2b_index -> state L1 -> state L2 -> Prop := | f2b_match_at: forall i s1 s2, match_states i s1 s2 -> f2b_match_states (F2BI_after O) s1 s2 | f2b_match_before: forall s1 t s1' s2b s2 n s2a i, Step L1 s1 t s1' -> t <> E0 -> Star L2 s2b E0 s2 -> starN (step L2) n s2 t s2a -> match_states i s1 s2b -> f2b_match_states (F2BI_before n) s1 s2 | f2b_match_after: forall n s2 s2a s1 i, starN (step L2) (S n) s2 E0 s2a -> match_states i s1 s2a -> f2b_match_states (F2BI_after (S n)) s1 s2. Remark f2b_match_after': forall n s2 s2a s1 i, starN (step L2) n s2 E0 s2a -> match_states i s1 s2a -> f2b_match_states (F2BI_after n) s1 s2. Proof. intros. inv H. econstructor; eauto. econstructor; eauto. econstructor; eauto. Qed. (** Backward simulation of L2 steps *) Lemma f2b_simulation_step: forall s2 t s2', Step L2 s2 t s2' -> forall i s1, f2b_match_states i s1 s2 -> safe L1 s1 -> exists i', exists s1', (Plus L1 s1 t s1' \/ (Star L1 s1 t s1' /\ f2b_order i' i)) /\ f2b_match_states i' s1' s2'. Proof. intros s2 t s2' STEP2 i s1 MATCH SAFE. inv MATCH. - (* 1. At matching states *) exploit f2b_progress; eauto. intros TRANS; inv TRANS. + (* 1.1 L1 can reach final state and L2 is at final state: impossible! *) exploit (sd_final_nostep L2_determinate); eauto. contradiction. + (* 1.2 L1 can make 0 or several steps; L2 can make 1 or several matching steps. *) inv H2. exploit f2b_determinacy_inv. eexact H5. eexact STEP2. intros [[EQ1 [EQ2 EQ3]] | [NOT1 [NOT2 MT]]]. * (* 1.2.1 L2 makes a silent transition *) destruct (silent_or_not_silent t2). (* 1.2.1.1 L1 makes a silent transition too: perform transition now and go to "after" state *) subst. simpl in *. destruct (star_starN H6) as [n STEPS2]. exists (F2BI_after n); exists s1''; split. left. eapply plus_right; eauto. eapply f2b_match_after'; eauto. (* 1.2.1.2 L1 makes a non-silent transition: keep it for later and go to "before" state *) subst. simpl in *. destruct (star_starN H6) as [n STEPS2]. exists (F2BI_before n); exists s1'; split. right; split. auto. constructor. econstructor. eauto. auto. apply star_one; eauto. eauto. eauto. * (* 1.2.2 L2 makes a non-silent transition, and so does L1 *) exploit not_silent_length. eapply (sr_traces L1_receptive); eauto. intros [EQ | EQ]. congruence. subst t2. rewrite E0_right in H1. (* Use receptiveness to equate the traces *) exploit (sr_receptive L1_receptive); eauto. intros [s1''' STEP1]. exploit fsim_simulation_not_E0. eexact STEP1. auto. eauto. intros [i''' [s2''' [P Q]]]. inv P. (* Exploit determinacy *) exploit not_silent_length. eapply (sr_traces L1_receptive); eauto. intros [EQ | EQ]. subst t0. simpl in *. exploit sd_determ_1. eauto. eexact STEP2. eexact H2. intros. elim NOT2. inv H8. auto. subst t2. rewrite E0_right in *. assert (s4 = s2'). eapply sd_determ_2; eauto. subst s4. (* Perform transition now and go to "after" state *) destruct (star_starN H7) as [n STEPS2]. exists (F2BI_after n); exists s1'''; split. left. eapply plus_right; eauto. eapply f2b_match_after'; eauto. - (* 2. Before *) inv H2. congruence. exploit f2b_determinacy_inv. eexact H4. eexact STEP2. intros [[EQ1 [EQ2 EQ3]] | [NOT1 [NOT2 MT]]]. + (* 2.1 L2 makes a silent transition: remain in "before" state *) subst. simpl in *. exists (F2BI_before n0); exists s1; split. right; split. apply star_refl. constructor. omega. econstructor; eauto. eapply star_right; eauto. + (* 2.2 L2 make a non-silent transition *) exploit not_silent_length. eapply (sr_traces L1_receptive); eauto. intros [EQ | EQ]. congruence. subst. rewrite E0_right in *. (* Use receptiveness to equate the traces *) exploit (sr_receptive L1_receptive); eauto. intros [s1''' STEP1]. exploit fsim_simulation_not_E0. eexact STEP1. auto. eauto. intros [i''' [s2''' [P Q]]]. (* Exploit determinacy *) exploit f2b_determinacy_star. eauto. eexact STEP2. auto. apply plus_star; eauto. intro R. inv R. congruence. exploit not_silent_length. eapply (sr_traces L1_receptive); eauto. intros [EQ | EQ]. subst. simpl in *. exploit sd_determ_1. eauto. eexact STEP2. eexact H2. intros. elim NOT2. inv H7; auto. subst. rewrite E0_right in *. assert (s3 = s2'). eapply sd_determ_2; eauto. subst s3. (* Perform transition now and go to "after" state *) destruct (star_starN H6) as [n STEPS2]. exists (F2BI_after n); exists s1'''; split. left. apply plus_one; auto. eapply f2b_match_after'; eauto. - (* 3. After *) inv H. exploit Eapp_E0_inv; eauto. intros [EQ1 EQ2]; subst. exploit f2b_determinacy_inv. eexact H2. eexact STEP2. intros [[EQ1 [EQ2 EQ3]] | [NOT1 [NOT2 MT]]]. subst. exists (F2BI_after n); exists s1; split. right; split. apply star_refl. constructor; omega. eapply f2b_match_after'; eauto. congruence. Qed. End FORWARD_TO_BACKWARD. (** The backward simulation *) Lemma forward_to_backward_simulation: forall L1 L2, forward_simulation L1 L2 -> receptive L1 -> determinate L2 -> backward_simulation L1 L2. Proof. intros L1 L2 FS L1_receptive L2_determinate. destruct FS as [index order match_states FS]. apply Backward_simulation with f2b_order (f2b_match_states L1 L2 match_states); constructor. - (* well founded *) apply wf_f2b_order. - (* initial cores exist *) intros. exploit (fsim_match_entry_points FS); eauto. intros [i [s2 [A B]]]. exists s2; auto. - (* initial states exist *) intros. exploit (fsim_match_initial_states FS); eauto. intros [i [s2 [A B]]]. exists s2; auto. - (* initial cores *) intros. exploit (fsim_match_entry_points FS); eauto. intros [i [s2' [A B]]]. assert (s2 = s2') by (eapply sd_initial_determ; eauto; supertransitivity). subst s2. exists (F2BI_after O); exists s1; repeat(split; auto). econstructor; eauto. - (* initial states *) intros. exploit (fsim_match_initial_states FS); eauto. intros [i [s2' [A B]]]. assert (s2 = s2') by (eapply sd_initial_state_determ; eauto; supertransitivity). subst s2. exists (F2BI_after O); exists s1; repeat(split; auto). econstructor; eauto. - (* final states *) intros. inv H. exploit f2b_progress; eauto. intros TRANS; inv TRANS. assert (r0 = r) by (eapply (sd_final_determ L2_determinate); eauto). subst r0. exists s1'; auto. inv H4. exploit (sd_final_nostep L2_determinate); eauto. contradiction. inv H5. congruence. exploit (sd_final_nostep L2_determinate); eauto. contradiction. inv H2. exploit (sd_final_nostep L2_determinate); eauto. contradiction. - (* progress *) intros. inv H. exploit f2b_progress; eauto. intros TRANS; inv TRANS. left; exists r; auto. inv H3. right; econstructor; econstructor; eauto. inv H4. congruence. right; econstructor; econstructor; eauto. inv H1. right; econstructor; econstructor; eauto. - (* simulation *) eapply f2b_simulation_step; eauto. - (* symbols preserved *) exact (fsim_public_preserved FS). Qed. (** * Transforming a semantics into a single-event, equivalent semantics *) Definition well_behaved_traces (L: semantics) : Prop := forall s t s', Step L s t s' -> match t with nil => True | ev :: t' => output_trace t' end. Section ATOMIC. Variable L: semantics. Hypothesis Lwb: well_behaved_traces L. Inductive atomic_step : (trace * state L) -> trace -> (trace * state L) -> Prop := | atomic_step_silent: forall s s', Step L s E0 s' -> atomic_step (E0, s) E0 (E0, s') | atomic_step_start: forall s ev t s', Step L s (ev :: t) s' -> atomic_step (E0, s) (ev :: nil) (t, s') | atomic_step_continue: forall ev t s, output_trace (ev :: t) -> atomic_step (ev :: t, s) (ev :: nil) (t, s). Definition part_atomic : part_semantics := {| state := (trace * state L)%type; get_mem := fun s => get_mem (snd s) ; set_mem := fun s m => (fst s, set_mem (snd s) m); genvtype := genvtype L; step := atomic_step; entry_point := fun m0 s f args => entry_point L m0 (snd s) f args /\ fst s = E0; at_external := fun s => at_external _ (snd s) ; after_external := fun ret s m => option_map (fun x => (fst s, x)) (after_external _ ret (snd s) m); final_state := fun s r => final_state L (snd s) r /\ fst s = E0; globalenv := globalenv L; symbolenv := symbolenv L |}. Definition atomic : semantics := {| part_sem := part_atomic; main_block := main_block L; init_mem := init_mem L; |}. End ATOMIC. (** A forward simulation from a semantics [L1] to a single-event semantics [L2] can be "factored" into a forward simulation from [atomic L1] to [L2]. *) Section FACTOR_FORWARD_SIMULATION. Variable L1: semantics. Variable L2: semantics. Context index order match_states (sim: fsim_properties L1 L2 index order match_states). Hypothesis L2single: single_events L2. Inductive ffs_match: index -> (trace * state L1) -> state L2 -> Prop := | ffs_match_at: forall i s1 s2, match_states i s1 s2 -> ffs_match i (E0, s1) s2 | ffs_match_buffer: forall i ev t s1 s2 s2', Star L2 s2 (ev :: t) s2' -> match_states i s1 s2' -> ffs_match i (ev :: t, s1) s2. Lemma star_non_E0_split': forall s2 t s2', Star L2 s2 t s2' -> match t with | nil => True | ev :: t' => exists s2x, Plus L2 s2 (ev :: nil) s2x /\ Star L2 s2x t' s2' end. Proof. induction 1. simpl. auto. exploit L2single; eauto. intros LEN. destruct t1. simpl in *. subst. destruct t2. auto. destruct IHstar as [s2x [A B]]. exists s2x; split; auto. eapply plus_left. eauto. apply plus_star; eauto. auto. destruct t1. simpl in *. subst t. exists s2; split; auto. apply plus_one; auto. simpl in LEN. omegaContradiction. Qed. Lemma ffs_simulation: forall s1 t s1', Step (atomic L1) s1 t s1' -> forall i s2, ffs_match i s1 s2 -> exists i', exists s2', (Plus L2 s2 t s2' \/ (Star L2 s2 t s2') /\ order i' i) /\ ffs_match i' s1' s2'. Proof. induction 1; intros. - (* silent step *) inv H0. exploit (fsim_simulation sim); eauto. intros [i' [s2' [A B]]]. exists i'; exists s2'; split. auto. constructor; auto. - (* start step *) inv H0. exploit (fsim_simulation sim); eauto. intros [i' [s2' [A B]]]. destruct t as [ | ev' t]. + (* single event *) exists i'; exists s2'; split. auto. constructor; auto. + (* multiple events *) assert (C: Star L2 s2 (ev :: ev' :: t) s2'). intuition. apply plus_star; auto. exploit star_non_E0_split'. eauto. simpl. intros [s2x [P Q]]. exists i'; exists s2x; split. auto. econstructor; eauto. - (* continue step *) inv H0. exploit star_non_E0_split'. eauto. simpl. intros [s2x [P Q]]. destruct t. exists i; exists s2'; split. left. eapply plus_star_trans; eauto. constructor; auto. exists i; exists s2x; split. auto. econstructor; eauto. Qed. End FACTOR_FORWARD_SIMULATION. Theorem factor_forward_simulation: forall L1 L2, forward_simulation L1 L2 -> single_events L2 -> forward_simulation (atomic L1) L2. Proof. intros L1 L2 FS L2single. destruct FS as [index order match_states sim]. apply Forward_simulation with order (ffs_match L1 L2 match_states); constructor. - (* wf *) eapply fsim_order_wf; eauto. - (* initial core *) intros. destruct s1 as [t1 s1]. simpl in H. destruct H. subst. exploit (fsim_match_entry_points sim); eauto. intros [i [s2 [A B]]]. exists i; exists s2; repeat(split; auto). constructor; auto. - (* initial states *) intros. destruct s1 as [t1 s1]. inv H. destruct H2; simpl in *; subst. exploit (fsim_match_initial_states sim); eauto. econstructor; eauto. intros [i [s2 [A B]]]. exists i; exists s2; split; auto. constructor; auto. - (* final states *) intros. destruct s1 as [t1 s1]. simpl in H0; destruct H0; subst. inv H. eapply (fsim_match_final_states sim); eauto. - (* simulation *) eapply ffs_simulation; eauto. - (* symbols preserved *) simpl. exact (fsim_public_preserved sim). Qed. (** Likewise, a backward simulation from a single-event semantics [L1] to a semantics [L2] can be "factored" as a backward simulation from [L1] to [atomic L2]. *) Section FACTOR_BACKWARD_SIMULATION. Variable L1: semantics. Variable L2: semantics. Context index order match_states (sim: bsim_properties L1 L2 index order match_states). Hypothesis L1single: single_events L1. Hypothesis L2wb: well_behaved_traces L2. Inductive fbs_match: index -> state L1 -> (trace * state L2) -> Prop := | fbs_match_intro: forall i s1 t s2 s1', Star L1 s1 t s1' -> match_states i s1' s2 -> t = E0 \/ output_trace t -> fbs_match i s1 (t, s2). Lemma fbs_simulation: forall s2 t s2', Step (atomic L2) s2 t s2' -> forall i s1, fbs_match i s1 s2 -> safe L1 s1 -> exists i', exists s1', (Plus L1 s1 t s1' \/ (Star L1 s1 t s1' /\ order i' i)) /\ fbs_match i' s1' s2'. Proof. induction 1; intros. - (* silent step *) inv H0. exploit (bsim_simulation sim); eauto. eapply star_safe; eauto. intros [i' [s1'' [A B]]]. exists i'; exists s1''; split. destruct A as [P | [P Q]]. left. eapply star_plus_trans; eauto. right; split; auto. eapply star_trans; eauto. econstructor. apply star_refl. auto. auto. - (* start step *) inv H0. exploit (bsim_simulation sim); eauto. eapply star_safe; eauto. intros [i' [s1'' [A B]]]. assert (C: Star L1 s1 (ev :: t) s1''). eapply star_trans. eauto. destruct A as [P | [P Q]]. apply plus_star; eauto. eauto. auto. exploit star_non_E0_split'; eauto. simpl. intros [s1x [P Q]]. exists i'; exists s1x; split. left; auto. econstructor; eauto. exploit L2wb; eauto. - (* continue step *) inv H0. unfold E0 in H8; destruct H8; try congruence. exploit star_non_E0_split'; eauto. simpl. intros [s1x [P Q]]. exists i; exists s1x; split. left; auto. econstructor; eauto. simpl in H0; tauto. Qed. Lemma fbs_progress: forall i s1 s2, fbs_match i s1 s2 -> safe L1 s1 -> (exists r, final_state (atomic L2) s2 r) \/ (exists t, exists s2', Step (atomic L2) s2 t s2'). Proof. intros. inv H. destruct t. - (* 1. no buffered events *) exploit (bsim_progress sim); eauto. eapply star_safe; eauto. intros [[r A] | [t [s2' A]]]. + (* final state *) left; exists r; simpl; auto. + (* L2 can step *) destruct t. right; exists E0; exists (nil, s2'). constructor. auto. right; exists (e :: nil); exists (t, s2'). constructor. auto. - (* 2. some buffered events *) unfold E0 in H3; destruct H3. congruence. right; exists (e :: nil); exists (t, s3). constructor. auto. Qed. End FACTOR_BACKWARD_SIMULATION. Lemma atomic_initial: forall L s, initial_state L s -> initial_state (atomic L) (E0, s). Proof. intros ? ? H; inv H. econstructor; simpl; eauto. Qed. Lemma atomic_initial': forall L s t, initial_state (atomic L) (t, s) -> initial_state L s. Proof. intros ? ? ? H; inv H. destruct H2; simpl in *. econstructor; simpl; eauto. Qed. Theorem factor_backward_simulation: forall L1 L2, backward_simulation L1 L2 -> single_events L1 -> well_behaved_traces L2 -> backward_simulation L1 (atomic L2). Proof. intros L1 L2 BS L1single L2wb. destruct BS as [index order match_states sim]. apply Backward_simulation with order (fbs_match L1 L2 match_states); constructor. - (* wf *) eapply bsim_order_wf; eauto. - (* initial cores exist *) intros. exploit (bsim_entry_points_exist sim); eauto. intros [s2 A]. exists (E0, s2). simpl; auto. - (* initial states exist *) intros. exploit (bsim_initial_states_exist sim); eauto. intros [s2 A]. exists (E0, s2). simpl. eapply atomic_initial; eauto. - (* initial cores match *) intros. destruct s2 as [t s2]; simpl in H0; destruct H0; subst. exploit (bsim_match_entry_points sim); eauto. intros [i [s1' [A B]]]. exists i; exists s1'; repeat(split; auto). econstructor. apply star_refl. auto. auto. - (* initial states match *) intros. destruct s2 as [t s2]; simpl in H0; inv H0; subst. destruct H3; simpl in *; subst. exploit (bsim_match_initial_states sim); eauto. + econstructor; eauto. + intros [i [s1' [A B]]]. exists i; exists s1'; repeat(split; auto). econstructor. apply star_refl. auto. auto. - (* final states match *) intros. destruct s2 as [t s2]; simpl in H1; destruct H1; subst. inv H. exploit (bsim_match_final_states sim); eauto. eapply star_safe; eauto. intros [s1'' [A B]]. exists s1''; split; auto. eapply star_trans; eauto. - (* progress *) eapply fbs_progress; eauto. - (* simulation *) eapply fbs_simulation; eauto. - (* symbols *) simpl. exact (bsim_public_preserved sim). Qed. (** Receptiveness of [atomic L]. *) Record strongly_receptive (L: semantics) : Prop := Strongly_receptive { ssr_receptive: forall s ev1 t1 s1 ev2, Step L s (ev1 :: t1) s1 -> match_traces (symbolenv L) (ev1 :: nil) (ev2 :: nil) -> exists s2, exists t2, Step L s (ev2 :: t2) s2; ssr_well_behaved: well_behaved_traces L }. Theorem atomic_receptive: forall L, strongly_receptive L -> receptive (atomic L). Proof. intros. constructor; intros. (* receptive *) inv H0. (* silent step *) inv H1. exists (E0, s'). constructor; auto. (* start step *) assert (exists ev2, t2 = ev2 :: nil). inv H1; econstructor; eauto. destruct H0 as [ev2 EQ]; subst t2. exploit ssr_receptive; eauto. intros [s2 [t2 P]]. exploit ssr_well_behaved. eauto. eexact P. simpl; intros Q. exists (t2, s2). constructor; auto. (* continue step *) simpl in H2; destruct H2. assert (t2 = ev :: nil). inv H1; simpl in H0; tauto. subst t2. exists (t, s0). constructor; auto. simpl; auto. (* single-event *) red. intros. inv H0; simpl; omega. Qed. (** * Connections with big-step semantics *) (** The general form of a big-step semantics *) Record bigstep_semantics : Type := Bigstep_semantics { bigstep_terminates: trace -> int -> Prop; bigstep_diverges: traceinf -> Prop }. (** Soundness with respect to a small-step semantics *) Record bigstep_sound (B: bigstep_semantics) (L: semantics) : Prop := Bigstep_sound { bigstep_terminates_sound: forall t r, bigstep_terminates B t r -> exists s1, exists s2, initial_state L s1 /\ Star L s1 t s2 /\ final_state L s2 r; bigstep_diverges_sound: forall T, bigstep_diverges B T -> exists s1, initial_state L s1 /\ forever (step L) s1 T }.
The symptoms of AML are caused by replacement of normal bone marrow with leukemic cells , which causes a drop in red blood cells , platelets , and normal white blood cells . These symptoms include fatigue , shortness of breath , easy bruising and bleeding , and increased risk of infection . Several risk factors and chromosomal abnormalities have been identified , but the specific cause is not clear . As an acute leukemia , AML progresses rapidly and is typically fatal within weeks or months if left untreated .
= Gold dollar =
State Before: R : Type u_1 K : Type u_2 inst✝¹ : Semiring R inst✝ : CommSemiring K i : R →+* K a b : R bi : K N : ℕ f g : R[X] x✝¹ : DenomsClearable a b N f i x✝ : DenomsClearable a b N g i Df : R bf : K bfu : bf * ↑i b = 1 Hf : ↑i Df = ↑i b ^ N * eval (↑i a * bf) (Polynomial.map i f) Dg : R bg : K bgu : bg * ↑i b = 1 Hg : ↑i Dg = ↑i b ^ N * eval (↑i a * bg) (Polynomial.map i g) ⊢ ↑i (Df + Dg) = ↑i b ^ N * eval (↑i a * bf) (Polynomial.map i (f + g)) State After: R : Type u_1 K : Type u_2 inst✝¹ : Semiring R inst✝ : CommSemiring K i : R →+* K a b : R bi : K N : ℕ f g : R[X] x✝¹ : DenomsClearable a b N f i x✝ : DenomsClearable a b N g i Df : R bf : K bfu : bf * ↑i b = 1 Hf : ↑i Df = ↑i b ^ N * eval (↑i a * bf) (Polynomial.map i f) Dg : R bg : K bgu : bg * ↑i b = 1 Hg : ↑i Dg = ↑i b ^ N * eval (↑i a * bg) (Polynomial.map i g) ⊢ ↑i b ^ N * eval (↑i a * bf) (Polynomial.map i f) + ↑i b ^ N * eval (↑i a * bg) (Polynomial.map i g) = ↑i b ^ N * eval (↑i a * bf) (Polynomial.map i f) + ↑i b ^ N * eval (↑i a * bf) (Polynomial.map i g) Tactic: rw [RingHom.map_add, Polynomial.map_add, eval_add, mul_add, Hf, Hg] State Before: R : Type u_1 K : Type u_2 inst✝¹ : Semiring R inst✝ : CommSemiring K i : R →+* K a b : R bi : K N : ℕ f g : R[X] x✝¹ : DenomsClearable a b N f i x✝ : DenomsClearable a b N g i Df : R bf : K bfu : bf * ↑i b = 1 Hf : ↑i Df = ↑i b ^ N * eval (↑i a * bf) (Polynomial.map i f) Dg : R bg : K bgu : bg * ↑i b = 1 Hg : ↑i Dg = ↑i b ^ N * eval (↑i a * bg) (Polynomial.map i g) ⊢ ↑i b ^ N * eval (↑i a * bf) (Polynomial.map i f) + ↑i b ^ N * eval (↑i a * bg) (Polynomial.map i g) = ↑i b ^ N * eval (↑i a * bf) (Polynomial.map i f) + ↑i b ^ N * eval (↑i a * bf) (Polynomial.map i g) State After: case e_a.e_a.e_a.e_a R : Type u_1 K : Type u_2 inst✝¹ : Semiring R inst✝ : CommSemiring K i : R →+* K a b : R bi : K N : ℕ f g : R[X] x✝¹ : DenomsClearable a b N f i x✝ : DenomsClearable a b N g i Df : R bf : K bfu : bf * ↑i b = 1 Hf : ↑i Df = ↑i b ^ N * eval (↑i a * bf) (Polynomial.map i f) Dg : R bg : K bgu : bg * ↑i b = 1 Hg : ↑i Dg = ↑i b ^ N * eval (↑i a * bg) (Polynomial.map i g) ⊢ bg = bf Tactic: congr State Before: case e_a.e_a.e_a.e_a R : Type u_1 K : Type u_2 inst✝¹ : Semiring R inst✝ : CommSemiring K i : R →+* K a b : R bi : K N : ℕ f g : R[X] x✝¹ : DenomsClearable a b N f i x✝ : DenomsClearable a b N g i Df : R bf : K bfu : bf * ↑i b = 1 Hf : ↑i Df = ↑i b ^ N * eval (↑i a * bf) (Polynomial.map i f) Dg : R bg : K bgu : bg * ↑i b = 1 Hg : ↑i Dg = ↑i b ^ N * eval (↑i a * bg) (Polynomial.map i g) ⊢ bg = bf State After: no goals Tactic: refine' @inv_unique K _ (i b) bg bf _ _ <;> rwa [mul_comm]
! DART software - Copyright UCAR. This open source software is provided ! by UCAR, "as is", without charge, subject to all terms of use at ! http://www.image.ucar.edu/DAReS/DART/DART_download ! ! BEGIN DART PREPROCESS TYPE DEFINITIONS !BUOY_U_WIND_COMPONENT, QTY_U_WIND_COMPONENT, COMMON_CODE !BUOY_V_WIND_COMPONENT, QTY_V_WIND_COMPONENT, COMMON_CODE !BUOY_SURFACE_PRESSURE, QTY_SURFACE_PRESSURE, COMMON_CODE !BUOY_TEMPERATURE, QTY_TEMPERATURE, COMMON_CODE !SHIP_U_WIND_COMPONENT, QTY_U_WIND_COMPONENT, COMMON_CODE !SHIP_V_WIND_COMPONENT, QTY_V_WIND_COMPONENT, COMMON_CODE !SHIP_SURFACE_PRESSURE, QTY_SURFACE_PRESSURE, COMMON_CODE !SHIP_TEMPERATURE, QTY_TEMPERATURE, COMMON_CODE !SYNOP_U_WIND_COMPONENT, QTY_U_WIND_COMPONENT, COMMON_CODE !SYNOP_V_WIND_COMPONENT, QTY_V_WIND_COMPONENT, COMMON_CODE !SYNOP_SURFACE_PRESSURE, QTY_SURFACE_PRESSURE, COMMON_CODE !SYNOP_SPECIFIC_HUMIDITY, QTY_SPECIFIC_HUMIDITY, COMMON_CODE !SYNOP_TEMPERATURE, QTY_TEMPERATURE, COMMON_CODE !AIREP_U_WIND_COMPONENT, QTY_U_WIND_COMPONENT, COMMON_CODE !AIREP_V_WIND_COMPONENT, QTY_V_WIND_COMPONENT, COMMON_CODE !AIREP_PRESSURE, QTY_PRESSURE, COMMON_CODE !AIREP_TEMPERATURE, QTY_TEMPERATURE, COMMON_CODE !AMDAR_U_WIND_COMPONENT, QTY_U_WIND_COMPONENT, COMMON_CODE !AMDAR_V_WIND_COMPONENT, QTY_V_WIND_COMPONENT, COMMON_CODE !AMDAR_PRESSURE, QTY_PRESSURE, COMMON_CODE !AMDAR_TEMPERATURE, QTY_TEMPERATURE, COMMON_CODE !PILOT_U_WIND_COMPONENT, QTY_U_WIND_COMPONENT, COMMON_CODE !PILOT_V_WIND_COMPONENT, QTY_V_WIND_COMPONENT, COMMON_CODE !PILOT_PRESSURE, QTY_PRESSURE, COMMON_CODE !PILOT_TEMPERATURE, QTY_TEMPERATURE, COMMON_CODE !BOGUS_U_WIND_COMPONENT, QTY_U_WIND_COMPONENT, COMMON_CODE !BOGUS_V_WIND_COMPONENT, QTY_V_WIND_COMPONENT, COMMON_CODE !BOGUS_PRESSURE, QTY_PRESSURE, COMMON_CODE !BOGUS_TEMPERATURE, QTY_TEMPERATURE, COMMON_CODE !PROFILER_U_WIND_COMPONENT, QTY_U_WIND_COMPONENT, COMMON_CODE !PROFILER_V_WIND_COMPONENT, QTY_V_WIND_COMPONENT, COMMON_CODE !PROFILER_PRESSURE, QTY_PRESSURE, COMMON_CODE !SATEM_THICKNESS, QTY_TEMPERATURE ! END DART PREPROCESS TYPE DEFINITIONS ! BEGIN DART PREPROCESS USE OF SPECIAL OBS_DEF MODULE ! use obs_def_gts_mod, only : get_expected_thickness ! END DART PREPROCESS USE OF SPECIAL OBS_DEF MODULE ! BEGIN DART PREPROCESS GET_EXPECTED_OBS_FROM_DEF ! case(SATEM_THICKNESS) ! call get_expected_thickness(state_handle, ens_size, location, expected_obs, istatus) ! END DART PREPROCESS GET_EXPECTED_OBS_FROM_DEF ! BEGIN DART PREPROCESS READ_OBS_DEF ! case(SATEM_THICKNESS) ! continue ! END DART PREPROCESS READ_OBS_DEF ! BEGIN DART PREPROCESS WRITE_OBS_DEF ! case(SATEM_THICKNESS) ! continue ! END DART PREPROCESS WRITE_OBS_DEF ! BEGIN DART PREPROCESS INTERACTIVE_OBS_DEF ! case(SATEM_THICKNESS) ! continue ! END DART PREPROCESS INTERACTIVE_OBS_DEF ! BEGIN DART PREPROCESS MODULE CODE module obs_def_gts_mod use types_mod, only : r8, missing_r8, gravity, gas_constant, gas_constant_v use utilities_mod, only : register_module use location_mod, only : location_type, set_location, get_location , & VERTISSURFACE, VERTISPRESSURE, VERTISHEIGHT use assim_model_mod, only : interpolate use obs_kind_mod, only : QTY_TEMPERATURE, QTY_SPECIFIC_HUMIDITY, QTY_PRESSURE use ensemble_manager_mod, only : ensemble_type use obs_def_utilities_mod, only : track_status implicit none private public :: get_expected_thickness ! version controlled file description for error handling, do not edit character(len=256), parameter :: source = & "$URL$" character(len=32 ), parameter :: revision = "$Revision$" character(len=128), parameter :: revdate = "$Date$" logical, save :: module_initialized = .false. contains subroutine initialize_module !----------------------------------------------------------------------------- call register_module(source, revision, revdate) module_initialized = .true. end subroutine initialize_module subroutine get_expected_thickness(state_handle, ens_size, location, thickness, istatus) !----------------------------------------------------------------------------- ! inputs: ! state_vector: DART state vector ! ! output parameters: ! thickness: modeled satem thickness between the specified layers. (unit: m) ! istatus: =0 normal; =1 either or both t or q interpolation failed !--------------------------------------------- ! Hui Liu NCAR/IMAGE April 9, 2008 !--------------------------------------------- implicit none type(ensemble_type), intent(in) :: state_handle integer, intent(in) :: ens_size type(location_type), intent(in) :: location real(r8), intent(out) :: thickness(ens_size) integer, intent(out) :: istatus(ens_size) ! local variables integer :: k integer, parameter :: nlevel = 9, num_press_int = 10 real(r8) :: lon, lat, pressure, obsloc(3), obs_level(nlevel), press(num_press_int+1) real(r8) :: press_top, press_bot, press_int integer :: t_istatus(ens_size), q_istatus(ens_size) data obs_level/85000.0, 70000.0, 50000.0, 40000.0, 30000.0, 25000.0, 20000.0, 15000.0, 10000.0/ real(r8), parameter:: rdrv1 = gas_constant_v/gas_constant - 1.0_r8 real(r8) :: lon2, p type(location_type) :: location2 integer :: which_vert real(r8) :: t(ens_size), q(ens_size), tv(ens_size) logical :: return_now if ( .not. module_initialized ) call initialize_module ! Start out assuming passing status istatus = 0 obsloc = get_location(location) lon = obsloc(1) ! degree: 0 to 360 lat = obsloc(2) ! degree: -90 to 90 pressure = obsloc(3) ! (Pa) press_bot = -999.9_r8 press_top = -999.9_r8 ! find the bottom and top of the layer - ! The 'bottom' is defined to be the incoming observation value. ! The 'top' is the next higher observation level. ! If the bottom is the highest observation level; ! there is no top, and it is an ERROR. if(pressure > obs_level(1) ) then press_bot = pressure press_top = obs_level(1) endif do k = 1, nlevel-1 if( abs(pressure - obs_level(k)) < 0.01_r8 ) then press_bot = obs_level(k) press_top = obs_level(k+1) exit endif end do ! define the vertical intervals for the integration of Tv. Use 10 sub_layers ! for the vertical integration. press_int = (press_bot - press_top)/num_press_int press(1) = press_bot do k=2, num_press_int+1 press(k) = press(1) - press_int * (k-1) end do ! define the location of the interpolated points. lon2 = lon if(lon > 360.0_r8 ) lon2 = lon - 360.0_r8 if(lon < 0.0_r8 ) lon2 = lon + 360.0_r8 which_vert = VERTISPRESSURE thickness = 0.0_r8 do k=2, num_press_int+1, 2 p = press(k) location2 = set_location(lon2, lat, p, which_vert) call interpolate(state_handle, ens_size, location2, QTY_TEMPERATURE, t, t_istatus) call track_status(ens_size, t_istatus, thickness, istatus, return_now) ! don't return until we have the corresponding q to test call interpolate(state_handle, ens_size, location2, QTY_SPECIFIC_HUMIDITY, q, q_istatus) call track_status(ens_size, q_istatus, thickness, istatus, return_now) ! use a consistent error code for failed t or q instead of ! the model specific return code. where (istatus > 0) istatus = 1 ! t : Kelvin, from top to bottom ! q : kg/kg, from top to bottom where (istatus == 0) tv = t * (1.0_r8 + rdrv1 * q ) ! virtual temperature thickness = thickness + gas_constant/gravity * tv * log(press(k-1)/press(k+1)) end where !> @todo is this magic number reasonable? jeff thinks no. where ( abs(thickness) > 10000.0_r8 ) istatus = 2 thickness = missing_r8 end where end do return end subroutine get_expected_thickness end module obs_def_gts_mod ! END DART PREPROCESS MODULE CODE
[GOAL] C : Type u₁ inst✝¹ : Category.{u_1, u₁} C D : Type u₂ inst✝ : Category.{u_2, u₂} D F : C ⥤ D X Y Z : C f : X ⟶ Y g : Y ⟶ Z W : D h : F.obj Z ⟶ W ⊢ F.map (f ≫ g) ≫ h = F.map f ≫ F.map g ≫ h [PROOFSTEP] rw [F.map_comp, Category.assoc] [GOAL] C : Type u₁ inst✝² : Category.{v₁, u₁} C D : Type u₂ inst✝¹ : Category.{v₂, u₂} D E : Type u₃ inst✝ : Category.{v₃, u₃} E F : C ⥤ D G : D ⥤ E ⊢ ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), { obj := fun X => G.obj (F.obj X), map := fun {X Y} f => G.map (F.map f) }.map (f ≫ g) = { obj := fun X => G.obj (F.obj X), map := fun {X Y} f => G.map (F.map f) }.map f ≫ { obj := fun X => G.obj (F.obj X), map := fun {X Y} f => G.map (F.map f) }.map g [PROOFSTEP] intros [GOAL] C : Type u₁ inst✝² : Category.{v₁, u₁} C D : Type u₂ inst✝¹ : Category.{v₂, u₂} D E : Type u₃ inst✝ : Category.{v₃, u₃} E F : C ⥤ D G : D ⥤ E X✝ Y✝ Z✝ : C f✝ : X✝ ⟶ Y✝ g✝ : Y✝ ⟶ Z✝ ⊢ { obj := fun X => G.obj (F.obj X), map := fun {X Y} f => G.map (F.map f) }.map (f✝ ≫ g✝) = { obj := fun X => G.obj (F.obj X), map := fun {X Y} f => G.map (F.map f) }.map f✝ ≫ { obj := fun X => G.obj (F.obj X), map := fun {X Y} f => G.map (F.map f) }.map g✝ [PROOFSTEP] dsimp [GOAL] C : Type u₁ inst✝² : Category.{v₁, u₁} C D : Type u₂ inst✝¹ : Category.{v₂, u₂} D E : Type u₃ inst✝ : Category.{v₃, u₃} E F : C ⥤ D G : D ⥤ E X✝ Y✝ Z✝ : C f✝ : X✝ ⟶ Y✝ g✝ : Y✝ ⟶ Z✝ ⊢ G.map (F.map (f✝ ≫ g✝)) = G.map (F.map f✝) ≫ G.map (F.map g✝) [PROOFSTEP] rw [F.map_comp, G.map_comp] [GOAL] C : Type u₁ inst✝² : Category.{v₁, u₁} C D : Type u₂ inst✝¹ : Category.{v₂, u₂} D E : Type u₃ inst✝ : Category.{v₃, u₃} E F : C ⥤ D ⊢ F ⋙ 𝟭 D = F [PROOFSTEP] cases F [GOAL] case mk C : Type u₁ inst✝² : Category.{v₁, u₁} C D : Type u₂ inst✝¹ : Category.{v₂, u₂} D E : Type u₃ inst✝ : Category.{v₃, u₃} E toPrefunctor✝ : C ⥤q D map_id✝ : ∀ (X : C), toPrefunctor✝.map (𝟙 X) = 𝟙 (toPrefunctor✝.obj X) map_comp✝ : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), toPrefunctor✝.map (f ≫ g) = toPrefunctor✝.map f ≫ toPrefunctor✝.map g ⊢ mk toPrefunctor✝ ⋙ 𝟭 D = mk toPrefunctor✝ [PROOFSTEP] rfl [GOAL] C : Type u₁ inst✝² : Category.{v₁, u₁} C D : Type u₂ inst✝¹ : Category.{v₂, u₂} D E : Type u₃ inst✝ : Category.{v₃, u₃} E F : C ⥤ D ⊢ 𝟭 C ⋙ F = F [PROOFSTEP] cases F [GOAL] case mk C : Type u₁ inst✝² : Category.{v₁, u₁} C D : Type u₂ inst✝¹ : Category.{v₂, u₂} D E : Type u₃ inst✝ : Category.{v₃, u₃} E toPrefunctor✝ : C ⥤q D map_id✝ : ∀ (X : C), toPrefunctor✝.map (𝟙 X) = 𝟙 (toPrefunctor✝.obj X) map_comp✝ : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), toPrefunctor✝.map (f ≫ g) = toPrefunctor✝.map f ≫ toPrefunctor✝.map g ⊢ 𝟭 C ⋙ mk toPrefunctor✝ = mk toPrefunctor✝ [PROOFSTEP] rfl [GOAL] C : Type u₁ inst✝³ : Category.{v₁, u₁} C D : Type u₂ inst✝² : Category.{v₂, u₂} D E : Type u₃ inst✝¹ : Category.{v₃, u₃} E F : C ⥤ D X Y : C P : Prop inst✝ : Decidable P f : P → (X ⟶ Y) g : ¬P → (X ⟶ Y) ⊢ F.map (if h : P then f h else g h) = if h : P then F.map (f h) else F.map (g h) [PROOFSTEP] aesop_cat
Require Import Coqlib. Require Export Axioms. Require Import Errors. Require Import Maps. Require Import Integers. Require Import Floats. Require Import AST. Require Import Values. Require Import Events. Require Import Memory. Require Import Globalenvs. Require Import Smallstep. Require Import Ctypes. Require Import Cop. Require Import Clight. Require Import Cminor. Require Import Csharpminor. Require Import Cshmgen. Require Import Clight_coop. Require Import Clight_eff. Require Import Csharpminor_coop. Require Import Csharpminor_eff. Require Import mem_lemmas. Require Import semantics. Require Import semantics_lemmas. Require Import effect_semantics. Require Import structured_injections. Require Import reach. Require Import simulations. Require Import effect_properties. Require Import simulations_lemmas. Require Import BuiltinEffects. Lemma assign_loc_freshloc: forall ty m b ofs v m' (AL:assign_loc ty m b ofs v m'), freshloc m m' = fun b => false. Proof. intros. inv AL. apply (storev_freshloc _ _ _ _ _ H0). apply (storebytes_freshloc _ _ _ _ _ H4). Qed. (** * Properties of operations over types *) Remark transl_params_types: forall params, map typ_of_type (map snd params) = typlist_of_typelist (type_of_params params). Proof. induction params; simpl. auto. destruct a as [id ty]; simpl. f_equal; auto. Qed. Lemma transl_fundef_sig1: forall f tf args res, transl_fundef f = OK tf -> classify_fun (type_of_fundef f) = fun_case_f args res -> funsig tf = signature_of_type args res. Proof. intros. destruct f; simpl in *. monadInv H. monadInv EQ. simpl. inversion H0. unfold signature_of_function, signature_of_type. f_equal. apply transl_params_types. destruct (list_typ_eq (sig_args (ef_sig e)) (typlist_of_typelist t)); simpl in H. destruct (opt_typ_eq (sig_res (ef_sig e)) (opttyp_of_type t0)); simpl in H. inv H. simpl. destruct (ef_sig e); simpl in *. inv H0. unfold signature_of_type. auto. congruence. congruence. Qed. Lemma transl_fundef_sig2: forall f tf args res, transl_fundef f = OK tf -> type_of_fundef f = Tfunction args res -> funsig tf = signature_of_type args res. Proof. intros. eapply transl_fundef_sig1; eauto. rewrite H0; reflexivity. Qed. (** * Properties of the translation functions *) (** Transformation of expressions and statements. *) Lemma transl_expr_lvalue: forall ge e le m a loc ofs ta, Clight.eval_lvalue ge e le m a loc ofs -> transl_expr a = OK ta -> (exists tb, transl_lvalue a = OK tb /\ make_load tb (typeof a) = OK ta). Proof. intros until ta; intros EVAL TR. inv EVAL; simpl in TR. (* var local *) exists (Eaddrof id); auto. (* var global *) exists (Eaddrof id); auto. (* deref *) monadInv TR. exists x; auto. (* field struct *) rewrite H0 in TR. monadInv TR. econstructor; split. simpl. rewrite H0. rewrite EQ; rewrite EQ1; simpl; eauto. auto. (* field union *) rewrite H0 in TR. monadInv TR. econstructor; split. simpl. rewrite H0. rewrite EQ; simpl; eauto. auto. Qed. (** Properties of labeled statements *) Lemma transl_lbl_stmt_1: forall tyret nbrk ncnt n sl tsl, transl_lbl_stmt tyret nbrk ncnt sl = OK tsl -> transl_lbl_stmt tyret nbrk ncnt (Clight.select_switch n sl) = OK (select_switch n tsl). Proof. induction sl; intros. monadInv H. simpl. rewrite EQ. auto. generalize H; intro TR. monadInv TR. simpl. destruct (Int.eq i n). auto. auto. Qed. Lemma transl_lbl_stmt_2: forall tyret nbrk ncnt sl tsl, transl_lbl_stmt tyret nbrk ncnt sl = OK tsl -> transl_statement tyret nbrk ncnt (seq_of_labeled_statement sl) = OK (seq_of_lbl_stmt tsl). Proof. induction sl; intros. monadInv H. simpl. auto. monadInv H. simpl. rewrite EQ; simpl. rewrite (IHsl _ EQ1). simpl. auto. Qed. (** * Correctness of Csharpminor construction functions *) Section CONSTRUCTORS. (*NEW*) Variable hf : I64Helpers.helper_functions. Variable ge: genv. Lemma make_intconst_correct: forall n e le m, eval_expr ge e le m (make_intconst n) (Vint n). Proof. intros. unfold make_intconst. econstructor. reflexivity. Qed. Lemma make_floatconst_correct: forall n e le m, eval_expr ge e le m (make_floatconst n) (Vfloat n). Proof. intros. unfold make_floatconst. econstructor. reflexivity. Qed. Lemma make_longconst_correct: forall n e le m, eval_expr ge e le m (make_longconst n) (Vlong n). Proof. intros. unfold make_floatconst. econstructor. reflexivity. Qed. Lemma make_floatofint_correct: forall a n sg sz e le m, eval_expr ge e le m a (Vint n) -> eval_expr ge e le m (make_floatofint a sg sz) (Vfloat(cast_int_float sg sz n)). Proof. intros. unfold make_floatofint, cast_int_float. destruct sz. destruct sg. rewrite Float.singleofint_floatofint. econstructor. econstructor; eauto. simpl; reflexivity. auto. rewrite Float.singleofintu_floatofintu. econstructor. econstructor; eauto. simpl; reflexivity. auto. destruct sg; econstructor; eauto. Qed. Lemma make_intoffloat_correct: forall e le m a sg f i, eval_expr ge e le m a (Vfloat f) -> cast_float_int sg f = Some i -> eval_expr ge e le m (make_intoffloat a sg) (Vint i). Proof. unfold cast_float_int, make_intoffloat; intros. destruct sg; econstructor; eauto; simpl; rewrite H0; auto. Qed. Lemma make_longofint_correct: forall a n sg e le m, eval_expr ge e le m a (Vint n) -> eval_expr ge e le m (make_longofint a sg) (Vlong(cast_int_long sg n)). Proof. intros. unfold make_longofint, cast_int_long. destruct sg; econstructor; eauto. Qed. Lemma make_floatoflong_correct: forall a n sg sz e le m, eval_expr ge e le m a (Vlong n) -> eval_expr ge e le m (make_floatoflong a sg sz) (Vfloat(cast_long_float sg sz n)). Proof. intros. unfold make_floatoflong, cast_int_long. destruct sg; destruct sz; econstructor; eauto. Qed. Lemma make_longoffloat_correct: forall e le m a sg f i, eval_expr ge e le m a (Vfloat f) -> cast_float_long sg f = Some i -> eval_expr ge e le m (make_longoffloat a sg) (Vlong i). Proof. unfold cast_float_long, make_longoffloat; intros. destruct sg; econstructor; eauto; simpl; rewrite H0; auto. Qed. Hint Resolve make_intconst_correct make_floatconst_correct make_longconst_correct make_floatofint_correct make_intoffloat_correct make_longofint_correct make_floatoflong_correct make_longoffloat_correct eval_Eunop eval_Ebinop: cshm. Hint Extern 2 (@eq trace _ _) => traceEq: cshm. Lemma make_cmp_ne_zero_correct: forall e le m a n, eval_expr ge e le m a (Vint n) -> eval_expr ge e le m (make_cmp_ne_zero a) (Vint (if Int.eq n Int.zero then Int.zero else Int.one)). Proof. intros. assert (DEFAULT: eval_expr ge e le m (Ebinop (Ocmp Cne) a (make_intconst Int.zero)) (Vint (if Int.eq n Int.zero then Int.zero else Int.one))). econstructor; eauto with cshm. simpl. unfold Val.cmp, Val.cmp_bool. unfold Int.cmp. destruct (Int.eq n Int.zero); auto. assert (CMP: forall ob, Val.of_optbool ob = Vint n -> n = (if Int.eq n Int.zero then Int.zero else Int.one)). intros. destruct ob; simpl in H0; inv H0. destruct b; inv H2. rewrite Int.eq_false. auto. apply Int.one_not_zero. rewrite Int.eq_true. auto. destruct a; simpl; auto. destruct b; auto. inv H. econstructor; eauto. rewrite H6. decEq. decEq. simpl in H6. inv H6. unfold Val.cmp in H0. eauto. inv H. econstructor; eauto. rewrite H6. decEq. decEq. simpl in H6. inv H6. unfold Val.cmp in H0. eauto. inv H. econstructor; eauto. rewrite H6. decEq. decEq. simpl in H6. inv H6. unfold Val.cmp in H0. eauto. inv H. econstructor; eauto. rewrite H6. decEq. decEq. simpl in H6. unfold Val.cmpl in H6. destruct (Val.cmpl_bool c v1 v2) as [[]|]; inv H6; reflexivity. inv H. econstructor; eauto. rewrite H6. decEq. decEq. simpl in H6. unfold Val.cmplu in H6. destruct (Val.cmplu_bool c v1 v2) as [[]|]; inv H6; reflexivity. Qed. Lemma make_cast_int_correct: forall e le m a n sz si, eval_expr ge e le m a (Vint n) -> eval_expr ge e le m (make_cast_int a sz si) (Vint (cast_int_int sz si n)). Proof. intros. unfold make_cast_int, cast_int_int. destruct sz. destruct si; eauto with cshm. destruct si; eauto with cshm. auto. apply make_cmp_ne_zero_correct; auto. Qed. Lemma make_cast_float_correct: forall e le m a n sz, eval_expr ge e le m a (Vfloat n) -> eval_expr ge e le m (make_cast_float a sz) (Vfloat (cast_float_float sz n)). Proof. intros. unfold make_cast_float, cast_float_float. destruct sz. eauto with cshm. auto. Qed. Hint Resolve make_cast_int_correct make_cast_float_correct: cshm. Lemma make_cast_correct: forall e le m a b v ty1 ty2 v', make_cast ty1 ty2 a = OK b -> eval_expr ge e le m a v -> sem_cast v ty1 ty2 = Some v' -> eval_expr ge e le m b v'. Proof. intros. unfold make_cast, sem_cast in *; destruct (classify_cast ty1 ty2); inv H; destruct v; inv H1; eauto with cshm. (* float -> int *) destruct (cast_float_int si2 f) as [i|] eqn:E; inv H2. eauto with cshm. (* float -> long *) destruct (cast_float_long si2 f) as [i|] eqn:E; inv H2. eauto with cshm. (* float -> bool *) econstructor; eauto with cshm. simpl. unfold Val.cmpf, Val.cmpf_bool. rewrite Float.cmp_ne_eq. destruct (Float.cmp Ceq f Float.zero); auto. (* long -> bool *) econstructor; eauto with cshm. simpl. unfold Val.cmpl, Val.cmpl_bool, Int64.cmp. destruct (Int64.eq i Int64.zero); auto. (* int -> bool *) econstructor; eauto with cshm. simpl. unfold Val.cmpu, Val.cmpu_bool, Int.cmpu. destruct (Int.eq i Int.zero); auto. (* struct *) destruct (ident_eq id1 id2 && fieldlist_eq fld1 fld2); inv H2; auto. (* union *) destruct (ident_eq id1 id2 && fieldlist_eq fld1 fld2); inv H2; auto. Qed. Lemma make_neg_correct: forall a tya c va v e le m, sem_neg va tya = Some v -> make_neg a tya = OK c -> eval_expr ge e le m a va -> eval_expr ge e le m c v. Proof. unfold sem_neg, make_neg; intros until m; intros SEM MAKE EV1; destruct (classify_neg tya); inv MAKE; destruct va; inv SEM; eauto with cshm. Qed. Lemma make_notbool_correct: forall a tya c va v e le m, sem_notbool va tya = Some v -> make_notbool a tya = OK c -> eval_expr ge e le m a va -> eval_expr ge e le m c v. Proof. unfold sem_notbool, make_notbool; intros until m; intros SEM MAKE EV1; destruct (classify_bool tya); inv MAKE; destruct va; inv SEM; eauto with cshm. Qed. Lemma make_notint_correct: forall a tya c va v e le m, sem_notint va tya = Some v -> make_notint a tya = OK c -> eval_expr ge e le m a va -> eval_expr ge e le m c v. Proof. unfold sem_notint, make_notint; intros until m; intros SEM MAKE EV1; destruct (classify_notint tya); inv MAKE; destruct va; inv SEM; eauto with cshm. Qed. Definition binary_constructor_correct (make: expr -> type -> expr -> type -> res expr) (sem: val -> type -> val -> type -> option val): Prop := forall a tya b tyb c va vb v e le m, sem va tya vb tyb = Some v -> make a tya b tyb = OK c -> eval_expr ge e le m a va -> eval_expr ge e le m b vb -> eval_expr ge e le m c v. Section MAKE_BIN. Variable sem_int: signedness -> int -> int -> option val. Variable sem_long: signedness -> int64 -> int64 -> option val. Variable sem_float: float -> float -> option val. Variables iop iopu fop lop lopu: binary_operation. Hypothesis iop_ok: forall x y m, eval_binop iop (Vint x) (Vint y) m = sem_int Signed x y. Hypothesis iopu_ok: forall x y m, eval_binop iopu (Vint x) (Vint y) m = sem_int Unsigned x y. Hypothesis lop_ok: forall x y m, eval_binop lop (Vlong x) (Vlong y) m = sem_long Signed x y. Hypothesis lopu_ok: forall x y m, eval_binop lopu (Vlong x) (Vlong y) m = sem_long Unsigned x y. Hypothesis fop_ok: forall x y m, eval_binop fop (Vfloat x) (Vfloat y) m = sem_float x y. Lemma make_binarith_correct: binary_constructor_correct (make_binarith iop iopu fop lop lopu) (sem_binarith sem_int sem_long sem_float). Proof. red; unfold make_binarith, sem_binarith; intros until m; intros SEM MAKE EV1 EV2. set (cls := classify_binarith tya tyb) in *. set (ty := binarith_type cls) in *. monadInv MAKE. destruct (sem_cast va tya ty) as [va'|] eqn:Ca; try discriminate. destruct (sem_cast vb tyb ty) as [vb'|] eqn:Cb; try discriminate. exploit make_cast_correct. eexact EQ. eauto. eauto. intros EV1'. exploit make_cast_correct. eexact EQ1. eauto. eauto. intros EV2'. destruct cls; inv EQ2; destruct va'; try discriminate; destruct vb'; try discriminate. - destruct s; inv H0; econstructor; eauto with cshm. rewrite iop_ok; auto. rewrite iopu_ok; auto. - destruct s; inv H0; econstructor; eauto with cshm. rewrite lop_ok; auto. rewrite lopu_ok; auto. - erewrite <- fop_ok in SEM; eauto with cshm. Qed. Lemma make_binarith_int_correct: binary_constructor_correct (make_binarith_int iop iopu lop lopu) (sem_binarith sem_int sem_long (fun x y => None)). Proof. red; unfold make_binarith_int, sem_binarith; intros until m; intros SEM MAKE EV1 EV2. set (cls := classify_binarith tya tyb) in *. set (ty := binarith_type cls) in *. monadInv MAKE. destruct (sem_cast va tya ty) as [va'|] eqn:Ca; try discriminate. destruct (sem_cast vb tyb ty) as [vb'|] eqn:Cb; try discriminate. exploit make_cast_correct. eexact EQ. eauto. eauto. intros EV1'. exploit make_cast_correct. eexact EQ1. eauto. eauto. intros EV2'. destruct cls; inv EQ2; destruct va'; try discriminate; destruct vb'; try discriminate. - destruct s; inv H0; econstructor; eauto with cshm. rewrite iop_ok; auto. rewrite iopu_ok; auto. - destruct s; inv H0; econstructor; eauto with cshm. rewrite lop_ok; auto. rewrite lopu_ok; auto. Qed. End MAKE_BIN. Hint Extern 2 (@eq (option val) _ _) => (simpl; reflexivity) : cshm. Lemma make_add_correct: binary_constructor_correct make_add sem_add. Proof. red; unfold make_add, sem_add; intros until m; intros SEM MAKE EV1 EV2; destruct (classify_add tya tyb); inv MAKE. - destruct va; try discriminate; destruct vb; inv SEM; eauto with cshm. - destruct va; try discriminate; destruct vb; inv SEM; eauto with cshm. - destruct va; try discriminate; destruct vb; inv SEM; eauto with cshm. - destruct va; try discriminate; destruct vb; inv SEM; eauto with cshm. - eapply make_binarith_correct; eauto; intros; auto. Qed. Lemma make_sub_correct: binary_constructor_correct make_sub sem_sub. Proof. red; unfold make_sub, sem_sub; intros until m; intros SEM MAKE EV1 EV2; destruct (classify_sub tya tyb); inv MAKE. - destruct va; try discriminate; destruct vb; inv SEM; eauto with cshm. - destruct va; try discriminate; destruct vb; inv SEM. destruct (eq_block b0 b1); try discriminate. destruct (Int.eq (Int.repr (sizeof ty)) Int.zero) eqn:E; inv H0. econstructor; eauto with cshm. rewrite dec_eq_true. simpl. rewrite E; auto. - destruct va; try discriminate; destruct vb; inv SEM; eauto with cshm. - eapply make_binarith_correct; eauto; intros; auto. Qed. Lemma make_mul_correct: binary_constructor_correct make_mul sem_mul. Proof. apply make_binarith_correct; intros; auto. Qed. Lemma make_div_correct: binary_constructor_correct make_div sem_div. Proof. apply make_binarith_correct; intros; auto. Qed. Lemma make_mod_correct: binary_constructor_correct make_mod sem_mod. Proof. apply make_binarith_int_correct; intros; auto. Qed. Lemma make_and_correct: binary_constructor_correct make_and sem_and. Proof. apply make_binarith_int_correct; intros; auto. Qed. Lemma make_or_correct: binary_constructor_correct make_or sem_or. Proof. apply make_binarith_int_correct; intros; auto. Qed. Lemma make_xor_correct: binary_constructor_correct make_xor sem_xor. Proof. apply make_binarith_int_correct; intros; auto. Qed. Ltac comput val := let x := fresh in set val as x in *; vm_compute in x; subst x. Remark small_shift_amount_1: forall i, Int64.ltu i Int64.iwordsize = true -> Int.ltu (Int64.loword i) Int64.iwordsize' = true /\ Int64.unsigned i = Int.unsigned (Int64.loword i). Proof. intros. apply Int64.ltu_inv in H. comput (Int64.unsigned Int64.iwordsize). assert (Int64.unsigned i = Int.unsigned (Int64.loword i)). { unfold Int64.loword. rewrite Int.unsigned_repr; auto. comput Int.max_unsigned; omega. } split; auto. unfold Int.ltu. apply zlt_true. rewrite <- H0. tauto. Qed. Remark small_shift_amount_2: forall i, Int64.ltu i (Int64.repr 32) = true -> Int.ltu (Int64.loword i) Int.iwordsize = true. Proof. intros. apply Int64.ltu_inv in H. comput (Int64.unsigned (Int64.repr 32)). assert (Int64.unsigned i = Int.unsigned (Int64.loword i)). { unfold Int64.loword. rewrite Int.unsigned_repr; auto. comput Int.max_unsigned; omega. } unfold Int.ltu. apply zlt_true. rewrite <- H0. tauto. Qed. Lemma small_shift_amount_3: forall i, Int.ltu i Int64.iwordsize' = true -> Int64.unsigned (Int64.repr (Int.unsigned i)) = Int.unsigned i. Proof. intros. apply Int.ltu_inv in H. comput (Int.unsigned Int64.iwordsize'). apply Int64.unsigned_repr. comput Int64.max_unsigned; omega. Qed. Lemma make_shl_correct: binary_constructor_correct make_shl sem_shl. Proof. red; unfold make_shl, sem_shl, sem_shift; intros until m; intros SEM MAKE EV1 EV2; destruct (classify_shift tya tyb); inv MAKE; destruct va; try discriminate; destruct vb; try discriminate. - destruct (Int.ltu i0 Int.iwordsize) eqn:E; inv SEM. econstructor; eauto. simpl; rewrite E; auto. - destruct (Int64.ltu i0 Int64.iwordsize) eqn:E; inv SEM. exploit small_shift_amount_1; eauto. intros [A B]. econstructor; eauto with cshm. simpl. rewrite A. f_equal; f_equal. unfold Int64.shl', Int64.shl. rewrite B; auto. - destruct (Int64.ltu i0 (Int64.repr 32)) eqn:E; inv SEM. econstructor; eauto with cshm. simpl. rewrite small_shift_amount_2; auto. - destruct (Int.ltu i0 Int64.iwordsize') eqn:E; inv SEM. econstructor; eauto with cshm. simpl. rewrite E. unfold Int64.shl', Int64.shl. rewrite small_shift_amount_3; auto. Qed. Lemma make_shr_correct: binary_constructor_correct make_shr sem_shr. Proof. red; unfold make_shr, sem_shr, sem_shift; intros until m; intros SEM MAKE EV1 EV2; destruct (classify_shift tya tyb); inv MAKE; destruct va; try discriminate; destruct vb; try discriminate. - destruct (Int.ltu i0 Int.iwordsize) eqn:E; inv SEM. destruct s; inv H0; econstructor; eauto; simpl; rewrite E; auto. - destruct (Int64.ltu i0 Int64.iwordsize) eqn:E; inv SEM. exploit small_shift_amount_1; eauto. intros [A B]. destruct s; inv H0; econstructor; eauto with cshm; simpl; rewrite A; f_equal; f_equal. unfold Int64.shr', Int64.shr; rewrite B; auto. unfold Int64.shru', Int64.shru; rewrite B; auto. - destruct (Int64.ltu i0 (Int64.repr 32)) eqn:E; inv SEM. destruct s; inv H0; econstructor; eauto with cshm; simpl; rewrite small_shift_amount_2; auto. - destruct (Int.ltu i0 Int64.iwordsize') eqn:E; inv SEM. destruct s; inv H0; econstructor; eauto with cshm; simpl; rewrite E. unfold Int64.shr', Int64.shr; rewrite small_shift_amount_3; auto. unfold Int64.shru', Int64.shru; rewrite small_shift_amount_3; auto. Qed. Lemma make_cmp_correct: forall cmp a tya b tyb c va vb v e le m, sem_cmp cmp va tya vb tyb m = Some v -> make_cmp cmp a tya b tyb = OK c -> eval_expr ge e le m a va -> eval_expr ge e le m b vb -> eval_expr ge e le m c v. Proof. unfold sem_cmp, make_cmp; intros until m; intros SEM MAKE EV1 EV2; destruct (classify_cmp tya tyb). - inv MAKE. destruct (Val.cmpu_bool (Mem.valid_pointer m) cmp va vb) as [bv|] eqn:E; simpl in SEM; inv SEM. econstructor; eauto. simpl. unfold Val.cmpu. rewrite E. auto. - inv MAKE. destruct vb; try discriminate. set (vb := Vint (Int.repr (Int64.unsigned i))) in *. destruct (Val.cmpu_bool (Mem.valid_pointer m) cmp va vb) as [bv|] eqn:E; simpl in SEM; inv SEM. econstructor; eauto with cshm. simpl. change (Vint (Int64.loword i)) with vb. unfold Val.cmpu. rewrite E. auto. - inv MAKE. destruct va; try discriminate. set (va := Vint (Int.repr (Int64.unsigned i))) in *. destruct (Val.cmpu_bool (Mem.valid_pointer m) cmp va vb) as [bv|] eqn:E; simpl in SEM; inv SEM. econstructor; eauto with cshm. simpl. change (Vint (Int64.loword i)) with va. unfold Val.cmpu. rewrite E. auto. - eapply make_binarith_correct; eauto; intros; auto. Qed. Lemma transl_unop_correct: forall op a tya c va v e le m, transl_unop op a tya = OK c -> sem_unary_operation op va tya = Some v -> eval_expr ge e le m a va -> eval_expr ge e le m c v. Proof. intros. destruct op; simpl in *. eapply make_notbool_correct; eauto. eapply make_notint_correct; eauto. eapply make_neg_correct; eauto. Qed. Lemma transl_binop_correct: forall op a tya b tyb c va vb v e le m, transl_binop op a tya b tyb = OK c -> sem_binary_operation op va tya vb tyb m = Some v -> eval_expr ge e le m a va -> eval_expr ge e le m b vb -> eval_expr ge e le m c v. Proof. intros. destruct op; simpl in *. eapply make_add_correct; eauto. eapply make_sub_correct; eauto. eapply make_mul_correct; eauto. eapply make_div_correct; eauto. eapply make_mod_correct; eauto. eapply make_and_correct; eauto. eapply make_or_correct; eauto. eapply make_xor_correct; eauto. eapply make_shl_correct; eauto. eapply make_shr_correct; eauto. eapply make_cmp_correct; eauto. eapply make_cmp_correct; eauto. eapply make_cmp_correct; eauto. eapply make_cmp_correct; eauto. eapply make_cmp_correct; eauto. eapply make_cmp_correct; eauto. Qed. Lemma make_load_correct: forall addr ty code b ofs v e le m, make_load addr ty = OK code -> eval_expr ge e le m addr (Vptr b ofs) -> deref_loc ty m b ofs v -> eval_expr ge e le m code v. Proof. unfold make_load; intros until m; intros MKLOAD EVEXP DEREF. inv DEREF. (* scalar *) rewrite H in MKLOAD. inv MKLOAD. apply eval_Eload with (Vptr b ofs); auto. (* by reference *) rewrite H in MKLOAD. inv MKLOAD. auto. (* by copy *) rewrite H in MKLOAD. inv MKLOAD. auto. Qed. Lemma make_memcpy_correct_BuiltinEffect: forall f dst src ty k e le m b ofs v m', eval_expr ge e le m dst (Vptr b ofs) -> eval_expr ge e le m src v -> assign_loc ty m b ofs v m' -> access_mode ty = By_copy -> exists b' ofs', v = Vptr b' ofs' /\ effstep (csharpmin_eff_sem hf) ge (BuiltinEffect ge (EF_memcpy (sizeof ty) (alignof_blockcopy ty)) (Vptr b ofs :: Vptr b' ofs' :: nil) m) (CSharpMin_State f (make_memcpy dst src ty) k e le) m (CSharpMin_State f Sskip k e le) m'. Proof. intros. inv H1; try congruence. unfold make_memcpy. change le with (set_optvar None Vundef le) at 2. exists b', ofs'. split; trivial. econstructor. econstructor. eauto. econstructor. eauto. constructor. econstructor; eauto. apply alignof_blockcopy_1248. apply sizeof_pos. eapply Zdivide_trans. apply alignof_blockcopy_divides. apply sizeof_alignof_compat. simpl. auto. Qed. Lemma make_store_correct_StoreEffect: forall addr ty rhs code e le m b ofs v m' f k, make_store addr ty rhs = OK code -> eval_expr ge e le m addr (Vptr b ofs) -> eval_expr ge e le m rhs v -> assign_loc ty m b ofs v m' -> match access_mode ty with By_value chunk => effstep (csharpmin_eff_sem hf) ge (StoreEffect (Vptr b ofs) (encode_val chunk v)) (CSharpMin_State f code k e le) m (CSharpMin_State f Sskip k e le) m' | By_copy => exists b' ofs', v = Vptr b' ofs' /\ effstep (csharpmin_eff_sem hf) ge (BuiltinEffect ge (EF_memcpy (sizeof ty) (alignof_blockcopy ty)) (Vptr b ofs :: Vptr b' ofs' :: nil) m) (CSharpMin_State f code k e le) m (CSharpMin_State f Sskip k e le) m' | _ => False end. Proof. unfold make_store. intros until k; intros MKSTORE EV1 EV2 ASSIGN. inversion ASSIGN; subst. (* nonvolatile scalar *) rewrite H in MKSTORE; inv MKSTORE. rewrite H. econstructor; eauto. (* by copy *) rewrite H in MKSTORE; inv MKSTORE. rewrite H. (* [memcpy] *) eapply make_memcpy_correct_BuiltinEffect; eauto. Qed. End CONSTRUCTORS. (** * Basic preservation invariants *) Section CORRECTNESS. Variable prog: Clight.program. Variable tprog: Csharpminor.program. Hypothesis TRANSL: transl_program prog = OK tprog. Let ge : Clight.genv := Genv.globalenv prog. Let tge : Csharpminor.genv := Genv.globalenv tprog. (*NEW*) Variable hf : I64Helpers.helper_functions. Lemma symbols_preserved: forall s, Genv.find_symbol tge s = Genv.find_symbol ge s. Proof (Genv.find_symbol_transf_partial2 transl_fundef transl_globvar _ TRANSL). Lemma functions_translated: forall v f, Genv.find_funct ge v = Some f -> exists tf, Genv.find_funct tge v = Some tf /\ transl_fundef f = OK tf. Proof (Genv.find_funct_transf_partial2 transl_fundef transl_globvar _ TRANSL). Lemma function_ptr_translated: forall b f, Genv.find_funct_ptr ge b = Some f -> exists tf, Genv.find_funct_ptr tge b = Some tf /\ transl_fundef f = OK tf. Proof (Genv.find_funct_ptr_transf_partial2 transl_fundef transl_globvar _ TRANSL). Lemma var_info_translated: forall b v, Genv.find_var_info ge b = Some v -> exists tv, Genv.find_var_info tge b = Some tv /\ transf_globvar transl_globvar v = OK tv. Proof (Genv.find_var_info_transf_partial2 transl_fundef transl_globvar _ TRANSL). Lemma var_info_rev_translated: forall b tv, Genv.find_var_info tge b = Some tv -> exists v, Genv.find_var_info ge b = Some v /\ transf_globvar transl_globvar v = OK tv. Proof (Genv.find_var_info_rev_transf_partial2 transl_fundef transl_globvar _ TRANSL). Lemma block_is_volatile_preserved: forall b, block_is_volatile tge b = block_is_volatile ge b. Proof. intros. unfold block_is_volatile. destruct (Genv.find_var_info ge b) eqn:?. exploit var_info_translated; eauto. intros [tv [A B]]. rewrite A. unfold transf_globvar in B. monadInv B. auto. destruct (Genv.find_var_info tge b) eqn:?. exploit var_info_rev_translated; eauto. intros [tv [A B]]. congruence. auto. Qed. (** * Matching between environments *) (** In this section, we define a matching relation between a Clight local environment and a Csharpminor local environment. *) (*LENB: added parameter j - first, let's try an attempt where all offsets are 0*) Record match_env (j:meminj) (e: Clight.env) (te: Csharpminor.env) : Prop := mk_match_env { me_local: forall id b ty, e!id = Some (b, ty) -> exists b', j b = Some(b',0) /\ te!id = Some(b', sizeof ty); me_local_inv: forall id b sz, te!id = Some (b, sz) -> exists b' ty, j b' = Some(b,0) /\e!id = Some(b', ty) }. Lemma match_env_inject_incr: forall j e te (MENV : match_env j e te) j' (INC: inject_incr j j'), match_env j' e te. Proof. intros. destruct MENV as [MENVa MENVb]. split; intros. destruct (MENVa _ _ _ H) as [b' [J Eb]]. apply INC in J. exists b'; split; trivial. destruct (MENVb _ _ _ H) as [b' [tp [J Eb]]]. apply INC in J. exists b', tp; split; trivial. Qed. Lemma match_env_restrictD: forall j X e te (MENV : match_env (restrict j X) e te), match_env j e te. Proof. intros. eapply match_env_inject_incr; try eassumption. eapply restrict_incr. Qed. Lemma match_env_globals: forall j e te id, match_env j e te -> e!id = None -> te!id = None. Proof. intros. destruct (te!id) as [[b sz] | ] eqn:?; auto. exploit me_local_inv; eauto. intros [b' [ty [J EQ]]]. congruence. Qed. Lemma match_env_same_blocks: forall j e te (ENV: match_env j e te), list_forall2 (fun (i_x : positive * (block * type)) (i_y : positive * (block * Z)) => fst i_x = fst i_y /\ j (fst (snd i_x)) = Some (fst (snd i_y), 0) /\ snd (snd i_y) = sizeof (snd (snd i_x))) (PTree.elements e) (PTree.elements te). Proof. intros. assert (HH1: forall (i : positive) (x : block * type), e ! i = Some x -> exists y : block * Z, te ! i = Some y /\ j (fst x) = Some (fst y,0) /\ snd y = sizeof (snd x)). intros. destruct ENV. destruct x. destruct (me_local0 _ _ _ H) as [b' [J T]]. exists (b', sizeof t). simpl. split; trivial. split; trivial. assert(HH2: forall (i : positive) (y : block * Z), te ! i = Some y -> exists x : block * type, e ! i = Some x /\ j (fst x) = Some (fst y, 0) /\ snd y = sizeof (snd x)). intros. destruct ENV. destruct y. destruct (me_local_inv0 _ _ _ H) as [b' [t [J T]]]. exists (b', t). simpl. split; trivial. split; trivial. destruct (HH1 _ _ T) as [yy [TY [JY SZY]]]. simpl in *. rewrite H in TY. inv TY. rewrite JY in J; inv J. simpl in *. trivial. apply (PTree.elements_canonical_order _ e te HH1 HH2). Qed. Lemma match_env_free_blocks_parallel_inject: forall e te m m' j tm (ENV: match_env j e te) (INJ: Mem.inject j m tm) (FL: Mem.free_list m (Clight.blocks_of_env e) = Some m'), exists tm', Mem.free_list tm (blocks_of_env te) = Some tm' /\ Mem.inject j m' tm'. Proof. intros. apply match_env_same_blocks in ENV. clear - ENV FL INJ. unfold Clight.blocks_of_env in FL. unfold blocks_of_env. remember (PTree.elements e) as l; clear Heql. remember (PTree.elements te) as tl; clear Heqtl. generalize dependent tm. generalize dependent m'. generalize dependent m. clear - ENV. induction ENV; simpl; intros. inv FL. exists tm. split; trivial. remember (Clight.block_of_binding a1) as A1. unfold Clight.block_of_binding in HeqA1. destruct a1 as [id [b ty]]. subst. simpl in *. remember (Mem.free m b 0 (sizeof ty)) as d. destruct d; inv FL; apply eq_sym in Heqd. specialize (IHENV _ _ H1); clear H1. destruct b1 as [x [tb sizeT]]. destruct H as [? [J SZ]]. simpl in *. subst. destruct (free_parallel_inject _ _ _ _ _ _ _ INJ Heqd _ _ J) as [tm0 [FRT INJ0]]. destruct (IHENV _ INJ0) as [tm' [FL' INJ']]; clear IHENV. exists tm'. simpl in *. rewrite Zplus_0_r in FRT. rewrite FRT. split; trivial. Qed. Lemma freelist_freelist_inject: forall m1 m1' j m2 e (FL1: Mem.free_list m1 (Clight.blocks_of_env e) = Some m1') (INJ : Mem.inject j m1 m2) te (MENV : match_env j e te) m2' (FL2 : Mem.free_list m2 (blocks_of_env te) = Some m2'), Mem.inject j m1' m2'. Proof. intros. destruct (match_env_free_blocks_parallel_inject _ _ _ _ _ _ MENV INJ FL1) as [tm [FL_tm Inj_tm]]. rewrite FL_tm in FL2. inv FL2. assumption. Qed. Lemma FreelistEffect_PropagateLeft: forall m e m' (FL : Mem.free_list m (Clight.blocks_of_env e) = Some m') mu m2 (SMV : sm_valid mu m m2) (WD: SM_wd mu) te (MENV: match_env (restrict (as_inj mu) (vis mu)) e te) b2 ofs (EFF : FreelistEffect m2 (blocks_of_env te) b2 ofs = true) (LB: locBlocksTgt mu b2 = false), exists b1 delta, foreign_of mu b1 = Some (b2, delta) /\ FreelistEffect m (Clight.blocks_of_env e) b1 (ofs - delta) = true /\ Mem.perm m b1 (ofs - delta) Max Nonempty. Proof. intros. apply match_env_same_blocks in MENV. clear - MENV FL SMV EFF LB WD. unfold Clight.blocks_of_env in FL. unfold Clight.blocks_of_env. unfold blocks_of_env in EFF. remember (PTree.elements e) as l; clear Heql. remember (PTree.elements te) as tl; clear Heqtl. generalize dependent m2. generalize dependent m'. generalize dependent m. clear - MENV LB WD. induction MENV; simpl; intros. intuition. destruct a1 as [x [b tp]]. destruct b1 as [id [b' z]]. simpl in *. destruct H as [? [Rb ?]]; subst. remember (Mem.free m b 0 (sizeof tp)) as d. destruct d; inv FL; apply eq_sym in Heqd. apply orb_true_iff in EFF. destruct EFF as [EFF | EFF]. specialize (IHMENV _ _ H0). assert (SMV': sm_valid mu m0 m2). split; intros. eapply (Mem.valid_block_free_1 _ _ _ _ _ Heqd). eapply SMV; eassumption. eapply SMV; eassumption. destruct (IHMENV _ SMV' EFF) as [b1 [delta [Frg [FL2 P]]]]. exists b1, delta; intuition. apply orb_true_iff; left. remember (map Clight.block_of_binding al) as t. clear - Heqd FL2. generalize dependent m0. generalize dependent m. induction t; simpl; intros. assumption. destruct a as [[bb lo] hi]. apply orb_true_iff in FL2. apply orb_true_iff. destruct FL2. apply (IHt _ _ Heqd) in H. left; trivial. right. clear IHt. unfold FreeEffect. unfold FreeEffect in H. destruct (valid_block_dec m0 b1). destruct (valid_block_dec m b1); trivial. apply (Mem.valid_block_free_2 _ _ _ _ _ Heqd) in v. contradiction. inv H. eapply Mem.perm_free_3; eassumption. destruct (restrictD_Some _ _ _ _ _ Rb). destruct (FreeEffect_PropagateLeft _ _ _ _ _ Heqd _ _ SMV WD _ H H1 _ _ EFF LB) as [b1 [delta [Frg [EFF1 P1]]]]. exists b1, delta. rewrite EFF1. intuition. Qed. Lemma match_env_empty: forall j, match_env j Clight.empty_env Csharpminor.empty_env. Proof. unfold Clight.empty_env, Csharpminor.empty_env. constructor. intros until ty. repeat rewrite PTree.gempty. congruence. intros until sz. rewrite PTree.gempty. congruence. Qed. (** The following lemmas establish the [match_env] invariant at the beginning of a function invocation, after allocation of local variables and initialization of the parameters. *) Lemma match_env_alloc_variables: forall vars e1 m1 e2 m2, Clight.alloc_variables e1 m1 vars e2 m2 -> forall mu te1 tm1, match_env (restrict (as_inj mu) (vis mu)) e1 te1 -> Mem.inject (as_inj mu) m1 tm1 -> SM_wd mu -> sm_valid mu m1 tm1 -> exists te2 tm2 mu', Csharpminor.alloc_variables te1 tm1 (map transl_var vars) te2 tm2 /\ match_env (restrict (as_inj mu') (vis mu')) e2 te2 /\ Mem.inject (as_inj mu') m2 tm2 /\ intern_incr mu mu' /\ sm_inject_separated mu mu' m1 tm1 /\ sm_locally_allocated mu mu' m1 tm1 m2 tm2 /\ SM_wd mu' /\ sm_valid mu' m2 tm2 /\ (REACH_closed m1 (vis mu) -> REACH_closed m2 (vis mu')). Proof. intros vars. induction vars; intros; simpl; inv H. exists te1, tm1, mu. intuition. constructor. apply intern_incr_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite freshloc_irrefl; intuition. specialize (IHvars _ _ _ _ H11). exploit (alloc_parallel_intern mu); try eassumption. apply Zle_refl. apply Zle_refl. intros [mu0 [tm0 [b2 [Alloc2 [INJ0 [IntInc0 [A [B [C [D [E [F G]]]]]]]]]]]]. assert (VisB1: vis mu0 b1 = true). assert (DomSrc mu0 b1 = true). eapply as_inj_DomRng; eassumption. unfold DomSrc in H. unfold vis. remember (locBlocksSrc mu0 b1) as d. destruct d; simpl in *; trivial. assert (extBlocksSrc mu = extBlocksSrc mu0) by eapply IntInc0. rewrite <- H4 in H. elim (Mem.fresh_block_alloc _ _ _ _ _ H8). eapply H3. unfold DOM, DomSrc. intuition. assert (MENV0 :match_env (restrict (as_inj mu0) (vis mu0)) (PTree.set id (b1, ty) e1) (PTree.set id (b2, sizeof ty) te1)). clear IHvars. constructor. (* me_local *) intros until ty0. repeat rewrite PTree.gsspec. destruct (peq id0 id); intros. inv H. exists b2; split; trivial. eapply restrictI_Some; assumption. destruct (me_local _ _ _ H0 _ _ _ H) as [b' [AI TE]]. exists b'; split; trivial. eapply intern_incr_restrict; eassumption. (* me_local_inv *) intros until sz. repeat rewrite PTree.gsspec. destruct (peq id0 id); intros. inv H. exists b1, ty; split; trivial. apply restrictI_Some; trivial. destruct (me_local_inv _ _ _ H0 _ _ _ H) as [b' [tp [AI TE]]]. exists b', tp; split; trivial. eapply intern_incr_restrict; eassumption. destruct (IHvars mu0 _ _ MENV0 INJ0 E F) as [te2 [tm2 [mu' [AVars' [MENV' [INJ' [IntInc' [SEP' [LAC' [WD' [VAL' RC']]]]]]]]]]]. simpl. exists te2, tm2, mu'. intuition. econstructor; eassumption. eapply intern_incr_trans; eassumption. eapply intern_separated_incr_fwd2; try eassumption. eapply alloc_forward; eassumption. eapply alloc_forward; eassumption. eapply sm_locally_allocated_trans; try eassumption. eapply alloc_forward; eassumption. eapply Clight_coop.alloc_variables_forward; try eassumption. eapply alloc_forward; eassumption. eapply alloc_variables_forward; try eassumption. Qed. Definition match_tempenv (j:meminj) (le: temp_env) (tle: Csharpminor.temp_env) := forall id v, le!id = Some v -> exists tv, val_inject j v tv /\ tle!id = Some tv. Lemma match_tempenv_inject_incr: forall j e te (TENV : match_tempenv j e te) j' (INC: inject_incr j j'), match_tempenv j' e te. Proof. red; intros. destruct (TENV _ _ H) as [v' [V' Tv']]. exists v'; split; trivial. eapply val_inject_incr; eassumption. Qed. Lemma match_tempenv_set: forall j le tle (TENV : match_tempenv j le tle) v tv (Inj : val_inject j v tv) x, match_tempenv j (PTree.set x v le) (PTree.set x tv tle). Proof. intros. red; intros. rewrite PTree.gsspec in H. rewrite PTree.gsspec. destruct (peq id x); subst. inv H. exists tv; split; trivial. apply (TENV _ _ H). Qed. Lemma create_undef_temps_match: forall temps, create_undef_temps (map fst temps) = Clight.create_undef_temps temps. Proof. induction temps; simpl. auto. destruct a as [id ty]. simpl. decEq. auto. Qed. Lemma create_undef_temps_match_inject: forall temps j, match_tempenv j (Clight.create_undef_temps temps) (create_undef_temps (map fst temps)). Proof. induction temps; simpl. intros. red; intros. rewrite PTree.gempty in H; discriminate. intros. destruct a as [id ty]. simpl. red; intros. rewrite PTree.gsspec in H. rewrite PTree.gsspec. destruct (peq id0 id); subst. inv H. exists Vundef; split; trivial. apply (IHtemps j id0 _ H). Qed. Lemma bind_parameter_temps_match_inject: forall vars vals le1 le2 (BP: Clight.bind_parameter_temps vars vals le1 = Some le2) j tle1 (TENV: match_tempenv j le1 tle1) tvals (Inj: val_list_inject j vals tvals), exists tle2, bind_parameters (map fst vars) tvals tle1 = Some tle2 /\ match_tempenv j le2 tle2. Proof. induction vars; simpl; intros. destruct vals; inv BP. inv Inj. exists tle1; split; trivial. destruct a as [id ty]. destruct vals; try discriminate. inv Inj. assert (TE:= match_tempenv_set _ _ _ TENV _ _ H1 id). apply (IHvars _ _ _ BP _ _ TE _ H3). Qed. (* Lemma bind_parameter_temps_match: forall vars vals le1 le2, Clight.bind_parameter_temps vars vals le1 = Some le2 -> bind_parameters (map fst vars) vals le1 = Some le2. Proof. induction vars; simpl; intros. destruct vals; inv H. auto. destruct a as [id ty]. destruct vals; try discriminate. auto. Qed. *) (** * Proof of semantic preservation *) (** ** Semantic preservation for expressions *) (** The proof of semantic preservation for the translation of expressions relies on simulation diagrams of the following form: << e, le, m, a ------------------- te, le, m, ta | | | | | | v v e, le, m, v ------------------- te, le, m, v >> Left: evaluation of r-value expression [a] in Clight. Right: evaluation of its translation [ta] in Csharpminor. Top (precondition): matching between environments [e], [te], plus well-typedness of expression [a]. Bottom (postcondition): the result values [v] are identical in both evaluations. We state these diagrams as the following properties, parameterized by the Clight evaluation. *) Lemma unary_op_inject: forall op v ty u (SUO:sem_unary_operation op v ty = Some u) j tv (V: val_inject j v tv), val_inject j u u /\ sem_unary_operation op tv ty = Some u. Proof. intros. destruct op; simpl in *. rewrite notbool_bool_val in *. remember (bool_val v ty) as q; apply eq_sym in Heqq. destruct q; inv SUO. split. apply val_inject_of_bool. rewrite (bool_val_inject _ _ _ _ _ Heqq V). trivial. unfold sem_notint in *. remember (classify_notint ty) as q; apply eq_sym in Heqq. destruct q; inv SUO. destruct v; inv H0. inv V. split. constructor. trivial. destruct v; inv H0. inv V. split. constructor. trivial. unfold sem_neg in *. remember (classify_neg ty) as q; apply eq_sym in Heqq. destruct q; inv SUO. destruct v; inv H0. inv V. split. constructor. trivial. destruct v; inv H0. inv V. split. constructor. trivial. destruct v; inv H0. inv V. split. constructor. trivial. Qed. Lemma unary_op_inject': forall op v ty u (SUO:sem_unary_operation op v ty = Some u) j tv (V: val_inject j v tv), exists tu, val_inject j u tu /\ sem_unary_operation op tv ty = Some tu. Proof. intros. exists u. eapply unary_op_inject; eassumption. Qed. Lemma binary_op_inject: forall op v1 v2 ty1 ty2 m u (SBO:sem_binary_operation op v1 ty1 v2 ty2 m = Some u) j tm (MINJ : Mem.inject j m tm) tv1 (V1: val_inject j v1 tv1) tv2 (V2: val_inject j v2 tv2), exists tu, sem_binary_operation op tv1 ty1 tv2 ty2 tm = Some tu /\ val_inject j u tu. Proof. intros. eapply sem_binary_operation_inj; try eassumption. intros. eapply Mem.valid_pointer_inject_val; try eassumption. econstructor. eassumption. trivial. intros. eapply Mem.weak_valid_pointer_inject_val; try eassumption. econstructor. eassumption. trivial. intros. eapply Mem.weak_valid_pointer_inject_no_overflow; try eassumption. intros. eapply Mem.different_pointers_inject; try eassumption. Qed. Section EXPR. Variable e: Clight.env. Variable le: temp_env. Variable m: mem. (*NEW: *) Variable tm: mem. Variable te: Csharpminor.env. Variable tle: Csharpminor.temp_env. Variable j: meminj. Hypothesis MENV: match_env j e te. Hypothesis LENV: match_tempenv j le tle. Hypothesis MINJ: Mem.inject j m tm. Hypothesis PG: meminj_preserves_globals ge j. Lemma deref_loc_inject: forall ty b ofs v (D:deref_loc ty m b ofs v) tb delta (J: j b = Some(tb,delta)), exists tv, val_inject j v tv /\ deref_loc ty tm tb (Int.add ofs (Int.repr delta)) tv. Proof. intros. inv D. (*case deref_loc_value*) assert (val_inject j (Vptr b ofs) (Vptr tb (Int.add ofs (Int.repr delta)))). econstructor. eassumption. trivial. destruct (Mem.loadv_inject _ _ _ _ _ _ _ MINJ H0 H1) as [tv [TLDV VI]]. exists tv; split; trivial. eapply (deref_loc_value); eassumption. (*case deref_loc_reference*) eexists; split. econstructor. eassumption. reflexivity. eapply (deref_loc_reference); assumption. (*case deref_loc_reference*) eexists; split. econstructor. eassumption. reflexivity. eapply (deref_loc_copy); assumption. Qed. Lemma transl_expr_lvalue_correct: (forall a v, Clight.eval_expr ge e le m a v -> forall ta (TR: transl_expr a = OK ta), exists tv, val_inject j v tv /\ Csharpminor.eval_expr tge te tle tm ta tv) /\(forall a b ofs, Clight.eval_lvalue ge e le m a b ofs -> forall ta (TR: transl_lvalue a = OK ta), exists tv, val_inject j (Vptr b ofs) tv /\ Csharpminor.eval_expr tge te tle tm ta tv). Proof. apply eval_expr_lvalue_ind; intros; try (monadInv TR). (* const int *) eexists. split. econstructor. apply make_intconst_correct. (* const float *) eexists. split. econstructor. apply make_floatconst_correct. (* const long *) eexists. split. econstructor. apply make_longconst_correct. (* temp var *) destruct (LENV _ _ H) as [tv [? ?]]. exists tv; split; trivial. constructor; auto. (* addrof *) inv TR. auto. (* unop *) destruct (H0 _ EQ) as [tv [VI EE]]; clear H0 EQ. destruct (unary_op_inject _ _ _ _ H1 _ _ VI); clear H1 VI. exists v; split; trivial. eapply transl_unop_correct; eauto. (* binop *) destruct (H0 _ EQ) as [tv1 [VI1 EE1]]; clear H0 EQ. destruct (H2 _ EQ1) as [tv2 [VI2 EE2]]; clear H2 EQ1. destruct (binary_op_inject _ _ _ _ _ _ _ H3 _ _ MINJ _ VI1 _ VI2) as [tv [TV ETV]]; clear H3 VI1 VI2. exists tv; split; trivial. eapply transl_binop_correct; eauto. (* cast *) destruct (H0 _ EQ) as [tv1 [TV1 ET1]]. clear H0. destruct (sem_cast_inject _ _ _ _ _ _ H1 TV1) as [tv [SC VI]]. exists tv; split; trivial. apply (make_cast_correct _ _ _ _ _ _ _ _ _ _ EQ0 ET1 SC). (* rvalue out of lvalue *) exploit transl_expr_lvalue; eauto. intros [tb [TRLVAL MKLOAD]]. destruct (H0 _ TRLVAL) as [tv [VT ET]]; clear H0. inv VT. destruct (deref_loc_inject _ _ _ _ H1 _ _ H3) as [tv [InjTv DerefTv]]. specialize (make_load_correct tge tb (typeof a) ta b2 (Int.add ofs (Int.repr delta)) _ _ _ _ MKLOAD ET DerefTv). intros. exists tv; split; eassumption. (* var local *) destruct (me_local _ _ _ MENV _ _ _ H) as [tb [J TH]]. eexists; split; econstructor. eassumption. reflexivity. eapply eval_var_addr_local; eassumption. (* var global *) exists (Vptr l Int.zero); split. econstructor. eapply (meminj_preserves_globals_isGlobalBlock _ _ PG). eapply find_symbol_isGlobal; eassumption. rewrite Int.add_zero. trivial. econstructor. eapply eval_var_addr_global. eapply match_env_globals; eauto. rewrite symbols_preserved. eassumption. (* deref *) auto. (* field struct *) simpl in TR. rewrite H1 in TR. monadInv TR. destruct (H0 _ EQ) as [tv [VT ET]]; clear H0. inv VT. eexists; split. econstructor. eassumption. reflexivity. eapply eval_Ebinop; eauto. apply make_intconst_correct. rewrite EQ1 in H2. inv H2. simpl. rewrite Int.add_assoc. rewrite Int.add_assoc. rewrite (Int.add_commut (Int.repr delta0)). trivial. (* field union *) simpl in TR. rewrite H1 in TR. eauto. Qed. Lemma transl_expr_correct: forall a v, Clight.eval_expr ge e le m a v -> forall ta, transl_expr a = OK ta -> exists tv, val_inject j v tv /\ eval_expr tge te tle tm ta tv. Proof (proj1 transl_expr_lvalue_correct). Lemma transl_lvalue_correct: forall a b ofs, eval_lvalue ge e le m a b ofs -> forall ta, transl_lvalue a = OK ta -> exists tv, val_inject j (Vptr b ofs) tv /\ eval_expr tge te tle tm ta tv. Proof (proj2 transl_expr_lvalue_correct). Lemma transl_arglist_correct: forall al tyl vl, Clight.eval_exprlist ge e le m al tyl vl -> forall tal, transl_arglist al tyl = OK tal -> exists tvl, val_list_inject j vl tvl /\ Csharpminor.eval_exprlist tge te tle tm tal tvl. Proof. induction 1; intros. monadInv H. exists nil. split; constructor. monadInv H2. destruct (IHeval_exprlist _ EQ0) as [tv1 [VT ET]]; clear IHeval_exprlist. destruct (transl_expr_correct _ _ H _ EQ) as [? [? ?]]. destruct (sem_cast_inject _ _ _ _ _ _ H0 H2) as [? [? ?]]. specialize (make_cast_correct _ _ _ _ _ _ _ _ _ _ EQ1 H3 H4). intros. eexists; split. econstructor; eassumption. econstructor; eassumption. Qed. Lemma make_boolean_inject: forall a v ty b, Clight.eval_expr ge e le m a v -> bool_val v ty = Some b -> forall ta, transl_expr a = OK ta -> exists tv, Csharpminor.eval_expr tge te tle tm (make_boolean ta ty) tv /\ Val.bool_of_val tv b. Proof. intros. unfold make_boolean. unfold bool_val in H0. destruct (classify_bool ty); destruct v; inv H0. (* int *) destruct (transl_expr_correct _ _ H _ H1) as [tv [Vinj ET]]. inv Vinj. eexists; split. apply make_cmp_ne_zero_correct with (n := i); auto. destruct (Int.eq i Int.zero); simpl; constructor. (* float *) destruct (transl_expr_correct _ _ H _ H1) as [tv [Vinj ET]]. inv Vinj. econstructor; split. econstructor; eauto. econstructor. reflexivity. simpl. reflexivity. unfold Val.cmpf, Val.cmpf_bool. rewrite <- Float.cmp_ne_eq. destruct (Float.cmp Cne f Float.zero); constructor. (* pointer *) destruct (transl_expr_correct _ _ H _ H1) as [tv [Vinj ET]]. inv Vinj. econstructor; split. econstructor; eauto. econstructor; reflexivity. reflexivity. unfold Val.cmpu, Val.cmpu_bool. simpl. destruct (Int.eq i Int.zero); simpl; constructor. destruct (transl_expr_correct _ _ H _ H1) as [tv [Vinj ET]]. inv Vinj. exists Vtrue; split. econstructor; eauto. constructor; reflexivity. simpl. unfold Val.cmpu, Val.cmpu_bool. simpl. destruct (Int.eq i Int.zero); simpl; constructor. constructor. (* long *) destruct (transl_expr_correct _ _ H _ H1) as [tv [Vinj ET]]. inv Vinj. econstructor; split. econstructor; eauto. constructor; reflexivity. simpl. unfold Val.cmpl. simpl. eauto. destruct (Int64.eq i Int64.zero); simpl; constructor. Qed. End EXPR. (** ** Semantic preservation for statements *) (** The simulation diagram for the translation of statements and functions is a "plus" diagram of the form << I S1 ------- R1 | | t | + | t v v S2 ------- R2 I I >> The invariant [I] is the [match_states] predicate that we now define. *) Inductive match_transl: stmt -> cont -> stmt -> cont -> Prop := | match_transl_0: forall ts tk, match_transl ts tk ts tk | match_transl_1: forall ts tk, match_transl (Sblock ts) tk ts (Kblock tk). (* Lemma match_transl_step: forall ts tk ts' tk' f te le m, match_transl (Sblock ts) tk ts' tk' -> star (clight_corestep tge (CL_core f ts' tk' te le) m E0 (State f ts (Kblock tk) te le m). Proof. intros. inv H. apply star_one. constructor. apply star_refl. Qed. *) Lemma match_transl_corestep: forall ts tk ts' tk' f te le m, match_transl (Sblock ts) tk ts' tk' -> corestep_star (csharpmin_eff_sem hf) tge (CSharpMin_State f ts' tk' te le) m (CSharpMin_State f ts (Kblock tk) te le) m. Proof. intros. inv H. apply corestep_star_one. constructor. apply corestep_star_zero. Qed. Lemma match_transl_effstep: forall ts tk ts' tk' f te le m, match_transl (Sblock ts) tk ts' tk' -> effstep_star (csharpmin_eff_sem hf) tge EmptyEffect (CSharpMin_State f ts' tk' te le) m (CSharpMin_State f ts (Kblock tk) te le) m. Proof. intros. inv H. apply effstep_star_one. constructor. apply effstep_star_zero. Qed. Inductive match_cont (j:meminj): type -> nat -> nat -> Clight.cont -> Csharpminor.cont -> Prop := | match_Kstop: forall tyret nbrk ncnt, match_cont j tyret nbrk ncnt Clight.Kstop Kstop | match_Kseq: forall tyret nbrk ncnt s k ts tk, transl_statement tyret nbrk ncnt s = OK ts -> match_cont j tyret nbrk ncnt k tk -> match_cont j tyret nbrk ncnt (Clight.Kseq s k) (Kseq ts tk) | match_Kloop1: forall tyret s1 s2 k ts1 ts2 nbrk ncnt tk, transl_statement tyret 1%nat 0%nat s1 = OK ts1 -> transl_statement tyret 0%nat (S ncnt) s2 = OK ts2 -> match_cont j tyret nbrk ncnt k tk -> match_cont j tyret 1%nat 0%nat (Clight.Kloop1 s1 s2 k) (Kblock (Kseq ts2 (Kseq (Sloop (Sseq (Sblock ts1) ts2)) (Kblock tk)))) | match_Kloop2: forall tyret s1 s2 k ts1 ts2 nbrk ncnt tk, transl_statement tyret 1%nat 0%nat s1 = OK ts1 -> transl_statement tyret 0%nat (S ncnt) s2 = OK ts2 -> match_cont j tyret nbrk ncnt k tk -> match_cont j tyret 0%nat (S ncnt) (Clight.Kloop2 s1 s2 k) (Kseq (Sloop (Sseq (Sblock ts1) ts2)) (Kblock tk)) | match_Kswitch: forall tyret nbrk ncnt k tk, match_cont j tyret nbrk ncnt k tk -> match_cont j tyret 0%nat (S ncnt) (Clight.Kswitch k) (Kblock tk) | match_Kcall_some: forall tyret nbrk ncnt nbrk' ncnt' f e k id tf te le tle tk, transl_function f = OK tf -> match_env j e te -> match_tempenv j le tle -> match_cont j (Clight.fn_return f) nbrk' ncnt' k tk -> match_cont j tyret nbrk ncnt (Clight.Kcall id f e le k) (Kcall id tf te tle tk). Lemma match_cont_inject_incr: forall j j' (I: inject_incr j j') tp n m k k' (MC: match_cont j tp n m k k'), match_cont j' tp n m k k'. Proof. intros. induction MC; try (econstructor; try eassumption). eapply match_env_inject_incr; eassumption. eapply match_tempenv_inject_incr; eassumption. Qed. Inductive match_states (j:meminj) : CL_core -> mem -> CSharpMin_core -> mem -> Prop := | match_state: forall f nbrk ncnt s k e le m tf ts tk te tle ts' tk' tm (TRF: transl_function f = OK tf) (TR: transl_statement (Clight.fn_return f) nbrk ncnt s = OK ts) (MTR: match_transl ts tk ts' tk') (MENV: match_env j e te) (TENV: match_tempenv j le tle) (MK: match_cont j (Clight.fn_return f) nbrk ncnt k tk), match_states j (CL_State f s k e le) m (CSharpMin_State tf ts' tk' te tle) tm | match_callstate: forall fd args1 k m tfd tk targs tres tm args2 (TR: transl_fundef fd = OK tfd) (MK: match_cont j Tvoid 0%nat 0%nat k tk) (ISCC: Clight.is_call_cont k) (TY: type_of_fundef fd = Tfunction targs tres) (ArgsInj: val_list_inject j args1 args2), match_states j (CL_Callstate fd args1 k) m (CSharpMin_Callstate tfd args2 tk) tm | match_returnstate: forall res1 res2 k m tk tm (MK: match_cont j Tvoid 0%nat 0%nat k tk) (Vinj: val_inject j res1 res2), match_states j (CL_Returnstate res1 k) m (CSharpMin_Returnstate res2 tk) tm. Remark match_states_skip: forall j f e le te tle nbrk ncnt k tf tk m tm, transl_function f = OK tf -> match_env j e te -> match_tempenv j le tle -> match_cont j (Clight.fn_return f) nbrk ncnt k tk -> match_states j (CL_State f Clight.Sskip k e le) m (CSharpMin_State tf Sskip tk te tle) tm. Proof. intros. econstructor; eauto. simpl; reflexivity. constructor. Qed. (** Commutation between label resolution and compilation *) Section FIND_LABEL. Variable lbl: label. Variable tyret: type. Lemma transl_find_label: forall s j nbrk ncnt k ts tk (TR: transl_statement tyret nbrk ncnt s = OK ts) (MC: match_cont j tyret nbrk ncnt k tk), match Clight.find_label lbl s k with | None => find_label lbl ts tk = None | Some (s', k') => exists ts', exists tk', exists nbrk', exists ncnt', find_label lbl ts tk = Some (ts', tk') /\ transl_statement tyret nbrk' ncnt' s' = OK ts' /\ match_cont j tyret nbrk' ncnt' k' tk' end with transl_find_label_ls: forall ls j nbrk ncnt k tls tk (TR: transl_lbl_stmt tyret nbrk ncnt ls = OK tls) (MC: match_cont j tyret nbrk ncnt k tk), match Clight.find_label_ls lbl ls k with | None => find_label_ls lbl tls tk = None | Some (s', k') => exists ts', exists tk', exists nbrk', exists ncnt', find_label_ls lbl tls tk = Some (ts', tk') /\ transl_statement tyret nbrk' ncnt' s' = OK ts' /\ match_cont j tyret nbrk' ncnt' k' tk' end. Proof. intros s; case s; intros; try (monadInv TR); simpl. (* skip *) auto. (* assign *) unfold make_store, make_memcpy in EQ3. destruct (access_mode (typeof e)); inv EQ3; auto. (* set *) auto. (* call *) simpl in TR. destruct (classify_fun (typeof e)); monadInv TR. auto. (* builtin *) auto. (* seq *) exploit (transl_find_label s0 j nbrk ncnt (Clight.Kseq s1 k)); eauto. constructor; eauto. destruct (Clight.find_label lbl s0 (Clight.Kseq s1 k)) as [[s' k'] | ]. intros [ts' [tk' [nbrk' [ncnt' [A [B C]]]]]]. rewrite A. exists ts'; exists tk'; exists nbrk'; exists ncnt'; auto. intro. rewrite H. eapply transl_find_label; eauto. (* ifthenelse *) exploit (transl_find_label s0); eauto. destruct (Clight.find_label lbl s0 k) as [[s' k'] | ]. intros [ts' [tk' [nbrk' [ncnt' [A [B C]]]]]]. rewrite A. exists ts'; exists tk'; exists nbrk'; exists ncnt'; auto. intro. rewrite H. eapply transl_find_label; eauto. (* loop *) exploit (transl_find_label s0 j 1%nat 0%nat (Kloop1 s0 s1 k)); eauto. econstructor; eauto. destruct (Clight.find_label lbl s0 (Kloop1 s0 s1 k)) as [[s' k'] | ]. intros [ts' [tk' [nbrk' [ncnt' [A [B C]]]]]]. rewrite A. exists ts'; exists tk'; exists nbrk'; exists ncnt'; auto. intro. rewrite H. eapply transl_find_label; eauto. econstructor; eauto. (* break *) auto. (* continue *) auto. (* return *) simpl in TR. destruct o; monadInv TR. auto. auto. (* switch *) eapply transl_find_label_ls with (k := Clight.Kswitch k); eauto. econstructor; eauto. (* label *) destruct (ident_eq lbl l). exists x; exists tk; exists nbrk; exists ncnt; auto. eapply transl_find_label; eauto. (* goto *) auto. intro ls; case ls; intros; monadInv TR; simpl. (* default *) eapply transl_find_label; eauto. (* case *) exploit (transl_find_label s j nbrk ncnt (Clight.Kseq (seq_of_labeled_statement l) k)); eauto. econstructor; eauto. apply transl_lbl_stmt_2; eauto. destruct (Clight.find_label lbl s (Clight.Kseq (seq_of_labeled_statement l) k)) as [[s' k'] | ]. intros [ts' [tk' [nbrk' [ncnt' [A [B C]]]]]]. rewrite A. exists ts'; exists tk'; exists nbrk'; exists ncnt'; auto. intro. rewrite H. eapply transl_find_label_ls; eauto. Qed. End FIND_LABEL. (** Properties of call continuations *) Lemma match_cont_call_cont: forall j tyret' nbrk' ncnt' tyret nbrk ncnt k tk, match_cont j tyret nbrk ncnt k tk -> match_cont j tyret' nbrk' ncnt' (Clight.call_cont k) (call_cont tk). Proof. induction 1; simpl; auto. constructor. econstructor; eauto. Qed. Lemma match_cont_is_call_cont: forall j tyret nbrk ncnt k tk tyret' nbrk' ncnt', match_cont j tyret nbrk ncnt k tk -> Clight.is_call_cont k -> match_cont j tyret' nbrk' ncnt' k tk /\ is_call_cont tk. Proof. intros. inv H; simpl in H0; try contradiction; simpl. split; auto; constructor. split; auto; econstructor; eauto. Qed. Lemma varinfo_preserved: forall b, (exists gv : globvar type, Genv.find_var_info ge b = Some gv) <-> (exists gv : globvar unit, Genv.find_var_info tge b = Some gv). Proof. intros. split; intros; destruct H. destruct (var_info_translated _ _ H). exists x0; apply H0. destruct (var_info_rev_translated _ _ H). exists x0; apply H0. Qed. Lemma GDE_lemma: genvs_domain_eq ge tge. Proof. unfold genvs_domain_eq, genv2blocks. simpl; split; intros. split; intros; destruct H as [id Hid]. rewrite <- symbols_preserved in Hid. exists id; trivial. rewrite symbols_preserved in Hid. exists id; trivial. split; intros b. apply varinfo_preserved. intros. split. intros [f H]. apply function_ptr_translated in H. destruct H as [? [? ?]]. eexists; eassumption. intros [f H]. unfold transl_program in TRANSL. apply (@Genv.find_funct_ptr_rev_transf_partial2 _ _ _ _ transl_fundef transl_globvar _ _ TRANSL) in H. destruct H as [? [? _]]. eexists; eassumption. Qed. (*From SimplLocals*) Lemma assign_loc_inject: forall f ty m loc ofs v m' tm loc' ofs' v', assign_loc ty m loc ofs v m' -> val_inject f (Vptr loc ofs) (Vptr loc' ofs') -> val_inject f v v' -> Mem.inject f m tm -> exists tm', assign_loc ty tm loc' ofs' v' tm' /\ Mem.inject f m' tm' /\ (forall b chunk v, f b = None -> Mem.load chunk m b 0 = Some v -> Mem.load chunk m' b 0 = Some v). Proof. intros. inv H. (* by value *) exploit Mem.storev_mapped_inject; eauto. intros [tm' [A B]]. exists tm'; split. eapply assign_loc_value; eauto. split. auto. intros. rewrite <- H5. eapply Mem.load_store_other; eauto. left. inv H0. congruence. (* by copy *) inv H0. inv H1. rename b' into bsrc. rename ofs'0 into osrc. rename loc into bdst. rename ofs into odst. rename loc' into bdst'. rename b2 into bsrc'. exploit Mem.loadbytes_length; eauto. intros LEN. assert (SZPOS: sizeof ty > 0) by apply sizeof_pos. assert (RPSRC: Mem.range_perm m bsrc (Int.unsigned osrc) (Int.unsigned osrc + sizeof ty) Cur Nonempty). eapply Mem.range_perm_implies. eapply Mem.loadbytes_range_perm; eauto. auto with mem. assert (RPDST: Mem.range_perm m bdst (Int.unsigned odst) (Int.unsigned odst + sizeof ty) Cur Nonempty). replace (sizeof ty) with (Z_of_nat (length bytes)). eapply Mem.range_perm_implies. eapply Mem.storebytes_range_perm; eauto. auto with mem. rewrite LEN. apply nat_of_Z_eq. omega. assert (PSRC: Mem.perm m bsrc (Int.unsigned osrc) Cur Nonempty). apply RPSRC. omega. assert (PDST: Mem.perm m bdst (Int.unsigned odst) Cur Nonempty). apply RPDST. omega. exploit Mem.address_inject. eauto. eexact PSRC. eauto. intros EQ1. exploit Mem.address_inject. eauto. eexact PDST. eauto. intros EQ2. exploit Mem.loadbytes_inject; eauto. intros [bytes2 [A B]]. exploit Mem.storebytes_mapped_inject; eauto. intros [tm' [C D]]. exists tm'. split. eapply assign_loc_copy; try rewrite EQ1; try rewrite EQ2; eauto. eapply Mem.aligned_area_inject with (m := m); eauto. apply alignof_blockcopy_1248. eapply Zdivide_trans. apply alignof_blockcopy_divides. apply sizeof_alignof_compat. eapply Mem.aligned_area_inject with (m := m); eauto. apply alignof_blockcopy_1248. eapply Zdivide_trans. apply alignof_blockcopy_divides. apply sizeof_alignof_compat. eapply Mem.disjoint_or_equal_inject with (m := m); eauto. apply Mem.range_perm_max with Cur; auto. apply Mem.range_perm_max with Cur; auto. split. auto. intros. rewrite <- H0. eapply Mem.load_storebytes_other; eauto. left. congruence. Qed. Lemma assign_loc_unique: forall t m b z v m1 m2 (AL1: assign_loc t m b z v m1) (AL2: assign_loc t m b z v m2), m1=m2. Proof. intros. inv AL1; inv AL2. rewrite H1 in H; inv H. rewrite H2 in H0; inv H0; trivial. rewrite H1 in H; inv H. rewrite H5 in H; inv H. rewrite H7 in H; inv H. destruct (loadbytes_D _ _ _ _ _ H3). destruct (loadbytes_D _ _ _ _ _ H11). rewrite <- H5 in H12. clear H5. subst. rewrite H4 in H13; inv H13; trivial. Qed. Definition MATCH (d:CL_core) mu c1 m1 c2 m2:Prop := match_states (restrict (as_inj mu) (vis mu)) c1 m1 c2 m2 /\ REACH_closed m1 (vis mu) /\ meminj_preserves_globals ge (as_inj mu) /\ globalfunction_ptr_inject ge (as_inj mu) /\ (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true) /\ sm_valid mu m1 m2 /\ SM_wd mu /\ Mem.inject (as_inj mu) m1 m2. Lemma MATCH_wd: forall d mu c1 m1 c2 m2 (MC: MATCH d mu c1 m1 c2 m2), SM_wd mu. Proof. intros. eapply MC. Qed. Lemma MATCH_RC: forall d mu c1 m1 c2 m2 (MC: MATCH d mu c1 m1 c2 m2), REACH_closed m1 (vis mu). Proof. intros. eapply MC. Qed. Lemma MATCH_restrict: forall d mu c1 m1 c2 m2 X (MC: MATCH d mu c1 m1 c2 m2) (HX: forall b : block, vis mu b = true -> X b = true) (RX: REACH_closed m1 X), MATCH d (restrict_sm mu X) c1 m1 c2 m2. Proof. intros. destruct MC as [MS [RC [PG [GF [Glob [SMV [WD INJ]]]]]]]. assert (WDR: SM_wd (restrict_sm mu X)). apply restrict_sm_WD; assumption. split. rewrite vis_restrict_sm. rewrite restrict_sm_all. rewrite restrict_nest; intuition. split. unfold vis. rewrite restrict_sm_locBlocksSrc, restrict_sm_frgnBlocksSrc. apply RC. split. clear -PG Glob HX. eapply restrict_sm_preserves_globals; try eassumption. unfold vis in HX. intuition. split. rewrite restrict_sm_all. eapply restrict_preserves_globalfun_ptr; try eassumption. unfold vis in HX. intuition. split. rewrite restrict_sm_frgnBlocksSrc. apply Glob. split. destruct SMV. split; intros. rewrite restrict_sm_DOM in H1. apply (H _ H1). rewrite restrict_sm_RNG in H1. apply (H0 _ H1). split. assumption. rewrite restrict_sm_all. eapply inject_restrict; eassumption. Qed. Lemma MATCH_valid: forall d mu c1 m1 c2 m2 (MC: MATCH d mu c1 m1 c2 m2), sm_valid mu m1 m2. Proof. intros. eapply MC. Qed. Lemma MATCH_PG: forall d mu c1 m1 c2 m2 (MC: MATCH d mu c1 m1 c2 m2), meminj_preserves_globals ge (extern_of mu) /\ (forall b : block, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true). Proof. intros. assert (GF: forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true). apply MC. split; trivial. rewrite <- match_genv_meminj_preserves_extern_iff_all; trivial. apply MC. apply MC. Qed. Lemma MATCH_initial: forall v vals1 c1 m1 j vals2 m2 (DomS DomT : block -> bool) (FE : Clight.function -> list val -> mem -> Clight.env -> Clight.temp_env -> mem -> Prop) (FE_FWD : forall f vargs m e lenv m', FE f vargs m e lenv m' -> mem_forward m m') (FE_UNCH : forall f vargs m e lenv m', FE f vargs m e lenv m' -> Mem.unchanged_on (fun (b : block) (z : Z) => EmptyEffect b z = false) m m') (Ini: initial_core (clight_eff_sem hf FE FE_FWD FE_UNCH) ge v vals1 = Some c1) (Inj: Mem.inject j m1 m2) (VInj: Forall2 (val_inject j) vals1 vals2) (PG:meminj_preserves_globals ge j) (R : list_norepet (map fst (prog_defs prog))) (J: forall b1 b2 delta, j b1 = Some (b2, delta) -> (DomS b1 = true /\ DomT b2 = true)) (RCH: forall b, REACH m2 (fun b' : block => isGlobalBlock tge b' || getBlocks vals2 b') b = true -> DomT b = true) (GFI: globalfunction_ptr_inject ge j) (GDE: genvs_domain_eq ge tge) (HDomS: forall b : block, DomS b = true -> Mem.valid_block m1 b) (HDomT: forall b : block, DomT b = true -> Mem.valid_block m2 b), exists c2, initial_core (csharpmin_eff_sem hf) tge v vals2 = Some c2 /\ MATCH c1 (initial_SM DomS DomT (REACH m1 (fun b : block => isGlobalBlock ge b || getBlocks vals1 b)) (REACH m2 (fun b : block => isGlobalBlock tge b || getBlocks vals2 b)) j) c1 m1 c2 m2. Proof. intros. simpl in Ini. unfold CL_initial_core in Ini. unfold ge in *. unfold tge in *. destruct v; inv Ini. remember (Int.eq_dec i Int.zero) as z; destruct z; inv H0. clear Heqz. remember (Genv.find_funct_ptr (Genv.globalenv prog) b) as zz; destruct zz. apply eq_sym in Heqzz. destruct f; try discriminate. remember (type_of_fundef (Internal f)) as tf. destruct tf; try solve[inv H1]. case_eq (val_casted.val_casted_list_func vals1 t). 2: solve[intros cast; rewrite cast in H1; inv H1]. intros cast. case_eq (val_casted.vals_defined vals1). 2: solve[intros def; rewrite cast, def in H1; simpl in H1; rewrite <-andb_assoc, andb_comm in H1; inv H1]. intros def; rewrite cast,def in H1. simpl in H1. rewrite andb_comm in H1; simpl in H1. case_eq (val_casted.tys_nonvoid t). 2: solve[intros nvoid; rewrite nvoid, andb_comm in H1; inv H1]. intros nvoid; rewrite nvoid in H1. inv H1. revert H0; case_eq (zlt (match match Zlength vals1 with 0 => 0 | Z.pos y' => Z.pos y'~0 | Z.neg y' => Z.neg y'~0 end with 0 => 0 | Z.pos y' => Z.pos y'~0~0 | Z.neg y' => Z.neg y'~0~0 end) Int.max_unsigned); simpl. 2: solve[inversion 2]. intros l _. inversion 1; subst. exploit function_ptr_translated; eauto. intros [tf' [FIND TR]]. exists (CSharpMin_Callstate tf' vals2 Kstop). split. simpl. subst. inv Heqzz. unfold tge in FIND. inv FIND. rewrite H2. unfold CSharpMin_initial_core. case_eq (Int.eq_dec Int.zero Int.zero). intros ? e. assert (Hlen: Zlength vals2 = Zlength vals1). { apply forall_inject_val_list_inject in VInj. clear - VInj. induction VInj; auto. rewrite !Zlength_cons, IHVInj; auto. } assert (val_casted.val_has_type_list_func vals2 (sig_args (funsig tf'))=true) as ->. { eapply val_casted.val_list_inject_hastype; eauto. eapply forall_inject_val_list_inject; eauto. eapply transl_fundef_sig2 in TR; eauto. rewrite TR. simpl. apply val_casted.val_casted_has_type_list; auto. } assert (val_casted.vals_defined vals2=true) as ->. { eapply val_casted.val_list_inject_defined. eapply forall_inject_val_list_inject; eauto. destruct (val_casted.vals_defined vals1); auto. } monadInv TR. rename x into tf'. rewrite Hlen. simpl. case_eq (zlt (match match Zlength vals1 with 0%Z => 0%Z | Z.pos y' => Z.pos y'~0 | Z.neg y' => Z.neg y'~0 end with 0%Z => 0%Z | Z.pos y' => Z.pos y'~0~0 | Z.neg y' => Z.neg y'~0~0 end) Int.max_unsigned). simpl; auto. simpl. inversion 1. omega. intros CONTRA. solve[elimtype False; auto]. assert (H : exists targs tres, type_of_fundef (Internal f) = Tfunction targs tres). { destruct f; simpl. eexists; eexists. reflexivity. } destruct H as [targs [tres Tfun]]. destruct (core_initial_wd ge tge _ _ _ _ _ _ _ Inj VInj J RCH PG GDE HDomS HDomT _ (eq_refl _)) as [AA [BB [CC [DD [EE [FF GG]]]]]]. split. eapply match_callstate; try eassumption. constructor. constructor. rewrite initial_SM_as_inj. unfold vis, initial_SM; simpl. apply forall_inject_val_list_inject. eapply restrict_forall_vals_inject; try eassumption. intros. apply REACH_nil. rewrite H; intuition. intuition. rewrite match_genv_meminj_preserves_extern_iff_all. assumption. apply BB. apply EE. rewrite initial_SM_as_inj. red; intros. destruct (GFI b0 f0 H); auto. rewrite initial_SM_as_inj; assumption. inv H1. Qed. Lemma MATCH_afterExternal: forall (FE : Clight.function -> list val -> mem -> Clight.env -> Clight.temp_env -> mem -> Prop) (FE_FWD : forall f vargs m e lenv m', FE f vargs m e lenv m' -> mem_forward m m') (FE_UNCH : forall f vargs m e lenv m', FE f vargs m e lenv m' -> Mem.unchanged_on (fun (b : block) (z : Z) => EmptyEffect b z = false) m m') (GDE : genvs_domain_eq ge tge) mu st1 st2 m1 e vals1 m2 ef_sig vals2 e' ef_sig' (MemInjMu : Mem.inject (as_inj mu) m1 m2) (MatchMu: MATCH st1 mu st1 m1 st2 m2) (AtExtSrc : at_external (clight_eff_sem hf FE FE_FWD FE_UNCH) st1 = Some (e, ef_sig, vals1)) (AtExtTgt : at_external (csharpmin_eff_sem hf) st2 = Some (e', ef_sig', vals2)) (ValInjMu : Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2) (pubSrc' : block -> bool) (pubSrcHyp : pubSrc' = (fun b : block => locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b)) (pubTgt' : block -> bool) (pubTgtHyp: pubTgt' = (fun b : block => locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b)) nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt') nu' ret1 m1' ret2 m2' (INC: extern_incr nu nu') (SEP : globals_separate tge nu nu') (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2') (MemInjNu': Mem.inject (as_inj nu') m1' m2') (RValInjNu': val_inject (as_inj nu') ret1 ret2) (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2') (frgnSrc' : block -> bool) (frgnSrcHyp: frgnSrc' = (fun b : block => DomSrc nu' b && (negb (locBlocksSrc nu' b) && REACH m1' (exportedSrc nu' (ret1 :: nil)) b))) (frgnTgt' : block -> bool) (frgnTgtHyp: frgnTgt' = (fun b : block => DomTgt nu' b && (negb (locBlocksTgt nu' b) && REACH m2' (exportedTgt nu' (ret2 :: nil)) b))) mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt') (UnchPrivSrc: Mem.unchanged_on (fun b z => locBlocksSrc nu b = true /\ pubBlocksSrc nu b = false) m1 m1') (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'), exists (st1' : CL_core) (st2' : CSharpMin_core), after_external (clight_eff_sem hf FE FE_FWD FE_UNCH) (Some ret1) st1 =Some st1' /\ after_external (csharpmin_eff_sem hf) (Some ret2) st2 = Some st2' /\ MATCH st1' mu' st1' m1' st2' m2'. Proof. intros. simpl. destruct MatchMu as [MC [RC [PG [GF [Glob [VAL [WDmu INJ]]]]]]]. simpl in *. inv MC; simpl in *; inv AtExtSrc. destruct fd; inv H0. simpl in TY. inv TY. destruct tfd; inv AtExtTgt. destruct (observableEF_dec hf e0); inv H1. destruct (observableEF_dec hf e1); inv H0. destruct (vals_def args1) eqn:Heqv; inv H2. simpl in *. remember (list_typ_eq (sig_args (ef_sig e)) (typlist_of_typelist targs) && opt_typ_eq (sig_res (ef_sig e)) (opttyp_of_type tres)) as dd. destruct dd; inv TR. clear o0; rename o into OBS. eexists. eexists. split. reflexivity. split. reflexivity. assert (INCvisNu': inject_incr (restrict (as_inj nu') (vis (replace_externs nu' (fun b : Values.block => DomSrc nu' b && (negb (locBlocksSrc nu' b) && REACH m1' (exportedSrc nu' (ret1 :: nil)) b)) (fun b : Values.block => DomTgt nu' b && (negb (locBlocksTgt nu' b) && REACH m2' (exportedTgt nu' (ret2 :: nil)) b))))) (as_inj nu')). unfold vis. rewrite replace_externs_frgnBlocksSrc, replace_externs_locBlocksSrc. apply restrict_incr. assert (RC': REACH_closed m1' (mapped (as_inj nu'))) by (eapply inject_REACH_closed; eassumption). assert (PGnu': meminj_preserves_globals (Genv.globalenv prog) (as_inj nu')). { eapply meminj_preserves_globals_extern_incr_separate. eassumption. rewrite replace_locals_as_inj. assumption. assumption. specialize (genvs_domain_eq_isGlobal _ _ GDE_lemma). intros GL. red. unfold ge in GL. rewrite GL. apply SEP. } assert (RR1: REACH_closed m1' (fun b : Values.block => locBlocksSrc nu' b || DomSrc nu' b && (negb (locBlocksSrc nu' b) && REACH m1' (exportedSrc nu' (ret1 :: nil)) b))). { intros b Hb. rewrite REACHAX in Hb. destruct Hb as [L HL]. generalize dependent b. induction L; simpl; intros; inv HL. assumption. specialize (IHL _ H1); clear H1. apply orb_true_iff in IHL. remember (locBlocksSrc nu' b') as l. destruct l; apply eq_sym in Heql. (*case locBlocksSrc nu' b' = true*) clear IHL. remember (pubBlocksSrc nu' b') as p. destruct p; apply eq_sym in Heqp. assert (Rb': REACH m1' (mapped (as_inj nu')) b' = true). apply REACH_nil. destruct (pubSrc _ WDnu' _ Heqp) as [bb2 [dd1 [PUB PT]]]. eapply mappedI_true. apply (pub_in_all _ WDnu' _ _ _ PUB). assert (Rb: REACH m1' (mapped (as_inj nu')) b = true). eapply REACH_cons; try eassumption. specialize (RC' _ Rb). destruct (mappedD_true _ _ RC') as [[b2 d1] AI']. remember (locBlocksSrc nu' b) as d. destruct d; simpl; trivial. apply andb_true_iff. split. eapply as_inj_DomRng; try eassumption. eapply REACH_cons; try eassumption. apply REACH_nil. unfold exportedSrc. rewrite (pubSrc_shared _ WDnu' _ Heqp). intuition. destruct (UnchPrivSrc) as [UP UV]; clear UnchLOOR. specialize (UP b' z Cur Readable). specialize (UV b' z). destruct INC as [_ [_ [_ [_ [LCnu' [_ [PBnu' [_ [FRGnu' _]]]]]]]]]. rewrite <- LCnu'. rewrite replace_locals_locBlocksSrc. rewrite <- LCnu' in Heql. rewrite replace_locals_locBlocksSrc in *. rewrite <- PBnu' in Heqp. rewrite replace_locals_pubBlocksSrc in *. clear INCvisNu'. rewrite Heql in *. simpl in *. intuition. assert (VB: Mem.valid_block m1 b'). eapply VAL. unfold DOM, DomSrc. rewrite Heql. intuition. apply (H VB) in H2. rewrite (H0 H2) in H4. clear H H0. remember (locBlocksSrc mu b) as q. destruct q; simpl; trivial; apply eq_sym in Heqq. assert (Rb : REACH m1 (vis mu) b = true). eapply REACH_cons; try eassumption. apply REACH_nil. unfold vis. rewrite Heql; trivial. specialize (RC _ Rb). unfold vis in RC. rewrite Heqq in RC; simpl in *. rewrite replace_locals_frgnBlocksSrc in FRGnu'. rewrite FRGnu' in RC. apply andb_true_iff. split. unfold DomSrc. rewrite (frgnBlocksSrc_extBlocksSrc _ WDnu' _ RC). intuition. apply REACH_nil. unfold exportedSrc. rewrite (frgnSrc_shared _ WDnu' _ RC). intuition. destruct IHL. congruence. apply andb_true_iff in H. simpl in H. destruct H as [DomNu' Rb']. clear INC SEP INCvisNu' UnchLOOR UnchPrivSrc. remember (locBlocksSrc nu' b) as d. destruct d; simpl; trivial. apply eq_sym in Heqd. apply andb_true_iff. split. assert (RET: Forall2 (val_inject (as_inj nu')) (ret1::nil) (ret2::nil)). constructor. assumption. constructor. destruct (REACH_as_inj _ WDnu' _ _ _ _ MemInjNu' RET _ Rb' (fun b => true)) as [b2 [d1 [AI' _]]]; trivial. assert (REACH m1' (mapped (as_inj nu')) b = true). eapply REACH_cons; try eassumption. apply REACH_nil. eapply mappedI_true; eassumption. specialize (RC' _ H). destruct (mappedD_true _ _ RC') as [[? ?] ?]. eapply as_inj_DomRng; eassumption. eapply REACH_cons; try eassumption. } assert (RRC: REACH_closed m1' (fun b : Values.block => mapped (as_inj nu') b && (locBlocksSrc nu' b || DomSrc nu' b && (negb (locBlocksSrc nu' b) && REACH m1' (exportedSrc nu' (ret1 :: nil)) b)))). { eapply REACH_closed_intersection; eassumption. } assert (GFnu': forall b, isGlobalBlock (Genv.globalenv prog) b = true -> DomSrc nu' b && (negb (locBlocksSrc nu' b) && REACH m1' (exportedSrc nu' (ret1 :: nil)) b) = true). { intros. specialize (Glob _ H). assert (FSRC:= extern_incr_frgnBlocksSrc _ _ INC). rewrite replace_locals_frgnBlocksSrc in FSRC. rewrite FSRC in Glob. rewrite (frgnBlocksSrc_locBlocksSrc _ WDnu' _ Glob). apply andb_true_iff; simpl. split. unfold DomSrc. rewrite (frgnBlocksSrc_extBlocksSrc _ WDnu' _ Glob). intuition. apply REACH_nil. unfold exportedSrc. rewrite (frgnSrc_shared _ WDnu' _ Glob). intuition. } split. unfold vis in *. rewrite replace_externs_frgnBlocksSrc, replace_externs_locBlocksSrc in *. econstructor; try eassumption. eapply match_cont_inject_incr; try eassumption. rewrite (*restrict_sm_all, *)replace_externs_as_inj. clear RRC RR1 RC' PGnu' INCvisNu' UnchLOOR UnchPrivSrc. destruct INC. rewrite replace_locals_extern in H. rewrite replace_locals_frgnBlocksTgt, replace_locals_frgnBlocksSrc, replace_locals_pubBlocksTgt, replace_locals_pubBlocksSrc, replace_locals_locBlocksTgt, replace_locals_locBlocksSrc, replace_locals_extBlocksTgt, replace_locals_extBlocksSrc, replace_locals_local in H0. destruct H0 as [? [? [? [? [? [? [? [? ?]]]]]]]]. red; intros. destruct (restrictD_Some _ _ _ _ _ H9); clear H9. apply restrictI_Some. apply joinI. destruct (joinD_Some _ _ _ _ _ H10). apply H in H9. left; trivial. destruct H9. right. rewrite H0 in H12. split; trivial. destruct (disjoint_extern_local _ WDnu' b); trivial. congruence. rewrite H3, H7 in H11. remember (locBlocksSrc nu' b) as d. destruct d; trivial; simpl in *. apply andb_true_iff. split. unfold DomSrc. rewrite (frgnBlocksSrc_extBlocksSrc _ WDnu' _ H11). intuition. apply REACH_nil. unfold exportedSrc. apply frgnSrc_shared in H11; trivial. rewrite H11; intuition. rewrite replace_externs_as_inj. (*rewrite replace_externs_frgnBlocksSrc, replace_externs_locBlocksSrc. *) eapply restrict_val_inject; try eassumption. intros. destruct (getBlocks_inject (as_inj nu') (ret1::nil) (ret2::nil)) with (b:=b) as [bb [dd [JJ' GBbb]]]; try eassumption. constructor. assumption. constructor. remember (locBlocksSrc nu' b) as d. destruct d; simpl; trivial. apply andb_true_iff. split. eapply as_inj_DomRng; eassumption. apply REACH_nil. unfold exportedSrc. rewrite H. trivial. unfold vis. rewrite replace_externs_locBlocksSrc, replace_externs_frgnBlocksSrc, replace_externs_as_inj. destruct (eff_after_check2 _ _ _ _ _ MemInjNu' RValInjNu' _ (eq_refl _) _ (eq_refl _) _ (eq_refl _) WDnu' SMvalNu'). intuition. (*last goal: globalfunction_ptr_inject *) red; intros. destruct (GF _ _ H1). split; trivial. eapply extern_incr_as_inj; try eassumption. rewrite replace_locals_as_inj. assumption. Qed. Lemma transl_expr_correctMu: forall e le m a v te tle tm mu (EVAL: Clight.eval_expr ge e le m a v) (MENV : match_env (restrict (as_inj mu) (vis mu)) e te) (TENV : match_tempenv (restrict (as_inj mu) (vis mu)) le tle) (INJ : Mem.inject (as_inj mu) m tm) (PG : meminj_preserves_globals ge (as_inj mu)) (RC: REACH_closed m (vis mu)) (GLOB: forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true), forall ta, transl_expr a = OK ta -> exists tv, val_inject (restrict (as_inj mu) (vis mu)) v tv /\ eval_expr tge te tle tm ta tv. Proof. intros. assert (MinjR: Mem.inject (restrict (as_inj mu) (vis mu)) m tm). eapply inject_restrict; eassumption. assert (PGR: meminj_preserves_globals ge (restrict (as_inj mu) (vis mu))). assert (PGR': meminj_preserves_globals ge (as_inj (restrict_sm mu (vis mu)))). eapply restrict_sm_preserves_globals; try eassumption. unfold vis. intuition. rewrite restrict_sm_all in PGR'. assumption. eapply (transl_expr_correct _ _ _ _ _ _ _ MENV TENV MinjR PGR); eassumption. Qed. Lemma transl_arglist_correctMu: forall e le m al tyl vl mu te tle tm (EVAL:Clight.eval_exprlist ge e le m al tyl vl) (MENV : match_env (restrict (as_inj mu) (vis mu)) e te) (TENV : match_tempenv (restrict (as_inj mu) (vis mu)) le tle) (INJ : Mem.inject (as_inj mu) m tm) (PG : meminj_preserves_globals ge (as_inj mu)) (RC: REACH_closed m (vis mu)) (GLOB: forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true), forall tal, transl_arglist al tyl = OK tal -> exists tvl, val_list_inject (restrict (as_inj mu) (vis mu)) vl tvl /\ Csharpminor.eval_exprlist tge te tle tm tal tvl. Proof. intros. assert (MinjR: Mem.inject (restrict (as_inj mu) (vis mu)) m tm). eapply inject_restrict; eassumption. assert (PGR: meminj_preserves_globals ge (restrict (as_inj mu) (vis mu))). assert (PGR': meminj_preserves_globals ge (as_inj (restrict_sm mu (vis mu)))). eapply restrict_sm_preserves_globals; try eassumption. unfold vis. intuition. rewrite restrict_sm_all in PGR'. assumption. eapply transl_arglist_correct; try eassumption. Qed. Lemma blocks_of_bindingD: forall l b lo hi (I: In (b,lo,hi) (map block_of_binding l)), lo=0 /\ exists x, In (x,(b,hi)) l. Proof. intros l. induction l; simpl; intros. contradiction. destruct I. destruct a as [? [? ?]]. simpl in H. inv H. split; trivial. exists i; left; trivial. destruct (IHl _ _ _ H) as [HH [x Hx]]. split; trivial. exists x; right; trivial. Qed. Lemma blocks_of_envD: forall te b lo hi (I:In (b, lo, hi) (blocks_of_env te)), lo = 0 /\ exists x, te!x=Some(b,hi). Proof. intros. destruct (blocks_of_bindingD _ _ _ _ I) as [HH [x Hx]]. split; trivial. exists x. eapply PTree.elements_complete. apply Hx. Qed. Lemma Match_effcore_diagram: forall (st1 : CL_core) (m1 : mem) (st1' : CL_core) (m1' : mem) (U1 : block -> Z -> bool) (EFFSTEP: effstep (CL_eff_sem2 hf) ge U1 st1 m1 st1' m1') (st2 : CSharpMin_core) (mu : SM_Injection) (m2 : mem) (MC: MATCH st1 mu st1 m1 st2 m2), exists (st2' : CSharpMin_core) (m2' : mem) (mu' : SM_Injection), (exists U2 : block -> Z -> bool, (effstep_plus (csharpmin_eff_sem hf) tge U2 st2 m2 st2' m2' /\ (forall (UHyp: forall b z, U1 b z = true -> vis mu b = true) b ofs, U2 b ofs = true -> visTgt mu b = true /\ (locBlocksTgt mu b = false -> exists (b1 : block) (delta1 : Z), foreign_of mu b1 = Some (b, delta1) /\ U1 b1 (ofs - delta1) = true /\ Mem.perm m1 b1 (ofs - delta1) Max Nonempty)))) /\ intern_incr mu mu' /\ globals_separate ge mu mu' /\ sm_inject_separated mu mu' m1 m2 /\ sm_locally_allocated mu mu' m1 m2 m1' m2' /\ MATCH st1' mu' st1' m1' st2' m2'. Proof. intros. assert (SymbPres := symbols_preserved). induction EFFSTEP; simpl in *. { (*corestep_assign*) destruct MC as [SMC PRE]. inv SMC; simpl in *. try (monadInv TR). destruct PRE as [PC [PG [GF [Glob [SMV [WD INJ]]]]]]. assert (SAME: ts' = ts /\ tk' = tk). inversion MTR. auto. subst ts. unfold make_store, make_memcpy in EQ3. destruct (access_mode (typeof a1)); congruence. destruct SAME; subst ts' tk'. assert (MinjR: Mem.inject (restrict (as_inj mu) (vis mu)) m m2). eapply inject_restrict; eassumption. assert (PGR: meminj_preserves_globals ge (restrict (as_inj mu) (vis mu))). rewrite <- restrict_sm_all. eapply restrict_sm_preserves_globals; try eassumption. unfold vis. intuition. destruct (transl_lvalue_correct _ _ _ _ _ _ _ MENV TENV MinjR PGR _ _ _ H _ EQ) as [vv [Hvv1 EvalX]]; inv Hvv1. destruct (transl_expr_correct _ _ _ _ _ _ _ MENV TENV MinjR PGR _ _ H0 _ EQ1) as [uu [VinjU EvalX0]]. destruct (sem_cast_inject _ _ _ _ _ _ H1 VinjU) as [? [? ?]]. assert (EVAL:= make_cast_correct _ _ _ _ _ _ _ _ _ _ EQ0 EvalX0 H3). exploit assign_loc_inject. eassumption. econstructor. eapply restrictD_Some. eapply H5. reflexivity. eapply val_inject_incr; try eapply H4. apply restrict_incr. eassumption. intros [m2' [AL2 INJ']]. exploit make_store_correct_StoreEffect. eassumption. eassumption. eassumption. eassumption. intros EffStep'. specialize (assign_loc_freshloc _ _ _ _ _ _ H2). intros Freshloc. specialize (assign_loc_forward _ _ _ _ _ _ H2). intros FWD. inv H2; rewrite H6 in EffStep'. (*by_value*) eexists. eexists. exists mu. split. eexists. split. apply effstep_plus_one. eassumption. intros. apply StoreEffectD in H2. destruct H2 as [i [VV Arith]]. inv VV. split. eapply visPropagateR; eassumption. exists loc, delta. split. eapply restrict_vis_foreign; eassumption. inv H7. assert (WR:Mem.perm m loc (Int.unsigned ofs) Cur Writable). eapply Mem.store_valid_access_3; try eassumption. specialize (size_chunk_pos chunk); intros. omega. destruct (restrictD_Some _ _ _ _ _ H5) as [AI VIS]; clear H5. rewrite (Mem.address_inject _ _ _ loc ofs b delta Writable INJ WR AI) in Arith. rewrite encode_val_length in *. split. unfold assign_loc_Effect. rewrite H6. destruct (eq_block loc loc); simpl. clear e0. destruct (zle (Int.unsigned ofs) (ofs0 - delta)); simpl in *. destruct (zlt (ofs0 - delta) (Int.unsigned ofs + Z.of_nat (size_chunk_nat chunk))); simpl; trivial. clear - Arith g H4. omega. omega. elim n; trivial. rewrite <- size_chunk_conv in *. eapply Mem.perm_implies. eapply Mem.perm_max. eapply Mem.store_valid_access_3; try eassumption. omega. constructor. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b. rewrite Freshloc. intuition. rewrite (assign_loc_freshloc _ _ _ _ _ _ AL2). intuition. rewrite Freshloc. intuition. rewrite (assign_loc_freshloc _ _ _ _ _ _ AL2). intuition. econstructor. econstructor; eauto. reflexivity. constructor. destruct (restrictD_Some _ _ _ _ _ H5). intuition. clear AL2. inv H7. eapply REACH_Store; try eassumption. intros. rewrite getBlocks_char in H7. destruct H7. destruct H7; try contradiction; subst. inv H4. eapply (restrictD_Some _ _ _ _ _ H13). split; intros. eapply FWD. eapply SMV; assumption. eapply assign_loc_forward; try eassumption. eapply SMV; assumption. (*by_copy*) destruct EffStep' as [b2' [ofs2' [X2 EffStep']]]; subst x2. eexists. eexists. exists mu. split. eexists. split. apply effstep_plus_one. eassumption. clear EffStep'. simpl. intros. destruct (eq_block b b2); subst; simpl in *; try discriminate. inv H4. destruct (valid_block_dec m2 b2); simpl in *. rewrite andb_true_r in H2. Focus 2. rewrite andb_false_r in H2. inv H2. split; intros. eapply visPropagateR; eassumption. assert (WR:Mem.perm m loc (Int.unsigned ofs) Cur Writable). eapply Mem.storebytes_range_perm; try eassumption. rewrite (Mem.loadbytes_length _ _ _ _ _ H10). specialize (sizeof_pos (typeof a1)); intros. rewrite nat_of_Z_eq. omega. omega. exists loc, delta. split. eapply restrict_vis_foreign; try eassumption. destruct (restrictD_Some _ _ _ _ _ H5). specialize (Mem.address_inject _ _ _ loc ofs b2 delta Writable INJ WR H12). intros. rewrite H14 in *. unfold assign_loc_Effect. rewrite H6. destruct (eq_block loc loc); simpl. clear e0. destruct (zle (Int.unsigned ofs + delta) ofs0); simpl in *; try discriminate. destruct (zle (Int.unsigned ofs) (ofs0 - delta)); simpl. Focus 2. exfalso. clear - l g. omega. specialize (sizeof_pos (typeof a1)); intros. destruct (zlt ofs0 (Int.unsigned ofs + delta + sizeof (typeof a1))); try discriminate. destruct (zlt (ofs0 - delta) (Int.unsigned ofs + sizeof (typeof a1))); simpl. split; trivial. eapply Mem.perm_implies. eapply Mem.perm_max. eapply Mem.storebytes_range_perm; eauto. split. omega. rewrite (Mem.loadbytes_length _ _ _ _ _ H10). rewrite nat_of_Z_eq. assumption. omega. apply perm_any_N. exfalso. clear - l1 g. omega. elim n; trivial. clear H9 EffStep'. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b. rewrite Freshloc. intuition. rewrite (assign_loc_freshloc _ _ _ _ _ _ AL2). intuition. rewrite Freshloc. intuition. rewrite (assign_loc_freshloc _ _ _ _ _ _ AL2). intuition. econstructor. econstructor; eauto. reflexivity. constructor. destruct (restrictD_Some _ _ _ _ _ H5). intuition. clear AL2. inv H4. destruct (restrictD_Some _ _ _ _ _ H17). eapply REACH_Storebytes; try eassumption. simpl; intros. destruct (Mem.loadbytes_inject _ _ _ _ _ _ _ _ _ MinjR H10 H17) as [bytes' [_ MVInj]]. clear H10 H11. induction MVInj; simpl in *. contradiction. destruct H15; subst. inv H10. eapply (restrictD_Some _ _ _ _ _ H19). apply (IHMVInj H11). split; intros. eapply FWD. eapply SMV; assumption. eapply assign_loc_forward; try eassumption. eapply SMV; assumption. } { (*clight_corestep_set*) destruct MC as [SMC PRE]. inv SMC; simpl in *. try (monadInv TR). inv MTR. destruct PRE as [PC [PG [GF [Glob [SMV [WD INJ]]]]]]. exploit transl_expr_correctMu; try eassumption. intros [uu [VinjU EvalX0]]. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. econstructor. eassumption. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. econstructor. eapply match_states_skip; eauto. eapply match_tempenv_set; eassumption. intuition. } { (*clight_corestep_call*) destruct MC as [SMC PRE]. inv SMC; simpl in *. revert TR. simpl. case_eq (classify_fun (typeof a)); try congruence. intros targs tres CF TR. monadInv TR. inv MTR. exploit functions_translated; eauto. intros [tfd [FIND TFD]]. rewrite H in CF. simpl in CF. inv CF. destruct PRE as [PC [PG [GF [Glob [SMV [WD INJ]]]]]]. exploit transl_expr_correctMu; try eassumption. intros [tvf [VinjE EvalE]]. exploit transl_arglist_correctMu; try eassumption. intros [tvl [Vargs EvalArgs]]. inv VinjE; inv FIND. destruct (Int.eq_dec ofs1 Int.zero); try inv H6. destruct (GF _ _ H2). destruct (restrictD_Some _ _ _ _ _ H4). rewrite H8 in H5; inv H5. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. econstructor; try eassumption. eapply transl_fundef_sig1; eauto. rewrite H3. auto. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. econstructor. econstructor; eauto. econstructor; eauto. econstructor. intuition. } { (* builtin *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. destruct PRE as [PC [PG [GF [Glob [SMV [WD INJ]]]]]]. assert (InjR: Mem.inject (restrict (as_inj mu) (vis mu)) m m2). eapply inject_restrict; eassumption. assert (PGR: meminj_preserves_globals ge (restrict (as_inj mu) (vis mu))). rewrite <- restrict_sm_all. eapply restrict_sm_preserves_globals; try eassumption. unfold vis. intuition. exploit transl_arglist_correctMu; try eassumption. intros [tvargs [EVAL2 VINJ2]]. exploit (inlineable_extern_inject _ _ GDE_lemma); try eapply H0; try eassumption. intros [mu' [vres' [tm' [EC [VINJ [MINJ' [UNMAPPED [OUTOFREACH [INCR [SEPARATED [GSEP [LOCALLOC [WD' [VAL' RC']]]]]]]]]]]]]]. eexists; eexists; eexists mu'. split. eexists. split. apply effstep_plus_one. econstructor; eassumption. intros. eapply BuiltinEffect_Propagate; eassumption. intuition. split. assert (INC:= intern_incr_restrict _ _ WD' INCR). econstructor; eauto. Focus 5. eapply match_cont_inject_incr; eassumption. reflexivity. constructor. eapply match_env_inject_incr; eassumption. assert (TENV':= match_tempenv_inject_incr _ _ _ TENV _ INC). destruct optid; trivial; simpl. eapply match_tempenv_set; eassumption. intuition. eapply meminj_preserves_incr_sep. eapply PG. eassumption. apply intern_incr_as_inj; trivial. apply sm_inject_separated_mem; eassumption. red. intros b fbb Hb. destruct (GF _ _ Hb). split; trivial. eapply intern_incr_as_inj; eassumption. assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INCR. rewrite <- FRG. apply Glob; assumption. } { (* seq *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. constructor. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. econstructor. econstructor; eauto. econstructor; eauto. econstructor; eauto. intuition. } { (* skip seq *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. inv MK. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. apply csharpmin_effstep_skip_seq. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. econstructor. econstructor; eauto. econstructor; eauto. intuition. } { (* continue seq *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. inv MK. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. econstructor; eauto. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. econstructor. econstructor; eauto. econstructor; eauto. econstructor; eauto. intuition. } { (* break seq *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. inv MK. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. econstructor; eauto. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. econstructor. econstructor; eauto. econstructor; eauto. econstructor; eauto. intuition. } { (* ifthenelse *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. destruct PRE as [PC [PG [GF [Glob [SMV [WD INJ]]]]]]. exploit make_boolean_inject; eauto. eapply inject_restrict; eassumption. assert (PGR': meminj_preserves_globals ge (as_inj (restrict_sm mu (vis mu)))). eapply restrict_sm_preserves_globals; try eassumption. unfold vis. intuition. rewrite restrict_sm_all in PGR'. assumption. intros [tv [Etv Btv]]. exploit transl_expr_correctMu; try eassumption. intros [tv1 [V1inj EvalV1]]. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. apply csharpmin_effstep_ifthenelse with (v := tv) (b := b); auto. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality bb; try rewrite (freshloc_irrefl); intuition. econstructor. destruct b; econstructor; eauto; constructor. intuition. } { (* loop *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. exists (CSharpMin_State tf x (Kblock (Kseq x0 (Kseq (Sloop (Sseq (Sblock x) x0)) (Kblock tk)))) te tle). eexists. exists mu. split. eexists; split. eapply effstep_star_plus_trans. eapply match_transl_effstep; eauto. eapply effstep_plus_star_trans. eapply effstep_plus_one. econstructor. eapply effstep_star_trans. eapply effstep_star_one. econstructor. eapply effstep_star_one. econstructor. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. econstructor. econstructor; try eassumption. econstructor. econstructor; eassumption. intuition. } { (* skip-or-continue loop *) destruct MC as [SMC PRE]. inv SMC; simpl in *. assert ((ts' = Sskip \/ ts' = Sexit ncnt) /\ tk' = tk). destruct H; subst x; monadInv TR; inv MTR; auto. destruct H0. inv MK. eexists; eexists. exists mu. split. eexists; split. eapply effstep_plus_star_trans. destruct H0; subst ts'. Focus 2. eapply effstep_plus_one. econstructor. eapply effstep_plus_one. econstructor. eapply effstep_star_one. econstructor. intuition. clear H0 H. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. econstructor. econstructor; eauto. econstructor; eauto. econstructor; eauto. intuition. } { (* break loop1 *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. inv MK. eexists; eexists. exists mu. split. eexists; split. eapply effstep_plus_star_trans. eapply effstep_plus_one. econstructor. eapply effstep_star_trans. eapply effstep_star_one. econstructor. eapply effstep_star_trans. eapply effstep_star_one. econstructor. eapply effstep_star_one. econstructor. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. econstructor. eapply match_states_skip; eauto. intuition. } { (* skip loop2 *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. inv MK. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. constructor. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. econstructor. econstructor; eauto. simpl. rewrite H5; simpl. rewrite H7; simpl. eauto. constructor. intuition. } { (* break loop2 *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. inv MK. eexists; eexists. exists mu. split. eexists; split. eapply effstep_plus_trans. eapply effstep_plus_one. constructor. eapply effstep_plus_one. constructor. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. econstructor. eapply match_states_skip; eauto. intuition. } { (* return none *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. destruct PRE as [PC [PG [GF [Glob [SMV [WD INJ]]]]]]. exploit match_env_free_blocks_parallel_inject; eauto. eapply inject_restrict; eassumption. intros [m2' [FL2 Inj']]. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. constructor. eassumption. intros U1Vis b2 ofs FEff2. split. apply FreelistEffect_exists_FreeEffect in FEff2. destruct FEff2 as [bb [lo [hi [NIB FEF]]]]. apply FreeEffectD in FEF. destruct FEF as [? [VB Arith2]]; subst. apply blocks_of_envD in NIB. destruct NIB as [? [id ID]]; subst. apply (me_local_inv _ _ _ MENV) in ID. destruct ID as [b [ty [RES EE]]]. eapply visPropagateR; try eassumption. intros. eapply FreelistEffect_PropagateLeft; eassumption. assert (SMV': sm_valid mu m' m2'). split; intros; eapply freelist_forward; try eassumption. eapply SMV; assumption. eapply SMV; assumption. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_free_list _ _ _ FL2); try rewrite (freshloc_free_list _ _ _ H); intuition. econstructor. econstructor; eauto. eapply match_cont_call_cont. eauto. intuition. eapply REACH_closed_freelist; eassumption. eapply freelist_freelist_inject; try eassumption. eapply match_env_restrictD; eassumption. } { (* return some *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. destruct PRE as [PC [PG [GF [Glob [SMV [WD INJ]]]]]]. assert (InjR: Mem.inject (restrict (as_inj mu) (vis mu)) m m2). eapply inject_restrict; eassumption. assert (PGR: meminj_preserves_globals ge (restrict (as_inj mu) (vis mu))). rewrite <- restrict_sm_all. eapply restrict_sm_preserves_globals; try eassumption. unfold vis. intuition. exploit match_env_free_blocks_parallel_inject; eauto. intros [m2' [FL2 Inj']]. destruct (transl_expr_correct _ _ _ _ _ _ _ MENV TENV InjR PGR _ _ H _ EQ) as [tv [VInj EvalA]]. destruct (sem_cast_inject _ _ _ _ _ _ H0 VInj) as [tv' [SemCast' VInj']]. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. constructor; try eassumption. eapply make_cast_correct; eauto. intros U1Vis b2 ofs FEff2. split. apply FreelistEffect_exists_FreeEffect in FEff2. destruct FEff2 as [bb [lo [hi [NIB FEF]]]]. apply FreeEffectD in FEF. destruct FEF as [? [VB Arith2]]; subst. apply blocks_of_envD in NIB. destruct NIB as [? [id ID]]; subst. apply (me_local_inv _ _ _ MENV) in ID. destruct ID as [b [ty [RES EE]]]. eapply visPropagateR; try eassumption. intros. eapply FreelistEffect_PropagateLeft; eassumption. assert (SMV': sm_valid mu m' m2'). split; intros; eapply freelist_forward; try eassumption. eapply SMV; assumption. eapply SMV; assumption. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_free_list _ _ _ FL2); try rewrite (freshloc_free_list _ _ _ H1); intuition. econstructor. econstructor; eauto. eapply match_cont_call_cont. eauto. intuition. eapply REACH_closed_freelist; eassumption. eapply freelist_freelist_inject; try eassumption. eapply match_env_restrictD; eassumption. } { (* skip call *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. exploit match_cont_is_call_cont; eauto. intros [A B]. destruct PRE as [PC [PG [GF [Glob [SMV [WD INJ]]]]]]. assert (InjR: Mem.inject (restrict (as_inj mu) (vis mu)) m m2). eapply inject_restrict; eassumption. destruct (match_env_free_blocks_parallel_inject _ _ _ _ _ _ MENV InjR H0) as [m2' [FL2 Inj']]. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. apply csharpmin_effstep_skip_call. auto. eassumption. intros U1Vis b2 ofs FEff2. split. apply FreelistEffect_exists_FreeEffect in FEff2. destruct FEff2 as [bb [lo [hi [NIB FEF]]]]. apply FreeEffectD in FEF. destruct FEF as [? [VB Arith2]]; subst. apply blocks_of_envD in NIB. destruct NIB as [? [id ID]]; subst. apply (me_local_inv _ _ _ MENV) in ID. destruct ID as [b [ty [RES EE]]]. eapply visPropagateR; try eassumption. intros. eapply FreelistEffect_PropagateLeft; eassumption. assert (SMV': sm_valid mu m' m2'). split; intros; eapply freelist_forward; try eassumption. eapply SMV; assumption. eapply SMV; assumption. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_free_list _ _ _ FL2); try rewrite (freshloc_free_list _ _ _ H0); intuition. econstructor. econstructor; eauto. intuition. eapply REACH_closed_freelist; eassumption. eapply freelist_freelist_inject; try eassumption. eapply match_env_restrictD; eassumption. } { (* switch *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. destruct PRE as [PC [PG [GF [Glob [SMV [WD INJ]]]]]]. assert (InjR: Mem.inject (restrict (as_inj mu) (vis mu)) m m2). eapply inject_restrict; eassumption. assert (PGR: meminj_preserves_globals ge (restrict (as_inj mu) (vis mu))). rewrite <- restrict_sm_all. eapply restrict_sm_preserves_globals; try eassumption. unfold vis. intuition. destruct (transl_expr_correct _ _ _ _ _ _ _ MENV TENV InjR PGR _ _ H _ EQ) as [tv [VInj EvalA]]. inv VInj. eexists; eexists. exists mu. split. eexists; split. eapply effstep_star_plus_trans. eapply match_transl_effstep; eauto. eapply effstep_plus_one. econstructor. eauto. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. econstructor. econstructor; try eassumption. apply transl_lbl_stmt_2. apply transl_lbl_stmt_1. eauto. constructor. econstructor. eauto. intuition. } { (* skip or break switch *) destruct MC as [SMC PRE]. inv SMC; simpl in *. assert ((ts' = Sskip \/ ts' = Sexit nbrk) /\ tk' = tk). destruct H; subst x; monadInv TR; inv MTR; auto. destruct H0. inv MK. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. destruct H0; subst ts'. 2: constructor. constructor. intuition. clear H0 H. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. econstructor. eapply match_states_skip; eauto. intuition. } { (* continue switch *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. inv MK. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. constructor. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. constructor. econstructor; eauto. simpl. reflexivity. constructor. intuition. } { (* label *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. constructor. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. constructor. econstructor; eauto. constructor. intuition. } { (* goto *) destruct MC as [SMC PRE]. inv SMC; simpl in *. monadInv TR. inv MTR. generalize TRF. unfold transl_function. intro TRF'. monadInv TRF'. exploit (transl_find_label lbl). eexact EQ. eapply match_cont_call_cont. eauto. rewrite H. intros [ts' [tk'' [nbrk' [ncnt' [A [B C]]]]]]. eexists; eexists. exists mu. split. eexists; split. apply effstep_plus_one. constructor. simpl. eexact A. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. constructor. econstructor; eauto. constructor. intuition. } { (* internal function *) destruct MC as [SMC PRE]. inv SMC; simpl in *. destruct PRE as [PC [PG [GF [Glob [SMV [WD INJ]]]]]]. inv H. monadInv TR. monadInv EQ. exploit match_cont_is_call_cont; eauto. intros [A B]. exploit match_env_alloc_variables; try eassumption. apply match_env_empty. intros [te1 [m2' [mu' [AVars2 [MENV' [INJ' [INC' [SEP' [LAC' [WD' [VAL' RC']]]]]]]]]]]. specialize (create_undef_temps_match_inject (Clight.fn_temps f) (restrict (as_inj mu') (vis mu'))); intros. destruct (bind_parameter_temps_match_inject _ _ _ _ H4 _ _ H args2) as [tle [BP TENV]]. eapply val_list_inject_incr; try eassumption. eapply intern_incr_restrict; eassumption. eexists; exists m2'. exists mu'. split. eexists; split. apply effstep_plus_one. eapply csharpmin_effstep_internal_function. simpl. rewrite list_map_compose. simpl. assumption. simpl. auto. simpl. auto. simpl. eauto. simpl. eassumption. intuition. intuition. solve [eapply intern_incr_globals_separate; eauto]. constructor. simpl. econstructor; try eassumption. unfold transl_function. rewrite EQ0; simpl. auto. constructor. eapply match_cont_inject_incr; try eassumption. eapply intern_incr_restrict; eassumption. destruct (@intern_incr_meminj_preserves_globals_as_inj _ _ ge _ WD) with (mu' := mu'). split; trivial. trivial. trivial. intuition. red; intros. destruct (GF _ _ H8). split; trivial. eapply intern_incr_as_inj; eassumption. } { (* returnstate *) destruct MC as [SMC PRE]. inv SMC; simpl in *. inv MK. eexists; exists m2. exists mu. split. eexists; split. apply effstep_plus_one. constructor. intuition. intuition. apply intern_incr_refl. apply gsep_refl. apply sm_inject_separated_same_sminj. apply sm_locally_allocatedChar. repeat split; extensionality b; try rewrite (freshloc_irrefl); intuition. constructor. econstructor; eauto. simpl; reflexivity. constructor. unfold set_opttemp. destruct optid. eapply match_tempenv_set; eassumption. simpl. assumption. intuition. } Qed. Lemma match_cont_replace_locals: forall mu tp n m k k' PS PT (MC: match_cont (as_inj mu) tp n m k k'), match_cont (as_inj (replace_locals mu PS PT)) tp n m k k'. Proof. intros. rewrite replace_locals_as_inj; trivial. Qed. Lemma MATCH_atExternal: forall (mu : SM_Injection) (c1 : CL_core) (m1 : mem) (c2 : CSharpMin_core) (m2 : mem) (e : external_function) (vals1 : list val) (ef_sig : signature), MATCH c1 mu c1 m1 c2 m2 -> at_external (CL_eff_sem2 hf) c1 = Some (e, ef_sig, vals1) -> Mem.inject (as_inj mu) m1 m2 /\ (exists vals2 : list val, Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2 /\ at_external (csharpmin_eff_sem hf) c2 = Some (e, ef_sig, vals2) /\ (forall pubSrc' pubTgt' : block -> bool, pubSrc' = (fun b : block => locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b) -> pubTgt' = (fun b : block => locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b) -> forall nu : SM_Injection, nu = replace_locals mu pubSrc' pubTgt' -> MATCH c1 nu c1 m1 c2 m2 /\ Mem.inject (shared_of nu) m1 m2)). Proof. intros. destruct H as [MC [RC [PG [GFP [Glob [SMV [WD INJ]]]]]]]. split; trivial. destruct c1; inv H0. destruct fd; inv H1. inv MC. simpl in TY. inv TY. specialize (val_list_inject_forall_inject _ _ _ ArgsInj). intros ValsInj. specialize (forall_vals_inject_restrictD _ _ _ _ ValsInj); intros. exploit replace_locals_wd_AtExternal; try eassumption. intros WDr. remember (observableEF_dec hf e0) as d. destruct d; inv H0. destruct (vals_def args) eqn:Heqv; inv H2. rename o into OBS. exists args2; intuition. destruct tfd; simpl in *. remember ( list_typ_eq (sig_args (ef_sig e)) (typlist_of_typelist targs) && opt_typ_eq (sig_res (ef_sig e)) (opttyp_of_type tres)) as q. destruct q; inv TR. remember ( list_typ_eq (sig_args (ef_sig e)) (typlist_of_typelist targs) && opt_typ_eq (sig_res (ef_sig e)) (opttyp_of_type tres)) as q. destruct q; inv TR. rewrite <- Heqd. trivial. (*MATCH*) split; subst; rewrite replace_locals_as_inj, replace_locals_vis. econstructor; repeat rewrite restrict_sm_all, vis_restrict_sm, replace_locals_vis, replace_locals_as_inj in *; eauto. simpl. reflexivity. rewrite replace_locals_frgnBlocksSrc. intuition. (*sm_valid*) red. rewrite replace_locals_DOM, replace_locals_RNG. apply SMV. (*Shared*) eapply inject_shared_replace_locals; try eassumption. subst; trivial. Qed. (** The simulation proof *) Theorem transl_program_correct: forall (R: list_norepet (map fst (prog_defs prog))), SM_simulation.SM_simulation_inject (CL_eff_sem2 hf) (csharpmin_eff_sem hf) ge tge. Proof. intros. eapply simulations_lemmas.inj_simulation_plus with (match_states:=MATCH) (measure:=fun x => O). (*genvs_dom_eq*) apply GDE_lemma. (*MATCH_wd*) apply MATCH_wd. (*MATCH_reachclosed*) apply MATCH_RC. (*MATCH_restrict apply MATCH_restrict.*) (*MATCH_valid*) apply MATCH_valid. (*MATCH_preserves_globals*) apply MATCH_PG. (*MATCHinitial*) { intros. eapply (MATCH_initial _ _ _); eauto. apply GDE_lemma. } (*halted*) { intros. destruct H as [MC [RC [PG [GF [Glob [VAL [WD INJ]]]]]]]. destruct c1; inv H0. destruct k; inv H1. destruct (negb (is_vundef res)); inv H0. inv MC. exists res2. split. assumption. split. eassumption. simpl. inv MK. trivial. } (* at_external*) { apply MATCH_atExternal. } (* after_external*) { apply MATCH_afterExternal. apply GDE_lemma. } (* effcore_diagram*) { intros. exploit Match_effcore_diagram; try eassumption. intros [st2' [m2' [mu' [[U2 CS2] MU']]]]. exists st2', m2', mu'. intuition. exists U2. split. left; assumption. assumption. } Qed. End CORRECTNESS.
using ATA # For load data to input in custom obj_fun: using CSV using FileIO using LinearAlgebra cd("where your input files are") # 1. Start ATA and add file with custom settings (Needed) ata_model = start_ata(; settings_file = "settings_ata_custom.jl", bank_file = "data/bank.csv", bank_delim = ";", ) # 2. Add categorical constraints (Optional) add_constraints!(ata_model; constraints_file = "constraints.csv", constraints_delim = ";") # 3. Add overlap maxima (Optional) add_overlap!(ata_model; overlap_file = "overlap_matrix.csv", overlap_delim = ";") # custom objective type, function and arguments ata_model.obj.name = "custom" ata_model.obj.fun = function (x::Matrix{Float64}, obj_args::NamedTuple) IIF = obj_args.IIF T = obj_args.T TIF = zeros(Float64, T) for t = 1:T K, I = size(IIF[t]) # ungroup items xₜ = fs_to_items(x[:, t], I, obj_args.fs_items) if K > 1 TIF[t] = Inf for k = 1:K TIF[t] = min(TIF[t], LinearAlgebra.dot(IIF[t][k, :], xₜ)) end else TIF[t] = LinearAlgebra.dot(IIF[t][1, :], xₜ)[1] end end min_TIF = minimum(TIF) TIF = [min_TIF for t = 1:T] # Must return a vector of length T. # The resulting objective function is the minimum of all values in this vector. return TIF::Vector{Float64} end ata_model.obj.args = ( T = ata_model.settings.T, IIF = FileIO.load("data/IIF.jld2", "IIF"), fs_items = ata_model.settings.fs.items, ) print_infos(ata_model) # Assembly settings # SIMAN (Suggested for Large scale ATA): # Set the solver, "siman" for simulated annealing, "jump" for MILP solver. solver = "siman" # SIMAN (Suggested for Large scale ATA): start_temp = 0.0001 # Default: `0.1`. Values: `[0, Inf]`. # Starting temperature, set to minimum for short journeys (if 0 worse solutions will never be accepted). geom_temp = 0.1 # Default: `0.1`. Values: `[0, Inf)`. # Decreasing geometric factor. n_item_sample = Inf # Default: 1. Values: `[1, Inf]`. # Number of items to alter. Set to minimum for a shallow analysis, # set to maximum for a deep analysis of the neighbourhoods. n_test_sample = ata_model.settings.T # Default: 1. Values: `[1, Inf]`. # Number of tests to alter. Set to minimum for a shallow analysis, set to maximum for a deep analysis of the neighbourhoods. opt_feas = 0.9 # Default: 0.0. Values: `[0, Inf)`. # Optimality/feasibility balancer, if 0 only feasibility of solution is analysed. Viceversa, if 1, only optimality is considered (uncontrained model). All the other values are accepted but produce uninterpretable results. n_fill = 1 # Default: 1. Values: `[0, Inf)`. # Number of fill-up phases, usually 1 is sufficient, if start_temp is high it can be higher. # If a starting_design is supplied, it should be set to 0. verbosity = 1 # Default: 2. Values: `1` (minimal), `2` (detailed). # Verbosity level. In the console '+' stands for improvement, '_' for accepting worse solution. # The dots are the fill-up improvement steps. #! Termination criteria: max_time = 100.0 # Default: `1000.0`. Values: `[0, Inf)`. # Time limit in seconds. max_conv = 5 # Default: `2`. Values: `[1, Inf)`. # Maximum convergence, stop when, after max_conv rounds no improvements have been found. # Set to minimum for shallow analysis, increase it for deep analysis of neighbourhoods. feas_nh = 1 # Default: `0`. Values: `[1, Inf)`. # Maximum number of Feasibility neighbourhoods to explore, set to the minimum if the model is small or not highly constrained. opt_nh = Inf # Default: `5`. Values: `[1, Inf)`. # Maximum number of Optimality neighbourhoods to explore, set to the minimum if the model is highly constrained. # 4. assemble assemble!( ata_model; solver = solver, max_time = max_time, start_temp = start_temp, geom_temp = geom_temp, n_item_sample = n_item_sample, n_test_sample = n_test_sample, verbosity = verbosity, max_conv = max_conv, opt_feas = opt_feas, n_fill = n_fill, feas_nh = feas_nh, opt_nh = opt_nh,# , # optimizer_attributes = optimizer_constructor, # optimizer_constructor =optimizer_attributes ) # All the settings and outputs from optimization are in ata_model object. # See the struct in ATA.jl to understand how to retrieve all the information. # A summary of the resulting tests is available in results_folder/results.txt # If siman is chosen, the optimality and feasibility of the best neighbourhood # is reported in "results/results_ata.jl" ata_model.obj.name = "maximin" print_results(ata_model; results_folder = "results") #]add https://github.com/giadasp/ATAPlot.jl using ATAPlot plot_results(ata_model; plots_folder = "plots")
The norm of the exponential function is the exponential function.
import numpy as np import MicEMD.tdem as tdem from MicEMD.preprocessor import data_prepare from MicEMD.handler import TDEMHandler import math # the attribute of the steel, Ni, and Al including permeability, permeability of vacuum and conductivity attribute = np.array([[696.3028547, 4*math.pi*1e-7, 50000000], [99.47183638, 4*math.pi*1e-7, 14619883.04], [1.000022202, 4*math.pi*1e-7, 37667620.91]]) # create and initial the target, detector, collection class of Tdem target = tdem.Target(material=['Steel', 'Ni', 'Al'], shape=['Oblate spheroid', 'Prolate spheroid'], attribute=attribute, ta_min=0.01, ta_max=1.5, tb_min=0.01, tb_max=1.5, a_r_step=0.08, b_r_step=0.08) detector = tdem.Detector(0.4, 20, 0, 0) collection = tdem.Collection(t_split=20, snr=30) # call the simulate interface, the forward_result is a tuple which conclude the Sample Set and a random # sample of Sample Set, the random sample of Sample Set is used to visualize fwd_res = tdem.simulate(target, detector, collection, model='dipole') # split data sets and normalization for the Sample Set, Here we classify materials ori_dataset_material = data_prepare(fwd_res[0], task='material') # dimensionality reduction, return a tuple conclude train_set and test_set dim_dataset_material = tdem.preprocess(ori_dataset_material, dim_red_method='PCA', n_components=20) # parameters setting of the classification model by dict para = {'solver': 'lbfgs', 'hidden_layer_sizes': (50,), 'activation': 'tanh'} # call the classify interface # the res of the classification which is a dict that conclude accuracy, predicted value and true value cls_material_res = tdem.classify(dim_dataset_material, 'ANN', para) # create the TDEMHandler and call the methods to show and save the results # set the TDEMHandler without parameters to save the results # the file path of the results is generated by your settings handler = TDEMHandler() # save the forward results and one sample data handler.save_fwd_data(fwd_res[0], file_name='fwd_res.csv') handler.save_sample_data(fwd_res[1], file_name='sample.csv', show=True) # save the original dataset that distinguishes material handler.save_fwd_data(ori_dataset_material[0], file_name='ori_material_train.csv') handler.save_fwd_data(ori_dataset_material[1], file_name='ori_material_test.csv') # save the final dataset after dimensionality reduction handler.save_fwd_data(dim_dataset_material[0], file_name='dim_material_train.csv') handler.save_fwd_data(dim_dataset_material[1], file_name='dim_material_test.csv') # save the classification results handler.show_cls_res(cls_material_res, ['Steel', 'Ni', 'Al'], show=True, save=True, file_name='cls_result_material.pdf') handler.save_cls_res(cls_material_res, 'cls_material_res.csv') # classify the shape of the targets ori_dataset_shape = data_prepare(fwd_res[0], task='shape') dim_dataset_shape = tdem.preprocess(ori_dataset_shape, dim_red_method='PCA', n_components=20) cls_shape_res = tdem.classify(dim_dataset_shape, 'ANN', para) # save the original dataset that distinguishes material handler.save_fwd_data(ori_dataset_shape[0], file_name='ori_shape_train.csv') handler.save_fwd_data(ori_dataset_shape[1], file_name='ori_shape_test.csv') # save the final dataset after dimensionality reduction handler.save_fwd_data(dim_dataset_shape[0], file_name='dim_shape_train.csv') handler.save_fwd_data(dim_dataset_shape[1], file_name='dim_shape_test.csv') handler.show_cls_res(cls_shape_res, ['Oblate spheroid', 'Prolate spheroid'], show=True, save=True, file_name='cls_result_shape.pdf') handler.save_cls_res(cls_shape_res, 'cls_shape_res.csv')
{-| Module: Numeric.Morpheus Description: Low-level machine learning auxiliary functions Copyright: (c) Alexander Ignatyev, 2017 License: BSD-3 Stability: experimental Portability: POSIX Purely functional interface to morpheus based on hmatrix. Morpheus library contains a bunch of cache line aware numerical algorithms suitable for using as a low-level primitives to build machine learning applications. Naive implementations, which do not take into account cache lines, would suffer order of magnitude performance degradation if tried to traverse a row major matrix in column order. The library functions take into account CPU cache and work well for both row major and column major matrices, as you can see from the benchmark below which measure time for finding indices of max elements for every column and every row in comparison with naive approach: @ | Benchmark | Morheus | Naive | +-------------------------------------+-----------+----------+ | max index in columns - row major | 0.9077 ms | 12.93 ms | +-------------------------------------+-----------+----------+ | max index in columns - column major | 0.8778 ms | 1.490 ms | +-------------------------------------+-----------+----------+ | max index in rows - row major | 0.8622 ms | 1.504 ms | +-------------------------------------+-----------+----------+ | max index in rows - column major | 0.8913 ms | 12.80 ms | +-------------------------------------+-----------+----------+ @ == Examples @ import Numeric.LinearAlgebra import Numeric.Morpheus a = matrix 5 [ 71, 11, 3, -9, -7, 21, -7, -2, 23, 11, -11, 32, 53, -49, 37, 1, -24, 78, 90, 17 ] main :: IO () main = do putStrLn "\nNumeric.Morpheus.MatrixReduce functions: " putStr "sum of elements of rows: " print $ rowSum a putStr "product of elements of rows: " print $ rowPredicate (*) a putStr "max values of columns: " print $ fst $ columnMaxIndex a putStr "indices of max values of columns: " print $ snd $ columnMaxIndex a putStrLn "\n\nNumeric.Morpheus.Activation functions: " putStrLn "\nSigmoid:" disp 3 (sigmoid a) putStrLn "ReLu:" disp 3 (relu a) putStrLn "ReLu gradient:" disp 3 (reluGradient a) putStrLn "\n\nNumeric.Morpheus.Statistics functions: " putStrLn "\nColumn Means:" let colmeans = columnMean a print colmeans putStrLn "Column Standard Deviations: " print (columnStddev_m colmeans a) @ -} module Numeric.Morpheus ( module Numeric.Morpheus.Activation , module Numeric.Morpheus.MatrixReduce , module Numeric.Morpheus.Statistics ) where import Numeric.Morpheus.Activation import Numeric.Morpheus.MatrixReduce import Numeric.Morpheus.Statistics
import numpy as np import cv2 # from cvutil.basicf import * # from cvutil.filter import * import matplotlib.pyplot as plt from CORS_utils import * def intensity(bgr_img): """Return intensity image computed by (R+G+B)/3. Used with color_opponency as an intensity channel.""" if np.ndim(bgr_img) != 3: raise ValueError('bgr_img must be BGR image (3 dimensions), not ' + str(np.ndim(bgr_img))) img_b, img_g, img_r = cv2.split(bgr_img.astype(np.float)) imgray = (img_b+img_g+img_r)/3.0 #imgray = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY).astype(np.float) return imgray def color_opponency(bgr_img): """Return tuple of color opponency from BGR color image(in format: [RG,GR,BY,YB])""" if np.ndim(bgr_img) != 3: raise ValueError('bgr_img must be BGR image (3 dimensions), not ' + str(np.ndim(bgr_img))) img_b, img_g, img_r = cv2.split(bgr_img.astype(np.float)) fimg_R = NoNegative(img_r - (img_g+img_b)/2.0) fimg_G = NoNegative(img_g - (img_r+img_b)/2.0) fimg_B = NoNegative(img_b - (img_r+img_g)/2.0) fimg_Y = NoNegative((img_r+img_g)/2.0 - np.abs(img_r-img_g)/2.0 - img_b) fimg_RG = NoNegative(fimg_R-fimg_G) fimg_GR = NoNegative(fimg_G-fimg_R) fimg_BY = NoNegative(fimg_B-fimg_Y) fimg_YB = NoNegative(fimg_Y-fimg_B) return [fimg_RG, fimg_GR, fimg_BY, fimg_YB] def LocalFigureNorm(src,figureRatio=0.2): """ Subtract src from boxFilter version of itself, with radius 0.2 of its side. Parameters: ========== - figureRatio is approximated figure's size compared to src's width. """ h,w = src.shape[:2] th,tw = int(h*figureRatio), int(w*figureRatio) figApprx = cv2.boxFilter(src, -1, (tw,tw)) return WNorm(MinMaxNorm(NoNegative(src-figApprx))) def WNorm(src): """Divide by sqrt of number of local maxima, e.g. too promote few local peaks""" peaks = local_maxima(src, 3) if len(peaks)==0: return src else: return src/float(np.sqrt(len(peaks))) def OnOffFM(i_gpyr): """On,off center-surround intensity maps""" onpyr = [] offpyr = [] for i in xrange(0,len(i_gpyr)): # scale 2,3,4 curi = i_gpyr[i] surround3 = cv2.boxFilter(curi, -1, (7,7)) surround7 = cv2.boxFilter(curi, -1, (15,15)) on3 = NoNegative(curi - surround3) on7 = NoNegative(curi - surround7) off3 = NoNegative(surround3 - curi) off7 = NoNegative(surround7 - curi) onpyr.append(on3+on7) offpyr.append(off3+off7) onmap = AcrossScaleAddition(onpyr) offmap = AcrossScaleAddition(offpyr) return onmap, offmap def saliency_map(imbgr,GaussR=9): """ Compute corner saliency maps. Parameters: ----------- - imbgr is input BGR colour image. - cornerForFigure is true for saliency map generation (e.g. take log and exhibit more corners to cue figures) - if false, will not take log, and show less, but more accurate corner locations. """ imbgr = resize_image(imbgr, 256) # R,G,B,Y colops = color_opponency(imbgr) # intensity imgray = intensity(imbgr) colors = ApplyEach(colops,laplacian_pyramid,[2]) Ion,Ioff = OnOffFM(gaussian_pyramid(imgray,2)) # all channels (r,g,b,y,i_on,i_off) feature maps lpyrs = [l1 for l1,l2 in colors] + [Ion,Ioff] edgepyrs = ApplyEach(lpyrs, complex_cells_response, [Gbs_r,Gbs_im]) mul_f = lambda x,y: x*y log_f = lambda x: np.log(x+1) # Corner Feature: # Extract corner features by multiply all orientations together, # thus leaves with only locations with multiple orientations. # --> take log on corner response to show more corner, to better cue figure locations cornermaps = [log_f(reduce(mul_f, edgepyrs[i])) for i in xrange(len(edgepyrs))] # make corner maps all channels comparable e.g. range (0,1) cornermaps = ApplyEach(cornermaps, MinMaxNorm) # suppress too abundance corner informations cornermaps = ApplyEach(cornermaps, LocalFigureNorm, [0.2]) # combine all "figure cues" cornermap = sum(cornermaps) cornermap = resize_image(cornermap, 128) cornermap = cv2.GaussianBlur(cornermap, (GaussR,GaussR), 0,0 ) return cornermap def prepare_gabor_kernels(): global Gbs_r, Gbs_im, OrientedGaussianKernels Gbs_r, Gbs_im = get_simple_cell_style_gabor_kernels(frequency=0.2, nOrientations=4) print('Gabor set up.'), if __name__ == '__main__': prepare_gabor_kernels() imbgr = cv2.imread('1.jpg') salmap = saliency_map(imbgr) plt.figure() plt.subplot(1,2,1) plt.imshow(cv2.cvtColor(imbgr,cv2.COLOR_BGR2RGB)) plt.title('input') plt.subplot(1,2,2) plt.imshow(salmap) plt.title('saliency map') plt.show()
%% LyX 1.3 created this file. For more info, see http://www.lyx.org/. %% Do not edit unless you really know what you are doing. \documentclass[12pt,english]{article} \usepackage[T1]{fontenc} \usepackage[latin1]{inputenc} \usepackage{babel} \usepackage{graphicx} \newcommand{\boldsymbol}[1]{\mbox{\boldmath $#1$}} \newcommand{\N}{\mbox{$I\!\!N$}} \newcommand{\Z}{\mbox{$Z\!\!\!Z$}} \newcommand{\Q}{\mbox{$I\:\!\!\!\!\!Q$}} \newcommand{\R}{\mbox{$I\!\!R$}} \makeindex \makeatletter \makeatother \begin{document} \title{Stability Analysis in COPASI} \author{Stefan Hoops\\ Virginia Bioinformatics Institute \\ 1880 Pratt Dr. \\ Blacksburg, VA 24060 \\ USA \\ [email protected]$ $} \date{2004-11-15} \maketitle \begin{abstract} The stability analysis is an important feature of COPASI. Since its implementation differs from Gepasi's yielding different results an explanation is in order. This document describes the methods used within COPASI in detail and explains the differences in comparison to Gepasi. \end{abstract} \section{Calculation of the Jacobian} \subsection{Complete Model} The Jacobian of a vector function $\boldsymbol{f}: \R^{n} \rightarrow \R^{n}$ is defined as: % \begin{eqnarray}\label{Jacobian} \boldsymbol{J}_{i,j}(\boldsymbol{x}) = {\left. \frac{\partial f_i}{\partial x_j} \right|}_{\boldsymbol{x}} & \mbox{where} & i = 1, \ldots, n \;\mbox{and}\; j = 1, \ldots, m \end{eqnarray} % Let us consider $M$ chemical species participating in $N$ reactions. The kinetics of such a system can then be described by: % \begin{eqnarray}\label{FullModel} \dot{\boldsymbol{x}} & = & \boldsymbol{N} \, \boldsymbol{v}(\boldsymbol{x}) \end{eqnarray} % where $\boldsymbol{N}$ is the stoichiometry matrix, $\boldsymbol{v}$ is the vector of reaction velocities, and $\dot{\boldsymbol{x}}$ denotes the change of the chemical species over time. Using the definition of the Jacobian (\ref{Jacobian}) we derive for $\boldsymbol{J}$: % \begin{eqnarray} \boldsymbol{J}_{i,j}(\boldsymbol{x}) = {\left. \frac{\partial \dot{x}_i}{\partial x_j} \right|}_{\boldsymbol{x}} = \boldsymbol{N}_{i,k} \, {\left. \frac{\partial v_k}{\partial x_j} \right|}_{\boldsymbol{x}} = \boldsymbol{N}_{i,k} \, \boldsymbol{E}_{k,j}(\boldsymbol{x}) \end{eqnarray} % where we used the definition of the Elasticity Matrix: % \begin{eqnarray} \boldsymbol{E}_{i,j}(\boldsymbol{x}) = {\left. \frac{\partial v_i}{\partial x_j} \right|}_{\boldsymbol{x}} \end{eqnarray} \subsection{Reduced Model} Let us assume that the Complete Model (\ref{FullModel}) contains $p$ independent species and $q = M - p$ dependent species. Furthermore, we can assume without loss of generalization that the first $p$ species are independent. We therefore can describe the dependent species through the following equations: % \begin{eqnarray}\label{MassConservation} x_i = c_i + \sum_{k=0}^p \alpha_{i,k} \, x_k & \mbox{where} & i = q, \ldots, M, \end{eqnarray} % which are also know as Mass Conservations or Moieties. Using this ability to express the dependent species we rewrite the velocity function so that the new velocity function $\boldsymbol{\tilde{v}}$ only depends on the first $p$ species $\boldsymbol{x}_r$. % \begin{eqnarray} \boldsymbol{\tilde{v}}(x_r) = \boldsymbol{v}(x_1, \ldots, x_p, c_q + \sum_{i=0}^p \alpha_{q,i} x_i, \ldots, c_M + \sum_{i=0}^M \alpha_{M,i} x_i) \end{eqnarray} % This leads to the reduced system: % \begin{eqnarray}\label{ReducedModel} \dot{\boldsymbol{x_r}} & = & \boldsymbol{N}_r \, \boldsymbol{\tilde{v}}(\boldsymbol{x}_r) \end{eqnarray} % where $\boldsymbol{N}_r$ is the matrix comprised of first $p$ rows of $N$. % Using the definition of the Jacobian (\ref{Jacobian}) once again we derive for the Jacobian ($p \mbox{x} p$) of the reduced system: % \begin{eqnarray} \boldsymbol{J}_{i,j}(\boldsymbol{x}_r) & = & {\left. \frac{\partial \dot{x}_i}{\partial x_j} \right|}_{\boldsymbol{x}_r} = \boldsymbol{N}_{i,k} \, {\left. \frac{\partial \tilde{v}_k}{\partial x_j} \right|}_{\boldsymbol{x}_r} \\ & = & \boldsymbol{N}_{i,k} \, \left( {\left. \frac{\partial v_k}{\partial x_j} \right|}_{\boldsymbol{x}_r} + \sum_{l=q}^{M} {\left. \frac{\partial v_k}{\partial x_l} \right|}_{\boldsymbol{x}_r} \frac{\partial x_l}{\partial x_j} \right) \\ & = & \boldsymbol{N}_{i,k} \, \left( \sum_{l=0}^p {\left. \frac{\partial v_k}{\partial x_l} \right|}_{\boldsymbol{x}_r} \delta_{l,j} + \sum_{l=q}^{M} {\left. \frac{\partial v_k}{\partial x_l} \right|}_{\boldsymbol{x}_r} \alpha_{l,j} \right) \\ & = & \label{LinkMatrix} \boldsymbol{N}_{i,k} \, \boldsymbol{E}_{k,l}(\boldsymbol{x}) \, \boldsymbol{L}_{l,j} \end{eqnarray} % where $\delta_{l,j} = 0$ for $l \neq j$ and $1$ otherwise. The link matrix $\boldsymbol{L}$ in (\ref{LinkMatrix}) is defined as: \begin{eqnarray} \boldsymbol{L}_{l,j} & = & \left\{ \begin{array}{ll} \delta_{l,j} & \mbox{if $l \leq p$} \\ \alpha_{l,j} & \mbox{if $l > p$} \end{array} \right. \end{eqnarray} \subsection{Comparison to Gepasi} Gepasi's calculation of the Jacobian is based on the reduced system. However it uses the following slightly different formula % \begin{eqnarray}\label{GepasiModel} \dot{\boldsymbol{x_r}} & = & \boldsymbol{N}_r \, \boldsymbol{v}(\boldsymbol{x}_r) \end{eqnarray} % This yields to the Jacobian ($N \mbox{x} p$) of the reduced system: % \begin{eqnarray} \boldsymbol{J}_{i,j}(\boldsymbol{x}_r) & = & \boldsymbol{N}_{i,k} \, \boldsymbol{E}_{k,l}(\boldsymbol{x}_r) \end{eqnarray} % The omission to express the kinetic functions in the new reduced variables leads to a different Jacobian in the case that the model contains dependent species. {\bf Note:} It is important to mention that the method to calculate the Jacobian is not effecting the calculation of the dynamics of a system in Gepasi. The reason for this is that Gepasi uses the full Differential and Algebraic Equation (DAE) system. \section{Stability Analysis} The stability analysis in both COPASI and Gepasi is based on the Jacobian of the reduced system since the complete system has a singular Jacobian whenever it contains dependent species. The interpretation for the reduced system differs between COPASI and Gepasi as shown in (\ref{ReducedModel}) and (\ref{GepasiModel}). We therefore achieve different results for the stability analysis especially the eigenvalues of the Jacobians differ. In most cases this does not effect the classification of the steady-state. We oberved a second cause for different results for the stability analysis, which is numerical instability. This behviour can be observed in the Brusellator model ({\tt brusselator.gps}), which is distributed with Gepasi. \\ \\ COPASI's result:\\ {\tt \small KINETIC STABILITY ANALYSIS \\ The linear stability analysis based on the eigenvalues \\ of the Jacobian matrix is only valid for steady states. \\ \\ Summary: \\ This steady state is unstable, \\ transient states in its vicinity have oscillatory components \\ \\ Eigenvalue statistics: \\ Largest real part: 2.5 \\ Largest absolute imaginary part: 1.65831 \\ 0 are purely real \\ 0 are purely imaginary \\ 2 are complex \\ 0 are equal to zero \\ 2 have positive real part \\ 0 have negative real part \\ stiffness = 1.00000 \\ time hierarchy = 0.000000 \\ } \\ Gepasi's Result: \\ {\tt \small KINETIC STABILITY ANALYSIS \\ \\ Summary: \\ This steady state is unstable. \\ \\ Eigenvalue statistics: \\ Largest real part: +1.593070e+000 \\ Largest absolute imaginary part: 0.000000e+000 \\ 2 are purely real \\ 0 are purely imaginary \\ 0 are complex \\ 0 are equal to zero \\ 2 have positive real part \\ 0 have negative real part \\ stiffness = 1.72068e+305 \\ time hierarchy = 1 \\ } \end{document}
[GOAL] α : Type u inst✝² : Mul α inst✝¹ : PartialOrder α inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x < x_1 ⊢ ContravariantClass (WithZero α) (WithZero α) (fun x x_1 => x * x_1) fun x x_1 => x < x_1 [PROOFSTEP] refine ⟨fun a b c h => ?_⟩ [GOAL] α : Type u inst✝² : Mul α inst✝¹ : PartialOrder α inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x < x_1 a b c : WithZero α h : a * b < a * c ⊢ b < c [PROOFSTEP] have := ((zero_le _).trans_lt h).ne' [GOAL] α : Type u inst✝² : Mul α inst✝¹ : PartialOrder α inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x < x_1 a b c : WithZero α h : a * b < a * c this : a * c ≠ 0 ⊢ b < c [PROOFSTEP] induction a using WithZero.recZeroCoe [GOAL] case h₁ α : Type u inst✝² : Mul α inst✝¹ : PartialOrder α inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x < x_1 b c : WithZero α h : 0 * b < 0 * c this : 0 * c ≠ 0 ⊢ b < c [PROOFSTEP] exfalso [GOAL] case h₁.h α : Type u inst✝² : Mul α inst✝¹ : PartialOrder α inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x < x_1 b c : WithZero α h : 0 * b < 0 * c this : 0 * c ≠ 0 ⊢ False [PROOFSTEP] exact left_ne_zero_of_mul this rfl [GOAL] case h₂ α : Type u inst✝² : Mul α inst✝¹ : PartialOrder α inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x < x_1 b c : WithZero α a✝ : α h : ↑a✝ * b < ↑a✝ * c this : ↑a✝ * c ≠ 0 ⊢ b < c [PROOFSTEP] induction c using WithZero.recZeroCoe [GOAL] case h₂.h₁ α : Type u inst✝² : Mul α inst✝¹ : PartialOrder α inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x < x_1 b : WithZero α a✝ : α h : ↑a✝ * b < ↑a✝ * 0 this : ↑a✝ * 0 ≠ 0 ⊢ b < 0 [PROOFSTEP] exfalso [GOAL] case h₂.h₁.h α : Type u inst✝² : Mul α inst✝¹ : PartialOrder α inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x < x_1 b : WithZero α a✝ : α h : ↑a✝ * b < ↑a✝ * 0 this : ↑a✝ * 0 ≠ 0 ⊢ False [PROOFSTEP] exact right_ne_zero_of_mul this rfl [GOAL] case h₂.h₂ α : Type u inst✝² : Mul α inst✝¹ : PartialOrder α inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x < x_1 b : WithZero α a✝¹ a✝ : α h : ↑a✝¹ * b < ↑a✝¹ * ↑a✝ this : ↑a✝¹ * ↑a✝ ≠ 0 ⊢ b < ↑a✝ [PROOFSTEP] induction b using WithZero.recZeroCoe [GOAL] case h₂.h₂.h₁ α : Type u inst✝² : Mul α inst✝¹ : PartialOrder α inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x < x_1 a✝¹ a✝ : α this : ↑a✝¹ * ↑a✝ ≠ 0 h : ↑a✝¹ * 0 < ↑a✝¹ * ↑a✝ ⊢ 0 < ↑a✝ case h₂.h₂.h₂ α : Type u inst✝² : Mul α inst✝¹ : PartialOrder α inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x < x_1 a✝² a✝¹ : α this : ↑a✝² * ↑a✝¹ ≠ 0 a✝ : α h : ↑a✝² * ↑a✝ < ↑a✝² * ↑a✝¹ ⊢ ↑a✝ < ↑a✝¹ [PROOFSTEP] exacts [zero_lt_coe _, coe_lt_coe.mpr (lt_of_mul_lt_mul_left' <| coe_lt_coe.mp h)]
(** studies coproducts in the categories on which is being acted in actegories author: Ralph Matthes, 2023 *) Require Import UniMath.Foundations.All. Require Import UniMath.MoreFoundations.All. Require Import UniMath.CategoryTheory.Core.Categories. Require Import UniMath.CategoryTheory.Core.Functors. Require Import UniMath.CategoryTheory.Core.NaturalTransformations. Require Import UniMath.CategoryTheory.Core.Isos. Require Import UniMath.CategoryTheory.Monoidal.WhiskeredBifunctors. Require Import UniMath.CategoryTheory.Monoidal.Categories. Require Import UniMath.CategoryTheory.Monoidal.Functors. Require Import UniMath.CategoryTheory.Actegories.Actegories. Require Import UniMath.CategoryTheory.Actegories.MorphismsOfActegories. Require Import UniMath.CategoryTheory.Actegories.ProductActegory. Require Import UniMath.CategoryTheory.Actegories.ConstructionOfActegories. (* Require Import UniMath.CategoryTheory.coslicecat. *) Require Import UniMath.CategoryTheory.PrecategoryBinProduct. Require Import UniMath.CategoryTheory.ProductCategory. Require Import UniMath.CategoryTheory.limits.bincoproducts. Require Import UniMath.CategoryTheory.limits.coproducts. (* Require Import UniMath.CategoryTheory.Monoidal.Examples.MonoidalPointedObjects. *) Local Open Scope cat. Import BifunctorNotations. Import MonoidalNotations. Import ActegoryNotations. Section FixAMonoidalCategory. Context {V : category} (Mon_V : monoidal V). (** given the monoidal category that acts upon categories *) Section BinaryCoproduct. Context {C : category} (BCP : BinCoproducts C) (Act : actegory Mon_V C). Definition actegory_bincoprod_antidistributor : ∏ (a : V) (c c' : C), BCP (leftwhiskering_functor Act a c) (leftwhiskering_functor Act a c') --> leftwhiskering_functor Act a (BCP c c') := bifunctor_bincoprod_antidistributor BCP BCP Act. Lemma actegory_bincoprod_antidistributor_nat_left (v : V) (cd1 cd2 : category_binproduct C C) (g : cd1 --> cd2) : actegory_bincoprod_antidistributor v (pr1 cd1) (pr2 cd1) · v ⊗^{Act}_{l} #(bincoproduct_functor BCP) g = #(bincoproduct_functor BCP) (v ⊗^{actegory_binprod Mon_V Act Act}_{l} g) · actegory_bincoprod_antidistributor v (pr1 cd2) (pr2 cd2). Proof. apply bincoprod_antidistributor_nat_left. Qed. Lemma actegory_bincoprod_antidistributor_nat_right (v1 v2 : V) (cd : category_binproduct C C) (f : v1 --> v2) : actegory_bincoprod_antidistributor v1 (pr1 cd) (pr2 cd) · f ⊗^{ Act}_{r} bincoproduct_functor BCP cd = #(bincoproduct_functor BCP) (f ⊗^{ actegory_binprod Mon_V Act Act}_{r} cd) · actegory_bincoprod_antidistributor v2 (pr1 cd) (pr2 cd). Proof. apply bincoprod_antidistributor_nat_right. Qed. Lemma bincoprod_antidistributor_pentagon_identity (v w : V) (cd : category_binproduct C C) : # (bincoproduct_functor BCP) aα^{actegory_binprod Mon_V Act Act}_{v, w, cd} · actegory_bincoprod_antidistributor v (w ⊗_{Act} pr1 cd) (w ⊗_{ Act} pr2 cd) · v ⊗^{Act}_{l} actegory_bincoprod_antidistributor w (pr1 cd) (pr2 cd) = actegory_bincoprod_antidistributor (v ⊗_{Mon_V} w) (pr1 cd) (pr2 cd) · aα^{Act}_{v, w, bincoproduct_functor BCP cd}. Proof. etrans. { rewrite assoc'. apply postcompWithBinCoproductArrow. } etrans. 2: { apply pathsinv0, postcompWithBinCoproductArrow. } apply maponpaths_12. - etrans. { repeat rewrite assoc. apply cancel_postcomposition. rewrite assoc'. apply maponpaths. apply BinCoproductIn1Commutes. } etrans. 2: { apply actegory_actornatleft. } rewrite assoc'. apply maponpaths. etrans. { apply pathsinv0, (functor_comp (leftwhiskering_functor Act v)). } apply maponpaths. apply BinCoproductIn1Commutes. - etrans. { repeat rewrite assoc. apply cancel_postcomposition. rewrite assoc'. apply maponpaths. apply BinCoproductIn2Commutes. } etrans. 2: { apply actegory_actornatleft. } rewrite assoc'. apply maponpaths. etrans. { apply pathsinv0, (functor_comp (leftwhiskering_functor Act v)). } apply maponpaths. apply BinCoproductIn2Commutes. Qed. Lemma bincoprod_antidistributor_triangle_identity (cd : category_binproduct C C) : #(bincoproduct_functor BCP) au^{actegory_binprod Mon_V Act Act}_{cd} = actegory_bincoprod_antidistributor I_{Mon_V} (pr1 cd) (pr2 cd) · au^{Act}_{bincoproduct_functor BCP cd}. Proof. etrans. 2: { apply pathsinv0, postcompWithBinCoproductArrow. } cbn. unfold BinCoproductOfArrows. apply maponpaths_12; apply pathsinv0, actegory_unitornat. Qed. Lemma actegory_bincoprod_antidistributor_commutes_with_associativity_of_coproduct (v : V) (c d e : C) : #(bincoproduct_functor BCP) (catbinprodmor (actegory_bincoprod_antidistributor v c d) (identity (v ⊗_{Act} e))) · actegory_bincoprod_antidistributor v (BCP c d) e · v ⊗^{Act}_{l} bincoprod_associator_data BCP c d e = bincoprod_associator_data BCP (v ⊗_{Act} c) (v ⊗_{Act} d) (v ⊗_{Act} e) · #(bincoproduct_functor BCP) (catbinprodmor (identity (v ⊗_{Act} c)) (actegory_bincoprod_antidistributor v d e)) · actegory_bincoprod_antidistributor v c (BCP d e). Proof. apply bincoprod_antidistributor_commutes_with_associativity_of_coproduct. Qed. Definition actegory_bincoprod_distributor_data : UU := bifunctor_bincoprod_distributor_data BCP BCP Act. Identity Coercion actegory_bincoprod_distributor_data_coercion: actegory_bincoprod_distributor_data >-> bifunctor_bincoprod_distributor_data. Definition actegory_bincoprod_distributor_iso_law (δ : actegory_bincoprod_distributor_data) : UU := bifunctor_bincoprod_distributor_iso_law BCP BCP Act δ. Definition actegory_bincoprod_distributor : UU := bifunctor_bincoprod_distributor BCP BCP Act. Definition actegory_bincoprod_distributor_to_data (δ : actegory_bincoprod_distributor) : actegory_bincoprod_distributor_data := pr1 δ. Coercion actegory_bincoprod_distributor_to_data : actegory_bincoprod_distributor >-> actegory_bincoprod_distributor_data. Definition bincoprod_functor_lineator_data (δ : actegory_bincoprod_distributor) : lineator_data Mon_V (actegory_binprod Mon_V Act Act) Act (bincoproduct_functor BCP). Proof. intros v cd. exact (δ v (pr1 cd) (pr2 cd)). Defined. Definition bincoprod_functor_lineator_strongly (δ : actegory_bincoprod_distributor) : lineator_strongly _ _ _ _ (bincoprod_functor_lineator_data δ). Proof. intros v cd. exists (actegory_bincoprod_antidistributor v (pr1 cd) (pr2 cd)). apply (pr2 δ v). Defined. Lemma bincoprod_functor_lineator_laxlaws (δ : actegory_bincoprod_distributor) : lineator_laxlaws _ _ _ _ (bincoprod_functor_lineator_data δ). Proof. red; repeat split. - red. intros v cd1 cd2 g. apply (z_iso_inv_to_right _ _ _ _ (_,,bincoprod_functor_lineator_strongly δ v _)). rewrite assoc'. apply (z_iso_inv_to_left _ _ _ (_,,bincoprod_functor_lineator_strongly δ v _)). apply (bincoprod_antidistributor_nat_left _ _ Act). - red. intros v1 v2 cd f. apply (z_iso_inv_to_right _ _ _ _ (_,,bincoprod_functor_lineator_strongly δ _ _)). rewrite assoc'. apply (z_iso_inv_to_left _ _ _ (_,,bincoprod_functor_lineator_strongly δ _ _)). apply (bincoprod_antidistributor_nat_right _ _ Act). - red. intros v w cd. apply pathsinv0, (z_iso_inv_to_right _ _ _ _ (_,,bincoprod_functor_lineator_strongly δ _ _)). rewrite assoc'. apply (z_iso_inv_to_left _ _ _ (_,,bincoprod_functor_lineator_strongly δ _ _)). rewrite assoc. apply (z_iso_inv_to_right _ _ _ _ (functor_on_z_iso (leftwhiskering_functor Act v) (_,,bincoprod_functor_lineator_strongly δ _ _))). apply pathsinv0, bincoprod_antidistributor_pentagon_identity. - red. intro cd. apply pathsinv0, (z_iso_inv_to_left _ _ _ (_,,bincoprod_functor_lineator_strongly δ _ _)). apply pathsinv0, bincoprod_antidistributor_triangle_identity. Qed. Definition bincoprod_functor_lineator (δ : actegory_bincoprod_distributor) : lineator Mon_V (actegory_binprod Mon_V Act Act) Act (bincoproduct_functor BCP). Proof. use tpair. - exists (bincoprod_functor_lineator_data δ). exact (bincoprod_functor_lineator_laxlaws δ). - apply bincoprod_functor_lineator_strongly. Defined. Lemma bincoprod_distributor_commutes_with_associativity_of_coproduct (δ : actegory_bincoprod_distributor) (v : V) (c d e : C) : v ⊗^{Act}_{l} bincoprod_associator_data BCP c d e · δ v c (BCP d e) · #(bincoproduct_functor BCP) (catbinprodmor (identity (v ⊗_{Act} c)) (δ v d e)) = δ v (BCP c d) e · #(bincoproduct_functor BCP) (catbinprodmor (δ v c d) (identity (v ⊗_{Act} e))) · bincoprod_associator_data BCP (v ⊗_{Act} c) (v ⊗_{Act} d) (v ⊗_{Act} e). Proof. repeat rewrite assoc'. apply (z_iso_inv_to_left _ _ _ (_,,bincoprod_functor_lineator_strongly δ v (((BCP c d): C),, e))). repeat rewrite assoc. apply (z_iso_inv_to_right _ _ _ _ (functor_on_z_iso (functor_fix_fst_arg _ _ _ (bincoproduct_functor BCP) (v ⊗_{ Act} c)) (_,,bincoprod_functor_lineator_strongly δ v (d,,e)))). apply (z_iso_inv_to_right _ _ _ _ (_,,bincoprod_functor_lineator_strongly δ v (c,,((BCP d e): C)))). repeat rewrite assoc'. apply (z_iso_inv_to_left _ _ _ (functor_on_z_iso (functor_fix_snd_arg _ _ _ (bincoproduct_functor BCP) (v ⊗_{ Act} e)) (_,,bincoprod_functor_lineator_strongly δ v (c,,d)))). repeat rewrite assoc. apply actegory_bincoprod_antidistributor_commutes_with_associativity_of_coproduct. Qed. End BinaryCoproduct. Section Coproduct. Context {I : UU} {C : category} (CP : Coproducts I C) (Act : actegory Mon_V C). Definition actegory_coprod_antidistributor := bifunctor_coprod_antidistributor CP CP Act. Lemma actegory_coprod_antidistributor_nat_left (v : V) (cs1 cs2 : power_category I C) (g : cs1 --> cs2) : actegory_coprod_antidistributor v cs1 · v ⊗^{Act}_{l} #(coproduct_functor I CP) g = #(coproduct_functor I CP) (v ⊗^{actegory_power Mon_V I Act}_{l} g) · actegory_coprod_antidistributor v cs2. Proof. apply coprod_antidistributor_nat_left. Qed. Lemma actegory_coprod_antidistributor_nat_right (v1 v2 : V) (cs : power_category I C) (f : v1 --> v2) : actegory_coprod_antidistributor v1 cs · f ⊗^{Act}_{r} coproduct_functor I CP cs = #(coproduct_functor I CP) (f ⊗^{actegory_power Mon_V I Act}_{r} cs) · actegory_coprod_antidistributor v2 cs. Proof. apply coprod_antidistributor_nat_right. Qed. Lemma coprod_antidistributor_pentagon_identity (v w : V) (cs : power_category I C) : # (coproduct_functor I CP) aα^{actegory_power Mon_V I Act}_{v, w, cs} · actegory_coprod_antidistributor v (fun i => w ⊗_{Act} (cs i)) · v ⊗^{Act}_{l} actegory_coprod_antidistributor w cs = actegory_coprod_antidistributor (v ⊗_{Mon_V} w) cs · aα^{Act}_{v, w, coproduct_functor I CP cs}. Proof. etrans. { rewrite assoc'. apply postcompWithCoproductArrow. } etrans. 2: { apply pathsinv0, postcompWithCoproductArrow. } apply maponpaths; apply funextsec; intro i. etrans. { repeat rewrite assoc. apply cancel_postcomposition. rewrite assoc'. apply maponpaths. apply CoproductInCommutes. } etrans. 2: { apply actegory_actornatleft. } rewrite assoc'. apply maponpaths. etrans. { apply pathsinv0, (functor_comp (leftwhiskering_functor Act v)). } apply maponpaths. apply CoproductInCommutes. Qed. Lemma coprod_antidistributor_triangle_identity (cs : power_category I C) : #(coproduct_functor I CP) au^{actegory_power Mon_V I Act}_{cs} = actegory_coprod_antidistributor I_{Mon_V} cs · au^{Act}_{coproduct_functor I CP cs}. Proof. etrans. 2: { apply pathsinv0, postcompWithCoproductArrow. } cbn. unfold CoproductOfArrows. apply maponpaths, funextsec; intro i; apply pathsinv0, actegory_unitornat. Qed. Definition actegory_coprod_distributor_data : UU := bifunctor_coprod_distributor_data CP CP Act. Identity Coercion actegory_coprod_distributor_data_coercion: actegory_coprod_distributor_data >-> bifunctor_coprod_distributor_data. Definition actegory_coprod_distributor_iso_law (δ : actegory_coprod_distributor_data) : UU := bifunctor_coprod_distributor_iso_law CP CP Act δ. Definition actegory_coprod_distributor : UU := bifunctor_coprod_distributor CP CP Act. Definition actegory_coprod_distributor_to_data (δ : actegory_coprod_distributor) : actegory_coprod_distributor_data := pr1 δ. Coercion actegory_coprod_distributor_to_data : actegory_coprod_distributor >-> actegory_coprod_distributor_data. Definition coprod_functor_lineator_data (δ : actegory_coprod_distributor_data) : lineator_data Mon_V (actegory_power Mon_V I Act) Act (coproduct_functor I CP). Proof. intros v cs. exact (δ v cs). Defined. Definition coprod_functor_lineator_strongly (δ : actegory_coprod_distributor) : lineator_strongly _ _ _ _ (coprod_functor_lineator_data δ). Proof. intros v cs. exists (actegory_coprod_antidistributor v cs). apply (pr2 δ). Defined. Lemma coprod_functor_lineator_laxlaws (δ : actegory_coprod_distributor) : lineator_laxlaws _ _ _ _ (coprod_functor_lineator_data δ). Proof. red; repeat split. - red. intros v cs1 cs2 g. apply (z_iso_inv_to_right _ _ _ _ (_,,coprod_functor_lineator_strongly δ v _)). rewrite assoc'. apply (z_iso_inv_to_left _ _ _ (_,,coprod_functor_lineator_strongly δ v _)). apply actegory_coprod_antidistributor_nat_left. - red. intros v1 v2 cs f. apply (z_iso_inv_to_right _ _ _ _ (_,,coprod_functor_lineator_strongly δ _ _)). rewrite assoc'. apply (z_iso_inv_to_left _ _ _ (_,,coprod_functor_lineator_strongly δ _ _)). apply actegory_coprod_antidistributor_nat_right. - red. intros v w cs. apply pathsinv0, (z_iso_inv_to_right _ _ _ _ (_,,coprod_functor_lineator_strongly δ _ _)). rewrite assoc'. apply (z_iso_inv_to_left _ _ _ (_,,coprod_functor_lineator_strongly δ _ _)). rewrite assoc. apply (z_iso_inv_to_right _ _ _ _ (functor_on_z_iso (leftwhiskering_functor Act v) (_,,coprod_functor_lineator_strongly δ _ _))). apply pathsinv0, coprod_antidistributor_pentagon_identity. - red. intro cs. apply pathsinv0, (z_iso_inv_to_left _ _ _ (_,,coprod_functor_lineator_strongly δ _ _)). apply pathsinv0, coprod_antidistributor_triangle_identity. Qed. Definition coprod_functor_lineator (δ : actegory_coprod_distributor) : lineator Mon_V (actegory_power Mon_V I Act) Act (coproduct_functor I CP). Proof. use tpair. - exists (coprod_functor_lineator_data δ). exact (coprod_functor_lineator_laxlaws δ). - apply coprod_functor_lineator_strongly. Defined. End Coproduct. End FixAMonoidalCategory. Section TwoMonoidalCategories. Context {V : category} (Mon_V : monoidal V) {C : category} (Act : actegory Mon_V C) {W : category} (Mon_W : monoidal W) {F : W ⟶ V} (U : fmonoidal Mon_W Mon_V F). Let ActW : actegory Mon_W C := lifted_actegory Mon_V Act Mon_W U. Section BinaryCase. Context (BCP : BinCoproducts C) (δ : actegory_bincoprod_distributor Mon_V BCP Act). Definition lifted_bincoprod_distributor_data : actegory_bincoprod_distributor_data Mon_W BCP ActW. Proof. intros w c c'. apply (δ (F w)). Defined. Lemma lifted_bincoprod_distributor_law : actegory_bincoprod_distributor_iso_law _ _ _ lifted_bincoprod_distributor_data. Proof. intros w c c'. split; unfold lifted_bincoprod_distributor_data; apply (pr2 δ (F w)). Qed. Definition lifted_bincoprod_distributor : actegory_bincoprod_distributor Mon_W BCP ActW := _,,lifted_bincoprod_distributor_law. End BinaryCase. Section IndexedCase. Context {I : UU} (CP : Coproducts I C) (δ : actegory_coprod_distributor Mon_V CP Act). Definition lifted_coprod_distributor_data : actegory_coprod_distributor_data Mon_W CP ActW. Proof. intros w cs. apply (δ (F w)). Defined. Lemma lifted_coprod_distributor_law : actegory_coprod_distributor_iso_law _ _ _ lifted_coprod_distributor_data. Proof. intros w cs. split; unfold lifted_coprod_distributor_data; apply (pr2 δ). Qed. Definition lifted_coprod_distributor : actegory_coprod_distributor Mon_W CP ActW := _,,lifted_coprod_distributor_law. End IndexedCase. End TwoMonoidalCategories.
classdef CutMeshProvisionalQuadrilater < CutMesh properties (Access = private) connec coord cutMesh subMesh subCutSubMesh subMesher fullSubCells cutSubCells levelSetSubMesh end properties (Access = private) lastNode end methods (Access = public) function obj = CutMeshProvisionalQuadrilater(cParams) obj.init(cParams); obj.lastNode = cParams.lastNode; end function compute(obj) obj.createSubMesher(); obj.createSubMesh(); obj.computeLevelSetInSubMesh(); obj.classifyCells(); obj.computeSubCutSubMesh(); obj.computeXcoord(); obj.computeCoord(); obj.computeConnec(); obj.computeCellContainingSubCell(); obj.computeMesh(); obj.computeBoundaryMesh(); obj.computeBoundaryXCoordsIso(); obj.computeBoundaryCellContainingSubCell(); obj.computeInnerCutMesh(); obj.computeBoundaryCutMesh(); end end methods (Access = private) function createSubMesher(obj) s.mesh = obj.backgroundMesh; s.lastNode = obj.lastNode; obj.subMesher = SubMesher(s); end function createSubMesh(obj) obj.subMesh = obj.subMesher.subMesh; end function computeLevelSetInSubMesh(obj) ls = obj.levelSet; s.mesh = obj.backgroundMesh; s.fValues = ls; f = P1Function(s); q = Quadrature.set(obj.backgroundMesh.type); q.computeQuadrature('CONSTANT'); xV = q.posgp; lsSubMesh = squeeze(f.evaluate(xV)); obj.levelSetSubMesh = [ls;lsSubMesh]; end function classifyCells(obj) lsInElem = obj.computeLevelSetInElem(); isFull = all(lsInElem<0,2); isEmpty = all(lsInElem>0,2); isCut = ~isFull & ~isEmpty; obj.fullSubCells = find(isFull); obj.cutSubCells = find(isCut); end function lsElem = computeLevelSetInElem(obj) ls = obj.levelSetSubMesh; nodes = obj.subMesh.connec; nnode = size(nodes,2); nElem = size(nodes,1); lsElem = zeros(nElem,nnode); for inode = 1:nnode node = nodes(:,inode); lsElem(:,inode) = ls(node); end end function computeSubCutSubMesh(obj) s.backgroundMesh = obj.subMesh; s.cutCells = obj.cutSubCells; s.levelSet = obj.levelSetSubMesh; cMesh = CutMesh.create(s); cMesh.compute(); obj.subCutSubMesh = cMesh; end function computeCellContainingSubCell(obj) cellSubMesh = obj.subCutSubMesh.innerCutMesh.cellContainingSubcell; fCells = obj.fullSubCells; cellSubMesh = [fCells;cellSubMesh]; cell = obj.computeSubTriangleOfSubCell(); obj.cellContainingSubcell = cell(cellSubMesh); end function cell = computeSubTriangleOfSubCell(obj) nnode = size(obj.backgroundMesh.connec,2); cElems = transpose(obj.cutCells); cell = repmat(cElems,nnode,1); cell = cell(:); end function globalToLocal = computeGlobalToLocal(obj) bConnec = obj.backgroundMesh.connec; nnode = size(bConnec,2); nElem = size(bConnec,1); cell = repmat((1:nnode)',1,nElem); globalToLocal = cell(:); end function computeXcoord(obj) s.fullCells = obj.fullSubCells; s.cutCells = obj.subCutSubMesh.innerCutMesh.cellContainingSubcell; s.globalToLocal = obj.computeGlobalToLocal(); s.localMesh = obj.subMesher.localMesh; s.xIsoCutCoord = obj.subCutSubMesh.innerCutMesh.xCoordsIso; xC = XcoordIsoComputer(s); obj.xCoordsIso = xC.compute(); end function computeConnec(obj) connecCutInterior = obj.subCutSubMesh.innerCutMesh.mesh.connec; connecFull = obj.subMesh.connec(obj.fullSubCells,:); obj.connec = [connecFull;connecCutInterior]; end function computeCoord(obj) obj.coord = obj.subCutSubMesh.innerCutMesh.mesh.coord; end function computeMesh(obj) sM.connec = obj.connec; sM.coord = obj.coord; sM.kFace = obj.backgroundMesh.kFace; obj.mesh = Mesh(sM); end function computeBoundaryMesh(obj) m = obj.subCutSubMesh.boundaryCutMesh.mesh; obj.boundaryMesh = m; end function computeBoundaryXCoordsIso(obj) xCutIso = obj.subCutSubMesh.xCoordsIsoBoundary; s.fullCells = obj.fullSubCells; s.cutCells = obj.cutSubCells; s.globalToLocal = obj.computeGlobalToLocal(); s.localMesh = obj.subMesher.localMesh; s.xIsoCutCoord = xCutIso; xC = XcoordIsoComputer(s); xCutG = xC.computeXSubCut(); obj.xCoordsIsoBoundary = xCutG; end function cellCont = computeBoundaryCellContainingSubCell(obj) cutC = obj.cutSubCells; cell = obj.computeSubTriangleOfSubCell(); cellCont = cell(cutC); obj.cellContainingSubCellBoundary = cellCont; end end end
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef LIBHE_H #define LIBHE_H #include <cassert> #include <algorithm> #include <optional> #include <gsl/span> #include "seal/seal.h" #include "seal/util/common.h" #include "seal/util/rlwe.h" #include "seal/util/polyarithsmallmod.h" using namespace std; using namespace seal; class RawPolynomData { vector<uint64_t > _data; size_t _size; public: explicit RawPolynomData(const SEALContext& context); SEAL_NODISCARD inline const size_t& size() const { return _size; }; SEAL_NODISCARD inline uint64_t* data() { return _data.data(); }; SEAL_NODISCARD inline gsl::span<uint64_t > data_span() { return { data(), size() }; }; void set_data(vector<uint64_t >& data); }; gsl::span<Ciphertext::ct_coeff_type > data_span(Ciphertext& c, size_t n); RawPolynomData generate_a(const SEALContext& context); EncryptionParameters generateParameters(); size_t get_slot_count(const SEALContext& ctx); // returns a vector filled with random double values between 0 and 1 vector<double> random_plaintext_data(size_t count); struct GlobalState { SEALContext context; RawPolynomData a; double scale; explicit GlobalState(double _scale); }; class Client { GlobalState _gs; CKKSEncoder _encoder; SecretKey _partial_secret_key; PublicKey _partial_public_key; std::optional<PublicKey> _public_key = std::nullopt; std::unique_ptr<Encryptor> _encryptor = nullptr; SEAL_NODISCARD static PublicKey generate_partial_public_key(const SecretKey &secret_key, const SEALContext &context, RawPolynomData& a); public: explicit Client(GlobalState global_state); SEAL_NODISCARD inline const SEALContext& context() const { return _gs.context; }; SEAL_NODISCARD inline const PublicKey& partial_public_key() const { return _partial_public_key; }; SEAL_NODISCARD inline const CKKSEncoder& encoder() const { return _encoder; }; SEAL_NODISCARD inline CKKSEncoder& encoder() { return _encoder; }; SEAL_NODISCARD inline const Encryptor& encryptor() const { assert(_encryptor != nullptr); return *_encryptor; }; SEAL_NODISCARD inline const PublicKey& public_key() { return *_public_key; }; inline void set_public_key(const PublicKey& pk) { _public_key = make_optional(pk); }; Ciphertext encrypted_data(gsl::span<const double> plain_data); Plaintext partial_decryption(const Ciphertext& encrypted); }; // adds b to a in place template<typename T> void sum_first_poly_inplace(const SEALContext& context, T& a, const T& b) { auto &context_data = *context.get_context_data(a.parms_id()); auto &parms = context_data.parms(); auto &coeff_modulus = parms.coeff_modulus(); size_t coeff_count = parms.poly_modulus_degree(); size_t coeff_modulus_size = coeff_modulus.size(); // by dereferencing we get only the first poly auto summand_iter = *util::ConstPolyIter(b.data(), coeff_count, coeff_modulus_size); auto sum_iter = *util::ConstPolyIter(a.data(), coeff_count, coeff_modulus_size); auto result_iter = *util::PolyIter(a.data(), coeff_count, coeff_modulus_size); // see Evaluator::add_inplace util::add_poly_coeffmod(sum_iter, summand_iter, coeff_modulus_size, coeff_modulus, result_iter); } // This function adds the first polys in summands to sum (either Ciphertext or Plaintext). template<typename T> T sum_first_polys_inplace(const SEALContext& context, T& sum, gsl::span<const T> summands) { for (size_t i = 0; i < summands.size(); i++) { sum_first_poly_inplace(context, sum, summands[i]); } return sum; } // This function sums the first polys in summands (either Ciphertext or Plaintext). template<typename T> T sum_first_polys(const SEALContext& context, gsl::span<const T> summands) { T sum = summands[0]; sum_first_polys_inplace(context, sum, gsl::span(&summands.data()[1], summands.size() - 1)); return sum; } class Server { GlobalState _gs; PublicKey _public_key; public: explicit Server(GlobalState global_state); SEAL_NODISCARD inline RawPolynomData& a() { return _gs.a; }; SEAL_NODISCARD inline const SEALContext& context() const { return _gs.context; }; SEAL_NODISCARD inline const PublicKey& public_key() const { return _public_key; }; void accumulate_partial_public_keys(gsl::span<const Ciphertext> partial_pub_keys); Ciphertext sum_data(vector<Ciphertext>&& data) const; vector<double> average(const Ciphertext& encrypted_sum, gsl::span<const Plaintext> partial_decryptions) const; }; #endif //LIBHE_H
module Lambdapants.Term.Nats import Lambdapants.Term %default total ||| Return the Church encoded term corresponding to the provided number. export encoded : Nat -> Term encoded n = Lam "f" (Lam "x" nat) where nat : Term nat = foldr apply (Var "x") (replicate n (Term.App (Var "f"))) apps : String -> String -> Term -> Maybe Nat apps f x = count 1 where count : Nat -> Term -> Maybe Nat count n (App (Var g) (Var v)) = if g == f && v == x then Just n else Nothing count n (App (Var g) e) = if g == f then count (succ n) e else Nothing count _ _ = Nothing ||| Return the natural number interpretation of the term, if it corresponds to ||| a valid Church encoding. export decoded : Term -> Maybe Nat decoded (Lam f (Lam x term)) = case term of Var v => if v == x then Just 0 else Nothing App _ _ => apps f x term Lam _ _ => Nothing decoded _ = Nothing
export opt_linear_fit! """ opt_linear_fit!( graph, objfun, discr, linear_cref; input = :A, errtype = :abserr, linlsqr = :backslash, droptol = 0, ) Linear fitting of a `graph` of the form c_1 g_1(x) + c_2 g_2(x) + … + c_n g_n(x) to the values of `objfun`, in the points `discr`. Reference to the coefficients `c_1,…,c_n` should be given `linear_cref`. The variable `graph` is modified during the iterations and the function has no return value. See [`opt_gauss_newton!`](@ref) for a description the kwarg `errtype` and `input`, and [`solve_linlsqr!`](@ref) for the kwargs `linlsqr and `droptol`. """ function opt_linear_fit!( graph, objfun, discr, linear_cref; input = :A, errtype = :abserr, linlsqr = :backslash, droptol = 0, ) objfun_vals = objfun.(discr) vals = init_vals_eval_graph!(graph, discr, nothing, input) eval_graph(graph, discr, vals = vals, input = input) n = length(linear_cref) T = eltype(valtype(vals)) A = ones(T, size(discr, 1), n) for k = 1:n parent = graph.parents[linear_cref[k][1]][linear_cref[k][2]] A[:, k] = vals[parent] end adjust_for_errtype!(A, objfun_vals, objfun_vals, errtype) c = solve_linlsqr!(A, objfun_vals, linlsqr, droptol) set_coeffs!(graph, c, linear_cref) return nothing end
module Divisors import ZZ %access public export %default total |||isDivisible a b can be constucted if b divides a isDivisible : ZZ -> ZZ -> Type isDivisible a b = (n : ZZ ** a = b * n) |||1 divides everything oneDiv : (a : ZZ) -> isDivisible a 1 oneDiv a = (a ** rewrite sym (multOneLeftNeutralZ a) in Refl) |||Genetes a proof of (a+b) = d*(n+m) from (a=d*n)and (b=d*m) DistributeProof: (a:ZZ)->(b:ZZ)->(d:ZZ)->(n:ZZ)->(m:ZZ)->(a=d*n)->(b=d*m)->((a+b) = d*(n+m)) DistributeProof a b d n m pf1 pf2 = rewrite (multDistributesOverPlusRightZ d n m) in(trans (the (a+b=(d*n)+b) (v1)) v2) where v1 =plusConstantRightZ a (d*n) b pf1 v2 =plusConstantLeftZ b (d*m) (d*n) pf2 |||The theorem d|a =>d|ac MultDiv:(isDivisible a d) ->(c:ZZ)->(isDivisible (a*c) d) MultDiv {d} (n**Refl) c =((n*c)** (rewrite sym (multAssociativeZ d n c) in (Refl))) |||The theorem d|a and d|b =>d|(a+b) PlusDiv : (isDivisible a d)->(isDivisible b d)->(isDivisible (a+b) d) PlusDiv {d}{a}{b} (n**prf1) (m**prf2) = ((n+m)**(DistributeProof a b d n m prf1 prf2)) |||The theorem b|a and c|b =>c|a TransDivide : (isDivisible a b)->(isDivisible b c)->(isDivisible a c) TransDivide {c} (x ** pf1) (y ** pf2) = (y*x ** (rewrite multAssociativeZ c y x in (rewrite pf1 in (rewrite pf2 in Refl)))) |||If d divides a and b it divides a linear combination of a and b LinCombDiv:(m:ZZ)->(n:ZZ)->(isDivisible a d)->(isDivisible b d)->(isDivisible ((a*m)+(b*n)) d) LinCombDiv m n dDiva dDivb = PlusDiv (MultDiv dDiva m) (MultDiv dDivb n) EuclidConservesDivisor:(m:ZZ)->(isDivisible a d)->(isDivisible b d)->(isDivisible (a+(b*(-m))) d) EuclidConservesDivisor m dDiva dDivb = PlusDiv dDiva (MultDiv dDivb (-m) ) |||Any integer divides zero ZZDividesZero:(a:ZZ)->(isDivisible 0 a ) ZZDividesZero a = (0**(sym (multZeroRightZeroZ a))) |||A type that is occupied iff c is a common factor of a and b isCommonFactorZ : (a:ZZ) -> (b:ZZ) -> (c:ZZ) -> Type isCommonFactorZ a b c = ((isDivisible a c),(isDivisible b c)) |||The GCD type that is occupied iff d = gcd (a,b). Here GCD is defined as that positive integer such that any common factor of a and b divides it GCDZ : (a:ZZ) -> (b:ZZ) -> (d:ZZ) -> Type GCDZ a b d = ((IsPositive d),(isCommonFactorZ a b d),({c:ZZ}->(isCommonFactorZ a b c)->(isDivisible d c))) |||Anything divides itself SelfDivide:(a:ZZ)->(isDivisible a a) SelfDivide a = (1**sym (multOneRightNeutralZ a)) |||Generates the proof that if c is a common factor of a and 0 then c divides a GCDCondition : (a:ZZ) -> ({c:ZZ}->(isCommonFactorZ a 0 c)->(isDivisible a c)) GCDCondition a {c} (cDiva,cDiv0) = cDiva |||Proves that the GCD of a and 0 is a gcdOfZeroAndInteger:(a:ZZ)->IsPositive a ->GCDZ a 0 a gcdOfZeroAndInteger a pf = (pf,((SelfDivide a),(ZZDividesZero a)),((GCDCondition a))) |||The theorem, d|a =>d|(-a) dDividesNegative:(isDivisible a d)->(isDivisible (-a) d) dDividesNegative{a}{d} (x ** pf) = ((-x)**(multNegateRightIsNegateZ a d x pf)) |||The theorem c|b and c|(a+bp) then c|a cDiva :{p:ZZ} ->(cDIvb :(isDivisible b c))->(cDIvExp:isDivisible (a+(b*p)) c)->(isDivisible a c) cDiva {p}{b}{a}{c} cDivb cDivExp = rewrite (sym (addAndSubNeutralZ a (b*p))) in (PlusDiv cDivExp (dDividesNegative(MultDiv cDivb (p)))) |||A helper function for euclidConservesGcd function genFunctionForGcd :(f:({c:ZZ}->(isCommonFactorZ a b c)->(isDivisible d c)))->(({c:ZZ}->(isCommonFactorZ b (a+(b*(-m))) c)->(isDivisible d c))) genFunctionForGcd f (cDivb,cDivExp) = f((cDiva cDivb cDivExp,cDivb)) |||The theorem, gcd(a,b)=d => gcd (b, a+ b(-m))=d euclidConservesGcd :(m:ZZ)->(GCDZ a b d)->(GCDZ b (a+(b*(-m))) d) euclidConservesGcd m (posProof, (dDiva,dDivb), f) = (posProof,(dDivb,(EuclidConservesDivisor m dDiva dDivb)),genFunctionForGcd f) |||The theorem that if c and d are positive d|c => (d is less than or equal to c) posDivPosImpliesLte:(isDivisible c d)->(IsPositive c)->(IsPositive d)->LTEZ d c posDivPosImpliesLte {d}{c}(x ** pf) cPos dPos = posLteMultPosPosEqZ {q=x} d c dPos cPos pf |||The Theorem that if c and d are positive, d|c and c|d =>(c=d) PosDivAndDivByImpliesEqual: (isDivisible c d)->(isDivisible d c)->(IsPositive c)->(IsPositive d) -> (c=d) PosDivAndDivByImpliesEqual x y z x1 =lteAndGteImpliesEqualZ dLtec cLted where dLtec =posDivPosImpliesLte x z x1 cLted =posDivPosImpliesLte y x1 z
import numpy as np from numpy.random import randn from filterpy.common import Q_discrete_white_noise from filterpy.kalman import KalmanFilter, unscented_transform from filterpy.kalman import UnscentedKalmanFilter as UKF from filterpy.kalman import MerweScaledSigmaPoints import math from scipy.signal import butter, lfilter from scipy.signal import freqs import sympy as sp from lmfit import Parameters from ..solver import Solver_jac def butter_lowpass(cutoff, fs, order=5): nyq = 0.5 * fs normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='low', analog=False) return b, a def butter_lowpass_filter(data, cutoff, fs, order=5): b, a = butter_lowpass(cutoff, fs, order=order) y = lfilter(b, a, data) return y def lowpass_filter(data): # Filter requirements. order = 6 fs = 10 # sample rate, Hz cutoff = 2 # desired cutoff frequency of the filter, Hz # Get the filter coefficients so we can check its frequency response. b, a = butter_lowpass(cutoff, fs, order) # Plot the frequency response. # w, h = freqz(b, a, worN=8000) # plt.subplot(2, 1, 1) # plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b') # plt.plot(cutoff, 0.5*np.sqrt(2), 'ko') # plt.axvline(cutoff, color='k') # plt.xlim(0, 0.5*fs) # plt.title("Lowpass Filter Frequency Response") # plt.xlabel('Frequency [Hz]') # plt.grid() # Demonstrate the use of the filter. # First make some data to be filtered. T = 5.0 # seconds n = int(T * fs) # total number of samples # t = np.linspace(0, T, n, endpoint=False) # "Noisy" data. We want to recover the 1.2 Hz signal from this. # data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + \ # 0.5*np.sin(12.0*2*np.pi*t) # Filter the data, and plot both the original and filtered signals. y = butter_lowpass_filter(data, cutoff, fs, order) return y def mean_filter(data, win=3): result = data.copy() size = data.size for i in range(1, size - win + 1): result[i] = np.mean(result[i:i + win]) return result def median_filter(data, win=3): result = data.copy() size = data.size for i in range(1, size - win + 1): result[i] = np.median(result[i:i + win]) return result
Formal statement is: lemma connectedI_interval: fixes U :: "'a :: linear_continuum_topology set" assumes *: "\<And>x y z. x \<in> U \<Longrightarrow> y \<in> U \<Longrightarrow> x \<le> z \<Longrightarrow> z \<le> y \<Longrightarrow> z \<in> U" shows "connected U" Informal statement is: If $U$ is a subset of a linear continuum such that for all $x, y, z \in U$ with $x \leq z \leq y$, we have $z \in U$, then $U$ is connected.
Formal statement is: lemma components_eq_sing_exists: "(\<exists>a. components s = {a}) \<longleftrightarrow> connected s \<and> s \<noteq> {}" Informal statement is: A set $s$ has exactly one component if and only if $s$ is connected and nonempty.
\clearpage \phantomsection \addcontentsline{toc}{subsection}{sx-read-held} \label{subr:sx-read-held} \subsection*{sx\_shared\_held: Is this shared mutex currently held by a reader} \subsubsection*{Calling convention} \begin{description} \item[\registerop{rd}] Boolean value indicating if this read/write mutex is currently held. \item[\registerop{arg0}] shared lock structure \end{description} \subsubsection*{Description} The \subroutine{sx_shared_held} subroutine takes an sx shared mutex as its only argument and returns a boolean value indicating if the mutex is currently held by a reader. \subsubsection*{Constraints} The \subroutine{sx_shared_held} subroutine is only available on Illumos and systems derivice from OpenSolaris. \subsubsection*{Failure modes} This subroutine has no run-time failure modes beyond its constraints.
(* Copyright 2020 Frédéric Besson <[email protected]> *) Require Import Bool ZifyClasses ZifyUint63 ZArith Lia. Require Import Cdcl.PatriciaR. Require Uint63. Section S. Import Uint63. Definition zero := 0%uint63. Definition one := 1%uint63. End S. Definition int_of_nat (n:nat) := Uint63.of_Z (Z.of_nat n). #[export] Program Instance Op_int_of_nat : UnOp int_of_nat := {| TUOp := fun x => x mod 9223372036854775808%Z ; TUOpInj := _ |}%Z. Next Obligation. unfold int_of_nat. rewrite Uint63.of_Z_spec. reflexivity. Qed. Add Zify UnOp Op_int_of_nat. Lemma int_of_nat_inj : forall n n', n < 63 -> n' < 63 -> int_of_nat n = int_of_nat n' -> n = n'. Proof. intros. unfold int_of_nat in *. lia. Qed. Definition testbit (i:Uint63.int) (n:nat) := if 63 <=? n then false else Uint63.bit i (int_of_nat n). Lemma zero_spec: forall n, testbit zero n = false. Proof. intros. unfold testbit,zero. rewrite Uint63.bit_0. destruct (63 <=?n); auto. Qed. Lemma eqb_spec : forall k1 k2, Uint63.eqb k1 k2 = true <-> k1 = k2. Proof. split ; intros. apply Uint63.eqb_correct; auto. apply Uint63.eqb_complete; auto. Qed. Lemma testbit_spec: forall k1 k2, (forall n, testbit k1 n = testbit k2 n) -> k1 = k2. Proof. intros. unfold testbit in *. apply Uint63.bit_ext;auto ; intros. specialize (H (Z.to_nat (Uint63.to_Z n))). destruct (63 <=? Z.to_nat (Uint63.to_Z n)) eqn:EQ. - assert (Uint63.leb Uint63.digits n = true). { unfold Uint63.digits. lia. } rewrite Uint63.bit_M by assumption. rewrite Uint63.bit_M by assumption. reflexivity. - assert ( int_of_nat (Z.to_nat (Uint63.to_Z n)) = n) by (unfold int_of_nat ; lia). congruence. Qed. Definition interp:= (fun i => (Uint63.sub i one)). Definition is_mask := (fun (m: Uint63.int) (n: nat) => forall p, testbit m p = true <-> n = p). Import Uint63. Section NatUP. Variable P : nat -> bool. Fixpoint forall_n (n:nat) : bool := match n with | O => P O | S n' => P n && forall_n n' end. Lemma forall_n_correct : forall n, forall_n n = true -> forall p, p <= n -> P p = true. Proof. induction n ; simpl. - intros. assert (p = 0) by lia. congruence. - intros. rewrite andb_true_iff in H. destruct H. specialize (IHn H1 p). assert (p = S n \/ p <= n) by lia. destruct H2 ; subst; auto. Qed. End NatUP. Section NatUP2. Variable P : nat -> nat -> bool. Fixpoint forall_2n (n:nat) (m:nat) := match n with | O => forall_n (P O) m | S n' => forall_n (P n) m && forall_2n n' m end. Lemma forall_2n_correct : forall n m, forall_2n n m = true -> forall p q, p <= n -> q <= m -> P p q = true. Proof. induction n ; simpl. - intros. assert (p = 0) by lia. subst. eapply forall_n_correct in H ; eauto. - intros. rewrite andb_true_iff in H. destruct H. specialize (IHn _ H2 p q). assert (p = S n \/ p <= n) by lia. destruct H3 ; subst; auto. eapply forall_n_correct; eauto. Qed. End NatUP2. Lemma bool_and : forall (b: bool) (P: bool -> Prop), (b = true -> P true) /\ (b = false -> P false) -> P b. Proof. intros. destruct b; tauto. Qed. Ltac elim_if := match goal with | |- context[match ?e with | true => _ | false => _ end] => apply (bool_and e) end. Lemma mask_small : forall m n (BOUND : n < 63) (BITN : is_mask m n), m = Uint63.lsl one (int_of_nat n). Proof. unfold one. intros. apply testbit_spec. intros. destruct (testbit m n0) eqn:TEST. - assert (n = n0). { apply BITN;auto. } subst. clear BITN. unfold testbit in *. revert TEST. rewrite Uint63.bit_lsl. rewrite bit_1. repeat elim_if. lia. - assert (n <> n0). { specialize (BITN n0). intuition congruence. } unfold testbit. rewrite Uint63.bit_lsl. rewrite bit_1. repeat elim_if ; intuition try lia. Qed. Lemma mask_big : forall m n (BOUND : n >= 63) (BITN : is_mask m n), False. Proof. unfold is_mask. intros. generalize (BITN n). generalize (BITN (n+1)). intros. unfold testbit in *. replace (63 <=? n +1) with true in * by lia. replace ( 63 <=? n) with true in * by lia. intuition lia. Qed. Definition mask_spec : forall m n, is_mask m n -> if 63 <=? n then False else m = Uint63.lsl one (int_of_nat n). Proof. intros. destruct (63 <=? n) eqn:EQ. eapply mask_big with (n:= n) ; eauto. lia. eapply mask_small with (n:= n) ; eauto. lia. Qed. Lemma eqb_iff : forall b1 b2, Bool.eqb b1 b2 = true <-> (b1 = true <-> b2 = true). Proof. intros. destruct b1,b2; intuition congruence. Qed. Lemma interp_spec: forall m n, is_mask m n -> forall p, testbit (interp m) p = true <-> (p < n)%nat. Proof. intros. apply mask_spec in H. destruct (63 <=? n) eqn:N; [tauto|]. subst. unfold testbit. destruct (63 <=?p) eqn:EQ. - lia. - assert (NS : n <= 62) by lia. assert (NP : p <= 62) by lia. rewrite <- Nat.ltb_lt. apply eqb_iff. set (Q:= fun n p => Bool.eqb (bit (interp (one << int_of_nat n)) (int_of_nat p)) (p <? n)). change (Q n p = true). eapply (forall_2n_correct _ 62 62);auto. Qed. Lemma land_spec: forall n k1 k2, testbit (Uint63.land k1 k2) n = testbit k1 n && testbit k2 n. Proof. intros. unfold testbit. rewrite Uint63.land_spec. destruct (63 <=? n) eqn:T; reflexivity. Qed. Lemma lxor_spec: forall n k1 k2, testbit (Uint63.lxor k1 k2) n = xorb (testbit k1 n) (testbit k2 n). Proof. intros. unfold testbit. rewrite Uint63.lxor_spec. destruct (63 <=? n) eqn:T; reflexivity. Qed. Ltac unfold_wB := let f := fresh "w" in set (f := wB) in *; compute in f ; unfold f in *; clear f. Definition ones (n:int) := ((1 << n) - 1)%uint63. Lemma power2_mod : forall n m, (0 <= n -> 0 <= m -> ((2 ^ n) mod (2 ^ m) = if Z.ltb n m then 2^n else 0))%Z. Proof. intros. destruct (n <?m)%Z eqn:T. - apply Z.mod_small; auto. split. apply Z.pow_nonneg. lia. apply Z.pow_lt_mono_r; lia. - assert ((2 ^ n) = 0 + 2^(n-m) * 2^m)%Z. rewrite <- Z.pow_add_r. simpl. f_equal. lia. lia. lia. rewrite H1. rewrite Z_mod_plus_full. apply Z.mod_0_l. generalize (Z.pow_pos_nonneg 2 m). lia. Qed. Lemma bit_ones : forall n p, (*(SMALL: (n < Uint63.digits = true)%uint63),*) bit (ones n) p = if (ltb p n && (ltb p 63))%uint63 then true else false. Proof. unfold ones,one. intros. rewrite bitE. rewrite sub_spec. rewrite lsl_spec. replace (((φ (1)%uint63 * 2 ^ φ (n)%uint63)))%Z with (2 ^ (to_Z n))%Z by lia. unfold wB. rewrite power2_mod by (unfold size ; lia). destruct ((φ (n)%uint63 <? Z.of_nat size)%Z) eqn:T. - unfold size in *. rewrite Z.mod_small. replace ( 2 ^ φ (n)%uint63 - φ (1)%uint63)%Z with (Z.pred (2 ^ φ (n)%uint63))%Z by lia. rewrite <- Z.ones_equiv. rewrite Z.testbit_ones_nonneg by lia. destruct ((p <? n) && (p <? 63))%uint63 eqn:LT. lia. lia. assert (BOUND : (0 < 2 ^ to_Z n < wB)%Z). { unfold wB. split. apply Z.pow_pos_nonneg; lia. apply Z.pow_lt_mono_r. lia. unfold size. lia. unfold digits, size in *. lia. } lia. - assert (1 < 2 ^ Z.of_nat size)%Z. { apply Z.pow_gt_1. lia. lia. } rewrite Z_mod_nz_opp_full; rewrite Z.mod_small ; try lia. replace ( 2 ^ Z.of_nat size - φ (1)%uint63)%Z with (Z.pred (2 ^ Z.of_nat size))%Z by lia. rewrite <- Z.ones_equiv. rewrite Z.testbit_ones_nonneg by lia. destruct ((p <? n)%uint63 && (p <? 63)%uint63) eqn:T2. lia. lia. Qed. Definition split_m (i: int) (m: int) := ( (i land ((ones digits) << m)) lor ((i land (ones m))))%uint63. Lemma split_all : forall i m, i = split_m i m. Proof. intros. unfold split_m. apply bit_ext. intros. rewrite lor_spec. rewrite Uint63.land_spec. rewrite bit_lsl. rewrite Uint63.land_spec. rewrite! bit_ones. generalize (bit_M i n). destruct ((n <? m)%uint63 || (digits ≤? n)%uint63) eqn:T1. destruct ((n <? m)%uint63 && (n <? 63)%uint63) eqn:T2. - unfold digits in *. destruct (bit i n); try lia. - unfold digits in *. destruct (bit i n); try lia. - destruct ((n - m <? digits)%uint63 && (n - m <? 63)%uint63) eqn:T2. destruct ((n <? m)%uint63 && (n <? 63)%uint63) eqn:T3. unfold digits in *. destruct (bit i n); try lia. unfold digits in *. destruct (bit i n); try lia. destruct ((n <? m)%uint63 && (n <? 63)%uint63) eqn:T3. unfold digits in *. destruct (bit i n); try lia. unfold digits in *. destruct (bit i n); try lia. Qed. Definition is_set (k:int) (m:nat) := (forall p, (p < m)%nat -> testbit k p = false) /\ testbit k m = true. Definition is_set_int (k:int) (m:int) := (forall p, (p <? m = true)%uint63 -> bit k p = false) /\ bit k m = true. Ltac split_and := match goal with | |- ?A /\ ?B => split ; intros; split_and | _ => idtac end. Definition nat_of_int (i:int) := Z.to_nat (to_Z i). Lemma is_set_small : forall k m, is_set k m -> m < 63. Proof. intros. unfold is_set in *. destruct H. unfold testbit in *. destruct (63 <=? m) eqn:EQ ; lia. Qed. Lemma is_set_eq : forall k m, is_set k m -> exists n, n = int_of_nat m /\ (n <? digits = true)%uint63 /\ is_set_int k n. Proof. intros. assert (SM := is_set_small _ _ H). unfold is_set, is_set_int in *. destruct H. exists (int_of_nat m). split_and; intros. - reflexivity. - unfold digits ; lia. - unfold testbit in H. rewrite <- H with (p := nat_of_int p). replace (63 <=? nat_of_int p) with false by (unfold nat_of_int in* ; lia). f_equal. unfold nat_of_int ; lia. unfold nat_of_int ; lia. - unfold testbit in H0. rewrite <- H0. destruct (63 <=? m) ; congruence. Qed. Lemma is_set_decomp : forall k m, is_set k m -> (k = ((k >> (int_of_nat m + 1)) << (int_of_nat m + 1)) lor (1 << int_of_nat m))%uint63. Proof. intros. apply is_set_eq in H. destruct H as (n & EQ & LT & SET). unfold is_set_int in SET. destruct SET as [F T]. rewrite <- EQ. clear EQ. apply bit_ext. intros. rewrite lor_spec. rewrite ! bit_lsl. rewrite ! bit_lsr. assert (n0 = n \/ n0 <? n = true \/ (Uint63.ltb n n0 && Uint63.ltb n0 digits) = true \/ (Uint63.leb digits n0) = true)%uint63 by lia. destruct H as [H | [H | [H |H]]]. + subst. rewrite T. repeat elim_if. rewrite bit_1. lia. + rewrite F by auto. repeat elim_if. rewrite bit_1. lia. + rewrite andb_true_iff in H. destruct H. replace (n0 <? n + 1)%uint63 with false by lia. simpl. replace (digits <=? n0)%uint63 with false by lia. replace ((n0 - (n + 1) ≤? n + 1 + (n0 - (n + 1)))%uint63) with true by lia. replace ((n + 1 + (n0 - (n + 1))))%uint63 with n0 by lia. elim_if. rewrite bit_1. destruct (bit k n0); lia. + rewrite bit_M; auto. repeat elim_if. rewrite! bit_1. lia. Qed. Lemma sub_pow2 : forall x k m, (0 <= k < m)%Z -> (0<= x < 2^m)%Z -> (x - x mod 2 ^ (k+1) + 2^k < 2^ m )%Z. Proof. intros. assert (2 ^(k +1) = 2 * 2^k)%Z. { rewrite Z.pow_add_r; lia. } rewrite H1. clear H1. assert (exists n, Z.of_nat n = m). { exists (Z.to_nat m). lia. } destruct H1 as (m' & EQ). subst. revert x k H0 H. induction m'. - intros. change (2^ Z.of_nat 0)%Z with 1%Z in *. assert (x = 0)%Z by lia. subst. lia. - intros. replace (Z.of_nat (S m'))%Z with (1 + Z.of_nat m')%Z in * by lia. assert (DB : (0 <= x / 2 < 2^ Z.of_nat m')%Z). { rewrite Z.pow_add_r in H0 by lia. lia. } assert (k = 0 \/ 0<= k-1 < Z.of_nat m')%Z by lia. destruct H1. + subst. change (2 * 2^0)%Z with 2%Z. rewrite Z.pow_add_r in * by lia. lia. + specialize (IHm' (x / 2)%Z _ DB H1). rewrite Z.pow_add_r by lia. assert (2 * 2^ (k-1) = 2 ^k)%Z. { change 2%Z with (2^1)%Z at 1. rewrite <- Z.pow_add_r by lia. f_equal. lia. } rewrite H2 in IHm'. assert (2^0 <= 2 ^ k)%Z. { apply Z.pow_le_mono_r; lia. } assert (2 * (x / 2 - (x / 2) mod 2 ^ k + 2 ^ (k - 1)) + 1 < 2 * 2 ^ Z.of_nat m')%Z by lia. eapply Z.le_lt_trans ; eauto. ring_simplify. rewrite H2. cut (x - x mod (2 * 2 ^ k) <= 2 * (x / 2) - 2 * ((x / 2) mod 2 ^ k) + 1)%Z. lia. clear - H3. zify. rewrite H5 by lia. rewrite H10 by lia. assert (q1 = q0) by nia. lia. Qed. Lemma to_Z_branch_bit : forall k m (SMALL : (m <? 63 = true)%uint63), to_Z ((k >> (m + 1)) << (m + 1) + 1 << m)%uint63 = ((to_Z k / 2^ (to_Z m + 1)) * 2^ (to_Z m + 1) + 2^ (to_Z m))%Z. Proof. intros. rewrite add_spec. rewrite! lsl_spec. rewrite lsr_spec. rewrite add_spec. change (to_Z m + to_Z 1%uint63)%Z with (to_Z m + 1)%Z. assert (B1 : (0 <= φ (1)%uint63 * 2 ^ φ (m)%uint63 < wB)%Z). { replace (φ (1)%uint63 * 2 ^ φ (m)%uint63)%Z with (2 ^ to_Z m)%Z by lia. split. apply Z.pow_nonneg. lia. apply Z.pow_lt_mono_r. lia. lia. lia. } assert (B2 : (2^1 <= 2 ^ ((φ (m)%uint63 + 1)))%Z). { apply Z.pow_le_mono_r. lia. lia. } assert (B3 : (0 <= φ (k)%uint63 / 2 ^ ((φ (m)%uint63 + 1)))%Z). { nia. } assert (B4 : (0 <= φ (k)%uint63 / 2 ^ ((φ (m)%uint63 + 1) mod wB) * 2 ^ ((φ (m)%uint63 + 1) mod wB) < wB)%Z). { change (Z.of_nat size) with 63%Z in *. rewrite Z.mod_small by lia. split. apply Z.mul_nonneg_nonneg ; nia. nia. } rewrite! Z.mod_small; auto. - lia. - unfold wB. change (Z.of_nat size) with 63%Z. lia. - rewrite Z.mod_small;auto. rewrite Z.mod_small;auto. rewrite Z.mod_small;auto. split. lia. clear B4. unfold wB in *. change (Z.of_nat size) with 63%Z. assert (φ (k)%uint63 / 2 ^ (φ (m)%uint63 + 1) * 2 ^ (φ (m)%uint63 + 1) = to_Z k - to_Z k mod 2 ^ (φ (m)%uint63 + 1))%Z. nia. rewrite H. change (to_Z 1%uint63) with 1%Z. rewrite Z.mul_1_l. apply sub_pow2. lia. lia. unfold wB. change (Z.of_nat size) with 63%Z. lia. Qed. Lemma testbit_0 : forall a n, (0 <= n)%Z -> Z.testbit a n = ((a / 2 ^ n) mod 2 =? 1)%Z. Proof. intros. generalize (Z.testbit_true a n H). destruct (Z.testbit a n); intuition. - rewrite H0. reflexivity. - assert ((a / 2 ^ n) mod 2 = 0 \/ a / 2 ^ n mod 2 = 1)%Z. clear. lia. destruct H0. rewrite H0. reflexivity. intuition congruence. Qed. Definition not_int (x : int) := (- x - 1)%uint63. Lemma bit_not_int : forall x n (SN : (n <? digits = true)%uint63), bit (not_int x) n = negb (bit x n). Proof. unfold not_int. intros. rewrite! bitE. unfold Uint63.opp. rewrite sub_spec. assert (x = 0 \/ x <> 0)%uint63 by lia. destruct H. - subst. change (to_Z (0 - 0)%uint63) with 0%Z. rewrite Z.bits_0. simpl. change ( - to_Z 1%uint63 mod wB)%Z with (wB - 1)%Z. assert (nat_of_int n <= 62). { unfold nat_of_int, digits in * ; lia. } replace (to_Z n) with (Z.of_nat (nat_of_int n)) by (unfold nat_of_int in * ; lia). set (P := fun n => Z.testbit (wB - 1) (Z.of_nat n)). change (P (nat_of_int n) = true). eapply (forall_n_correct _ 62); auto. - rewrite sub_spec. rewrite Z.sub_0_l. unfold digits in SN. rewrite Z.mod_opp_l_nz. rewrite (Z.mod_small (to_Z x)%Z). rewrite Z.mod_small. rewrite <- (Z.opp_involutive (wB - φ (x)%uint63 - φ (1)%uint63)). rewrite Z.bits_opp. f_equal. replace ((Z.pred (- (wB - φ (x)%uint63 - φ (1)%uint63))))%Z with (to_Z x + (-1) * wB)%Z by lia. rewrite! testbit_0 by lia. replace (-1 * wB)%Z with ((2 * (-1 * 2^(62 - to_Z n))) * 2^(to_Z n))%Z. rewrite Z_div_plus. rewrite Z.mul_comm. rewrite Z_mod_plus_full. reflexivity. apply pow2_pos. lia. unfold wB. change (Z.of_nat size) with 63%Z. replace 63%Z with (1 + (62 - to_Z n) + to_Z n)%Z by lia. rewrite! Z.pow_add_r. all: try (change wB with (2^63)%Z ; lia). Qed. Lemma opp_spec : forall x, (- x = not_int x + 1)%uint63. Proof. unfold not_int. intros. lia. Qed. Lemma bit_ext' : forall a b, (forall n, n <? digits = true -> bit a n = bit b n)%uint63 -> a = b. Proof. intros. apply bit_ext. intros. assert (digits <=? n = true \/ n <? digits = true)%uint63 by lia. destruct H0. - rewrite! bit_M by auto. reflexivity. - apply H ; auto. Qed. Lemma not_int_lor : forall a b, (not_int (a lor b) = (not_int a) land (not_int b))%uint63. Proof. intros. apply bit_ext'; intros. rewrite Uint63.land_spec. rewrite! bit_not_int by auto. rewrite Uint63.lor_spec. apply negb_orb. Qed. Definition bit_excl (x y: int) := (forall n : int, bit x n = true -> bit y n = true -> False). Lemma lsl_1_spec : forall n, (n <? digits = true)%uint63 -> (φ (1 << n)%uint63 = 2 ^ to_Z n)%Z. Proof. intros. rewrite lsl_spec. rewrite Z.mod_small. lia. replace (φ (1)%uint63 * 2 ^ φ (n)%uint63)%Z with (2^ to_Z n)%Z by lia. split. apply Z.pow_nonneg. lia. unfold wB. unfold size. apply Z.pow_lt_mono_r. lia. lia. unfold digits in *; lia. Qed. Lemma bit_pred_1_lsl : forall n i , (n <? digits = true)%uint63 -> (bit (1 << n - 1) i)%uint63 = (to_Z i <? to_Z n)%Z. Proof. intros. rewrite bitE. rewrite sub_spec. rewrite Z.mod_small. rewrite lsl_1_spec by auto. replace (2 ^ φ (n)%uint63 - φ (1)%uint63)%Z with (Z.pred (2 ^ (to_Z n)))%Z by lia. rewrite <- Z.ones_equiv. apply Z.testbit_ones_nonneg. lia. lia. rewrite lsl_1_spec by auto. assert (2^0 <= 2 ^ to_Z n)%Z. { apply Z.pow_le_mono_r ; lia. } unfold wB, size. change (Z.of_nat 63) with 63%Z. assert (2^ to_Z n < 2 ^ 63)%Z. { apply Z.pow_lt_mono_r. lia. lia. lia. } lia. Qed. Lemma not_int_lsl : forall k m, (m <? digits = true)%uint63 -> (not_int ((k >> (m+1)) << (m+1) lor (1 << m)) = (((not_int k) >> (m+1) << (m+1)) lor (1 << m - 1)))%uint63. Proof. intros. apply bit_ext'; intros. rewrite! bit_not_int by auto. rewrite! Uint63.lor_spec. rewrite bit_pred_1_lsl by auto. rewrite bit_lsl. rewrite! bit_lsr. rewrite! bit_lsl. rewrite bit_lsr. rewrite bit_not_int. replace ((m + 1 + (n - (m + 1))))%uint63 with n by lia. rewrite bit_1. repeat elim_if. intuition try lia. destruct (bit k n); lia. zify. lia. Qed. Lemma bit_add_or : forall x y : int, (forall n : int, bit x n = true -> bit y n = true -> False) -> (x + y)%uint63 = (x lor y)%uint63. Proof. intros. now apply Uint63.bit_add_or. Qed. Lemma opp_mask : forall k m, (m <? digits = true)%uint63 -> (- ((k >> (m + 1)) << ( m + 1) lor 1 << m) = (((not_int k) >> (m+1)) << (m+1)) lor ((1 << m)))%uint63. Proof. intros. rewrite opp_spec. rewrite! not_int_lsl by auto. repeat rewrite <- bit_add_or. zify. lia. - intros. rewrite bit_lsl in H1. rewrite bit_1 in H1. rewrite bit_lsl in H0. rewrite bit_lsr in H0. revert H0 H1. repeat elim_if. intuition try lia. - intros. rewrite bit_pred_1_lsl in H1 by lia. rewrite bit_lsl in H0. revert H0 H1. elim_if; intuition try lia. Qed. Lemma LPO : forall (k:Uint63.int), k <> zero -> exists p, testbit k p = true. Proof. intros. unfold zero in *. assert (LPO: (exists p, ((p <? int_of_nat size) = true) /\ (bit k p = true))%uint63). { case (to_Z_bounded k). unfold wB. assert (0 < size <= 63). { unfold size. lia. } revert k H. induction size; try lia. intros. assert (n = 0 \/ 0 < n) by lia. destruct H3. - subst. assert (k = one). { change (2 ^Z.of_nat 1)%Z with 2%Z in H2. unfold one. lia. } subst. exists 0%uint63. split. unfold int_of_nat. lia. apply bit_1. - assert ((k >> 1) = 0 \/ (k >> 1) <> 0)%uint63 by lia. destruct H4. + exists 0%uint63. unfold int_of_nat. split. lia. destruct (bit k 0) eqn:B0;auto. rewrite (bit_split k) in H. rewrite B0 in H. rewrite H4 in H. compute in H. lia. + assert (exists p : int, (p <? int_of_nat n)%uint63 = true /\ bit (k >> 1) p = true). { apply IHn ; auto. lia. lia. rewrite lsr_spec. replace (Z.of_nat (S n)) with (1 + Z.of_nat n)%Z in H2 by lia. rewrite Z.pow_add_r in H2 by lia. lia. } destruct H5. exists (x+1)%uint63. split. unfold int_of_nat in *. lia. destruct H5. rewrite bit_lsr in H6. destruct ((x ≤? 1 + x)%uint63) eqn:EQ ; try lia. rewrite <- H6. f_equal. lia. } destruct LPO. exists (Z.to_nat (to_Z x)). unfold testbit. destruct (63 <=? Z.to_nat (to_Z x)) eqn:LE. unfold int_of_nat,size in H0. lia. destruct H0. rewrite <- H1. f_equal. unfold int_of_nat; lia. Qed. Definition lowest_bit (x: int) := (x land (opp x))%uint63. Fixpoint find_lowest (n: nat) (k: int) (p: nat) := match p with | O => n | S q => if testbit k (n - p)%nat then (n - p)%nat else find_lowest n k q end. Lemma find_lowest_spec: forall n p k, testbit k n = true -> (forall q, ((n - p)%nat <= q < find_lowest n k p)%nat -> testbit k q = false) /\ testbit k (find_lowest n k p) = true. Proof. induction p; intros. - simpl. split; auto. intros; lia. - apply IHp in H. destruct H as [HA HB]. simpl. case_eq (testbit k (n - S p)%nat); intros. + split; intros; auto; lia. + split; intros; auto. destruct (Nat.eq_dec (n - S p)%nat q). * subst q. auto. * apply HA; lia. Qed. Lemma lopp_spec_low: forall k m, (forall p, (p < m)%nat -> testbit k p = false) -> testbit k m = true -> forall p, (p < m)%nat -> testbit (Uint63.opp k) p = false. Proof. intros. assert (IS : is_set k m). { unfold is_set ; auto. } assert (MSMALL := is_set_small k m IS). apply is_set_decomp in IS. rewrite IS. rewrite opp_mask by (unfold digits; lia). unfold testbit. replace (int_of_nat (Init.Nat.min p 62)) with (int_of_nat p) by lia. rewrite Uint63.lor_spec. rewrite bit_lsl. rewrite bit_lsl. rewrite bit_1. repeat elim_if ; lia. Qed. Lemma lopp_spec_eq: forall k m, (forall p, (p < m)%nat -> testbit k p = false) -> testbit k m = true -> testbit (Uint63.opp k) m = true. Proof. intros. assert (IS : is_set k m). { unfold is_set ; auto. } assert (MSMALL := is_set_small k m IS). apply is_set_decomp in IS. rewrite IS. rewrite opp_mask by (unfold digits; lia). unfold testbit. replace (int_of_nat (Init.Nat.min m 62)) with (int_of_nat m) by lia. rewrite Uint63.lor_spec. rewrite bit_lsl. rewrite bit_lsl. rewrite bit_1. unfold digits. repeat elim_if ; lia. Qed. Definition digits := Some 63%nat. Lemma testbit_M : forall k n, le_o digits n -> testbit k n = false. Proof. simpl. intros. unfold testbit. replace (63 <=? n)%nat with true by lia. reflexivity. Qed. Lemma lopp_spec_high: forall k m, (forall p, (p < m)%nat -> testbit k p = false) -> testbit k m = true -> forall p, (p > m)%nat -> ~ le_o digits p -> testbit (Uint63.opp k) p = negb (testbit k p). Proof. intros. assert (IS : is_set k m). { unfold is_set ; auto. } assert (MSMALL := is_set_small k m IS). apply is_set_decomp in IS. rewrite IS. clear IS. simpl in H2. rewrite opp_mask by (unfold Uint63.digits; lia). unfold testbit. replace (63 <=?p)%nat with false by lia. rewrite! Uint63.lor_spec. rewrite bit_lsl. rewrite! bit_lsl. rewrite bit_1. rewrite! bit_lsr. unfold Uint63.digits. repeat elim_if ; intuition try lia. + rewrite bit_not_int by (unfold Uint63.digits ; lia). destruct (bit k (int_of_nat m + 1 + (int_of_nat p - (int_of_nat m + 1)))). lia. lia. Qed. Lemma ltb_spec: forall m1 n1 m2 n2, is_mask m1 n1 -> is_mask m2 n2 -> (Uint63.ltb m1 m2 = true <-> (n1 < n2)%nat). Proof. intros. apply mask_spec in H. apply mask_spec in H0. destruct (63 <=? n1)%nat eqn:N1; [tauto|]. destruct (63 <=? n2)%nat eqn:N2; [tauto|]. subst. assert (NS : (n1 <= 62)%nat) by lia. assert (NP : (n2 <= 62)%nat) by lia. rewrite <- Nat.ltb_lt. apply eqb_iff. set (Q:= fun n1 n2=> Bool.eqb (one << int_of_nat n1 <? one << int_of_nat n2)%uint63 (n1 <? n2)%nat). change (Q n1 n2 = true). eapply (forall_2n_correct _ 62 62);auto. Qed. #[export] Instance KInt : Keys_Base.Key Uint63.int := {| Keys_Base.eqb:= Uint63.eqb; Keys_Base.testbit:= testbit; Keys_Base.interp:= (fun i => (Uint63.sub i one)); Keys_Base.land:= Uint63.land; Keys_Base.lxor:= Uint63.lxor; Keys_Base.lopp:= Uint63.opp; Keys_Base.ltb:= Uint63.ltb; Keys_Base.digits := digits; Keys_Base.testbit_M := testbit_M; Keys_Base.zero_spec:= zero_spec; Keys_Base.eqb_spec := KeyInt.eqb_spec; Keys_Base.testbit_spec:= testbit_spec; Keys_Base.interp_spec:= interp_spec; Keys_Base.land_spec:= land_spec; Keys_Base.lxor_spec:= lxor_spec; Keys_Base.lopp_spec_low:= lopp_spec_low; Keys_Base.lopp_spec_eq:= lopp_spec_eq; Keys_Base.lopp_spec_high:= lopp_spec_high; Keys_Base.ltb_spec:= ltb_spec; Keys_Base.LPO := LPO; |}.
\chapterimage{chapter_head_2.pdf} \chapter{Boundaries} Interesting things happen at boundaries(e.g. between our code and 3rd-party libraries). Change(e.g. from a 3rd-party library) is one of those things. Good software designs accommodate change without huge investments and rework. When we use code that is out of our control, special care must be taken to protect our investment and make sure future change is not too costly. Code at the boundaries needs clear separation and tests that define expectations. We should avoid letting too much of our code know about the third-party particulars. It's better to depend on something you control than on something you don't control, lest it end up controlling you. We manage third-party boundaries by having very few places in the code that refer to them. We may wrap them in our own object, or we may use an ADAPTER to convert from our perfect interface to the provided interface. Either way our code speaks to us better, promotes internally consistent usage across the boundary, and has fewer maintenance points when the third-party code changes. The sections below discusses how to achieve this in detail and, of course, guides your review process. \section{Using Third-Party Code}\index{Boundaries!Using Third-Party Code} There is a natural tension between the provider of an interface and the user of an interface. Providers of third-party packages and frameworks strive for broad applicability so they can work in many environments and appeal to a wide audience. Users, on the other hand, want an interface that is focused on their particular needs. This tension can cause problems at the boundaries of our systems. For example, \inlinecode[green]{java.util.Map} is a very useful object, but what if we would like a map that just supports inserts and retrievals, but not delete? When you pass this map around system, you cannot guarantee that other maintainers would not misused it by calling a delete method. A cleaner way to use Map, for example, might look like the following: \begin{tcolorbox}[breakable, colback=green!10!white, colframe=green!85!black, sidebyside, righthand width = 3cm, tikz lower, label=blocks-and-indenting-good] \begin{lstlisting}[language = java, basicstyle=\small] public class Sensors { private Map sensors = new HashMap(); public Sensor getById(String id) { return (Sensor) sensors.get(id); } //snip } \end{lstlisting} \tcblower \path[fill = yellow, draw = yellow!75!red] (0, 0) circle (1cm); \fill[red] (45:5mm) circle (1mm); \fill[red] (135:5mm) circle (1mm); \draw[line width=1mm,red] (215:5mm) arc (215:325:5mm); \end{tcolorbox} \textbf{The interface at the boundary (Map) is hidden}. It is able to evolve with very little impact on the rest of the application. The misuse of calling delete is not possible because you never expose that method in this class. This interface is also tailored and constrained to meet the needs of the application. It results in code that is easier to understand and harder to misuse. Therefore this class can enforce design and business rules. \begin{marker} Try not to pass Maps (or any other interface at a boundary) around your system. If you use a boundary interface like Map, keep it inside the class, or close family of classes, where it is used. Avoid returning it from, or accepting it as an argument to, public APIs. \end{marker} \section{Exploring and Learning Boundaries}\index{Boundaries!Exploring and Learning Boundaries} It's not our job to test the third-party code, but it may be in our best interest to write tests for the third-party code we use. Here is why: when we code 3rd-party libraries into our production system, We would not be surprised to find ourselves bogged down in long debugging sessions trying to figure out whether the bugs we are experiencing are in our code or theirs. Instead of experimenting and trying out the new stuff in our production code, we could write some tests to explore our understanding of the third-party code. Such tests are called \textit{learning tests}(or boundary tests). \begin{marker} Write learning tests to make sure 3rd-parity API does the right things for us. \end{marker} In learning tests we call the third-party API, as we expect to use it in our application. We're essentially doing controlled experiments that check our understanding of that API. The tests focus on what we want out of the API. To summarize the benefits of learning tests: \begin{itemize} \item Writing learning tests is a very good way to learn a 3rd-party API. \item When there are new releases of the third-party package, we run the learning tests to see whether there are behavioral differences. \item Learning tests verify that the third-party packages we are using work the way we expect them to. \end{itemize}
import topology.sheaves.sheaf import topology.category.Top.opens import algebra.category.CommRing import cats open category_theory Top topological_space opposite structure PresheafOfModules1 (X : Top) := (𝒪 : presheaf CommRing X) (ℱ : presheaf AddCommGroup X) [is_module : Π (U : (opens X)ᵒᵖ), module (𝒪.obj U) (ℱ.obj U)] (res_compatible : Π (U V : (opens X)ᵒᵖ) (h : U ⟶ V) (r : 𝒪.obj U) (a: ℱ.obj U), ℱ.map h (r • a) = 𝒪.map h r • ℱ.map h a) -- Now I believe this is not the correct definition, because for `h : U ⟶ V`, `ℱ.map h` is only an `AddCommGroup`-map not a `Module`-map open restriction_of_scalar /-- This is a presheaf of Modules over ℱ ⋙ BundledModule.forget If `h : U ⊆ V`, then `ℱ.map h` is a pair `⟨res₁, res₂⟩`, and `res₁` is the restriction map of sheaf of ring while `res₂` is the restriction map of sheaf of module. -/ class PresheafOfModules2 {X : Top} (ℱ : @presheaf BundledModule BundledModule.is_cat X):= (res_compatible : Π (U V : (opens X)ᵒᵖ) (h : U ⟶ V) (r : (ℱ.obj U).R) (m : (ℱ.obj U).M), (ℱ.map h).2 (r • m) = (r • (ℱ.map h).2 m)) open ulift @[reducible] instance int_as_cring.has_add : has_add (ulift ℤ) := ⟨λ x y, up (down x + down y)⟩ @[simp] lemma int_as_cring.add_def (x y : ℤ) : (up x) + (up y) = up (x + y) := rfl @[reducible] instance int_as_cring.has_neg : has_neg (ulift ℤ) := ⟨λ x, up (- down x)⟩ @[simp] lemma int_as_cring.neg_def (z : ℤ) : -(up z) = up (- z) := rfl @[reducible] instance int_as_cring.has_mul : has_mul (ulift ℤ) := ⟨λ x y, up (down x * down y)⟩ @[simp] lemma int_as_cring.mul_def (x y : ℤ) : up x * up y = up (x * y) := rfl def int_as_cring : CommRing := { α := ulift ℤ, str := { add_assoc := λ a b c, begin cases a, cases b, cases c, dsimp only, rw add_assoc, end, zero := up 0, add_zero := λ a, begin cases a, dsimp only, rw add_zero, end, zero_add := λ a, begin cases a, dsimp only, rw zero_add, end, neg := λ r, up (- down r), add_left_neg := λ a, begin cases a, rw [int_as_cring.neg_def, int_as_cring.add_def, int.add_left_neg], refl, end, add_comm := λ x y, begin cases x, cases y, rw [int_as_cring.add_def, add_comm, int_as_cring.add_def], end, mul_assoc := λ x y z, begin cases x, cases y, cases z, rw [int_as_cring.mul_def, int_as_cring.mul_def, mul_assoc], end, mul_comm := λ x y, begin cases x, cases y, rw [int_as_cring.mul_def, mul_comm, int_as_cring.mul_def], end, one := up 1, one_mul := λ a, begin cases a, rw [int_as_cring.mul_def, one_mul], end, mul_one := λ a, begin cases a, rw [int_as_cring.mul_def, mul_one], end, left_distrib := λ a b c, begin cases a, cases b, cases c, rw [int_as_cring.add_def, int_as_cring.mul_def, mul_add], end, right_distrib := λ a b c, begin cases a, cases b, cases c, rw [int_as_cring.add_def, int_as_cring.mul_def, add_mul], end, ..(int_as_cring.has_add), ..(int_as_cring.has_neg), ..(int_as_cring.has_mul) } } @[simp] lemma lift_int.add_down (x y : int_as_cring) : (x + y).down = x.down + y.down := rfl @[simp] lemma lift_int.zero_down : (0 : int_as_cring).down = 0 := rfl instance int_as_cring.distrib_mul_action (A : AddCommGroup) : distrib_mul_action (int_as_cring) A := { smul := λ x y, x.1 • y, one_smul := λ x, by erw one_zsmul, mul_smul := λ x y r, begin cases x, cases y, rw [int_as_cring.mul_def, mul_zsmul], end, smul_add := λ r x y, by rw zsmul_add, smul_zero := λ r, by rw zsmul_zero } @[simp] lemma lift_int.zsmul (A : AddCommGroup) (r : int_as_cring) (a : A) : r • a = r.1 • a := rfl instance is_int_module (A : AddCommGroup) : module int_as_cring A := { add_smul := λ x y r, begin cases x, cases y, unfold has_scalar.smul, simp only [zsmul_eq_smul], rw [lift_int.add_down], dsimp only, rw add_smul, end, zero_smul := λ x, begin unfold has_scalar.smul, simp only [zsmul_eq_smul], rw [lift_int.zero_down, zero_smul], end} def as_int_module (A : AddCommGroup) : module ℤ A := by apply_instance -- @[reducible] def psh_m {X : Top} (𝒪 : presheaf AddCommGroup X) : -- @presheaf BundledModule BundledModule.is_cat X := -- { obj := λ U, { R := int_as_cring, M := { carrier := 𝒪.obj U, is_module := is_int_module (𝒪.obj U)} }, -- map := λ U V h, -- ⟨𝟙 _, { to_fun := λ m, 𝒪.map h m, -- map_add' := λ x y, by rw add_monoid_hom.map_add, -- map_smul' := λ r m, begin -- dsimp only at *, -- rw [ring_hom.id_apply], -- erw add_monoid_hom.map_zsmul, -- erw [lift_int.zsmul], -- end }⟩ } -- instance {X : Top} (𝒪 : presheaf AddCommGroup X) : -- (PresheafOfModules2 (psh_m 𝒪)) := -- { res_compatible := λ U V h r m, begin -- dsimp only, -- erw [smul_def', id_apply, add_monoid_hom.map_zsmul, lift_int.zsmul], -- end } example (X : Top) (ℱ : @presheaf BundledModule BundledModule.is_cat X) [PresheafOfModules2 ℱ]: PresheafOfModules1 X := { 𝒪 := { obj := λ U, (ℱ.obj U).R, map := λ _ _ h, (ℱ.map h).1 }, ℱ := { obj := λ U, AddCommGroup.of (ℱ.obj U).M, map := λ U V h, @AddCommGroup.of_hom (AddCommGroup.of (ℱ.obj U).M) (AddCommGroup.of (ℱ.obj V).M) _ _ { to_fun := (ℱ.map h).2, map_zero' := linear_map.map_zero _, map_add' := λ m m', begin -- rw linear_map.map_add, sorry, end, }, }, is_module := λ U, begin dsimp only [AddCommGroup.coe_of], apply_instance, end, res_compatible := λ U V h r m, begin dsimp only [AddCommGroup.coe_of, linear_map.map_zero, functor.map_comp, functor.map_id] at *, erw PresheafOfModules2.res_compatible U V h r m, erw [smul_def'], end} @[reducible] def convert_to2 (X : Top) (psofm : PresheafOfModules1 X) : @presheaf BundledModule BundledModule.is_cat X := { obj := λ U,{ R := psofm.𝒪.obj U, M := { carrier := psofm.ℱ.obj U, is_module := psofm.is_module U } }, map := λ U V h, ⟨psofm.𝒪.map h, { to_fun := λ m, psofm.ℱ.map h m, map_add' := λ m m', begin dsimp only at *, simp only [add_monoid_hom.map_add], end, map_smul' := λ r m, begin dsimp only at *, rw [ring_hom.id_apply, psofm.res_compatible _ _ h], -- erw (smul_def' (psofm.𝒪.map h) r { carrier := psofm.ℱ.obj V, -- is_module := psofm.is_module V } (psofm.ℱ.map h m)).symm, sorry, end}⟩ } instance (X : Top) (psofm : PresheafOfModules1 X) : PresheafOfModules2 (convert_to2 X psofm) := { res_compatible := λ U V h r m, begin dsimp only [convert_to2] at *, rw smul_def', erw psofm.res_compatible, refl, end }
From Coq Require Export Strings.String. Require Export Maps. From Coq Require Export Bool.Bool. From Coq Require Export Arith.Arith. From Coq Require Export Arith.EqNat. From Coq Require Export Arith.PeanoNat. Export Nat. From Coq Require Export Lia. Require Export Imp. Require Export Hoare. Definition FILL_IN_HERE {T: Type} : T. Admitted. (* ################################################################# *) (** * Automation for Hoare Logic *) Theorem hoare_if_wp : forall P1 P2 Q (b:bexp) c1 c2, {{ P1 }} c1 {{ Q }} -> {{ P2 }} c2 {{ Q }} -> {{ (b -> P1) /\ (~ b -> P2) }} if b then c1 else c2 end {{ Q }}. Proof. intros P1 P2 Q b c1 c2 HTrue HFalse st st' HE [HP1 HP2]. inversion HE; subst; eauto. Qed. Ltac hauto_vc := eauto; unfold "->>", assn_sub, t_update, bassn; intros; simpl in *; repeat match goal with | [H: _ <> true |- _] => apply not_true_iff_false in H | [H: _ <> false |- _] => apply not_false_iff_true in H | [H: _ /\ _ |- _] => destruct H | [H: _ && _ = true |- _] => apply andb_true_iff in H | [H: _ && _ = false |- _] => apply andb_false_iff in H | [H: _ || _ = true |- _] => apply orb_true_iff in H | [H: _ || _ = false |- _] => apply orb_false_iff in H | [H: negb _ = true |- _] => eapply negb_true_iff in H | [H: negb _ = false |- _] => eapply negb_false_iff in H | [H: (_ =? _) = true |- _] => eapply beq_nat_true in H | [H: (_ =? _) = false |- _] => eapply beq_nat_false in H end; repeat ( try rewrite -> eqb_eq in *; try rewrite -> leb_le in *; try rewrite leb_iff in *; try rewrite leb_iff_conv in * ); try discriminate; try contradiction; eauto; try nia. Ltac hauto_split1 := try match goal with | [|- {{_}} skip {{_}}] => first [eapply hoare_skip;[] | eapply hoare_consequence_pre; [eapply hoare_skip|]] | [|- {{_}} _ := _ {{_}}] => first [eapply hoare_asgn;[] | eapply hoare_consequence_pre; [eapply hoare_asgn|]] | [|- {{_}} _; _ {{_}}] => eapply hoare_seq | [|- {{_}} if _ then _ else _ end {{_}}] => first [eapply hoare_if_wp;[|] | eapply hoare_consequence_pre; [eapply hoare_if_wp|]] end. Ltac hauto := match goal with | [|- {{_}} _ {{_}}] => repeat hauto_split1 | _ => idtac end; try (hauto_vc; fail). Ltac hauto_while P := first[ eapply (hoare_while P) | eapply hoare_consequence_post; [eapply (hoare_while P)|] | eapply hoare_consequence_post; [eapply hoare_consequence_pre; [eapply (hoare_while P)|]|] ]; hauto. Fixpoint factgen (n c: nat) := match n, c with | 0,_ => 1 | _,0 => 1 | S n', S c' => n * factgen n' c' end. Definition fact n := factgen n n. Fixpoint power_series (b n: nat) := match n with | 0 => 1 | S n' => b^n + power_series b n' end.
from numpy import random x = random.choice([3, 5, 7, 9], p=[0.1, 0.3, 0.6, 0.0], size=(100)) print(x)
\documentclass{beamer} \usepackage[utf8]{inputenc} \usepackage{default} \input{preamble-devcon.tex} \title{\textsc{swap, swear and swindle}: \\incentive system for swarm and beyond} \author{Viktor Trón and Aron Fischer} \AtBeginSection[] { \begin{frame}<beamer> \frametitle{Outline} \tableofcontents[currentsection,sectionstyle=show/shaded,subsectionstyle=show/show/shaded,subsubsectionstyle=show/show/show/hide] \end{frame} } \begin{document} \begin{frame} \titlepage \end{frame} \blankslide{\includegraphics[width=0.8\textwidth]{ecosystem0.jpg}} \begin{frame}{Outline} \tableofcontents[subsectionstyle=shaded/shaded,subsubsectionstyle=show/hide/hide] \end{frame} \begin{section}{content delivery} \subsection{data retrieval} \blockslide{\textbf{data out}}{How to retrieve data stored in the swarm.} \begin{frame}{data retrieval} \begin{columns}[T] \begin{column}{0.4\textwidth} \small \begin{itemize} \item<1-> node id, chunk id, function as addresses in the same keyspace \item<4-> dapp retrieves \texttt{awesome-swarm-slides.pdf} \item<5-> get its address \textbf{H} \item<6-> content with address \textbf{H} stored with the node whose own address is \emph{closest} to \textbf{H} \item<7-> swarm's \textbf{retrieval process} is responsible for deliviering \end{itemize} \end{column} \begin{column}{0.6\textwidth} \begin{tikzpicture} \node[scale=0.7]{ \begin{tikzpicture} \node[visible on=<2->] at (2,2) {\textbf{the swarm network:}}; \node[node,visible on=<2->] at (0,0) {}; \node[node,visible on=<2->] at (1,-0.9) {}; \node[node,visible on=<2->] at (0.5,-3) {}; \node[node,visible on=<2->] at (0,-6.3) {}; \node[node,visible on=<2->] at (5.8,-1.2) {}; \node[node,visible on=<2->] at (4,-5.9) {}; \node[node,visible on=<2->] at (4.1,-3) {}; \node[node,visible on=<2->] at (2.1,-2) {}; \node[node,visible on=<2>] at (4,0) (younode) {swarm-node}; \node[peer,visible on=<3->] at (4,0) (you) {You}; \node[visible on=<5->] (chunk) at (1,-5) {$\bullet$}; \node[visible on=<5->] (chunklabel) at (2,-4.5) {H} edge[point,->,visible on =<5->] (chunk); \node[visible on=<2-6>, node] at (-0.5,-4.2) (close) {}; \node[visible on=<7->, peer] at (-0.5,-4.2) (closestnode) {Closest Node}; \node[visible on=<7->] at (-0.5, -5.5) (hlabel) {Look for ``H'' here} edge[visible on=<7->,point,->] (closestnode); \end{tikzpicture} }; \end{tikzpicture} \end{column} \end{columns} \end{frame} \begin{frame}{swarm retrieval process} \begin{tikzpicture} \node[peer,visible on=<1->] at (12,0) (retriever){retriever}; \node[visible on=<13>,scale=2] at (12,-1.5) {\Smiley}; \node[visible on=<2->] (chunk) at (4,-5) {$\bullet$}; \node[visible on=<2->] (chunklabel) at (3,-4) {data address} edge[point,->,visible on =<2->] (chunk); \node[peer,visible on=<4-12>, dimmed on=<13->] at (8.5,-0.5) (connectedpeer){peer} (retriever.-150) edge[point, ->,visible on=<5>,dimmed on=<6-12>, bend left=15] node[below=2pt,visible on=<5>, dimmed on=<6-12>] {request} (connectedpeer.-10); \node[node,visible on=<6-11>, dimmed on=<12->] at (6,-2) (firstnode){some node} (connectedpeer.-70) edge[point,->,visible on=<6>, dimmed on=<7-11>,bend left=30] node[right of=2pt,visible on=<6>, dimmed on=<7-11>] {request} (firstnode.east); \node[node,visible on=<7-10>, dimmed on=<11->] at (7.5,-4.5) (secondnode){other node} (firstnode.-70) edge[point,->,dashed,visible on=<7>, dimmed on=<8-10>,bend left=10] node[right of=2pt,visible on=<7>, dimmed on=<8-10>] {requests...} (secondnode.120); \node[peer,visible on=<3-9>, dimmed on=<10->] at (4,-6) (closestnode){closest node} (secondnode.-110) edge[point,->,visible on=<8>, dimmed on=<9>,out=-110,in=0] node[right of=2pt,visible on=<8>, dimmed on=<9>] {request} (closestnode.east) (closestnode) edge[thick,point,->,visible on=<9>] node[above=2pt,visible on=<9>]{deliver} (secondnode) (secondnode.north west) edge[thick, point,->,visible on=<10>, dashed] node[left of=2pt,visible on=<10>]{deliveries} (firstnode.-120) (firstnode.55) edge[thick,point,->,visible on=<11>] node[left of=2pt,visible on=<11>]{deliver} (connectedpeer.-150) (connectedpeer) edge[thick,point,->,visible on=<12>] node[above=2pt,visible on=<12>]{deliver} (retriever) ; \node[chunk, scale=0.6,visible on=<3->, below=3pt of closestnode.-50] {}; \node[chunk, scale=0.6,visible on=<9->, below=3pt of secondnode.-50] {}; \node[chunk, scale=0.6,visible on=<10->, below=3pt of firstnode.-50] {}; \node[chunk, scale=0.6,visible on=<11->, below=3pt of connectedpeer.-50] {}; \node[chunk, scale=0.6,visible on=<12->, below=3pt of retriever.-50] {}; \end{tikzpicture} \end{frame} \subsection[swap]{paying for data} \plainblockslide{}{\textsc{swap}: \textbf{sw}arm \textbf{a}ccounting \textbf{p}rotocol} \begin{frame}{\textsc{swap}: swarm accounting protocol} \begin{columns}[T] \begin{column}{0.5\textwidth} \uncover<2->{\begin{block}{per-peer bandwidth accounting} keeps track of all data retrieved both directions \end{block} } \uncover<9->{ \begin{block}{settlement} service for service or tally too imbalanced $\rightarrow$ a \emph{payment} is initiated \end{block} } \end{column} \begin{column}{0.5\textwidth} \begin{center} \begin{tikzpicture} \node[peer,visible on=<3->] at (-2,0) (node1) {me}; \node[peer,visible on=<4->] at (2,0) (node2) {peer} (node1.50) edge[point,->,dashed,visible on=<5->,bend right=30,out=50,in=130] node[below=10pt,visible on=<7->,scale=0.8] (sup){data delivered} (node2.130) (node2.-130) edge[point,->,dashed,visible on=<6->,bend left=30,in=130,out=50] node[above=10pt,visible on=<9->,scale=0.8]{data received} (node1.-50) ; \node[visible on=<8->,below= 2mm of sup]{\Large{-}}; \end{tikzpicture} \end{center} \end{column} \end{columns} \end{frame} \begin{frame}{chequebook vs payment channel} \begin{itemize} \item \emph{not feasible} to pay for every chunk of data delivered with a transation \item<2-> even batch payments would constitute unacceptable blockchain bloat (and transaction cost). \end{itemize} \uncover<3->{instead of processing every payment on-chain, SWAP employs a \emph{chequebook} smart contract:} \begin{itemize} \item<4-> cheques are passed between connected swarm nodes (peers) off-chain. \item<4-> peers can cash in (process on-chain) the received cheques at any time. \item<4-> issued cheques are \emph{cumulative}, i.e., \textbf{only the last cheque needs to be cashed for settlement}. \end{itemize} \uncover<5>{\textsc{swap} will soon also be usable via \emph{payment channels} (see Raiden).} \end{frame} \begin{frame}{chequebook vs payment channel} \begin{overlayarea}{\textwidth}{5.2cm} \setbeamercovered{transparent}% Dim out "inactive" elements \begin{columns}[t] \column{0.5\textwidth} \begin{block}{chequebook} \textbf{pro:} \begin{itemize} \item<1>{offchain payments} \item<2>{low barrier to entry (pay anyone)} \end{itemize} \textbf{con:} \begin{itemize} \item<3>{cheques can bounce (payment not guaranteed)} \end{itemize} \end{block} \column{0.5\textwidth} \begin{block}{channel} \textbf{pro:} \begin{itemize} \item<1>{offchain payments} \item<3>{secure - payments guaranteed} \end{itemize} \textbf{con:} \begin{itemize} \item<2>{high barrier to entry (must first join channel network)} \end{itemize} \end{block} \end{columns} \end{overlayarea} \end{frame} \begin{frame} \begin{block}{SWARM + SWAP demonstrates} \begin{itemize} \item programmable incentives \item drive towards low latency retrieval \item auto-scaling delivery network \end{itemize} \end{block} \end{frame} \begin{frame}{swarm CDN is auto-scaling} \begin{tikzpicture} \node[peer,visible on=<1->] at (12,0) (retriever){}; \node[visible on=<1->] (chunk) at (4,-5) {$\bullet$}; \node[visible on=<1->] (chunklabel) at (3,-4) {data address} edge[point,->,visible on =<1->] (chunk); \node[node,visible on=<2->,] at (8.5,-0.5) (connectedpeer){} (retriever.-150) edge[point, ->,visible on=<4-8>, bend left=15] node[below=2pt,visible on=<4>] {request} (connectedpeer.-10); \node[node,visible on=<2->] at (6,-2) (firstnode){} (connectedpeer.-70) edge[point,->,visible on=<4-7>,bend left=30] node[right of=2pt,visible on=<4>] {request} (firstnode.east); \node[node,visible on=<2->] at (7.5,-4.5) (secondnode){} (firstnode.-70) edge[point,->,dashed,visible on=<4-6>,bend left=10] node[right of=2pt,visible on=<4>] {requests...} (secondnode.120); \node[peer,visible on=<2->] at (4,-6) (closestnode){} (secondnode.-110) edge[point,->,visible on=<4-5>,out=-110,in=0] node[right of=2pt,visible on=<4>] {request} (closestnode.east) (closestnode) edge[thick,point,->,visible on=<5>] (secondnode) (secondnode.north west) edge[thick, point,->,visible on=<6>, dashed] (firstnode.-120) (firstnode.55) edge[thick,point,->,visible on=<7>] (connectedpeer.-150) (connectedpeer) edge[thick,point,->,visible on=<8>] (retriever) ; \node[chunk, scale=0.6,visible on=<3->, below=3pt of closestnode.-50] {}; \node[chunk, scale=0.6,visible on=<5->, below=3pt of secondnode.-50] {}; \node[chunk, scale=0.6,visible on=<6-9>, below=3pt of firstnode.-50] {}; \node[chunk, scale=0.6,visible on=<7-9>, below=3pt of connectedpeer.-50] {}; \node[chunk, scale=0.6,visible on=<8->, below=3pt of retriever.-50] {}; \node[peer, visible on=<11->] at (12,-6) (newguy){}; \node[node, visible on=<11->] at (11,-4) (newnode){} (newguy) edge[point,->,visible on=<12-15>,dashed,bend left=20] (newnode) (newnode) edge[point,->,visible on=<13-14>,bend left=20] (secondnode) ; \node[chunk, scale=0.6,visible on=<14->, below=3pt of newnode.-50] {} (secondnode) edge[thick,point,->,visible on=<14>] (newnode); \node[chunk, scale=0.6,visible on=<15->, below=3pt of newguy.-50] {} (newnode) edge[thick,point,->,visible on=<15>] (newguy); \node[visible on=<16>,scale=4] at (3,-1) {\Smiley}; \end{tikzpicture} \end{frame} \end{section} \begin{section}{content storage} \subsection[pay-as-you-store]{deferred payments and proof-of-custody} \begin{frame}{} SWAP allows for speedy retrieval of \emph{popular content}, but there is \textbf{no guarantee that less popular content will remain available}. Whatever is not accessed for a long time is likely to be deleted.\\[5mm] The first step: change the swarm's incentives by \textbf{paying nodes to store your content}. \end{frame} \begin{frame}{payment for proof-of-custody} The basic idea: \begin{enumerate} \item commit in advance to paying for data to be available in the swarm. \item over time, challenge the swarm to provide proof that the data is still available: request \emph{proof-of-custody}. \item every valid proof-of-custody releases the next payment installment to the storing nodes. \end{enumerate} \begin{block}{Remember:} The \textbf{proof-of-custody} here is a small message - a single hash - which cryptographically proves that the issuer has access to the data. \end{block} \end{frame} \begin{frame}{proof of custody + payment channel} These deferred payments constitute a \textbf{conditional escrow}: payment is made up-front, payment is held (escrow) and is only released when a valid proof-of-custody is received (condition).\\[5mm] This procedure can be handled off-chain and can be directly \textbf{integrated into the payment channels.} All you need is a payment-channel \emph{judge contract} that can understand swarm storage receipts. \end{frame} \subsection[insurance]{storage insurance and negative incentives} \begin{frame}{If data goes missing...} If data goes missing nodes will lose potential revenue for no longer being able to generate proofs-of-custody, but there are \emph{no further consequences} (yet). \\[5mm] Therefore, to complete the storage incentive scheme, we introduce an \emph{insurance system} the can \textbf{punish offending nodes for not keeping their storage promises}. \end{frame} \plainblockslide{}{\textsc{swear}: \textbf{sw}arm \textbf{e}nforcement of \textbf{a}rchiving \textbf{r}ules} \begin{frame}{\textsc{swear} to store} SWEAR is a smart contract that allows nodes to register as long-term storage nodes by posting a \textbf{security deposit}.\\[5mm] Registered nodes can sell promissory notes guaranteeing long-term data availablilty -- essentially insurance against deleting. \\[5mm] Implementation: swarm syncing process with added receipts. \end{frame} \begin{frame}{the syncing process} \begin{columns}[T] \begin{column}{0.4\textwidth} \only<1-10>{ \begin{block}{syncing} \begin{itemize} \item<3-> chunks to be stored at the nodes whose address is closest to the chunk ID \item<5-> relaying: syncing \item<7-> data is passed on from node to node % \item<10->[] %dummy. I needed this to get line spacing to work in the point above. \end{itemize} \end{block} } \uncover<11>{\frametitle{insured upload to swarm}} \only<11->{ \begin{block}{insured storage} syncing via registered nodes with each swap receipted. \end{block} \begin{block}{insured storage:} \begin{itemize} \item owner passes data to a registered peer and receives an insurance receipt \item relaying: syncing \item all receipts are accounted and paid for \end{itemize} \end{block} } \end{column} \begin{column}{0.6\textwidth} \begin{tikzpicture} \node[scale=0.7,visible on=<1-10>] at (0,0) { \begin{tikzpicture} \node[invisible] at (0,-9) (dummy){}; \node[invisible] at (5,-5) (dummy2){}; \node[peer,visible on=<2->] at (-2,0) (owner){owner}; \node[visible on=<3->] (chunk) at (4,-5) {$\bullet$}; \node[visible on=<3->] (chunklabel) at (5,-4) {chunk address} edge[point,->,visible on =<3->] (chunk); \node[peer,visible on=<5->] at (0.5,-0.5) (connectedpeer){peer} (owner.east) edge[point, ->,visible on=<6->, bend left=15] node[above=2pt,visible on=<6->] {sync} (connectedpeer.150); \node[node,visible on=<7->] at (1,-2) (firstnode){some node} (connectedpeer.-70) edge[point,->,visible on=<7->,bend left=10] node[right of=2pt,visible on=<7->] {sync} (firstnode.north); \node[node,visible on=<8->] at (0.5,-4.5) (secondnode){other node} (firstnode.-70) edge[point,->,dashed,visible on=<8->,bend left=10] node[right of=2pt,visible on=<8->] {syncing...} (secondnode.70); \node[peer,visible on=<4->] at (4,-6) (closestnode){closest node} (secondnode.-110) edge[point,->,visible on=<9->,out=-110,in=180] node[above=2pt,visible on=<9->] {sync} (closestnode.west); \end{tikzpicture} }; \node[scale=0.7,visible on=<12->] at (0,0) { \begin{tikzpicture} \node[invisible] at (0,-9) (dummy){}; \node[invisible] at (5,-5) (dummy2){}; \node[peer,visible on=<11->] at (-2,0) (owner){owner}; \node[visible on=<12->] (chunk) at (4,-5) {$\bullet$}; \node[visible on=<12->] (chunklabel) at (5,-4) {chunk address} edge[point,->,visible on =<11->] (chunk); \node[peer,visible on=<12->] at (0.5,-0.5) (connectedpeer){peer} (owner.east) edge[point, ->,visible on=<12->, bend left=15] node[above=2pt,visible on=<12->] {store} (connectedpeer.150) (connectedpeer.-170) edge[point,->,visible on=<12->,thick,bend right=15] (owner.-20); \node[node,visible on=<12->] at (1,-2) (firstnode){some node} (connectedpeer.-70) edge[point,->,visible on=<12->,bend left=10] node[right of=2pt,visible on=<12->] {store} (firstnode.north) (firstnode.140) edge[point,->,visible on=<12->,thick,bend right=10] node[left of=2pt,visible on=<12->] {receipts} (connectedpeer.-140); \node[node,visible on=<12->] at (0.5,-4.5) (secondnode){other node} (firstnode.-70) edge[point,->,dashed,visible on=<12->,bend left=10] node[right of=2pt,visible on=<12->] {store...} (secondnode.70) (secondnode.110) edge[point,->,visible on=<12->,dashed,thick,bend right=10] node[left of=2pt,visible on=<12->] {receipts} (firstnode.-110); \node[peer,visible on=<12->] at (4,-6) (closestnode){closest node} (secondnode.-110) edge[point,->,visible on=<12->,out=-110,in=180] node[above=2pt,visible on=<12->] {store} (closestnode.west) (closestnode.-160) edge[point,->,visible on=<12->,thick,out=180,in=-110] node[left of=2pt,visible on=<12->] {receipt} (secondnode.-130); \end{tikzpicture} }; \end{tikzpicture} \end{column} \end{columns} \end{frame} \plainblockslide{}{\textsc{swindle}: \textbf{s}torage \textbf{w}ith \textbf{in}surance \textbf{d}eposit, \textbf{l}itigation and \textbf{e}scrow } \blockslide[\textsc{swindle}]{TL;DR}{if insured data is lost, the storers lose their deposit} \begin{frame}{litigation upon data loss} \begin{block}{if insured data is not found} %If insured data is lost, anyone holding a valid receipt can launch the litigation procedure.\\ %A node so challenged may defend itself by presenting litigation by challenge \end{block} \begin{block}{defense by providing} \begin{itemize} \item proof-of-custody of the data (eventually the data itself) \item a storage receipt for the data, shifting the blame and implicating another node as the culprit. \end{itemize} \end{block} \begin{block}{upload and disappear} \begin{itemize} \item swear to sync and receipting $\rightarrow$ immediate settlement with the peer at upload \item finger-pointing along chain of receipts $\rightarrow$ correct accountability of storer thereafter \end{itemize} \end{block} %Only at the time of litigation is the chain from owner to storer explicitly determined. %This is an important feature -- litigation may take time but initial storage can be fast allowing you to `upload and disappear'. \end{frame} \begin{frame} \begin{center} \textsc{ swap $\bullet$ swear $\bullet$ swindle } \end{center} \end{frame} \begin{frame}{ethersphere orange paper series} \begin{block}{} Viktor Trón, Aron Fischer, Dániel Nagy A and Zsolt Felföldi, Nick Johnson: swap, swear and swindle: incentive system for swarm. May 2016 \end{block} \begin{block}{} Viktor Trón, Aron Fischer, Nick Johnson: smash-proof: auditable storage for swarm secured by masked audit secret hash. May 2016 \end{block} \end{frame} \end{section} \begin{frame}{swarm: status and usage} \begin{block}{what is the development status of swarm?} \begin{enumerate} \item golang implementation: proof-of-concept iteration 2 release 4, code has been merged to go-ethereum develop branch \item Microsoft Azure hosting a testnet of 100+ nodes over 3 regions \item expanding team, come join or contribute \end{enumerate} \end{block} \begin{block}{how can swarm be used?} \begin{itemize} \item \texttt{bzzd} - swarm daemon, communicates with ethereum via IPC, so any ethereum client works \item APIs: JSON RPC (via websockets, http, or ipc), http proxy, cli, fuse driver (planned) \item API bindings: web3.js and CLI \end{itemize} \end{block} \end{frame} \begin{frame}[plain]{join us} \begin{block}<1->{contact and contribute} \begin{description} \item[swarm channel:] \texttt{gitter.im/ethereum/swarm} \item[swarm info page \& orange papers:] \texttt{swarm-gateways.net} \item[swarm gateway:] \texttt{swarm-gateways.net} \texttt{web3.download} \end{description} \end{block} \begin{block}{} \begin{itemize} \footnotesize \item Daniel Nagy A., Nick Johnson, Viktor Trón, Zsolt Felföldi (core team) \item Aron Fischer \& Ethersphere orange lounge group \item Ram Devish, Bas van Kervel, Alex van der Sande (Mist integration) \item Felix Lange (integration, devp2p) \item Alex Beregszaszi (git, mango) \item Igor Shadurin (file manager dapp) \item Nick Johnson, Alex van der Sande (Ethereum Name Service) \item Gavin Wood, Vitalik Buterin, Jeffrey Wilcke (visionaries) \end{itemize} \end{block} \end{frame} \end{document}
The empty set is collinear.
The 1932 NFL season was the 13th regular season of the National Football League. The Boston Braves (the current Washington Redskins) joined the NFL before the season, whereas the loss of the Providence Steam Roller, Cleveland Indians and Frankford Yellow Jackets dropped league membership to eight teams, the lowest in NFL history; the league also had eight teams in 1943 due to World War II. Although the Green Bay Packers finished the season with 10 wins, the league title was determined at the time by winning percentage with ties excluded, so the Portsmouth Spartans and the Chicago Bears finished the season tied for first place (6–1). Since both games between the teams ended in ties, the NFL arranged for the first ever playoff game to determine the NFL champion. Extremely cold weather forced the game to be moved from Wrigley Field to the indoor Chicago Stadium. The makeshift football field in the stadium was only 80 yards long with undersized endzones, forcing officials to move the goal posts to the goal line due to a lack of space to put them at the back of the end zone, as was standard in college and professional football. This change was favored by players and fans, and the goal posts were moved to the goal line as one of several rule changes the league made in 1933, with the rule lasting until 1973. The Bears won the playoff game 9–0, which was scoreless until the fourth quarter, and as the game counted in the final standings, the Spartans finished in third place. The Spartans became the Detroit Lions in 1934. Because the Portsmouth Spartans and the Chicago Bears finished the season tied for first place, a playoff game was held to determine the NFL champion. The league decreased to eight teams in 1932. Following the 1932 season, the NFL would be split into two divisions (later two conferences), with the champions of each meeting in a championship game. This was the result of the end of the 1932 season, where there was a tie for first in the standings at the end of the regular season: as tied games did not count until 1972, the Spartans record of 6–1–4 and the Bears record of 6–1–6 were taken to be six wins, one loss, giving both an .857 win percentage. Had pure win-loss differential or the current (post-1972) system of counting ties as half a win, half a loss been in place in 1932, the Packers' record of 10–3–1 (.750, +7) would have won them a fourth consecutive championship, ahead of the Spartans' 6–1–4 (.727, +5) and the Bears' 6–1–6 (.692, +5). The Green Bay Packers were unbeaten (8–0–1) after nine games, and after the Thanksgiving weekend, their 10–1–1 record (.909) was still well ahead of Portsmouth at 5–1–4 (.833) and Chicago at 4–1–6 (.800). In Week Twelve (December 4), the Spartans handed the Packers a 19–0 defeat, while the Bears beat the Giants 6–0. Portsmouth, at 6–1–4 (.857), took the lead, while the Packers (10–2–1) and the Bears (5–1–6) were tied for second (.833). In Week Thirteen, the Bears hosted the Packers; a Green Bay win would have the Packers finish second with an 11–2–1 record (.846) and hand Portsmouth their first ever title. The Bears beat the Packers 9–0, meaning they finished 6–1–6, and tied for first in the standings with Portsmouth. Though it was described as a "playoff", the Bears 9–0 win over Portsmouth on December 18 counted in the regular season standings. As such, the Bears finished at 7–1–6 (.875) and won the 1932 title, with the Packers runners-up, and the Spartans, at 6–2–4 (.750), finished third. Kenneth "Ken" R. Wendt (January 29, 1910 – January 19, 1982) was an American football player, jurist, and politician. Wendt was a guard for the Chicago Cardinals of the National Football League in 1932. He then served in the Illinois General Assembly and as a judge in Cook County, Illinois. The National Football League champions, prior to the merger between the National Football League (NFL) and American Football League (AFL) in 1970, were determined by two different systems. The National Football League was established on September 17, 1920, as the American Professional Football Association (APFA). The APFA changed its name in 1922 to the National Football League, which it has retained ever since.From 1921 to 1931, the APFA/NFL determined its champion by overall win–loss record, with no playoff games; ties were not counted in the winning percentage total. The APFA did not keep records of the 1920 season; they declared the Akron Pros, who finished the season with an 8–0–3 (8 wins, 0 losses, 3 ties) record, as the league's first champions, by a vote of the owners, with the Buffalo-All Americans and Decatur Staleys also claiming the title. According to modern-tie breaking rules, the Buffalo All-Americans tied Akron for the championship. The Canton Bulldogs won two straight championships from 1922 to 1923, and the Green Bay Packers won three in a row from 1929 to 1931.There also has been controversy over the championshipships of the 1921 APFA season and the 1925 NFL season, with the Buffalo All-Americans laying claim to another championship in an incident known as the "Staley Swindle" and the Pottsville Maroons being stripped of their championship in 1925 for playing an exhibition game against college football powerhouse Notre Dame's famed Four Horsemen, leading to a last minute field goal victory for the Maroons, stunning the crowd and nation, and also put the NFL ahead of college football for the first time ever. These three disputed championships contributed to the beginning of the NFL's rich history. The 1932 NFL season resulted in a tie for first place between the Chicago Bears and Portsmouth Spartans, and could not be resolved by the typical win–loss system. To settle the tie, a playoff game was played; Chicago won the game and the championship. The following year, the NFL split into two divisions, and the winner of each division would play in the NFL Championship Game. In 1967, the NFL and the rival AFL agreed to merge, effective following the 1969 season; as part of this deal, the NFL champion from 1966 to 1969 would play the AFL champion in an AFL–NFL World Championship Game in each of the four seasons before the completed merger. The NFL Championship Game was ended after the 1969 season, succeeded by the NFC Championship Game. The champions of that game play the champions of the AFC Championship Game in the Super Bowl to determine the NFL champion.The Green Bay Packers won the most NFL championships before the merger, winning eleven of the fifty championships. The Packers were also the only team to win three straight championships, an achievement they accomplished twice: from 1929–31 and from 1965–67. The Chicago Bears won a total of eight titles, and the Cleveland Browns, Detroit Lions, and New York Giants each won four. The Bears recorded the largest victory in a championship game, defeating the Washington Redskins 73–0 in the 1940 NFL Championship Game; six other title games ended in a shutout as well. The Philadelphia Eagles recorded two consecutive shutouts in 1948 and 1949. New York City hosted the most championship games (eight), while the highest-attended title game was the 1955 NFL Championship Game, where 85,693 fans showed up in Los Angeles to watch the Browns beat the Rams 38–14. Staten Island () is one of the five boroughs of New York City, in the U.S. state of New York. Located in the southwest portion of the city, the borough is separated from New Jersey by the Arthur Kill and the Kill Van Kull and from the rest of New York by New York Bay. With an estimated population of 479,458 in 2017, Staten Island is the least populated of the boroughs but is the third-largest in land area at 58.5 sq mi (152 km2). The borough also contains the southern-most point in the state, South Point. The borough is coextensive with Richmond County and until 1975 was referred to as the Borough of Richmond. Staten Island has sometimes been called "the forgotten borough" by inhabitants who feel neglected by the city government.The North Shore—especially the neighborhoods of St. George, Tompkinsville, Clifton and Stapleton—is the most urban part of the island; it contains the designated St. George Historic District and the St. Paul's Avenue-Stapleton Heights Historic District, which feature large Victorian houses. The East Shore is home to the 2.5-mile (4 km) F.D.R. Boardwalk, the fourth-longest boardwalk in the world. The South Shore, site of the 17th-century Dutch and French Huguenot settlement, developed rapidly beginning in the 1960s and 1970s and is now mostly suburban in character. The West Shore is the least populated and most industrial part of the island.
function bc = specific_bc(xbd,ybd) %backwardstep_bc Reference problem 5.2 boundary condition % bc = specific_bc(xbd,ybd); % input % xbd x boundary coordinate vector % ybd y boundary coordinate vector % % specifies streamfunction associated with Backward step flow % IFISS function: DJS; 6 March 2005. % Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage bc=0*xbd; k=find(xbd==-1); bc(k)=2*ybd(k).*ybd(k).*(1-2*ybd(k)/3); k=find(ybd==1); bc(k)=2/3; return
```python import sympy from sympy import * print(sympy.__version__) init_printing(use_unicode=True) ``` 0.7.6.1 ```python from sympy import S, Eq, solve m, mt, k, a, b = symbols('m mt k a b') equations = [ ... Eq(vf, vi+a*t), ... Eq(d, vi*t + a*t**2/2), ... Eq(a, 10), ... Eq(d, 60), ... Eq(vi, 5)] p = m**2/k**2 E = a*sinh(b*m) pd = 2*m/k**2 Ed = a*b*cosh(b*m) sols = solve([E, Ed], [p, pd]) print("p = {}".format((sols[].factor())) ``` ```python solve([Eq(a*sinh(b*1), 1**2/1**2)], [a, b]) ``` ```python solve([Eq(a*b*cosh(b*1), 2*1/0.4**2)], [a,b]) ``` ```python solve([Eq(a*sinh(b*0.3), 0.3**2/1**2), Eq(a*b*cosh(b*0.3), 2*0.3/1**2)], [a, b]) ``` ```python solve(Eq(a*sinh(b*x)), x) ``` ```python ```
If $f$ is holomorphic on an open set $S$, then the $n$th derivative of $-f$ is $-f^{(n)}$.
module Photo import Objects.Size public export record Photo where constructor CreatePhoto id : Integer albumID : Integer ownerID : Integer userID : Integer text : String date : Integer size : Maybe $ List Size.Size photo75 : String photo130 : String photo604 : String photo807 : String photo1280 : String photo2560 : String width : Integer heoght : Integer
lemma decseq_emeasure: assumes "range B \<subseteq> sets M" "decseq B" shows "decseq (\<lambda>i. emeasure M (B i))"
lemma filtermap_at_shift: "filtermap (\<lambda>x. x - d) (at a) = at (a - d)" for a d :: "'a::real_normed_vector"
[STATEMENT] lemma integrable_neg_iff: "(\<lambda>x. -f(x)) integrable_on S \<longleftrightarrow> f integrable_on S" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((\<lambda>x. - f x) integrable_on S) = (f integrable_on S) [PROOF STEP] using integrable_neg [PROOF STATE] proof (prove) using this: ?f integrable_on ?S \<Longrightarrow> (\<lambda>x. - ?f x) integrable_on ?S goal (1 subgoal): 1. ((\<lambda>x. - f x) integrable_on S) = (f integrable_on S) [PROOF STEP] by fastforce
# PIT Summary # Purpose There has been a lot done in the parameter identification techniques (PIT) in this project, this notebook is a summary. # Setup ```python # %load imports.py # %load imports.py %matplotlib inline %load_ext autoreload %autoreload 2 %config Completer.use_jedi = False ## (To fix autocomplete) ## External packages: import pandas as pd pd.options.display.max_rows = 999 pd.options.display.max_columns = 999 pd.set_option("display.max_columns", None) import numpy as np import os import matplotlib.pyplot as plt #if os.name == 'nt': # plt.style.use('presentation.mplstyle') # Windows import plotly.express as px import plotly.graph_objects as go import seaborn as sns import sympy as sp from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Particle, Point) from sympy.physics.vector.printing import vpprint, vlatex from IPython.display import display, Math, Latex from src.substitute_dynamic_symbols import run, lambdify #import pyro import sklearn import pykalman from statsmodels.sandbox.regression.predstd import wls_prediction_std import statsmodels.api as sm from scipy.integrate import solve_ivp ## Local packages: from src.data import mdl #import src.models.nonlinear_martin_vmm as vmm #import src.nonlinear_martin_vmm_equations as eq #import src.models.linear_vmm as vmm import src.linear_vmm_equations as eq #import src.models.linear_vmm as model from src.symbols import * from src.parameters import * import src.symbols as symbols from src import prime_system from src.models import regression from src.visualization.plot import track_plot from src.equation import Equation ``` ```python Math(vlatex(eq.X_eq)) ``` ```python Math(vlatex(eq.Y_eq)) ``` ```python Math(vlatex(eq.N_eq)) ``` ```python Math(vlatex(eq.X_eq.rhs-eq.X_eq.lhs)) ``` ```python Math(vlatex(eq.Y_eq.rhs-eq.Y_eq.lhs)) ``` ```python Math(vlatex(eq.N_eq.rhs-eq.N_eq.lhs)) ``` ## Load test ```python #id=22773 #id=22616 id=22774 #id=22770 df, units, meta_data = mdl.load(id=id, dir_path='../data/processed/kalman') df.index = df.index.total_seconds() df = df.iloc[0:-100].copy() df.index-=df.index[0] df['t'] = df.index df.sort_index(inplace=True) df['-delta'] = -df['delta'] df['V'] = np.sqrt(df['u']**2 + df['v']**2) df['thrust'] = df['Prop/PS/Thrust'] + df['Prop/SB/Thrust'] df['U'] = df['V'] df['beta'] = -np.arctan2(df['v'],df['u']) ``` ```python meta_data['rho']=1000 meta_data['mass'] = meta_data['Volume']*meta_data['rho'] ``` ```python from src.visualization.plot import track_plot fig,ax=plt.subplots() #fig.set_size_inches(10,10) track_plot(df=df, lpp=meta_data.lpp, x_dataset='x0', y_dataset='y0', psi_dataset='psi', beam=meta_data.beam, ax=ax); df.plot(y='u') ``` # Ship parameters ```python T_ = (meta_data.TA + meta_data.TF)/2 L_ = meta_data.lpp m_ = meta_data.mass rho_ = meta_data.rho B_ = meta_data.beam CB_ = m_/(T_*B_*L_*rho_) I_z_ = m_*meta_data.KZZ**2 #I_z_=839.725 ship_parameters = { 'T' : T_, 'L' : L_, 'CB' :CB_, 'B' : B_, 'rho' : rho_, #'x_G' : meta_data.lcg, # motions are expressed at CG 'x_G' : 0, # motions are expressed at CG 'm' : m_, 'I_z': I_z_, 'volume':meta_data.Volume, } ps = prime_system.PrimeSystem(**ship_parameters) # model scale_factor = meta_data.scale_factor ps_ship = prime_system.PrimeSystem(L=ship_parameters['L']*scale_factor, rho=meta_data['rho']) # ship ship_parameters_prime = ps.prime(ship_parameters) ``` ```python I_z_+m_*meta_data.lcg**2 # Steiner rule... ``` ```python I_z_ ``` ```python ship_parameters ``` ```python ship_parameters_prime ``` ## Prime system ```python interesting = ['x0','y0','psi','u','v','r','u1d','v1d','r1d','U','t','delta','thrust','beta'] df_prime = ps.prime(df[interesting], U=df['U']) df_prime.set_index('t', inplace=True) ``` ```python fig,ax=plt.subplots() #fig.set_size_inches(10,10) track_plot(df=df_prime, lpp=ship_parameters_prime['L'], beam=ship_parameters_prime['B'], x_dataset='x0', y_dataset='y0', psi_dataset='psi', ax=ax); df_prime.plot(y='u') ``` ```python df.index ``` ```python df_prime.index ``` ```python t_ = np.array([0,1,2]) U_ = np.array([1,2,2]) t_prime = ps._prime(t_, unit='time', U=U_) t_prime ``` ```python ps._unprime(t_prime, unit='time', U=U_) ``` # Brix parameters ```python def calculate_prime(row, ship_parameters): return run(function=row['brix_lambda'], inputs=ship_parameters) mask = df_parameters['brix_lambda'].notnull() df_parameters.loc[mask,'brix_prime'] = df_parameters.loc[mask].apply(calculate_prime, ship_parameters=ship_parameters, axis=1) df_parameters.loc['Ydelta','brix_prime'] = 0.0004 # Just guessing df_parameters.loc['Ndelta','brix_prime'] = -df_parameters.loc['Ydelta','brix_prime']/4 # Just guessing df_parameters['brix_prime'].fillna(0, inplace=True) #df_parameters['brix_SI'].fillna(0, inplace=True) ``` ## Simulate with Brix ```python X_eq = eq.X_eq.copy() Y_eq = eq.Y_eq.copy() N_eq = eq.N_eq.copy() subs=[ #(x_G,0), (eq.p.Xvdot,0), (eq.p.Xrdot,0), (eq.p.Yudot,0), (eq.p.Yrdot,0), (eq.p.Nudot,0), (eq.p.Nvdot,0), ] X_eq = X_eq.subs(subs) Y_eq = Y_eq.subs(subs) N_eq = N_eq.subs(subs) eqs = [X_eq, Y_eq, N_eq] solution = sp.solve(eqs, u1d, v1d, r1d, dict=True) ## Decouple the equations: u1d_eq = sp.Eq(u1d, solution[0][u1d]) v1d_eq = sp.Eq(v1d, solution[0][v1d]) r1d_eq = sp.Eq(r1d, solution[0][r1d]) ## Lambdify: subs = {value:key for key,value in eq.p.items()} u1d_lambda = lambdify(u1d_eq.subs(subs).rhs) v1d_lambda = lambdify(v1d_eq.subs(subs).rhs) r1d_lambda = lambdify(r1d_eq.subs(subs).rhs) ``` ```python from scipy.spatial.transform import Rotation as R def step(t, states, parameters, ship_parameters, control): u,v,r,x0,y0,psi = states states_dict = { 'u':u, 'v':v, 'r':r, 'x0':x0, 'y0':y0, 'psi':psi, } inputs = dict(parameters) inputs.update(ship_parameters) inputs.update(states_dict) if isinstance(control, pd.DataFrame): index = np.argmin(np.array(np.abs(control.index - t))) control_ = dict(control.iloc[index]) else: control_ = control inputs.update(control_) inputs['U'] = np.sqrt(u**2 + v**2) #Instantanious velocity u1d = run(function=u1d_lambda, inputs=inputs) v1d = run(function=v1d_lambda, inputs=inputs) r1d = run(function=r1d_lambda, inputs=inputs) rotation = R.from_euler('z', psi, degrees=False) w = 0 velocities = rotation.apply([u,v,w]) x01d = velocities[0] y01d = velocities[1] psi1d = r dstates = [ u1d, v1d, r1d, x01d, y01d, psi1d, ] return dstates ``` ```python fig,ax=plt.subplots() df_prime.plot(y='delta', ax=ax) df_cut_prime = df_prime.iloc[2000:12000] df_cut_prime.plot(y='delta', ax=ax, style='--', label='cut') ``` ```python def simulate(df_, parameters, ship_parameters): t = df_.index t_span = [t.min(),t.max()] t_eval = np.linspace(t.min(),t.max(),len(t)) #control = df_[['delta','thrust']] control = { 'delta': df_[['delta']].mean() } df_0 = df_.iloc[0:100].median(axis=0) y0 = { 'u' : df_0['u'], 'v' : df_0['v'], 'r' : df_0['r'], 'x0' : df_0['x0'], 'y0' : df_0['y0'], 'psi' : df_0['psi'] } solution = solve_ivp(fun=step, t_span=t_span, y0=list(y0.values()), t_eval=t_eval, args=(parameters, ship_parameters, control)) columns = list(y0.keys()) df_result = pd.DataFrame(data=solution.y.T, columns=columns) df_result.index=t[0:len(df_result)] df_result['beta'] = -np.arctan2(df_result['v'],df_result['u']) return solution, df_result ``` ```python solution, df_result_brix = simulate(df_cut_prime, parameters = df_parameters['brix_prime'], ship_parameters=ship_parameters_prime) ``` ```python fig,ax=plt.subplots() track_plot(df=df_cut_prime, lpp=ship_parameters_prime['L'], beam=ship_parameters_prime['B'],ax=ax, label='model test') track_plot(df=df_result_brix, lpp=ship_parameters_prime['L'], beam=ship_parameters_prime['B'],ax=ax, label='simulation', color='green') ax.legend() for key in df_result_brix: fig,ax = plt.subplots() df_cut_prime.plot(y=key, label='model test', ax=ax) df_result_brix.plot(y=key, label='simulation', ax=ax) ax.set_ylabel(key) ``` ## Back to SI ```python fig,ax=plt.subplots() ax.plot(df.index,df_prime.index) ``` ```python U_ = ship_parameters['L']*df_prime.index/df.index df_unprime = ps.unprime(df_prime, U=U_) df_unprime.index = ps._unprime(df_prime.index,unit='time',U=U_) ``` ```python fig,ax=plt.subplots() #fig.set_size_inches(10,10) track_plot(df=df, lpp=meta_data.lpp, x_dataset='x0', y_dataset='y0', psi_dataset='psi', beam=meta_data.beam, ax=ax); track_plot(df=df_unprime, lpp=meta_data.lpp, x_dataset='x0', y_dataset='y0', psi_dataset='psi', beam=meta_data.beam, ax=ax); fig,ax=plt.subplots() df.plot(y='u',ax=ax) df_unprime.plot(y='u', style='--', ax=ax) fig,ax=plt.subplots() df.plot(y='v',ax=ax) df_unprime.plot(y='v', style='--', ax=ax) ``` # VCT regression ## Load VCT data ```python df_VCT_all = pd.read_csv('../data/external/vct.csv', index_col=0) df_VCT_all.head() ``` ```python df_VCT = df_VCT_all.groupby(by=['model_name']).get_group('V2_5_MDL_modelScale') ``` ```python df_VCT['test type'].unique() ``` # Subtract the resistance ```python df_resistance = df_VCT.groupby(by='test type').get_group('resistance') X = df_resistance[['u','fx']].copy() X['u**2'] = X['u']**2 y = X.pop('fx') model_resistance = sm.OLS(y,X) results_resistance = model_resistance.fit() X_pred = pd.DataFrame() X_pred['u'] = np.linspace(X['u'].min(), X['u'].max(), 20) X_pred['u**2'] = X_pred['u']**2 X_pred['fx'] = results_resistance.predict(X_pred) fig,ax=plt.subplots() df_resistance.plot(x='u', y='fx', style='.', ax=ax) X_pred.plot(x='u', y='fx', style='--', ax=ax); ``` ```python df_VCT_0_resistance = df_VCT.copy() df_VCT_0_resistance['u**2'] = df_VCT_0_resistance['u']**2 df_VCT_0_resistance['fx']-= results_resistance.predict(df_VCT_0_resistance[['u','u**2']]) ``` ## VCT to prime system ```python interesting = [ 'u', 'v', 'r', 'delta', 'fx', 'fy', 'mz', 'thrust', ] df_VCT_prime = ps_ship.prime(df_VCT_0_resistance[interesting], U=df_VCT_0_resistance['V']) ``` ```python from statsmodels.sandbox.regression.predstd import wls_prediction_std def show_pred_vct(X,y,results, label): display(results.summary()) X_ = X.copy() X_['y'] = y X_.sort_values(by='y', inplace=True) y_ = X_.pop('y') y_pred = results.predict(X_) prstd, iv_l, iv_u = wls_prediction_std(results, exog=X_, alpha=0.05) #iv_l*=-1 #iv_u*=-1 fig,ax=plt.subplots() #ax.plot(X_.index,y_, label='Numerical gradient from model test') #ax.plot(X_.index,y_pred, '--', label='OLS') ax.plot(y_,y_pred, '.') ax.plot([y_.min(),y_.max()], [y_.min(),y_.max()], 'r-') ax.set_ylabel(f'{label} (prediction)') ax.set_xlabel(label) ax.fill_between(y_, y1=iv_l, y2=iv_u, zorder=-10, color='grey', alpha=0.5, label=r'5% confidence') ax.legend(); ``` ## N ```python eq.N_qs_eq ``` ```python label = sp.symbols('N_qs') N_eq_ = eq.N_qs_eq.subs(N_qs,label) diff_eq_N = regression.DiffEqToMatrix(ode=N_eq_, label=label, base_features=[delta,u,v,r]) ``` ```python Math(vlatex(diff_eq_N.acceleration_equation)) ``` ```python X = diff_eq_N.calculate_features(data=df_VCT_prime) y = diff_eq_N.calculate_label(y=df_VCT_prime['mz']) model_N = sm.OLS(y,X) results_N = model_N.fit() show_pred_vct(X=X,y=y,results=results_N, label=r'$N$') ``` ## Y ```python eq.Y_qs_eq ``` ```python label = sp.symbols('Y_qs') Y_eq_ = eq.Y_qs_eq.subs(Y_qs,label) diff_eq_Y = regression.DiffEqToMatrix(ode=Y_eq_, label=label, base_features=[delta,u,v,r]) ``` ```python Math(vlatex(diff_eq_Y.acceleration_equation)) ``` ```python X = diff_eq_Y.calculate_features(data=df_VCT_prime) y = diff_eq_Y.calculate_label(y=df_VCT_prime['fy']) model_Y = sm.OLS(y,X) results_Y = model_Y.fit() show_pred_vct(X=X,y=y,results=results_Y, label=r'$Y$') ``` ## X ```python eq.X_qs_eq ``` ```python label = sp.symbols('X_qs') X_eq_ = eq.X_qs_eq.subs(X_qs,label) diff_eq_X = regression.DiffEqToMatrix(ode=X_eq_, label=label, base_features=[delta,u,v,r]) ``` ```python Math(vlatex(diff_eq_X.acceleration_equation)) ``` ```python X = diff_eq_X.calculate_features(data=df_VCT_prime) y = diff_eq_X.calculate_label(y=df_VCT_prime['fx']) model_X = sm.OLS(y,X) results_X = model_X.fit() show_pred_vct(X=X,y=y,results=results_X, label=r'$X$') ``` ```python results_summary_X = regression.results_summary_to_dataframe(results_X) results_summary_Y = regression.results_summary_to_dataframe(results_Y) results_summary_N = regression.results_summary_to_dataframe(results_N) ``` ## Add the regressed parameters Hydrodynamic derivatives that depend on acceleration cannot be obtained from the VCT regression. They are however essential if a time simulation should be conducted. These values have then been taken from Brix semi empirical formulas for the simulations below. ```python df_parameters_all = df_parameters.copy() for other in [results_summary_X, results_summary_Y, results_summary_N]: df_parameters_all = df_parameters_all.combine_first(other) df_parameters_all.rename(columns={'coeff':'regressed'}, inplace=True) df_parameters_all.drop(columns=['brix_lambda'], inplace=True) df_parameters_all['prime'] = df_parameters_all['regressed'].combine_first(df_parameters_all['brix_prime']) # prefer regressed ``` ```python fig,ax=plt.subplots() fig.set_size_inches(15,5) mask = ((df_parameters_all['brix_prime']!=0) | (pd.notnull(df_parameters_all['regressed']))) df_parameters_all_plot = df_parameters_all.loc[mask] df_parameters_all_plot.plot.bar(y=['brix_prime','regressed'], ax=ax); ``` ## Simulate ```python solution, df_result_VCT = simulate(df_cut_prime, parameters = df_parameters_all['prime'], ship_parameters=ship_parameters_prime) ``` ```python fig,ax=plt.subplots() track_plot(df=df_cut_prime, lpp=ship_parameters_prime['L'], beam=ship_parameters_prime['B'],ax=ax, label='model test') track_plot(df=df_result_VCT, lpp=ship_parameters_prime['L'], beam=ship_parameters_prime['B'],ax=ax, label='simulation', color='green') ax.legend() for key in df_result_VCT: fig,ax = plt.subplots() df_cut_prime.plot(y=key, label='model test', ax=ax) df_result_VCT.plot(y=key, label='simulation', ax=ax) ax.set_ylabel(key) ``` # Time series PIT ```python from statsmodels.sandbox.regression.predstd import wls_prediction_std def show_pred(X,y,results, label): display(results.summary()) X_ = X y_ = y y_pred = results.predict(X_) prstd, iv_l, iv_u = wls_prediction_std(results, exog=X_, alpha=0.05) #iv_l*=-1 #iv_u*=-1 fig,ax=plt.subplots() ax.plot(X_.index,y_, label='Numerical gradient from model test') ax.plot(X_.index,y_pred, '--', label='OLS') ax.set_ylabel(label) ax.fill_between(X_.index, y1=iv_l, y2=iv_u, zorder=-10, color='grey', alpha=0.5, label=r'5\% confidence') ax.legend(); ``` ## N ```python N_eq_ = N_eq.copy() N_eq_ = N_eq_.subs([ (x_G,0), # Assuming or moving to CG=0 # #(I_z,1), # Removing inertia # #(eq.p.Nrdot,0), # Removing added mass # #(eq.p.Nvdot,0), # Removing added mass # #(eq.p.Nudot,0), # Removing added mass # ]) solution = sp.solve(N_eq_,r1d)[0] inertia_ = (I_z-eq.p.Nrdot) N_eq_ = sp.Eq(r1d*inertia_, solution*inertia_) ``` ```python Math(vlatex(N_eq_)) ``` ```python label_N = N_eq_.lhs diff_eq_N = regression.DiffEqToMatrix(ode=N_eq_, label=label_N, base_features=[delta,u,v,r]) ``` ```python Math(vlatex(diff_eq_N.acceleration_equation)) ``` ```python Math(vlatex(diff_eq_N.acceleration_equation_x)) ``` ```python Math(vlatex(diff_eq_N.eq_y)) ``` ```python diff_eq_N.eq_beta ``` ```python Math(vlatex(diff_eq_N.eq_X)) ``` ```python diff_eq_N.y_lambda ``` ```python X = diff_eq_N.calculate_features(data=df_prime) y = run(function=diff_eq_N.y_lambda, inputs=df_prime, **ship_parameters_prime, **df_parameters_all['brix_prime']) model_N = sm.OLS(y,X) results_N = model_N.fit() show_pred(X=X,y=y,results=results_N, label=r'$%s$' % vlatex(label_N)) ``` ## Y ```python Y_eq_ = Y_eq.copy() Y_eq_ = Y_eq.subs([ (x_G,0), # Assuming or moving to CG=0 # #(I_z,1), # Removing inertia # #(eq.p.Nrdot,0), # Removing added mass # #(eq.p.Nvdot,0), # Removing added mass # #(eq.p.Nudot,0), # Removing added mass # ]) solution = sp.solve(Y_eq_,v1d)[0] inertia_ = (eq.p.Yvdot-m) Y_eq_ = sp.simplify(sp.Eq(v1d*inertia_-U*m*r, solution*inertia_-U*m*r)) Math(vlatex(Y_eq_)) ``` ```python label_Y = Y_eq_.rhs diff_eq_Y = regression.DiffEqToMatrix(ode=Y_eq_, label=label_Y, base_features=[delta,u,v,r]) ``` ```python X = diff_eq_Y.calculate_features(data=df_prime) y = run(function=diff_eq_Y.y_lambda, inputs=df_prime, **ship_parameters_prime, **df_parameters_all['brix_prime']) model_Y = sm.OLS(y,X) results_Y = model_Y.fit() show_pred(X=X,y=y,results=results_Y, label=r'$%s$' % vlatex(label_Y)) ``` ## X ```python X_eq_ = X_eq.copy() X_eq_ = X_eq_.subs([ (x_G,0), # Assuming or moving to CG=0 # #(I_z,1), # Removing inertia # #(eq.p.Nrdot,0), # Removing added mass # #(eq.p.Nvdot,0), # Removing added mass # #(eq.p.Nudot,0), # Removing added mass # ]) solution = sp.solve(X_eq_,u1d)[0] inertia_ = m-eq.p.Xudot X_eq_ = sp.simplify(sp.Eq(u1d*inertia_, solution*inertia_)) Math(vlatex(X_eq_)) ``` ```python label_X = X_eq_.lhs diff_eq_X = regression.DiffEqToMatrix(ode=X_eq_, label=label_X, base_features=[delta,u,v,r]) ``` ```python X = diff_eq_X.calculate_features(data=df_prime) y = run(function=diff_eq_X.y_lambda, inputs=df_prime, **ship_parameters_prime, **df_parameters_all['brix_prime']) model_X = sm.OLS(y,X) results_X = model_X.fit() show_pred(X=X,y=y,results=results_X, label=r'$%s$' % vlatex(label_X)) ``` ```python results_summary_X = regression.results_summary_to_dataframe(results_X) results_summary_Y = regression.results_summary_to_dataframe(results_Y) results_summary_N = regression.results_summary_to_dataframe(results_N) ``` ## Add regressed parameters ```python results = pd.concat([results_summary_X, results_summary_Y, results_summary_N],axis=0) df_parameters_all['PIT'] = results['coeff'] df_parameters_all['PIT'] = df_parameters_all['PIT'].combine_first(df_parameters_all['brix_prime']) # prefer regressed ``` ```python fig,ax=plt.subplots() fig.set_size_inches(15,5) mask = ((df_parameters_all['brix_prime']!=0) | (pd.notnull(df_parameters_all['regressed'])) | (df_parameters_all['PIT']!=0) ) df_parameters_all_plot = df_parameters_all.loc[mask] df_parameters_all_plot.plot.bar(y=['brix_prime','regressed','PIT'], ax=ax); ``` ## Simulate ```python parameters = df_parameters_all['PIT'].copy() #parameters['Xv']=0 #parameters['Xr']=0 #parameters['Xu']=0 #parameters['Xdelta']=0 #parameters['Nv']*=-1 solution, df_result_PIT = simulate(df_cut_prime, parameters = parameters, ship_parameters=ship_parameters_prime) ``` ```python fig,ax=plt.subplots() track_plot(df=df_cut_prime, lpp=ship_parameters_prime['L'], beam=ship_parameters_prime['B'],ax=ax, label='model test') track_plot(df=df_result_PIT, lpp=ship_parameters_prime['L'], beam=ship_parameters_prime['B'],ax=ax, label='simulation', color='green') ax.legend() for key in df_result_PIT: fig,ax = plt.subplots() df_cut_prime.plot(y=key, label='model test', ax=ax) df_result_PIT.plot(y=key, label='simulation', ax=ax) ax.set_ylabel(key) ``` ```python ```
lemma enum_mono: "i \<le> n \<Longrightarrow> j \<le> n \<Longrightarrow> enum i \<le> enum j \<longleftrightarrow> i \<le> j"
function [success,origScanNum] = segmentationWrapper(cerrPath,fullSessionPath,... containerPath, algorithm, skipMaskExport) % function success =heart(cerrPath,segResultCERRPath,fullSessionPath,deepLabContainerPath) % % This function serves as a wrapper for the all segmentation models % % INPUT: % cerrPath - path to the original CERR file to be segmented % fullSessionPath - path to write temporary segmentation metadata. % deepLabContainerPath - path to the MR Prostate DeepLab V3+ container on the % algorithm - name of the algorithm to run % skipMaskExport (optional) - Set to false if model requires segmentation % masks as input.Default: true. % % % % RKP, 5/21/2019 % RKP, 9/11/19 Updates for compatibility with training pipeline if ~exist('skipMaskExport','var') skipMaskExport = true; end %Copy config file to session dir configFilePath = fullfile(getCERRPath,'ModelImplementationLibrary',... 'SegmentationModels', 'ModelConfigurations', [algorithm, '_config.json']); copyfile(configFilePath,fullSessionPath); %% Export data to fmt reqd by model cmdFlag = 'singcontainer'; planCfiles = dir(fullfile(cerrPath,'*.mat')); for p=1:length(planCfiles) % Load plan planCfiles(p).name fileNam = fullfile(planCfiles(p).folder,planCfiles(p).name); planC = loadPlanC(fileNam, tempdir); planC = quality_assure_planC(fileNam,planC); %Pre-process data and export to model input fmt [~,command,userOptS,~,scanNumV,planC] = ... prepDataForSeg(planC,fullSessionPath,algorithm,cmdFlag,... containerPath,[],skipMaskExport); %Save updated planC file tic save_planC(planC,[],'PASSED',fileNam); toc end %% Execute the container disp('Running container....'); %Print command to stdout disp(command); tic status = system(command); toc % Run container app to get git_hash gitHash = 'unavailable'; [~,hashChk] = system(['singularity exec ' containerPath ' ls /scif/apps | grep get_hash'],'-echo'); if ~isempty(hashChk) [~,gitHash] = system(['singularity run --app get_hash ' containerPath],'-echo'); end roiDescrpt = ''; if isfield(userOptS,'roiGenerationDescription') roiDescrpt = userOptS.roiGenerationDescription; end roiDescrpt = [roiDescrpt, ' __git_hash:',gitHash]; userOptS.roiGenerationDescription = roiDescrpt; %% Stack output mask files fprintf('\nRreading output masks...'); tic outFmt = userOptS.modelInputFormat; passedScanDim = userOptS.passedScanDim; outC = stackDLMaskFiles(fullSessionPath,outFmt,passedScanDim); toc %% Import segmented mask to planC fprintf('\nImporting to CERR...\n'); tic identifierS = userOptS.structAssocScan.identifier; labelPath = fullfile(fullSessionPath,'outputLabelMap'); if ~isempty(fieldnames(userOptS.structAssocScan.identifier)) origScanNum = getScanNumFromIdentifiers(identifierS,planC); else origScanNum = 1; %Assoc with first scan by default end outScanNum = scanNumV(origScanNum); userOptS.scan(outScanNum) = userOptS.scan(origScanNum); userOptS.scan(outScanNum).origScan = origScanNum; success = joinH5CERR(cerrPath,outC{1},labelPath,outScanNum,userOptS); %Updated toc
#pragma once //#include <gsl/string_span> namespace Util { //static gsl::string_span<> toLower(gsl::string_span<> const&); }; // namespace util
State Before: 𝕜 : Type ?u.36968 ι : Type ?u.36971 κ : Type ?u.36974 α : Type u_1 β : Type u_2 inst✝¹ : LinearOrderedField 𝕜 r : α → β → Prop inst✝ : (a : α) → DecidablePred (r a) s s₁ s₂ : Finset α t t₁ t₂ : Finset β a : α b : β δ : 𝕜 hs : s₂ ⊆ s₁ ht : t₂ ⊆ t₁ hs₂ : Finset.Nonempty s₂ ht₂ : Finset.Nonempty t₂ ⊢ abs (edgeDensity r s₂ t₂ - edgeDensity r s₁ t₁) ≤ 1 - ↑(card s₂) / ↑(card s₁) * (↑(card t₂) / ↑(card t₁)) State After: 𝕜 : Type ?u.36968 ι : Type ?u.36971 κ : Type ?u.36974 α : Type u_1 β : Type u_2 inst✝¹ : LinearOrderedField 𝕜 r : α → β → Prop inst✝ : (a : α) → DecidablePred (r a) s s₁ s₂ : Finset α t t₁ t₂ : Finset β a : α b : β δ : 𝕜 hs : s₂ ⊆ s₁ ht : t₂ ⊆ t₁ hs₂ : Finset.Nonempty s₂ ht₂ : Finset.Nonempty t₂ ⊢ edgeDensity r s₁ t₁ - edgeDensity r s₂ t₂ ≤ 1 - ↑(card s₂) / ↑(card s₁) * (↑(card t₂) / ↑(card t₁)) Tactic: refine' abs_sub_le_iff.2 ⟨edgeDensity_sub_edgeDensity_le_one_sub_mul r hs ht hs₂ ht₂, _⟩ State Before: 𝕜 : Type ?u.36968 ι : Type ?u.36971 κ : Type ?u.36974 α : Type u_1 β : Type u_2 inst✝¹ : LinearOrderedField 𝕜 r : α → β → Prop inst✝ : (a : α) → DecidablePred (r a) s s₁ s₂ : Finset α t t₁ t₂ : Finset β a : α b : β δ : 𝕜 hs : s₂ ⊆ s₁ ht : t₂ ⊆ t₁ hs₂ : Finset.Nonempty s₂ ht₂ : Finset.Nonempty t₂ ⊢ edgeDensity r s₁ t₁ - edgeDensity r s₂ t₂ ≤ 1 - ↑(card s₂) / ↑(card s₁) * (↑(card t₂) / ↑(card t₁)) State After: 𝕜 : Type ?u.36968 ι : Type ?u.36971 κ : Type ?u.36974 α : Type u_1 β : Type u_2 inst✝¹ : LinearOrderedField 𝕜 r : α → β → Prop inst✝ : (a : α) → DecidablePred (r a) s s₁ s₂ : Finset α t t₁ t₂ : Finset β a : α b : β δ : 𝕜 hs : s₂ ⊆ s₁ ht : t₂ ⊆ t₁ hs₂ : Finset.Nonempty s₂ ht₂ : Finset.Nonempty t₂ ⊢ edgeDensity (fun x y => ¬r x y) s₂ t₂ - edgeDensity (fun x y => ¬r x y) s₁ t₁ ≤ 1 - ↑(card s₂) / ↑(card s₁) * (↑(card t₂) / ↑(card t₁)) Tactic: rw [← add_sub_cancel (edgeDensity r s₁ t₁) (edgeDensity (fun x y ↦ ¬r x y) s₁ t₁), ← add_sub_cancel (edgeDensity r s₂ t₂) (edgeDensity (fun x y ↦ ¬r x y) s₂ t₂), edgeDensity_add_edgeDensity_compl _ (hs₂.mono hs) (ht₂.mono ht), edgeDensity_add_edgeDensity_compl _ hs₂ ht₂, sub_sub_sub_cancel_left] State Before: 𝕜 : Type ?u.36968 ι : Type ?u.36971 κ : Type ?u.36974 α : Type u_1 β : Type u_2 inst✝¹ : LinearOrderedField 𝕜 r : α → β → Prop inst✝ : (a : α) → DecidablePred (r a) s s₁ s₂ : Finset α t t₁ t₂ : Finset β a : α b : β δ : 𝕜 hs : s₂ ⊆ s₁ ht : t₂ ⊆ t₁ hs₂ : Finset.Nonempty s₂ ht₂ : Finset.Nonempty t₂ ⊢ edgeDensity (fun x y => ¬r x y) s₂ t₂ - edgeDensity (fun x y => ¬r x y) s₁ t₁ ≤ 1 - ↑(card s₂) / ↑(card s₁) * (↑(card t₂) / ↑(card t₁)) State After: no goals Tactic: exact edgeDensity_sub_edgeDensity_le_one_sub_mul _ hs ht hs₂ ht₂
// Copyright (C) 2006 Douglas Gregor <doug.gregor -at- gmail.com>. // Use, modification and distribution is subject to 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) /** @file status.hpp * * This header defines the class @c status, which reports on the * results of point-to-point communication. */ #ifndef BOOST_MPI_STATUS_HPP #define BOOST_MPI_STATUS_HPP #include <boost/mpi/config.hpp> #include <boost/optional.hpp> namespace boost { namespace mpi { class request; class communicator; /** @brief Contains information about a message that has been or can * be received. * * This structure contains status information about messages that * have been received (with @c communicator::recv) or can be received * (returned from @c communicator::probe or @c * communicator::iprobe). It permits access to the source of the * message, message tag, error code (rarely used), or the number of * elements that have been transmitted. */ class BOOST_MPI_DECL status { public: status() : m_count(-1) { } /** * Retrieve the source of the message. */ int source() const { return m_status.MPI_SOURCE; } /** * Retrieve the message tag. */ int tag() const { return m_status.MPI_TAG; } /** * Retrieve the error code. */ int error() const { return m_status.MPI_ERROR; } /** * Determine whether the communication associated with this object * has been successfully cancelled. */ bool cancelled() const; /** * Determines the number of elements of type @c T contained in the * message. The type @c T must have an associated data type, i.e., * @c is_mpi_datatype<T> must derive @c mpl::true_. In cases where * the type @c T does not match the transmitted type, this routine * will return an empty @c optional<int>. * * @returns the number of @c T elements in the message, if it can be * determined. */ template<typename T> optional<int> count() const; /** * References the underlying @c MPI_Status */ operator MPI_Status&() { return m_status; } /** * References the underlying @c MPI_Status */ operator const MPI_Status&() const { return m_status; } private: /** * INTERNAL ONLY */ template<typename T> optional<int> count_impl(mpl::true_) const; /** * INTERNAL ONLY */ template<typename T> optional<int> count_impl(mpl::false_) const; public: // friend templates are not portable /// INTERNAL ONLY mutable MPI_Status m_status; mutable int m_count; friend class communicator; friend class request; }; } } // end namespace boost::mpi #endif // BOOST_MPI_STATUS_HPP
module Main %default total codata Stream' a = Nil | (::) a (Stream' a) countFrom : Int -> Stream' Int countFrom x = x :: countFrom (x + 1) take : Nat -> Stream' a -> List a take Z _ = [] take (S n) (x :: xs) = x :: take n xs take n [] = [] main : IO () main = do printLn (take 10 (Main.countFrom 10))
Require Export refine. Require Export parser. Require Export Station. Require Export Vehicle. Require Export comp. (** The CyCab example *) Definition FVehicle: IA := parse "IA [s1,s2,s3,s4,s5,s6] (s1) [fstart,start,emrg,far,halt] [pos,reset] [move,stop] [s1->(start)s2, s2->(move)s3, s2->(emrg)s5, s3->(pos)s4, s3->(emrg)s5, s4->(far)s2, s4->(halt)s1, s4->(emrg)s5, s5->(reset)s1, s1->(fstart)s6, s6->(move)s6, s6->(emrg)s5, s6->(stop)s1]". (* FVehicle is a refinement of Vehicle *) Eval compute in IAutomaton.bRefine Vehicle FVehicle. Eval compute in IAutomaton.b_compatible FVehicle Station. (*Definition FVehicle_Station_prod: IA := IAutomaton.IAProd FVehicle Station. Eval compute in :> FVehicle_Station_prod.*) Definition FVehicle_Station: IA :=IAutomaton.composition FVehicle Station. Eval compute in :> FVehicle_Station. (* the composition results comply with the refinement relation *) Eval compute in IAutomaton.bRefine Vehicle_Station FVehicle_Station. (*********** security of FVehicle*Station ******************************************) (*************************** \Gamma(fstart)=h ****************************) (* SIR-GNNI at m: true *) Definition FVehicle_Station_hid_m: IA := IAutomaton.hiding FVehicle_Station (ASet.GenActs [&"emrg",&"reset",&"fstart"]). Definition FVehicle_Station_res_m: IA := IAutomaton.hiding ( IAutomaton.restriction FVehicle_Station (ASet.GenActs [&"emrg",&"fstart"]) ) (ASet.GenActs [&"reset"]). Eval compute in :> FVehicle_Station_hid_m. Eval compute in :> FVehicle_Station_res_m. Eval compute in SIRGNNI_refinement FVehicle_Station_res_m FVehicle_Station_hid_m. (* SME-NI at m: true *) Definition FVehicle_Station_rep_m: IA := IAutomaton.hiding ( IAutomaton.replacement FVehicle_Station (&"tau") (ASet.GenActs [&"emrg",&"fstart"]) ) (ASet.GenActs [&"reset"]). Eval compute in :> FVehicle_Station_rep_m. Eval compute in SMENI_refinement FVehicle_Station_rep_m FVehicle_Station_hid_m. (* SIR-GNNI at l: true *) Definition FVehicle_Station_hid_l: IA := IAutomaton.hiding FVehicle_Station (ASet.GenActs [&"emrg",&"start",&"fstart",&"reset"]). Definition FVehicle_Station_res_l: IA := IAutomaton.hiding ( IAutomaton.restriction FVehicle_Station (ASet.GenActs [&"emrg",&"start",&"fstart"]) ) (ASet.GenActs [&"reset"]). Eval compute in :>FVehicle_Station_hid_l. Eval compute in :>FVehicle_Station_res_l. Eval compute in SIRGNNI_refinement FVehicle_Station_res_l FVehicle_Station_hid_l. (* SME-NI at l: true *) Definition FVehicle_Station_rep_l: IA := IAutomaton.hiding ( IAutomaton.replacement FVehicle_Station (&"tau") (ASet.GenActs [&"emrg",&"start",&"fstart"]) ) (ASet.GenActs [&"reset"]). Eval compute in :>FVehicle_Station_rep_l. Eval compute in SMENI_refinement FVehicle_Station_rep_l FVehicle_Station_hid_l.
Normally, in an everyday car kind of way, so long as it’s shiny, a nice colour and isn’t going to break down, usually I’m fairly easy going. Jules (who takes care of our brides and grooms) on the other hand has been very focussed on cars this last week and definitely knows what she likes. She’s also got an uncanny knack of remembering every number plate that she comes across. It’s that attention to detail that is mind boggling! Just occasionally though even I can really understand the excitement about a having a gorgeous car. I’d be lying if I said there wasn’t the teeniest bit of excitement when the gold wrapped Bentley of one of our clients drove up to the studio last year. We really weren’t all sneakily admiring it parked on the driveway, honest! I love the fun factor in a car that shows your personality. I really get this as my own first car was a fiat 126 and was diddy, in fact I had two at one point a blue and a red which I used to joke that I chose between depending on my outfit that day. One of our couples had a fiat 500 as their wedding car last year. How awesome is that! Some couples choose a car because of the sentiment attached to it. At our last wedding of 2016 on New Years Eve, the wedding car had huge sentimental value to the bride and her family and was justifiably an important part of the day. At my own nieces wedding she had a VW camper-van, which are perfect for a vintage wedding, but I knew that was also a special choice for my sister and her hubby who both loved VW campers. So, who knew a car could be so important!!! But which to choose, well we’ve had the pleasure of photographing some amazing cars over the years. Not least some of those belonging to Chris Evans, who brought them to our neck of the woods at Cliveden House Hotel for Children in Need. Here are his pics and todays gallery is a selection of wedding cars to give you inspiration, go have a browse!
r=359.36 https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7rg61/media/images/d7rg61-016/svc:tesseract/full/full/359.36/default.jpg Accept:application/hocr+xml
-- Mergesort {-# OPTIONS --without-K --safe #-} module Algorithms.List.Sort.Merge where -- agda-stdlib open import Level open import Data.Bool using (true; false) open import Data.List import Data.List.Properties as Listₚ open import Data.Product as Prod import Data.Nat as ℕ open import Data.Nat.Induction as Ind open import Function.Base open import Relation.Binary as B open import Relation.Binary.PropositionalEquality as P using (_≡_) open import Relation.Nullary open import Relation.Unary as U import Relation.Unary.Properties as Uₚ open import Induction.WellFounded private variable a p r : Level module Mergesort {A : Set a} {_≤_ : Rel A r} (_≤?_ : B.Decidable _≤_) where merge′ : A → A → List A → List A → List A merge′ x y xs ys with x ≤? y merge′ x y [] ys | true because _ = x ∷ y ∷ ys merge′ x y (x₁ ∷ xs) ys | true because _ = x ∷ merge′ x₁ y xs ys merge′ x y xs [] | false because _ = y ∷ x ∷ xs merge′ x y xs (y₁ ∷ ys) | false because _ = y ∷ merge′ x y₁ xs ys merge : List A → List A → List A merge [] ys = ys merge (x ∷ xs) [] = x ∷ xs merge (x ∷ xs) (y ∷ ys) = merge′ x y xs ys _L<_ : Rel (List A) _ _L<_ = ℕ._<_ on length L<-wf : WellFounded _L<_ L<-wf = InverseImage.wellFounded length Ind.<-wellFounded split : List A → (List A × List A) split [] = [] , [] split (x ∷ []) = [ x ] , [] split (x ∷ y ∷ xs) = Prod.map (x ∷_) (y ∷_) (split xs) {- sort : List A → List A sort [] = [] sort (x ∷ xs) = {! !} sort xs = split xs ys , zs = merge (sort ys) (sort zs) -}
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import data.finsupp.interval import data.mv_polynomial.basic import data.polynomial.algebra_map import data.polynomial.coeff import linear_algebra.std_basis import ring_theory.ideal.local_ring import ring_theory.multiplicity import tactic.linarith /-! # Formal power series This file defines (multivariate) formal power series and develops the basic properties of these objects. A formal power series is to a polynomial like an infinite sum is to a finite sum. We provide the natural inclusion from polynomials to formal power series. ## Generalities The file starts with setting up the (semi)ring structure on multivariate power series. `trunc n φ` truncates a formal power series to the polynomial that has the same coefficients as `φ`, for all `m < n`, and `0` otherwise. If the constant coefficient of a formal power series is invertible, then this formal power series is invertible. Formal power series over a local ring form a local ring. ## Formal power series in one variable We prove that if the ring of coefficients is an integral domain, then formal power series in one variable form an integral domain. The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`. If the coefficients form an integral domain, then `order` is a valuation (`order_mul`, `le_order_add`). ## Implementation notes In this file we define multivariate formal power series with variables indexed by `σ` and coefficients in `R` as `mv_power_series σ R := (σ →₀ ℕ) → R`. Unfortunately there is not yet enough API to show that they are the completion of the ring of multivariate polynomials. However, we provide most of the infrastructure that is needed to do this. Once I-adic completion (topological or algebraic) is available it should not be hard to fill in the details. Formal power series in one variable are defined as `power_series R := mv_power_series unit R`. This allows us to port a lot of proofs and properties from the multivariate case to the single variable case. However, it means that formal power series are indexed by `unit →₀ ℕ`, which is of course canonically isomorphic to `ℕ`. We then build some glue to treat formal power series as if they are indexed by `ℕ`. Occasionally this leads to proofs that are uglier than expected. -/ noncomputable theory open_locale classical big_operators polynomial /-- Multivariate formal power series, where `σ` is the index set of the variables and `R` is the coefficient ring.-/ def mv_power_series (σ : Type*) (R : Type*) := (σ →₀ ℕ) → R namespace mv_power_series open finsupp variables {σ R : Type*} instance [inhabited R] : inhabited (mv_power_series σ R) := ⟨λ _, default⟩ instance [has_zero R] : has_zero (mv_power_series σ R) := pi.has_zero instance [add_monoid R] : add_monoid (mv_power_series σ R) := pi.add_monoid instance [add_group R] : add_group (mv_power_series σ R) := pi.add_group instance [add_comm_monoid R] : add_comm_monoid (mv_power_series σ R) := pi.add_comm_monoid instance [add_comm_group R] : add_comm_group (mv_power_series σ R) := pi.add_comm_group instance [nontrivial R] : nontrivial (mv_power_series σ R) := function.nontrivial instance {A} [semiring R] [add_comm_monoid A] [module R A] : module R (mv_power_series σ A) := pi.module _ _ _ instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A] [has_smul R S] [is_scalar_tower R S A] : is_scalar_tower R S (mv_power_series σ A) := pi.is_scalar_tower section semiring variables (R) [semiring R] /-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/ def monomial (n : σ →₀ ℕ) : R →ₗ[R] mv_power_series σ R := linear_map.std_basis R _ n /-- The `n`th coefficient of a multivariate formal power series.-/ def coeff (n : σ →₀ ℕ) : (mv_power_series σ R) →ₗ[R] R := linear_map.proj n variables {R} /-- Two multivariate formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) : φ = ψ := funext h /-- Two multivariate formal power series are equal if and only if all their coefficients are equal.-/ lemma ext_iff {φ ψ : mv_power_series σ R} : φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) := function.funext_iff lemma monomial_def [decidable_eq σ] (n : σ →₀ ℕ) : monomial R n = linear_map.std_basis R _ n := by convert rfl -- unify the `decidable` arguments lemma coeff_monomial [decidable_eq σ] (m n : σ →₀ ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := by rw [coeff, monomial_def, linear_map.proj_apply, linear_map.std_basis_apply, function.update_apply, pi.zero_apply] @[simp] lemma coeff_monomial_same (n : σ →₀ ℕ) (a : R) : coeff R n (monomial R n a) = a := linear_map.std_basis_same R _ n a lemma coeff_monomial_ne {m n : σ →₀ ℕ} (h : m ≠ n) (a : R) : coeff R m (monomial R n a) = 0 := linear_map.std_basis_ne R _ _ _ h a lemma eq_of_coeff_monomial_ne_zero {m n : σ →₀ ℕ} {a : R} (h : coeff R m (monomial R n a) ≠ 0) : m = n := by_contra $ λ h', h $ coeff_monomial_ne h' a @[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) : (coeff R n).comp (monomial R n) = linear_map.id := linear_map.ext $ coeff_monomial_same n @[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff R n (0 : mv_power_series σ R) = 0 := rfl variables (m n : σ →₀ ℕ) (φ ψ : mv_power_series σ R) instance : has_one (mv_power_series σ R) := ⟨monomial R (0 : σ →₀ ℕ) 1⟩ lemma coeff_one [decidable_eq σ] : coeff R n (1 : mv_power_series σ R) = if n = 0 then 1 else 0 := coeff_monomial _ _ _ lemma coeff_zero_one : coeff R (0 : σ →₀ ℕ) 1 = 1 := coeff_monomial_same 0 1 lemma monomial_zero_one : monomial R (0 : σ →₀ ℕ) 1 = 1 := rfl instance : add_monoid_with_one (mv_power_series σ R) := { nat_cast := λ n, monomial R 0 n, nat_cast_zero := by simp [nat.cast], nat_cast_succ := by simp [nat.cast, monomial_zero_one], one := 1, .. mv_power_series.add_monoid } instance : has_mul (mv_power_series σ R) := ⟨λ φ ψ n, ∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ⟩ lemma coeff_mul : coeff R n (φ * ψ) = ∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := rfl protected lemma zero_mul : (0 : mv_power_series σ R) * φ = 0 := ext $ λ n, by simp [coeff_mul] protected lemma mul_zero : φ * 0 = 0 := ext $ λ n, by simp [coeff_mul] lemma coeff_monomial_mul (a : R) : coeff R m (monomial R n a * φ) = if n ≤ m then a * coeff R (m - n) φ else 0 := begin have : ∀ p ∈ antidiagonal m, coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 (monomial R n a) * coeff R p.2 φ ≠ 0 → p.1 = n := λ p _ hp, eq_of_coeff_monomial_ne_zero (left_ne_zero_of_mul hp), rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_fst_eq, finset.sum_ite_index], simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty] end lemma coeff_mul_monomial (a : R) : coeff R m (φ * monomial R n a) = if n ≤ m then coeff R (m - n) φ * a else 0 := begin have : ∀ p ∈ antidiagonal m, coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 φ * coeff R p.2 (monomial R n a) ≠ 0 → p.2 = n := λ p _ hp, eq_of_coeff_monomial_ne_zero (right_ne_zero_of_mul hp), rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_snd_eq, finset.sum_ite_index], simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty] end lemma coeff_add_monomial_mul (a : R) : coeff R (m + n) (monomial R m a * φ) = a * coeff R n φ := begin rw [coeff_monomial_mul, if_pos, add_tsub_cancel_left], exact le_add_right le_rfl end lemma coeff_add_mul_monomial (a : R) : coeff R (m + n) (φ * monomial R n a) = coeff R m φ * a := begin rw [coeff_mul_monomial, if_pos, add_tsub_cancel_right], exact le_add_left le_rfl end @[simp] lemma commute_monomial {a : R} {n} : commute φ (monomial R n a) ↔ ∀ m, commute (coeff R m φ) a := begin refine ext_iff.trans ⟨λ h m, _, λ h m, _⟩, { have := h (m + n), rwa [coeff_add_mul_monomial, add_comm, coeff_add_monomial_mul] at this }, { rw [coeff_mul_monomial, coeff_monomial_mul], split_ifs; [apply h, refl] } end protected lemma one_mul : (1 : mv_power_series σ R) * φ = φ := ext $ λ n, by simpa using coeff_add_monomial_mul 0 n φ 1 protected lemma mul_one : φ * 1 = φ := ext $ λ n, by simpa using coeff_add_mul_monomial n 0 φ 1 protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ R) : φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ := ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, linear_map.map_add] protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ := ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, linear_map.map_add] protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) := begin ext1 n, simp only [coeff_mul, finset.sum_mul, finset.mul_sum, finset.sum_sigma'], refine finset.sum_bij (λ p _, ⟨(p.2.1, p.2.2 + p.1.2), (p.2.2, p.1.2)⟩) _ _ _ _; simp only [mem_antidiagonal, finset.mem_sigma, heq_iff_eq, prod.mk.inj_iff, and_imp, exists_prop], { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩, dsimp only, rintro rfl rfl, simp [add_assoc] }, { rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩, dsimp only, rintro rfl rfl, apply mul_assoc }, { rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩ ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl - rfl rfl - rfl rfl, refl }, { rintro ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl, refine ⟨⟨(i + k, l), (i, k)⟩, _, _⟩; simp [add_assoc] } end instance : semiring (mv_power_series σ R) := { mul_one := mv_power_series.mul_one, one_mul := mv_power_series.one_mul, mul_assoc := mv_power_series.mul_assoc, mul_zero := mv_power_series.mul_zero, zero_mul := mv_power_series.zero_mul, left_distrib := mv_power_series.mul_add, right_distrib := mv_power_series.add_mul, .. mv_power_series.add_monoid_with_one, .. mv_power_series.has_mul, .. mv_power_series.add_comm_monoid } end semiring instance [comm_semiring R] : comm_semiring (mv_power_series σ R) := { mul_comm := λ φ ψ, ext $ λ n, by simpa only [coeff_mul, mul_comm] using sum_antidiagonal_swap n (λ a b, coeff R a φ * coeff R b ψ), .. mv_power_series.semiring } instance [ring R] : ring (mv_power_series σ R) := { .. mv_power_series.semiring, .. mv_power_series.add_comm_group } instance [comm_ring R] : comm_ring (mv_power_series σ R) := { .. mv_power_series.comm_semiring, .. mv_power_series.add_comm_group } section semiring variables [semiring R] lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : R) : monomial R m a * monomial R n b = monomial R (m + n) (a * b) := begin ext k, simp only [coeff_mul_monomial, coeff_monomial], split_ifs with h₁ h₂ h₃ h₃ h₂; try { refl }, { rw [← h₂, tsub_add_cancel_of_le h₁] at h₃, exact (h₃ rfl).elim }, { rw [h₃, add_tsub_cancel_right] at h₂, exact (h₂ rfl).elim }, { exact zero_mul b }, { rw h₂ at h₁, exact (h₁ $ le_add_left le_rfl).elim } end variables (σ) (R) /-- The constant multivariate formal power series.-/ def C : R →+* mv_power_series σ R := { map_one' := rfl, map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm, map_zero' := (monomial R (0 : _)).map_zero, .. monomial R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma monomial_zero_eq_C : ⇑(monomial R (0 : σ →₀ ℕ)) = C σ R := rfl lemma monomial_zero_eq_C_apply (a : R) : monomial R (0 : σ →₀ ℕ) a = C σ R a := rfl lemma coeff_C [decidable_eq σ] (n : σ →₀ ℕ) (a : R) : coeff R n (C σ R a) = if n = 0 then a else 0 := coeff_monomial _ _ _ lemma coeff_zero_C (a : R) : coeff R (0 : σ →₀ℕ) (C σ R a) = a := coeff_monomial_same 0 a /-- The variables of the multivariate formal power series ring.-/ def X (s : σ) : mv_power_series σ R := monomial R (single s 1) 1 lemma coeff_X [decidable_eq σ] (n : σ →₀ ℕ) (s : σ) : coeff R n (X s : mv_power_series σ R) = if n = (single s 1) then 1 else 0 := coeff_monomial _ _ _ lemma coeff_index_single_X [decidable_eq σ] (s t : σ) : coeff R (single t 1) (X s : mv_power_series σ R) = if t = s then 1 else 0 := by simp only [coeff_X, single_left_inj one_ne_zero] @[simp] lemma coeff_index_single_self_X (s : σ) : coeff R (single s 1) (X s : mv_power_series σ R) = 1 := coeff_monomial_same _ _ lemma coeff_zero_X (s : σ) : coeff R (0 : σ →₀ ℕ) (X s : mv_power_series σ R) = 0 := by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) } lemma commute_X (φ : mv_power_series σ R) (s : σ) : commute φ (X s) := φ.commute_monomial.mpr $ λ m, commute.one_right _ lemma X_def (s : σ) : X s = monomial R (single s 1) 1 := rfl lemma X_pow_eq (s : σ) (n : ℕ) : (X s : mv_power_series σ R)^n = monomial R (single s n) 1 := begin induction n with n ih, { rw [pow_zero, finsupp.single_zero, monomial_zero_one] }, { rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] } end lemma coeff_X_pow [decidable_eq σ] (m : σ →₀ ℕ) (s : σ) (n : ℕ) : coeff R m ((X s : mv_power_series σ R)^n) = if m = single s n then 1 else 0 := by rw [X_pow_eq s n, coeff_monomial] @[simp] lemma coeff_mul_C (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (φ * C σ R a) = coeff R n φ * a := by simpa using coeff_add_mul_monomial n 0 φ a @[simp] lemma coeff_C_mul (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (C σ R a * φ) = a * coeff R n φ := by simpa using coeff_add_monomial_mul 0 n φ a lemma coeff_zero_mul_X (φ : mv_power_series σ R) (s : σ) : coeff R (0 : σ →₀ ℕ) (φ * X s) = 0 := begin have : ¬single s 1 ≤ 0, from λ h, by simpa using h s, simp only [X, coeff_mul_monomial, if_neg this] end lemma coeff_zero_X_mul (φ : mv_power_series σ R) (s : σ) : coeff R (0 : σ →₀ ℕ) (X s * φ) = 0 := by rw [← (φ.commute_X s).eq, coeff_zero_mul_X] variables (σ) (R) /-- The constant coefficient of a formal power series.-/ def constant_coeff : (mv_power_series σ R) →+* R := { to_fun := coeff R (0 : σ →₀ ℕ), map_one' := coeff_zero_one, map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero], map_zero' := linear_map.map_zero _, .. coeff R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma coeff_zero_eq_constant_coeff : ⇑(coeff R (0 : σ →₀ ℕ)) = constant_coeff σ R := rfl lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ R) : coeff R (0 : σ →₀ ℕ) φ = constant_coeff σ R φ := rfl @[simp] lemma constant_coeff_C (a : R) : constant_coeff σ R (C σ R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff σ R).comp (C σ R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff σ R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff σ R 1 = 1 := rfl @[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ R (X s) = 0 := coeff_zero_X s /-- If a multivariate formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : mv_power_series σ R) (h : is_unit φ) : is_unit (constant_coeff σ R φ) := h.map _ @[simp] lemma coeff_smul (f : mv_power_series σ R) (n) (a : R) : coeff _ n (a • f) = a * coeff _ n f := rfl lemma smul_eq_C_mul (f : mv_power_series σ R) (a : R) : a • f = C σ R a * f := by { ext, simp } lemma X_inj [nontrivial R] {s t : σ} : (X s : mv_power_series σ R) = X t ↔ s = t := ⟨begin intro h, replace h := congr_arg (coeff R (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h, split_ifs at h with H, { rw finsupp.single_eq_single_iff at H, cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } }, { exfalso, exact one_ne_zero h } end, congr_arg X⟩ end semiring section map variables {S T : Type*} [semiring R] [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) variable (σ) /-- The map between multivariate formal power series induced by a map on the coefficients.-/ def map : mv_power_series σ R →+* mv_power_series σ S := { to_fun := λ φ n, f $ coeff R n φ, map_zero' := ext $ λ n, f.map_zero, map_one' := ext $ λ n, show f ((coeff R n) 1) = (coeff S n) 1, by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] }, map_add' := λ φ ψ, ext $ λ n, show f ((coeff R n) (φ + ψ)) = f ((coeff R n) φ) + f ((coeff R n) ψ), by simp, map_mul' := λ φ ψ, ext $ λ n, show f _ = _, begin rw [coeff_mul, f.map_sum, coeff_mul, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [f.map_mul], refl, end } variable {σ} @[simp] lemma map_id : map σ (ring_hom.id R) = ring_hom.id _ := rfl lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl @[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ R) : coeff S n (map σ f φ) = f (coeff R n φ) := rfl @[simp] lemma constant_coeff_map (φ : mv_power_series σ R) : constant_coeff σ S (map σ f φ) = f (constant_coeff σ R φ) := rfl @[simp] lemma map_monomial (n : σ →₀ ℕ) (a : R) : map σ f (monomial R n a) = monomial S n (f a) := by { ext m, simp [coeff_monomial, apply_ite f] } @[simp] lemma map_C (a : R) : map σ f (C σ R a) = C σ S (f a) := map_monomial _ _ _ @[simp] lemma map_X (s : σ) : map σ f (X s) = X s := by simp [mv_power_series.X] end map section algebra variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A] instance : algebra R (mv_power_series σ A) := { commutes' := λ a φ, by { ext n, simp [algebra.commutes] }, smul_def' := λ a σ, by { ext n, simp [(coeff A n).map_smul_of_tower a, algebra.smul_def] }, to_ring_hom := (mv_power_series.map σ (algebra_map R A)).comp (C σ R), .. mv_power_series.module } theorem C_eq_algebra_map : C σ R = (algebra_map R (mv_power_series σ R)) := rfl theorem algebra_map_apply {r : R} : algebra_map R (mv_power_series σ A) r = C σ A (algebra_map R A r) := begin change (mv_power_series.map σ (algebra_map R A)).comp (C σ R) r = _, simp, end instance [nonempty σ] [nontrivial R] : nontrivial (subalgebra R (mv_power_series σ R)) := ⟨⟨⊥, ⊤, begin rw [ne.def, set_like.ext_iff, not_forall], inhabit σ, refine ⟨X default, _⟩, simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top], intros x, rw [ext_iff, not_forall], refine ⟨finsupp.single default 1, _⟩, simp [algebra_map_apply, coeff_C], end⟩⟩ end algebra section trunc variables [comm_semiring R] (n : σ →₀ ℕ) /-- Auxiliary definition for the truncation function. -/ def trunc_fun (φ : mv_power_series σ R) : mv_polynomial σ R := ∑ m in finset.Iio n, mv_polynomial.monomial m (coeff R m φ) lemma coeff_trunc_fun (m : σ →₀ ℕ) (φ : mv_power_series σ R) : (trunc_fun n φ).coeff m = if m < n then coeff R m φ else 0 := by simp [trunc_fun, mv_polynomial.coeff_sum] variable (R) /-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/ def trunc : mv_power_series σ R →+ mv_polynomial σ R := { to_fun := trunc_fun n, map_zero' := by { ext, simp [coeff_trunc_fun] }, map_add' := by { intros, ext, simp [coeff_trunc_fun, ite_add], split_ifs; refl } } variable {R} lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ R) : (trunc R n φ).coeff m = if m < n then coeff R m φ else 0 := by simp [trunc, coeff_trunc_fun] @[simp] lemma trunc_one (hnn : n ≠ 0) : trunc R n 1 = 1 := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H', { subst m, simp }, { symmetry, rw mv_polynomial.coeff_one, exact if_neg (ne.symm H'), }, { symmetry, rw mv_polynomial.coeff_one, refine if_neg _, rintro rfl, apply H, exact ne.bot_lt hnn, } end @[simp] lemma trunc_C (hnn : n ≠ 0) (a : R) : trunc R n (C σ R a) = mv_polynomial.C a := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *}, exfalso, apply H, subst m, exact ne.bot_lt hnn, end end trunc section semiring variable [semiring R] lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff R m φ = 0 := begin split, { rintros ⟨φ, rfl⟩ m h, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul], contrapose! h, subst i, rw finsupp.mem_antidiagonal at hij, rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ }, { intro h, refine ⟨λ m, coeff R (m + (single s n)) φ, _⟩, ext m, by_cases H : m - single s n + single s n = m, { rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)], { rw [coeff_X_pow, if_pos rfl, one_mul], simpa using congr_arg (λ (m : σ →₀ ℕ), coeff R m φ) H.symm }, { rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩, ext t, simp only [add_tsub_cancel_left, finsupp.add_apply, finsupp.tsub_apply] }, { exact zero_mul _ } }, { intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal, add_comm] } }, { rw [h, coeff_mul, finset.sum_eq_zero], { rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply H, rw [← hij, hi], ext, rw [coe_add, coe_add, pi.add_apply, pi.add_apply, add_tsub_cancel_left, add_comm], }, { exact zero_mul _ } }, { classical, contrapose! H, ext t, by_cases hst : s = t, { subst t, simpa using tsub_add_cancel_of_le H }, { simp [finsupp.single_apply, hst] } } } } end lemma X_dvd_iff {s : σ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff R m φ = 0 := begin rw [← pow_one (X s : mv_power_series σ R), X_pow_dvd_iff], split; intros h m hm, { exact h m (hm.symm ▸ zero_lt_one) }, { exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) } end end semiring section ring variables [ring R] /- The inverse of a multivariate formal power series is defined by well-founded recursion on the coeffients of the inverse. -/ /-- Auxiliary definition that unifies the totalised inverse formal power series `(_)⁻¹` and the inverse formal power series that depends on an inverse of the constant coefficient `inv_of_unit`.-/ protected noncomputable def inv.aux (a : R) (φ : mv_power_series σ R) : mv_power_series σ R | n := if n = 0 then a else - a * ∑ x in n.antidiagonal, if h : x.2 < n then coeff R x.1 φ * inv.aux x.2 else 0 using_well_founded { rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩], dec_tac := tactic.assumption } lemma coeff_inv_aux [decidable_eq σ] (n : σ →₀ ℕ) (a : R) (φ : mv_power_series σ R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in n.antidiagonal, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := show inv.aux a φ n = _, begin rw inv.aux, convert rfl -- unify `decidable` instances end /-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : mv_power_series σ R) (u : Rˣ) : mv_power_series σ R := inv.aux (↑u⁻¹) φ lemma coeff_inv_of_unit [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ R) (u : Rˣ) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in n.antidiagonal, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n (↑u⁻¹) φ @[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ R) (u : Rˣ) : constant_coeff σ R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : mv_power_series σ R) (u : Rˣ) (h : constant_coeff σ R φ = u) : φ * inv_of_unit φ u = 1 := ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], } else begin have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal, { rw [finsupp.mem_antidiagonal, zero_add] }, rw [coeff_one, if_neg H, coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H, neg_mul, mul_neg, units.mul_inv_cancel_left, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.insert_erase this, if_neg (not_lt_of_ge $ le_rfl), zero_add, add_comm, ← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal] at hij, cases hij with h₁ h₂, subst n, rw if_pos, suffices : (0 : _) + j < i + j, {simpa}, apply add_lt_add_right, split, { intro s, exact nat.zero_le _ }, { intro H, apply h₁, suffices : i = 0, {simp [this]}, ext1 s, exact nat.eq_zero_of_le_zero (H s) } end end ring section comm_ring variable [comm_ring R] /-- Multivariate formal power series over a local ring form a local ring. -/ instance [local_ring R] : local_ring (mv_power_series σ R) := local_ring.of_is_unit_or_is_unit_one_sub_self $ by { intro φ, rcases local_ring.is_unit_or_is_unit_one_sub_self (constant_coeff σ R φ) with ⟨u,h⟩|⟨u,h⟩; [left, right]; { refine is_unit_of_mul_eq_one _ _ (mul_inv_of_unit _ u _), simpa using h.symm } } -- TODO(jmc): once adic topology lands, show that this is complete end comm_ring section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] -- Thanks to the linter for informing us that this instance does -- not actually need R and S to be local rings! /-- The map `A[[X]] → B[[X]]` induced by a local ring hom `A → B` is local -/ instance map.is_local_ring_hom : is_local_ring_hom (map σ f) := ⟨begin rintros φ ⟨ψ, h⟩, replace h := congr_arg (constant_coeff σ S) h, rw constant_coeff_map at h, have : is_unit (constant_coeff σ S ↑ψ) := @is_unit_constant_coeff σ S _ (↑ψ) ψ.is_unit, rw h at this, rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩, exact is_unit_of_mul_eq_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc.symm) end⟩ end local_ring section field variables {k : Type*} [field k] /-- The inverse `1/f` of a multivariable power series `f` over a field -/ protected def inv (φ : mv_power_series σ k) : mv_power_series σ k := inv.aux (constant_coeff σ k φ)⁻¹ φ instance : has_inv (mv_power_series σ k) := ⟨mv_power_series.inv⟩ lemma coeff_inv [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff σ k φ)⁻¹ else - (constant_coeff σ k φ)⁻¹ * ∑ x in n.antidiagonal, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := coeff_inv_aux n _ φ @[simp] lemma constant_coeff_inv (φ : mv_power_series σ k) : constant_coeff σ k (φ⁻¹) = (constant_coeff σ k φ)⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl] lemma inv_eq_zero {φ : mv_power_series σ k} : φ⁻¹ = 0 ↔ constant_coeff σ k φ = 0 := ⟨λ h, by simpa using congr_arg (constant_coeff σ k) h, λ h, ext $ λ n, by { rw coeff_inv, split_ifs; simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩ @[simp] lemma zero_inv : (0 : mv_power_series σ k)⁻¹ = 0 := by rw [inv_eq_zero, constant_coeff_zero] @[simp, priority 1100] lemma inv_of_unit_eq (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl @[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ k) (u : units k) (h : constant_coeff σ k φ = u) : inv_of_unit φ u = φ⁻¹ := begin rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero), congr' 1, rw [units.ext_iff], exact h.symm, end @[simp] protected lemma mul_inv_cancel (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ * φ⁻¹ = 1 := by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl] @[simp] protected lemma inv_mul_cancel (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ⁻¹ * φ = 1 := by rw [mul_comm, φ.mul_inv_cancel h] protected lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : mv_power_series σ k} (h : constant_coeff σ k φ₃ ≠ 0) : φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ := ⟨λ k, by simp [k, mul_assoc, mv_power_series.inv_mul_cancel _ h], λ k, by simp [← k, mul_assoc, mv_power_series.mul_inv_cancel _ h]⟩ protected lemma eq_inv_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) : φ = ψ⁻¹ ↔ φ * ψ = 1 := by rw [← mv_power_series.eq_mul_inv_iff_mul_eq h, one_mul] protected lemma inv_eq_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := by rw [eq_comm, mv_power_series.eq_inv_iff_mul_eq_one h] @[simp] protected lemma mul_inv_rev (φ ψ : mv_power_series σ k) : (φ * ψ)⁻¹ = ψ⁻¹ * φ⁻¹ := begin by_cases h : constant_coeff σ k (φ * ψ) = 0, { rw inv_eq_zero.mpr h, simp only [map_mul, mul_eq_zero] at h, -- we don't have `no_zero_divisors (mw_power_series σ k)` yet, cases h; simp [inv_eq_zero.mpr h] }, { rw [mv_power_series.inv_eq_iff_mul_eq_one h], simp only [not_or_distrib, map_mul, mul_eq_zero] at h, rw [←mul_assoc, mul_assoc _⁻¹, mv_power_series.inv_mul_cancel _ h.left, mul_one, mv_power_series.inv_mul_cancel _ h.right] } end instance : inv_one_class (mv_power_series σ k) := { inv_one := by { rw [mv_power_series.inv_eq_iff_mul_eq_one, mul_one], simp }, ..mv_power_series.has_one, ..mv_power_series.has_inv } @[simp] lemma C_inv (r : k) : (C σ k r)⁻¹ = C σ k r⁻¹ := begin rcases eq_or_ne r 0 with rfl|hr, { simp }, rw [mv_power_series.inv_eq_iff_mul_eq_one, ←map_mul, inv_mul_cancel hr, map_one], simpa using hr end @[simp] lemma X_inv (s : σ) : (X s : mv_power_series σ k)⁻¹ = 0 := by rw [inv_eq_zero, constant_coeff_X] @[simp] end field end mv_power_series namespace mv_polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] (φ ψ : mv_polynomial σ R) /-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/ instance coe_to_mv_power_series : has_coe (mv_polynomial σ R) (mv_power_series σ R) := ⟨λ φ n, coeff n φ⟩ lemma coe_def : (φ : mv_power_series σ R) = λ n, coeff n φ := rfl @[simp, norm_cast] lemma coeff_coe (n : σ →₀ ℕ) : mv_power_series.coeff R n ↑φ = coeff n φ := rfl @[simp, norm_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : R) : (monomial n a : mv_power_series σ R) = mv_power_series.monomial R n a := mv_power_series.ext $ λ m, begin rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial], split_ifs with h₁ h₂; refl <|> subst m; contradiction end @[simp, norm_cast] lemma coe_zero : ((0 : mv_polynomial σ R) : mv_power_series σ R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : mv_polynomial σ R) : mv_power_series σ R) = 1 := coe_monomial _ _ @[simp, norm_cast] lemma coe_add : ((φ + ψ : mv_polynomial σ R) : mv_power_series σ R) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul : ((φ * ψ : mv_polynomial σ R) : mv_power_series σ R) = φ * ψ := mv_power_series.ext $ λ n, by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.C σ R a := coe_monomial _ _ @[simp, norm_cast] lemma coe_bit0 : ((bit0 φ : mv_polynomial σ R) : mv_power_series σ R) = bit0 (φ : mv_power_series σ R) := coe_add _ _ @[simp, norm_cast] lemma coe_bit1 : ((bit1 φ : mv_polynomial σ R) : mv_power_series σ R) = bit1 (φ : mv_power_series σ R) := by rw [bit1, bit1, coe_add, coe_one, coe_bit0] @[simp, norm_cast] lemma coe_X (s : σ) : ((X s : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.X s := coe_monomial _ _ variables (σ R) lemma coe_injective : function.injective (coe : mv_polynomial σ R → mv_power_series σ R) := λ x y h, by { ext, simp_rw [←coeff_coe, h] } variables {σ R φ ψ} @[simp, norm_cast] lemma coe_inj : (φ : mv_power_series σ R) = ψ ↔ φ = ψ := (coe_injective σ R).eq_iff @[simp] lemma coe_eq_zero_iff : (φ : mv_power_series σ R) = 0 ↔ φ = 0 := by rw [←coe_zero, coe_inj] @[simp] lemma coe_eq_one_iff : (φ : mv_power_series σ R) = 1 ↔ φ = 1 := by rw [←coe_one, coe_inj] /-- The coercion from multivariable polynomials to multivariable power series as a ring homomorphism. -/ def coe_to_mv_power_series.ring_hom : mv_polynomial σ R →+* mv_power_series σ R := { to_fun := (coe : mv_polynomial σ R → mv_power_series σ R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } @[simp, norm_cast] lemma coe_pow (n : ℕ) : ((φ ^ n : mv_polynomial σ R) : mv_power_series σ R) = (φ : mv_power_series σ R) ^ n := coe_to_mv_power_series.ring_hom.map_pow _ _ variables (φ ψ) @[simp] lemma coe_to_mv_power_series.ring_hom_apply : coe_to_mv_power_series.ring_hom φ = φ := rfl section algebra variables (A : Type*) [comm_semiring A] [algebra R A] /-- The coercion from multivariable polynomials to multivariable power series as an algebra homomorphism. -/ def coe_to_mv_power_series.alg_hom : mv_polynomial σ R →ₐ[R] mv_power_series σ A := { commutes' := λ r, by simp [algebra_map_apply, mv_power_series.algebra_map_apply], ..(mv_power_series.map σ (algebra_map R A)).comp coe_to_mv_power_series.ring_hom} @[simp] lemma coe_to_mv_power_series.alg_hom_apply : (coe_to_mv_power_series.alg_hom A φ) = mv_power_series.map σ (algebra_map R A) ↑φ := rfl end algebra end mv_polynomial namespace mv_power_series variables {σ R A : Type*} [comm_semiring R] [comm_semiring A] [algebra R A] (f : mv_power_series σ R) instance algebra_mv_polynomial : algebra (mv_polynomial σ R) (mv_power_series σ A) := ring_hom.to_algebra (mv_polynomial.coe_to_mv_power_series.alg_hom A).to_ring_hom instance algebra_mv_power_series : algebra (mv_power_series σ R) (mv_power_series σ A) := (map σ (algebra_map R A)).to_algebra variables (A) lemma algebra_map_apply' (p : mv_polynomial σ R): algebra_map (mv_polynomial σ R) (mv_power_series σ A) p = map σ (algebra_map R A) p := rfl lemma algebra_map_apply'' : algebra_map (mv_power_series σ R) (mv_power_series σ A) f = map σ (algebra_map R A) f := rfl end mv_power_series /-- Formal power series over the coefficient ring `R`.-/ def power_series (R : Type*) := mv_power_series unit R namespace power_series open finsupp (single) variable {R : Type*} section local attribute [reducible] power_series instance [inhabited R] : inhabited (power_series R) := by apply_instance instance [add_monoid R] : add_monoid (power_series R) := by apply_instance instance [add_group R] : add_group (power_series R) := by apply_instance instance [add_comm_monoid R] : add_comm_monoid (power_series R) := by apply_instance instance [add_comm_group R] : add_comm_group (power_series R) := by apply_instance instance [semiring R] : semiring (power_series R) := by apply_instance instance [comm_semiring R] : comm_semiring (power_series R) := by apply_instance instance [ring R] : ring (power_series R) := by apply_instance instance [comm_ring R] : comm_ring (power_series R) := by apply_instance instance [nontrivial R] : nontrivial (power_series R) := by apply_instance instance {A} [semiring R] [add_comm_monoid A] [module R A] : module R (power_series A) := by apply_instance instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A] [has_smul R S] [is_scalar_tower R S A] : is_scalar_tower R S (power_series A) := pi.is_scalar_tower instance {A} [semiring A] [comm_semiring R] [algebra R A] : algebra R (power_series A) := by apply_instance end section semiring variables (R) [semiring R] /-- The `n`th coefficient of a formal power series.-/ def coeff (n : ℕ) : power_series R →ₗ[R] R := mv_power_series.coeff R (single () n) /-- The `n`th monomial with coefficient `a` as formal power series.-/ def monomial (n : ℕ) : R →ₗ[R] power_series R := mv_power_series.monomial R (single () n) variables {R} lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) : coeff R n = mv_power_series.coeff R s := by erw [coeff, ← h, ← finsupp.unique_single s] /-- Two formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ : power_series R} (h : ∀ n, coeff R n φ = coeff R n ψ) : φ = ψ := mv_power_series.ext $ λ n, by { rw ← coeff_def, { apply h }, refl } /-- Two formal power series are equal if all their coefficients are equal.-/ lemma ext_iff {φ ψ : power_series R} : φ = ψ ↔ (∀ n, coeff R n φ = coeff R n ψ) := ⟨λ h n, congr_arg (coeff R n) h, ext⟩ /-- Constructor for formal power series.-/ def mk {R} (f : ℕ → R) : power_series R := λ s, f (s ()) @[simp] lemma coeff_mk (n : ℕ) (f : ℕ → R) : coeff R n (mk f) = f n := congr_arg f finsupp.single_eq_same lemma coeff_monomial (m n : ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := calc coeff R m (monomial R n a) = _ : mv_power_series.coeff_monomial _ _ _ ... = if m = n then a else 0 : by simp only [finsupp.unique_single_eq_iff] lemma monomial_eq_mk (n : ℕ) (a : R) : monomial R n a = mk (λ m, if m = n then a else 0) := ext $ λ m, by { rw [coeff_monomial, coeff_mk] } @[simp] lemma coeff_monomial_same (n : ℕ) (a : R) : coeff R n (monomial R n a) = a := mv_power_series.coeff_monomial_same _ _ @[simp] lemma coeff_comp_monomial (n : ℕ) : (coeff R n).comp (monomial R n) = linear_map.id := linear_map.ext $ coeff_monomial_same n variable (R) /--The constant coefficient of a formal power series. -/ def constant_coeff : power_series R →+* R := mv_power_series.constant_coeff unit R /-- The constant formal power series.-/ def C : R →+* power_series R := mv_power_series.C unit R variable {R} /-- The variable of the formal power series ring.-/ def X : power_series R := mv_power_series.X () lemma commute_X (φ : power_series R) : commute φ X := φ.commute_X _ @[simp] lemma coeff_zero_eq_constant_coeff : ⇑(coeff R 0) = constant_coeff R := by { rw [coeff, finsupp.single_zero], refl } lemma coeff_zero_eq_constant_coeff_apply (φ : power_series R) : coeff R 0 φ = constant_coeff R φ := by rw [coeff_zero_eq_constant_coeff]; refl @[simp] lemma monomial_zero_eq_C : ⇑(monomial R 0) = C R := by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C] lemma monomial_zero_eq_C_apply (a : R) : monomial R 0 a = C R a := by simp lemma coeff_C (n : ℕ) (a : R) : coeff R n (C R a : power_series R) = if n = 0 then a else 0 := by rw [← monomial_zero_eq_C_apply, coeff_monomial] @[simp] lemma coeff_zero_C (a : R) : coeff R 0 (C R a) = a := by rw [← monomial_zero_eq_C_apply, coeff_monomial_same 0 a] lemma X_eq : (X : power_series R) = monomial R 1 1 := rfl lemma coeff_X (n : ℕ) : coeff R n (X : power_series R) = if n = 1 then 1 else 0 := by rw [X_eq, coeff_monomial] @[simp] lemma coeff_zero_X : coeff R 0 (X : power_series R) = 0 := by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X] @[simp] lemma coeff_one_X : coeff R 1 (X : power_series R) = 1 := by rw [coeff_X, if_pos rfl] @[simp] lemma X_ne_zero [nontrivial R] : (X : power_series R) ≠ 0 := λ H, by simpa only [coeff_one_X, one_ne_zero, map_zero] using congr_arg (coeff R 1) H lemma X_pow_eq (n : ℕ) : (X : power_series R)^n = monomial R n 1 := mv_power_series.X_pow_eq _ n lemma coeff_X_pow (m n : ℕ) : coeff R m ((X : power_series R)^n) = if m = n then 1 else 0 := by rw [X_pow_eq, coeff_monomial] @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff R n ((X : power_series R)^n) = 1 := by rw [coeff_X_pow, if_pos rfl] @[simp] lemma coeff_one (n : ℕ) : coeff R n (1 : power_series R) = if n = 0 then 1 else 0 := coeff_C n 1 lemma coeff_zero_one : coeff R 0 (1 : power_series R) = 1 := coeff_zero_C 1 lemma coeff_mul (n : ℕ) (φ ψ : power_series R) : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := begin symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, refl }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end @[simp] lemma coeff_mul_C (n : ℕ) (φ : power_series R) (a : R) : coeff R n (φ * C R a) = coeff R n φ * a := mv_power_series.coeff_mul_C _ φ a @[simp] lemma coeff_C_mul (n : ℕ) (φ : power_series R) (a : R) : coeff R n (C R a * φ) = a * coeff R n φ := mv_power_series.coeff_C_mul _ φ a @[simp] lemma coeff_smul {S : Type*} [semiring S] [module R S] (n : ℕ) (φ : power_series S) (a : R) : coeff S n (a • φ) = a • coeff S n φ := rfl lemma smul_eq_C_mul (f : power_series R) (a : R) : a • f = C R a * f := by { ext, simp } @[simp] lemma coeff_succ_mul_X (n : ℕ) (φ : power_series R) : coeff R (n+1) (φ * X) = coeff R n φ := begin simp only [coeff, finsupp.single_add], convert φ.coeff_add_mul_monomial (single () n) (single () 1) _, rw mul_one end @[simp] lemma coeff_succ_X_mul (n : ℕ) (φ : power_series R) : coeff R (n + 1) (X * φ) = coeff R n φ := begin simp only [coeff, finsupp.single_add, add_comm n 1], convert φ.coeff_add_monomial_mul (single () 1) (single () n) _, rw one_mul, end @[simp] lemma constant_coeff_C (a : R) : constant_coeff R (C R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff R).comp (C R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff R 1 = 1 := rfl @[simp] lemma constant_coeff_X : constant_coeff R X = 0 := mv_power_series.coeff_zero_X _ lemma coeff_zero_mul_X (φ : power_series R) : coeff R 0 (φ * X) = 0 := by simp lemma coeff_zero_X_mul (φ : power_series R) : coeff R 0 (X * φ) = 0 := by simp -- The following section duplicates the api of `data.polynomial.coeff` and should attempt to keep -- up to date with that section lemma coeff_C_mul_X_pow (x : R) (k n : ℕ) : coeff R n (C R x * X ^ k : power_series R) = if n = k then x else 0 := by simp [X_pow_eq, coeff_monomial] @[simp] theorem coeff_mul_X_pow (p : power_series R) (n d : ℕ) : coeff R (d + n) (p * X ^ n) = coeff R d p := begin rw [coeff_mul, finset.sum_eq_single (d, n), coeff_X_pow, if_pos rfl, mul_one], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, mul_zero], rintro rfl, apply h2, rw [finset.nat.mem_antidiagonal, add_right_cancel_iff] at h1, subst h1 }, { exact λ h1, (h1 (finset.nat.mem_antidiagonal.2 rfl)).elim } end @[simp] theorem coeff_X_pow_mul (p : power_series R) (n d : ℕ) : coeff R (d + n) (X ^ n * p) = coeff R d p := begin rw [coeff_mul, finset.sum_eq_single (n,d), coeff_X_pow, if_pos rfl, one_mul], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, zero_mul], rintro rfl, apply h2, rw [finset.nat.mem_antidiagonal, add_comm, add_right_cancel_iff] at h1, subst h1 }, { rw add_comm, exact λ h1, (h1 (finset.nat.mem_antidiagonal.2 rfl)).elim } end lemma coeff_mul_X_pow' (p : power_series R) (n d : ℕ) : coeff R d (p * X ^ n) = ite (n ≤ d) (coeff R (d - n) p) 0 := begin split_ifs, { rw [← tsub_add_cancel_of_le h, coeff_mul_X_pow, add_tsub_cancel_right] }, { refine (coeff_mul _ _ _).trans (finset.sum_eq_zero (λ x hx, _)), rw [coeff_X_pow, if_neg, mul_zero], exact ((le_of_add_le_right (finset.nat.mem_antidiagonal.mp hx).le).trans_lt $ not_le.mp h).ne } end lemma coeff_X_pow_mul' (p : power_series R) (n d : ℕ) : coeff R d (X ^ n * p) = ite (n ≤ d) (coeff R (d - n) p) 0 := begin split_ifs, { rw [← tsub_add_cancel_of_le h, coeff_X_pow_mul], simp, }, { refine (coeff_mul _ _ _).trans (finset.sum_eq_zero (λ x hx, _)), rw [coeff_X_pow, if_neg, zero_mul], have := finset.nat.mem_antidiagonal.mp hx, rw add_comm at this, exact ((le_of_add_le_right this.le).trans_lt $ not_le.mp h).ne } end end /-- If a formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : power_series R) (h : is_unit φ) : is_unit (constant_coeff R φ) := mv_power_series.is_unit_constant_coeff φ h /-- Split off the constant coefficient. -/ lemma eq_shift_mul_X_add_const (φ : power_series R) : φ = mk (λ p, coeff R (p + 1) φ) * X + C R (constant_coeff R φ) := begin ext (_ | n), { simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff, zero_add, mul_zero, ring_hom.map_mul], }, { simp only [coeff_succ_mul_X, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero, if_false, add_zero], } end /-- Split off the constant coefficient. -/ lemma eq_X_mul_shift_add_const (φ : power_series R) : φ = X * mk (λ p, coeff R (p + 1) φ) + C R (constant_coeff R φ) := begin ext (_ | n), { simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff, zero_add, zero_mul, ring_hom.map_mul], }, { simp only [coeff_succ_X_mul, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero, if_false, add_zero], } end section map variables {S : Type*} {T : Type*} [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) /-- The map between formal power series induced by a map on the coefficients.-/ def map : power_series R →+* power_series S := mv_power_series.map _ f @[simp] lemma map_id : (map (ring_hom.id R) : power_series R → power_series R) = id := rfl lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl @[simp] lemma coeff_map (n : ℕ) (φ : power_series R) : coeff S n (map f φ) = f (coeff R n φ) := rfl @[simp] lemma map_C (r : R) : map f (C _ r) = C _ (f r) := by { ext, simp [coeff_C, apply_ite f] } @[simp] lemma map_X : map f X = X := by { ext, simp [coeff_X, apply_ite f] } end map lemma X_pow_dvd_iff {n : ℕ} {φ : power_series R} : (X : power_series R)^n ∣ φ ↔ ∀ m, m < n → coeff R m φ = 0 := begin convert @mv_power_series.X_pow_dvd_iff unit R _ () n φ, apply propext, classical, split; intros h m hm, { rw finsupp.unique_single m, convert h _ hm }, { apply h, simpa only [finsupp.single_eq_same] using hm } end lemma X_dvd_iff {φ : power_series R} : (X : power_series R) ∣ φ ↔ constant_coeff R φ = 0 := begin rw [← pow_one (X : power_series R), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply], split; intro h, { exact h 0 zero_lt_one }, { intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) } end end semiring section comm_semiring variables [comm_semiring R] open finset nat /-- The ring homomorphism taking a power series `f(X)` to `f(aX)`. -/ noncomputable def rescale (a : R) : power_series R →+* power_series R := { to_fun := λ f, power_series.mk $ λ n, a^n * (power_series.coeff R n f), map_zero' := by { ext, simp only [linear_map.map_zero, power_series.coeff_mk, mul_zero], }, map_one' := by { ext1, simp only [mul_boole, power_series.coeff_mk, power_series.coeff_one], split_ifs, { rw [h, pow_zero], }, refl, }, map_add' := by { intros, ext, exact mul_add _ _ _, }, map_mul' := λ f g, by { ext, rw [power_series.coeff_mul, power_series.coeff_mk, power_series.coeff_mul, finset.mul_sum], apply sum_congr rfl, simp only [coeff_mk, prod.forall, nat.mem_antidiagonal], intros b c H, rw [←H, pow_add, mul_mul_mul_comm] }, } @[simp] lemma coeff_rescale (f : power_series R) (a : R) (n : ℕ) : coeff R n (rescale a f) = a^n * coeff R n f := coeff_mk n _ @[simp] lemma rescale_zero : rescale 0 = (C R).comp (constant_coeff R) := begin ext, simp only [function.comp_app, ring_hom.coe_comp, rescale, ring_hom.coe_mk, power_series.coeff_mk _ _, coeff_C], split_ifs, { simp only [h, one_mul, coeff_zero_eq_constant_coeff, pow_zero], }, { rw [zero_pow' n h, zero_mul], }, end lemma rescale_zero_apply : rescale 0 X = C R (constant_coeff R X) := by simp @[simp] lemma rescale_one : rescale 1 = ring_hom.id (power_series R) := by { ext, simp only [ring_hom.id_apply, rescale, one_pow, coeff_mk, one_mul, ring_hom.coe_mk], } lemma rescale_mk (f : ℕ → R) (a : R) : rescale a (mk f) = mk (λ n : ℕ, a^n * (f n)) := by { ext, rw [coeff_rescale, coeff_mk, coeff_mk], } lemma rescale_rescale (f : power_series R) (a b : R) : rescale b (rescale a f) = rescale (a * b) f := begin ext, repeat { rw coeff_rescale, }, rw [mul_pow, mul_comm _ (b^n), mul_assoc], end lemma rescale_mul (a b : R) : rescale (a * b) = (rescale b).comp (rescale a) := by { ext, simp [← rescale_rescale], } section trunc /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc (n : ℕ) (φ : power_series R) : R[X] := ∑ m in Ico 0 n, polynomial.monomial m (coeff R m φ) lemma coeff_trunc (m) (n) (φ : power_series R) : (trunc n φ).coeff m = if m < n then coeff R m φ else 0 := by simp [trunc, polynomial.coeff_sum, polynomial.coeff_monomial, nat.lt_succ_iff] @[simp] lemma trunc_zero (n) : trunc n (0 : power_series R) = 0 := polynomial.ext $ λ m, begin rw [coeff_trunc, linear_map.map_zero, polynomial.coeff_zero], split_ifs; refl end @[simp] lemma trunc_one (n) : trunc (n + 1) (1 : power_series R) = 1 := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H'; rw [polynomial.coeff_one], { subst m, rw [if_pos rfl] }, { symmetry, exact if_neg (ne.elim (ne.symm H')) }, { symmetry, refine if_neg _, rintro rfl, apply H, exact nat.zero_lt_succ _ } end @[simp] lemma trunc_C (n) (a : R) : trunc (n + 1) (C R a) = polynomial.C a := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_C, polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *} end @[simp] lemma trunc_add (n) (φ ψ : power_series R) : trunc n (φ + ψ) = trunc n φ + trunc n ψ := polynomial.ext $ λ m, begin simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add], split_ifs with H, {refl}, {rw [zero_add]} end end trunc end comm_semiring section ring variables [ring R] /-- Auxiliary function used for computing inverse of a power series -/ protected def inv.aux : R → power_series R → power_series R := mv_power_series.inv.aux lemma coeff_inv_aux (n : ℕ) (a : R) (φ : power_series R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := begin rw [coeff, inv.aux, mv_power_series.coeff_inv_aux], simp only [finsupp.single_eq_zero], split_ifs, {refl}, congr' 1, symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, by_cases H : j < n, { rw [if_pos H, if_pos], {refl}, split, { rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H }, { intro hh, rw lt_iff_not_ge at H, apply H, simpa [finsupp.single_eq_same] using hh () } }, { rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩, simpa [finsupp.single_eq_same] using not_lt.1 H } }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end /-- A formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : power_series R) (u : Rˣ) : power_series R := mv_power_series.inv_of_unit φ u lemma coeff_inv_of_unit (n : ℕ) (φ : power_series R) (u : Rˣ) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n ↑u⁻¹ φ @[simp] lemma constant_coeff_inv_of_unit (φ : power_series R) (u : Rˣ) : constant_coeff R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : power_series R) (u : Rˣ) (h : constant_coeff R φ = u) : φ * inv_of_unit φ u = 1 := mv_power_series.mul_inv_of_unit φ u $ h /-- Two ways of removing the constant coefficient of a power series are the same. -/ lemma sub_const_eq_shift_mul_X (φ : power_series R) : φ - C R (constant_coeff R φ) = power_series.mk (λ p, coeff R (p + 1) φ) * X := sub_eq_iff_eq_add.mpr (eq_shift_mul_X_add_const φ) lemma sub_const_eq_X_mul_shift (φ : power_series R) : φ - C R (constant_coeff R φ) = X * power_series.mk (λ p, coeff R (p + 1) φ) := sub_eq_iff_eq_add.mpr (eq_X_mul_shift_add_const φ) end ring section comm_ring variables {A : Type*} [comm_ring A] @[simp] lemma rescale_X (a : A) : rescale a X = C A a * X := begin ext, simp only [coeff_rescale, coeff_C_mul, coeff_X], split_ifs with h; simp [h], end lemma rescale_neg_one_X : rescale (-1 : A) X = -X := by rw [rescale_X, map_neg, map_one, neg_one_mul] /-- The ring homomorphism taking a power series `f(X)` to `f(-X)`. -/ noncomputable def eval_neg_hom : power_series A →+* power_series A := rescale (-1 : A) @[simp] lemma eval_neg_hom_X : eval_neg_hom (X : power_series A) = -X := rescale_neg_one_X end comm_ring section domain variables [ring R] lemma eq_zero_or_eq_zero_of_mul_eq_zero [no_zero_divisors R] (φ ψ : power_series R) (h : φ * ψ = 0) : φ = 0 ∨ ψ = 0 := begin rw or_iff_not_imp_left, intro H, have ex : ∃ m, coeff R m φ ≠ 0, { contrapose! H, exact ext H }, let m := nat.find ex, have hm₁ : coeff R m φ ≠ 0 := nat.find_spec ex, have hm₂ : ∀ k < m, ¬coeff R k φ ≠ 0 := λ k, nat.find_min ex, ext n, rw (coeff R n).map_zero, apply nat.strong_induction_on n, clear n, intros n ih, replace h := congr_arg (coeff R (m + n)) h, rw [linear_map.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h, { replace h := eq_zero_or_eq_zero_of_mul_eq_zero h, rw or_iff_not_imp_left at h, exact h hm₁ }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j < n, { rw [ih j hj, mul_zero] }, by_cases hi : i < m, { specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] }, rw finset.nat.mem_antidiagonal at hij, push_neg at hi hj, suffices : m < i, { have : m + n < i + j := add_lt_add_of_lt_of_le this hj, exfalso, exact ne_of_lt this hij.symm }, contrapose! hne, obtain rfl := le_antisymm hi hne, simpa [ne.def, prod.mk.inj_iff] using (add_right_inj m).mp hij }, { contrapose!, intro h, rw finset.nat.mem_antidiagonal } end instance [no_zero_divisors R] : no_zero_divisors (power_series R) := { eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero } instance [is_domain R] : is_domain (power_series R) := no_zero_divisors.to_is_domain _ end domain section is_domain variables [comm_ring R] [is_domain R] /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ lemma span_X_is_prime : (ideal.span ({X} : set (power_series R))).is_prime := begin suffices : ideal.span ({X} : set (power_series R)) = (constant_coeff R).ker, { rw this, exact ring_hom.ker_is_prime _ }, apply ideal.ext, intro φ, rw [ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff] end /-- The variable of the power series ring over an integral domain is prime.-/ lemma X_prime : prime (X : power_series R) := begin rw ← ideal.span_singleton_prime, { exact span_X_is_prime }, { intro h, simpa using congr_arg (coeff R 1) h } end lemma rescale_injective {a : R} (ha : a ≠ 0) : function.injective (rescale a) := begin intros p q h, rw power_series.ext_iff at *, intros n, specialize h n, rw [coeff_rescale, coeff_rescale, mul_eq_mul_left_iff] at h, apply h.resolve_right, intro h', exact ha (pow_eq_zero h'), end end is_domain section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] instance map.is_local_ring_hom : is_local_ring_hom (map f) := mv_power_series.map.is_local_ring_hom f variables [local_ring R] [local_ring S] instance : local_ring (power_series R) := mv_power_series.local_ring end local_ring section algebra variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A] theorem C_eq_algebra_map {r : R} : C R r = (algebra_map R (power_series R)) r := rfl theorem algebra_map_apply {r : R} : algebra_map R (power_series A) r = C A (algebra_map R A r) := mv_power_series.algebra_map_apply instance [nontrivial R] : nontrivial (subalgebra R (power_series R)) := mv_power_series.subalgebra.nontrivial end algebra section field variables {k : Type*} [field k] /-- The inverse 1/f of a power series f defined over a field -/ protected def inv : power_series k → power_series k := mv_power_series.inv instance : has_inv (power_series k) := ⟨power_series.inv⟩ lemma inv_eq_inv_aux (φ : power_series k) : φ⁻¹ = inv.aux (constant_coeff k φ)⁻¹ φ := rfl lemma coeff_inv (n) (φ : power_series k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff k φ)⁻¹ else - (constant_coeff k φ)⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff k φ)⁻¹ φ] @[simp] lemma constant_coeff_inv (φ : power_series k) : constant_coeff k (φ⁻¹) = (constant_coeff k φ)⁻¹ := mv_power_series.constant_coeff_inv φ lemma inv_eq_zero {φ : power_series k} : φ⁻¹ = 0 ↔ constant_coeff k φ = 0 := mv_power_series.inv_eq_zero @[simp] lemma zero_inv : (0 : power_series k)⁻¹ = 0 := mv_power_series.zero_inv @[simp, priority 1100] lemma inv_of_unit_eq (φ : power_series k) (h : constant_coeff k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := mv_power_series.inv_of_unit_eq _ _ @[simp] lemma inv_of_unit_eq' (φ : power_series k) (u : units k) (h : constant_coeff k φ = u) : inv_of_unit φ u = φ⁻¹ := mv_power_series.inv_of_unit_eq' φ _ h @[simp] protected lemma mul_inv_cancel (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ * φ⁻¹ = 1 := mv_power_series.mul_inv_cancel φ h @[simp] protected lemma inv_mul_cancel (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul_cancel φ h lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : power_series k} (h : constant_coeff k φ₃ ≠ 0) : φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ := mv_power_series.eq_mul_inv_iff_mul_eq h lemma eq_inv_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) : φ = ψ⁻¹ ↔ φ * ψ = 1 := mv_power_series.eq_inv_iff_mul_eq_one h lemma inv_eq_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := mv_power_series.inv_eq_iff_mul_eq_one h @[simp] protected lemma mul_inv_rev (φ ψ : power_series k) : (φ * ψ)⁻¹ = ψ⁻¹ * φ⁻¹ := mv_power_series.mul_inv_rev _ _ instance : inv_one_class (power_series k) := mv_power_series.inv_one_class @[simp] lemma C_inv (r : k) : (C k r)⁻¹ = C k r⁻¹ := mv_power_series.C_inv _ @[simp] lemma X_inv : (X : power_series k)⁻¹ = 0 := mv_power_series.X_inv _ @[simp] lemma smul_inv (r : k) (φ : power_series k) : (r • φ)⁻¹ = r⁻¹ • φ⁻¹ := mv_power_series.smul_inv _ _ end field end power_series namespace power_series variable {R : Type*} local attribute [instance, priority 1] classical.prop_decidable noncomputable theory section order_basic open multiplicity variables [semiring R] {φ : power_series R} lemma exists_coeff_ne_zero_iff_ne_zero : (∃ (n : ℕ), coeff R n φ ≠ 0) ↔ φ ≠ 0 := begin refine not_iff_not.mp _, push_neg, simp [power_series.ext_iff] end /-- The order of a formal power series `φ` is the greatest `n : part_enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ def order (φ : power_series R) : part_enat := if h : φ = 0 then ⊤ else nat.find (exists_coeff_ne_zero_iff_ne_zero.mpr h) /-- The order of the `0` power series is infinite.-/ @[simp] lemma order_zero : order (0 : power_series R) = ⊤ := dif_pos rfl lemma order_finite_iff_ne_zero : (order φ).dom ↔ φ ≠ 0 := begin simp only [order], split, { split_ifs with h h; intro H, { contrapose! H, simpa [←part.eq_none_iff'] }, { exact h } }, { intro h, simp [h] } end /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ lemma coeff_order (h : (order φ).dom) : coeff R (φ.order.get h) φ ≠ 0 := begin simp only [order, order_finite_iff_ne_zero.mp h, not_false_iff, dif_neg, part_enat.get_coe'], generalize_proofs h, exact nat.find_spec h end /-- If the `n`th coefficient of a formal power series is nonzero, then the order of the power series is less than or equal to `n`.-/ lemma order_le (n : ℕ) (h : coeff R n φ ≠ 0) : order φ ≤ n := begin have := exists.intro n h, rw [order, dif_neg], { simp only [part_enat.coe_le_coe, nat.find_le_iff], exact ⟨n, le_rfl, h⟩ }, { exact exists_coeff_ne_zero_iff_ne_zero.mp ⟨n, h⟩ } end /-- The `n`th coefficient of a formal power series is `0` if `n` is strictly smaller than the order of the power series.-/ lemma coeff_of_lt_order (n : ℕ) (h: ↑n < order φ) : coeff R n φ = 0 := by { contrapose! h, exact order_le _ h } /-- The `0` power series is the unique power series with infinite order.-/ @[simp] lemma order_eq_top {φ : power_series R} : φ.order = ⊤ ↔ φ = 0 := begin split, { intro h, ext n, rw [(coeff R n).map_zero, coeff_of_lt_order], simp [h] }, { rintros rfl, exact order_zero } end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma nat_le_order (φ : power_series R) (n : ℕ) (h : ∀ i < n, coeff R i φ = 0) : ↑n ≤ order φ := begin by_contra H, rw not_le at H, have : (order φ).dom := part_enat.dom_of_le_coe H.le, rw [← part_enat.coe_get this, part_enat.coe_lt_coe] at H, exact coeff_order this (h _ H) end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma le_order (φ : power_series R) (n : part_enat) (h : ∀ i : ℕ, ↑i < n → coeff R i φ = 0) : n ≤ order φ := begin induction n using part_enat.cases_on, { show _ ≤ _, rw [top_le_iff, order_eq_top], ext i, exact h _ (part_enat.coe_lt_top i) }, { apply nat_le_order, simpa only [part_enat.coe_lt_coe] using h } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq_nat {φ : power_series R} {n : ℕ} : order φ = n ↔ (coeff R n φ ≠ 0) ∧ (∀ i, i < n → coeff R i φ = 0) := begin rcases eq_or_ne φ 0 with rfl|hφ, { simpa using (part_enat.coe_ne_top _).symm }, simp [order, dif_neg hφ, nat.find_eq_iff] end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq {φ : power_series R} {n : part_enat} : order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff R i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff R i φ = 0) := begin induction n using part_enat.cases_on, { rw order_eq_top, split, { rintro rfl, split; intros, { exfalso, exact part_enat.coe_ne_top ‹_› ‹_› }, { exact (coeff _ _).map_zero } }, { rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (part_enat.coe_lt_top i) } }, { simpa [part_enat.coe_inj] using order_eq_nat } end /-- The order of the sum of two formal power series is at least the minimum of their orders.-/ lemma le_order_add (φ ψ : power_series R) : min (order φ) (order ψ) ≤ order (φ + ψ) := begin refine le_order _ _ _, simp [coeff_of_lt_order] {contextual := tt} end private lemma order_add_of_order_eq.aux (φ ψ : power_series R) (h : order φ ≠ order ψ) (H : order φ < order ψ) : order (φ + ψ) ≤ order φ ⊓ order ψ := begin suffices : order (φ + ψ) = order φ, { rw [le_inf_iff, this], exact ⟨le_rfl, le_of_lt H⟩ }, { rw order_eq, split, { intros i hi, rw ←hi at H, rw [(coeff _ _).map_add, coeff_of_lt_order i H, add_zero], exact (order_eq_nat.1 hi.symm).1 }, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order i hi, coeff_of_lt_order i (lt_trans hi H), zero_add] } } end /-- The order of the sum of two formal power series is the minimum of their orders if their orders differ.-/ lemma order_add_of_order_eq (φ ψ : power_series R) (h : order φ ≠ order ψ) : order (φ + ψ) = order φ ⊓ order ψ := begin refine le_antisymm _ (le_order_add _ _), by_cases H₁ : order φ < order ψ, { apply order_add_of_order_eq.aux _ _ h H₁ }, by_cases H₂ : order ψ < order φ, { simpa only [add_comm, inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ }, exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁)) end /-- The order of the product of two formal power series is at least the sum of their orders.-/ lemma order_mul_ge (φ ψ : power_series R) : order φ + order ψ ≤ order (φ * ψ) := begin apply le_order, intros n hn, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, by_cases hi : ↑i < order φ, { rw [coeff_of_lt_order i hi, zero_mul] }, by_cases hj : ↑j < order ψ, { rw [coeff_of_lt_order j hj, mul_zero] }, rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij, exfalso, apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add hi hj), rw [← nat.cast_add, hij] end /-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/ lemma order_monomial (n : ℕ) (a : R) [decidable (a = 0)] : order (monomial R n a) = if a = 0 then ⊤ else n := begin split_ifs with h, { rw [h, order_eq_top, linear_map.map_zero] }, { rw [order_eq], split; intros i hi, { rw [part_enat.coe_inj] at hi, rwa [hi, coeff_monomial_same] }, { rw [part_enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } } end /-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/ lemma order_monomial_of_ne_zero (n : ℕ) (a : R) (h : a ≠ 0) : order (monomial R n a) = n := by rw [order_monomial, if_neg h] /-- If `n` is strictly smaller than the order of `ψ`, then the `n`th coefficient of its product with any other power series is `0`. -/ lemma coeff_mul_of_lt_order {φ ψ : power_series R} {n : ℕ} (h : ↑n < ψ.order) : coeff R n (φ * ψ) = 0 := begin suffices : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, 0, rw [this, finset.sum_const_zero], rw [coeff_mul], apply finset.sum_congr rfl (λ x hx, _), refine mul_eq_zero_of_right (coeff R x.fst φ) (coeff_of_lt_order x.snd (lt_of_le_of_lt _ h)), rw finset.nat.mem_antidiagonal at hx, norm_cast, linarith, end lemma coeff_mul_one_sub_of_lt_order {R : Type*} [comm_ring R] {φ ψ : power_series R} (n : ℕ) (h : ↑n < ψ.order) : coeff R n (φ * (1 - ψ)) = coeff R n φ := by simp [coeff_mul_of_lt_order h, mul_sub] lemma coeff_mul_prod_one_sub_of_lt_order {R ι : Type*} [comm_ring R] (k : ℕ) (s : finset ι) (φ : power_series R) (f : ι → power_series R) : (∀ i ∈ s, ↑k < (f i).order) → coeff R k (φ * ∏ i in s, (1 - f i)) = coeff R k φ := begin apply finset.induction_on s, { simp }, { intros a s ha ih t, simp only [finset.mem_insert, forall_eq_or_imp] at t, rw [finset.prod_insert ha, ← mul_assoc, mul_right_comm, coeff_mul_one_sub_of_lt_order _ t.1], exact ih t.2 }, end -- TODO: link with `X_pow_dvd_iff` lemma X_pow_order_dvd (h : (order φ).dom) : X ^ ((order φ).get h) ∣ φ := begin refine ⟨power_series.mk (λ n, coeff R (n + (order φ).get h) φ), _⟩, ext n, simp only [coeff_mul, coeff_X_pow, coeff_mk, boole_mul, finset.sum_ite, finset.nat.filter_fst_eq_antidiagonal, finset.sum_const_zero, add_zero], split_ifs with hn hn, { simp [tsub_add_cancel_of_le hn] }, { simp only [finset.sum_empty], refine coeff_of_lt_order _ _, simpa [part_enat.coe_lt_iff] using λ _, hn } end lemma order_eq_multiplicity_X {R : Type*} [semiring R] (φ : power_series R) : order φ = multiplicity X φ := begin rcases eq_or_ne φ 0 with rfl|hφ, { simp }, induction ho : order φ using part_enat.cases_on with n, { simpa [hφ] using ho }, have hn : φ.order.get (order_finite_iff_ne_zero.mpr hφ) = n, { simp [ho] }, rw ←hn, refine le_antisymm (le_multiplicity_of_pow_dvd $ X_pow_order_dvd (order_finite_iff_ne_zero.mpr hφ)) (part_enat.find_le _ _ _), rintro ⟨ψ, H⟩, have := congr_arg (coeff R n) H, rw [← (ψ.commute_X.pow_right _).eq, coeff_mul_of_lt_order, ←hn] at this, { exact coeff_order _ this }, { rw [X_pow_eq, order_monomial], split_ifs, { exact part_enat.coe_lt_top _ }, { rw [←hn, part_enat.coe_lt_coe], exact nat.lt_succ_self _ } } end end order_basic section order_zero_ne_one variables [semiring R] [nontrivial R] /-- The order of the formal power series `1` is `0`.-/ @[simp] lemma order_one : order (1 : power_series R) = 0 := by simpa using order_monomial_of_ne_zero 0 (1:R) one_ne_zero /-- The order of the formal power series `X` is `1`.-/ @[simp] lemma order_X : order (X : power_series R) = 1 := by simpa only [nat.cast_one] using order_monomial_of_ne_zero 1 (1:R) one_ne_zero /-- The order of the formal power series `X^n` is `n`.-/ @[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series R)^n) = n := by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero } end order_zero_ne_one section order_is_domain -- TODO: generalize to `[semiring R] [no_zero_divisors R]` variables [comm_ring R] [is_domain R] /-- The order of the product of two formal power series over an integral domain is the sum of their orders.-/ lemma order_mul (φ ψ : power_series R) : order (φ * ψ) = order φ + order ψ := begin simp_rw [order_eq_multiplicity_X], exact multiplicity.mul X_prime end end order_is_domain end power_series namespace polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] (φ ψ : R[X]) /-- The natural inclusion from polynomials into formal power series.-/ instance coe_to_power_series : has_coe R[X] (power_series R) := ⟨λ φ, power_series.mk $ λ n, coeff φ n⟩ lemma coe_def : (φ : power_series R) = power_series.mk (coeff φ) := rfl @[simp, norm_cast] lemma coeff_coe (n) : power_series.coeff R n φ = coeff φ n := congr_arg (coeff φ) (finsupp.single_eq_same) @[simp, norm_cast] lemma coe_monomial (n : ℕ) (a : R) : (monomial n a : power_series R) = power_series.monomial R n a := by { ext, simp [coeff_coe, power_series.coeff_monomial, polynomial.coeff_monomial, eq_comm] } @[simp, norm_cast] lemma coe_zero : ((0 : R[X]) : power_series R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : R[X]) : power_series R) = 1 := begin have := coe_monomial 0 (1:R), rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_add : ((φ + ψ : R[X]) : power_series R) = φ + ψ := by { ext, simp } @[simp, norm_cast] lemma coe_mul : ((φ * ψ : R[X]) : power_series R) = φ * ψ := power_series.ext $ λ n, by simp only [coeff_coe, power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : R[X]) : power_series R) = power_series.C R a := begin have := coe_monomial 0 a, rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_bit0 : ((bit0 φ : R[X]) : power_series R) = bit0 (φ : power_series R) := coe_add φ φ @[simp, norm_cast] lemma coe_bit1 : ((bit1 φ : R[X]) : power_series R) = bit1 (φ : power_series R) := by rw [bit1, bit1, coe_add, coe_one, coe_bit0] @[simp, norm_cast] lemma coe_X : ((X : R[X]) : power_series R) = power_series.X := coe_monomial _ _ @[simp] lemma constant_coeff_coe : power_series.constant_coeff R φ = φ.coeff 0 := rfl variables (R) lemma coe_injective : function.injective (coe : R[X] → power_series R) := λ x y h, by { ext, simp_rw [←coeff_coe, h] } variables {R φ ψ} @[simp, norm_cast] lemma coe_inj : (φ : power_series R) = ψ ↔ φ = ψ := (coe_injective R).eq_iff @[simp] lemma coe_eq_zero_iff : (φ : power_series R) = 0 ↔ φ = 0 := by rw [←coe_zero, coe_inj] @[simp] lemma coe_eq_one_iff : (φ : power_series R) = 1 ↔ φ = 1 := by rw [←coe_one, coe_inj] variables (φ ψ) /-- The coercion from polynomials to power series as a ring homomorphism. -/ def coe_to_power_series.ring_hom : R[X] →+* power_series R := { to_fun := (coe : R[X] → power_series R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } @[simp] lemma coe_to_power_series.ring_hom_apply : coe_to_power_series.ring_hom φ = φ := rfl @[simp, norm_cast] lemma coe_pow (n : ℕ): ((φ ^ n : R[X]) : power_series R) = (φ : power_series R) ^ n := coe_to_power_series.ring_hom.map_pow _ _ variables (A : Type*) [semiring A] [algebra R A] /-- The coercion from polynomials to power series as an algebra homomorphism. -/ def coe_to_power_series.alg_hom : R[X] →ₐ[R] power_series A := { commutes' := λ r, by simp [algebra_map_apply, power_series.algebra_map_apply], ..(power_series.map (algebra_map R A)).comp coe_to_power_series.ring_hom } @[simp] lemma coe_to_power_series.alg_hom_apply : (coe_to_power_series.alg_hom A φ) = power_series.map (algebra_map R A) ↑φ := rfl end polynomial namespace power_series variables {R A : Type*} [comm_semiring R] [comm_semiring A] [algebra R A] (f : power_series R) instance algebra_polynomial : algebra R[X] (power_series A) := ring_hom.to_algebra (polynomial.coe_to_power_series.alg_hom A).to_ring_hom instance algebra_power_series : algebra (power_series R) (power_series A) := (map (algebra_map R A)).to_algebra @[priority 100] -- see Note [lower instance priority] instance algebra_polynomial' {A : Type*} [comm_semiring A] [algebra R A[X]] : algebra R (power_series A) := ring_hom.to_algebra $ polynomial.coe_to_power_series.ring_hom.comp (algebra_map R A[X]) variables (A) lemma algebra_map_apply' (p : R[X]) : algebra_map R[X] (power_series A) p = map (algebra_map R A) p := rfl lemma algebra_map_apply'' : algebra_map (power_series R) (power_series A) f = map (algebra_map R A) f := rfl end power_series
/* Copyright 2020, 2021 Evandro Chagas Ribeiro da Rosa <[email protected]> * Copyright 2020, 2021 Rafael de Santiago <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../include/ket" #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> using namespace ket; context::context() : process_on_top{process_on_top_stack.top()}, ps{process_stack.top()} {} bool context::has_executed() const { return ps->has_executed(); } bool context::in_scope() const { return *process_on_top; } std::string context::get_return(const std::string& arg) const { if (not ps->has_executed()) return "NA"; std::stringstream json_file; json_file << ps->get_result_str(); boost::property_tree::ptree pt; boost::property_tree::read_json(json_file, pt); return pt.get<std::string>(arg); } std::string context::get_json() const { if (not ps->has_executed()) return "NA"; return ps->get_result_str(); }
function findpkgpath() for depot in DEPOT_PATH path = joinpath(depot, "dev", "Pkg", "src", "Pkg.jl") isfile(path) && return path end error("Pkg.jl is not checked out at `dev/Pkg` in a depot (e.g., `~/.julia/dev/Pkg`).") end code = """ const pkgpath = $(repr(findpkgpath())) """ write(joinpath(@__DIR__, "deps.jl"), code)
(* Title: Jinja/Compiler/TypeComp.thy Author: Tobias Nipkow Copyright TUM 2003 *) section \<open>Preservation of Well-Typedness\<close> theory TypeComp imports Compiler "../BV/BVSpec" begin (*<*) declare nth_append[simp] (*>*) locale TC0 = fixes P :: "J\<^sub>1_prog" and mxl :: nat begin definition "ty E e = (THE T. P,E \<turnstile>\<^sub>1 e :: T)" definition "ty\<^sub>l E A' = map (\<lambda>i. if i \<in> A' \<and> i < size E then OK(E!i) else Err) [0..<mxl]" definition "ty\<^sub>i' ST E A = (case A of None \<Rightarrow> None | \<lfloor>A'\<rfloor> \<Rightarrow> Some(ST, ty\<^sub>l E A'))" definition "after E A ST e = ty\<^sub>i' (ty E e # ST) E (A \<squnion> \<A> e)" end lemma (in TC0) ty_def2 [simp]: "P,E \<turnstile>\<^sub>1 e :: T \<Longrightarrow> ty E e = T" (*<*)by(unfold ty_def) (blast intro: the_equality WT\<^sub>1_unique)(*>*) lemma (in TC0) [simp]: "ty\<^sub>i' ST E None = None" (*<*)by (simp add: ty\<^sub>i'_def)(*>*) lemma (in TC0) ty\<^sub>l_app_diff[simp]: "ty\<^sub>l (E@[T]) (A - {size E}) = ty\<^sub>l E A" (*<*)by(auto simp add:ty\<^sub>l_def hyperset_defs)(*>*) lemma (in TC0) ty\<^sub>i'_app_diff[simp]: "ty\<^sub>i' ST (E @ [T]) (A \<ominus> size E) = ty\<^sub>i' ST E A" (*<*)by(auto simp add:ty\<^sub>i'_def hyperset_defs)(*>*) lemma (in TC0) ty\<^sub>l_antimono: "A \<subseteq> A' \<Longrightarrow> P \<turnstile> ty\<^sub>l E A' [\<le>\<^sub>\<top>] ty\<^sub>l E A" (*<*)by(auto simp:ty\<^sub>l_def list_all2_conv_all_nth)(*>*) lemma (in TC0) ty\<^sub>i'_antimono: "A \<subseteq> A' \<Longrightarrow> P \<turnstile> ty\<^sub>i' ST E \<lfloor>A'\<rfloor> \<le>' ty\<^sub>i' ST E \<lfloor>A\<rfloor>" (*<*)by(auto simp:ty\<^sub>i'_def ty\<^sub>l_def list_all2_conv_all_nth)(*>*) lemma (in TC0) ty\<^sub>l_env_antimono: "P \<turnstile> ty\<^sub>l (E@[T]) A [\<le>\<^sub>\<top>] ty\<^sub>l E A" (*<*)by(auto simp:ty\<^sub>l_def list_all2_conv_all_nth)(*>*) lemma (in TC0) ty\<^sub>i'_env_antimono: "P \<turnstile> ty\<^sub>i' ST (E@[T]) A \<le>' ty\<^sub>i' ST E A" (*<*)by(auto simp:ty\<^sub>i'_def ty\<^sub>l_def list_all2_conv_all_nth)(*>*) lemma (in TC0) ty\<^sub>i'_incr: "P \<turnstile> ty\<^sub>i' ST (E @ [T]) \<lfloor>insert (size E) A\<rfloor> \<le>' ty\<^sub>i' ST E \<lfloor>A\<rfloor>" (*<*)by(auto simp:ty\<^sub>i'_def ty\<^sub>l_def list_all2_conv_all_nth)(*>*) lemma (in TC0) ty\<^sub>l_incr: "P \<turnstile> ty\<^sub>l (E @ [T]) (insert (size E) A) [\<le>\<^sub>\<top>] ty\<^sub>l E A" (*<*)by(auto simp: hyperset_defs ty\<^sub>l_def list_all2_conv_all_nth)(*>*) lemma (in TC0) ty\<^sub>l_in_types: "set E \<subseteq> types P \<Longrightarrow> ty\<^sub>l E A \<in> nlists mxl (err (types P))" (*<*)by(auto simp add:ty\<^sub>l_def intro!:nlistsI dest!: nth_mem)(*>*) locale TC1 = TC0 begin primrec compT :: "ty list \<Rightarrow> nat hyperset \<Rightarrow> ty list \<Rightarrow> expr\<^sub>1 \<Rightarrow> ty\<^sub>i' list" and compTs :: "ty list \<Rightarrow> nat hyperset \<Rightarrow> ty list \<Rightarrow> expr\<^sub>1 list \<Rightarrow> ty\<^sub>i' list" where "compT E A ST (new C) = []" | "compT E A ST (Cast C e) = compT E A ST e @ [after E A ST e]" | "compT E A ST (Val v) = []" | "compT E A ST (e\<^sub>1 \<guillemotleft>bop\<guillemotright> e\<^sub>2) = (let ST\<^sub>1 = ty E e\<^sub>1#ST; A\<^sub>1 = A \<squnion> \<A> e\<^sub>1 in compT E A ST e\<^sub>1 @ [after E A ST e\<^sub>1] @ compT E A\<^sub>1 ST\<^sub>1 e\<^sub>2 @ [after E A\<^sub>1 ST\<^sub>1 e\<^sub>2])" | "compT E A ST (Var i) = []" | "compT E A ST (i := e) = compT E A ST e @ [after E A ST e, ty\<^sub>i' ST E (A \<squnion> \<A> e \<squnion> \<lfloor>{i}\<rfloor>)]" | "compT E A ST (e\<bullet>F{D}) = compT E A ST e @ [after E A ST e]" | "compT E A ST (e\<^sub>1\<bullet>F{D} := e\<^sub>2) = (let ST\<^sub>1 = ty E e\<^sub>1#ST; A\<^sub>1 = A \<squnion> \<A> e\<^sub>1; A\<^sub>2 = A\<^sub>1 \<squnion> \<A> e\<^sub>2 in compT E A ST e\<^sub>1 @ [after E A ST e\<^sub>1] @ compT E A\<^sub>1 ST\<^sub>1 e\<^sub>2 @ [after E A\<^sub>1 ST\<^sub>1 e\<^sub>2] @ [ty\<^sub>i' ST E A\<^sub>2])" | "compT E A ST {i:T; e} = compT (E@[T]) (A\<ominus>i) ST e" | "compT E A ST (e\<^sub>1;;e\<^sub>2) = (let A\<^sub>1 = A \<squnion> \<A> e\<^sub>1 in compT E A ST e\<^sub>1 @ [after E A ST e\<^sub>1, ty\<^sub>i' ST E A\<^sub>1] @ compT E A\<^sub>1 ST e\<^sub>2)" | "compT E A ST (if (e) e\<^sub>1 else e\<^sub>2) = (let A\<^sub>0 = A \<squnion> \<A> e; \<tau> = ty\<^sub>i' ST E A\<^sub>0 in compT E A ST e @ [after E A ST e, \<tau>] @ compT E A\<^sub>0 ST e\<^sub>1 @ [after E A\<^sub>0 ST e\<^sub>1, \<tau>] @ compT E A\<^sub>0 ST e\<^sub>2)" | "compT E A ST (while (e) c) = (let A\<^sub>0 = A \<squnion> \<A> e; A\<^sub>1 = A\<^sub>0 \<squnion> \<A> c; \<tau> = ty\<^sub>i' ST E A\<^sub>0 in compT E A ST e @ [after E A ST e, \<tau>] @ compT E A\<^sub>0 ST c @ [after E A\<^sub>0 ST c, ty\<^sub>i' ST E A\<^sub>1, ty\<^sub>i' ST E A\<^sub>0])" | "compT E A ST (throw e) = compT E A ST e @ [after E A ST e]" | "compT E A ST (e\<bullet>M(es)) = compT E A ST e @ [after E A ST e] @ compTs E (A \<squnion> \<A> e) (ty E e # ST) es" | "compT E A ST (try e\<^sub>1 catch(C i) e\<^sub>2) = compT E A ST e\<^sub>1 @ [after E A ST e\<^sub>1] @ [ty\<^sub>i' (Class C#ST) E A, ty\<^sub>i' ST (E@[Class C]) (A \<squnion> \<lfloor>{i}\<rfloor>)] @ compT (E@[Class C]) (A \<squnion> \<lfloor>{i}\<rfloor>) ST e\<^sub>2" | "compTs E A ST [] = []" | "compTs E A ST (e#es) = compT E A ST e @ [after E A ST e] @ compTs E (A \<squnion> (\<A> e)) (ty E e # ST) es" definition compT\<^sub>a :: "ty list \<Rightarrow> nat hyperset \<Rightarrow> ty list \<Rightarrow> expr\<^sub>1 \<Rightarrow> ty\<^sub>i' list" where "compT\<^sub>a E A ST e = compT E A ST e @ [after E A ST e]" end lemma compE\<^sub>2_not_Nil[simp]: "compE\<^sub>2 e \<noteq> []" (*<*)by(induct e) auto(*>*) lemma (in TC1) compT_sizes[simp]: shows "\<And>E A ST. size(compT E A ST e) = size(compE\<^sub>2 e) - 1" and "\<And>E A ST. size(compTs E A ST es) = size(compEs\<^sub>2 es)" (*<*) by(induct e and es rule: compE\<^sub>2.induct compEs\<^sub>2.induct) (auto split:bop.splits nat_diff_split) (*>*) lemma (in TC1) [simp]: "\<And>ST E. \<lfloor>\<tau>\<rfloor> \<notin> set (compT E None ST e)" and [simp]: "\<And>ST E. \<lfloor>\<tau>\<rfloor> \<notin> set (compTs E None ST es)" (*<*)by(induct e and es rule: compT.induct compTs.induct) (simp_all add:after_def)(*>*) lemma (in TC0) pair_eq_ty\<^sub>i'_conv: "(\<lfloor>(ST, LT)\<rfloor> = ty\<^sub>i' ST\<^sub>0 E A) = (case A of None \<Rightarrow> False | Some A \<Rightarrow> (ST = ST\<^sub>0 \<and> LT = ty\<^sub>l E A))" (*<*)by(simp add:ty\<^sub>i'_def)(*>*) lemma (in TC0) pair_conv_ty\<^sub>i': "\<lfloor>(ST, ty\<^sub>l E A)\<rfloor> = ty\<^sub>i' ST E \<lfloor>A\<rfloor>" (*<*)by(simp add:ty\<^sub>i'_def)(*>*) (*<*) declare (in TC0) ty\<^sub>i'_antimono [intro!] after_def[simp] pair_conv_ty\<^sub>i'[simp] pair_eq_ty\<^sub>i'_conv[simp] (*>*) lemma (in TC1) compT_LT_prefix: "\<And>E A ST\<^sub>0. \<lbrakk> \<lfloor>(ST,LT)\<rfloor> \<in> set(compT E A ST\<^sub>0 e); \<B> e (size E) \<rbrakk> \<Longrightarrow> P \<turnstile> \<lfloor>(ST,LT)\<rfloor> \<le>' ty\<^sub>i' ST E A" and "\<And>E A ST\<^sub>0. \<lbrakk> \<lfloor>(ST,LT)\<rfloor> \<in> set(compTs E A ST\<^sub>0 es); \<B>s es (size E) \<rbrakk> \<Longrightarrow> P \<turnstile> \<lfloor>(ST,LT)\<rfloor> \<le>' ty\<^sub>i' ST E A" (*<*) proof(induct e and es rule: compT.induct compTs.induct) case FAss thus ?case by(fastforce simp:hyperset_defs elim!:sup_state_opt_trans) next case BinOp thus ?case by(fastforce simp:hyperset_defs elim!:sup_state_opt_trans split:bop.splits) next case Seq thus ?case by(fastforce simp:hyperset_defs elim!:sup_state_opt_trans) next case While thus ?case by(fastforce simp:hyperset_defs elim!:sup_state_opt_trans) next case Cond thus ?case by(fastforce simp:hyperset_defs elim!:sup_state_opt_trans) next case Block thus ?case by(force simp add:hyperset_defs ty\<^sub>i'_def simp del:pair_conv_ty\<^sub>i' elim!:sup_state_opt_trans) next case Call thus ?case by(fastforce simp:hyperset_defs elim!:sup_state_opt_trans) next case Cons_exp thus ?case by(fastforce simp:hyperset_defs elim!:sup_state_opt_trans) next case TryCatch thus ?case by(fastforce simp:hyperset_defs intro!:(* ty\<^sub>i'_env_antimono *) ty\<^sub>i'_incr elim!:sup_state_opt_trans) qed (auto simp:hyperset_defs) declare (in TC0) ty\<^sub>i'_antimono [rule del] after_def[simp del] pair_conv_ty\<^sub>i'[simp del] pair_eq_ty\<^sub>i'_conv[simp del] (*>*) lemma (in TC0) after_in_states: assumes wf: "wf_prog p P" and wt: "P,E \<turnstile>\<^sub>1 e :: T" and Etypes: "set E \<subseteq> types P" and STtypes: "set ST \<subseteq> types P" and stack: "size ST + max_stack e \<le> mxs" shows "OK (after E A ST e) \<in> states P mxs mxl" (*<*) proof - have "size ST + 1 \<le> mxs" using max_stack1[of e] wt stack by fastforce then show ?thesis using assms by(simp add: after_def ty\<^sub>i'_def JVM_states_unfold ty\<^sub>l_in_types) (blast intro!:nlistsI WT\<^sub>1_is_type) qed (*>*) lemma (in TC0) OK_ty\<^sub>i'_in_statesI[simp]: "\<lbrakk> set E \<subseteq> types P; set ST \<subseteq> types P; size ST \<le> mxs \<rbrakk> \<Longrightarrow> OK (ty\<^sub>i' ST E A) \<in> states P mxs mxl" (*<*) by(simp add:ty\<^sub>i'_def JVM_states_unfold ty\<^sub>l_in_types) (blast intro!:nlistsI) (*>*) lemma is_class_type_aux: "is_class P C \<Longrightarrow> is_type P (Class C)" (*<*)by(simp)(*>*) (*<*) declare is_type_simps[simp del] subsetI[rule del] (*>*) theorem (in TC1) compT_states: assumes wf: "wf_prog p P" shows "\<And>E T A ST. \<lbrakk> P,E \<turnstile>\<^sub>1 e :: T; set E \<subseteq> types P; set ST \<subseteq> types P; size ST + max_stack e \<le> mxs; size E + max_vars e \<le> mxl \<rbrakk> \<Longrightarrow> OK ` set(compT E A ST e) \<subseteq> states P mxs mxl" (*<*)(is "\<And>E T A ST. PROP ?P e E T A ST")(*>*) and "\<And>E Ts A ST. \<lbrakk> P,E \<turnstile>\<^sub>1 es[::]Ts; set E \<subseteq> types P; set ST \<subseteq> types P; size ST + max_stacks es \<le> mxs; size E + max_varss es \<le> mxl \<rbrakk> \<Longrightarrow> OK ` set(compTs E A ST es) \<subseteq> states P mxs mxl" (*<*)(is "\<And>E Ts A ST. PROP ?Ps es E Ts A ST") proof(induct e and es rule: compT.induct compTs.induct) case new thus ?case by(simp) next case (Cast C e) thus ?case by (auto simp:after_in_states[OF wf]) next case Val thus ?case by(simp) next case Var thus ?case by(simp) next case LAss thus ?case by(auto simp:after_in_states[OF wf]) next case FAcc thus ?case by(auto simp:after_in_states[OF wf]) next case FAss thus ?case by(auto simp:image_Un WT\<^sub>1_is_type[OF wf] after_in_states[OF wf]) next case Seq thus ?case by(auto simp:image_Un after_in_states[OF wf]) next case BinOp thus ?case by(auto simp:image_Un WT\<^sub>1_is_type[OF wf] after_in_states[OF wf]) next case Cond thus ?case by(force simp:image_Un WT\<^sub>1_is_type[OF wf] after_in_states[OF wf]) next case While thus ?case by(auto simp:image_Un WT\<^sub>1_is_type[OF wf] after_in_states[OF wf]) next case Block thus ?case by(auto) next case (TryCatch e\<^sub>1 C i e\<^sub>2) moreover have "size ST + 1 \<le> mxs" using TryCatch.prems max_stack1[of e\<^sub>1] by auto ultimately show ?case by(auto simp:image_Un WT\<^sub>1_is_type[OF wf] after_in_states[OF wf] is_class_type_aux) next case Nil_exp thus ?case by simp next case Cons_exp thus ?case by(auto simp:image_Un WT\<^sub>1_is_type[OF wf] after_in_states[OF wf]) next case throw thus ?case by(auto simp: WT\<^sub>1_is_type[OF wf] after_in_states[OF wf]) next case Call thus ?case by(auto simp:image_Un WT\<^sub>1_is_type[OF wf] after_in_states[OF wf]) qed declare is_type_simps[simp] subsetI[intro!] (*>*) definition shift :: "nat \<Rightarrow> ex_table \<Rightarrow> ex_table" where "shift n xt \<equiv> map (\<lambda>(from,to,C,handler,depth). (from+n,to+n,C,handler+n,depth)) xt" lemma [simp]: "shift n [] = []" (*<*)by(simp add:shift_def)(*>*) lemma [simp]: "shift n (xt\<^sub>1 @ xt\<^sub>2) = shift n xt\<^sub>1 @ shift n xt\<^sub>2" (*<*)by(simp add:shift_def)(*>*) lemma [simp]: "shift m (shift n xt) = shift (m+n) xt" (*<*)by(induct xt)(auto simp:shift_def)(*>*) lemma [simp]: "pcs (shift n xt) = {pc+n|pc. pc \<in> pcs xt}" (*<*) proof - { fix x f t C h d assume "(f,t,C,h,d) \<in> set xt" and "f + n \<le> x" and "x < t + n" then have "\<exists>pc. x = pc + n \<and> (\<exists>x\<in>set xt. pc \<in> (case x of (f, t, C, h, d) \<Rightarrow> {f..<t}))" by(rule_tac x = "x-n" in exI) (force split:nat_diff_split) } then show ?thesis by(auto simp:shift_def pcs_def) fast qed (*>*) lemma shift_compxE\<^sub>2: shows "\<And>pc pc' d. shift pc (compxE\<^sub>2 e pc' d) = compxE\<^sub>2 e (pc' + pc) d" and "\<And>pc pc' d. shift pc (compxEs\<^sub>2 es pc' d) = compxEs\<^sub>2 es (pc' + pc) d" (*<*) by(induct e and es rule: compxE\<^sub>2.induct compxEs\<^sub>2.induct) (auto simp:shift_def ac_simps) (*>*) lemma compxE\<^sub>2_size_convs[simp]: shows "n \<noteq> 0 \<Longrightarrow> compxE\<^sub>2 e n d = shift n (compxE\<^sub>2 e 0 d)" and "n \<noteq> 0 \<Longrightarrow> compxEs\<^sub>2 es n d = shift n (compxEs\<^sub>2 es 0 d)" (*<*)by(simp_all add:shift_compxE\<^sub>2)(*>*) locale TC2 = TC1 + fixes T\<^sub>r :: ty and mxs :: pc begin definition wt_instrs :: "instr list \<Rightarrow> ex_table \<Rightarrow> ty\<^sub>i' list \<Rightarrow> bool" ("(\<turnstile> _, _ /[::]/ _)" [0,0,51] 50) where "\<turnstile> is,xt [::] \<tau>s \<longleftrightarrow> size is < size \<tau>s \<and> pcs xt \<subseteq> {0..<size is} \<and> (\<forall>pc< size is. P,T\<^sub>r,mxs,size \<tau>s,xt \<turnstile> is!pc,pc :: \<tau>s)" end notation TC2.wt_instrs ("(_,_,_ \<turnstile>/ _, _ /[::]/ _)" [50,50,50,50,50,51] 50) (*<*) lemmas (in TC2) wt_defs = wt_instrs_def wt_instr_def app_def eff_def norm_eff_def (*>*) lemma (in TC2) [simp]: "\<tau>s \<noteq> [] \<Longrightarrow> \<turnstile> [],[] [::] \<tau>s" (*<*) by (simp add: wt_defs) (*>*) lemma [simp]: "eff i P pc et None = []" (*<*)by (simp add: Effect.eff_def)(*>*) (*<*) declare split_comp_eq[simp del] (*>*) lemma wt_instr_appR: "\<lbrakk> P,T,m,mpc,xt \<turnstile> is!pc,pc :: \<tau>s; pc < size is; size is < size \<tau>s; mpc \<le> size \<tau>s; mpc \<le> mpc' \<rbrakk> \<Longrightarrow> P,T,m,mpc',xt \<turnstile> is!pc,pc :: \<tau>s@\<tau>s'" (*<*)by (fastforce simp:wt_instr_def app_def)(*>*) lemma relevant_entries_shift [simp]: "relevant_entries P i (pc+n) (shift n xt) = shift n (relevant_entries P i pc xt)" (*<*) proof(induct xt) case Nil then show ?case by (simp add: relevant_entries_def shift_def) next case (Cons a xt) then show ?case by (auto simp add: relevant_entries_def shift_def is_relevant_entry_def) qed (*>*) lemma [simp]: "xcpt_eff i P (pc+n) \<tau> (shift n xt) = map (\<lambda>(pc,\<tau>). (pc + n, \<tau>)) (xcpt_eff i P pc \<tau> xt)" (*<*) proof - obtain ST LT where "\<tau> = (ST, LT)" by(cases \<tau>) simp then show ?thesis by(simp add: xcpt_eff_def) (auto simp add: shift_def) qed (*>*) lemma [simp]: "app\<^sub>i (i, P, pc, m, T, \<tau>) \<Longrightarrow> eff i P (pc+n) (shift n xt) (Some \<tau>) = map (\<lambda>(pc,\<tau>). (pc+n,\<tau>)) (eff i P pc xt (Some \<tau>))" (*<*)by(cases "i") (auto simp add:eff_def norm_eff_def)(*>*) lemma [simp]: "xcpt_app i P (pc+n) mxs (shift n xt) \<tau> = xcpt_app i P pc mxs xt \<tau>" (*<*)by (simp add: xcpt_app_def) (auto simp add: shift_def)(*>*) lemma wt_instr_appL: assumes "P,T,m,mpc,xt \<turnstile> i,pc :: \<tau>s" and "pc < size \<tau>s" and "mpc \<le> size \<tau>s" shows "P,T,m,mpc + size \<tau>s',shift (size \<tau>s') xt \<turnstile> i,pc+size \<tau>s' :: \<tau>s'@\<tau>s" (*<*) proof - let ?t = "(\<tau>s'@\<tau>s)!(pc+size \<tau>s')" show ?thesis proof(cases ?t) case (Some \<tau>) obtain ST LT where [simp]: "\<tau> = (ST, LT)" by(cases \<tau>) simp have "app\<^sub>i (i, P, pc + length \<tau>s', m, T, \<tau>)" using Some assms by(cases "i") (auto simp:wt_instr_def app_def) moreover { fix pc' \<tau>' assume "(pc',\<tau>') \<in> set (eff i P pc xt ?t)" then have "P \<turnstile> \<tau>' \<le>' \<tau>s!pc'" and "pc' < mpc" using Some assms by(auto simp:wt_instr_def app_def) } ultimately show ?thesis using Some assms by(fastforce simp:wt_instr_def app_def) qed (auto simp:wt_instr_def app_def) qed (*>*) lemma wt_instr_Cons: assumes wti: "P,T,m,mpc - 1,[] \<turnstile> i,pc - 1 :: \<tau>s" and pcl: "0 < pc" and mpcl: "0 < mpc" and pcu: "pc < size \<tau>s + 1" and mpcu: "mpc \<le> size \<tau>s + 1" shows "P,T,m,mpc,[] \<turnstile> i,pc :: \<tau>#\<tau>s" (*<*) proof - have "pc - 1 < length \<tau>s" using pcl pcu by arith moreover have "mpc - 1 \<le> length \<tau>s" using mpcl mpcu by arith ultimately have "P,T,m,mpc - 1 + length [\<tau>],shift (length [\<tau>]) [] \<turnstile> i,pc - 1 + length [\<tau>] :: [\<tau>] @ \<tau>s" by(rule wt_instr_appL[where \<tau>s' = "[\<tau>]", OF wti]) then show ?thesis using pcl mpcl by (simp split:nat_diff_split_asm) qed (*>*) lemma wt_instr_append: assumes wti: "P,T,m,mpc - size \<tau>s',[] \<turnstile> i,pc - size \<tau>s' :: \<tau>s" and pcl: "size \<tau>s' \<le> pc" and mpcl: "size \<tau>s' \<le> mpc" and pcu: "pc < size \<tau>s + size \<tau>s'" and mpcu: "mpc \<le> size \<tau>s + size \<tau>s'" shows "P,T,m,mpc,[] \<turnstile> i,pc :: \<tau>s'@\<tau>s" (*<*) proof - have "pc - length \<tau>s' < length \<tau>s" using pcl pcu by arith moreover have "mpc - length \<tau>s' \<le> length \<tau>s" using mpcl mpcu by arith thm wt_instr_appL[where \<tau>s' = "\<tau>s'", OF wti] ultimately have "P,T,m,mpc - length \<tau>s' + length \<tau>s',shift (length \<tau>s') [] \<turnstile> i,pc - length \<tau>s' + length \<tau>s' :: \<tau>s' @ \<tau>s" by(rule wt_instr_appL[where \<tau>s' = "\<tau>s'", OF wti]) then show ?thesis using pcl mpcl by (simp split:nat_diff_split_asm) qed (*>*) lemma xcpt_app_pcs: "pc \<notin> pcs xt \<Longrightarrow> xcpt_app i P pc mxs xt \<tau>" (*<*) by (auto simp add: xcpt_app_def relevant_entries_def is_relevant_entry_def pcs_def) (*>*) lemma xcpt_eff_pcs: "pc \<notin> pcs xt \<Longrightarrow> xcpt_eff i P pc \<tau> xt = []" (*<*) by (cases \<tau>) (auto simp add: is_relevant_entry_def xcpt_eff_def relevant_entries_def pcs_def intro!: filter_False) (*>*) lemma pcs_shift: "pc < n \<Longrightarrow> pc \<notin> pcs (shift n xt)" (*<*)by (auto simp add: shift_def pcs_def)(*>*) lemma wt_instr_appRx: "\<lbrakk> P,T,m,mpc,xt \<turnstile> is!pc,pc :: \<tau>s; pc < size is; size is < size \<tau>s; mpc \<le> size \<tau>s \<rbrakk> \<Longrightarrow> P,T,m,mpc,xt @ shift (size is) xt' \<turnstile> is!pc,pc :: \<tau>s" (*<*)by (auto simp:wt_instr_def eff_def app_def xcpt_app_pcs xcpt_eff_pcs)(*>*) lemma wt_instr_appLx: "\<lbrakk> P,T,m,mpc,xt \<turnstile> i,pc :: \<tau>s; pc \<notin> pcs xt' \<rbrakk> \<Longrightarrow> P,T,m,mpc,xt'@xt \<turnstile> i,pc :: \<tau>s" (*<*)by (auto simp:wt_instr_def app_def eff_def xcpt_app_pcs xcpt_eff_pcs)(*>*) lemma (in TC2) wt_instrs_extR: "\<turnstile> is,xt [::] \<tau>s \<Longrightarrow> \<turnstile> is,xt [::] \<tau>s @ \<tau>s'" (*<*)by(auto simp add:wt_instrs_def wt_instr_appR)(*>*) lemma (in TC2) wt_instrs_ext: assumes wt\<^sub>1: "\<turnstile> is\<^sub>1,xt\<^sub>1 [::] \<tau>s\<^sub>1@\<tau>s\<^sub>2" and wt\<^sub>2: "\<turnstile> is\<^sub>2,xt\<^sub>2 [::] \<tau>s\<^sub>2" and \<tau>s_size: "size \<tau>s\<^sub>1 = size is\<^sub>1" shows "\<turnstile> is\<^sub>1@is\<^sub>2, xt\<^sub>1 @ shift (size is\<^sub>1) xt\<^sub>2 [::] \<tau>s\<^sub>1@\<tau>s\<^sub>2" (*<*) proof - let ?is = "is\<^sub>1@is\<^sub>2" and ?xt = "xt\<^sub>1 @ shift (size is\<^sub>1) xt\<^sub>2" and ?\<tau>s = "\<tau>s\<^sub>1@\<tau>s\<^sub>2" have "size ?is < size ?\<tau>s" using wt\<^sub>2 \<tau>s_size by(fastforce simp:wt_instrs_def) moreover have "pcs ?xt \<subseteq> {0..<size ?is}" using wt\<^sub>1 wt\<^sub>2 by(fastforce simp:wt_instrs_def) moreover { fix pc assume pc: "pc<size ?is" have "P,T\<^sub>r,mxs,size ?\<tau>s,?xt \<turnstile> ?is!pc,pc :: ?\<tau>s" proof(cases "pc < length is\<^sub>1") case True then show ?thesis using wt\<^sub>1 pc by(fastforce simp: wt_instrs_def wt_instr_appRx) next case False then have "pc - length is\<^sub>1 < length is\<^sub>2" using pc by fastforce then have "P,T\<^sub>r,mxs,length \<tau>s\<^sub>2,xt\<^sub>2 \<turnstile> is\<^sub>2 ! (pc - length is\<^sub>1),pc - length is\<^sub>1 :: \<tau>s\<^sub>2" using wt\<^sub>2 by(clarsimp simp: wt_instrs_def) moreover have "pc - length is\<^sub>1 < length \<tau>s\<^sub>2" using pc wt\<^sub>2 by(clarsimp simp: wt_instrs_def) arith moreover have "length \<tau>s\<^sub>2 \<le> length \<tau>s\<^sub>2" by simp moreover have "pc - length is\<^sub>1 + length \<tau>s\<^sub>1 \<notin> pcs xt\<^sub>1" using wt\<^sub>1 \<tau>s_size by(fastforce simp: wt_instrs_def) ultimately have "P,T\<^sub>r,mxs,length \<tau>s\<^sub>2 + length \<tau>s\<^sub>1,xt\<^sub>1 @ shift (length \<tau>s\<^sub>1) xt\<^sub>2 \<turnstile> is\<^sub>2 ! (pc - length is\<^sub>1),pc - length is\<^sub>1 + length \<tau>s\<^sub>1 :: \<tau>s\<^sub>1 @ \<tau>s\<^sub>2" by(rule wt_instr_appLx[OF wt_instr_appL[where \<tau>s' = "\<tau>s\<^sub>1"]]) then show ?thesis using False \<tau>s_size by(simp add:add.commute) qed } ultimately show ?thesis by(clarsimp simp:wt_instrs_def) qed (*>*) corollary (in TC2) wt_instrs_ext2: "\<lbrakk> \<turnstile> is\<^sub>2,xt\<^sub>2 [::] \<tau>s\<^sub>2; \<turnstile> is\<^sub>1,xt\<^sub>1 [::] \<tau>s\<^sub>1@\<tau>s\<^sub>2; size \<tau>s\<^sub>1 = size is\<^sub>1 \<rbrakk> \<Longrightarrow> \<turnstile> is\<^sub>1@is\<^sub>2, xt\<^sub>1 @ shift (size is\<^sub>1) xt\<^sub>2 [::] \<tau>s\<^sub>1@\<tau>s\<^sub>2" (*<*)by(rule wt_instrs_ext)(*>*) corollary (in TC2) wt_instrs_ext_prefix [trans]: "\<lbrakk> \<turnstile> is\<^sub>1,xt\<^sub>1 [::] \<tau>s\<^sub>1@\<tau>s\<^sub>2; \<turnstile> is\<^sub>2,xt\<^sub>2 [::] \<tau>s\<^sub>3; size \<tau>s\<^sub>1 = size is\<^sub>1; prefix \<tau>s\<^sub>3 \<tau>s\<^sub>2 \<rbrakk> \<Longrightarrow> \<turnstile> is\<^sub>1@is\<^sub>2, xt\<^sub>1 @ shift (size is\<^sub>1) xt\<^sub>2 [::] \<tau>s\<^sub>1@\<tau>s\<^sub>2" (*<*)by(bestsimp simp:prefix_def elim: wt_instrs_ext dest:wt_instrs_extR)(*>*) corollary (in TC2) wt_instrs_app: assumes is\<^sub>1: "\<turnstile> is\<^sub>1,xt\<^sub>1 [::] \<tau>s\<^sub>1@[\<tau>]" assumes is\<^sub>2: "\<turnstile> is\<^sub>2,xt\<^sub>2 [::] \<tau>#\<tau>s\<^sub>2" assumes s: "size \<tau>s\<^sub>1 = size is\<^sub>1" shows "\<turnstile> is\<^sub>1@is\<^sub>2, xt\<^sub>1@shift (size is\<^sub>1) xt\<^sub>2 [::] \<tau>s\<^sub>1@\<tau>#\<tau>s\<^sub>2" (*<*) proof - from is\<^sub>1 have "\<turnstile> is\<^sub>1,xt\<^sub>1 [::] (\<tau>s\<^sub>1@[\<tau>])@\<tau>s\<^sub>2" by (rule wt_instrs_extR) hence "\<turnstile> is\<^sub>1,xt\<^sub>1 [::] \<tau>s\<^sub>1@\<tau>#\<tau>s\<^sub>2" by simp from this is\<^sub>2 s show ?thesis by (rule wt_instrs_ext) qed (*>*) corollary (in TC2) wt_instrs_app_last[trans]: assumes "\<turnstile> is\<^sub>2,xt\<^sub>2 [::] \<tau>#\<tau>s\<^sub>2" "\<turnstile> is\<^sub>1,xt\<^sub>1 [::] \<tau>s\<^sub>1" "last \<tau>s\<^sub>1 = \<tau>" "size \<tau>s\<^sub>1 = size is\<^sub>1+1" shows "\<turnstile> is\<^sub>1@is\<^sub>2, xt\<^sub>1@shift (size is\<^sub>1) xt\<^sub>2 [::] \<tau>s\<^sub>1@\<tau>s\<^sub>2" (*<*) using assms proof(cases \<tau>s\<^sub>1 rule:rev_cases) case (snoc ys y) then show ?thesis using assms by(simp add:wt_instrs_app) qed simp (*>*) corollary (in TC2) wt_instrs_append_last[trans]: assumes wtis: "\<turnstile> is,xt [::] \<tau>s" and wti: "P,T\<^sub>r,mxs,mpc,[] \<turnstile> i,pc :: \<tau>s" and pc: "pc = size is" and mpc: "mpc = size \<tau>s" and is_\<tau>s: "size is + 1 < size \<tau>s" shows "\<turnstile> is@[i],xt [::] \<tau>s" (*<*) proof - have pc_xt: "pc \<notin> pcs xt" using wtis pc by (fastforce simp:wt_instrs_def) have "pcs xt \<subseteq> {..<Suc (length is)}" using wtis by (fastforce simp:wt_instrs_def) moreover { fix pc' assume pc': "\<not> pc' < length is" "pc' < Suc (length is)" have "P,T\<^sub>r,mxs,length \<tau>s,xt \<turnstile> i,pc' :: \<tau>s" using wt_instr_appLx[where xt = "[]",simplified,OF wti pc_xt] less_antisym[OF pc'] pc mpc by simp } ultimately show ?thesis using wtis is_\<tau>s by(clarsimp simp add:wt_instrs_def) qed (*>*) corollary (in TC2) wt_instrs_app2: "\<lbrakk> \<turnstile> is\<^sub>2,xt\<^sub>2 [::] \<tau>'#\<tau>s\<^sub>2; \<turnstile> is\<^sub>1,xt\<^sub>1 [::] \<tau>#\<tau>s\<^sub>1@[\<tau>']; xt' = xt\<^sub>1 @ shift (size is\<^sub>1) xt\<^sub>2; size \<tau>s\<^sub>1+1 = size is\<^sub>1 \<rbrakk> \<Longrightarrow> \<turnstile> is\<^sub>1@is\<^sub>2,xt' [::] \<tau>#\<tau>s\<^sub>1@\<tau>'#\<tau>s\<^sub>2" (*<*)using wt_instrs_app[where ?\<tau>s\<^sub>1.0 = "\<tau> # \<tau>s\<^sub>1"] by simp (*>*) corollary (in TC2) wt_instrs_app2_simp[trans,simp]: "\<lbrakk> \<turnstile> is\<^sub>2,xt\<^sub>2 [::] \<tau>'#\<tau>s\<^sub>2; \<turnstile> is\<^sub>1,xt\<^sub>1 [::] \<tau>#\<tau>s\<^sub>1@[\<tau>']; size \<tau>s\<^sub>1+1 = size is\<^sub>1 \<rbrakk> \<Longrightarrow> \<turnstile> is\<^sub>1@is\<^sub>2, xt\<^sub>1@shift (size is\<^sub>1) xt\<^sub>2 [::] \<tau>#\<tau>s\<^sub>1@\<tau>'#\<tau>s\<^sub>2" (*<*)using wt_instrs_app[where ?\<tau>s\<^sub>1.0 = "\<tau> # \<tau>s\<^sub>1"] by simp(*>*) corollary (in TC2) wt_instrs_Cons[simp]: "\<lbrakk> \<tau>s \<noteq> []; \<turnstile> [i],[] [::] [\<tau>,\<tau>']; \<turnstile> is,xt [::] \<tau>'#\<tau>s \<rbrakk> \<Longrightarrow> \<turnstile> i#is,shift 1 xt [::] \<tau>#\<tau>'#\<tau>s" (*<*) using wt_instrs_app2[where ?is\<^sub>1.0 = "[i]" and ?\<tau>s\<^sub>1.0 = "[]" and ?is\<^sub>2.0 = "is" and ?xt\<^sub>1.0 = "[]"] by simp corollary (in TC2) wt_instrs_Cons2[trans]: assumes \<tau>s: "\<turnstile> is,xt [::] \<tau>s" assumes i: "P,T\<^sub>r,mxs,mpc,[] \<turnstile> i,0 :: \<tau>#\<tau>s" assumes mpc: "mpc = size \<tau>s + 1" shows "\<turnstile> i#is,shift 1 xt [::] \<tau>#\<tau>s" (*<*) proof - from \<tau>s have "\<tau>s \<noteq> []" by (auto simp: wt_instrs_def) with mpc i have "\<turnstile> [i],[] [::] [\<tau>]@\<tau>s" by (simp add: wt_instrs_def) with \<tau>s show ?thesis by (fastforce dest: wt_instrs_ext) qed (*>*) lemma (in TC2) wt_instrs_last_incr[trans]: assumes wtis: "\<turnstile> is,xt [::] \<tau>s@[\<tau>]" and ss: "P \<turnstile> \<tau> \<le>' \<tau>'" shows "\<turnstile> is,xt [::] \<tau>s@[\<tau>']" (*<*) proof - let ?\<tau>s = "\<tau>s@[\<tau>]" and ?\<tau>s' = "\<tau>s@[\<tau>']" { fix pc assume pc: "pc< size is" let ?i = "is!pc" have app_pc: "app (is ! pc) P mxs T\<^sub>r pc (length ?\<tau>s) xt (\<tau>s ! pc)" using wtis pc by(clarsimp simp add:wt_instrs_def wt_instr_def) then have Apc\<tau>': "\<And>pc' \<tau>'. (pc',\<tau>') \<in> set (eff ?i P pc xt (?\<tau>s!pc)) \<Longrightarrow> pc' < length ?\<tau>s" using wtis pc by(fastforce simp add:wt_instrs_def app_def) have Aepc\<tau>': "\<And>pc' \<tau>'. (pc',\<tau>') \<in> set (eff ?i P pc xt (?\<tau>s!pc)) \<Longrightarrow> P \<turnstile> \<tau>' \<le>' ?\<tau>s!pc'" using wtis pc by(fastforce simp add:wt_instrs_def wt_instr_def) { fix pc1 \<tau>1 assume pc\<tau>1: "(pc1,\<tau>1) \<in> set (eff ?i P pc xt (?\<tau>s'!pc))" then have epc\<tau>': "(pc1,\<tau>1) \<in> set (eff ?i P pc xt (?\<tau>s!pc))" using wtis pc by(simp add:wt_instrs_def) have "P \<turnstile> \<tau>1 \<le>' ?\<tau>s'!pc1" proof(cases "pc1 < length \<tau>s") case True then show ?thesis using wtis pc pc\<tau>1 by(fastforce simp add:wt_instrs_def wt_instr_def) next case False then have "pc1 < length ?\<tau>s" using Apc\<tau>'[OF epc\<tau>'] by simp then have [simp]: "pc1 = size \<tau>s" using False by clarsimp have "P \<turnstile> \<tau>1 \<le>' \<tau>" using Aepc\<tau>'[OF epc\<tau>'] by simp then have "P \<turnstile> \<tau>1 \<le>' \<tau>'" by(rule sup_state_opt_trans[OF _ ss]) then show ?thesis by simp qed } then have "P,T\<^sub>r,mxs,size ?\<tau>s',xt \<turnstile> is!pc,pc :: ?\<tau>s'" using wtis pc by(clarsimp simp add:wt_instrs_def wt_instr_def) } then show ?thesis using wtis by(simp add:wt_instrs_def) qed (*>*) lemma [iff]: "xcpt_app i P pc mxs [] \<tau>" (*<*)by (simp add: xcpt_app_def relevant_entries_def)(*>*) lemma [simp]: "xcpt_eff i P pc \<tau> [] = []" (*<*)by (simp add: xcpt_eff_def relevant_entries_def)(*>*) lemma (in TC2) wt_New: "\<lbrakk> is_class P C; size ST < mxs \<rbrakk> \<Longrightarrow> \<turnstile> [New C],[] [::] [ty\<^sub>i' ST E A, ty\<^sub>i' (Class C#ST) E A]" (*<*)by(simp add:wt_defs ty\<^sub>i'_def)(*>*) lemma (in TC2) wt_Cast: "is_class P C \<Longrightarrow> \<turnstile> [Checkcast C],[] [::] [ty\<^sub>i' (Class D # ST) E A, ty\<^sub>i' (Class C # ST) E A]" (*<*)by(simp add: ty\<^sub>i'_def wt_defs)(*>*) lemma (in TC2) wt_Push: "\<lbrakk> size ST < mxs; typeof v = Some T \<rbrakk> \<Longrightarrow> \<turnstile> [Push v],[] [::] [ty\<^sub>i' ST E A, ty\<^sub>i' (T#ST) E A]" (*<*)by(simp add: ty\<^sub>i'_def wt_defs)(*>*) lemma (in TC2) wt_Pop: "\<turnstile> [Pop],[] [::] (ty\<^sub>i' (T#ST) E A # ty\<^sub>i' ST E A # \<tau>s)" (*<*)by(simp add: ty\<^sub>i'_def wt_defs)(*>*) lemma (in TC2) wt_CmpEq: "\<lbrakk> P \<turnstile> T\<^sub>1 \<le> T\<^sub>2 \<or> P \<turnstile> T\<^sub>2 \<le> T\<^sub>1\<rbrakk> \<Longrightarrow> \<turnstile> [CmpEq],[] [::] [ty\<^sub>i' (T\<^sub>2 # T\<^sub>1 # ST) E A, ty\<^sub>i' (Boolean # ST) E A]" (*<*) by(auto simp:ty\<^sub>i'_def wt_defs elim!: refTE not_refTE) (*>*) lemma (in TC2) wt_IAdd: "\<turnstile> [IAdd],[] [::] [ty\<^sub>i' (Integer#Integer#ST) E A, ty\<^sub>i' (Integer#ST) E A]" (*<*)by(simp add:ty\<^sub>i'_def wt_defs)(*>*) lemma (in TC2) wt_Load: "\<lbrakk> size ST < mxs; size E \<le> mxl; i \<in>\<in> A; i < size E \<rbrakk> \<Longrightarrow> \<turnstile> [Load i],[] [::] [ty\<^sub>i' ST E A, ty\<^sub>i' (E!i # ST) E A]" (*<*)by(auto simp add:ty\<^sub>i'_def wt_defs ty\<^sub>l_def hyperset_defs)(*>*) lemma (in TC2) wt_Store: "\<lbrakk> P \<turnstile> T \<le> E!i; i < size E; size E \<le> mxl \<rbrakk> \<Longrightarrow> \<turnstile> [Store i],[] [::] [ty\<^sub>i' (T#ST) E A, ty\<^sub>i' ST E (\<lfloor>{i}\<rfloor> \<squnion> A)]" (*<*) by(auto simp:hyperset_defs nth_list_update ty\<^sub>i'_def wt_defs ty\<^sub>l_def intro:list_all2_all_nthI) (*>*) lemma (in TC2) wt_Get: "\<lbrakk> P \<turnstile> C sees F:T in D \<rbrakk> \<Longrightarrow> \<turnstile> [Getfield F D],[] [::] [ty\<^sub>i' (Class C # ST) E A, ty\<^sub>i' (T # ST) E A]" (*<*)by(auto simp: ty\<^sub>i'_def wt_defs dest: sees_field_idemp sees_field_decl_above)(*>*) lemma (in TC2) wt_Put: "\<lbrakk> P \<turnstile> C sees F:T in D; P \<turnstile> T' \<le> T \<rbrakk> \<Longrightarrow> \<turnstile> [Putfield F D],[] [::] [ty\<^sub>i' (T' # Class C # ST) E A, ty\<^sub>i' ST E A]" (*<*)by(auto intro: sees_field_idemp sees_field_decl_above simp: ty\<^sub>i'_def wt_defs)(*>*) lemma (in TC2) wt_Throw: "\<turnstile> [Throw],[] [::] [ty\<^sub>i' (Class C # ST) E A, \<tau>']" (*<*)by(auto simp: ty\<^sub>i'_def wt_defs)(*>*) lemma (in TC2) wt_IfFalse: "\<lbrakk> 2 \<le> i; nat i < size \<tau>s + 2; P \<turnstile> ty\<^sub>i' ST E A \<le>' \<tau>s ! nat(i - 2) \<rbrakk> \<Longrightarrow> \<turnstile> [IfFalse i],[] [::] ty\<^sub>i' (Boolean # ST) E A # ty\<^sub>i' ST E A # \<tau>s" (*<*) by(simp add: ty\<^sub>i'_def wt_defs eval_nat_numeral nat_diff_distrib) (*>*) lemma wt_Goto: "\<lbrakk> 0 \<le> int pc + i; nat (int pc + i) < size \<tau>s; size \<tau>s \<le> mpc; P \<turnstile> \<tau>s!pc \<le>' \<tau>s ! nat (int pc + i) \<rbrakk> \<Longrightarrow> P,T,mxs,mpc,[] \<turnstile> Goto i,pc :: \<tau>s" (*<*)by(clarsimp simp add: TC2.wt_defs)(*>*) lemma (in TC2) wt_Invoke: "\<lbrakk> size es = size Ts'; P \<turnstile> C sees M: Ts\<rightarrow>T = m in D; P \<turnstile> Ts' [\<le>] Ts \<rbrakk> \<Longrightarrow> \<turnstile> [Invoke M (size es)],[] [::] [ty\<^sub>i' (rev Ts' @ Class C # ST) E A, ty\<^sub>i' (T#ST) E A]" (*<*)by(fastforce simp add: ty\<^sub>i'_def wt_defs)(*>*) corollary (in TC2) wt_instrs_app3[simp]: "\<lbrakk> \<turnstile> is\<^sub>2,[] [::] (\<tau>' # \<tau>s\<^sub>2); \<turnstile> is\<^sub>1,xt\<^sub>1 [::] \<tau> # \<tau>s\<^sub>1 @ [\<tau>']; size \<tau>s\<^sub>1+1 = size is\<^sub>1\<rbrakk> \<Longrightarrow> \<turnstile> (is\<^sub>1 @ is\<^sub>2),xt\<^sub>1 [::] \<tau> # \<tau>s\<^sub>1 @ \<tau>' # \<tau>s\<^sub>2" (*<*)using wt_instrs_app2[where ?xt\<^sub>2.0 = "[]"] by (simp add:shift_def)(*>*) corollary (in TC2) wt_instrs_Cons3[simp]: "\<lbrakk> \<tau>s \<noteq> []; \<turnstile> [i],[] [::] [\<tau>,\<tau>']; \<turnstile> is,[] [::] \<tau>'#\<tau>s \<rbrakk> \<Longrightarrow> \<turnstile> (i # is),[] [::] \<tau> # \<tau>' # \<tau>s" (*<*) using wt_instrs_Cons[where ?xt = "[]"] by (simp add:shift_def) (*<*) declare nth_append[simp del] declare [[simproc del: list_to_set_comprehension]] (*>*) lemma (in TC2) wt_instrs_xapp[trans]: assumes wtis: "\<turnstile> is\<^sub>1 @ is\<^sub>2, xt [::] \<tau>s\<^sub>1 @ ty\<^sub>i' (Class C # ST) E A # \<tau>s\<^sub>2" and P_\<tau>s\<^sub>1: "\<forall>\<tau> \<in> set \<tau>s\<^sub>1. \<forall>ST' LT'. \<tau> = Some(ST',LT') \<longrightarrow> size ST \<le> size ST' \<and> P \<turnstile> Some (drop (size ST' - size ST) ST',LT') \<le>' ty\<^sub>i' ST E A" and is_\<tau>s: "size is\<^sub>1 = size \<tau>s\<^sub>1" and PC: "is_class P C" and ST_mxs: "size ST < mxs" shows "\<turnstile> is\<^sub>1 @ is\<^sub>2, xt @ [(0,size is\<^sub>1 - 1,C,size is\<^sub>1,size ST)] [::] \<tau>s\<^sub>1 @ ty\<^sub>i' (Class C # ST) E A # \<tau>s\<^sub>2" (*<*)(is "\<turnstile> ?is, xt@[?xte] [::] ?\<tau>s" is "\<turnstile> ?is, ?xt' [::] ?\<tau>s") proof - let ?is = "is\<^sub>1 @ is\<^sub>2" and ?\<tau>s = "\<tau>s\<^sub>1 @ ty\<^sub>i' (Class C # ST) E A # \<tau>s\<^sub>2" let ?xte = "(0,size is\<^sub>1 - 1,C,size is\<^sub>1,size ST)" let ?xt' = "xt @ [?xte]" have P_\<tau>s\<^sub>1': "\<And>\<tau>. \<tau> \<in> set \<tau>s\<^sub>1 \<Longrightarrow> (\<forall>ST' LT'. \<tau> = Some(ST',LT') \<longrightarrow> size ST \<le> size ST' \<and> P \<turnstile> Some (drop (size ST' - size ST) ST',LT') \<le>' ty\<^sub>i' ST E A)" using P_\<tau>s\<^sub>1 by fast have "size ?is < size ?\<tau>s" and "pcs ?xt' \<subseteq> {0..<size ?is}" and P_pc: "\<And>pc. pc< size ?is \<Longrightarrow> P,T\<^sub>r,mxs,size ?\<tau>s,xt \<turnstile> ?is!pc,pc :: ?\<tau>s" using wtis by(simp_all add:wt_instrs_def) moreover { fix pc let ?mpc = "size ?\<tau>s" and ?i = "?is!pc" and ?t = "?\<tau>s!pc" assume "pc< size ?is" then have wti: "P,T\<^sub>r,mxs,?mpc,xt \<turnstile> ?i,pc :: ?\<tau>s" by(rule P_pc) then have app: "app ?i P mxs T\<^sub>r pc ?mpc xt ?t" and eff_ss: "\<And>pc' \<tau>'. (pc',\<tau>') \<in> set (eff ?i P pc xt (?\<tau>s!pc)) \<Longrightarrow> P \<turnstile> \<tau>' \<le>' ?\<tau>s!pc'" by(fastforce simp add: wt_instr_def)+ have "app ?i P mxs T\<^sub>r pc ?mpc ?xt' ?t \<and> (\<forall>(pc',\<tau>') \<in> set (eff ?i P pc ?xt' ?t). P \<turnstile> \<tau>' \<le>' ?\<tau>s!pc')" proof (cases ?t) case (Some \<tau>) obtain ST' LT' where \<tau>: "\<tau> = (ST', LT')" by(cases \<tau>) simp have app\<^sub>i: "app\<^sub>i (?i,P,pc,mxs,T\<^sub>r,\<tau>)" and xcpt_app: "xcpt_app ?i P pc mxs xt \<tau>" and eff_pc: "\<And>pc' \<tau>'. (pc',\<tau>') \<in> set (eff ?i P pc xt ?t) \<Longrightarrow> pc' < ?mpc" using Some app by(fastforce simp add: app_def)+ have "xcpt_app ?i P pc mxs ?xt' \<tau>" proof(cases "pc < length \<tau>s\<^sub>1 - 1") case False then show ?thesis using Some \<tau> is_\<tau>s xcpt_app by (clarsimp simp: xcpt_app_def relevant_entries_def is_relevant_entry_def) next case True then have True': "pc < length \<tau>s\<^sub>1" by simp then have "\<tau>s\<^sub>1 ! pc = ?t" by(fastforce simp: nth_append) moreover have \<tau>s\<^sub>1_pc: "\<tau>s\<^sub>1 ! pc \<in> set \<tau>s\<^sub>1" by(rule nth_mem[OF True']) ultimately show ?thesis using Some \<tau> PC ST_mxs xcpt_app P_\<tau>s\<^sub>1'[OF \<tau>s\<^sub>1_pc] by (simp add: xcpt_app_def relevant_entries_def) qed moreover { fix pc' \<tau>' assume efft: "(pc',\<tau>') \<in> set (eff ?i P pc ?xt' ?t)" have "pc' < ?mpc \<and> P \<turnstile> \<tau>' \<le>' ?\<tau>s!pc'" (is "?P1 \<and> ?P2") proof(cases "(pc',\<tau>') \<in> set (eff ?i P pc xt ?t)") case True have ?P1 using True by(rule eff_pc) moreover have ?P2 using True by(rule eff_ss) ultimately show ?thesis by simp next case False then have xte: "(pc',\<tau>') \<in> set (xcpt_eff ?i P pc \<tau> [?xte])" using efft Some by(clarsimp simp: eff_def) then have ?P1 using Some \<tau> is_\<tau>s by(clarsimp simp: xcpt_eff_def relevant_entries_def split: if_split_asm) moreover have ?P2 proof(cases "pc < length \<tau>s\<^sub>1 - 1") case False': False then show ?thesis using False Some \<tau> xte is_\<tau>s by(simp add: xcpt_eff_def relevant_entries_def is_relevant_entry_def) next case True then have True': "pc < length \<tau>s\<^sub>1" by simp have \<tau>s\<^sub>1_pc: "\<tau>s\<^sub>1 ! pc \<in> set \<tau>s\<^sub>1" by(rule nth_mem[OF True']) have "P \<turnstile> \<lfloor>(Class C # drop (length ST' - length ST) ST', LT')\<rfloor> \<le>' ty\<^sub>i' (Class C # ST) E A" using True' Some \<tau> P_\<tau>s\<^sub>1'[OF \<tau>s\<^sub>1_pc] by (fastforce simp: nth_append ty\<^sub>i'_def) then show ?thesis using \<tau> xte is_\<tau>s by(simp add: xcpt_eff_def relevant_entries_def split: if_split_asm) qed ultimately show ?thesis by simp qed } ultimately show ?thesis using Some app\<^sub>i by(fastforce simp add: app_def) qed simp then have "P,T\<^sub>r,mxs,size ?\<tau>s,?xt' \<turnstile> ?is!pc,pc :: ?\<tau>s" by(simp add: wt_instr_def) } ultimately show ?thesis by(simp add:wt_instrs_def) qed declare [[simproc add: list_to_set_comprehension]] declare nth_append[simp] (*>*) lemma drop_Cons_Suc: "\<And>xs. drop n xs = y#ys \<Longrightarrow> drop (Suc n) xs = ys" proof(induct n) case (Suc n) then show ?case by(simp add: drop_Suc) qed simp lemma drop_mess: assumes "Suc (length xs\<^sub>0) \<le> length xs" and "drop (length xs - Suc (length xs\<^sub>0)) xs = x # xs\<^sub>0" shows "drop (length xs - length xs\<^sub>0) xs = xs\<^sub>0" using assms proof(cases xs) case (Cons a list) then show ?thesis using assms proof(cases "length list - length xs\<^sub>0") case Suc then show ?thesis using Cons assms by (simp add: Suc_diff_le drop_Cons_Suc) qed simp qed simp (*<*) declare (in TC0) after_def[simp] pair_eq_ty\<^sub>i'_conv[simp] (*>*) lemma (in TC1) compT_ST_prefix: "\<And>E A ST\<^sub>0. \<lfloor>(ST,LT)\<rfloor> \<in> set(compT E A ST\<^sub>0 e) \<Longrightarrow> size ST\<^sub>0 \<le> size ST \<and> drop (size ST - size ST\<^sub>0) ST = ST\<^sub>0" and "\<And>E A ST\<^sub>0. \<lfloor>(ST,LT)\<rfloor> \<in> set(compTs E A ST\<^sub>0 es) \<Longrightarrow> size ST\<^sub>0 \<le> size ST \<and> drop (size ST - size ST\<^sub>0) ST = ST\<^sub>0" (*<*) proof(induct e and es rule: compT.induct compTs.induct) case (FAss e\<^sub>1 F D e\<^sub>2) moreover { let ?ST\<^sub>0 = "ty E e\<^sub>1 # ST\<^sub>0" fix A assume "\<lfloor>(ST, LT)\<rfloor> \<in> set (compT E A ?ST\<^sub>0 e\<^sub>2)" with FAss have "length ?ST\<^sub>0 \<le> length ST \<and> drop (size ST - size ?ST\<^sub>0) ST = ?ST\<^sub>0" by blast hence ?case by (clarsimp simp add: drop_mess) } ultimately show ?case by auto next case TryCatch thus ?case by auto next case Block thus ?case by auto next case Seq thus ?case by auto next case While thus ?case by auto next case Cond thus ?case by auto next case (Call e M es) moreover { let ?ST\<^sub>0 = "ty E e # ST\<^sub>0" fix A assume "\<lfloor>(ST, LT)\<rfloor> \<in> set (compTs E A ?ST\<^sub>0 es)" with Call have "length ?ST\<^sub>0 \<le> length ST \<and> drop (size ST - size ?ST\<^sub>0) ST = ?ST\<^sub>0" by blast hence ?case by (clarsimp simp add: drop_mess) } ultimately show ?case by auto next case (Cons_exp e es) moreover { let ?ST\<^sub>0 = "ty E e # ST\<^sub>0" fix A assume "\<lfloor>(ST, LT)\<rfloor> \<in> set (compTs E A ?ST\<^sub>0 es)" with Cons_exp have "length ?ST\<^sub>0 \<le> length ST \<and> drop (size ST - size ?ST\<^sub>0) ST = ?ST\<^sub>0" by blast hence ?case by (clarsimp simp add: drop_mess) } ultimately show ?case by auto next case (BinOp e\<^sub>1 bop e\<^sub>2) moreover { let ?ST\<^sub>0 = "ty E e\<^sub>1 # ST\<^sub>0" fix A assume "\<lfloor>(ST, LT)\<rfloor> \<in> set (compT E A ?ST\<^sub>0 e\<^sub>2)" with BinOp have "length ?ST\<^sub>0 \<le> length ST \<and> drop (size ST - size ?ST\<^sub>0) ST = ?ST\<^sub>0" by blast hence ?case by (clarsimp simp add: drop_mess) } ultimately show ?case by auto next case new thus ?case by auto next case Val thus ?case by auto next case Cast thus ?case by auto next case Var thus ?case by auto next case LAss thus ?case by auto next case throw thus ?case by auto next case FAcc thus ?case by auto next case Nil_exp thus ?case by auto qed declare (in TC0) after_def[simp del] pair_eq_ty\<^sub>i'_conv[simp del] (*>*) (* FIXME *) lemma fun_of_simp [simp]: "fun_of S x y = ((x,y) \<in> S)" (*<*) by (simp add: fun_of_def)(*>*) theorem (in TC2) compT_wt_instrs: "\<And>E T A ST. \<lbrakk> P,E \<turnstile>\<^sub>1 e :: T; \<D> e A; \<B> e (size E); size ST + max_stack e \<le> mxs; size E + max_vars e \<le> mxl \<rbrakk> \<Longrightarrow> \<turnstile> compE\<^sub>2 e, compxE\<^sub>2 e 0 (size ST) [::] ty\<^sub>i' ST E A # compT E A ST e @ [after E A ST e]" (*<*)(is "\<And>E T A ST. PROP ?P e E T A ST")(*>*) and "\<And>E Ts A ST. \<lbrakk> P,E \<turnstile>\<^sub>1 es[::]Ts; \<D>s es A; \<B>s es (size E); size ST + max_stacks es \<le> mxs; size E + max_varss es \<le> mxl \<rbrakk> \<Longrightarrow> let \<tau>s = ty\<^sub>i' ST E A # compTs E A ST es in \<turnstile> compEs\<^sub>2 es,compxEs\<^sub>2 es 0 (size ST) [::] \<tau>s \<and> last \<tau>s = ty\<^sub>i' (rev Ts @ ST) E (A \<squnion> \<A>s es)" (*<*) (is "\<And>E Ts A ST. PROP ?Ps es E Ts A ST") proof(induct e and es rule: compxE\<^sub>2.induct compxEs\<^sub>2.induct) case (TryCatch e\<^sub>1 C i e\<^sub>2) hence [simp]: "i = size E" by simp have wt\<^sub>1: "P,E \<turnstile>\<^sub>1 e\<^sub>1 :: T" and wt\<^sub>2: "P,E@[Class C] \<turnstile>\<^sub>1 e\<^sub>2 :: T" and "class": "is_class P C" using TryCatch by auto let ?A\<^sub>1 = "A \<squnion> \<A> e\<^sub>1" let ?A\<^sub>i = "A \<squnion> \<lfloor>{i}\<rfloor>" let ?E\<^sub>i = "E @ [Class C]" let ?\<tau> = "ty\<^sub>i' ST E A" let ?\<tau>s\<^sub>1 = "compT E A ST e\<^sub>1" let ?\<tau>\<^sub>1 = "ty\<^sub>i' (T#ST) E ?A\<^sub>1" let ?\<tau>\<^sub>2 = "ty\<^sub>i' (Class C#ST) E A" let ?\<tau>\<^sub>3 = "ty\<^sub>i' ST ?E\<^sub>i ?A\<^sub>i" let ?\<tau>s\<^sub>2 = "compT ?E\<^sub>i ?A\<^sub>i ST e\<^sub>2" let ?\<tau>\<^sub>2' = "ty\<^sub>i' (T#ST) ?E\<^sub>i (?A\<^sub>i \<squnion> \<A> e\<^sub>2)" let ?\<tau>' = "ty\<^sub>i' (T#ST) E (A \<squnion> \<A> e\<^sub>1 \<sqinter> (\<A> e\<^sub>2 \<ominus> i))" let ?go = "Goto (int(size(compE\<^sub>2 e\<^sub>2)) + 2)" have "PROP ?P e\<^sub>2 ?E\<^sub>i T ?A\<^sub>i ST" by fact hence "\<turnstile> compE\<^sub>2 e\<^sub>2,compxE\<^sub>2 e\<^sub>2 0 (size ST) [::] (?\<tau>\<^sub>3 # ?\<tau>s\<^sub>2) @ [?\<tau>\<^sub>2']" using TryCatch.prems by(auto simp:after_def) also have "?A\<^sub>i \<squnion> \<A> e\<^sub>2 = (A \<squnion> \<A> e\<^sub>2) \<squnion> \<lfloor>{size E}\<rfloor>" by(fastforce simp:hyperset_defs) also have "P \<turnstile> ty\<^sub>i' (T#ST) ?E\<^sub>i \<dots> \<le>' ty\<^sub>i' (T#ST) E (A \<squnion> \<A> e\<^sub>2)" by(simp add:hyperset_defs ty\<^sub>l_incr ty\<^sub>i'_def) also have "P \<turnstile> \<dots> \<le>' ty\<^sub>i' (T#ST) E (A \<squnion> \<A> e\<^sub>1 \<sqinter> (\<A> e\<^sub>2 \<ominus> i))" by(auto intro!: ty\<^sub>l_antimono simp:hyperset_defs ty\<^sub>i'_def) also have "(?\<tau>\<^sub>3 # ?\<tau>s\<^sub>2) @ [?\<tau>'] = ?\<tau>\<^sub>3 # ?\<tau>s\<^sub>2 @ [?\<tau>']" by simp also have "\<turnstile> [Store i],[] [::] ?\<tau>\<^sub>2 # [] @ [?\<tau>\<^sub>3]" using TryCatch.prems by(auto simp:nth_list_update wt_defs ty\<^sub>i'_def ty\<^sub>l_def list_all2_conv_all_nth hyperset_defs) also have "[] @ (?\<tau>\<^sub>3 # ?\<tau>s\<^sub>2 @ [?\<tau>']) = (?\<tau>\<^sub>3 # ?\<tau>s\<^sub>2 @ [?\<tau>'])" by simp also have "P,T\<^sub>r,mxs,size(compE\<^sub>2 e\<^sub>2)+3,[] \<turnstile> ?go,0 :: ?\<tau>\<^sub>1#?\<tau>\<^sub>2#?\<tau>\<^sub>3#?\<tau>s\<^sub>2 @ [?\<tau>']" by (auto simp: hyperset_defs ty\<^sub>i'_def wt_defs nth_Cons nat_add_distrib fun_of_def intro: ty\<^sub>l_antimono list_all2_refl split:nat.split) also have "\<turnstile> compE\<^sub>2 e\<^sub>1,compxE\<^sub>2 e\<^sub>1 0 (size ST) [::] ?\<tau> # ?\<tau>s\<^sub>1 @ [?\<tau>\<^sub>1]" using TryCatch by(auto simp:after_def) also have "?\<tau> # ?\<tau>s\<^sub>1 @ ?\<tau>\<^sub>1 # ?\<tau>\<^sub>2 # ?\<tau>\<^sub>3 # ?\<tau>s\<^sub>2 @ [?\<tau>'] = (?\<tau> # ?\<tau>s\<^sub>1 @ [?\<tau>\<^sub>1]) @ ?\<tau>\<^sub>2 # ?\<tau>\<^sub>3 # ?\<tau>s\<^sub>2 @ [?\<tau>']" by simp also have "compE\<^sub>2 e\<^sub>1 @ ?go # [Store i] @ compE\<^sub>2 e\<^sub>2 = (compE\<^sub>2 e\<^sub>1 @ [?go]) @ (Store i # compE\<^sub>2 e\<^sub>2)" by simp also let "?Q \<tau>" = "\<forall>ST' LT'. \<tau> = \<lfloor>(ST', LT')\<rfloor> \<longrightarrow> size ST \<le> size ST' \<and> P \<turnstile> Some (drop (size ST' - size ST) ST',LT') \<le>' ty\<^sub>i' ST E A" { have "?Q (ty\<^sub>i' ST E A)" by (clarsimp simp add: ty\<^sub>i'_def) moreover have "?Q (ty\<^sub>i' (T # ST) E ?A\<^sub>1)" by (fastforce simp add: ty\<^sub>i'_def hyperset_defs intro!: ty\<^sub>l_antimono) moreover have "\<And>\<tau>. \<tau> \<in> set (compT E A ST e\<^sub>1) \<Longrightarrow> ?Q \<tau>" using TryCatch.prems by clarsimp (frule compT_ST_prefix, fastforce dest!: compT_LT_prefix simp add: ty\<^sub>i'_def) ultimately have "\<forall>\<tau>\<in>set (ty\<^sub>i' ST E A # compT E A ST e\<^sub>1 @ [ty\<^sub>i' (T # ST) E ?A\<^sub>1]). ?Q \<tau>" by auto } also from TryCatch.prems max_stack1[of e\<^sub>1] have "size ST + 1 \<le> mxs" by auto ultimately show ?case using wt\<^sub>1 wt\<^sub>2 TryCatch.prems "class" by (simp add:after_def) next case new thus ?case by(auto simp add:after_def wt_New) next case (BinOp e\<^sub>1 bop e\<^sub>2) let ?op = "case bop of Eq \<Rightarrow> [CmpEq] | Add \<Rightarrow> [IAdd]" have T: "P,E \<turnstile>\<^sub>1 e\<^sub>1 \<guillemotleft>bop\<guillemotright> e\<^sub>2 :: T" by fact then obtain T\<^sub>1 T\<^sub>2 where T\<^sub>1: "P,E \<turnstile>\<^sub>1 e\<^sub>1 :: T\<^sub>1" and T\<^sub>2: "P,E \<turnstile>\<^sub>1 e\<^sub>2 :: T\<^sub>2" and bopT: "case bop of Eq \<Rightarrow> (P \<turnstile> T\<^sub>1 \<le> T\<^sub>2 \<or> P \<turnstile> T\<^sub>2 \<le> T\<^sub>1) \<and> T = Boolean | Add \<Rightarrow> T\<^sub>1 = Integer \<and> T\<^sub>2 = Integer \<and> T = Integer" by auto let ?A\<^sub>1 = "A \<squnion> \<A> e\<^sub>1" let ?A\<^sub>2 = "?A\<^sub>1 \<squnion> \<A> e\<^sub>2" let ?\<tau> = "ty\<^sub>i' ST E A" let ?\<tau>s\<^sub>1 = "compT E A ST e\<^sub>1" let ?\<tau>\<^sub>1 = "ty\<^sub>i' (T\<^sub>1#ST) E ?A\<^sub>1" let ?\<tau>s\<^sub>2 = "compT E ?A\<^sub>1 (T\<^sub>1#ST) e\<^sub>2" let ?\<tau>\<^sub>2 = "ty\<^sub>i' (T\<^sub>2#T\<^sub>1#ST) E ?A\<^sub>2" let ?\<tau>' = "ty\<^sub>i' (T#ST) E ?A\<^sub>2" from bopT have "\<turnstile> ?op,[] [::] [?\<tau>\<^sub>2,?\<tau>']" by (cases bop) (auto simp add: wt_CmpEq wt_IAdd) also have "PROP ?P e\<^sub>2 E T\<^sub>2 ?A\<^sub>1 (T\<^sub>1#ST)" by fact with BinOp.prems T\<^sub>2 have "\<turnstile> compE\<^sub>2 e\<^sub>2, compxE\<^sub>2 e\<^sub>2 0 (size (T\<^sub>1#ST)) [::] ?\<tau>\<^sub>1#?\<tau>s\<^sub>2@[?\<tau>\<^sub>2]" by (auto simp: after_def) also from BinOp T\<^sub>1 have "\<turnstile> compE\<^sub>2 e\<^sub>1, compxE\<^sub>2 e\<^sub>1 0 (size ST) [::] ?\<tau>#?\<tau>s\<^sub>1@[?\<tau>\<^sub>1]" by (auto simp: after_def) finally show ?case using T T\<^sub>1 T\<^sub>2 by (simp add: after_def hyperUn_assoc) next case (Cons_exp e es) have "P,E \<turnstile>\<^sub>1 e # es [::] Ts" by fact then obtain T\<^sub>e Ts' where T\<^sub>e: "P,E \<turnstile>\<^sub>1 e :: T\<^sub>e" and Ts': "P,E \<turnstile>\<^sub>1 es [::] Ts'" and Ts: "Ts = T\<^sub>e#Ts'" by auto let ?A\<^sub>e = "A \<squnion> \<A> e" let ?\<tau> = "ty\<^sub>i' ST E A" let ?\<tau>s\<^sub>e = "compT E A ST e" let ?\<tau>\<^sub>e = "ty\<^sub>i' (T\<^sub>e#ST) E ?A\<^sub>e" let ?\<tau>s' = "compTs E ?A\<^sub>e (T\<^sub>e#ST) es" let ?\<tau>s = "?\<tau> # ?\<tau>s\<^sub>e @ (?\<tau>\<^sub>e # ?\<tau>s')" have Ps: "PROP ?Ps es E Ts' ?A\<^sub>e (T\<^sub>e#ST)" by fact with Cons_exp.prems T\<^sub>e Ts' have "\<turnstile> compEs\<^sub>2 es, compxEs\<^sub>2 es 0 (size (T\<^sub>e#ST)) [::] ?\<tau>\<^sub>e#?\<tau>s'" by (simp add: after_def) also from Cons_exp T\<^sub>e have "\<turnstile> compE\<^sub>2 e, compxE\<^sub>2 e 0 (size ST) [::] ?\<tau>#?\<tau>s\<^sub>e@[?\<tau>\<^sub>e]" by (auto simp: after_def) moreover from Ps Cons_exp.prems T\<^sub>e Ts' Ts have "last ?\<tau>s = ty\<^sub>i' (rev Ts@ST) E (?A\<^sub>e \<squnion> \<A>s es)" by simp ultimately show ?case using T\<^sub>e by (simp add: after_def hyperUn_assoc) next case (FAss e\<^sub>1 F D e\<^sub>2) hence Void: "P,E \<turnstile>\<^sub>1 e\<^sub>1\<bullet>F{D} := e\<^sub>2 :: Void" by auto then obtain C T T' where C: "P,E \<turnstile>\<^sub>1 e\<^sub>1 :: Class C" and sees: "P \<turnstile> C sees F:T in D" and T': "P,E \<turnstile>\<^sub>1 e\<^sub>2 :: T'" and T'_T: "P \<turnstile> T' \<le> T" by auto let ?A\<^sub>1 = "A \<squnion> \<A> e\<^sub>1" let ?A\<^sub>2 = "?A\<^sub>1 \<squnion> \<A> e\<^sub>2" let ?\<tau> = "ty\<^sub>i' ST E A" let ?\<tau>s\<^sub>1 = "compT E A ST e\<^sub>1" let ?\<tau>\<^sub>1 = "ty\<^sub>i' (Class C#ST) E ?A\<^sub>1" let ?\<tau>s\<^sub>2 = "compT E ?A\<^sub>1 (Class C#ST) e\<^sub>2" let ?\<tau>\<^sub>2 = "ty\<^sub>i' (T'#Class C#ST) E ?A\<^sub>2" let ?\<tau>\<^sub>3 = "ty\<^sub>i' ST E ?A\<^sub>2" let ?\<tau>' = "ty\<^sub>i' (Void#ST) E ?A\<^sub>2" from FAss.prems sees T'_T have "\<turnstile> [Putfield F D,Push Unit],[] [::] [?\<tau>\<^sub>2,?\<tau>\<^sub>3,?\<tau>']" by (fastforce simp add: wt_Push wt_Put) also have "PROP ?P e\<^sub>2 E T' ?A\<^sub>1 (Class C#ST)" by fact with FAss.prems T' have "\<turnstile> compE\<^sub>2 e\<^sub>2, compxE\<^sub>2 e\<^sub>2 0 (size ST+1) [::] ?\<tau>\<^sub>1#?\<tau>s\<^sub>2@[?\<tau>\<^sub>2]" by (auto simp add: after_def hyperUn_assoc) also from FAss C have "\<turnstile> compE\<^sub>2 e\<^sub>1, compxE\<^sub>2 e\<^sub>1 0 (size ST) [::] ?\<tau>#?\<tau>s\<^sub>1@[?\<tau>\<^sub>1]" by (auto simp add: after_def) finally show ?case using Void C T' by (simp add: after_def hyperUn_assoc) next case Val thus ?case by(auto simp:after_def wt_Push) next case Cast thus ?case by (auto simp:after_def wt_Cast) next case (Block i T\<^sub>i e) let ?\<tau>s = "ty\<^sub>i' ST E A # compT (E @ [T\<^sub>i]) (A\<ominus>i) ST e" have IH: "PROP ?P e (E@[T\<^sub>i]) T (A\<ominus>i) ST" by fact hence "\<turnstile> compE\<^sub>2 e, compxE\<^sub>2 e 0 (size ST) [::] ?\<tau>s @ [ty\<^sub>i' (T#ST) (E@[T\<^sub>i]) (A\<ominus>(size E) \<squnion> \<A> e)]" using Block.prems by (auto simp add: after_def) also have "P \<turnstile> ty\<^sub>i' (T # ST) (E@[T\<^sub>i]) (A \<ominus> size E \<squnion> \<A> e) \<le>' ty\<^sub>i' (T # ST) (E@[T\<^sub>i]) ((A \<squnion> \<A> e) \<ominus> size E)" by(auto simp add:hyperset_defs intro: ty\<^sub>i'_antimono) also have "\<dots> = ty\<^sub>i' (T # ST) E (A \<squnion> \<A> e)" by simp also have "P \<turnstile> \<dots> \<le>' ty\<^sub>i' (T # ST) E (A \<squnion> (\<A> e \<ominus> i))" by(auto simp add:hyperset_defs intro: ty\<^sub>i'_antimono) finally show ?case using Block.prems by(simp add: after_def) next case Var thus ?case by(auto simp:after_def wt_Load) next case FAcc thus ?case by(auto simp:after_def wt_Get) next case (LAss i e) thus ?case using max_stack1[of e] by(auto simp: hyper_insert_comm after_def wt_Store wt_Push) next case Nil_exp thus ?case by auto next case throw thus ?case by(auto simp add: after_def wt_Throw) next case (While e c) obtain Tc where wte: "P,E \<turnstile>\<^sub>1 e :: Boolean" and wtc: "P,E \<turnstile>\<^sub>1 c :: Tc" and [simp]: "T = Void" using While by auto have [simp]: "ty E (while (e) c) = Void" using While by simp let ?A\<^sub>0 = "A \<squnion> \<A> e" let ?A\<^sub>1 = "?A\<^sub>0 \<squnion> \<A> c" let ?\<tau> = "ty\<^sub>i' ST E A" let ?\<tau>s\<^sub>e = "compT E A ST e" let ?\<tau>\<^sub>e = "ty\<^sub>i' (Boolean#ST) E ?A\<^sub>0" let ?\<tau>\<^sub>1 = "ty\<^sub>i' ST E ?A\<^sub>0" let ?\<tau>s\<^sub>c = "compT E ?A\<^sub>0 ST c" let ?\<tau>\<^sub>c = "ty\<^sub>i' (Tc#ST) E ?A\<^sub>1" let ?\<tau>\<^sub>2 = "ty\<^sub>i' ST E ?A\<^sub>1" let ?\<tau>' = "ty\<^sub>i' (Void#ST) E ?A\<^sub>0" let ?\<tau>s = "(?\<tau> # ?\<tau>s\<^sub>e @ [?\<tau>\<^sub>e]) @ ?\<tau>\<^sub>1 # ?\<tau>s\<^sub>c @ [?\<tau>\<^sub>c, ?\<tau>\<^sub>2, ?\<tau>\<^sub>1, ?\<tau>']" have "\<turnstile> [],[] [::] [] @ ?\<tau>s" by(simp add:wt_instrs_def) also have "PROP ?P e E Boolean A ST" by fact hence "\<turnstile> compE\<^sub>2 e,compxE\<^sub>2 e 0 (size ST) [::] ?\<tau> # ?\<tau>s\<^sub>e @ [?\<tau>\<^sub>e]" using While.prems by (auto simp:after_def) also have "[] @ ?\<tau>s = (?\<tau> # ?\<tau>s\<^sub>e) @ ?\<tau>\<^sub>e # ?\<tau>\<^sub>1 # ?\<tau>s\<^sub>c @ [?\<tau>\<^sub>c,?\<tau>\<^sub>2,?\<tau>\<^sub>1,?\<tau>']" by simp also let ?n\<^sub>e = "size(compE\<^sub>2 e)" let ?n\<^sub>c = "size(compE\<^sub>2 c)" let ?if = "IfFalse (int ?n\<^sub>c + 3)" have "\<turnstile> [?if],[] [::] ?\<tau>\<^sub>e # ?\<tau>\<^sub>1 # ?\<tau>s\<^sub>c @ [?\<tau>\<^sub>c, ?\<tau>\<^sub>2, ?\<tau>\<^sub>1, ?\<tau>']" proof-{ show ?thesis apply (rule wt_IfFalse) apply simp apply simp apply (subgoal_tac "length (compE\<^sub>2 c) = length (compT E (A \<squnion> \<A> e) ST c) + 1" "nat (int (length (compE\<^sub>2 c)) + 3 - 2) > length (compT E (A \<squnion> \<A> e) ST c)") apply simp+ done } qed also have "(?\<tau> # ?\<tau>s\<^sub>e) @ (?\<tau>\<^sub>e # ?\<tau>\<^sub>1 # ?\<tau>s\<^sub>c @ [?\<tau>\<^sub>c, ?\<tau>\<^sub>2, ?\<tau>\<^sub>1, ?\<tau>']) = ?\<tau>s" by simp also have "PROP ?P c E Tc ?A\<^sub>0 ST" by fact hence "\<turnstile> compE\<^sub>2 c,compxE\<^sub>2 c 0 (size ST) [::] ?\<tau>\<^sub>1 # ?\<tau>s\<^sub>c @ [?\<tau>\<^sub>c]" using While.prems wtc by (auto simp:after_def) also have "?\<tau>s = (?\<tau> # ?\<tau>s\<^sub>e @ [?\<tau>\<^sub>e,?\<tau>\<^sub>1] @ ?\<tau>s\<^sub>c) @ [?\<tau>\<^sub>c,?\<tau>\<^sub>2,?\<tau>\<^sub>1,?\<tau>']" by simp also have "\<turnstile> [Pop],[] [::] [?\<tau>\<^sub>c, ?\<tau>\<^sub>2]" by(simp add:wt_Pop) also have "(?\<tau> # ?\<tau>s\<^sub>e @ [?\<tau>\<^sub>e,?\<tau>\<^sub>1] @ ?\<tau>s\<^sub>c) @ [?\<tau>\<^sub>c,?\<tau>\<^sub>2,?\<tau>\<^sub>1,?\<tau>'] = ?\<tau>s" by simp also let ?go = "Goto (-int(?n\<^sub>c+?n\<^sub>e+2))" have "P \<turnstile> ?\<tau>\<^sub>2 \<le>' ?\<tau>" by(fastforce intro: ty\<^sub>i'_antimono simp: hyperset_defs) hence "P,T\<^sub>r,mxs,size ?\<tau>s,[] \<turnstile> ?go,?n\<^sub>e+?n\<^sub>c+2 :: ?\<tau>s" proof-{ let ?t1 = "ty\<^sub>i' ST E A" let ?t2 = "ty\<^sub>i' (Boolean # ST) E (A \<squnion> \<A> e)" let ?t3 = "ty\<^sub>i' ST E (A \<squnion> \<A> e)" let ?t4 = "[ty\<^sub>i' (Tc # ST) E (A \<squnion> \<A> e \<squnion> \<A> c), ty\<^sub>i' ST E (A \<squnion> \<A> e \<squnion> \<A> c), ty\<^sub>i' ST E (A \<squnion> \<A> e), ty\<^sub>i' (Void # ST) E (A \<squnion> \<A> e)]" let ?c = " compT E (A \<squnion> \<A> e) ST c" let ?e = "compT E A ST e" assume ass: "P \<turnstile> ty\<^sub>i' ST E (A \<squnion> \<A> e \<squnion> \<A> c) \<le>' ?t1" show ?thesis apply (rule wt_Goto) apply simp apply simp apply simp proof-{ let ?s1 = "((?t1 # ?e @ [?t2]) @ ?t3 # ?c)" have "length (compE\<^sub>2 e) + length (compE\<^sub>2 c) + 2 > length ?s1" by auto hence "(?s1 @ ?t4) ! (length (compE\<^sub>2 e) + length (compE\<^sub>2 c) + 2) = ?t4 ! (length (compE\<^sub>2 e) + length (compE\<^sub>2 c) + 2 - length ?s1)" by (auto simp only:nth_append split: if_splits) hence "(?s1 @ ?t4) ! (length (compE\<^sub>2 e) + length (compE\<^sub>2 c) + 2) = ty\<^sub>i' ST E (A \<squnion> \<A> e \<squnion> \<A> c)" using compT_sizes by auto hence "P \<turnstile> (?s1 @ ?t4) ! (length (compE\<^sub>2 e) + length (compE\<^sub>2 c) + 2) \<le>' ty\<^sub>i' ST E A" using ass by simp thus "P \<turnstile> ((?t1 # ?e @ [?t2]) @ ?t3 # ?c @ ?t4) ! (length (compE\<^sub>2 e) + length (compE\<^sub>2 c) + 2) \<le>' ((?t1 # ?e @ [?t2]) @ ?t3 # ?c @ ?t4) ! nat (int (length (compE\<^sub>2 e) + length (compE\<^sub>2 c) + 2) + - int (length (compE\<^sub>2 c) + length (compE\<^sub>2 e) + 2))" by simp }qed }qed also have "?\<tau>s = (?\<tau> # ?\<tau>s\<^sub>e @ [?\<tau>\<^sub>e,?\<tau>\<^sub>1] @ ?\<tau>s\<^sub>c @ [?\<tau>\<^sub>c, ?\<tau>\<^sub>2]) @ [?\<tau>\<^sub>1, ?\<tau>']" by simp also have "\<turnstile> [Push Unit],[] [::] [?\<tau>\<^sub>1,?\<tau>']" using While.prems max_stack1[of c] by(auto simp add:wt_Push) finally show ?case using wtc wte by (simp add:after_def) next case (Cond e e\<^sub>1 e\<^sub>2) obtain T\<^sub>1 T\<^sub>2 where wte: "P,E \<turnstile>\<^sub>1 e :: Boolean" and wt\<^sub>1: "P,E \<turnstile>\<^sub>1 e\<^sub>1 :: T\<^sub>1" and wt\<^sub>2: "P,E \<turnstile>\<^sub>1 e\<^sub>2 :: T\<^sub>2" and sub\<^sub>1: "P \<turnstile> T\<^sub>1 \<le> T" and sub\<^sub>2: "P \<turnstile> T\<^sub>2 \<le> T" using Cond by auto have [simp]: "ty E (if (e) e\<^sub>1 else e\<^sub>2) = T" using Cond by simp let ?A\<^sub>0 = "A \<squnion> \<A> e" let ?A\<^sub>2 = "?A\<^sub>0 \<squnion> \<A> e\<^sub>2" let ?A\<^sub>1 = "?A\<^sub>0 \<squnion> \<A> e\<^sub>1" let ?A' = "?A\<^sub>0 \<squnion> \<A> e\<^sub>1 \<sqinter> \<A> e\<^sub>2" let ?\<tau>\<^sub>2 = "ty\<^sub>i' ST E ?A\<^sub>0" let ?\<tau>' = "ty\<^sub>i' (T#ST) E ?A'" let ?\<tau>s\<^sub>2 = "compT E ?A\<^sub>0 ST e\<^sub>2" have "PROP ?P e\<^sub>2 E T\<^sub>2 ?A\<^sub>0 ST" by fact hence "\<turnstile> compE\<^sub>2 e\<^sub>2, compxE\<^sub>2 e\<^sub>2 0 (size ST) [::] (?\<tau>\<^sub>2#?\<tau>s\<^sub>2) @ [ty\<^sub>i' (T\<^sub>2#ST) E ?A\<^sub>2]" using Cond.prems wt\<^sub>2 by(auto simp add:after_def) also have "P \<turnstile> ty\<^sub>i' (T\<^sub>2#ST) E ?A\<^sub>2 \<le>' ?\<tau>'" using sub\<^sub>2 by(auto simp add: hyperset_defs ty\<^sub>i'_def intro!: ty\<^sub>l_antimono) also let ?\<tau>\<^sub>3 = "ty\<^sub>i' (T\<^sub>1 # ST) E ?A\<^sub>1" let ?g\<^sub>2 = "Goto(int (size (compE\<^sub>2 e\<^sub>2) + 1))" from sub\<^sub>1 have "P,T\<^sub>r,mxs,size(compE\<^sub>2 e\<^sub>2)+2,[] \<turnstile> ?g\<^sub>2,0 :: ?\<tau>\<^sub>3#(?\<tau>\<^sub>2#?\<tau>s\<^sub>2)@[?\<tau>']" by(auto simp: hyperset_defs wt_defs nth_Cons ty\<^sub>i'_def split:nat.split intro!: ty\<^sub>l_antimono) also let ?\<tau>s\<^sub>1 = "compT E ?A\<^sub>0 ST e\<^sub>1" have "PROP ?P e\<^sub>1 E T\<^sub>1 ?A\<^sub>0 ST" by fact hence "\<turnstile> compE\<^sub>2 e\<^sub>1,compxE\<^sub>2 e\<^sub>1 0 (size ST) [::] ?\<tau>\<^sub>2 # ?\<tau>s\<^sub>1 @ [?\<tau>\<^sub>3]" using Cond.prems wt\<^sub>1 by(auto simp add:after_def) also let ?\<tau>s\<^sub>1\<^sub>2 = "?\<tau>\<^sub>2 # ?\<tau>s\<^sub>1 @ ?\<tau>\<^sub>3 # (?\<tau>\<^sub>2 # ?\<tau>s\<^sub>2) @ [?\<tau>']" let ?\<tau>\<^sub>1 = "ty\<^sub>i' (Boolean#ST) E ?A\<^sub>0" let ?g\<^sub>1 = "IfFalse(int (size (compE\<^sub>2 e\<^sub>1) + 2))" let ?code = "compE\<^sub>2 e\<^sub>1 @ ?g\<^sub>2 # compE\<^sub>2 e\<^sub>2" have "\<turnstile> [?g\<^sub>1],[] [::] [?\<tau>\<^sub>1] @ ?\<tau>s\<^sub>1\<^sub>2" proof-{ show ?thesis apply clarsimp apply (rule wt_IfFalse) apply (simp only:nat_add_distrib) apply simp apply (auto simp only:nth_append split:if_splits) apply (simp only:compT_sizes) apply simp done }qed also (wt_instrs_ext2) have "[?\<tau>\<^sub>1] @ ?\<tau>s\<^sub>1\<^sub>2 = ?\<tau>\<^sub>1 # ?\<tau>s\<^sub>1\<^sub>2" by simp also let ?\<tau> = "ty\<^sub>i' ST E A" have "PROP ?P e E Boolean A ST" by fact hence "\<turnstile> compE\<^sub>2 e, compxE\<^sub>2 e 0 (size ST) [::] ?\<tau> # compT E A ST e @ [?\<tau>\<^sub>1]" using Cond.prems wte by(auto simp add:after_def) finally show ?case using wte wt\<^sub>1 wt\<^sub>2 by(simp add:after_def hyperUn_assoc) next case (Call e M es) obtain C D Ts m Ts' where C: "P,E \<turnstile>\<^sub>1 e :: Class C" and "method": "P \<turnstile> C sees M:Ts \<rightarrow> T = m in D" and wtes: "P,E \<turnstile>\<^sub>1 es [::] Ts'" and subs: "P \<turnstile> Ts' [\<le>] Ts" using Call.prems by auto from wtes have same_size: "size es = size Ts'" by(rule WTs\<^sub>1_same_size) let ?A\<^sub>0 = "A \<squnion> \<A> e" let ?A\<^sub>1 = "?A\<^sub>0 \<squnion> \<A>s es" let ?\<tau> = "ty\<^sub>i' ST E A" let ?\<tau>s\<^sub>e = "compT E A ST e" let ?\<tau>\<^sub>e = "ty\<^sub>i' (Class C # ST) E ?A\<^sub>0" let ?\<tau>s\<^sub>e\<^sub>s = "compTs E ?A\<^sub>0 (Class C # ST) es" let ?\<tau>\<^sub>1 = "ty\<^sub>i' (rev Ts' @ Class C # ST) E ?A\<^sub>1" let ?\<tau>' = "ty\<^sub>i' (T # ST) E ?A\<^sub>1" have "\<turnstile> [Invoke M (size es)],[] [::] [?\<tau>\<^sub>1,?\<tau>']" by(rule wt_Invoke[OF same_size "method" subs]) also have "PROP ?Ps es E Ts' ?A\<^sub>0 (Class C # ST)" by fact hence "\<turnstile> compEs\<^sub>2 es,compxEs\<^sub>2 es 0 (size ST+1) [::] ?\<tau>\<^sub>e # ?\<tau>s\<^sub>e\<^sub>s" "last (?\<tau>\<^sub>e # ?\<tau>s\<^sub>e\<^sub>s) = ?\<tau>\<^sub>1" using Call.prems wtes by(auto simp add:after_def) also have "(?\<tau>\<^sub>e # ?\<tau>s\<^sub>e\<^sub>s) @ [?\<tau>'] = ?\<tau>\<^sub>e # ?\<tau>s\<^sub>e\<^sub>s @ [?\<tau>']" by simp also have "\<turnstile> compE\<^sub>2 e,compxE\<^sub>2 e 0 (size ST) [::] ?\<tau> # ?\<tau>s\<^sub>e @ [?\<tau>\<^sub>e]" using Call C by(auto simp add:after_def) finally show ?case using Call.prems C by(simp add:after_def hyperUn_assoc) next case Seq thus ?case by(auto simp:after_def) (fastforce simp:wt_Push wt_Pop hyperUn_assoc intro:wt_instrs_app2 wt_instrs_Cons) qed (*>*) lemma [simp]: "types (compP f P) = types P" (*<*)by auto(*>*) lemma [simp]: "states (compP f P) mxs mxl = states P mxs mxl" (*<*)by (simp add: JVM_states_unfold)(*>*) lemma [simp]: "app\<^sub>i (i, compP f P, pc, mpc, T, \<tau>) = app\<^sub>i (i, P, pc, mpc, T, \<tau>)" (*<*)(is "?A = ?B") proof - obtain ST LT where \<tau>: "\<tau> = (ST, LT)" by(cases \<tau>) simp then show ?thesis proof(cases i) case Invoke show ?thesis proof(rule iffI) assume ?A then show ?B using Invoke \<tau> by auto (fastforce dest!: sees_method_compPD) next assume ?B then show ?A using Invoke \<tau> by auto (force dest: sees_method_compP) qed qed auto qed (*>*) lemma [simp]: "is_relevant_entry (compP f P) i = is_relevant_entry P i" (*<*) proof - { fix pc e have "is_relevant_entry (compP f P) i pc e = is_relevant_entry P i pc e" by(cases i) (auto simp: is_relevant_entry_def) } then show ?thesis by fast qed (*>*) lemma [simp]: "relevant_entries (compP f P) i pc xt = relevant_entries P i pc xt" (*<*) by (simp add: relevant_entries_def)(*>*) lemma [simp]: "app i (compP f P) mpc T pc mxl xt \<tau> = app i P mpc T pc mxl xt \<tau>" (*<*) by (simp add: app_def xcpt_app_def eff_def xcpt_eff_def norm_eff_def) (fastforce simp add: image_def) (*>*) lemma [simp]: assumes "app i P mpc T pc mxl xt \<tau>" shows "eff i (compP f P) pc xt \<tau> = eff i P pc xt \<tau>" (*<*) using assms proof(clarsimp simp: eff_def norm_eff_def xcpt_eff_def app_def, cases i) qed auto (*>*) lemma [simp]: "subtype (compP f P) = subtype P" (*<*)by (rule ext)+ simp(*>*) lemma [simp]: "compP f P \<turnstile> \<tau> \<le>' \<tau>' = P \<turnstile> \<tau> \<le>' \<tau>'" (*<*) by (simp add: sup_state_opt_def sup_state_def sup_ty_opt_def)(*>*) lemma [simp]: "compP f P,T,mpc,mxl,xt \<turnstile> i,pc :: \<tau>s = P,T,mpc,mxl,xt \<turnstile> i,pc :: \<tau>s" (*<*)by (simp add: wt_instr_def cong: conj_cong)(*>*) declare TC1.compT_sizes[simp] TC0.ty_def2[simp] context TC2 begin lemma compT_method: fixes e and A and C and Ts and mxl\<^sub>0 defines [simp]: "E \<equiv> Class C # Ts" and [simp]: "A \<equiv> \<lfloor>{..size Ts}\<rfloor>" and [simp]: "A' \<equiv> A \<squnion> \<A> e" and [simp]: "mxl\<^sub>0 \<equiv> max_vars e" assumes mxs: "max_stack e = mxs" and mxl: "Suc (length Ts + max_vars e) = mxl" assumes wf: "wf_prog p P" and wte: "P,E \<turnstile>\<^sub>1 e :: T" and \<D>: "\<D> e A" and \<B>: "\<B> e (size E)" and E_P: "set E \<subseteq> types P" and wid: "P \<turnstile> T \<le> T\<^sub>r" shows "wt_method (compP\<^sub>2 P) C Ts T\<^sub>r mxs mxl\<^sub>0 (compE\<^sub>2 e @ [Return]) (compxE\<^sub>2 e 0 0) (ty\<^sub>i' [] E A # compT\<^sub>a E A [] e)" (*<*)(is "wt_method ?P C Ts T\<^sub>r mxs mxl\<^sub>0 ?is ?xt ?\<tau>s") proof - let ?n = "length E + mxl\<^sub>0" have wt_compE: "P,T\<^sub>r,mxs \<turnstile> compE\<^sub>2 e, compxE\<^sub>2 e 0 (length []) [::] TC0.ty\<^sub>i' ?n [] E A # TC1.compT P ?n E A [] e @[TC0.after P ?n E A [] e]" using mxs TC2.compT_wt_instrs [OF wte \<D> \<B>, of "[]" mxs ?n T\<^sub>r] by simp have "OK (ty\<^sub>i' [T] E A') \<in> states P mxs mxl" using mxs WT\<^sub>1_is_type[OF wf wte E_P] max_stack1[of e] OK_ty\<^sub>i'_in_statesI[OF E_P] by simp moreover have "OK ` set (compT E A [] e) \<subseteq> states P mxs mxl" using mxs mxl wid compT_states(1)[OF wf wte E_P] by simp ultimately have "check_types ?P mxs ?n (map OK ?\<tau>s)" using mxl wte E_P by (simp add: compT\<^sub>a_def after_def check_types_def) moreover have "wt_start ?P C Ts mxl\<^sub>0 ?\<tau>s" using mxl by (auto simp: wt_start_def ty\<^sub>i'_def ty\<^sub>l_def list_all2_conv_all_nth nth_Cons split: nat.split) moreover { fix pc assume pc: "pc < size ?is" then have "?P,T\<^sub>r,mxs,size ?is,?xt \<turnstile> ?is!pc,pc :: ?\<tau>s" proof(cases "pc < length (compE\<^sub>2 e)") case True then show ?thesis using mxs wte wt_compE by (clarsimp simp: compT\<^sub>a_def mxl after_def wt_instrs_def) next case False have "length (compE\<^sub>2 e) = pc" using less_antisym[OF False] pc by simp then show ?thesis using mxl wte E_P wid by (clarsimp simp: compT\<^sub>a_def after_def wt_defs xcpt_app_pcs xcpt_eff_pcs ty\<^sub>i'_def) qed } moreover have "0 < size ?is" and "size ?\<tau>s = size ?is" using wte by (simp_all add: compT\<^sub>a_def) ultimately show ?thesis by(simp add: wt_method_def) qed (*>*) end definition compTP :: "J\<^sub>1_prog \<Rightarrow> ty\<^sub>P" where "compTP P C M = ( let (D,Ts,T,e) = method P C M; E = Class C # Ts; A = \<lfloor>{..size Ts}\<rfloor>; mxl = 1 + size Ts + max_vars e in (TC0.ty\<^sub>i' mxl [] E A # TC1.compT\<^sub>a P mxl E A [] e))" theorem wt_compP\<^sub>2: assumes wf: "wf_J\<^sub>1_prog P" shows "wf_jvm_prog (compP\<^sub>2 P)" (*<*) proof - let ?\<Phi> = "compTP P" and ?f = compMb\<^sub>2 let ?wf\<^sub>2 = "\<lambda>P C (M, Ts, T\<^sub>r, mxs, mxl\<^sub>0, is, xt). wt_method P C Ts T\<^sub>r mxs mxl\<^sub>0 is xt (?\<Phi> C M)" and ?P = "compP ?f P" { fix C M Ts T m assume cM: "P \<turnstile> C sees M : Ts\<rightarrow>T = m in C" and wfm: "wf_mdecl wf_J\<^sub>1_mdecl P C (M,Ts,T,m)" then have Ts_types: "\<forall>T'\<in>set Ts. is_type P T'" and T_type: "is_type P T" and wfm\<^sub>1: "wf_J\<^sub>1_mdecl P C (M,Ts,T,m)" by(simp_all add: wf_mdecl_def) then obtain T' where wte: "P,Class C#Ts \<turnstile>\<^sub>1 m :: T'" and wid: "P \<turnstile> T' \<le> T" and \<D>: "\<D> m \<lfloor>{..size Ts}\<rfloor>" and \<B>: "\<B> m (Suc (size Ts))" by(auto simp: wf_mdecl_def) have CTs_P: "is_class P C \<and> set Ts \<subseteq> types P" using sees_wf_mdecl[OF wf cM] sees_method_is_class[OF cM] by (clarsimp simp: wf_mdecl_def) have "?wf\<^sub>2 ?P C (M,Ts,T,?f m)" using cM TC2.compT_method [simplified, OF _ _ wf wte \<D> \<B> CTs_P wid] by(simp add: compTP_def) then have "wf_mdecl ?wf\<^sub>2 ?P C (M, Ts, T, ?f m)" using Ts_types T_type by(simp add: wf_mdecl_def) } then have "wf_prog ?wf\<^sub>2 (compP ?f P)" by(rule wf_prog_compPI[OF _ wf]) then show ?thesis by (simp add: wf_jvm_prog_def wf_jvm_prog_phi_def) fast qed (*>*) theorem wt_J2JVM: "wf_J_prog P \<Longrightarrow> wf_jvm_prog (J2JVM P)" (*<*) by(simp only:o_def J2JVM_def) (blast intro:wt_compP\<^sub>2 compP\<^sub>1_pres_wf) end
If $S$ is a connected set, then any continuous function $f$ defined on $S$ with a disconnected range, a discrete range, or a finite range is constant.
\pageId{mathMode} % Simple input/result table environment \newenvironment{demotable} {\begin{center} \begin{tabular}{|r|c|} \hline \\ Input & Result \\ \hline \\ }{\hline \end{tabular} \end{center} } \newenvironment{ndemotable} {\begin{center} \begin{tabular}{|l|c|l|} \hline \\ Input & Result & Notes \\ \hline \\ }{\hline \end{tabular} \end{center} } % Creates two columns, 1st shows math input, 2nd shows math output \newcommand{\minout}[1]{\verb|$ #1 $| & $#1$} \newcommand{\dminout}[1]{\verb|$$ #1 $$| & $$#1$$} \newcommand{\bigdminout}[1]{\begin{verbatim}\[ #1 \]\end{verbatim} & $$#1$$} \newcommand{\note}[1]{\small #1} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% This page lists the main commands for producing basic symbols and operators in math mode. \textbf{NOTE:} The default view of this page (with the \verb|.html| file extension) is actually the \href[Legacy Web Pages]{docs://legacyWebPages} output! If you want to see MathML versions of this page, look at the \href[Web Output Samples]{docs://samples} page for details. \subsection*{Entering and Leaving math Mode} SnuggleTeX supports the usual LaTeX commands for entering and leaving math mode: \begin{itemize} \item \verb|$...$| \item \verb|\(...\)| \item \verb|\begin{math}...\end{math}| \end{itemize} all produce inline mathematics, whereas: \begin{itemize} \item \verb|$$...$$| \item \verb|\[...\]| \item \verb|\begin{displaymath}...\end{displaymath}| \end{itemize} all produce "display" mathematics. The \verb|eqnarray| and \verb|eqnarray*| environments also enter math mode. SnuggleTeX also supports the \verb|\ensuremath{...}| command. \subsection*{Basic Mathematics} \begin{ndemotable} \minout{-5.32} & \note{Simple number. (Currently SnuggleTeX only understands UK number formats but this will improve soon\ldots)} \\ \minout{x} & \note{An identifier} \\ \minout{x+1 \over 3y} & \note{Old style fractions} \\ \minout{\frac{x+1}{3y}} & \note{New style fractions} \\ \minout{x^2} & \note{Simple superscript example} \\ \minout{x^{2^{y-z}}} & \note{Complex superscript example} \\ \minout{(x_1, x_2)} & \note{Subscript example.} \\ \minout{x_1^2} & \note{Mix of subscripts and superscripts} \\ \minout{\sqrt{x}} & \note{Square roots} \\ \minout{\sqrt[n]{x}} & \note{$n^\mathrm{th}$ roots} \\ \end{ndemotable} \subsection*{Greek Letters} As is normal here, note that commands are only required for upper case letters if there is no standard roman alphabet equivalent. \newcommand{\gkdemo}[1]{\minout{#1} \\} \newcommand{\Gkdemo}[2]{\minout{#1} & \minout{#2} \\} \begin{center} \begin{tabular}{|r|c|r|c|} \hline Input & Result & Input & Result \\ \hline \gkdemo{\alpha} \gkdemo{\beta} \Gkdemo{\gamma}{\Gamma} \Gkdemo{\delta}{\Delta} \gkdemo{\epsilon} \gkdemo{\varepsilon} \gkdemo{\zeta} \gkdemo{\eta} \Gkdemo{\theta}{\Theta} \gkdemo{\vartheta} \gkdemo{\iota} \gkdemo{\kappa} \Gkdemo{\lambda}{\Lambda} \gkdemo{\mu} \gkdemo{\nu} \Gkdemo{\xi}{\Xi} \Gkdemo{\pi}{\Pi} \gkdemo{\varpi} \gkdemo{\rho} \gkdemo{\varrho} \Gkdemo{\sigma}{\Sigma} \gkdemo{\varsigma} \gkdemo{\tau} \Gkdemo{\upsilon}{\Upsilon} \Gkdemo{\phi}{\Phi} \gkdemo{\varphi} \gkdemo{\chi} \Gkdemo{\psi}{\Psi} \Gkdemo{\omega}{\Omega} \hline \end{tabular} \end{center} \subsection*{Mathematical Functions} % Math-mode demo line \newcommand{\mdemo}[1]{\minout{#1} \\} \begin{demotable} \mdemo{\arccos x} \mdemo{\arcsin x} \mdemo{\arctan x} \mdemo{\arg x} \mdemo{\cos x} \mdemo{\cosh x} \mdemo{\cot x} \mdemo{\coth x} \mdemo{\csc x} \mdemo{\deg x} \mdemo{\det x} \mdemo{\dim x} \mdemo{\exp x} \mdemo{\gcd x} \mdemo{\hom x} \mdemo{\inf x} \mdemo{\ker x} \mdemo{\lg x} \mdemo{\lim x} \mdemo{\liminf x} \mdemo{\limsup x} \mdemo{\ln x} \mdemo{\log x} \mdemo{\max x} \mdemo{\min x} \mdemo{\Pr x} \mdemo{\sec x} \mdemo{\sin x} \mdemo{\sinh x} \mdemo{\sup x} \mdemo{\tan x} \mdemo{\tanh x} \end{demotable} \subsection*{Ellipses} \begin{demotable} \mdemo{\cdots} \mdemo{\vdots} \mdemo{\ddots} \end{demotable} \subsection*{Spacing} Note that MathML-enabled browsers don't support spacing particularly well. You can also use the \verb|\hspace| command to enter specific amounts of spacing. \begin{demotable} \mdemo{a\!b} \mdemo{a\,b} \mdemo{a\:b} \mdemo{a\;b} \mdemo{a\quad b} \mdemo{a\qquad b} \mdemo{a\hspace{3.0em}b} \end{demotable} \subsection*{Variable-sized symbols} Note that some of the more exotic operators may require extra fonts installed. \newcommand{\dmdemo}[1]{\minout{#1} & \dminout{#1} \\} \newcommand{\vdemo}[1]{\dmdemo{#1_a^b A_{\lambda}}} \newenvironment{dmdemotable} {\begin{center} \begin{tabular}{|r|l|r|l|} \hline \\ Input & Result & Input (Displaymath) & Result \\ \hline \\ }{\hline \end{tabular} \end{center} } \begin{dmdemotable} \vdemo{\sum} \vdemo{\prod} \vdemo{\coprod} \vdemo{\int} \vdemo{\oint} \vdemo{\bigcap} \vdemo{\bigcup} \vdemo{\bigsqcup} \vdemo{\bigvee} \vdemo{\bigwedge} \vdemo{\bigodot} \vdemo{\bigotimes} \vdemo{\bigoplus} \vdemo{\biguplus} \end{dmdemotable} \subsection*{Binary Operators} As with LaTeX, we support the \verb|\not| command to negate certain operators. Only the ones listed in the table below are supported. \newcommand{\rdemo}[1]{\minout{#1} & & \\} \newcommand{\rndemo}[1]{\minout{#1} & \minout{\not #1} \\} \newenvironment{rdemotable} {\begin{center} \begin{tabular}{|r|l|r|l|} \hline \\ Input & Result & Input (negated) & Result \\ \hline \\ }{\hline \end{tabular} \end{center} } \begin{rdemotable} \rdemo{\pm} \rdemo{\mp} \rdemo{\times} \rdemo{\div} \rdemo{\ast} \rdemo{\star} \rdemo{\circ} \rdemo{\bullet} \rdemo{\cdot} \rdemo{\cap} \rdemo{\cup} \rdemo{\uplus} \rdemo{\sqcap} \rdemo{\sqcup} \rdemo{\vee} \rdemo{\lor} \rdemo{\wedge} \rdemo{\land} \rdemo{\setminus} \rdemo{\wr} \rdemo{\diamond} \rdemo{\bigtriangleup} \rdemo{\bigtriangledown} \rdemo{\triangleleft} \rdemo{\triangleright} \rdemo{\oplus} \rdemo{\ominus} \rdemo{\otimes} \rdemo{\oslash} \rdemo{\odot} \rdemo{\bigcirc} \rdemo{\dagger} \rdemo{\ddagger} \rdemo{\amalg} \rndemo{\leq} \rndemo{\le} \rndemo{\prec} \rdemo{\preceq} \rdemo{\ll} \rndemo{\subset} \rndemo{\subseteq} \rdemo{\sqsubset} \rndemo{\sqsubseteq} \rndemo{\in} \rndemo{\vdash} \rndemo{\geq} \rndemo{\ge} \rndemo{\succ} \rdemo{\succeq} \rdemo{\gg} \rndemo{\supset} \rndemo{\supseteq} \rdemo{\sqsupset} \rndemo{\sqsupseteq} \rndemo{\ni} \rdemo{\dashv} \rndemo{\equiv} \rndemo{\sim} \rndemo{\simeq} \rdemo{\asymp} \rndemo{\approx} \rndemo{\cong} \rdemo{\neq} \rdemo{\doteq} \rdemo{\notin} \rdemo{\models} \rdemo{\perp} \rndemo{\mid} \rdemo{\parallel} \rdemo{\bowtie} \rdemo{\smile} \rdemo{\frown} \rdemo{\propto} \end{rdemotable} SnuggleTeX also supports \verb|\stackrel| to make stacked operators: \begin{demotable} \mdemo{1 \stackrel{2}{+} y} \end{demotable} \subsection*{Arrows} \begin{demotable} \mdemo{\leftarrow} \mdemo{\Leftarrow} \mdemo{\rightarrow} \mdemo{\Rightarrow} \mdemo{\leftrightarrow} \mdemo{\Leftrightarrow} \mdemo{\mapsto} \mdemo{\hookleftarrow} \mdemo{\leftharpoonup} \mdemo{\leftharpoondown} \mdemo{\rightleftharpoons} \mdemo{\longleftarrow} \mdemo{\Longleftarrow} \mdemo{\longrightarrow} \mdemo{\Longrightarrow} \mdemo{\longleftrightarrow} \mdemo{\Longleftrightarrow} \mdemo{\longmapsto} \mdemo{\hookrightarrow} \mdemo{\rightharpoonup} \mdemo{\rightharpoondown} \mdemo{\uparrow} \mdemo{\Uparrow} \mdemo{\downarrow} \mdemo{\Downarrow} \mdemo{\updownarrow} \mdemo{\Updownarrow} \mdemo{\nearrow} \mdemo{\searrow} \mdemo{\swarrow} \mdemo{\nwarrow} \end{demotable} \subsection*{Miscellaneous Maths Symbols} \begin{demotable} \mdemo{\aleph} \mdemo{\imath} \mdemo{\jmath} \mdemo{\ell} \mdemo{\wp} \mdemo{\Re} \mdemo{\Im} \mdemo{\mho} \mdemo{\prime} \mdemo{\emptyset} \mdemo{\nabla} \mdemo{\surd} \mdemo{\top} \mdemo{\bot} \mdemo{\angle} \mdemo{\forall} \mdemo{\exists} \mdemo{\neg} \mdemo{\lnot} \mdemo{\flat} \mdemo{\natural} \mdemo{\sharp} \mdemo{\backslash} \mdemo{\partial} \mdemo{\infty} \mdemo{\triangle} \mdemo{\clubsuit} \mdemo{\diamondsuit} \mdemo{\heartsuit} \mdemo{\spadesuit} \mdemo{\hbar} \mdemo{\aa} \mdemo{\AA} \verb_$ \| $_ & $\|$ \\ \end{demotable} \subsection*{Mathematical Accents} Some of these do not work particularly well in some cases, so it is wise to check the results on all of the browsers that you need to support! \newcommand{\mademo}[1]{\minout{#1{x}} & \minout{#1{x-y}} \\ } \newenvironment{mademotable} {\begin{center} \begin{tabular}{|r|l|r|l|} \hline \\ Input (narrow) & Result & Input (wide) & Result \\ \hline \\ }{\hline \end{tabular} \end{center} } \begin{mademotable} \mademo{\hat} \mademo{\bar} \mademo{\vec} \mademo{\dot} \mademo{\ddot} \mademo{\tilde} \mademo{\widehat} \mademo{\widetilde} \mademo{\overline} \mademo{\overbrace} \mademo{\underbrace} \mademo{\overrightarrow} \mademo{\overleftarrow} \mademo{\underline} \end{mademotable} \subsection*{Stretchy Parentheses} \newcommand{\mpdemo}[2]{\minout{\left#1 x \right#2} & \minout{\left#1 \frac{1}{1+\frac{1}{1+x}} \right#2} \\ } \newenvironment{mptable} {\begin{center} \begin{tabular}{|r|l|r|l|} \hline \\ Input (narrow) & Result & Input (wide) & Result \\ \hline \\ }{\hline \end{tabular} \end{center} } \begin{mptable} \mpdemo{(}{)} \mpdemo{[}{]} \mpdemo{\{}{\}} \mpdemo{\vert}{\vert} \mpdemo{\Vert}{\Vert} \mpdemo{<}{>} \mpdemo{.}{)} \mpdemo{[}{.} \end{mptable} \subsection*{Math Fonts} These LaTeX commands apply a particular mathematical style to their arguments. Note that some styles are not supported well by some browsers. \newcommand{\mfdemo}[1]{\mdemo{#1{xyz} + xyz}} \begin{demotable} \mfdemo{\mathrm} \mfdemo{\mathsf} \mfdemo{\mathit} \mfdemo{\mathbf} \mfdemo{\mathtt} \end{demotable} \subsection*{Text inside Maths} SnuggleTeX supports the traditional \verb|\mbox| command to enter LR mode from within math mode. It also supports \verb|\textrm| and friends. \begin{demotable} \mdemo{1\mbox{ if $x=3$}} \mdemo{1\textrm{ if $x=3$}} \mdemo{1\textsf{ if $x=3$}} \mdemo{1\textit{ if $x=3$}} \mdemo{1\textsl{ if $x=3$}} \mdemo{1\textsc{ if $x=3$}} \mdemo{1\textbf{ if $x=3$}} \mdemo{1\texttt{ if $x=3$}} \mdemo{1\emph{ if $x=3$}} \end{demotable} \subsection*{Mathematical Structures} \begin{ndemotable} \newcommand{\biginout}[1]{\begin{verbatim}#1\end{verbatim} & #1} \biginout{\begin{eqnarray*} x & = & y \\ & = & z \end{eqnarray*}} & \note{This is a standard LaTeX \texttt{eqnarray*}. SnuggleTeX also supports \texttt{eqnarray}, though labelling is not supported so it behaves exactly like \texttt{eqnarray*}.} \\ \bigdminout{\left( \begin{array}{cc} 1 & 2 \\ 3 & 4 \end{array} \right)} & \note{This uses the \texttt{array} environment combined with stretchy brackets to make a matrix.} \\ \bigdminout{\begin{matrix} 1 & 2 \\ 3 & 4 \end{matrix}} & \note{SnuggleTeX supports the convenient AMS-LaTeX \texttt{matrix} environment\ldots} \\ \bigdminout{\begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}} & \note{\ldots and \texttt{pmatrix} \ldots} \\ \bigdminout{\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}} & \note{\ldots and \texttt{bmatrix} \ldots} \\ \bigdminout{\begin{Bmatrix} 1 & 2 \\ 3 & 4 \end{Bmatrix}} & \note{\ldots and \texttt{Bmatrix} \ldots} \\ \bigdminout{\begin{vmatrix} 1 & 2 \\ 3 & 4 \end{vmatrix}} & \note{\ldots and \texttt{vmatrix} \ldots} \\ \bigdminout{\begin{Vmatrix} 1 & 2 \\ 3 & 4 \end{Vmatrix}} & \note{\ldots and \texttt{Vmatrix}.} \\ \bigdminout{A=\begin{cases} 1 & 2 \\ 3 & 4 \end{cases}} & \note{Another useful AMS-LaTeX environment environment.} \\ \end{ndemotable} \subsection*{Variant Characters} This is one area of MathML which cause practical issues in browsers, usually due to a lack of fonts. By default, SnuggleTeX adds \texttt{mathvariant} attributes to the MathML whenever variant fonts like "script" (a.k.a.\ "calligraphic"), "fraktur" and "double-struck" are used, leaving the browser to use an appropriate font. By default, Firefox doesn't do anything here so, like similar conversion tools, SnuggleTeX can also try to remap certain "safe" characters to other symbols that users are likely to have installed. The output below demonstrates this. \newcommand{\vcdemo}[1]{\minout{#1{abcdefghijklmnopqrstuvwxyz}} \\ } \newcommand{\vcudemo}[1]{\minout{#1{ABCDEFGHIJKLMNOPQRSTUVWXYZ}} \\ } \newenvironment{vctable} {\begin{center} \begin{tabular}{|r|l|} \hline \\ Input & Result \\ \hline \\ }{\hline \end{tabular} \end{center} } \begin{vctable} \vcdemo{\mathcal} \vcudemo{\mathcal} \vcdemo{\mathsc} \vcudemo{\mathsc} \vcdemo{\mathbb} \vcudemo{\mathbb} \vcdemo{\mathfrak} \vcudemo{\mathfrak} \end{vctable}
Located between Pure Beauty and Strings Italian Cafe in the The Marketplace Marketplace, Cold Stone Creamery is possibly the best Ice Cream ice cream shop in town. Their ice cream is made fresh daily. They custom make ice cream, shakes, smoothies, and cakes. If you tip for any amount, even as small as a penny, all of the employees sing a fun thank you song. Its fun! If you know someone who works there, its even more fun. The price of the ice cream is average compared to other super premium ice creams, and the portions are large. A small size with one mix in costs $3.19, a medium love it is $3.49, and a large Gotta have it is $3.99. If youre a student at UCD, you can get 10% off ice cream by flashing your Reg card. The cakes are a bit more but worth it! The cake is soft and moist unlike most other ice cream cake. Look for coupons...they are always available. They always have a full display of cakes ready for pick up anytime, or you can call and have one custom made. They can usually have your custom cake done within a day. Sometimes the same day, but always within a day. Use the Super Saver Card and get a free Kids Creation Size with purchase of any like it or larger size ice cream OR $3 off any Cold Stone cake. They have a birthday club good for a free creation register on their website. Look for the Market Place coupon book, they always have a coupon in it. Cold Stone does fundraisers: check them out at http://www.coldstonecreamery.com. The fundraisers are fun and easy. They also do field trips for the elementary schools, child care centers, ets. They do birthday parties, office parties, catering for 10 to 1000, special events, and more. If it has to do with Ice cream or cake, Cold Stone can make it happen, so check them out for your next event. They sponsor UCD athletics, so you may want to patronize them to show support for the Aggie team of your choice. Check them out at the Aggie home games: they will be having contests, and giving away prizes. Watch for the next contest where contestants will create a Cold Stone Song, and dance... the winner will get Free Ice Cream for an entire year and the winner gets a creation named after them. There will also be ice cream eating contests and more. History Cold Stone originally opened May 9th, 2005 in Davis. During the January 5th 2008 storm power outage they closed and did not reopen. In June of that year, signs appeared that they were hiring, and on July 8th, they reopened under new ownership. Gotta love ice cream, gelato, or frozen yogurt on a hot Summer day! Older Reviews /Prior to Close Reviews Reviews prior to the Spring 2008 closure Current Reviews 20080725 09:27:13 nbsp I went in to check out the new Cold Stone and was given the ol upsell: Oh, you like chocolate? You should try the quadruple chocolate with extra chocolate. And you like peanut butter? Try our superpeanut buttery delight with extra peanutty goodness! Your taste buds will be so swamped you wont noticed how many more mixins that you had to pay for! Users/CovertProfessor, hoping that this is not regular store practice. 20080729 01:55:40 nbsp Oh I think it is regular store practice amongst several stores (at least throughout Sacramento). Almost every location I have visited has been like that but worse if its possible. In all actuality the employees are usually snobby, rude, incompetent, or just plain annoying. The ice cream itself is average in taste but so many people love it anyway. Users/csmith 20090127 05:34:40 nbsp I cant speak for the new Davis management, but the old management and the stores Ive frequented in Vacaville and Irvine always have fine customer service. . .then again I have a specific order (and I usually get a pint) so maybe they dont bother to upsell me. Users/KellyCorcoran 20090401 09:04:15 nbsp the ladies working there ( havent been any men as of yet) have always been very pleasant and accommodating. Since I dont like chocolate chips in my selection theyve always asked if I want to swap it out. They smile and are polite. Users/patrick82 20090504 16:47:14 nbsp The customer service was good last time I was here. Pretty much the same stuffs with other Cold Stones Ive been to. Users/thtly 20090523 01:54:21 nbsp I got A Cheesecake Named Desire It was the absolute most delicious thing on earth. A cake for 20 dollars really can feed 8 people, and feed as in make full. the cakes are tall, dont be fooled by the small circumference. It can easily feed more if you want people to just get a taste of cake. Users/chand3123k 20100307 00:11:13 nbsp i was an old employee of coldstone creamry and i am so pissed to see that people think o no poor family who owned cold stone couldnt get back on their feet after the power outage! First the family are such asses. The power outage was never the reason they closed. They were doing horribly. I know i worked there. I had a feeling that they were closing but stacy roe, the owner, would just say when they were packing up all the cold stone thing, we are just moving out all the 2008 things to make room for the 2009 stuff! She was planning on closing down. Thankfully i am not stupid, and i started looking for a job. Then during that storm, where yes the power went out, i went in to get my check, and wouldnt you know it stacy and her friends were ripping down the store. She said ok so i kept it a secret, we are closing. WOW she really only gives a crap about herself, not her college student employees who think they have ajob, and dont. Then she handed me $40 and told me that was for working the last 2 weeks! OK STACY you are about $200 short!!! i was to shocked to say anything, but i should have sued her. I hope these people never own another business agian! They are horrible! All stacy would do is come in and complain that she is overwheight. Well ya you eat icecream all day, no joke. I have to say thank god they went under cause i have nightmares about working there! Users/poed 20110123 01:00:50 nbsp This coldstone was already heading south after they got rid of their banana flavor back in September. Users/argyle
{-# OPTIONS --without-K --safe #-} open import Algebra.Structures.Bundles.Field module Algebra.Linear.Morphism.Bundles {k ℓᵏ} (K : Field k ℓᵏ) where open import Algebra.FunctionProperties as FP open import Relation.Binary using (Rel; Setoid) open import Level import Algebra.Linear.Structures.Bundles as VS open import Algebra.Linear.Morphism.VectorSpace K open import Function.Equality as FunEq using (_⟶_; _⟨$⟩_; setoid) module _ {a₁ ℓ₁} (From : VS.VectorSpace K a₁ ℓ₁) {a₂ ℓ₂} (To : VS.VectorSpace K a₂ ℓ₂) where private module F = VS.VectorSpace From module T = VS.VectorSpace To K' : Set k K' = Field.Carrier K open F using () renaming ( Carrier to A ; _≈_ to _≈₁_ ; refl to ≈₁-refl ; sym to ≈₁-sym ; setoid to A-setoid ; _+_ to +₁ ; _∙_ to ∙₁ ) open T using () renaming ( Carrier to B ; _≈_ to _≈₂_ ; refl to ≈₂-refl ; sym to ≈₂-sym ; trans to ≈₂-trans ; setoid to B-setoid ; _+_ to +₂ ; _∙_ to ∙₂ ) hom-setoid : ∀ {Carrier} -> (Carrier -> (A-setoid ⟶ B-setoid)) -> Setoid (suc (k ⊔ a₁ ⊔ a₂ ⊔ ℓ₁ ⊔ ℓ₂)) (a₁ ⊔ ℓ₁ ⊔ ℓ₂) hom-setoid {Carrier} app = record { Carrier = Carrier ; _≈_ = λ f g → ∀ {x y} (r : x ≈₁ y) -> (app f ⟨$⟩ x) ≈₂ (app g ⟨$⟩ y) ; isEquivalence = record { refl = λ {f} -> FunEq.cong (app f) ; sym = λ r rₓ → ≈₂-sym (r (≈₁-sym rₓ)) ; trans = λ r₁ r₂ rₓ → ≈₂-trans (r₁ ≈₁-refl) (r₂ rₓ) } } open LinearDefinitions A B _≈₂_ record LinearMap : Set (suc (k ⊔ a₁ ⊔ a₂ ⊔ ℓ₁ ⊔ ℓ₂)) where field ⟦_⟧ : Morphism isLinearMap : IsLinearMap From To ⟦_⟧ infixr 25 _⟪$⟫_ _⟪$⟫_ : A -> B _⟪$⟫_ = ⟦_⟧ open IsLinearMap isLinearMap public linearMap-setoid : Setoid (suc (k ⊔ a₁ ⊔ a₂ ⊔ ℓ₁ ⊔ ℓ₂)) (a₁ ⊔ ℓ₁ ⊔ ℓ₂) linearMap-setoid = hom-setoid {LinearMap} λ f → record { _⟨$⟩_ = λ x → f LinearMap.⟪$⟫ x ; cong = LinearMap.⟦⟧-cong f } record LinearIsomorphism : Set (suc (k ⊔ a₁ ⊔ a₂ ⊔ ℓ₁ ⊔ ℓ₂)) where field ⟦_⟧ : Morphism isLinearIsomorphism : IsLinearIsomorphism From To ⟦_⟧ open IsLinearIsomorphism isLinearIsomorphism public linearMap : LinearMap linearMap = record { ⟦_⟧ = ⟦_⟧ ; isLinearMap = isLinearMap } open LinearMap linearMap public using (_⟪$⟫_) linearIsomorphism-setoid : Setoid (suc (k ⊔ a₁ ⊔ a₂ ⊔ ℓ₁ ⊔ ℓ₂)) (a₁ ⊔ ℓ₁ ⊔ ℓ₂) linearIsomorphism-setoid = hom-setoid {LinearIsomorphism} λ f → record { _⟨$⟩_ = λ x -> f LinearIsomorphism.⟪$⟫ x ; cong = LinearIsomorphism.⟦⟧-cong f } module _ {a ℓ} (V : VS.VectorSpace K a ℓ) where LinearEndomorphism : Set (suc (k ⊔ a ⊔ ℓ)) LinearEndomorphism = LinearMap V V LinearAutomorphism : Set (suc (k ⊔ a ⊔ ℓ)) LinearAutomorphism = LinearIsomorphism V V
\lesson{3}{Nov 29 2021 Mon (21:06:20)}{Polynomial Transformations}{Unit 3} \begin{definition}[Polynomial Function] A \bf{Polynomial Function} is a function composed of $1$ or more terms, at least $1$ of which contains a variable. A polynomial function whose degree is $3$ is called a \bf{Cubic Function}. A \bf{Polynomial Function} whose degree is $4$ is called a \bf{Quartic Function}. Simple polynomial functions may be graphed by hand by substituting x-coordinates and solving for the corresponding y-coordinates. The real number solutions of a polynomial equation can be found by identifying the x-intercepts from the graph of the function. Graph the function, and find the point(s) of intersection between the graph and the x-axis. \end{definition} \subsubsection*{Odd vs Even vs Neither Polynomial Functions} \begin{center} \begin{table}[h] \begin{tabular}{ |r|c|l| } \hline Result & Function Type & Symmetry \\ \hline \multirow{3}{4em}{} $f(-x) = f(x)$ & Even function & y-axis \\ $f(-x) = -f(x)$ & Odd function & Origin \\ $f(-x) \neq f(x)$ or $f(-x)$ & Neither even and odd & \\ \hline \end{tabular} \caption{Odd vs Even vs Neither Polynomial Functions} \label{table:odd-vs-even-vs-neither-polynomial-functions} \end{table} \end{center} \newpage
open import Data.Bool using (Bool; true; false; _∧_) import Relation.Binary.PropositionalEquality as Eq open Eq using (_≡_; refl; sym; subst) open Eq.≡-Reasoning using (begin_; _≡⟨⟩_; _≡⟨_⟩_; _∎) open import Data.Unit using (⊤; tt) open import Data.Nat using (ℕ; zero; suc; _≤_; _≥_; _>_) open import Data.Product using (_×_; _,_; proj₁; proj₂; Σ-syntax; ∃; ∃-syntax) open import Data.Sum using (_⊎_; inj₁; inj₂) open import Data.List using (List; []; [_]; _∷_; _∷ʳ_; _++_) open import Data.List.Reverse using (Reverse; reverseView) open import Function using (_$_) module SnapshotConsistency (Addr : Set) (_≟_ : Addr → Addr → Bool) (_≤?MAXADDR : Addr → Bool) (_≤?MAXWCNT : ℕ → Bool) (Data : Set) (defaultData : Data) where infixl 20 _•_ infixl 20 _⊙_ infixl 20 _++RTC_ infixl 20 _<≐>_ variable addr : Addr dat : Data _≐_ : {A B : Set} → (A → B) → (A → B) → Set s ≐ t = ∀ a → s a ≡ t a sym-≐ : {A B : Set} {s t : A → B} → s ≐ t → t ≐ s sym-≐ eq = λ{x → sym (eq x)} _<≐>_ : {A B : Set} {s t u : A → B} → s ≐ t → t ≐ u → s ≐ u _<≐>_ {A} {B} {s} {t} {u} e q = λ{x → begin s x ≡⟨ e x ⟩ t x ≡⟨ q x ⟩ u x ∎} data SnocList (A : Set) : Set where [] : SnocList A _•_ : (as : SnocList A) → (a : A) → SnocList A _⊙_ : {A : Set} → SnocList A → SnocList A → SnocList A xs ⊙ [] = xs xs ⊙ (ys • y) = (xs ⊙ ys) • y data All {A : Set} (P : A → Set) : SnocList A → Set where [] : All P [] _∷_ : ∀ {xs : SnocList A} {x : A} → All P xs → P x → All P (xs • x) _++All_ : {A : Set} {P : A → Set} {xs ys : SnocList A} → All P xs → All P ys → All P (xs ⊙ ys) all₁ ++All [] = all₁ all₁ ++All (all₂ ∷ x) = all₁ ++All all₂ ∷ x mapAll : {A : Set} {P Q : A → Set} {xs : SnocList A} → ({x : A} → P x → Q x) → All P xs → All Q xs mapAll pq [] = [] mapAll pq (all ∷ x) = (mapAll pq all) ∷ (pq x) data Action : Set where w[_↦_] : (addr : Addr) (dat : Data) → Action f : Action r : Action wᶜ[_↦_] : (addr : Addr) (dat : Data) → Action fᶜ : Action rᶜ : Action cp : Action er : Action cpᶜ : Action erᶜ : Action variable ac : Action data Regular : Action → Set where w : Regular w[ addr ↦ dat ] cp : Regular cp er : Regular er data Write : Action → Set where w : Write w[ addr ↦ dat ] data Snapshot : Action → Set where f : Snapshot f data RecoveryCrash : Action → Set where rᶜ : RecoveryCrash rᶜ data RegularSuccess : Action → Set where w : RegularSuccess w[ addr ↦ dat ] f : RegularSuccess f data Regular×Snapshot : Action → Set where w : Regular×Snapshot w[ addr ↦ dat ] cp : Regular×Snapshot cp er : Regular×Snapshot er f : Regular×Snapshot f data Regular×SnapshotCrash : Action → Set where wᶜ : Regular×SnapshotCrash wᶜ[ addr ↦ dat ] fᶜ : Regular×SnapshotCrash fᶜ cpᶜ : Regular×SnapshotCrash cpᶜ erᶜ : Regular×SnapshotCrash erᶜ Trace = SnocList Action variable ef : Trace ef₁ : Trace ef₂ : Trace ef₃ : Trace frag : Trace frag-w : Trace frag-rᶜ : Trace flist : SnocList Action flist-w : SnocList Action flist-rᶜ : SnocList Action --Reflexive Transitive Closure data RTC {A S : Set} (R : S → A → S → Set) : S → SnocList A → S → Set where ∅ : ∀ {s : S} → RTC R s [] s _•_ : ∀ {s t u : S} {acs : SnocList A} {ac : A} → RTC R s acs t → R t ac u → RTC R s (acs • ac) u _++RTC_ : {A S : Set} {R : S → A → S → Set} {s t u : S} {ef₁ ef₂ : SnocList A} → RTC R s ef₁ t → RTC R t ef₂ u → RTC R s (ef₁ ⊙ ef₂) u tc-s-t ++RTC ∅ = tc-s-t tc-s-t ++RTC (tc-t-u • rr) = (tc-s-t ++RTC tc-t-u) • rr splitRTC : {A S : Set} {R : S → A → S → Set} {s s' : S} → (splitOn : SnocList A) → {rest : SnocList A} → ( fr : RTC R s (splitOn ⊙ rest) s') → Σ[ s'' ∈ S ] Σ[ fr₁ ∈ RTC R s splitOn s'' ] Σ[ fr₂ ∈ RTC R s'' rest s' ] (fr ≡ (fr₁ ++RTC fr₂)) splitRTC ef₁ {rest = []} t = (_ , t , ∅ , refl) splitRTC ef₁ {rest = (ef₂ • ac)} (t • rr) with splitRTC ef₁ t ... | s'' , t₁ , t₂ , refl = s'' , t₁ , t₂ • rr , refl data OneRecovery : Trace → Set where wᶜ : {tr₁ tr₂ tr₃ : Trace} → All Regular×Snapshot tr₁ → All Regular tr₂ → All RecoveryCrash tr₃ → OneRecovery (tr₁ ⊙ ([] • f ⊙ tr₂) ⊙ ([] • wᶜ[ addr ↦ dat ] ⊙ tr₃ • r)) fᶜ : {tr₁ tr₂ tr₃ : Trace} → All Regular×Snapshot tr₁ → All Regular tr₂ → All RecoveryCrash tr₃ → OneRecovery (tr₁ ⊙ ([] • f ⊙ tr₂) ⊙ ([] • fᶜ ⊙ tr₃ • r)) wᶜ-nof : {tr₂ tr₃ : Trace} → All Regular tr₂ → All RecoveryCrash tr₃ → OneRecovery (tr₂ ⊙ ([] • wᶜ[ addr ↦ dat ] ⊙ tr₃ • r)) fᶜ-nof : {tr₂ tr₃ : Trace} → All Regular tr₂ → All RecoveryCrash tr₃ → OneRecovery (tr₂ ⊙ ([] • fᶜ ⊙ tr₃ • r)) data MultiRecovery : Trace → Set where init : {tr : Trace} → All RecoveryCrash tr → MultiRecovery (tr • r) one : {tr₁ tr₂ : Trace} → MultiRecovery tr₁ → OneRecovery tr₂ → MultiRecovery (tr₁ ⊙ tr₂) data 1RFrags {S : Set} {R : S → Action → S → Set} : {s s' : S} {tr : Trace} → OneRecovery tr → RTC R s tr s' → Set where wᶜ : {tr₁ tr₂ tr₃ : Trace} {all₁ : All Regular×Snapshot tr₁} {all₂ : All Regular tr₂} {all₃ : All RecoveryCrash tr₃} → {s₁ s₂ s₃ s₄ : S} (fr₁ : RTC R s₁ tr₁ s₂) (fr₂ : RTC R s₂ ([] • f ⊙ tr₂) s₃) (fr₃ : RTC R s₃ ([] • wᶜ[ addr ↦ dat ] ⊙ tr₃ • r) s₄) → 1RFrags (wᶜ all₁ all₂ all₃) (fr₁ ++RTC fr₂ ++RTC fr₃) fᶜ : {tr₁ tr₂ tr₃ : Trace} {all₁ : All Regular×Snapshot tr₁} {all₂ : All Regular tr₂} {all₃ : All RecoveryCrash tr₃} → {s₁ s₂ s₃ s₄ : S} (fr₁ : RTC R s₁ tr₁ s₂) (fr₂ : RTC R s₂ ([] • f ⊙ tr₂) s₃) (fr₃ : RTC R s₃ ([] • fᶜ ⊙ tr₃ • r) s₄) → 1RFrags (fᶜ all₁ all₂ all₃) (fr₁ ++RTC fr₂ ++RTC fr₃) wᶜ-nof : {tr₂ tr₃ : Trace} {all₂ : All Regular tr₂} {all₃ : All RecoveryCrash tr₃} → {s₂ s₃ s₄ : S} (fr₂ : RTC R s₂ tr₂ s₃) (fr₃ : RTC R s₃ ([] • wᶜ[ addr ↦ dat ] ⊙ tr₃ • r) s₄) → 1RFrags (wᶜ-nof all₂ all₃) (fr₂ ++RTC fr₃) fᶜ-nof : {tr₂ tr₃ : Trace} {all₂ : All Regular tr₂} {all₃ : All RecoveryCrash tr₃} → {s₂ s₃ s₄ : S} (fr₂ : RTC R s₂ tr₂ s₃) (fr₃ : RTC R s₃ ([] • fᶜ ⊙ tr₃ • r) s₄) → 1RFrags (fᶜ-nof all₂ all₃) (fr₂ ++RTC fr₃) view1R : {tr : Trace} (1r : OneRecovery tr) {S : Set} {R : S → Action → S → Set} {s s' : S} (fr : RTC R s tr s') → 1RFrags 1r fr view1R (wᶜ {tr₁ = tr₁} {tr₂ = tr₂} {tr₃ = tr₃} all₁ all₂ all₃) {s = s₁} {s' = s₄} fr with splitRTC (tr₁ ⊙ ([] • f ⊙ tr₂)) {rest = [] • wᶜ[ _ ↦ _ ] ⊙ tr₃ • r} fr ... | s₃ , fr-l , fr₃ , refl with splitRTC tr₁ {rest = [] • f ⊙ tr₂} fr-l ... | s₂ , fr₁ , fr₂ , refl = wᶜ fr₁ fr₂ fr₃ view1R (fᶜ {tr₁ = tr₁} {tr₂ = tr₂} {tr₃ = tr₃} all₁ all₂ all₃) {s = s₁} {s' = s₄} fr with splitRTC (tr₁ ⊙ ([] • f ⊙ tr₂)) {rest = [] • fᶜ ⊙ tr₃ • r} fr ... | s₃ , fr-l , fr₃ , refl with splitRTC tr₁ {rest = [] • f ⊙ tr₂} fr-l ... | s₂ , fr₁ , fr₂ , refl = fᶜ fr₁ fr₂ fr₃ view1R (wᶜ-nof {tr₂ = tr₂} {tr₃ = tr₃} all₂ all₃) fr with splitRTC tr₂ fr ... | _ , fr₁ , fr₂ , refl = wᶜ-nof fr₁ fr₂ view1R (fᶜ-nof {tr₂ = tr₂} {tr₃ = tr₃} all₂ all₃) fr with splitRTC tr₂ fr ... | _ , fr₁ , fr₂ , refl = fᶜ-nof fr₁ fr₂ data MRFrags {S : Set} {R : S → Action → S → Set} : {s s' : S} {tr : Trace} → MultiRecovery tr → RTC R s tr s' → Set where init : {tr : Trace} {all : All RecoveryCrash tr} {s s' : S} (fr : RTC R s (tr • r) s') → MRFrags (init all) fr one : {tr₁ : Trace} {mr : MultiRecovery tr₁} {s₁ s₂ : S} {fr₁ : RTC R s₁ tr₁ s₂} → MRFrags mr fr₁ → {tr₂ : Trace} {1r : OneRecovery tr₂} {s₃ : S} (fr₂ : RTC R s₂ tr₂ s₃) → 1RFrags 1r fr₂ → MRFrags (one mr 1r) (fr₁ ++RTC fr₂) viewMR : {tr : Trace} (mr : MultiRecovery tr) {S : Set} {R : S → Action → S → Set} {s s' : S} (fr : RTC R s tr s') → MRFrags mr fr viewMR (init all) fr = init fr viewMR (one {tr₁ = tr₁} mr all) fr with splitRTC tr₁ fr ... | _ , fr-l , fr-r , refl = one (viewMR mr fr-l) fr-r (view1R all fr-r) lastr : {S : Set} {s s' : S} {R : S → Action → S → Set} {tr : Trace} (mr : MultiRecovery tr) → (fr : RTC R s tr s') → (frs : MRFrags mr fr) → Σ[ s'' ∈ S ] (R s'' r s') lastr .(init _) .fr (init fr) with fr ... | _ • x = _ , x lastr ._ ._ (one _ ._ (wᶜ _ _ (fr₃ • x))) = _ , x lastr ._ ._ (one _ ._ (fᶜ _ _ (fr₃ • x))) = _ , x lastr ._ ._ (one _ ._ (wᶜ-nof _ (fr₃ • x))) = _ , x lastr ._ ._ (one _ ._ (fᶜ-nof _ (fr₃ • x))) = _ , x SnapshotConsistency : {S : Set} {s s' : S} {R : S → Action → S → Set} (ER : S → S → Set) {tr : Trace} → (1r : OneRecovery tr) → (fr : RTC R s tr s') → 1RFrags 1r fr → Set SnapshotConsistency ER ._ ._ (wᶜ {s₂ = s₂} {s₄ = s₄} _ _ _) = ER s₂ s₄ SnapshotConsistency ER ._ ._ (fᶜ {s₂ = s₂} {s₃} {s₄} _ _ _) = ER s₃ s₄ ⊎ ER s₂ s₄ SnapshotConsistency ER ._ ._ (wᶜ-nof {s₂ = s₂} {s₄ = s₄} _ _) = ER s₂ s₄ SnapshotConsistency ER ._ ._ (fᶜ-nof {s₂ = s₂} {s₃} {s₄} _ _) = ER s₃ s₄ ⊎ ER s₂ s₄ module Spec where record State : Set where field volatile : Addr → Data stable : Addr → Data w-count : ℕ Init : State → Set Init s = (addr : Addr) → (State.stable s addr ≡ defaultData) variable t : State t' : State update : (Addr → Data) → ℕ → Addr → Data → (Addr → Data) update s wcnt addr dat i with (addr ≤?MAXADDR) ∧ (wcnt ≤?MAXWCNT) update s wcnt addr dat i | false = s i update s wcnt addr dat i | true with addr ≟ i update s wcnt addr dat i | true | true = dat update s wcnt addr dat i | true | false = s i data Step (s s' : State) : Action → Set where w : update (State.volatile s) (State.w-count s) addr dat ≐ State.volatile s' → State.stable s ≐ State.stable s' → suc (State.w-count s) ≡ State.w-count s' → Step s s' w[ addr ↦ dat ] f : State.volatile s ≐ State.volatile s' → State.volatile s ≐ State.stable s' → State.w-count s' ≡ zero → Step s s' f r : State.stable s ≐ State.volatile s' → State.stable s ≐ State.stable s' → State.w-count s' ≡ zero → Step s s' r wᶜ : State.stable s ≐ State.stable s' → Step s s' (wᶜ[ addr ↦ dat ]) fᶜ : State.volatile s ≐ State.stable s' ⊎ State.stable s ≐ State.stable s' → Step s s' fᶜ rᶜ : State.stable s ≐ State.stable s' → Step s s' rᶜ cp : State.volatile s ≐ State.volatile s' → State.stable s ≐ State.stable s' → State.w-count s ≡ State.w-count s' → Step s s' cp er : State.volatile s ≐ State.volatile s' → State.stable s ≐ State.stable s' → State.w-count s ≡ State.w-count s' → Step s s' er cpᶜ : State.stable s ≐ State.stable s' → Step s s' cpᶜ erᶜ : State.stable s ≐ State.stable s' → Step s s' erᶜ _⟦_⟧▸_ : State → Action → State → Set s ⟦ ac ⟧▸ s' = Step s s' ac _⟦_⟧*▸_ = RTC _⟦_⟧▸_ record StbP (ac : Action) : Set where --Stability Reserving Actions field preserve : {s s' : State} → s ⟦ ac ⟧▸ s' → (State.stable s ≐ State.stable s') instance stb-r : StbP r stb-r = record { preserve = λ{(r _ ss _) → ss} } stb-w : StbP w[ addr ↦ dat ] stb-w = record { preserve = λ{(w _ ss _ ) → ss} } stb-wᶜ : StbP wᶜ[ addr ↦ dat ] stb-wᶜ = record { preserve = λ{(wᶜ ss) → ss} } stb-rᶜ : StbP rᶜ stb-rᶜ = record { preserve = λ{(rᶜ ss) → ss} } stb-cp : StbP cp stb-cp = record { preserve = λ{(cp _ ss _) → ss}} stb-er : StbP er stb-er = record { preserve = λ{(er _ ss _) → ss}} stb-cpᶜ : StbP cpᶜ stb-cpᶜ = record { preserve = λ{(cpᶜ ss) → ss}} stb-erᶜ : StbP erᶜ stb-erᶜ = record { preserve = λ{(erᶜ ss) → ss}} idemₛ : {tr : Trace} → All StbP tr → ∀ {s s' : State} → s ⟦ tr ⟧*▸ s' → State.stable s ≐ State.stable s' idemₛ [] ∅ = λ{_ → refl} idemₛ (all ∷ x) (s2s'' • s''2s') = idemₛ all s2s'' <≐> StbP.preserve x s''2s' r→rs : Regular ac → Regular×Snapshot ac r→rs w = w r→rs cp = cp r→rs er = er n→sp : Regular ac → StbP ac n→sp w = stb-w n→sp cp = stb-cp n→sp er = stb-er rᶜ→sp : RecoveryCrash ac → StbP ac rᶜ→sp rᶜ = stb-rᶜ SpecSC-wᶜ : ∀ {s₂ s₃ s₄ : State} {tr-w tr-rᶜ} → {{_ : All Regular tr-w}} {{_ : All RecoveryCrash tr-rᶜ}} → s₂ ⟦ [] • f ⊙ tr-w ⟧*▸ s₃ → s₃ ⟦ [] • wᶜ[ addr ↦ dat ] ⊙ tr-rᶜ • r ⟧*▸ s₄ → State.volatile s₂ ≐ State.volatile s₄ SpecSC-wᶜ {{ all₂ }} {{ all₃ }} s₂▸s₃ (s₃▹ • r sv _ _) with splitRTC ([] • f) s₂▸s₃ | splitRTC ([] • wᶜ[ _ ↦ _ ]) s₃▹ ... | s₂' , ∅ • (f vv vs _) , s₂'▸s₃ , _ | s₃' , ∅ • (wᶜ ss) , s₃'▸s₄▹ , _ = vs <≐> idemₛ (mapAll n→sp all₂) s₂'▸s₃ <≐> ss <≐> idemₛ (mapAll rᶜ→sp all₃) s₃'▸s₄▹ <≐> sv SpecSC-wᶜ-nof : ∀ {s₁ s₂ s₃ s₄ : State} {tr-w tr-rᶜ} → {{_ : All Regular tr-w}} {{_ : All RecoveryCrash tr-rᶜ}} → s₁ ⟦ r ⟧▸ s₂ → s₂ ⟦ tr-w ⟧*▸ s₃ → s₃ ⟦ [] • wᶜ[ addr ↦ dat ] ⊙ tr-rᶜ • r ⟧*▸ s₄ → State.volatile s₂ ≐ State.volatile s₄ SpecSC-wᶜ-nof {{ all₂ }} {{ all₃ }} (r sv' ss' _) s₂▸s₃ (s₃▹ • r sv _ _) with splitRTC ([] • wᶜ[ _ ↦ _ ]) s₃▹ ... | s₃' , ∅ • (wᶜ ss) , s₃'▸s₄▹ , _ = sym-≐ sv' <≐> ss' <≐> idemₛ (mapAll n→sp all₂) s₂▸s₃ <≐> ss <≐> idemₛ (mapAll rᶜ→sp all₃) s₃'▸s₄▹ <≐> sv SpecSC-fᶜ : ∀ {s₂ s₃ s : State} {tr-w tr-rᶜ} → {{_ : All Regular tr-w}} {{_ : All RecoveryCrash tr-rᶜ}} → s₂ ⟦ ([] • f) ⊙ tr-w ⟧*▸ s₃ → s₃ ⟦ ([] • fᶜ) ⊙ tr-rᶜ • r ⟧*▸ s → State.volatile s₃ ≐ State.volatile s ⊎ State.volatile s₂ ≐ State.volatile s SpecSC-fᶜ {{all₁}} {{all₂}} s₂▸s₃ (s₃▸s • r sv ss _) with splitRTC ([] • f) s₂▸s₃ | splitRTC ([] • fᶜ) s₃▸s ... | _ , ∅ • f vv vs _ , ▸s₃ , _ | s₃' , ∅ • fᶜ (inj₁ vsᶜ) , s₃'▸s , _ = inj₁ $ vsᶜ <≐> idemₛ (mapAll rᶜ→sp all₂) s₃'▸s <≐> sv ... | _ , ∅ • f vv vs _ , ▸s₃ , _ | s₃' , ∅ • fᶜ (inj₂ ssᶜ) , s₃'▸s , _ = inj₂ $ vs <≐> idemₛ (mapAll n→sp all₁) ▸s₃ <≐> ssᶜ <≐> idemₛ (mapAll rᶜ→sp all₂) s₃'▸s <≐> sv SpecSC-fᶜ-nof : ∀ {s₁ s₂ s₃ s₄ : State} {tr-w tr-rᶜ} → {{_ : All Regular tr-w}} {{_ : All RecoveryCrash tr-rᶜ}} → s₁ ⟦ r ⟧▸ s₂ → s₂ ⟦ tr-w ⟧*▸ s₃ → s₃ ⟦ [] • fᶜ ⊙ tr-rᶜ • r ⟧*▸ s₄ → State.volatile s₃ ≐ State.volatile s₄ ⊎ State.volatile s₂ ≐ State.volatile s₄ SpecSC-fᶜ-nof {{ all₂ }} {{ all₃ }} (r sv' ss' _) s₂▸s₃ (s₃▹ • r sv _ _) with splitRTC ([] • fᶜ) s₃▹ ... | s₃' , ∅ • fᶜ (inj₁ vsᶜ) , s₃'▸s , _ = inj₁ $ vsᶜ <≐> idemₛ (mapAll rᶜ→sp all₃) s₃'▸s <≐> sv ... | s₃' , ∅ • fᶜ (inj₂ ssᶜ) , s₃'▸s , _ = inj₂ $ sym-≐ sv' <≐> ss' <≐> idemₛ (mapAll n→sp all₂) s₂▸s₃ <≐> ssᶜ <≐> idemₛ (mapAll rᶜ→sp all₃) s₃'▸s <≐> sv SC : {t₀ t t' : State} {tr₀ tr : Trace} → (mr : MultiRecovery tr₀) → (1r : OneRecovery tr) → Init t₀ → (fr₀ : t₀ ⟦ tr₀ ⟧*▸ t) → MRFrags mr fr₀ → (fr : t ⟦ tr ⟧*▸ t') → (frs : 1RFrags 1r fr) → SnapshotConsistency (λ t t' → State.volatile t ≐ State.volatile t') 1r fr frs SC mr _ init-t₀ fr₀ frs₀ ._ (wᶜ {all₂ = all₂} {all₃} fr₁ fr₂ fr₃) = SpecSC-wᶜ {{all₂}} {{all₃}} fr₂ fr₃ SC mr _ init-t₀ fr₀ frs₀ ._ (fᶜ {all₂ = all₂} {all₃} fr₁ fr₂ fr₃) = SpecSC-fᶜ {{all₂}} {{all₃}} fr₂ fr₃ SC mr _ init-t₀ fr₀ frs₀ ._ (wᶜ-nof {all₂ = all₂} {all₃} fr₂ fr₃) = SpecSC-wᶜ-nof {{all₂}} {{all₃}} (proj₂ (lastr mr fr₀ frs₀)) fr₂ fr₃ SC mr _ init-t₀ fr₀ frs₀ ._ (fᶜ-nof {all₂ = all₂} {all₃} fr₂ fr₃) = SpecSC-fᶜ-nof {{all₂}} {{all₃}} (proj₂ (lastr mr fr₀ frs₀)) fr₂ fr₃ open Spec hiding (SC) module Prog (runSpec : (t : State) (ac : Action) → ∃[ t' ] (t ⟦ ac ⟧▸ t')) (RawStateᴾ : Set) (_⟦_⟧ᴿ▸_ : RawStateᴾ → Action → RawStateᴾ → Set) (RI CI : RawStateᴾ → Set) (AR CR : RawStateᴾ → State → Set) (RIRI : {s s' : RawStateᴾ} {ac : Action} → Regular×Snapshot ac → s ⟦ ac ⟧ᴿ▸ s' → RI s → RI s') (ARAR : {s s' : RawStateᴾ} {t t' : State} {ac : Action} → Regular×Snapshot ac → s ⟦ ac ⟧ᴿ▸ s' → t ⟦ ac ⟧▸ t' → RI s × AR s t → AR s' t') (RICI : {s s' : RawStateᴾ} {ac : Action} → Regular×SnapshotCrash ac → s ⟦ ac ⟧ᴿ▸ s' → RI s → CI s') (ARCR : {s s' : RawStateᴾ} {t t' : State} {ac : Action} → Regular×SnapshotCrash ac → s ⟦ ac ⟧ᴿ▸ s' → t ⟦ ac ⟧▸ t' → RI s × AR s t → CR s' t') (CIRI : {s s' : RawStateᴾ} → s ⟦ r ⟧ᴿ▸ s' → CI s → RI s') (CRAR : {s s' : RawStateᴾ} {t t' : State} → s ⟦ r ⟧ᴿ▸ s' → t ⟦ r ⟧▸ t' → CI s × CR s t → AR s' t') (CICI : {s s' : RawStateᴾ} → s ⟦ rᶜ ⟧ᴿ▸ s' → CI s → CI s') (CRCR : {s s' : RawStateᴾ} {t t' : State} → s ⟦ rᶜ ⟧ᴿ▸ s' → t ⟦ rᶜ ⟧▸ t' → CI s × CR s t → CR s' t') (read : RawStateᴾ → Addr → Data) (AR⇒ObsEquiv : {s : RawStateᴾ} {t : State} → RI s × AR s t → read s ≐ State.volatile t) (Initᴿ : RawStateᴾ → Set) (initᴿ-CI : (s : RawStateᴾ) → Initᴿ s → CI s) (initᴿ-CR : (s : RawStateᴾ) → Initᴿ s → (t : State) → Init t → CR s t) (t-init : Σ[ t ∈ State ] Init t) where variable rs : RawStateᴾ rs₁ : RawStateᴾ rinv : RI rs cinv : CI rs rs' : RawStateᴾ rs'' : RawStateᴾ rs''' : RawStateᴾ rinv' : RI rs' cinv' : CI rs' _⟦_⟧ᴿ*▸_ = RTC _⟦_⟧ᴿ▸_ data Inv (rs : RawStateᴾ) : Set where normal : RI rs → Inv rs crash : CI rs → Inv rs Stateᴾ : Set Stateᴾ = Σ[ rs ∈ RawStateᴾ ] Inv rs data Initᴾ : Stateᴾ → Set where init : Initᴿ rs → Initᴾ (rs , crash cinv) variable s : Stateᴾ s' : Stateᴾ s'' : Stateᴾ s''' : Stateᴾ data _⟦_⟧ᴾ▸_ : Stateᴾ → Action → Stateᴾ → Set where w : rs ⟦ w[ addr ↦ dat ] ⟧ᴿ▸ rs' → (rs , normal rinv) ⟦ w[ addr ↦ dat ] ⟧ᴾ▸ (rs' , normal rinv') f : rs ⟦ f ⟧ᴿ▸ rs' → (rs , normal rinv) ⟦ f ⟧ᴾ▸ (rs' , normal rinv') wᶜ : rs ⟦ wᶜ[ addr ↦ dat ] ⟧ᴿ▸ rs' → (rs , normal rinv) ⟦ wᶜ[ addr ↦ dat ] ⟧ᴾ▸ (rs' , crash cinv') fᶜ : rs ⟦ fᶜ ⟧ᴿ▸ rs' → (rs , normal rinv) ⟦ fᶜ ⟧ᴾ▸ (rs' , crash cinv') rᶜ : rs ⟦ rᶜ ⟧ᴿ▸ rs' → (rs , crash cinv) ⟦ rᶜ ⟧ᴾ▸ (rs' , crash cinv') r : rs ⟦ r ⟧ᴿ▸ rs' → (rs , crash cinv) ⟦ r ⟧ᴾ▸ (rs' , normal rinv') cp : rs ⟦ cp ⟧ᴿ▸ rs' → (rs , normal rinv) ⟦ cp ⟧ᴾ▸ (rs' , normal rinv') er : rs ⟦ er ⟧ᴿ▸ rs' → (rs , normal rinv) ⟦ er ⟧ᴾ▸ (rs' , normal rinv') cpᶜ : rs ⟦ cpᶜ ⟧ᴿ▸ rs' → (rs , normal rinv) ⟦ cpᶜ ⟧ᴾ▸ (rs' , crash cinv') erᶜ : rs ⟦ erᶜ ⟧ᴿ▸ rs' → (rs , normal rinv) ⟦ erᶜ ⟧ᴾ▸ (rs' , crash cinv') _⟦_⟧ᴾ*▸_ = RTC _⟦_⟧ᴾ▸_ lift-n×s : {tr : Trace} {{_ : All Regular×Snapshot tr}} → rs ⟦ tr ⟧ᴿ*▸ rs' → ∃[ rinv' ] ((rs , normal rinv) ⟦ tr ⟧ᴾ*▸ (rs' , normal rinv')) lift-n×s ∅ = _ , ∅ lift-n×s {{all ∷ w}} (rs*▸rs'' • rs''▸rs') = let (rinv'' , s*▸s'') = lift-n×s {{all}} rs*▸rs'' in RIRI w rs''▸rs' rinv'' , s*▸s'' • w rs''▸rs' lift-n×s {{all ∷ f}} (rs*▸rs'' • rs''▸rs') = let (rinv'' , s*▸s'') = lift-n×s {{all}} rs*▸rs'' in RIRI f rs''▸rs' rinv'' , s*▸s'' • f rs''▸rs' lift-n×s {{all ∷ cp}} (rs*▸rs'' • rs''▸rs') = let (rinv'' , s*▸s'') = lift-n×s {{all}} rs*▸rs'' in RIRI cp rs''▸rs' rinv'' , s*▸s'' • cp rs''▸rs' lift-n×s {{all ∷ er}} (rs*▸rs'' • rs''▸rs') = let (rinv'' , s*▸s'') = lift-n×s {{all}} rs*▸rs'' in RIRI er rs''▸rs' rinv'' , s*▸s'' • er rs''▸rs' lift-n : {tr : Trace} {{_ : All Regular tr}} → rs ⟦ tr ⟧ᴿ*▸ rs' → ∃[ rinv' ] ((rs , normal rinv) ⟦ tr ⟧ᴾ*▸ (rs' , normal rinv')) lift-n {{all}} rs*▸rs' = lift-n×s {{(mapAll (λ{w → w; cp → cp; er → er}) all)}} rs*▸rs' lift-rᶜ : {tr : Trace} {{_ : All RecoveryCrash tr}} → rs ⟦ tr ⟧ᴿ*▸ rs' → ∃[ cinv' ] ((rs , crash cinv) ⟦ tr ⟧ᴾ*▸ (rs' , crash cinv')) lift-rᶜ ∅ = _ , ∅ lift-rᶜ {{all ∷ rᶜ}} (rs*▸rs'' • rs''▸rs') = let (cinv'' , s*▸s'') = lift-rᶜ {{all}} rs*▸rs'' in CICI rs''▸rs' cinv'' , s*▸s'' • rᶜ rs''▸rs' lift-mr : {tr : Trace} (mr : MultiRecovery tr) (fr : rs ⟦ tr ⟧ᴿ*▸ rs') → MRFrags mr fr → Initᴿ rs → ∃[ cinv ] ∃[ rinv' ] let s = (rs , crash cinv) in (s ⟦ tr ⟧ᴾ*▸ (rs' , normal rinv')) × Initᴾ s lift-mr ._ ._ (init {all = all} fr) init-rs with fr ... | fr₀ • rr with lift-rᶜ {cinv = initᴿ-CI _ init-rs} {{all}} fr₀ ... | cinv₀ , fr₀ᴾ = _ , CIRI rr cinv₀ , fr₀ᴾ • r rr , init init-rs lift-mr ._ ._ (one frs₀ fr frs) init-rs with lift-mr _ _ frs₀ init-rs lift-mr ._ ._ (one frs₀ ._ (wᶜ {tr₃ = tr₃} {all₁ = all₁} {all₂} {all₃} fr₁ fr₂ fr₃)) init-rs | cinv₀ , rinv₀ , fr₀ᴾ , init-s with splitRTC ([] • (wᶜ[ _ ↦ _ ])) {rest = (tr₃ • r)} fr₃ ... | rs'' , ∅ • s₃▸s₃' , s₃'▸r • r▸rs' , eq with lift-n×s {rinv = rinv₀} {{all₁}} fr₁ ... | rinv₁ , frP₁ with lift-n×s {rinv = rinv₁} {{ ([] ∷ f) ++All mapAll r→rs all₂ }} fr₂ ... | rinv₂ , frP₂ with RICI wᶜ s₃▸s₃' rinv₂ ... | cinv₂' with lift-rᶜ {cinv = cinv₂'} {{all₃}} s₃'▸r ... | cinv₃ , frP₃ with CIRI r▸rs' cinv₃ ... | rinv₄ = cinv₀ , rinv₄ , fr₀ᴾ ++RTC (frP₁ ++RTC frP₂ ++RTC ((∅ • wᶜ s₃▸s₃') ++RTC (frP₃ • r r▸rs'))), init-s lift-mr ._ ._ (one frs₀ ._ (fᶜ {tr₃ = tr₃} {all₁ = all₁} {all₂} {all₃} fr₁ fr₂ fr₃)) init-rs | cinv₀ , rinv₀ , fr₀ᴾ , init-s with splitRTC ([] • fᶜ) {rest = (tr₃ • r)} fr₃ ... | rs'' , ∅ • s₃▸s₃' , s₃'▸r • r▸rs' , eq with lift-n×s {rinv = rinv₀} {{all₁}} fr₁ ... | rinv₁ , frP₁ with lift-n×s {rinv = rinv₁} {{ ([] ∷ f) ++All mapAll r→rs all₂ }} fr₂ ... | rinv₂ , frP₂ with RICI fᶜ s₃▸s₃' rinv₂ ... | cinv₂' with lift-rᶜ {cinv = cinv₂'} {{all₃}} s₃'▸r ... | cinv₃ , frP₃ with CIRI r▸rs' cinv₃ ... | rinv₄ = cinv₀ , rinv₄ , fr₀ᴾ ++RTC (frP₁ ++RTC frP₂ ++RTC ((∅ • fᶜ s₃▸s₃') ++RTC (frP₃ • r r▸rs'))), init-s lift-mr ._ ._ (one frs₀ ._ (wᶜ-nof {tr₃ = tr₃} {all₂ = all₂} {all₃} fr₂ fr₃)) init-rs | cinv₀ , rinv₀ , fr₀ᴾ , init-s with splitRTC ([] • wᶜ[ _ ↦ _ ]) {rest = (tr₃ • r)} fr₃ ... | rs'' , ∅ • s₃▸s₃' , s₃'▸r • r▸rs' , eq with lift-n×s {rinv = rinv₀} {{ mapAll r→rs all₂ }} fr₂ ... | rinv₂ , frP₂ with RICI wᶜ s₃▸s₃' rinv₂ ... | cinv₂' with lift-rᶜ {cinv = cinv₂'} {{all₃}} s₃'▸r ... | cinv₃ , frP₃ with CIRI r▸rs' cinv₃ ... | rinv₄ = cinv₀ , rinv₄ , fr₀ᴾ ++RTC (frP₂ ++RTC ((∅ • wᶜ s₃▸s₃') ++RTC (frP₃ • r r▸rs'))), init-s lift-mr ._ ._ (one frs₀ ._ (fᶜ-nof {tr₃ = tr₃} {all₂ = all₂} {all₃} fr₂ fr₃)) init-rs | cinv₀ , rinv₀ , fr₀ᴾ , init-s with splitRTC ([] • fᶜ) {rest = (tr₃ • r)} fr₃ ... | rs'' , ∅ • s₃▸s₃' , s₃'▸r • r▸rs' , eq with lift-n×s {rinv = rinv₀} {{ mapAll r→rs all₂ }} fr₂ ... | rinv₂ , frP₂ with RICI fᶜ s₃▸s₃' rinv₂ ... | cinv₂' with lift-rᶜ {cinv = cinv₂'} {{all₃}} s₃'▸r ... | cinv₃ , frP₃ with CIRI r▸rs' cinv₃ ... | rinv₄ = cinv₀ , rinv₄ , fr₀ᴾ ++RTC (frP₂ ++RTC ((∅ • fᶜ s₃▸s₃') ++RTC (frP₃ • r r▸rs'))), init-s ObsEquiv : Stateᴾ → State → Set ObsEquiv (rs , _) t = read rs ≐ State.volatile t data SR : Stateᴾ → State → Set where ar : AR rs t → SR (rs , normal rinv) t cr : CR rs t → SR (rs , crash cinv) t simSR : SR s t → s ⟦ ac ⟧ᴾ▸ s' → ∃[ t' ] (t ⟦ ac ⟧▸ t' × SR s' t') simSR {s , normal rinv} {t} (ar AR-rs-t) (w {addr = addr} {dat = dat} rs▸rs') = let (t' , t▸t') = runSpec t w[ addr ↦ dat ] in t' , t▸t' , ar (ARAR w rs▸rs' t▸t' (rinv , AR-rs-t)) simSR {s , normal rinv} {t} (ar AR-rs-t) (f rs▸rs') = let (t' , t▸t') = runSpec t f in t' , t▸t' , ar (ARAR f rs▸rs' t▸t' (rinv , AR-rs-t)) simSR {s , normal rinv} {t} (ar AR-rs-t) (wᶜ {addr = addr} {dat = dat} rs▸rs') = let (t' , t▸t') = runSpec t wᶜ[ addr ↦ dat ] in t' , t▸t' , cr (ARCR wᶜ rs▸rs' t▸t' (rinv , AR-rs-t)) simSR {s , normal rinv} {t} (ar AR-rs-t) (fᶜ rs▸rs') = let (t' , t▸t') = runSpec t fᶜ in t' , t▸t' , cr (ARCR fᶜ rs▸rs' t▸t' (rinv , AR-rs-t)) simSR {s , crash cinv} {t} (cr CR-rs-t) (rᶜ rs▸rs') = let (t' , t▸t') = runSpec t rᶜ in t' , t▸t' , cr (CRCR rs▸rs' t▸t' (cinv , CR-rs-t)) simSR {s , crash cinv} {t} (cr CR-rs-t) (r rs▸rs') = let (t' , t▸t') = runSpec t r in t' , t▸t' , ar (CRAR rs▸rs' t▸t' (cinv , CR-rs-t)) simSR {s , normal rinv} {t} (ar AR-rs-t) (cp rs▸rs') = let (t' , t▸t') = runSpec t cp in t' , t▸t' , ar (ARAR cp rs▸rs' t▸t' (rinv , AR-rs-t)) simSR {s , normal rinv} {t} (ar AR-rs-t) (er rs▸rs') = let (t' , t▸t') = runSpec t er in t' , t▸t' , ar (ARAR er rs▸rs' t▸t' (rinv , AR-rs-t)) simSR {s , normal rinv} {t} (ar AR-rs-t) (cpᶜ rs▸rs') = let (t' , t▸t') = runSpec t cpᶜ in t' , t▸t' , cr (ARCR cpᶜ rs▸rs' t▸t' (rinv , AR-rs-t)) simSR {s , normal rinv} {t} (ar AR-rs-t) (erᶜ rs▸rs') = let (t' , t▸t') = runSpec t erᶜ in t' , t▸t' , cr (ARCR erᶜ rs▸rs' t▸t' (rinv , AR-rs-t)) runSimSR : SR s t → s ⟦ ef ⟧ᴾ*▸ s' → ∃[ t' ] (t ⟦ ef ⟧*▸ t' × SR s' t') runSimSR SR-s-t ∅ = _ , ∅ , SR-s-t runSimSR SR-s-t (s*▸s'' • s''▸s') = let (t'' , t*▸t'' , SR-s''-t'') = runSimSR SR-s-t s*▸s'' (t' , t''▸t' , SR-s'-t' ) = simSR SR-s''-t'' s''▸s' in _ , (t*▸t'' • t''▸t') , SR-s'-t' Conformant-all : {tr : Trace} {s s' : Stateᴾ} → s ⟦ tr ⟧ᴾ*▸ s' → {t t' : State} → t ⟦ tr ⟧*▸ t' → Set Conformant-all {s' = s'} ∅ {t' = t'} ∅ = ⊤ Conformant-all {s' = s'} (frP • _) {t' = t'} (frS • _) = Conformant-all frP frS × ObsEquiv s' t' Conformant-1R : {tr : Trace} (1r : OneRecovery tr) → {s s' : Stateᴾ} (frP : s ⟦ tr ⟧ᴾ*▸ s') → 1RFrags 1r frP → {t t' : State } (frS : t ⟦ tr ⟧*▸ t') → 1RFrags 1r frS → Set Conformant-1R ._ {s' = s'} ._ (wᶜ frP₁ frP₂ frP₃) {t' = t'} ._ (wᶜ frS₁ frS₂ frS₃) = Conformant-all (frP₁ ++RTC frP₂) (frS₁ ++RTC frS₂) × ObsEquiv s' t' Conformant-1R ._ {s' = s'} ._ (fᶜ frP₁ frP₂ frP₃) {t' = t'} ._ (fᶜ frS₁ frS₂ frS₃) = Conformant-all (frP₁ ++RTC frP₂) (frS₁ ++RTC frS₂) × ObsEquiv s' t' Conformant-1R ._ {s' = s'} ._ (wᶜ-nof frP₂ frP₃) {t' = t'} ._ (wᶜ-nof frS₂ frS₃) = Conformant-all frP₂ frS₂ × ObsEquiv s' t' Conformant-1R ._ {s' = s'} ._ (fᶜ-nof frP₂ frP₃) {t' = t'} ._ (fᶜ-nof frS₂ frS₃) = Conformant-all frP₂ frS₂ × ObsEquiv s' t' Conformant-all-intermediate : {s₁ s₂ s₃ : Stateᴾ} {t₁ t₂ t₃ : State} {tr tr' : Trace} (frP : s₁ ⟦ tr ⟧ᴾ*▸ s₂) (frS : t₁ ⟦ tr ⟧*▸ t₂) (frP' : s₂ ⟦ tr' ⟧ᴾ*▸ s₃) (frS' : t₂ ⟦ tr' ⟧*▸ t₃) → Conformant-all (frP ++RTC frP') (frS ++RTC frS') → ObsEquiv s₁ t₁ → ObsEquiv s₂ t₂ Conformant-all-intermediate ∅ ∅ _ _ conf oe = oe Conformant-all-intermediate (frP • sP) (frS • sS) ∅ ∅ conf oe = proj₂ conf Conformant-all-intermediate (frP • sP) (frS • sS) (frP' • sP') (frS' • sS') conf oe = Conformant-all-intermediate (frP • sP) (frS • sS) frP' frS' (proj₁ conf) oe conf-all++ : {s₁ s₂ s₃ : Stateᴾ} {t₁ t₂ t₃ : State} {tr tr' : Trace} (frP : s₁ ⟦ tr ⟧ᴾ*▸ s₂) (frS : t₁ ⟦ tr ⟧*▸ t₂) (frP' : s₂ ⟦ tr' ⟧ᴾ*▸ s₃) (frS' : t₂ ⟦ tr' ⟧*▸ t₃) → Conformant-all frP frS → Conformant-all frP' frS' → Conformant-all (frP ++RTC frP') (frS ++RTC frS') conf-all++ frP frS ∅ ∅ conf conf' = conf conf-all++ frP frS (frP' • p) (frS' • s) conf (conf' , oe) = conf-all++ frP frS frP' frS' conf conf' , oe Conformant : {tr : Trace} (mr : MultiRecovery tr) {s s' : Stateᴾ} (frP : s ⟦ tr ⟧ᴾ*▸ s') → MRFrags mr frP → {t t' : State } (frS : t ⟦ tr ⟧*▸ t') → MRFrags mr frS → Set Conformant (init _) {s' = s'} _ _ {t' = t'} _ _ = ObsEquiv s' t' Conformant (one mr 1r) .(_ ++RTC frP₂) (one {s₂ = s''} frPs frP₂ frPs₂) .(_ ++RTC frS₂) (one {s₂ = t''} frSs frS₂ frSs₂) = Conformant mr _ frPs _ frSs × ObsEquiv s'' t'' × Conformant-1R 1r frP₂ frPs₂ frS₂ frSs₂ BC-all : {tr : Trace} → All Regular×Snapshot tr → {s s' : Stateᴾ} {t : State} → SR s t → ObsEquiv s t → (frP : s ⟦ tr ⟧ᴾ*▸ s') → Σ[ t' ∈ State ] Σ[ frS ∈ t ⟦ tr ⟧*▸ t' ] SR s' t' × ObsEquiv s' t' × Conformant-all frP frS BC-all [] sr oe-s-t ∅ = _ , ∅ , sr , oe-s-t , tt BC-all (all ∷ _) sr oe-s-t (frP • _) with BC-all all sr oe-s-t frP BC-all (all ∷ _) sr oe-s-t (frP • s''▸s') | t'' , frS'' , sr'' , oe'' , conf'' with simSR sr'' s''▸s' BC-all (all ∷ w) sr oe-s-t (frP • w {rinv' = rinv'} rs''▸s') | t'' , frS'' , sr'' , oe'' , conf'' | t' , t''▸t' , ar ar' = let oe' = AR⇒ObsEquiv (rinv' , ar') in t' , frS'' • t''▸t' , ar ar' , oe' , conf'' , oe' BC-all (all ∷ cp) sr oe-s-t (frP • cp {rinv' = rinv'} rs''▸s') | t'' , frS'' , sr'' , oe'' , conf'' | t' , t''▸t' , ar ar' = let oe' = AR⇒ObsEquiv (rinv' , ar') in t' , frS'' • t''▸t' , ar ar' , oe' , conf'' , oe' BC-all (all ∷ er) sr oe-s-t (frP • er {rinv' = rinv'} rs''▸s') | t'' , frS'' , sr'' , oe'' , conf'' | t' , t''▸t' , ar ar' = let oe' = AR⇒ObsEquiv (rinv' , ar') in t' , frS'' • t''▸t' , ar ar' , oe' , conf'' , oe' BC-all (all ∷ f) sr oe-s-t (frP • f {rinv' = rinv'} rs''▸s') | t'' , frS'' , sr'' , oe'' , conf'' | t' , t''▸t' , ar ar' = let oe' = AR⇒ObsEquiv (rinv' , ar') in t' , frS'' • t''▸t' , ar ar' , oe' , conf'' , oe' BC-1R : {tr : Trace} → (1r : OneRecovery tr) → {s s' : Stateᴾ} {t : State} → SR s t → ObsEquiv s t → (frP : s ⟦ tr ⟧ᴾ*▸ s') (frPs : 1RFrags 1r frP) → Σ[ t' ∈ State ] Σ[ frS ∈ t ⟦ tr ⟧*▸ t' ] Σ[ frSs ∈ 1RFrags 1r frS ] SR s' t' × ObsEquiv s' t' × Conformant-1R 1r frP frPs frS frSs BC-1R 1r sr s=t frP (wᶜ {all₁ = all₁} {all₂ = all₂} fr₁ fr₂ fr₃@(fr₃' • r {rinv' = rinv'} _)) with BC-all all₁ sr s=t fr₁ ... | t₁ , frS₁ , sr-s₁-t₁ , s₁=t₁ , conf₁ with BC-all (([] ∷ f) ++All mapAll r→rs all₂) sr-s₁-t₁ s₁=t₁ fr₂ ... | t₂ , frS₂ , sr-s₂-t₂ , s₂=t₂ , conf₂ with runSimSR sr-s₂-t₂ fr₃ ... | t' , frS' , ar ar-s'-t' = let oe' = AR⇒ObsEquiv (rinv' , ar-s'-t') in t' , frS₁ ++RTC frS₂ ++RTC frS' , wᶜ frS₁ frS₂ frS' , ar ar-s'-t' , oe' , conf-all++ fr₁ frS₁ fr₂ frS₂ conf₁ conf₂ , oe' BC-1R 1r sr s=t frP (fᶜ {all₁ = all₁} {all₂ = all₂} fr₁ fr₂ fr₃@(fr₃' • r {rinv' = rinv'} _)) with BC-all all₁ sr s=t fr₁ ... | t₁ , frS₁ , sr-s₁-t₁ , s₁=t₁ , conf₁ with BC-all (([] ∷ f) ++All mapAll r→rs all₂) sr-s₁-t₁ s₁=t₁ fr₂ ... | t₂ , frS₂ , sr-s₂-t₂ , s₂=t₂ , conf₂ with runSimSR sr-s₂-t₂ fr₃ ... | t' , frS' , ar ar-s'-t' = let oe' = AR⇒ObsEquiv (rinv' , ar-s'-t') in t' , frS₁ ++RTC frS₂ ++RTC frS' , fᶜ frS₁ frS₂ frS' , ar ar-s'-t' , oe' , conf-all++ fr₁ frS₁ fr₂ frS₂ conf₁ conf₂ , oe' BC-1R 1r sr s=t frP (wᶜ-nof {all₂ = all₂} fr₂ fr₃@(fr₃' • r {rinv' = rinv'} _)) with BC-all (mapAll r→rs all₂) sr s=t fr₂ ... | _ , frS₂ , sr-s₂-t₂ , s₂=t₂ , conf₂ with runSimSR sr-s₂-t₂ fr₃ ... | t' , frS' , ar ar-s'-t' = let oe' = AR⇒ObsEquiv (rinv' , ar-s'-t') in t' , frS₂ ++RTC frS' , wᶜ-nof frS₂ frS' , ar ar-s'-t' , oe' , conf₂ , oe' BC-1R 1r sr s=t frP (fᶜ-nof {all₂ = all₂} fr₂ fr₃@(fr₃' • r {rinv' = rinv'} _)) with BC-all (mapAll r→rs all₂) sr s=t fr₂ ... | _ , frS₂ , sr-s₂-t₂ , s₂=t₂ , conf₂ with runSimSR sr-s₂-t₂ fr₃ ... | t' , frS' , ar ar-s'-t' = let oe' = AR⇒ObsEquiv (rinv' , ar-s'-t') in t' , frS₂ ++RTC frS' , fᶜ-nof frS₂ frS' , ar ar-s'-t' , oe' , conf₂ , oe' BC-ind : {tr : Trace} (mr : MultiRecovery tr) {s s' : Stateᴾ} → Initᴾ s → (frP : s ⟦ tr ⟧ᴾ*▸ s') (frPs : MRFrags mr frP) → Σ[ t ∈ State ] Init t × Σ[ t' ∈ State ] SR s' t' × ObsEquiv s' t' × Σ[ frS ∈ t ⟦ tr ⟧*▸ t' ] Σ[ frSs ∈ MRFrags mr frS ] Conformant mr frP frPs frS frSs BC-ind (init all) {s = s₀} (init rs₀) (frP • rP@(r {rinv' = rinv'} rs)) frPs with runSimSR (cr (initᴿ-CR (proj₁ s₀) rs₀ (proj₁ t-init) (proj₂ t-init))) frP ... | t'' , frS , sr' with simSR sr' rP ... | t' , rS , (ar ar-rs'-t') = let eq = AR⇒ObsEquiv (rinv' , ar-rs'-t') in proj₁ t-init , proj₂ t-init , t' , ar ar-rs'-t' , eq , frS • rS , init (frS • rS) , eq BC-ind (one mr x) init-s _ (one {mr = mr₁} {fr₁ = frP₁} frPs₁ {1r = 1r} frP₂ frPs₂) with BC-ind mr init-s _ frPs₁ ... | t , init-t , t'' , sr'' , oe'' , frS₁ , frSs₁ , conf₁ with BC-1R 1r sr'' oe'' frP₂ frPs₂ ... | t' , frS₂ , frSs₂ , sr' , oe' , conf₂ = t , init-t , t' , sr' , oe' , frS₁ ++RTC frS₂ , one frSs₁ frS₂ frSs₂ , conf₁ , oe'' , conf₂ BC-mr : {tr : Trace} (mr : MultiRecovery tr) {s s' : Stateᴾ} → Initᴾ s → (frP : s ⟦ tr ⟧ᴾ*▸ s') → (frPs : MRFrags mr frP) → Σ[ t ∈ State ] Init t × Σ[ t' ∈ State ] Σ[ frS ∈ t ⟦ tr ⟧*▸ t' ] Σ[ frSs ∈ MRFrags mr frS ] Conformant mr frP frPs frS frSs BC-mr mr init-s frP frPs = let (t , init-t , t' , _ , _ , frS , frSs , conf) = BC-ind mr init-s frP frPs in (t , init-t , t' , frS , frSs , conf) BC : {tr : Trace} (mr : MultiRecovery tr) {s s' : Stateᴾ} → Initᴾ s → (frP : s ⟦ tr ⟧ᴾ*▸ s') (frPs : MRFrags mr frP) → {tr' : Trace} {s'' : Stateᴾ} → All Regular×Snapshot tr' → (frP' : s' ⟦ tr' ⟧ᴾ*▸ s'') → Σ[ t ∈ State ] Init t × Σ[ t' ∈ State ] Σ[ frS ∈ t ⟦ tr ⟧*▸ t' ] Σ[ frSs ∈ MRFrags mr frS ] Σ[ t'' ∈ State ] Σ[ frS' ∈ t' ⟦ tr' ⟧*▸ t'' ] Conformant mr frP frPs frS frSs × Conformant-all frP' frS' BC mr init-s frP frPs all frP' = let (t , init-t , t' , sr' , oe' , frS , frSs , conf) = BC-ind mr init-s frP frPs (t'' , frS' , _ , _ , conf') = BC-all all sr' oe' frP' in (t , init-t , t' , frS , frSs , t'' , frS' , conf , conf') SC : {s₀ s s' : Stateᴾ} {tr₀ tr : Trace} → (mr : MultiRecovery tr₀) → (1r : OneRecovery tr) → Initᴾ s₀ → (fr₀ : s₀ ⟦ tr₀ ⟧ᴾ*▸ s) → MRFrags mr fr₀ → (frP : s ⟦ tr ⟧ᴾ*▸ s') → (frPs : 1RFrags 1r frP) → SnapshotConsistency (λ{(rs , _) (rs' , _) → read rs ≐ read rs'}) 1r frP frPs SC mr 1r init-s₀ frP₀ frPs₀ frP frPs with BC-mr (one mr 1r) init-s₀ (frP₀ ++RTC frP) (one frPs₀ frP frPs) SC mr ._ init-s₀ frP₀ frPs₀ ._ (wᶜ frP₁ frP₂ frP₃) | t₀ , init-t₀ , t' , ._ , one frSs ._ (wᶜ {all₁ = all₁} {all₂ = all₂} {all₃ = all₃} frS₁ frS₂ frS₃) , (_ , oe-s-t , conf , oe-s'-t') = Conformant-all-intermediate frP₁ frS₁ frP₂ frS₂ conf oe-s-t <≐> SpecSC-wᶜ ⦃ all₂ ⦄ ⦃ all₃ ⦄ frS₂ frS₃ <≐> sym-≐ oe-s'-t' SC mr ._ init-s₀ frP₀ frPs₀ ._ (fᶜ frP₁ frP₂ frP₃) | t₀ , init-t₀ , t' , ._ , one frSs ._ (fᶜ {all₁ = all₁} {all₂ = all₂} {all₃ = all₃} frS₁ frS₂ frS₃) , (_ , oe-s-t , conf , oe-s'-t') with SpecSC-fᶜ {{all₂}} {{all₃}} frS₂ frS₃ ... | inj₁ req = inj₁ $ Conformant-all-intermediate (frP₁ ++RTC frP₂) (frS₁ ++RTC frS₂) ∅ ∅ conf oe-s-t <≐> req <≐> sym-≐ oe-s'-t' ... | inj₂ req = inj₂ $ Conformant-all-intermediate frP₁ frS₁ frP₂ frS₂ conf oe-s-t <≐> req <≐> sym-≐ oe-s'-t' SC mr ._ init-s₀ frP₀ frPs₀ ._ (wᶜ-nof frP₂ frP₃) | t₀ , init-t₀ , t' , ._ , one {fr₁ = frS₀} frSs ._ (wᶜ-nof {all₂ = all₂} {all₃ = all₃} frS₂ frS₃) , (_ , oe-s-t , conf , oe-s'-t') = oe-s-t <≐> SpecSC-wᶜ-nof ⦃ all₂ ⦄ ⦃ all₃ ⦄ (proj₂ (lastr mr frS₀ frSs)) frS₂ frS₃ <≐> sym-≐ oe-s'-t' SC mr ._ init-s₀ frP₀ frPs₀ ._ (fᶜ-nof frP₂ frP₃) | t₀ , init-t₀ , t' , ._ , one frSs ._ (fᶜ-nof {all₂ = all₂} {all₃ = all₃} frS₂ frS₃) , (_ , oe-s-t , conf , oe-s'-t') with SpecSC-fᶜ-nof {{all₂}} {{all₃}} (proj₂ (lastr mr _ frSs)) frS₂ frS₃ ... | inj₁ req = inj₁ $ Conformant-all-intermediate frP₂ frS₂ ∅ ∅ conf oe-s-t <≐> req <≐> sym-≐ oe-s'-t' ... | inj₂ req = inj₂ $ oe-s-t <≐> req <≐> sym-≐ oe-s'-t'
theory PMLanguage imports Language begin inductive_set dep_traces :: "'a rel \<Rightarrow> 'a lan" for D where dt_Nil [simp]: "[] \<in> dep_traces D" | dt_no_dep: "b \<notin> Field D \<Longrightarrow> as @ cs \<in> dep_traces D \<Longrightarrow> as @ [b] @ cs \<in> dep_traces D" | dt_dep: "b \<in> fst ` D \<Longrightarrow> c \<in> snd ` D \<Longrightarrow> as @ ds \<in> dep_traces D \<Longrightarrow> as @ [b] @ [c] @ ds \<in> dep_traces D" definition shuffle_dep :: "'a lan \<Rightarrow> 'a rel \<Rightarrow> 'a lan \<Rightarrow> 'a lan" where "shuffle_dep X D Y = (X \<parallel> Y) \<inter> dep_traces D" notation (input) shuffle_dep ("_ \<parallel>\<^sub>_ _" [74,0,75] 75) lemma dep_traces_empty: "xs \<in> dep_traces {}" by (induct xs) (auto intro: dt_no_dep[where as = "[]", simplified]) lemma "D = {} \<Longrightarrow> (X \<parallel>\<^sub>D Y) \<parallel>\<^sub>D Z = X \<parallel>\<^sub>D (Y \<parallel>\<^sub>D Z)" by (simp add: shuffle_dep_def shuffle_assoc) definition shf :: "('c list \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'c) \<Rightarrow> ('b \<Rightarrow> 'c) \<Rightarrow> 'a list \<Rightarrow> 'b list \<Rightarrow> ('a + 'b) lan" where "shf P f g xs ys = {zs. \<ll> zs = xs \<and> \<rr> zs = ys \<and> P (map \<langle>f,g\<rangle> zs)}" lemma [simp]: "\<langle>f,g\<rangle> \<circ> Inr = g" by (simp add: o_def) lemma [simp]: "shf P f g [] ys = (if P (map g ys) then {map Inr ys} else {})" apply (auto simp add: shf_def) apply (metis no_lefts) sorry lemma shf_emptyl [simp]: "shf P f g xs [] = (if P (map f xs) then {map Inl xs} else {})" sorry lemma tshuffle_words_map: fixes f :: "'a \<Rightarrow> 'b" and g :: "'c \<Rightarrow> 'd" and h :: "'b \<Rightarrow> 'e" and k :: "'d \<Rightarrow> 'e" shows "shf P h k (map f xs) (map g ys) = map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` shf P (h \<circ> f) (k \<circ> g) xs ys" nitpick proof show "shf P h k (map f xs) (map g ys) \<subseteq> map \<langle>Inl \<circ> f,Inr \<circ> g\<rangle> ` shf P (h \<circ> f) (k \<circ> g) xs ys" proof (induct xs arbitrary: ys) fix ys case Nil show ?case by (simp add: o_def) next fix ys :: "'c list" case (Cons x xs) note ih_xs = this have "shf P h k (map f (x # xs)) (map g ys) = shf P h k (f x # map f xs) (map g ys)" by simp also have "... \<subseteq> map \<langle>Inl \<circ> f,Inr \<circ> g\<rangle> ` shf P (h \<circ> f) (k \<circ> g) (x # xs) ys" proof (induct ys) case Nil show ?case by (simp add: o_def) next case (Cons y ys) have "shf P h k (f x # map f xs) (map g (y # ys)) = shf P h k (f x # map f xs) (g y # map g ys)" by simp lemma tshuffle_words_map: shows "map f xs \<sha>\<^sub>D map g ys = map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` (xs \<sha>\<^sub>D ys)" proof show "map f xs \<sha>\<^sub>D map g ys \<subseteq> map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` (xs \<sha>\<^sub>D ys)" proof (induct xs arbitrary: ys, simp_all) fix x xs and ys :: "'c list" assume ih_xs: "\<And>ys::'c list. (map f xs) \<sha>\<^sub>D (map g ys) \<subseteq> map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` (xs \<sha>\<^sub>D ys)" show "(f x # map f xs) \<sha> (map g ys) \<subseteq> map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` ((x # xs) \<sha> ys)" proof (induct ys, simp) fix y and ys :: "'c list" assume ih_ys: "(f x # map f xs) \<sha> (map g ys) \<subseteq> map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` ((x # xs) \<sha> ys)" have "op # (Inl (f x)) ` (map f xs \<sha> map g (y # ys)) \<subseteq> map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` ((x # xs) \<sha> (y # ys))" proof - have "op # (Inl (f x)) ` (map f xs \<sha> map g (y # ys)) \<subseteq> op # (Inl (f x)) ` map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` (xs \<sha> (y # ys))" by (rule image_mono, rule ih_xs) also have "... \<subseteq> map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` op # (Inl x) ` (xs \<sha> (y # ys))" by (auto simp add: image_def) also have "... \<subseteq> map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` ((x # xs) \<sha> (y # ys))" by (metis (hide_lams, no_types) image_mono le_sup_iff tshuffle_ind eq_refl) finally show ?thesis . qed moreover have "op # (Inr (g y)) ` ((f x # map f xs) \<sha> (map g ys)) \<subseteq> map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` ((x # xs) \<sha> (y # ys))" proof - have "op # (Inr (g y)) ` ((f x # map f xs) \<sha> (map g ys)) \<subseteq> op # (Inr (g y)) ` map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` ((x # xs) \<sha> ys)" by (rule image_mono, rule ih_ys) also have "... \<subseteq> map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` op # (Inr y) ` ((x # xs) \<sha> ys)" by (auto simp add: image_def) also have "... \<subseteq> map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` ((x # xs) \<sha> (y # ys))" by (metis (hide_lams, no_types) image_mono le_sup_iff tshuffle_ind eq_refl) finally show ?thesis . qed ultimately show "((f x # map f xs) \<sha> (map g (y # ys))) \<subseteq> map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` ((x # xs) \<sha> (y # ys))" by (simp, subst tshuffle_ind, auto) qed qed show "map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> ` (xs \<sha> ys) \<subseteq> map f xs \<sha> map g ys" proof (auto simp add: tshuffle_words_def) fix x :: "('a, 'c) sum list" show "\<ll> (map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> x) = map f (\<ll> x)" by (induct x rule: sum_list_induct, auto) show "\<rr> (map \<langle>Inl \<circ> f, Inr \<circ> g\<rangle> x) = map g (\<rr> x)" by (induct x rule: sum_list_induct, auto) qed qed lemma shuffle_dep: "(X \<parallel>\<^sub>D Y) = \<Union>{map \<langle>id,id\<rangle> ` (x \<sha> y) \<inter> dep_traces D|x y. x \<in> X \<and> y \<in> Y}" apply simp by (auto simp: shuffle_dep_def shuffle_def Int_Union2) lemma "(X \<parallel>\<^sub>D Y) = \<Union>{map \<langle>id,id\<rangle> ` (x \<sha> y) \<inter> dep_traces D|x y. x \<in> X \<and> y \<in> Y}" lemma "(X \<parallel>\<^sub>D Y) \<parallel>\<^sub>D Z = X \<parallel>\<^sub>D (Y \<parallel>\<^sub>D Z)" by (simp add: shuffle_dep_def shuffle_assoc) class comm_monoid_zero = comm_monoid_mult + zero + assumes mult_zero: "0 * x = 0" lemma shuffle_sm: "X\<^sup>\<ddagger> \<parallel> Y \<subseteq> (X \<parallel> Y)\<^sup>\<ddagger>" proof - have "X\<^sup>\<ddagger> \<parallel> Y = \<Union>sm_set ` X \<parallel> Y" by (simp add: sm_closure_def) also have "... = \<Union>{sm_set xs \<parallel> Y|xs. xs \<in> X}" by (subst shuffle_inf_distr) (auto simp add: image_def) also have "... = \<Union>{\<Union>{map \<langle>id,id\<rangle> ` (xs' \<sha> ys) |xs' ys. xs' \<in> sm_set xs \<and> ys \<in> Y}|xs. xs \<in> X}" by (simp add: shuffle_def) also have "... = \<Union>{\<Union>{map \<langle>id,id\<rangle> ` (xs' \<sha> ys) |xs'. xs' \<in> sm_set xs}|xs ys. xs \<in> X \<and> ys \<in> Y}" by blast also have "... \<subseteq> \<Union>{(map \<langle>id,id\<rangle> ` (xs \<sha> ys))\<^sup>\<ddagger>|xs ys. xs \<in> X \<and> ys \<in> Y}" by (insert tshuffle_sm) blast also have "... = \<Union>{\<Union>zs\<in>xs \<sha> ys. sm_set (map \<langle>id,id\<rangle> zs)|xs ys. xs \<in> X \<and> ys \<in> Y}" by (simp add: sm_closure_def) also have "... = (X \<parallel> Y)\<^sup>\<ddagger>" by (auto simp add: shuffle_def sm_closure_def) finally show ?thesis . qed
# Calculate near surface RH% using ERA-interim fields * 2-m dew point * 2-m temperature * surface pressure Once the yearly RH files are made, merge these data into a single file and put into the era merged time directory, then, regrid that file and place in the common grid file, such that this newly created variable has the same handling as variables processed by Python/format_raw_era_data.py NOTE: RH was calculated from raw, native (0.75 x 0.75 deg grid) era-interim nc data. These data live in a different project directory (metSpreadData). Link to documentations and instructions on how to calculate near surface relative humidity using ecmwf era-interim: https://www.ecmwf.int/en/faq/do-era-datasets-contain-parameters-near-surface-humidity \begin{align} RH=100\frac{es(T_{d})}{es(T)} \end{align} ### Saturation Specific Humidity Saturation specific humidity is expressed as a function of saturation water vapor pressure as: \begin{align} q_{sat} & = \frac{e_{sat}(T)\frac{R_{dry}}{R_{vapor}}}{p-(1-\frac{R_{dry}}{R_{vapor}})e_{sat}(T)} \end{align} where the saturation water vopor pressure ($e_{sat}$) is expressed with the Teten's formula: \begin{align} e_{sat}(T) & = a_{1}exp(a_{3}\frac{T - T_{0}}{T-a_{4}})\\ \\ a_{1} & = 611.21Pa \\ a_{3} & = 17.502 \\ a_{4} & = 32.19 \\ T_{0} & = 273.16 \end{align} ```python import numpy as np def calculat_svp(T, P): """Calculates and returns saturation vapor pressure (svp)""" # constants for saturation over water a1 = 611.21 # Pa a3 = 17.502 a4 = 32.19 # K To = 273.16 # K R_dry = 287. # J/kg/K gas constant of dry air R_vap = 461. # J/kg/K gas constant for water vapor e_sat = a1 * np.exp( a3 * (T-To)/(T-a4) ) # Saturation specific humidity (eqn 7.4) top = e_sat * R_dry / R_vap bottom = P - (1. - R_dry / R_vap) * e_sat q_sat = top / bottom return q_sat ``` ### Create 3D RH arrays ```python from netCDF4 import Dataset import os from matplotlib import pylab as plt dataDir = os.path.join("..","..","metSpreadData","ERA-Interim") def get_nc(var, year): """ Loads an era-interim netcdf file. Very simple. """ loadFile = os.path.join(dataDir, var + "_" + str(year) + ".nc") nc = Dataset(loadFile) vals = nc.variables[var][:] t = nc.variables["time"][:] lon = nc.variables["longitude"][:] lat = nc.variables["latitude"][:] nc.close() return vals, t, lon, lat def write_RH_nc(RH, t, x, y, year, dataDir): """ Writes a relative humidity netcdf file. """ outputFile = os.path.join(dataDir, "RH_" + str(year) + ".nc") ncFile = Dataset(outputFile, 'w', format='NETCDF4') ncFile.description = 'Relative Humidity (saturation pressure relative to water, Tetons eq.)' ncFile.location = 'Global' ncFile.createDimension('time', len(t) ) ncFile.createDimension('latitude', len(y) ) ncFile.createDimension('longitude', len(x) ) VAR_ = ncFile.createVariable("RH", 'f4',('time', 'latitude','longitude')) VAR_.long_name = "Relative Humidity" VAR_.units = "%" # Create time variable time_ = ncFile.createVariable('time', 'i4', ('time',)) time_.units = "hours since 1900-01-01 00:00:0.0" time_.calendar = "gregorian" # create lat variable latitude_ = ncFile.createVariable('latitude', 'f4', ('latitude',)) latitude_.units = 'degrees_north' # create longitude variable longitude_ = ncFile.createVariable('longitude', 'f4', ('longitude',)) longitude_.units = 'degrees_east' # Write the actual data to these dimensions VAR_[:] = RH time_[:] = t latitude_[:] = y longitude_[:] = x ncFile.close() ``` Generate the RH yearly files! ```python years = range(1983, 2017+1) for year in years : print("Making RH file for %i " % year) # Get the grids needed to calculate specific humidity t2m,t,x,y = get_nc("t2m", year) # 2 meter temperature d2m,t,x,y = get_nc("d2m", year) # 2 meter dew point sp,t,x,y = get_nc("sp", year) # Surface pressure RH = calculat_svp(d2m, sp) / calculat_svp(t2m, sp) * 100. write_RH_nc(RH, t, x, y, year, dataDir) ``` Making RH file for 1983 Making RH file for 1984 Making RH file for 1985 Making RH file for 1986 Making RH file for 1987 Making RH file for 1988 Making RH file for 1989 Making RH file for 1990 Making RH file for 1991 Making RH file for 1992 Making RH file for 1993 Making RH file for 1994 Making RH file for 1995 Making RH file for 1996 Making RH file for 1997 Making RH file for 1998 Making RH file for 1999 Making RH file for 2000 Making RH file for 2001 Making RH file for 2002 Making RH file for 2003 Making RH file for 2004 Making RH file for 2005 Making RH file for 2006 Making RH file for 2007 Making RH file for 2008 Making RH file for 2009 Making RH file for 2010 Making RH file for 2011 Making RH file for 2012 Making RH file for 2013 Making RH file for 2014 Making RH file for 2015 Making RH file for 2016 Making RH file for 2017 Show the last month for the last year output as an example of what these values and output look like. Make sure the dry places in the world have lower RH values. ```python plt.figure(dpi=150) plt.pcolor(x,y,RH[0,:,:]) plt.title("Example of RH% output for January 2017") plt.colorbar(extend="both", label="RH%") plt.xlabel("Longitude") plt.ylabel("Latitude") plt.show() ``` Merge yearly files and regrid - TODO: the code below is not working in a notebook, something strange with the call to Cdo() - These commands were issued at the command line using cdo on 11/24/2018. import globfrom cdo import * # python version cdo = Cdo()common_grid_txt = os.path.join(dataDir, 'COMMON_GRID.txt') files_to_merge = glob.glob(os.path.join(dataDir, "RH_*")) merged_time_file = os.path.join(dataDir, 'merged_time', 'RH_1983-2017.nc') common_grid_out = os.path.join(dataDir, 'merged_t_COMMON_GRID', 'RH_1983-2017.nc')cdo.mergetime(input=" ".join(files_to_merge), output=merged_time_file, options="-b F64")cdo.remapbil(common_grid_txt, input=merged_time_file, output=common_grid_out, options="-b F64")
Formal statement is: lemma BseqI': "(\<And>n. norm (X n) \<le> K) \<Longrightarrow> Bseq X" Informal statement is: If $X_n$ is a sequence of real numbers such that $|X_n| \leq K$ for all $n$, then $X_n$ is a bounded sequence.
proposition path_connected_convex_diff_countable: fixes U :: "'a::euclidean_space set" assumes "convex U" "\<not> collinear U" "countable S" shows "path_connected(U - S)"
Set Implicit Arguments. Require Import Arith_Max_extra. Require Import LNameless_Meta. Require Import LNameless_Meta_Env. Require Import LNameless_Isomorphism. Require Import LNameless_Fsub_Iso. Require Import LN_Template_Two_Sort. (* ************************************************************ *) (** ** Fsub Part 1A and 2A *) (** Reference: Chargueraud's POPL solution using Locally Nameless style and cofinite quantification *) (****************************************************************************) (****************************************************************************) (** Here begins a concrete formalization of System Fsub for part 1A and 2A. *) (****************************************************************************) (****************************************************************************) (** [typ] and [trm] are already defined in LNameless_Fsub_Iso.v << Notation var := atom. Inductive typ : Set := | typ_bvar : nat -> typ | typ_fvar : var -> typ | typ_top : typ | typ_arrow : typ -> typ -> typ | typ_all : typ -> typ -> typ. Inductive trm : Set := | trm_bvar : nat -> trm | trm_fvar : var -> trm | trm_app : trm -> trm -> trm | trm_abs : typ -> trm -> trm | trm_tapp : trm -> typ -> trm | trm_tabs : typ -> trm -> trm. >> *) (** Many of the generic properties about substitution, environments are already proved in a generic *) (** M_tt, M_yt, M_yy, and M_ty are already defined in LN_Template_Two_Sort.v *) (** For cases where generic and non-generic concepts are mixed, it is sometimes better to work with original definitions. - Induction on well-formed terms is a typical case. - Although we have to give a double definition and prove its equivalence to the generic one, it still saves a lot about the generic properties. - It is still possible to work with the generic definitions only, but some proofs would demand size induction instead of structural inductions. *) (** Original definition of well-formed types. *) Inductive type : typ -> Prop := | type_top : type typ_top | type_var : forall X, type (typ_fvar X) | type_arrow : forall T1 T2, type T1 -> type T2 -> type (typ_arrow T1 T2) | type_all : forall L T1 T2, type T1 -> (forall X, X `notin` L -> type (M_yy.M.Tbsubst T2 0 (typ_fvar X))) -> type (typ_all T1 T2). Hint Constructors type. Hint Resolve type_top type_var type_var type_all. Inductive term : trm -> Prop := | term_var : forall x, term (trm_fvar x) | term_abs : forall L V e1, M_yy.M.TwfT V -> (forall x, x `notin` L -> term (M_tt.M.Tbsubst e1 0 (trm_fvar x))) -> term (trm_abs V e1) | term_app : forall e1 e2, term e1 -> term e2 -> term (trm_app e1 e2) | term_tabs : forall L V e1, M_yy.M.TwfT V -> (forall X, X `notin` L -> term (M_yt.M.Tbsubst e1 0 (typ_fvar X))) -> term (trm_tabs V e1) | term_tapp : forall e1 V, term e1 -> M_yy.M.TwfT V -> term (trm_tapp e1 V). Hint Constructors term. Inductive wft : env typ -> env typ -> typ -> Prop := | wft_top : forall E F, wft E F typ_top | wft_var : forall U E F X, binds X U E -> wft E F (typ_fvar X) | wft_arrow : forall E F T1 T2, wft E F T1 -> wft E F T2 -> wft E F (typ_arrow T1 T2) | wft_all : forall E F T1 T2 L V, wft E F T1 -> (forall X, X `notin` L -> wft (X ~ V ++ E) F (M_yy.M.Tbsubst T2 0 (typ_fvar X))) -> wft E F (typ_all T1 T2). Hint Constructors wft. (** The concept of "Binding" in Chargueraud's original code needs some adaptation - Instead of using mixed environments, we use two kinds of environments. - An environment is a pair of two disjoint environments. - One for subtyping variables - The other for term variables - We distinguish them by giving different names. - This is possible because there is no interaction between type variables and term variables. *) (** Subtyping relation *) Inductive sub : env typ -> env typ -> typ -> typ -> Prop := | sub_top : forall E F S, M_yy.Ywf_env E -> M_yy.YTenvT E F S -> sub E F S typ_top | sub_refl_tvar : forall E F X, M_yy.Ywf_env E -> M_yy.YTenvT E F (typ_fvar X) -> sub E F (typ_fvar X) (typ_fvar X) | sub_trans_tvar : forall U E F T X, binds X U E -> sub E F U T -> sub E F (typ_fvar X) T | sub_arrow : forall E F S1 S2 T1 T2, sub E F T1 S1 -> sub E F S2 T2 -> sub E F (typ_arrow S1 S2) (typ_arrow T1 T2) | sub_all : forall L E F S1 S2 T1 T2, sub E F T1 S1 -> (forall X, X `notin` L -> sub (X ~ T1 ++ E) F (M_yy.M.Tbsubst S2 0 (typ_fvar X)) (M_yy.M.Tbsubst T2 0 (typ_fvar X))) -> sub E F (typ_all S1 S2) (typ_all T1 T2). (** Typing relation *) Inductive typing : env typ -> env typ -> trm -> typ -> Prop := | typing_var : forall E F x T, YTwf_env E F -> binds x T F -> typing E F (trm_fvar x) T | typing_abs : forall L E F V e1 T1, (forall x, x `notin` L -> typing E (x ~ V ++ F) (M_tt.M.Tbsubst e1 0 (trm_fvar x)) T1) -> typing E F (trm_abs V e1) (typ_arrow V T1) | typing_app : forall T1 E F e1 e2 T2, typing E F e1 (typ_arrow T1 T2) -> typing E F e2 T1 -> typing E F (trm_app e1 e2) T2 | typing_tabs : forall L E F V e1 T1, (forall X, X `notin` L -> typing (X ~ V ++ E) F (M_yt.M.Tbsubst e1 0 (typ_fvar X)) (M_yy.M.Tbsubst T1 0 (typ_fvar X))) -> typing E F (trm_tabs V e1) (typ_all V T1) | typing_tapp : forall T1 E F e1 T T2, typing E F e1 (typ_all T1 T2) -> sub E F T T1 -> typing E F (trm_tapp e1 T) (M_yy.M.Tbsubst T2 0 T) | typing_sub : forall S E F e T, typing E F e S -> sub E F S T -> typing E F e T. (** Values *) Inductive value : trm -> Prop := | value_abs : forall V e1, TTwfT (trm_abs V e1) -> value (trm_abs V e1) | value_tabs : forall V e1, TTwfT (trm_tabs V e1) -> value (trm_tabs V e1). (** One-step reduction *) Inductive red : trm -> trm -> Prop := | red_app_1 : forall e1 e1' e2, TTwfT e2 -> red e1 e1' -> red (trm_app e1 e2) (trm_app e1' e2) | red_app_2 : forall e1 e2 e2', value e1 -> red e2 e2' -> red (trm_app e1 e2) (trm_app e1 e2') | red_tapp : forall e1 e1' V, M_yy.M.TwfT V -> red e1 e1' -> red (trm_tapp e1 V) (trm_tapp e1' V) | red_abs : forall V e1 v2, TTwfT (trm_abs V e1) -> value v2 -> red (trm_app (trm_abs V e1) v2) (M_tt.M.Tbsubst e1 0 v2) | red_tabs : forall V1 e1 V2, TTwfT (trm_tabs V1 e1) -> M_yy.M.TwfT V2 -> red (trm_tapp (trm_tabs V1 e1) V2) (M_yt.M.Tbsubst e1 0 V2). (** Our goal is to prove preservation and progress *) Definition preservation := forall E F e e' T, typing E F e T -> red e e' -> typing E F e' T. Definition progress := forall e T, typing empty_env empty_env e T -> value e \/ exists e', red e e'.
[STATEMENT] lemma cos_plus_pi: "cos ((z :: 'a :: {real_normed_field,banach}) + of_real pi) = - cos z" [PROOF STATE] proof (prove) goal (1 subgoal): 1. cos (z + of_real pi) = - cos z [PROOF STEP] by (simp add: cos_add)
theory Planar_Subgraph imports Graph_Genus Permutations_2 "HOL-Library.FuncSet" "HOL-Library.Simps_Case_Conv" begin section \<open>Combinatorial Planarity and Subgraphs\<close> lemma out_arcs_emptyD_dominates: assumes "out_arcs G x = {}" shows "\<not>x \<rightarrow>\<^bsub>G\<^esub> y" using assms by (auto simp: out_arcs_def) lemma (in wf_digraph) reachable_refl_iff: "u \<rightarrow>\<^sup>* u \<longleftrightarrow> u \<in> verts G" by (auto simp: reachable_in_verts) context digraph_map begin lemma face_cycle_set_succ[simp]: "face_cycle_set (face_cycle_succ a) = face_cycle_set a" by (metis face_cycle_eq face_cycle_set_self face_cycle_succ_inD) lemma face_cycle_succ_funpow_in[simp]: "(face_cycle_succ ^^ n) a \<in> arcs G \<longleftrightarrow> a \<in> arcs G" by (induct n) auto lemma segment_face_cycle_x_x_eq: "segment face_cycle_succ x x = face_cycle_set x - {x}" unfolding face_cycle_set_def using face_cycle_succ_permutes finite_arcs permutation_permutes by (intro segment_x_x_eq) blast lemma fcs_x_eq_x: "face_cycle_succ x = x \<longleftrightarrow> face_cycle_set x = {x}" (is "?L \<longleftrightarrow> ?R") unfolding face_cycle_set_def orbit_eq_singleton_iff .. end lemma (in bidirected_digraph) bidirected_digraph_del_arc: "bidirected_digraph (pre_digraph.del_arc (pre_digraph.del_arc G (arev a)) a) (perm_restrict arev (arcs G - {a , arev a}))" proof unfold_locales fix b assume A: "b \<in> arcs (pre_digraph.del_arc (del_arc (arev a)) a)" have "arev b \<noteq> b \<Longrightarrow> b \<noteq> arev a \<Longrightarrow> b \<noteq> a \<Longrightarrow> perm_restrict arev (arcs G - {a, arev a}) (arev b) = b" using bij_arev arev_dom by (subst perm_restrict_simps) (auto simp: bij_iff) then show "perm_restrict arev (arcs G - {a, arev a}) (perm_restrict arev (arcs G - {a, arev a}) b) = b" using A by (auto simp: pre_digraph.del_arc_simps perm_restrict_simps arev_dom) qed (auto simp: pre_digraph.del_arc_simps perm_restrict_simps arev_dom) lemma (in bidirected_digraph) bidirected_digraph_del_vert: "bidirected_digraph (del_vert u) (perm_restrict arev (arcs (del_vert u)))" by unfold_locales (auto simp: del_vert_simps perm_restrict_simps arev_dom) lemma (in pre_digraph) dominates_arcsD: assumes "v \<rightarrow>\<^bsub>del_arc u\<^esub> w" shows "v \<rightarrow>\<^bsub>G\<^esub> w" using assms by (auto simp: arcs_ends_def ends_del_arc) lemma (in wf_digraph) reachable_del_arcD: assumes "v \<rightarrow>\<^sup>*\<^bsub>del_arc u\<^esub> w" shows "v \<rightarrow>\<^sup>*\<^bsub>G\<^esub> w" proof - interpret H: wf_digraph "del_arc u" by (rule wf_digraph_del_arc) from assms show ?thesis by (induct) (auto dest: dominates_arcsD intro: adj_reachable_trans) qed lemma (in fin_digraph) finite_isolated_verts[intro!]: "finite isolated_verts" by (auto simp: isolated_verts_def) lemma (in wf_digraph) isolated_verts_in_sccs: assumes "u \<in> isolated_verts" shows "{u} \<in> sccs_verts" proof - have "v = u" if "u \<rightarrow>\<^sup>*\<^bsub>G\<^esub> v" for v using that assms by induct (auto simp: arcs_ends_def arc_to_ends_def isolated_verts_def) with assms show ?thesis by (auto simp: sccs_verts_def isolated_verts_def) qed lemma (in digraph_map) in_face_cycle_sets: "a \<in> arcs G \<Longrightarrow> face_cycle_set a \<in> face_cycle_sets" by (auto simp: face_cycle_sets_def) lemma (in digraph_map) heads_face_cycle_set: assumes "a \<in> arcs G" shows "head G ` face_cycle_set a = tail G ` face_cycle_set a" (is "?L = ?R") proof (intro set_eqI iffI) fix u assume "u \<in> ?L" then obtain b where "b \<in> face_cycle_set a" "head G b = u" by blast then have "face_cycle_succ b \<in> face_cycle_set a" "tail G (face_cycle_succ b) = u" using assms by (auto simp: tail_face_cycle_succ face_cycle_succ_inI in_face_cycle_setD) then show "u \<in> ?R" by auto next fix u assume "u \<in> ?R" then obtain b where "b \<in> face_cycle_set a" "tail G b = u" by blast moreover then obtain c where "b = face_cycle_succ c" by (metis face_cycle_succ_pred) ultimately have "c \<in> face_cycle_set a" "head G c = u" by (auto dest: face_cycle_succ_inD) (metis assms face_cycle_succ_no_arc in_face_cycle_setD tail_face_cycle_succ) then show "u \<in> ?L" by auto qed lemma (in pre_digraph) casI_nth: assumes "p \<noteq> []" "u = tail G (hd p)" "v = head G (last p)" "\<And>i. Suc i < length p \<Longrightarrow> head G (p ! i) = tail G (p ! Suc i)" shows "cas u p v" using assms proof (induct p arbitrary: u) case Nil then show ?case by simp next case (Cons a p) have "cas (head G a) p v" proof (cases "p = []") case False then show ?thesis using Cons.prems(1-3) Cons.prems(4)[of 0] Cons.prems(4)[of "Suc i" for i] by (intro Cons) (simp_all add: hd_conv_nth) qed (simp add: Cons) with Cons show ?case by simp qed lemma (in digraph_map) obtain_trail_in_fcs: assumes "a \<in> arcs G" "a0 \<in> face_cycle_set a" "an \<in> face_cycle_set a" obtains p where "trail (tail G a0) p (head G an)" "p \<noteq> []" "hd p = a0" "last p = an" "set p \<subseteq> face_cycle_set a" proof - have fcs_a: "face_cycle_set a = orbit face_cycle_succ a0" using assms face_cycle_eq by (simp add: face_cycle_set_def) have "a0 = (face_cycle_succ ^^ 0) a0" by simp have "an = (face_cycle_succ ^^ funpow_dist face_cycle_succ a0 an) a0" using assms by (simp add: fcs_a funpow_dist_prop) define p where "p = map (\<lambda>n. (face_cycle_succ ^^ n) a0) [0..<Suc (funpow_dist face_cycle_succ a0 an)]" have p_nth: "\<And>i. i < length p \<Longrightarrow> p ! i = (face_cycle_succ ^^ i) a0" by (auto simp: p_def simp del: upt_Suc) have P2: "p \<noteq> []" by (simp add: p_def) have P3: "hd p = a0" using \<open>a0 = _\<close> by (auto simp: p_def hd_map simp del: upt_Suc) have P4: "last p = an" using \<open>an = _\<close> by (simp add: p_def) have P5: "set p \<subseteq> face_cycle_set a" unfolding p_def fcs_a orbit_altdef_permutation[OF permutation_face_cycle_succ] by auto have P1: "trail (tail G a0) p (head G an)" proof - have "distinct p" proof - have "an \<in> orbit face_cycle_succ a0" using assms by (simp add: fcs_a) then have "inj_on (\<lambda>n. (face_cycle_succ ^^ n) a0) {0..funpow_dist face_cycle_succ a0 an}" by (rule inj_on_funpow_dist) also have "{0..funpow_dist face_cycle_succ a0 an} = (set [0..<Suc (funpow_dist face_cycle_succ a0 an)])" by auto finally have "inj_on (\<lambda>n. (face_cycle_succ ^^ n) a0) (set [0..<Suc (funpow_dist face_cycle_succ a0 an)])" . then show "distinct p" by (simp add: distinct_map p_def) qed moreover have "a0 \<in> arcs G" by (metis assms(1-2) in_face_cycle_setD) then have "tail G a0 \<in> verts G" by simp moreover have "set p \<subseteq> arcs G" using P5 by (metis assms(1) in_face_cycle_setD subset_code(1)) moreover then have "\<And>i. Suc i < length p \<Longrightarrow> p ! Suc i \<in> arcs G" by auto then have "\<And>i. Suc i < length p \<Longrightarrow> head G (p ! i) = tail G (p ! Suc i)" by (auto simp: p_nth tail_face_cycle_succ) ultimately show ?thesis using P2 P3 P4 unfolding trail_def awalk_def by (auto intro: casI_nth) qed from P1 P2 P3 P4 P5 show ?thesis .. qed lemma (in digraph_map) obtain_trail_in_fcs': assumes "a \<in> arcs G" "u \<in> tail G ` face_cycle_set a" "v \<in> tail G ` face_cycle_set a" obtains p where "trail u p v" "set p \<subseteq> face_cycle_set a" proof - from assms obtain a0 where "tail G a0 = u" "a0 \<in> face_cycle_set a" by auto moreover from assms obtain an where "head G an = v" "an \<in> face_cycle_set a" by (auto simp: heads_face_cycle_set[symmetric]) ultimately obtain p where "trail u p v" "set p \<subseteq> face_cycle_set a" using \<open>a \<in> arcs G\<close> by (metis obtain_trail_in_fcs) then show ?thesis .. qed subsection \<open>Deleting an isolated vertex\<close> locale del_vert_props = digraph_map + fixes u assumes u_in: "u \<in> verts G" assumes u_isolated: "out_arcs G u = {}" begin lemma u_isolated_in: "in_arcs G u = {}" using u_isolated by (simp add: in_arcs_eq) lemma arcs_dv: "arcs (del_vert u) = arcs G" using u_isolated u_isolated_in by (auto simp: del_vert_simps) lemma out_arcs_dv: "out_arcs (del_vert u) = out_arcs G" by (auto simp: fun_eq_iff arcs_dv tail_del_vert) lemma digraph_map_del_vert: shows "digraph_map (del_vert u) M" proof - have "perm_restrict (edge_rev M) (arcs (del_vert u)) = edge_rev M" using has_dom_arev arcs_dv by (auto simp: perm_restrict_dom_subset) then interpret H: bidirected_digraph "del_vert u" "edge_rev M" using bidirected_digraph_del_vert[of u] by simp show ?thesis by unfold_locales (auto simp: arcs_dv edge_succ_permutes out_arcs_dv edge_succ_cyclic verts_del_vert) qed end sublocale del_vert_props \<subseteq> H: digraph_map "del_vert u" M by (rule digraph_map_del_vert) context del_vert_props begin lemma card_verts_dv: "card (verts G) = Suc (card (verts (del_vert u)))" by (auto simp: verts_del_vert) (rule card.remove, auto simp: u_in) lemma card_arcs_dv: "card (arcs (del_vert u)) = card (arcs G)" using u_isolated by (auto simp add: arcs_dv in_arcs_eq) lemma isolated_verts_dv: "H.isolated_verts = isolated_verts - {u}" by (auto simp: isolated_verts_def H.isolated_verts_def verts_del_vert out_arcs_dv) lemma u_in_isolated_verts: "u \<in> isolated_verts" using u_in u_isolated by (auto simp: isolated_verts_def) lemma card_isolated_verts_dv: "card isolated_verts = Suc (card H.isolated_verts)" by (simp add: isolated_verts_dv) (rule card.remove, auto simp: u_in_isolated_verts) lemma face_cycles_dv: "H.face_cycle_sets = face_cycle_sets" unfolding H.face_cycle_sets_def face_cycle_sets_def arcs_dv .. lemma euler_char_dv: "euler_char = 1 + H.euler_char" by (auto simp: euler_char_def H.euler_char_def card_arcs_dv card_verts_dv face_cycles_dv) lemma adj_dv: "v \<rightarrow>\<^bsub>del_vert u\<^esub> w \<longleftrightarrow> v \<rightarrow>\<^bsub>G\<^esub> w" by (auto simp: arcs_ends_def arcs_dv ends_del_vert) lemma reachable_del_vertD: assumes "v \<rightarrow>\<^sup>*\<^bsub>del_vert u\<^esub> w" shows "v \<rightarrow>\<^sup>*\<^bsub>G\<^esub> w" using assms by induct (auto simp: verts_del_vert adj_dv intro: adj_reachable_trans) lemma reachable_del_vertI: assumes "v \<rightarrow>\<^sup>*\<^bsub>G\<^esub> w" "u \<noteq> v \<or> u \<noteq> w" shows "v \<rightarrow>\<^sup>*\<^bsub>del_vert u\<^esub> w" using assms proof induct case (step x y) from \<open>x \<rightarrow>\<^bsub>G\<^esub> y\<close> obtain a where "a \<in> arcs G" "head G a = y" by auto then have "a \<in> in_arcs G y" by auto then have "y \<noteq> u" using u_isolated in_arcs_eq[of u] by auto with step show ?case by (auto simp: adj_dv intro: H.adj_reachable_trans) qed (auto simp: verts_del_vert) lemma G_reach_conv: "v \<rightarrow>\<^sup>*\<^bsub>G\<^esub> w \<longleftrightarrow> v \<rightarrow>\<^sup>*\<^bsub>del_vert u\<^esub> w \<or> (v = u \<and> w = u)" by (auto dest: reachable_del_vertI reachable_del_vertD intro: u_in) lemma sccs_verts_dv: "H.sccs_verts = sccs_verts - {{u}}" (is "?L = ?R") proof - have *:"\<And>S x. S \<in> sccs_verts \<Longrightarrow> S \<notin> H.sccs_verts \<Longrightarrow> x \<in> S \<Longrightarrow> x = u" by (simp add: H.in_sccs_verts_conv_reachable in_sccs_verts_conv_reachable G_reach_conv) (meson H.reachable_trans) show ?thesis by (auto dest: *) (auto simp: H.in_sccs_verts_conv_reachable in_sccs_verts_conv_reachable G_reach_conv H.reachable_refl_iff verts_del_vert) qed lemma card_sccs_verts_dv: "card sccs_verts = Suc (card H.sccs_verts)" unfolding sccs_verts_dv by (rule card.remove) (auto simp: isolated_verts_in_sccs u_in_isolated_verts finite_sccs_verts) lemma card_sccs_dv: "card sccs = Suc (card H.sccs)" using card_sccs_verts_dv by (simp add: card_sccs_verts H.card_sccs_verts) lemma euler_genus_eq: "H.euler_genus = euler_genus" by (auto simp: pre_digraph_map.euler_genus_def card_sccs_dv card_isolated_verts_dv euler_char_dv) end subsection \<open>Deleting an arc pair\<close> locale bidel_arc = G: digraph_map + fixes a assumes a_in: "a \<in> arcs G" begin abbreviation "a' \<equiv> edge_rev M a" definition H :: "('a,'b) pre_digraph" where "H \<equiv> pre_digraph.del_arc (pre_digraph.del_arc G a') a" definition HM :: "'b pre_map" where "HM = \<lparr> edge_rev = perm_restrict (edge_rev M) (arcs G - {a, a'}) , edge_succ = perm_rem a (perm_rem a' (edge_succ M)) \<rparr>" lemma verts_H: "verts H = verts G" and arcs_H: "arcs H = arcs G - {a, a'}" and tail_H: "tail H = tail G" and head_H: "head H = head G" and ends_H: "arc_to_ends H = arc_to_ends G"and arcs_in: "{a,a'} \<subseteq> arcs G" and ends_in: "{tail G a, head G a} \<subseteq> verts G" by (auto simp: H_def pre_digraph.del_arc_simps a_in arc_to_ends_def) lemma cyclic_on_edge_succ: assumes "x \<in> verts H" "out_arcs H x \<noteq> {}" shows "cyclic_on (edge_succ HM) (out_arcs H x)" proof - have oa_H: "out_arcs H x = (out_arcs G x - {a'}) - {a}" by (auto simp: arcs_H tail_H) have "cyclic_on (perm_rem a (perm_rem a' (edge_succ M))) (out_arcs G x - {a'} - {a})" using assms by (intro cyclic_on_perm_rem G.edge_succ_cyclic) (auto simp: oa_H G.bij_edge_succ G.edge_succ_cyclic) then show ?thesis by (simp add: HM_def oa_H) qed lemma digraph_map: "digraph_map H HM" proof - interpret fin_digraph H unfolding H_def by (rule fin_digraph.fin_digraph_del_arc) (rule G.fin_digraph_del_arc) interpret bidirected_digraph H "edge_rev HM" unfolding H_def using G.bidirected_digraph_del_arc[of a] by (auto simp: HM_def) have *: "insert a' (insert a (arcs H)) = arcs G" using a_in by (auto simp: arcs_H) have "edge_succ HM permutes arcs H" unfolding HM_def by (auto simp: * intro!: perm_rem_permutes G.edge_succ_permutes) moreover { fix v assume "v \<in> verts H" "out_arcs H v \<noteq> {}" then have "cyclic_on (edge_succ HM) (out_arcs H v)" by (rule cyclic_on_edge_succ) } ultimately show ?thesis by unfold_locales qed lemma rev_H: "bidel_arc.H G M a' = H" (is ?t1) and rev_HM: "bidel_arc.HM G M a' = HM" (is ?t2) proof - interpret rev: bidel_arc G M a' using a_in by unfold_locales simp show ?t1 by (rule pre_digraph.equality) (auto simp: rev.verts_H verts_H rev.arcs_H arcs_H rev.tail_H tail_H rev.head_H head_H) show ?t2 using G.edge_succ_permutes by (intro pre_map.equality) (auto simp: HM_def rev.HM_def insert_commute perm_rem_commutes permutes_conv_has_dom) qed end sublocale bidel_arc \<subseteq> H: digraph_map H HM by (rule digraph_map) context bidel_arc begin lemma a_neq_a': "a \<noteq> a'" by (metis G.arev_neq a_in) lemma arcs_G: "arcs G = insert a (insert a' (arcs H))" and arcs_not_in: "{a,a'} \<inter> arcs H = {}" using arcs_in by (auto simp: arcs_H) lemma card_arcs_da: "card (arcs G) = 2 + card (arcs H)" using arcs_G arcs_not_in a_neq_a' by (auto simp: card_insert_if) lemma cas_da: "H.cas = G.cas" proof - { fix u p v have "H.cas u p v = G.cas u p v" by (induct p arbitrary: u) (simp_all add: tail_H head_H) } then show ?thesis by (simp add: fun_eq_iff) qed lemma reachable_daD: assumes "v \<rightarrow>\<^sup>*\<^bsub>H\<^esub> w" shows "v \<rightarrow>\<^sup>*\<^bsub>G\<^esub> w" apply (rule G.reachable_del_arcD) apply (rule wf_digraph.reachable_del_arcD) apply (rule G.wf_digraph_del_arc) using assms unfolding H_def by assumption lemma not_G_isolated_a: "{tail G a, head G a} \<inter> G.isolated_verts = {}" using a_in G.in_arcs_eq[of "head G a"] by (auto simp: G.isolated_verts_def) lemma isolated_other_da: assumes "u \<notin> {tail G a, head G a}" shows "u \<in> H.isolated_verts \<longleftrightarrow> u \<in> G.isolated_verts" using assms by (auto simp: pre_digraph.isolated_verts_def verts_H arcs_H tail_H out_arcs_def) lemma isolated_da_pre: "H.isolated_verts = G.isolated_verts \<union> (if tail G a \<in> H.isolated_verts then {tail G a} else {}) \<union> (if head G a \<in> H.isolated_verts then {head G a} else {})" (is "?L = ?R") proof (intro set_eqI iffI) fix x assume "x \<in> ?L" then show "x \<in> ?R" by (cases "x \<in> {tail G a, head G a}") (auto simp:isolated_other_da) next fix x assume "x \<in> ?R" then show "x \<in> ?L" using not_G_isolated_a by (cases "x \<in> {tail G a, head G a}") (auto simp:isolated_other_da split: if_splits) qed lemma card_isolated_verts_da0: "card H.isolated_verts = card G.isolated_verts + card ({tail G a, head G a} \<inter> H.isolated_verts)" using not_G_isolated_a by (subst isolated_da_pre) (auto simp: card_insert_if G.finite_isolated_verts) lemma segments_neq: assumes "segment G.face_cycle_succ a' a \<noteq> {} \<or> segment G.face_cycle_succ a a' \<noteq> {}" shows "segment G.face_cycle_succ a a' \<noteq> segment G.face_cycle_succ a' a" proof - have bij_fcs: "bij G.face_cycle_succ" using G.face_cycle_succ_permutes by (auto simp: permutes_conv_has_dom) show ?thesis using segment_disj[OF a_neq_a' bij_fcs] assms by auto qed lemma H_fcs_eq_G_fcs: assumes "b \<in> arcs G" "{b,G.face_cycle_succ b} \<inter> {a,a'} = {}" shows "H.face_cycle_succ b = G.face_cycle_succ b" proof - have "edge_rev M b \<notin> {a,a'}" using assms by auto (metis G.arev_arev) then show ?thesis using assms unfolding G.face_cycle_succ_def H.face_cycle_succ_def by (auto simp: HM_def perm_restrict_simps perm_rem_simps G.bij_edge_succ) qed lemma face_cycle_set_other_da: assumes "{a, a'} \<inter> G.face_cycle_set b = {}" "b \<in> arcs G" shows "H.face_cycle_set b = G.face_cycle_set b" proof - have "\<And>s. s \<in> G.face_cycle_set b \<Longrightarrow> b \<in> arcs G \<Longrightarrow> a \<notin> G.face_cycle_set b \<Longrightarrow> a' \<notin> G.face_cycle_set b \<Longrightarrow> pre_digraph_map.face_cycle_succ HM s = G.face_cycle_succ s" by (subst H_fcs_eq_G_fcs) (auto simp: G.in_face_cycle_setD G.face_cycle_succ_inI) then show ?thesis using assms unfolding pre_digraph_map.face_cycle_set_def by (intro orbit_cong) (auto simp add: pre_digraph_map.face_cycle_set_def[symmetric]) qed lemma in_face_cycle_set_other: assumes "S \<in> G.face_cycle_sets" "{a, a'} \<inter> S = {}" shows "S \<in> H.face_cycle_sets" proof - from assms obtain b where "S = G.face_cycle_set b" "b \<in> arcs G" by (auto simp: G.face_cycle_sets_def) with assms have "S = H.face_cycle_set b" by (simp add: face_cycle_set_other_da) moreover with assms have "b \<in> arcs H" using \<open>b \<in> arcs G\<close> by (auto simp: arcs_H) ultimately show ?thesis by (auto simp: H.face_cycle_sets_def) qed lemma H_fcs_in_G_fcs: assumes "b \<in> arcs H - (G.face_cycle_set a \<union> G.face_cycle_set a')" shows "H.face_cycle_set b \<in> G.face_cycle_sets - {G.face_cycle_set a, G.face_cycle_set a'}" proof - have "H.face_cycle_set b = G.face_cycle_set b" using assms by (intro face_cycle_set_other_da) (auto simp: arcs_H G.face_cycle_eq) moreover have "G.face_cycle_set b \<notin> {G.face_cycle_set a, G.face_cycle_set a'}" "b \<in> arcs G" using G.face_cycle_eq assms by (auto simp: arcs_H) ultimately show ?thesis by (auto simp: G.face_cycle_sets_def) qed lemma face_cycle_sets_da0: "H.face_cycle_sets = G.face_cycle_sets - {G.face_cycle_set a, G.face_cycle_set a'} \<union> H.face_cycle_set ` ((G.face_cycle_set a \<union> G.face_cycle_set a') - {a,a'})" (is "?L = ?R") proof (intro set_eqI iffI) fix S assume "S \<in> ?L" then obtain b where "S = H.face_cycle_set b" "b \<in> arcs H" by (auto simp: H.face_cycle_sets_def) then show "S \<in> ?R" using arcs_not_in H_fcs_in_G_fcs by (cases "b \<in> G.face_cycle_set a \<union> G.face_cycle_set a'") auto next fix S assume "S \<in> ?R" show "S \<in> ?L" proof (cases "S \<in> G.face_cycle_sets - {G.face_cycle_set a, G.face_cycle_set a'}") case True then have "S \<inter> {a,a'} = {}" using G.face_cycle_set_parts by (auto simp: G.face_cycle_sets_def) with True show ?thesis by (intro in_face_cycle_set_other) auto next case False then have "S \<in> H.face_cycle_set ` ((G.face_cycle_set a \<union> G.face_cycle_set a') - {a,a'})" using \<open>S \<in> ?R\<close> by blast moreover have "(G.face_cycle_set a \<union> G.face_cycle_set a') - {a,a'} \<subseteq> arcs H" using a_in by (auto simp: arcs_H dest: G.in_face_cycle_setD) ultimately show ?thesis by (auto simp: H.face_cycle_sets_def) qed qed lemma card_fcs_aa'_le: "card {G.face_cycle_set a, G.face_cycle_set a'} \<le> card G.face_cycle_sets" using a_in by (intro card_mono) (auto simp: G.face_cycle_sets_def) lemma card_face_cycle_sets_da0: "card H.face_cycle_sets = card G.face_cycle_sets - card {G.face_cycle_set a, G.face_cycle_set a'} + card (H.face_cycle_set ` ((G.face_cycle_set a \<union> G.face_cycle_set a') - {a,a'}))" proof - have face_cycle_sets_inter: "(G.face_cycle_sets - {G.face_cycle_set a, G.face_cycle_set a'}) \<inter> H.face_cycle_set ` ((G.face_cycle_set a \<union> G.face_cycle_set a') - {a, a'}) = {}" (is "?L \<inter> ?R = _") proof - define L R P where "L = ?L" and "R = ?R" and "P x \<longleftrightarrow> x \<inter> (G.face_cycle_set a \<union> G.face_cycle_set a') = {}" for x then have "\<And>x. x \<in> L \<Longrightarrow> P x" "\<And>x. x \<in> R \<Longrightarrow> \<not>P x" using G.face_cycle_set_parts by (auto simp: G.face_cycle_sets_def) then have "L \<inter> R = {}" by blast then show ?thesis unfolding L_def R_def . qed then show ?thesis using arcs_G by (simp add: card_Diff_subset[symmetric] card_Un_disjoint[symmetric] G.in_face_cycle_sets face_cycle_sets_da0) qed end locale bidel_arc_same_face = bidel_arc + assumes same_face: "G.face_cycle_set a' = G.face_cycle_set a" begin lemma a_in_o: "a \<in> orbit G.face_cycle_succ a'" unfolding G.face_cycle_set_def[symmetric] by (simp add: same_face) lemma segment_a'_a_in: "segment G.face_cycle_succ a' a \<subseteq> arcs H" (is "?seg \<subseteq> _") proof - have "?seg \<subseteq> G.face_cycle_set a'" by (auto simp: G.face_cycle_set_def segmentD_orbit) moreover have "G.face_cycle_set a' \<subseteq> arcs G" by (auto simp: G.face_cycle_set_altdef a_in) ultimately show ?thesis using a_in_o by (auto simp: arcs_H a_in not_in_segment1 not_in_segment2) qed lemma segment_a'_a_neD: assumes "segment G.face_cycle_succ a' a \<noteq> {}" shows "segment G.face_cycle_succ a' a \<in> H.face_cycle_sets" (is "?seg \<in> _") proof - let ?b = "G.face_cycle_succ a'" have fcs_a_neq_a': "G.face_cycle_succ a' \<noteq> a" by (metis assms segment1_empty) have in_aG: "\<And>x. x \<in> segment G.face_cycle_succ a' a \<Longrightarrow> x \<in> arcs G - {a,a'}" using not_in_segment1 not_in_segment2 segment_a'_a_in by (auto simp: arcs_H) { fix x assume A: "x \<in> segment G.face_cycle_succ a' a" and B: "G.face_cycle_succ x \<noteq> a" from A have "G.face_cycle_succ x \<noteq> a'" proof induct case base then show ?case by (metis a_neq_a' G.face_cycle_set_self not_in_segment1 G.face_cycle_set_def same_face segment.intros) next case step then show ?case by (metis a_in_o a_neq_a' not_in_segment1 segment.step) qed with A B have "{x, G.face_cycle_succ x} \<inter> {a, a'} = {}" using not_in_segment1[OF a_in_o] not_in_segment2[of a G.face_cycle_succ a'] by safe with in_aG have "H.face_cycle_succ x = G.face_cycle_succ x" by (intro H_fcs_eq_G_fcs) (auto intro: A) } note fcs_x_eq = this { fix x assume A: "x \<in> segment G.face_cycle_succ a' a" and B: "G.face_cycle_succ x = a" have "G.face_cycle_succ a \<noteq> a" using B in_aG[OF A] G.bij_face_cycle_succ by (auto simp: bij_eq_iff) then have "edge_succ M a \<noteq> edge_rev M a" by (metis a_in_o G.arev_arev comp_apply G.face_cycle_succ_def not_in_segment1 segment.base) then have "H.face_cycle_succ x = G.face_cycle_succ a'" using in_aG[OF A] B G.bij_edge_succ unfolding H.face_cycle_succ_def G.face_cycle_succ_def by (auto simp: HM_def perm_restrict_simps perm_rem_conv G.arev_eq_iff) } note fcs_last_x_eq = this have "segment G.face_cycle_succ a' a = H.face_cycle_set ?b" proof (intro set_eqI iffI) fix x assume "x \<in> segment G.face_cycle_succ a' a" then show "x \<in> H.face_cycle_set ?b" proof induct case base then show ?case by auto next case (step x) then show ?case by (subst fcs_x_eq[symmetric]) (auto simp: H.face_cycle_succ_inI) qed next fix x assume A: "x \<in> H.face_cycle_set ?b" then show "x \<in> segment G.face_cycle_succ a' a" proof induct case base then show ?case by (intro segment.base fcs_a_neq_a') next case (step x) then show ?case using fcs_a_neq_a' by (cases "G.face_cycle_succ x = a") (auto simp: fcs_last_x_eq fcs_x_eq intro: segment.intros) qed qed then show ?thesis using segment_a'_a_in by (auto simp: H.face_cycle_sets_def) qed lemma segment_a_a'_neD: assumes "segment G.face_cycle_succ a a' \<noteq> {}" shows "segment G.face_cycle_succ a a' \<in> H.face_cycle_sets" proof - interpret rev: bidel_arc_same_face G M a' using a_in same_face by unfold_locales simp_all from assms show ?thesis using rev.segment_a'_a_neD by (simp add: rev_H rev_HM) qed lemma H_fcs_full: assumes "SS \<subseteq> H.face_cycle_sets" shows "H.face_cycle_set ` (\<Union>SS) = SS" proof - { fix x assume "x \<in> \<Union>SS" then obtain S where "S \<in> SS" "x \<in> S" "S \<in> H.face_cycle_sets" using assms by auto then have "H.face_cycle_set x = S" using H.face_cycle_set_parts by (auto simp: H.face_cycle_sets_def) then have "H.face_cycle_set x \<in> SS" using \<open>S \<in> SS\<close> by auto } moreover { fix S assume "S \<in> SS" then obtain x where "x \<in> arcs H" "S = H.face_cycle_set x" "x \<in> S" using assms by (auto simp: H.face_cycle_sets_def) then have "S \<in> H.face_cycle_set ` \<Union>SS" using \<open>S \<in> SS\<close> by auto } ultimately show ?thesis by auto qed lemma card_fcs_gt_0: "0 < card G.face_cycle_sets" using a_in by (auto simp: card_gt_0_iff dest: G.in_face_cycle_sets) lemma card_face_cycle_sets_da': "card H.face_cycle_sets = card G.face_cycle_sets - 1 + card ({segment G.face_cycle_succ a a', segment G.face_cycle_succ a' a, {}} - {{}})" proof - have "G.face_cycle_set a = {a,a'} \<union> segment G.face_cycle_succ a a' \<union> segment G.face_cycle_succ a' a" using a_neq_a' same_face by (intro cyclic_split_segment) (auto simp: G.face_cycle_succ_cyclic) then have *: "G.face_cycle_set a \<union> G.face_cycle_set a' - {a, a'} = segment G.face_cycle_succ a a' \<union> segment G.face_cycle_succ a' a" by (auto simp: same_face G.face_cycle_set_def[symmetric] not_in_segment1 not_in_segment2) have **: "H.face_cycle_set ` (G.face_cycle_set a \<union> G.face_cycle_set a' - {a, a'}) = (if segment G.face_cycle_succ a a' \<noteq> {} then {segment G.face_cycle_succ a a'} else {}) \<union> (if segment G.face_cycle_succ a' a \<noteq> {} then {segment G.face_cycle_succ a' a} else {})" unfolding * using H_fcs_full[of "{segment G.face_cycle_succ a a', segment G.face_cycle_succ a' a}"] using H_fcs_full[of "{segment G.face_cycle_succ a a'}"] using H_fcs_full[of "{segment G.face_cycle_succ a' a}"] by (auto simp add: segment_a_a'_neD segment_a'_a_neD) show ?thesis unfolding card_face_cycle_sets_da0 ** by (simp add: same_face card_insert_if) qed end locale bidel_arc_diff_face = bidel_arc + assumes diff_face: "G.face_cycle_set a' \<noteq> G.face_cycle_set a" begin definition S :: "'b set" where "S \<equiv> segment G.face_cycle_succ a a \<union> segment G.face_cycle_succ a' a'" lemma diff_face_not_in: "a \<notin> G.face_cycle_set a'" "a' \<notin> G.face_cycle_set a" using diff_face G.face_cycle_eq by auto lemma H_fcs_eq_for_a: assumes "b \<in> arcs H \<inter> G.face_cycle_set a" shows "H.face_cycle_set b = S" (is "?L = ?R") proof (intro set_eqI iffI) fix c assume "c \<in> ?L" then have "c \<in> arcs H" using assms by (auto dest: H.in_face_cycle_setD) moreover have "c \<in> G.face_cycle_set a \<union> G.face_cycle_set a'" proof (rule ccontr) assume A: "\<not>?thesis" then have "G.face_cycle_set c \<inter> (G.face_cycle_set a \<union> G.face_cycle_set a') = {}" using G.face_cycle_set_parts by (auto simp: arcs_H) also then have "G.face_cycle_set c = H.face_cycle_set c" using \<open>c \<in> arcs H\<close> by (subst face_cycle_set_other_da) (auto simp: arcs_H) also have "\<dots> = H.face_cycle_set b" using \<open>c \<in> ?L\<close> using H.face_cycle_set_parts by auto finally show False using assms by auto qed ultimately show "c \<in> ?R" unfolding S_def arcs_H G.segment_face_cycle_x_x_eq by auto next fix x assume "x \<in> ?R" from assms have "a \<noteq> b" by (auto simp: arcs_H) from assms have b_in: "b \<in> segment G.face_cycle_succ a a" using G.segment_face_cycle_x_x_eq by (auto simp: arcs_H) have fcs_a_neq_a: "G.face_cycle_succ a \<noteq> a" using assms \<open>a \<noteq> b\<close> by (auto simp add: G.segment_face_cycle_x_x_eq G.fcs_x_eq_x) have split_seg: "segment G.face_cycle_succ a a = segment G.face_cycle_succ a b \<union> {b} \<union> segment G.face_cycle_succ b a" using b_in by (intro segment_split) have a_in_orb_a: "a \<in> orbit G.face_cycle_succ a" by (simp add: G.face_cycle_set_def[symmetric]) define c where "c = inv G.face_cycle_succ a" have c_succ: "G.face_cycle_succ c = a" unfolding c_def by (meson bij_inv_eq_iff permutation_bijective G.permutation_face_cycle_succ) have c_in_aa: "c \<in> segment G.face_cycle_succ a a" unfolding G.segment_face_cycle_x_x_eq c_def using fcs_a_neq_a c_succ c_def by force have c_in: "c \<in> {b} \<union> segment G.face_cycle_succ b a" using split_seg b_in c_succ c_in_aa by (auto dest: not_in_segment1[OF segmentD_orbit] intro: segment.intros) from c_in_aa have "c \<in> arcs H" unfolding G.segment_face_cycle_x_x_eq using arcs_in c_succ diff_face by (auto simp: arcs_H G.face_cycle_eq[of a']) have b_in_L: "b \<in> ?L" by auto moreover { fix x assume "x \<in> segment G.face_cycle_succ b a" then have "x \<in> ?L" proof induct case base then show ?case using assms diff_face_not_in(2) by (subst H_fcs_eq_G_fcs[symmetric]) (auto simp: arcs_H intro: H.face_cycle_succ_inI G.face_cycle_succ_inI) next case (step x) have "G.face_cycle_succ x \<notin> G.face_cycle_set a \<Longrightarrow> b \<in> G.face_cycle_set a \<Longrightarrow> False" using step(1) by (metis G.face_cycle_eq G.face_cycle_succ_inI pre_digraph_map.face_cycle_set_def segmentD_orbit) moreover have "x \<in> arcs G" using step assms H.in_face_cycle_setD arcs_H by auto moreover then have "(G.face_cycle_succ x \<notin> G.face_cycle_set a \<Longrightarrow> b \<in> G.face_cycle_set a \<Longrightarrow> False) \<Longrightarrow> {x, G.face_cycle_succ x} \<inter> {a, a'} = {}" using step(2,3) assms diff_face_not_in(2) H.in_face_cycle_setD arcs_H by safe auto ultimately show ?case using step by (subst H_fcs_eq_G_fcs[symmetric]) (auto intro: H.face_cycle_succ_inI) qed } note sba_in_L = this moreover { fix x assume A: "x \<in> segment G.face_cycle_succ a' a'" then have "x \<in> ?L" proof - from c_in have "c \<in> ?L" using b_in_L sba_in_L by blast have "G.face_cycle_succ a' \<noteq> a'" using A by (auto simp add: G.segment_face_cycle_x_x_eq G.fcs_x_eq_x) then have *: "G.face_cycle_succ a' = H.face_cycle_succ c" using a_neq_a' c_succ \<open>c \<in> arcs H\<close> unfolding G.face_cycle_succ_def H.face_cycle_succ_def arcs_H by (auto simp: HM_def perm_restrict_simps perm_rem_conv G.bij_edge_succ G.arev_eq_iff) from A have "x \<in> H.face_cycle_set c" proof induct case base then show ?case by (simp add: * H.face_cycle_succ_inI) next case (step x) have "x \<in> arcs G" using\<open>c \<in> arcs H\<close> step.hyps(2) by (auto simp: arcs_H dest: H.in_face_cycle_setD) moreover have "G.face_cycle_succ x \<noteq> a' \<Longrightarrow> {x, G.face_cycle_succ x} \<inter> {a, a'} = {}" using step(1) diff_face_not_in(1) G.face_cycle_succ_inI G.segment_face_cycle_x_x_eq by (auto simp: not_in_segment2) ultimately show ?case using step by (subst H_fcs_eq_G_fcs[symmetric]) (auto intro: H.face_cycle_succ_inI) qed also have "H.face_cycle_set c = ?L" using \<open>c \<in> ?L\<close> H.face_cycle_set_parts by auto finally show ?thesis . qed } note sa'a'_in_L = this moreover { assume A: "x \<in> segment G.face_cycle_succ a b" obtain d where "d \<in> ?L" and d_succ: "H.face_cycle_succ d = G.face_cycle_succ a" proof (cases "G.face_cycle_succ a' = a'") case True from c_in have "c \<in> ?L" using b_in_L sba_in_L by blast moreover have "H.face_cycle_succ c = G.face_cycle_succ a" using fcs_a_neq_a c_succ a_neq_a' True \<open>c \<in> arcs H\<close> unfolding G.face_cycle_succ_def H.face_cycle_succ_def arcs_H by (auto simp: HM_def perm_restrict_simps arcs_H perm_rem_conv G.bij_edge_succ G.arev_eq_iff) ultimately show ?thesis .. next case False define d where "d = inv G.face_cycle_succ a'" have d_succ: "G.face_cycle_succ d = a'" unfolding d_def by (meson bij_inv_eq_iff permutation_bijective G.permutation_face_cycle_succ) have *: "d \<in> ?L" using sa'a'_in_L False by (metis DiffI d_succ empty_iff G.face_cycle_set_self G.face_cycle_set_succ insert_iff G.permutation_face_cycle_succ pre_digraph_map.face_cycle_set_def segment_x_x_eq) then have "d \<in> arcs H" using assms by (auto dest: H.in_face_cycle_setD) have "H.face_cycle_succ d = G.face_cycle_succ a" using fcs_a_neq_a a_neq_a' \<open>d \<in> arcs H\<close> d_succ unfolding G.face_cycle_succ_def H.face_cycle_succ_def arcs_H by (auto simp: HM_def perm_restrict_simps arcs_H perm_rem_conv G.bij_edge_succ G.arev_eq_iff) with * show ?thesis .. qed then have "d \<in> arcs H" using assms by - (drule H.in_face_cycle_setD, auto) from A have "x \<in> H.face_cycle_set d" proof induct case base then show ?case by (simp add: d_succ[symmetric] H.face_cycle_succ_inI) next case (step x) moreover have "x \<in> arcs G" using \<open>d \<in> arcs H\<close> arcs_H digraph_map.in_face_cycle_setD step.hyps(2) by fastforce moreover have " {x, G.face_cycle_succ x} \<inter> {a, a'} = {}" proof - have "a \<noteq> x" using step(2) H.in_face_cycle_setD \<open>d \<in> arcs H\<close> arcs_not_in by blast moreover have "a \<noteq> G.face_cycle_succ x" by (metis b_in not_in_segment1 segment.step segmentD_orbit step(1)) moreover have "a' \<noteq> x" "a' \<noteq> G.face_cycle_succ x" using step(1) diff_face_not_in(2) by (auto simp: G.face_cycle_set_def dest!: segmentD_orbit intro: orbit.step) ultimately show ?thesis by auto qed ultimately show ?case using step by (subst H_fcs_eq_G_fcs[symmetric]) (auto intro: H.face_cycle_succ_inI) qed also have "H.face_cycle_set d = ?L" using \<open>d \<in> ?L\<close> H.face_cycle_set_parts by auto finally have "x \<in> ?L" . } ultimately show "x \<in> ?L" using \<open>x \<in> ?R\<close> unfolding S_def split_seg by blast qed lemma HJ_fcs_eq_for_a': assumes "b \<in> arcs H \<inter> G.face_cycle_set a'" shows "H.face_cycle_set b = S" proof - interpret rev: bidel_arc_diff_face G M a' using arcs_in diff_face by unfold_locales simp_all show ?thesis using rev.H_fcs_eq_for_a assms by (auto simp: rev_H rev_HM S_def rev.S_def) qed lemma card_face_cycle_sets_da': "card H.face_cycle_sets = card G.face_cycle_sets - card {G.face_cycle_set a, G.face_cycle_set a'} + (if S = {} then 0 else 1)" proof - have "S = G.face_cycle_set a \<union> G.face_cycle_set a' - {a, a'}" unfolding S_def using diff_face_not_in by (auto simp: segment_x_x_eq G.permutation_face_cycle_succ G.face_cycle_set_def) moreover { fix x assume "x \<in> S" then have "x \<in> arcs H \<inter> (G.face_cycle_set a \<union> G.face_cycle_set a' - {a, a'})" unfolding \<open>S = _\<close> arcs_H using a_in by (auto intro: G.in_face_cycle_setD) then have "H.face_cycle_set x = S" using H_fcs_eq_for_a HJ_fcs_eq_for_a' by blast } then have "H.face_cycle_set ` S = (if S = {} then {} else {S})" by auto ultimately show ?thesis by (simp add: card_face_cycle_sets_da0) qed end locale bidel_arc_biconnected = bidel_arc + assumes reach_a: "tail G a \<rightarrow>\<^sup>*\<^bsub>H\<^esub> head G a" begin lemma reach_a': "tail G a' \<rightarrow>\<^sup>*\<^bsub>H\<^esub> head G a'" using reach_a a_in by (simp add: symmetric_reachable H.sym_arcs) lemma tail_a': "tail G a' = head G a" and head_a': "head G a' = tail G a" using a_in by simp_all lemma reachable_daI: assumes "v \<rightarrow>\<^sup>*\<^bsub>G\<^esub> w" shows "v \<rightarrow>\<^sup>*\<^bsub>H\<^esub> w" proof - have *: "\<And>v w. v \<rightarrow>\<^bsub>G\<^esub> w \<Longrightarrow> v \<rightarrow>\<^sup>*\<^bsub>H\<^esub> w" using reach_a reach_a' by (auto simp: arcs_ends_def ends_H arcs_G arc_to_ends_def tail_a') show ?thesis using assms by induct (auto simp: verts_H intro: * H.reachable_trans) qed lemma reachable_da: "v \<rightarrow>\<^sup>*\<^bsub>H\<^esub> w \<longleftrightarrow> v \<rightarrow>\<^sup>*\<^bsub>G\<^esub> w" by (metis reachable_daD reachable_daI) lemma sccs_verts_da: "H.sccs_verts = G.sccs_verts" by (auto simp: G.in_sccs_verts_conv_reachable H.in_sccs_verts_conv_reachable reachable_da) lemma card_sccs_da: "card H.sccs = card G.sccs" by (simp add: G.card_sccs_verts[symmetric] H.card_sccs_verts[symmetric] sccs_verts_da) end locale bidel_arc_not_biconnected = bidel_arc + assumes not_reach_a: "\<not>tail G a \<rightarrow>\<^sup>*\<^bsub>H\<^esub> head G a" begin lemma H_awalkI: "G.awalk u p v \<Longrightarrow> {a,a'} \<inter> set p = {} \<Longrightarrow> H.awalk u p v" by (auto simp: pre_digraph.apath_def pre_digraph.awalk_def verts_H arcs_H cas_da) lemma tail_neq_head: "tail G a \<noteq> head G a" using not_reach_a a_in by (metis H.reachable_refl G.head_in_verts verts_H) lemma scc_of_tail_neq_head: "H.scc_of (tail G a) \<noteq> H.scc_of (head G a)" proof - have "tail G a \<in> H.scc_of (tail G a)" "head G a \<in> H.scc_of (head G a)" using ends_in by (auto simp: H.in_scc_of_self verts_H) with not_reach_a show ?thesis by (auto simp: H.scc_of_def) qed lemma scc_of_G_tail: assumes "u \<in> G.scc_of (tail G a)" shows "H.scc_of u = H.scc_of (tail G a) \<or> H.scc_of u = H.scc_of (head G a)" proof - from assms have "u \<rightarrow>\<^sup>*\<^bsub>G\<^esub> tail G a" by (auto simp: G.scc_of_def) then obtain p where p: "G.apath u p (tail G a)" by (auto simp: G.reachable_apath) show ?thesis proof (cases "head G a \<in> set (G.awalk_verts u p)") case True with p obtain p' q where "p = p' @ q" "G.awalk (head G a) q (tail G a)" and p': "G.awalk u p' (head G a)" unfolding G.apath_def by (metis G.awalk_decomp) moreover then have "tail G a \<in> set (tl (G.awalk_verts (head G a) q))" using tail_neq_head apply (cases q) apply (simp add: G.awalk_Nil_iff ) apply (simp add: G.awalk_Cons_iff) by (metis G.awalkE G.awalk_verts_non_Nil last_in_set) ultimately have "tail G a \<notin> set (G.awalk_verts u p')" using G.apath_decomp_disjoint[OF p, of p' q "tail G a"] by auto with p' have "{a,a'} \<inter> set p' = {}" by (auto simp: G.set_awalk_verts G.apath_def) (metis a_in imageI G.head_arev) with p' show ?thesis unfolding G.apath_def by (metis H.scc_ofI_awalk H.scc_of_eq H_awalkI) next case False with p have "{a,a'} \<inter> set p = {}" by (auto simp: G.set_awalk_verts G.apath_def) (metis a_in imageI G.tail_arev) with p show ?thesis unfolding G.apath_def by (metis H.scc_ofI_awalk H.scc_of_eq H_awalkI) qed qed lemma scc_of_other: assumes "u \<notin> G.scc_of (tail G a)" shows "H.scc_of u = G.scc_of u" using assms proof (intro set_eqI iffI) fix v assume "v \<in> H.scc_of u" then show "v \<in> G.scc_of u" by (auto simp: H.scc_of_def G.scc_of_def intro: reachable_daD) next fix v assume "v \<in> G.scc_of u" then obtain p where p: "G.awalk u p v" by (auto simp: G.scc_of_def G.reachable_awalk) moreover have "{a,a'} \<inter> set p = {}" proof - have "\<not>u \<rightarrow>\<^sup>*\<^bsub>G\<^esub> tail G a" using assms by (metis G.scc_ofI_reachable) then have "\<And>p. \<not>G.awalk u p (tail G a)" by (metis G.reachable_awalk) then have "tail G a \<notin> set (G.awalk_verts u p)" using p by (auto dest: G.awalk_decomp) with p show ?thesis by (auto simp: G.set_awalk_verts G.apath_def) (metis a_in imageI G.head_arev) qed ultimately have "H.awalk u p v" by (rule H_awalkI) then show "v \<in> H.scc_of u" by (metis H.scc_ofI_reachable' H.reachable_awalk) qed lemma scc_of_tail_inter: "tail G a \<in> G.scc_of (tail G a) \<inter> H.scc_of (tail G a)" using ends_in by (auto simp: G.in_scc_of_self H.in_scc_of_self verts_H) lemma scc_of_head_inter: "head G a \<in> G.scc_of (tail G a) \<inter> H.scc_of (head G a)" proof - have "tail G a \<rightarrow>\<^bsub>G\<^esub> head G a" "head G a \<rightarrow>\<^bsub>G\<^esub> tail G a" by (metis a_in G.in_arcs_imp_in_arcs_ends) (metis a_in G.graph_symmetric G.in_arcs_imp_in_arcs_ends) then have "tail G a \<rightarrow>\<^sup>*\<^bsub>G\<^esub> head G a" "head G a \<rightarrow>\<^sup>*\<^bsub>G\<^esub> tail G a" by auto then show ?thesis using ends_in by (auto simp: G.scc_of_def H.in_scc_of_self verts_H) qed lemma H_scc_of_a_not_in: "H.scc_of (tail G a) \<notin> G.sccs_verts" "H.scc_of (head G a) \<notin> G.sccs_verts" proof safe assume "H.scc_of (tail G a) \<in> G.sccs_verts" with scc_of_tail_inter have "G.scc_of (tail G a) = H.scc_of (tail G a)" by (metis G.scc_of_in_sccs_verts G.sccs_verts_disjoint a_in empty_iff G.tail_in_verts) with G_scc_of_tail_not_in show False using ends_in by (auto simp: H.scc_of_in_sccs_verts verts_H) next assume "H.scc_of (head G a) \<in> G.sccs_verts" with scc_of_head_inter have "G.scc_of (tail G a) = H.scc_of (head G a)" by (metis G.scc_of_in_sccs_verts G.sccs_verts_disjoint a_in empty_iff G.tail_in_verts) with G_scc_of_tail_not_in show False using ends_in by (auto simp: H.scc_of_in_sccs_verts verts_H) qed lemma scc_verts_da: "H.sccs_verts = (G.sccs_verts - {G.scc_of (tail G a)}) \<union> {H.scc_of (tail G a), H.scc_of (head G a)}" (is "?L = ?R") proof (intro set_eqI iffI) fix S assume "S \<in> ?L" then obtain u where "u \<in> verts G" "S = H.scc_of u" by (auto simp: verts_H H.sccs_verts_conv_scc_of) moreover then have "G.scc_of (tail G a) \<noteq> H.scc_of u" using \<open>S \<in> ?L\<close> G_scc_of_tail_not_in by auto ultimately show "S \<in> ?R" unfolding G.sccs_verts_conv_scc_of by (cases "u \<in> G.scc_of (tail G a)") (auto dest: scc_of_G_tail scc_of_other) next fix S assume "S \<in> ?R" show "S \<in> ?L" proof (cases "S \<in> G.sccs_verts") case True with \<open>S \<in> ?R\<close> obtain u where u: "u \<in> verts G" "S = G.scc_of u" and "S \<noteq> G.scc_of (tail G a)" using H_scc_of_a_not_in by (auto simp: G.sccs_verts_conv_scc_of) then have "G.scc_of u \<inter> G.scc_of (tail G a) = {}" using ends_in by (intro G.sccs_verts_disjoint) (auto simp: G.scc_of_in_sccs_verts) then have "u \<notin> G.scc_of (tail G a)" using u by (auto dest: G.in_scc_of_self) with u show ?thesis using scc_of_other by (auto simp: H.sccs_verts_conv_scc_of verts_H G.sccs_verts_conv_scc_of) next case False with \<open>S \<in> ?R\<close> ends_in show ?thesis by (auto simp: H.sccs_verts_conv_scc_of verts_H) qed qed lemma card_sccs_da: "card H.sccs = Suc (card G.sccs)" using H_scc_of_a_not_in ends_in unfolding G.card_sccs_verts[symmetric] H.card_sccs_verts[symmetric] scc_verts_da by (simp add: card_insert_if G.finite_sccs_verts scc_of_tail_neq_head card_Suc_Diff1 G.scc_of_in_sccs_verts del: card_Diff_insert) end sublocale bidel_arc_not_biconnected \<subseteq> bidel_arc_same_face proof note a_in moreover from a_in have "head G a \<in> tail G ` G.face_cycle_set a" by (simp add: G.heads_face_cycle_set[symmetric]) moreover have "tail G a \<in> tail G ` G.face_cycle_set a" by simp ultimately obtain p where p: "G.trail (head G a) p (tail G a)" "set p \<subseteq> G.face_cycle_set a" by (rule G.obtain_trail_in_fcs') define p' where "p' = G.awalk_to_apath p" from p have p': "G.apath (head G a) p' (tail G a)" "set p' \<subseteq> G.face_cycle_set a" by (auto simp: G.trail_def p'_def dest: G.apath_awalk_to_apath G.awalk_to_apath_subset) then have "set p' \<subseteq> arcs G" using a_in by (blast dest: G.in_face_cycle_setD) have "\<not>set p' \<subseteq> arcs H" proof assume "set p' \<subseteq> arcs H" then have "H.awalk (head G a) p' (tail G a)" using p' by (auto simp: G.apath_def arcs_H intro: H_awalkI) then show False using not_reach_a by (metis H.symmetric_reachable' H.reachable_awalk) qed then have "set p' \<inter> {a,a'} \<noteq> {}" using \<open>set p' \<subseteq> arcs G\<close> by (auto simp: arcs_H) moreover have "a \<notin> set p'" proof assume "a \<in> set p'" then have "head G a \<in> set (tl (G.awalk_verts (head G a) p'))" using \<open>G.apath _ p' _\<close> by (cases p') (auto simp: G.set_awalk_verts G.apath_def G.awalk_Cons_iff, metis imageI) moreover have "head G a \<notin> set (tl (G.awalk_verts (head G a) p'))" using \<open>G.apath _ p' _\<close> by (cases p') (auto simp: G.apath_def) ultimately show False by contradiction qed ultimately have "a' \<in> G.face_cycle_set a" using p'(2) by auto then show "G.face_cycle_set a' = G.face_cycle_set a" using G.face_cycle_set_parts by auto qed locale bidel_arc_tail_conn = bidel_arc + assumes conn_tail: "tail G a \<notin> H.isolated_verts" locale bidel_arc_head_conn = bidel_arc + assumes conn_head: "head G a \<notin> H.isolated_verts" locale bidel_arc_tail_isolated = bidel_arc + assumes isolated_tail: "tail G a \<in> H.isolated_verts" locale bidel_arc_head_isolated = bidel_arc + assumes isolated_head: "head G a \<in> H.isolated_verts" begin lemma G_edge_succ_a'_no_loop: assumes no_loop_a: "head G a \<noteq> tail G a" shows G_edge_succ_a': "edge_succ M a' = a'" (is ?t2) proof - have *: "out_arcs G (tail G a') = {a'}" using a_in isolated_head no_loop_a by (auto simp: H.isolated_verts_def verts_H out_arcs_def arcs_H tail_H) obtain "edge_succ M a' \<in> {a'}" using G.edge_succ_cyclic[of "tail G a'"] apply (rule eq_on_cyclic_on_iff1[where x="a'"]) using * a_in a_neq_a' no_loop_a by simp_all then show ?thesis by auto qed lemma G_face_cycle_succ_a_no_loop: assumes no_loop_a: "head G a \<noteq> tail G a" shows "G.face_cycle_succ a = a'" using assms by (auto simp: G.face_cycle_succ_def G_edge_succ_a'_no_loop) end locale bidel_arc_same_face_tail_conn = bidel_arc_same_face + bidel_arc_tail_conn begin definition a_neigh :: 'b where "a_neigh \<equiv> SOME b. G.face_cycle_succ b = a" lemma face_cycle_succ_a_neigh: "G.face_cycle_succ a_neigh = a" proof - have "\<exists>b. G.face_cycle_succ b = a" by (metis G.face_cycle_succ_pred) then show ?thesis unfolding a_neigh_def by (rule someI_ex) qed lemma a_neigh_in: "a_neigh \<in> arcs G" using a_in by (metis face_cycle_succ_a_neigh G.face_cycle_succ_closed) lemma a_neigh_neq_a: "a_neigh \<noteq> a" proof assume "a_neigh = a" then have "G.face_cycle_set a = {a}" using face_cycle_succ_a_neigh by (simp add: G.fcs_x_eq_x) with a_neq_a' same_face G.face_cycle_set_self[of a'] show False by simp qed lemma a_neigh_neq_a': "a_neigh \<noteq> a'" proof assume A: "a_neigh = a'" have a_in_oa: "a \<in> out_arcs G (tail G a)" using a_in by auto have cyc: "cyclic_on (edge_succ M) (out_arcs G (tail G a))" using a_in by (intro G.edge_succ_cyclic) auto from A have "G.face_cycle_succ a' = a" by (metis face_cycle_succ_a_neigh) then have "edge_succ M a = a " by (auto simp: G.face_cycle_succ_def) then have "card (out_arcs G (tail G a)) = 1" using cyc a_in by (auto elim: eq_on_cyclic_on_iff1) then have "out_arcs G (tail G a) = {a}" using a_in_oa by (auto simp del: in_out_arcs_conv dest: card_eq_SucD) then show False using conn_tail a_in by (auto simp: H.isolated_verts_def arcs_H tail_H verts_H out_arcs_def) qed lemma edge_rev_a_neigh_neq: "edge_rev M a_neigh \<noteq> a'" by (metis a_neigh_neq_a G.arev_arev) lemma edge_succ_a_neq: "edge_succ M a \<noteq> a'" proof assume "edge_succ M a = a'" then have "G.face_cycle_set a' = {a'}" using face_cycle_succ_a_neigh by (auto simp: G.face_cycle_set_altdef id_funpow_id G.face_cycle_succ_def) with a_neq_a' same_face G.face_cycle_set_self[of a] show False by auto qed lemma H_face_cycle_succ_a_neigh: "H.face_cycle_succ a_neigh = G.face_cycle_succ a'" using face_cycle_succ_a_neigh edge_succ_a_neq edge_rev_a_neigh_neq a_neigh_neq_a a_neigh_neq_a' a_neigh_in unfolding H.face_cycle_succ_def G.face_cycle_succ_def by (auto simp: HM_def perm_restrict_simps perm_rem_conv G.bij_edge_succ) lemma H_fcs_a_neigh: "H.face_cycle_set a_neigh = segment G.face_cycle_succ a' a" (is "?L = ?R") proof - { fix n assume A: "0 < n" "n < funpow_dist1 G.face_cycle_succ a' a" then have *: "(G.face_cycle_succ ^^ n) a' \<in> segment G.face_cycle_succ a' a" using a_in_o by (auto simp: segment_altdef) then have "(G.face_cycle_succ ^^ n) a' \<notin> {a,a'}" "(G.face_cycle_succ ^^ n) a' \<in> arcs G" using not_in_segment1[OF a_in_o] not_in_segment2[of a G.face_cycle_succ a'] by (auto simp: segment_altdef a_in_o) } note X = this { fix n assume "0 < n" "n < funpow_dist1 G.face_cycle_succ a' a" then have "(H.face_cycle_succ ^^ n) a_neigh = (G.face_cycle_succ ^^ n) a'" proof (induct n) case 0 then show ?case by simp next case (Suc n) show ?case proof (cases "n=0") case True then show ?thesis by (simp add: H_face_cycle_succ_a_neigh) next case False then have "(H.face_cycle_succ ^^ n) a_neigh = (G.face_cycle_succ ^^ n) a'" using Suc by simp then show ?thesis using X[of "Suc n"] X[of n] False Suc by (simp add: H_fcs_eq_G_fcs) qed qed } note Y = this have fcs_a'_neq_a: "G.face_cycle_succ a' \<noteq> a" by (metis (no_types) a_neigh_neq_a' G.face_cycle_pred_succ face_cycle_succ_a_neigh) show ?thesis proof (intro set_eqI iffI) fix b assume "b \<in> ?L" define m where "m = funpow_dist1 G.face_cycle_succ a' a - 1" have b_in0: "b \<in> orbit H.face_cycle_succ (a_neigh)" using \<open>b \<in> ?L\<close> by (simp add: H.face_cycle_set_def[symmetric]) have "0 < m" by (auto simp: m_def) (metis a_neigh_neq_a' G.face_cycle_pred_succ G.face_cycle_set_def G.face_cycle_set_self G.face_cycle_set_succ face_cycle_succ_a_neigh funpow_dist_0_eq neq0_conv same_face) then have pos_dist: "0 < funpow_dist1 H.face_cycle_succ a_neigh b" by (simp add: m_def) have *: "(G.face_cycle_succ ^^ Suc m) a' = a" using a_in_o by (simp add: m_def funpow_simp_l funpow_dist1_prop del: funpow.simps) have "(H.face_cycle_succ ^^ m) a_neigh = a_neigh" proof - have "a = G.face_cycle_succ ((H.face_cycle_succ ^^ m) a_neigh)" using * \<open>0 < m\<close> by (simp add: Y m_def) then show ?thesis using face_cycle_succ_a_neigh by (metis G.face_cycle_pred_succ) qed then have "funpow_dist1 H.face_cycle_succ a_neigh b \<le> m" using \<open>0 < m\<close> b_in0 by (intro funpow_dist1_le_self) simp_all also have "\<dots> < funpow_dist1 G.face_cycle_succ a' a" unfolding m_def by simp finally have dist_less: "funpow_dist1 H.face_cycle_succ a_neigh b < funpow_dist1 G.face_cycle_succ a' a" . have "b = (H.face_cycle_succ ^^ funpow_dist1 H.face_cycle_succ a_neigh b) a_neigh" using b_in0 by (simp add: funpow_dist1_prop del: funpow.simps) also have "\<dots> = (G.face_cycle_succ ^^ funpow_dist1 H.face_cycle_succ a_neigh b) a'" using pos_dist dist_less by (rule Y) also have "\<dots> \<in> ?R" using pos_dist dist_less by (simp add: segment_altdef a_in_o del: funpow.simps) finally show "b \<in> ?R" . next fix b assume "b \<in> ?R" then show "b \<in> ?L" using Y by (auto simp: segment_altdef a_in_o H.face_cycle_set_altdef Suc_le_eq) metis qed qed end locale bidel_arc_isolated_loop = bidel_arc_biconnected + bidel_arc_tail_isolated begin lemma loop_a[simp]: "head G a = tail G a" using isolated_tail reach_a by (auto simp: H.isolated_verts_def elim: H.converse_reachable_cases dest: out_arcs_emptyD_dominates) end sublocale bidel_arc_isolated_loop \<subseteq> bidel_arc_head_isolated using isolated_tail loop_a by unfold_locales simp context bidel_arc_isolated_loop begin text \<open>The edges @{term a} and @{term a'} form a loop on an otherwise isolated vertex \<close> lemma card_isolated_verts_da: "card H.isolated_verts = Suc (card G.isolated_verts)" by (simp add: card_isolated_verts_da0 isolated_tail) lemma G_edge_succ_a[simp]: "edge_succ M a = a'" (is ?t1) and G_edge_succ_a'[simp]: "edge_succ M a' = a" (is ?t2) proof - have *: "out_arcs G (tail G a) = {a,a'}" using a_in isolated_tail by (auto simp: H.isolated_verts_def verts_H out_arcs_def arcs_H tail_H) obtain "edge_succ M a' \<in> {a,a'}" "edge_succ M a' \<noteq> a'" using G.edge_succ_cyclic[of "tail G a'"] apply (rule eq_on_cyclic_on_iff1[where x="a'"]) using * a_in a_neq_a' loop_a by auto moreover obtain "edge_succ M a \<in> {a,a'}" "edge_succ M a \<noteq> a" using G.edge_succ_cyclic[of "tail G a"] apply (rule eq_on_cyclic_on_iff1[where x="a"]) using * a_in a_neq_a' loop_a by auto ultimately show ?t1 ?t2 by auto qed lemma G_face_cycle_succ_a[simp]: "G.face_cycle_succ a = a" and G_face_cycle_succ_a'[simp]: "G.face_cycle_succ a' = a'" by (auto simp: G.face_cycle_succ_def) lemma G_face_cycle_set_a[simp]: "G.face_cycle_set a = {a}" and G_face_cycle_set_a'[simp]: "G.face_cycle_set a' = {a'}" unfolding G.fcs_x_eq_x[symmetric] by simp_all end sublocale bidel_arc_isolated_loop \<subseteq> bidel_arc_diff_face using a_neq_a' by unfold_locales auto context bidel_arc_isolated_loop begin lemma card_face_cycle_sets_da: "card G.face_cycle_sets = Suc (Suc (card H.face_cycle_sets))" unfolding card_face_cycle_sets_da' using diff_face card_fcs_aa'_le by (auto simp: card_insert_if S_def G.segment_face_cycle_x_x_eq) lemma euler_genus_da: "H.euler_genus = G.euler_genus" unfolding G.euler_genus_def H.euler_genus_def G.euler_char_def H.euler_char_def by (simp add: card_isolated_verts_da verts_H card_arcs_da card_face_cycle_sets_da card_sccs_da) end locale bidel_arc_two_isolated = bidel_arc_not_biconnected + bidel_arc_tail_isolated + bidel_arc_head_isolated begin text \<open>@{term "tail G a"} and @{term "head G a"} form an SCC with @{term a} and @{term a'} as the only arcs.\<close> lemma no_loop_a: "head G a \<noteq> tail G a" using not_reach_a a_in by (auto simp: verts_H) lemma card_isolated_verts_da: "card H.isolated_verts = Suc (Suc (card G.isolated_verts))" using no_loop_a isolated_tail isolated_head by (simp add: card_isolated_verts_da0 card_insert_if) lemma G_edge_succ_a'[simp]: "edge_succ M a' = a'" using G_edge_succ_a'_no_loop no_loop_a by simp lemma G_edge_succ_a[simp]: "edge_succ M a = a" proof - have *: "out_arcs G (tail G a) = {a}" using a_in isolated_tail isolated_head no_loop_a by (auto simp: H.isolated_verts_def verts_H out_arcs_def arcs_H tail_H) obtain "edge_succ M a \<in> {a}" using G.edge_succ_cyclic[of "tail G a"] apply (rule eq_on_cyclic_on_iff1[where x="a"]) using * a_in a_neq_a' no_loop_a by simp_all then show ?thesis by auto qed lemma G_face_cycle_succ_a[simp]: "G.face_cycle_succ a = a'" and G_face_cycle_succ_a'[simp]: "G.face_cycle_succ a' = a" by (auto simp: G.face_cycle_succ_def) lemma G_face_cycle_set_a[simp]: "G.face_cycle_set a = {a,a'}" (is ?t1) and G_face_cycle_set_a'[simp]: "G.face_cycle_set a' = {a,a'}" (is ?t2) proof - { fix n have "(G.face_cycle_succ ^^ n) a \<in> {a,a'}" "(G.face_cycle_succ ^^ n) a' \<in> {a,a'}" by (induct n) auto } then show ?t1 ?t2 by (auto simp: G.face_cycle_set_altdef intro: exI[where x=0] exI[where x=1]) qed lemma card_face_cycle_sets_da: "card G.face_cycle_sets = Suc (card H.face_cycle_sets)" unfolding card_face_cycle_sets_da0 using card_fcs_aa'_le by simp lemma euler_genus_da: "H.euler_genus = G.euler_genus" unfolding G.euler_genus_def H.euler_genus_def G.euler_char_def H.euler_char_def by (simp add: card_isolated_verts_da verts_H card_arcs_da card_face_cycle_sets_da card_sccs_da) end locale bidel_arc_tail_not_isol = bidel_arc_not_biconnected + bidel_arc_tail_conn sublocale bidel_arc_tail_not_isol \<subseteq> bidel_arc_same_face_tail_conn by unfold_locales locale bidel_arc_only_tail_not_isol = bidel_arc_tail_not_isol + bidel_arc_head_isolated context bidel_arc_only_tail_not_isol begin lemma card_isolated_verts_da: "card H.isolated_verts = Suc (card G.isolated_verts)" using isolated_head conn_tail by (simp add: card_isolated_verts_da0) lemma segment_a'_a_ne: "segment G.face_cycle_succ a' a \<noteq> {}" unfolding H_fcs_a_neigh[symmetric] by auto lemma segment_a_a'_e: "segment G.face_cycle_succ a a' = {}" proof - have "a' = G.face_cycle_succ a" using tail_neq_head by (simp add: G_face_cycle_succ_a_no_loop) then show ?thesis by (auto simp: segment1_empty) qed lemma card_face_cycle_sets_da: "card H.face_cycle_sets = card G.face_cycle_sets" unfolding card_face_cycle_sets_da' using segment_a'_a_ne segment_a_a'_e card_fcs_gt_0 by (simp add: card_insert_if) lemma euler_genus_da: "H.euler_genus = G.euler_genus" unfolding G.euler_genus_def H.euler_genus_def G.euler_char_def H.euler_char_def by (simp add: card_isolated_verts_da verts_H card_arcs_da card_face_cycle_sets_da card_sccs_da) end locale bidel_arc_only_head_not_isol = bidel_arc_not_biconnected + bidel_arc_head_conn + bidel_arc_tail_isolated begin interpretation rev: bidel_arc G M a' using a_in by unfold_locales simp interpretation rev: bidel_arc_only_tail_not_isol G M a' using a_in not_reach_a by unfold_locales (auto simp: rev_H isolated_tail conn_head dest: H.symmetric_reachable') lemma euler_genus_da: "H.euler_genus = G.euler_genus" using rev.euler_genus_da by (simp add: rev_H rev_HM) end locale bidel_arc_two_not_isol = bidel_arc_tail_not_isol + bidel_arc_head_conn begin lemma isolated_verts_da: "H.isolated_verts = G.isolated_verts" using conn_head conn_tail by (subst isolated_da_pre) simp lemma segment_a'_a_ne': "segment G.face_cycle_succ a' a \<noteq> {}" unfolding H_fcs_a_neigh[symmetric] by auto interpretation rev: bidel_arc_tail_not_isol G M a' using arcs_in not_reach_a rev_H conn_head by unfold_locales (auto dest: H.symmetric_reachable') lemma segment_a_a'_ne': "segment G.face_cycle_succ a a' \<noteq> {}" using rev.H_fcs_a_neigh[symmetric] rev_H rev_HM by auto lemma card_face_cycle_sets_da: "card H.face_cycle_sets = Suc (card G.face_cycle_sets)" unfolding card_face_cycle_sets_da' using segment_a'_a_ne' segment_a_a'_ne' card_fcs_gt_0 by (simp add: segments_neq card_insert_if) lemma euler_genus_da: "H.euler_genus = G.euler_genus" unfolding G.euler_genus_def H.euler_genus_def G.euler_char_def H.euler_char_def by (simp add: isolated_verts_da verts_H card_arcs_da card_face_cycle_sets_da card_sccs_da) end locale bidel_arc_biconnected_non_triv = bidel_arc_biconnected + bidel_arc_tail_conn sublocale bidel_arc_biconnected_non_triv \<subseteq> bidel_arc_head_conn by unfold_locales (metis (mono_tags) G.in_sccs_verts_conv_reachable G.symmetric_reachable' H.isolated_verts_in_sccs conn_tail empty_iff insert_iff reach_a reachable_daD sccs_verts_da) context bidel_arc_biconnected_non_triv begin lemma isolated_verts_da: "H.isolated_verts = G.isolated_verts" using conn_head conn_tail by (subst isolated_da_pre) simp end locale bidel_arc_biconnected_same = bidel_arc_biconnected_non_triv + bidel_arc_same_face sublocale bidel_arc_biconnected_same \<subseteq> bidel_arc_same_face_tail_conn by unfold_locales context bidel_arc_biconnected_same begin interpretation rev: bidel_arc_same_face_tail_conn G M a' using arcs_in conn_head by unfold_locales (auto simp: same_face rev_H) lemma card_face_cycle_sets_da: "Suc (card H.face_cycle_sets) \<ge> (card G.face_cycle_sets)" unfolding card_face_cycle_sets_da' using card_fcs_gt_0 by linarith lemma euler_genus_da: "H.euler_genus \<le> G.euler_genus" using card_face_cycle_sets_da unfolding G.euler_genus_def H.euler_genus_def G.euler_char_def H.euler_char_def by (simp add: isolated_verts_da verts_H card_arcs_da card_sccs_da ) end locale bidel_arc_biconnected_diff = bidel_arc_biconnected_non_triv + bidel_arc_diff_face begin lemma fcs_not_triv: "G.face_cycle_set a \<noteq> {a} \<or> G.face_cycle_set a' \<noteq> {a'}" proof (rule ccontr) assume "\<not>?thesis" then have "G.face_cycle_succ a = a" "G.face_cycle_succ a' = a'" by (auto simp: G.fcs_x_eq_x) then have *: "edge_succ M a = a'" "edge_succ M a' = a" by (auto simp: G.face_cycle_succ_def) then have "(edge_succ M ^^ 2) a = a" by (auto simp: eval_nat_numeral) { fix n have "(edge_succ M ^^ 2) a = a" by (auto simp: * eval_nat_numeral) then have "(edge_succ M ^^ n) a = (edge_succ M ^^ (n mod 2)) a" by (auto simp: funpow_mod_eq) moreover have "n mod 2 = 0 \<or> n mod 2 = 1" by auto ultimately have "(edge_succ M ^^ n) a \<in> {a, a'}" by (auto simp: *) } then have "orbit (edge_succ M) a = {a, a'}" by (auto simp: orbit_altdef_permutation[OF G.permutation_edge_succ] exI[where x=0] exI[where x=1] *) have "out_arcs G (tail G a) \<subseteq> {a,a'}" proof - have "cyclic_on (edge_succ M) (out_arcs G (tail G a))" using arcs_in by (intro G.edge_succ_cyclic) auto then have "orbit (edge_succ M) a = out_arcs G (tail G a)" using arcs_in by (intro orbit_cyclic_eq3) auto then show ?thesis using \<open>orbit _ _ = {_, _}\<close> by auto qed then have "out_arcs H (tail G a) = {}" by (auto simp: arcs_H tail_H) then have "tail G a \<in> H.isolated_verts" using arcs_in by (simp add: H.isolated_verts_def verts_H) then show False using conn_tail by contradiction qed lemma S_ne: "S \<noteq> {}" using fcs_not_triv by (auto simp: S_def G.segment_face_cycle_x_x_eq) lemma card_face_cycle_sets_da: "card G.face_cycle_sets = Suc (card H.face_cycle_sets)" unfolding card_face_cycle_sets_da' using S_ne diff_face card_fcs_aa'_le by simp lemma euler_genus_da: "H.euler_genus = G.euler_genus" unfolding G.euler_genus_def H.euler_genus_def G.euler_char_def H.euler_char_def by (simp add: isolated_verts_da verts_H card_arcs_da card_sccs_da card_face_cycle_sets_da) end context bidel_arc begin lemma euler_genus_da: "H.euler_genus \<le> G.euler_genus" proof - let ?biconnected = "tail G a \<rightarrow>\<^sup>*\<^bsub>H\<^esub> head G a" let ?isol_tail = "tail G a \<in> H.isolated_verts" let ?isol_head = "head G a \<in> H.isolated_verts" let ?same_face = "G.face_cycle_set a' = G.face_cycle_set a" { assume ?biconnected ?isol_tail then interpret EG: bidel_arc_isolated_loop by unfold_locales have ?thesis by (simp add: EG.euler_genus_da) } moreover { assume ?biconnected "\<not>?isol_tail" ?same_face then interpret EG: bidel_arc_biconnected_same by unfold_locales have ?thesis by (simp add: EG.euler_genus_da) } moreover { assume ?biconnected "\<not>?isol_tail" "\<not>?same_face" then interpret EG: bidel_arc_biconnected_diff by unfold_locales have ?thesis by (simp add: EG.euler_genus_da) } moreover { assume "\<not>?biconnected" ?isol_tail ?isol_head then interpret EG: bidel_arc_two_isolated by unfold_locales have ?thesis by (simp add: EG.euler_genus_da) } moreover { assume "\<not>?biconnected" "\<not>?isol_tail" ?isol_head then interpret EG: bidel_arc_only_tail_not_isol by unfold_locales have ?thesis by (simp add: EG.euler_genus_da) } moreover { assume "\<not>?biconnected" ?isol_tail "\<not>?isol_head" then interpret EG: bidel_arc_only_head_not_isol by unfold_locales have ?thesis by (simp add: EG.euler_genus_da) } moreover { assume "\<not>?biconnected" "\<not>?isol_tail" "\<not>?isol_head" then interpret EG: bidel_arc_two_not_isol by unfold_locales have ?thesis by (simp add: EG.euler_genus_da) } ultimately show ?thesis by satx qed end subsection \<open>Modifying @{term edge_rev}\<close> definition (in pre_digraph_map) rev_swap :: "'b \<Rightarrow> 'b \<Rightarrow> 'b pre_map" where "rev_swap a b = \<lparr> edge_rev = perm_swap a b (edge_rev M), edge_succ = perm_swap a b (edge_succ M) \<rparr>" context digraph_map begin lemma digraph_map_rev_swap: assumes "arc_to_ends G a = arc_to_ends G b" "{a,b} \<subseteq> arcs G" shows "digraph_map G (rev_swap a b)" proof let ?M' = "rev_swap a b" have tail_swap: "\<And>x. tail G ((a \<rightleftharpoons>\<^sub>F b) x) = tail G x" using assms by (case_tac "x \<in> {a,b}") (auto simp: arc_to_ends_def) have swap_in_arcs: "\<And>x. (a \<rightleftharpoons>\<^sub>F b) x \<in> arcs G \<longleftrightarrow> x \<in> arcs G" using assms by (case_tac "x \<in> {a,b}") auto have es_perm: "edge_succ ?M' permutes arcs G" using assms edge_succ_permutes unfolding permutes_conv_has_dom by (auto simp: rev_swap_def has_dom_perm_swap) { fix x show "(x \<in> arcs G) = (edge_rev (rev_swap a b) x \<noteq> x)" using assms(2) by (cases "x \<in> {a,b}") (auto simp: rev_swap_def perm_swap_def arev_dom swap_def split: if_splits) next fix x assume "x \<in> arcs G" then show "edge_rev ?M' (edge_rev ?M' x) = x" by (auto simp: rev_swap_def perm_swap_comp[symmetric]) next fix x assume "x \<in> arcs G" then show "tail G (edge_rev ?M' x) = head G x" using assms by (case_tac "x \<in> {a,b}") (auto simp: rev_swap_def perm_swap_def tail_swap arc_to_ends_def) next show "edge_succ ?M' permutes arcs G" by fact next fix v assume A: "v \<in> verts G" "out_arcs G v \<noteq> {}" then obtain c where "c \<in> out_arcs G v" by blast have "inj (perm_swap a b (edge_succ M))" by (simp add: bij_is_inj bij_edge_succ) have "out_arcs G v = (a \<rightleftharpoons>\<^sub>F b) ` out_arcs G v" by (auto simp: tail_swap swap_swap_id swap_in_arcs intro: image_eqI[where x="(a \<rightleftharpoons>\<^sub>F b) y" for y]) also have "(a \<rightleftharpoons>\<^sub>F b) ` out_arcs G v = (a \<rightleftharpoons>\<^sub>F b) ` orbit (edge_succ M) ((a \<rightleftharpoons>\<^sub>F b) c)" using edge_succ_cyclic using A \<open>c \<in> _\<close> by (intro arg_cong[where f="(`) (a \<rightleftharpoons>\<^sub>F b)"]) (intro orbit_cyclic_eq3[symmetric], auto simp: swap_in_arcs tail_swap) also have "\<dots> = orbit (edge_succ ?M') c" by (simp add: orbit_perm_swap rev_swap_def) finally have oa_orb: "out_arcs G v = orbit (edge_succ ?M') c" . show "cyclic_on (edge_succ ?M') (out_arcs G v)" unfolding oa_orb using es_perm finite_arcs by (rule cyclic_on_orbit) } qed lemma euler_genus_rev_swap: assumes "arc_to_ends G a = arc_to_ends G b" "{a,b} \<subseteq> arcs G" shows "pre_digraph_map.euler_genus G (rev_swap a b) = euler_genus" proof - let ?M' = "rev_swap a b" interpret G': digraph_map G ?M' using assms by (rule digraph_map_rev_swap) have swap_in_arcs: "\<And>x. (a \<rightleftharpoons>\<^sub>F b) x \<in> arcs G \<longleftrightarrow> x \<in> arcs G" using assms by (case_tac "x \<in> {a,b}") auto have G'_fcs: "G'.face_cycle_succ = perm_swap a b face_cycle_succ" unfolding G'.face_cycle_succ_def face_cycle_succ_def by (auto simp: fun_eq_iff rev_swap_def perm_swap_comp) have "\<And>x. G'.face_cycle_set x = (a \<rightleftharpoons>\<^sub>F b) ` face_cycle_set ((a \<rightleftharpoons>\<^sub>F b) x)" by (auto simp: face_cycle_set_def G'.face_cycle_set_def orbit_perm_swap G'_fcs imageI) then have "G'.face_cycle_sets = (\<lambda>S. (a \<rightleftharpoons>\<^sub>F b) ` S) ` face_cycle_sets" by (auto simp: pre_digraph_map.face_cycle_sets_def swap_in_arcs) (metis swap_swap_id image_eqI swap_in_arcs) then have "card G'.face_cycle_sets = card ((\<lambda>S. (a \<rightleftharpoons>\<^sub>F b) ` S) ` face_cycle_sets)" by simp also have "\<dots> = card face_cycle_sets" by (rule card_image) (rule inj_on_f_imageI[where S="UNIV"], auto) finally show "pre_digraph_map.euler_genus G ?M' = euler_genus" unfolding pre_digraph_map.euler_genus_def pre_digraph_map.euler_char_def by simp qed end subsection \<open>Conclusion\<close> lemma bidirected_subgraph_obtain: assumes sg: "subgraph H G" "arcs H \<noteq> arcs G" assumes fin: "finite (arcs G)" assumes bidir: "\<exists>rev. bidirected_digraph G rev" "\<exists>rev. bidirected_digraph H rev" obtains a a' where "{a,a'} \<subseteq> arcs G - arcs H" "a' \<noteq> a" "tail G a' = head G a" "head G a'= tail G a" proof - obtain a where a: "a \<in> arcs G - arcs H" using sg by blast obtain rev_G rev_H where rev: "bidirected_digraph G rev_G" "bidirected_digraph H rev_H" using bidir by blast interpret G: bidirected_digraph G rev_G by (rule rev) interpret H: bidirected_digraph H rev_H by (rule rev) have sg_props: "arcs H \<subseteq> arcs G" "tail H = tail G" "head H = head G" using sg by (auto simp: subgraph_def compatible_def) { fix w1 w2 assume A: "tail G a = w1" "head G a = w2" have "in_arcs H w1 \<inter> out_arcs H w2 = rev_H ` (out_arcs H w1 \<inter> in_arcs H w2)" (is "?Sh = _") unfolding H.in_arcs_eq by (simp add: image_Int image_image H.inj_on_arev) then have "card (in_arcs H w1 \<inter> out_arcs H w2) = card (out_arcs H w1 \<inter> in_arcs H w2)" by (metis card_image H.arev_arev inj_on_inverseI) also have "\<dots> < card (out_arcs G w1 \<inter> in_arcs G w2)" (is "card ?Sh1 < card ?Sg1") proof (rule psubset_card_mono) show "finite ?Sg1" using fin by (auto simp: out_arcs_def) show "?Sh1 \<subset> ?Sg1" using A a sg_props by auto qed also have "?Sg1 = rev_G ` (in_arcs G w1 \<inter> out_arcs G w2)" (is "_ = _ ` ?Sg") unfolding G.in_arcs_eq by (simp add: image_Int image_image G.inj_on_arev) also have "card \<dots> = card ?Sg" by (metis card_image G.arev_arev inj_on_inverseI) finally have card_less: "card ?Sh < card ?Sg" . have S_ss: "?Sh \<subseteq> ?Sg" using sg_props by auto have ?thesis proof (cases "w1 = w2") case True have "card (?Sh - {a}) = card ?Sh" using a by (intro arg_cong[where f=card]) auto also have "\<dots> < card ?Sg - 1" proof - from True have "even (card ?Sg)" "even (card ?Sh)" by (auto simp: G.even_card_loops H.even_card_loops) then show ?thesis using card_less by simp (metis Suc_pred even_Suc le_neq_implies_less lessE less_Suc_eq_le zero_less_Suc) qed also have "\<dots> = card (?Sg - {a})" using fin a A True by (auto simp: out_arcs_def card_Diff_singleton) finally have card_diff_a_less: "card (?Sh - {a}) < card (?Sg - {a})" . moreover from S_ss have "?Sh - {a} \<subseteq> ?Sg - {a}" using S_ss by blast ultimately have "?Sh - {a} \<subset> ?Sg - {a}" by (intro card_psubset) auto then obtain a' where "a' \<in> (?Sg - {a})- ?Sh" by blast then have "{a,a'} \<subseteq> arcs G - arcs H" "a' \<noteq> a" "tail G a' = head G a" "head G a'= tail G a" using A a sg_props by auto then show ?thesis .. next case False from card_less S_ss have "?Sh \<subset> ?Sg" by auto then obtain a' where "a' \<in> ?Sg - ?Sh" by blast then have "{a,a'} \<subseteq> arcs G - arcs H" "a' \<noteq> a" "tail G a' = head G a" "head G a'= tail G a" using A a sg_props False by auto then show ?thesis .. qed } then show ?thesis by simp qed lemma subgraph_euler_genus_le: assumes G: "subgraph H G" "digraph_map G GM" and H: "\<exists>rev. bidirected_digraph H rev" obtains HM where "digraph_map H HM" "pre_digraph_map.euler_genus H HM \<le> pre_digraph_map.euler_genus G GM" proof - let ?d = "\<lambda>G. card (arcs G) + card (verts G) - card (arcs H) - card (verts H)" from H obtain rev_H where "bidirected_digraph H rev_H" by blast then interpret H: bidirected_digraph H rev_H . from G have "\<exists>HM. digraph_map H HM \<and> pre_digraph_map.euler_genus H HM \<le> pre_digraph_map.euler_genus G GM" proof (induct "?d G" arbitrary: G GM rule: less_induct) case less from less interpret G: digraph_map G GM by - have H_ss: "arcs H \<subseteq> arcs G" "verts H \<subseteq> verts G" using \<open>subgraph H G\<close> by auto then have card_le: "card (arcs H) \<le> card (arcs G)" "card (verts H) \<le> card (verts G)" by (auto intro: card_mono) have ends: "tail H = tail G" "head H = head G" using \<open>subgraph H G\<close> by (auto simp: compatible_def) show ?case proof (cases "?d G = 0") case True then have "card (arcs H) = card (arcs G)" "card (verts H) = card (verts G)" using card_le by linarith+ then have "arcs H = arcs G" "verts H = verts G" using H_ss by (auto simp: card_subset_eq) then have "H = G" using \<open>subgraph H G\<close> by (auto simp: compatible_def) then have "digraph_map H GM \<and> pre_digraph_map.euler_genus H GM \<le> G.euler_genus" by auto then show ?thesis .. next case False then have H_ne: "(arcs G - arcs H) \<noteq> {} \<or> (verts G - verts H) \<noteq> {}" using H_ss card_le by auto { assume A: "arcs G - arcs H \<noteq> {}" then obtain a a' where aa': "{a, a'} \<subseteq> arcs G - arcs H" "a' \<noteq> a" "tail G a' = head G a" "head G a' = tail G a" using H_ss \<open>subgraph H G\<close> by (auto intro: bidirected_subgraph_obtain) let ?GM' = "G.rev_swap (edge_rev GM a) a'" interpret G': digraph_map G ?GM' using aa' by (intro G.digraph_map_rev_swap) (auto simp: arc_to_ends_def) interpret G': bidel_arc G ?GM' a using aa' by unfold_locales simp have "edge_rev GM a \<noteq> a" using aa' by (intro G.arev_neq) auto then have er_a: "edge_rev ?GM' a = a'" using \<open>a' \<noteq> a\<close> by (auto simp: G.rev_swap_def perm_swap_def swap_id_eq dest: G.arev_neq) then have sg: "subgraph H G'.H" using H_ss aa' by (intro subgraphI) (auto simp: G'.verts_H G'.arcs_H G'.tail_H G'.head_H ends compatible_def intro: H.wf_digraph G'.H.wf_digraph) have "card {a,a'} \<le> card (arcs G)" using aa' by (intro card_mono) auto then obtain HM where HM: "digraph_map H HM" "pre_digraph_map.euler_genus H HM \<le> G'.H.euler_genus" using aa' False by atomize_elim (rule less, auto simp: G'.verts_H G'.arcs_H card_insert_if sg er_a) have "G'.H.euler_genus \<le> G'.euler_genus" by (rule G'.euler_genus_da) also have "G'.euler_genus = G.euler_genus" using aa' by (auto simp: G.euler_genus_rev_swap arc_to_ends_def) finally have ?thesis using HM by auto } moreover { assume A: "arcs G - arcs H = {}" then have A': "verts G - verts H \<noteq> {}" and arcs_H: "arcs H = arcs G" using H_ss H_ne by auto then obtain v where v: "v \<in> verts G - verts H" by auto have card_lt: "card (verts H) < card (verts G)" using A' H_ss by (intro psubset_card_mono) auto have "out_arcs G v = out_arcs H v" using A H_ss by (auto simp: ends) then interpret G: del_vert_props G GM v using v by unfold_locales auto have "?d (G.del_vert v) < ?d G" using card_lt by (simp add: arcs_H G.arcs_dv G.card_verts_dv) moreover have "subgraph H (G.del_vert v)" using H_ss v by (auto simp: subgraph_def arcs_H G.arcs_dv G.verts_del_vert H.wf_digraph G.H.wf_digraph compatible_def G.tail_del_vert G.head_del_vert ends) moreover have "bidirected_digraph (G.del_vert v) (edge_rev GM)" using G.arev_dom by (intro G.H.bidirected_digraphI) (auto simp: G.arcs_dv) ultimately have ?thesis unfolding G.euler_genus_eq[symmetric] by (intro less) auto } ultimately show ?thesis by blast qed qed then obtain HM where "digraph_map H HM" "pre_digraph_map.euler_genus H HM \<le> pre_digraph_map.euler_genus G GM" by atomize_elim then show ?thesis .. qed lemma (in digraph_map) nonneg_euler_genus: "0 \<le> euler_genus" proof - define H where "H = \<lparr> verts = {}, arcs = {}, tail = tail G, head = head G \<rparr>" then have H_simps: "verts H = {}" "arcs H = {}" "tail H = tail G" "head H = head G" by (simp_all add: H_def) interpret H: bidirected_digraph H id by unfold_locales (auto simp: H_def) have "wf_digraph H" "wf_digraph G" by unfold_locales then have "subgraph H G" by (intro subgraphI) (auto simp: H_def compatible_def) then obtain HM where "digraph_map H HM" "pre_digraph_map.euler_genus H HM \<le> euler_genus" by (rule subgraph_euler_genus_le) auto then interpret H: digraph_map H HM by - have "H.sccs = {}" proof - { fix x assume *: "x \<in> H.sccs_verts" then have "x = {}" by (auto dest: H.sccs_verts_subsets simp: H_simps) with * have False by (auto simp: H.in_sccs_verts_conv_reachable) } then show ?thesis by (auto simp: H.sccs_verts_conv) qed then have "H.euler_genus = 0" by (auto simp: H.euler_genus_def H.euler_char_def H.isolated_verts_def H.face_cycle_sets_def H_simps) then show ?thesis using \<open>H.euler_genus \<le> _\<close> by simp qed lemma subgraph_comb_planar: assumes "subgraph G H" "comb_planar H" "\<exists>rev. bidirected_digraph G rev" shows "comb_planar G" proof - from \<open>comb_planar H\<close> obtain HM where "digraph_map H HM" and H_genus: "pre_digraph_map.euler_genus H HM = 0" unfolding comb_planar_def by metis obtain GM where G: "digraph_map G GM" "pre_digraph_map.euler_genus G GM \<le> pre_digraph_map.euler_genus H HM" using assms(1) \<open>digraph_map H HM\<close> assms(3) by (rule subgraph_euler_genus_le) interpret G: digraph_map G GM by fact show ?thesis using G H_genus G.nonneg_euler_genus unfolding comb_planar_def by auto qed end
# Using NumPy and SciPy modules In addition to using Cantera and Pint to help solve thermodynamics problems, we will need to use some additional packages in the scientific Python ecosystem to make plots, solve systems of equations, integrate ordinary differential equations, and more. ```{margin} The [*SciPy Lecture Notes*](https://scipy-lectures.org) are excellent, detailed resources on all these topics, and Python programming in general {cite}`scipylecture`. ``` The examples contained in this electronic book will integrate these techniques as needed, but this notebook contains some specific examples. ## Index 1. [Plotting](#plotting) 2. [Solving systems of equations](#solving-systems-of-equations) 3. [Integrating ODE systems](#integrating-ode-systems) 4. [Optimization](#optimization) 5. [Differentiation](#differentiation) ## Plotting We can use [Matplotlib](https://matplotlib.org) to produce nice plots of our results. If you used Anaconda to set up your computing environment, you likely already have Matplotlib installed; if not, see their [installation instructions](https://matplotlib.org/users/installing.html). Matplotlib provides an interface that is very similar to what you might already know from Matlab: `pyplot`. You can import this in Python files or a Jupyter notebook with the standard abbreviation `plt`: ```python # this line makes figures interactive in Jupyter notebooks %matplotlib inline from matplotlib import pyplot as plt ``` ```python # these lines are only for helping improve the display import matplotlib_inline.backend_inline matplotlib_inline.backend_inline.set_matplotlib_formats('pdf', 'png') plt.rcParams['figure.dpi']= 150 plt.rcParams['savefig.dpi'] = 150 ``` For example, let's generate some values of an independent variable $x$ linearly spaced between 0 and 10 (using the NumPy function [`linspace()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html)), and then plot the function $y(x) = \sin(x)$. We can also add labels to the axes, a legend, and a helpful grid. ```python import numpy as np x = np.linspace(0, 10, num=50, endpoint=True) y = np.sin(x) plt.plot(x, y, label='y(x)') plt.xlabel('x axis') plt.ylabel('y axis') plt.legend() plt.grid(True) plt.tight_layout() plt.show() ``` We can also plot multiple data series in a single figure: ```python plt.plot(x, y, label='sin(x)') plt.plot(x, np.cos(x), label='cos(x)') plt.xlabel('x axis') plt.ylabel('y axis') plt.grid(True) plt.legend() plt.show() ``` Or, we can use subplots to plot multiple axes in the same overall figure: ```python # 2 rows, 1 column fig, axes = plt.subplots(2, 1) axes[0].plot(x, y, label='sin(x)') axes[0].set_ylabel('sin(x)') axes[0].grid(True) axes[1].plot(x, np.cos(x), label='cos(x)') axes[1].set_xlabel('x axis') axes[1].set_ylabel('cos(x)') axes[1].grid(True) plt.show() ``` ## Solving systems of equations Frequently we will encounter a system of one or more equations that involves an equal number of unknowns. If this is a linear system of equations, we can use linear algebra and the NumPy [`linalg.solve()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.solve.html) function, but more often in thermodynamics we encounter complex and/or nonlinear systems. In cases like this, we will need to set up our problems to find the roots, or zeroes, of the function(s); in other words, given a function $ f(x) $, finding the root means to find the value of $x$ such that $ f(x) = 0 $. If we are dealing with a system of equations and the same number of unknowns, then these would be vectors: $\mathbf{f}(\mathbf{x}) = 0$. (You might be wondering what to do about equations that don't equal zero... for example, if you have something like $f(x) = g(x)$. In this case, you just need to manipulate the equation to be in the form $f(x) - g(x) = 0$.) The [SciPy optimization module](https://docs.scipy.org/doc/scipy/reference/optimize.html) provides functions to find roots of equations; for scalar equations, we can use [`root_scalar()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.root_scalar.html#scipy.optimize.root_scalar), and for vector equations, we can use [`root()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.root.html). ### Scalar equations Let's first look at an example of a scalar function: one equation, one unknown. Find the root of this equation: \begin{equation} \cos(x) = x^3 \end{equation} We need to create a Python function that returns $f(x) = 0$, so that the function returns zero when the input value of $x$ is the (correct) root. Then, we can use the `root_scalar` function with some initial guesses. ```python import numpy as np from scipy import optimize def func(x): return np.cos(x) - x**3 sol = optimize.root_scalar(func, x0=1.0, x1=2.0) print(f'Root: x ={sol.root: .3f}') print(f'Function evaluated at root: {func(sol.root)}') ``` Root: x = 0.865 Function evaluated at root: -2.220446049250313e-16 ### Systems of equations / vector functions We can also solve systems of equations in a similar fashion using the SciPy [`root()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.root.html) functino, where we find the roots $\mathbf{x}$ that satisfy $\mathbf{f} (\mathbf{x}) = 0$. For example, let's try to find the values of $x$ and $y$ that satisfy these equations: $$ x \ln (x) = y^3 \\ \sqrt{x} = \frac{1}{y} $$ We have two equations and two unknowns, so we should be able to find the roots. To solve, we create a function that evaluates these equations when made equal to zero, or $$ x \ln (x) - y^3 = 0 \\ \sqrt{x} - \frac{1}{y} = 0 $$ then we call `root` specifying this function and two initial guesses for $x$ and $y$: ```python import numpy as np from scipy import optimize def system(vars): x = vars[0] y = vars[1] return [ x*np.log(x) - y**3, np.sqrt(x) - (1/y) ] sol = optimize.root(system, [1.0, 1.0]) x = sol.x[0] y = sol.x[1] print(f'Roots: x = {x: .3f}, y = {y: .3f}') ``` Roots: x = 1.467, y = 0.826 ## Integrating ODE systems In some cases, we encounter problems that require integrating one or more ordinary different equations in time. Depending on the form of the problem, we may need to integrate a function between two points (definite integral), or we may have a system of ordinary differential equations. ### Numerical integral of samples In some cases we have a set of $(x,y)$ data that we want to integrate numerically. We can do this using the NumPy [`trapz()` function](https://docs.scipy.org/doc/numpy/reference/generated/numpy.trapz.html), which implements the composite trapezoidal rule. For example, let's consider a situation where a reciprocating compressor is being used to compress ammonia vapor during a refrigeration cycle. We have some experimental measurements of the pressure-volume data during the compression stroke (see table), and we want to determine the work done on the ammonia by the piston. | Pressure (psi) | Volume (in^3) | |----------------|---------------| | 65.1 | 80.0 | | 80.5 | 67.2 | | 93.2 | 60.1 | | 110 | 52.5 | | 134 | 44.8 | | 161 | 37.6 | | 190 | 32.5 | To find the work done by the piston to the ammonia, we can integrate pressure with respect to volume: \begin{equation} W_{\text{in}} = -\int_{V_1}^{V_2} P \, dV \end{equation} ```python import numpy as np from pint import UnitRegistry ureg = UnitRegistry() Q_ = ureg.Quantity pressure = Q_([65.1, 80.5, 93.2, 110, 134, 161, 190], 'psi') volume = Q_([80.0, 67.2, 60.1, 52.5, 44.8, 37.6, 32.5], 'in^3') # convert to SI units pressure.ito('Pa') volume.ito('m^3') work = -Q_( np.trapz(pressure.magnitude, volume.magnitude), pressure.units * volume.units ) print(f'Work done on fluid: {work.to("J"): .2f}') ``` Work done on fluid: 589.45 joule ### Numerical integral of expression We can also numerically integrate expressions/functions using the SciPy [`quad()` function](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html), also in the `integrate` module. Let's build on the previous example: first, let's fit the compressor data to the polytropic form $P V^n = c$, where $c$ and $n$ are constants, then we can integrate the resulting function to calculate work. To fit the data, we need to rearrange the equation to the form $y = f(x)$: \begin{equation} P = c V^{-n} \end{equation} We'll use the [`scipy.optimize.curve_fit()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html) function for that. ```python import numpy as np from scipy.optimize import curve_fit from scipy.integrate import quad from pint import UnitRegistry ureg = UnitRegistry() Q_ = ureg.Quantity pressure = Q_([65.1, 80.5, 93.2, 110, 134, 161, 190], 'psi') volume = Q_([80.0, 67.2, 60.1, 52.5, 44.8, 37.6, 32.5], 'in^3') # convert to SI units pressure.ito('Pa') volume.ito('m^3') def fit(V, n, c): '''Evaluate P = c * V**(-n). n and c will be found by the curve_fit functino. ''' return c * np.power(V, -n) # this function will automatically fit the unknown constants params, cov = curve_fit(fit, volume.magnitude, pressure.magnitude) print(f'Parameters: n={params[0]: 5.3f}, c={params[1]: 5.3f}') ``` Parameters: n= 1.170, c= 194.200 /var/folders/ng/d9rd9fb92c7bxz9fy7vwpj7m0000gp/T/ipykernel_14239/2169371920.py:21: RuntimeWarning: overflow encountered in power return c * np.power(V, -n) ```python plt.plot(volume.magnitude, pressure.magnitude, 'o', label='Data') x = np.linspace(volume[0].magnitude, volume[-1].magnitude, 100) # plot data and fit plt.plot(x, fit(x, *params), 'r-', label=f'fit: n={params[0]: 5.3f}, c={params[1]: 5.3f}' ) plt.xlabel('Volume (m^3)') plt.ylabel('Pressure (Pa)') plt.legend() plt.tight_layout() plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.show() ``` That looks like a great fit to the data, so now let's evaluate the work by integrating: ```python y, err = quad( fit, volume[0].magnitude, volume[-1].magnitude, args=(params[0], params[1]) ) work = -Q_(y, pressure.units * volume.units) print(f'Work done on fluid: {work.to("J"): .2f}') ``` Work done on fluid: 586.26 joule ### Initial value problems In other words, we may have a system like \begin{equation} \frac{d \mathbf{y}}{dt} = \mathbf{f} (t, \mathbf{y}) \end{equation} where $\mathbf{y}$ is the vector of state variables, for which we should have the initial values ($\mathbf{y}(t=0)$). In this case, we can use the SciPy function [`solve_ivp()` function](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html), part of the `integrate` module. For example, let's consider a problem where we want to find the volume of water, volume of air, and pressure in a tank as a function of time, as the tank releases water to an environment. The volumetric flow rate through the tank's valve is based on its instantaneous pressure: $$ \dot{V}_f = \frac{P - P_{\text{atm}}}{R_v} \;, $$ where $P_{\text{atm}}$ is atmospheric pressure and $R_v = 10$ psi/gpm is the valve resistance parameter. The tank has volume 50 gal, and is initially filled with water (volume fraction $f$ = 0.8); the air in the tank is initially at 100 psi. We will treat the air as an ideal gas, and the water as an incompressible substance. We have the initial air pressure, and we can calculate the initial volumes of water and air: $$ V_{f,0} = f \, V \\ V_{g,0} = (1 - f) V \\ $$ We can perform a mass balance on the water in the tank to obtain a rate equation for the volume of water: $$ 0 = \dot{m}_f + \frac{d m_f}{dt} = \dot{V}_f \rho_f + \rho_f \frac{d V_f}{dt} \\ 0 = \dot{V}_f + \frac{dV_f}{dt} \\ \therefore \frac{dV_f}{dt} = -\frac{(P - P_{\text{atm}})}{R_v} $$ Since the overall volume of the tank is constant, we can obtain the rate of change of the volume of air: $$ V = V_g + V_f \\ \frac{dV_g}{dt} + \frac{dV_f}{dt} = 0 \\ \therefore \frac{dV_g}{dt} = -\frac{dV_f}{dt} $$ Finally, a mass balance on the air in the tank allows us to find the rate of change of pressure: $$ 0 = \frac{dm_a}{dt} \\ 0 = \frac{d}{dt} \left( \frac{P V_g}{R T} \right) \\ 0 = V_g \frac{dP}{dt} + P \frac{dV_g}{dt} \\ \therefore \frac{dP}{dt} = -\frac{P}{V_g} \frac{dV_g}{dt} $$ Now, we can integrate this system of ODEs: ```python from pint import UnitRegistry ureg = UnitRegistry() Q_ = ureg.Quantity # initial conditions and constants valve_resistance = Q_(10, 'psi/(gal/min)') pressure_atmosphere = Q_(1, 'atm') volume_tank = Q_(50, 'gal') water_fraction = 0.8 pressure_initial = Q_(100, 'psi') volume_water_initial = water_fraction * volume_tank volume_air_initial = (1.0 - water_fraction) * volume_tank ``` ```python def tank_equations(t, y, valve_resistance, pressure_atmosphere): '''Rates of change for water volume, air volume, and air pressure in tank. Input values in SI units. ''' volume_water = Q_(y[0], 'm^3') volume_air = Q_(y[1], 'm^3') pressure_air = Q_(y[2], 'Pa') dVf_dt = -(pressure_air - pressure_atmosphere) / valve_resistance dVg_dt = -dVf_dt dP_dt = -(pressure_air / volume_air) * dVg_dt return [ dVf_dt.to('m^3/s').magnitude, dVg_dt.to('m^3/s').magnitude, dP_dt.to('Pa/s').magnitude ] ``` Now that we have the initial conditions and rate function set up, we can integrate in time. Let's do this for 500 seconds, and then plot the water volume and tank pressure as functions of time: ```python from scipy.integrate import solve_ivp # now integrate for 500 seconds, specifying the function, time interval, #initial conditions, and additional arguments to the function sol = solve_ivp( tank_equations, [0, 500.0], [volume_water_initial.to('m^3').magnitude, volume_air_initial.to('m^3').magnitude, pressure_initial.to('Pa').magnitude ], args=(valve_resistance, pressure_atmosphere,), method='BDF' ) ``` ```python time = sol.t volume_water = Q_(sol.y[0], 'm^3') volume_air = Q_(sol.y[1], 'm^3') pressure = Q_(sol.y[2], 'Pa') plt.plot(time, pressure.to('psi').magnitude, label='Tank pressure (psi)') plt.plot(time, volume_water.to('gal').magnitude, label='Water volume (gal)') plt.grid(True) plt.xlabel('Time (s)') plt.ylabel('Water volume (gal) and tank pressure (psi)') plt.ylim(ymin=0.0) # ensure lower y-axis bound is zero plt.legend() plt.tight_layout() plt.show() ``` ## Optimization For some problems, we may want to find the input parameter(s) that minimize or maximize some function. In these cases, we can use the SciPy [`minimize_scalar()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize_scalar.html) function for a scalar function with one input variable, or the [`minimize()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html) function for a scalar function of one or more input variables. (Note: this is a fairly complicated topic, and we will only consider relatively simple optimization problems.) For example, consider a spring with a horizontal force applied; we can calculate the potential energy of the spring: \begin{equation} PE(x) = 0.5 k x^2 - F x \;. \end{equation} At equilibrium, the potential energy will be at a minimum, so given a particular force we can find the displacement by finding the value that minimizes the potential energy. ```python from scipy.optimize import minimize_scalar spring_constant = 2.0 # N/cm force = 5.0 # N def spring(x, k, F): '''Calculates potential energy of spring pulled by force. ''' return 0.5 * k * x**2 - F * x sol = minimize_scalar(spring, args=(spring_constant, force)) print(f'Equilibrium displacement: {sol.x: .2f} cm') ``` Equilibrium displacement: 2.50 cm A more complicated problem is a system with two springs, connected at one end with a force in some general direction (with $x$ and $y$ components); the system has both horizontal and vertical components. The springs have spring constants $k_a$ and $k_b$, and unloaded lengths $L_a$ and $L_b$. The potential energy for this system is \begin{equation} PE(x,y) = 0.5 k_a \left( \sqrt{x^2 + (L_a - y)^2} - L_a \right)^2 + 0.5 k_b \left( \sqrt{x^2 + (L_b + y)^2} - L_b \right)^2 - F_x x - F_y y \end{equation} where $x$ and $y$ are the horizontal and vertical deformations from the unloaded state. We can minimize this function of two variables to find the displacement based on the force: ```python from scipy.optimize import minimize spring_constant_a = 9.0 # N/cm spring_constant_b = 2.0 # N/cm length_a = 10.0 # cm length_b = 10.0 # cm force_x = 2.0 # N force_y = 4.0 # N def spring_system(xvec, ka, kb, La, Lb, Fx, Fy): '''Calculates potential energy of springs pulled by force. ''' x = xvec[0] y = xvec[1] return ( 0.5*ka * (np.sqrt(x**2 + (La - y)**2) - La)**2 + 0.5*kb * (np.sqrt(x**2 + (Lb + y)**2) - Lb)**2 - (Fx * x) - (Fy * y) ) guesses = [1.0, 1.0] sol = minimize( spring_system, guesses, args=(spring_constant_a, spring_constant_b, length_a, length_b, force_x, force_y ) ) x = sol.x[0] y = sol.x[1] print(f'Equilibrium displacement: x={x: .2f} cm, y={y: .2f} cm') ``` Equilibrium displacement: x= 4.95 cm, y= 1.28 cm ## Differentiation Many thermodynamic properties are derivatives of other properties, so you may find the need to take derivatives of either data or of an expression. We can use the NumPy function [`gradient()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html) to take numerical derivatives of data using finite differences, and we can use [SymPy](https://www.sympy.org/en/index.html) to find analytical derivatives of expressions. ### Numerical derivatives Let's say we have data for some function $f(x) = x^2$ at some locations $x$: ```python x = np.linspace(0, 1, 10) f = x**2 plt.plot(x, f) plt.xlabel('x') plt.ylabel('f(x)') plt.grid(True) plt.tight_layout() plt.show() ``` We do not need to know the functional form of $f(x)$ to take the numerical derivatives—this example just uses a simple function for ease of checking the results. The `gradient()` function uses second-order central differences to evaluate the derivative of input data, using forward and backward differences at the boundaries. Let's use that to get the derivative, and compare against the exact derivative ($\frac{df}{dx} = 2x$): ```python dfdx = np.gradient(f, x) dfdx_exact = 2*x plt.plot(x, dfdx_exact, label='Exact') plt.plot(x, dfdx, 'o', label='Numerical') plt.xlabel('x') plt.ylabel('df/dx') plt.grid(True) plt.legend() plt.show() ``` The numerical derivative we obtain is very accurate, thanks to the linear nature of the derivative. However, at the boundaries the approximate derivative is a bit off, due to the first-order finite differences used there. ### Analytical derivative In some cases we may be given (or obtain) analytical expressions that we need to differentiate. Given a function, we have two options for calculating the derivative: 1. Use the function to calculate values over the desired range, then numerically differentiate. 2. Obtain the exact derivative by differentiating analytically. We'll now focus on the latter case; we can use SymPy to construct a function symbolically, and then find the exact derivative. ```python import sympy sympy.init_printing(use_latex='mathjax') x = sympy.symbols('x', real=True) f = x**2 # take derivative of f with respect to x dfdx = sympy.diff(f, x) # this complicated expression is only necessary for printing. # It creates an equation object, that sets the unevaluated # derivative of f equal to the calculated derivative. display(sympy.Eq(sympy.Derivative(f), dfdx)) ``` $\displaystyle \frac{d}{d x} x^{2} = 2 x$ Once we have evaluated the analytical derivative, we can even turn it into a Python function for evaluation! Passing the `'numpy'` argument creates a NumPy array-compatible function. ```python calc_derivative = sympy.lambdify(x, dfdx, 'numpy') x_vals = np.linspace(0, 1, 10) plt.plot(x_vals, 2*x_vals, label='Exact derivative') plt.plot(x_vals, calc_derivative(x_vals), 'o', label='SymPy derivative') plt.xlabel('x') plt.ylabel('df/dx') plt.grid(True) plt.legend() plt.show() ``` As expected, the exact derivative we calculated using SymPy matches the known derivative perfectly—this was obtained symbolically, so there are no approximations/errors involved. When taking the derivative of more complicated expressions that involve other functions (e.g., $\sin$, $\log$), you will need to use the SymPy-provided versions: `sympy.sin`, `sympy.log`, etc. We also need to explicitly define symbolic variables, either using `x = sympy.Symbol('x')` to create one variable at a time or `x, y = sympy.symbols('x y', real=True)` to create multiple variables at once. (The string you specify is the displayed representation of the variable, and can include complex formatting such as subscripts/superscripts and Greek letters.) For example, let's take the derivative of \begin{equation} f(x) = \log(x) + x^3 \end{equation} ```python x = sympy.Symbol('x') f = sympy.log(x) + x**3 dfdx = sympy.diff(f, x) display(dfdx) ``` $\displaystyle 3 x^{2} + \frac{1}{x}$ This matches what we expect for this derivative.
open import Data.Product using ( _×_ ; _,_ ) open import Relation.Binary.PropositionalEquality using ( refl ) open import Relation.Unary using ( _∈_ ) open import Web.Semantic.DL.ABox using ( ABox ; ⟨ABox⟩ ) open import Web.Semantic.DL.ABox.Interp using ( Interp ; Surjective ; _,_ ; ⌊_⌋ ; ind ; _*_ ; emp ) open import Web.Semantic.DL.ABox.Interp.Morphism using ( _≲_ ; _,_ ; ≲⌊_⌋ ; ≲-resp-ind ; _≋_ ; _**_ ) open import Web.Semantic.DL.ABox.Model using ( _⊨a_ ; ⟨ABox⟩-resp-⊨ ; *-resp-⟨ABox⟩ ; ⊨a-resp-≡ ) open import Web.Semantic.DL.Integrity using ( _⊕_⊨_ ; Initial ; Mediator ; Mediated ; _,_ ) open import Web.Semantic.DL.KB using ( KB ; _,_ ) open import Web.Semantic.DL.KB.Model using ( _⊨_ ) open import Web.Semantic.DL.Signature using ( Signature ) open import Web.Semantic.DL.TBox.Interp using ( _⊨_≈_ ; ≈-refl ) open import Web.Semantic.DL.TBox.Interp.Morphism using ( morph ; ≲-image ) open import Web.Semantic.Util using ( False ; _∘_ ; _⊕_⊕_ ; bnode ; inode ; enode ) module Web.Semantic.DL.Integrity.Closed {Σ : Signature} {X : Set} where infix 2 _⊨₀_ sur_⊨₀_ infixr 4 _,_ -- A closed-world variant on integrity constraints. data Mediated₀ (I J : Interp Σ X) : Set where _,_ : (I≲J : I ≲ J) → (∀ (I≲₁J I≲₂J : I ≲ J) → (I≲₁J ≋ I≲₂J)) → Mediated₀ I J data Initial₀ KB (I : Interp Σ X) : Set₁ where _,_ : (I ⊨ KB) → (∀ J → (J ⊨ KB) → Mediated₀ I J) → (I ∈ Initial₀ KB) data _⊨₀_ (KB₁ KB₂ : KB Σ X) : Set₁ where _,_ : ∀ I → ((I ∈ Initial₀ KB₁) × (I ⊨ KB₂)) → (KB₁ ⊨₀ KB₂) -- Surjective variant data sur_⊨₀_ (KB₁ KB₂ : KB Σ X) : Set₁ where _,_ : ∀ I → ((I ∈ Surjective) × (I ∈ Initial₀ KB₁) × (I ⊨ KB₂)) → (sur KB₁ ⊨₀ KB₂) -- Closed-world ICs are given by specializing the open-world case -- to the empty imported interpretion. exp : KB Σ X → KB Σ (False ⊕ False ⊕ X) exp (T , A) = (T , ⟨ABox⟩ enode A) enode⁻¹ : (False ⊕ False ⊕ X) → X enode⁻¹ (inode ()) enode⁻¹ (bnode ()) enode⁻¹ (enode x) = x emp-≲ : ∀ (I : Interp Σ False) → (emp ≲ I) emp-≲ I = (morph (λ ()) (λ {}) (λ ()) (λ {r} → λ {}) , λ ()) ⊨₀-impl-⊨ : ∀ KB₁ KB₂ → (KB₁ ⊨₀ KB₂) → (emp ⊕ exp KB₁ ⊨ KB₂) ⊨₀-impl-⊨ (T , A) (U , B) (I , ((I⊨T , I⊨A) , I-med) , I⊨U , I⊨B) = (I′ , I′-init , I⊨U , ⊨a-resp-≡ I (ind I) refl B I⊨B) where A′ : ABox Σ (False ⊕ False ⊕ X) A′ = ⟨ABox⟩ enode A I′ : Interp Σ (False ⊕ False ⊕ X) I′ = enode⁻¹ * I emp≲I′ : emp ≲ inode * I′ emp≲I′ = emp-≲ (inode * I′) I′-med : Mediator emp I′ emp≲I′ (T , A′) I′-med J′ emp≲J′ (J′⊨T , J′⊨A′) = lemma (I-med J (J′⊨T , J⊨A)) where J : Interp Σ X J = enode * J′ J⊨A : J ⊨a A J⊨A = *-resp-⟨ABox⟩ enode J′ A J′⊨A′ lemma : Mediated₀ I J → Mediated emp I′ J′ emp≲I′ emp≲J′ lemma ((I≲J , i≲j) , I≲J-uniq) = ((I≲J , i′≲j′) , (λ ()) , I′≲J′-uniq) where i′≲j′ : ∀ x → ⌊ J′ ⌋ ⊨ ≲-image I≲J (ind I (enode⁻¹ x)) ≈ ind J′ x i′≲j′ (inode ()) i′≲j′ (bnode ()) i′≲j′ (enode x) = i≲j x I′≲J′-uniq : ∀ (I≲₁J I≲₂J : I′ ≲ J′)_ _ → I≲₁J ≋ I≲₂J I′≲J′-uniq I≲₁J I≲₂J _ _ = I≲J-uniq (≲⌊ I≲₁J ⌋ , λ x → ≲-resp-ind I≲₁J (enode x)) (≲⌊ I≲₂J ⌋ , λ x → ≲-resp-ind I≲₂J (enode x)) I′⊨A′ : I′ ⊨a A′ I′⊨A′ = ⟨ABox⟩-resp-⊨ enode (λ x → ≈-refl ⌊ I ⌋) A I⊨A I′-init : I′ ∈ Initial emp (T , A′) I′-init = ( emp-≲ (inode * I′) , (I⊨T , I′⊨A′) , I′-med ) ⊨-impl-⊨₀ : ∀ KB₁ KB₂ → (emp ⊕ exp KB₁ ⊨ KB₂) → (KB₁ ⊨₀ KB₂) ⊨-impl-⊨₀ (T , A) (U , B) (I′ , (emp≲I′ , (I′⊨T , I′⊨A) , I′-med) , I′⊨U , I′⊨B) = (I , ((I′⊨T , I⊨A) , I-med) , I′⊨U , I′⊨B) where I : Interp Σ X I = enode * I′ I⊨A : I ⊨a A I⊨A = *-resp-⟨ABox⟩ enode I′ A I′⊨A I-med : ∀ J → (J ⊨ T , A) → Mediated₀ I J I-med J (J⊨T , J⊨A) = lemma (I′-med J′ emp≲J′ (J⊨T , J′⊨A)) where J′ : Interp Σ (False ⊕ False ⊕ X) J′ = enode⁻¹ * J emp≲J′ : emp ≲ inode * J′ emp≲J′ = emp-≲ (inode * J′) J′⊨A : J′ ⊨a ⟨ABox⟩ enode A J′⊨A = ⟨ABox⟩-resp-⊨ enode (λ x → ≈-refl ⌊ J ⌋) A J⊨A I≲J-impl-I′≲J′ : (I ≲ J) → (I′ ≲ J′) I≲J-impl-I′≲J′ I≲J = (≲⌊ I≲J ⌋ , i≲j) where i≲j : ∀ x → ⌊ J ⌋ ⊨ ≲-image ≲⌊ I≲J ⌋ (ind I′ x) ≈ ind J (enode⁻¹ x) i≲j (inode ()) i≲j (bnode ()) i≲j (enode x) = ≲-resp-ind I≲J x lemma : Mediated emp I′ J′ emp≲I′ emp≲J′ → Mediated₀ I J lemma (I≲J , _ , I≲J-uniq) = ( (≲⌊ I≲J ⌋ , λ x → ≲-resp-ind I≲J (enode x)) , λ I≲₁J I≲₂J x → I≲J-uniq (I≲J-impl-I′≲J′ I≲₁J) (I≲J-impl-I′≲J′ I≲₂J) (λ ()) (λ ()) x)
function [traj] = initTraj(NbSteps) traj.Rot = zeros(3,3,NbSteps); traj.phi = zeros(1,NbSteps); traj.theta = zeros(1,NbSteps); traj.psi = zeros(1,NbSteps); traj.v = zeros(3,NbSteps); traj.x = zeros(3,NbSteps); traj.omega_b = zeros(3,NbSteps); traj.a_b = zeros(3,NbSteps); end
Nourishing Hydrating Shampoo an antioxidant-packed shampoo that thoroughly cleans without stripping. Leaves hair and scalp hydrated and nourished. Luxurious synthetic-free lather. No harsh sulfates or surfactants. Suits normal, dry, damaged, and color-treated hair. Fresh scent: bright citrus with subtle floral notes. Both the shampoo and conditioner smell absolutely amazing, are extremely nourishing, and are completely toxin-free. Apply to wet hair and work into a lather. Rinse and follow with Nourishing Conditioner. You don’t need harmful SLS to get a good a lather. Instead we use a coconut-derived surfactant, so you can lather to your heart’s content without stripping hair of its natural oils. And because antioxidants are just as important for hair health as they are for skin health, we added those in too. Have we mentioned we love antioxidants? Green and White Tea leaves contain the potent antioxidant catechins which protect your skin, scalp and hair from the oxidative stress that accompanies sun exposure. Green Tea has been shown to prevent the damage associated with skin cancer, wrinkles, and hyperpigmentation. Tea polyphenols have natural astringent, toning, soothing, and anti-inflammatory properties and prevent the enzymes that attack and break down your body's natural production of collagen and elastase. A water soluble surfactant derived from Coconut. Behind every great lather is a great surfactant. Unlike many shampoos, ours is naturally derived (from coconut) and gives a luxurious lather while offering excellent cleansing and moisturizing properties. A combination of antimicrobial peptides, Lactobacillus works to rid of harmful bacteria and stimulate the production of good bacteria on your skin. This humectant prevents moisture loss while balancing and soothing the scalp. A surfactant derived from apples, Sodium Cocoyl Apple Amino Acids conditions the skin. Emollient, nutritive and rich in antioxidants, this oil actually dissolves the oil complex that holds dead skin cells together. Part exfoliant, part lubricant, it reduces flaking and improves texture. Derived from the seeds of the Limnanthes alba, Meadowfoam Seed Oil's long chain fatty acid structure and waxy texture gives it great barrier function, allowing it to lock in moisture and hydrate the hair. Additionally, Meadowfoam functions as a powerful antioxidant, protecting your hair from UV damage. Citric acid helps to preserve a formula by preventing the growth of bacteria. Although it can be obtained from a variety of sources, ours is derived from non-GMO cassava root. This light, naturally fresh blend of whole essential oils was created exclusively for True Botanicals by one of the oldest fragrance houses in the world and incorporates lemon, orange, mimosa, violet, and ylang ylang. Retaining the moisturizing properties of the coconut oil from which it is derived, Decyl Glucoside is a surfactant that also works to moisturize, smooth, and soften the skin.
State Before: R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ det (vandermonde v) = 0 ↔ ∃ i j, v i = v j ∧ i ≠ j State After: case mp R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ det (vandermonde v) = 0 → ∃ i j, v i = v j ∧ i ≠ j case mpr R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ (∃ i j, v i = v j ∧ i ≠ j) → det (vandermonde v) = 0 Tactic: constructor State Before: case mp R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ det (vandermonde v) = 0 → ∃ i j, v i = v j ∧ i ≠ j State After: case mp R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ ∀ (x : Fin n), (x ∈ univ ∧ ∃ a, a ∈ Ioi x ∧ v a = v x) → ∃ i j, v i = v j ∧ i ≠ j Tactic: simp only [det_vandermonde v, Finset.prod_eq_zero_iff, sub_eq_zero, forall_exists_index] State Before: case mp R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ ∀ (x : Fin n), (x ∈ univ ∧ ∃ a, a ∈ Ioi x ∧ v a = v x) → ∃ i j, v i = v j ∧ i ≠ j State After: case mp.intro.intro.intro R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R i : Fin n left✝ : i ∈ univ j : Fin n h₁ : j ∈ Ioi i h₂ : v j = v i ⊢ ∃ i j, v i = v j ∧ i ≠ j Tactic: rintro i ⟨_, j, h₁, h₂⟩ State Before: case mp.intro.intro.intro R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R i : Fin n left✝ : i ∈ univ j : Fin n h₁ : j ∈ Ioi i h₂ : v j = v i ⊢ ∃ i j, v i = v j ∧ i ≠ j State After: no goals Tactic: exact ⟨j, i, h₂, (mem_Ioi.mp h₁).ne'⟩ State Before: case mpr R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ (∃ i j, v i = v j ∧ i ≠ j) → det (vandermonde v) = 0 State After: case mpr R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ ∀ (x x_1 : Fin n), v x = v x_1 → ¬x = x_1 → det (vandermonde v) = 0 Tactic: simp only [Ne.def, forall_exists_index, and_imp] State Before: case mpr R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R ⊢ ∀ (x x_1 : Fin n), v x = v x_1 → ¬x = x_1 → det (vandermonde v) = 0 State After: case mpr R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R i j : Fin n h₁ : v i = v j h₂ : ¬i = j k : Fin n ⊢ vandermonde v i k = vandermonde v j k Tactic: refine' fun i j h₁ h₂ => Matrix.det_zero_of_row_eq h₂ (funext fun k => _) State Before: case mpr R : Type u_1 inst✝¹ : CommRing R inst✝ : IsDomain R n : ℕ v : Fin n → R i j : Fin n h₁ : v i = v j h₂ : ¬i = j k : Fin n ⊢ vandermonde v i k = vandermonde v j k State After: no goals Tactic: rw [vandermonde_apply, vandermonde_apply, h₁]
[STATEMENT] lemma join_table: "table n A X \<Longrightarrow> table n B Y \<Longrightarrow> (\<not> b \<Longrightarrow> B \<subseteq> A) \<Longrightarrow> A \<union> B = C \<Longrightarrow> table n C (join X b Y)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>table n A X; table n B Y; \<not> b \<Longrightarrow> B \<subseteq> A; A \<union> B = C\<rbrakk> \<Longrightarrow> table n C (join X b Y) [PROOF STEP] unfolding table_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>Ball X (wf_tuple n A); Ball Y (wf_tuple n B); \<not> b \<Longrightarrow> B \<subseteq> A; A \<union> B = C\<rbrakk> \<Longrightarrow> Ball (join X b Y) (wf_tuple n C) [PROOF STEP] by (auto elim!: join_wf_tuple)
program test_fluid use fluid implicit none ! Fluid solver class. type(FluidSlv) :: FldSlv2D, FldSlv3D ! Names of variables. character(len=:), dimension(:), allocatable :: names2D, names3D ! Dimensions of the simulation domains. integer :: whd2D(2), whd3D(3) ! Simulation parameters. real(dp) :: scale, safety ! Density. real(dp) :: rho, timestep ! Add in flow coordinates. type(Vec2D2) :: xi2D real(dp) :: initial_cond(3) ! Time real(dp) :: t ! Timers integer :: startvalues(8), endvalues(8), startcount, endcount real(4) :: countrate ! Counter integer :: i, j ! Arrays real(dp), allocatable :: u(:,:), prhs(:) real(dp) :: celsiz ! Initialise names. allocate(character(len=8) :: names2D(4)) ! Test 2D.1: Initialise Fluid. ! Safety factor. safety = 1._dp ! Grid scale. scale = 1._dp ! 3x3 2D grid with sides of length 3 (each box is of size 1x1). whd2D = 3 ! Density. rho = 0.1_dp ! Initial timestep. timestep = 0.005 ! Names names2D(1)(:) = "Density." names2D(2)(:) = "Vx." names2D(3)(:) = "Vy." call FldSlv2D % Init(names2D, whd2D, rho, timestep, scale, safety) print*, " rho % name = ", FldSlv2D % rho % name, & new_line(" "), " Expected rho % name = ", names2D(1)(1:len(names2D(1))) print*, " u(1) % name = ", FldSlv2D % u(1) % name, & new_line(" "), " Expected u(1) % name = ", names2D(2)(1:len(names2D(2))) print*, " u(2) % name = ", FldSlv2D % u(2) % name, & new_line(" "), " Expected u(2) % name = ", names2D(3)(1:len(names2D(3))) print*, " Box Width = ", FldSlv2D % whd(1), & new_line(" "), " Expected width = ", whd2D(1) print*, " Box Height = ", FldSlv2D % whd(2), & new_line(" "), " Expected height = ", whd2D(2) print*, " Density = ", FldSlv2D % srho, & new_line(" "), " Expected Density = ", rho print*, " Cell size = ", FldSlv2D % celsiz, & new_line(" "), " Expected Cell size = ", scale/minval(whd2D) print*, " Safety factor = ", FldSlv2D % safety, & new_line(" "), " Expected Safety factor = ", safety print*, new_line(new_line(" ")), " FldSlv2D % prhs = ", FldSlv2D % prhs, & new_line(new_line(" ")), " Expected FldSlv2D % prhs = ", [(real(i)*0._dp, i = 1, product(whd2D))] print*, new_line(new_line(" ")), " FldSlv2D % p = ", FldSlv2D % prhs, & new_line(new_line(" ")), " Expected FldSlv2D % p = ", [(real(i)*0._dp, i = 1, product(whd2D))] print*, new_line(new_line(" ")), " FldSlv2D % u(1) % old = ", FldSlv2D % u(1) % old, & new_line(new_line(" ")), " Expected FldSlv2D % u(1) % old = ", [(real(i)*0._dp, i = 1, (whd2D(1) + 1)*whd2D(2))] print*, new_line(new_line(" ")), " FldSlv2D % u(1) % new = ", FldSlv2D % u(1) % new, & new_line(new_line(" ")), " Expected FldSlv2D % u(1) % new = ", [(real(i)*0._dp, i = 1, (whd2D(1) + 1)*whd2D(2))] print*, " Size(FldSlv2D % u(1) % old) = ", size(FldSlv2D % u(1) % old), & new_line(" "), " Expected Size(FldSlv2D % u(1) % old) = ", (whd2D(1) + 1)*whd2D(2) print*, " Size(FldSlv2D % u(1) % new) = ", size(FldSlv2D % u(1) % new), & new_line(" "), " Expected Size(FldSlv2D % u(1) % new) = ", (whd2D(1) + 1)*whd2D(2) print*, " FldSlv2D % u(1) % ost = ", FldSlv2D % u(1) % ost, & new_line(" "), " Expected FldSlv2D % u(1) % ost = ", [0._dp, 0.5_dp] print*, " FldSlv2D % u(1) % whd = ", FldSlv2D % u(1) % whd, & new_line(" "), " Expected FldSlv2D % u(1) % whd = ", [whd2D(1) + 1, whd2D(2)] print*, " FldSlv2D % u(1) % celsiz = ", FldSlv2D % u(1) % celsiz, & new_line(" "), " Expected FldSlv2D % u(1) % celsiz = ", scale/minval(whd2D) print*, new_line(new_line(" ")), " FldSlv2D % u(2) % old = ", FldSlv2D % u(2) % old, & new_line(new_line(" ")), " Expected FldSlv2D % u(2) % old = ", [(real(i)*0._dp, i = 1, (whd2D(2) + 1)*whd2D(1))] print*, new_line(new_line(" ")), " FldSlv2D % u(2) % new = ", FldSlv2D % u(2) % new, & new_line(new_line(" ")), " Expected FldSlv2D % u(2) % new = ", [(real(i)*0._dp, i = 1, (whd2D(2) + 1)*whd2D(1))] print*, " Size(FldSlv2D % u(2) % old) = ", size(FldSlv2D % u(2) % old), & new_line(" "), " Expected Size(FldSlv2D % u(2) % old) = ", (whd2D(2) + 1)*whd2D(1) print*, " Size(FldSlv2D % u(2) % new) = ", size(FldSlv2D % u(2) % new), & new_line(" "), " Expected Size(FldSlv2D % u(2) % new) = ", (whd2D(2) + 1)*whd2D(2) print*, " FldSlv2D % u(2) % ost = ", FldSlv2D % u(2) % ost, & new_line(" "), " Expected FldSlv2D % u(2) % ost = ", [0.5_dp, 0._dp] print*, " FldSlv2D % u(2) % whd = ", FldSlv2D % u(2) % whd, & new_line(" "), " Expected FldSlv2D % u(2) % whd = ", [whd2D(1), whd2D(2) + 1] print*, " FldSlv2D % u(2) % celsiz = ", FldSlv2D % u(2) % celsiz, & new_line(" "), " Expected FldSlv2D % celsiz = ", scale/minval(whd2D) print*, new_line(new_line(" ")), " FldSlv2D % rho % new = ", FldSlv2D % rho % new, & new_line(new_line(" ")), " Expected FldSlv2D % rho % new = ", [(real(i)*0._dp, i = 1, product(whd2D))] print*, " Size(FldSlv2D % rho % old) = ", size(FldSlv2D % rho % old), & new_line(" "), " Expected Size(FldSlv2D % rho % old) = ", product(whd2D) print*, " Size(FldSlv2D % rho % new) = ", size(FldSlv2D % rho % new), & new_line(" "), " Expected Size(FldSlv2D % rho % new) = ", product(whd2D) print*, " FldSlv2D % rho % ost = ", FldSlv2D % rho % ost, & new_line(" "), " Expected FldSlv2D % rho % ost = ", [0.5_dp, 0.5_dp] print*, " FldSlv2D % rho % whd = ", FldSlv2D % rho % whd, & new_line(" "), " Expected FldSlv2D % rho % whd = ", [whd2D(1), whd2D(2)] print*, " FldSlv2D % rho % celsiz = ", FldSlv2D % rho % celsiz, & new_line(" "), " Expected FldSlv2D % rho % celsiz = ", scale/minval(whd2D), new_line(new_line(" ")) xi2D % x = [0._dp, 1._dp, 0._dp, 1._dp] initial_cond = [1.0_dp, 2.0_dp, 3.0_dp] CALL SYSTEM_CLOCK(startcount, countrate) do i = 1, 1 call FldSlv2D % AddFlow(xi2D, initial_cond) end do CALL SYSTEM_CLOCK(endcount, countrate) print*, "ADDFLOW: It took me", endcount - startcount, "clicks (", (endcount - startcount)/countrate*1000," ms)" print*, new_line(new_line(" ")), "FldSlv2D % rho % old = ", new_line(" "), FldSlv2D % rho % old print*, new_line(new_line(" ")), "FldSlv2D % u(1) % old = ", new_line(" "), FldSlv2D % u(1) % old print*, new_line(new_line(" ")), "FldSlv2D % u(2) % old = ", new_line(" "), FldSlv2D % u(2) % old, new_line(new_line(" ")) t = 0._dp CALL SYSTEM_CLOCK(startcount, countrate) do i = 1, 1 call FldSlv2D % MaxTimeStep2D(t) end do CALL SYSTEM_CLOCK(endcount, countrate) print*, "MAXTIMESTEP: It took me", endcount - startcount, "clicks (", (endcount - startcount)/countrate*1000," ms)" print*, new_line(new_line(" ")), FldSlv2D % TimeStep CALL SYSTEM_CLOCK(startcount, countrate) do i = 1, 1 call FldSlv2D % BuildRhs2D() end do CALL SYSTEM_CLOCK(endcount, countrate) print*, "BUILDRHS: It took me", endcount - startcount, "clicks (", (endcount - startcount)/countrate*1000," ms)" print*, new_line(new_line(" ")), " FldSlv2D % prhs = ", FldSlv2D % prhs CALL SYSTEM_CLOCK(startcount, countrate) call FldSlv2D % GSPSlv2D(60, 1d-5) CALL SYSTEM_CLOCK(endcount, countrate) !print*, endvalues - startvalues print*, "Gauss-Seidel: It took me", endcount - startcount, "clicks (", (endcount - startcount)/countrate*1000," ms)" call FldSlv2D % ApplyPressure2D() do j = 0, 2 do i = 0, 2 write(*,"(A,A,I2,A,I2,A,A,F5.3,A,F5.3,A)"), "(Vx(i,j), Vy(i,j) = ", "(", i,",", j, "), ", "(", FldSlv2D % u(1) % ReadVal(i,j)& ,", ", FldSlv2D % u(2) % ReadVal(i,j), ")" end do end do call FldSlv2D % rho % Advect2D(FluidQty2D([FldSlv2D % u]), FldSlv2D%timestep(1)) call FldSlv2D % u(1) % Advect2D(FluidQty2D([FldSlv2D % u]), FldSlv2D%timestep(1)) call FldSlv2D % u(2) % Advect2D(FluidQty2D([FldSlv2D % u]), FldSlv2D%timestep(1)) !do i = 0, 8 ! print*, FldSlv2D % rho % new(i) !end do end program test_fluid
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Continuous distributions} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame} \frametitle{Continuous distributions} \begin{itemize} \item Below is a histogram of the distribution of heights of US adults. \item The proportion of data that falls in the shaded bins gives the probability that a randomly sampled US adult is between 180 cm and 185 cm (about 5'11" to 6'1"). \end{itemize} \begin{center} \includegraphics[width=\textwidth]{3-5_continuous_distributions/figures/usHeightsHist180185/usHeightsHist180185} \end{center} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \subsection{From histograms to continuous distributions} \begin{frame} \frametitle{From histograms to continuous distributions} Since height is a continuous numerical variable, its \hl{probability density function} is a smooth curve. \begin{center} \includegraphics[width=\textwidth]{3-5_continuous_distributions/figures/fdicHeightContDist/fdicHeightContDist} \end{center} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \subsection{Probabilities from continuous distributions} \begin{frame} \frametitle{Probabilities from continuous distributions} Therefore, the probability that a randomly sampled US adult is between 180 cm and 185 cm can also be estimated as the shaded area under the curve. \begin{center} \includegraphics[width=\textwidth]{3-5_continuous_distributions/figures/fdicHeightContDistFilled/fdicHeightContDistFilled} \end{center} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame} \frametitle{By definition...} Since continuous probabilities are estimated as ``the area under the curve", the probability of a person being exactly 180 cm (or any exact value) is defined as 0. \begin{center} \includegraphics[width=0.8\textwidth]{3-5_continuous_distributions/figures/fdicHeightContDist180} \end{center} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import tactic.basic import logic.function.basic /-! # Extra facts about `prod` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines `prod.swap : α × β → β × α` and proves various simple lemmas about `prod`. -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} @[simp] namespace prod @[simp] theorem «forall» {p : α × β → Prop} : (∀ x, p x) ↔ (∀ a b, p (a, b)) := ⟨assume h a b, h (a, b), assume h ⟨a, b⟩, h a b⟩ @[simp] theorem «exists» {p : α × β → Prop} : (∃ x, p x) ↔ (∃ a b, p (a, b)) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ theorem forall' {p : α → β → Prop} : (∀ x : α × β, p x.1 x.2) ↔ ∀ a b, p a b := prod.forall theorem exists' {p : α → β → Prop} : (∃ x : α × β, p x.1 x.2) ↔ ∃ a b, p a b := prod.exists @[simp] lemma snd_comp_mk (x : α) : prod.snd ∘ (prod.mk x : β → α × β) = id := rfl @[simp] lemma fst_comp_mk (x : α) : prod.fst ∘ (prod.mk x : β → α × β) = function.const β x := rfl @[simp] lemma map_mk (f : α → γ) (g : β → δ) (a : α) (b : β) : map f g (a, b) = (f a, g b) := rfl lemma map_fst (f : α → γ) (g : β → δ) (p : α × β) : (map f g p).1 = f (p.1) := rfl lemma map_snd (f : α → γ) (g : β → δ) (p : α × β) : (map f g p).2 = g (p.2) := rfl lemma map_fst' (f : α → γ) (g : β → δ) : (prod.fst ∘ map f g) = f ∘ prod.fst := funext $ map_fst f g lemma map_snd' (f : α → γ) (g : β → δ) : (prod.snd ∘ map f g) = g ∘ prod.snd := funext $ map_snd f g /-- Composing a `prod.map` with another `prod.map` is equal to a single `prod.map` of composed functions. -/ lemma map_comp_map {ε ζ : Type*} (f : α → β) (f' : γ → δ) (g : β → ε) (g' : δ → ζ) : prod.map g g' ∘ prod.map f f' = prod.map (g ∘ f) (g' ∘ f') := rfl /-- Composing a `prod.map` with another `prod.map` is equal to a single `prod.map` of composed functions, fully applied. -/ lemma map_map {ε ζ : Type*} (f : α → β) (f' : γ → δ) (g : β → ε) (g' : δ → ζ) (x : α × γ) : prod.map g g' (prod.map f f' x) = prod.map (g ∘ f) (g' ∘ f') x := rfl variables {a a₁ a₂ : α} {b b₁ b₂ : β} @[simp] lemma mk.inj_iff : (a₁, b₁) = (a₂, b₂) ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨prod.mk.inj, by cc⟩ lemma mk.inj_left {α β : Type*} (a : α) : function.injective (prod.mk a : β → α × β) := by { intros b₁ b₂ h, simpa only [true_and, prod.mk.inj_iff, eq_self_iff_true] using h } lemma mk.inj_right {α β : Type*} (b : β) : function.injective (λ a, prod.mk a b : α → α × β) := by { intros b₁ b₂ h, by simpa only [and_true, eq_self_iff_true, mk.inj_iff] using h } lemma mk_inj_left : (a, b₁) = (a, b₂) ↔ b₁ = b₂ := (mk.inj_left _).eq_iff lemma mk_inj_right : (a₁, b) = (a₂, b) ↔ a₁ = a₂ := (mk.inj_right _).eq_iff lemma ext_iff {p q : α × β} : p = q ↔ p.1 = q.1 ∧ p.2 = q.2 := by rw [← @mk.eta _ _ p, ← @mk.eta _ _ q, mk.inj_iff] @[ext] lemma ext {α β} {p q : α × β} (h₁ : p.1 = q.1) (h₂ : p.2 = q.2) : p = q := ext_iff.2 ⟨h₁, h₂⟩ lemma map_def {f : α → γ} {g : β → δ} : prod.map f g = λ (p : α × β), (f p.1, g p.2) := funext (λ p, ext (map_fst f g p) (map_snd f g p)) lemma id_prod : (λ (p : α × β), (p.1, p.2)) = id := funext $ λ ⟨a, b⟩, rfl lemma map_id : (prod.map (@id α) (@id β)) = id := id_prod lemma fst_surjective [h : nonempty β] : function.surjective (@fst α β) := λ x, h.elim $ λ y, ⟨⟨x, y⟩, rfl⟩ lemma snd_surjective [h : nonempty α] : function.surjective (@snd α β) := λ y, h.elim $ λ x, ⟨⟨x, y⟩, rfl⟩ lemma fst_injective [subsingleton β] : function.injective (@fst α β) := λ x y h, ext h (subsingleton.elim _ _) lemma snd_injective [subsingleton α] : function.injective (@snd α β) := λ x y h, ext (subsingleton.elim _ _) h /-- Swap the factors of a product. `swap (a, b) = (b, a)` -/ def swap : α × β → β × α := λp, (p.2, p.1) @[simp] lemma swap_swap : ∀ x : α × β, swap (swap x) = x | ⟨a, b⟩ := rfl @[simp] lemma fst_swap {p : α × β} : (swap p).1 = p.2 := rfl @[simp] lemma snd_swap {p : α × β} : (swap p).2 = p.1 := rfl @[simp] lemma swap_prod_mk {a : α} {b : β} : swap (a, b) = (b, a) := rfl @[simp] lemma swap_swap_eq : swap ∘ swap = @id (α × β) := funext swap_swap @[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap := swap_swap @[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap := swap_swap lemma swap_injective : function.injective (@swap α β) := swap_left_inverse.injective lemma swap_surjective : function.surjective (@swap α β) := swap_left_inverse.surjective lemma swap_bijective : function.bijective (@swap α β) := ⟨swap_injective, swap_surjective⟩ @[simp] lemma swap_inj {p q : α × β} : swap p = swap q ↔ p = q := swap_injective.eq_iff lemma eq_iff_fst_eq_snd_eq : ∀{p q : α × β}, p = q ↔ (p.1 = q.1 ∧ p.2 = q.2) | ⟨p₁, p₂⟩ ⟨q₁, q₂⟩ := by simp lemma fst_eq_iff : ∀ {p : α × β} {x : α}, p.1 = x ↔ p = (x, p.2) | ⟨a, b⟩ x := by simp lemma snd_eq_iff : ∀ {p : α × β} {x : β}, p.2 = x ↔ p = (p.1, x) | ⟨a, b⟩ x := by simp variables {r : α → α → Prop} {s : β → β → Prop} {x y : α × β} theorem lex_def (r : α → α → Prop) (s : β → β → Prop) {p q : α × β} : prod.lex r s p q ↔ r p.1 q.1 ∨ p.1 = q.1 ∧ s p.2 q.2 := ⟨λ h, by cases h; simp *, λ h, match p, q, h with | (a, b), (c, d), or.inl h := lex.left _ _ h | (a, b), (c, d), or.inr ⟨e, h⟩ := by change a = c at e; subst e; exact lex.right _ h end⟩ lemma lex_iff : lex r s x y ↔ r x.1 y.1 ∨ x.1 = y.1 ∧ s x.2 y.2 := lex_def _ _ instance lex.decidable [decidable_eq α] (r : α → α → Prop) (s : β → β → Prop) [decidable_rel r] [decidable_rel s] : decidable_rel (prod.lex r s) := λ p q, decidable_of_decidable_of_iff (by apply_instance) (lex_def r s).symm @[refl] lemma lex.refl_left (r : α → α → Prop) (s : β → β → Prop) [is_refl α r] : ∀ x, prod.lex r s x x | (x₁, x₂) := lex.left _ _ (refl _) instance is_refl_left {r : α → α → Prop} {s : β → β → Prop} [is_refl α r] : is_refl (α × β) (lex r s) := ⟨lex.refl_left _ _⟩ @[refl] lemma lex.refl_right (r : α → α → Prop) (s : β → β → Prop) [is_refl β s] : ∀ x, prod.lex r s x x | (x₁, x₂) := lex.right _ (refl _) instance is_refl_right {r : α → α → Prop} {s : β → β → Prop} [is_refl β s] : is_refl (α × β) (lex r s) := ⟨lex.refl_right _ _⟩ instance is_irrefl [is_irrefl α r] [is_irrefl β s] : is_irrefl (α × β) (lex r s) := ⟨by rintro ⟨i, a⟩ (⟨_, _, h⟩ | ⟨_, h⟩); exact irrefl _ h⟩ @[trans] lemma lex.trans {r : α → α → Prop} {s : β → β → Prop} [is_trans α r] [is_trans β s] : ∀ {x y z : α × β}, prod.lex r s x y → prod.lex r s y z → prod.lex r s x z | (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.left _ _ hxy₁) (lex.left _ _ hyz₁) := lex.left _ _ (trans hxy₁ hyz₁) | (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.left _ _ hxy₁) (lex.right _ hyz₂) := lex.left _ _ hxy₁ | (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.right _ _) (lex.left _ _ hyz₁) := lex.left _ _ hyz₁ | (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.right _ hxy₂) (lex.right _ hyz₂) := lex.right _ (trans hxy₂ hyz₂) instance {r : α → α → Prop} {s : β → β → Prop} [is_trans α r] [is_trans β s] : is_trans (α × β) (lex r s) := ⟨λ _ _ _, lex.trans⟩ instance {r : α → α → Prop} {s : β → β → Prop} [is_strict_order α r] [is_antisymm β s] : is_antisymm (α × β) (lex r s) := ⟨λ x₁ x₂ h₁₂ h₂₁, match x₁, x₂, h₁₂, h₂₁ with | (a₁, b₁), (a₂, b₂), lex.left _ _ hr₁, lex.left _ _ hr₂ := (irrefl a₁ (trans hr₁ hr₂)).elim | (a₁, b₁), (a₂, b₂), lex.left _ _ hr₁, lex.right _ _ := (irrefl _ hr₁).elim | (a₁, b₁), (a₂, b₂), lex.right _ _, lex.left _ _ hr₂ := (irrefl _ hr₂).elim | (a₁, b₁), (a₂, b₂), lex.right _ hs₁, lex.right _ hs₂ := antisymm hs₁ hs₂ ▸ rfl end⟩ instance is_total_left {r : α → α → Prop} {s : β → β → Prop} [is_total α r] : is_total (α × β) (lex r s) := ⟨λ ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, (is_total.total a₁ a₂).imp (lex.left _ _) (lex.left _ _)⟩ instance is_total_right {r : α → α → Prop} {s : β → β → Prop} [is_trichotomous α r] [is_total β s] : is_total (α × β) (lex r s) := ⟨λ ⟨i, a⟩ ⟨j, b⟩, begin obtain hij | rfl | hji := trichotomous_of r i j, { exact or.inl (lex.left _ _ hij) }, { exact (total_of (s) a b).imp (lex.right _) (lex.right _), }, { exact or.inr (lex.left _ _ hji) } end⟩ instance is_trichotomous [is_trichotomous α r] [is_trichotomous β s] : is_trichotomous (α × β) (lex r s) := ⟨λ ⟨i, a⟩ ⟨j, b⟩, begin obtain hij | rfl | hji := trichotomous_of r i j, { exact or.inl (lex.left _ _ hij) }, { exact (trichotomous_of s a b).imp3 (lex.right _) (congr_arg _) (lex.right _) }, { exact or.inr (or.inr $ lex.left _ _ hji) } end⟩ end prod open prod namespace function variables {f : α → γ} {g : β → δ} {f₁ : α → β} {g₁ : γ → δ} {f₂ : β → α} {g₂ : δ → γ} lemma injective.prod_map (hf : injective f) (hg : injective g) : injective (map f g) := λ x y h, ext (hf (ext_iff.1 h).1) (hg $ (ext_iff.1 h).2) lemma surjective.prod_map (hf : surjective f) (hg : surjective g) : surjective (map f g) := λ p, let ⟨x, hx⟩ := hf p.1 in let ⟨y, hy⟩ := hg p.2 in ⟨(x, y), prod.ext hx hy⟩ lemma bijective.prod_map (hf : bijective f) (hg : bijective g) : bijective (map f g) := ⟨hf.1.prod_map hg.1, hf.2.prod_map hg.2⟩ lemma left_inverse.prod_map (hf : left_inverse f₁ f₂) (hg : left_inverse g₁ g₂) : left_inverse (map f₁ g₁) (map f₂ g₂) := λ a, by rw [prod.map_map, hf.comp_eq_id, hg.comp_eq_id, map_id, id] lemma right_inverse.prod_map : right_inverse f₁ f₂ → right_inverse g₁ g₂ → right_inverse (map f₁ g₁) (map f₂ g₂) := left_inverse.prod_map lemma involutive.prod_map {f : α → α} {g : β → β} : involutive f → involutive g → involutive (map f g) := left_inverse.prod_map end function namespace prod open function @[simp] lemma map_injective [nonempty α] [nonempty β] {f : α → γ} {g : β → δ} : injective (map f g) ↔ injective f ∧ injective g := ⟨λ h, ⟨λ a₁ a₂ ha, begin inhabit β, injection @h (a₁, default) (a₂, default) (congr_arg (λ c : γ, prod.mk c (g default)) ha : _), end, λ b₁ b₂ hb, begin inhabit α, injection @h (default, b₁) (default, b₂) (congr_arg (prod.mk (f default)) hb : _), end⟩, λ h, h.1.prod_map h.2⟩ @[simp] lemma map_surjective [nonempty γ] [nonempty δ] {f : α → γ} {g : β → δ} : surjective (map f g) ↔ surjective f ∧ surjective g := ⟨λ h, ⟨λ c, begin inhabit δ, obtain ⟨⟨a, b⟩, h⟩ := h (c, default), exact ⟨a, congr_arg prod.fst h⟩, end, λ d, begin inhabit γ, obtain ⟨⟨a, b⟩, h⟩ := h (default, d), exact ⟨b, congr_arg prod.snd h⟩, end⟩, λ h, h.1.prod_map h.2⟩ @[simp] lemma map_bijective [nonempty α] [nonempty β] {f : α → γ} {g : β → δ} : bijective (map f g) ↔ bijective f ∧ bijective g := begin haveI := nonempty.map f ‹_›, haveI := nonempty.map g ‹_›, exact (map_injective.and map_surjective).trans (and_and_and_comm _ _ _ _) end @[simp] lemma map_left_inverse [nonempty β] [nonempty δ] {f₁ : α → β} {g₁ : γ → δ} {f₂ : β → α} {g₂ : δ → γ} : left_inverse (map f₁ g₁) (map f₂ g₂) ↔ left_inverse f₁ f₂ ∧ left_inverse g₁ g₂ := ⟨λ h, ⟨λ b, begin inhabit δ, exact congr_arg prod.fst (h (b, default)), end, λ d, begin inhabit β, exact congr_arg prod.snd (h (default, d)), end⟩, λ h, h.1.prod_map h.2⟩ @[simp] lemma map_right_inverse [nonempty α] [nonempty γ] {f₁ : α → β} {g₁ : γ → δ} {f₂ : β → α} {g₂ : δ → γ} : right_inverse (map f₁ g₁) (map f₂ g₂) ↔ right_inverse f₁ f₂ ∧ right_inverse g₁ g₂ := map_left_inverse @[simp] lemma map_involutive [nonempty α] [nonempty β] {f : α → α} {g : β → β} : involutive (map f g) ↔ involutive f ∧ involutive g := map_left_inverse end prod
function SDP = relax_category_registration(problem,varargin) %% Apply a sparse third-order relaxation to category registration %% Depending on multivariate polynomial package in SPOT %% Bounded translation is modelled as an inequality constraint, which leads %% to an extra PSD block in the semidefinite relaxation %% Heng Yang %% July 05, 2021 params = inputParser; params.CaseSensitive = false; params.addParameter('checkMonomials',true, @(x) islogical(x)); params.addParameter('lambda',0.1, @(x) isscalar(x)); params.parse(varargin{:}); checkMonomials = params.Results.checkMonomials; lambda = params.Results.lambda; fprintf('\n===================================================================') fprintf('\nApplying SDP relaxation to category registration problem') fprintf('\n===================================================================\n') t0 = tic; N = problem.N; K = problem.K; scene = problem.scene; shapes = problem.shapes; noiseBoundSq = problem.noiseBoundSq; tBound = problem.translationBound; tBoundSq = tBound^2; % t'*t <= tBoundSq cBoundSq = problem.cBound^2; % should just be 1 barc2 = 1.0; %% define POP variables nrPrimalVars = 9+3+K+N; % rotation: 9, translation: 3, binary: N, shape: K p = msspoly('p',nrPrimalVars); r = p(1:9); R = reshape(r,3,3); col1 = R(:,1); col2 = R(:,2); col3 = R(:,3); t = p(10:12); c = p(12+1:12+K); theta = p(12+K+1:nrPrimalVars); %% define cost function shape = combine_shapes(shapes,c); residuals = {}; for i = 1:N distance = scene(:,i) - R * shape(:,i) - t; residuals{end+1} = (distance' * distance) / noiseBoundSq; end f_cost = 0; for i = 1:N f_cost = f_cost + (1+theta(i))/2 * residuals{i} + (1-theta(i))/2 * barc2; end % add regularization on c f_cost = f_cost + lambda * (c'*c); %% define constraints h_r = [1.0-col1'*col1;... 1.0-col2'*col2;... 1.0-col3'*col3;... % column unit length col1'*col2;... col2'*col3;... col3'*col1;... % colums orthogonal cross(col1,col2) - col3;... cross(col2,col3) - col1;... cross(col3,col1) - col2]; % columns righthandedness % h_c = [sum(c) - 1.0]; h_theta = []; for i = 1:N h_theta =[h_theta; 1-theta(i)^2]; end g_t = tBoundSq - t'*t; % Translation bounded g_c = [cBoundSq - c'*c;c]; % nonnegative and bounded shape parameters %% Formulate the sparse third-order relaxation cr = mykron(c,r); x = [r;t]; basis_p = [1;x;c;cr;theta;mykron(theta,x);mykron(theta,cr)]; n = length(basis_p); basis_r = get_multiplier_basis(p,basis_p,h_r(1)); basis_theta = get_multiplier_basis(p,basis_p,h_theta(1)); % basis_c = get_multiplier_basis(p,basis_p,h_c(1)); basis_g_t = [1;theta]; basis_g_t_f = mykron(basis_g_t,basis_g_t); basis_g_c = [1;r]; basis_g_c_f = mykron(basis_g_c,basis_g_c); n1 = length(basis_g_t); n2 = length(basis_g_c); n1delta = triangle_number(n1); n2delta = triangle_number(n2); fprintf('Computing localizing and moment polynomials ...') time_start = tic; pop = [mykron(basis_r,h_r);... mykron(basis_theta,h_theta);... mykron(basis_p,basis_p);... f_cost;... mykron(g_t,basis_g_t_f);... mykron(g_c,basis_g_c_f)]; [~,degmat,coef_all] = decomp(pop); coef_all = coef_all'; time_prep = toc(time_start); fprintf(' Done in %g seconds.\n',time_prep); if checkMonomials fprintf('Checking consistency of monomials ...') time_check0 = tic; monomials_mom = mono(mykron(basis_p,basis_p)); fprintf(' %d ... %d ...',size(degmat,1),length(monomials_mom)); assert(size(degmat,1) == length(monomials_mom),'monomials not consistent'); time_check = toc(time_check0); fprintf('Done in %g seconds.\n',time_check); end dim_loc_eq = length(basis_r)*length(h_r)+length(basis_theta)*length(h_theta); dim_loc_ineq = length(g_t)*n1delta+length(g_c)*n2delta; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% generate standard SDP data from degmat and coefficients ndelta = triangle_number(n); nterms = size(degmat,1); m_mom = ndelta - nterms; m_loc = dim_loc_eq; m_loc_ineq = dim_loc_ineq; m = m_mom + m_loc + m_loc_ineq + 1; fprintf('SDP: n = %d, n1 = %d, m = %d, m_mom = %d, m_loc = %d, m_loc_ineq = %d, ndelta = %d.\n',... n,n1,m,m_mom,m_loc,m_loc_ineq,ndelta); coef_mom = coef_all(:,dim_loc_eq+1:dim_loc_eq+n^2); coef_mom = coef_mom'; B = {}; B_normalize = {}; A = {}; fprintf('Building B and A... Progress ') for i = 1:nterms if rem(i,10000) == 1 fprintf('%d/%d ',i,nterms); end [row,~,~] = find(coef_mom(:,i)); SDP_coli = floor((row-1)./n) + 1; SDP_rowi = mod(row-1,n) + 1; nnz = length(SDP_rowi); Bi = sparse(SDP_rowi,SDP_coli,ones(nnz,1),n,n); B{end+1} = Bi; B_normalize{end+1} = Bi/nnz; mask_triu = (SDP_rowi >= SDP_coli); si = SDP_rowi(mask_triu); sj = SDP_coli(mask_triu); nnz_triu = length(si); if nnz_triu > 1 [~,base_idx] = max(sj); si_base = si(base_idx); sj_base = sj(base_idx); si_nonbase = si; si_nonbase(base_idx)= []; sj_nonbase = sj; sj_nonbase(base_idx)= []; is_base_diag = (si_base == sj_base); if is_base_diag A_si = [si_base]; A_sj = [sj_base]; A_v = [1]; else A_si = [si_base,sj_base]; A_sj = [sj_base,si_base]; A_v = [0.5,0.5]; end for nonbase_idx = 1:length(si_nonbase) is_nonbase_diag = (si_nonbase(nonbase_idx) == sj_nonbase(nonbase_idx)); if is_nonbase_diag A_sii = [A_si,si_nonbase(nonbase_idx)]; A_sjj = [A_sj,sj_nonbase(nonbase_idx)]; A_vv = [A_v,-1]; else A_sii = [A_si,si_nonbase(nonbase_idx),sj_nonbase(nonbase_idx)]; A_sjj = [A_sj,sj_nonbase(nonbase_idx),si_nonbase(nonbase_idx)]; A_vv = [A_v,-0.5,-0.5]; end A_temp = sparse(A_sii,A_sjj,A_vv,n,n); A{end+1} = A_temp; end end end fprintf('Done.\n') assert(length(A) == m_mom,'length(A)+length(B) == ndelta!'); %% Now build A's associated with localizing constraints if dim_loc_eq == 0 % Do nothing A_local = {}; else coef_loc = coef_all(:,1:dim_loc_eq); A_local = {}; fprintf('Building localizing constraints A_local... Progress ') for i = 1:dim_loc_eq if rem(i,10000) == 1 fprintf('%d/%d ',i,m_loc); end [rowi,~,vi] = find(coef_loc(:,i)); Ai = sparse(n,n); for j = 1:length(rowi) Ai = Ai + vi(j) * B_normalize{rowi(j)}; end A_local{end+1} = Ai; end end fprintf('Done.\n') %% Leading A A0 = sparse([1],[1],[1],n,n); %% Combine all A for the main block A = [{A0},A_local,A]; %% Now build the cost matrix coef_cost = coef_all(:,dim_loc_eq+n^2+1); [row,~,v] = find(coef_cost); C = sparse(n,n); fprintf('Building cost matrix C... Progress ') for i = 1:length(row) if rem(i,1000) == 1 fprintf('%d/%d ',i,length(row)); end C = C + v(i) * B_normalize{row(i)}; end fprintf('Done.\n') %% Now build the sub PSD constraint g_t coef_ineq = coef_all(:,dim_loc_eq+n^2+1+1:dim_loc_eq+n^2+1+n1^2); % nterms by n1^2 A1 = {}; for ii = 1:n1^2 row = mod(ii-1,n1) + 1; col = floor((ii-1)./n1) + 1; if row < col % Do nothing for upper triangular parts else if row == col A1tmp = sparse([row],[col],[-1],n1,n1); else A1tmp = sparse([row,col],[col,row],[-0.5,-0.5],n1,n1); end [termIds,~,v] = find(coef_ineq(:,ii)); Atmp = sparse(n,n); for iii = 1:length(termIds) Atmp = Atmp + v(iii) * B_normalize{termIds(iii)}; end A{end+1} = Atmp; A1{end+1} = A1tmp; end end %% Now build the sub PSD constraint g_c (multiple of them) Ac = {}; for k = 1:length(g_c) idx = dim_loc_eq+n^2+1+n1^2+blkIndices(k,n2^2); coef_ineq = coef_all(:,idx); % nterms by n2^2 A2 = {}; for ii = 1:n2^2 row = mod(ii-1,n2) + 1; col = floor((ii-1)./n2) + 1; if row < col % Do nothing for upper triangular parts else if row == col A2tmp = sparse([row],[col],[-1],n2,n2); else A2tmp = sparse([row,col],[col,row],[-0.5,-0.5],n2,n2); end [termIds,~,v] = find(coef_ineq(:,ii)); Atmp = sparse(n,n); for iii = 1:length(termIds) Atmp = Atmp + v(iii) * B_normalize{termIds(iii)}; end A{end+1} = Atmp; A2{end+1} = A2tmp; end end Ac{end+1} = A2; end assert(length(A) == m,'Total number of equality constraints wrong.') count = length(A1); for k = 1:length(g_c) count = count + length(Ac{k}); end assert(count == m_loc_ineq,'Equality constraints from second PSD blk wrong') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% blk{1,1} = 's'; blk{1,2} = n; blk{2,1} = 's'; blk{2,2} = n1; for k = 1:length(g_c) blk{2+k,1} = 's'; blk{2+k,2} = n2; end b = sparse([1],[1],[1],m,1); %% svec in sdpt3 format and output standard data At0 = sparsesvec(blk(1,:),A); At1 = [sparse(n1delta,m-m_loc_ineq),... % moment and localizing sparsesvec(blk(2,:),A1),... % sub PSD t sparse(n1delta,length(g_c)*n2delta)]; % sub PSD c At = {At0;At1}; for k = 1:length(g_c) Atc = [sparse(n2delta,m-m_loc_ineq),... % moment and localizing sparse(n2delta,n1delta),... % sub PSD t sparse(n2delta,(k-1)*n2delta),... % sub PSD c sparsesvec(blk(2+k,:),Ac{k}),... % sub PSD k-th c sparse(n2delta,(length(g_c)-k)*n2delta)]; % sub PSD k-th c At = [At;{Atc}]; end C = {C;sparse(n1,n1)}; for k = 1:length(g_c) C = [C;{sparse(n2,n2)}]; end SDP.blk = blk; SDP.At = At; SDP.m = m; SDP.C = C; SDP.b = b; SDP.lam = lambda; SDP.M = 4+tBoundSq+cBoundSq+3*cBoundSq+N+(3+tBoundSq)*N+(3*cBoundSq)*N; tf = toc(t0); fprintf('\nDone in %g seconds.\n',tf); fprintf('===================================================================\n') end
\chapter*{Abstract} This thesis deals with the problem of generating test data for indoor localization and mapping systems using acoustic sources (speakers) and receivers (microphones) in a given environment. In particular methods of ray tracing and ultrasonic path evaluation will be explored and presented. The suggested methods have been implemented in an Acoustic Ray Tracing Simulator (ARTS). \newline ARTS is able to generate test sample data for a set of receivers by approximating the propagation of sound waves from acoustic sources as rays in a 3D modeled environment. The geometry of the environment is provided by 3D data from tools which support the Wavefront OBJ file format. Using this data and the geometric ray tracing method, reflections up to third order are being computed and sampled at the receivers end. The sampled data can then be used in localization or mapping systems to evaluate different environments and setups.
\section{Configuring a Neural Network} \coderef{Nn/NeuralNetwork.hh} Squirrel supports a variety of different neural network architectures, including CNNs and recurrent neural networks. In the following, details on configuring neural networks in Squirrel are provided. In order to set up a neural network, first its architecture needs to be defined. Therefore, two major components need to be specified: Connections and layers. Connections are initially just a list of names that are later filled with meaning. So, configuring a network with two layers requires to define the connections between the layers first: \begin{verbatim} [neural-network] connections = connection-0-1, connection-1-2 [neural-network.connection-0-1] from = network-input to = layer-1 type = weight-connection [neural-network.connection-1-2] from = layer-1 to = layer-2 type = weight-connection \end{verbatim} For each of the specified connections, the source and destination layer are specified, also by arbitrary names, here \texttt{layer-1} and \texttt{layer-2}. The first connection usually has the \texttt{network-input} as source and forwards it to the first layer. There are different types of connections (see below). The \texttt{weight-connection} simply multiplies a weight matrix to the input. The layer types still need to be added to the configuration: \begin{verbatim} [neural-network.layer-1] type = rectified number-of-units = 128 [neural-network.layer-2] type = softmax number-of-units = 10 \end{verbatim} A list of possible layers and their description can be found below. Be aware of the \texttt{connections} list as this specifies the topology of the network. Particularly when building network with recurrent skip connections, the order of the list is important. \subsection{Layer Types} \subsubsection*{Layer Base Class} \coderef{Nn/Layer.hh} All layers inherit from a base layer class. Parameters accessible for all layers are: \begin{itemize} \item \texttt{number-of-units} the number of units. Default is $ 0 $, mandatory to be specified unless the connection leading to the layer is a convolutional connection. \item \texttt{dropout-probability} amount of units that are randomly set to zero for dropout (default: 0.0). \item \texttt{use-bias} add a bias for this layer if true, else omit bias (default: true). \item \texttt{is-bias-trainable} bias is trained if true or left unchanged if false (default: true). \item \texttt{bias-initialization} Initialization if bias can not be loaded from file. Possible options: \texttt{random, zero} (default: \texttt{random}). \item \texttt{random-bias-min} and \texttt{random-bias-max} min and max value for the random (uniform) initialization (default: $ -0.1 $ and $ 0.1 $). \item \texttt{learning-rate-factor} train this layer stronger (factor $ > 1 $) or weaker (factor $ < 1 $) than other layers (default: 1.0). \end{itemize} \subsubsection*{Identity Layer} Does not change the layer units at all (apart from adding a bias if \texttt{use-bias} is true, which is done by all layers). \subsubsection*{Sigmoid Layer} \coderef{Nn/ActivationLayer.hh} Applies the sigmoid function $ \sigma(x) = \frac{1}{1+\exp(-x)} $ to each input unit. Use by setting \texttt{type = sigmoid}. \subsubsection*{Tanh Layer} \coderef{Nn/ActivationLayer.hh} Applies the $ \mathrm{tanh} $ to each input unit. Use by setting \texttt{type = tanh}. \subsubsection*{Rectified Layer} \coderef{Nn/ActivationLayer.hh} Applies the rectifier $ \mathrm{relu}(x) = \max(0, x) $ to each input unit. Use by setting \texttt{type = rectified}. \subsubsection*{Average-Pooling and Max-Pooling Layer} \coderef{Nn/MultiPortLayer.hh} Applies average-pooling/max-pooling the the input units. Usually used for CNNs. Use by setting \texttt{type = avg-pooling} or \texttt{type = max-pooling}. Parameters are \begin{itemize} \item \texttt{grid-size} the region to apply pooling to, \eg 3 for a $ 3 \times 3 $ grid. Default: 2. \item \texttt{stride} spatial stride of the pooling region. Default: 2. \end{itemize} \subsubsection*{Batch-Normalization Layer} \coderef{Nn/MultiPortLayer.hh} Applies batch normalization to the input units. Use by setting \texttt{type = batch-normalization}. Parameters are \begin{itemize} \item \texttt{is-spatial} apply batch normalization spatially if true, else apply batch normalization to each input unit. Default: true. \item \texttt{is-inference} use inference mode of batch-normalization (load mean and variance from file) if true, else use training mode (estimate running mean and variance) \end{itemize} \subsubsection*{Gated Recurrent Unit Layer} \coderef{Nn/MultiPortLayer.hh} Implementation of gated recurrent units. Use by setting \texttt{type = gated-recurrent-unit}. Note that this layer is inherently recurrent and does not need the specification of any recurrent connection (\ie a connection with same source and target layer). \subsubsection*{Softmax Layer} \coderef{Nn/ActivationLayer.hh} Applies the $ \mathrm{softmax} $ function to the input units. Although usually used as output layer, it can also be used as an internal layer in Squirrel. Use by setting \texttt{type = softmax}. \subsubsection*{Clipped Layer} \coderef{Nn/ActivationLayer.hh} A generalization of the rectified layer. Clips each input unit at a lower and upper bound. Use by setting \texttt{type = clipped}. Parameters are \begin{itemize} \item \texttt{left-threshold} lower bound for clipping (default: 0.0) \item \texttt{right-threshold} upper bound for clipping (default: 1.0) \end{itemize} If the lower bound is zero and the upper bound is infinity, the layer is a rectifier. \subsubsection*{L2-Normalization Layer} \coderef{Nn/ActivationLayer.hh} Applies $ \ell_2 $-normalization to the input, \ie divides each input unit by the $ \ell_2 $ norm of all input units. Use by setting \texttt{type = l2-normalization}. \subsubsection*{Power-Normalization Layer} \coderef{Nn/ActivationLayer.hh} Applies power-normalization to each input unit, \ie applies the function $ \mathrm{power}(x) = \mathrm{sign}(x) \cdot x^p $. Use by setting \texttt{type = power-normalization}. Set the value $ p $ using the parameter \texttt{power} (default: 0.5). \subsubsection*{Sequence length normalization layer} \coderef{Nn/ActivationLayer.hh} Only useful for recurrent networks. Divides the input units at the last timeframe of the sequence by the sequence length. Use by setting \texttt{type = sequence-length-normalization}. \subsubsection*{Temporal Reversion Layer} \coderef{Nn/ActivationLayer.hh} Only useful for recurrent networks. Reverts the temporal order of the input units. Can be used to define bi-directional recurrent networks. Use by setting \texttt{type = temporal-reversion}. \subsection{Connection Types} \subsubsection*{Connection Base Class} All connections inherit from a base connection class. Parameters accessible for all connections are \begin{itemize} \item \texttt{learning-rate-factor} train this connection stronger (factor $ > 1 $) or weaker (factor $ < 1 $) than other connections (default: 1.0). \item \texttt{is-recurrent} force the connection to be treated as recurrent even if it is configured as a standard forward from \texttt{layer-from} to \texttt{layer-to}. If true, the input to \texttt{layer-to} at time $ t $ is a linear transformation (matrix multiplicaiton or convolution) of the output of \texttt{layer-from} at time $ t - 1 $. If false, the input to \texttt{layer-to} at time $ t $ is a linear transformation (matrix multiplication or convolution) of the output of \texttt{layer-from} at time $ t $ (default: false). \end{itemize} \subsubsection*{Weight Connection} Causes the input of \texttt{layer-to} to be the output of \texttt{layer-from} multiplied by the connections weight matrix. Use by setting \texttt{type = weight-connection}. This type of connection is also used if no \texttt{type} value has been set. Parameters are \begin{itemize} \item \texttt{is-trainable} train the weights of this connection if true, else leave them unchanged during training (default: true) \item \texttt{weight-initialization} if the weights can not be loaded from a file, initialize them by one of these: \texttt{random, zero, identity, glorot}. \texttt{random} is a unifrom random initialization, \texttt{zero} initializes with zeros, \texttt{identity} initializes with the identity matrix (if matrix is not square, all remaining columns/rows are initialized with zeros), and \texttt{glorot} initializes based on a strategy proposed by Glorot et.\ al.\ (default: \texttt{random}) \item \texttt{random-weight-min} and \texttt{random-weight-max} the interval to uniformly sample values from in case of \texttt{random} initialization (default: $ -0.1 $ and $ 0.1 $). \end{itemize} \subsubsection*{Convolutional Connection} Causes the input of \texttt{layer-to} to be a convolution of the output of \texttt{layer-from} with the kernels of this connections. Use by setting \texttt{type = convolutional-connection}. Parameters are the same as for the weight connections plus \begin{itemize} \item \texttt{kernel-height} and \texttt{kernel-width} the height and width of the kernels (default: $ 3 $ for both) \item \texttt{dest-channels} the number of destination channels/feature maps (mandatory to be set) \item \texttt{stride-x} and \texttt{stride-y} the stride in $ x $- and $ y $-direction (default: $ 1 $ for both) \end{itemize} \subsubsection*{Plain Connection} Does not apply any linear transformation, \ie input of \texttt{layer-to} is equal to output of \texttt{layer-from}. Requires \texttt{layer-from} and \texttt{layer-to} to have the same number of units. \section{Training Neural Network} \coderef{examples/mnist/config/training.config} \subsection{General Settings} Neural network training requires some general settings. These are: \begin{itemize} \item \texttt{source-type} and \texttt{target-type}, \ie if they are single vectors/images/labels or sequences of vectors/images/labels. Use \texttt{single} for the first, \texttt{sequence} for the latter (default: \texttt{single}). \item \texttt{batch-size} the batch size to use (default: 1). \item \texttt{trainer} the kind of trainer to use (\texttt{feed-forward-trainer, rnn-trainer}). \item \texttt{training-criterion} the criterion to use for training, \eg \texttt{cross-entropy, squared-error}, see \textit{Nn/TrainingCriteria.hh} for more options. \end{itemize} \subsection{Loading Data} In order to provide data for the network, the \textit{Features} module is used. Provide the input and target data by specifying an \texttt{aligend-feature-reader}: \begin{verbatim} [features.aligned-feature-reader] feature-cache = <input feature file> target-cache = <target label/feature file> \end{verbatim} For details \eg on how to shuffle data, see Chapter~\ref{ch:features}. If you only want to forward data without using a target-cache, use the \texttt{feature-reader} instead of the \texttt{aligned-feature-reader}. As the network needs some information on the feature dimension, also specify the following parameters: \begin{verbatim} [neural-network] input-dimension = <input-feature-dimension> source-width = <width of input images/videos> source-height = <height of input images/videos> source-channels = <number of input channels (e.g. 3 for rgb, 1 for gray)> \end{verbatim} Note that the last three parameters are only required if the input is images or videos. \section{Further Configuration} We refer to the \texttt{config} files in the \texttt{examples} directory for more example configuration of both, CNNs and recurrent neural networks.
After moving to Tokyo , Oribe formed the band Love is Same All with members from the indie band Parking Out and began using the stage name LiSA , which is an acronym for Love is Same All . The band performs with LiSA during the latter 's solo live performances . In 2010 , she made her major debut singing songs for the anime series Angel Beats ! as one of two vocalists for the fictional in @-@ story band Girls Dead Monster . She was the vocalist for the character Yui , and the second vocalist , Marina , sang as the character Masami Iwasawa . LiSA put out three singles and one album in 2010 under the name Girls Dead Monster on Key 's record label Key Sounds Label . The first single " Thousand Enemies " was released on May 12 ; the second single " Little Braver " came out on June 9 ; and the third single " Ichiban no Takaramono ( Yui final ver . ) " ( <unk> 〜 Yui final ver . 〜 , " My Most Precious Treasure ( Yui final ver . ) " ) was sold on December 8 . The album Keep The Beats ! was released on June 30 . LiSA made her first appearance at Animelo Summer Live during the concert 's 2010 iteration on August 28 .
Cult of Weird probably isn’t the first site that comes to mind when searching for the latest haute couture, but if you’re looking for the season’s hottest swimwear, you’ve come to the right place. Fabiana LaFleur’s taxidermy frog bikini is a thing of beauty. We’ve all seen the fanciful taxidermy dioramas of frogs playing instruments or engaged in deadly duels, but this is by far the most unique use of dead frogs I’ve ever seen. No other swimsuit provides both dinner and high fashion. You might end up with some pretty strange tan lines, though. “I could go to the mall and get a suit but they don’t sell anything that turns heads like the one I’ve made,” Fabiana says. I would like to get in touch with Fabiana. I a Ron Savage from ‘The Ron Savage Show’ and Producer at WCBM.
theory "AList-Utils-Nominal" imports "AList-Utils" "Nominal-Utils" begin subsubsection {* Freshness lemmas related to associative lists *} lemma domA_not_fresh: "x \<in> domA \<Gamma> \<Longrightarrow> \<not>(atom x \<sharp> \<Gamma>)" by (induct \<Gamma>, auto simp add: fresh_Cons fresh_Pair) lemma fresh_delete: assumes "atom x \<sharp> \<Gamma>" shows "atom x \<sharp> (delete v \<Gamma>)" using assms by(induct \<Gamma>)(auto simp add: fresh_Cons) lemma fv_delete_subset: "fv (delete v \<Gamma>) \<subseteq> fv \<Gamma>" using fresh_delete unfolding fresh_def fv_def by auto lemma fresh_heap_expr: assumes "a \<sharp> \<Gamma>" and "(x,e) \<in> set \<Gamma>" shows "a \<sharp> e" using assms by (metis fresh_list_elem fresh_Pair) lemma fresh_heap_expr': assumes "a \<sharp> \<Gamma>" and "e \<in> snd ` set \<Gamma>" shows "a \<sharp> e" using assms by (induct \<Gamma>, auto simp add: fresh_Cons fresh_Pair) lemma fresh_star_heap_expr': assumes "S \<sharp>* \<Gamma>" and "e \<in> snd ` set \<Gamma>" shows "S \<sharp>* e" using assms by (metis fresh_star_def fresh_heap_expr') lemma fresh_map_of: assumes "x \<in> domA \<Gamma>" assumes "a \<sharp> \<Gamma>" shows "a \<sharp> the (map_of \<Gamma> x)" using assms by (induct \<Gamma>)(auto simp add: fresh_Cons fresh_Pair) lemma fresh_star_map_of: assumes "x \<in> domA \<Gamma>" assumes "a \<sharp>* \<Gamma>" shows "a \<sharp>* the (map_of \<Gamma> x)" using assms by (simp add: fresh_star_def fresh_map_of) lemma domA_fv_subset: "domA \<Gamma> \<subseteq> fv \<Gamma>" by (induction \<Gamma>) auto lemma map_of_fv_subset: "x \<in> domA \<Gamma> \<Longrightarrow> fv (the (map_of \<Gamma> x)) \<subseteq> fv \<Gamma>" by (induction \<Gamma>) auto subsubsection {* Equivariance lemmas *} lemma domA[eqvt]: "\<pi> \<bullet> domA \<Gamma> = domA (\<pi> \<bullet> \<Gamma>)" by (simp add: domA_def) subsubsection {* Freshness and distinctness *} subsubsection {* Pure codomains *} lemma domA_fv_pure: fixes \<Gamma> :: "('a::at_base \<times> 'b::pure) list" shows "fv \<Gamma> = domA \<Gamma>" apply (induct \<Gamma>) apply simp apply (case_tac a) apply (simp) done lemma domA_fresh_pure: fixes \<Gamma> :: "('a::at_base \<times> 'b::pure) list" shows "x \<in> domA \<Gamma> \<longleftrightarrow> \<not>(atom x \<sharp> \<Gamma>)" unfolding domA_fv_pure[symmetric] by (auto simp add: fv_def fresh_def) end
Acorn 2 is out and it’s getting very positive press. Unfortunately, much of it is from the usual suspects — i.e. folks who use their image editor for cropping and adding captions — so the question is, really is it any good? Acorn remains the cheapest of the credible Photoshop replacements at $50. (Upgrades from 1.x are $20. I just paid for mine.) And with Acorn’s free version, competing products that don’t offer significant levels of usability and functionality are pretty much screwed. Here’s an updated version of my giant table comparing the three main contenders. Significant changes are in bold. Excellent Core Image support Excellent Core Image support and some additional useful filters, such as Clouds. Comprehensive set of filters (including some marked improvements over Photoshop) but no Core Image support. Stuff that Core Image doesn’t give you like comprehensive noise reduction tools, and fractal clouds. Oh and you can create and reuse named presets for almost everything. Slicing support. Photoshop-style (but far simpler) web export dialog with file-size preview etc. Some random subset of Fireworks is implemented (slicing, button states, etc.). Not really sure how good or extensive it is (much more extensive than Pixelmator or Acorn) since I have no use for such stuff. Being able to use one layer as a mask for layers adjacent to it. It’s probably worth mentioning that all three of these programs have a lot of rough edges. Of the three, I’d have to say Photoline’s bugs get addressed the most quickly, while Pixelmator’s get addressed the most slowly. While writing this blog entry I encountered a half-dozen bugs in Acorn 2.1 and if I did not think they would be addressed in a reasonably timely manner I would not recommend Acorn to anyone (or pay for the upgrade). It’s a bit unfair to compare a major new version of Acorn with a couple of “bump” releases from its rivals. Acorn 2 has definitely moved from being an over-hyped toy to a genuinely useful piece of software which still launches in under a second. Meanwhile, Acorn’s free version is going to be painful for anyone else writing a thin wrapper around Core Image. The bottom line is that Pixelmator retains its edge as the best “painting” program, but Acorn has the edge for more professional use (e.g. all kinds of scripting and workflow animation options), while Photoline wins the “ugly but really powerful” prize. Photoshop Elements 6 for the Mac has shipped which means bad times for half-assed shareware products pretending to be cheap Photoshop replacements. It’s not that Elements is itself a Photoshop replacement, it’s just that it’s more of one than the half-assed wannabes. If you’ve been keeping score, the candidates are Pixelmator, Acorn, Iris, and Photoline. I’ve tried them all and the short version of my opinion is that Pixelmator is a pretty but ultimately useless piece of junk, Iris is an ugly, useless piece of junk, Acorn is a tidy, scriptable little app that works well but will almost certainly be missing some feature you need, and that Photoline is actually a credible replacement for Photoshop in a pinch, although it’s a bit ugly. I can’t stress enough how it fundamentally doesn’t matter what else a graphics program does, if you can’t select what you want, everything else is a waste of time. This is like trying to ship a word-processor with broken text selection*. Pixelmator and Acorn both have incredibly nice front ends for CoreImage. Just how much faster and more interactive these are than Photoshop’s filters is just breathtaking — I might be tempted to switch to Pixelmator just to use its zoom blur filter on the rare occasions I use zoom blur — but the sad thing is that Photoshop’s are good enough (as are Photoline’s) and unless you have no taste, filters are NOT the thing you spend most, or even a significant fraction, of your time in with an image editing application. One of the really nice things about good freeware and shareware is availability in a pinch. If I find myself needing to edit an image on some random computer, I can download Photoline, using the license stored in my gmail account, perform my edit, and then uninstall in a matter of minutes. Most shareware apps aren’t so large that downloading them is painful (Photoline for the Mac is ~20MB) while Photoshop Elements is a 1.25 GB download and involves product activation. Before Photoshop Elements came out only two of the wannabe apps could even begin to justify their existence. Acorn is scriptable, making it intrinsically useful for workflow automation in a way that Pixelmator and Iris can never be. Iris is simply a joke, while Pixelmator could be useful one day. Photoline is a useful Photoshop replacement in a pinch, and its capabilities complement Photoshop Elements’ capabilities since Photoshop Elements has features photographers will want, while Photoline fills the gaps if you don’t want or can’t afford Photoshop CS3. * Well, Microsoft does that and seems to make money. You cannot select parts of two different words in Microsoft Word. E.g. if you accidentally typed “teh rpoblem with Word” you can’t select the hilited text to fix it. Once a selection extends beyond one word, Word forces you to select entire words, leading to endless annoyance.
theory Individuals imports Common begin record 'i individual_structure = individuals :: "'i set" ("\<I>\<index>") inheres_in :: "'i \<Rightarrow> 'i \<Rightarrow> bool" (infix "\<triangleleft>\<index>" 75) exactly_similar_to :: "'i \<Rightarrow> 'i \<Rightarrow> bool" (infix "\<simeq>\<index>" 75) worlds :: "'i set set" ("\<W>\<index>") refers_to :: "'i \<Rightarrow> 'i \<Rightarrow> bool" (infix "\<hookrightarrow>\<index>" 75) lemma individual_structure_eqI: fixes A B :: "'i individual_structure" assumes "\<I>\<^bsub>A\<^esub> = \<I>\<^bsub>B\<^esub>" "(\<triangleleft>\<^bsub>A\<^esub>) = (\<triangleleft>\<^bsub>B\<^esub>)" "(\<simeq>\<^bsub>A\<^esub>) = (\<simeq>\<^bsub>B\<^esub>)" "\<W>\<^bsub>A\<^esub> = \<W>\<^bsub>B\<^esub>" "(\<hookrightarrow>\<^bsub>A\<^esub>) = (\<hookrightarrow>\<^bsub>B\<^esub>)" shows "A = B" using assms by auto definition substantials :: "'i individual_structure \<Rightarrow> 'i set" ("\<S>\<index>") where "\<S> \<equiv> { x . x \<in> \<I> \<and> (\<forall>y. \<not> x \<triangleleft> y) }" for IS :: "'i individual_structure" (structure) lemma substantialsI[intro!]: fixes IS :: "'i individual_structure" (structure) assumes "x \<in> \<I>" "\<And>y. \<not> x \<triangleleft> y" shows "x \<in> \<S>" using assms by (auto simp: substantials_def) lemma substantialsE[elim!]: fixes IS :: "'i individual_structure" (structure) assumes "x \<in> \<S>" obtains "x \<in> \<I>" "\<And>y. \<not> x \<triangleleft> y" using assms by (auto simp: substantials_def) definition moments :: "'i individual_structure \<Rightarrow> 'i set" ("\<M>\<index>") where "\<M> \<equiv> { x . x \<in> \<I> \<and> (\<exists>y. x \<triangleleft> y) }" for IS :: "'i individual_structure" (structure) definition bearer :: "'i individual_structure \<Rightarrow> 'i \<Rightarrow> 'i" ("\<beta>\<index>") where "\<beta> x \<equiv> if (\<exists>y. x \<triangleleft> y) then (THE y. x \<triangleleft> y) else undefined" for IS :: "'i individual_structure" (structure) definition existentially_dependent :: "'i individual_structure \<Rightarrow> 'i \<Rightarrow> 'i \<Rightarrow> bool" ("ed\<index>") where "ed x y \<equiv> x \<in> \<I> \<and> y \<in> \<I> \<and> (\<forall>w \<in> \<W>. x \<in> w \<longrightarrow> y \<in> w)" for IS :: "'i individual_structure" (structure) lemma ed_I[intro!]: "\<lbrakk> x \<in> \<I> ; y \<in> \<I> ; \<forall>w. w \<in> \<W> \<and> x \<in> w \<longrightarrow> y \<in> w \<rbrakk> \<Longrightarrow> ed x y" for IS (structure) by (auto simp: existentially_dependent_def) (* UNUSED lemma ed_I_1: "\<lbrakk> x \<in> \<I> ; y \<in> \<I> ; \<And>w. \<lbrakk> w \<in> \<W> ; x \<in> w \<rbrakk> \<Longrightarrow> y \<in> w \<rbrakk> \<Longrightarrow> ed x y" for IS (structure) by (auto) *) lemma ed_E[elim!]: "\<lbrakk> ed x y ; \<lbrakk> x \<in> \<I> ; y \<in> \<I> ; \<forall>w. w \<in> \<W> \<and> x \<in> w \<longrightarrow> y \<in> w \<rbrakk> \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" for IS (structure) by (auto simp: existentially_dependent_def) (* UNUSED lemma ed_E_1: "\<lbrakk> ed x y ; \<And>x y. \<lbrakk> x \<in> \<I> ; y \<in> \<I> ; \<And>w. \<lbrakk> w \<in> \<W> ; x \<in> w \<rbrakk> \<Longrightarrow> y \<in> w \<rbrakk> \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" for IS (structure) by (auto) *) (* UNUSED lemma ed_refl[intro!]: "x \<in> \<I> \<Longrightarrow> ed x x" for IS (structure) using ed_I by metis *) (* UNUSED lemma ed_trans[trans]: "\<lbrakk> ed x y ; ed y z \<rbrakk> \<Longrightarrow> ed x z" for IS (structure) by (auto simp: existentially_dependent_def) *) lemma moments_subset_individuals[simp,intro!]: "\<M> \<subseteq> \<I>" for IS :: "'i individual_structure" (structure) by (simp add: moments_def subset_eq) lemma substantials_subset_individuals[simp,intro!]: "\<S> \<subseteq> \<I>" for IS :: "'i individual_structure" (structure) by blast locale individual_structure_defs = fixes IS :: "'i individual_structure" (structure) begin end locale individual_structure = individual_structure_defs + assumes undefined_not_in_individuals[iff]: "undefined \<notin> \<I>" and inheres_in_scope: "x \<triangleleft> y \<Longrightarrow> x \<in> \<I> \<and> y \<in> \<I>" and inheres_in_sep: "x \<triangleleft> y \<Longrightarrow> \<not> y \<triangleleft> z" and inheres_in_single[dest]: "\<lbrakk> x \<triangleleft> y ; x \<triangleleft> z \<rbrakk> \<Longrightarrow> y = z" and exactly_similar_scope: "x \<simeq> y \<Longrightarrow> x \<in> \<M> \<and> y \<in> \<M>" and exactly_similar_refl[intro!]: "x \<in> \<M> \<Longrightarrow> x \<simeq> x" and exactly_similar_trans[trans]: "\<lbrakk> x \<simeq> y ; x \<simeq> z \<rbrakk> \<Longrightarrow> x \<simeq> z" and exactly_similar_sym[sym]: "x \<simeq> y \<Longrightarrow> y \<simeq> x" and empty_world[iff]: "{} \<in> \<W>" and worlds_are_made_of_individuals: "w \<in> \<W> \<Longrightarrow> w \<subseteq> \<I>" and every_individual_exists_somewhere: "x \<in> \<I> \<Longrightarrow> \<exists>w \<in> \<W>. x \<in> w" and inherence_imp_ed: "x \<triangleleft> y \<Longrightarrow> ed x y" and refers_to_scope: "x \<hookrightarrow> y \<Longrightarrow> x \<in> \<M> \<and> y \<in> \<S>" and refers_to_diff_bearer: "\<lbrakk> x \<hookrightarrow> y ; x \<triangleleft> z \<rbrakk> \<Longrightarrow> z \<noteq> y" and refers_to_imp_ed: "x \<hookrightarrow> y \<Longrightarrow> ed x y" (* and moment_uniqueness: "\<lbrakk> x \<triangleleft> z ; y \<triangleleft> z ; x \<simeq> y ; \<forall>s. x \<hookrightarrow> s \<longleftrightarrow> y \<hookrightarrow> s \<rbrakk> \<Longrightarrow> x = y" *) begin lemma momentsI[intro]: assumes "x \<triangleleft> y" shows "x \<in> \<M>" using assms inheres_in_scope by (auto simp: moments_def) lemma momentsE[elim]: assumes "x \<in> \<M>" obtains y where "x \<triangleleft> y" using assms by (auto simp: moments_def) lemma substantialsI2[intro]: assumes "x \<triangleleft> y" shows "y \<in> \<S>" using inheres_in_sep inheres_in_scope assms substantialsI by metis lemma individuals_moments_substantials: "\<I> = \<S> \<union> \<M>" using inheres_in_scope by (auto simp: substantials_def moments_def) lemma substantials_moments_disj: "\<S> \<inter> \<M> = {}" by (auto simp: substantials_def moments_def) (* UNUSED lemma substantials_eq_diff: "\<S> = \<I> - \<M>" using individuals_moments_substantials substantials_moments_disj by blast *) (* UNUSED lemma moments_eq_diff: "\<M> = \<I> - \<S>" using individuals_moments_substantials substantials_moments_disj by blast *) lemma individuals_cases[cases set]: assumes "x \<in> \<I>" obtains (substantial) "x \<in> \<S>" "x \<notin> \<M>" | (moment) "x \<in> \<M>" "x \<notin> \<S>" using assms individuals_moments_substantials substantials_moments_disj by blast lemma bearer_eq: assumes "x \<triangleleft> y" shows "\<beta> x = y" using assms inheres_in_single by (auto simp: bearer_def) lemma bearerI[intro]: assumes "x \<in> \<M>" "\<And>y. x \<triangleleft> y \<Longrightarrow> P y" shows "P (\<beta> x)" using assms apply (auto simp: bearer_def) using momentsE assms by (simp add: inheres_in_single the_equality) (* UNUSED lemma bearer_eqE: assumes "\<beta> x = y" obtains "x \<in> \<M> \<Longrightarrow> x \<triangleleft> y" using assms by blast *) lemma inheres_in_scope_2: assumes "x \<triangleleft> y" obtains "x \<in> \<M>" "y \<in> \<S>" using assms by (simp add: momentsI substantialsI2) lemma inheres_in_scope_D: assumes "x \<triangleleft> y" shows "x \<in> \<M>" "y \<in> \<S>" using assms by (auto elim!: inheres_in_scope_2) lemma inheres_in_out_scope: "x \<notin> \<M> \<Longrightarrow> \<not> x \<triangleleft> y" "x \<notin> \<S> \<Longrightarrow> \<not> y \<triangleleft> x" using inheres_in_scope_2 by metis+ lemma moments_are_individuals[dest]: "x \<in> \<M> \<Longrightarrow> x \<in> \<I>" by (meson moments_subset_individuals subset_iff) lemma substantials_are_individuals[dest]: "x \<in> \<S> \<Longrightarrow> x \<in> \<I>" by blast lemma substantials_moments_disj_2[dest]: "\<lbrakk> x \<in> \<M> ; x \<in> \<S> \<rbrakk> \<Longrightarrow> False" by blast lemma undefined_not_in_moments[iff]: "undefined \<notin> \<M>" by (meson moments_are_individuals undefined_not_in_individuals) lemma undefined_not_in_substantials[iff]: "undefined \<notin> \<S>" using undefined_not_in_individuals by blast lemma inheres_in_sep_2[dest]: "\<lbrakk> x \<triangleleft> y ; y \<triangleleft> z \<rbrakk> \<Longrightarrow> False" using inheres_in_sep by blast lemma exactly_similar_sym_iff[iff]: "x \<simeq> y \<longleftrightarrow> y \<simeq> x" using exactly_similar_sym by blast lemma individuals_iff: "x \<in> \<I> \<longleftrightarrow> (\<exists>w. w \<in> \<W> \<and> x \<in> w)" using worlds_are_made_of_individuals every_individual_exists_somewhere by (meson contra_subsetD) (* UNUSED lemma ed_intro_1: "x \<triangleleft> y \<or> x \<hookrightarrow> y \<Longrightarrow> ed x y" using inherence_imp_ed refers_to_imp_ed by metis *) lemma ed_scope: "ed x y \<Longrightarrow> x \<in> \<I> \<and> y \<in> \<I>" by blast lemma undefined_simps[iff]: "\<not> undefined \<triangleleft> x" "\<not> x \<triangleleft> undefined" "\<not> undefined \<simeq> x" "\<not> x \<simeq> undefined" "\<not> undefined \<hookrightarrow> x" "\<not> x \<hookrightarrow> undefined" "\<not> ed undefined x" "\<not> ed x undefined" using undefined_not_in_moments undefined_not_in_substantials undefined_not_in_individuals inheres_in_scope refers_to_scope exactly_similar_scope ed_scope by metis+ (* UNUSED lemma bearer_non_moment[simp,intro!]: "\<beta> x \<notin> \<M>" by (metis bearer_def bearer_eq inheres_in_sep momentsE undefined_not_in_moments) *) lemma bearer_ex1[dest]: assumes "w \<in> \<W>" "x \<in> w" "x \<triangleleft> y" shows "y \<in> w" using assms inherence_imp_ed ed_E by metis end end
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stddef.h> #include <unistd.h> #include <math.h> #include "bigfile-mpi.h" #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> void usage() { fprintf(stderr, "usage: bigfile-sample-mpi [-r ratio] [-N Nfile] [-f newfilepath] filepath block newblock\n"); exit(1); } #define DONE_TAG 1293 #define ERROR_TAG 1295 #define DIE_TAG 1290 #define WORK_TAG 1291 MPI_Datatype MPI_TYPE_WORK; BigFile bf = {0}; BigFile bfnew = {0}; BigBlock bb = {0}; BigBlock bbnew = {0}; int verbose = 0; int Nfile = -1; size_t CHUNKSIZE = 1 * 1024 * 1024; int ThisTask, NTask; char * newfilepath = NULL; void slave(void); void server(void); double ratio = 1.0; struct work { int64_t offset; int64_t seed; int64_t chunksize; int64_t offsetnew; int64_t nsel; }; static size_t filesize(); int main(int argc, char * argv[]) { MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &ThisTask); MPI_Comm_size(MPI_COMM_WORLD, &NTask); MPI_Type_contiguous(sizeof(struct work), MPI_BYTE, &MPI_TYPE_WORK); MPI_Type_commit(&MPI_TYPE_WORK); int ch; while(-1 != (ch = getopt(argc, argv, "n:N:vf:r:"))) { switch(ch) { case 'r': ratio = atof(optarg); break; case 'N': case 'n': Nfile = atoi(optarg); break; case 'f': newfilepath = optarg; break; case 'v': verbose = 1; break; default: usage(); } } if(argc - optind + 1 != 4) { usage(); } argv += optind - 1; if(0 != big_file_mpi_open(&bf, argv[1], MPI_COMM_WORLD)) { fprintf(stderr, "failed to open: %s\n", big_file_get_error_message()); exit(1); } if(0 != big_file_mpi_open_block(&bf, &bb, argv[2], MPI_COMM_WORLD)) { fprintf(stderr, "failed to open: %s\n", big_file_get_error_message()); exit(1); } if(Nfile == -1 || bb.Nfile == 0) { Nfile = bb.Nfile; } if(newfilepath == NULL) { newfilepath = argv[1]; } if(0 != big_file_mpi_create(&bfnew, newfilepath, MPI_COMM_WORLD)) { fprintf(stderr, "failed to open: %s\n", big_file_get_error_message()); exit(1); } size_t newsize = filesize(); if(0 != big_file_mpi_create_block(&bfnew, &bbnew, argv[3], bb.dtype, bb.nmemb, Nfile, newsize, MPI_COMM_WORLD)) { fprintf(stderr, "failed to create temp: %s\n", big_file_get_error_message()); exit(1); } /* copy attrs */ size_t nattr; BigAttr * attrs = big_block_list_attrs(&bb, &nattr); int i; for(i = 0; i < nattr; i ++) { BigAttr * attr = &attrs[i]; big_block_set_attr(&bbnew, attr->name, attr->data, attr->dtype, attr->nmemb); } if(bb.nmemb > 0 && bb.size > 0) { /* copy data */ if(ThisTask == 0) { server(); } else { slave(); } } if(0 != big_block_mpi_close(&bbnew, MPI_COMM_WORLD)) { fprintf(stderr, "failed to close new: %s\n", big_file_get_error_message()); exit(1); } big_block_mpi_close(&bb, MPI_COMM_WORLD); big_file_mpi_close(&bf, MPI_COMM_WORLD); big_file_mpi_close(&bfnew, MPI_COMM_WORLD); return 0; } static size_t filesize() { gsl_rng * rng = gsl_rng_alloc(gsl_rng_mt19937); gsl_rng_set(rng, 1984); int64_t offset = 0; int64_t offsetnew = 0; struct work work; for(offset = 0; offset < bb.size; ) { int64_t chunksize = CHUNKSIZE; /* never read beyond my end (read_simple caps at EOF) */ if(offset + chunksize >= bb.size) { /* this is the last chunk */ chunksize = bb.size - offset; } work.offset = offset; work.chunksize = chunksize; work.seed = gsl_rng_get(rng); work.offsetnew = offsetnew; if(ratio == 1.0) { work.nsel = chunksize; } else { work.nsel = gsl_ran_poisson(rng, chunksize * ratio); } offset += chunksize; offsetnew += work.nsel; } return offsetnew; } void server() { int64_t offset = 0; int64_t offsetnew = 0; struct work work; gsl_rng * rng = gsl_rng_alloc(gsl_rng_mt19937); gsl_rng_set(rng, 1984); for(offset = 0; offset < bb.size; ) { int64_t chunksize = CHUNKSIZE; MPI_Status status; int result = 0; MPI_Recv(&result, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); if(status.MPI_TAG == ERROR_TAG) { break; } /* never read beyond my end (read_simple caps at EOF) */ if(offset + chunksize >= bb.size) { /* this is the last chunk */ chunksize = bb.size - offset; } work.offset = offset; work.chunksize = chunksize; work.seed = gsl_rng_get(rng); work.offsetnew = offsetnew; if(ratio == 1.0) { work.nsel = chunksize; } else { work.nsel = gsl_ran_poisson(rng, chunksize * ratio); } MPI_Send(&work, 1, MPI_TYPE_WORK, status.MPI_SOURCE, WORK_TAG, MPI_COMM_WORLD); offset += chunksize; offsetnew += work.nsel; if(verbose) { fprintf(stderr, "%td / %td done (%0.4g%%)\r", offset, bb.size, (100. / bb.size) * offset); } } int i; for(i = 1; i < NTask; i ++) { struct work work; MPI_Send(&work, 1, MPI_TYPE_WORK, i, DIE_TAG, MPI_COMM_WORLD); } } void slave() { gsl_rng * rng = gsl_rng_alloc(gsl_rng_mt19937); int result = 0; MPI_Send(&result, 1, MPI_INT, 0, DONE_TAG, MPI_COMM_WORLD); while(1) { struct work work; MPI_Status status; MPI_Recv(&work, 1, MPI_TYPE_WORK, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status); if(status.MPI_TAG == DIE_TAG) { break; } gsl_rng_set(rng, work.seed); int64_t offset = work.offset; int64_t chunksize = work.chunksize; int64_t offsetnew = work.offsetnew; int64_t nsel = work.nsel; BigArray array; BigBlockPtr ptrnew; BigArray arraynew; size_t dims[2]; void * buffer = malloc(dtype_itemsize(bb.dtype) * bb.nmemb * nsel); dims[0] = nsel; dims[1] = bb.nmemb; big_array_init(&arraynew, buffer, bb.dtype, 2, dims, NULL); ptrdiff_t i; size_t step = dtype_itemsize(bb.dtype) * bb.nmemb; size_t leftover = chunksize; char * p = buffer; char * q; if(0 != big_block_read_simple(&bb, offset, chunksize, &array, NULL)) { fprintf(stderr, "failed to read original: %s\n", big_file_get_error_message()); result = -1; goto bad; } q = array.data; // printf("%ld %ld\n", nsel, leftover); for(i = 0; i < chunksize; i ++) { int64_t r = gsl_rng_uniform_int(rng, leftover); if(r < nsel) { memcpy(p, q, step); p += step; nsel --; } if(nsel == 0) break; leftover --; q += step; } if(nsel != 0) abort(); free(array.data); if(0 != big_block_seek(&bbnew, &ptrnew, offsetnew)) { fprintf(stderr, "failed to seek new: %s\n", big_file_get_error_message()); result = -1; free(arraynew.data); goto bad; } if(0 != big_block_write(&bbnew, &ptrnew, &arraynew)) { fprintf(stderr, "failed to write new: %s\n", big_file_get_error_message()); result = -1; free(arraynew.data); goto bad; } free(arraynew.data); MPI_Send(&result, 1, MPI_INT, 0, DONE_TAG, MPI_COMM_WORLD); continue; bad: MPI_Send(&result, 1, MPI_INT, 0, ERROR_TAG, MPI_COMM_WORLD); continue; } return; }
module Lvl where open import Type open import Agda.Primitive public using (Level; _⊔_) renaming (lzero to 𝟎; lsuc to 𝐒) -- Wraps a lower level set in a higher level wrapper set. record Up {ℓ₁ ℓ₂} (T : Type{ℓ₂}) : Type{ℓ₁ ⊔ ℓ₂} where constructor up field obj : T of : ∀{ℓ} → Type{ℓ} → Level of {ℓ} _ = ℓ {-# INLINE of #-} ofType : ∀{ℓ} → Type{𝐒(ℓ)} → Level ofType {ℓ} _ = ℓ {-# INLINE ofType #-}
If $p$ is a nonzero polynomial and $a$ is a root of $p$, then $p$ is divisible by $(x - a)^k$ but not by $(x - a)^{k + 1}$, where $k$ is the multiplicity of $a$ as a root of $p$.
Business cards are still a vital form of communication in the corporate world. Business cards are used far more often than most people realize and a business card must be chosen for its size. Anything could be printed on your business cards and you are looking for the most effective business card for your marketing. Business cards are given out in many different ways. You may hand out business cards to people you meet during the day, and you may give them out at networking functions. This is the simplest way to use business cards, but your business cards will blend in with others if you use the standard size. Consider using a slightly larger business card that people cannot miss. The card sticks up above other cards, and customers may store the card in a unique place that makes them easy to find. Do You Send Out Magnets? Business card magnets are a common use for business cards that you may create yourself. A standard business card size makes for easy shipping, but the magnet is not large enough to be seen on the refrigerator. Families may lose the magnets because of their size, or the magnets may be dwarfed by other magnets that are larger. Your magnets will be the largest magnets on fridges in your area if you choose larger business cards. A large business card is nearly the size of an index card, and it is larger enough to draw the attention of anyone in the room. Customers may not receive your business card on their own, but they may see the card at the home of a friend. This sort of marketing is no less effective than marketing done through other means. Local businesses keep bulletin boards where you may place your business card for community reference. A wise business owner uses a business card size that large enough to catch the eye of local customers. Tacking the business card on the board is made so much simpler when the card is large enough to be seen. Local businesses run their contests in much the same way. Your business card goes in a bucket from which the business pulls a card. A card that is larger than the others, and it is easier to find in the bucket. You increase your chances of winning a lovely prize, but you also increase your chances of being noticed by people who witness the drawing. The cash register of every local business near your office must have a stack of business cards representing your company. Choose the business card size that makes you noticeable, and ensure that your cards are replenished often. The careful selection of a large business card becomes moot when your cards are nowhere to be found. Local businesses that do not keep business cards by the register are a prime opportunity for you to be the first company represented. Offer the business a small stand for cards in exchange for advertising your business with the cards. You are doing a favor to businesses in the area through your generosity, but your business still benefits. You must partner with other businesses that do not compete with your own. Partners are given your business cards as a sign of support. You hand out some of their cards to your customers, and your partner hands out some of your cards. You and your partner business should have a different business card size to prevent confusion. A business card is the first step in a business relationship, but the business card size determines how far that relationship goes. Choose your business cards carefully to accomplish your goals, and pick the cards that will meet your needs when you market your business.
-- Idris2 import System import System.Concurrency ||| Test double-release errors correctly main : IO () main = do m <- makeMutex mutexAcquire m putStrLn "Mutex acquired" mutexRelease m putStrLn "1st release" mutexRelease m putStrLn "2nd release (SHOULDN'T HAPPEN)"
# A TUTORIAL ON HAMINTONIAN MONTE CARLO by Sebastian T. Glavind, January, 2022 ```python import jax # automatic differentiation import jax.numpy as jnp import jax.scipy.stats as jss import numpy as np import scipy import scipy.stats as ss from tqdm import tqdm # progress bars from matplotlib import pyplot as plt %matplotlib inline ``` ```python print('numpy: ', np.__version__,', scipy: ', scipy.__version__, ', jax: ', jax.__version__) ``` numpy: 1.21.2 , scipy: 1.7.3 , jax: 0.2.26 # Hamintonian Monte Carlo ## Introduction Hamiltonian Monte Carlo (HMC) is an effifient algorithm for performing Markov chain Monte Carlo (MCMC) inference, which uses gradients of the log-posterior distribution to guide the generation of new proposal states - the gradient at a given state provides information on the geometry of the posterior density function. Based on the gradient information, HMC can propose new states far from the current state with high acceptance probability by solving the so-called Hamiltonian equations, and it can thereby avoid the typical MCMC (local) random walk behaiviour. This enables HMC to scale to higher dimensions. The basis for HMC is to consider the sampling domain as a conservative dynamical system, where the total energy - in terms of kinetic energy (momentum) and potential energy (position) - is preserved, i.e., if the system gains kinetic energy then is loses the same amount of potential energy. In a physical setting, the potential energy is due to the pull of gravity, and the momentum is due to the motion of the particle. As an example, consider a particle with zero momentum on a declining surface; it will be pulled downwards by gravity, and its potential energy (from its initial height) will be transferred into kinetic energy (motion). Conversely, if the particle is moving along a flat plain, and it encounters a rise, it will slow down as it ascends, transferring its kinetic energy into potential energy. We thus consider the so-called momentum-position phase space, which can be represended by the following, convenient joint probability distribution: $$p(\mathbf{p}, \mathbf{q}) = p(\mathbf{p} | \mathbf{q}) p(\mathbf{q}).$$ In this representation, we can immediately recover the target distribution for the position (parameters) $p(\mathbf{q})$ by marginalizing out the momentum $\mathbf{p}$, and thus $\mathbf{p}$ is regarded as an auxilary variable. The joint distribution, also called the canonical density, for such a system may also be represented in terms of the invariant Hamiltonian function: $$ p(\mathbf{p}, \mathbf{q}) = \exp( -H(\mathbf{p}, \mathbf{q}) ), $$ where the value of the Hamiltonian function at any point in phase space represents the total energy at that point. Thus, as the joint density decomposes, the Hamiltonian function may be written: $$ H(\mathbf{p}, \mathbf{q}) = - \log p(\mathbf{p}, \mathbf{q}) = \underbrace{- \log p(\mathbf{p} | \mathbf{q})}_{K(\mathbf{p}, \mathbf{q})} \underbrace{- \log p(\mathbf{q})}_{V(\mathbf{q})} = K(\mathbf{p}, \mathbf{q}) + V(\mathbf{q}), $$ where $K(\mathbf{p}, \mathbf{q})$ resembles the kinetic energy and $V(\mathbf{q})$ resembles the potential energy. The trajectory of a particle within an energy level set can be obtained (simulated) by solving the following continuous time differential equations, known as Hamilton’s equations; $$ \require{xcancel} \begin{align} \frac{d\mathbf{q}}{dt} &= \frac{ \partial H }{\partial \mathbf{p}} = \frac{ \partial K }{\partial \mathbf{p}} + \xcancel{ \frac{ \partial V }{\partial \mathbf{p}} } \\ \frac{d\mathbf{p}}{dt} &= - \frac{ \partial H }{\partial \mathbf{q}} = - \frac{ \partial K }{\partial \mathbf{q}} - \frac{ \partial V }{\partial \mathbf{q}}, \end{align} $$ where $\partial V / \partial \mathbf{p}$ cancels, as $V$ does not depend on $\mathbf{p}$. This mapping is volume preserving, i.e., it has a Jacobian determinant of 1, a facts that will is important when turning then system into an MCMC algorithm. If we now chose the kinetic energy to be a Gaussian and drop the normalization constant, we have: $$ K(\mathbf{p}, \mathbf{q}) = \frac{1}{2} \mathbf{p}^T M^{-1} \mathbf{p} + \log |M|, $$ where M is called the mass matrix in the HMC literature. We scose this to be the identity matrix, i.e., $M=I$, which leads to $$ K(\mathbf{p}, \mathbf{q}) = \frac{1}{2} \mathbf{p}^T \mathbf{p}, $$ which simplifies the Hamiltonian equations to $$ \begin{align} \frac{d\mathbf{q}}{dt} &= \mathbf{p} \\ \frac{d\mathbf{p}}{dt} &= - \frac{ \partial V }{\partial \mathbf{q}}, \end{align} $$ as $\partial K / \partial \mathbf{p}=\mathbf{p}$ and $\partial K / \partial \mathbf{q}=0$ for the Gaussian definition of $K(\mathbf{p}, \mathbf{q})$ above; see e.g., Hoffman and Gelman (2014), Betancourt (2017), Martin et al (2021) and Murphy (2023) for further details. A simulation procedure is now taken shape; thus, we can sample $\mathbf{p}_0 \sim \mathcal{N}(0,I)$ and simulate a trajectory $\{ \mathbf{q}_t, \mathbf{p}_t \}_{t=1}^T$ for some amount of time $T$, where $\mathbf{q}_T$ is then our new sample. In the following section, we will study how we simulate the trajectory $\{ \mathbf{q}_t, \mathbf{p}_t \}_{t=1}^T$ by solving Hamilton’s equations. *** Hoffman, Matthew D., and Andrew Gelman. "The No-U-Turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo." J. Mach. Learn. Res. 15.1 (2014): 1593-1623 ([link](https://www.jmlr.org/papers/volume15/hoffman14a/hoffman14a.pdf)). Betancourt, Michael. "A conceptual introduction to Hamiltonian Monte Carlo." arXiv preprint arXiv:1701.02434, 2017 ([link](https://arxiv.org/pdf/1701.02434.pdf?ref=https://githubhelp.com)) Martin, Osvaldo A. and Kumar, Ravin and Lao, Junpeng, "Bayesian Modeling and Computation in Python", CRC, 2021. Murphy, Kevin P., "Probabilistic Machine Learning: Advanced Topics", MIT Press, 2023 ([draft](https://probml.github.io/pml-book/book2.html) from feb. 2022). *** ## Solving Hamilton's equations In this section, we discuss how to simulate trajectories from Hamilton’s equations in discrete time. ### Euler's method One simple way to simulate these trajectories is to update the position and momentum simultaneously by a small amount based on the gradients: $$ \begin{align} \mathbf{p}_{t+1} &= \mathbf{p}_{t} + \eta \frac{d\mathbf{p}}{dt}(\mathbf{q}_t,\mathbf{p}_t) = \mathbf{p}_{t} - \eta \frac{ \partial V }{\partial \mathbf{q}}(\mathbf{q}_t) \\ \mathbf{q}_{t+1} &= \mathbf{q}_{t} + \eta \frac{d\mathbf{q}}{dt}(\mathbf{q}_t,\mathbf{p}_t) = \mathbf{q}_{t} + \eta \mathbf{p}_{t}, \end{align} $$ where $\eta$ is the step size, and we have included the simple definition for kinetic energy above in the second expression. Unfortunally, though, Euler’s method does not preserve volume, and can lead to inaccurate approximations after only a few steps. ### Modified Euler's method In Modified Euler's method, we make Euler's method symplectic (volume preserving) by first updating the momentum, and then we update the position using the new momentum: $$ \begin{align} \mathbf{p}_{t+1} &= \mathbf{p}_{t} + \eta \frac{d\mathbf{p}}{dt}(\mathbf{q}_t,\mathbf{p}_t) = \mathbf{p}_{t} - \eta \frac{ \partial V }{\partial \mathbf{q}}(\mathbf{q}_t) \\ \mathbf{q}_{t+1} &= \mathbf{q}_{t} + \eta \frac{d\mathbf{q}}{dt}(\mathbf{q}_t,\mathbf{p}_{t+1}) = \mathbf{q}_{t} + \eta \mathbf{p}_{t+1}, \end{align} $$ Note that we can equivalently perform the updates in the opposite order. Unfortunally, this procedure is not reversible due to the asymmetry in the updates. ### Leapfrog integrator Using the Leapfrog integrator, we can make Euler's method symplectic and reversible by first performing a half-update of the momentum, next we perform a full update of the position, and then we perform another half-update of the momentum: $$ \begin{align} \mathbf{p}_{t+1/2} &= \mathbf{p}_{t} + \frac{\eta}{2} \frac{d\mathbf{p}}{dt}(\mathbf{q}_t,\mathbf{p}_t) = \mathbf{p}_{t} - \frac{\eta}{2} \frac{ \partial V }{\partial \mathbf{q}}(\mathbf{q}_t) \\ \mathbf{q}_{t+1} &= \mathbf{q}_{t} + \eta \frac{d\mathbf{q}}{dt}(\mathbf{q}_t,\mathbf{p}_{t+1/2}) = \mathbf{q}_{t} + \eta \mathbf{p}_{t+1/2} \\ \mathbf{p}_{t+1} &= \mathbf{p}_{t+1/2} + \frac{\eta}{2} \frac{d\mathbf{p}}{dt}(\mathbf{q}_{t+1},\mathbf{p}_{t+1/2}) = \mathbf{p}_{t+1/2} - \frac{\eta}{2} \frac{ \partial V }{\partial \mathbf{q}}(\mathbf{q}_{t+1}), \end{align} $$ It can be shown that the Leapfrog integrator is volumen preserving, and given that we reverse the momentum at the end of the iteration, i.e., replace $\mathbf{p}$ by $-\mathbf{p}$, it is also reversible. Note that if the kinetic energy satisfies $K(\mathbf{p})=K(-\mathbf{p})$, the reversal of momentum is not needed to make the method reversible. How effectively HMC explores the target distribution is determined by the integration length $T$, or equavantly the number of leapfrog steps $L$, at each iteration. One the one hand, if we integrate for only a short time then we do not take full advantage of the coherent exploration of the Hamiltonian trajectories, and the algorithm will exhibit random walk-like behaviour. On the other hand, trajectories will eventually return to previously explored neighborhoods, i.e., integrating too long can suffer from diminishing returns. Unfortunally, the Leapfrog integrator does not exactly perserve energy, due to the finite step size. This, however, can be fixed by treating the method as a proposal distribution, and then we can use the Metropolis acceptance criterion to ensure that we sample form the target distribution. The Metropolis acceptance criterion for this case is defined as $$ \mathbf{q}_{k+1} = \begin{cases} \mathbf{q}_{T} & \text{with probability}\ \min\left( \left[p(\mathbf{q}_{T}, \mathbf{p}_{T}) \big/ p(\mathbf{q}_{k}, \mathbf{p}_0) \right], \ 1 \right) \\ \mathbf{q}_{k} & \text{otherwise}, \end{cases} $$ where $(\mathbf{q}_{T}, \mathbf{p}_{T})$ is our porposal, and $(\mathbf{q}_{k}, \mathbf{p}_{0})$ is the previous sample of $\mathbf{q}$ and the random, initial momentum for sample $k+1$, respectively. For more information on solving Hamilton's equations, see Murphy (2023), as well as this nice [blog post](https://bayesianbrad.github.io/posts/2019_hmc.html). ```python # Code inspired by the implementation in the "Bayesian Modeling and Computation in Python" book # https://bayesiancomputationbook.com/markdown/chp_11.html def leapfrog(q, p, dVdq, path_len, step_size): p -= step_size * dVdq(q) / 2 # half step for _ in range(int(path_len / step_size) - 1): q += step_size * p # whole step p -= step_size * dVdq(q) # whole step q += step_size * p # whole step p -= step_size * dVdq(q) / 2 # half step return q, -p # momentum flip at end ``` ## The HMC algorithm Now that we have the boilding blocks, we are ready to summarize the HMC algorithm: At each iteration, we 1. sample a momentum $\mathbf{p}_0 \sim \mathcal{N}(0,I)$ and 2. simulate a trajectory $\{ \mathbf{q}_t, \mathbf{p}_t \}_{t=1}^T$ for some amount of time $T$, i.e., $L$ Leapfrog steps. 3. chose $\mathbf{q}_T$ is then our new sample. 4. use the Metropolis acceptance criterion to judge whether $\mathbf{q}_T$ should be accepted or rejected as a sample from the traget distribution. Note that in order the make the HMC implementation below general, we will use the autodiff library `jax`, whereby the implementation does not rely on our ability to provide the analytical gradients for the Leapfrog integrator. ```python def hamiltonian_monte_carlo( n_samples, negative_log_prob, initial_position, path_len=1, step_size=0.5): # counter of acceptance counter = 0 # jax autodiff magic - initialize dVdq = jax.grad(negative_log_prob) # collect all our samples in a list samples = [initial_position] # Keep a single object for momentum resampling momentum = ss.norm(0, 1) # If initial_position is a 10d vector and n_samples is 100, we want # 100 x 10 momentum draws. We can do this in one call to momentum.rvs, and # iterate over rows size = (n_samples,) + initial_position.shape[:1] for p0 in momentum.rvs(size=size): # Integrate over our path to get a new position and momentum q_new, p_new = leapfrog( samples[-1], p0, dVdq, path_len=path_len, step_size=step_size) # Check Metropolis acceptance criterion start_log_p = negative_log_prob(samples[-1]) - np.sum(momentum.logpdf(p0)) new_log_p = negative_log_prob(q_new) - np.sum(momentum.logpdf(p_new)) if np.log(np.random.rand()) < start_log_p - new_log_p: samples.append(q_new) counter += 1 else: samples.append(np.copy(samples[-1])) return np.array(samples[1:]), counter ``` ## Setting the step size by dual avaging To set the step size $\epsilon$ in HMC (and its extension the no-uturn sampler (NUTS)), Hoffman and Gelman (2014) propose to use stochastic optimization with vanishing adaptation, specifically an extension of the primal-dual algorithm of Nesterov (2009). Generally, we consider a statistic $H_k$ that describes some aspect of the behavior of an MCMC algorithm at iteration $k$, which has expectation $h(x)$, where $x \in \mathbb{R}$ is a tunable parameter of the MCMC algorithm. For our case, we will target the average Metropolis acceptance probability (see above) based on the criterion $$ H_k = \delta - \alpha_k; \quad h(x) = \mathbb{E}[H_k|x] $$ where $\delta$ is the desired average acceptance probability, and $\alpha_k$ is the Metropolis acceptance probability for iteration $k$. The following updating scheme: $$ x_{k+1} = \mu - \frac{\sqrt(k)}{\gamma} \frac{1}{k + k_0} \sum_{i=1}^k H_i; \quad \bar{x}_{k+1} \leftarrow \eta_k x_{k+1} + (1 - \eta_k) \bar{x}_k $$ than guarantees that the sequence of averaged iterates $\bar{x}_k$ converges to a value, such that $h(\bar{x}_k)$ converges to $0$ for $\eta_k = k^{-\kappa}$ with $\kappa \in (0.5, 1]$. Further, $\mu$ is a freely chosen point that the iterates $x_k$ are shrunk towards, $\gamma > 0$ is a free parameter that controls the amount of shrinkage towards $\mu$, $k_0 \geq 0$ is a free parameter that stabilizes the initial iterations of the algorithm, and we define $\bar{x}_1 = x_1$. Hoffman and Gelman (2014) propose to use $x = \log \epsilon$ with parameters $\gamma = 0.05$, $t_0 = 10$, $\kappa = 0.75$, and $\mu = \log(10 \epsilon_0)$, where $\epsilon_0$ is the initial step size. Moreover, it has been shown that the optimal value of $\epsilon$ for a given simulation length $\epsilon L$ is the one that produces an average Metropolis acceptance probability of approximately $0.65$, thus we set $\delta=0.65$. Please refer to Hoffman and Gelman (2014) for further details. *** Hoffman, Matthew D., and Andrew Gelman. "The No-U-Turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo." J. Mach. Learn. Res. 15.1 (2014): 1593-1623 ([link](https://www.jmlr.org/papers/volume15/hoffman14a/hoffman14a.pdf)). Nesterov, Yurii. "Primal-dual subgradient methods for convex problems." Mathematical programming 120.1 (2009): 221-259. *** ```python # See Hoffman and Gelman (2013), section 3.2.1. # https://colindcarroll.com/2019/04/21/step-size-adaptation-in-hamiltonian-monte-carlo/ # https://github.com/ColCarroll/minimc/blob/master/minimc/minimc.py class DualAveragingStepSize: def __init__(self, initial_step_size, target_accept=0.65, gamma=0.05, t0=10.0, kappa=0.75): self.mu = np.log(10 * initial_step_size) # proposals are biased upwards to stay away from 0. self.target_accept = target_accept self.gamma = gamma self.t = t0 self.kappa = kappa self.error_sum = 0 self.log_averaged_step = 0 def update(self, p_accept): # Running tally of absolute error. Can be positive or negative, but optimally 0. self.error_sum += self.target_accept - p_accept # This is the next proposed (log) step size. Note it is biased towards mu. log_step = self.mu - self.error_sum / (np.sqrt(self.t) * self.gamma) # Forgetting rate. As 't' gets bigger, 'eta' gets smaller. eta = self.t ** -self.kappa # Smoothed average step size self.log_averaged_step = eta * log_step + (1 - eta) * self.log_averaged_step # State update, such taht 't' keeps updating self.t += 1 # Return both the noisy step size (tuning phase), and the smoothed step size (after tuning) return np.exp(log_step), np.exp(self.log_averaged_step) def hamiltonian_monte_carlo_dual( n_samples, negative_log_prob, initial_position, path_len=1, initial_step_size=0.5, tune=500): # counter of acceptance counter = 0 # jax autodiff magic - initialize dVdq = jax.grad(negative_log_prob) # collect all our samples in a list samples = [initial_position] # Keep a single object for momentum resampling momentum = ss.norm(0, 1) # Step size adaption - initialization step_size = initial_step_size step_size_tuning = DualAveragingStepSize(step_size) # If initial_position is a 10d vector and n_samples is 100, we want # 100 x 10 momentum draws. We can do this in one call to momentum.rvs, and # iterate over rows size = (n_samples + tune,) + initial_position.shape[:1] for idx, p0 in tqdm(enumerate(momentum.rvs(size=size)), total=size[0]): # for idx, p0 in enumerate(momentum.rvs(size=size)): # Integrate over our path to get a new position and momentum # NB!!! Jitter the path length to stabilize algorithm - on average it equals the specified path length q_new, p_new = leapfrog( samples[-1], p0, dVdq, path_len=2*np.random.rand()*path_len, step_size=step_size) # Check Metropolis acceptance criterion start_log_p = np.sum(momentum.logpdf(p0)) - negative_log_prob(samples[-1]) new_log_p = np.sum(momentum.logpdf(p_new)) - negative_log_prob(q_new) p_accept = min(1, np.exp(new_log_p - start_log_p)) if np.random.rand() < p_accept: samples.append(q_new) if idx > tune - 1: counter += 1 else: samples.append(samples[-1]) # Step size adaption if idx < tune - 1: step_size, _ = step_size_tuning.update(p_accept) elif idx == tune - 1: _, step_size = step_size_tuning.update(p_accept) return np.array(samples[1 + tune :]), counter, step_size ``` # Numerical example In this tutorial, we will study how HMC can be used to perform Bayesian inference in linear regression. For this simple case, we can ofcause derive the analytical gradients needed by the Leapfrog integrator, see e.g., my tutorial on linear regression ([link](https://nbviewer.org/github/SebastianGlavind/PhD-study/blob/master/Linear-regression/LinReg.ipynb)), but to showcase the generality of the implementation above, we will used the autodiff library `jax` for this case as well. ## The model In the simplest case of linear regression, sometimes called ordinary linear regression, the scalar output $y$ is assumed to be a linear combination of the inputs $\mathbf{x}$, and the observation errors follow a Gaussian white noise distribution, thus $$ y | \mathbf{w}, \sigma, \mathbf{x} \sim \mathcal{N}(w_0 + \sum_{m=1}^{M-1} w_m x_m, \sigma^2) = \mathcal{N}(\mathbf{w}^T \mathbf{x}, \sigma^2), $$ where we have augmented the input vector $\mathbf{x}$ with an additional first element, which is always 1, i.e, $\mathbf{x} = (1, x_1, x_2, ..., x_{M-1})$, and the corresponding weight vector $\mathbf{w} = (w_0, w_1, w_2, ..., w_{M-1})$. If we now consider a training data set $\mathcal{D}=\{ \mathbf{x}[n], y[n] \}_{n=1}^N = \{ \mathbf{X}, \mathbf{y} \}$, where $\mathbf{X}$ is a $ N \times M $ design matrix and $\mathbf{y}$ is a column vector of the corresponding output observations, the joint likelihood of the training data may be written: $$ \mathbf{y} | \mathbf{w}, \sigma, \mathbf{X} \sim \prod_{n=1}^N \mathcal{N}(\mathbf{w}^T \mathbf{x}[n], \sigma^2) = \mathcal{N}(\mathbf{X}\mathbf{w},\sigma^2\mathbf{I}), $$ where $\mathbf{I}$ is an $ N \times N $ identity matrix. ## Sample data ```python # True, underlaying model w0_true = 4 w1_true = 8 sigma_true = 2 def generate_training_data(x, w0, w1, sigma): n = len(x) error = np.random.normal(loc=0, scale=sigma, size=n) return( w0 + w1*x + error ) # Generate and plot data x_tr = np.arange(start=-1, stop=1, step=0.1) np.random.seed(10) # good seed y_tr = generate_training_data(x=x_tr, w0 = w0_true, w1 = w1_true, sigma = sigma_true) XX = np.vstack((np.ones(len(x_tr)), x_tr)).T # design matrix (convention Bishop(2006)) nX_tr, mX_tr = XX.shape # - np.array([0, 1]); # data dimensions are defined as actual features ;) x_te = np.arange(start=-1.25, stop=1.25, step=0.1) XX_te = np.vstack((np.ones(len(x_te)), x_te)).T # design matrix (convention Bishop(2006)) nX_te, mX_te = XX_te.shape # - np.array([0, 1]); # data dimensions are defined as actual features ;) plt.plot(x_tr, y_tr,'ob'); plt.plot(x_tr,(w0_true + w1_true * x_tr),'-r'); plt.xlabel('x') plt.ylabel('y') plt.title('Training data and true linear model') plt.grid() ``` ## Bayesian inference See e.g. Gelman et al. (2013; Sec.12.4 and App.C.4 (R implementation)) for a reference on the Hamiltonian Monte Carlo algorithm. ### The generative story We sample a realization of the parameter vector $\theta$ as $$ p(\boldsymbol\theta |\mathcal{D}) \propto p(\mathbf{y}|\mathbf{X},\boldsymbol\theta) p(\boldsymbol\theta), $$ where $$ \theta_{0:1} = w_{0:1} \sim \mathcal{N}(0,10), $$ and $$ \theta_{2} = \sigma^2 \sim \text{Gamma}(2,2). $$ ### The unnormalized parameter posterior Recall that the parameter posterior is defined through Bayes' rule as $$p(\boldsymbol\theta|\mathcal{D}) = \frac{ p(\mathbf{y},\boldsymbol\theta|\mathbf{x}) }{ p(\mathbf{y})}, $$ but we will work with the unnormalized version, i.e. $$p(\boldsymbol\theta|\mathcal{D}) \propto p(\mathbf{y},\boldsymbol\theta|\mathbf{x}), $$ to avoid calculating the always troubling normalizing constant $\mathbf{y}$. *** Gelman, Andrew, et al. Bayesian data analysis. CRC press, 2013. *** ```python # This function calculates the unnormalized posterior for theta, i.e. p(theta|D) = p(y,theta|x)/p(y) def neg_log_pos_hmc(theta,pam1=np.array([0.,10.]),pam2=np.array([0.,10.]),pam3=np.array([2.,2.])): w0 = theta[0] w1 = theta[1] sig2 = theta[2] mu = w0 + w1 * x_tr logPos = (sum( jss.norm.logpdf(y_tr, loc = mu, scale = jnp.sqrt(sig2)) ) + jss.norm.logpdf(w0, loc=pam1[0], scale=pam1[1]) + jss.norm.logpdf(w1, loc=pam2[0], scale=pam2[1]) + jss.gamma.logpdf(sig2, a = pam3[0], scale = pam3[1]) ) negLogPos = - logPos return(negLogPos) # Test the implementation print( neg_log_pos_hmc(np.array([4., 8., 4.])) ) print( jax.grad(neg_log_pos_hmc)(np.array([4., 8., 4.])) ) ``` WARNING:absl:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.) 48.206924 [-1.1471946 0.42492092 0.96945906] ## Basic Hamiltonian Monte Carlo This shows how to sample from éne chain; in a real application, we would initialize multiple chains overdispersed in the plausible range of the variables and check for mixing. ### Sampling from the posterior ```python # %%time # Call the HMC implementation np.random.seed(42) n_samp_hmc = int(2e2) samp_hmc, counter_hmc = hamiltonian_monte_carlo(n_samp_hmc, neg_log_pos_hmc, np.array([4., 8., 2.]), path_len=2, step_size=0.65) counter_hmc/n_samp_hmc ``` 0.645 ### Analyze samples We regard the first half of the samples as burn-in and plot the posterior samples (blue). ```python samp_hmc0 = samp_hmc[0:round(n_samp_hmc/2),:] # burn-in samp_hmc1 = samp_hmc[round(n_samp_hmc/2):n_samp_hmc,:] # without burn-in # Marginal distribution approximations plt.figure() plt.hist(samp_hmc0[:,0], color='red' ); plt.hist(samp_hmc1[:,0] , color='blue' ); plt.title('Noise standard deviation') plt.figure() plt.hist(samp_hmc0[:,1], color='red' ); plt.hist(samp_hmc1[:,1] , color='blue' ); plt.title('Kernel standard deviation (signal)') plt.figure() plt.hist(samp_hmc0[:,2], color='red' ); plt.hist(samp_hmc1[:,2] , color='blue' ); plt.title('Kernel length scale (signal)'); ``` ```python # Scatter plot of regression parameter plt.plot(samp_hmc0[:,0],samp_hmc0[:,1],'*r'); plt.plot(samp_hmc1[:,0],samp_hmc1[:,1],'*b'); plt.xlabel('$w_0$'); plt.ylabel('$w_1$'); plt.title('Weights samples'); ``` #### Define sample statistics for the latent function (f) and the output (y) ```python f_pred_hmc = samp_hmc1[:,0:2].dot(XX_te.T) y_pred_hmc = f_pred_hmc + np.random.normal(scale=np.sqrt(samp_hmc1[:,2])).reshape([-1,1]) mu_pred_hmc = np.mean(f_pred_hmc,axis=0) cf_pred_f_hmc= np.quantile(f_pred_hmc,q=[0.025, 0.975],axis=0) cf_pred_y_hmc= np.quantile(y_pred_hmc,q=[0.025, 0.975],axis=0) ``` #### Plot the resulting model 95\% Bayesian credible interval of the posterior model. ```python plt.plot(x_tr, y_tr,'ob'); plt.plot(x_tr,(w0_true + w1_true * x_tr),'-r'); plt.plot(x_te,mu_pred_hmc,'--k'); plt.fill_between(x=x_te, y1=cf_pred_f_hmc[0,:], y2=cf_pred_f_hmc[1,:], alpha=0.5); plt.fill_between(x=x_te, y1=cf_pred_y_hmc[0,:], y2=cf_pred_y_hmc[1,:], alpha=0.1, color='blue'); plt.xlabel('x'); plt.ylabel('y'); plt.title('Training data, true linear model and linear regression'); plt.grid(); ``` ## Hamiltonian Monte Carlo with step size adaption This shows how to sample from éne chain; in a real application, we would initialize multiple chains overdispersed in the plausible range of the variables and check for mixing. ### Sampling from the posterior ```python # %%time # Call the HMC implementation np.random.seed(42) n_samp_hmc_dual = int(2e2) samp_hmc_dual, counter_hmc_dual, step_size_hmc_dual = hamiltonian_monte_carlo_dual(n_samp_hmc_dual, neg_log_pos_hmc, np.array([2., 16., 4.]), path_len=3, initial_step_size=0.33, tune=100) print('Acceptance rate: ', counter_hmc_dual/n_samp_hmc_dual) print('Optimized step size: ', step_size_hmc_dual) ``` 100%|█████████████████████████████████████████| 300/300 [01:53<00:00, 2.65it/s] Acceptance rate: 0.85 Optimized step size: 5.009077704356696e-01 ### Analyze samples We regard the first half of the samples as burn-in and plot the posterior samples (blue). ```python samp_hmc_dual0 = samp_hmc_dual[0:round(n_samp_hmc_dual/2),:] # burn-in samp_hmc_dual1 = samp_hmc_dual[round(n_samp_hmc_dual/2):n_samp_hmc_dual,:] # without burn-in # Marginal distribution approximations plt.figure() plt.hist(samp_hmc_dual0[:,0], color='red' ); plt.hist(samp_hmc_dual1[:,0] , color='blue' ); plt.title('Noise standard deviation') plt.figure() plt.hist(samp_hmc_dual0[:,1], color='red' ); plt.hist(samp_hmc_dual1[:,1] , color='blue' ); plt.title('Kernel standard deviation (signal)') plt.figure() plt.hist(samp_hmc_dual0[:,2], color='red' ); plt.hist(samp_hmc_dual1[:,2] , color='blue' ); plt.title('Kernel length scale (signal)'); ``` ```python # Scatter plot of regression parameter plt.plot(samp_hmc_dual0[:,0],samp_hmc_dual0[:,1],'*r'); plt.plot(samp_hmc_dual1[:,0],samp_hmc_dual1[:,1],'*b'); plt.xlabel('$w_0$'); plt.ylabel('$w_1$'); plt.title('Weights samples'); ``` #### Define sample statistics for the latent function (f) and the output (y) ```python f_pred_hmc_dual = samp_hmc_dual1[:,0:2].dot(XX_te.T) y_pred_hmc_dual = f_pred_hmc_dual + np.random.normal(scale=np.sqrt(samp_hmc_dual1[:,2])).reshape([-1,1]) mu_pred_hmc_dual = np.mean(f_pred_hmc_dual,axis=0) cf_pred_f_hmc_dual = np.quantile(f_pred_hmc_dual,q=[0.025, 0.975],axis=0) cf_pred_y_hmc_dual = np.quantile(y_pred_hmc_dual,q=[0.025, 0.975],axis=0) ``` #### Plot the resulting model 95\% Bayesian credible interval of the posterior model. ```python plt.plot(x_tr, y_tr,'ob'); plt.plot(x_tr,(w0_true + w1_true * x_tr),'-r'); plt.plot(x_te,mu_pred_hmc_dual,'--k'); plt.fill_between(x=x_te, y1=cf_pred_f_hmc_dual[0,:], y2=cf_pred_f_hmc_dual[1,:], alpha=0.5); plt.fill_between(x=x_te, y1=cf_pred_y_hmc_dual[0,:], y2=cf_pred_y_hmc_dual[1,:], alpha=0.1, color='blue'); plt.xlabel('x'); plt.ylabel('y'); plt.title('Training data, true linear model and linear regression'); plt.grid(); ```
\chapter{Business Analysis}\label{sec-biz-analysis} In this chapter, we analyse our product, services and the market, and discuss our business decisions and plans. \section{Value Proposition} The current value proposition of Pear is: to catalyse the sharing economy in computing. Pear works on precisely scheduling idle computing resources and bandwidth to match the demand/supply of all relevant parties through the Internet. We are learning from Uber, trying to involve more players to share and achieve multi-wins without destroying the current ecosystem. As there would be a number of services multiplexed on Pear's fog resources pool, it is infeasible to analyse them one-by-one. Here we only take Pear's Fog CDN service as an example. The changes of the industry chain can be illustrated as shown in Figure~\ref{fig:eco-sys-change}. \begin{figure}[ht] \centering \includegraphics[width=.66\textwidth]{fig/biz/eco-system-change.png} \caption{Ecosystem change before and after Pear comes in.} \label{fig:eco-sys-change} \end{figure} The value proposition also illustrates the main reason why Pear is called ``Pear''. In ``The Three-Character Classic'' or ``San Zi Jing'', one of the most famous Chinese classic texts, an entire story is condensed into these twelve Chinese characters, means ``Aged four years, Rong proffered pears. Bear in mind, fraternally be kind''. The story mainly appreciates the then 4-year-old boy's virtue of being willing to share big pears to his elder and younger brothers. We extract the sharing spirit from this classic and find a better way to explain it with the success stories of Uber and Airbnb. Besides trying to make a profit, Pear is struggling to provide the best technical and economic means of P2P Internet sharing and to promote the concept of sharing resources for win-win situations via Fog Computing. \section{Services Offered} Based on the concept and infrastructure of Fog Computing, Pear has the ambition of running hundreds of services that practise the philosophy of sharing economy. However, Pear is a company which surely needs revenue and profit in order to provide services consistently over time and grow to the next level. Thus, Pear is initially focusing on a few main services: \begin{enumerate} \item Fog CDN for Live Streaming and VoD (Video on Demand), aka Fog VDN; \item Fog Media Coding Service; \item Fog Storage Service; \item Fog VPN (Virtual Private Network); \item Fog Crawler/Spider; \item Fog BaaS (Blockchain as a Service); \item Fog Computing for IoT. \end{enumerate} \section{Revenue Streams} Pear is a technology-driven start-up company, with limited financial resources. The primary revenue during the beginning years will be generated from a business-to-business (B2B) model. Pear is responsible for developing customised fog service platforms for business partners and will charge them appropriate prices that help them save costs and/or generate more revenue. Take Pear's Fog CDN service as an example: CPs currently obtain traditional CDN services, which are mainly charged according to peak bandwidth consumed and which typically range from HKD~$30,000$ to $100,000$/Gbps/Month. For Pear's Fog CDN service, the price charged will be within HKD~$10,000$ to $15,000$/Gbps/Month. Pear would invest part of the revenue into regularly scaling up the network infrastructure in order to build a stronger Fog CDN offering more bandwidth and better usability. \begin{figure}[ht] \centering \includegraphics[width=.80\textwidth]{fig/biz/revenue_stream.png} \caption{Proposed revenue streams for Pear Fog's VDN service.} \label{fig:vdn-revenue-stream} \end{figure} \section{Distinctivenesses, Challenges and Risk Factors} The brief introductions to Pear's technology and business have provided a rough picture of what Pear is, what it is doing and why it is doing it. Nevertheless, knowing how it works does not mean anyone can easily bring it into a real competitive market. Conversely, for projects like Pear's Fog VDN, the clearer people know about the details, the more likely they would realise that there is a solid barrier to success. The most difficult task throughout the development of Pear's Fog CDN platform has been to elegantly build the framework with pure C language. The platform interfaces with the front-end media control using HTML5 and JavaScript, with the back-end schedulers and servers using C++ and FastCGI, and with the embedded system programs using C and assembly. That is already beyond an ordinary full-stack engineer's range. Howbeit, Pear can do even more. A traditional programmer would probably not be qualified to lead this project, because the Fog CDN platform also requires expert knowledge in streaming and network protocols, like WebRTC, HLS and MPEG-DASH, as well as various open P2P protocols. Even inside IT Giants, it is hard to find such guys with such versatile skills. Fortunately, Pear's three technology co-founders' backgrounds cover all these special criteria. Pear Fog is a demanding project in terms of hardware and software engineering, and it is also highly correlated to the newest Internet technology, which sets barriers for potential competitors. Only a special ops hardware and software team could try to do what Pear is doing. In spite of all Pear's human capital, it does face some challenges and associated risks: \begin{enumerate} \item Pear does not yet have much capital investment. This shortage of funding could hinder Pear from scaling up rapidly. \item Pear is overstretched with human capital. The team will have to work very hard and smart to achieve its goals in the given time frame. \item Pear still lacks its own market resources. It must initially solely rely on its partners, such as router vendors and CPs, and Pear knows it is a little bit over-reliant upon them. \item The trial-test-and-pay nature of B2B businesses would make the revenue come relatively late. \end{enumerate} Nevertheless, Pear's risk factors should also help Pear to work hard and work smart. We are young, eager and confident that Pear will grow much stronger soon. This is based on our working experience, input from experts and relationships in the CDN field and elsewhere that should encourage win-win cooperation. \section{Product and Marketing Plan} Among all the services we are offering, Fog CDN is Pear's featured product. It is a huge system, and we plan to steadily build it step by step, firmly. We believe the Fog CDN market will eventually capture people's attention. We also expect the Fog CDN to be the ever first successful product based on fog computing technologies. \subsection{Market Analysis} Pear is an innovator in the CDN market. We are not able to tell whether our Fog CDN will completely replace the traditional CDN's role, but we aim to make it step gently into the traditional CDN market and gradually capture more and more market share until the two coexist and complement one another for a relatively long time in the future. \subsubsection{Target Customers} In Pear's B2B Model, the targeted customers mainly refer to the CPs and traditional CDN service providers. Because of the inherent advantages of the background of one of the co-founders, Pear has a close relationship with the biggest video content provider in mainland China: Tencent Video. Pear's initial marketing efforts will focus on Mainland China since it is the largest market in the world and most of the co-founders are Chinese. Pear now is helping a new CDN provider to build a video cloud platform which implements part of Pear's Fog CDN technology aiming to help deliver the 4k video smoothly, and with a reasonable cost. As user generated content (UGC) becomes more popular on the Internet, Pear expects to see some new types of CPs that leverage UGC business, such as BiliBili.com and ACfun.tv. Pear will also target them as customers in the first stage. Due to the versatile Fog CDN infrastructure, as Pear grows, we can reuse this network to build the Fog VPN service with a high degree of usability. Pear plans to present consumers with the Fog VPN service in the second stage after the B2B business is proven to be viable. \subsubsection{Market Characteristics and Trends} From a commercial CDN market survey report, we can see that the Total Addressable Market (TAM) of the commercial CDN is increasing at a phenomenal rate, especially in China, see Figure~\ref{fig:CN-CDN-TAM}. \begin{figure}[ht] \centering \begin{center} \begin{tikzpicture} %[>=latex] \begin{axis}[ height=0.75\textwidth, symbolic x coords={2012, 2013, 2014, 2015, 2016, 2017}, xtick=data, ymin=0, ylabel=Size (in 100M), enlarge x limits=0.1, %xticklabel style={text width=0.2\textwidth,align=flush left}, ] \addplot[ybar, axis on top, fill=blue] coordinates { (2012, 16.8) (2013, 23.6) (2014, 35.6) (2015, 54.4) (2016, 81.4) (2017, 140.0) }; \node (n2)[above] at (axis cs: 2012, 16.8) {$16.8$}; \node (n3)[above] at (axis cs: 2013, 23.6) {$23.6$}; \node (n4)[above] at (axis cs: 2014, 35.6) {$35.6$}; \node (n5)[above] at (axis cs: 2015, 54.4) {$54.4$}; \node (n6)[above] at (axis cs: 2016, 81.4) {$81.4$}; \node (n7)[above] at (axis cs: 2017, 140.0) {$140.0$}; \draw [->] (n2) -- (n3) node [midway, above, sloped] (tn1) {$+40.5\%$}; \draw [->] (n3) -- (n4) node [midway, above, sloped] (tn2) {$+50.8\%$}; \draw [->] (n4) -- (n5) node [midway, above, sloped] (tn3) {$+52.8\%$}; \draw [->] (n5) -- (n6) node [midway, above, sloped] (tn4) {$+49.6\%$}; \draw [->] (n6) -- (n7) node [midway, above, sloped] (tn5) {$+72.0\%$}; \end{axis} \end{tikzpicture} \end{center} \caption{TMM of China Market.}\label{fig:CN-CDN-TAM} \end{figure} \begin{figure}[ht] \centering \begin{tikzpicture} \node(c1) [circle,shading=radial,outer color=blue!30,inner color=white, minimum width=1.855cm,align=center,text width=3cm] at (0.1,3.3) {\textcolor{blue!80!black}{USD 3.71 B\\ 2014}}; \node(c2) [circle,shading=radial,outer color=blue!30,inner color=white, minimum width=6.08cm,align=center,text width=3cm] at (7.5,4.6) {\textcolor{blue!80!black}{USD 12.16 B\\ 2019}}; \draw [->, thick] (c1) -- (c2) node [midway, above, sloped] (c1c2) {CAGR: $26.3\%$};; \end{tikzpicture} \caption{Cisco's world commercial CDN TAM growth expectations from 2014 to 2019.}\label{fig:World-CDN-TAM} \end{figure} According to a prediction by iResearch, the TAM of China's commercial CDN is expected to reach RMB 8.16 billion in 2016 with an annually increase at about 53\%. In fact, we have witnessed that all previous CDN market size predictions were eventually proven to be far behind the real growth. For example, in a Cisco white paper published in 2014, the world's commercial CDN TAM in 2012 was predicted to reach USD 12.16 billion at a CAGR of 26.3\% as depicted in Figure~\ref{fig:World-CDN-TAM}, while a report\footnote{\url{http://www.researchandmarkets.com/research/8vnkvv/mobile_cdn_market}} issued in 2015 suggested that the mobile CDN market alone will grow from USD 2.11 billion in 2015 to USD 13.40 billion by 2020, at a CAGR of 44.7\%. The fact is telling us: data traffic demand tends to run far over the commercial CDN capacity. Moreover, the gap between demand and supply is becoming wider and wider. When we compare China's market and the World's, we find that commercial CDN only serves 8-10\% of total Internet data traffic in China, while in the US, commercial CDN has already been serving around 50\% Internet data traffic. This is another reason why Pear is focusing on the China market in the first stage. Apart from that, we expect that the demand for commercial CDN will last for long, so we are sufficiently confident with its market, even in the global depression. This is because commercial CDN mainly serves online video, games and related entertainment industries that are expected to perform very well regardless of the economic outlook. History shows that Broadway and Hollywood thrived during the Great Depression, so unless there is a war or global cataclysm, we expect similar favourable conditions in the CDN market. \subsubsection{Revenue Potential}\label{revenue-potential} During stage one, we have a simple method to estimate the revenue of this business: Assume a CP needs 8Tbps bandwidth for delivering its video content, 1\% of its traffic is 80Gbps. For the general case of CDN bandwidth price, HKD~$30,000$/Gbps/Month, 1\% of his traffic will cost HKD~$2.4$ million. For our Fog CDN, we need only around $8,000$ signed smart routers to share their idle uploading peak bandwidth less than 10Mbps. With our pricing strategy, we will only charge this CP HKD~$1.2$ million as the service price. In this case, the CP will save HKD~$1.2$ million to and be able to purchase the broadcasting rights of more video content, and we will also have the flexibility to manage our income. For example, we could return HKD~$600$k cash or equivalent VIP memberships to the $8,000$ signed users, and retain left HKD~$600$k as profit. The above scenario only shows the starting case of taking 1\% of this CP's data traffic. The business is clearly scalable, because if we have more signed home/business routers and idle bandwidth, we will be able to take more traffic volume. Above all, there is only one CP for this illustrative example. In reality, we can provide this Fog CDN to multiple CPs with both a sweet price and good quality. Our target is to serve as many CPs as possible within our capability. \subsection{Product \& Service Plan} Pear has divided its product and service marketing plan into three stages, as describes in Table~\ref{tb:product-market-plan}. \begin{table}[htb] \centering \caption{Pear's first three stages of its product and service and marketing plan.}\label{tb:product-market-plan} \footnotesize \begin{tabular}{p{0.11\linewidth}p{0.28\linewidth}p{0.28\linewidth}p{0.28\linewidth}} \toprule Stage & Stage 1 & Stage 2 & Stage 3 \\ \midrule Time & Year 0-1.5 & Year 1.5-2 & Year 2+ \\ End-users & Low awareness of Pear's Fog Computing \& sharing economy philosophy & High awareness of Pear's services & Actively install Pear to their own devices to join Pear's world\\ Cooperating Firms & {Pear has no user base at this stage. We need to cooperate with large user-base companies to build up the Pear Virtual Network: HW: MeegoPad, AllWinner, Huawei, Intel; CP: Tencent Video, imeme.tv; Pear's own device: in design} & {Pear will have built up a broad-range network. Cooperating firms (mostly CPs) gradually become Pear's customers} & {Pear will not be depending solely on the end-user base of cooperating companies}\\ Target Customers & {Testing with cooperated firms; small or medium CPs} & {Large CPs, especially cooperating companies} & All web CPs\\ \bottomrule \end{tabular} \end{table} \subsubsection{R\&D Milestones} Pear plans to launch the Fog email delivery and Fog CDN services at the same time since quite a number of elements overlap. It is highly efficient to reuse the resources while achieving multiple targets, although the email delivery source may not be used as thoroughly as the Fog CDN. The detailed milestones are shown in Table~\ref{tb:rd_milestone}. \begin{table} \centering \caption{Pear's R\&D Milestones}\label{tb:rd_milestone} \small \begin{tabular}[t]{ccp{0.68\linewidth}} \toprule \multicolumn{2}{c}{Period} \\ \cmidrule(r){1-2} From & To & {\textsc{~~~~~~~~~~}Description}\\ \midrule 01/02/2016 & 01/03/2016 & {1. Basically finish the protocol, API, and architecture designs for Pear's fog computing system.\newline 2. Establish one or two partnerships in which we help partners solve cost optimisation problems and hopefully gain some referrals and/or more attractive contracts.}\\ 01/03/2016 & 01/09/2016 & {Implement Pear's fog computing protocols on the firmware of Pear's routers and/or IPTV set-top boxes (all-in-one devices).}\\ 01/09/2016 & 01/10/2016 & {1. Enable Pear's fog computing system on the live streaming platform(s) of partner(s) of Pear.\newline 2. Provide open source versions of some components of Pear's fog computing project under MIT, Apache, BSD or GPL license(s), and at the same time maintain a commercial version.\newline 3. Create real impacts in the corresponding industry, especially the open source communities.}\\ 01/10/2016 & 01/02/2017 & {1. Complete the project developed for Partner 1 (Probably ``Fog'' email delivery and HD video transmission).\newline 2. Complete the project developed for Partner 2 (``Fog'' live streaming service platform).}\\ 01/02/2017 & 01/12/2017 & {Launch and complete the project developed for Partner 3 (“Fog” Multimedia CDN)}\\ \bottomrule \end{tabular} \end{table} \subsection{Marketing and Sales Strategy} We have carefully thought through the four Ps of marketing: product, promotion, place, and pricing. Our strategies for each of these are introduced below. \subsubsection{Product Strategy} Pear's Fog CDN service is designed to run like a duet: it serves both the CPs \& ISPs and the end-users simultaneously, like a precise driving gear powering its driven counterparts automatically. Pear is already prepared to cooperate with ISPs who have a large user base but are weak in cloud data centres (such as China Mobile) and hardware vendors (such as Huawei). Through this fundamental work, the end-users will enjoy: \begin{enumerate} \item Faster Internet access and a better video streaming experience; \item Remote control, monitoring and management for the signed smart devices; \item Real cash/coupons or VIP service as a reward for sharing their idle bandwidth. \end{enumerate} Pear is ready to provide high-quality CDN services, initially mainly for online video CPs, promising to reduce operating costs significantly. For these wise content providers, they can enjoy: \begin{enumerate} \item Better streaming quality and transmission efficiency of CDN services; \item Better geographical access coverage; \item Significantly lower content delivery cost; \item ``Flash-crowd'' and ``bottle-neck'' headaches minimisation. \end{enumerate} \subsubsection{Promotion Strategy} Pear plans to use common channels, like social media and mass media, for public awareness. At the same time, Pear is leveraging media resources of device vendors (agreed), Intel (agreed), Tencent, and JD.com crowd-funding for promoting the fog computing devices and services. There are three main methods Pear is going to use for promotion in B2C model as illustrated in Figure~\ref{fig:promotion-strategy}. \begin{figure}[ht] \centering \includegraphics[width=.80\textwidth]{fig/biz/promotion_strategy.png} \caption{Promotion strategies for Pear's B2C Model.} \label{fig:promotion-strategy} \end{figure} \begin{enumerate} \item Cash rewards or interest-free instalments as incentives. Pear even can deliver the smart routers for free to end-users who sign an agreement to stay online 24/7 to provide bandwidth for the Pear Fog, thus helping the network accommodate more traffic or content delivery volume. \item CP VIP memberships to leverage activities or direct exchange with end-users, so they will contribute bandwidth to support more network traffic. \item Cooperation with the ISPs and/or telecom operators, such as China Mobile. Pear will be able to provide them with the scaled end-users' contributed traffic volume through cellular phones' data networks. \end{enumerate} \subsubsection{Place and Channel Strategy} Initially, Pear must partner with vendor companies to bundle Fog services with their smart devices, such as routers and TV boxes, as well as mini PCs to establish a wider user base among the general public. For most of the initial stage, Pear will not face consumers directly, so Pear must focus on its B2B channel to first help vendors with their bandwidth needs. However, at a later stage, Pear would pay much more attention to its B2C channel, which is related to the life and death of Pear in the long run. Otherwise, vendors would eventually develop their own in-house fog platforms and go around us, thus leaving us without work to do. Facing customers will not only help with our longevity, but it will also help us better understand their needs and wants and serve them directly. Thus, Pear will pay full attention to all possible channels that could reach the consumers. % Only when we could face with customers directly, we have the initiative of development and going concern. So Pear would pay full attention to all possible channels that could reach the consumers. \subsubsection{Pricing Strategy} For Pear's Fog CDN service, its price will initially be about HKD~$12,000-15,000$/Gbps/month. This price is about 40\% of the currently cheapest traditional CDN competitors in Mainland China. Pear is also considering other flexible pricing schemes for different scenarios, {\em e.g.}, by total traffic/size of data, by user base, by coverage of outlying regions and edge ISPs, and by the load shifting effect. Pear's aim is to always be to provide equivalent or better quality CDN services at less than half of the original pure-traditional CDN price. \subsection{Competition} Pear is an innovator in the relatively mature traditional CDN market. We will face challenges from existing giants who are also considering Fog CDN as well as from the other innovators with similar Fog CDN services. On the other hand, these competitors could also be Pear's customers and partners. Thus, Pear keeps an open mind to the competition and expects all interested communities and individuals to join in the fog computing world to explore and contribute. One proof of this open-mindedness is that Pear has already kept and will always keep all wheel-like core components open source. This is similar to the early Microsoft model of allowing its software (MS-DOS) to be freely copied all over the world, which gave it a clear victory over IBM's PC-DOS, which became the standard for most PCs in the 1980s. IBM did not foresee the rampant of ``file sharing'' of PC retailers in countries outside the US, nor did it expect Bill Gate's tiny start-up to actually gain so much from it. This was all thanks to a non-exclusive agreement that the tiny start-up signed with the computing giant in 1980 \cite{ms-ibm-dos}. \subsubsection{Traditional CDN Competitors in Mainland China} In China, there are two outstanding traditional CDN giants to whom Pear is paying attention: ChinaNetCenter and ChinaCache. In 2014, ChinaNetCenter had a market share of about 43\%, and ChinaCache about 37\%. In 2015, ChinaNetCenter had revenue over RMB 2 billion, with a market capitalization at around RMB 30 billion, and ChinaCache had a market capitalization at USD 185 million while its revenue was around USD 220 million. Among the two CDN giants, ChinaCache is more willing to access new technology, since it has recently signed a cooperation contract with HiWiFi Router and Youku LuYouBao. Pear looks upon ChinaCache as one of the biggest competitors, and sincerely admires its strategy as well as executive power. On the contrary, Pear looks forward to potential cooperation opportunities with ChinaNetCenter. \subsubsection{New-born Competitors in China Mainland} From 2015 till now, Pear only has two new competitors in the Fog CDN market: Xunlei (Thunder) XYCDN\footnote{\url{http://www.xycdn.com/}} and Youku LuYouBao\footnote{\url{http://yj.youku.com/luyou}}. Xunlei originally is a download manager and Peer-to-peer software developed by Thunder Networking Technologies, supporting HTTP, FTP, eDonkey, and BitTorrent protocols. As of 2010, it was the most commonly used BitTorrent client in the world. On 24 June 2014, it went public on the Nasdaq Stock Exchange, raising 88 million USD. Xunlei's advantage concentrates on file downloading techniques which are essential for Fog CDN. Moreover, now Xunlei has just adjusted their strategic direction to ``crowd-sourced CDN''. Their CDN, called XYCDN, is their featured product right now. The product is still naive but has efficient iterations. Xunlei has just announced their 2nd Generation ZhuanQianBao miner: a low-cost mini server which when plugged into users' home routers, is ready for sharing not only idle bandwidth but also storage. Youku Tudou Inc. is one of China's biggest video CPs, having a market capitalization of over USD 5 billion. It is aggressively investing in innovative technology that enhances its services while reduces its cost. Recently, it was reported that Youku had sold over 500k 1st generation LuYouBao intelligent network terminals in 2015. Different from the Xunlei ZhuanQianBao miner, LuYouBao is a smart router with full functions. Youku LuYouBao signed a co-development contract with ChinaCache in 2015, so Pear sees these joined forces as great competitors. \subsubsection{New-born Competitors outside of the Greater China} Unlike the Chinese competitors who focus on CDN hardware, Pear's international competitors are leading the software and platform design for the P2P CDN industry. One of the competitors is named Peer5. Established in 2012, Peer5 is a CDN provider that leverages WebRTC (see Appendix B) to improve content delivery with the assistance of P2P technologies. Peer5's offerings include a live streaming CDN, a radio streaming CDN, a big object downloader, a VoD CDN and image loading service. Peer5 has already received angel investment and has over ten staff working full-time. The idea of leveraging WebRTC protocol coincides with Pear's Fog CDN R\&D plan. This fact gives Pear confidence, and Pear appreciates Peer5's courage to be the first mover to help the P2P CDN industry get a second wind. Currently, Peer5 is not doing much in China, but if Pear expands outsides of China, especially in western countries, Peer5 is likely to be a competitor. \subsubsection{Pear's Comparative Advantages} \begin{itemize} \item Pear's comparative advantages over traditional competitors\\ Although a traditional CDN is easy to schedule in the initial stage, two critical shortcomings lie in front of a traditional CDN company when it is going to scale up. One is the cost. Even for the biggest traditional CDN provider with sophisticated cost control, the bandwidth's price is still two to three times as much as that of the Pear's Fog CDN. The other is the geographic limitation. Since traditional CDN deployment requires data centres, the outlying regions and edge ISPs typically meet trouble to set up CDN servers. On the contrary, because end-users' smart devices are working as distributed CDN servers, Pear's Fog CDN servers can instantly work anywhere Internet users exist. Pear will never face the same problems as its traditional CDN competitors do when scaling up or expanding geographically. This is similar to the advantage Microsoft had over IBM in the 1980s. \item Pear's comparative advantages over new-born competitors in China\\ The new-born Chinese competitors all have one problem in common: neglecting the system architecture design at the beginning. It is understandable that companies have pressure to bring in income as soon as possible. However, in Xunlei XYCDN's case, stuffing the miner with outdated HTTP server techniques along with proprietary protocols as a crowd-sourced CDN server, has created hidden risks in case other competitors prove that the WebRTC protocol is overwhelmingly useful for Fog services, on which Pear is now working. With old and proprietary (and exclusive) protocols and modules, Xunlei's CDN service is completely Web-unfriendly: the end-users need to install apps or clients; the served CPs need to modify their source code to call Xunlei's services as well. Thus, they are not user and CP transparent. So these issues will be a stumbling block to Xunlei in the future if they cannot realise it and rectify it in time. The differences between Xunlei's hardware and Pear's hardware are briefly summarised in Figure~\ref{fig:hw-comp-xunlei}. \begin{figure}[ht] \centering \includegraphics[width=.88\textwidth]{fig/biz/hw_comp_xunlei.png} \caption{Comparison between Xunlei's and Pear's hardware.} \label{fig:hw-comp-xunlei} \end{figure} \item Pear's comparative advantages over new-born global competitors\\ When we consider competitors like Peer5, it is rather respectful and admirable to have such a strong R\&D team fighting on the frontier. WebRTC is an advanced, future-oriented protocol for communication between any browsers. It can easily enable P2P communication and maintain the web-friendliness at the same time. That is why Pear shares a similar concept for implementing WebRTC protocol as the infrastructure of Pear's Fog CDN. However, there is one problem that Peer5 may have considered but has no solutions for right now. Peer5's CDN service is based on the web browsers on desktop PCs, whose behaviour is unpredictable because the user behaviour behind them is random. In large-scale commercialised services, Peer5's performance will be affected, and they need to find a way to try to keep most of the nodes always working online. Bur it is hard, because they have no enough monetary incentive to encourage the end-users to keep their PCs and browsers running 24/7. Pear has chosen another approach --- a deliberate method to ensure each nodes' stability as a Fog CDN server. We are embedding the WebRTC protocol directly into routers with pure C language. Experienced engineers will know the difficulties on the way to success, and we are determined to achieve success on the way. We are now working to overcome the highest hurdles for popularising the Fog computing technology into reality. We are also seeking talented engineers and professionals to join us. Pear has another inherent advantage: geographic proximity. Pear is based in Hong Kong and Shenzhen, which enables us to develop connections with various router, TV-box and mini PC vendors in these two thriving cities. This makes it easy to cooperate and receive technical support more easily, compared with Peer5 or other competitors outside China. \item Pear's comparative advantages over other start-ups by fresh graduates\\ Pear's founders have an unusual background. The three of them combined have a dozen years of professional experience in the networking field, and two of them are currently pursuing postgraduate degrees at HKUST in the prestigious TLE program. Combining their connections and resources from the industry with their advanced research work, they have put together a dream team for Fog CDN services and smart router innovation. They are not merely IT guys. With technical experience, not are they academics with lots of conceptual knowledge but no practical industry experience. They have the best of both worlds. %Pear is a little bit unusual for its background. Three of the co-founders have years of working experience, and two of them are back to university although they already have achievements in their career. They brought back the connections and resources from the industry and through the research work in HKUST, they polished their entrepreneurship ideas. Finally, with endless passions, these guys started the new story at the ever highest point, and this is how pear begins. %Moreover, also this is the one difference between Pear and the other start-ups mainly composed of PhDs and professors who have never or rarely been deeply involved in the real industry. \end{itemize} In summary, Table~\ref{tb:features-pearcompetitors}, Figure~\ref{fig:cost-performance-competitors} and Figure~\ref{fig:all-essences-advantage} provide comparisons of Pear with its primary competitors. \begin{table}[hb] \footnotesize \centering \caption{Features of Pear Fog VDN and its competitors}\label{tb:features-pearcompetitors} \begin{tabular}[t]{p{0.08\linewidth}p{0.05\linewidth}p{0.05\linewidth}p{0.06\linewidth}p{0.05\linewidth}p{0.25\linewidth}p{0.14\linewidth}p{0.10\linewidth}} \toprule Product & Wi-Fi AP & Media CDN & Patented & Rebate profit to end-users & Price @ CP side & Coverage & Targeted Customer\\ \midrule Pear & Yes & Yes & Yes & Yes & HKD~$12$K/Gbps/month & Worldwide\tablefootnote{We start with the Greater China and branch out in Asia; One Belt, One Road (OBOR) countries will also be target regions: they have 60\% of the world's population and way be happier with fog.} & Any CP\\ Thunder XYCDN & No & Yes & No & Yes & CNY~$10$K/Gbps/month & China & Large CP\\ ChinaNet-Center & No & Yes & No & No & CNY~$60$K+/Gbps/month & Mainly China & Traditional Websites\\ Akamai & No & Yes & Yes & No & Depends on service region, generally expensive & Worldwide (except China) & Traditional Websites\\ \bottomrule \end{tabular} \end{table} \begin{figure}[ht] \centering \includegraphics[width=.8\textwidth]{fig/biz/cost-performance-competitors.png} \caption{Cost/Performance view on Pear and its competitors.} \label{fig:cost-performance-competitors} \end{figure} \begin{figure}[htb] \centering \includegraphics[width=.8\textwidth]{fig/biz/all-essences-advantage.png} \caption{Illustration of why Pear is ``tasty''.} \label{fig:all-essences-advantage} \end{figure} \subsubsection{Potential Competitors in Emerging Fields} Potential competitors in emerging fields may be grouped into two categories: \begin{itemize} \item Cloud WebRTC Service Providers \item IoT Fog Computing Service Providers \end{itemize} The first group is characterised by products which are enabling mobile apps and web pages with real-time communication capabilities. They offer the web and mobile SDKs that connect to their cloud WebRTC services and charge business users based on total connections, sessions or bits. An example is Agora, founded by YY Live's co-founder and ex-CTO. Agora raised USD 25.9 million in its Series A and B investments in 2015. It then sponsored the world's most influential WebRTC conference and translated a WebRTC standard book to Chinese, which made it the most well-known WebRTC-specialised technology company in China. The second category is characterised by businesses that are bringing intelligence to the edge. FogHorn is a such example. It provides an edge software stack for industrial IoT that ingests the data from sensors and industrial devices onto a high-speed data bus and then executes user-defined analytics expressions on the data stream to gain insights and optimise the devices. ForHorn secured USD 12 million in Series A funding on 27 July 2016. Pear acknowledges strong competition from these competitors. However, viewed from another angle, the competition will help bring the WebRTC and Fog concepts to the industry. Pear's initial revenue source is expected to be from services to Cloud providers, while its own emphasis is the Fog. The Fog requires wide coverage by a huge amount of enabled nodes, while the Cloud only requires a simple ``one-click-enabling''. \subsection{Strategic Partners} Before introducing Pear's strategic partners, it is necessary to have a full view of China's “CP+Vendor+CDN” ecosystem in Figure~\ref{fig:cp-vendor-cdn}. \begin{figure}[ht] \centering \includegraphics[width=.75\textwidth]{fig/biz/cp-vendor-cdn.png} \caption{Rough view of power distribution in the ``CP+Vendor+CDN'' ecosystem.} \label{fig:cp-vendor-cdn} \end{figure} It is not surprising to see the ``BAT (Baidu-Alibaba-Tencent)'' allied pattern in the current market; after all, they are the only three dominant giants in China's IT industry. Right now, Pear has cooperation with Tencent. In the meantime, Pear is trying to be neutral to all CPs, since the quickest way to promote the Fog CDN service is to open it to everyone. We can see that there still exist neutral or unallied formidable players in the industry, and Pear is aiming at prioritising cooperation with these participants, such as Huawei, Pear has already negotiated with Huawei and has reached an initial agreement on co-developing the APIs on top of Huawei Honour router's customised firmware. \subsubsection{Vendor Partners} Pear Fog CDN edge programs are fundamentally designed to be cross-platform and can be installed on every smart device with Windows or Linux OS, {\em e.g.} home routers, TV boxes, PCs, self-hosted servers and even cellular phones. To achieve the optimal result, we chose routers as the best candidates mainly because: \begin{enumerate} \item they can ensure a high probability of 24/7 online connectivity; \item they have a good chance of obtaining public IP addresses, which reduces of at least one layer of NAT traversal, which can mean much better accessibility. \end{enumerate} Pear will not have hardware manufacturing capabilities until January 2017, so Pear has acquired several hardware partners for developing and testing Pear's Fog CDN services. \begin{itemize} \item NetGear Hong Kong\\ NetGear is a US-headquartered global networking company that specialised in producing high-end routers for retail and business markets. NetGear Hong Kong has offered Pear and RADICA four Nighthawk R8000 and one R7000 routers (see Figure~\ref{fig:netgear-r7000-r8000}) for developing and testing the Fog email delivery project. RADICA also proposed to deliver a few thousands of routers in Hong Kong and Taiwan to launch a fog computing platform. \begin{figure}[ht] \centering \includegraphics[width=.7\textwidth]{fig/biz/netgear-r7000-r8000.png} \caption{NetGear Nighthawk R7000 and R8000 Wi-Fi Routers.} \label{fig:netgear-r7000-r8000} \end{figure} \item Huawei Honor\\ Huawei Honor has independent R\&D and marketing teams. In 2015, they sold over two million ``Honor Routers''. The Huawei Honor R\&D team has agreed to open their proprietary APIs to Pear to enable Pear's fog computing services. However, after some small trials, Pear engineers found Honor's VM environment is currently not friendly to native C program development. The porting work has been put on hold for one year. \item QNAP\\ Headquartered in Taiwan, QNAP is the 2nd largest global NAS vendor. Intrigued by Pear's Sharing Fog Computing concepts, QNAP had a meeting with Pear in Shenzhen in early autumn 2016. QNAP expects to see when Pear schedules the computational resources of 5,000,000+ QNAP devices (see example types in Figure~\ref{fig:qnap-x51}) worldwide and brings value added to the device owners. QNAP is willing to promote Pear's software with its own channels. After that meeting, QNAP offered Pear the latest SDK (called QDK) to make the development easier. A tentative plan is to beta test the software by January 2017 and launch the service by March 2017. \begin{figure}[ht] \centering \includegraphics[width=.7\textwidth]{fig/biz/QNAP_x51.jpg} \caption{QNAP x51 Series.} \label{fig:qnap-x51} \end{figure} \item MeegoPad\\ MeeGoPad was the earliest vendors to offer its hardware for Pear's R\&D and testing. In fact, MeeGoPad is the biggest ODM \& OEM for Intel Compute Stick product line in China. They have promised to develop a customised carrier to run Pear's fog services. Pear is preparing the supporting software for the so-called \emph{Pear Stick} or \emph{Pear Sharing Box} at this moment. Beta testing is scheduled for January to March 2016, and Pear hopes to begin marketing it in April 2017 and shipping it to vendors and crowd-funding platforms in May 2017. \begin{figure}[ht] \centering \includegraphics[width=.7\textwidth]{fig/biz/huawei-honor-and-meego-stick.png} \caption{Other carriers of Pear Fog: Huawei Honor Router and MeeGopad Compute Stick.} \label{fig:huawei-honor-and-meego-stick} \end{figure} \end{itemize} \subsubsection{CDN Partners} Shanghai Maichuang Network Technology Co., Ltd. (aka Tan14\footnote{\url{https://www.tan14.cn/}}) is a CDN start-up company with seemingly strong financial strength and based in Shanghai. They have admirably extensive connections with CPs, and their customers have already generated enough profit for scaling up and investing in R\&D. Currently, they have more than 80 CDN nodes distributed in Mainland China and Hong Kong as well as Taiwan. Pear and Tan14 have reached a cooperation agreement to build an entirely new cloud \& fog integrated platform for live streaming by the end of 2016. Pear is responsible for architecture design and software implementation coordination, while Tan14 has promised the customers and the investment. Hopefully it will be a win-win partnership. \subsubsection{CP \& SP Partners} \begin{itemize} \item Tencent\\ Tencent Video is one of the biggest online video content providers in Mainland China. It has a private CDN to support the growing bandwidth demands. However, as Figure~\ref{fig:tencent-youku-cost-growth} depicts, it is now facing a serious cost/revenue bottleneck. Tencent Video and Pear have also reached an agreement for scheduling and testing the Pear Fog CDN when Pear's active routers arrive at a certain number. As mentioned in Section~\ref{revenue-potential}, Tencent Video will immediately resolve their cost bottleneck once they are equipped with Pear's Fog CDN. Besides Tencent Video, Pear also has oral agreements with two other Tencent subsidiaries Qzone's and QQ Video Album's teams plan to schedule the video content delivery through Pear's Fog CDN when it is ready. \begin{figure}[ht] \centering \includegraphics[width=1.00\textwidth]{fig/biz/tencent-youku-cost-growth.png} \caption{Some CPs' cost growth rate.} \label{fig:tencent-youku-cost-growth} \end{figure} To summarise the partnership with Tencent: Pear has the chance to test the Fog CDN serving: \begin{enumerate} \item the largest online video platform in China (in terms of traffic); \item the largest social networking service in China; \item and one of the largest photo album platforms in the world. \end{enumerate} \item RADICA\\ RADICA Systems is an HKUST alumni-owned IT company based in Hong Kong. With 15 years of experience, RADICA has mainly helped Asia Pacific brands and enterprises to effectively perform direct marketing. Over 300 enterprises are now their customers. With the aid of Pear's fog computing platform, RADICA expects to be able to provide its current services at an astonishingly lower price so that they can hopefully increase their customer base. RADICA, Pear and NetGear are now jointly launching a ``fog email delivery'' project. Pear is responsible for the software and RADICA is responsible for the customers and technology support for the email servers'resources. Currently, the project is successful in the first stage; the prototype is working online. In the second stage after Autumn 2016, RADICA and Pear will start a large-scale test in a real commercial scenario. This fog email pushing project is critically important to Pear since it contributes to building the fundamental framework of Pear's fog computing network. Pear will save time in developing its Fog CDN and Fog VPN infrastructures thanks to this fog email pushing product. \end{itemize} \subsection{Operating Plan} \subsubsection{Hiring and Development Plan} Pear plans to scale up to around 10-15 staff by mid-2017, including three owners. Details are in Table~\ref{tb:hiring-plan}. \begin{table}[ht] \centering \caption{Pear's Hiring Plan.}\label{tb:hiring-plan} \begin{tabular}[t]{llr} \toprule Time (mm/yyyy) & Vacant Positions & Number on Plan\\ \midrule 09/2016 & Front-end Engineer & 1\\ 10/2016 & Full-stack Engineer & 1\\ 10/2016 & App Client Engineer & 1\\ 11/2016 & OSS Engineer & 1\\ 12/2016 & Marketing \& Sales Manager & 1\\ 03/2017 & HR \& Admin. Manager & 1\\ 03/2017 & Project Manager & 1\\ \bottomrule \end{tabular} \end{table} Pear's marketing base is in Hong Kong, and its R\&D base is in Shenzhen. Considering some projects under negotiation, Pear may establish a branch in Shanghai in 2017 if needed. If so, the Shanghai branch will be responsible for the collaborative projects with leading IDC/CDN providers or CPs. \subsection{Funding and Financial Plan} Pear has been awarded some funding support from both the Hong Kong and Shenzhen governments. However, for such a big and hard project it is far from enough. Pear has a Series Pre-A round funding plan: HKD $6$ million for 10\% equity ownership, which is expected to happen by February 2017. This should be sufficient for covering expenses at least until April 2018. \subsubsection{Financial Projection} Making financial projections over all possible fog services is impractical at this stage. Herein we only analyse that of the relatively matured streaming service charged by peak (usually the 95th percentile) bandwidth. Figure~\ref{fig:financial-projections}\footnote{Fee: HKD 12,000 per Gbps per month; Peak bandwidth utilization: $70\%$; Non-Recurring Costs: HKD 1.5 million; Number of enabled devices: 20k in 2016, with Sigmoid growth; only calculate the new covered equipment every year (pessimistic); Investment cost: $9.0\%$; User rebate: $30\%$; Tax rate: $25.0\%$} shows a rough 5-year financial projection of Pear. It indicates that: \begin{enumerate} \item Pear is expected to start generating profits in 2017; \item The revenue of Pear is hoped to reach HKD~$100$ million in 2021 with the peak bandwidth pricing model. \end{enumerate} \begin{figure}[ht] \centering \input{fig/biz/financial-projections} \caption{Rough financial projections of Pear in 5 years.} \label{fig:financial-projections} \end{figure} \subsubsection{Exit Strategy and IRR} Table~\ref{tb:exit-strategy-irr} shows the exit strategy and the corresponding return rate. \begin{table}[htbp] \centering \caption{Exit Strategy and IRR}\label{tb:exit-strategy-irr} \begin{tabular}[t]{lrrr} \toprule Cases & Optimistic & Baseline & Pessimistic\\ \midrule Exit Strategy & IPO & Buy Back & M\&A\\ NPV (HKD) & 355,829,000 & 33,778,000 & 5,648,000\\ IRR & $242\%$ & $93\%$ & $51\%$\\ \bottomrule \end{tabular} \end{table} \subsubsection{Use of Investment} Table~\ref{tb:use-of-investment} shows the use of investment which can be roughly divided into four parts. \begin{table}[htbp] \centering \caption{Use of Investment}\label{tb:use-of-investment} \begin{tabular}[t]{ccccc} \toprule Total & Pilot \& Field testing & R \& D & Marketing & G \& A\\ \midrule $6,000$ K & $1,500$ K & $3,800$ K & $500$ K & $200$ K\\ \bottomrule \end{tabular} \end{table} In this recession \& capital winter, Pear will spend about two-thirds of its Series Pre-A round funding on R\&D, in order to build finely crafted products, competitive advantages and barriers to market entry. This long-term investment will generate unexpected results in ``winter to spring'', when there will be a lot of cheap resources ({\em e.g.} dying O2O companies' legacies) available to obtain. \newpage
theorem root_test_divergence: fixes f :: "nat \<Rightarrow> 'a :: banach" defines "l \<equiv> limsup (\<lambda>n. ereal (root n (norm (f n))))" assumes l: "l > 1" shows "\<not>summable f"
If $f$ and $g$ are real-valued functions and $f(x) \leq g(x)$ for all $x$ in some set $S$, and if $f(x)$ and $g(x)$ both tend to $L$ as $x$ tends to $a$, then $L$ is the limit of $f(x)$ and $g(x)$ as $x$ tends to $a$.
[STATEMENT] lemma continuous_on_const[continuous_intros,simp]: "continuous_on s (\<lambda>x. c)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. continuous_on s (\<lambda>x. c) [PROOF STEP] unfolding continuous_on_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>x\<in>s. ((\<lambda>x. c) \<longlongrightarrow> c) (at x within s) [PROOF STEP] by auto
using PolarFact using Test, LinearAlgebra using Random Random.seed!(1103) include("test_newton.jl") include("test_halley.jl") include("test_svd.jl") include("test_hybrid.jl") include("test_f32.jl") # test Float32 case