Datasets:
AI4M
/

text
stringlengths
0
3.34M
State Before: o : Ordinal ⊢ aleph' (succ o) = succ (aleph' o) State After: o : Ordinal ⊢ alephIdx (aleph' (succ o)) ≤ alephIdx (succ (aleph' o)) Tactic: apply (succ_le_of_lt <| aleph'_lt.2 <| lt_succ o).antisymm' (Cardinal.alephIdx_le.1 <| _) State Before: o : Ordinal ⊢ alephIdx (aleph' (succ o)) ≤ alephIdx (succ (aleph' o)) State After: o : Ordinal ⊢ aleph' o < succ (aleph' o) Tactic: rw [alephIdx_aleph', succ_le_iff, ← aleph'_lt, aleph'_alephIdx] State Before: o : Ordinal ⊢ aleph' o < succ (aleph' o) State After: no goals Tactic: apply lt_succ
[STATEMENT] lemma of_weak_ranking_Collect_ge_Cons [simp]: "y \<in> x \<Longrightarrow> of_weak_ranking_Collect_ge (x#xs) y = \<Union>(set (x#xs))" "y \<notin> x \<Longrightarrow> of_weak_ranking_Collect_ge (x#xs) y = of_weak_ranking_Collect_ge xs y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (y \<in> x \<Longrightarrow> of_weak_ranking_Collect_ge (x # xs) y = \<Union> (set (x # xs))) &&& (y \<notin> x \<Longrightarrow> of_weak_ranking_Collect_ge (x # xs) y = of_weak_ranking_Collect_ge xs y) [PROOF STEP] by (auto simp: of_weak_ranking_Cons of_weak_ranking_Collect_ge_def)
From Coq Require Import Reals Psatz. From Coq.ssr Require Import ssreflect ssrfun. From Coquelicot Require Import Rcomplements Rbar Series Lim_seq Hierarchy. From stdpp Require Export countable. From self.prelude Require Export base Coquelicot_ext Reals_ext. From self.prob Require Export countable_sum distribution. Open Scope R. Section couplings. Context `{Countable A, Countable B, Countable A', Countable B'}. Context (μ1 : distr A) (μ2 : distr B) (R : A -> B -> Prop) (S : A' → B' → Prop). Definition isCoupl (μ : distr (A * B)) : Prop := lmarg μ = μ1 ∧ rmarg μ = μ2. Definition coupl := ∃ (μ : distr (A * B)), isCoupl μ. Definition isRcoupl (μ : distr (A * B)) : Prop := isCoupl μ ∧ (∀ (p : A * B), (μ p > 0) -> R (fst p) (snd p)). Definition Rcoupl := ∃ (μ : distr (A * B)), isRcoupl μ. Lemma isRcoupl_isCoupl μ : isRcoupl μ -> isCoupl μ. Proof. intro C; destruct C; auto. Qed. Lemma isCoupl_mass_l μ : isCoupl μ -> SeriesC μ = SeriesC μ1. Proof. intro Hμ. destruct Hμ as (Hμl & Hμr). rewrite <- Hμl. rewrite /lmarg. rewrite <- dmap_mass. auto. Qed. Lemma isCoupl_mass_r μ : isCoupl μ -> SeriesC μ = SeriesC μ2. Proof. intro Hμ. destruct Hμ as (Hμl & Hμr). rewrite <- Hμr. rewrite /rmarg. rewrite <- dmap_mass. auto. Qed. Lemma isCoupl_mass_eq μ : isCoupl μ -> SeriesC μ1 = SeriesC μ2. Proof. intro Hμ. rewrite <- (isCoupl_mass_l μ); auto. rewrite <- (isCoupl_mass_r μ); auto. Qed. End couplings. Section couplings_theory. Context `{Countable A, Countable B, Countable A', Countable B'}. Lemma isCoupl_dret (a : A) (b : B) : isCoupl (dret a) (dret b) (dret (a, b)). Proof. split; [rewrite /lmarg dmap_dret // |rewrite /rmarg dmap_dret //]. Qed. Lemma coupl_dret (a : A) (b : B) : coupl (dret a) (dret b). Proof. exists (dret (a, b)). apply isCoupl_dret. Qed. Lemma isRcoupl_dret (a : A) (b : B) (R : A → B → Prop) : R a b → isRcoupl (dret a) (dret b) R (dret (a, b)). Proof. split; [apply isCoupl_dret |]. intro p. rewrite /pmf /= /dret_pmf /=. case_bool_decide as Hp; [rewrite Hp //| lra]. Qed. Lemma Rcoupl_dret (a : A) (b : B) (R : A → B → Prop) : R a b → Rcoupl (dret a) (dret b) R. Proof. exists (dret (a, b)). apply isRcoupl_dret. auto. Qed. Lemma Rcoupl_mass_eq (μ1 : distr A) (μ2 : distr B) (R : A → B → Prop) : Rcoupl μ1 μ2 R → SeriesC μ1 = SeriesC μ2. Proof. intros (?&?&?). by eapply isCoupl_mass_eq. Qed. Lemma Rcoupl_eq (μ1 : distr A) : Rcoupl μ1 μ1 (=). Proof. exists (ddiag μ1); split; [split | ]. + apply distr_ext. intro a. rewrite lmarg_pmf. rewrite {1}/pmf/=/dbind_pmf/=. rewrite SeriesC_singleton'; auto. + apply distr_ext. intro a. rewrite rmarg_pmf. rewrite {1}/pmf/=/dbind_pmf/=. (* TODO: Need lemma to rewrite these singletons *) rewrite (SeriesC_ext _ (λ a0 : A, if bool_decide (a0 = a) then μ1 a else 0)); [rewrite SeriesC_singleton; auto | ]. intro a'; case_bool_decide; simplify_eq; auto. + intros (a1 & a2) Hpos; simpl. rewrite /pmf/= in Hpos. case_bool_decide; simplify_eq; auto; lra. Qed. Lemma coupl_sym (μ1 : distr A) (μ2 : distr B) : coupl μ1 μ2 -> coupl μ2 μ1. Proof. intros (μ & HμL & HμR). exists (dmap (λ '(a, b), (b, a)) μ); split; apply distr_ext. + intro b. rewrite <- HμR. rewrite lmarg_pmf rmarg_pmf. apply SeriesC_ext; intro a. simpl. rewrite {1}/pmf /= /dbind_pmf /=. rewrite {2}/pmf /= /dret_pmf /=. assert (∀ a0, μ a0 * (if bool_decide ((b, a) = (let '(a1, b0) := a0 in (b0, a1))) then 1 else 0) = if bool_decide ((a, b) = a0 ) then μ (a, b) else 0) as Heq1. { intros (a' & b'). case_bool_decide; case_bool_decide; simplify_eq; try lra. } rewrite (SeriesC_ext _ _ Heq1). apply SeriesC_singleton'. + intro a. rewrite <- HμL. rewrite lmarg_pmf rmarg_pmf. apply SeriesC_ext; intro b. simpl. rewrite {1}/pmf /= /dbind_pmf /=. rewrite {2}/pmf /= /dret_pmf /=. assert (∀ a0, μ a0 * (if bool_decide ((b, a) = (let '(a1, b0) := a0 in (b0, a1))) then 1 else 0) = if bool_decide ((a, b) = a0 ) then μ (a, b) else 0) as Heq1. { intros (a' & b'). case_bool_decide; case_bool_decide; simplify_eq; try lra. } rewrite (SeriesC_ext _ _ Heq1). apply SeriesC_singleton'. Qed. Lemma coupl_dbind (f : A → distr A') (g : B → distr B') (μ1 : distr A) (μ2 : distr B) : (∀ a b, coupl (f a) (g b)) → coupl μ1 μ2 → coupl (dbind f μ1) (dbind g μ2). Proof. intros Hfg (μ & Hμ). rewrite /coupl in Hfg. assert (∀ (p : A * B), ∃ μ : distr (A' * B'), isCoupl (f p.1) (g p.2) μ) as Hfg'; auto. pose proof (Choice (A * B) (distr (A' * B')) _ Hfg') as Ch. rewrite /coupl. destruct Ch as (Ch & HCh). exists (dbind Ch μ); split. + apply distr_ext; intro a'. rewrite lmarg_pmf. rewrite {1 2}/pmf/=/dbind_pmf. rewrite <- distr_double_swap_lmarg. setoid_rewrite SeriesC_scal_l. assert (∀ p , μ p * SeriesC (λ b' : B', Ch p (a', b')) = μ p * f p.1 a') as Heq2. { intros (a & b). specialize (HCh (a, b)) as (HChL & HChR). rewrite <- HChL. rewrite lmarg_pmf. auto. } rewrite (SeriesC_ext _ _ Heq2). rewrite fubini_pos_seriesC_prod_lr; auto. 2:{simpl; intros; apply Rmult_le_pos; auto. } 2:{apply (ex_seriesC_le _ μ); auto. intros; split; [apply Rmult_le_pos; auto | ]. rewrite <- Rmult_1_r; apply Rmult_le_compat; auto. apply Rle_refl. } assert (∀ a : A, SeriesC (λ b : B, μ (a, b) * f (a, b).1 a') = SeriesC (λ b : B, μ (a, b) ) * f a a') as Heq3. { intro a; simpl; apply SeriesC_scal_r. } rewrite (SeriesC_ext _ _ Heq3). assert (∀ a, SeriesC (λ b : B, μ (a, b)) = μ1 a) as Heq4. { intro a. destruct Hμ as (Hμ1 & Hμ2). rewrite <- Hμ1; rewrite lmarg_pmf; auto. } apply SeriesC_ext. intro a. rewrite (Heq4 a); auto. (* The second half is esentially the same as the first, can it be proven somehow by symmetry? *) + apply distr_ext; intro b'. rewrite rmarg_pmf. rewrite {1 2}/pmf/=/dbind_pmf. rewrite <- distr_double_swap_rmarg. setoid_rewrite SeriesC_scal_l. assert (∀ p , μ p * SeriesC (λ a' : A', Ch p (a', b')) = μ p * g p.2 b') as Heq2. { intros (a & b). specialize (HCh (a, b)) as (HChL & HChR). rewrite <- HChR. rewrite rmarg_pmf. auto. } rewrite (SeriesC_ext _ _ Heq2). rewrite fubini_pos_seriesC_prod_rl; auto. 2:{simpl; intros; apply Rmult_le_pos; auto. } 2:{apply (ex_seriesC_le _ μ); auto. intros; split; [apply Rmult_le_pos; auto | ]. rewrite <- Rmult_1_r; apply Rmult_le_compat; auto. apply Rle_refl. } assert (∀ b : B, SeriesC (λ a : A, μ (a, b) * g (a, b).2 b') = SeriesC (λ a : A, μ (a, b) ) * g b b') as Heq3. { intro b; simpl; apply SeriesC_scal_r. } rewrite (SeriesC_ext _ _ Heq3). assert (∀ b, SeriesC (λ a : A, μ (a, b)) = μ2 b) as Heq4. { intro b. destruct Hμ as (Hμ1 & Hμ2). rewrite <- Hμ2; rewrite rmarg_pmf; auto. } apply SeriesC_ext. intro b. rewrite (Heq4 b); auto. Qed. Lemma Rcoupl_dbind (f : A → distr A') (g : B → distr B') (μ1 : distr A) (μ2 : distr B) (R : A → B → Prop) (S : A' → B' → Prop) : (∀ a b, R a b → Rcoupl (f a) (g b) S) → Rcoupl μ1 μ2 R → Rcoupl (dbind f μ1) (dbind g μ2) S. Proof. intros Hfg (μ & HμC & HμS). rewrite /Rcoupl /isRcoupl in Hfg. (* First we rewrite Hfg to be able to use Choice *) assert (∀ p, ∃ μ', R p.1 p.2 → (isCoupl (f p.1) (g p.2) μ' ∧ (∀ q : A' * B', μ' q > 0 → S q.1 q.2))) as Hfg'; auto. { intro p. specialize (HμS p). specialize (Hfg p.1 p.2). pose proof (ExcludedMiddle (R p.1 p.2)) as H3; destruct H3 as [HR | HnR]. + specialize (Hfg HR). destruct Hfg as (μ' & Hμ'1 & Hμ'2). exists μ'; auto. + exists dzero; intro ; done. } pose proof (Choice (A * B) (distr (A' * B')) _ Hfg') as (Ch & HCh). rewrite /Rcoupl /isRcoupl. exists (dbind Ch μ); split; try split. (* To prove that the first marginal coincides is a matter of rearranging the sums and using the fact that μ and (Ch p) are couplings *) + apply distr_ext; intro a'. rewrite lmarg_pmf. rewrite {1 2}/pmf/=/dbind_pmf. rewrite <- distr_double_swap_lmarg. setoid_rewrite SeriesC_scal_l. erewrite (SeriesC_ext _ (λ p, μ p * f p.1 a')); last first. { intros (a & b). destruct (Rtotal_order (μ (a, b)) 0) as [Hlt | [Heqz | Hgt]]. - pose proof (pmf_pos μ (a, b)); lra. - rewrite Heqz; lra. - specialize (HCh (a, b) (HμS (a, b) Hgt )) as ((HChL & HChR) & HChS). rewrite -HChL lmarg_pmf //=. } rewrite fubini_pos_seriesC_prod_lr; auto. 2:{simpl; intros; apply Rmult_le_pos; auto. } 2:{apply (ex_seriesC_le _ μ); auto. intros; split; [apply Rmult_le_pos; auto | ]. rewrite <- Rmult_1_r; apply Rmult_le_compat; auto. apply Rle_refl. } erewrite (SeriesC_ext _ (λ a, SeriesC (λ b : B, μ (a, b) ) * f a a')); [ | intro a; simpl; apply SeriesC_scal_r ]. erewrite (SeriesC_ext _ (λ a, (μ1 a) * f a a')); auto. intro a. destruct HμC as (Hμ1 & Hμ2). rewrite <- Hμ1; rewrite lmarg_pmf; auto. (* The second half is esentially the same as the first, can it be proven somehow by symmetry? *) + apply distr_ext; intro b'. rewrite rmarg_pmf. rewrite {1 2}/pmf/=/dbind_pmf. rewrite <- distr_double_swap_rmarg. setoid_rewrite SeriesC_scal_l. erewrite (SeriesC_ext _ (λ p, μ p * g p.2 b')); last first. {intros (a & b); destruct (Rtotal_order (μ (a, b)) 0) as [Hlt | [Heqz | Hgt]]; [ pose proof (pmf_pos μ (a, b)); lra | rewrite Heqz; lra | specialize (HCh (a, b) (HμS (a, b) Hgt)) as ((HChL & HChR) & HChS); rewrite -HChR rmarg_pmf //=]. } rewrite fubini_pos_seriesC_prod_rl; auto. 2:{simpl; intros; apply Rmult_le_pos; auto. } 2:{apply (ex_seriesC_le _ μ); auto. intros; split; [apply Rmult_le_pos; auto | ]. rewrite <- Rmult_1_r; apply Rmult_le_compat; auto. apply Rle_refl. } erewrite (SeriesC_ext _ (λ b, SeriesC (λ a : A, μ (a, b) ) * g b b')); [ | intro b; simpl; apply SeriesC_scal_r]. erewrite (SeriesC_ext _ (λ b, (μ2 b) * g b b')); auto. intro b. destruct HμC as (Hμ1 & Hμ2). rewrite <- Hμ2; rewrite rmarg_pmf; auto. + intros (a' & b') H3; simpl. pose proof (dbind_pos_support Ch μ (a', b')) as (H4 & H5). specialize (H4 H3) as ((a0, b0) & H7 & H8). specialize (HCh (a0, b0) (HμS (a0, b0) H8)) as (HCh1 & HCh2). specialize (HCh2 (a', b') H7). done. Qed. Lemma Rcoupl_eq_elim (μ1 μ2 : distr A) : Rcoupl μ1 μ2 (=) → μ1 = μ2. Proof. intros (μ & (HμL & HμR) & HμS). rewrite <- HμL, <- HμR. apply distr_ext. intro a1. rewrite lmarg_pmf rmarg_pmf. apply SeriesC_ext. intro a2. specialize (HμS (a1, a2)) as HμS12. specialize (HμS (a2, a1)) as HμS21. simpl in HμS12. simpl in HμS21. pose proof (Rtotal_order (μ (a1, a2)) (μ (a2, a1))) as [Hlt | [Heq | Hgt]]; auto. + pose proof (pmf_pos μ (a1, a2)). assert (μ (a2, a1) > 0) as H'; try lra. specialize (HμS21 H'); destruct HμS21; auto. + pose proof (pmf_pos μ (a2, a1)). assert (μ (a1, a2) > 0) as H'; try lra. specialize (HμS12 H'); destruct HμS12; auto. Qed. Lemma Rcoupl_eq_sym (μ1 μ2: distr A) : Rcoupl μ1 μ2 eq → Rcoupl μ2 μ1 eq. Proof. intros Hc. apply Rcoupl_eq_elim in Hc as ->; auto. apply Rcoupl_eq. Qed. Lemma Rcoupl_eq_trans (μ1 μ2 μ3 : distr A) : Rcoupl μ1 μ2 eq → Rcoupl μ2 μ3 eq → Rcoupl μ1 μ3 eq. Proof. by intros ->%Rcoupl_eq_elim ?. Qed. Lemma Rcoupl_weaken (μ1 : distr A) (μ2 : distr B) (R : A → B → Prop) (S : A → B → Prop): Rcoupl μ1 μ2 R → (∀ a b, R a b -> S a b) → Rcoupl μ1 μ2 S. Proof. intros [μ [[HμL HμR] HμSupp]] Hwk. exists μ; split; [split | ]; auto. Qed. Definition Rcoupl_impl μ1 μ2 R S H RC := Rcoupl_weaken μ1 μ2 R S RC H. Lemma Rcoupl_inhabited_l (μ1 : distr A) (μ2 : distr B) R : Rcoupl μ1 μ2 R → SeriesC μ1 > 0 → ∃ a b, R a b. Proof. intros [μ [Hcpl HR]] Hz. assert (SeriesC μ > 0) as Hsup by by erewrite isCoupl_mass_l. apply SeriesC_gtz_ex in Hsup as [[a b] Hμ]; [|done]. eauto. Qed. Lemma Rcoupl_inhabited_r (μ1 : distr A) (μ2 : distr B) R : Rcoupl μ1 μ2 R → SeriesC μ2 > 0 → ∃ a b, R a b. Proof. intros [μ [Hcpl HR]] Hz. assert (SeriesC μ > 0) as Hsup by by erewrite isCoupl_mass_r. apply SeriesC_gtz_ex in Hsup as [[a b] Hμ]; [|done]. eauto. Qed. End couplings_theory. (* TODO: cleanup *) Section Rcoupl. Context `{Countable A, Countable B}. Variable (μ1 : distr A) (μ2 : distr B). Lemma Rcoupl_trivial : SeriesC μ1 = 1 -> SeriesC μ2 = 1 -> Rcoupl μ1 μ2 (λ _ _, True). Proof. intros Hμ1 Hμ2. exists (dprod μ1 μ2). split; [|done]. split; [apply lmarg_dprod|apply rmarg_dprod]; done. Qed. Lemma Rcoupl_pos_R R : Rcoupl μ1 μ2 R → Rcoupl μ1 μ2 (λ a b, R a b ∧ μ1 a > 0 ∧ μ2 b > 0). Proof. intros [μ [[Hμ1 Hμ2] HR]]. exists μ. split; [done|]. intros [a b] Hρ. split; [auto|]. rewrite -Hμ1 -Hμ2. rewrite 2!dmap_pos. split; eauto. Qed. End Rcoupl. Lemma Rcoupl_dzero_r_inv `{Countable A, Countable B} μ1 (R : A → B → Prop) : Rcoupl μ1 dzero R → μ1 = dzero. Proof. intros Hz%Rcoupl_mass_eq. apply SeriesC_zero_dzero. rewrite Hz SeriesC_0 //. Qed. Lemma Rcoupl_dzero_l_inv `{Countable A, Countable B} μ2 (R : A → B → Prop) : Rcoupl dzero μ2 R → μ2 = dzero. Proof. intros Hz%Rcoupl_mass_eq. apply SeriesC_zero_dzero. rewrite -Hz SeriesC_0 //. Qed. Lemma Rcoupl_map `{Countable A, Countable B, Countable A', Countable B'} (f : A → A') (g : B → B') (μ1 : distr A) (μ2 : distr B) (R : A' → B' → Prop) : Rcoupl μ1 μ2 (λ a a', R (f a) (g a')) → Rcoupl (dmap f μ1) (dmap g μ2) R. Proof. intros Hcoupl. rewrite /dmap. eapply (Rcoupl_dbind _ _ _ _ (λ (a : A) (a' : B), R (f a) (g a'))); auto. intros a b Hab. apply (Rcoupl_dret (f a) (g b) R Hab). Qed. (* I think this should be true, maybe it can be proven through Strassens theorem, but I don't see how to do it directly *) (* Lemma Rcoupl_from_mapL `{Countable A, Countable B, Countable A', Countable B'}: forall (f : A → A') (μ1 : distr A) (μ2 : distr B) (R : A' → B → Prop), Rcoupl (dmap f μ1) μ2 R -> Rcoupl μ1 μ2 (λ a b, R (f a) b). Proof. intros f μ1 μ2 R (μ & ((HμL & HμR) & HμSup)). eexists (dprod μ1 μ2). split; [split | ]. eexists (MkDistr (λ '(a, b), μ (f a , g b)) _ _ _). Qed. *) (* TODO: move somewhere else *) Definition f_inv {A B} f `{Surj A B (=) f} : B → A := λ b, epsilon (surj f b). Lemma f_inv_cancel_r {A B} f `{Surj A B (=) f} b : f (f_inv f b) = b. Proof. rewrite /f_inv /= (epsilon_correct _ (surj f b)) //. Qed. Lemma f_inv_cancel_l {A B} f `{Inj A B (=) (=) f, Surj A B (=) f} b : f_inv f (f b) = b. Proof. apply (inj f), (epsilon_correct _ (surj f (f b))). Qed. Lemma Rcoupl_fair_coin f `{Inj bool bool (=) (=) f, Surj bool bool (=) f} : Rcoupl fair_coin fair_coin (λ b b', b = f b'). Proof. exists (fair_coins f). repeat split. - eapply distr_ext=> b. rewrite lmarg_pmf /pmf /= /fair_coins_pmf /fair_coin_pmf /=. rewrite (SeriesC_ext _ (λ b', if bool_decide (b' = f_inv f b) then 0.5 else 0)). { rewrite SeriesC_singleton //. } intros b'. case_bool_decide as Heq. + rewrite bool_decide_eq_true_2 //. rewrite Heq f_inv_cancel_l //. + rewrite bool_decide_eq_false_2 //. intros [= ->]. apply Heq. rewrite f_inv_cancel_r //. - eapply distr_ext=> b. rewrite rmarg_pmf /pmf /= /fair_coins_pmf /fair_coin_pmf /=. rewrite SeriesC_singleton //. - intros []. rewrite /pmf /= /fair_coins_pmf /=. case_bool_decide; [done|lra]. Qed. (* NB: Classical proof, but should be possible to make constructive TODO: finish *) Local Lemma pigeonhole_aux1 n f `{Inj nat nat (=) (=) f, Surj nat nat (=) f} : (forall m, (m <= n)%nat -> (f m <= n)%nat) -> (forall m, (m <= n)%nat -> exists p, (p <= n)%nat /\ f p = m). Proof. induction n. - intros Hdom m Hm. inversion Hm; simplify_eq. exists 0%nat; split; auto. specialize (Hdom 0%nat (le_refl 0%nat)); auto with arith. - intros Hdom m Hm. pose proof (ExcludedMiddle (∀ m : nat, m ≤ n → f m ≤ n)) as [Hem | Hem]. + specialize (IHn Hem). inversion Hm. * admit. * destruct (IHn m) as [p [Hp1 Hp2]]; auto. exists p; split; auto with arith. + apply not_forall_exists_not in Hem as [x Hx]. Admitted. Local Lemma pigeonhole_aux2 n f `{Inj nat nat (=) (=) f, Surj nat nat (=) f} : (forall m, (m <= n)%nat -> (f m <= n)%nat) -> (forall m, (f m <= n)%nat -> (m <= n)%nat). Proof. intros Hdom m Hfm. pose proof (H0 m) as [x Hx]. pose proof (pigeonhole_aux1 n f Hdom (f m) Hfm) as [y [Hy1 Hy2]]. specialize (H y m Hy2); simplify_eq; auto. Qed. Lemma Rcoupl_unif_distr n f `{Inj nat nat (=) (=) f, Surj nat nat (=) f} : (forall m, (m <= n)%nat -> (f m <= n)%nat) -> Rcoupl (unif_distr n) (unif_distr n) (λ m m', m' = f m). Proof. intro Hdom. exists (dbind (λ x, dret (x, f x)) (unif_distr n)); repeat split. - eapply distr_ext=> y1. rewrite lmarg_pmf. erewrite (SeriesC_ext _ (λ y2, if bool_decide ( (0 <= y1 <= n)%nat /\ y2 = f y1) then / (INR n + 1) else 0)); last first. { intro. case_bool_decide as H1; destruct_and?; simplify_eq. - apply dbind_dret_unif_nonzero. + intros ? ? ?; simplify_eq; auto. + exists y1; auto. - apply dbind_dret_unif_zero. intros ? ? ?; simplify_eq; apply H1; auto. } rewrite /pmf/=. case_bool_decide as H1. + erewrite (SeriesC_ext); [apply (SeriesC_singleton (f y1)) | ]. intro; simpl. case_bool_decide as H2; case_bool_decide; destruct_and?; simplify_eq; auto. destruct H2; auto with arith. + erewrite (SeriesC_ext _ (λ x, 0)); [apply (SeriesC_0); auto | ]. intro. case_bool_decide; destruct_and?; simplify_eq; auto. destruct H1; auto. - eapply distr_ext=> y2. rewrite rmarg_pmf. erewrite (SeriesC_ext _ (λ y1, if bool_decide ( (0 <= y1 <= n)%nat /\ y2 = f y1) then / (INR n + 1) else 0)); last first. { intro n0. case_bool_decide as H1; destruct_and?; simplify_eq. - apply dbind_dret_unif_nonzero. + intros ? ? ?; simplify_eq; auto. + exists n0; auto. - apply dbind_dret_unif_zero. intros ? ? ?; simplify_eq; apply H1; auto. } rewrite /pmf/=. case_bool_decide as H1. + erewrite (SeriesC_ext). * apply (SeriesC_singleton_inj y2 f); auto. * intro y1; case_bool_decide as H2; case_bool_decide; destruct_and?; simplify_eq; auto. destruct H2; split; auto; split; auto with arith. apply (pigeonhole_aux2 n f); auto. + erewrite (SeriesC_ext); [apply SeriesC_0; done | ]. intro m; simpl. case_bool_decide; destruct_and?; simplify_eq; auto. destruct H1. apply Hdom; done. - intros (m1 & m2) Haux; simpl. rewrite /pmf/=/dbind_pmf in Haux. apply SeriesC_gtz_ex in Haux as [l Hl]; auto. + rewrite /pmf/=/dret_pmf/= in Hl. case_bool_decide; case_bool_decide; destruct_and?; simplify_eq; auto; lra. + intro; rewrite /pmf/=/dret_pmf. case_bool_decide; case_bool_decide; try lra. rewrite Rmult_1_r. left; apply RinvN_pos. Qed. Lemma Rcoupl_fair_conv_comb `{Countable A, Countable B} f `{Inj bool bool (=) (=) f, Surj bool bool (=) f} (S : A → B → Prop) (μ1 μ2 : distr A) (μ1' μ2' : distr B) : (∀ a, Rcoupl (if f a then μ1 else μ2) (if a then μ1' else μ2') S) → Rcoupl (fair_conv_comb μ1 μ2) (fair_conv_comb μ1' μ2') S. Proof. intros HS. rewrite /fair_conv_comb. eapply Rcoupl_dbind; [|apply (Rcoupl_fair_coin f)]. simpl. intros a b ->. done. Qed. Lemma Rcoupl_fair_conv_comb_id `{Countable A, Countable B} (S : A → B → Prop) (μ1 μ2 : distr A) (μ1' μ2' : distr B) : Rcoupl μ1 μ1' S → Rcoupl μ2 μ2' S → Rcoupl (fair_conv_comb μ1 μ2) (fair_conv_comb μ1' μ2') S. Proof. intros HS1 HS2. eapply (Rcoupl_fair_conv_comb id). intros []; (eapply Rcoupl_impl; [|done]); eauto. Qed. Lemma Rcoupl_fair_conv_comb_neg `{Countable A, Countable B} (S : A → B → Prop) (μ1 μ2 : distr A) (μ1' μ2' : distr B) : Rcoupl μ1 μ2' S → Rcoupl μ2 μ1' S → Rcoupl (fair_conv_comb μ1 μ2) (fair_conv_comb μ1' μ2') S. Proof. intros HS1 HS2. eapply (Rcoupl_fair_conv_comb negb). intros []; (eapply Rcoupl_impl; [|done]); eauto. Qed. (* This is a lemma about convex combinations, but it is easier to prove with couplings TODO: find a better place to put it in *) Lemma fair_conv_comb_dbind `{Countable A, Countable B} (μ1 μ2 : distr A) (f : A -> distr B) : dbind f (fair_conv_comb μ1 μ2) = fair_conv_comb (dbind f μ1) (dbind f μ2). Proof. rewrite /fair_conv_comb -dbind_assoc. apply Rcoupl_eq_elim. eapply (Rcoupl_dbind _ _ _ _ (=)); [ | apply Rcoupl_eq]. intros b1 b2 ->. destruct b2; apply Rcoupl_eq. Qed. Section Rcoupl_strength. Context `{Countable A, Countable B, Countable D, Countable E}. Variable (μ1 : distr A) (μ2 : distr B). Lemma Rcoupl_strength_l (R : A → B → Prop) (d : D) : Rcoupl μ1 μ2 R → Rcoupl (strength_l d μ1) μ2 (λ '(d', a) b, d' = d ∧ R a b). Proof. rewrite /strength_l /dmap. intros Hcpl. rewrite -(dret_id_right μ2). eapply Rcoupl_dbind; [|done]. intros. by apply Rcoupl_dret. Qed. Lemma Rcoupl_strength (R : A → B → Prop) (d : D) (e : E) : Rcoupl μ1 μ2 R → Rcoupl (strength_l d μ1) (strength_l e μ2) (λ '(d', a) '(e', b), d' = d ∧ e' = e ∧ R a b). Proof. rewrite /strength_l /dmap. eapply Rcoupl_dbind. intros. by apply Rcoupl_dret. Qed. End Rcoupl_strength. Section refinement_couplings. Context `{Countable A, Countable B, Countable A', Countable B'}. Context (μ1 : distr A) (μ2 : distr B) (R : A -> B -> Prop) (S : A' → B' → Prop). Definition isRefCoupl (μ : distr (A * B)) : Prop := lmarg μ = μ1 /\ (∀ (b : B), rmarg μ b <= μ2 b). Definition refCoupl := ∃ (μ : distr (A * B)), isRefCoupl μ. Definition isRefRcoupl (μ : distr (A * B)) : Prop := isRefCoupl μ ∧ (forall (p : A * B), (μ p > 0) -> R (fst p) (snd p)). Definition refRcoupl := ∃ (μ : distr (A * B)), isRefRcoupl μ. Lemma isRefCoupl_mass_l μ : isRefCoupl μ -> SeriesC μ = SeriesC μ1. Proof. intro Hμ. destruct Hμ as (Hμl & Hμr). rewrite <- Hμl. rewrite /lmarg. rewrite <- dmap_mass. auto. Qed. Lemma isRefCoupl_mass_r μ : isRefCoupl μ -> SeriesC μ <= SeriesC μ2. Proof. intro Hμ. destruct Hμ as (Hμl & Hμr). rewrite (dmap_mass μ snd). apply SeriesC_le; auto. Qed. Lemma isRefCoupl_mass_eq μ : isRefCoupl μ -> SeriesC μ1 <= SeriesC μ2. Proof. intro Hμ. rewrite <- (isRefCoupl_mass_l μ); auto. apply (isRefCoupl_mass_r μ); auto. Qed. End refinement_couplings. Section ref_couplings_theory. Context `{Countable A, Countable B}. Lemma refRcoupl_mass_eq (μ1 : distr A) (μ2 : distr B) (R : A → B → Prop) : refRcoupl μ1 μ2 R → SeriesC μ1 <= SeriesC μ2. Proof. intros (?&?&?). by eapply isRefCoupl_mass_eq. Qed. Lemma refRcoupl_eq_elim (μ1 μ2 : distr A) : refRcoupl μ1 μ2 (=) → (∀ a, μ1 a <= μ2 a). Proof. intros (μ & (HμL & HμR) & HμS) a. eapply (Rle_Transitive _ (rmarg μ a) _); auto. rewrite <- HμL. rewrite lmarg_pmf rmarg_pmf. eapply SeriesC_le. { intro . specialize (HμS (a,n)). simpl in HμS. destruct (Rtotal_order (μ (a,n)) 0) as [? | [? | H3]]; [ pose proof (pmf_pos μ (a, n)); lra | pose proof (pmf_pos μ (n, a)); lra | pose proof (HμS H3); simplify_eq; lra ]. } apply ex_distr_rmarg. Qed. Lemma refRcoupl_from_leq (μ1 μ2 : distr A) : (∀ a, μ1 a <= μ2 a) -> refRcoupl μ1 μ2 (=). Proof. intro Hleq. exists (ddiag μ1). split;[ split | ]. + apply distr_ext; intro a. rewrite lmarg_pmf {2}/pmf/=. rewrite SeriesC_singleton'; auto. + intro a. rewrite ddiag_rmarg. auto. + intros p Hp. rewrite ddiag_pmf in Hp. case_bool_decide; auto; lra. Qed. Lemma refRcoupl_eq_refl (μ1 : distr A): refRcoupl μ1 μ1 (=). Proof. apply refRcoupl_from_leq. intro a. apply Rle_refl. Qed. Lemma refRcoupl_eq_trans (μ1 μ2 μ3 : distr A): refRcoupl μ1 μ2 (=) → refRcoupl μ2 μ3 (=) → refRcoupl μ1 μ3 (=). Proof. intros H12 H23. pose proof (refRcoupl_eq_elim _ _ H12) as H12'. pose proof (refRcoupl_eq_elim _ _ H23) as H23'. apply refRcoupl_from_leq. intros; eapply Rle_trans; eauto. Qed. Lemma refRcoupl_eq_refRcoupl_unfoldl (μ1 μ2 μ3 : distr A) R : Rcoupl μ1 μ2 (=) → refRcoupl μ2 μ3 R → refRcoupl μ1 μ3 R. Proof. by intros ->%Rcoupl_eq_elim ?. Qed. Lemma refRcoupl_eq_refRcoupl_unfoldr (μ1 μ2 μ3 : distr A) R : refRcoupl μ1 μ2 R → Rcoupl μ2 μ3 (=) → refRcoupl μ1 μ3 R. Proof. by intros ? <-%Rcoupl_eq_elim. Qed. Lemma isRefCoupl_dret (a : A) (b : B) : isRefCoupl (dret a) (dret b) (dret (a, b)). Proof. split; [rewrite /lmarg dmap_dret // | rewrite /rmarg dmap_dret //]. Qed. Lemma refCoupl_dret (a : A) (b : B) : refCoupl (dret a) (dret b). Proof. exists (dret (a, b)). apply isRefCoupl_dret. Qed. Lemma Rcoupl_refRcoupl (μ1 : distr A) (μ2 : distr B) (R : A → B → Prop) : Rcoupl μ1 μ2 R → refRcoupl μ1 μ2 R. Proof. rewrite /refRcoupl /Rcoupl. intros (μ & ((HμL & HμR) & HμSupp)). exists μ. split; auto. split; auto. intro. rewrite HμR; lra. Qed. Lemma refRcoupl_dret a b (R : A → B → Prop) : R a b → refRcoupl (dret a) (dret b) R. Proof. intros HR. eexists. split; [eapply isRefCoupl_dret|]. intros [] [=<- <-]%dret_pos. done. Qed. Context `{Countable A', Countable B'}. Lemma refRcoupl_dbind (f : A → distr A') (g : B → distr B') (μ1 : distr A) (μ2 : distr B) (R : A → B → Prop) (S : A' → B' → Prop) : (∀ a b, R a b → refRcoupl (f a) (g b) S) → refRcoupl μ1 μ2 R → refRcoupl (dbind f μ1) (dbind g μ2) S. Proof. intros Hfg (μ & HμC & HμS). rewrite /Rcoupl /isRcoupl in Hfg. (* First we rewrite Hfg to be able to use Choice *) assert (∀ p, ∃ μ' , R p.1 p.2 → (isRefCoupl (f p.1) (g p.2) μ' ∧ (∀ q : A' * B', μ' q > 0 → S q.1 q.2))) as Hfg'. { intro p. specialize (HμS p). specialize (Hfg p.1 p.2). pose proof (ExcludedMiddle (R p.1 p.2)) as H3; destruct H3 as [HR | HnR]. + specialize (Hfg HR). destruct Hfg as (μ' & Hμ'1 & Hμ'2). exists μ'; auto. + exists dzero; intro ; done. } pose proof (Choice (A * B) (distr (A' * B')) _ Hfg') as (Ch & HCh). rewrite /Rcoupl /isRcoupl. exists (dbind Ch μ); split; try split. (* To prove that the first marginal coincides is a matter of rearranging the sums and using the fact that μ and (Ch p) are couplings *) + apply distr_ext; intro a'. rewrite lmarg_pmf. rewrite /pmf /= /dbind_pmf. rewrite <- distr_double_swap_lmarg. setoid_rewrite SeriesC_scal_l. erewrite (SeriesC_ext _ (λ p, μ p * f p.1 a')); last first. { intros (a & b). destruct (Rtotal_order (μ (a, b)) 0) as [Hlt | [Heqz | Hgt]]. + pose proof (pmf_pos μ (a, b)); lra. + rewrite Heqz; lra. + specialize (HCh (a, b) (HμS (a, b) Hgt )) as ((HChL & HChR) & HChS). rewrite -HChL lmarg_pmf //=. } rewrite fubini_pos_seriesC_prod_lr; auto. 2:{simpl; intros; apply Rmult_le_pos; auto. } 2:{apply (ex_seriesC_le _ μ); auto. intros; split; [apply Rmult_le_pos; auto | ]. rewrite <- Rmult_1_r; apply Rmult_le_compat; auto. apply Rle_refl. } erewrite (SeriesC_ext _ (λ a, SeriesC (λ b : B, μ (a, b) ) * f a a')); [ | intro a; simpl; apply SeriesC_scal_r ]. erewrite (SeriesC_ext _ (λ a, (μ1 a) * f a a')); auto. intro a. destruct HμC as (Hμ1 & Hμ2). rewrite <- Hμ1; rewrite lmarg_pmf; auto. + intro b'. rewrite rmarg_pmf. rewrite /pmf/=/dbind_pmf. rewrite <- distr_double_swap_rmarg. erewrite (SeriesC_ext _ (λ b, μ b * SeriesC (λ a : A', Ch b (a, b'))) ); [ | intro p; apply SeriesC_scal_l]. apply (Rle_trans _ (SeriesC (λ p, μ p * g p.2 b')) _). { apply SeriesC_le; [ | ]; last first. + apply (ex_seriesC_le _ μ); auto. intros; split. ++ apply Rmult_le_pos; auto. ++ rewrite <- Rmult_1_r. apply Rmult_le_compat_l; auto. + intros (a & b); split; [ apply Rmult_le_pos; auto | ]. { assert (SeriesC (λ a0 : A', Ch (a, b) (a0, b')) = rmarg (Ch (a, b)) b') as ->; [rewrite rmarg_pmf; auto | apply pmf_pos]. } destruct (Rtotal_order (μ (a, b)) 0) as [Hlt | [Heqz | Hgt]]. ++ pose proof (pmf_pos μ (a, b)); lra. ++ rewrite Heqz; lra. ++ specialize (HCh (a, b) (HμS (a, b) Hgt )) as ((HChL & HChR) & HChS). specialize (HChR b'). rewrite (rmarg_pmf (Ch (a, b))) in HChR. apply Rmult_le_compat_l; auto. } rewrite fubini_pos_seriesC_prod_rl; auto. 2:{simpl; intros; apply Rmult_le_pos; auto. } 2:{apply (ex_seriesC_le _ μ); auto. intros; split; [apply Rmult_le_pos; auto | ]. rewrite <- Rmult_1_r; apply Rmult_le_compat; auto. apply Rle_refl. } apply SeriesC_le; [ | ]; last first. { apply (ex_seriesC_le _ μ2); auto. intros; split. + apply Rmult_le_pos; auto. + rewrite <- Rmult_1_r. apply Rmult_le_compat_l; auto. } intro b; split; simpl. ++ rewrite SeriesC_scal_r. apply Rmult_le_pos ; auto. assert (SeriesC (λ x : A, μ (x, b)) = rmarg μ b ) as -> ; [rewrite rmarg_pmf | apply pmf_pos ]; auto. ++ destruct HμC as [HμCL HμCR]. rewrite SeriesC_scal_r. apply Rmult_le_compat_r; auto. specialize (HμCR b). rewrite rmarg_pmf in HμCR; auto. + intros (a' & b') H3; simpl. pose proof (dbind_pos_support Ch μ (a', b')) as (H4 & H5). specialize (H4 H3) as ((a0, b0) & H7 & H8). specialize (HCh (a0, b0) (HμS (a0, b0) H8)) as (HCh1 & HCh2). specialize (HCh2 (a', b') H7). done. Qed. Lemma refRcoupl_dzero (μ : distr B) (R: A → B → Prop): refRcoupl dzero μ R. Proof. exists dzero; split; try split. + rewrite /lmarg dmap_dzero; done. + intro a. rewrite rmarg_pmf {1}/pmf/=. rewrite SeriesC_0; auto. + rewrite /pmf/=; intros; lra. Qed. Lemma refRcoupl_weaken (μ1 : distr A) (μ2 : distr B) (R : A → B → Prop) (S : A → B → Prop): (∀ a b, R a b -> S a b) → refRcoupl μ1 μ2 R → refRcoupl μ1 μ2 S. Proof. intros Hwk [μ [[HμL HμR] HμSupp]]. exists μ; split; [split | ]; auto. Qed. Lemma refRcoupl_trivial (μ1 :distr A) (μ2 :distr B): SeriesC μ1 <= SeriesC μ2 -> refRcoupl μ1 μ2 (λ _ _, True). Proof. intros Hμ. pose proof (pmf_SeriesC_ge_0 μ1) as H3. destruct (Rlt_or_le 0 (SeriesC μ1)); last first. + destruct H3 ; try lra. rewrite (SeriesC_zero_dzero μ1); [ | apply Rle_antisym; auto]. apply refRcoupl_dzero. + assert (0 < SeriesC μ2); [apply (Rlt_le_trans _ (SeriesC μ1)) | ]; auto. eexists (distr_scal (/(SeriesC μ2)) (dprod μ1 μ2) _). Unshelve. 2:{ split; auto. - left; apply Rinv_0_lt_compat; auto. - rewrite dprod_mass. rewrite Rmult_comm Rmult_assoc. rewrite Rinv_r; auto; try lra. rewrite Rmult_1_r. apply pmf_SeriesC. } split; [|done]. split. ++ apply distr_ext. intro a. rewrite lmarg_pmf SeriesC_scal_l -lmarg_pmf lmarg_dprod_pmf -Rmult_comm Rmult_assoc Rinv_r; lra. ++ intro b. rewrite rmarg_pmf SeriesC_scal_l -rmarg_pmf rmarg_dprod_pmf -Rmult_comm Rmult_assoc. assert (μ2 b = μ2 b * 1) as Hrw; [rewrite Rmult_1_r; auto | ]. rewrite {2}Hrw. apply (Rmult_le_compat_l); auto; try lra. apply (Rdiv_le_1 (SeriesC μ1) (SeriesC μ2)) ; try lra. Qed. End ref_couplings_theory.
%install; load('..\mat\LPnetlib\lp_agg.mat') A = Problem.A; p = colamd(A'); A = A(p,:); w = (0.5+rand(size(A,2),1)).^5; R = chol((A*(w.*A'))); x = rand(size(A,1),1); z = R\(R'\x); d = full(diag(R)); w = diag(sparse(w)); o = AdaptiveChol(A, 1e-8); acc = o.factorize(w) z2 = o.solve(ddouble(x), ddouble(w)); z3 = o.solve(ddouble(x), ddouble(w), 2); z4 = o.solve(ddouble(x), ddouble(w), 3); z5 = o.solve(ddouble(x), ddouble(w), 4); d2 = o.diagonal(); norm(z2-z) norm(z2-z3) norm(z3-z4) norm(z4-z5) %norm(d2-d) ls = o.leverageScore(100); max(ls)
(* * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230) * * SPDX-License-Identifier: GPL-2.0-only *) (* seL4-specific lemmas for automation framework for C refinement *) theory Ctac_lemmas_C imports "../lib/Ctac" begin context kernel begin lemma c_guard_abs_cte: fixes p :: "cte_C ptr" shows "\<forall>s s'. (s, s') \<in> rf_sr \<and> cte_at' (ptr_val p) s \<and> True \<longrightarrow> s' \<Turnstile>\<^sub>c p" apply (cases p) apply (clarsimp simp: cte_wp_at_ctes_of) apply (erule (1) rf_sr_ctes_of_cliftE) apply (simp add: typ_heap_simps') done lemmas ccorres_move_c_guard_cte [corres_pre] = ccorres_move_c_guards [OF c_guard_abs_cte] lemma c_guard_abs_tcb: fixes p :: "tcb_C ptr" shows "\<forall>s s'. (s, s') \<in> rf_sr \<and> tcb_at' (ctcb_ptr_to_tcb_ptr p) s \<and> True \<longrightarrow> s' \<Turnstile>\<^sub>c p" apply clarsimp apply (drule (1) tcb_at_h_t_valid) apply simp done lemmas ccorres_move_c_guard_tcb [corres_pre] = ccorres_move_c_guards [OF c_guard_abs_tcb] lemma cte_array_relation_array_assertion: "gsCNodes s p = Some n \<Longrightarrow> cte_array_relation s cstate \<Longrightarrow> array_assertion (cte_Ptr p) (2 ^ n) (hrs_htd (t_hrs_' cstate))" apply (rule h_t_array_valid_array_assertion) apply (clarsimp simp: cvariable_array_map_relation_def) apply simp done lemma rf_sr_tcb_ctes_array_assertion': "\<lbrakk> (s, s') \<in> rf_sr; tcb_at' (ctcb_ptr_to_tcb_ptr tcb) s \<rbrakk> \<Longrightarrow> array_assertion (cte_Ptr (ptr_val tcb && ~~mask tcbBlockSizeBits)) (unat tcbCNodeEntries) (hrs_htd (t_hrs_' (globals s')))" apply (rule h_t_array_valid_array_assertion, simp_all add: tcbCNodeEntries_def) apply (clarsimp simp: rf_sr_def cstate_relation_def Let_def cvariable_array_map_relation_def cpspace_relation_def) apply (drule obj_at_ko_at', clarsimp) apply (drule spec, drule mp, rule exI, erule ko_at_projectKO_opt) apply (frule ptr_val_tcb_ptr_mask) apply (simp add: mask_def) done lemmas rf_sr_tcb_ctes_array_assertion = rf_sr_tcb_ctes_array_assertion'[simplified objBits_defs mask_def, simplified] lemma rf_sr_tcb_ctes_array_assertion2: "\<lbrakk> (s, s') \<in> rf_sr; tcb_at' tcb s \<rbrakk> \<Longrightarrow> array_assertion (cte_Ptr tcb) (unat tcbCNodeEntries) (hrs_htd (t_hrs_' (globals s')))" apply (frule(1) rf_sr_tcb_ctes_array_assertion[where tcb="tcb_ptr_to_ctcb_ptr t" for t, simplified]) apply (simp add: ptr_val_tcb_ptr_mask) done lemma array_assertion_abs_tcb_ctes': "\<forall>s s'. (s, s') \<in> rf_sr \<and> tcb_at' (ctcb_ptr_to_tcb_ptr (tcb s')) s \<and> (n s' \<le> unat tcbCNodeEntries) \<longrightarrow> (x s' = 0 \<or> array_assertion (cte_Ptr (ptr_val (tcb s') && ~~mask tcbBlockSizeBits)) (n s') (hrs_htd (t_hrs_' (globals s'))))" "\<forall>s s'. (s, s') \<in> rf_sr \<and> tcb_at' tcb' s \<and> (n s' \<le> unat tcbCNodeEntries) \<longrightarrow> (x s' = 0 \<or> array_assertion (cte_Ptr tcb') (n s') (hrs_htd (t_hrs_' (globals s'))))" apply (safe intro!: disjCI2) apply (drule(1) rf_sr_tcb_ctes_array_assertion' rf_sr_tcb_ctes_array_assertion2 | erule array_assertion_shrink_right | simp)+ done lemmas array_assertion_abs_tcb_ctes = array_assertion_abs_tcb_ctes'[simplified objBits_defs mask_def, simplified] lemma array_assertion_abs_tcb_ctes_add': "\<forall>s s'. (s, s') \<in> rf_sr \<and> tcb_at' (ctcb_ptr_to_tcb_ptr (tcb s')) s \<and> (n s' \<ge> 0 \<and> (case strong of True \<Rightarrow> n s' + 1 | False \<Rightarrow> n s') \<le> uint tcbCNodeEntries) \<longrightarrow> ptr_add_assertion (cte_Ptr (ptr_val (tcb s') && ~~mask tcbBlockSizeBits)) (n s') strong (hrs_htd (t_hrs_' (globals s')))" apply (clarsimp, drule(1) rf_sr_tcb_ctes_array_assertion') apply (simp add: ptr_add_assertion_positive, rule disjCI2) apply (erule array_assertion_shrink_right) apply (cases strong, simp_all add: unat_def) done lemmas array_assertion_abs_tcb_ctes_add = array_assertion_abs_tcb_ctes_add'[simplified objBits_defs mask_def, simplified] lemmas ccorres_move_array_assertion_tcb_ctes [corres_pre] = ccorres_move_array_assertions [OF array_assertion_abs_tcb_ctes(1)] ccorres_move_array_assertions [OF array_assertion_abs_tcb_ctes(2)] ccorres_move_Guard_Seq[OF array_assertion_abs_tcb_ctes_add] ccorres_move_Guard[OF array_assertion_abs_tcb_ctes_add] lemma c_guard_abs_tcb_ctes': fixes p :: "cte_C ptr" shows "\<forall>s s'. (s, s') \<in> rf_sr \<and> tcb_at' (ctcb_ptr_to_tcb_ptr (tcb s')) s \<and> (n < ucast tcbCNodeEntries) \<longrightarrow> s' \<Turnstile>\<^sub>c cte_Ptr (((ptr_val (tcb s') && ~~mask tcbBlockSizeBits) + n * 2^cteSizeBits))" apply (clarsimp) apply (rule c_guard_abs_cte[rule_format], intro conjI, simp_all) apply (simp add: cte_at'_obj_at', rule disjI2) apply (frule ptr_val_tcb_ptr_mask) apply (rule_tac x="n * 2^cteSizeBits" in bexI) apply (simp add: mask_def) apply (simp add: word_less_nat_alt tcbCNodeEntries_def tcb_cte_cases_def objBits_defs) apply (case_tac "unat n", simp_all add: unat_eq_of_nat, rename_tac n_rem) apply (case_tac "n_rem", simp_all add: unat_eq_of_nat, (rename_tac n_rem)?)+ done lemmas c_guard_abs_tcb_ctes = c_guard_abs_tcb_ctes'[simplified objBits_defs mask_def, simplified] lemmas ccorres_move_c_guard_tcb_ctes [corres_pre] = ccorres_move_c_guards [OF c_guard_abs_tcb_ctes] lemma c_guard_abs_pte: "\<forall>s s'. (s, s') \<in> rf_sr \<and> pte_at' (ptr_val p) s \<and> True \<longrightarrow> s' \<Turnstile>\<^sub>c (p :: pte_C ptr)" apply (clarsimp simp: typ_at_to_obj_at_arches) apply (drule obj_at_ko_at', clarsimp) apply (erule cmap_relationE1[OF rf_sr_cpte_relation]) apply (erule ko_at_projectKO_opt) apply (fastforce intro: typ_heap_simps) done lemmas ccorres_move_c_guard_pte = ccorres_move_c_guards [OF c_guard_abs_pte] lemma array_assertion_abs_pt: "\<forall>s s'. (s, s') \<in> rf_sr \<and> (page_table_at' pd s) \<and> (n s' \<le> 2 ^ (ptBits - 3) \<and> (x s' \<noteq> 0 \<longrightarrow> n s' \<noteq> 0)) \<longrightarrow> (x s' = 0 \<or> array_assertion (pte_Ptr pd) (n s') (hrs_htd (t_hrs_' (globals s'))))" apply (intro allI impI disjCI2, clarsimp) apply (drule(1) page_table_at_rf_sr, clarsimp) apply (erule clift_array_assertion_imp, simp_all add: bit_simps) apply (rule_tac x=0 in exI, simp) done lemmas ccorres_move_array_assertion_pt = ccorres_move_array_assertions[OF array_assertion_abs_pt] lemma c_guard_abs_pde: "\<forall>s s'. (s, s') \<in> rf_sr \<and> pde_at' (ptr_val p) s \<and> True \<longrightarrow> s' \<Turnstile>\<^sub>c (p :: pde_C ptr)" apply (clarsimp simp: typ_at_to_obj_at_arches) apply (drule obj_at_ko_at', clarsimp) apply (erule cmap_relationE1[OF rf_sr_cpde_relation]) apply (erule ko_at_projectKO_opt) apply (fastforce intro: typ_heap_simps) done lemmas ccorres_move_c_guard_pde = ccorres_move_c_guards [OF c_guard_abs_pde] lemma array_assertion_abs_pd: "\<forall>s s'. (s, s') \<in> rf_sr \<and> (page_directory_at' pd s) \<and> (n s' \<le> 2 ^ (pdBits - 3) \<and> (x s' \<noteq> 0 \<longrightarrow> n s' \<noteq> 0)) \<longrightarrow> (x s' = 0 \<or> array_assertion (pde_Ptr pd) (n s') (hrs_htd (t_hrs_' (globals s'))))" apply (intro allI impI disjCI2, clarsimp) apply (drule(1) page_directory_at_rf_sr, clarsimp) apply (erule clift_array_assertion_imp, simp_all add: bit_simps) apply (rule_tac x=0 in exI, simp) done lemmas ccorres_move_array_assertion_pd = ccorres_move_array_assertions[OF array_assertion_abs_pd] lemma c_guard_abs_pdpte: "\<forall>s s'. (s, s') \<in> rf_sr \<and> pdpte_at' (ptr_val p) s \<and> True \<longrightarrow> s' \<Turnstile>\<^sub>c (p :: pdpte_C ptr)" apply (clarsimp simp: typ_at_to_obj_at_arches) apply (drule obj_at_ko_at', clarsimp) apply (erule cmap_relationE1[OF rf_sr_cpdpte_relation]) apply (erule ko_at_projectKO_opt) apply (fastforce intro: typ_heap_simps) done lemmas ccorres_move_c_guard_pdpte = ccorres_move_c_guards [OF c_guard_abs_pdpte] lemma array_assertion_abs_pdpt: "\<forall>s s'. (s, s') \<in> rf_sr \<and> (pd_pointer_table_at' pd s) \<and> (n s' \<le> 2 ^ (pdptBits - 3) \<and> (x s' \<noteq> 0 \<longrightarrow> n s' \<noteq> 0)) \<longrightarrow> (x s' = 0 \<or> array_assertion (pdpte_Ptr pd) (n s') (hrs_htd (t_hrs_' (globals s'))))" apply (intro allI impI disjCI2, clarsimp) apply (drule(1) pd_pointer_table_at_rf_sr, clarsimp) apply (erule clift_array_assertion_imp, simp_all add: bit_simps) apply (rule_tac x=0 in exI, simp) done lemmas ccorres_move_array_assertion_pdpt = ccorres_move_array_assertions[OF array_assertion_abs_pdpt] lemma c_guard_abs_pml4e: "\<forall>s s'. (s, s') \<in> rf_sr \<and> pml4e_at' (ptr_val p) s \<and> True \<longrightarrow> s' \<Turnstile>\<^sub>c (p :: pml4e_C ptr)" apply (clarsimp simp: typ_at_to_obj_at_arches) apply (drule obj_at_ko_at', clarsimp) apply (erule cmap_relationE1[OF rf_sr_cpml4e_relation]) apply (erule ko_at_projectKO_opt) apply (fastforce intro: typ_heap_simps) done lemmas ccorres_move_c_guard_pml4e = ccorres_move_c_guards [OF c_guard_abs_pml4e] lemma array_assertion_abs_pml4: "\<forall>s s'. (s, s') \<in> rf_sr \<and> (page_map_l4_at' pd s) \<and> (n s' \<le> 2 ^ (pml4Bits - 3) \<and> (x s' \<noteq> 0 \<longrightarrow> n s' \<noteq> 0)) \<longrightarrow> (x s' = 0 \<or> array_assertion (pml4e_Ptr pd) (n s') (hrs_htd (t_hrs_' (globals s'))))" apply (intro allI impI disjCI2, clarsimp) apply (drule(1) page_map_l4_at_rf_sr, clarsimp) apply (erule clift_array_assertion_imp, simp_all add: bit_simps) apply (rule_tac x=0 in exI, simp) done lemmas ccorres_move_array_assertion_pml4 = ccorres_move_array_assertions[OF array_assertion_abs_pml4] lemma move_c_guard_ap: "\<forall>s s'. (s, s') \<in> rf_sr \<and> asid_pool_at' (ptr_val p) s \<and> True \<longrightarrow> s' \<Turnstile>\<^sub>c (p :: asid_pool_C ptr)" apply (clarsimp simp: typ_at_to_obj_at_arches) apply (drule obj_at_ko_at', clarsimp) apply (erule cmap_relationE1 [OF rf_sr_cpspace_asidpool_relation]) apply (erule ko_at_projectKO_opt) apply (fastforce intro: typ_heap_simps) done lemmas ccorres_move_c_guard_ap = ccorres_move_c_guards [OF move_c_guard_ap] lemma array_assertion_abs_irq: "\<forall>s s'. (s, s') \<in> rf_sr \<and> True \<and> (n s' \<le> 256 \<and> (x s' \<noteq> 0 \<longrightarrow> n s' \<noteq> 0)) \<longrightarrow> (x s' = 0 \<or> array_assertion intStateIRQNode_Ptr (n s') (hrs_htd (t_hrs_' (globals s'))))" apply (intro allI impI disjCI2) apply (clarsimp simp: rf_sr_def cstate_relation_def Let_def) apply (clarsimp simp: h_t_valid_clift_Some_iff) apply (erule clift_array_assertion_imp, (simp add: exI[where x=0])+) done lemmas ccorres_move_array_assertion_irq = ccorres_move_array_assertions [OF array_assertion_abs_irq] lemma ccorres_Guard_intStateIRQNode_array_Ptr_Seq: assumes "ccorres_underlying rf_sr \<Gamma> r xf arrel axf A C hs a (c;; d)" shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf A C hs a (Guard F {s. s \<Turnstile>\<^sub>c intStateIRQNode_array_Ptr} c;; d)" by (rule ccorres_guard_imp2[OF ccorres_move_Guard_Seq[where P=\<top> and P'=\<top>, OF _ assms]] ; simp add: rf_sr_def cstate_relation_def Let_def) lemmas ccorres_Guard_intStateIRQNode_array_Ptr = ccorres_Guard_intStateIRQNode_array_Ptr_Seq[where d=SKIP, simplified ccorres_seq_skip'] ccorres_Guard_intStateIRQNode_array_Ptr_Seq lemma rf_sr_gsCNodes_array_assertion: "gsCNodes s p = Some n \<Longrightarrow> (s, s') \<in> rf_sr \<Longrightarrow> array_assertion (cte_Ptr p) (2 ^ n) (hrs_htd (t_hrs_' (globals s')))" by (clarsimp simp: rf_sr_def cstate_relation_def Let_def cte_array_relation_array_assertion) end end
--- author: Nathan Carter ([email protected]) --- This answer assumes you have imported SymPy as follows. ```python from sympy import * # load all math functions init_printing( use_latex='mathjax' ) # use pretty math output ``` Sequences are typically written in terms of an independent variable $n$, so we will tell SymPy to use $n$ as a symbol, then define our sequence in terms of $n$. We define a term of an example sequence as $a_n=\frac{1}{n+1}$, then build a sequence from that term. The code `(n,0,oo)` means that $n$ starts counting at $n=0$ and goes on forever (with `oo` being the SymPy notation for $\infty$). ```python var( 'n' ) # use n as a symbol a_n = 1 / ( n + 1 ) # formula for a term seq = sequence( a_n, (n,0,oo) ) # build the sequence seq ``` $\displaystyle \left[1, \frac{1}{2}, \frac{1}{3}, \frac{1}{4}, \ldots\right]$ You can ask for specific terms in the sequence, or many terms in a row, as follows. ```python seq[20] ``` $\displaystyle \frac{1}{21}$ ```python seq[:10] ``` $\displaystyle \left[ 1, \ \frac{1}{2}, \ \frac{1}{3}, \ \frac{1}{4}, \ \frac{1}{5}, \ \frac{1}{6}, \ \frac{1}{7}, \ \frac{1}{8}, \ \frac{1}{9}, \ \frac{1}{10}\right]$ You can compute the limit of a sequence, $$ \lim_{n\to\infty} a_n. $$ ```python limit( a_n, n, oo ) ``` $\displaystyle 0$
\documentclass{article} % Use `report` for longer reports % Borders \usepackage{geometry} \geometry{ a4paper, total={170mm,257mm}, left=20mm, top=20mm, } % Fonts \usepackage[no-math]{fontspec} \usepackage{unicode-math} \defaultfontfeatures{ Scale=1.22 } % Setting custom fonts \setmainfont{Atkinson-Hyperlegible}[ Path = resources/fonts/, Extension = .ttf, UprightFont = *-Regular-102, BoldFont = *-Bold-102, ItalicFont = *-Italic-102, BoldItalicFont = *-BoldItalic-102 ] \setmonofont{FiraCode}[ Path = resources/fonts/, Extension = .ttf, UprightFont = *-Regular, BoldFont = *-Bold, Scale = MatchLowercase ] %\setmathfont{Latin Modern Math}[Scale=MatchLowercase] %\setmathrm{Latin Modern Roman}[Scale=MatchLowercase] \setlength{\parskip}{0.75em} \renewcommand{\baselinestretch}{1.35} \usepackage[scaled=1.22]{helvet} % Remove a bit of the space after headings \usepackage{titlesec} \titlespacing\section{0pt}{12pt plus 4pt minus 2pt}{0pt plus 2pt minus 2pt} \titlespacing\subsection{0pt}{12pt plus 4pt minus 2pt}{0pt plus 2pt minus 2pt} \titlespacing\subsubsection{0pt}{12pt plus 4pt minus 2pt}{0pt plus 2pt minus 2pt} % Glossary \usepackage[acronym,toc]{glossaries} \makeglossaries \loadglsentries{resources/glossary} % Give a bit of colour to the glossary entries. \renewcommand{\glstextformat}[1]{{\color{glossary} #1}} % Add dots to the TOC \usepackage{tocloft} \renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}} % Support for hyperlinks \usepackage[hyphens]{url} \usepackage{hyperref} \hypersetup{ colorlinks=true, linkcolor=exturlblue, urlcolor=urlblue, breaklinks=true, citecolor=citations, } \urlstyle{same} % Bibliograpy \usepackage[ backend=biber, style=nature ]{biblatex} \addbibresource{resources/Transcriptomics.bib} % Support for colors \usepackage{xcolor} \definecolor{listingback}{RGB}{225, 235, 252} \definecolor{commentgreen}{RGB}{24, 153, 76} \definecolor{numbergray}{RGB}{133, 133, 133} \definecolor{keywordorange}{RGB}{199, 86, 10} \definecolor{urlblue}{RGB}{35, 68, 107} \definecolor{exturlblue}{RGB}{0, 65, 145} \definecolor{glossary}{RGB}{0, 107, 18} \definecolor{mono}{RGB}{204, 71, 0} \definecolor{citations}{RGB}{123, 12, 179} % Code listings \usepackage{listings} \lstdefinestyle{RStyle} { language=R, otherkeywords={!,!=,~,\$,*,\&,\%/\%,\%*\%,\%\%,<-,<<-,/,TRUE,FALSE}, alsoother={.\$} } \lstdefinestyle{PyStyle} { language=Python } \lstdefinestyle{ShellStyle} { language=bash } % For inline monospace font: \lstinline{insert code here} \lstset{ style=Rstyle, alsoletter=_, frame=tb, numbers=left, showspaces=false, basicstyle=\scriptsize, numberstyle=\tiny\color{numbergray}, keywordstyle=\color{keywordorange}, commentstyle=\color{gray}, stringstyle=\color{commentgreen}, backgroundcolor=\color{listingback} } % Pretty colours in mono font \newcommand{\mono}[1]{\texttt{\color{mono}#1}} % Smaller title \makeatletter \renewcommand\maketitle{ {\raggedright % Note the extra { {\huge \bfseries \sffamily \@title }\\[2ex] {\large \@author~-~\@date} }} % Note the extra } \makeatother % Images \usepackage{graphicx} \graphicspath{ {./resources/images/} } \usepackage{float} % To use hard 'H' % Style of images % Set a max width to all images \usepackage[export]{adjustbox}% http://ctan.org/pkg/adjustbox \let\oldincludegraphics\includegraphics \renewcommand{\includegraphics}[2][]{% \oldincludegraphics[#1,max width=\linewidth]{#2} } % Support for subfigures \usepackage{caption} \usepackage{subcaption} % Better lists \usepackage{enumitem} \setlist{nosep} % Highlight boxes \usepackage{awesomebox} % Pretty commits \usepackage{pdftexcmds} % \commit[link]{shortcode}{date} \definecolor{commithash}{RGB}{128, 128, 128} \definecolor{commitdate}{RGB}{4, 100, 138} \makeatletter \newcommand{\commit}[3][""]{ \ifnum\pdf@strcmp{\unexpanded{#1}}{""}=1 % [\texttt{\href{#1}{\color{commithash}#2}} - {\color{commitdate}#3}] \else [\texttt{\color{commithash}#2} - {\color{commitdate}#3}] \fi } \makeatother % Making appendices \newcommand{\printappendices}{ % Reset the section/figure/table counter \setcounter{figure}{0} \setcounter{section}{0} \setcounter{table}{0} % Set the figure/table counter to aleph \renewcommand\thefigure{\Alph{figure}} \renewcommand\thesection{Appendix \Alph{section}} \renewcommand\thetable{\Alph{table}} % Set the chapters to use letters \appendix % Set the section numberings \newpage % Add a large (clickable) title \addcontentsline{toc}{part}{Appendices} \part*{Appendices} \input{appendices} } \title{\normalfont GATTACA Manual} \author{Visentin Luca and Ruffinatti A. Federico, Ph.D.} \date{December 2021} \begin{document} \maketitle \tableofcontents \input{document} \printglossaries \Urlmuskip=0mu plus 1mu\relax % This allows for better linebreaks in URLs \printbibliography[heading=bibintoc,title=Bibliograpy] % Uncomment this to add appendices \printappendices \end{document}
lemmas scaleR_left_diff_distrib = scaleR_diff_left
Maureen Jackson knew life as a trainee nurse wouldn't be easy, but she didn't expect her hospital to be badly bombed on her first shift. Plus Maureen still has her family and friends in Mulberry Lane to keep her busy – she's needed as much there as she is by her patients. Running the pub on the corner of Mulberry Lane, Peggy Ashley is used to taking in all sorts of waifs and strays. But the arrival of a dashing American captain has got tongues wagging about Mulberry Lane's favourite landlady... Janet Ashley's husband is back from the frontline. Which is more than so many of the wives of Mulberry Lane. But her beloved Mike is a completely different man from the one she fell in love with – and what's more he doesn't remember her, or their young daughter. How do you cope when your darling husband is a virtual stranger? As WW2 continues around them, the women of Mulberry Lane know that community spirit and friendship is the key to surviving the Blitz.
module Main import CFFI %lib C "tensorflow" %include C "tensorflow/c/c_api.h" -- %include C "/usr/include/tensorflow/c/c_api.h" -- %link C "testlib.o" -- data TF_Tensor -- IO (Raw TF_Tensor) works,but c warns assignment from incompatible pointer type -- data TF_Status2:(a:Type)->Type where --safer way -- TF_Status22:TF_Status2 Ptr TF_Status : Type TF_Status = Ptr -- attention! -- Tfs : Raw TF_Status -- Tfs = MkRaw TF_Status {- typedef enum TF_Code { TF_OK = 0, TF_CANCELLED = 1, TF_UNKNOWN = 2, TF_INVALID_ARGUMENT = 3, TF_DEADLINE_EXCEEDED = 4, TF_NOT_FOUND = 5, TF_ALREADY_EXISTS = 6, TF_PERMISSION_DENIED = 7, TF_UNAUTHENTICATED = 16, TF_RESOURCE_EXHAUSTED = 8, TF_FAILED_PRECONDITION = 9, TF_ABORTED = 10, TF_OUT_OF_RANGE = 11, TF_UNIMPLEMENTED = 12, TF_INTERNAL = 13, TF_UNAVAILABLE = 14, TF_DATA_LOSS = 15, } TF_Code; 17 fields ! -} TF_Code_struct : Composite TF_Code_struct = STRUCT $ replicate 17 I32 tfNewStatus : IO TF_Status tfNewStatus = foreign FFI_C "TF_NewStatus" (IO TF_Status) tfGetCode : TF_Status ->IO Int tfGetCode = foreign FFI_C "TF_Code" (TF_Status ->IO Int) tfVersion : IO String tfVersion = foreign FFI_C "TF_Version" (IO String) |||Always returns an empty string if TF_GetCode(s) is TF_OK. tfMessage : TF_Status -> IO String tfMessage = foreign FFI_C "TF_Message" (TF_Status -> IO String) TF_Buffer : Type TF_Buffer = Ptr TF_Library : Type TF_Library = Ptr ||| Get the OpList of OpDefs defined in the library pointed by lib_handle,like matmul,placeholder,etc tfGetOpList : TF_Library->IO TF_Buffer tfGetOpList = foreign FFI_C "TF_GetOpList" (TF_Library->IO TF_Buffer ) main : IO () main = do ver<-tfVersion s<-tfNewStatus msg<-tfMessage s putStrLn $ "tfMessage is : " ++ msg putStrLn $ "tfVersion is : " ++ ver
!Crown Copyright 2012 AWE. ! ! This file is part of CloverLeaf. ! ! CloverLeaf is free software: you can redistribute it and/or modify it under ! the terms of the GNU General Public License as published by the ! Free Software Foundation, either version 3 of the License, or (at your option) ! any later version. ! ! CloverLeaf is distributed in the hope that it will be useful, but ! WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ! FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ! details. ! ! You should have received a copy of the GNU General Public License along with ! CloverLeaf. If not, see http://www.gnu.org/licenses/. !> @brief Fortran revert kernel. !> @author Wayne Gaudin !> @details Takes the half step field data used in the predictor and reverts !> it to the start of step data, ready for the corrector. !> Note that this does not seem necessary in this proxy-app but should be !> left in to remain relevant to the full method. MODULE revert_kernel_module CONTAINS SUBROUTINE revert_kernel(x_min,x_max,y_min,y_max,density0,density1,energy0,energy1) IMPLICIT NONE INTEGER :: x_min,x_max,y_min,y_max REAL(KIND=8), DIMENSION(x_min-2:x_max+2,y_min-2:y_max+2) :: density0 REAL(KIND=8), DIMENSION(x_min-2:x_max+2,y_min-2:y_max+2) :: density1 REAL(KIND=8), DIMENSION(x_min-2:x_max+2,y_min-2:y_max+2) :: energy0 REAL(KIND=8), DIMENSION(x_min-2:x_max+2,y_min-2:y_max+2) :: energy1 INTEGER :: j,k DO k=y_min,y_max DO j=x_min,x_max density1(j,k)=density0(j,k) ENDDO ENDDO DO k=y_min,y_max DO j=x_min,x_max energy1(j,k)=energy0(j,k) ENDDO ENDDO END SUBROUTINE revert_kernel END MODULE revert_kernel_module
State Before: x : ℕ b : Bool ⊢ addLsb x b / 2 = x State After: case true x : ℕ ⊢ x + 1 / 2 = x Tactic: cases b <;> simp only [Nat.add_mul_div_left, addLsb, ← two_mul, add_comm, Nat.succ_pos', Nat.mul_div_right, gt_iff_lt, zero_add, cond] State Before: case true x : ℕ ⊢ x + 1 / 2 = x State After: no goals Tactic: norm_num
import Lean def checkWithMkMatcherInput (matcher : Lean.Name) : Lean.MetaM Unit := Lean.Meta.Match.withMkMatcherInput matcher fun input => do let res ← Lean.Meta.Match.mkMatcher input let origMatcher ← Lean.getConstInfo matcher if not <| input.matcherName == matcher then throwError "matcher name not reconstructed correctly: {matcher} ≟ {input.matcherName}" let lCtx ← Lean.getLCtx let fvars ← Lean.collectFVars {} res.matcher let closure ← Lean.Meta.Closure.mkLambda (fvars.fvarSet.toList.toArray.map lCtx.get!) res.matcher let origTy := origMatcher.value! let newTy ← closure if not <| ←Lean.Meta.isDefEq origTy newTy then throwError "matcher {matcher} does not round-trip correctly:\n{origTy} ≟ {newTy}" def f (xs : List Nat) : List Bool := xs.map fun | 0 => true | _ => false #eval checkWithMkMatcherInput ``f.match_1 #eval f [1, 2, 0, 2] theorem ex1 : f [1, 0, 2] = [false, true, false] := rfl #check f set_option pp.raw true set_option pp.raw.maxDepth 10 set_option trace.Elab.step true in def g (xs : List Nat) : List Bool := xs.map <| by { intro | 0 => exact true | _ => exact false } theorem ex2 : g [1, 0, 2] = [false, true, false] := rfl theorem ex3 {p q r : Prop} : p ∨ q → r → (q ∧ r) ∨ (p ∧ r) := by intro | Or.inl hp, h => { apply Or.inr; apply And.intro; assumption; assumption } | Or.inr hq, h => { apply Or.inl; exact ⟨hq, h⟩ } #eval checkWithMkMatcherInput ``ex3.match_1 inductive C | mk₁ : Nat → C | mk₂ : Nat → Nat → C def C.x : C → Nat | C.mk₁ x => x | C.mk₂ x _ => x #eval checkWithMkMatcherInput ``C.x.match_1 def head : {α : Type} → List α → Option α | _, a::as => some a | _, _ => none #eval checkWithMkMatcherInput ``head.match_1 theorem ex4 : head [1, 2] = some 1 := rfl def head2 : {α : Type} → List α → Option α := @fun | _, a::as => some a | _, _ => none theorem ex5 : head2 [1, 2] = some 1 := rfl def head3 {α : Type} (xs : List α) : Option α := let rec aux : {α : Type} → List α → Option α | _, a::as => some a | _, _ => none; aux xs theorem ex6 : head3 [1, 2] = some 1 := rfl inductive Vec.{u} (α : Type u) : Nat → Type u | nil : Vec α 0 | cons {n} (head : α) (tail : Vec α n) : Vec α (n+1) def Vec.mapHead1 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ | _, nil, nil, f => none | _, cons a as, cons b bs, f => some (f a b) #eval checkWithMkMatcherInput ``Vec.mapHead1.match_1 def Vec.mapHead2 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ | _, nil, nil, f => none | _, @cons _ n a as, cons b bs, f => some (f a b) #eval checkWithMkMatcherInput ``Vec.mapHead2.match_1 def Vec.mapHead3 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ | _, nil, nil, f => none | _, cons (tail := as) (head := a), cons b bs, f => some (f a b) inductive Foo | mk₁ (x y z w : Nat) | mk₂ (x y z w : Nat) def Foo.z : Foo → Nat | mk₁ (z := z) .. => z | mk₂ (z := z) .. => z #eval checkWithMkMatcherInput ``Foo.z.match_1 #eval (Foo.mk₁ 10 20 30 40).z theorem ex7 : (Foo.mk₁ 10 20 30 40).z = 30 := rfl def Foo.addY? : Foo × Foo → Option Nat | (mk₁ (y := y₁) .., mk₁ (y := y₂) ..) => some (y₁ + y₂) | _ => none #eval checkWithMkMatcherInput ``Foo.addY?.match_1 #eval Foo.addY? (Foo.mk₁ 1 2 3 4, Foo.mk₁ 10 20 30 40) theorem ex8 : Foo.addY? (Foo.mk₁ 1 2 3 4, Foo.mk₁ 10 20 30 40) = some 22 := rfl instance {α} : Inhabited (Sigma fun m => Vec α m) := ⟨⟨0, Vec.nil⟩⟩ partial def filter {α} (p : α → Bool) : {n : Nat} → Vec α n → Sigma fun m => Vec α m | _, Vec.nil => ⟨0, Vec.nil⟩ | _, Vec.cons x xs => match p x, filter p xs with | true, ⟨_, ys⟩ => ⟨_, Vec.cons x ys⟩ | false, ys => ys #eval checkWithMkMatcherInput ``filter.match_1 inductive Bla | ofNat (x : Nat) | ofBool (x : Bool) def Bla.optional? : Bla → Option Nat | ofNat x => some x | ofBool _ => none #eval checkWithMkMatcherInput ``Bla.optional?.match_1 def Bla.isNat? (b : Bla) : Option { x : Nat // optional? b = some x } := match b.optional? with | some y => some ⟨y, rfl⟩ | none => none #eval checkWithMkMatcherInput ``Bla.isNat?.match_1 def foo (b : Bla) : Option Nat := b.optional? theorem fooEq (b : Bla) : foo b = b.optional? := rfl def Bla.isNat2? (b : Bla) : Option { x : Nat // optional? b = some x } := match h:foo b with | some y => some ⟨y, Eq.trans (fooEq b).symm h⟩ | none => none #eval checkWithMkMatcherInput ``Bla.isNat2?.match_1 def foo2 (x : Nat) : Nat := match x, rfl : (y : Nat) → x = y → Nat with | 0, h => 0 | x+1, h => 1 #eval checkWithMkMatcherInput ``foo2.match_1
This is awesome images ideas about Small Courtyard Garden Design Inspiraions 12. Hopefully these will give you some inspirations. This Images is part of our Inspiring Small Courtyard Garden Design for Your House pictures gallery. A curated list of images that will get you Good ideas and Inspiration.
import .struc3 open category_theory def Magma2 : Type 1 := Σ (G : Type), G → G → G def Magma_struc : struc Type := struc.sigma_arrow Type (𝟭 Type) (struc.sigma_arrow Type (𝟭 Type) (struc.of_functor (𝟭 Type))) example (A B : sigma Magma_struc) : (A ⟶ B) ≃ { f : A.1 → B.1 // ∀ x y, f (A.2 x y) = B.2 (f x) (f y) } := { to_fun := λ f, ⟨f.1, λ x y, begin cases f with f₁ f₂, cases A with A₁ A₂, cases B with B₁ B₂, dsimp at *, specialize f₂ x _ rfl, cases f₂ with f₂ f₃, dunfold quiver.hom at *, dsimp at *, have f₄ := f₃ y _ rfl, cases f₄, dsimp at *, end⟩ }
(* Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Authors: Russell O'Connor *) Require Vector. Require Import Arith List Eqdep_dec. Require Import FunctionalExtensionality. Set Asymmetric Patterns. Set Implicit Arguments. Unset Strict Implicit. Lemma Vector_map_id n a (f : a -> a) (v : Vector.t a n) : (forall x, f x = x) -> (Vector.map f v) = v. Proof. intros H. induction v. reflexivity. simpl. rewrite IHv, H. reflexivity. Qed. Lemma Vector_map_compose n a b c (g : b -> c) (f : a -> b) (h : a -> c) (v : Vector.t a n) : (forall x, g (f x) = h x) -> Vector.map g (Vector.map f v) = Vector.map h v. Proof. intros H. induction v. reflexivity. simpl. rewrite IHv, H. reflexivity. Qed. Lemma Vector_map_append n m a b (f : a -> b) (v1 : Vector.t a n) (v2 : Vector.t a m) : Vector.map f (Vector.append v1 v2) = Vector.append (Vector.map f v1) (Vector.map f v2). Proof. induction v1. reflexivity. simpl. rewrite IHv1. reflexivity. Qed. Lemma append_inj a n m (v1 v1' : Vector.t a n) (v2 v2' : Vector.t a m) : Vector.append v1 v2 = Vector.append v1' v2' -> v1 = v1' /\ v2 = v2'. Proof. revert n v1 v1'. apply (Vector.rect2 (fun n v1 v1' => Vector.append v1 v2 = Vector.append v1' v2' -> v1 = v1' /\ v2 = v2')). intros H; split. reflexivity. assumption. simpl. intros n t t' IH h h' H. injection H. intros dep1 Hh. rewrite Hh; clear Hh. destruct IH as [IH1 IH2]. refine (inj_pair2_eq_dec _ _ _ _ _ _ dep1). decide equality. rewrite IH1. split. reflexivity. assumption. Qed. Lemma append_assoc a n m p (v1 : Vector.t a n) (v2 : Vector.t a m) (v3 : Vector.t a p) (e : n + (m + p) = n + m + p) : eq_rect _ _ (Vector.append v1 (Vector.append v2 v3)) _ e = Vector.append (Vector.append v1 v2) v3. Proof. induction v1; simpl in *. pattern e. apply K_dec_set. decide equality. reflexivity. injection e. intros e'. rewrite <- (IHv1 e'). clear IHv1. revert e. generalize e'. rewrite <- e'. clear e'; intros e'. pattern e'. apply K_dec_set. decide equality. apply K_dec_set. decide equality. reflexivity. Qed. Lemma to_list_eq A n m (e: n = m) : forall (v1 : Vector.t A n) (v2 : Vector.t A m), Vector.to_list v1 = Vector.to_list v2 -> eq_rect _ (Vector.t A) v1 _ e = v2. Proof. rewrite e. (* magical *) simpl. clear n e. revert m. apply (Vector.rect2 (fun m (v1 v2 : Vector.t A m) => Vector.to_list v1 = Vector.to_list v2 -> v1 = v2)). reflexivity. intros n v1 v2 IH a b H. injection H; intros H1 H2. rewrite IH. rewrite H2. reflexivity. assumption. Qed. Record KleeneStore i j a := kleeneStore { dim : nat ; peek : Vector.t j dim -> a ; pos : Vector.t i dim }. Definition extract i a (s : KleeneStore i i a) : a := peek (pos s). Definition KSmap i j a b (f : a -> b) (s : KleeneStore i j a) : KleeneStore i j b := kleeneStore (fun v => f (peek v)) (pos s). Definition duplicate i j k a (s : KleeneStore i k a) : KleeneStore i j (KleeneStore j k a) := kleeneStore (fun v => kleeneStore (peek (k:=s)) v) (pos s). Record KleeneCoalg (i o : Type -> Type) := kleeneCoalg { coalg :> forall a b, (o a) -> KleeneStore (i a) (i b) (o b) ; coalg_extract : forall a (x:o a), extract (coalg _ x) = x ; coalg_duplicate : forall a b c (x:o a), duplicate (i b) (coalg c x) = KSmap (coalg c) (coalg b x) }. Lemma free_b_dim i o (k : KleeneCoalg i o) a b b' (x : o a) : dim (coalg k b x) = dim (coalg k b' x). Proof. apply (f_equal (fun x=> dim x) (@coalg_duplicate i o k a b' b x)). Qed. Lemma free_b_pos i o (k : KleeneCoalg i o) a b b' (x : o a) : eq_rect _ _ (pos (coalg k b x)) _ (free_b_dim k _ _ x) = pos (coalg k b' x). Proof. assert (H := (@coalg_duplicate i o k a b' b x)). change (pos (k a b' x)) with (pos (KSmap (k b' b) (k a b' x))). change (pos (k a b x)) with (pos (duplicate (i b') (k a b x))). generalize (free_b_dim k b b' x). change (dim (k a b' x)) with (dim (KSmap (k b' b) (k a b' x))). change (dim (k a b x)) with (dim (duplicate (i b') (k a b x))). rewrite H. apply K_dec_set. decide equality. reflexivity. Qed. (* Definition KCmap i o (k : KleeneCoalg i o) a b (f : i a -> i b) (x : o a) : o b := let s := k _ _ x in peek (Vector.map f (pos s)). *) Section Traversable. Variable t : Type -> Type. Variable traverse : KleeneCoalg (fun x => x) t. Definition size a (x:t a) : nat := dim (traverse a a x). Lemma size_preservation a b (x: t a) v : size (peek (k:=traverse a b x) v) = size x. Proof. unfold size. replace (coalg traverse (a:=b) b (peek (k:=traverse a b x) v)) with (peek (k:=(duplicate b (coalg traverse b x))) v). rewrite (free_b_dim traverse a b). reflexivity. change v with (eq_rect (dim (traverse a b x)) (Vector.t b) v (dim (duplicate b (traverse a b x))) (refl_equal _)) at 1. generalize (eq_refl (dim (traverse a b x))). change (dim (traverse a b x)) with (dim (duplicate b (traverse a b x))) at 2. rewrite (coalg_duplicate traverse b b x). apply K_dec_set; [ decide equality |]. reflexivity. Qed. Lemma dim_preservation a a' b b' (x: t a) v : dim (traverse b b' (peek (k:=traverse a b x) v)) = dim (traverse a a' x). Proof. change (dim (peek (k:=KSmap (traverse b b') (traverse a b x)) v) = dim (traverse a a' x)). change (Vector.t b (dim (KSmap (traverse b b') (traverse a b x)))) in v. revert v. rewrite <- (coalg_duplicate traverse b b'). simpl. intros _. rewrite (free_b_dim traverse a' b'). reflexivity. Qed. Definition iso1 a (x: t a) : {x : t unit & Vector.t a (size x)} := let s := coalg traverse unit x in existT (fun x : t unit => Vector.t a (size x)) (peek (k:=s) (Vector.const tt _)) (eq_rect _ (Vector.t a) (pos s) _ (eq_sym (dim_preservation _ _ _))). Definition iso2 a (y : {x : t unit & Vector.t a (size x)}) : t a := let (t,s) := y in peek (k:=coalg traverse a t) (eq_rect _ (Vector.t a) s _ (eq_sym (free_b_dim _ _ _ _))). Lemma iso2_iso1 a (x : t a) : iso2 (iso1 x) = x. Proof. simpl. unfold size. set (e1 := (eq_sym (dim_preservation _ _ _))). set (e2 := (eq_sym (free_b_dim traverse (a:=unit) a unit (peek (k:=traverse a unit x) (Vector.const tt (dim (traverse a unit x))))))). generalize e1 e2. rewrite <- e1. clear e1 e2. (* turn this into a match goal *) apply (fun H => K_dec_set H (fun e1 : dim (traverse a unit x) = dim (traverse a unit x) => forall e2 : dim (traverse a unit x) = dim (traverse unit a (peek (k:=traverse a unit x) (Vector.const tt (dim (traverse a unit x))))), peek (k:=traverse unit a (peek (k:=traverse a unit x) (Vector.const tt (dim (traverse a unit x))))) (eq_rect (dim (traverse a unit x)) (Vector.t a) (eq_rect (dim (traverse a unit x)) (Vector.t a) (pos (traverse a unit x)) (dim (traverse a unit x)) e1) (dim (traverse unit a (peek (k:=traverse a unit x) (Vector.const tt (dim (traverse a unit x)))))) e2) = x)). decide equality. simpl. pose (Z0 := KSmap (traverse unit a) (traverse a unit x)). pose (Z1 := peek (k:=Z0) (Vector.const tt _)). change (traverse unit a (peek (k:= traverse a unit x) (Vector.const tt _))) with (peek (k:=Z0) (Vector.const tt _)). unfold Z0. rewrite <- (coalg_duplicate traverse). simpl. rewrite <- (free_b_pos traverse a unit x). generalize (free_b_dim traverse a unit x). intros e. generalize e. rewrite <- e. (* turn this into a match goal *) apply (fun H => K_dec_set H (fun e0 : dim (traverse a a x) = dim (traverse a a x) => forall e2 : dim (traverse a a x) = dim (traverse a a x), peek (k:=traverse a a x) (eq_rect (dim (traverse a a x)) (Vector.t a) (eq_rect (dim (traverse a a x)) (Vector.t a) (pos (traverse a a x)) (dim (traverse a a x)) e0) (dim (traverse a a x)) e2) = x)). decide equality. apply K_dec_set. decide equality. simpl. change (extract (traverse a a x) = x). apply (coalg_extract traverse x). Qed. Lemma iso1_iso2_1 a (y : {x : t unit & Vector.t a (size x)}) : projT1 (iso1 (iso2 y)) = projT1 y. Proof. destruct y as [x v]. simpl. set (a' := (eq_rect (size x) (Vector.t a) v (dim _) _)). clearbody a'. pose (X := KSmap (traverse a unit) (traverse unit a x)). change (Vector.t a (dim X)) in a'. change (peek (k:=(peek (k:=X) a')) (Vector.const tt _) = x). generalize a'. unfold X. rewrite <- (coalg_duplicate traverse a unit). simpl. intros _. replace (Vector.const tt (dim (traverse unit unit x))) with (pos (traverse unit unit x)). apply (coalg_extract traverse). generalize (pos (traverse unit unit x)). clear - x. induction t0. reflexivity. rewrite IHt0. destruct h. reflexivity. Qed. Lemma iso1_iso2_2 a (y : {x : t unit & Vector.t a (size x)}) : eq_rect _ (Vector.t a) (projT2 (iso1 (iso2 y))) _ (f_equal (@size unit) (iso1_iso2_1 y)) = projT2 y. Proof. set (e := (f_equal _ _)). clearbody e. destruct y. set (t1 := projT1 (iso1 _)) in *. simpl in *. set (e1 := (eq_sym (dim_preservation _ _ _))). clearbody e1. fold t1 in e1 |- *. change (dim (traverse unit unit t1)) with (size t1) in e1 |- *. generalize e e1. rewrite e. (* turn this into a match goal *) apply (fun H => K_dec_set H (fun e0 : size x = size x => forall (e2 : dim (traverse a unit (peek (k:=traverse unit a x) (eq_rect (size x) (Vector.t a) t0 (dim (traverse unit a x)) (eq_sym (free_b_dim traverse (a:=unit) a unit x))))) = size x), eq_rect (size x) (Vector.t a) (eq_rect (dim (traverse a unit (peek (k:=traverse unit a x) (eq_rect (size x) (Vector.t a) t0 (dim (traverse unit a x)) (eq_sym (free_b_dim traverse (a:=unit) a unit x)))))) (Vector.t a) (pos (traverse a unit (peek (k:=traverse unit a x) (eq_rect (size x) (Vector.t a) t0 (dim (traverse unit a x)) (eq_sym (free_b_dim traverse (a:=unit) a unit x)))))) (size x) e2) (size x) e0 = t0)). decide equality. simpl. clear e e1 t1. pose (X := KSmap (traverse a unit) (traverse unit a x)). set (e :=(eq_sym (free_b_dim traverse (a:=unit) a unit x))). clearbody e. change (dim (traverse unit a x)) with (dim X) in e|- *. set (a' := eq_rect (size x) _ _ (dim X) e). change (traverse a unit _) with (peek (k:=X) a'). unfold a'; clear a'. revert e. replace X with (duplicate a (traverse unit unit x)); [|rewrite (coalg_duplicate traverse); reflexivity]. (* turn this into a match goal *) apply (fun H => K_dec_set H (fun e : dim (traverse unit unit x) = dim (duplicate a (traverse unit unit x)) => forall (e1 : dim (peek (k:=duplicate a (traverse unit unit x)) (eq_rect (size x) (Vector.t a) t0 (dim (duplicate a (traverse unit unit x))) e)) = dim (traverse unit unit x)), eq_rect (dim (peek (k:=duplicate a (traverse unit unit x)) (eq_rect (size x) (Vector.t a) t0 (dim (duplicate a (traverse unit unit x))) e))) (Vector.t a) (pos (peek (k:=duplicate a (traverse unit unit x)) (eq_rect (size x) (Vector.t a) t0 (dim (duplicate a (traverse unit unit x))) e))) (dim (traverse unit unit x)) e1 = t0)). decide equality. apply K_dec_set. decide equality. reflexivity. Qed. Lemma iso1_iso2 a (y : {x : t unit & Vector.t a (size x)}) : (iso1 (iso2 y)) = y. Proof. assert (H2 := iso1_iso2_2 y). revert H2. set (e:= (f_equal _ _)). generalize e; clear e. assert (H2 := iso1_iso2_1 y). revert H2. destruct (iso1 (iso2 y)). destruct y. simpl. intros e. revert t0. rewrite e. intros t0. (* turn this into a match goal *) apply (fun H => K_dec_set H (fun e0 : size x0 = size x0 =>eq_rect (size x0) (Vector.t a) t0 (size x0) e0 = t1 -> existT (fun x1 : t unit => Vector.t a (size x1)) x0 t0 = existT (fun x1 : t unit => Vector.t a (size x1)) x0 t1)). decide equality. simpl. intros e0; rewrite e0. reflexivity. Qed. Lemma iso_coalg a b (x : t a) : (let (s,v) := iso1 x in kleeneStore (fun b => iso2 (existT _ s b)) v) = traverse a b x. Proof. unfold iso1; simpl. unfold size; simpl. generalize (eq_sym (dim_preservation unit unit (x:=x) (Vector.const tt (dim (traverse a unit x))))). set (e' := (eq_sym (free_b_dim traverse (a:=unit) b unit (peek (k:=traverse a unit x) (Vector.const tt (dim (traverse a unit x))))))). generalize e'. clear e'. rewrite (dim_preservation unit unit (Vector.const tt (dim (traverse a unit x)))). set (d:= dim (traverse a unit x)). unfold d at 1 3 4 5 6 8 10 11. intros e. apply K_dec_set. decide equality. simpl. revert e. rewrite <- (free_b_pos traverse (a:=a) b unit x). generalize (free_b_dim traverse (a:=a) b unit x). intros e; generalize e; rewrite <- e; clear e. (* turn this into a match goal *) apply (fun H => K_dec_set H (fun e : dim (traverse a b x) = dim (traverse a b x) => forall (e0 : dim (traverse a b x) = dim (traverse unit b (peek (k:=traverse a unit x) (Vector.const tt d)))), {| dim := dim (traverse a b x); peek := fun b0 : Vector.t b (dim (traverse a b x)) => peek (k:=traverse unit b (peek (k:=traverse a unit x) (Vector.const tt d))) (eq_rect (dim (traverse a b x)) (Vector.t b) b0 (dim (traverse unit b (peek (k:=traverse a unit x) (Vector.const tt d)))) e0); pos := eq_rect (dim (traverse a b x)) (Vector.t a) (pos (traverse a b x)) (dim (traverse a b x)) e |} = traverse a b x)). decide equality. simpl. intros e. transitivity (kleeneStore (peek (k:=traverse a b x)) (pos (traverse a b x))); [|destruct (traverse a b x); reflexivity]. f_equal. apply functional_extensionality; intros v. revert e. change (forall e : dim (traverse a b x) = (dim (peek (k:=(KSmap (traverse unit b) (traverse a unit x))) (Vector.const tt d))), peek (k:=(peek (k:=KSmap (traverse unit b) (traverse a unit x)) (Vector.const tt d))) (eq_rect (dim (traverse a b x)) (Vector.t b) v (dim (peek (k:=(KSmap (traverse unit b) (traverse a unit x))) (Vector.const tt d))) e) = peek (k:=traverse a b x) v). change d with (dim (KSmap (traverse unit b) (traverse a unit x))). clear d. set (X:=(KSmap (traverse unit b) (traverse a unit x))). replace X with (duplicate unit (traverse a b x)) by apply (coalg_duplicate traverse unit b x). clear X. simpl. apply K_dec_set. decide equality. reflexivity. Qed. End Traversable. (******************************************************************************) Record Applicative := applicative { carrier :> Type -> Type ; pure : forall a, a -> carrier a ; ap : forall a b, carrier (a -> b) -> carrier a -> carrier b ; map := fun a b (f : a -> b) x => ap (pure f) x ; _ : forall (a : Type) x, map (fun (y : a) => y) x = x ; _ : forall a b c x y z, ap (ap (map (fun (f : b -> c) (g : a -> b) (w:a) => f (g w)) x) y) z = ap x (ap y z) ; _ : forall a b (f : a -> b) x, map f (pure x) = pure (f x) ; _ : forall a b (f : carrier (a -> b)) x, ap f (pure x) = map (fun g => g x) f }. Fixpoint sequenceVector n a (F:Applicative) (v: Vector.t (F a) n) : F (Vector.t a n) := match v in Vector.t _ n return F (Vector.t a n) with | Vector.nil => pure _ (Vector.nil _) | Vector.cons h m t => ap (map (fun x => Vector.cons _ x m) h) (sequenceVector t) end. Definition traverseVector n a b (F:Applicative) (f : a -> F b) (v : Vector.t a n) : F (Vector.t b n) := sequenceVector (Vector.map f v). Lemma identity_law (F : Applicative) a (x : F a) : map (fun (y : a) => y) x = x. Proof. destruct F. auto. Qed. Lemma composition_law (F : Applicative) a b c x y (z : F a) : ap (ap (map (fun (f : b -> c) (g : a -> b) (w:a) => f (g w)) x) y) z = ap x (ap y z). Proof. destruct F. auto. Qed. Lemma homomorphism_law (F : Applicative) a b (f : a -> b) x : ap (pure F f) (pure F x) = pure F (f x). Proof. fold (map f (pure F x)). destruct F. auto. Qed. Lemma interchange_law (F : Applicative) a b (f : F (a -> b)) x : ap f (pure F x) = map (fun g => g x) f. Proof. destruct F. auto. Qed. Lemma map_compose a b c (F : Applicative) (g : b -> c) (f: a -> b) (h : a -> c) (x : F a) : (forall x, g (f x) = h x) -> map g (map f x) = map h x. Proof. intros H. unfold map; rewrite <- composition_law. unfold map; rewrite !homomorphism_law. repeat f_equal. apply functional_extensionality. assumption. Qed. Definition IdApplicative : Applicative. exists (fun A => A) (fun a (x : a) => x) (fun a b (f : a -> b) => f); try reflexivity. Defined. Definition NatPlusApplicative : Applicative. exists (fun _ => nat) (fun _ _ => 0) (fun a b => plus). reflexivity. intros _ _ _ x y z. apply plus_assoc_reverse. reflexivity. intros _ _ x _. apply plus_0_r. Defined. Definition ConstListApplicative (a : Type) : Applicative. exists (fun _ => list a) (fun _ _ => nil) (fun _ _ => (@app a)). reflexivity. intros _ _ _ x y z. apply app_assoc_reverse. reflexivity. intros _ _ x _. apply app_nil_r. Defined. Definition KSpure i j a (x : a) : KleeneStore i j a := kleeneStore (fun v => x) (Vector.nil _). Definition append_view A n p (P : Vector.t A (n + p) -> Type) : (forall v1 v2, P (Vector.append v1 v2)) -> forall v, P v. induction n. intros f v. apply (f (Vector.nil _)). intros f v. replace v with (Vector.cons _ (Vector.hd v) (n + p) (Vector.tl v)). destruct (Vector.tl v) as [v1 v2] using IHn. apply (f (Vector.cons _ (Vector.hd v) _ v1)). assert (forall m (v : Vector.t A (S m)), Vector.cons A (Vector.hd v) m (Vector.tl v) = v). clear -A. apply Vector.caseS. reflexivity. apply H. Defined. Lemma append_view_append A n p (P : Vector.t A (n + p) -> Type) f v1 v2 : append_view (P:=P) f (Vector.append v1 v2) = f v1 v2. Proof. induction v1. reflexivity. simpl. rewrite IHv1. reflexivity. Qed. Definition KSap i j a b (g : KleeneStore i j (a -> b)) (k : KleeneStore i j a) : KleeneStore i j b := kleeneStore (fun v => append_view (P := fun _ => b) (fun v1 v2 => (peek (k:=g) v1) (peek (k:=k) v2)) v) (Vector.append (pos g) (pos k)). Lemma KSpure_KSap_KSmap i j a b (f : a -> b) (k : KleeneStore i j a) : KSap (KSpure i j f) k = KSmap f k. Proof. reflexivity. Qed. Lemma KSpure_id i j a (k : KleeneStore i j a) : KSap (KSpure i j (fun x => x)) k = k. Proof. destruct k. reflexivity. Qed. Lemma equivalent_KS i j a (dim1 dim2 : nat) (peek1 : Vector.t j dim1 -> a) (peek2 : Vector.t j dim2 -> a) (pos1 : Vector.t i dim1) (pos2 : Vector.t i dim2) (e : dim1 = dim2) : (forall (v1 : Vector.t j dim1) (v2 : Vector.t j dim2), (eq_rect _ _ v1 _ e) = v2 -> peek1 v1 = peek2 v2) -> eq_rect _ _ pos1 _ e = pos2 -> kleeneStore peek1 pos1 = kleeneStore peek2 pos2. Proof. intros Hpeek Hpos. transitivity (kleeneStore (fun v => peek1 (eq_rect _ _ v _ (eq_sym e))) (eq_rect _ _ pos1 _ e)). clear Hpeek Hpos. generalize e. rewrite <- e. apply K_dec_set. decide equality. reflexivity. rewrite Hpos. f_equal. apply functional_extensionality; intros v. apply Hpeek. generalize e. rewrite e. apply K_dec_set. decide equality. reflexivity. Qed. Lemma composition_KS i j a b c x y (z : KleeneStore i j a) : KSap (KSap (KSap (KSpure i j (fun (f : b -> c) (g : a -> b) (x : a) => f (g x))) x) y) z = KSap x (KSap y z). Proof. destruct x; destruct y; destruct z. unfold KSap. simpl. apply (equivalent_KS (e:=(eq_sym (plus_assoc dim0 dim1 dim2)))). intros v1 v2. pattern v1; apply append_view; intros v1' v1c. pattern v1'; apply append_view; intros v1a v1b. pattern v2; apply append_view; intros v2a v2'. pattern v2'; apply append_view; intros v2b v2c. repeat rewrite append_view_append. clear -v2c. rewrite <- (append_assoc _ _ _ (plus_assoc _ _ _)). generalize (eq_sym (plus_assoc dim0 dim1 dim2)). generalize (plus_assoc dim0 dim1 dim2). intros e; generalize e; rewrite <- e; clear e. intros e; pattern e; apply K_dec_set; clear e. decide equality. intros e; pattern e; apply K_dec_set; clear e. decide equality. simpl; intros H. destruct (append_inj H) as [H0 H']. destruct (append_inj H') as [H1 H2]. rewrite H0, H1, H2. reflexivity. clear -i. apply to_list_eq. induction pos0. reflexivity. simpl. unfold Vector.to_list in *. rewrite IHpos0. reflexivity. Qed. Lemma KSpure_KSpure i j a b (f : a -> b) (x : a): KSap (KSpure i j f) (KSpure i j x) = KSpure i j (f x). Proof. reflexivity. Qed. Lemma interchange_KSpure i j a b (f : KleeneStore i j (a -> b)) (x : a): KSap f (KSpure i j x) = KSap (KSpure i j (fun f => f x)) f. Proof. destruct f as [dimf peekf posf]. unfold KSap. simpl. symmetry. apply (equivalent_KS (e:=(eq_sym (plus_0_r dimf)))). intros v1 v2 Hv. replace v2 with (Vector.append v1 (Vector.nil _)). rewrite append_view_append; reflexivity. rewrite <- Hv. clear -v1. symmetry. apply to_list_eq. induction v1. reflexivity. simpl. unfold Vector.to_list in *. rewrite IHv1. reflexivity. apply to_list_eq. clear -posf. induction posf. reflexivity. simpl. unfold Vector.to_list in *. rewrite IHposf. reflexivity. Qed. Definition KSApplicative (i j : Type) : Applicative. exists (KleeneStore i j) (KSpure i j) (@KSap i j). apply KSpure_id. apply composition_KS. apply KSpure_KSpure. apply interchange_KSpure. Defined. Section ComposeApplicative. Variable (F G :Applicative). Let FG (a:Type) := F (G a). Definition Compose_pure (a:Type) (x:a) : FG a := pure F (pure G x). Definition Compose_ap (a b:Type) (f:FG (a -> b)) (x:FG a) : FG b := ap (ap (pure F (fun g x => ap g x)) f) x. Lemma Compose_identity (a:Type) (x : FG a): Compose_ap (Compose_pure (fun y : a => y)) x = x. Proof. unfold Compose_ap, Compose_pure. rewrite homomorphism_law. replace (fun x0 : G a => ap (a:=G) (a0:=a) (b:=a) (pure G (fun y : a => y)) x0) with (fun (y : G a) => y). apply identity_law. apply functional_extensionality; intro y. symmetry. apply identity_law. Qed. Lemma Compose_composition (a b c:Type) x y (z : FG a) : Compose_ap (Compose_ap (Compose_ap (Compose_pure (fun (f : b -> c) (g : a -> b) (w:a) => f (g w))) x) y) z = Compose_ap x (Compose_ap y z). Proof. unfold Compose_ap, Compose_pure. repeat rewrite homomorphism_law. repeat (unfold map; simpl; (repeat rewrite homomorphism_law); rewrite <- composition_law). unfold map; simpl; repeat rewrite homomorphism_law. repeat rewrite interchange_law. repeat (unfold map; simpl; (repeat rewrite homomorphism_law); rewrite <- composition_law). unfold map; simpl; repeat rewrite homomorphism_law. replace (fun (w : G (b -> c)) (w0 : G (a -> b)) (x0 : G a) => ap (a:=G) (a0:=a) (b:=c) (ap (a:=G) (a0:=a -> b) (b:=a -> c) (ap (a:=G) (a0:=b -> c) (b:=(a -> b) -> a -> c) (pure G (fun (f : b -> c) (g : a -> b) (w1 : a) => f (g w1))) w) w0) x0) with (fun (w : G (b -> c)) (w0 : G (a -> b)) (w1 : G a) => ap (a:=G) (a0:=b) (b:=c) w (ap (a:=G) (a0:=a) (b:=b) w0 w1)). reflexivity. repeat (apply functional_extensionality; intro). symmetry. apply composition_law. Qed. Lemma Compose_homomorphism a b (f : a -> b) x : Compose_ap (Compose_pure f) (Compose_pure x) = Compose_pure (f x). Proof. unfold Compose_ap, Compose_pure. repeat rewrite homomorphism_law. reflexivity. Qed. Lemma Compose_interchange a b (f : FG (a -> b)) x : Compose_ap f (Compose_pure x) = Compose_ap (Compose_pure (fun g => g x)) f. Proof. unfold Compose_ap, Compose_pure. repeat rewrite homomorphism_law. repeat rewrite interchange_law. repeat (unfold map; simpl; (repeat rewrite homomorphism_law); rewrite <- composition_law). repeat rewrite interchange_law. unfold map; simpl; repeat rewrite homomorphism_law. replace (fun w : G (a -> b) => ap (a:=G) (a0:=a) (b:=b) w (pure G x)) with (fun x0 : G (a -> b) => ap (a:=G) (a0:=a -> b) (b:=b) (pure G (fun g : a -> b => g x)) x0). reflexivity. apply functional_extensionality; intro. symmetry. apply interchange_law. Qed. Definition ComposeApplicative : Applicative. exists FG Compose_pure Compose_ap. apply Compose_identity. apply Compose_composition. apply Compose_homomorphism. apply Compose_interchange. Defined. End ComposeApplicative. Lemma sequenceVector_Id n a (v: Vector.t a n) : sequenceVector (F:=IdApplicative) v = v. Proof. induction v. reflexivity. simpl. rewrite IHv. reflexivity. Qed. Lemma sequenceVector_map n a b (F:Applicative) (f : a -> b) (v :Vector.t (F a) n) : map (Vector.map f) (sequenceVector v) = sequenceVector (Vector.map (map f) v). Proof. induction v. unfold map; simpl. rewrite homomorphism_law. reflexivity. simpl. rewrite <- IHv. repeat (repeat rewrite homomorphism_law; repeat rewrite <- composition_law; unfold map). rewrite interchange_law. repeat (repeat rewrite homomorphism_law; repeat rewrite <- composition_law; unfold map). reflexivity. Qed. Lemma sequenceVector_compose n a (F G:Applicative) (v :Vector.t (F (G a)) n) : sequenceVector (F:=ComposeApplicative F G) v = map (fun x => sequenceVector x) (sequenceVector v). Proof. induction v. simpl. unfold map. rewrite homomorphism_law. reflexivity. simpl. rewrite IHv. unfold map. unfold Compose_ap, Compose_pure. repeat (repeat rewrite homomorphism_law; repeat rewrite <- composition_law; unfold map). rewrite interchange_law. repeat (repeat rewrite homomorphism_law; repeat rewrite <- composition_law; unfold map). reflexivity. Qed. Lemma sequenceVector_append n m a (F:Applicative) (v1:Vector.t (F a) n) (v2:Vector.t (F a) m) : sequenceVector (Vector.append v1 v2) = ap (map (fun x y => Vector.append x y) (sequenceVector v1)) (sequenceVector v2). Proof. induction v1; simpl. unfold map; rewrite homomorphism_law; simpl. symmetry; apply identity_law. rewrite IHv1; clear IHv1. unfold map. repeat (repeat rewrite homomorphism_law; repeat rewrite <- composition_law; unfold map). rewrite interchange_law. repeat (repeat rewrite homomorphism_law; repeat rewrite <- composition_law; unfold map). reflexivity. Qed. Record IdiomaticTransformation (F G:Applicative) := idiomaticTransformation { transform :> forall a, F a -> G a ; _ : forall a (x:a), transform (pure F x) = pure G x ; _ : forall a b (f : F (a -> b)) x, transform (ap f x) = ap (transform f) (transform x) }. Section IdiomaticTransformation. Variables (F G:Applicative). Variable (eta : IdiomaticTransformation F G). Lemma idiomaticTransform_pure a (x:a) : eta _ (pure F x) = pure G x. Proof. destruct eta. auto. Qed. Lemma idiomaticTransform_ap a b (f: F (a -> b)) (x: F a) : eta _ (ap f x) = ap (eta _ f) (eta _ x). Proof. destruct eta. auto. Qed. Lemma idiomaticTransform_map a b (f: a -> b) (x: F a) : eta _ (map f x) = map f (eta _ x). Proof. unfold map. rewrite idiomaticTransform_ap, idiomaticTransform_pure. reflexivity. Qed. Lemma idiomaticTransform_sequenceVector n a (v : Vector.t (F a) n) : eta _ (sequenceVector v) = sequenceVector (Vector.map (eta _) v). Proof. induction v. apply idiomaticTransform_pure. simpl; rewrite idiomaticTransform_ap, idiomaticTransform_map, IHv. reflexivity. Qed. Lemma idiomaticTransform_traverseVector n a b (f : a -> F b) (v : Vector.t a n) : eta _ (traverseVector f v) = traverseVector (fun y => eta _ (f y)) v. Proof. unfold traverseVector. rewrite idiomaticTransform_sequenceVector. f_equal. apply Vector_map_compose. reflexivity. Qed. End IdiomaticTransformation. Lemma extract_pure i a (x : a) : extract (KSpure i i x) = x. Proof. reflexivity. Qed. Lemma extract_ap i a b (f : KleeneStore i i (a -> b)) (x : KleeneStore i i a) : extract (KSap f x) = extract f (extract x). Proof. destruct f; destruct x. simpl. rewrite append_view_append. reflexivity. Qed. Definition extractIT i : IdiomaticTransformation (KSApplicative i i) IdApplicative. exists (@extract i). exact (@extract_pure i). exact (@extract_ap i). Defined. Lemma duplicate_pure i j k a (x : a) : duplicate j (KSpure i k x) = KSpure i j (KSpure j k x). Proof. unfold KSpure, duplicate. simpl. f_equal. apply functional_extensionality. apply Vector.case0. reflexivity. Qed. Lemma duplicate_ap i j k a b (f : KleeneStore i k (a -> b)) (x : KleeneStore i k a): duplicate j (KSap f x) = ap (a:=ComposeApplicative (KSApplicative i j) (KSApplicative j k)) (duplicate j f) (duplicate j x). Proof. simpl. unfold KSap, duplicate. simpl. f_equal. apply functional_extensionality. apply append_view; intros v1 v2. rewrite append_view_append. reflexivity. Qed. Definition duplicateIT i j k : IdiomaticTransformation (KSApplicative i k) (ComposeApplicative (KSApplicative i j) (KSApplicative j k)). exists (@duplicate i j k). exact (@duplicate_pure i j k). exact (@duplicate_ap i j k). Defined. Definition dimIT i j : IdiomaticTransformation (KSApplicative i j) NatPlusApplicative. exists (@dim i j). reflexivity. reflexivity. Defined. Lemma pos_ap i j a b (f : KleeneStore i j (a -> b)) (x : KleeneStore i j a) : Vector.to_list (pos (KSap f x)) = app (Vector.to_list (pos f)) (Vector.to_list (pos x)). Proof. simpl. induction (pos f). reflexivity. unfold Vector.to_list in *. simpl. rewrite IHt. reflexivity. Qed. Definition posIT i j : IdiomaticTransformation (KSApplicative i j) (ConstListApplicative i). exists (fun a (x : KSApplicative i j a) => Vector.to_list (pos x)). reflexivity. apply (@pos_ap i j). Defined. Section Research. Variables (F:Applicative) (a b : Type) (h : a -> F b). Definition research c (k : KSApplicative a b c) : F c := map (peek (k:=k)) (sequenceVector (Vector.map h (pos k))). Lemma research_pure c (x : c) : research (pure _ x) = pure _ x. Proof. apply homomorphism_law. Qed. Lemma research_ap c d (f : KSApplicative a b (c -> d)) (x : KSApplicative a b c): research (ap f x) = ap (research f) (research x). Proof. unfold research; simpl. unfold map; simpl. rewrite Vector_map_append, sequenceVector_append. repeat (repeat rewrite homomorphism_law; repeat rewrite <- composition_law; unfold map). rewrite interchange_law. repeat (repeat rewrite homomorphism_law; repeat rewrite <- composition_law; unfold map). repeat f_equal. apply functional_extensionality_dep; intros v1. apply functional_extensionality; intros v2. rewrite append_view_append. reflexivity. Qed. Definition Research : IdiomaticTransformation (KSApplicative a b) F. exists research. exact research_pure. exact research_ap. Defined. End Research. Record Traversal := traversal { container :> Type -> Type ; traverse : forall a b (F : Applicative), (a -> F b) -> container a -> F (container b) ; free_applicative : forall a b (F G : Applicative) (eta : IdiomaticTransformation F G) (f : a -> F b) (x : container a), eta _ (traverse f x) = traverse (fun y => eta _ (f y)) x ; traverse_identity : forall a (x : container a), traverse (F:=IdApplicative) (fun y => y) x = x ; traverse_compose : forall a b c (F G : Applicative) (f : a -> F b) (g : b -> G c) (x : container a), traverse (F:=ComposeApplicative F G) (fun y => map g (f y)) x = map (traverse g) (traverse f x) }. Lemma traverseVector_free_applicative n a b (F G : Applicative) (eta :IdiomaticTransformation F G) (f : a -> F b) (x : Vector.t a n) : eta _ (traverseVector f x) = traverseVector (fun y => eta _ (f y)) x. Proof. induction x. unfold traverseVector; simpl. rewrite idiomaticTransform_pure. reflexivity. unfold traverseVector in *; simpl. rewrite idiomaticTransform_ap, idiomaticTransform_map. rewrite IHx. reflexivity. Qed. Lemma traverseVector_identity n a (x : Vector.t a n) : traverseVector (F:=IdApplicative) (fun y => y) x = x. Proof. unfold traverseVector. simpl. rewrite Vector_map_id. apply (sequenceVector_Id x). reflexivity. Qed. Lemma traverseVector_compose n a b c (F G : Applicative) (f : a -> F b) (g : b -> G c) (x : Vector.t a n) : traverseVector (F:=ComposeApplicative F G) (fun y => map g (f y)) x = map (traverseVector g) (traverseVector f x). Proof. unfold traverseVector. simpl. rewrite (sequenceVector_compose (Vector.map (fun y : a => map (a:=F) g (f y)) x)). rewrite <- (Vector_map_compose (g:=map (a:=F) g) (f:=f) (h:= (fun y : a => map (a:=F) g (f y)))); [|reflexivity]. rewrite <- sequenceVector_map. simpl. apply map_compose. reflexivity. Qed. Definition Vector (n : nat) : Traversal. exists (fun a => Vector.t a n) (@traverseVector n). apply traverseVector_free_applicative. apply traverseVector_identity. apply traverseVector_compose. Defined. Section Traversal. Definition impure a b (x : a) : KleeneStore a b b := kleeneStore (fun v => Vector.hd v) (Vector.cons _ x _ (Vector.nil _)). Lemma research_impure (F:Applicative) a b (h : a -> F b) (x : a) : research h (impure b x) = h x. Proof. unfold research; simpl; unfold map. repeat (repeat rewrite homomorphism_law; repeat rewrite <- composition_law; unfold map). rewrite interchange_law. repeat (repeat rewrite homomorphism_law; repeat rewrite <- composition_law; unfold map). replace (fun w : b => Vector.hd (Vector.cons b w 0 (Vector.nil b))) with (fun y : b => y). apply identity_law. apply functional_extensionality. reflexivity. Qed. Variable T : Traversal. (* Definition liftT a b (f : a -> b) := traverse (t:=T) (F:=IdApplicative) f. Lemma free_traversal_b a b b' (h : b -> b') (F : Applicative) (f : a -> F b) (x : T a) : map (liftT h) (traverse f x) = traverse (fun y => map h (f y)) x. Proof. unfold liftT. rewrite <- (traverse_compose (G:=IdApplicative) f h). assert (etaH : (forall (a b : Type) (f : F (a -> b)) (x : F a), Compose_ap (F:=F) (G:=IdApplicative) (a:=a) (b:=b) f x = ap (a:=F) (a0:=a) (b:=b) f x)). intros a0 b0; intros. unfold Compose_ap. simpl. replace ((fun (g : a0 -> b0) (x1 : a0) => g x1)) with (fun x : (a0 -> b0) => x). change (ap (pure F _) f0) with (map (fun x => x) f0). rewrite identity_law. reflexivity. apply functional_extensionality. reflexivity. pose (eta := @idiomaticTransformation (ComposeApplicative F IdApplicative) F (fun a x => x) (fun a x => refl_equal _) etaH). change (eta _ (traverse (t:=T) (b:=b') (F:=ComposeApplicative F IdApplicative) (fun y : a => map (a:=F) h (f y)) x) = traverse (t:=T) (b:=b') (F:=F) (fun y : a => map (a:=F) h (f y)) x). rewrite free_applicative. reflexivity. Qed. *) Let traversal_coalg a b := traverse (t:=T) (F:=KSApplicative a b) (impure (a:=a) b). Lemma traversal_coalg_extract a (x: T a) : extractIT _ _ (traversal_coalg _ x) = x. Proof. unfold traversal_coalg. rewrite free_applicative. apply traverse_identity. Qed. Lemma traversal_coalg_duplicate a b c (x: T a) : duplicateIT a b c _ (traversal_coalg c x) = KSmap (traversal_coalg c) (traversal_coalg b x). Proof. unfold traversal_coalg. rewrite free_applicative. replace (fun y : a => (duplicateIT a b c) c (impure c y)) with (fun y : a => (KSmap (impure c) (impure b y))). rewrite (@traverse_compose T a b c (KSApplicative a b) (KSApplicative b c) (impure b) (impure c)). reflexivity. apply functional_extensionality; intros y. simpl; unfold KSmap, duplicate; simpl. f_equal. apply functional_extensionality; intros v; clear -v. unfold impure. f_equal. transitivity (Vector.cons b (Vector.hd v) 0 (Vector.tl v)). f_equal. apply Vector.case0. reflexivity. (* this is a little screwy *) apply (Vector.caseS (fun n v => forall (t : Vector.t b n), Vector.cons b (Vector.hd v) n (Vector.tl v) = v)). reflexivity. constructor. Qed. (* Lemma traversal_free_b_dim a b b' (h : b -> b') (x: T a) : dimIT _ _ _ (traversal_coalg b x) = dimIT _ _ _ (traversal_coalg b' x). Proof. unfold traversal_coalg. do 2 rewrite free_applicative. simpl. change (map (liftT h) (traverse (t:=T) (b:=b) (F:=NatPlusApplicative) (fun y : a => (dimIT a b) b (impure b y)) x) = traverse (t:=T) (b:=b') (F:=NatPlusApplicative) (fun y : a => (dimIT a b') b' (impure b' y)) x). rewrite (@free_traversal_b a b b' h). reflexivity. Qed. Lemma traversal_free_b_pos a b b' (h : b -> b') (x: T a) : eq_rect _ _ (pos (traversal_coalg b x)) _ (traversal_free_b_dim h x) = pos (traversal_coalg b' x). Proof. apply to_list_eq. unfold traversal_coalg. change (posIT _ _ _ (traverse (t:=T) (b:=b) (F:=KSApplicative a b) (impure b) x) = posIT _ _ _ (traverse (t:=T) (b:=b') (F:=KSApplicative a b') (impure b') x)). do 2 rewrite free_applicative. change (map (liftT h) (traverse (t:=T) (b:=b) (F:=ConstListApplicative a) (fun y : a => (posIT a b) b (impure b y)) x) = traverse (t:=T) (b:=b') (F:=ConstListApplicative a) (fun y : a => (posIT a b') b' (impure b' y)) x). rewrite (@free_traversal_b a b b' h). reflexivity. Qed. *) Definition traversal_is_coalg : KleeneCoalg (fun a => a) T. exists traversal_coalg. exact traversal_coalg_extract. exact traversal_coalg_duplicate. Defined. End Traversal. Record FinContainerSpec := finContainerSpec { shape : Type ; card : shape -> nat }. Section FinContainer. Variable spec : FinContainerSpec. Definition finContainer (a:Type) := {x : shape spec & Vector (card x) a}. Definition finContainer_traverse a b (F : Applicative) (f : a -> F b) (x : finContainer a) : F (finContainer b) := let (s, v) := x in map (existT _ s) (traverse f v). Lemma finContainer_free_applicative a b (F G : Applicative) (eta : IdiomaticTransformation F G) (f : a -> F b) (x : finContainer a) : eta _ (finContainer_traverse f x) = finContainer_traverse (fun y => eta _ (f y)) x. Proof. destruct x as [s v]. simpl. change (traverseVector (b:=b) (F:=G) (fun y : a => eta b (f y)) v) with (traverse (fun y : a => eta b (f y)) v). rewrite <- free_applicative. rewrite idiomaticTransform_map. reflexivity. Qed. Lemma finContainer_traverse_identity a (x : finContainer a) : finContainer_traverse (F:=IdApplicative) (fun y => y) x = x. Proof. destruct x as [s v]. simpl. unfold traverseVector. simpl. rewrite Vector_map_id;[| reflexivity]. rewrite (sequenceVector_Id v). reflexivity. Qed. Lemma finContainer_traverse_compose a b c (F G : Applicative) (f : a -> F b) (g : b -> G c) (x : finContainer a) : finContainer_traverse (F:=ComposeApplicative F G) (fun y => map g (f y)) x = map (finContainer_traverse g) (finContainer_traverse f x). Proof. destruct x as [s v]. simpl. change (traverseVector (b:=b) (F:=F) f v) with (traverse f v). pose (h:= fun y => finContainer_traverse (b:=c) (F:=G) g (existT (fun x : shape spec => Vector.t b (card (f:=spec) x)) s y)). rewrite (map_compose (h:= h));[|reflexivity]. unfold h; simpl. rewrite <- (map_compose (g:=map (a:=G) (existT (fun x : shape spec => Vector.t c (card (f:=spec) x)) s)) (f:=traverseVector (b:=c) (F:=G) g) (h:= h));[|reflexivity]. change (map (a:=F) (traverseVector (b:=c) (F:=G) g) (traverseVector (b:=b) (F:=F) f v)) with (map (a:=F) (traverse (b:=c) (F:=G) g) (traverse (b:=b) (F:=F) f v)). rewrite <- (traverse_compose f g). unfold Compose_ap, Compose_pure, map. rewrite interchange_law. repeat (repeat rewrite homomorphism_law; repeat rewrite <- composition_law; unfold map). reflexivity. Qed. Definition FinContainer : Traversal. exists finContainer finContainer_traverse. apply finContainer_free_applicative. apply finContainer_traverse_identity. apply finContainer_traverse_compose. Defined. End FinContainer. (*============================================================================*) (*The main result *) (*============================================================================*) Theorem Traversal_is_finite_container : forall (T:Traversal), exists (spec : FinContainerSpec) (f : forall a, T a -> FinContainer spec a) (g : forall a, FinContainer spec a -> T a), (forall a, (forall x, g a (f a x) = x) /\ forall y, f a (g a y) = y) /\ (forall a b (F : Applicative) (h: a -> F b) (x : T a), map (f b) (traverse h x) = traverse h (f a x)). Proof. intros T. pose (K := traversal_is_coalg T). exists (finContainerSpec (size K (a:=unit))). exists (iso1 K). exists (iso2 (traverse:=K)). split. intros a. split. apply iso2_iso1. apply iso1_iso2. intros a b F h x. rewrite <- identity_law. replace (fun y : (FinContainer {| shape := T unit; card := size K (a:=unit) |}) b => y) with (fun y => iso1 K (iso2 (traverse:=K) (a:=b) y)) by (apply functional_extensionality; apply iso1_iso2). rewrite <- (map_compose (g:=iso1 K (a:=b)) (f:=iso2 (traverse:=K) (a:=b))); [|reflexivity]. f_equal. unfold traverse at 2; simpl. unfold traverseVector; simpl. (* close your eyes for a moment *) set (z := (fun b0 : Vector.t b (size K (a:=unit) (peek (k:=traverse (t:=T) (b:=unit) (F:=KSApplicative a unit) (impure unit) x) (Vector.const tt (dim (traverse (t:=T) (b:=unit) (F:=KSApplicative a unit) (impure unit) x))))) => peek (k:=traverse (t:=T) (b:=b) (F:=KSApplicative unit b) (impure b) (peek (k:=traverse (t:=T) (b:=unit) (F:=KSApplicative a unit) (impure unit) x) (Vector.const tt (dim (traverse (t:=T) (b:=unit) (F:=KSApplicative a unit) (impure unit) x))))) (eq_rect (size K (a:=unit) (peek (k:=traverse (t:=T) (b:=unit) (F:=KSApplicative a unit) (impure unit) x) (Vector.const tt (dim (traverse (t:=T) (b:=unit) (F:=KSApplicative a unit) (impure unit) x))))) (Vector.t b) b0 (dim (traverse (t:=T) (b:=b) (F:=KSApplicative unit b) (impure b) (peek (k:=traverse (t:=T) (b:=unit) (F:=KSApplicative a unit) (impure unit) x) (Vector.const tt (dim (traverse (t:=T) (b:=unit) (F:=KSApplicative a unit) (impure unit) x)))))) (eq_sym (free_b_dim K (a:=unit) b unit (peek (k:=traverse (t:=T) (b:=unit) (F:=KSApplicative a unit) (impure unit) x) (Vector.const tt (dim (traverse (t:=T) (b:=unit) (F:=KSApplicative a unit) (impure unit) x))))))))). rewrite (map_compose (h:=z));[|reflexivity]. change (traverse h x = research h (let (s,v) := iso1 K (a:=a) x in kleeneStore (fun b => iso2 (existT _ s b)) v)). clear z. transitivity (Research h _ (K a b x)). unfold K. simpl ((traversal_is_coalg T) a b x). rewrite free_applicative. f_equal. apply functional_extensionality; intros y. simpl. rewrite research_impure. reflexivity. simpl ((Research (F:=F) (b:=b) h) (T b)). f_equal. symmetry. apply iso_coalg. Qed. Print Assumptions Traversal_is_finite_container.
#' Title #' #' @param model #' @param parms #' @param over #' @param xrange #' @param res #' @param ini #' @param t_max #' @param method #' #' @return #' @export #' #' @examples #' #' library(foreach) #' library(doSNOW) #' #' workerlist <- c(rep("localhost", times = 3)) #' cl <- makeSOCKcluster(workerlist) #' registerDoSNOW(cl) #' #' p <- set_parms(livestock$parms, set = list(b = 0.9, c = 0.2, f = 0, p = 0, alpha = 0.2)) #' sim_bifurcations(livestock, over = "b", res = 31, parms = p) #' #' stopCluster(cl) #' sim_bifurcations <- function( model, parms = model$defparms, over = "b", xrange = c(0,1), res = 31, ini = c(0.9, 0.0001), t_max = 150, func = model$pair, method = "ode45" ) { parms[[over]] <- seq(xrange[1],xrange[2],length = res) parms$rho_ini <- ini iterations <- expand.grid(parms) iterations <- cbind(ID = 1:dim(iterations)[1],iterations) iterations$b <- as.numeric(as.character(iterations$b)) iterations$L <- as.numeric(as.character(iterations$L)) foreach(iteration = iterations$ID, .packages = c("deSolve", "livestock"), .combine = rbind) %dopar% { model_parms <- as.list(iterations[iteration,]) rho_starting <- ini_rho(model_parms$rho_ini) # running the ode-solver runmodel <- run_ode(rho_starting, func = model$pair, times = c(0,t_max), parms = model_parms, method = method) return(tail(runmodel,1)) } -> output output <- cbind(iterations,output) # CHECK: produces a warning return(output) }
print(a);print(b)
[STATEMENT] lemma wp_test[simp]: "wp \<lceil>P\<rceil> \<lceil>Q\<rceil> = \<lceil>\<lambda>s. P s \<longrightarrow> Q s\<rceil>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. wp \<lceil>P\<rceil> \<lceil>Q\<rceil> = \<lceil>\<lambda>s. P s \<longrightarrow> Q s\<rceil> [PROOF STEP] by (subst wp_nd_fun, simp) \<comment> \<open> Assignments \<close>
module BinomialHeap import Heap %default total %access private data Tree a = Node Int a (List (Tree a)) export data BinomialHeap a = BH (List (Tree a)) rank : Tree a -> Int rank (Node r x c) = r root : Tree a -> a root (Node r x c) = x link : Ord a => Tree a -> Tree a -> Tree a link t1@(Node r x1 c1) t2@(Node _ x2 c2) = if x1 <= x2 then Node (r + 1) x1 (t2 :: c1) else Node (r + 1) x2 (t1 :: c2) insTree : Ord a => Tree a -> List (Tree a) -> List (Tree a) insTree t [] = [t] insTree t ts@(t' :: ts') = if rank t < rank t' then t :: ts else insTree (link t t') ts' mrg : Ord a => List (Tree a) -> List (Tree a) -> List (Tree a) mrg ts1 [] = ts1 mrg [] ts2 = ts2 mrg ts1@(t1 :: ts1') ts2@(t2 :: ts2') = case compare (rank t1) (rank t2) of LT => t1 :: mrg ts1' ts2 GT => t2 :: mrg ts1 ts2' EQ => insTree (link t1 t2) (mrg ts1' ts2') removeMinTree : Ord a => List (Tree a) -> (Tree a, List (Tree a)) removeMinTree [] = idris_crash "empty heap" removeMinTree [t] = (t, []) removeMinTree (t :: ts) = let (t', ts') = removeMinTree ts in if root t < root t' then (t, ts) else (t', t :: ts') Heap BinomialHeap where empty = BH [] isEmpty (BH ts) = isNil ts insert x (BH ts) = BH (insTree (Node 0 x []) ts) merge (BH ts1) (BH ts2) = BH (mrg ts1 ts2) findMin (BH ts) = root (fst (removeMinTree ts)) deleteMin (BH ts) = let (Node _ x ts1, ts2) = removeMinTree ts in BH (mrg (reverse ts1) ts2)
-- WARNING: This file was generated automatically by Vehicle -- and should not be modified manually! -- Metadata -- - Agda version: 2.6.2 -- - AISEC version: 0.1.0.1 -- - Time generated: ??? {-# OPTIONS --allow-exec #-} open import Vehicle open import Vehicle.Data.Tensor open import Data.Product open import Data.Integer as ℤ using (ℤ) open import Data.Rational as ℚ using (ℚ) open import Data.Bool as 𝔹 using (Bool; true; false; if_then_else_) open import Data.Fin as Fin using (Fin; #_) open import Data.List open import Relation.Nullary open import Relation.Nullary.Decidable module simple-if-temp-output where postulate f : Tensor ℚ (1 ∷ []) → Tensor ℚ (1 ∷ []) abstract prop1 : ∀ (x : ℚ) → if ⌊ x ℚ.>? ℤ.+ 0 ℚ./ 1 ⌋ then f (x ∷ []) (# 0) ℚ.> ℤ.+ 0 ℚ./ 1 else f (x ∷ []) (# 0) ℚ.≤ ℤ.+ 0 ℚ./ 1 prop1 = checkSpecification record { proofCache = "/home/matthew/Code/AISEC/vehicle/proofcache.vclp" } abstract prop3 : ∃ λ (x : ℚ) → if ⌊ f (x ∷ []) (# 0) ℚ.>? ℤ.+ 0 ℚ./ 1 ⌋ then x ℚ.≥ ℤ.+ 0 ℚ./ 1 else x ℚ.< ℤ.+ 0 ℚ./ 1 prop3 = checkSpecification record { proofCache = "/home/matthew/Code/AISEC/vehicle/proofcache.vclp" }
import data.real.basic import data.nat.prime open nat -- BEGIN example : ∃ x : ℝ, 2 < x ∧ x < 4 := begin use 5 / 2, split, norm_num, norm_num, end example : ∃ m n : ℕ, 4 < m ∧ m < n ∧ n < 10 ∧ nat.prime m ∧ nat.prime n := begin use [5, 7], split; norm_num end example {x y : ℝ} : x ≤ y ∧ x ≠ y → x ≤ y ∧ ¬ y ≤ x := begin rintros ⟨h₀, h₁⟩, use [h₀, λ h', h₁ (le_antisymm h₀ h')] end /- Alternatively, the proof can be spelled out as done eariler -/ example {x y : ℝ} : x ≤ y ∧ x ≠ y → x ≤ y ∧ ¬ y ≤ x := begin intro h, cases h with h1 h2, split, exact h1, contrapose! h2, apply le_antisymm h1 h2, end -- END
module BosonSampling using Permanents using Plots using Test using Combinatorics using Random using IterTools using Statistics using LinearAlgebra #removed so as to be able to use generic types such as BigFloats, can be put back if needed using PolynomialRoots using StatsBase #using JLD using CSV using DataFrames using Tables using Plots#; plotly() #plotly allows to make "dynamic" plots where you can point the mouse and see the values, they can also be saved like that but note that this makes them heavy (and html instead of png) using PrettyTables #to display large matrices using Roots using BenchmarkTools using Optim using ProgressMeter using Parameters using ArgCheck using Distributions using Luxor # using Distributed # using SharedArrays const ATOL = 1e-10 include("special_matrices.jl") include("matrix_tests.jl") include("proba_tools.jl") include("circuits/circuit_elements.jl") include("types/type_functions.jl") include("types/types.jl") include("scattering.jl") include("bunching/bunching.jl") include("partitions/legacy.jl") include("partitions/partition_expectation_values.jl") include("partitions/partitions.jl") include("boson_samplers/tools.jl") include("boson_samplers/classical_sampler.jl") include("boson_samplers/cliffords_sampler.jl") include("boson_samplers/methods.jl") include("boson_samplers/metropolis_sampler.jl") include("boson_samplers/noisy_sampler.jl") include("distributions/noisy_distribution.jl") include("distributions/theoretical_distribution.jl") include("permanent_conjectures/bapat_sunder.jl") include("permanent_conjectures/counter_example_functions.jl") include("permanent_conjectures/counter_example_numerical_search.jl") include("permanent_conjectures/permanent_on_top.jl") include("visual.jl") permanent = ryser for n in names(@__MODULE__; all=true) if Base.isidentifier(n) && n ∉ (Symbol(@__MODULE__), :eval, :include) @eval export $n end end end
lemma add_right_comm (a b c : mynat) : a + b + c = a + c + b := begin rw add_assoc, rw add_assoc, rw add_comm b, refl, end
Require Import ExtLib.Structures.Maps. Require Import ExtLib.Structures.Functor. Require Import ExtLib.Data.Option. Require Import ExtLib.Data.Positive. Require Import ExtLib.Tactics.Cases. Set Implicit Arguments. Set Strict Implicit. Section pmap. Variable T : Type. Inductive pmap : Type := | Empty | Branch : option T -> pmap -> pmap -> pmap. Definition pmap_here (m : pmap) : option T := match m with | Empty => None | Branch d _ _ => d end. Definition pmap_left (m : pmap) : pmap := match m with | Empty => Empty | Branch _ l _ => l end. Definition pmap_right (m : pmap) : pmap := match m with | Empty => Empty | Branch _ _ r => r end. Fixpoint pmap_lookup (p : positive) (m : pmap) : option T := match m with | Empty => None | Branch d l r => match p with | xH => d | xO p => pmap_lookup p l | xI p => pmap_lookup p r end end. Fixpoint pmap_insert (p : positive) (v : T) (m : pmap) : pmap := match p with | xH => Branch (Some v) (pmap_left m) (pmap_right m) | xO p => Branch (pmap_here m) (pmap_insert p v (pmap_left m)) (pmap_right m) | xI p => Branch (pmap_here m) (pmap_left m) (pmap_insert p v (pmap_right m)) end. Definition branch (o : option T) (l r : pmap) : pmap := match o , l , r with | None , Empty , Empty => Empty | _ , _ , _ => Branch o l r end. Fixpoint pmap_remove (p : positive) (m : pmap) : pmap := match m with | Empty => Empty | Branch d l r => match p with | xH => branch None l r | xO p => branch d (pmap_remove p l) r | xI p => branch d l (pmap_remove p r) end end. Definition pmap_empty : pmap := Empty. Fixpoint pmap_union (f m : pmap) : pmap := match f with | Empty => m | Branch d l r => Branch (match d with | Some x => Some x | None => pmap_here m end) (pmap_union l (pmap_left m)) (pmap_union r (pmap_right m)) end. Global Instance Map_pmap : Map positive T pmap := { empty := pmap_empty ; add := pmap_insert ; remove := pmap_remove ; lookup := pmap_lookup ; union := pmap_union }. Lemma tilde_1_inj_neg : forall k k', (k~1)%positive <> (k'~1)%positive -> k <> k'. Proof. induction k; destruct k'; intuition; try match goal with | H : _ = _ |- _ => inversion H; clear H; subst end; intuition eauto. Qed. Lemma tilde_0_inj_neg : forall k k', (k~0)%positive <> (k'~0)%positive -> k <> k'. Proof. induction k; destruct k'; intuition; try match goal with | H : _ = _ |- _ => inversion H; clear H; subst end; intuition eauto. Qed. Lemma pmap_lookup_insert_empty : forall k k' v, k <> k' -> pmap_lookup k' (pmap_insert k v Empty) = None. Proof. induction k; destruct k'; simpl; intros; eauto using tilde_0_inj_neg, tilde_1_inj_neg. destruct k'; simpl; auto. destruct k'; simpl; auto. destruct k'; simpl; auto. destruct k'; simpl; auto. congruence. Qed. Lemma lookup_empty : forall k, pmap_lookup k Empty = None. Proof. destruct k; reflexivity. Qed. Hint Rewrite lookup_empty pmap_lookup_insert_empty using (eauto using tilde_1_inj_neg, tilde_1_inj_neg) : pmap_rw. Lemma pmap_lookup_insert_eq : forall (m : pmap) (k : positive) (v : T), pmap_lookup k (pmap_insert k v m) = Some v. Proof. intros m k; revert m. induction k; simpl; intros; forward; Cases.rewrite_all_goal; eauto. Qed. Lemma pmap_lookup_insert_Some_neq : forall (m : pmap) (k : positive) (v : T) (k' : positive), k <> k' -> forall v' : T, pmap_lookup k' m = Some v' <-> pmap_lookup k' (pmap_insert k v m) = Some v'. Proof. intros m k; revert m. induction k; simpl; intros; forward; Cases.rewrite_all_goal; autorewrite with pmap_rw; eauto. { destruct k'; simpl; destruct m; simpl; autorewrite with pmap_rw; Cases.rewrite_all_goal; try reflexivity. erewrite IHk; eauto using tilde_1_inj_neg. reflexivity. } { destruct k'; simpl; destruct m; simpl; autorewrite with pmap_rw; Cases.rewrite_all_goal; try reflexivity; try congruence. erewrite IHk. reflexivity. eauto using tilde_0_inj_neg. } { destruct k'; simpl; destruct m; simpl; autorewrite with pmap_rw; Cases.rewrite_all_goal; try reflexivity; try congruence. } Qed. Lemma pmap_lookup_insert_None_neq : forall (m : pmap) (k : positive) (v : T) (k' : positive), k <> k' -> pmap_lookup k' m = None <-> pmap_lookup k' (pmap_insert k v m) = None. Proof. intros m k; revert m. induction k; simpl; intros; forward; Cases.rewrite_all_goal; autorewrite with pmap_rw; eauto. { destruct k'; simpl; destruct m; simpl; autorewrite with pmap_rw; Cases.rewrite_all_goal; try reflexivity. erewrite IHk; eauto using tilde_1_inj_neg. reflexivity. } { destruct k'; simpl; destruct m; simpl; autorewrite with pmap_rw; Cases.rewrite_all_goal; try reflexivity; try congruence. erewrite IHk. reflexivity. eauto using tilde_0_inj_neg. } { destruct k'; simpl; destruct m; simpl; autorewrite with pmap_rw; Cases.rewrite_all_goal; try reflexivity; try congruence. } Qed. Lemma pmap_lookup_insert_neq : forall (m : pmap) (k : positive) (v : T) (k' : positive), k <> k' -> forall v' : T, pmap_lookup k' (pmap_insert k v m) = pmap_lookup k' m. Proof. intros. remember (pmap_lookup k' m). destruct o; [ apply pmap_lookup_insert_Some_neq; intuition | apply pmap_lookup_insert_None_neq; intuition]. Qed. Global Instance MapOk_pmap : MapOk (@eq _) Map_pmap. Proof. refine {| mapsto := fun k v m => pmap_lookup k m = Some v |}. { abstract (induction k; simpl; congruence). } { abstract (induction k; simpl; intros; forward). } { eauto using pmap_lookup_insert_eq. } { eauto using pmap_lookup_insert_Some_neq. } Defined. Definition from_list : list T -> pmap := (fix from_list acc i ls {struct ls} := match ls with | nil => acc | List.cons l ls => from_list (pmap_insert i l acc) (Pos.succ i) ls end) Empty 1%positive. End pmap. Arguments Empty {_}. Arguments Branch {_} _ _ _. Section fmap. Variables T U : Type. Variable f : T -> U. Fixpoint fmap_pmap (m : pmap T) : pmap U := match m with | Empty => Empty | Branch h l r => Branch (fmap f h) (fmap_pmap l) (fmap_pmap r) end. Theorem fmap_lookup : forall a b m, mapsto a b m -> mapsto a (f b) (fmap_pmap m). Proof. induction a; destruct m; simpl; intros; try congruence. { eapply IHa. eapply H. } { eapply IHa; eapply H. } { subst. auto. } Qed. Theorem fmap_lookup_bk : forall a b m, mapsto a b (fmap_pmap m) -> exists b', mapsto a b' m /\ f b' = b. Proof. induction a; destruct m; simpl; intros; try congruence. { eapply IHa. eapply H. } { eapply IHa. eapply H. } { destruct o; try congruence. eexists; split; eauto. inversion H; auto. } Qed. End fmap. Require Import ExtLib.Core.Type. Section type. Variable T : Type. Variable tT : type T. Instance type_pmap : type (pmap T) := type_from_equal (fun l r => (forall k v, mapsto k v l -> exists v', mapsto k v' r /\ equal v v') /\ (forall k v, mapsto k v r -> exists v', mapsto k v' l /\ equal v v')). End type. Global Instance Functor_pmap : Functor pmap := { fmap := fmap_pmap }.
[GOAL] m n : ℕ ⊢ ¬n % 2 = 1 ↔ n % 2 = 0 [PROOFSTEP] cases' mod_two_eq_zero_or_one n with h h [GOAL] case inl m n : ℕ h : n % 2 = 0 ⊢ ¬n % 2 = 1 ↔ n % 2 = 0 [PROOFSTEP] simp [h] [GOAL] case inr m n : ℕ h : n % 2 = 1 ⊢ ¬n % 2 = 1 ↔ n % 2 = 0 [PROOFSTEP] simp [h] [GOAL] m n : ℕ ⊢ ¬n % 2 = 0 ↔ n % 2 = 1 [PROOFSTEP] cases' mod_two_eq_zero_or_one n with h h [GOAL] case inl m n : ℕ h : n % 2 = 0 ⊢ ¬n % 2 = 0 ↔ n % 2 = 1 [PROOFSTEP] simp [h] [GOAL] case inr m n : ℕ h : n % 2 = 1 ⊢ ¬n % 2 = 0 ↔ n % 2 = 1 [PROOFSTEP] simp [h] [GOAL] m✝ n : ℕ x✝ : Even n m : ℕ hm : n = m + m ⊢ n % 2 = 0 [PROOFSTEP] simp [← two_mul, hm] [GOAL] m n : ℕ h : n % 2 = 0 ⊢ n % 2 + 2 * (n / 2) = n / 2 + n / 2 [PROOFSTEP] simp [← two_mul, h] [GOAL] m✝ n : ℕ x✝ : Odd n m : ℕ hm : n = 2 * m + 1 ⊢ n % 2 = 1 [PROOFSTEP] rw [hm, add_mod, mul_mod_right] [GOAL] m✝ n : ℕ x✝ : Odd n m : ℕ hm : n = 2 * m + 1 ⊢ (0 + 1 % 2) % 2 = 1 [PROOFSTEP] rfl [GOAL] m n : ℕ h : n % 2 = 1 ⊢ n % 2 + 2 * (n / 2) = 2 * (n / 2) + 1 [PROOFSTEP] rw [h, add_comm] [GOAL] m n : ℕ ⊢ ¬Even n ↔ n % 2 = 1 [PROOFSTEP] rw [even_iff, mod_two_ne_zero] [GOAL] m n : ℕ ⊢ ¬Odd n ↔ n % 2 = 0 [PROOFSTEP] rw [odd_iff, mod_two_ne_one] [GOAL] m n : ℕ ⊢ Even n ↔ ¬Odd n [PROOFSTEP] rw [not_odd_iff, even_iff] [GOAL] m n : ℕ ⊢ Odd n ↔ ¬Even n [PROOFSTEP] rw [not_even_iff, odd_iff] [GOAL] m n : ℕ h : Odd n ⊢ ¬2 ∣ n [PROOFSTEP] rwa [← even_iff_two_dvd, ← odd_iff_not_even] [GOAL] m n : ℕ ⊢ IsCompl {n | Even n} {n | Odd n} [PROOFSTEP] simp only [← Set.compl_setOf, isCompl_compl, odd_iff_not_even] [GOAL] m n✝ n : ℕ ⊢ Xor' (Even n) (Odd n) [PROOFSTEP] simp [Xor', odd_iff_not_even, Decidable.em (Even n)] [GOAL] m n✝ n : ℕ ⊢ ∃ k, n = 2 * k ∨ n = 2 * k + 1 [PROOFSTEP] simpa only [← two_mul, exists_or, Odd, Even] using even_or_odd n [GOAL] m n✝ n : ℕ ⊢ ∃ k, Xor' (n = 2 * k) (n = 2 * k + 1) [PROOFSTEP] rcases even_or_odd n with (⟨k, rfl⟩ | ⟨k, rfl⟩) [GOAL] case inl.intro m n k : ℕ ⊢ ∃ k_1, Xor' (k + k = 2 * k_1) (k + k = 2 * k_1 + 1) [PROOFSTEP] use k [GOAL] case inr.intro m n k : ℕ ⊢ ∃ k_1, Xor' (2 * k + 1 = 2 * k_1) (2 * k + 1 = 2 * k_1 + 1) [PROOFSTEP] use k [GOAL] case h m n k : ℕ ⊢ Xor' (k + k = 2 * k) (k + k = 2 * k + 1) [PROOFSTEP] simpa only [← two_mul, eq_self_iff_true, xor_true] using (succ_ne_self (2 * k)).symm [GOAL] case h m n k : ℕ ⊢ Xor' (2 * k + 1 = 2 * k) (2 * k + 1 = 2 * k + 1) [PROOFSTEP] simpa only [xor_true, xor_comm] using (succ_ne_self _) [GOAL] m✝ n✝ m n : ℕ hn : Odd n hm : Even m ⊢ m % 2 + (m + n) % 2 = 1 [PROOFSTEP] rw [even_iff.1 hm, odd_iff.1 (hm.add_odd hn)] [GOAL] m✝ n✝ m n : ℕ hn : Odd n hm : Odd m ⊢ m % 2 + (m + n) % 2 = 1 [PROOFSTEP] rw [odd_iff.1 hm, even_iff.1 (hm.add_odd hn)] [GOAL] m✝ n m : ℕ ⊢ (m + 1) % 2 + m % 2 = 1 [PROOFSTEP] rw [add_comm, mod_two_add_succ_mod_two] [GOAL] m n : ℕ ⊢ Even (m + n) ↔ (Even m ↔ Even n) [PROOFSTEP] cases' mod_two_eq_zero_or_one m with h₁ h₁ [GOAL] case inl m n : ℕ h₁ : m % 2 = 0 ⊢ Even (m + n) ↔ (Even m ↔ Even n) [PROOFSTEP] cases' mod_two_eq_zero_or_one n with h₂ h₂ [GOAL] case inr m n : ℕ h₁ : m % 2 = 1 ⊢ Even (m + n) ↔ (Even m ↔ Even n) [PROOFSTEP] cases' mod_two_eq_zero_or_one n with h₂ h₂ [GOAL] case inl.inl m n : ℕ h₁ : m % 2 = 0 h₂ : n % 2 = 0 ⊢ Even (m + n) ↔ (Even m ↔ Even n) [PROOFSTEP] simp [even_iff, h₁, h₂, Nat.add_mod] [GOAL] case inl.inr m n : ℕ h₁ : m % 2 = 0 h₂ : n % 2 = 1 ⊢ Even (m + n) ↔ (Even m ↔ Even n) [PROOFSTEP] simp [even_iff, h₁, h₂, Nat.add_mod] [GOAL] case inr.inl m n : ℕ h₁ : m % 2 = 1 h₂ : n % 2 = 0 ⊢ Even (m + n) ↔ (Even m ↔ Even n) [PROOFSTEP] simp [even_iff, h₁, h₂, Nat.add_mod] [GOAL] case inr.inr m n : ℕ h₁ : m % 2 = 1 h₂ : n % 2 = 1 ⊢ Even (m + n) ↔ (Even m ↔ Even n) [PROOFSTEP] simp [even_iff, h₁, h₂, Nat.add_mod] [GOAL] m n : ℕ ⊢ Even (m + n) ↔ (Odd m ↔ Odd n) [PROOFSTEP] rw [even_add, even_iff_not_odd, even_iff_not_odd, not_iff_not] [GOAL] m n : ℕ ⊢ Even (n + 1) ↔ ¬Even n [PROOFSTEP] simp [even_add] [GOAL] m n✝ n : ℕ ⊢ ¬Even (bit1 n) [PROOFSTEP] simp [bit1, parity_simps] [GOAL] m n✝ n : ℕ ⊢ ¬2 ∣ 2 * n + 1 [PROOFSTEP] simp [add_mod] [GOAL] m n : ℕ h : n ≤ m ⊢ Even (m - n) ↔ (Even m ↔ Even n) [PROOFSTEP] conv_rhs => rw [← tsub_add_cancel_of_le h, even_add] [GOAL] m n : ℕ h : n ≤ m | Even m ↔ Even n [PROOFSTEP] rw [← tsub_add_cancel_of_le h, even_add] [GOAL] m n : ℕ h : n ≤ m | Even m ↔ Even n [PROOFSTEP] rw [← tsub_add_cancel_of_le h, even_add] [GOAL] m n : ℕ h : n ≤ m | Even m ↔ Even n [PROOFSTEP] rw [← tsub_add_cancel_of_le h, even_add] [GOAL] m n : ℕ h : n ≤ m ⊢ Even (m - n) ↔ ((Even (m - n) ↔ Even n) ↔ Even n) [PROOFSTEP] by_cases h : Even n [GOAL] case pos m n : ℕ h✝ : n ≤ m h : Even n ⊢ Even (m - n) ↔ ((Even (m - n) ↔ Even n) ↔ Even n) [PROOFSTEP] simp [h] [GOAL] case neg m n : ℕ h✝ : n ≤ m h : ¬Even n ⊢ Even (m - n) ↔ ((Even (m - n) ↔ Even n) ↔ Even n) [PROOFSTEP] simp [h] [GOAL] m n : ℕ h : n ≤ m ⊢ Even (m - n) ↔ (Odd m ↔ Odd n) [PROOFSTEP] rw [even_sub h, even_iff_not_odd, even_iff_not_odd, not_iff_not] [GOAL] m n : ℕ hm : Odd m hn : Odd n h : n ≤ m ⊢ Even (m - n) [PROOFSTEP] simp only [even_sub' h, *] [GOAL] m n : ℕ hm : Odd m hn : Odd n h : m ≤ n ⊢ Even (m - n) [PROOFSTEP] simp only [tsub_eq_zero_iff_le.mpr h, even_zero] [GOAL] m n : ℕ ⊢ Even (m * n) ↔ Even m ∨ Even n [PROOFSTEP] cases' mod_two_eq_zero_or_one m with h₁ h₁ [GOAL] case inl m n : ℕ h₁ : m % 2 = 0 ⊢ Even (m * n) ↔ Even m ∨ Even n [PROOFSTEP] cases' mod_two_eq_zero_or_one n with h₂ h₂ [GOAL] case inr m n : ℕ h₁ : m % 2 = 1 ⊢ Even (m * n) ↔ Even m ∨ Even n [PROOFSTEP] cases' mod_two_eq_zero_or_one n with h₂ h₂ [GOAL] case inl.inl m n : ℕ h₁ : m % 2 = 0 h₂ : n % 2 = 0 ⊢ Even (m * n) ↔ Even m ∨ Even n [PROOFSTEP] simp [even_iff, h₁, h₂, Nat.mul_mod] [GOAL] case inl.inr m n : ℕ h₁ : m % 2 = 0 h₂ : n % 2 = 1 ⊢ Even (m * n) ↔ Even m ∨ Even n [PROOFSTEP] simp [even_iff, h₁, h₂, Nat.mul_mod] [GOAL] case inr.inl m n : ℕ h₁ : m % 2 = 1 h₂ : n % 2 = 0 ⊢ Even (m * n) ↔ Even m ∨ Even n [PROOFSTEP] simp [even_iff, h₁, h₂, Nat.mul_mod] [GOAL] case inr.inr m n : ℕ h₁ : m % 2 = 1 h₂ : n % 2 = 1 ⊢ Even (m * n) ↔ Even m ∨ Even n [PROOFSTEP] simp [even_iff, h₁, h₂, Nat.mul_mod] [GOAL] m n : ℕ ⊢ Odd (m * n) ↔ Odd m ∧ Odd n [PROOFSTEP] simp [not_or, even_mul] [GOAL] m n : ℕ ⊢ Even (m ^ n) ↔ Even m ∧ n ≠ 0 [PROOFSTEP] induction' n with n ih [GOAL] case zero m n : ℕ ⊢ Even (m ^ zero) ↔ Even m ∧ zero ≠ 0 [PROOFSTEP] simp (config := { contextual := true }) [*, pow_succ', even_mul] [GOAL] case succ m n✝ n : ℕ ih : Even (m ^ n) ↔ Even m ∧ n ≠ 0 ⊢ Even (m ^ succ n) ↔ Even m ∧ succ n ≠ 0 [PROOFSTEP] simp (config := { contextual := true }) [*, pow_succ', even_mul] [GOAL] m n : ℕ ⊢ Even (m / n) ↔ m % (2 * n) / n = 0 [PROOFSTEP] rw [even_iff_two_dvd, dvd_iff_mod_eq_zero, Nat.div_mod_eq_mod_mul_div, mul_comm] [GOAL] m n : ℕ ⊢ Odd (m + n) ↔ (Odd m ↔ Even n) [PROOFSTEP] rw [odd_iff_not_even, even_add, not_iff, odd_iff_not_even] [GOAL] m n : ℕ ⊢ Odd (m + n) ↔ (Odd n ↔ Even m) [PROOFSTEP] rw [add_comm, odd_add] [GOAL] m n : ℕ h : Odd (m + n) hnot : m = n ⊢ False [PROOFSTEP] simp [hnot] at h [GOAL] m n : ℕ h : n ≤ m ⊢ Odd (m - n) ↔ (Odd m ↔ Even n) [PROOFSTEP] rw [odd_iff_not_even, even_sub h, not_iff, odd_iff_not_even] [GOAL] m n : ℕ h : n ≤ m ⊢ Odd (m - n) ↔ (Odd n ↔ Even m) [PROOFSTEP] rw [odd_iff_not_even, even_sub h, not_iff, not_iff_comm, odd_iff_not_even] [GOAL] m n✝ n : ℕ ⊢ Even (n * (n + 1)) [PROOFSTEP] rw [even_mul, even_add_one] [GOAL] m n✝ n : ℕ ⊢ Even n ∨ ¬Even n [PROOFSTEP] exact em _ [GOAL] m n : ℕ h : Odd n ⊢ 2 * (n / 2) + 1 = n [PROOFSTEP] rw [← odd_iff.mp h, div_add_mod] [GOAL] m n : ℕ h : Odd n ⊢ n / 2 * 2 + 1 = n [PROOFSTEP] rw [← odd_iff.mp h, div_add_mod'] [GOAL] m n : ℕ h : Odd n ⊢ 1 + n / 2 * 2 = n [PROOFSTEP] rw [← odd_iff.mp h, mod_add_div'] [GOAL] m n : ℕ ⊢ bit0 n / 2 = n [PROOFSTEP] rw [← Nat.bit0_eq_bit0, bit0_eq_two_mul, two_mul_div_two_of_even (even_bit0 n)] [GOAL] m n : ℕ ⊢ bit1 n / 2 = n [PROOFSTEP] rw [← Nat.bit1_eq_bit1, bit1, bit0_eq_two_mul, Nat.two_mul_div_two_add_one_of_odd (odd_bit1 n)] [GOAL] m n : ℕ ⊢ bit0 n / bit0 m = n / m [PROOFSTEP] rw [bit0_eq_two_mul m, ← Nat.div_div_eq_div_mul, bit0_div_two] [GOAL] m n : ℕ ⊢ bit1 n / bit0 m = n / m [PROOFSTEP] rw [bit0_eq_two_mul, ← Nat.div_div_eq_div_mul, bit1_div_two] [GOAL] m n : ℕ ⊢ bit0 n % bit0 m = bit0 (n % m) [PROOFSTEP] rw [bit0_eq_two_mul n, bit0_eq_two_mul m, bit0_eq_two_mul (n % m), Nat.mul_mod_mul_left] [GOAL] m n : ℕ ⊢ bit1 n % bit0 m = bit1 (n % m) [PROOFSTEP] have h₁ := congr_arg bit1 (Nat.div_add_mod n m) -- `∀ m n : ℕ, bit0 m * n = bit0 (m * n)` seems to be missing... [GOAL] m n : ℕ h₁ : bit1 (m * (n / m) + n % m) = bit1 n ⊢ bit1 n % bit0 m = bit1 (n % m) [PROOFSTEP] rw [bit1_add, bit0_eq_two_mul, ← mul_assoc, ← bit0_eq_two_mul] at h₁ [GOAL] m n : ℕ h₁ : bit0 m * (n / m) + bit1 (n % m) = bit1 n ⊢ bit1 n % bit0 m = bit1 (n % m) [PROOFSTEP] have h₂ := Nat.div_add_mod (bit1 n) (bit0 m) [GOAL] m n : ℕ h₁ : bit0 m * (n / m) + bit1 (n % m) = bit1 n h₂ : bit0 m * (bit1 n / bit0 m) + bit1 n % bit0 m = bit1 n ⊢ bit1 n % bit0 m = bit1 (n % m) [PROOFSTEP] rw [bit1_div_bit0] at h₂ [GOAL] m n : ℕ h₁ : bit0 m * (n / m) + bit1 (n % m) = bit1 n h₂ : bit0 m * (n / m) + bit1 n % bit0 m = bit1 n ⊢ bit1 n % bit0 m = bit1 (n % m) [PROOFSTEP] exact add_left_cancel (h₂.trans h₁.symm) [GOAL] m✝ n✝ m n : ℕ h : Even m ⊢ ¬Even (n + 3) ↔ Even (m ^ 2 + m + n) [PROOFSTEP] simp [*, two_ne_zero, parity_simps] /- Porting note: the `simp` lemmas about `bit*` no longer apply, but `simp` in Lean 4 currently simplifies decidable propositions. This may change in the future. -/ [GOAL] m n : ℕ ⊢ ¬Even 25394535 [PROOFSTEP] simp only [GOAL] α : Type u_1 f : α → α n✝ : ℕ hf : Involutive f n : ℕ ⊢ f^[bit0 n] = id [PROOFSTEP] rw [bit0, ← two_mul, iterate_mul, involutive_iff_iter_2_eq_id.1 hf, iterate_id] [GOAL] α : Type u_1 f : α → α n✝ : ℕ hf : Involutive f n : ℕ ⊢ f^[bit1 n] = f [PROOFSTEP] rw [bit1, ← succ_eq_add_one, iterate_succ, hf.iterate_bit0, comp.left_id] [GOAL] α : Type u_1 f : α → α n✝ : ℕ hf : Involutive f n : ℕ ⊢ f^[2 * n] = id [PROOFSTEP] rw [iterate_mul, involutive_iff_iter_2_eq_id.1 hf, iterate_id] [GOAL] α : Type u_1 f : α → α n : ℕ hf : Involutive f hn : Even n ⊢ f^[n] = id [PROOFSTEP] rcases hn with ⟨m, rfl⟩ [GOAL] case intro α : Type u_1 f : α → α hf : Involutive f m : ℕ ⊢ f^[m + m] = id [PROOFSTEP] rw [← two_mul, hf.iterate_two_mul] [GOAL] α : Type u_1 f : α → α n : ℕ hf : Involutive f hn : Odd n ⊢ f^[n] = f [PROOFSTEP] rcases hn with ⟨m, rfl⟩ [GOAL] case intro α : Type u_1 f : α → α hf : Involutive f m : ℕ ⊢ f^[2 * m + 1] = f [PROOFSTEP] rw [iterate_add, hf.iterate_two_mul, comp.left_id, iterate_one] [GOAL] α : Type u_1 f : α → α n : ℕ hf : Involutive f hne : f ≠ id H : f^[n] = f hn : Even n ⊢ f = id [PROOFSTEP] rwa [hf.iterate_even hn, eq_comm] at H [GOAL] α : Type u_1 f : α → α n : ℕ hf : Involutive f hne : f ≠ id H : f^[n] = id hn : Odd n ⊢ f = id [PROOFSTEP] rwa [hf.iterate_odd hn] at H [GOAL] R : Type u_1 inst✝¹ : Monoid R inst✝ : HasDistribNeg R n✝ m n : ℕ hn : Odd n hm : m ∣ n ⊢ m ≠ 2 [PROOFSTEP] rintro rfl [GOAL] R : Type u_1 inst✝¹ : Monoid R inst✝ : HasDistribNeg R n✝ n : ℕ hn : Odd n hm : 2 ∣ n ⊢ False [PROOFSTEP] exact absurd (hn.of_dvd_nat hm) (by decide) [GOAL] R : Type u_1 inst✝¹ : Monoid R inst✝ : HasDistribNeg R n✝ n : ℕ hn : Odd n hm : 2 ∣ n ⊢ ¬Odd 2 [PROOFSTEP] decide
# <center>Block 1: Linear programming</center> # <center>R Notebook</center> ### <center>Alfred Galichon (NYU)</center> ## <center>`math+econ+code' masterclass on matching models, optimal transport and applications</center> <center>© 2018-2019 by Alfred Galichon. Support from NSF grant DMS-1716489 is acknowledged. James Nesbit contributed.</center> ## Linear programming: duality ### Learning objectives * Linear programming duality * Economic interpretation of the dual * Numerical computation ### References * [OTME], App. B * Stigler (1945), The cost of subsistence. *Journal of Farm Economics*. * Dantzig (1990), The diet problem. *Interface*. * Complements: * Gale (1960), *The theory of linear economic models*. * Vohra (2011), *Mechanism Design: A Linear Programming Approach*. ### The diet problem During World War II, engineers in US Army were wondering how to feed their personnel at minimal cost, leading to what is now called the **optimal diet problem**. * Nutritionists have identified a number of vital nutrients (calories, protein, calcium, iron, etc.) that matter for a person's health, and have determined the minimum daily intake of each nutrient * For each basic food (pasta, butter, bread, etc), nutritionists have characterized the intake in each of the various nutrients * Each food has a unit cost, and the problem is to find the optimal diet = combination of foods that meet the minimal intake in each of the nutrients and achieves minimal cost The problem was taken on by G. Stigler, who published a paper about it in 1945, giving a first heuristic solution, exhibiting a diet that costs $\$39.93$ per year in $1939$ dollars. Later (in $1947$) it was one of the first application of G.B. Dantzig's method (the simplex algorithm), which provided the exact solution ($\$39.67$). It then took $120$ man-day to perform this operation. However today the computer will perform it for us in a fraction of second. However, don't try this diet at home! Dantzig did so and almost died from it... ## Motivation ### A look at the Data Our dataset was directly taken from Stigler's article. It is a .csv file called `StiglerData1939.txt': ```R thepath = paste0(getwd(),"/../data_mec_optim/lp_stigler-diet") filename = "/StiglerData1939.txt" thedata = as.matrix(read.csv(paste0(thepath, filename), sep = "\t", header = T)) thedata[1:(dim(thedata)[1] - 2), ] # cut off 2 redunant rows at the bottom ``` <table> <caption>A matrix: 78 × 13 of type chr</caption> <thead> <tr><th scope=col>Commodity</th><th scope=col>Unit</th><th scope=col>Price.Aug.15.1939.cents.</th><th scope=col>Edible.Weight.per..1.00..grams.</th><th scope=col>Calories..1000.</th><th scope=col>Protein.grams.</th><th scope=col>Calcium.grams.</th><th scope=col>Iron.mg..</th><th scope=col>Vitamin.A.1000.I.U.</th><th scope=col>Thiamine.mg..</th><th scope=col>Riboflavin.mg..</th><th scope=col>Niacin.mg..</th><th scope=col>Asorbic.Acid..mg..</th></tr> </thead> <tbody> <tr><td>1. Wheat Flour (Enriched) </td><td>10 lb. </td><td>36.0</td><td>12600</td><td>44.7</td><td>1411</td><td> 2.0</td><td>365</td><td>NA </td><td>55.4</td><td>33.3</td><td>441</td><td>NA </td></tr> <tr><td>2. Macaroni </td><td>1 lb. </td><td>14.1</td><td> 3217</td><td>11.6</td><td> 418</td><td> 0.7</td><td> 54</td><td>NA </td><td> 3.2</td><td> 1.9</td><td> 68</td><td>NA </td></tr> <tr><td>3. Wheat Cereal (Enriched)</td><td>28 oz. </td><td>24.2</td><td> 3280</td><td>11.8</td><td> 377</td><td>14.4</td><td>175</td><td>NA </td><td>14.4</td><td> 8.8</td><td>114</td><td>NA </td></tr> <tr><td>4. Corn Flakes </td><td>8 oz. </td><td> 7.1</td><td> 3194</td><td>11.4</td><td> 252</td><td> 0.1</td><td> 56</td><td>NA </td><td>13.5</td><td> 2.3</td><td> 68</td><td>NA </td></tr> <tr><td>5. Corn Meal </td><td>1 lb. </td><td> 4.6</td><td> 9861</td><td>36.0</td><td> 897</td><td> 1.7</td><td> 99</td><td> 30.9</td><td>17.4</td><td> 7.9</td><td>106</td><td>NA </td></tr> <tr><td>6. Hominy Grits </td><td>24 oz. </td><td> 8.5</td><td> 8005</td><td>28.6</td><td> 680</td><td> 0.8</td><td> 80</td><td>NA </td><td>10.6</td><td> 1.6</td><td>110</td><td>NA </td></tr> <tr><td>7. Rice </td><td>1 lb. </td><td> 7.5</td><td> 6048</td><td>21.2</td><td> 460</td><td> 0.6</td><td> 41</td><td>NA </td><td> 2.0</td><td> 4.8</td><td> 60</td><td>NA </td></tr> <tr><td>8. Rolled Oats </td><td>1 lb. </td><td> 7.1</td><td> 6389</td><td>25.3</td><td> 907</td><td> 5.1</td><td>341</td><td>NA </td><td>37.1</td><td> 8.9</td><td> 64</td><td>NA </td></tr> <tr><td>9. White Bread (Enriched) </td><td>1 lb. </td><td> 7.9</td><td> 5742</td><td>15.0</td><td> 488</td><td> 2.5</td><td>115</td><td>NA </td><td>13.8</td><td> 8.5</td><td>126</td><td>NA </td></tr> <tr><td>10. Whole Wheat Bread </td><td>1 lb. </td><td> 9.1</td><td> 4985</td><td>12.2</td><td> 484</td><td> 2.7</td><td>125</td><td>NA </td><td>13.9</td><td> 6.4</td><td>160</td><td>NA </td></tr> <tr><td>11. Rye Bread </td><td>1 lb. </td><td> 9.2</td><td> 4930</td><td>12.4</td><td> 439</td><td> 1.1</td><td> 82</td><td>NA </td><td> 9.9</td><td> 3.0</td><td> 66</td><td>NA </td></tr> <tr><td>12. Pound Cake </td><td>1 lb. </td><td>24.8</td><td> 1829</td><td> 8.0</td><td> 130</td><td> 0.4</td><td> 31</td><td> 18.9</td><td> 2.8</td><td> 3.0</td><td> 17</td><td>NA </td></tr> <tr><td>13. Soda Crackers </td><td>1 lb. </td><td>15.1</td><td> 3004</td><td>12.5</td><td> 288</td><td> 0.5</td><td> 50</td><td>NA </td><td>NA </td><td>NA </td><td>NA </td><td>NA </td></tr> <tr><td>14. Milk </td><td>1 qt. </td><td>11.0</td><td> 8867</td><td> 6.1</td><td> 310</td><td>10.5</td><td> 18</td><td> 16.8</td><td> 4.0</td><td>16.0</td><td> 7</td><td> 177</td></tr> <tr><td>15. Evaporated Milk (can) </td><td>14.5 oz.</td><td> 6.7</td><td> 6035</td><td> 8.4</td><td> 422</td><td>15.1</td><td> 9</td><td> 26.0</td><td> 3.0</td><td>23.5</td><td> 11</td><td> 60</td></tr> <tr><td>16. Butters </td><td>1 lb. </td><td>30.8</td><td> 1473</td><td>10.8</td><td> 9</td><td> 0.2</td><td> 3</td><td> 44.2</td><td>NA </td><td> 0.2</td><td> 2</td><td>NA </td></tr> <tr><td>17. Oleomargarine </td><td>1 lb. </td><td>16.1</td><td> 2817</td><td>20.6</td><td> 17</td><td> 0.6</td><td> 6</td><td> 55.8</td><td> 0.2</td><td>NA </td><td>NA </td><td>NA </td></tr> <tr><td>18. Eggs </td><td>1 doz. </td><td>32.6</td><td> 1857</td><td> 2.9</td><td> 238</td><td> 1.0</td><td> 52</td><td> 18.6</td><td> 2.8</td><td> 6.5</td><td> 1</td><td>NA </td></tr> <tr><td>19. Cheese (Cheddar) </td><td>1 lb. </td><td>24.2</td><td> 1874</td><td> 7.4</td><td> 448</td><td>16.4</td><td> 19</td><td> 28.1</td><td> 0.8</td><td>10.3</td><td> 4</td><td>NA </td></tr> <tr><td>20. Cream </td><td>0.5 pt. </td><td>14.1</td><td> 1689</td><td> 3.5</td><td> 49</td><td> 1.7</td><td> 3</td><td> 16.9</td><td> 0.6</td><td> 2.5</td><td>NA </td><td> 17</td></tr> <tr><td>21. Peanut Butter </td><td>1 lb. </td><td>17.9</td><td> 2534</td><td>15.7</td><td> 661</td><td> 1.0</td><td> 48</td><td>NA </td><td> 9.6</td><td> 8.1</td><td>471</td><td>NA </td></tr> <tr><td>22. Mayonnaise </td><td>0.5 pt. </td><td>16.7</td><td> 1198</td><td> 8.6</td><td> 18</td><td> 0.2</td><td> 8</td><td> 2.7</td><td> 0.4</td><td> 0.5</td><td>NA </td><td>NA </td></tr> <tr><td>23. Crisco </td><td>1 lb. </td><td>20.3</td><td> 2234</td><td>20.1</td><td>NA </td><td>NA </td><td>NA </td><td>NA </td><td>NA </td><td>NA </td><td>NA </td><td>NA </td></tr> <tr><td>24. Lard </td><td>1 lb. </td><td> 9.8</td><td> 4628</td><td>41.7</td><td>NA </td><td>NA </td><td>NA </td><td> 0.2</td><td>NA </td><td> 0.5</td><td> 5</td><td>NA </td></tr> <tr><td>25. Sirloin Steak </td><td>1 lb. </td><td>39.6</td><td> 1145</td><td> 2.9</td><td> 166</td><td> 0.1</td><td> 34</td><td> 0.2</td><td> 2.1</td><td> 2.9</td><td> 69</td><td>NA </td></tr> <tr><td>26. Round Steak </td><td>1 lb. </td><td>36.4</td><td> 1246</td><td> 2.2</td><td> 214</td><td> 0.1</td><td> 32</td><td> 0.4</td><td> 2.5</td><td> 2.4</td><td> 87</td><td>NA </td></tr> <tr><td>27. Rib Roast </td><td>1 lb. </td><td>29.2</td><td> 1553</td><td> 3.4</td><td> 213</td><td> 0.1</td><td> 33</td><td>NA </td><td>NA </td><td> 2.0</td><td>NA </td><td>NA </td></tr> <tr><td>28. Chuck Roast </td><td>1 lb. </td><td>22.6</td><td> 2007</td><td> 3.6</td><td> 309</td><td> 0.2</td><td> 46</td><td> 0.4</td><td> 1.0</td><td> 4.0</td><td>120</td><td>NA </td></tr> <tr><td>29. Plate </td><td>1 lb. </td><td>14.6</td><td> 3107</td><td> 8.5</td><td> 404</td><td> 0.2</td><td> 62</td><td>NA </td><td> 0.9</td><td>NA </td><td>NA </td><td>NA </td></tr> <tr><td>30. Liver (Beef) </td><td>1 lb. </td><td>26.8</td><td> 1692</td><td> 2.2</td><td> 333</td><td> 0.2</td><td>139</td><td>169.2</td><td> 6.4</td><td>50.8</td><td>316</td><td> 525</td></tr> <tr><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td></tr> <tr><td>49. Lettuce </td><td>1 head </td><td> 8.2</td><td> 2247</td><td> 0.4</td><td> 27</td><td> 1.1</td><td> 22</td><td>112.4</td><td> 1.8</td><td> 3.4</td><td> 11</td><td> 449</td></tr> <tr><td>50. Onions </td><td>1 lb. </td><td> 3.6</td><td>11844</td><td> 5.8</td><td> 166</td><td> 3.8</td><td> 59</td><td> 16.6</td><td> 4.7</td><td> 5.9</td><td> 21</td><td>1184</td></tr> <tr><td>51. Potatoes </td><td>15 lb. </td><td>34.0</td><td>16810</td><td>14.3</td><td> 336</td><td> 1.8</td><td>118</td><td> 6.7</td><td>29.4</td><td> 7.1</td><td>198</td><td>2522</td></tr> <tr><td>52. Spinach </td><td>1 lb. </td><td> 8.1</td><td> 4592</td><td> 1.1</td><td> 106</td><td>NA </td><td>138</td><td>918.4</td><td> 5.7</td><td>13.8</td><td> 33</td><td>2755</td></tr> <tr><td>53. Sweet Potatoes </td><td>1 lb. </td><td> 5.1</td><td> 7649</td><td> 9.6</td><td> 138</td><td> 2.7</td><td> 54</td><td>290.7</td><td> 8.4</td><td> 5.4</td><td> 83</td><td>1912</td></tr> <tr><td>54. Peaches (can) </td><td>No.2.5 </td><td>16.8</td><td> 4894</td><td> 3.7</td><td> 20</td><td> 0.4</td><td> 10</td><td> 21.5</td><td> 0.5</td><td> 1.0</td><td> 31</td><td> 196</td></tr> <tr><td>55. Pears (can) </td><td>No.2.5 </td><td>20.4</td><td> 4030</td><td> 3.0</td><td> 8</td><td> 0.3</td><td> 8</td><td> 0.8</td><td> 0.8</td><td> 0.8</td><td> 5</td><td> 81</td></tr> <tr><td>56. Pineapple (can) </td><td>No.2.5 </td><td>21.3</td><td> 3993</td><td> 2.4</td><td> 16</td><td> 0.4</td><td> 8</td><td> 2.0</td><td> 2.8</td><td> 0.8</td><td> 7</td><td> 399</td></tr> <tr><td>57. Asparagus (can) </td><td>No.2 </td><td>27.7</td><td> 1945</td><td> 0.4</td><td> 33</td><td> 0.3</td><td> 12</td><td> 16.3</td><td> 1.4</td><td> 2.1</td><td> 17</td><td> 272</td></tr> <tr><td>58. Green Beans (can) </td><td>No.2 </td><td>10.0</td><td> 5386</td><td> 1.0</td><td> 54</td><td> 2.0</td><td> 65</td><td> 53.9</td><td> 1.6</td><td> 4.3</td><td> 32</td><td> 431</td></tr> <tr><td>59. Pork and Beans (can) </td><td>16 oz. </td><td> 7.1</td><td> 6389</td><td> 7.5</td><td> 364</td><td> 4.0</td><td>134</td><td> 3.5</td><td> 8.3</td><td> 7.7</td><td> 56</td><td>NA </td></tr> <tr><td>60. Corn (can) </td><td>No.2 </td><td>10.4</td><td> 5452</td><td> 5.2</td><td> 136</td><td> 0.2</td><td> 16</td><td> 12.0</td><td> 1.6</td><td> 2.7</td><td> 42</td><td> 218</td></tr> <tr><td>61. Peas (can) </td><td>No.2 </td><td>13.8</td><td> 4109</td><td> 2.3</td><td> 136</td><td> 0.6</td><td> 45</td><td> 34.9</td><td> 4.9</td><td> 2.5</td><td> 37</td><td> 370</td></tr> <tr><td>62. Tomatoes (can) </td><td>No.2 </td><td> 8.6</td><td> 6263</td><td> 1.3</td><td> 63</td><td> 0.7</td><td> 38</td><td> 53.2</td><td> 3.4</td><td> 2.5</td><td> 36</td><td>1253</td></tr> <tr><td>63. Tomato Soup (can) </td><td>10.5 oz.</td><td> 7.6</td><td> 3917</td><td> 1.6</td><td> 71</td><td> 0.6</td><td> 43</td><td> 57.9</td><td> 3.5</td><td> 2.4</td><td> 67</td><td> 862</td></tr> <tr><td>64. Peaches Dried </td><td>1 lb. </td><td>15.7</td><td> 2889</td><td> 8.5</td><td> 87</td><td> 1.7</td><td>173</td><td> 86.8</td><td> 1.2</td><td> 4.3</td><td> 55</td><td> 57</td></tr> <tr><td>65. Prunes Dried </td><td>1 lb. </td><td> 9.0</td><td> 4284</td><td>12.8</td><td> 99</td><td> 2.5</td><td>154</td><td> 85.7</td><td> 3.9</td><td> 4.3</td><td> 65</td><td> 257</td></tr> <tr><td>66. Raisins Dried </td><td>15 oz. </td><td> 9.4</td><td> 4524</td><td>13.5</td><td> 104</td><td> 2.5</td><td>136</td><td> 4.5</td><td> 6.3</td><td> 1.4</td><td> 24</td><td> 136</td></tr> <tr><td>67. Peas Dried </td><td>1 lb. </td><td> 7.9</td><td> 5742</td><td>20.0</td><td>1367</td><td> 4.2</td><td>345</td><td> 2.9</td><td>28.7</td><td>18.4</td><td>162</td><td>NA </td></tr> <tr><td>68. Lima Beans Dried </td><td>1 lb. </td><td> 8.9</td><td> 5097</td><td>17.4</td><td>1055</td><td> 3.7</td><td>459</td><td> 5.1</td><td>26.9</td><td>38.2</td><td> 93</td><td>NA </td></tr> <tr><td>69. Navy Beans Dried </td><td>1 lb. </td><td> 5.9</td><td> 7688</td><td>26.9</td><td>1691</td><td>11.4</td><td>792</td><td>NA </td><td>38.4</td><td>24.6</td><td>217</td><td>NA </td></tr> <tr><td>70. Coffee </td><td>1 lb. </td><td>22.4</td><td> 2025</td><td>NA </td><td>NA </td><td>NA </td><td>NA </td><td>NA </td><td> 4.0</td><td> 5.1</td><td> 50</td><td>NA </td></tr> <tr><td>71. Tea </td><td>0.25 lb.</td><td>17.4</td><td> 652</td><td>NA </td><td>NA </td><td>NA </td><td>NA </td><td>NA </td><td>NA </td><td> 2.3</td><td> 42</td><td>NA </td></tr> <tr><td>72. Cocoa </td><td>8 oz. </td><td> 8.6</td><td> 2657</td><td> 8.7</td><td> 237</td><td> 3.0</td><td> 72</td><td>NA </td><td> 2.0</td><td>11.9</td><td> 40</td><td>NA </td></tr> <tr><td>73. Chocolate </td><td>8 oz. </td><td>16.2</td><td> 1400</td><td> 8.0</td><td> 77</td><td> 1.3</td><td> 39</td><td>NA </td><td> 0.9</td><td> 3.4</td><td> 14</td><td>NA </td></tr> <tr><td>74. Sugar </td><td>10 lb. </td><td>51.2</td><td> 8773</td><td>34.9</td><td>NA </td><td>NA </td><td>NA </td><td>NA </td><td>NA </td><td>NA </td><td>NA </td><td>NA </td></tr> <tr><td>75. Corn Sirup </td><td>24 oz. </td><td>13.7</td><td> 4966</td><td>14.7</td><td>NA </td><td> 0.5</td><td> 74</td><td>NA </td><td>NA </td><td>NA </td><td> 5</td><td>NA </td></tr> <tr><td>76. Molasses </td><td>18 oz. </td><td>13.6</td><td> 3752</td><td> 9.0</td><td>NA </td><td>10.3</td><td>244</td><td>NA </td><td> 1.9</td><td> 7.5</td><td>146</td><td>NA </td></tr> <tr><td>77. Strawberry Preserves </td><td>1 lb. </td><td>20.5</td><td> 2213</td><td> 6.4</td><td> 11</td><td> 0.4</td><td> 7</td><td> 0.2</td><td> 0.2</td><td> 0.4</td><td> 3</td><td>NA </td></tr> <tr><td>Daily allowance </td><td> </td><td>NA </td><td>NA </td><td> 3.0</td><td> 70</td><td> 0.8</td><td> 12</td><td> 5.0</td><td> 1.8</td><td> 2.7</td><td> 18</td><td> 75</td></tr> </tbody> </table> Our dataset has the nutritional content of $77$ commodities, and in the final row, the daily minimum requirement of each of these nutrients. ### The Diet problem Problem setup: * Assume there are nutrients $i\in\left\{ 1,...,m\right\} $ (calories, protein, calcium, iron, etc.) that matter for a person's health, in such way that the minimum daily intake of nutrient $i$ should be $d_{i}$. * Nutrients do not come as standalone elements, but are combined into various foods. Each unit of food $j\in\left\{ 1,...,n\right\}$ yields a quantity $N_{ij}$ of nutrient $i\in\left\{1,...,m\right\}$. The dollar cost of food $j$ is $c_{j}$. The problem is to find the diet that achieves the minimal intake of each nutrient at a cheapest price. If $q\in\mathbb{R}^{n}$ is a vector such that $q_{j}\geq0$ is the quantity of food $i$ purchased, the quantity of nutrient $i$ ingested is $\sum_{j=1}^{n}N_{ij}q_{j}$, and the cost of the diet is $\sum_{j=1}^{n}q_{j}c_{j}$. The optimal diet is therefore given by \begin{align*} \min_{q\geq0} & ~c^{\top}q\\ s.t.~ & Nq\geq d.\nonumber \end{align*} Before we tackle this problem, let's look into the linear programming problem in standard form. ## A Crash Course on Linear Programming ### Linear programming in standard form Let $c\in\mathbb{R}^{n}$, $d\in\mathbb{R}^{m}$, $A$ be a $m\times n$ matrix, and consider the following problem \begin{align} V_{P} = \max_{x\in\mathbb{R}_{+}^{n}} & \, c^{\top} x \\ s.t.~Ax & \leq d \end{align} This problem is a *linear programming problem*, as the objective function, namely $x\rightarrow c^{\top}x$ is linear, and as the constraint, namely $x\in\mathbb{R}_{+}^{n}$ and $Ax=d$ are also linear (or more accurately, affine). This problem is called the *primal program*, for reasons to be explained soon. The set of $x$'s that satisfy the constraint are called *feasible solutions*; the set of solutions of the primal problem are called *optimal solutions*. ### Remarks * The previous diet problem can be reformulate into this problem - why? * A problem does not necessarly have a feasible solution (e.g. if $A=0$ and $d\neq0$), in which case (by convention) $V_{P}=-\infty$. * The whole space may be solution (e.g. if $A=0$ and $d=0$), in which case $V_{P}=+\infty$. ### Duality There is a powerful tool called duality which provides much insight into the analysis of the primal problem. The idea is to rewrite the problem as \begin{align*} V_{P}=\max_{x\in\mathbb{R}_{+}^{n}}\left\{ c^{\top}x+L_{P}\left( d-Ax\right) \right\} \end{align*} where $L_{P}\left(z\right)$ is a penalty function whose value is zero if the constraint is met, that is if $z=0$, and $-\infty$ if it is not, namely if $z\neq0$. The simplest choice of such penalty function is given by $L_{P}\left( z\right) =\min_{y\in\mathbb{R}^{m}}\left\{ z^{\top}y\right\}$. One has \begin{align*} V_{P}=\max_{x\in\mathbb{R}_{+}^{n}}\min_{y\in\mathbb{R}^{m}}\left\{c^{\top}x+\left( d-Ax\right) ^{\top}y\right\} . \end{align*} However, the minimax inequality $\max_{x}\min_{y}\leq\min_{y}\max_{x}$ always holds, thus \begin{align*} V_{P} & \leq\min_{y\in\mathbb{R}^{m}}\max_{x\in\mathbb{R}_{+}^{n}}\left\{ c^{\top}x+\left( d-Ax\right) ^{\top}y\right\} =\min_{y\in\mathbb{R}^{m} }\max_{x\in\mathbb{R}_{+}^{n}}\left\{ x^{\top}\left( c-A^{\top}y\right) +d^{\top}y\right\} \\ & \leq\min_{y\in\mathbb{R}^{m}}\left\{ d^{\top}y+L_{D}\left( c-A^{\top }y\right) \right\} =:V_{D} \end{align*} where $L_{D}\left(z\right) = \max_{x\in\mathbb{R}_{+}^{n}}\left\{x^{\top}z\right\}$ is equal to $0$ if $z\in\mathbb{R}_{-}^{n}$, and to $+\infty$ if not. Therefore, the value $V_{D}$ is expressed by the *dual program* \begin{align} V_{D}=\min_{y\in\mathbb{R}^{m}} & \, d^{\top}y, \\ s.t.~A^{\top}y & \geq c \end{align} and the weak duality inequality $V_{P}\leq V_{D}$ holds. It turns out that as soon as either the primal or dual program has an optimal solution, then both programs have an optimal solution and the values of the two programs coincide, so the weak duality becomes an equality $V_{P}=V_{D}$ called strong duality. Further, if $x^{\ast}\in\mathbb{R}_{+}^{n}$ is an optimal primal solution, and $y^{\ast}\in\mathbb{R}^{m}$ is an optimal dual solution, then complementary slackness holds, that is $x_{i}^{\ast}>0$ implies $\left( A^{\top}y^{\ast }\right) _{i}=c_{i}$. ### Duality theorem We summarize these results into the following statement. --- **Theorem.** In the setting described above: 1. The weak duality inequality holds: \begin{align} V_{P}\leq V_{D}. \end{align} 2. As soon as the primal or the dual program have an optimal solution, then both programs have an optimal solution, and strong duality holds: \begin{align} V_{P}=V_{D}. \end{align} 3. If $x^{\ast}\in\mathbb{R}_{+}^{n}$ is an optimal primal solution, and $y^{\ast}\in\mathbb{R}^{m}$ is an optimal dual solution, then complementary slackness holds: \begin{align} x_{i}^{\ast}>0\text{ implies }\left( A^{\top}y^{\ast}\right) _{i}=c_{i}. \end{align} --- ## The diet problem (revisited) Recall the optimal diet problem \begin{align*} \min_{q\geq0} & \, c^{\top}q\\ s.t.~ & Nq\geq d. \end{align*} which has minimax formulation $\min_{q\geq0}\max_{\pi\geq0}c^{\top}q+d^{\top}\pi-q^{\top}N^{\top}\pi$, so the dual is \begin{align*} \max_{\pi\geq0} & \, d^{\top}\pi\\ s.t.~ & N^{\top}\pi\leq c \end{align*} Interpretation: imagine that there is a new firm called Nutrient Shoppe, who sells raw nutrients. Let $\pi_{i}$ be the price of nutrient $i$. The cost of the diet is $d^{\top}\pi$. Consumer purchase raw nutrients and can generate "synthetic foods". The cost of the synthetic version of food $j$ is $\sum_{i=1}^{m}N_{ij}\pi_{i}=\left(N^{\intercal}\pi\right)_{j}$. The constraint thus means that each "synthetic food" is more affordable than its natural counterpart. The duality means that it is possible to price the nutrients so that the synthetic foods are cheaper than the natural ones, in such a way that the price of the synthetic diet equals the price of the natural diet. Complementary slackness yields: * $q_{j}>0$ implies $\left( N^{\intercal}\pi\right) _{j}=c_{j}$; that is, if natural food $j$ is actually purchased, then the prices of its synthetic and natural versions coincide * $\pi_{i}>0$ implies $\left( Nq\right) _{i}=d_{i}$; that is, if nutrient $i$ has a positive price, then the natural diet has the "just right" amount. ### Solving the diet problem To solve the primal problem we need to construct the objects $c$, $N$ and $d$. $c$ is simply a vector of ones, the size of the number of commodities. $N$ is a matrix of amount of nutrients in each commodity. $d$ is the required daily allowance of each nutrient. ```R nbCommodities = length(which(thedata[, 1] != "")) - 1 names = thedata[1:nbCommodities, 1] themat = matrix(as.numeric(thedata[, 3:13]), ncol = 11) themat[is.na(themat)] = 0 N = t(themat[1:nbCommodities, 3:11]) d = themat[(nbCommodities + 1), 3:11] c = rep(1, nbCommodities) ``` We will be using [Gurobi](http://www.gurobi.com/) as our linear programming solver for the entirety of this course. Whilst Gurobi is not neccassary-as there are many available linear programming solvers-it is lightning quick and free for acedemics. So let's first load up the Gurobi library. ```R library(gurobi) ``` Loading required package: slam Warning message: "package 'slam' was built under R version 3.6.2" And look at the functions syntax. ```R ?gurobi ``` ```R ?gurobi_model ``` ```R ?gurobi_params ``` So mapping from gurobis notation to ours, * `A` = $N$ * `obj` = $c$ * `sense` = '$>$' * `rhs` = $d$ * `modelsense` = '$\min$' ```R result = gurobi(list(A = N, obj = c, sense = ">", rhs = d, modelsense = "min")) #, params = list(OutputFlag = 0)) ``` Gurobi Optimizer version 9.0.0 build v9.0.0rc2 (win64) Optimize a model with 9 rows, 77 columns and 570 nonzeros Model fingerprint: 0x7ae6b743 Coefficient statistics: Matrix range [1e-01, 5e+03] Objective range [1e+00, 1e+00] Bounds range [0e+00, 0e+00] RHS range [8e-01, 8e+01] Presolve removed 0 rows and 47 columns Presolve time: 0.00s Presolved: 9 rows, 30 columns, 240 nonzeros Iteration Objective Primal Inf. Dual Inf. Time 0 0.0000000e+00 1.384688e+01 0.000000e+00 0s 5 1.0866228e-01 0.000000e+00 0.000000e+00 0s Solved in 5 iterations and 0.00 seconds Optimal objective 1.086622782e-01 Let's see what is in the `result` object: ```R str(result) ``` List of 13 $ status : chr "OPTIMAL" $ runtime : num 0.001 $ itercount : num 5 $ baritercount: int 0 $ nodecount : num 0 $ objval : num 0.109 $ x : num [1:77] 0.0295 0 0 0 0 ... $ slack : num [1:9] 0 -77.4 0 -48.5 0 ... $ rc : num [1:77] 0 0.845 0.296 0.859 0.489 ... $ pi : num [1:9] 0.00877 0 0.03174 0 0.0004 ... $ vbasis : int [1:77] 0 -1 -1 -1 -1 -1 -1 -1 -1 -1 ... $ cbasis : int [1:9] -1 0 -1 0 -1 0 -1 0 -1 $ objbound : num 0.109 We are after the optimal solutions `x`, the dual solution `pi` and the value function `objval` ```R q_yearly = result$x * 365 # convert into yearly cost pi = result$pi cost_daily = result$objval ``` Our optimal solution (including only foods which are non-zero) ```R print("*** Optimal solution ***") toKeep = which(q_yearly != 0) foods = q_yearly[toKeep] names(foods) = names[toKeep] foods print(paste0("Total cost (optimal)= ", sum(q_yearly * c))) ``` [1] "*** Optimal solution ***" <dl class=dl-horizontal> <dt>1. Wheat Flour (Enriched)</dt> <dd>10.7744575119182</dd> <dt>30. Liver (Beef)</dt> <dd>0.690783411107421</dd> <dt>46. Cabbage</dt> <dd>4.09326886484288</dd> <dt>52. Spinach </dt> <dd>1.8277960703547</dd> <dt>69. Navy Beans Dried</dt> <dd>22.275425687243</dd> </dl> [1] "Total cost (optimal)= 39.6617315454663" As promised, we achieve the minimum cost bundle at $\$39.67$ per year in $1939$ dollars. We can compare this to Stigler's solutions which was: |Food| Annual Quantities| Annual Cost| | ---------- | ------------------ | ------------ | | Wheat Flour | 370 lb.| \$13.33 | | Evaporated Milk | 57 cans | \$3.84 | |Cabbage| 111 lb. |\$4.11| |Spinach| 23 lb. |\$1.85| |Dried Navy Beans| 285 lb. | \$16.80| |Total Annual Cost| &nbsp; | \$39.93 | ## Recovering the solution with the glpk solver ```R library(Rglpk) resGlpk = Rglpk_solve_LP(obj = c, mat = N, dir = rep(">", length(d)), rhs = d, bounds = NULL, max = FALSE, control = list()) print(resGlpk$optimum * 365) ``` Warning message: "package 'Rglpk' was built under R version 3.6.2"Using the GLPK callable library version 4.47 [1] 39.66173 ```R ```
Require Setoid. Require Import PeanoNat Le Gt Minus Bool Lt List. Require Import Omega. Section ReDun. Variable A : Type. Variable decA : forall (a b : A), {a = b}+{a <> b}. Theorem NoDup_count_occ' l: NoDup l <-> (forall x:A, In x l -> count_occ decA l x = 1). Proof. rewrite (NoDup_count_occ decA). setoid_rewrite (count_occ_In decA) at 1. unfold gt, lt in *. split; intros H x; specialize (H x); set (n := count_occ decA l x) in *; clearbody n; omega. Qed. End ReDun.
State Before: V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' u u' : V p : Walk G u u hu : u = u' ⊢ IsCircuit (Walk.copy p hu hu) ↔ IsCircuit p State After: V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' u' : V p : Walk G u' u' ⊢ IsCircuit (Walk.copy p (_ : u' = u') (_ : u' = u')) ↔ IsCircuit p Tactic: subst_vars State Before: V : Type u V' : Type v V'' : Type w G : SimpleGraph V G' : SimpleGraph V' G'' : SimpleGraph V'' u' : V p : Walk G u' u' ⊢ IsCircuit (Walk.copy p (_ : u' = u') (_ : u' = u')) ↔ IsCircuit p State After: no goals Tactic: rfl
[STATEMENT] lemma idx_iteratei_aux_simps[simp]: "i=0 \<Longrightarrow> idx_iteratei_aux get sz i l c f \<sigma> = \<sigma>" "\<not>c \<sigma> \<Longrightarrow> idx_iteratei_aux get sz i l c f \<sigma> = \<sigma>" "\<lbrakk>i\<noteq>0; c \<sigma>\<rbrakk> \<Longrightarrow> idx_iteratei_aux get sz i l c f \<sigma> = idx_iteratei_aux get sz (i - 1) l c f (f (get l (sz-i)) \<sigma>)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (i = 0 \<Longrightarrow> idx_iteratei_aux get sz i l c f \<sigma> = \<sigma>) &&& (\<not> c \<sigma> \<Longrightarrow> idx_iteratei_aux get sz i l c f \<sigma> = \<sigma>) &&& (\<lbrakk>i \<noteq> 0; c \<sigma>\<rbrakk> \<Longrightarrow> idx_iteratei_aux get sz i l c f \<sigma> = idx_iteratei_aux get sz (i - 1) l c f (f (get l (sz - i)) \<sigma>)) [PROOF STEP] apply - [PROOF STATE] proof (prove) goal (3 subgoals): 1. i = 0 \<Longrightarrow> idx_iteratei_aux get sz i l c f \<sigma> = \<sigma> 2. \<not> c \<sigma> \<Longrightarrow> idx_iteratei_aux get sz i l c f \<sigma> = \<sigma> 3. \<lbrakk>i \<noteq> 0; c \<sigma>\<rbrakk> \<Longrightarrow> idx_iteratei_aux get sz i l c f \<sigma> = idx_iteratei_aux get sz (i - 1) l c f (f (get l (sz - i)) \<sigma>) [PROOF STEP] apply (subst idx_iteratei_aux.simps, simp)+ [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !! !! !! This file is part of SciFT project !! !! Copyright (c) 2011-2016 Nestor F. Aguirre ([email protected]) !! !! !! !! Redistribution and use in source and binary forms, with or without !! !! modification, are permitted provided that the following conditions are met: !! !! !! !! 1. Redistributions of source code must retain the above copyright notice, this !! !! list of conditions and the following disclaimer. !! !! 2. Redistributions in binary form must reproduce the above copyright notice, !! !! this list of conditions and the following disclaimer in the documentation !! !! and/or other materials provided with the distribution. !! !! 3. Neither the name of the copyright holders nor the names of its contributors !! !! may be used to endorse or promote products derived from this software !! !! without specific prior written permission. !! !! !! !! The copyright holders provide no reassurances that the source code provided !! !! does not infringe any patent, copyright, or any other intellectual property !! !! rights of third parties. The copyright holders disclaim any liability to any !! !! recipient for claims brought against recipient by any third party for !! !! infringement of that parties intellectual property rights. !! !! !! !! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND !! !! ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED !! !! WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE !! !! DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR !! !! ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES !! !! (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; !! !! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND !! !! ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT !! !! (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS !! !! SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. !! !! !! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !> !! @brief Test program !! program main use GOptions_ use Math_ use IOStream_ use String_ use CommandLineParser_ use Grid_ use RNFunction_ use NIntegrator_ implicit none type(String) :: iFileName type(String) :: oFileName type(String) :: filter real(8) :: t, ta, tb type(Grid) :: tgrid type(IFStream) :: ifile type(RNFunction) :: nFunc, nFunc2, nFuncWindow, oFunc type(NIntegrator) :: integrator type(String) :: strBuffer type(CommandLineParser) :: parser character(5), allocatable :: tokens(:) integer :: columns(2) integer :: i iFileName = parser.getString( "-i" ) oFileName = parser.getString( "-o" ) filter = parser.getString( "-f" ) strBuffer = parser.getString( "-c", def="1,2" ) call strBuffer.split( tokens, "," ) columns = [ FString_toInteger(tokens(1)), FString_toInteger(tokens(2)) ] call ifile.init( iFileName.fstr ) call nFunc.fromFStream( ifile, columns=columns ) call ifile.close() ! call oFunc.init( nFunc.xGrid, value=0.0_8 ) call oFunc.init( nFunc.xGrid ) select case( trim(filter.fstr) ) case( ">0" ) oFunc.fArray = merge( nFunc.fArray, 0.0_8, nFunc.fArray > 0.0_8 ) case default write(*,*) "### ERROR ### Filter "//trim(filter.fstr)//" is not supported" stop end select call oFunc.save( oFileName.fstr ) end program main
def f (x : α) := x theorem ex1 (a : α) (b : List α) : f (a::b = []) = False := by simp [f] def length : List α → Nat | [] => 0 | a::as => length as + 1 theorem ex2 (a b c : α) (as : List α) : length (a :: b :: as) > length as := by simp [length] apply Nat.lt.step apply Nat.lt_succ_self def fact : Nat → Nat | 0 => 1 | x+1 => (x+1) * fact x theorem ex3 : fact x > 0 := by induction x with | zero => decide | succ x ih => simp [fact] apply Nat.mul_pos apply Nat.zero_lt_succ apply ih def head [Inhabited α] : List α → α | [] => default | a::_ => a theorem ex4 [Inhabited α] (a : α) (as : List α) : head (a::as) = a := by simp [head] def foo := 10 theorem ex5 (x : Nat) : foo + x = 10 + x := by simp [foo] done def g (x : Nat) : Nat := Id.run <| do let x := x return x theorem ex6 : g x = x := by simp [g, bind, pure] rfl def f1 : StateM Nat Unit := do modify fun x => g x def f2 : StateM Nat Unit := do let s ← get set <| g s theorem ex7 : f1 = f2 := by simp [f1, f2, bind, StateT.bind, get, getThe, MonadStateOf.get, StateT.get, pure, set, StateT.set, modify, modifyGet, MonadStateOf.modifyGet, StateT.modifyGet] def h (x : Nat) : Sum (Nat × Nat) Nat := Sum.inl (x, x) def bla (x : Nat) := match h x with | Sum.inl (y, z) => y + z | Sum.inr _ => 0 theorem ex8 (x : Nat) : bla x = x + x := by simp [bla, h]
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash ! This file was ported from Lean 3 source module algebra.lie.of_associative ! leanprover-community/mathlib commit f0f3d964763ecd0090c9eb3ae0d15871d08781c4 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Algebra.Lie.Basic import Mathbin.Algebra.Lie.Subalgebra import Mathbin.Algebra.Lie.Submodule import Mathbin.Algebra.Algebra.Subalgebra.Basic /-! # Lie algebras of associative algebras This file defines the Lie algebra structure that arises on an associative algebra via the ring commutator. Since the linear endomorphisms of a Lie algebra form an associative algebra, one can define the adjoint action as a morphism of Lie algebras from a Lie algebra to its linear endomorphisms. We make such a definition in this file. ## Main definitions * `lie_algebra.of_associative_algebra` * `lie_algebra.of_associative_algebra_hom` * `lie_module.to_endomorphism` * `lie_algebra.ad` * `linear_equiv.lie_conj` * `alg_equiv.to_lie_equiv` ## Tags lie algebra, ring commutator, adjoint action -/ universe u v w w₁ w₂ section OfAssociative variable {A : Type v} [Ring A] namespace Ring /-- The bracket operation for rings is the ring commutator, which captures the extent to which a ring is commutative. It is identically zero exactly when the ring is commutative. -/ instance (priority := 100) : Bracket A A := ⟨fun x y => x * y - y * x⟩ theorem lie_def (x y : A) : ⁅x, y⁆ = x * y - y * x := rfl #align ring.lie_def Ring.lie_def end Ring theorem commute_iff_lie_eq {x y : A} : Commute x y ↔ ⁅x, y⁆ = 0 := sub_eq_zero.symm #align commute_iff_lie_eq commute_iff_lie_eq theorem Commute.lie_eq {x y : A} (h : Commute x y) : ⁅x, y⁆ = 0 := sub_eq_zero_of_eq h #align commute.lie_eq Commute.lie_eq namespace LieRing /-- An associative ring gives rise to a Lie ring by taking the bracket to be the ring commutator. -/ instance (priority := 100) ofAssociativeRing : LieRing A where add_lie := by simp only [Ring.lie_def, right_distrib, left_distrib, sub_eq_add_neg, add_comm, add_left_comm, forall_const, eq_self_iff_true, neg_add_rev] lie_add := by simp only [Ring.lie_def, right_distrib, left_distrib, sub_eq_add_neg, add_comm, add_left_comm, forall_const, eq_self_iff_true, neg_add_rev] lie_self := by simp only [Ring.lie_def, forall_const, sub_self] leibniz_lie x y z := by repeat' rw [Ring.lie_def] noncomm_ring #align lie_ring.of_associative_ring LieRing.ofAssociativeRing theorem of_associative_ring_bracket (x y : A) : ⁅x, y⁆ = x * y - y * x := rfl #align lie_ring.of_associative_ring_bracket LieRing.of_associative_ring_bracket @[simp] theorem lie_apply {α : Type _} (f g : α → A) (a : α) : ⁅f, g⁆ a = ⁅f a, g a⁆ := rfl #align lie_ring.lie_apply LieRing.lie_apply end LieRing section AssociativeModule variable {M : Type w} [AddCommGroup M] [Module A M] /-- We can regard a module over an associative ring `A` as a Lie ring module over `A` with Lie bracket equal to its ring commutator. Note that this cannot be a global instance because it would create a diamond when `M = A`, specifically we can build two mathematically-different `has_bracket A A`s: 1. `@ring.has_bracket A _` which says `⁅a, b⁆ = a * b - b * a` 2. `(@lie_ring_module.of_associative_module A _ A _ _).to_has_bracket` which says `⁅a, b⁆ = a • b` (and thus `⁅a, b⁆ = a * b`) See note [reducible non-instances] -/ @[reducible] def LieRingModule.ofAssociativeModule : LieRingModule A M where bracket := (· • ·) add_lie := add_smul lie_add := smul_add leibniz_lie := by simp [LieRing.of_associative_ring_bracket, sub_smul, mul_smul, sub_add_cancel] #align lie_ring_module.of_associative_module LieRingModule.ofAssociativeModule attribute [local instance] LieRingModule.ofAssociativeModule theorem lie_eq_smul (a : A) (m : M) : ⁅a, m⁆ = a • m := rfl #align lie_eq_smul lie_eq_smul end AssociativeModule section LieAlgebra variable {R : Type u} [CommRing R] [Algebra R A] /-- An associative algebra gives rise to a Lie algebra by taking the bracket to be the ring commutator. -/ instance (priority := 100) LieAlgebra.ofAssociativeAlgebra : LieAlgebra R A where lie_smul t x y := by rw [LieRing.of_associative_ring_bracket, LieRing.of_associative_ring_bracket, Algebra.mul_smul_comm, Algebra.smul_mul_assoc, smul_sub] #align lie_algebra.of_associative_algebra LieAlgebra.ofAssociativeAlgebra attribute [local instance] LieRingModule.ofAssociativeModule section AssociativeRepresentation variable {M : Type w} [AddCommGroup M] [Module R M] [Module A M] [IsScalarTower R A M] /-- A representation of an associative algebra `A` is also a representation of `A`, regarded as a Lie algebra via the ring commutator. See the comment at `lie_ring_module.of_associative_module` for why the possibility `M = A` means this cannot be a global instance. -/ def LieModule.ofAssociativeModule : LieModule R A M where smul_lie := smul_assoc lie_smul := smul_algebra_smul_comm #align lie_module.of_associative_module LieModule.ofAssociativeModule instance Module.End.lieRingModule : LieRingModule (Module.End R M) M := LieRingModule.ofAssociativeModule #align module.End.lie_ring_module Module.End.lieRingModule instance Module.End.lieModule : LieModule R (Module.End R M) M := LieModule.ofAssociativeModule #align module.End.lie_module Module.End.lieModule end AssociativeRepresentation namespace AlgHom variable {B : Type w} {C : Type w₁} [Ring B] [Ring C] [Algebra R B] [Algebra R C] variable (f : A →ₐ[R] B) (g : B →ₐ[R] C) /-- The map `of_associative_algebra` associating a Lie algebra to an associative algebra is functorial. -/ def toLieHom : A →ₗ⁅R⁆ B := { f.toLinearMap with map_lie' := fun x y => show f ⁅x, y⁆ = ⁅f x, f y⁆ by simp only [LieRing.of_associative_ring_bracket, AlgHom.map_sub, AlgHom.map_mul] } #align alg_hom.to_lie_hom AlgHom.toLieHom instance : Coe (A →ₐ[R] B) (A →ₗ⁅R⁆ B) := ⟨toLieHom⟩ @[simp] theorem toLieHom_coe : f.toLieHom = ↑f := rfl #align alg_hom.to_lie_hom_coe AlgHom.toLieHom_coe @[simp] theorem coe_to_lieHom : ((f : A →ₗ⁅R⁆ B) : A → B) = f := rfl #align alg_hom.coe_to_lie_hom AlgHom.coe_to_lieHom theorem toLieHom_apply (x : A) : f.toLieHom x = f x := rfl #align alg_hom.to_lie_hom_apply AlgHom.toLieHom_apply @[simp] theorem to_lieHom_id : (AlgHom.id R A : A →ₗ⁅R⁆ A) = LieHom.id := rfl #align alg_hom.to_lie_hom_id AlgHom.to_lieHom_id @[simp] theorem to_lieHom_comp : (g.comp f : A →ₗ⁅R⁆ C) = (g : B →ₗ⁅R⁆ C).comp (f : A →ₗ⁅R⁆ B) := rfl #align alg_hom.to_lie_hom_comp AlgHom.to_lieHom_comp theorem to_lieHom_injective {f g : A →ₐ[R] B} (h : (f : A →ₗ⁅R⁆ B) = (g : A →ₗ⁅R⁆ B)) : f = g := by ext a exact LieHom.congr_fun h a #align alg_hom.to_lie_hom_injective AlgHom.to_lieHom_injective end AlgHom end LieAlgebra end OfAssociative section AdjointAction variable (R : Type u) (L : Type v) (M : Type w) variable [CommRing R] [LieRing L] [LieAlgebra R L] [AddCommGroup M] [Module R M] variable [LieRingModule L M] [LieModule R L M] /-- A Lie module yields a Lie algebra morphism into the linear endomorphisms of the module. See also `lie_module.to_module_hom`. -/ @[simps] def LieModule.toEndomorphism : L →ₗ⁅R⁆ Module.End R M where toFun x := { toFun := fun m => ⁅x, m⁆ map_add' := lie_add x map_smul' := fun t => lie_smul t x } map_add' x y := by ext m apply add_lie map_smul' t x := by ext m apply smul_lie map_lie' x y := by ext m apply lie_lie #align lie_module.to_endomorphism LieModule.toEndomorphism /-- The adjoint action of a Lie algebra on itself. -/ def LieAlgebra.ad : L →ₗ⁅R⁆ Module.End R L := LieModule.toEndomorphism R L L #align lie_algebra.ad LieAlgebra.ad @[simp] theorem LieAlgebra.ad_apply (x y : L) : LieAlgebra.ad R L x y = ⁅x, y⁆ := rfl #align lie_algebra.ad_apply LieAlgebra.ad_apply @[simp] theorem LieModule.toEndomorphism_module_end : LieModule.toEndomorphism R (Module.End R M) M = LieHom.id := by ext (g m) simp [lie_eq_smul] #align lie_module.to_endomorphism_module_End LieModule.toEndomorphism_module_end theorem LieSubalgebra.toEndomorphism_eq (K : LieSubalgebra R L) {x : K} : LieModule.toEndomorphism R K M x = LieModule.toEndomorphism R L M x := rfl #align lie_subalgebra.to_endomorphism_eq LieSubalgebra.toEndomorphism_eq @[simp] theorem LieSubalgebra.toEndomorphism_mk (K : LieSubalgebra R L) {x : L} (hx : x ∈ K) : LieModule.toEndomorphism R K M ⟨x, hx⟩ = LieModule.toEndomorphism R L M x := rfl #align lie_subalgebra.to_endomorphism_mk LieSubalgebra.toEndomorphism_mk variable {R L M} namespace LieSubmodule open LieModule variable {N : LieSubmodule R L M} {x : L} theorem coe_map_toEndomorphism_le : (N : Submodule R M).map (LieModule.toEndomorphism R L M x) ≤ N := by rintro n ⟨m, hm, rfl⟩ exact N.lie_mem hm #align lie_submodule.coe_map_to_endomorphism_le LieSubmodule.coe_map_toEndomorphism_le variable (N x) theorem toEndomorphism_comp_subtype_mem (m : M) (hm : m ∈ (N : Submodule R M)) : (toEndomorphism R L M x).comp (N : Submodule R M).Subtype ⟨m, hm⟩ ∈ (N : Submodule R M) := by simpa using N.lie_mem hm #align lie_submodule.to_endomorphism_comp_subtype_mem LieSubmodule.toEndomorphism_comp_subtype_mem @[simp] theorem toEndomorphism_restrict_eq_toEndomorphism (h := N.toEndomorphism_comp_subtype_mem x) : (toEndomorphism R L M x).restrict h = toEndomorphism R L N x := by ext simp [LinearMap.restrict_apply] #align lie_submodule.to_endomorphism_restrict_eq_to_endomorphism LieSubmodule.toEndomorphism_restrict_eq_toEndomorphism end LieSubmodule open LieAlgebra theorem LieAlgebra.ad_eq_lmul_left_sub_lmul_right (A : Type v) [Ring A] [Algebra R A] : (ad R A : A → Module.End R A) = LinearMap.mulLeft R - LinearMap.mulRight R := by ext (a b) simp [LieRing.of_associative_ring_bracket] #align lie_algebra.ad_eq_lmul_left_sub_lmul_right LieAlgebra.ad_eq_lmul_left_sub_lmul_right theorem LieSubalgebra.ad_comp_incl_eq (K : LieSubalgebra R L) (x : K) : (ad R L ↑x).comp (K.incl : K →ₗ[R] L) = (K.incl : K →ₗ[R] L).comp (ad R K x) := by ext y simp only [ad_apply, LieHom.coe_toLinearMap, LieSubalgebra.coe_incl, LinearMap.coe_comp, LieSubalgebra.coe_bracket, Function.comp_apply] #align lie_subalgebra.ad_comp_incl_eq LieSubalgebra.ad_comp_incl_eq end AdjointAction /-- A subalgebra of an associative algebra is a Lie subalgebra of the associated Lie algebra. -/ def lieSubalgebraOfSubalgebra (R : Type u) [CommRing R] (A : Type v) [Ring A] [Algebra R A] (A' : Subalgebra R A) : LieSubalgebra R A := { A'.toSubmodule with lie_mem' := fun x y hx hy => by change ⁅x, y⁆ ∈ A' change x ∈ A' at hx change y ∈ A' at hy rw [LieRing.of_associative_ring_bracket] have hxy := A'.mul_mem hx hy have hyx := A'.mul_mem hy hx exact Submodule.sub_mem A'.to_submodule hxy hyx } #align lie_subalgebra_of_subalgebra lieSubalgebraOfSubalgebra namespace LinearEquiv variable {R : Type u} {M₁ : Type v} {M₂ : Type w} variable [CommRing R] [AddCommGroup M₁] [Module R M₁] [AddCommGroup M₂] [Module R M₂] variable (e : M₁ ≃ₗ[R] M₂) /-- A linear equivalence of two modules induces a Lie algebra equivalence of their endomorphisms. -/ def lieConj : Module.End R M₁ ≃ₗ⁅R⁆ Module.End R M₂ := { e.conj with map_lie' := fun f g => show e.conj ⁅f, g⁆ = ⁅e.conj f, e.conj g⁆ by simp only [LieRing.of_associative_ring_bracket, LinearMap.mul_eq_comp, e.conj_comp, LinearEquiv.map_sub] } #align linear_equiv.lie_conj LinearEquiv.lieConj @[simp] theorem lieConj_apply (f : Module.End R M₁) : e.lieConj f = e.conj f := rfl #align linear_equiv.lie_conj_apply LinearEquiv.lieConj_apply @[simp] theorem lieConj_symm : e.lieConj.symm = e.symm.lieConj := rfl #align linear_equiv.lie_conj_symm LinearEquiv.lieConj_symm end LinearEquiv namespace AlgEquiv variable {R : Type u} {A₁ : Type v} {A₂ : Type w} variable [CommRing R] [Ring A₁] [Ring A₂] [Algebra R A₁] [Algebra R A₂] variable (e : A₁ ≃ₐ[R] A₂) /-- An equivalence of associative algebras is an equivalence of associated Lie algebras. -/ def toLieEquiv : A₁ ≃ₗ⁅R⁆ A₂ := { e.toLinearEquiv with toFun := e.toFun map_lie' := fun x y => by simp [LieRing.of_associative_ring_bracket] } #align alg_equiv.to_lie_equiv AlgEquiv.toLieEquiv @[simp] theorem toLieEquiv_apply (x : A₁) : e.toLieEquiv x = e x := rfl #align alg_equiv.to_lie_equiv_apply AlgEquiv.toLieEquiv_apply @[simp] theorem toLieEquiv_symm_apply (x : A₂) : e.toLieEquiv.symm x = e.symm x := rfl #align alg_equiv.to_lie_equiv_symm_apply AlgEquiv.toLieEquiv_symm_apply end AlgEquiv
-- Andreas, 2017-07-11, issue #2637, reported by nad. -- -- This error was triggered by a meta m in a constraint UnBlock m -- which is solved to infinity by the size solver. -- The constraint printer did not expect such a situation -- and crashed when printing the UnBlock constraint. {-# OPTIONS --allow-unsolved-metas #-} module _ (Z : Set) where open import Common.Size open import Common.Product postulate map : (A B C : Set) → (A → C) → A × B → C × B I : Set P : I → Set Q : Size → I → Set f : I → I lemma₁ : (R : I → Set) → (∀ x → R (f x) → R x) → ∀ x → R x → R (f x) lemma₂ : ∀ i x → Q i (f x) → Q i x works : ∀ i x → Q i (f x) × P x → Q i (f (f x)) × P x works i x = map (Q i (f x)) (P x) (Q i (f (f x))) (lemma₁ (Q i) (λ y → lemma₂ i y) (f x)) -- Replacing any underscore by its solution or parts of its solution -- makes the internal error disappear. lemma₃ : ∀ i x → Q i (f x) × P x → Q i (f (f x)) × P x lemma₃ i x = map (Q _ _) (P x) (Q _ (f (f x))) (lemma₁ _ (λ y → lemma₂ _ _) _)
Formal statement is: lemma diameter_singleton [simp]: "diameter{x} = 0" Informal statement is: The diameter of a singleton set is zero.
### A Pluto.jl notebook ### # v0.12.16 using Markdown using InteractiveUtils # ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328 using Pkg, DrWatson # ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed begin @quickactivate "StatisticsWithJuliaPlutoNotebooks" using Random, Distributions, Plots, LaTeXStrings Random.seed!(0) end # ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5 md"## Listing5.09" # ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426 begin actualAlpha, actualLambda = 2,3 gammaDist = Gamma(actualAlpha,1/actualLambda) n = 10^2 sample = rand(gammaDist, n) end # ╔═╡ 68b12c46-3a9c-11eb-03b3-bf9862c5371c begin alphaGrid = 1:0.02:3 lambdaGrid = 2:0.02:5 end # ╔═╡ 68b16da0-3a9c-11eb-21e2-53c689f1599c likelihood = [prod([pdf.(Gamma(a,1/l),v) for v in sample]) for l in lambdaGrid, a in alphaGrid] # ╔═╡ 68b1f8ce-3a9c-11eb-2ad9-a5af4bd66c0e surface(alphaGrid, lambdaGrid, likelihood, lw=0.1, c=cgrad([:blue, :red]), legend=:none, camera = (135,20), xlabel=L"\alpha", ylabel=L"\lambda", zlabel="Likelihood") # ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12 md"## End of listing5.09" # ╔═╡ Cell order: # ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5 # ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328 # ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed # ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426 # ╠═68b12c46-3a9c-11eb-03b3-bf9862c5371c # ╠═68b16da0-3a9c-11eb-21e2-53c689f1599c # ╠═68b1f8ce-3a9c-11eb-2ad9-a5af4bd66c0e # ╟─475ff888-22e6-11eb-2354-09f8f40a8e12
#' f_newton #' #' The newton algorithm to minimize the criteria #' #' @param v_y vector of y #' @param v_x vector of x #' @param v_k0 vector of internal knots for covariates #' @param v_m vector of orders for covariates #' #' @param init initialization for $\beta$ #' @param alpha threshold $\alpha$, within $(0, 0.5)$. #' @param bet shrinkage rate $\bet$, within $(0, 1)$. #' @param v_smooth vector of smoothing parameters #' @param maxit maximum number of iterations #' @param thresh stopping critria threshhold #' @param trace indicator whether to plot trace #' #' @import MASS #' #' @return the estimated $\beta$ #' f_newton <- function(v_y, v_x, v_k0, v_m, init, alpha = 0.2, bet = 0.1, v_smooth = rep(1, 3), maxit = 1e4, thresh = 1e-3, trace = NULL) { #------------------------------------------------------- ##### set up ##### #------------------------------------------------------- function_call <- match.call() x_ord <- order(v_x) v_x <- v_x[x_ord] v_y <- v_y[x_ord] iter <- 0L #Define dimensions k1 <- v_k0[1]; k2 <- v_k0[2]; m1 <- v_m[1]; m2 <- v_m[2] #Require m_n1 <- f_n1(v_x, k1, m1) m_g1 <- f_g1(k2, m2) m_g2 <- f_g2(k2, m2) m_sigmatau <- f_sigmatau(k2 + m2) m_sigma <- f_sigma(k1 + m1, k2 + m2) m_s <- f_mats(k1 + m1, k2 + m2, v_smooth) n_m2 <- rep(0, k2 + m2); n_m2[k2 + m2] <- 1 #Precalculate m_h1 <- f_h1(m_n1, m_g1, m_g2, m_sigmatau, n_m2) #Initialization if (is.null(init)) { init <- f_init(v_y, v_x, m_sigma, m_n1, v_k0, v_m, m_s) } til_beta <- init v_beta <- og_beta(til_beta, k1 + m1, k2 + m2) #Calculate H2 v_taustar <- f_tausearch(v_y, m_n1, til_beta, m_sigma, k2, m2) m_ntau <- f_ntau(v_taustar, k2, m2) m_h2 <- f_h2(m_n1, m_ntau, m_g1, m_sigmatau) #Loss s_loss <- f_loss(v_beta, til_beta, v_taustar, v_y, m_sigma, m_h1, m_h2, m_s) ##trace if (!is.null(trace)) { plot(v_x, v_y, type = "p", pch = 16, cex = 0.8, col = "grey", xlim = grDevices::extendrange(v_x, f = .5), ylim = grDevices::extendrange(v_y, f = .5), xlab = "", ylab = "", sub = paste("Iter:", iter, ", Error=", round(Inf, 3)) ) for (i in seq_along(trace)) { v_med <- f_qscop(trace[i], m_n1, til_beta, m_sigma, k2, m2) lines(v_x, v_med, col = i + 1) } } #Repeat while (maxit > iter) { iter <- iter + 1 #Calculate gradient v_deriv <- f_lossderiv(til_beta, v_k0 + v_m, m_sigma, m_h1, m_h2) v_grad <- f_grad(v_beta, v_deriv, m_s) #Calculate Hessian m_hess <- f_hess(v_deriv, v_k0 + v_m, m_s) ##Loss t <- 1 #Line search step_size <- c(MASS::ginv(m_hess) %*% v_grad) grad_size <- alpha * crossprod(v_grad, step_size) repeat{ new_beta <- v_beta - t * step_size new_tilbeta <- tilde_beta(new_beta, k1 + m1, k2 + m2) new_loss <- f_loss(new_beta, new_tilbeta, v_taustar, v_y, m_sigma, m_h1, m_h2, m_s) t <- bet * t if (new_loss <= (s_loss - t * grad_size)) { break } } #Update v_beta v_beta <- new_beta til_beta <- new_tilbeta #Update H2 (most time consuming) #ptm <- proc.time()# Start the clock! v_taustar <- f_tausearch(v_y, m_n1, til_beta, m_sigma, k2, m2) #print(proc.time() - ptm)# Stop the clock m_ntau <- f_ntau(v_taustar, k2, m2) m_h2 <- f_h2(m_n1, m_ntau, m_g1, m_sigmatau) ##trace if (!is.null(trace)) { plot(v_x, v_y, type = "p", pch = 16, cex = 0.8, col = "grey", xlim = grDevices::extendrange(v_x, f = .5), ylim = grDevices::extendrange(v_y, f = .5), xlab = "", ylab = "", sub = paste("Iter:", iter, "Error=", round(s_loss, 3)) ) for (i in seq_along(trace)) { v_med <- f_qscop(trace[i], m_n1, til_beta, m_sigma, k2, m2) lines(v_x, v_med, col = i + 1) } } #Check stop criterion converge <- (abs(new_loss - s_loss) <= thresh * s_loss) s_loss <- new_loss if (converge) break } #------------------------------------------------------- ##### Output ##### #------------------------------------------------------- out <- list( beta = v_beta, til_beta = til_beta, converge = converge, iter = iter, loss = s_loss, tau = v_taustar, x = v_x, y = v_y, n1 = m_n1, m_sigma = m_sigma, mat_s = m_s, call = function_call) return(out) }
module GRIN.Opts.NormaliseBind import GRIN.AST import GRIN.GrinM mutual normaliseExp : Exp name -> Exp name normaliseExp (SimpleExp (Do e)) = normaliseExp e normaliseExp e@(SimpleExp _) = e normaliseExp (Bind val (Do e) rest) = bind val e (normaliseExp rest) normaliseExp (Bind val e rest) = Bind val e $ normaliseExp rest normaliseExp (Case val alts) = Case val $ mapExpAlt normaliseExp <$> alts bind : Val name -> Exp name -> Exp name -> Exp name bind v0 e0 = case normaliseExp e0 of SimpleExp e1 => Bind v0 e1 Bind v1 (Do e1) rest => bind v1 e1 . bind v0 rest Bind v1 e1 rest => Bind v1 e1 . bind v0 rest Case v1 alts => Bind v0 (mkDo $ Case v1 $ mapExpAlt normaliseExp <$> alts) export normaliseBind : Monad m => GrinT name m () normaliseBind = mapProg $ mapExpProg normaliseExp
import discord import pandas as pd import numpy as np from dotenv import load_dotenv import os from yahoo_finance_async import OHLC, Interval, History, api import atexit print(os.getcwd()) print(os.listdir()) os.chdir('./bot') print(os.getcwd()) print(os.listdir()) tokenFile = open('token.txt', 'r') TOKEN = tokenFile.read() #load_dotenv() #TOKEN = os.getenv('DISCORD_TOKEN') bot = commands.Bot(command_prefix='$') client = discord.Client() @bot.event async def on_ready(): print('Beep Boop Bot Is On...'.format(client)) @bot.command() async def stonks(ctx, ticker): if ctx.author.bot: return #sends message saying it will take time so peopel don't get angery, also to tell user that bot has been called noticeEmbed = discord.Embed(title='Getting Stonks', description='this may take some time') sentMessage = await ctx.send(embed=noticeEmbed) try: #gets the ticker data using yahoo_finance_async, data is the overview of the last trading day result = await OHLC.fetch(ticker,interval=Interval.DAY,history=History.DAY) #gets the current price for a share price = result['meta']['regularMarketPrice'] #formats the message into an embed stonkInfoEmbed = discord.Embed(title='Today\'s Data for {stock}'.format(stock=ticker),color=0xf812ec) stonkInfoEmbed.add_field(name='Current Price:',value='{pps:.3f}'.format(pps=price),inline=False) stonkInfoEmbed.add_field(name='Today\'s High:',value='{high:.3f}'.format(high=result['candles'][0]['high']),inline=False) stonkInfoEmbed.add_field(name='Today\'s Low:',value='{low:.3f}'.format(low=result['candles'][0]['low']),inline=False) #sends the message to discord await sentMessage.edit(embed=stonkInfoEmbed) except api.APIError: errorEmbed = discord.Embed(title='ERROR: NSS',description='NO SUCH STOCK',color=0xf812ec) await sentMessage.edit(embed=errorEmbed) @bot.command() async def sar(ctx): if ctx.author.bot: return await ctx.send('Sarukei Is Not Cool') @bot.command() async def kill(ctx): if ctx.author.id == 200802901944303616: await ctx.send('I am kill') await cleanup() quit() async def cleanup(): print ('committing seppuku') await bot.logout() atexit.register(cleanup) bot.run(TOKEN)
function hs = plotGaussEllipses( mus, Cs, rad ) % Plots 2D ellipses derived from 2D Gaussians specified by mus & Cs. % % USAGE % hs = plotGaussEllipses( mus, Cs, [rad] ) % % INPUTS % mus - k x 2 matrix of means % Cs - 2 x 2 x k covariance matricies % rad - [2] Number of std to create the ellipse to % % OUTPUTS % hs - handles to ellipses % % EXAMPLE % plotGaussEllipses( [ 10 10; 10 10 ], cat(3,eye(2),eye(2)*2) ); % % See also PLOTELLIPSE, GAUSS2ELLIPSE % % Piotr's Computer Vision Matlab Toolbox Version 2.0 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] if (nargin<3 || isempty(rad) ); rad=2; end colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']; nc = length(colors); washeld = ishold; if (~washeld); hold('on'); end hs = zeros( size(mus,1),1 ); for i=1:size( mus,1) [ cRow, ccol, ra, rb, phi ] = gauss2ellipse( mus(i,:), Cs(:,:,i), rad ); hs(i)=plotEllipse( cRow, ccol, ra, rb, phi, colors( mod(i-1,nc)+1) ); end if (~washeld); hold('off'); end
------------------------------------------------------------------------ -- The Agda standard library -- -- This module is DEPRECATED. Please use -- Data.List.Relation.Binary.Permutation.Propositional.Properties -- directly. ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} module Data.List.Relation.Binary.Permutation.Inductive.Properties where {-# WARNING_ON_IMPORT "Data.List.Relation.Binary.Permutation.Inductive.Properties was deprecated in v1.1. Use Data.List.Relation.Binary.Permutation.Propositional.Properties instead." #-} open import Data.List.Relation.Binary.Permutation.Propositional.Properties public
How should employees give notice when they are sick? › Blog Articles › How should employees give notice when they are sick? it makes sense for the policy to require the employee taking leave to have to speak to a person in management. Such a requirement generally is not unreasonable and will not prevent an employee whom is genuinely unfit for work, or required to provide care or support to a member of his or her immediate family or household, from making such contact and providing notice. What constitutes a family emergency when giving employees’ carer’s leave?
[GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ p₁ : Path x₀ x₁ F : Homotopy p₀ p₁ t : ↑I ⊢ ContinuousMap.toFun (ContinuousMap.mk ↑(↑(ContinuousMap.Homotopy.curry F.toHomotopy) t)) 0 = x₀ [PROOFSTEP] simp [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ p₁ : Path x₀ x₁ F : Homotopy p₀ p₁ t : ↑I ⊢ ContinuousMap.toFun (ContinuousMap.mk ↑(↑(ContinuousMap.Homotopy.curry F.toHomotopy) t)) 1 = x₁ [PROOFSTEP] simp [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ p₁ : Path x₀ x₁ F : Homotopy p₀ p₁ ⊢ eval F 0 = p₀ [PROOFSTEP] ext t [GOAL] case a.h X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ p₁ : Path x₀ x₁ F : Homotopy p₀ p₁ t : ↑I ⊢ ↑(eval F 0) t = ↑p₀ t [PROOFSTEP] simp [eval] [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ p₁ : Path x₀ x₁ F : Homotopy p₀ p₁ ⊢ eval F 1 = p₁ [PROOFSTEP] ext t [GOAL] case a.h X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ p₁ : Path x₀ x₁ F : Homotopy p₀ p₁ t : ↑I ⊢ ↑(eval F 1) t = ↑p₁ t [PROOFSTEP] simp [eval] [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ ⊢ Continuous fun x => (x.fst, Set.projIcc 0 1 extend.proof_1 (2 * ↑x.snd)) [PROOFSTEP] continuity [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ ⊢ Continuous fun x => (x.fst, Set.projIcc 0 1 extend.proof_1 (2 * ↑x.snd - 1)) [PROOFSTEP] continuity [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ x : ↑I × ↑I hx : ↑x.snd = 1 / 2 ⊢ extend (eval F x.fst) (2 * ↑x.snd) = extend (eval G x.fst) (2 * ↑x.snd - 1) [PROOFSTEP] rw [hx] [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ x : ↑I × ↑I hx : ↑x.snd = 1 / 2 ⊢ extend (eval F x.fst) (2 * (1 / 2)) = extend (eval G x.fst) (2 * (1 / 2) - 1) [PROOFSTEP] norm_num [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ x : ↑I ⊢ ContinuousMap.toFun (ContinuousMap.mk fun x => if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1)) (0, x) = ↑(Path.trans p₀ p₁).toContinuousMap x [PROOFSTEP] simp [Path.trans] [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ x : ↑I ⊢ ContinuousMap.toFun (ContinuousMap.mk fun x => if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1)) (1, x) = ↑(Path.trans q₀ q₁).toContinuousMap x [PROOFSTEP] simp [Path.trans] [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ x t : ↑I ht : t ∈ {0, 1} ⊢ ↑(ContinuousMap.mk fun x_1 => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1), map_zero_left := (_ : ∀ (x : ↑I), (if ↑(0, x).snd ≤ 1 / 2 then extend (eval F (0, x).fst) (2 * ↑(0, x).snd) else extend (eval G (0, x).fst) (2 * ↑(0, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend p₀ (2 * t) else extend p₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x), map_one_left := (_ : ∀ (x : ↑I), (if ↑(1, x).snd ≤ 1 / 2 then extend (eval F (1, x).fst) (2 * ↑(1, x).snd) else extend (eval G (1, x).fst) (2 * ↑(1, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend q₀ (2 * t) else extend q₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x) }.toContinuousMap (x, x_1)) t = ↑(Path.trans p₀ p₁).toContinuousMap t ∧ ↑(ContinuousMap.mk fun x_1 => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1), map_zero_left := (_ : ∀ (x : ↑I), (if ↑(0, x).snd ≤ 1 / 2 then extend (eval F (0, x).fst) (2 * ↑(0, x).snd) else extend (eval G (0, x).fst) (2 * ↑(0, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend p₀ (2 * t) else extend p₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x), map_one_left := (_ : ∀ (x : ↑I), (if ↑(1, x).snd ≤ 1 / 2 then extend (eval F (1, x).fst) (2 * ↑(1, x).snd) else extend (eval G (1, x).fst) (2 * ↑(1, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend q₀ (2 * t) else extend q₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x) }.toContinuousMap (x, x_1)) t = ↑(Path.trans q₀ q₁).toContinuousMap t [PROOFSTEP] cases' ht with ht ht [GOAL] case inl X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ x t : ↑I ht : t = 0 ⊢ ↑(ContinuousMap.mk fun x_1 => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1), map_zero_left := (_ : ∀ (x : ↑I), (if ↑(0, x).snd ≤ 1 / 2 then extend (eval F (0, x).fst) (2 * ↑(0, x).snd) else extend (eval G (0, x).fst) (2 * ↑(0, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend p₀ (2 * t) else extend p₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x), map_one_left := (_ : ∀ (x : ↑I), (if ↑(1, x).snd ≤ 1 / 2 then extend (eval F (1, x).fst) (2 * ↑(1, x).snd) else extend (eval G (1, x).fst) (2 * ↑(1, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend q₀ (2 * t) else extend q₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x) }.toContinuousMap (x, x_1)) t = ↑(Path.trans p₀ p₁).toContinuousMap t ∧ ↑(ContinuousMap.mk fun x_1 => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1), map_zero_left := (_ : ∀ (x : ↑I), (if ↑(0, x).snd ≤ 1 / 2 then extend (eval F (0, x).fst) (2 * ↑(0, x).snd) else extend (eval G (0, x).fst) (2 * ↑(0, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend p₀ (2 * t) else extend p₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x), map_one_left := (_ : ∀ (x : ↑I), (if ↑(1, x).snd ≤ 1 / 2 then extend (eval F (1, x).fst) (2 * ↑(1, x).snd) else extend (eval G (1, x).fst) (2 * ↑(1, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend q₀ (2 * t) else extend q₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x) }.toContinuousMap (x, x_1)) t = ↑(Path.trans q₀ q₁).toContinuousMap t [PROOFSTEP] rw [ht] [GOAL] case inl X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ x t : ↑I ht : t = 0 ⊢ ↑(ContinuousMap.mk fun x_1 => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1), map_zero_left := (_ : ∀ (x : ↑I), (if ↑(0, x).snd ≤ 1 / 2 then extend (eval F (0, x).fst) (2 * ↑(0, x).snd) else extend (eval G (0, x).fst) (2 * ↑(0, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend p₀ (2 * t) else extend p₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x), map_one_left := (_ : ∀ (x : ↑I), (if ↑(1, x).snd ≤ 1 / 2 then extend (eval F (1, x).fst) (2 * ↑(1, x).snd) else extend (eval G (1, x).fst) (2 * ↑(1, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend q₀ (2 * t) else extend q₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x) }.toContinuousMap (x, x_1)) 0 = ↑(Path.trans p₀ p₁).toContinuousMap 0 ∧ ↑(ContinuousMap.mk fun x_1 => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1), map_zero_left := (_ : ∀ (x : ↑I), (if ↑(0, x).snd ≤ 1 / 2 then extend (eval F (0, x).fst) (2 * ↑(0, x).snd) else extend (eval G (0, x).fst) (2 * ↑(0, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend p₀ (2 * t) else extend p₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x), map_one_left := (_ : ∀ (x : ↑I), (if ↑(1, x).snd ≤ 1 / 2 then extend (eval F (1, x).fst) (2 * ↑(1, x).snd) else extend (eval G (1, x).fst) (2 * ↑(1, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend q₀ (2 * t) else extend q₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x) }.toContinuousMap (x, x_1)) 0 = ↑(Path.trans q₀ q₁).toContinuousMap 0 [PROOFSTEP] norm_num [GOAL] case inr X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ x t : ↑I ht : t ∈ {1} ⊢ ↑(ContinuousMap.mk fun x_1 => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1), map_zero_left := (_ : ∀ (x : ↑I), (if ↑(0, x).snd ≤ 1 / 2 then extend (eval F (0, x).fst) (2 * ↑(0, x).snd) else extend (eval G (0, x).fst) (2 * ↑(0, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend p₀ (2 * t) else extend p₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x), map_one_left := (_ : ∀ (x : ↑I), (if ↑(1, x).snd ≤ 1 / 2 then extend (eval F (1, x).fst) (2 * ↑(1, x).snd) else extend (eval G (1, x).fst) (2 * ↑(1, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend q₀ (2 * t) else extend q₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x) }.toContinuousMap (x, x_1)) t = ↑(Path.trans p₀ p₁).toContinuousMap t ∧ ↑(ContinuousMap.mk fun x_1 => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1), map_zero_left := (_ : ∀ (x : ↑I), (if ↑(0, x).snd ≤ 1 / 2 then extend (eval F (0, x).fst) (2 * ↑(0, x).snd) else extend (eval G (0, x).fst) (2 * ↑(0, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend p₀ (2 * t) else extend p₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x), map_one_left := (_ : ∀ (x : ↑I), (if ↑(1, x).snd ≤ 1 / 2 then extend (eval F (1, x).fst) (2 * ↑(1, x).snd) else extend (eval G (1, x).fst) (2 * ↑(1, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend q₀ (2 * t) else extend q₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x) }.toContinuousMap (x, x_1)) t = ↑(Path.trans q₀ q₁).toContinuousMap t [PROOFSTEP] rw [Set.mem_singleton_iff] at ht [GOAL] case inr X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ x t : ↑I ht : t = 1 ⊢ ↑(ContinuousMap.mk fun x_1 => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1), map_zero_left := (_ : ∀ (x : ↑I), (if ↑(0, x).snd ≤ 1 / 2 then extend (eval F (0, x).fst) (2 * ↑(0, x).snd) else extend (eval G (0, x).fst) (2 * ↑(0, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend p₀ (2 * t) else extend p₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x), map_one_left := (_ : ∀ (x : ↑I), (if ↑(1, x).snd ≤ 1 / 2 then extend (eval F (1, x).fst) (2 * ↑(1, x).snd) else extend (eval G (1, x).fst) (2 * ↑(1, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend q₀ (2 * t) else extend q₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x) }.toContinuousMap (x, x_1)) t = ↑(Path.trans p₀ p₁).toContinuousMap t ∧ ↑(ContinuousMap.mk fun x_1 => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1), map_zero_left := (_ : ∀ (x : ↑I), (if ↑(0, x).snd ≤ 1 / 2 then extend (eval F (0, x).fst) (2 * ↑(0, x).snd) else extend (eval G (0, x).fst) (2 * ↑(0, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend p₀ (2 * t) else extend p₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x), map_one_left := (_ : ∀ (x : ↑I), (if ↑(1, x).snd ≤ 1 / 2 then extend (eval F (1, x).fst) (2 * ↑(1, x).snd) else extend (eval G (1, x).fst) (2 * ↑(1, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend q₀ (2 * t) else extend q₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x) }.toContinuousMap (x, x_1)) t = ↑(Path.trans q₀ q₁).toContinuousMap t [PROOFSTEP] rw [ht] [GOAL] case inr X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ x t : ↑I ht : t = 1 ⊢ ↑(ContinuousMap.mk fun x_1 => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1), map_zero_left := (_ : ∀ (x : ↑I), (if ↑(0, x).snd ≤ 1 / 2 then extend (eval F (0, x).fst) (2 * ↑(0, x).snd) else extend (eval G (0, x).fst) (2 * ↑(0, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend p₀ (2 * t) else extend p₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x), map_one_left := (_ : ∀ (x : ↑I), (if ↑(1, x).snd ≤ 1 / 2 then extend (eval F (1, x).fst) (2 * ↑(1, x).snd) else extend (eval G (1, x).fst) (2 * ↑(1, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend q₀ (2 * t) else extend q₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x) }.toContinuousMap (x, x_1)) 1 = ↑(Path.trans p₀ p₁).toContinuousMap 1 ∧ ↑(ContinuousMap.mk fun x_1 => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1), map_zero_left := (_ : ∀ (x : ↑I), (if ↑(0, x).snd ≤ 1 / 2 then extend (eval F (0, x).fst) (2 * ↑(0, x).snd) else extend (eval G (0, x).fst) (2 * ↑(0, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend p₀ (2 * t) else extend p₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend p₀ (2 * x) else extend p₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x), map_one_left := (_ : ∀ (x : ↑I), (if ↑(1, x).snd ≤ 1 / 2 then extend (eval F (1, x).fst) (2 * ↑(1, x).snd) else extend (eval G (1, x).fst) (2 * ↑(1, x).snd - 1)) = ↑{ toContinuousMap := ContinuousMap.mk ((fun t => if t ≤ 1 / 2 then extend q₀ (2 * t) else extend q₁ (2 * t - 1)) ∘ Subtype.val), source' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 0 = x₀), target' := (_ : ((fun x => if x ≤ 1 / 2 then extend q₀ (2 * x) else extend q₁ (2 * x - 1)) ∘ Subtype.val) 1 = x₂) }.toContinuousMap x) }.toContinuousMap (x, x_1)) 1 = ↑(Path.trans q₀ q₁).toContinuousMap 1 [PROOFSTEP] norm_num [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ x : ↑I × ↑I ⊢ (if ↑x.snd ≤ 1 / 2 then extend (eval F x.fst) (2 * ↑x.snd) else extend (eval G x.fst) (2 * ↑x.snd - 1)) = if h : ↑x.snd ≤ 1 / 2 then ↑(eval F x.fst) { val := 2 * ↑x.snd, property := (_ : 2 * ↑x.snd ∈ I) } else ↑(eval G x.fst) { val := 2 * ↑x.snd - 1, property := (_ : 2 * ↑x.snd - 1 ∈ I) } [PROOFSTEP] split_ifs [GOAL] case pos X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ x : ↑I × ↑I h✝ : ↑x.snd ≤ 1 / 2 ⊢ extend (eval F x.fst) (2 * ↑x.snd) = ↑(eval F x.fst) { val := 2 * ↑x.snd, property := (_ : 2 * ↑x.snd ∈ I) } [PROOFSTEP] exact Path.extend_extends _ _ [GOAL] case neg X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ x : ↑I × ↑I h✝ : ¬↑x.snd ≤ 1 / 2 ⊢ extend (eval G x.fst) (2 * ↑x.snd - 1) = ↑(eval G x.fst) { val := 2 * ↑x.snd - 1, property := (_ : 2 * ↑x.snd - 1 ∈ I) } [PROOFSTEP] exact Path.extend_extends _ _ [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ t : ↑I ⊢ 0 ≤ 1 / 2 [PROOFSTEP] norm_num [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ t : ↑I ⊢ 1 / 2 ≤ 1 [PROOFSTEP] norm_num [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₀ q₀ : Path x₀ x₁ p₁ q₁ : Path x₁ x₂ F : Homotopy p₀ q₀ G : Homotopy p₁ q₁ t : ↑I ⊢ (if ↑(t, { val := 1 / 2, property := (_ : 0 ≤ 1 / 2 ∧ 1 / 2 ≤ 1) }).snd ≤ 1 / 2 then extend (eval F (t, { val := 1 / 2, property := (_ : 0 ≤ 1 / 2 ∧ 1 / 2 ≤ 1) }).fst) (2 * ↑(t, { val := 1 / 2, property := (_ : 0 ≤ 1 / 2 ∧ 1 / 2 ≤ 1) }).snd) else extend (eval G (t, { val := 1 / 2, property := (_ : 0 ≤ 1 / 2 ∧ 1 / 2 ≤ 1) }).fst) (2 * ↑(t, { val := 1 / 2, property := (_ : 0 ≤ 1 / 2 ∧ 1 / 2 ≤ 1) }).snd - 1)) = x₁ [PROOFSTEP] norm_num [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 x : ↑I × ↑I ⊢ 0 ≤ ↑(σ x.fst) [PROOFSTEP] unit_interval [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 x : ↑I × ↑I ⊢ 0 ≤ ↑x.fst [PROOFSTEP] unit_interval [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 x : ↑I × ↑I ⊢ ↑(σ x.fst) + ↑x.fst = 1 [PROOFSTEP] simp [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 ⊢ Continuous fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) } [PROOFSTEP] refine continuous_const.path_eval ?_ [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 ⊢ Continuous fun x => { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) } [PROOFSTEP] apply Continuous.subtype_mk [GOAL] case h X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 ⊢ Continuous fun x => ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd) [PROOFSTEP] apply Continuous.add [GOAL] case h.hf X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 ⊢ Continuous fun x => ↑(σ x.fst) * ↑x.snd [PROOFSTEP] apply Continuous.mul [GOAL] case h.hg X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 ⊢ Continuous fun x => ↑x.fst * ↑(f x.snd) [PROOFSTEP] apply Continuous.mul [GOAL] case h.hf.hf X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 ⊢ Continuous fun x => ↑(σ x.fst) [PROOFSTEP] exact continuous_induced_dom.comp (unitInterval.continuous_symm.comp continuous_fst) [GOAL] case h.hf.hg X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 ⊢ Continuous fun x => ↑x.snd [PROOFSTEP] continuity [GOAL] case h.hg.hf X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 ⊢ Continuous fun x => ↑x.fst [PROOFSTEP] continuity [GOAL] case h.hg.hg X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 ⊢ Continuous fun x => ↑(f x.snd) [PROOFSTEP] continuity [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 x : ↑I ⊢ ContinuousMap.toFun (ContinuousMap.mk fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) }) (0, x) = ↑p.toContinuousMap x [PROOFSTEP] norm_num [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 x : ↑I ⊢ ContinuousMap.toFun (ContinuousMap.mk fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) }) (1, x) = ↑(Path.reparam p f hf hf₀ hf₁).toContinuousMap x [PROOFSTEP] norm_num [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 t x : ↑I hx : x ∈ {0, 1} ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) }, map_zero_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (0, x).fst) * ↑(0, x).snd + ↑(0, x).fst * ↑(f (0, x).snd), property := (_ : ↑(σ (0, x).fst) • ↑(0, x).snd + ↑(0, x).fst • ↑(f (0, x).snd) ∈ I) } = ↑p x), map_one_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (1, x).fst) * ↑(1, x).snd + ↑(1, x).fst * ↑(f (1, x).snd), property := (_ : ↑(σ (1, x).fst) • ↑(1, x).snd + ↑(1, x).fst • ↑(f (1, x).snd) ∈ I) } = ↑p (f x)) }.toContinuousMap (t, x)) x = ↑p.toContinuousMap x ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) }, map_zero_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (0, x).fst) * ↑(0, x).snd + ↑(0, x).fst * ↑(f (0, x).snd), property := (_ : ↑(σ (0, x).fst) • ↑(0, x).snd + ↑(0, x).fst • ↑(f (0, x).snd) ∈ I) } = ↑p x), map_one_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (1, x).fst) * ↑(1, x).snd + ↑(1, x).fst * ↑(f (1, x).snd), property := (_ : ↑(σ (1, x).fst) • ↑(1, x).snd + ↑(1, x).fst • ↑(f (1, x).snd) ∈ I) } = ↑p (f x)) }.toContinuousMap (t, x)) x = ↑(Path.reparam p f hf hf₀ hf₁).toContinuousMap x [PROOFSTEP] cases' hx with hx hx [GOAL] case inl X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 t x : ↑I hx : x = 0 ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) }, map_zero_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (0, x).fst) * ↑(0, x).snd + ↑(0, x).fst * ↑(f (0, x).snd), property := (_ : ↑(σ (0, x).fst) • ↑(0, x).snd + ↑(0, x).fst • ↑(f (0, x).snd) ∈ I) } = ↑p x), map_one_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (1, x).fst) * ↑(1, x).snd + ↑(1, x).fst * ↑(f (1, x).snd), property := (_ : ↑(σ (1, x).fst) • ↑(1, x).snd + ↑(1, x).fst • ↑(f (1, x).snd) ∈ I) } = ↑p (f x)) }.toContinuousMap (t, x)) x = ↑p.toContinuousMap x ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) }, map_zero_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (0, x).fst) * ↑(0, x).snd + ↑(0, x).fst * ↑(f (0, x).snd), property := (_ : ↑(σ (0, x).fst) • ↑(0, x).snd + ↑(0, x).fst • ↑(f (0, x).snd) ∈ I) } = ↑p x), map_one_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (1, x).fst) * ↑(1, x).snd + ↑(1, x).fst * ↑(f (1, x).snd), property := (_ : ↑(σ (1, x).fst) • ↑(1, x).snd + ↑(1, x).fst • ↑(f (1, x).snd) ∈ I) } = ↑p (f x)) }.toContinuousMap (t, x)) x = ↑(Path.reparam p f hf hf₀ hf₁).toContinuousMap x [PROOFSTEP] rw [hx] [GOAL] case inl X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 t x : ↑I hx : x = 0 ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) }, map_zero_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (0, x).fst) * ↑(0, x).snd + ↑(0, x).fst * ↑(f (0, x).snd), property := (_ : ↑(σ (0, x).fst) • ↑(0, x).snd + ↑(0, x).fst • ↑(f (0, x).snd) ∈ I) } = ↑p x), map_one_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (1, x).fst) * ↑(1, x).snd + ↑(1, x).fst * ↑(f (1, x).snd), property := (_ : ↑(σ (1, x).fst) • ↑(1, x).snd + ↑(1, x).fst • ↑(f (1, x).snd) ∈ I) } = ↑p (f x)) }.toContinuousMap (t, x)) 0 = ↑p.toContinuousMap 0 ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) }, map_zero_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (0, x).fst) * ↑(0, x).snd + ↑(0, x).fst * ↑(f (0, x).snd), property := (_ : ↑(σ (0, x).fst) • ↑(0, x).snd + ↑(0, x).fst • ↑(f (0, x).snd) ∈ I) } = ↑p x), map_one_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (1, x).fst) * ↑(1, x).snd + ↑(1, x).fst * ↑(f (1, x).snd), property := (_ : ↑(σ (1, x).fst) • ↑(1, x).snd + ↑(1, x).fst • ↑(f (1, x).snd) ∈ I) } = ↑p (f x)) }.toContinuousMap (t, x)) 0 = ↑(Path.reparam p f hf hf₀ hf₁).toContinuousMap 0 [PROOFSTEP] simp [hf₀] -- Porting note: Originally `norm_num [hf₀]` [GOAL] case inr X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 t x : ↑I hx : x ∈ {1} ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) }, map_zero_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (0, x).fst) * ↑(0, x).snd + ↑(0, x).fst * ↑(f (0, x).snd), property := (_ : ↑(σ (0, x).fst) • ↑(0, x).snd + ↑(0, x).fst • ↑(f (0, x).snd) ∈ I) } = ↑p x), map_one_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (1, x).fst) * ↑(1, x).snd + ↑(1, x).fst * ↑(f (1, x).snd), property := (_ : ↑(σ (1, x).fst) • ↑(1, x).snd + ↑(1, x).fst • ↑(f (1, x).snd) ∈ I) } = ↑p (f x)) }.toContinuousMap (t, x)) x = ↑p.toContinuousMap x ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) }, map_zero_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (0, x).fst) * ↑(0, x).snd + ↑(0, x).fst * ↑(f (0, x).snd), property := (_ : ↑(σ (0, x).fst) • ↑(0, x).snd + ↑(0, x).fst • ↑(f (0, x).snd) ∈ I) } = ↑p x), map_one_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (1, x).fst) * ↑(1, x).snd + ↑(1, x).fst * ↑(f (1, x).snd), property := (_ : ↑(σ (1, x).fst) • ↑(1, x).snd + ↑(1, x).fst • ↑(f (1, x).snd) ∈ I) } = ↑p (f x)) }.toContinuousMap (t, x)) x = ↑(Path.reparam p f hf hf₀ hf₁).toContinuousMap x [PROOFSTEP] rw [Set.mem_singleton_iff] at hx [GOAL] case inr X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 t x : ↑I hx : x = 1 ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) }, map_zero_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (0, x).fst) * ↑(0, x).snd + ↑(0, x).fst * ↑(f (0, x).snd), property := (_ : ↑(σ (0, x).fst) • ↑(0, x).snd + ↑(0, x).fst • ↑(f (0, x).snd) ∈ I) } = ↑p x), map_one_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (1, x).fst) * ↑(1, x).snd + ↑(1, x).fst * ↑(f (1, x).snd), property := (_ : ↑(σ (1, x).fst) • ↑(1, x).snd + ↑(1, x).fst • ↑(f (1, x).snd) ∈ I) } = ↑p (f x)) }.toContinuousMap (t, x)) x = ↑p.toContinuousMap x ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) }, map_zero_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (0, x).fst) * ↑(0, x).snd + ↑(0, x).fst * ↑(f (0, x).snd), property := (_ : ↑(σ (0, x).fst) • ↑(0, x).snd + ↑(0, x).fst • ↑(f (0, x).snd) ∈ I) } = ↑p x), map_one_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (1, x).fst) * ↑(1, x).snd + ↑(1, x).fst * ↑(f (1, x).snd), property := (_ : ↑(σ (1, x).fst) • ↑(1, x).snd + ↑(1, x).fst • ↑(f (1, x).snd) ∈ I) } = ↑p (f x)) }.toContinuousMap (t, x)) x = ↑(Path.reparam p f hf hf₀ hf₁).toContinuousMap x [PROOFSTEP] rw [hx] [GOAL] case inr X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p : Path x₀ x₁ f : ↑I → ↑I hf : Continuous f hf₀ : f 0 = 0 hf₁ : f 1 = 1 t x : ↑I hx : x = 1 ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) }, map_zero_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (0, x).fst) * ↑(0, x).snd + ↑(0, x).fst * ↑(f (0, x).snd), property := (_ : ↑(σ (0, x).fst) • ↑(0, x).snd + ↑(0, x).fst • ↑(f (0, x).snd) ∈ I) } = ↑p x), map_one_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (1, x).fst) * ↑(1, x).snd + ↑(1, x).fst * ↑(f (1, x).snd), property := (_ : ↑(σ (1, x).fst) • ↑(1, x).snd + ↑(1, x).fst • ↑(f (1, x).snd) ∈ I) } = ↑p (f x)) }.toContinuousMap (t, x)) 1 = ↑p.toContinuousMap 1 ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑p { val := ↑(σ x.fst) * ↑x.snd + ↑x.fst * ↑(f x.snd), property := (_ : ↑(σ x.fst) • ↑x.snd + ↑x.fst • ↑(f x.snd) ∈ I) }, map_zero_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (0, x).fst) * ↑(0, x).snd + ↑(0, x).fst * ↑(f (0, x).snd), property := (_ : ↑(σ (0, x).fst) • ↑(0, x).snd + ↑(0, x).fst • ↑(f (0, x).snd) ∈ I) } = ↑p x), map_one_left := (_ : ∀ (x : ↑I), ↑p { val := ↑(σ (1, x).fst) * ↑(1, x).snd + ↑(1, x).fst * ↑(f (1, x).snd), property := (_ : ↑(σ (1, x).fst) • ↑(1, x).snd + ↑(1, x).fst • ↑(f (1, x).snd) ∈ I) } = ↑p (f x)) }.toContinuousMap (t, x)) 1 = ↑(Path.reparam p f hf hf₀ hf₁).toContinuousMap 1 [PROOFSTEP] simp [hf₁] -- Porting note: Originally `norm_num [hf₀]` [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p q : Path x₀ x₁ F : Homotopy p q ⊢ ∀ (x : ↑I), ContinuousMap.toFun (ContinuousMap.mk fun x => ↑F (x.fst, σ x.snd)) (0, x) = ↑(Path.symm p).toContinuousMap x [PROOFSTEP] simp [Path.symm] [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p q : Path x₀ x₁ F : Homotopy p q ⊢ ∀ (x : ↑I), ContinuousMap.toFun (ContinuousMap.mk fun x => ↑F (x.fst, σ x.snd)) (1, x) = ↑(Path.symm q).toContinuousMap x [PROOFSTEP] simp [Path.symm] [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p q : Path x₀ x₁ F : Homotopy p q t x : ↑I hx : x ∈ {0, 1} ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑F (x.fst, σ x.snd), map_zero_left := (_ : ∀ (a : ↑I), ↑F (0, σ a) = ↑p (σ a)), map_one_left := (_ : ∀ (a : ↑I), ↑F (1, σ a) = ↑q (σ a)) }.toContinuousMap (t, x)) x = ↑(Path.symm p).toContinuousMap x ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑F (x.fst, σ x.snd), map_zero_left := (_ : ∀ (a : ↑I), ↑F (0, σ a) = ↑p (σ a)), map_one_left := (_ : ∀ (a : ↑I), ↑F (1, σ a) = ↑q (σ a)) }.toContinuousMap (t, x)) x = ↑(Path.symm q).toContinuousMap x [PROOFSTEP] cases' hx with hx hx [GOAL] case inl X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p q : Path x₀ x₁ F : Homotopy p q t x : ↑I hx : x = 0 ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑F (x.fst, σ x.snd), map_zero_left := (_ : ∀ (a : ↑I), ↑F (0, σ a) = ↑p (σ a)), map_one_left := (_ : ∀ (a : ↑I), ↑F (1, σ a) = ↑q (σ a)) }.toContinuousMap (t, x)) x = ↑(Path.symm p).toContinuousMap x ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑F (x.fst, σ x.snd), map_zero_left := (_ : ∀ (a : ↑I), ↑F (0, σ a) = ↑p (σ a)), map_one_left := (_ : ∀ (a : ↑I), ↑F (1, σ a) = ↑q (σ a)) }.toContinuousMap (t, x)) x = ↑(Path.symm q).toContinuousMap x [PROOFSTEP] rw [hx] [GOAL] case inl X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p q : Path x₀ x₁ F : Homotopy p q t x : ↑I hx : x = 0 ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑F (x.fst, σ x.snd), map_zero_left := (_ : ∀ (a : ↑I), ↑F (0, σ a) = ↑p (σ a)), map_one_left := (_ : ∀ (a : ↑I), ↑F (1, σ a) = ↑q (σ a)) }.toContinuousMap (t, x)) 0 = ↑(Path.symm p).toContinuousMap 0 ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑F (x.fst, σ x.snd), map_zero_left := (_ : ∀ (a : ↑I), ↑F (0, σ a) = ↑p (σ a)), map_one_left := (_ : ∀ (a : ↑I), ↑F (1, σ a) = ↑q (σ a)) }.toContinuousMap (t, x)) 0 = ↑(Path.symm q).toContinuousMap 0 [PROOFSTEP] simp [GOAL] case inr X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p q : Path x₀ x₁ F : Homotopy p q t x : ↑I hx : x ∈ {1} ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑F (x.fst, σ x.snd), map_zero_left := (_ : ∀ (a : ↑I), ↑F (0, σ a) = ↑p (σ a)), map_one_left := (_ : ∀ (a : ↑I), ↑F (1, σ a) = ↑q (σ a)) }.toContinuousMap (t, x)) x = ↑(Path.symm p).toContinuousMap x ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑F (x.fst, σ x.snd), map_zero_left := (_ : ∀ (a : ↑I), ↑F (0, σ a) = ↑p (σ a)), map_one_left := (_ : ∀ (a : ↑I), ↑F (1, σ a) = ↑q (σ a)) }.toContinuousMap (t, x)) x = ↑(Path.symm q).toContinuousMap x [PROOFSTEP] rw [Set.mem_singleton_iff] at hx [GOAL] case inr X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p q : Path x₀ x₁ F : Homotopy p q t x : ↑I hx : x = 1 ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑F (x.fst, σ x.snd), map_zero_left := (_ : ∀ (a : ↑I), ↑F (0, σ a) = ↑p (σ a)), map_one_left := (_ : ∀ (a : ↑I), ↑F (1, σ a) = ↑q (σ a)) }.toContinuousMap (t, x)) x = ↑(Path.symm p).toContinuousMap x ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑F (x.fst, σ x.snd), map_zero_left := (_ : ∀ (a : ↑I), ↑F (0, σ a) = ↑p (σ a)), map_one_left := (_ : ∀ (a : ↑I), ↑F (1, σ a) = ↑q (σ a)) }.toContinuousMap (t, x)) x = ↑(Path.symm q).toContinuousMap x [PROOFSTEP] rw [hx] [GOAL] case inr X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p q : Path x₀ x₁ F : Homotopy p q t x : ↑I hx : x = 1 ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑F (x.fst, σ x.snd), map_zero_left := (_ : ∀ (a : ↑I), ↑F (0, σ a) = ↑p (σ a)), map_one_left := (_ : ∀ (a : ↑I), ↑F (1, σ a) = ↑q (σ a)) }.toContinuousMap (t, x)) 1 = ↑(Path.symm p).toContinuousMap 1 ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk fun x => ↑F (x.fst, σ x.snd), map_zero_left := (_ : ∀ (a : ↑I), ↑F (0, σ a) = ↑p (σ a)), map_one_left := (_ : ∀ (a : ↑I), ↑F (1, σ a) = ↑q (σ a)) }.toContinuousMap (t, x)) 1 = ↑(Path.symm q).toContinuousMap 1 [PROOFSTEP] simp [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p q : Path x₀ x₁ F : Homotopy p q f : C(X, Y) ⊢ ∀ (x : ↑I), ContinuousMap.toFun (ContinuousMap.mk (↑f ∘ ↑F)) (0, x) = ↑(Path.map p (_ : Continuous ↑f)).toContinuousMap x [PROOFSTEP] simp [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p q : Path x₀ x₁ F : Homotopy p q f : C(X, Y) ⊢ ∀ (x : ↑I), ContinuousMap.toFun (ContinuousMap.mk (↑f ∘ ↑F)) (1, x) = ↑(Path.map q (_ : Continuous ↑f)).toContinuousMap x [PROOFSTEP] simp [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p q : Path x₀ x₁ F : Homotopy p q f : C(X, Y) t x : ↑I hx : x ∈ {0, 1} ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk (↑f ∘ ↑F), map_zero_left := (_ : ∀ (a : ↑I), ↑f (↑F (0, a)) = ↑(Path.map p (_ : Continuous ↑f)) a), map_one_left := (_ : ∀ (a : ↑I), ↑f (↑F (1, a)) = ↑(Path.map q (_ : Continuous ↑f)) a) }.toContinuousMap (t, x)) x = ↑(Path.map p (_ : Continuous ↑f)).toContinuousMap x ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk (↑f ∘ ↑F), map_zero_left := (_ : ∀ (a : ↑I), ↑f (↑F (0, a)) = ↑(Path.map p (_ : Continuous ↑f)) a), map_one_left := (_ : ∀ (a : ↑I), ↑f (↑F (1, a)) = ↑(Path.map q (_ : Continuous ↑f)) a) }.toContinuousMap (t, x)) x = ↑(Path.map q (_ : Continuous ↑f)).toContinuousMap x [PROOFSTEP] cases' hx with hx hx [GOAL] case inl X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p q : Path x₀ x₁ F : Homotopy p q f : C(X, Y) t x : ↑I hx : x = 0 ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk (↑f ∘ ↑F), map_zero_left := (_ : ∀ (a : ↑I), ↑f (↑F (0, a)) = ↑(Path.map p (_ : Continuous ↑f)) a), map_one_left := (_ : ∀ (a : ↑I), ↑f (↑F (1, a)) = ↑(Path.map q (_ : Continuous ↑f)) a) }.toContinuousMap (t, x)) x = ↑(Path.map p (_ : Continuous ↑f)).toContinuousMap x ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk (↑f ∘ ↑F), map_zero_left := (_ : ∀ (a : ↑I), ↑f (↑F (0, a)) = ↑(Path.map p (_ : Continuous ↑f)) a), map_one_left := (_ : ∀ (a : ↑I), ↑f (↑F (1, a)) = ↑(Path.map q (_ : Continuous ↑f)) a) }.toContinuousMap (t, x)) x = ↑(Path.map q (_ : Continuous ↑f)).toContinuousMap x [PROOFSTEP] simp [hx] [GOAL] case inr X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p q : Path x₀ x₁ F : Homotopy p q f : C(X, Y) t x : ↑I hx : x ∈ {1} ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk (↑f ∘ ↑F), map_zero_left := (_ : ∀ (a : ↑I), ↑f (↑F (0, a)) = ↑(Path.map p (_ : Continuous ↑f)) a), map_one_left := (_ : ∀ (a : ↑I), ↑f (↑F (1, a)) = ↑(Path.map q (_ : Continuous ↑f)) a) }.toContinuousMap (t, x)) x = ↑(Path.map p (_ : Continuous ↑f)).toContinuousMap x ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk (↑f ∘ ↑F), map_zero_left := (_ : ∀ (a : ↑I), ↑f (↑F (0, a)) = ↑(Path.map p (_ : Continuous ↑f)) a), map_one_left := (_ : ∀ (a : ↑I), ↑f (↑F (1, a)) = ↑(Path.map q (_ : Continuous ↑f)) a) }.toContinuousMap (t, x)) x = ↑(Path.map q (_ : Continuous ↑f)).toContinuousMap x [PROOFSTEP] rw [Set.mem_singleton_iff] at hx [GOAL] case inr X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p q : Path x₀ x₁ F : Homotopy p q f : C(X, Y) t x : ↑I hx : x = 1 ⊢ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk (↑f ∘ ↑F), map_zero_left := (_ : ∀ (a : ↑I), ↑f (↑F (0, a)) = ↑(Path.map p (_ : Continuous ↑f)) a), map_one_left := (_ : ∀ (a : ↑I), ↑f (↑F (1, a)) = ↑(Path.map q (_ : Continuous ↑f)) a) }.toContinuousMap (t, x)) x = ↑(Path.map p (_ : Continuous ↑f)).toContinuousMap x ∧ ↑(ContinuousMap.mk fun x => ContinuousMap.toFun { toContinuousMap := ContinuousMap.mk (↑f ∘ ↑F), map_zero_left := (_ : ∀ (a : ↑I), ↑f (↑F (0, a)) = ↑(Path.map p (_ : Continuous ↑f)) a), map_one_left := (_ : ∀ (a : ↑I), ↑f (↑F (1, a)) = ↑(Path.map q (_ : Continuous ↑f)) a) }.toContinuousMap (t, x)) x = ↑(Path.map q (_ : Continuous ↑f)).toContinuousMap x [PROOFSTEP] simp [hx] [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₁ : Path x₀ x₁ p₂ : Path x₂ x₃ hp : ∀ (t : ↑I), ↑p₁ t = ↑p₂ t ⊢ HEq (Quotient.mk (Homotopic.setoid x₀ x₁) p₁) (Quotient.mk (Homotopic.setoid x₂ x₃) p₂) [PROOFSTEP] obtain rfl : x₀ = x₂ := by convert hp 0 <;> simp [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₁ : Path x₀ x₁ p₂ : Path x₂ x₃ hp : ∀ (t : ↑I), ↑p₁ t = ↑p₂ t ⊢ x₀ = x₂ [PROOFSTEP] convert hp 0 [GOAL] case h.e'_2 X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₁ : Path x₀ x₁ p₂ : Path x₂ x₃ hp : ∀ (t : ↑I), ↑p₁ t = ↑p₂ t ⊢ x₀ = ↑p₁ 0 [PROOFSTEP] simp [GOAL] case h.e'_3 X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X p₁ : Path x₀ x₁ p₂ : Path x₂ x₃ hp : ∀ (t : ↑I), ↑p₁ t = ↑p₂ t ⊢ x₂ = ↑p₂ 0 [PROOFSTEP] simp [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₃ : X p₁ : Path x₀ x₁ p₂ : Path x₀ x₃ hp : ∀ (t : ↑I), ↑p₁ t = ↑p₂ t ⊢ HEq (Quotient.mk (Homotopic.setoid x₀ x₁) p₁) (Quotient.mk (Homotopic.setoid x₀ x₃) p₂) [PROOFSTEP] obtain rfl : x₁ = x₃ := by convert hp 1 <;> simp [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₃ : X p₁ : Path x₀ x₁ p₂ : Path x₀ x₃ hp : ∀ (t : ↑I), ↑p₁ t = ↑p₂ t ⊢ x₁ = x₃ [PROOFSTEP] convert hp 1 [GOAL] case h.e'_2 X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₃ : X p₁ : Path x₀ x₁ p₂ : Path x₀ x₃ hp : ∀ (t : ↑I), ↑p₁ t = ↑p₂ t ⊢ x₁ = ↑p₁ 1 [PROOFSTEP] simp [GOAL] case h.e'_3 X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ x₃ : X p₁ : Path x₀ x₁ p₂ : Path x₀ x₃ hp : ∀ (t : ↑I), ↑p₁ t = ↑p₂ t ⊢ x₃ = ↑p₂ 1 [PROOFSTEP] simp [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ : X p₁ p₂ : Path x₀ x₁ hp : ∀ (t : ↑I), ↑p₁ t = ↑p₂ t ⊢ HEq (Quotient.mk (Homotopic.setoid x₀ x₁) p₁) (Quotient.mk (Homotopic.setoid x₀ x₁) p₂) [PROOFSTEP] rw [heq_iff_eq] [GOAL] X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ : X p₁ p₂ : Path x₀ x₁ hp : ∀ (t : ↑I), ↑p₁ t = ↑p₂ t ⊢ Quotient.mk (Homotopic.setoid x₀ x₁) p₁ = Quotient.mk (Homotopic.setoid x₀ x₁) p₂ [PROOFSTEP] congr [GOAL] case e_a X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ : X p₁ p₂ : Path x₀ x₁ hp : ∀ (t : ↑I), ↑p₁ t = ↑p₂ t ⊢ p₁ = p₂ [PROOFSTEP] ext t [GOAL] case e_a.a.h X : Type u Y : Type v inst✝¹ : TopologicalSpace X inst✝ : TopologicalSpace Y x₀ x₁ : X p₁ p₂ : Path x₀ x₁ hp : ∀ (t : ↑I), ↑p₁ t = ↑p₂ t t : ↑I ⊢ ↑p₁ t = ↑p₂ t [PROOFSTEP] exact hp t [GOAL] X : Type u Y : Type v inst✝² : TopologicalSpace X inst✝¹ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X inst✝ : Nonempty Y ⊢ Homotopic (const Y x₀) (const Y x₁) ↔ Joined x₀ x₁ [PROOFSTEP] inhabit Y [GOAL] X : Type u Y : Type v inst✝² : TopologicalSpace X inst✝¹ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X inst✝ : Nonempty Y inhabited_h : Inhabited Y ⊢ Homotopic (const Y x₀) (const Y x₁) ↔ Joined x₀ x₁ [PROOFSTEP] refine ⟨fun ⟨H⟩ ↦ ⟨⟨(H.toContinuousMap.comp .prodSwap).curry default, ?_, ?_⟩⟩, fun ⟨p⟩ ↦ ⟨p.toHomotopyConst⟩⟩ [GOAL] case refine_1 X : Type u Y : Type v inst✝² : TopologicalSpace X inst✝¹ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X inst✝ : Nonempty Y inhabited_h : Inhabited Y x✝ : Homotopic (const Y x₀) (const Y x₁) H : Homotopy (const Y x₀) (const Y x₁) ⊢ ContinuousMap.toFun (↑(curry (comp H.toContinuousMap prodSwap)) default) 0 = x₀ [PROOFSTEP] simp [GOAL] case refine_2 X : Type u Y : Type v inst✝² : TopologicalSpace X inst✝¹ : TopologicalSpace Y x₀ x₁ x₂ x₃ : X inst✝ : Nonempty Y inhabited_h : Inhabited Y x✝ : Homotopic (const Y x₀) (const Y x₁) H : Homotopy (const Y x₀) (const Y x₁) ⊢ ContinuousMap.toFun (↑(curry (comp H.toContinuousMap prodSwap)) default) 1 = x₁ [PROOFSTEP] simp
Formal statement is: lemma csqrt_minus [simp]: assumes "Im x < 0 \<or> (Im x = 0 \<and> 0 \<le> Re x)" shows "csqrt (- x) = \<i> * csqrt x" Informal statement is: If $x$ is in the lower half-plane, then $\sqrt{-x} = i \sqrt{x}$.
[GOAL] m n r : ℤ ⊢ r ∈ range m n ↔ m ≤ r ∧ r < n [PROOFSTEP] simp only [range, List.mem_map, List.mem_range, lt_toNat, lt_sub_iff_add_lt, add_comm] [GOAL] m n r : ℤ ⊢ (∃ a, m + ↑a < n ∧ m + ↑a = r) ↔ m ≤ r ∧ r < n [PROOFSTEP] exact ⟨fun ⟨a, ha⟩ => ha.2 ▸ ⟨le_add_of_nonneg_right (Int.coe_nat_nonneg _), ha.1⟩, fun h => ⟨toNat (r - m), by simp [toNat_of_nonneg (sub_nonneg.2 h.1), h.2]⟩⟩ [GOAL] m n r : ℤ h : m ≤ r ∧ r < n ⊢ m + ↑(toNat (r - m)) < n ∧ m + ↑(toNat (r - m)) = r [PROOFSTEP] simp [toNat_of_nonneg (sub_nonneg.2 h.1), h.2] [GOAL] P : ℤ → Prop inst✝ : DecidablePred P m n : ℤ ⊢ (∀ (r : ℤ), r ∈ range m n → P r) ↔ ∀ (r : ℤ), m ≤ r → r < n → P r [PROOFSTEP] simp only [mem_range_iff, and_imp] [GOAL] P : ℤ → Prop inst✝ : DecidablePred P m n : ℤ ⊢ Decidable (∀ (r : ℤ), m ≤ r → r ≤ n → P r) [PROOFSTEP] apply decidable_of_iff (∀ r ∈ range m (n + 1), P r) [GOAL] case h P : ℤ → Prop inst✝ : DecidablePred P m n : ℤ ⊢ (∀ (r : ℤ), r ∈ range m (n + 1) → P r) ↔ ∀ (r : ℤ), m ≤ r → r ≤ n → P r [PROOFSTEP] apply Iff.intro [GOAL] case h.mp P : ℤ → Prop inst✝ : DecidablePred P m n : ℤ ⊢ (∀ (r : ℤ), r ∈ range m (n + 1) → P r) → ∀ (r : ℤ), m ≤ r → r ≤ n → P r [PROOFSTEP] intros h _ _ [GOAL] case h.mpr P : ℤ → Prop inst✝ : DecidablePred P m n : ℤ ⊢ (∀ (r : ℤ), m ≤ r → r ≤ n → P r) → ∀ (r : ℤ), r ∈ range m (n + 1) → P r [PROOFSTEP] intros h _ _ [GOAL] case h.mp P : ℤ → Prop inst✝ : DecidablePred P m n : ℤ h : ∀ (r : ℤ), r ∈ range m (n + 1) → P r r✝ : ℤ a✝ : m ≤ r✝ ⊢ r✝ ≤ n → P r✝ [PROOFSTEP] intro _ [GOAL] case h.mp P : ℤ → Prop inst✝ : DecidablePred P m n : ℤ h : ∀ (r : ℤ), r ∈ range m (n + 1) → P r r✝ : ℤ a✝¹ : m ≤ r✝ a✝ : r✝ ≤ n ⊢ P r✝ [PROOFSTEP] apply h [GOAL] case h.mp.a P : ℤ → Prop inst✝ : DecidablePred P m n : ℤ h : ∀ (r : ℤ), r ∈ range m (n + 1) → P r r✝ : ℤ a✝¹ : m ≤ r✝ a✝ : r✝ ≤ n ⊢ r✝ ∈ range m (n + 1) [PROOFSTEP] simp_all only [mem_range_iff, and_imp, lt_add_one_iff] [GOAL] case h.mpr P : ℤ → Prop inst✝ : DecidablePred P m n : ℤ h : ∀ (r : ℤ), m ≤ r → r ≤ n → P r r✝ : ℤ a✝ : r✝ ∈ range m (n + 1) ⊢ P r✝ [PROOFSTEP] simp_all only [mem_range_iff, and_imp, lt_add_one_iff]
inductive InfTree.{u} (α : Type u) | leaf : α → InfTree α | node : (Nat → InfTree α) → InfTree α open InfTree def szn.{u} {α : Type u} (n : Nat) : InfTree α → InfTree α → Nat | leaf a, t2 => 1 | node c, leaf b => 0 | node c, node d => szn n (c n) (d n) universes u theorem ex1 {α : Type u} (n : Nat) (c : Nat → InfTree α) (d : Nat → InfTree α) : szn n (node c) (node d) = szn n (c n) (d n) := rfl inductive BTree (α : Type u) | leaf : α → BTree α | node : (Bool → Bool → BTree α) → BTree α def BTree.sz {α : Type u} : BTree α → Nat | leaf a => 1 | node c => sz (c true true) + sz (c true false) + sz (c false true) + sz (c false false) + 1 theorem ex2 {α : Type u} (c : Bool → Bool → BTree α) : (BTree.node c).sz = (c true true).sz + (c true false).sz + (c false true).sz + (c false false).sz + 1 := rfl inductive L (α : Type u) | nil : L α | cons : (Unit → α) → (Unit → L α) → L α def L.append {α} : L α → L α → L α | nil, bs => bs | cons a as, bs => cons a (fun _ => append (as ()) bs) theorem L.appendNil {α} : (as : L α) → append as nil = as | nil => rfl | cons a as => show cons a (fun _ => append (as ()) nil) = cons a as from have ih : append (as ()) nil = as () := appendNil $ as () have thunkAux : (fun _ => as ()) = as := funext fun x => by cases x exact rfl by rw [ih, thunkAux]
(** * Simulation up to taus *) (** A preorder [sutt t1 t2], where every visible step ([RetF] or [VisF]) on the left must be matched with a corresponding step on the right, ignoring [TauF]. In particular, [spin := Tau spin] is less than everything. The induced equivalence relation is [eutt]. [[ Theorem sutt_eutt : sutt eq t u -> sutt eq u t -> eutt eq t u. ]] Various lemmas about [eutt] may be more easily proved as [Proper] lemmas about [sutt] first, and then symmetrizing using [eutt_sutt] and [sutt_eutt]. *) Require Import Paco.paco. From Coq Require Import Classes.RelationClasses Classes.Morphisms Setoids.Setoid Program Relations.Relations. From ITree Require Import Core.ITreeDefinition Eq.Eq Eq.UpToTaus Eq.Shallow Eq.Paco2. Section SUTT. Context {E : Type -> Type} {R1 R2 : Type} (RR : R1 -> R2 -> Prop). Inductive suttF (sutt: itree' E R1 -> itree' E R2 -> Prop) : itree' E R1 -> itree' E R2 -> Prop := | suttF_ret r1 r2 : RR r1 r2 -> suttF sutt (RetF r1) (RetF r2) | suttF_vis u (e : E u) k1 k2 (SUTTK: forall x, sutt (observe (k1 x)) (observe (k2 x))): suttF sutt (VisF e k1) (VisF e k2) | suttF_tau_right ot1 t2 (EQTAUS: suttF sutt ot1 (observe t2)): suttF sutt ot1 (TauF t2) | suttF_tau_left t1 ot2 (EQTAUS: sutt (observe t1) ot2): suttF sutt (TauF t1) ot2 . Hint Constructors suttF: core. Definition sutt (t1 : itree E R1) (t2 : itree E R2) := paco2 suttF bot2 (observe t1) (observe t2). Hint Unfold sutt: core. End SUTT. Global Hint Constructors suttF: core. Global Hint Unfold sutt: core. Section SUTT_rel. Context {E : Type -> Type} {R : Type} (RR : R -> R -> Prop). Lemma reflexive_suttF `{Reflexive _ RR} sutt (r1:Reflexive sutt) : Reflexive (@suttF E _ _ RR sutt). Proof. unfold Reflexive. intros x. destruct x; eauto. Qed. End SUTT_rel. Section SUTT_facts. Context {E : Type -> Type} {R1 R2 : Type} (RR : R1 -> R2 -> Prop). Lemma monotone_suttF : monotone2 (@suttF E _ _ RR). Proof. repeat red; intros. induction IN; eauto. Qed. Hint Resolve monotone_suttF : paco. End SUTT_facts. Global Hint Resolve monotone_suttF : paco. Lemma suttF_inv_vis {E R1 R2} (RR : R1 -> R2 -> Prop) sutt : forall X e (k1 : X -> itree E R1) (k2 : X -> itree E R2), suttF RR sutt (VisF e k1) (VisF e k2) -> forall x, sutt (observe (k1 x)) (observe (k2 x)). Proof. intros. inv H. apply inj_pair2 in H3; apply inj_pair2 in H5. subst. auto. Qed. Lemma sutt_inv_vis {E R1 R2} (RR : R1 -> R2 -> Prop) : forall X e (k1 : X -> itree E R1) (k2 : X -> itree E R2), sutt RR (Vis e k1) (Vis e k2) -> forall x, sutt RR (k1 x) (k2 x). Proof. intros. pstep. punfold H. simpl in *. eapply suttF_inv_vis in H; pclearbot; punfold H. Qed. Lemma sutt_tau_right {E R1 R2} (RR : R1 -> R2 -> Prop) : forall (t1 : itree E R1) (t2 : itree E R2), sutt RR t1 t2 -> sutt RR t1 (Tau t2). Proof. intros. punfold H. pstep. repeat red. repeat red in H. constructor. auto. Qed. Lemma sutt_tau_left {E R1 R2} (RR : R1 -> R2 -> Prop) : forall (t1 : itree E R1) (t2 : itree E R2), sutt RR t1 t2 -> sutt RR (Tau t1) t2. Proof. intros. punfold H. pstep. repeat red. repeat red in H. constructor. eauto with paco. Qed. Lemma sutt_elim_tau_right {E R1 R2} (RR : R1 -> R2 -> Prop) : forall (t1: itree E R1) (t2: itree E R2), sutt RR t1 (Tau t2) -> sutt RR t1 t2. Proof. pcofix CIH. pstep. intros. punfold H0. repeat red in H0. inv H0. - eapply monotone_suttF; eauto using upaco2_mon_bot with paco. - constructor. pclearbot. eauto with paco. Qed. Lemma suttF_inv_tau_left {E R1 R2} (RR : R1 -> R2 -> Prop) : forall (t1: itree E R1) ot2, suttF RR (upaco2 (suttF RR) bot2) (TauF t1) ot2 -> suttF RR (upaco2 (suttF RR) bot2) (observe t1) ot2. Proof. intros. remember (TauF t1) as ott1. induction H; intros; subst; try dependent destruction Heqott1; eauto. pclearbot. punfold EQTAUS. Qed. Lemma sutt_inv_tau_left {E R1 R2} (RR : R1 -> R2 -> Prop) : forall (t1: itree E R1) (t2: itree E R2), sutt RR (Tau t1) t2 -> sutt RR t1 t2. Proof. intros. punfold H. pstep. repeat red in H |- *. apply suttF_inv_tau_left; auto. Qed. Theorem sutt_eutt {E R1 R2} (RR : R1 -> R2 -> Prop) : forall (t1 : itree E R1) (t2 : itree E R2), sutt RR t1 t2 -> sutt (flip RR) t2 t1 -> eutt RR t1 t2. Proof. pcofix CIH. intros. punfold H0. punfold H. pstep. red. induction H0; intros; subst; auto. - constructor. intro. right. eapply suttF_inv_vis in H. pclearbot. eauto with paco. - constructor; eauto. eapply IHsuttF; auto. eapply suttF_inv_tau_left; auto. - (* doing induction when one of the trees is a tau doesn't work well *) inv H; pclearbot. + clear t1 t2. genobs t0 ot0. hinduction EQTAUS0 before CIH; intros; subst; pclearbot. * constructor; eauto. simpobs. constructor. eauto. * constructor; eauto. simpobs. constructor. intros. right. apply CIH; auto. eapply sutt_inv_vis in EQTAUS; eauto. * constructor; eauto. simpobs. eapply IHEQTAUS0; eauto. rewrite (itree_eta' ot1). apply sutt_inv_tau_left; auto. * constructor. right. apply CIH; auto. apply sutt_elim_tau_right; auto. + constructor. right. apply CIH; apply sutt_elim_tau_right; auto. Qed. Theorem eutt_sutt {E R1 R2} (RR : R1 -> R2 -> Prop) : forall (t1 : itree E R1) (t2 : itree E R2), eutt RR t1 t2 -> sutt RR t1 t2. Proof. pcofix CIH. pstep. intros. punfold H0. red in H0. induction H0; constructor; pclearbot; eauto 7 with paco. Qed. (** Generalized heterogeneous version of [eutt_bind] *) Lemma sutt_bind' {E R1 R2 S1 S2} {RR: R1 -> R2 -> Prop} {SS: S1 -> S2 -> Prop}: forall t1 t2, sutt RR t1 t2 -> forall s1 s2, (forall r1 r2, RR r1 r2 -> sutt SS (s1 r1) (s2 r2)) -> @sutt E _ _ SS (ITree.bind t1 s1) (ITree.bind t2 s2). Proof. pcofix self. pstep. intros. punfold H0. unfold observe; cbn. induction H0; intros. - simpl. apply H1 in H. punfold H. eapply monotone_suttF; eauto using upaco2_mon_bot. - simpl. pclearbot. econstructor. eauto. - constructor. eauto with paco. - constructor. pclearbot. right. specialize (self t0 (go ot2) EQTAUS _ _ H1). apply self. Qed. Require Import Coq.Relations.Relations. (* todo: this could be made stronger with eutt rather than eq_itree *) #[global] Instance Proper_sutt {E : Type -> Type} {R1 R2 : Type} r : Proper (eq_itree eq ==> eq_itree eq ==> flip impl) (@sutt E R1 R2 r). Proof. repeat red. pcofix CIH; pstep. intros. punfold H0; punfold H1; punfold H2. red in H0, H1. (* rename H1 into H2, Hxy into H1. *) hinduction H2 before CIH; subst; intros. - inv H0; try discriminate. inv H1; try discriminate. econstructor. eauto. - dependent destruction H0; try discriminate. dependent destruction H1; try discriminate. simpobs. pclearbot. constructor. intros. right. eauto 7 with paco. - dependent destruction H1; try discriminate. simpobs. pclearbot. punfold REL. - dependent destruction H0; try discriminate. simpobs. pclearbot. constructor. right. rewrite (itree_eta' ot2) in *. eauto. Qed.
function xy = ellipse_grid ( n, r, c, ng ) %*****************************************************************************80 % %% ELLIPSE_GRID generates grid points inside an ellipse. % % Discussion: % % The ellipse is specified as % % ( ( X - C1 ) / R1 )^2 + ( ( Y - C2 ) / R2 )^2 = 1 % % The user supplies a number N. There will be N+1 grid points along % the shorter axis. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 10 November 2011 % % Author: % % John Burkardt % % Parameters: % % Input, integer N, the number of subintervals. % % Input, real R(2), the half axis lengths. % % Input, real C(2), the center of the ellipse. % % Input, integer NG, the number of grid points inside the ellipse. % % Output, real XY(2,NG), the grid points. % if ( r(1) < r(2) ) h = 2 * r(1) / ( 2 * n + 1 ); ni = n; nj = ceil ( r(2) / r(1) ) * n; else h = 2 * r(2) / ( 2 * n + 1 ); nj = n; ni = ceil ( r(1) / r(2) ) * n; end p = 0; for j = 0 : nj i = 0; x = c(1); y = c(2) + j * h; p = p + 1; xy(1:2,p) = [ x, y ]'; if ( 0 < j ) p = p + 1; xy(1:2,p) = [ x, 2 * c(2) - y ]'; end while ( 1 ) i = i + 1; x = c(1) + i * h; if ( 1 < ( ( x - c(1) ) / r(1) ).^2 + ( ( y - c(2) ) / r(2) ).^2 ) break end p = p + 1; xy(1:2,p) = [ x, y ]'; p = p + 1; xy(1:2,p) = [ 2 * c(1) - x, y ]'; if ( 0 < j ) p = p + 1; xy(1:2,p) = [ x, 2 * c(2) - y ]'; p = p + 1; xy(1:2,p) = [ 2 * c(1) - x, 2 * c(2) - y ]'; end end end return end
// Copyright John Maddock 2007. // Copyright Paul A. Bristow 2010 // Use, modification and distribution are 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) // Note that this file contains quickbook mark-up as well as code // and comments, don't change any of the special comment mark-ups! //[policy_eg_10 /*` To understand how the rounding policies for the discrete distributions can be used, we'll use the 50-sample binomial distribution with a success fraction of 0.5 once again, and calculate all the possible quantiles at 0.05 and 0.95. Begin by including the needed headers (and some using statements for conciseness): */ #include <iostream> using std::cout; using std::endl; using std::left; using std::fixed; using std::right; using std::scientific; #include <iomanip> using std::setw; using std::setprecision; #include <boost/math/distributions/binomial.hpp> /*` Next we'll bring the needed declarations into scope, and define distribution types for all the available rounding policies: */ // Avoid // using namespace std; // and // using namespace boost::math; // to avoid potential ambiguity of names, like binomial. // using namespace boost::math::policies; is small risk, but // the necessary items are brought into scope thus: using boost::math::binomial_distribution; using boost::math::policies::policy; using boost::math::policies::discrete_quantile; using boost::math::policies::integer_round_outwards; using boost::math::policies::integer_round_down; using boost::math::policies::integer_round_up; using boost::math::policies::integer_round_nearest; using boost::math::policies::integer_round_inwards; using boost::math::policies::real; using boost::math::binomial_distribution; // Not std::binomial_distribution. typedef binomial_distribution< double, policy<discrete_quantile<integer_round_outwards> > > binom_round_outwards; typedef binomial_distribution< double, policy<discrete_quantile<integer_round_inwards> > > binom_round_inwards; typedef binomial_distribution< double, policy<discrete_quantile<integer_round_down> > > binom_round_down; typedef binomial_distribution< double, policy<discrete_quantile<integer_round_up> > > binom_round_up; typedef binomial_distribution< double, policy<discrete_quantile<integer_round_nearest> > > binom_round_nearest; typedef binomial_distribution< double, policy<discrete_quantile<real> > > binom_real_quantile; /*` Now let's set to work calling those quantiles: */ int main() { cout << "Testing rounding policies for a 50 sample binomial distribution,\n" "with a success fraction of 0.5.\n\n" "Lower quantiles are calculated at p = 0.05\n\n" "Upper quantiles at p = 0.95.\n\n"; cout << setw(25) << right << "Policy"<< setw(18) << right << "Lower Quantile" << setw(18) << right << "Upper Quantile" << endl; // Test integer_round_outwards: cout << setw(25) << right << "integer_round_outwards" << setw(18) << right << quantile(binom_round_outwards(50, 0.5), 0.05) << setw(18) << right << quantile(binom_round_outwards(50, 0.5), 0.95) << endl; // Test integer_round_inwards: cout << setw(25) << right << "integer_round_inwards" << setw(18) << right << quantile(binom_round_inwards(50, 0.5), 0.05) << setw(18) << right << quantile(binom_round_inwards(50, 0.5), 0.95) << endl; // Test integer_round_down: cout << setw(25) << right << "integer_round_down" << setw(18) << right << quantile(binom_round_down(50, 0.5), 0.05) << setw(18) << right << quantile(binom_round_down(50, 0.5), 0.95) << endl; // Test integer_round_up: cout << setw(25) << right << "integer_round_up" << setw(18) << right << quantile(binom_round_up(50, 0.5), 0.05) << setw(18) << right << quantile(binom_round_up(50, 0.5), 0.95) << endl; // Test integer_round_nearest: cout << setw(25) << right << "integer_round_nearest" << setw(18) << right << quantile(binom_round_nearest(50, 0.5), 0.05) << setw(18) << right << quantile(binom_round_nearest(50, 0.5), 0.95) << endl; // Test real: cout << setw(25) << right << "real" << setw(18) << right << quantile(binom_real_quantile(50, 0.5), 0.05) << setw(18) << right << quantile(binom_real_quantile(50, 0.5), 0.95) << endl; } // int main() /*` Which produces the program output: [pre policy_eg_10.vcxproj -> J:\Cpp\MathToolkit\test\Math_test\Release\policy_eg_10.exe Testing rounding policies for a 50 sample binomial distribution, with a success fraction of 0.5. Lower quantiles are calculated at p = 0.05 Upper quantiles at p = 0.95. Policy Lower Quantile Upper Quantile integer_round_outwards 18 31 integer_round_inwards 19 30 integer_round_down 18 30 integer_round_up 19 31 integer_round_nearest 19 30 real 18.701 30.299 ] */ //] //[policy_eg_10] ends quickbook import.
Require Import Omega. Lemma foo : forall n m : Z, (n >= 0)%Z -> (n * m >= 0)%Z -> (n <= n + n * m)%Z. Proof. intros. omega. Qed. Lemma foo' : forall n m : nat, n <= n + n * m. Proof. intros. Fail omega. Abort.
# Simplified Ikeda sensitivity ```python #from jupyterthemes import jtplot #jtplot.style(theme='onedork', context='notebook', ticks=True, grid=False) ``` ```python %matplotlib inline %load_ext autoreload %autoreload 2 ``` ```python import pandas as pd pd.options.display.max_rows = 999 pd.options.display.max_columns = 999 import numpy as np import matplotlib.pyplot as plt from pylab import rcParams rcParams['figure.figsize'] = 15, 5 from rolldecayestimators.simplified_ikeda import calculate_roll_damping, SimplifiedIkedaInputError from rolldecayestimators import equations import sympy as sp from rolldecayestimators import symbols from rolldecayestimators.substitute_dynamic_symbols import lambdify from mdldb.tables import Run from rolldecayestimators.ikeda_estimator import IkedaEstimator from rolldecayestimators.transformers import CutTransformer, LowpassFilterDerivatorTransformer, ScaleFactorTransformer, OffsetTransformer from sklearn.pipeline import Pipeline from rolldecay import database import data import copy from rolldecay import database from sympy.physics.vector.printing import vpprint, vlatex from IPython.display import display, Math, Latex from rolldecay.paper_writing import save_fig ``` ```python from rolldecay.sensitivity import calculate ``` ```python db = database.get_db() ``` ```python sql = """ SELECT * from loading_conditions INNER JOIN models ON loading_conditions.model_number==models.model_number INNER JOIN ships ON ships.name == models.ship_name """ df = pd.read_sql_query(sql=sql, con=db.engine) ``` ```python mask = df['Volume']>0 df=df.loc[mask].copy() ``` ```python df.describe() ``` ```python df['DRAFT']=(df.TA + df.TF)/2 df['CB'] = df.Volume/(df.lpp*df.beam*df.DRAFT) mask = df['CB'].abs()!=np.inf df=df.loc[mask] ``` ```python df['CB'].hist(bins=30) ``` ```python mask = ((0 < df['CB']) & (df['CB'] <=1)) df = df.loc[mask] ``` ```python mask = df['Volume'] == df['Volume'].median() ship = df.loc[mask].iloc[0] ship['phi_max'] = 5 ship['omega0'] = 0.5 ``` ```python ship.Volume/(ship.lpp*ship.beam*(ship.TA+ship.TF)/2) ``` ```python from rolldecay.sensitivity import variate_ship ``` ```python N=30 changes = np.linspace(0.5,1.5,N) df = variate_ship(ship=ship, key='lpp', changes=changes) ``` ```python result = df.apply(func=calculate, axis=1) ``` ```python result.plot() ``` ```python from rolldecay.sensitivity import plot_variation, calculate_variation ``` ```python plot_variation(ship=ship, key='lpp') ``` ```python variations = ['lpp','beam','DRAFT','phi_max','BKL','BKB','omega0','kg','CB','A0'] N=30 changes = np.linspace(0.85,1.32,N) ylims=[] axes=[] for variation in variations: fig,ax=plt.subplots() plot_variation(ship=ship, key=variation, ax=ax, changes=changes, catch_error=True) ax.set_title('Variation of %s: %0.2f' % (variation, ship[variation])) ylims.append(list(ax.get_ylim())) axes.append(ax) for ax in axes: ax.set_ylim(np.min(ylims),np.max(ylims)) ``` ```python ``` ```python plot_variation(ship=ship, key='lpp') ``` ```python ikeda_parameters = ['lpp','beam','DRAFT','phi_max','BKL','BKB','omega0','kg','CB','A0'] ship_=ship[ikeda_parameters] ship_['phi_max']=8 ``` ```python ship_ ``` ```python calculate(ship_) ``` ```python ship2 = ship_.copy() scale = 0.01 ship2['lpp']/=scale ship2['beam']/=scale ship2['DRAFT']/=scale ship2['BKL']/=scale ship2['BKB']/=scale ship2['kg']/=scale ship2['omega0']*=np.sqrt(scale) calculate(ship2) ``` ```python ship2 = ship_.copy() scale = ship_['lpp'] ship2['lpp']/=scale ship2['beam']/=scale ship2['DRAFT']/=scale ship2['BKL']/=scale ship2['BKB']/=scale ship2['kg']/=scale ship2['omega0']*=np.sqrt(scale) #ship2['BKB']*=10 calculate(ship2) ``` ```python variations = list(set(ikeda_parameters) - set(['lpp'])) N=100 changes = np.linspace(0.85,1.43,N) ylims=[] axes=[] for variation in variations: fig,ax=plt.subplots() plot_variation(ship=ship2, key=variation, ax=ax, changes=changes, catch_error=True, plot_change_factor=False) ylims.append(list(ax.get_ylim())) axes.append(ax) ax.grid(True) for ax in axes: ax.set_ylim(np.min(ylims),np.max(ylims)) ``` ```python df = variate_ship(ship=ship2, key='beam', changes=changes) result = calculate_variation(df=df, catch_error=True) result = pd.concat([result,df], axis=1) ``` ```python result['Disp'] = result['CB']*result['lpp']*result['beam']*result['DRAFT'] ``` ```python equations.B44_hat_equation ``` ```python B44_equation = sp.Eq(symbols.B_44,sp.solve(equations.B44_hat_equation,symbols.B_44)[0]) B44_equation ``` ```python B44_lambda = lambdify(sp.solve(B44_equation,symbols.B_44)[0]) ``` ```python result['B44'] = B44_lambda(result['B44HAT'], result['Disp'], beam=result['beam'], g=9.81, rho=1000) ``` ```python result.plot(x='beam', y = 'B44') ``` ```python variations = list(set(ikeda_parameters) - set(['lpp'])) N=100 changes = np.linspace(0.7,1.32,N) ylims=[] axes=[] for variation in variations: fig,ax=plt.subplots() df = variate_ship(ship=ship2, key=variation, changes=changes) result = calculate_variation(df=df, catch_error=True) #result.fillna(0,inplace=True) df['Disp'] = df['CB']*df['lpp']*df['beam']*df['DRAFT'] dampings = ['B44','BW','BE','BBK'] for key in dampings: result[key] = B44_lambda(np.array(result[key+'HAT']), np.array(df['Disp']), beam=df['beam'].astype(float), g=9.81, rho=1000) result[variation]=df[variation] result.plot(x=variation, y=dampings, ax=ax) ax.plot(ship2[variation],0,'ro', label='reference') ylims.append(list(ax.get_ylim())) axes.append(ax) for ax in axes: ax.set_ylim(np.min(ylims),np.max(ylims)) ``` ```python from rolldecayestimators.ikeda_speed import bilge_keel variation='BKB' N=100 changes = np.linspace(0.5,3,N) df = variate_ship(ship=ship2, key=variation, changes=changes) result = calculate_variation(df=df, catch_error=True) ``` ```python dddf = variate_ship(ship=ship2, key=variation, changes=changes) ddresult = calculate_variation(df=df, catch_error=True) ``` ```python R=0.3/175 df=df.astype(float) def calculate_bilge_keel(row,R): OG=-row.kg + row.DRAFT Ho=(row['beam']/(2*row['DRAFT']) ) A=(row['A0']*row['beam']*row['DRAFT']) Bp44BK_N0, Bp44BK_H0, B44BK_L, B44BKW0 = bilge_keel(w=row['omega0'], fi_a=np.deg2rad(row['phi_max']), V=0, B=row['beam'], d=row['DRAFT'], A=A, bBK=row['BKB'], R=R, g=9.81, OG=OG, Ho=Ho, ra=1000) s = pd.Series(name=row.name) s['Bp44BK_N0'] = Bp44BK_N0 s['Bp44BK_H0'] = Bp44BK_H0 s['B44BK_L'] = B44BK_L s['B44BKW0'] = B44BKW0 LBK = row.BKL B44BK_N0 = Bp44BK_N0*LBK B44BK_H0 = Bp44BK_H0*LBK B44BK_L = B44BK_L # B44BKW0 = B44BKW0 * dim... B44_BK = B44BK_N0 + B44BK_H0 + B44BK_L s['B44_BK'] = B44_BK return s ``` ```python result2 = df.apply(func=calculate_bilge_keel, R=R, axis=1) ``` ```python key='BBK' df['Disp'] = df['CB']*df['lpp']*df['beam']*df['DRAFT'] result[key] = B44_lambda(np.array(result[key+'HAT']), np.array(df['Disp']), beam=df['beam'].astype(float), g=9.81, rho=1000) ``` ```python fig,ax=plt.subplots() result.plot(y='BBK', ax=ax) result2.plot(y='B44_BK', ax=ax) ``` ```python df_rolldecay = database.load(rolldecay_table_name='rolldecay_quadratic_b', limit_score=0.90, exclude_table_name='rolldecay_exclude') db = database.get_db() ``` ```python loading_conditions=df_rolldecay.copy() scale = np.array(loading_conditions['lpp']) loading_conditions['lpp']/=scale loading_conditions['beam']/=scale loading_conditions['DRAFT']=(loading_conditions['TA']+loading_conditions['TF'])/2/scale loading_conditions['BKL']/=scale loading_conditions['BKB']/=scale loading_conditions['kg']/=scale volume = loading_conditions['Volume']/scale**3 lpp=loading_conditions['lpp'] T=loading_conditions['DRAFT'] beam=loading_conditions['beam'] loading_conditions['phi_max']=np.rad2deg(loading_conditions['phi_start'].abs()) loading_conditions['CB']=volume/(lpp*beam*T) ``` ```python variations = list(set(ikeda_parameters) - set(['lpp'])) N=100 ship2.omega0 = loading_conditions['omega0'].median() ylimss=[] axes=[] fig,axes=plt.subplots(nrows=len(variations)) for variation,ax in zip(variations,axes): s = loading_conditions[variation] changes = np.linspace(s.min(),s.max(),N)/ship2[variation] df = variate_ship(ship=ship2, key=variation, changes=changes) result = calculate_variation(df=df, catch_error=True) #result.fillna(0,inplace=True) df['Disp'] = df['CB']*df['lpp']*df['beam']*df['DRAFT'] dampings = ['B44','BW','BE','BBK'] for key in dampings: result[key] = B44_lambda(np.array(result[key+'HAT']), np.array(df['Disp']), beam=df['beam'].astype(float), g=9.81, rho=1000) result[variation]=df[variation] result.plot(x=variation, y=dampings, ax=ax) ylims = ax.get_ylim() ax.plot([ship2[variation],ship2[variation]],ylims,'r--', label='median ship') ax.get_legend().remove() axes[0].legend() plt.tight_layout() save_fig(fig=fig, name='ikeda_variation', full_page=True) ``` ```python ```
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #pragma once #include <event.h> #include <memcached/engine_error.h> #include <memcached/types.h> #include <platform/socket.h> #include <subdoc/operations.h> #include <gsl/gsl> #include <mutex> #include <queue> #include <unordered_map> #include <vector> /** \file * The main memcached header holding commonly used data * structures and function prototypes. */ /** Maximum length of a key. */ #define KEY_MAX_LENGTH 250 #define MAX_SENDBUF_SIZE (256 * 1024 * 1024) /* Maximum length of config which can be validated */ #define CONFIG_VALIDATE_MAX_LENGTH (64 * 1024) /* Maximum IOCTL get/set key and payload (body) length */ #define IOCTL_KEY_LENGTH 128 #define IOCTL_VAL_LENGTH 128 #define MAX_VERBOSITY_LEVEL 2 class Cookie; class Connection; struct thread_stats; void initialize_buckets(); void cleanup_buckets(); void associate_initial_bucket(Connection& connection); /* * Functions such as the libevent-related calls that need to do cross-thread * communication in multithreaded mode (rather than actually doing the work * in the current thread) are called via "dispatch_" frontends, which are * also #define-d to directly call the underlying code in singlethreaded mode. */ void worker_threads_init(); void threads_shutdown(); void threads_cleanup(); /** * Create a socketpair and make it non-blocking * * @param sockets Where to store the sockets * @return true if success, false otherwise (and the error reason logged) */ bool create_nonblocking_socketpair(std::array<SOCKET, 2>& sockets); class ListeningPort; void dispatch_conn_new(SOCKET sfd, std::shared_ptr<ListeningPort>& interface); void threadlocal_stats_reset(std::vector<thread_stats>& thread_stats); void notify_io_complete(gsl::not_null<const void*> cookie, ENGINE_ERROR_CODE status); void safe_close(SOCKET sfd); int add_conn_to_pending_io_list(Connection* c, Cookie* cookie, ENGINE_ERROR_CODE status); const char* get_server_version(); bool is_memcached_shutting_down(); /** * Connection-related functions */ /** * Increments topkeys count for the key specified within the command context * provided by the cookie. */ void update_topkeys(const Cookie& cookie); struct ServerApi; ServerApi* get_server_api(); void shutdown_server(); bool associate_bucket(Connection& connection, const char* name); void disassociate_bucket(Connection& connection); void disable_listen(); bool is_listen_disabled(); /** * The executor pool used to pick up the result for requests spawn by the * client io threads and dispatched over to a background thread (in order * to allow for out of order replies). */ namespace cb { class ExecutorPool; } extern std::unique_ptr<cb::ExecutorPool> executorPool; void iterate_all_connections(std::function<void(Connection&)> callback); void start_stdin_listener(std::function<void()> function);
[GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε ⊢ Finset.card (increment hP G ε).parts = stepBound (Finset.card P.parts) [PROOFSTEP] have hPα' : stepBound P.parts.card ≤ card α := (mul_le_mul_left' (pow_le_pow_of_le_left' (by norm_num) _) _).trans hPα [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε ⊢ 4 ≤ 16 [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α ⊢ Finset.card (increment hP G ε).parts = stepBound (Finset.card P.parts) [PROOFSTEP] have hPpos : 0 < stepBound P.parts.card := stepBound_pos (nonempty_of_not_uniform hPG).card_pos [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ Finset.card (increment hP G ε).parts = stepBound (Finset.card P.parts) [PROOFSTEP] rw [increment, card_bind] [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ∑ A in attach P.parts, Finset.card (chunk hP G ε (_ : ↑A ∈ P.parts)).parts = stepBound (Finset.card P.parts) [PROOFSTEP] simp_rw [chunk, apply_dite Finpartition.parts, apply_dite card, sum_dite] [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ∑ x in attach (filter (fun x => Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)), Finset.card (equitabilise (_ : (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) * (Fintype.card α / stepBound (Finset.card P.parts)) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts) * (Fintype.card α / stepBound (Finset.card P.parts) + 1) = Finset.card ↑↑x)).parts + ∑ x in attach (filter (fun x => ¬Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)), Finset.card (equitabilise (_ : (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1)) * (Fintype.card α / stepBound (Finset.card P.parts)) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1) * (Fintype.card α / stepBound (Finset.card P.parts) + 1) = Finset.card ↑↑x)).parts = stepBound (Finset.card P.parts) [PROOFSTEP] rw [sum_const_nat, sum_const_nat, card_attach, card_attach] [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ Finset.card (filter (fun x => Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) * ?m.158358 + Finset.card (filter (fun x => ¬Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) * ?m.158415 = stepBound (Finset.card P.parts) α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ∀ (x : { x // x ∈ filter (fun x => ¬Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts) }), x ∈ attach (filter (fun x => ¬Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) → Finset.card (equitabilise (_ : (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1)) * (Fintype.card α / stepBound (Finset.card P.parts)) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1) * (Fintype.card α / stepBound (Finset.card P.parts) + 1) = Finset.card ↑↑x)).parts = ?m.158415 α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ∀ (x : { x // x ∈ filter (fun x => Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts) }), x ∈ attach (filter (fun x => Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) → Finset.card (equitabilise (_ : (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) * (Fintype.card α / stepBound (Finset.card P.parts)) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts) * (Fintype.card α / stepBound (Finset.card P.parts) + 1) = Finset.card ↑↑x)).parts = ?m.158358 α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ [PROOFSTEP] rotate_left [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ∀ (x : { x // x ∈ filter (fun x => ¬Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts) }), x ∈ attach (filter (fun x => ¬Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) → Finset.card (equitabilise (_ : (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1)) * (Fintype.card α / stepBound (Finset.card P.parts)) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1) * (Fintype.card α / stepBound (Finset.card P.parts) + 1) = Finset.card ↑↑x)).parts = ?m.158415 α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ∀ (x : { x // x ∈ filter (fun x => Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts) }), x ∈ attach (filter (fun x => Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) → Finset.card (equitabilise (_ : (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) * (Fintype.card α / stepBound (Finset.card P.parts)) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts) * (Fintype.card α / stepBound (Finset.card P.parts) + 1) = Finset.card ↑↑x)).parts = ?m.158358 α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ Finset.card (filter (fun x => Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) * ?m.158358 + Finset.card (filter (fun x => ¬Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) * ?m.158415 = stepBound (Finset.card P.parts) [PROOFSTEP] any_goals exact fun x hx => card_parts_equitabilise _ _ (Nat.div_pos hPα' hPpos).ne' [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ [PROOFSTEP] exact fun x hx => card_parts_equitabilise _ _ (Nat.div_pos hPα' hPpos).ne' [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ [PROOFSTEP] exact fun x hx => card_parts_equitabilise _ _ (Nat.div_pos hPα' hPpos).ne' [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ [PROOFSTEP] exact fun x hx => card_parts_equitabilise _ _ (Nat.div_pos hPα' hPpos).ne' [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ [PROOFSTEP] exact fun x hx => card_parts_equitabilise _ _ (Nat.div_pos hPα' hPpos).ne' [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ∀ (x : { x // x ∈ filter (fun x => ¬Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts) }), x ∈ attach (filter (fun x => ¬Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) → Finset.card (equitabilise (_ : (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1)) * (Fintype.card α / stepBound (Finset.card P.parts)) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1) * (Fintype.card α / stepBound (Finset.card P.parts) + 1) = Finset.card ↑↑x)).parts = ?m.158415 [PROOFSTEP] exact fun x hx => card_parts_equitabilise _ _ (Nat.div_pos hPα' hPpos).ne' [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ℕ [PROOFSTEP] exact fun x hx => card_parts_equitabilise _ _ (Nat.div_pos hPα' hPpos).ne' [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ ∀ (x : { x // x ∈ filter (fun x => Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts) }), x ∈ attach (filter (fun x => Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) → Finset.card (equitabilise (_ : (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) * (Fintype.card α / stepBound (Finset.card P.parts)) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts) * (Fintype.card α / stepBound (Finset.card P.parts) + 1) = Finset.card ↑↑x)).parts = ?m.158358 [PROOFSTEP] exact fun x hx => card_parts_equitabilise _ _ (Nat.div_pos hPα' hPpos).ne' [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ Finset.card (filter (fun x => Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) * (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) + Finset.card (filter (fun x => ¬Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) * (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1)) = stepBound (Finset.card P.parts) [PROOFSTEP] exact fun x hx => card_parts_equitabilise _ _ (Nat.div_pos hPα' hPpos).ne' [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ Finset.card (filter (fun x => Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) * (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) + Finset.card (filter (fun x => ¬Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) * (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1)) = stepBound (Finset.card P.parts) [PROOFSTEP] rw [Nat.sub_add_cancel a_add_one_le_four_pow_parts_card, Nat.sub_add_cancel ((Nat.le_succ _).trans a_add_one_le_four_pow_parts_card), ← add_mul] [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ (Finset.card (filter (fun x => Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) + Finset.card (filter (fun x => ¬Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts))) * 4 ^ Finset.card P.parts = stepBound (Finset.card P.parts) [PROOFSTEP] congr [GOAL] case e_a α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hPα' : stepBound (Finset.card P.parts) ≤ Fintype.card α hPpos : 0 < stepBound (Finset.card P.parts) ⊢ Finset.card (filter (fun x => Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) + Finset.card (filter (fun x => ¬Finset.card ↑x = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) (attach P.parts)) = Finset.card P.parts [PROOFSTEP] rw [filter_card_add_filter_neg_card_eq_card, card_attach] [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP✝ : IsEquipartition P G✝ : SimpleGraph α ε✝ : ℝ hP : IsEquipartition P G : SimpleGraph α ε : ℝ ⊢ IsEquipartition (increment hP G ε) [PROOFSTEP] simp_rw [IsEquipartition, Set.equitableOn_iff_exists_eq_eq_add_one] [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP✝ : IsEquipartition P G✝ : SimpleGraph α ε✝ : ℝ hP : IsEquipartition P G : SimpleGraph α ε : ℝ ⊢ ∃ b, ∀ (a : Finset α), a ∈ ↑(increment hP G ε).parts → Finset.card a = b ∨ Finset.card a = b + 1 [PROOFSTEP] refine' ⟨m, fun A hA => _⟩ [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP✝ : IsEquipartition P G✝ : SimpleGraph α ε✝ : ℝ hP : IsEquipartition P G : SimpleGraph α ε : ℝ A : Finset α hA : A ∈ ↑(increment hP G ε).parts ⊢ Finset.card A = Fintype.card α / stepBound (Finset.card P.parts) ∨ Finset.card A = Fintype.card α / stepBound (Finset.card P.parts) + 1 [PROOFSTEP] rw [mem_coe, increment, mem_bind] at hA [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP✝ : IsEquipartition P G✝ : SimpleGraph α ε✝ : ℝ hP : IsEquipartition P G : SimpleGraph α ε : ℝ A : Finset α hA : ∃ A_1 hA, A ∈ (chunk hP G ε hA).parts ⊢ Finset.card A = Fintype.card α / stepBound (Finset.card P.parts) ∨ Finset.card A = Fintype.card α / stepBound (Finset.card P.parts) + 1 [PROOFSTEP] obtain ⟨U, hU, hA⟩ := hA [GOAL] case intro.intro α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP✝ : IsEquipartition P G✝ : SimpleGraph α ε✝ : ℝ hP : IsEquipartition P G : SimpleGraph α ε : ℝ A U : Finset α hU : U ∈ P.parts hA : A ∈ (chunk hP G ε hU).parts ⊢ Finset.card A = Fintype.card α / stepBound (Finset.card P.parts) ∨ Finset.card A = Fintype.card α / stepBound (Finset.card P.parts) + 1 [PROOFSTEP] exact card_eq_of_mem_parts_chunk hA [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ ⊢ (Finset.biUnion (attach (offDiag P.parts)) fun UV => (chunk hP G ε (_ : (↑UV).fst ∈ P.parts)).parts ×ˢ (chunk hP G ε (_ : (↑UV).snd ∈ P.parts)).parts) ⊆ offDiag (increment hP G ε).parts [PROOFSTEP] rintro ⟨Ui, Vj⟩ [GOAL] case mk α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ Ui Vj : Finset α ⊢ ((Ui, Vj) ∈ Finset.biUnion (attach (offDiag P.parts)) fun UV => (chunk hP G ε (_ : (↑UV).fst ∈ P.parts)).parts ×ˢ (chunk hP G ε (_ : (↑UV).snd ∈ P.parts)).parts) → (Ui, Vj) ∈ offDiag (increment hP G ε).parts [PROOFSTEP] simp only [increment, mem_offDiag, bind_parts, mem_biUnion, Prod.exists, exists_and_left, exists_prop, mem_product, mem_attach, true_and_iff, Subtype.exists, and_imp, mem_offDiag, forall_exists_index, bex_imp, Ne.def] [GOAL] case mk α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ Ui Vj : Finset α ⊢ ∀ (x x_1 : Finset α) (x_2 : x ∈ P.parts ∧ x_1 ∈ P.parts ∧ ¬x = x_1), Ui ∈ (chunk hP G ε (_ : (↑{ val := (x, x_1), property := (_ : (x, x_1) ∈ offDiag P.parts) }).fst ∈ P.parts)).parts → Vj ∈ (chunk hP G ε (_ : (↑{ val := (x, x_1), property := (_ : (x, x_1) ∈ offDiag P.parts) }).snd ∈ P.parts)).parts → (∃ a h, Ui ∈ (chunk hP G ε (_ : ↑{ val := a, property := (_ : a ∈ P.parts) } ∈ P.parts)).parts) ∧ (∃ a h, Vj ∈ (chunk hP G ε (_ : ↑{ val := a, property := (_ : a ∈ P.parts) } ∈ P.parts)).parts) ∧ ¬Ui = Vj [PROOFSTEP] refine' fun U V hUV hUi hVj => ⟨⟨_, hUV.1, hUi⟩, ⟨_, hUV.2.1, hVj⟩, _⟩ [GOAL] case mk α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ Ui Vj U V : Finset α hUV : U ∈ P.parts ∧ V ∈ P.parts ∧ ¬U = V hUi : Ui ∈ (chunk hP G ε (_ : (↑{ val := (U, V), property := (_ : (U, V) ∈ offDiag P.parts) }).fst ∈ P.parts)).parts hVj : Vj ∈ (chunk hP G ε (_ : (↑{ val := (U, V), property := (_ : (U, V) ∈ offDiag P.parts) }).snd ∈ P.parts)).parts ⊢ ¬Ui = Vj [PROOFSTEP] rintro rfl [GOAL] case mk α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ Ui U V : Finset α hUV : U ∈ P.parts ∧ V ∈ P.parts ∧ ¬U = V hUi : Ui ∈ (chunk hP G ε (_ : (↑{ val := (U, V), property := (_ : (U, V) ∈ offDiag P.parts) }).fst ∈ P.parts)).parts hVj : Ui ∈ (chunk hP G ε (_ : (↑{ val := (U, V), property := (_ : (U, V) ∈ offDiag P.parts) }).snd ∈ P.parts)).parts ⊢ False [PROOFSTEP] obtain ⟨i, hi⟩ := nonempty_of_mem_parts _ hUi [GOAL] case mk.intro α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ Ui U V : Finset α hUV : U ∈ P.parts ∧ V ∈ P.parts ∧ ¬U = V hUi : Ui ∈ (chunk hP G ε (_ : (↑{ val := (U, V), property := (_ : (U, V) ∈ offDiag P.parts) }).fst ∈ P.parts)).parts hVj : Ui ∈ (chunk hP G ε (_ : (↑{ val := (U, V), property := (_ : (U, V) ∈ offDiag P.parts) }).snd ∈ P.parts)).parts i : α hi : i ∈ Ui ⊢ False [PROOFSTEP] exact hUV.2.2 (P.disjoint.elim_finset hUV.1 hUV.2.1 i (Finpartition.le _ hUi hi) <| Finpartition.le _ hVj hi) [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ ⊢ ∑ x in attach (offDiag P.parts), SzemerediRegularity.pairContrib G ε hP x / ↑(Finset.card (increment hP G ε).parts) ^ 2 ≤ energy (increment hP G ε) G [PROOFSTEP] simp_rw [pairContrib, ← sum_div] [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ ⊢ (∑ x in attach (offDiag P.parts), ∑ i in (chunk hP G ε (_ : (↑x).fst ∈ P.parts)).parts ×ˢ (chunk hP G ε (_ : (↑x).snd ∈ P.parts)).parts, edgeDensity G i.fst i.snd ^ 2) / ↑(Finset.card (increment hP G ε).parts) ^ 2 ≤ energy (increment hP G ε) G [PROOFSTEP] refine' div_le_div_of_le_of_nonneg (α := ℚ) _ (sq_nonneg _) [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ ⊢ ∑ x in attach (offDiag P.parts), ∑ i in (chunk hP G ε (_ : (↑x).fst ∈ P.parts)).parts ×ˢ (chunk hP G ε (_ : (↑x).snd ∈ P.parts)).parts, edgeDensity G i.fst i.snd ^ 2 ≤ ∑ uv in offDiag (increment hP G ε).parts, edgeDensity G uv.fst uv.snd ^ 2 [PROOFSTEP] rw [← sum_biUnion] [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ ⊢ ∑ x in Finset.biUnion (attach (offDiag P.parts)) fun x => (chunk hP G ε (_ : (↑x).fst ∈ P.parts)).parts ×ˢ (chunk hP G ε (_ : (↑x).snd ∈ P.parts)).parts, edgeDensity G x.fst x.snd ^ 2 ≤ ∑ uv in offDiag (increment hP G ε).parts, edgeDensity G uv.fst uv.snd ^ 2 [PROOFSTEP] exact sum_le_sum_of_subset_of_nonneg distinct_pairs_increment fun i _ _ => sq_nonneg _ [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ ⊢ Set.PairwiseDisjoint ↑(attach (offDiag P.parts)) fun x => (chunk hP G ε (_ : (↑x).fst ∈ P.parts)).parts ×ˢ (chunk hP G ε (_ : (↑x).snd ∈ P.parts)).parts [PROOFSTEP] simp only [Set.PairwiseDisjoint, Function.onFun, disjoint_left, inf_eq_inter, mem_inter, mem_product] [GOAL] α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ ⊢ Set.Pairwise ↑(attach (offDiag P.parts)) fun x y => ∀ ⦃a : Finset α × Finset α⦄, a.fst ∈ (chunk hP G ε (_ : (↑x).fst ∈ P.parts)).parts ∧ a.snd ∈ (chunk hP G ε (_ : (↑x).snd ∈ P.parts)).parts → ¬(a.fst ∈ (chunk hP G ε (_ : (↑y).fst ∈ P.parts)).parts ∧ a.snd ∈ (chunk hP G ε (_ : (↑y).snd ∈ P.parts)).parts) [PROOFSTEP] rintro ⟨⟨s₁, s₂⟩, hs⟩ _ ⟨⟨t₁, t₂⟩, ht⟩ _ hst ⟨u, v⟩ huv₁ huv₂ [GOAL] case mk.mk.mk.mk.mk α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ s₁ s₂ : Finset α hs : (s₁, s₂) ∈ offDiag P.parts a✝¹ : { val := (s₁, s₂), property := hs } ∈ ↑(attach (offDiag P.parts)) t₁ t₂ : Finset α ht : (t₁, t₂) ∈ offDiag P.parts a✝ : { val := (t₁, t₂), property := ht } ∈ ↑(attach (offDiag P.parts)) hst : { val := (s₁, s₂), property := hs } ≠ { val := (t₁, t₂), property := ht } u v : Finset α huv₁ : (u, v).fst ∈ (chunk hP G ε (_ : (↑{ val := (s₁, s₂), property := hs }).fst ∈ P.parts)).parts ∧ (u, v).snd ∈ (chunk hP G ε (_ : (↑{ val := (s₁, s₂), property := hs }).snd ∈ P.parts)).parts huv₂ : (u, v).fst ∈ (chunk hP G ε (_ : (↑{ val := (t₁, t₂), property := ht }).fst ∈ P.parts)).parts ∧ (u, v).snd ∈ (chunk hP G ε (_ : (↑{ val := (t₁, t₂), property := ht }).snd ∈ P.parts)).parts ⊢ False [PROOFSTEP] rw [mem_offDiag] at hs ht [GOAL] case mk.mk.mk.mk.mk α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ s₁ s₂ : Finset α hs✝ : (s₁, s₂) ∈ offDiag P.parts hs : (s₁, s₂).fst ∈ P.parts ∧ (s₁, s₂).snd ∈ P.parts ∧ (s₁, s₂).fst ≠ (s₁, s₂).snd a✝¹ : { val := (s₁, s₂), property := hs✝ } ∈ ↑(attach (offDiag P.parts)) t₁ t₂ : Finset α ht✝ : (t₁, t₂) ∈ offDiag P.parts ht : (t₁, t₂).fst ∈ P.parts ∧ (t₁, t₂).snd ∈ P.parts ∧ (t₁, t₂).fst ≠ (t₁, t₂).snd a✝ : { val := (t₁, t₂), property := ht✝ } ∈ ↑(attach (offDiag P.parts)) hst : { val := (s₁, s₂), property := hs✝ } ≠ { val := (t₁, t₂), property := ht✝ } u v : Finset α huv₁ : (u, v).fst ∈ (chunk hP G ε (_ : (↑{ val := (s₁, s₂), property := hs✝ }).fst ∈ P.parts)).parts ∧ (u, v).snd ∈ (chunk hP G ε (_ : (↑{ val := (s₁, s₂), property := hs✝ }).snd ∈ P.parts)).parts huv₂ : (u, v).fst ∈ (chunk hP G ε (_ : (↑{ val := (t₁, t₂), property := ht✝ }).fst ∈ P.parts)).parts ∧ (u, v).snd ∈ (chunk hP G ε (_ : (↑{ val := (t₁, t₂), property := ht✝ }).snd ∈ P.parts)).parts ⊢ False [PROOFSTEP] obtain ⟨a, ha⟩ := Finpartition.nonempty_of_mem_parts _ huv₁.1 [GOAL] case mk.mk.mk.mk.mk.intro α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ s₁ s₂ : Finset α hs✝ : (s₁, s₂) ∈ offDiag P.parts hs : (s₁, s₂).fst ∈ P.parts ∧ (s₁, s₂).snd ∈ P.parts ∧ (s₁, s₂).fst ≠ (s₁, s₂).snd a✝¹ : { val := (s₁, s₂), property := hs✝ } ∈ ↑(attach (offDiag P.parts)) t₁ t₂ : Finset α ht✝ : (t₁, t₂) ∈ offDiag P.parts ht : (t₁, t₂).fst ∈ P.parts ∧ (t₁, t₂).snd ∈ P.parts ∧ (t₁, t₂).fst ≠ (t₁, t₂).snd a✝ : { val := (t₁, t₂), property := ht✝ } ∈ ↑(attach (offDiag P.parts)) hst : { val := (s₁, s₂), property := hs✝ } ≠ { val := (t₁, t₂), property := ht✝ } u v : Finset α huv₁ : (u, v).fst ∈ (chunk hP G ε (_ : (↑{ val := (s₁, s₂), property := hs✝ }).fst ∈ P.parts)).parts ∧ (u, v).snd ∈ (chunk hP G ε (_ : (↑{ val := (s₁, s₂), property := hs✝ }).snd ∈ P.parts)).parts huv₂ : (u, v).fst ∈ (chunk hP G ε (_ : (↑{ val := (t₁, t₂), property := ht✝ }).fst ∈ P.parts)).parts ∧ (u, v).snd ∈ (chunk hP G ε (_ : (↑{ val := (t₁, t₂), property := ht✝ }).snd ∈ P.parts)).parts a : α ha : a ∈ (u, v).fst ⊢ False [PROOFSTEP] obtain ⟨b, hb⟩ := Finpartition.nonempty_of_mem_parts _ huv₁.2 [GOAL] case mk.mk.mk.mk.mk.intro.intro α : Type u_1 inst✝ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ s₁ s₂ : Finset α hs✝ : (s₁, s₂) ∈ offDiag P.parts hs : (s₁, s₂).fst ∈ P.parts ∧ (s₁, s₂).snd ∈ P.parts ∧ (s₁, s₂).fst ≠ (s₁, s₂).snd a✝¹ : { val := (s₁, s₂), property := hs✝ } ∈ ↑(attach (offDiag P.parts)) t₁ t₂ : Finset α ht✝ : (t₁, t₂) ∈ offDiag P.parts ht : (t₁, t₂).fst ∈ P.parts ∧ (t₁, t₂).snd ∈ P.parts ∧ (t₁, t₂).fst ≠ (t₁, t₂).snd a✝ : { val := (t₁, t₂), property := ht✝ } ∈ ↑(attach (offDiag P.parts)) hst : { val := (s₁, s₂), property := hs✝ } ≠ { val := (t₁, t₂), property := ht✝ } u v : Finset α huv₁ : (u, v).fst ∈ (chunk hP G ε (_ : (↑{ val := (s₁, s₂), property := hs✝ }).fst ∈ P.parts)).parts ∧ (u, v).snd ∈ (chunk hP G ε (_ : (↑{ val := (s₁, s₂), property := hs✝ }).snd ∈ P.parts)).parts huv₂ : (u, v).fst ∈ (chunk hP G ε (_ : (↑{ val := (t₁, t₂), property := ht✝ }).fst ∈ P.parts)).parts ∧ (u, v).snd ∈ (chunk hP G ε (_ : (↑{ val := (t₁, t₂), property := ht✝ }).snd ∈ P.parts)).parts a : α ha : a ∈ (u, v).fst b : α hb : b ∈ (u, v).snd ⊢ False [PROOFSTEP] exact hst (Subtype.ext_val <| Prod.ext (P.disjoint.elim_finset hs.1 ht.1 a (Finpartition.le _ huv₁.1 ha) <| Finpartition.le _ huv₂.1 ha) <| P.disjoint.elim_finset hs.2.1 ht.2.1 b (Finpartition.le _ huv₁.2 hb) <| Finpartition.le _ huv₂.2 hb) [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α x : { i // i ∈ offDiag P.parts } hε₁ : ε ≤ 1 hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 ⊢ (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) ≤ ↑(SzemerediRegularity.pairContrib G ε hP x) / 16 ^ Finset.card P.parts [PROOFSTEP] rw [pairContrib] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α x : { i // i ∈ offDiag P.parts } hε₁ : ε ≤ 1 hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 ⊢ (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) ≤ ↑(∑ i in (chunk hP G ε (_ : (↑x).fst ∈ P.parts)).parts ×ˢ (chunk hP G ε (_ : (↑x).snd ∈ P.parts)).parts, edgeDensity G i.fst i.snd ^ 2) / 16 ^ Finset.card P.parts [PROOFSTEP] push_cast [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α x : { i // i ∈ offDiag P.parts } hε₁ : ε ≤ 1 hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 ⊢ (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) ≤ (∑ x in (chunk hP G ε (_ : (↑x).fst ∈ P.parts)).parts ×ˢ (chunk hP G ε (_ : (↑x).snd ∈ P.parts)).parts, ↑(edgeDensity G x.fst x.snd) ^ 2) / 16 ^ Finset.card P.parts [PROOFSTEP] split_ifs with h [GOAL] case pos α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α x : { i // i ∈ offDiag P.parts } hε₁ : ε ≤ 1 hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 h : SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd ⊢ ↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + 0 ≤ (∑ x in (chunk hP G ε (_ : (↑x).fst ∈ P.parts)).parts ×ˢ (chunk hP G ε (_ : (↑x).snd ∈ P.parts)).parts, ↑(edgeDensity G x.fst x.snd) ^ 2) / 16 ^ Finset.card P.parts [PROOFSTEP] rw [add_zero] [GOAL] case pos α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α x : { i // i ∈ offDiag P.parts } hε₁ : ε ≤ 1 hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 h : SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd ⊢ ↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 ≤ (∑ x in (chunk hP G ε (_ : (↑x).fst ∈ P.parts)).parts ×ˢ (chunk hP G ε (_ : (↑x).snd ∈ P.parts)).parts, ↑(edgeDensity G x.fst x.snd) ^ 2) / 16 ^ Finset.card P.parts [PROOFSTEP] exact edgeDensity_chunk_uniform hPα hPε _ _ [GOAL] case neg α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α x : { i // i ∈ offDiag P.parts } hε₁ : ε ≤ 1 hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 h : ¬SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd ⊢ ↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + ε ^ 4 / 3 ≤ (∑ x in (chunk hP G ε (_ : (↑x).fst ∈ P.parts)).parts ×ˢ (chunk hP G ε (_ : (↑x).snd ∈ P.parts)).parts, ↑(edgeDensity G x.fst x.snd) ^ 2) / 16 ^ Finset.card P.parts [PROOFSTEP] exact edgeDensity_chunk_not_uniform hPα hPε hε₁ (mem_offDiag.1 x.2).2.2 h [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε ⊢ (∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 + ↑(Finset.card P.parts) ^ 2 * (ε ^ 5 / 4)) / ↑(Finset.card P.parts) ^ 2 ≤ ∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / ↑(Finset.card (increment hP G ε).parts) ^ 2 [PROOFSTEP] conv_rhs => rw [← sum_div, card_increment hPα hPG, stepBound, ← Nat.cast_pow, mul_pow, pow_right_comm, Nat.cast_mul, mul_comm, ← div_div, show 4 ^ 2 = 16 by norm_num, sum_div] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε | ∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / ↑(Finset.card (increment hP G ε).parts) ^ 2 [PROOFSTEP] rw [← sum_div, card_increment hPα hPG, stepBound, ← Nat.cast_pow, mul_pow, pow_right_comm, Nat.cast_mul, mul_comm, ← div_div, show 4 ^ 2 = 16 by norm_num, sum_div] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε | ∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / ↑(Finset.card (increment hP G ε).parts) ^ 2 [PROOFSTEP] rw [← sum_div, card_increment hPα hPG, stepBound, ← Nat.cast_pow, mul_pow, pow_right_comm, Nat.cast_mul, mul_comm, ← div_div, show 4 ^ 2 = 16 by norm_num, sum_div] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε | ∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / ↑(Finset.card (increment hP G ε).parts) ^ 2 [PROOFSTEP] rw [← sum_div, card_increment hPα hPG, stepBound, ← Nat.cast_pow, mul_pow, pow_right_comm, Nat.cast_mul, mul_comm, ← div_div, show 4 ^ 2 = 16 by norm_num, sum_div] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε ⊢ 4 ^ 2 = 16 [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε ⊢ (∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 + ↑(Finset.card P.parts) ^ 2 * (ε ^ 5 / 4)) / ↑(Finset.card P.parts) ^ 2 ≤ (∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / ↑(16 ^ Finset.card P.parts)) / ↑(Finset.card P.parts ^ 2) [PROOFSTEP] rw [← Nat.cast_pow, Nat.cast_pow 16] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε ⊢ (∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 + ↑(Finset.card P.parts ^ 2) * (ε ^ 5 / 4)) / ↑(Finset.card P.parts ^ 2) ≤ (∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / ↑16 ^ Finset.card P.parts) / ↑(Finset.card P.parts ^ 2) [PROOFSTEP] refine' div_le_div_of_le_of_nonneg _ (Nat.cast_nonneg _) [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε ⊢ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 + ↑(Finset.card P.parts ^ 2) * (ε ^ 5 / 4) ≤ ∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / ↑16 ^ Finset.card P.parts [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε ⊢ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 + ↑(Finset.card P.parts) ^ 2 * (ε ^ 5 / 4) ≤ ∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / 16 ^ Finset.card P.parts [PROOFSTEP] trans ∑ x in P.parts.offDiag.attach, ((G.edgeDensity x.1.1 x.1.2 : ℝ) ^ 2 - ε ^ 5 / ↑25 + if G.IsUniform ε x.1.1 x.1.2 then (0 : ℝ) else ε ^ 4 / 3 : ℝ) [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε ⊢ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 + ↑(Finset.card P.parts) ^ 2 * (ε ^ 5 / 4) ≤ ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε ⊢ ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) ≤ ∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / 16 ^ Finset.card P.parts [PROOFSTEP] swap [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε ⊢ ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) ≤ ∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / 16 ^ Finset.card P.parts [PROOFSTEP] exact sum_le_sum fun i _ => pairContrib_lower_bound i hε₁ hPα hPε [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε ⊢ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 + ↑(Finset.card P.parts) ^ 2 * (ε ^ 5 / 4) ≤ ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) [PROOFSTEP] have : ∑ x in P.parts.offDiag.attach, ((G.edgeDensity x.1.1 x.1.2 : ℝ) ^ 2 - ε ^ 5 / ↑25 + if G.IsUniform ε x.1.1 x.1.2 then (0 : ℝ) else ε ^ 4 / 3 : ℝ) = ∑ x in P.parts.offDiag, ((G.edgeDensity x.1 x.2 : ℝ) ^ 2 - ε ^ 5 / ↑25 + if G.IsUniform ε x.1 x.2 then (0 : ℝ) else ε ^ 4 / 3) := by convert sum_attach (β := ℝ); rfl [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε ⊢ ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) [PROOFSTEP] convert sum_attach (β := ℝ) [GOAL] case h.e'_2.a α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε x✝ : { x // x ∈ offDiag P.parts } a✝ : x✝ ∈ attach (offDiag P.parts) ⊢ (↑(edgeDensity G (↑x✝).fst (↑x✝).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x✝).fst (↑x✝).snd then 0 else ε ^ 4 / 3) = ↑(edgeDensity G (↑x✝).fst (↑x✝).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x✝).fst (↑x✝).snd then 0 else ε ^ 4 / 3 [PROOFSTEP] rfl [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) ⊢ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 + ↑(Finset.card P.parts) ^ 2 * (ε ^ 5 / 4) ≤ ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) [PROOFSTEP] rw [this, sum_add_distrib, sum_sub_distrib, sum_const, nsmul_eq_mul, sum_ite, sum_const_zero, zero_add, sum_const, nsmul_eq_mul, ← Finpartition.nonUniforms] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ¬Finpartition.IsUniform P G ε this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) ⊢ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 + ↑(Finset.card P.parts) ^ 2 * (ε ^ 5 / 4) ≤ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 - ↑(Finset.card (offDiag P.parts)) * (ε ^ 5 / 25) + ↑(Finset.card (nonUniforms P G ε)) * (ε ^ 4 / 3) [PROOFSTEP] rw [Finpartition.IsUniform, not_le] at hPG [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) ⊢ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 + ↑(Finset.card P.parts) ^ 2 * (ε ^ 5 / 4) ≤ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 - ↑(Finset.card (offDiag P.parts)) * (ε ^ 5 / 25) + ↑(Finset.card (nonUniforms P G ε)) * (ε ^ 4 / 3) [PROOFSTEP] refine' le_trans _ (add_le_add_left (mul_le_mul_of_nonneg_right hPG.le <| by positivity) _) [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) ⊢ 0 ≤ ε ^ 4 / 3 [PROOFSTEP] positivity [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) ⊢ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 + ↑(Finset.card P.parts) ^ 2 * (ε ^ 5 / 4) ≤ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 - ↑(Finset.card (offDiag P.parts)) * (ε ^ 5 / 25) + ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε * (ε ^ 4 / 3) [PROOFSTEP] conv_rhs => enter [1, 2] rw [offDiag_card] conv => enter [1, 1, 2]; rw [← mul_one P.parts.card] rw [← Nat.mul_sub_left_distrib] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) | ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 - ↑(Finset.card (offDiag P.parts)) * (ε ^ 5 / 25) + ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε * (ε ^ 4 / 3) [PROOFSTEP] enter [1, 2] rw [offDiag_card] conv => enter [1, 1, 2]; rw [← mul_one P.parts.card] rw [← Nat.mul_sub_left_distrib] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) | ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 - ↑(Finset.card (offDiag P.parts)) * (ε ^ 5 / 25) + ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε * (ε ^ 4 / 3) [PROOFSTEP] enter [1, 2] rw [offDiag_card] conv => enter [1, 1, 2]; rw [← mul_one P.parts.card] rw [← Nat.mul_sub_left_distrib] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) | ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 - ↑(Finset.card (offDiag P.parts)) * (ε ^ 5 / 25) + ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε * (ε ^ 4 / 3) [PROOFSTEP] enter [1, 2] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) | ↑(Finset.card (offDiag P.parts)) * (ε ^ 5 / 25) [PROOFSTEP] rw [offDiag_card] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) | ↑(Finset.card P.parts * Finset.card P.parts - Finset.card P.parts) * (ε ^ 5 / 25) [PROOFSTEP] conv => enter [1, 1, 2]; rw [← mul_one P.parts.card] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) | ↑(Finset.card P.parts * Finset.card P.parts - Finset.card P.parts) * (ε ^ 5 / 25) [PROOFSTEP] enter [1, 1, 2]; rw [← mul_one P.parts.card] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) | ↑(Finset.card P.parts * Finset.card P.parts - Finset.card P.parts) * (ε ^ 5 / 25) [PROOFSTEP] enter [1, 1, 2] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) | Finset.card P.parts [PROOFSTEP] rw [← mul_one P.parts.card] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) | ↑(Finset.card P.parts * Finset.card P.parts - Finset.card P.parts * 1) * (ε ^ 5 / 25) [PROOFSTEP] rw [← Nat.mul_sub_left_distrib] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) ⊢ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 + ↑(Finset.card P.parts) ^ 2 * (ε ^ 5 / 4) ≤ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 - ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * (ε ^ 5 / 25) + ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε * (ε ^ 4 / 3) [PROOFSTEP] simp_rw [mul_assoc, sub_add_eq_add_sub, add_sub_assoc, ← mul_sub_left_distrib, mul_div_assoc' ε, ← pow_succ, show 4 + 1 = 5 by rfl, div_eq_mul_one_div (ε ^ 5), ← mul_sub_left_distrib, mul_left_comm _ (ε ^ 5), sq, Nat.cast_mul, mul_assoc, ← mul_assoc (ε ^ 5)] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) ⊢ 4 + 1 = 5 [PROOFSTEP] rfl [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) ⊢ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) * ↑(edgeDensity G x.fst x.snd) + ε ^ 5 * ↑(Finset.card P.parts) * (↑(Finset.card P.parts) * (1 / 4)) ≤ ∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) * ↑(edgeDensity G x.fst x.snd) + ε ^ 5 * ↑(Finset.card P.parts) * (↑(Finset.card P.parts - 1) * (1 / 3 - 1 / 25)) [PROOFSTEP] refine' add_le_add_left (mul_le_mul_of_nonneg_left _ <| by sz_positivity) _ [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) ⊢ 0 ≤ ε ^ 5 * ↑(Finset.card P.parts) [PROOFSTEP] sz_positivity [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) ⊢ ↑(Finset.card P.parts) * (1 / 4) ≤ ↑(Finset.card P.parts - 1) * (1 / 3 - 1 / 25) [PROOFSTEP] rw [Nat.cast_sub (P.parts_nonempty <| univ_nonempty.ne_empty).card_pos, mul_sub_right_distrib, Nat.cast_one, one_mul, le_sub_comm, ← mul_sub_left_distrib, ← div_le_iff (show (0 : ℝ) < 1 / 3 - 1 / 25 - 1 / 4 by norm_num)] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) ⊢ 0 < 1 / 3 - 1 / 25 - 1 / 4 [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) ⊢ (1 / 3 - 1 / 25) / (1 / 3 - 1 / 25 - 1 / 4) ≤ ↑(Finset.card P.parts) [PROOFSTEP] exact le_trans (show _ ≤ (7 : ℝ) by norm_num) (by exact_mod_cast hP₇) [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) ⊢ (1 / 3 - 1 / 25) / (1 / 3 - 1 / 25 - 1 / 4) ≤ 7 [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hε₁ : ε ≤ 1 hP₇ : 7 ≤ Finset.card P.parts hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : 100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hPG : ↑(Finset.card P.parts * (Finset.card P.parts - 1)) * ε < ↑(Finset.card (nonUniforms P G ε)) this : ∑ x in attach (offDiag P.parts), (↑(edgeDensity G (↑x).fst (↑x).snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε (↑x).fst (↑x).snd then 0 else ε ^ 4 / 3) = ∑ x in offDiag P.parts, (↑(edgeDensity G x.fst x.snd) ^ 2 - ε ^ 5 / 25 + if SimpleGraph.IsUniform G ε x.fst x.snd then 0 else ε ^ 4 / 3) ⊢ 7 ≤ ↑(Finset.card P.parts) [PROOFSTEP] exact_mod_cast hP₇ [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP✝ : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hP : IsEquipartition P hP₇ : 7 ≤ Finset.card P.parts hε : 100 < 4 ^ Finset.card P.parts * ε ^ 5 hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hε₁ : ε ≤ 1 ⊢ ↑(energy P G) + ε ^ 5 / 4 ≤ ↑(energy (increment hP G ε) G) [PROOFSTEP] rw [coe_energy] [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP✝ : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hP : IsEquipartition P hP₇ : 7 ≤ Finset.card P.parts hε : 100 < 4 ^ Finset.card P.parts * ε ^ 5 hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hε₁ : ε ≤ 1 ⊢ (∑ uv in offDiag P.parts, ↑(edgeDensity G uv.fst uv.snd) ^ 2) / ↑(Finset.card P.parts) ^ 2 + ε ^ 5 / 4 ≤ ↑(energy (increment hP G ε) G) [PROOFSTEP] have h := uniform_add_nonuniform_eq_offDiag_pairs (hP := hP) hε₁ hP₇ hPα hε.le hPG [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP✝ : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hP : IsEquipartition P hP₇ : 7 ≤ Finset.card P.parts hε : 100 < 4 ^ Finset.card P.parts * ε ^ 5 hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hε₁ : ε ≤ 1 h : (∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2 + ↑(Finset.card P.parts) ^ 2 * (ε ^ 5 / 4)) / ↑(Finset.card P.parts) ^ 2 ≤ ∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / ↑(Finset.card (increment hP G ε).parts) ^ 2 ⊢ (∑ uv in offDiag P.parts, ↑(edgeDensity G uv.fst uv.snd) ^ 2) / ↑(Finset.card P.parts) ^ 2 + ε ^ 5 / 4 ≤ ↑(energy (increment hP G ε) G) [PROOFSTEP] rw [add_div, mul_div_cancel_left] at h [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP✝ : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hP : IsEquipartition P hP₇ : 7 ≤ Finset.card P.parts hε : 100 < 4 ^ Finset.card P.parts * ε ^ 5 hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hε₁ : ε ≤ 1 h : (∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2) / ↑(Finset.card P.parts) ^ 2 + ε ^ 5 / 4 ≤ ∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / ↑(Finset.card (increment hP G ε).parts) ^ 2 ⊢ (∑ uv in offDiag P.parts, ↑(edgeDensity G uv.fst uv.snd) ^ 2) / ↑(Finset.card P.parts) ^ 2 + ε ^ 5 / 4 ≤ ↑(energy (increment hP G ε) G) case ha α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP✝ : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hP : IsEquipartition P hP₇ : 7 ≤ Finset.card P.parts hε : 100 < 4 ^ Finset.card P.parts * ε ^ 5 hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hε₁ : ε ≤ 1 h : (∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2) / ↑(Finset.card P.parts) ^ 2 + ↑(Finset.card P.parts) ^ 2 * (ε ^ 5 / 4) / ↑(Finset.card P.parts) ^ 2 ≤ ∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / ↑(Finset.card (increment hP G ε).parts) ^ 2 ⊢ ↑(Finset.card P.parts) ^ 2 ≠ 0 [PROOFSTEP] exact h.trans (by exact_mod_cast offDiag_pairs_le_increment_energy) [GOAL] α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP✝ : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hP : IsEquipartition P hP₇ : 7 ≤ Finset.card P.parts hε : 100 < 4 ^ Finset.card P.parts * ε ^ 5 hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hε₁ : ε ≤ 1 h : (∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2) / ↑(Finset.card P.parts) ^ 2 + ε ^ 5 / 4 ≤ ∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / ↑(Finset.card (increment hP G ε).parts) ^ 2 ⊢ ∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / ↑(Finset.card (increment hP G ε).parts) ^ 2 ≤ ↑(energy (increment hP G ε) G) [PROOFSTEP] exact_mod_cast offDiag_pairs_le_increment_energy [GOAL] case ha α : Type u_1 inst✝¹ : Fintype α P : Finpartition univ hP✝ : IsEquipartition P G : SimpleGraph α ε : ℝ inst✝ : Nonempty α hP : IsEquipartition P hP₇ : 7 ≤ Finset.card P.parts hε : 100 < 4 ^ Finset.card P.parts * ε ^ 5 hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPG : ¬Finpartition.IsUniform P G ε hε₁ : ε ≤ 1 h : (∑ x in offDiag P.parts, ↑(edgeDensity G x.fst x.snd) ^ 2) / ↑(Finset.card P.parts) ^ 2 + ↑(Finset.card P.parts) ^ 2 * (ε ^ 5 / 4) / ↑(Finset.card P.parts) ^ 2 ≤ ∑ x in attach (offDiag P.parts), ↑(SzemerediRegularity.pairContrib G ε hP x) / ↑(Finset.card (increment hP G ε).parts) ^ 2 ⊢ ↑(Finset.card P.parts) ^ 2 ≠ 0 [PROOFSTEP] positivity
lemma measure_of_eq: assumes closed: "A \<subseteq> Pow \<Omega>" and eq: "(\<And>a. a \<in> sigma_sets \<Omega> A \<Longrightarrow> \<mu> a = \<mu>' a)" shows "measure_of \<Omega> A \<mu> = measure_of \<Omega> A \<mu>'"
[STATEMENT] lemma loc_env_simps[simp]: "loc [] = []" "env [] = []" [PROOF STATE] proof (prove) goal (1 subgoal): 1. loc [] = [] &&& env [] = [] [PROOF STEP] by (unfold loc_def env_def) auto
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker, Aaron Anderson -/ import algebra.big_operators.associated import algebra.gcd_monoid.basic import data.finsupp.multiset import ring_theory.noetherian import ring_theory.multiplicity /-! # Unique factorization ## Main Definitions * `wf_dvd_monoid` holds for `monoid`s for which a strict divisibility relation is well-founded. * `unique_factorization_monoid` holds for `wf_dvd_monoid`s where `irreducible` is equivalent to `prime` ## To do * set up the complete lattice structure on `factor_set`. -/ variables {α : Type*} local infix ` ~ᵤ ` : 50 := associated /-- Well-foundedness of the strict version of |, which is equivalent to the descending chain condition on divisibility and to the ascending chain condition on principal ideals in an integral domain. -/ class wf_dvd_monoid (α : Type*) [comm_monoid_with_zero α] : Prop := (well_founded_dvd_not_unit : well_founded (@dvd_not_unit α _)) export wf_dvd_monoid (well_founded_dvd_not_unit) @[priority 100] -- see Note [lower instance priority] instance is_noetherian_ring.wf_dvd_monoid [comm_ring α] [is_domain α] [is_noetherian_ring α] : wf_dvd_monoid α := ⟨by { convert inv_image.wf (λ a, ideal.span ({a} : set α)) (well_founded_submodule_gt _ _), ext, exact ideal.span_singleton_lt_span_singleton.symm }⟩ namespace wf_dvd_monoid variables [comm_monoid_with_zero α] open associates nat theorem of_wf_dvd_monoid_associates (h : wf_dvd_monoid (associates α)): wf_dvd_monoid α := ⟨begin haveI := h, refine (surjective.well_founded_iff mk_surjective _).2 wf_dvd_monoid.well_founded_dvd_not_unit, intros, rw mk_dvd_not_unit_mk_iff end⟩ variables [wf_dvd_monoid α] instance wf_dvd_monoid_associates : wf_dvd_monoid (associates α) := ⟨begin refine (surjective.well_founded_iff mk_surjective _).1 wf_dvd_monoid.well_founded_dvd_not_unit, intros, rw mk_dvd_not_unit_mk_iff end⟩ theorem well_founded_associates : well_founded ((<) : associates α → associates α → Prop) := subrelation.wf (λ x y, dvd_not_unit_of_lt) wf_dvd_monoid.well_founded_dvd_not_unit local attribute [elab_as_eliminator] well_founded.fix lemma exists_irreducible_factor {a : α} (ha : ¬ is_unit a) (ha0 : a ≠ 0) : ∃ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_rfl⟩) (well_founded.fix wf_dvd_monoid.well_founded_dvd_not_unit (λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (λ hxi, ⟨x, hxi, hxy ▸ by simp⟩) (λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, hi.2.trans (hxy ▸ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma induction_on_irreducible {P : α → Prop} (a : α) (h0 : P 0) (hu : ∀ u : α, is_unit u → P u) (hi : ∀ a i : α, a ≠ 0 → irreducible i → P a → P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix wf_dvd_monoid.well_founded_dvd_not_unit (λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b ≠ 0, from λ hb0, by simp * at *, hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : α) : a ≠ 0 → ∃f : multiset α, (∀b ∈ f, irreducible b) ∧ associated f.prod a := wf_dvd_monoid.induction_on_irreducible a (λ h, (h rfl).elim) (λ u hu _, ⟨0, ⟨by simp [hu], associated.symm (by simp [hu, associated_one_iff_is_unit])⟩⟩) (λ a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i ::ₘ s, ⟨by clear _let_match; { intros b H, cases (multiset.mem_cons.mp H), { convert hii }, { exact hs.1 b h } }, by { rw multiset.prod_cons, exact hs.2.mul_left _ }⟩⟩) end wf_dvd_monoid theorem wf_dvd_monoid.of_well_founded_associates [cancel_comm_monoid_with_zero α] (h : well_founded ((<) : associates α → associates α → Prop)) : wf_dvd_monoid α := wf_dvd_monoid.of_wf_dvd_monoid_associates ⟨by { convert h, ext, exact associates.dvd_not_unit_iff_lt }⟩ theorem wf_dvd_monoid.iff_well_founded_associates [cancel_comm_monoid_with_zero α] : wf_dvd_monoid α ↔ well_founded ((<) : associates α → associates α → Prop) := ⟨by apply wf_dvd_monoid.well_founded_associates, wf_dvd_monoid.of_well_founded_associates⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- unique factorization monoids. These are defined as `cancel_comm_monoid_with_zero`s with well-founded strict divisibility relations, but this is equivalent to more familiar definitions: Each element (except zero) is uniquely represented as a multiset of irreducible factors. Uniqueness is only up to associated elements. Each element (except zero) is non-uniquely represented as a multiset of prime factors. To define a UFD using the definition in terms of multisets of irreducible factors, use the definition `of_exists_unique_irreducible_factors` To define a UFD using the definition in terms of multisets of prime factors, use the definition `of_exists_prime_factors` -/ class unique_factorization_monoid (α : Type*) [cancel_comm_monoid_with_zero α] extends wf_dvd_monoid α : Prop := (irreducible_iff_prime : ∀ {a : α}, irreducible a ↔ prime a) /-- Can't be an instance because it would cause a loop `ufm → wf_dvd_monoid → ufm → ...`. -/ @[reducible] lemma ufm_of_gcd_of_wf_dvd_monoid [cancel_comm_monoid_with_zero α] [wf_dvd_monoid α] [gcd_monoid α] : unique_factorization_monoid α := { irreducible_iff_prime := λ _, gcd_monoid.irreducible_iff_prime .. ‹wf_dvd_monoid α› } instance associates.ufm [cancel_comm_monoid_with_zero α] [unique_factorization_monoid α] : unique_factorization_monoid (associates α) := { irreducible_iff_prime := by { rw ← associates.irreducible_iff_prime_iff, apply unique_factorization_monoid.irreducible_iff_prime, } .. (wf_dvd_monoid.wf_dvd_monoid_associates : wf_dvd_monoid (associates α)) } end prio namespace unique_factorization_monoid variables [cancel_comm_monoid_with_zero α] [unique_factorization_monoid α] theorem exists_prime_factors (a : α) : a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a := by { simp_rw ← unique_factorization_monoid.irreducible_iff_prime, apply wf_dvd_monoid.exists_factors a } @[elab_as_eliminator] lemma induction_on_prime {P : α → Prop} (a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x) (h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a := begin simp_rw ← unique_factorization_monoid.irreducible_iff_prime at h₃, exact wf_dvd_monoid.induction_on_irreducible a h₁ h₂ h₃, end lemma factors_unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).not_unit (is_unit_iff_dvd_one.2 ((multiset.dvd_prod hx).trans (is_unit_iff_dvd_one.1 this))))) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (irreducible_iff_prime.1 (hf p (by simp))) (λ q hq, irreducible_iff_prime.1 (hg _ hq)) $ hfg.dvd_iff_dvd_right.1 (show p ∣ (p ::ₘ f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated.of_mul_left (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)) end) end unique_factorization_monoid lemma prime_factors_unique [cancel_comm_monoid_with_zero α] : ∀ {f g : multiset α}, (∀ x ∈ f, prime x) → (∀ x ∈ g, prime x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem $ λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).not_unit $ is_unit_iff_dvd_one.2 $ (multiset.dvd_prod hx).trans (is_unit_iff_dvd_one.1 this)) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (hf p (by simp)) (λ q hq, hg _ hq) $ hfg.dvd_iff_dvd_right.1 (show p ∣ (p ::ₘ f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated.of_mul_left (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)), end) /-- If an irreducible has a prime factorization, then it is an associate of one of its prime factors. -/ lemma prime_factors_irreducible [cancel_comm_monoid_with_zero α] {a : α} {f : multiset α} (ha : irreducible a) (pfa : (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) : ∃ p, a ~ᵤ p ∧ f = {p} := begin haveI := classical.dec_eq α, refine multiset.induction_on f (λ h, (ha.not_unit (associated_one_iff_is_unit.1 (associated.symm h))).elim) _ pfa.2 pfa.1, rintros p s _ ⟨u, hu⟩ hs, use p, have hs0 : s = 0, { by_contra hs0, obtain ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0, apply (hs q (by simp [hq])).2.1, refine (ha.is_unit_or_is_unit (_ : _ = ((p * ↑u) * (s.erase q).prod) * _)).resolve_left _, { rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq, ← hu, mul_comm, mul_comm p _, mul_assoc], simp, }, apply mt is_unit_of_mul_is_unit_left (mt is_unit_of_mul_is_unit_left _), apply (hs p (multiset.mem_cons_self _ _)).2.1 }, simp only [mul_one, multiset.prod_cons, multiset.prod_zero, hs0] at *, exact ⟨associated.symm ⟨u, hu⟩, rfl⟩, end section exists_prime_factors variables [cancel_comm_monoid_with_zero α] variables (pf : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) include pf lemma wf_dvd_monoid.of_exists_prime_factors : wf_dvd_monoid α := ⟨begin classical, refine rel_hom_class.well_founded (rel_hom.mk _ _ : (dvd_not_unit : α → α → Prop) →r ((<) : with_top ℕ → with_top ℕ → Prop)) (with_top.well_founded_lt nat.lt_wf), { intro a, by_cases h : a = 0, { exact ⊤ }, exact (classical.some (pf a h)).card }, rintros a b ⟨ane0, ⟨c, hc, b_eq⟩⟩, rw dif_neg ane0, by_cases h : b = 0, { simp [h, lt_top_iff_ne_top] }, rw [dif_neg h, with_top.coe_lt_coe], have cne0 : c ≠ 0, { refine mt (λ con, _) h, rw [b_eq, con, mul_zero] }, calc multiset.card (classical.some (pf a ane0)) < _ + multiset.card (classical.some (pf c cne0)) : lt_add_of_pos_right _ (multiset.card_pos.mpr (λ con, hc (associated_one_iff_is_unit.mp _))) ... = multiset.card (classical.some (pf a ane0) + classical.some (pf c cne0)) : (multiset.card_add _ _).symm ... = multiset.card (classical.some (pf b h)) : multiset.card_eq_card_of_rel (prime_factors_unique _ (classical.some_spec (pf _ h)).1 _), { convert (classical.some_spec (pf c cne0)).2.symm, rw [con, multiset.prod_zero] }, { intros x hadd, rw multiset.mem_add at hadd, cases hadd; apply (classical.some_spec (pf _ _)).1 _ hadd }, { rw multiset.prod_add, transitivity a * c, { apply associated.mul_mul; apply (classical.some_spec (pf _ _)).2 }, { rw ← b_eq, apply (classical.some_spec (pf _ _)).2.symm, } } end⟩ lemma irreducible_iff_prime_of_exists_prime_factors {p : α} : irreducible p ↔ prime p := begin by_cases hp0 : p = 0, { simp [hp0] }, refine ⟨λ h, _, prime.irreducible⟩, obtain ⟨f, hf⟩ := pf p hp0, obtain ⟨q, hq, rfl⟩ := prime_factors_irreducible h hf, rw hq.prime_iff, exact hf.1 q (multiset.mem_singleton_self _) end theorem unique_factorization_monoid.of_exists_prime_factors : unique_factorization_monoid α := { irreducible_iff_prime := λ _, irreducible_iff_prime_of_exists_prime_factors pf, .. wf_dvd_monoid.of_exists_prime_factors pf } end exists_prime_factors theorem unique_factorization_monoid.iff_exists_prime_factors [cancel_comm_monoid_with_zero α] : unique_factorization_monoid α ↔ (∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) := ⟨λ h, @unique_factorization_monoid.exists_prime_factors _ _ h, unique_factorization_monoid.of_exists_prime_factors⟩ theorem irreducible_iff_prime_of_exists_unique_irreducible_factors [cancel_comm_monoid_with_zero α] (eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a) (uif : ∀ (f g : multiset α), (∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) (p : α) : irreducible p ↔ prime p := ⟨by letI := classical.dec_eq α; exact λ hpi, ⟨hpi.ne_zero, hpi.1, λ a b ⟨x, hx⟩, if hab0 : a * b = 0 then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim (λ ha0, by simp [ha0]) (λ hb0, by simp [hb0]) else have hx0 : x ≠ 0, from λ hx0, by simp * at *, have ha0 : a ≠ 0, from left_ne_zero_of_mul hab0, have hb0 : b ≠ 0, from right_ne_zero_of_mul hab0, begin cases eif x hx0 with fx hfx, cases eif a ha0 with fa hfa, cases eif b hb0 with fb hfb, have h : multiset.rel associated (p ::ₘ fx) (fa + fb), { apply uif, { exact λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (hfx.1 _), }, { exact λ i hi, (multiset.mem_add.1 hi).elim (hfa.1 _) (hfb.1 _), }, calc multiset.prod (p ::ₘ fx) ~ᵤ a * b : by rw [hx, multiset.prod_cons]; exact hfx.2.mul_left _ ... ~ᵤ (fa).prod * (fb).prod : hfa.2.symm.mul_mul hfb.2.symm ... = _ : by rw multiset.prod_add, }, exact let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem h (multiset.mem_cons_self p _) in (multiset.mem_add.1 hqf).elim (λ hqa, or.inl $ hq.dvd_iff_dvd_left.2 $ hfa.2.dvd_iff_dvd_right.1 (multiset.dvd_prod hqa)) (λ hqb, or.inr $ hq.dvd_iff_dvd_left.2 $ hfb.2.dvd_iff_dvd_right.1 (multiset.dvd_prod hqb)) end⟩, prime.irreducible⟩ theorem unique_factorization_monoid.of_exists_unique_irreducible_factors [cancel_comm_monoid_with_zero α] (eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a) (uif : ∀ (f g : multiset α), (∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) : unique_factorization_monoid α := unique_factorization_monoid.of_exists_prime_factors (by { convert eif, simp_rw irreducible_iff_prime_of_exists_unique_irreducible_factors eif uif }) namespace unique_factorization_monoid variables [cancel_comm_monoid_with_zero α] [decidable_eq α] variables [unique_factorization_monoid α] /-- Noncomputably determines the multiset of prime factors. -/ noncomputable def factors (a : α) : multiset α := if h : a = 0 then 0 else classical.some (unique_factorization_monoid.exists_prime_factors a h) theorem factors_prod {a : α} (ane0 : a ≠ 0) : associated (factors a).prod a := begin rw [factors, dif_neg ane0], exact (classical.some_spec (exists_prime_factors a ane0)).2 end theorem prime_of_factor {a : α} : ∀ (x : α), x ∈ factors a → prime x := begin rw [factors], split_ifs with ane0, { simp only [multiset.not_mem_zero, forall_false_left, forall_const] }, intros x hx, exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 x hx, end theorem irreducible_of_factor {a : α} : ∀ (x : α), x ∈ factors a → irreducible x := λ x h, (prime_of_factor x h).irreducible lemma exists_mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ q ∈ factors a, p ~ᵤ q := λ ⟨b, hb⟩, have hb0 : b ≠ 0, from λ hb0, by simp * at *, have multiset.rel associated (p ::ₘ factors b) (factors a), from factors_unique (λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_of_factor _)) irreducible_of_factor (associated.symm $ calc multiset.prod (factors a) ~ᵤ a : factors_prod ha0 ... = p * b : hb ... ~ᵤ multiset.prod (p ::ₘ factors b) : by rw multiset.prod_cons; exact (factors_prod hb0).symm.mul_left _), multiset.exists_mem_of_rel_of_mem this (by simp) end unique_factorization_monoid namespace unique_factorization_monoid variables [cancel_comm_monoid_with_zero α] [decidable_eq α] [normalization_monoid α] variables [unique_factorization_monoid α] /-- Noncomputably determines the multiset of prime factors. -/ noncomputable def normalized_factors (a : α) : multiset α := multiset.map normalize $ factors a theorem normalized_factors_prod {a : α} (ane0 : a ≠ 0) : associated (normalized_factors a).prod a := begin rw [normalized_factors, factors, dif_neg ane0], refine associated.trans _ (classical.some_spec (exists_prime_factors a ane0)).2, rw [← associates.mk_eq_mk_iff_associated, ← associates.prod_mk, ← associates.prod_mk, multiset.map_map], congr' 2, ext, rw [function.comp_apply, associates.mk_normalize], end theorem prime_of_normalized_factor {a : α} : ∀ (x : α), x ∈ normalized_factors a → prime x := begin rw [normalized_factors, factors], split_ifs with ane0, { simp }, intros x hx, rcases multiset.mem_map.1 hx with ⟨y, ⟨hy, rfl⟩⟩, rw (normalize_associated _).prime_iff, exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 y hy, end theorem irreducible_of_normalized_factor {a : α} : ∀ (x : α), x ∈ normalized_factors a → irreducible x := λ x h, (prime_of_normalized_factor x h).irreducible theorem normalize_normalized_factor {a : α} : ∀ (x : α), x ∈ normalized_factors a → normalize x = x := begin rw [normalized_factors, factors], split_ifs with h, { simp }, intros x hx, obtain ⟨y, hy, rfl⟩ := multiset.mem_map.1 hx, apply normalize_idem end lemma normalized_factors_irreducible {a : α} (ha : irreducible a) : normalized_factors a = {normalize a} := begin obtain ⟨p, a_assoc, hp⟩ := prime_factors_irreducible ha ⟨prime_of_normalized_factor, normalized_factors_prod ha.ne_zero⟩, have p_mem : p ∈ normalized_factors a, { rw hp, exact multiset.mem_singleton_self _ }, convert hp, rwa [← normalize_normalized_factor p p_mem, normalize_eq_normalize_iff, dvd_dvd_iff_associated] end lemma exists_mem_normalized_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ q ∈ normalized_factors a, p ~ᵤ q := λ ⟨b, hb⟩, have hb0 : b ≠ 0, from λ hb0, by simp * at *, have multiset.rel associated (p ::ₘ normalized_factors b) (normalized_factors a), from factors_unique (λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_of_normalized_factor _)) irreducible_of_normalized_factor (associated.symm $ calc multiset.prod (normalized_factors a) ~ᵤ a : normalized_factors_prod ha0 ... = p * b : hb ... ~ᵤ multiset.prod (p ::ₘ normalized_factors b) : by rw multiset.prod_cons; exact (normalized_factors_prod hb0).symm.mul_left _), multiset.exists_mem_of_rel_of_mem this (by simp) @[simp] lemma normalized_factors_zero : normalized_factors (0 : α) = 0 := by simp [normalized_factors, factors] @[simp] lemma normalized_factors_one : normalized_factors (1 : α) = 0 := begin nontriviality α using [normalized_factors, factors], rw ← multiset.rel_zero_right, apply factors_unique irreducible_of_normalized_factor, { intros x hx, exfalso, apply multiset.not_mem_zero x hx }, { simp [normalized_factors_prod (@one_ne_zero α _ _)] }, apply_instance end @[simp] lemma normalized_factors_mul {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) : normalized_factors (x * y) = normalized_factors x + normalized_factors y := begin have h : (normalize : α → α) = associates.out ∘ associates.mk, { ext, rw [function.comp_apply, associates.out_mk], }, rw [← multiset.map_id' (normalized_factors (x * y)), ← multiset.map_id' (normalized_factors x), ← multiset.map_id' (normalized_factors y), ← multiset.map_congr rfl normalize_normalized_factor, ← multiset.map_congr rfl normalize_normalized_factor, ← multiset.map_congr rfl normalize_normalized_factor, ← multiset.map_add, h, ← multiset.map_map associates.out, eq_comm, ← multiset.map_map associates.out], refine congr rfl _, apply multiset.map_mk_eq_map_mk_of_rel, apply factors_unique, { intros x hx, rcases multiset.mem_add.1 hx with hx | hx; exact irreducible_of_normalized_factor x hx }, { exact irreducible_of_normalized_factor }, { rw multiset.prod_add, exact ((normalized_factors_prod hx).mul_mul (normalized_factors_prod hy)).trans (normalized_factors_prod (mul_ne_zero hx hy)).symm } end @[simp] lemma normalized_factors_pow {x : α} (n : ℕ) : normalized_factors (x ^ n) = n • normalized_factors x := begin induction n with n ih, { simp }, by_cases h0 : x = 0, { simp [h0, zero_pow n.succ_pos, smul_zero] }, rw [pow_succ, succ_nsmul, normalized_factors_mul h0 (pow_ne_zero _ h0), ih], end lemma dvd_iff_normalized_factors_le_normalized_factors {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) : x ∣ y ↔ normalized_factors x ≤ normalized_factors y := begin split, { rintro ⟨c, rfl⟩, simp [hx, right_ne_zero_of_mul hy] }, { rw [← (normalized_factors_prod hx).dvd_iff_dvd_left, ← (normalized_factors_prod hy).dvd_iff_dvd_right], apply multiset.prod_dvd_prod_of_le } end lemma zero_not_mem_normalized_factors (x : α) : (0 : α) ∉ normalized_factors x := λ h, prime.ne_zero (prime_of_normalized_factor _ h) rfl lemma dvd_of_mem_normalized_factors {a p : α} (H : p ∈ normalized_factors a) : p ∣ a := begin by_cases hcases : a = 0, { rw hcases, exact dvd_zero p }, { exact dvd_trans (multiset.dvd_prod H) (associated.dvd (normalized_factors_prod hcases)) }, end end unique_factorization_monoid namespace unique_factorization_monoid open_locale classical open multiset associates noncomputable theory variables [cancel_comm_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α] /-- Noncomputably defines a `normalization_monoid` structure on a `unique_factorization_monoid`. -/ protected def normalization_monoid : normalization_monoid α := normalization_monoid_of_monoid_hom_right_inverse { to_fun := λ a : associates α, if a = 0 then 0 else ((normalized_factors a).map (classical.some mk_surjective.has_right_inverse : associates α → α)).prod, map_one' := by simp, map_mul' := λ x y, by { by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, simp [hx, hy] } } begin intro x, dsimp, by_cases hx : x = 0, { simp [hx] }, have h : associates.mk_monoid_hom ∘ (classical.some mk_surjective.has_right_inverse) = (id : associates α → associates α), { ext x, rw [function.comp_apply, mk_monoid_hom_apply, classical.some_spec mk_surjective.has_right_inverse x], refl }, rw [if_neg hx, ← mk_monoid_hom_apply, monoid_hom.map_multiset_prod, map_map, h, map_id, ← associated_iff_eq], apply normalized_factors_prod hx end instance : inhabited (normalization_monoid α) := ⟨unique_factorization_monoid.normalization_monoid⟩ end unique_factorization_monoid namespace unique_factorization_monoid variables {R : Type*} [cancel_comm_monoid_with_zero R] [unique_factorization_monoid R] lemma no_factors_of_no_prime_factors {a b : R} (ha : a ≠ 0) (h : (∀ {d}, d ∣ a → d ∣ b → ¬ prime d)) : ∀ {d}, d ∣ a → d ∣ b → is_unit d := λ d, induction_on_prime d (by { simp only [zero_dvd_iff], intros, contradiction }) (λ x hx _ _, hx) (λ d q hp hq ih dvd_a dvd_b, absurd hq (h (dvd_of_mul_right_dvd dvd_a) (dvd_of_mul_right_dvd dvd_b))) /-- Euclid's lemma: if `a ∣ b * c` and `a` and `c` have no common prime factors, `a ∣ b`. Compare `is_coprime.dvd_of_dvd_mul_left`. -/ lemma dvd_of_dvd_mul_left_of_no_prime_factors {a b c : R} (ha : a ≠ 0) : (∀ {d}, d ∣ a → d ∣ c → ¬ prime d) → a ∣ b * c → a ∣ b := begin refine induction_on_prime c _ _ _, { intro no_factors, simp only [dvd_zero, mul_zero, forall_prop_of_true], haveI := classical.prop_decidable, exact is_unit_iff_forall_dvd.mp (no_factors_of_no_prime_factors ha @no_factors (dvd_refl a) (dvd_zero a)) _ }, { rintros _ ⟨x, rfl⟩ _ a_dvd_bx, apply units.dvd_mul_right.mp a_dvd_bx }, { intros c p hc hp ih no_factors a_dvd_bpc, apply ih (λ q dvd_a dvd_c hq, no_factors dvd_a (dvd_c.mul_left _) hq), rw mul_left_comm at a_dvd_bpc, refine or.resolve_left (hp.left_dvd_or_dvd_right_of_dvd_mul a_dvd_bpc) (λ h, _), exact no_factors h (dvd_mul_right p c) hp } end /-- Euclid's lemma: if `a ∣ b * c` and `a` and `b` have no common prime factors, `a ∣ c`. Compare `is_coprime.dvd_of_dvd_mul_right`. -/ lemma dvd_of_dvd_mul_right_of_no_prime_factors {a b c : R} (ha : a ≠ 0) (no_factors : ∀ {d}, d ∣ a → d ∣ b → ¬ prime d) : a ∣ b * c → a ∣ c := by simpa [mul_comm b c] using dvd_of_dvd_mul_left_of_no_prime_factors ha @no_factors /-- If `a ≠ 0, b` are elements of a unique factorization domain, then dividing out their common factor `c'` gives `a'` and `b'` with no factors in common. -/ lemma exists_reduced_factors : ∀ (a ≠ (0 : R)) b, ∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b := begin haveI := classical.prop_decidable, intros a, refine induction_on_prime a _ _ _, { intros, contradiction }, { intros a a_unit a_ne_zero b, use [a, b, 1], split, { intros p p_dvd_a _, exact is_unit_of_dvd_unit p_dvd_a a_unit }, { simp } }, { intros a p a_ne_zero p_prime ih_a pa_ne_zero b, by_cases p ∣ b, { rcases h with ⟨b, rfl⟩, obtain ⟨a', b', c', no_factor, ha', hb'⟩ := ih_a a_ne_zero b, refine ⟨a', b', p * c', @no_factor, _, _⟩, { rw [mul_assoc, ha'] }, { rw [mul_assoc, hb'] } }, { obtain ⟨a', b', c', coprime, rfl, rfl⟩ := ih_a a_ne_zero b, refine ⟨p * a', b', c', _, mul_left_comm _ _ _, rfl⟩, intros q q_dvd_pa' q_dvd_b', cases p_prime.left_dvd_or_dvd_right_of_dvd_mul q_dvd_pa' with p_dvd_q q_dvd_a', { have : p ∣ c' * b' := dvd_mul_of_dvd_right (p_dvd_q.trans q_dvd_b') _, contradiction }, exact coprime q_dvd_a' q_dvd_b' } } end lemma exists_reduced_factors' (a b : R) (hb : b ≠ 0) : ∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b := let ⟨b', a', c', no_factor, hb, ha⟩ := exists_reduced_factors b hb a in ⟨a', b', c', λ _ hpb hpa, no_factor hpa hpb, ha, hb⟩ section multiplicity variables [nontrivial R] [normalization_monoid R] [decidable_eq R] variables [decidable_rel (has_dvd.dvd : R → R → Prop)] open multiplicity multiset lemma le_multiplicity_iff_repeat_le_normalized_factors {a b : R} {n : ℕ} (ha : irreducible a) (hb : b ≠ 0) : ↑n ≤ multiplicity a b ↔ repeat (normalize a) n ≤ normalized_factors b := begin rw ← pow_dvd_iff_le_multiplicity, revert b, induction n with n ih, { simp }, intros b hb, split, { rintro ⟨c, rfl⟩, rw [ne.def, pow_succ, mul_assoc, mul_eq_zero, decidable.not_or_iff_and_not] at hb, rw [pow_succ, mul_assoc, normalized_factors_mul hb.1 hb.2, repeat_succ, normalized_factors_irreducible ha, singleton_add, cons_le_cons_iff, ← ih hb.2], apply dvd.intro _ rfl }, { rw [multiset.le_iff_exists_add], rintro ⟨u, hu⟩, rw [← (normalized_factors_prod hb).dvd_iff_dvd_right, hu, prod_add, prod_repeat], exact (associated.pow_pow $ associated_normalize a).dvd.trans (dvd.intro u.prod rfl) } end lemma multiplicity_eq_count_normalized_factors {a b : R} (ha : irreducible a) (hb : b ≠ 0) : multiplicity a b = (normalized_factors b).count (normalize a) := begin apply le_antisymm, { apply enat.le_of_lt_add_one, rw [← nat.cast_one, ← nat.cast_add, lt_iff_not_ge, ge_iff_le, le_multiplicity_iff_repeat_le_normalized_factors ha hb, ← le_count_iff_repeat_le], simp }, rw [le_multiplicity_iff_repeat_le_normalized_factors ha hb, ← le_count_iff_repeat_le], end end multiplicity end unique_factorization_monoid namespace associates open unique_factorization_monoid associated multiset variables [cancel_comm_monoid_with_zero α] /-- `factor_set α` representation elements of unique factorization domain as multisets. `multiset α` produced by `normalized_factors` are only unique up to associated elements, while the multisets in `factor_set α` are unique by equality and restricted to irreducible elements. This gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a complete lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple. -/ @[reducible] def {u} factor_set (α : Type u) [cancel_comm_monoid_with_zero α] : Type u := with_top (multiset { a : associates α // irreducible a }) local attribute [instance] associated.setoid theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} : (↑(a + b) : factor_set α) = a + b := by norm_cast lemma factor_set.sup_add_inf_eq_add [decidable_eq (associates α)] : ∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b | none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp | a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp | (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from begin rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add, with_top.coe_eq_coe], exact multiset.union_add_inter _ _ end /-- Evaluates the product of a `factor_set` to be the product of the corresponding multiset, or `0` if there is none. -/ def factor_set.prod : factor_set α → associates α | none := 0 | (some s) := (s.map coe).prod @[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl @[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} : (s : factor_set α).prod = (s.map coe).prod := rfl @[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod | none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp | a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp | (some a) (some b) := show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod, by rw [← factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add] theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod | none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_rfl | a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top | (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h theorem factor_set.prod_eq_zero_iff [nontrivial α] (p : factor_set α) : p.prod = 0 ↔ p = ⊤ := begin induction p using with_top.rec_top_coe, { simp only [iff_self, eq_self_iff_true, associates.prod_top] }, simp only [prod_coe, with_top.coe_ne_top, iff_false, prod_eq_zero_iff, multiset.mem_map], rintro ⟨⟨a, ha⟩, -, eq⟩, rw [subtype.coe_mk] at eq, exact ha.ne_zero eq, end /-- `bcount p s` is the multiplicity of `p` in the factor_set `s` (with bundled `p`)-/ def bcount [decidable_eq (associates α)] (p : {a : associates α // irreducible a}) : factor_set α → ℕ | none := 0 | (some s) := s.count p variables [dec_irr : Π (p : associates α), decidable (irreducible p)] include dec_irr /-- `count p s` is the multiplicity of the irreducible `p` in the factor_set `s`. If `p` is not irreducible, `count p s` is defined to be `0`. -/ def count [decidable_eq (associates α)] (p : associates α) : factor_set α → ℕ := if hp : irreducible p then bcount ⟨p, hp⟩ else 0 @[simp] lemma count_some [decidable_eq (associates α)] {p : associates α} (hp : irreducible p) (s : multiset _) : count p (some s) = s.count ⟨p, hp⟩:= by { dunfold count, split_ifs, refl } @[simp] lemma count_zero [decidable_eq (associates α)] {p : associates α} (hp : irreducible p) : count p (0 : factor_set α) = 0 := by { dunfold count, split_ifs, refl } lemma count_reducible [decidable_eq (associates α)] {p : associates α} (hp : ¬ irreducible p) : count p = 0 := dif_neg hp omit dec_irr /-- membership in a factor_set (bundled version) -/ def bfactor_set_mem : {a : associates α // irreducible a} → (factor_set α) → Prop | _ ⊤ := true | p (some l) := p ∈ l include dec_irr /-- `factor_set_mem p s` is the predicate that the irreducible `p` is a member of `s : factor_set α`. If `p` is not irreducible, `p` is not a member of any `factor_set`. -/ def factor_set_mem (p : associates α) (s : factor_set α) : Prop := if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false instance : has_mem (associates α) (factor_set α) := ⟨factor_set_mem⟩ @[simp] lemma factor_set_mem_eq_mem (p : associates α) (s : factor_set α) : factor_set_mem p s = (p ∈ s) := rfl lemma mem_factor_set_top {p : associates α} {hp : irreducible p} : p ∈ (⊤ : factor_set α) := begin dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, exact trivial end lemma mem_factor_set_some {p : associates α} {hp : irreducible p} {l : multiset {a : associates α // irreducible a }} : p ∈ (l : factor_set α) ↔ subtype.mk p hp ∈ l := begin dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, refl end lemma reducible_not_mem_factor_set {p : associates α} (hp : ¬ irreducible p) (s : factor_set α) : ¬ p ∈ s := λ (h : if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false), by rwa [dif_neg hp] at h omit dec_irr variable [unique_factorization_monoid α] theorem unique' {p q : multiset (associates α)} : (∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q := begin apply multiset.induction_on_multiset_quot p, apply multiset.induction_on_multiset_quot q, assume s t hs ht eq, refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_monoid.factors_unique _ _ _), { exact assume a ha, ((irreducible_mk _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) }, { exact assume a ha, ((irreducible_mk _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) }, simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq end theorem factor_set.unique [nontrivial α] {p q : factor_set α} (h : p.prod = q.prod) : p = q := begin induction p using with_top.rec_top_coe; induction q using with_top.rec_top_coe, { refl }, { rw [eq_comm, ←factor_set.prod_eq_zero_iff, ←h, associates.prod_top] }, { rw [←factor_set.prod_eq_zero_iff, h, associates.prod_top] }, { congr' 1, rw ←multiset.map_eq_map subtype.coe_injective, apply unique' _ _ h; { intros a ha, obtain ⟨⟨a', irred⟩, -, rfl⟩ := multiset.mem_map.mp ha, rwa [subtype.coe_mk] } }, end theorem prod_le_prod_iff_le [nontrivial α] {p q : multiset (associates α)} (hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) : p.prod ≤ q.prod ↔ p ≤ q := iff.intro begin classical, rintros ⟨c, eqc⟩, refine multiset.le_iff_exists_add.2 ⟨factors c, unique' hq (λ x hx, _) _⟩, { obtain h|h := multiset.mem_add.1 hx, { exact hp x h }, { exact irreducible_of_factor _ h } }, { rw [eqc, multiset.prod_add], congr, refine associated_iff_eq.mp (factors_prod (λ hc, _)).symm, refine not_irreducible_zero (hq _ _), rw [←prod_eq_zero_iff, eqc, hc, mul_zero] } end prod_le_prod variables [dec : decidable_eq α] [dec' : decidable_eq (associates α)] include dec /-- This returns the multiset of irreducible factors as a `factor_set`, a multiset of irreducible associates `with_top`. -/ noncomputable def factors' (a : α) : multiset { a : associates α // irreducible a } := (factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk _).2 ha⟩) (irreducible_of_factor) @[simp] theorem map_subtype_coe_factors' {a : α} : (factors' a).map coe = (factors a).map associates.mk := by simp [factors', multiset.map_pmap, multiset.pmap_eq_map] theorem factors'_cong {a b : α} (h : a ~ᵤ b) : factors' a = factors' b := begin obtain rfl|hb := eq_or_ne b 0, { rw associated_zero_iff_eq_zero at h, rw h }, have ha : a ≠ 0, { contrapose! hb with ha, rw [←associated_zero_iff_eq_zero, ←ha], exact h.symm }, rw [←multiset.map_eq_map subtype.coe_injective, map_subtype_coe_factors', map_subtype_coe_factors', ←rel_associated_iff_map_eq_map], exact factors_unique irreducible_of_factor irreducible_of_factor ((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm), end include dec' /-- This returns the multiset of irreducible factors of an associate as a `factor_set`, a multiset of irreducible associates `with_top`. -/ noncomputable def factors (a : associates α) : factor_set α := begin refine (if h : a = 0 then ⊤ else quotient.hrec_on a (λx h, some $ factors' x) _ h), assume a b hab, apply function.hfunext, { have : a ~ᵤ 0 ↔ b ~ᵤ 0, from iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0), simp only [associated_zero_iff_eq_zero] at this, simp only [quotient_mk_eq_mk, this, mk_eq_zero] }, exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong hab) end @[simp] theorem factors_0 : (0 : associates α).factors = ⊤ := dif_pos rfl @[simp] theorem factors_mk (a : α) (h : a ≠ 0) : (associates.mk a).factors = factors' a := by { classical, apply dif_neg, apply (mt mk_eq_zero.1 h) } @[simp] theorem factors_prod (a : associates α) : a.factors.prod = a := quotient.induction_on a $ assume a, decidable.by_cases (assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this]) (assume : associates.mk a ≠ 0, have a ≠ 0, by simp * at *, by simp [this, quotient_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated.2 (factors_prod this)]) theorem prod_factors [nontrivial α] (s : factor_set α) : s.prod.factors = s := factor_set.unique $ factors_prod _ @[nontriviality] lemma factors_subsingleton [subsingleton α] {a : associates α} : a.factors = option.none := by { convert factors_0; apply_instance } lemma factors_eq_none_iff_zero {a : associates α} : a.factors = option.none ↔ a = 0 := begin nontriviality α, exact ⟨λ h, by rwa [← factors_prod a, factor_set.prod_eq_zero_iff], λ h, h.symm ▸ factors_0⟩ end lemma factors_eq_some_iff_ne_zero {a : associates α} : (∃ (s : multiset {p : associates α // irreducible p}), a.factors = some s) ↔ a ≠ 0 := by rw [← option.is_some_iff_exists, ← option.ne_none_iff_is_some, ne.def, ne.def, factors_eq_none_iff_zero] theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b := have a.factors.prod = b.factors.prod, by rw h, by rwa [factors_prod, factors_prod] at this omit dec dec' theorem eq_of_prod_eq_prod [nontrivial α] {a b : factor_set α} (h : a.prod = b.prod) : a = b := begin classical, have : a.prod.factors = b.prod.factors, by rw h, rwa [prod_factors, prod_factors] at this end include dec dec' dec_irr theorem eq_factors_of_eq_counts {a b : associates α} (ha : a ≠ 0) (hb : b ≠ 0) (h : ∀ (p : associates α) (hp : irreducible p), p.count a.factors = p.count b.factors) : a.factors = b.factors := begin obtain ⟨sa, h_sa⟩ := factors_eq_some_iff_ne_zero.mpr ha, obtain ⟨sb, h_sb⟩ := factors_eq_some_iff_ne_zero.mpr hb, rw [h_sa, h_sb] at h ⊢, rw option.some_inj, have h_count : ∀ (p : associates α) (hp : irreducible p), sa.count ⟨p, hp⟩ = sb.count ⟨p, hp⟩, { intros p hp, rw [← count_some, ← count_some, h p hp] }, apply multiset.to_finsupp.injective, ext ⟨p, hp⟩, rw [multiset.to_finsupp_apply, multiset.to_finsupp_apply, h_count p hp] end theorem eq_of_eq_counts {a b : associates α} (ha : a ≠ 0) (hb : b ≠ 0) (h : ∀ (p : associates α), irreducible p → p.count a.factors = p.count b.factors) : a = b := eq_of_factors_eq_factors (eq_factors_of_eq_counts ha hb h) omit dec_irr @[simp] theorem factors_mul [nontrivial α] (a b : associates α) : (a * b).factors = a.factors + b.factors := eq_of_prod_eq_prod $ eq_of_factors_eq_factors $ by rw [prod_add, factors_prod, factors_prod, factors_prod] theorem factors_mono [nontrivial α] : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors | s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right bot_le theorem factors_le [nontrivial α] {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b := iff.intro (assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h, by rwa [factors_prod, factors_prod] at this) factors_mono omit dec dec' theorem prod_le [nontrivial α] {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b := begin classical, exact iff.intro (assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h, by rwa [prod_factors, prod_factors] at this) prod_mono end include dec dec' noncomputable instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩ noncomputable instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩ noncomputable instance [nontrivial α] : lattice (associates α) := { sup := (⊔), inf := (⊓), sup_le := assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)), le_sup_left := assume a b, le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left, le_sup_right := assume a b, le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right, le_inf := assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)), inf_le_left := assume a b, le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)), inf_le_right := assume a b, le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)), .. associates.partial_order } lemma sup_mul_inf [nontrivial α] (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b := show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b, begin refine eq_of_factors_eq_factors _, rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add] end include dec_irr lemma dvd_of_mem_factors {a p : associates α} {hp : irreducible p} (hm : p ∈ factors a) : p ∣ a := begin by_cases ha0 : a = 0, { rw ha0, exact dvd_zero p }, obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha0, rw [← associates.factors_prod a], rw [← ha', factors_mk a0 nza] at hm ⊢, erw prod_coe, apply multiset.dvd_prod, apply multiset.mem_map.mpr, exact ⟨⟨p, hp⟩, mem_factor_set_some.mp hm, rfl⟩ end omit dec' lemma dvd_of_mem_factors' {a : α} {p : associates α} {hp : irreducible p} {hz : a ≠ 0} (h_mem : subtype.mk p hp ∈ factors' a) : p ∣ associates.mk a := by { haveI := classical.dec_eq (associates α), apply @dvd_of_mem_factors _ _ _ _ _ _ _ _ hp, rw factors_mk _ hz, apply mem_factor_set_some.2 h_mem } omit dec_irr lemma mem_factors'_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) : subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a := begin obtain ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd ha0 hp hd, apply multiset.mem_pmap.mpr, use q, use hq, exact subtype.eq (eq.symm (mk_eq_mk_iff_associated.mpr hpq)) end include dec_irr lemma mem_factors'_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a ↔ p ∣ a := begin split, { rw ← mk_dvd_mk, apply dvd_of_mem_factors', apply ha0 }, { apply mem_factors'_of_dvd ha0 } end include dec' lemma mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) : (associates.mk p) ∈ factors (associates.mk a) := begin rw factors_mk _ ha0, exact mem_factor_set_some.mpr (mem_factors'_of_dvd ha0 hp hd) end lemma mem_factors_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : (associates.mk p) ∈ factors (associates.mk a) ↔ p ∣ a := begin split, { rw ← mk_dvd_mk, apply dvd_of_mem_factors, exact (irreducible_mk p).mpr hp }, { apply mem_factors_of_dvd ha0 hp } end lemma exists_prime_dvd_of_not_inf_one {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : (associates.mk a) ⊓ (associates.mk b) ≠ 1) : ∃ (p : α), prime p ∧ p ∣ a ∧ p ∣ b := begin have hz : (factors (associates.mk a)) ⊓ (factors (associates.mk b)) ≠ 0, { contrapose! h with hf, change ((factors (associates.mk a)) ⊓ (factors (associates.mk b))).prod = 1, rw hf, exact multiset.prod_zero }, rw [factors_mk a ha, factors_mk b hb, ← with_top.coe_inf] at hz, obtain ⟨⟨p0, p0_irr⟩, p0_mem⟩ := multiset.exists_mem_of_ne_zero ((mt with_top.coe_eq_coe.mpr) hz), rw multiset.inf_eq_inter at p0_mem, obtain ⟨p, rfl⟩ : ∃ p, associates.mk p = p0 := quot.exists_rep p0, refine ⟨p, _, _, _⟩, { rw [← irreducible_iff_prime, ← irreducible_mk], exact p0_irr }, { apply dvd_of_mk_le_mk, apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).left, apply ha, }, { apply dvd_of_mk_le_mk, apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).right, apply hb } end theorem coprime_iff_inf_one [nontrivial α] {a b : α} (ha0 : a ≠ 0) (hb0 : b ≠ 0) : (associates.mk a) ⊓ (associates.mk b) = 1 ↔ ∀ {d : α}, d ∣ a → d ∣ b → ¬ prime d := begin split, { intros hg p ha hb hp, refine ((associates.prime_mk _).mpr hp).not_unit (is_unit_of_dvd_one _ _), rw ← hg, exact le_inf (mk_le_mk_of_dvd ha) (mk_le_mk_of_dvd hb) }, { contrapose, intros hg hc, obtain ⟨p, hp, hpa, hpb⟩ := exists_prime_dvd_of_not_inf_one ha0 hb0 hg, exact hc hpa hpb hp } end omit dec_irr include dec_irr theorem prime_pow_dvd_iff_le [nontrivial α] {m p : associates α} (h₁ : m ≠ 0) (h₂ : irreducible p) {k : ℕ} : p ^ k ≤ m ↔ k ≤ count p m.factors := begin obtain ⟨a, nz, rfl⟩ := associates.exists_non_zero_rep h₁, rw [factors_mk _ nz, ← with_top.some_eq_coe, count_some, multiset.le_count_iff_repeat_le, ← factors_le, factors_prime_pow h₂, factors_mk _ nz], exact with_top.coe_le_coe end theorem le_of_count_ne_zero [nontrivial α] {m p : associates α} (h0 : m ≠ 0) (hp : irreducible p) : count p m.factors ≠ 0 → p ≤ m := begin rw [← pos_iff_ne_zero], intro h, rw [← pow_one p], apply (prime_pow_dvd_iff_le h0 hp).2, simpa only end theorem count_ne_zero_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : (associates.mk p).count (associates.mk a).factors ≠ 0 ↔ p ∣ a := begin nontriviality α, rw ← associates.mk_le_mk_iff_dvd_iff, refine ⟨λ h, associates.le_of_count_ne_zero (associates.mk_ne_zero.mpr ha0) ((associates.irreducible_mk p).mpr hp) h, λ h, _⟩, { rw [← pow_one (associates.mk p), associates.prime_pow_dvd_iff_le (associates.mk_ne_zero.mpr ha0) ((associates.irreducible_mk p).mpr hp)] at h, exact (zero_lt_one.trans_le h).ne' } end theorem count_mul [nontrivial α] {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) : count p (factors (a * b)) = count p a.factors + count p b.factors := begin obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha, obtain ⟨b0, nzb, hb'⟩ := exists_non_zero_rep hb, rw [factors_mul, ← ha', ← hb', factors_mk a0 nza, factors_mk b0 nzb, ← factor_set.coe_add, ← with_top.some_eq_coe, ← with_top.some_eq_coe, ← with_top.some_eq_coe, count_some hp, multiset.count_add, count_some hp, count_some hp] end theorem count_of_coprime [nontrivial α] {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {p : associates α} (hp : irreducible p) : count p a.factors = 0 ∨ count p b.factors = 0 := begin rw [or_iff_not_imp_left, ← ne.def], intro hca, contrapose! hab with hcb, exact ⟨p, le_of_count_ne_zero ha hp hca, le_of_count_ne_zero hb hp hcb, (irreducible_iff_prime.mp hp)⟩, end theorem count_mul_of_coprime [nontrivial α] {a : associates α} {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) : count p a.factors = 0 ∨ count p a.factors = count p (a * b).factors := begin by_cases ha : a = 0, { simp [ha], }, cases count_of_coprime ha hb hab hp with hz hb0, { tauto }, apply or.intro_right, rw [count_mul ha hb hp, hb0, add_zero] end theorem count_mul_of_coprime' [nontrivial α] {a b : associates α} {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) : count p (a * b).factors = count p a.factors ∨ count p (a * b).factors = count p b.factors := begin by_cases ha : a = 0, { simp [ha], }, by_cases hb : b = 0, { simp [hb], }, rw [count_mul ha hb hp], cases count_of_coprime ha hb hab hp with ha0 hb0, { apply or.intro_right, rw [ha0, zero_add] }, { apply or.intro_left, rw [hb0, add_zero] } end theorem dvd_count_of_dvd_count_mul [nontrivial α] {a b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {k : ℕ} (habk : k ∣ count p (a * b).factors) : k ∣ count p a.factors := begin by_cases ha : a = 0, { simpa [*] using habk, }, cases count_of_coprime ha hb hab hp with hz h, { rw hz, exact dvd_zero k }, { rw [count_mul ha hb hp, h] at habk, exact habk } end omit dec_irr @[simp] lemma factors_one [nontrivial α] : factors (1 : associates α) = 0 := begin apply eq_of_prod_eq_prod, rw associates.factors_prod, exact multiset.prod_zero, end @[simp] theorem pow_factors [nontrivial α] {a : associates α} {k : ℕ} : (a ^ k).factors = k • a.factors := begin induction k with n h, { rw [zero_nsmul, pow_zero], exact factors_one }, { rw [pow_succ, succ_nsmul, factors_mul, h] } end include dec_irr lemma count_pow [nontrivial α] {a : associates α} (ha : a ≠ 0) {p : associates α} (hp : irreducible p) (k : ℕ) : count p (a ^ k).factors = k * count p a.factors := begin induction k with n h, { rw [pow_zero, factors_one, zero_mul, count_zero hp] }, { rw [pow_succ, count_mul ha (pow_ne_zero _ ha) hp, h, nat.succ_eq_add_one], ring } end theorem dvd_count_pow [nontrivial α] {a : associates α} (ha : a ≠ 0) {p : associates α} (hp : irreducible p) (k : ℕ) : k ∣ count p (a ^ k).factors := by { rw count_pow ha hp, apply dvd_mul_right } theorem is_pow_of_dvd_count [nontrivial α] {a : associates α} (ha : a ≠ 0) {k : ℕ} (hk : ∀ (p : associates α) (hp : irreducible p), k ∣ count p a.factors) : ∃ (b : associates α), a = b ^ k := begin obtain ⟨a0, hz, rfl⟩ := exists_non_zero_rep ha, rw [factors_mk a0 hz] at hk, have hk' : ∀ p, p ∈ (factors' a0) → k ∣ (factors' a0).count p, { rintros p -, have pp : p = ⟨p.val, p.2⟩, { simp only [subtype.coe_eta, subtype.val_eq_coe] }, rw [pp, ← count_some p.2], exact hk p.val p.2 }, obtain ⟨u, hu⟩ := multiset.exists_smul_of_dvd_count _ hk', use (u : factor_set α).prod, apply eq_of_factors_eq_factors, rw [pow_factors, prod_factors, factors_mk a0 hz, ← with_top.some_eq_coe, hu], exact with_bot.coe_nsmul u k end omit dec omit dec_irr omit dec' theorem eq_pow_of_mul_eq_pow [nontrivial α] {a b c : associates α} (ha : a ≠ 0) (hb : b ≠ 0) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {k : ℕ} (h : a * b = c ^ k) : ∃ (d : associates α), a = d ^ k := begin classical, by_cases hk0 : k = 0, { use 1, rw [hk0, pow_zero] at h ⊢, apply (mul_eq_one_iff.1 h).1 }, { refine is_pow_of_dvd_count ha _, intros p hp, apply dvd_count_of_dvd_count_mul hb hp hab, rw h, apply dvd_count_pow _ hp, rintros rfl, rw zero_pow' _ hk0 at h, cases mul_eq_zero.mp h; contradiction } end end associates section open associates unique_factorization_monoid lemma associates.quot_out {α : Type*} [comm_monoid α] (a : associates α): associates.mk (quot.out (a)) = a := by rw [←quot_mk_eq_mk, quot.out_eq] /-- `to_gcd_monoid` constructs a GCD monoid out of a unique factorization domain. -/ noncomputable def unique_factorization_monoid.to_gcd_monoid (α : Type*) [cancel_comm_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α] [decidable_eq (associates α)] [decidable_eq α] : gcd_monoid α := { gcd := λa b, quot.out (associates.mk a ⊓ associates.mk b : associates α), lcm := λa b, quot.out (associates.mk a ⊔ associates.mk b : associates α), gcd_dvd_left := λ a b, by { rw [←mk_dvd_mk, (associates.mk a ⊓ associates.mk b).quot_out, dvd_eq_le], exact inf_le_left }, gcd_dvd_right := λ a b, by { rw [←mk_dvd_mk, (associates.mk a ⊓ associates.mk b).quot_out, dvd_eq_le], exact inf_le_right }, dvd_gcd := λ a b c hac hab, by { rw [←mk_dvd_mk, (associates.mk c ⊓ associates.mk b).quot_out, dvd_eq_le, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff], exact ⟨hac, hab⟩ }, lcm_zero_left := λ a, by { have : associates.mk (0 : α) = ⊤ := rfl, rw [this, top_sup_eq, ←this, ←associated_zero_iff_eq_zero, ←mk_eq_mk_iff_associated, ←associated_iff_eq, associates.quot_out] }, lcm_zero_right := λ a, by { have : associates.mk (0 : α) = ⊤ := rfl, rw [this, sup_top_eq, ←this, ←associated_zero_iff_eq_zero, ←mk_eq_mk_iff_associated, ←associated_iff_eq, associates.quot_out] }, gcd_mul_lcm := λ a b, by { rw [←mk_eq_mk_iff_associated, ←associates.mk_mul_mk, ←associated_iff_eq, associates.quot_out, associates.quot_out, mul_comm, sup_mul_inf, associates.mk_mul_mk] } } /-- `to_normalized_gcd_monoid` constructs a GCD monoid out of a normalization on a unique factorization domain. -/ noncomputable def unique_factorization_monoid.to_normalized_gcd_monoid (α : Type*) [cancel_comm_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α] [normalization_monoid α] [decidable_eq (associates α)] [decidable_eq α] : normalized_gcd_monoid α := { gcd := λa b, (associates.mk a ⊓ associates.mk b).out, lcm := λa b, (associates.mk a ⊔ associates.mk b).out, gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left, gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right, dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out, by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩, lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp, lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp, gcd_mul_lcm := assume a b, by { rw [← out_mul, mul_comm, sup_mul_inf, mk_mul_mk, out_mk], exact normalize_associated (a * b) }, normalize_gcd := assume a b, by convert normalize_out _, normalize_lcm := assume a b, by convert normalize_out _, .. ‹normalization_monoid α› } end namespace unique_factorization_monoid /-- If `y` is a nonzero element of a unique factorization monoid with finitely many units (e.g. `ℤ`, `ideal (ring_of_integers K)`), it has finitely many divisors. -/ noncomputable def fintype_subtype_dvd {M : Type*} [cancel_comm_monoid_with_zero M] [unique_factorization_monoid M] [fintype Mˣ] (y : M) (hy : y ≠ 0) : fintype {x // x ∣ y} := begin haveI : nontrivial M := ⟨⟨y, 0, hy⟩⟩, haveI : normalization_monoid M := unique_factorization_monoid.normalization_monoid, haveI := classical.dec_eq M, haveI := classical.dec_eq (associates M), -- We'll show `λ (u : Mˣ) (f ⊆ factors y) → u * Π f` is injective -- and has image exactly the divisors of `y`. refine fintype.of_finset (((normalized_factors y).powerset.to_finset.product (finset.univ : finset Mˣ)).image (λ s, (s.snd : M) * s.fst.prod)) (λ x, _), simp only [exists_prop, finset.mem_image, finset.mem_product, finset.mem_univ, and_true, multiset.mem_to_finset, multiset.mem_powerset, exists_eq_right, multiset.mem_map], split, { rintros ⟨s, hs, rfl⟩, have prod_s_ne : s.fst.prod ≠ 0, { intro hz, apply hy (eq_zero_of_zero_dvd _), have hz := (@multiset.prod_eq_zero_iff M _ _ _ s.fst).mp hz, rw ← (normalized_factors_prod hy).dvd_iff_dvd_right, exact multiset.dvd_prod (multiset.mem_of_le hs hz) }, show (s.snd : M) * s.fst.prod ∣ y, rw [(unit_associated_one.mul_right s.fst.prod).dvd_iff_dvd_left, one_mul, ← (normalized_factors_prod hy).dvd_iff_dvd_right], exact multiset.prod_dvd_prod_of_le hs }, { rintro (h : x ∣ y), have hx : x ≠ 0, { refine mt (λ hx, _) hy, rwa [hx, zero_dvd_iff] at h }, obtain ⟨u, hu⟩ := normalized_factors_prod hx, refine ⟨⟨normalized_factors x, u⟩, _, (mul_comm _ _).trans hu⟩, exact (dvd_iff_normalized_factors_le_normalized_factors hx hy).mp h } end end unique_factorization_monoid section finsupp variables [cancel_comm_monoid_with_zero α] [unique_factorization_monoid α] variables [normalization_monoid α] [decidable_eq α] open unique_factorization_monoid /-- This returns the multiset of irreducible factors as a `finsupp` -/ noncomputable def factorization (n : α) : α →₀ ℕ := (normalized_factors n).to_finsupp lemma factorization_eq_count {n p : α} : factorization n p = multiset.count p (normalized_factors n) := by simp [factorization] @[simp] lemma factorization_zero : factorization (0 : α) = 0 := by simp [factorization] @[simp] lemma factorization_one : factorization (1 : α) = 0 := by simp [factorization] /-- The support of `factorization n` is exactly the finset of normalized factors -/ @[simp] lemma support_factorization {n : α} : (factorization n).support = (normalized_factors n).to_finset := by simp [factorization, multiset.to_finsupp_support] /-- For nonzero `a` and `b`, the power of `p` in `a * b` is the sum of the powers in `a` and `b` -/ @[simp] lemma factorization_mul {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : factorization (a * b) = factorization a + factorization b := by simp [factorization, normalized_factors_mul ha hb] /-- For any `p`, the power of `p` in `x^n` is `n` times the power in `x` -/ lemma factorization_pow {x : α} {n : ℕ} : factorization (x^n) = n • factorization x := by { ext, simp [factorization] } lemma associated_of_factorization_eq (a b: α) (ha: a ≠ 0) (hb: b ≠ 0) (h: factorization a = factorization b) : associated a b := begin simp only [factorization, add_equiv.apply_eq_iff_eq] at h, have ha' := normalized_factors_prod ha, rw h at ha', exact associated.trans ha'.symm (normalized_factors_prod hb), end end finsupp
section "Permutation Lemmas" theory PermutationLemmas imports "HOL-Library.Multiset" begin \<comment> \<open>following function is very close to that in multisets- now we can make the connection that x <~~> y iff the multiset of x is the same as that of y\<close> subsection "perm, count equivalence" lemma count_eq: \<open>count_list xs x = Multiset.count (mset xs) x\<close> by (induction xs) simp_all lemma perm_count: "mset A = mset B \<Longrightarrow> (\<forall> x. count_list A x = count_list B x)" by (simp add: count_eq) lemma count_0: "(\<forall>x. count_list B x = 0) = (B = [])" by (simp add: count_list_0_iff) lemma count_Suc: "count_list B a = Suc m \<Longrightarrow> a : set B" by (metis Zero_not_Suc count_notin) lemma count_perm: "!! B. (\<forall> x. count_list A x = count_list B x) \<Longrightarrow> mset A = mset B" by (simp add: count_eq multiset_eq_iff) lemma perm_count_conv: "mset A = mset B \<longleftrightarrow> (\<forall> x. count_list A x = count_list B x)" by (simp add: count_eq multiset_eq_iff) subsection "Properties closed under Perm and Contr hold for x iff hold for remdups x" lemma remdups_append: "y : set ys --> remdups (ws@y#ys) = remdups (ws@ys)" apply (induct ws, simp) apply (case_tac "y = a", simp, simp) done lemma perm_contr': assumes perm[rule_format]: "! xs ys. mset xs = mset ys --> (P xs = P ys)" and contr'[rule_format]: "! x xs. P(x#x#xs) = P (x#xs)" shows "! xs. length xs = n --> (P xs = P (remdups xs))" apply(induct n rule: nat_less_induct) proof (safe) fix xs :: "'a list" assume a[rule_format]: "\<forall>m<length xs. \<forall>ys. length ys = m \<longrightarrow> P ys = P (remdups ys)" show "P xs = P (remdups xs)" proof (cases "distinct xs") case True thus ?thesis by(simp add:distinct_remdups_id) next case False from not_distinct_decomp[OF this] obtain ws ys zs y where xs: "xs = ws@[y]@ys@[y]@zs" by force have "P xs = P (ws@[y]@ys@[y]@zs)" by (simp add: xs) also have "... = P ([y,y]@ws@ys@zs)" apply(rule perm) apply(rule iffD2[OF perm_count_conv]) apply rule apply(simp) done also have "... = P ([y]@ws@ys@zs)" apply simp apply(rule contr') done also have "... = P (ws@ys@[y]@zs)" apply(rule perm) apply(rule iffD2[OF perm_count_conv]) apply rule apply(simp) done also have "... = P (remdups (ws@ys@[y]@zs))" apply(rule a) by(auto simp: xs) also have "(remdups (ws@ys@[y]@zs)) = (remdups xs)" apply(simp add: xs remdups_append) done finally show "P xs = P (remdups xs)" . qed qed lemma perm_contr: assumes perm: "! xs ys. mset xs = mset ys --> (P xs = P ys)" and contr': "! x xs. P(x#x#xs) = P (x#xs)" shows "(P xs = P (remdups xs))" apply(rule perm_contr'[OF perm contr', rule_format]) by force subsection "List properties closed under Perm, Weak and Contr are monotonic in the set of the list" definition rem :: "'a => 'a list => 'a list" where "rem x xs = filter (%y. y ~= x) xs" lemma rem: "x ~: set (rem x xs)" by(simp add: rem_def) lemma length_rem: "length (rem x xs) <= length xs" by(simp add: rem_def) lemma rem_notin: "x ~: set xs ==> rem x xs = xs" apply(simp add: rem_def) apply(rule filter_True) apply force done lemma perm_weak_filter': assumes perm[rule_format]: "! xs ys. mset xs = mset ys --> (P xs = P ys)" and weak[rule_format]: "! x xs. P xs --> P (x#xs)" shows "! ys. P (ys@filter Q xs) --> P (ys@xs)" proof (rule allI, rule impI) fix ys define zs where \<open>zs = filter (Not \<circ> Q) xs\<close> assume \<open>P (ys @ filter Q xs)\<close> then have \<open>P (filter Q xs @ ys)\<close> apply (subst perm) defer apply assumption apply simp done then have \<open>P (zs @ filter Q xs @ ys)\<close> apply (induction zs) apply (simp_all add: weak) done with zs_def show \<open>P (ys @ xs)\<close> apply (subst perm) defer apply assumption apply simp done qed lemma perm_weak_filter: assumes perm: "! xs ys. mset xs = mset ys --> (P xs = P ys)" and weak: "! x xs. P xs --> P (x#xs)" shows "P (filter Q xs) ==> P xs" using perm_weak_filter'[OF perm weak, rule_format, of "[]", simplified] by blast \<comment> \<open>right, now in a position to prove that in presence of perm, contr and weak, set x leq set y and x : ded implies y : ded\<close> lemma perm_weak_contr_mono: assumes perm: "! xs ys. mset xs = mset ys --> (P xs = P ys)" and contr: "! x xs. P (x#x#xs) --> P (x#xs)" and weak: "! x xs. P xs --> P (x#xs)" and xy: "set x <= set y" and Px : "P x" shows "P y" proof - from contr weak have contr': "! x xs. P(x#x#xs) = P (x#xs)" by blast define y' where "y' = filter (% z. z : set x) y" from xy have "set x = set y'" apply(simp add: y'_def) apply blast done hence rxry': "mset (remdups x) = mset (remdups y')" using set_eq_iff_mset_remdups_eq by auto from Px perm_contr[OF perm contr'] have Prx: "P (remdups x)" by simp with rxry' have "P (remdups y')" apply (subst perm) defer apply assumption apply simp done with perm_contr[OF perm contr'] have "P y'" by simp thus "P y" apply(simp add: y'_def) apply(rule perm_weak_filter[OF perm weak]) . qed (* No, not used subsection "Following used in Soundness" primrec multiset_of_list :: "'a list \<Rightarrow> 'a multiset" where "multiset_of_list [] = {#}" | "multiset_of_list (x#xs) = {#x#} + multiset_of_list xs" lemma count_count[symmetric]: "count x A = Multiset.count (multiset_of_list A) x" by (induct A) simp_all lemma perm_multiset: "A <~~> B = (multiset_of_list A = multiset_of_list B)" apply(simp add: perm_count_conv) apply(simp add: multiset_eq_iff) apply(simp add: count_count) done lemma set_of_multiset_of_list: "set_of (multiset_of_list A) = set A" by (induct A) auto *) end
\ifdefined\draft \appendix \iffalse \subsection{Code to Get Qdisc Length} \label{ssec:code} \mylabel{ssec:code} \begin{lstlisting}[language=c, basicstyle=\scriptsize, upquote=true, numbers=left, numbersep=0.5em, breaklines=true, showstringspaces=false, keywordstyle=\color{blue}\textbf, commentstyle=\color{purple}\textit] #include <linux/netdevice.h> #include <linux/rcupdate.h> #include <net/sch_generic.h> // kernel 4.2 // http://lxr.free-electrons.com/source/net/core/dev.c?v=4.2#L3036 int GetQdiscLength(struct sk_buff *skb) { struct net_device *dev = skb->dev; struct netdev_queue *txq; struct Qdisc *q; struct sock *sk = skb->sk; int ret = -1; if(sk==NULL) goto qdisc_end; int queue_index = sk->sk_tx_queue_mapping ; txq = &dev->_tx[queue_index]; q = rcu_dereference_bh(txq->qdisc); if (q!=NULL && q->enqueue) ret = qdisc_qlen(q); qdisc_end: // printk(KERN_ALERT "net_device is %s, qdisc_length is %d\n", dev->name, ret); return ret; } \end{lstlisting} \fi \fi
open import Auto open import Function using (const) open import Data.Bool using (Bool; true; false) open import Data.Bool.Show as Bool using () open import Data.List using (_∷_; []) open import Data.Maybe open import Data.Nat using (ℕ; suc; zero) open import Data.Nat.Show as Nat using () open import Data.String using (String; _++_) open import Data.Sum renaming (_⊎_ to Either; inj₁ to left; inj₂ to right) open import Relation.Binary.PropositionalEquality using (_≡_; refl) module Auto.Example.TypeClasses where -------------------------------------------------------------------------------- -- * We can construct a class for the Show function (as a dependent record) * -- -------------------------------------------------------------------------------- record Show (A : Set) : Set where constructor mkShow field show : A → String open Show {{...}} -------------------------------------------------------------------------------- -- * And set up a list of rules which guide the instance resolution * -- -------------------------------------------------------------------------------- rules : HintDB rules = [] << quote instShowEither << quote instShowBool << quote instShowNat where instShowBool : Show Bool instShowBool = mkShow Bool.show instShowNat : Show ℕ instShowNat = mkShow Nat.show instShowEither : {A B : Set} → Show A → Show B → Show (Either A B) instShowEither {A} {B} instShowA instShowB = mkShow showEither where showEither : Either A B → String showEither (left x) = "left " ++ show x showEither (right y) = "right " ++ show y -------------------------------------------------------------------------------- -- * Using these rules and `auto` we can easily and robustly compute the * -- -- * instances we need. * -- -------------------------------------------------------------------------------- example₁ : String example₁ = show (left true) ++ show (right 4) where instance inst : Show (Either Bool ℕ) inst = tactic (auto 5 rules) -------------------------------------------------------------------------------- -- * This fails due to normalisation from the non-dependent pair _×_ to the * -- -- * dependent pair Σ (as `A × B` is defined as `Σ A (λ _ → B)`). * -- -------------------------------------------------------------------------------- module DefaultPair where open import Data.Product using (_×_; _,_) instShowPair : {A B : Set} → Show A → Show B → Show (A × B) instShowPair {A} {B} showA showB = record { show = showPair } where showPair : A × B → String showPair (proj₁ , proj₂) = show proj₁ ++ "," ++ show proj₂ inst : Exception unsupportedSyntax inst = unquote (auto 5 (rules << quote instShowPair) g) where g = quoteTerm (Show (Bool × ℕ)) -------------------------------------------------------------------------------- -- * So we're forced to use a custom pair, which isn't derived from * -- -- * a dependent pair * -- -------------------------------------------------------------------------------- module CustomPair where data _×_ (A B : Set) : Set where _,_ : A → B → A × B instShowPair : ∀ {A B} → Show A → Show B → Show (A × B) instShowPair {A} {B} showA showB = record { show = showPair } where showPair : A × B → String showPair (proj₁ , proj₂) = show proj₁ ++ "," ++ show proj₂ example₂ : String example₂ = show (true , 1) where instance inst : Show (Bool × ℕ) inst = tactic (auto 5 (rules << quote instShowPair)) -------------------------------------------------------------------------------- -- * This fails due to something super weird which I haven't encountered * -- -- * before at all... * -- -------------------------------------------------------------------------------- module AbstractPair where open import Data.Product as Σ using (Σ) abstract _×_ : (A B : Set) → Set A × B = Σ A (const B) instShowPair : ∀ {A B} → Show A → Show B → Show (A × B) instShowPair {A} {B} showA showB = record { show = showPair } where showPair : A × B → String showPair (proj₁ Σ., proj₂) = show proj₁ ++ "," ++ show proj₂ _,_ : {A B : Set} (x : A) (y : B) → A × B _,_ = Σ._,_ --inst : Show (Bool × ℕ) --inst = tactic (auto 5 (rules << quote instShowPair))
""" fuzzify(df::DataFrames.DataFrame; kwargs...) This function adds "fuzziness" to an input `df` # Keyword Arguments - value::Symbol=VALUE_COL - nsample::Integer=50 - distribution::Symbol=:normal - factor """ function fuzzify(df; value = VALUE_COL, sample = SAMPLE_COL, units = :Units, label, sublabel, kwargs..., ) # If samples are not already included in the DataFrame, add them. if !(:Sample in propertynames(df)) val = random_samples(df[:,value]; kwargs...) update_stop!(val) df = DataFrames.crossjoin(df, DataFrames.DataFrame(sample=>1:size(val,2))) df[!,value] .= vcat(val'...) end idx = DataFrames.Not([value, sample]) return DataFrames.groupby(df, idx) end """ """ _distribution_error(args...) = _option_error("distribution", [:normal,:uniform], args...) "" function _option_error(option, allowed::String) throw(ArgumentError("Allowed values for $option: $allowed")) end function _option_error(option, allowed::AbstractArray) return _option_error(option, string((string.(allowed).*", ")...,)[1:end-2]) end function _option_error(option, allowed, value) return if isempty(value) _option_error(option, allowed) else throw(ArgumentError("$option = $value. Allowed values: $allowed")) end end
function installRes = plugin_askinstall(pluginName, pluginFunc, forceInstall) if nargin < 3, forceInstall = false; end; if nargin < 2 || ~exist(pluginFunc) if ~forceInstall db = dbstack; if length(db) > 2 && ~strcmpi(db(end).name, 'checkouteeglab.m'); error([ 'Cannot find ' pluginName ' extension, use EEGLAB Extension Manager to install it' ]); end; installRes = 0; % check is deactivated try, PLUGINLIST = evalin('base', 'PLUGINLIST'); catch, PLUGINLIST = []; end; if ~isempty(PLUGINLIST) && isfield(PLUGINLIST, 'plugin') indPlugin = strmatch(lower(pluginName), lower({ PLUGINLIST.plugin }), 'exact'); if ~isempty(indPlugin) && strcmpi(PLUGINLIST(indPlugin(1)).status, 'deactivated') res = questdlg2( [ pluginName ' extension is de-activated. Do you want to reactivate it now?' ], [ pluginName ' extension installation' ], 'No', 'Yes', 'Yes' ); if strcmpi(res, 'no'), return, end; plugin_reactivate(PLUGINLIST(indPlugin(1)).foldername); evalin('base', 'eeglab rebuild'); installRes = 1; return; end; end; % check for installing res = questdlg2( [ pluginName ' extension is not installed. Do you want to download it now?' ], [ pluginName ' extension installation' ], 'No', 'Yes', 'Yes' ); else res = 'yes'; end; if strcmpi(res, 'no'), return, end; plugins = plugin_getweb('import', []); indPlugin = strmatch(lower(pluginName), lower({ plugins.name }), 'exact'); if isempty(indPlugin), plugins = plugin_getweb('process', []); indPlugin = strmatch(lower(pluginName), lower({ plugins.name })); if isempty(indPlugin), error([ pluginName ' extension not found' ]); end; end; result = plugin_install(plugins(indPlugin(1)).zip, plugins(indPlugin(1)).name, plugins(indPlugin(1)).version, forceInstall); if result == 1, installRes = 1; end; evalin('base', 'eeglab rebuild'); else installRes = 1; end;
module MachineLearning.UtilsTest ( tests ) where import Test.Framework (testGroup) import Test.Framework.Providers.HUnit import Test.HUnit import Test.HUnit.Approx import Test.HUnit.Plus import MachineLearning.Types (Vector, Matrix) import qualified Numeric.LinearAlgebra as LA import qualified Data.Vector.Storable as V import Numeric.LinearAlgebra ((><)) import MachineLearning.Utils a :: Matrix a = (4><5) [ 1, 7, 9, 11, 2 , 77, 4, 6, 9, 0 , -11, -55, 3, 11, 55 , 7, 9, 11, 13, 15 ] sumRows :: Matrix sumRows = (4><1) [ 30 , 96 , 3 , 55 ] sumCols :: Matrix sumCols = (1><5) [74, -35, 29, 44, 72] maxRows :: Matrix maxRows = (4><1) [ 11 , 77 , 55 , 15 ] minCols :: Matrix minCols = (1><5) [-11, -55, 3, 9, 0] sumRowsV = LA.flatten sumRows sumColsV = LA.flatten sumCols maxRowsV = LA.flatten maxRows minColsV = LA.flatten minCols tests = [ testGroup "reduceV" [ testCase "reduceByRowsV: sum" $ assertVector "" 1e-10 sumRowsV (reduceByRowsV V.sum a) , testCase "reduceByColumnsV: sum" $ assertVector "" 1e-10 sumColsV (reduceByColumnsV V.sum a) , testCase "reduceByRowsV: max" $ assertVector "" 1e-10 maxRowsV (reduceByRowsV V.maximum a) , testCase "reduceByColumnsV: min" $ assertVector "" 1e-10 minColsV (reduceByColumnsV V.minimum a) ] , testGroup "reduce" [ testCase "reduceByRows: sum" $ assertMatrix "" 1e-10 sumRows (reduceByRows V.sum a) , testCase "reduceByColumns: sum" $ assertMatrix "" 1e-10 sumCols (reduceByColumns V.sum a) , testCase "reduceByRows: max" $ assertMatrix "" 1e-10 maxRows (reduceByRows V.maximum a) , testCase "reduceByColumns: min" $ assertMatrix "" 1e-10 minCols (reduceByColumns V.minimum a) ] , testGroup "sum" [ testCase "sumByRows" $ assertMatrix "" 1e-10 sumRows (sumByRows a) , testCase "sumColumns" $ assertMatrix "" 1e-10 sumCols (sumByColumns a) ] , testCase "listOfTuplesToList" $ assertEqual "" [11, 9, 27, 3, 43, 11] (listOfTuplesToList [(11, 9), (27, 3), (43, 11)]) ]
\documentclass[DM]{lsstdoc} \author{G. Comoretto} \begin{document} \date{\today} \title{How To Execute docsteady} \mkshorttitle \section{Introduction} This is intended to be a short guide to help the installation and execution of docsteady. \section{Installation}\label{sec:install} Create a conda environment based on the \textbf{docsteady} conda package: \texttt{conda create --name docsteady-env docsteady -c gcomoretto} Ensure that the conda configuration file \texttt{.condarc} does not include the conda-forge channel. To use docsteady, activate the environment as follows: \texttt{conda activate docsteady-env} This environment will provide all dependencies that are required to run docsteady. It is recommended to use the provided conda environment also for development activities, see section \ref{sec:development}. Future releases of docsteady should be provided in the \texttt{conda-forge} channel instead of a private channel. The anaconda \texttt{lsst-dm} channel could however be a more flexible alternative. \section{Execution} It is recommended to provide the credentials seting up the following environment variables: \begin{itemize} \item \texttt{export JIRA\_USER=<jira-username>} \item \texttt{export JIRA\_PASSWORD=<password>} \end{itemize} otherwise, it is required to specify them from the command line using the \texttt{--username} and \texttt{--password} options. In case credential options are omitted and no environment variables are defined, username and password will be prompted interactively. Personal Jira credentials can be used. For CI purposes, a general set of credentials are available, as specified in section \ref{sec:auth}. In order to execute any of the docsteady commands described in the following subsections, a conda environment providing docsteady shall be activated, as described in section \ref{sec:install}. Use \texttt{--help} to get the list of available options for each of the docsteady commands. In addition, existing documents generated using docsteady, have a \texttt{.docugen} file with the command to be executed in CI, which can be used as an example. \subsection{Test Specification Generation} Test specifications are extracted using REST API. All tests cases included in a TM4J folder, including subfolders, are rendered in the same extraction. The folder organization in Jira should correspond to the major subsystem components, and modeled in MagicDraw. The syntax to extract a test specification is the following: \texttt{docsteady generate-spec "</tm4j\_folder>" jira\_docugen.tex} where \texttt{</tm4j\_folder>} shall be replaced by the exact folder where the test cases are defined in the Jira \texttt{Test Cases} tab. For example, the command to extract the DM Acceptance test specification, LDM-639, is the following: \texttt{docsteady generate-spec "/Data Management/Acceptance|LDM-639" [jira\_docugen.tex]} Note that: \begin{itemize} \item the output file \textit{jira\_docugen.tex} is optional in the execution of docsteady, but required in this context in order to include the extracted information in a \LaTeX~document (i.e. LDM-639.tex). If omitted, the docsteady output will just be printed in the terminal; \item the folder name in Jira includes at the end the test specification document handler. This is a best practice to use when organizing test cases in Jira, it helps to orientate in the folder structure; \item an appendix with the traceability to the requirements is produced in the file \textit{jira\_docugen.appendix.tex}, to be included in the test specification tex file. \end{itemize} See LDM-639 Git repository as an example. \subsection{Test Plan and Report Generation} \textbf{Important}: before extracting a test plan and report using docsteady, the corresponding document handler has to be added in the \texttt{Document ID} field in the Jira test plan object. This ensures that the Verification Control Document will include this information. The following command extracts a Test Plan and Report using Jira REST API: \texttt{docsteady generate-tpr <LVV-PXX> <file.tex> [--trace true]} Where: \begin{itemize} \item \texttt{LVV-PXX} is the TM4J object that describes the test campaign, for example \texttt{LVV-P72}; \item \texttt{file.tex} is the Test Plan and Report tex file where the document will be rendered, for example \texttt{DMTR-231.tex}; \item \texttt{--trace true} (optional) generates an appendix with the traceability information. \end{itemize} Each TM4J test plan and related information in Jira is rendered in a different Test Plan and Report document, which filename usually corresponds also to the document handler in Docushare. The generated file can be built directly into the corresponding pdf, however additional files are required. \begin{itemize} \item Makefile \item appendix.tex \item history\_and\_info.tex \end{itemize} When creating the Git repository using \textbf{sqrbot-jr}, all the required files should already be present. See \href{https://sqr-006.lsst.io/}{SQR-006} for more information regarding sqrbot-jr. In case you want to generate a Test Plan and Report for a different subsystem, not DM, you can use the namespace global option: \texttt{docsteady --namespace <NS> generate-tpr <LVV-PXX> <file.tex> [--trace true]} Valid namespaces are: \begin{itemize} \item SE: system Enginering \item DM: Data Management \item TS: Telescope \& Site \end{itemize} See SCTR-14 or DMTR-231 Git repositories as an example. \subsection{Verification Element Baseline Generation} Verification Elements (VE) are Jira issues in the LVV Jira project, of type \texttt{Verification}. They are categorized in Components (DM, SITCOM, etc) and Sub-Components. A VE baseline document is extracted using REST API. All VE associated with a Jira Component or Sub-Component, if specified, are rendered in the same extraction. The syntax to extract a VE baseline information is the following: \texttt{docsteady [--namespace <CMP>] baseline-ve [--subcomponent <SUBC>] jira\_docugen.tex [--details true]} The information is saved in the specified \texttt{jira\_docugen.tex} file. This file has to be included in a \LaTeX~document, where the corresponding context about the Component and Sub-Component is provided. The \texttt{--namespace <CMP>} option identifies the Jira component from which to extract the information. The parameter \texttt{CMP} shall correspond to the Rubin Observatory sub-systems. See the See subsection \ref{sec:components} for the complete list of components. If omitted, the DM component is selected by default. The \texttt{--subcomponent <SUBC>} is optional. If omitted all verification elements of the specified component will be extracted. See \ref{sec:subcomp} for the description of the DM subcomponents. If the option \texttt{--details true} is provided, an extra technical note is generated, including all test case details. See LDM-732 Git repository as an example. \subsubsection{Sub-Components}\label{sec:subcomp} Ideally, Sub-Components are matched to the major products of a LSST/Rubin subsystem. They should also be mapped to the product tree defined in the MagicDraw model. In DM, trying to find a good balance between details and practice, the following components have been defined, in agreement with the DM scientist leader: \begin{itemize} \item Science \item Service \item Network \item Infrastructure \end{itemize} For each of these subcomponents, a different VE baseline document is extracted. \subsection{Verification Control Document Generation} The extraction of the Verification Control Document is done using direct access to the Jira database and not using REST API access, like for all other test documents described above. Since the access to the Jira database is possible only from the Tucson network, it is required to be connected via VPN. A direct access to the Jira database implies also that the username and password to use are different since credentials to access the Jira web interface or the REST API are not enabled to access the database. They are two different authentication systems. Therefore personal Jira credentials will not work with this docsteady command. A special read-only user has been enabled in the Jira database, \textbf{jiraro}. Section \ref{sec:auth} explains where to find the full credentials details. For your convenience, the credentials can be specified in the following environment variables: \begin{itemize} \item \texttt{export JIRA\_VCD\_USER=jiraro} \item \texttt{export JIRA\_VCD\_PASSWORD} (see section \ref{sec:auth}) \item \texttt{export JIRA\_DB=140.252.201.12} \end{itemize} otherwise, it is required to specify them from the command line using the options \texttt{--vcduser}, \texttt{--vcdpwd}, and \texttt{--jiradb}. In case credential options are omitted and no environment variables are defined, they will be prompted interactively. Note also that the Jira database IP address may change. Updated information are maintained in the vault specified in section \ref{sec:auth}. The following command extractsall VCD information regarding \textbf{DM} and generates the file \texttt{jira\_docugen.tex}: \texttt{docsteady [--namespace <COM>] generate-vcd --sql True jira\_docugen.tex} When no \texttt{--namespace if provided}, the DM component is selected by default. The generated file \textbf{jira\_docugen.tex} is meant to be included in LDM-692.tex. In case you want to generate the VCD for a different LSST/Rubin Observatory subsystem VCD, just use the corresponding subsystem code configured in the Jira \textbf{component} field. See next subsection \ref{sec:components} for the complete list. \subsection{Components - Sub-systems}\label{sec:components} Follows the list of components configured for the Jira LVV project. Each component corresponds to a Rubin Observatory Construction subsystem. \begin{itemize} \item \textbf{CAM}: Camera \item \textbf{DM}: Data Management, the default component for all docsteady commands. \item \textbf{EPO}: Education and Public Outreach \item \textbf{OCS}: Observatory Control System \item \textbf{PSE}: Project System Engineering, used for Commisioning (SitCom) \item \textbf{T\&S}: Telescope and Site \end{itemize} In case the subcomponent specified is "None", all VE without subcomponent will be extracted. \section{Development} \label{sec:development} Despite docsteady is a pure python tool, it depends on \textbf{pandoc}, that is a \texttt{c++} compiled library available only as conda package. It has been observed also, that any small change in the version of pandoc may lead to unexpected changes in the resulting \LaTeX~format. Therefore, in order to ensure the expected pandoc behavior, it is important to set-up the conda environment corresponding to the latest docsteady working version. The environment set-up is explained in section \ref{sec:install}. The docsteady source code of available at \url{https://github.com/lsst-dm/docsteady}. To test changes done locally in the source code, use the following procedure: \begin{itemize} \item (if not available) create the environment as specified in section \ref{sec:install} \item activate the environment: \texttt{conda activate docsteady-env} \item clone docsteady repository and checkout a ticket branch \item do your changes \item install the updates in the docsteady-env environment: \texttt{python setup.py install} \item activate the same docsteady-env environment in a different terminal to test the new changed \item once the changes are OK, commit them in the repository and open a PR for merging the branch to master \end{itemize} \section{Documentation Procedure} \label{sec:docproc} The autogeneration of documents may become very confusing if not done in a programmatic way. Please consider the DM documentation approach as a guideline, summarized here. \begin{itemize} \item Create a document handler in DocuShare \item Use the document handler to create a repository in Github, using sqrbot-jr that will also create the corresponding landing page in lsst.io \item Configure the continuous integrations described in next section ~\ref{sec:ci}. \item Render the document to a ticket branch, or to the \textbf{jira-sync} special branch. Never auto-generate the document directly to master \item Ensure that the document is correctly published in the corresponding LSST The Docs landing page and that everybody who is interested can access it. \item Create a GitHub Pull Request to let contributors and stakeholders comment on the changes. \item When a set of activities are completed, and all comments have been addressed, merge the branch/PR to master. \item In case the special \textbf{jira-sync} branch is used, after merging it to master, delete it and recreate from the latest master. Documentation tags corresponding to official issues of the document in Docushare can also be done in the jira-sync special branch. \end{itemize} \section{Continuous Integration}\label{sec:ci} The real added-value of this approach, is the capability to auto-generate continuously the documents from Jira. This is done using the Jenkins service available at: \url{https://lsst-docs-ci.ncsa.illinois.edu/jenkins/} This service is at the moment behind the NCSA firewall, and therefore it requires a VPN to access and monitor the jobs. Authentication to this Jenkins instance is managed via OATH. See next sub-section \ref{sec:auth}. The rendered documents will be available in the corresponding GitHub repositories and LSST The Docs landing pages. The docugen jobs are created using the seeds script defined at the following location: \url{https://github.com/docs-ci/docs-ci-seeds/blob/master/jobs/docugen_jobs.groovy} There should be no need to change this script, unless problems are found in its logic, or improvements need to be implemented The jobs are configured in the following YAML file: \url{https://github.com/docs-ci/docs-ci-seeds/blob/master/etc/docugen.yaml} The seeds job in Jenkins: \url{https://lsst-docs-ci.ncsa.illinois.edu/jenkins/job/Service/job/seeding/} will detect the changes in the YAML configuration file and create/update the the corresponding Jenkins docugen jobs. \subsection{Authentication}\label{sec:auth} The access to \url{https://lsst-docs-ci.ncsa.illinois.edu/jenkins} is granted adding users to the \textbf{docs-ci} GitHub organization, managed by DM Architecture team. Two generic set of credentials to access Jira REST API and the Jira database have been defined. These credentials are available at \texttt{1password.com}, in the LSST-IT architecture vault, but not yet integrated into docsteady. In order to use these credentials, they have to be configured using environment variables, added as options from the command line, or entered when prompted, as specified in this technical note. \appendix \section{Acronyms} \label{sec:acronyms} \begin{tabular}{p{0.145\textwidth}p{0.8\textwidth}}\hline \textbf{Acronym} & \textbf{Description} \\\hline & \\\hline API & Application Programming Interface \\\hline CAM & CAMera \\\hline CI & Continuous Integration \\\hline DM & Data Management \\\hline DMSR & DM System Requirements; LSE-61 \\\hline DMTR & DM Test Report \\\hline EPO & Education and Public Outreach \\\hline HTML & HyperText Markup Language \\\hline IT & Information Technology \\\hline LDM & LSST Data Management (Document Handle) \\\hline LSE & LSST Systems Engineering (Document Handle) \\\hline LSST & Legacy Survey of Space and Time (formerly Large Synoptic Survey Telescope) \\\hline LSSTC & LSST Corporation \\\hline LVV & LSST Verification and Validation (Jira Project) \\\hline LaTeX & (Leslie) Lamport TeX (document markup language and document preparation system) \\\hline NCSA & National Center for Supercomputing Applications \\\hline OAUTH & Open Authorization \\\hline OCS & Observatory Control System \\\hline PR & Pull Request \\\hline PSE & Project System Engineering \\\hline REST & REpresentational State Transfer \\\hline SCTR & SITCOM Test Report \\\hline SITCOM & System Engineering and Commissioning \\\hline T\&S & Telescope and Site \\\hline TM4J & Test Manager for Jira (formerly ATM, Adaptivist Test Manager) \\\hline TS & Test Specification \\\hline VCD & Verification Control Document \\\hline VE & Verification Element \\\hline VPN & virtual private network \\\hline \end{tabular} \end{document}
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.normed_space.multilinear /-! # Formal multilinear series In this file we define `formal_multilinear_series 𝕜 E F` to be a family of `n`-multilinear maps for all `n`, designed to model the sequence of derivatives of a function. In other files we use this notion to define `C^n` functions (called `cont_diff` in `mathlib`) and analytic functions. ## Notations We use the notation `E [×n]→L[𝕜] F` for the space of continuous multilinear maps on `E^n` with values in `F`. This is the space in which the `n`-th derivative of a function from `E` to `F` lives. ## Tags multilinear, formal series -/ noncomputable theory open set fin open_locale topological_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] /-- A formal multilinear series over a field `𝕜`, from `E` to `F`, is given by a family of multilinear maps from `E^n` to `F` for all `n`. -/ @[derive add_comm_group] def formal_multilinear_series (𝕜 : Type*) [nondiscrete_normed_field 𝕜] (E : Type*) [normed_group E] [normed_space 𝕜 E] (F : Type*) [normed_group F] [normed_space 𝕜 F] := Π (n : ℕ), (E [×n]→L[𝕜] F) instance : inhabited (formal_multilinear_series 𝕜 E F) := ⟨0⟩ section module /- `derive` is not able to find the module structure, probably because Lean is confused by the dependent types. We register it explicitly. -/ local attribute [reducible] formal_multilinear_series instance : module 𝕜 (formal_multilinear_series 𝕜 E F) := begin letI : ∀ n, module 𝕜 (continuous_multilinear_map 𝕜 (λ (i : fin n), E) F) := λ n, by apply_instance, apply_instance end end module namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) /-- Forgetting the zeroth term in a formal multilinear series, and interpreting the following terms as multilinear maps into `E →L[𝕜] F`. If `p` corresponds to the Taylor series of a function, then `p.shift` is the Taylor series of the derivative of the function. -/ def shift : formal_multilinear_series 𝕜 E (E →L[𝕜] F) := λn, (p n.succ).curry_right /-- Adding a zeroth term to a formal multilinear series taking values in `E →L[𝕜] F`. This corresponds to starting from a Taylor series for the derivative of a function, and building a Taylor series for the function itself. -/ def unshift (q : formal_multilinear_series 𝕜 E (E →L[𝕜] F)) (z : F) : formal_multilinear_series 𝕜 E F | 0 := (continuous_multilinear_curry_fin0 𝕜 E F).symm z | (n + 1) := continuous_multilinear_curry_right_equiv' 𝕜 n E F (q n) /-- Killing the zeroth coefficient in a formal multilinear series -/ def remove_zero (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E F | 0 := 0 | (n + 1) := p (n + 1) @[simp] lemma remove_zero_coeff_zero : p.remove_zero 0 = 0 := rfl @[simp] lemma remove_zero_coeff_succ (n : ℕ) : p.remove_zero (n+1) = p (n+1) := rfl lemma remove_zero_of_pos {n : ℕ} (h : 0 < n) : p.remove_zero n = p n := by { rw ← nat.succ_pred_eq_of_pos h, refl } /-- Convenience congruence lemma stating in a dependent setting that, if the arguments to a formal multilinear series are equal, then the values are also equal. -/ lemma congr (p : formal_multilinear_series 𝕜 E F) {m n : ℕ} {v : fin m → E} {w : fin n → E} (h1 : m = n) (h2 : ∀ (i : ℕ) (him : i < m) (hin : i < n), v ⟨i, him⟩ = w ⟨i, hin⟩) : p m v = p n w := by { cases h1, congr' with ⟨i, hi⟩, exact h2 i hi hi } /-- Composing each term `pₙ` in a formal multilinear series with `(u, ..., u)` where `u` is a fixed continuous linear map, gives a new formal multilinear series `p.comp_continuous_linear_map u`. -/ def comp_continuous_linear_map (p : formal_multilinear_series 𝕜 F G) (u : E →L[𝕜] F) : formal_multilinear_series 𝕜 E G := λ n, (p n).comp_continuous_linear_map (λ (i : fin n), u) @[simp] lemma comp_continuous_linear_map_apply (p : formal_multilinear_series 𝕜 F G) (u : E →L[𝕜] F) (n : ℕ) (v : fin n → E) : (p.comp_continuous_linear_map u) n v = p n (u ∘ v) := rfl variables (𝕜) {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables [normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] variables [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] /-- Reinterpret a formal `𝕜'`-multilinear series as a formal `𝕜`-multilinear series, where `𝕜'` is a normed algebra over `𝕜`. -/ @[simp] protected def restrict_scalars (p : formal_multilinear_series 𝕜' E F) : formal_multilinear_series 𝕜 E F := λ n, (p n).restrict_scalars 𝕜 end formal_multilinear_series namespace continuous_linear_map /-- Composing each term `pₙ` in a formal multilinear series with a continuous linear map `f` on the left gives a new formal multilinear series `f.comp_formal_multilinear_series p` whose general term is `f ∘ pₙ`. -/ def comp_formal_multilinear_series (f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E G := λ n, f.comp_continuous_multilinear_map (p n) @[simp] lemma comp_formal_multilinear_series_apply (f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : (f.comp_formal_multilinear_series p) n = f.comp_continuous_multilinear_map (p n) := rfl lemma comp_formal_multilinear_series_apply' (f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (v : fin n → E) : (f.comp_formal_multilinear_series p) n v = f (p n v) := rfl end continuous_linear_map
program main use iso_fortran_env , only : dp => REAL64 use matrix_utils , only : toepliz, print use direct_linear_solve , only : mgs_qrfactor, cgs_qrfactor, & & householder, banded_householder, householder_factorization use direct_linear_solve , only : givens_factorization, givens, qriteration use linear_algebra , only : eigvals, svdvals implicit none real(dp), parameter :: lambda = 2.0d0 integer , parameter :: npts = 5 real(8) , allocatable, dimension(:,:) :: A, Q, R, D, U integer :: i real(dp) :: h allocate(A(npts,npts)) allocate(Q(npts,npts)) allocate(R(npts,npts)) allocate(D(npts,npts)) allocate(U(npts,npts)) call assemble_matrix(0.0d0, 1.0d0, npts, lambda, A) call qriteration(A, R, Q, 100, 1.0d-3) stop print *, 'Performing Givens Transformation' Q = 0 R = 0 call givens_factorization(A, Q, R) print *, 'matrix' call print(A) print *, 'Q' call print(Q) print *, 'R' call print(R) ! Check similarity with A print *, 'consistency A' D = matmul(Q, R) print *, norm2(A - D) ! Check Orthogonality D = matmul(Q,transpose(Q)) print *, 'orthogonality Q' do i = 1, npts D(i,i) = 1.0d0 - D(i,i) end do print *, norm2(D) deallocate(A,Q,R,D) contains ! Model problem to solve subroutine assemble_matrix(a, b, npts, lambda, V) real(8), intent(in) :: a, b ! bound of domain integer :: npts ! number of points real(8), intent(out) :: V(npts,npts) real(8), intent(in) :: lambda real(8), parameter :: PI = 3.141592653589793d0 integer :: m, n, i, j h = (b-a)/dble(npts+1) V = 0.0d0 m = npts n = npts do i = 1, m do j = 1, n if (i .eq. j-1) then V(i,j) = -1.0d0 else if (i .eq. j+1) then V(i,j) = -1.0d0 else if (i .eq. j) then V(i,i) = 2.0d0 + lambda*h*h else ! skip zeros end if end do end do end subroutine assemble_matrix end program main
Require Import oeuf.SafeInt. Require Import oeuf.SafeDouble. Definition double_to_int f := match Float.to_int f with | Some i => i | None => Int.zero end.
function d = Point2LineDistance(P, A, B) %------------------------------- Copyright -------------------------------- % Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for % research purposes. All publications which use this platform or any code % in the platform should acknowledge the use of "PlatEMO" and reference "Ye % Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform % for evolutionary multi-objective optimization [educational forum], IEEE % Computational Intelligence Magazine, 2017, 12(4): 73-87". %-------------------------------------------------------------------------- % This function is written by Annibale Panichella d = zeros(size(P,1),1); for i = 1:size(P,1) pa = P(i,:) - A; ba = B - A; t = dot(pa, ba)/dot(ba, ba); d(i,1) = norm(pa - t * ba,2); end end
#!/usr/bin/env python # -*- coding: utf-8 -*- # # nnutil2 - Tensorflow utilities for training neural networks # Copyright (c) 2019, Abdó Roig-Maranges <[email protected]> # # This file is part of 'nnutil2'. # # This file may be modified and distributed under the terms of the 3-clause BSD # license. See the LICENSE file for details. import unittest import numpy as np import tensorflow as tf import nnutil2 as nnu class InitializersApproxIdentity(tf.test.TestCase): def test_approx_identity_1(self): approx_id = nnu.initializers.approx_identity() x = approx_id(shape=(3, 3), dtype=tf.float32) self.assertAllClose(x, tf.eye(3)) def test_approx_identity_2(self): approx_id = nnu.initializers.approx_identity() x = approx_id(shape=(2, 3, 6), dtype=tf.float32) self.assertEqual(x.shape, tf.TensorShape([2, 3, 6])) def test_approx_identity_3(self): approx_id = nnu.initializers.approx_identity() x = approx_id(shape=(2, 6, 3), dtype=tf.float32) self.assertEqual(x.shape, tf.TensorShape([2, 6, 3])) if __name__ == '__main__': tf.test.main()
(** * Sort [SProp], czyli zdania, ale takie jakby inne (TODO) *) (* begin hide *) Set Warnings "-cannot-define-projection". Inductive sEmpty : SProp := . Inductive sUnit : SProp := | stt : sUnit. Inductive seq {A : Type} (x : A) : A -> SProp := | srefl : seq x x. Goal forall A : Type, sEmpty -> A. Proof. destruct 1. Qed. Goal forall {A : Type} (P : A -> Type) (x y : A), seq x y -> P x -> P y. Proof. intros A P x y Hs Hp. Abort. Inductive Box (A : Type) : Prop := | box : A -> Box A. Require Import SetIsType. Lemma SetIsType : Set = Type. Proof. reflexivity. Qed. (* end hide *)
function f=comp_idgtreal(coef,g,a,M,lt,phasetype) %COMP_IDGTREAL Compute IDGTREAL % Usage: f=comp_idgtreal(c,g,a,M,lt,phasetype); % % Input parameters: % c : Array of coefficients. % g : Window function. % a : Length of time shift. % M : Number of modulations. % lt : lattice type % Output parameters: % f : Signal. % % AUTHOR : Peter L. Søndergaard. % TESTING: TEST_DGT % REFERENCE: OK N=size(coef,2); L=N*a; if lt(2)==1 f = comp_isepdgtreal(coef,g,L,a,M,phasetype); else % Quinqux lattice f=comp_inonsepdgtreal_quinqux(coef,g,a,M); end;
module Lang.Function where import Lvl open import Data.Boolean open import Data.List as List using (List) open import Data.List.Functions.Positional as List open import Data.Option open import Data open import Lang.Reflection open import Syntax.Do open import Type -- A default value tactic for implicit arguments. -- This implements a "default arguments" language feature. -- It works by always unifying the hole with the specified value. -- Essentially a constant function for holes. -- Example: -- test : ∀{@(tactic default 𝑇) x : Bool} → Bool -- test{x} = x -- Now, `test = 𝑇`, `test{𝑇} = 𝑇`, `test{𝐹} = 𝐹`. default : ∀{ℓ}{T : Type{ℓ}} → T → Term → TC(Unit{Lvl.𝟎}) default x hole = quoteTC x >>= unify hole -- A no inferrance tactic for implicit arguments. -- This makes implicit arguments work like explicit arguments by throwing an error when the hole does not match perfectly while still maintaining its implicit visibility status. -- It works by always selecting the last argument in the hole, and the last argument is the one closest to the value, which is the argument one expects it to choose. -- Examples: -- idᵢwith : ∀{T : TYPE} → {@(tactic no-infer) x : T} → T -- idᵢwith {x = x} = x -- -- idᵢwithout : ∀{T : TYPE} → {x : T} → T -- idᵢwithout {x = x} = x -- -- postulate test : ({_ : Bool} → Bool) → Bool -- -- test1 : Bool -- test1 = test idᵢwith -- -- test2 : (Bool → Bool) → Bool -- test2 _ = test idᵢwith -- -- test3 : ∀{T : TYPE} → {_ : T} → T -- test3 = idᵢwith -- -- It is useful in these kinds of scenarios because idᵢwithout would require writing the implicit argument explicitly, while idᵢwith always uses the given argument in order like how explicit arguments work. no-infer : Term → TC(Unit{Lvl.𝟎}) no-infer hole@(meta _ args) with List.last(args) ... | None = typeError (List.singleton (strErr "Expected a parameter with \"hidden\" visibility when using \"no-infer\", found none.")) ... | Some (arg (arg-info hidden _) term) = unify hole term {-# CATCHALL #-} ... | Some (arg (arg-info _ _) term) = typeError (List.singleton (strErr "Wrong visibility of argument. Expected \"hidden\" when using \"no-infer\".")) {-# CATCHALL #-} no-infer _ = typeError (List.singleton (strErr "TODO: In what situations is this error occurring?")) -- TODO: Implement idᵢwith, rename it to idᵢ, and put it in Functional. Also, try to refactor Data.Boolean, Data.List and Data.Option so that they only contain the type definition and its constructors. This minimizes the amount of dependencies this module requires (which should help in case of circular dependencies when importing this module).
You can extend the life of your scooter's battery if you take proper care of it. Most people report trouble in getting more than a year or two out of their razor scooter battery set. This is actually a common problem with vehicle batteries. It is recommended to keep your battery fully charged to avoid the build-up of sulfate-ion inside it. Sulfate-ion accumulates when the battery is in a discharged state for a long time.This is the most common reason of premature depletion of lead acid batteries. This can be easily avoided if the scooter battery is kept in a constantly charged state. Even if not used Sealed Lead Acid Batteries will self discharge over long periods. This will leave the battery in a not fully charges state which will enable the sulfate-ions to build up inside the internal plates which will slowly deplete the battery's capacity. In order to prevent that, you should charge the razor scooter battery at least once every three months when it is not in service. Battery Tender chargers are a great way extend the life of your SLA batteries as they are designed to fully charge and maintain a battery at proper storage voltage without the damaging effects caused by trickle chargers. The battery lights had been on for days, indicating a full charge, but nothing happens when turning the throttle. Battery housing is very cumbersome to open, but I'll try to disconnect the battery next. Razor Dirt Quad will intermittently make humming noise rather than moving when throttle is turned. This is a Christmas gift for my grandson and has less than 3 hours of riding time on it. Most likely, the last 2 answers are correct. When you charge the battery, does the light on the charger stay red for several hours before turning green? Check the voltage of the 3 batteries after the charger light turns green. It should be 39-40 volts or so no load. Turn the throttle and see if the voltage drops when the relay clicks. You can connect the batteries directly to the motor and it should go full speed if they are good. Why is my razor e100 red electric scooter going so slow? I purchased my Batteries on E-Bay. Make sure the Batteries they offer come with a Square Trader Warranty.
Require Export Andcomr. Section ml. Variables A B:Prop. Theorem Andcom: and A B <-> and B A. Proof. split; apply Andcomr. Qed. End ml. Check Andcom.
lemma snd_im_cbox [simp]: "cbox a b \<noteq> {} \<Longrightarrow> (snd ` cbox (a,c) (b,d)) = cbox c d"
------------------------------------------------------------------------ -- The Agda standard library -- -- Basic definitions for Characters ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} module Data.Char.Base where ------------------------------------------------------------------------ -- Re-export the type, and renamed primitives open import Agda.Builtin.Char public using ( Char ) renaming -- testing ( primIsLower to isLower ; primIsDigit to isDigit ; primIsAlpha to isAlpha ; primIsSpace to isSpace ; primIsAscii to isAscii ; primIsLatin1 to isLatin1 ; primIsPrint to isPrint ; primIsHexDigit to isHexDigit -- transforming ; primToUpper to toUpper ; primToLower to toLower -- converting ; primCharToNat to toNat ; primNatToChar to fromNat ) open import Agda.Builtin.String public using () renaming ( primShowChar to show )
(* Anders Schlichtkrull & Jørgen Villadsen, DTU Compute, Denmark *) chapter \<open>On Paraconsistency\<close> text \<open> Paraconsistency concerns inference systems that do not explode given a contradiction. The Internet Encyclopedia of Philosophy has a survey article on paraconsistent logic. The following Isabelle theory formalizes a specific paraconsistent many-valued logic. \<close> theory Paraconsistency imports Main begin text \<open> The details about our logic are in our article in a special issue on logical approaches to paraconsistency in the Journal of Applied Non-Classical Logics (Volume 15, Number 1, 2005). \<close> section \<open>Syntax and Semantics\<close> subsection \<open>Syntax of Propositional Logic\<close> text \<open> Only the primed operators return indeterminate truth values. \<close> type_synonym id = string datatype fm = Pro id | Truth | Neg' fm | Con' fm fm | Eql fm fm | Eql' fm fm abbreviation Falsity :: fm where "Falsity \<equiv> Neg' Truth" abbreviation Dis' :: "fm \<Rightarrow> fm \<Rightarrow> fm" where "Dis' p q \<equiv> Neg' (Con' (Neg' p) (Neg' q))" abbreviation Imp :: "fm \<Rightarrow> fm \<Rightarrow> fm" where "Imp p q \<equiv> Eql p (Con' p q)" abbreviation Imp' :: "fm \<Rightarrow> fm \<Rightarrow> fm" where "Imp' p q \<equiv> Eql' p (Con' p q)" abbreviation Box :: "fm \<Rightarrow> fm" where "Box p \<equiv> Eql p Truth" abbreviation Neg :: "fm \<Rightarrow> fm" where "Neg p \<equiv> Box (Neg' p)" abbreviation Con :: "fm \<Rightarrow> fm \<Rightarrow> fm" where "Con p q \<equiv> Box (Con' p q)" abbreviation Dis :: "fm \<Rightarrow> fm \<Rightarrow> fm" where "Dis p q \<equiv> Box (Dis' p q)" abbreviation Cla :: "fm \<Rightarrow> fm" where "Cla p \<equiv> Dis (Box p) (Eql p Falsity)" abbreviation Nab :: "fm \<Rightarrow> fm" where "Nab p \<equiv> Neg (Cla p)" subsection \<open>Semantics of Propositional Logic\<close> text \<open> There is a countably infinite number of indeterminate truth values. \<close> datatype tv = Det bool | Indet nat abbreviation (input) eval_neg :: "tv \<Rightarrow> tv" where "eval_neg x \<equiv> ( case x of Det False \<Rightarrow> Det True | Det True \<Rightarrow> Det False | Indet n \<Rightarrow> Indet n )" fun eval :: "(id \<Rightarrow> tv) \<Rightarrow> fm \<Rightarrow> tv" where "eval i (Pro s) = i s" | "eval i Truth = Det True" | "eval i (Neg' p) = eval_neg (eval i p)" | "eval i (Con' p q) = ( if eval i p = eval i q then eval i p else if eval i p = Det True then eval i q else if eval i q = Det True then eval i p else Det False )" | "eval i (Eql p q) = ( if eval i p = eval i q then Det True else Det False )" | "eval i (Eql' p q) = ( if eval i p = eval i q then Det True else ( case (eval i p, eval i q) of (Det True, _) \<Rightarrow> eval i q | (_, Det True) \<Rightarrow> eval i p | (Det False, _) \<Rightarrow> eval_neg (eval i q) | (_, Det False) \<Rightarrow> eval_neg (eval i p) | _ \<Rightarrow> Det False ) )" lemma eval_equality_simplify: "eval i (Eql p q) = Det (eval i p = eval i q)" by simp theorem eval_equality: "eval i (Eql' p q) = ( if eval i p = eval i q then Det True else if eval i p = Det True then eval i q else if eval i q = Det True then eval i p else if eval i p = Det False then eval i (Neg' q) else if eval i q = Det False then eval i (Neg' p) else Det False )" by (cases "eval i p"; cases "eval i q") simp_all theorem eval_negation: "eval i (Neg' p) = ( if eval i p = Det False then Det True else if eval i p = Det True then Det False else eval i p )" by (cases "eval i p") simp_all corollary "eval i (Cla p) = eval i (Box (Dis' p (Neg' p)))" using eval_negation by simp lemma double_negation: "eval i p = eval i (Neg' (Neg' p))" using eval_negation by simp subsection \<open>Validity and Consistency\<close> text \<open> Validity gives the set of theorems and the logic has at least a theorem and a non-theorem. \<close> definition valid :: "fm \<Rightarrow> bool" where "valid p \<equiv> \<forall>i. eval i p = Det True" proposition "valid Truth" and "\<not> valid Falsity" unfolding valid_def by simp_all section \<open>Truth Tables\<close> subsection \<open>String Functions\<close> text \<open> The following functions support arbitrary unary and binary truth tables. \<close> definition tv_pair_row :: "tv list \<Rightarrow> tv \<Rightarrow> (tv * tv) list" where "tv_pair_row tvs tv \<equiv> map (\<lambda>x. (tv, x)) tvs" definition tv_pair_table :: "tv list \<Rightarrow> (tv * tv) list list" where "tv_pair_table tvs \<equiv> map (tv_pair_row tvs) tvs" definition map_row :: "(tv \<Rightarrow> tv \<Rightarrow> tv) \<Rightarrow> (tv * tv) list \<Rightarrow> tv list" where "map_row f tvtvs \<equiv> map (\<lambda>(x, y). f x y) tvtvs" definition map_table :: "(tv \<Rightarrow> tv \<Rightarrow> tv) \<Rightarrow> (tv * tv) list list \<Rightarrow> tv list list" where "map_table f tvtvss \<equiv> map (map_row f) tvtvss" definition unary_truth_table :: "fm \<Rightarrow> tv list \<Rightarrow> tv list" where "unary_truth_table p tvs \<equiv> map (\<lambda>x. eval ((\<lambda>s. undefined)(''p'' := x)) p) tvs" definition binary_truth_table :: "fm \<Rightarrow> tv list \<Rightarrow> tv list list" where "binary_truth_table p tvs \<equiv> map_table (\<lambda>x y. eval ((\<lambda>s. undefined)(''p'' := x, ''q'' := y)) p) (tv_pair_table tvs)" definition digit_of_nat :: "nat \<Rightarrow> char" where "digit_of_nat n \<equiv> (if n = 1 then (CHR ''1'') else if n = 2 then (CHR ''2'') else if n = 3 then (CHR ''3'') else if n = 4 then (CHR ''4'') else if n = 5 then (CHR ''5'') else if n = 6 then (CHR ''6'') else if n = 7 then (CHR ''7'') else if n = 8 then (CHR ''8'') else if n = 9 then (CHR ''9'') else (CHR ''0''))" fun string_of_nat :: "nat \<Rightarrow> string" where "string_of_nat n = (if n < 10 then [digit_of_nat n] else string_of_nat (n div 10) @ [digit_of_nat (n mod 10)])" fun string_tv :: "tv \<Rightarrow> string" where "string_tv (Det True) = ''*''" | "string_tv (Det False) = ''o''" | "string_tv (Indet n) = string_of_nat n" definition appends :: "string list \<Rightarrow> string" where "appends strs \<equiv> foldr append strs []" definition appends_nl :: "string list \<Rightarrow> string" where "appends_nl strs \<equiv> ''\<newline> '' @ foldr (\<lambda>s s'. s @ ''\<newline> '' @ s') (butlast strs) (last strs) @ ''\<newline>''" definition string_table :: "tv list list \<Rightarrow> string list list" where "string_table tvss \<equiv> map (map string_tv) tvss" definition string_table_string :: "string list list \<Rightarrow> string" where "string_table_string strss \<equiv> appends_nl (map appends strss)" definition unary :: "fm \<Rightarrow> tv list \<Rightarrow> string" where "unary p tvs \<equiv> appends_nl (map string_tv (unary_truth_table p tvs))" definition binary :: "fm \<Rightarrow> tv list \<Rightarrow> string" where "binary p tvs \<equiv> string_table_string (string_table (binary_truth_table p tvs))" subsection \<open>Main Truth Tables\<close> text \<open> The omitted Cla (for Classic) is discussed later; Nab (for Nabla) is simply the negation of it. \<close> proposition (* Box Truth Table *) "unary (Box (Pro ''p'')) [Det True, Det False, Indet 1] = '' * o o ''" by code_simp proposition (* Con' Truth Table *) "binary (Con' (Pro ''p'') (Pro ''q'')) [Det True, Det False, Indet 1, Indet 2] = '' *o12 oooo 1o1o 2oo2 ''" by code_simp proposition (* Dis' Truth Table *) "binary (Dis' (Pro ''p'') (Pro ''q'')) [Det True, Det False, Indet 1, Indet 2] = '' **** *o12 *11* *2*2 ''" by code_simp proposition (* Neg' Truth Table *) "unary (Neg' (Pro ''p'')) [Det True, Det False, Indet 1] = '' o * 1 ''" by code_simp proposition (* Eql' Truth Table *) "binary (Eql' (Pro ''p'') (Pro ''q'')) [Det True, Det False, Indet 1, Indet 2] = '' *o12 o*12 11*o 22o* ''" by code_simp proposition (* Imp' Truth Table *) "binary (Imp' (Pro ''p'') (Pro ''q'')) [Det True, Det False, Indet 1, Indet 2] = '' *o12 **** *1*1 *22* ''" by code_simp proposition (* Neg Truth Table *) "unary (Neg (Pro ''p'')) [Det True, Det False, Indet 1] = '' o * o ''" by code_simp proposition (* Eql Truth Table *) "binary (Eql (Pro ''p'') (Pro ''q'')) [Det True, Det False, Indet 1, Indet 2] = '' *ooo o*oo oo*o ooo* ''" by code_simp proposition (* Imp Truth Table *) "binary (Imp (Pro ''p'') (Pro ''q'')) [Det True, Det False, Indet 1, Indet 2] = '' *ooo **** *o*o *oo* ''" by code_simp proposition (* Nab Truth Table *) "unary (Nab (Pro ''p'')) [Det True, Det False, Indet 1] = '' o o * ''" by code_simp proposition (* Con Truth Table *) "binary (Con (Pro ''p'') (Pro ''q'')) [Det True, Det False, Indet 1, Indet 2] = '' *ooo oooo oooo oooo ''" by code_simp proposition (* Dis Truth Table *) "binary (Dis (Pro ''p'') (Pro ''q'')) [Det True, Det False, Indet 1, Indet 2] = '' **** *ooo *oo* *o*o ''" by code_simp section \<open>Basic Theorems\<close> subsection \<open>Selected Theorems and Non-Theorems\<close> text \<open> Many of the following theorems and non-theorems use assumptions and meta-variables. \<close> proposition "valid (Cla (Box p))" and "\<not> valid (Nab (Box p))" unfolding valid_def by simp_all proposition "valid (Cla (Cla p))" and "\<not> valid (Nab (Nab p))" unfolding valid_def by simp_all proposition "valid (Cla (Nab p))" and "\<not> valid (Nab (Cla p))" unfolding valid_def by simp_all proposition "valid (Box p) \<longleftrightarrow> valid (Box (Box p))" unfolding valid_def by simp proposition "valid (Neg p) \<longleftrightarrow> valid (Neg' p)" unfolding valid_def by simp proposition "valid (Con p q) \<longleftrightarrow> valid (Con' p q)" unfolding valid_def by simp proposition "valid (Dis p q) \<longleftrightarrow> valid (Dis' p q)" unfolding valid_def by simp proposition "valid (Eql p q) \<longleftrightarrow> valid (Eql' p q)" unfolding valid_def using eval.simps tv.inject eval_equality eval_negation by (metis (full_types)) proposition "valid (Imp p q) \<longleftrightarrow> valid (Imp' p q)" unfolding valid_def using eval.simps tv.inject eval_equality eval_negation by (metis (full_types)) proposition "\<not> valid (Pro ''p'')" unfolding valid_def by auto proposition "\<not> valid (Neg' (Pro ''p''))" proof - have "eval (\<lambda>s. Det True) (Neg' (Pro ''p'')) = Det False" by simp then show ?thesis unfolding valid_def using tv.inject by metis qed proposition assumes "valid p" shows "\<not> valid (Neg' p)" using assms unfolding valid_def by simp proposition assumes "valid (Neg' p)" shows "\<not> valid p" using assms unfolding valid_def by force proposition "valid (Neg' (Neg' p)) \<longleftrightarrow> valid p" unfolding valid_def using double_negation by simp theorem conjunction: "valid (Con' p q) \<longleftrightarrow> valid p \<and> valid q" unfolding valid_def by auto corollary assumes "valid (Con' p q)" shows "valid p" and "valid q" using assms conjunction by simp_all proposition assumes "valid p" and "valid (Imp p q)" shows "valid q" using assms eval.simps tv.inject unfolding valid_def by (metis (full_types)) proposition assumes "valid p" and "valid (Imp' p q)" shows "valid q" using assms eval.simps tv.inject eval_equality unfolding valid_def by (metis (full_types)) subsection \<open>Key Equalities\<close> text \<open> The key equalities are part of the motivation for the semantic clauses. \<close> proposition "valid (Eql p (Neg' (Neg' p)))" unfolding valid_def using double_negation by simp proposition "valid (Eql Truth (Neg' Falsity))" unfolding valid_def by simp proposition "valid (Eql Falsity (Neg' Truth))" unfolding valid_def by simp proposition "valid (Eql p (Con' p p))" unfolding valid_def by simp proposition "valid (Eql p (Con' Truth p))" unfolding valid_def by simp proposition "valid (Eql p (Con' p Truth))" unfolding valid_def by simp proposition "valid (Eql Truth (Eql' p p))" unfolding valid_def by simp proposition "valid (Eql p (Eql' Truth p))" unfolding valid_def by simp proposition "valid (Eql p (Eql' p Truth))" unfolding valid_def proof fix i show "eval i (Eql p (Eql' p Truth)) = Det True" by (cases "eval i p") simp_all qed proposition "valid (Eql (Neg' p) (Eql' Falsity p))" unfolding valid_def proof fix i show "eval i (Eql (Neg' p) (Eql' (Neg' Truth) p)) = Det True" by (cases "eval i p") simp_all qed proposition "valid (Eql (Neg' p) (Eql' p Falsity))" unfolding valid_def using eval.simps eval_equality eval_negation by metis section \<open>Further Non-Theorems\<close> subsection \<open>Smaller Domains and Paraconsistency\<close> text \<open> Validity is relativized to a set of indeterminate truth values (called a domain). \<close> definition domain :: "nat set \<Rightarrow> tv set" where "domain U \<equiv> {Det True, Det False} \<union> Indet ` U" theorem universal_domain: "domain {n. True} = {x. True}" proof - have "\<forall>x. x = Det True \<or> x = Det False \<or> x \<in> range Indet" using range_eqI tv.exhaust tv.inject by metis then show ?thesis unfolding domain_def by blast qed definition valid_in :: "nat set \<Rightarrow> fm \<Rightarrow> bool" where "valid_in U p \<equiv> \<forall>i. range i \<subseteq> domain U \<longrightarrow> eval i p = Det True" abbreviation valid_boole :: "fm \<Rightarrow> bool" where "valid_boole p \<equiv> valid_in {} p" proposition "valid p \<longleftrightarrow> valid_in {n. True} p" unfolding valid_def valid_in_def using universal_domain by simp theorem valid_valid_in: assumes "valid p" shows "valid_in U p" using assms unfolding valid_in_def valid_def by simp theorem transfer: assumes "\<not> valid_in U p" shows "\<not> valid p" using assms valid_valid_in by blast proposition "valid_in U (Neg' (Neg' p)) \<longleftrightarrow> valid_in U p" unfolding valid_in_def using double_negation by simp theorem conjunction_in: "valid_in U (Con' p q) \<longleftrightarrow> valid_in U p \<and> valid_in U q" unfolding valid_in_def by auto corollary assumes "valid_in U (Con' p q)" shows "valid_in U p" and "valid_in U q" using assms conjunction_in by simp_all proposition assumes "valid_in U p" and "valid_in U (Imp p q)" shows "valid_in U q" using assms eval.simps tv.inject unfolding valid_in_def by (metis (full_types)) proposition assumes "valid_in U p" and "valid_in U (Imp' p q)" shows "valid_in U q" using assms eval.simps tv.inject eval_equality unfolding valid_in_def by (metis (full_types)) abbreviation (input) Explosion :: "fm \<Rightarrow> fm \<Rightarrow> fm" where "Explosion p q \<equiv> Imp' (Con' p (Neg' p)) q" proposition "valid_boole (Explosion (Pro ''p'') (Pro ''q''))" unfolding valid_in_def proof (rule; rule) fix i :: "id \<Rightarrow> tv" assume "range i \<subseteq> domain {}" then have "i ''p'' \<in> {Det True, Det False}" "i ''q'' \<in> {Det True, Det False}" unfolding domain_def by auto then show "eval i (Explosion (Pro ''p'') (Pro ''q'')) = Det True" by (cases "i ''p''"; cases "i ''q''") simp_all qed lemma explosion_counterexample: "\<not> valid_in {1} (Explosion (Pro ''p'') (Pro ''q''))" proof - let ?i = "(\<lambda>s. Indet 1)(''q'' := Det False)" have "range ?i \<subseteq> domain {1}" unfolding domain_def by (simp add: image_subset_iff) moreover have "eval ?i (Explosion (Pro ''p'') (Pro ''q'')) = Indet 1" by simp moreover have "Indet 1 \<noteq> Det True" by simp ultimately show ?thesis unfolding valid_in_def by metis qed theorem explosion_not_valid: "\<not> valid (Explosion (Pro ''p'') (Pro ''q''))" using explosion_counterexample transfer by simp proposition "\<not> valid (Imp (Con' (Pro ''p'') (Neg' (Pro ''p''))) (Pro ''q''))" using explosion_counterexample transfer eval.simps tv.simps unfolding valid_in_def \<comment> \<open>by smt OK\<close> proof - assume *: "\<not> (\<forall>i. range i \<subseteq> domain U \<longrightarrow> eval i p = Det True) \<Longrightarrow> \<not> valid p" for U p assume "\<not> (\<forall>i. range i \<subseteq> domain {1} \<longrightarrow> eval i (Explosion (Pro ''p'') (Pro ''q'')) = Det True)" then obtain i where **: "range i \<subseteq> domain {1} \<and> eval i (Explosion (Pro ''p'') (Pro ''q'')) \<noteq> Det True" by blast then have "eval i (Con' (Pro ''p'') (Neg' (Pro ''p''))) \<noteq> eval i (Con' (Con' (Pro ''p'') (Neg' (Pro ''p''))) (Pro ''q''))" by force then show ?thesis using * ** by force qed subsection \<open>Example: Contraposition\<close> text \<open> Contraposition is not valid. \<close> abbreviation (input) Contraposition :: "fm \<Rightarrow> fm \<Rightarrow> fm" where "Contraposition p q \<equiv> Eql' (Imp' p q) (Imp' (Neg' q) (Neg' p))" proposition "valid_boole (Contraposition (Pro ''p'') (Pro ''q''))" unfolding valid_in_def proof (rule; rule) fix i :: "id \<Rightarrow> tv" assume "range i \<subseteq> domain {}" then have "i ''p'' \<in> {Det True, Det False}" "i ''q'' \<in> {Det True, Det False}" unfolding domain_def by auto then show "eval i (Contraposition (Pro ''p'') (Pro ''q'')) = Det True" by (cases "i ''p''"; cases "i ''q''") simp_all qed proposition "valid_in {1} (Contraposition (Pro ''p'') (Pro ''q''))" unfolding valid_in_def proof (rule; rule) fix i :: "id \<Rightarrow> tv" assume "range i \<subseteq> domain {1}" then have "i ''p'' \<in> {Det True, Det False, Indet 1}" "i ''q'' \<in> {Det True, Det False, Indet 1}" unfolding domain_def by auto then show "eval i (Contraposition (Pro ''p'') (Pro ''q'')) = Det True" by (cases "i ''p''"; cases "i ''q''") simp_all qed lemma contraposition_counterexample: "\<not> valid_in {1, 2} (Contraposition (Pro ''p'') (Pro ''q''))" proof - let ?i = "(\<lambda>s. Indet 1)(''q'' := Indet 2)" have "range ?i \<subseteq> domain {1, 2}" unfolding domain_def by (simp add: image_subset_iff) moreover have "eval ?i (Contraposition (Pro ''p'') (Pro ''q'')) = Det False" by simp moreover have "Det False \<noteq> Det True" by simp ultimately show ?thesis unfolding valid_in_def by metis qed theorem contraposition_not_valid: "\<not> valid (Contraposition (Pro ''p'') (Pro ''q''))" using contraposition_counterexample transfer by simp subsection \<open>More Than Four Truth Values Needed\<close> text \<open> Cla3 is valid for two indeterminate truth values but not for three indeterminate truth values. \<close> lemma ranges: assumes "range i \<subseteq> domain U" shows "eval i p \<in> domain U" using assms unfolding domain_def by (induct p) auto proposition (* Cla Truth Table *) "unary (Cla (Pro ''p'')) [Det True, Det False, Indet 1] = '' * * o ''" by code_simp proposition "valid_boole (Cla p)" unfolding valid_in_def proof (rule; rule) fix i :: "id \<Rightarrow> tv" assume "range i \<subseteq> domain {}" then have "eval i p \<in> {Det True, Det False}" using ranges[of i "{}"] unfolding domain_def by auto then show "eval i (Cla p) = Det True" by (cases "eval i p") simp_all qed proposition "\<not> valid_in {1} (Cla (Pro ''p''))" proof - let ?i = "\<lambda>s. Indet 1" have "range ?i \<subseteq> domain {1}" unfolding domain_def by (simp add: image_subset_iff) moreover have "eval ?i (Cla (Pro ''p'')) = Det False" by simp moreover have "Det False \<noteq> Det True" by simp ultimately show ?thesis unfolding valid_in_def by metis qed abbreviation (input) Cla2 :: "fm \<Rightarrow> fm \<Rightarrow> fm" where "Cla2 p q \<equiv> Dis (Dis (Cla p) (Cla q)) (Eql p q)" proposition (* Cla2 Truth Table *) "binary (Cla2 (Pro ''p'') (Pro ''q'')) [Det True, Det False, Indet 1, Indet 2] = '' **** **** ***o **o* ''" by code_simp proposition "valid_boole (Cla2 p q)" unfolding valid_in_def proof (rule; rule) fix i :: "id \<Rightarrow> tv" assume range: "range i \<subseteq> domain {}" then have "eval i p \<in> {Det True, Det False}" "eval i q \<in> {Det True, Det False}" using ranges[of i "{}"] unfolding domain_def by auto then show "eval i (Cla2 p q) = Det True" by (cases "eval i p"; cases "eval i q") simp_all qed proposition "valid_in {1} (Cla2 p q)" unfolding valid_in_def proof (rule; rule) fix i :: "id \<Rightarrow> tv" assume range: "range i \<subseteq> domain {1}" then have "eval i p \<in> {Det True, Det False, Indet 1}" "eval i q \<in> {Det True, Det False, Indet 1}" using ranges[of i "{1}"] unfolding domain_def by auto then show "eval i (Cla2 p q) = Det True" by (cases "eval i p"; cases "eval i q") simp_all qed proposition "\<not> valid_in {1, 2} (Cla2 (Pro ''p'') (Pro ''q''))" proof - let ?i = "(\<lambda>s. Indet 1)(''q'' := Indet 2)" have "range ?i \<subseteq> domain {1, 2}" unfolding domain_def by (simp add: image_subset_iff) moreover have "eval ?i (Cla2 (Pro ''p'') (Pro ''q'')) = Det False" by simp moreover have "Det False \<noteq> Det True" by simp ultimately show ?thesis unfolding valid_in_def by metis qed abbreviation (input) Cla3 :: "fm \<Rightarrow> fm \<Rightarrow> fm \<Rightarrow> fm" where "Cla3 p q r \<equiv> Dis (Dis (Cla p) (Dis (Cla q) (Cla r))) (Dis (Eql p q) (Dis (Eql p r) (Eql q r)))" proposition "valid_boole (Cla3 p q r)" unfolding valid_in_def proof (rule; rule) fix i :: "id \<Rightarrow> tv" assume "range i \<subseteq> domain {}" then have "eval i p \<in> {Det True, Det False}" "eval i q \<in> {Det True, Det False}" "eval i r \<in> {Det True, Det False}" using ranges[of i "{}"] unfolding domain_def by auto then show "eval i (Cla3 p q r) = Det True" by (cases "eval i p"; cases "eval i q"; cases "eval i r") simp_all qed proposition "valid_in {1} (Cla3 p q r)" unfolding valid_in_def proof (rule; rule) fix i :: "id \<Rightarrow> tv" assume "range i \<subseteq> domain {1}" then have "eval i p \<in> {Det True, Det False, Indet 1}" "eval i q \<in> {Det True, Det False, Indet 1}" "eval i r \<in> {Det True, Det False, Indet 1}" using ranges[of i "{1}"] unfolding domain_def by auto then show "eval i (Cla3 p q r) = Det True" by (cases "eval i p"; cases "eval i q"; cases "eval i r") simp_all qed proposition "valid_in {1, 2} (Cla3 p q r)" unfolding valid_in_def proof (rule; rule) fix i :: "id \<Rightarrow> tv" assume "range i \<subseteq> domain {1, 2}" then have "eval i p \<in> {Det True, Det False, Indet 1, Indet 2}" "eval i q \<in> {Det True, Det False, Indet 1, Indet 2}" "eval i r \<in> {Det True, Det False, Indet 1, Indet 2}" using ranges[of i "{1, 2}"] unfolding domain_def by auto then show "eval i (Cla3 p q r) = Det True" by (cases "eval i p"; cases "eval i q"; cases "eval i r") auto qed proposition "\<not> valid_in {1, 2, 3} (Cla3 (Pro ''p'') (Pro ''q'') (Pro ''r''))" proof - let ?i = "(\<lambda>s. Indet 1)(''q'' := Indet 2, ''r'' := Indet 3)" have "range ?i \<subseteq> domain {1, 2, 3}" unfolding domain_def by (simp add: image_subset_iff) moreover have "eval ?i (Cla3 (Pro ''p'') (Pro ''q'') (Pro ''r'')) = Det False" by simp moreover have "Det False \<noteq> Det True" by simp ultimately show ?thesis unfolding valid_in_def by metis qed section \<open>Further Meta-Theorems\<close> subsection \<open>Fundamental Definitions and Lemmas\<close> text \<open> The function props collects the set of propositional symbols occurring in a formula. \<close> fun props :: "fm \<Rightarrow> id set" where "props Truth = {}" | "props (Pro s) = {s}" | "props (Neg' p) = props p" | "props (Con' p q) = props p \<union> props q" | "props (Eql p q) = props p \<union> props q" | "props (Eql' p q) = props p \<union> props q" lemma relevant_props: assumes "\<forall>s \<in> props p. i1 s = i2 s" shows "eval i1 p = eval i2 p" using assms by (induct p) (simp_all, metis) fun change_tv :: "(nat \<Rightarrow> nat) \<Rightarrow> tv \<Rightarrow> tv" where "change_tv f (Det b) = Det b" | "change_tv f (Indet n) = Indet (f n)" lemma change_tv_injection: assumes "inj f" shows "inj (change_tv f)" proof - have "change_tv f tv1 = change_tv f tv2 \<Longrightarrow> tv1 = tv2" for tv1 tv2 using assms by (cases tv1; cases tv2) (simp_all add: inj_eq) then show ?thesis by (simp add: injI) qed definition change_int :: "(nat \<Rightarrow> nat) \<Rightarrow> (id \<Rightarrow> tv) \<Rightarrow> (id \<Rightarrow> tv)" where "change_int f i \<equiv> \<lambda>s. change_tv f (i s)" lemma eval_change: assumes "inj f" shows "eval (change_int f i) p = change_tv f (eval i p)" proof (induct p) fix p assume "eval (change_int f i) p = change_tv f (eval i p)" then have "eval_neg (eval (change_int f i) p) = eval_neg (change_tv f (eval i p))" by simp then have "eval_neg (eval (change_int f i) p) = change_tv f (eval_neg (eval i p))" by (cases "eval i p") (simp_all add: case_bool_if) then show "eval (change_int f i) (Neg' p) = change_tv f (eval i (Neg' p))" by simp next fix p1 p2 assume ih1: "eval (change_int f i) p1 = change_tv f (eval i p1)" assume ih2: "eval (change_int f i) p2 = change_tv f (eval i p2)" show "eval (change_int f i) (Con' p1 p2) = change_tv f (eval i (Con' p1 p2))" proof (cases "eval i p1 = eval i p2") assume a: "eval i p1 = eval i p2" then have yes: "eval i (Con' p1 p2) = eval i p1" by auto from a have "change_tv f (eval i p1) = change_tv f (eval i p2)" by auto then have "eval (change_int f i) p1 = eval (change_int f i) p2" using ih1 ih2 by auto then have "eval (change_int f i) (Con' p1 p2) = eval (change_int f i) p1" by auto then show "eval (change_int f i) (Con' p1 p2) = change_tv f (eval i (Con' p1 p2))" using yes ih1 by auto next assume a': "eval i p1 \<noteq> eval i p2" from a' have b': "eval (change_int f i) p1 \<noteq> eval (change_int f i) p2" using assms ih1 ih2 change_tv_injection the_inv_f_f by metis show "eval (change_int f i) (Con' p1 p2) = change_tv f (eval i (Con' p1 p2))" proof (cases "eval i p1 = Det True") assume a: "eval i p1 = Det True" from a a' have "eval i (Con' p1 p2) = eval i p2" by auto then have c: "change_tv f (eval i (Con' p1 p2)) = change_tv f (eval i p2)" by auto from a have b: "eval (change_int f i) p1 = Det True" using ih1 by auto from b b' have "eval (change_int f i) (Con' p1 p2) = eval (change_int f i) p2" by auto then show "eval (change_int f i) (Con' p1 p2) = change_tv f (eval i (Con' p1 p2))" using c ih2 by auto next assume a'': "eval i p1 \<noteq> Det True" from a'' have b'': "eval (change_int f i) p1 \<noteq> Det True" using assms ih1 ih2 change_tv_injection the_inv_f_f change_tv.simps by metis show "eval (change_int f i) (Con' p1 p2) = change_tv f (eval i (Con' p1 p2))" proof (cases "eval i p2 = Det True") assume a: "eval i p2 = Det True" from a a' a'' have "eval i (Con' p1 p2) = eval i p1" by auto then have c: "change_tv f (eval i (Con' p1 p2)) = change_tv f (eval i p1)" by auto from a have b: "eval (change_int f i) p2 = Det True" using ih2 by auto from b b' b'' have "eval (change_int f i) (Con' p1 p2) = eval (change_int f i) p1" by auto then show "eval (change_int f i) (Con' p1 p2) = change_tv f (eval i (Con' p1 p2))" using c ih1 by auto next assume a''': "eval i p2 \<noteq> Det True" from a' a'' a''' have "eval i (Con' p1 p2) = Det False" by auto then have c: "change_tv f (eval i (Con' p1 p2)) = Det False" by auto from a''' have b''': "eval (change_int f i) p2 \<noteq> Det True" using assms ih1 ih2 change_tv_injection the_inv_f_f change_tv.simps by metis from b' b'' b''' have "eval (change_int f i) (Con' p1 p2) = Det False" by auto then show "eval (change_int f i) (Con' p1 p2) = change_tv f (eval i (Con' p1 p2))" using c by auto qed qed qed next fix p1 p2 assume ih1: "eval (change_int f i) p1 = change_tv f (eval i p1)" assume ih2: "eval (change_int f i) p2 = change_tv f (eval i p2)" have "Det (eval (change_int f i) p1 = eval (change_int f i) p2) = Det (change_tv f (eval i p1) = change_tv f (eval i p2))" using ih1 ih2 by simp also have "... = Det ((eval i p1) = (eval i p2))" using assms change_tv_injection by (simp add: inj_eq) also have "... = change_tv f (Det (eval i p1 = eval i p2))" by simp finally show "eval (change_int f i) (Eql p1 p2) = change_tv f (eval i (Eql p1 p2))" by simp next fix p1 p2 assume ih1: "eval (change_int f i) p1 = change_tv f (eval i p1)" assume ih2: "eval (change_int f i) p2 = change_tv f (eval i p2)" show "eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))" proof (cases "eval i p1 = eval i p2") assume a: "eval i p1 = eval i p2" then have yes: "eval i (Eql' p1 p2) = Det True" by auto from a have "change_tv f (eval i p1) = change_tv f (eval i p2)" by auto then have "eval (change_int f i) p1 = eval (change_int f i) p2" using ih1 ih2 by auto then have "eval (change_int f i) (Eql' p1 p2) = Det True" by auto then show "eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))" using yes ih1 by auto next assume a': "eval i p1 \<noteq> eval i p2" show "eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))" proof (cases "eval i p1 = Det True") assume a: "eval i p1 = Det True" from a a' have yes: "eval i (Eql' p1 p2) = eval i p2" by auto from a have "change_tv f (eval i p1) = Det True" by auto then have b: "eval (change_int f i) p1 = Det True" using ih1 by auto from a' have b': "eval (change_int f i) p1 \<noteq> eval (change_int f i) p2" using assms ih1 ih2 change_tv_injection the_inv_f_f change_tv.simps by metis from b b' have "eval (change_int f i) (Eql' p1 p2) = eval (change_int f i) p2" by auto then show "eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))" using ih2 yes by auto next assume a'': "eval i p1 \<noteq> Det True" show "eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))" proof (cases "eval i p2 = Det True") assume a: "eval i p2 = Det True" from a a' a'' have yes: "eval i (Eql' p1 p2) = eval i p1" using eval_equality[of i p1 p2] by auto from a have "change_tv f (eval i p2) = Det True" by auto then have b: "eval (change_int f i) p2 = Det True" using ih2 by auto from a' have b': "eval (change_int f i) p1 \<noteq> eval (change_int f i) p2" using assms ih1 ih2 change_tv_injection the_inv_f_f change_tv.simps by metis from a'' have b'': "eval (change_int f i) p1 \<noteq> Det True" using b b' by auto from b b' b'' have "eval (change_int f i) (Eql' p1 p2) = eval (change_int f i) p1" using eval_equality[of "change_int f i" p1 p2] by auto then show "eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))" using ih1 yes by auto next assume a''': "eval i p2 \<noteq> Det True" show "eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))" proof (cases "eval i p1 = Det False") assume a: "eval i p1 = Det False" from a a' a'' a''' have yes: "eval i (Eql' p1 p2) = eval i (Neg' p2)" using eval_equality[of i p1 p2] by auto from a have "change_tv f (eval i p1) = Det False" by auto then have b: "eval (change_int f i) p1 = Det False" using ih1 by auto from a' have b': "eval (change_int f i) p1 \<noteq> eval (change_int f i) p2" using assms ih1 ih2 change_tv_injection the_inv_f_f change_tv.simps by metis from a'' have b'': "eval (change_int f i) p1 \<noteq> Det True" using b b' by auto from a''' have b''': "eval (change_int f i) p2 \<noteq> Det True" using b b' b'' by (metis assms change_tv.simps(1) change_tv_injection inj_eq ih2) from b b' b'' b''' have "eval (change_int f i) (Eql' p1 p2) = eval (change_int f i) (Neg' p2)" using eval_equality[of "change_int f i" p1 p2] by auto then show "eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))" using ih2 yes a a' a''' b b' b''' eval_negation by metis next assume a'''': "eval i p1 \<noteq> Det False" show "eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))" proof (cases "eval i p2 = Det False") assume a: "eval i p2 = Det False" from a a' a'' a''' a'''' have yes: "eval i (Eql' p1 p2) = eval i (Neg' p1)" using eval_equality[of i p1 p2] by auto from a have "change_tv f (eval i p2) = Det False" by auto then have b: "eval (change_int f i) p2 = Det False" using ih2 by auto from a' have b': "eval (change_int f i) p1 \<noteq> eval (change_int f i) p2" using assms ih1 ih2 change_tv_injection the_inv_f_f change_tv.simps by metis from a'' have b'': "eval (change_int f i) p1 \<noteq> Det True" using change_tv.elims ih1 tv.simps(4) by auto from a''' have b''': "eval (change_int f i) p2 \<noteq> Det True" using b b' b'' by (metis assms change_tv.simps(1) change_tv_injection inj_eq ih2) from a'''' have b'''': "eval (change_int f i) p1 \<noteq> Det False" using b b' by auto from b b' b'' b''' b'''' have "eval (change_int f i) (Eql' p1 p2) = eval (change_int f i) (Neg' p1)" using eval_equality[of "change_int f i" p1 p2] by auto then show "eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))" using ih1 yes a a' a''' a'''' b b' b''' b'''' eval_negation a'' b'' by metis next assume a''''': "eval i p2 \<noteq> Det False" from a' a'' a''' a'''' a''''' have yes: "eval i (Eql' p1 p2) = Det False" using eval_equality[of i p1 p2] by auto from a''''' have "change_tv f (eval i p2) \<noteq> Det False" using change_tv_injection inj_eq assms change_tv.simps by metis then have b: "eval (change_int f i) p2 \<noteq> Det False" using ih2 by auto from a' have b': "eval (change_int f i) p1 \<noteq> eval (change_int f i) p2" using assms ih1 ih2 change_tv_injection the_inv_f_f change_tv.simps by metis from a'' have b'': "eval (change_int f i) p1 \<noteq> Det True" using change_tv.elims ih1 tv.simps(4) by auto from a''' have b''': "eval (change_int f i) p2 \<noteq> Det True" using b b' b'' by (metis assms change_tv.simps(1) change_tv_injection the_inv_f_f ih2) from a'''' have b'''': "eval (change_int f i) p1 \<noteq> Det False" by (metis a'' change_tv.simps(2) ih1 string_tv.cases tv.distinct(1)) from b b' b'' b''' b'''' have "eval (change_int f i) (Eql' p1 p2) = Det False" using eval_equality[of "change_int f i" p1 p2] by auto then show "eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))" using ih1 yes a' a''' a'''' b b' b''' b'''' a'' b'' by auto qed qed qed qed qed qed (simp_all add: change_int_def) subsection \<open>Only a Finite Number of Truth Values Needed\<close> text \<open> Theorem valid_in_valid is a kind of the reverse of valid_valid_in (or its transfer variant). \<close> abbreviation is_indet :: "tv \<Rightarrow> bool" where "is_indet tv \<equiv> (case tv of Det _ \<Rightarrow> False | Indet _ \<Rightarrow> True)" abbreviation get_indet :: "tv \<Rightarrow> nat" where "get_indet tv \<equiv> (case tv of Det _ \<Rightarrow> undefined | Indet n \<Rightarrow> n)" theorem valid_in_valid: assumes "card U \<ge> card (props p)" and "valid_in U p" shows "valid p" proof - have "finite U \<Longrightarrow> card (props p) \<le> card U \<Longrightarrow> valid_in U p \<Longrightarrow> valid p" for U p proof - assume assms: "finite U" "card (props p) \<le> card U" "valid_in U p" show "valid p" unfolding valid_def proof fix i obtain f where f_p: "(change_int f i) ` (props p) \<subseteq> (domain U) \<and> inj f" proof - have "finite U \<Longrightarrow> card (props p) \<le> card U \<Longrightarrow> \<exists>f. change_int f i ` props p \<subseteq> domain U \<and> inj f" for U p proof - assume assms: "finite U" "card (props p) \<le> card U" show ?thesis proof - let ?X = "(get_indet ` ((i ` props p) \<inter> {tv. is_indet tv}))" have d: "finite (props p)" by (induct p) auto then have cx: "card ?X \<le> card U" using assms surj_card_le Int_lower1 card_image_le finite_Int finite_imageI le_trans by metis have f: "finite ?X" using d by simp obtain f where f_p: "(\<forall>n \<in> ?X. f n \<in> U) \<and> (inj f)" proof - have "finite X \<Longrightarrow> finite Y \<Longrightarrow> card X \<le> card Y \<Longrightarrow> \<exists>f. (\<forall>n \<in> X. f n \<in> Y) \<and> inj f" for X Y :: "nat set" proof - assume assms: "finite X" "finite Y" "card X \<le> card Y" show ?thesis proof - from assms obtain Z where xyz: "Z \<subseteq> Y \<and> card Z = card X" by (metis card_image card_le_inj) then obtain f where "bij_betw f X Z" by (metis assms(1) assms(2) finite_same_card_bij infinite_super) then have f_p: "(\<forall>n \<in> X. f n \<in> Y) \<and> inj_on f X" using bij_betwE bij_betw_imp_inj_on xyz by blast obtain f' where f': "f' = (\<lambda>n. if n \<in> X then f n else n + Suc (Max Y + n))" by simp have "inj f'" unfolding f' inj_on_def using assms(2) f_p le_add2 trans_le_add2 not_less_eq_eq by (simp, metis Max_ge add.commute inj_on_eq_iff) moreover have "(\<forall>n \<in> X. f' n \<in> Y)" unfolding f' using f_p by auto ultimately show ?thesis by metis qed qed then show "(\<And>f. (\<forall>n \<in> get_indet ` (i ` props p \<inter> {tv. is_indet tv}). f n \<in> U) \<and> inj f \<Longrightarrow> thesis) \<Longrightarrow> thesis" using assms cx f unfolding inj_on_def by metis qed have "(change_int f i) ` (props p) \<subseteq> (domain U)" proof fix x assume "x \<in> change_int f i ` props p" then obtain s where s_p: "s \<in> props p \<and> change_int f i s = x" by auto then have "change_int f i s \<in> {Det True, Det False} \<union> Indet ` U" proof (cases "change_int f i s \<in> {Det True, Det False}") case True then show ?thesis by auto next case False then obtain n' where "change_int f i s = Indet n'" by (cases "change_int f i s") simp_all then have p: "change_tv f (i s) = Indet n'" by (simp add: change_int_def) moreover have "n' \<in> U" proof - obtain n'' where "f n'' = n'" using calculation change_tv.elims by blast moreover have "s \<in> props p \<and> i s = (Indet n'')" using p calculation change_tv.simps change_tv_injection the_inv_f_f f_p s_p by metis then have "(Indet n'') \<in> i ` props p" using image_iff by metis then have "(Indet n'') \<in> i ` props p \<and> is_indet (Indet n'') \<and> get_indet (Indet n'') = n''" by auto then have "n'' \<in> ?X" using Int_Collect image_iff by metis ultimately show ?thesis using f_p by auto qed ultimately have "change_tv f (i s) \<in> Indet ` U" by auto then have "change_int f i s \<in> Indet ` U" unfolding change_int_def by auto then show ?thesis by auto qed then show "x \<in> domain U" unfolding domain_def using s_p by simp qed then have "(change_int f i) ` (props p) \<subseteq> (domain U) \<and> (inj f)" unfolding domain_def using f_p by simp then show ?thesis using f_p by metis qed qed then show "(\<And>f. change_int f i ` props p \<subseteq> domain U \<and> inj f \<Longrightarrow> thesis) \<Longrightarrow> thesis" using assms by metis qed obtain i2 where i2: "i2 = (\<lambda>s. if s \<in> props p then (change_int f i) s else Det True)" by simp then have i2_p: "\<forall>s \<in> props p. i2 s = (change_int f i) s" "\<forall>s \<in> - props p. i2 s = Det True" by auto then have "range i2 \<subseteq> (domain U)" using i2 f_p unfolding domain_def by auto then have "eval i2 p = Det True" using assms unfolding valid_in_def by auto then have "eval (change_int f i) p = Det True" using relevant_props[of p i2 "change_int f i"] i2_p by auto then have "change_tv f (eval i p) = Det True" using eval_change f_p by auto then show "eval i p = Det True" by (cases "eval i p") simp_all qed qed then show ?thesis using assms subsetI sup_bot.comm_neutral image_is_empty subsetCE UnCI valid_in_def Un_insert_left card.empty card.infinite finite.intros(1) unfolding domain_def by metis qed theorem reduce: "valid p \<longleftrightarrow> valid_in {1..card (props p)} p" using valid_in_valid transfer by force section \<open>Case Study\<close> subsection \<open>Abbreviations\<close> text \<open> Entailment takes a list of assumptions. \<close> abbreviation (input) Entail :: "fm list \<Rightarrow> fm \<Rightarrow> fm" where "Entail l p \<equiv> Imp (if l = [] then Truth else fold Con' (butlast l) (last l)) p" theorem entailment_not_chain: "\<not> valid (Eql (Entail [Pro ''p'', Pro ''q''] (Pro ''r'')) (Box ((Imp' (Pro ''p'') (Imp' (Pro ''q'') (Pro ''r''))))))" proof - let ?i = "(\<lambda>s. Indet 1)(''r'' := Det False)" have "eval ?i (Eql (Entail [Pro ''p'', Pro ''q''] (Pro ''r'')) (Box ((Imp' (Pro ''p'') (Imp' (Pro ''q'') (Pro ''r'')))))) = Det False" by simp moreover have "Det False \<noteq> Det True" by simp ultimately show ?thesis unfolding valid_def by metis qed abbreviation (input) B0 :: fm where "B0 \<equiv> Con' (Con' (Pro ''p'') (Pro ''q'')) (Neg' (Pro ''r''))" abbreviation (input) B1 :: fm where "B1 \<equiv> Imp' (Con' (Pro ''p'') (Pro ''q'')) (Pro ''r'')" abbreviation (input) B2 :: fm where "B2 \<equiv> Imp' (Pro ''r'') (Pro ''s'')" abbreviation (input) B3 :: fm where "B3 \<equiv> Imp' (Neg' (Pro ''s'')) (Neg' (Pro ''r''))" subsection \<open>Results\<close> text \<open> The paraconsistent logic is usable in contrast to classical logic. \<close> theorem classical_logic_is_not_usable: "valid_boole (Entail [B0, B1] p)" unfolding valid_in_def proof (rule; rule) fix i :: "id \<Rightarrow> tv" assume "range i \<subseteq> domain {}" then have "i ''p'' \<in> {Det True, Det False}" "i ''q'' \<in> {Det True, Det False}" "i ''r'' \<in> {Det True, Det False}" unfolding domain_def by auto then show "eval i (Entail [B0, B1] p) = Det True" by (cases "i ''p''"; cases "i ''q''"; cases "i ''r''") simp_all qed corollary "valid_boole (Entail [B0, B1] (Pro ''r''))" by (rule classical_logic_is_not_usable) corollary "valid_boole (Entail [B0, B1] (Neg' (Pro ''r'')))" by (rule classical_logic_is_not_usable) proposition "\<not> valid (Entail [B0, B1] (Pro ''r''))" proof - let ?i = "(\<lambda>s. Indet 1)(''r'' := Det False)" have "eval ?i (Entail [B0, B1] (Pro ''r'')) = Det False" by simp moreover have "Det False \<noteq> Det True" by simp ultimately show ?thesis unfolding valid_def by metis qed proposition "valid_boole (Entail [B0, Box B1] p)" unfolding valid_in_def proof (rule; rule) fix i :: "id \<Rightarrow> tv" assume "range i \<subseteq> domain {}" then have "i ''p'' \<in> {Det True, Det False}" "i ''q'' \<in> {Det True, Det False}" "i ''r'' \<in> {Det True, Det False}" unfolding domain_def by auto then show "eval i (Entail [B0, Box B1] p) = Det True" by (cases "i ''p''"; cases "i ''q''"; cases "i ''r''") simp_all qed proposition "\<not> valid (Entail [B0, Box B1, Box B2] (Neg' (Pro ''p'')))" proof - let ?i = "(\<lambda>s. Indet 1)(''p'' := Det True)" have "eval ?i (Entail [B0, Box B1, Box B2] (Neg' (Pro ''p''))) = Det False" by simp moreover have "Det False \<noteq> Det True" by simp ultimately show ?thesis unfolding valid_def by metis qed proposition "\<not> valid (Entail [B0, Box B1, Box B2] (Neg' (Pro ''q'')))" proof - let ?i = "(\<lambda>s. Indet 1)(''q'' := Det True)" have "eval ?i (Entail [B0, Box B1, Box B2] (Neg' (Pro ''q''))) = Det False" by simp moreover have "Det False \<noteq> Det True" by simp ultimately show ?thesis unfolding valid_def by metis qed proposition "\<not> valid (Entail [B0, Box B1, Box B2] (Neg' (Pro ''s'')))" proof - let ?i = "(\<lambda>s. Indet 1)(''s'' := Det True)" have "eval ?i (Entail [B0, Box B1, Box B2] (Neg' (Pro ''s''))) = Det False" by simp moreover have "Det False \<noteq> Det True" by simp ultimately show ?thesis unfolding valid_def by metis qed proposition "valid (Entail [B0, Box B1, Box B2] (Pro ''r''))" proof - have "{1..card (props (Entail [B0, Box B1, Box B2] (Pro ''r'')))} = {1, 2, 3, 4}" by code_simp moreover have "valid_in {1, 2, 3, 4} (Entail [B0, Box B1, Box B2] (Pro ''r''))" unfolding valid_in_def proof (rule; rule) fix i :: "id \<Rightarrow> tv" assume "range i \<subseteq> domain {1, 2, 3, 4}" then have icase: "i ''p'' \<in> {Det True, Det False, Indet 1, Indet 2, Indet 3, Indet 4}" "i ''q'' \<in> {Det True, Det False, Indet 1, Indet 2, Indet 3, Indet 4}" "i ''r'' \<in> {Det True, Det False, Indet 1, Indet 2, Indet 3, Indet 4}" "i ''s'' \<in> {Det True, Det False, Indet 1, Indet 2, Indet 3, Indet 4}" unfolding domain_def by auto show "eval i (Entail [B0, Box B1, Box B2] (Pro ''r'')) = Det True" using icase by (cases "i ''p''"; cases "i ''q''"; cases "i ''r''"; cases "i ''s''") simp_all qed ultimately show ?thesis using reduce by simp qed proposition "valid (Entail [B0, Box B1, Box B2] (Neg' (Pro ''r'')))" proof - have "{1..card (props (Entail [B0, Box B1, Box B2] (Neg' (Pro ''r''))))} = {1, 2, 3, 4}" by code_simp moreover have "valid_in {1, 2, 3, 4} (Entail [B0, Box B1, Box B2] (Neg' (Pro ''r'')))" unfolding valid_in_def proof (rule; rule) fix i :: "id \<Rightarrow> tv" assume "range i \<subseteq> domain {1, 2, 3, 4}" then have icase: "i ''p'' \<in> {Det True, Det False, Indet 1, Indet 2, Indet 3, Indet 4}" "i ''q'' \<in> {Det True, Det False, Indet 1, Indet 2, Indet 3, Indet 4}" "i ''r'' \<in> {Det True, Det False, Indet 1, Indet 2, Indet 3, Indet 4}" "i ''s'' \<in> {Det True, Det False, Indet 1, Indet 2, Indet 3, Indet 4}" unfolding domain_def by auto show "eval i (Entail [B0, Box B1, Box B2] (Neg' (Pro ''r''))) = Det True" using icase by (cases "i ''p''"; cases "i ''q''"; cases "i ''r''"; cases "i ''s''") simp_all qed ultimately show ?thesis using reduce by simp qed proposition "valid (Entail [B0, Box B1, Box B2] (Pro ''s''))" proof - have "{1..card (props (Entail [B0, Box B1, Box B2] (Pro ''s'')))} = {1, 2, 3, 4}" by code_simp moreover have "valid_in {1, 2, 3, 4} (Entail [B0, Box B1, Box B2] (Pro ''s''))" unfolding valid_in_def proof (rule; rule) fix i :: "id \<Rightarrow> tv" assume "range i \<subseteq> domain {1, 2, 3, 4}" then have icase: "i ''p'' \<in> {Det True, Det False, Indet 1, Indet 2, Indet 3, Indet 4}" "i ''q'' \<in> {Det True, Det False, Indet 1, Indet 2, Indet 3, Indet 4}" "i ''r'' \<in> {Det True, Det False, Indet 1, Indet 2, Indet 3, Indet 4}" "i ''s'' \<in> {Det True, Det False, Indet 1, Indet 2, Indet 3, Indet 4}" unfolding domain_def by auto show "eval i (Entail [B0, Box B1, Box B2] (Pro ''s'')) = Det True" using icase by (cases "i ''p''"; cases "i ''q''"; cases "i ''r''"; cases "i ''s''") simp_all qed ultimately show ?thesis using reduce by simp qed section \<open>Acknowledgements\<close> text \<open> Thanks to the Isabelle developers for making a superb system and for always being willing to help. \<close> end \<comment> \<open>Paraconsistency file\<close>
(** This file proves the basic laws of the HeapLang program logic by applying the Iris lifting lemmas. *) From iris.proofmode Require Import tactics. From iris.bi.lib Require Import fractional. From iris.base_logic.lib Require Export gen_heap proph_map gen_inv_heap. From iris.program_logic Require Export weakestpre total_weakestpre. From iris.program_logic Require Import ectx_lifting total_ectx_lifting. From iris.heap_lang Require Export class_instances. From iris.heap_lang Require Import tactics notation. From iris.prelude Require Import options. Class heapG Σ := HeapG { heapG_invG : invG Σ; heapG_gen_heapG :> gen_heapG loc (option val) Σ; heapG_inv_heapG :> inv_heapG loc (option val) Σ; heapG_proph_mapG :> proph_mapG proph_id (val * val) Σ; }. Global Instance heapG_irisG `{!heapG Σ} : irisG heap_lang Σ := { iris_invG := heapG_invG; state_interp σ κs _ := (gen_heap_interp σ.(heap) ∗ proph_map_interp κs σ.(used_proph_id))%I; fork_post _ := True%I; }. (** Since we use an [option val] instance of [gen_heap], we need to overwrite the notations. That also helps for scopes and coercions. *) (** FIXME: Refactor these notations using custom entries once Coq bug #13654 has been fixed. *) Notation "l ↦{ dq } v" := (mapsto (L:=loc) (V:=option val) l dq (Some v%V)) (at level 20, format "l ↦{ dq } v") : bi_scope. Notation "l ↦□ v" := (mapsto (L:=loc) (V:=option val) l DfracDiscarded (Some v%V)) (at level 20, format "l ↦□ v") : bi_scope. Notation "l ↦{# q } v" := (mapsto (L:=loc) (V:=option val) l (DfracOwn q) (Some v%V)) (at level 20, format "l ↦{# q } v") : bi_scope. Notation "l ↦ v" := (mapsto (L:=loc) (V:=option val) l (DfracOwn 1) (Some v%V)) (at level 20, format "l ↦ v") : bi_scope. (** Same for [gen_inv_heap], except that these are higher-order notations so to make setoid rewriting in the predicate [I] work we need actual definitions here. *) Section definitions. Context `{!heapG Σ}. Definition inv_mapsto_own (l : loc) (v : val) (I : val → Prop) : iProp Σ := inv_mapsto_own l (Some v) (from_option I False). Definition inv_mapsto (l : loc) (I : val → Prop) : iProp Σ := inv_mapsto l (from_option I False). End definitions. Global Instance: Params (@inv_mapsto_own) 4 := {}. Global Instance: Params (@inv_mapsto) 3 := {}. Notation inv_heap_inv := (inv_heap_inv loc (option val)). Notation "l '↦_' I □" := (inv_mapsto l I%stdpp%type) (at level 20, I at level 9, format "l '↦_' I '□'") : bi_scope. Notation "l ↦_ I v" := (inv_mapsto_own l v I%stdpp%type) (at level 20, I at level 9, format "l ↦_ I v") : bi_scope. Section lifting. Context `{!heapG Σ}. Implicit Types P Q : iProp Σ. Implicit Types Φ Ψ : val → iProp Σ. Implicit Types efs : list expr. Implicit Types σ : state. Implicit Types v : val. Implicit Types l : loc. (** Recursive functions: we do not use this lemmas as it is easier to use Löb induction directly, but this demonstrates that we can state the expected reasoning principle for recursive functions, without any visible ▷. *) Lemma wp_rec_löb s E f x e Φ Ψ : □ ( □ (∀ v, Ψ v -∗ WP (rec: f x := e)%V v @ s; E {{ Φ }}) -∗ ∀ v, Ψ v -∗ WP (subst' x v (subst' f (rec: f x := e) e)) @ s; E {{ Φ }}) -∗ ∀ v, Ψ v -∗ WP (rec: f x := e)%V v @ s; E {{ Φ }}. Proof. iIntros "#Hrec". iLöb as "IH". iIntros (v) "HΨ". iApply lifting.wp_pure_step_later; first done. iNext. iApply ("Hrec" with "[] HΨ"). iIntros "!>" (w) "HΨ". iApply ("IH" with "HΨ"). Qed. (** Fork: Not using Texan triples to avoid some unnecessary [True] *) Lemma wp_fork s E e Φ : ▷ WP e @ s; ⊤ {{ _, True }} -∗ ▷ Φ (LitV LitUnit) -∗ WP Fork e @ s; E {{ Φ }}. Proof. iIntros "He HΦ". iApply wp_lift_atomic_head_step; [done|]. iIntros (σ1 κ κs n) "Hσ !>"; iSplit; first by eauto with head_step. iIntros "!>" (v2 σ2 efs Hstep); inv_head_step. by iFrame. Qed. Lemma twp_fork s E e Φ : WP e @ s; ⊤ [{ _, True }] -∗ Φ (LitV LitUnit) -∗ WP Fork e @ s; E [{ Φ }]. Proof. iIntros "He HΦ". iApply twp_lift_atomic_head_step; [done|]. iIntros (σ1 κs n) "Hσ !>"; iSplit; first by eauto with head_step. iIntros (κ v2 σ2 efs Hstep); inv_head_step. by iFrame. Qed. (** Heap *) (** We need to adjust the [gen_heap] and [gen_inv_heap] lemmas because of our value type being [option val]. *) Lemma mapsto_valid l dq v : l ↦{dq} v -∗ ⌜✓ dq⌝. Proof. apply mapsto_valid. Qed. Lemma mapsto_valid_2 l dq1 dq2 v1 v2 : l ↦{dq1} v1 -∗ l ↦{dq2} v2 -∗ ⌜✓ (dq1 ⋅ dq2) ∧ v1 = v2⌝. Proof. iIntros "H1 H2". iDestruct (mapsto_valid_2 with "H1 H2") as %[? [=?]]. done. Qed. Lemma mapsto_agree l dq1 dq2 v1 v2 : l ↦{dq1} v1 -∗ l ↦{dq2} v2 -∗ ⌜v1 = v2⌝. Proof. iIntros "H1 H2". iDestruct (mapsto_agree with "H1 H2") as %[=?]. done. Qed. Lemma mapsto_combine l dq1 dq2 v1 v2 : l ↦{dq1} v1 -∗ l ↦{dq2} v2 -∗ l ↦{dq1 ⋅ dq2} v1 ∗ ⌜v1 = v2⌝. Proof. iIntros "Hl1 Hl2". iDestruct (mapsto_combine with "Hl1 Hl2") as "[$ Heq]". by iDestruct "Heq" as %[= ->]. Qed. Lemma mapsto_frac_ne l1 l2 dq1 dq2 v1 v2 : ¬ ✓(dq1 ⋅ dq2) → l1 ↦{dq1} v1 -∗ l2 ↦{dq2} v2 -∗ ⌜l1 ≠ l2⌝. Proof. apply mapsto_frac_ne. Qed. Lemma mapsto_ne l1 l2 dq2 v1 v2 : l1 ↦ v1 -∗ l2 ↦{dq2} v2 -∗ ⌜l1 ≠ l2⌝. Proof. apply mapsto_ne. Qed. Lemma mapsto_persist l dq v : l ↦{dq} v ==∗ l ↦□ v. Proof. apply mapsto_persist. Qed. Global Instance inv_mapsto_own_proper l v : Proper (pointwise_relation _ iff ==> (≡)) (inv_mapsto_own l v). Proof. intros I1 I2 HI. rewrite /inv_mapsto_own. f_equiv=>-[w|]; last done. simpl. apply HI. Qed. Global Instance inv_mapsto_proper l : Proper (pointwise_relation _ iff ==> (≡)) (inv_mapsto l). Proof. intros I1 I2 HI. rewrite /inv_mapsto. f_equiv=>-[w|]; last done. simpl. apply HI. Qed. Lemma make_inv_mapsto l v (I : val → Prop) E : ↑inv_heapN ⊆ E → I v → inv_heap_inv -∗ l ↦ v ={E}=∗ l ↦_I v. Proof. iIntros (??) "#HI Hl". iApply make_inv_mapsto; done. Qed. Lemma inv_mapsto_own_inv l v I : l ↦_I v -∗ l ↦_I □. Proof. apply inv_mapsto_own_inv. Qed. Lemma inv_mapsto_own_acc_strong E : ↑inv_heapN ⊆ E → inv_heap_inv ={E, E ∖ ↑inv_heapN}=∗ ∀ l v I, l ↦_I v -∗ (⌜I v⌝ ∗ l ↦ v ∗ (∀ w, ⌜I w ⌝ -∗ l ↦ w ==∗ inv_mapsto_own l w I ∗ |={E ∖ ↑inv_heapN, E}=> True)). Proof. iIntros (?) "#Hinv". iMod (inv_mapsto_own_acc_strong with "Hinv") as "Hacc"; first done. iIntros "!>" (l v I) "Hl". iDestruct ("Hacc" with "Hl") as "(% & Hl & Hclose)". iFrame "%∗". iIntros (w) "% Hl". iApply "Hclose"; done. Qed. Lemma inv_mapsto_own_acc E l v I: ↑inv_heapN ⊆ E → inv_heap_inv -∗ l ↦_I v ={E, E ∖ ↑inv_heapN}=∗ (⌜I v⌝ ∗ l ↦ v ∗ (∀ w, ⌜I w ⌝ -∗ l ↦ w ={E ∖ ↑inv_heapN, E}=∗ l ↦_I w)). Proof. iIntros (?) "#Hinv Hl". iMod (inv_mapsto_own_acc with "Hinv Hl") as "(% & Hl & Hclose)"; first done. iFrame "%∗". iIntros "!>" (w) "% Hl". iApply "Hclose"; done. Qed. Lemma inv_mapsto_acc l I E : ↑inv_heapN ⊆ E → inv_heap_inv -∗ l ↦_I □ ={E, E ∖ ↑inv_heapN}=∗ ∃ v, ⌜I v⌝ ∗ l ↦ v ∗ (l ↦ v ={E ∖ ↑inv_heapN, E}=∗ ⌜True⌝). Proof. iIntros (?) "#Hinv Hl". iMod (inv_mapsto_acc with "Hinv Hl") as ([v|]) "(% & Hl & Hclose)"; [done| |done]. iIntros "!>". iExists (v). iFrame "%∗". Qed. (** The usable rules for [allocN] stated in terms of the [array] proposition are derived in te file [array]. *) Lemma heap_array_to_seq_meta l vs (n : nat) : length vs = n → ([∗ map] l' ↦ _ ∈ heap_array l vs, meta_token l' ⊤) -∗ [∗ list] i ∈ seq 0 n, meta_token (l +ₗ (i : nat)) ⊤. Proof. iIntros (<-) "Hvs". iInduction vs as [|v vs] "IH" forall (l)=> //=. rewrite big_opM_union; last first. { apply map_disjoint_spec=> l' v1 v2 /lookup_singleton_Some [-> _]. intros (j&w&?&Hjl&?&?)%heap_array_lookup. rewrite loc_add_assoc -{1}[l']loc_add_0 in Hjl. simplify_eq; lia. } rewrite loc_add_0 -fmap_S_seq big_sepL_fmap. setoid_rewrite Nat2Z.inj_succ. setoid_rewrite <-Z.add_1_l. setoid_rewrite <-loc_add_assoc. rewrite big_opM_singleton; iDestruct "Hvs" as "[$ Hvs]". by iApply "IH". Qed. Lemma heap_array_to_seq_mapsto l v (n : nat) : ([∗ map] l' ↦ ov ∈ heap_array l (replicate n v), gen_heap.mapsto l' (DfracOwn 1) ov) -∗ [∗ list] i ∈ seq 0 n, (l +ₗ (i : nat)) ↦ v. Proof. iIntros "Hvs". iInduction n as [|n] "IH" forall (l); simpl. { done. } rewrite big_opM_union; last first. { apply map_disjoint_spec=> l' v1 v2 /lookup_singleton_Some [-> _]. intros (j&w&?&Hjl&_)%heap_array_lookup. rewrite loc_add_assoc -{1}[l']loc_add_0 in Hjl. simplify_eq; lia. } rewrite loc_add_0 -fmap_S_seq big_sepL_fmap. setoid_rewrite Nat2Z.inj_succ. setoid_rewrite <-Z.add_1_l. setoid_rewrite <-loc_add_assoc. rewrite big_opM_singleton; iDestruct "Hvs" as "[$ Hvs]". by iApply "IH". Qed. Lemma twp_allocN_seq s E v n : (0 < n)%Z → [[{ True }]] AllocN (Val $ LitV $ LitInt $ n) (Val v) @ s; E [[{ l, RET LitV (LitLoc l); [∗ list] i ∈ seq 0 (Z.to_nat n), (l +ₗ (i : nat)) ↦ v ∗ meta_token (l +ₗ (i : nat)) ⊤ }]]. Proof. iIntros (Hn Φ) "_ HΦ". iApply twp_lift_atomic_head_step_no_fork; first done. iIntros (σ1 κs k) "[Hσ Hκs] !>"; iSplit; first by destruct n; auto with lia head_step. iIntros (κ v2 σ2 efs Hstep); inv_head_step. iMod (gen_heap_alloc_big _ (heap_array _ (replicate (Z.to_nat n) v)) with "Hσ") as "(Hσ & Hl & Hm)". { apply heap_array_map_disjoint. rewrite replicate_length Z2Nat.id; auto with lia. } iModIntro; do 2 (iSplit; first done). iFrame "Hσ Hκs". iApply "HΦ". iApply big_sepL_sep. iSplitL "Hl". - by iApply heap_array_to_seq_mapsto. - iApply (heap_array_to_seq_meta with "Hm"). by rewrite replicate_length. Qed. Lemma wp_allocN_seq s E v n : (0 < n)%Z → {{{ True }}} AllocN (Val $ LitV $ LitInt $ n) (Val v) @ s; E {{{ l, RET LitV (LitLoc l); [∗ list] i ∈ seq 0 (Z.to_nat n), (l +ₗ (i : nat)) ↦ v ∗ meta_token (l +ₗ (i : nat)) ⊤ }}}. Proof. iIntros (Hn Φ) "_ HΦ". iApply (twp_wp_step with "HΦ"). iApply twp_allocN_seq; [by auto..|]; iIntros (l) "H HΦ". by iApply "HΦ". Qed. Lemma twp_alloc s E v : [[{ True }]] Alloc (Val v) @ s; E [[{ l, RET LitV (LitLoc l); l ↦ v ∗ meta_token l ⊤ }]]. Proof. iIntros (Φ) "_ HΦ". iApply twp_allocN_seq; [auto with lia..|]. iIntros (l) "/= (? & _)". rewrite loc_add_0. iApply "HΦ"; iFrame. Qed. Lemma wp_alloc s E v : {{{ True }}} Alloc (Val v) @ s; E {{{ l, RET LitV (LitLoc l); l ↦ v ∗ meta_token l ⊤ }}}. Proof. iIntros (Φ) "_ HΦ". iApply (twp_wp_step with "HΦ"). iApply twp_alloc; [by auto..|]; iIntros (l) "H HΦ". by iApply "HΦ". Qed. Lemma twp_free s E l v : [[{ l ↦ v }]] Free (Val $ LitV $ LitLoc l) @ s; E [[{ RET LitV LitUnit; True }]]. Proof. iIntros (Φ) "Hl HΦ". iApply twp_lift_atomic_head_step_no_fork; first done. iIntros (σ1 κs n) "[Hσ Hκs] !>". iDestruct (gen_heap_valid with "Hσ Hl") as %?. iSplit; first by eauto with head_step. iIntros (κ v2 σ2 efs Hstep); inv_head_step. iMod (gen_heap_update with "Hσ Hl") as "[$ Hl]". iModIntro. iSplit; first done. iSplit; first done. iFrame. by iApply "HΦ". Qed. Lemma wp_free s E l v : {{{ ▷ l ↦ v }}} Free (Val $ LitV (LitLoc l)) @ s; E {{{ RET LitV LitUnit; True }}}. Proof. iIntros (Φ) ">H HΦ". iApply (twp_wp_step with "HΦ"). iApply (twp_free with "H"); [by auto..|]; iIntros "H HΦ". by iApply "HΦ". Qed. Lemma twp_load s E l dq v : [[{ l ↦{dq} v }]] Load (Val $ LitV $ LitLoc l) @ s; E [[{ RET v; l ↦{dq} v }]]. Proof. iIntros (Φ) "Hl HΦ". iApply twp_lift_atomic_head_step_no_fork; first done. iIntros (σ1 κs n) "[Hσ Hκs] !>". iDestruct (gen_heap_valid with "Hσ Hl") as %?. iSplit; first by eauto with head_step. iIntros (κ v2 σ2 efs Hstep); inv_head_step. iModIntro; iSplit=> //. iSplit; first done. iFrame. by iApply "HΦ". Qed. Lemma wp_load s E l dq v : {{{ ▷ l ↦{dq} v }}} Load (Val $ LitV $ LitLoc l) @ s; E {{{ RET v; l ↦{dq} v }}}. Proof. iIntros (Φ) ">H HΦ". iApply (twp_wp_step with "HΦ"). iApply (twp_load with "H"). iIntros "H HΦ". by iApply "HΦ". Qed. Lemma twp_store s E l v' v : [[{ l ↦ v' }]] Store (Val $ LitV $ LitLoc l) (Val v) @ s; E [[{ RET LitV LitUnit; l ↦ v }]]. Proof. iIntros (Φ) "Hl HΦ". iApply twp_lift_atomic_head_step_no_fork; first done. iIntros (σ1 κs n) "[Hσ Hκs] !>". iDestruct (gen_heap_valid with "Hσ Hl") as %?. iSplit; first by eauto with head_step. iIntros (κ v2 σ2 efs Hstep); inv_head_step. iMod (gen_heap_update with "Hσ Hl") as "[$ Hl]". iModIntro. iSplit; first done. iSplit; first done. iFrame. by iApply "HΦ". Qed. Lemma wp_store s E l v' v : {{{ ▷ l ↦ v' }}} Store (Val $ LitV (LitLoc l)) (Val v) @ s; E {{{ RET LitV LitUnit; l ↦ v }}}. Proof. iIntros (Φ) ">H HΦ". iApply (twp_wp_step with "HΦ"). iApply (twp_store with "H"); [by auto..|]; iIntros "H HΦ". by iApply "HΦ". Qed. Lemma twp_cmpxchg_fail s E l dq v' v1 v2 : v' ≠ v1 → vals_compare_safe v' v1 → [[{ l ↦{dq} v' }]] CmpXchg (Val $ LitV $ LitLoc l) (Val v1) (Val v2) @ s; E [[{ RET PairV v' (LitV $ LitBool false); l ↦{dq} v' }]]. Proof. iIntros (?? Φ) "Hl HΦ". iApply twp_lift_atomic_head_step_no_fork; first done. iIntros (σ1 κs n) "[Hσ Hκs] !>". iDestruct (gen_heap_valid with "Hσ Hl") as %?. iSplit; first by eauto with head_step. iIntros (κ v2' σ2 efs Hstep); inv_head_step. rewrite bool_decide_false //. iModIntro; iSplit; first done. iSplit; first done. iFrame. by iApply "HΦ". Qed. Lemma wp_cmpxchg_fail s E l dq v' v1 v2 : v' ≠ v1 → vals_compare_safe v' v1 → {{{ ▷ l ↦{dq} v' }}} CmpXchg (Val $ LitV $ LitLoc l) (Val v1) (Val v2) @ s; E {{{ RET PairV v' (LitV $ LitBool false); l ↦{dq} v' }}}. Proof. iIntros (?? Φ) ">H HΦ". iApply (twp_wp_step with "HΦ"). iApply (twp_cmpxchg_fail with "H"); [by auto..|]; iIntros "H HΦ". by iApply "HΦ". Qed. Lemma twp_cmpxchg_suc s E l v1 v2 v' : v' = v1 → vals_compare_safe v' v1 → [[{ l ↦ v' }]] CmpXchg (Val $ LitV $ LitLoc l) (Val v1) (Val v2) @ s; E [[{ RET PairV v' (LitV $ LitBool true); l ↦ v2 }]]. Proof. iIntros (?? Φ) "Hl HΦ". iApply twp_lift_atomic_head_step_no_fork; first done. iIntros (σ1 κs n) "[Hσ Hκs] !>". iDestruct (gen_heap_valid with "Hσ Hl") as %?. iSplit; first by eauto with head_step. iIntros (κ v2' σ2 efs Hstep); inv_head_step. rewrite bool_decide_true //. iMod (gen_heap_update with "Hσ Hl") as "[$ Hl]". iModIntro. iSplit; first done. iSplit; first done. iFrame. by iApply "HΦ". Qed. Lemma wp_cmpxchg_suc s E l v1 v2 v' : v' = v1 → vals_compare_safe v' v1 → {{{ ▷ l ↦ v' }}} CmpXchg (Val $ LitV $ LitLoc l) (Val v1) (Val v2) @ s; E {{{ RET PairV v' (LitV $ LitBool true); l ↦ v2 }}}. Proof. iIntros (?? Φ) ">H HΦ". iApply (twp_wp_step with "HΦ"). iApply (twp_cmpxchg_suc with "H"); [by auto..|]; iIntros "H HΦ". by iApply "HΦ". Qed. Lemma twp_faa s E l i1 i2 : [[{ l ↦ LitV (LitInt i1) }]] FAA (Val $ LitV $ LitLoc l) (Val $ LitV $ LitInt i2) @ s; E [[{ RET LitV (LitInt i1); l ↦ LitV (LitInt (i1 + i2)) }]]. Proof. iIntros (Φ) "Hl HΦ". iApply twp_lift_atomic_head_step_no_fork; first done. iIntros (σ1 κs n) "[Hσ Hκs] !>". iDestruct (gen_heap_valid with "Hσ Hl") as %?. iSplit; first by eauto with head_step. iIntros (κ e2 σ2 efs Hstep); inv_head_step. iMod (gen_heap_update with "Hσ Hl") as "[$ Hl]". iModIntro. do 2 (iSplit; first done). iFrame. by iApply "HΦ". Qed. Lemma wp_faa s E l i1 i2 : {{{ ▷ l ↦ LitV (LitInt i1) }}} FAA (Val $ LitV $ LitLoc l) (Val $ LitV $ LitInt i2) @ s; E {{{ RET LitV (LitInt i1); l ↦ LitV (LitInt (i1 + i2)) }}}. Proof. iIntros (Φ) ">H HΦ". iApply (twp_wp_step with "HΦ"). iApply (twp_faa with "H"); [by auto..|]; iIntros "H HΦ". by iApply "HΦ". Qed. Lemma wp_new_proph s E : {{{ True }}} NewProph @ s; E {{{ pvs p, RET (LitV (LitProphecy p)); proph p pvs }}}. Proof. iIntros (Φ) "_ HΦ". iApply wp_lift_atomic_head_step_no_fork; first done. iIntros (σ1 κ κs n) "[Hσ HR] !>". iSplit; first by eauto with head_step. iIntros "!>" (v2 σ2 efs Hstep). inv_head_step. rename select proph_id into p. iMod (proph_map_new_proph p with "HR") as "[HR Hp]"; first done. iModIntro; iSplit; first done. iFrame. by iApply "HΦ". Qed. (* In the following, strong atomicity is required due to the fact that [e] must be able to make a head step for [Resolve e _ _] not to be (head) stuck. *) Lemma resolve_reducible e σ (p : proph_id) v : Atomic StronglyAtomic e → reducible e σ → reducible (Resolve e (Val (LitV (LitProphecy p))) (Val v)) σ. Proof. intros A (κ & e' & σ' & efs & H). exists (κ ++ [(p, (default v (to_val e'), v))]), e', σ', efs. eapply (Ectx_step []); try done. assert (∃w, Val w = e') as [w <-]. { unfold Atomic in A. apply (A σ e' κ σ' efs) in H. unfold is_Some in H. destruct H as [w H]. exists w. simpl in H. by apply (of_to_val _ _ H). } simpl. constructor. by apply prim_step_to_val_is_head_step. Qed. Lemma step_resolve e vp vt σ1 κ e2 σ2 efs : Atomic StronglyAtomic e → prim_step (Resolve e (Val vp) (Val vt)) σ1 κ e2 σ2 efs → head_step (Resolve e (Val vp) (Val vt)) σ1 κ e2 σ2 efs. Proof. intros A [Ks e1' e2' Hfill -> step]. simpl in *. induction Ks as [|K Ks _] using rev_ind. + simpl in *. subst. inv_head_step. by constructor. + rewrite fill_app /= in Hfill. destruct K; inversion Hfill; subst; clear Hfill. - rename select ectx_item into Ki. assert (fill_item Ki (fill Ks e1') = fill (Ks ++ [Ki]) e1') as Eq1; first by rewrite fill_app. assert (fill_item Ki (fill Ks e2') = fill (Ks ++ [Ki]) e2') as Eq2; first by rewrite fill_app. rewrite fill_app /=. rewrite Eq1 in A. assert (is_Some (to_val (fill (Ks ++ [Ki]) e2'))) as H. { apply (A σ1 _ κ σ2 efs). eapply (Ectx_step (Ks ++ [Ki])); done. } destruct H as [v H]. apply to_val_fill_some in H. by destruct H, Ks. - rename select (of_val vp = _) into Hvp. assert (to_val (fill Ks e1') = Some vp) as Hfillvp by rewrite -Hvp //. apply to_val_fill_some in Hfillvp as [-> ->]. inv_head_step. - rename select (of_val vt = _) into Hvt. assert (to_val (fill Ks e1') = Some vt) as Hfillvt by rewrite -Hvt //. apply to_val_fill_some in Hfillvt as [-> ->]. inv_head_step. Qed. Lemma wp_resolve s E e Φ (p : proph_id) v (pvs : list (val * val)) : Atomic StronglyAtomic e → to_val e = None → proph p pvs -∗ WP e @ s; E {{ r, ∀ pvs', ⌜pvs = (r, v)::pvs'⌝ -∗ proph p pvs' -∗ Φ r }} -∗ WP Resolve e (Val $ LitV $ LitProphecy p) (Val v) @ s; E {{ Φ }}. Proof. (* TODO we should try to use a generic lifting lemma (and avoid [wp_unfold]) here, since this breaks the WP abstraction. *) iIntros (A He) "Hp WPe". rewrite !wp_unfold /wp_pre /= He. simpl in *. iIntros (σ1 κ κs n) "[Hσ Hκ]". destruct κ as [|[p' [w' v']] κ' _] using rev_ind. - iMod ("WPe" $! σ1 [] κs n with "[$Hσ $Hκ]") as "[Hs WPe]". iModIntro. iSplit. { iDestruct "Hs" as "%". iPureIntro. destruct s; [ by apply resolve_reducible | done]. } iIntros (e2 σ2 efs step). exfalso. apply step_resolve in step; last done. inv_head_step. match goal with H: ?κs ++ [_] = [] |- _ => by destruct κs end. - rewrite -assoc. iMod ("WPe" $! σ1 _ _ n with "[$Hσ $Hκ]") as "[Hs WPe]". iModIntro. iSplit. { iDestruct "Hs" as %?. iPureIntro. destruct s; [ by apply resolve_reducible | done]. } iIntros (e2 σ2 efs step). apply step_resolve in step; last done. inv_head_step; simplify_list_eq. iMod ("WPe" $! (Val w') σ2 efs with "[%]") as "WPe". { by eexists [] _ _. } iModIntro. iNext. iMod "WPe" as "[[$ Hκ] WPe]". iMod (proph_map_resolve_proph p' (w',v') κs with "[$Hκ $Hp]") as (vs' ->) "[$ HPost]". iModIntro. rewrite !wp_unfold /wp_pre /=. iDestruct "WPe" as "[HΦ $]". iMod "HΦ". iModIntro. by iApply "HΦ". Qed. End lifting.
[GOAL] n : ℕ ⊢ 0 < 4 [PROOFSTEP] norm_num [GOAL] a b : ℕ h : a ≤ b ⊢ 4 > 0 [PROOFSTEP] norm_num [GOAL] n : ℕ ⊢ 0 < 4 ^ n [PROOFSTEP] positivity [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε✝ ε : ℝ n : ℕ h : ↑100 ≤ 4 ^ n * ε ^ 5 ⊢ Odd 5 [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε✝ ε : ℝ n : ℕ h : ↑100 ≤ 4 ^ n * ε ^ 5 ⊢ 0 < 100 [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε✝ ε : ℝ n : ℕ h : ↑100 ≤ 4 ^ n * ε ^ 5 ⊢ 0 ≤ 4 ^ n [PROOFSTEP] positivity [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Fintype α P : Finpartition univ u : Finset α ε : ℝ inst✝ : Nonempty α hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α ⊢ 4 ≤ 16 [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Fintype α P : Finpartition univ u : Finset α ε : ℝ inst✝ : Nonempty α hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α ⊢ 0 < Fintype.card α / stepBound (Finset.card P.parts) [PROOFSTEP] sz_positivity [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ ⊢ 0 < ↑(Fintype.card α / stepBound (Finset.card P.parts)) + 1 [PROOFSTEP] positivity [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ hPε : ↑100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 ⊢ 0 < 100 [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ hPε : ↑100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 ⊢ 0 ≤ 4 [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ hPε : ↑100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 ⊢ Odd 5 [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Fintype α P : Finpartition univ u : Finset α ε : ℝ inst✝ : Nonempty α hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : ↑100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 ⊢ 0 ≤ 4 ^ Finset.card P.parts [PROOFSTEP] positivity [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Fintype α P : Finpartition univ u : Finset α ε : ℝ inst✝ : Nonempty α hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : ↑100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 ⊢ 4 ^ Finset.card P.parts ≤ ↑(Fintype.card α / stepBound (Finset.card P.parts)) [PROOFSTEP] norm_cast [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Fintype α P : Finpartition univ u : Finset α ε : ℝ inst✝ : Nonempty α hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : ↑100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 ⊢ 4 ^ Finset.card P.parts ≤ Fintype.card α / stepBound (Finset.card P.parts) [PROOFSTEP] rwa [Nat.le_div_iff_mul_le' (stepBound_pos (P.parts_nonempty <| univ_nonempty.ne_empty).card_pos), stepBound, mul_left_comm, ← mul_pow] [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Fintype α P : Finpartition univ u : Finset α ε : ℝ inst✝ : Nonempty α hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : ↑100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hε : ε ≤ 1 ⊢ 100 ≤ Fintype.card α / stepBound (Finset.card P.parts) [PROOFSTEP] exact_mod_cast (hundred_div_ε_pow_five_le_m hPα hPε).trans' (le_div_self (by norm_num) (by sz_positivity) <| pow_le_one _ (by sz_positivity) hε) [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Fintype α P : Finpartition univ u : Finset α ε : ℝ inst✝ : Nonempty α hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : ↑100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hε : ε ≤ 1 ⊢ 0 ≤ ↑100 [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Fintype α P : Finpartition univ u : Finset α ε : ℝ inst✝ : Nonempty α hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : ↑100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hε : ε ≤ 1 ⊢ 0 < ε ^ 5 [PROOFSTEP] sz_positivity [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Fintype α P : Finpartition univ u : Finset α ε : ℝ inst✝ : Nonempty α hPα : Finset.card P.parts * 16 ^ Finset.card P.parts ≤ Fintype.card α hPε : ↑100 ≤ 4 ^ Finset.card P.parts * ε ^ 5 hε : ε ≤ 1 ⊢ 0 ≤ ε [PROOFSTEP] sz_positivity [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ ⊢ Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1 ≤ 4 ^ Finset.card P.parts [PROOFSTEP] have h : 1 ≤ 4 ^ P.parts.card := one_le_pow_of_one_le (by norm_num) _ [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ ⊢ 1 ≤ 4 [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ h : 1 ≤ 4 ^ Finset.card P.parts ⊢ Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1 ≤ 4 ^ Finset.card P.parts [PROOFSTEP] rw [stepBound, ← Nat.div_div_eq_div_mul] [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ h : 1 ≤ 4 ^ Finset.card P.parts ⊢ Fintype.card α / Finset.card P.parts - Fintype.card α / Finset.card P.parts / 4 ^ Finset.card P.parts * 4 ^ Finset.card P.parts + 1 ≤ 4 ^ Finset.card P.parts [PROOFSTEP] conv_rhs => rw [← Nat.sub_add_cancel h] [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ h : 1 ≤ 4 ^ Finset.card P.parts | 4 ^ Finset.card P.parts [PROOFSTEP] rw [← Nat.sub_add_cancel h] [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ h : 1 ≤ 4 ^ Finset.card P.parts | 4 ^ Finset.card P.parts [PROOFSTEP] rw [← Nat.sub_add_cancel h] [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ h : 1 ≤ 4 ^ Finset.card P.parts | 4 ^ Finset.card P.parts [PROOFSTEP] rw [← Nat.sub_add_cancel h] [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ h : 1 ≤ 4 ^ Finset.card P.parts ⊢ Fintype.card α / Finset.card P.parts - Fintype.card α / Finset.card P.parts / 4 ^ Finset.card P.parts * 4 ^ Finset.card P.parts + 1 ≤ 4 ^ Finset.card P.parts - 1 + 1 [PROOFSTEP] rw [add_le_add_iff_right, tsub_le_iff_left, ← Nat.add_sub_assoc h] [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ h : 1 ≤ 4 ^ Finset.card P.parts ⊢ Fintype.card α / Finset.card P.parts ≤ Fintype.card α / Finset.card P.parts / 4 ^ Finset.card P.parts * 4 ^ Finset.card P.parts + 4 ^ Finset.card P.parts - 1 [PROOFSTEP] exact Nat.le_pred_of_lt (Nat.lt_div_mul_add h) [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ hucard : Finset.card u = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts) ⊢ (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts)) * (Fintype.card α / stepBound (Finset.card P.parts)) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts) * (Fintype.card α / stepBound (Finset.card P.parts) + 1) = Finset.card u [PROOFSTEP] rw [hucard, mul_add, mul_one, ← add_assoc, ← add_mul, Nat.sub_add_cancel ((Nat.le_succ _).trans a_add_one_le_four_pow_parts_card), mul_comm] [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ hP : Finpartition.IsEquipartition P hu : u ∈ P.parts hucard : ¬Finset.card u = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts) ⊢ (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1)) * (Fintype.card α / stepBound (Finset.card P.parts)) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1) * (Fintype.card α / stepBound (Finset.card P.parts) + 1) = Finset.card u [PROOFSTEP] have : m * 4 ^ P.parts.card ≤ card α / P.parts.card := by rw [stepBound, ← Nat.div_div_eq_div_mul] exact Nat.div_mul_le_self _ _ [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ hP : Finpartition.IsEquipartition P hu : u ∈ P.parts hucard : ¬Finset.card u = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts) ⊢ Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts ≤ Fintype.card α / Finset.card P.parts [PROOFSTEP] rw [stepBound, ← Nat.div_div_eq_div_mul] [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ hP : Finpartition.IsEquipartition P hu : u ∈ P.parts hucard : ¬Finset.card u = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts) ⊢ Fintype.card α / Finset.card P.parts / 4 ^ Finset.card P.parts * 4 ^ Finset.card P.parts ≤ Fintype.card α / Finset.card P.parts [PROOFSTEP] exact Nat.div_mul_le_self _ _ [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ hP : Finpartition.IsEquipartition P hu : u ∈ P.parts hucard : ¬Finset.card u = Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts) this : Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts ≤ Fintype.card α / Finset.card P.parts ⊢ (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1)) * (Fintype.card α / stepBound (Finset.card P.parts)) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1) * (Fintype.card α / stepBound (Finset.card P.parts) + 1) = Finset.card u [PROOFSTEP] rw [Nat.add_sub_of_le this] at hucard [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ hP : Finpartition.IsEquipartition P hu : u ∈ P.parts hucard : ¬Finset.card u = Fintype.card α / Finset.card P.parts this : Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts ≤ Fintype.card α / Finset.card P.parts ⊢ (4 ^ Finset.card P.parts - (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1)) * (Fintype.card α / stepBound (Finset.card P.parts)) + (Fintype.card α / Finset.card P.parts - Fintype.card α / stepBound (Finset.card P.parts) * 4 ^ Finset.card P.parts + 1) * (Fintype.card α / stepBound (Finset.card P.parts) + 1) = Finset.card u [PROOFSTEP] rw [(hP.card_parts_eq_average hu).resolve_left hucard, mul_add, mul_one, ← add_assoc, ← add_mul, Nat.sub_add_cancel a_add_one_le_four_pow_parts_card, ← add_assoc, mul_comm, Nat.add_sub_of_le this, card_univ] [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ hP : Finpartition.IsEquipartition P hu : u ∈ P.parts ⊢ 4 ^ Finset.card P.parts * ↑(Fintype.card α / stepBound (Finset.card P.parts)) ≤ ↑(Finset.card u) [PROOFSTEP] norm_cast [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ hP : Finpartition.IsEquipartition P hu : u ∈ P.parts ⊢ 4 ^ Finset.card P.parts * (Fintype.card α / stepBound (Finset.card P.parts)) ≤ Finset.card u [PROOFSTEP] rw [stepBound, ← Nat.div_div_eq_div_mul] [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ hP : Finpartition.IsEquipartition P hu : u ∈ P.parts ⊢ 4 ^ Finset.card P.parts * (Fintype.card α / Finset.card P.parts / 4 ^ Finset.card P.parts) ≤ Finset.card u [PROOFSTEP] exact (Nat.mul_div_le _ _).trans (hP.average_le_card_part hu) [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε✝ : ℝ l✝ : ℕ ε : ℝ hε : 0 < ε l : ℕ ⊢ ↑100 < 4 ^ initialBound ε l * ε ^ 5 [PROOFSTEP] rw [← rpow_nat_cast 4, ← div_lt_iff (pow_pos hε 5), lt_rpow_iff_log_lt _ zero_lt_four, ← div_lt_iff, initialBound, Nat.cast_max, Nat.cast_max] [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε✝ : ℝ l✝ : ℕ ε : ℝ hε : 0 < ε l : ℕ ⊢ log (↑100 / ε ^ 5) / log 4 < max (↑7) (max ↑l ↑(⌊log (↑100 / ε ^ 5) / log 4⌋₊ + 1)) [PROOFSTEP] push_cast [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε✝ : ℝ l✝ : ℕ ε : ℝ hε : 0 < ε l : ℕ ⊢ log (100 / ε ^ 5) / log 4 < max 7 (max (↑l) (↑⌊log (100 / ε ^ 5) / log 4⌋₊ + 1)) [PROOFSTEP] exact lt_max_of_lt_right (lt_max_of_lt_right <| Nat.lt_floor_add_one _) [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε✝ : ℝ l✝ : ℕ ε : ℝ hε : 0 < ε l : ℕ ⊢ 0 < log 4 [PROOFSTEP] exact log_pos (by norm_num) [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε✝ : ℝ l✝ : ℕ ε : ℝ hε : 0 < ε l : ℕ ⊢ 1 < 4 [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε✝ : ℝ l✝ : ℕ ε : ℝ hε : 0 < ε l : ℕ ⊢ 0 < ↑100 / ε ^ 5 [PROOFSTEP] exact div_pos (by norm_num) (pow_pos hε 5) [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε✝ : ℝ l✝ : ℕ ε : ℝ hε : 0 < ε l : ℕ ⊢ 0 < ↑100 [PROOFSTEP] norm_num [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ⊢ 0 < 16 ^ stepBound^[⌊↑4 / ε ^ 5⌋₊] (initialBound ε l) [PROOFSTEP] positivity [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 ⊢ d + ↑(Finset.card s) / ↑(Finset.card t) * x ^ 2 ≤ (∑ i in t, f i ^ 2) / ↑(Finset.card t) [PROOFSTEP] obtain hscard | hscard := (s.card.cast_nonneg : (0 : 𝕜) ≤ s.card).eq_or_lt [GOAL] case inl α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 = ↑(Finset.card s) ⊢ d + ↑(Finset.card s) / ↑(Finset.card t) * x ^ 2 ≤ (∑ i in t, f i ^ 2) / ↑(Finset.card t) [PROOFSTEP] simpa [← hscard] using ht.trans sum_div_card_sq_le_sum_sq_div_card [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) ⊢ d + ↑(Finset.card s) / ↑(Finset.card t) * x ^ 2 ≤ (∑ i in t, f i ^ 2) / ↑(Finset.card t) [PROOFSTEP] have htcard : (0 : 𝕜) < t.card := hscard.trans_le (Nat.cast_le.2 (card_le_of_subset hst)) [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) ⊢ d + ↑(Finset.card s) / ↑(Finset.card t) * x ^ 2 ≤ (∑ i in t, f i ^ 2) / ↑(Finset.card t) [PROOFSTEP] have h₁ : x ^ 2 ≤ ((∑ i in s, f i) / s.card - (∑ i in t, f i) / t.card) ^ 2 := sq_le_sq.2 (by rwa [abs_of_nonneg hx]) [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) ⊢ |x| ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| [PROOFSTEP] rwa [abs_of_nonneg hx] [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 ⊢ d + ↑(Finset.card s) / ↑(Finset.card t) * x ^ 2 ≤ (∑ i in t, f i ^ 2) / ↑(Finset.card t) [PROOFSTEP] have h₂ : x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / t.card)) / s.card) ^ 2 := by apply h₁.trans rw [sum_sub_distrib, sum_const, nsmul_eq_mul, sub_div, mul_div_cancel_left _ hscard.ne'] [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 ⊢ x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 [PROOFSTEP] apply h₁.trans [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 ⊢ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 [PROOFSTEP] rw [sum_sub_distrib, sum_const, nsmul_eq_mul, sub_div, mul_div_cancel_left _ hscard.ne'] [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 h₂ : x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 ⊢ d + ↑(Finset.card s) / ↑(Finset.card t) * x ^ 2 ≤ (∑ i in t, f i ^ 2) / ↑(Finset.card t) [PROOFSTEP] apply (add_le_add_right ht _).trans [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 h₂ : x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 ⊢ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 + ↑(Finset.card s) / ↑(Finset.card t) * x ^ 2 ≤ (∑ i in t, f i ^ 2) / ↑(Finset.card t) [PROOFSTEP] rw [← mul_div_right_comm, le_div_iff htcard, add_mul, div_mul_cancel _ htcard.ne'] [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 h₂ : x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 ⊢ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 * ↑(Finset.card t) + ↑(Finset.card s) * x ^ 2 ≤ ∑ i in t, f i ^ 2 [PROOFSTEP] have h₃ := mul_sq_le_sum_sq hst (fun i => (f i - (∑ j in t, f j) / t.card)) h₂ hscard.ne' [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 h₂ : x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 h₃ : ↑(Finset.card s) * x ^ 2 ≤ ∑ i in t, (fun i => f i - (∑ j in t, f j) / ↑(Finset.card t)) i ^ 2 ⊢ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 * ↑(Finset.card t) + ↑(Finset.card s) * x ^ 2 ≤ ∑ i in t, f i ^ 2 [PROOFSTEP] apply (add_le_add_left h₃ _).trans [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 h₂ : x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 h₃ : ↑(Finset.card s) * x ^ 2 ≤ ∑ i in t, (fun i => f i - (∑ j in t, f j) / ↑(Finset.card t)) i ^ 2 ⊢ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 * ↑(Finset.card t) + ∑ i in t, (fun i => f i - (∑ j in t, f j) / ↑(Finset.card t)) i ^ 2 ≤ ∑ i in t, f i ^ 2 [PROOFSTEP] simp_rw [sub_div' _ _ _ htcard.ne'] [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 h₂ : x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 h₃ : ↑(Finset.card s) * x ^ 2 ≤ ∑ i in t, (fun i => f i - (∑ j in t, f j) / ↑(Finset.card t)) i ^ 2 ⊢ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 * ↑(Finset.card t) + ∑ x in t, ((f x * ↑(Finset.card t) - ∑ i in t, f i) / ↑(Finset.card t)) ^ 2 ≤ ∑ i in t, f i ^ 2 [PROOFSTEP] conv_lhs => enter [2, 2, x]; rw [div_pow] [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 h₂ : x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 h₃ : ↑(Finset.card s) * x ^ 2 ≤ ∑ i in t, (fun i => f i - (∑ j in t, f j) / ↑(Finset.card t)) i ^ 2 | ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 * ↑(Finset.card t) + ∑ x in t, ((f x * ↑(Finset.card t) - ∑ i in t, f i) / ↑(Finset.card t)) ^ 2 [PROOFSTEP] enter [2, 2, x]; rw [div_pow] [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 h₂ : x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 h₃ : ↑(Finset.card s) * x ^ 2 ≤ ∑ i in t, (fun i => f i - (∑ j in t, f j) / ↑(Finset.card t)) i ^ 2 | ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 * ↑(Finset.card t) + ∑ x in t, ((f x * ↑(Finset.card t) - ∑ i in t, f i) / ↑(Finset.card t)) ^ 2 [PROOFSTEP] enter [2, 2, x]; rw [div_pow] [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 h₂ : x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 h₃ : ↑(Finset.card s) * x ^ 2 ≤ ∑ i in t, (fun i => f i - (∑ j in t, f j) / ↑(Finset.card t)) i ^ 2 | ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 * ↑(Finset.card t) + ∑ x in t, ((f x * ↑(Finset.card t) - ∑ i in t, f i) / ↑(Finset.card t)) ^ 2 [PROOFSTEP] enter [2, 2, x] [GOAL] case h α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x✝ : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x✝ hs : x✝ ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x✝ ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 h₂ : x✝ ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 h₃ : ↑(Finset.card s) * x✝ ^ 2 ≤ ∑ i in t, (fun i => f i - (∑ j in t, f j) / ↑(Finset.card t)) i ^ 2 x : ι | ((f x * ↑(Finset.card t) - ∑ i in t, f i) / ↑(Finset.card t)) ^ 2 [PROOFSTEP] rw [div_pow] [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 h₂ : x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 h₃ : ↑(Finset.card s) * x ^ 2 ≤ ∑ i in t, (fun i => f i - (∑ j in t, f j) / ↑(Finset.card t)) i ^ 2 ⊢ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 * ↑(Finset.card t) + ∑ x in t, (f x * ↑(Finset.card t) - ∑ i in t, f i) ^ 2 / ↑(Finset.card t) ^ 2 ≤ ∑ i in t, f i ^ 2 [PROOFSTEP] rw [div_pow, ← sum_div, ← mul_div_right_comm _ (t.card : 𝕜), ← add_div, div_le_iff (sq_pos_of_ne_zero _ htcard.ne')] [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 h₂ : x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 h₃ : ↑(Finset.card s) * x ^ 2 ≤ ∑ i in t, (fun i => f i - (∑ j in t, f j) / ↑(Finset.card t)) i ^ 2 ⊢ (∑ i in t, f i) ^ 2 * ↑(Finset.card t) + ∑ x in t, (f x * ↑(Finset.card t) - ∑ i in t, f i) ^ 2 ≤ (∑ i in t, f i ^ 2) * ↑(Finset.card t) ^ 2 [PROOFSTEP] simp_rw [sub_sq, sum_add_distrib, sum_const, nsmul_eq_mul, sum_sub_distrib, mul_pow, ← sum_mul, ← mul_sum, ← sum_mul] [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 h₂ : x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 h₃ : ↑(Finset.card s) * x ^ 2 ≤ ∑ i in t, (fun i => f i - (∑ j in t, f j) / ↑(Finset.card t)) i ^ 2 ⊢ (∑ i in t, f i) ^ 2 * ↑(Finset.card t) + ((∑ x in t, f x ^ 2) * ↑(Finset.card t) ^ 2 - 2 * ((∑ i in t, f i) * ↑(Finset.card t)) * ∑ i in t, f i + ↑(Finset.card t) * (∑ i in t, f i) ^ 2) ≤ (∑ i in t, f i ^ 2) * ↑(Finset.card t) ^ 2 [PROOFSTEP] ring_nf [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : Fintype α P : Finpartition univ u : Finset α ε : ℝ l : ℕ ι : Type u_2 𝕜 : Type u_3 inst✝¹ : LinearOrderedField 𝕜 r : ι → ι → Prop inst✝ : DecidableRel r s t : Finset ι x : 𝕜 hst : s ⊆ t f : ι → 𝕜 d : 𝕜 hx : 0 ≤ x hs : x ≤ |(∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)| ht : d ≤ ((∑ i in t, f i) / ↑(Finset.card t)) ^ 2 hscard : 0 < ↑(Finset.card s) htcard : 0 < ↑(Finset.card t) h₁ : x ^ 2 ≤ ((∑ i in s, f i) / ↑(Finset.card s) - (∑ i in t, f i) / ↑(Finset.card t)) ^ 2 h₂ : x ^ 2 ≤ ((∑ i in s, (f i - (∑ j in t, f j) / ↑(Finset.card t))) / ↑(Finset.card s)) ^ 2 h₃ : ↑(Finset.card s) * x ^ 2 ≤ ∑ i in t, (fun i => f i - (∑ j in t, f j) / ↑(Finset.card t)) i ^ 2 ⊢ ↑(Finset.card t) ^ 2 * ∑ x in t, f x ^ 2 ≤ ↑(Finset.card t) ^ 2 * ∑ x in t, f x ^ 2 [PROOFSTEP] rfl [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε✝ ε : ℝ l : ℕ ⊢ 0 < initialBound ε l [PROOFSTEP] positivity [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : Fintype α P : Finpartition univ u : Finset α ε✝ ε : ℝ l : ℕ ⊢ 0 < bound ε l [PROOFSTEP] positivity
view [ button "kk" banner "test" h5 "test 2" btn-cancel btn-enter btn-help ]
import LMT variable {I} [Nonempty I] {E} [Nonempty E] [Nonempty (A I E)] example {a1 a2 a3 : A I E} : ((((a3).write i2 (v3)).write i1 (v3)).read i2) ≠ (v3) → False := by arr
Rebol [ Title: "Nightly build for SVN tango" ] do %rcopy.r location: %/c/projects/tango_install/nightly_build recreateDir: func [ dir [ file! ] ] [ if exists? dir [ delete-dir dir ] make-dir dir ] ;check out tango ;http://svn.dsource.org/projects/tango/trunk/ ;delete old installation file change-dir location if exists? %tango-svn-installer.zip [ delete %tango-svn-installer.zip ] svn-tango: join [ svn --force export http://svn.dsource.org/projects/tango/trunk] rejoin [ to-local-file location "/tango" ] ;svn-tango: join [ svn --force export http://svn.dsource.org/projects/tango/branches/D1_0/0_96_beta2/ ] rejoin [ to-local-file location "/tango" ] probe svn-tango delete-dir %tango call/console reduce [svn-tango] change-dir rejoin [ location "/tango/lib" ] call/console [ build-dmd.bat ] change-dir location recreateDir %tango_temp recreateDir %tango_temp/tango/ rcopy/verbose %tango/tango/ %tango_temp/tango/ recreateDir %tango_temp/std/ rcopy/verbose %tango/std/ %tango_temp/std/ recreateDir %tango_temp/example/ rcopy/verbose %tango/example/ %tango_temp/example/ write %tango_temp/object.di read %tango/object.di recreateDir %lib/ write/binary %lib/tango_phobos.lib read/binary %tango/lib/phobos.lib rcopy/verbose %../nightly_svn_lib/ %lib/ recreateDir %tango/ rcopy/verbose %tango_temp/ %tango/ delete-dir %tango_temp/ delete-dir %tango/lib/ recreateDir %bin/ rcopy/verbose %../nightly_svn_bin/ %bin/ call/console [ "7z a -r -tzip tango-svn-installer.zip * "] write/binary %../downloads_checkout/tango-svn-installer.zip read/binary %tango-svn-installer.zip change-dir %.. call/console ["svn ci -m svn_build downloads_checkout/" ]
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel ! This file was ported from Lean 3 source module topology.metric_space.emetric_space ! leanprover-community/mathlib commit 195fcd60ff2bfe392543bceb0ec2adcdb472db4c ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Data.Nat.Interval import Mathlib.Data.Real.ENNReal import Mathlib.Topology.UniformSpace.Pi import Mathlib.Topology.UniformSpace.UniformConvergence import Mathlib.Topology.UniformSpace.UniformEmbedding /-! # Extended metric spaces This file is devoted to the definition and study of `EMetricSpace`s, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ℝ≥0∞`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity. The class `EMetricSpace` therefore extends `UniformSpace` (and `TopologicalSpace`). Since a lot of elementary properties don't require `eq_of_edist_eq_zero` we start setting up the theory of `PseudoEMetricSpace`, where we don't require `edist x y = 0 → x = y` and we specialize to `EMetricSpace` at the end. -/ open Set Filter Classical Uniformity Topology BigOperators NNReal ENNReal universe u v w variable {α : Type u} {β : Type v} {X : Type _} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ theorem uniformity_dist_of_mem_uniformity [LinearOrder β] {U : Filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ ε > z, ∀ {a b : α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε > z, 𝓟 { p : α × α | D p.1 p.2 < ε } := HasBasis.eq_binfᵢ ⟨fun s => by simp only [H, subset_def, Prod.forall, mem_setOf]⟩ #align uniformity_dist_of_mem_uniformity uniformity_dist_of_mem_uniformity /-- `EDist α` means that `α` is equipped with an extended distance. -/ class EDist (α : Type _) where edist : α → α → ℝ≥0∞ #align has_edist EDist export EDist (edist) /-- Creating a uniform space from an extended distance. -/ def uniformSpaceOfEDist (edist : α → α → ℝ≥0∞) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : UniformSpace α := .ofFun edist edist_self edist_comm edist_triangle fun ε ε0 => ⟨ε / 2, ENNReal.half_pos ε0.ne', fun _ h₁ _ h₂ => (ENNReal.add_lt_add h₁ h₂).trans_eq (ENNReal.add_halves _)⟩ #align uniform_space_of_edist uniformSpaceOfEDist -- the uniform structure is embedded in the emetric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- Extended (pseudo) metric spaces, with an extended distance `edist` possibly taking the value ∞ Each pseudo_emetric space induces a canonical `UniformSpace` and hence a canonical `TopologicalSpace`. This is enforced in the type class definition, by extending the `UniformSpace` structure. When instantiating a `PseudoEMetricSpace` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating a `PseudoEMetricSpace` structure on a product. Continuity of `edist` is proved in `topology.instances.ennreal` -/ class PseudoEMetricSpace (α : Type u) extends EDist α : Type u where edist_self : ∀ x : α, edist x x = 0 edist_comm : ∀ x y : α, edist x y = edist y x edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z toUniformSpace : UniformSpace α := uniformSpaceOfEDist edist edist_self edist_comm edist_triangle uniformity_edist : 𝓤 α = ⨅ ε > 0, 𝓟 { p : α × α | edist p.1 p.2 < ε } := by rfl #align pseudo_emetric_space PseudoEMetricSpace attribute [instance] PseudoEMetricSpace.toUniformSpace /- Pseudoemetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variable [PseudoEMetricSpace α] export PseudoEMetricSpace (edist_self edist_comm edist_triangle) attribute [simp] edist_self /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw [edist_comm z]; apply edist_triangle #align edist_triangle_left edist_triangle_left theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw [edist_comm y]; apply edist_triangle #align edist_triangle_right edist_triangle_right theorem edist_congr_right {x y z : α} (h : edist x y = 0) : edist x z = edist y z := by apply le_antisymm · rw [← zero_add (edist y z), ← h] apply edist_triangle · rw [edist_comm] at h rw [← zero_add (edist x z), ← h] apply edist_triangle #align edist_congr_right edist_congr_right theorem edist_congr_left {x y z : α} (h : edist x y = 0) : edist z x = edist z y := by rw [edist_comm z x, edist_comm z y] apply edist_congr_right h #align edist_congr_left edist_congr_left theorem edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t := edist_triangle x z t _ ≤ edist x y + edist y z + edist z t := add_le_add_right (edist_triangle x y z) _ #align edist_triangle4 edist_triangle4 /-- The triangle (polygon) inequality for sequences of points; `Finset.Ico` version. -/ theorem edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ ∑ i in Finset.Ico m n, edist (f i) (f (i + 1)) := by induction n, h using Nat.le_induction case base => rw [Finset.Ico_self, Finset.sum_empty, edist_self] case succ n hle ihn => calc edist (f m) (f (n + 1)) ≤ edist (f m) (f n) + edist (f n) (f (n + 1)) := edist_triangle _ _ _ _ ≤ (∑ i in Finset.Ico m n, _) + _ := add_le_add ihn le_rfl _ = ∑ i in Finset.Ico m (n + 1), _ := by { rw [Nat.Ico_succ_right_eq_insert_Ico hle, Finset.sum_insert, add_comm]; simp } #align edist_le_Ico_sum_edist edist_le_Ico_sum_edist /-- The triangle (polygon) inequality for sequences of points; `Finset.range` version. -/ theorem edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ ∑ i in Finset.range n, edist (f i) (f (i + 1)) := Nat.Ico_zero_eq_range ▸ edist_le_Ico_sum_edist f (Nat.zero_le n) #align edist_le_range_sum_edist edist_le_range_sum_edist /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ theorem edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ ∑ i in Finset.Ico m n, d i := le_trans (edist_le_Ico_sum_edist f hmn) <| Finset.sum_le_sum fun _k hk => hd (Finset.mem_Ico.1 hk).1 (Finset.mem_Ico.1 hk).2 #align edist_le_Ico_sum_of_edist_le edist_le_Ico_sum_of_edist_le /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ theorem edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ ∑ i in Finset.range n, d i := Nat.Ico_zero_eq_range ▸ edist_le_Ico_sum_of_edist_le (zero_le n) fun _ => hd #align edist_le_range_sum_of_edist_le edist_le_range_sum_of_edist_le /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_pseudoedist : 𝓤 α = ⨅ ε > 0, 𝓟 { p : α × α | edist p.1 p.2 < ε } := PseudoEMetricSpace.uniformity_edist #align uniformity_pseudoedist uniformity_pseudoedist theorem uniformSpace_edist : ‹PseudoEMetricSpace α›.toUniformSpace = uniformSpaceOfEDist edist edist_self edist_comm edist_triangle := uniformSpace_eq uniformity_pseudoedist #align uniform_space_edist uniformSpace_edist theorem uniformity_basis_edist : (𝓤 α).HasBasis (fun ε : ℝ≥0∞ => 0 < ε) fun ε => { p : α × α | edist p.1 p.2 < ε } := (@uniformSpace_edist α _).symm ▸ UniformSpace.hasBasis_ofFun ⟨1, one_pos⟩ _ _ _ _ _ #align uniformity_basis_edist uniformity_basis_edist /-- Characterization of the elements of the uniformity in terms of the extended distance -/ theorem mem_uniformity_edist {s : Set (α × α)} : s ∈ 𝓤 α ↔ ∃ ε > 0, ∀ {a b : α}, edist a b < ε → (a, b) ∈ s := uniformity_basis_edist.mem_uniformity_iff #align mem_uniformity_edist mem_uniformity_edist /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`, `uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/ protected theorem EMetric.mk_uniformity_basis {β : Type _} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x, p x ∧ f x ≤ ε) : (𝓤 α).HasBasis p fun x => { p : α × α | edist p.1 p.2 < f x } := by refine' ⟨fun s => uniformity_basis_edist.mem_iff.trans _⟩ constructor · rintro ⟨ε, ε₀, hε⟩ rcases hf ε ε₀ with ⟨i, hi, H⟩ exact ⟨i, hi, fun x hx => hε <| lt_of_lt_of_le hx.out H⟩ · exact fun ⟨i, hi, H⟩ => ⟨f i, hf₀ i hi, H⟩ #align emetric.mk_uniformity_basis EMetric.mk_uniformity_basis /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/ protected theorem EMetric.mk_uniformity_basis_le {β : Type _} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x, p x ∧ f x ≤ ε) : (𝓤 α).HasBasis p fun x => { p : α × α | edist p.1 p.2 ≤ f x } := by refine' ⟨fun s => uniformity_basis_edist.mem_iff.trans _⟩ constructor · rintro ⟨ε, ε₀, hε⟩ rcases exists_between ε₀ with ⟨ε', hε'⟩ rcases hf ε' hε'.1 with ⟨i, hi, H⟩ exact ⟨i, hi, fun x hx => hε <| lt_of_le_of_lt (le_trans hx.out H) hε'.2⟩ · exact fun ⟨i, hi, H⟩ => ⟨f i, hf₀ i hi, fun x hx => H (le_of_lt hx.out)⟩ #align emetric.mk_uniformity_basis_le EMetric.mk_uniformity_basis_le theorem uniformity_basis_edist_le : (𝓤 α).HasBasis (fun ε : ℝ≥0∞ => 0 < ε) fun ε => { p : α × α | edist p.1 p.2 ≤ ε } := EMetric.mk_uniformity_basis_le (fun _ => id) fun ε ε₀ => ⟨ε, ε₀, le_refl ε⟩ #align uniformity_basis_edist_le uniformity_basis_edist_le theorem uniformity_basis_edist' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).HasBasis (fun ε : ℝ≥0∞ => ε ∈ Ioo 0 ε') fun ε => { p : α × α | edist p.1 p.2 < ε } := EMetric.mk_uniformity_basis (fun _ => And.left) fun ε ε₀ => let ⟨δ, hδ⟩ := exists_between hε' ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩ #align uniformity_basis_edist' uniformity_basis_edist' theorem uniformity_basis_edist_le' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).HasBasis (fun ε : ℝ≥0∞ => ε ∈ Ioo 0 ε') fun ε => { p : α × α | edist p.1 p.2 ≤ ε } := EMetric.mk_uniformity_basis_le (fun _ => And.left) fun ε ε₀ => let ⟨δ, hδ⟩ := exists_between hε' ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩ #align uniformity_basis_edist_le' uniformity_basis_edist_le' theorem uniformity_basis_edist_nnreal : (𝓤 α).HasBasis (fun ε : ℝ≥0 => 0 < ε) fun ε => { p : α × α | edist p.1 p.2 < ε } := EMetric.mk_uniformity_basis (fun _ => ENNReal.coe_pos.2) fun _ε ε₀ => let ⟨δ, hδ⟩ := ENNReal.lt_iff_exists_nnreal_btwn.1 ε₀ ⟨δ, ENNReal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩ #align uniformity_basis_edist_nnreal uniformity_basis_edist_nnreal theorem uniformity_basis_edist_nnreal_le : (𝓤 α).HasBasis (fun ε : ℝ≥0 => 0 < ε) fun ε => { p : α × α | edist p.1 p.2 ≤ ε } := EMetric.mk_uniformity_basis_le (fun _ => ENNReal.coe_pos.2) fun _ε ε₀ => let ⟨δ, hδ⟩ := ENNReal.lt_iff_exists_nnreal_btwn.1 ε₀ ⟨δ, ENNReal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩ #align uniformity_basis_edist_nnreal_le uniformity_basis_edist_nnreal_le theorem uniformity_basis_edist_inv_nat : (𝓤 α).HasBasis (fun _ => True) fun n : ℕ => { p : α × α | edist p.1 p.2 < (↑n)⁻¹ } := EMetric.mk_uniformity_basis (fun n _ => ENNReal.inv_pos.2 <| ENNReal.nat_ne_top n) fun _ε ε₀ => let ⟨n, hn⟩ := ENNReal.exists_inv_nat_lt (ne_of_gt ε₀) ⟨n, trivial, le_of_lt hn⟩ #align uniformity_basis_edist_inv_nat uniformity_basis_edist_inv_nat theorem uniformity_basis_edist_inv_two_pow : (𝓤 α).HasBasis (fun _ => True) fun n : ℕ => { p : α × α | edist p.1 p.2 < 2⁻¹ ^ n } := EMetric.mk_uniformity_basis (fun _ _ => ENNReal.pow_pos (ENNReal.inv_pos.2 ENNReal.two_ne_top) _) fun _ε ε₀ => let ⟨n, hn⟩ := ENNReal.exists_inv_two_pow_lt (ne_of_gt ε₀) ⟨n, trivial, le_of_lt hn⟩ #align uniformity_basis_edist_inv_two_pow uniformity_basis_edist_inv_two_pow /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε : ℝ≥0∞} (ε0 : 0 < ε) : { p : α × α | edist p.1 p.2 < ε } ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, id⟩ #align edist_mem_uniformity edist_mem_uniformity namespace EMetric instance (priority := 900) : IsCountablyGenerated (𝓤 α) := isCountablyGenerated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infᵢ⟩ -- porting note: changed explicit/implicit /-- ε-δ characterization of uniform continuity on a set for pseudoemetric spaces -/ theorem uniformContinuousOn_iff [PseudoEMetricSpace β] {f : α → β} {s : Set α} : UniformContinuousOn f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ {a}, a ∈ s → ∀ {b}, b ∈ s → edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniformContinuousOn_iff uniformity_basis_edist #align emetric.uniform_continuous_on_iff EMetric.uniformContinuousOn_iff /-- ε-δ characterization of uniform continuity on pseudoemetric spaces -/ theorem uniformContinuous_iff [PseudoEMetricSpace β] {f : α → β} : UniformContinuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniformContinuous_iff uniformity_basis_edist #align emetric.uniform_continuous_iff EMetric.uniformContinuous_iff -- porting note: new lemma theorem uniformInducing_iff [PseudoEMetricSpace β] {f : α → β} : UniformInducing f ↔ UniformContinuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniformInducing_iff'.trans <| Iff.rfl.and <| ((uniformity_basis_edist.comap _).le_basis_iff uniformity_basis_edist).trans <| by simp only [subset_def, Prod.forall]; rfl /-- ε-δ characterization of uniform embeddings on pseudoemetric spaces -/ nonrec theorem uniformEmbedding_iff [PseudoEMetricSpace β] {f : α → β} : UniformEmbedding f ↔ Function.Injective f ∧ UniformContinuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := (uniformEmbedding_iff _).trans <| and_comm.trans <| Iff.rfl.and uniformInducing_iff #align emetric.uniform_embedding_iff EMetric.uniformEmbedding_iff /-- If a map between pseudoemetric spaces is a uniform embedding then the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y`. In fact, this lemma holds for a `UniformInducing` map. TODO: generalize? -/ theorem controlled_of_uniformEmbedding [PseudoEMetricSpace β] {f : α → β} (h : UniformEmbedding f) : (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := ⟨uniformContinuous_iff.1 h.uniformContinuous, (uniformEmbedding_iff.1 h).2.2⟩ #align emetric.controlled_of_uniform_embedding EMetric.controlled_of_uniformEmbedding /-- ε-δ characterization of Cauchy sequences on pseudoemetric spaces -/ protected theorem cauchy_iff {f : Filter α} : Cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x, x ∈ t → ∀ y, y ∈ t → edist x y < ε := by rw [← neBot_iff]; exact uniformity_basis_edist.cauchy_iff #align emetric.cauchy_iff EMetric.cauchy_iff /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem complete_of_convergent_controlled_sequences (B : ℕ → ℝ≥0∞) (hB : ∀ n, 0 < B n) (H : ∀ u : ℕ → α, (∀ N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃ x, Tendsto u atTop (𝓝 x)) : CompleteSpace α := UniformSpace.complete_of_convergent_controlled_sequences (fun n => { p : α × α | edist p.1 p.2 < B n }) (fun n => edist_mem_uniformity <| hB n) H #align emetric.complete_of_convergent_controlled_sequences EMetric.complete_of_convergent_controlled_sequences /-- A sequentially complete pseudoemetric space is complete. -/ /-- Expressing locally uniform convergence on a set using `edist`. -/ theorem tendstoLocallyUniformlyOn_iff {ι : Type _} [TopologicalSpace β] {F : ι → β → α} {f : β → α} {p : Filter ι} {s : Set β} : TendstoLocallyUniformlyOn F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := by refine' ⟨fun H ε hε => H _ (edist_mem_uniformity hε), fun H u hu x hx => _⟩ rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩ rcases H ε εpos x hx with ⟨t, ht, Ht⟩ exact ⟨t, ht, Ht.mono fun n hs x hx => hε (hs x hx)⟩ #align emetric.tendsto_locally_uniformly_on_iff EMetric.tendstoLocallyUniformlyOn_iff /-- Expressing uniform convergence on a set using `edist`. -/ theorem tendstoUniformlyOn_iff {ι : Type _} {F : ι → β → α} {f : β → α} {p : Filter ι} {s : Set β} : TendstoUniformlyOn F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε := by refine' ⟨fun H ε hε => H _ (edist_mem_uniformity hε), fun H u hu => _⟩ rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩ exact (H ε εpos).mono fun n hs x hx => hε (hs x hx) #align emetric.tendsto_uniformly_on_iff EMetric.tendstoUniformlyOn_iff /-- Expressing locally uniform convergence using `edist`. -/ theorem tendstoLocallyUniformly_iff {ι : Type _} [TopologicalSpace β] {F : ι → β → α} {f : β → α} {p : Filter ι} : TendstoLocallyUniformly F f p ↔ ∀ ε > 0, ∀ x : β, ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := by simp only [← tendstoLocallyUniformlyOn_univ, tendstoLocallyUniformlyOn_iff, mem_univ, forall_const, exists_prop, nhdsWithin_univ] #align emetric.tendsto_locally_uniformly_iff EMetric.tendstoLocallyUniformly_iff /-- Expressing uniform convergence using `edist`. -/ theorem tendstoUniformly_iff {ι : Type _} {F : ι → β → α} {f : β → α} {p : Filter ι} : TendstoUniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε := by simp only [← tendstoUniformlyOn_univ, tendstoUniformlyOn_iff, mem_univ, forall_const] #align emetric.tendsto_uniformly_iff EMetric.tendstoUniformly_iff end EMetric open EMetric /-- Auxiliary function to replace the uniformity on a pseudoemetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct a pseudoemetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def PseudoEMetricSpace.replaceUniformity {α} [U : UniformSpace α] (m : PseudoEMetricSpace α) (H : 𝓤[U] = 𝓤[PseudoEMetricSpace.toUniformSpace]) : PseudoEMetricSpace α where edist := @edist _ m.toEDist edist_self := edist_self edist_comm := edist_comm edist_triangle := edist_triangle toUniformSpace := U uniformity_edist := H.trans (@PseudoEMetricSpace.uniformity_edist α _) #align pseudo_emetric_space.replace_uniformity PseudoEMetricSpace.replaceUniformity /-- The extended pseudometric induced by a function taking values in a pseudoemetric space. -/ def PseudoEMetricSpace.induced {α β} (f : α → β) (m : PseudoEMetricSpace β) : PseudoEMetricSpace α where edist x y := edist (f x) (f y) edist_self _ := edist_self _ edist_comm _ _ := edist_comm _ _ edist_triangle _ _ _ := edist_triangle _ _ _ toUniformSpace := UniformSpace.comap f m.toUniformSpace uniformity_edist := (uniformity_basis_edist.comap (Prod.map f f)).eq_binfᵢ #align pseudo_emetric_space.induced PseudoEMetricSpace.induced /-- Pseudoemetric space instance on subsets of pseudoemetric spaces -/ instance {α : Type _} {p : α → Prop} [PseudoEMetricSpace α] : PseudoEMetricSpace (Subtype p) := PseudoEMetricSpace.induced Subtype.val ‹_› /-- The extended psuedodistance on a subset of a pseudoemetric space is the restriction of the original pseudodistance, by definition -/ theorem Subtype.edist_eq {p : α → Prop} (x y : Subtype p) : edist x y = edist (x : α) y := rfl #align subtype.edist_eq Subtype.edist_eq namespace MulOpposite /-- Pseudoemetric space instance on the multiplicative opposite of a pseudoemetric space. -/ @[to_additive "Pseudoemetric space instance on the additive opposite of a pseudoemetric space."] instance {α : Type _} [PseudoEMetricSpace α] : PseudoEMetricSpace αᵐᵒᵖ := PseudoEMetricSpace.induced unop ‹_› @[to_additive] theorem edist_unop (x y : αᵐᵒᵖ) : edist (unop x) (unop y) = edist x y := rfl #align mul_opposite.edist_unop MulOpposite.edist_unop #align add_opposite.edist_unop AddOpposite.edist_unop @[to_additive] theorem edist_op (x y : α) : edist (op x) (op y) = edist x y := rfl #align mul_opposite.edist_op MulOpposite.edist_op #align add_opposite.edist_op AddOpposite.edist_op end MulOpposite section ULift instance : PseudoEMetricSpace (ULift α) := PseudoEMetricSpace.induced ULift.down ‹_› theorem ULift.edist_eq (x y : ULift α) : edist x y = edist x.down y.down := rfl #align ulift.edist_eq ULift.edist_eq @[simp] theorem ULift.edist_up_up (x y : α) : edist (ULift.up x) (ULift.up y) = edist x y := rfl #align ulift.edist_up_up ULift.edist_up_up end ULift /-- The product of two pseudoemetric spaces, with the max distance, is an extended pseudometric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance Prod.pseudoEMetricSpaceMax [PseudoEMetricSpace β] : PseudoEMetricSpace (α × β) where edist x y := edist x.1 y.1 ⊔ edist x.2 y.2 edist_self x := by simp edist_comm x y := by simp [edist_comm] edist_triangle x y z := max_le (le_trans (edist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))) uniformity_edist := uniformity_prod.trans <| by simp [PseudoEMetricSpace.uniformity_edist, ← infᵢ_inf_eq, setOf_and] toUniformSpace := inferInstance #align prod.pseudo_emetric_space_max Prod.pseudoEMetricSpaceMax theorem Prod.edist_eq [PseudoEMetricSpace β] (x y : α × β) : edist x y = max (edist x.1 y.1) (edist x.2 y.2) := rfl #align prod.edist_eq Prod.edist_eq section Pi open Finset variable {π : β → Type _} [Fintype β] -- porting note: reordered instances instance [∀ b, EDist (π b)] : EDist (∀ b, π b) where edist f g := Finset.sup univ fun b => edist (f b) (g b) theorem edist_pi_def [∀ b, EDist (π b)] (f g : ∀ b, π b) : edist f g = Finset.sup univ fun b => edist (f b) (g b) := rfl #align edist_pi_def edist_pi_def theorem edist_le_pi_edist [∀ b, EDist (π b)] (f g : ∀ b, π b) (b : β) : edist (f b) (g b) ≤ edist f g := le_sup (f := fun b => edist (f b) (g b)) (Finset.mem_univ b) #align edist_le_pi_edist edist_le_pi_edist theorem edist_pi_le_iff [∀ b, EDist (π b)] {f g : ∀ b, π b} {d : ℝ≥0∞} : edist f g ≤ d ↔ ∀ b, edist (f b) (g b) ≤ d := Finset.sup_le_iff.trans <| by simp only [Finset.mem_univ, forall_const] #align edist_pi_le_iff edist_pi_le_iff theorem edist_pi_const_le (a b : α) : (edist (fun _ : β => a) fun _ => b) ≤ edist a b := edist_pi_le_iff.2 fun _ => le_rfl #align edist_pi_const_le edist_pi_const_le @[simp] theorem edist_pi_const [Nonempty β] (a b : α) : (edist (fun _ : β => a) fun _ => b) = edist a b := Finset.sup_const univ_nonempty (edist a b) #align edist_pi_const edist_pi_const /-- The product of a finite number of pseudoemetric spaces, with the max distance, is still a pseudoemetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance pseudoEMetricSpacePi [∀ b, PseudoEMetricSpace (π b)] : PseudoEMetricSpace (∀ b, π b) where edist_self f := bot_unique <| Finset.sup_le <| by simp edist_comm f g := by simp [edist_pi_def, edist_comm] edist_triangle f g h := edist_pi_le_iff.2 <| fun b => le_trans (edist_triangle _ (g b) _) (add_le_add (edist_le_pi_edist _ _ _) (edist_le_pi_edist _ _ _)) toUniformSpace := Pi.uniformSpace _ uniformity_edist := by simp only [Pi.uniformity, PseudoEMetricSpace.uniformity_edist, comap_infᵢ, gt_iff_lt, preimage_setOf_eq, comap_principal, edist_pi_def] rw [infᵢ_comm]; congr ; funext ε rw [infᵢ_comm]; congr ; funext εpos simp [setOf_forall, εpos] #align pseudo_emetric_space_pi pseudoEMetricSpacePi end Pi namespace EMetric variable {x y z : α} {ε ε₁ ε₂ : ℝ≥0∞} {s t : Set α} /-- `EMetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ℝ≥0∞) : Set α := { y | edist y x < ε } #align emetric.ball EMetric.ball @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := Iff.rfl #align emetric.mem_ball EMetric.mem_ball theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw [edist_comm, mem_ball] #align emetric.mem_ball' EMetric.mem_ball' /-- `EMetric.closedBall x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closedBall (x : α) (ε : ℝ≥0∞) := { y | edist y x ≤ ε } #align emetric.closed_ball EMetric.closedBall @[simp] theorem mem_closedBall : y ∈ closedBall x ε ↔ edist y x ≤ ε := Iff.rfl #align emetric.mem_closed_ball EMetric.mem_closedBall theorem mem_closedBall' : y ∈ closedBall x ε ↔ edist x y ≤ ε := by rw [edist_comm, mem_closedBall] #align emetric.mem_closed_ball' EMetric.mem_closedBall' @[simp] theorem closedBall_top (x : α) : closedBall x ∞ = univ := eq_univ_of_forall fun _ => mem_setOf.2 le_top #align emetric.closed_ball_top EMetric.closedBall_top theorem ball_subset_closedBall : ball x ε ⊆ closedBall x ε := fun _ h => le_of_lt h.out #align emetric.ball_subset_closed_ball EMetric.ball_subset_closedBall theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy #align emetric.pos_of_mem_ball EMetric.pos_of_mem_ball theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := by rwa [mem_ball, edist_self] #align emetric.mem_ball_self EMetric.mem_ball_self theorem mem_closedBall_self : x ∈ closedBall x ε := by rw [mem_closedBall, edist_self]; apply zero_le #align emetric.mem_closed_ball_self EMetric.mem_closedBall_self theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by rw [mem_ball', mem_ball] #align emetric.mem_ball_comm EMetric.mem_ball_comm theorem mem_closedBall_comm : x ∈ closedBall y ε ↔ y ∈ closedBall x ε := by rw [mem_closedBall', mem_closedBall] #align emetric.mem_closed_ball_comm EMetric.mem_closedBall_comm theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := fun _y (yx : _ < ε₁) => lt_of_lt_of_le yx h #align emetric.ball_subset_ball EMetric.ball_subset_ball theorem closedBall_subset_closedBall (h : ε₁ ≤ ε₂) : closedBall x ε₁ ⊆ closedBall x ε₂ := fun _y (yx : _ ≤ ε₁) => le_trans yx h #align emetric.closed_ball_subset_closed_ball EMetric.closedBall_subset_closedBall theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : Disjoint (ball x ε₁) (ball y ε₂) := Set.disjoint_left.mpr fun z h₁ h₂ => (edist_triangle_left x y z).not_lt <| (ENNReal.add_lt_add h₁ h₂).trans_le h #align emetric.ball_disjoint EMetric.ball_disjoint theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y ≠ ∞) : ball x ε₁ ⊆ ball y ε₂ := fun z zx => calc edist z y ≤ edist z x + edist x y := edist_triangle _ _ _ _ = edist x y + edist z x := add_comm _ _ _ < edist x y + ε₁ := ENNReal.add_lt_add_left h' zx _ ≤ ε₂ := h #align emetric.ball_subset EMetric.ball_subset theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := by have : 0 < ε - edist y x := by simpa using h refine' ⟨ε - edist y x, this, ball_subset _ (ne_top_of_lt h)⟩ exact (add_tsub_cancel_of_le (mem_ball.mp h).le).le #align emetric.exists_ball_subset_ball EMetric.exists_ball_subset_ball theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨fun h => le_bot_iff.1 (le_of_not_gt fun ε0 => h _ (mem_ball_self ε0)), fun ε0 _ h => not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ #align emetric.ball_eq_empty_iff EMetric.ball_eq_empty_iff theorem ordConnected_setOf_closedBall_subset (x : α) (s : Set α) : OrdConnected { r | closedBall x r ⊆ s } := ⟨fun _ _ _ h₁ _ h₂ => (closedBall_subset_closedBall h₂.2).trans h₁⟩ #align emetric.ord_connected_set_of_closed_ball_subset EMetric.ordConnected_setOf_closedBall_subset theorem ordConnected_setOf_ball_subset (x : α) (s : Set α) : OrdConnected { r | ball x r ⊆ s } := ⟨fun _ _ _ h₁ _ h₂ => (ball_subset_ball h₂.2).trans h₁⟩ #align emetric.ord_connected_set_of_ball_subset EMetric.ordConnected_setOf_ball_subset /-- Relation “two points are at a finite edistance” is an equivalence relation. -/ def edistLtTopSetoid : Setoid α where r x y := edist x y < ⊤ iseqv := ⟨fun x => by rw [edist_self]; exact ENNReal.coe_lt_top, fun h => by rwa [edist_comm], fun hxy hyz => lt_of_le_of_lt (edist_triangle _ _ _) (ENNReal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ #align emetric.edist_lt_top_setoid EMetric.edistLtTopSetoid @[simp] theorem ball_zero : ball x 0 = ∅ := by rw [EMetric.ball_eq_empty_iff] #align emetric.ball_zero EMetric.ball_zero theorem nhds_basis_eball : (𝓝 x).HasBasis (fun ε : ℝ≥0∞ => 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_edist #align emetric.nhds_basis_eball EMetric.nhds_basis_eball theorem nhdsWithin_basis_eball : (𝓝[s] x).HasBasis (fun ε : ℝ≥0∞ => 0 < ε) fun ε => ball x ε ∩ s := nhdsWithin_hasBasis nhds_basis_eball s #align emetric.nhds_within_basis_eball EMetric.nhdsWithin_basis_eball theorem nhds_basis_closed_eball : (𝓝 x).HasBasis (fun ε : ℝ≥0∞ => 0 < ε) (closedBall x) := nhds_basis_uniformity uniformity_basis_edist_le #align emetric.nhds_basis_closed_eball EMetric.nhds_basis_closed_eball theorem nhdsWithin_basis_closed_eball : (𝓝[s] x).HasBasis (fun ε : ℝ≥0∞ => 0 < ε) fun ε => closedBall x ε ∩ s := nhdsWithin_hasBasis nhds_basis_closed_eball s #align emetric.nhds_within_basis_closed_eball EMetric.nhdsWithin_basis_closed_eball theorem nhds_eq : 𝓝 x = ⨅ ε > 0, 𝓟 (ball x ε) := nhds_basis_eball.eq_binfᵢ #align emetric.nhds_eq EMetric.nhds_eq theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ ε > 0, ball x ε ⊆ s := nhds_basis_eball.mem_iff #align emetric.mem_nhds_iff EMetric.mem_nhds_iff theorem mem_nhdsWithin_iff : s ∈ 𝓝[t] x ↔ ∃ ε > 0, ball x ε ∩ t ⊆ s := nhdsWithin_basis_eball.mem_iff #align emetric.mem_nhds_within_iff EMetric.mem_nhdsWithin_iff section variable [PseudoEMetricSpace β] {f : α → β} theorem tendsto_nhdsWithin_nhdsWithin {t : Set β} {a b} : Tendsto f (𝓝[s] a) (𝓝[t] b) ↔ ∀ ε > 0, ∃ δ > 0, ∀ ⦃x⦄, x ∈ s → edist x a < δ → f x ∈ t ∧ edist (f x) b < ε := (nhdsWithin_basis_eball.tendsto_iff nhdsWithin_basis_eball).trans <| forall₂_congr fun ε _ => exists_congr fun δ => and_congr_right fun _ => forall_congr' fun x => by simp; tauto #align emetric.tendsto_nhds_within_nhds_within EMetric.tendsto_nhdsWithin_nhdsWithin theorem tendsto_nhdsWithin_nhds {a b} : Tendsto f (𝓝[s] a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀ {x : α}, x ∈ s → edist x a < δ → edist (f x) b < ε := by rw [← nhdsWithin_univ b, tendsto_nhdsWithin_nhdsWithin] simp only [mem_univ, true_and_iff] #align emetric.tendsto_nhds_within_nhds EMetric.tendsto_nhdsWithin_nhds theorem tendsto_nhds_nhds {a b} : Tendsto f (𝓝 a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀ ⦃x⦄, edist x a < δ → edist (f x) b < ε := nhds_basis_eball.tendsto_iff nhds_basis_eball #align emetric.tendsto_nhds_nhds EMetric.tendsto_nhds_nhds end theorem isOpen_iff : IsOpen s ↔ ∀ x ∈ s, ∃ ε > 0, ball x ε ⊆ s := by simp [isOpen_iff_nhds, mem_nhds_iff] #align emetric.is_open_iff EMetric.isOpen_iff theorem isOpen_ball : IsOpen (ball x ε) := isOpen_iff.2 fun _ => exists_ball_subset_ball #align emetric.is_open_ball EMetric.isOpen_ball theorem isClosed_ball_top : IsClosed (ball x ⊤) := isOpen_compl_iff.1 <| isOpen_iff.2 fun _y hy => ⟨⊤, ENNReal.coe_lt_top, fun _z hzy hzx => hy (edistLtTopSetoid.trans (edistLtTopSetoid.symm hzy) hzx)⟩ #align emetric.is_closed_ball_top EMetric.isClosed_ball_top theorem ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := isOpen_ball.mem_nhds (mem_ball_self ε0) #align emetric.ball_mem_nhds EMetric.ball_mem_nhds theorem closedBall_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : closedBall x ε ∈ 𝓝 x := mem_of_superset (ball_mem_nhds x ε0) ball_subset_closedBall #align emetric.closed_ball_mem_nhds EMetric.closedBall_mem_nhds theorem ball_prod_same [PseudoEMetricSpace β] (x : α) (y : β) (r : ℝ≥0∞) : ball x r ×ˢ ball y r = ball (x, y) r := ext fun z => by simp [Prod.edist_eq] #align emetric.ball_prod_same EMetric.ball_prod_same theorem closedBall_prod_same [PseudoEMetricSpace β] (x : α) (y : β) (r : ℝ≥0∞) : closedBall x r ×ˢ closedBall y r = closedBall (x, y) r := ext fun z => by simp [Prod.edist_eq] #align emetric.closed_ball_prod_same EMetric.closedBall_prod_same /-- ε-characterization of the closure in pseudoemetric spaces -/ theorem mem_closure_iff : x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, edist x y < ε := (mem_closure_iff_nhds_basis nhds_basis_eball).trans <| by simp only [mem_ball, edist_comm x] #align emetric.mem_closure_iff EMetric.mem_closure_iff theorem tendsto_nhds {f : Filter β} {u : β → α} {a : α} : Tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε := nhds_basis_eball.tendsto_right_iff #align emetric.tendsto_nhds EMetric.tendsto_nhds theorem tendsto_atTop [Nonempty β] [SemilatticeSup β] {u : β → α} {a : α} : Tendsto u atTop (𝓝 a) ↔ ∀ ε > 0, ∃ N, ∀ n ≥ N, edist (u n) a < ε := (atTop_basis.tendsto_iff nhds_basis_eball).trans <| by simp only [exists_prop, true_and_iff, mem_Ici, mem_ball] #align emetric.tendsto_at_top EMetric.tendsto_atTop theorem inseparable_iff : Inseparable x y ↔ edist x y = 0 := by simp [inseparable_iff_mem_closure, mem_closure_iff, edist_comm, forall_lt_iff_le'] #align emetric.inseparable_iff EMetric.inseparable_iff -- see Note [nolint_ge] /-- In a pseudoemetric space, Cauchy sequences are characterized by the fact that, eventually, the pseudoedistance between its elements is arbitrarily small -/ theorem cauchySeq_iff [Nonempty β] [SemilatticeSup β] {u : β → α} : CauchySeq u ↔ ∀ ε > 0, ∃ N, ∀ m, N ≤ m → ∀ n, N ≤ n → edist (u m) (u n) < ε := uniformity_basis_edist.cauchySeq_iff #align emetric.cauchy_seq_iff EMetric.cauchySeq_iff /-- A variation around the emetric characterization of Cauchy sequences -/ theorem cauchySeq_iff' [Nonempty β] [SemilatticeSup β] {u : β → α} : CauchySeq u ↔ ∀ ε > (0 : ℝ≥0∞), ∃ N, ∀ n ≥ N, edist (u n) (u N) < ε := uniformity_basis_edist.cauchySeq_iff' #align emetric.cauchy_seq_iff' EMetric.cauchySeq_iff' /-- A variation of the emetric characterization of Cauchy sequences that deals with `ℝ≥0` upper bounds. -/ theorem cauchySeq_iff_NNReal [Nonempty β] [SemilatticeSup β] {u : β → α} : CauchySeq u ↔ ∀ ε : ℝ≥0, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε := uniformity_basis_edist_nnreal.cauchySeq_iff' #align emetric.cauchy_seq_iff_nnreal EMetric.cauchySeq_iff_NNReal theorem totallyBounded_iff {s : Set α} : TotallyBounded s ↔ ∀ ε > 0, ∃ t : Set α, t.Finite ∧ s ⊆ ⋃ y ∈ t, ball y ε := ⟨fun H _ε ε0 => H _ (edist_mem_uniformity ε0), fun H _r ru => let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru let ⟨t, ft, h⟩ := H ε ε0 ⟨t, ft, h.trans <| unionᵢ₂_mono fun _ _ _ => hε⟩⟩ #align emetric.totally_bounded_iff EMetric.totallyBounded_iff theorem totallyBounded_iff' {s : Set α} : TotallyBounded s ↔ ∀ ε > 0, ∃ t, t ⊆ s ∧ Set.Finite t ∧ s ⊆ ⋃ y ∈ t, ball y ε := ⟨fun H _ε ε0 => (totallyBounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), fun H _r ru => let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru let ⟨t, _, ft, h⟩ := H ε ε0 ⟨t, ft, h.trans <| unionᵢ₂_mono fun _ _ _ => hε⟩⟩ #align emetric.totally_bounded_iff' EMetric.totallyBounded_iff' section Compact -- porting note: todo: generalize to a uniform space with metrizable uniformity /-- For a set `s` in a pseudo emetric space, if for every `ε > 0` there exists a countable set that is `ε`-dense in `s`, then there exists a countable subset `t ⊆ s` that is dense in `s`. -/ theorem subset_countable_closure_of_almost_dense_set (s : Set α) (hs : ∀ ε > 0, ∃ t : Set α, t.Countable ∧ s ⊆ ⋃ x ∈ t, closedBall x ε) : ∃ t, t ⊆ s ∧ t.Countable ∧ s ⊆ closure t := by rcases s.eq_empty_or_nonempty with (rfl | ⟨x₀, hx₀⟩) · exact ⟨∅, empty_subset _, countable_empty, empty_subset _⟩ choose! T hTc hsT using fun n : ℕ => hs n⁻¹ (by simp) have : ∀ r x, ∃ y ∈ s, closedBall x r ∩ s ⊆ closedBall y (r * 2) := fun r x => by rcases (closedBall x r ∩ s).eq_empty_or_nonempty with (he | ⟨y, hxy, hys⟩) · refine' ⟨x₀, hx₀, _⟩ rw [he] exact empty_subset _ · refine' ⟨y, hys, fun z hz => _⟩ calc edist z y ≤ edist z x + edist y x := edist_triangle_right _ _ _ _ ≤ r + r := (add_le_add hz.1 hxy) _ = r * 2 := (mul_two r).symm choose f hfs hf using this refine' ⟨⋃ n : ℕ, f n⁻¹ '' T n, unionᵢ_subset fun n => image_subset_iff.2 fun z _ => hfs _ _, countable_unionᵢ fun n => (hTc n).image _, _⟩ refine' fun x hx => mem_closure_iff.2 fun ε ε0 => _ rcases ENNReal.exists_inv_nat_lt (ENNReal.half_pos ε0.lt.ne').ne' with ⟨n, hn⟩ rcases mem_unionᵢ₂.1 (hsT n hx) with ⟨y, hyn, hyx⟩ refine' ⟨f n⁻¹ y, mem_unionᵢ.2 ⟨n, mem_image_of_mem _ hyn⟩, _⟩ calc edist x (f n⁻¹ y) ≤ (n : ℝ≥0∞)⁻¹ * 2 := hf _ _ ⟨hyx, hx⟩ _ < ε := ENNReal.mul_lt_of_lt_div hn #align emetric.subset_countable_closure_of_almost_dense_set EMetric.subset_countable_closure_of_almost_dense_set open TopologicalSpace in /-- If a set `s` is separable, then the corresponding subtype is separable in a (pseudo extended) metric space. This is not obvious, as the countable set whose closure covers `s` does not need in general to be contained in `s`. -/ theorem _root_.TopologicalSpace.IsSeparable.separableSpace {s : Set α} (hs : IsSeparable s) : SeparableSpace s := by have : ∀ ε > 0, ∃ t : Set α, t.Countable ∧ s ⊆ ⋃ x ∈ t, closedBall x ε := fun ε ε0 => by rcases hs with ⟨t, htc, hst⟩ refine ⟨t, htc, hst.trans fun x hx => ?_⟩ rcases mem_closure_iff.1 hx ε ε0 with ⟨y, hyt, hxy⟩ exact mem_unionᵢ₂.2 ⟨y, hyt, mem_closedBall.2 hxy.le⟩ rcases subset_countable_closure_of_almost_dense_set _ this with ⟨t, hts, htc, hst⟩ lift t to Set s using hts refine ⟨⟨t, countable_of_injective_of_countable_image (Subtype.coe_injective.injOn _) htc, ?_⟩⟩ rwa [inducing_subtype_val.dense_iff, Subtype.forall] #align topological_space.is_separable.separable_space TopologicalSpace.IsSeparable.separableSpace -- porting note: todo: generalize to metrizable spaces /-- A compact set in a pseudo emetric space is separable, i.e., it is a subset of the closure of a countable set. -/ theorem subset_countable_closure_of_compact {s : Set α} (hs : IsCompact s) : ∃ t, t ⊆ s ∧ t.Countable ∧ s ⊆ closure t := by refine' subset_countable_closure_of_almost_dense_set s fun ε hε => _ rcases totallyBounded_iff'.1 hs.totallyBounded ε hε with ⟨t, -, htf, hst⟩ exact ⟨t, htf.countable, hst.trans <| unionᵢ₂_mono fun _ _ => ball_subset_closedBall⟩ #align emetric.subset_countable_closure_of_compact EMetric.subset_countable_closure_of_compact end Compact section SecondCountable open TopologicalSpace variable (α) /-- A sigma compact pseudo emetric space has second countable topology. This is not an instance to avoid a loop with `sigmaCompactSpace_of_locally_compact_second_countable`. -/ theorem secondCountable_of_sigmaCompact [SigmaCompactSpace α] : SecondCountableTopology α := by suffices SeparableSpace α by exact UniformSpace.secondCountable_of_separable α choose T _ hTc hsubT using fun n => subset_countable_closure_of_compact (isCompact_compactCovering α n) refine' ⟨⟨⋃ n, T n, countable_unionᵢ hTc, fun x => _⟩⟩ rcases unionᵢ_eq_univ_iff.1 (unionᵢ_compactCovering α) x with ⟨n, hn⟩ exact closure_mono (subset_unionᵢ _ n) (hsubT _ hn) #align emetric.second_countable_of_sigma_compact EMetric.secondCountable_of_sigmaCompact variable {α} theorem secondCountable_of_almost_dense_set (hs : ∀ ε > 0, ∃ t : Set α, t.Countable ∧ (⋃ x ∈ t, closedBall x ε) = univ) : SecondCountableTopology α := by suffices SeparableSpace α from UniformSpace.secondCountable_of_separable α have : ∀ ε > 0, ∃ t : Set α, Set.Countable t ∧ univ ⊆ ⋃ x ∈ t, closedBall x ε · simpa only [univ_subset_iff] using hs rcases subset_countable_closure_of_almost_dense_set (univ : Set α) this with ⟨t, -, htc, ht⟩ exact ⟨⟨t, htc, fun x => ht (mem_univ x)⟩⟩ #align emetric.second_countable_of_almost_dense_set EMetric.secondCountable_of_almost_dense_set end SecondCountable section Diam /-- The diameter of a set in a pseudoemetric space, named `EMetric.diam` -/ noncomputable def diam (s : Set α) := ⨆ (x ∈ s) (y ∈ s), edist x y #align emetric.diam EMetric.diam theorem diam_eq_supₛ (s : Set α) : diam s = supₛ (image2 edist s s) := supₛ_image2.symm theorem diam_le_iff {d : ℝ≥0∞} : diam s ≤ d ↔ ∀ x ∈ s, ∀ y ∈ s, edist x y ≤ d := by simp only [diam, supᵢ_le_iff] #align emetric.diam_le_iff EMetric.diam_le_iff theorem diam_image_le_iff {d : ℝ≥0∞} {f : β → α} {s : Set β} : diam (f '' s) ≤ d ↔ ∀ x ∈ s, ∀ y ∈ s, edist (f x) (f y) ≤ d := by simp only [diam_le_iff, ball_image_iff] #align emetric.diam_image_le_iff EMetric.diam_image_le_iff theorem edist_le_of_diam_le {d} (hx : x ∈ s) (hy : y ∈ s) (hd : diam s ≤ d) : edist x y ≤ d := diam_le_iff.1 hd x hx y hy #align emetric.edist_le_of_diam_le EMetric.edist_le_of_diam_le /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ theorem edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := edist_le_of_diam_le hx hy le_rfl #align emetric.edist_le_diam_of_mem EMetric.edist_le_diam_of_mem /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ theorem diam_le {d : ℝ≥0∞} (h : ∀ x ∈ s, ∀ y ∈ s, edist x y ≤ d) : diam s ≤ d := diam_le_iff.2 h #align emetric.diam_le EMetric.diam_le /-- The diameter of a subsingleton vanishes. -/ theorem diam_subsingleton (hs : s.Subsingleton) : diam s = 0 := nonpos_iff_eq_zero.1 <| diam_le fun _x hx y hy => (hs hx hy).symm ▸ edist_self y ▸ le_rfl #align emetric.diam_subsingleton EMetric.diam_subsingleton /-- The diameter of the empty set vanishes -/ @[simp] theorem diam_empty : diam (∅ : Set α) = 0 := diam_subsingleton subsingleton_empty #align emetric.diam_empty EMetric.diam_empty /-- The diameter of a singleton vanishes -/ @[simp] theorem diam_singleton : diam ({x} : Set α) = 0 := diam_subsingleton subsingleton_singleton #align emetric.diam_singleton EMetric.diam_singleton theorem diam_unionᵢ_mem_option {ι : Type _} (o : Option ι) (s : ι → Set α) : diam (⋃ i ∈ o, s i) = ⨆ i ∈ o, diam (s i) := by cases o <;> simp #align emetric.diam_Union_mem_option EMetric.diam_unionᵢ_mem_option theorem diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) := eq_of_forall_ge_iff fun d => by simp only [diam_le_iff, ball_insert_iff, edist_self, edist_comm x, max_le_iff, supᵢ_le_iff, zero_le, true_and_iff, forall_and, and_self_iff, ← and_assoc] #align emetric.diam_insert EMetric.diam_insert theorem diam_pair : diam ({x, y} : Set α) = edist x y := by simp only [supᵢ_singleton, diam_insert, diam_singleton, ENNReal.max_zero_right] #align emetric.diam_pair EMetric.diam_pair theorem diam_triple : diam ({x, y, z} : Set α) = max (max (edist x y) (edist x z)) (edist y z) := by simp only [diam_insert, supᵢ_insert, supᵢ_singleton, diam_singleton, ENNReal.max_zero_right, ENNReal.sup_eq_max] #align emetric.diam_triple EMetric.diam_triple /-- The diameter is monotonous with respect to inclusion -/ theorem diam_mono {s t : Set α} (h : s ⊆ t) : diam s ≤ diam t := diam_le fun _x hx _y hy => edist_le_diam_of_mem (h hx) (h hy) #align emetric.diam_mono EMetric.diam_mono /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ theorem diam_union {t : Set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := by have A : ∀ a ∈ s, ∀ b ∈ t, edist a b ≤ diam s + edist x y + diam t := fun a ha b hb => calc edist a b ≤ edist a x + edist x y + edist y b := edist_triangle4 _ _ _ _ _ ≤ diam s + edist x y + diam t := add_le_add (add_le_add (edist_le_diam_of_mem ha xs) le_rfl) (edist_le_diam_of_mem yt hb) refine' diam_le fun a ha b hb => _ cases' (mem_union _ _ _).1 ha with h'a h'a <;> cases' (mem_union _ _ _).1 hb with h'b h'b · calc edist a b ≤ diam s := edist_le_diam_of_mem h'a h'b _ ≤ diam s + (edist x y + diam t) := le_self_add _ = diam s + edist x y + diam t := (add_assoc _ _ _).symm · exact A a h'a b h'b · have Z := A b h'b a h'a rwa [edist_comm] at Z · calc edist a b ≤ diam t := edist_le_diam_of_mem h'a h'b _ ≤ diam s + edist x y + diam t := le_add_self #align emetric.diam_union EMetric.diam_union theorem diam_union' {t : Set α} (h : (s ∩ t).Nonempty) : diam (s ∪ t) ≤ diam s + diam t := by let ⟨x, ⟨xs, xt⟩⟩ := h simpa using diam_union xs xt #align emetric.diam_union' EMetric.diam_union' theorem diam_closedBall {r : ℝ≥0∞} : diam (closedBall x r) ≤ 2 * r := diam_le fun a ha b hb => calc edist a b ≤ edist a x + edist b x := edist_triangle_right _ _ _ _ ≤ r + r := (add_le_add ha hb) _ = 2 * r := (two_mul r).symm #align emetric.diam_closed_ball EMetric.diam_closedBall theorem diam_ball {r : ℝ≥0∞} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closedBall) diam_closedBall #align emetric.diam_ball EMetric.diam_ball theorem diam_pi_le_of_le {π : β → Type _} [Fintype β] [∀ b, PseudoEMetricSpace (π b)] {s : ∀ b : β, Set (π b)} {c : ℝ≥0∞} (h : ∀ b, diam (s b) ≤ c) : diam (Set.pi univ s) ≤ c := by refine diam_le fun x hx y hy => edist_pi_le_iff.mpr ?_ rw [mem_univ_pi] at hx hy exact fun b => diam_le_iff.1 (h b) (x b) (hx b) (y b) (hy b) #align emetric.diam_pi_le_of_le EMetric.diam_pi_le_of_le end Diam end EMetric --namespace /-- We now define `EMetricSpace`, extending `PseudoEMetricSpace`. -/ class EMetricSpace (α : Type u) extends PseudoEMetricSpace α : Type u where eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y #align emetric_space EMetricSpace variable {γ : Type w} [EMetricSpace γ] export EMetricSpace (eq_of_edist_eq_zero) /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : γ} : edist x y = 0 ↔ x = y := ⟨eq_of_edist_eq_zero, fun h => h ▸ edist_self _⟩ #align edist_eq_zero edist_eq_zero @[simp] theorem zero_eq_edist {x y : γ} : 0 = edist x y ↔ x = y := eq_comm.trans edist_eq_zero #align zero_eq_edist zero_eq_edist theorem edist_le_zero {x y : γ} : edist x y ≤ 0 ↔ x = y := nonpos_iff_eq_zero.trans edist_eq_zero #align edist_le_zero edist_le_zero @[simp] theorem edist_pos {x y : γ} : 0 < edist x y ↔ x ≠ y := by simp [← not_le] #align edist_pos edist_pos /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : γ} (h : ∀ ε > 0, edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) #align eq_of_forall_edist_le eq_of_forall_edist_le -- see Note [lower instance priority] /-- An emetric space is separated -/ instance (priority := 100) to_separated : SeparatedSpace γ := separated_def.2 fun _ _ h => eq_of_forall_edist_le fun _ ε0 => le_of_lt (h _ (edist_mem_uniformity ε0)) #align to_separated to_separated /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem EMetric.uniformEmbedding_iff' [EMetricSpace β] {f : γ → β} : UniformEmbedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, edist a b < δ → edist (f a) (f b) < ε) ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, edist (f a) (f b) < ε → edist a b < δ := by rw [uniformEmbedding_iff_uniformInducing, uniformInducing_iff, uniformContinuous_iff] #align emetric.uniform_embedding_iff' EMetric.uniformEmbedding_iff' /-- If a `PseudoEMetricSpace` is a T₀ space, then it is an `EMetricSpace`. -/ @[reducible] -- porting note: made `reducible`; todo: make it an instance? def EMetricSpace.ofT0PseudoEMetricSpace (α : Type _) [PseudoEMetricSpace α] [T0Space α] : EMetricSpace α := { ‹PseudoEMetricSpace α› with eq_of_edist_eq_zero := fun h => (EMetric.inseparable_iff.2 h).eq } #align emetric_space.of_t0_pseudo_emetric_space EMetricSpace.ofT0PseudoEMetricSpace /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def EMetricSpace.replaceUniformity {γ} [U : UniformSpace γ] (m : EMetricSpace γ) (H : 𝓤[U] = 𝓤[PseudoEMetricSpace.toUniformSpace]) : EMetricSpace γ where edist := @edist _ m.toEDist edist_self := edist_self eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _ edist_comm := edist_comm edist_triangle := edist_triangle toUniformSpace := U uniformity_edist := H.trans (@PseudoEMetricSpace.uniformity_edist γ _) #align emetric_space.replace_uniformity EMetricSpace.replaceUniformity /-- The extended metric induced by an injective function taking values in a emetric space. -/ def EMetricSpace.induced {γ β} (f : γ → β) (hf : Function.Injective f) (m : EMetricSpace β) : EMetricSpace γ := { PseudoEMetricSpace.induced f m.toPseudoEMetricSpace with eq_of_edist_eq_zero := fun h => hf (edist_eq_zero.1 h) } #align emetric_space.induced EMetricSpace.induced /-- EMetric space instance on subsets of emetric spaces -/ instance {α : Type _} {p : α → Prop} [EMetricSpace α] : EMetricSpace (Subtype p) := EMetricSpace.induced Subtype.val Subtype.coe_injective ‹_› /-- EMetric space instance on the multiplicative opposite of an emetric space. -/ @[to_additive "EMetric space instance on the additive opposite of an emetric space."] instance {α : Type _} [EMetricSpace α] : EMetricSpace αᵐᵒᵖ := EMetricSpace.induced MulOpposite.unop MulOpposite.unop_injective ‹_› instance {α : Type _} [EMetricSpace α] : EMetricSpace (ULift α) := EMetricSpace.induced ULift.down ULift.down_injective ‹_› /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance Prod.emetricSpaceMax [EMetricSpace β] : EMetricSpace (γ × β) := .ofT0PseudoEMetricSpace _ #align prod.emetric_space_max Prod.emetricSpaceMax /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 γ = ⨅ ε > 0, 𝓟 { p : γ × γ | edist p.1 p.2 < ε } := PseudoEMetricSpace.uniformity_edist #align uniformity_edist uniformity_edist section Pi open Finset variable {π : β → Type _} [Fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetricSpacePi [∀ b, EMetricSpace (π b)] : EMetricSpace (∀ b, π b) := .ofT0PseudoEMetricSpace _ #align emetric_space_pi emetricSpacePi end Pi namespace EMetric /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set. -/ theorem countable_closure_of_compact {s : Set γ} (hs : IsCompact s) : ∃ t, t ⊆ s ∧ t.Countable ∧ s = closure t := by rcases subset_countable_closure_of_compact hs with ⟨t, hts, htc, hsub⟩ exact ⟨t, hts, htc, hsub.antisymm (closure_minimal hts hs.isClosed)⟩ #align emetric.countable_closure_of_compact EMetric.countable_closure_of_compact section Diam variable {s : Set γ} theorem diam_eq_zero_iff : diam s = 0 ↔ s.Subsingleton := ⟨fun h _x hx _y hy => edist_le_zero.1 <| h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩ #align emetric.diam_eq_zero_iff EMetric.diam_eq_zero_iff theorem diam_pos_iff : 0 < diam s ↔ s.Nontrivial := by simp only [pos_iff_ne_zero, Ne.def, diam_eq_zero_iff, Set.not_subsingleton_iff] theorem diam_pos_iff' : 0 < diam s ↔ ∃ x ∈ s, ∃ y ∈ s, x ≠ y := by simp only [diam_pos_iff, Set.Nontrivial, exists_prop] #align emetric.diam_pos_iff EMetric.diam_pos_iff' end Diam end EMetric /-! ### Separation quotient -/ instance [PseudoEMetricSpace X] : EDist (UniformSpace.SeparationQuotient X) where edist x y := Quotient.liftOn₂' x y edist fun x y x' y' hx hy => calc edist x y = edist x' y := edist_congr_right $ EMetric.inseparable_iff.1 <| separationRel_iff_inseparable.1 hx _ = edist x' y' := edist_congr_left $ EMetric.inseparable_iff.1 <| separationRel_iff_inseparable.1 hy @[simp] theorem UniformSpace.SeparationQuotient.edist_mk [PseudoEMetricSpace X] (x y : X) : @edist (UniformSpace.SeparationQuotient X) _ (Quot.mk _ x) (Quot.mk _ y) = edist x y := rfl #align uniform_space.separation_quotient.edist_mk UniformSpace.SeparationQuotient.edist_mk instance [PseudoEMetricSpace X] : EMetricSpace (UniformSpace.SeparationQuotient X) := @EMetricSpace.ofT0PseudoEMetricSpace (UniformSpace.SeparationQuotient X) { edist_self := fun x => Quotient.inductionOn' x edist_self, edist_comm := fun x y => Quotient.inductionOn₂' x y edist_comm, edist_triangle := fun x y z => Quotient.inductionOn₃' x y z edist_triangle, toUniformSpace := inferInstance, uniformity_edist := (uniformity_basis_edist.map _).eq_binfᵢ.trans $ infᵢ_congr $ fun ε => infᵢ_congr $ fun _ => congr_arg 𝓟 <| by ext ⟨⟨x⟩, ⟨y⟩⟩ refine ⟨?_, fun h => ⟨(x, y), h, rfl⟩⟩ rintro ⟨⟨x', y'⟩, h', h⟩ simp only [Prod.ext_iff] at h rwa [← h.1, ← h.2] } _ /-! ### `Additive`, `Multiplicative` The distance on those type synonyms is inherited without change. -/ open Additive Multiplicative section variable [EDist X] instance : EDist (Additive X) := ‹EDist X› instance : EDist (Multiplicative X) := ‹EDist X› @[simp] theorem edist_ofMul (a b : X) : edist (ofMul a) (ofMul b) = edist a b := rfl #align edist_of_mul edist_ofMul @[simp] theorem edist_ofAdd (a b : X) : edist (ofAdd a) (ofAdd b) = edist a b := rfl #align edist_of_add edist_ofAdd @[simp] theorem edist_toMul (a b : Additive X) : edist (toMul a) (toMul b) = edist a b := rfl #align edist_to_mul edist_toMul @[simp] theorem edist_toAdd (a b : Multiplicative X) : edist (toAdd a) (toAdd b) = edist a b := rfl #align edist_to_add edist_toAdd end instance [PseudoEMetricSpace X] : PseudoEMetricSpace (Additive X) := ‹PseudoEMetricSpace X› instance [PseudoEMetricSpace X] : PseudoEMetricSpace (Multiplicative X) := ‹PseudoEMetricSpace X› instance [EMetricSpace X] : EMetricSpace (Additive X) := ‹EMetricSpace X› instance [EMetricSpace X] : EMetricSpace (Multiplicative X) := ‹EMetricSpace X› /-! ### Order dual The distance on this type synonym is inherited without change. -/ open OrderDual section variable [EDist X] instance : EDist Xᵒᵈ := ‹EDist X› @[simp] theorem edist_toDual (a b : X) : edist (toDual a) (toDual b) = edist a b := rfl #align edist_to_dual edist_toDual @[simp] theorem edist_ofDual (a b : Xᵒᵈ) : edist (ofDual a) (ofDual b) = edist a b := rfl #align edist_of_dual edist_ofDual end instance [PseudoEMetricSpace X] : PseudoEMetricSpace Xᵒᵈ := ‹PseudoEMetricSpace X› instance [EMetricSpace X] : EMetricSpace Xᵒᵈ := ‹EMetricSpace X›
From hahn Require Import Hahn. From Coq Require Import Lia. Require Import Events. Set Implicit Arguments. (******************************************************************************) (** ** Inserting into relation *) (******************************************************************************) (** Update a partial order [r] by insert [b] right after [a]. *) Definition into_rel A (r : relation A) (a b : A) := fun e e' => r e e' \/ r e a /\ e' = b \/ e = a /\ e' = b \/ e = b /\ r a e'. Lemma into_rel_trans A (r : relation A) a b (TR_r : transitive r) (IRR_r : irreflexive r) (Nrxb : forall x, ~ r x b) (Nrbx : forall x, ~ r b x) : transitive (into_rel r a b). Proof. unfold transitive, not, into_rel in *; ins; desf; eauto 8. all: solve [exfalso; eauto]. Qed. Lemma into_rel_irr A (r : relation A) a b (IRR_r : irreflexive r) (Nrxb : forall x, ~ r x b) (Nrbx : forall x, ~ r b x) (Nab : a <> b) : irreflexive (into_rel r a b). Proof. intros x; unfold not, into_rel in *; ins; desf; eauto. Qed. Add Parametric Morphism A : (@into_rel A) with signature inclusion ==> eq ==> eq ==> inclusion as into_rel_mori. Proof. unfold into_rel; unfolder; ins; desf; eauto 8. Qed. Add Parametric Morphism A : (@into_rel A) with signature same_relation ==> eq ==> eq ==> same_relation as into_rel_more. Proof. unfold same_relation; intuition; auto using into_rel_mori. Qed. (******************************************************************************) (** ** Other lemmas *) (******************************************************************************) Lemma total_order_from_list_filterP A l (P : A -> Prop): total_order_from_list (filterP P l) ≡ ⦗P⦘ ⨾ total_order_from_list l ⨾ ⦗P⦘. Proof. induction l as [ | a l]; unfolder in *; split; ins; desf. all: try solve [forward eapply total_order_from_list_in1; eauto; ins]. all: rewrite total_order_from_list_cons in *; desf. all: try rewrite in_filterP_iff in *; desf; eauto. all: apply IHl in H; desf; eauto. Qed. Lemma total_order_from_list_total A (l : list A) : is_total (fun x => In x l) (total_order_from_list l). Proof. elim l; [basic_solver|intros ?? IHl ? IN1 ? IN2 NE; ins; desf]. 3: apply (IHl _ IN1 _ IN2) in NE; desf. all: by left+right; apply total_order_from_list_cons; eauto. Qed. Lemma total_order_from_list_cons_max A (l : list A) x y (ND : NoDup (y :: l)) : ~ total_order_from_list (y :: l) x y. Proof. intro T; apply total_order_from_list_cons in T; apply nodup_cons in ND; desf. by apply total_order_from_list_in2 in T. Qed. Lemma length_filterP A l (P : A -> Prop) : length (filterP P l) <= length l. Proof. induction l; ins; destruct (excluded_middle_informative _); ins; lia. Qed. Lemma total_sub A (ord1 ord2 : relation A) D (T2 : is_total D ord2) (IRR1 : irreflexive ord1) (ordD : <|D|> ;; ord1 ∩ (ord2⁻¹) ;; <|D|> ≡ ∅₂): restr_rel D ord1 ⊆ restr_rel D ord2. Proof. intros x y [ORD [Dx Dy]]. destruct (T2 _ Dx _ Dy); [|basic_solver|]. { by intro; desf; apply IRR1 in ORD. } exfalso; eapply ordD with (x := x) (y := y); basic_solver. Qed. Lemma total_eqv A (ord1 ord2 : relation A) D (T1 : is_total D ord1) (T2 : is_total D ord2) (IRR1 : irreflexive ord1) (IRR2 : irreflexive ord2) (ordD : <|D|> ;; ord1 ∩ (ord2⁻¹) ;; <|D|> ≡ ∅₂): restr_rel D ord1 ≡ restr_rel D ord2. Proof. split; apply total_sub; auto. generalize ordD. unfolder. firstorder. Qed. Lemma total_transp A (ord : relation A) D: is_total D ord <-> is_total D ord⁻¹. Proof. firstorder. Qed. Lemma n_is_w : is_r ≡₁ set_compl is_w. Proof using. unfolder; split; intro e; ins; by destruct e as [[]|??[]]. Qed. Lemma n_is_r : is_w ≡₁ set_compl is_r. Proof using. unfolder; split; intro e; ins; by destruct e as [[]|??[]]. Qed. Lemma wf_ext_sb : well_founded ext_sb. Proof. apply Wf_nat.well_founded_lt_compat with (f := fun e => match e with | InitEvent _ => 0 | _ => S (index e) end). intros x y SB; destruct x, y; ins; lia. Qed. Inductive Revisit := | RV : Event -> Revisit | NR : Revisit. Lemma ct_step_ct A (r : relation A) : r⁺ ≡ r ;; r⁺ ∪ r. Proof using. split; intros ?? R. { apply clos_trans_t1n in R; destruct R; vauto. apply clos_t1n_trans in R; vauto. } apply clos_t1n_trans; destruct R as [R|R]; vauto. destruct R as [? R]; desf; apply clos_trans_t1n in R0; vauto. Qed. Lemma codom_seq A (r1 r2 : relation A) : codom_rel (r1 ;; r2) ≡₁ codom_rel (<|codom_rel r1|> ;; r2). Proof using. basic_solver. Qed. Lemma not_finite A (P : A -> Prop) (NFIN : ~ exists s, P ⊆₁ (fun x => In x s)): forall k : nat, exists s, << NDs : NoDup s >> /\ << LENs : length s = k >> /\ << SUBs : (fun x => In x s) ⊆₁ P >>. Proof. ins; induction k. { exists nil; basic_solver. } desf. tertium_non_datur (P \₁ (fun x => In x s) ≡₁ ∅) as [F|F]. { destruct NFIN; exists s. by apply set_subsetE. } exists (n :: s); splits; eauto. { apply nodup_cons; generalize F; basic_solver. } generalize SUBs F. basic_solver. Qed. Lemma transp_imm A (r : relation A) : immediate r⁻¹ ≡ (immediate r)⁻¹. Proof. rewrite ?immediateE, <-transp_seq. basic_solver. Qed. Lemma acyclic_transp A (r : relation A) : acyclic r -> acyclic r⁻¹. Proof. intros AC; intros ? R. by apply transp_ct, AC in R. Qed. Lemma pow_transp A (r : relation A) k : r⁻¹^^k ≡ r^^k⁻¹. Proof. induction k; [firstorder|]. rewrite pow_S_begin; ins. by rewrite transp_seq, IHk. Qed.
[STATEMENT] lemma mult_lcm_right: "lcm a b * c = lcm (a * c) (b * c) * unit_factor c" [PROOF STATE] proof (prove) goal (1 subgoal): 1. lcm a b * c = lcm (a * c) (b * c) * unit_factor c [PROOF STEP] using mult_lcm_left [of c a b] [PROOF STATE] proof (prove) using this: c * lcm a b = unit_factor c * lcm (c * a) (c * b) goal (1 subgoal): 1. lcm a b * c = lcm (a * c) (b * c) * unit_factor c [PROOF STEP] by (simp add: ac_simps)
#ifndef AMICI_MISC_H #define AMICI_MISC_H #include "amici/defines.h" #include <sunmatrix/sunmatrix_sparse.h> // SUNMatrixContent_Sparse #include <algorithm> #include <vector> #include <memory> #include <regex> #include <gsl/gsl-lite.hpp> namespace amici { /** * @brief creates a slice from existing data * * @param data to be sliced * @param index slice index * @param size slice size * @return span of the slice */ gsl::span<realtype> slice(std::vector<realtype> &data, int index, unsigned size); /** * @brief Remove parameter scaling according to the parameter scaling in pscale * * All vectors must be of same length. * * @param bufferScaled scaled parameters * @param pscale parameter scaling * @param bufferUnscaled unscaled parameters are written to the array */ void unscaleParameters(gsl::span<const realtype> bufferScaled, gsl::span<const ParameterScaling> pscale, gsl::span<realtype> bufferUnscaled); /** * @brief Remove parameter scaling according to `scaling` * * @param scaledParameter scaled parameter * @param scaling parameter scaling * * @return Unscaled parameter */ double getUnscaledParameter(double scaledParameter, ParameterScaling scaling); /** * @brief Apply parameter scaling according to `scaling` * @param unscaledParameter * @param scaling parameter scaling * @return Scaled parameter */ double getScaledParameter(double unscaledParameter, ParameterScaling scaling); /** * @brief Apply parameter scaling according to `scaling` * @param bufferUnscaled * @param pscale parameter scaling * @param bufferScaled destination */ void scaleParameters(gsl::span<const realtype> bufferUnscaled, gsl::span<const ParameterScaling> pscale, gsl::span<realtype> bufferScaled); /** * @brief Returns the current backtrace as std::string * @param maxFrames Number of frames to include * @return Backtrace */ std::string backtraceString(int maxFrames); /** * @brief Convert std::regex_constants::error_type to string * @param err_type error type * @return Error type as string */ std::string regexErrorToString(std::regex_constants::error_type err_type); /** * @brief Format printf-style arguments to std::string * @param fmt Format string * @param ap Argument list pointer * @return Formatted String */ std::string printfToString(const char *fmt, va_list ap); } // namespace amici #ifndef __cpp_lib_make_unique // custom make_unique while we are still using c++11 namespace std { template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } } #endif #endif // AMICI_MISC_H
\documentclass[letterpaper]{article} \usepackage{fullpage} \usepackage{nopageno} \usepackage{amsmath} \usepackage{amssymb} \allowdisplaybreaks \newcommand{\abs}[1]{\left\lvert #1 \right\rvert} \begin{document} \title{Notes} \date{November 3, 2014} \maketitle \section*{Section 4.1: 3, 5(d), 6, 19.} \subsection*{3} $f(x)=x^{3}+x^2-2x+1\to f(x)=q(x)(x-1)+f(1)$ \subsection*{5d} $x^3+2x+3;c=2;F=\mathbb{Z}_5$ \begin{align*} x^3+2x+3&=q(x)(x-c)+f(c)\\ &=q(x)(x-2)+f(2)\\ &=q(x)(x-2)+8+4+3\\ &=q(x)(x-2) \end{align*} \begin{align*} 2&|1\quad0\quad2\quad 3\\ &\vdots\quad2\quad4\quad 2\\ \hline &1\quad2\quad1\quad0 \end{align*} \subsection*{6} everything but zero is a root from 1.4.11 \begin{align*} a^{\varphi(n)}\equiv1\mod n \end{align*} for $(a,n)=1$ if $n$ is print and $(a,p)=1$ then $a^{p-1}\equiv 1\mod p$ that is $a^{p-1}=1$ in $\mathbb{Z}_p$. and $x(x^{p-1}-1)=x^p-x$ has a zero for all elements in $\mathbb{Z}_p$ corollary $p$ is prime means that $a^p\equiv a\mod p$ (1.4.12) \section*{4.2} theorem 4.2.1 $f(x)=q(x)g(x)+r(x)$ where $\deg r<\deg g$ or $\deg r=0$ proof, if $\deg f<\deg g$ then $q=0, r=f$ now assume $\deg f\ge \deg g$. easily see that if $\deg f=0$ is true now assume that $\deg f=m$ and $\deg g=$. \subsection*{4.2.2} $I$ is an {\bfseries ideal} of $F[x]$ notation $I=d(x)K[x]=(d(x))$ where the last one is ideal notation \end{document}
module Client.Action.Init import Client.Skeleton.Skeleton import Data.List import Fmt import Inigo.Async.Base import Inigo.Async.FS import Inigo.Async.Promise import Inigo.Template import System.Path export init : String -> -- template String -> -- package namespace String -> -- package name Promise () init tmplFile packageNS packageName = do tmplInp <- fs_readFile tmplFile tmpl <- liftEither $ runTemplate packageNS packageName tmplFile tmplInp ignore $ all $ map writeTmplFile tmpl log (fmt "Successfully built %s" tmplFile) where ensureParent : String -> Promise () ensureParent path = case parent path of Just parentPath => unless (parentPath == "") $ fs_mkdir True parentPath Nothing => pure () writeTmplFile : (String, String) -> Promise () writeTmplFile (path, contents) = do ensureParent path fs_writeFile path contents
Section pbc. Variable phi: Prop. Axiom lem: phi \/ ~phi. Hypothesis H: ~phi -> False. Lemma pbc: phi. Proof. pose proof lem. destruct H0. - assumption. - apply H in H0. contradiction. Qed. Lemma pbc2: phi. Proof. pose proof lem. destruct H0. - assumption. - apply False_ind. apply H. assumption. Qed. End pbc.
Require Import isla.isla. Require Import isla.aarch64.aarch64. Require Export isla.instructions.binary_search.a4. Lemma a4_spec `{!islaG Σ} `{!threadG} pc: instr pc (Some a4) -∗ instr_body pc (stp_uninit_spec pc "R24" "R23" "SP_EL2" (16) false). Proof. iStartProof. repeat liAStep; liShow. Unshelve. all: prepare_sidecond. all: bv_solve. Qed. Definition a4_spec_inst `{!islaG Σ} `{!threadG} pc := entails_to_simplify_hyp 0 (a4_spec pc). Global Existing Instance a4_spec_inst.
Our training include practical and theory. Mining machines practicals are done straight in.the mining ground. Carpentry, Brick laying, Plumbing, Electrical engineering,Burglar proofs and Gates installation. Contact us for any operators and welding course that may not be mentioned above.No company bits our lowest course fees call us @ 0784722212 for fees inquiries about any course you want to train. Also get a free forklift training if you train any course with our company. NB please you can check on google to confirm our company registration and Accreditation.
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} module Lib where -- ( someFunc -- ) where import Statistics.Distribution (probability) import Statistics.Distribution.Binomial (binomial) import Data.List import qualified Data.Map.Strict as Map import qualified Data.Text.Lazy as TL import Web.Scotty as S import Text.Blaze.Html5 as H import Text.Blaze.Html5.Attributes as A import Text.Blaze.Html.Renderer.Pretty import Text.Blaze.Internal (customAttribute) import Network.Wai.Middleware.Static import Data.Aeson import GHC.Generics import Views (indexPage) someFunc :: IO () someFunc = scotty 5000 $ do middleware $ staticPolicy (noDots >-> addBase "Static") get "/" indexPage post "/data" postRoute postRoute :: ActionM () postRoute = do shippy <- S.body maybeShip shippy maybeShip param = let shippy = decode param :: Maybe Parameters in case (shippy) of (Just fleet) -> S.json $ calcFleet fleet Nothing -> S.json $ calcFleet testParam data ShipPart = Empty | IonCannon | ElectronComputer | Hull | NuclearDrive | NuclearSource | PlasmaCannon | AntimatterCannon | PlasmaMissile | PositronComputer | GluonComputer | GaussShield | PhaseShield | ImprovedHull | FusionDrive | TachyonDrive | FusionSource | TachyonSource deriving (Show, Generic) instance ToJSON ShipPart instance FromJSON ShipPart data Parameters = Parameters {ships :: [([ShipPart], Count)], enemyShield :: Count} deriving (Show, Generic) instance ToJSON Parameters instance FromJSON Parameters partsToShip :: [ShipPart] -> Ship partsToShip xs = foldr (\x acc -> sumShips acc (partToShip x)) (Ship 0 0 0 0 0) xs where sumShips (Ship i p a c m) (Ship i' p' a' c' m') = Ship {ions = i + i' , plasmas = p + p' , antis = a + a' , computers = c + c' , missiles = m + m'} partToShip :: ShipPart -> Ship partToShip IonCannon = Ship 1 0 0 0 0 partToShip ElectronComputer = Ship 0 0 0 1 0 partToShip PlasmaCannon = Ship 0 1 0 0 0 partToShip AntimatterCannon = Ship 0 0 1 0 0 partToShip PlasmaMissile = Ship 0 0 0 0 1 partToShip PositronComputer = Ship 0 0 0 2 0 partToShip GluonComputer = Ship 0 0 0 3 0 partToShip _ = Ship 0 0 0 0 0 type Damage = Int type Dices = Int type ToHit = Int type Count = Int type Percentage = Double type ResMap = Map.Map Int Percentage data Probability = Prob [(Damage, Percentage)] deriving Show data Hits = Hits [(Count, Percentage)] deriving Show type Damages = [(Damage, Percentage)] data Results = Results {labels :: [Damage], probs:: [Percentage], mprobs :: [Percentage]} deriving (Show, Generic) instance ToJSON Results instance FromJSON Results testParam :: Parameters testParam = Parameters {ships = [([IonCannon, IonCannon, ElectronComputer, Empty], 2), ([IonCannon, PlasmaCannon, Hull, Empty], 1)] , enemyShield = 0} data Ship = Ship {ions :: Count, plasmas :: Count, antis :: Count, computers:: ToHit, missiles :: Count} deriving (Generic, Show) instance ToJSON Ship instance FromJSON Ship type EnemyShields = Count calcHits :: Dices -> ToHit -> Hits calcHits k hit | k < 1 || hit < 1 || hit > 6 = Hits [] | otherwise = Hits $ fmap (\x -> (x, probability binom x)) [0..k] where binom = binomial k p p = if hit <= 2 then fromIntegral 5 /6 else fromIntegral (6 - hit + 1) / 6 calcDmgs :: Ship -> EnemyShields -> Damages calcDmgs ship shield = combineDmgs [ionDmg,plasmaDmg,antiDmg] where ionDmg = hitsToDmgs 1 $ calcHits (ions ship) toHit plasmaDmg = hitsToDmgs 2 $ calcHits (plasmas ship) toHit antiDmg = hitsToDmgs 4 $ calcHits (antis ship) toHit toHit | shield - (computers ship) > 0 = 6 | otherwise = 6 - (computers ship) + shield calcMissiles :: Ship -> EnemyShields -> Damages calcMissiles ship shield = hitsToDmgs 2 $ calcHits (missiles ship * 2) toHit where toHit | shield - (computers ship) > 0 = 6 | otherwise = 6 - (computers ship) + shield hitsToDmgs :: Damage -> Hits -> Damages hitsToDmgs d (Hits xs) = fmap (\x -> (fst x * d, snd x)) xs combineDmgs :: [Damages] -> Damages combineDmgs [] = [] combineDmgs dmgs = foldr1 combine dmgs where combine xs [] = xs combine [] ys = ys combine xs ys = func <$> xs <*> ys func = \x y -> (fst x + (fst y), snd x * (snd y)) sortMerge :: Damages -> ResMap sortMerge xs = foldr helper startMap xs where largest = foldr (\x acc -> if fst x > acc then fst x else acc) 0 xs startMap = Map.fromList [(k, 0::Percentage) | k<-[0..largest]] helper x acc = Map.insertWith (+) (fst x) (snd x) acc calcFleet :: Parameters -> Results calcFleet (Parameters fleet shields) = Results {labels = labels', probs = probs', mprobs = mprobs'} where mergedShips = uncurry mergeShip <$> fmap (\x -> (partsToShip (fst x), snd x)) fleet cannonsDmgs = flip calcDmgs shields <$> mergedShips missileDmgs = flip calcMissiles shields <$> mergedShips otherDmgs = sortMerge $ combineDmgs cannonsDmgs misDmg = sortMerge $ combineDmgs missileDmgs len = Prelude.max (Map.size otherDmgs) (Map.size misDmg) labels' = [0..len - 1] probs' = Map.elems $ Map.map (*100) $ fillMap otherDmgs labels' mprobs' = Map.elems $ Map.map (*100) $ fillMap misDmg labels' mergeShip :: Ship -> Count -> Ship mergeShip ship k = Ship {ions = ions ship * k , plasmas = plasmas ship * k , antis = antis ship * k , missiles = missiles ship * k , computers = computers ship} fillMap mp l = foldr fun mp l where fun x acc = if Map.notMember x mp then Map.insert x 0 acc else acc
subroutine test(a, b) real(kind=8), intent(in), dimension(:) :: a real(kind=8), intent(out), dimension(size(a)) :: b b = a end subroutine test
#include <boost/date_time/date_duration.hpp>
State Before: α : Type u_1 inst✝ : MeasurableSpace α m✝ m : OuterMeasure α s : Set α h : ↑(trim m) s = 0 ⊢ ∃ t, s ⊆ t ∧ MeasurableSet t ∧ ↑m t = 0 State After: case intro.intro.intro α : Type u_1 inst✝ : MeasurableSpace α m✝ m : OuterMeasure α s : Set α h : ↑(trim m) s = 0 t : Set α hst : s ⊆ t ht : MeasurableSet t hm : ↑m t = ↑(trim m) s ⊢ ∃ t, s ⊆ t ∧ MeasurableSet t ∧ ↑m t = 0 Tactic: rcases exists_measurable_superset_eq_trim m s with ⟨t, hst, ht, hm⟩ State Before: case intro.intro.intro α : Type u_1 inst✝ : MeasurableSpace α m✝ m : OuterMeasure α s : Set α h : ↑(trim m) s = 0 t : Set α hst : s ⊆ t ht : MeasurableSet t hm : ↑m t = ↑(trim m) s ⊢ ∃ t, s ⊆ t ∧ MeasurableSet t ∧ ↑m t = 0 State After: no goals Tactic: exact ⟨t, hst, ht, h ▸ hm⟩
[GOAL] R L : Type u inst✝⁴ : CommRing R inst✝³ : CommRing L inst✝² : IsDomain L inst✝¹ : Algebra R L inst✝ : NoZeroSMulDivisors R L halg : IsAlgebraic R L x : L p : { x_1 // x_1 ≠ 0 ∧ ↑(Polynomial.aeval x) x_1 = 0 } := Classical.indefiniteDescription (fun x_1 => x_1 ≠ 0 ∧ ↑(Polynomial.aeval x) x_1 = 0) (_ : _root_.IsAlgebraic R x) ⊢ x ∈ {x_1 | x_1 ∈ Polynomial.roots (Polynomial.map (algebraMap R L) ↑p)} [PROOFSTEP] dsimp [GOAL] R L : Type u inst✝⁴ : CommRing R inst✝³ : CommRing L inst✝² : IsDomain L inst✝¹ : Algebra R L inst✝ : NoZeroSMulDivisors R L halg : IsAlgebraic R L x : L p : { x_1 // x_1 ≠ 0 ∧ ↑(Polynomial.aeval x) x_1 = 0 } := Classical.indefiniteDescription (fun x_1 => x_1 ≠ 0 ∧ ↑(Polynomial.aeval x) x_1 = 0) (_ : _root_.IsAlgebraic R x) ⊢ x ∈ Polynomial.roots (Polynomial.map (algebraMap R L) ↑(Classical.indefiniteDescription (fun x_1 => ¬x_1 = 0 ∧ ↑(Polynomial.aeval x) x_1 = 0) (_ : _root_.IsAlgebraic R x))) [PROOFSTEP] have h : p.1.map (algebraMap R L) ≠ 0 := by rw [Ne.def, ← Polynomial.degree_eq_bot, Polynomial.degree_map_eq_of_injective (NoZeroSMulDivisors.algebraMap_injective R L), Polynomial.degree_eq_bot] exact p.2.1 [GOAL] R L : Type u inst✝⁴ : CommRing R inst✝³ : CommRing L inst✝² : IsDomain L inst✝¹ : Algebra R L inst✝ : NoZeroSMulDivisors R L halg : IsAlgebraic R L x : L p : { x_1 // x_1 ≠ 0 ∧ ↑(Polynomial.aeval x) x_1 = 0 } := Classical.indefiniteDescription (fun x_1 => x_1 ≠ 0 ∧ ↑(Polynomial.aeval x) x_1 = 0) (_ : _root_.IsAlgebraic R x) ⊢ Polynomial.map (algebraMap R L) ↑p ≠ 0 [PROOFSTEP] rw [Ne.def, ← Polynomial.degree_eq_bot, Polynomial.degree_map_eq_of_injective (NoZeroSMulDivisors.algebraMap_injective R L), Polynomial.degree_eq_bot] [GOAL] R L : Type u inst✝⁴ : CommRing R inst✝³ : CommRing L inst✝² : IsDomain L inst✝¹ : Algebra R L inst✝ : NoZeroSMulDivisors R L halg : IsAlgebraic R L x : L p : { x_1 // x_1 ≠ 0 ∧ ↑(Polynomial.aeval x) x_1 = 0 } := Classical.indefiniteDescription (fun x_1 => x_1 ≠ 0 ∧ ↑(Polynomial.aeval x) x_1 = 0) (_ : _root_.IsAlgebraic R x) ⊢ ¬↑p = 0 [PROOFSTEP] exact p.2.1 [GOAL] R L : Type u inst✝⁴ : CommRing R inst✝³ : CommRing L inst✝² : IsDomain L inst✝¹ : Algebra R L inst✝ : NoZeroSMulDivisors R L halg : IsAlgebraic R L x : L p : { x_1 // x_1 ≠ 0 ∧ ↑(Polynomial.aeval x) x_1 = 0 } := Classical.indefiniteDescription (fun x_1 => x_1 ≠ 0 ∧ ↑(Polynomial.aeval x) x_1 = 0) (_ : _root_.IsAlgebraic R x) h : Polynomial.map (algebraMap R L) ↑p ≠ 0 ⊢ x ∈ Polynomial.roots (Polynomial.map (algebraMap R L) ↑(Classical.indefiniteDescription (fun x_1 => ¬x_1 = 0 ∧ ↑(Polynomial.aeval x) x_1 = 0) (_ : _root_.IsAlgebraic R x))) [PROOFSTEP] erw [Polynomial.mem_roots h, Polynomial.IsRoot, Polynomial.eval_map, ← Polynomial.aeval_def, p.2.2] [GOAL] R L : Type u inst✝⁴ : CommRing R inst✝³ : CommRing L inst✝² : IsDomain L inst✝¹ : Algebra R L inst✝ : NoZeroSMulDivisors R L halg : IsAlgebraic R L x y : L ⊢ (fun x => let p := Classical.indefiniteDescription (fun x_1 => x_1 ≠ 0 ∧ ↑(Polynomial.aeval x) x_1 = 0) (_ : _root_.IsAlgebraic R x); { fst := ↑p, snd := { val := x, property := (_ : x ∈ {x_1 | x_1 ∈ Polynomial.roots (Polynomial.map (algebraMap R L) ↑p)}) } }) x = (fun x => let p := Classical.indefiniteDescription (fun x_1 => x_1 ≠ 0 ∧ ↑(Polynomial.aeval x) x_1 = 0) (_ : _root_.IsAlgebraic R x); { fst := ↑p, snd := { val := x, property := (_ : x ∈ {x_1 | x_1 ∈ Polynomial.roots (Polynomial.map (algebraMap R L) ↑p)}) } }) y → x = y [PROOFSTEP] intro h [GOAL] R L : Type u inst✝⁴ : CommRing R inst✝³ : CommRing L inst✝² : IsDomain L inst✝¹ : Algebra R L inst✝ : NoZeroSMulDivisors R L halg : IsAlgebraic R L x y : L h : (fun x => let p := Classical.indefiniteDescription (fun x_1 => x_1 ≠ 0 ∧ ↑(Polynomial.aeval x) x_1 = 0) (_ : _root_.IsAlgebraic R x); { fst := ↑p, snd := { val := x, property := (_ : x ∈ {x_1 | x_1 ∈ Polynomial.roots (Polynomial.map (algebraMap R L) ↑p)}) } }) x = (fun x => let p := Classical.indefiniteDescription (fun x_1 => x_1 ≠ 0 ∧ ↑(Polynomial.aeval x) x_1 = 0) (_ : _root_.IsAlgebraic R x); { fst := ↑p, snd := { val := x, property := (_ : x ∈ {x_1 | x_1 ∈ Polynomial.roots (Polynomial.map (algebraMap R L) ↑p)}) } }) y ⊢ x = y [PROOFSTEP] simp at h [GOAL] R L : Type u inst✝⁴ : CommRing R inst✝³ : CommRing L inst✝² : IsDomain L inst✝¹ : Algebra R L inst✝ : NoZeroSMulDivisors R L halg : IsAlgebraic R L x y : L h : ↑(Classical.indefiniteDescription (fun x_1 => ¬x_1 = 0 ∧ ↑(Polynomial.aeval x) x_1 = 0) (_ : _root_.IsAlgebraic R x)) = ↑(Classical.indefiniteDescription (fun x => ¬x = 0 ∧ ↑(Polynomial.aeval y) x = 0) (_ : _root_.IsAlgebraic R y)) ∧ HEq { val := x, property := (_ : x ∈ {x_1 | x_1 ∈ Polynomial.roots (Polynomial.map (algebraMap R L) ↑(Classical.indefiniteDescription (fun x_2 => x_2 ≠ 0 ∧ ↑(Polynomial.aeval x) x_2 = 0) (_ : _root_.IsAlgebraic R x)))}) } { val := y, property := (_ : y ∈ {x | x ∈ Polynomial.roots (Polynomial.map (algebraMap R L) ↑(Classical.indefiniteDescription (fun x => x ≠ 0 ∧ ↑(Polynomial.aeval y) x = 0) (_ : _root_.IsAlgebraic R y)))}) } ⊢ x = y [PROOFSTEP] refine' (Subtype.heq_iff_coe_eq _).1 h.2 [GOAL] R L : Type u inst✝⁴ : CommRing R inst✝³ : CommRing L inst✝² : IsDomain L inst✝¹ : Algebra R L inst✝ : NoZeroSMulDivisors R L halg : IsAlgebraic R L x y : L h : ↑(Classical.indefiniteDescription (fun x_1 => ¬x_1 = 0 ∧ ↑(Polynomial.aeval x) x_1 = 0) (_ : _root_.IsAlgebraic R x)) = ↑(Classical.indefiniteDescription (fun x => ¬x = 0 ∧ ↑(Polynomial.aeval y) x = 0) (_ : _root_.IsAlgebraic R y)) ∧ HEq { val := x, property := (_ : x ∈ {x_1 | x_1 ∈ Polynomial.roots (Polynomial.map (algebraMap R L) ↑(Classical.indefiniteDescription (fun x_2 => x_2 ≠ 0 ∧ ↑(Polynomial.aeval x) x_2 = 0) (_ : _root_.IsAlgebraic R x)))}) } { val := y, property := (_ : y ∈ {x | x ∈ Polynomial.roots (Polynomial.map (algebraMap R L) ↑(Classical.indefiniteDescription (fun x => x ≠ 0 ∧ ↑(Polynomial.aeval y) x = 0) (_ : _root_.IsAlgebraic R y)))}) } ⊢ ∀ (x_1 : L), x_1 ∈ {x_2 | x_2 ∈ Polynomial.roots (Polynomial.map (algebraMap R L) ↑(Classical.indefiniteDescription (fun x_3 => x_3 ≠ 0 ∧ ↑(Polynomial.aeval x) x_3 = 0) (_ : _root_.IsAlgebraic R x)))} ↔ x_1 ∈ {x | x ∈ Polynomial.roots (Polynomial.map (algebraMap R L) ↑(Classical.indefiniteDescription (fun x => x ≠ 0 ∧ ↑(Polynomial.aeval y) x = 0) (_ : _root_.IsAlgebraic R y)))} [PROOFSTEP] simp only [h.1, iff_self_iff, forall_true_iff] [GOAL] R L : Type u inst✝⁴ : CommRing R inst✝³ : CommRing L inst✝² : IsDomain L inst✝¹ : Algebra R L inst✝ : NoZeroSMulDivisors R L halg : IsAlgebraic R L ⊢ #((p : R[X]) × { x // x ∈ Polynomial.roots (Polynomial.map (algebraMap R L) p) }) = sum fun p => #↑{x | x ∈ Polynomial.roots (Polynomial.map (algebraMap R L) p)} [PROOFSTEP] rw [← mk_sigma] [GOAL] R L : Type u inst✝⁴ : CommRing R inst✝³ : CommRing L inst✝² : IsDomain L inst✝¹ : Algebra R L inst✝ : NoZeroSMulDivisors R L halg : IsAlgebraic R L ⊢ #((p : R[X]) × { x // x ∈ Polynomial.roots (Polynomial.map (algebraMap R L) p) }) = #((i : R[X]) × ↑{x | x ∈ Polynomial.roots (Polynomial.map (algebraMap R L) i)}) [PROOFSTEP] rfl [GOAL] R L : Type u inst✝⁴ : CommRing R inst✝³ : CommRing L inst✝² : IsDomain L inst✝¹ : Algebra R L inst✝ : NoZeroSMulDivisors R L halg : IsAlgebraic R L ⊢ max (max (max #R ℵ₀) ℵ₀) ℵ₀ = max #R ℵ₀ [PROOFSTEP] simp only [max_assoc, max_comm ℵ₀, max_left_comm ℵ₀, max_self] [GOAL] R : Type u_1 L : Type u_2 K : Type u_3 inst✝⁵ : CommRing R inst✝⁴ : Field K inst✝³ : Algebra R K inst✝² : Field L inst✝¹ : Algebra R L ι : Type u_4 v : ι → K κ : Type u_5 w : κ → L hv✝ : AlgebraicIndependent R v inst✝ : IsAlgClosed K hv : IsTranscendenceBasis R v this : Nontrivial R := RingHom.domain_nontrivial (algebraMap R K) ⊢ IsAlgClosed K [PROOFSTEP] infer_instance [GOAL] R : Type u_1 L : Type u_2 K : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : Field K inst✝⁴ : Algebra R K inst✝³ : Field L inst✝² : Algebra R L ι : Type u_4 v : ι → K κ : Type u_5 w : κ → L hv✝ : AlgebraicIndependent R v hw✝ : AlgebraicIndependent R w inst✝¹ : IsAlgClosed K inst✝ : IsAlgClosed L e : ι ≃ κ hv : IsTranscendenceBasis R v hw : IsTranscendenceBasis R w ⊢ K ≃+* L [PROOFSTEP] letI := isAlgClosure_of_transcendence_basis v hv [GOAL] R : Type u_1 L : Type u_2 K : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : Field K inst✝⁴ : Algebra R K inst✝³ : Field L inst✝² : Algebra R L ι : Type u_4 v : ι → K κ : Type u_5 w : κ → L hv✝ : AlgebraicIndependent R v hw✝ : AlgebraicIndependent R w inst✝¹ : IsAlgClosed K inst✝ : IsAlgClosed L e : ι ≃ κ hv : IsTranscendenceBasis R v hw : IsTranscendenceBasis R w this : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range v) } K := isAlgClosure_of_transcendence_basis v hv ⊢ K ≃+* L [PROOFSTEP] letI := isAlgClosure_of_transcendence_basis w hw [GOAL] R : Type u_1 L : Type u_2 K : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : Field K inst✝⁴ : Algebra R K inst✝³ : Field L inst✝² : Algebra R L ι : Type u_4 v : ι → K κ : Type u_5 w : κ → L hv✝ : AlgebraicIndependent R v hw✝ : AlgebraicIndependent R w inst✝¹ : IsAlgClosed K inst✝ : IsAlgClosed L e : ι ≃ κ hv : IsTranscendenceBasis R v hw : IsTranscendenceBasis R w this✝ : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range v) } K := isAlgClosure_of_transcendence_basis v hv this : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range w) } L := isAlgClosure_of_transcendence_basis w hw ⊢ K ≃+* L [PROOFSTEP] have e : Algebra.adjoin R (Set.range v) ≃+* Algebra.adjoin R (Set.range w) [GOAL] case e R : Type u_1 L : Type u_2 K : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : Field K inst✝⁴ : Algebra R K inst✝³ : Field L inst✝² : Algebra R L ι : Type u_4 v : ι → K κ : Type u_5 w : κ → L hv✝ : AlgebraicIndependent R v hw✝ : AlgebraicIndependent R w inst✝¹ : IsAlgClosed K inst✝ : IsAlgClosed L e : ι ≃ κ hv : IsTranscendenceBasis R v hw : IsTranscendenceBasis R w this✝ : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range v) } K := isAlgClosure_of_transcendence_basis v hv this : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range w) } L := isAlgClosure_of_transcendence_basis w hw ⊢ { x // x ∈ Algebra.adjoin R (Set.range v) } ≃+* { x // x ∈ Algebra.adjoin R (Set.range w) } [PROOFSTEP] refine' hv.1.aevalEquiv.symm.toRingEquiv.trans _ [GOAL] case e R : Type u_1 L : Type u_2 K : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : Field K inst✝⁴ : Algebra R K inst✝³ : Field L inst✝² : Algebra R L ι : Type u_4 v : ι → K κ : Type u_5 w : κ → L hv✝ : AlgebraicIndependent R v hw✝ : AlgebraicIndependent R w inst✝¹ : IsAlgClosed K inst✝ : IsAlgClosed L e : ι ≃ κ hv : IsTranscendenceBasis R v hw : IsTranscendenceBasis R w this✝ : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range v) } K := isAlgClosure_of_transcendence_basis v hv this : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range w) } L := isAlgClosure_of_transcendence_basis w hw ⊢ MvPolynomial ι R ≃+* { x // x ∈ Algebra.adjoin R (Set.range w) } [PROOFSTEP] refine' (AlgEquiv.ofAlgHom (MvPolynomial.rename e) (MvPolynomial.rename e.symm) _ _).toRingEquiv.trans _ [GOAL] case e.refine'_1 R : Type u_1 L : Type u_2 K : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : Field K inst✝⁴ : Algebra R K inst✝³ : Field L inst✝² : Algebra R L ι : Type u_4 v : ι → K κ : Type u_5 w : κ → L hv✝ : AlgebraicIndependent R v hw✝ : AlgebraicIndependent R w inst✝¹ : IsAlgClosed K inst✝ : IsAlgClosed L e : ι ≃ κ hv : IsTranscendenceBasis R v hw : IsTranscendenceBasis R w this✝ : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range v) } K := isAlgClosure_of_transcendence_basis v hv this : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range w) } L := isAlgClosure_of_transcendence_basis w hw ⊢ AlgHom.comp (MvPolynomial.rename ↑e) (MvPolynomial.rename ↑e.symm) = AlgHom.id R (MvPolynomial κ R) [PROOFSTEP] ext [GOAL] case e.refine'_1.hf.a R : Type u_1 L : Type u_2 K : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : Field K inst✝⁴ : Algebra R K inst✝³ : Field L inst✝² : Algebra R L ι : Type u_4 v : ι → K κ : Type u_5 w : κ → L hv✝ : AlgebraicIndependent R v hw✝ : AlgebraicIndependent R w inst✝¹ : IsAlgClosed K inst✝ : IsAlgClosed L e : ι ≃ κ hv : IsTranscendenceBasis R v hw : IsTranscendenceBasis R w this✝ : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range v) } K := isAlgClosure_of_transcendence_basis v hv this : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range w) } L := isAlgClosure_of_transcendence_basis w hw i✝ : κ m✝ : κ →₀ ℕ ⊢ MvPolynomial.coeff m✝ (↑(AlgHom.comp (MvPolynomial.rename ↑e) (MvPolynomial.rename ↑e.symm)) (MvPolynomial.X i✝)) = MvPolynomial.coeff m✝ (↑(AlgHom.id R (MvPolynomial κ R)) (MvPolynomial.X i✝)) [PROOFSTEP] simp [GOAL] case e.refine'_2 R : Type u_1 L : Type u_2 K : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : Field K inst✝⁴ : Algebra R K inst✝³ : Field L inst✝² : Algebra R L ι : Type u_4 v : ι → K κ : Type u_5 w : κ → L hv✝ : AlgebraicIndependent R v hw✝ : AlgebraicIndependent R w inst✝¹ : IsAlgClosed K inst✝ : IsAlgClosed L e : ι ≃ κ hv : IsTranscendenceBasis R v hw : IsTranscendenceBasis R w this✝ : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range v) } K := isAlgClosure_of_transcendence_basis v hv this : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range w) } L := isAlgClosure_of_transcendence_basis w hw ⊢ AlgHom.comp (MvPolynomial.rename ↑e.symm) (MvPolynomial.rename ↑e) = AlgHom.id R (MvPolynomial ι R) [PROOFSTEP] ext [GOAL] case e.refine'_2.hf.a R : Type u_1 L : Type u_2 K : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : Field K inst✝⁴ : Algebra R K inst✝³ : Field L inst✝² : Algebra R L ι : Type u_4 v : ι → K κ : Type u_5 w : κ → L hv✝ : AlgebraicIndependent R v hw✝ : AlgebraicIndependent R w inst✝¹ : IsAlgClosed K inst✝ : IsAlgClosed L e : ι ≃ κ hv : IsTranscendenceBasis R v hw : IsTranscendenceBasis R w this✝ : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range v) } K := isAlgClosure_of_transcendence_basis v hv this : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range w) } L := isAlgClosure_of_transcendence_basis w hw i✝ : ι m✝ : ι →₀ ℕ ⊢ MvPolynomial.coeff m✝ (↑(AlgHom.comp (MvPolynomial.rename ↑e.symm) (MvPolynomial.rename ↑e)) (MvPolynomial.X i✝)) = MvPolynomial.coeff m✝ (↑(AlgHom.id R (MvPolynomial ι R)) (MvPolynomial.X i✝)) [PROOFSTEP] simp [GOAL] case e.refine'_3 R : Type u_1 L : Type u_2 K : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : Field K inst✝⁴ : Algebra R K inst✝³ : Field L inst✝² : Algebra R L ι : Type u_4 v : ι → K κ : Type u_5 w : κ → L hv✝ : AlgebraicIndependent R v hw✝ : AlgebraicIndependent R w inst✝¹ : IsAlgClosed K inst✝ : IsAlgClosed L e : ι ≃ κ hv : IsTranscendenceBasis R v hw : IsTranscendenceBasis R w this✝ : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range v) } K := isAlgClosure_of_transcendence_basis v hv this : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range w) } L := isAlgClosure_of_transcendence_basis w hw ⊢ MvPolynomial κ R ≃+* { x // x ∈ Algebra.adjoin R (Set.range w) } [PROOFSTEP] exact hw.1.aevalEquiv.toRingEquiv [GOAL] R : Type u_1 L : Type u_2 K : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : Field K inst✝⁴ : Algebra R K inst✝³ : Field L inst✝² : Algebra R L ι : Type u_4 v : ι → K κ : Type u_5 w : κ → L hv✝ : AlgebraicIndependent R v hw✝ : AlgebraicIndependent R w inst✝¹ : IsAlgClosed K inst✝ : IsAlgClosed L e✝ : ι ≃ κ hv : IsTranscendenceBasis R v hw : IsTranscendenceBasis R w this✝ : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range v) } K := isAlgClosure_of_transcendence_basis v hv this : IsAlgClosure { x // x ∈ Algebra.adjoin R (Set.range w) } L := isAlgClosure_of_transcendence_basis w hw e : { x // x ∈ Algebra.adjoin R (Set.range v) } ≃+* { x // x ∈ Algebra.adjoin R (Set.range w) } ⊢ K ≃+* L [PROOFSTEP] exact IsAlgClosure.equivOfEquiv K L e [GOAL] R L K : Type u inst✝³ : CommRing R inst✝² : Field K inst✝¹ : Algebra R K inst✝ : IsAlgClosed K ι : Type u v : ι → K hv✝ hv : IsTranscendenceBasis R v ⊢ max #{ x // x ∈ Algebra.adjoin R (Set.range v) } ℵ₀ = max #(MvPolynomial ι R) ℵ₀ [PROOFSTEP] rw [Cardinal.eq.2 ⟨hv.1.aevalEquiv.toEquiv⟩] [GOAL] R L K : Type u inst✝³ : CommRing R inst✝² : Field K inst✝¹ : Algebra R K inst✝ : IsAlgClosed K ι : Type u v : ι → K hv✝ hv : IsTranscendenceBasis R v ⊢ max (max (max #R #ι) ℵ₀) ℵ₀ = max (max #R #ι) ℵ₀ [PROOFSTEP] simp [max_assoc] [GOAL] R L K : Type u inst✝⁴ : CommRing R inst✝³ : Field K inst✝² : Algebra R K inst✝¹ : IsAlgClosed K ι : Type u v : ι → K hv✝ : IsTranscendenceBasis R v inst✝ : Nontrivial R hv : IsTranscendenceBasis R v hR : #R ≤ ℵ₀ hK : ℵ₀ < #K this : ℵ₀ ≤ #ι ⊢ max (max #R #ι) ℵ₀ = #ι [PROOFSTEP] rw [max_eq_left, max_eq_right] [GOAL] R L K : Type u inst✝⁴ : CommRing R inst✝³ : Field K inst✝² : Algebra R K inst✝¹ : IsAlgClosed K ι : Type u v : ι → K hv✝ : IsTranscendenceBasis R v inst✝ : Nontrivial R hv : IsTranscendenceBasis R v hR : #R ≤ ℵ₀ hK : ℵ₀ < #K this : ℵ₀ ≤ #ι ⊢ #R ≤ #ι [PROOFSTEP] exact le_trans hR this [GOAL] R L K : Type u inst✝⁴ : CommRing R inst✝³ : Field K inst✝² : Algebra R K inst✝¹ : IsAlgClosed K ι : Type u v : ι → K hv✝ : IsTranscendenceBasis R v inst✝ : Nontrivial R hv : IsTranscendenceBasis R v hR : #R ≤ ℵ₀ hK : ℵ₀ < #K this : ℵ₀ ≤ #ι ⊢ ℵ₀ ≤ max #R #ι [PROOFSTEP] exact le_max_of_le_right this [GOAL] K L : Type inst✝⁵ : Field K inst✝⁴ : Field L inst✝³ : IsAlgClosed K inst✝² : IsAlgClosed L inst✝¹ : CharZero K inst✝ : CharZero L hK : ℵ₀ < #K hKL : #K = #L ⊢ Nonempty (K ≃+* L) [PROOFSTEP] cases' exists_isTranscendenceBasis ℤ (show Function.Injective (algebraMap ℤ K) from Int.cast_injective) with s hs [GOAL] case intro K L : Type inst✝⁵ : Field K inst✝⁴ : Field L inst✝³ : IsAlgClosed K inst✝² : IsAlgClosed L inst✝¹ : CharZero K inst✝ : CharZero L hK : ℵ₀ < #K hKL : #K = #L s : Set K hs : IsTranscendenceBasis ℤ Subtype.val ⊢ Nonempty (K ≃+* L) [PROOFSTEP] cases' exists_isTranscendenceBasis ℤ (show Function.Injective (algebraMap ℤ L) from Int.cast_injective) with t ht [GOAL] case intro.intro K L : Type inst✝⁵ : Field K inst✝⁴ : Field L inst✝³ : IsAlgClosed K inst✝² : IsAlgClosed L inst✝¹ : CharZero K inst✝ : CharZero L hK : ℵ₀ < #K hKL : #K = #L s : Set K hs : IsTranscendenceBasis ℤ Subtype.val t : Set L ht : IsTranscendenceBasis ℤ Subtype.val ⊢ Nonempty (K ≃+* L) [PROOFSTEP] have : #s = #t := by rw [← cardinal_eq_cardinal_transcendence_basis_of_aleph0_lt _ hs (le_of_eq mk_int) hK, ← cardinal_eq_cardinal_transcendence_basis_of_aleph0_lt _ ht (le_of_eq mk_int), hKL] rwa [← hKL] [GOAL] K L : Type inst✝⁵ : Field K inst✝⁴ : Field L inst✝³ : IsAlgClosed K inst✝² : IsAlgClosed L inst✝¹ : CharZero K inst✝ : CharZero L hK : ℵ₀ < #K hKL : #K = #L s : Set K hs : IsTranscendenceBasis ℤ Subtype.val t : Set L ht : IsTranscendenceBasis ℤ Subtype.val ⊢ #↑s = #↑t [PROOFSTEP] rw [← cardinal_eq_cardinal_transcendence_basis_of_aleph0_lt _ hs (le_of_eq mk_int) hK, ← cardinal_eq_cardinal_transcendence_basis_of_aleph0_lt _ ht (le_of_eq mk_int), hKL] [GOAL] K L : Type inst✝⁵ : Field K inst✝⁴ : Field L inst✝³ : IsAlgClosed K inst✝² : IsAlgClosed L inst✝¹ : CharZero K inst✝ : CharZero L hK : ℵ₀ < #K hKL : #K = #L s : Set K hs : IsTranscendenceBasis ℤ Subtype.val t : Set L ht : IsTranscendenceBasis ℤ Subtype.val ⊢ ℵ₀ < #L [PROOFSTEP] rwa [← hKL] [GOAL] case intro.intro K L : Type inst✝⁵ : Field K inst✝⁴ : Field L inst✝³ : IsAlgClosed K inst✝² : IsAlgClosed L inst✝¹ : CharZero K inst✝ : CharZero L hK : ℵ₀ < #K hKL : #K = #L s : Set K hs : IsTranscendenceBasis ℤ Subtype.val t : Set L ht : IsTranscendenceBasis ℤ Subtype.val this : #↑s = #↑t ⊢ Nonempty (K ≃+* L) [PROOFSTEP] cases' Cardinal.eq.1 this with e [GOAL] case intro.intro.intro K L : Type inst✝⁵ : Field K inst✝⁴ : Field L inst✝³ : IsAlgClosed K inst✝² : IsAlgClosed L inst✝¹ : CharZero K inst✝ : CharZero L hK : ℵ₀ < #K hKL : #K = #L s : Set K hs : IsTranscendenceBasis ℤ Subtype.val t : Set L ht : IsTranscendenceBasis ℤ Subtype.val this : #↑s = #↑t e : ↑s ≃ ↑t ⊢ Nonempty (K ≃+* L) [PROOFSTEP] exact ⟨equivOfTranscendenceBasis _ _ e hs ht⟩ [GOAL] K L : Type inst✝⁶ : Field K inst✝⁵ : Field L inst✝⁴ : IsAlgClosed K inst✝³ : IsAlgClosed L p : ℕ inst✝² : Fact (Nat.Prime p) inst✝¹ : CharP K p inst✝ : CharP L p hK : ℵ₀ < #K hKL : #K = #L ⊢ Nonempty (K ≃+* L) [PROOFSTEP] letI : Algebra (ZMod p) K := ZMod.algebra _ _ [GOAL] K L : Type inst✝⁶ : Field K inst✝⁵ : Field L inst✝⁴ : IsAlgClosed K inst✝³ : IsAlgClosed L p : ℕ inst✝² : Fact (Nat.Prime p) inst✝¹ : CharP K p inst✝ : CharP L p hK : ℵ₀ < #K hKL : #K = #L this : Algebra (ZMod p) K := ZMod.algebra K p ⊢ Nonempty (K ≃+* L) [PROOFSTEP] letI : Algebra (ZMod p) L := ZMod.algebra _ _ [GOAL] K L : Type inst✝⁶ : Field K inst✝⁵ : Field L inst✝⁴ : IsAlgClosed K inst✝³ : IsAlgClosed L p : ℕ inst✝² : Fact (Nat.Prime p) inst✝¹ : CharP K p inst✝ : CharP L p hK : ℵ₀ < #K hKL : #K = #L this✝ : Algebra (ZMod p) K := ZMod.algebra K p this : Algebra (ZMod p) L := ZMod.algebra L p ⊢ Nonempty (K ≃+* L) [PROOFSTEP] cases' exists_isTranscendenceBasis (ZMod p) (show Function.Injective (algebraMap (ZMod p) K) from RingHom.injective _) with s hs [GOAL] case intro K L : Type inst✝⁶ : Field K inst✝⁵ : Field L inst✝⁴ : IsAlgClosed K inst✝³ : IsAlgClosed L p : ℕ inst✝² : Fact (Nat.Prime p) inst✝¹ : CharP K p inst✝ : CharP L p hK : ℵ₀ < #K hKL : #K = #L this✝ : Algebra (ZMod p) K := ZMod.algebra K p this : Algebra (ZMod p) L := ZMod.algebra L p s : Set K hs : IsTranscendenceBasis (ZMod p) Subtype.val ⊢ Nonempty (K ≃+* L) [PROOFSTEP] cases' exists_isTranscendenceBasis (ZMod p) (show Function.Injective (algebraMap (ZMod p) L) from RingHom.injective _) with t ht [GOAL] case intro.intro K L : Type inst✝⁶ : Field K inst✝⁵ : Field L inst✝⁴ : IsAlgClosed K inst✝³ : IsAlgClosed L p : ℕ inst✝² : Fact (Nat.Prime p) inst✝¹ : CharP K p inst✝ : CharP L p hK : ℵ₀ < #K hKL : #K = #L this✝ : Algebra (ZMod p) K := ZMod.algebra K p this : Algebra (ZMod p) L := ZMod.algebra L p s : Set K hs : IsTranscendenceBasis (ZMod p) Subtype.val t : Set L ht : IsTranscendenceBasis (ZMod p) Subtype.val ⊢ Nonempty (K ≃+* L) [PROOFSTEP] have : #s = #t := by rw [← cardinal_eq_cardinal_transcendence_basis_of_aleph0_lt _ hs (lt_aleph0_of_finite (ZMod p)).le hK, ← cardinal_eq_cardinal_transcendence_basis_of_aleph0_lt _ ht (lt_aleph0_of_finite (ZMod p)).le, hKL] rwa [← hKL] [GOAL] K L : Type inst✝⁶ : Field K inst✝⁵ : Field L inst✝⁴ : IsAlgClosed K inst✝³ : IsAlgClosed L p : ℕ inst✝² : Fact (Nat.Prime p) inst✝¹ : CharP K p inst✝ : CharP L p hK : ℵ₀ < #K hKL : #K = #L this✝ : Algebra (ZMod p) K := ZMod.algebra K p this : Algebra (ZMod p) L := ZMod.algebra L p s : Set K hs : IsTranscendenceBasis (ZMod p) Subtype.val t : Set L ht : IsTranscendenceBasis (ZMod p) Subtype.val ⊢ #↑s = #↑t [PROOFSTEP] rw [← cardinal_eq_cardinal_transcendence_basis_of_aleph0_lt _ hs (lt_aleph0_of_finite (ZMod p)).le hK, ← cardinal_eq_cardinal_transcendence_basis_of_aleph0_lt _ ht (lt_aleph0_of_finite (ZMod p)).le, hKL] [GOAL] K L : Type inst✝⁶ : Field K inst✝⁵ : Field L inst✝⁴ : IsAlgClosed K inst✝³ : IsAlgClosed L p : ℕ inst✝² : Fact (Nat.Prime p) inst✝¹ : CharP K p inst✝ : CharP L p hK : ℵ₀ < #K hKL : #K = #L this✝ : Algebra (ZMod p) K := ZMod.algebra K p this : Algebra (ZMod p) L := ZMod.algebra L p s : Set K hs : IsTranscendenceBasis (ZMod p) Subtype.val t : Set L ht : IsTranscendenceBasis (ZMod p) Subtype.val ⊢ ℵ₀ < #L [PROOFSTEP] rwa [← hKL] [GOAL] case intro.intro K L : Type inst✝⁶ : Field K inst✝⁵ : Field L inst✝⁴ : IsAlgClosed K inst✝³ : IsAlgClosed L p : ℕ inst✝² : Fact (Nat.Prime p) inst✝¹ : CharP K p inst✝ : CharP L p hK : ℵ₀ < #K hKL : #K = #L this✝¹ : Algebra (ZMod p) K := ZMod.algebra K p this✝ : Algebra (ZMod p) L := ZMod.algebra L p s : Set K hs : IsTranscendenceBasis (ZMod p) Subtype.val t : Set L ht : IsTranscendenceBasis (ZMod p) Subtype.val this : #↑s = #↑t ⊢ Nonempty (K ≃+* L) [PROOFSTEP] cases' Cardinal.eq.1 this with e [GOAL] case intro.intro.intro K L : Type inst✝⁶ : Field K inst✝⁵ : Field L inst✝⁴ : IsAlgClosed K inst✝³ : IsAlgClosed L p : ℕ inst✝² : Fact (Nat.Prime p) inst✝¹ : CharP K p inst✝ : CharP L p hK : ℵ₀ < #K hKL : #K = #L this✝¹ : Algebra (ZMod p) K := ZMod.algebra K p this✝ : Algebra (ZMod p) L := ZMod.algebra L p s : Set K hs : IsTranscendenceBasis (ZMod p) Subtype.val t : Set L ht : IsTranscendenceBasis (ZMod p) Subtype.val this : #↑s = #↑t e : ↑s ≃ ↑t ⊢ Nonempty (K ≃+* L) [PROOFSTEP] exact ⟨equivOfTranscendenceBasis _ _ e hs ht⟩ [GOAL] K L : Type inst✝⁵ : Field K inst✝⁴ : Field L inst✝³ : IsAlgClosed K inst✝² : IsAlgClosed L p : ℕ inst✝¹ : CharP K p inst✝ : CharP L p hK : ℵ₀ < #K hKL : #K = #L ⊢ Nonempty (K ≃+* L) [PROOFSTEP] rcases CharP.char_is_prime_or_zero K p with (hp | hp) [GOAL] case inl K L : Type inst✝⁵ : Field K inst✝⁴ : Field L inst✝³ : IsAlgClosed K inst✝² : IsAlgClosed L p : ℕ inst✝¹ : CharP K p inst✝ : CharP L p hK : ℵ₀ < #K hKL : #K = #L hp : Nat.Prime p ⊢ Nonempty (K ≃+* L) [PROOFSTEP] haveI : Fact p.Prime := ⟨hp⟩ [GOAL] case inl K L : Type inst✝⁵ : Field K inst✝⁴ : Field L inst✝³ : IsAlgClosed K inst✝² : IsAlgClosed L p : ℕ inst✝¹ : CharP K p inst✝ : CharP L p hK : ℵ₀ < #K hKL : #K = #L hp : Nat.Prime p this : Fact (Nat.Prime p) ⊢ Nonempty (K ≃+* L) [PROOFSTEP] exact ringEquivOfCardinalEqOfCharP p hK hKL [GOAL] case inr K L : Type inst✝⁵ : Field K inst✝⁴ : Field L inst✝³ : IsAlgClosed K inst✝² : IsAlgClosed L p : ℕ inst✝¹ : CharP K p inst✝ : CharP L p hK : ℵ₀ < #K hKL : #K = #L hp : p = 0 ⊢ Nonempty (K ≃+* L) [PROOFSTEP] simp only [hp] at * [GOAL] case inr K L : Type inst✝⁵ : Field K inst✝⁴ : Field L inst✝³ : IsAlgClosed K inst✝² : IsAlgClosed L p : ℕ hK : ℵ₀ < #K hKL : #K = #L inst✝¹ : CharP K 0 inst✝ : CharP L 0 hp : True ⊢ Nonempty (K ≃+* L) [PROOFSTEP] letI : CharZero K := CharP.charP_to_charZero K [GOAL] case inr K L : Type inst✝⁵ : Field K inst✝⁴ : Field L inst✝³ : IsAlgClosed K inst✝² : IsAlgClosed L p : ℕ hK : ℵ₀ < #K hKL : #K = #L inst✝¹ : CharP K 0 inst✝ : CharP L 0 hp : True this : CharZero K := CharP.charP_to_charZero K ⊢ Nonempty (K ≃+* L) [PROOFSTEP] letI : CharZero L := CharP.charP_to_charZero L [GOAL] case inr K L : Type inst✝⁵ : Field K inst✝⁴ : Field L inst✝³ : IsAlgClosed K inst✝² : IsAlgClosed L p : ℕ hK : ℵ₀ < #K hKL : #K = #L inst✝¹ : CharP K 0 inst✝ : CharP L 0 hp : True this✝ : CharZero K := CharP.charP_to_charZero K this : CharZero L := CharP.charP_to_charZero L ⊢ Nonempty (K ≃+* L) [PROOFSTEP] exact ringEquivOfCardinalEqOfCharZero hK hKL
lemma pairwise_disjnt_countable_Union: assumes "countable (\<Union>\<N>)" and pwd: "pairwise disjnt \<N>" shows "countable \<N>"
Who is Northeastern Fine Fishing Co. Located in Pittsburgh, Pennsylvania, we are determined to spread our passion for float fishing. We first encountered this form of fishing in Canada and are eager to watch this emerging sport spread in North America especially across the northeastern US where we work and play. As one of the finest forms of river and stream fishing, we enjoy float fishing for bass and trout in our local Pennsylvania rivers, but our true love is fishing for salmon and steelhead in the Great Lakes tributaries. From September to May, we fish the tributaries of Lake Ontario and Lake Erie spanning from Southern Ontario to the northeastern US. If you see us on the river, come say hi! We take pride in having a positive impact on keeping our waters and lands clean, and sharing our knowledge of this incredible sport with others. We have a fantastic selection of centerpin reels and tackle, and we encourage all local customers to come by and support our small business. We are here to help all centerpin anglers of all skill levels. When you purchase from us online, you will have a choice to pay with PayPal, Amazon Pay, or by credit card. If you have any questions or concerns regarding your purchase, please contact us! We love to hear from our customers, whether it is to discuss our products or just float fishing in general. If you are in need of expedited shipping, please be sure to call or email us before placing your order, to ensure we are not away fishing. To share our enthusiasm for float fishing by offering quality, premium products at affordable prices; to create an online community for angling enthusiasts to share stories, learnings, and mutual appreciation of wildlife and the sport. Michael Sola, owner and angling enthusiast, founded Northeastern Fine Fishing Co. with a passion for float fishing. Currently, Michael resides in Pittsburgh, Pennsylvania with his wife and children. Prior to living in the Keystone state, Michael and his family lived in Toronto, Ontario where he first experienced float fishing in the tributaries of Lake Ontario and Lake Erie. The Grand River in Southern Ontario, which is the first river he used a centerpin reel, is still one of his favorite fisheries. After experiencing so much success float fishing, he now uses a centerpin reel year-round as he makes regular trips to Lake Ontario and Lake Erie tributaries. Michael can be reached directly at (570) 704-7123 or by email to [email protected]. Preservation of Land, Waters & Wildlife. We practice C&R (catch and release) and keeping our tributaries and surrounding lands clean. We support programs that support preservation. When you purchase from us you’re giving back too. So, kudos to you! Passion for the Sport. Passion is contagious. We encourage you to share your stories, perspectives, shot patterns, pictures, and more on our blog and Facebook page to enable anglers at all levels. Learning & Growth. It is important to our mission to offer anglers tools, resources, and connections that elevate the sport of float fishing. We never stop learning, and strive for continuous growth. We love float fishing. We love story telling. We hope you do too! Gratitude. We have a profound appreciation for what we have—wildlife that is awe-inspiring, sport which offers recreational relief and hobby, and a connection with others through a strong sense of community. What do you love about today?
(* Todo: *) (* -list method -> list ty ==> list (method * ty) -write refinesADT' *) Require Import FiatFormal.Language.Step. Require Import FiatFormal.Language.TyJudge. Set Printing Projections. Definition refines (x1 x2 : exp) := forall pb ds pbOK v, STEPS pb ds pbOK x2 v -> STEPS pb ds pbOK x1 v. Definition refinesP (p1 p2 : prog) := forall pb ds pbOK v, STEPSP pb ds pbOK p2 v -> STEPSP pb ds pbOK p1 v. Definition getRepType (a : adt) := match a with | IADT r ms ss => r end. Definition getMethods (a : adt) := match a with | IADT r ms ss => ms end. Definition getSigs (a : adt) := match a with | IADT r ms ss => ss end. Definition getArity (m : method) := m.(arity). Definition getDom (m : method) := m.(dom). Definition getCod (m : method) := m.(cod). Definition getBody (m : method) := m.(body). Inductive refinesADT (ProofBuilder : propcon -> list exp -> Prop) (ds : defs) (ProofBuilderOK : forall ke te pc xs ts, ProofBuilder pc xs -> getPropDef pc ds = Some (DefProp pc ts) -> Forall2 (TYPE ds ke te) xs ts) : adt -> adt -> Prop := | CREFINE : forall methodsNew repNew sigsNew methodsOld repOld sigsOld, (exists (R : exp -> exp -> Prop), forall n arity dom bodyOld bodyNew cod v vs repNew' repsNew repsOld, get n methodsOld = Some (mkMethod arity dom bodyOld cod) -> get n methodsNew = Some (mkMethod arity dom bodyNew cod) -> Forall wnfX vs -> Forall2 R repsOld repsNew -> STEPS ProofBuilder ds ProofBuilderOK (XNApp (bodyNew) (repsNew >< vs)) (XTup ((nil :> v) :> repNew')) -> (exists repOld', STEPS ProofBuilder ds ProofBuilderOK (XNApp (bodyOld) (repsOld >< vs)) (XTup ((nil :> v) :> repOld')) /\ R repOld' repNew')) -> refinesADT ProofBuilder ds ProofBuilderOK (IADT repOld methodsOld sigsOld) (IADT repNew methodsNew sigsNew). Theorem refinementSoundess : forall pb ds pbOK ao an p, refinesADT pb ds pbOK ao an -> refinesP (PLET ao p) (PLET an p). Proof. unfold refinesP. intros. inverts H. dest H1. Admitted.
function bp=backprojection(c); % function backp=backprojection(c); % calculates backprojections from eigenvalues (e) and Group Space %(c.GroupSpace) which are the outputs of cmdscale. eigenvals=diag(c.eigenvalues(1:c.ndims),0); A=c.GroupSpace(:,1:c.ndims)*sqrt(eigenvals); for n=1:size(c.data,3); mdata=c.data(:,:,n); backproj(:,:,n)=A'*(mdata*inv(mdata'*mdata))'; end bp=mean(backproj,3);
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # 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. import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from ppdet.core.workspace import register, serializable from .. import ops @register @serializable class ProposalGenerator(object): def __init__(self, pre_nms_top_n=12000, post_nms_top_n=2000, nms_thresh=.5, min_size=.1, eta=1., topk_after_collect=False): super(ProposalGenerator, self).__init__() self.pre_nms_top_n = pre_nms_top_n self.post_nms_top_n = post_nms_top_n self.nms_thresh = nms_thresh self.min_size = min_size self.eta = eta self.topk_after_collect = topk_after_collect def __call__(self, scores, bbox_deltas, anchors, im_shape): top_n = self.pre_nms_top_n if self.topk_after_collect else self.post_nms_top_n variances = paddle.ones_like(anchors) rpn_rois, rpn_rois_prob, rpn_rois_num = ops.generate_proposals( scores, bbox_deltas, im_shape, anchors, variances, pre_nms_top_n=self.pre_nms_top_n, post_nms_top_n=top_n, nms_thresh=self.nms_thresh, min_size=self.min_size, eta=self.eta, return_rois_num=True) return rpn_rois, rpn_rois_prob, rpn_rois_num, self.post_nms_top_n