Datasets:
AI4M
/

text
stringlengths
0
3.34M
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.monomial import Mathlib.data.finset.nat_antidiagonal import Mathlib.PostPort universes u v u_1 namespace Mathlib /-! # Theory of univariate polynomials The theorems include formulas for computing coefficients, such as `coeff_add`, `coeff_sum`, `coeff_mul` -/ namespace polynomial theorem coeff_one {R : Type u} [semiring R] (n : ℕ) : coeff 1 n = ite (0 = n) 1 0 := coeff_monomial @[simp] theorem coeff_add {R : Type u} [semiring R] (p : polynomial R) (q : polynomial R) (n : ℕ) : coeff (p + q) n = coeff p n + coeff q n := rfl theorem coeff_sum {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (n : ℕ) (f : ℕ → R → polynomial S) : coeff (finsupp.sum p f) n = finsupp.sum p fun (a : ℕ) (b : R) => coeff (f a b) n := finsupp.sum_apply @[simp] theorem coeff_smul {R : Type u} [semiring R] (p : polynomial R) (r : R) (n : ℕ) : coeff (r • p) n = r * coeff p n := finsupp.smul_apply theorem mem_support_iff_coeff_ne_zero {R : Type u} {n : ℕ} [semiring R] {p : polynomial R} : n ∈ finsupp.support p ↔ coeff p n ≠ 0 := eq.mpr (id (Eq._oldrec (Eq.refl (n ∈ finsupp.support p ↔ coeff p n ≠ 0)) (propext (finsupp.mem_support_to_fun p n)))) (iff.refl (finsupp.to_fun p n ≠ 0)) theorem not_mem_support_iff_coeff_zero {R : Type u} {n : ℕ} [semiring R] {p : polynomial R} : ¬n ∈ finsupp.support p ↔ coeff p n = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (¬n ∈ finsupp.support p ↔ coeff p n = 0)) (propext (finsupp.mem_support_to_fun p n)))) (eq.mpr (id (Eq._oldrec (Eq.refl (¬finsupp.to_fun p n ≠ 0 ↔ coeff p n = 0)) (propext not_not))) (iff.refl (finsupp.to_fun p n = 0))) /-- The nth coefficient, as a linear map. -/ def lcoeff (R : Type u) [semiring R] (n : ℕ) : linear_map R (polynomial R) R := finsupp.lapply n @[simp] theorem lcoeff_apply {R : Type u} [semiring R] (n : ℕ) (f : polynomial R) : coe_fn (lcoeff R n) f = coeff f n := rfl @[simp] theorem finset_sum_coeff {R : Type u} [semiring R] {ι : Type u_1} (s : finset ι) (f : ι → polynomial R) (n : ℕ) : coeff (finset.sum s fun (b : ι) => f b) n = finset.sum s fun (b : ι) => coeff (f b) n := Eq.symm (finset.sum_hom s fun (q : polynomial R) => coe_fn (lcoeff R n) q) theorem coeff_mul {R : Type u} [semiring R] (p : polynomial R) (q : polynomial R) (n : ℕ) : coeff (p * q) n = finset.sum (finset.nat.antidiagonal n) fun (x : ℕ × ℕ) => coeff p (prod.fst x) * coeff q (prod.snd x) := add_monoid_algebra.mul_apply_antidiagonal p q n (finset.nat.antidiagonal n) fun (x : ℕ × ℕ) => finset.nat.mem_antidiagonal @[simp] theorem mul_coeff_zero {R : Type u} [semiring R] (p : polynomial R) (q : polynomial R) : coeff (p * q) 0 = coeff p 0 * coeff q 0 := sorry theorem coeff_mul_X_zero {R : Type u} [semiring R] (p : polynomial R) : coeff (p * X) 0 = 0 := sorry theorem coeff_X_mul_zero {R : Type u} [semiring R] (p : polynomial R) : coeff (X * p) 0 = 0 := sorry theorem coeff_C_mul_X {R : Type u} [semiring R] (x : R) (k : ℕ) (n : ℕ) : coeff (coe_fn C x * X ^ k) n = ite (n = k) x 0 := sorry @[simp] theorem coeff_C_mul {R : Type u} {a : R} {n : ℕ} [semiring R] (p : polynomial R) : coeff (coe_fn C a * p) n = a * coeff p n := add_monoid_algebra.single_zero_mul_apply p a n theorem C_mul' {R : Type u} [semiring R] (a : R) (f : polynomial R) : coe_fn C a * f = a • f := ext fun (n : ℕ) => coeff_C_mul f @[simp] theorem coeff_mul_C {R : Type u} [semiring R] (p : polynomial R) (n : ℕ) (a : R) : coeff (p * coe_fn C a) n = coeff p n * a := add_monoid_algebra.mul_single_zero_apply p a n theorem coeff_X_pow {R : Type u} [semiring R] (k : ℕ) (n : ℕ) : coeff (X ^ k) n = ite (n = k) 1 0 := sorry @[simp] theorem coeff_X_pow_self {R : Type u} [semiring R] (n : ℕ) : coeff (X ^ n) n = 1 := sorry theorem coeff_mul_X_pow {R : Type u} [semiring R] (p : polynomial R) (n : ℕ) (d : ℕ) : coeff (p * X ^ n) (d + n) = coeff p d := sorry @[simp] theorem coeff_mul_X {R : Type u} [semiring R] (p : polynomial R) (n : ℕ) : coeff (p * X) (n + 1) = coeff p n := sorry theorem mul_X_pow_eq_zero {R : Type u} [semiring R] {p : polynomial R} {n : ℕ} (H : p * X ^ n = 0) : p = 0 := ext fun (k : ℕ) => Eq.trans (Eq.symm (coeff_mul_X_pow p n k)) (iff.mp ext_iff H (k + n)) theorem C_mul_X_pow_eq_monomial {R : Type u} [semiring R] (c : R) (n : ℕ) : coe_fn C c * X ^ n = coe_fn (monomial n) c := sorry theorem support_mul_X_pow {R : Type u} [semiring R] (c : R) (n : ℕ) (H : c ≠ 0) : finsupp.support (coe_fn C c * X ^ n) = singleton n := eq.mpr (id (Eq._oldrec (Eq.refl (finsupp.support (coe_fn C c * X ^ n) = singleton n)) (C_mul_X_pow_eq_monomial c n))) (eq.mpr (id (Eq._oldrec (Eq.refl (finsupp.support (coe_fn (monomial n) c) = singleton n)) (support_monomial n c H))) (Eq.refl (singleton n))) theorem support_C_mul_X_pow' {R : Type u} [semiring R] {c : R} {n : ℕ} : finsupp.support (coe_fn C c * X ^ n) ⊆ singleton n := eq.mpr (id (Eq._oldrec (Eq.refl (finsupp.support (coe_fn C c * X ^ n) ⊆ singleton n)) (C_mul_X_pow_eq_monomial c n))) (support_monomial' n c) theorem C_dvd_iff_dvd_coeff {R : Type u} [semiring R] (r : R) (φ : polynomial R) : coe_fn C r ∣ φ ↔ ∀ (i : ℕ), r ∣ coeff φ i := sorry /-- If the coefficients of a polynomial belong to n ideal contains the submodule span of the coefficients of a polynomial. -/ theorem span_le_of_coeff_mem_C_inverse {R : Type u} [semiring R] {f : polynomial R} {I : submodule (polynomial R) (polynomial R)} (cf : ∀ (i : ℕ), coeff f i ∈ ⇑C ⁻¹' submodule.carrier I) : submodule.span (polynomial R) (set_of fun (g : polynomial R) => ∃ (i : ℕ), g = coe_fn C (coeff f i)) ≤ I := sorry theorem mem_span_C_coeff {R : Type u} [semiring R] {f : polynomial R} : f ∈ submodule.span (polynomial R) (set_of fun (g : polynomial R) => ∃ (i : ℕ), g = coe_fn C (coeff f i)) := sorry theorem exists_coeff_not_mem_C_inverse {R : Type u} [semiring R] {f : polynomial R} {I : submodule (polynomial R) (polynomial R)} : ¬f ∈ I → ∃ (i : ℕ), ¬coeff f i ∈ ⇑C ⁻¹' submodule.carrier I := imp_of_not_imp_not (¬f ∈ I) (∃ (i : ℕ), ¬coeff f i ∈ ⇑C ⁻¹' submodule.carrier I) fun (cf : ¬∃ (i : ℕ), ¬coeff f i ∈ ⇑C ⁻¹' submodule.carrier I) => iff.mpr not_not (span_le_of_coeff_mem_C_inverse (iff.mp not_exists_not cf) mem_span_C_coeff) end Mathlib
Require Import Assertions. Require Import HahnBase. Require Import Heaps. Require Import List. Require Import Models. Require Import Permissions. Require Import Permutation. Require Import Prelude. Require Import Processes. Require Import Programs. Require Import QArith. Require Import Qcanon. Require Import Utf8. Import ListNotations. Set Implicit Arguments. (** * Soundness *) Module Type Soundness (doms: Domains) (procs: Processes doms) (heaps: Heaps doms) (progs: Programs doms procs heaps) (models: Models doms procs heaps progs) (assns: Assertions doms procs heaps progs models). Export doms procs heaps progs models assns. (** ** Instrumented semantics *) (** The instrumented semantics [istep] defines the _lock-step execution_ of [step] and [pstep]. The instrumented semantics is defined up to bisimulation equivalence of permission processes. This is not strictly necessary (one may do without all [pbisim] conditions and handle bisimulation inside [safe]), but gives some very nice properties (e.g. [istep_bisim_l] and [istep_bisim_r]). *) Inductive istep : Cmd -> Proc -> Heap -> Store -> Label -> Cmd -> Proc -> Heap -> Store -> Prop := (* internal computation *) | istep_comp C P Q h s C' h' s' : step C h s Lcomp C' h' s' -> bisim P Q -> istep C P h s Lcomp C' Q h' s' (* explicit send *) | istep_send C P Q h s C' P' Q' h' s' v tag : step C h s (Lsend v tag) C' h' s' -> bisim P P' -> pstep P' (PLsend v tag) Q' -> bisim Q' Q -> istep C P h s (Lsend v tag) C' Q h' s' (* explicit receive *) | istep_recv C P Q h s C' P' Q' h' s' v tag : step C h s (Lrecv v tag) C' h' s' -> bisim P P' -> pstep P' (PLrecv v tag) Q' -> bisim Q' Q -> istep C P h s (Lrecv v tag) C' Q h' s' (* explicit communication *) | istep_comm C P Q h s C' P' Q' h' s' v tag : step C h s (Lcomm v tag) C' h' s' -> bisim P P' -> pstep P' (PLcomm v tag) Q' -> bisim Q' Q -> istep C P h s (Lcomm v tag) C' Q h' s' (* explicit querying *) | istep_query C P Q h s C' P' Q' h' s' b : step C h s (Lquery b) C' h' s' -> bisim P P' -> pstep P' (PLassn b) Q' -> bisim Q' Q -> istep C P h s (Lquery b) C' Q h' s'. Lemma istep_comp_proc_pres : forall C P h s C' P' h' s', istep C P h s Lcomp C' P' h' s' -> bisim P P'. Proof. induction C; intros P h s C' P' h' s' H1; inv H1. Qed. Lemma istep_seq_l : forall C1 C2 P h s l C1' P' h' s', istep C1 P h s l C1' P' h' s' <-> istep (Cseq C1 C2) P h s l (Cseq C1' C2) P' h' s'. Proof. intros C1 C2 P h s l C1' P' h' s'. split; intro STEP. (* left to right *) - inv STEP; clear STEP. + apply istep_comp; vauto. + rename P'0 into Q. apply istep_send with Q Q'; vauto. + rename P'0 into Q. apply istep_recv with Q Q'; vauto. + rename P'0 into Q. apply istep_comm with Q Q'; vauto. + rename P'0 into Q. apply istep_query with Q Q'; vauto. (* right to left *) - inv STEP; clear STEP. + inv H; vauto. by apply cmd_neg_seq in H5. + inv H; vauto. + inv H; vauto. + inv H; vauto. + inv H; vauto. Qed. Lemma istep_seq_r : forall C P h s l h' s', step (Cseq Cskip C) h s l C h' s' <-> istep (Cseq Cskip C) P h s l C P h' s'. Proof. intros C P h s l h' s'. split; intro H1. (* left to right *) - induction l; vauto. + inv H1. inv H8. + inv H1. inv H8. + inv H1. inv H8. + inv H1. inv H8. (* right to left *) - induction l; vauto. + inv H1. + inv H1. + inv H1. + inv H1. + inv H1. Qed. Lemma istep_par_l : forall C1 C2 P h s l C1' P' h' s', istep C1 P h s l C1' P' h' s' <-> istep (Cpar C1 C2) P h s l (Cpar C1' C2) P' h' s'. Proof. intros C1 C2 P h s l C1' P' h' s'. split; intro H; inv H; clear H. - constructor; vauto. - apply istep_send with P'0 Q'; vauto. - apply istep_recv with P'0 Q'; vauto. - apply istep_comm with P'0 Q'; vauto. - apply istep_query with P'0 Q'; vauto. - inv H0; clear H0. + constructor; vauto. + apply prog_sos_neg_C in H10. vauto. - apply istep_send with P'0 Q'; vauto. inv H0; clear H0. by apply prog_sos_neg_C in H12. - apply istep_recv with P'0 Q'; vauto. inv H0; clear H0. by apply prog_sos_neg_C in H12. - apply istep_comm with P'0 Q'; vauto. inv H0; clear H0. + by apply prog_sos_neg_C in H12. + by apply prog_sos_neg_C in H14. + by apply prog_sos_neg_C in H14. - apply istep_query with P'0 Q'; vauto. inv H0; clear H0. by apply prog_sos_neg_C in H12. Qed. Lemma istep_par_r : forall C1 C2 P h s l C2' P' h' s', istep C2 P h s l C2' P' h' s' <-> istep (Cpar C1 C2) P h s l (Cpar C1 C2') P' h' s'. Proof. intros C1 C2 P h s l C2' P' h' s'. split; intro H; inv H; clear H. - constructor; vauto. - apply istep_send with P'0 Q'; vauto. - apply istep_recv with P'0 Q'; vauto. - apply istep_comm with P'0 Q'; vauto. - apply istep_query with P'0 Q'; vauto. - inv H0; clear H0. + by apply prog_sos_neg_C in H10. + constructor; vauto. - apply istep_send with P'0 Q'; vauto. inv H0; clear H0. by apply prog_sos_neg_C in H12. - apply istep_recv with P'0 Q'; vauto. inv H0; clear H0. by apply prog_sos_neg_C in H12. - apply istep_comm with P'0 Q'; vauto. inv H0; clear H0. + by apply prog_sos_neg_C in H12. + by apply prog_sos_neg_C in H13. + by apply prog_sos_neg_C in H13. - apply istep_query with P'0 Q'; vauto. inv H0; clear H0. by apply prog_sos_neg_C in H12. Qed. Lemma istep_bisim_l : forall C P1 P2 h s l C' Q h' s', bisim P1 P2 -> istep C P1 h s l C' Q h' s' -> istep C P2 h s l C' Q h' s'. Proof. intros C P1 P2 h s l C' Q h' s' H1 H2. inv H2; vauto. - apply istep_comp; auto. by rewrite <- H1. - apply istep_send with P' Q'; auto. by rewrite <- H1. - apply istep_recv with P' Q'; auto. by rewrite <- H1. - apply istep_comm with P' Q'; auto. by rewrite <- H1. - apply istep_query with P' Q'; auto. by rewrite <- H1. Qed. Lemma istep_bisim_r : forall C P h s l C' Q1 Q2 h' s', bisim Q1 Q2 -> istep C P h s l C' Q1 h' s' -> istep C P h s l C' Q2 h' s'. Proof. intros C P h s l C' Q1 Q2 h' s' H1 H2. inv H2; vauto. - apply istep_comp; auto. by rewrite <- H1. - apply istep_send with P' Q'; auto. by rewrite <- H1. - apply istep_recv with P' Q'; auto. by rewrite <- H1. - apply istep_comm with P' Q'; auto. by rewrite <- H1. - apply istep_query with P' Q'; auto. by rewrite <- H1. Qed. Add Parametric Morphism : istep with signature eq ==> bisim ==> eq ==> eq ==> eq ==> eq ==> bisim ==> eq ==> eq ==> iff as istep_bisim_mor. Proof. intros C P1 P2 H1 h s l C' Q1 Q2 H2 h' s'. split; intro H3. - apply istep_bisim_l with P1; auto. apply istep_bisim_r with Q1; auto. - apply istep_bisim_l with P2; auto. apply istep_bisim_r with Q2; auto. Qed. Lemma istep_proc_frame : forall C P Q h s l C' P' h' s', istep C P h s l C' P' h' s' -> istep C (Ppar P Q) h s l C' (Ppar P' Q) h' s'. Proof. intros C P1 Q h s l C' P1' h' s' H. inv H; vauto. - apply istep_comp; auto. by rewrite H1. - apply istep_send with (Ppar P' Q)(Ppar Q' Q); auto. + by rewrite H1. + by apply pstep_par_frame_l. + by rewrite H3. - apply istep_recv with (Ppar P' Q)(Ppar Q' Q); auto. + by rewrite H1. + by apply pstep_par_frame_l. + by rewrite H3. - apply istep_comm with (Ppar P' Q)(Ppar Q' Q); auto. + by rewrite H1. + by apply pstep_par_frame_l. + by rewrite H3. - apply istep_query with (Ppar P' Q)(Ppar Q' Q); auto. + by rewrite H1. + by apply pstep_par_frame_l. + by rewrite H3. Qed. Lemma istep_fv_mod : forall l C h P s C' h' P' s', istep C P h s l C' P' h' s' -> (forall x, In x (cmd_fv C') -> In x (cmd_fv C)) /\ (forall x, In x (cmd_mod C') -> In x (cmd_mod C)) /\ (forall x, ~ In x (cmd_mod C) -> s x = s' x). Proof. induction l; intros C h P s C' h' P' s'; intros STEP. - inv STEP. repeat split; vauto. + intros x H3. apply step_fv_mod in H0. destruct H0 as (M1 & M2 & M3). by apply M1. + intros x H3. apply step_fv_mod in H0. destruct H0 as (M1 & M2 & M3). by apply M2. + intros x H3. apply step_fv_mod in H0. destruct H0 as (M1 & M2 & M3). by apply M3. - inv STEP. repeat split; vauto. + intros x H3. apply step_fv_mod in H1. destruct H1 as (M1 & M2 & M3). by apply M1. + intros x H3. apply step_fv_mod in H1. destruct H1 as (M1 & M2 & M3). by apply M2. + intros x H3. apply step_fv_mod in H1. destruct H1 as (M1 & M2 & M3). by apply M3. - inv STEP. repeat split; vauto. + intros x H3. apply step_fv_mod in H1. destruct H1 as (M1 & M2 & M3). by apply M1. + intros x H3. apply step_fv_mod in H1. destruct H1 as (M1 & M2 & M3). by apply M2. + intros x H3. apply step_fv_mod in H1. destruct H1 as (M1 & M2 & M3). by apply M3. - inv STEP. repeat split; vauto. + intros x H3. apply step_fv_mod in H1. destruct H1 as (M1 & M2 & M3). by apply M1. + intros x H3. apply step_fv_mod in H1. destruct H1 as (M1 & M2 & M3). by apply M2. + intros x H3. apply step_fv_mod in H1. destruct H1 as (M1 & M2 & M3). by apply M3. - inv STEP. repeat split; vauto. + intros x H3. apply step_fv_mod in H. destruct H as (M1 & M2 & M3). by apply M1. + intros x H3. apply step_fv_mod in H. destruct H as (M1 & M2 & M3). by apply M2. + intros x H3. apply step_fv_mod in H. destruct H as (M1 & M2 & M3). by apply M3. Qed. Lemma istep_agree : forall l C h P s1 s2 C' h' P' s1' (phi : Var -> Prop), (forall x, In x (cmd_fv C) -> phi x) -> (forall x, phi x -> s1 x = s2 x) -> istep C P h s1 l C' P' h' s1' -> exists s2', (forall x, phi x -> s1' x = s2' x) /\ istep C P h s2 l C' P' h' s2'. Proof. induction l; intros C h P1 s1 s2 C' h' P1' s1' phi H1 H2 STEP. - inv STEP. apply step_agree with (s2 := s2)(phi := phi) in H0; auto. destruct H0 as (s2' & H5 & H6). exists s2'. intuition. apply istep_query with (P' := P')(Q' := Q'); auto. - inv STEP. apply step_agree with (s2 := s2)(phi := phi) in H3; auto. destruct H3 as (s2' & H5 & H6). exists s2'. intuition. apply istep_send with (P' := P')(Q' := Q'); auto. - inv STEP. apply step_agree with (s2 := s2)(phi := phi) in H3; auto. destruct H3 as (s2' & H5 & H6). exists s2'. intuition. apply istep_recv with (P' := P')(Q' := Q'); auto. - inv STEP. apply step_agree with (s2 := s2)(phi := phi) in H3; auto. destruct H3 as (s2' & H5 & H6). exists s2'. intuition. apply istep_comm with (P' := P')(Q' := Q'); auto. - inv STEP. apply step_agree with (s2 := s2)(phi := phi) in H; auto. destruct H as (s2' & H5 & H6). exists s2'. intuition vauto. Qed. Lemma istep_agree_sim : forall C h P s1 s2 l C' h' P' s1' s2', (forall x, In x (cmd_fv C) -> s1 x = s2 x) -> (forall x, In x (cmd_fv C) -> s1' x = s2' x) -> step C h s1 l C' h' s1' -> istep C P h s2 l C' P' h' s2' -> istep C P h s1 l C' P' h' s1'. Proof. induction C; intros h P s1 s2 l C' h' P' s1' s2' H1 H2 H3 H4. (* skip *) - inv H3. (* sequential composition *) - inv H3; clear H3. + rewrite <- istep_seq_l. apply IHC1 with s2 s2'; vauto. * intros x D1. apply H1. simpl. apply in_or_app. by left. * intros x D1. apply H2. simpl. apply in_or_app. by left. * by rewrite <- istep_seq_l in H4. + apply istep_comp_proc_pres in H4. rewrite <- H4. rewrite <- istep_seq_r. constructor. (* assignment *) - inv H3. constructor; vauto. by apply istep_comp_proc_pres in H4. (* heap reading *) - inv H3. constructor; vauto. by apply istep_comp_proc_pres in H4. (* heap writing *) - inv H3. constructor; vauto. by apply istep_comp_proc_pres in H4. (* if-then-else *) - inv H3; clear H3. + inv H4. clear H4. constructor; vauto. + inv H4. clear H4. constructor; vauto. (* while loops *) - inv H3. clear H3. inv H4. clear H4. constructor; vauto. (* parallel composition *) - inv H3; clear H3. + apply istep_par_l. apply IHC1 with s2 s2'; vauto. * intros x D1. apply H1. simpl. apply in_or_app. by left. * intros x D1. apply H2. simpl. apply in_or_app. by left. * by apply istep_par_l in H4. + apply istep_par_r. apply IHC2 with s2 s2'; vauto. * intros x D1. apply H1. simpl. apply in_or_app. by right. * intros x D1. apply H2. simpl. apply in_or_app. by right. * by apply istep_par_r in H4. + constructor; vauto. inv H4. + inv H4. clear H4. apply istep_comm with P'0 Q'; vauto. + inv H4. clear H4. apply istep_comm with P'0 Q'; vauto. (* heap allocation *) - inv H3. clear H3. constructor; vauto. inv H4. (* heap disposal *) - inv H3. clear H3. constructor; vauto. inv H4. (* sending *) - inv H3. clear H3. inv H4. clear H4. apply istep_send with P'0 Q'; vauto. (* receiving *) - inv H3. clear H3. inv H4. clear H4. apply istep_recv with P'0 Q'; vauto. - inv H3. clear H3. inv H4. clear H4. apply istep_recv with P'0 Q'; vauto. (* querying *) - inv H3. clear H3. inv H4. clear H4. apply istep_query with P'0 Q'; vauto. Qed. (** ** Adequacy *) Definition heap_preserve (l: Label)(ph1 ph2: PermHeap): Prop := match l with | Lsend _ _ => ph1 = ph2 | _ => True end. CoInductive safe (C: Cmd)(ph: PermHeap)(P: Proc)(s: Store)(A: Assn): Prop := | safe_prog : (* terminating programs satisfy the postcondition *) (C = Cskip -> sat ph P s A) /\ (* computation preserves safety *) (forall phF C' h' s' l, permheap_disj ph phF -> let h := permheap_concr (permheap_add ph phF) in heap_finite h -> psafe P -> step C h s l C' h' s' -> exists ph', heap_preserve l ph ph' /\ permheap_disj ph' phF /\ permheap_concr (permheap_add ph' phF) = h' /\ heap_finite h' /\ exists P', psafe P' /\ istep C P h s l C' P' h' s' /\ safe C' ph' P' s' A) -> safe C ph P s A. Lemma safe_skip : forall ph P s A, sat ph P s A <-> safe Cskip ph P s A. Proof. intros ph P s A. split; intro H1. - constructor. split; vauto. intros ????????? STEP. inv STEP. - inv H1. clear H1. destruct H as (H & _). by apply H. Qed. Lemma safe_agree : forall C ph P s1 s2 A, (forall x, assn_fv A x -> s1 x = s2 x) -> (forall x, In x (cmd_fv C) -> s1 x = s2 x) -> safe C ph P s1 A -> safe C ph P s2 A. Proof. cofix CH. intros C ph P s1 s2 A H1 H2 H3. repeat split. (* termination *) - intro H4. clarify. apply sat_agree with s1; auto. by apply safe_skip in H3. (* computation *) - simpl. intros phF C' h' s' l H4 H5 H6 STEP. generalize STEP. intro STEP'. apply step_agree with (s2 := s1)(phi := fun x => In x (cmd_fv C) \/ assn_fv A x) in STEP; vauto. 2 : { intros x [H7 | H7]. + symmetry. by apply H2. + symmetry. by apply H1. } destruct STEP as (s2' & H7 & H8). inv H3. clear H3. destruct H as (_ & H). simpl in H. apply H in H8; vauto. clear H. destruct H8 as (ph' & D1 & D2 & D3 & D4 & P' & D5 & D6 & D7). exists ph'. intuition. exists P'. intuition. + apply istep_agree with (s2 := s2)(phi := fun x => In x (cmd_fv C) \/ assn_fv A x) in D6; vauto. destruct D6 as (s3 & D6 & D8). apply istep_agree_sim with s2 s3; vauto. * intros x S1. rewrite H7; vauto. apply D6. by left. * intros x [S1 | S1]. ** apply H2. vauto. ** apply H1. vauto. + apply CH with s2'; vauto. * intros x S1. symmetry. apply H7. vauto. * intros x S1. symmetry. apply H7. vauto. left. apply step_fv_mod in STEP'. destruct STEP' as (STEP' & _). by apply STEP'. Qed. Lemma safe_bisim : forall C ph P1 P2 s A, bisim P1 P2 -> safe C ph P1 s A -> safe C ph P2 s A. Proof. intros C ph P1 P2 s A H1 H2. repeat split. (* termination *) - intro H3. clarify. rewrite <- safe_skip in H2. by rewrite <- H1. (* computation *) - simpl. intros phF C' h' s' l H3 H4 H5 H6. inv H2. clear H2. destruct H as (_ & H2). apply H2 in H6; clear H2; vauto. 2 : { by rewrite H1. } destruct H6 as (ph' & D1 & D2 & D3 & D4 & P' & D5 & D6 & D7). exists ph'. intuition. exists P'. intuition. by rewrite <- H1. Qed. Add Parametric Morphism : safe with signature eq ==> eq ==> bisim ==> eq ==> eq ==> iff as safe_mor. Proof. intros C ph P1 P2 H1 s A. split; intro H2. - apply safe_bisim with P1; auto. - apply safe_bisim with P2; auto. Qed. (** ** Proof rules *) Definition csl (A1: Assn)(C: Cmd)(A2: Assn): Prop := forall ph P s, permheap_valid ph -> sat ph P s A1 -> safe C ph P s A2. (** *** Skip *) Theorem rule_skip : forall A, csl A Cskip A. Proof. intros A ph P s H1 H2. by apply safe_skip. Qed. (** *** Sequential composition *) Lemma safe_seq : forall C1 C2 A1 A2 ph P s, permheap_valid ph -> safe C1 ph P s A1 -> (forall ph' P' s', permheap_valid ph' -> sat ph' P' s' A1 -> safe C2 ph' P' s' A2) -> safe (Cseq C1 C2) ph P s A2. Proof. cofix CH. intros C1 C2 A1 A2 ph P s H1 H2 H3. constructor. split. (* termination *) - intro H4. vauto. (* computation *) - simpl. intros phF C' h' s' l H4 H5 H6 STEP. inv STEP; clear STEP. (* step in [C1] *) + apply H2 in H13; auto. clear H2. destruct H13 as (ph'&D1&D2&D3&D4&P'&D5&D6&D7). exists ph'. intuition. exists P'. intuition. * rewrite <- istep_seq_l; auto. * apply CH with A1; auto. by apply permheap_disj_valid_l in D2. (* [C1] terminated *) + exists ph. intuition. exists P. intuition. * rewrite <- istep_seq_r; vauto. * apply H3; auto. by apply safe_skip in H2. Qed. Theorem rule_seq : forall A1 A2 A3 C1 C2, csl A1 C1 A2 -> csl A2 C2 A3 -> csl A1 (Cseq C1 C2) A3. Proof. cofix CH. intros A1 A2 A3 C1 C2 H1 H2. red. intros ph P s H3 H4. apply safe_seq with A2; auto. Qed. (** *** If-then-else *) Lemma safe_ite : forall A1 A2 B C1 C2 ph P s, sat ph P s A1 -> (sat ph P s (Astar A1 (Aplain B)) -> safe C1 ph P s A2) -> (sat ph P s (Astar A1 (Aplain (Bnot B))) -> safe C2 ph P s A2) -> safe (Cite B C1 C2) ph P s A2. Proof. intros A1 A2 B C1 C2 ph P s H1 H2 H3. constructor. split; vauto. simpl. intros phF C' h' s' l H4 H5 H6 STEP. inv STEP; clear STEP; vauto. (* [B] evaluates positively *) - exists ph. intuition. exists P. intuition vauto. apply H2. simpl. exists ph, permheap_iden. intuition auto. { apply permheap_disj_iden_l. by apply permheap_disj_valid_l in H4. } { by rewrite permheap_add_iden_l. } exists P, Pepsilon. intuition. rewrite par_epsilon_r. auto. (* [B] evaluates negatively *) - exists ph. intuition. exists P. intuition vauto. apply H3. simpl. exists ph, permheap_iden. intuition vauto. { apply permheap_disj_iden_l. by apply permheap_disj_valid_l in H4. } { by rewrite permheap_add_iden_l. } exists P, Pepsilon. intuition. rewrite par_epsilon_r. auto. Qed. Theorem rule_ite : forall A1 A2 B C1 C2, csl (Astar A1 (Aplain B)) C1 A2 -> csl (Astar A1 (Aplain (Bnot B))) C2 A2 -> csl A1 (Cite B C1 C2) A2. Proof. intros A1 A2 B C1 C2 H1 H2. red. intros ph P s H3 H4. apply safe_ite with A1; auto. Qed. (** *** While loops *) Lemma safe_while1 : forall B C1 C2 ph P s A, safe C1 ph P s A -> csl (Astar A (Aplain B)) C2 A -> safe (Cseq C1 (Cwhile B C2)) ph P s (Astar A (Aplain (Bnot B))). Proof. cofix CH. intros B C1 C2 ph P s A H1 H2. constructor. split; vauto. simpl. intros phF C' h' s' l H3 H4 H5 STEP. inv STEP; clear STEP. (* step in [C1] *) - apply H1 in H12; auto. destruct H12 as (ph'&D1&D2&D3&D4&P'&D5&D6&D7). exists ph'. intuition. exists P'. intuition. by apply istep_seq_l. (* [C1] terminated *) - exists ph. intuition. exists P. intuition vauto. apply safe_skip in H1. constructor. split; vauto. simpl. intros phF' C' h' s'' l D1 D2 D3 STEP. inv STEP; clear STEP. exists ph. intuition. exists P. intuition vauto. constructor. split; vauto. simpl. intros phF'' C' h' s' l F1 F2 F3 STEP. inv STEP; clear STEP. (* step in [C2] *) + exists ph. intuition. exists P. intuition vauto. apply CH; auto. apply H2; auto. { by apply permheap_disj_valid_l in F1. } exists ph, permheap_iden. intuition. { apply permheap_disj_iden_l. by apply permheap_disj_valid_l in F1. } { by rewrite permheap_add_iden_l. } exists P, Pepsilon. intuition. by apply par_epsilon_r. (* termination of the loop *) + exists ph. intuition. exists P. intuition vauto. apply safe_skip. exists ph, permheap_iden. intuition. { apply permheap_disj_iden_l. by apply permheap_disj_valid_l in F1. } { by rewrite permheap_add_iden_l. } exists P, Pepsilon. intuition vauto. { by apply par_epsilon_r. } simpl. apply eq_true_not_negb. vauto. Qed. Lemma safe_while2 : forall B C ph P s A, csl (Astar A (Aplain B)) C A -> sat ph P s A -> safe (Cwhile B C) ph P s (Astar A (Aplain (Bnot B))). Proof. intros B C ph P s A H1 H2. constructor. split; vauto. simpl. intros phF C' h' s' l H3 H4 H5 STEP. inv STEP. clear STEP. exists ph. intuition. exists P. intuition vauto. apply safe_ite with A; auto. (* any loop iteration must be safe *) - intro H6. apply safe_while1; auto. apply H1; auto. by apply permheap_disj_valid_l in H3. (* safety must be preserved after termination of the loop *) - intro H6. by apply safe_skip. Qed. Theorem rule_while : forall A B C, csl (Astar A (Aplain B)) C A -> csl A (Cwhile B C) (Astar A (Aplain (Bnot B))). Proof. intros A B C CSL. red. intros ph P s H1 H2. apply safe_while2; auto. Qed. (** *** Assignment *) Lemma safe_assign : forall A x E ph P s, sat ph P s (assn_subst x E A) -> safe (Cass x E) ph P s A. Proof. cofix CH. intros A x E ph P s H1. repeat split; vauto. simpl. intros phF C' h' s' l H2 H3 H4 STEP. inv STEP. exists ph. intuition. exists P. intuition vauto. apply safe_skip. rewrite sat_subst in H1. vauto. Qed. Theorem rule_assign : forall A x E, csl (assn_subst x E A) (Cass x E) A. Proof. ins. red. split; vauto. ins. by apply safe_assign. Qed. (** *** Framing *) Lemma safe_frame : forall C ph1 ph2 P1 P2 s A1 A2, permheap_disj ph1 ph2 -> disjoint (assn_fv A2) (cmd_mod C) -> sat ph2 P2 s A2 -> safe C ph1 P1 s A1 -> safe C (permheap_add ph1 ph2) (Ppar P1 P2) s (Astar A1 A2). Proof. cofix CH. intros C ph1 ph2 P1 P2 s A1 A2 H1 FV1 SAT1 SAFE1. repeat split. (* termination *) - intros ?. clarify. apply safe_skip in SAFE1. exists ph1, ph2. intuition. exists P1, P2. intuition. (* computation *) - simpl. intros phF C' h' s' l H2 H3 SAFE2 STEP. inv SAFE1. clear SAFE1. destruct H as (_ & SAFE1). rewrite permheap_add_swap_r with (ph2 := ph2) in STEP. rewrite permheap_add_assoc in STEP. rewrite permheap_add_comm with phF ph2 in STEP. apply SAFE1 in STEP; clear SAFE1; vauto. + destruct STEP as (ph' & D1 & D2 & D3 & D4 & P' & D5 & D6 & D7). clarify. exists (permheap_add ph' ph2). intuition. { red in D1. desf. } { apply permheap_disj_assoc_r; auto. apply permheap_disj_add_l with ph1; auto. } { rewrite permheap_add_swap_r with (ph2 := ph2). rewrite permheap_add_assoc. by rewrite permheap_add_comm with phF ph2. } exists (Ppar P' P2). intuition. { apply psafe_par_rev in SAFE2. destruct SAFE2 as (_ & SAFE2). by apply psafe_par. } { rewrite permheap_add_swap_r with (ph2 := ph2). rewrite permheap_add_assoc. rewrite permheap_add_comm with phF ph2. by apply istep_proc_frame. } apply CH; vauto. { apply permheap_disj_add_r with phF; auto. apply permheap_disj_add_l with ph1; auto. } { red. intros x H7 H8. apply istep_fv_mod in D6. destruct D6 as (FV2 & FV3 & FV4). apply FV1 in H7. by apply FV3 in H8. } { apply istep_fv_mod in D6. destruct D6 as (FV2 & FV3 & FV4). apply sat_agree with s; auto. intros x ?. apply FV4. intro. by apply FV1 with x. } + apply permheap_disj_assoc_l; auto. + by rewrite <- permheap_add_assoc. + apply psafe_par_rev in SAFE2. desf. Qed. Theorem rule_frame : forall A1 A2 A3 C, disjoint (assn_fv A3) (cmd_mod C) -> csl A1 C A2 -> csl(Astar A1 A3) C (Astar A2 A3). Proof. intros A1 A2 A3 C H1 H2. red. intros ph P s H3 H4. simpl in H4. destruct H4 as (ph1&ph2&H4&H5&P1&P2&H6&H7&H8). rewrite <- H5, <- H6. apply safe_frame; vauto. apply H2; vauto. by apply permheap_disj_valid_l in H4. Qed. (** *** Parallel composition *) Lemma safe_par : forall C1 C2 ph1 ph2 P1 P2 s A1 A2, permheap_disj ph1 ph2 -> disjoint (cmd_fv C1) (cmd_mod C2) -> disjoint (assn_fv A1) (cmd_mod C2) -> disjoint (cmd_fv C2) (cmd_mod C1) -> disjoint (assn_fv A2) (cmd_mod C1) -> safe C1 ph1 P1 s A1 -> safe C2 ph2 P2 s A2 -> safe (Cpar C1 C2) (permheap_add ph1 ph2) (Ppar P1 P2) s (Astar A1 A2). Proof. cofix CH. intros C1 C2 ph1 ph2 P1 P2 s A1 A2 H1 H2 H3 H4 H5 SAFE1 SAFE2. repeat split. (* termination *) - intro H8. clarify. (* computation *) - simpl. intros phF C' h' s' l H6 H7 SAFE3 STEP. inv STEP; clear STEP. (* step in left program *) + inv SAFE1. clear SAFE1. destruct H as (_ & H). simpl in H. specialize H with (permheap_add ph2 phF) C1' h' s' l. rewrite permheap_add_assoc in H14. apply H in H14; clear H. 2:{ apply permheap_disj_assoc_l; auto. } 2:{ rewrite <- permheap_add_assoc. auto. } 2:{ apply psafe_par_rev in SAFE3. desf. } destruct H14 as (ph' & D1 & D2 & D3 & D4 & P' & D5 & D6 & D7). exists (permheap_add ph' ph2). intuition. { red in D1. desf. } { apply permheap_disj_assoc_r; auto. apply permheap_disj_add_l with ph1; auto. } { by rewrite permheap_add_assoc. } exists (Ppar P' P2). intuition. { apply psafe_par_rev in SAFE3. destruct SAFE3 as (_ & SAFE3). apply psafe_par; auto. } { clarify. rewrite permheap_add_assoc with ph1 ph2 phF. apply istep_par_l. apply istep_proc_frame. auto. } apply CH; auto. { apply permheap_disj_add_r with phF; auto. apply permheap_disj_add_l with ph1; auto. } { red. intros x FV1 FV2. apply istep_fv_mod in D6. destruct D6 as (D6 & _). apply D6 in FV1. by apply H2 with x. } { red. intros x FV1 FV2. apply istep_fv_mod in D6. destruct D6 as (_ & D6 & _). apply D6 in FV2. by apply H4 with x. } { red. intros x FV1 FV2. apply istep_fv_mod in D6. destruct D6 as (_ & D6 & _). apply D6 in FV2. by apply H5 with x. } apply safe_agree with s; vauto. { intros x S1. apply istep_fv_mod in D6. destruct D6 as (_ & _ & D6). apply D6. intro S2. red in H5. apply H5 with x; vauto. } { intros x S1. apply istep_fv_mod in D6. destruct D6 as (_ & _ & D6). apply D6. intro S2. red in H4. apply H4 with x; vauto. } (* step in right program *) + inv SAFE2. clear SAFE2. destruct H as (_ & H). simpl in H. specialize H with (permheap_add ph1 phF) C2' h' s' l. rewrite permheap_add_comm with ph1 ph2 in H14. rewrite permheap_add_assoc in H14. apply H in H14; clear H. 2:{ apply permheap_disj_assoc_l; auto. by rewrite permheap_add_comm. } 2:{ rewrite <- permheap_add_assoc. by rewrite permheap_add_comm with ph2 ph1. } 2:{ apply psafe_par_rev in SAFE3. desf. } destruct H14 as (ph' & D1 & D2 & D3 & D4 & P' & D5 & D6 & D7). exists (permheap_add ph1 ph'). intuition. { red in D1. desf. } { rewrite permheap_add_comm. apply permheap_disj_assoc_r; auto. apply permheap_disj_add_l with ph2; auto. by rewrite permheap_add_comm. } { rewrite permheap_add_comm with ph1 ph'. by rewrite permheap_add_assoc. } exists (Ppar P1 P'). intuition. { apply psafe_par_rev in SAFE3. destruct SAFE3 as (SAFE3 & _). apply psafe_par; auto. } { clarify. rewrite permheap_add_comm with ph1 ph2. rewrite permheap_add_assoc with ph2 ph1 phF. apply istep_par_r. rewrite par_comm with (P := P1)(Q := P2). rewrite par_comm with (P := P1)(Q := P'). apply istep_proc_frame. auto. } apply CH; auto. { symmetry. apply permheap_disj_add_r with phF; auto. apply permheap_disj_add_l with ph2; auto. by rewrite permheap_add_comm. } { red. intros x FV1 FV2. apply istep_fv_mod in D6. destruct D6 as (_ & D6 & _). apply D6 in FV2. by apply H2 with x. } { red. intros x FV1 FV2. apply istep_fv_mod in D6. destruct D6 as (_ & D6 & _). apply D6 in FV2. by apply H3 with x. } { red. intros x FV1 FV2. apply istep_fv_mod in D6. destruct D6 as (D6 & _ & _). apply D6 in FV1. by apply H4 with x. } apply safe_agree with s; vauto. { intros x S1. apply istep_fv_mod in D6. destruct D6 as (_ & _ & D6). apply D6. intro S2. red in H3. apply H3 with x; vauto. } { intros x S1. apply istep_fv_mod in D6. destruct D6 as (_ & _ & D6). apply D6. intro S2. red in H2. apply H2 with x; vauto. } (* both programs are empty *) + exists (permheap_add ph1 ph2). intuition. exists (Ppar P1 P2). intuition. * constructor; vauto. * apply safe_skip. simpl. exists ph1, ph2. intuition. exists P1, P2. intuition. ** inv SAFE1. clear SAFE1. destruct H as (H & _). by apply H. ** inv SAFE2. clear SAFE2. destruct H as (H & _). by apply H. (* communication: left program sends, right program receives *) + inv SAFE1. clear SAFE1. destruct H as (_ & SAFE1). simpl in SAFE1. repeat rewrite permheap_add_assoc in H8. apply SAFE1 in H8; clear SAFE1; vauto. 2:{ apply permheap_disj_assoc_l; vauto. } 2:{ by rewrite <- permheap_add_assoc. } 2:{ apply psafe_par_rev in SAFE3. desf. } destruct H8 as (ph1' & D1 & D2 & D3 & D4 & P1' & D5 & D6 & D7). simpl in D1. clarify. rename ph1' into ph1. clear D3. inv SAFE2. clear SAFE2. destruct H as (_ & SAFE2). simpl in SAFE2. repeat rewrite permheap_add_comm with ph1 ph2 in H15. repeat rewrite permheap_add_assoc in H15. apply SAFE2 in H15; clear SAFE2. 2:{ apply permheap_disj_assoc_l. - by symmetry. - by rewrite permheap_add_comm with ph2 ph1. } 2:{ rewrite <- permheap_add_assoc. by rewrite permheap_add_comm with ph2 ph1. } 2:{ apply psafe_par_rev in SAFE3. desf. } destruct H15 as (ph2' & F1 & F2 & F3 & F4 & P2' & F5 & F6 & F7). simpl in F1. clear F1. exists (permheap_add ph1 ph2'). intuition. { red. vauto. } { rewrite permheap_add_comm. apply permheap_disj_assoc_r; auto. apply permheap_disj_add_l with ph2; auto. by rewrite permheap_add_comm. } { rewrite permheap_add_comm with ph1 ph2'. rewrite permheap_add_assoc. rewrite F3. rewrite <- permheap_add_assoc. by rewrite permheap_add_comm with ph2 ph1. } exists (Ppar P1' P2'). intuition. { apply psafe_par; vauto. } { inv D6. clear D6. inv F6. clear F6. rename P'0 into Q2, Q'0 into Q2'. rename P' into Q1, Q' into Q1'. apply istep_comm with (Ppar Q1 Q2) (Ppar Q1' Q2'); vauto. - apply step_comm_l; vauto. + by repeat rewrite permheap_add_assoc. + repeat rewrite permheap_add_comm with ph1 ph2. by repeat rewrite permheap_add_assoc. - apply bisim_par; vauto. - apply bisim_par; vauto. } apply CH; vauto. { symmetry. apply permheap_disj_add_r with phF; auto. apply permheap_disj_add_l with ph2; auto. by rewrite permheap_add_comm. } { red. intros x FV1 FV2. apply istep_fv_mod in D6. destruct D6 as (D6 & _). apply istep_fv_mod in F6. destruct F6 as (_ & F6 & _). apply D6 in FV1. apply F6 in FV2. by apply H2 with x. } { red. intros x FV1 FV2. apply istep_fv_mod in F6. destruct F6 as (_ & F6 & _). apply F6 in FV2. by apply H3 with x. } { red. intros x FV1 FV2. apply istep_fv_mod in D6. destruct D6 as (_ & D6 & _). apply istep_fv_mod in F6. destruct F6 as (F6 & _). apply D6 in FV2. apply F6 in FV1. by apply H4 with x. } { red. intros x FV1 FV2. apply istep_fv_mod in D6. destruct D6 as (_ & D6 & _). apply D6 in FV2. by apply H5 with x. } apply safe_agree with s; vauto. { intros x FV1. apply istep_fv_mod in F6. destruct F6 as (_ & _ & F6). apply F6. intro FV2. by apply H3 with x. } { intros x FV1. apply istep_fv_mod in F6. destruct F6 as (_ & _ & F6). apply F6. intro FV2. apply istep_fv_mod in D6. destruct D6 as (D6 & _). apply D6 in FV1. by apply H2 with x. } (* communication: right program sends, left program receives *) + inv SAFE1. clear SAFE1. destruct H as (_ & SAFE1). simpl in SAFE1. repeat rewrite permheap_add_assoc in H8. apply SAFE1 in H8; clear SAFE1; vauto. 2:{ apply permheap_disj_assoc_l; vauto. } 2:{ by rewrite <- permheap_add_assoc. } 2:{ apply psafe_par_rev in SAFE3. desf. } destruct H8 as (ph1' & D1 & D2 & D3 & D4 & P1' & D5 & D6 & D7). simpl in D1. clear D1. inv SAFE2. clear SAFE2. destruct H as (_ & SAFE2). simpl in SAFE2. repeat rewrite permheap_add_comm with ph1 ph2 in H15. repeat rewrite permheap_add_assoc in H15. apply SAFE2 in H15; clear SAFE2. 2:{ apply permheap_disj_assoc_l. - by symmetry. - by rewrite permheap_add_comm with ph2 ph1. } 2:{ rewrite <- permheap_add_assoc. by rewrite permheap_add_comm with ph2 ph1. } 2:{ apply psafe_par_rev in SAFE3. desf. } destruct H15 as (ph2' & F1 & F2 & F3 & F4 & P2' & F5 & F6 & F7). simpl in F1. clarify. rename ph2' into ph2. clear F3. exists (permheap_add ph1' ph2). intuition. { red. vauto. } { apply permheap_disj_assoc_r; auto. by apply permheap_disj_add_l with ph1. } { by repeat rewrite permheap_add_assoc. } exists (Ppar P1' P2'). intuition. { apply psafe_par; vauto. } { inv D6. clear D6. inv F6. clear F6. rename P'0 into Q2, Q'0 into Q2'. rename P' into Q1, Q' into Q1'. apply istep_comm with (Ppar Q1 Q2) (Ppar Q1' Q2'); vauto. - apply step_comm_r; vauto. + by repeat rewrite permheap_add_assoc. + repeat rewrite permheap_add_comm with ph1 ph2. by repeat rewrite permheap_add_assoc. - apply bisim_par; vauto. - apply bisim_par; vauto. } apply CH; vauto. { apply permheap_disj_add_r with phF; auto. apply permheap_disj_add_l with ph1; auto. } { red. intros x FV1 FV2. apply istep_fv_mod in D6. destruct D6 as (D6 & _). apply istep_fv_mod in F6. destruct F6 as (_ & F6 & _). apply D6 in FV1. apply F6 in FV2. by apply H2 with x. } { red. intros x FV1 FV2. apply istep_fv_mod in F6. destruct F6 as (_ & F6 & _). apply F6 in FV2. by apply H3 with x. } { red. intros x FV1 FV2. apply istep_fv_mod in D6. destruct D6 as (_ & D6 & _). apply istep_fv_mod in F6. destruct F6 as (F6 & _). apply D6 in FV2. apply F6 in FV1. by apply H4 with x. } { red. intros x FV1 FV2. apply istep_fv_mod in D6. destruct D6 as (_ & D6 & _). apply D6 in FV2. by apply H5 with x. } apply safe_agree with s; vauto. { intros x FV1. apply istep_fv_mod in D6. destruct D6 as (_ & _ & D6). apply D6. intro FV2. by apply H5 with x. } { intros x FV1. apply istep_fv_mod in D6. destruct D6 as (_ & _ & D6). apply D6. intro FV2. apply istep_fv_mod in F6. destruct F6 as (F6 & _). apply F6 in FV1. by apply H4 with x. } Qed. Theorem rule_par : forall C1 C2 A1 A2 A1' A2', disjoint (cmd_fv C1) (cmd_mod C2) -> disjoint (assn_fv A1') (cmd_mod C2) -> disjoint (cmd_fv C2) (cmd_mod C1) -> disjoint (assn_fv A2') (cmd_mod C1) -> csl A1 C1 A1' -> csl A2 C2 A2' -> csl (Astar A1 A2) (Cpar C1 C2) (Astar A1' A2'). Proof. intros C1 C2 A1 A2 A1' A2' FV1 FV2 FV3 FV4 CSL1 CSL2. red. intros ph P s H1 H2. simpl in H2. destruct H2 as (ph1 & ph2 & H2 & H3 & P1 & P2 & H4 & H5 & H6). clarify. rewrite <- H4. apply safe_par; vauto. - red in CSL1. apply CSL1 in H5; vauto. by apply permheap_disj_valid_l in H2. - red in CSL2. apply CSL2 in H6; vauto. by apply permheap_disj_valid_r in H2. Qed. (** *** Sending *) Theorem rule_send : forall E T AP, csl (Aproc (APseq (APsend E T) AP)) (Csend E T) (Aproc AP). Proof. intros E T AP ph P s H1 SAT1. constructor. split. (* termination *) - intros ?. vauto. (* computation *) - simpl. intros phF C' h' s' l H2 FIN1 SAFE1 STEP. inv STEP. rename v0 into v', s' into s. exists ph. intuition. destruct SAT1 as (P'' & H3). set (P' := Ppar (aproc_conv AP s) P''). exists P'. intuition. { rewrite H3 in SAFE1. apply psafe_par_rev in SAFE1. destruct SAFE1 as (SAFE1 & SAFE2). simpl in SAFE1. inv SAFE1. clear SAFE1. destruct H as (_ & SAFE1). subst P'. apply psafe_par; auto. assert (H4: pstep (Pseq (Psend (expr_conv E s) (expr_conv T s)) (aproc_conv AP s)) (PLsend (pexpr_eval (expr_conv E s)) (pexpr_eval (expr_conv T s))) (Pseq Pepsilon (aproc_conv AP s))) by vauto. apply SAFE1 in H4. clear SAFE1. rewrite pseq_epsilon_r in H4. simpls. } { inv STEP. clear H8. rewrite H3. subst P'. apply istep_proc_frame. apply istep_send with (P' := aproc_conv (APseq (APsend E T) AP) s) (Q' := aproc_conv (APseq APepsilon AP) s); auto. - repeat constructor. subst v'. rewrite expr_conv_eval. subst tag0. rewrite expr_conv_eval. constructor. - simpl. by rewrite pseq_epsilon_r. } inv STEP. clear H8. apply safe_skip. subst P'. exists P''. intuition. Qed. (** *** Receiving *) Theorem rule_recv1 : forall x1 x2 y1 y2 AP, ~ aproc_fv AP x1 -> ~ aproc_fv AP x2 -> ~ y1 = y2 -> ~ x1 = y2 -> ~ x2 = y1 -> ~ x1 = x2 -> csl (Aproc (APsigma y1 (APsigma y2 (APseq (APrecv (Evar y1) (Evar y2)) AP)))) (Crecv1 x1 x2) (Aproc (aproc_subst y2 (Evar x2) (aproc_subst y1 (Evar x1) AP))). Proof. intros x1 x2 y1 y2 AP H1 H2 V1 V2 V3 V4 ph P s H3 SAT1. constructor. split. (* termination *) - intros ?. vauto. (* computation *) - simpl. intros phF C' h' s' l H4 FIN1 SAFE1 STEP. inv STEP. exists ph. intuition. destruct SAT1 as (P'' & H5). assert (H6: pstep (aproc_conv (APsigma y1 (APsigma y2 (APseq (APrecv (Evar y1) (Evar y2)) AP))) s) (PLrecv v1 v2) (aproc_conv (aproc_subst y1 (Econst v1) (aproc_subst y2 (Econst v2) (APseq APepsilon AP))) s)). { simpl. desf. apply pstep_sum with v1, pstep_sum with v2. apply pstep_seq_l. simpl. desf. vauto. } assert (H7: aproc_conv (aproc_subst y2 (Evar x2) (aproc_subst y1 (Evar x1) AP)) (updatestore (updatestore s x1 v1) x2 v2) = aproc_conv (aproc_subst y1 (Econst v1) (aproc_subst y2 (Econst v2) AP)) s). { rewrite aproc_conv_subst_upd, aproc_conv_subst_upd_swap, aproc_conv_subst_upd; vauto. + intro H8. apply aproc_fv_subst_in in H8; vauto. + intro H7. apply V1. by symmetry. + intro H7. apply V2. by symmetry. + intro H8. apply aproc_fv_subst_in in H8; vauto. simpls. apply and_not_or. intuition. } set (P' := Ppar (aproc_conv (aproc_subst y2 (Evar x2) (aproc_subst y1 (Evar x1) AP)) (updatestore (updatestore s x1 v1) x2 v2)) P''). exists P'. intuition. { rewrite H5 in SAFE1. apply psafe_par_rev in SAFE1. destruct SAFE1 as (SAFE1 & SAFE2). inv SAFE1. clear SAFE1. destruct H as (_ & SAFE1). apply SAFE1 in H6. clear SAFE1. simpl in H6. rewrite pseq_epsilon_r in H6. subst P'. apply psafe_par; auto. rewrite H7; vauto. } { rewrite H5. subst P'. apply istep_proc_frame. apply istep_recv with (P' := aproc_conv (APsigma y1 (APsigma y2 (APseq (APrecv (Evar y1) (Evar y2)) AP))) s) (Q' := aproc_conv (APseq APepsilon (aproc_subst y2 (Evar x2) (aproc_subst y1 (Evar x1) AP))) (updatestore (updatestore s x1 v1) x2 v2)); auto. - rewrite aproc_conv_sigma. apply pstep_sum with v1. simpl. desf. clear e. apply pstep_sum with v2. simpl. desf. clear e. rewrite <- H7. vauto. - simpls. intuition. by rewrite pseq_epsilon_r. } apply safe_skip. subst P'. exists P''. apply bisim_par; intuition. Qed. Theorem rule_recv2 : forall x y T AP, ~ aproc_fv AP x -> ~ In y (expr_fv T) -> csl (Aproc (APsigma y (APseq (APrecv (Evar y) T) AP))) (Crecv2 x T) (Aproc (aproc_subst y (Evar x) AP)). Proof. intros x y T AP H1 H2 ph P s H3 SAT1. constructor. split. (* termination *) - intros ?. vauto. (* computation *) - simpl. intros phF C' h' s' l H4 FIN1 SAFE1 STEP. inv STEP. exists ph. intuition. destruct SAT1 as (P'' & H5). set (P' := Ppar (aproc_conv (aproc_subst y (Evar x) AP) (updatestore s x v)) P''). exists P'. intuition. { rewrite H5 in SAFE1. apply psafe_par_rev in SAFE1. destruct SAFE1 as (SAFE1 & SAFE2). inv SAFE1. clear SAFE1. destruct H as (_ & SAFE1). subst P'. repeat apply ppsafe_add; auto. rewrite aproc_conv_subst_upd; auto. assert (H6: pstep (aproc_conv (APsigma y (APseq (APrecv (Evar y) T) AP)) s) (PLrecv v tag) (aproc_conv (aproc_subst y (Econst v) (APseq APepsilon AP)) s)). { simpl. desf. apply pstep_sum with v. constructor. subst tag. rewrite expr_subst_pres. + rewrite expr_conv_eval. vauto. + intro H6. by apply H2. } apply SAFE1 in H6. clear SAFE1. simpl in H6. rewrite pseq_epsilon_r in H6. simpls. apply psafe_par; auto. } { rewrite H5. subst P'. apply istep_proc_frame. apply istep_recv with (P' := aproc_conv (APsigma y (APseq (APrecv (Evar y) T) AP)) s) (Q' := aproc_conv (APseq APepsilon (aproc_subst y (Evar x) AP)) (updatestore s x v)); auto. - rewrite aproc_conv_sigma. apply pstep_sum with v. simpl. desf. clear e. simpl. rewrite aproc_conv_subst_upd; auto. apply pstep_seq_l. rewrite expr_subst_pres. + subst tag. rewrite expr_conv_eval. vauto. + intro H6. by apply H2. - simpls. intuition. by rewrite pseq_epsilon_r. } apply safe_skip. subst P'. exists P''. intuition. Qed. (** *** Querying *) Theorem rule_query : forall B AP, csl (Aproc (APseq (APassn B) AP)) (Cquery B) (Astar (Aproc AP) (Aplain B)). Proof. intros B AP ph P s H1 SAT1. constructor. split. (* termination *) - intros H. inv H. (* computation *) - simpl. intros phF C' h' s' l H2 FIN1 SAFE1 STEP. inv STEP. rename s' into s. exists ph. intuition. destruct SAT1 as (P'' & H3). assert (H5: cond_eval B s). { rewrite cond_conv_eval. rewrite H3 in SAFE1. apply psafe_par_rev in SAFE1. destruct SAFE1 as (SAFE1 & _). simpl in SAFE1. apply psafe_seq_left in SAFE1. inv SAFE1. clear SAFE1. destruct H as (SAFE1 & _). by apply passn_nfault. } set (P' := Ppar (aproc_conv AP s) P''). exists P'. intuition. { rewrite H3 in SAFE1. apply psafe_par_rev in SAFE1. destruct SAFE1 as (SAFE1 & SAFE2). simpl in SAFE1. inv SAFE1. clear SAFE1. destruct H as (_ & SAFE1). subst P'. repeat apply ppsafe_add; auto. assert (H6: pstep (Pseq (Passn (cond_conv B s)) (aproc_conv AP s)) (PLassn (pcond_eval (cond_conv B s))) (Pseq Pepsilon (aproc_conv AP s))). { repeat constructor. by rewrite <- cond_conv_eval. } apply SAFE1 in H6. clear SAFE1. rewrite pseq_epsilon_r in H6. apply psafe_par; auto. } { subst P'. rewrite H3. apply istep_proc_frame. apply istep_query with (P' := aproc_conv (APseq (APassn B) AP) s) (Q' := aproc_conv (APseq APepsilon AP) s); auto. - apply pstep_seq_l. rewrite cond_conv_eval at 1. constructor. by rewrite <- cond_conv_eval. - simpl. intuition. by rewrite pseq_epsilon_r. } apply safe_skip. subst P'. exists ph, permheap_iden. intuition. { by rewrite permheap_add_iden_l. } exists (aproc_conv AP s), P''. intuition. simpl. exists Pepsilon. by rewrite par_epsilon_r. Qed. End Soundness.
C---------------------------------------------------------------------- C PATCH2_SET.FOR C Set of subroutines: C C PATCH3, PATCH2, PATCH22, STRDELT, STRCOPY, STRESTO. C C Package of routines for finding and removing defects from C an image array. The position of the area to delete may C be specified manually using the cursor, or by reading a file. C The user is prompted for the diameter of a circle C of pixels to delete around this position, which are C replaced by an interpolation of a surface fitted to C an annulus of surrounding pixels. A constant, planar, C quadratic, or cubic surface may be specified (1,3,6, or 10 C terms). The interpolation is then displayed on the screen C and the user judges the quality of fit. If necessary, the C original values of the pixels may be restored and a C different interpolation attempted. C C JLP C Version of 29-11-2006 C---------------------------------------------------------------------- C++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ C C CALLING SEQUENCE:- C PATCH [ NOISE=f ] [ ORDER=n ] [ FILE=f ] C C C FUNCTION:- C It allows the user to replace several circular patches in C an image with a fitted noisy piece of synthetic data. It is C derived from a program, by W D Pence (at University of C Sussex). C C C USE:- C It may be used to remove large defects, bright galaxies or C any other localised unwanted pixels. The result can be very C convincing. C C USER PARAMETERS:- C C IN The input 2-D image which is C being displayed on the ARGS. C C OUTPUT The new image with the C patched regions. C C NORMALLY DEFAULTED PARAMETERS:- C C NOISE 1 This is a noise factor which C may be between 0 (no noise) C and 1 (noise level calculated C from the whole image). C C ORDER 3 This is the the degree of the C 2-dimensional surface which C is to be fitted to an annulus C around the circular patch. It C may be 0 (constant) to 3 C (bi-cubic). C C C FILE FALSE This defines if the position C and size of the patches will C be written to the file C PATCHES.DAT C C C USE OF TRACKER-BALL BUTTONS:- C C GREEN 1 Accept this size of patch and then do a fit and C display the results. AFTER THIS BUTTON has been used C then GREEN means accept the result and move on to C another location, whilst RED means revert to the C previous state. C C WHITE 2 Decrease the size of the patch. C C WHITE 3 Increase the size of the patch. C C RED 4 Exit from the program. C C C D J King-W D Pence RGO-U. of Sussex 7-JAN-82 C C-------------------------------------------------------------------------- C************************************************************************* C Non-interactive version C with only a few questions C C INPUT: C I_MIN,I_MAX,J_MIN,J_MAX: boundaries of the zoomed image ARRAY C (expressed as C indices starting at (0,0)!) C************************************************************************* SUBROUTINE PATCH3(ARRAY,NX,NY,IDIM,IMAGE2,IDIM2, 1 I_MIN,I_MAX,J_MIN,J_MAX, 1 NCOLORS,ITT_IS_LINEAR,LOWER_ITT,UPPER_ITT, 1 XP,YP,DIAM,NCODE,SIG,ISTATUS,GAMMA_D,IDV1) IMPLICIT NONE INTEGER*4 NX,NY,IDIM,IDIM2,NCOLORS,NDIMER,IDV1 INTEGER*4 I_MIN,I_MAX,J_MIN,J_MAX,ITT_IS_LINEAR PARAMETER (NDIMER=200) REAL*4 ARRAY(IDIM,*),ER(NDIMER) REAL*4 LOWER_ITT,UPPER_ITT,SIG,XP,YP,DIAM INTEGER*4 IMAGE2(IDIM2,*),ISTATUS,GAMMA_D INTEGER*4 DRAW_CROSS,AUTOMATIC_PATCH,NCODE INTEGER*4 I,IN_FRAME,IBUTTON,IXP,IYP LOGICAL FILE CHARACTER ANS*1,BUFFER*80 10 FORMAT(A) AUTOMATIC_PATCH=1 FILE=.FALSE. ISTATUS=-1 C Order of polynomial: NCODE=3 C Sigma of the noise: SIG=0. C Set up array of random errors with gaussian distribution C for approximating the noise when interpolating C Generate normal errors, mean=0. IF(SIG.GT.0.)THEN CALL JLP_RANDOM_INIT(1) DO I=1,NDIMER CALL JLP_RANDOM_GAUSS(ER(I)) ER(I)=ER(I)*SIG END DO ELSE DO I=1,NDIMER ER(I)=0. END DO ENDIF 17 WRITE(BUFFER,10)'Click on the mouse to select the center' CALL JLP_DRAW_TO_STATUS_BAR(BUFFER,IDV1) C Reading the position of the cursor: DRAW_CROSS = 0 CALL JLP_WHERE(XP,YP,IN_FRAME,IBUTTON,DRAW_CROSS,IDV1) C JLP_WHERE is written in C and returns an index starting at 0,0: IXP=INT(XP) IYP=INT(YP) C Test to check if the point is on the image : IF(IXP.LT.0.OR.IXP.GE.NX 1 .OR.IYP.LT.0.OR.IYP.GE.NY.OR.IN_FRAME.EQ.0)THEN WRITE(6,77) IXP,IYP,IN_FRAME 77 FORMAT(' PATCH3/Exit: Point outside of the image ' 1 ' IX, IY, IN_FRAME:',3I5) GO TO 99 ENDIF WRITE(BUFFER,10)'Please enter some data on the terminal...' CALL JLP_DRAW_TO_STATUS_BAR(BUFFER,IDV1) C JLP2006: I tried with NCODE=4 or 5, but it was always worse! 700 WRITE(6,*) ' Diameter, order of polynomial (between 0 and 3):' READ(5,*) DIAM,NCODE IF(NCODE.LT.0.OR.NCODE.GT.3)NCODE=3 WRITE(6,71) XP,YP,DIAM,NCODE,SIG 71 FORMAT(' XP,YP,DIAMETER,NCODE,SIG :',3(F7.1,2X),I5,2X,F7.3) C Displaying a circle: C Warning: convention here is that (0,0) is the lower left corner, CALL JLP_CIRCLE1(XP,YP,DIAM,IDV1) CALL JLP_GFLUSH(IDV1) WRITE(6,*) ' Diameter is OK [y] ?' READ(5,10) ANS IF(ANS.EQ.'N'.OR.ANS.EQ.'n') THEN C Refresh screen to erase previous circle: CALL PATCH_DISP(ARRAY,NX,NY,IDIM,I_MIN,I_MAX,J_MIN,J_MAX, 1 IMAGE2,IDIM2,NCOLORS,ITT_IS_LINEAR, 1 LOWER_ITT,UPPER_ITT,GAMMA_D,IDV1) GOTO 700 ENDIF C Correcting the selected patch : C NCODE: polynomial order CALL STRDELT(ARRAY,NX,NY,IDIM,I_MIN,I_MAX,J_MIN,J_MAX, 1 IMAGE2,IDIM2, 1 XP,YP,SIG,DIAM,ER,NDIMER,NCODE,FILE, 1 NCOLORS,ITT_IS_LINEAR,LOWER_ITT,UPPER_ITT, 1 AUTOMATIC_PATCH,ISTATUS,GAMMA_D,IDV1) C Counting the number of patches : IF(ISTATUS.NE.0)THEN WRITE(6,*) ' Do you want another patch ? (Y)' READ(5,10) ANS IF(ANS.NE.'N'.AND.ANS.NE.'n')GO TO 17 ENDIF 99 CALL JLP_ERASE_STATUS_BAR(IDV1) RETURN END C************************************************************************* C Interactive version C with many questions C************************************************************************* SUBROUTINE PATCH2(ARRAY,NX,NY,IDIM,IMAGE2,IDIM2, 1 I_MIN,I_MAX,J_MIN,J_MAX, 1 NCOLORS,ITT_IS_LINEAR,LOWER_ITT,UPPER_ITT, 1 GAMMA_D,IDV1) IMPLICIT NONE INTEGER*4 NX,NY,IDIM,NX2,NY2,IDIM2,NCOLORS,NDIMER,IDV1 PARAMETER (NDIMER=200) REAL*4 ARRAY(IDIM,*),ER(NDIMER) REAL*4 LOWER_ITT,UPPER_ITT,SIG,XP,YP,DIAM INTEGER*4 I_MIN,I_MAX,J_MIN,J_MAX,ITT_IS_LINEAR INTEGER*4 IMAGE2(IDIM2,*),ISTATUS,GAMMA_D INTEGER*4 DRAW_CROSS,AUTOMATIC_PATCH,IOBJECT,NCODE INTEGER*4 I,IN_FRAME,IBUTTON,IXP,IYP LOGICAL FILE,CURSOR CHARACTER NAME*40,ANS*1,BUFFER*80 10 FORMAT(A) IOBJECT=0 AUTOMATIC_PATCH=0 WRITE(6,12) 12 FORMAT(' Input positions with a file (f),', 1 ' with the cursor (c) or manually (m)? (Return=c)') READ(5,10) ANS FILE=.FALSE. CURSOR=.TRUE. IF(ANS.EQ.'f'.OR.ANS.EQ.'F')FILE=.TRUE. IF(ANS.EQ.'m'.OR.ANS.EQ.'M')CURSOR=.FALSE. C---------------------------------------------------------------------- C First option : Positions in a file : C---------------------------------------------------------------------- IF(FILE) THEN WRITE(6,*) ' Name of the file containing the positions ?' READ(5,10) NAME OPEN(UNIT=9,STATUS='OLD',FILE=NAME) C Loop as long as file 9 contains something : C Reading centre (XP,YP), and diameter DIAM from the file : 70 READ (9,*,END=55) XP,YP,DIAM,NCODE,SIG WRITE(6,71) XP,YP,DIAM,NCODE,SIG 71 FORMAT(' XP,YP,DIAMETER,NCODE,SIG :',3(F7.2,2X),I5,2X,F7.3) C Go to next point if point outside of the image : IXP=INT(XP) IYP=INT(YP) IF(IXP.LT.0.OR.IXP.GE.NX.OR.IYP.LT.0.OR.IYP.GE.NY)THEN WRITE(6,*) ' PATCH2/Error ' WRITE(6,*) ' The patch is outside the limits of the image' GO TO 70 ENDIF C Set up array of random errors with gaussian distribution C for approximating the noise when interpolating C MEAN=0 IF(SIG.GT.0.)THEN CALL JLP_RANDOM_INIT(1) DO I=1,NDIMER CALL JLP_RANDOM_GAUSS(ER(I)) ER(I)=ER(I)*SIG END DO ELSE DO I=1,NDIMER ER(I)=0. END DO ENDIF C Counting the number of patches : IOBJECT=IOBJECT+1 C Displaying a circle: C Warning: convention here is that (0,0) is the lower left corner, CALL JLP_CIRCLE1(XP,YP,DIAM,IDV1) CALL JLP_GFLUSH(IDV1) C Correcting the selected patch : CALL STRDELT(ARRAY,NX,NY,IDIM,I_MIN,I_MAX,J_MIN,J_MAX, 1 IMAGE2,IDIM2, 1 XP,YP,SIG,DIAM,ER,NDIMER,NCODE,FILE, 1 NCOLORS,ITT_IS_LINEAR,LOWER_ITT,UPPER_ITT, 1 AUTOMATIC_PATCH,ISTATUS,GAMMA_D,IDV1) GO TO 70 55 WRITE(6,*) ' End of patch2: ',IOBJECT,' patches treated' CLOSE(9) ENDIF C---------------------------------------------------------------------- C Second option : Interactive mode C---------------------------------------------------------------------- IF(.NOT.FILE) THEN NAME='patch2.dat' WRITE(6,63) NAME 63 FORMAT(' Creating an output file to store the positions', 1 /,' Name = ',A) OPEN(4,STATUS='unknown',FILE=NAME) WRITE(6,*) ' Order of the polynomial (0 to 5) and noise', 1 ' (about 1.0) ?' READ(5,*) NCODE,SIG C Set up array of random errors with gaussian distribution C for approximating the noise when interpolating C Generate normal errors, mean=0. CALL JLP_RANDOM_INIT(1) DO I=1,NDIMER CALL JLP_RANDOM_GAUSS(ER(I)) ER(I)=ER(I)*SIG END DO 17 IF(CURSOR)THEN WRITE(BUFFER,10)'Click on the mouse to select the center' CALL JLP_DRAW_TO_STATUS_BAR(BUFFER,IDV1) C Read the position of the cursor: DRAW_CROSS = 0 CALL JLP_WHERE(XP,YP,IN_FRAME,IBUTTON,DRAW_CROSS,IDV1) ELSE WRITE(6,29) 29 FORMAT(' Enter center coordinates XP,YP', 1 ' (0,0 is origin at bottom left) :') READ(5,*)XP,YP IN_FRAME=1 ENDIF C JLP_WHERE is written in C and returns an index starting at 0,0: IXP=INT(XP) IYP=INT(YP) C Test to check if the point is on the image : IF(IXP.LT.0.OR.IXP.GE.NX 1 .OR.IYP.LT.0.OR.IYP.GE.NY.OR.IN_FRAME.EQ.0)THEN WRITE(6,77) IXP,IYP,IN_FRAME 77 FORMAT(' PATCH2/Exit: Point outside of the image ' 1 ' IX, IY, IN_FRAME:',3I5) GO TO 99 ENDIF WRITE(BUFFER,10)'Please enter some data on the terminal...' CALL JLP_DRAW_TO_STATUS_BAR(BUFFER,IDV1) WRITE(6,*) ' Diameter (in pixel units) ?' READ(5,*) DIAM C Display current parameters to terminal: WRITE(6,71) XP,YP,DIAM,NCODE,SIG C Displaying a circle: CALL JLP_CIRCLE1(XP,YP,DIAM,IDV1) CALL JLP_GFLUSH(IDV1) C Correcting the selected patch : C NCODE: polynomial order CALL STRDELT(ARRAY,NX,NY,IDIM,I_MIN,I_MAX,J_MIN,J_MAX, 1 IMAGE2,IDIM2, 1 XP,YP,SIG,DIAM,ER,NDIMER,NCODE,FILE, 1 NCOLORS,ITT_IS_LINEAR,LOWER_ITT,UPPER_ITT, 1 AUTOMATIC_PATCH,ISTATUS,GAMMA_D,IDV1) C Counting the number of patches : C and writing parameters to "patch2.dat": IF(ISTATUS.EQ.0)THEN IOBJECT=IOBJECT+1 WRITE(4,*) XP,YP,DIAM,NCODE,SIG ENDIF WRITE(6,*) ' DO YOU WANT ANOTHER PATCH ? (Y)' READ(5,10) ANS IF(ANS.NE.'N'.AND.ANS.NE.'n')GO TO 17 99 CALL JLP_ERASE_STATUS_BAR(IDV1) CLOSE(4) ENDIF RETURN END C **************************************************************** C SUBROUTINE STRDELT C C Deletes pixels within a circle around point (XP,YP) and C interpolates them with a polynomial fitted to an annulus C of surrounding points. C C INPUT: C NCODE: polynomial order C I_MIN,I_MAX,J_MIN,J_MAX: boundaries of the zoomed image ARRAY C (expressed as C indices starting at (0,0)!) C C OUPUT: C ISTATUS: 0 if patch has been validated C 1 otherwise C **************************************************************** SUBROUTINE STRDELT(ARRAY,NX,NY,IDIM,I_MIN,I_MAX,J_MIN,J_MAX, 1 IMAGE2,IDIM2, 1 XP,YP,SIG,DIAM,ER,NDIMER,NCODE,FILE, 1 NCOLORS,ITT_IS_LINEAR,LOWER_ITT,UPPER_ITT, 1 AUTOMATIC_PATCH,ISTATUS,GAMMA_D,IDV1) IMPLICIT NONE INTEGER*4 NX,NY,IDIM,I_MIN,I_MAX,J_MIN,J_MAX,IDV1 INTEGER*4 IDIM2,IMAGE2(IDIM2,*) INTEGER*4 NCODE,NDIMER,NCOLORS,AUTOMATIC_PATCH INTEGER*4 ISTATUS,GAMMA_D,ITT_IS_LINEAR REAL ARRAY(IDIM,*),ER(NDIMER) REAL LOWER_ITT,UPPER_ITT,XP,YP,SIG,DIAM REAL*4 NEW_VAL CHARACTER ANS*1,BUFFER*40 LOGICAL FILE INTEGER*4 I1,I2,J1,J2,IS,JS,IRAD INTEGER*4 MADRID(1),ISIZE,IPNT,I COMMON /VMR/MADRID 10 FORMAT(A) ISTATUS=1 C C DEFINE LIMITS OF AREA TO DELETE C IF(DIAM.GT.2)THEN IRAD=INT(DIAM/2.) ELSE C Select +/-2 pixels around the central pixel for display: IRAD=2 ENDIF C Conversion to Fortran convention: IS = INT(XP)+1 JS = INT(YP)+1 I1=MAX(IS-IRAD,I_MIN+1) I2=MIN(IS+IRAD,I_MAX) J1=MAX(JS-IRAD,J_MIN+1) J2=MIN(JS+IRAD,J_MAX) C WRITE(6,*) '(Fortran) boundaries (Imax,Imin,Jmax,Jmin): ',I1,I2,J1,J2 C C Temporarily store current array contents C ISIZE=4*(I2-I1+1)*(J2-J1+1) CALL JLP_GETVM(IPNT,ISIZE) CALL STRCOPY(ARRAY,NX,NY,IDIM,MADRID(IPNT),I1,I2,J1,J2) C Fit a polynomial to the data: 30 IF(DIAM.GT.2)THEN C If large diameter, call main routine which fits a polynomial to the data: C NCODE: polynomial order CALL PATCH22(ARRAY,NX,NY,IDIM,XP,YP, 1 I_MIN,I_MAX,J_MIN,J_MAX, 1 I1,I2,J1,J2,DIAM,ER,NDIMER,NCODE) ELSE C Else linear interpolation only (when DIAM <=2) I1=MAX(IS-1,I_MIN+1) I2=MIN(IS+1,I_MAX) J1=MAX(JS-1,J_MIN+1) J2=MIN(JS+1,J_MAX) C Store new value (used later) NEW_VAL=(ARRAY(I1,JS)+ARRAY(I2,JS) 1 +ARRAY(IS,J1)+ARRAY(IS,J2))/4. ARRAY(IS,JS)=NEW_VAL ENDIF C New version: display the whole image (since computers are fast nowadays): CALL PATCH_DISP(ARRAY,NX,NY,IDIM,I_MIN,I_MAX,J_MIN,J_MAX, 1 IMAGE2,IDIM2,NCOLORS,ITT_IS_LINEAR, 1 LOWER_ITT,UPPER_ITT,GAMMA_D,IDV1) C--------------------------------------------------------------- C Interactive choice IF(.NOT.FILE)THEN WRITE(6,*) ' Are you satisfied ? (Y)' READ(5,10) ANS IF(ANS.NE.'n'.AND.ANS.NE.'N')THEN ISTATUS = 0 ELSE C Restores previous data on the image: CALL STRESTO(ARRAY,NX,NY,IDIM,MADRID(IPNT),I1,I2,J1,J2) C New version: display the whole image (since computers are fast nowadays): CALL PATCH_DISP(ARRAY,NX,NY,IDIM,I_MIN,I_MAX,J_MIN,J_MAX, 1 IMAGE2,IDIM2,NCOLORS,ITT_IS_LINEAR, 1 LOWER_ITT,UPPER_ITT,GAMMA_D,IDV1) IF(AUTOMATIC_PATCH.NE.1)THEN C Possibility of another try with different order and noise parameters IF(DIAM.GT.2)THEN WRITE(6,864) NCODE,SIG 864 FORMAT(' Remember : order =',I2,' noise :',F6.3,/, 1 ' Do you want to change these parameters ? (Y)') READ(5,10) ANS IF(ANS.NE.'n'.AND.ANS.NE.'N')THEN WRITE(6,*) ' Order of the polynomial (0 to 3)', 1 ' and noise (sigma) ?' READ(5,*) NCODE,SIG C Set up array of random errors with gaussian distribution C for approximating the noise when interpolating IF(SIG.GT.0.)THEN CALL JLP_RANDOM_INIT(1) DO I=1,NDIMER CALL JLP_RANDOM_GAUSS(ER(I)) ER(I)=ER(I)*SIG END DO ELSE DO I=1,NDIMER ER(I)=0. END DO ENDIF GO TO 30 C End of case with change of parameters ENDIF C Case when DIAM.LT.2 ELSE WRITE(6,34) ARRAY(IS,JS),NEW_VAL 34 FORMAT(' Current (old) value is',G12.5,/, 1 ' Proposed new value is',G12.5,/ 1 ' Which new value do you want to put instead? (E to exit)') READ(5,10)BUFFER IF(BUFFER(1:1).EQ.'E'.OR.BUFFER(1:1).EQ.'e')GOTO 200 READ(BUFFER,*,ERR=200)NEW_VAL GO TO 30 C End of DIAM.LT.2... ENDIF C End of not AUTOMATIC_PATCH ENDIF C End of case not satisfied .... ENDIF C End of condition "IF (.NOT.FILE)" ELSE ISTATUS = 0 ENDIF C----------------------------------------------------------------------- C Label for exit when problem 200 CONTINUE CALL JLP_FREEVM(IPNT,ISIZE) RETURN END C************************************************************************ C C New version: display the whole image (since computers are fast nowadays): C C I_MIN,I_MAX,J_MIN,J_MAX: boundaries of the zoomed image ARRAY C (expressed as C indices starting at (0,0)!) C************************************************************************ SUBROUTINE PATCH_DISP(ARRAY,NX,NY,IDIM,I_MIN,I_MAX,J_MIN,J_MAX, 1 IMAGE2,IDIM2,NCOLORS,ITT_IS_LINEAR, 1 LOWER_ITT,UPPER_ITT,GAMMA_D,IDV1) IMPLICIT NONE INTEGER*4 NX,NY,IDIM,I_MIN,I_MAX,J_MIN,J_MAX,IDV1 INTEGER*4 IDIM2,IMAGE2(IDIM2,*) INTEGER*4 NCOLORS,GAMMA1,GAMMA_D,BLACK_AND_WHITE REAL ARRAY(IDIM,*) REAL LOWER_ITT,UPPER_ITT,XMIN,XMAX,YMIN,YMAX INTEGER*4 MADRID(1),ITT_IS_LINEAR INTEGER*4 NI,NJ,NI2,NJ2,OFFX,OFFY,AXLEN,AYLEN,PLAN COMMON /VMR/MADRID NI = I_MAX - I_MIN NJ = J_MAX - J_MIN GAMMA1 = IDIM/IDIM2 NI2=NI/GAMMA1 NJ2=NJ/GAMMA1 CALL CONVERT_TO_LUT(ARRAY(I_MIN+1,J_MIN+1),NI,NJ,IDIM, 1 IMAGE2,NI2,NJ2,IDIM2,NCOLORS, 1 ITT_IS_LINEAR,LOWER_ITT,UPPER_ITT,IDV1) BLACK_AND_WHITE=0 CALL JLP_GET_PLOT_PARAM(OFFX,OFFY,AXLEN,AYLEN,XMIN,XMAX, 1 YMIN,YMAX,PLAN,IDV1) CALL JLP_PLOT_IMAGE(IMAGE2,NI2,NJ2,IDIM2,OFFX,OFFY, 1 GAMMA_D,BLACK_AND_WHITE,IDV1) CALL JLP_GFLUSH(IDV1) RETURN END C************************************************************************ C C Store current star image in temporary array C C************************************************************************ SUBROUTINE STRCOPY(ARRAY,NX,NY,IDIM,TEMP,I1,I2,J1,J2) IMPLICIT NONE INTEGER NX,NY,IDIM,I1,I2,J1,J2 REAL ARRAY(IDIM,*),TEMP(*) INTEGER I,J,N C N=0 DO J=J1,J2 DO I=I1,I2 N=N+1 TEMP(N)=ARRAY(I,J) END DO END DO RETURN END C************************************************************************ C C Restore array to previous state C C************************************************************************ SUBROUTINE STRESTO(ARRAY,NX,NY,IDIM,TEMP,I1,I2,J1,J2) IMPLICIT NONE INTEGER NX,NY,IDIM,I1,I2,J1,J2 REAL ARRAY(IDIM,*),TEMP(*) INTEGER I,J,N N=0 DO J=J1,J2 DO I=I1,I2 N=N+1 ARRAY(I,J)=TEMP(N) END DO END DO RETURN END C****************************************************************** C Subroutine to fit a polynomial to an annulus around the center C and replace input values by noised computed values C Real "core" of patch2 C C INPUT: C NCODE: polynomial order C****************************************************************** SUBROUTINE PATCH22(ARRAY,NX,NY,IDIM,XP,YP, 1 I_MIN,I_MAX,J_MIN,J_MAX, 1 I1,I2,J1,J2,DIAM,ER,NDIMER,NCODE) IMPLICIT NONE INTEGER*4 NX,NY,IDIM,IS,JS,I1,I2,J1,J2,NDIMER,NCODE INTEGER*4 NDIM,I_MIN,I_MAX,J_MIN,J_MAX PARAMETER (NDIM=1000) C Maximum: NTERMS=30 DOUBLE PRECISION ZZ(NDIM),D(30),SE(30),RDOE(30) DOUBLE PRECISION POLY REAL ARRAY(IDIM,*),ER(NDIMER) REAL XX(NDIM,2),YY(NDIM),XP,YP REAL FACTOR,XRAN,XZ,YZ,DIAM,XNOISE REAL TEST,SDOR,DX,DY REAL RADMIN2,DIAM_MAX,RADMAX,RADMAX2,RAD2 INTEGER*4 I,J,K,KQ,NR,NINC INTEGER*4 NTERMS,NPTS,IMIN,IMAX,JMIN,JMAX C Contained in "patch_set.for" EXTERNAL POLY C C SET UP ARRAYS FOR NEQSOL C C FACTOR=2 => annulus of diameters DIAM (inside) and 2*DIAM (outside) C Before 2006: C FACTOR=2 C JLP2006: FACTOR=2 is bad: I reduce it to 1.5 FACTOR=1.5 DIAM_MAX=DIAM*FACTOR RADMAX=(DIAM_MAX+1)/2 RADMAX2=RADMAX*RADMAX NINC=(DIAM_MAX-1)/30+1 C Conversion to Fortran convention: IS = INT(XP)+1 JS = INT(YP)+1 IMIN=MAX(IS-RADMAX,I_MIN+1) IMAX=MIN(IS+RADMAX,I_MAX) JMIN=MAX(JS-RADMAX,J_MIN+1) JMAX=MIN(JS+RADMAX,J_MAX) C C DEFINE NORMALIZING FACTORS SUCH THAT THE COORDS. OF C ALL THE POINTS ARE BETWEEN (-1,-1) AND (1,1). C RADMIN2=(DIAM/2.)**2 DX=2./(IMAX-IMIN) DY=2./(JMAX-JMIN) NPTS=0 DO 20 J=JMIN,JMAX,NINC DO 20 I=IMIN,IMAX,NINC C C Calculate radius, and reject if too close to star centre C C JLP2006: The cursor gives (0.5,0.5) when the cursor C is centered on the pixel (0,0) in the bottom-left corner: RAD2=(REAL(J - 1) - (YP - 0.5))**2 1 + (REAL(I - 1) - (XP - 0.5))**2 IF (RAD2 .GT. RADMIN2 .AND. RAD2 .LE. RADMAX2)THEN NPTS=NPTS+1 XX(NPTS,1)=(I-IMIN)*DX-1. XX(NPTS,2)=(J-JMIN)*DY-1. YY(NPTS)=ARRAY(I,J) ENDIF 20 CONTINUE IF (NCODE .EQ. 5)THEN NTERMS=21 ELSE IF (NCODE .EQ. 4)THEN NTERMS=15 ELSE IF (NCODE .EQ. 3)THEN NTERMS=10 ELSE IF (NCODE .EQ. 2)THEN NTERMS=6 ELSE IF (NCODE .EQ. 1)THEN NTERMS=3 ELSE NTERMS=1 END IF C IF (NPTS .LT. NTERMS)THEN WRITE(6,62) 62 FORMAT('PATCH22/Error: too few points to fit background') WRITE(6,*) ' NPTS, NTERMS',NPTS,NTERMS GO TO 200 END IF C C Erase any previous solution C DO I=1,30 D(I)=0. END DO C C Fit the polynomial with all points: C CALL NEQSOL(XX,YY,ZZ,NDIM,NPTS,NTERMS,1,0,D,SE,RDOE,SDOR) C Perform twice a 2 sigma rejection: DO KQ=1,2 TEST=2.*SDOR CALL REJECT(XX,YY,NDIM,D,NPTS,NTERMS,TEST,NR,1) C NR: number of points after rejection NPTS=NR IF (NPTS .LT. NTERMS)THEN WRITE(6,63) NPTS 63 FORMAT('PATCH22/Error: too few points after rejection (NPTS=', 1 I3,')') GO TO 200 END IF C Refit polynomial with less points: C CALL NEQSOL(XX,YY,ZZ,NDIM,NPTS,NTERMS,1,0,D,SE,RDOE,SDOR) END DO C C Evaluate polynomial at each point within circle C DO 60 J=J1,J2 C C Find a random starting points in the sequence of noise points C To obtain random numbers between 0. and 1. CALL JLP_RANDOM(XRAN) K=INT(XRAN*REAL(NDIMER)) K=MAX(1,K) K=MIN(K,NDIMER) C YZ=(J-JMIN)*DY-1. DO 50 I=I1,I2 C JLP2006: The cursor gives (0.5,0.5) when the cursor C is centered on the pixel (0,0) in the bottom-left corner: RAD2=(REAL(J - 1) - (YP - 0.5))**2 1 + (REAL(I - 1) - (XP - 0.5))**2 IF (RAD2 .LE. RADMIN2) THEN XZ=(I-IMIN)*DX-1. K=K+1 IF (K .GT. NDIMER)K=1 XNOISE=ER(K)*SDOR C Calling POLY, contained in "patch_set.for" ARRAY(I,J)=POLY(XZ,YZ,D)+XNOISE ENDIF 50 CONTINUE 60 CONTINUE 200 RETURN END
theory day4 imports Main begin lemma IsarTest: "((P\<longrightarrow>Q) \<and> P) \<longrightarrow> Q" proof assume 0: "((P\<longrightarrow>Q) \<and> P)" then have 1: "P\<longrightarrow>Q" by (simp) from 0 have 2: "P" .. from 1 2 show "Q" .. qed (* from this = then then show = thus then have = hence from 0 = by (simp add:0) *) end
struct Figure9 error::Matrix{Float64} Ω::Vector{Float64} dates::Vector{Float64} function Figure9() @load "dat/anonomous_data.jld" wavetime = wavetime ./24 ./3600 errorgram, Ω, spectime = PaperAnalysis.compute_errorgram(waveseries,wavetime) new(errorgram, Ω, spectime) end end @recipe function f(f::Figure9) seriestype := :heatmap seriescolor := :balance clims := (-12,12) xticks := (1:5,map(i->"day $i",1:5)) f.dates, f.Ω, f.error end
[STATEMENT] lemma hcomplex_numeral_hcmod [simp]: "hcmod (numeral v :: hcomplex) = (numeral v :: hypreal)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. hcmod (numeral v) = numeral v [PROOF STEP] by transfer (rule norm_numeral)
__precompile__(true) module SearchBall using Reactive include("reactive_extension.jl") include("geometry_utils.jl") include("orders.jl") include("graphics_2d.jl") include("world_state.jl") include("handle_orders.jl") include("configuration.jl") include("strategy_utils.jl") include("strategies/compare_shadow.jl") include("strategies/show_shadow.jl") include("strategies/test_strategy.jl") include("strategies/global_com_shadow.jl") # include("strategies/ba_jakob.jl") include("strategies/startpositions01.jl") include("strategies/pushball_NN.jl") include("strategies/growing_regions.jl") include("game_state.jl") include("game_view_gtk.jl") export main function main(arguments::AbstractVector{<:AbstractString}, ignore_commandline::Bool=false) if ignore_commandline || isinteractive() config = get_config(arguments) else # Parse the command line arguments as initialization config = get_config(ARGS) end start_view(config) end main(config_file_path::AbstractString) = main(String["--file", config_file_path], true) main(ignore_commandline::Bool=false) = main(String[], ignore_commandline) end
module Languages.FILL.Syntax where open import level open import bool open import nat open import unit open import empty open import list open import eq open import sum open import Utils.HaskellTypes open import Utils.HaskellFunctions open import Languages.FILL.TypeSyntax True : Set True = ⊤{lzero} False : Set False = ⊥{lzero} Name : Set Name = ℕ name-in : ∀{A : Set} → (A → A → 𝔹) → A → 𝕃 A → Set name-in eq x ctx with list-member eq x ctx name-in _ x ctx | tt = True name-in _ x ctx | ff = False -- Bound Variable Labels: data VLabel : Set where LPV : VLabel -- Let-Bound Left Pattern Variable RPV : VLabel -- Let-Bound Right Pattern Variable BV : VLabel -- λ-Bound Variable _vl-eq_ : VLabel → VLabel → 𝔹 LPV vl-eq LPV = tt RPV vl-eq RPV = tt BV vl-eq BV = tt _ vl-eq _ = ff data Pattern : Set where PTriv : Pattern PTensor : String → String → Pattern PPar : String → String → Pattern data Term : Set where Triv : Term Void : Term FVar : String → Term BVar : Name → String → VLabel → Term Let : Term → Type → Pattern → Term → Term Lam : String → Type → Term → Term App : Term → Term → Term Tensor : Term → Term → Term Par : Term → Term → Term open-t : Name → VLabel → Term → Term → Term open-t x l u (BVar y ys l') with x =ℕ y | l vl-eq l' ... | tt | tt = u ... | _ | _ = BVar y ys l' open-t x BV u (Let t₁ y z t₂) = Let (open-t x BV u t₁) y z (open-t x BV u t₂) open-t x l u (Let t₁ a p t₂) = Let (open-t (suc x) l u t₁) a p (open-t (suc x) l u t₂) open-t x BV u (Lam ys a t) = Lam ys a (open-t (suc x) BV u t) open-t x l u (Lam ys a t) = Lam ys a (open-t x l u t) open-t x l u (App t₁ t₂) = App (open-t x l u t₁) (open-t x l u t₂) open-t x l u (Tensor t₁ t₂) = Tensor (open-t x l u t₁) (open-t x l u t₂) open-t x l u (Par t₁ t₂) = Par (open-t x l u t₁) (open-t x l u t₂) open-t _ _ _ t = t close-t : Name → String → VLabel → String → Term → Term close-t x xs l y (FVar z) with y str-eq z ... | tt = BVar x xs l ... | ff = FVar z close-t x xs l y (Let t₁ ty p t₂) = Let (close-t x xs l y t₁) ty p (close-t x xs l y t₂) close-t x xs l y (Lam ys a t) = Lam ys a (close-t x xs l y t) close-t x xs l y (App t₁ t₂) = App (close-t x xs l y t₁) (close-t x xs l y t₂) close-t x xs l y (Tensor t₁ t₂) = Tensor (close-t x xs l y t₁) (close-t x xs l y t₂) close-t x xs l y (Par t₁ t₂) = Par (close-t x xs l y t₁) (close-t x xs l y t₂) close-t _ _ _ _ t = t data LC : Term → Set where Triv : LC Triv Void : LC Void FVar : ∀{x : String} → LC (FVar x) Lam : ∀{ns : 𝕃 String}{t : Term}{a : Type}{y : String} → LC t → (∀{x : String} → (name-in _str-eq_ x ns → False) → LC (open-t 0 BV (FVar x) t)) → LC (Lam y a t) LetTriv : ∀{t₁ : Term}{a : Type}{t₂ : Term} → LC t₁ → LC t₂ → LC (Let t₁ a PTriv t₂) LetTensor : ∀{ns : 𝕃 String}{t₁ : Term}{a : Type}{t₂ : Term}{s₁ s₂ : String} → LC t₁ → LC t₂ → (∀{x y : String} → (name-in _str-eq_ x ns → False) → (name-in _str-eq_ y ns → False) → LC (open-t 0 LPV (FVar x) (open-t 0 RPV (FVar y) t₂))) → LC (Let t₁ a (PTensor s₁ s₂) t₂) LetPar : ∀{ns : 𝕃 String}{t₁ : Term}{a : Type}{t₂ : Term}{s₁ s₂ : String} → LC t₁ → LC t₂ → (∀{x y : String} → (name-in _str-eq_ x ns → False) → (name-in _str-eq_ y ns → False) → LC (open-t 0 LPV (FVar x) (open-t 0 RPV (FVar y) t₂))) → LC (Let t₁ a (PPar s₁ s₂) t₂) App : ∀{t₁ t₂ : Term} → LC t₁ → LC t₂ → LC (App t₁ t₂) Tensor : ∀{t₁ t₂ : Term} → LC t₁ → LC t₂ → LC (Tensor t₁ t₂) Par : ∀{t₁ t₂ : Term} → LC t₁ → LC t₂ → LC (Par t₁ t₂)
const INTERIOR_COEFFICIENTS = Dict{Int, Vector{Float64}}( 2 => [ 0.482962913145 ; 0.836516303738 ; 0.224143868042 ; -0.129409522551 ] , 3 => [ .332670552950 ; .806891509311 ; .459877502118 ; -.135011020010 ; -.085441273882 ; .035226291882 ] , 4 => [ 0.045570345896 ; -0.0178247014417 ; -0.140317624179 ; 0.421234534204 ; 1.13665824341 ; 0.703739068656 ; -0.0419109651251 ; -0.107148901418 ] / sqrt2 , 5 => [ 0.0276321529578 ; -0.0298424998687 ; -0.247951362613 ; 0.0234789231361 ; 0.89658164838 ; 1.02305296689 ; 0.281990696854 ; -0.0553441861166 ; 0.0417468644215 ; 0.0386547959548 ] / sqrt2 , 6 => [ -0.0110318675094 ; 0.00249992209279 ; 0.06325056266 ; -0.0297837512985 ; -0.102724969862 ; 0.477904371333 ; 1.11389278393 ; 0.694457972958 ; -0.0683231215866 ; -0.166863215412 ; 0.00493661237185 ; 0.0217847003266 ] / sqrt2 , 7 => [ 0.014521394762 ; 0.00567134268574 ; -0.152463871896 ; -0.198056706807 ; 0.408183939725 ; 1.08578270981 ; 0.758162601964 ; 0.0246656594886 ; -0.070078291222 ; 0.0960147679355 ; 0.043155452582 ; -0.0178704316511 ; -0.0014812259146 ; 0.0037926585342 ] / sqrt2 , 8 => [ 0.00267279339281 ; -0.000428394300246 ; -0.0211456865284 ; 0.00538638875377 ; 0.0694904659113 ; -0.0384935212634 ; -0.0734625087609 ; 0.515398670374 ; 1.09910663054 ; 0.68074534719 ; -0.0866536154058 ; -0.202648655286 ; 0.0107586117505 ; 0.0448236230437 ; -0.000766690896228 ; -0.0047834585115 ] / sqrt2 )
CUT egg into 4 or 5 pieces; arrange on flatbread. TOP with cheese. MICROWAVE an additional 10 to 15 seconds to melt cheese. SERVE immediately.
The measure of a subset of a countable set is zero if and only if the subset is empty.
#ifndef STAN_MATH_PRIM_SCAL_PROB_GAMMA_LPDF_HPP #define STAN_MATH_PRIM_SCAL_PROB_GAMMA_LPDF_HPP #include <stan/math/prim/scal/meta/is_constant_struct.hpp> #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/err/check_greater_or_equal.hpp> #include <stan/math/prim/scal/err/check_less_or_equal.hpp> #include <stan/math/prim/scal/err/check_nonnegative.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/err/check_positive_finite.hpp> #include <stan/math/prim/scal/fun/constants.hpp> #include <stan/math/prim/scal/fun/multiply_log.hpp> #include <stan/math/prim/scal/fun/value_of.hpp> #include <stan/math/prim/scal/fun/gamma_p.hpp> #include <stan/math/prim/scal/fun/digamma.hpp> #include <stan/math/prim/scal/meta/VectorBuilder.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <stan/math/prim/scal/fun/grad_reg_inc_gamma.hpp> #include <boost/random/gamma_distribution.hpp> #include <boost/random/variate_generator.hpp> #include <cmath> namespace stan { namespace math { /** * The log of a gamma density for y with the specified * shape and inverse scale parameters. * Shape and inverse scale parameters must be greater than 0. * y must be greater than or equal to 0. * \f{eqnarray*}{ y &\sim& \mbox{\sf{Gamma}}(\alpha, \beta) \\ \log (p (y \, |\, \alpha, \beta) ) &=& \log \left( \frac{\beta^\alpha}{\Gamma(\alpha)} y^{\alpha - 1} \exp^{- \beta y} \right) \\ &=& \alpha \log(\beta) - \log(\Gamma(\alpha)) + (\alpha - 1) \log(y) - \beta y\\ & & \mathrm{where} \; y > 0 \f} * @param y A scalar variable. * @param alpha Shape parameter. * @param beta Inverse scale parameter. * @throw std::domain_error if alpha is not greater than 0. * @throw std::domain_error if beta is not greater than 0. * @throw std::domain_error if y is not greater than or equal to 0. * @tparam T_y Type of scalar. * @tparam T_shape Type of shape. * @tparam T_inv_scale Type of inverse scale. */ template <bool propto, typename T_y, typename T_shape, typename T_inv_scale> typename return_type<T_y, T_shape, T_inv_scale>::type gamma_lpdf(const T_y& y, const T_shape& alpha, const T_inv_scale& beta) { static const char* function("gamma_lpdf"); typedef typename stan::partials_return_type<T_y, T_shape, T_inv_scale>::type T_partials_return; using stan::is_constant_struct; if (!(stan::length(y) && stan::length(alpha) && stan::length(beta))) return 0.0; T_partials_return logp(0.0); check_not_nan(function, "Random variable", y); check_positive_finite(function, "Shape parameter", alpha); check_positive_finite(function, "Inverse scale parameter", beta); check_consistent_sizes(function, "Random variable", y, "Shape parameter", alpha, "Inverse scale parameter", beta); if (!include_summand<propto, T_y, T_shape, T_inv_scale>::value) return 0.0; scalar_seq_view<T_y> y_vec(y); scalar_seq_view<T_shape> alpha_vec(alpha); scalar_seq_view<T_inv_scale> beta_vec(beta); for (size_t n = 0; n < length(y); n++) { const T_partials_return y_dbl = value_of(y_vec[n]); if (y_dbl < 0) return LOG_ZERO; } size_t N = max_size(y, alpha, beta); operands_and_partials<T_y, T_shape, T_inv_scale> ops_partials(y, alpha, beta); using boost::math::lgamma; using boost::math::digamma; using std::log; VectorBuilder<include_summand<propto, T_y, T_shape>::value, T_partials_return, T_y> log_y(length(y)); if (include_summand<propto, T_y, T_shape>::value) { for (size_t n = 0; n < length(y); n++) { if (value_of(y_vec[n]) > 0) log_y[n] = log(value_of(y_vec[n])); } } VectorBuilder<include_summand<propto, T_shape>::value, T_partials_return, T_shape> lgamma_alpha(length(alpha)); VectorBuilder<!is_constant_struct<T_shape>::value, T_partials_return, T_shape> digamma_alpha(length(alpha)); for (size_t n = 0; n < length(alpha); n++) { if (include_summand<propto, T_shape>::value) lgamma_alpha[n] = lgamma(value_of(alpha_vec[n])); if (!is_constant_struct<T_shape>::value) digamma_alpha[n] = digamma(value_of(alpha_vec[n])); } VectorBuilder<include_summand<propto, T_shape, T_inv_scale>::value, T_partials_return, T_inv_scale> log_beta(length(beta)); if (include_summand<propto, T_shape, T_inv_scale>::value) { for (size_t n = 0; n < length(beta); n++) log_beta[n] = log(value_of(beta_vec[n])); } for (size_t n = 0; n < N; n++) { const T_partials_return y_dbl = value_of(y_vec[n]); const T_partials_return alpha_dbl = value_of(alpha_vec[n]); const T_partials_return beta_dbl = value_of(beta_vec[n]); if (include_summand<propto, T_shape>::value) logp -= lgamma_alpha[n]; if (include_summand<propto, T_shape, T_inv_scale>::value) logp += alpha_dbl * log_beta[n]; if (include_summand<propto, T_y, T_shape>::value) logp += (alpha_dbl - 1.0) * log_y[n]; if (include_summand<propto, T_y, T_inv_scale>::value) logp -= beta_dbl * y_dbl; if (!is_constant_struct<T_y>::value) ops_partials.edge1_.partials_[n] += (alpha_dbl - 1) / y_dbl - beta_dbl; if (!is_constant_struct<T_shape>::value) ops_partials.edge2_.partials_[n] += -digamma_alpha[n] + log_beta[n] + log_y[n]; if (!is_constant_struct<T_inv_scale>::value) ops_partials.edge3_.partials_[n] += alpha_dbl / beta_dbl - y_dbl; } return ops_partials.build(logp); } template <typename T_y, typename T_shape, typename T_inv_scale> inline typename return_type<T_y, T_shape, T_inv_scale>::type gamma_lpdf(const T_y& y, const T_shape& alpha, const T_inv_scale& beta) { return gamma_lpdf<false>(y, alpha, beta); } } } #endif
! This routine computes equivalent reflectivity factor (in dBZ) at ! each model grid point. In calculating Ze, the RIP algorithm makes ! assumptions consistent with those made in an early version ! (ca. 1996) of the bulk mixed-phase microphysical scheme in the MM5 ! model (i.e., the scheme known as "Resiner-2"). For each species: ! ! 1. Particles are assumed to be spheres of constant density. The ! densities of rain drops, snow particles, and graupel particles are ! taken to be rho_r = rho_l = 1000 kg m^-3, rho_s = 100 kg m^-3, and ! rho_g = 400 kg m^-3, respectively. (l refers to the density of ! liquid water.) ! ! 2. The size distribution (in terms of the actual diameter of the ! particles, rather than the melted diameter or the equivalent solid ! ice sphere diameter) is assumed to follow an exponential ! distribution of the form N(D) = N_0 * exp( lambda*D ). ! ! 3. If ivarint=0, the intercept parameters are assumed constant ! (as in early Reisner-2), with values of 8x10^6, 2x10^7, ! and 4x10^6 m^-4, for rain, snow, and graupel, respectively. ! If ivarint=1, variable intercept parameters are used, as ! calculated in Thompson, Rasmussen, and Manning (2004, Monthly ! Weather Review, Vol. 132, No. 2, pp. 519-542.) ! ! 4. If iliqskin=1, frozen particles that are at a temperature above ! freezing are assumed to scatter as a liquid particle. ! ! More information on the derivation of simulated reflectivity in ! RIP can be found in Stoelinga (2005, unpublished write-up). ! Contact Mark Stoelinga ([email protected]) for a copy. !NCLFORTSTART SUBROUTINE CALCDBZ(prs, tmk, qvp, qra, qsn, qgr, sn0, ivarint, iliqskin, dbz, nx, ny, nz) USE wrf_constants, ONLY : GAMMA_SEVEN, RHOWAT, RHO_R, RHO_S, RHO_G, ALPHA, & CELKEL, PI, RD IMPLICIT NONE !f2py threadsafe !f2py intent(in,out) :: dbz ! Arguments INTEGER, INTENT(IN) :: nx, ny, nz INTEGER, INTENT(IN) :: sn0, ivarint, iliqskin REAL(KIND=8), DIMENSION(nx,ny,nz), INTENT(OUT) :: dbz REAL(KIND=8), DIMENSION(nx,ny,nz), INTENT(IN) :: prs REAL(KIND=8), DIMENSION(nx,ny,nz), INTENT(IN) :: tmk REAL(KIND=8), DIMENSION(nx,ny,nz), INTENT(INOUT) :: qvp REAL(KIND=8), DIMENSION(nx,ny,nz), INTENT(INOUT) :: qra REAL(KIND=8), DIMENSION(nx,ny,nz), INTENT(INOUT) :: qsn REAL(KIND=8), DIMENSION(nx,ny,nz), INTENT(INOUT) :: qgr !NCLEND ! Local Variables INTEGER :: i, j, k REAL(KIND=8) :: temp_c, virtual_t REAL(KIND=8) :: gonv, ronv, sonv REAL(KIND=8) :: factor_g, factor_r, factor_s REAL(KIND=8) :: factorb_g, factorb_s REAL(KIND=8) :: rhoair, z_e ! Constants used to calculate variable intercepts REAL(KIND=8), PARAMETER :: R1 = 1.D-15 REAL(KIND=8), PARAMETER :: RON = 8.D6 REAL(KIND=8), PARAMETER :: RON2 = 1.D10 REAL(KIND=8), PARAMETER :: SON = 2.D7 REAL(KIND=8), PARAMETER :: GON = 5.D7 REAL(KIND=8), PARAMETER :: RON_MIN = 8.D6 REAL(KIND=8), PARAMETER :: RON_QR0 = 0.00010D0 REAL(KIND=8), PARAMETER :: RON_DELQR0 = 0.25D0*RON_QR0 REAL(KIND=8), PARAMETER :: RON_CONST1R = (RON2-RON_MIN)*0.5D0 REAL(KIND=8), PARAMETER :: RON_CONST2R = (RON2+RON_MIN)*0.5D0 ! Constant intercepts REAL(KIND=8), PARAMETER :: RN0_R = 8.D6 REAL(KIND=8), PARAMETER :: RN0_S = 2.D7 REAL(KIND=8), PARAMETER :: RN0_G = 4.D6 !$OMP PARALLEL ! Force all Q arrays to be 0.0 or greater. !$OMP DO COLLAPSE(3) SCHEDULE(runtime) DO k = 1,nz DO j = 1,ny DO i = 1,nx IF (qvp(i,j,k) .LT. 0.0) THEN qvp(i,j,k) = 0.0 END IF IF (qra(i,j,k) .LT. 0.0) THEN qra(i,j,k) = 0.0 END IF IF (qsn(i,j,k) .LT. 0.0) THEN qsn(i,j,k) = 0.0 END IF IF (qgr(i,j,k) .LT. 0.0) THEN qgr(i,j,k) = 0.0 END IF END DO END DO END DO !$OMP END DO ! Input pressure is Pa, but we need hPa in calculations IF (sn0 .EQ. 0) THEN !$OMP DO COLLAPSE(3) SCHEDULE(runtime) DO k = 1,nz DO j = 1,ny DO i = 1,nx IF (tmk(i,j,k) .LT. CELKEL) THEN qsn(i,j,k) = qra(i,j,k) qra(i,j,k) = 0.D0 END IF END DO END DO END DO !$OMP END DO END IF factor_r = GAMMA_SEVEN*1.D18*(1.D0/(PI*RHO_R))**1.75D0 factor_s = GAMMA_SEVEN*1.D18*(1.D0/(PI*RHO_S))**1.75D0*(RHO_S/RHOWAT)**2*ALPHA factor_g = GAMMA_SEVEN*1.D18*(1.D0/(PI*RHO_G))**1.75D0*(RHO_G/RHOWAT)**2*ALPHA !$OMP DO COLLAPSE(3) PRIVATE(i, j, k, temp_c, virtual_t, gonv, ronv, sonv, & !$OMP factorb_g, factorb_s, rhoair, z_e) & !$OMP FIRSTPRIVATE(factor_r, factor_s, factor_g) SCHEDULE(runtime) DO k = 1,nz DO j = 1,ny DO i = 1,nx virtual_t = tmk(i,j,k)*(0.622D0 + qvp(i,j,k))/(0.622D0*(1.D0 + qvp(i,j,k))) rhoair = prs(i,j,k)/(RD*virtual_t) ! Adjust factor for brightband, where snow or graupel particle ! scatters like liquid water (alpha=1.0) because it is assumed to ! have a liquid skin. IF (iliqskin .EQ. 1 .AND. tmk(i,j,k) .GT. CELKEL) THEN factorb_s = factor_s/ALPHA factorb_g = factor_g/ALPHA ELSE factorb_s = factor_s factorb_g = factor_g END IF ! Calculate variable intercept parameters IF (ivarint .EQ. 1) THEN temp_c = MIN(-0.001D0, tmk(i,j,k)-CELKEL) sonv = MIN(2.0D8, 2.0D6*EXP(-0.12D0*temp_c)) gonv = gon IF (qgr(i,j,k) .GT. R1) THEN gonv = 2.38D0 * (PI*RHO_G/(rhoair*qgr(i,j,k)))**0.92D0 gonv = MAX(1.D4, MIN(gonv,GON)) END IF ronv = RON2 IF (qra(i,j,k) .GT. R1) THEN ronv = RON_CONST1R*TANH((RON_QR0 - qra(i,j,k))/RON_DELQR0) + RON_CONST2R END IF ELSE ronv = RN0_R sonv = RN0_S gonv = RN0_G END IF ! Total equivalent reflectivity factor (z_e, in mm^6 m^-3) is ! the sum of z_e for each hydrometeor species: z_e = factor_r*(rhoair*qra(i,j,k))**1.75D0/ronv**.75D0 + & factorb_s*(rhoair*qsn(i,j,k))**1.75D0/sonv**.75D0 + & factorb_g*(rhoair*qgr(i,j,k))**1.75D0/gonv**.75D0 ! Adjust small values of Z_e so that dBZ is no lower than -30 z_e = MAX(z_e, .001D0) ! Convert to dBZ dbz(i,j,k) = 10.D0*LOG10(z_e) END DO END DO END DO !$OMP END DO !$OMP END PARALLEL RETURN END SUBROUTINE CALCDBZ
Formal statement is: lemma closed_connected_component: assumes S: "closed S" shows "closed (connected_component_set S x)" Informal statement is: If $S$ is a closed set, then the connected component of $S$ containing $x$ is closed.
# These functions are only conditionally loaded with Clustering.jl # Code adapted from @cormullion's [ColorSchemeTools](https://github.com/JuliaGraphics/ColorSchemeTools.jl). function get_colorscheme( img, ncolors; maxiter=Clustering._kmeans_default_maxiter, tol=Clustering._kmeans_default_tol, ) # Cluster in Lab color space data = reshape(channelview(Lab.(img)), 3, :) R = Clustering.kmeans(data, ncolors; maxiter=maxiter, tol=tol) # Make color scheme out of cluster centers cs = Lab{Float64}[] for i in 1:3:length(R.centers) push!(cs, Lab(R.centers[i], R.centers[i + 1], R.centers[i + 2])) end return cs end function _colordither( ::Type{T}, img, alg, ncolors::Int; maxiter=Clustering._kmeans_default_maxiter, tol=Clustering._kmeans_default_tol, kwargs..., ) where {T} cs = get_colorscheme(img, ncolors; maxiter=maxiter, tol=tol) return _colordither(T, img, alg, cs; kwargs...) end """ dither!([out,] img, alg::AbstractDither, ncolors; maxiter, tol, kwargs...) Dither image `img` using algorithm `alg`. A color palette with `ncolors` is computed by Clustering.jl's K-means clustering. The amount of `maxiter` and tolerance `tol` default to those exported by Clustering.jl. """ dither!(img, alg::AbstractDither, ncolors::Int; kwargs...) """ dither([T::Type,] img, alg::AbstractDither, ncolors; maxiter, tol, kwargs...) Dither image `img` using algorithm `alg`. A color palette with `ncolors` is computed by Clustering.jl's K-means clustering. The amount of `maxiter` and tolerance `tol` default to those exported by Clustering.jl. """ dither(::Type, img, alg::AbstractDither, ncolors::Int; kwargs...)
The Sacramento Municipal Utility District (wiki:sacramento:SMUD) provides electricity to Sacramento County. It is a nonforprofit and publiclyowned utility with an elected board of directors. Yolo Annexation In January 2003, parts of Yolo County (i.e. Davis, Woodland, West Sacramento) started a feasibility study looking into switching from PG&E as electricity provider to SMUD. A map of the planned expansion as well as Yolo County Board of Supervisors agendas and documents are available at http://www.yolocounty.org/SMUD/default.htm. On April 20, 2006, the http://www.saclafco.org/ Sacramento Local Agency Formation Commission approved the annexation. SMUD may become the electrical provider for Davis, Woodland, and West Sacramento (as well as areas between them) as early as 2008 if voters in Yolo County approve November 2006 Election/Measure H Measures H&I and voters in Sacramento county approve Measure L in November 2006 Election November 2006. Measure H passed with 51% of the vote and Measure I failed by 10 votes. Furthermore, less than 40% of voters in both Sacramento and Placer Counties were in support of annexation, which means that, even if H and I both passed, annexation could not continue. Therefore, PG&E will remain the electricity provider for Yolo County. 20050712 10:30:55 nbsp Having lived in Sacramento, I see this as a good thing. Their rates are cheaper and they have much better customer service. Unfortunately PG&E will still be the gas company. Users/RogerClark 20060531 11:40:17 nbsp Ive been in Sac for 5 years now, and I also have only good things to say about SMUD. Where PG&E is well known for polluting land (i.e. the hexavalent chromium in Hinkley) SMUDs claim to fame is investment in renewable energy resources (see: http://en.wikipedia.org/wiki/SMUD). Users/LeightonHinkley 20060602 18:45:53 nbsp Public control of public resources, what a shocking idea! Users/KenjiYamada 20061020 01:01:11 nbsp vote! Users/MatthiasGropp 20071202 10:59:52 nbsp Im not happy with SMUD in Midtown Sacramento. If you have basic good habits and conserve energy, you wont use much, and youll end up with more expensive bills than PGEs: SMUD adds a $5.00 a month service charge which is pretty lame. Users/EdWins
Despite the setback of Crete , Andrew remained as commander of 22nd Battalion during the early phases of the North African Campaign . At one stage he was temporary commander of 5th Infantry Brigade when its nominal commander , Brigadier James Hargest , was captured in late November 1941 . Andrew was awarded with the Distinguished Service Order for his leadership of the brigade , which had to deal with repeated attacks by German forces in early December . He relinquished command of 22nd Battalion on 3 February 1942 , and returned to New Zealand . He was promoted to full colonel and commanded the Wellington Fortress Area for the rest of the war .
section "Hash-Maps (Interface Instantiations)" theory Hash_Map_Impl imports Imp_Map_Spec Hash_Map begin lemma hm_map_impl: "imp_map is_hashmap" apply unfold_locales apply (rule is_hashmap_prec) done interpretation hm: imp_map is_hashmap by (rule hm_map_impl) lemma hm_lookup_impl: "imp_map_lookup is_hashmap hm_lookup" apply unfold_locales apply (sep_auto heap: hm_lookup_rule) done interpretation hm: imp_map_lookup is_hashmap hm_lookup by (rule hm_lookup_impl) lemma hm_update_impl: "imp_map_update is_hashmap hm_update" apply unfold_locales apply (sep_auto heap: hm_update_rule) done interpretation hm: imp_map_update is_hashmap hm_update by (rule hm_update_impl) lemma hm_delete_impl: "imp_map_delete is_hashmap hm_delete" apply unfold_locales apply (sep_auto heap: hm_delete_rule) done interpretation hm: imp_map_delete is_hashmap hm_delete by (rule hm_delete_impl) lemma hm_is_empty_impl: "imp_map_is_empty is_hashmap hm_isEmpty" apply unfold_locales apply (sep_auto heap: hm_isEmpty_rule) done interpretation hm: imp_map_is_empty is_hashmap hm_isEmpty by (rule hm_is_empty_impl) lemma hm_size_impl: "imp_map_size is_hashmap hm_size" apply unfold_locales apply (sep_auto heap: hm_size_rule) done interpretation hm: imp_map_size is_hashmap hm_size by (rule hm_size_impl) lemma hm_iterate_impl: "imp_map_iterate is_hashmap hm_is_it hm_it_init hm_it_has_next hm_it_next" apply unfold_locales apply (rule hm_it_init_rule) apply (sep_auto heap add: hm_it_next_rule) apply (sep_auto heap add: hm_it_has_next_rule) apply (rule ent_frame_fwd[OF hm_it_finish]) apply (frame_inference) apply solve_entails done interpretation hm: imp_map_iterate is_hashmap hm_is_it hm_it_init hm_it_has_next hm_it_next by (rule hm_iterate_impl) (* definition "hm_is_it'' m ht l' it \<equiv> \<exists>\<^sub>Al. hm_is_it' l ht l' it * \<up>(map_of (concat l) = m)" lemma hm_iterate'_impl: "imp_map_iterate' is_hashmap hm_is_it'' hm_it_init hm_it_has_next hm_it_next" apply unfold_locales apply (rule hm_it_init_rule) apply (erule hm_it_next_rule) apply (rule hm_it_has_next_rule) apply (rule ent_frame_fwd[OF hm_it_finish]) apply (frame_inference) apply solve_entails done *) export_code hm_new hm_lookup hm_update hm_delete hm_isEmpty hm_size hm_it_init hm_it_has_next hm_it_next checking SML_imp end
# Learn More We're about ready to wrap up this brief course on Python for scientific computing. In this last lecture we give some pointers to the major scientific libraries and suggestions for further reading. ## NumPy Fundamental matrix and array processing capabilities are provided by the excellent [NumPy](http://www.numpy.org/) library. For example, let\'s build some arrays ``` import numpy as np # Load the library a = np.linspace(-np.pi, np.pi, 100) # Create even grid from -π to π b = np.cos(a) # Apply cosine to each element of a c = np.sin(a) # Apply sin to each element of a ``` Now let\'s take the inner product ``` b @ c ``` The number you see here might vary slightly due to floating point arithmetic but it\'s essentially zero. As with other standard NumPy operations, this inner product calls into highly optimized machine code. It is as efficient as carefully hand-coded FORTRAN or C. ## SciPy The [SciPy](http://www.scipy.org) library is built on top of NumPy and provides additional functionality. (tuple_unpacking_example)= For example, let\'s calculate $\int_{-2}^2 \phi(z) dz$ where $\phi$ is the standard normal density. ``` from scipy.stats import norm from scipy.integrate import quad ϕ = norm() value, error = quad(ϕ.pdf, -2, 2) # Integrate using Gaussian quadrature value ``` SciPy includes many of the standard routines used in - [linear algebra](http://docs.scipy.org/doc/scipy/reference/linalg.html) - [integration](http://docs.scipy.org/doc/scipy/reference/integrate.html) - [interpolation](http://docs.scipy.org/doc/scipy/reference/interpolate.html) - [optimization](http://docs.scipy.org/doc/scipy/reference/optimize.html) - [distributions and random number generation](http://docs.scipy.org/doc/scipy/reference/stats.html) - [signal processing](http://docs.scipy.org/doc/scipy/reference/signal.html) See them all [here](http://docs.scipy.org/doc/scipy/reference/index.html). ## Graphics The most popular and comprehensive Python library for creating figures and graphs is [Matplotlib](http://matplotlib.org/), with functionality including - plots, histograms, contour images, 3D graphs, bar charts etc. - output in many formats (PDF, PNG, EPS, etc.) - LaTeX integration Example 2D plot with embedded LaTeX annotations ```{figure} /_static/lecture_specific/about_py/qs.png :scale: 55% ``` Example contour plot ```{figure} /_static/lecture_specific/about_py/bn_density1.png :scale: 55% ``` Example 3D plot ```{figure} /_static/lecture_specific/about_py/career_vf.png :scale: 80% ``` More examples can be found in the [Matplotlib thumbnail gallery](http://matplotlib.org/gallery.html). Other graphics libraries include - [Plotly](https://plot.ly/python/) - [Bokeh](http://bokeh.pydata.org/en/latest/) ## Symbolic Algebra It\'s useful to be able to manipulate symbolic expressions, as in Mathematica or Maple. The [SymPy](http://www.sympy.org/) library provides this functionality from within the Python shell. ``` from sympy import Symbol x, y = Symbol('x'), Symbol('y') # Treat 'x' and 'y' as algebraic symbols x + x + x + y ``` We can manipulate expressions ``` expression = (x + y)**2 expression.expand() ``` solve polynomials ``` from sympy import solve solve(x**2 + x + 2) ``` and calculate limits, derivatives and integrals ``` from sympy import limit, sin, diff limit(1 / x, x, 0) ``` ``` limit(sin(x) / x, x, 0) ``` ``` diff(sin(x), x) ``` The beauty of importing this functionality into Python is that we are working within a fully fledged programming language. We can easily create tables of derivatives, generate LaTeX output, add that output to figures and so on. ## Pandas One of the most popular libraries for working with data is [pandas](http://pandas.pydata.org/). Pandas is fast, efficient, flexible and well designed. Here\'s a simple example, using some dummy data generated with Numpy\'s excellent `random` functionality. ``` import pandas as pd np.random.seed(1234) data = np.random.randn(5, 2) # 5x2 matrix of N(0, 1) random draws dates = pd.date_range('28/12/2010', periods=5) df = pd.DataFrame(data, columns=('price', 'weight'), index=dates) print(df) ``` ``` df.mean() ``` ## Further Reading These lectures were originally taken from a longer and more complete lecture series on Python programming hosted by [QuantEcon](https://quantecon.org). The [full set of lectures](https://python-programming.quantecon.org/) might be useful as the next step of your study.
A space $S$ is a deformation retract of a space $T$ if and only if $T$ is a retract of $S$ and there exists a continuous map $f$ from $S$ to $T$ such that $f$ is homotopic to the identity map on $S$ and $f(S) \subseteq T$.
(* Title: Native_Word_Test_Emu.thy Author: Andreas Lochbihler, ETH Zurich *) theory Native_Word_Test_Emu imports Native_Word_Test Code_Target_Int_Bit begin section \<open>Test cases for emulation of native words\<close> subsection \<open>Tests for @{typ uint16}\<close> text \<open> Test that @{typ uint16} is emulated for PolyML and OCaml via @{typ "16 word"} if @{theory Native_Word.Code_Target_Int_Bit} is imported. \<close> definition test_uint16_emulation :: bool where "test_uint16_emulation \<longleftrightarrow> (0xFFFFF - 0x1000 = (0xEFFF :: uint16))" export_code test_uint16_emulation checking SML OCaml? \<comment> \<open>test the other target languages as well\<close> Haskell? Scala notepad begin have test_uint16 by eval have test_uint16_emulation by eval have test_uint16_emulation by normalization have test_uint16_emulation by code_simp end ML_val \<open> val true = @{code test_uint16}; val true = @{code test_uint16_emulation}; \<close> lemma "x AND y = x OR (y :: uint16)" quickcheck[random, expect=counterexample] quickcheck[exhaustive, expect=counterexample] oops subsection \<open>Tests for @{typ uint8}\<close> text \<open> Test that @{typ uint8} is emulated for OCaml via @{typ "8 word"} if @{theory Native_Word.Code_Target_Int_Bit} is imported. \<close> definition test_uint8_emulation :: bool where "test_uint8_emulation \<longleftrightarrow> (0xFFF - 0x10 = (0xEF :: uint8))" export_code test_uint8_emulation checking OCaml? \<comment> \<open>test the other target languages as well\<close> SML Haskell? Scala end
function get_frequency(obj::ObservationType, arg0::SatelliteSystem) return jcall(obj, "getFrequency", Frequency, (SatelliteSystem,), arg0) end function get_measurement_type(obj::ObservationType) return jcall(obj, "getMeasurementType", MeasurementType, ()) end function get_signal_code(obj::ObservationType) return jcall(obj, "getSignalCode", SignalCode, ()) end function value_of(::Type{ObservationType}, arg0::JString) return jcall(ObservationType, "valueOf", ObservationType, (JString,), arg0) end function values(::Type{ObservationType}) return jcall(ObservationType, "values", Vector{ObservationType}, ()) end
Lane — F. Kinsey <unk>
module MUniverse where -- This is universe polymorphism and extensional equality module open import Sec2 -- import Data.List data _≃₀_ {A : Set} (a : A) (b : A) : Set where a≃b : (a ≡ b) → a ≃₀ b data _≃₁_ {A : Set} (f : A → A) (g : A → A) : Set where f≃g : ((x y : A) → (x ≃₀ y) → (f x ≃₀ g y)) → f ≃₁ g B==B : 1 ≃₀ 1 B==B = a≃b refl B==B1 : T ≃₀ T B==B1 = a≃b refl -- This is the same as + for natural numbers _⋆_ : (x y : ℕ) → ℕ Z ⋆ y = y (S x) ⋆ y = S (x ⋆ y) -- Proof that + and ⋆ are equivalent functions! +==⋆ : (x : ℕ) → ((_+_) x) ≃₁ ((_⋆_) x) +==⋆ x = f≃g (λ x₁ y x₂ → a≃b (prove x x₁ y x₂)) where fcong : (x y : ℕ) → (p : (x + y) ≡ (x ⋆ y)) → S (x + y) ≡ S (x ⋆ y) fcong x y p with (x + y) | (x ⋆ y) fcong x y refl | m | .m = refl prove' : (x y : ℕ) → (x + y) ≡ (x ⋆ y) prove' Z y = refl prove' (S x) y with (prove' x y) prove' (S x) y | p = fcong x y p prove : (x y z : ℕ) → (p : y ≃₀ z) → (x + y) ≡ (x ⋆ z) prove x y .y (a≃b refl) = prove' x y elim≃₁ : {A : Set} → (f g : A → A) (a : f ≃₁ g) → (x y : A) → (p : x ≃₀ y) → (f x ≃₀ g y) elim≃₁ f g (f≃g a) x .x (a≃b refl) = a x x (a≃b refl) -- Theorem that ≃₁ is a partial equivalence relation ≃₁-symmetric : {A : Set} → {f g : A → A} → (f ≃₁ g) → (g ≃₁ f) ≃₁-symmetric {A} {f} {g} (f≃g x) = f≃g (λ x₁ y x₂ → a≃b (prove x₁ y x₂ (f≃g x))) where prove : (z y : A) → (p : z ≃₀ y) → (f ≃₁ g) → (g z ≡ f y) prove z .z (a≃b refl) (f≃g x) with (x z z (a≃b refl) ) prove z .z (a≃b refl) (f≃g x₁) | a≃b p with (f z) | (g z) prove z .z (a≃b refl) (f≃g x₁) | a≃b refl | m | .m = refl ≃₁-transitive : {A : Set} → {f g h : A → A} → (f ≃₁ g) → (g ≃₁ h) → (f ≃₁ h) ≃₁-transitive {A} {f} {g} {h} (f≃g x) (f≃g y) = f≃g (λ x₁ y₁ x₂ → a≃b (prove x₁ y₁ x₂ (f≃g x) (f≃g y))) where prove : (x y : A) (p : x ≃₀ y) → (f ≃₁ g) → (g ≃₁ h) → (f x ≡ h y) prove x₁ .x₁ (a≃b refl) (f≃g x₂) (f≃g x₃) with (x₂ x₁ x₁ (a≃b refl)) | (x₃ x₁ x₁ (a≃b refl)) prove x₁ .x₁ (a≃b refl) (f≃g x₂) (f≃g x₃) | a≃b x₄ | a≃b x₅ with (f x₁) | (g x₁) | (h x₁) prove x₁ .x₁ (a≃b refl) (f≃g x₂) (f≃g x₃) | a≃b refl | a≃b refl | p1 | .p1 | .p1 = refl
/** * @copyright 2017 Edwin Kepler * @license MIT */ #ifndef VECTORS_OF_TUPLES_HPP #define VECTORS_OF_TUPLES_HPP #include <vector> #include <tuple> #include <algorithm> #include <iostream> #include <boost/test/unit_test.hpp> using namespace std; void print_vector_of_tuples_3(vector<tuple<int, int, int>> vot) { for(int i = 0; i < vot.size(); i++) { cout << "(" << get<0>(vot.at(i)) << ", " << get<1>(vot.at(i)) << ", " << get<2>(vot.at(i)) << ")" << endl; } } void print_vector_of_tuples_7( vector<tuple<int, int, int, int, int, int, int>> vot) { for(int i = 0; i < vot.size(); i++) { cout << "(" << get<0>(vot.at(i)) << ", " << get<1>(vot.at(i)) << ", " << get<2>(vot.at(i)) << ")" << endl; } } void TEST_PAIRS(pair<int, int> lh, pair<int, int> rh) { BOOST_REQUIRE_EQUAL(get<0>(lh), get<0>(rh)); BOOST_REQUIRE_EQUAL(get<1>(lh), get<1>(rh)); } void TEST_VECTORS_OF_TUPLES_3( vector<tuple<int, int, int>> lh, vector<tuple<int, int, int>> rh) { sort(lh.begin(), lh.end()); sort(rh.begin(), rh.end()); if(lh.size() != rh.size()) { cout << "LH != RH" << endl; cout << "LH (after sorting):" << endl; print_vector_of_tuples_3(lh); cout << "RH (after sorting):" << endl; print_vector_of_tuples_3(rh); BOOST_FAIL("LH != RH"); } for(int i = 0; i < lh.size(); i++) { if( get<0>(lh.at(i)) != get<0>(rh.at(i)) || get<1>(lh.at(i)) != get<1>(rh.at(i)) || get<2>(lh.at(i)) != get<2>(rh.at(i))) { cout << "LH != RH" << endl; cout << "LH (after sorting):" << endl; print_vector_of_tuples_3(lh); cout << "RH (after sorting):" << endl; print_vector_of_tuples_3(rh); BOOST_FAIL("LH != RH"); } } } void TEST_VECTORS_OF_TUPLES_7( vector<tuple<int, int, int, int, int, int, int>> lh, vector<tuple<int, int, int, int, int, int, int>> rh) { if(lh.size() != rh.size()) { cout << "LH != RH" << endl; cout << "LH:" << endl; print_vector_of_tuples_7(lh); cout << "RH:" << endl; print_vector_of_tuples_7(rh); BOOST_FAIL("LH != RH"); } for(int i = 0; i < lh.size(); i++) { BOOST_REQUIRE_EQUAL(get<0>(lh.at(i)), get<0>(rh.at(i))); BOOST_REQUIRE_EQUAL(get<1>(lh.at(i)), get<1>(rh.at(i))); BOOST_REQUIRE_EQUAL(get<2>(lh.at(i)), get<2>(rh.at(i))); BOOST_REQUIRE_EQUAL(get<3>(lh.at(i)), get<3>(rh.at(i))); BOOST_REQUIRE_EQUAL(get<4>(lh.at(i)), get<4>(rh.at(i))); BOOST_REQUIRE_EQUAL(get<5>(lh.at(i)), get<5>(rh.at(i))); BOOST_REQUIRE_EQUAL(get<6>(lh.at(i)), get<6>(rh.at(i))); } } #endif // VECTORS_OF_TUPLES_HPP
On 26 April 2008 , Stansfield scored in Exeter 's 4 – 4 draw at Burton Albion which qualified them for that season 's play @-@ offs . He started in the final , whereby the team returned to The Football League for the first time in five years with a 1 – 0 Wembley win over Cambridge United .
``` # Se importan las librerias para calculo simbolico from IPython.display import display from sympy import var, simplify, collect, expand, solve, sin, cos, Matrix, eye, diff, Function, expand_power_base, exp from sympy.physics.mechanics import mlatex, mechanics_printing mechanics_printing() ``` ``` var("s, t, lamda") ``` ``` A = Matrix([[-2, 3, 0], [0, 1, 0], [0, 1, -1]]) ``` ``` (s*eye(3) - A).inv() ``` ``` exp(A*t) ``` ``` exp(A*t).subs(t, 0) ``` ``` exp(A*t).diff(t) == A*exp(A*t) ``` True ``` (Matrix([[1, -1, 1], [1, 1, 1], [1, -2, 4]]).inv()*Matrix([[exp(-t)], [exp(t)], [exp(-2*t)]])).T ``` ``` (Matrix([[1, -1, 1], [1, 1, 1], [1, -2, 4]]).inv()*Matrix([[exp(-t)], [exp(t)], [exp(-2*t)]])) ```
lemma closed_Un [continuous_intros, intro]: "closed S \<Longrightarrow> closed T \<Longrightarrow> closed (S \<union> T)"
### Lab 3: Expectation Maximization and Variational Autoencoder ### Machine Learning 2 (2019) * The lab exercises can be done in groups of two people, or individually. * The deadline is Tuesday, October 15th at 17:00. * Assignment should be submitted through Canvas! Make sure to include your and your teammates' names with the submission. * Attach the .IPYNB (IPython Notebook) file containing your code and answers. Naming of the file should be "studentid1\_studentid2\_lab#", for example, the attached file should be "12345\_12346\_lab1.ipynb". Only use underscores ("\_") to connect ids, otherwise the files cannot be parsed. Notes on implementation: * You should write your code and answers in an IPython Notebook: http://ipython.org/notebook.html. If you have problems, please ask. * Use __one cell__ for code and markdown answers only! * Put all code in the cell with the ```# YOUR CODE HERE``` comment and overwrite the ```raise NotImplementedError()``` line. * For theoretical questions, put your solution using LaTeX style formatting in the YOUR ANSWER HERE cell. * Among the first lines of your notebook should be "%pylab inline". This imports all required modules, and your plots will appear inline. * Large parts of you notebook will be graded automatically. Therefore it is important that your notebook can be run completely without errors and within a reasonable time limit. To test your notebook before submission, select Kernel -> Restart \& Run All. $\newcommand{\bx}{\mathbf{x}} \newcommand{\bpi}{\mathbf{\pi}} \newcommand{\bmu}{\mathbf{\mu}} \newcommand{\bX}{\mathbf{X}} \newcommand{\bZ}{\mathbf{Z}} \newcommand{\bz}{\mathbf{z}}$ ### Installing PyTorch In this lab we will use PyTorch. PyTorch is an open source deep learning framework primarily developed by Facebook's artificial-intelligence research group. In order to install PyTorch in your conda environment go to https://pytorch.org and select your operating system, conda, Python 3.6, no cuda. Copy the text from the "Run this command:" box. Now open a terminal and activate your 'ml2labs' conda environment. Paste the text and run. After the installation is done you should restart Jupyter. ### MNIST data In this Lab we will use several methods for unsupervised learning on the MNIST dataset of written digits. The dataset contains digital images of handwritten numbers $0$ through $9$. Each image has 28x28 pixels that each take 256 values in a range from white ($= 0$) to black ($=1$). The labels belonging to the images are also included. Fortunately, PyTorch comes with a MNIST data loader. The first time you run the box below it will download the MNIST data set. That can take a couple of minutes. The main data types in PyTorch are tensors. For Part 1, we will convert those tensors to numpy arrays. In Part 2, we will use the torch module to directly work with PyTorch tensors. ```python %pylab inline import torch from torchvision import datasets, transforms train_dataset = datasets.MNIST('../data', train=True, download=True, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])) train_labels = train_dataset.train_labels.numpy() train_data = train_dataset.train_data.numpy() # For EM we will use flattened data train_data = train_data.reshape(train_data.shape[0], -1) ``` Populating the interactive namespace from numpy and matplotlib C:\Users\lintl\Anaconda3\envs\rl2019\lib\site-packages\torchvision\datasets\mnist.py:43: UserWarning: train_labels has been renamed targets warnings.warn("train_labels has been renamed targets") C:\Users\lintl\Anaconda3\envs\rl2019\lib\site-packages\torchvision\datasets\mnist.py:53: UserWarning: train_data has been renamed data warnings.warn("train_data has been renamed data") ## Part 1: Expectation Maximization We will use the Expectation Maximization (EM) algorithm for the recognition of handwritten digits in the MNIST dataset. The images are modelled as a Bernoulli mixture model (see Bishop $\S9.3.3$): $$ p(\bx|\bmu, \bpi) = \sum_{k=1}^K \pi_k \prod_{i=1}^D \mu_{ki}^{x_i}(1-\mu_{ki})^{(1-x_i)} $$ where $x_i$ is the value of pixel $i$ in an image, $\mu_{ki}$ represents the probability that pixel $i$ in class $k$ is black, and $\{\pi_1, \ldots, \pi_K\}$ are the mixing coefficients of classes in the data. We want to use this data set to classify new images of handwritten numbers. ### 1.1 Binary data (5 points) As we like to apply our Bernoulli mixture model, write a function `binarize` to convert the (flattened) MNIST data to binary images, where each pixel $x_i \in \{0,1\}$, by thresholding at an appropriate level. ```python def binarize(X): return (X > 128).astype(np.float) ``` ```python # Test test test! bin_train_data = binarize(train_data) assert bin_train_data.dtype == np.float assert bin_train_data.shape == train_data.shape ``` Sample a few images of digits $2$, $3$ and $4$; and show both the original and the binarized image together with their label. ```python numbers = [2,3,4] def plot_image(number, images, labels, sample): index = np.where(labels == number)[0][sample] title = "Digit" + str(labels[index]) + ":" plt.imshow(images[index].reshape(28,28)) plt.title(title + " Non Binarized") def plot_bin_non_bin(numbers, train, train_labels, bin_train, sample): counter = 0 for i in range(len(numbers)): fig = plt.figure(figsize=(15,10)) plt.subplot(341) plot_image(numbers[i], train_data, train_labels, sample[0]) plt.subplot(341 + 1) plot_image(numbers[i], bin_train, train_labels, sample[0]) plt.subplot(341 + 2) plot_image(numbers[i], train_data, train_labels, sample[1]) plt.subplot(341 + 3) plot_image(numbers[i], bin_train, train_labels, sample[1]) plt.show() plot_bin_non_bin(numbers, train_data, train_labels, bin_train_data, [3,4]) ``` ### 1.2 Implementation (40 points) You are going to write a function ```EM(X, K, max_iter)``` that implements the EM algorithm on the Bernoulli mixture model. The only parameters the function has are: * ```X``` :: (NxD) array of input training images * ```K``` :: size of the latent space * ```max_iter``` :: maximum number of iterations, i.e. one E-step and one M-step You are free to specify your return statement. Make sure you use a sensible way of terminating the iteration process early to prevent unnecessarily running through all epochs. Vectorize computations using ```numpy``` as much as possible. You should implement the `E_step(X, mu, pi)` and `M_step(X, gamma)` separately in the functions defined below. These you can then use in your function `EM(X, K, max_iter)`. ```python def E_step(X, mu, pi): # get dimensions of gamma X_expand = np.expand_dims(X, axis=1) unnorm_gamma = pi * np.prod((mu ** X_expand) * ((1 - mu) ** (1 - X_expand)), axis=2) denominator = np.expand_dims(np.sum(unnorm_gamma, axis=1), axis=1) gamma = unnorm_gamma / denominator return gamma ``` ```python # Let's test on 5 datapoints n_test = 5 X_test = bin_train_data[:n_test] D_test, K_test = X_test.shape[1], 10 np.random.seed(2018) mu_test = np.random.uniform(low=.25, high=.75, size=(K_test,D_test)) pi_test = np.ones(K_test) / K_test gamma_test = E_step(X_test, mu_test, pi_test) assert gamma_test.shape == (n_test, K_test) ``` ```python def M_step(X, gamma): # we sum over the number of datapoints N_k = gamma.sum(axis=0) # pi is the fraction of N_k over the total sum ofer N_k pi = N_k / np.sum(N_k) # expanding with [None,:] and [:, None] tmp_mu = gamma[None,:].T * X[None, :] # unnormalized mu unnorm_mu = tmp_mu.sum(axis=1) # normalized mu mu = unnorm_mu / N_k[:, None] return mu, pi ``` ```python # Oh, let's test again mu_test, pi_test = M_step(X_test, gamma_test) assert mu_test.shape == (K_test,D_test) assert pi_test.shape == (K_test, ) ``` ```python def EM(X, K, max_iter, mu=None, pi=None): # dimensions N = X.shape[0] D = X.shape[1] # parameter initialization if mu is None: mu = np.random.uniform(0.25, 0.75, (K,D)) if pi is None: pi = np.ones(K) / K conv_crit = 1e-4 for i in range(max_iter): mu_old = mu pi_old = pi gamma = E_step(X, mu, pi) mu, pi = M_step(X, gamma) mu_update = np.linalg.norm(mu-mu_old) pi_update = np.linalg.norm(pi-pi_old) print("Iteration: {}, delta_mu: {}, delta_pi: {}".format(i, np.round(mu_update, 5), np.round(pi_update, 5))) if mu_update < conv_crit and pi_update < conv_crit: print("After iteration {}, convergence is reached".format(i)) break return gamma, mu, pi ``` ### 1.3 Three digits experiment (10 points) In analogue with Bishop $\S9.3.3$, sample a training set consisting of only __binary__ images of written digits $2$, $3$, and $4$. Run your EM algorithm and show the reconstructed digits. ```python def plot_mu(mu): K = mu.shape[0] fig, axes = plt.subplots(1, K, figsize=(15, 10)) for k, ax in enumerate(axes): ax.imshow(mu[k].reshape((28,28))) plt.show() numbers = [2,3,4] max_iter = 100 example_train_labels = train_labels[np.isin(train_labels, numbers)] example_trainbinary = bin_train_data[np.isin(train_labels, numbers), :] ``` ```python gamma, mu, pi = EM(example_trainbinary, 3, 100) #show_mu(mu_3) ``` Iteration: 0, delta_mu: 20.62302, delta_pi: 0.47597 Iteration: 1, delta_mu: 2.69712, delta_pi: 0.16751 Iteration: 2, delta_mu: 1.76431, delta_pi: 0.12087 Iteration: 3, delta_mu: 1.19617, delta_pi: 0.11609 Iteration: 4, delta_mu: 0.6832, delta_pi: 0.06307 Iteration: 5, delta_mu: 0.23769, delta_pi: 0.01967 Iteration: 6, delta_mu: 0.06954, delta_pi: 0.00507 Iteration: 7, delta_mu: 0.02194, delta_pi: 0.00145 Iteration: 8, delta_mu: 0.00868, delta_pi: 0.00052 Iteration: 9, delta_mu: 0.00348, delta_pi: 0.00019 Iteration: 10, delta_mu: 0.00165, delta_pi: 6e-05 Iteration: 11, delta_mu: 0.00181, delta_pi: 8e-05 Iteration: 12, delta_mu: 0.00072, delta_pi: 5e-05 Iteration: 13, delta_mu: 0.00044, delta_pi: 3e-05 Iteration: 14, delta_mu: 0.00095, delta_pi: 4e-05 Iteration: 15, delta_mu: 0.0011, delta_pi: 5e-05 Iteration: 16, delta_mu: 0.00022, delta_pi: 2e-05 Iteration: 17, delta_mu: 9e-05, delta_pi: 1e-05 After iteration 17, convergence is reached ```python plot_mu(mu) print("Mixing coefficients: {}".format(pi)) ``` Can you identify which element in the latent space corresponds to which digit? What are the identified mixing coefficients for digits $2$, $3$ and $4$, and how do these compare to the true ones? Considering the visualizations, it is obvious that the elements in the latent space illustrate the numbers of the classes, namely 2,3,4. So, in the above shown images, the activated regions illustrate probabilities represent if a pixel is active and therefore, the shape of the digits is detectable. The mixing coefficients are uniformly distributed, which is in line with the assumption, that each number appears equally often. ### 1.4 Experiments (20 points) Perform the follow-up experiments listed below using your implementation of the EM algorithm. For each of these, describe/comment on the obtained results and give an explanation. You may still use your dataset with only digits 2, 3 and 4 as otherwise computations can take very long. #### 1.4.1 Size of the latent space (5 points) Run EM with $K$ larger or smaller than the true number of classes. Describe your results. ```python gamma_2, mu_2, pi_2 = EM(example_trainbinary, 2, 100) plot_mu(mu_2) print("Mixing coefficients for 2 classes: {}".format(pi_2)) ``` ```python gamma_5, mu_5, pi_5 = EM(example_trainbinary, 5, 100) plot_mu(mu_5) print("Mixing coefficients for 5 classes: {}".format(pi)) ``` The first case, a number smaller than the actual number of classes, the convergence of $\mu_k$s to the actual classes is not guaranteed anymore, as seen in the picture, the first image is not clearly a three, but rather a mixture between three and two. The second image actually looks like it converged to a proper 4. For the larger case, we see, that convergence in itself takes much longer. Also, it is notable that the digits 4 and 2 are represented doubly. Therefore, compared to the smaller number of classes each $\mu_k$ seemingly actually converged to a true class, as none of the shown digits seems distorted or as a mixture of classes. It is also notable, that the digits of the same class vary in their look (the two 2s and 4s seem different), which might stemm from the fact that they reflect a different region of the possible shapes of the respective digits. The mixture components seem to adapt, as they stay relatively uniform. So, both a too small and a too large number of classes lead to acuracy loss. Once, the classes are mixed and once multiple representations appear. #### 1.4.2 Identify misclassifications (10 points) How can you use the data labels to assign a label to each of the clusters/latent variables? Use this to identify images that are 'misclassified' and try to understand why they are. Report your findings. ```python ``` YOUR ANSWER HERE #### 1.4.3 Initialize with true values (5 points) Initialize the three classes with the true values of the parameters and see what happens. Report your results. ```python ``` YOUR ANSWER HERE ## Part 2: Variational Auto-Encoder A Variational Auto-Encoder (VAE) is a probabilistic model $p(\bx, \bz)$ over observed variables $\bx$ and latent variables and/or parameters $\bz$. Here we distinguish the decoder part, $p(\bx | \bz) p(\bz)$ and an encoder part $p(\bz | \bx)$ that are both specified with a neural network. A lower bound on the log marginal likelihood $\log p(\bx)$ can be obtained by approximately inferring the latent variables z from the observed data x using an encoder distribution $q(\bz| \bx)$ that is also specified as a neural network. This lower bound is then optimized to fit the model to the data. The model was introduced by Diederik Kingma (during his PhD at the UVA) and Max Welling in 2013, https://arxiv.org/abs/1312.6114. Since it is such an important model there are plenty of well written tutorials that should help you with the assignment. E.g: https://jaan.io/what-is-variational-autoencoder-vae-tutorial/. In the following, we will make heavily use of the torch module, https://pytorch.org/docs/stable/index.html. Most of the time replacing `np.` with `torch.` will do the trick, e.g. `np.sum` becomes `torch.sum` and `np.log` becomes `torch.log`. In addition, we will use `torch.FloatTensor()` as an equivalent to `np.array()`. In order to train our VAE efficiently we will make use of batching. The number of data points in a batch will become the first dimension of our data tensor, e.g. A batch of 128 MNIST images has the dimensions [128, 1, 28, 28]. To check check the dimensions of a tensor you can call `.size()`. ### 2.1 Loss function The objective function (variational lower bound), that we will use to train the VAE, consists of two terms: a log Bernoulli loss (reconstruction loss) and a Kullback–Leibler divergence. We implement the two terms separately and combine them in the end. As seen in Part 1: Expectation Maximization, we can use a multivariate Bernoulli distribution to model the likelihood $p(\bx | \bz)$ of black and white images. Formally, the variational lower bound is maximized but in PyTorch we are always minimizing therefore we need to calculate the negative log Bernoulli loss and Kullback–Leibler divergence. ### 2.1.1 Negative Log Bernoulli loss (5 points) The negative log Bernoulli loss is defined as, \begin{align} loss = - (\sum_i^D \bx_i \log \hat{\bx_i} + (1 − \bx_i) \log(1 − \hat{\bx_i})). \end{align} Write a function `log_bernoulli_loss` that takes a D dimensional vector `x`, its reconstruction `x_hat` and returns the negative log Bernoulli loss. Make sure that your function works for batches of arbitrary size. ```python def log_bernoulli_loss(x_hat, x): loss = -torch.sum(x * torch.log(x_hat) + (1 - x) * torch.log(1 - x_hat)) return loss ``` ```python ### Test test test x_test = torch.FloatTensor([[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], [0.9, 0.9, 0.9, 0.9]]) x_hat_test = torch.FloatTensor([[0.11, 0.22, 0.33, 0.44], [0.55, 0.66, 0.77, 0.88], [0.99, 0.99, 0.99, 0.99]]) assert log_bernoulli_loss(x_hat_test, x_test) > 0.0 assert log_bernoulli_loss(x_hat_test, x_test) < 10.0 ``` ### 2.1.2 Negative Kullback–Leibler divergence (10 Points) The variational lower bound (the objective to be maximized) contains a KL term $D_{KL}(q(\bz)||p(\bz))$ that can often be calculated analytically. In the VAE we assume $q = N(\bz, \mu, \sigma^2I)$ and $p = N(\bz, 0, I)$. Solve analytically! YOUR ANSWER HERE Write a function `KL_loss` that takes two J dimensional vectors `mu` and `logvar` and returns the negative Kullback–Leibler divergence. Where `logvar` is $\log(\sigma^2)$. Make sure that your function works for batches of arbitrary size. ```python def KL_loss(mu, logvar): loss = -(1/2) * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) return loss ``` ```python ### Test test test mu_test = torch.FloatTensor([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]) logvar_test = torch.FloatTensor([[0.01, 0.02], [0.03, 0.04], [0.05, 0.06]]) assert KL_loss(mu_test, logvar_test) > 0.0 assert KL_loss(mu_test, logvar_test) < 10.0 ``` ### 2.1.3 Putting the losses together (5 points) Write a function `loss_function` that takes a D dimensional vector `x`, its reconstruction `x_hat`, two J dimensional vectors `mu` and `logvar` and returns the final loss. Make sure that your function works for batches of arbitrary size. ```python def loss_function(x_hat, x, mu, logvar): loss = log_bernoulli_loss(x_hat, x) + KL_loss(mu, logvar) return loss ``` ```python x_test = torch.FloatTensor([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]]) x_hat_test = torch.FloatTensor([[0.11, 0.22, 0.33], [0.44, 0.55, 0.66], [0.77, 0.88, 0.99]]) mu_test = torch.FloatTensor([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]) logvar_test = torch.FloatTensor([[0.01, 0.02], [0.03, 0.04], [0.05, 0.06]]) assert loss_function(x_hat_test, x_test, mu_test, logvar_test) > 0.0 assert loss_function(x_hat_test, x_test, mu_test, logvar_test) < 10.0 ``` ### 2.2 The model Below you see a data structure for the VAE. The modell itself consists of two main parts the encoder (images $\bx$ to latent variables $\bz$) and the decoder (latent variables $\bz$ to images $\bx$). The encoder is using 3 fully-connected layers, whereas the decoder is using fully-connected layers. Right now the data structure is quite empty, step by step will update its functionality. For test purposes we will initialize a VAE for you. After the data structure is completed you will do the hyperparameter search. ```python from torch import nn from torch.nn import functional as F class VAE(nn.Module): def __init__(self, fc1_dims, fc21_dims, fc22_dims, fc3_dims, fc4_dims): super(VAE, self).__init__() self.fc1 = nn.Linear(*fc1_dims) self.fc21 = nn.Linear(*fc21_dims) self.fc22 = nn.Linear(*fc22_dims) self.fc3 = nn.Linear(*fc3_dims) self.fc4 = nn.Linear(*fc4_dims) def encode(self, x): # To be implemented raise Exception('Method not implemented') def reparameterize(self, mu, logvar): # To be implemented raise Exception('Method not implemented') def decode(self, z): # To be implemented raise Exception('Method not implemented') def forward(self, x): # To be implemented raise Exception('Method not implemented') VAE_test = VAE(fc1_dims=(784, 4), fc21_dims=(4, 2), fc22_dims=(4, 2), fc3_dims=(2, 4), fc4_dims=(4, 784)) ``` ### 2.3 Encoding (10 points) Write a function `encode` that gets a vector `x` with 784 elements (flattened MNIST image) and returns `mu` and `logvar`. Your function should use three fully-connected layers (`self.fc1()`, `self.fc21()`, `self.fc22()`). First, you should use `self.fc1()` to embed `x`. Second, you should use `self.fc21()` and `self.fc22()` on the embedding of `x` to compute `mu` and `logvar` respectively. PyTorch comes with a variety of activation functions, the most common calls are `F.relu()`, `F.sigmoid()`, `F.tanh()`. Make sure that your function works for batches of arbitrary size. ```python def encode(self, x): h1 = F.relu(self.fc1(x)) mu = self.fc21(h1) logvar = self.fc22(h1) return mu, logvar ``` ```python ### Test, test, test VAE.encode = encode x_test = torch.ones((5,784)) mu_test, logvar_test = VAE_test.encode(x_test) assert np.allclose(mu_test.size(), [5, 2]) assert np.allclose(logvar_test.size(), [5, 2]) ``` ### 2.4 Reparameterization (10 points) One of the major question that the VAE is answering, is 'how to take derivatives with respect to the parameters of a stochastic variable?', i.e. if we are given $\bz$ that is drawn from a distribution $q(\bz|\bx)$, and we want to take derivatives. This step is necessary to be able to use gradient-based optimization algorithms like SGD. For some distributions, it is possible to reparameterize samples in a clever way, such that the stochasticity is independent of the parameters. We want our samples to deterministically depend on the parameters of the distribution. For example, in a normally-distributed variable with mean $\mu$ and standard deviation $\sigma$, we can sample from it like this: \begin{align} \bz = \mu + \sigma \odot \epsilon, \end{align} where $\odot$ is the element-wise multiplication and $\epsilon$ is sampled from $N(0, I)$. Write a function `reparameterize` that takes two J dimensional vectors `mu` and `logvar`. It should return $\bz = \mu + \sigma \odot \epsilon$. ```python def reparameterize(self, mu, logvar): return mu + torch.exp(1/2 * logvar) * torch.randn_like(mu) ``` ```python ### Test, test, test VAE.reparameterize = reparameterize VAE_test.train() mu_test = torch.FloatTensor([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]) logvar_test = torch.FloatTensor([[0.01, 0.02], [0.03, 0.04], [0.05, 0.06]]) z_test = VAE_test.reparameterize(mu_test, logvar_test) assert np.allclose(z_test.size(), [3, 2]) assert z_test[0][0] < 5.0 assert z_test[0][0] > -5.0 ``` ### 2.5 Decoding (10 points) Write a function `decode` that gets a vector `z` with J elements and returns a vector `x_hat` with 784 elements (flattened MNIST image). Your function should use two fully-connected layers (`self.fc3()`, `self.fc4()`). PyTorch comes with a variety of activation functions, the most common calls are `F.relu()`, `F.sigmoid()`, `F.tanh()`. Make sure that your function works for batches of arbitrary size. ```python def decode(self, z): h1 = self.fc3(z) h1 = F.relu(h1) h1 = self.fc4(h1) x_hat = F.sigmoid(h1) return x_hat ``` ```python # test test test VAE.decode = decode z_test = torch.ones((5,2)) x_hat_test = VAE_test.decode(z_test) assert np.allclose(x_hat_test.size(), [5, 784]) assert (x_hat_test <= 1).all() assert (x_hat_test >= 0).all() ``` C:\Users\lintl\Anaconda3\envs\rl2019\lib\site-packages\torch\nn\functional.py:1350: UserWarning: nn.functional.sigmoid is deprecated. Use torch.sigmoid instead. warnings.warn("nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.") ### 2.6 Forward pass (10) To complete the data structure you have to define a forward pass through the VAE. A single forward pass consists of the encoding of an MNIST image $\bx$ into latent space $\bz$, the reparameterization of $\bz$ and the decoding of $\bz$ into an image $\bx$. Write a function `forward` that gets a a vector `x` with 784 elements (flattened MNIST image) and returns a vector `x_hat` with 784 elements (flattened MNIST image), `mu` and `logvar`. ```python def forward(self, x): x = x.view(-1, 784) mu, logvar = self.encode(x) z = self.reparameterize(mu, logvar) x_hat = self.decode(z) return x_hat, mu, logvar ``` ```python # test test test VAE.forward = forward x_test = torch.ones((5,784)) x_hat_test, mu_test, logvar_test = VAE_test.forward(x_test) assert np.allclose(x_hat_test.size(), [5, 784]) assert np.allclose(mu_test.size(), [5, 2]) assert np.allclose(logvar_test.size(), [5, 2]) ``` ### 2.7 Training (15) We will now train the VAE using an optimizer called Adam, https://arxiv.org/abs/1412.6980. The code to train a model in PyTorch is given below. ```python from torch.autograd import Variable def train(epoch, train_loader, model, optimizer): model.train() train_loss = 0 for batch_idx, (data, _) in enumerate(train_loader): data = Variable(data) optimizer.zero_grad() recon_batch, mu, logvar = model(data) loss = loss_function(recon_batch, data.view(-1, 784), mu, logvar) loss.backward() train_loss += loss.data optimizer.step() if batch_idx % 100 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.data / len(data))) print('====> Epoch: {} Average loss: {:.4f}'.format( epoch, train_loss / len(train_loader.dataset))) ``` Let's train. You have to choose the hyperparameters. Make sure your loss is going down in a reasonable amount of epochs (around 10). ```python # Hyperparameters fc1_dims = (784, 400) fc21_dims = (400, 20) fc22_dims = (400, 20) fc3_dims = (20, 400) fc4_dims = (400, 784) lr = 1e-4 batch_size = 120 epochs = 10 ``` ```python # This cell contains a hidden test, please don't delete it, thx ``` Run the box below to train the model using the hyperparameters you entered above. ```python from torchvision import datasets, transforms from torch import nn, optim # Load data train_data = datasets.MNIST('../data', train=True, download=True, transform=transforms.ToTensor()) train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True, **{}) # Init model VAE_MNIST = VAE(fc1_dims=fc1_dims, fc21_dims=fc21_dims, fc22_dims=fc22_dims, fc3_dims=fc3_dims, fc4_dims=fc4_dims) # Init optimizer optimizer = optim.Adam(VAE_MNIST.parameters(), lr=lr) # Train for epoch in range(1, epochs + 1): train(epoch, train_loader, VAE_MNIST, optimizer) ``` Train Epoch: 1 [0/60000 (0%)] Loss: 550.567566 Train Epoch: 1 [12000/60000 (20%)] Loss: 268.343658 Train Epoch: 1 [24000/60000 (40%)] Loss: 235.497818 Train Epoch: 1 [36000/60000 (60%)] Loss: 212.567719 Train Epoch: 1 [48000/60000 (80%)] Loss: 207.858917 ====> Epoch: 1 Average loss: 254.7273 Train Epoch: 2 [0/60000 (0%)] Loss: 192.445572 Train Epoch: 2 [12000/60000 (20%)] Loss: 184.283844 Train Epoch: 2 [24000/60000 (40%)] Loss: 174.772934 Train Epoch: 2 [36000/60000 (60%)] Loss: 176.407883 Train Epoch: 2 [48000/60000 (80%)] Loss: 168.189941 ====> Epoch: 2 Average loss: 174.8130 Train Epoch: 3 [0/60000 (0%)] Loss: 161.005066 Train Epoch: 3 [12000/60000 (20%)] Loss: 158.476639 Train Epoch: 3 [24000/60000 (40%)] Loss: 156.709290 Train Epoch: 3 [36000/60000 (60%)] Loss: 158.456818 Train Epoch: 3 [48000/60000 (80%)] Loss: 151.390640 ====> Epoch: 3 Average loss: 155.7453 Train Epoch: 4 [0/60000 (0%)] Loss: 151.145935 Train Epoch: 4 [12000/60000 (20%)] Loss: 137.667313 Train Epoch: 4 [24000/60000 (40%)] Loss: 143.940842 Train Epoch: 4 [36000/60000 (60%)] Loss: 144.788986 Train Epoch: 4 [48000/60000 (80%)] Loss: 138.139908 ====> Epoch: 4 Average loss: 144.3600 Train Epoch: 5 [0/60000 (0%)] Loss: 140.378143 Train Epoch: 5 [12000/60000 (20%)] Loss: 138.112839 Train Epoch: 5 [24000/60000 (40%)] Loss: 139.341797 Train Epoch: 5 [36000/60000 (60%)] Loss: 140.853287 Train Epoch: 5 [48000/60000 (80%)] Loss: 130.976883 ====> Epoch: 5 Average loss: 136.7890 Train Epoch: 6 [0/60000 (0%)] Loss: 131.719711 Train Epoch: 6 [12000/60000 (20%)] Loss: 132.215408 Train Epoch: 6 [24000/60000 (40%)] Loss: 131.544479 Train Epoch: 6 [36000/60000 (60%)] Loss: 137.173676 Train Epoch: 6 [48000/60000 (80%)] Loss: 134.207764 ====> Epoch: 6 Average loss: 131.5690 Train Epoch: 7 [0/60000 (0%)] Loss: 130.113449 Train Epoch: 7 [12000/60000 (20%)] Loss: 134.579498 Train Epoch: 7 [24000/60000 (40%)] Loss: 127.660347 Train Epoch: 7 [36000/60000 (60%)] Loss: 130.052444 Train Epoch: 7 [48000/60000 (80%)] Loss: 126.369286 ====> Epoch: 7 Average loss: 127.7944 Train Epoch: 8 [0/60000 (0%)] Loss: 127.497429 Train Epoch: 8 [12000/60000 (20%)] Loss: 124.193436 Train Epoch: 8 [24000/60000 (40%)] Loss: 124.477249 Train Epoch: 8 [36000/60000 (60%)] Loss: 126.167824 Train Epoch: 8 [48000/60000 (80%)] Loss: 124.408363 ====> Epoch: 8 Average loss: 124.9271 Train Epoch: 9 [0/60000 (0%)] Loss: 121.864845 Train Epoch: 9 [12000/60000 (20%)] Loss: 120.650017 Train Epoch: 9 [24000/60000 (40%)] Loss: 118.843796 Train Epoch: 9 [36000/60000 (60%)] Loss: 121.871872 Train Epoch: 9 [48000/60000 (80%)] Loss: 121.571045 ====> Epoch: 9 Average loss: 122.5673 Train Epoch: 10 [0/60000 (0%)] Loss: 127.931313 Train Epoch: 10 [12000/60000 (20%)] Loss: 123.621147 Train Epoch: 10 [24000/60000 (40%)] Loss: 119.833107 Train Epoch: 10 [36000/60000 (60%)] Loss: 114.540863 Train Epoch: 10 [48000/60000 (80%)] Loss: 118.989517 ====> Epoch: 10 Average loss: 120.6853 Run the box below to check if the model you trained above is able to correctly reconstruct images. ```python ### Let's check if the reconstructions make sense # Set model to test mode VAE_MNIST.eval() # Reconstructed train_data_plot = datasets.MNIST('../data', train=True, download=True, transform=transforms.ToTensor()) train_loader_plot = torch.utils.data.DataLoader(train_data_plot, batch_size=1, shuffle=False, **{}) for batch_idx, (data, _) in enumerate(train_loader_plot): x_hat, mu, logvar = VAE_MNIST(data) plt.imshow(x_hat.view(1,28,28).squeeze().data.numpy(), cmap='gray') plt.title('%i' % train_data.train_labels[batch_idx]) plt.show() if batch_idx == 3: break ``` ### 2.8 Visualize latent space (20 points) Now, implement the auto-encoder now with a 2-dimensional latent space, and train again over the MNIST data. Make a visualization of the learned manifold by using a linearly spaced coordinate grid as input for the latent space, as seen in https://arxiv.org/abs/1312.6114 Figure 4. ```python fc1_dims = (784, 256) fc21_dims = (256, 2) fc22_dims = (256, 2) fc3_dims = (2, 256) fc4_dims = (256, 784) lr = 1e-4 batch_size = 128 epochs = 10 # Load data train_data = datasets.MNIST('../data', train=True, download=True, transform=transforms.ToTensor()) train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True, **{}) # Init model VAE_MNIST = VAE(fc1_dims=fc1_dims, fc21_dims=fc21_dims, fc22_dims=fc22_dims, fc3_dims=fc3_dims, fc4_dims=fc4_dims) # Init optimizer optimizer = optim.Adam(VAE_MNIST.parameters(), lr=lr) # Train for epoch in range(1, epochs + 1): train(epoch, train_loader, VAE_MNIST, optimizer) ``` Train Epoch: 1 [0/60000 (0%)] Loss: 551.562500 Train Epoch: 1 [12800/60000 (21%)] Loss: 263.747467 Train Epoch: 1 [25600/60000 (43%)] Loss: 238.770248 Train Epoch: 1 [38400/60000 (64%)] Loss: 221.702301 Train Epoch: 1 [51200/60000 (85%)] Loss: 223.060852 ====> Epoch: 1 Average loss: 264.5905 Train Epoch: 2 [0/60000 (0%)] Loss: 208.024170 Train Epoch: 2 [12800/60000 (21%)] Loss: 211.439774 Train Epoch: 2 [25600/60000 (43%)] Loss: 202.066025 Train Epoch: 2 [38400/60000 (64%)] Loss: 198.744766 Train Epoch: 2 [51200/60000 (85%)] Loss: 193.100998 ====> Epoch: 2 Average loss: 199.6053 Train Epoch: 3 [0/60000 (0%)] Loss: 190.765076 Train Epoch: 3 [12800/60000 (21%)] Loss: 192.474442 Train Epoch: 3 [25600/60000 (43%)] Loss: 187.244492 Train Epoch: 3 [38400/60000 (64%)] Loss: 187.458191 Train Epoch: 3 [51200/60000 (85%)] Loss: 190.158081 ====> Epoch: 3 Average loss: 190.6890 Train Epoch: 4 [0/60000 (0%)] Loss: 187.374985 Train Epoch: 4 [12800/60000 (21%)] Loss: 180.420563 Train Epoch: 4 [25600/60000 (43%)] Loss: 188.807617 Train Epoch: 4 [38400/60000 (64%)] Loss: 187.241302 Train Epoch: 4 [51200/60000 (85%)] Loss: 185.843384 ====> Epoch: 4 Average loss: 185.7557 Train Epoch: 5 [0/60000 (0%)] Loss: 178.010010 Train Epoch: 5 [12800/60000 (21%)] Loss: 180.615494 Train Epoch: 5 [25600/60000 (43%)] Loss: 186.501984 Train Epoch: 5 [38400/60000 (64%)] Loss: 182.561722 Train Epoch: 5 [51200/60000 (85%)] Loss: 176.204254 ====> Epoch: 5 Average loss: 182.3810 Train Epoch: 6 [0/60000 (0%)] Loss: 184.070938 Train Epoch: 6 [12800/60000 (21%)] Loss: 186.254715 Train Epoch: 6 [25600/60000 (43%)] Loss: 174.112152 Train Epoch: 6 [38400/60000 (64%)] Loss: 181.852188 Train Epoch: 6 [51200/60000 (85%)] Loss: 178.781525 ====> Epoch: 6 Average loss: 179.9251 Train Epoch: 7 [0/60000 (0%)] Loss: 185.035431 Train Epoch: 7 [12800/60000 (21%)] Loss: 179.148438 Train Epoch: 7 [25600/60000 (43%)] Loss: 170.358719 Train Epoch: 7 [38400/60000 (64%)] Loss: 168.970840 Train Epoch: 7 [51200/60000 (85%)] Loss: 173.702774 ====> Epoch: 7 Average loss: 177.9628 Train Epoch: 8 [0/60000 (0%)] Loss: 171.521820 Train Epoch: 8 [12800/60000 (21%)] Loss: 171.705261 Train Epoch: 8 [25600/60000 (43%)] Loss: 178.153992 Train Epoch: 8 [38400/60000 (64%)] Loss: 172.498566 Train Epoch: 8 [51200/60000 (85%)] Loss: 174.557022 ====> Epoch: 8 Average loss: 176.2270 Train Epoch: 9 [0/60000 (0%)] Loss: 173.551559 Train Epoch: 9 [12800/60000 (21%)] Loss: 172.849670 Train Epoch: 9 [25600/60000 (43%)] Loss: 174.010452 Train Epoch: 9 [38400/60000 (64%)] Loss: 174.835938 Train Epoch: 9 [51200/60000 (85%)] Loss: 183.921448 ====> Epoch: 9 Average loss: 174.4494 Train Epoch: 10 [0/60000 (0%)] Loss: 169.704361 Train Epoch: 10 [12800/60000 (21%)] Loss: 183.385513 Train Epoch: 10 [25600/60000 (43%)] Loss: 163.904984 Train Epoch: 10 [38400/60000 (64%)] Loss: 171.295914 Train Epoch: 10 [51200/60000 (85%)] Loss: 172.903488 ====> Epoch: 10 Average loss: 172.6839 ### 2.8 Amortized inference (10 points) What is amortized inference? Where in the code of Part 2 is it used? What is the benefit of using it?
A constant polynomial is a unit if and only if the constant is a unit.
#' Title #' #' @param x is the dataset vector #' @param mn is the name of the barplot #' @param ... #' #' @return Returns a pareto barplot #' @export #' #' @examples pareto<-function(x,mn="Pareto barplot",...){ # x is a vector x.tab=table(x) xx.tab=sort(x.tab, decreasing=TRUE,index.return=FALSE) cumsum(as.vector(xx.tab))->cs length(x.tab)->lenx bp<-barplot(xx.tab,ylim=c(0,max(cs)),las=2) lb<-seq(0,cs[lenx],l=11) axis(side=4,at=lb,labels=paste(seq(0,100,length=11),"%",sep=""),las=1,line=-1,col="Blue",col.axis="Red") for(i in 1:(lenx-1)){ segments(bp[i],cs[i],bp[i+1],cs[i+1],col=i,lwd=2) } title(main=mn,...) } pareto(c(1,2,3,4,4))
#' Create a "sql src" object #' #' `src_sql()` is the standard constructor for all SQL based srcs. #' #' @keywords internal #' @export #' @param subclass name of subclass. "src_sql" is an abstract base class, so you #' must supply this value. `src_` is automatically prepended to the #' class name #' @param con the connection object #' @param ... fields used by object src_sql <- function(subclass, con, ...) { subclass <- paste0("src_", subclass) structure(list(obj = con, ...), class = c(subclass, "src_sql", "src")) } #' Acquire/release connections from a src object #' #' `con_acquire()` gets a connection from a src object; `con_release()` #' returns a previously acquired connection back to its src object. Intended for #' internal use. #' #' These methods have default implementations for `src_sql` and can be #' overridden for src objects that are not themselves DB connections, but know #' how to get them (e.g. a connection pool). #' #' @keywords internal #' @export #' @param src A src object (most commonly, from `src_sql()`) #' @param con A connection #' @return For `con_acquire()`, a connection object; for `con_release()`, #' nothing. con_acquire <- function(src) { UseMethod("con_acquire", src) } #' @rdname con_acquire #' @export con_release <- function(src, con) { UseMethod("con_release", src) } #' @export con_acquire.src_sql <- function(src) { src$obj } #' @export con_release.src_sql <- function(src, con) { } #' @export same_src.src_sql <- function(x, y) { if (!inherits(y, "src_sql")) return(FALSE) identical(x$obj, y$obj) } #' @export src_tbls.src_sql <- function(x, ...) { con <- con_acquire(x) on.exit(con_release(x, con), add = TRUE) db_list_tables(con) } #' @export format.src_sql <- function(x, ...) { paste0( "src: ", src_desc(x), "\n", wrap("tbls: ", paste0(sort(src_tbls(x)), collapse = ", ")) ) }
[STATEMENT] lemma is_denormal_denormal_of_Float: "is_denormal (denormal_of_Float x::('e, 'f)float)" if "is_denormal_Float TYPE(('e, 'f)float) x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. is_denormal (denormal_of_Float x) [PROOF STEP] using that [PROOF STATE] proof (prove) using this: is_denormal_Float TYPE(('e, 'f) IEEE.float) x goal (1 subgoal): 1. is_denormal (denormal_of_Float x) [PROOF STEP] by (auto simp: is_denormal_def exponent_denormal_of_Float that is_denormal_Float_def emax_eq fraction_denormal_of_Float le_nat_iff bias_def)
#include <OpenCLExecutionPlan.h> #include <IOpenCLChainableExecutionPlan.h> #include <OpenCLContext.h> #include <ConfigurationReader.h> #include <boost/log/trivial.hpp> #if GCC #include <cxxabi.h> #endif using namespace neneta; using namespace neneta::gpu; OpenCLExecutionPlan::OpenCLExecutionPlan(const std::string& id, const conf::ConfigurationReader& confReader, const OpenCLProgram& program) : OpenCLBasicExecutionPlan(id) , m_confReader(confReader) , m_kernelConfiguration(m_confReader) , m_program(program) { } OpenCLExecutionPlan::OpenCLExecutionPlan(const OpenCLExecutionPlan& cp) : OpenCLBasicExecutionPlan(cp.getId()) , m_confReader(cp.m_confReader) , m_kernelConfiguration(m_confReader) , m_program(cp.m_program) , m_fpParamSet(cp.m_fpParamSet) , m_bpParamSet(cp.m_bpParamSet) { } OpenCLExecutionPlan::~OpenCLExecutionPlan() { } void OpenCLExecutionPlan::planFwd(const boost::variant<std::string, OpenCLExecutionPlan>& task) { if(const std::string* pstr = boost::get<std::string>(&task)) { addKernel(m_fpParamSet, *pstr, {0,0}); } else if(const OpenCLExecutionPlan* pplan = boost::get<OpenCLExecutionPlan>(&task)) { addPlan(m_fpParamSet, *pplan); } } void OpenCLExecutionPlan::planBck(const boost::variant<std::string, OpenCLExecutionPlan>& task) { if(const std::string* pstr = boost::get<std::string>(&task)) { addKernel(m_bpParamSet, *pstr, {0,0}); } else if(const OpenCLExecutionPlan* pplan = boost::get<OpenCLExecutionPlan>(&task)) { addPlan(m_bpParamSet, *pplan); } } void OpenCLExecutionPlan::runBckPropagation(const OpenCLContext& context) { m_chainedEvents.clear(); runBckImpl(context, m_chainedEvents); } void OpenCLExecutionPlan::addKernel(PropagationParamSet& pSet, const std::string& kernelName, const OpenCLKernelParameters& params) { try { const conf::KernelParams& kernelParams = m_kernelConfiguration.getParamSet(kernelName); pSet.m_kernels.emplace_back(OpenCLKernel(m_program.getProgram(), kernelName.c_str(), params)); pSet.m_events.emplace_back(); pSet.m_profilingHooks.emplace_back(kernelParams.m_profilingEnabled); } catch(const std::out_of_range& ex) { BOOST_LOG_TRIVIAL(error) << "Kernel \"" << kernelName << "\" not configured."; } } void OpenCLExecutionPlan::addPlan(PropagationParamSet& pSet, const OpenCLExecutionPlan& newPlan) { pSet.m_kernels.emplace_back(&newPlan); pSet.m_events.emplace_back(); pSet.m_profilingHooks.emplace_back(false); } void OpenCLExecutionPlan::addCopyBufferKernel(PropagationParamSet& pSet, const CopyBufferKernel& newCopyBuffer) { pSet.m_kernels.emplace_back(newCopyBuffer); pSet.m_events.emplace_back(); pSet.m_profilingHooks.emplace_back(false); } void OpenCLExecutionPlan::addPlanFwdPropagation(const OpenCLExecutionPlan& newPlan) { m_fpParamSet.m_kernels.emplace_front(&newPlan); m_fpParamSet.m_events.emplace_front(); m_fpParamSet.m_profilingHooks.emplace_front(false); } void OpenCLExecutionPlan::addPlanBckPropagation(const OpenCLExecutionPlan& newPlan) { m_bpParamSet.m_kernels.emplace_front(&newPlan); m_bpParamSet.m_events.emplace_front(); m_bpParamSet.m_profilingHooks.emplace_front(false); } void OpenCLExecutionPlan::runFwdPropagation(const OpenCLContext& context) { m_chainedEvents.clear(); runFwdImpl(context, m_chainedEvents); } void OpenCLExecutionPlan::runFwdImpl(const OpenCLContext& context, std::vector<cl::Event>& chainedEvents) { PropagationParamSet& pSet = m_fpParamSet; if(!m_fpParamSet.m_kernels.empty()) { try { auto end = pSet.m_kernels.end(); auto kerIt = pSet.m_kernels.begin(); auto eveIt = pSet.m_events.begin(); for(kerIt, eveIt; kerIt != end; ++kerIt, ++eveIt) { switch(kerIt->which()) { case KernelTypes::CL_KERNEL: { OpenCLKernel& kernel = boost::get<OpenCLKernel>(*kerIt); BOOST_LOG_TRIVIAL(debug) << "Queue kernel " << kernel.getKernel().getInfo<CL_KERNEL_FUNCTION_NAME>(); context.getCommandQueue().enqueueNDRangeKernel(kernel.getKernel(), cl::NullRange, kernel.getGWS(), kernel.getLWS(), &chainedEvents, &*eveIt); chainedEvents.push_back(*eveIt); break; } case KernelTypes::COPY_BUFFER_KERNEL: { CopyBufferKernel* pplan = boost::get<CopyBufferKernel>(&*kerIt); assert(pplan->m_to.getInfo<CL_MEM_SIZE>() >= pplan->m_bytesNo || "Invalid m_to buffer size"); BOOST_LOG_TRIVIAL(debug) << "Queue copy buffer no. bytes " << pplan->m_bytesNo; context.getCommandQueue().enqueueCopyBuffer(pplan->m_from, pplan->m_to, 0, pplan->m_offset, pplan->m_bytesNo, &chainedEvents, &*eveIt); chainedEvents.push_back(*eveIt); break; } case KernelTypes::EXECUTION_PLAN: { BOOST_LOG_TRIVIAL(debug) << "Jump to another execution plan"; const OpenCLExecutionPlan* pplan = boost::get<const OpenCLExecutionPlan*>(*kerIt); const_cast<OpenCLExecutionPlan*>(pplan)->runFwdImpl(context, chainedEvents); break; } } } } catch(cl::Error& err) { BOOST_LOG_TRIVIAL(error) << "OpenCLExecutionPlan::runImpl() error: " << err.what() << " error no. = " << err.err(); abort(); } } } void OpenCLExecutionPlan::wait() const { cl::WaitForEvents(m_chainedEvents); } void OpenCLExecutionPlan::getFwdOrderedProfilingEvents(std::vector<const cl::Event*>& events, std::vector<std::string>& kernelNames) const { auto end = m_fpParamSet.m_kernels.end(); auto kerIt = m_fpParamSet.m_kernels.begin(); auto eveIt = m_fpParamSet.m_events.begin(); auto proIt = m_fpParamSet.m_profilingHooks.begin(); auto size = m_fpParamSet.m_kernels.size(); auto i = 0; for(i, kerIt, eveIt, proIt; kerIt != end; ++i, ++kerIt, ++eveIt, ++proIt) { switch(kerIt->which()) { case KernelTypes::CL_KERNEL: { if(*proIt || i == 0 || i == (size - 1)) { events.emplace_back(&*eveIt); kernelNames.emplace_back(boost::get<OpenCLKernel>(*kerIt).getKernelName()); } break; } case KernelTypes::COPY_BUFFER_KERNEL: { if(*proIt || i == 0 || i == (size - 1)) { events.emplace_back(&*eveIt); kernelNames.emplace_back("copy_buffer_kernel"); } break; } case KernelTypes::EXECUTION_PLAN: { boost::get<const OpenCLExecutionPlan*>(*kerIt)->getFwdOrderedProfilingEvents(events, kernelNames); break; } } } } void OpenCLExecutionPlan::runBckImpl(const OpenCLContext& context, std::vector<cl::Event>& chainedEvents) { PropagationParamSet& pSet = m_bpParamSet; if(!pSet.m_kernels.empty()) { try { auto end = pSet.m_kernels.end(); auto kerIt = pSet.m_kernels.begin(); auto eveIt = pSet.m_events.begin(); for(kerIt, eveIt; kerIt != end; ++kerIt, ++eveIt) { switch(kerIt->which()) { case KernelTypes::CL_KERNEL: { OpenCLKernel& kernel = boost::get<OpenCLKernel>(*kerIt); BOOST_LOG_TRIVIAL(debug) << "Queue kernel " << kernel.getKernel().getInfo<CL_KERNEL_FUNCTION_NAME>(); context.getCommandQueue().enqueueNDRangeKernel(kernel.getKernel(), cl::NullRange, kernel.getGWS(), kernel.getLWS(), &chainedEvents, &*eveIt); chainedEvents.push_back(*eveIt); break; } case KernelTypes::COPY_BUFFER_KERNEL: { CopyBufferKernel* pplan = boost::get<CopyBufferKernel>(&*kerIt); assert(pplan->m_to.getInfo<CL_MEM_SIZE>() >= pplan->m_bytesNo || "Invalid m_to buffer size"); assert(pplan->m_from.getInfo<CL_MEM_SIZE>() >= pplan->m_bytesNo || "Invalid m_from buffer size"); BOOST_LOG_TRIVIAL(debug) << "Queue copy buffer no. bytes " << pplan->m_bytesNo; context.getCommandQueue().enqueueCopyBuffer(pplan->m_from, pplan->m_to, 0, pplan->m_offset, pplan->m_bytesNo, &chainedEvents, &*eveIt); chainedEvents.push_back(*eveIt); break; } case KernelTypes::EXECUTION_PLAN: { BOOST_LOG_TRIVIAL(debug) << "Jump to another execution plan"; const OpenCLExecutionPlan* pplan = boost::get<const OpenCLExecutionPlan*>(*kerIt); const_cast<OpenCLExecutionPlan*>(pplan)->runBckImpl(context, chainedEvents); break; } } } } catch(cl::Error& err) { BOOST_LOG_TRIVIAL(error) << "OpenCLExecutionPlan::runImpl() error: " << err.what() << " error no. = " << err.err(); abort(); } } } void OpenCLExecutionPlan::getBckOrderedProfilingEvents(std::vector<const cl::Event*>& events, std::vector<std::string>& kernelNames) const { auto end = m_fpParamSet.m_kernels.end(); auto kerIt = m_fpParamSet.m_kernels.begin(); auto eveIt = m_fpParamSet.m_events.begin(); auto proIt = m_fpParamSet.m_profilingHooks.begin(); auto size = m_fpParamSet.m_kernels.size(); auto i = 0; for(i, kerIt, eveIt, proIt; kerIt != end; ++i, ++kerIt, ++eveIt, ++proIt) { switch(kerIt->which()) { case KernelTypes::CL_KERNEL: { if(*proIt || i == 0 || i == (size - 1)) { events.emplace_back(&*eveIt); kernelNames.emplace_back(boost::get<OpenCLKernel>(*kerIt).getKernelName()); } break; } case KernelTypes::COPY_BUFFER_KERNEL: { if(*proIt || i == 0 || i == (size - 1)) { events.emplace_back(&*eveIt); kernelNames.emplace_back("copy_buffer_kernel"); } break; } case KernelTypes::EXECUTION_PLAN: { boost::get<const OpenCLExecutionPlan*>(*kerIt)->getBckOrderedProfilingEvents(events, kernelNames); break; } } } } const conf::KernelConfiguration &OpenCLExecutionPlan::getKernelConfiguration() const { return m_kernelConfiguration; } void OpenCLExecutionPlan::writeToBuffer(const cl::CommandQueue& queue, const cl::Buffer& buffer, size_t size, void* ptr) { queue.enqueueWriteBuffer(buffer, CL_TRUE, 0, size, ptr); } void OpenCLExecutionPlan::writeToBuffer(const cl::CommandQueue& queue, const cl::Buffer& buffer, size_t offset, size_t size, void* ptr) { queue.enqueueWriteBuffer(buffer, CL_TRUE, offset, size, ptr); } void OpenCLExecutionPlan::planCopyBufferFwd(const cl::Buffer& from, const cl::Buffer& to, size_t bytesNo) { //add last kernel event from the plan addCopyBufferKernel(m_fpParamSet, {from, to, 0, bytesNo}); } void OpenCLExecutionPlan::planCopyBufferFwd(const cl::Buffer& from, const cl::Buffer& to, size_t offset, size_t bytesNo) { //add last kernel event from the plan addCopyBufferKernel(m_fpParamSet, {from, to, offset, bytesNo}); } void OpenCLExecutionPlan::planCopyBufferBck(const cl::Buffer& from, const cl::Buffer& to, size_t bytesNo) { //add last kernel event from the plan addCopyBufferKernel(m_bpParamSet, {from, to, 0, bytesNo}); } void OpenCLExecutionPlan::planCopyBufferBck(const cl::Buffer& from, const cl::Buffer& to, size_t offset, size_t bytesNo) { //add last kernel event from the plan addCopyBufferKernel(m_bpParamSet, {from, to, offset, bytesNo}); } void OpenCLExecutionPlan::readFromBuffer(const cl::CommandQueue& queue, const cl::Buffer& buffer, size_t size, void* ptr) const { queue.enqueueReadBuffer(buffer, CL_TRUE, 0, size, ptr); } OpenCLExecutionPlan& OpenCLExecutionPlan::operator<<(OpenCLExecutionPlan& right) { IOpenCLChainableExecutionPlan* ptrRight; IOpenCLChainableExecutionPlan* ptrLeft; if((ptrRight = dynamic_cast<IOpenCLChainableExecutionPlan*>(&right)) && (ptrLeft = dynamic_cast<IOpenCLChainableExecutionPlan*>(this))) { ptrLeft->setBkpInput(ptrRight->getBkpOutput()); } addPlanBckPropagation(right); return right; } OpenCLExecutionPlan& OpenCLExecutionPlan::operator>>(OpenCLExecutionPlan& right) { IOpenCLChainableExecutionPlan* ptrRight; IOpenCLChainableExecutionPlan* ptrLeft; if((ptrRight = dynamic_cast<IOpenCLChainableExecutionPlan*>(&right)) && (ptrLeft = dynamic_cast<IOpenCLChainableExecutionPlan*>(this))) { ptrRight->setInput(ptrLeft->getOutput()); } right.addPlanFwdPropagation(*this); return right; } void OpenCLExecutionPlan::printFwdProfilingInfo() const { wait(); if(m_confReader.getBooleanParameter("configuration.gpu.profiling")) { try { std::vector<const cl::Event*> orderedEvents; std::vector<std::string> kernelNames; getFwdOrderedProfilingEvents(orderedEvents, kernelNames); size_t size = orderedEvents.size(); cl_ulong queued, submit, start, end; cl_ulong overallQueued, overallEnd; BOOST_LOG_TRIVIAL(debug) << "Execution Plan profiling information:"; for(size_t i = 0; i < size; ++i) { BOOST_LOG_TRIVIAL(debug) << "\t\tKernel " << kernelNames[i] << " profiling information:"; orderedEvents[i]->getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_QUEUED, &queued); BOOST_LOG_TRIVIAL(debug) << "\t\t\t\tenqueued to command queue at (OpenCL device time) " << queued * 1e-6 << "ms"; orderedEvents[i]->getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_SUBMIT, &submit); BOOST_LOG_TRIVIAL(debug) << "\t\t\t\tsubmition to the device took " << (submit - queued) * 1e-6 << "ms"; orderedEvents[i]->getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_START, &start); BOOST_LOG_TRIVIAL(debug) << "\t\t\t\tto start execution took " << (start - submit) * 1e-6 << "ms"; orderedEvents[i]->getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_END, &end); BOOST_LOG_TRIVIAL(debug) << "\t\t\t\texecution took " << (end - start) * 1e-6 << "ms"; BOOST_LOG_TRIVIAL(debug) << "\t\tKernel execution took " << (end - queued) * 1e-6 << "ms."; if(i==0) { overallQueued = queued; } else if(i==size-1) { overallEnd = end; } } BOOST_LOG_TRIVIAL(debug) << "Execution Plan took " << (overallEnd - overallQueued) * 1e-6 << "ms."; } catch(cl::Error& err) { BOOST_LOG_TRIVIAL(error) << "Exception printProfilingInfo error " << err.what() << " no: " << err.err(); } } else { BOOST_LOG_TRIVIAL(info) << "No profiling information available!"; } } void OpenCLExecutionPlan::printBckProfilingInfo() const { wait(); if(m_confReader.getBooleanParameter("configuration.gpu.profiling")) { try { std::vector<const cl::Event*> orderedEvents; std::vector<std::string> kernelNames; getBckOrderedProfilingEvents(orderedEvents, kernelNames); size_t size = orderedEvents.size(); cl_ulong queued, submit, start, end; cl_ulong overallQueued, overallEnd; BOOST_LOG_TRIVIAL(debug) << "Execution Plan profiling information:"; for(size_t i = 0; i < size; ++i) { BOOST_LOG_TRIVIAL(debug) << "\t\tKernel " << kernelNames[i] << " profiling information:"; orderedEvents[i]->getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_QUEUED, &queued); BOOST_LOG_TRIVIAL(debug) << "\t\t\t\tenqueued to command queue at (OpenCL device time) " << queued * 1e-6 << "ms"; orderedEvents[i]->getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_SUBMIT, &submit); BOOST_LOG_TRIVIAL(debug) << "\t\t\t\tsubmition to the device took " << (submit - queued) * 1e-6 << "ms"; orderedEvents[i]->getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_START, &start); BOOST_LOG_TRIVIAL(debug) << "\t\t\t\tto start execution took " << (start - submit) * 1e-6 << "ms"; orderedEvents[i]->getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_END, &end); BOOST_LOG_TRIVIAL(debug) << "\t\t\t\texecution took " << (end - start) * 1e-6 << "ms"; BOOST_LOG_TRIVIAL(debug) << "\t\tKernel execution took " << (end - queued) * 1e-6 << "ms."; if(i==0) { overallQueued = queued; } else if(i==size-1) { overallEnd = end; } } BOOST_LOG_TRIVIAL(debug) << "Execution Plan took " << (overallEnd - overallQueued) * 1e-6 << "ms."; } catch(cl::Error& err) { BOOST_LOG_TRIVIAL(error) << "Exception printProfilingInfo error " << err.what() << " no: " << err.err(); } } else { BOOST_LOG_TRIVIAL(info) << "No profiling information available!"; } }
Require Export patterns. Require Export proof. Require Export himp_steps. (* Environment or record entry, taking a string and kitem*) Notation "x 's|->' y" := (mapItem (kra (KId x) kdot) (kra (y : kitem) kdot)) (at level 50, no associativity) : Map. (* Heap entry, from an integer key and kitem value *) Notation "x 'h|->' y" := (mapItem (kra (KInt x) kdot) (kra (y : kitem) kdot)) (at level 50, no associativity) : Map. Notation "x 'h|->' y" := (itemP (kra (KInt x) kdot) (kra (y : kitem) kdot)) (at level 50, no associativity) : MapPattern. (* Notations to help unify typed and untyped maps *) Notation load_field v f := (EProject (ELoad (EVar v)) f). (* Notation funEntry name args body := (name%string s|-> FunDef name args body). *) Definition name (d : Defn) : string := match d with | FunDef n _ _ => n end. Definition fundefs (deps : list Defn) (d : Map k k) : Map k k := fold_right (fun def m => (name def s|-> KDefn def) :* m) d deps. Definition value_heap ret krest store stack frame funs mark : kcfg -> Prop := fun c' => match c' with | KCfg k' store' stack' heap' funs' mark' => exists r', k' = kra r' krest /\ store' ~= store /\ stack' = stack /\ heap' |= ret r' :* litP frame /\ funs' ~= funs /\ (mark' >= mark)%Z end. Definition heap_fun (R : Spec kcfg) (deps : list Defn) (d:Defn) : forall (args : list KResult) (init_heap : MapPattern k k) (ret : Z -> MapPattern k k), Prop := match d with FunDef name formals body => fun args init_heap ret => forall krest store stack heap funs mark otherfuns, funs ~= fundefs deps (name s|-> KDefn d) :* otherfuns -> (mark > 0)%Z -> forall frame, heap |= (init_heap :* litP frame) -> R (KCfg (kra (ECall name (map KResultToExp args)) krest) store stack heap funs mark) (value_heap (fun r => existsP v, constraint (r = KInt v) :* ret v)%pattern krest store stack frame funs mark) end. Definition heap_gen_fun (R : Spec kcfg) (d:Defn) : forall (args : list KResult) (init_heap : MapPattern k k) (ret : kitem -> MapPattern k k), Prop := match d with FunDef name formals body => fun args init_heap ret => forall krest store stack heap funs mark otherfuns, funs ~= name s|-> KDefn d :* otherfuns -> (mark > 0)%Z -> forall frame, heap |= (init_heap :* litP frame) -> R (KCfg (kra (ECall name (map KResultToExp args)) krest) store stack heap funs mark) (value_heap ret krest store stack frame funs mark) end. Definition void_heap ret krest store stack frame funs mark : kcfg -> Prop := fun c' => match c' with | KCfg k' store' stack' heap' funs' mark' => k' = krest /\ store' ~= store /\ stack' = stack /\ heap' |= ret :* litP frame /\ funs' ~= funs /\ (mark' >= mark)%Z end. Definition heap_void_fun (R : Spec kcfg) (deps : list Defn) (d:Defn) : forall (args : list KResult) (init_heap ret : MapPattern k k), Prop := match d with FunDef name formals body => fun args init_heap ret => forall krest store stack heap funs mark otherfuns, funs ~= fundefs deps (name s|-> KDefn d) :* otherfuns -> (mark > 0)%Z -> forall frame, heap |= (init_heap :* litP frame) -> R (KCfg (kra (SCall name (map KResultToExp args)) krest) store stack heap funs mark) (void_heap ret krest store stack frame funs mark) end. Definition return_heap ret stack frame funs mark : kcfg -> Prop := fun c' => match c' with | KCfg k' store' stack' heap' funs' mark' => exists r' krest, k' = kra (KStmt (SReturn r')) krest /\ stack' = stack /\ heap' |= ret r' :* litP frame /\ funs' ~= funs /\ (mark' >= mark)%Z end. Definition suffix_claim (R : Spec kcfg) (body : k) (init_store : Map k k) (init_heap : MapPattern k k) (final_heap : Z -> MapPattern k k) : Prop := forall stack store store_rest heap frame funs mark, store ~= init_store :* store_rest -> heap |= (init_heap :* litP frame) -> (mark > 0)%Z -> R (KCfg body store stack heap funs mark) (return_heap (fun r => existsP v, constraint (r = ECon v) :* final_heap v)%pattern stack frame funs mark). Definition return_void_heap ret stack frame funs mark : kcfg -> Prop := fun c' => match c' with | KCfg k' store' stack' heap' funs' mark' => exists krest, k' = kra (KStmt SReturnVoid) krest /\ stack' = stack /\ heap' |= ret :* litP frame /\ funs' ~= funs /\ (mark' >= mark)%Z end. Definition suffix_void_claim (R : Spec kcfg) (deps : list Defn) (body : k) (init_store : Map k k) (init_heap final_heap : MapPattern k k) : Prop := forall stack store store_rest heap frame funs otherfuns mark, funs ~= fundefs deps otherfuns -> store ~= init_store :* store_rest -> heap |= (init_heap :* litP frame) -> (mark > 0)%Z -> R (KCfg body store stack heap funs mark) (return_void_heap final_heap stack frame funs mark). Fixpoint loop_tails (s : Stmt) (rest : k) : list k := match s with | Seq s1 s2 => loop_tails s1 (kra s2 rest) ++ loop_tails s2 rest | SIf _ s1 s2 => loop_tails s1 rest ++ loop_tails s2 rest | SWhile _ s' => (kra s rest) :: loop_tails s' (kra s rest) | _ => nil end. Definition body (def : Defn) := match def with FunDef _ _ body => body end. Definition heap_loop (R : Spec kcfg) (def : Defn) (n : nat) : Map k k -> MapPattern k k -> (Z -> MapPattern k k) -> Prop := suffix_claim R (nth n (loop_tails (body def) kdot) kdot). Definition heap_void_loop (R : Spec kcfg) (deps : list Defn) (def : Defn) (n : nat) : Map k k -> MapPattern k k -> MapPattern k k -> Prop := suffix_void_claim R deps (nth n (loop_tails (body def) kdot) kdot).
I was all excited that I had an S storytime in my files, but as I looked it over, I found that it was very specific to February, with snowflakes and groundhogs’ shadows. Well, shucks. I’ll give you some favorites, and as always, I welcome your storytime suggestions. You forgot my favorite part of the "Shake Your Sillies" song: "jump my jiggles out," especially when used in a baby and toddler storytime group, most of whom have not yet mastered the gross motor skills required to jump. HI-larious. I have one for S. Do you know Skinnamarink? My Kinders loved it, and it was a great hit when performed for parents. Sung nice and slowly with actions, especially pointing to mum or dad.
[STATEMENT] lemma widen1_is_type: assumes wfP: "wf_prog wfmd P" shows "(A, B) \<in> widen1 P \<Longrightarrow> is_type P B" [PROOF STATE] proof (prove) goal (1 subgoal): 1. P \<turnstile> A <\<^sup>1 B \<Longrightarrow> is_type P B [PROOF STEP] proof(induct rule: widen1.induct) [PROOF STATE] proof (state) goal (6 subgoals): 1. is_type P (Class Object) 2. is_type P (Class Object) 3. is_type P (Class Object) 4. is_type P (Class Object) 5. \<And>C D. P \<turnstile> C \<prec>\<^sup>1 D \<Longrightarrow> is_type P (Class D) 6. \<And>T U. \<lbrakk>P \<turnstile> T <\<^sup>1 U; is_type P U; ground_type T \<noteq> NT\<rbrakk> \<Longrightarrow> is_type P (U\<lfloor>\<rceil>) [PROOF STEP] case (widen1_Class C D) [PROOF STATE] proof (state) this: P \<turnstile> C \<prec>\<^sup>1 D goal (6 subgoals): 1. is_type P (Class Object) 2. is_type P (Class Object) 3. is_type P (Class Object) 4. is_type P (Class Object) 5. \<And>C D. P \<turnstile> C \<prec>\<^sup>1 D \<Longrightarrow> is_type P (Class D) 6. \<And>T U. \<lbrakk>P \<turnstile> T <\<^sup>1 U; is_type P U; ground_type T \<noteq> NT\<rbrakk> \<Longrightarrow> is_type P (U\<lfloor>\<rceil>) [PROOF STEP] hence "is_class P C" "is_class P D" [PROOF STATE] proof (prove) using this: P \<turnstile> C \<prec>\<^sup>1 D goal (1 subgoal): 1. is_class P C &&& is_class P D [PROOF STEP] by(auto intro: subcls_is_class converse_subcls_is_class[OF wfP]) [PROOF STATE] proof (state) this: is_class P C is_class P D goal (6 subgoals): 1. is_type P (Class Object) 2. is_type P (Class Object) 3. is_type P (Class Object) 4. is_type P (Class Object) 5. \<And>C D. P \<turnstile> C \<prec>\<^sup>1 D \<Longrightarrow> is_type P (Class D) 6. \<And>T U. \<lbrakk>P \<turnstile> T <\<^sup>1 U; is_type P U; ground_type T \<noteq> NT\<rbrakk> \<Longrightarrow> is_type P (U\<lfloor>\<rceil>) [PROOF STEP] thus ?case [PROOF STATE] proof (prove) using this: is_class P C is_class P D goal (1 subgoal): 1. is_type P (Class D) [PROOF STEP] by simp [PROOF STATE] proof (state) this: is_type P (Class D) goal (5 subgoals): 1. is_type P (Class Object) 2. is_type P (Class Object) 3. is_type P (Class Object) 4. is_type P (Class Object) 5. \<And>T U. \<lbrakk>P \<turnstile> T <\<^sup>1 U; is_type P U; ground_type T \<noteq> NT\<rbrakk> \<Longrightarrow> is_type P (U\<lfloor>\<rceil>) [PROOF STEP] next [PROOF STATE] proof (state) goal (5 subgoals): 1. is_type P (Class Object) 2. is_type P (Class Object) 3. is_type P (Class Object) 4. is_type P (Class Object) 5. \<And>T U. \<lbrakk>P \<turnstile> T <\<^sup>1 U; is_type P U; ground_type T \<noteq> NT\<rbrakk> \<Longrightarrow> is_type P (U\<lfloor>\<rceil>) [PROOF STEP] case (widen1_Array_Array T U) [PROOF STATE] proof (state) this: P \<turnstile> T <\<^sup>1 U is_type P U ground_type T \<noteq> NT goal (5 subgoals): 1. is_type P (Class Object) 2. is_type P (Class Object) 3. is_type P (Class Object) 4. is_type P (Class Object) 5. \<And>T U. \<lbrakk>P \<turnstile> T <\<^sup>1 U; is_type P U; ground_type T \<noteq> NT\<rbrakk> \<Longrightarrow> is_type P (U\<lfloor>\<rceil>) [PROOF STEP] thus ?case [PROOF STATE] proof (prove) using this: P \<turnstile> T <\<^sup>1 U is_type P U ground_type T \<noteq> NT goal (1 subgoal): 1. is_type P (U\<lfloor>\<rceil>) [PROOF STEP] by(cases U)(auto elim: widen1.cases) [PROOF STATE] proof (state) this: is_type P (U\<lfloor>\<rceil>) goal (4 subgoals): 1. is_type P (Class Object) 2. is_type P (Class Object) 3. is_type P (Class Object) 4. is_type P (Class Object) [PROOF STEP] qed(insert wfP, auto)
[STATEMENT] theorem (in Group) Group_Qg:"G \<triangleright> N \<Longrightarrow> Group (Qg G N)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. G \<triangleright> N \<Longrightarrow> Group (G / N) [PROOF STEP] apply (frule Qg_top [of "N"], frule Qg_iop [of "N"], frule Qg_unit[of "N"], frule Qg_i[of "N" ], frule Qg_tassoc[of "N"], frule Qg_unit_closed[of "N" ]) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>G \<triangleright> N; c_top G N \<in> set_rcs G N \<rightarrow> set_rcs G N \<rightarrow> set_rcs G N; c_iop G N \<in> set_rcs G N \<rightarrow> set_rcs G N; \<forall>x\<in>set_rcs G N. c_top G N N x = x; \<forall>x\<in>set_rcs G N. c_top G N (c_iop G N x) x = N; \<forall>X\<in>set_rcs G N. \<forall>Y\<in>set_rcs G N. \<forall>Z\<in>set_rcs G N. c_top G N X (c_top G N Y Z) = c_top G N (c_top G N X Y) Z; N \<in> set_rcs G N\<rbrakk> \<Longrightarrow> Group (G / N) [PROOF STEP] apply (simp add:Qg_def Group_def) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
function [n,msg1,msg2] = firchk(n,Fend,a,exception) %FIRCHK Check if specified filter order is valid. % FIRCHK(N,Fend,A) checks if the specified order N is valid given the % final frequency point Fend and the desired magnitude response vector A. % Type 2 linear phase FIR filters (symmetric, odd order) must have a % desired magnitude response vector that ends in zero if Fend = 1. This % is because type 2 filters necessarily have a zero at w = pi. % % If the order is not valid, a warning is given and the order % of the filter is incremented by one. % % If A is a scalar (as when called from fircls1), A = 0 is % interpreted as lowpass and A = 1 is interpreted as highpass. % % FIRCHK(N,Fend,A,EXCEPTION) will not warn or increase the order % if EXCEPTION = 1. Examples of EXCEPTIONS are type 4 filters % (such as differentiators or hilbert transformers) or non-linear % phase filters (such as minimum and maximum phase filters). % Author : R. Losada % Copyright 1988-2004 The MathWorks, Inc. % $Revision: 1.7.4.5 $ $Date: 2007/12/14 15:15:06 $ matlab_v = version('-release'); matlab_v = str2double(matlab_v(1:4)); if matlab_v > 2012 narginchk(3,4) else error(nargchk(3,4,nargin,'struct')) end if nargin == 3, exception = false; end msg1 = ''; msg2 = ''; oddord = false; % Flag, initially we assume even order if isempty(n) || length(n) > 1 || ~isnumeric(n) || ~isreal(n) || n~=round(n) || n<=0, msg1 = 'Filter order must be a real, positive integer.'; return end if rem(n,2) == 1, oddord = true; % Overwrite flag end if (a(end) ~= 0) && Fend == 1 && oddord && ~exception, str = ['Odd order symmetric FIR filters must have a gain of zero \n'... 'at the Nyquist frequency. The order is being increased by one.']; msg2 = sprintf(str); n = n+1; end
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.order import Mathlib.order.lattice import Mathlib.PostPort universes u v namespace Mathlib /-! # `max` and `min` This file proves basic properties about maxima and minima on a `linear_order`. ## Tags min, max -/ -- translate from lattices to linear orders (sup → max, inf → min) @[simp] theorem le_min_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : c ≤ min a b ↔ c ≤ a ∧ c ≤ b := le_inf_iff @[simp] theorem max_le_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : max a b ≤ c ↔ a ≤ c ∧ b ≤ c := sup_le_iff theorem max_le_max {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α} : a ≤ c → b ≤ d → max a b ≤ max c d := sup_le_sup theorem min_le_min {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α} : a ≤ c → b ≤ d → min a b ≤ min c d := inf_le_inf theorem le_max_left_of_le {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : a ≤ b → a ≤ max b c := le_sup_left_of_le theorem le_max_right_of_le {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : a ≤ c → a ≤ max b c := le_sup_right_of_le theorem min_le_left_of_le {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : a ≤ c → min a b ≤ c := inf_le_left_of_le theorem min_le_right_of_le {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : b ≤ c → min a b ≤ c := inf_le_right_of_le theorem max_min_distrib_left {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : max a (min b c) = min (max a b) (max a c) := sup_inf_left theorem max_min_distrib_right {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : max (min a b) c = min (max a c) (max b c) := sup_inf_right theorem min_max_distrib_left {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : min a (max b c) = max (min a b) (min a c) := inf_sup_left theorem min_max_distrib_right {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : min (max a b) c = max (min a c) (min b c) := inf_sup_right theorem min_le_max {α : Type u} [linear_order α] {a : α} {b : α} : min a b ≤ max a b := le_trans (min_le_left a b) (le_max_left a b) @[simp] theorem min_eq_left_iff {α : Type u} [linear_order α] {a : α} {b : α} : min a b = a ↔ a ≤ b := inf_eq_left @[simp] theorem min_eq_right_iff {α : Type u} [linear_order α] {a : α} {b : α} : min a b = b ↔ b ≤ a := inf_eq_right @[simp] theorem max_eq_left_iff {α : Type u} [linear_order α] {a : α} {b : α} : max a b = a ↔ b ≤ a := sup_eq_left @[simp] theorem max_eq_right_iff {α : Type u} [linear_order α] {a : α} {b : α} : max a b = b ↔ a ≤ b := sup_eq_right /-- An instance asserting that `max a a = a` -/ protected instance max_idem {α : Type u} [linear_order α] : is_idempotent α max := Mathlib.sup_is_idempotent /-- An instance asserting that `min a a = a` -/ protected instance min_idem {α : Type u} [linear_order α] : is_idempotent α min := Mathlib.inf_is_idempotent @[simp] theorem max_lt_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : max a b < c ↔ a < c ∧ b < c := sup_lt_iff @[simp] theorem lt_min_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : a < min b c ↔ a < b ∧ a < c := lt_inf_iff @[simp] theorem lt_max_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : a < max b c ↔ a < b ∨ a < c := lt_sup_iff @[simp] theorem min_lt_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : min a b < c ↔ a < c ∨ b < c := lt_max_iff @[simp] theorem min_le_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : min a b ≤ c ↔ a ≤ c ∨ b ≤ c := inf_le_iff @[simp] theorem le_max_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : a ≤ max b c ↔ a ≤ b ∨ a ≤ c := min_le_iff theorem max_lt_max {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α} (h₁ : a < c) (h₂ : b < d) : max a b < max c d := sorry theorem min_lt_min {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α} (h₁ : a < c) (h₂ : b < d) : min a b < min c d := max_lt_max h₁ h₂ theorem min_right_comm {α : Type u} [linear_order α] (a : α) (b : α) (c : α) : min (min a b) c = min (min a c) b := right_comm min min_comm min_assoc a b c theorem max.left_comm {α : Type u} [linear_order α] (a : α) (b : α) (c : α) : max a (max b c) = max b (max a c) := left_comm max max_comm max_assoc a b c theorem max.right_comm {α : Type u} [linear_order α] (a : α) (b : α) (c : α) : max (max a b) c = max (max a c) b := right_comm max max_comm max_assoc a b c theorem monotone.map_max {α : Type u} {β : Type v} [linear_order α] [linear_order β] {f : α → β} {a : α} {b : α} (hf : monotone f) : f (max a b) = max (f a) (f b) := sorry theorem monotone.map_min {α : Type u} {β : Type v} [linear_order α] [linear_order β] {f : α → β} {a : α} {b : α} (hf : monotone f) : f (min a b) = min (f a) (f b) := monotone.map_max (monotone.order_dual hf) theorem min_choice {α : Type u} [linear_order α] (a : α) (b : α) : min a b = a ∨ min a b = b := sorry theorem max_choice {α : Type u} [linear_order α] (a : α) (b : α) : max a b = a ∨ max a b = b := min_choice a b theorem le_of_max_le_left {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h : max a b ≤ c) : a ≤ c := le_trans (le_max_left a b) h theorem le_of_max_le_right {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h : max a b ≤ c) : b ≤ c := le_trans (le_max_right a b) h
\documentclass[12pt]{article} %% Vector based fonts instead of bitmaps \usepackage{lmodern} %% Useful %\usepackage{fullpage} % Smaller margins \usepackage{enumerate} %% Theorem \usepackage{amsthm} %% More math \usepackage{amsmath} \usepackage{amssymb} %% Diagrams \usepackage{tikz} %% Document Header \title{Glider on Frictionless Air Track Lab Report} \author{AP Physics B Block | Lab \#2\\Ryan McCrystal} \date{\today} \begin{document} \maketitle \newpage \begin{abstract} %% Include purpose, approach, and assumptions. \end{abstract} \section{Methodology} %% Include a detailed description of the procedures and relevant diagram(s) of the physical layout. Specify measurement apparatus and equipment used. \newpage \section{Calculations} %% Include a detailed presentation of the data, calculations, and other relevant diagrams. \newpage \section{Results and Conclusions} %% Were the results what you expected? Why or why not? Make sure to indicate any significant sources of error, or how you would conduct the experiment next time to improve the accuracy of your results. How did the assumptions and methodology change as the analysis progressed. \newpage \end{document}
abstract Animal speak(a::Animal) = "$(a.name) says $(sound(a))" type Horse <: Animal name end sound(h::Horse) = "neigh" type Cow <: Animal name end sound(c::Cow) = "moooo" type Sheep <: Animal name end sound(s::Sheep) = "baaaa" s = Horse("CJ") @assert speak(s) == "CJ says neigh" c = Cow("Bessie") @assert speak(c) == "Bessie says moooo" @assert speak(Sheep("Little Lamb")) == "Little Lamb says baaaa"
#! /usr/bin/Rscript args <- commandArgs(trailingOnly = TRUE) headersTXT = c( "Miranda_score", "miR_ID", "mRNA_ID", "Start_position", "End_position", "Seed_match_6mer2", "miR_match_P01", "Seed_match_7mer2", "Seed_match_7mer1", "Seed_MFE", "X3p_MFE", "Target_UC_comp", "miR_match_P09", "miR_match_P02", "Seed_GU", "miR_match_P07", "miR_match_P19", "miR_match_P15" ) read.table(args[1],sep="\t", header=TRUE) -> features features = subset(features, select = headersTXT) #library(seqinr) #read.fasta(file=args[2], as.string=TRUE) -> fa #fa=fa[which(!duplicated(names(fa)))] #utr_length = t(sapply(names(fa), function(i) { # c(i, nchar(fa[[i]][1])) #})) #remove records with UTRs not in fasta file #features = subset(features, mRNA_ID %in% names(fa)) attach(features) features_numeric = subset(features, select = -c(miR_ID,mRNA_ID)) aggregate(features_numeric, by=list(miR_ID,mRNA_ID), sum) -> features_sum aggregate(1:dim(features_numeric)[1], by=list(miR_ID,mRNA_ID), length) -> number_sites colnames(number_sites)[3] <- "number_sites" aggregate(features_numeric, by=list(miR_ID,mRNA_ID), mean) -> features_mean aggregate(features_numeric, by=list(miR_ID,mRNA_ID), max) -> features_max aggregate(features_numeric, by=list(miR_ID,mRNA_ID), min) -> features_min detach(features) features_sum2 = features_sum features_mean2 = features_mean features_max2 = features_max features_min2 = features_min colnames(features_sum2) <- paste0(colnames(features_sum2), ".sum") colnames(features_mean2) <- paste0(colnames(features_mean2), ".mean") colnames(features_max2) <- paste0(colnames(features_max2), ".max") colnames(features_min2) <- paste0(colnames(features_min2), ".min") output = merge(number_sites, features_sum2, by=c(1,2)) output = merge(output, features_mean2, by=c(1,2)) output = merge(output, features_max2, by=c(1,2)) output = merge(output, features_min2, by=c(1,2)) selected_features = c("Group.1", "Group.2", "Miranda_score.max", "Seed_match_6mer2.mean", "miR_match_P01.min", "Seed_match_7mer2.max", "Seed_match_7mer1.mean", "Seed_MFE.min", "X3p_MFE.mean", "Target_UC_comp.mean", "miR_match_P09.mean", "miR_match_P02.min", "Seed_GU.mean", "miR_match_P07.mean", "Start_position.min", "miR_match_P19.min", "miR_match_P15.min" ) output2 <- output[,selected_features] write.table(output2, file=paste0(args[2], ".csv"), sep=",", row.names=FALSE)
library(tidyr) df=spread(df,platform,count) periscope.table(df)
import Data.List.Views palindrome : Eq a => List a -> Bool palindrome xs with (vList xs) palindrome [] | VNil = True palindrome [x] | VOne = True palindrome (x :: (ys ++ [y])) | (VCons rec) = if x == y then palindrome ys | rec else False
I get the point; this is an M-rated Kinect game. Can you please stop throwing blood all over me, Sega? Oh god, it's in my mouth. Sega's Rise of Nightmares is the gamer that finally realizes the joy of air-chainsawing the undead into tiny little pieces, even if it still has a way to go towards capturing the joy of simple movement and navigation. Frankly I feel Sega is trying too hard. All we really need is a guy standing still in a dark room while hordes of bizarre creatures charging us and tons of dismemberment-friendly devices within arm's reach. Don't sweat the moving about. All I crave are clockwork zombies, undead maids, and a scythe to disembowel them by.
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Scott Morrison ! This file was ported from Lean 3 source module data.finsupp.basic ! leanprover-community/mathlib commit f7fc89d5d5ff1db2d1242c7bb0e9062ce47ef47c ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Algebra.BigOperators.Finsupp import Mathlib.Algebra.Hom.GroupAction import Mathlib.Algebra.Regular.SMul import Mathlib.Data.Finset.Preimage import Mathlib.Data.Rat.BigOperators /-! # Miscellaneous definitions, lemmas, and constructions using finsupp ## Main declarations * `Finsupp.graph`: the finset of input and output pairs with non-zero outputs. * `Finsupp.mapRange.equiv`: `Finsupp.mapRange` as an equiv. * `Finsupp.mapDomain`: maps the domain of a `Finsupp` by a function and by summing. * `Finsupp.comapDomain`: postcomposition of a `Finsupp` with a function injective on the preimage of its support. * `Finsupp.some`: restrict a finitely supported function on `option α` to a finitely supported function on `α`. * `Finsupp.filter`: `filter p f` is the finitely supported function that is `f a` if `p a` is true and 0 otherwise. * `Finsupp.frange`: the image of a finitely supported function on its support. * `Finsupp.subtype_domain`: the restriction of a finitely supported function `f` to a subtype. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## TODO * This file is currently ~1600 lines long and is quite a miscellany of definitions and lemmas, so it should be divided into smaller pieces. * Expand the list of definitions and important lemmas to the module docstring. -/ noncomputable section open Finset Function open BigOperators variable {α β γ ι M M' N P G H R S : Type _} namespace Finsupp /-! ### Declarations about `graph` -/ section Graph variable [Zero M] /-- The graph of a finitely supported function over its support, i.e. the finset of input and output pairs with non-zero outputs. -/ def graph (f : α →₀ M) : Finset (α × M) := f.support.map ⟨fun a => Prod.mk a (f a), fun _ _ h => (Prod.mk.inj h).1⟩ #align finsupp.graph Finsupp.graph theorem mk_mem_graph_iff {a : α} {m : M} {f : α →₀ M} : (a, m) ∈ f.graph ↔ f a = m ∧ m ≠ 0 := by simp_rw [graph, mem_map, mem_support_iff] constructor · rintro ⟨b, ha, rfl, -⟩ exact ⟨rfl, ha⟩ · rintro ⟨rfl, ha⟩ exact ⟨a, ha, rfl⟩ #align finsupp.mk_mem_graph_iff Finsupp.mk_mem_graph_iff @[simp] theorem mem_graph_iff {c : α × M} {f : α →₀ M} : c ∈ f.graph ↔ f c.1 = c.2 ∧ c.2 ≠ 0 := by cases c exact mk_mem_graph_iff #align finsupp.mem_graph_iff Finsupp.mem_graph_iff theorem mk_mem_graph (f : α →₀ M) {a : α} (ha : a ∈ f.support) : (a, f a) ∈ f.graph := mk_mem_graph_iff.2 ⟨rfl, mem_support_iff.1 ha⟩ #align finsupp.mk_mem_graph Finsupp.mk_mem_graph theorem apply_eq_of_mem_graph {a : α} {m : M} {f : α →₀ M} (h : (a, m) ∈ f.graph) : f a = m := (mem_graph_iff.1 h).1 #align finsupp.apply_eq_of_mem_graph Finsupp.apply_eq_of_mem_graph @[simp 1100] -- porting note: change priority to appease `simpNF` theorem not_mem_graph_snd_zero (a : α) (f : α →₀ M) : (a, (0 : M)) ∉ f.graph := fun h => (mem_graph_iff.1 h).2.irrefl #align finsupp.not_mem_graph_snd_zero Finsupp.not_mem_graph_snd_zero @[simp] theorem image_fst_graph [DecidableEq α] (f : α →₀ M) : f.graph.image Prod.fst = f.support := by classical simp only [graph, map_eq_image, image_image, Embedding.coeFn_mk, (· ∘ ·), image_id'] #align finsupp.image_fst_graph Finsupp.image_fst_graph theorem graph_injective (α M) [Zero M] : Injective (@graph α M _) := by intro f g h classical have hsup : f.support = g.support := by rw [← image_fst_graph, h, image_fst_graph] refine' ext_iff'.2 ⟨hsup, fun x hx => apply_eq_of_mem_graph <| h.symm ▸ _⟩ exact mk_mem_graph _ (hsup ▸ hx) #align finsupp.graph_injective Finsupp.graph_injective @[simp] theorem graph_inj {f g : α →₀ M} : f.graph = g.graph ↔ f = g := (graph_injective α M).eq_iff #align finsupp.graph_inj Finsupp.graph_inj @[simp] theorem graph_zero : graph (0 : α →₀ M) = ∅ := by simp [graph] #align finsupp.graph_zero Finsupp.graph_zero @[simp] theorem graph_eq_empty {f : α →₀ M} : f.graph = ∅ ↔ f = 0 := (graph_injective α M).eq_iff' graph_zero #align finsupp.graph_eq_empty Finsupp.graph_eq_empty end Graph end Finsupp /-! ### Declarations about `mapRange` -/ section MapRange namespace Finsupp section Equiv variable [Zero M] [Zero N] [Zero P] /-- `Finsupp.mapRange` as an equiv. -/ @[simps apply] def mapRange.equiv (f : M ≃ N) (hf : f 0 = 0) (hf' : f.symm 0 = 0) : (α →₀ M) ≃ (α →₀ N) where toFun := (mapRange f hf : (α →₀ M) → α →₀ N) invFun := (mapRange f.symm hf' : (α →₀ N) → α →₀ M) left_inv x := by rw [← mapRange_comp _ _ _ _] <;> simp_rw [Equiv.symm_comp_self] · exact mapRange_id _ · rfl right_inv x := by rw [← mapRange_comp _ _ _ _] <;> simp_rw [Equiv.self_comp_symm] · exact mapRange_id _ · rfl #align finsupp.map_range.equiv Finsupp.mapRange.equiv @[simp] theorem mapRange.equiv_refl : mapRange.equiv (Equiv.refl M) rfl rfl = Equiv.refl (α →₀ M) := Equiv.ext mapRange_id #align finsupp.map_range.equiv_refl Finsupp.mapRange.equiv_refl theorem mapRange.equiv_trans (f : M ≃ N) (hf : f 0 = 0) (hf') (f₂ : N ≃ P) (hf₂ : f₂ 0 = 0) (hf₂') : (mapRange.equiv (f.trans f₂) (by rw [Equiv.trans_apply, hf, hf₂]) (by rw [Equiv.symm_trans_apply, hf₂', hf']) : (α →₀ _) ≃ _) = (mapRange.equiv f hf hf').trans (mapRange.equiv f₂ hf₂ hf₂') := Equiv.ext <| mapRange_comp f₂ hf₂ f hf ((congrArg f₂ hf).trans hf₂) #align finsupp.map_range.equiv_trans Finsupp.mapRange.equiv_trans @[simp] theorem mapRange.equiv_symm (f : M ≃ N) (hf hf') : ((mapRange.equiv f hf hf').symm : (α →₀ _) ≃ _) = mapRange.equiv f.symm hf' hf := Equiv.ext fun _ => rfl #align finsupp.map_range.equiv_symm Finsupp.mapRange.equiv_symm end Equiv section ZeroHom variable [Zero M] [Zero N] [Zero P] /-- Composition with a fixed zero-preserving homomorphism is itself an zero-preserving homomorphism on functions. -/ @[simps] def mapRange.zeroHom (f : ZeroHom M N) : ZeroHom (α →₀ M) (α →₀ N) where toFun := (mapRange f f.map_zero : (α →₀ M) → α →₀ N) map_zero' := mapRange_zero #align finsupp.map_range.zero_hom Finsupp.mapRange.zeroHom @[simp] theorem mapRange.zeroHom_id : mapRange.zeroHom (ZeroHom.id M) = ZeroHom.id (α →₀ M) := ZeroHom.ext mapRange_id #align finsupp.map_range.zero_hom_id Finsupp.mapRange.zeroHom_id theorem mapRange.zeroHom_comp (f : ZeroHom N P) (f₂ : ZeroHom M N) : (mapRange.zeroHom (f.comp f₂) : ZeroHom (α →₀ _) _) = (mapRange.zeroHom f).comp (mapRange.zeroHom f₂) := ZeroHom.ext <| mapRange_comp f (map_zero f) f₂ (map_zero f₂) (by simp only [comp_apply, map_zero]) #align finsupp.map_range.zero_hom_comp Finsupp.mapRange.zeroHom_comp end ZeroHom section AddMonoidHom variable [AddCommMonoid M] [AddCommMonoid N] [AddCommMonoid P] /-- Composition with a fixed additive homomorphism is itself an additive homomorphism on functions. -/ @[simps] def mapRange.addMonoidHom (f : M →+ N) : (α →₀ M) →+ α →₀ N where toFun := (mapRange f f.map_zero : (α →₀ M) → α →₀ N) map_zero' := mapRange_zero map_add' a b := by dsimp only; exact mapRange_add f.map_add _ _; -- porting note: `dsimp` needed #align finsupp.map_range.add_monoid_hom Finsupp.mapRange.addMonoidHom @[simp] theorem mapRange.addMonoidHom_id : mapRange.addMonoidHom (AddMonoidHom.id M) = AddMonoidHom.id (α →₀ M) := AddMonoidHom.ext mapRange_id #align finsupp.map_range.add_monoid_hom_id Finsupp.mapRange.addMonoidHom_id theorem mapRange.addMonoidHom_comp (f : N →+ P) (f₂ : M →+ N) : (mapRange.addMonoidHom (f.comp f₂) : (α →₀ _) →+ _) = (mapRange.addMonoidHom f).comp (mapRange.addMonoidHom f₂) := AddMonoidHom.ext <| mapRange_comp f (map_zero f) f₂ (map_zero f₂) (by simp only [comp_apply, map_zero]) #align finsupp.map_range.add_monoid_hom_comp Finsupp.mapRange.addMonoidHom_comp @[simp] theorem mapRange.addMonoidHom_toZeroHom (f : M →+ N) : (mapRange.addMonoidHom f).toZeroHom = (mapRange.zeroHom f.toZeroHom : ZeroHom (α →₀ _) _) := ZeroHom.ext fun _ => rfl #align finsupp.map_range.add_monoid_hom_to_zero_hom Finsupp.mapRange.addMonoidHom_toZeroHom theorem mapRange_multiset_sum (f : M →+ N) (m : Multiset (α →₀ M)) : mapRange f f.map_zero m.sum = (m.map fun x => mapRange f f.map_zero x).sum := (mapRange.addMonoidHom f : (α →₀ _) →+ _).map_multiset_sum _ #align finsupp.map_range_multiset_sum Finsupp.mapRange_multiset_sum theorem mapRange_finset_sum (f : M →+ N) (s : Finset ι) (g : ι → α →₀ M) : mapRange f f.map_zero (∑ x in s, g x) = ∑ x in s, mapRange f f.map_zero (g x) := (mapRange.addMonoidHom f : (α →₀ _) →+ _).map_sum _ _ #align finsupp.map_range_finset_sum Finsupp.mapRange_finset_sum /-- `Finsupp.mapRange.AddMonoidHom` as an equiv. -/ @[simps apply] def mapRange.addEquiv (f : M ≃+ N) : (α →₀ M) ≃+ (α →₀ N) := { mapRange.addMonoidHom f.toAddMonoidHom with toFun := (mapRange f f.map_zero : (α →₀ M) → α →₀ N) invFun := (mapRange f.symm f.symm.map_zero : (α →₀ N) → α →₀ M) left_inv := fun x => by rw [← mapRange_comp _ _ _ _] <;> simp_rw [AddEquiv.symm_comp_self] · exact mapRange_id _ · rfl right_inv := fun x => by rw [← mapRange_comp _ _ _ _] <;> simp_rw [AddEquiv.self_comp_symm] · exact mapRange_id _ · rfl } #align finsupp.map_range.add_equiv Finsupp.mapRange.addEquiv @[simp] theorem mapRange.addEquiv_refl : mapRange.addEquiv (AddEquiv.refl M) = AddEquiv.refl (α →₀ M) := AddEquiv.ext mapRange_id #align finsupp.map_range.add_equiv_refl Finsupp.mapRange.addEquiv_refl theorem mapRange.addEquiv_trans (f : M ≃+ N) (f₂ : N ≃+ P) : (mapRange.addEquiv (f.trans f₂) : (α →₀ M) ≃+ (α →₀ P)) = (mapRange.addEquiv f).trans (mapRange.addEquiv f₂) := AddEquiv.ext (mapRange_comp _ f₂.map_zero _ f.map_zero (by simp)) #align finsupp.map_range.add_equiv_trans Finsupp.mapRange.addEquiv_trans @[simp] theorem mapRange.addEquiv_symm (f : M ≃+ N) : ((mapRange.addEquiv f).symm : (α →₀ _) ≃+ _) = mapRange.addEquiv f.symm := AddEquiv.ext fun _ => rfl #align finsupp.map_range.add_equiv_symm Finsupp.mapRange.addEquiv_symm @[simp] theorem mapRange.addEquiv_toAddMonoidHom (f : M ≃+ N) : (mapRange.addEquiv f : (α →₀ _) ≃+ _).toAddMonoidHom = (mapRange.addMonoidHom f.toAddMonoidHom : (α →₀ _) →+ _) := AddMonoidHom.ext fun _ => rfl #align finsupp.map_range.add_equiv_to_add_monoid_hom Finsupp.mapRange.addEquiv_toAddMonoidHom @[simp] theorem mapRange.addEquiv_toEquiv (f : M ≃+ N) : ↑(mapRange.addEquiv f : (α →₀ _) ≃+ _) = (mapRange.equiv (f : M ≃ N) f.map_zero f.symm.map_zero : (α →₀ _) ≃ _) := Equiv.ext fun _ => rfl #align finsupp.map_range.add_equiv_to_equiv Finsupp.mapRange.addEquiv_toEquiv end AddMonoidHom end Finsupp end MapRange /-! ### Declarations about `equivCongrLeft` -/ section EquivCongrLeft variable [Zero M] namespace Finsupp /-- Given `f : α ≃ β`, we can map `l : α →₀ M` to `equivMapDomain f l : β →₀ M` (computably) by mapping the support forwards and the function backwards. -/ def equivMapDomain (f : α ≃ β) (l : α →₀ M) : β →₀ M where support := l.support.map f.toEmbedding toFun a := l (f.symm a) mem_support_toFun a := by simp only [Finset.mem_map_equiv, mem_support_toFun]; rfl #align finsupp.equiv_map_domain Finsupp.equivMapDomain @[simp] theorem equivMapDomain_apply (f : α ≃ β) (l : α →₀ M) (b : β) : equivMapDomain f l b = l (f.symm b) := rfl #align finsupp.equiv_map_domain_apply Finsupp.equivMapDomain_apply theorem equivMapDomain_symm_apply (f : α ≃ β) (l : β →₀ M) (a : α) : equivMapDomain f.symm l a = l (f a) := rfl #align finsupp.equiv_map_domain_symm_apply Finsupp.equivMapDomain_symm_apply @[simp] theorem equivMapDomain_refl (l : α →₀ M) : equivMapDomain (Equiv.refl _) l = l := by ext x; rfl #align finsupp.equiv_map_domain_refl Finsupp.equivMapDomain_refl theorem equivMapDomain_refl' : equivMapDomain (Equiv.refl _) = @id (α →₀ M) := by ext x; rfl #align finsupp.equiv_map_domain_refl' Finsupp.equivMapDomain_refl' theorem equivMapDomain_trans (f : α ≃ β) (g : β ≃ γ) (l : α →₀ M) : equivMapDomain (f.trans g) l = equivMapDomain g (equivMapDomain f l) := by ext x; rfl #align finsupp.equiv_map_domain_trans Finsupp.equivMapDomain_trans theorem equivMapDomain_trans' (f : α ≃ β) (g : β ≃ γ) : @equivMapDomain _ _ M _ (f.trans g) = equivMapDomain g ∘ equivMapDomain f := by ext x; rfl #align finsupp.equiv_map_domain_trans' Finsupp.equivMapDomain_trans' @[simp] theorem equivMapDomain_single (f : α ≃ β) (a : α) (b : M) : equivMapDomain f (single a b) = single (f a) b := by classical ext x simp only [single_apply, Equiv.apply_eq_iff_eq_symm_apply, equivMapDomain_apply] #align finsupp.equiv_map_domain_single Finsupp.equivMapDomain_single @[simp] theorem equivMapDomain_zero {f : α ≃ β} : equivMapDomain f (0 : α →₀ M) = (0 : β →₀ M) := by ext; simp only [equivMapDomain_apply, coe_zero, Pi.zero_apply] #align finsupp.equiv_map_domain_zero Finsupp.equivMapDomain_zero /-- Given `f : α ≃ β`, the finitely supported function spaces are also in bijection: `(α →₀ M) ≃ (β →₀ M)`. This is the finitely-supported version of `Equiv.piCongrLeft`. -/ def equivCongrLeft (f : α ≃ β) : (α →₀ M) ≃ (β →₀ M) := by refine' ⟨equivMapDomain f, equivMapDomain f.symm, fun f => _, fun f => _⟩ <;> ext x <;> simp only [equivMapDomain_apply, Equiv.symm_symm, Equiv.symm_apply_apply, Equiv.apply_symm_apply] #align finsupp.equiv_congr_left Finsupp.equivCongrLeft @[simp] theorem equivCongrLeft_apply (f : α ≃ β) (l : α →₀ M) : equivCongrLeft f l = equivMapDomain f l := rfl #align finsupp.equiv_congr_left_apply Finsupp.equivCongrLeft_apply @[simp] theorem equivCongrLeft_symm (f : α ≃ β) : (@equivCongrLeft _ _ M _ f).symm = equivCongrLeft f.symm := rfl #align finsupp.equiv_congr_left_symm Finsupp.equivCongrLeft_symm end Finsupp end EquivCongrLeft section CastFinsupp variable [Zero M] (f : α →₀ M) namespace Nat @[simp, norm_cast] theorem cast_finsupp_prod [CommSemiring R] (g : α → M → ℕ) : (↑(f.prod g) : R) = f.prod fun a b => ↑(g a b) := Nat.cast_prod _ _ #align nat.cast_finsupp_prod Nat.cast_finsupp_prod @[simp, norm_cast] theorem cast_finsupp_sum [CommSemiring R] (g : α → M → ℕ) : (↑(f.sum g) : R) = f.sum fun a b => ↑(g a b) := Nat.cast_sum _ _ #align nat.cast_finsupp_sum Nat.cast_finsupp_sum end Nat namespace Int @[simp, norm_cast] theorem cast_finsupp_prod [CommRing R] (g : α → M → ℤ) : (↑(f.prod g) : R) = f.prod fun a b => ↑(g a b) := Int.cast_prod _ _ #align int.cast_finsupp_prod Int.cast_finsupp_prod @[simp, norm_cast] theorem cast_finsupp_sum [CommRing R] (g : α → M → ℤ) : (↑(f.sum g) : R) = f.sum fun a b => ↑(g a b) := Int.cast_sum _ _ #align int.cast_finsupp_sum Int.cast_finsupp_sum end Int namespace Rat @[simp, norm_cast] theorem cast_finsupp_sum [DivisionRing R] [CharZero R] (g : α → M → ℚ) : (↑(f.sum g) : R) = f.sum fun a b => ↑(g a b) := cast_sum _ _ #align rat.cast_finsupp_sum Rat.cast_finsupp_sum @[simp, norm_cast] theorem cast_finsupp_prod [Field R] [CharZero R] (g : α → M → ℚ) : (↑(f.prod g) : R) = f.prod fun a b => ↑(g a b) := cast_prod _ _ #align rat.cast_finsupp_prod Rat.cast_finsupp_prod end Rat end CastFinsupp /-! ### Declarations about `mapDomain` -/ namespace Finsupp section MapDomain variable [AddCommMonoid M] {v v₁ v₂ : α →₀ M} /-- Given `f : α → β` and `v : α →₀ M`, `mapDomain f v : β →₀ M` is the finitely supported function whose value at `a : β` is the sum of `v x` over all `x` such that `f x = a`. -/ def mapDomain (f : α → β) (v : α →₀ M) : β →₀ M := v.sum fun a => single (f a) #align finsupp.map_domain Finsupp.mapDomain theorem mapDomain_apply {f : α → β} (hf : Function.Injective f) (x : α →₀ M) (a : α) : mapDomain f x (f a) = x a := by rw [mapDomain, sum_apply, sum, Finset.sum_eq_single a, single_eq_same] · intro b _ hba exact single_eq_of_ne (hf.ne hba) · intro h rw [not_mem_support_iff.1 h, single_zero, zero_apply] #align finsupp.map_domain_apply Finsupp.mapDomain_apply theorem mapDomain_notin_range {f : α → β} (x : α →₀ M) (a : β) (h : a ∉ Set.range f) : mapDomain f x a = 0 := by rw [mapDomain, sum_apply, sum] exact Finset.sum_eq_zero fun a' _ => single_eq_of_ne fun eq => h <| eq ▸ Set.mem_range_self _ #align finsupp.map_domain_notin_range Finsupp.mapDomain_notin_range @[simp] theorem mapDomain_id : mapDomain id v = v := sum_single _ #align finsupp.map_domain_id Finsupp.mapDomain_id theorem mapDomain_comp {f : α → β} {g : β → γ} : mapDomain (g ∘ f) v = mapDomain g (mapDomain f v) := by refine' ((sum_sum_index _ _).trans _).symm · intro exact single_zero _ · intro exact single_add _ refine' sum_congr fun _ _ => sum_single_index _ · exact single_zero _ #align finsupp.map_domain_comp Finsupp.mapDomain_comp @[simp] theorem mapDomain_single {f : α → β} {a : α} {b : M} : mapDomain f (single a b) = single (f a) b := sum_single_index <| single_zero _ #align finsupp.map_domain_single Finsupp.mapDomain_single @[simp] theorem mapDomain_zero {f : α → β} : mapDomain f (0 : α →₀ M) = (0 : β →₀ M) := sum_zero_index #align finsupp.map_domain_zero Finsupp.mapDomain_zero theorem mapDomain_congr {f g : α → β} (h : ∀ x ∈ v.support, f x = g x) : v.mapDomain f = v.mapDomain g := Finset.sum_congr rfl fun _ H => by simp only [h _ H] #align finsupp.map_domain_congr Finsupp.mapDomain_congr theorem mapDomain_add {f : α → β} : mapDomain f (v₁ + v₂) = mapDomain f v₁ + mapDomain f v₂ := sum_add_index' (fun _ => single_zero _) fun _ => single_add _ #align finsupp.map_domain_add Finsupp.mapDomain_add @[simp] theorem mapDomain_equiv_apply {f : α ≃ β} (x : α →₀ M) (a : β) : mapDomain f x a = x (f.symm a) := by conv_lhs => rw [← f.apply_symm_apply a] exact mapDomain_apply f.injective _ _ #align finsupp.map_domain_equiv_apply Finsupp.mapDomain_equiv_apply /-- `Finsupp.mapDomain` is an `AddMonoidHom`. -/ @[simps] def mapDomain.addMonoidHom (f : α → β) : (α →₀ M) →+ β →₀ M where toFun := mapDomain f map_zero' := mapDomain_zero map_add' _ _ := mapDomain_add #align finsupp.map_domain.add_monoid_hom Finsupp.mapDomain.addMonoidHom @[simp] theorem mapDomain.addMonoidHom_id : mapDomain.addMonoidHom id = AddMonoidHom.id (α →₀ M) := AddMonoidHom.ext fun _ => mapDomain_id #align finsupp.map_domain.add_monoid_hom_id Finsupp.mapDomain.addMonoidHom_id theorem mapDomain.addMonoidHom_comp (f : β → γ) (g : α → β) : (mapDomain.addMonoidHom (f ∘ g) : (α →₀ M) →+ γ →₀ M) = (mapDomain.addMonoidHom f).comp (mapDomain.addMonoidHom g) := AddMonoidHom.ext fun _ => mapDomain_comp #align finsupp.map_domain.add_monoid_hom_comp Finsupp.mapDomain.addMonoidHom_comp theorem mapDomain_finset_sum {f : α → β} {s : Finset ι} {v : ι → α →₀ M} : mapDomain f (∑ i in s, v i) = ∑ i in s, mapDomain f (v i) := (mapDomain.addMonoidHom f : (α →₀ M) →+ β →₀ M).map_sum _ _ #align finsupp.map_domain_finset_sum Finsupp.mapDomain_finset_sum theorem mapDomain_sum [Zero N] {f : α → β} {s : α →₀ N} {v : α → N → α →₀ M} : mapDomain f (s.sum v) = s.sum fun a b => mapDomain f (v a b) := (mapDomain.addMonoidHom f : (α →₀ M) →+ β →₀ M).map_finsupp_sum _ _ #align finsupp.map_domain_sum Finsupp.mapDomain_sum theorem mapDomain_support [DecidableEq β] {f : α → β} {s : α →₀ M} : (s.mapDomain f).support ⊆ s.support.image f := Finset.Subset.trans support_sum <| Finset.Subset.trans (Finset.bunionᵢ_mono fun a _ => support_single_subset) <| by rw [Finset.bunionᵢ_singleton] #align finsupp.map_domain_support Finsupp.mapDomain_support theorem mapDomain_apply' (S : Set α) {f : α → β} (x : α →₀ M) (hS : (x.support : Set α) ⊆ S) (hf : Set.InjOn f S) {a : α} (ha : a ∈ S) : mapDomain f x (f a) = x a := by classical rw [mapDomain, sum_apply, sum] simp_rw [single_apply] by_cases hax : a ∈ x.support · rw [← Finset.add_sum_erase _ _ hax, if_pos rfl] convert add_zero (x a) refine' Finset.sum_eq_zero fun i hi => if_neg _ exact (hf.mono hS).ne (Finset.mem_of_mem_erase hi) hax (Finset.ne_of_mem_erase hi) · rw [not_mem_support_iff.1 hax] refine' Finset.sum_eq_zero fun i hi => if_neg _ exact hf.ne (hS hi) ha (ne_of_mem_of_not_mem hi hax) #align finsupp.map_domain_apply' Finsupp.mapDomain_apply' theorem mapDomain_support_of_injective [DecidableEq β] {f : α → β} (hf : Function.Injective f) (s : α →₀ M) : (mapDomain f s).support = Finset.image f s.support := mapDomain_support_of_injOn s (hf.injOn _) #align finsupp.map_domain_support_of_injective Finsupp.mapDomain_support_of_injective @[to_additive] theorem prod_mapDomain_index [CommMonoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (h_zero : ∀ b, h b 0 = 1) (h_add : ∀ b m₁ m₂, h b (m₁ + m₂) = h b m₁ * h b m₂) : (mapDomain f s).prod h = s.prod fun a m => h (f a) m := (prod_sum_index h_zero h_add).trans <| prod_congr fun _ _ => prod_single_index (h_zero _) #align finsupp.prod_map_domain_index Finsupp.prod_mapDomain_index #align finsupp.sum_map_domain_index Finsupp.sum_mapDomain_index -- Note that in `prod_mapDomain_index`, `M` is still an additive monoid, -- so there is no analogous version in terms of `MonoidHom`. /-- A version of `sum_mapDomain_index` that takes a bundled `AddMonoidHom`, rather than separate linearity hypotheses. -/ @[simp] theorem sum_mapDomain_index_addMonoidHom [AddCommMonoid N] {f : α → β} {s : α →₀ M} (h : β → M →+ N) : ((mapDomain f s).sum fun b m => h b m) = s.sum fun a m => h (f a) m := sum_mapDomain_index (fun b => (h b).map_zero) (fun b _ _ => (h b).map_add _ _) #align finsupp.sum_map_domain_index_add_monoid_hom Finsupp.sum_mapDomain_index_addMonoidHom theorem embDomain_eq_mapDomain (f : α ↪ β) (v : α →₀ M) : embDomain f v = mapDomain f v := by ext a by_cases h : a ∈ Set.range f · rcases h with ⟨a, rfl⟩ rw [mapDomain_apply f.injective, embDomain_apply] · rw [mapDomain_notin_range, embDomain_notin_range] <;> assumption #align finsupp.emb_domain_eq_map_domain Finsupp.embDomain_eq_mapDomain @[to_additive] theorem prod_mapDomain_index_inj [CommMonoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (hf : Function.Injective f) : (s.mapDomain f).prod h = s.prod fun a b => h (f a) b := by rw [← Function.Embedding.coeFn_mk f hf, ← embDomain_eq_mapDomain, prod_embDomain] #align finsupp.prod_map_domain_index_inj Finsupp.prod_mapDomain_index_inj #align finsupp.sum_map_domain_index_inj Finsupp.sum_mapDomain_index_inj theorem mapDomain_injective {f : α → β} (hf : Function.Injective f) : Function.Injective (mapDomain f : (α →₀ M) → β →₀ M) := by intro v₁ v₂ eq ext a have : mapDomain f v₁ (f a) = mapDomain f v₂ (f a) := by rw [eq] rwa [mapDomain_apply hf, mapDomain_apply hf] at this #align finsupp.map_domain_injective Finsupp.mapDomain_injective /-- When `f` is an embedding we have an embedding `(α →₀ ℕ) ↪ (β →₀ ℕ)` given by `mapDomain`. -/ @[simps] def mapDomainEmbedding {α β : Type _} (f : α ↪ β) : (α →₀ ℕ) ↪ β →₀ ℕ := ⟨Finsupp.mapDomain f, Finsupp.mapDomain_injective f.injective⟩ #align finsupp.map_domain_embedding Finsupp.mapDomainEmbedding theorem mapDomain.addMonoidHom_comp_mapRange [AddCommMonoid N] (f : α → β) (g : M →+ N) : (mapDomain.addMonoidHom f).comp (mapRange.addMonoidHom g) = (mapRange.addMonoidHom g).comp (mapDomain.addMonoidHom f) := by apply Finsupp.addHom_ext' intro x apply AddMonoidHom.ext intro x_1 apply Finsupp.ext intro a simp only [AddMonoidHom.coe_comp, Finsupp.mapRange_single, Finsupp.mapDomain.addMonoidHom_apply, Finsupp.singleAddHom_apply, eq_self_iff_true, Function.comp_apply, Finsupp.mapDomain_single, Finsupp.mapRange.addMonoidHom_apply] -- porting note: this is ugly, just expanded the Lean 3 proof; `ext` didn't work in the same way #align finsupp.map_domain.add_monoid_hom_comp_map_range Finsupp.mapDomain.addMonoidHom_comp_mapRange /-- When `g` preserves addition, `mapRange` and `mapDomain` commute. -/ theorem mapDomain_mapRange [AddCommMonoid N] (f : α → β) (v : α →₀ M) (g : M → N) (h0 : g 0 = 0) (hadd : ∀ x y, g (x + y) = g x + g y) : mapDomain f (mapRange g h0 v) = mapRange g h0 (mapDomain f v) := let g' : M →+ N := { toFun := g map_zero' := h0 map_add' := hadd } FunLike.congr_fun (mapDomain.addMonoidHom_comp_mapRange f g') v #align finsupp.map_domain_map_range Finsupp.mapDomain_mapRange theorem sum_update_add [AddCommMonoid α] [AddCommMonoid β] (f : ι →₀ α) (i : ι) (a : α) (g : ι → α → β) (hg : ∀ i, g i 0 = 0) (hgg : ∀ (j : ι) (a₁ a₂ : α), g j (a₁ + a₂) = g j a₁ + g j a₂) : (f.update i a).sum g + g i (f i) = f.sum g + g i a := by rw [update_eq_erase_add_single, sum_add_index' hg hgg] conv_rhs => rw [← Finsupp.update_self f i] rw [update_eq_erase_add_single, sum_add_index' hg hgg, add_assoc, add_assoc] congr 1 rw [add_comm, sum_single_index (hg _), sum_single_index (hg _)] #align finsupp.sum_update_add Finsupp.sum_update_add theorem mapDomain_injOn (S : Set α) {f : α → β} (hf : Set.InjOn f S) : Set.InjOn (mapDomain f : (α →₀ M) → β →₀ M) { w | (w.support : Set α) ⊆ S } := by intro v₁ hv₁ v₂ hv₂ eq ext a classical by_cases h : a ∈ v₁.support ∪ v₂.support · rw [← mapDomain_apply' S _ hv₁ hf _, ← mapDomain_apply' S _ hv₂ hf _, eq] <;> · apply Set.union_subset hv₁ hv₂ exact_mod_cast h · simp only [not_or, mem_union, not_not, mem_support_iff] at h simp [h] #align finsupp.map_domain_inj_on Finsupp.mapDomain_injOn theorem equivMapDomain_eq_mapDomain {M} [AddCommMonoid M] (f : α ≃ β) (l : α →₀ M) : equivMapDomain f l = mapDomain f l := by ext x; simp [mapDomain_equiv_apply] #align finsupp.equiv_map_domain_eq_map_domain Finsupp.equivMapDomain_eq_mapDomain end MapDomain /-! ### Declarations about `comapDomain` -/ section ComapDomain /-- Given `f : α → β`, `l : β →₀ M` and a proof `hf` that `f` is injective on the preimage of `l.support`, `comapDomain f l hf` is the finitely supported function from `α` to `M` given by composing `l` with `f`. -/ @[simps support] def comapDomain [Zero M] (f : α → β) (l : β →₀ M) (hf : Set.InjOn f (f ⁻¹' ↑l.support)) : α →₀ M where support := l.support.preimage f hf toFun a := l (f a) mem_support_toFun := by intro a simp only [Finset.mem_def.symm, Finset.mem_preimage] exact l.mem_support_toFun (f a) #align finsupp.comap_domain Finsupp.comapDomain @[simp] theorem comapDomain_apply [Zero M] (f : α → β) (l : β →₀ M) (hf : Set.InjOn f (f ⁻¹' ↑l.support)) (a : α) : comapDomain f l hf a = l (f a) := rfl #align finsupp.comap_domain_apply Finsupp.comapDomain_apply theorem sum_comapDomain [Zero M] [AddCommMonoid N] (f : α → β) (l : β →₀ M) (g : β → M → N) (hf : Set.BijOn f (f ⁻¹' ↑l.support) ↑l.support) : (comapDomain f l hf.injOn).sum (g ∘ f) = l.sum g := by simp only [sum, comapDomain_apply, (· ∘ ·), comapDomain] exact Finset.sum_preimage_of_bij f _ hf fun x => g x (l x) #align finsupp.sum_comap_domain Finsupp.sum_comapDomain theorem eq_zero_of_comapDomain_eq_zero [AddCommMonoid M] (f : α → β) (l : β →₀ M) (hf : Set.BijOn f (f ⁻¹' ↑l.support) ↑l.support) : comapDomain f l hf.injOn = 0 → l = 0 := by rw [← support_eq_empty, ← support_eq_empty, comapDomain] simp only [Finset.ext_iff, Finset.not_mem_empty, iff_false_iff, mem_preimage] intro h a ha cases' hf.2.2 ha with b hb exact h b (hb.2.symm ▸ ha) #align finsupp.eq_zero_of_comap_domain_eq_zero Finsupp.eq_zero_of_comapDomain_eq_zero section FInjective section Zero variable [Zero M] /-- Note the `hif` argument is needed for this to work in `rw`. -/ @[simp] theorem comapDomain_zero (f : α → β) (hif : Set.InjOn f (f ⁻¹' ↑(0 : β →₀ M).support) := Finset.coe_empty ▸ (Set.injOn_empty f)) : comapDomain f (0 : β →₀ M) hif = (0 : α →₀ M) := by ext rfl #align finsupp.comap_domain_zero Finsupp.comapDomain_zero @[simp] theorem comapDomain_single (f : α → β) (a : α) (m : M) (hif : Set.InjOn f (f ⁻¹' (single (f a) m).support)) : comapDomain f (Finsupp.single (f a) m) hif = Finsupp.single a m := by rcases eq_or_ne m 0 with (rfl | hm) · simp only [single_zero, comapDomain_zero] · rw [eq_single_iff, comapDomain_apply, comapDomain_support, ← Finset.coe_subset, coe_preimage, support_single_ne_zero _ hm, coe_singleton, coe_singleton, single_eq_same] rw [support_single_ne_zero _ hm, coe_singleton] at hif exact ⟨fun x hx => hif hx rfl hx, rfl⟩ #align finsupp.comap_domain_single Finsupp.comapDomain_single end Zero section AddZeroClass variable [AddZeroClass M] {f : α → β} theorem comapDomain_add (v₁ v₂ : β →₀ M) (hv₁ : Set.InjOn f (f ⁻¹' ↑v₁.support)) (hv₂ : Set.InjOn f (f ⁻¹' ↑v₂.support)) (hv₁₂ : Set.InjOn f (f ⁻¹' ↑(v₁ + v₂).support)) : comapDomain f (v₁ + v₂) hv₁₂ = comapDomain f v₁ hv₁ + comapDomain f v₂ hv₂ := by ext simp only [comapDomain_apply, coe_add, Pi.add_apply] #align finsupp.comap_domain_add Finsupp.comapDomain_add /-- A version of `Finsupp.comapDomain_add` that's easier to use. -/ theorem comapDomain_add_of_injective (hf : Function.Injective f) (v₁ v₂ : β →₀ M) : comapDomain f (v₁ + v₂) (hf.injOn _) = comapDomain f v₁ (hf.injOn _) + comapDomain f v₂ (hf.injOn _) := comapDomain_add _ _ _ _ _ #align finsupp.comap_domain_add_of_injective Finsupp.comapDomain_add_of_injective /-- `Finsupp.comapDomain` is an `AddMonoidHom`. -/ @[simps] def comapDomain.addMonoidHom (hf : Function.Injective f) : (β →₀ M) →+ α →₀ M where toFun x := comapDomain f x (hf.injOn _) map_zero' := comapDomain_zero f map_add' := comapDomain_add_of_injective hf #align finsupp.comap_domain.add_monoid_hom Finsupp.comapDomain.addMonoidHom end AddZeroClass variable [AddCommMonoid M] (f : α → β) theorem mapDomain_comapDomain (hf : Function.Injective f) (l : β →₀ M) (hl : ↑l.support ⊆ Set.range f) : mapDomain f (comapDomain f l (hf.injOn _)) = l := by ext a by_cases h_cases : a ∈ Set.range f · rcases Set.mem_range.1 h_cases with ⟨b, hb⟩ rw [hb.symm, mapDomain_apply hf, comapDomain_apply] · rw [mapDomain_notin_range _ _ h_cases] by_contra h_contr apply h_cases (hl <| Finset.mem_coe.2 <| mem_support_iff.2 fun h => h_contr h.symm) #align finsupp.map_domain_comap_domain Finsupp.mapDomain_comapDomain end FInjective end ComapDomain /-! ### Declarations about finitely supported functions whose support is an `option` type -/ section Option /-- Restrict a finitely supported function on `option α` to a finitely supported function on `α`. -/ def some [Zero M] (f : Option α →₀ M) : α →₀ M := f.comapDomain Option.some fun _ => by simp #align finsupp.some Finsupp.some @[simp] theorem some_apply [Zero M] (f : Option α →₀ M) (a : α) : f.some a = f (Option.some a) := rfl #align finsupp.some_apply Finsupp.some_apply @[simp] theorem some_zero [Zero M] : (0 : Option α →₀ M).some = 0 := by ext simp #align finsupp.some_zero Finsupp.some_zero @[simp] theorem some_add [AddCommMonoid M] (f g : Option α →₀ M) : (f + g).some = f.some + g.some := by ext simp #align finsupp.some_add Finsupp.some_add @[simp] theorem some_single_none [Zero M] (m : M) : (single none m : Option α →₀ M).some = 0 := by ext simp #align finsupp.some_single_none Finsupp.some_single_none @[simp] theorem some_single_some [Zero M] (a : α) (m : M) : (single (Option.some a) m : Option α →₀ M).some = single a m := by classical ext b simp [single_apply] #align finsupp.some_single_some Finsupp.some_single_some @[to_additive] theorem prod_option_index [AddCommMonoid M] [CommMonoid N] (f : Option α →₀ M) (b : Option α → M → N) (h_zero : ∀ o, b o 0 = 1) (h_add : ∀ o m₁ m₂, b o (m₁ + m₂) = b o m₁ * b o m₂) : f.prod b = b none (f none) * f.some.prod fun a => b (Option.some a) := by classical apply induction_linear f · simp [some_zero, h_zero] · intro f₁ f₂ h₁ h₂ rw [Finsupp.prod_add_index, h₁, h₂, some_add, Finsupp.prod_add_index] simp only [h_add, Pi.add_apply, Finsupp.coe_add] rw [mul_mul_mul_comm] all_goals simp [h_zero, h_add] · rintro (_ | a) m <;> simp [h_zero, h_add] #align finsupp.prod_option_index Finsupp.prod_option_index #align finsupp.sum_option_index Finsupp.sum_option_index theorem sum_option_index_smul [Semiring R] [AddCommMonoid M] [Module R M] (f : Option α →₀ R) (b : Option α → M) : (f.sum fun o r => r • b o) = f none • b none + f.some.sum fun a r => r • b (Option.some a) := f.sum_option_index _ (fun _ => zero_smul _ _) fun _ _ _ => add_smul _ _ _ #align finsupp.sum_option_index_smul Finsupp.sum_option_index_smul end Option /-! ### Declarations about `Finsupp.filter` -/ section Filter section Zero variable [Zero M] (p : α → Prop) (f : α →₀ M) /-- `filter p f` is the finitely supported function that is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) (f : α →₀ M) : α →₀ M where toFun a := haveI := Classical.decPred p if p a then f a else 0 support := haveI := Classical.decPred p f.support.filter fun a => p a mem_support_toFun a := by simp only -- porting note: necessary to beta reduce to activate `split_ifs` split_ifs with h <;> · simp only [h, @mem_filter _ _ (Classical.decPred p), mem_support_iff] -- porting note: I needed to provide the instance explicitly tauto #align finsupp.filter Finsupp.filter theorem filter_apply (a : α) [D : Decidable (p a)] : f.filter p a = if p a then f a else 0 := by rw [Subsingleton.elim D] <;> rfl #align finsupp.filter_apply Finsupp.filter_apply theorem filter_eq_indicator : ⇑(f.filter p) = Set.indicator { x | p x } f := rfl #align finsupp.filter_eq_indicator Finsupp.filter_eq_indicator theorem filter_eq_zero_iff : f.filter p = 0 ↔ ∀ x, p x → f x = 0 := by simp only [FunLike.ext_iff, filter_eq_indicator, zero_apply, Set.indicator_apply_eq_zero, Set.mem_setOf_eq] #align finsupp.filter_eq_zero_iff Finsupp.filter_eq_zero_iff theorem filter_eq_self_iff : f.filter p = f ↔ ∀ x, f x ≠ 0 → p x := by simp only [FunLike.ext_iff, filter_eq_indicator, Set.indicator_apply_eq_self, Set.mem_setOf_eq, not_imp_comm] #align finsupp.filter_eq_self_iff Finsupp.filter_eq_self_iff @[simp] theorem filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h #align finsupp.filter_apply_pos Finsupp.filter_apply_pos @[simp] theorem filter_apply_neg {a : α} (h : ¬p a) : f.filter p a = 0 := if_neg h #align finsupp.filter_apply_neg Finsupp.filter_apply_neg @[simp] theorem support_filter [D : DecidablePred p] : (f.filter p).support = f.support.filter p := by rw [Subsingleton.elim D] <;> rfl #align finsupp.support_filter Finsupp.support_filter theorem filter_zero : (0 : α →₀ M).filter p = 0 := by classical rw [← support_eq_empty, support_filter, support_zero, Finset.filter_empty] #align finsupp.filter_zero Finsupp.filter_zero @[simp] theorem filter_single_of_pos {a : α} {b : M} (h : p a) : (single a b).filter p = single a b := (filter_eq_self_iff _ _).2 fun _ hx => (single_apply_ne_zero.1 hx).1.symm ▸ h #align finsupp.filter_single_of_pos Finsupp.filter_single_of_pos @[simp] theorem filter_single_of_neg {a : α} {b : M} (h : ¬p a) : (single a b).filter p = 0 := (filter_eq_zero_iff _ _).2 fun _ hpx => single_apply_eq_zero.2 fun hxa => absurd hpx (hxa.symm ▸ h) #align finsupp.filter_single_of_neg Finsupp.filter_single_of_neg @[to_additive] theorem prod_filter_index [CommMonoid N] (g : α → M → N) : (f.filter p).prod g = ∏ x in (f.filter p).support, g x (f x) := by classical refine' Finset.prod_congr rfl fun x hx => _ rw [support_filter, Finset.mem_filter] at hx rw [filter_apply_pos _ _ hx.2] #align finsupp.prod_filter_index Finsupp.prod_filter_index #align finsupp.sum_filter_index Finsupp.sum_filter_index @[to_additive (attr := simp)] theorem prod_filter_mul_prod_filter_not [CommMonoid N] (g : α → M → N) : (f.filter p).prod g * (f.filter fun a => ¬p a).prod g = f.prod g := by classical simp_rw [prod_filter_index, support_filter, Finset.prod_filter_mul_prod_filter_not, Finsupp.prod] #align finsupp.prod_filter_mul_prod_filter_not Finsupp.prod_filter_mul_prod_filter_not #align finsupp.sum_filter_add_sum_filter_not Finsupp.sum_filter_add_sum_filter_not @[to_additive (attr := simp)] theorem prod_div_prod_filter [CommGroup G] (g : α → M → G) : f.prod g / (f.filter p).prod g = (f.filter fun a => ¬p a).prod g := div_eq_of_eq_mul' (prod_filter_mul_prod_filter_not _ _ _).symm #align finsupp.prod_div_prod_filter Finsupp.prod_div_prod_filter #align finsupp.sum_sub_sum_filter Finsupp.sum_sub_sum_filter end Zero theorem filter_pos_add_filter_neg [AddZeroClass M] (f : α →₀ M) (p : α → Prop) : (f.filter p + f.filter fun a => ¬p a) = f := FunLike.coe_injective <| Set.indicator_self_add_compl { x | p x } f #align finsupp.filter_pos_add_filter_neg Finsupp.filter_pos_add_filter_neg end Filter /-! ### Declarations about `frange` -/ section Frange variable [Zero M] /-- `frange f` is the image of `f` on the support of `f`. -/ def frange (f : α →₀ M) : Finset M := haveI := Classical.decEq M Finset.image f f.support #align finsupp.frange Finsupp.frange theorem mem_frange {f : α →₀ M} {y : M} : y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y := by rw [frange, @Finset.mem_image _ _ (Classical.decEq _) _ f.support] exact ⟨fun ⟨x, hx1, hx2⟩ => ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩, fun ⟨hy, x, hx⟩ => ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩ -- porting note: maybe there is a better way to fix this, but (1) it wasn't seeing past `frange` -- the definition, and (2) it needed the `Classical.decEq` instance again. #align finsupp.mem_frange Finsupp.mem_frange theorem zero_not_mem_frange {f : α →₀ M} : (0 : M) ∉ f.frange := fun H => (mem_frange.1 H).1 rfl #align finsupp.zero_not_mem_frange Finsupp.zero_not_mem_frange theorem frange_single {x : α} {y : M} : frange (single x y) ⊆ {y} := fun r hr => let ⟨t, ht1, ht2⟩ := mem_frange.1 hr ht2 ▸ by classical rw [single_apply] at ht2⊢ split_ifs at ht2⊢ · exact Finset.mem_singleton_self _ · exact (t ht2.symm).elim #align finsupp.frange_single Finsupp.frange_single end Frange /-! ### Declarations about `Finsupp.subtypeDomain` -/ section SubtypeDomain section Zero variable [Zero M] {p : α → Prop} /-- `subtypeDomain p f` is the restriction of the finitely supported function `f` to subtype `p`. -/ def subtypeDomain (p : α → Prop) (f : α →₀ M) : Subtype p →₀ M where support := haveI := Classical.decPred p f.support.subtype p toFun := f ∘ Subtype.val mem_support_toFun a := by simp only [@mem_subtype _ _ (Classical.decPred p), mem_support_iff]; rfl #align finsupp.subtype_domain Finsupp.subtypeDomain @[simp] theorem support_subtypeDomain [D : DecidablePred p] {f : α →₀ M} : (subtypeDomain p f).support = f.support.subtype p := by rw [Subsingleton.elim D] <;> rfl #align finsupp.support_subtype_domain Finsupp.support_subtypeDomain @[simp] theorem subtypeDomain_apply {a : Subtype p} {v : α →₀ M} : (subtypeDomain p v) a = v a.val := rfl #align finsupp.subtype_domain_apply Finsupp.subtypeDomain_apply @[simp] theorem subtypeDomain_zero : subtypeDomain p (0 : α →₀ M) = 0 := rfl #align finsupp.subtype_domain_zero Finsupp.subtypeDomain_zero theorem subtypeDomain_eq_zero_iff' {f : α →₀ M} : f.subtypeDomain p = 0 ↔ ∀ x, p x → f x = 0 := by classical simp_rw [← support_eq_empty, support_subtypeDomain, subtype_eq_empty, not_mem_support_iff] #align finsupp.subtype_domain_eq_zero_iff' Finsupp.subtypeDomain_eq_zero_iff' theorem subtypeDomain_eq_zero_iff {f : α →₀ M} (hf : ∀ x ∈ f.support, p x) : f.subtypeDomain p = 0 ↔ f = 0 := subtypeDomain_eq_zero_iff'.trans ⟨fun H => ext fun x => by classical exact if hx : p x then H x hx else not_mem_support_iff.1 <| mt (hf x) hx, fun H x _ => by simp [H]⟩ #align finsupp.subtype_domain_eq_zero_iff Finsupp.subtypeDomain_eq_zero_iff @[to_additive] theorem prod_subtypeDomain_index [CommMonoid N] {v : α →₀ M} {h : α → M → N} (hp : ∀ x ∈ v.support, p x) : ((v.subtypeDomain p).prod fun a b => h a b) = v.prod h := prod_bij (fun p _ => p.val) (fun _ => by classical exact mem_subtype.1) (fun _ _ => rfl) (fun _ _ _ _ => Subtype.eq) fun b hb => ⟨⟨b, hp b hb⟩, by classical exact mem_subtype.2 hb, rfl⟩ #align finsupp.prod_subtype_domain_index Finsupp.prod_subtypeDomain_index #align finsupp.sum_subtype_domain_index Finsupp.sum_subtypeDomain_index end Zero section AddZeroClass variable [AddZeroClass M] {p : α → Prop} {v v' : α →₀ M} @[simp] theorem subtypeDomain_add {v v' : α →₀ M} : (v + v').subtypeDomain p = v.subtypeDomain p + v'.subtypeDomain p := ext fun _ => rfl #align finsupp.subtype_domain_add Finsupp.subtypeDomain_add /-- `subtypeDomain` but as an `AddMonoidHom`. -/ def subtypeDomainAddMonoidHom : (α →₀ M) →+ Subtype p →₀ M where toFun := subtypeDomain p map_zero' := subtypeDomain_zero map_add' _ _ := subtypeDomain_add #align finsupp.subtype_domain_add_monoid_hom Finsupp.subtypeDomainAddMonoidHom /-- `Finsupp.filter` as an `AddMonoidHom`. -/ def filterAddHom (p : α → Prop) : (α →₀ M) →+ α →₀ M where toFun := filter p map_zero' := filter_zero p map_add' f g := FunLike.coe_injective <| Set.indicator_add { x | p x } f g #align finsupp.filter_add_hom Finsupp.filterAddHom @[simp] theorem filter_add {v v' : α →₀ M} : (v + v').filter p = v.filter p + v'.filter p := (filterAddHom p).map_add v v' #align finsupp.filter_add Finsupp.filter_add end AddZeroClass section CommMonoid variable [AddCommMonoid M] {p : α → Prop} theorem subtypeDomain_sum {s : Finset ι} {h : ι → α →₀ M} : (∑ c in s, h c).subtypeDomain p = ∑ c in s, (h c).subtypeDomain p := (subtypeDomainAddMonoidHom : _ →+ Subtype p →₀ M).map_sum _ s #align finsupp.subtype_domain_sum Finsupp.subtypeDomain_sum theorem subtypeDomain_finsupp_sum [Zero N] {s : β →₀ N} {h : β → N → α →₀ M} : (s.sum h).subtypeDomain p = s.sum fun c d => (h c d).subtypeDomain p := subtypeDomain_sum #align finsupp.subtype_domain_finsupp_sum Finsupp.subtypeDomain_finsupp_sum theorem filter_sum (s : Finset ι) (f : ι → α →₀ M) : (∑ a in s, f a).filter p = ∑ a in s, filter p (f a) := (filterAddHom p : (α →₀ M) →+ _).map_sum f s #align finsupp.filter_sum Finsupp.filter_sum theorem filter_eq_sum (p : α → Prop) [D : DecidablePred p] (f : α →₀ M) : f.filter p = ∑ i in f.support.filter p, single i (f i) := (f.filter p).sum_single.symm.trans <| Finset.sum_congr (by rw [Subsingleton.elim D] <;> rfl) fun x hx => by rw [filter_apply_pos _ _ (mem_filter.1 hx).2] #align finsupp.filter_eq_sum Finsupp.filter_eq_sum end CommMonoid section Group variable [AddGroup G] {p : α → Prop} {v v' : α →₀ G} @[simp] theorem subtypeDomain_neg : (-v).subtypeDomain p = -v.subtypeDomain p := ext fun _ => rfl #align finsupp.subtype_domain_neg Finsupp.subtypeDomain_neg @[simp] theorem subtypeDomain_sub : (v - v').subtypeDomain p = v.subtypeDomain p - v'.subtypeDomain p := ext fun _ => rfl #align finsupp.subtype_domain_sub Finsupp.subtypeDomain_sub @[simp] theorem single_neg (a : α) (b : G) : single a (-b) = -single a b := (singleAddHom a : G →+ _).map_neg b #align finsupp.single_neg Finsupp.single_neg @[simp] theorem single_sub (a : α) (b₁ b₂ : G) : single a (b₁ - b₂) = single a b₁ - single a b₂ := (singleAddHom a : G →+ _).map_sub b₁ b₂ #align finsupp.single_sub Finsupp.single_sub @[simp] theorem erase_neg (a : α) (f : α →₀ G) : erase a (-f) = -erase a f := (eraseAddHom a : (_ →₀ G) →+ _).map_neg f #align finsupp.erase_neg Finsupp.erase_neg @[simp] theorem erase_sub (a : α) (f₁ f₂ : α →₀ G) : erase a (f₁ - f₂) = erase a f₁ - erase a f₂ := (eraseAddHom a : (_ →₀ G) →+ _).map_sub f₁ f₂ #align finsupp.erase_sub Finsupp.erase_sub @[simp] theorem filter_neg (p : α → Prop) (f : α →₀ G) : filter p (-f) = -filter p f := (filterAddHom p : (_ →₀ G) →+ _).map_neg f #align finsupp.filter_neg Finsupp.filter_neg @[simp] theorem filter_sub (p : α → Prop) (f₁ f₂ : α →₀ G) : filter p (f₁ - f₂) = filter p f₁ - filter p f₂ := (filterAddHom p : (_ →₀ G) →+ _).map_sub f₁ f₂ #align finsupp.filter_sub Finsupp.filter_sub end Group end SubtypeDomain theorem mem_support_multiset_sum [AddCommMonoid M] {s : Multiset (α →₀ M)} (a : α) : a ∈ s.sum.support → ∃ f ∈ s, a ∈ (f : α →₀ M).support := Multiset.induction_on s (fun h => False.elim (by simp at h)) (by intro f s ih ha by_cases h : a ∈ f.support · exact ⟨f, Multiset.mem_cons_self _ _, h⟩ · simp only [Multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩ exact ⟨f', Multiset.mem_cons_of_mem h₀, h₁⟩) #align finsupp.mem_support_multiset_sum Finsupp.mem_support_multiset_sum theorem mem_support_finset_sum [AddCommMonoid M] {s : Finset ι} {h : ι → α →₀ M} (a : α) (ha : a ∈ (∑ c in s, h c).support) : ∃ c ∈ s, a ∈ (h c).support := let ⟨_, hf, hfa⟩ := mem_support_multiset_sum a ha let ⟨c, hc, Eq⟩ := Multiset.mem_map.1 hf ⟨c, hc, Eq.symm ▸ hfa⟩ #align finsupp.mem_support_finset_sum Finsupp.mem_support_finset_sum /-! ### Declarations about `curry` and `uncurry` -/ section CurryUncurry variable [AddCommMonoid M] [AddCommMonoid N] /-- Given a finitely supported function `f` from a product type `α × β` to `γ`, `curry f` is the "curried" finitely supported function from `α` to the type of finitely supported functions from `β` to `γ`. -/ protected def curry (f : α × β →₀ M) : α →₀ β →₀ M := f.sum fun p c => single p.1 (single p.2 c) #align finsupp.curry Finsupp.curry @[simp] theorem curry_apply (f : α × β →₀ M) (x : α) (y : β) : f.curry x y = f (x, y) := by classical have : ∀ b : α × β, single b.fst (single b.snd (f b)) x y = if b = (x, y) then f b else 0 := by rintro ⟨b₁, b₂⟩ simp [single_apply, ite_apply, Prod.ext_iff, ite_and] split_ifs <;> simp [single_apply, *] rw [Finsupp.curry, sum_apply, sum_apply, Finsupp.sum, Finset.sum_eq_single, this, if_pos rfl] · intro b _ b_ne rw [this b, if_neg b_ne] · intro hxy rw [this (x, y), if_pos rfl, not_mem_support_iff.mp hxy] #align finsupp.curry_apply Finsupp.curry_apply theorem sum_curry_index (f : α × β →₀ M) (g : α → β → M → N) (hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀ a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : (f.curry.sum fun a f => f.sum (g a)) = f.sum fun p c => g p.1 p.2 c := by rw [Finsupp.curry] trans · exact sum_sum_index (fun a => sum_zero_index) fun a b₀ b₁ => sum_add_index' (fun a => hg₀ _ _) fun c d₀ d₁ => hg₁ _ _ _ _ congr ; funext p c trans · exact sum_single_index sum_zero_index exact sum_single_index (hg₀ _ _) #align finsupp.sum_curry_index Finsupp.sum_curry_index /-- Given a finitely supported function `f` from `α` to the type of finitely supported functions from `β` to `M`, `uncurry f` is the "uncurried" finitely supported function from `α × β` to `M`. -/ protected def uncurry (f : α →₀ β →₀ M) : α × β →₀ M := f.sum fun a g => g.sum fun b c => single (a, b) c #align finsupp.uncurry Finsupp.uncurry /-- `finsuppProdEquiv` defines the `Equiv` between `((α × β) →₀ M)` and `(α →₀ (β →₀ M))` given by currying and uncurrying. -/ def finsuppProdEquiv : (α × β →₀ M) ≃ (α →₀ β →₀ M) where toFun := Finsupp.curry invFun := Finsupp.uncurry left_inv f := by rw [Finsupp.uncurry, sum_curry_index] · simp_rw [Prod.mk.eta, sum_single] · intros apply single_zero · intros apply single_add right_inv f := by simp only [Finsupp.curry, Finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall₃_true_iff, Prod.mk.eta, (single_sum _ _ _).symm, sum_single] #align finsupp.finsupp_prod_equiv Finsupp.finsuppProdEquiv theorem filter_curry (f : α × β →₀ M) (p : α → Prop) : (f.filter fun a : α × β => p a.1).curry = f.curry.filter p := by classical rw [Finsupp.curry, Finsupp.curry, Finsupp.sum, Finsupp.sum, filter_sum, support_filter, sum_filter] refine' Finset.sum_congr rfl _ rintro ⟨a₁, a₂⟩ _ dsimp only split_ifs with h · rw [filter_apply_pos, filter_single_of_pos] <;> exact h · rwa [filter_single_of_neg] #align finsupp.filter_curry Finsupp.filter_curry theorem support_curry [DecidableEq α] (f : α × β →₀ M) : f.curry.support ⊆ f.support.image Prod.fst := by rw [← Finset.bunionᵢ_singleton] refine' Finset.Subset.trans support_sum _ refine' Finset.bunionᵢ_mono fun a _ => support_single_subset #align finsupp.support_curry Finsupp.support_curry end CurryUncurry /-! ### Declarations about finitely supported functions whose support is a `sum` type -/ section Sum /-- `Finsupp.sumElim f g` maps `inl x` to `f x` and `inr y` to `g y`. -/ def sumElim {α β γ : Type _} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) : Sum α β →₀ γ := onFinset (by haveI := Classical.decEq α haveI := Classical.decEq β exact f.support.map ⟨_, Sum.inl_injective⟩ ∪ g.support.map ⟨_, Sum.inr_injective⟩) (Sum.elim f g) fun ab h => by cases' ab with a b <;> letI := Classical.decEq α <;> letI := Classical.decEq β <;> -- porting note: had to add these `DecidableEq` instances simp only [Sum.elim_inl, Sum.elim_inr] at h <;> simpa #align finsupp.sum_elim Finsupp.sumElim @[simp] theorem coe_sumElim {α β γ : Type _} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) : ⇑(sumElim f g) = Sum.elim f g := rfl #align finsupp.coe_sum_elim Finsupp.coe_sumElim theorem sumElim_apply {α β γ : Type _} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : Sum α β) : sumElim f g x = Sum.elim f g x := rfl #align finsupp.sum_elim_apply Finsupp.sumElim_apply theorem sumElim_inl {α β γ : Type _} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α) : sumElim f g (Sum.inl x) = f x := rfl #align finsupp.sum_elim_inl Finsupp.sumElim_inl theorem sumElim_inr {α β γ : Type _} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : β) : sumElim f g (Sum.inr x) = g x := rfl #align finsupp.sum_elim_inr Finsupp.sumElim_inr /-- The equivalence between `(α ⊕ β) →₀ γ` and `(α →₀ γ) × (β →₀ γ)`. This is the `Finsupp` version of `Equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps apply symm_apply] def sumFinsuppEquivProdFinsupp {α β γ : Type _} [Zero γ] : (Sum α β →₀ γ) ≃ (α →₀ γ) × (β →₀ γ) where toFun f := ⟨f.comapDomain Sum.inl (Sum.inl_injective.injOn _), f.comapDomain Sum.inr (Sum.inr_injective.injOn _)⟩ invFun fg := sumElim fg.1 fg.2 left_inv f := by ext ab cases' ab with a b <;> simp right_inv fg := by ext <;> simp #align finsupp.sum_finsupp_equiv_prod_finsupp Finsupp.sumFinsuppEquivProdFinsupp theorem fst_sumFinsuppEquivProdFinsupp {α β γ : Type _} [Zero γ] (f : Sum α β →₀ γ) (x : α) : (sumFinsuppEquivProdFinsupp f).1 x = f (Sum.inl x) := rfl #align finsupp.fst_sum_finsupp_equiv_prod_finsupp Finsupp.fst_sumFinsuppEquivProdFinsupp theorem snd_sumFinsuppEquivProdFinsupp {α β γ : Type _} [Zero γ] (f : Sum α β →₀ γ) (y : β) : (sumFinsuppEquivProdFinsupp f).2 y = f (Sum.inr y) := rfl #align finsupp.snd_sum_finsupp_equiv_prod_finsupp Finsupp.snd_sumFinsuppEquivProdFinsupp theorem sumFinsuppEquivProdFinsupp_symm_inl {α β γ : Type _} [Zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (x : α) : (sumFinsuppEquivProdFinsupp.symm fg) (Sum.inl x) = fg.1 x := rfl #align finsupp.sum_finsupp_equiv_prod_finsupp_symm_inl Finsupp.sumFinsuppEquivProdFinsupp_symm_inl theorem sumFinsuppEquivProdFinsupp_symm_inr {α β γ : Type _} [Zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (y : β) : (sumFinsuppEquivProdFinsupp.symm fg) (Sum.inr y) = fg.2 y := rfl #align finsupp.sum_finsupp_equiv_prod_finsupp_symm_inr Finsupp.sumFinsuppEquivProdFinsupp_symm_inr variable [AddMonoid M] /-- The additive equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`. This is the `Finsupp` version of `Equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps! apply symm_apply] def sumFinsuppAddEquivProdFinsupp {α β : Type _} : (Sum α β →₀ M) ≃+ (α →₀ M) × (β →₀ M) := { sumFinsuppEquivProdFinsupp with map_add' := by intros ext <;> simp only [Equiv.toFun_as_coe, Prod.fst_add, Prod.snd_add, add_apply, snd_sumFinsuppEquivProdFinsupp, fst_sumFinsuppEquivProdFinsupp] } #align finsupp.sum_finsupp_add_equiv_prod_finsupp Finsupp.sumFinsuppAddEquivProdFinsupp theorem fst_sumFinsuppAddEquivProdFinsupp {α β : Type _} (f : Sum α β →₀ M) (x : α) : (sumFinsuppAddEquivProdFinsupp f).1 x = f (Sum.inl x) := rfl #align finsupp.fst_sum_finsupp_add_equiv_prod_finsupp Finsupp.fst_sumFinsuppAddEquivProdFinsupp theorem snd_sumFinsuppAddEquivProdFinsupp {α β : Type _} (f : Sum α β →₀ M) (y : β) : (sumFinsuppAddEquivProdFinsupp f).2 y = f (Sum.inr y) := rfl #align finsupp.snd_sum_finsupp_add_equiv_prod_finsupp Finsupp.snd_sumFinsuppAddEquivProdFinsupp theorem sumFinsuppAddEquivProdFinsupp_symm_inl {α β : Type _} (fg : (α →₀ M) × (β →₀ M)) (x : α) : (sumFinsuppAddEquivProdFinsupp.symm fg) (Sum.inl x) = fg.1 x := rfl #align finsupp.sum_finsupp_add_equiv_prod_finsupp_symm_inl Finsupp.sumFinsuppAddEquivProdFinsupp_symm_inl theorem sumFinsuppAddEquivProdFinsupp_symm_inr {α β : Type _} (fg : (α →₀ M) × (β →₀ M)) (y : β) : (sumFinsuppAddEquivProdFinsupp.symm fg) (Sum.inr y) = fg.2 y := rfl #align finsupp.sum_finsupp_add_equiv_prod_finsupp_symm_inr Finsupp.sumFinsuppAddEquivProdFinsupp_symm_inr end Sum /-! ### Declarations about scalar multiplication -/ section variable [Zero M] [MonoidWithZero R] [MulActionWithZero R M] @[simp] theorem single_smul (a b : α) (f : α → M) (r : R) : single a r b • f a = single a (r • f b) b := by by_cases h : a = b <;> simp [h] #align finsupp.single_smul Finsupp.single_smul end section variable [Monoid G] [MulAction G α] [AddCommMonoid M] /-- Scalar multiplication acting on the domain. This is not an instance as it would conflict with the action on the range. See the `instance_diamonds` test for examples of such conflicts. -/ def comapSMul : SMul G (α →₀ M) where smul g := mapDomain ((· • ·) g) #align finsupp.comap_has_smul Finsupp.comapSMul attribute [local instance] comapSMul theorem comapSMul_def (g : G) (f : α →₀ M) : g • f = mapDomain ((· • ·) g) f := rfl #align finsupp.comap_smul_def Finsupp.comapSMul_def @[simp] theorem comapSMul_single (g : G) (a : α) (b : M) : g • single a b = single (g • a) b := mapDomain_single #align finsupp.comap_smul_single Finsupp.comapSMul_single /-- `Finsupp.comapSMul` is multiplicative -/ def comapMulAction : MulAction G (α →₀ M) where one_smul f := by rw [comapSMul_def, one_smul_eq_id, mapDomain_id] mul_smul g g' f := by rw [comapSMul_def, comapSMul_def, comapSMul_def, ← comp_smul_left, mapDomain_comp] #align finsupp.comap_mul_action Finsupp.comapMulAction attribute [local instance] comapMulAction /-- `Finsupp.comapSMul` is distributive -/ def comapDistribMulAction : DistribMulAction G (α →₀ M) where smul_zero g := by ext a simp only [comapSMul_def] simp smul_add g f f' := by ext simp only [comapSMul_def] simp [mapDomain_add] #align finsupp.comap_distrib_mul_action Finsupp.comapDistribMulAction end section variable [Group G] [MulAction G α] [AddCommMonoid M] attribute [local instance] comapSMul comapMulAction comapDistribMulAction /-- When `G` is a group, `Finsupp.comapSMul` acts by precomposition with the action of `g⁻¹`. -/ @[simp] theorem comapSMul_apply (g : G) (f : α →₀ M) (a : α) : (g • f) a = f (g⁻¹ • a) := by conv_lhs => rw [← smul_inv_smul g a] exact mapDomain_apply (MulAction.injective g) _ (g⁻¹ • a) #align finsupp.comap_smul_apply Finsupp.comapSMul_apply end section instance smulZeroClass [Zero M] [SMulZeroClass R M] : SMulZeroClass R (α →₀ M) where smul a v := v.mapRange ((· • ·) a) (smul_zero _) smul_zero a := by ext apply smul_zero #align finsupp.smul_zero_class Finsupp.smulZeroClass /-! Throughout this section, some `Monoid` and `Semiring` arguments are specified with `{}` instead of `[]`. See note [implicit instance arguments]. -/ @[simp] theorem coe_smul [AddMonoid M] [DistribSMul R M] (b : R) (v : α →₀ M) : ⇑(b • v) = b • ⇑v := rfl #align finsupp.coe_smul Finsupp.coe_smul theorem smul_apply [AddMonoid M] [DistribSMul R M] (b : R) (v : α →₀ M) (a : α) : (b • v) a = b • v a := rfl #align finsupp.smul_apply Finsupp.smul_apply theorem _root_.IsSMulRegular.finsupp [AddMonoid M] [DistribSMul R M] {k : R} (hk : IsSMulRegular M k) : IsSMulRegular (α →₀ M) k := fun _ _ h => ext fun i => hk (FunLike.congr_fun h i) #align is_smul_regular.finsupp IsSMulRegular.finsupp instance faithfulSMul [Nonempty α] [AddMonoid M] [DistribSMul R M] [FaithfulSMul R M] : FaithfulSMul R (α →₀ M) where eq_of_smul_eq_smul h := let ⟨a⟩ := ‹Nonempty α› eq_of_smul_eq_smul fun m : M => by simpa using FunLike.congr_fun (h (single a m)) a #align finsupp.faithful_smul Finsupp.faithfulSMul variable (α M) instance distribSMul [AddZeroClass M] [DistribSMul R M] : DistribSMul R (α →₀ M) where smul := (· • ·) smul_add _ _ _ := ext fun _ => smul_add _ _ _ smul_zero _ := ext fun _ => smul_zero _ #align finsupp.distrib_smul Finsupp.distribSMul instance distribMulAction [Monoid R] [AddMonoid M] [DistribMulAction R M] : DistribMulAction R (α →₀ M) := { Finsupp.distribSMul _ _ with one_smul := fun x => ext fun y => one_smul R (x y) mul_smul := fun r s x => ext fun y => mul_smul r s (x y) } #align finsupp.distrib_mul_action Finsupp.distribMulAction instance isScalarTower [Monoid R] [Monoid S] [AddMonoid M] [DistribMulAction R M] [DistribMulAction S M] [SMul R S] [IsScalarTower R S M] : IsScalarTower R S (α →₀ M) where smul_assoc _ _ _ := ext fun _ => smul_assoc _ _ _ #align finsuppp.is_scalar_tower Finsupp.isScalarTower instance smulCommClass [Monoid R] [Monoid S] [AddMonoid M] [DistribMulAction R M] [DistribMulAction S M] [SMulCommClass R S M] : SMulCommClass R S (α →₀ M) where smul_comm _ _ _ := ext fun _ => smul_comm _ _ _ #align finsupp.smul_comm_class Finsupp.smulCommClass instance isCentralScalar [Monoid R] [AddMonoid M] [DistribMulAction R M] [DistribMulAction Rᵐᵒᵖ M] [IsCentralScalar R M] : IsCentralScalar R (α →₀ M) where op_smul_eq_smul _ _ := ext fun _ => op_smul_eq_smul _ _ #align finsupp.is_central_scalar Finsupp.isCentralScalar instance module [Semiring R] [AddCommMonoid M] [Module R M] : Module R (α →₀ M) := { Finsupp.distribMulAction α M with smul := (· • ·) zero_smul := fun _ => ext fun _ => zero_smul _ _ add_smul := fun _ _ _ => ext fun _ => add_smul _ _ _ } #align finsupp.module Finsupp.module variable {α M} theorem support_smul {_ : Monoid R} [AddMonoid M] [DistribMulAction R M] {b : R} {g : α →₀ M} : (b • g).support ⊆ g.support := fun a => by simp only [smul_apply, mem_support_iff, Ne.def] exact mt fun h => h.symm ▸ smul_zero _ #align finsupp.support_smul Finsupp.support_smul @[simp] theorem support_smul_eq [Semiring R] [AddCommMonoid M] [Module R M] [NoZeroSMulDivisors R M] {b : R} (hb : b ≠ 0) {g : α →₀ M} : (b • g).support = g.support := Finset.ext fun a => by simp [Finsupp.smul_apply, hb] #align finsupp.support_smul_eq Finsupp.support_smul_eq section variable {p : α → Prop} @[simp] theorem filter_smul {_ : Monoid R} [AddMonoid M] [DistribMulAction R M] {b : R} {v : α →₀ M} : (b • v).filter p = b • v.filter p := FunLike.coe_injective <| Set.indicator_const_smul { x | p x } b v #align finsupp.filter_smul Finsupp.filter_smul end theorem mapDomain_smul {_ : Monoid R} [AddCommMonoid M] [DistribMulAction R M] {f : α → β} (b : R) (v : α →₀ M) : mapDomain f (b • v) = b • mapDomain f v := mapDomain_mapRange _ _ _ _ (smul_add b) #align finsupp.map_domain_smul Finsupp.mapDomain_smul @[simp] theorem smul_single {_ : Monoid R} [AddMonoid M] [DistribMulAction R M] (c : R) (a : α) (b : M) : c • Finsupp.single a b = Finsupp.single a (c • b) := mapRange_single #align finsupp.smul_single Finsupp.smul_single -- porting note: removed `simp` because `simpNF` can prove it. theorem smul_single' {_ : Semiring R} (c : R) (a : α) (b : R) : c • Finsupp.single a b = Finsupp.single a (c * b) := smul_single _ _ _ #align finsupp.smul_single' Finsupp.smul_single' theorem mapRange_smul {_ : Monoid R} [AddMonoid M] [DistribMulAction R M] [AddMonoid N] [DistribMulAction R N] {f : M → N} {hf : f 0 = 0} (c : R) (v : α →₀ M) (hsmul : ∀ x, f (c • x) = c • f x) : mapRange f hf (c • v) = c • mapRange f hf v := by erw [← mapRange_comp] have : f ∘ (· • ·) c = (· • ·) c ∘ f := funext hsmul simp_rw [this] apply mapRange_comp simp only [Function.comp_apply, smul_zero, hf] #align finsupp.map_range_smul Finsupp.mapRange_smul theorem smul_single_one [Semiring R] (a : α) (b : R) : b • single a (1 : R) = single a b := by rw [smul_single, smul_eq_mul, mul_one] #align finsupp.smul_single_one Finsupp.smul_single_one theorem comapDomain_smul [AddMonoid M] [Monoid R] [DistribMulAction R M] {f : α → β} (r : R) (v : β →₀ M) (hfv : Set.InjOn f (f ⁻¹' ↑v.support)) (hfrv : Set.InjOn f (f ⁻¹' ↑(r • v).support) := hfv.mono <| Set.preimage_mono <| Finset.coe_subset.mpr support_smul) : comapDomain f (r • v) hfrv = r • comapDomain f v hfv := by ext rfl #align finsupp.comap_domain_smul Finsupp.comapDomain_smul /-- A version of `Finsupp.comapDomain_smul` that's easier to use. -/ theorem comapDomain_smul_of_injective [AddMonoid M] [Monoid R] [DistribMulAction R M] {f : α → β} (hf : Function.Injective f) (r : R) (v : β →₀ M) : comapDomain f (r • v) (hf.injOn _) = r • comapDomain f v (hf.injOn _) := comapDomain_smul _ _ _ _ #align finsupp.comap_domain_smul_of_injective Finsupp.comapDomain_smul_of_injective end theorem sum_smul_index [Semiring R] [AddCommMonoid M] {g : α →₀ R} {b : R} {h : α → R → M} (h0 : ∀ i, h i 0 = 0) : (b • g).sum h = g.sum fun i a => h i (b * a) := Finsupp.sum_mapRange_index h0 #align finsupp.sum_smul_index Finsupp.sum_smul_index theorem sum_smul_index' [AddMonoid M] [DistribSMul R M] [AddCommMonoid N] {g : α →₀ M} {b : R} {h : α → M → N} (h0 : ∀ i, h i 0 = 0) : (b • g).sum h = g.sum fun i c => h i (b • c) := Finsupp.sum_mapRange_index h0 #align finsupp.sum_smul_index' Finsupp.sum_smul_index' /-- A version of `Finsupp.sum_smul_index'` for bundled additive maps. -/ theorem sum_smul_index_addMonoidHom [AddMonoid M] [AddCommMonoid N] [DistribSMul R M] {g : α →₀ M} {b : R} {h : α → M →+ N} : ((b • g).sum fun a => h a) = g.sum fun i c => h i (b • c) := sum_mapRange_index fun i => (h i).map_zero #align finsupp.sum_smul_index_add_monoid_hom Finsupp.sum_smul_index_addMonoidHom instance noZeroSMulDivisors [Semiring R] [AddCommMonoid M] [Module R M] {ι : Type _} [NoZeroSMulDivisors R M] : NoZeroSMulDivisors R (ι →₀ M) := ⟨fun h => or_iff_not_imp_left.mpr fun hc => Finsupp.ext fun i => (smul_eq_zero.mp (FunLike.ext_iff.mp h i)).resolve_left hc⟩ #align finsupp.no_zero_smul_divisors Finsupp.noZeroSMulDivisors section DistribMulActionHom variable [Semiring R] variable [AddCommMonoid M] [AddCommMonoid N] [DistribMulAction R M] [DistribMulAction R N] /-- `Finsupp.single` as a `DistribMulActionHom`. See also `Finsupp.lsingle` for the version as a linear map. -/ def DistribMulActionHom.single (a : α) : M →+[R] α →₀ M := { singleAddHom a with map_smul' := fun k m => by simp only show singleAddHom a (k • m) = k • singleAddHom a m change Finsupp.single a (k • m) = k • (Finsupp.single a m) -- porting note: because `singleAddHom_apply` is missing simp only [smul_single] } #align finsupp.distrib_mul_action_hom.single Finsupp.DistribMulActionHom.single theorem distribMulActionHom_ext {f g : (α →₀ M) →+[R] N} (h : ∀ (a : α) (m : M), f (single a m) = g (single a m)) : f = g := DistribMulActionHom.toAddMonoidHom_injective <| addHom_ext h #align finsupp.distrib_mul_action_hom_ext Finsupp.distribMulActionHom_ext /-- See note [partially-applied ext lemmas]. -/ @[ext] theorem distribMulActionHom_ext' {f g : (α →₀ M) →+[R] N} (h : ∀ a : α, f.comp (DistribMulActionHom.single a) = g.comp (DistribMulActionHom.single a)) : f = g := distribMulActionHom_ext fun a => DistribMulActionHom.congr_fun (h a) #align finsupp.distrib_mul_action_hom_ext' Finsupp.distribMulActionHom_ext' end DistribMulActionHom section variable [Zero R] /-- The `Finsupp` version of `Pi.unique`. -/ instance uniqueOfRight [Subsingleton R] : Unique (α →₀ R) := FunLike.coe_injective.unique #align finsupp.unique_of_right Finsupp.uniqueOfRight /-- The `Finsupp` version of `Pi.uniqueOfIsEmpty`. -/ instance uniqueOfLeft [IsEmpty α] : Unique (α →₀ R) := FunLike.coe_injective.unique #align finsupp.unique_of_left Finsupp.uniqueOfLeft end /-- Given an `AddCommMonoid M` and `s : Set α`, `restrictSupportEquiv s M` is the `Equiv` between the subtype of finitely supported functions with support contained in `s` and the type of finitely supported functions from `s`. -/ def restrictSupportEquiv (s : Set α) (M : Type _) [AddCommMonoid M] : { f : α →₀ M // ↑f.support ⊆ s } ≃ (s →₀ M) where toFun f := subtypeDomain (fun x => x ∈ s) f.1 invFun f := ⟨f.mapDomain Subtype.val, by classical refine' Set.Subset.trans (Finset.coe_subset.2 mapDomain_support) _ rw [Finset.coe_image, Set.image_subset_iff] exact fun x _ => x.2⟩ left_inv := by rintro ⟨f, hf⟩ apply Subtype.eq ext a dsimp only refine' by_cases (fun h : a ∈ Set.range (Subtype.val : s → α) => _) fun h => _ · rcases h with ⟨x, rfl⟩ rw [mapDomain_apply Subtype.val_injective, subtypeDomain_apply] · convert mapDomain_notin_range (subtypeDomain (fun x => x ∈ s) f) _ h rw [← not_mem_support_iff] refine' mt _ h exact fun ha => ⟨⟨a, hf ha⟩, rfl⟩ right_inv f := by ext ⟨a, ha⟩ dsimp only rw [subtypeDomain_apply, mapDomain_apply Subtype.val_injective] #align finsupp.restrict_support_equiv Finsupp.restrictSupportEquiv /-- Given `AddCommMonoid M` and `e : α ≃ β`, `domCongr e` is the corresponding `Equiv` between `α →₀ M` and `β →₀ M`. This is `Finsupp.equivCongrLeft` as an `AddEquiv`. -/ @[simps apply] protected def domCongr [AddCommMonoid M] (e : α ≃ β) : (α →₀ M) ≃+ (β →₀ M) where toFun := equivMapDomain e invFun := equivMapDomain e.symm left_inv v := by simp only [← equivMapDomain_trans, Equiv.self_trans_symm] exact equivMapDomain_refl _ right_inv := by intro v simp only [← equivMapDomain_trans, Equiv.symm_trans_self] exact equivMapDomain_refl _ map_add' a b := by simp only [equivMapDomain_eq_mapDomain]; exact mapDomain_add #align finsupp.dom_congr Finsupp.domCongr @[simp] theorem domCongr_refl [AddCommMonoid M] : Finsupp.domCongr (Equiv.refl α) = AddEquiv.refl (α →₀ M) := AddEquiv.ext fun _ => equivMapDomain_refl _ #align finsupp.dom_congr_refl Finsupp.domCongr_refl @[simp] theorem domCongr_symm [AddCommMonoid M] (e : α ≃ β) : (Finsupp.domCongr e).symm = (Finsupp.domCongr e.symm : (β →₀ M) ≃+ (α →₀ M)) := AddEquiv.ext fun _ => rfl #align finsupp.dom_congr_symm Finsupp.domCongr_symm @[simp] theorem domCongr_trans [AddCommMonoid M] (e : α ≃ β) (f : β ≃ γ) : (Finsupp.domCongr e).trans (Finsupp.domCongr f) = (Finsupp.domCongr (e.trans f) : (α →₀ M) ≃+ _) := AddEquiv.ext fun _ => (equivMapDomain_trans _ _ _).symm #align finsupp.dom_congr_trans Finsupp.domCongr_trans end Finsupp namespace Finsupp /-! ### Declarations about sigma types -/ section Sigma variable {αs : ι → Type _} [Zero M] (l : (Σi, αs i) →₀ M) /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `M` and an index element `i : ι`, `split l i` is the `i`th component of `l`, a finitely supported function from `as i` to `M`. This is the `Finsupp` version of `Sigma.curry`. -/ def split (i : ι) : αs i →₀ M := l.comapDomain (Sigma.mk i) fun _ _ _ _ hx => heq_iff_eq.1 (Sigma.mk.inj_iff.mp hx).2 -- porting note: it seems like Lean 4 never generated the `Sigma.mk.inj` lemma? #align finsupp.split Finsupp.split theorem split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ := by dsimp only [split] rw [comapDomain_apply] #align finsupp.split_apply Finsupp.split_apply /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`, `split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/ def splitSupport (l : (Σi, αs i) →₀ M) : Finset ι := haveI := Classical.decEq ι l.support.image Sigma.fst #align finsupp.split_support Finsupp.splitSupport theorem mem_splitSupport_iff_nonzero (i : ι) : i ∈ splitSupport l ↔ split l i ≠ 0 := by rw [splitSupport, @mem_image _ _ (Classical.decEq _), Ne.def, ← support_eq_empty, ← Ne.def, ← Finset.nonempty_iff_ne_empty, split, comapDomain, Finset.Nonempty] -- porting note: had to add the `Classical.decEq` instance manually simp only [exists_prop, Finset.mem_preimage, exists_and_right, exists_eq_right, mem_support_iff, Sigma.exists, Ne.def] #align finsupp.mem_split_support_iff_nonzero Finsupp.mem_splitSupport_iff_nonzero /-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a finitely supported function from the index type `ι` to `γ` given by composing `g i` with `split l i`. -/ def splitComp [Zero N] (g : ∀ i, (αs i →₀ M) → N) (hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ N where support := splitSupport l toFun i := g i (split l i) mem_support_toFun := by intro i rw [mem_splitSupport_iff_nonzero, not_iff_not, hg] #align finsupp.split_comp Finsupp.splitComp theorem sigma_support : l.support = l.splitSupport.sigma fun i => (l.split i).support := by simp only [Finset.ext_iff, splitSupport, split, comapDomain, @mem_image _ _ (Classical.decEq _), mem_preimage, Sigma.forall, mem_sigma] -- porting note: had to add the `Classical.decEq` instance manually tauto #align finsupp.sigma_support Finsupp.sigma_support theorem sigma_sum [AddCommMonoid N] (f : (Σi : ι, αs i) → M → N) : l.sum f = ∑ i in splitSupport l, (split l i).sum fun (a : αs i) b => f ⟨i, a⟩ b := by simp only [sum, sigma_support, sum_sigma, split_apply] #align finsupp.sigma_sum Finsupp.sigma_sum variable {η : Type _} [Fintype η] {ιs : η → Type _} [Zero α] /-- On a `Fintype η`, `Finsupp.split` is an equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `Finsupp` version of `Equiv.Pi_curry`. -/ noncomputable def sigmaFinsuppEquivPiFinsupp : ((Σj, ιs j) →₀ α) ≃ ∀ j, ιs j →₀ α where toFun := split invFun f := onFinset (Finset.univ.sigma fun j => (f j).support) (fun ji => f ji.1 ji.2) fun g hg => Finset.mem_sigma.mpr ⟨Finset.mem_univ _, mem_support_iff.mpr hg⟩ left_inv f := by ext simp [split] right_inv f := by ext simp [split] #align finsupp.sigma_finsupp_equiv_pi_finsupp Finsupp.sigmaFinsuppEquivPiFinsupp @[simp] theorem sigmaFinsuppEquivPiFinsupp_apply (f : (Σj, ιs j) →₀ α) (j i) : sigmaFinsuppEquivPiFinsupp f j i = f ⟨j, i⟩ := rfl #align finsupp.sigma_finsupp_equiv_pi_finsupp_apply Finsupp.sigmaFinsuppEquivPiFinsupp_apply /-- On a `Fintype η`, `Finsupp.split` is an additive equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `AddEquiv` version of `Finsupp.sigmaFinsuppEquivPiFinsupp`. -/ noncomputable def sigmaFinsuppAddEquivPiFinsupp {α : Type _} {ιs : η → Type _} [AddMonoid α] : ((Σj, ιs j) →₀ α) ≃+ ∀ j, ιs j →₀ α := { sigmaFinsuppEquivPiFinsupp with map_add' := fun f g => by ext simp } #align finsupp.sigma_finsupp_add_equiv_pi_finsupp Finsupp.sigmaFinsuppAddEquivPiFinsupp @[simp] theorem sigmaFinsuppAddEquivPiFinsupp_apply {α : Type _} {ιs : η → Type _} [AddMonoid α] (f : (Σj, ιs j) →₀ α) (j i) : sigmaFinsuppAddEquivPiFinsupp f j i = f ⟨j, i⟩ := rfl #align finsupp.sigma_finsupp_add_equiv_pi_finsupp_apply Finsupp.sigmaFinsuppAddEquivPiFinsupp_apply end Sigma /-! ### Meta declarations -/ /- porting note: meta code removed /-- Stringify a `Finsupp` as a sequence of `Finsupp.single` terms. Note this is `meta` as it has to choose some order for the terms. -/ unsafe instance (ι α : Type _) [Zero α] [Repr ι] [Repr α] : Repr (ι →₀ α) where repr f := if f.support.card = 0 then "0" else " + ".intercalate <| f.support.val.unquot.map fun i => "finsupp.single " ++ repr i ++ " " ++ repr (f i) -/ end Finsupp
[STATEMENT] lemma hcomp_in_hom\<^sub>W\<^sub>C [intro]: assumes "\<nu> \<star> \<mu> \<noteq> null" shows "\<guillemotleft>\<nu> \<star> \<mu> : dom \<nu> \<star> dom \<mu> \<Rightarrow> cod \<nu> \<star> cod \<mu>\<guillemotright>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<guillemotleft>\<nu> \<star> \<mu> : local.dom \<nu> \<star> local.dom \<mu> \<Rightarrow> cod \<nu> \<star> cod \<mu>\<guillemotright> [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: \<nu> \<star> \<mu> \<noteq> null goal (1 subgoal): 1. \<guillemotleft>\<nu> \<star> \<mu> : local.dom \<nu> \<star> local.dom \<mu> \<Rightarrow> cod \<nu> \<star> cod \<mu>\<guillemotright> [PROOF STEP] by auto
!---------------------------------------- subroutine computeorthogradient(msk,psi,dx,dy,nh,n,m,u,v) ! compute u,v= (-dpsi/dy,dpsi/dx) ! implicit none integer,intent(in):: n,m,nh integer*1,dimension(m,n) :: msk real*8,dimension(m,n) :: psi,u,v real*8::dx,dy !f2py intent(inplace)::psi,msk,u,v real*8::zdx,zdy integer:: i,j integer*1:: mm zdx = 1./dx zdy = 1./dy do j=2,m-1!nh-1,m-nh+1 do i=2,n-1!nh-1,n-nh+1 mm=msk(j,i)+msk(j,i+1) if(mm.eq.2)then u(j,i) = zdy*(psi(j-1,i)-psi(j,i)) else u(j,i) = 0. endif mm=msk(j,i)+msk(j+1,i) if(mm.eq.2)then v(j,i) = zdx*(psi(j,i)-psi(j,i-1)) else v(j,i) = 0. endif enddo enddo end subroutine !---------------------------------------- subroutine celltocorner(xr,xp,n,m) ! average 4 cell centers at upper right cell corner ! implicit none integer,intent(in):: n,m real*8,dimension(m,n) :: xr,xp !f2py intent(inplace)::xr,xp integer:: i,j do j=1,m-1 do i=1,n-1 xp(j,i)=0.25*(xr(j,i)+xr(j,i+1)+xr(j+1,i)+xr(j+1,i+1)) enddo enddo end subroutine !---------------------------------------- subroutine celltocornerbicubic(xr,xp,n,m) ! average 4x4 cell centers at upper right cell corner ! using the finite difference interpolation [-1,9,9,1]/16 in each direction implicit none integer,intent(in):: n,m real*8,dimension(m,n) :: xr,xp !f2py intent(inplace)::xr,xp real:: cff integer:: i,j,jj,k1,k2,k3,k4 real*8,dimension(n,4)::z cff = 1./12. do j=1,m k1 = mod(j-1,4)+1 do i=2,n-2 z(i,k1)=cff*(-xr(j,i-1)+7*(xr(j,i)+xr(j,i+1))-xr(j,i+2)) enddo if (j.ge.4)then k2 = mod(j-2,4)+1 k3 = mod(j-3,4)+1 k4 = mod(j-4,4)+1 jj = j-2 do i=2,n-2 xp(jj,i)=cff*(-z(i,k1)+7*(z(i,k2)+z(i,k3))-z(i,k4)) enddo endif enddo end subroutine !---------------------------------------- subroutine cornertocell(xp,xr,n,m) ! average 4 cell centers at upper right cell corner ! implicit none integer,intent(in):: n,m real*8,dimension(m,n) :: xr,xp !f2py intent(inplace)::xr,xp integer:: i,j do j=2,m do i=2,n xr(j,i)=0.25*(xp(j,i)+xp(j,i-1)+xp(j-1,i)+xp(j-1,i-1)) enddo enddo end subroutine !---------------------------------------- subroutine add_diffusion(msk,trac,dx,nh,Kdiff,dtrac,n,m) ! add a diffusion term (with homogenous Neumann BC) on trac ! implicit none integer,intent(in):: n,m,nh integer*1,dimension(m,n) :: msk real*8,dimension(m,n) :: trac,dtrac real*8,intent(in)::dx,Kdiff !f2py intent(inplace)::msk,trac,dtrac real*8::coef,dbl,dbr integer:: i,j integer*1:: mm,ml,mr coef = Kdiff/(dx*dx) do j=2,m-1 do i=2,n-1 if (msk(j,i).eq.1) then dtrac(j,i) = dtrac(j,i) + coef*( & + msk(j,i-1) * ( trac(j,i-1)-trac(j,i) ) & + msk(j,i+1) * ( trac(j,i+1)-trac(j,i) ) & + msk(j-1,i) * ( trac(j-1,i)-trac(j,i) ) & + msk(j+1,i) * ( trac(j+1,i)-trac(j,i) ) ) endif enddo enddo end subroutine !---------------------------------------- subroutine computewallshear(msk,x,y,total,dx,nh,m,n) ! compute y=b-A*x implicit none integer,intent(in):: n,m,nh integer*1,dimension(m,n) :: msk real*8,dimension(m,n) :: x real*8,dimension(m,n) :: y real*8::dx,total !f2py intent(inplace)::msk,x !f2py intent(inplace)::y !f2py intent(out)::total ! real*8,dimension(n,3) :: xo integer:: i,j integer*1::msku,mskv real*8::cff,u,v cff=1./(2*dx*dx) ! y(:,:)=0. total=0. y(1:nh,:)=0. do j=nh+1,m-nh+1 y(j,1:nh)=0. do i=nh+1,n-nh+1 y(j,i)=0. msku=msk(j,i-1)+msk(j,i) if (msku.eq.1)then if(msk(j,i).ne.0)then v=(x(j,i+1)+x(j-1,i+1))*cff y(j,i)=y(j,i)-v total=total-v else v=(x(j,i-3)+x(j-1,i-3))*cff y(j,i-1)=y(j,i-1)+v total=total+v endif endif mskv=msk(j-1,i)+msk(j,i) if (mskv.eq.1)then if(msk(j,i).ne.0)then u=(x(j+1,i)+x(j+1,i-1))*cff y(j,i)=y(j,i)+u total=total+u else u=(x(j-3,i)+x(j-3,i-1))*cff y(j-1,i)=y(j-1,i)-u total=total-u endif endif enddo enddo end subroutine !---------------------------------------- subroutine computenoslipsourceterm(msk,x,y,total,dx,dy,nh,m,n) ! compute y=b-A*x implicit none integer,intent(in):: n,m,nh integer*1,dimension(m,n) :: msk real*8,dimension(m,n) :: x real*8,dimension(m,n) :: y real*8::dx,dy,total !f2py intent(inplace)::msk,x !f2py intent(inplace)::y !f2py intent(out)::total ! real*8,dimension(n,3) :: xo integer:: i,j integer*1::msku,mskv real*8::cff,u,v cff=1./(2*dx*dy) ! y(:,:)=0. total=0. y(1:nh,:)=0. do j=nh+1,m-nh+1 y(j,1:nh)=0. do i=nh+1,n-nh+1 y(j,i)=0. msku=msk(j,i-1)+msk(j,i) if (msku.eq.1)then v=(x(j,i)+x(j-1,i)-x(j,i-2)-x(j-1,i-2))*cff if(msk(j,i).ne.0)then y(j,i)=y(j,i)-v total=total-v else y(j,i-1)=y(j,i-1)+v total=total+v endif endif mskv=msk(j-1,i)+msk(j,i) if (mskv.eq.1)then u=-(x(j,i)+x(j,i-1)-x(j-2,i)-x(j-2,i-1))*cff if(msk(j,i).ne.0)then y(j,i)=y(j,i)+u total=total+u else y(j-1,i)=y(j-1,i)-u total=total-u endif endif enddo enddo end subroutine !---------------------------------------- subroutine computenoslipsourceterm_regularized(msk,x,y,cu,cv,total,dx,nh,m,n) ! compute y=b-A*x implicit none integer,intent(in):: n,m,nh integer*1,dimension(m,n) :: msk real*8,dimension(m,n) :: x,cu,cv real*8,dimension(m,n) :: y real*8::dx,total !f2py intent(inplace)::msk,x,cu,cv !f2py intent(inplace)::y !f2py intent(out)::total ! real*8,dimension(n,3) :: xo integer:: i,j integer*1::msku,mskv real*8::cff,ul,ur,vl,vr,z cff=2./(dx*dx) ! y(:,:)=0. total=0. y(1:nh,:)=0. do j=nh+1,m-nh+1 y(j,1:nh)=0. do i=nh+1,n-nh+1 if(msk(j,i).ne.0)then vl = (x(j,i)-x(j,i-1))*cv(j,i-1)/(msk(j,i)+msk(j,i-1)) vr = (x(j,i)-x(j,i+1))*cv(j,i)/(msk(j,i)+msk(j,i+1)) ul = (x(j,i)-x(j-1,i))*cu(j-1,i)/(msk(j,i)+msk(j-1,i)) ur = (x(j,i)-x(j+1,i))*cu(j,i)/(msk(j,i)+msk(j+1,i)) z = -(vl+ur+vr+ul)*cff y(j,i) = z total=total+z else y(j,i)=0. endif enddo enddo end subroutine !---------------------------------------- subroutine add_torque(msk,buoy,dx,nh,gravity,domega,n,m) ! add torque db/dx to domega ! implicit none integer,intent(in):: n,m,nh integer*1,dimension(m,n) :: msk real*8,dimension(m,n) :: buoy,domega real*8,intent(in)::dx,gravity !f2py intent(inplace)::msk,buoy,domega real*8::coef,dbl,dbr,sum,z integer:: i,j,ii integer*1:: ml,mr,mm,one coef = 0.5*gravity/(dx) one = 1 do j=1+nh,m-nh ! sum=0. i=1+nh ml = max(one,msk(j,i)+ msk(j,i-1)) dbl = (buoy(j,i)*msk(j,i)+buoy(j,i-1)*msk(j,i-1))/ml do i=1+nh,n-nh mr = max(one,msk(j,i+1)+ msk(j,i)) dbr=(buoy(j,i+1)*msk(j,i+1)+buoy(j,i)*msk(j,i))/mr mm=(ml+mr) ! if(mm.gt.0) then ! z = (dbr-dbl)*(coef) ! else ! z=0. ! endif if (mm.eq.4) then ! domega(j,i) = domega(j,i) + (dbr-dbl)*(coef)*msk(j,i) domega(j,i) = domega(j,i) + (buoy(j,i+1)-buoy(j,i-1))*(coef)*msk(j,i) endif ! sum=sum+z ! if(mm.gt.0) domega(j,i) = domega(j,i)+(dbr-dbl)*(coef/mm) ml=mr dbl=dbr ! ii=ii+1 enddo ! write(*,*)"sum=",j,ii,sum enddo end subroutine
Section EqDec. Variable A:Type. Variable eq_dec: forall (x y:A), { x = y } + { x <> y }. Definition eq_dec_to_bool x y := if eq_dec x y then true else false. Lemma eq_dec_inv_true: forall x y, eq_dec_to_bool x y = true -> x = y. Proof. intros. unfold eq_dec_to_bool in *. destruct (eq_dec x y); auto; try inversion H. Qed. Lemma eq_dec_inv_false: forall x y, eq_dec_to_bool x y = false -> x <> y. Proof. intros. unfold eq_dec_to_bool in *. destruct (eq_dec x y); auto; try inversion H. Qed. Lemma eq_dec_rw: forall x y, { eq_dec_to_bool x y = true /\ x = y } + { eq_dec_to_bool x y = false /\ x <> y }. Proof. intros. unfold eq_dec_to_bool. destruct (eq_dec x y). - left; intuition. - right; intuition. Qed. Lemma eq_dec_refl: forall x, eq_dec_to_bool x x = true. Proof. intros. destruct eq_dec_rw with (x:=x) (y:=x) as [(?,?)|(?,?)]. - trivial. - contradiction H0. trivial. Qed. End EqDec.
```python %pylab inline pylab.rcParams['figure.figsize'] = (16.0, 8.0) ``` Populating the interactive namespace from numpy and matplotlib # Drawing from multivariate distributions ## Draws from the multivariate normal distribution Draws from a multivariate normal distribution $$ N(\mathbf{\mu}, \mathbf{\Sigma}) $$ can be generated by 1) Calculate the Cholesky decomposition $\mathbf{\Sigma} = \mathbf{R}^T\mathbf{R}$ ``` python from numpy.linalg import cholesky R = cholesky(Sigma) ``` 2) Generate standard normally distributed values $\mathbf{Z}$ 3) Evaluate $$ \mathbf{X} = \mathbf{\mu 1} + \mathbf{RZ}$$ ### Exercise 2.1 Draw 1000 samples from the bivariate distribution $$ N\left(\left( \begin{array}{c} 0.2 \\ -1.0 \end{array}\right), \left(\begin{array}{cc} 0.01 & -0.014 \\ -0.014 & 0.04 \end{array}\right) \right) $$ ```python draws = 1000 mu = array([0.2, -1.0]) Sigma = array([[0.01, -0.014],[-0.014, 0.04]]) R = linalg.cholesky(Sigma) Z = random.randn(2,draws) X = dot(mu[:,newaxis], ones((1, draws))) + dot(R, Z) ``` ```python figure() scatter(X[0,:], X[1,:], 100, edgecolor="none"); ``` Draws from the multivariate normal distribution can more easily generated using the built-in **scipy** functions ```python from scipy.stats import multivariate_normal dist = multivariate_normal(mu, Sigma) X = dist.rvs(size) ``` **Note** Scipy *rvs* functions return arrays of shape (number of draws, size of mean) ### Exercise 2.2 Repeat Exercise 2.1 with the built-in scipy function and compare the results. ```python from scipy.stats import multivariate_normal mu = array([0.2, -1.0]) Sigma = array([[0.01, -0.014],[-0.014, 0.04]]) dist = multivariate_normal(mu, Sigma) X = dist.rvs(1000) figure() scatter(X[:,0], X[:,1], 100, edgecolor="none"); ``` ## Draws using a copula function In many practical cases knowledge about the input quantities is available in terms of their individual distributions and a correlation coefficient. This is insufficient to assign a unique multivariate distribution. Therefore, a copula function can be defined $$ C(\mu_1,\ldots,\mu_N) = \mathbb{P} \left[ X_1\leq G_{X_1}^{-1}(\mu_1)\ldots,X_N\leq G_{X_N}^{-1}(\mu_N) \right] $$ ### Example copula functions * all input quantities are mutually independent $$ C(\mu_1,\ldots,\mu_N) = \prod_{k=1}^N \mu_k $$ * the input quantities are correlated with $\rho\equiv 1$ $$ C(\mu_1,\ldots,\mu_N) = \min_{k} \mu_k $$ * two input quantities are correlated with $\rho$ $$ C(\mu_1,\mu_2) = F_2(G_{X_1}^{-1}(\mu_1),G_{X_2}^{-1}(\mu_2),\rho) $$ The copula can be used to incorporate the correlation coefficient and the individual distributions $g_{X_i}$ to formally define a multivariate distribution. #### Example Input quantities $X_1,X_2$ with correlation coefficient $\rho$ and \begin{align} X_1 \sim & N(\mu, \sigma) \\ X_2 \sim & U(a, b) \end{align} Use bivariate normal copula function: 1) Draw from bivariate standard normal distribution $$ z \sim N\left(\mathbf{0}, \left(\begin{array}{cc} 1.0 & \rho \\ \rho & 1.0 \end{array}\right) \right) $$ 2) Evaluate cumulative distribution function of the copula \begin{align} \zeta_1 =& G_N(z_1) \\ \zeta_2 =& G_N(z_2) \end{align} 3) Evaluate inverse cumulative distribution functions \begin{align} x_1 =& G_{X_1}^{-1}(\zeta_1) \\ x_2 =& G_{X_2}^{-1}(\zeta_2) \end{align} ### Exercise 2.3 Consider the input quantities $X_1,X_2$ with * $X_1$ has best estimate 0.2 with uncertainty of 50% * $X_2$ has best estimate -1.0 with uncertainty of 20% * correlation between $X_1$ and $X_2$ is $\rho=-0.7$ Generate 1000 random draws using a bivariate normal copula function. ```python from scipy.stats import norm rho = -0.7 draws = 1000 mu = array([0, 0]) Sigma = array([[1, rho],[rho,1]]) dist = multivariate_normal(mu, Sigma) Z = dist.rvs(1000) zeta1 = norm.cdf(Z[:,0]) zeta2 = norm.cdf(Z[:,1]) X1 = norm.ppf(zeta1, loc=0.2, scale=0.1) X2 = norm.ppf(zeta2, loc=-1.0, scale=0.2) figure() scatter(X1, X2, 100, edgecolor="none"); ``` ### Exercise 2.4 Consider the input quantities $X_1, X_2$ with * $X_1$ has best estimate $x_1=2.4$ with expanded uncertainty $U=0.4 (k=2)$ under normality assumption * $X_2$ is located in $[-1.5, 1.5]$ * $X_1, X_2$ are correlated with $\rho = 0.4$ Draw 1000 samples from their joint probability distribution using a normal distribution copula function. ```python from scipy.stats import norm, uniform, multivariate_normal rho = 0.7 draws = 10000 copula = multivariate_normal(zeros(2), array([[1.0, rho],[rho, 1.0]])) z = copula.rvs(draws) xi1 = norm.cdf(z[:,0]) xi2 = norm.cdf(z[:,1]) X1dist = norm(loc=2.4, scale=0.2) X2dist = uniform(loc=-1.5, scale=3) x1 = X1dist.ppf(xi1) x2 = X2dist.ppf(xi2) figure(1) scatter(x1,x2,100,edgecolor="none") ``` ```python figure() subplot(121) hist(x1, bins=100, edgecolor="none") subplot(122) hist(x2, bins=100, edgecolor="none"); ``` ```python ```
------------------------------------------------------------------------ -- Functional semantics for an untyped λ-calculus with constants ------------------------------------------------------------------------ module Lambda.Closure.Functional where open import Category.Monad open import Category.Monad.Partiality as Partiality using (_⊥; never; OtherKind; other; steps) open import Codata.Musical.Notation open import Data.Empty using (⊥-elim) open import Data.List hiding (lookup) open import Data.Maybe hiding (_>>=_) import Data.Maybe.Categorical as Maybe open import Data.Nat open import Data.Product open import Data.Sum open import Data.Vec using (Vec; []; _∷_; lookup) open import Function import Level open import Relation.Binary using (module Preorder) open import Relation.Binary.PropositionalEquality as P using (_≡_) open import Relation.Nullary open import Relation.Nullary.Negation open Partiality._⊥ private open module E {A : Set} = Partiality.Equality (_≡_ {A = A}) open module R {A : Set} = Partiality.Reasoning (P.isEquivalence {A = A}) open import Lambda.Syntax open Closure Tm open import Lambda.VirtualMachine open Functional private module VM = Closure Code ------------------------------------------------------------------------ -- A monad with partiality and failure PF : RawMonad {f = Level.zero} (_⊥ ∘ Maybe) PF = Maybe.monadT Partiality.monad module PF where open RawMonad PF public fail : {A : Set} → Maybe A ⊥ fail = now nothing _>>=-cong_ : ∀ {k} {A B : Set} {x₁ x₂ : Maybe A ⊥} {f₁ f₂ : A → Maybe B ⊥} → Rel k x₁ x₂ → (∀ x → Rel k (f₁ x) (f₂ x)) → Rel k (x₁ >>= f₁) (x₂ >>= f₂) _>>=-cong_ {k} {f₁ = f₁} {f₂} x₁≈x₂ f₁≈f₂ = Partiality._>>=-cong_ x₁≈x₂ helper where helper : ∀ {x y} → x ≡ y → Rel k (maybe f₁ fail x) (maybe f₂ fail y) helper {x = nothing} P.refl = fail ∎ helper {x = just x} P.refl = f₁≈f₂ x associative : {A B C : Set} (x : Maybe A ⊥) (f : A → Maybe B ⊥) (g : B → Maybe C ⊥) → (x >>= f >>= g) ≅ (x >>= λ y → f y >>= g) associative x f g = (x >>= f >>= g) ≅⟨ Partiality.associative P.refl x _ _ ⟩ (x >>=′ λ y → maybe f fail y >>= g) ≅⟨ Partiality._>>=-cong_ (x ∎) helper ⟩ (x >>= λ y → f y >>= g) ∎ where open RawMonad Partiality.monad renaming (_>>=_ to _>>=′_) helper : ∀ {y₁ y₂} → y₁ ≡ y₂ → (maybe f fail y₁ >>= g) ≅ maybe (λ z → f z >>= g) fail y₂ helper {y₁ = nothing} P.refl = fail ∎ helper {y₁ = just y} P.refl = (f y >>= g) ∎ >>=-inversion-⇓ : ∀ {k} {A B : Set} x {f : A → Maybe B ⊥} {y} → (x>>=f⇓ : (x >>= f) ⇓[ k ] just y) → ∃ λ z → ∃₂ λ (x⇓ : x ⇓[ k ] just z) (fz⇓ : f z ⇓[ k ] just y) → steps x⇓ + steps fz⇓ ≡ steps x>>=f⇓ >>=-inversion-⇓ x {f} x>>=f⇓ with Partiality.>>=-inversion-⇓ {_∼A_ = _≡_} P.refl x x>>=f⇓ ... | (nothing , x↯ , now () , _) ... | (just z , x⇓ , fz⇓ , eq) = (z , x⇓ , fz⇓ , eq) >>=-inversion-⇑ : ∀ {k} {A B : Set} x {f : A → Maybe B ⊥} → (x >>= f) ⇑[ other k ] → ¬ ¬ (x ⇑[ other k ] ⊎ ∃ λ y → x ⇓[ other k ] just y × f y ⇑[ other k ]) >>=-inversion-⇑ {k} x {f} x>>=f⇑ = helper ⟨$⟩ Partiality.>>=-inversion-⇑ P.isEquivalence x x>>=f⇑ where open RawMonad ¬¬-Monad renaming (_<$>_ to _⟨$⟩_) helper : (_ ⊎ ∃ λ (y : Maybe _) → _) → _ helper (inj₁ x⇑ ) = inj₁ x⇑ helper (inj₂ (just y , x⇓,fy⇑) ) = inj₂ (y , x⇓,fy⇑) helper (inj₂ (nothing , x↯,now∼never)) = ⊥-elim (Partiality.now≉never (proj₂ x↯,now∼never)) ------------------------------------------------------------------------ -- A workaround for the limitations of guardedness module Workaround where data Maybe_⊥P : Set → Set₁ where fail : ∀ {A} → Maybe A ⊥P return : ∀ {A} (x : A) → Maybe A ⊥P later : ∀ {A} (x : ∞ (Maybe A ⊥P)) → Maybe A ⊥P _>>=_ : ∀ {A B} (x : Maybe A ⊥P) (f : A → Maybe B ⊥P) → Maybe B ⊥P private data Maybe_⊥W : Set → Set₁ where fail : ∀ {A} → Maybe A ⊥W return : ∀ {A} (x : A) → Maybe A ⊥W later : ∀ {A} (x : Maybe A ⊥P) → Maybe A ⊥W mutual _>>=W_ : ∀ {A B} → Maybe A ⊥W → (A → Maybe B ⊥P) → Maybe B ⊥W fail >>=W f = fail return x >>=W f = whnf (f x) later x >>=W f = later (x >>= f) whnf : ∀ {A} → Maybe A ⊥P → Maybe A ⊥W whnf fail = fail whnf (return x) = return x whnf (later x) = later (♭ x) whnf (x >>= f) = whnf x >>=W f mutual private ⟪_⟫W : ∀ {A} → Maybe A ⊥W → Maybe A ⊥ ⟪ fail ⟫W = PF.fail ⟪ return x ⟫W = PF.return x ⟪ later x ⟫W = later (♯ ⟪ x ⟫P) ⟪_⟫P : ∀ {A} → Maybe A ⊥P → Maybe A ⊥ ⟪ p ⟫P = ⟪ whnf p ⟫W -- The definitions above make sense. ⟪_⟫P is homomorphic with respect -- to fail, return, later and _>>=_. fail-hom : ∀ {A} → ⟪ fail {A = A} ⟫P ≅ PF.fail fail-hom = PF.fail ∎ return-hom : ∀ {A} (x : A) → ⟪ return x ⟫P ≅ PF.return x return-hom x = PF.return x ∎ later-hom : ∀ {A} (x : ∞ Maybe A ⊥P) → ⟪ later x ⟫P ≅ later (♯ ⟪ ♭ x ⟫P) later-hom x = later (♯ (⟪ ♭ x ⟫P ∎)) mutual private >>=-homW : ∀ {A B} (x : Maybe A ⊥W) (f : A → Maybe B ⊥P) → ⟪ x >>=W f ⟫W ≅ PF._>>=_ ⟪ x ⟫W (λ y → ⟪ f y ⟫P) >>=-homW fail f = PF.fail ∎ >>=-homW (return x) f = ⟪ f x ⟫P ∎ >>=-homW (later x) f = later (♯ >>=-hom x f) >>=-hom : ∀ {A B} (x : Maybe A ⊥P) (f : A → Maybe B ⊥P) → ⟪ x >>= f ⟫P ≅ PF._>>=_ ⟪ x ⟫P (λ y → ⟪ f y ⟫P) >>=-hom x f = >>=-homW (whnf x) f open Workaround hiding (_>>=_) ------------------------------------------------------------------------ -- Semantics infix 5 _∙_ -- Note that this definition gives us determinism "for free". mutual ⟦_⟧′ : ∀ {n} → Tm n → Env n → Maybe Value ⊥P ⟦ con i ⟧′ ρ = return (con i) ⟦ var x ⟧′ ρ = return (lookup ρ x) ⟦ ƛ t ⟧′ ρ = return (ƛ t ρ) ⟦ t₁ · t₂ ⟧′ ρ = ⟦ t₁ ⟧′ ρ >>= λ v₁ → ⟦ t₂ ⟧′ ρ >>= λ v₂ → v₁ ∙ v₂ where open Workaround _∙_ : Value → Value → Maybe Value ⊥P con i ∙ v₂ = fail ƛ t₁ ρ ∙ v₂ = later (♯ (⟦ t₁ ⟧′ (v₂ ∷ ρ))) ⟦_⟧ : ∀ {n} → Tm n → Env n → Maybe Value ⊥ ⟦ t ⟧ ρ = ⟪ ⟦ t ⟧′ ρ ⟫P ------------------------------------------------------------------------ -- Example Ω-loops : ⟦ Ω ⟧ [] ≈ never Ω-loops = later (♯ Ω-loops) ------------------------------------------------------------------------ -- Some lemmas open PF hiding (_>>=_) -- An abbreviation. infix 5 _⟦·⟧_ _⟦·⟧_ : Maybe Value ⊥ → Maybe Value ⊥ → Maybe Value ⊥ v₁ ⟦·⟧ v₂ = v₁ >>= λ v₁ → v₂ >>= λ v₂ → ⟪ v₁ ∙ v₂ ⟫P where open PF -- _⟦·⟧_ preserves equality. _⟦·⟧-cong_ : ∀ {k v₁₁ v₁₂ v₂₁ v₂₂} → Rel k v₁₁ v₂₁ → Rel k v₁₂ v₂₂ → Rel k (v₁₁ ⟦·⟧ v₁₂) (v₂₁ ⟦·⟧ v₂₂) v₁₁≈v₂₁ ⟦·⟧-cong v₁₂≈v₂₂ = v₁₁≈v₂₁ >>=-cong λ v₁ → v₁₂≈v₂₂ >>=-cong λ v₂ → ⟪ v₁ ∙ v₂ ⟫P ∎ -- The semantics of application is compositional (with respect to the -- syntactic equality which is used). ·-comp : ∀ {n} (t₁ t₂ : Tm n) {ρ} → ⟦ t₁ · t₂ ⟧ ρ ≅ ⟦ t₁ ⟧ ρ ⟦·⟧ ⟦ t₂ ⟧ ρ ·-comp t₁ t₂ {ρ} = ⟦ t₁ · t₂ ⟧ ρ ≅⟨ >>=-hom (⟦ t₁ ⟧′ ρ) _ ⟩ PF._>>=_ (⟦ t₁ ⟧ ρ) (λ v₁ → ⟪ Workaround._>>=_ (⟦ t₂ ⟧′ ρ) (λ v₂ → v₁ ∙ v₂) ⟫P) ≅⟨ ((⟦ t₁ ⟧ ρ ∎) >>=-cong λ _ → >>=-hom (⟦ t₂ ⟧′ ρ) _) ⟩ ⟦ t₁ ⟧ ρ ⟦·⟧ ⟦ t₂ ⟧ ρ ∎ open PF ------------------------------------------------------------------------ -- Compiler correctness module Correctness {k : OtherKind} where infix 4 _≈P_ _≈W_ infixr 2 _≡⟨_⟩W_ _≈⟨_⟩P_ _≈⟨_⟩W_ mutual data _≈P_ : Maybe VM.Value ⊥ → Maybe VM.Value ⊥ → Set where _≈⟨_⟩P_ : ∀ x {y z} (x≈y : x ≈P y) (y≅z : y ≅ z) → x ≈P z correct : ∀ {n} t {ρ : Env n} {c s} {k : Value → Maybe VM.Value ⊥} → (hyp : ∀ v → exec ⟨ c , val (comp-val v) ∷ s , comp-env ρ ⟩ ≈W k v) → exec ⟨ comp t c , s , comp-env ρ ⟩ ≈P (⟦ t ⟧ ρ >>= k) data _≈W_ : Maybe VM.Value ⊥ → Maybe VM.Value ⊥ → Set where ⌈_⌉ : ∀ {x y} (x≈y : Rel (other k) x y) → x ≈W y later : ∀ {x y} (x≈y : ♭ x ≈P ♭ y) → later x ≈W later y laterˡ : ∀ {x y} (x≈y : ♭ x ≈W y) → later x ≈W y _≡⟨_⟩W_ : ∀ x {y z} → x ≡ y → y ≈W z → x ≈W z _ ≡⟨ P.refl ⟩W y≈z = y≈z _≈⟨_⟩W_ : ∀ x {y z} → x ≈W y → y ≅ z → x ≈W z ._ ≈⟨ later x≈y ⟩W later y≅z = later (_ ≈⟨ x≈y ⟩P ♭ y≅z) ._ ≈⟨ laterˡ x≈y ⟩W y≅z = laterˡ (_ ≈⟨ x≈y ⟩W y≅z) _ ≈⟨ ⌈ x≈y ⌉ ⟩W y≅z = ⌈ trans x≈y (Partiality.≅⇒ y≅z) ⌉ where trans = Preorder.trans (Partiality.preorder P.isPreorder _) -- The relation _≈_ does not admit unrestricted use of transitivity -- in corecursive proofs, so I have formulated the correctness proof -- using a continuation. Note that the proof would perhaps be easier -- if the semantics was also formulated in continuation-passing -- style. mutual correctW : ∀ {n} t {ρ : Env n} {c s} {k : Value → Maybe VM.Value ⊥} → (∀ v → exec ⟨ c , val (comp-val v) ∷ s , comp-env ρ ⟩ ≈W k v) → exec ⟨ comp t c , s , comp-env ρ ⟩ ≈W (⟦ t ⟧ ρ >>= k) correctW (con i) {ρ} {c} {s} {k} hyp = laterˡ ( exec ⟨ c , val (Lambda.Syntax.Closure.con i) ∷ s , comp-env ρ ⟩ ≈⟨ hyp (con i) ⟩W k (con i) ∎) correctW (var x) {ρ} {c} {s} {k} hyp = laterˡ ( exec ⟨ c , val (lookup (comp-env ρ) x) ∷ s , comp-env ρ ⟩ ≡⟨ P.cong (λ v → exec ⟨ c , val v ∷ s , comp-env ρ ⟩) $ lookup-hom x ρ ⟩W exec ⟨ c , val (comp-val (lookup ρ x)) ∷ s , comp-env ρ ⟩ ≈⟨ hyp (lookup ρ x) ⟩W k (lookup ρ x) ∎) correctW (ƛ t) {ρ} {c} {s} {k} hyp = laterˡ ( exec ⟨ c , val (comp-val (ƛ t ρ)) ∷ s , comp-env ρ ⟩ ≈⟨ hyp (ƛ t ρ) ⟩W k (ƛ t ρ) ∎) correctW (t₁ · t₂) {ρ} {c} {s} {k} hyp = exec ⟨ comp t₁ (comp t₂ (app ∷ c)) , s , comp-env ρ ⟩ ≈⟨ correctW t₁ (λ v₁ → correctW t₂ (λ v₂ → ∙-correctW v₁ v₂ hyp)) ⟩W (⟦ t₁ ⟧ ρ >>= λ v₁ → ⟦ t₂ ⟧ ρ >>= λ v₂ → ⟪ v₁ ∙ v₂ ⟫P >>= k) ≅⟨ ((⟦ t₁ ⟧ ρ ∎) >>=-cong λ _ → sym $ associative (⟦ t₂ ⟧ ρ) _ _) ⟩ (⟦ t₁ ⟧ ρ >>= λ v₁ → (⟦ t₂ ⟧ ρ >>= λ v₂ → ⟪ v₁ ∙ v₂ ⟫P) >>= k) ≅⟨ sym $ associative (⟦ t₁ ⟧ ρ) _ _ ⟩ (⟦ t₁ ⟧ ρ ⟦·⟧ ⟦ t₂ ⟧ ρ >>= k) ≅⟨ sym (·-comp t₁ t₂ >>=-cong λ v → k v ∎) ⟩ (⟦ t₁ · t₂ ⟧ ρ >>= k) ∎ ∙-correctW : ∀ {n} v₁ v₂ {ρ : Env n} {c s} {k : Value → Maybe VM.Value ⊥} → (∀ v → exec ⟨ c , val (comp-val v) ∷ s , comp-env ρ ⟩ ≈W k v) → exec ⟨ app ∷ c , val (comp-val v₂) ∷ val (comp-val v₁) ∷ s , comp-env ρ ⟩ ≈W (⟪ v₁ ∙ v₂ ⟫P >>= k) ∙-correctW (con i) v₂ _ = ⌈ PF.fail ∎ ⌉ ∙-correctW (ƛ t₁ ρ₁) v₂ {ρ} {c} {s} {k} hyp = exec ⟨ app ∷ c , val (comp-val v₂) ∷ val (comp-val (ƛ t₁ ρ₁)) ∷ s , comp-env ρ ⟩ ≈⟨ later ( exec ⟨ comp t₁ [ ret ] , ret c (comp-env ρ) ∷ s , comp-env (v₂ ∷ ρ₁) ⟩ ≈⟨ correct t₁ (λ v → laterˡ (hyp v)) ⟩P (⟦ t₁ ⟧ (v₂ ∷ ρ₁) >>= k) ∎) ⟩W (⟪ ƛ t₁ ρ₁ ∙ v₂ ⟫P >>= k) ∎ whnf : ∀ {x y} → x ≈P y → x ≈W y whnf (x ≈⟨ x≈y ⟩P y≅z) = x ≈⟨ whnf x≈y ⟩W y≅z whnf (correct t hyp) = correctW t hyp mutual soundW : ∀ {x y} → x ≈W y → Rel (other k) x y soundW ⌈ x≈y ⌉ = x≈y soundW (later x≈y) = later (♯ soundP x≈y) soundW (laterˡ x≈y) = laterˡ (soundW x≈y) soundP : ∀ {x y} → x ≈P y → Rel (other k) x y soundP x≈y = soundW (whnf x≈y) -- Note that the equality that is used here is syntactic. correct : ∀ t → exec ⟨ comp t [] , [] , [] ⟩ ≈ (⟦ t ⟧ [] >>= λ v → PF.return (comp-val v)) correct t = soundP $ Correctness.correct t (λ v → ⌈ PF.return (comp-val v) ∎ ⌉) where open Correctness
theory prop_65 imports Main "$HIPSTER_HOME/IsaHipster" begin datatype Nat = Z | S "Nat" fun plus :: "Nat => Nat => Nat" where "plus (Z) y = y" | "plus (S z) y = S (plus z y)" fun lt :: "Nat => Nat => bool" where "lt x (Z) = False" | "lt (Z) (S z) = True" | "lt (S x2) (S z) = lt x2 z" (*hipster plus lt *) (*hipster lt*)(* lemma lemma_al [thy_expl]: "lt x2 x2 = False" by (hipster_induct_schemes lt.simps) lemma lemma_aal [thy_expl]: "lt x2 (S x2) = True" by (hipster_induct_schemes lt.simps) lemma lemma_abl [thy_expl]: "lt (S x2) x2 = False" by (hipster_induct_schemes lt.simps) *) lemma lemma_a [thy_expl]: "plus x2 Z = x2" by (hipster_induct_schemes plus.simps) lemma lemma_aa [thy_expl]: "plus (plus x2 y2) z2 = plus x2 (plus y2 z2)" by (hipster_induct_schemes plus.simps) lemma lemma_ab [thy_expl]: "plus x2 (S y2) = S (plus x2 y2)" by (hipster_induct_schemes plus.simps) lemma lemma_ac [thy_expl]: "plus x1 (plus y1 x1) = plus y1 (plus x1 x1)" by (hipster_induct_schemes plus.simps) lemma lemma_ad [thy_expl]: "plus x2 (plus y2 y2) = plus y2 (plus y2 x2)" by (hipster_induct_schemes plus.simps) lemma lemma_ae [thy_expl]: "plus x2 (S y2) = S (plus y2 x2)" by (hipster_induct_schemes plus.simps) lemma lemma_af [thy_expl]: "plus (S x2) y2 = S (plus y2 x2)" by (hipster_induct_schemes plus.simps) lemma lemma_ag [thy_expl]: "plus (plus x2 y2) (plus x2 z2) = plus (plus x2 z2) (plus x2 y2)" by (hipster_induct_schemes plus.simps) lemma lemma_ah [thy_expl]: "plus (plus x2 y2) (plus z2 x2) = plus (plus z2 x2) (plus x2 y2)" by (hipster_induct_schemes plus.simps) lemma lemma_ai [thy_expl]: "plus x2 (plus y2 z2) = plus y2 (plus z2 x2)" by (hipster_induct_schemes plus.simps) theorem x0 : "lt i (S (plus m i))" by (tactic \<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\<close>) end
[GOAL] j : WalkingPair ⊢ (fun j => WalkingPair.recOn j right left) ((fun j => WalkingPair.recOn j right left) j) = j [PROOFSTEP] cases j [GOAL] case left ⊢ (fun j => WalkingPair.recOn j right left) ((fun j => WalkingPair.recOn j right left) left) = left case right ⊢ (fun j => WalkingPair.recOn j right left) ((fun j => WalkingPair.recOn j right left) right) = right [PROOFSTEP] repeat rfl [GOAL] case left ⊢ (fun j => WalkingPair.recOn j right left) ((fun j => WalkingPair.recOn j right left) left) = left case right ⊢ (fun j => WalkingPair.recOn j right left) ((fun j => WalkingPair.recOn j right left) right) = right [PROOFSTEP] rfl [GOAL] case right ⊢ (fun j => WalkingPair.recOn j right left) ((fun j => WalkingPair.recOn j right left) right) = right [PROOFSTEP] rfl [GOAL] [PROOFSTEP] rfl [GOAL] j : WalkingPair ⊢ (fun j => WalkingPair.recOn j right left) ((fun j => WalkingPair.recOn j right left) j) = j [PROOFSTEP] cases j [GOAL] case left ⊢ (fun j => WalkingPair.recOn j right left) ((fun j => WalkingPair.recOn j right left) left) = left case right ⊢ (fun j => WalkingPair.recOn j right left) ((fun j => WalkingPair.recOn j right left) right) = right [PROOFSTEP] repeat rfl [GOAL] case left ⊢ (fun j => WalkingPair.recOn j right left) ((fun j => WalkingPair.recOn j right left) left) = left case right ⊢ (fun j => WalkingPair.recOn j right left) ((fun j => WalkingPair.recOn j right left) right) = right [PROOFSTEP] rfl [GOAL] case right ⊢ (fun j => WalkingPair.recOn j right left) ((fun j => WalkingPair.recOn j right left) right) = right [PROOFSTEP] rfl [GOAL] [PROOFSTEP] rfl [GOAL] j : WalkingPair ⊢ (fun b => Bool.recOn b right left) ((fun j => WalkingPair.recOn j true false) j) = j [PROOFSTEP] cases j [GOAL] case left ⊢ (fun b => Bool.recOn b right left) ((fun j => WalkingPair.recOn j true false) left) = left case right ⊢ (fun b => Bool.recOn b right left) ((fun j => WalkingPair.recOn j true false) right) = right [PROOFSTEP] repeat rfl [GOAL] case left ⊢ (fun b => Bool.recOn b right left) ((fun j => WalkingPair.recOn j true false) left) = left case right ⊢ (fun b => Bool.recOn b right left) ((fun j => WalkingPair.recOn j true false) right) = right [PROOFSTEP] rfl [GOAL] case right ⊢ (fun b => Bool.recOn b right left) ((fun j => WalkingPair.recOn j true false) right) = right [PROOFSTEP] rfl [GOAL] [PROOFSTEP] rfl [GOAL] b : Bool ⊢ (fun j => WalkingPair.recOn j true false) ((fun b => Bool.recOn b right left) b) = b [PROOFSTEP] cases b [GOAL] case false ⊢ (fun j => WalkingPair.recOn j true false) ((fun b => Bool.recOn b right left) false) = false case true ⊢ (fun j => WalkingPair.recOn j true false) ((fun b => Bool.recOn b right left) true) = true [PROOFSTEP] repeat rfl [GOAL] case false ⊢ (fun j => WalkingPair.recOn j true false) ((fun b => Bool.recOn b right left) false) = false case true ⊢ (fun j => WalkingPair.recOn j true false) ((fun b => Bool.recOn b right left) true) = true [PROOFSTEP] rfl [GOAL] case true ⊢ (fun j => WalkingPair.recOn j true false) ((fun b => Bool.recOn b right left) true) = true [PROOFSTEP] rfl [GOAL] [PROOFSTEP] rfl [GOAL] C : Type u inst✝ : Category.{v, u} C F G : Discrete WalkingPair ⥤ C f : F.obj { as := left } ⟶ G.obj { as := left } g : F.obj { as := right } ⟶ G.obj { as := right } x✝² x✝¹ : Discrete WalkingPair X Y : WalkingPair x✝ : { as := X } ⟶ { as := Y } u : { as := X }.as = { as := Y }.as ⊢ F.map { down := { down := u } } ≫ (fun j => Discrete.recOn j fun j => WalkingPair.casesOn j f g) { as := Y } = (fun j => Discrete.recOn j fun j => WalkingPair.casesOn j f g) { as := X } ≫ G.map { down := { down := u } } [PROOFSTEP] aesop_cat [GOAL] C : Type u inst✝ : Category.{v, u} C F G : Discrete WalkingPair ⥤ C f✝ : F.obj { as := left } ⟶ G.obj { as := left } g✝ : F.obj { as := right } ⟶ G.obj { as := right } f : F.obj { as := left } ≅ G.obj { as := left } g : F.obj { as := right } ≅ G.obj { as := right } X✝ Y✝ : Discrete WalkingPair x✝ : X✝ ⟶ Y✝ u : X✝.as = Y✝.as ⊢ F.map { down := { down := u } } ≫ ((fun j => Discrete.recOn j fun j => WalkingPair.casesOn j f g) Y✝).hom = ((fun j => Discrete.recOn j fun j => WalkingPair.casesOn j f g) X✝).hom ≫ G.map { down := { down := u } } [PROOFSTEP] aesop_cat [GOAL] C : Type u inst✝ : Category.{v, u} C X Y : C s : BinaryFan X Y lift : {T : C} → (T ⟶ X) → (T ⟶ Y) → (T ⟶ s.pt) hl₁ : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y), lift f g ≫ fst s = f hl₂ : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y), lift f g ≫ snd s = g uniq : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y) (m : T ⟶ s.pt), m ≫ fst s = f → m ≫ snd s = g → m = lift f g ⊢ ∀ (s_1 : Cone (pair X Y)) (j : Discrete WalkingPair), (fun t => lift (fst t) (snd t)) s_1 ≫ NatTrans.app s.π j = NatTrans.app s_1.π j [PROOFSTEP] rintro t (rfl | rfl) [GOAL] case mk.left C : Type u inst✝ : Category.{v, u} C X Y : C s : BinaryFan X Y lift : {T : C} → (T ⟶ X) → (T ⟶ Y) → (T ⟶ s.pt) hl₁ : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y), lift f g ≫ fst s = f hl₂ : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y), lift f g ≫ snd s = g uniq : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y) (m : T ⟶ s.pt), m ≫ fst s = f → m ≫ snd s = g → m = lift f g t : Cone (pair X Y) ⊢ (fun t => lift (fst t) (snd t)) t ≫ NatTrans.app s.π { as := left } = NatTrans.app t.π { as := left } [PROOFSTEP] exact hl₁ _ _ [GOAL] case mk.right C : Type u inst✝ : Category.{v, u} C X Y : C s : BinaryFan X Y lift : {T : C} → (T ⟶ X) → (T ⟶ Y) → (T ⟶ s.pt) hl₁ : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y), lift f g ≫ fst s = f hl₂ : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y), lift f g ≫ snd s = g uniq : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y) (m : T ⟶ s.pt), m ≫ fst s = f → m ≫ snd s = g → m = lift f g t : Cone (pair X Y) ⊢ (fun t => lift (fst t) (snd t)) t ≫ NatTrans.app s.π { as := right } = NatTrans.app t.π { as := right } [PROOFSTEP] exact hl₂ _ _ [GOAL] C : Type u inst✝ : Category.{v, u} C X Y : C s : BinaryCofan X Y desc : {T : C} → (X ⟶ T) → (Y ⟶ T) → (s.pt ⟶ T) hd₁ : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T), inl s ≫ desc f g = f hd₂ : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T), inr s ≫ desc f g = g uniq : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T) (m : s.pt ⟶ T), inl s ≫ m = f → inr s ≫ m = g → m = desc f g ⊢ ∀ (s_1 : Cocone (pair X Y)) (j : Discrete WalkingPair), NatTrans.app s.ι j ≫ (fun t => desc (inl t) (inr t)) s_1 = NatTrans.app s_1.ι j [PROOFSTEP] rintro t (rfl | rfl) [GOAL] case mk.left C : Type u inst✝ : Category.{v, u} C X Y : C s : BinaryCofan X Y desc : {T : C} → (X ⟶ T) → (Y ⟶ T) → (s.pt ⟶ T) hd₁ : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T), inl s ≫ desc f g = f hd₂ : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T), inr s ≫ desc f g = g uniq : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T) (m : s.pt ⟶ T), inl s ≫ m = f → inr s ≫ m = g → m = desc f g t : Cocone (pair X Y) ⊢ NatTrans.app s.ι { as := left } ≫ (fun t => desc (inl t) (inr t)) t = NatTrans.app t.ι { as := left } [PROOFSTEP] exact hd₁ _ _ [GOAL] case mk.right C : Type u inst✝ : Category.{v, u} C X Y : C s : BinaryCofan X Y desc : {T : C} → (X ⟶ T) → (Y ⟶ T) → (s.pt ⟶ T) hd₁ : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T), inl s ≫ desc f g = f hd₂ : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T), inr s ≫ desc f g = g uniq : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T) (m : s.pt ⟶ T), inl s ≫ m = f → inr s ≫ m = g → m = desc f g t : Cocone (pair X Y) ⊢ NatTrans.app s.ι { as := right } ≫ (fun t => desc (inl t) (inr t)) t = NatTrans.app t.ι { as := right } [PROOFSTEP] exact hd₂ _ _ [GOAL] C : Type u inst✝ : Category.{v, u} C X Y P : C π₁ : P ⟶ X π₂ : P ⟶ Y x✝ : Discrete WalkingPair j : WalkingPair ⊢ ((Functor.const (Discrete WalkingPair)).obj P).obj { as := j } ⟶ (pair X Y).obj { as := j } [PROOFSTEP] cases j [GOAL] case left C : Type u inst✝ : Category.{v, u} C X Y P : C π₁ : P ⟶ X π₂ : P ⟶ Y x✝ : Discrete WalkingPair ⊢ ((Functor.const (Discrete WalkingPair)).obj P).obj { as := left } ⟶ (pair X Y).obj { as := left } [PROOFSTEP] simpa [GOAL] case right C : Type u inst✝ : Category.{v, u} C X Y P : C π₁ : P ⟶ X π₂ : P ⟶ Y x✝ : Discrete WalkingPair ⊢ ((Functor.const (Discrete WalkingPair)).obj P).obj { as := right } ⟶ (pair X Y).obj { as := right } [PROOFSTEP] simpa [GOAL] C : Type u inst✝ : Category.{v, u} C X Y P : C ι₁ : X ⟶ P ι₂ : Y ⟶ P x✝ : Discrete WalkingPair j : WalkingPair ⊢ (pair X Y).obj { as := j } ⟶ ((Functor.const (Discrete WalkingPair)).obj P).obj { as := j } [PROOFSTEP] cases j [GOAL] case left C : Type u inst✝ : Category.{v, u} C X Y P : C ι₁ : X ⟶ P ι₂ : Y ⟶ P x✝ : Discrete WalkingPair ⊢ (pair X Y).obj { as := left } ⟶ ((Functor.const (Discrete WalkingPair)).obj P).obj { as := left } [PROOFSTEP] simpa [GOAL] case right C : Type u inst✝ : Category.{v, u} C X Y P : C ι₁ : X ⟶ P ι₂ : Y ⟶ P x✝ : Discrete WalkingPair ⊢ (pair X Y).obj { as := right } ⟶ ((Functor.const (Discrete WalkingPair)).obj P).obj { as := right } [PROOFSTEP] simpa [GOAL] C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C c : BinaryFan X Y j : Discrete WalkingPair ⊢ NatTrans.app c.π j = (Iso.refl c.pt).hom ≫ NatTrans.app (BinaryFan.mk (BinaryFan.fst c) (BinaryFan.snd c)).π j [PROOFSTEP] cases' j with l [GOAL] case mk C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C c : BinaryFan X Y l : WalkingPair ⊢ NatTrans.app c.π { as := l } = (Iso.refl c.pt).hom ≫ NatTrans.app (BinaryFan.mk (BinaryFan.fst c) (BinaryFan.snd c)).π { as := l } [PROOFSTEP] cases l [GOAL] case mk.left C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C c : BinaryFan X Y ⊢ NatTrans.app c.π { as := left } = (Iso.refl c.pt).hom ≫ NatTrans.app (BinaryFan.mk (BinaryFan.fst c) (BinaryFan.snd c)).π { as := left } case mk.right C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C c : BinaryFan X Y ⊢ NatTrans.app c.π { as := right } = (Iso.refl c.pt).hom ≫ NatTrans.app (BinaryFan.mk (BinaryFan.fst c) (BinaryFan.snd c)).π { as := right } [PROOFSTEP] repeat simp [GOAL] case mk.left C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C c : BinaryFan X Y ⊢ NatTrans.app c.π { as := left } = (Iso.refl c.pt).hom ≫ NatTrans.app (BinaryFan.mk (BinaryFan.fst c) (BinaryFan.snd c)).π { as := left } case mk.right C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C c : BinaryFan X Y ⊢ NatTrans.app c.π { as := right } = (Iso.refl c.pt).hom ≫ NatTrans.app (BinaryFan.mk (BinaryFan.fst c) (BinaryFan.snd c)).π { as := right } [PROOFSTEP] simp [GOAL] case mk.right C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C c : BinaryFan X Y ⊢ NatTrans.app c.π { as := right } = (Iso.refl c.pt).hom ≫ NatTrans.app (BinaryFan.mk (BinaryFan.fst c) (BinaryFan.snd c)).π { as := right } [PROOFSTEP] simp [GOAL] [PROOFSTEP] simp [GOAL] C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C c : BinaryCofan X Y j : Discrete WalkingPair ⊢ NatTrans.app c.ι j ≫ (Iso.refl c.pt).hom = NatTrans.app (BinaryCofan.mk (BinaryCofan.inl c) (BinaryCofan.inr c)).ι j [PROOFSTEP] cases' j with l [GOAL] case mk C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C c : BinaryCofan X Y l : WalkingPair ⊢ NatTrans.app c.ι { as := l } ≫ (Iso.refl c.pt).hom = NatTrans.app (BinaryCofan.mk (BinaryCofan.inl c) (BinaryCofan.inr c)).ι { as := l } [PROOFSTEP] cases l [GOAL] case mk.left C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C c : BinaryCofan X Y ⊢ NatTrans.app c.ι { as := left } ≫ (Iso.refl c.pt).hom = NatTrans.app (BinaryCofan.mk (BinaryCofan.inl c) (BinaryCofan.inr c)).ι { as := left } case mk.right C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C c : BinaryCofan X Y ⊢ NatTrans.app c.ι { as := right } ≫ (Iso.refl c.pt).hom = NatTrans.app (BinaryCofan.mk (BinaryCofan.inl c) (BinaryCofan.inr c)).ι { as := right } [PROOFSTEP] repeat simp [GOAL] case mk.left C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C c : BinaryCofan X Y ⊢ NatTrans.app c.ι { as := left } ≫ (Iso.refl c.pt).hom = NatTrans.app (BinaryCofan.mk (BinaryCofan.inl c) (BinaryCofan.inr c)).ι { as := left } case mk.right C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C c : BinaryCofan X Y ⊢ NatTrans.app c.ι { as := right } ≫ (Iso.refl c.pt).hom = NatTrans.app (BinaryCofan.mk (BinaryCofan.inl c) (BinaryCofan.inr c)).ι { as := right } [PROOFSTEP] simp [GOAL] case mk.right C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C c : BinaryCofan X Y ⊢ NatTrans.app c.ι { as := right } ≫ (Iso.refl c.pt).hom = NatTrans.app (BinaryCofan.mk (BinaryCofan.inl c) (BinaryCofan.inr c)).ι { as := right } [PROOFSTEP] simp [GOAL] [PROOFSTEP] simp [GOAL] C : Type u inst✝ : Category.{v, u} C X Y W : C fst : W ⟶ X snd : W ⟶ Y lift : (s : BinaryFan X Y) → s.pt ⟶ W fac_left : ∀ (s : BinaryFan X Y), lift s ≫ fst = CategoryTheory.Limits.BinaryFan.fst s fac_right : ∀ (s : BinaryFan X Y), lift s ≫ snd = CategoryTheory.Limits.BinaryFan.snd s uniq : ∀ (s : BinaryFan X Y) (m : s.pt ⟶ W), m ≫ fst = CategoryTheory.Limits.BinaryFan.fst s → m ≫ snd = CategoryTheory.Limits.BinaryFan.snd s → m = lift s s : Cone (pair X Y) j : Discrete WalkingPair ⊢ lift s ≫ NatTrans.app (mk fst snd).π j = NatTrans.app s.π j [PROOFSTEP] rcases j with ⟨⟨⟩⟩ [GOAL] case mk.left C : Type u inst✝ : Category.{v, u} C X Y W : C fst : W ⟶ X snd : W ⟶ Y lift : (s : BinaryFan X Y) → s.pt ⟶ W fac_left : ∀ (s : BinaryFan X Y), lift s ≫ fst = CategoryTheory.Limits.BinaryFan.fst s fac_right : ∀ (s : BinaryFan X Y), lift s ≫ snd = CategoryTheory.Limits.BinaryFan.snd s uniq : ∀ (s : BinaryFan X Y) (m : s.pt ⟶ W), m ≫ fst = CategoryTheory.Limits.BinaryFan.fst s → m ≫ snd = CategoryTheory.Limits.BinaryFan.snd s → m = lift s s : Cone (pair X Y) ⊢ lift s ≫ NatTrans.app (mk fst snd).π { as := left } = NatTrans.app s.π { as := left } case mk.right C : Type u inst✝ : Category.{v, u} C X Y W : C fst : W ⟶ X snd : W ⟶ Y lift : (s : BinaryFan X Y) → s.pt ⟶ W fac_left : ∀ (s : BinaryFan X Y), lift s ≫ fst = CategoryTheory.Limits.BinaryFan.fst s fac_right : ∀ (s : BinaryFan X Y), lift s ≫ snd = CategoryTheory.Limits.BinaryFan.snd s uniq : ∀ (s : BinaryFan X Y) (m : s.pt ⟶ W), m ≫ fst = CategoryTheory.Limits.BinaryFan.fst s → m ≫ snd = CategoryTheory.Limits.BinaryFan.snd s → m = lift s s : Cone (pair X Y) ⊢ lift s ≫ NatTrans.app (mk fst snd).π { as := right } = NatTrans.app s.π { as := right } [PROOFSTEP] exacts [fac_left s, fac_right s] [GOAL] C : Type u inst✝ : Category.{v, u} C X Y W : C inl : X ⟶ W inr : Y ⟶ W desc : (s : BinaryCofan X Y) → W ⟶ s.pt fac_left : ∀ (s : BinaryCofan X Y), inl ≫ desc s = CategoryTheory.Limits.BinaryCofan.inl s fac_right : ∀ (s : BinaryCofan X Y), inr ≫ desc s = CategoryTheory.Limits.BinaryCofan.inr s uniq : ∀ (s : BinaryCofan X Y) (m : W ⟶ s.pt), inl ≫ m = CategoryTheory.Limits.BinaryCofan.inl s → inr ≫ m = CategoryTheory.Limits.BinaryCofan.inr s → m = desc s s : Cocone (pair X Y) j : Discrete WalkingPair ⊢ NatTrans.app (mk inl inr).ι j ≫ desc s = NatTrans.app s.ι j [PROOFSTEP] rcases j with ⟨⟨⟩⟩ [GOAL] case mk.left C : Type u inst✝ : Category.{v, u} C X Y W : C inl : X ⟶ W inr : Y ⟶ W desc : (s : BinaryCofan X Y) → W ⟶ s.pt fac_left : ∀ (s : BinaryCofan X Y), inl ≫ desc s = CategoryTheory.Limits.BinaryCofan.inl s fac_right : ∀ (s : BinaryCofan X Y), inr ≫ desc s = CategoryTheory.Limits.BinaryCofan.inr s uniq : ∀ (s : BinaryCofan X Y) (m : W ⟶ s.pt), inl ≫ m = CategoryTheory.Limits.BinaryCofan.inl s → inr ≫ m = CategoryTheory.Limits.BinaryCofan.inr s → m = desc s s : Cocone (pair X Y) ⊢ NatTrans.app (mk inl inr).ι { as := left } ≫ desc s = NatTrans.app s.ι { as := left } case mk.right C : Type u inst✝ : Category.{v, u} C X Y W : C inl : X ⟶ W inr : Y ⟶ W desc : (s : BinaryCofan X Y) → W ⟶ s.pt fac_left : ∀ (s : BinaryCofan X Y), inl ≫ desc s = CategoryTheory.Limits.BinaryCofan.inl s fac_right : ∀ (s : BinaryCofan X Y), inr ≫ desc s = CategoryTheory.Limits.BinaryCofan.inr s uniq : ∀ (s : BinaryCofan X Y) (m : W ⟶ s.pt), inl ≫ m = CategoryTheory.Limits.BinaryCofan.inl s → inr ≫ m = CategoryTheory.Limits.BinaryCofan.inr s → m = desc s s : Cocone (pair X Y) ⊢ NatTrans.app (mk inl inr).ι { as := right } ≫ desc s = NatTrans.app s.ι { as := right } [PROOFSTEP] exacts [fac_left s, fac_right s] [GOAL] C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsTerminal Y c : BinaryFan X Y ⊢ Nonempty (IsLimit c) ↔ IsIso (fst c) [PROOFSTEP] constructor [GOAL] case mp C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsTerminal Y c : BinaryFan X Y ⊢ Nonempty (IsLimit c) → IsIso (fst c) [PROOFSTEP] rintro ⟨H⟩ [GOAL] case mp.intro C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsTerminal Y c : BinaryFan X Y H : IsLimit c ⊢ IsIso (fst c) [PROOFSTEP] obtain ⟨l, hl, -⟩ := BinaryFan.IsLimit.lift' H (𝟙 X) (h.from X) [GOAL] case mp.intro.mk.intro C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsTerminal Y c : BinaryFan X Y H : IsLimit c l : X ⟶ c.pt hl : l ≫ fst c = 𝟙 X ⊢ IsIso (fst c) [PROOFSTEP] exact ⟨⟨l, BinaryFan.IsLimit.hom_ext H (by simpa [hl, -Category.comp_id] using Category.comp_id _) (h.hom_ext _ _), hl⟩⟩ [GOAL] C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsTerminal Y c : BinaryFan X Y H : IsLimit c l : X ⟶ c.pt hl : l ≫ fst c = 𝟙 X ⊢ (fst c ≫ l) ≫ fst c = 𝟙 (((Functor.const (Discrete WalkingPair)).obj c.pt).obj { as := left }) ≫ fst c [PROOFSTEP] simpa [hl, -Category.comp_id] using Category.comp_id _ [GOAL] case mpr C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsTerminal Y c : BinaryFan X Y ⊢ IsIso (fst c) → Nonempty (IsLimit c) [PROOFSTEP] intro [GOAL] case mpr C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsTerminal Y c : BinaryFan X Y a✝ : IsIso (fst c) ⊢ Nonempty (IsLimit c) [PROOFSTEP] exact ⟨BinaryFan.IsLimit.mk _ (fun f _ => f ≫ inv c.fst) (fun _ _ => by simp) (fun _ _ => h.hom_ext _ _) fun _ _ _ e _ => by simp [← e]⟩ [GOAL] C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsTerminal Y c : BinaryFan X Y a✝ : IsIso (fst c) T✝ : C x✝¹ : T✝ ⟶ X x✝ : T✝ ⟶ Y ⊢ (fun {T} f x => f ≫ inv (fst c)) x✝¹ x✝ ≫ fst c = x✝¹ [PROOFSTEP] simp [GOAL] C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsTerminal Y c : BinaryFan X Y a✝ : IsIso (fst c) T✝ : C x✝³ : T✝ ⟶ X x✝² : T✝ ⟶ Y x✝¹ : T✝ ⟶ c.pt e : x✝¹ ≫ fst c = x✝³ x✝ : x✝¹ ≫ snd c = x✝² ⊢ x✝¹ = (fun {T} f x => f ≫ inv (fst c)) x✝³ x✝² [PROOFSTEP] simp [← e] [GOAL] C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsTerminal X c : BinaryFan X Y ⊢ Nonempty (IsLimit c) ↔ IsIso (snd c) [PROOFSTEP] refine' Iff.trans _ (BinaryFan.isLimit_iff_isIso_fst h (BinaryFan.mk c.snd c.fst)) [GOAL] C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsTerminal X c : BinaryFan X Y ⊢ Nonempty (IsLimit c) ↔ Nonempty (IsLimit (mk (snd c) (fst c))) [PROOFSTEP] exact ⟨fun h => ⟨BinaryFan.isLimitFlip h.some⟩, fun h => ⟨(BinaryFan.isLimitFlip h.some).ofIsoLimit (isoBinaryFanMk c).symm⟩⟩ [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryFan X Y f : X ⟶ X' inst✝ : IsIso f h : IsLimit c ⊢ IsLimit (mk (fst c ≫ f) (snd c)) [PROOFSTEP] fapply BinaryFan.isLimitMk [GOAL] case lift C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryFan X Y f : X ⟶ X' inst✝ : IsIso f h : IsLimit c ⊢ (s : BinaryFan X' ((pair X Y).obj { as := right })) → s.pt ⟶ ((Functor.const (Discrete WalkingPair)).obj c.pt).obj { as := left } [PROOFSTEP] exact fun s => h.lift (BinaryFan.mk (s.fst ≫ inv f) s.snd) [GOAL] case fac_left C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryFan X Y f : X ⟶ X' inst✝ : IsIso f h : IsLimit c ⊢ ∀ (s : BinaryFan X' ((pair X Y).obj { as := right })), IsLimit.lift h (mk (fst s ≫ inv f) (snd s)) ≫ fst c ≫ f = fst s [PROOFSTEP] intro s [GOAL] case fac_left C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryFan X Y f : X ⟶ X' inst✝ : IsIso f h : IsLimit c s : BinaryFan X' ((pair X Y).obj { as := right }) ⊢ IsLimit.lift h (mk (fst s ≫ inv f) (snd s)) ≫ fst c ≫ f = fst s [PROOFSTEP] simp only [Category.comp_id, BinaryFan.π_app_left, IsIso.inv_hom_id, BinaryFan.mk_fst, IsLimit.fac_assoc, eq_self_iff_true, Category.assoc] [GOAL] case fac_right C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryFan X Y f : X ⟶ X' inst✝ : IsIso f h : IsLimit c ⊢ ∀ (s : BinaryFan X' ((pair X Y).obj { as := right })), IsLimit.lift h (mk (fst s ≫ inv f) (snd s)) ≫ snd c = snd s [PROOFSTEP] intro s [GOAL] case fac_right C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryFan X Y f : X ⟶ X' inst✝ : IsIso f h : IsLimit c s : BinaryFan X' ((pair X Y).obj { as := right }) ⊢ IsLimit.lift h (mk (fst s ≫ inv f) (snd s)) ≫ snd c = snd s [PROOFSTEP] simp only [BinaryFan.π_app_right, BinaryFan.mk_snd, eq_self_iff_true, IsLimit.fac] [GOAL] case uniq C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryFan X Y f : X ⟶ X' inst✝ : IsIso f h : IsLimit c ⊢ ∀ (s : BinaryFan X' ((pair X Y).obj { as := right })) (m : s.pt ⟶ ((Functor.const (Discrete WalkingPair)).obj c.pt).obj { as := left }), m ≫ fst c ≫ f = fst s → m ≫ snd c = snd s → m = IsLimit.lift h (mk (fst s ≫ inv f) (snd s)) [PROOFSTEP] intro s m e₁ e₂ [GOAL] case uniq C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryFan X Y f : X ⟶ X' inst✝ : IsIso f h : IsLimit c s : BinaryFan X' ((pair X Y).obj { as := right }) m : s.pt ⟶ ((Functor.const (Discrete WalkingPair)).obj c.pt).obj { as := left } e₁ : m ≫ fst c ≫ f = fst s e₂ : m ≫ snd c = snd s ⊢ m = IsLimit.lift h (mk (fst s ≫ inv f) (snd s)) [PROOFSTEP] apply BinaryFan.IsLimit.hom_ext h [GOAL] case uniq.h₁ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryFan X Y f : X ⟶ X' inst✝ : IsIso f h : IsLimit c s : BinaryFan X' ((pair X Y).obj { as := right }) m : s.pt ⟶ ((Functor.const (Discrete WalkingPair)).obj c.pt).obj { as := left } e₁ : m ≫ fst c ≫ f = fst s e₂ : m ≫ snd c = snd s ⊢ m ≫ fst c = IsLimit.lift h (mk (fst s ≫ inv f) (snd s)) ≫ fst c [PROOFSTEP] simpa only [BinaryFan.π_app_left, BinaryFan.mk_fst, Category.assoc, IsLimit.fac, IsIso.eq_comp_inv] [GOAL] case uniq.h₂ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryFan X Y f : X ⟶ X' inst✝ : IsIso f h : IsLimit c s : BinaryFan X' ((pair X Y).obj { as := right }) m : s.pt ⟶ ((Functor.const (Discrete WalkingPair)).obj c.pt).obj { as := left } e₁ : m ≫ fst c ≫ f = fst s e₂ : m ≫ snd c = snd s ⊢ m ≫ snd c = IsLimit.lift h (mk (fst s ≫ inv f) (snd s)) ≫ snd c [PROOFSTEP] simpa only [BinaryFan.π_app_right, BinaryFan.mk_snd, IsLimit.fac] [GOAL] C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsInitial Y c : BinaryCofan X Y ⊢ Nonempty (IsColimit c) ↔ IsIso (inl c) [PROOFSTEP] constructor [GOAL] case mp C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsInitial Y c : BinaryCofan X Y ⊢ Nonempty (IsColimit c) → IsIso (inl c) [PROOFSTEP] rintro ⟨H⟩ [GOAL] case mp.intro C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsInitial Y c : BinaryCofan X Y H : IsColimit c ⊢ IsIso (inl c) [PROOFSTEP] obtain ⟨l, hl, -⟩ := BinaryCofan.IsColimit.desc' H (𝟙 X) (h.to X) [GOAL] case mp.intro.mk.intro C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsInitial Y c : BinaryCofan X Y H : IsColimit c l : c.pt ⟶ X hl : inl c ≫ l = 𝟙 X ⊢ IsIso (inl c) [PROOFSTEP] refine ⟨⟨l, hl, BinaryCofan.IsColimit.hom_ext H (?_) (h.hom_ext _ _)⟩⟩ [GOAL] case mp.intro.mk.intro C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsInitial Y c : BinaryCofan X Y H : IsColimit c l : c.pt ⟶ X hl : inl c ≫ l = 𝟙 X ⊢ inl c ≫ l ≫ inl c = inl c ≫ 𝟙 (((Functor.const (Discrete WalkingPair)).obj c.pt).obj { as := left }) [PROOFSTEP] rw [Category.comp_id] [GOAL] case mp.intro.mk.intro C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsInitial Y c : BinaryCofan X Y H : IsColimit c l : c.pt ⟶ X hl : inl c ≫ l = 𝟙 X ⊢ inl c ≫ l ≫ inl c = inl c [PROOFSTEP] have e : (inl c ≫ l) ≫ inl c = 𝟙 X ≫ inl c := congrArg (· ≫ inl c) hl [GOAL] case mp.intro.mk.intro C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsInitial Y c : BinaryCofan X Y H : IsColimit c l : c.pt ⟶ X hl : inl c ≫ l = 𝟙 X e : (inl c ≫ l) ≫ inl c = 𝟙 X ≫ inl c ⊢ inl c ≫ l ≫ inl c = inl c [PROOFSTEP] rwa [Category.assoc, Category.id_comp] at e [GOAL] case mpr C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsInitial Y c : BinaryCofan X Y ⊢ IsIso (inl c) → Nonempty (IsColimit c) [PROOFSTEP] intro [GOAL] case mpr C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsInitial Y c : BinaryCofan X Y a✝ : IsIso (inl c) ⊢ Nonempty (IsColimit c) [PROOFSTEP] exact ⟨BinaryCofan.IsColimit.mk _ (fun f _ => inv c.inl ≫ f) (fun _ _ => IsIso.hom_inv_id_assoc _ _) (fun _ _ => h.hom_ext _ _) fun _ _ _ e _ => (IsIso.eq_inv_comp _).mpr e⟩ [GOAL] C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsInitial X c : BinaryCofan X Y ⊢ Nonempty (IsColimit c) ↔ IsIso (inr c) [PROOFSTEP] refine' Iff.trans _ (BinaryCofan.isColimit_iff_isIso_inl h (BinaryCofan.mk c.inr c.inl)) [GOAL] C : Type u inst✝ : Category.{v, u} C X✝ Y✝ X Y : C h : IsInitial X c : BinaryCofan X Y ⊢ Nonempty (IsColimit c) ↔ Nonempty (IsColimit (mk (inr c) (inl c))) [PROOFSTEP] exact ⟨fun h => ⟨BinaryCofan.isColimitFlip h.some⟩, fun h => ⟨(BinaryCofan.isColimitFlip h.some).ofIsoColimit (isoBinaryCofanMk c).symm⟩⟩ [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryCofan X Y f : X' ⟶ X inst✝ : IsIso f h : IsColimit c ⊢ IsColimit (mk (f ≫ inl c) (inr c)) [PROOFSTEP] fapply BinaryCofan.isColimitMk [GOAL] case desc C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryCofan X Y f : X' ⟶ X inst✝ : IsIso f h : IsColimit c ⊢ (s : BinaryCofan X' ((pair X Y).obj { as := right })) → ((Functor.const (Discrete WalkingPair)).obj c.pt).obj { as := left } ⟶ s.pt [PROOFSTEP] exact fun s => h.desc (BinaryCofan.mk (inv f ≫ s.inl) s.inr) [GOAL] case fac_left C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryCofan X Y f : X' ⟶ X inst✝ : IsIso f h : IsColimit c ⊢ ∀ (s : BinaryCofan X' ((pair X Y).obj { as := right })), (f ≫ inl c) ≫ IsColimit.desc h (mk (inv f ≫ inl s) (inr s)) = inl s [PROOFSTEP] intro s [GOAL] case fac_left C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryCofan X Y f : X' ⟶ X inst✝ : IsIso f h : IsColimit c s : BinaryCofan X' ((pair X Y).obj { as := right }) ⊢ (f ≫ inl c) ≫ IsColimit.desc h (mk (inv f ≫ inl s) (inr s)) = inl s [PROOFSTEP] simp only [IsColimit.fac, BinaryCofan.ι_app_left, eq_self_iff_true, Category.assoc, BinaryCofan.mk_inl, IsIso.hom_inv_id_assoc] [GOAL] case fac_right C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryCofan X Y f : X' ⟶ X inst✝ : IsIso f h : IsColimit c ⊢ ∀ (s : BinaryCofan X' ((pair X Y).obj { as := right })), inr c ≫ IsColimit.desc h (mk (inv f ≫ inl s) (inr s)) = inr s [PROOFSTEP] intro s [GOAL] case fac_right C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryCofan X Y f : X' ⟶ X inst✝ : IsIso f h : IsColimit c s : BinaryCofan X' ((pair X Y).obj { as := right }) ⊢ inr c ≫ IsColimit.desc h (mk (inv f ≫ inl s) (inr s)) = inr s [PROOFSTEP] simp only [IsColimit.fac, BinaryCofan.ι_app_right, eq_self_iff_true, BinaryCofan.mk_inr] [GOAL] case uniq C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryCofan X Y f : X' ⟶ X inst✝ : IsIso f h : IsColimit c ⊢ ∀ (s : BinaryCofan X' ((pair X Y).obj { as := right })) (m : ((Functor.const (Discrete WalkingPair)).obj c.pt).obj { as := left } ⟶ s.pt), (f ≫ inl c) ≫ m = inl s → inr c ≫ m = inr s → m = IsColimit.desc h (mk (inv f ≫ inl s) (inr s)) [PROOFSTEP] intro s m e₁ e₂ [GOAL] case uniq C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryCofan X Y f : X' ⟶ X inst✝ : IsIso f h : IsColimit c s : BinaryCofan X' ((pair X Y).obj { as := right }) m : ((Functor.const (Discrete WalkingPair)).obj c.pt).obj { as := left } ⟶ s.pt e₁ : (f ≫ inl c) ≫ m = inl s e₂ : inr c ≫ m = inr s ⊢ m = IsColimit.desc h (mk (inv f ≫ inl s) (inr s)) [PROOFSTEP] apply BinaryCofan.IsColimit.hom_ext h [GOAL] case uniq.h₁ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryCofan X Y f : X' ⟶ X inst✝ : IsIso f h : IsColimit c s : BinaryCofan X' ((pair X Y).obj { as := right }) m : ((Functor.const (Discrete WalkingPair)).obj c.pt).obj { as := left } ⟶ s.pt e₁ : (f ≫ inl c) ≫ m = inl s e₂ : inr c ≫ m = inr s ⊢ inl c ≫ m = inl c ≫ IsColimit.desc h (mk (inv f ≫ inl s) (inr s)) [PROOFSTEP] rw [← cancel_epi f] -- Porting note: simp timed out here too [GOAL] case uniq.h₁ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryCofan X Y f : X' ⟶ X inst✝ : IsIso f h : IsColimit c s : BinaryCofan X' ((pair X Y).obj { as := right }) m : ((Functor.const (Discrete WalkingPair)).obj c.pt).obj { as := left } ⟶ s.pt e₁ : (f ≫ inl c) ≫ m = inl s e₂ : inr c ≫ m = inr s ⊢ f ≫ inl c ≫ m = f ≫ inl c ≫ IsColimit.desc h (mk (inv f ≫ inl s) (inr s)) [PROOFSTEP] simpa only [IsColimit.fac, BinaryCofan.ι_app_left, eq_self_iff_true, Category.assoc, BinaryCofan.mk_inl, IsIso.hom_inv_id_assoc] using e₁ [GOAL] case uniq.h₂ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y X' : C c : BinaryCofan X Y f : X' ⟶ X inst✝ : IsIso f h : IsColimit c s : BinaryCofan X' ((pair X Y).obj { as := right }) m : ((Functor.const (Discrete WalkingPair)).obj c.pt).obj { as := left } ⟶ s.pt e₁ : (f ≫ inl c) ≫ m = inl s e₂ : inr c ≫ m = inr s ⊢ inr c ≫ m = inr c ≫ IsColimit.desc h (mk (inv f ≫ inl s) (inr s)) [PROOFSTEP] simpa only [IsColimit.fac, BinaryCofan.ι_app_right, eq_self_iff_true, BinaryCofan.mk_inr] [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryProduct X Y x✝ : Discrete WalkingPair u : WalkingPair ⊢ NatTrans.app (limit.cone (pair X Y)).π { as := u } = (Iso.refl (limit.cone (pair X Y)).pt).hom ≫ NatTrans.app (BinaryFan.mk prod.fst prod.snd).π { as := u } [PROOFSTEP] cases u [GOAL] case left C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryProduct X Y x✝ : Discrete WalkingPair ⊢ NatTrans.app (limit.cone (pair X Y)).π { as := left } = (Iso.refl (limit.cone (pair X Y)).pt).hom ≫ NatTrans.app (BinaryFan.mk prod.fst prod.snd).π { as := left } [PROOFSTEP] dsimp [GOAL] case left C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryProduct X Y x✝ : Discrete WalkingPair ⊢ BinaryFan.fst (limit.cone (pair X Y)) = 𝟙 (limit (pair X Y)) ≫ prod.fst [PROOFSTEP] simp only [Category.id_comp] [GOAL] case left C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryProduct X Y x✝ : Discrete WalkingPair ⊢ BinaryFan.fst (limit.cone (pair X Y)) = prod.fst [PROOFSTEP] rfl [GOAL] case right C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryProduct X Y x✝ : Discrete WalkingPair ⊢ NatTrans.app (limit.cone (pair X Y)).π { as := right } = (Iso.refl (limit.cone (pair X Y)).pt).hom ≫ NatTrans.app (BinaryFan.mk prod.fst prod.snd).π { as := right } [PROOFSTEP] dsimp [GOAL] case right C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryProduct X Y x✝ : Discrete WalkingPair ⊢ BinaryFan.snd (limit.cone (pair X Y)) = 𝟙 (limit (pair X Y)) ≫ prod.snd [PROOFSTEP] simp only [Category.id_comp] [GOAL] case right C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryProduct X Y x✝ : Discrete WalkingPair ⊢ BinaryFan.snd (limit.cone (pair X Y)) = prod.snd [PROOFSTEP] rfl [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryCoproduct X Y x✝ : Discrete WalkingPair u : WalkingPair ⊢ NatTrans.app (colimit.cocone (pair X Y)).ι { as := u } ≫ (Iso.refl (colimit.cocone (pair X Y)).pt).hom = NatTrans.app (BinaryCofan.mk coprod.inl coprod.inr).ι { as := u } [PROOFSTEP] cases u [GOAL] case left C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryCoproduct X Y x✝ : Discrete WalkingPair ⊢ NatTrans.app (colimit.cocone (pair X Y)).ι { as := left } ≫ (Iso.refl (colimit.cocone (pair X Y)).pt).hom = NatTrans.app (BinaryCofan.mk coprod.inl coprod.inr).ι { as := left } [PROOFSTEP] dsimp [GOAL] case left C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryCoproduct X Y x✝ : Discrete WalkingPair ⊢ colimit.ι (pair X Y) { as := left } ≫ 𝟙 (colimit (pair X Y)) = coprod.inl [PROOFSTEP] simp only [Category.comp_id] [GOAL] case right C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryCoproduct X Y x✝ : Discrete WalkingPair ⊢ NatTrans.app (colimit.cocone (pair X Y)).ι { as := right } ≫ (Iso.refl (colimit.cocone (pair X Y)).pt).hom = NatTrans.app (BinaryCofan.mk coprod.inl coprod.inr).ι { as := right } [PROOFSTEP] dsimp [GOAL] case right C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryCoproduct X Y x✝ : Discrete WalkingPair ⊢ colimit.ι (pair X Y) { as := right } ≫ 𝟙 (colimit (pair X Y)) = coprod.inr [PROOFSTEP] simp only [Category.comp_id] [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ V W X Y : C inst✝ : HasBinaryProduct X Y f : V ⟶ W g : W ⟶ X h : W ⟶ Y ⊢ f ≫ lift g h = lift (f ≫ g) (f ≫ h) [PROOFSTEP] ext [GOAL] case h₁ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ V W X Y : C inst✝ : HasBinaryProduct X Y f : V ⟶ W g : W ⟶ X h : W ⟶ Y ⊢ (f ≫ lift g h) ≫ fst = lift (f ≫ g) (f ≫ h) ≫ fst [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ V W X Y : C inst✝ : HasBinaryProduct X Y f : V ⟶ W g : W ⟶ X h : W ⟶ Y ⊢ (f ≫ lift g h) ≫ snd = lift (f ≫ g) (f ≫ h) ≫ snd [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryProduct Y Y f : X ⟶ Y ⊢ f ≫ diag Y = lift f f [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryProduct X Y ⊢ map (𝟙 X) (𝟙 Y) = 𝟙 (X ⨯ Y) [PROOFSTEP] ext [GOAL] case h₁ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryProduct X Y ⊢ map (𝟙 X) (𝟙 Y) ≫ fst = 𝟙 (X ⨯ Y) ≫ fst [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryProduct X Y ⊢ map (𝟙 X) (𝟙 Y) ≫ snd = 𝟙 (X ⨯ Y) ≫ snd [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryProduct X Y ⊢ lift fst snd = 𝟙 (X ⨯ Y) [PROOFSTEP] ext [GOAL] case h₁ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryProduct X Y ⊢ lift fst snd ≫ fst = 𝟙 (X ⨯ Y) ≫ fst [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryProduct X Y ⊢ lift fst snd ≫ snd = 𝟙 (X ⨯ Y) ≫ snd [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ V W X Y Z : C inst✝¹ : HasBinaryProduct W X inst✝ : HasBinaryProduct Y Z f : V ⟶ W g : V ⟶ X h : W ⟶ Y k : X ⟶ Z ⊢ lift f g ≫ map h k = lift (f ≫ h) (g ≫ k) [PROOFSTEP] ext [GOAL] case h₁ C : Type u inst✝² : Category.{v, u} C X✝ Y✝ V W X Y Z : C inst✝¹ : HasBinaryProduct W X inst✝ : HasBinaryProduct Y Z f : V ⟶ W g : V ⟶ X h : W ⟶ Y k : X ⟶ Z ⊢ (lift f g ≫ map h k) ≫ fst = lift (f ≫ h) (g ≫ k) ≫ fst [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝² : Category.{v, u} C X✝ Y✝ V W X Y Z : C inst✝¹ : HasBinaryProduct W X inst✝ : HasBinaryProduct Y Z f : V ⟶ W g : V ⟶ X h : W ⟶ Y k : X ⟶ Z ⊢ (lift f g ≫ map h k) ≫ snd = lift (f ≫ h) (g ≫ k) ≫ snd [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ W X Y Z : C inst✝¹ : HasBinaryProduct W Y inst✝ : HasBinaryProduct X Z g : W ⟶ X g' : Y ⟶ Z ⊢ lift (fst ≫ g) (snd ≫ g') = map g g' [PROOFSTEP] rw [← prod.lift_map] [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ W X Y Z : C inst✝¹ : HasBinaryProduct W Y inst✝ : HasBinaryProduct X Z g : W ⟶ X g' : Y ⟶ Z ⊢ lift fst snd ≫ map g g' = map g g' [PROOFSTEP] simp [GOAL] C : Type u inst✝³ : Category.{v, u} C X Y A₁ A₂ A₃ B₁ B₂ B₃ : C inst✝² : HasBinaryProduct A₁ B₁ inst✝¹ : HasBinaryProduct A₂ B₂ inst✝ : HasBinaryProduct A₃ B₃ f : A₁ ⟶ A₂ g : B₁ ⟶ B₂ h : A₂ ⟶ A₃ k : B₂ ⟶ B₃ ⊢ map f g ≫ map h k = map (f ≫ h) (g ≫ k) [PROOFSTEP] ext [GOAL] case h₁ C : Type u inst✝³ : Category.{v, u} C X Y A₁ A₂ A₃ B₁ B₂ B₃ : C inst✝² : HasBinaryProduct A₁ B₁ inst✝¹ : HasBinaryProduct A₂ B₂ inst✝ : HasBinaryProduct A₃ B₃ f : A₁ ⟶ A₂ g : B₁ ⟶ B₂ h : A₂ ⟶ A₃ k : B₂ ⟶ B₃ ⊢ (map f g ≫ map h k) ≫ fst = map (f ≫ h) (g ≫ k) ≫ fst [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝³ : Category.{v, u} C X Y A₁ A₂ A₃ B₁ B₂ B₃ : C inst✝² : HasBinaryProduct A₁ B₁ inst✝¹ : HasBinaryProduct A₂ B₂ inst✝ : HasBinaryProduct A₃ B₃ f : A₁ ⟶ A₂ g : B₁ ⟶ B₂ h : A₂ ⟶ A₃ k : B₂ ⟶ B₃ ⊢ (map f g ≫ map h k) ≫ snd = map (f ≫ h) (g ≫ k) ≫ snd [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ A B X Y : C f : A ⟶ B g : X ⟶ Y inst✝ : HasLimitsOfShape (Discrete WalkingPair) C ⊢ map (𝟙 X) f ≫ map g (𝟙 B) = map g (𝟙 A) ≫ map (𝟙 Y) f [PROOFSTEP] simp [GOAL] C : Type u inst✝³ : Category.{v, u} C X✝ Y✝ X Y Z W : C f : X ⟶ Y g : Y ⟶ Z inst✝² : HasBinaryProduct X W inst✝¹ : HasBinaryProduct Z W inst✝ : HasBinaryProduct Y W ⊢ map (f ≫ g) (𝟙 W) = map f (𝟙 W) ≫ map g (𝟙 W) [PROOFSTEP] simp [GOAL] C : Type u inst✝³ : Category.{v, u} C X✝ Y✝ X Y Z W : C f : X ⟶ Y g : Y ⟶ Z inst✝² : HasBinaryProduct W X inst✝¹ : HasBinaryProduct W Y inst✝ : HasBinaryProduct W Z ⊢ map (𝟙 W) (f ≫ g) = map (𝟙 W) f ≫ map (𝟙 W) g [PROOFSTEP] simp [GOAL] C✝ : Type u inst✝⁵ : Category.{v, u} C✝ X✝ Y✝ : C✝ C : Type u_1 inst✝⁴ : Category.{?u.160582, u_1} C W X Y Z : C f : W ⟶ Y g : X ⟶ Z inst✝³ : Mono f inst✝² : Mono g inst✝¹ : HasBinaryProduct W X inst✝ : HasBinaryProduct Y Z Z✝ : C i₁ i₂ : Z✝ ⟶ W ⨯ X h : i₁ ≫ map f g = i₂ ≫ map f g ⊢ i₁ = i₂ [PROOFSTEP] ext [GOAL] case h₁ C✝ : Type u inst✝⁵ : Category.{v, u} C✝ X✝ Y✝ : C✝ C : Type u_1 inst✝⁴ : Category.{?u.160582, u_1} C W X Y Z : C f : W ⟶ Y g : X ⟶ Z inst✝³ : Mono f inst✝² : Mono g inst✝¹ : HasBinaryProduct W X inst✝ : HasBinaryProduct Y Z Z✝ : C i₁ i₂ : Z✝ ⟶ W ⨯ X h : i₁ ≫ map f g = i₂ ≫ map f g ⊢ i₁ ≫ fst = i₂ ≫ fst [PROOFSTEP] rw [← cancel_mono f] [GOAL] case h₁ C✝ : Type u inst✝⁵ : Category.{v, u} C✝ X✝ Y✝ : C✝ C : Type u_1 inst✝⁴ : Category.{?u.160582, u_1} C W X Y Z : C f : W ⟶ Y g : X ⟶ Z inst✝³ : Mono f inst✝² : Mono g inst✝¹ : HasBinaryProduct W X inst✝ : HasBinaryProduct Y Z Z✝ : C i₁ i₂ : Z✝ ⟶ W ⨯ X h : i₁ ≫ map f g = i₂ ≫ map f g ⊢ (i₁ ≫ fst) ≫ f = (i₂ ≫ fst) ≫ f [PROOFSTEP] simpa using congr_arg (fun f => f ≫ prod.fst) h [GOAL] case h₂ C✝ : Type u inst✝⁵ : Category.{v, u} C✝ X✝ Y✝ : C✝ C : Type u_1 inst✝⁴ : Category.{?u.160582, u_1} C W X Y Z : C f : W ⟶ Y g : X ⟶ Z inst✝³ : Mono f inst✝² : Mono g inst✝¹ : HasBinaryProduct W X inst✝ : HasBinaryProduct Y Z Z✝ : C i₁ i₂ : Z✝ ⟶ W ⨯ X h : i₁ ≫ map f g = i₂ ≫ map f g ⊢ i₁ ≫ snd = i₂ ≫ snd [PROOFSTEP] rw [← cancel_mono g] [GOAL] case h₂ C✝ : Type u inst✝⁵ : Category.{v, u} C✝ X✝ Y✝ : C✝ C : Type u_1 inst✝⁴ : Category.{?u.160582, u_1} C W X Y Z : C f : W ⟶ Y g : X ⟶ Z inst✝³ : Mono f inst✝² : Mono g inst✝¹ : HasBinaryProduct W X inst✝ : HasBinaryProduct Y Z Z✝ : C i₁ i₂ : Z✝ ⟶ W ⨯ X h : i₁ ≫ map f g = i₂ ≫ map f g ⊢ (i₁ ≫ snd) ≫ g = (i₂ ≫ snd) ≫ g [PROOFSTEP] simpa using congr_arg (fun f => f ≫ prod.snd) h [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ X Y : C f : X ⟶ Y inst✝¹ : HasBinaryProduct X X inst✝ : HasBinaryProduct Y Y ⊢ diag X ≫ map f f = f ≫ diag Y [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ X Y : C inst✝¹ : HasBinaryProduct X Y inst✝ : HasBinaryProduct (X ⨯ Y) (X ⨯ Y) ⊢ diag (X ⨯ Y) ≫ map fst snd = 𝟙 (X ⨯ Y) [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ : C inst✝ : HasLimitsOfShape (Discrete WalkingPair) C X X' Y Y' : C g : X ⟶ Y g' : X' ⟶ Y' ⊢ diag (X ⨯ X') ≫ map (fst ≫ g) (snd ≫ g') = map g g' [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ V W X Y : C inst✝ : HasBinaryCoproduct X Y f : V ⟶ W g : X ⟶ V h : Y ⟶ V ⊢ desc g h ≫ f = desc (g ≫ f) (h ≫ f) [PROOFSTEP] ext [GOAL] case h₁ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ V W X Y : C inst✝ : HasBinaryCoproduct X Y f : V ⟶ W g : X ⟶ V h : Y ⟶ V ⊢ inl ≫ desc g h ≫ f = inl ≫ desc (g ≫ f) (h ≫ f) [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ V W X Y : C inst✝ : HasBinaryCoproduct X Y f : V ⟶ W g : X ⟶ V h : Y ⟶ V ⊢ inr ≫ desc g h ≫ f = inr ≫ desc (g ≫ f) (h ≫ f) [PROOFSTEP] simp [GOAL] C✝ : Type u inst✝² : Category.{v, u} C✝ X✝ Y✝ : C✝ C : Type u inst✝¹ : Category.{u_1, u} C V W X Y : C inst✝ : HasBinaryCoproduct X Y f : V ⟶ W g : X ⟶ V h : Y ⟶ V Z : C l : W ⟶ Z ⊢ desc g h ≫ f ≫ l = desc (g ≫ f) (h ≫ f) ≫ l [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryCoproduct X X f : X ⟶ Y ⊢ codiag X ≫ f = desc f f [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryCoproduct X Y ⊢ map (𝟙 X) (𝟙 Y) = 𝟙 (X ⨿ Y) [PROOFSTEP] ext [GOAL] case h₁ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryCoproduct X Y ⊢ inl ≫ map (𝟙 X) (𝟙 Y) = inl ≫ 𝟙 (X ⨿ Y) [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryCoproduct X Y ⊢ inr ≫ map (𝟙 X) (𝟙 Y) = inr ≫ 𝟙 (X ⨿ Y) [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryCoproduct X Y ⊢ desc inl inr = 𝟙 (X ⨿ Y) [PROOFSTEP] ext [GOAL] case h₁ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryCoproduct X Y ⊢ inl ≫ desc inl inr = inl ≫ 𝟙 (X ⨿ Y) [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ X Y : C inst✝ : HasBinaryCoproduct X Y ⊢ inr ≫ desc inl inr = inr ≫ 𝟙 (X ⨿ Y) [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X Y S T U V W : C inst✝¹ : HasBinaryCoproduct U W inst✝ : HasBinaryCoproduct T V f : U ⟶ S g : W ⟶ S h : T ⟶ U k : V ⟶ W ⊢ map h k ≫ desc f g = desc (h ≫ f) (k ≫ g) [PROOFSTEP] ext [GOAL] case h₁ C : Type u inst✝² : Category.{v, u} C X Y S T U V W : C inst✝¹ : HasBinaryCoproduct U W inst✝ : HasBinaryCoproduct T V f : U ⟶ S g : W ⟶ S h : T ⟶ U k : V ⟶ W ⊢ inl ≫ map h k ≫ desc f g = inl ≫ desc (h ≫ f) (k ≫ g) [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝² : Category.{v, u} C X Y S T U V W : C inst✝¹ : HasBinaryCoproduct U W inst✝ : HasBinaryCoproduct T V f : U ⟶ S g : W ⟶ S h : T ⟶ U k : V ⟶ W ⊢ inr ≫ map h k ≫ desc f g = inr ≫ desc (h ≫ f) (k ≫ g) [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ W X Y Z : C inst✝¹ : HasBinaryCoproduct W Y inst✝ : HasBinaryCoproduct X Z g : W ⟶ X g' : Y ⟶ Z ⊢ desc (g ≫ inl) (g' ≫ inr) = map g g' [PROOFSTEP] rw [← coprod.map_desc] [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ W X Y Z : C inst✝¹ : HasBinaryCoproduct W Y inst✝ : HasBinaryCoproduct X Z g : W ⟶ X g' : Y ⟶ Z ⊢ map g g' ≫ desc inl inr = map g g' [PROOFSTEP] simp [GOAL] C : Type u inst✝³ : Category.{v, u} C X Y A₁ A₂ A₃ B₁ B₂ B₃ : C inst✝² : HasBinaryCoproduct A₁ B₁ inst✝¹ : HasBinaryCoproduct A₂ B₂ inst✝ : HasBinaryCoproduct A₃ B₃ f : A₁ ⟶ A₂ g : B₁ ⟶ B₂ h : A₂ ⟶ A₃ k : B₂ ⟶ B₃ ⊢ map f g ≫ map h k = map (f ≫ h) (g ≫ k) [PROOFSTEP] ext [GOAL] case h₁ C : Type u inst✝³ : Category.{v, u} C X Y A₁ A₂ A₃ B₁ B₂ B₃ : C inst✝² : HasBinaryCoproduct A₁ B₁ inst✝¹ : HasBinaryCoproduct A₂ B₂ inst✝ : HasBinaryCoproduct A₃ B₃ f : A₁ ⟶ A₂ g : B₁ ⟶ B₂ h : A₂ ⟶ A₃ k : B₂ ⟶ B₃ ⊢ inl ≫ map f g ≫ map h k = inl ≫ map (f ≫ h) (g ≫ k) [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝³ : Category.{v, u} C X Y A₁ A₂ A₃ B₁ B₂ B₃ : C inst✝² : HasBinaryCoproduct A₁ B₁ inst✝¹ : HasBinaryCoproduct A₂ B₂ inst✝ : HasBinaryCoproduct A₃ B₃ f : A₁ ⟶ A₂ g : B₁ ⟶ B₂ h : A₂ ⟶ A₃ k : B₂ ⟶ B₃ ⊢ inr ≫ map f g ≫ map h k = inr ≫ map (f ≫ h) (g ≫ k) [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ A B X Y : C f : A ⟶ B g : X ⟶ Y inst✝ : HasColimitsOfShape (Discrete WalkingPair) C ⊢ map (𝟙 X) f ≫ map g (𝟙 B) = map g (𝟙 A) ≫ map (𝟙 Y) f [PROOFSTEP] simp [GOAL] C : Type u inst✝³ : Category.{v, u} C X✝ Y✝ X Y Z W : C f : X ⟶ Y g : Y ⟶ Z inst✝² : HasBinaryCoproduct Z W inst✝¹ : HasBinaryCoproduct Y W inst✝ : HasBinaryCoproduct X W ⊢ map (f ≫ g) (𝟙 W) = map f (𝟙 W) ≫ map g (𝟙 W) [PROOFSTEP] simp [GOAL] C : Type u inst✝³ : Category.{v, u} C X✝ Y✝ X Y Z W : C f : X ⟶ Y g : Y ⟶ Z inst✝² : HasBinaryCoproduct W X inst✝¹ : HasBinaryCoproduct W Y inst✝ : HasBinaryCoproduct W Z ⊢ map (𝟙 W) (f ≫ g) = map (𝟙 W) f ≫ map (𝟙 W) g [PROOFSTEP] simp [GOAL] C✝ : Type u inst✝⁵ : Category.{v, u} C✝ X✝ Y✝ : C✝ C : Type u_1 inst✝⁴ : Category.{?u.203502, u_1} C W X Y Z : C f : W ⟶ Y g : X ⟶ Z inst✝³ : Epi f inst✝² : Epi g inst✝¹ : HasBinaryCoproduct W X inst✝ : HasBinaryCoproduct Y Z Z✝ : C i₁ i₂ : Y ⨿ Z ⟶ Z✝ h : map f g ≫ i₁ = map f g ≫ i₂ ⊢ i₁ = i₂ [PROOFSTEP] ext [GOAL] case h₁ C✝ : Type u inst✝⁵ : Category.{v, u} C✝ X✝ Y✝ : C✝ C : Type u_1 inst✝⁴ : Category.{?u.203502, u_1} C W X Y Z : C f : W ⟶ Y g : X ⟶ Z inst✝³ : Epi f inst✝² : Epi g inst✝¹ : HasBinaryCoproduct W X inst✝ : HasBinaryCoproduct Y Z Z✝ : C i₁ i₂ : Y ⨿ Z ⟶ Z✝ h : map f g ≫ i₁ = map f g ≫ i₂ ⊢ inl ≫ i₁ = inl ≫ i₂ [PROOFSTEP] rw [← cancel_epi f] [GOAL] case h₁ C✝ : Type u inst✝⁵ : Category.{v, u} C✝ X✝ Y✝ : C✝ C : Type u_1 inst✝⁴ : Category.{?u.203502, u_1} C W X Y Z : C f : W ⟶ Y g : X ⟶ Z inst✝³ : Epi f inst✝² : Epi g inst✝¹ : HasBinaryCoproduct W X inst✝ : HasBinaryCoproduct Y Z Z✝ : C i₁ i₂ : Y ⨿ Z ⟶ Z✝ h : map f g ≫ i₁ = map f g ≫ i₂ ⊢ f ≫ inl ≫ i₁ = f ≫ inl ≫ i₂ [PROOFSTEP] simpa using congr_arg (fun f => coprod.inl ≫ f) h [GOAL] case h₂ C✝ : Type u inst✝⁵ : Category.{v, u} C✝ X✝ Y✝ : C✝ C : Type u_1 inst✝⁴ : Category.{?u.203502, u_1} C W X Y Z : C f : W ⟶ Y g : X ⟶ Z inst✝³ : Epi f inst✝² : Epi g inst✝¹ : HasBinaryCoproduct W X inst✝ : HasBinaryCoproduct Y Z Z✝ : C i₁ i₂ : Y ⨿ Z ⟶ Z✝ h : map f g ≫ i₁ = map f g ≫ i₂ ⊢ inr ≫ i₁ = inr ≫ i₂ [PROOFSTEP] rw [← cancel_epi g] [GOAL] case h₂ C✝ : Type u inst✝⁵ : Category.{v, u} C✝ X✝ Y✝ : C✝ C : Type u_1 inst✝⁴ : Category.{?u.203502, u_1} C W X Y Z : C f : W ⟶ Y g : X ⟶ Z inst✝³ : Epi f inst✝² : Epi g inst✝¹ : HasBinaryCoproduct W X inst✝ : HasBinaryCoproduct Y Z Z✝ : C i₁ i₂ : Y ⨿ Z ⟶ Z✝ h : map f g ≫ i₁ = map f g ≫ i₂ ⊢ g ≫ inr ≫ i₁ = g ≫ inr ≫ i₂ [PROOFSTEP] simpa using congr_arg (fun f => coprod.inr ≫ f) h [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ X Y : C f : X ⟶ Y inst✝¹ : HasBinaryCoproduct X X inst✝ : HasBinaryCoproduct Y Y ⊢ map f f ≫ codiag Y = codiag X ≫ f [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ X Y : C inst✝¹ : HasBinaryCoproduct X Y inst✝ : HasBinaryCoproduct (X ⨿ Y) (X ⨿ Y) ⊢ map inl inr ≫ codiag (X ⨿ Y) = 𝟙 (X ⨿ Y) [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ : C inst✝ : HasColimitsOfShape (Discrete WalkingPair) C X X' Y Y' : C g : X ⟶ Y g' : X' ⟶ Y' ⊢ map (g ≫ inl) (g' ≫ inr) ≫ codiag (Y ⨿ Y') = map g g' [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ : C inst✝ : HasBinaryProducts C W X Y Z : C f : X ⟶ Y g : Z ⟶ W ⊢ prod.map f g ≫ (prod.braiding Y W).hom = (prod.braiding X Z).hom ≫ prod.map g f [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C X✝ Y✝ : C inst✝ : HasBinaryProducts C W X Y Z : C ⊢ map (associator W X Y).hom (𝟙 Z) ≫ (associator W (X ⨯ Y) Z).hom ≫ map (𝟙 W) (associator X Y Z).hom = (associator (W ⨯ X) Y Z).hom ≫ (associator W X (Y ⨯ Z)).hom [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C X Y : C inst✝ : HasBinaryProducts C X₁ X₂ X₃ Y₁ Y₂ Y₃ : C f₁ : X₁ ⟶ Y₁ f₂ : X₂ ⟶ Y₂ f₃ : X₃ ⟶ Y₃ ⊢ map (map f₁ f₂) f₃ ≫ (associator Y₁ Y₂ Y₃).hom = (associator X₁ X₂ X₃).hom ≫ map f₁ (map f₂ f₃) [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : HasTerminal C P : C inst✝ : HasBinaryProduct (⊤_ C) P ⊢ snd ≫ lift (terminal.from P) (𝟙 P) = 𝟙 ((⊤_ C) ⨯ P) [PROOFSTEP] apply prod.hom_ext [GOAL] case h₁ C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : HasTerminal C P : C inst✝ : HasBinaryProduct (⊤_ C) P ⊢ (snd ≫ lift (terminal.from P) (𝟙 P)) ≫ fst = 𝟙 ((⊤_ C) ⨯ P) ≫ fst [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : HasTerminal C P : C inst✝ : HasBinaryProduct (⊤_ C) P ⊢ (snd ≫ lift (terminal.from P) (𝟙 P)) ≫ snd = 𝟙 ((⊤_ C) ⨯ P) ≫ snd [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : HasTerminal C P : C inst✝ : HasBinaryProduct (⊤_ C) P ⊢ lift (terminal.from P) (𝟙 P) ≫ snd = 𝟙 P [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : HasTerminal C P : C inst✝ : HasBinaryProduct P (⊤_ C) ⊢ fst ≫ lift (𝟙 P) (terminal.from P) = 𝟙 (P ⨯ ⊤_ C) [PROOFSTEP] apply prod.hom_ext [GOAL] case h₁ C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : HasTerminal C P : C inst✝ : HasBinaryProduct P (⊤_ C) ⊢ (fst ≫ lift (𝟙 P) (terminal.from P)) ≫ fst = 𝟙 (P ⨯ ⊤_ C) ≫ fst [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : HasTerminal C P : C inst✝ : HasBinaryProduct P (⊤_ C) ⊢ (fst ≫ lift (𝟙 P) (terminal.from P)) ≫ snd = 𝟙 (P ⨯ ⊤_ C) ≫ snd [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : HasTerminal C P : C inst✝ : HasBinaryProduct P (⊤_ C) ⊢ lift (𝟙 P) (terminal.from P) ≫ fst = 𝟙 P [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : HasTerminal C inst✝ : HasBinaryProducts C f : X ⟶ Y ⊢ (leftUnitor X).inv ≫ map (𝟙 (⊤_ C)) f = f ≫ (leftUnitor Y).inv [PROOFSTEP] rw [Iso.inv_comp_eq, ← Category.assoc, Iso.eq_comp_inv, prod.leftUnitor_hom_naturality] [GOAL] C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : HasTerminal C inst✝ : HasBinaryProducts C f : X ⟶ Y ⊢ (prod.rightUnitor X).inv ≫ prod.map f (𝟙 (⊤_ C)) = f ≫ (prod.rightUnitor Y).inv [PROOFSTEP] rw [Iso.inv_comp_eq, ← Category.assoc, Iso.eq_comp_inv, prod.rightUnitor_hom_naturality] [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasTerminal C inst✝ : HasBinaryProducts C X Y : C ⊢ (associator X (⊤_ C) Y).hom ≫ map (𝟙 X) (leftUnitor Y).hom = map (rightUnitor X).hom (𝟙 Y) [PROOFSTEP] ext [GOAL] case h₁ C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasTerminal C inst✝ : HasBinaryProducts C X Y : C ⊢ ((associator X (⊤_ C) Y).hom ≫ map (𝟙 X) (leftUnitor Y).hom) ≫ fst = map (rightUnitor X).hom (𝟙 Y) ≫ fst [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : HasTerminal C inst✝ : HasBinaryProducts C X Y : C ⊢ ((associator X (⊤_ C) Y).hom ≫ map (𝟙 X) (leftUnitor Y).hom) ≫ snd = map (rightUnitor X).hom (𝟙 Y) ≫ snd [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X✝ Y✝ : C inst✝¹ : Category.{v, u} C inst✝ : HasBinaryCoproducts C W X Y Z : C ⊢ map (associator W X Y).hom (𝟙 Z) ≫ (associator W (X ⨿ Y) Z).hom ≫ map (𝟙 W) (associator X Y Z).hom = (associator (W ⨿ X) Y Z).hom ≫ (associator W X (Y ⨿ Z)).hom [PROOFSTEP] simp [GOAL] C : Type u inst✝² : Category.{v, u} C X Y : C inst✝¹ : Category.{v, u} C inst✝ : HasBinaryCoproducts C X₁ X₂ X₃ Y₁ Y₂ Y₃ : C f₁ : X₁ ⟶ Y₁ f₂ : X₂ ⟶ Y₂ f₃ : X₃ ⟶ Y₃ ⊢ map (map f₁ f₂) f₃ ≫ (associator Y₁ Y₂ Y₃).hom = (associator X₁ X₂ X₃).hom ≫ map f₁ (map f₂ f₃) [PROOFSTEP] simp [GOAL] C : Type u inst✝³ : Category.{v, u} C X Y : C inst✝² : Category.{v, u} C inst✝¹ : HasBinaryCoproducts C inst✝ : HasInitial C P : C ⊢ desc (initial.to P) (𝟙 P) ≫ inr = 𝟙 ((⊥_ C) ⨿ P) [PROOFSTEP] apply coprod.hom_ext [GOAL] case h₁ C : Type u inst✝³ : Category.{v, u} C X Y : C inst✝² : Category.{v, u} C inst✝¹ : HasBinaryCoproducts C inst✝ : HasInitial C P : C ⊢ inl ≫ desc (initial.to P) (𝟙 P) ≫ inr = inl ≫ 𝟙 ((⊥_ C) ⨿ P) [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝³ : Category.{v, u} C X Y : C inst✝² : Category.{v, u} C inst✝¹ : HasBinaryCoproducts C inst✝ : HasInitial C P : C ⊢ inr ≫ desc (initial.to P) (𝟙 P) ≫ inr = inr ≫ 𝟙 ((⊥_ C) ⨿ P) [PROOFSTEP] simp [GOAL] C : Type u inst✝³ : Category.{v, u} C X Y : C inst✝² : Category.{v, u} C inst✝¹ : HasBinaryCoproducts C inst✝ : HasInitial C P : C ⊢ inr ≫ desc (initial.to P) (𝟙 P) = 𝟙 P [PROOFSTEP] simp [GOAL] C : Type u inst✝³ : Category.{v, u} C X Y : C inst✝² : Category.{v, u} C inst✝¹ : HasBinaryCoproducts C inst✝ : HasInitial C P : C ⊢ desc (𝟙 P) (initial.to P) ≫ inl = 𝟙 (P ⨿ ⊥_ C) [PROOFSTEP] apply coprod.hom_ext [GOAL] case h₁ C : Type u inst✝³ : Category.{v, u} C X Y : C inst✝² : Category.{v, u} C inst✝¹ : HasBinaryCoproducts C inst✝ : HasInitial C P : C ⊢ inl ≫ desc (𝟙 P) (initial.to P) ≫ inl = inl ≫ 𝟙 (P ⨿ ⊥_ C) [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝³ : Category.{v, u} C X Y : C inst✝² : Category.{v, u} C inst✝¹ : HasBinaryCoproducts C inst✝ : HasInitial C P : C ⊢ inr ≫ desc (𝟙 P) (initial.to P) ≫ inl = inr ≫ 𝟙 (P ⨿ ⊥_ C) [PROOFSTEP] simp [GOAL] C : Type u inst✝³ : Category.{v, u} C X Y : C inst✝² : Category.{v, u} C inst✝¹ : HasBinaryCoproducts C inst✝ : HasInitial C P : C ⊢ inl ≫ desc (𝟙 P) (initial.to P) = 𝟙 P [PROOFSTEP] simp [GOAL] C : Type u inst✝³ : Category.{v, u} C X✝ Y✝ : C inst✝² : Category.{v, u} C inst✝¹ : HasBinaryCoproducts C inst✝ : HasInitial C X Y : C ⊢ (associator X (⊥_ C) Y).hom ≫ map (𝟙 X) (leftUnitor Y).hom = map (rightUnitor X).hom (𝟙 Y) [PROOFSTEP] ext [GOAL] case h₁.h₁ C : Type u inst✝³ : Category.{v, u} C X✝ Y✝ : C inst✝² : Category.{v, u} C inst✝¹ : HasBinaryCoproducts C inst✝ : HasInitial C X Y : C ⊢ inl ≫ inl ≫ (associator X (⊥_ C) Y).hom ≫ map (𝟙 X) (leftUnitor Y).hom = inl ≫ inl ≫ map (rightUnitor X).hom (𝟙 Y) [PROOFSTEP] simp [GOAL] case h₁.h₂.w C : Type u inst✝³ : Category.{v, u} C X✝ Y✝ : C inst✝² : Category.{v, u} C inst✝¹ : HasBinaryCoproducts C inst✝ : HasInitial C X Y : C j✝ : Discrete PEmpty ⊢ colimit.ι (Functor.empty C) j✝ ≫ inr ≫ inl ≫ (associator X (⊥_ C) Y).hom ≫ map (𝟙 X) (leftUnitor Y).hom = colimit.ι (Functor.empty C) j✝ ≫ inr ≫ inl ≫ map (rightUnitor X).hom (𝟙 Y) [PROOFSTEP] simp [GOAL] case h₂ C : Type u inst✝³ : Category.{v, u} C X✝ Y✝ : C inst✝² : Category.{v, u} C inst✝¹ : HasBinaryCoproducts C inst✝ : HasInitial C X Y : C ⊢ inr ≫ (associator X (⊥_ C) Y).hom ≫ map (𝟙 X) (leftUnitor Y).hom = inr ≫ map (rightUnitor X).hom (𝟙 Y) [PROOFSTEP] simp [GOAL] C : Type u inst✝⁵ : Category.{v, u} C X Y : C D : Type u₂ inst✝⁴ : Category.{w, u₂} D F : C ⥤ D A A' B B' : C inst✝³ : HasBinaryProduct A B inst✝² : HasBinaryProduct A' B' inst✝¹ : HasBinaryProduct (F.obj A) (F.obj B) inst✝ : HasBinaryProduct (F.obj A') (F.obj B') f : A ⟶ A' g : B ⟶ B' ⊢ F.map (prod.map f g) ≫ prodComparison F A' B' = prodComparison F A B ≫ prod.map (F.map f) (F.map g) [PROOFSTEP] rw [prodComparison, prodComparison, prod.lift_map, ← F.map_comp, ← F.map_comp, prod.comp_lift, ← F.map_comp, prod.map_fst, ← F.map_comp, prod.map_snd] [GOAL] C : Type u inst✝⁷ : Category.{v, u} C X Y : C D : Type u₂ inst✝⁶ : Category.{w, u₂} D F✝ : C ⥤ D A✝ A' B B' : C inst✝⁵ : HasBinaryProduct A✝ B inst✝⁴ : HasBinaryProduct A' B' inst✝³ : HasBinaryProduct (F✝.obj A✝) (F✝.obj B) inst✝² : HasBinaryProduct (F✝.obj A') (F✝.obj B') inst✝¹ : HasBinaryProducts C inst✝ : HasBinaryProducts D F : C ⥤ D A f : C ⊢ ∀ ⦃Y : C⦄ (f_1 : f ⟶ Y), (prod.functor.obj A ⋙ F).map f_1 ≫ (fun B => prodComparison F A B) Y = (fun B => prodComparison F A B) f ≫ (F ⋙ prod.functor.obj (F.obj A)).map f_1 [PROOFSTEP] simp [prodComparison_natural] [GOAL] C : Type u inst✝⁶ : Category.{v, u} C X Y : C D : Type u₂ inst✝⁵ : Category.{w, u₂} D F : C ⥤ D A A' B B' : C inst✝⁴ : HasBinaryProduct A B inst✝³ : HasBinaryProduct A' B' inst✝² : HasBinaryProduct (F.obj A) (F.obj B) inst✝¹ : HasBinaryProduct (F.obj A') (F.obj B') inst✝ : IsIso (prodComparison F A B) ⊢ inv (prodComparison F A B) ≫ F.map prod.fst = prod.fst [PROOFSTEP] simp [IsIso.inv_comp_eq] [GOAL] C : Type u inst✝⁶ : Category.{v, u} C X Y : C D : Type u₂ inst✝⁵ : Category.{w, u₂} D F : C ⥤ D A A' B B' : C inst✝⁴ : HasBinaryProduct A B inst✝³ : HasBinaryProduct A' B' inst✝² : HasBinaryProduct (F.obj A) (F.obj B) inst✝¹ : HasBinaryProduct (F.obj A') (F.obj B') inst✝ : IsIso (prodComparison F A B) ⊢ inv (prodComparison F A B) ≫ F.map prod.snd = prod.snd [PROOFSTEP] simp [IsIso.inv_comp_eq] [GOAL] C : Type u inst✝⁷ : Category.{v, u} C X Y : C D : Type u₂ inst✝⁶ : Category.{w, u₂} D F : C ⥤ D A A' B B' : C inst✝⁵ : HasBinaryProduct A B inst✝⁴ : HasBinaryProduct A' B' inst✝³ : HasBinaryProduct (F.obj A) (F.obj B) inst✝² : HasBinaryProduct (F.obj A') (F.obj B') f : A ⟶ A' g : B ⟶ B' inst✝¹ : IsIso (prodComparison F A B) inst✝ : IsIso (prodComparison F A' B') ⊢ inv (prodComparison F A B) ≫ F.map (prod.map f g) = prod.map (F.map f) (F.map g) ≫ inv (prodComparison F A' B') [PROOFSTEP] rw [IsIso.eq_comp_inv, Category.assoc, IsIso.inv_comp_eq, prodComparison_natural] [GOAL] C : Type u inst✝⁸ : Category.{v, u} C X Y : C D : Type u₂ inst✝⁷ : Category.{w, u₂} D F : C ⥤ D A✝ A' B B' : C inst✝⁶ : HasBinaryProduct A✝ B inst✝⁵ : HasBinaryProduct A' B' inst✝⁴ : HasBinaryProduct (F.obj A✝) (F.obj B) inst✝³ : HasBinaryProduct (F.obj A') (F.obj B') inst✝² : HasBinaryProducts C inst✝¹ : HasBinaryProducts D A : C inst✝ : ∀ (B : C), IsIso (prodComparison F A B) ⊢ prod.functor.obj A ⋙ F ≅ F ⋙ prod.functor.obj (F.obj A) [PROOFSTEP] refine { @asIso _ _ _ _ _ (?_) with hom := prodComparisonNatTrans F A } [GOAL] C : Type u inst✝⁸ : Category.{v, u} C X Y : C D : Type u₂ inst✝⁷ : Category.{w, u₂} D F : C ⥤ D A✝ A' B B' : C inst✝⁶ : HasBinaryProduct A✝ B inst✝⁵ : HasBinaryProduct A' B' inst✝⁴ : HasBinaryProduct (F.obj A✝) (F.obj B) inst✝³ : HasBinaryProduct (F.obj A') (F.obj B') inst✝² : HasBinaryProducts C inst✝¹ : HasBinaryProducts D A : C inst✝ : ∀ (B : C), IsIso (prodComparison F A B) ⊢ IsIso (NatTrans.mk fun B => prodComparison F A B) [PROOFSTEP] apply NatIso.isIso_of_isIso_app [GOAL] C : Type u inst✝⁵ : Category.{v, u} C X Y : C D : Type u₂ inst✝⁴ : Category.{w, u₂} D F : C ⥤ D A A' B B' : C inst✝³ : HasBinaryCoproduct A B inst✝² : HasBinaryCoproduct A' B' inst✝¹ : HasBinaryCoproduct (F.obj A) (F.obj B) inst✝ : HasBinaryCoproduct (F.obj A') (F.obj B') f : A ⟶ A' g : B ⟶ B' ⊢ coprodComparison F A B ≫ F.map (coprod.map f g) = coprod.map (F.map f) (F.map g) ≫ coprodComparison F A' B' [PROOFSTEP] rw [coprodComparison, coprodComparison, coprod.map_desc, ← F.map_comp, ← F.map_comp, coprod.desc_comp, ← F.map_comp, coprod.inl_map, ← F.map_comp, coprod.inr_map] [GOAL] C : Type u inst✝⁷ : Category.{v, u} C X Y : C D : Type u₂ inst✝⁶ : Category.{w, u₂} D F✝ : C ⥤ D A✝ A' B B' : C inst✝⁵ : HasBinaryCoproduct A✝ B inst✝⁴ : HasBinaryCoproduct A' B' inst✝³ : HasBinaryCoproduct (F✝.obj A✝) (F✝.obj B) inst✝² : HasBinaryCoproduct (F✝.obj A') (F✝.obj B') inst✝¹ : HasBinaryCoproducts C inst✝ : HasBinaryCoproducts D F : C ⥤ D A f : C ⊢ ∀ ⦃Y : C⦄ (f_1 : f ⟶ Y), (F ⋙ coprod.functor.obj (F.obj A)).map f_1 ≫ (fun B => coprodComparison F A B) Y = (fun B => coprodComparison F A B) f ≫ (coprod.functor.obj A ⋙ F).map f_1 [PROOFSTEP] simp [coprodComparison_natural] [GOAL] C : Type u inst✝⁶ : Category.{v, u} C X Y : C D : Type u₂ inst✝⁵ : Category.{w, u₂} D F : C ⥤ D A A' B B' : C inst✝⁴ : HasBinaryCoproduct A B inst✝³ : HasBinaryCoproduct A' B' inst✝² : HasBinaryCoproduct (F.obj A) (F.obj B) inst✝¹ : HasBinaryCoproduct (F.obj A') (F.obj B') inst✝ : IsIso (coprodComparison F A B) ⊢ F.map coprod.inl ≫ inv (coprodComparison F A B) = coprod.inl [PROOFSTEP] simp [IsIso.inv_comp_eq] [GOAL] C : Type u inst✝⁶ : Category.{v, u} C X Y : C D : Type u₂ inst✝⁵ : Category.{w, u₂} D F : C ⥤ D A A' B B' : C inst✝⁴ : HasBinaryCoproduct A B inst✝³ : HasBinaryCoproduct A' B' inst✝² : HasBinaryCoproduct (F.obj A) (F.obj B) inst✝¹ : HasBinaryCoproduct (F.obj A') (F.obj B') inst✝ : IsIso (coprodComparison F A B) ⊢ F.map coprod.inr ≫ inv (coprodComparison F A B) = coprod.inr [PROOFSTEP] simp [IsIso.inv_comp_eq] [GOAL] C : Type u inst✝⁷ : Category.{v, u} C X Y : C D : Type u₂ inst✝⁶ : Category.{w, u₂} D F : C ⥤ D A A' B B' : C inst✝⁵ : HasBinaryCoproduct A B inst✝⁴ : HasBinaryCoproduct A' B' inst✝³ : HasBinaryCoproduct (F.obj A) (F.obj B) inst✝² : HasBinaryCoproduct (F.obj A') (F.obj B') f : A ⟶ A' g : B ⟶ B' inst✝¹ : IsIso (coprodComparison F A B) inst✝ : IsIso (coprodComparison F A' B') ⊢ inv (coprodComparison F A B) ≫ coprod.map (F.map f) (F.map g) = F.map (coprod.map f g) ≫ inv (coprodComparison F A' B') [PROOFSTEP] rw [IsIso.eq_comp_inv, Category.assoc, IsIso.inv_comp_eq, coprodComparison_natural] [GOAL] C : Type u inst✝⁸ : Category.{v, u} C X Y : C D : Type u₂ inst✝⁷ : Category.{w, u₂} D F : C ⥤ D A✝ A' B B' : C inst✝⁶ : HasBinaryCoproduct A✝ B inst✝⁵ : HasBinaryCoproduct A' B' inst✝⁴ : HasBinaryCoproduct (F.obj A✝) (F.obj B) inst✝³ : HasBinaryCoproduct (F.obj A') (F.obj B') inst✝² : HasBinaryCoproducts C inst✝¹ : HasBinaryCoproducts D A : C inst✝ : ∀ (B : C), IsIso (coprodComparison F A B) ⊢ F ⋙ coprod.functor.obj (F.obj A) ≅ coprod.functor.obj A ⋙ F [PROOFSTEP] refine { @asIso _ _ _ _ _ (?_) with hom := coprodComparisonNatTrans F A } [GOAL] C : Type u inst✝⁸ : Category.{v, u} C X Y : C D : Type u₂ inst✝⁷ : Category.{w, u₂} D F : C ⥤ D A✝ A' B B' : C inst✝⁶ : HasBinaryCoproduct A✝ B inst✝⁵ : HasBinaryCoproduct A' B' inst✝⁴ : HasBinaryCoproduct (F.obj A✝) (F.obj B) inst✝³ : HasBinaryCoproduct (F.obj A') (F.obj B') inst✝² : HasBinaryCoproducts C inst✝¹ : HasBinaryCoproducts D A : C inst✝ : ∀ (B : C), IsIso (coprodComparison F A B) ⊢ IsIso (NatTrans.mk fun B => coprodComparison F A B) [PROOFSTEP] apply NatIso.isIso_of_isIso_app [GOAL] C : Type u inst✝¹ : Category.{v, u} C inst✝ : HasBinaryCoproducts C A : C X✝ Y✝ : Over A k : X✝ ⟶ Y✝ g : Over A ⊢ coprod.map k.left (𝟙 ((𝟭 C).obj g.left)) ≫ (((fun f => coprodObj f) Y✝).obj g).hom = (((fun f => coprodObj f) X✝).obj g).hom [PROOFSTEP] dsimp [GOAL] C : Type u inst✝¹ : Category.{v, u} C inst✝ : HasBinaryCoproducts C A : C X✝ Y✝ : Over A k : X✝ ⟶ Y✝ g : Over A ⊢ coprod.map k.left (𝟙 g.left) ≫ coprod.desc Y✝.hom g.hom = coprod.desc X✝.hom g.hom [PROOFSTEP] rw [coprod.map_desc, Category.id_comp, Over.w k] [GOAL] C : Type u inst✝¹ : Category.{v, u} C inst✝ : HasBinaryCoproducts C A : C X✝ Y✝ : Over A k✝ : X✝ ⟶ Y✝ f g : Over A k : f ⟶ g ⊢ ((fun f => coprodObj f) X✝).map k ≫ (fun g => homMk (coprod.map k✝.left (𝟙 ((𝟭 C).obj g.left)))) g = (fun g => homMk (coprod.map k✝.left (𝟙 ((𝟭 C).obj g.left)))) f ≫ ((fun f => coprodObj f) Y✝).map k [PROOFSTEP] ext [GOAL] case h C : Type u inst✝¹ : Category.{v, u} C inst✝ : HasBinaryCoproducts C A : C X✝ Y✝ : Over A k✝ : X✝ ⟶ Y✝ f g : Over A k : f ⟶ g ⊢ (((fun f => coprodObj f) X✝).map k ≫ (fun g => homMk (coprod.map k✝.left (𝟙 ((𝟭 C).obj g.left)))) g).left = ((fun g => homMk (coprod.map k✝.left (𝟙 ((𝟭 C).obj g.left)))) f ≫ ((fun f => coprodObj f) Y✝).map k).left [PROOFSTEP] dsimp [GOAL] case h C : Type u inst✝¹ : Category.{v, u} C inst✝ : HasBinaryCoproducts C A : C X✝ Y✝ : Over A k✝ : X✝ ⟶ Y✝ f g : Over A k : f ⟶ g ⊢ coprod.map (𝟙 X✝.left) k.left ≫ coprod.map k✝.left (𝟙 g.left) = coprod.map k✝.left (𝟙 f.left) ≫ coprod.map (𝟙 Y✝.left) k.left [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C inst✝ : HasBinaryCoproducts C A : C X : Over A ⊢ { obj := fun f => coprodObj f, map := fun {X Y} k => NatTrans.mk fun g => homMk (coprod.map k.left (𝟙 ((𝟭 C).obj g.left))) }.map (𝟙 X) = 𝟙 ({ obj := fun f => coprodObj f, map := fun {X Y} k => NatTrans.mk fun g => homMk (coprod.map k.left (𝟙 ((𝟭 C).obj g.left))) }.obj X) [PROOFSTEP] ext [GOAL] case w.h.h C : Type u inst✝¹ : Category.{v, u} C inst✝ : HasBinaryCoproducts C A : C X x✝ : Over A ⊢ (NatTrans.app ({ obj := fun f => coprodObj f, map := fun {X Y} k => NatTrans.mk fun g => homMk (coprod.map k.left (𝟙 ((𝟭 C).obj g.left))) }.map (𝟙 X)) x✝).left = (NatTrans.app (𝟙 ({ obj := fun f => coprodObj f, map := fun {X Y} k => NatTrans.mk fun g => homMk (coprod.map k.left (𝟙 ((𝟭 C).obj g.left))) }.obj X)) x✝).left [PROOFSTEP] dsimp [GOAL] case w.h.h C : Type u inst✝¹ : Category.{v, u} C inst✝ : HasBinaryCoproducts C A : C X x✝ : Over A ⊢ coprod.map (𝟙 X.left) (𝟙 x✝.left) = 𝟙 (X.left ⨿ x✝.left) [PROOFSTEP] simp [GOAL] C : Type u inst✝¹ : Category.{v, u} C inst✝ : HasBinaryCoproducts C A : C X✝ Y✝ Z✝ : Over A f : X✝ ⟶ Y✝ g : Y✝ ⟶ Z✝ ⊢ { obj := fun f => coprodObj f, map := fun {X Y} k => NatTrans.mk fun g => homMk (coprod.map k.left (𝟙 ((𝟭 C).obj g.left))) }.map (f ≫ g) = { obj := fun f => coprodObj f, map := fun {X Y} k => NatTrans.mk fun g => homMk (coprod.map k.left (𝟙 ((𝟭 C).obj g.left))) }.map f ≫ { obj := fun f => coprodObj f, map := fun {X Y} k => NatTrans.mk fun g => homMk (coprod.map k.left (𝟙 ((𝟭 C).obj g.left))) }.map g [PROOFSTEP] ext [GOAL] case w.h.h C : Type u inst✝¹ : Category.{v, u} C inst✝ : HasBinaryCoproducts C A : C X✝ Y✝ Z✝ : Over A f : X✝ ⟶ Y✝ g : Y✝ ⟶ Z✝ x✝ : Over A ⊢ (NatTrans.app ({ obj := fun f => coprodObj f, map := fun {X Y} k => NatTrans.mk fun g => homMk (coprod.map k.left (𝟙 ((𝟭 C).obj g.left))) }.map (f ≫ g)) x✝).left = (NatTrans.app ({ obj := fun f => coprodObj f, map := fun {X Y} k => NatTrans.mk fun g => homMk (coprod.map k.left (𝟙 ((𝟭 C).obj g.left))) }.map f ≫ { obj := fun f => coprodObj f, map := fun {X Y} k => NatTrans.mk fun g => homMk (coprod.map k.left (𝟙 ((𝟭 C).obj g.left))) }.map g) x✝).left [PROOFSTEP] dsimp [GOAL] case w.h.h C : Type u inst✝¹ : Category.{v, u} C inst✝ : HasBinaryCoproducts C A : C X✝ Y✝ Z✝ : Over A f : X✝ ⟶ Y✝ g : Y✝ ⟶ Z✝ x✝ : Over A ⊢ coprod.map (f.left ≫ g.left) (𝟙 x✝.left) = coprod.map f.left (𝟙 x✝.left) ≫ coprod.map g.left (𝟙 x✝.left) [PROOFSTEP] simp
Royal Albert 100 Years of Royal Albert 1900 Regency Blue 3-Piece Set - In celebration of Royal Albert's 100th anniversary, a specialist collection has been envisioned to commemorate the company's longevity and commitment to excellence. Each piece in the collection is decorated using a pattern and design representing some of the most iconic styles and colours of each decade. Combining patterns 240 and 241 from the Royal Albert archive, the 1900 Regency Blue 3-Piece Set features a Dessert Plate, Teacup and Tea saucer decorated in regal blue with delicate stylised maroon floral themes and delicate gold accents. This 100 Years Of Royal Albert 1900 Regency Blue 3-Piece Set y Royal Albert is the perfect addition to any home.
Lev Polugaevsky – <unk> Ftáčnik , Lucerne Olympiad 1982 : 1 . Nf3 Nf6 2 @.@ c4 c5 3 . Nc3 e6 4 @.@ g3 b6 5 . Bg2 Bb7 6 . 0 @-@ 0 Be7 7 @.@ d4 cxd4 8 . Qxd4 d6 9 . Rd1 a6 10 @.@ b3 Nbd7 11 @.@ e4 Qb8 12 . Bb2 0 @-@ 0 Suba wrote of a similar Hedgehog position , " White 's position looks ideal . That 's the naked truth about it , but the ' ideal ' has by definition one drawback — it cannot be improved . " 13 . Nd2 Rd8 14 @.@ a4 Qc7 15 . <unk> <unk> 16 . Qe2 Ne5 17 @.@ h3 ? According to Ftáčnik , <unk> <unk> <unk> is <unk> h5 ! 18 @.@ f4 Ng6 19 . Nf3 Now Black breaks open the position in typical Hedgehog <unk> d5 ! 20 @.@ cxd5 ? ! Ftáčnik considers <unk> or <unk> <unk> h4 ! 21 . Nxh4 Nxh4 22 @.@ <unk> <unk> 23 @.@ dxe6 fxe6 24 @.@ e5 ? Ftáčnik recommends instead <unk> Rxd8 <unk> Bc5 + 25 . <unk> Nh5 ! 26 . <unk> <unk> 27 . Nd5 Other moves get mated immediately : <unk> <unk> # ; <unk> Qxh3 # ; <unk> <unk> # . Rxd5 28 . Rf1 <unk> + ! 29 . <unk> Rd2 + If <unk> ( the only legal response to the double check ) , <unk> + 31.Kf4 Rf8 + forces mate . 0 – 1
From Coq Require Import ZArith List. From mathcomp Require Import ssreflect ssrbool ssrnat eqtype seq ssrfun. From BitBlasting Require Import QFBV CNF BBCommon. From ssrlib Require Import ZAriths Seqs Tactics. From nbits Require Import NBits. Set Implicit Arguments. Unset Strict Implicit. Import Prenex Implicits. (* ===== bit_blast_concat ===== *) Definition bit_blast_concat g ls1 ls0 : generator * cnf * word := (g, [::], ls0 ++ ls1) . Definition mk_env_concat E g ls1 ls0 : env * generator * cnf * word := (E, g, [::], ls0 ++ ls1) . Lemma bit_blast_concat_correct E g bs0 bs1 ls0 ls1 g' cs lr : bit_blast_concat g ls1 ls0 = (g', cs, lr) -> enc_bits E ls0 bs0 -> enc_bits E ls1 bs1 -> enc_bits E lr (cat bs0 bs1) . Proof . case => _ _ <-; exact: enc_bits_cat . Qed . Lemma mk_env_concat_is_bit_blast_concat E g ls0 ls1 E' g' cs lr : mk_env_concat E g ls1 ls0 = (E', g', cs, lr) -> bit_blast_concat g ls1 ls0 = (g', cs, lr) . Proof . rewrite /mk_env_concat /bit_blast_concat . case => _ <- <- <- // . Qed . Lemma mk_env_concat_newer_gen E g ls0 ls1 E' g' cs lr : mk_env_concat E g ls1 ls0 = (E', g', cs, lr) -> (g <=? g')%positive . Proof . rewrite /mk_env_concat; case => _ <- _ _ . t_auto_newer . Qed . Lemma mk_env_concat_newer_res E g ls0 ls1 E' g' cs lrs : mk_env_concat E g ls1 ls0 = (E', g', cs, lrs) -> newer_than_lits g ls0 -> newer_than_lits g ls1 -> newer_than_lits g' lrs . Proof . rewrite /mk_env_concat; case => _ <- _ <- Hls0 Hls1 . rewrite newer_than_lits_cat Hls0 Hls1 // . Qed . Lemma mk_env_concat_newer_cnf E g ls0 ls1 E' g' cs lrs : mk_env_concat E g ls1 ls0 = (E', g', cs, lrs) -> newer_than_lits g ls0 -> newer_than_lits g ls1 -> newer_than_cnf g' cs . Proof . rewrite /mk_env_concat; case => _ <- <- _ // . Qed . Lemma mk_env_concat_preserve E g ls0 ls1 E' g' cs lrs : mk_env_concat E g ls1 ls0 = (E', g', cs, lrs) -> env_preserve E E' g . Proof . rewrite /mk_env_concat; case => <- _ _ _ // . Qed . Lemma mk_env_concat_sat E g ls0 ls1 E' g' cs lrs : mk_env_concat E g ls1 ls0 = (E', g', cs, lrs) -> newer_than_lits g ls0 -> newer_than_lits g ls1 -> interp_cnf E' cs . Proof . rewrite /mk_env_concat; case => <- _ <- _ // . Qed . Lemma mk_env_concat_env_equal E1 E2 g ls1 ls2 E1' E2' g1' g2' cs1 cs2 lrs1 lrs2 : env_equal E1 E2 -> mk_env_concat E1 g ls1 ls2 = (E1', g1', cs1, lrs1) -> mk_env_concat E2 g ls1 ls2 = (E2', g2', cs2, lrs2) -> env_equal E1' E2' /\ g1' = g2' /\ cs1 = cs2 /\ lrs1 = lrs2. Proof. rewrite /mk_env_concat => Heq. case=> ? ? ? ?; case=> ? ? ? ?; subst. done. Qed.
function ms() global MS_START if ! @isdefined MS_START MS_START = time() end ms = round(Int, 1000*(time() - MS_START)) return (ms/1000) end function ms_reset() global MS_START = time() end macro ms(cmd) cmdstr = string(cmd) # information about the file that called this macro if isinteractive() # interactive mode => no file to call fileinfo = "(mode repl)" else # retrieve the relative name of the file that called this macro fname = string(__source__.file) fname = fname[length("$APPDIR")+2 : end] # retrieve the line number where the macro is called fline = string(__source__.line) fileinfo = "$(fname):$fline" end quote local t0 = time() print("@ms START ", round(ms(), digits=3), "s ", $fileinfo, ":", $(cmdstr)) println(" ... ") local val = $(esc(cmd)) local t1 = time() print("@ms END ", round(ms(), digits=3), "s ", $fileinfo, ":", $(cmdstr)) println(" in ", round(t1-t0, digits=3), "s") val end end # start the chronometer ms()
print("About to plot to screen.") source("do_plot.r") print("Finished plotting. Waiting 5") Sys.sleep(5) print("Goodbye.")
Paul Rodgers’ fans always want to hear his musical catalog and he delivered during his concert in Niagara Falls. A resume that includes a stint with Queen, founding member of Free, Bad Company, The Law and The Firm. Paul Rodgers, a musical innovator who has successfully reinvented himself over the course of a five-decade career. A powerhouse blues vocalist, hit songwriter and a frontman/showman helped redefine rock ‘n’ roll in the process. The Royal Sessions is his most recent release, which is a throwback of old-school blues\recording that finds Rodgers belting out tunes of the deep South soul and R&B tunes of the ‘60s and ‘70s. Blues legends such as Albert King, Muddy Waters, Dionne Warwick, Issac Hayes and Otis Redding. The concert started with Wishing Well and it hit it’s stride when Rodgers did an amazing version of Albert King’s “Born Under A Bad Side” He didn’t miss a note and it sounds like Rodgers’ voice hasn’t deteriorated after years of singing. Another highlight was doing The Firm’s “Radio Active” It was great to hear Rodgers tell a story of Jimmy Page when they were in The Firm. The encore was a fans delight as the crowd were on their feet for “Bad Company” and the finale was Free-“Alright Now” One thing you can say about Paul Rodgers is: “He’s Fan Friendly” He mingled with the crowd, shook hands, signed autographs and gave high fives to the fans. It was great to see a musician still passionate about his craft and love his fans. Hopefully Bad Company will tour again with Paul Rodgers and if possible maybe reunite with Jimmy Page for The Firm.
{-# OPTIONS --safe --warning=error --without-K #-} open import LogicalFormulae open import Groups.Definition open import Groups.Abelian.Definition open import Setoids.Setoids open import Rings.Definition open import Modules.Definition module Modules.DirectSum {a b : _} {A : Set a} {S : Setoid {a} {b} A} {_+R_ : A → A → A} {_*R_ : A → A → A} (R : Ring S _+R_ _*R_) {m n o p : _} {M : Set m} {T : Setoid {m} {n} M} {_+_ : M → M → M} {G' : Group T _+_} {G : AbelianGroup G'} {_·1_ : A → M → M} {N : Set o} {U : Setoid {o} {p} N} {_+'_ : N → N → N} {H' : Group U _+'_} {H : AbelianGroup H'} {_·2_ : A → N → N} (M1 : Module R G _·1_) (M2 : Module R H _·2_) where open import Groups.Abelian.DirectSum G H open import Setoids.Product T U directSumModule : Module R directSumAbGroup λ r mn → ((r ·1 (_&&_.fst mn)) ,, (r ·2 (_&&_.snd mn))) Module.dotWellDefined directSumModule r=s t=u = productLift (Module.dotWellDefined M1 r=s (_&&_.fst t=u)) (Module.dotWellDefined M2 r=s (_&&_.snd t=u)) Module.dotDistributesLeft directSumModule = productLift (Module.dotDistributesLeft M1) (Module.dotDistributesLeft M2) Module.dotDistributesRight directSumModule = productLift (Module.dotDistributesRight M1) (Module.dotDistributesRight M2) Module.dotAssociative directSumModule = productLift (Module.dotAssociative M1) (Module.dotAssociative M2) Module.dotIdentity directSumModule = productLift (Module.dotIdentity M1) (Module.dotIdentity M2)
module hbuffer use grid use params implicit none integer hbuf_length, HBUF_MAX_LENGTH parameter(HBUF_MAX_LENGTH = 1000) real(8) hbuf(HBUF_MAX_LENGTH*nzm+30) character(8) namelist(HBUF_MAX_LENGTH) character(80) deflist(HBUF_MAX_LENGTH) character(10) unitlist(HBUF_MAX_LENGTH) integer status(HBUF_MAX_LENGTH) integer average_type(HBUF_MAX_LENGTH) integer, external :: lenstr CONTAINS !------------------------------------------------------------ subroutine hbuf_average(n) ! Average the profiles in buffer use vars implicit none integer l, n real(8) coef coef=1./dble(n) do l = 1,hbuf_length*nzm hbuf(l) = hbuf(l) *coef end do end subroutine hbuf_average !------------------------------------------------------------ subroutine hbuf_avg_put(name, f, dimx1,dimx2,dimy1,dimy2,dimz,factor) ! Write to buffer an averaged 3D field (not to file yet) implicit none integer dimx1, dimx2, dimy1, dimy2, dimz real f(dimx1:dimx2, dimy1:dimy2, dimz), fz(nzm), factor character *(*) name integer l, begin, k logical flag flag=.false. do l = 1,hbuf_length if(.not.(lgt(name,namelist(l)).or.llt(name,namelist(l)))) then flag=.true. if(status(l).gt.0) then status(l) = 999 call averageXY(f,dimx1,dimx2,dimy1,dimy2,dimz,fz) begin = (l-1)*nzm do k = 1,nzm hbuf(begin+k) = hbuf(begin+k) + fz(k) * factor end do endif endif end do if(.not.flag.and.masterproc) print*,name end subroutine hbuf_avg_put !------------------------------------------------------------ subroutine hbuf_flush ! Flush the buffer use vars implicit none integer l,k,n do l=1,hbuf_length*nzm hbuf(l) = 0. end do do n=1,ncondavg do k=1,nzm condavg_factor(k,n) = 0. end do end do s_acld=0. s_acldl=0. s_acldm=0. s_acldh=0. s_acldcold=0. s_acldisccp=0. s_acldlisccp=0. s_acldmisccp=0. s_acldhisccp=0. s_acldmodis=0. s_acldlmodis=0. s_acldliqmodis=0. s_acldicemodis=0. s_acldhmodis=0. s_acldmodis=0. s_acldmisr=0. s_relmodis=0. s_reimodis=0. s_lwpmodis=0. s_iwpmodis=0. s_tbisccp=0. s_tbclrisccp=0. s_cldtauisccp=0. s_cldalbisccp=0. s_cldtaumodis=0. s_cldtaulmodis=0. s_cldtauimodis=0. s_ptopisccp=0. s_ptopmodis=0. s_ztopmisr=0. s_ar=0. s_arthr=0. w_max=0. u_max=0. s_flnt=0. s_flntoa=0. s_flntoac=0. s_flns=0. s_flnsc=0. s_flds=0. s_fsnt=0. s_fsntoa=0. s_fsntoac=0. s_fsns=0. s_fsnsc=0. s_fsds=0. s_solin=0. lhobs=0. shobs=0. s_sst = 0. z_inv=0. z2_inv=0. z_ct=0. z_cb=z(nzm) z_ctmn=0. z_cbmn=0. z2_cb=0. z2_ct=0. cwpmean=0. cwp2=0. prec2=0. precmax=0. precmean=0. precmean=0. ncmn=0. nrmn=0. ncloudy=0. nrainy=0. end subroutine hbuf_flush !------------------------------------------------------------ subroutine hbuf_init ! Read list of vertical profile names to store in file use grid, only: case, masterproc use tracers, only: tracers_hbuf_init implicit none character *8 nm character *80 def character *10 un integer stat,count,type,i,trcount character*3 filestatus integer n,m logical duplicate_entries open(66,file=trim(rundatadir)//'/lst',& status='old',form='formatted') ! first determine number of entries: hbuf_length = 0 111 continue read(66,err=111,end=222,fmt=*) stat,type,nm if(stat.gt.0) hbuf_length = hbuf_length+1 goto 111 222 continue if(hbuf_length.gt.HBUF_MAX_LENGTH) then print *,'Error: hbuf_length > HBUF_MAX_LENGTH.' call task_abort() endif ! fill the buffers: rewind(66) count = 0 333 continue read(66,err=333,end=444,fmt=*) stat,type,nm,def,un if(stat.gt.0) then count = count + 1 namelist(count) = nm deflist(count) = def unitlist(count) = un status(count) = stat average_type(count) = type endif goto 333 444 continue trcount=0 call hbuf_conditionals_init(count,trcount) hbuf_length = hbuf_length+trcount trcount=0 if(dotracers) call tracers_hbuf_init(namelist,deflist,unitlist,status,average_type,count,trcount) hbuf_length = hbuf_length+trcount trcount=0 if(docloud.or.dosmoke) call hbuf_micro_init(namelist,deflist,unitlist,status,average_type,count,trcount) hbuf_length = hbuf_length+trcount trcount=0 if(dosgs) call hbuf_sgs_init(namelist,deflist,unitlist,status,average_type,count,trcount) hbuf_length = hbuf_length+trcount ! check if there are dublicate entries in the stat list: duplicate_entries = .false. do n = 1,count-1 do m = n+1,count if (trim(namelist(n)).eq.trim(namelist(m))) then duplicate_entries=.true. if(masterproc) then print*,'Error: Multiple definition of '//namelist(n)// ' variable in stat list' end if end if end do end do ! Halt simulation if duplicate entries appear in namelist. if(duplicate_entries) call task_abort() if(masterproc) then print *,'Number of statistics profiles:', hbuf_length print *,'Statistics profiles to save:' write(*,'(8(a,3x))')(namelist(i),i=1,hbuf_length) ! make sure that the stat file doesn't exist if a new run to prevent ! accidental overwrite filestatus='old' if(nrestart.eq.0.or.nrestart.eq.2) then filestatus='new' end if open (55,file='./OUT_STAT/'// & case(1:lenstr(case))//'_'// & caseid(1:lenstr(caseid))//'.stat', & status=filestatus,form='unformatted') close(55) end if close (66) call hbuf_flush() end subroutine hbuf_init !----------------------------------------------------------------- subroutine hbuf_put(name, f, factor) ! Write to buffer (not to file yet) use grid, only: masterproc implicit none real f(nzm), factor character *(*) name integer l, begin, k logical flag flag=.false. do l = 1,hbuf_length if(.not.(lgt(name,namelist(l)).or.llt(name,namelist(l)))) then flag=.true. if(status(l).gt.0) then status(l) = 999 begin = (l-1)*nzm do k = 1,nzm hbuf(begin+k) = hbuf(begin+k) + f(k)*factor end do endif endif end do if(.not.flag.and.masterproc) print*,'name ', name,' is missing in "lst" file.' end subroutine hbuf_put !---------------------------------------------------------------- subroutine hbuf_write(n) ! Write buffer to file use vars implicit none integer l, k, n, ntape, length real(8) coef,aver,factor real tmp(nzm),tmp1(nzm) real(8) hbuf1(HBUF_MAX_LENGTH*nzm+100) real(4) hbuf_real4(HBUF_MAX_LENGTH*nzm+100),dummy integer nbuf real cloud_f(nzm,ncondavg), tmp_f(nzm,ncondavg) !bloss integer ncond !bloss integer nsteplast data ntape/56/ aver=1./dble(n) factor=1./dble(nx*ny) if(dompi) then ! average condavg_factor across domains. This will sum the ! weighting of all of the conditional statistics across the ! processors and allow us to normalize the statistics on each ! processor accordingly. In the end, these normalized statistics ! on each processor will sum to give the value of the conditional ! statistic. ! sum across processors call task_sum_real(condavg_factor,cloud_f,nzm*ncondavg) else cloud_f(1:nzm,1:ncondavg) = condavg_factor(1:nzm,1:ncondavg) end if ! create normalization/weighting factor for conditional statistics ! Here, cloud_f holds the sum of condavg_factor across all processors. condavg_factor(:,:) = 0. do ncond = 1,ncondavg do k=1,nzm if(ABS(cloud_f(k,ncond)).gt.EPSILON(1.)) then condavg_factor(k,ncond)=float(nsubdomains)*float(n)/cloud_f(k,ncond) end if end do end do ! compute each processor's component of the total conditional average. length = 0 do l = 1,hbuf_length if(status(l).eq. 999) then length = length+1 do ncond = 1,ncondavg if(average_type(l).eq.ncond) then do k=1,nzm hbuf((l-1)*nzm+k) = hbuf((l-1)*nzm+k)*condavg_factor(k,ncond) end do do k=1,nzm ! insert a missing value if there are no samples of this ! conditional statistic at this level. if(ABS(cloud_f(k,ncond)).lt.EPSILON(1.)) hbuf((l-1)*nzm+k) = -9999. end do endif end do endif end do ! Get statistics buffer from different processes, add them together ! and average if(dompi) then tmp1(1)=w_max tmp1(2)=u_max tmp1(3)=precmax tmp1(4)=z_ct call task_max_real(tmp1,tmp,4) w_max=tmp(1) u_max=tmp(2) precmax=tmp(3) z_ct=tmp(4) tmp1(1)=z_cb call task_min_real(tmp1,tmp,1) z_cb=tmp(1) k=hbuf_length*nzm hbuf(k+1)=s_acld hbuf(k+2)=s_acldl hbuf(k+3)=s_acldm hbuf(k+4)=s_acldh hbuf(k+5)=s_acldcold hbuf(k+6)=s_ar hbuf(k+7)=s_flns hbuf(k+8)=s_flnt hbuf(k+9)=s_flntoa hbuf(k+10)=s_flnsc hbuf(k+11)=s_flntoac hbuf(k+12)=s_flds hbuf(k+13)=s_fsns hbuf(k+14)=s_fsnt hbuf(k+15)=s_fsntoa hbuf(k+16)=s_fsnsc hbuf(k+17)=s_fsntoac hbuf(k+18)=s_fsds hbuf(k+19)=s_solin hbuf(k+20)=s_acldisccp hbuf(k+21)=s_acldlisccp hbuf(k+22)=s_acldmisccp hbuf(k+23)=s_acldhisccp hbuf(k+24)=s_sst hbuf(k+25)=s_acldmodis hbuf(k+26)=s_acldlmodis hbuf(k+27)=s_acldmmodis hbuf(k+28)=s_acldhmodis hbuf(k+29)=s_acldmisr hbuf(k+30)=s_relmodis hbuf(k+31)=s_reimodis hbuf(k+32)=s_lwpmodis hbuf(k+33)=s_iwpmodis hbuf(k+34)=s_tbisccp hbuf(k+35)=s_tbclrisccp hbuf(k+36)=s_acldliqmodis hbuf(k+37)=s_acldicemodis hbuf(k+38)=s_cldtaumodis hbuf(k+39)=s_cldtaulmodis hbuf(k+40)=s_cldtauimodis hbuf(k+41)=s_cldtauisccp hbuf(k+42)=s_cldalbisccp hbuf(k+43)=s_ptopisccp hbuf(k+44)=s_ptopmodis hbuf(k+45)=s_ztopmisr hbuf(k+46)=z_inv hbuf(k+47)=z2_inv hbuf(k+48)=ncloudy if(ncloudy.gt.0) then coef = 1./dble(ncloudy) ncloudy = 1. else coef = 0. end if hbuf(k+49)=z_cbmn*coef hbuf(k+50)=z2_cb*coef hbuf(k+51)=z_ctmn*coef hbuf(k+52)=z2_ct*coef hbuf(k+53)=cwpmean hbuf(k+54)=cwp2 hbuf(k+55)=precmean hbuf(k+56)=prec2 hbuf(k+57)=ncmn*coef hbuf(k+58)=nrainy if(nrainy.gt.0) then coef = 1./dble(nrainy) nrainy = 1. else coef = 0. end if hbuf(k+59)=nrmn*coef hbuf(k+60)=s_arthr nbuf = k+60 call task_sum_real8(hbuf,hbuf1,nbuf) coef = 1./dble(nsubdomains) hbuf(1:nbuf) = hbuf1(1:nbuf)*coef s_acld=hbuf(k+1) s_acldl=hbuf(k+2) s_acldm=hbuf(k+3) s_acldh=hbuf(k+4) s_acldcold=hbuf(k+5) s_ar=hbuf(k+6) s_flns=hbuf(k+7) s_flnt=hbuf(k+8) s_flntoa=hbuf(k+9) s_flnsc=hbuf(k+10) s_flntoac=hbuf(k+11) s_flds=hbuf(k+12) s_fsns=hbuf(k+13) s_fsnt=hbuf(k+14) s_fsntoa=hbuf(k+15) s_fsnsc=hbuf(k+16) s_fsntoac=hbuf(k+17) s_fsds=hbuf(k+18) s_solin=hbuf(k+19) s_acldisccp=hbuf(k+20) s_acldlisccp=hbuf(k+21) s_acldmisccp=hbuf(k+22) s_acldhisccp=hbuf(k+23) s_sst=hbuf(k+24) s_acldmodis=hbuf(k+25) s_acldlmodis=hbuf(k+26) s_acldmmodis=hbuf(k+27) s_acldhmodis=hbuf(k+28) s_acldmisr=hbuf(k+29) s_relmodis=hbuf(k+30) s_reimodis=hbuf(k+31) s_lwpmodis=hbuf(k+32) s_iwpmodis=hbuf(k+33) s_tbisccp=hbuf(k+34) s_tbclrisccp=hbuf(k+35) s_acldliqmodis=hbuf(k+36) s_acldicemodis=hbuf(k+37) s_cldtaumodis=hbuf(k+38) s_cldtaulmodis=hbuf(k+39) s_cldtauimodis=hbuf(k+40) s_cldtauisccp=hbuf(k+41) s_cldalbisccp=hbuf(k+42) s_ptopisccp=hbuf(k+43) s_ptopmodis=hbuf(k+44) s_ztopmisr=hbuf(k+45) z_inv=hbuf(k+46) z2_inv=hbuf(k+47) if(hbuf(k+48).gt.0) then coef=1./hbuf(k+48) else coef=1. end if z_cbmn=hbuf(k+49)*coef z2_cb=hbuf(k+50)*coef z_ctmn=hbuf(k+51)*coef z2_ct=hbuf(k+52)*coef cwpmean=hbuf(k+53) cwp2=hbuf(k+54) precmean=hbuf(k+55) prec2=hbuf(k+56) ncmn=hbuf(k+57)*coef if(hbuf(k+58).gt.0) then coef=1./hbuf(k+58) else coef=1. end if nrmn=hbuf(k+59)*coef s_arthr=hbuf(k+60) z2_inv=z2_inv*factor*aver-(z_inv*factor*aver)**2 z2_cb=z2_cb*factor-(z_cbmn*factor)**2 z2_ct=z2_ct*factor-(z_ctmn*factor)**2 cwp2=cwp2*factor*aver-(cwpmean*factor*aver)**2 prec2=prec2*factor*aver-(precmean*factor*aver)**2 endif if(masterproc) then open (ntape,file='./OUT_STAT/'// & case(1:lenstr(case))//'_'// & caseid(1:lenstr(caseid))//'.stat', & status='unknown',form='unformatted') if(nstep.ne.nstat) then do while(.true.) read(ntape, end=222) read(ntape) dummy,dummy,nsteplast if(nsteplast.ge.nstep) then backspace(ntape) backspace(ntape) ! these two lines added because of read(ntape) ! a bug in gfrotran compiler print*,'stat file at nstep ',nsteplast goto 222 ! yeh, I know, it's bad .... end if read(ntape) do l = 1,hbuf_length if(status(l).eq. 999) then read(ntape) read(ntape) read(ntape) read(ntape) end if end do end do 222 continue backspace(ntape) backspace(ntape) read(ntape) endif print *,'Writting history file ',caseid write(ntape) caseid, version write(ntape) & real(day-nstat*dt/2./86400.,4),real(dt,4),nstep,nx,ny,nz,nzm, & real(dx,4),real(dy,4),real(dz,4),real(adz,4), & real(z,4),real(pres,4),real(s_sst*aver*factor+t00,4),real(pres0,4), & real(s_acld*aver*factor,4),real(s_ar*aver*factor,4), & real(s_acldcold*aver*factor,4),real(w_max,4),real(u_max,4),-1._4,& real(s_flns*aver*factor,4),real(s_flnt*aver*factor,4),real(s_flntoa*aver*factor,4),& real(s_flnsc*aver*factor,4),real(s_flntoac*aver*factor,4),real(s_flds*aver*factor,4), & real(s_fsns*aver*factor,4),real(s_fsnt*aver*factor,4),real(s_fsntoa*aver*factor,4), & real(s_fsnsc*aver*factor,4),real(s_fsntoac*aver*factor,4), & real(s_fsds*aver*factor,4),real(s_solin*aver*factor,4), & real(sstobs,4),real(lhobs*aver,4),real(shobs*aver,4), & real(s_acldl*aver*factor,4),real(s_acldm*aver*factor,4),real(s_acldh*aver*factor,4), & real(s_acldisccp,4),real(s_acldlisccp,4),real(s_acldmisccp,4),real(s_acldhisccp,4), & real(s_acldmodis,4),real(s_acldlmodis,4),real(s_acldmmodis,4), & real(s_acldhmodis,4),real(s_acldmisr,4), & real(s_relmodis,4), real(s_reimodis,4), real(s_lwpmodis,4), & real(s_iwpmodis,4), real(s_tbisccp,4), real(s_tbclrisccp,4), & real(s_acldliqmodis,4), real(s_acldicemodis,4), real(s_cldtauisccp,4), & real(s_cldalbisccp,4), real(s_ptopisccp,4), & real(s_cldtaumodis,4), real(s_cldtaulmodis,4), real(s_cldtauimodis,4), & real(s_ptopmodis,4), real(s_ztopmisr,4), & real(z_inv*aver*factor,4), real(z2_inv,4), & real(z_ctmn*factor,4), real(z2_ct,4), real(z_ct,4), & real(z_cbmn*factor,4), real(z2_cb,4), real(z_cb,4), & real(cwpmean*aver*factor,4), real(cwp2,4), & real(precmean*aver*factor,4), real(prec2,4), real(precmax,4), & ncmn, nrmn, real(s_arthr*aver*factor,4) write(ntape) length hbuf_real4(1:hbuf_length*nzm) = hbuf(1:hbuf_length*nzm) do l = 1,hbuf_length if(status(l).eq. 999) then write(ntape) namelist(l) write(ntape) deflist(l) write(ntape) unitlist(l) write(ntape) (hbuf_real4((l-1)*nzm+k),k=1,nzm) end if end do close (ntape) end if end subroutine hbuf_write end module hbuffer
import algebra.big_operators.ring import data.real.basic import algebra.indicator_function import algebra.algebra.basic import algebra.order.nonneg /-! # Nonnegative rationals -/ noncomputable theory open_locale classical big_operators /-- Nonnegative rational numbers. -/ @[derive [canonically_ordered_comm_semiring, canonically_linear_ordered_add_monoid, linear_ordered_comm_group_with_zero, linear_ordered_semiring, has_sub, has_ordered_sub, densely_ordered, archimedean, inhabited]] def nnrat := {q : ℚ // 0 ≤ q} localized "notation ` ℚ≥0 ` := nnrat" in nnreal namespace nnrat instance : has_coe ℚ≥0 ℚ := ⟨subtype.val⟩ /- Simp lemma to put back `n.val` into the normal form given by the coercion. -/ @[simp] lemma val_eq_coe (n : ℚ≥0) : n.val = n := rfl instance : can_lift ℚ ℚ≥0 := { coe := coe, cond := λ r, 0 ≤ r, prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ } protected lemma eq {n m : ℚ≥0} : (n : ℚ) = (m : ℚ) → n = m := subtype.eq protected lemma eq_iff {n m : ℚ≥0} : (n : ℚ) = (m : ℚ) ↔ n = m := iff.intro nnrat.eq (congr_arg coe) lemma ne_iff {x y : ℚ≥0} : (x : ℚ) ≠ (y : ℚ) ↔ x ≠ y := not_iff_not_of_iff $ nnrat.eq_iff /-- Reinterpret a rational number `q` as a non-negative rational number. Returns `0` if `q < 0`. -/ protected def of_rat (q : ℚ) : ℚ≥0 := ⟨max q 0, le_max_right _ _⟩ lemma coe_of_rat (q : ℚ) (hr : 0 ≤ q) : (nnrat.of_rat q : ℚ) = q := max_eq_left hr lemma le_coe_of_rat (r : ℚ) : r ≤ nnrat.of_rat r := le_max_left r 0 lemma coe_nonneg (r : ℚ≥0) : (0 : ℚ) ≤ r := r.2 @[norm_cast] theorem coe_mk (a : ℚ) (ha) : ((⟨a, ha⟩ : ℚ≥0) : ℚ) = a := rfl protected lemma coe_injective : function.injective (coe : ℚ≥0 → ℚ) := subtype.coe_injective @[simp, norm_cast] protected lemma coe_eq {r₁ r₂ : ℚ≥0} : (r₁ : ℚ) = r₂ ↔ r₁ = r₂ := nnrat.coe_injective.eq_iff protected lemma coe_zero : ((0 : ℚ≥0) : ℚ) = 0 := rfl protected lemma coe_one : ((1 : ℚ≥0) : ℚ) = 1 := rfl protected lemma coe_add (r₁ r₂ : ℚ≥0) : ((r₁ + r₂ : ℚ≥0) : ℚ) = r₁ + r₂ := rfl protected lemma coe_mul (r₁ r₂ : ℚ≥0) : ((r₁ * r₂ : ℚ≥0) : ℚ) = r₁ * r₂ := rfl protected lemma coe_inv (r : ℚ≥0) : ((r⁻¹ : ℚ≥0) : ℚ) = r⁻¹ := rfl protected lemma coe_div (r₁ r₂ : ℚ≥0) : ((r₁ / r₂ : ℚ≥0) : ℚ) = r₁ / r₂ := rfl @[simp, norm_cast] protected lemma coe_bit0 (r : ℚ≥0) : ((bit0 r : ℚ≥0) : ℚ) = bit0 r := rfl @[simp, norm_cast] protected lemma coe_bit1 (r : ℚ≥0) : ((bit1 r : ℚ≥0) : ℚ) = bit1 r := rfl @[simp, norm_cast] protected lemma coe_sub {r₁ r₂ : ℚ≥0} (h : r₂ ≤ r₁) : ((r₁ - r₂ : ℚ≥0) : ℚ) = r₁ - r₂ := max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℚ) ≤ r₁, from h] -- TODO: setup semifield! @[simp] protected lemma coe_eq_zero (r : ℚ≥0) : ↑r = (0 : ℚ) ↔ r = 0 := by norm_cast lemma coe_ne_zero {r : ℚ≥0} : (r : ℚ) ≠ 0 ↔ r ≠ 0 := by norm_cast /-- Coercion `ℚ≥0 → ℚ` as a `ring_hom`. -/ def to_rational_hom : ℚ≥0 →+* ℚ := ⟨coe, nnrat.coe_one, nnrat.coe_mul, nnrat.coe_zero, nnrat.coe_add⟩ /-- The rational numbers are an algebra over the non-negative rationals. -/ instance : algebra ℚ≥0 ℚ := to_rational_hom.to_algebra /-- A `module` over `ℚ` restricts to a `module` over `ℚ≥0`. -/ instance {M : Type*} [add_comm_monoid M] [module ℚ M] : module ℚ≥0 M := module.comp_hom M to_rational_hom @[simp] lemma coe_to_rational_hom : ⇑to_rational_hom = coe := rfl @[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℚ≥0) (a : α) : ((s.indicator f a : ℚ≥0) : ℚ) = s.indicator (λ x, f x) a := (to_rational_hom : ℚ≥0 →+ ℚ).map_indicator _ _ _ @[simp, norm_cast] lemma coe_pow (r : ℚ≥0) (n : ℕ) : ((r^n : ℚ≥0) : ℚ) = r^n := to_rational_hom.map_pow r n @[norm_cast] lemma coe_list_sum (l : list ℚ≥0) : ((l.sum : ℚ≥0) : ℚ) = (l.map coe).sum := to_rational_hom.map_list_sum l @[norm_cast] lemma coe_list_prod (l : list ℚ≥0) : ((l.prod : ℚ≥0) : ℚ) = (l.map coe).prod := to_rational_hom.map_list_prod l @[norm_cast] lemma coe_multiset_sum (s : multiset ℚ≥0) : ((s.sum : ℚ≥0) : ℚ) = (s.map coe).sum := to_rational_hom.map_multiset_sum s @[norm_cast] lemma coe_multiset_prod (s : multiset ℚ≥0) : ((s.prod : ℚ≥0) : ℚ) = (s.map coe).prod := to_rational_hom.map_multiset_prod s @[norm_cast] lemma coe_sum {α} {s : finset α} {f : α → ℚ≥0} : ↑(∑ a in s, f a) = ∑ a in s, (f a : ℚ) := to_rational_hom.map_sum _ _ lemma of_rat_sum_of_nonneg {α} {s : finset α} {f : α → ℚ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : nnrat.of_rat (∑ a in s, f a) = ∑ a in s, nnrat.of_rat (f a) := begin rw [←nnrat.coe_eq, nnrat.coe_sum, nnrat.coe_of_rat _ (finset.sum_nonneg hf)], exact finset.sum_congr rfl (λ x hxs, by rw nnrat.coe_of_rat _ (hf x hxs)), end @[norm_cast] lemma coe_prod {α} {s : finset α} {f : α → ℚ≥0} : ↑(∏ a in s, f a) = ∏ a in s, (f a : ℚ) := to_rational_hom.map_prod _ _ lemma of_rat_prod_of_nonneg {α} {s : finset α} {f : α → ℚ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : nnrat.of_rat (∏ a in s, f a) = ∏ a in s, nnrat.of_rat (f a) := begin rw [←nnrat.coe_eq, nnrat.coe_prod, nnrat.coe_of_rat _ (finset.prod_nonneg hf)], exact finset.prod_congr rfl (λ x hxs, by rw nnrat.coe_of_rat _ (hf x hxs)), end @[norm_cast] lemma nsmul_coe (r : ℚ≥0) (n : ℕ) : ↑(n • r) = n • (r:ℚ) := to_rational_hom.to_add_monoid_hom.map_nsmul _ _ @[simp, norm_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℚ≥0) : ℚ) = n := map_nat_cast to_rational_hom n @[simp, norm_cast] protected lemma coe_le_coe {r₁ r₂ : ℚ≥0} : (r₁ : ℚ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl @[simp, norm_cast] protected lemma coe_lt_coe {r₁ r₂ : ℚ≥0} : (r₁ : ℚ) < r₂ ↔ r₁ < r₂ := iff.rfl @[simp, norm_cast] protected lemma coe_pos {r : ℚ≥0} : (0 : ℚ) < r ↔ 0 < r := iff.rfl protected lemma coe_mono : monotone (coe : ℚ≥0 → ℚ) := λ _ _, nnrat.coe_le_coe.2 protected lemma of_rat_mono : monotone nnrat.of_rat := λ x y h, max_le_max h (le_refl 0) @[simp] lemma of_rat_coe {r : ℚ≥0} : nnrat.of_rat r = r := nnrat.eq $ max_eq_left r.2 @[simp] lemma mk_coe_nat (n : ℕ) : @eq ℚ≥0 (⟨(n : ℚ), n.cast_nonneg⟩ : ℚ≥0) n := nnrat.eq (nnrat.coe_nat_cast n).symm @[simp] lemma of_rat_coe_nat (n : ℕ) : nnrat.of_rat n = n := nnrat.eq $ by simp [coe_of_rat] /-- `nnrat.of_rat` and `coe : ℚ≥0 → ℚ` form a Galois insertion. -/ protected def gi : galois_insertion nnrat.of_rat coe := galois_insertion.monotone_intro nnrat.coe_mono nnrat.of_rat_mono le_coe_of_rat (λ _, of_rat_coe) -- TODO: why are these three instances necessary? why aren't they inferred? (same for `ℝ≥0`) instance covariant_add : covariant_class ℚ≥0 ℚ≥0 (+) (≤) := ordered_add_comm_monoid.to_covariant_class_left ℚ≥0 instance contravariant_add : contravariant_class ℚ≥0 ℚ≥0 (+) (<) := ordered_cancel_add_comm_monoid.to_contravariant_class_left ℚ≥0 instance covariant_mul : covariant_class ℚ≥0 ℚ≥0 (*) (≤) := ordered_comm_monoid.to_covariant_class_left ℚ≥0 lemma bdd_above_coe {s : set ℚ≥0} : bdd_above ((coe : ℚ≥0 → ℚ) '' s) ↔ bdd_above s := iff.intro (assume ⟨b, hb⟩, ⟨nnrat.of_rat b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from le_trans (hb $ set.mem_image_of_mem _ hys) (le_max_left _ _)⟩) (assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb hx⟩) lemma bdd_below_coe (s : set ℚ≥0) : bdd_below ((coe : ℚ≥0 → ℚ) '' s) := ⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩ lemma le_of_forall_pos_le_add {a b : ℚ≥0} (h : ∀ε, 0 < ε → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense $ assume x hxb, begin rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩, exact h _ ((lt_add_iff_pos_right b).1 hxb) end -- TODO: generalize to some ordered add_monoids, based on #6145 lemma le_of_add_le_left {a b c : ℚ≥0} (h : a + b ≤ c) : a ≤ c := by { refine le_trans _ h, simp } lemma le_of_add_le_right {a b c : ℚ≥0} (h : a + b ≤ c) : b ≤ c := by { refine le_trans _ h, simp } lemma bot_eq_zero : (⊥ : ℚ≥0) = 0 := rfl lemma mul_sup (a b c : ℚ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) := begin cases le_total b c with h h, { simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] }, { simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] }, end lemma mul_finset_sup {α} {f : α → ℚ≥0} {s : finset α} (r : ℚ≥0) : r * s.sup f = s.sup (λa, r * f a) := begin refine s.induction_on _ _, { simp [bot_eq_zero] }, { assume a s has ih, simp [has, ih, mul_sup], } end @[simp, norm_cast] lemma coe_max (x y : ℚ≥0) : ((max x y : ℚ≥0) : ℚ) = max (x : ℚ) (y : ℚ) := nnrat.coe_mono.map_max @[simp, norm_cast] lemma coe_min (x y : ℚ≥0) : ((min x y : ℚ≥0) : ℚ) = min (x : ℚ) (y : ℚ) := nnrat.coe_mono.map_min section of_rat @[simp] lemma zero_le_coe {q : ℚ≥0} : 0 ≤ (q : ℚ) := q.2 @[simp] lemma of_rat_zero : nnrat.of_rat 0 = 0 := by simp [nnrat.of_rat]; refl @[simp] lemma of_rat_one : nnrat.of_rat 1 = 1 := by simp [nnrat.of_rat, max_eq_left (zero_le_one : (0 :ℚ) ≤ 1)]; refl @[simp] lemma of_rat_pos {r : ℚ} : 0 < nnrat.of_rat r ↔ 0 < r := by simp [nnrat.of_rat, nnrat.coe_lt_coe.symm, lt_irrefl] @[simp] lemma of_rat_eq_zero {r : ℚ} : nnrat.of_rat r = 0 ↔ r ≤ 0 := by simpa [-of_rat_pos] using (not_iff_not.2 (@of_rat_pos r)) lemma of_rat_of_nonpos {r : ℚ} : r ≤ 0 → nnrat.of_rat r = 0 := of_rat_eq_zero.2 @[simp] lemma of_rat_le_of_rat_iff {r p : ℚ} (hp : 0 ≤ p) : nnrat.of_rat r ≤ nnrat.of_rat p ↔ r ≤ p := by simp [nnrat.coe_le_coe.symm, nnrat.of_rat, hp] @[simp] lemma of_rat_lt_of_rat_iff' {r p : ℚ} : nnrat.of_rat r < nnrat.of_rat p ↔ r < p ∧ 0 < p := by { simp [nnrat.coe_lt_coe.symm, nnrat.of_rat, lt_irrefl], intros h0p hr0, exact hr0.trans h0p } lemma of_rat_lt_of_rat_iff {r p : ℚ} (h : 0 < p) : nnrat.of_rat r < nnrat.of_rat p ↔ r < p := of_rat_lt_of_rat_iff'.trans (and_iff_left h) lemma of_rat_lt_of_rat_iff_of_nonneg {r p : ℚ} (hr : 0 ≤ r) : nnrat.of_rat r < nnrat.of_rat p ↔ r < p := of_rat_lt_of_rat_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩ @[simp] lemma of_rat_add {r p : ℚ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnrat.of_rat (r + p) = nnrat.of_rat r + nnrat.of_rat p := nnrat.eq $ by simp [nnrat.of_rat, hr, hp, add_nonneg] lemma of_rat_add_of_rat {r p : ℚ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnrat.of_rat r + nnrat.of_rat p = nnrat.of_rat (r + p) := (of_rat_add hr hp).symm lemma of_rat_le_of_rat {r p : ℚ} (h : r ≤ p) : nnrat.of_rat r ≤ nnrat.of_rat p := nnrat.of_rat_mono h lemma of_rat_add_le {r p : ℚ} : nnrat.of_rat (r + p) ≤ nnrat.of_rat r + nnrat.of_rat p := nnrat.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnrat.zero_le_coe lemma of_rat_le_iff_le_coe {r : ℚ} {p : ℚ≥0} : nnrat.of_rat r ≤ p ↔ r ≤ ↑p := nnrat.gi.gc r p lemma le_of_rat_iff_coe_le {r : ℚ≥0} {p : ℚ} (hp : 0 ≤ p) : r ≤ nnrat.of_rat p ↔ ↑r ≤ p := by rw [← nnrat.coe_le_coe, nnrat.coe_of_rat p hp] lemma le_of_rat_iff_coe_le' {r : ℚ≥0} {p : ℚ} (hr : 0 < r) : r ≤ nnrat.of_rat p ↔ ↑r ≤ p := (le_or_lt 0 p).elim le_of_rat_iff_coe_le $ λ hp, by simp only [(hp.trans_le r.coe_nonneg).not_le, of_rat_eq_zero.2 hp.le, hr.not_le] lemma of_rat_lt_iff_lt_coe {r : ℚ} {p : ℚ≥0} (ha : 0 ≤ r) : nnrat.of_rat r < p ↔ r < ↑p := by rw [← nnrat.coe_lt_coe, nnrat.coe_of_rat r ha] lemma lt_of_rat_iff_coe_lt {r : ℚ≥0} {p : ℚ} : r < nnrat.of_rat p ↔ ↑r < p := begin cases le_total 0 p, { rw [← nnrat.coe_lt_coe, nnrat.coe_of_rat p h] }, { rw [of_rat_eq_zero.2 h], split, intro, have := not_lt_of_le (zero_le r), contradiction, intro rp, have : ¬(p ≤ 0) := not_le_of_lt (lt_of_le_of_lt (coe_nonneg _) rp), contradiction } end @[simp] lemma of_rat_bit0 {r : ℚ} (hr : 0 ≤ r) : nnrat.of_rat (bit0 r) = bit0 (nnrat.of_rat r) := of_rat_add hr hr @[simp] lemma of_rat_bit1 {r : ℚ} (hr : 0 ≤ r) : nnrat.of_rat (bit1 r) = bit1 (nnrat.of_rat r) := (of_rat_add (by simp [hr]) zero_le_one).trans (by simp [of_rat_one, bit1, hr]) end of_rat section mul lemma mul_eq_mul_left {a b c : ℚ≥0} (h : a ≠ 0) : (a * b = a * c ↔ b = c) := begin rw [← nnrat.eq_iff, ← nnrat.eq_iff, nnrat.coe_mul, nnrat.coe_mul], split, { exact mul_left_cancel₀ (mt (@nnrat.eq_iff a 0).1 h) }, { assume h, rw [h] } end lemma of_rat_mul {p q : ℚ} (hp : 0 ≤ p) : nnrat.of_rat (p * q) = nnrat.of_rat p * nnrat.of_rat q := begin cases le_total 0 q with hq hq, { apply nnrat.eq, simp [nnrat.of_rat, hp, hq, max_eq_left, mul_nonneg] }, { have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq, rw [of_rat_eq_zero.2 hq, of_rat_eq_zero.2 hpq, mul_zero] } end end mul section sub lemma sub_def {r p : ℚ≥0} : r - p = nnrat.of_rat (r - p) := rfl lemma sub_eq_zero {r p : ℚ≥0} (h : r ≤ p) : r - p = 0 := nnrat.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnrat.coe_le_coe] using h @[simp] lemma sub_self {r : ℚ≥0} : r - r = 0 := sub_eq_zero $ le_refl r @[simp] lemma sub_zero {r : ℚ≥0} : r - 0 = r := by rw [sub_def, nnrat.coe_zero, sub_zero, nnrat.of_rat_coe] lemma sub_pos {r p : ℚ≥0} : 0 < r - p ↔ p < r := of_rat_pos.trans $ sub_pos.trans $ nnrat.coe_lt_coe protected lemma sub_lt_self {r p : ℚ≥0} : 0 < r → 0 < p → r - p < r := assume hr hp, begin cases le_total r p, { rwa [sub_eq_zero h] }, { rw [← nnrat.coe_lt_coe, nnrat.coe_sub h], exact sub_lt_self _ hp } end @[simp] lemma sub_le_iff_le_add {r p q : ℚ≥0} : r - p ≤ q ↔ r ≤ q + p := match le_total p r with | or.inl h := by rw [← nnrat.coe_le_coe, ← nnrat.coe_le_coe, nnrat.coe_sub h, nnrat.coe_add, sub_le_iff_le_add] | or.inr h := have r ≤ p + q, from le_add_right h, by simpa [nnrat.coe_le_coe, nnrat.coe_le_coe, sub_eq_zero h, add_comm] end @[simp] lemma sub_le_self {r p : ℚ≥0} : r - p ≤ r := sub_le_iff_le_add.2 $ le_add_right $ le_refl r lemma add_sub_cancel {r p : ℚ≥0} : (p + r) - r = p := nnrat.eq $ by rw [nnrat.coe_sub, nnrat.coe_add, add_sub_cancel]; exact le_add_left (le_refl _) lemma add_sub_cancel' {r p : ℚ≥0} : (r + p) - r = p := by rw [add_comm, add_sub_cancel] lemma sub_add_eq_max {r p : ℚ≥0} : (r - p) + p = max r p := nnrat.eq $ by rw [sub_def, nnrat.coe_add, coe_max, nnrat.of_rat, coe_mk, ← max_add_add_right, zero_add, sub_add_cancel] lemma add_sub_eq_max {r p : ℚ≥0} : p + (r - p) = max p r := by rw [add_comm, sub_add_eq_max, max_comm] @[simp] lemma sub_add_cancel_of_le {a b : ℚ≥0} (h : b ≤ a) : (a - b) + b = a := by rw [sub_add_eq_max, max_eq_left h] lemma sub_sub_cancel_of_le {r p : ℚ≥0} (h : r ≤ p) : p - (p - r) = r := by rw [nnrat.sub_def, nnrat.sub_def, nnrat.coe_of_rat _ $ sub_nonneg.2 h, sub_sub_cancel, nnrat.of_rat_coe] lemma lt_sub_iff_add_lt {p q r : ℚ≥0} : p < q - r ↔ p + r < q := begin split, { assume H, have : (((q - r) : ℚ≥0) : ℚ) = (q : ℚ) - (r : ℚ) := nnrat.coe_sub (le_of_lt (sub_pos.1 (lt_of_le_of_lt (zero_le _) H))), rwa [← nnrat.coe_lt_coe, this, lt_sub_iff_add_lt, ← nnrat.coe_add] at H }, { assume H, have : r ≤ q := le_trans (le_add_left (le_refl _)) (le_of_lt H), rwa [← nnrat.coe_lt_coe, nnrat.coe_sub this, lt_sub_iff_add_lt, ← nnrat.coe_add] } end lemma sub_lt_iff_lt_add {a b c : ℚ≥0} (h : b ≤ a) : a - b < c ↔ a < b + c := by simp only [←nnrat.coe_lt_coe, nnrat.coe_sub h, nnrat.coe_add, sub_lt_iff_lt_add'] lemma sub_eq_iff_eq_add {a b c : ℚ≥0} (h : b ≤ a) : a - b = c ↔ a = c + b := by rw [←nnrat.eq_iff, nnrat.coe_sub h, ←nnrat.eq_iff, nnrat.coe_add, sub_eq_iff_eq_add] end sub section inv lemma sum_div {ι} (s : finset ι) (f : ι → ℚ≥0) (b : ℚ≥0) : (∑ i in s, f i) / b = ∑ i in s, (f i / b) := by simp only [div_eq_mul_inv, finset.sum_mul] @[simp] lemma inv_pos {r : ℚ≥0} : 0 < r⁻¹ ↔ 0 < r := by simp [pos_iff_ne_zero] lemma div_pos {r p : ℚ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p := by simpa only [div_eq_mul_inv] using mul_pos hr (inv_pos.2 hp) protected lemma mul_inv {r p : ℚ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnrat.eq $ mul_inv_rev _ _ lemma div_self_le (r : ℚ≥0) : r / r ≤ 1 := if h : r = 0 then by simp [h] else by rw [div_self h] @[simp] lemma inv_le {r p : ℚ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p := by rw [← mul_le_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h] lemma inv_le_of_le_mul {r p : ℚ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p := by by_cases r = 0; simp [*, inv_le] @[simp] lemma le_inv_iff_mul_le {r p : ℚ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) := by rw [← mul_le_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] @[simp] lemma lt_inv_iff_mul_lt {r p : ℚ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) := by rw [← mul_lt_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] lemma mul_le_iff_le_inv {a b r : ℚ≥0} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b := have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm, by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul] lemma le_div_iff_mul_le {a b r : ℚ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b := by rw [div_eq_inv_mul, ← mul_le_iff_le_inv hr, mul_comm] lemma div_le_iff {a b r : ℚ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ b * r := @div_le_iff ℚ _ a r b $ pos_iff_ne_zero.2 hr lemma lt_div_iff {a b r : ℚ≥0} (hr : r ≠ 0) : a < b / r ↔ a * r < b := lt_iff_lt_of_le_iff_le (div_le_iff hr) lemma mul_lt_of_lt_div {a b r : ℚ≥0} (h : a < b / r) : a * r < b := begin refine (lt_div_iff $ λ hr, false.elim _).1 h, subst r, simpa using h end lemma le_of_forall_lt_one_mul_le {x y : ℚ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y := le_of_forall_ge_of_dense $ assume a ha, have hx : x ≠ 0 := pos_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha), have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero], have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv], have (a * x⁻¹) * x ≤ y, from h _ this, by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this lemma div_add_div_same (a b c : ℚ≥0) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma half_pos {a : ℚ≥0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma add_halves (a : ℚ≥0) : a / 2 + a / 2 = a := nnrat.eq (add_halves a) lemma half_lt_self {a : ℚ≥0} (h : a ≠ 0) : a / 2 < a := by rw [← nnrat.coe_lt_coe, nnrat.coe_div]; exact half_lt_self (bot_lt_iff_ne_bot.2 h) lemma two_inv_lt_one : (2⁻¹:ℚ≥0) < 1 := by simpa using half_lt_self zero_ne_one.symm lemma div_lt_iff {a b c : ℚ≥0} (hc : c ≠ 0) : b / c < a ↔ b < a * c := lt_iff_lt_of_le_iff_le $ nnrat.le_div_iff_mul_le hc lemma div_lt_one_of_lt {a b : ℚ≥0} (h : a < b) : a / b < 1 := begin rwa [div_lt_iff, one_mul], exact ne_of_gt (lt_of_le_of_lt (zero_le _) h) end @[field_simps] lemma div_add_div (a : ℚ≥0) {b : ℚ≥0} (c : ℚ≥0) {d : ℚ≥0} (hb : b ≠ 0) (hd : d ≠ 0) : a / b + c / d = (a * d + b * c) / (b * d) := begin rw ← nnrat.eq_iff, simp only [nnrat.coe_add, nnrat.coe_div, nnrat.coe_mul], exact div_add_div _ _ (coe_ne_zero.2 hb) (coe_ne_zero.2 hd) end @[field_simps] lemma add_div' (a b c : ℚ≥0) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : ℚ≥0) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] lemma of_rat_inv {x : ℚ} : nnrat.of_rat x⁻¹ = (nnrat.of_rat x)⁻¹ := begin by_cases hx : 0 ≤ x, { nth_rewrite 0 ← coe_of_rat x hx, rw [←nnrat.coe_inv, of_rat_coe], }, { have hx' := le_of_not_ge hx, rw [of_rat_eq_zero.mpr hx', inv_zero, of_rat_eq_zero.mpr (inv_nonpos.mpr hx')], }, end lemma of_rat_div {x y : ℚ} (hx : 0 ≤ x) : nnrat.of_rat (x / y) = nnrat.of_rat x / nnrat.of_rat y := by rw [div_eq_mul_inv, div_eq_mul_inv, ←of_rat_inv, ←of_rat_mul hx] lemma of_rat_div' {x y : ℚ} (hy : 0 ≤ y) : nnrat.of_rat (x / y) = nnrat.of_rat x / nnrat.of_rat y := by rw [div_eq_inv_mul, div_eq_inv_mul, of_rat_mul (inv_nonneg.2 hy), of_rat_inv] end inv @[simp] lemma abs_eq (x : ℚ≥0) : abs (x : ℚ) = x := abs_of_nonneg x.property end nnrat /-- The absolute value on `ℚ` as a map to `ℚ≥0`. -/ @[pp_nodot] def rational.nnabs (x : ℚ) : ℚ≥0 := ⟨abs x, abs_nonneg x⟩ @[norm_cast, simp] lemma nnrat.coe_nnabs (x : ℚ) : (rational.nnabs x : ℚ) = abs x := by simp [rational.nnabs]
Formal statement is: lemma norm_power_ineq: "norm (x ^ n) \<le> norm x ^ n" for x :: "'a::real_normed_algebra_1" Informal statement is: For any real normed algebra $A$, and any $x \in A$, we have $||x^n|| \leq ||x||^n$.
(* Copyright 2018 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. *) theory msb_mem imports tasks begin text \<open>Up to two locales per function in the binary.\<close> locale msb_function = tasks_context + fixes rsp\<^sub>0 rbp\<^sub>0 a msb_ret :: \<open>64 word\<close> and v\<^sub>0 :: \<open>8 word\<close> and blocks :: \<open>(nat \<times> 64 word \<times> nat) set\<close> assumes seps: \<open>seps blocks\<close> and masters: \<open>master blocks (a, 1) 0\<close> \<open>master blocks (rsp\<^sub>0, 8) 1\<close> \<open>master blocks (rsp\<^sub>0-8, 8) 2\<close> \<open>master blocks (rsp\<^sub>0-16, 8) 3\<close> \<open>master blocks (rsp\<^sub>0-32, 8) 4\<close> and ret_address: \<open>outside msb_ret 2154 2194\<close> \<comment> \<open>Only works for non-recursive functions.\<close> begin text \<open> The Floyd invariant expresses for some locations properties that are invariably true. Simply expresses that a byte in the memory remains untouched. \<close> definition pp_\<Theta> :: floyd_invar where \<open>pp_\<Theta> \<equiv> [ \<comment> \<open>precondition\<close> boffset+2154 \<mapsto> \<lambda>\<sigma>. regs \<sigma> rsp = rsp\<^sub>0 \<and> regs \<sigma> rbp = rbp\<^sub>0 \<and> \<sigma> \<turnstile> *[rsp\<^sub>0,8] = boffset+msb_ret \<and> \<sigma> \<turnstile> *[a,1] = v\<^sub>0, boffset+2192 \<mapsto> \<lambda>\<sigma>. regs \<sigma> rsp = rsp\<^sub>0-8 \<and> regs \<sigma> rbp = rsp\<^sub>0-8 \<and> \<sigma> \<turnstile> *[rsp\<^sub>0-8,8] = rbp\<^sub>0 \<and> \<sigma> \<turnstile> *[rsp\<^sub>0,8] = boffset+msb_ret \<and> \<sigma> \<turnstile> *[a,1] = v\<^sub>0, \<comment> \<open>postcondition\<close> boffset+msb_ret \<mapsto> \<lambda>\<sigma>. \<sigma> \<turnstile> *[a,1] = v\<^sub>0 \<and> regs \<sigma> rsp = rsp\<^sub>0+8 \<and> regs \<sigma> rbp = rbp\<^sub>0 ]\<close> text \<open>Adding some rules to the simplifier to simplify proofs.\<close> schematic_goal pp_\<Theta>_zero[simp]: shows \<open>pp_\<Theta> boffset = ?x\<close> unfolding pp_\<Theta>_def by simp schematic_goal pp_\<Theta>_numeral_l[simp]: shows \<open>pp_\<Theta> (n + boffset) = ?x\<close> unfolding pp_\<Theta>_def by simp schematic_goal pp_\<Theta>_numeral_r[simp]: shows \<open>pp_\<Theta> (boffset + n) = ?x\<close> unfolding pp_\<Theta>_def by simp lemma rewrite_msb_mem: \<open>is_std_invar msb_ret (floyd.invar msb_ret pp_\<Theta>)\<close> text \<open>Boilerplate code to start the VCG\<close> apply (rule floyd_invarI) apply (rewrite at \<open>floyd_vcs msb_ret \<hole> _\<close> pp_\<Theta>_def) apply (intro floyd_vcsI) text \<open>Subgoal for rip = boffset+2154\<close> subgoal premises prems for \<sigma> text \<open>Insert relevant knowledge\<close> apply (insert prems seps ret_address) text \<open>Apply VCG/symb.\ execution\<close> apply (restart_symbolic_execution?, (symbolic_execution masters: masters)+, (finish_symbolic_execution masters: masters)?)+ done text \<open>Subgoal for rip = boffset+2192\<close> subgoal premises prems for \<sigma> text \<open>Insert relevant knowledge\<close> apply (insert prems seps ret_address) text \<open>Apply VCG/symb.\ execution\<close> apply (restart_symbolic_execution?, (symbolic_execution masters: masters)+, (finish_symbolic_execution masters: masters)?)+ done text \<open>Trivial ending subgoal.\<close> subgoal by simp done end end
module Main where import qualified Numeric.LinearAlgebra as LA import qualified MachineLearning.Types as T import qualified MachineLearning as ML import qualified MachineLearning.Classification.OneVsAll as OVA import qualified MachineLearning.PCA as PCA import qualified MachineLearning.LogisticModel as LM processFeatures :: T.Matrix -> T.Matrix processFeatures = ML.addBiasDimension . (ML.mapFeatures 2) calcAccuracy :: T.Matrix -> T.Vector -> [T.Vector] -> Double calcAccuracy x y thetas = OVA.calcAccuracy y yPredicted where yPredicted = OVA.predict x thetas printOptPath x optPath = let thetas = optPath LA.?? (LA.All, LA.Drop 2) thetas_norm = LA.col $ map (LA.norm_2) $ LA.toRows . log $ 1 - LM.sigmoid (thetas LA.<> LA.tr x) in LA.disp 3 $ (optPath LA.?? (LA.All, LA.Take 2)) LA.||| thetas_norm printInfinities x thetaList = let thetas = LA.fromColumns thetaList y :: T.Matrix y = log $ 1-LM.sigmoid (x LA.<> thetas) inf = 1/0 xList = LA.toRows x x' = LA.fromRows $ map (\(xi, _) -> xList !! xi) $ LA.find (<=(-inf)) y z = x' LA.<> thetas h = LM.sigmoid z h' = 1 - h logh = log h logh' = log h' in do putStrLn "X" LA.disp 3 x' putStrLn "Z = X * Theta" LA.disp 3 z putStrLn "h(Theta) = sigmoid(Z)" LA.disp 3 h putStrLn "1 - h(Theta)" LA.disp 3 h' putStrLn "log (h(Theta))" LA.disp 3 logh putStrLn "log (1-h(Theta))" LA.disp 3 logh' main = do -- Step 1. Data loading. -- Step 1.1 Training Data loading. (x, y) <- pure ML.splitToXY <*> LA.loadMatrix "samples/digits_classification/optdigits.tra" -- Step 1.1 Testing Data loading. (xTest, yTest) <- pure ML.splitToXY <*> LA.loadMatrix "samples/digits_classification/optdigits.tes" -- Step 2. Outputs and features preprocessing. let numLabels = 10 x' = processFeatures x (reduceDims, reducedDimensions, x1) = PCA.getDimReducer x' 10 initialTheta = LA.konst 0 (LA.cols x1) initialThetaList = replicate numLabels initialTheta -- Step 3. Learning. (thetaList, optPath) = OVA.learn (OVA.BFGS2 0.1 0.5) 0.0001 30 (OVA.L2 30) numLabels x1 y initialThetaList -- Step 4. Prediction and checking accuracy accuracyTrain = calcAccuracy x1 y thetaList accuracyTest = calcAccuracy (reduceDims $ processFeatures xTest) yTest thetaList -- Step 5. Printing results. putStrLn "\n=== Numerical Issues Demonstration ===" putStrLn $ "\nNumber of iterations to learn: " ++ show (map LA.rows optPath) putStrLn $ "\nReduced from " ++ show (LA.cols x') ++ " to " ++ show (LA.cols x1) ++ " dimensions" putStrLn "\nOptimization Paths (# iter, J(Theta), norm_2(Theta))" mapM_ (printOptPath x1) optPath print "\nDisplay numerical issues" printInfinities x1 thetaList putStrLn $ "\nAccuracy on train set (%): " ++ show (accuracyTrain*100) putStrLn $ "Accuracy on test set (%): " ++ show (accuracyTest*100)
lemma starlike_UNIV [simp]: "starlike UNIV"
function r8vec_uniform_01_test ( ) %*****************************************************************************80 % %% R8VEC_UNIFORM_01_TEST tests R8VEC_UNIFORM_01. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 14 April 2009 % % Author: % % John Burkardt % n = 10; fprintf ( 1, '\n' ); fprintf ( 1, 'R8VEC_UNIFORM_01\n' ); fprintf ( 1, ' R8VEC_UNIFORM_01 returns a random R8VEC\n' ); fprintf ( 1, ' with entries in [ 0.0, 1.0 ]\n' ); fprintf ( 1, '\n' ); seed = 123456789; for j = 1 : 3 fprintf ( 1, '\n' ); fprintf ( 1, ' Input SEED = %12d\n', seed ); fprintf ( 1, '\n' ); [ r, seed ] = r8vec_uniform_01 ( n, seed ); r8vec_print ( n, r, ' Random R8VEC:' ); end return end
[STATEMENT] lemma inj_on_proj_verts_H: "inj_on ((`) proj_verts_H) (pre_digraph.sccs_verts H)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. inj_on ((`) proj_verts_H) H.sccs_verts [PROOF STEP] proof (rule inj_onI) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x y. \<lbrakk>x \<in> H.sccs_verts; y \<in> H.sccs_verts; proj_verts_H ` x = proj_verts_H ` y\<rbrakk> \<Longrightarrow> x = y [PROOF STEP] fix S T [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x y. \<lbrakk>x \<in> H.sccs_verts; y \<in> H.sccs_verts; proj_verts_H ` x = proj_verts_H ` y\<rbrakk> \<Longrightarrow> x = y [PROOF STEP] assume A: "S \<in> H.sccs_verts" "T \<in> H.sccs_verts" "proj_verts_H ` S = proj_verts_H ` T" [PROOF STATE] proof (state) this: S \<in> H.sccs_verts T \<in> H.sccs_verts proj_verts_H ` S = proj_verts_H ` T goal (1 subgoal): 1. \<And>x y. \<lbrakk>x \<in> H.sccs_verts; y \<in> H.sccs_verts; proj_verts_H ` x = proj_verts_H ` y\<rbrakk> \<Longrightarrow> x = y [PROOF STEP] have "\<And>x. w \<notin> x \<Longrightarrow> proj_verts_H ` x = x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x. w \<notin> x \<Longrightarrow> proj_verts_H ` x = x [PROOF STEP] by (auto simp: proj_verts_H_def) [PROOF STATE] proof (state) this: w \<notin> ?x1 \<Longrightarrow> proj_verts_H ` ?x1 = ?x1 goal (1 subgoal): 1. \<And>x y. \<lbrakk>x \<in> H.sccs_verts; y \<in> H.sccs_verts; proj_verts_H ` x = proj_verts_H ` y\<rbrakk> \<Longrightarrow> x = y [PROOF STEP] with A [PROOF STATE] proof (chain) picking this: S \<in> H.sccs_verts T \<in> H.sccs_verts proj_verts_H ` S = proj_verts_H ` T w \<notin> ?x1 \<Longrightarrow> proj_verts_H ` ?x1 = ?x1 [PROOF STEP] have "S \<noteq> T \<Longrightarrow> S \<inter> T \<noteq> {}" [PROOF STATE] proof (prove) using this: S \<in> H.sccs_verts T \<in> H.sccs_verts proj_verts_H ` S = proj_verts_H ` T w \<notin> ?x1 \<Longrightarrow> proj_verts_H ` ?x1 = ?x1 goal (1 subgoal): 1. S \<noteq> T \<Longrightarrow> S \<inter> T \<noteq> {} [PROOF STEP] by (metis H.in_sccs_verts_conv_reachable Int_iff empty_iff image_eqI proj_verts_H_def w_reach(1,2)) [PROOF STATE] proof (state) this: S \<noteq> T \<Longrightarrow> S \<inter> T \<noteq> {} goal (1 subgoal): 1. \<And>x y. \<lbrakk>x \<in> H.sccs_verts; y \<in> H.sccs_verts; proj_verts_H ` x = proj_verts_H ` y\<rbrakk> \<Longrightarrow> x = y [PROOF STEP] then [PROOF STATE] proof (chain) picking this: S \<noteq> T \<Longrightarrow> S \<inter> T \<noteq> {} [PROOF STEP] show "S = T" [PROOF STATE] proof (prove) using this: S \<noteq> T \<Longrightarrow> S \<inter> T \<noteq> {} goal (1 subgoal): 1. S = T [PROOF STEP] using H.sccs_verts_disjoint[OF A(1,2)] [PROOF STATE] proof (prove) using this: S \<noteq> T \<Longrightarrow> S \<inter> T \<noteq> {} S \<noteq> T \<Longrightarrow> S \<inter> T = {} goal (1 subgoal): 1. S = T [PROOF STEP] by metis [PROOF STATE] proof (state) this: S = T goal: No subgoals! [PROOF STEP] qed
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro ! This file was ported from Lean 3 source module topology.separation ! leanprover-community/mathlib commit 195fcd60ff2bfe392543bceb0ec2adcdb472db4c ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Topology.SubsetProperties import Mathbin.Topology.Connected import Mathbin.Topology.NhdsSet import Mathbin.Topology.Inseparable /-! # Separation properties of topological spaces. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the predicate `separated_nhds`, and common separation axioms (under the Kolmogorov classification). ## Main definitions * `separated_nhds`: Two `set`s are separated by neighbourhoods if they are contained in disjoint open sets. * `t0_space`: A T₀/Kolmogorov space is a space where, for every two points `x ≠ y`, there is an open set that contains one, but not the other. * `t1_space`: A T₁/Fréchet space is a space where every singleton set is closed. This is equivalent to, for every pair `x ≠ y`, there existing an open set containing `x` but not `y` (`t1_space_iff_exists_open` shows that these conditions are equivalent.) * `t2_space`: A T₂/Hausdorff space is a space where, for every two points `x ≠ y`, there is two disjoint open sets, one containing `x`, and the other `y`. * `t2_5_space`: A T₂.₅/Urysohn space is a space where, for every two points `x ≠ y`, there is two open sets, one containing `x`, and the other `y`, whose closures are disjoint. * `t3_space`: A T₃ space, is one where given any closed `C` and `x ∉ C`, there is disjoint open sets containing `x` and `C` respectively. In `mathlib`, T₃ implies T₂.₅. * `normal_space`: A T₄ space (sometimes referred to as normal, but authors vary on whether this includes T₂; `mathlib` does), is one where given two disjoint closed sets, we can find two open sets that separate them. In `mathlib`, T₄ implies T₃. * `t5_space`: A T₅ space, also known as a *completely normal Hausdorff space* ## Main results ### T₀ spaces * `is_closed.exists_closed_singleton` Given a closed set `S` in a compact T₀ space, there is some `x ∈ S` such that `{x}` is closed. * `exists_open_singleton_of_open_finset` Given an open `finset` `S` in a T₀ space, there is some `x ∈ S` such that `{x}` is open. ### T₁ spaces * `is_closed_map_const`: The constant map is a closed map. * `discrete_of_t1_of_finite`: A finite T₁ space must have the discrete topology. ### T₂ spaces * `t2_iff_nhds`: A space is T₂ iff the neighbourhoods of distinct points generate the bottom filter. * `t2_iff_is_closed_diagonal`: A space is T₂ iff the `diagonal` of `α` (that is, the set of all points of the form `(a, a) : α × α`) is closed under the product topology. * `finset_disjoint_finset_opens_of_t2`: Any two disjoint finsets are `separated_nhds`. * Most topological constructions preserve Hausdorffness; these results are part of the typeclass inference system (e.g. `embedding.t2_space`) * `set.eq_on.closure`: If two functions are equal on some set `s`, they are equal on its closure. * `is_compact.is_closed`: All compact sets are closed. * `locally_compact_of_compact_nhds`: If every point has a compact neighbourhood, then the space is locally compact. * `totally_separated_space_of_t1_of_basis_clopen`: If `α` has a clopen basis, then it is a `totally_separated_space`. * `loc_compact_t2_tot_disc_iff_tot_sep`: A locally compact T₂ space is totally disconnected iff it is totally separated. If the space is also compact: * `normal_of_compact_t2`: A compact T₂ space is a `normal_space`. * `connected_components_eq_Inter_clopen`: The connected component of a point is the intersection of all its clopen neighbourhoods. * `compact_t2_tot_disc_iff_tot_sep`: Being a `totally_disconnected_space` is equivalent to being a `totally_separated_space`. * `connected_components.t2`: `connected_components α` is T₂ for `α` T₂ and compact. ### T₃ spaces * `disjoint_nested_nhds`: Given two points `x ≠ y`, we can find neighbourhoods `x ∈ V₁ ⊆ U₁` and `y ∈ V₂ ⊆ U₂`, with the `Vₖ` closed and the `Uₖ` open, such that the `Uₖ` are disjoint. ## References https://en.wikipedia.org/wiki/Separation_axiom -/ open Function Set Filter TopologicalSpace open Topology Filter Classical universe u v variable {α : Type u} {β : Type v} [TopologicalSpace α] section Separation #print SeparatedNhds /- /-- `separated_nhds` is a predicate on pairs of sub`set`s of a topological space. It holds if the two sub`set`s are contained in disjoint open sets. -/ def SeparatedNhds : Set α → Set α → Prop := fun s t : Set α => ∃ U V : Set α, IsOpen U ∧ IsOpen V ∧ s ⊆ U ∧ t ⊆ V ∧ Disjoint U V #align separated_nhds SeparatedNhds -/ /- warning: separated_nhds_iff_disjoint -> separatedNhds_iff_disjoint is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α}, Iff (SeparatedNhds.{u1} α _inst_1 s t) (Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) (nhdsSet.{u1} α _inst_1 s) (nhdsSet.{u1} α _inst_1 t)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α}, Iff (SeparatedNhds.{u1} α _inst_1 s t) (Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) (nhdsSet.{u1} α _inst_1 s) (nhdsSet.{u1} α _inst_1 t)) Case conversion may be inaccurate. Consider using '#align separated_nhds_iff_disjoint separatedNhds_iff_disjointₓ'. -/ theorem separatedNhds_iff_disjoint {s t : Set α} : SeparatedNhds s t ↔ Disjoint (𝓝ˢ s) (𝓝ˢ t) := by simp only [(hasBasis_nhdsSet s).disjoint_iff (hasBasis_nhdsSet t), SeparatedNhds, exists_prop, ← exists_and_left, and_assoc, and_comm, and_left_comm] #align separated_nhds_iff_disjoint separatedNhds_iff_disjoint namespace SeparatedNhds variable {s s₁ s₂ t t₁ t₂ u : Set α} #print SeparatedNhds.symm /- @[symm] theorem symm : SeparatedNhds s t → SeparatedNhds t s := fun ⟨U, V, oU, oV, aU, bV, UV⟩ => ⟨V, U, oV, oU, bV, aU, Disjoint.symm UV⟩ #align separated_nhds.symm SeparatedNhds.symm -/ #print SeparatedNhds.comm /- theorem comm (s t : Set α) : SeparatedNhds s t ↔ SeparatedNhds t s := ⟨symm, symm⟩ #align separated_nhds.comm SeparatedNhds.comm -/ #print SeparatedNhds.preimage /- theorem preimage [TopologicalSpace β] {f : α → β} {s t : Set β} (h : SeparatedNhds s t) (hf : Continuous f) : SeparatedNhds (f ⁻¹' s) (f ⁻¹' t) := let ⟨U, V, oU, oV, sU, tV, UV⟩ := h ⟨f ⁻¹' U, f ⁻¹' V, oU.Preimage hf, oV.Preimage hf, preimage_mono sU, preimage_mono tV, UV.Preimage f⟩ #align separated_nhds.preimage SeparatedNhds.preimage -/ /- warning: separated_nhds.disjoint -> SeparatedNhds.disjoint is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α}, (SeparatedNhds.{u1} α _inst_1 s t) -> (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α}, (SeparatedNhds.{u1} α _inst_1 s t) -> (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) s t) Case conversion may be inaccurate. Consider using '#align separated_nhds.disjoint SeparatedNhds.disjointₓ'. -/ protected theorem disjoint (h : SeparatedNhds s t) : Disjoint s t := let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h hd.mono hsU htV #align separated_nhds.disjoint SeparatedNhds.disjoint /- warning: separated_nhds.disjoint_closure_left -> SeparatedNhds.disjoint_closure_left is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α}, (SeparatedNhds.{u1} α _inst_1 s t) -> (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (closure.{u1} α _inst_1 s) t) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α}, (SeparatedNhds.{u1} α _inst_1 s t) -> (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (closure.{u1} α _inst_1 s) t) Case conversion may be inaccurate. Consider using '#align separated_nhds.disjoint_closure_left SeparatedNhds.disjoint_closure_leftₓ'. -/ theorem disjoint_closure_left (h : SeparatedNhds s t) : Disjoint (closure s) t := let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h (hd.closure_left hV).mono (closure_mono hsU) htV #align separated_nhds.disjoint_closure_left SeparatedNhds.disjoint_closure_left /- warning: separated_nhds.disjoint_closure_right -> SeparatedNhds.disjoint_closure_right is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α}, (SeparatedNhds.{u1} α _inst_1 s t) -> (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s (closure.{u1} α _inst_1 t)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α}, (SeparatedNhds.{u1} α _inst_1 s t) -> (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) s (closure.{u1} α _inst_1 t)) Case conversion may be inaccurate. Consider using '#align separated_nhds.disjoint_closure_right SeparatedNhds.disjoint_closure_rightₓ'. -/ theorem disjoint_closure_right (h : SeparatedNhds s t) : Disjoint s (closure t) := h.symm.disjoint_closure_left.symm #align separated_nhds.disjoint_closure_right SeparatedNhds.disjoint_closure_right #print SeparatedNhds.empty_right /- theorem empty_right (s : Set α) : SeparatedNhds s ∅ := ⟨_, _, isOpen_univ, isOpen_empty, fun a h => mem_univ a, fun a h => by cases h, disjoint_empty _⟩ #align separated_nhds.empty_right SeparatedNhds.empty_right -/ #print SeparatedNhds.empty_left /- theorem empty_left (s : Set α) : SeparatedNhds ∅ s := (empty_right _).symm #align separated_nhds.empty_left SeparatedNhds.empty_left -/ #print SeparatedNhds.mono /- theorem mono (h : SeparatedNhds s₂ t₂) (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : SeparatedNhds s₁ t₁ := let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h ⟨U, V, hU, hV, hs.trans hsU, ht.trans htV, hd⟩ #align separated_nhds.mono SeparatedNhds.mono -/ /- warning: separated_nhds.union_left -> SeparatedNhds.union_left is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (SeparatedNhds.{u1} α _inst_1 s u) -> (SeparatedNhds.{u1} α _inst_1 t u) -> (SeparatedNhds.{u1} α _inst_1 (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) s t) u) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (SeparatedNhds.{u1} α _inst_1 s u) -> (SeparatedNhds.{u1} α _inst_1 t u) -> (SeparatedNhds.{u1} α _inst_1 (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) s t) u) Case conversion may be inaccurate. Consider using '#align separated_nhds.union_left SeparatedNhds.union_leftₓ'. -/ theorem union_left : SeparatedNhds s u → SeparatedNhds t u → SeparatedNhds (s ∪ t) u := by simpa only [separatedNhds_iff_disjoint, nhdsSet_union, disjoint_sup_left] using And.intro #align separated_nhds.union_left SeparatedNhds.union_left /- warning: separated_nhds.union_right -> SeparatedNhds.union_right is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (SeparatedNhds.{u1} α _inst_1 s t) -> (SeparatedNhds.{u1} α _inst_1 s u) -> (SeparatedNhds.{u1} α _inst_1 s (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) t u)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} {t : Set.{u1} α} {u : Set.{u1} α}, (SeparatedNhds.{u1} α _inst_1 s t) -> (SeparatedNhds.{u1} α _inst_1 s u) -> (SeparatedNhds.{u1} α _inst_1 s (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) t u)) Case conversion may be inaccurate. Consider using '#align separated_nhds.union_right SeparatedNhds.union_rightₓ'. -/ theorem union_right (ht : SeparatedNhds s t) (hu : SeparatedNhds s u) : SeparatedNhds s (t ∪ u) := (ht.symm.union_left hu.symm).symm #align separated_nhds.union_right SeparatedNhds.union_right end SeparatedNhds #print T0Space /- /-- A T₀ space, also known as a Kolmogorov space, is a topological space such that for every pair `x ≠ y`, there is an open set containing one but not the other. We formulate the definition in terms of the `inseparable` relation. -/ class T0Space (α : Type u) [TopologicalSpace α] : Prop where t0 : ∀ ⦃x y : α⦄, Inseparable x y → x = y #align t0_space T0Space -/ #print t0Space_iff_inseparable /- theorem t0Space_iff_inseparable (α : Type u) [TopologicalSpace α] : T0Space α ↔ ∀ x y : α, Inseparable x y → x = y := ⟨fun ⟨h⟩ => h, fun h => ⟨h⟩⟩ #align t0_space_iff_inseparable t0Space_iff_inseparable -/ #print t0Space_iff_not_inseparable /- theorem t0Space_iff_not_inseparable (α : Type u) [TopologicalSpace α] : T0Space α ↔ ∀ x y : α, x ≠ y → ¬Inseparable x y := by simp only [t0Space_iff_inseparable, Ne.def, not_imp_not] #align t0_space_iff_not_inseparable t0Space_iff_not_inseparable -/ #print Inseparable.eq /- theorem Inseparable.eq [T0Space α] {x y : α} (h : Inseparable x y) : x = y := T0Space.t0 h #align inseparable.eq Inseparable.eq -/ #print Inducing.injective /- protected theorem Inducing.injective [TopologicalSpace β] [T0Space α] {f : α → β} (hf : Inducing f) : Injective f := fun x y h => Inseparable.eq <| hf.inseparable_iff.1 <| h ▸ Inseparable.refl _ #align inducing.injective Inducing.injective -/ #print Inducing.embedding /- protected theorem Inducing.embedding [TopologicalSpace β] [T0Space α] {f : α → β} (hf : Inducing f) : Embedding f := ⟨hf, hf.Injective⟩ #align inducing.embedding Inducing.embedding -/ #print embedding_iff_inducing /- theorem embedding_iff_inducing [TopologicalSpace β] [T0Space α] {f : α → β} : Embedding f ↔ Inducing f := ⟨Embedding.to_inducing, Inducing.embedding⟩ #align embedding_iff_inducing embedding_iff_inducing -/ #print t0Space_iff_nhds_injective /- theorem t0Space_iff_nhds_injective (α : Type u) [TopologicalSpace α] : T0Space α ↔ Injective (𝓝 : α → Filter α) := t0Space_iff_inseparable α #align t0_space_iff_nhds_injective t0Space_iff_nhds_injective -/ #print nhds_injective /- theorem nhds_injective [T0Space α] : Injective (𝓝 : α → Filter α) := (t0Space_iff_nhds_injective α).1 ‹_› #align nhds_injective nhds_injective -/ #print inseparable_iff_eq /- theorem inseparable_iff_eq [T0Space α] {x y : α} : Inseparable x y ↔ x = y := nhds_injective.eq_iff #align inseparable_iff_eq inseparable_iff_eq -/ #print nhds_eq_nhds_iff /- @[simp] theorem nhds_eq_nhds_iff [T0Space α] {a b : α} : 𝓝 a = 𝓝 b ↔ a = b := nhds_injective.eq_iff #align nhds_eq_nhds_iff nhds_eq_nhds_iff -/ #print inseparable_eq_eq /- @[simp] theorem inseparable_eq_eq [T0Space α] : Inseparable = @Eq α := funext₂ fun x y => propext inseparable_iff_eq #align inseparable_eq_eq inseparable_eq_eq -/ #print t0Space_iff_exists_isOpen_xor'_mem /- theorem t0Space_iff_exists_isOpen_xor'_mem (α : Type u) [TopologicalSpace α] : T0Space α ↔ ∀ x y, x ≠ y → ∃ U : Set α, IsOpen U ∧ Xor' (x ∈ U) (y ∈ U) := by simp only [t0Space_iff_not_inseparable, xor_iff_not_iff, not_forall, exists_prop, inseparable_iff_forall_open] #align t0_space_iff_exists_is_open_xor_mem t0Space_iff_exists_isOpen_xor'_mem -/ #print exists_isOpen_xor'_mem /- theorem exists_isOpen_xor'_mem [T0Space α] {x y : α} (h : x ≠ y) : ∃ U : Set α, IsOpen U ∧ Xor' (x ∈ U) (y ∈ U) := (t0Space_iff_exists_isOpen_xor'_mem α).1 ‹_› x y h #align exists_is_open_xor_mem exists_isOpen_xor'_mem -/ #print specializationOrder /- /-- Specialization forms a partial order on a t0 topological space. -/ def specializationOrder (α : Type _) [TopologicalSpace α] [T0Space α] : PartialOrder α := { specializationPreorder α, PartialOrder.lift (OrderDual.toDual ∘ 𝓝) nhds_injective with } #align specialization_order specializationOrder -/ instance : T0Space (SeparationQuotient α) := ⟨fun x' y' => Quotient.inductionOn₂' x' y' fun x y h => SeparationQuotient.mk_eq_mk.2 <| SeparationQuotient.inducing_mk.inseparable_iff.1 h⟩ /- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (t «expr ⊆ » s) -/ #print minimal_nonempty_closed_subsingleton /- theorem minimal_nonempty_closed_subsingleton [T0Space α] {s : Set α} (hs : IsClosed s) (hmin : ∀ (t) (_ : t ⊆ s), t.Nonempty → IsClosed t → t = s) : s.Subsingleton := by refine' fun x hx y hy => of_not_not fun hxy => _ rcases exists_isOpen_xor'_mem hxy with ⟨U, hUo, hU⟩ wlog h : x ∈ U ∧ y ∉ U · exact this hmin y hy x hx (Ne.symm hxy) U hUo hU.symm (hU.resolve_left h) cases' h with hxU hyU have : s \ U = s := hmin (s \ U) (diff_subset _ _) ⟨y, hy, hyU⟩ (hs.sdiff hUo) exact (this.symm.subset hx).2 hxU #align minimal_nonempty_closed_subsingleton minimal_nonempty_closed_subsingleton -/ /- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (t «expr ⊆ » s) -/ #print minimal_nonempty_closed_eq_singleton /- theorem minimal_nonempty_closed_eq_singleton [T0Space α] {s : Set α} (hs : IsClosed s) (hne : s.Nonempty) (hmin : ∀ (t) (_ : t ⊆ s), t.Nonempty → IsClosed t → t = s) : ∃ x, s = {x} := exists_eq_singleton_iff_nonempty_subsingleton.2 ⟨hne, minimal_nonempty_closed_subsingleton hs hmin⟩ #align minimal_nonempty_closed_eq_singleton minimal_nonempty_closed_eq_singleton -/ #print IsClosed.exists_closed_singleton /- /-- Given a closed set `S` in a compact T₀ space, there is some `x ∈ S` such that `{x}` is closed. -/ theorem IsClosed.exists_closed_singleton {α : Type _} [TopologicalSpace α] [T0Space α] [CompactSpace α] {S : Set α} (hS : IsClosed S) (hne : S.Nonempty) : ∃ x : α, x ∈ S ∧ IsClosed ({x} : Set α) := by obtain ⟨V, Vsub, Vne, Vcls, hV⟩ := hS.exists_minimal_nonempty_closed_subset hne rcases minimal_nonempty_closed_eq_singleton Vcls Vne hV with ⟨x, rfl⟩ exact ⟨x, Vsub (mem_singleton x), Vcls⟩ #align is_closed.exists_closed_singleton IsClosed.exists_closed_singleton -/ /- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (t «expr ⊆ » s) -/ #print minimal_nonempty_open_subsingleton /- theorem minimal_nonempty_open_subsingleton [T0Space α] {s : Set α} (hs : IsOpen s) (hmin : ∀ (t) (_ : t ⊆ s), t.Nonempty → IsOpen t → t = s) : s.Subsingleton := by refine' fun x hx y hy => of_not_not fun hxy => _ rcases exists_isOpen_xor'_mem hxy with ⟨U, hUo, hU⟩ wlog h : x ∈ U ∧ y ∉ U · exact this hs hmin y hy x hx (Ne.symm hxy) U hUo hU.symm (hU.resolve_left h) cases' h with hxU hyU have : s ∩ U = s := hmin (s ∩ U) (inter_subset_left _ _) ⟨x, hx, hxU⟩ (hs.inter hUo) exact hyU (this.symm.subset hy).2 #align minimal_nonempty_open_subsingleton minimal_nonempty_open_subsingleton -/ /- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (t «expr ⊆ » s) -/ #print minimal_nonempty_open_eq_singleton /- theorem minimal_nonempty_open_eq_singleton [T0Space α] {s : Set α} (hs : IsOpen s) (hne : s.Nonempty) (hmin : ∀ (t) (_ : t ⊆ s), t.Nonempty → IsOpen t → t = s) : ∃ x, s = {x} := exists_eq_singleton_iff_nonempty_subsingleton.2 ⟨hne, minimal_nonempty_open_subsingleton hs hmin⟩ #align minimal_nonempty_open_eq_singleton minimal_nonempty_open_eq_singleton -/ /- warning: exists_open_singleton_of_open_finite -> exists_open_singleton_of_open_finite is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T0Space.{u1} α _inst_1] {s : Set.{u1} α}, (Set.Finite.{u1} α s) -> (Set.Nonempty.{u1} α s) -> (IsOpen.{u1} α _inst_1 s) -> (Exists.{succ u1} α (fun (x : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) (fun (H : Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) => IsOpen.{u1} α _inst_1 (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T0Space.{u1} α _inst_1] {s : Set.{u1} α}, (Set.Finite.{u1} α s) -> (Set.Nonempty.{u1} α s) -> (IsOpen.{u1} α _inst_1 s) -> (Exists.{succ u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) (IsOpen.{u1} α _inst_1 (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)))) Case conversion may be inaccurate. Consider using '#align exists_open_singleton_of_open_finite exists_open_singleton_of_open_finiteₓ'. -/ /- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (t «expr ⊂ » s) -/ /-- Given an open finite set `S` in a T₀ space, there is some `x ∈ S` such that `{x}` is open. -/ theorem exists_open_singleton_of_open_finite [T0Space α] {s : Set α} (hfin : s.Finite) (hne : s.Nonempty) (ho : IsOpen s) : ∃ x ∈ s, IsOpen ({x} : Set α) := by lift s to Finset α using hfin induction' s using Finset.strongInductionOn with s ihs rcases em (∃ (t : _)(_ : t ⊂ s), t.Nonempty ∧ IsOpen (t : Set α)) with (⟨t, hts, htne, hto⟩ | ht) · rcases ihs t hts htne hto with ⟨x, hxt, hxo⟩ exact ⟨x, hts.1 hxt, hxo⟩ · rcases minimal_nonempty_open_eq_singleton ho hne _ with ⟨x, hx⟩ · exact ⟨x, hx.symm ▸ rfl, hx ▸ ho⟩ refine' fun t hts htne hto => of_not_not fun hts' => ht _ lift t to Finset α using s.finite_to_set.subset hts exact ⟨t, ssubset_iff_subset_ne.2 ⟨hts, mt Finset.coe_inj.2 hts'⟩, htne, hto⟩ #align exists_open_singleton_of_open_finite exists_open_singleton_of_open_finite #print exists_open_singleton_of_finite /- theorem exists_open_singleton_of_finite [T0Space α] [Finite α] [Nonempty α] : ∃ x : α, IsOpen ({x} : Set α) := let ⟨x, _, h⟩ := exists_open_singleton_of_open_finite (Set.toFinite _) univ_nonempty isOpen_univ ⟨x, h⟩ #align exists_open_singleton_of_fintype exists_open_singleton_of_finite -/ #print t0Space_of_injective_of_continuous /- theorem t0Space_of_injective_of_continuous [TopologicalSpace β] {f : α → β} (hf : Function.Injective f) (hf' : Continuous f) [T0Space β] : T0Space α := ⟨fun x y h => hf <| (h.map hf').Eq⟩ #align t0_space_of_injective_of_continuous t0Space_of_injective_of_continuous -/ #print Embedding.t0Space /- protected theorem Embedding.t0Space [TopologicalSpace β] [T0Space β] {f : α → β} (hf : Embedding f) : T0Space α := t0Space_of_injective_of_continuous hf.inj hf.Continuous #align embedding.t0_space Embedding.t0Space -/ #print Subtype.t0Space /- instance Subtype.t0Space [T0Space α] {p : α → Prop} : T0Space (Subtype p) := embedding_subtype_val.T0Space #align subtype.t0_space Subtype.t0Space -/ #print t0Space_iff_or_not_mem_closure /- theorem t0Space_iff_or_not_mem_closure (α : Type u) [TopologicalSpace α] : T0Space α ↔ ∀ a b : α, a ≠ b → a ∉ closure ({b} : Set α) ∨ b ∉ closure ({a} : Set α) := by simp only [t0Space_iff_not_inseparable, inseparable_iff_mem_closure, not_and_or] #align t0_space_iff_or_not_mem_closure t0Space_iff_or_not_mem_closure -/ instance [TopologicalSpace β] [T0Space α] [T0Space β] : T0Space (α × β) := ⟨fun x y h => Prod.ext (h.map continuous_fst).Eq (h.map continuous_snd).Eq⟩ instance {ι : Type _} {π : ι → Type _} [∀ i, TopologicalSpace (π i)] [∀ i, T0Space (π i)] : T0Space (∀ i, π i) := ⟨fun x y h => funext fun i => (h.map (continuous_apply i)).Eq⟩ #print T0Space.of_cover /- theorem T0Space.of_cover (h : ∀ x y, Inseparable x y → ∃ s : Set α, x ∈ s ∧ y ∈ s ∧ T0Space s) : T0Space α := by refine' ⟨fun x y hxy => _⟩ rcases h x y hxy with ⟨s, hxs, hys, hs⟩; skip lift x to s using hxs; lift y to s using hys rw [← subtype_inseparable_iff] at hxy exact congr_arg coe hxy.eq #align t0_space.of_cover T0Space.of_cover -/ #print T0Space.of_open_cover /- theorem T0Space.of_open_cover (h : ∀ x, ∃ s : Set α, x ∈ s ∧ IsOpen s ∧ T0Space s) : T0Space α := T0Space.of_cover fun x y hxy => let ⟨s, hxs, hso, hs⟩ := h x ⟨s, hxs, (hxy.mem_open_iff hso).1 hxs, hs⟩ #align t0_space.of_open_cover T0Space.of_open_cover -/ #print T1Space /- /-- A T₁ space, also known as a Fréchet space, is a topological space where every singleton set is closed. Equivalently, for every pair `x ≠ y`, there is an open set containing `x` and not `y`. -/ class T1Space (α : Type u) [TopologicalSpace α] : Prop where t1 : ∀ x, IsClosed ({x} : Set α) #align t1_space T1Space -/ #print isClosed_singleton /- theorem isClosed_singleton [T1Space α] {x : α} : IsClosed ({x} : Set α) := T1Space.t1 x #align is_closed_singleton isClosed_singleton -/ /- warning: is_open_compl_singleton -> isOpen_compl_singleton is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α}, IsOpen.{u1} α _inst_1 (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α}, IsOpen.{u1} α _inst_1 (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)) Case conversion may be inaccurate. Consider using '#align is_open_compl_singleton isOpen_compl_singletonₓ'. -/ theorem isOpen_compl_singleton [T1Space α] {x : α} : IsOpen ({x}ᶜ : Set α) := isClosed_singleton.isOpen_compl #align is_open_compl_singleton isOpen_compl_singleton #print isOpen_ne /- theorem isOpen_ne [T1Space α] {x : α} : IsOpen { y | y ≠ x } := isOpen_compl_singleton #align is_open_ne isOpen_ne -/ #print Continuous.isOpen_mulSupport /- @[to_additive] theorem Continuous.isOpen_mulSupport [T1Space α] [One α] [TopologicalSpace β] {f : β → α} (hf : Continuous f) : IsOpen (mulSupport f) := isOpen_ne.Preimage hf #align continuous.is_open_mul_support Continuous.isOpen_mulSupport #align continuous.is_open_support Continuous.isOpen_support -/ /- warning: ne.nhds_within_compl_singleton -> Ne.nhdsWithin_compl_singleton is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Eq.{succ u1} (Filter.{u1} α) (nhdsWithin.{u1} α _inst_1 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) y))) (nhds.{u1} α _inst_1 x)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Eq.{succ u1} (Filter.{u1} α) (nhdsWithin.{u1} α _inst_1 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) y))) (nhds.{u1} α _inst_1 x)) Case conversion may be inaccurate. Consider using '#align ne.nhds_within_compl_singleton Ne.nhdsWithin_compl_singletonₓ'. -/ theorem Ne.nhdsWithin_compl_singleton [T1Space α] {x y : α} (h : x ≠ y) : 𝓝[{y}ᶜ] x = 𝓝 x := isOpen_ne.nhdsWithin_eq h #align ne.nhds_within_compl_singleton Ne.nhdsWithin_compl_singleton /- warning: ne.nhds_within_diff_singleton -> Ne.nhdsWithin_diff_singleton is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (forall (s : Set.{u1} α), Eq.{succ u1} (Filter.{u1} α) (nhdsWithin.{u1} α _inst_1 x (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) y))) (nhdsWithin.{u1} α _inst_1 x s)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (forall (s : Set.{u1} α), Eq.{succ u1} (Filter.{u1} α) (nhdsWithin.{u1} α _inst_1 x (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) y))) (nhdsWithin.{u1} α _inst_1 x s)) Case conversion may be inaccurate. Consider using '#align ne.nhds_within_diff_singleton Ne.nhdsWithin_diff_singletonₓ'. -/ theorem Ne.nhdsWithin_diff_singleton [T1Space α] {x y : α} (h : x ≠ y) (s : Set α) : 𝓝[s \ {y}] x = 𝓝[s] x := by rw [diff_eq, inter_comm, nhdsWithin_inter_of_mem] exact mem_nhdsWithin_of_mem_nhds (is_open_ne.mem_nhds h) #align ne.nhds_within_diff_singleton Ne.nhdsWithin_diff_singleton /- warning: is_open_set_of_eventually_nhds_within -> isOpen_setOf_eventually_nhdsWithin is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {p : α -> Prop}, IsOpen.{u1} α _inst_1 (setOf.{u1} α (fun (x : α) => Filter.Eventually.{u1} α (fun (y : α) => p y) (nhdsWithin.{u1} α _inst_1 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x))))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {p : α -> Prop}, IsOpen.{u1} α _inst_1 (setOf.{u1} α (fun (x : α) => Filter.Eventually.{u1} α (fun (y : α) => p y) (nhdsWithin.{u1} α _inst_1 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x))))) Case conversion may be inaccurate. Consider using '#align is_open_set_of_eventually_nhds_within isOpen_setOf_eventually_nhdsWithinₓ'. -/ theorem isOpen_setOf_eventually_nhdsWithin [T1Space α] {p : α → Prop} : IsOpen { x | ∀ᶠ y in 𝓝[≠] x, p y } := by refine' is_open_iff_mem_nhds.mpr fun a ha => _ filter_upwards [eventually_nhds_nhds_within.mpr ha]with b hb by_cases a = b · subst h exact hb · rw [(Ne.symm h).nhdsWithin_compl_singleton] at hb exact hb.filter_mono nhdsWithin_le_nhds #align is_open_set_of_eventually_nhds_within isOpen_setOf_eventually_nhdsWithin #print Set.Finite.isClosed /- protected theorem Set.Finite.isClosed [T1Space α] {s : Set α} (hs : Set.Finite s) : IsClosed s := by rw [← bUnion_of_singleton s] exact isClosed_bunionᵢ hs fun i hi => isClosed_singleton #align set.finite.is_closed Set.Finite.isClosed -/ /- warning: topological_space.is_topological_basis.exists_mem_of_ne -> TopologicalSpace.IsTopologicalBasis.exists_mem_of_ne is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {b : Set.{u1} (Set.{u1} α)}, (TopologicalSpace.IsTopologicalBasis.{u1} α _inst_1 b) -> (forall {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (a : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Set.{u1} (Set.{u1} α)) (Set.hasMem.{u1} (Set.{u1} α)) a b) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Set.{u1} (Set.{u1} α)) (Set.hasMem.{u1} (Set.{u1} α)) a b) => And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x a) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) y a)))))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {b : Set.{u1} (Set.{u1} α)}, (TopologicalSpace.IsTopologicalBasis.{u1} α _inst_1 b) -> (forall {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (a : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Set.{u1} (Set.{u1} α)) (Set.instMembershipSet.{u1} (Set.{u1} α)) a b) (And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x a) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) y a)))))) Case conversion may be inaccurate. Consider using '#align topological_space.is_topological_basis.exists_mem_of_ne TopologicalSpace.IsTopologicalBasis.exists_mem_of_neₓ'. -/ theorem TopologicalSpace.IsTopologicalBasis.exists_mem_of_ne [T1Space α] {b : Set (Set α)} (hb : IsTopologicalBasis b) {x y : α} (h : x ≠ y) : ∃ a ∈ b, x ∈ a ∧ y ∉ a := by rcases hb.is_open_iff.1 isOpen_ne x h with ⟨a, ab, xa, ha⟩ exact ⟨a, ab, xa, fun h => ha h rfl⟩ #align topological_space.is_topological_basis.exists_mem_of_ne TopologicalSpace.IsTopologicalBasis.exists_mem_of_ne /- warning: filter.coclosed_compact_le_cofinite -> Filter.coclosedCompact_le_cofinite is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1], LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (Filter.coclosedCompact.{u1} α _inst_1) (Filter.cofinite.{u1} α) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1], LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (Filter.coclosedCompact.{u1} α _inst_1) (Filter.cofinite.{u1} α) Case conversion may be inaccurate. Consider using '#align filter.coclosed_compact_le_cofinite Filter.coclosedCompact_le_cofiniteₓ'. -/ theorem Filter.coclosedCompact_le_cofinite [T1Space α] : Filter.coclosedCompact α ≤ Filter.cofinite := fun s hs => compl_compl s ▸ hs.IsCompact.compl_mem_coclosedCompact_of_isClosed hs.IsClosed #align filter.coclosed_compact_le_cofinite Filter.coclosedCompact_le_cofinite variable (α) #print Bornology.relativelyCompact /- /-- In a `t1_space`, relatively compact sets form a bornology. Its cobounded filter is `filter.coclosed_compact`. See also `bornology.in_compact` the bornology of sets contained in a compact set. -/ def Bornology.relativelyCompact [T1Space α] : Bornology α where cobounded := Filter.coclosedCompact α le_cofinite := Filter.coclosedCompact_le_cofinite #align bornology.relatively_compact Bornology.relativelyCompact -/ variable {α} #print Bornology.relativelyCompact.isBounded_iff /- theorem Bornology.relativelyCompact.isBounded_iff [T1Space α] {s : Set α} : @Bornology.IsBounded _ (Bornology.relativelyCompact α) s ↔ IsCompact (closure s) := by change sᶜ ∈ Filter.coclosedCompact α ↔ _ rw [Filter.mem_coclosedCompact] constructor · rintro ⟨t, ht₁, ht₂, hst⟩ rw [compl_subset_compl] at hst exact isCompact_of_isClosed_subset ht₂ isClosed_closure (closure_minimal hst ht₁) · intro h exact ⟨closure s, isClosed_closure, h, compl_subset_compl.mpr subset_closure⟩ #align bornology.relatively_compact.is_bounded_iff Bornology.relativelyCompact.isBounded_iff -/ #print Finset.isClosed /- protected theorem Finset.isClosed [T1Space α] (s : Finset α) : IsClosed (s : Set α) := s.finite_toSet.IsClosed #align finset.is_closed Finset.isClosed -/ /- warning: t1_space_tfae -> t1Space_TFAE is a dubious translation: lean 3 declaration is forall (α : Type.{u1}) [_inst_2 : TopologicalSpace.{u1} α], List.TFAE (List.cons.{0} Prop (T1Space.{u1} α _inst_2) (List.cons.{0} Prop (forall (x : α), IsClosed.{u1} α _inst_2 (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)) (List.cons.{0} Prop (forall (x : α), IsOpen.{u1} α _inst_2 (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x))) (List.cons.{0} Prop (Continuous.{u1, u1} α (CofiniteTopology.{u1} α) _inst_2 (CofiniteTopology.topologicalSpace.{u1} α) (coeFn.{succ u1, succ u1} (Equiv.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) (fun (_x : Equiv.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) => α -> (CofiniteTopology.{u1} α)) (Equiv.hasCoeToFun.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) (CofiniteTopology.of.{u1} α))) (List.cons.{0} Prop (forall {{x : α}} {{y : α}}, (Ne.{succ u1} α x y) -> (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) y)) (nhds.{u1} α _inst_2 x))) (List.cons.{0} Prop (forall {{x : α}} {{y : α}}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (s : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) s (nhds.{u1} α _inst_2 x)) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) s (nhds.{u1} α _inst_2 x)) => Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) y s))))) (List.cons.{0} Prop (forall {{x : α}} {{y : α}}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (U : Set.{u1} α) => Exists.{0} (IsOpen.{u1} α _inst_2 U) (fun (hU : IsOpen.{u1} α _inst_2 U) => And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x U) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) y U)))))) (List.cons.{0} Prop (forall {{x : α}} {{y : α}}, (Ne.{succ u1} α x y) -> (Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) (nhds.{u1} α _inst_2 x) (Pure.pure.{u1, u1} Filter.{u1} Filter.hasPure.{u1} α y))) (List.cons.{0} Prop (forall {{x : α}} {{y : α}}, (Ne.{succ u1} α x y) -> (Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) (Pure.pure.{u1, u1} Filter.{u1} Filter.hasPure.{u1} α x) (nhds.{u1} α _inst_2 y))) (List.cons.{0} Prop (forall {{x : α}} {{y : α}}, (Specializes.{u1} α _inst_2 x y) -> (Eq.{succ u1} α x y)) (List.nil.{0} Prop))))))))))) but is expected to have type forall (α : Type.{u1}) [_inst_2 : TopologicalSpace.{u1} α], List.TFAE (List.cons.{0} Prop (T1Space.{u1} α _inst_2) (List.cons.{0} Prop (forall (x : α), IsClosed.{u1} α _inst_2 (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)) (List.cons.{0} Prop (forall (x : α), IsOpen.{u1} α _inst_2 (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x))) (List.cons.{0} Prop (Continuous.{u1, u1} α (CofiniteTopology.{u1} α) _inst_2 (CofiniteTopology.instTopologicalSpaceCofiniteTopology.{u1} α) (FunLike.coe.{succ u1, succ u1, succ u1} (Equiv.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) α (fun (_x : α) => (fun ([email protected]._hyg.808 : α) => CofiniteTopology.{u1} α) _x) (Equiv.instFunLikeEquiv.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) (CofiniteTopology.of.{u1} α))) (List.cons.{0} Prop (forall {{x : α}} {{y : α}}, (Ne.{succ u1} α x y) -> (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) y)) (nhds.{u1} α _inst_2 x))) (List.cons.{0} Prop (forall {{x : α}} {{y : α}}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (s : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) s (nhds.{u1} α _inst_2 x)) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) y s))))) (List.cons.{0} Prop (forall {{x : α}} {{y : α}}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (U : Set.{u1} α) => And (IsOpen.{u1} α _inst_2 U) (And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x U) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) y U)))))) (List.cons.{0} Prop (forall {{x : α}} {{y : α}}, (Ne.{succ u1} α x y) -> (Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) (nhds.{u1} α _inst_2 x) (Pure.pure.{u1, u1} Filter.{u1} Filter.instPureFilter.{u1} α y))) (List.cons.{0} Prop (forall {{x : α}} {{y : α}}, (Ne.{succ u1} α x y) -> (Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) (Pure.pure.{u1, u1} Filter.{u1} Filter.instPureFilter.{u1} α x) (nhds.{u1} α _inst_2 y))) (List.cons.{0} Prop (forall {{x : α}} {{y : α}}, (Specializes.{u1} α _inst_2 x y) -> (Eq.{succ u1} α x y)) (List.nil.{0} Prop))))))))))) Case conversion may be inaccurate. Consider using '#align t1_space_tfae t1Space_TFAEₓ'. -/ theorem t1Space_TFAE (α : Type u) [TopologicalSpace α] : TFAE [T1Space α, ∀ x, IsClosed ({x} : Set α), ∀ x, IsOpen ({x}ᶜ : Set α), Continuous (@CofiniteTopology.of α), ∀ ⦃x y : α⦄, x ≠ y → {y}ᶜ ∈ 𝓝 x, ∀ ⦃x y : α⦄, x ≠ y → ∃ s ∈ 𝓝 x, y ∉ s, ∀ ⦃x y : α⦄, x ≠ y → ∃ (U : Set α)(hU : IsOpen U), x ∈ U ∧ y ∉ U, ∀ ⦃x y : α⦄, x ≠ y → Disjoint (𝓝 x) (pure y), ∀ ⦃x y : α⦄, x ≠ y → Disjoint (pure x) (𝓝 y), ∀ ⦃x y : α⦄, x ⤳ y → x = y] := by tfae_have 1 ↔ 2; exact ⟨fun h => h.1, fun h => ⟨h⟩⟩ tfae_have 2 ↔ 3; · simp only [isOpen_compl_iff] tfae_have 5 ↔ 3 · refine' forall_swap.trans _ simp only [isOpen_iff_mem_nhds, mem_compl_iff, mem_singleton_iff] tfae_have 5 ↔ 6 · simp only [← subset_compl_singleton_iff, exists_mem_subset_iff] tfae_have 5 ↔ 7 · simp only [(nhds_basis_opens _).mem_iff, subset_compl_singleton_iff, exists_prop, and_assoc, and_left_comm] tfae_have 5 ↔ 8 · simp only [← principal_singleton, disjoint_principal_right] tfae_have 8 ↔ 9; exact forall_swap.trans (by simp only [disjoint_comm, ne_comm]) tfae_have 1 → 4 · simp only [continuous_def, CofiniteTopology.isOpen_iff'] rintro H s (rfl | hs) exacts[isOpen_empty, compl_compl s ▸ (@Set.Finite.isClosed _ _ H _ hs).isOpen_compl] tfae_have 4 → 2 exact fun h x => (CofiniteTopology.isClosed_iff.2 <| Or.inr (finite_singleton _)).Preimage h tfae_have 2 ↔ 10 · simp only [← closure_subset_iff_isClosed, specializes_iff_mem_closure, subset_def, mem_singleton_iff, eq_comm] tfae_finish #align t1_space_tfae t1Space_TFAE /- warning: t1_space_iff_continuous_cofinite_of -> t1Space_iff_continuous_cofinite_of is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_2 : TopologicalSpace.{u1} α], Iff (T1Space.{u1} α _inst_2) (Continuous.{u1, u1} α (CofiniteTopology.{u1} α) _inst_2 (CofiniteTopology.topologicalSpace.{u1} α) (coeFn.{succ u1, succ u1} (Equiv.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) (fun (_x : Equiv.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) => α -> (CofiniteTopology.{u1} α)) (Equiv.hasCoeToFun.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) (CofiniteTopology.of.{u1} α))) but is expected to have type forall {α : Type.{u1}} [_inst_2 : TopologicalSpace.{u1} α], Iff (T1Space.{u1} α _inst_2) (Continuous.{u1, u1} α (CofiniteTopology.{u1} α) _inst_2 (CofiniteTopology.instTopologicalSpaceCofiniteTopology.{u1} α) (FunLike.coe.{succ u1, succ u1, succ u1} (Equiv.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) α (fun (_x : α) => (fun ([email protected]._hyg.808 : α) => CofiniteTopology.{u1} α) _x) (Equiv.instFunLikeEquiv.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) (CofiniteTopology.of.{u1} α))) Case conversion may be inaccurate. Consider using '#align t1_space_iff_continuous_cofinite_of t1Space_iff_continuous_cofinite_ofₓ'. -/ theorem t1Space_iff_continuous_cofinite_of {α : Type _} [TopologicalSpace α] : T1Space α ↔ Continuous (@CofiniteTopology.of α) := (t1Space_TFAE α).out 0 3 #align t1_space_iff_continuous_cofinite_of t1Space_iff_continuous_cofinite_of /- warning: cofinite_topology.continuous_of -> CofiniteTopology.continuous_of is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1], Continuous.{u1, u1} α (CofiniteTopology.{u1} α) _inst_1 (CofiniteTopology.topologicalSpace.{u1} α) (coeFn.{succ u1, succ u1} (Equiv.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) (fun (_x : Equiv.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) => α -> (CofiniteTopology.{u1} α)) (Equiv.hasCoeToFun.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) (CofiniteTopology.of.{u1} α)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1], Continuous.{u1, u1} α (CofiniteTopology.{u1} α) _inst_1 (CofiniteTopology.instTopologicalSpaceCofiniteTopology.{u1} α) (FunLike.coe.{succ u1, succ u1, succ u1} (Equiv.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) α (fun (_x : α) => (fun ([email protected]._hyg.808 : α) => CofiniteTopology.{u1} α) _x) (Equiv.instFunLikeEquiv.{succ u1, succ u1} α (CofiniteTopology.{u1} α)) (CofiniteTopology.of.{u1} α)) Case conversion may be inaccurate. Consider using '#align cofinite_topology.continuous_of CofiniteTopology.continuous_ofₓ'. -/ theorem CofiniteTopology.continuous_of [T1Space α] : Continuous (@CofiniteTopology.of α) := t1Space_iff_continuous_cofinite_of.mp ‹_› #align cofinite_topology.continuous_of CofiniteTopology.continuous_of /- warning: t1_space_iff_exists_open -> t1Space_iff_exists_open is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T1Space.{u1} α _inst_1) (forall (x : α) (y : α), (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (U : Set.{u1} α) => Exists.{0} (IsOpen.{u1} α _inst_1 U) (fun (hU : IsOpen.{u1} α _inst_1 U) => And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x U) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) y U)))))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T1Space.{u1} α _inst_1) (forall (x : α) (y : α), (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (U : Set.{u1} α) => And (IsOpen.{u1} α _inst_1 U) (And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x U) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) y U)))))) Case conversion may be inaccurate. Consider using '#align t1_space_iff_exists_open t1Space_iff_exists_openₓ'. -/ theorem t1Space_iff_exists_open : T1Space α ↔ ∀ x y, x ≠ y → ∃ (U : Set α)(hU : IsOpen U), x ∈ U ∧ y ∉ U := (t1Space_TFAE α).out 0 6 #align t1_space_iff_exists_open t1Space_iff_exists_open /- warning: t1_space_iff_disjoint_pure_nhds -> t1Space_iff_disjoint_pure_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T1Space.{u1} α _inst_1) (forall {{x : α}} {{y : α}}, (Ne.{succ u1} α x y) -> (Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) (Pure.pure.{u1, u1} Filter.{u1} Filter.hasPure.{u1} α x) (nhds.{u1} α _inst_1 y))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T1Space.{u1} α _inst_1) (forall {{x : α}} {{y : α}}, (Ne.{succ u1} α x y) -> (Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) (Pure.pure.{u1, u1} Filter.{u1} Filter.instPureFilter.{u1} α x) (nhds.{u1} α _inst_1 y))) Case conversion may be inaccurate. Consider using '#align t1_space_iff_disjoint_pure_nhds t1Space_iff_disjoint_pure_nhdsₓ'. -/ theorem t1Space_iff_disjoint_pure_nhds : T1Space α ↔ ∀ ⦃x y : α⦄, x ≠ y → Disjoint (pure x) (𝓝 y) := (t1Space_TFAE α).out 0 8 #align t1_space_iff_disjoint_pure_nhds t1Space_iff_disjoint_pure_nhds /- warning: t1_space_iff_disjoint_nhds_pure -> t1Space_iff_disjoint_nhds_pure is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T1Space.{u1} α _inst_1) (forall {{x : α}} {{y : α}}, (Ne.{succ u1} α x y) -> (Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) (nhds.{u1} α _inst_1 x) (Pure.pure.{u1, u1} Filter.{u1} Filter.hasPure.{u1} α y))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T1Space.{u1} α _inst_1) (forall {{x : α}} {{y : α}}, (Ne.{succ u1} α x y) -> (Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) (nhds.{u1} α _inst_1 x) (Pure.pure.{u1, u1} Filter.{u1} Filter.instPureFilter.{u1} α y))) Case conversion may be inaccurate. Consider using '#align t1_space_iff_disjoint_nhds_pure t1Space_iff_disjoint_nhds_pureₓ'. -/ theorem t1Space_iff_disjoint_nhds_pure : T1Space α ↔ ∀ ⦃x y : α⦄, x ≠ y → Disjoint (𝓝 x) (pure y) := (t1Space_TFAE α).out 0 7 #align t1_space_iff_disjoint_nhds_pure t1Space_iff_disjoint_nhds_pure #print t1Space_iff_specializes_imp_eq /- theorem t1Space_iff_specializes_imp_eq : T1Space α ↔ ∀ ⦃x y : α⦄, x ⤳ y → x = y := (t1Space_TFAE α).out 0 9 #align t1_space_iff_specializes_imp_eq t1Space_iff_specializes_imp_eq -/ /- warning: disjoint_pure_nhds -> disjoint_pure_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) (Pure.pure.{u1, u1} Filter.{u1} Filter.hasPure.{u1} α x) (nhds.{u1} α _inst_1 y)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) (Pure.pure.{u1, u1} Filter.{u1} Filter.instPureFilter.{u1} α x) (nhds.{u1} α _inst_1 y)) Case conversion may be inaccurate. Consider using '#align disjoint_pure_nhds disjoint_pure_nhdsₓ'. -/ theorem disjoint_pure_nhds [T1Space α] {x y : α} (h : x ≠ y) : Disjoint (pure x) (𝓝 y) := t1Space_iff_disjoint_pure_nhds.mp ‹_› h #align disjoint_pure_nhds disjoint_pure_nhds /- warning: disjoint_nhds_pure -> disjoint_nhds_pure is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) (nhds.{u1} α _inst_1 x) (Pure.pure.{u1, u1} Filter.{u1} Filter.hasPure.{u1} α y)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) (nhds.{u1} α _inst_1 x) (Pure.pure.{u1, u1} Filter.{u1} Filter.instPureFilter.{u1} α y)) Case conversion may be inaccurate. Consider using '#align disjoint_nhds_pure disjoint_nhds_pureₓ'. -/ theorem disjoint_nhds_pure [T1Space α] {x y : α} (h : x ≠ y) : Disjoint (𝓝 x) (pure y) := t1Space_iff_disjoint_nhds_pure.mp ‹_› h #align disjoint_nhds_pure disjoint_nhds_pure #print Specializes.eq /- theorem Specializes.eq [T1Space α] {x y : α} (h : x ⤳ y) : x = y := t1Space_iff_specializes_imp_eq.1 ‹_› h #align specializes.eq Specializes.eq -/ #print specializes_iff_eq /- theorem specializes_iff_eq [T1Space α] {x y : α} : x ⤳ y ↔ x = y := ⟨Specializes.eq, fun h => h ▸ specializes_rfl⟩ #align specializes_iff_eq specializes_iff_eq -/ #print specializes_eq_eq /- @[simp] theorem specializes_eq_eq [T1Space α] : (· ⤳ ·) = @Eq α := funext₂ fun x y => propext specializes_iff_eq #align specializes_eq_eq specializes_eq_eq -/ /- warning: pure_le_nhds_iff -> pure_le_nhds_iff is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {a : α} {b : α}, Iff (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (Pure.pure.{u1, u1} Filter.{u1} Filter.hasPure.{u1} α a) (nhds.{u1} α _inst_1 b)) (Eq.{succ u1} α a b) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {a : α} {b : α}, Iff (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (Pure.pure.{u1, u1} Filter.{u1} Filter.instPureFilter.{u1} α a) (nhds.{u1} α _inst_1 b)) (Eq.{succ u1} α a b) Case conversion may be inaccurate. Consider using '#align pure_le_nhds_iff pure_le_nhds_iffₓ'. -/ @[simp] theorem pure_le_nhds_iff [T1Space α] {a b : α} : pure a ≤ 𝓝 b ↔ a = b := specializes_iff_pure.symm.trans specializes_iff_eq #align pure_le_nhds_iff pure_le_nhds_iff /- warning: nhds_le_nhds_iff -> nhds_le_nhds_iff is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {a : α} {b : α}, Iff (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (nhds.{u1} α _inst_1 a) (nhds.{u1} α _inst_1 b)) (Eq.{succ u1} α a b) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {a : α} {b : α}, Iff (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (nhds.{u1} α _inst_1 a) (nhds.{u1} α _inst_1 b)) (Eq.{succ u1} α a b) Case conversion may be inaccurate. Consider using '#align nhds_le_nhds_iff nhds_le_nhds_iffₓ'. -/ @[simp] theorem nhds_le_nhds_iff [T1Space α] {a b : α} : 𝓝 a ≤ 𝓝 b ↔ a = b := specializes_iff_eq #align nhds_le_nhds_iff nhds_le_nhds_iff instance {α : Type _} : T1Space (CofiniteTopology α) := t1Space_iff_continuous_cofinite_of.mpr continuous_id /- warning: t1_space_antitone -> t1Space_antitone is a dubious translation: lean 3 declaration is forall {α : Type.{u1}}, Antitone.{u1, 0} (TopologicalSpace.{u1} α) Prop (PartialOrder.toPreorder.{u1} (TopologicalSpace.{u1} α) (TopologicalSpace.partialOrder.{u1} α)) (PartialOrder.toPreorder.{0} Prop Prop.partialOrder) (T1Space.{u1} α) but is expected to have type forall {α : Type.{u1}}, Antitone.{u1, 0} (TopologicalSpace.{u1} α) Prop (PartialOrder.toPreorder.{u1} (TopologicalSpace.{u1} α) (TopologicalSpace.instPartialOrderTopologicalSpace.{u1} α)) (PartialOrder.toPreorder.{0} Prop Prop.partialOrder) (T1Space.{u1} α) Case conversion may be inaccurate. Consider using '#align t1_space_antitone t1Space_antitoneₓ'. -/ theorem t1Space_antitone {α : Type _} : Antitone (@T1Space α) := by simp only [Antitone, t1Space_iff_continuous_cofinite_of, continuous_iff_le_induced] exact fun t₁ t₂ h => h.trans #align t1_space_antitone t1Space_antitone #print continuousWithinAt_update_of_ne /- theorem continuousWithinAt_update_of_ne [T1Space α] [DecidableEq α] [TopologicalSpace β] {f : α → β} {s : Set α} {x y : α} {z : β} (hne : y ≠ x) : ContinuousWithinAt (Function.update f x z) s y ↔ ContinuousWithinAt f s y := EventuallyEq.congr_continuousWithinAt (mem_nhdsWithin_of_mem_nhds <| mem_of_superset (isOpen_ne.mem_nhds hne) fun y' hy' => Function.update_noteq hy' _ _) (Function.update_noteq hne _ _) #align continuous_within_at_update_of_ne continuousWithinAt_update_of_ne -/ #print continuousAt_update_of_ne /- theorem continuousAt_update_of_ne [T1Space α] [DecidableEq α] [TopologicalSpace β] {f : α → β} {x y : α} {z : β} (hne : y ≠ x) : ContinuousAt (Function.update f x z) y ↔ ContinuousAt f y := by simp only [← continuousWithinAt_univ, continuousWithinAt_update_of_ne hne] #align continuous_at_update_of_ne continuousAt_update_of_ne -/ /- warning: continuous_on_update_iff -> continuousOn_update_iff is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] [_inst_3 : DecidableEq.{succ u1} α] [_inst_4 : TopologicalSpace.{u2} β] {f : α -> β} {s : Set.{u1} α} {x : α} {y : β}, Iff (ContinuousOn.{u1, u2} α β _inst_1 _inst_4 (Function.update.{succ u1, succ u2} α (fun (ᾰ : α) => β) (fun (a : α) (b : α) => _inst_3 a b) f x y) s) (And (ContinuousOn.{u1, u2} α β _inst_1 _inst_4 f (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x))) ((Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) -> (Filter.Tendsto.{u1, u2} α β f (nhdsWithin.{u1} α _inst_1 x (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x))) (nhds.{u2} β _inst_4 y)))) but is expected to have type forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] [_inst_3 : DecidableEq.{succ u1} α] [_inst_4 : TopologicalSpace.{u2} β] {f : α -> β} {s : Set.{u1} α} {x : α} {y : β}, Iff (ContinuousOn.{u1, u2} α β _inst_1 _inst_4 (Function.update.{succ u1, succ u2} α (fun (ᾰ : α) => β) (fun (a : α) (b : α) => _inst_3 a b) f x y) s) (And (ContinuousOn.{u1, u2} α β _inst_1 _inst_4 f (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x))) ((Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) -> (Filter.Tendsto.{u1, u2} α β f (nhdsWithin.{u1} α _inst_1 x (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x))) (nhds.{u2} β _inst_4 y)))) Case conversion may be inaccurate. Consider using '#align continuous_on_update_iff continuousOn_update_iffₓ'. -/ theorem continuousOn_update_iff [T1Space α] [DecidableEq α] [TopologicalSpace β] {f : α → β} {s : Set α} {x : α} {y : β} : ContinuousOn (Function.update f x y) s ↔ ContinuousOn f (s \ {x}) ∧ (x ∈ s → Tendsto f (𝓝[s \ {x}] x) (𝓝 y)) := by rw [ContinuousOn, ← and_forall_ne x, and_comm'] refine' and_congr ⟨fun H z hz => _, fun H z hzx hzs => _⟩ (forall_congr' fun hxs => _) · specialize H z hz.2 hz.1 rw [continuousWithinAt_update_of_ne hz.2] at H exact H.mono (diff_subset _ _) · rw [continuousWithinAt_update_of_ne hzx] refine' (H z ⟨hzs, hzx⟩).mono_of_mem (inter_mem_nhdsWithin _ _) exact is_open_ne.mem_nhds hzx · exact continuousWithinAt_update_same #align continuous_on_update_iff continuousOn_update_iff #print t1Space_of_injective_of_continuous /- theorem t1Space_of_injective_of_continuous [TopologicalSpace β] {f : α → β} (hf : Function.Injective f) (hf' : Continuous f) [T1Space β] : T1Space α := t1Space_iff_specializes_imp_eq.2 fun x y h => hf (h.map hf').Eq #align t1_space_of_injective_of_continuous t1Space_of_injective_of_continuous -/ #print Embedding.t1Space /- protected theorem Embedding.t1Space [TopologicalSpace β] [T1Space β] {f : α → β} (hf : Embedding f) : T1Space α := t1Space_of_injective_of_continuous hf.inj hf.Continuous #align embedding.t1_space Embedding.t1Space -/ #print Subtype.t1Space /- instance Subtype.t1Space {α : Type u} [TopologicalSpace α] [T1Space α] {p : α → Prop} : T1Space (Subtype p) := embedding_subtype_val.T1Space #align subtype.t1_space Subtype.t1Space -/ instance [TopologicalSpace β] [T1Space α] [T1Space β] : T1Space (α × β) := ⟨fun ⟨a, b⟩ => @singleton_prod_singleton _ _ a b ▸ isClosed_singleton.Prod isClosed_singleton⟩ instance {ι : Type _} {π : ι → Type _} [∀ i, TopologicalSpace (π i)] [∀ i, T1Space (π i)] : T1Space (∀ i, π i) := ⟨fun f => univ_pi_singleton f ▸ isClosed_set_pi fun i hi => isClosed_singleton⟩ #print T1Space.t0Space /- -- see Note [lower instance priority] instance (priority := 100) T1Space.t0Space [T1Space α] : T0Space α := ⟨fun x y h => h.Specializes.Eq⟩ #align t1_space.t0_space T1Space.t0Space -/ /- warning: compl_singleton_mem_nhds_iff -> compl_singleton_mem_nhds_iff is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α} {y : α}, Iff (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)) (nhds.{u1} α _inst_1 y)) (Ne.{succ u1} α y x) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α} {y : α}, Iff (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)) (nhds.{u1} α _inst_1 y)) (Ne.{succ u1} α y x) Case conversion may be inaccurate. Consider using '#align compl_singleton_mem_nhds_iff compl_singleton_mem_nhds_iffₓ'. -/ @[simp] theorem compl_singleton_mem_nhds_iff [T1Space α] {x y : α} : {x}ᶜ ∈ 𝓝 y ↔ y ≠ x := isOpen_compl_singleton.mem_nhds_iffₓ #align compl_singleton_mem_nhds_iff compl_singleton_mem_nhds_iff /- warning: compl_singleton_mem_nhds -> compl_singleton_mem_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α y x) -> (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)) (nhds.{u1} α _inst_1 y)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α y x) -> (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)) (nhds.{u1} α _inst_1 y)) Case conversion may be inaccurate. Consider using '#align compl_singleton_mem_nhds compl_singleton_mem_nhdsₓ'. -/ theorem compl_singleton_mem_nhds [T1Space α] {x y : α} (h : y ≠ x) : {x}ᶜ ∈ 𝓝 y := compl_singleton_mem_nhds_iff.mpr h #align compl_singleton_mem_nhds compl_singleton_mem_nhds #print closure_singleton /- @[simp] theorem closure_singleton [T1Space α] {a : α} : closure ({a} : Set α) = {a} := isClosed_singleton.closure_eq #align closure_singleton closure_singleton -/ #print Set.Subsingleton.closure /- theorem Set.Subsingleton.closure [T1Space α] {s : Set α} (hs : s.Subsingleton) : (closure s).Subsingleton := hs.inductionOn (by simp) fun x => by simp #align set.subsingleton.closure Set.Subsingleton.closure -/ #print subsingleton_closure /- @[simp] theorem subsingleton_closure [T1Space α] {s : Set α} : (closure s).Subsingleton ↔ s.Subsingleton := ⟨fun h => h.anti subset_closure, fun h => h.closure⟩ #align subsingleton_closure subsingleton_closure -/ /- warning: is_closed_map_const -> isClosedMap_const is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_2 : TopologicalSpace.{u1} α] [_inst_3 : TopologicalSpace.{u2} β] [_inst_4 : T1Space.{u2} β _inst_3] {y : β}, IsClosedMap.{u1, u2} α β _inst_2 _inst_3 (Function.const.{succ u2, succ u1} β α y) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} [_inst_2 : TopologicalSpace.{u2} α] [_inst_3 : TopologicalSpace.{u1} β] [_inst_4 : T1Space.{u1} β _inst_3] {y : β}, IsClosedMap.{u2, u1} α β _inst_2 _inst_3 (Function.const.{succ u1, succ u2} β α y) Case conversion may be inaccurate. Consider using '#align is_closed_map_const isClosedMap_constₓ'. -/ theorem isClosedMap_const {α β} [TopologicalSpace α] [TopologicalSpace β] [T1Space β] {y : β} : IsClosedMap (Function.const α y) := IsClosedMap.of_nonempty fun s hs h2s => by simp_rw [h2s.image_const, isClosed_singleton] #align is_closed_map_const isClosedMap_const #print nhdsWithin_insert_of_ne /- theorem nhdsWithin_insert_of_ne [T1Space α] {x y : α} {s : Set α} (hxy : x ≠ y) : 𝓝[insert y s] x = 𝓝[s] x := by refine' le_antisymm (fun t ht => _) (nhdsWithin_mono x <| subset_insert y s) obtain ⟨o, ho, hxo, host⟩ := mem_nhds_within.mp ht refine' mem_nhds_within.mpr ⟨o \ {y}, ho.sdiff isClosed_singleton, ⟨hxo, hxy⟩, _⟩ rw [inter_insert_of_not_mem <| not_mem_diff_of_mem (mem_singleton y)] exact (inter_subset_inter (diff_subset _ _) subset.rfl).trans host #align nhds_within_insert_of_ne nhdsWithin_insert_of_ne -/ #print insert_mem_nhdsWithin_of_subset_insert /- /-- If `t` is a subset of `s`, except for one point, then `insert x s` is a neighborhood of `x` within `t`. -/ theorem insert_mem_nhdsWithin_of_subset_insert [T1Space α] {x y : α} {s t : Set α} (hu : t ⊆ insert y s) : insert x s ∈ 𝓝[t] x := by rcases eq_or_ne x y with (rfl | h) · exact mem_of_superset self_mem_nhdsWithin hu refine' nhdsWithin_mono x hu _ rw [nhdsWithin_insert_of_ne h] exact mem_of_superset self_mem_nhdsWithin (subset_insert x s) #align insert_mem_nhds_within_of_subset_insert insert_mem_nhdsWithin_of_subset_insert -/ /- warning: bInter_basis_nhds -> binterᵢ_basis_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {ι : Sort.{u2}} {p : ι -> Prop} {s : ι -> (Set.{u1} α)} {x : α}, (Filter.HasBasis.{u1, u2} α ι (nhds.{u1} α _inst_1 x) p s) -> (Eq.{succ u1} (Set.{u1} α) (Set.interᵢ.{u1, u2} α ι (fun (i : ι) => Set.interᵢ.{u1, 0} α (p i) (fun (h : p i) => s i))) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)) but is expected to have type forall {α : Type.{u2}} [_inst_1 : TopologicalSpace.{u2} α] [_inst_2 : T1Space.{u2} α _inst_1] {ι : Sort.{u1}} {p : ι -> Prop} {s : ι -> (Set.{u2} α)} {x : α}, (Filter.HasBasis.{u2, u1} α ι (nhds.{u2} α _inst_1 x) p s) -> (Eq.{succ u2} (Set.{u2} α) (Set.interᵢ.{u2, u1} α ι (fun (i : ι) => Set.interᵢ.{u2, 0} α (p i) (fun (h : p i) => s i))) (Singleton.singleton.{u2, u2} α (Set.{u2} α) (Set.instSingletonSet.{u2} α) x)) Case conversion may be inaccurate. Consider using '#align bInter_basis_nhds binterᵢ_basis_nhdsₓ'. -/ theorem binterᵢ_basis_nhds [T1Space α] {ι : Sort _} {p : ι → Prop} {s : ι → Set α} {x : α} (h : (𝓝 x).HasBasis p s) : (⋂ (i) (h : p i), s i) = {x} := by simp only [eq_singleton_iff_unique_mem, mem_Inter] refine' ⟨fun i hi => mem_of_mem_nhds <| h.mem_of_mem hi, fun y hy => _⟩ contrapose! hy rcases h.mem_iff.1 (compl_singleton_mem_nhds hy.symm) with ⟨i, hi, hsub⟩ exact ⟨i, hi, fun h => hsub h rfl⟩ #align bInter_basis_nhds binterᵢ_basis_nhds /- warning: compl_singleton_mem_nhds_set_iff -> compl_singleton_mem_nhdsSet_iff is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α} {s : Set.{u1} α}, Iff (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)) (nhdsSet.{u1} α _inst_1 s)) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {x : α} {s : Set.{u1} α}, Iff (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)) (nhdsSet.{u1} α _inst_1 s)) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s)) Case conversion may be inaccurate. Consider using '#align compl_singleton_mem_nhds_set_iff compl_singleton_mem_nhdsSet_iffₓ'. -/ @[simp] theorem compl_singleton_mem_nhdsSet_iff [T1Space α] {x : α} {s : Set α} : {x}ᶜ ∈ 𝓝ˢ s ↔ x ∉ s := by rwa [is_open_compl_singleton.mem_nhds_set, subset_compl_singleton_iff] #align compl_singleton_mem_nhds_set_iff compl_singleton_mem_nhdsSet_iff /- warning: nhds_set_le_iff -> nhdsSet_le_iff is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {s : Set.{u1} α} {t : Set.{u1} α}, Iff (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (nhdsSet.{u1} α _inst_1 s) (nhdsSet.{u1} α _inst_1 t)) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s t) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {s : Set.{u1} α} {t : Set.{u1} α}, Iff (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (nhdsSet.{u1} α _inst_1 s) (nhdsSet.{u1} α _inst_1 t)) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) s t) Case conversion may be inaccurate. Consider using '#align nhds_set_le_iff nhdsSet_le_iffₓ'. -/ @[simp] theorem nhdsSet_le_iff [T1Space α] {s t : Set α} : 𝓝ˢ s ≤ 𝓝ˢ t ↔ s ⊆ t := by refine' ⟨_, fun h => monotone_nhdsSet h⟩ simp_rw [Filter.le_def]; intro h x hx specialize h ({x}ᶜ) simp_rw [compl_singleton_mem_nhdsSet_iff] at h by_contra hxt exact h hxt hx #align nhds_set_le_iff nhdsSet_le_iff #print nhdsSet_inj_iff /- @[simp] theorem nhdsSet_inj_iff [T1Space α] {s t : Set α} : 𝓝ˢ s = 𝓝ˢ t ↔ s = t := by simp_rw [le_antisymm_iff] exact and_congr nhdsSet_le_iff nhdsSet_le_iff #align nhds_set_inj_iff nhdsSet_inj_iff -/ #print injective_nhdsSet /- theorem injective_nhdsSet [T1Space α] : Function.Injective (𝓝ˢ : Set α → Filter α) := fun s t hst => nhdsSet_inj_iff.mp hst #align injective_nhds_set injective_nhdsSet -/ /- warning: strict_mono_nhds_set -> strictMono_nhdsSet is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1], StrictMono.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α))))))) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α)) (nhdsSet.{u1} α _inst_1) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1], StrictMono.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α))))))) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α)) (nhdsSet.{u1} α _inst_1) Case conversion may be inaccurate. Consider using '#align strict_mono_nhds_set strictMono_nhdsSetₓ'. -/ theorem strictMono_nhdsSet [T1Space α] : StrictMono (𝓝ˢ : Set α → Filter α) := monotone_nhdsSet.strictMono_of_injective injective_nhdsSet #align strict_mono_nhds_set strictMono_nhdsSet /- warning: nhds_le_nhds_set_iff -> nhds_le_nhdsSet_iff is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {s : Set.{u1} α} {x : α}, Iff (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (nhds.{u1} α _inst_1 x) (nhdsSet.{u1} α _inst_1 s)) (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {s : Set.{u1} α} {x : α}, Iff (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (nhds.{u1} α _inst_1 x) (nhdsSet.{u1} α _inst_1 s)) (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) Case conversion may be inaccurate. Consider using '#align nhds_le_nhds_set_iff nhds_le_nhdsSet_iffₓ'. -/ @[simp] theorem nhds_le_nhdsSet_iff [T1Space α] {s : Set α} {x : α} : 𝓝 x ≤ 𝓝ˢ s ↔ x ∈ s := by rw [← nhdsSet_singleton, nhdsSet_le_iff, singleton_subset_iff] #align nhds_le_nhds_set_iff nhds_le_nhdsSet_iff /- warning: dense.diff_singleton -> Dense.diff_singleton is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {s : Set.{u1} α}, (Dense.{u1} α _inst_1 s) -> (forall (x : α) [_inst_3 : Filter.NeBot.{u1} α (nhdsWithin.{u1} α _inst_1 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)))], Dense.{u1} α _inst_1 (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] {s : Set.{u1} α}, (Dense.{u1} α _inst_1 s) -> (forall (x : α) [_inst_3 : Filter.NeBot.{u1} α (nhdsWithin.{u1} α _inst_1 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)))], Dense.{u1} α _inst_1 (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x))) Case conversion may be inaccurate. Consider using '#align dense.diff_singleton Dense.diff_singletonₓ'. -/ /-- Removing a non-isolated point from a dense set, one still obtains a dense set. -/ theorem Dense.diff_singleton [T1Space α] {s : Set α} (hs : Dense s) (x : α) [NeBot (𝓝[≠] x)] : Dense (s \ {x}) := hs.inter_of_open_right (dense_compl_singleton x) isOpen_compl_singleton #align dense.diff_singleton Dense.diff_singleton /- warning: dense.diff_finset -> Dense.diff_finset is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] [_inst_3 : forall (x : α), Filter.NeBot.{u1} α (nhdsWithin.{u1} α _inst_1 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)))] {s : Set.{u1} α}, (Dense.{u1} α _inst_1 s) -> (forall (t : Finset.{u1} α), Dense.{u1} α _inst_1 (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) (Finset.{u1} α) (Set.{u1} α) (HasLiftT.mk.{succ u1, succ u1} (Finset.{u1} α) (Set.{u1} α) (CoeTCₓ.coe.{succ u1, succ u1} (Finset.{u1} α) (Set.{u1} α) (Finset.Set.hasCoeT.{u1} α))) t))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] [_inst_3 : forall (x : α), Filter.NeBot.{u1} α (nhdsWithin.{u1} α _inst_1 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)))] {s : Set.{u1} α}, (Dense.{u1} α _inst_1 s) -> (forall (t : Finset.{u1} α), Dense.{u1} α _inst_1 (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s (Finset.toSet.{u1} α t))) Case conversion may be inaccurate. Consider using '#align dense.diff_finset Dense.diff_finsetₓ'. -/ /-- Removing a finset from a dense set in a space without isolated points, one still obtains a dense set. -/ theorem Dense.diff_finset [T1Space α] [∀ x : α, NeBot (𝓝[≠] x)] {s : Set α} (hs : Dense s) (t : Finset α) : Dense (s \ t) := by induction' t using Finset.induction_on with x s hxs ih hd · simpa using hs · rw [Finset.coe_insert, ← union_singleton, ← diff_diff] exact ih.diff_singleton _ #align dense.diff_finset Dense.diff_finset /- warning: dense.diff_finite -> Dense.diff_finite is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] [_inst_3 : forall (x : α), Filter.NeBot.{u1} α (nhdsWithin.{u1} α _inst_1 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)))] {s : Set.{u1} α}, (Dense.{u1} α _inst_1 s) -> (forall {t : Set.{u1} α}, (Set.Finite.{u1} α t) -> (Dense.{u1} α _inst_1 (SDiff.sdiff.{u1} (Set.{u1} α) (BooleanAlgebra.toHasSdiff.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) s t))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T1Space.{u1} α _inst_1] [_inst_3 : forall (x : α), Filter.NeBot.{u1} α (nhdsWithin.{u1} α _inst_1 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)))] {s : Set.{u1} α}, (Dense.{u1} α _inst_1 s) -> (forall {t : Set.{u1} α}, (Set.Finite.{u1} α t) -> (Dense.{u1} α _inst_1 (SDiff.sdiff.{u1} (Set.{u1} α) (Set.instSDiffSet.{u1} α) s t))) Case conversion may be inaccurate. Consider using '#align dense.diff_finite Dense.diff_finiteₓ'. -/ /-- Removing a finite set from a dense set in a space without isolated points, one still obtains a dense set. -/ theorem Dense.diff_finite [T1Space α] [∀ x : α, NeBot (𝓝[≠] x)] {s : Set α} (hs : Dense s) {t : Set α} (ht : t.Finite) : Dense (s \ t) := by convert hs.diff_finset ht.to_finset exact (finite.coe_to_finset _).symm #align dense.diff_finite Dense.diff_finite #print eq_of_tendsto_nhds /- /-- If a function to a `t1_space` tends to some limit `b` at some point `a`, then necessarily `b = f a`. -/ theorem eq_of_tendsto_nhds [TopologicalSpace β] [T1Space β] {f : α → β} {a : α} {b : β} (h : Tendsto f (𝓝 a) (𝓝 b)) : f a = b := by_contra fun hfa : f a ≠ b => have fact₁ : {f a}ᶜ ∈ 𝓝 b := compl_singleton_mem_nhds hfa.symm have fact₂ : Tendsto f (pure a) (𝓝 b) := h.comp (tendsto_id'.2 <| pure_le_nhds a) fact₂ fact₁ (Eq.refl <| f a) #align eq_of_tendsto_nhds eq_of_tendsto_nhds -/ /- warning: filter.tendsto.eventually_ne -> Filter.Tendsto.eventually_ne is a dubious translation: lean 3 declaration is forall {β : Type.{u1}} [_inst_2 : TopologicalSpace.{u1} β] [_inst_3 : T1Space.{u1} β _inst_2] {α : Type.{u2}} {g : α -> β} {l : Filter.{u2} α} {b₁ : β} {b₂ : β}, (Filter.Tendsto.{u2, u1} α β g l (nhds.{u1} β _inst_2 b₁)) -> (Ne.{succ u1} β b₁ b₂) -> (Filter.Eventually.{u2} α (fun (z : α) => Ne.{succ u1} β (g z) b₂) l) but is expected to have type forall {β : Type.{u2}} [_inst_2 : TopologicalSpace.{u2} β] [_inst_3 : T1Space.{u2} β _inst_2] {α : Type.{u1}} {g : α -> β} {l : Filter.{u1} α} {b₁ : β} {b₂ : β}, (Filter.Tendsto.{u1, u2} α β g l (nhds.{u2} β _inst_2 b₁)) -> (Ne.{succ u2} β b₁ b₂) -> (Filter.Eventually.{u1} α (fun (z : α) => Ne.{succ u2} β (g z) b₂) l) Case conversion may be inaccurate. Consider using '#align filter.tendsto.eventually_ne Filter.Tendsto.eventually_neₓ'. -/ theorem Filter.Tendsto.eventually_ne [TopologicalSpace β] [T1Space β] {α : Type _} {g : α → β} {l : Filter α} {b₁ b₂ : β} (hg : Tendsto g l (𝓝 b₁)) (hb : b₁ ≠ b₂) : ∀ᶠ z in l, g z ≠ b₂ := hg.Eventually (isOpen_compl_singleton.eventually_mem hb) #align filter.tendsto.eventually_ne Filter.Tendsto.eventually_ne #print ContinuousAt.eventually_ne /- theorem ContinuousAt.eventually_ne [TopologicalSpace β] [T1Space β] {g : α → β} {a : α} {b : β} (hg1 : ContinuousAt g a) (hg2 : g a ≠ b) : ∀ᶠ z in 𝓝 a, g z ≠ b := hg1.Tendsto.eventually_ne hg2 #align continuous_at.eventually_ne ContinuousAt.eventually_ne -/ #print continuousAt_of_tendsto_nhds /- /-- To prove a function to a `t1_space` is continuous at some point `a`, it suffices to prove that `f` admits *some* limit at `a`. -/ theorem continuousAt_of_tendsto_nhds [TopologicalSpace β] [T1Space β] {f : α → β} {a : α} {b : β} (h : Tendsto f (𝓝 a) (𝓝 b)) : ContinuousAt f a := show Tendsto f (𝓝 a) (𝓝 <| f a) by rwa [eq_of_tendsto_nhds h] #align continuous_at_of_tendsto_nhds continuousAt_of_tendsto_nhds -/ #print tendsto_const_nhds_iff /- @[simp] theorem tendsto_const_nhds_iff [T1Space α] {l : Filter β} [NeBot l] {c d : α} : Tendsto (fun x => c) l (𝓝 d) ↔ c = d := by simp_rw [tendsto, Filter.map_const, pure_le_nhds_iff] #align tendsto_const_nhds_iff tendsto_const_nhds_iff -/ #print isOpen_singleton_of_finite_mem_nhds /- /-- A point with a finite neighborhood has to be isolated. -/ theorem isOpen_singleton_of_finite_mem_nhds {α : Type _} [TopologicalSpace α] [T1Space α] (x : α) {s : Set α} (hs : s ∈ 𝓝 x) (hsf : s.Finite) : IsOpen ({x} : Set α) := by have A : {x} ⊆ s := by simp only [singleton_subset_iff, mem_of_mem_nhds hs] have B : IsClosed (s \ {x}) := (hsf.subset (diff_subset _ _)).IsClosed have C : (s \ {x})ᶜ ∈ 𝓝 x := B.is_open_compl.mem_nhds fun h => h.2 rfl have D : {x} ∈ 𝓝 x := by simpa only [← diff_eq, diff_diff_cancel_left A] using inter_mem hs C rwa [← mem_interior_iff_mem_nhds, ← singleton_subset_iff, subset_interior_iff_isOpen] at D #align is_open_singleton_of_finite_mem_nhds isOpen_singleton_of_finite_mem_nhds -/ /- warning: infinite_of_mem_nhds -> infinite_of_mem_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_2 : TopologicalSpace.{u1} α] [_inst_3 : T1Space.{u1} α _inst_2] (x : α) [hx : Filter.NeBot.{u1} α (nhdsWithin.{u1} α _inst_2 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)))] {s : Set.{u1} α}, (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) s (nhds.{u1} α _inst_2 x)) -> (Set.Infinite.{u1} α s) but is expected to have type forall {α : Type.{u1}} [_inst_2 : TopologicalSpace.{u1} α] [_inst_3 : T1Space.{u1} α _inst_2] (x : α) [hx : Filter.NeBot.{u1} α (nhdsWithin.{u1} α _inst_2 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)))] {s : Set.{u1} α}, (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) s (nhds.{u1} α _inst_2 x)) -> (Set.Infinite.{u1} α s) Case conversion may be inaccurate. Consider using '#align infinite_of_mem_nhds infinite_of_mem_nhdsₓ'. -/ /-- If the punctured neighborhoods of a point form a nontrivial filter, then any neighborhood is infinite. -/ theorem infinite_of_mem_nhds {α} [TopologicalSpace α] [T1Space α] (x : α) [hx : NeBot (𝓝[≠] x)] {s : Set α} (hs : s ∈ 𝓝 x) : Set.Infinite s := by refine' fun hsf => hx.1 _ rw [← isOpen_singleton_iff_punctured_nhds] exact isOpen_singleton_of_finite_mem_nhds x hs hsf #align infinite_of_mem_nhds infinite_of_mem_nhds #print discrete_of_t1_of_finite /- theorem discrete_of_t1_of_finite {X : Type _} [TopologicalSpace X] [T1Space X] [Finite X] : DiscreteTopology X := by apply singletons_open_iff_discrete.mp intro x rw [← isClosed_compl_iff] exact (Set.toFinite _).IsClosed #align discrete_of_t1_of_finite discrete_of_t1_of_finite -/ #print PreconnectedSpace.trivial_of_discrete /- theorem PreconnectedSpace.trivial_of_discrete [PreconnectedSpace α] [DiscreteTopology α] : Subsingleton α := by rw [← not_nontrivial_iff_subsingleton] rintro ⟨x, y, hxy⟩ rw [Ne.def, ← mem_singleton_iff, (isClopen_discrete _).eq_univ <| singleton_nonempty y] at hxy exact hxy (mem_univ x) #align preconnected_space.trivial_of_discrete PreconnectedSpace.trivial_of_discrete -/ #print IsPreconnected.infinite_of_nontrivial /- theorem IsPreconnected.infinite_of_nontrivial [T1Space α] {s : Set α} (h : IsPreconnected s) (hs : s.Nontrivial) : s.Infinite := by refine' mt (fun hf => (subsingleton_coe s).mp _) (not_subsingleton_iff.mpr hs) haveI := @discrete_of_t1_of_finite s _ _ hf.to_subtype exact @PreconnectedSpace.trivial_of_discrete _ _ (Subtype.preconnectedSpace h) _ #align is_preconnected.infinite_of_nontrivial IsPreconnected.infinite_of_nontrivial -/ #print ConnectedSpace.infinite /- theorem ConnectedSpace.infinite [ConnectedSpace α] [Nontrivial α] [T1Space α] : Infinite α := infinite_univ_iff.mp <| isPreconnected_univ.infinite_of_nontrivial nontrivial_univ #align connected_space.infinite ConnectedSpace.infinite -/ #print singleton_mem_nhdsWithin_of_mem_discrete /- theorem singleton_mem_nhdsWithin_of_mem_discrete {s : Set α} [DiscreteTopology s] {x : α} (hx : x ∈ s) : {x} ∈ 𝓝[s] x := by have : ({⟨x, hx⟩} : Set s) ∈ 𝓝 (⟨x, hx⟩ : s) := by simp [nhds_discrete] simpa only [nhdsWithin_eq_map_subtype_coe hx, image_singleton] using @image_mem_map _ _ _ (coe : s → α) _ this #align singleton_mem_nhds_within_of_mem_discrete singleton_mem_nhdsWithin_of_mem_discrete -/ #print nhdsWithin_of_mem_discrete /- /-- The neighbourhoods filter of `x` within `s`, under the discrete topology, is equal to the pure `x` filter (which is the principal filter at the singleton `{x}`.) -/ theorem nhdsWithin_of_mem_discrete {s : Set α} [DiscreteTopology s] {x : α} (hx : x ∈ s) : 𝓝[s] x = pure x := le_antisymm (le_pure_iff.2 <| singleton_mem_nhdsWithin_of_mem_discrete hx) (pure_le_nhdsWithin hx) #align nhds_within_of_mem_discrete nhdsWithin_of_mem_discrete -/ /- warning: filter.has_basis.exists_inter_eq_singleton_of_mem_discrete -> Filter.HasBasis.exists_inter_eq_singleton_of_mem_discrete is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {ι : Type.{u2}} {p : ι -> Prop} {t : ι -> (Set.{u1} α)} {s : Set.{u1} α} [_inst_2 : DiscreteTopology.{u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} α) Type.{u1} (Set.hasCoeToSort.{u1} α) s) (Subtype.topologicalSpace.{u1} α (fun (x : α) => Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) _inst_1)] {x : α}, (Filter.HasBasis.{u1, succ u2} α ι (nhds.{u1} α _inst_1 x) p t) -> (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) -> (Exists.{succ u2} ι (fun (i : ι) => Exists.{0} (p i) (fun (hi : p i) => Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) (t i) s) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)))) but is expected to have type forall {α : Type.{u2}} [_inst_1 : TopologicalSpace.{u2} α] {ι : Type.{u1}} {p : ι -> Prop} {t : ι -> (Set.{u2} α)} {s : Set.{u2} α} [_inst_2 : DiscreteTopology.{u2} (Set.Elem.{u2} α s) (instTopologicalSpaceSubtype.{u2} α (fun (x : α) => Membership.mem.{u2, u2} α (Set.{u2} α) (Set.instMembershipSet.{u2} α) x s) _inst_1)] {x : α}, (Filter.HasBasis.{u2, succ u1} α ι (nhds.{u2} α _inst_1 x) p t) -> (Membership.mem.{u2, u2} α (Set.{u2} α) (Set.instMembershipSet.{u2} α) x s) -> (Exists.{succ u1} ι (fun (i : ι) => And (p i) (Eq.{succ u2} (Set.{u2} α) (Inter.inter.{u2} (Set.{u2} α) (Set.instInterSet.{u2} α) (t i) s) (Singleton.singleton.{u2, u2} α (Set.{u2} α) (Set.instSingletonSet.{u2} α) x)))) Case conversion may be inaccurate. Consider using '#align filter.has_basis.exists_inter_eq_singleton_of_mem_discrete Filter.HasBasis.exists_inter_eq_singleton_of_mem_discreteₓ'. -/ theorem Filter.HasBasis.exists_inter_eq_singleton_of_mem_discrete {ι : Type _} {p : ι → Prop} {t : ι → Set α} {s : Set α} [DiscreteTopology s] {x : α} (hb : (𝓝 x).HasBasis p t) (hx : x ∈ s) : ∃ (i : _)(hi : p i), t i ∩ s = {x} := by rcases(nhdsWithin_hasBasis hb s).mem_iff.1 (singleton_mem_nhdsWithin_of_mem_discrete hx) with ⟨i, hi, hix⟩ exact ⟨i, hi, subset.antisymm hix <| singleton_subset_iff.2 ⟨mem_of_mem_nhds <| hb.mem_of_mem hi, hx⟩⟩ #align filter.has_basis.exists_inter_eq_singleton_of_mem_discrete Filter.HasBasis.exists_inter_eq_singleton_of_mem_discrete /- warning: nhds_inter_eq_singleton_of_mem_discrete -> nhds_inter_eq_singleton_of_mem_discrete is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} [_inst_2 : DiscreteTopology.{u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} α) Type.{u1} (Set.hasCoeToSort.{u1} α) s) (Subtype.topologicalSpace.{u1} α (fun (x : α) => Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) _inst_1)] {x : α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) -> (Exists.{succ u1} (Set.{u1} α) (fun (U : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) U (nhds.{u1} α _inst_1 x)) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) U (nhds.{u1} α _inst_1 x)) => Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) U s) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} [_inst_2 : DiscreteTopology.{u1} (Set.Elem.{u1} α s) (instTopologicalSpaceSubtype.{u1} α (fun (x : α) => Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) _inst_1)] {x : α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) -> (Exists.{succ u1} (Set.{u1} α) (fun (U : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) U (nhds.{u1} α _inst_1 x)) (Eq.{succ u1} (Set.{u1} α) (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) U s) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)))) Case conversion may be inaccurate. Consider using '#align nhds_inter_eq_singleton_of_mem_discrete nhds_inter_eq_singleton_of_mem_discreteₓ'. -/ /-- A point `x` in a discrete subset `s` of a topological space admits a neighbourhood that only meets `s` at `x`. -/ theorem nhds_inter_eq_singleton_of_mem_discrete {s : Set α} [DiscreteTopology s] {x : α} (hx : x ∈ s) : ∃ U ∈ 𝓝 x, U ∩ s = {x} := by simpa using (𝓝 x).basis_sets.exists_inter_eq_singleton_of_mem_discrete hx #align nhds_inter_eq_singleton_of_mem_discrete nhds_inter_eq_singleton_of_mem_discrete /- warning: disjoint_nhds_within_of_mem_discrete -> disjoint_nhdsWithin_of_mem_discrete is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} [_inst_2 : DiscreteTopology.{u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} α) Type.{u1} (Set.hasCoeToSort.{u1} α) s) (Subtype.topologicalSpace.{u1} α (fun (x : α) => Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) _inst_1)] {x : α}, (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x s) -> (Exists.{succ u1} (Set.{u1} α) (fun (U : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) U (nhdsWithin.{u1} α _inst_1 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)))) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) U (nhdsWithin.{u1} α _inst_1 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.hasSingleton.{u1} α) x)))) => Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) U s))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {s : Set.{u1} α} [_inst_2 : DiscreteTopology.{u1} (Set.Elem.{u1} α s) (instTopologicalSpaceSubtype.{u1} α (fun (x : α) => Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) _inst_1)] {x : α}, (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x s) -> (Exists.{succ u1} (Set.{u1} α) (fun (U : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) U (nhdsWithin.{u1} α _inst_1 x (HasCompl.compl.{u1} (Set.{u1} α) (BooleanAlgebra.toHasCompl.{u1} (Set.{u1} α) (Set.instBooleanAlgebraSet.{u1} α)) (Singleton.singleton.{u1, u1} α (Set.{u1} α) (Set.instSingletonSet.{u1} α) x)))) (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) U s))) Case conversion may be inaccurate. Consider using '#align disjoint_nhds_within_of_mem_discrete disjoint_nhdsWithin_of_mem_discreteₓ'. -/ /-- For point `x` in a discrete subset `s` of a topological space, there is a set `U` such that 1. `U` is a punctured neighborhood of `x` (ie. `U ∪ {x}` is a neighbourhood of `x`), 2. `U` is disjoint from `s`. -/ theorem disjoint_nhdsWithin_of_mem_discrete {s : Set α} [DiscreteTopology s] {x : α} (hx : x ∈ s) : ∃ U ∈ 𝓝[≠] x, Disjoint U s := let ⟨V, h, h'⟩ := nhds_inter_eq_singleton_of_mem_discrete hx ⟨{x}ᶜ ∩ V, inter_mem_nhdsWithin _ h, disjoint_iff_inter_eq_empty.mpr (by rw [inter_assoc, h', compl_inter_self])⟩ #align disjoint_nhds_within_of_mem_discrete disjoint_nhdsWithin_of_mem_discrete #print TopologicalSpace.subset_trans /- /-- Let `X` be a topological space and let `s, t ⊆ X` be two subsets. If there is an inclusion `t ⊆ s`, then the topological space structure on `t` induced by `X` is the same as the one obtained by the induced topological space structure on `s`. -/ theorem TopologicalSpace.subset_trans {X : Type _} [tX : TopologicalSpace X] {s t : Set X} (ts : t ⊆ s) : (Subtype.topologicalSpace : TopologicalSpace t) = (Subtype.topologicalSpace : TopologicalSpace s).induced (Set.inclusion ts) := by change tX.induced ((coe : s → X) ∘ Set.inclusion ts) = TopologicalSpace.induced (Set.inclusion ts) (tX.induced _) rw [← induced_compose] #align topological_space.subset_trans TopologicalSpace.subset_trans -/ #print T2Space /- /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ @[mk_iff] class T2Space (α : Type u) [TopologicalSpace α] : Prop where t2 : ∀ x y, x ≠ y → ∃ u v : Set α, IsOpen u ∧ IsOpen v ∧ x ∈ u ∧ y ∈ v ∧ Disjoint u v #align t2_space T2Space -/ /- warning: t2_separation -> t2_separation is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (u : Set.{u1} α) => Exists.{succ u1} (Set.{u1} α) (fun (v : Set.{u1} α) => And (IsOpen.{u1} α _inst_1 u) (And (IsOpen.{u1} α _inst_1 v) (And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x u) (And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) y v) (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) u v))))))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (u : Set.{u1} α) => Exists.{succ u1} (Set.{u1} α) (fun (v : Set.{u1} α) => And (IsOpen.{u1} α _inst_1 u) (And (IsOpen.{u1} α _inst_1 v) (And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x u) (And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) y v) (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) u v))))))) Case conversion may be inaccurate. Consider using '#align t2_separation t2_separationₓ'. -/ /-- Two different points can be separated by open sets. -/ theorem t2_separation [T2Space α] {x y : α} (h : x ≠ y) : ∃ u v : Set α, IsOpen u ∧ IsOpen v ∧ x ∈ u ∧ y ∈ v ∧ Disjoint u v := T2Space.t2 x y h #align t2_separation t2_separation /- warning: t2_space_iff_disjoint_nhds -> t2Space_iff_disjoint_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T2Space.{u1} α _inst_1) (forall (x : α) (y : α), (Ne.{succ u1} α x y) -> (Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) (nhds.{u1} α _inst_1 x) (nhds.{u1} α _inst_1 y))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T2Space.{u1} α _inst_1) (forall (x : α) (y : α), (Ne.{succ u1} α x y) -> (Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) (nhds.{u1} α _inst_1 x) (nhds.{u1} α _inst_1 y))) Case conversion may be inaccurate. Consider using '#align t2_space_iff_disjoint_nhds t2Space_iff_disjoint_nhdsₓ'. -/ theorem t2Space_iff_disjoint_nhds : T2Space α ↔ ∀ x y : α, x ≠ y → Disjoint (𝓝 x) (𝓝 y) := by refine' (t2Space_iff α).trans (forall₃_congr fun x y hne => _) simp only [(nhds_basis_opens x).disjoint_iff (nhds_basis_opens y), exists_prop, ← exists_and_left, and_assoc, and_comm', and_left_comm] #align t2_space_iff_disjoint_nhds t2Space_iff_disjoint_nhds /- warning: disjoint_nhds_nhds -> disjoint_nhds_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] {x : α} {y : α}, Iff (Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) (nhds.{u1} α _inst_1 x) (nhds.{u1} α _inst_1 y)) (Ne.{succ u1} α x y) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] {x : α} {y : α}, Iff (Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) (nhds.{u1} α _inst_1 x) (nhds.{u1} α _inst_1 y)) (Ne.{succ u1} α x y) Case conversion may be inaccurate. Consider using '#align disjoint_nhds_nhds disjoint_nhds_nhdsₓ'. -/ @[simp] theorem disjoint_nhds_nhds [T2Space α] {x y : α} : Disjoint (𝓝 x) (𝓝 y) ↔ x ≠ y := ⟨fun hd he => by simpa [he, nhds_ne_bot.ne] using hd, t2Space_iff_disjoint_nhds.mp ‹_› x y⟩ #align disjoint_nhds_nhds disjoint_nhds_nhds /- warning: pairwise_disjoint_nhds -> pairwise_disjoint_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1], Pairwise.{u1} α (Function.onFun.{succ u1, succ u1, 1} α (Filter.{u1} α) Prop (Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α)))) (nhds.{u1} α _inst_1)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1], Pairwise.{u1} α (Function.onFun.{succ u1, succ u1, 1} α (Filter.{u1} α) Prop (Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α)))) (nhds.{u1} α _inst_1)) Case conversion may be inaccurate. Consider using '#align pairwise_disjoint_nhds pairwise_disjoint_nhdsₓ'. -/ theorem pairwise_disjoint_nhds [T2Space α] : Pairwise (Disjoint on (𝓝 : α → Filter α)) := fun x y => disjoint_nhds_nhds.2 #align pairwise_disjoint_nhds pairwise_disjoint_nhds /- warning: set.pairwise_disjoint_nhds -> Set.pairwiseDisjoint_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] (s : Set.{u1} α), Set.PairwiseDisjoint.{u1, u1} (Filter.{u1} α) α (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) s (nhds.{u1} α _inst_1) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] (s : Set.{u1} α), Set.PairwiseDisjoint.{u1, u1} (Filter.{u1} α) α (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) s (nhds.{u1} α _inst_1) Case conversion may be inaccurate. Consider using '#align set.pairwise_disjoint_nhds Set.pairwiseDisjoint_nhdsₓ'. -/ protected theorem Set.pairwiseDisjoint_nhds [T2Space α] (s : Set α) : s.PairwiseDisjoint 𝓝 := pairwise_disjoint_nhds.set_pairwise s #align set.pairwise_disjoint_nhds Set.pairwiseDisjoint_nhds /- warning: set.finite.t2_separation -> Set.Finite.t2_separation is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] {s : Set.{u1} α}, (Set.Finite.{u1} α s) -> (Exists.{succ u1} (α -> (Set.{u1} α)) (fun (U : α -> (Set.{u1} α)) => And (forall (x : α), And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (U x)) (IsOpen.{u1} α _inst_1 (U x))) (Set.PairwiseDisjoint.{u1, u1} (Set.{u1} α) α (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s U))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] {s : Set.{u1} α}, (Set.Finite.{u1} α s) -> (Exists.{succ u1} (α -> (Set.{u1} α)) (fun (U : α -> (Set.{u1} α)) => And (forall (x : α), And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x (U x)) (IsOpen.{u1} α _inst_1 (U x))) (Set.PairwiseDisjoint.{u1, u1} (Set.{u1} α) α (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) s U))) Case conversion may be inaccurate. Consider using '#align set.finite.t2_separation Set.Finite.t2_separationₓ'. -/ /-- Points of a finite set can be separated by open sets from each other. -/ theorem Set.Finite.t2_separation [T2Space α] {s : Set α} (hs : s.Finite) : ∃ U : α → Set α, (∀ x, x ∈ U x ∧ IsOpen (U x)) ∧ s.PairwiseDisjoint U := s.pairwise_disjoint_nhds.exists_mem_filter_basisₓ hs nhds_basis_opens #align set.finite.t2_separation Set.Finite.t2_separation /- warning: is_open_set_of_disjoint_nhds_nhds -> isOpen_setOf_disjoint_nhds_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], IsOpen.{u1} (Prod.{u1, u1} α α) (Prod.topologicalSpace.{u1, u1} α α _inst_1 _inst_1) (setOf.{u1} (Prod.{u1, u1} α α) (fun (p : Prod.{u1, u1} α α) => Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) (nhds.{u1} α _inst_1 (Prod.fst.{u1, u1} α α p)) (nhds.{u1} α _inst_1 (Prod.snd.{u1, u1} α α p)))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], IsOpen.{u1} (Prod.{u1, u1} α α) (instTopologicalSpaceProd.{u1, u1} α α _inst_1 _inst_1) (setOf.{u1} (Prod.{u1, u1} α α) (fun (p : Prod.{u1, u1} α α) => Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) (nhds.{u1} α _inst_1 (Prod.fst.{u1, u1} α α p)) (nhds.{u1} α _inst_1 (Prod.snd.{u1, u1} α α p)))) Case conversion may be inaccurate. Consider using '#align is_open_set_of_disjoint_nhds_nhds isOpen_setOf_disjoint_nhds_nhdsₓ'. -/ theorem isOpen_setOf_disjoint_nhds_nhds : IsOpen { p : α × α | Disjoint (𝓝 p.1) (𝓝 p.2) } := by simp only [isOpen_iff_mem_nhds, Prod.forall, mem_set_of_eq] intro x y h obtain ⟨U, hU, V, hV, hd⟩ := ((nhds_basis_opens x).disjoint_iff (nhds_basis_opens y)).mp h exact mem_nhds_prod_iff.mpr ⟨U, hU.2.mem_nhds hU.1, V, hV.2.mem_nhds hV.1, fun ⟨x', y'⟩ ⟨hx', hy'⟩ => disjoint_of_disjoint_of_mem hd (hU.2.mem_nhds hx') (hV.2.mem_nhds hy')⟩ #align is_open_set_of_disjoint_nhds_nhds isOpen_setOf_disjoint_nhds_nhds #print T2Space.t1Space /- -- see Note [lower instance priority] instance (priority := 100) T2Space.t1Space [T2Space α] : T1Space α := t1Space_iff_disjoint_pure_nhds.mpr fun x y hne => (disjoint_nhds_nhds.2 hne).mono_left <| pure_le_nhds _ #align t2_space.t1_space T2Space.t1Space -/ /- warning: t2_iff_nhds -> t2_iff_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T2Space.{u1} α _inst_1) (forall {x : α} {y : α}, (Filter.NeBot.{u1} α (Inf.inf.{u1} (Filter.{u1} α) (Filter.hasInf.{u1} α) (nhds.{u1} α _inst_1 x) (nhds.{u1} α _inst_1 y))) -> (Eq.{succ u1} α x y)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T2Space.{u1} α _inst_1) (forall {x : α} {y : α}, (Filter.NeBot.{u1} α (Inf.inf.{u1} (Filter.{u1} α) (Filter.instInfFilter.{u1} α) (nhds.{u1} α _inst_1 x) (nhds.{u1} α _inst_1 y))) -> (Eq.{succ u1} α x y)) Case conversion may be inaccurate. Consider using '#align t2_iff_nhds t2_iff_nhdsₓ'. -/ /-- A space is T₂ iff the neighbourhoods of distinct points generate the bottom filter. -/ theorem t2_iff_nhds : T2Space α ↔ ∀ {x y : α}, NeBot (𝓝 x ⊓ 𝓝 y) → x = y := by simp only [t2Space_iff_disjoint_nhds, disjoint_iff, ne_bot_iff, Ne.def, not_imp_comm] #align t2_iff_nhds t2_iff_nhds /- warning: eq_of_nhds_ne_bot -> eq_of_nhds_neBot is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] {x : α} {y : α}, (Filter.NeBot.{u1} α (Inf.inf.{u1} (Filter.{u1} α) (Filter.hasInf.{u1} α) (nhds.{u1} α _inst_1 x) (nhds.{u1} α _inst_1 y))) -> (Eq.{succ u1} α x y) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] {x : α} {y : α}, (Filter.NeBot.{u1} α (Inf.inf.{u1} (Filter.{u1} α) (Filter.instInfFilter.{u1} α) (nhds.{u1} α _inst_1 x) (nhds.{u1} α _inst_1 y))) -> (Eq.{succ u1} α x y) Case conversion may be inaccurate. Consider using '#align eq_of_nhds_ne_bot eq_of_nhds_neBotₓ'. -/ theorem eq_of_nhds_neBot [T2Space α] {x y : α} (h : NeBot (𝓝 x ⊓ 𝓝 y)) : x = y := t2_iff_nhds.mp ‹_› h #align eq_of_nhds_ne_bot eq_of_nhds_neBot /- warning: t2_space_iff_nhds -> t2Space_iff_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T2Space.{u1} α _inst_1) (forall {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (U : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) U (nhds.{u1} α _inst_1 x)) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) U (nhds.{u1} α _inst_1 x)) => Exists.{succ u1} (Set.{u1} α) (fun (V : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) V (nhds.{u1} α _inst_1 y)) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) V (nhds.{u1} α _inst_1 y)) => Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) U V)))))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T2Space.{u1} α _inst_1) (forall {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (U : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) U (nhds.{u1} α _inst_1 x)) (Exists.{succ u1} (Set.{u1} α) (fun (V : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) V (nhds.{u1} α _inst_1 y)) (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) U V)))))) Case conversion may be inaccurate. Consider using '#align t2_space_iff_nhds t2Space_iff_nhdsₓ'. -/ theorem t2Space_iff_nhds : T2Space α ↔ ∀ {x y : α}, x ≠ y → ∃ U ∈ 𝓝 x, ∃ V ∈ 𝓝 y, Disjoint U V := by simp only [t2Space_iff_disjoint_nhds, Filter.disjoint_iff] #align t2_space_iff_nhds t2Space_iff_nhds /- warning: t2_separation_nhds -> t2_separation_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (u : Set.{u1} α) => Exists.{succ u1} (Set.{u1} α) (fun (v : Set.{u1} α) => And (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) u (nhds.{u1} α _inst_1 x)) (And (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) v (nhds.{u1} α _inst_1 y)) (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) u v))))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (u : Set.{u1} α) => Exists.{succ u1} (Set.{u1} α) (fun (v : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) u (nhds.{u1} α _inst_1 x)) (And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) v (nhds.{u1} α _inst_1 y)) (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) u v))))) Case conversion may be inaccurate. Consider using '#align t2_separation_nhds t2_separation_nhdsₓ'. -/ theorem t2_separation_nhds [T2Space α] {x y : α} (h : x ≠ y) : ∃ u v, u ∈ 𝓝 x ∧ v ∈ 𝓝 y ∧ Disjoint u v := let ⟨u, v, open_u, open_v, x_in, y_in, huv⟩ := t2_separation h ⟨u, v, open_u.mem_nhds x_in, open_v.mem_nhds y_in, huv⟩ #align t2_separation_nhds t2_separation_nhds /- warning: t2_separation_compact_nhds -> t2_separation_compact_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : LocallyCompactSpace.{u1} α _inst_1] [_inst_3 : T2Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (u : Set.{u1} α) => Exists.{succ u1} (Set.{u1} α) (fun (v : Set.{u1} α) => And (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) u (nhds.{u1} α _inst_1 x)) (And (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) v (nhds.{u1} α _inst_1 y)) (And (IsCompact.{u1} α _inst_1 u) (And (IsCompact.{u1} α _inst_1 v) (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) u v))))))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : LocallyCompactSpace.{u1} α _inst_1] [_inst_3 : T2Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (u : Set.{u1} α) => Exists.{succ u1} (Set.{u1} α) (fun (v : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) u (nhds.{u1} α _inst_1 x)) (And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) v (nhds.{u1} α _inst_1 y)) (And (IsCompact.{u1} α _inst_1 u) (And (IsCompact.{u1} α _inst_1 v) (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) u v))))))) Case conversion may be inaccurate. Consider using '#align t2_separation_compact_nhds t2_separation_compact_nhdsₓ'. -/ theorem t2_separation_compact_nhds [LocallyCompactSpace α] [T2Space α] {x y : α} (h : x ≠ y) : ∃ u v, u ∈ 𝓝 x ∧ v ∈ 𝓝 y ∧ IsCompact u ∧ IsCompact v ∧ Disjoint u v := by simpa only [exists_prop, ← exists_and_left, and_comm', and_assoc, and_left_comm] using ((compact_basis_nhds x).disjoint_iff (compact_basis_nhds y)).1 (disjoint_nhds_nhds.2 h) #align t2_separation_compact_nhds t2_separation_compact_nhds /- warning: t2_iff_ultrafilter -> t2_iff_ultrafilter is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T2Space.{u1} α _inst_1) (forall {x : α} {y : α} (f : Ultrafilter.{u1} α), (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) (Ultrafilter.{u1} α) (Filter.{u1} α) (HasLiftT.mk.{succ u1, succ u1} (Ultrafilter.{u1} α) (Filter.{u1} α) (CoeTCₓ.coe.{succ u1, succ u1} (Ultrafilter.{u1} α) (Filter.{u1} α) (Ultrafilter.Filter.hasCoeT.{u1} α))) f) (nhds.{u1} α _inst_1 x)) -> (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) (Ultrafilter.{u1} α) (Filter.{u1} α) (HasLiftT.mk.{succ u1, succ u1} (Ultrafilter.{u1} α) (Filter.{u1} α) (CoeTCₓ.coe.{succ u1, succ u1} (Ultrafilter.{u1} α) (Filter.{u1} α) (Ultrafilter.Filter.hasCoeT.{u1} α))) f) (nhds.{u1} α _inst_1 y)) -> (Eq.{succ u1} α x y)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T2Space.{u1} α _inst_1) (forall {x : α} {y : α} (f : Ultrafilter.{u1} α), (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (Ultrafilter.toFilter.{u1} α f) (nhds.{u1} α _inst_1 x)) -> (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (Ultrafilter.toFilter.{u1} α f) (nhds.{u1} α _inst_1 y)) -> (Eq.{succ u1} α x y)) Case conversion may be inaccurate. Consider using '#align t2_iff_ultrafilter t2_iff_ultrafilterₓ'. -/ theorem t2_iff_ultrafilter : T2Space α ↔ ∀ {x y : α} (f : Ultrafilter α), ↑f ≤ 𝓝 x → ↑f ≤ 𝓝 y → x = y := t2_iff_nhds.trans <| by simp only [← exists_ultrafilter_iff, and_imp, le_inf_iff, exists_imp] #align t2_iff_ultrafilter t2_iff_ultrafilter /- warning: t2_iff_is_closed_diagonal -> t2_iff_isClosed_diagonal is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T2Space.{u1} α _inst_1) (IsClosed.{u1} (Prod.{u1, u1} α α) (Prod.topologicalSpace.{u1, u1} α α _inst_1 _inst_1) (Set.diagonal.{u1} α)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], Iff (T2Space.{u1} α _inst_1) (IsClosed.{u1} (Prod.{u1, u1} α α) (instTopologicalSpaceProd.{u1, u1} α α _inst_1 _inst_1) (Set.diagonal.{u1} α)) Case conversion may be inaccurate. Consider using '#align t2_iff_is_closed_diagonal t2_iff_isClosed_diagonalₓ'. -/ theorem t2_iff_isClosed_diagonal : T2Space α ↔ IsClosed (diagonal α) := by simp only [t2Space_iff_disjoint_nhds, ← isOpen_compl_iff, isOpen_iff_mem_nhds, Prod.forall, nhds_prod_eq, compl_diagonal_mem_prod, mem_compl_iff, mem_diagonal_iff] #align t2_iff_is_closed_diagonal t2_iff_isClosed_diagonal /- warning: is_closed_diagonal -> isClosed_diagonal is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1], IsClosed.{u1} (Prod.{u1, u1} α α) (Prod.topologicalSpace.{u1, u1} α α _inst_1 _inst_1) (Set.diagonal.{u1} α) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1], IsClosed.{u1} (Prod.{u1, u1} α α) (instTopologicalSpaceProd.{u1, u1} α α _inst_1 _inst_1) (Set.diagonal.{u1} α) Case conversion may be inaccurate. Consider using '#align is_closed_diagonal isClosed_diagonalₓ'. -/ theorem isClosed_diagonal [T2Space α] : IsClosed (diagonal α) := t2_iff_isClosed_diagonal.mp ‹_› #align is_closed_diagonal isClosed_diagonal section Separated open SeparatedNhds Finset /- warning: finset_disjoint_finset_opens_of_t2 -> finset_disjoint_finset_opens_of_t2 is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] (s : Finset.{u1} α) (t : Finset.{u1} α), (Disjoint.{u1} (Finset.{u1} α) (Finset.partialOrder.{u1} α) (Finset.orderBot.{u1} α) s t) -> (SeparatedNhds.{u1} α _inst_1 ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) (Finset.{u1} α) (Set.{u1} α) (HasLiftT.mk.{succ u1, succ u1} (Finset.{u1} α) (Set.{u1} α) (CoeTCₓ.coe.{succ u1, succ u1} (Finset.{u1} α) (Set.{u1} α) (Finset.Set.hasCoeT.{u1} α))) s) ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) (Finset.{u1} α) (Set.{u1} α) (HasLiftT.mk.{succ u1, succ u1} (Finset.{u1} α) (Set.{u1} α) (CoeTCₓ.coe.{succ u1, succ u1} (Finset.{u1} α) (Set.{u1} α) (Finset.Set.hasCoeT.{u1} α))) t)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] (s : Finset.{u1} α) (t : Finset.{u1} α), (Disjoint.{u1} (Finset.{u1} α) (Finset.partialOrder.{u1} α) (Finset.instOrderBotFinsetToLEToPreorderPartialOrder.{u1} α) s t) -> (SeparatedNhds.{u1} α _inst_1 (Finset.toSet.{u1} α s) (Finset.toSet.{u1} α t)) Case conversion may be inaccurate. Consider using '#align finset_disjoint_finset_opens_of_t2 finset_disjoint_finset_opens_of_t2ₓ'. -/ theorem finset_disjoint_finset_opens_of_t2 [T2Space α] : ∀ s t : Finset α, Disjoint s t → SeparatedNhds (s : Set α) t := by refine' induction_on_union _ (fun a b hi d => (hi d.symm).symm) (fun a d => empty_right a) (fun a b ab => _) _ · obtain ⟨U, V, oU, oV, aU, bV, UV⟩ := t2_separation (Finset.disjoint_singleton.1 ab) refine' ⟨U, V, oU, oV, _, _, UV⟩ <;> exact singleton_subset_set_iff.mpr ‹_› · intro a b c ac bc d apply_mod_cast union_left (ac (disjoint_of_subset_left (a.subset_union_left b) d)) (bc _) exact disjoint_of_subset_left (a.subset_union_right b) d #align finset_disjoint_finset_opens_of_t2 finset_disjoint_finset_opens_of_t2 #print point_disjoint_finset_opens_of_t2 /- theorem point_disjoint_finset_opens_of_t2 [T2Space α] {x : α} {s : Finset α} (h : x ∉ s) : SeparatedNhds ({x} : Set α) s := by exact_mod_cast finset_disjoint_finset_opens_of_t2 {x} s (finset.disjoint_singleton_left.mpr h) #align point_disjoint_finset_opens_of_t2 point_disjoint_finset_opens_of_t2 -/ end Separated #print tendsto_nhds_unique /- theorem tendsto_nhds_unique [T2Space α] {f : β → α} {l : Filter β} {a b : α} [NeBot l] (ha : Tendsto f l (𝓝 a)) (hb : Tendsto f l (𝓝 b)) : a = b := eq_of_nhds_neBot <| neBot_of_le <| le_inf ha hb #align tendsto_nhds_unique tendsto_nhds_unique -/ #print tendsto_nhds_unique' /- theorem tendsto_nhds_unique' [T2Space α] {f : β → α} {l : Filter β} {a b : α} (hl : NeBot l) (ha : Tendsto f l (𝓝 a)) (hb : Tendsto f l (𝓝 b)) : a = b := eq_of_nhds_neBot <| neBot_of_le <| le_inf ha hb #align tendsto_nhds_unique' tendsto_nhds_unique' -/ #print tendsto_nhds_unique_of_eventuallyEq /- theorem tendsto_nhds_unique_of_eventuallyEq [T2Space α] {f g : β → α} {l : Filter β} {a b : α} [NeBot l] (ha : Tendsto f l (𝓝 a)) (hb : Tendsto g l (𝓝 b)) (hfg : f =ᶠ[l] g) : a = b := tendsto_nhds_unique (ha.congr' hfg) hb #align tendsto_nhds_unique_of_eventually_eq tendsto_nhds_unique_of_eventuallyEq -/ #print tendsto_nhds_unique_of_frequently_eq /- theorem tendsto_nhds_unique_of_frequently_eq [T2Space α] {f g : β → α} {l : Filter β} {a b : α} (ha : Tendsto f l (𝓝 a)) (hb : Tendsto g l (𝓝 b)) (hfg : ∃ᶠ x in l, f x = g x) : a = b := have : ∃ᶠ z : α × α in 𝓝 (a, b), z.1 = z.2 := (ha.prod_mk_nhds hb).Frequently hfg Classical.not_not.1 fun hne => this (isClosed_diagonal.isOpen_compl.mem_nhds hne) #align tendsto_nhds_unique_of_frequently_eq tendsto_nhds_unique_of_frequently_eq -/ #print T25Space /- /-- A T₂.₅ space, also known as a Urysohn space, is a topological space where for every pair `x ≠ y`, there are two open sets, with the intersection of closures empty, one containing `x` and the other `y` . -/ class T25Space (α : Type u) [TopologicalSpace α] : Prop where t2_5 : ∀ ⦃x y : α⦄ (h : x ≠ y), Disjoint ((𝓝 x).lift' closure) ((𝓝 y).lift' closure) #align t2_5_space T25Space -/ /- warning: disjoint_lift'_closure_nhds -> disjoint_lift'_closure_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T25Space.{u1} α _inst_1] {x : α} {y : α}, Iff (Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) (Filter.lift'.{u1, u1} α α (nhds.{u1} α _inst_1 x) (closure.{u1} α _inst_1)) (Filter.lift'.{u1, u1} α α (nhds.{u1} α _inst_1 y) (closure.{u1} α _inst_1))) (Ne.{succ u1} α x y) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T25Space.{u1} α _inst_1] {x : α} {y : α}, Iff (Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) (Filter.lift'.{u1, u1} α α (nhds.{u1} α _inst_1 x) (closure.{u1} α _inst_1)) (Filter.lift'.{u1, u1} α α (nhds.{u1} α _inst_1 y) (closure.{u1} α _inst_1))) (Ne.{succ u1} α x y) Case conversion may be inaccurate. Consider using '#align disjoint_lift'_closure_nhds disjoint_lift'_closure_nhdsₓ'. -/ @[simp] theorem disjoint_lift'_closure_nhds [T25Space α] {x y : α} : Disjoint ((𝓝 x).lift' closure) ((𝓝 y).lift' closure) ↔ x ≠ y := ⟨fun h hxy => by simpa [hxy, nhds_ne_bot.ne] using h, fun h => T25Space.t2_5 h⟩ #align disjoint_lift'_closure_nhds disjoint_lift'_closure_nhds #print T25Space.t2Space /- -- see Note [lower instance priority] instance (priority := 100) T25Space.t2Space [T25Space α] : T2Space α := t2Space_iff_disjoint_nhds.2 fun x y hne => (disjoint_lift'_closure_nhds.2 hne).mono (le_lift'_closure _) (le_lift'_closure _) #align t2_5_space.t2_space T25Space.t2Space -/ /- warning: exists_nhds_disjoint_closure -> exists_nhds_disjoint_closure is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T25Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (s : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) s (nhds.{u1} α _inst_1 x)) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) s (nhds.{u1} α _inst_1 x)) => Exists.{succ u1} (Set.{u1} α) (fun (t : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) t (nhds.{u1} α _inst_1 y)) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) t (nhds.{u1} α _inst_1 y)) => Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (closure.{u1} α _inst_1 s) (closure.{u1} α _inst_1 t)))))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T25Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (s : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) s (nhds.{u1} α _inst_1 x)) (Exists.{succ u1} (Set.{u1} α) (fun (t : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) t (nhds.{u1} α _inst_1 y)) (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (closure.{u1} α _inst_1 s) (closure.{u1} α _inst_1 t)))))) Case conversion may be inaccurate. Consider using '#align exists_nhds_disjoint_closure exists_nhds_disjoint_closureₓ'. -/ theorem exists_nhds_disjoint_closure [T25Space α] {x y : α} (h : x ≠ y) : ∃ s ∈ 𝓝 x, ∃ t ∈ 𝓝 y, Disjoint (closure s) (closure t) := ((𝓝 x).basis_sets.lift'_closure.disjoint_iff (𝓝 y).basis_sets.lift'_closure).1 <| disjoint_lift'_closure_nhds.2 h #align exists_nhds_disjoint_closure exists_nhds_disjoint_closure /- warning: exists_open_nhds_disjoint_closure -> exists_open_nhds_disjoint_closure is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T25Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (u : Set.{u1} α) => And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x u) (And (IsOpen.{u1} α _inst_1 u) (Exists.{succ u1} (Set.{u1} α) (fun (v : Set.{u1} α) => And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) y v) (And (IsOpen.{u1} α _inst_1 v) (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) (closure.{u1} α _inst_1 u) (closure.{u1} α _inst_1 v)))))))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T25Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (u : Set.{u1} α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x u) (And (IsOpen.{u1} α _inst_1 u) (Exists.{succ u1} (Set.{u1} α) (fun (v : Set.{u1} α) => And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) y v) (And (IsOpen.{u1} α _inst_1 v) (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (closure.{u1} α _inst_1 u) (closure.{u1} α _inst_1 v)))))))) Case conversion may be inaccurate. Consider using '#align exists_open_nhds_disjoint_closure exists_open_nhds_disjoint_closureₓ'. -/ theorem exists_open_nhds_disjoint_closure [T25Space α] {x y : α} (h : x ≠ y) : ∃ u : Set α, x ∈ u ∧ IsOpen u ∧ ∃ v : Set α, y ∈ v ∧ IsOpen v ∧ Disjoint (closure u) (closure v) := by simpa only [exists_prop, and_assoc] using ((nhds_basis_opens x).lift'_closure.disjoint_iff (nhds_basis_opens y).lift'_closure).1 (disjoint_lift'_closure_nhds.2 h) #align exists_open_nhds_disjoint_closure exists_open_nhds_disjoint_closure section limUnder variable [T2Space α] {f : Filter α} /-! ### Properties of `Lim` and `lim` In this section we use explicit `nonempty α` instances for `Lim` and `lim`. This way the lemmas are useful without a `nonempty α` instance. -/ /- warning: Lim_eq -> lim_eq is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] {f : Filter.{u1} α} {a : α} [_inst_3 : Filter.NeBot.{u1} α f], (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) f (nhds.{u1} α _inst_1 a)) -> (Eq.{succ u1} α (lim.{u1} α _inst_1 (Nonempty.intro.{succ u1} α a) f) a) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] {f : Filter.{u1} α} {a : α} [_inst_3 : Filter.NeBot.{u1} α f], (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) f (nhds.{u1} α _inst_1 a)) -> (Eq.{succ u1} α (lim.{u1} α _inst_1 (Nonempty.intro.{succ u1} α a) f) a) Case conversion may be inaccurate. Consider using '#align Lim_eq lim_eqₓ'. -/ theorem lim_eq {a : α} [NeBot f] (h : f ≤ 𝓝 a) : @lim _ _ ⟨a⟩ f = a := tendsto_nhds_unique (le_nhds_lim ⟨a, h⟩) h #align Lim_eq lim_eq /- warning: Lim_eq_iff -> lim_eq_iff is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] {f : Filter.{u1} α} [_inst_3 : Filter.NeBot.{u1} α f], (Exists.{succ u1} α (fun (a : α) => LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) f (nhds.{u1} α _inst_1 a))) -> (forall {a : α}, Iff (Eq.{succ u1} α (lim.{u1} α _inst_1 (Nonempty.intro.{succ u1} α a) f) a) (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) f (nhds.{u1} α _inst_1 a))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] {f : Filter.{u1} α} [_inst_3 : Filter.NeBot.{u1} α f], (Exists.{succ u1} α (fun (a : α) => LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) f (nhds.{u1} α _inst_1 a))) -> (forall {a : α}, Iff (Eq.{succ u1} α (lim.{u1} α _inst_1 (Nonempty.intro.{succ u1} α a) f) a) (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) f (nhds.{u1} α _inst_1 a))) Case conversion may be inaccurate. Consider using '#align Lim_eq_iff lim_eq_iffₓ'. -/ theorem lim_eq_iff [NeBot f] (h : ∃ a : α, f ≤ nhds a) {a} : @lim _ _ ⟨a⟩ f = a ↔ f ≤ 𝓝 a := ⟨fun c => c ▸ le_nhds_lim h, lim_eq⟩ #align Lim_eq_iff lim_eq_iff /- warning: ultrafilter.Lim_eq_iff_le_nhds -> Ultrafilter.lim_eq_iff_le_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] [_inst_3 : CompactSpace.{u1} α _inst_1] {x : α} {F : Ultrafilter.{u1} α}, Iff (Eq.{succ u1} α (Ultrafilter.lim.{u1} α _inst_1 F) x) (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) (Ultrafilter.{u1} α) (Filter.{u1} α) (HasLiftT.mk.{succ u1, succ u1} (Ultrafilter.{u1} α) (Filter.{u1} α) (CoeTCₓ.coe.{succ u1, succ u1} (Ultrafilter.{u1} α) (Filter.{u1} α) (Ultrafilter.Filter.hasCoeT.{u1} α))) F) (nhds.{u1} α _inst_1 x)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] [_inst_3 : CompactSpace.{u1} α _inst_1] {x : α} {F : Ultrafilter.{u1} α}, Iff (Eq.{succ u1} α (Ultrafilter.lim.{u1} α _inst_1 F) x) (LE.le.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (Ultrafilter.toFilter.{u1} α F) (nhds.{u1} α _inst_1 x)) Case conversion may be inaccurate. Consider using '#align ultrafilter.Lim_eq_iff_le_nhds Ultrafilter.lim_eq_iff_le_nhdsₓ'. -/ theorem Ultrafilter.lim_eq_iff_le_nhds [CompactSpace α] {x : α} {F : Ultrafilter α} : F.lim = x ↔ ↑F ≤ 𝓝 x := ⟨fun h => h ▸ F.le_nhds_lim, lim_eq⟩ #align ultrafilter.Lim_eq_iff_le_nhds Ultrafilter.lim_eq_iff_le_nhds #print isOpen_iff_ultrafilter' /- theorem isOpen_iff_ultrafilter' [CompactSpace α] (U : Set α) : IsOpen U ↔ ∀ F : Ultrafilter α, F.lim ∈ U → U ∈ F.1 := by rw [isOpen_iff_ultrafilter] refine' ⟨fun h F hF => h F.lim hF F F.le_nhds_lim, _⟩ intro cond x hx f h rw [← Ultrafilter.lim_eq_iff_le_nhds.2 h] at hx exact cond _ hx #align is_open_iff_ultrafilter' isOpen_iff_ultrafilter' -/ #print Filter.Tendsto.limUnder_eq /- theorem Filter.Tendsto.limUnder_eq {a : α} {f : Filter β} [NeBot f] {g : β → α} (h : Tendsto g f (𝓝 a)) : @limUnder _ _ _ ⟨a⟩ f g = a := lim_eq h #align filter.tendsto.lim_eq Filter.Tendsto.limUnder_eq -/ #print Filter.limUnder_eq_iff /- theorem Filter.limUnder_eq_iff {f : Filter β} [NeBot f] {g : β → α} (h : ∃ a, Tendsto g f (𝓝 a)) {a} : @limUnder _ _ _ ⟨a⟩ f g = a ↔ Tendsto g f (𝓝 a) := ⟨fun c => c ▸ tendsto_nhds_limUnder h, Filter.Tendsto.limUnder_eq⟩ #align filter.lim_eq_iff Filter.limUnder_eq_iff -/ #print Continuous.limUnder_eq /- theorem Continuous.limUnder_eq [TopologicalSpace β] {f : β → α} (h : Continuous f) (a : β) : @limUnder _ _ _ ⟨f a⟩ (𝓝 a) f = f a := (h.Tendsto a).limUnder_eq #align continuous.lim_eq Continuous.limUnder_eq -/ #print lim_nhds /- @[simp] theorem lim_nhds (a : α) : @lim _ _ ⟨a⟩ (𝓝 a) = a := lim_eq le_rfl #align Lim_nhds lim_nhds -/ #print limUnder_nhds_id /- @[simp] theorem limUnder_nhds_id (a : α) : @limUnder _ _ _ ⟨a⟩ (𝓝 a) id = a := lim_nhds a #align lim_nhds_id limUnder_nhds_id -/ #print lim_nhdsWithin /- @[simp] theorem lim_nhdsWithin {a : α} {s : Set α} (h : a ∈ closure s) : @lim _ _ ⟨a⟩ (𝓝[s] a) = a := haveI : ne_bot (𝓝[s] a) := mem_closure_iff_clusterPt.1 h lim_eq inf_le_left #align Lim_nhds_within lim_nhdsWithin -/ #print limUnder_nhdsWithin_id /- @[simp] theorem limUnder_nhdsWithin_id {a : α} {s : Set α} (h : a ∈ closure s) : @limUnder _ _ _ ⟨a⟩ (𝓝[s] a) id = a := lim_nhdsWithin h #align lim_nhds_within_id limUnder_nhdsWithin_id -/ end limUnder /-! ### `t2_space` constructions We use two lemmas to prove that various standard constructions generate Hausdorff spaces from Hausdorff spaces: * `separated_by_continuous` says that two points `x y : α` can be separated by open neighborhoods provided that there exists a continuous map `f : α → β` with a Hausdorff codomain such that `f x ≠ f y`. We use this lemma to prove that topological spaces defined using `induced` are Hausdorff spaces. * `separated_by_open_embedding` says that for an open embedding `f : α → β` of a Hausdorff space `α`, the images of two distinct points `x y : α`, `x ≠ y` can be separated by open neighborhoods. We use this lemma to prove that topological spaces defined using `coinduced` are Hausdorff spaces. -/ #print DiscreteTopology.toT2Space /- -- see Note [lower instance priority] instance (priority := 100) DiscreteTopology.toT2Space {α : Type _} [TopologicalSpace α] [DiscreteTopology α] : T2Space α := ⟨fun x y h => ⟨{x}, {y}, isOpen_discrete _, isOpen_discrete _, rfl, rfl, disjoint_singleton.2 h⟩⟩ #align discrete_topology.to_t2_space DiscreteTopology.toT2Space -/ /- warning: separated_by_continuous -> separated_by_continuous is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_2 : TopologicalSpace.{u1} α] [_inst_3 : TopologicalSpace.{u2} β] [_inst_4 : T2Space.{u2} β _inst_3] {f : α -> β}, (Continuous.{u1, u2} α β _inst_2 _inst_3 f) -> (forall {x : α} {y : α}, (Ne.{succ u2} β (f x) (f y)) -> (Exists.{succ u1} (Set.{u1} α) (fun (u : Set.{u1} α) => Exists.{succ u1} (Set.{u1} α) (fun (v : Set.{u1} α) => And (IsOpen.{u1} α _inst_2 u) (And (IsOpen.{u1} α _inst_2 v) (And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x u) (And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) y v) (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) u v)))))))) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} [_inst_2 : TopologicalSpace.{u2} α] [_inst_3 : TopologicalSpace.{u1} β] [_inst_4 : T2Space.{u1} β _inst_3] {f : α -> β}, (Continuous.{u2, u1} α β _inst_2 _inst_3 f) -> (forall {x : α} {y : α}, (Ne.{succ u1} β (f x) (f y)) -> (Exists.{succ u2} (Set.{u2} α) (fun (u : Set.{u2} α) => Exists.{succ u2} (Set.{u2} α) (fun (v : Set.{u2} α) => And (IsOpen.{u2} α _inst_2 u) (And (IsOpen.{u2} α _inst_2 v) (And (Membership.mem.{u2, u2} α (Set.{u2} α) (Set.instMembershipSet.{u2} α) x u) (And (Membership.mem.{u2, u2} α (Set.{u2} α) (Set.instMembershipSet.{u2} α) y v) (Disjoint.{u2} (Set.{u2} α) (CompleteSemilatticeInf.toPartialOrder.{u2} (Set.{u2} α) (CompleteLattice.toCompleteSemilatticeInf.{u2} (Set.{u2} α) (Order.Coframe.toCompleteLattice.{u2} (Set.{u2} α) (CompleteDistribLattice.toCoframe.{u2} (Set.{u2} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u2} (Set.{u2} α) (Set.instCompleteBooleanAlgebraSet.{u2} α)))))) (BoundedOrder.toOrderBot.{u2} (Set.{u2} α) (Preorder.toLE.{u2} (Set.{u2} α) (PartialOrder.toPreorder.{u2} (Set.{u2} α) (CompleteSemilatticeInf.toPartialOrder.{u2} (Set.{u2} α) (CompleteLattice.toCompleteSemilatticeInf.{u2} (Set.{u2} α) (Order.Coframe.toCompleteLattice.{u2} (Set.{u2} α) (CompleteDistribLattice.toCoframe.{u2} (Set.{u2} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u2} (Set.{u2} α) (Set.instCompleteBooleanAlgebraSet.{u2} α)))))))) (CompleteLattice.toBoundedOrder.{u2} (Set.{u2} α) (Order.Coframe.toCompleteLattice.{u2} (Set.{u2} α) (CompleteDistribLattice.toCoframe.{u2} (Set.{u2} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u2} (Set.{u2} α) (Set.instCompleteBooleanAlgebraSet.{u2} α)))))) u v)))))))) Case conversion may be inaccurate. Consider using '#align separated_by_continuous separated_by_continuousₓ'. -/ theorem separated_by_continuous {α : Type _} {β : Type _} [TopologicalSpace α] [TopologicalSpace β] [T2Space β] {f : α → β} (hf : Continuous f) {x y : α} (h : f x ≠ f y) : ∃ u v : Set α, IsOpen u ∧ IsOpen v ∧ x ∈ u ∧ y ∈ v ∧ Disjoint u v := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h ⟨f ⁻¹' u, f ⁻¹' v, uo.Preimage hf, vo.Preimage hf, xu, yv, uv.Preimage _⟩ #align separated_by_continuous separated_by_continuous /- warning: separated_by_open_embedding -> separated_by_openEmbedding is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_2 : TopologicalSpace.{u1} α] [_inst_3 : TopologicalSpace.{u2} β] [_inst_4 : T2Space.{u1} α _inst_2] {f : α -> β}, (OpenEmbedding.{u1, u2} α β _inst_2 _inst_3 f) -> (forall {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u2} (Set.{u2} β) (fun (u : Set.{u2} β) => Exists.{succ u2} (Set.{u2} β) (fun (v : Set.{u2} β) => And (IsOpen.{u2} β _inst_3 u) (And (IsOpen.{u2} β _inst_3 v) (And (Membership.Mem.{u2, u2} β (Set.{u2} β) (Set.hasMem.{u2} β) (f x) u) (And (Membership.Mem.{u2, u2} β (Set.{u2} β) (Set.hasMem.{u2} β) (f y) v) (Disjoint.{u2} (Set.{u2} β) (CompleteSemilatticeInf.toPartialOrder.{u2} (Set.{u2} β) (CompleteLattice.toCompleteSemilatticeInf.{u2} (Set.{u2} β) (Order.Coframe.toCompleteLattice.{u2} (Set.{u2} β) (CompleteDistribLattice.toCoframe.{u2} (Set.{u2} β) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u2} (Set.{u2} β) (Set.completeBooleanAlgebra.{u2} β)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u2} (Set.{u2} β) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u2} (Set.{u2} β) (Set.booleanAlgebra.{u2} β))) u v)))))))) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} [_inst_2 : TopologicalSpace.{u2} α] [_inst_3 : TopologicalSpace.{u1} β] [_inst_4 : T2Space.{u2} α _inst_2] {f : α -> β}, (OpenEmbedding.{u2, u1} α β _inst_2 _inst_3 f) -> (forall {x : α} {y : α}, (Ne.{succ u2} α x y) -> (Exists.{succ u1} (Set.{u1} β) (fun (u : Set.{u1} β) => Exists.{succ u1} (Set.{u1} β) (fun (v : Set.{u1} β) => And (IsOpen.{u1} β _inst_3 u) (And (IsOpen.{u1} β _inst_3 v) (And (Membership.mem.{u1, u1} β (Set.{u1} β) (Set.instMembershipSet.{u1} β) (f x) u) (And (Membership.mem.{u1, u1} β (Set.{u1} β) (Set.instMembershipSet.{u1} β) (f y) v) (Disjoint.{u1} (Set.{u1} β) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} β) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} β) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} β) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} β) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} β) (Set.instCompleteBooleanAlgebraSet.{u1} β)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} β) (Preorder.toLE.{u1} (Set.{u1} β) (PartialOrder.toPreorder.{u1} (Set.{u1} β) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} β) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} β) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} β) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} β) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} β) (Set.instCompleteBooleanAlgebraSet.{u1} β)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} β) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} β) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} β) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} β) (Set.instCompleteBooleanAlgebraSet.{u1} β)))))) u v)))))))) Case conversion may be inaccurate. Consider using '#align separated_by_open_embedding separated_by_openEmbeddingₓ'. -/ theorem separated_by_openEmbedding {α β : Type _} [TopologicalSpace α] [TopologicalSpace β] [T2Space α] {f : α → β} (hf : OpenEmbedding f) {x y : α} (h : x ≠ y) : ∃ u v : Set β, IsOpen u ∧ IsOpen v ∧ f x ∈ u ∧ f y ∈ v ∧ Disjoint u v := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h ⟨f '' u, f '' v, hf.IsOpenMap _ uo, hf.IsOpenMap _ vo, mem_image_of_mem _ xu, mem_image_of_mem _ yv, disjoint_image_of_injective hf.inj uv⟩ #align separated_by_open_embedding separated_by_openEmbedding instance {α : Type _} {p : α → Prop} [t : TopologicalSpace α] [T2Space α] : T2Space (Subtype p) := ⟨fun x y h => separated_by_continuous continuous_subtype_val (mt Subtype.eq h)⟩ instance {α : Type _} {β : Type _} [t₁ : TopologicalSpace α] [T2Space α] [t₂ : TopologicalSpace β] [T2Space β] : T2Space (α × β) := ⟨fun ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ h => Or.elim (not_and_or.mp (mt Prod.ext_iff.mpr h)) (fun h₁ => separated_by_continuous continuous_fst h₁) fun h₂ => separated_by_continuous continuous_snd h₂⟩ #print Embedding.t2Space /- theorem Embedding.t2Space [TopologicalSpace β] [T2Space β] {f : α → β} (hf : Embedding f) : T2Space α := ⟨fun x y h => separated_by_continuous hf.Continuous (hf.inj.Ne h)⟩ #align embedding.t2_space Embedding.t2Space -/ instance {α : Type _} {β : Type _} [t₁ : TopologicalSpace α] [T2Space α] [t₂ : TopologicalSpace β] [T2Space β] : T2Space (Sum α β) := by constructor rintro (x | x) (y | y) h · replace h : x ≠ y := fun c => (c.subst h) rfl exact separated_by_openEmbedding openEmbedding_inl h · exact ⟨_, _, isOpen_range_inl, isOpen_range_inr, ⟨x, rfl⟩, ⟨y, rfl⟩, is_compl_range_inl_range_inr.disjoint⟩ · exact ⟨_, _, isOpen_range_inr, isOpen_range_inl, ⟨x, rfl⟩, ⟨y, rfl⟩, is_compl_range_inl_range_inr.disjoint.symm⟩ · replace h : x ≠ y := fun c => (c.subst h) rfl exact separated_by_openEmbedding openEmbedding_inr h #print Pi.t2Space /- instance Pi.t2Space {α : Type _} {β : α → Type v} [t₂ : ∀ a, TopologicalSpace (β a)] [∀ a, T2Space (β a)] : T2Space (∀ a, β a) := ⟨fun x y h => let ⟨i, hi⟩ := not_forall.mp (mt funext h) separated_by_continuous (continuous_apply i) hi⟩ #align Pi.t2_space Pi.t2Space -/ /- warning: sigma.t2_space -> Sigma.t2Space is a dubious translation: lean 3 declaration is forall {ι : Type.{u1}} {α : ι -> Type.{u2}} [_inst_2 : forall (i : ι), TopologicalSpace.{u2} (α i)] [_inst_3 : forall (a : ι), T2Space.{u2} (α a) (_inst_2 a)], T2Space.{max u1 u2} (Sigma.{u1, u2} ι (fun (i : ι) => α i)) (Sigma.topologicalSpace.{u1, u2} ι (fun (i : ι) => α i) (fun (a : ι) => _inst_2 a)) but is expected to have type forall {ι : Type.{u1}} {α : ι -> Type.{u2}} [_inst_2 : forall (i : ι), TopologicalSpace.{u2} (α i)] [_inst_3 : forall (a : ι), T2Space.{u2} (α a) (_inst_2 a)], T2Space.{max u2 u1} (Sigma.{u1, u2} ι (fun (i : ι) => α i)) (instTopologicalSpaceSigma.{u1, u2} ι (fun (i : ι) => α i) (fun (a : ι) => _inst_2 a)) Case conversion may be inaccurate. Consider using '#align sigma.t2_space Sigma.t2Spaceₓ'. -/ instance Sigma.t2Space {ι : Type _} {α : ι → Type _} [∀ i, TopologicalSpace (α i)] [∀ a, T2Space (α a)] : T2Space (Σi, α i) := by constructor rintro ⟨i, x⟩ ⟨j, y⟩ neq rcases em (i = j) with (rfl | h) · replace neq : x ≠ y := fun c => (c.subst neq) rfl exact separated_by_openEmbedding openEmbedding_sigmaMk neq · exact ⟨_, _, isOpen_range_sigmaMk, isOpen_range_sigmaMk, ⟨x, rfl⟩, ⟨y, rfl⟩, set.disjoint_left.mpr <| by tidy⟩ #align sigma.t2_space Sigma.t2Space variable {γ : Type _} [TopologicalSpace β] [TopologicalSpace γ] #print isClosed_eq /- theorem isClosed_eq [T2Space α] {f g : β → α} (hf : Continuous f) (hg : Continuous g) : IsClosed { x : β | f x = g x } := continuous_iff_isClosed.mp (hf.prod_mk hg) _ isClosed_diagonal #align is_closed_eq isClosed_eq -/ #print isOpen_ne_fun /- theorem isOpen_ne_fun [T2Space α] {f g : β → α} (hf : Continuous f) (hg : Continuous g) : IsOpen { x : β | f x ≠ g x } := isOpen_compl_iff.mpr <| isClosed_eq hf hg #align is_open_ne_fun isOpen_ne_fun -/ #print Set.EqOn.closure /- /-- If two continuous maps are equal on `s`, then they are equal on the closure of `s`. See also `set.eq_on.of_subset_closure` for a more general version. -/ theorem Set.EqOn.closure [T2Space α] {s : Set β} {f g : β → α} (h : EqOn f g s) (hf : Continuous f) (hg : Continuous g) : EqOn f g (closure s) := closure_minimal h (isClosed_eq hf hg) #align set.eq_on.closure Set.EqOn.closure -/ #print Continuous.ext_on /- /-- If two continuous functions are equal on a dense set, then they are equal. -/ theorem Continuous.ext_on [T2Space α] {s : Set β} (hs : Dense s) {f g : β → α} (hf : Continuous f) (hg : Continuous g) (h : EqOn f g s) : f = g := funext fun x => h.closure hf hg (hs x) #align continuous.ext_on Continuous.ext_on -/ /- warning: eq_on_closure₂' -> eqOn_closure₂' is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : TopologicalSpace.{u1} α] {γ : Type.{u3}} [_inst_2 : TopologicalSpace.{u2} β] [_inst_3 : TopologicalSpace.{u3} γ] [_inst_4 : T2Space.{u1} α _inst_1] {s : Set.{u2} β} {t : Set.{u3} γ} {f : β -> γ -> α} {g : β -> γ -> α}, (forall (x : β), (Membership.Mem.{u2, u2} β (Set.{u2} β) (Set.hasMem.{u2} β) x s) -> (forall (y : γ), (Membership.Mem.{u3, u3} γ (Set.{u3} γ) (Set.hasMem.{u3} γ) y t) -> (Eq.{succ u1} α (f x y) (g x y)))) -> (forall (x : β), Continuous.{u3, u1} γ α _inst_3 _inst_1 (f x)) -> (forall (y : γ), Continuous.{u2, u1} β α _inst_2 _inst_1 (fun (x : β) => f x y)) -> (forall (x : β), Continuous.{u3, u1} γ α _inst_3 _inst_1 (g x)) -> (forall (y : γ), Continuous.{u2, u1} β α _inst_2 _inst_1 (fun (x : β) => g x y)) -> (forall (x : β), (Membership.Mem.{u2, u2} β (Set.{u2} β) (Set.hasMem.{u2} β) x (closure.{u2} β _inst_2 s)) -> (forall (y : γ), (Membership.Mem.{u3, u3} γ (Set.{u3} γ) (Set.hasMem.{u3} γ) y (closure.{u3} γ _inst_3 t)) -> (Eq.{succ u1} α (f x y) (g x y)))) but is expected to have type forall {α : Type.{u2}} {β : Type.{u3}} [_inst_1 : TopologicalSpace.{u2} α] {γ : Type.{u1}} [_inst_2 : TopologicalSpace.{u3} β] [_inst_3 : TopologicalSpace.{u1} γ] [_inst_4 : T2Space.{u2} α _inst_1] {s : Set.{u3} β} {t : Set.{u1} γ} {f : β -> γ -> α} {g : β -> γ -> α}, (forall (x : β), (Membership.mem.{u3, u3} β (Set.{u3} β) (Set.instMembershipSet.{u3} β) x s) -> (forall (y : γ), (Membership.mem.{u1, u1} γ (Set.{u1} γ) (Set.instMembershipSet.{u1} γ) y t) -> (Eq.{succ u2} α (f x y) (g x y)))) -> (forall (x : β), Continuous.{u1, u2} γ α _inst_3 _inst_1 (f x)) -> (forall (y : γ), Continuous.{u3, u2} β α _inst_2 _inst_1 (fun (x : β) => f x y)) -> (forall (x : β), Continuous.{u1, u2} γ α _inst_3 _inst_1 (g x)) -> (forall (y : γ), Continuous.{u3, u2} β α _inst_2 _inst_1 (fun (x : β) => g x y)) -> (forall (x : β), (Membership.mem.{u3, u3} β (Set.{u3} β) (Set.instMembershipSet.{u3} β) x (closure.{u3} β _inst_2 s)) -> (forall (y : γ), (Membership.mem.{u1, u1} γ (Set.{u1} γ) (Set.instMembershipSet.{u1} γ) y (closure.{u1} γ _inst_3 t)) -> (Eq.{succ u2} α (f x y) (g x y)))) Case conversion may be inaccurate. Consider using '#align eq_on_closure₂' eqOn_closure₂'ₓ'. -/ theorem eqOn_closure₂' [T2Space α] {s : Set β} {t : Set γ} {f g : β → γ → α} (h : ∀ x ∈ s, ∀ y ∈ t, f x y = g x y) (hf₁ : ∀ x, Continuous (f x)) (hf₂ : ∀ y, Continuous fun x => f x y) (hg₁ : ∀ x, Continuous (g x)) (hg₂ : ∀ y, Continuous fun x => g x y) : ∀ x ∈ closure s, ∀ y ∈ closure t, f x y = g x y := suffices closure s ⊆ ⋂ y ∈ closure t, { x | f x y = g x y } by simpa only [subset_def, mem_Inter] (closure_minimal fun x hx => mem_interᵢ₂.2 <| Set.EqOn.closure (h x hx) (hf₁ _) (hg₁ _)) <| isClosed_binterᵢ fun y hy => isClosed_eq (hf₂ _) (hg₂ _) #align eq_on_closure₂' eqOn_closure₂' /- warning: eq_on_closure₂ -> eqOn_closure₂ is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : TopologicalSpace.{u1} α] {γ : Type.{u3}} [_inst_2 : TopologicalSpace.{u2} β] [_inst_3 : TopologicalSpace.{u3} γ] [_inst_4 : T2Space.{u1} α _inst_1] {s : Set.{u2} β} {t : Set.{u3} γ} {f : β -> γ -> α} {g : β -> γ -> α}, (forall (x : β), (Membership.Mem.{u2, u2} β (Set.{u2} β) (Set.hasMem.{u2} β) x s) -> (forall (y : γ), (Membership.Mem.{u3, u3} γ (Set.{u3} γ) (Set.hasMem.{u3} γ) y t) -> (Eq.{succ u1} α (f x y) (g x y)))) -> (Continuous.{max u2 u3, u1} (Prod.{u2, u3} β γ) α (Prod.topologicalSpace.{u2, u3} β γ _inst_2 _inst_3) _inst_1 (Function.uncurry.{u2, u3, u1} β γ α f)) -> (Continuous.{max u2 u3, u1} (Prod.{u2, u3} β γ) α (Prod.topologicalSpace.{u2, u3} β γ _inst_2 _inst_3) _inst_1 (Function.uncurry.{u2, u3, u1} β γ α g)) -> (forall (x : β), (Membership.Mem.{u2, u2} β (Set.{u2} β) (Set.hasMem.{u2} β) x (closure.{u2} β _inst_2 s)) -> (forall (y : γ), (Membership.Mem.{u3, u3} γ (Set.{u3} γ) (Set.hasMem.{u3} γ) y (closure.{u3} γ _inst_3 t)) -> (Eq.{succ u1} α (f x y) (g x y)))) but is expected to have type forall {α : Type.{u2}} {β : Type.{u3}} [_inst_1 : TopologicalSpace.{u2} α] {γ : Type.{u1}} [_inst_2 : TopologicalSpace.{u3} β] [_inst_3 : TopologicalSpace.{u1} γ] [_inst_4 : T2Space.{u2} α _inst_1] {s : Set.{u3} β} {t : Set.{u1} γ} {f : β -> γ -> α} {g : β -> γ -> α}, (forall (x : β), (Membership.mem.{u3, u3} β (Set.{u3} β) (Set.instMembershipSet.{u3} β) x s) -> (forall (y : γ), (Membership.mem.{u1, u1} γ (Set.{u1} γ) (Set.instMembershipSet.{u1} γ) y t) -> (Eq.{succ u2} α (f x y) (g x y)))) -> (Continuous.{max u1 u3, u2} (Prod.{u3, u1} β γ) α (instTopologicalSpaceProd.{u3, u1} β γ _inst_2 _inst_3) _inst_1 (Function.uncurry.{u3, u1, u2} β γ α f)) -> (Continuous.{max u1 u3, u2} (Prod.{u3, u1} β γ) α (instTopologicalSpaceProd.{u3, u1} β γ _inst_2 _inst_3) _inst_1 (Function.uncurry.{u3, u1, u2} β γ α g)) -> (forall (x : β), (Membership.mem.{u3, u3} β (Set.{u3} β) (Set.instMembershipSet.{u3} β) x (closure.{u3} β _inst_2 s)) -> (forall (y : γ), (Membership.mem.{u1, u1} γ (Set.{u1} γ) (Set.instMembershipSet.{u1} γ) y (closure.{u1} γ _inst_3 t)) -> (Eq.{succ u2} α (f x y) (g x y)))) Case conversion may be inaccurate. Consider using '#align eq_on_closure₂ eqOn_closure₂ₓ'. -/ theorem eqOn_closure₂ [T2Space α] {s : Set β} {t : Set γ} {f g : β → γ → α} (h : ∀ x ∈ s, ∀ y ∈ t, f x y = g x y) (hf : Continuous (uncurry f)) (hg : Continuous (uncurry g)) : ∀ x ∈ closure s, ∀ y ∈ closure t, f x y = g x y := eqOn_closure₂' h (fun x => continuous_uncurry_left x hf) (fun x => continuous_uncurry_right x hf) (fun y => continuous_uncurry_left y hg) fun y => continuous_uncurry_right y hg #align eq_on_closure₂ eqOn_closure₂ #print Set.EqOn.of_subset_closure /- /-- If `f x = g x` for all `x ∈ s` and `f`, `g` are continuous on `t`, `s ⊆ t ⊆ closure s`, then `f x = g x` for all `x ∈ t`. See also `set.eq_on.closure`. -/ theorem Set.EqOn.of_subset_closure [T2Space α] {s t : Set β} {f g : β → α} (h : EqOn f g s) (hf : ContinuousOn f t) (hg : ContinuousOn g t) (hst : s ⊆ t) (hts : t ⊆ closure s) : EqOn f g t := by intro x hx have : (𝓝[s] x).ne_bot := mem_closure_iff_cluster_pt.mp (hts hx) exact tendsto_nhds_unique_of_eventuallyEq ((hf x hx).mono_left <| nhdsWithin_mono _ hst) ((hg x hx).mono_left <| nhdsWithin_mono _ hst) (h.eventually_eq_of_mem self_mem_nhdsWithin) #align set.eq_on.of_subset_closure Set.EqOn.of_subset_closure -/ #print Function.LeftInverse.closed_range /- theorem Function.LeftInverse.closed_range [T2Space α] {f : α → β} {g : β → α} (h : Function.LeftInverse f g) (hf : Continuous f) (hg : Continuous g) : IsClosed (range g) := have : EqOn (g ∘ f) id (closure <| range g) := h.rightInvOn_range.EqOn.closure (hg.comp hf) continuous_id isClosed_of_closure_subset fun x hx => calc x = g (f x) := (this hx).symm _ ∈ _ := mem_range_self _ #align function.left_inverse.closed_range Function.LeftInverse.closed_range -/ #print Function.LeftInverse.closedEmbedding /- theorem Function.LeftInverse.closedEmbedding [T2Space α] {f : α → β} {g : β → α} (h : Function.LeftInverse f g) (hf : Continuous f) (hg : Continuous g) : ClosedEmbedding g := ⟨h.Embedding hf hg, h.closed_range hf hg⟩ #align function.left_inverse.closed_embedding Function.LeftInverse.closedEmbedding -/ /- warning: is_compact_is_compact_separated -> isCompact_isCompact_separated is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_4 : T2Space.{u1} α _inst_1] {s : Set.{u1} α} {t : Set.{u1} α}, (IsCompact.{u1} α _inst_1 s) -> (IsCompact.{u1} α _inst_1 t) -> (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) -> (SeparatedNhds.{u1} α _inst_1 s t) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_4 : T2Space.{u1} α _inst_1] {s : Set.{u1} α} {t : Set.{u1} α}, (IsCompact.{u1} α _inst_1 s) -> (IsCompact.{u1} α _inst_1 t) -> (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) s t) -> (SeparatedNhds.{u1} α _inst_1 s t) Case conversion may be inaccurate. Consider using '#align is_compact_is_compact_separated isCompact_isCompact_separatedₓ'. -/ theorem isCompact_isCompact_separated [T2Space α] {s t : Set α} (hs : IsCompact s) (ht : IsCompact t) (hst : Disjoint s t) : SeparatedNhds s t := by simp only [SeparatedNhds, prod_subset_compl_diagonal_iff_disjoint.symm] at hst⊢ <;> exact generalized_tube_lemma hs ht is_closed_diagonal.is_open_compl hst #align is_compact_is_compact_separated isCompact_isCompact_separated #print IsCompact.isClosed /- /-- In a `t2_space`, every compact set is closed. -/ theorem IsCompact.isClosed [T2Space α] {s : Set α} (hs : IsCompact s) : IsClosed s := isOpen_compl_iff.1 <| isOpen_iff_forall_mem_open.mpr fun x hx => let ⟨u, v, uo, vo, su, xv, uv⟩ := isCompact_isCompact_separated hs isCompact_singleton (disjoint_singleton_right.2 hx) ⟨v, (uv.mono_left <| show s ≤ u from su).subset_compl_left, vo, by simpa using xv⟩ #align is_compact.is_closed IsCompact.isClosed -/ #print Filter.coclosedCompact_eq_cocompact /- @[simp] theorem Filter.coclosedCompact_eq_cocompact [T2Space α] : coclosedCompact α = cocompact α := by simp [coclosed_compact, cocompact, infᵢ_and', and_iff_right_of_imp IsCompact.isClosed] #align filter.coclosed_compact_eq_cocompact Filter.coclosedCompact_eq_cocompact -/ #print Bornology.relativelyCompact_eq_inCompact /- @[simp] theorem Bornology.relativelyCompact_eq_inCompact [T2Space α] : Bornology.relativelyCompact α = Bornology.inCompact α := by rw [Bornology.ext_iff] <;> exact Filter.coclosedCompact_eq_cocompact #align bornology.relatively_compact_eq_in_compact Bornology.relativelyCompact_eq_inCompact -/ /- warning: exists_subset_nhds_of_is_compact -> exists_subset_nhds_of_isCompact is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_4 : T2Space.{u1} α _inst_1] {ι : Type.{u2}} [_inst_5 : Nonempty.{succ u2} ι] {V : ι -> (Set.{u1} α)}, (Directed.{u1, succ u2} (Set.{u1} α) ι (Superset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α)) V) -> (forall (i : ι), IsCompact.{u1} α _inst_1 (V i)) -> (forall {U : Set.{u1} α}, (forall (x : α), (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x (Set.interᵢ.{u1, succ u2} α ι (fun (i : ι) => V i))) -> (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) U (nhds.{u1} α _inst_1 x))) -> (Exists.{succ u2} ι (fun (i : ι) => HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (V i) U))) but is expected to have type forall {α : Type.{u2}} [_inst_1 : TopologicalSpace.{u2} α] [_inst_4 : T2Space.{u2} α _inst_1] {ι : Type.{u1}} [_inst_5 : Nonempty.{succ u1} ι] {V : ι -> (Set.{u2} α)}, (Directed.{u2, succ u1} (Set.{u2} α) ι (fun ([email protected]._hyg.13080 : Set.{u2} α) ([email protected]._hyg.13082 : Set.{u2} α) => Superset.{u2} (Set.{u2} α) (Set.instHasSubsetSet.{u2} α) [email protected]._hyg.13080 [email protected]._hyg.13082) V) -> (forall (i : ι), IsCompact.{u2} α _inst_1 (V i)) -> (forall {U : Set.{u2} α}, (forall (x : α), (Membership.mem.{u2, u2} α (Set.{u2} α) (Set.instMembershipSet.{u2} α) x (Set.interᵢ.{u2, succ u1} α ι (fun (i : ι) => V i))) -> (Membership.mem.{u2, u2} (Set.{u2} α) (Filter.{u2} α) (instMembershipSetFilter.{u2} α) U (nhds.{u2} α _inst_1 x))) -> (Exists.{succ u1} ι (fun (i : ι) => HasSubset.Subset.{u2} (Set.{u2} α) (Set.instHasSubsetSet.{u2} α) (V i) U))) Case conversion may be inaccurate. Consider using '#align exists_subset_nhds_of_is_compact exists_subset_nhds_of_isCompactₓ'. -/ /-- If `V : ι → set α` is a decreasing family of compact sets then any neighborhood of `⋂ i, V i` contains some `V i`. This is a version of `exists_subset_nhd_of_compact'` where we don't need to assume each `V i` closed because it follows from compactness since `α` is assumed to be Hausdorff. -/ theorem exists_subset_nhds_of_isCompact [T2Space α] {ι : Type _} [Nonempty ι] {V : ι → Set α} (hV : Directed (· ⊇ ·) V) (hV_cpct : ∀ i, IsCompact (V i)) {U : Set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U := exists_subset_nhds_of_isCompact' hV hV_cpct (fun i => (hV_cpct i).IsClosed) hU #align exists_subset_nhds_of_is_compact exists_subset_nhds_of_isCompact #print CompactExhaustion.isClosed /- theorem CompactExhaustion.isClosed [T2Space α] (K : CompactExhaustion α) (n : ℕ) : IsClosed (K n) := (K.IsCompact n).IsClosed #align compact_exhaustion.is_closed CompactExhaustion.isClosed -/ /- warning: is_compact.inter -> IsCompact.inter is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_4 : T2Space.{u1} α _inst_1] {s : Set.{u1} α} {t : Set.{u1} α}, (IsCompact.{u1} α _inst_1 s) -> (IsCompact.{u1} α _inst_1 t) -> (IsCompact.{u1} α _inst_1 (Inter.inter.{u1} (Set.{u1} α) (Set.hasInter.{u1} α) s t)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_4 : T2Space.{u1} α _inst_1] {s : Set.{u1} α} {t : Set.{u1} α}, (IsCompact.{u1} α _inst_1 s) -> (IsCompact.{u1} α _inst_1 t) -> (IsCompact.{u1} α _inst_1 (Inter.inter.{u1} (Set.{u1} α) (Set.instInterSet.{u1} α) s t)) Case conversion may be inaccurate. Consider using '#align is_compact.inter IsCompact.interₓ'. -/ theorem IsCompact.inter [T2Space α] {s t : Set α} (hs : IsCompact s) (ht : IsCompact t) : IsCompact (s ∩ t) := hs.inter_right <| ht.IsClosed #align is_compact.inter IsCompact.inter #print isCompact_closure_of_subset_compact /- theorem isCompact_closure_of_subset_compact [T2Space α] {s t : Set α} (ht : IsCompact t) (h : s ⊆ t) : IsCompact (closure s) := isCompact_of_isClosed_subset ht isClosed_closure (closure_minimal h ht.IsClosed) #align is_compact_closure_of_subset_compact isCompact_closure_of_subset_compact -/ #print exists_compact_superset_iff /- @[simp] theorem exists_compact_superset_iff [T2Space α] {s : Set α} : (∃ K, IsCompact K ∧ s ⊆ K) ↔ IsCompact (closure s) := ⟨fun ⟨K, hK, hsK⟩ => isCompact_closure_of_subset_compact hK hsK, fun h => ⟨closure s, h, subset_closure⟩⟩ #align exists_compact_superset_iff exists_compact_superset_iff -/ #print image_closure_of_isCompact /- theorem image_closure_of_isCompact [T2Space β] {s : Set α} (hs : IsCompact (closure s)) {f : α → β} (hf : ContinuousOn f (closure s)) : f '' closure s = closure (f '' s) := Subset.antisymm hf.image_closure <| closure_minimal (image_subset f subset_closure) (hs.image_of_continuousOn hf).IsClosed #align image_closure_of_is_compact image_closure_of_isCompact -/ /- warning: is_compact.binary_compact_cover -> IsCompact.binary_compact_cover is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_4 : T2Space.{u1} α _inst_1] {K : Set.{u1} α} {U : Set.{u1} α} {V : Set.{u1} α}, (IsCompact.{u1} α _inst_1 K) -> (IsOpen.{u1} α _inst_1 U) -> (IsOpen.{u1} α _inst_1 V) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) K (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) U V)) -> (Exists.{succ u1} (Set.{u1} α) (fun (K₁ : Set.{u1} α) => Exists.{succ u1} (Set.{u1} α) (fun (K₂ : Set.{u1} α) => And (IsCompact.{u1} α _inst_1 K₁) (And (IsCompact.{u1} α _inst_1 K₂) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) K₁ U) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) K₂ V) (Eq.{succ u1} (Set.{u1} α) K (Union.union.{u1} (Set.{u1} α) (Set.hasUnion.{u1} α) K₁ K₂)))))))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_4 : T2Space.{u1} α _inst_1] {K : Set.{u1} α} {U : Set.{u1} α} {V : Set.{u1} α}, (IsCompact.{u1} α _inst_1 K) -> (IsOpen.{u1} α _inst_1 U) -> (IsOpen.{u1} α _inst_1 V) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) K (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) U V)) -> (Exists.{succ u1} (Set.{u1} α) (fun (K₁ : Set.{u1} α) => Exists.{succ u1} (Set.{u1} α) (fun (K₂ : Set.{u1} α) => And (IsCompact.{u1} α _inst_1 K₁) (And (IsCompact.{u1} α _inst_1 K₂) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) K₁ U) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) K₂ V) (Eq.{succ u1} (Set.{u1} α) K (Union.union.{u1} (Set.{u1} α) (Set.instUnionSet.{u1} α) K₁ K₂)))))))) Case conversion may be inaccurate. Consider using '#align is_compact.binary_compact_cover IsCompact.binary_compact_coverₓ'. -/ /-- If a compact set is covered by two open sets, then we can cover it by two compact subsets. -/ theorem IsCompact.binary_compact_cover [T2Space α] {K U V : Set α} (hK : IsCompact K) (hU : IsOpen U) (hV : IsOpen V) (h2K : K ⊆ U ∪ V) : ∃ K₁ K₂ : Set α, IsCompact K₁ ∧ IsCompact K₂ ∧ K₁ ⊆ U ∧ K₂ ⊆ V ∧ K = K₁ ∪ K₂ := by obtain ⟨O₁, O₂, h1O₁, h1O₂, h2O₁, h2O₂, hO⟩ := isCompact_isCompact_separated (hK.diff hU) (hK.diff hV) (by rwa [disjoint_iff_inter_eq_empty, diff_inter_diff, diff_eq_empty]) exact ⟨_, _, hK.diff h1O₁, hK.diff h1O₂, by rwa [diff_subset_comm], by rwa [diff_subset_comm], by rw [← diff_inter, hO.inter_eq, diff_empty]⟩ #align is_compact.binary_compact_cover IsCompact.binary_compact_cover #print Continuous.isClosedMap /- theorem Continuous.isClosedMap [CompactSpace α] [T2Space β] {f : α → β} (h : Continuous f) : IsClosedMap f := fun s hs => (hs.IsCompact.image h).IsClosed #align continuous.is_closed_map Continuous.isClosedMap -/ #print Continuous.closedEmbedding /- theorem Continuous.closedEmbedding [CompactSpace α] [T2Space β] {f : α → β} (h : Continuous f) (hf : Function.Injective f) : ClosedEmbedding f := closedEmbedding_of_continuous_injective_closed h hf h.IsClosedMap #align continuous.closed_embedding Continuous.closedEmbedding -/ section open Finset Function /- warning: is_compact.finite_compact_cover -> IsCompact.finite_compact_cover is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_4 : T2Space.{u1} α _inst_1] {s : Set.{u1} α}, (IsCompact.{u1} α _inst_1 s) -> (forall {ι : Type.{u2}} (t : Finset.{u2} ι) (U : ι -> (Set.{u1} α)), (forall (i : ι), (Membership.Mem.{u2, u2} ι (Finset.{u2} ι) (Finset.hasMem.{u2} ι) i t) -> (IsOpen.{u1} α _inst_1 (U i))) -> (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) s (Set.unionᵢ.{u1, succ u2} α ι (fun (i : ι) => Set.unionᵢ.{u1, 0} α (Membership.Mem.{u2, u2} ι (Finset.{u2} ι) (Finset.hasMem.{u2} ι) i t) (fun (H : Membership.Mem.{u2, u2} ι (Finset.{u2} ι) (Finset.hasMem.{u2} ι) i t) => U i)))) -> (Exists.{max (succ u2) (succ u1)} (ι -> (Set.{u1} α)) (fun (K : ι -> (Set.{u1} α)) => And (forall (i : ι), IsCompact.{u1} α _inst_1 (K i)) (And (forall (i : ι), HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (K i) (U i)) (Eq.{succ u1} (Set.{u1} α) s (Set.unionᵢ.{u1, succ u2} α ι (fun (i : ι) => Set.unionᵢ.{u1, 0} α (Membership.Mem.{u2, u2} ι (Finset.{u2} ι) (Finset.hasMem.{u2} ι) i t) (fun (H : Membership.Mem.{u2, u2} ι (Finset.{u2} ι) (Finset.hasMem.{u2} ι) i t) => K i)))))))) but is expected to have type forall {α : Type.{u2}} [_inst_1 : TopologicalSpace.{u2} α] [_inst_4 : T2Space.{u2} α _inst_1] {s : Set.{u2} α}, (IsCompact.{u2} α _inst_1 s) -> (forall {ι : Type.{u1}} (t : Finset.{u1} ι) (U : ι -> (Set.{u2} α)), (forall (i : ι), (Membership.mem.{u1, u1} ι (Finset.{u1} ι) (Finset.instMembershipFinset.{u1} ι) i t) -> (IsOpen.{u2} α _inst_1 (U i))) -> (HasSubset.Subset.{u2} (Set.{u2} α) (Set.instHasSubsetSet.{u2} α) s (Set.unionᵢ.{u2, succ u1} α ι (fun (i : ι) => Set.unionᵢ.{u2, 0} α (Membership.mem.{u1, u1} ι (Finset.{u1} ι) (Finset.instMembershipFinset.{u1} ι) i t) (fun (H : Membership.mem.{u1, u1} ι (Finset.{u1} ι) (Finset.instMembershipFinset.{u1} ι) i t) => U i)))) -> (Exists.{max (succ u2) (succ u1)} (ι -> (Set.{u2} α)) (fun (K : ι -> (Set.{u2} α)) => And (forall (i : ι), IsCompact.{u2} α _inst_1 (K i)) (And (forall (i : ι), HasSubset.Subset.{u2} (Set.{u2} α) (Set.instHasSubsetSet.{u2} α) (K i) (U i)) (Eq.{succ u2} (Set.{u2} α) s (Set.unionᵢ.{u2, succ u1} α ι (fun (i : ι) => Set.unionᵢ.{u2, 0} α (Membership.mem.{u1, u1} ι (Finset.{u1} ι) (Finset.instMembershipFinset.{u1} ι) i t) (fun (H : Membership.mem.{u1, u1} ι (Finset.{u1} ι) (Finset.instMembershipFinset.{u1} ι) i t) => K i)))))))) Case conversion may be inaccurate. Consider using '#align is_compact.finite_compact_cover IsCompact.finite_compact_coverₓ'. -/ /-- For every finite open cover `Uᵢ` of a compact set, there exists a compact cover `Kᵢ ⊆ Uᵢ`. -/ theorem IsCompact.finite_compact_cover [T2Space α] {s : Set α} (hs : IsCompact s) {ι} (t : Finset ι) (U : ι → Set α) (hU : ∀ i ∈ t, IsOpen (U i)) (hsC : s ⊆ ⋃ i ∈ t, U i) : ∃ K : ι → Set α, (∀ i, IsCompact (K i)) ∧ (∀ i, K i ⊆ U i) ∧ s = ⋃ i ∈ t, K i := by classical induction' t using Finset.induction with x t hx ih generalizing U hU s hs hsC · refine' ⟨fun _ => ∅, fun i => isCompact_empty, fun i => empty_subset _, _⟩ simpa only [subset_empty_iff, Union_false, Union_empty] using hsC simp only [Finset.set_bunionᵢ_insert] at hsC simp only [Finset.mem_insert] at hU have hU' : ∀ i ∈ t, IsOpen (U i) := fun i hi => hU i (Or.inr hi) rcases hs.binary_compact_cover (hU x (Or.inl rfl)) (isOpen_bunionᵢ hU') hsC with ⟨K₁, K₂, h1K₁, h1K₂, h2K₁, h2K₂, hK⟩ rcases ih U hU' h1K₂ h2K₂ with ⟨K, h1K, h2K, h3K⟩ refine' ⟨update K x K₁, _, _, _⟩ · intro i by_cases hi : i = x · simp only [update_same, hi, h1K₁] · rw [← Ne.def] at hi simp only [update_noteq hi, h1K] · intro i by_cases hi : i = x · simp only [update_same, hi, h2K₁] · rw [← Ne.def] at hi simp only [update_noteq hi, h2K] · simp only [set_bUnion_insert_update _ hx, hK, h3K] #align is_compact.finite_compact_cover IsCompact.finite_compact_cover end #print locally_compact_of_compact_nhds /- theorem locally_compact_of_compact_nhds [T2Space α] (h : ∀ x : α, ∃ s, s ∈ 𝓝 x ∧ IsCompact s) : LocallyCompactSpace α := ⟨fun x n hn => let ⟨u, un, uo, xu⟩ := mem_nhds_iff.mp hn let ⟨k, kx, kc⟩ := h x -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := isCompact_isCompact_separated isCompact_singleton (kc.diffₓ uo) (disjoint_singleton_left.2 fun h => h.2 xu) have wn : wᶜ ∈ 𝓝 x := mem_nhds_iff.mpr ⟨v, vw.subset_compl_right, vo, singleton_subset_iff.mp xv⟩ ⟨k \ w, Filter.inter_mem kx wn, Subset.trans (diff_subset_comm.mp kuw) un, kc.diffₓ wo⟩⟩ #align locally_compact_of_compact_nhds locally_compact_of_compact_nhds -/ #print locally_compact_of_compact /- -- see Note [lower instance priority] instance (priority := 100) locally_compact_of_compact [T2Space α] [CompactSpace α] : LocallyCompactSpace α := locally_compact_of_compact_nhds fun x => ⟨univ, isOpen_univ.mem_nhds trivial, isCompact_univ⟩ #align locally_compact_of_compact locally_compact_of_compact -/ #print exists_open_with_compact_closure /- /-- In a locally compact T₂ space, every point has an open neighborhood with compact closure -/ theorem exists_open_with_compact_closure [LocallyCompactSpace α] [T2Space α] (x : α) : ∃ U : Set α, IsOpen U ∧ x ∈ U ∧ IsCompact (closure U) := by rcases exists_compact_mem_nhds x with ⟨K, hKc, hxK⟩ rcases mem_nhds_iff.1 hxK with ⟨t, h1t, h2t, h3t⟩ exact ⟨t, h2t, h3t, isCompact_closure_of_subset_compact hKc h1t⟩ #align exists_open_with_compact_closure exists_open_with_compact_closure -/ #print exists_open_superset_and_isCompact_closure /- /-- In a locally compact T₂ space, every compact set has an open neighborhood with compact closure. -/ theorem exists_open_superset_and_isCompact_closure [LocallyCompactSpace α] [T2Space α] {K : Set α} (hK : IsCompact K) : ∃ V, IsOpen V ∧ K ⊆ V ∧ IsCompact (closure V) := by rcases exists_compact_superset hK with ⟨K', hK', hKK'⟩ refine' ⟨interior K', isOpen_interior, hKK', isCompact_closure_of_subset_compact hK' interior_subset⟩ #align exists_open_superset_and_is_compact_closure exists_open_superset_and_isCompact_closure -/ #print exists_open_between_and_isCompact_closure /- /-- In a locally compact T₂ space, given a compact set `K` inside an open set `U`, we can find a open set `V` between these sets with compact closure: `K ⊆ V` and the closure of `V` is inside `U`. -/ theorem exists_open_between_and_isCompact_closure [LocallyCompactSpace α] [T2Space α] {K U : Set α} (hK : IsCompact K) (hU : IsOpen U) (hKU : K ⊆ U) : ∃ V, IsOpen V ∧ K ⊆ V ∧ closure V ⊆ U ∧ IsCompact (closure V) := by rcases exists_compact_between hK hU hKU with ⟨V, hV, hKV, hVU⟩ exact ⟨interior V, isOpen_interior, hKV, (closure_minimal interior_subset hV.is_closed).trans hVU, isCompact_closure_of_subset_compact hV interior_subset⟩ #align exists_open_between_and_is_compact_closure exists_open_between_and_isCompact_closure -/ #print isPreirreducible_iff_subsingleton /- theorem isPreirreducible_iff_subsingleton [T2Space α] {S : Set α} : IsPreirreducible S ↔ S.Subsingleton := by refine' ⟨fun h x hx y hy => _, Set.Subsingleton.isPreirreducible⟩ by_contra e obtain ⟨U, V, hU, hV, hxU, hyV, h'⟩ := t2_separation e exact ((h U V hU hV ⟨x, hx, hxU⟩ ⟨y, hy, hyV⟩).mono <| inter_subset_right _ _).not_disjoint h' #align is_preirreducible_iff_subsingleton isPreirreducible_iff_subsingleton -/ alias isPreirreducible_iff_subsingleton ↔ IsPreirreducible.subsingleton _ #align is_preirreducible.subsingleton IsPreirreducible.subsingleton attribute [protected] IsPreirreducible.subsingleton #print isIrreducible_iff_singleton /- theorem isIrreducible_iff_singleton [T2Space α] {S : Set α} : IsIrreducible S ↔ ∃ x, S = {x} := by rw [IsIrreducible, isPreirreducible_iff_subsingleton, exists_eq_singleton_iff_nonempty_subsingleton] #align is_irreducible_iff_singleton isIrreducible_iff_singleton -/ #print not_preirreducible_nontrivial_t2 /- /-- There does not exist a nontrivial preirreducible T₂ space. -/ theorem not_preirreducible_nontrivial_t2 (α) [TopologicalSpace α] [PreirreducibleSpace α] [Nontrivial α] [T2Space α] : False := (PreirreducibleSpace.isPreirreducible_univ α).Subsingleton.not_nontrivial nontrivial_univ #align not_preirreducible_nontrivial_t2 not_preirreducible_nontrivial_t2 -/ end Separation section RegularSpace #print RegularSpace /- /-- A topological space is called a *regular space* if for any closed set `s` and `a ∉ s`, there exist disjoint open sets `U ⊇ s` and `V ∋ a`. We formulate this condition in terms of `disjoint`ness of filters `𝓝ˢ s` and `𝓝 a`. -/ @[mk_iff] class RegularSpace (X : Type u) [TopologicalSpace X] : Prop where regular : ∀ {s : Set X} {a}, IsClosed s → a ∉ s → Disjoint (𝓝ˢ s) (𝓝 a) #align regular_space RegularSpace -/ /- warning: regular_space_tfae -> regularSpace_TFAE is a dubious translation: lean 3 declaration is forall (X : Type.{u1}) [_inst_2 : TopologicalSpace.{u1} X], List.TFAE (List.cons.{0} Prop (RegularSpace.{u1} X _inst_2) (List.cons.{0} Prop (forall (s : Set.{u1} X) (a : X), (Not (Membership.Mem.{u1, u1} X (Set.{u1} X) (Set.hasMem.{u1} X) a (closure.{u1} X _inst_2 s))) -> (Disjoint.{u1} (Filter.{u1} X) (Filter.partialOrder.{u1} X) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} X) (Preorder.toLE.{u1} (Filter.{u1} X) (PartialOrder.toPreorder.{u1} (Filter.{u1} X) (Filter.partialOrder.{u1} X))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} X) (Filter.completeLattice.{u1} X))) (nhdsSet.{u1} X _inst_2 s) (nhds.{u1} X _inst_2 a))) (List.cons.{0} Prop (forall (a : X) (s : Set.{u1} X), Iff (Disjoint.{u1} (Filter.{u1} X) (Filter.partialOrder.{u1} X) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} X) (Preorder.toLE.{u1} (Filter.{u1} X) (PartialOrder.toPreorder.{u1} (Filter.{u1} X) (Filter.partialOrder.{u1} X))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} X) (Filter.completeLattice.{u1} X))) (nhdsSet.{u1} X _inst_2 s) (nhds.{u1} X _inst_2 a)) (Not (Membership.Mem.{u1, u1} X (Set.{u1} X) (Set.hasMem.{u1} X) a (closure.{u1} X _inst_2 s)))) (List.cons.{0} Prop (forall (a : X) (s : Set.{u1} X), (Membership.Mem.{u1, u1} (Set.{u1} X) (Filter.{u1} X) (Filter.hasMem.{u1} X) s (nhds.{u1} X _inst_2 a)) -> (Exists.{succ u1} (Set.{u1} X) (fun (t : Set.{u1} X) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} X) (Filter.{u1} X) (Filter.hasMem.{u1} X) t (nhds.{u1} X _inst_2 a)) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} X) (Filter.{u1} X) (Filter.hasMem.{u1} X) t (nhds.{u1} X _inst_2 a)) => And (IsClosed.{u1} X _inst_2 t) (HasSubset.Subset.{u1} (Set.{u1} X) (Set.hasSubset.{u1} X) t s))))) (List.cons.{0} Prop (forall (a : X), LE.le.{u1} (Filter.{u1} X) (Preorder.toLE.{u1} (Filter.{u1} X) (PartialOrder.toPreorder.{u1} (Filter.{u1} X) (Filter.partialOrder.{u1} X))) (Filter.lift'.{u1, u1} X X (nhds.{u1} X _inst_2 a) (closure.{u1} X _inst_2)) (nhds.{u1} X _inst_2 a)) (List.cons.{0} Prop (forall (a : X), Eq.{succ u1} (Filter.{u1} X) (Filter.lift'.{u1, u1} X X (nhds.{u1} X _inst_2 a) (closure.{u1} X _inst_2)) (nhds.{u1} X _inst_2 a)) (List.nil.{0} Prop))))))) but is expected to have type forall (X : Type.{u1}) [_inst_2 : TopologicalSpace.{u1} X], List.TFAE (List.cons.{0} Prop (RegularSpace.{u1} X _inst_2) (List.cons.{0} Prop (forall (s : Set.{u1} X) (a : X), (Not (Membership.mem.{u1, u1} X (Set.{u1} X) (Set.instMembershipSet.{u1} X) a (closure.{u1} X _inst_2 s))) -> (Disjoint.{u1} (Filter.{u1} X) (Filter.instPartialOrderFilter.{u1} X) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} X) (Preorder.toLE.{u1} (Filter.{u1} X) (PartialOrder.toPreorder.{u1} (Filter.{u1} X) (Filter.instPartialOrderFilter.{u1} X))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} X) (Filter.instCompleteLatticeFilter.{u1} X))) (nhdsSet.{u1} X _inst_2 s) (nhds.{u1} X _inst_2 a))) (List.cons.{0} Prop (forall (a : X) (s : Set.{u1} X), Iff (Disjoint.{u1} (Filter.{u1} X) (Filter.instPartialOrderFilter.{u1} X) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} X) (Preorder.toLE.{u1} (Filter.{u1} X) (PartialOrder.toPreorder.{u1} (Filter.{u1} X) (Filter.instPartialOrderFilter.{u1} X))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} X) (Filter.instCompleteLatticeFilter.{u1} X))) (nhdsSet.{u1} X _inst_2 s) (nhds.{u1} X _inst_2 a)) (Not (Membership.mem.{u1, u1} X (Set.{u1} X) (Set.instMembershipSet.{u1} X) a (closure.{u1} X _inst_2 s)))) (List.cons.{0} Prop (forall (a : X) (s : Set.{u1} X), (Membership.mem.{u1, u1} (Set.{u1} X) (Filter.{u1} X) (instMembershipSetFilter.{u1} X) s (nhds.{u1} X _inst_2 a)) -> (Exists.{succ u1} (Set.{u1} X) (fun (t : Set.{u1} X) => And (Membership.mem.{u1, u1} (Set.{u1} X) (Filter.{u1} X) (instMembershipSetFilter.{u1} X) t (nhds.{u1} X _inst_2 a)) (And (IsClosed.{u1} X _inst_2 t) (HasSubset.Subset.{u1} (Set.{u1} X) (Set.instHasSubsetSet.{u1} X) t s))))) (List.cons.{0} Prop (forall (a : X), LE.le.{u1} (Filter.{u1} X) (Preorder.toLE.{u1} (Filter.{u1} X) (PartialOrder.toPreorder.{u1} (Filter.{u1} X) (Filter.instPartialOrderFilter.{u1} X))) (Filter.lift'.{u1, u1} X X (nhds.{u1} X _inst_2 a) (closure.{u1} X _inst_2)) (nhds.{u1} X _inst_2 a)) (List.cons.{0} Prop (forall (a : X), Eq.{succ u1} (Filter.{u1} X) (Filter.lift'.{u1, u1} X X (nhds.{u1} X _inst_2 a) (closure.{u1} X _inst_2)) (nhds.{u1} X _inst_2 a)) (List.nil.{0} Prop))))))) Case conversion may be inaccurate. Consider using '#align regular_space_tfae regularSpace_TFAEₓ'. -/ /- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (a «expr ∉ » closure[closure] s) -/ theorem regularSpace_TFAE (X : Type u) [TopologicalSpace X] : TFAE [RegularSpace X, ∀ (s : Set X) (a) (_ : a ∉ closure s), Disjoint (𝓝ˢ s) (𝓝 a), ∀ (a : X) (s : Set X), Disjoint (𝓝ˢ s) (𝓝 a) ↔ a ∉ closure s, ∀ (a : X), ∀ s ∈ 𝓝 a, ∃ t ∈ 𝓝 a, IsClosed t ∧ t ⊆ s, ∀ a : X, (𝓝 a).lift' closure ≤ 𝓝 a, ∀ a : X, (𝓝 a).lift' closure = 𝓝 a] := by tfae_have 1 ↔ 5 · rw [regularSpace_iff, (@compl_surjective (Set X) _).forall, forall_swap] simp only [isClosed_compl_iff, mem_compl_iff, Classical.not_not, @and_comm' (_ ∈ _), (nhds_basis_opens _).lift'_closure.le_basis_iffₓ (nhds_basis_opens _), and_imp, (nhds_basis_opens _).disjoint_iff_rightₓ, exists_prop, ← subset_interior_iff_mem_nhdsSet, interior_compl, compl_subset_compl] tfae_have 5 → 6; exact fun h a => (h a).antisymm (𝓝 _).le_lift'_closure tfae_have 6 → 4 · intro H a s hs rw [← H] at hs rcases(𝓝 a).basis_sets.lift'_closure.mem_iff.mp hs with ⟨U, hU, hUs⟩ exact ⟨closure U, mem_of_superset hU subset_closure, isClosed_closure, hUs⟩ tfae_have 4 → 2 · intro H s a ha have ha' : sᶜ ∈ 𝓝 a := by rwa [← mem_interior_iff_mem_nhds, interior_compl] rcases H _ _ ha' with ⟨U, hU, hUc, hUs⟩ refine' disjoint_of_disjoint_of_mem disjoint_compl_left _ hU rwa [← subset_interior_iff_mem_nhdsSet, hUc.is_open_compl.interior_eq, subset_compl_comm] tfae_have 2 → 3 · refine' fun H a s => ⟨fun hd has => mem_closure_iff_nhds_ne_bot.mp has _, H s a⟩ exact (hd.symm.mono_right <| @principal_le_nhdsSet _ _ s).eq_bot tfae_have 3 → 1; exact fun H => ⟨fun s a hs ha => (H _ _).mpr <| hs.closure_eq.symm ▸ ha⟩ tfae_finish #align regular_space_tfae regularSpace_TFAE #print RegularSpace.ofLift'_closure /- theorem RegularSpace.ofLift'_closure (h : ∀ a : α, (𝓝 a).lift' closure = 𝓝 a) : RegularSpace α := Iff.mpr ((regularSpace_TFAE α).out 0 5) h #align regular_space.of_lift'_closure RegularSpace.ofLift'_closure -/ /- warning: regular_space.of_basis -> RegularSpace.ofBasis is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] {ι : α -> Sort.{u2}} {p : forall (a : α), (ι a) -> Prop} {s : forall (a : α), (ι a) -> (Set.{u1} α)}, (forall (a : α), Filter.HasBasis.{u1, u2} α (ι a) (nhds.{u1} α _inst_1 a) (p a) (s a)) -> (forall (a : α) (i : ι a), (p a i) -> (IsClosed.{u1} α _inst_1 (s a i))) -> (RegularSpace.{u1} α _inst_1) but is expected to have type forall {α : Type.{u2}} [_inst_1 : TopologicalSpace.{u2} α] {ι : α -> Sort.{u1}} {p : forall (a : α), (ι a) -> Prop} {s : forall (a : α), (ι a) -> (Set.{u2} α)}, (forall (a : α), Filter.HasBasis.{u2, u1} α (ι a) (nhds.{u2} α _inst_1 a) (p a) (s a)) -> (forall (a : α) (i : ι a), (p a i) -> (IsClosed.{u2} α _inst_1 (s a i))) -> (RegularSpace.{u2} α _inst_1) Case conversion may be inaccurate. Consider using '#align regular_space.of_basis RegularSpace.ofBasisₓ'. -/ theorem RegularSpace.ofBasis {ι : α → Sort _} {p : ∀ a, ι a → Prop} {s : ∀ a, ι a → Set α} (h₁ : ∀ a, (𝓝 a).HasBasis (p a) (s a)) (h₂ : ∀ a i, p a i → IsClosed (s a i)) : RegularSpace α := RegularSpace.ofLift'_closure fun a => (h₁ a).lift'_closure_eq_self (h₂ a) #align regular_space.of_basis RegularSpace.ofBasis /- warning: regular_space.of_exists_mem_nhds_is_closed_subset -> RegularSpace.ofExistsMemNhdsIsClosedSubset is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], (forall (a : α) (s : Set.{u1} α), (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) s (nhds.{u1} α _inst_1 a)) -> (Exists.{succ u1} (Set.{u1} α) (fun (t : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) t (nhds.{u1} α _inst_1 a)) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) t (nhds.{u1} α _inst_1 a)) => And (IsClosed.{u1} α _inst_1 t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t s))))) -> (RegularSpace.{u1} α _inst_1) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α], (forall (a : α) (s : Set.{u1} α), (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) s (nhds.{u1} α _inst_1 a)) -> (Exists.{succ u1} (Set.{u1} α) (fun (t : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) t (nhds.{u1} α _inst_1 a)) (And (IsClosed.{u1} α _inst_1 t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t s))))) -> (RegularSpace.{u1} α _inst_1) Case conversion may be inaccurate. Consider using '#align regular_space.of_exists_mem_nhds_is_closed_subset RegularSpace.ofExistsMemNhdsIsClosedSubsetₓ'. -/ theorem RegularSpace.ofExistsMemNhdsIsClosedSubset (h : ∀ (a : α), ∀ s ∈ 𝓝 a, ∃ t ∈ 𝓝 a, IsClosed t ∧ t ⊆ s) : RegularSpace α := Iff.mpr ((regularSpace_TFAE α).out 0 3) h #align regular_space.of_exists_mem_nhds_is_closed_subset RegularSpace.ofExistsMemNhdsIsClosedSubset variable [RegularSpace α] {a : α} {s : Set α} /- warning: disjoint_nhds_set_nhds -> disjoint_nhdsSet_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1] {a : α} {s : Set.{u1} α}, Iff (Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) (nhdsSet.{u1} α _inst_1 s) (nhds.{u1} α _inst_1 a)) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a (closure.{u1} α _inst_1 s))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1] {a : α} {s : Set.{u1} α}, Iff (Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) (nhdsSet.{u1} α _inst_1 s) (nhds.{u1} α _inst_1 a)) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a (closure.{u1} α _inst_1 s))) Case conversion may be inaccurate. Consider using '#align disjoint_nhds_set_nhds disjoint_nhdsSet_nhdsₓ'. -/ theorem disjoint_nhdsSet_nhds : Disjoint (𝓝ˢ s) (𝓝 a) ↔ a ∉ closure s := Iff.mp ((regularSpace_TFAE α).out 0 2) ‹_› _ _ #align disjoint_nhds_set_nhds disjoint_nhdsSet_nhds /- warning: disjoint_nhds_nhds_set -> disjoint_nhds_nhdsSet is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1] {a : α} {s : Set.{u1} α}, Iff (Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) (nhds.{u1} α _inst_1 a) (nhdsSet.{u1} α _inst_1 s)) (Not (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a (closure.{u1} α _inst_1 s))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1] {a : α} {s : Set.{u1} α}, Iff (Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) (nhds.{u1} α _inst_1 a) (nhdsSet.{u1} α _inst_1 s)) (Not (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a (closure.{u1} α _inst_1 s))) Case conversion may be inaccurate. Consider using '#align disjoint_nhds_nhds_set disjoint_nhds_nhdsSetₓ'. -/ theorem disjoint_nhds_nhdsSet : Disjoint (𝓝 a) (𝓝ˢ s) ↔ a ∉ closure s := disjoint_comm.trans disjoint_nhdsSet_nhds #align disjoint_nhds_nhds_set disjoint_nhds_nhdsSet /- warning: exists_mem_nhds_is_closed_subset -> exists_mem_nhds_isClosed_subset is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1] {a : α} {s : Set.{u1} α}, (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) s (nhds.{u1} α _inst_1 a)) -> (Exists.{succ u1} (Set.{u1} α) (fun (t : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) t (nhds.{u1} α _inst_1 a)) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) t (nhds.{u1} α _inst_1 a)) => And (IsClosed.{u1} α _inst_1 t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) t s)))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1] {a : α} {s : Set.{u1} α}, (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) s (nhds.{u1} α _inst_1 a)) -> (Exists.{succ u1} (Set.{u1} α) (fun (t : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) t (nhds.{u1} α _inst_1 a)) (And (IsClosed.{u1} α _inst_1 t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) t s)))) Case conversion may be inaccurate. Consider using '#align exists_mem_nhds_is_closed_subset exists_mem_nhds_isClosed_subsetₓ'. -/ theorem exists_mem_nhds_isClosed_subset {a : α} {s : Set α} (h : s ∈ 𝓝 a) : ∃ t ∈ 𝓝 a, IsClosed t ∧ t ⊆ s := Iff.mp ((regularSpace_TFAE α).out 0 3) ‹_› _ _ h #align exists_mem_nhds_is_closed_subset exists_mem_nhds_isClosed_subset #print closed_nhds_basis /- theorem closed_nhds_basis (a : α) : (𝓝 a).HasBasis (fun s : Set α => s ∈ 𝓝 a ∧ IsClosed s) id := hasBasis_self.2 fun _ => exists_mem_nhds_isClosed_subset #align closed_nhds_basis closed_nhds_basis -/ #print lift'_nhds_closure /- theorem lift'_nhds_closure (a : α) : (𝓝 a).lift' closure = 𝓝 a := (closed_nhds_basis a).lift'_closure_eq_self fun s hs => hs.2 #align lift'_nhds_closure lift'_nhds_closure -/ /- warning: filter.has_basis.nhds_closure -> Filter.HasBasis.nhds_closure is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1] {ι : Sort.{u2}} {a : α} {p : ι -> Prop} {s : ι -> (Set.{u1} α)}, (Filter.HasBasis.{u1, u2} α ι (nhds.{u1} α _inst_1 a) p s) -> (Filter.HasBasis.{u1, u2} α ι (nhds.{u1} α _inst_1 a) p (fun (i : ι) => closure.{u1} α _inst_1 (s i))) but is expected to have type forall {α : Type.{u2}} [_inst_1 : TopologicalSpace.{u2} α] [_inst_2 : RegularSpace.{u2} α _inst_1] {ι : Sort.{u1}} {a : α} {p : ι -> Prop} {s : ι -> (Set.{u2} α)}, (Filter.HasBasis.{u2, u1} α ι (nhds.{u2} α _inst_1 a) p s) -> (Filter.HasBasis.{u2, u1} α ι (nhds.{u2} α _inst_1 a) p (fun (i : ι) => closure.{u2} α _inst_1 (s i))) Case conversion may be inaccurate. Consider using '#align filter.has_basis.nhds_closure Filter.HasBasis.nhds_closureₓ'. -/ theorem Filter.HasBasis.nhds_closure {ι : Sort _} {a : α} {p : ι → Prop} {s : ι → Set α} (h : (𝓝 a).HasBasis p s) : (𝓝 a).HasBasis p fun i => closure (s i) := lift'_nhds_closure a ▸ h.lift'_closure #align filter.has_basis.nhds_closure Filter.HasBasis.nhds_closure #print hasBasis_nhds_closure /- theorem hasBasis_nhds_closure (a : α) : (𝓝 a).HasBasis (fun s => s ∈ 𝓝 a) closure := (𝓝 a).basis_sets.nhds_closure #align has_basis_nhds_closure hasBasis_nhds_closure -/ #print hasBasis_opens_closure /- theorem hasBasis_opens_closure (a : α) : (𝓝 a).HasBasis (fun s => a ∈ s ∧ IsOpen s) closure := (nhds_basis_opens a).nhds_closure #align has_basis_opens_closure hasBasis_opens_closure -/ #print TopologicalSpace.IsTopologicalBasis.nhds_basis_closure /- theorem TopologicalSpace.IsTopologicalBasis.nhds_basis_closure {B : Set (Set α)} (hB : TopologicalSpace.IsTopologicalBasis B) (a : α) : (𝓝 a).HasBasis (fun s : Set α => a ∈ s ∧ s ∈ B) closure := by simpa only [and_comm'] using hB.nhds_has_basis.nhds_closure #align topological_space.is_topological_basis.nhds_basis_closure TopologicalSpace.IsTopologicalBasis.nhds_basis_closure -/ /- warning: topological_space.is_topological_basis.exists_closure_subset -> TopologicalSpace.IsTopologicalBasis.exists_closure_subset is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1] {B : Set.{u1} (Set.{u1} α)}, (TopologicalSpace.IsTopologicalBasis.{u1} α _inst_1 B) -> (forall {a : α} {s : Set.{u1} α}, (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) s (nhds.{u1} α _inst_1 a)) -> (Exists.{succ u1} (Set.{u1} α) (fun (t : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Set.{u1} (Set.{u1} α)) (Set.hasMem.{u1} (Set.{u1} α)) t B) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Set.{u1} (Set.{u1} α)) (Set.hasMem.{u1} (Set.{u1} α)) t B) => And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) a t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) (closure.{u1} α _inst_1 t) s))))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1] {B : Set.{u1} (Set.{u1} α)}, (TopologicalSpace.IsTopologicalBasis.{u1} α _inst_1 B) -> (forall {a : α} {s : Set.{u1} α}, (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) s (nhds.{u1} α _inst_1 a)) -> (Exists.{succ u1} (Set.{u1} α) (fun (t : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Set.{u1} (Set.{u1} α)) (Set.instMembershipSet.{u1} (Set.{u1} α)) t B) (And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) a t) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) (closure.{u1} α _inst_1 t) s))))) Case conversion may be inaccurate. Consider using '#align topological_space.is_topological_basis.exists_closure_subset TopologicalSpace.IsTopologicalBasis.exists_closure_subsetₓ'. -/ theorem TopologicalSpace.IsTopologicalBasis.exists_closure_subset {B : Set (Set α)} (hB : TopologicalSpace.IsTopologicalBasis B) {a : α} {s : Set α} (h : s ∈ 𝓝 a) : ∃ t ∈ B, a ∈ t ∧ closure t ⊆ s := by simpa only [exists_prop, and_assoc] using hB.nhds_has_basis.nhds_closure.mem_iff.mp h #align topological_space.is_topological_basis.exists_closure_subset TopologicalSpace.IsTopologicalBasis.exists_closure_subset /- warning: disjoint_nhds_nhds_iff_not_specializes -> disjoint_nhds_nhds_iff_not_specializes is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1] {a : α} {b : α}, Iff (Disjoint.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.partialOrder.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.completeLattice.{u1} α))) (nhds.{u1} α _inst_1 a) (nhds.{u1} α _inst_1 b)) (Not (Specializes.{u1} α _inst_1 a b)) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1] {a : α} {b : α}, Iff (Disjoint.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α) (BoundedOrder.toOrderBot.{u1} (Filter.{u1} α) (Preorder.toLE.{u1} (Filter.{u1} α) (PartialOrder.toPreorder.{u1} (Filter.{u1} α) (Filter.instPartialOrderFilter.{u1} α))) (CompleteLattice.toBoundedOrder.{u1} (Filter.{u1} α) (Filter.instCompleteLatticeFilter.{u1} α))) (nhds.{u1} α _inst_1 a) (nhds.{u1} α _inst_1 b)) (Not (Specializes.{u1} α _inst_1 a b)) Case conversion may be inaccurate. Consider using '#align disjoint_nhds_nhds_iff_not_specializes disjoint_nhds_nhds_iff_not_specializesₓ'. -/ theorem disjoint_nhds_nhds_iff_not_specializes {a b : α} : Disjoint (𝓝 a) (𝓝 b) ↔ ¬a ⤳ b := by rw [← nhdsSet_singleton, disjoint_nhdsSet_nhds, specializes_iff_mem_closure] #align disjoint_nhds_nhds_iff_not_specializes disjoint_nhds_nhds_iff_not_specializes #print specializes_comm /- theorem specializes_comm {a b : α} : a ⤳ b ↔ b ⤳ a := by simp only [← disjoint_nhds_nhds_iff_not_specializes.not_left, disjoint_comm] #align specializes_comm specializes_comm -/ alias specializes_comm ↔ Specializes.symm _ #align specializes.symm Specializes.symm #print specializes_iff_inseparable /- theorem specializes_iff_inseparable {a b : α} : a ⤳ b ↔ Inseparable a b := ⟨fun h => h.antisymm h.symm, le_of_eq⟩ #align specializes_iff_inseparable specializes_iff_inseparable -/ /- warning: is_closed_set_of_specializes -> isClosed_setOf_specializes is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1], IsClosed.{u1} (Prod.{u1, u1} α α) (Prod.topologicalSpace.{u1, u1} α α _inst_1 _inst_1) (setOf.{u1} (Prod.{u1, u1} α α) (fun (p : Prod.{u1, u1} α α) => Specializes.{u1} α _inst_1 (Prod.fst.{u1, u1} α α p) (Prod.snd.{u1, u1} α α p))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1], IsClosed.{u1} (Prod.{u1, u1} α α) (instTopologicalSpaceProd.{u1, u1} α α _inst_1 _inst_1) (setOf.{u1} (Prod.{u1, u1} α α) (fun (p : Prod.{u1, u1} α α) => Specializes.{u1} α _inst_1 (Prod.fst.{u1, u1} α α p) (Prod.snd.{u1, u1} α α p))) Case conversion may be inaccurate. Consider using '#align is_closed_set_of_specializes isClosed_setOf_specializesₓ'. -/ theorem isClosed_setOf_specializes : IsClosed { p : α × α | p.1 ⤳ p.2 } := by simp only [← isOpen_compl_iff, compl_set_of, ← disjoint_nhds_nhds_iff_not_specializes, isOpen_setOf_disjoint_nhds_nhds] #align is_closed_set_of_specializes isClosed_setOf_specializes /- warning: is_closed_set_of_inseparable -> isClosed_setOf_inseparable is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1], IsClosed.{u1} (Prod.{u1, u1} α α) (Prod.topologicalSpace.{u1, u1} α α _inst_1 _inst_1) (setOf.{u1} (Prod.{u1, u1} α α) (fun (p : Prod.{u1, u1} α α) => Inseparable.{u1} α _inst_1 (Prod.fst.{u1, u1} α α p) (Prod.snd.{u1, u1} α α p))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : RegularSpace.{u1} α _inst_1], IsClosed.{u1} (Prod.{u1, u1} α α) (instTopologicalSpaceProd.{u1, u1} α α _inst_1 _inst_1) (setOf.{u1} (Prod.{u1, u1} α α) (fun (p : Prod.{u1, u1} α α) => Inseparable.{u1} α _inst_1 (Prod.fst.{u1, u1} α α p) (Prod.snd.{u1, u1} α α p))) Case conversion may be inaccurate. Consider using '#align is_closed_set_of_inseparable isClosed_setOf_inseparableₓ'. -/ theorem isClosed_setOf_inseparable : IsClosed { p : α × α | Inseparable p.1 p.2 } := by simp only [← specializes_iff_inseparable, isClosed_setOf_specializes] #align is_closed_set_of_inseparable isClosed_setOf_inseparable #print Inducing.regularSpace /- protected theorem Inducing.regularSpace [TopologicalSpace β] {f : β → α} (hf : Inducing f) : RegularSpace β := RegularSpace.ofBasis (fun b => by rw [hf.nhds_eq_comap b] exact (closed_nhds_basis _).comap _) fun b s hs => hs.2.Preimage hf.Continuous #align inducing.regular_space Inducing.regularSpace -/ #print regularSpace_induced /- theorem regularSpace_induced (f : β → α) : @RegularSpace β (induced f ‹_›) := letI := induced f ‹_› Inducing.regularSpace ⟨rfl⟩ #align regular_space_induced regularSpace_induced -/ /- warning: regular_space_Inf -> regularSpace_infₛ is a dubious translation: lean 3 declaration is forall {X : Type.{u1}} {T : Set.{u1} (TopologicalSpace.{u1} X)}, (forall (t : TopologicalSpace.{u1} X), (Membership.Mem.{u1, u1} (TopologicalSpace.{u1} X) (Set.{u1} (TopologicalSpace.{u1} X)) (Set.hasMem.{u1} (TopologicalSpace.{u1} X)) t T) -> (RegularSpace.{u1} X t)) -> (RegularSpace.{u1} X (InfSet.infₛ.{u1} (TopologicalSpace.{u1} X) (ConditionallyCompleteLattice.toHasInf.{u1} (TopologicalSpace.{u1} X) (CompleteLattice.toConditionallyCompleteLattice.{u1} (TopologicalSpace.{u1} X) (TopologicalSpace.completeLattice.{u1} X))) T)) but is expected to have type forall {X : Type.{u1}} {T : Set.{u1} (TopologicalSpace.{u1} X)}, (forall (t : TopologicalSpace.{u1} X), (Membership.mem.{u1, u1} (TopologicalSpace.{u1} X) (Set.{u1} (TopologicalSpace.{u1} X)) (Set.instMembershipSet.{u1} (TopologicalSpace.{u1} X)) t T) -> (RegularSpace.{u1} X t)) -> (RegularSpace.{u1} X (InfSet.infₛ.{u1} (TopologicalSpace.{u1} X) (ConditionallyCompleteLattice.toInfSet.{u1} (TopologicalSpace.{u1} X) (CompleteLattice.toConditionallyCompleteLattice.{u1} (TopologicalSpace.{u1} X) (TopologicalSpace.instCompleteLatticeTopologicalSpace.{u1} X))) T)) Case conversion may be inaccurate. Consider using '#align regular_space_Inf regularSpace_infₛₓ'. -/ theorem regularSpace_infₛ {X} {T : Set (TopologicalSpace X)} (h : ∀ t ∈ T, @RegularSpace X t) : @RegularSpace X (infₛ T) := by letI := Inf T have : ∀ a, (𝓝 a).HasBasis (fun If : ΣI : Set T, I → Set X => If.1.Finite ∧ ∀ i : If.1, If.2 i ∈ @nhds X i a ∧ is_closed[↑i] (If.2 i)) fun If => ⋂ i : If.1, If.snd i := by intro a rw [nhds_infₛ, ← infᵢ_subtype''] exact has_basis_infi fun t : T => @closed_nhds_basis X t (h t t.2) a refine' RegularSpace.ofBasis this fun a If hIf => isClosed_interᵢ fun i => _ exact (hIf.2 i).2.mono (infₛ_le (i : T).2) #align regular_space_Inf regularSpace_infₛ /- warning: regular_space_infi -> regularSpace_infᵢ is a dubious translation: lean 3 declaration is forall {ι : Sort.{u1}} {X : Type.{u2}} {t : ι -> (TopologicalSpace.{u2} X)}, (forall (i : ι), RegularSpace.{u2} X (t i)) -> (RegularSpace.{u2} X (infᵢ.{u2, u1} (TopologicalSpace.{u2} X) (ConditionallyCompleteLattice.toHasInf.{u2} (TopologicalSpace.{u2} X) (CompleteLattice.toConditionallyCompleteLattice.{u2} (TopologicalSpace.{u2} X) (TopologicalSpace.completeLattice.{u2} X))) ι t)) but is expected to have type forall {ι : Sort.{u2}} {X : Type.{u1}} {t : ι -> (TopologicalSpace.{u1} X)}, (forall (i : ι), RegularSpace.{u1} X (t i)) -> (RegularSpace.{u1} X (infᵢ.{u1, u2} (TopologicalSpace.{u1} X) (ConditionallyCompleteLattice.toInfSet.{u1} (TopologicalSpace.{u1} X) (CompleteLattice.toConditionallyCompleteLattice.{u1} (TopologicalSpace.{u1} X) (TopologicalSpace.instCompleteLatticeTopologicalSpace.{u1} X))) ι t)) Case conversion may be inaccurate. Consider using '#align regular_space_infi regularSpace_infᵢₓ'. -/ theorem regularSpace_infᵢ {ι X} {t : ι → TopologicalSpace X} (h : ∀ i, @RegularSpace X (t i)) : @RegularSpace X (infᵢ t) := regularSpace_infₛ <| forall_range_iff.mpr h #align regular_space_infi regularSpace_infᵢ /- warning: regular_space.inf -> RegularSpace.inf is a dubious translation: lean 3 declaration is forall {X : Type.{u1}} {t₁ : TopologicalSpace.{u1} X} {t₂ : TopologicalSpace.{u1} X}, (RegularSpace.{u1} X t₁) -> (RegularSpace.{u1} X t₂) -> (RegularSpace.{u1} X (Inf.inf.{u1} (TopologicalSpace.{u1} X) (SemilatticeInf.toHasInf.{u1} (TopologicalSpace.{u1} X) (Lattice.toSemilatticeInf.{u1} (TopologicalSpace.{u1} X) (ConditionallyCompleteLattice.toLattice.{u1} (TopologicalSpace.{u1} X) (CompleteLattice.toConditionallyCompleteLattice.{u1} (TopologicalSpace.{u1} X) (TopologicalSpace.completeLattice.{u1} X))))) t₁ t₂)) but is expected to have type forall {X : Type.{u1}} {t₁ : TopologicalSpace.{u1} X} {t₂ : TopologicalSpace.{u1} X}, (RegularSpace.{u1} X t₁) -> (RegularSpace.{u1} X t₂) -> (RegularSpace.{u1} X (Inf.inf.{u1} (TopologicalSpace.{u1} X) (Lattice.toInf.{u1} (TopologicalSpace.{u1} X) (ConditionallyCompleteLattice.toLattice.{u1} (TopologicalSpace.{u1} X) (CompleteLattice.toConditionallyCompleteLattice.{u1} (TopologicalSpace.{u1} X) (TopologicalSpace.instCompleteLatticeTopologicalSpace.{u1} X)))) t₁ t₂)) Case conversion may be inaccurate. Consider using '#align regular_space.inf RegularSpace.infₓ'. -/ theorem RegularSpace.inf {X} {t₁ t₂ : TopologicalSpace X} (h₁ : @RegularSpace X t₁) (h₂ : @RegularSpace X t₂) : @RegularSpace X (t₁ ⊓ t₂) := by rw [inf_eq_infᵢ] exact regularSpace_infᵢ (Bool.forall_bool.2 ⟨h₂, h₁⟩) #align regular_space.inf RegularSpace.inf instance {p : α → Prop} : RegularSpace (Subtype p) := embedding_subtype_val.to_inducing.RegularSpace instance [TopologicalSpace β] [RegularSpace β] : RegularSpace (α × β) := (regularSpace_induced Prod.fst).inf (regularSpace_induced Prod.snd) instance {ι : Type _} {π : ι → Type _} [∀ i, TopologicalSpace (π i)] [∀ i, RegularSpace (π i)] : RegularSpace (∀ i, π i) := regularSpace_infᵢ fun i => regularSpace_induced _ end RegularSpace section T3 #print T3Space /- /-- A T₃ space is a T₀ space which is a regular space. Any T₃ space is a T₁ space, a T₂ space, and a T₂.₅ space. -/ class T3Space (α : Type u) [TopologicalSpace α] extends T0Space α, RegularSpace α : Prop #align t3_space T3Space -/ #print T3Space.t25Space /- -- see Note [lower instance priority] instance (priority := 100) T3Space.t25Space [T3Space α] : T25Space α := by refine' ⟨fun x y hne => _⟩ rw [lift'_nhds_closure, lift'_nhds_closure] have aux : x ∉ closure {y} ∨ y ∉ closure {x} := (t0Space_iff_or_not_mem_closure α).mp inferInstance x y hne wlog H : x ∉ closure ({y} : Set α) · refine' (this y x hne.symm aux.symm (aux.resolve_left H)).symm · rwa [← disjoint_nhds_nhdsSet, nhdsSet_singleton] at H #align t3_space.t2_5_space T3Space.t25Space -/ #print Embedding.t3Space /- protected theorem Embedding.t3Space [TopologicalSpace β] [T3Space β] {f : α → β} (hf : Embedding f) : T3Space α := { to_t0Space := hf.T0Space to_regularSpace := hf.to_inducing.RegularSpace } #align embedding.t3_space Embedding.t3Space -/ #print Subtype.t3Space /- instance Subtype.t3Space [T3Space α] {p : α → Prop} : T3Space (Subtype p) := embedding_subtype_val.T3Space #align subtype.t3_space Subtype.t3Space -/ instance [TopologicalSpace β] [T3Space α] [T3Space β] : T3Space (α × β) := ⟨⟩ instance {ι : Type _} {π : ι → Type _} [∀ i, TopologicalSpace (π i)] [∀ i, T3Space (π i)] : T3Space (∀ i, π i) := ⟨⟩ /- warning: disjoint_nested_nhds -> disjoint_nested_nhds is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T3Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (U₁ : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) U₁ (nhds.{u1} α _inst_1 x)) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) U₁ (nhds.{u1} α _inst_1 x)) => Exists.{succ u1} (Set.{u1} α) (fun (V₁ : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) V₁ (nhds.{u1} α _inst_1 x)) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) V₁ (nhds.{u1} α _inst_1 x)) => Exists.{succ u1} (Set.{u1} α) (fun (U₂ : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) U₂ (nhds.{u1} α _inst_1 y)) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) U₂ (nhds.{u1} α _inst_1 y)) => Exists.{succ u1} (Set.{u1} α) (fun (V₂ : Set.{u1} α) => Exists.{0} (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) V₂ (nhds.{u1} α _inst_1 y)) (fun (H : Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) V₂ (nhds.{u1} α _inst_1 y)) => And (IsClosed.{u1} α _inst_1 V₁) (And (IsClosed.{u1} α _inst_1 V₂) (And (IsOpen.{u1} α _inst_1 U₁) (And (IsOpen.{u1} α _inst_1 U₂) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) V₁ U₁) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) V₂ U₂) (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) U₁ U₂))))))))))))))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T3Space.{u1} α _inst_1] {x : α} {y : α}, (Ne.{succ u1} α x y) -> (Exists.{succ u1} (Set.{u1} α) (fun (U₁ : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) U₁ (nhds.{u1} α _inst_1 x)) (Exists.{succ u1} (Set.{u1} α) (fun (V₁ : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) V₁ (nhds.{u1} α _inst_1 x)) (Exists.{succ u1} (Set.{u1} α) (fun (U₂ : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) U₂ (nhds.{u1} α _inst_1 y)) (Exists.{succ u1} (Set.{u1} α) (fun (V₂ : Set.{u1} α) => And (Membership.mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (instMembershipSetFilter.{u1} α) V₂ (nhds.{u1} α _inst_1 y)) (And (IsClosed.{u1} α _inst_1 V₁) (And (IsClosed.{u1} α _inst_1 V₂) (And (IsOpen.{u1} α _inst_1 U₁) (And (IsOpen.{u1} α _inst_1 U₂) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) V₁ U₁) (And (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) V₂ U₂) (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) U₁ U₂))))))))))))))) Case conversion may be inaccurate. Consider using '#align disjoint_nested_nhds disjoint_nested_nhdsₓ'. -/ /- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (U₁ V₁ «expr ∈ » nhds() x) -/ /- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (U₂ V₂ «expr ∈ » nhds() y) -/ /-- Given two points `x ≠ y`, we can find neighbourhoods `x ∈ V₁ ⊆ U₁` and `y ∈ V₂ ⊆ U₂`, with the `Vₖ` closed and the `Uₖ` open, such that the `Uₖ` are disjoint. -/ theorem disjoint_nested_nhds [T3Space α] {x y : α} (h : x ≠ y) : ∃ (U₁ : _)(_ : U₁ ∈ 𝓝 x)(V₁ : _)(_ : V₁ ∈ 𝓝 x)(U₂ : _)(_ : U₂ ∈ 𝓝 y)(V₂ : _)(_ : V₂ ∈ 𝓝 y), IsClosed V₁ ∧ IsClosed V₂ ∧ IsOpen U₁ ∧ IsOpen U₂ ∧ V₁ ⊆ U₁ ∧ V₂ ⊆ U₂ ∧ Disjoint U₁ U₂ := by rcases t2_separation h with ⟨U₁, U₂, U₁_op, U₂_op, x_in, y_in, H⟩ rcases exists_mem_nhds_isClosed_subset (U₁_op.mem_nhds x_in) with ⟨V₁, V₁_in, V₁_closed, h₁⟩ rcases exists_mem_nhds_isClosed_subset (U₂_op.mem_nhds y_in) with ⟨V₂, V₂_in, V₂_closed, h₂⟩ exact ⟨U₁, mem_of_superset V₁_in h₁, V₁, V₁_in, U₂, mem_of_superset V₂_in h₂, V₂, V₂_in, V₁_closed, V₂_closed, U₁_op, U₂_op, h₁, h₂, H⟩ #align disjoint_nested_nhds disjoint_nested_nhds open SeparationQuotient /-- The `separation_quotient` of a regular space is a T₃ space. -/ instance [RegularSpace α] : T3Space (SeparationQuotient α) where regular s := surjective_mk.forall.2 fun a hs ha => by rw [← disjoint_comap_iff surjective_mk, comap_mk_nhds_mk, comap_mk_nhds_set] exact RegularSpace.regular (hs.preimage continuous_mk) ha end T3 section Normality #print NormalSpace /- /-- A T₄ space, also known as a normal space (although this condition sometimes omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`, there exist disjoint open sets containing `C` and `D` respectively. -/ class NormalSpace (α : Type u) [TopologicalSpace α] extends T1Space α : Prop where normal : ∀ s t : Set α, IsClosed s → IsClosed t → Disjoint s t → SeparatedNhds s t #align normal_space NormalSpace -/ /- warning: normal_separation -> normal_separation is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : NormalSpace.{u1} α _inst_1] {s : Set.{u1} α} {t : Set.{u1} α}, (IsClosed.{u1} α _inst_1 s) -> (IsClosed.{u1} α _inst_1 t) -> (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α))) s t) -> (SeparatedNhds.{u1} α _inst_1 s t) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : NormalSpace.{u1} α _inst_1] {s : Set.{u1} α} {t : Set.{u1} α}, (IsClosed.{u1} α _inst_1 s) -> (IsClosed.{u1} α _inst_1 t) -> (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) (BoundedOrder.toOrderBot.{u1} (Set.{u1} α) (Preorder.toLE.{u1} (Set.{u1} α) (PartialOrder.toPreorder.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))))) (CompleteLattice.toBoundedOrder.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.instCompleteBooleanAlgebraSet.{u1} α)))))) s t) -> (SeparatedNhds.{u1} α _inst_1 s t) Case conversion may be inaccurate. Consider using '#align normal_separation normal_separationₓ'. -/ theorem normal_separation [NormalSpace α] {s t : Set α} (H1 : IsClosed s) (H2 : IsClosed t) (H3 : Disjoint s t) : SeparatedNhds s t := NormalSpace.normal s t H1 H2 H3 #align normal_separation normal_separation #print normal_exists_closure_subset /- theorem normal_exists_closure_subset [NormalSpace α] {s t : Set α} (hs : IsClosed s) (ht : IsOpen t) (hst : s ⊆ t) : ∃ u, IsOpen u ∧ s ⊆ u ∧ closure u ⊆ t := by have : Disjoint s (tᶜ) := set.disjoint_left.mpr fun x hxs hxt => hxt (hst hxs) rcases normal_separation hs (isClosed_compl_iff.2 ht) this with ⟨s', t', hs', ht', hss', htt', hs't'⟩ refine' ⟨s', hs', hss', subset.trans (closure_minimal _ (isClosed_compl_iff.2 ht')) (compl_subset_comm.1 htt')⟩ exact fun x hxs hxt => hs't'.le_bot ⟨hxs, hxt⟩ #align normal_exists_closure_subset normal_exists_closure_subset -/ #print NormalSpace.t3Space /- -- see Note [lower instance priority] instance (priority := 100) NormalSpace.t3Space [NormalSpace α] : T3Space α where regular s x hs hxs := let ⟨u, v, hu, hv, hsu, hxv, huv⟩ := normal_separation hs isClosed_singleton (disjoint_singleton_right.mpr hxs) disjoint_of_disjoint_of_mem huv (hu.mem_nhdsSet.2 hsu) (hv.mem_nhds <| hxv rfl) #align normal_space.t3_space NormalSpace.t3Space -/ #print normalOfCompactT2 /- -- We can't make this an instance because it could cause an instance loop. theorem normalOfCompactT2 [CompactSpace α] [T2Space α] : NormalSpace α := ⟨fun s t hs ht => isCompact_isCompact_separated hs.IsCompact ht.IsCompact⟩ #align normal_of_compact_t2 normalOfCompactT2 -/ #print ClosedEmbedding.normalSpace /- protected theorem ClosedEmbedding.normalSpace [TopologicalSpace β] [NormalSpace β] {f : α → β} (hf : ClosedEmbedding f) : NormalSpace α := { to_t1Space := hf.toEmbedding.T1Space normal := by intro s t hs ht hst have H : SeparatedNhds (f '' s) (f '' t) := NormalSpace.normal (f '' s) (f '' t) (hf.is_closed_map s hs) (hf.is_closed_map t ht) (disjoint_image_of_injective hf.inj hst) exact (H.preimage hf.continuous).mono (subset_preimage_image _ _) (subset_preimage_image _ _) } #align closed_embedding.normal_space ClosedEmbedding.normalSpace -/ namespace SeparationQuotient /-- The `separation_quotient` of a normal space is a T₄ space. We don't have separate typeclasses for normal spaces (without T₁ assumption) and T₄ spaces, so we use the same class for assumption and for conclusion. One can prove this using a homeomorphism between `α` and `separation_quotient α`. We give an alternative proof that works without assuming that `α` is a T₁ space. -/ instance [NormalSpace α] : NormalSpace (SeparationQuotient α) where normal s t hs ht hd := separatedNhds_iff_disjoint.2 <| by rw [← disjoint_comap_iff surjective_mk, comap_mk_nhds_set, comap_mk_nhds_set] exact separatedNhds_iff_disjoint.1 (normal_separation (hs.preimage continuous_mk) (ht.preimage continuous_mk) (hd.preimage mk)) end SeparationQuotient variable (α) #print normalSpaceOfT3SecondCountable /- /-- A T₃ topological space with second countable topology is a normal space. This lemma is not an instance to avoid a loop. -/ theorem normalSpaceOfT3SecondCountable [SecondCountableTopology α] [T3Space α] : NormalSpace α := by have key : ∀ {s t : Set α}, IsClosed t → Disjoint s t → ∃ U : Set (countable_basis α), (s ⊆ ⋃ u ∈ U, ↑u) ∧ (∀ u ∈ U, Disjoint (closure ↑u) t) ∧ ∀ n : ℕ, IsClosed (⋃ (u ∈ U) (h : Encodable.encode u ≤ n), closure (u : Set α)) := by intro s t hc hd rw [disjoint_left] at hd have : ∀ x ∈ s, ∃ U ∈ countable_basis α, x ∈ U ∧ Disjoint (closure U) t := by intro x hx rcases(is_basis_countable_basis α).exists_closure_subset (hc.is_open_compl.mem_nhds (hd hx)) with ⟨u, hu, hxu, hut⟩ exact ⟨u, hu, hxu, disjoint_left.2 hut⟩ choose! U hu hxu hd set V : s → countable_basis α := maps_to.restrict _ _ _ hu refine' ⟨range V, _, forall_range_iff.2 <| Subtype.forall.2 hd, fun n => _⟩ · rw [bUnion_range] exact fun x hx => mem_Union.2 ⟨⟨x, hx⟩, hxu x hx⟩ · simp only [← supr_eq_Union, supᵢ_and'] exact isClosed_bunionᵢ (((finite_le_nat n).preimage_embedding (Encodable.encode' _)).Subset <| inter_subset_right _ _) fun u hu => isClosed_closure refine' ⟨fun s t hs ht hd => _⟩ rcases key ht hd with ⟨U, hsU, hUd, hUc⟩ rcases key hs hd.symm with ⟨V, htV, hVd, hVc⟩ refine' ⟨⋃ u ∈ U, ↑u \ ⋃ (v ∈ V) (hv : Encodable.encode v ≤ Encodable.encode u), closure ↑v, ⋃ v ∈ V, ↑v \ ⋃ (u ∈ U) (hu : Encodable.encode u ≤ Encodable.encode v), closure ↑u, isOpen_bunionᵢ fun u hu => (is_open_of_mem_countable_basis u.2).sdiff (hVc _), isOpen_bunionᵢ fun v hv => (is_open_of_mem_countable_basis v.2).sdiff (hUc _), fun x hx => _, fun x hx => _, _⟩ · rcases mem_Union₂.1 (hsU hx) with ⟨u, huU, hxu⟩ refine' mem_bUnion huU ⟨hxu, _⟩ simp only [mem_Union] rintro ⟨v, hvV, -, hxv⟩ exact (hVd v hvV).le_bot ⟨hxv, hx⟩ · rcases mem_Union₂.1 (htV hx) with ⟨v, hvV, hxv⟩ refine' mem_bUnion hvV ⟨hxv, _⟩ simp only [mem_Union] rintro ⟨u, huU, -, hxu⟩ exact (hUd u huU).le_bot ⟨hxu, hx⟩ · simp only [disjoint_left, mem_Union, mem_diff, not_exists, not_and, not_forall, Classical.not_not] rintro a ⟨u, huU, hau, haV⟩ v hvV hav cases' le_total (Encodable.encode u) (Encodable.encode v) with hle hle exacts[⟨u, huU, hle, subset_closure hau⟩, (haV _ hvV hle <| subset_closure hav).elim] #align normal_space_of_t3_second_countable normalSpaceOfT3SecondCountable -/ end Normality section CompletelyNormal #print T5Space /- /-- A topological space `α` is a *completely normal Hausdorff space* if each subspace `s : set α` is a normal Hausdorff space. Equivalently, `α` is a `T₁` space and for any two sets `s`, `t` such that `closure s` is disjoint with `t` and `s` is disjoint with `closure t`, there exist disjoint neighbourhoods of `s` and `t`. -/ class T5Space (α : Type u) [TopologicalSpace α] extends T1Space α : Prop where completely_normal : ∀ ⦃s t : Set α⦄, Disjoint (closure s) t → Disjoint s (closure t) → Disjoint (𝓝ˢ s) (𝓝ˢ t) #align t5_space T5Space -/ export T5Space (completely_normal) #print Embedding.t5Space /- theorem Embedding.t5Space [TopologicalSpace β] [T5Space β] {e : α → β} (he : Embedding e) : T5Space α := by haveI := he.t1_space refine' ⟨fun s t hd₁ hd₂ => _⟩ simp only [he.to_inducing.nhds_set_eq_comap] refine' disjoint_comap (completely_normal _ _) · rwa [← subset_compl_iff_disjoint_left, image_subset_iff, preimage_compl, ← he.closure_eq_preimage_closure_image, subset_compl_iff_disjoint_left] · rwa [← subset_compl_iff_disjoint_right, image_subset_iff, preimage_compl, ← he.closure_eq_preimage_closure_image, subset_compl_iff_disjoint_right] #align embedding.t5_space Embedding.t5Space -/ /-- A subspace of a `T₅` space is a `T₅` space. -/ instance [T5Space α] {p : α → Prop} : T5Space { x // p x } := embedding_subtype_val.T5Space #print T5Space.toNormalSpace /- -- see Note [lower instance priority] /-- A `T₅` space is a `T₄` space. -/ instance (priority := 100) T5Space.toNormalSpace [T5Space α] : NormalSpace α := ⟨fun s t hs ht hd => separatedNhds_iff_disjoint.2 <| completely_normal (by rwa [hs.closure_eq]) (by rwa [ht.closure_eq])⟩ #align t5_space.to_normal_space T5Space.toNormalSpace -/ open SeparationQuotient /-- The `separation_quotient` of a completely normal space is a T₅ space. We don't have separate typeclasses for completely normal spaces (without T₁ assumption) and T₅ spaces, so we use the same class for assumption and for conclusion. One can prove this using a homeomorphism between `α` and `separation_quotient α`. We give an alternative proof that works without assuming that `α` is a T₁ space. -/ instance [T5Space α] : T5Space (SeparationQuotient α) where completely_normal s t hd₁ hd₂ := by rw [← disjoint_comap_iff surjective_mk, comap_mk_nhds_set, comap_mk_nhds_set] apply T5Space.completely_normal <;> rw [← preimage_mk_closure] exacts[hd₁.preimage mk, hd₂.preimage mk] end CompletelyNormal #print connectedComponent_eq_interᵢ_clopen /- /-- In a compact t2 space, the connected component of a point equals the intersection of all its clopen neighbourhoods. -/ theorem connectedComponent_eq_interᵢ_clopen [T2Space α] [CompactSpace α] (x : α) : connectedComponent x = ⋂ Z : { Z : Set α // IsClopen Z ∧ x ∈ Z }, Z := by apply eq_of_subset_of_subset connectedComponent_subset_interᵢ_clopen -- Reduce to showing that the clopen intersection is connected. refine' IsPreconnected.subset_connectedComponent _ (mem_Inter.2 fun Z => Z.2.2) -- We do this by showing that any disjoint cover by two closed sets implies -- that one of these closed sets must contain our whole thing. -- To reduce to the case where the cover is disjoint on all of `α` we need that `s` is closed have hs : IsClosed (⋂ Z : { Z : Set α // IsClopen Z ∧ x ∈ Z }, Z : Set α) := isClosed_interᵢ fun Z => Z.2.1.2 rw [isPreconnected_iff_subset_of_fully_disjoint_closed hs] intro a b ha hb hab ab_disj haveI := @normalOfCompactT2 α _ _ _ -- Since our space is normal, we get two larger disjoint open sets containing the disjoint -- closed sets. If we can show that our intersection is a subset of any of these we can then -- "descend" this to show that it is a subset of either a or b. rcases normal_separation ha hb ab_disj with ⟨u, v, hu, hv, hau, hbv, huv⟩ -- If we can find a clopen set around x, contained in u ∪ v, we get a disjoint decomposition -- Z = Z ∩ u ∪ Z ∩ v of clopen sets. The intersection of all clopen neighbourhoods will then lie -- in whichever of u or v x lies in and hence will be a subset of either a or b. rsuffices ⟨Z, H⟩ : ∃ Z : Set α, IsClopen Z ∧ x ∈ Z ∧ Z ⊆ u ∪ v · have H1 := isClopen_inter_of_disjoint_cover_clopen H.1 H.2.2 hu hv huv rw [union_comm] at H have H2 := isClopen_inter_of_disjoint_cover_clopen H.1 H.2.2 hv hu huv.symm by_cases x ∈ u -- The x ∈ u case. · left suffices (⋂ Z : { Z : Set α // IsClopen Z ∧ x ∈ Z }, ↑Z) ⊆ u by replace hab : (⋂ Z : { Z // IsClopen Z ∧ x ∈ Z }, ↑Z) ≤ a ∪ b := hab replace this : (⋂ Z : { Z // IsClopen Z ∧ x ∈ Z }, ↑Z) ≤ u := this exact Disjoint.left_le_of_le_sup_right hab (huv.mono this hbv) · apply subset.trans _ (inter_subset_right Z u) apply Inter_subset (fun Z : { Z : Set α // IsClopen Z ∧ x ∈ Z } => ↑Z) ⟨Z ∩ u, H1, mem_inter H.2.1 h⟩ -- If x ∉ u, we get x ∈ v since x ∈ u ∪ v. The rest is then like the x ∈ u case. have h1 : x ∈ v := by cases' (mem_union x u v).1 (mem_of_subset_of_mem (subset.trans hab (union_subset_union hau hbv)) (mem_Inter.2 fun i => i.2.2)) with h1 h1 · exfalso exact h h1 · exact h1 right suffices (⋂ Z : { Z : Set α // IsClopen Z ∧ x ∈ Z }, ↑Z) ⊆ v by replace this : (⋂ Z : { Z // IsClopen Z ∧ x ∈ Z }, ↑Z) ≤ v := this exact (huv.symm.mono this hau).left_le_of_le_sup_left hab · apply subset.trans _ (inter_subset_right Z v) apply Inter_subset (fun Z : { Z : Set α // IsClopen Z ∧ x ∈ Z } => ↑Z) ⟨Z ∩ v, H2, mem_inter H.2.1 h1⟩ -- Now we find the required Z. We utilize the fact that X \ u ∪ v will be compact, -- so there must be some finite intersection of clopen neighbourhoods of X disjoint to it, -- but a finite intersection of clopen sets is clopen so we let this be our Z. have H1 := (hu.union hv).isClosed_compl.IsCompact.inter_interᵢ_nonempty (fun Z : { Z : Set α // IsClopen Z ∧ x ∈ Z } => Z) fun Z => Z.2.1.2 rw [← not_disjoint_iff_nonempty_inter, imp_not_comm, not_forall] at H1 cases' H1 (disjoint_compl_left_iff_subset.2 <| hab.trans <| union_subset_union hau hbv) with Zi H2 refine' ⟨⋂ U ∈ Zi, Subtype.val U, _, _, _⟩ · exact isClopen_binterᵢ_finset fun Z hZ => Z.2.1 · exact mem_Inter₂.2 fun Z hZ => Z.2.2 · rwa [← disjoint_compl_left_iff_subset, disjoint_iff_inter_eq_empty, ← not_nonempty_iff_eq_empty] #align connected_component_eq_Inter_clopen connectedComponent_eq_interᵢ_clopen -/ section Profinite #print totallySeparatedSpace_of_t1_of_basis_clopen /- /-- A T1 space with a clopen basis is totally separated. -/ theorem totallySeparatedSpace_of_t1_of_basis_clopen [T1Space α] (h : IsTopologicalBasis { s : Set α | IsClopen s }) : TotallySeparatedSpace α := by constructor rintro x - y - hxy rcases h.mem_nhds_iff.mp (is_open_ne.mem_nhds hxy) with ⟨U, hU, hxU, hyU⟩ exact ⟨U, Uᶜ, hU.is_open, hU.compl.is_open, hxU, fun h => hyU h rfl, (union_compl_self U).Superset, disjoint_compl_right⟩ #align totally_separated_space_of_t1_of_basis_clopen totallySeparatedSpace_of_t1_of_basis_clopen -/ variable [T2Space α] [CompactSpace α] #print compact_t2_tot_disc_iff_tot_sep /- /-- A compact Hausdorff space is totally disconnected if and only if it is totally separated, this is also true for locally compact spaces. -/ theorem compact_t2_tot_disc_iff_tot_sep : TotallyDisconnectedSpace α ↔ TotallySeparatedSpace α := by constructor · intro h constructor rintro x - y - contrapose! intro hyp suffices x ∈ connectedComponent y by simpa [totallyDisconnectedSpace_iff_connectedComponent_singleton.1 h y, mem_singleton_iff] rw [connectedComponent_eq_interᵢ_clopen, mem_Inter] rintro ⟨w : Set α, hw : IsClopen w, hy : y ∈ w⟩ by_contra hx exact hyp (wᶜ) w hw.2.isOpen_compl hw.1 hx hy (@isCompl_compl _ w _).symm.Codisjoint.top_le disjoint_compl_left apply TotallySeparatedSpace.totallyDisconnectedSpace #align compact_t2_tot_disc_iff_tot_sep compact_t2_tot_disc_iff_tot_sep -/ variable [TotallyDisconnectedSpace α] #print nhds_basis_clopen /- theorem nhds_basis_clopen (x : α) : (𝓝 x).HasBasis (fun s : Set α => x ∈ s ∧ IsClopen s) id := ⟨fun U => by constructor · have : connectedComponent x = {x} := totally_disconnected_space_iff_connected_component_singleton.mp ‹_› x rw [connectedComponent_eq_interᵢ_clopen] at this intro hU let N := { Z // IsClopen Z ∧ x ∈ Z } rsuffices ⟨⟨s, hs, hs'⟩, hs''⟩ : ∃ Z : N, Z.val ⊆ U · exact ⟨s, ⟨hs', hs⟩, hs''⟩ haveI : Nonempty N := ⟨⟨univ, isClopen_univ, mem_univ x⟩⟩ have hNcl : ∀ Z : N, IsClosed Z.val := fun Z => Z.property.1.2 have hdir : Directed Superset fun Z : N => Z.val := by rintro ⟨s, hs, hxs⟩ ⟨t, ht, hxt⟩ exact ⟨⟨s ∩ t, hs.inter ht, ⟨hxs, hxt⟩⟩, inter_subset_left s t, inter_subset_right s t⟩ have h_nhd : ∀ y ∈ ⋂ Z : N, Z.val, U ∈ 𝓝 y := by intro y y_in erw [this, mem_singleton_iff] at y_in rwa [y_in] exact exists_subset_nhds_of_compactSpace hdir hNcl h_nhd · rintro ⟨V, ⟨hxV, V_op, -⟩, hUV : V ⊆ U⟩ rw [mem_nhds_iff] exact ⟨V, hUV, V_op, hxV⟩⟩ #align nhds_basis_clopen nhds_basis_clopen -/ #print isTopologicalBasis_clopen /- theorem isTopologicalBasis_clopen : IsTopologicalBasis { s : Set α | IsClopen s } := by apply is_topological_basis_of_open_of_nhds fun U (hU : IsClopen U) => hU.1 intro x U hxU U_op have : U ∈ 𝓝 x := IsOpen.mem_nhds U_op hxU rcases(nhds_basis_clopen x).mem_iff.mp this with ⟨V, ⟨hxV, hV⟩, hVU : V ⊆ U⟩ use V tauto #align is_topological_basis_clopen isTopologicalBasis_clopen -/ /- warning: compact_exists_clopen_in_open -> compact_exists_clopen_in_open is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] [_inst_3 : CompactSpace.{u1} α _inst_1] [_inst_4 : TotallyDisconnectedSpace.{u1} α _inst_1] {x : α} {U : Set.{u1} α}, (IsOpen.{u1} α _inst_1 U) -> (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x U) -> (Exists.{succ u1} (Set.{u1} α) (fun (V : Set.{u1} α) => Exists.{0} (IsClopen.{u1} α _inst_1 V) (fun (hV : IsClopen.{u1} α _inst_1 V) => And (Membership.Mem.{u1, u1} α (Set.{u1} α) (Set.hasMem.{u1} α) x V) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.hasSubset.{u1} α) V U)))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : TopologicalSpace.{u1} α] [_inst_2 : T2Space.{u1} α _inst_1] [_inst_3 : CompactSpace.{u1} α _inst_1] [_inst_4 : TotallyDisconnectedSpace.{u1} α _inst_1] {x : α} {U : Set.{u1} α}, (IsOpen.{u1} α _inst_1 U) -> (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x U) -> (Exists.{succ u1} (Set.{u1} α) (fun (V : Set.{u1} α) => And (IsClopen.{u1} α _inst_1 V) (And (Membership.mem.{u1, u1} α (Set.{u1} α) (Set.instMembershipSet.{u1} α) x V) (HasSubset.Subset.{u1} (Set.{u1} α) (Set.instHasSubsetSet.{u1} α) V U)))) Case conversion may be inaccurate. Consider using '#align compact_exists_clopen_in_open compact_exists_clopen_in_openₓ'. -/ /-- Every member of an open set in a compact Hausdorff totally disconnected space is contained in a clopen set contained in the open set. -/ theorem compact_exists_clopen_in_open {x : α} {U : Set α} (is_open : IsOpen U) (memU : x ∈ U) : ∃ (V : Set α)(hV : IsClopen V), x ∈ V ∧ V ⊆ U := (IsTopologicalBasis.mem_nhds_iff isTopologicalBasis_clopen).1 (IsOpen.mem_nhds memU) #align compact_exists_clopen_in_open compact_exists_clopen_in_open end Profinite section LocallyCompact variable {H : Type _} [TopologicalSpace H] [LocallyCompactSpace H] [T2Space H] #print loc_compact_Haus_tot_disc_of_zero_dim /- /-- A locally compact Hausdorff totally disconnected space has a basis with clopen elements. -/ theorem loc_compact_Haus_tot_disc_of_zero_dim [TotallyDisconnectedSpace H] : IsTopologicalBasis { s : Set H | IsClopen s } := by refine' is_topological_basis_of_open_of_nhds (fun u hu => hu.1) _ rintro x U memU hU obtain ⟨s, comp, xs, sU⟩ := exists_compact_subset hU memU obtain ⟨t, h, ht, xt⟩ := mem_interior.1 xs let u : Set s := (coe : s → H) ⁻¹' interior s have u_open_in_s : IsOpen u := is_open_interior.preimage continuous_subtype_val let X : s := ⟨x, h xt⟩ have Xu : X ∈ u := xs haveI : CompactSpace s := isCompact_iff_compactSpace.1 comp obtain ⟨V : Set s, clopen_in_s, Vx, V_sub⟩ := compact_exists_clopen_in_open u_open_in_s Xu have V_clopen : IsClopen ((coe : s → H) '' V) := by refine' ⟨_, comp.is_closed.closed_embedding_subtype_coe.closed_iff_image_closed.1 clopen_in_s.2⟩ let v : Set u := (coe : u → s) ⁻¹' V have : (coe : u → H) = (coe : s → H) ∘ (coe : u → s) := rfl have f0 : Embedding (coe : u → H) := embedding_subtype_coe.comp embedding_subtype_val have f1 : OpenEmbedding (coe : u → H) := by refine' ⟨f0, _⟩ · have : Set.range (coe : u → H) = interior s := by rw [this, Set.range_comp, Subtype.range_coe, Subtype.image_preimage_coe] apply Set.inter_eq_self_of_subset_left interior_subset rw [this] apply isOpen_interior have f2 : IsOpen v := clopen_in_s.1.Preimage continuous_subtype_val have f3 : (coe : s → H) '' V = (coe : u → H) '' v := by rw [this, image_comp coe coe, Subtype.image_preimage_coe, inter_eq_self_of_subset_left V_sub] rw [f3] apply f1.is_open_map v f2 refine' ⟨coe '' V, V_clopen, by simp [Vx, h xt], _⟩ trans s · simp assumption #align loc_compact_Haus_tot_disc_of_zero_dim loc_compact_Haus_tot_disc_of_zero_dim -/ #print loc_compact_t2_tot_disc_iff_tot_sep /- /-- A locally compact Hausdorff space is totally disconnected if and only if it is totally separated. -/ theorem loc_compact_t2_tot_disc_iff_tot_sep : TotallyDisconnectedSpace H ↔ TotallySeparatedSpace H := by constructor · intro h exact totallySeparatedSpace_of_t1_of_basis_clopen loc_compact_Haus_tot_disc_of_zero_dim apply TotallySeparatedSpace.totallyDisconnectedSpace #align loc_compact_t2_tot_disc_iff_tot_sep loc_compact_t2_tot_disc_iff_tot_sep -/ end LocallyCompact #print ConnectedComponents.t2 /- /-- `connected_components α` is Hausdorff when `α` is Hausdorff and compact -/ instance ConnectedComponents.t2 [T2Space α] [CompactSpace α] : T2Space (ConnectedComponents α) := by -- Proof follows that of: https://stacks.math.columbia.edu/tag/0900 -- Fix 2 distinct connected components, with points a and b refine' ⟨connected_components.surjective_coe.forall₂.2 fun a b ne => _⟩ rw [ConnectedComponents.coe_ne_coe] at ne have h := connectedComponent_disjoint Ne -- write ↑b as the intersection of all clopen subsets containing it rw [connectedComponent_eq_interᵢ_clopen b, disjoint_iff_inter_eq_empty] at h -- Now we show that this can be reduced to some clopen containing `↑b` being disjoint to `↑a` obtain ⟨U, V, hU, ha, hb, rfl⟩ : ∃ (U : Set α)(V : Set (ConnectedComponents α)), IsClopen U ∧ connectedComponent a ∩ U = ∅ ∧ connectedComponent b ⊆ U ∧ coe ⁻¹' V = U := by cases' is_closed_connected_component.is_compact.elim_finite_subfamily_closed _ _ h with fin_a ha swap · exact fun Z => Z.2.1.2 -- This clopen and its complement will separate the connected components of `a` and `b` set U : Set α := ⋂ (i : { Z // IsClopen Z ∧ b ∈ Z }) (H : i ∈ fin_a), i have hU : IsClopen U := isClopen_binterᵢ_finset fun i j => i.2.1 exact ⟨U, coe '' U, hU, ha, subset_Inter₂ fun Z _ => Z.2.1.connectedComponent_subset Z.2.2, (connectedComponents_preimage_image U).symm ▸ hU.bUnion_connected_component_eq⟩ rw [connected_components.quotient_map_coe.is_clopen_preimage] at hU refine' ⟨Vᶜ, V, hU.compl.is_open, hU.is_open, _, hb mem_connectedComponent, disjoint_compl_left⟩ exact fun h => flip Set.Nonempty.ne_empty ha ⟨a, mem_connectedComponent, h⟩ #align connected_components.t2 ConnectedComponents.t2 -/
A set $S$ is simply connected if and only if it is path connected and every path in $S$ with the same start and end point is homotopic to a constant path.
\documentclass [12pt]{article} \usepackage {amsmath} \usepackage {amsthm} \usepackage {amssymb} \usepackage {graphicx} \usepackage {float} \usepackage {multirow} \usepackage {xcolor} \usepackage {algorithmic} \usepackage [ruled,vlined,commentsnumbered,titlenotnumbered]{algorithm2e} \usepackage {array} \usepackage {booktabs} \usepackage {url} \usepackage {parskip} \usepackage [margin=1in]{geometry} \usepackage [T1]{fontenc} \usepackage {cmbright} \usepackage [many]{tcolorbox} \usepackage [colorlinks = true, linkcolor = blue, urlcolor = blue, citecolor = blue, anchorcolor = blue]{hyperref} \usepackage {enumitem} \usepackage {xparse} \usepackage {verbatim} \usepackage{listings} \usepackage{xcolor} \lstset { % language=C++, backgroundcolor=\color{black!5}, % set backgroundcolor basicstyle=\footnotesize,% basic font setting } \newtheorem{theorem}{Theorem} \newtheorem{remark}{Remark} \newtheorem{lemma}[theorem]{Lemma} \theoremstyle{definition} \newtheorem{definition}{Definition}[section] \newtheorem{claim}{Claim} \DeclareTColorBox {Solution}{}{breakable, title={Solution}} \DeclareTColorBox {Solution*}{}{breakable, title={Solution (provided)}} \DeclareTColorBox {Instruction}{}{boxrule=0pt, boxsep=0pt, left=0.5em, right=0.5em, top=0.5em, bottom=0.5em, arc=0pt, toprule=1pt, bottomrule=1pt} \DeclareDocumentCommand {\Expecting }{+m}{\textbf {[We are expecting:} #1\textbf {]}} \DeclareDocumentCommand {\Points }{m}{\textbf {(#1 pt.)}} \begin {document} \vspace {1em} \begin {Instruction} Adapted From Virginia Williams' lecture notes. \end {Instruction} {\LARGE \textbf {COMP 285 (NC A\&T, Spr `22)}\hfill \textbf {Lecture 24} } \begin{centering} \section*{Dynamic Programming II: Bellman-Ford} \end{centering} \section{More on the Bellman-Ford Algorithm} We didn't quite make it to the Bellman-Ford algorithm in the last lecture, so we'll re-hash some of that again today. In the notes for the previous lecture, we introduced Bellman-Ford in the context of Dijkstra's algorithm. We'll see it in this lecture in a different way, so as to naturally introduce \textit{dynamic programming}. The Bellman-Ford algorithm is a dynamic programming algorithm, and dynamic programming is a basic paradigm in algorithm design used to solve problems by relying on intermediate solutions to smaller subproblems. The main step for solving a dynamic programming problem is to analyze the problem's \textbf{optimal substructure} and \textbf{overlapping subproblems}. The Bellman-Ford algorithm is pretty simple to state: \begin{algorithm} \caption{Bellman-Ford Algorithm(G,s)} \label{alg:bellman-ford} \begin{algorithmic} \STATE $d^{(0)}[v] \gets \infty, \forall v \in V$ \STATE $d^{(0)}[s] \gets 0$ \STATE $d^{(k)}[v] = \texttt{None}, \forall v \in V, \forall k > 0$ \FOR{$i$ from $1 \to n - 1$} \STATE $d^{(k)}[v] \gets d^{(k-1)}[v]$ for all $v$ \FOR{$(u,v) \in E$} \STATE $d^{(k)}[v] \gets \min\{d^{(k)}[v], d^{(k-1)}[u] + w(u,v) \}$ \ENDFOR \STATE \texttt{// Here we release the memory for } $d^{(k-1)}$ \texttt{, we'll never need it again} \ENDFOR \RETURN $d^{(n-1)}[v], \forall v \in V$ \end{algorithmic} \end{algorithm} What's going on here? The value $d^{(k)}[v]$ is the cost of the shortest path from $s$ to $v$ with at most $k$ edges in it. Once we realize this, a proof by induction falls right out, with the inductive hypothesis that ``$d^{(k)}[v]$ is the cost of the shortest path from $s$ to $v$ with at most $k$ edges in it.'' \textbf{Runtime and Storage} The runtime of the Bellman-Ford algorithm is $O(mn)$; for $n$ iterations, we loop through all the edges. This is slower than Dijkstra's algorithm. However, it is simpler to implement, and further as we saw in Lecture Notes 23, it can handle negative edge weights. For storage, in the pseudocode above, we keep n different arrays $d^{(k)}$ of length $n$. This isn't necessary: we only need to store two of them at a time. This is noted in the comment in the pseudocode. \subsection{What's really going on here?} The thing that makes that Bellman-Ford algorithm work is that that the shortest paths of length at most $k$ can be computed by leveraging the shortest paths of length at most $k - 1$. More specifically, we relied on the following recurrence relation between the intermediate solutions: $$ d^{(k)} [v ] = \min_{u \in V}\{ d^{(k-1)}[u] + w(u, v ) \} $$ where $d^{k}[v ]$ is the length of the shortest path from source $s$ to node $v$ using at most $k$ edges, and $w(u, v )$ is the weight of edge $(u, v )$. (Above, we are assuming $w(v, v ) = 0$). This idea of using the intermediate solutions is similar to the divide-and-conquer paradigm. However, a divide-and-conquer algorithm recursively computes intermediate solutions once for each subproblem, but a dynamic programming algorithm solves the subproblems exactly once and uses these results multiple times. \section{Dynamic Programming} The idea of dynamic programming is to have a table of solutions of subproblems and fill it out in a particular order (e.g. left to right and top to bottom) so that the contents of any particular table cell only depends on the contents of cells before it. For example, in the Bellman-Ford algorithm, we filled out $d^{(k-1)}$ before we filled out $d^{(k)}$ ; and in order to fill out $d^{(k)}$ , we just had to look back at $d^{(k-1)}$, rather than compute anything new. In this lecture, we will discuss dynamic programming more. \subsection{Dynamic Programming Algorithm Recipe} Here, we give a general recipe for solving problems (usually optimization problems) by dynamic programming. Dynamic programming is a good candidate paradigm to use for problems with the following properties: \begin{itemize} \item Optimal substructure gives a recursive formulation; and \item Overlapping subproblems give a small table, that is, we can store the precomputed answers such that it doesn't actually take too long when evaluating a recursive function multiple times. \end{itemize} What exactly do these things mean? We'll discuss them a bit more below, with the BellmanFord algorithm in mind as a reference. \subsubsection{Optimal Substructure} By this property, we mean that the optimal solution to the problem is composed of optimal solutions to smaller independent subproblems. For example, the shortest path from $s$ to $t$ consists of a shortest path $P$ from $s$ to $k$ (for node $k$ on $P$) and a shortest path from $k$ to $t$. This allows us to write down an expression for the distance between $s$ and $t$ with respect to the lengths of sub-paths: $$ d(s, t) = d(s, k) + d(k, t), \text{for all } k \text{ on a shortest } s - t \text{ path} $$ We used this in the Bellman-Ford algorithm when we wrote $$ d^{(k)} [u] = \min_{v\in V} \{d^{(k-1)}[v ] + w(u, v )\} $$ \subsubsection{Overlapping subproblems} The goal of dynamic programming is to construct a table of entries, where early entries in the table can be used to compute later entries. Ideally, the optimal solutions of subproblems can be reused multiple times to compute the optimal solutions of larger problems. For our shortest paths example, $d(s, k)$ can used to compute $d(s, t)$ for any $t$ where the shortest $s - t$ path contains $k$. To save time, we can compute $d(s, k)$ once and just look it up each time, instead of recomputing it. More concretely in the Bellman-Ford example, suppose that $(v, u)$ and $(v, u' )$ are both in $E$. When we go to compute $d^{(k)}[u]$, we'll need $d^{(k-1)}[v ]$. Then when we go to compute $d^{(k)}[u ' ]$, we'll need $d^{k-1}[v ]$ again. If we just set this up as a divide-and-conquer algorithm, this would be extremely wasteful, and we'd be re-doing lots of work. By storing this value in a table and looking it up when we need it, we are taking advantage of the fact that these subproblems overlap. \subsubsection{Implementations} The above two properties lead to two different ways to implement dynamic programming algorithms. In each, we will store a table $T$ with optimal solutions to subproblems; the two variants differ in how we decide to fill up the table: \begin{enumerate} \item Bottom-up: Here, we will fill in the table starting with the smallest subproblems. Then, assuming that we have computed the optimal solution to small subproblems, we can compute the answers for larger subproblems using our recursive optimal substructure. \item Top-down: In this approach, we will compute the optimal solution to the entire problem recursively. At each recursive call, we will end up looking up the answer or filling in the table if the entry has not been computed yet. \end{enumerate} In fact, these two methods are completely equivalent. Any dynamic programming algorithm can be formulated as an iterative table-filling algorithm or a recursive algorithm with look-ups. \section{Why is it called dynamic programming?} The name doesn't immediately make a lot of sense. ``Dynamic programming'' sounds like the type of coding that action heroes do in late-90's hacker movies. However, ``progamming'' here refers to a program, like a plan (for example, the path you are trying to optimize), not to programming a computer. ``Dynamic'' refers to the fact that we update the table over time: this is a dynamic process. But the fact that it makes you (or at least me) think about action movies isn't an accident. As Richard Bellman, who coined the term, writes in his autobiography: \begin{quote} An interesting question is, ``Where did the name, dynamic programming, come from?'' The 1950s were not good years for mathematical research. We had a very interesting gentleman in Washington named Wilson. He was Secretary of Defense, and he actually had a pathological fear and hatred of the word, research. Im not using the term lightly; Im using it precisely. His face would suffuse, he would turn red, and he would get violent if people used the term, research, in his presence. You can imagine how he felt, then, about the term, mathematical. The RAND Corporation was employed by the Air Force, and the Air Force had Wilson as its boss, essentially. Hence, I felt I had to do something to shield Wilson and the Air Force from the fact that I was really doing mathematics inside the RAND Corporation. What title, what name, could I choose? In the first place, I was interested in planning, in decision-making, in thinking. But planning, is not a good word for various reasons. I decided therefore to use the word, ``programming``. I wanted to get across the idea that this was dynamic, this was multistage, this was time-varying- I thought, let’s kill two birds with one stone. Let’s take a word which has an absolutely precise meaning, namely dynamic, in the classical physical sense. It also has a very interesting property as an adjective, and that is it’s impossible to use the word, dynamic, in the pejorative sense. Try thinking of some combination which will possibly give it a pejorative meaning. It’s impossible. Thus, I thought dynamic programming was a good name. It was something not even a Congressman could object to. So I used it as an umbrella for my activities. \end{quote} \end{document}
# Copyright (C) 2021-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # import os.path as osp import tempfile from os import remove import mmcv import numpy as np import pytest from ote_sdk.entities.annotation import ( Annotation, AnnotationSceneEntity, AnnotationSceneKind, ) from ote_sdk.entities.dataset_item import DatasetItemEntity from ote_sdk.entities.datasets import DatasetEntity from ote_sdk.entities.image import Image from ote_sdk.entities.label import Domain, LabelEntity from ote_sdk.entities.scored_label import ScoredLabel from ote_sdk.entities.shapes.rectangle import Rectangle from ote_sdk.test_suite.e2e_test_system import e2e_pytest_unit from ote_sdk.tests.parameters_validation.validation_helper import ( check_value_error_exception_raised, ) from segmentation_tasks.extension.datasets.mmdataset import ( abs_path_if_valid, OTEDataset, get_annotation_mmseg_format, get_classes_from_annotation, create_annotation_from_hard_seg_map, load_labels_from_annotation, add_labels, check_labels, get_extended_label_names, load_dataset_items, ) def label_entity(): return LabelEntity(name="test label", domain=Domain.SEGMENTATION) def dataset_item(): image = Image(data=np.random.randint(low=0, high=255, size=(10, 16, 3))) annotation = Annotation( shape=Rectangle.generate_full_box(), labels=[ScoredLabel(label_entity())] ) annotation_scene = AnnotationSceneEntity( annotations=[annotation], kind=AnnotationSceneKind.ANNOTATION ) return DatasetItemEntity(media=image, annotation_scene=annotation_scene) def _create_dummy_coco_json(json_name): image = { "id": 0, "width": 640, "height": 640, "file_name": "fake_name.jpg", } annotation_1 = { "id": 1, "image_id": 0, "category_id": 0, "area": 400, "bbox": [50, 60, 20, 20], "iscrowd": 0, } annotation_2 = { "id": 2, "image_id": 0, "category_id": 0, "area": 900, "bbox": [100, 120, 30, 30], "iscrowd": 0, } categories = [ { "id": 0, "name": "car", "supercategory": "car", } ] fake_json = { "images": [image], "annotations": [annotation_1, annotation_2], "categories": categories, } mmcv.dump(fake_json, json_name) class TestMMDatasetFunctionsInputParamsValidation: @e2e_pytest_unit def test_get_annotation_mmseg_format_input_params_validation(self): """ <b>Description:</b> Check "get_annotation_mmseg_format" function input parameters validation <b>Input data:</b> "get_annotation_mmseg_format" function unexpected-type input parameters <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "get_annotation_mmseg_format" function """ label = label_entity() correct_values_dict = { "dataset_item": dataset_item(), "labels": [label], } unexpected_int = 1 unexpected_values = [ # Unexpected integer is specified as "dataset_item" parameter ("dataset_item", unexpected_int), # Unexpected integer is specified as "labels" parameter ("labels", unexpected_int), # Unexpected integer is specified as nested label ("labels", [label, unexpected_int]), ] check_value_error_exception_raised( correct_parameters=correct_values_dict, unexpected_values=unexpected_values, class_or_function=get_annotation_mmseg_format, ) @e2e_pytest_unit def test_get_classes_from_annotation_input_params_validation(self): """ <b>Description:</b> Check "get_classes_from_annotation" function input parameters validation <b>Input data:</b> "annot_path" unexpected object <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "get_classes_from_annotation" function """ for unexpected_value in [ # non string object is specified as "annot_path" parameter 1, # Empty string is specified as "annot_path" parameter "", # Path to file with unexpected extension is specified as "annot_path" parameter "./unexpected_extension.yaml", # Path to non-existing file is specified as "annot_path" parameter "./non_existing.json", # Path with null character is specified as "annot_path" parameter "./null\0char.json", # Path with non-printable character is specified as "annot_path" parameter "./\non_printable_char.json", ]: with pytest.raises(ValueError): get_classes_from_annotation(annot_path=unexpected_value) @e2e_pytest_unit def test_abs_path_if_valid_input_params_validation(self): """ <b>Description:</b> Check "abs_path_if_valid" function input parameters validation <b>Input data:</b> "value" unexpected object <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "abs_path_if_valid" function """ for unexpected_value in [ # Unexpected integer is specified as "value" parameter 1, # Empty string is specified as "value" parameter "", # Path with null character is specified as "value" parameter "./\0null_char", # Path with non-printable character is specified as "value" parameter "./\non_printable_char", ]: with pytest.raises(ValueError): abs_path_if_valid(value=unexpected_value) @e2e_pytest_unit def test_create_annotation_from_hard_seg_map_input_params_validation(self): """ <b>Description:</b> Check "create_annotation_from_hard_seg_map" function input parameters validation <b>Input data:</b> "create_annotation_from_hard_seg_map" function unexpected-type input parameters <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "create_annotation_from_hard_seg_map" function """ label = label_entity() correct_values_dict = { "hard_seg_map": np.random.rand(2, 2), "labels": [label], } unexpected_int = 1 unexpected_values = [ # Unexpected integer is specified as "dataset_item" parameter ("hard_seg_map", unexpected_int), # Unexpected integer is specified as "labels" parameter ("labels", unexpected_int), # Unexpected integer is specified as nested label ("labels", [label, unexpected_int]), ] check_value_error_exception_raised( correct_parameters=correct_values_dict, unexpected_values=unexpected_values, class_or_function=create_annotation_from_hard_seg_map, ) @e2e_pytest_unit def test_load_labels_from_annotation_input_params_validation(self): """ <b>Description:</b> Check "load_labels_from_annotation" function input parameters validation <b>Input data:</b> "ann_dir" unexpected object <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "load_labels_from_annotation" function """ for unexpected_value in [ # Unexpected integer is specified as "ann_dir" parameter 1, # Empty string is specified as "ann_dir" parameter "", # Path with null character is specified as "ann_dir" parameter "./\0null_char", # Path with non-printable character is specified as "ann_dir" parameter "./\non_printable_char", ]: with pytest.raises(ValueError): load_labels_from_annotation(ann_dir=unexpected_value) @e2e_pytest_unit def test_add_labels_input_params_validation(self): """ <b>Description:</b> Check "add_labels" function input parameters validation <b>Input data:</b> "add_labels" function unexpected-type input parameters <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "add_labels" function """ label = label_entity() correct_values_dict = { "cur_labels": [label], "new_labels": [("label_name1", "label_id1")], } unexpected_int = 1 unexpected_values = [ # Unexpected integer is specified as "cur_labels" parameter ("cur_labels", unexpected_int), # Unexpected integer is specified as nested label ("cur_labels", [label, unexpected_int]), # Unexpected integer is specified as "new_labels" parameter ("new_labels", unexpected_int), # Unexpected integer is specified as nested new_label ("new_labels", [("label_name1", "label_id1"), unexpected_int]), ] check_value_error_exception_raised( correct_parameters=correct_values_dict, unexpected_values=unexpected_values, class_or_function=add_labels, ) @e2e_pytest_unit def test_check_labels_input_params_validation(self): """ <b>Description:</b> Check "check_labels" function input parameters validation <b>Input data:</b> "check_labels" function unexpected-type input parameters <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "check_labels" function """ label = label_entity() correct_values_dict = { "cur_labels": [label], "new_labels": [("label_name1", "label_id1")], } unexpected_int = 1 unexpected_values = [ # Unexpected integer is specified as "cur_labels" parameter ("cur_labels", unexpected_int), # Unexpected integer is specified as nested label ("cur_labels", [label, unexpected_int]), # Unexpected integer is specified as "new_labels" parameter ("new_labels", unexpected_int), # Unexpected integer is specified as nested new_label ("new_labels", [("label_name1", "label_id1"), unexpected_int]), ] check_value_error_exception_raised( correct_parameters=correct_values_dict, unexpected_values=unexpected_values, class_or_function=check_labels, ) @e2e_pytest_unit def test_get_extended_label_names_input_params_validation(self): """ <b>Description:</b> Check "get_extended_label_names" function input parameters validation <b>Input data:</b> "labels" unexpected object <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "get_extended_label_names" function """ label = label_entity() unexpected_int = 1 for unexpected_value in [ # Unexpected integer is specified as "labels" parameter unexpected_int, # Empty string is specified as nested label [label, unexpected_int], ]: with pytest.raises(ValueError): get_extended_label_names(labels=unexpected_value) @e2e_pytest_unit def test_load_dataset_items_params_validation(self): """ <b>Description:</b> Check "load_dataset_items" function input parameters validation <b>Input data:</b> "load_dataset_items" function unexpected-type input parameters <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "load_dataset_items" function """ tmp_dir = tempfile.TemporaryDirectory() fake_json_file = osp.join(tmp_dir.name, "fake_data.json") _create_dummy_coco_json(fake_json_file) label = LabelEntity(name="test label", domain=Domain.DETECTION) correct_values_dict = { "ann_file_path": fake_json_file, "data_root_dir": tmp_dir.name, } unexpected_int = 1 unexpected_values = [ # Unexpected integer is specified as "ann_file_path" parameter ("ann_file_path", unexpected_int), # Empty string is specified as "ann_file_path" parameter ("ann_file_path", ""), # Path with null character is specified as "ann_file_path" parameter ("ann_file_path", osp.join(tmp_dir.name, "\0fake_data.json")), # Path with non-printable character is specified as "ann_file_path" parameter ("ann_file_path", osp.join(tmp_dir.name, "\nfake_data.json")), # Unexpected integer is specified as "data_root_dir" parameter ("data_root_dir", unexpected_int), # Empty string is specified as "data_root_dir" parameter ("data_root_dir", ""), # Path with null character is specified as "data_root_dir" parameter ("data_root_dir", "./\0null_char"), # Path with non-printable character is specified as "data_root_dir" parameter ("data_root_dir", "./\non_printable_char"), # Unexpected integer is specified as "subset" parameter ("subset", unexpected_int), # Unexpected integer is specified as "labels_list" parameter ("labels_list", unexpected_int), # Unexpected integer is specified as nested label ("labels_list", [label, unexpected_int]), ] check_value_error_exception_raised( correct_parameters=correct_values_dict, unexpected_values=unexpected_values, class_or_function=load_dataset_items, ) remove(fake_json_file) class TestOTEDatasetInputParamsValidation: @staticmethod def dataset(): return OTEDataset( ote_dataset=DatasetEntity(), pipeline=[{"type": "LoadImageFromFile", "to_float32": True}], classes=["class_1", "class_2"], ) @e2e_pytest_unit def test_ote_dataset_init_params_validation(self): """ <b>Description:</b> Check OTEDataset object initialization parameters validation <b>Input data:</b> OTEDataset object initialization parameters with unexpected type <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as OTEDataset object initialization parameter """ correct_values_dict = { "ote_dataset": DatasetEntity(), "pipeline": [{"type": "LoadImageFromFile", "to_float32": True}], } unexpected_str = "unexpected string" unexpected_int = 1 unexpected_values = [ # Unexpected string is specified as "ote_dataset" parameter ("ote_dataset", unexpected_str), # Unexpected integer is specified as "pipeline" parameter ("pipeline", unexpected_int), # Unexpected string is specified as nested pipeline ("pipeline", [{"config": 1}, unexpected_str]), # Unexpected string is specified as "classes" parameter ("classes", unexpected_str), # Unexpected string is specified as nested class ("classes", ["class_1", unexpected_int]), # Unexpected string is specified as "test_mode" parameter ("test_mode", unexpected_str), ] check_value_error_exception_raised( correct_parameters=correct_values_dict, unexpected_values=unexpected_values, class_or_function=OTEDataset, ) @e2e_pytest_unit def test_ote_dataset_filter_labels_params_validation(self): """ <b>Description:</b> Check OTEDataset object "filter_labels" method input parameters validation <b>Input data:</b> OTEDataset object, "filter_labels" method unexpected parameters <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "filter_labels" method """ label = label_entity() dataset = self.dataset() correct_values_dict = { "all_labels": [label], "label_names": ["label_1", "label_2"], } unexpected_int = 1 unexpected_values = [ # Unexpected integer is specified as "all_labels" parameter ("all_labels", unexpected_int), # Unexpected integer is specified as nested label ("all_labels", [label, unexpected_int]), # Unexpected integer is specified as "label_names" parameter ("label_names", unexpected_int), # Unexpected integer is specified as nested name ("label_names", ["label_1", unexpected_int]), ] check_value_error_exception_raised( correct_parameters=correct_values_dict, unexpected_values=unexpected_values, class_or_function=dataset.filter_labels, ) @e2e_pytest_unit def test_ote_dataset_pre_pipeline_params_validation(self): """ <b>Description:</b> Check OTEDataset object "pre_pipeline" method input parameters validation <b>Input data:</b> OTEDataset object, "results" unexpected type object <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "pre_pipeline" method """ dataset = self.dataset() unexpected_int = 1 for unexpected_value in [ # Unexpected integer is specified as "results" parameter unexpected_int, # Unexpected integer is specified as "results" dictionary key {"result_1": "some results", unexpected_int: "unexpected results"}, ]: with pytest.raises(ValueError): dataset.pre_pipeline(results=unexpected_value) @e2e_pytest_unit def test_ote_dataset_prepare_train_img_params_validation(self): """ <b>Description:</b> Check OTEDataset object "prepare_train_img" method input parameters validation <b>Input data:</b> OTEDataset object, "idx" non-integer type parameter <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "prepare_train_img" method """ dataset = self.dataset() with pytest.raises(ValueError): dataset.prepare_train_img(idx="unexpected string") # type: ignore @e2e_pytest_unit def test_ote_dataset_prepare_test_img_params_validation(self): """ <b>Description:</b> Check OTEDataset object "prepare_test_img" method input parameters validation <b>Input data:</b> OTEDataset object, "idx" non-integer type parameter <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "prepare_test_img" method """ dataset = self.dataset() with pytest.raises(ValueError): dataset.prepare_test_img(idx="unexpected string") # type: ignore @e2e_pytest_unit def test_ote_dataset_get_ann_info_params_validation(self): """ <b>Description:</b> Check OTEDataset object "get_ann_info" method input parameters validation <b>Input data:</b> OTEDataset object, "idx" non-integer type parameter <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "get_ann_info" method """ dataset = self.dataset() with pytest.raises(ValueError): dataset.get_ann_info(idx="unexpected string") # type: ignore @e2e_pytest_unit def test_ote_dataset_get_gt_seg_maps_params_validation(self): """ <b>Description:</b> Check OTEDataset object "get_gt_seg_maps" method input parameters validation <b>Input data:</b> OTEDataset object, "efficient_test" non-bool type parameter <b>Expected results:</b> Test passes if ValueError exception is raised when unexpected type object is specified as input parameter for "get_gt_seg_maps" method """ dataset = self.dataset() with pytest.raises(ValueError): dataset.get_gt_seg_maps(efficient_test="unexpected string") # type: ignore
```python # for interest, here is how I would make this a software project # training classifier using hugging face api (high, high level nlp) # then classifying script text content # dataset and csv are fomatted and ready to go for api (as in this sofware works) # will need a valid hugging face api to work- (will fail but illustrates working code) !python3 main.py --hugging_face --login --api_key sldkfjdummykey ``` here sldkfjdummykey > ERROR ❌ Failed to authenticate. Check the passed token is valid! > ERROR ❌ Oops! Something failed in AutoNLP backend.. > ERROR Error code: 401; Details: '{"error":"Unauthorized"}' Model trianing using autonlp (hugging face api) #### Here is the software verison with and args parser that I wrote as an example of using hugging face api to train a binary text classifier and an illustration of how I would approach this problem as a piece of end to end software that runs in terminal ```python # to show you what the args parser -help would return of this sofware !python3 main.py --help ``` usage: main.py [-h] [--input csv INPUT CSV] [--project PROJECT] [--split SPLIT] [--col_mapping COL_MAPPING] [--files FILES] [--api_key API_KEY] [--resize RESIZE] [--name NAME] [--language LANGUAGE] [--task TASK] [--max_models MAX_MODELS] [--create_project] [--hugging_face] [--send] [--login] [--make] [--train] Training Calssifier optional arguments: -h, --help show this help message and exit --input csv INPUT CSV relative loacation of input csv for training --project PROJECT poject name --split SPLIT dataset split --col_mapping COL_MAPPING text:text, label:target --files FILES formated csv only 2 colls one for text one for target --api_key API_KEY api key from hugging_face account --resize RESIZE Resizes images by percentage as scalar --name NAME project name hugging face --language LANGUAGE lang in eg [en,sp,fr] --task TASK Resizes images by percentage as scalar --max_models MAX_MODELS nuber of trainable models --create_project create_new hf project --hugging_face uses hugging face api to train model --send if entered will try to sen .csv --login if entered will try to sen .csv --make create_new hf project --train create_new hf project ```python #files import gdown import os import zipfile #data import pandas as pd import numpy as np import matplotlib.pyplot as plt # utils from pathlib import Path import time from tqdm import tqdm # web import urllib.request import requests from bs4 import BeautifulSoup # evaluation metrics from scipy import stats from scipy.spatial import distance from sklearn.metrics import matthews_corrcoef from sklearn.metrics import confusion_matrix ``` ### Start time ```python #starting time time.strftime("%H:%M:%S", time.localtime()) ``` '20:46:46' ```python !ls ``` README.md main.py scripts_html bechdel.ipynb pre_scraped scripts_html.zip classifier.py requirments.txt super_woman.png ## **preamble** **bechdel criteria:** - 1. [x] (of film or literature) Has to have at least two women (discrete int) or $\in \mathbb{Z}$ - 2. [x] Talk to each other in (continuous time) or $\in \mathbb{R}$ - 3. [x] Talk about somthing other than a man (not.self) (binary) or $\in \mathbb{B}$ > here the problem is framed as one of comparing those that meet first condition with two different consecutive female first names in script segments and verifieable ground truth - that is the first condition a prediction of passing overall -- this is to gauge whether more detailed anaylis might be needed such as training an NLP classifier. ```python def get_scripts(did=None): '''this funciton gets scripts using gdown from google drive zip unzips and preservs file name''' url = 'https://drive.google.com/drive/folders/1PWoip6Hkl-3WG9Syyd_IxOPeC-FsshDP?usp=sharing' os.makedirs(did,exist_ok=True) gdown.download_folder(url,output=None,quiet=False) fid = Path('scripts_html.zip') with zipfile.ZipFile(fid, 'r') as zip_fid: zip_fid.extractall(fid.parent) # path to scripts did = Path('pre_scraped/') os.makedirs(did,exist_ok=True) get_scripts(did) did = Path('scripts_html/') # using path object as itterator to ge file in directory fids = [fid for fid in did.iterdir()] scripts = { } for fid in tqdm(fids): with open(fid,'r') as handle: scripts[fid.name.strip(fid.suffix)]=BeautifulSoup(handle, 'html.parser') ``` Retrieving folder list Processing file 1sKXHb17Ah6Bl6nVMCUE--SnCGV-rvlzk scripts_html.zip Building directory structure completed Retrieving folder list completed Building directory structure Downloading... From: https://drive.google.com/uc?id=1sKXHb17Ah6Bl6nVMCUE--SnCGV-rvlzk To: /Users/fridades/Projects/bechdel/scripts_html.zip 100%|██████████████████████████████████████| 16.1M/16.1M [00:01<00:00, 8.99MB/s] Download completed 100%|█████████████████████████████████████████| 282/282 [00:16<00:00, 17.12it/s] ```python def clean(script): script = [element for element in script.find_all('b')] script = [element.get_text() for element in script] script = [" ".join(element.split()) for element in script if " ".join(element.split()) !=''] return [element.upper() for element in script] # make dict for ease of manipulation later and if need to save as .json names_dict = {script:clean(scripts[script]) for script in scripts} names_dict = {key.strip(', The').upper():names_dict[key] for key in names_dict} #clean names and make upper ``` ```python #get list of first names (man and woman from academic source) women_names ='https://www.cs.cmu.edu/Groups/AI/areas/nlp/corpora/names/female.txt' man_names = 'https://www.cs.cmu.edu/Groups/AI/areas/nlp/corpora/names/male.txt' gdown.download(women_names);gdown.download(man_names) ``` Downloading... From: https://www.cs.cmu.edu/Groups/AI/areas/nlp/corpora/names/female.txt To: /Users/fridades/Projects/bechdel/female.txt 35.8kB [00:00, 58.1MB/s] Downloading... From: https://www.cs.cmu.edu/Groups/AI/areas/nlp/corpora/names/male.txt To: /Users/fridades/Projects/bechdel/male.txt 20.5kB [00:00, 33.6MB/s] 'male.txt' ```python def read_text(fid): '''gets names from txt removing preamble (prints) prints first name converted to upper''' with open(fid,'r') as hndl: txt = hndl.read().splitlines() preamble = txt[:5] #convert all names to upper txt = [name.upper() for name in txt[5:]] print(preamble,'\n', txt[1]) return txt # get lists fem_first, man_first = read_text('female.txt'), read_text('male.txt') ``` ['# List of common female names.', '# Copyright (c) January 1991 by Mark Kantrowitz.', '# 4987 names', '# Thanks to Bill.Ross for about 1000 additional names.', '# Version 1.3 (29-MAR-94)'] ABAGAEL ['# List of common male names.', '# Copyright (c) January 1991 by Mark Kantrowitz.', '# 2940 names', '# Thanks to Bill Ross for about 1000 additional names.', '# Version 1.3 (29-MAR-94)'] AAMIR ```python # might take a minute to parse and compute (but less time than training an nlp model :-)) def bechdel_one(script_names,fems): '''a generator function that yields whther or not condtion 1 is passed where 2 female names not the same in seqence are a potential proxy for passing condition 1 of Bechdel test''' for idx,name in enumerate(script_names[3:]): if idx+1!=len(script_names): dialoge = script_names[idx:idx+2] #not the same person not_solo = dialoge[0]!=dialoge[1] # first person is in womens names a_is_girl = dialoge[0] in fems # secong perons is in womens names b_is_girl = dialoge[1] in fems yield all([not_solo,a_is_girl,b_is_girl]) passes_bechdel_one = {title:any(list(bechdel_one(names_dict[title],fem_first))) for title in names_dict} ``` ```python # passed condition one according to boolean process passes_bechdel_one['10 THINGS I HATE ABOUT YOU'] ``` True ```python passes_one_vector = np.array([passes_bechdel_one[key] for key in passes_bechdel_one]) #convert bools to ints passes_one_vector = passes_one_vector.astype(int) len(passes_one_vector) plt.bar(['does not pass','passes'],np.bincount(passes_one_vector)) np.count_nonzero(passes_one_vector) ``` ```python time.strftime("%H:%M:%S", time.localtime()) ``` '20:48:18' #### list of film titles that pass all three conditions from bechdeltest.com (here taken as **ground truth**) ```python bechdel_films = requests.get('https://bechdeltest.com/?list=all').text ``` ```python bechdel_soup = BeautifulSoup(bechdel_films, 'html.parser') ``` ```python criteria = "[There are two or more women in this movie and they talk to each other about something other than a man]" films = bechdel_soup.find_all('a') titles_that_pass = [films[idx-2].text for idx,film in enumerate(films) if criteria in str(film.contents)] titles_that_pass = [title.upper().strip('THE ') for title in titles_that_pass if title !=''] to_check = [title.strip(', The').upper() for title in list(names_dict.keys())] len(to_check) ``` 281 ```python # 1*n d array (aka a vector) of those that pass all 1=pass 0=fail pass_all_vector = np.array([i in titles_that_pass for i in to_check]).astype(int) ``` ```python plt.bar(['does not pass','passes'],np.bincount(pass_all_vector)) ``` ```python np.count_nonzero(pass_all_vector) ``` 86 #### PLCC vanilla correlation coeff (can be used for binary and give phi coefficinet) to compare method used to derive condition one with ground truth (human rated unambiguous passes of Bechdel test $$\begin{equation} r = \frac{{}\sum_{i=1}^{n} (x_i - \overline{x})(y_i -\overline{y})}{\sqrt{\sum_{i=1}^{n} (x_i -\overline{x})^2(y_i - \overline{y})^2}} \label{PLCC} \end{equation}$$ ```python pearson_r, p_val = stats.pearsonr(passes_one_vector,pass_all_vector) f'R value = {pearson_r:.3f} P value {p_val:.3f}' ``` 'R value = -0.080 P value 0.183' #### Shows that not very significant prediction and that either the method of using sequential female names is not very good or that it is a poor proxy for passing the Bechdel test #### hack proof using mathews (specifically binary) PLCC vanilla correlation coeff (can be used for binary as and give phi coefficinet) $$\begin{equation} MMC = \frac{TP\times TN - FP \times FN}{\sqrt{(TP+FP)(TP+FN)(TN+FP)(TN+FN)}} \end{equation}$$ ```python f' Mathews coef = {matthews_corrcoef(pass_all_vector,passes_one_vector):.3f}' ``` ' Mathews coef = -0.080' #### however perhaps more appropriate as shows 'set similarity' is Jacard's Distance (a bit like SSIM but for binary vectors) $$\begin{equation} d_j(A,B) = 1-J(A,B) = \frac{| A \cup B| - | A \cap B|}{| A \cup B|} \end{equation}$$ ```python f' Jackards Dist = {distance.jaccard(pass_all_vector,passes_one_vector):.3f}' ``` ' Jackards Dist = 0.761' #### shows significant distance however about 1/3 of sample space is same > therefore while poor correlation (between those that pass condition 1 of bechdel and are in ground truth) ther is some promise that those that meet two fmale charachter names being used in seqece maight be good a prediction condition one but that the textuall content accounts for faliure of the Bechdel test after this (indicates that textuall analysis is needed)!! #### Show if condition of one by names method is a an accurate predictory of all three. $$\begin{equation} Accuracy = \frac{TP+TN}{TP+TN+FP+FN} \end{equation}$$ ```python tn, fp, fn, tp = confusion_matrix(pass_all_vector,passes_one_vector).ravel() f'accuracy = {sum([tp,tn])/sum([tn,fp,fn,tp]):.3f}' ``` 'accuracy = 0.399' ```python main_films = requests.get('https://imsdb.com/all-scripts.html').text main_films = BeautifulSoup(main_films, 'html.parser') ``` ```python script_urls = [ ] for i in main_films.find_all('a'): if '/Movie Scripts/' in i['href']: if i.text.strip(' ,The').upper() not in passes_bechdel_one: url = 'https://imsdb.com'+str(i['href']) script_urls.append(url) ``` ```python script_urls[0].split('/')[-1].strip('.html').strip(', The').upper() ``` 'RESERVOIR DOGS SCRIP' ```python 'https://imsdb.com/Movie%20Scripts/Four%20Rooms%20Script.html' def get_script(parent_page): '''gets script form parent html (script page rather thatn script itself)''' one_film = requests.get(parent_page).text one_film = BeautifulSoup(one_film, 'html.parser') for i in one_film.find_all('a'): if 'Read' in i.text: # get one script one_script = requests.get( 'https://imsdb.com/Movie Scripts'+i['href']).text return BeautifulSoup(one_script, 'html.parser') ``` #### probably a bit exaggerated on the evasion of web crawl blocking but illustrates some techniques for this ```python script_urls = np.array(script_urls) # random shuffle urls array so (evasion of blocking) np.random.shuffle(script_urls) constant = 100 #batching scripts into 100 to take a #longer break of random time every 100 scrapes batches = [script_urls[i-constant:i] for i in range(constant,len(script_urls),constant)] new_scripts = { } for batch in tqdm(batches): # random sleep of uniform probability (evasion of blocking) for url in batch: #sleep_for = sum(np.random.random_sample(1))*0.5 # micro sleep to emulate unpredictable behaviour #time.sleep(sleep_for) title = url.split('/')[-1].strip('.html').strip(', The').upper() # try as some pages migh be irregular/not parsed etc try: script = clean(get_script(url)) new_scripts[title]=script except: print(title, 'not parsed') ``` 0%| | 0/9 [00:00<?, ?it/s] GREMLINS 2 SCRIP not parsed FURY SCRIP not parsed CONTACT SCRIP not parsed DONNIE DARKO SCRIP not parsed 11%|█████ | 1/9 [00:48<06:29, 48.70s/it] WHAT ABOUT BOB? SCRIP not parsed O BROTHER WHERE ART THOU? SCRIP not parsed BATMAN FOREVER SCRIP not parsed BATMAN RETURNS SCRIP not parsed 22%|██████████ | 2/9 [01:36<05:38, 48.38s/it] BATMAN BEGINS SCRIP not parsed HARRY POTTER AND THE HALF-BLOOD PRINCE SCRIP not parsed OUTBREAK SCRIP not parsed EXECUTIVE DECISION SCRIP not parsed HARRY POTTER AND THE GOBLET OF FIRE SCRIP not parsed 33%|███████████████ | 3/9 [02:25<04:51, 48.53s/it] VALENTINE'S DAY SCRIP not parsed 44%|████████████████████ | 4/9 [03:14<04:04, 48.85s/it] UNFORGIVEN SCRIP not parsed MATCHSTICK MEN SCRIP not parsed HARRY POTTER AND THE CHAMBER OF SECRETS SCRIP not parsed 56%|█████████████████████████ | 5/9 [04:04<03:16, 49.10s/it] GOODFELLAS SCRIP not parsed LETHAL WEAPON SCRIP not parsed CASABLANCA SCRIP not parsed BATMAN AND ROBIN SCRIP not parsed 67%|██████████████████████████████ | 6/9 [04:54<02:28, 49.43s/it] EYES WIDE SHUT SCRIP not parsed GINGER SNAPS SCRIP not parsed 78%|███████████████████████████████████ | 7/9 [05:46<01:39, 50.00s/it] WHO FRAMED ROGER RABBIT? SCRIP not parsed 89%|████████████████████████████████████████ | 8/9 [06:33<00:49, 49.38s/it] DARK KNIGHT, THE SCRIP not parsed HARRY POTTER AND THE DEATHLY HALLOWS PART 1 SCRIP not parsed 100%|█████████████████████████████████████████████| 9/9 [07:25<00:00, 49.46s/it] ```python len(new_scripts) ``` 866 ```python new_script = {key.replace('THE SCRIP','').replace('SCRIP',''):new_scripts[key] for key in new_scripts} ``` ```python all_scripts = {**names_dict, **new_script} print(f'there are now {len(all_scripts)} scripts scraped') passes_bechdel_one = {title:any(list(bechdel_one(all_scripts[title],fem_first))) for title in all_scripts} ``` there are now 1147 scripts scraped ```python passes_one_vector = np.array([passes_bechdel_one[key] for key in passes_bechdel_one]) #convert bools to ints passes_one_vector = passes_one_vector.astype(int) len(passes_one_vector) plt.bar(['does not pass','passes'],np.bincount(passes_one_vector)) np.count_nonzero(passes_one_vector) ``` ```python pass_all_vector = np.array([i in titles_that_pass for i in all_scripts]).astype(int) plt.bar(['does not pass','passes'],np.bincount(pass_all_vector)) ``` ```python pearson_r, p_val = stats.pearsonr(passes_one_vector,pass_all_vector) f'R value = {pearson_r:.3f} P value {p_val:.3f}' ``` 'R value = -0.022 P value 0.455' ```python f' Mathews coef = {matthews_corrcoef(pass_all_vector,passes_one_vector):.3f}' ``` ' Mathews coef = -0.022' ```python f' Jackards Dist = {distance.jaccard(pass_all_vector,passes_one_vector):.3f}' ``` ' Jackards Dist = 0.935' ```python tn, fp, fn, tp = confusion_matrix(pass_all_vector,passes_one_vector).ravel() f'accuracy = {sum([tp,tn])/sum([tn,fp,fn,tp]):.3f}' ``` 'accuracy = 0.364'
lemma integral_lebesgue_on_empty [simp]: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::{second_countable_topology,banach}" shows "integral\<^sup>L (lebesgue_on {}) f = 0"
(* This file is a part of IsarMathLib - a library of formalized mathematics for Isabelle/Isar. Copyright (C) 2022 Daniel de la Concepcion This program is free software; 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. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. *) section \<open>Rings - Ideals\<close> theory Ring_ZF_2 imports Ring_ZF Group_ZF_2 Finite_ZF Finite1 Cardinal_ZF Semigroup_ZF begin text \<open>This section defines the concept of a ring ideal, and defines some basic concepts and types, finishing with the theorem that shows that the quotient of the additive group by the ideal is actually a full ring.\<close> text\<open>An ideal is a subgroup of the additive group of the ring, which is closed by left and right multiplication by any ring element.\<close> definition (in ring0) Ideal ("_\<triangleleft>R") where "I \<triangleleft>R \<equiv> (\<forall>x\<in>I. \<forall>y\<in>R. y\<cdot>x\<in>I \<and> x\<cdot>y\<in>I) \<and> IsAsubgroup(I,A)" text\<open>To write less during proofs, we add this small definition\<close> abbreviation (in ring0) ideals ("\<I>") where "\<I> \<equiv> {J\<in>Pow(R). J\<triangleleft>R}" text\<open>The first examples of ideals are the whole ring and the zero ring:\<close> lemma (in ring0) R_ideal: shows "R \<triangleleft>R" unfolding Ideal_def apply simp using add_group.group0_3_T3[of R] Ring_ZF_1_L3(1) Ring_ZF_1_L2(1) unfolding IsOpClosed_def using Ring_ZF_1_L4(1,3) by auto lemma (in ring0) zero_ideal: shows "{\<zero>} \<triangleleft>R" unfolding Ideal_def using Ring_ZF_1_L6 add_group.unit_singl_subgr by auto text\<open>Some small lemmas dividing the definition of ideal into small parts\<close> lemma (in ring0) ideal_dest_subset: assumes "I \<triangleleft>R" shows "I \<subseteq> R" using assms unfolding Ideal_def using add_group.group0_3_L2 by auto lemma (in ring0) ideal_dest_sum: assumes "I \<triangleleft>R" "x\<in>I" "y\<in>I" shows "x\<ra>y \<in>I" using assms add_group.group0_3_L6 unfolding Ideal_def by auto lemma (in ring0) ideal_dest_mult: assumes "I \<triangleleft>R" "x\<in>I" "y\<in>R" shows "x\<cdot>y \<in>I" "y\<cdot>x \<in>I" using assms unfolding Ideal_def by auto lemma (in ring0) ideal_dest_minus: assumes "I \<triangleleft>R" "x\<in>I" shows "(\<rm>x) \<in> I" using assms unfolding Ideal_def using add_group.group0_3_T3A by auto lemma (in ring0) ideal_dest_zero: assumes "I \<triangleleft>R" shows "\<zero> \<in> I" using assms unfolding Ideal_def using add_group.group0_3_L5 by auto text\<open>The most simple way to obtain an ideal from others is the intersection, since the intersection of arbitrary ideals is an ideal.\<close> theorem (in ring0) intersection_ideals: assumes "\<forall>J\<in>\<J>. (J \<triangleleft>R)" "\<J> \<noteq> 0" shows "(\<Inter>\<J>) \<triangleleft>R" proof- { fix x assume x:"x:\<Inter>\<J>" { fix y assume y:"y:R" { fix J assume J:"J\<in>\<J>" with x have "x\<in>J" by auto with y J have "y\<cdot>x\<in>J \<and> x\<cdot>y\<in>J" using assms(1) ideal_dest_mult by auto } then have "y\<cdot>x\<in>\<Inter>\<J> \<and> x\<cdot>y\<in>\<Inter>\<J>" using assms(2) by auto } then have "\<forall>y\<in>R. y\<cdot>x\<in>\<Inter>\<J> \<and> x\<cdot>y\<in>\<Inter>\<J>" by auto } then have e2:"\<forall>x\<in>\<Inter>\<J>. \<forall>y\<in>R. y\<cdot>x\<in>\<Inter>\<J> \<and> x\<cdot>y\<in>\<Inter>\<J>" by auto have "IsAsubgroup(\<Inter>\<J>,A)" using add_group.subgroup_inter[OF assms(2)] assms(1) unfolding Ideal_def by auto with e2 show ?thesis unfolding Ideal_def by auto qed text\<open>From any set, we may construct the minimal ideal containing that set\<close> definition (in ring0) generatedIdeal ("\<langle>_\<rangle>\<^sub>I") where "X\<subseteq>R \<Longrightarrow> \<langle>X\<rangle>\<^sub>I \<equiv> \<Inter>{I\<in>\<I>. X \<subseteq> I}" text\<open>The ideal generated by a set is an ideal\<close> corollary (in ring0) generated_ideal_is_ideal: assumes "X\<subseteq>R" shows " \<langle>X\<rangle>\<^sub>I \<triangleleft>R" unfolding generatedIdeal_def[OF assms] apply (rule intersection_ideals) apply simp using R_ideal assms by auto text\<open>The ideal generated by a set is contained in any ideal containing the set\<close> corollary (in ring0) generated_ideal_small: assumes "X \<subseteq> I" "I \<triangleleft>R" shows " \<langle>X\<rangle>\<^sub>I \<subseteq> I" proof- have "I\<in>{J\<in>Pow(R). J \<triangleleft>R \<and> X\<subseteq>J}" using assms(2,1) ideal_dest_subset by auto then have "\<Inter>{J\<in>Pow(R). J \<triangleleft>R \<and> X\<subseteq>J} \<subseteq> I" by auto moreover from assms have "X\<subseteq> R" using ideal_dest_subset by auto ultimately show "\<langle>X\<rangle>\<^sub>I \<subseteq> I" using generatedIdeal_def[of X] by auto qed text\<open>The ideal generated by a set contains the set\<close> corollary (in ring0) generated_ideal_contains_set: assumes "X\<subseteq>R" shows "X\<subseteq>\<langle>X\<rangle>\<^sub>I" proof- { fix J assume J:"J:{J\<in>\<I>. X\<subseteq>J}" { fix t assume "t:X" with J have "t:J" by auto } then have "X\<subseteq>J" by auto } then have "X\<subseteq>\<Inter>{J\<in>\<I>. X\<subseteq>J} \<or> {J\<in>\<I>. X\<subseteq>J}=0" by auto then show "X\<subseteq>\<langle>X\<rangle>\<^sub>I" unfolding generatedIdeal_def[OF assms] using assms R_ideal by auto qed text\<open>To be able to show properties of an ideal generated by a set, we have the following induction result\<close> lemma (in ring0) induction_generated_ideal: assumes "\<forall>y\<in>R. \<forall>z\<in>R. \<forall>q\<in>\<langle>X\<rangle>\<^sub>I. P(q) \<longrightarrow> P(y\<cdot>q\<cdot>z)" "\<forall>y\<in>R. \<forall>z\<in>R. P(y) \<and> P(z) \<longrightarrow> P(y\<ra>z)" "X \<subseteq> R" "\<forall>x\<in>X. P(x)" "X\<noteq>0" shows "\<forall>y\<in>\<langle>X\<rangle>\<^sub>I. P(y)" proof- let ?J="{m\<in>\<langle>X\<rangle>\<^sub>I. P(m)}" have XJ:"X \<subseteq> ?J" using assms(3,4) generated_ideal_contains_set by auto have sub:"?J \<subseteq> R" using generated_ideal_is_ideal ideal_dest_subset assms(3) by auto moreover { fix y z assume "y\<in>R" "z\<in>?J" then have yz:"z\<in>\<langle>X\<rangle>\<^sub>I" "y\<in>R" "P(z)" "z:R" using sub by auto from assms(1) yz have "P(y\<cdot>z)" using Ring_ZF_1_L2(2) Ring_ZF_1_L3(5)[of "y\<cdot>z"] Ring_ZF_1_L4(3)[of y] by force moreover from assms(1) yz have "P(z\<cdot>y)" using Ring_ZF_1_L2(2) Ring_ZF_1_L3(6) Ring_ZF_1_L4(3)[of _ y] by force moreover from yz(1,2) have "y\<cdot>z\<in>\<langle>X\<rangle>\<^sub>I" "z\<cdot>y\<in>\<langle>X\<rangle>\<^sub>I" using generated_ideal_is_ideal[OF assms(3)] ideal_dest_mult by auto ultimately have "y\<cdot>z\<in>?J" "z\<cdot>y\<in>?J" by auto } then have "\<forall>x\<in>?J. \<forall>y\<in>R. y \<cdot> x \<in> ?J \<and> x \<cdot> y \<in> ?J" by auto moreover have "IsAsubgroup(?J,A)" proof(rule add_group.group0_3_T3) show "?J\<noteq>0" using assms(3-5) generated_ideal_contains_set[OF assms(3)] by force show "?J\<subseteq>R" using sub . { fix x assume "x:?J" then have x:"x:\<langle>X\<rangle>\<^sub>I" "x\<in>R" "P(x)" using sub by auto moreover have "\<one>:R" using Ring_ZF_1_L2(2). then have "\<one>:R" "(\<rm>\<one>):R" using Ring_ZF_1_L3(1) by auto ultimately have "P((\<rm>\<one>)\<cdot>x\<cdot>\<one>)" using assms(1) by auto then have "P((\<rm>x)\<cdot>\<one>)" using Ring_ZF_1_L3(6)[of x] Ring_ZF_1_L7(1)[of \<one> x] `\<one>:R` `x:R` by auto then have "P(\<rm>x)" using Ring_ZF_1_L3(5)[OF Ring_ZF_1_L3(1)] `x:R` by auto moreover from x(1) have "(\<rm>x)\<in>\<langle>X\<rangle>\<^sub>I" using generated_ideal_is_ideal[OF assms(3)] ideal_dest_minus by auto ultimately have "(\<rm>x)\<in>?J" by auto } then show "\<forall>x\<in>?J. (\<rm> x) \<in> ?J" by auto { fix x y assume as:"x\<in>?J" "y\<in>?J" from as have "P(x\<ra>y)" using assms(2) ideal_dest_subset[OF generated_ideal_is_ideal[OF assms(3)]] by auto moreover have "x\<ra>y\<in>\<langle>X\<rangle>\<^sub>I" using as generated_ideal_is_ideal[OF assms(3)] ideal_dest_sum by auto ultimately have "x\<ra>y \<in> ?J" by auto } then show "?J {is closed under} A" unfolding IsOpClosed_def by auto qed ultimately have "?J\<triangleleft>R" unfolding Ideal_def by auto with XJ have "\<langle>X\<rangle>\<^sub>I \<subseteq> ?J" using generated_ideal_small by auto then show ?thesis by auto qed text\<open>An ideal is very particular with the elements it may contain. If it contains any invertible element, it is in fact the whole ring and not a proper subset\<close> theorem (in ring0) ideal_with_one: assumes "I\<triangleleft>R" "\<one>\<in>I" shows "I = R" proof- from assms(1) have "I \<subseteq> R" using ideal_dest_subset by auto moreover { fix t assume t:"t:R" with assms have "t\<cdot>\<one> \<in>I" using ideal_dest_mult(2) by auto with t have "t:I" using Ring_ZF_1_L3(5) by auto } then have "R\<subseteq> I" by auto ultimately show "I=R" by auto qed theorem (in ring0) ideal_with_unit: assumes "I\<triangleleft>R" "x\<in>I" "\<exists>y\<in>R. y\<cdot>x = \<one> \<or> x\<cdot>y =\<one>" shows "I = R" proof- from assms(3) obtain y where y:"y:R" "y\<cdot>x = \<one> \<or> x\<cdot>y =\<one>" by auto from this(1) assms(1,2) have "y\<cdot>x \<in>I" "x\<cdot>y\<in>I" unfolding Ideal_def by auto with y(2) have "\<one>\<in>I" by auto with ideal_with_one assms(1) show ?thesis by auto qed text\<open>The previous result drives us to define what a maximal ideal would be: an ideal such that any bigger ideal is the whole ring\<close> definition (in ring0) maximalIdeal ("_\<triangleleft>\<^sub>mR") where "I\<triangleleft>\<^sub>mR \<equiv> I\<triangleleft>R \<and> I \<noteq>R \<and> (\<forall>J\<in>\<I>. I\<subseteq>J \<and> J\<noteq>R \<longrightarrow> I=J)" text\<open>Before delving into maximal ideals, lets define some operation on ideals that are useful when formulating some proofs.\<close> definition (in ring0) productIdeal (infix "\<cdot>\<^sub>I" 90) where "I\<triangleleft>R \<Longrightarrow> J\<triangleleft>R \<Longrightarrow> I\<cdot>\<^sub>IJ \<equiv> \<langle>M``(I\<times>J)\<rangle>\<^sub>I" definition (in ring0) sumIdeal (infix "+\<^sub>I" 90) where "I\<triangleleft>R \<Longrightarrow> J\<triangleleft>R \<Longrightarrow> I+\<^sub>IJ \<equiv> \<langle>I\<union>J\<rangle>\<^sub>I" text\<open>Some times, we may need to sum an arbitrary number of ideals, and not just two\<close> definition(in ring0) sumArbitraryIdeals ("\<oplus>\<^sub>I_" 90) where "\<J> \<subseteq> \<I> \<Longrightarrow> \<oplus>\<^sub>I\<J> \<equiv> \<langle>\<Union>\<J>\<rangle>\<^sub>I" text\<open>Every element in the arbitrary sum of ideals is generated by only a finite subset of those ideals\<close> lemma (in ring0) sum_ideals_finite_sum: assumes "\<J> \<subseteq> \<I>" "s\<in>(\<oplus>\<^sub>I\<J>)" shows "\<exists>\<T>\<in>FinPow(\<J>). s\<in>(\<oplus>\<^sub>I\<T>)" proof- { assume "\<Union>\<J>=0" then have "\<J>\<subseteq>{0}" by auto then have "Finite(\<J>)" using subset_Finite[OF _ nat_into_Finite[of 1]] by auto then have "\<J>\<in>FinPow(\<J>)" unfolding FinPow_def by auto then have ?thesis using assms(2) by auto } moreover { assume notE:"\<Union>\<J>\<noteq>0" let ?P= "\<lambda>t. \<exists>\<T>\<in>FinPow(\<J>). t\<in>(\<oplus>\<^sub>I\<T>)" { fix t assume "t\<in>\<Union>\<J>" then obtain J where J:"t\<in>J" "J\<in>\<J>" by auto then have "{J}\<in>FinPow(\<J>)" unfolding FinPow_def using eqpoll_imp_Finite_iff[of "{J}" "1"] nat_into_Finite by auto moreover have "(\<oplus>\<^sub>I{J}) = \<langle>J\<rangle>\<^sub>I" using J(2) assms(1) sumArbitraryIdeals_def by auto with J(1) have "t\<in>(\<oplus>\<^sub>I{J})" using generated_ideal_contains_set[of J] J(2) assms(1) by auto ultimately have "?P(t)" by auto } then have "\<forall>t\<in>\<Union>\<J>. ?P(t)" by auto moreover { fix y z q assume q:"?P(q)" "y:R" "z:R" "q:\<langle>\<Union>\<J>\<rangle>\<^sub>I" then obtain \<T> where T:"\<T>\<in>FinPow(\<J>)" "q:\<oplus>\<^sub>I\<T>" by auto from T(1) have "\<Union>\<T> \<subseteq> R" "\<T>\<subseteq>\<I>" using assms(1) unfolding FinPow_def by auto then have "(\<oplus>\<^sub>I\<T>)\<triangleleft>R" using generated_ideal_is_ideal[of "\<Union>\<T>"] sumArbitraryIdeals_def[of \<T>] by auto with T(2) q(2,3) have "y \<cdot> q \<cdot> z \<in> \<oplus>\<^sub>I\<T>" unfolding Ideal_def by auto with T(1) have "?P(y \<cdot> q \<cdot> z)" by auto } then have "\<forall>y\<in>R. \<forall>z\<in>R. \<forall>q\<in>\<langle>\<Union>\<J>\<rangle>\<^sub>I. ?P(q) \<longrightarrow> ?P(y \<cdot> q \<cdot> z)" by auto moreover { fix y z assume "?P(y)" "?P(z)" then obtain Ty Tz where T:"Ty\<in>FinPow(\<J>)" "y \<in> \<oplus>\<^sub>ITy" "Tz\<in>FinPow(\<J>)" "z \<in> \<oplus>\<^sub>ITz" by auto from T(1,3) have A:"Ty\<union>Tz:FinPow(\<J>)" unfolding FinPow_def using Finite_Un by auto then have "\<Union>Ty \<subseteq> \<Union>(Ty\<union>Tz)" "\<Union>Tz \<subseteq> \<Union>(Ty\<union>Tz)" and sub:"\<Union>(Ty\<union>Tz) \<subseteq>R" unfolding FinPow_def using assms(1) by auto with A have "\<Union>Ty \<subseteq> \<langle>\<Union>(Ty\<union>Tz)\<rangle>\<^sub>I" "\<Union>Tz \<subseteq> \<langle>\<Union>(Ty\<union>Tz)\<rangle>\<^sub>I" using generated_ideal_contains_set[of "\<Union>(Ty\<union>Tz)"] by auto then have "\<langle>\<Union>Ty\<rangle>\<^sub>I\<subseteq> \<langle>\<Union>(Ty\<union>Tz)\<rangle>\<^sub>I" "\<langle>\<Union>Tz\<rangle>\<^sub>I \<subseteq> \<langle>\<Union>(Ty\<union>Tz)\<rangle>\<^sub>I" using generated_ideal_small[OF _ generated_ideal_is_ideal] sub by auto moreover from T(1,3) have Q:"Ty \<subseteq>\<I>" "Tz\<subseteq> \<I>" using assms(1) unfolding FinPow_def by auto moreover note T(2,4) ultimately have "y\<in>\<langle>\<Union>(Ty\<union>Tz)\<rangle>\<^sub>I" "z\<in>\<langle>\<Union>(Ty\<union>Tz)\<rangle>\<^sub>I" using sumArbitraryIdeals_def[of "Ty"] sumArbitraryIdeals_def[of "Tz"] by auto then have "y\<ra>z\<in>\<langle>\<Union>(Ty\<union>Tz)\<rangle>\<^sub>I" using generated_ideal_is_ideal[OF sub] ideal_dest_sum by auto then have "y\<ra>z\<in>(\<oplus>\<^sub>I(Ty\<union>Tz))" using sumArbitraryIdeals_def[of "Ty\<union>Tz"] Q by force with A have "?P(y\<ra>z)" by auto } then have "\<forall>y\<in>R. \<forall>z\<in>R. ?P(y) \<and> ?P(z) \<longrightarrow> ?P(y \<ra> z)" by auto moreover have sub:"\<Union>\<J> \<subseteq> R" using assms(1) by auto ultimately have "\<forall>t\<in>\<langle>\<Union>\<J>\<rangle>\<^sub>I. ?P(t)" using induction_generated_ideal[of "\<Union>\<J>" ?P] notE by blast with assms(2) have ?thesis unfolding sumArbitraryIdeals_def[OF assms(1)] by auto } ultimately show ?thesis by auto qed text\<open>By definition of product of ideals and of an ideal itself, it follows that the product of ideals is an ideal contained in the intersection\<close> theorem (in ring0) product_in_intersection: assumes "I\<triangleleft>R" "J\<triangleleft>R" shows "I\<cdot>\<^sub>IJ \<subseteq> I\<inter>J" and "(I\<cdot>\<^sub>IJ)\<triangleleft>R" and "M``(I\<times>J) \<subseteq> I\<cdot>\<^sub>IJ" proof- have s:"M``(I\<times>J) \<subseteq> I\<inter>J" proof fix x assume x:"x\<in>M``(I\<times>J)" then obtain y where "y:I\<times>J" "\<langle>y,x\<rangle>\<in>M" unfolding image_def by auto then obtain yi yj where y:"yi:I" "yj:J" "\<langle>\<langle>yi,yj\<rangle>,x\<rangle>\<in>M" by auto then have "yi\<cdot>yj:I" "yi\<cdot>yj:J" using assms ideal_dest_subset[of I] ideal_dest_subset[of J] unfolding Ideal_def by auto with y(3) show "x\<in>I\<inter>J" using apply_equality[of _ x M] using ringAssum unfolding IsAring_def IsAmonoid_def IsAssociative_def by auto qed moreover have "(I\<inter>J) \<triangleleft>R" using intersection_ideals[of "{I,J}"] assms by auto ultimately show "I\<cdot>\<^sub>IJ \<subseteq> I\<inter>J" unfolding productIdeal_def[OF assms] using generated_ideal_small by auto from s have q:"M``(I\<times>J) \<subseteq> R" using assms ideal_dest_subset by auto with generated_ideal_is_ideal show "(I\<cdot>\<^sub>IJ) \<triangleleft>R" unfolding productIdeal_def[OF assms] by auto from q show "M``(I\<times>J) \<subseteq> I\<cdot>\<^sub>IJ" using generated_ideal_contains_set unfolding productIdeal_def[OF assms] by auto qed text\<open>We will show now that the sum of ideals is no more that the sum of the ideal elements\<close> lemma (in ring0) sum_elements: assumes "I \<triangleleft>R" "J \<triangleleft>R" "x \<in> I" "y \<in> J" shows "x\<ra>y \<in> I+\<^sub>IJ" proof- from assms(1,2) have "I\<union>J \<subseteq> R" using ideal_dest_subset by auto moreover have "x\<in> I\<union>J" "y\<in> I\<union>J" using assms(3,4) by auto ultimately have "x \<in> \<langle>I\<union>J\<rangle>\<^sub>I" "y \<in> \<langle>I\<union>J\<rangle>\<^sub>I" using generated_ideal_contains_set by auto moreover have "\<langle>I\<union>J\<rangle>\<^sub>I \<triangleleft>R" using generated_ideal_is_ideal[of "I\<union>J"] assms(1,2) using ideal_dest_subset[of I] ideal_dest_subset[of J] by auto ultimately have "x\<ra>y\<in>\<langle>I\<union>J\<rangle>\<^sub>I" using ideal_dest_sum by auto then show ?thesis using sumIdeal_def assms(1,2) by auto qed lemma (in ring0) sum_elements_is_ideal: assumes "I \<triangleleft>R" "J \<triangleleft>R" shows "(A``(I\<times>J)) \<triangleleft>R" proof- have a:"A:R\<times>R \<rightarrow> R" using add_group.groupAssum IsAgroup_def IsAmonoid_def IsAssociative_def by simp from assms have ij:"I\<times>J \<subseteq> R\<times>R" using ideal_dest_subset by auto from a have Aimage:"A``(I\<times>J) \<subseteq> R" using func1_1_L6(2) by auto moreover { fix x y assume xy:"x\<in>R" "y\<in>A``(I\<times>J)" from ij xy(2) obtain z where "y=A`z" "z\<in>I\<times>J" using func_imagedef[OF a, of "I\<times>J"] by auto then obtain yi yj where y:"y=yi\<ra>yj" "yi\<in>I" "yj\<in>J" by auto from y(1) have "x\<cdot>y = x\<cdot>(yi\<ra>yj)" "y\<cdot>x = (yi\<ra>yj)\<cdot>x" by auto then have "x\<cdot>y = (x\<cdot>yi)\<ra>(x\<cdot>yj)" "y\<cdot>x = (yi\<cdot>x)\<ra>(yj\<cdot>x)" using ring_oper_distr xy(1) y ij add_group.group_op_closed by auto moreover have "x\<cdot>yi \<in> I" "yi\<cdot>x \<in> I" "x\<cdot>yj \<in> J" "yj\<cdot>x \<in> J" using assms xy(1) y(2,3) ideal_dest_mult by auto ultimately have "x\<cdot>y\<in>A``(I\<times>J)" "y\<cdot>x\<in>A``(I\<times>J)" using func_imagedef[OF a, of "I\<times>J"] ij by auto } then have "\<forall>x\<in>A``(I\<times>J). \<forall>y\<in>R. y \<cdot> x \<in> A``(I\<times>J) \<and> x \<cdot> y \<in> A``(I\<times>J)" by auto moreover have "IsAsubgroup(A``(I\<times>J),A)" proof(rule add_group.group0_3_T3) show AsubR:"A `` (I \<times> J) \<subseteq> R" using Aimage. { fix x assume "x\<in>A `` (I \<times> J)" then obtain z where "x=A`z" "z\<in>I\<times>J" using func_imagedef[OF a, of "I\<times>J"] ij by auto then obtain xi xj where x:"xi\<in>I" "xj\<in>J" "x=xi\<ra>xj" by auto from x(3) have "(\<rm>x) = \<rm>(xi\<ra>xj)" by auto then have "(\<rm>x) = (\<rm>xi)\<rs>xj" using Ring_ZF_1_L9(2) assms x(1,2) ideal_dest_subset by auto moreover have "(\<rm>xi)\<in>I" using assms(1) ideal_dest_minus x(1) by auto moreover have "(\<rm>xj)\<in>J" using assms(2) ideal_dest_minus x(2) by auto ultimately have "(\<rm>x) \<in> A``(I\<times>J)" using func_imagedef[OF a, of "I\<times>J"] ij by auto } then show "\<forall>x\<in>A `` (I \<times> J). (\<rm> x) \<in> A `` (I \<times> J)" by auto have "\<zero>\<in>I" "\<zero>\<in>J" using ideal_dest_zero assms by auto then have "\<zero>\<ra>\<zero> \<in> A `` (I \<times> J)" using func_imagedef[OF a, of "I\<times>J"] ij by auto then show "A `` (I \<times> J) \<noteq> 0" by auto { fix x y assume xy:"x\<in> A `` (I \<times> J)" "y\<in> A `` (I \<times> J)" then obtain z g where "x=A`z" "z\<in>I\<times>J" "y=A`g" "g\<in>I\<times>J" using func_imagedef[OF a, of "I\<times>J"] ij by auto then obtain xi xj yi yj where x:"xi\<in>I" "xj\<in>J" "x=xi\<ra>xj" "yi\<in>I" "yj\<in>J" "y=yi\<ra>yj" by auto have "x\<ra>y = (x\<ra>yi)\<ra>yj" using xy(1) AsubR x(4-6) ij Ring_ZF_1_L10(1)[of x yi yj] by force then have "x\<ra>y = (xi\<ra>yi)\<ra>(xj\<ra>yj)" using x(1-5) ij Ring_ZF_2_L5(4)[of xi xj yi yj] by auto moreover have "xi\<ra>yi \<in> I" using x(1,4) assms(1) ideal_dest_sum by auto moreover have "xj\<ra>yj \<in> J" using x(2,5) assms(2) ideal_dest_sum by auto ultimately have "x\<ra>y \<in> A``(I\<times>J)" using func_imagedef[OF a, of "I\<times>J"] ij by auto } then show "A `` (I \<times> J) {is closed under} A" unfolding IsOpClosed_def by auto qed ultimately show "(A `` (I \<times> J))\<triangleleft>R" unfolding Ideal_def by auto qed corollary (in ring0) sum_ideals_is_sum_elements: assumes "I \<triangleleft>R" "J \<triangleleft>R" shows "(A `` (I \<times> J)) = I+\<^sub>IJ" proof have a:"A:R\<times>R \<rightarrow> R" using add_group.groupAssum IsAgroup_def IsAmonoid_def IsAssociative_def by simp from assms have ij:"I\<subseteq>R" "J \<subseteq> R" using ideal_dest_subset by auto then have ij_prd:"I\<times>J \<subseteq> R\<times>R" by auto then show "A `` (I \<times> J) \<subseteq> I +\<^sub>I J" using sum_elements[OF assms] func_imagedef[OF a, of "I\<times>J"] by auto { fix x assume x:"x\<in>I" with ij(1) have "x=x\<ra>\<zero>" using Ring_ZF_1_L3(3)[of x] by auto then have "x\<in>A `` (I \<times> J)" using x assms(2) add_group.group0_3_L5[of J] unfolding Ideal_def using func_imagedef[OF a, of "I\<times>J"] ij_prd by auto } then have "I \<subseteq> A `` (I \<times> J)" by auto moreover { fix x assume x:"x\<in>J" with ij(2) have "x=\<zero>\<ra>x" using Ring_ZF_1_L3(4)[of x] by auto then have "x\<in>A `` (I \<times> J)" using x assms(1) add_group.group0_3_L5[of I] unfolding Ideal_def using func_imagedef[OF a, of "I\<times>J"] ij_prd by auto } then have "J \<subseteq> A `` (I \<times> J)" by auto ultimately have "I\<union>J \<subseteq> A `` (I \<times> J)" by auto then show "I+\<^sub>IJ \<subseteq> A `` (I \<times> J)" using generated_ideal_small sum_elements_is_ideal[OF assms] assms sumIdeal_def by auto qed corollary (in ring0) sum_ideals_is_ideal: assumes "I \<triangleleft>R" "J \<triangleleft>R" shows "(I +\<^sub>I J) \<triangleleft>R" using assms sum_ideals_is_sum_elements sum_elements_is_ideal ideal_dest_subset by auto corollary (in ring0) sum_ideals_commute: assumes "I\<triangleleft>R" "J\<triangleleft>R" shows "(I +\<^sub>I J) = (J +\<^sub>I I)" proof- have "I \<union> J = J \<union> I" by auto then show ?thesis unfolding sumIdeal_def[OF assms] sumIdeal_def[OF assms(2,1)] by auto qed text\<open>Now that we know what the product of ideals is, we are able to define what a prime ideal is:\<close> definition (in ring0) primeIdeal ("_\<triangleleft>\<^sub>pR") where "P\<triangleleft>\<^sub>pR \<equiv> P\<triangleleft>R \<and> P\<noteq>R \<and> (\<forall>I\<in>\<I>. \<forall>J\<in>\<I>. I \<cdot>\<^sub>I J \<subseteq> P \<longrightarrow> (I \<subseteq> P \<or> J \<subseteq> P))" text\<open>Any maximal ideal is prime\<close> theorem (in ring0) maximal_is_prime: assumes "Q\<triangleleft>\<^sub>mR" shows "Q\<triangleleft>\<^sub>pR" proof- have a:"A:R\<times>R \<rightarrow> R" using add_group.groupAssum IsAgroup_def IsAmonoid_def IsAssociative_def by simp have MI:"Q \<in> \<I>" using assms unfolding maximalIdeal_def using ideal_dest_subset by auto { fix I J assume ij:"I\<in>\<I>" "J\<in>\<I>" "I \<cdot>\<^sub>I J \<subseteq> Q" { assume K:"\<not>(I\<subseteq>Q)" "\<not>(J\<subseteq>Q)" from this(1) obtain x where x:"x\<in>I-Q" by auto then have xR:"x\<in>R" using ij(1) ideal_dest_subset by auto let ?K = "\<langle>Q\<union>{x}\<rangle>\<^sub>I" have MK:"Q \<subseteq> ?K" "x\<in>?K" using generated_ideal_contains_set[of "Q\<union>{x}"] assms unfolding maximalIdeal_def using ideal_dest_subset[of Q] xR by auto with x have "Q \<subseteq> ?K" "?K\<noteq>Q" by auto with assms have "?K\<in>\<I> \<Longrightarrow> ?K=R" unfolding maximalIdeal_def by auto then have KR:"?K=R" using generated_ideal_is_ideal[of "Q\<union>{x}"] xR assms unfolding maximalIdeal_def using ideal_dest_subset[of Q] ideal_dest_subset[of "\<langle>Q\<union>{x}\<rangle>\<^sub>I"] by auto let ?P="Q+\<^sub>II" have "Q\<union>I \<subseteq> Q+\<^sub>II" using generated_ideal_contains_set[of "Q\<union>I"] sumIdeal_def[of Q I] assms ij(1) maximalIdeal_def using ideal_dest_subset by auto then have "Q\<union>{x} \<subseteq> Q+\<^sub>II" using x by auto then have "?K \<subseteq> Q+\<^sub>II" "Q+\<^sub>II \<subseteq>R" using generated_ideal_small[of "Q\<union>{x}" "Q+\<^sub>II"] generated_ideal_is_ideal[of "Q\<union>I"] sumIdeal_def[of Q I] ij(1) assms unfolding maximalIdeal_def using ideal_dest_subset by auto with KR have "Q+\<^sub>II = R" by auto then have "\<one>\<in>Q+\<^sub>II " using Ring_ZF_1_L2(2) by auto then have "\<one>\<in>A``(Q\<times>I)" using sum_ideals_is_sum_elements MI ij(1) by auto moreover have "Q\<times>I \<subseteq> R\<times>R" using MI ij(1) by auto ultimately obtain xm xi where mi1:"xm\<in>Q" "xi\<in>I" "\<one>=xm\<ra>xi" using func_imagedef[OF a, of "Q\<times>I"] by auto { fix y assume y:"y\<in>J" then have "\<one>\<cdot>y = y" using Ring_ZF_1_L3(6) ij(2) by auto with mi1(3) have "(xm\<ra>xi)\<cdot>y = y" by auto moreover have elems:"y:R" "xm:R" "xi:R" using y mi1(1,2) MI ij(1,2) by auto ultimately have "(xm\<cdot>y)\<ra>(xi\<cdot>y) = y" using ring_oper_distr(2)[of y xm xi] by auto moreover have "xm\<cdot>y:Q" using mi1(1) elems(1) MI ideal_dest_mult(1) by auto moreover have sub:"I\<times>J \<subseteq> R\<times>R" using ij(1,2) by auto have MR:"M:R\<times>R\<rightarrow>R" using ringAssum unfolding IsAring_def IsAmonoid_def IsAssociative_def by auto from sub MR have "xi\<cdot>y:M``(I\<times>J)" using func_imagedef[of M "R\<times>R" R "I\<times>J"] y mi1(2) by auto then have "xi\<cdot>y:I\<cdot>\<^sub>IJ" using generated_ideal_contains_set[of "M``(I\<times>J)"] func1_1_L6(2)[OF MR] productIdeal_def ij(1,2) by auto with ij(3) have "xi\<cdot>y:Q" by auto ultimately have "y\<in>Q" using MI ideal_dest_sum by force } then have "J \<subseteq> Q" by auto with K have False by auto } then have "(I\<subseteq>Q)\<or>(J\<subseteq>Q)" by auto } then have "\<forall>I\<in>\<I>. \<forall>J\<in>\<I>. I \<cdot>\<^sub>I J \<subseteq> Q \<longrightarrow> (I \<subseteq> Q \<or> J \<subseteq> Q)" by auto then show ?thesis using assms unfolding maximalIdeal_def primeIdeal_def by auto qed text\<open>In case of non-commutative rings, the zero divisor concept is too constrictive. For that we define the following concept of a prime ring. Note that in case that our ring is commutative, this is equivalent to having no zero divisors (there is no proof yet)\<close> definition primeRing ("[_,_,_]{is a prime ring}") where "IsAring(R,A,M) \<Longrightarrow> [R,A,M]{is a prime ring} \<equiv> (\<forall>x\<in>R. \<forall>y\<in>R. (\<forall>z\<in>R. M`\<langle>M`\<langle>x,z\<rangle>,y\<rangle> = TheNeutralElement(R,A)) \<longrightarrow> x =TheNeutralElement(R,A) \<or> y=TheNeutralElement(R,A))" text\<open>Prime rings appear when the zero ideal is prime\<close> lemma (in ring0) prime_ring_zero_prime_ideal: assumes "[R,A,M]{is a prime ring}" "R\<noteq>{\<zero>}" shows "{\<zero>}\<triangleleft>\<^sub>pR" proof- have MR:"M:R\<times>R\<rightarrow>R" using ringAssum unfolding IsAring_def IsAmonoid_def IsAssociative_def by auto { fix I J assume ij:"I\<in>\<I>" "J\<in>\<I>" "I \<cdot>\<^sub>I J \<subseteq> {\<zero>}" from ij(1,2) have ij_rr:"I\<times>J \<subseteq> R\<times>R" by auto { assume "\<not>(I\<subseteq>{\<zero>})" "\<not>(J\<subseteq>{\<zero>})" then obtain xi xj where x:"xi\<noteq>\<zero>" "xj\<noteq>\<zero>" "xi\<in>I" "xj:J" by auto { fix u assume "u\<in>R" with x(3) have "xi\<cdot>u\<in>I" using ij(1) ideal_dest_mult(1) by auto with x(4) have "xi\<cdot>u\<cdot>xj:M``(I\<times>J)" using func_imagedef[OF MR] ij_rr by auto then have "xi\<cdot>u\<cdot>xj:I \<cdot>\<^sub>I J" using generated_ideal_contains_set[of "M `` (I \<times> J)"] func1_1_L6(2)[OF MR, of "I\<times>J"] productIdeal_def ij(1,2) by auto with ij(3) have "xi\<cdot>u\<cdot>xj = \<zero>" by auto } then have "\<forall>u\<in>R. xi\<cdot>u\<cdot>xj = \<zero>" by auto moreover have "xi\<in>R" "xj\<in>R" using ij(1,2) x(3,4) by auto moreover note assms(1) ultimately have False using x(1,2) unfolding primeRing_def[OF ringAssum] by auto } then have "I\<subseteq>{\<zero>} \<or> J\<subseteq>{\<zero>}" by auto } then have "\<forall>I\<in>\<I>. \<forall>J\<in>\<I>. I \<cdot>\<^sub>I J \<subseteq> {\<zero>} \<longrightarrow> (I \<subseteq> {\<zero>} \<or> J \<subseteq> {\<zero>})" by auto moreover note zero_ideal assms(2) ultimately show ?thesis unfolding primeIdeal_def by auto qed lemma (in ring0) zero_prime_ideal_prime_ring: assumes "{\<zero>}\<triangleleft>\<^sub>pR" shows "[R,A,M]{is a prime ring}" proof- have MR:"M:R\<times>R\<rightarrow>R" using ringAssum unfolding IsAring_def IsAmonoid_def IsAssociative_def by auto { fix x y z assume as:"x\<in>R" "y\<in>R" "\<forall>z\<in>R. x\<cdot>z\<cdot>y = \<zero>" let ?X="\<langle>{x}\<rangle>\<^sub>I" let ?Y="\<langle>{y}\<rangle>\<^sub>I" have "?X\<subseteq>R" "?Y\<subseteq>R" using generated_ideal_is_ideal ideal_dest_subset as(1,2) by auto then have XY:"?X\<times>?Y \<subseteq> R\<times>R" by auto let ?P="\<lambda>q. (\<forall>z\<in>?Y. q\<cdot>z = \<zero>)" let ?Q="\<lambda>q. (\<forall>z\<in>R. x\<cdot>z\<cdot>q =\<zero>)" have Y:"\<forall>y\<in>?Y. ?Q(y)" proof(rule induction_generated_ideal) show "{y}\<subseteq>R" "{y}\<noteq>0" using as(2) by auto show "\<forall>xa\<in>{y}. \<forall>z\<in>R. x \<cdot> z \<cdot> xa = \<zero>" using as(3) by auto { fix s t q assume yzq:"s:R" "t:R" "q:\<langle>{y}\<rangle>\<^sub>I" "\<forall>k\<in>R. x \<cdot> k \<cdot> q = \<zero>" from yzq(3) have q:"q\<in>R" using generated_ideal_is_ideal ideal_dest_subset as(2) by auto { fix u assume "u:R" have "x \<cdot> u \<cdot> (s \<cdot> q \<cdot> t) = (x \<cdot> (u\<cdot>s)\<cdot>q)\<cdot>t" using Ring_ZF_1_L11(2) yzq(1-2) q `u:R` as(1) Ring_ZF_1_L4(3) by auto moreover have "u\<cdot>s:R" using `u:R` yzq(1) Ring_ZF_1_L4(3) by auto moreover note yzq(4) ultimately have "x \<cdot> u \<cdot> (s \<cdot> q \<cdot> t) = \<zero>\<cdot>t" by auto then have "x \<cdot> u \<cdot> (s \<cdot> q \<cdot> t) = \<zero>" using yzq(2) Ring_ZF_1_L6(1) by auto } then have "\<forall>za\<in>R. x \<cdot> za \<cdot> (s \<cdot> q \<cdot> t) = \<zero>" by auto } then show "\<forall>t\<in>R. \<forall>z\<in>R. \<forall>q\<in>\<langle>{y}\<rangle>\<^sub>I. (\<forall>z\<in>R. x \<cdot> z \<cdot> q = \<zero>) \<longrightarrow> (\<forall>za\<in>R. x \<cdot> za \<cdot> (t \<cdot> q \<cdot> z) = \<zero>)" by auto { fix s t assume st:"s:R" "t:R" "\<forall>k\<in>R. x \<cdot> k \<cdot> s = \<zero>" "\<forall>k\<in>R. x \<cdot> k \<cdot> t = \<zero>" { fix u assume "u:R" have "x \<cdot> u \<cdot> (s \<ra> t) = (x \<cdot> u \<cdot> s) \<ra>(x \<cdot> u \<cdot> t)" using ring_oper_distr(1) `u:R` as(1) st(1,2) Ring_ZF_1_L4(3) by auto with st(3,4) `u:R` have "x \<cdot> u \<cdot> (s \<ra> t) = \<zero> \<ra> \<zero>" by auto then have "x \<cdot> u \<cdot> (s \<ra> t) = \<zero>" using Ring_ZF_1_L3(3) Ring_ZF_1_L2(1) by auto } then have "\<forall>za\<in>R. x \<cdot> za \<cdot> (s \<ra> t) = \<zero>" by auto } then show "\<forall>y\<in>R. \<forall>z\<in>R. (\<forall>z\<in>R. x \<cdot> z \<cdot> y = \<zero>) \<and> (\<forall>za\<in>R. x \<cdot> za \<cdot> z = \<zero>) \<longrightarrow> (\<forall>za\<in>R. x \<cdot> za \<cdot> (y \<ra> z) = \<zero>)" by auto qed { fix yy assume "yy:?Y" with Y have "\<forall>z\<in>R. x \<cdot> z \<cdot> yy = \<zero>" by auto then have "x\<cdot>yy = \<zero>" using Ring_ZF_1_L2(2) Ring_ZF_1_L3(5) as(1) by auto } then have z:"\<forall>y\<in>?Y. x\<cdot>y = \<zero>" by auto have yy:"?Y\<triangleleft>R" "?Y \<subseteq> R" using generated_ideal_is_ideal as(2) ideal_dest_subset by auto have xy:"\<forall>y\<in>?X. ?P(y)" proof(rule induction_generated_ideal) show "{x}\<subseteq>R" "{x}\<noteq>0" using as(1) by auto from z show "\<forall>x\<in>{x}. \<forall>z\<in>\<langle>{y}\<rangle>\<^sub>I. x \<cdot> z = \<zero>" by auto { fix q1 q2 q3 assume q:"q1:R" "q2:R" "q3:\<langle>{x}\<rangle>\<^sub>I" "\<forall>k\<in>?Y. q3 \<cdot> k = \<zero>" have q3:"q3\<in>R" using q(3) generated_ideal_is_ideal as(1) ideal_dest_subset by auto { fix q4 assume q4:"q4\<in>?Y" from yy q4 q(2) have "q2 \<cdot> q4 :?Y" using ideal_dest_mult(2) by auto moreover have "q1 \<cdot> q3 \<cdot> q2 \<cdot> q4 = q1 \<cdot> (q3 \<cdot> (q2 \<cdot> q4))" using q(1-2) q3 q4 yy(2) Ring_ZF_1_L4(3) Ring_ZF_1_L11(2) by auto moreover note q(4) ultimately have "q1 \<cdot> q3 \<cdot> q2 \<cdot> q4 = q1 \<cdot> \<zero>" by auto then have "q1 \<cdot> q3 \<cdot> q2 \<cdot> q4 = \<zero>" using Ring_ZF_1_L6(2) q(1) by auto } then have "\<forall>za\<in>\<langle>{y}\<rangle>\<^sub>I. q1 \<cdot> q3 \<cdot> q2 \<cdot> za = \<zero>" by auto } then show "\<forall>ya\<in>R. \<forall>z\<in>R. \<forall>q\<in>\<langle>{x}\<rangle>\<^sub>I. (\<forall>z\<in>\<langle>{y}\<rangle>\<^sub>I. q \<cdot> z = \<zero>) \<longrightarrow> (\<forall>za\<in>\<langle>{y}\<rangle>\<^sub>I. ya \<cdot> q \<cdot> z \<cdot> za = \<zero>)" by auto { fix q1 q2 assume q:"q1:R" "q2:R" "\<forall>z\<in>\<langle>{y}\<rangle>\<^sub>I. q1 \<cdot> z = \<zero>" "\<forall>za\<in>\<langle>{y}\<rangle>\<^sub>I. q2 \<cdot> za = \<zero>" { fix q3 assume "q3\<in>?Y" have "(q1 \<ra> q2) \<cdot> q3 = (q1\<cdot>q3) \<ra> (q2\<cdot>q3)" using ring_oper_distr(2) q(1,2) `q3:?Y` yy(2) by auto with q(3,4) have "(q1 \<ra> q2) \<cdot> q3 = \<zero> \<ra> \<zero>" using `q3:?Y` by auto then have "(q1 \<ra> q2) \<cdot> q3 = \<zero>" using Ring_ZF_1_L3(3) Ring_ZF_1_L2(1) by auto } then have "\<forall>q\<in>?Y. (q1 \<ra> q2) \<cdot> q = \<zero>" by auto } then show "\<forall>ya\<in>R. \<forall>z\<in>R. (\<forall>z\<in>\<langle>{y}\<rangle>\<^sub>I. ya \<cdot> z = \<zero>) \<and> (\<forall>za\<in>\<langle>{y}\<rangle>\<^sub>I. z \<cdot> za = \<zero>) \<longrightarrow> (\<forall>za\<in>\<langle>{y}\<rangle>\<^sub>I. (ya \<ra> z) \<cdot> za = \<zero>)" by auto qed { fix q assume "q\<in>M``(?X\<times>?Y)" then obtain qx qy where q:"qx:?X" "qy:?Y" "q=qx\<cdot>qy" using func_imagedef[OF MR XY] by auto with xy have "q=\<zero>" by auto } then have "M``(?X\<times>?Y) \<subseteq> {\<zero>}" by auto then have "?X\<cdot>\<^sub>I?Y \<subseteq> {\<zero>}" using generated_ideal_small zero_ideal productIdeal_def generated_ideal_is_ideal as(1,2) by auto then have "?X \<subseteq> {\<zero>} \<or> ?Y \<subseteq> {\<zero>}" using assms unfolding primeIdeal_def using generated_ideal_is_ideal as(1,2) ideal_dest_subset by auto then have "x=\<zero> \<or> y =\<zero>" using generated_ideal_contains_set as(1,2) by auto } then have " \<forall>x\<in>R. \<forall>y\<in>R. (\<forall>z\<in>R. x \<cdot> z \<cdot> y = \<zero>) \<longrightarrow> x = \<zero> \<or> y = \<zero>" by auto then show ?thesis unfolding primeRing_def[OF ringAssum] by auto qed text\<open>We can actually use this definition of a prime ring, as a condition to check for prime ideals.\<close> theorem (in ring0) equivalent_prime_ideal: assumes "P\<triangleleft>\<^sub>pR" shows "\<forall>x\<in>R. \<forall>y\<in>R. (\<forall>z\<in>R. x\<cdot>z\<cdot>y\<in>P) \<longrightarrow> x\<in>P \<or> y\<in>P" proof(safe) fix x y assume as:"x\<in>R" "y\<in>R" "\<forall>z\<in>R. x\<cdot>z\<cdot>y\<in>P" "y\<notin>P" let ?X="\<langle>{x}\<rangle>\<^sub>I" let ?Y="\<langle>{y}\<rangle>\<^sub>I" from as(3) have "\<forall>x\<in>{x}. \<forall>u\<in>R. x \<cdot> u \<cdot> y \<in> P" by auto moreover have "\<forall>ya\<in>R. \<forall>z\<in>R. \<forall>q\<in>?X. (\<forall>u\<in>R. q \<cdot> u \<cdot> y \<in> P) \<longrightarrow> (\<forall>u\<in>R. ya \<cdot> q \<cdot> z \<cdot> u \<cdot> y \<in> P)" proof(safe) fix ya z q u assume ass:"ya\<in>R" "z\<in>R" "q\<in>?X" "\<forall>u\<in>R. q \<cdot> u \<cdot> y \<in> P" "u \<in> R" from ass(3) have q:"q\<in>R" using generated_ideal_is_ideal[THEN ideal_dest_subset] as(1) by auto from ass(2,5) have "z\<cdot>u\<in>R" using Ring_ZF_1_L4(3) by auto with ass(4) have "q\<cdot>(z\<cdot>u)\<cdot>y:P" by auto with ass(1) have "ya\<cdot>(q\<cdot>(z\<cdot>u)\<cdot>y)\<in>P" using assms unfolding primeIdeal_def using ideal_dest_mult(2) by auto then show "ya\<cdot>q\<cdot>z\<cdot>u\<cdot>y\<in>P" using Ring_ZF_1_L4(3) Ring_ZF_1_L11(2) ass(1,2,5) as(2) q by auto qed moreover have "\<forall>ya\<in>R. \<forall>z\<in>R. (\<forall>u\<in>R. ya \<cdot> u \<cdot> y \<in> P) \<and> (\<forall>u\<in>R. z \<cdot> u \<cdot> y \<in> P) \<longrightarrow> (\<forall>u\<in>R. (ya \<ra> z) \<cdot> u \<cdot> y \<in> P)" proof(safe) fix ya z u assume ass:"ya\<in>R" "z\<in>R" "u\<in>R" "\<forall>u\<in>R. ya \<cdot> u \<cdot> y \<in> P" "\<forall>u\<in>R. z \<cdot> u \<cdot> y \<in> P" from ass(3-5) have "ya \<cdot> u \<cdot> y \<in> P" "z \<cdot> u \<cdot> y \<in> P" by auto then have "(ya \<cdot> u \<cdot> y)\<ra>(z \<cdot> u \<cdot> y) \<in> P" using ideal_dest_sum assms unfolding primeIdeal_def by auto then have "((ya\<cdot>u)\<ra>(z\<cdot>u))\<cdot>y\<in>P" using ring_oper_distr(2) as(2) Ring_ZF_1_L4(3) ass(1-3) by auto then show "((ya\<ra>z)\<cdot>u)\<cdot>y\<in>P" using ring_oper_distr(2) ass(1-3) by auto qed ultimately have R:"\<forall>ya\<in>\<langle>{x}\<rangle>\<^sub>I. \<forall>u\<in>R. ya \<cdot> u \<cdot> y \<in> P" using induction_generated_ideal[of "{x}" "\<lambda>t. \<forall>u\<in>R. t\<cdot>u\<cdot>y \<in> P"] as(1) by auto then have "\<forall>xa\<in>{y}. \<forall>t\<in>\<langle>{x}\<rangle>\<^sub>I. \<forall>u\<in>R. t \<cdot> u \<cdot> xa \<in> P" by auto moreover have "\<forall>ya\<in>R. \<forall>z\<in>R. \<forall>q\<in>\<langle>{y}\<rangle>\<^sub>I. (\<forall>t\<in>\<langle>{x}\<rangle>\<^sub>I. \<forall>u\<in>R. t \<cdot> u \<cdot> q \<in> P) \<longrightarrow> (\<forall>t\<in>\<langle>{x}\<rangle>\<^sub>I. \<forall>u\<in>R. t \<cdot> u \<cdot> (ya \<cdot> q \<cdot> z) \<in> P)" proof(safe) fix ya z q t u assume ass:"ya\<in>R" "z\<in>R" "q\<in>?Y" "\<forall>t\<in>?X. \<forall>u\<in>R. t \<cdot> u \<cdot> q \<in> P" "t\<in>?X" "u\<in>R" from ass(3,5) have qt:"q:R" "t\<in>R" using generated_ideal_is_ideal ideal_dest_subset as(1,2) by auto from ass(1,6) have "u\<cdot>ya:R" using Ring_ZF_1_L4(3) by auto with ass(4,5) have "t\<cdot>(u\<cdot>ya)\<cdot>q \<in>P" by auto then have "(t\<cdot>(u\<cdot>ya)\<cdot>q)\<cdot>z\<in>P" using ass(2) assms ideal_dest_mult(1) unfolding primeIdeal_def by auto then show "t \<cdot> u \<cdot> (ya \<cdot> q \<cdot> z) \<in>P" using Ring_ZF_1_L4(3) Ring_ZF_1_L11(2) ass(1,2,6) qt by auto qed moreover have "\<forall>y\<in>R. \<forall>z\<in>R. (\<forall>t\<in>\<langle>{x}\<rangle>\<^sub>I. \<forall>u\<in>R. t \<cdot> u \<cdot> y \<in> P) \<and> (\<forall>t\<in>\<langle>{x}\<rangle>\<^sub>I. \<forall>u\<in>R. t \<cdot> u \<cdot> z \<in> P) \<longrightarrow> (\<forall>t\<in>\<langle>{x}\<rangle>\<^sub>I. \<forall>u\<in>R. t \<cdot> u \<cdot> (y \<ra> z) \<in> P)" proof(safe) fix ya z t u assume ass:"ya\<in>R" "z\<in>R" "t\<in>?X" "u\<in>R" "\<forall>t\<in>\<langle>{x}\<rangle>\<^sub>I. \<forall>u\<in>R. t \<cdot> u \<cdot> ya \<in> P" "\<forall>t\<in>\<langle>{x}\<rangle>\<^sub>I. \<forall>u\<in>R. t \<cdot> u \<cdot> z \<in> P" from ass(3) have "t\<in>R" using ideal_dest_subset generated_ideal_is_ideal as(1) by auto from ass(3-6) have "t \<cdot> u \<cdot> ya \<in> P" "t \<cdot> u \<cdot> z \<in> P" by auto then have "(t \<cdot> u \<cdot> ya)\<ra>(t \<cdot> u \<cdot> z) \<in>P" using assms unfolding primeIdeal_def using ideal_dest_sum by auto then have "t\<cdot>((u\<cdot>ya)\<ra>(u\<cdot>z)) \<in>P" using ring_oper_distr(1) `t\<in>R` Ring_ZF_1_L4(3) ass(4,2,1) Ring_ZF_1_L11 by auto then have "t\<cdot>(u\<cdot>(ya\<ra>z)) \<in>P" using ring_oper_distr(1) ass(1,2,4) by auto then show "t\<cdot>u\<cdot>(ya\<ra>z) \<in>P" using Ring_ZF_1_L11(2) Ring_ZF_1_L4(1) ass(1,2,4) `t\<in>R` by auto qed ultimately have R:"\<forall>q\<in>?Y. \<forall>t\<in>?X. \<forall>u\<in>R. t\<cdot>u\<cdot>q \<in> P" using induction_generated_ideal[of "{y}" "\<lambda>q. \<forall>t\<in>?X. \<forall>u\<in>R. t\<cdot>u\<cdot>q \<in> P"] as(2) by auto have "?X\<subseteq>R" "?Y\<subseteq>R" using ideal_dest_subset generated_ideal_is_ideal as(1,2) by auto then have subprd:"?X\<times>?Y \<subseteq> R\<times>R" by auto { fix t assume "t\<in>M``(?X\<times>?Y)" then obtain tx ty where t:"tx\<in>?X" "ty\<in>?Y" "t= tx\<cdot>ty" using func_imagedef[of M "R\<times>R" R "?X\<times>?Y"] subprd ringAssum unfolding IsAring_def IsAmonoid_def IsAssociative_def by auto from this(1,2) have "tx\<cdot>\<one>\<cdot>ty \<in>P" using R Ring_ZF_1_L2(2) by auto moreover from t(1) have "tx\<in>R" using generated_ideal_is_ideal[THEN ideal_dest_subset] as(1) by auto ultimately have "t\<in>P" using Ring_ZF_1_L3(5) t(3) by auto } then have "M``(?X\<times>?Y) \<subseteq> P" by auto then have "?X\<cdot>\<^sub>I?Y \<subseteq> P" using generated_ideal_small assms unfolding primeIdeal_def using productIdeal_def[ OF generated_ideal_is_ideal generated_ideal_is_ideal] as(1,2) by auto moreover have "?X:\<I>" "?Y:\<I>" using generated_ideal_is_ideal generated_ideal_is_ideal[THEN ideal_dest_subset] as(1,2) by auto ultimately have "?X \<subseteq> P \<or> ?Y \<subseteq> P" using assms unfolding primeIdeal_def by auto with as(4) generated_ideal_contains_set as(2) have "?X \<subseteq> P" by auto then show "x\<in>P" using generated_ideal_contains_set as(1) by auto qed theorem (in ring0) equivalent_prime_ideal_2: assumes "\<forall>x\<in>R. \<forall>y\<in>R. (\<forall>z\<in>R. x\<cdot>z\<cdot>y\<in>P) \<longrightarrow> x\<in>P \<or> y\<in>P" "P\<triangleleft>R" "P\<noteq>R" shows "P\<triangleleft>\<^sub>pR" unfolding primeIdeal_def apply(safe) using assms(2) apply simp using assms(3) apply simp proof- fix I J x xa assume as:"I\<triangleleft>R" "I\<subseteq>R" "J\<triangleleft>R" "J\<subseteq>R" "I \<cdot>\<^sub>I J \<subseteq> P" "x \<in> J" "x \<notin> P" "xa \<in> I" from as(4,2) have prdsub:"I\<times>J \<subseteq> R\<times>R" by auto { fix z assume z:"z\<in>R" then have "xa\<cdot>z\<in>I" using as(1,8) ideal_dest_mult(1) by auto then have "\<langle>xa\<cdot>z,x\<rangle>\<in>I\<times>J" using as(6) by auto then have "(xa\<cdot>z\<cdot>x)\<in>M``(I\<times>J)" using func_imagedef[of M "R\<times>R" R "I\<times>J"] prdsub ringAssum unfolding IsAring_def IsAmonoid_def IsAssociative_def by auto then have "(xa\<cdot>z\<cdot>x)\<in>\<langle>M``(I\<times>J)\<rangle>\<^sub>I" using generated_ideal_contains_set [OF func1_1_L6(2)[of M "R\<times>R" R]] ringAssum unfolding IsAring_def IsAmonoid_def IsAssociative_def by force then have "(xa\<cdot>z\<cdot>x)\<in> I\<cdot>\<^sub>IJ" using productIdeal_def as(1,3) by auto with as(5) have "xa\<cdot>z\<cdot>x\<in>P" by auto } then have "\<forall>z\<in>R. xa\<cdot>z\<cdot>x \<in> P" by auto moreover have "xa\<in>R" "x\<in>R" using as(2,4,6,8) by auto with assms(1) have "(\<forall>z\<in>R. xa \<cdot> z \<cdot> x \<in> P) \<longrightarrow> x \<in> P \<or> xa \<in> P" by auto ultimately have "x\<in>P \<or> xa\<in>P" by auto with as(7) show "xa\<in>P" by auto qed subsection\<open>Ring quotient\<close> text\<open>Similar to groups, rings can be quotiented by normal additive subgroups; but to keep the structure of the multiplicative monoid we need extra structure in the normal subgroup. This extra structure is given by the ideal.\<close> text\<open>Any ideal is a normal subgroup\<close> lemma (in ring0) ideal_normal_add_subgroup: assumes "I\<triangleleft>R" shows "IsAnormalSubgroup(R,A,I)" using Group_ZF_2_4_L6(1) using ringAssum unfolding IsAring_def using assms unfolding Ideal_def by auto definition (in ring0) QuotientBy where "I\<triangleleft>R \<Longrightarrow> QuotientBy(I) \<equiv> R//QuotientGroupRel(R,A,I)" text\<open>Any ideal gives rise to an equivalent relation\<close> corollary (in ring0) equiv_rel: assumes "I\<triangleleft>R" shows "equiv(R,QuotientGroupRel(R,A,I))" using assms add_group.Group_ZF_2_4_L3 unfolding Ideal_def by auto text\<open>Any quotient by an ideal is an abelian group\<close> lemma (in ring0) quotientBy_add_group: assumes "I\<triangleleft>R" shows "IsAgroup(QuotientBy(I), QuotientGroupOp(R, A, I))" and "QuotientGroupOp(R, A, I) {is commutative on} QuotientBy(I)" proof- from Group_ZF_2_4_T1[of R A I] show "IsAgroup(QuotientBy(I), QuotientGroupOp(R, A, I))" using ideal_normal_add_subgroup[OF assms] ringAssum unfolding QuotientBy_def[OF assms] IsAring_def by auto from Group_ZF_2_4_L6(2) show "QuotientGroupOp(R, A, I) {is commutative on} QuotientBy(I)" using ringAssum unfolding IsAring_def QuotientBy_def[OF assms] using assms unfolding Ideal_def by auto qed text\<open>The multiplicative monoid is congruent with the quotient relation and gives rise to a monoid in the quotient\<close> lemma (in ring0) quotientBy_mul_monoid: assumes "I\<triangleleft>R" shows "Congruent2(QuotientGroupRel(R, A, I),M)" and "IsAmonoid(QuotientBy(I),ProjFun2(R, QuotientGroupRel(R,A,I), M))" proof- { fix x y s t assume "\<langle>x,y\<rangle>\<in>QuotientGroupRel(R,A,I)" "\<langle>s,t\<rangle>\<in>QuotientGroupRel(R,A,I)" then have xyst:"x\<in>R" "y\<in>R" "s\<in>R" "t\<in>R" "x\<rs>y \<in>I" "s\<rs>t \<in>I" unfolding QuotientGroupRel_def by auto have "(x\<cdot>s)\<rs>(y\<cdot>t) = (x\<cdot>s)\<ra>\<zero>\<rs>(y\<cdot>t)" using Ring_ZF_1_L3(3) Ring_ZF_1_L4(3)[OF xyst(1,3)] by auto then have "(x\<cdot>s)\<rs>(y\<cdot>t) = ((x\<cdot>s)\<ra>((\<rm>(y\<cdot>s))\<ra>(y\<cdot>s)))\<rs>(y\<cdot>t)" using Ring_ZF_1_L3(7)[of "y\<cdot>s"] Ring_ZF_1_L4(3)[OF xyst(2,3)] Ring_ZF_1_L4(4)[of "\<rm>(y\<cdot>s)" "y\<cdot>s"] Ring_ZF_1_L3(1)[of "y\<cdot>s"] by auto then have "(x\<cdot>s)\<rs>(y\<cdot>t) = ((x\<cdot>s)\<rs>(y\<cdot>s))\<ra>((y\<cdot>s)\<rs>(y\<cdot>t))" using Ring_ZF_1_L3(1) Ring_ZF_1_L4(1,2) Ring_ZF_1_L10(1)[of "x\<cdot>s" "\<rm>(y\<cdot>s)" "y\<cdot>s"] Ring_ZF_1_L10(1)[of "(x\<cdot>s)\<rs>(y\<cdot>s)" "y\<cdot>s" "\<rm>(y\<cdot>t)"] Ring_ZF_1_L4(3)[OF xyst(1,3)] Ring_ZF_1_L4(3)[OF xyst(2,3)] Ring_ZF_1_L4(3)[OF xyst(2,4)] by auto then have "(x\<cdot>s)\<rs>(y\<cdot>t) = ((x\<rs>y)\<cdot>s)\<ra>(y\<cdot>(s\<rs>t))" using Ring_ZF_1_L8 xyst(1-4) by auto moreover have "(x\<rs>y)\<cdot>s \<in>I" using xyst(3,5) assms ideal_dest_mult(1) by auto moreover have "y\<cdot>(s\<rs>t) \<in>I" using xyst(2,6) assms ideal_dest_mult(2) by auto ultimately have "(x\<cdot>s)\<rs>(y\<cdot>t) \<in>I" using assms ideal_dest_sum by auto then have "\<langle>M ` \<langle>x, s\<rangle>, M ` \<langle>y, t\<rangle>\<rangle> \<in> QuotientGroupRel(R, A, I)" unfolding QuotientGroupRel_def using Ring_ZF_1_L4(3) xyst(1-4) by auto } then show "Congruent2(QuotientGroupRel(R, A, I),M)" unfolding Congruent2_def by auto moreover have "equiv(R,QuotientGroupRel(R,A,I))" using add_group.Group_ZF_2_4_L3 assms unfolding Ideal_def by auto moreover note mult_monoid.Group_ZF_2_2_T1 ultimately show "IsAmonoid(QuotientBy(I),ProjFun2(R, QuotientGroupRel(R,A,I), M))" unfolding QuotientBy_def[OF assms] by auto qed definition (in ring0) ideal_radd ("_{\<ra>_}_") where "x{\<ra>I}y \<equiv> QuotientGroupOp(R, A, I)`\<langle>x,y\<rangle>" definition (in ring0) ideal_rmult ("_{\<cdot>_}_") where "x{\<cdot>I}y \<equiv> ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,y\<rangle>" definition (in ring0) ideal_rmin ("{\<rm>_}_") where "{\<rm>I}y \<equiv> GroupInv(QuotientBy(I),QuotientGroupOp(R, A, I))`y" definition (in ring0) ideal_rsub ("_{\<rs>_}_") where "x{\<rs>I}y \<equiv> x{\<ra>I}({\<rm>I}y)" definition (in ring0) ideal_rzero ("\<zero>\<^sub>_") where "\<zero>\<^sub>I \<equiv> QuotientGroupRel(R,A,I)``{\<zero>}" definition (in ring0) ideal_rone ("\<one>\<^sub>_") where "\<one>\<^sub>I \<equiv> QuotientGroupRel(R,A,I)``{\<one>}" definition (in ring0) ideal_rtwo ("\<two>\<^sub>_") where "\<two>\<^sub>I \<equiv> QuotientGroupRel(R,A,I)``{\<two>}" definition (in ring0) ideal_rsqr ("_\<^sup>2\<^sup>_") where "x\<^sup>2\<^sup>I \<equiv> ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,x\<rangle>" lemma (in ring0) neutral_quotient: assumes "I\<triangleleft>R" shows "QuotientGroupRel(R,A,I)``{\<zero>} = TheNeutralElement(QuotientBy(I),QuotientGroupOp(R, A, I))" using Group_ZF_2_4_L5B[of R A I "QuotientGroupRel(R, A, I)" \<zero>] ideal_normal_add_subgroup[OF assms] ringAssum unfolding IsAring_def QuotientBy_def[OF assms] by auto lemma (in ring0) one_quotient: assumes "I\<triangleleft>R" shows "QuotientGroupRel(R,A,I)``{\<one>} = TheNeutralElement(QuotientBy(I),ProjFun2(R, QuotientGroupRel(R, A, I), M))" using Group_ZF_2_2_L1[of R M "QuotientGroupRel(R, A, I)" "ProjFun2(R, QuotientGroupRel(R, A, I), M)" \<one>] equiv_rel[OF assms] quotientBy_mul_monoid[OF assms] ringAssum unfolding IsAring_def QuotientBy_def[OF assms] by auto lemma (in ring0) two_quotient: assumes "I\<triangleleft>R" shows "QuotientGroupRel(R,A,I)``{\<two>} = QuotientGroupOp(R, A, I)`\<langle>QuotientGroupRel(R,A,I)``{\<one>},QuotientGroupRel(R,A,I)``{\<one>}\<rangle>" proof- have "QuotientGroupRel(R,A,I)``{\<two>} = QuotientGroupRel(R,A,I)``{\<one>\<ra>\<one>}" unfolding ringtwo_def by auto then show "QuotientGroupRel(R,A,I)``{\<two>} = QuotientGroupOp(R, A, I)`\<langle>QuotientGroupRel(R,A,I)``{\<one>}, QuotientGroupRel(R,A,I)``{\<one>}\<rangle>" using EquivClass_1_L10[OF equiv_rel[OF assms] _ Ring_ZF_1_L2(2) Ring_ZF_1_L2(2), of A] Group_ZF_2_4_L5A[of R A I] ringAssum ideal_normal_add_subgroup[OF assms] unfolding IsAring_def QuotientGroupOp_def by auto qed lemma (in ring0) sqrt_quotient: assumes "I\<triangleleft>R" "x\<in>R" shows "QuotientGroupRel(R,A,I)``{x\<^sup>2} = ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>QuotientGroupRel(R,A,I)``{x},QuotientGroupRel(R,A,I)``{x}\<rangle>" proof- have "QuotientGroupRel(R,A,I)``{x\<^sup>2} = QuotientGroupRel(R,A,I)``{x\<cdot>x}" unfolding ringsq_def by auto then show ?thesis using EquivClass_1_L10[OF equiv_rel[OF assms(1)] quotientBy_mul_monoid(1)[OF assms(1)] assms(2,2)] by auto qed text\<open>Both quotient operations are distributive\<close> lemma (in ring0) quotientBy_distributive: assumes "I\<triangleleft>R" shows "IsDistributive(QuotientBy(I),QuotientGroupOp(R, A, I),ProjFun2(R, QuotientGroupRel(R,A,I), M))" proof- { fix x y z assume xyz:"x\<in>QuotientBy(I)" "y\<in>QuotientBy(I)" "z\<in>QuotientBy(I)" then obtain x1 y1 z1 where xyz1:"x1\<in>R" "y1\<in>R" "z1\<in>R" "QuotientGroupRel(R,A,I)``{x1} =x" "QuotientGroupRel(R,A,I)``{y1} =y" "QuotientGroupRel(R,A,I)``{z1} =z" unfolding QuotientBy_def[OF assms] quotient_def by auto have aux:"QuotientGroupOp(R, A, I)`\<langle>y,z\<rangle> = QuotientGroupRel(R,A,I)``{y1\<ra>z1}" using EquivClass_1_L10[OF equiv_rel Group_ZF_2_4_L5A] unfolding QuotientGroupOp_def using assms ringAssum ideal_normal_add_subgroup unfolding IsAring_def using xyz1(2,3,5,6) by auto then have "ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,QuotientGroupOp(R, A, I)`\<langle>y,z\<rangle>\<rangle> = QuotientGroupRel(R,A,I)``{x1\<cdot>(y1\<ra>z1)}" using EquivClass_1_L10[OF equiv_rel quotientBy_mul_monoid(1)] assms xyz1(1-4) Ring_ZF_1_L4(1) by auto moreover have "ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,y\<rangle> = QuotientGroupRel(R,A,I)``{x1\<cdot>y1}" "ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,z\<rangle> = QuotientGroupRel(R,A,I)``{x1\<cdot>z1}" using EquivClass_1_L10[OF equiv_rel quotientBy_mul_monoid(1)] assms xyz1 by auto then have "QuotientGroupOp(R, A, I)`\<langle>ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,y\<rangle>,ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,z\<rangle>\<rangle> = QuotientGroupRel(R,A,I)``{(x1\<cdot>y1)\<ra>(x1\<cdot>z1)}" using EquivClass_1_L10[OF equiv_rel Group_ZF_2_4_L5A] unfolding QuotientGroupOp_def using assms ringAssum ideal_normal_add_subgroup unfolding IsAring_def using Ring_ZF_1_L4(3) xyz1(1-3) by auto then have "QuotientGroupOp(R, A, I)`\<langle>ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,y\<rangle>,ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,z\<rangle>\<rangle> = QuotientGroupRel(R,A,I)``{x1\<cdot>(y1\<ra>z1)}" using ring_oper_distr(1) xyz1 by auto ultimately have A:"ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,QuotientGroupOp(R, A, I)`\<langle>y,z\<rangle>\<rangle> = QuotientGroupOp(R, A, I)`\<langle>ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,y\<rangle>,ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,z\<rangle>\<rangle>" by auto from aux have "ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>QuotientGroupOp(R, A, I)`\<langle>y,z\<rangle>,x\<rangle> = QuotientGroupRel(R,A,I)``{(y1\<ra>z1)\<cdot>x1}" using EquivClass_1_L10[OF equiv_rel quotientBy_mul_monoid(1)] assms xyz1(1-4) Ring_ZF_1_L4(1) by auto moreover have "ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>y,x\<rangle> = QuotientGroupRel(R,A,I)``{y1\<cdot>x1}" "ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>z,x\<rangle> = QuotientGroupRel(R,A,I)``{z1\<cdot>x1}" using EquivClass_1_L10[OF equiv_rel quotientBy_mul_monoid(1)] assms xyz1 by auto then have "QuotientGroupOp(R, A, I)`\<langle>ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>y,x\<rangle>,ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>z,x\<rangle>\<rangle> = QuotientGroupRel(R,A,I)``{(y1\<cdot>x1)\<ra>(z1\<cdot>x1)}" using EquivClass_1_L10[OF equiv_rel Group_ZF_2_4_L5A] unfolding QuotientGroupOp_def using assms ringAssum ideal_normal_add_subgroup unfolding IsAring_def using Ring_ZF_1_L4(3) xyz1(1-3) by auto then have "QuotientGroupOp(R, A, I)`\<langle>ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>y,x\<rangle>,ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>z,x\<rangle>\<rangle> = QuotientGroupRel(R,A,I)``{(y1\<ra>z1)\<cdot>x1}" using ring_oper_distr(2) xyz1 by auto ultimately have B:"ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>QuotientGroupOp(R, A, I)`\<langle>y,z\<rangle>,x\<rangle> = QuotientGroupOp(R, A, I)`\<langle>ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>y,x\<rangle>,ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>z,x\<rangle>\<rangle>" by auto with A have "ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,QuotientGroupOp(R, A, I)`\<langle>y,z\<rangle>\<rangle> = QuotientGroupOp(R, A, I)`\<langle>ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,y\<rangle>,ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>x,z\<rangle>\<rangle>" "ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>QuotientGroupOp(R, A, I)`\<langle>y,z\<rangle>,x\<rangle> = QuotientGroupOp(R, A, I)`\<langle>ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>y,x\<rangle>,ProjFun2(R, QuotientGroupRel(R,A,I), M)`\<langle>z,x\<rangle>\<rangle>" by auto } with IsDistributive_def show "IsDistributive (QuotientBy(I), QuotientGroupOp(R, A, I), ProjFun2(R, QuotientGroupRel(R, A, I), M))" by auto qed text\<open>The quotient group is a ring with the quotient multiplication\<close> theorem (in ring0) quotientBy_is_ring: assumes "I\<triangleleft>R" shows "IsAring(QuotientBy(I), QuotientGroupOp(R, A, I), ProjFun2(R, QuotientGroupRel(R, A, I), M))" unfolding IsAring_def using quotientBy_distributive[OF assms] quotientBy_mul_monoid(2)[OF assms] quotientBy_add_group[OF assms] by auto text\<open>An import property satisfied by many important rings is being Noetherian: every ideal is finitely generated.\<close> definition (in ring0) isFinGen ("_{is finitely generated}") where "I\<triangleleft>R \<Longrightarrow> I{is finitely generated} \<equiv> \<exists>S\<in>FinPow(R). I = \<langle>S\<rangle>\<^sub>I" text\<open>For noetherian rings the arbitrary sum can be reduced to the sum of a finite subset of the initial set of ideals\<close> theorem (in ring0) sum_ideals_noetherian: assumes "\<forall>I\<in>\<I>. (I{is finitely generated})" "\<J> \<subseteq> \<I>" shows "\<exists>\<T>\<in>FinPow(\<J>). (\<oplus>\<^sub>I\<J>) = (\<oplus>\<^sub>I\<T>)" proof- have JR:"(\<oplus>\<^sub>I\<J>)\<triangleleft>R" using generated_ideal_is_ideal[of "\<Union>\<J>"] assms(2) unfolding sumArbitraryIdeals_def[OF assms(2)] by auto with assms(1) have "(\<oplus>\<^sub>I\<J>) {is finitely generated}" using ideal_dest_subset by auto then obtain S where S:"S\<in>FinPow(R)" "(\<oplus>\<^sub>I\<J>) = \<langle>S\<rangle>\<^sub>I" unfolding isFinGen_def[OF JR] by auto from this(1) have fins:"Finite(S)" unfolding FinPow_def by auto then obtain n where n:"n\<in>nat" "S\<approx>n" unfolding Finite_def by auto then have "S\<lesssim>n" using eqpoll_iff by auto moreover let ?N = "\<lambda>s\<in>S. {J\<in>FinPow(\<J>). s\<in>(\<oplus>\<^sub>IJ)}" from n(1) have "{the axiom of} n {choice holds}" using finite_choice by auto ultimately have "(\<forall>t\<in>S. ?N ` t \<noteq> 0) \<longrightarrow> (\<exists>f. f \<in> (\<Prod>t\<in>S. ?N ` t) \<and> (\<forall>t\<in>S. f ` t \<in> ?N ` t))" unfolding AxiomCardinalChoiceGen_def by blast moreover { fix t assume t:"t\<in>S" then have "?N`t = {J\<in>FinPow(\<J>). t\<in>(\<oplus>\<^sub>IJ)}" using lamE by auto moreover from t have "t\<in>\<langle>S\<rangle>\<^sub>I" using generated_ideal_contains_set S(1) unfolding FinPow_def by auto with S(2) have "t\<in>(\<oplus>\<^sub>I\<J>)" by auto ultimately have "?N`t\<noteq>0" using sum_ideals_finite_sum[OF assms(2)] by auto } ultimately obtain f where f:"f:(\<Prod>t\<in>S. ?N ` t)" "\<forall>t\<in>S. f ` t \<in> ?N ` t" by auto { fix y assume "y\<in>f``S" with image_iff obtain x where x:"x\<in>S" "\<langle>x,y\<rangle>\<in>f" by auto with f(1) have "y\<in>?N`x" unfolding Pi_def by auto then have "y:{J\<in>FinPow(\<J>). x\<in>(\<oplus>\<^sub>IJ)}" using x(1) lamE by auto then have "Finite(y)" using lamE unfolding FinPow_def by auto } moreover from f(1) have f_Fun:"f:S\<rightarrow> (\<Union>{?N`t. t:S})" unfolding Pi_def Sigma_def by blast then have "Finite(f``S)" using Finite1_L6A[of f S _ S] Finite_Fin_iff fins Fin_into_Finite by auto ultimately have A:"Finite(\<Union>(f``S))" using Finite_Union by auto { fix t assume "t\<in>\<Union>(f``S)" then obtain q where q:"t\<in>q" "q\<in>f``S" by auto then obtain s where s:"t\<in>f`s" "s\<in>S" using func_imagedef[OF f_Fun] by auto from s(2) have J:"f`s\<in>FinPow(\<J>)" "s\<in>(\<oplus>\<^sub>I(f`s))" using f(2) lamE by auto with s(1) have "t:\<J>" unfolding FinPow_def by auto } with A have B:"(\<Union>(f``S)):FinPow(\<J>)" unfolding FinPow_def by auto then have P:"(\<Union>(f``S)) \<subseteq> \<J>" unfolding FinPow_def by auto then have C:"(\<Union>(f``S)) \<subseteq> \<I>" using assms(2) by auto then have "(\<Union>(f``S)) \<subseteq> Pow(R)" by auto then have sub:"\<Union>(\<Union>(f``S)) \<subseteq> R" by auto { fix t assume t:"t\<in>S" then have J:"f`t\<in>FinPow(\<J>)" "t\<in>(\<oplus>\<^sub>I(f`t))" using f(2) lamE by auto from t have "\<Union>(f`t) \<subseteq> \<Union>(\<Union>(f``S))" using func_imagedef[OF f_Fun] by auto then have "\<Union>(f`t) \<subseteq> \<langle>\<Union>(\<Union>(f``S))\<rangle>\<^sub>I" using generated_ideal_contains_set sub by blast then have "\<langle>\<Union>(f`t)\<rangle>\<^sub>I \<subseteq> \<langle>\<Union>(\<Union>(f``S))\<rangle>\<^sub>I" using generated_ideal_is_ideal[OF sub] generated_ideal_small by auto moreover have "f`t \<subseteq> \<I>" using J(1) assms(2) unfolding FinPow_def by auto moreover note J(2) ultimately have "t\<in>\<langle>\<Union>(\<Union>(f``S))\<rangle>\<^sub>I" using sumArbitraryIdeals_def by auto then have "t\<in>(\<oplus>\<^sub>I(\<Union>(f``S)))" using sumArbitraryIdeals_def C by auto } then have "S \<subseteq> \<oplus>\<^sub>I(\<Union>(f``S))" by auto then have "\<langle>S\<rangle>\<^sub>I \<subseteq> \<oplus>\<^sub>I(\<Union>(f``S))" using generated_ideal_small[ OF _ generated_ideal_is_ideal[OF sub]] sumArbitraryIdeals_def[OF C] by auto with S(2) have "(\<oplus>\<^sub>I\<J>)\<subseteq> \<oplus>\<^sub>I(\<Union>(f `` S))" by auto moreover from P have "\<Union>(\<Union>(f``S)) \<subseteq> \<Union>\<J>" by auto then have "\<Union>(\<Union>(f``S)) \<subseteq>\<langle>\<Union>\<J>\<rangle>\<^sub>I" using generated_ideal_contains_set[of "\<Union>\<J>"] assms(2) by blast then have "\<langle>\<Union>(\<Union>(f``S))\<rangle>\<^sub>I \<subseteq> \<langle>\<Union>\<J>\<rangle>\<^sub>I" using generated_ideal_small[OF _ generated_ideal_is_ideal] assms(2) by blast then have "(\<oplus>\<^sub>I(\<Union>(f `` S))) \<subseteq>(\<oplus>\<^sub>I\<J>)" unfolding sumArbitraryIdeals_def[OF assms(2)] sumArbitraryIdeals_def[OF C]. ultimately have "(\<oplus>\<^sub>I\<J>) = \<oplus>\<^sub>I(\<Union>(f `` S))" by auto with B show ?thesis by auto qed end
function data = read_artinis_oxy55(filename, header, begsample, endsample, chanindx) % reads Artinix oxy55-files into FieldTrip format % % use as % header = read_artinis_oxy5(filename) % or % event = read_artinis_oxy5(filename, read_event) % where read_event is a Boolean with the value true, or % data = read_artinis_oxy55(filename, header, [begsample], [endsample], [chanindx]) % where begsample, endsample and chanindx are optional. % % The returned variables will be in FieldTrip style. % % See also FT_READ_HEADER, FT_READ_DATA, READ_ARTINIS_OXU5 % You are using the FieldTrip NIRS toolbox developed and maintained by % Artinis Medical Systems (http://www.artinis.com). For more information % on FieldTrip, see http://www.fieldtriptoolbox.org % % This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 % International License. To view a copy of this license, visit % http://creativecommons.org/licenses/by-sa/4.0/ or send a letter to % Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. % % Creative Commons Attribution-ShareAlike 4.0 International License: % ----------------------------------- % You are free to: % % Share - copy and redistribute the material in any medium or format % Adapt - remix, transform, and build upon the material % for any purpose, even commercially. % % The licensor cannot revoke these freedoms as long as you follow the % license terms. % % Under the following terms: % % Attribution - You must give appropriate credit, provide a link to % the license, and indicate if changes were made. You % may do so in any reasonable manner, but not in any way % that suggests the licensor endorses you or your use. % % ShareAlike - If you remix, transform, or build upon the material, % you must distribute your contributions under the same % license as the original. % % No additional restrictions - You may not apply legal terms or % technological measures that legally % restrict others from doing anything the % license permits. % % ----------------------------------- % % This toolbox is not to be used for medical or clinical purposes. % % Copyright (c) 2021 by Artinis Medical Systems. % Contact: [email protected] if nargin > 2 && islogical(header) % header must be defined if begsample and endsample are used error('wrong type of header variable.') end if nargin == 1 || nargin == 2 && islogical(header) && ~header data = read_oxy5_header(filename); if isfield(data, 'opto') % ensure that the optode definition is according to the latest standards data.opto = ft_datatype_sens(data.opto); end elseif nargin == 2 && islogical(header) && header data = read_oxy3_event(filename); else % nargin > 1 && ~islogical(header) if nargin < 5 chanindx = 1:header.nChans; if nargin < 4 endsample = header.nSamples; if nargin < 3 begsample = 1; end end end data = read_oxy5_data(filename, 0, header.nSamples); % sample subselection does not work yet if endsample > size(data, 2) warning('Cannot deliver all requested samples, nan''ing %d sample(s)', endsample-size(data, 2)); data(:, end:endsample) = nan; end data = data(chanindx, begsample:endsample); end
\chapter{Experiment preparation} \epigraph{\textit{On est trop souvent imprécis lorsqu'on fait une citation.}}{Quelqu'un, un jour.} Generative part of all experiments \section{Base Z cercle} \begin{lstlisting} def complex_cal(qc, statevector_sim): statevector_job = execute(qc, statevector_sim) statevector_result = statevector_job.result() psi = statevector_result.get_statevector() z0 = psi[0] z1 = psi[1] if z1.real != 0 or z1.imag != 0: z = z0/z1 z = round(z.real, 2) + round(z.imag, 2) * 1j else: z = 0 return z init_q = QuantumRegister(1, 'q') qc_cercle = QuantumCircuit(init_q) tab_cercle = [[], []] x_cercle = [] y_cercle = [] tab_temp = [] z0 = 0+0j z1 = 0+0j z = 0+0j shots = 100 max_shots = 1 qc_cercle.h(init_q) for w in range(max_shots): for i in range(shots): qc_cercle.rz(pi/(shots/8), init_q) z = complex_cal(qc_cercle, statevector_sim) if z != 0: tab_temp.append(z) qc_cercle.barrier() if (w + 1) % 5 == 0: print("Full circuit bloch :", w+1, "/", max_shots) print("Fini!") for i in tab_temp: iteration = tab_temp.count(i) if tab_cercle[0].count(i) < 1: tab_cercle[0].append(i) tab_cercle[1].append(iteration) for i in range(len(tab_cercle[0])): x_cercle.append(tab_cercle[0][i].real) y_cercle.append(tab_cercle[0][i].imag) print("Total of SV :", len(tab_temp)) \end{lstlisting} \section{Generical functions} \subsection{Qubit and variable preparation} \begin{lstlisting} init_q = QuantumRegister(1, 'q') qc = QuantumCircuit(init_q) tab = [[], []] x = [] y = [] x_north = [] y_north = [] x_south = [] y_south = [] tab_temp = [[], [], []] z0 = 0+0j z1 = 0+0j z = 0+0j z_north = 0*0j z_south = 0*0j shots = 100 # Never change -> Concidere it as 1 full circuit max_shots = 100 # Change in fonction of how many full block we want \end{lstlisting} \subsection{Transform spherical plan to 2d plan} \begin{lstlisting} def complex_cal(qc, statevector_sim): statevector_job = execute(qc, statevector_sim) statevector_result = statevector_job.result() psi = statevector_result.get_statevector() z0 = psi[0] z1 = psi[1] if z1.real != 0 or z1.imag != 0: z = z0/z1 z = round(z.real, 2) + round(z.imag, 2) * 1j if np.abs(z0.real) >= 1.0 / np.sqrt(2): z_north = z0/z1 z_north = round(z_north.real, 2) + round(z_north.imag, 2) * 1j z_south = 0 return z, z_north, z_south if np.abs(z0.real) <= 1.0 / np.sqrt(2): z_south = z0/z1 z_south = round(z_south.real, 2) + round(z_south.imag, 2) * 1j z_north = 0 return z, z_north, z_south else: z = 0 z_north = 0 z_south = 0 return z, z_north, z_south \end{lstlisting} \subsection{Data analyse for plan} \begin{lstlisting} for i in tab_temp[0]: iteration = tab_temp[0].count(i) if tab[0].count(i) < 1: tab[0].append(i) tab[1].append(iteration) # the whole world for i in range(len(tab[0])): x.append(tab[0][i].real) y.append(tab[0][i].imag) # northern hemisphere for i in range(len(tab_temp[1])): x_north.append(tab_temp[1][i].real) y_north.append(tab_temp[1][i].imag) # southern hemisphere for i in range(len(tab_temp[2])): x_south.append(tab_temp[2][i].real) y_south.append(tab_temp[2][i].imag) print("Total of SV :", len(tab_temp[0])) \end{lstlisting} \section{Graph} \begin{lstlisting} plt.scatter(x_cercle, y_cercle, c=tab_cercle[1], s=1, cmap="coolwarm") plt.scatter(x, y, c=tab[1], s=1, cmap="coolwarm") plt.colorbar() print("Number of different value : ", len(x)) \end{lstlisting} \begin{lstlisting} print("The whole world !") gen_tab = [[], [], []] zoom_in = 4 for i in range(len(x)): if (x[i] > -1.05 and x[i] < 2) and (y[i] > -1.05 and y[i] < 1.05): gen_tab[0].append(x[i]) gen_tab[1].append(y[i]) gen_tab[2].append(tab[1][i]) #plt.scatter(x_cercle, y_cercle, c=tab_cercle[1], s=2, cmap="coolwarm") plt.scatter(gen_tab[0], gen_tab[1], c=gen_tab[2], s=2, cmap="coolwarm") #plt.colorbar() print("Number of different values in zoom : ", len(gen_tab[0]), "/", len(x)) \end{lstlisting}
#include "mLibInclude.h" #include "../../shared/OptUtils.h" #define GLOG_NO_ABBREVIATED_SEVERITIES #include <Eigen33b1/Eigen> #include <Eigen33b1/IterativeLinearSolvers> #include <cuda_runtime.h> #include <time.h> #define LEAST_SQ_CONJ_GRADIENT 0 #define SPARSE_QR 1 #define SOLVER LEAST_SQ_CONJ_GRADIENT typedef Eigen::Triplet<float> Tripf; typedef Eigen::SparseMatrix<float> SpMatrixf; #include "EigenSolverPoissonImageEditing.h" #include <Eigen33b1/OrderingMethods> #if SOLVER == LEAST_SQ_CONJ_GRADIENT typedef Eigen::LeastSquaresConjugateGradient<SpMatrixf > AxEqBSolver; #elif SOLVER == SPARSE_QR typedef Eigen::SparseQR<SpMatrixf, Eigen::COLAMDOrdering<int> > AxEqBSolver; #endif struct vec2iHash { size_t operator()(const vec2i& v) const { return std::hash < int > {}(v.x) ^ std::hash < int > {}(v.y); } }; float4 sampleImage(float4* image, vec2i p, int W) { return image[p.y*W + p.x]; } void setPixel(float4* image, vec2i p, int W, float r, float g, float b) { image[p.y*W + p.x].x = r; image[p.y*W + p.x].y = g; image[p.y*W + p.x].z = b; } void solveAxEqb(AxEqBSolver& solver, const Eigen::VectorXf& b, Eigen::VectorXf& x) { #if SOLVER==LEAST_SQ_CONJ_GRADIENT x = solver.solveWithGuess(b, x); //std::cout << "#iterations: " << solver.iterations() << std::endl; //std::cout << "estimated error: " << solver.error() << std::endl; #else x = solver.solve(b); #endif } double EigenSolverPoissonImageEditing::solve(const NamedParameters& solverParameters, const NamedParameters& problemParameters, bool profileSolve, std::vector<SolverIteration>& iters) { int numUnknowns = 0; std::unordered_map<vec2i, int, vec2iHash> pixelLocationsToIndex; std::vector<vec2i> pixelLocations; size_t pixelCount = m_dims[0] * m_dims[1]; std::vector<float4> h_unknownFloat(pixelCount); std::vector<float4> h_target(pixelCount); std::vector<float> h_mask(pixelCount); findAndCopyArrayToCPU("X", h_unknownFloat, problemParameters); findAndCopyArrayToCPU("T", h_target, problemParameters); findAndCopyArrayToCPU("M", h_mask, problemParameters); for (int y = 0; y < (int)m_dims[1]; ++y) { for (int x = 0; x < (int)m_dims[0]; ++x) { if (h_mask[y*m_dims[0] + x] == 0.0f) { ++numUnknowns; vec2i p(x, y); pixelLocationsToIndex[p] =(int)pixelLocations.size(); pixelLocations.push_back(p); } } } printf("# Unknowns: %d\n", numUnknowns); int numResiduals = (int)pixelLocations.size() * 4; Eigen::VectorXf x_r(numUnknowns), b_r(numResiduals); Eigen::VectorXf x_g(numUnknowns), b_g(numResiduals); Eigen::VectorXf x_b(numUnknowns), b_b(numResiduals); Eigen::VectorXf x_a(numUnknowns), b_a(numResiduals); b_r.setZero(); b_g.setZero(); b_b.setZero(); b_a.setZero(); for (int i = 0; i < pixelLocations.size(); ++i) { vec2i p = pixelLocations[i]; float4 color = sampleImage(h_unknownFloat.data(), p, m_dims[0]); x_r[i] = color.x; //printf("%f\n", color.x); x_g[i] = color.y; x_b[i] = color.z; x_a[i] = color.w; } SpMatrixf A(numResiduals, numUnknowns); A.setZero(); printf("Constructing Matrix\n"); std::vector<Tripf> entriesA; std::vector<vec2i> offsets; offsets.push_back(vec2i(-1, 0)); offsets.push_back(vec2i(1, 0)); offsets.push_back(vec2i(0, -1)); offsets.push_back(vec2i(0, 1)); for (int i = 0; i < pixelLocations.size(); ++i) { vec2i p = pixelLocations[i]; int numInternalNeighbors = 0; float4 g_p = sampleImage(h_target.data(), p, m_dims[0]); int j = 0; for (vec2i off : offsets) { vec2i q = p + off; if (q.x >= 0 && q.y >= 0 && q.x < (int)m_dims[0] && q.y < (int)m_dims[1]) { auto it = pixelLocationsToIndex.find(q); int row = 4 * i + j; if (it == pixelLocationsToIndex.end()) { float4 f_q = sampleImage(h_unknownFloat.data(), q, m_dims[0]); b_r[row] += f_q.x; b_g[row] += f_q.y; b_b[row] += f_q.z; b_a[row] += f_q.w; } else { entriesA.push_back(Tripf(row, it->second, -1.0f)); } entriesA.push_back(Tripf(row, i, 1.0f)); float4 g_q = sampleImage(h_target.data(), q, m_dims[0]); b_r[row] += (g_p.x - g_q.x); b_g[row] += (g_p.y - g_q.y); b_b[row] += (g_p.z - g_q.z); b_a[row] += (g_p.w - g_q.w); } ++j; } } printf("Entries Set\n"); A.setFromTriplets(entriesA.begin(), entriesA.end()); printf("Sparse Matrix Constructed\n"); A.makeCompressed(); printf("Matrix Compressed\n"); { float totalCost = 0.0f; float cost_r = (A*x_r - b_r).squaredNorm(); float cost_g = (A*x_g - b_g).squaredNorm(); float cost_b = (A*x_b - b_b).squaredNorm(); float cost_a = (A*x_a - b_a).squaredNorm(); totalCost = cost_r + cost_g + cost_b + cost_a; printf("Initial Cost: %f : (%f, %f, %f, %f)\n", totalCost, cost_r, cost_g, cost_b, cost_a); } AxEqBSolver solver; solver.setMaxIterations(97); printf("Solvers Initialized\n"); clock_t start = clock(), diff; solver.compute(A); //printf("solver.compute(A)\n"); solveAxEqb(solver, b_r, x_r); //printf("Red solve done\n"); solveAxEqb(solver, b_g, x_g); //printf("Green solve done\n"); solveAxEqb(solver, b_b, x_b); //printf("Blue solve done\n"); solveAxEqb(solver, b_a, x_a); diff = clock() - start; printf("Time taken %f ms\n", diff*1000.0 / double(CLOCKS_PER_SEC)); float totalCost = 0.0f; float cost_r = (A*x_r - b_r).squaredNorm(); float cost_g = (A*x_g - b_g).squaredNorm(); float cost_b = (A*x_b - b_b).squaredNorm(); float cost_a = (A*x_a - b_a).squaredNorm(); totalCost = cost_r + cost_g + cost_b + cost_a; printf("Final Cost: %f : (%f, %f, %f, %f)\n", totalCost, cost_r, cost_g, cost_b, cost_a); for (int i = 0; i < pixelLocations.size(); ++i) { setPixel(h_unknownFloat.data(), pixelLocations[i], m_dims[0], x_r[i], x_g[i], x_b[i]); } findAndCopyToArrayFromCPU("X", h_unknownFloat, problemParameters);; return (double)totalCost; } /* Proper Poisson Image Editing for (int i = 0; i < pixelLocations.size(); ++i) { vec2i p = pixelLocations[i]; int row = i; int numInternalNeighbors = 0; float4 g_p = sampleImage(h_target, p, m_width); for (int off_y = -1; off_y <= 1; off_y += 2) { for (int off_x = -1; off_x <= 1; off_x += 2) { vec2i q(p.x + off_x, p.y + off_y); auto it = pixelLocationsToIndex.find(q); if (it != pixelLocationsToIndex.end()) { ++numInternalNeighbors; entriesA.push_back(Tripf(row, it->second, -1.0f)); } else { float4 f_star_q = sampleImage(h_target, q, m_width); b_r[i] += f_star_q.x; b_g[i] += f_star_q.y; b_b[i] += f_star_q.z; } float4 g_q = sampleImage(h_target, q, m_width); b_r[i] += (g_p.x - g_q.x); b_g[i] += (g_p.y - g_q.y); b_b[i] += (g_p.z - g_q.z); } } entriesA.push_back(Tripf(row, row, (float)numInternalNeighbors)); } */
[GOAL] α : Type u_1 β : Type ?u.2132 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α hs : MeasurableSet s ⊢ ↑↑count s = ∑' (i : ↑s), 1 [PROOFSTEP] simp only [count, sum_apply, hs, dirac_apply', ← tsum_subtype s (1 : α → ℝ≥0∞), Pi.one_apply] [GOAL] α : Type u_1 β : Type ?u.3143 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α ⊢ ↑↑count ∅ = 0 [PROOFSTEP] rw [count_apply MeasurableSet.empty, tsum_empty] [GOAL] α : Type u_1 β : Type ?u.3931 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s✝ : Set α s : Finset α s_mble : MeasurableSet ↑s ⊢ ∑ i in s, 1 = ↑(Finset.card s) [PROOFSTEP] simp [GOAL] α : Type u_1 β : Type ?u.7325 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s✝ s : Set α s_fin : Set.Finite s s_mble : MeasurableSet s ⊢ ↑↑count s = ↑(Finset.card (Finite.toFinset s_fin)) [PROOFSTEP] simp [← @count_apply_finset' _ _ s_fin.toFinset (by simpa only [Finite.coe_toFinset] using s_mble)] [GOAL] α : Type u_1 β : Type ?u.7325 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s✝ s : Set α s_fin : Set.Finite s s_mble : MeasurableSet s ⊢ MeasurableSet ↑(Finite.toFinset s_fin) [PROOFSTEP] simpa only [Finite.coe_toFinset] using s_mble [GOAL] α : Type u_1 β : Type ?u.8457 inst✝² : MeasurableSpace α inst✝¹ : MeasurableSpace β s✝ : Set α inst✝ : MeasurableSingletonClass α s : Set α hs : Set.Finite s ⊢ ↑↑count s = ↑(Finset.card (Finite.toFinset hs)) [PROOFSTEP] rw [← count_apply_finset, Finite.coe_toFinset] [GOAL] α : Type u_1 β : Type ?u.8764 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α hs : Set.Infinite s ⊢ ↑↑count s = ⊤ [PROOFSTEP] refine' top_unique (le_of_tendsto' ENNReal.tendsto_nat_nhds_top fun n => _) [GOAL] α : Type u_1 β : Type ?u.8764 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α hs : Set.Infinite s n : ℕ ⊢ ↑n ≤ ↑↑count s [PROOFSTEP] rcases hs.exists_subset_card_eq n with ⟨t, ht, rfl⟩ [GOAL] case intro.intro α : Type u_1 β : Type ?u.8764 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α hs : Set.Infinite s t : Finset α ht : ↑t ⊆ s ⊢ ↑(Finset.card t) ≤ ↑↑count s [PROOFSTEP] calc (t.card : ℝ≥0∞) = ∑ i in t, 1 := by simp _ = ∑' i : (t : Set α), 1 := (t.tsum_subtype 1).symm _ ≤ count (t : Set α) := le_count_apply _ ≤ count s := measure_mono ht [GOAL] α : Type u_1 β : Type ?u.8764 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α hs : Set.Infinite s t : Finset α ht : ↑t ⊆ s ⊢ ↑(Finset.card t) = ∑ i in t, 1 [PROOFSTEP] simp [GOAL] α : Type u_1 β : Type ?u.12614 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α s_mble : MeasurableSet s ⊢ ↑↑count s = ⊤ ↔ Set.Infinite s [PROOFSTEP] by_cases hs : s.Finite [GOAL] case pos α : Type u_1 β : Type ?u.12614 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α s_mble : MeasurableSet s hs : Set.Finite s ⊢ ↑↑count s = ⊤ ↔ Set.Infinite s [PROOFSTEP] simp [Set.Infinite, hs, count_apply_finite' hs s_mble] [GOAL] case neg α : Type u_1 β : Type ?u.12614 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α s_mble : MeasurableSet s hs : ¬Set.Finite s ⊢ ↑↑count s = ⊤ ↔ Set.Infinite s [PROOFSTEP] change s.Infinite at hs [GOAL] case neg α : Type u_1 β : Type ?u.12614 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α s_mble : MeasurableSet s hs : Set.Infinite s ⊢ ↑↑count s = ⊤ ↔ Set.Infinite s [PROOFSTEP] simp [hs, count_apply_infinite] [GOAL] α : Type u_1 β : Type ?u.13909 inst✝² : MeasurableSpace α inst✝¹ : MeasurableSpace β s : Set α inst✝ : MeasurableSingletonClass α ⊢ ↑↑count s = ⊤ ↔ Set.Infinite s [PROOFSTEP] by_cases hs : s.Finite [GOAL] case pos α : Type u_1 β : Type ?u.13909 inst✝² : MeasurableSpace α inst✝¹ : MeasurableSpace β s : Set α inst✝ : MeasurableSingletonClass α hs : Set.Finite s ⊢ ↑↑count s = ⊤ ↔ Set.Infinite s [PROOFSTEP] exact count_apply_eq_top' hs.measurableSet [GOAL] case neg α : Type u_1 β : Type ?u.13909 inst✝² : MeasurableSpace α inst✝¹ : MeasurableSpace β s : Set α inst✝ : MeasurableSingletonClass α hs : ¬Set.Finite s ⊢ ↑↑count s = ⊤ ↔ Set.Infinite s [PROOFSTEP] change s.Infinite at hs [GOAL] case neg α : Type u_1 β : Type ?u.13909 inst✝² : MeasurableSpace α inst✝¹ : MeasurableSpace β s : Set α inst✝ : MeasurableSingletonClass α hs : Set.Infinite s ⊢ ↑↑count s = ⊤ ↔ Set.Infinite s [PROOFSTEP] simp [hs, count_apply_infinite] [GOAL] α : Type u_1 β : Type ?u.16312 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α s_mble : MeasurableSet s hsc : ↑↑count s = 0 ⊢ s = ∅ [PROOFSTEP] have hs : s.Finite := by rw [← count_apply_lt_top' s_mble, hsc] exact WithTop.zero_lt_top [GOAL] α : Type u_1 β : Type ?u.16312 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α s_mble : MeasurableSet s hsc : ↑↑count s = 0 ⊢ Set.Finite s [PROOFSTEP] rw [← count_apply_lt_top' s_mble, hsc] [GOAL] α : Type u_1 β : Type ?u.16312 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α s_mble : MeasurableSet s hsc : ↑↑count s = 0 ⊢ 0 < ⊤ [PROOFSTEP] exact WithTop.zero_lt_top [GOAL] α : Type u_1 β : Type ?u.16312 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α s_mble : MeasurableSet s hsc : ↑↑count s = 0 hs : Set.Finite s ⊢ s = ∅ [PROOFSTEP] simpa [count_apply_finite' hs s_mble] using hsc [GOAL] α : Type u_1 β : Type ?u.17964 inst✝² : MeasurableSpace α inst✝¹ : MeasurableSpace β s : Set α inst✝ : MeasurableSingletonClass α hsc : ↑↑count s = 0 ⊢ s = ∅ [PROOFSTEP] have hs : s.Finite := by rw [← count_apply_lt_top, hsc] exact WithTop.zero_lt_top [GOAL] α : Type u_1 β : Type ?u.17964 inst✝² : MeasurableSpace α inst✝¹ : MeasurableSpace β s : Set α inst✝ : MeasurableSingletonClass α hsc : ↑↑count s = 0 ⊢ Set.Finite s [PROOFSTEP] rw [← count_apply_lt_top, hsc] [GOAL] α : Type u_1 β : Type ?u.17964 inst✝² : MeasurableSpace α inst✝¹ : MeasurableSpace β s : Set α inst✝ : MeasurableSingletonClass α hsc : ↑↑count s = 0 ⊢ 0 < ⊤ [PROOFSTEP] exact WithTop.zero_lt_top [GOAL] α : Type u_1 β : Type ?u.17964 inst✝² : MeasurableSpace α inst✝¹ : MeasurableSpace β s : Set α inst✝ : MeasurableSingletonClass α hsc : ↑↑count s = 0 hs : Set.Finite s ⊢ s = ∅ [PROOFSTEP] simpa [count_apply_finite _ hs] using hsc [GOAL] α : Type u_1 β : Type ?u.20387 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α hs' : Set.Nonempty s s_mble : MeasurableSet s ⊢ ↑↑count s ≠ 0 [PROOFSTEP] rw [Ne.def, count_eq_zero_iff' s_mble] [GOAL] α : Type u_1 β : Type ?u.20387 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α hs' : Set.Nonempty s s_mble : MeasurableSet s ⊢ ¬s = ∅ [PROOFSTEP] exact hs'.ne_empty [GOAL] α : Type u_1 β : Type ?u.20618 inst✝² : MeasurableSpace α inst✝¹ : MeasurableSpace β s : Set α inst✝ : MeasurableSingletonClass α hs' : Set.Nonempty s ⊢ ↑↑count s ≠ 0 [PROOFSTEP] rw [Ne.def, count_eq_zero_iff] [GOAL] α : Type u_1 β : Type ?u.20618 inst✝² : MeasurableSpace α inst✝¹ : MeasurableSpace β s : Set α inst✝ : MeasurableSingletonClass α hs' : Set.Nonempty s ⊢ ¬s = ∅ [PROOFSTEP] exact hs'.ne_empty [GOAL] α : Type u_1 β : Type ?u.20894 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α a : α ha : MeasurableSet {a} ⊢ ↑↑count {a} = 1 [PROOFSTEP] rw [count_apply_finite' (Set.finite_singleton a) ha, Set.Finite.toFinset] [GOAL] α : Type u_1 β : Type ?u.20894 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s : Set α a : α ha : MeasurableSet {a} ⊢ ↑(Finset.card (toFinset {a})) = 1 [PROOFSTEP] simp [@toFinset_card _ _ (Set.finite_singleton a).fintype, @Fintype.card_unique _ _ (Set.finite_singleton a).fintype] [GOAL] α : Type u_2 β : Type u_1 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s✝ : Set α f : β → α hf : Function.Injective f s : Set β s_mble : MeasurableSet s fs_mble : MeasurableSet (f '' s) ⊢ ↑↑count (f '' s) = ↑↑count s [PROOFSTEP] by_cases hs : s.Finite [GOAL] case pos α : Type u_2 β : Type u_1 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s✝ : Set α f : β → α hf : Function.Injective f s : Set β s_mble : MeasurableSet s fs_mble : MeasurableSet (f '' s) hs : Set.Finite s ⊢ ↑↑count (f '' s) = ↑↑count s [PROOFSTEP] lift s to Finset β using hs [GOAL] case pos.intro α : Type u_2 β : Type u_1 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s✝ : Set α f : β → α hf : Function.Injective f s : Finset β s_mble : MeasurableSet ↑s fs_mble : MeasurableSet (f '' ↑s) ⊢ ↑↑count (f '' ↑s) = ↑↑count ↑s [PROOFSTEP] rw [← Finset.coe_image, count_apply_finset' _, count_apply_finset' s_mble, s.card_image_of_injective hf] [GOAL] α : Type u_2 β : Type u_1 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s✝ : Set α f : β → α hf : Function.Injective f s : Finset β s_mble : MeasurableSet ↑s fs_mble : MeasurableSet (f '' ↑s) ⊢ MeasurableSet ↑(Finset.image f s) [PROOFSTEP] simpa only [Finset.coe_image] using fs_mble [GOAL] case neg α : Type u_2 β : Type u_1 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s✝ : Set α f : β → α hf : Function.Injective f s : Set β s_mble : MeasurableSet s fs_mble : MeasurableSet (f '' s) hs : ¬Set.Finite s ⊢ ↑↑count (f '' s) = ↑↑count s [PROOFSTEP] rw [count_apply_infinite hs] [GOAL] case neg α : Type u_2 β : Type u_1 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s✝ : Set α f : β → α hf : Function.Injective f s : Set β s_mble : MeasurableSet s fs_mble : MeasurableSet (f '' s) hs : ¬Set.Finite s ⊢ ↑↑count (f '' s) = ⊤ [PROOFSTEP] rw [← finite_image_iff <| hf.injOn _] at hs [GOAL] case neg α : Type u_2 β : Type u_1 inst✝¹ : MeasurableSpace α inst✝ : MeasurableSpace β s✝ : Set α f : β → α hf : Function.Injective f s : Set β s_mble : MeasurableSet s fs_mble : MeasurableSet (f '' s) hs : ¬Set.Finite (f '' s) ⊢ ↑↑count (f '' s) = ⊤ [PROOFSTEP] rw [count_apply_infinite hs] [GOAL] α : Type u_1 β : Type u_2 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β s✝ : Set α inst✝¹ : MeasurableSingletonClass α inst✝ : MeasurableSingletonClass β f : β → α hf : Function.Injective f s : Set β ⊢ ↑↑count (f '' s) = ↑↑count s [PROOFSTEP] by_cases hs : s.Finite [GOAL] case pos α : Type u_1 β : Type u_2 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β s✝ : Set α inst✝¹ : MeasurableSingletonClass α inst✝ : MeasurableSingletonClass β f : β → α hf : Function.Injective f s : Set β hs : Set.Finite s ⊢ ↑↑count (f '' s) = ↑↑count s [PROOFSTEP] exact count_injective_image' hf hs.measurableSet (Finite.image f hs).measurableSet [GOAL] case neg α : Type u_1 β : Type u_2 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β s✝ : Set α inst✝¹ : MeasurableSingletonClass α inst✝ : MeasurableSingletonClass β f : β → α hf : Function.Injective f s : Set β hs : ¬Set.Finite s ⊢ ↑↑count (f '' s) = ↑↑count s [PROOFSTEP] rw [count_apply_infinite hs] [GOAL] case neg α : Type u_1 β : Type u_2 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β s✝ : Set α inst✝¹ : MeasurableSingletonClass α inst✝ : MeasurableSingletonClass β f : β → α hf : Function.Injective f s : Set β hs : ¬Set.Finite s ⊢ ↑↑count (f '' s) = ⊤ [PROOFSTEP] rw [← finite_image_iff <| hf.injOn _] at hs [GOAL] case neg α : Type u_1 β : Type u_2 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β s✝ : Set α inst✝¹ : MeasurableSingletonClass α inst✝ : MeasurableSingletonClass β f : β → α hf : Function.Injective f s : Set β hs : ¬Set.Finite (f '' s) ⊢ ↑↑count (f '' s) = ⊤ [PROOFSTEP] rw [count_apply_infinite hs] [GOAL] α : Type ?u.24262 β : Type ?u.24265 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β s : Set α inst✝¹ : Finite α inst✝ : MeasurableSpace α ⊢ ↑↑count univ < ⊤ [PROOFSTEP] cases nonempty_fintype α [GOAL] case intro α : Type ?u.24262 β : Type ?u.24265 inst✝³ : MeasurableSpace α inst✝² : MeasurableSpace β s : Set α inst✝¹ : Finite α inst✝ : MeasurableSpace α val✝ : Fintype α ⊢ ↑↑count univ < ⊤ [PROOFSTEP] simpa [Measure.count_apply, tsum_fintype] using (ENNReal.nat_ne_top _).lt_top
Formal statement is: lemma tendsto_Lim: "\<not> trivial_limit net \<Longrightarrow> (f \<longlongrightarrow> l) net \<Longrightarrow> Lim net f = l" Informal statement is: If a net has a non-trivial limit, then the limit of the net is equal to the limit of the function.
# Numerical Solution of the Helmholtz Equation with Robin Boundary Conditions using the Finite Element Method This notebook illustrates the numerical solution of the wave equation for an harmonic excitation and Robin boundary conditions using the [Finite Element Method](https://en.wikipedia.org/wiki/Finite_element_method) (FEM). The method aims at an approximate solution by subdividing the area of interest into smaller parts with simpler geometry, linking these parts together and applying methods from the calculus of variations to solve the problem numerically. The FEM is a well established method for the numerical approximation of the solution of partial differential equations (PDEs). The solutions of PDEs are often known analytically only for rather simple geometries. FEM based simulations allow to gain insights into other more complex cases. ## Problem Statement The inhomogeneous [Helmholtz equation](https://en.wikipedia.org/wiki/Helmholtz_equation) is given as \begin{equation} \Delta P(\mathbf{x}, \omega) + \frac{\omega^2}{c^2} P(\mathbf{x}, \omega) = - Q(\mathbf{x}, \omega) . \end{equation} We aim for a numerical solution of the Helmholtz equation on the domain $V$ with respect to the homogeneous Robin boundary condition \begin{equation} V_n(\mathbf{x}, \omega) + \frac{1}{Z(\mathbf{x}, \omega)} P(\mathbf{x}, \omega) = 0 \qquad \text{for } x \in \partial V , \end{equation} where $V_n(\mathbf{x}, \omega)$ denotes the particle velocity in inward normal direction to the boundary $\partial V$ of $V$ and $Z(\mathbf{x}, \omega)$ the acoustic impedance of the boundary. The particle velocity can be linked to the pressure using the Euler equation \begin{equation} -\mathrm{j} \omega \rho_0 V_n(\mathbf{x}, \omega) = \frac{\partial}{\partial n} P(\mathbf{x}, \omega) , \end{equation} where $\rho_0$ denotes the static density of air. Introducing this into the Robin boundary equation above yields \begin{equation} \frac{\partial}{\partial n} P(\mathbf{x}, \omega) - \mathrm{j} \underbrace{\frac{\omega \rho_0}{Z}}_{\sigma} P(\mathbf{x}, \omega) = 0 \qquad \text{for } x \in \partial V . \end{equation} The medium impedance of air for free-field propagation is $Z_0 = \rho_0 c$, hence $\sigma_0 = \frac{\omega}{c}$ in this case. Free-field conditions can be simulated by matching the impedance of the boundary to $Z_0$. ## Variational Formulation Starting from the [variational formulation of the Helmholtz equation](FEM_Helmholtz_equation_2D.ipynb#Variational-Formulation) (before application of Green's first theorem) \begin{equation} {-} \int_V \nabla P(\mathbf{x}, \omega) \cdot \nabla V(\mathbf{x}, \omega) \mathrm{d}x + \int_{\partial V} V(\mathbf{x}, \omega) \frac{\partial}{\partial n} P(\mathbf{x}, \omega) \mathrm{d}s + \frac{\omega^2}{c^2} \int_V P(\mathbf{x}, \omega) V(\mathbf{x}, \omega) \mathrm{d}x = -\int_V Q(\mathbf{x}, \omega) V(\mathbf{x}, \omega) \mathrm{d}x \end{equation} and introducing the Robin boundary condition into the second integral yields \begin{equation} {-} \int_V \nabla P(\mathbf{x}, \omega) \cdot \nabla V(\mathbf{x}, \omega) \mathrm{d}x + \mathrm{j} \sigma \int_{\partial V} V(\mathbf{x}, \omega) P(\mathbf{x}, \omega) \mathrm{d}s + \frac{\omega^2}{c^2} \int_V P(\mathbf{x}, \omega) V(\mathbf{x}, \omega) \mathrm{d}x = -\int_V Q(\mathbf{x}, \omega) V(\mathbf{x}, \omega) \mathrm{d}x . \end{equation} It is common to express this integral equation in terms of the bilinear $a(P, V)$ and linear $L(V)$ forms \begin{equation} a(P, V) = \frac{\omega^2}{c^2} \int_V P(\mathbf{x}, \omega) V(\mathbf{x}, \omega) \mathrm{d}x - \int_V \nabla P(\mathbf{x}, \omega) \cdot \nabla V(\mathbf{x}, \omega) \mathrm{d}x + \mathrm{j} \sigma \int_{\partial V} V(\mathbf{x}, \omega) P(\mathbf{x}, \omega) \mathrm{d}s , \end{equation} \begin{equation} L(V) = -\int_V Q(\mathbf{x}, \omega) V(\mathbf{x}, \omega) \mathrm{d}x , \end{equation} where \begin{equation} a(P, V) = L(V) . \end{equation} Computational implementations of the FEM (like FEniCS) may not be able to handle complex numbers. In this case the problem can be split into two coupled problems with respect to the real and imaginary part. By introducing $P(\mathbf{x}, \omega) = P_r(\mathbf{x}, \omega) + \mathrm{j} P_i(\mathbf{x}, \omega)$ and $V(\mathbf{x}, \omega) = V_r(\mathbf{x}, \omega) + \mathrm{j} V_i(\mathbf{x}, \omega)$ and identifying the real and imaginary parts of the bilinear and linear forms, we get \begin{equation} a_r = \int_V \left( \frac{\omega^2}{c^2} V_r(\mathbf{x}, \omega) P_r(\mathbf{x}, \omega) - \frac{\omega^2}{c^2} V_i(\mathbf{x}, \omega) P_i(\mathbf{x}, \omega) - \nabla P_r(\mathbf{x}, \omega) \cdot \nabla V_r(\mathbf{x}, \omega) + \nabla P_i(\mathbf{x}, \omega) \cdot \nabla V_i(\mathbf{x}, \omega) \right) \mathrm{d}x - \sigma \cdot \int_{\partial V} \left( V_i(\mathbf{x}, \omega) P_r(\mathbf{x}, \omega) + V_r(\mathbf{x}, \omega) P_i(\mathbf{x}, \omega) \right) \mathrm{d}s, \end{equation} \begin{equation} a_i = \int_V \left( \frac{\omega^2}{c^2} V_r(\mathbf{x}, \omega) P_i(\mathbf{x}, \omega) + \frac{\omega^2}{c^2} V_i(\mathbf{x}, \omega) P_r(\mathbf{x}, \omega) - \nabla P_i(\mathbf{x}, \omega) \cdot \nabla V_r(\mathbf{x}, \omega) + \nabla P_r(\mathbf{x}, \omega) \cdot \nabla V_i(\mathbf{x}, \omega) \right) \mathrm{d}x + \sigma \cdot \int_{\partial V} \left( V_r(\mathbf{x}, \omega) P_r(\mathbf{x}, \omega) - V_i(\mathbf{x}, \omega) P_i(\mathbf{x}, \omega) \right) \mathrm{d}s \end{equation} for the bilinear form. ## Numerical Solution The numerical solution of the variational problem is based on [FEniCS](https://fenicsproject.org/), an open-source framework for numerical solution of PDEs. Its high-level Python interface `dolfin` is used in the following to define the problem and compute the solution. The implementation is based on the variational formulation derived above. It is common in the FEM to denote the solution of the problem by $u$ and the test function by $v$. The definition of the problem in FEniCS is very close to the mathematical formulation of the problem. For the subsequent examples the solution of inhomogeneous wave equation for a point source $Q(\mathbf{x}) = \delta(\mathbf{x}-\mathbf{x_s})$ at position $\mathbf{x_s}$ is computed using the FEM. A function is defined for this purpose, as well as for the plotting of the resulting sound field. ```python import dolfin import mshr import matplotlib.pyplot as plt %matplotlib inline def Helmholtz_Robin(mesh, frequency, xs, sigma=dolfin.Constant(0), c=343): # squared wavenumber k2 = dolfin.Constant(2*dolfin.pi*frequency/c)**2 # define function space V = dolfin.VectorFunctionSpace(mesh, "CG", 1, dim=2) # define variational problem (u_r, u_i) = dolfin.TrialFunction(V) (v_r, v_i) = dolfin.TestFunction(V) a_r = ( k2 * dolfin.inner(u_r,v_r) - k2 * dolfin.inner(u_i,v_i) - dolfin.inner(dolfin.grad(u_r), dolfin.grad(v_r)) + dolfin.inner(dolfin.grad(u_i), dolfin.grad(v_i)) ) * dolfin.dx - sigma*dolfin.inner(u_r, v_i) * dolfin.ds - sigma*dolfin.inner(u_i, v_r) * dolfin.ds a_i = ( k2 * dolfin.inner(u_r,v_i) + k2 * dolfin.inner(u_i,v_r) - dolfin.inner(dolfin.grad(u_r), dolfin.grad(v_i)) - dolfin.inner(dolfin.grad(u_i), dolfin.grad(v_r)) ) * dolfin.dx + sigma*dolfin.inner(u_r, v_r) * dolfin.ds - sigma*dolfin.inner(u_i, v_i) * dolfin.ds L_r = dolfin.Constant(0) * v_r * dolfin.dx L_i = dolfin.Constant(0) * v_i * dolfin.dx a = a_r + a_i L = L_r + L_i A, b = dolfin.assemble_system(a, L) # define inhomogenity delta = dolfin.PointSource(V.sub(0), xs, -1) # negative amplitude accounts for -Q(x,w) in inhomogeneous wave equation delta.apply(b) # compute solution u = dolfin.Function(V) dolfin.solve(A, u.vector(), b) (u_r, u_i) = dolfin.split(u) return u_r def plot_soundfield(u): '''plots solution of FEM-based simulation''' fig = plt.figure(figsize=(10,10)) fig = dolfin.plot(u) plt.title(r'$P(\mathbf{x}, \omega)$') plt.xlabel(r'$x$ in m') plt.ylabel(r'$y$ in m') plt.colorbar(fig, fraction=0.038, pad=0.04); ``` ### Sound Field in a Rectangular Room The two-dimensional sound field in a rectangular room (rectangular plate) with homogeneous Robin boundary conditions is computed for the frequency $f=1000$ Hz and source position $x_s = (1.2,3.2)$ m. ```python f = 1000 # frequency xs = dolfin.Point(1.2, 3.2) # source position # define geometry and mesh mesh = dolfin.RectangleMesh(dolfin.Point(0, 0), dolfin.Point(5, 4), 200, 200, "right/left") ``` First, the case of sound-hard (Neumann) boundary conditions with $\sigma = 0$ ($Z \to \infty$) is considered. ```python # compute solution for sigma=0 u = Helmholtz_Robin(mesh, f, xs, sigma=dolfin.Constant(0)) # plot sound field plot_soundfield(u) plot_soundfield(abs(u)) plt.title(r'$|P(\mathbf{x}, \omega)|$'); ``` Now the case of a matched boundary (free-field propagation) with $\sigma = \frac{\omega}{c}$ ($Z = Z_0$) is considered. ```python # compute solution for free-field propogation u = Helmholtz_Robin(mesh, f, xs, sigma=dolfin.Constant(2*dolfin.pi*f/343)) # plot sound field plot_soundfield(u) plot_soundfield(abs(u)) plt.title(r'$|P(\mathbf{x}, \omega)|$'); ``` The last example shows the simulation result for sound-soft (Dirichlet) boundary conditions with $\sigma \to \infty$ ($Z=0$). ```python # compute solution for very large sigma u = Helmholtz_Robin(mesh, f, xs, sigma=dolfin.Constant(1e15)) # plot sound field plot_soundfield(u) plot_soundfield(abs(u)) plt.title(r'$|P(\mathbf{x}, \omega)|$'); ``` The effect of the homogeneous Dirichlet boundary condition (zero pressure at the boundary) can be observed conveniently by inspecting the magnitude of the sound field close to the boundary. **Copyright** This notebook is provided as [Open Educational Resource](https://en.wikipedia.org/wiki/Open_educational_resources). Feel free to use the notebook for your own purposes. The text is licensed under [Creative Commons Attribution 4.0](https://creativecommons.org/licenses/by/4.0/), the code of the IPython examples under the [MIT license](https://opensource.org/licenses/MIT).
#' @title Function to read Illumina "Sample Sheet" adapted from \code{read.450k.sheet} in \code{R/minfi} #' #' @description #' Reading an Illumina methylation sample sheet, containing pheno-data #' information for the samples in an experiment. #' #' @param base The base directory from which the search is started. #' @param basenames Output from \code{\link{meffil.basenames}} #' @param pattern = "csv$" What pattern is used to identify a sample sheet file, see \code{list.files} #' @param ignore.case = TRUE Should the file search be case sensitive? #' @param recursive = TRUE Should the file search be recursive, see \code{list.files}? #' @param verbose = TRUE Should the function be verbose? #' #' @details #' This function search the directory \code{base} (possibly including #' subdirectories depending on the argument \code{recursive} for #' \dQuote{sample sheet} files (see below). These files are identified #' solely on the base of their filename given by the arguments #' \code{pattern} and \code{ignore.case} (note the use of a dollarsign to #' mean end of file name).#' #' #' In case multiple sheet files are found, they are all read and the #' return object will contain the concatenation of the files. #' #' A sample sheet file is essentially a CSV (comma-separated) file #' containing one line per sample, with a number of columns describing #' pheno-data or other important information about the sample. The file #' may contain a header, in which case it is assumed that all lines up to #' and including a line starting with \code{\[Data\]} should be dropped. #' This is modelled after a sample sheet file Illumina provides. It is #' also very similar to the \code{targets} file made used by the popular #' \code{limma} package (see the extensive package vignette).#' #' #' An attempt at guessing the file path to the IDAT files represented in #' the sheet is made. This should be doublechecked and might need to #' manually changed. #' #' @export #' #' @return #' A \code{data.frame} containing the columns of all the sample sheets. #' As described in details, a column named \code{Sentrix_Position} is renamed #' to \code{Array} and \code{Sentrix_ID} is renamed to \code{Slide}. In addition #' the \code{data.frame} will contain a column named \code{Basename}. #' meffil.read.samplesheet <- function(base, pattern = "csv$", ignore.case = TRUE, recursive = TRUE, verbose = TRUE) { stopifnot(file.info(base)$isdir) readSheet <- function(file) { dataheader <- grep("^\\[DATA\\]", readLines(file), ignore.case = TRUE) if(length(dataheader) == 0) dataheader <- 0 df <- read.csv(file, stringsAsFactor = FALSE, skip = dataheader) if(length(nam <- grep("Sentrix_Position", names(df), ignore.case = TRUE, value = TRUE)) == 1) { df$Array <- df[, nam] df[, nam] <- NULL } if(length(nam <- grep("Array[\\._]ID", names(df), ignore.case = TRUE, value = TRUE)) == 1) { df$Array <- df[, nam] df[, nam] <- NULL } if(! "Array" %in% names(df)) warning(sprintf("Could not infer array name for file: %s", file)) if(length(nam <- grep("Sentrix_ID", names(df), ignore.case = TRUE, value = TRUE)) == 1) { df$Slide <- df[, nam] df[, nam] <- NULL } if(length(nam <- grep("Slide[\\._]ID", names(df), ignore.case = TRUE, value = TRUE)) == 1) { df$Slide <- df[, nam] df[, nam] <- NULL } if(! "Slide" %in% names(df)) warning(sprintf("Could not infer slide name for file: %s", file)) else df[, "Slide"] <- as.character(df[, "Slide"]) if(length(nam <- grep("Plate[\\._]ID", names(df), ignore.case = TRUE, value = TRUE)) == 1) { df$Plate <- df[, nam] df[, nam] <- NULL } if(!is.null(df$Array)) { patterns <- sprintf("%s_%s_Grn.idat", df$Slide, df$Array) allfiles <- list.files(dirname(file), recursive = recursive, full.names = TRUE) mbasenames <- sapply(patterns, function(xx) grep(xx, allfiles, value = TRUE)) names(mbasenames) <- NULL mbasenames <- sub("_Grn\\.idat(|\\.gz)", "", mbasenames, ignore.case = TRUE) df$Basename <- mbasenames sapply(df$Basename, function(x) { nom <- paste(x, "_Grn.idat", sep="") if(!file.exists(nom) && !file.exists(paste(nom, "gz", sep="."))) warning(paste("Inferred basename", nom, "does not exist")) nom <- paste(x, "_Red.idat", sep="") if(!file.exists(nom) && !file.exists(paste(nom, "gz", sep="."))) warning(paste("Inferred basename", nom, "does not exist")) }) } df } if(!all(file.exists(base))) stop("'base' does not exists") info <- file.info(base) if(!all(info$isdir) && !all(!info$isdir)) stop("'base needs to be either directories or files") if(all(info$isdir)) { csvfiles <- list.files(base, recursive = recursive, pattern = pattern, ignore.case = ignore.case, full.names = TRUE) if(verbose) { cat("[read.450k.sheet] Found the following CSV files:\n") print(csvfiles) } } else csvfiles <- list.files(base, full.names = TRUE) if (length(csvfiles) == 0) return(NULL) dfs <- lapply(csvfiles, readSheet) namesUnion <- Reduce(union, lapply(dfs, names)) df <- do.call(rbind, lapply(dfs, function(df) { newnames <- setdiff(namesUnion, names(df)) newdf <- matrix(NA, ncol = length(newnames), nrow = nrow(df), dimnames = list(NULL, newnames)) cbind(df, as.data.frame(newdf)) })) # Check that Sex column is present in sample sheet # Avoid case issues if(length(nam <- grep("Sex", names(df), ignore.case = TRUE)) == 1) { names(df)[nam] <- "Sex" } else { warning("There should be one 'Sex' column") df$Sex <- NA } # Check Sample_Name column if(length(nam <- grep("Sample_Name", names(df), ignore.case = TRUE)) == 1) { names(df)[nam] <- "Sample_Name" } else if(length(nam) > 1) { warning("Multiple Sample_Name columns. Keeping first column only.") temp <- df[,nam] df[,nam] <- NULL df$Sample_Name <- temp[,1] } else if("Slide" %in% names(df) & "Array" %in% names(df)) { warning("No 'Sample_Name' column in samplesheet. Creating Sample_Name using <Slide>_<Array>") df$Sample_Name <- paste(df$Slide, df$Array, sep="_") } else { warning("No Sample_Name column, and no Slide and Array columns to generate Sample_Name column. Using IDAT basenames.") df$Sample_Name <- make.samplename.from.basename(df$Basename) } check.samplesheet(df) return(df) } check.samplesheet <- function(samplesheet) { if(!"Sample_Name" %in% names(samplesheet)) { stop("No 'Sample_Name' column in samplesheet") } if(any(duplicated(samplesheet$Sample_Name))) { stop("Duplicate IDs in samplesheet") } if(!"Sex" %in% names(samplesheet)) { stop("No 'Sex' column in samplesheet") } if(any(! samplesheet$Sex %in% c("M", "F", NA))) { stop("Sex column must only contain 'M', 'F' or NA values") } }
# loads the buridans xml file load.buridan.xml <- function(xmlpath) { doc <- xmlInternalTreeParse(xmlpath) data <- xmlChildren(xmlChildren(doc)$HEADER) values <- sapply(data, xmlValue) erg <- lapply(values,unlist) datapath = strsplit(xmlpath,"/") datapath = paste(c(datapath[[1]][1:length(datapath[[1]])-1],""),collapse="/") erg$DATAPATH = datapath class(erg) <- "bur.xml" return(erg) } # loads buridan data from the object created by load.buridan.xml load.buridan.data <- function(params,id_prefix=NA,center=FALSE) { if (!inherits(params,"bur.xml")) stop("params should be of class \"bur.xml\". created by the function load.buridan.xml()") # read the data files data <- read.table(paste(params$DATAPATH,params$DATAFILE,sep=""), header=TRUE) # TODO: check if the params are the same if (center) { data$x = data$x-as.numeric(params$ARENA_CENTER_X) data$y = data$y-as.numeric(params$ARENA_CENTER_Y) } experiment_time = as.numeric(params$TIMESTAMP) fly_id <- params$FLY if (!is.na(id_prefix)) fly_id <- paste(id_prefix,params$FLY,sep="_") #create xy coordinates res <- as.numeric(params$ARENA_DIAMETER_MM)/(as.numeric(params$ARENA_RADIUS)*2) xy <- data.frame(data$x*res,data$y*res) #create time time <- ISOdatetime(1970,1,1,0,0,0) + experiment_time + data$time/1000 if (!is.na(id_prefix)) {data$burst <- sapply(data$burst,function(v) { add.group_id.prefix(v,id_prefix) }) }else data$burst <- sapply(data$burst,function(v) { add.zero.prefix(v) }) new_traj = as.ltraj(xy,time,id=fly_id, burst = data$burst,slsp="missing") #do a lowpass to 10 Hz new_traj <- set.sampling.rate(new_traj,0.1) #take data only if distance >,< tresholds new_traj2 <- mindistkeep3(new_traj, thresholdmin= g_treshold/10, thresholdmax = 70) return(new_traj2) } # loads buridan data from the object created by load.buridan.xml load.buridan.data.22 <- function(params,id_prefix=NA,center=TRUE) { if (!inherits(params,"bur.xml")) stop("params should be of class \"bur.xml\". created by the function load.buridan.xml()") # read the data files data <- read.table(paste(params$DATAPATH,params$DATAFILE,sep=""), header=TRUE) # TODO: check if the params are the same experiment_time = as.numeric(params$TIMESTAMP) fly_id <- params$FLY if (!is.na(id_prefix)) fly_id <- paste(id_prefix,params$FLY,sep="_") #create xy coordinates res <- as.numeric(params$ARENA_DIAMETER_MM)/(as.numeric(params$ARENA_RADIUS)*2) xy <- data.frame(data$x*res,data$y*res) if (center) { data$x = data$x-params$CENTER_X data$y = data$y-params$CENTER_Y } #create time time <- ISOdatetime(1970,1,1,0,0,0) + experiment_time + data$time/1000 if (!is.na(id_prefix)) data$burst <- sapply(data$burst,function(v) { add.group_id.prefix(v,id_prefix) }) else data$burst <- sapply(data$burst,function(v) { add.zero.prefix(v) }) new_traj = as.ltraj(xy,time,id=fly_id, burst = data$burst,slsp="missing") #do a lowpass to 10 Hz new_traj2 <- set.sampling.rate(new_traj,0.1) #take data only if distance >,< tresholds new_traj3 <- mindistkeep3(new_traj2, thresholdmin= g_treshold/10, thresholdmax = 35) return(list(new_traj3, new_traj)) } create.arena.poly <- function(arena,outer_circle=FALSE) { if (!inherits(arena,"bur.env")) stop("Arena should be of class \"bur.env\".") # create circles poly <- circle(arena$cx,arena$cy,arena$r) p_id <- rep(1,100) if (outer_circle) { poly <- rbind(poly, circle(arena$cx,arena$cy,arena$outer_r)) p_id <- c(p_id,rep(0,100)) } return(data.frame(p_id,poly)) } # creates black stripe polygon create.stripe.poly <- function(env) { pos = env$stripe_pos[[1]] w = env$stripe_w r = env$r+4 px = matrix(c(env$cx+(cos(pos+w)*r),env$cx+(cos(pos-w))*r),ncol=2) py = matrix(c(env$cy+(sin(pos+w)*r),env$cy+(sin(pos-w))*r),ncol=2) p_id <- c() x <- c() y <- c() for (i in c(1:length(pos))) { p_id <- c(p_id,rep(i-1,2)) x <- c(x,px[i,]) y <- c(y,py[i,]) } return(data.frame(p_id,x,y)) } #creates a data frame with all the environment variables create.env.vars <- function(params,res=0) { if (res==0) res <- as.numeric(params$ARENA_DIAMETER_MM)/(as.numeric(params$ARENA_RADIUS)*2) # TODO: resolution erg <- data.frame( cx = as.numeric(params$ARENA_CENTER_X)*res, cy = as.numeric(params$ARENA_CENTER_Y)*res, r = as.numeric(params$ARENA_DIAMETER_MM)/2, outer_r = as.numeric(params$OUTER_DIAMETER_MM)/2, stripe_pos = I(list (as.numeric(unlist(strsplit(params$STRIPE_POS,",")))/180*pi )), stripe_w = as.numeric(params$STRIPE_WIDTH)/180*pi, res = res ) class(erg) <- c("bur.env","data.frame") return(erg) } #creates a data frame with all the environment variables +center create.env.vars.center <- function(params,res=0) { if (res==0) res <- as.numeric(params$ARENA_DIAMETER_MM)/(as.numeric(params$ARENA_RADIUS)*2) # TODO: resolution erg <- data.frame( cx = 0, cy = 0, r = as.numeric(params$ARENA_DIAMETER_MM)/2, outer_r = as.numeric(params$OUTER_DIAMETER_MM)/2, stripe_pos = I(list (as.numeric(unlist(strsplit(params$STRIPE_POS,",")))/180*pi )), stripe_w = as.numeric(params$STRIPE_WIDTH)/180*pi, res = res ) class(erg) <- c("bur.env","data.frame") return(erg) } get5min <- function (ltraj) { if (!inherits(ltraj, "ltraj")) stop("ltraj should be of class \"ltraj\"") newtraj="a" gotone=FALSE for (i in 1:length(ltraj)){ if (!gotone){ if (nrow(ltraj[[i]]) > 3000){ newtraj = c(ltraj[i]) gotone= TRUE } } } newtraj2=c() if (newtraj !="a") newtraj2 = gdltraj(newtraj,newtraj[[1]]$date [1],newtraj[[1]]$date [3002], type ="POSIXct") return(newtraj2) } get5minR <- function (ltraj) { if (!inherits(ltraj, "ltraj")) stop("ltraj should be of class \"ltraj\"") gotone=FALSE for (i in length(ltraj):1){ if (!gotone){ if (nrow(ltraj[[i]]) > 3000){ newtraj = c(ltraj[i]) gotone= TRUE } } } newtraj2 = gdltraj(newtraj,newtraj[[1]]$date [length(newtraj[[1]]$date)-3001],newtraj[[1]]$date [length(newtraj[[1]]$date)], type ="POSIXct") return(newtraj2) } # creates a trajectorie with a sampling rate in dt secs out of the given ltraj object, adds interpolated points #TODO: make this work with bigger dt set.sampling.rate <- function(ltraj,dt=0.1) { if (dt!=0.1) stop("currently works only with dt=0.1") if (!inherits(ltraj, "ltraj")) stop("ltraj should be of class \"ltraj\"") if (!attr(ltraj, "typeII")) stop("ltraj should be of type II (time recorded)") ## for each burst for (oo in c(1:length(ltraj))) { data = ltraj[[oo]] date <- data$date x <- data$x y <- data$y # get the ref date and duration date.ref <- as.seconds(date[1]) date.ref <- ISOdatetime(1970,1,1,0,0,0) + date.ref$s+date.ref$r duration <- as.seconds(date[length(date)])-as.seconds(date[1]) duration <- duration$sec+duration$r offset <- as.seconds(date[1])$r # create new dates first_date <- as.seconds(date[1]) da <- as.seconds(date) da$sec <- da$sec-first_date$sec da$r <- da$r - first_date$r da <- da$sec + da$r # creates a sequence for the new dates: start <- (offset%/%dt)*dt+dt start <- start - offset if (start>duration) { next() } time_seq = seq(start,duration,dt) ndates <- date.ref + time_seq #TODO: round to 1/10th second class(ndates) <- c("POSIXct", "POSIXt") #interpolates the curve at given positions nx <- approx(da,x,method="linear",xout= time_seq,ties="mean")$y ny <- approx(da,y,method="linear",xout= time_seq,ties="mean")$y if (length(nx)!=length(ny)||length(ndates)!=length(ny)) stop("Something went wrong!") #create id id <- id(ltraj[oo]) id <- rep(id,length(ndates)) burst <- burst(ltraj[oo]) burst <- rep(burst,length(ndates)) #adds the data to the new trajectorie if (oo==1) { new_x <- nx new_y <- ny new_date <- ndates new_burst <- burst new_id <- id } else { new_x <- c(new_x,nx) new_y <- c(new_y,ny) new_date <- c(new_date,ndates) new_burst <- c(new_burst,burst) new_id <- c(new_id,id) } } # create the new trajectorie new_traj = as.ltraj(data.frame(new_x,new_y),new_date,id=new_id, burst = new_burst) attr(new_traj, "typeII") <- TRUE attr(new_traj, "regular") <- TRUE return(new_traj) } # computes the deviation of the flies walking direction towards the black stripe direction c.angle.dev <- function(traj,env) { if (!inherits(env,"bur.env")) stop("env should be of class \"bur.env\".") if (!inherits(traj, "ltraj")) stop("ltraj should be of class \"ltraj\"") deviation <- c() dates <- c() #calculate the position of the black stripes stripe_pos <- env$stripe_pos[[1]] stripe_radius <- env$outer_r stripes <- matrix(c(cos(stripe_pos)*stripe_radius,sin(stripe_pos)*stripe_radius),ncol=2) center <- c(env$cx,env$cy) for (oo in c(1:length(traj))) { data <- traj[[oo]] date <- data$date angles <- data$abs.angle # take only when there is more than one point in the burst if (length (angles)>1) { points <- matrix(c(data$x,data$y),ncol=2) # center the points at the arena center if (center [1]>0){ points[,1] <- points[,1] - center[1] points[,2] <- points[,2] - center[2]} #now calculate the vectors angle pointing towards the column v <- apply(points,1,function(p) { res <- t(t(stripes)-p) return (atan2(res[,2],res[,1])) }) #calculate the deviation from the fly direction to the v vectors if (class(v)=="numeric") { tv <- t(v) } else { tv <- v } angle_diff <- apply(tv,1,function(c) { return(angular.diff(c,angles)) }) dev <- apply(abs(angle_diff),1,min) # add to the result vector deviation <- c(deviation,dev) dates <- c(dates,date) } } erg <- data.frame(date=dates,dev=deviation/pi*180) return(erg) } # calculates speed in unit/s, averages the speed over np points (works only with regular trajectories) c.speeds <- function(traj,np=1) { speeds <- c() dates <- c() speed_detail <- c() for (oo in c(1:length(traj))) { data = traj[[oo]] dt <- data$dt ddist <- data$dist date <- data$date speed <- ddist/dt average_speeds <- c() le <- length(speed) if (np>1) { #smooth the curve by taking the average of np points for (i in c(1:le)) { low <- max(i-np/2,0) high <- min(i + np/2,le) average_speed <- speed[low:high] average_speed[is.na(average_speed)] <- 0 average_speed <- sum(average_speed)/length(average_speed) average_speeds <- c(average_speeds,average_speed) } speed <- average_speeds } speeds <- c(speeds,speed) dates <- c(dates,date) speed_detail <- c(speed_detail,speed) } erg <- data.frame(date=dates,speed=speeds, speed_det=speed_detail) class(erg$date) <- "POSIXct" return(erg) } c.distance <- function(traj) { dists <- c() time <-c() for (oo in c(1:length(traj))) { data = traj[[oo]] dist <- data$dist dist <- dist[!is.na(dist)] dtime <- data$dt dtime <- dtime [!is.na(dtime)] dists <- c(dists,sum(dist)) time <- c(time,sum(dtime)) } return(sum(dists)/sum(time)*60) } c.time <- function(traj) { time <-c() for (oo in c(1:length(traj))) { data = traj[[oo]] dtime <- data$dt dtime <- dtime [!is.na(dtime)] time <- c(time,sum(dtime)) } return(sum(time)/60) } c.activity <- function(traj,min_pause_length) { activities <- c() distances <- c() timestart <- c() timestop <- c() Xstart <- c() Ystart <- c() Xend <- c() Yend <- c() for (oo in c(1:length(traj))) { data = traj[[oo]] dt <- data$dt xx <- data$x yy <- data$y ddist <- data$dist date <- data$date moving <- data$dist moving[is.na(moving)] <- 0 dt[is.na(dt)] <- 0 activity <- c() Distance <- c() datesstart <- c() datesend <- c() dataXstart <- c() dataYstart <- c() dataXend <- c() dataYend <- c() pause_length <- 0 active_length <- 0 Distance_traveled <- 0 dtempP <- date [1] dtempA <-date [1] xP<-xx [1] yP<-yy [1] xA<-xx [1] yA<-yy [1] active <- FALSE # TODO: use rapply here! for (i in c(1:length(dt))) { if (moving[i]==0) { pause_length <- pause_length + dt[i] dtempP= ifelse(pause_length > dt [i],dtempP,date [i])## end of bout temporary xP = ifelse(pause_length > dt[i],xP,xx [i]) yP = ifelse(pause_length > dt[i],yP,yy [i]) if (active_length>0 && pause_length>=min_pause_length) { activity <- c(activity,active_length) Distance <- c(Distance,Distance_traveled) datesstart <- c(datesstart,dtempA) datesend <- c(datesend,dtempP) dataXstart <- c(dataXstart,xA) dataYstart <- c(dataYstart,yA) dataXend <- c(dataXend,xP) dataYend <- c(dataYend,yP) active_length <- 0 Distance_traveled <- 0 } } else { active_length <- active_length + dt[i] Distance_traveled <- Distance_traveled + ddist [i] if (pause_length>0) { dtempA= ifelse( active_length > dt [i],dtempA,date [i]) #start of bout temporary, change if active_length was 0(bout def depend on what happen next) xA = ifelse(active_length > dt [i],xA,xx [i]) yA = ifelse(active_length > dt [i],yA,yy [i]) if (pause_length<min_pause_length){ active_length <- active_length + pause_length pause_length <- 0 } else { activity <- c(activity,-pause_length) Distance <- c(Distance,0) datesstart <- c(datesstart,dtempP) datesend <- c(datesend,date [i]) dataXstart <- c(dataXstart,xP) dataYstart <- c(dataYstart,yP) dataXend <- c(dataXend,xx[i]) dataYend <- c(dataYend,yy[i]) pause_length <- 0 } } } } # add activitity for the last bout i=length(dt) dataXend <- c(dataXend,xx[i]) dataYend <- c(dataYend,yy[i]) datesend <- c(datesend,date [i]) if (!pause_length<min_pause_length){ activity <- c(activity,-pause_length) Distance <- c(Distance,0) datesstart <- c(datesstart,dtempP) dataXstart <- c(dataXstart,xP) dataYstart <- c(dataYstart,yP) }else{ active_length <- active_length + pause_length activity <- c(activity,active_length) Distance <- c(Distance,Distance_traveled) datesstart <- c(datesstart,dtempA) dataXstart <- c(dataXstart,xA) dataYstart <- c(dataYstart,yA) } #write activities for this burst activities <- c(activities,activity) distances <- c(distances, Distance) timestart <- c(timestart, datesstart) timestop <- c(timestop, datesend) Xstart <- c(Xstart, dataXstart) Ystart <- c(Ystart, dataYstart) Xend <- c(Xend, dataXend) Yend <- c(Yend, dataYend) } erg <- data.frame(datestart=timestart, datesend=timestop,Xs=Xstart,Xe= Xend,Ys=Ystart, Ye=Yend,dist_traveled = distances,act=activities) class(erg$datestart) <- "POSIXct" class(erg$datesend) <- "POSIXct" return(erg) } c.activity_speed <- function(traj,min_pause_length) { activities <- c() distances <- c() timestart <- c() timestop <- c() Xstart <- c() Ystart <- c() Xend <- c() Yend <- c() speedmax_all<- c() for (oo in c(1:length(traj))) { data = traj[[oo]] dt <- data$dt xx <- data$x yy <- data$y ddist <- data$dist date <- data$date moving <- data$dist moving[is.na(moving)] <- 0 dt[is.na(dt)] <- 0 activity <- c() Distance <- c() datesstart <- c() datesend <- c() dataXstart <- c() dataYstart <- c() dataXend <- c() dataYend <- c() speedmax_burst <- c() pause_length <- 0 active_length <- 0 Distance_traveled <- 0 speedmax_temp <- 0 dtempP <- date [1] dtempA <-date [1] xP<-xx [1] yP<-yy [1] xA<-xx [1] yA<-yy [1] active <- FALSE # TODO: use rapply here! for (i in c(1:length(dt))) { cond = (ddist[i]/dt[i]> 250) cond[is.na (cond)] <- "FALSE" if (cond) {print (c(moving [i],i,id(traj[oo]) ))} if (moving[i]==0) { pause_length <- pause_length + dt[i] dtempP= ifelse(pause_length > dt [i],dtempP,date [i])## end of bout temporary xP = ifelse(pause_length > dt[i],xP,xx [i]) yP = ifelse(pause_length > dt[i],yP,yy [i]) if (active_length>0 && pause_length>=min_pause_length) { activity <- c(activity,active_length) Distance <- c(Distance,Distance_traveled) speedmax_burst <- c(speedmax_burst,speedmax_temp) datesstart <- c(datesstart,dtempA) datesend <- c(datesend,dtempP) dataXstart <- c(dataXstart,xA) dataYstart <- c(dataYstart,yA) dataXend <- c(dataXend,xP) dataYend <- c(dataYend,yP) active_length <- 0 Distance_traveled <- 0 speedmax_temp <-0 } } else { active_length <- active_length + dt[i] Distance_traveled <- Distance_traveled + ddist [i] speedmax_temp <- ifelse (ddist[i]/dt[i] >speedmax_temp,ddist [i]/dt[i] ,speedmax_temp) if (pause_length>0) { dtempA= ifelse( active_length > dt [i],dtempA,date [i]) #start of bout temporary, change if active_length was 0(bout def depend on what happen next) xA = ifelse(active_length > dt [i],xA,xx [i]) yA = ifelse(active_length > dt [i],yA,yy [i]) if (pause_length<min_pause_length){ active_length <- active_length + pause_length pause_length <- 0 } else { activity <- c(activity,-pause_length) Distance <- c(Distance,0) speedmax_burst <- c(speedmax_burst,speedmax_temp) datesstart <- c(datesstart,dtempP) datesend <- c(datesend,date [i]) dataXstart <- c(dataXstart,xP) dataYstart <- c(dataYstart,yP) dataXend <- c(dataXend,xx[i]) dataYend <- c(dataYend,yy[i]) pause_length <- 0 speedmax_temp <-0 } } } } # add activitity for the last bout i=length(dt) dataXend <- c(dataXend,xx[i]) dataYend <- c(dataYend,yy[i]) datesend <- c(datesend,date [i]) speedmax_burst <- c(speedmax_burst,speedmax_temp) if (!pause_length<min_pause_length){ activity <- c(activity,-pause_length) Distance <- c(Distance,0) datesstart <- c(datesstart,dtempP) dataXstart <- c(dataXstart,xP) dataYstart <- c(dataYstart,yP) }else{ active_length <- active_length + pause_length activity <- c(activity,active_length) Distance <- c(Distance,Distance_traveled) datesstart <- c(datesstart,dtempA) dataXstart <- c(dataXstart,xA) dataYstart <- c(dataYstart,yA) } #write activities for this burst activities <- c(activities,activity) distances <- c(distances, Distance) speedmax_all<- c(speedmax_all,speedmax_burst) timestart <- c(timestart, datesstart) timestop <- c(timestop, datesend) Xstart <- c(Xstart, dataXstart) Ystart <- c(Ystart, dataYstart) Xend <- c(Xend, dataXend) Yend <- c(Yend, dataYend) } erg <- data.frame(datestart=timestart, datesend=timestop,Xs=Xstart,Xe= Xend,Ys=Ystart, Ye=Yend,dist_traveled = distances,speedmax_inbout = speedmax_all,act=activities) class(erg$datestart) <- "POSIXct" class(erg$datesend) <- "POSIXct" return(erg) } # straightness averaged over bin_size points, bin_size=1 returns the relative angles between all relocation, # abs = TRUE doesnt differ between right or left turns c.straightness.ori <- function(traj,bin_size=1,abs=FALSE) { #if (!attr(traj, "regular")) # stop("traj should have regular time differences between relocations") erg_angles <- c() erg_dates <- c() for (oo in c(1:length(traj))) { angles <- traj[[oo]]$rel.angle dates <- traj[[oo]]$date angles[is.na(angles)] <- 0 if (bin_size>length(angles)) next(); seq = seq(bin_size,length(angles),1) angle_sum <-sapply(seq,function(i) { if (!abs) sum(angles[c((i-bin_size+1):i)]) #/bin_size else sum(abs(angles[c((i-bin_size+1):i)])) #/bin_size }) dates <- dates[seq] erg_angles <- c(erg_angles,angle_sum) erg_dates <- c(erg_dates,dates) } erg <- data.frame(date=erg_dates,angle=erg_angles) class(erg$date) <- "POSIXct" return(erg) } # straightness averaged over bin_size points, bin_size=1 returns the relative angles between all relocation, # abs = TRUE doesnt differ between right or left turns c.straightness <- function(traj,bin_size=1,abs=FALSE) { #if (!attr(traj, "regular")) # stop("traj should have regular time differences between relocations") erg_angles <- c() erg_dates <- c() erg_meander <- c() for (oo in c(1:length(traj))) { angles <- traj[[oo]]$rel.angle*180/pi dates <- traj[[oo]]$date speed <-traj[[oo]]$dist/traj[[oo]]$dt beta = data.frame(angles,speed,dates) is.na (beta$speed [beta$speed>30]) beta = na.omit(beta) angles <- beta$angles dates <- beta$dates meander <- beta$angles/beta$speed erg_angles <- c(erg_angles,angles) erg_dates <- c(erg_dates,dates) erg_meander <- c(erg_meander,meander) } erg <- data.frame(date=erg_dates,angle=erg_angles, meander=erg_meander) class(erg$date) <- "POSIXct" return(erg) } c.straightness.fast <- function(traj,abs=FALSE) { #if (!attr(traj, "regular")) # stop("traj should have regular time differences between relocations") erg_angles <- c() erg_dates <- c() for (oo in c(1:length(traj))) { angles <- traj[[oo]]$rel.angle dates <- traj[[oo]]$date angles[is.na(angles)] <- 0 erg_angles <- c(erg_angles,angles) erg_dates <- c(erg_dates,dates) } erg <- data.frame(date=erg_dates,angle=erg_angles) class(erg$date) <- "POSIXct" return(erg) } # compute number of walks from trajectorie c.nwalks<- function(traj,env) { if (!inherits(env,"bur.env")) stop("env should be of class \"bur.env\".") if (length(env$stripe_pos[[1]])==0) return(data.frame()); if (!inherits(traj, "ltraj")) stop("ltraj should be of class \"ltraj\"") erg <- c() #define the areas between the fly circles to count as a walk center <- c(env$cx,env$cy) stripe_pos <- env$stripe_pos[[1]] a_normvec <- matrix(c(cos(stripe_pos),sin(stripe_pos)),ncol=2) a_dist <- env$r*0.8 start_date <- c() end_date <- c() distances <- c() for (oo in c(1:length(traj))) { data <- traj[[oo]] points <- matrix(c(data$x,data$y),ncol=2) dist <- data$dist dist[is.na(dist)] <- 0 # center the points at the arena center if (center [1] >0){ points[,1] <- points[,1] - center[1] points[,2] <- points[,2] - center[2]} # now test if the fly comes near the arena border where the stripe is attached dp <- points%*%t(a_normvec) - a_dist #dotproduct in_area <- dp>0 mask <- seq(TRUE,nrow(a_normvec)) in_btw <- TRUE first_run <- TRUE distance <- 0 # count the walks for (i in c(1:nrow(in_area))) { # fly leaves the stripe area if (!in_btw&&sum(in_area[i,])==0) { in_btw <- TRUE start_date_c <- data$date[i] distance <- 0 } # fly enters the stripe area if (in_btw&&sum(in_area[i,]&mask)>0) { if (first_run) first_run <- FALSE else { end_date <- c(end_date,I(data$date[i])) start_date <- c(start_date,I(start_date_c)) distances <- c(distances,distance) } in_btw <- FALSE mask <- !(in_area[i,]&mask) } distance <- distance + dist[i] } } if (length(start_date)==0) return(data.frame(c())) erg <- data.frame(start=start_date,end=end_date,dt=end_date-start_date,dist=distances) class(erg$start) <- "POSIXct" class(erg$end) <- "POSIXct" return(erg) } # creates a mean table of a data_table, containing one column with the group # and one ore more columns containg the data which should be averaged create.mean.table <- function(data_table,groups,data_cols=1,group_col=ncol(data_table)) { mean_table = data.frame() sd_table = data.frame() se_table = data.frame() for (g in groups) { data = data_table[data_table[group_col]==g,] mean_table = rbind(mean_table,data.frame(t(colMeans(data[data_cols],na.rm=TRUE)))) sd_table = rbind(sd_table,data.frame(t(sapply(data[data_cols],na.rm=TRUE,sd)))) se_table = sd_table/sqrt(nrow(data)) } rownames(mean_table) = groups rownames(sd_table) = groups erg <- list(mean_table,sd_table,se_table) names(erg) <- c("means","sds","ses") return(erg) } ####individual data: plot trajectories /individual analyses ## trajectories plot.circle <- function (traj, env, g_traj_color1=TRUE) { traj_title = paste(c("Trajectorie for ", id(traj[1])),collapse="") if (!inherits(env,"bur.env")) stop("env should be of class \"bur.env\".") if (!inherits(traj, "ltraj")) stop("ltraj should be of class \"ltraj\".") umg <- as.area(create.arena.poly(env,outer_circle=FALSE)) radius=env$r xdim = c((env$cx-radius),(env$cx+radius)) ydim = c((env$cy-radius),(env$cy+radius)) s = create.stripe.poly(env) plot.ltraj(traj, area=umg, xlab="", ylab="y [mm]", main=traj_title, xlim=xdim, ylim=ydim, colpol="white", addpoints=FALSE,perani=TRUE,final=FALSE,frame=FALSE,xaxt = "n") # paint black stripe positions lines(s$x[s$p_id==0],s$y[s$p_id==0],lwd=4) lines(s$x[s$p_id==1],s$y[s$p_id==1],lwd=4) #colour the walks walks = c.nwalks(traj,env) if (g_traj_color1) { if (nrow(walks)>0) for (i in c(1:nrow(walks))) { lt = gdltraj_old(traj, min = walks$start[i], max = walks$end[i], type="POSIXct") t = ltraj2traj(lt) lines(t$x,t$y,col=2+i%%7); } } } ####individual data: plot trajectories /individual analyses ## individual analyses plotindividtests <- function (traj, g_speed_average=10) { speed_title =paste("speed average per sec: ", id(traj)) speeds=c() speeds = c.speeds(traj,g_speed_average) durations = get.durations(speeds$date) hist(log(speeds$speed), breaks =200) layout(matrix (1:2,2,1)) plot(durations,speeds$speed,type='l',main=speed_title, ylab="Speed [mm/s]",xlab="Experiment Duration [s]", xlim=c(0,450)) plot(durations,speeds$speed,type='l',main=speed_title, ylab="Speed [mm/s]",xlab="Experiment Duration [s]", xlim=c(450,900)) ###angle relative- and speed rel.angle2=c() dist= c() for (oo in c(1:length(traj))){ rel.angle2 =c(rel.angle2,traj[[oo]]$rel.angle /pi*180) dist= c(dist,traj[[oo]]$dist) } layout(matrix (1:3,3,1)) plot(durations,rel.angle2, ylim=c(-180,180), type= "h", pch=21, cex =speeds$speed/10, xlim=c(0,300)) points(durations,rel.angle2, ylim=c(-180,180), pch=21, col =speeds$speed/5) points(durations,speeds$speed*2-180, col=speeds$speed/5,pch=19) abline(h=0, col=2) abline(h=90, col=3) abline(h=-90, col=3) plot(durations,rel.angle2, ylim=c(-180,180), type= "h", pch=21, cex =speeds$speed/10, xlim=c(300,600)) points(durations,rel.angle2, ylim=c(-180,180), pch=21, col =speeds$speed/5) points(durations,speeds$speed*2-180, col=speeds$speed/5,pch=19) abline(h=0, col=2) abline(h=90, col=3) abline(h=-90, col=3) plot(durations,rel.angle2, ylim=c(-180,180), type= "h", pch=21, cex =speeds$speed/10, xlim=c(600,900)) points(durations,rel.angle2, ylim=c(-180,180), pch=21, col =speeds$speed/5) points(durations,speeds$speed*2-180, col=speeds$speed/5,pch=19) abline(h=0, col=2) abline(h=90, col=3) abline(h=-90, col=3) layout(matrix (1:2,2,1)) h=hist(rel.angle2, breaks=seq(-181,181,1), xlim= c(-180,180),freq=FALSE,main="relative angle histogram") g=hist(rel.angle2/(dist/0.75), breaks=seq(-181,181,1), xlim= c(-180,180),freq=FALSE, main="meander histogram (*7.5)") h=hist(abs(rel.angle2), breaks=seq(0,180,1), xlim= c(0,180),freq=FALSE,main="relative angle (abs) histogram", plot=FALSE) g=hist(abs(rel.angle2/(dist/0.75)), breaks=seq(-1,180,1), xlim= c(0,180),freq=FALSE, main="meander (abs)histogram", plot=FALSE) plot(h$density~h$mids, ylim= c(-0.2,0.2),xlim= c(0,180),main="relative angle (red),meanderx7.5(green) histogram", col=2, type="h") points(g$mids,-g$density-0.02, col=3, pch=19,cex=0.5) abline(h=0) abline(h=-0.02) layout(matrix (1:1,1,1)) } function (corr, ...) { corrplot(corr = corr, method = "circle", ...) }
Require Import Undecidability.TM.SBTM Undecidability.TM.Enumerators.SBTM_HALT_enum. Require Import Undecidability.Synthetic.Definitions. (* ** SBTM_HALT is enumerable *) Lemma SBTM_HALT_enum : enumerable (SBTM_HALT). Proof. exists SBTM_HALT_enumerator. exact SBTM_HALT_enumerator_spec. Qed.
-- ----------------------------------------------------------------- [ Eff.idr ] -- Module : XML.Reader.Eff -- Copyright : (c) Jan de Muijnck-Hughes -- License : see LICENSE -- --------------------------------------------------------------------- [ EOH ] module XML.Serialise.Eff import Lightyear import Lightyear.Strings import Lightyear.StringFile import Effects import Effect.File import Effect.Exception import XML.DOM import XML.Parser import XML.Serialise %access private export readXMLDoc : String -> Eff (Either XMLError (Document DOCUMENT)) [FILE ()] readXMLDoc f = parseFile CannotReadFile FileParseError parseXMLDoc f export readXMLSnippet : String -> Eff (Either XMLError (Document ELEMENT)) [FILE ()] readXMLSnippet f = parseFile CannotReadFile FileParseError parseXMLSnippet f -- --------------------------------------------------------------------- [ EOF ]
#include <boost/asio.hpp> #include <iostream> using namespace boost; int main() { asio::streambuf buf; std::ostream output(&buf); // Writing the message to the stream-based buffer. output << "Message1\nMessage2"; // Now we want to read all data from a streambuf // until '\n' delimiter. // Instantiate an intput stream which uses our // stream buffer. std::istream input(&buf); // We'll read data into this string. std::string message1; std::getline(input, message1); // Now message1 string contains 'Message1'. return 0; }
import Relation.Unary.Monotone as Mono open import Data.List.Prefix open import Data.List as List module Category.Monad.Monotone.Heap.HList (T : Set) (V : T → List T → Set)⦃ wkV : ∀ {a} → Mono.Monotone ⊑-preorder (V a) ⦄ where open import Level open import Data.List.All as All open import Data.List.All.Properties.Extra open import Data.List.Any open import Data.List.Membership.Propositional using (_∈_) open import Data.List.Properties.Extra open import Data.Product open import Data.Unit open import Relation.Binary using (Preorder) open import Relation.Unary hiding (_∈_) open import Relation.Unary.PredicateTransformer using (Pt) open import Relation.Unary.Monotone.Prefix {T = T} private HeapT : Set HeapT = List T Heap : Pred HeapT _ Heap = λ W → All (λ a → V a W) W open Mono (⊑-preorder {A = T}) open import Category.Monad.Monotone (⊑-preorder {A = T}) open import Category.Monad.Monotone.State ⊑-preorder Heap open import Category.Monad.Monotone.Heap ⊑-preorder T V Heap _∈_ open import Category.Monad using (RawMonad) module _ {M : Set → Set}⦃ Mon : RawMonad M ⦄ where private module M = RawMonad Mon hlist-heap-monad : HeapMonad (MST M) HeapMonad.store hlist-heap-monad {a}{i} sv μ = let ext = ∷ʳ-⊒ a i in M.return (_ , ext , (wk ext μ all-∷ʳ wk ext sv) , ∈-∷ʳ i a ) HeapMonad.modify hlist-heap-monad ptr v μ = M.return (_ , ⊑-refl , μ All[ ptr ]≔' v , lift tt) HeapMonad.deref hlist-heap-monad ptr μ = M.return (_ , ⊑-refl , μ , ∈-all ptr μ)
Catalog Datasheet MFG & Type PDF Document datasheets Tags; - BC547 BJT. Datasheets On- line Справочник. Link gray means no datasheets were found but will suggest similar words for which there are datasheets in our database. View the manufacturer stock datasheet pdf for the 7NV04. ecadata - data sheet - marking code - search engine for Electronic Components. 7nk80: 7nk80 7nk80: SP3767AHN: SP3767AHN: S7530. We have more Special DataSheet than other site. Datasheet archive onЗапросить on- line склады. 7nk80 datasheets. yo me arriesgaria a aconsejarte que uses un 6N60 7nk80 que son clasicos deberian de abundar. datasheetcatalog. View the manufacturer stock datasheet pdf for the 7OX- V. com is a free 7nk80 electronic engineering tool that enables you to locate product datasheets from hundreds of electronic. Datasheet pdf search engine - www. Datasheet search; Электронные книги Избранные схемы Сборник статей FAQ по электронике: Каталог программ Производители Каталог схем Datasheet catalog: Datasheets On- line Справочник Логотипы IC Форум по электронике. ارسال پستی رایگان به ازای خرید بالای 250 هزار تومان. a mi me pasó tambien y solo funcionó con otro mosfet original que saque de un chasis de desguase en este caso era 7nk80. STP7NK80ZFP datasheet STP7NK80ZFP data sheet, datasheet, pdf, data datasheets sheet, ST Microelectronics, STP7NK80ZFP pdf N- CHANNEL 800V - 1. Blue link means the search has found datasheet. mira solo de aventurero por la numeracion que das te puedo anticipar que se trata de un transistor de 3 amperes 600 voltios de canal N cualquiera que cumpla las mismas caracteristicas podes usarlo. Buy 7NV04 ST view datasheet manufacturer stock at Jotrin Electronics. Buy 7OX- V CITY view datasheet manufacturer stock at Jotrin 7nk80 Electronics. STP7NK80 Datasheets Context Search. Datasheets history of inquiries. © — « Электронный портал» связь. ( It will updated in 12 hours. Datasheet archive on. اجرای بازیهاي Play Station 2 از روی فلش مموری( بدون نیاز به چشم) برای تمامی مدلها. com is a datasheets free electronic engineering tool that enables you to locate product datasheets from hundreds of electronic component manufacturers worldwide. If There is not a datasheet which searches Request! buenos días amigos necesito una ayuda con un transistor mosfet el P13NK60ZFP el cual no encuentro su reemplazo o sus posibles reemplazos este transistor es de un televisor daewoo de 42 pulgadas lcd el cual tiene la fuente de poder da& ntilde; ada si alguien me puede ayudar a encontrar el posible reemplazo se los a. 7NK80 datasheet, 7NK80 pdf, 7NK80 data sheet, datasheet, data sheet, pdf. Data sheet search engine for semiconductors. de - ECA Electronic portalECA Electronic portal. STB7NK80ZT4 datasheet, STB7NK80ZT4 pdf, STB7NK80ZT4 data sheet, datasheet, data sheet, pdf, ST Microelectronics, N- CHANNEL 800V - 1. 2A TO- 220/ TO- 220FP/ I2PAK.
SUBROUTINE LA_TEST_ZGTSVX( FACT, TRANS, N, NRHS, DL, D, DU, DLF, DF,& & DUF, DU2, IPIV, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, & & RWORK, INFO) ! ! -- LAPACK95 interface driver routine (version 1.1) -- ! UNI-C, Denmark, ! March 28, 1999 ! ! .. Use Statements .. USE LA_PRECISION, ONLY: WP => DP USE F95_LAPACK, ONLY: LA_GTSVX ! .. Implicit Statement .. IMPLICIT NONE ! .. Scalar Arguments .. INTEGER, INTENT(IN) :: N, NRHS, LDB, LDX INTEGER, INTENT(INOUT) :: INFO CHARACTER(LEN=1), INTENT(IN) :: FACT, TRANS REAL(WP), INTENT(OUT) :: RCOND ! .. Array Arguments .. INTEGER, INTENT(INOUT) :: IPIV(1:N) COMPLEX(WP), INTENT(IN) :: B(1:LDB,1:NRHS) COMPLEX(WP), INTENT(IN) :: DL(1:N-1), D(1:N), DU(1:N-1) COMPLEX(WP), INTENT(INOUT) :: DF(1:N), DLF(1:N-1), DU2(1:N-2), & & DUF(1:N-1) REAL(WP), INTENT(OUT) :: FERR(1:NRHS), BERR(1:NRHS) COMPLEX(WP), INTENT(OUT) :: X(1:LDX,1:NRHS), WORK(1:3*N) REAL(WP), INTENT(OUT) :: RWORK(1:N) ! .. Parameters .. CHARACTER(LEN=8), PARAMETER :: SRNAME = 'LA_GTSVX' CHARACTER(LEN=14), PARAMETER :: SRNAMT = 'LA_TEST_ZGTSVX' ! .. Common blocks .. INTEGER :: INFOTC COMMON /LINFO95/ INFOTC ! .. Local Scalars .. INTEGER :: I, J, IDU, ID, IDL,IB1, IB2, IX1, IX2, IDLF,& & IDF, IDUF, IDU2, IIPIV, IFERR, IBERR CHARACTER(LEN=1) :: IFACT, ITRANS ! .. Local Arrays .. LOGICAL, SAVE :: CTEST = .TRUE., ETEST = .TRUE. ! .. Executable Statements .. IDL = N-1; ID = N; IDU = N-1; IB1 = N; IB2 = NRHS IX1=N; IX2=NRHS;IDLF=N-1;IDF=N; IDUF=N-1; IDU2= N-2 IIPIV = N; IFACT = FACT; ITRANS=TRANS; IFERR=NRHS IBERR = NRHS I = INFO / 100; J = INFO - I*100 SELECT CASE(I) CASE(0) IF ( NRHS == 1 ) THEN CALL LA_GTSVX( DL(1:IDL), D(1:ID), DU(1:IDU), B(1:IB1, 1), & & X(1:IX1, 1), DLF(1:IDLF), DF(1:IDF), DUF(1:IDUF), & & DU2(1: IDU2), IPIV(1:IIPIV), IFACT, ITRANS, FERR(1), & & BERR(1), RCOND, INFO ) INFO = INFOTC ELSE CALL LA_GTSVX( DL(1:IDL), D(1:ID), DU(1:IDU), B(1:IB1, 1:IB2), & & X(1:IX1, 1:IX2), DLF(1:IDLF), DF(1:IDF), DUF(1:IDUF), & & DU2(1: IDU2), IPIV(1:IIPIV), IFACT, ITRANS, FERR(1:IFERR), & & BERR(1: IBERR), RCOND, INFO ) INFO = INFOTC END IF CASE (1) IDL = ID CASE(3) IDU = ID CASE(4) IB1 = ID - 1 CASE (5) IX1 = ID - 1 CASE (6) IDLF = IDL - 1 CASE (7) IDF = ID - 1 CASE (8) IDUF = IDL - 1 CASE (9) IDU2 = IDL - 3 CASE (10) IIPIV = ID - 1 CASE (11) IFACT = 'T' CASE (12) ITRANS = 'E' CASE (13) IFERR = IB2 - 1 CASE (14) IBERR = IB2 - 1 CASE(:-1,2,15:) CALL UESTOP(SRNAMT) END SELECT IF( I /= 0 ) THEN SELECT CASE (NRHS) CASE (2:) CALL LA_GTSVX( DL(1:IDL), D(1:ID), DU(1:IDU), B(1:IB1, 1:IB2), & & X(1:IX1, 1:IX2), DLF(1:IDLF), DF(1:IDF), DUF(1:IDUF), & & DU2(1: IDU2), IPIV(1:IIPIV), IFACT, ITRANS, FERR(1:IFERR), & & BERR(1: IBERR), RCOND, INFO ) CASE(1) CALL LA_GTSVX( DL(1:IDL), D(1:ID), DU(1:IDU), B(1:IB1, 1), & & X(1:IX1, 1), DLF(1:IDLF), DF(1:IDF), DUF(1:IDUF), & & DU2(1: IDU2), IPIV(1:IIPIV), IFACT, ITRANS, FERR(1), & & BERR(1), RCOND, INFO ) CASE(:-1) CALL UESTOP(SRNAMT) END SELECT END IF CALL LA_AUX_AA01( I, CTEST, ETEST, SRNAMT ) END SUBROUTINE LA_TEST_ZGTSVX
"""@author: Bryan Silverthorn <[email protected]>""" import os.path import csv import copy import numpy import condor import borg logger = borg.get_logger(__name__, default_level = "INFO") def infer_distributions(run_data, model_name, instance, exclude): """Compute model predictions on every instance.""" # customize the run data filtered_data = copy.deepcopy(run_data) filtered_runs = filter(lambda r: r.solver != exclude, filtered_data.run_lists[instance]) filtered_data.run_lists[instance] = filtered_runs # sample from the model posterior model = borg.experiments.common.train_model(model_name, filtered_data, bins = 8) # summarize the samples (M, S, B) = model.log_masses.shape n = sorted(filtered_data.run_lists).index(instance) true = run_data.to_bins_array(run_data.solver_names, B = 8)[n].astype(float) true /= numpy.sum(true, axis = -1)[:, None] + 1e-16 observed = filtered_data.to_bins_array(run_data.solver_names, B = 8)[n].astype(float) observed /= numpy.sum(observed, axis = -1)[:, None] + 1e-16 mask = model.names == instance log_predicted_all = model.log_weights[mask][:, None, None] + model.log_masses[mask, :, :] predicted = numpy.sum(numpy.exp(log_predicted_all), axis = 0) predicted /= numpy.sum(predicted, axis = -1)[..., None] def yield_rows(): for s in xrange(S): solver_name = run_data.solver_names[s] for b in xrange(B): yield (model_name, instance, solver_name, b, predicted[s, b]) yield ("observed", instance, solver_name, b, observed[s, b]) yield ("true", instance, solver_name, b, true[s, b]) return list(yield_rows()) @borg.annotations( out_path = ("results output path"), bundle = ("path to pre-recorded runs", "positional", None, os.path.abspath), experiments = ("path to experiments JSON", "positional", None, borg.util.load_json), workers = ("submit jobs?", "option", "w", int), local = ("workers are local?", "flag"), ) def main(out_path, bundle, experiments, workers = 0, local = False): """Write the actual output of multiple models.""" def yield_jobs(): run_data = borg.storage.RunData.from_bundle(bundle) for experiment in experiments: yield ( infer_distributions, [ run_data, experiment["model_name"], experiment["instance"], experiment["exclude"], ], ) with open(out_path, "w") as out_file: writer = csv.writer(out_file) writer.writerow(["model_name", "instance", "solver", "bin", "probability"]) for (_, row) in condor.do(yield_jobs(), workers, local): writer.writerows(row) if __name__ == "__main__": borg.script(main)
// Copyright (c) 2021 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or https://www.opensource.org/licenses/mit-license.php. #include "tiertwo/init.h" #include "budget/budgetdb.h" #include "guiinterface.h" #include "guiinterfaceutil.h" #include "masternodeman.h" #include "masternode-payments.h" #include "masternodeconfig.h" #include "validation.h" #include <boost/thread.hpp> // Sets the last CACHED_BLOCK_HASHES hashes into masternode manager cache static void LoadBlockHashesCache(CMasternodeMan& man) { LOCK(cs_main); const CBlockIndex* pindex = chainActive.Tip(); unsigned int inserted = 0; while (pindex && inserted < CACHED_BLOCK_HASHES) { man.CacheBlockHash(pindex); pindex = pindex->pprev; ++inserted; } } bool LoadTierTwo(int chain_active_height) { // ################################# // // ## Legacy Masternodes Manager ### // // ################################# // uiInterface.InitMessage(_("Loading masternode cache...")); mnodeman.SetBestHeight(chain_active_height); LoadBlockHashesCache(mnodeman); CMasternodeDB mndb; CMasternodeDB::ReadResult readResult = mndb.Read(mnodeman); if (readResult == CMasternodeDB::FileError) LogPrintf("Missing masternode cache file - mncache.dat, will try to recreate\n"); else if (readResult != CMasternodeDB::Ok) { LogPrintf("Error reading mncache.dat - cached data discarded\n"); } // ##################### // // ## Budget Manager ### // // ##################### // uiInterface.InitMessage(_("Loading budget cache...")); CBudgetDB budgetdb; const bool fDryRun = (chain_active_height <= 0); if (!fDryRun) g_budgetman.SetBestHeight(chain_active_height); CBudgetDB::ReadResult readResult2 = budgetdb.Read(g_budgetman, fDryRun); if (readResult2 == CBudgetDB::FileError) LogPrintf("Missing budget cache - budget.dat, will try to recreate\n"); else if (readResult2 != CBudgetDB::Ok) { LogPrintf("Error reading budget.dat - cached data discarded\n"); } // flag our cached items so we send them to our peers g_budgetman.ResetSync(); g_budgetman.ReloadMapSeen(); // ######################################### // // ## Legacy Masternodes-Payments Manager ## // // ######################################### // uiInterface.InitMessage(_("Loading masternode payment cache...")); CMasternodePaymentDB mnpayments; CMasternodePaymentDB::ReadResult readResult3 = mnpayments.Read(masternodePayments); if (readResult3 == CMasternodePaymentDB::FileError) LogPrintf("Missing masternode payment cache - mnpayments.dat, will try to recreate\n"); else if (readResult3 != CMasternodePaymentDB::Ok) { LogPrintf("Error reading mnpayments.dat - cached data discarded\n"); } return true; } void RegisterTierTwoValidationInterface() { RegisterValidationInterface(&g_budgetman); RegisterValidationInterface(&masternodePayments); if (activeMasternodeManager) RegisterValidationInterface(activeMasternodeManager); } void DumpTierTwo() { DumpMasternodes(); DumpBudgets(g_budgetman); DumpMasternodePayments(); } void SetBudgetFinMode(const std::string& mode) { g_budgetman.strBudgetMode = mode; LogPrintf("Budget Mode %s\n", g_budgetman.strBudgetMode); } bool InitActiveMN() { fMasterNode = gArgs.GetBoolArg("-masternode", DEFAULT_MASTERNODE); if ((fMasterNode || masternodeConfig.getCount() > -1) && fTxIndex == false) { return UIError(strprintf(_("Enabling Masternode support requires turning on transaction indexing." "Please add %s to your configuration and start with %s"), "txindex=1", "-reindex")); } if (fMasterNode) { const std::string& mnoperatorkeyStr = gArgs.GetArg("-mnoperatorprivatekey", ""); const bool fDeterministic = !mnoperatorkeyStr.empty(); LogPrintf("IS %s MASTERNODE\n", (fDeterministic ? "DETERMINISTIC " : "")); if (fDeterministic) { // Check enforcement if (!deterministicMNManager->IsDIP3Enforced()) { const std::string strError = strprintf( _("Cannot start deterministic masternode before enforcement. Remove %s to start as legacy masternode"), "-mnoperatorprivatekey"); LogPrintf("-- ERROR: %s\n", strError); return UIError(strError); } // Create and register activeMasternodeManager activeMasternodeManager = new CActiveDeterministicMasternodeManager(); auto res = activeMasternodeManager->SetOperatorKey(mnoperatorkeyStr); if (!res) { return UIError(res.getError()); } // Init active masternode const CBlockIndex* pindexTip = WITH_LOCK(cs_main, return chainActive.Tip();); activeMasternodeManager->Init(pindexTip); } else { // Check enforcement if (deterministicMNManager->LegacyMNObsolete()) { const std::string strError = strprintf( _("Legacy masternode system disabled. Use %s to start as deterministic masternode"), "-mnoperatorprivatekey"); LogPrintf("-- ERROR: %s\n", strError); return UIError(strError); } auto res = initMasternode(gArgs.GetArg("-masternodeprivkey", ""), gArgs.GetArg("-masternodeaddr", ""), true); if (!res) { return UIError(res.getError()); } } } // All good return true; } void StartTierTwoThreadsAndScheduleJobs(boost::thread_group& threadGroup, CScheduler& scheduler) { threadGroup.create_thread(std::bind(&ThreadCheckMasternodes)); }
(* Title: ZF/AC/Cardinal_aux.thy Author: Krzysztof Grabczewski Auxiliary lemmas concerning cardinalities. *) theory Cardinal_aux imports AC_Equiv begin lemma Diff_lepoll: "\<lbrakk>A \<lesssim> succ(m); B \<subseteq> A; B\<noteq>0\<rbrakk> \<Longrightarrow> A-B \<lesssim> m" apply (rule not_emptyE, assumption) apply (blast intro: lepoll_trans [OF subset_imp_lepoll Diff_sing_lepoll]) done (* ********************************************************************** *) (* Lemmas involving ordinals and cardinalities used in the proofs *) (* concerning AC16 and DC *) (* ********************************************************************** *) (* j=|A| *) lemma lepoll_imp_ex_le_eqpoll: "\<lbrakk>A \<lesssim> i; Ord(i)\<rbrakk> \<Longrightarrow> \<exists>j. j \<le> i \<and> A \<approx> j" by (blast intro!: lepoll_cardinal_le well_ord_Memrel well_ord_cardinal_eqpoll [THEN eqpoll_sym] dest: lepoll_well_ord) (* j=|A| *) lemma lesspoll_imp_ex_lt_eqpoll: "\<lbrakk>A \<prec> i; Ord(i)\<rbrakk> \<Longrightarrow> \<exists>j. j<i \<and> A \<approx> j" by (unfold lesspoll_def, blast dest!: lepoll_imp_ex_le_eqpoll elim!: leE) lemma Un_eqpoll_Inf_Ord: assumes A: "A \<approx> i" and B: "B \<approx> i" and NFI: "\<not> Finite(i)" and i: "Ord(i)" shows "A \<union> B \<approx> i" proof (rule eqpollI) have AB: "A \<approx> B" using A B by (blast intro: eqpoll_sym eqpoll_trans) have "2 \<lesssim> nat" by (rule subset_imp_lepoll) (rule OrdmemD [OF nat_2I Ord_nat]) also have "... \<lesssim> i" by (simp add: nat_le_infinite_Ord le_imp_lepoll NFI i)+ also have "... \<approx> A" by (blast intro: eqpoll_sym A) finally have "2 \<lesssim> A" . have ICI: "InfCard(|i|)" by (simp add: Inf_Card_is_InfCard Finite_cardinal_iff NFI i) have "A \<union> B \<lesssim> A + B" by (rule Un_lepoll_sum) also have "... \<lesssim> A \<times> B" by (rule lepoll_imp_sum_lepoll_prod [OF AB [THEN eqpoll_imp_lepoll] \<open>2 \<lesssim> A\<close>]) also have "... \<approx> i \<times> i" by (blast intro: prod_eqpoll_cong eqpoll_imp_lepoll A B) also have "... \<approx> i" by (blast intro: well_ord_InfCard_square_eq well_ord_Memrel ICI i) finally show "A \<union> B \<lesssim> i" . next have "i \<approx> A" by (blast intro: A eqpoll_sym) also have "... \<lesssim> A \<union> B" by (blast intro: subset_imp_lepoll) finally show "i \<lesssim> A \<union> B" . qed schematic_goal paired_bij: "?f \<in> bij({{y,z}. y \<in> x}, x)" apply (rule RepFun_bijective) apply (simp add: doubleton_eq_iff, blast) done lemma paired_eqpoll: "{{y,z}. y \<in> x} \<approx> x" by (unfold eqpoll_def, fast intro!: paired_bij) lemma ex_eqpoll_disjoint: "\<exists>B. B \<approx> A \<and> B \<inter> C = 0" by (fast intro!: paired_eqpoll equals0I elim: mem_asym) (*Finally we reach this result. Surely there's a simpler proof?*) lemma Un_lepoll_Inf_Ord: "\<lbrakk>A \<lesssim> i; B \<lesssim> i; \<not>Finite(i); Ord(i)\<rbrakk> \<Longrightarrow> A \<union> B \<lesssim> i" apply (rule_tac A1 = i and C1 = i in ex_eqpoll_disjoint [THEN exE]) apply (erule conjE) apply (drule lepoll_trans) apply (erule eqpoll_sym [THEN eqpoll_imp_lepoll]) apply (rule Un_lepoll_Un [THEN lepoll_trans], (assumption+)) apply (blast intro: eqpoll_refl Un_eqpoll_Inf_Ord eqpoll_imp_lepoll) done lemma Least_in_Ord: "\<lbrakk>P(i); i \<in> j; Ord(j)\<rbrakk> \<Longrightarrow> (\<mu> i. P(i)) \<in> j" apply (erule Least_le [THEN leE]) apply (erule Ord_in_Ord, assumption) apply (erule ltE) apply (fast dest: OrdmemD) apply (erule subst_elem, assumption) done lemma Diff_first_lepoll: "\<lbrakk>well_ord(x,r); y \<subseteq> x; y \<lesssim> succ(n); n \<in> nat\<rbrakk> \<Longrightarrow> y - {THE b. first(b,y,r)} \<lesssim> n" apply (case_tac "y=0", simp add: empty_lepollI) apply (fast intro!: Diff_sing_lepoll the_first_in) done lemma UN_subset_split: "(\<Union>x \<in> X. P(x)) \<subseteq> (\<Union>x \<in> X. P(x)-Q(x)) \<union> (\<Union>x \<in> X. Q(x))" by blast lemma UN_sing_lepoll: "Ord(a) \<Longrightarrow> (\<Union>x \<in> a. {P(x)}) \<lesssim> a" unfolding lepoll_def apply (rule_tac x = "\<lambda>z \<in> (\<Union>x \<in> a. {P (x) }) . (\<mu> i. P (i) =z) " in exI) apply (rule_tac d = "\<lambda>z. P (z) " in lam_injective) apply (fast intro!: Least_in_Ord) apply (fast intro: LeastI elim!: Ord_in_Ord) done lemma UN_fun_lepoll_lemma [rule_format]: "\<lbrakk>well_ord(T, R); \<not>Finite(a); Ord(a); n \<in> nat\<rbrakk> \<Longrightarrow> \<forall>f. (\<forall>b \<in> a. f`b \<lesssim> n \<and> f`b \<subseteq> T) \<longrightarrow> (\<Union>b \<in> a. f`b) \<lesssim> a" apply (induct_tac "n") apply (rule allI) apply (rule impI) apply (rule_tac b = "\<Union>b \<in> a. f`b" in subst) apply (rule_tac [2] empty_lepollI) apply (rule equals0I [symmetric], clarify) apply (fast dest: lepoll_0_is_0 [THEN subst]) apply (rule allI) apply (rule impI) apply (erule_tac x = "\<lambda>x \<in> a. f`x - {THE b. first (b,f`x,R) }" in allE) apply (erule impE, simp) apply (fast intro!: Diff_first_lepoll, simp) apply (rule UN_subset_split [THEN subset_imp_lepoll, THEN lepoll_trans]) apply (fast intro: Un_lepoll_Inf_Ord UN_sing_lepoll) done lemma UN_fun_lepoll: "\<lbrakk>\<forall>b \<in> a. f`b \<lesssim> n \<and> f`b \<subseteq> T; well_ord(T, R); \<not>Finite(a); Ord(a); n \<in> nat\<rbrakk> \<Longrightarrow> (\<Union>b \<in> a. f`b) \<lesssim> a" by (blast intro: UN_fun_lepoll_lemma) lemma UN_lepoll: "\<lbrakk>\<forall>b \<in> a. F(b) \<lesssim> n \<and> F(b) \<subseteq> T; well_ord(T, R); \<not>Finite(a); Ord(a); n \<in> nat\<rbrakk> \<Longrightarrow> (\<Union>b \<in> a. F(b)) \<lesssim> a" apply (rule rev_mp) apply (rule_tac f="\<lambda>b \<in> a. F (b)" in UN_fun_lepoll) apply auto done lemma UN_eq_UN_Diffs: "Ord(a) \<Longrightarrow> (\<Union>b \<in> a. F(b)) = (\<Union>b \<in> a. F(b) - (\<Union>c \<in> b. F(c)))" apply (rule equalityI) prefer 2 apply fast apply (rule subsetI) apply (erule UN_E) apply (rule UN_I) apply (rule_tac P = "\<lambda>z. x \<in> F (z) " in Least_in_Ord, (assumption+)) apply (rule DiffI, best intro: Ord_in_Ord LeastI, clarify) apply (erule_tac P = "\<lambda>z. x \<in> F (z) " and i = c in less_LeastE) apply (blast intro: Ord_Least ltI) done lemma lepoll_imp_eqpoll_subset: "a \<lesssim> X \<Longrightarrow> \<exists>Y. Y \<subseteq> X \<and> a \<approx> Y" apply (unfold lepoll_def eqpoll_def, clarify) apply (blast intro: restrict_bij dest: inj_is_fun [THEN fun_is_rel, THEN image_subset]) done (* ********************************************************************** *) (* Diff_lesspoll_eqpoll_Card *) (* ********************************************************************** *) lemma Diff_lesspoll_eqpoll_Card_lemma: "\<lbrakk>A\<approx>a; \<not>Finite(a); Card(a); B \<prec> a; A-B \<prec> a\<rbrakk> \<Longrightarrow> P" apply (elim lesspoll_imp_ex_lt_eqpoll [THEN exE] Card_is_Ord conjE) apply (frule_tac j=xa in Un_upper1_le [OF lt_Ord lt_Ord], assumption) apply (frule_tac j=xa in Un_upper2_le [OF lt_Ord lt_Ord], assumption) apply (drule Un_least_lt, assumption) apply (drule eqpoll_imp_lepoll [THEN lepoll_trans], rule le_imp_lepoll, assumption)+ apply (case_tac "Finite(x \<union> xa)") txt\<open>finite case\<close> apply (drule Finite_Un [OF lepoll_Finite lepoll_Finite], assumption+) apply (drule subset_Un_Diff [THEN subset_imp_lepoll, THEN lepoll_Finite]) apply (fast dest: eqpoll_sym [THEN eqpoll_imp_lepoll, THEN lepoll_Finite]) txt\<open>infinite case\<close> apply (drule Un_lepoll_Inf_Ord, (assumption+)) apply (blast intro: le_Ord2) apply (drule lesspoll_trans1 [OF subset_Un_Diff [THEN subset_imp_lepoll, THEN lepoll_trans] lt_Card_imp_lesspoll], assumption+) apply (simp add: lesspoll_def) done lemma Diff_lesspoll_eqpoll_Card: "\<lbrakk>A \<approx> a; \<not>Finite(a); Card(a); B \<prec> a\<rbrakk> \<Longrightarrow> A - B \<approx> a" apply (rule ccontr) apply (rule Diff_lesspoll_eqpoll_Card_lemma, (assumption+)) apply (blast intro: lesspoll_def [THEN def_imp_iff, THEN iffD2] subset_imp_lepoll eqpoll_imp_lepoll lepoll_trans) done end
section \<open> Incubator \<close> theory Incubator_locales imports "Z_Machines.Z_Machine" "HOL-Library.Code_Target_Int" begin consts MAX_TEMP :: \<nat> consts MIN_TEMP :: \<nat> definition "TEMP = {MIN_TEMP..MAX_TEMP}" def_consts MAX_TEMP = 30 MIN_TEMP = 15 zstore IncubatorMonitor = temp :: \<nat> where mintemp: "MIN_TEMP \<le> temp" maxtemp: "temp \<le> MAX_TEMP" zoperation Increment = over IncubatorMonitor pre "temp < MAX_TEMP" update "[temp\<Zprime> = temp + 1]" lemma Increment_correct: "\<^bold>{IncubatorMonitor_inv\<^bold>} Increment() \<^bold>{IncubatorMonitor_inv\<^bold>}" proof zpog fix temp assume pres: "temp < MAX_TEMP" and inv: "IncubatorMonitor temp" then interpret IncubatorMonitor temp by simp show "IncubatorMonitor (Suc temp )" proof show "MIN_TEMP \<le> Suc temp" using mintemp by auto show "Suc temp \<le> MAX_TEMP" using pres by auto qed qed zoperation Decrement = over IncubatorMonitor pre "temp > MIN_TEMP" \<comment> \<open> Change to @{term "(temp \<ge> MIN_TEMP)\<^sub>e"} to break the invariant \<close> update "[temp\<Zprime> = temp - 1]" lemma Decrement_correct: "\<^bold>{IncubatorMonitor_inv\<^bold>} Decrement() \<^bold>{IncubatorMonitor_inv\<^bold>}" by (zpog_full; simp) zoperation GetTemp = over IncubatorMonitor params currentTemp \<in> TEMP where "temp = currentTemp" lemma GetTemp_correct: "\<^bold>{IncubatorMonitor_inv\<^bold>} GetTemp v \<^bold>{IncubatorMonitor_inv\<^bold>}" by zpog_full zmachine Incubator = init "[temp \<leadsto> 20]" operations Increment Decrement GetTemp animate Incubator end
theory "Coincidence" imports Ordinary_Differential_Equations.ODE_Analysis "Ids" "Lib" "Syntax" "Denotational_Semantics" "Frechet_Correctness" "Static_Semantics" begin section \<open>Coincidence Theorems and Corollaries\<close> text \<open>This section proves coincidence: semantics of terms, odes, formulas and programs depend only on the free variables. This is one of the major lemmas for the correctness of uniform substitutions. Along the way, we also prove the equivalence between two similar, but different semantics for ODE programs: It does not matter whether the semantics of ODE's insist on the existence of a solution that agrees with the start state on all variables vs. one that agrees only on the variables that are actually relevant to the ODE. This is proven here by simultaneous induction with the coincidence theorem for the following reason: The reason for having two different semantics is that some proofs are easier with one semantics and other proofs are easier with the other definition. The coincidence proof is either with the more complicated definition, which should not be used as the main definition because it would make the specification for the dL semantics significantly larger, effectively increasing the size of the trusted core. However, that the proof of equivalence between the semantics using the coincidence lemma for formulas. In order to use the coincidence proof in the equivalence proof and the equivalence proof in the coincidence proof, they are proved by simultaneous induction. \<close> subsection \<open>Term Coincidence Theorems\<close> lemma coincidence_sterm:"Vagree \<nu> \<nu>' (FVT \<theta>) \<Longrightarrow> sterm_sem I \<theta> (fst \<nu>) = sterm_sem I \<theta> (fst \<nu>')" apply(induct "\<theta>") (* 7 subgoals *) apply(auto simp add: Vagree_def) by (meson rangeI) lemma coincidence_sterm':"dfree \<theta> \<Longrightarrow> Vagree \<nu> \<nu>' (FVT \<theta>) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>} \<Longrightarrow> sterm_sem I \<theta> (fst \<nu>) = sterm_sem J \<theta> (fst \<nu>')" proof (induction rule: dfree.induct) case (dfree_Fun i args ) then show ?case proof (auto) from dfree_Fun.IH have free:"(\<And>i. dfree (args i))" and IH:"(\<And>i. Vagree \<nu> \<nu>' (FVT (args i)) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT (args i)} \<Longrightarrow> sterm_sem I (args i) (fst \<nu>) = sterm_sem J (args i) (fst \<nu>'))" by auto from dfree_Fun.prems have VA:"Vagree \<nu> \<nu>' (\<Union>i. FVT (args i))" and IA:"Iagree I J {Inl x |x. x = i \<or> (\<exists>xa. x \<in> SIGT (args xa))}" by auto from IA have IAorig:"Iagree I J {Inl x |x. x \<in> SIGT (Function i args)}" by auto from Iagree_Func[OF IAorig] have eqF:"Functions I i = Functions J i" by auto have Vsubs:"\<And>i. FVT (args i) \<subseteq> (\<Union>i. FVT (args i))" by auto from VA have VAs:"\<And>i. Vagree \<nu> \<nu>' (FVT (args i))" using agree_sub[OF Vsubs] by auto have Isubs:"\<And>j. {Inl x |x. x \<in> SIGT (args j)} \<subseteq> {Inl x |x. x \<in> SIGT (Function i args)}" by auto from IA have IAs:"\<And>i. Iagree I J {Inl x |x. x \<in> SIGT (args i)}" using Iagree_sub[OF Isubs] by auto show "Functions I i (\<chi> i. sterm_sem I (args i) (fst \<nu>)) = Functions J i (\<chi> i. sterm_sem J (args i) (fst \<nu>'))" using IH[OF VAs IAs] eqF by auto qed next case (dfree_Plus \<theta>\<^sub>1 \<theta>\<^sub>2) then show ?case proof (auto) assume "dfree \<theta>\<^sub>1" "dfree \<theta>\<^sub>2" and IH1:"(Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1} \<Longrightarrow> sterm_sem I \<theta>\<^sub>1 (fst \<nu>) = sterm_sem J \<theta>\<^sub>1 (fst \<nu>'))" and IH2:"(Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>2) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>2} \<Longrightarrow> sterm_sem I \<theta>\<^sub>2 (fst \<nu>) = sterm_sem J \<theta>\<^sub>2 (fst \<nu>'))" and VA:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1 \<union> FVT \<theta>\<^sub>2)" and IA:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1 \<or> x \<in> SIGT \<theta>\<^sub>2}" from VA have VAs:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1)" "Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>2)" unfolding Vagree_def by auto have Isubs:"{Inl x |x. x \<in> SIGT \<theta>\<^sub>1} \<subseteq> {Inl x |x. x \<in> SIGT (Plus \<theta>\<^sub>1 \<theta>\<^sub>2)}" "{Inl x |x. x \<in> SIGT \<theta>\<^sub>2} \<subseteq> {Inl x |x. x \<in> SIGT (Plus \<theta>\<^sub>1 \<theta>\<^sub>2)}" by auto from IA have IAs:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1}" "Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>2}" using Iagree_sub[OF Isubs(1)] Iagree_sub[OF Isubs(2)] by auto show "sterm_sem I \<theta>\<^sub>1 (fst \<nu>) + sterm_sem I \<theta>\<^sub>2 (fst \<nu>) = sterm_sem J \<theta>\<^sub>1 (fst \<nu>') + sterm_sem J \<theta>\<^sub>2 (fst \<nu>')" using IH1[OF VAs(1) IAs(1)] IH2[OF VAs(2) IAs(2)] by auto qed next case (dfree_Times \<theta>\<^sub>1 \<theta>\<^sub>2) then show ?case proof (auto) assume "dfree \<theta>\<^sub>1" "dfree \<theta>\<^sub>2" and IH1:"(Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1} \<Longrightarrow> sterm_sem I \<theta>\<^sub>1 (fst \<nu>) = sterm_sem J \<theta>\<^sub>1 (fst \<nu>'))" and IH2:"(Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>2) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>2} \<Longrightarrow> sterm_sem I \<theta>\<^sub>2 (fst \<nu>) = sterm_sem J \<theta>\<^sub>2 (fst \<nu>'))" and VA:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1 \<union> FVT \<theta>\<^sub>2)" and IA:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1 \<or> x \<in> SIGT \<theta>\<^sub>2}" from VA have VAs:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1)" "Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>2)" unfolding Vagree_def by auto have Isubs:"{Inl x |x. x \<in> SIGT \<theta>\<^sub>1} \<subseteq> {Inl x |x. x \<in> SIGT (Times \<theta>\<^sub>1 \<theta>\<^sub>2)}" "{Inl x |x. x \<in> SIGT \<theta>\<^sub>2} \<subseteq> {Inl x |x. x \<in> SIGT (Times \<theta>\<^sub>1 \<theta>\<^sub>2)}" by auto from IA have IAs:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1}" "Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>2}" using Iagree_sub[OF Isubs(1)] Iagree_sub[OF Isubs(2)] by auto show "sterm_sem I \<theta>\<^sub>1 (fst \<nu>) * sterm_sem I \<theta>\<^sub>2 (fst \<nu>) = sterm_sem J \<theta>\<^sub>1 (fst \<nu>') * sterm_sem J \<theta>\<^sub>2 (fst \<nu>')" using IH1[OF VAs(1) IAs(1)] IH2[OF VAs(2) IAs(2)] by auto qed qed (unfold Vagree_def Iagree_def, auto) lemma coincidence_frechet : fixes I :: "interp" and \<nu> :: "state" and \<nu>'::"state" shows "dfree \<theta> \<Longrightarrow> Vagree \<nu> \<nu>' (FVDiff \<theta>) \<Longrightarrow> frechet I \<theta> (fst \<nu>) (snd \<nu>) = frechet I \<theta> (fst \<nu>') (snd \<nu>')" proof (induction rule: dfree.induct) case dfree_Var then show ?case by (auto simp: inner_prod_eq Vagree_def) next case dfree_Const then show ?case by auto next case (dfree_Fun var args) have free:"(\<And>i. dfree (args i))" and IH:"(\<And>i. Vagree \<nu> \<nu>' (FVDiff (args i)) \<Longrightarrow> frechet I (args i) (fst \<nu>) (snd \<nu>) = frechet I (args i) (fst \<nu>') (snd \<nu>'))" and agree:"Vagree \<nu> \<nu>' (FVDiff ($f var args))" using dfree_Fun.IH dfree_Fun.prems by auto have frees:"(\<And>i. dfree (args i))" using free by (auto simp add: rangeI) have agrees:"\<And>i. Vagree \<nu> \<nu>' (FVDiff (args i))" using agree agree_func by metis have agrees':"\<And>i. Vagree \<nu> \<nu>' (FVT (args i))" subgoal for i using agrees[of i] FVDiff_sub[of "args i"] unfolding Vagree_def by blast done have sterms:"\<And>i. sterm_sem I (args i) (fst \<nu>) = sterm_sem I (args i) (fst \<nu>')" by (rule coincidence_sterm[of "\<nu>" "\<nu>'", OF agrees']) have frechets:"\<And>i. frechet I (args i) (fst \<nu>) (snd \<nu>) = frechet I (args i) (fst \<nu>') (snd \<nu>')" using IH agrees frees rangeI by blast show "?case" using agrees sterms frechets by (auto) next case (dfree_Neg t) assume dfree1:"dfree t" assume IH1:"(Vagree \<nu> \<nu>' (FVDiff t) \<Longrightarrow> frechet I t (fst \<nu>) (snd \<nu>) = frechet I t (fst \<nu>') (snd \<nu>'))" assume agree:"Vagree \<nu> \<nu>' (FVDiff (Neg t))" have agree1:"Vagree \<nu> \<nu>' (FVDiff t)" using agree agree_neg by (blast) have IH1':"(frechet I t (fst \<nu>) (snd \<nu>) = frechet I t (fst \<nu>') (snd \<nu>'))" using IH1 agree1 by (auto) show "?case" by (metis FVT.simps(4) IH1' UnCI Vagree_def coincidence_sterm frechet.simps(3) mem_Collect_eq) next case (dfree_Plus t1 t2) assume dfree1:"dfree t1" assume IH1:"(Vagree \<nu> \<nu>' (FVDiff t1) \<Longrightarrow> frechet I t1 (fst \<nu>) (snd \<nu>) = frechet I t1 (fst \<nu>') (snd \<nu>'))" assume dfree2:"dfree t2" assume IH2:"(Vagree \<nu> \<nu>' (FVDiff t2) \<Longrightarrow> frechet I t2 (fst \<nu>) (snd \<nu>) = frechet I t2 (fst \<nu>') (snd \<nu>'))" assume agree:"Vagree \<nu> \<nu>' (FVDiff (Plus t1 t2))" have agree1:"Vagree \<nu> \<nu>' (FVDiff t1)" using agree agree_plus1 by (blast) have agree2:"Vagree \<nu> \<nu>' (FVDiff t2)" using agree agree_plus2 by (blast) have IH1':"(frechet I t1 (fst \<nu>) (snd \<nu>) = frechet I t1 (fst \<nu>') (snd \<nu>'))" using IH1 agree1 by (auto) have IH2':"(frechet I t2 (fst \<nu>) (snd \<nu>) = frechet I t2 (fst \<nu>') (snd \<nu>'))" using IH2 agree2 by (auto) show "?case" by(metis FVT_Plus IH1' IH2' UnCI Vagree_def coincidence_sterm Frechet_Plus mem_Collect_eq) next case (dfree_Times t1 t2) assume dfree1:"dfree t1" assume IH1:"(Vagree \<nu> \<nu>' (FVDiff t1) \<Longrightarrow> frechet I t1 (fst \<nu>) (snd \<nu>) = frechet I t1 (fst \<nu>') (snd \<nu>'))" assume dfree2:"dfree t2" assume IH2:"(Vagree \<nu> \<nu>' (FVDiff t2) \<Longrightarrow> frechet I t2 (fst \<nu>) (snd \<nu>) = frechet I t2 (fst \<nu>') (snd \<nu>'))" assume agree:"Vagree \<nu> \<nu>' (FVDiff (Times t1 t2))" have agree1:"Vagree \<nu> \<nu>' (FVDiff t1)" using agree agree_times1 by blast have agree2:"Vagree \<nu> \<nu>' (FVDiff t2)" using agree agree_times2 by blast have agree1':"Vagree \<nu> \<nu>' (FVT t1)" using agree1 apply(auto simp add: Vagree_def) using primify_contains by blast+ have agree2':"Vagree \<nu> \<nu>' (FVT t2)" using agree2 apply(auto simp add: Vagree_def) using primify_contains by blast+ have IH1':"(frechet I t1 (fst \<nu>) (snd \<nu>) = frechet I t1 (fst \<nu>') (snd \<nu>'))" using IH1 agree1 by (auto) have IH2':"(frechet I t2 (fst \<nu>) (snd \<nu>) = frechet I t2 (fst \<nu>') (snd \<nu>'))" using IH2 agree2 by (auto) have almost:"Vagree \<nu> \<nu>' (FVT (Times t1 t2)) \<Longrightarrow> frechet I (Times t1 t2) (fst \<nu>) (snd \<nu>) = frechet I (Times t1 t2) (fst \<nu>') (snd \<nu>')" by (auto simp add: UnCI Vagree_def agree IH1' IH2' coincidence_sterm[OF agree1', of I] coincidence_sterm[OF agree2', of I]) show "?case" using agree FVDiff_sub almost by (metis agree_supset) qed lemma coincidence_frechet' : fixes I J :: "interp" and \<nu> :: "state" and \<nu>'::"state" shows "dfree \<theta> \<Longrightarrow> Vagree \<nu> \<nu>' (FVDiff \<theta>) \<Longrightarrow> Iagree I J {Inl x | x. x \<in> (SIGT \<theta>)} \<Longrightarrow> frechet I \<theta> (fst \<nu>) (snd \<nu>) = frechet J \<theta> (fst \<nu>') (snd \<nu>')" proof (induction rule: dfree.induct) case dfree_Var then show ?case by (auto simp: inner_prod_eq Vagree_def) next case dfree_Const then show ?case by auto next case (dfree_Fun var args) have free:"(\<And>i. dfree (args i))" and IH:"(\<And>i. Vagree \<nu> \<nu>' (FVDiff (args i)) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT (args i)} \<Longrightarrow> frechet I (args i) (fst \<nu>) (snd \<nu>) = frechet J (args i) (fst \<nu>') (snd \<nu>'))" and agree:"Vagree \<nu> \<nu>' (FVDiff ($f var args))" and IA:"Iagree I J {Inl x |x. x \<in> SIGT ($f var args)}" using dfree_Fun.IH dfree_Fun.prems by auto have frees:"(\<And>i. dfree (args i))" using free by (auto simp add: rangeI) have agrees:"\<And>i. Vagree \<nu> \<nu>' (FVDiff (args i))" using agree agree_func by metis then have agrees':"\<And>i. Vagree \<nu> \<nu>' (FVT (args i))" using agrees FVDiff_sub by (metis agree_sub) from Iagree_Func [OF IA ]have fEq:"Functions I var = Functions J var" by auto have subs:"\<And>i.{Inl x |x. x \<in> SIGT (args i)} \<subseteq> {Inl x |x. x \<in> SIGT ($f var args)}" by auto from IA have IAs:"\<And>i. Iagree I J {Inl x |x. x \<in> SIGT (args i)}" using Iagree_sub[OF subs] by auto have sterms:"\<And>i. sterm_sem I (args i) (fst \<nu>) = sterm_sem J (args i) (fst \<nu>')" subgoal for i using frees agrees' coincidence_sterm'[of "args i" \<nu> \<nu>' I J] IAs by (auto) done have frechets:"\<And>i. frechet I (args i) (fst \<nu>) (snd \<nu>) = frechet J (args i) (fst \<nu>') (snd \<nu>')" using IH[OF agrees IAs] agrees frees rangeI by blast show "?case" using agrees agrees' sterms frechets fEq by auto next case (dfree_Neg t1) assume dfree1:"dfree t1" assume IH1:"(Vagree \<nu> \<nu>' (FVDiff t1) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT t1} \<Longrightarrow> frechet I t1 (fst \<nu>) (snd \<nu>) = frechet J t1 (fst \<nu>') (snd \<nu>'))" assume agree:"Vagree \<nu> \<nu>' (FVDiff (Neg t1))" assume IA:"Iagree I J {Inl x |x. x \<in> SIGT (Neg t1)}" have subs:"{Inl x |x. x \<in> SIGT t1} \<subseteq> {Inl x |x. x \<in> SIGT (Neg t1)}" by auto from IA have IA1:"Iagree I J {Inl x |x. x \<in> SIGT t1}" using Iagree_sub[OF subs(1)] by auto have agree1:"Vagree \<nu> \<nu>' (FVDiff t1)" using agree agree_neg by (blast) have agree1':"Vagree \<nu> \<nu>' (FVT t1)" using agree1 primify_contains by (auto simp add: Vagree_def, metis) have IH1':"(frechet I t1 (fst \<nu>) (snd \<nu>) = frechet J t1 (fst \<nu>') (snd \<nu>'))" using IH1 agree1 IA1 by (auto) show "?case" using coincidence_sterm[OF agree1'] coincidence_sterm[OF agree1'] by (auto simp add: IH1' UnCI Vagree_def) next case (dfree_Plus t1 t2) assume dfree1:"dfree t1" assume dfree2:"dfree t2" assume IH1:"(Vagree \<nu> \<nu>' (FVDiff t1) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT t1} \<Longrightarrow> frechet I t1 (fst \<nu>) (snd \<nu>) = frechet J t1 (fst \<nu>') (snd \<nu>'))" assume IH2:"(Vagree \<nu> \<nu>' (FVDiff t2) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT t2} \<Longrightarrow> frechet I t2 (fst \<nu>) (snd \<nu>) = frechet J t2 (fst \<nu>') (snd \<nu>'))" assume agree:"Vagree \<nu> \<nu>' (FVDiff (Plus t1 t2))" assume IA:"Iagree I J {Inl x |x. x \<in> SIGT (Plus t1 t2)}" have subs:"{Inl x |x. x \<in> SIGT t1} \<subseteq> {Inl x |x. x \<in> SIGT (Plus t1 t2)}" "{Inl x |x. x \<in> SIGT t2} \<subseteq> {Inl x |x. x \<in> SIGT (Plus t1 t2)}" by auto from IA have IA1:"Iagree I J {Inl x |x. x \<in> SIGT t1}" and IA2:"Iagree I J {Inl x |x. x \<in> SIGT t2}" using Iagree_sub[OF subs(1)] Iagree_sub[OF subs(2)] by auto have agree1:"Vagree \<nu> \<nu>' (FVDiff t1)" using agree agree_plus1 by (blast) have agree2:"Vagree \<nu> \<nu>' (FVDiff t2)" using agree agree_plus2 by (blast) have agree1':"Vagree \<nu> \<nu>' (FVT t1)" using agree1 primify_contains by (auto simp add: Vagree_def, metis) have agree2':"Vagree \<nu> \<nu>' (FVT t2)" using agree2 primify_contains by (auto simp add: Vagree_def, metis) have IH1':"(frechet I t1 (fst \<nu>) (snd \<nu>) = frechet J t1 (fst \<nu>') (snd \<nu>'))" using IH1 agree1 IA1 by (auto) have IH2':"(frechet I t2 (fst \<nu>) (snd \<nu>) = frechet J t2 (fst \<nu>') (snd \<nu>'))" using IH2 agree2 IA2 by (auto) show "?case" using coincidence_sterm[OF agree1'] coincidence_sterm[OF agree1'] coincidence_sterm[OF agree2'] by (auto simp add: IH1' IH2' UnCI Vagree_def) next case (dfree_Times t1 t2) assume dfree1:"dfree t1" assume dfree2:"dfree t2" assume IH1:"(Vagree \<nu> \<nu>' (FVDiff t1) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT t1} \<Longrightarrow> frechet I t1 (fst \<nu>) (snd \<nu>) = frechet J t1 (fst \<nu>') (snd \<nu>'))" assume IH2:"(Vagree \<nu> \<nu>' (FVDiff t2) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT t2} \<Longrightarrow> frechet I t2 (fst \<nu>) (snd \<nu>) = frechet J t2 (fst \<nu>') (snd \<nu>'))" assume agree:"Vagree \<nu> \<nu>' (FVDiff (Times t1 t2))" assume IA:"Iagree I J {Inl x |x. x \<in> SIGT (Times t1 t2)}" have subs:"{Inl x |x. x \<in> SIGT t1} \<subseteq> {Inl x |x. x \<in> SIGT (Times t1 t2)}" "{Inl x |x. x \<in> SIGT t2} \<subseteq> {Inl x |x. x \<in> SIGT (Times t1 t2)}" by auto from IA have IA1:"Iagree I J {Inl x |x. x \<in> SIGT t1}" and IA2:"Iagree I J {Inl x |x. x \<in> SIGT t2}" using Iagree_sub[OF subs(1)] Iagree_sub[OF subs(2)] by auto have agree1:"Vagree \<nu> \<nu>' (FVDiff t1)" using agree agree_times1 by (blast) then have agree1':"Vagree \<nu> \<nu>' (FVT t1)" using agree1 primify_contains by (auto simp add: Vagree_def, metis) have agree2:"Vagree \<nu> \<nu>' (FVDiff t2)" using agree agree_times2 by (blast) then have agree2':"Vagree \<nu> \<nu>' (FVT t2)" using agree2 primify_contains by (auto simp add: Vagree_def, metis) have IH1':"(frechet I t1 (fst \<nu>) (snd \<nu>) = frechet J t1 (fst \<nu>') (snd \<nu>'))" using IH1 agree1 IA1 by (auto) have IH2':"(frechet I t2 (fst \<nu>) (snd \<nu>) = frechet J t2 (fst \<nu>') (snd \<nu>'))" using IH2 agree2 IA2 by (auto) note co1 = coincidence_sterm'[of "t1" \<nu> \<nu>' I J] and co2 = coincidence_sterm'[of "t2" \<nu> \<nu>' I J] show "?case" using co1 [OF dfree1 agree1' IA1] co2 [OF dfree2 agree2' IA2] IH1' IH2' by auto qed lemma coincidence_dterm: fixes I :: "interp" and \<nu> :: "state" and \<nu>'::"state" shows "dsafe \<theta> \<Longrightarrow> Vagree \<nu> \<nu>' (FVT \<theta>) \<Longrightarrow> dterm_sem I \<theta> \<nu> = dterm_sem I \<theta> \<nu>'" proof (induction rule: dsafe.induct) case (dsafe_Funl f) assume "Vagree \<nu> \<nu>' (FVT ($$F f))" then have agree:"Vagree \<nu> \<nu>' UNIV" by simp then show "?case" using agree_UNIV_eq[OF agree] by auto next case (dsafe_Fun f args) have safe:"(\<And>i. dsafe (args i))" and IH:"\<And>i. Vagree \<nu> \<nu>' (FVT (args i)) \<Longrightarrow> dterm_sem I (args i) \<nu> = dterm_sem I (args i) \<nu>'" and agree:"Vagree \<nu> \<nu>' (FVT ($f f args))" using dsafe_Fun.IH dsafe_Fun.prems by auto then have "\<And>i. Vagree \<nu> \<nu>' (FVT (args i))" using agree_func_fvt by (metis) then show "?case" using safe coincidence_sterm IH rangeI by (auto) qed (auto simp: Vagree_def directional_derivative_def coincidence_frechet) lemma coincidence_dterm': fixes I J :: "interp" and \<nu> :: "state" and \<nu>'::"state" shows "dsafe \<theta> \<Longrightarrow> Vagree \<nu> \<nu>' (FVT \<theta>) \<Longrightarrow> Iagree I J {Inl x | x. x \<in> (SIGT \<theta>)} \<Longrightarrow> dterm_sem I \<theta> \<nu> = dterm_sem J \<theta> \<nu>'" proof (induction rule: dsafe.induct) case (dsafe_Fun f args) then have safe:"(\<And>i. dsafe (args i))" and IH:"\<And>i. Vagree \<nu> \<nu>' (FVT (args i)) \<Longrightarrow> Iagree I J {Inl x | x. x \<in> (SIGT (args i))} \<Longrightarrow> dterm_sem I (args i) \<nu> = dterm_sem J (args i) \<nu>'" and agree:"Vagree \<nu> \<nu>' (FVT ($f f args))" and IA:"Iagree I J {Inl x |x. x \<in> SIGT ($f f args)}" by auto have subs:"\<And>i. {Inl x |x. x \<in> SIGT (args i)} \<subseteq> {Inl x |x. x \<in> SIGT ($f f args)}" by auto from IA have IAs: "\<And>i. Iagree I J {Inl x |x. x \<in> SIGT (args i)}" using Iagree_sub [OF subs IA] by auto from agree have agrees:"\<And>i. Vagree \<nu> \<nu>' (FVT (args i))" using agree_func_fvt by (metis) from Iagree_Func [OF IA] have fEq:"Functions I f = Functions J f" by auto then show "?case" using safe coincidence_sterm IH[OF agrees IAs] rangeI agrees fEq by (auto) next case (dsafe_Funl f) then have agree:"Vagree \<nu> \<nu>' (UNIV)" and IA:"Iagree I J {Inl x |x. x \<in> SIGT ($$F f)}" by auto from Iagree_Funl [OF IA] have fEq:"Funls I f = Funls J f" by auto then show "?case" using agree_UNIV_eq[OF agree] by auto next case (dsafe_Plus \<theta>\<^sub>1 \<theta>\<^sub>2) then have safe:"dsafe \<theta>\<^sub>1" "dsafe \<theta>\<^sub>2" and IH1:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1} \<Longrightarrow> dterm_sem I \<theta>\<^sub>1 \<nu> = dterm_sem J \<theta>\<^sub>1 \<nu>'" and IH2:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>2) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>2} \<Longrightarrow> dterm_sem I \<theta>\<^sub>2 \<nu> = dterm_sem J \<theta>\<^sub>2 \<nu>'" and VA:"Vagree \<nu> \<nu>' (FVT (Plus \<theta>\<^sub>1 \<theta>\<^sub>2))" and IA:"Iagree I J {Inl x |x. x \<in> SIGT (Plus \<theta>\<^sub>1 \<theta>\<^sub>2)}" by auto from VA have VA1:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1)" and VA2:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>2)" unfolding Vagree_def by auto have subs:"{Inl x |x. x \<in> SIGT \<theta>\<^sub>1} \<subseteq> {Inl x |x. x \<in> SIGT (Plus \<theta>\<^sub>1 \<theta>\<^sub>2)}" "{Inl x |x. x \<in> SIGT \<theta>\<^sub>2} \<subseteq> {Inl x |x. x \<in> SIGT (Plus \<theta>\<^sub>1 \<theta>\<^sub>2)}"by auto from IA have IA1:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1}" and IA2:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>2}" using Iagree_sub subs by auto then show ?case using IH1[OF VA1 IA1] IH2[OF VA2 IA2] by auto next case (dsafe_Times \<theta>\<^sub>1 \<theta>\<^sub>2) then have safe:"dsafe \<theta>\<^sub>1" "dsafe \<theta>\<^sub>2" and IH1:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1} \<Longrightarrow> dterm_sem I \<theta>\<^sub>1 \<nu> = dterm_sem J \<theta>\<^sub>1 \<nu>'" and IH2:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>2) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>2} \<Longrightarrow> dterm_sem I \<theta>\<^sub>2 \<nu> = dterm_sem J \<theta>\<^sub>2 \<nu>'" and VA:"Vagree \<nu> \<nu>' (FVT (Times \<theta>\<^sub>1 \<theta>\<^sub>2))" and IA:"Iagree I J {Inl x |x. x \<in> SIGT (Times \<theta>\<^sub>1 \<theta>\<^sub>2)}" by auto from VA have VA1:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1)" and VA2:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>2)" unfolding Vagree_def by auto have subs:"{Inl x |x. x \<in> SIGT \<theta>\<^sub>1} \<subseteq> {Inl x |x. x \<in> SIGT (Times \<theta>\<^sub>1 \<theta>\<^sub>2)}" "{Inl x |x. x \<in> SIGT \<theta>\<^sub>2} \<subseteq> {Inl x |x. x \<in> SIGT (Times \<theta>\<^sub>1 \<theta>\<^sub>2)}"by auto from IA have IA1:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1}" and IA2:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>2}" using Iagree_sub subs by auto then show ?case using IH1[OF VA1 IA1] IH2[OF VA2 IA2] by auto next case (dsafe_Div \<theta>\<^sub>1 \<theta>\<^sub>2) then have safe:"dsafe \<theta>\<^sub>1" "dsafe \<theta>\<^sub>2" and IH1:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1} \<Longrightarrow> dterm_sem I \<theta>\<^sub>1 \<nu> = dterm_sem J \<theta>\<^sub>1 \<nu>'" and IH2:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>2) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>2} \<Longrightarrow> dterm_sem I \<theta>\<^sub>2 \<nu> = dterm_sem J \<theta>\<^sub>2 \<nu>'" and VA:"Vagree \<nu> \<nu>' (FVT (Div \<theta>\<^sub>1 \<theta>\<^sub>2))" and IA:"Iagree I J {Inl x |x. x \<in> SIGT (Div \<theta>\<^sub>1 \<theta>\<^sub>2)}" by auto from VA have VA1:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1)" and VA2:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>2)" unfolding Vagree_def by auto have subs:"{Inl x |x. x \<in> SIGT \<theta>\<^sub>1} \<subseteq> {Inl x |x. x \<in> SIGT (Div \<theta>\<^sub>1 \<theta>\<^sub>2)}" "{Inl x |x. x \<in> SIGT \<theta>\<^sub>2} \<subseteq> {Inl x |x. x \<in> SIGT (Div \<theta>\<^sub>1 \<theta>\<^sub>2)}"by auto from IA have IA1:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1}" and IA2:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>2}" using Iagree_sub subs by auto then show ?case using IH1[OF VA1 IA1] IH2[OF VA2 IA2] by auto next case (dsafe_Max \<theta>\<^sub>1 \<theta>\<^sub>2) then have safe:"dsafe \<theta>\<^sub>1" "dsafe \<theta>\<^sub>2" and IH1:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1} \<Longrightarrow> dterm_sem I \<theta>\<^sub>1 \<nu> = dterm_sem J \<theta>\<^sub>1 \<nu>'" and IH2:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>2) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>2} \<Longrightarrow> dterm_sem I \<theta>\<^sub>2 \<nu> = dterm_sem J \<theta>\<^sub>2 \<nu>'" and VA:"Vagree \<nu> \<nu>' (FVT (trm.Max \<theta>\<^sub>1 \<theta>\<^sub>2))" and IA:"Iagree I J {Inl x |x. x \<in> SIGT (trm.Max \<theta>\<^sub>1 \<theta>\<^sub>2)}" by auto from VA have VA1:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1)" and VA2:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>2)" unfolding Vagree_def by auto have subs:"{Inl x |x. x \<in> SIGT \<theta>\<^sub>1} \<subseteq> {Inl x |x. x \<in> SIGT (Max \<theta>\<^sub>1 \<theta>\<^sub>2)}" "{Inl x |x. x \<in> SIGT \<theta>\<^sub>2} \<subseteq> {Inl x |x. x \<in> SIGT (Max \<theta>\<^sub>1 \<theta>\<^sub>2)}"by auto from IA have IA1:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1}" and IA2:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>2}" using Iagree_sub subs by auto then show ?case using IH1[OF VA1 IA1] IH2[OF VA2 IA2] by auto next case (dsafe_Min \<theta>\<^sub>1 \<theta>\<^sub>2) then have safe:"dsafe \<theta>\<^sub>1" "dsafe \<theta>\<^sub>2" and IH1:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1} \<Longrightarrow> dterm_sem I \<theta>\<^sub>1 \<nu> = dterm_sem J \<theta>\<^sub>1 \<nu>'" and IH2:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>2) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>2} \<Longrightarrow> dterm_sem I \<theta>\<^sub>2 \<nu> = dterm_sem J \<theta>\<^sub>2 \<nu>'" and VA:"Vagree \<nu> \<nu>' (FVT (trm.Min \<theta>\<^sub>1 \<theta>\<^sub>2))" and IA:"Iagree I J {Inl x |x. x \<in> SIGT (trm.Min \<theta>\<^sub>1 \<theta>\<^sub>2)}" by auto from VA have VA1:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>1)" and VA2:"Vagree \<nu> \<nu>' (FVT \<theta>\<^sub>2)" unfolding Vagree_def by auto have subs:"{Inl x |x. x \<in> SIGT \<theta>\<^sub>1} \<subseteq> {Inl x |x. x \<in> SIGT (Max \<theta>\<^sub>1 \<theta>\<^sub>2)}" "{Inl x |x. x \<in> SIGT \<theta>\<^sub>2} \<subseteq> {Inl x |x. x \<in> SIGT (Max \<theta>\<^sub>1 \<theta>\<^sub>2)}"by auto from IA have IA1:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>1}" and IA2:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>\<^sub>2}" using Iagree_sub subs by auto then show ?case using IH1[OF VA1 IA1] IH2[OF VA2 IA2] by auto next case (dsafe_Abs \<theta>) then have safe:"dsafe \<theta>" and IH1:"Vagree \<nu> \<nu>' (FVT \<theta>) \<Longrightarrow> Iagree I J {Inl x |x. x \<in> SIGT \<theta>} \<Longrightarrow> dterm_sem I \<theta> \<nu> = dterm_sem J \<theta> \<nu>'" and VA:"Vagree \<nu> \<nu>' (FVT (trm.Abs \<theta>))" and IA:"Iagree I J {Inl x |x. x \<in> SIGT (trm.Abs \<theta>)}" by auto from VA have VA1:"Vagree \<nu> \<nu>' (FVT \<theta>)" unfolding Vagree_def by auto have subs:"{Inl x |x. x \<in> SIGT \<theta>} \<subseteq> {Inl x |x. x \<in> SIGT (Abs \<theta>)}" by auto from IA have IA1:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>}" using Iagree_sub subs by auto then show ?case using IH1[OF VA1 IA1] by auto qed (auto simp: Vagree_def directional_derivative_def coincidence_frechet') subsection \<open>ODE Coincidence Theorems\<close> lemma coincidence_ode: fixes I J :: "interp" and \<nu> :: "state" and \<nu>'::"state" assumes goodI:"is_interp I" assumes goodJ:"is_interp J" shows "osafe ODE \<Longrightarrow> Vagree \<nu> \<nu>' (Inl ` FVO ODE) \<Longrightarrow> Iagree I J ({Inl x | x. Inl x \<in> SIGO ODE} \<union> {Inr (Inr x) | x. Inr x \<in> SIGO ODE}) \<Longrightarrow> ODE_sem I ODE (fst \<nu>) = ODE_sem J ODE (fst \<nu>')" proof (induction rule: osafe.induct) case (osafe_Var c sp) then show ?case proof (auto, cases sp, simp) assume sp:"sp = None" assume VA:"Vagree \<nu> \<nu>' (range Inl)" have eqV:"(fst \<nu>) = (fst \<nu>')" using agree_UNIV_fst[OF VA] by auto assume IA:"Iagree I J {Inr (Inr c)}" have eqIJ:"ODEs I c All = ODEs J c All" using Iagree_ODE[OF IA] by auto have eqbvIJ:"ODEBV I c All = ODEBV J c All" using Iagree_ODEBV[OF IA] by auto show "(\<lambda> i. if i \<in> ODEBV I c None then ODEs I c sp (fst \<nu>) $ i else 0) = (\<lambda> i. if i \<in> ODEBV J c None then ODEs J c sp (fst \<nu>') $ i else 0)" using sp eqV eqIJ eqbvIJ by (auto) next fix x assume sp:"sp = Some x" assume VA:"Vagree \<nu> \<nu>' (Inl ` FVO (OVar c sp))" then have VA:"Vagree \<nu> \<nu>' (range Inl)" using sp by auto have eqV:"(fst \<nu>) = (fst \<nu>')" using agree_UNIV_fst[OF VA] by auto assume IA:"Iagree I J {Inr (Inr c)}" have eqIJ:"ODEs I c (NB x) = ODEs J c (NB x)" using Iagree_ODE[OF IA] by auto have eqbvIJ:"ODEBV I c (NB x) = ODEBV J c (NB x)" using Iagree_ODEBV[OF IA] by auto have iBound:"\<And>ode x. ODEBV I ode (NB x) \<subseteq> - {x}" using goodI unfolding is_interp_def by auto have jBound:"\<And>ode x. ODEBV J ode (NB x) \<subseteq> - {x}" using goodJ unfolding is_interp_def by auto show "(\<lambda> i. if i \<in> ODEBV I c sp then ODEs I c sp (fst \<nu>) $ i else 0) = (\<lambda> i. if i \<in> ODEBV J c sp then ODEs J c sp (fst \<nu>') $ i else 0)" using sp eqV eqIJ eqbvIJ by(auto simp add: eqV eqIJ sp eqbvIJ) qed next case (osafe_Sing \<theta> x) then show ?case proof (auto) assume free:"dfree \<theta>" and VA:"Vagree \<nu> \<nu>' (insert (Inl x) (Inl ` {x. Inl x \<in> FVT \<theta>}))" and IA:"Iagree I J {Inl x |x. x \<in> SIGT \<theta>}" from VA have VA':"Vagree \<nu> \<nu>' {Inl x | x. Inl x \<in> FVT \<theta>}" unfolding Vagree_def by auto have agree_Lem:"\<And>\<theta>. dfree \<theta> \<Longrightarrow> Vagree \<nu> \<nu>' {Inl x | x. Inl x \<in> FVT \<theta>} \<Longrightarrow> Vagree \<nu> \<nu>' (FVT \<theta>)" subgoal for \<theta> apply(induction rule: dfree.induct) by(auto simp add: Vagree_def) done have trm:"sterm_sem I \<theta> (fst \<nu>) = sterm_sem J \<theta> (fst \<nu>')" using coincidence_sterm' free VA' IA agree_Lem[of \<theta>, OF free] by blast show "(\<lambda> i. if i = x then sterm_sem I \<theta> (fst \<nu>) else 0) = (\<lambda> i. if i = x then sterm_sem J \<theta> (fst \<nu>') else 0)" by (auto simp add: vec_eq_iff trm) qed next case (osafe_Prod ODE1 ODE2) then show ?case proof (auto) assume safe1:"osafe ODE1" and safe2:"osafe ODE2" and disjoint:"ODE_dom ODE1 \<inter> ODE_dom ODE2 = {}" and IH1:"Vagree \<nu> \<nu>' (Inl ` FVO ODE1) \<Longrightarrow> Iagree I J ({Inl x |x. Inl x \<in> SIGO ODE1} \<union> {Inr (Inr x) |x. Inr x \<in> SIGO ODE1}) \<Longrightarrow> ODE_sem I ODE1 (fst \<nu>) = ODE_sem J ODE1 (fst \<nu>')" and IH2:"Vagree \<nu> \<nu>' (Inl ` FVO ODE2) \<Longrightarrow> Iagree I J ({Inl x |x. Inl x \<in> SIGO ODE2} \<union> {Inr (Inr x) |x. Inr x \<in> SIGO ODE2}) \<Longrightarrow> ODE_sem I ODE2 (fst \<nu>) = ODE_sem J ODE2 (fst \<nu>')" and VA:"Vagree \<nu> \<nu>' (Inl ` (FVO ODE1 \<union> FVO ODE2))" and IA:"Iagree I J ({Inl x |x. Inl x \<in> SIGO ODE1 \<or> Inl x \<in> SIGO ODE2} \<union> {Inr (Inr x) |x. Inr x \<in> SIGO ODE1 \<or> Inr x \<in> SIGO ODE2})" let ?IA = "({Inl x |x. Inl x \<in> SIGO ODE1 \<or> Inl x \<in> SIGO ODE2} \<union> {Inr (Inr x) |x. Inr x \<in> SIGO ODE1 \<or> Inr x \<in> SIGO ODE2})" have FVsubs: "Inl ` FVO ODE2 \<subseteq> Inl ` (FVO ODE1 \<union> FVO ODE2)" "Inl ` FVO ODE1 \<subseteq> Inl ` (FVO ODE1 \<union> FVO ODE2)" by auto from VA have VA1:"Vagree \<nu> \<nu>' (Inl ` FVO ODE1)" and VA2:"Vagree \<nu> \<nu>' (Inl ` FVO ODE2)" using agree_sub[OF FVsubs(1)] agree_sub[OF FVsubs(2)] by (auto) have SIGsubs: "({Inl x |x. Inl x \<in> SIGO ODE1} \<union> {Inr (Inr x) |x. Inr x \<in> SIGO ODE1}) \<subseteq> ?IA" "({Inl x |x. Inl x \<in> SIGO ODE2} \<union> {Inr (Inr x) |x. Inr x \<in> SIGO ODE2}) \<subseteq> ?IA" by auto from IA have IA1:"Iagree I J ({Inl x |x. Inl x \<in> SIGO ODE1} \<union> {Inr (Inr x) |x. Inr x \<in> SIGO ODE1})" and IA2:"Iagree I J ({Inl x |x. Inl x \<in> SIGO ODE2} \<union> {Inr (Inr x) |x. Inr x \<in> SIGO ODE2})" using Iagree_sub[OF SIGsubs(1)] Iagree_sub[OF SIGsubs(2)] by auto show "ODE_sem I ODE1 (fst \<nu>) + ODE_sem I ODE2 (fst \<nu>) = ODE_sem J ODE1 (fst \<nu>') + ODE_sem J ODE2 (fst \<nu>')" using IH1[OF VA1 IA1] IH2[OF VA2 IA2] by auto qed qed lemma coincidence_ode': fixes I J :: "interp" and \<nu> :: "simple_state" and \<nu>'::"simple_state" assumes goodI:"is_interp I" assumes goodJ:"is_interp J" shows " osafe ODE \<Longrightarrow> VSagree \<nu> \<nu>' (FVO ODE) \<Longrightarrow> Iagree I J ({Inl x | x. Inl x \<in> SIGO ODE} \<union> {Inr (Inr x) | x. Inr x \<in> SIGO ODE}) \<Longrightarrow> ODE_sem I ODE \<nu> = ODE_sem J ODE \<nu>'" using coincidence_ode[of I J ODE "(\<nu>, \<chi> i. 0)" "(\<nu>', \<chi> i. 0)"] goodI goodJ apply(auto) unfolding VSagree_def Vagree_def apply auto done lemma alt_sem_lemma:"\<And> I::interp. \<And> ODE::ODE. \<And>sol. \<And>t::real. \<And> ab. osafe ODE \<Longrightarrow> is_interp I \<Longrightarrow> ODE_sem I ODE (sol t) = ODE_sem I ODE (\<chi> i. if i \<in> FVO ODE then sol t $ i else ab $ i)" proof - fix I::"interp" and ODE::"ODE" and sol and t::real and ab assume safe:"osafe ODE" assume good_interp:"is_interp I" have VA:"VSagree (sol t) (\<chi> i. if i \<in> FVO ODE then sol t $ i else ab $ i) (FVO ODE)" unfolding VSagree_def Vagree_def by auto have IA: "Iagree I I ({Inl x | x. Inl x \<in> SIGO ODE} \<union> {Inr (Inr x) | x. Inr x \<in> SIGO ODE})" unfolding Iagree_def by auto show "ODE_sem I ODE (sol t) = ODE_sem I ODE (\<chi> i. if i \<in> FVO ODE then sol t $ i else ab $ i)" using coincidence_ode'[OF good_interp good_interp safe VA IA] by auto qed lemma bvo_to_fvo:"Inl x \<in> BVO ODE \<Longrightarrow> x \<in> FVO ODE" proof (induction ODE) case (OVar x1 x2) then show ?case by(cases x2,auto) next case (OSing x1 x2) then show ?case by auto next case (OProd ODE1 ODE2) then show ?case by auto qed lemma ode_to_fvo:"x \<in> ODE_vars I ODE \<Longrightarrow> x \<in> FVO ODE" proof (induction ODE) case (OVar x1 x2) then show ?case by(cases x2,auto) next case (OSing x1 x2) then show ?case by auto next case (OProd ODE1 ODE2) then show ?case by auto qed definition coincide_hp :: "hp \<Rightarrow> interp \<Rightarrow> interp \<Rightarrow> bool" where "coincide_hp \<alpha> I J \<longleftrightarrow> (\<forall> \<nu> \<nu>' \<mu> V. Iagree I J (SIGP \<alpha>) \<longrightarrow> Vagree \<nu> \<nu>' V \<longrightarrow> V \<supseteq> (FVP \<alpha>) \<longrightarrow> (\<nu>, \<mu>) \<in> prog_sem I \<alpha> \<longrightarrow> (\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J \<alpha> \<and> Vagree \<mu> \<mu>' (MBV \<alpha> \<union> V)))" definition ode_sem_equiv ::"hp \<Rightarrow> interp \<Rightarrow> bool" where "ode_sem_equiv \<alpha> I \<longleftrightarrow> (\<forall>ODE::ODE. \<forall>\<phi>::formula. osafe ODE \<longrightarrow> fsafe \<phi> \<longrightarrow> (\<alpha> = EvolveODE ODE \<phi>) \<longrightarrow> {(\<nu>, mk_v I ODE \<nu> (sol t)) | \<nu> sol t. t \<ge> 0 \<and> (sol solves_ode (\<lambda>_. ODE_sem I ODE)) {0..t} {x. mk_v I ODE \<nu> x \<in> fml_sem I \<phi>} \<and> VSagree (sol 0) (fst \<nu>) {x | x. Inl x \<in> FVP (EvolveODE ODE \<phi>)}} = {(\<nu>, mk_v I ODE \<nu> (sol t)) | \<nu> sol t. t \<ge> 0 \<and> (sol solves_ode (\<lambda>_. ODE_sem I ODE)) {0..t} {x. mk_v I ODE \<nu> x \<in> fml_sem I \<phi>} \<and> sol 0 = fst \<nu>})" definition coincide_hp' :: "hp \<Rightarrow> bool" where "coincide_hp' \<alpha> \<longleftrightarrow> (\<forall> I J. is_interp I \<longrightarrow> is_interp J \<longrightarrow> (coincide_hp \<alpha> I J \<and> ode_sem_equiv \<alpha> I))" definition coincide_fml :: "formula \<Rightarrow> bool" where "coincide_fml \<phi> \<longleftrightarrow> (\<forall> \<nu> \<nu>' I J . is_interp I \<longrightarrow> is_interp J \<longrightarrow> Iagree I J (SIGF \<phi>) \<longrightarrow> Vagree \<nu> \<nu>' (FVF \<phi>) \<longrightarrow> \<nu> \<in> fml_sem I \<phi> \<longleftrightarrow> \<nu>' \<in> fml_sem J \<phi>)" lemma coinc_fml [simp]: "coincide_fml \<phi> = (\<forall> \<nu> \<nu>' I J. is_interp I \<longrightarrow> is_interp J \<longrightarrow>Iagree I J (SIGF \<phi>) \<longrightarrow> Vagree \<nu> \<nu>' (FVF \<phi>) \<longrightarrow> \<nu> \<in> fml_sem I \<phi> \<longleftrightarrow> \<nu>' \<in> fml_sem J \<phi>)" unfolding coincide_fml_def by auto subsection \<open>Coincidence Theorems for Programs and Formulas\<close> lemma coincidence_hp_fml: fixes \<alpha>::hp fixes \<phi>::formula shows "(hpsafe \<alpha> \<longrightarrow> coincide_hp' \<alpha>) \<and> (fsafe \<phi> \<longrightarrow> coincide_fml \<phi>)" proof (induction rule: hpsafe_fsafe.induct) case (hpsafe_Pvar x) thus "?case" apply(unfold coincide_hp'_def | rule allI | rule conjI | rule impI)+ prefer 2 unfolding ode_sem_equiv_def subgoal by auto unfolding coincide_hp_def apply(auto) subgoal for I J a b aa ba ab bb V proof - assume IA:"Iagree I J {Inr (Inr x)}" have Peq:"\<And>y. y \<in> Programs I x \<longleftrightarrow> y \<in> Programs J x" using Iagree_Prog[OF IA] by auto assume agree:"Vagree (a, b) (aa, ba) V" and sub:"UNIV \<subseteq> V" and sem:"((a, b), ab, bb) \<in> Programs I x" from agree_UNIV_eq[OF agree_sub [OF sub agree]] have eq:"(a,b) = (aa,ba)" by auto hence sem':"((aa,ba), (ab,bb)) \<in> Programs I x" using sem by auto have triv_sub:"V \<subseteq> UNIV" by auto have VA:"Vagree (ab,bb) (ab,bb) V" using agree_sub[OF triv_sub agree_refl[of "(ab,bb)"]] eq by auto show "\<exists>a b. ((aa, ba), a, b) \<in> Programs J x \<and> Vagree (ab, bb) (a, b) V" apply(rule exI[where x="ab"]) apply(rule exI[where x="bb"]) using sem eq VA by (auto simp add: Peq) qed done next case (hpsafe_Assign e x) then show "?case" proof (auto simp only: coincide_hp'_def ode_sem_equiv_def coincide_hp_def) fix I J :: "interp" and \<nu>1 \<nu>2 \<nu>'1 \<nu>'2 \<mu>1 \<mu>2 V assume safe:"dsafe e" and IA:"Iagree I J (SIGP (x := e))" and VA:"Vagree (\<nu>1, \<nu>2) (\<nu>'1, \<nu>'2) V" and sub:"FVP (x := e) \<subseteq> V" and sem:"((\<nu>1, \<nu>2), (\<mu>1, \<mu>2)) \<in> prog_sem I (x := e)" from VA have VA':"Vagree (\<nu>1, \<nu>2) (\<nu>'1, \<nu>'2) (FVT e)" unfolding FVP.simps Vagree_def using sub by auto have Ssub:"{Inl x | x. x \<in> SIGT e} \<subseteq> (SIGP (x := e))" by auto from IA have IA':"Iagree I J {Inl x | x. x \<in> SIGT e}" using Ssub unfolding SIGP.simps by auto have "((\<nu>1, \<nu>2), repv (\<nu>1, \<nu>2) x (dterm_sem I e (\<nu>1, \<nu>2))) \<in> prog_sem I (x := e)" by auto then have sem':"((\<nu>'1, \<nu>'2), repv (\<nu>'1, \<nu>'2) x (dterm_sem J e (\<nu>'1, \<nu>'2))) \<in> prog_sem J (x := e)" using coincidence_dterm' safe VA' IA' by auto from sem have eq:"(\<mu>1, \<mu>2) = (repv (\<nu>1, \<nu>2) x (dterm_sem I e (\<nu>1, \<nu>2)))" by auto have VA'':"Vagree (\<mu>1, \<mu>2) (repv (\<nu>'1, \<nu>'2) x (dterm_sem J e (\<nu>'1, \<nu>'2))) (MBV (x := e) \<union> V)" using coincidence_dterm'[of e "(\<nu>1,\<nu>2)" "(\<nu>'1,\<nu>'2)" I J] safe VA' IA' eq agree_refl VA unfolding MBV.simps Vagree_def by auto show "\<exists>\<mu>'. ((\<nu>'1, \<nu>'2), \<mu>') \<in> prog_sem J (x := e) \<and> Vagree (\<mu>1, \<mu>2) \<mu>' (MBV (x := e) \<union> V)" using VA'' sem' by blast qed next case (hpsafe_AssignAny x) then show "?case" proof (auto simp only: coincide_hp'_def ode_sem_equiv_def coincide_hp_def) fix I J :: "interp" and \<nu>1 \<nu>2 \<nu>'1 \<nu>'2 \<mu>1 \<mu>2 V assume IA:"Iagree I J (SIGP (AssignAny x))" and VA:"Vagree (\<nu>1, \<nu>2) (\<nu>'1, \<nu>'2) V" and sub:"FVP (AssignAny x) \<subseteq> V" and sem:"((\<nu>1, \<nu>2), (\<mu>1, \<mu>2)) \<in> prog_sem I (AssignAny x)" show "\<exists>\<mu>'. ((\<nu>'1, \<nu>'2), \<mu>') \<in> prog_sem J (AssignAny x) \<and> Vagree (\<mu>1, \<mu>2) \<mu>' (MBV (AssignAny x) \<union> V)" using IA VA sub sem apply auto subgoal for r apply(rule exI[where x="fst (repv (\<nu>'1,\<nu>'2) x r)"]) apply(rule conjI) subgoal apply(rule exI[where x=r]) apply(rule vec_extensionality) using VA sub sem by(auto simp add: vec_eq_iff Vagree_def) subgoal using VA sub sem by(auto simp add: vec_eq_iff Vagree_def) done done qed next case (hpsafe_DiffAssign e x) then show "?case" proof (auto simp only: coincide_hp'_def ode_sem_equiv_def coincide_hp_def) fix I J::"interp" and \<nu> \<nu>' \<mu> V assume safe:"dsafe e" and IA:"Iagree I J (SIGP (DiffAssign x e))" and VA:"Vagree \<nu> \<nu>' V" and sub:"FVP (DiffAssign x e) \<subseteq> V" and sem:"(\<nu>, \<mu>) \<in> prog_sem I (DiffAssign x e)" from VA have VA':"Vagree \<nu> \<nu>' (FVT e)" unfolding FVP.simps Vagree_def using sub by auto have Ssub:"{Inl x | x. x \<in> SIGT e} \<subseteq> (SIGP (DiffAssign x e))" by auto from IA have IA':"Iagree I J {Inl x | x. x \<in> SIGT e}" using Ssub unfolding SIGP.simps by auto have "(\<nu>, repv \<nu> x (dterm_sem I e \<nu>)) \<in> prog_sem I (x := e)" by auto then have sem':"(\<nu>', repd \<nu>' x (dterm_sem J e \<nu>')) \<in> prog_sem J (DiffAssign x e)" using coincidence_dterm' safe VA' IA' by auto from sem have eq:"\<mu> = (repd \<nu> x (dterm_sem I e \<nu>))" by auto have VA':"Vagree \<mu> (repd \<nu>' x (dterm_sem J e \<nu>')) (MBV (DiffAssign x e) \<union> V)" using coincidence_dterm'[OF safe VA', of I J, OF IA'] eq agree_refl VA unfolding MBV.simps Vagree_def by auto show "\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J (DiffAssign x e) \<and> Vagree \<mu> \<mu>' (MBV (DiffAssign x e) \<union> V)" using VA' sem' by blast qed next case (hpsafe_Test P) then show "?case" proof (auto simp add:coincide_hp'_def ode_sem_equiv_def coincide_hp_def) fix I J::"interp" and \<nu> \<nu>' \<omega> \<omega>' ::"simple_state" and V assume safe:"fsafe P" assume goodI:"is_interp I" assume goodJ:"is_interp J" assume "\<forall>a b aa ba I. is_interp I \<longrightarrow> (\<forall>J. is_interp J \<longrightarrow> Iagree I J (SIGF P) \<longrightarrow> Vagree (a, b) (aa, ba) (FVF P) \<longrightarrow> ((a, b) \<in> fml_sem I P) = ((aa, ba) \<in> fml_sem J P))" hence IH:"Iagree I J (SIGF P) \<Longrightarrow> Vagree (\<nu>, \<nu>') (\<omega>, \<omega>') (FVF P) \<Longrightarrow> ((\<nu>, \<nu>') \<in> fml_sem I P) = ((\<omega>, \<omega>') \<in> fml_sem J P)" using goodI goodJ by auto assume IA:"Iagree I J (SIGF P)" assume VA:"Vagree (\<nu>, \<nu>') (\<omega>, \<omega>') V" assume sub:"FVF P \<subseteq> V" hence VA':"Vagree (\<nu>, \<nu>') (\<omega>, \<omega>') (FVF P)" using agree_supset VA by auto assume sem:"(\<nu>, \<nu>') \<in> fml_sem I P" show "(\<omega>, \<omega>') \<in> fml_sem J P" using IH[OF IA VA'] sem by auto qed next case (hpsafe_Evolve ODE P) then show "?case" proof (unfold coincide_hp'_def) assume osafe:"osafe ODE" assume fsafe:"fsafe P" assume IH:"coincide_fml P" from IH have IHF:"\<And>\<nu> \<nu>' I J. Iagree I J (SIGF P) \<Longrightarrow> is_interp I \<Longrightarrow> is_interp J \<Longrightarrow> Vagree \<nu> \<nu>' (FVF P) \<Longrightarrow> (\<nu> \<in> fml_sem I P) = (\<nu>' \<in> fml_sem J P)" unfolding coincide_fml_def by auto have equiv:"\<And>I. is_interp I \<Longrightarrow> ode_sem_equiv (EvolveODE ODE P) I" subgoal for I apply(unfold ode_sem_equiv_def) apply(rule allI)+ subgoal for ODE \<phi> apply(rule impI)+ apply(auto) (* 2 subgoals *) subgoal for aa ba ab bb sol t apply(rule exI[where x="(\<lambda>t. \<chi> i. if i \<in> FVO ODE then sol t $ i else ab $ i)"]) apply(rule conjI) subgoal using mk_v_agree[of I ODE "(ab,bb)" "sol t"] mk_v_agree[of I ODE "(ab,bb)" "(\<chi> i. if i \<in> FVO ODE then sol t $ i else ab $ i)"] unfolding Vagree_def VSagree_def by (auto simp add: vec_eq_iff) apply(rule exI[where x=t]) apply(rule conjI) (* 2 subgoals*) subgoal apply(rule agree_UNIV_eq) using mk_v_agree[of I ODE "(ab,bb)" "sol t"] mk_v_agree[of I ODE "(ab,bb)" "(\<chi> i. if i \<in> FVO ODE then sol t $ i else ab $ i)"] mk_v_agree[of I ODE "(\<chi> i. if i \<in> FVO ODE then sol 0 $ i else ab $ i, bb)" "(\<chi> i. if i \<in> FVO ODE then sol t $ i else ab $ i)"] unfolding Vagree_def VSagree_def apply(auto) (* 2 subgoals *) subgoal for i apply(cases "Inl i \<in> BVO ODE") subgoal using bvo_to_fvo[of i ODE] by (metis (no_types, lifting) image_eqI) using bvo_to_fvo[of i ODE] by (smt Inl_Inr_False Inl_inject image_iff ode_to_fvo) using bvo_to_fvo[where ODE=ODE] proof - fix ia :: ident assume good_interp:"is_interp I" assume a1: "osafe ODE" assume a2: "(aa, ba) = mk_v I ODE (ab, bb) (sol t)" assume a3: "\<forall>i. (Inr i \<in> Inl ` ODE_vars I ODE \<longrightarrow> snd (mk_v I ODE (\<chi> i. if i \<in> FVO ODE then sol 0 $ i else ab $ i, bb) (\<chi> i. if i \<in> FVO ODE then sol t $ i else ab $ i)) $ i = ODE_sem I ODE (\<chi> i. if i \<in> FVO ODE then sol t $ i else ab $ i) $ i) \<and> ((Inr i::ident + ident) \<in> Inr ` ODE_vars I ODE \<longrightarrow> snd (mk_v I ODE (\<chi> i. if i \<in> FVO ODE then sol 0 $ i else ab $ i, bb) (\<chi> i. if i \<in> FVO ODE then sol t $ i else ab $ i)) $ i = ODE_sem I ODE (\<chi> i. if i \<in> FVO ODE then sol t $ i else ab $ i) $ i)" assume a4: "\<forall>i. (Inr i \<in> Inl ` ODE_vars I ODE \<longrightarrow> snd (mk_v I ODE (ab, bb) (sol t)) $ i = ODE_sem I ODE (sol t) $ i) \<and> ((Inr i::ident + ident) \<in> Inr ` ODE_vars I ODE \<longrightarrow> snd (mk_v I ODE (ab, bb) (sol t)) $ i = ODE_sem I ODE (sol t) $ i)" assume a5: "\<forall>i. Inr i \<notin> Inl ` ODE_vars I ODE \<and> (Inr i::ident + ident) \<notin> Inr ` ODE_vars I ODE \<longrightarrow> snd (mk_v I ODE (\<chi> i. if i \<in> FVO ODE then sol 0 $ i else ab $ i, bb) (\<chi> i. if i \<in> FVO ODE then sol t $ i else ab $ i)) $ i = bb $ i" assume a6: "\<forall>i. Inr i \<notin> Inl ` ODE_vars I ODE \<and> (Inr i::ident + ident) \<notin> Inr ` ODE_vars I ODE \<longrightarrow> snd (mk_v I ODE (ab, bb) (sol t)) $ i = bb $ i" have f7: "\<And>f r v. ODE_sem I ODE (\<chi> i. if i \<in> FVO ODE then f (r::real) $ i else v $ i) = ODE_sem I ODE (f r)" (* using a1 good_interp alt_sem_lemma*) subgoal for f r v by (rule HOL.sym[OF alt_sem_lemma[OF a1 good_interp, of f r v]] ) done { assume "Inr ia \<notin> Inl ` ODE_vars I ODE" { assume "(Inr ia::(ident + ident)) \<notin> Inr ` ODE_vars I ODE \<and> Inr ia \<notin> Inl ` ODE_vars I ODE \<and> (Inr ia::(ident + ident)) \<notin> Inr ` ODE_vars I ODE \<and> Inr ia \<notin> Inl ` ODE_vars I ODE" then have "snd (aa, ba) $ ia = bb $ ia \<and> (Inr ia::ident + ident) \<notin> Inr ` ODE_vars I ODE \<and> Inr ia \<notin> Inl ` ODE_vars I ODE" using a6 a2 by presburger then have "snd (mk_v I ODE (\<chi> c. if c \<in> FVO ODE then sol 0 $ c else ab $ c, bb) (\<chi> c. if c \<in> FVO ODE then sol t $ c else ab $ c)) $ ia = snd (aa, ba) $ ia" using a5 by presburger } then have "snd (mk_v I ODE (\<chi> c. if c \<in> FVO ODE then sol 0 $ c else ab $ c, bb) (\<chi> c. if c \<in> FVO ODE then sol t $ c else ab $ c)) $ ia = snd (aa, ba) $ ia" using f7 a4 a3 a2 by force } then show "snd (mk_v I ODE (ab, bb) (sol t)) $ ia = snd (mk_v I ODE (\<chi> c. if c \<in> FVO ODE then sol 0 $ c else ab $ c, bb) (\<chi> c. if c \<in> FVO ODE then sol t $ c else ab $ c)) $ ia" using a2 by fastforce qed apply(rule conjI) subgoal by auto apply(auto simp only: solves_ode_def has_vderiv_on_def has_vector_derivative_def) apply (rule has_derivative_vec[THEN has_derivative_eq_rhs]) defer apply (rule ext) apply (subst scaleR_vec_def) apply (rule refl) subgoal for x unfolding VSagree_def apply auto proof - assume osafe:"osafe ODE" and fsafe:"fsafe \<phi>" and eqP:"P = \<phi>" and aaba: "(aa, ba) = mk_v I ODE (ab, bb) (sol t)" and all:"\<forall>i. \<^cancel>\<open>(Inl i \<in> BVO ODE \<longrightarrow> sol 0 $ i = ab $ i) \<and>\<close> (Inl i \<in> Inl ` FVO ODE \<longrightarrow> sol 0 $ i = ab $ i) \<and> (Inl i \<in> FVF \<phi> \<longrightarrow> sol 0 $ i = ab $ i)" and allSol:"\<forall>x\<in>{0..t}. (sol has_derivative (\<lambda>xa. xa *\<^sub>R ODE_sem I ODE (sol x))) (at x within {0..t})" and mkV:"sol \<in> {0..t} \<rightarrow> {x. mk_v I ODE (ab, bb) x \<in> fml_sem I \<phi>}" and x:"0 \<le> x" and t:"x \<le> t" and good_interp:"is_interp I" from all have allT:"\<And>s. s \<ge> 0 \<Longrightarrow> s \<le> t \<Longrightarrow> mk_v I ODE (ab,bb) (sol s) \<in> fml_sem I \<phi>" using mkV by auto have VA:"\<And>x. Vagree (mk_v I ODE (ab, bb) (sol x)) (mk_v I ODE (ab, bb) (\<chi> i. if i \<in> FVO ODE then sol x $ i else ab $ i)) (FVF \<phi>)" unfolding Vagree_def apply(auto) (* 2 subgoals *) subgoal for xa i using mk_v_agree[of I ODE "(ab,bb)" "sol xa"] mk_v_agree[of I ODE "(ab,bb)" "(\<chi> i. if i \<in> FVO ODE then sol xa $ i else ab $ i)"] apply(cases "i \<in> ODE_vars I ODE") using ode_to_fvo [of i I ODE] unfolding Vagree_def apply auto by fastforce subgoal for xa i using mk_v_agree[of I ODE "(ab,bb)" "sol xa"] mk_v_agree[of I ODE "(ab,bb)" "(\<chi> i. if i \<in> FVO ODE then sol xa $ i else ab $ i)"] ODE_vars_lr using ode_to_fvo[of i I ODE] unfolding Vagree_def apply auto using alt_sem_lemma osafe subgoal proof - assume a1: "\<forall>i. Inr i \<notin> Inl ` ODE_vars I ODE \<and> (Inr i::ident + ident) \<notin> Inr ` ODE_vars I ODE \<longrightarrow> snd (mk_v I ODE (ab, bb) (sol xa)) $ i = bb $ i" assume a2: "\<forall>i. Inr i \<notin> Inl ` ODE_vars I ODE \<and> (Inr i::ident + ident) \<notin> Inr ` ODE_vars I ODE \<longrightarrow> snd (mk_v I ODE (ab, bb) (\<chi> i. if i \<in> FVO ODE then sol xa $ i else ab $ i)) $ i = bb $ i" assume a3: "\<forall>i. (Inr i \<in> Inl ` ODE_vars I ODE \<longrightarrow> snd (mk_v I ODE (ab, bb) (sol xa)) $ i = ODE_sem I ODE (sol xa) $ i) \<and> ((Inr i::ident + ident) \<in> Inr ` ODE_vars I ODE \<longrightarrow> snd (mk_v I ODE (ab, bb) (sol xa)) $ i = ODE_sem I ODE (sol xa) $ i)" assume a4: "\<forall>i. (Inr i \<in> Inl ` ODE_vars I ODE \<longrightarrow> snd (mk_v I ODE (ab, bb) (\<chi> i. if i \<in> FVO ODE then sol xa $ i else ab $ i)) $ i = ODE_sem I ODE (\<chi> i. if i \<in> FVO ODE then sol xa $ i else ab $ i) $ i) \<and> ((Inr i::ident + ident) \<in> Inr ` ODE_vars I ODE \<longrightarrow> snd (mk_v I ODE (ab, bb) (\<chi> i. if i \<in> FVO ODE then sol xa $ i else ab $ i)) $ i = ODE_sem I ODE (\<chi> i. if i \<in> FVO ODE then sol xa $ i else ab $ i) $ i)" have "ODE_sem I ODE (\<chi> c. if c \<in> FVO ODE then sol xa $ c else ab $ c) $ i = ODE_sem I ODE (sol xa) $ i" using good_interp by (metis (no_types) alt_sem_lemma osafe) then have "Inr i \<notin> Inl ` ODE_vars I ODE \<and> (Inr i::ident + ident) \<notin> Inr ` ODE_vars I ODE \<or> snd (mk_v I ODE (ab, bb) (sol xa)) $ i = snd (mk_v I ODE (ab, bb) (\<chi> c. if c \<in> FVO ODE then sol xa $ c else ab $ c)) $ i" using a4 a3 by fastforce then show ?thesis using a2 a1 by presburger qed done done note sem = IHF[OF Iagree_refl[of I]] have VA1:"(\<forall>i. Inl i \<in> FVF \<phi> \<longrightarrow> fst (mk_v I ODE ((\<chi> i. if i \<in> FVO ODE then sol 0 $ i else ab $ i), bb) (\<chi> i. if i \<in> FVO ODE then sol x $ i else ab $ i)) $ i = fst (mk_v I ODE (ab, bb) (sol x)) $ i)" and VA2: "(\<forall>i. Inr i \<in> FVF \<phi> \<longrightarrow> snd (mk_v I ODE ((\<chi> i. if i \<in> FVO ODE then sol 0 $ i else ab $ i), bb) (\<chi> i. if i \<in> FVO ODE then sol x $ i else ab $ i)) $ i = snd (mk_v I ODE (ab, bb) (sol x)) $ i)" apply(auto) (* 2 subgoals *) subgoal for i using mk_v_agree[of I ODE "((\<chi> i. if i \<in> FVO ODE then sol 0 $ i else ab $ i),bb)" "(\<chi> i. if i \<in> FVO ODE then sol x $ i else ab $ i)"] using mk_v_agree[of I ODE "(ab,bb)" "(sol x)"] ODE_vars_lr[of i I ODE] unfolding Vagree_def apply (auto) apply(erule allE[where x=i])+ apply(cases " i \<in> FVO ODE") apply(auto) apply(cases " i \<in> FVO ODE") (* 18 subgoals *) apply(auto) using ODE_vars_lr[of i I ODE] ode_to_fvo[of i I ODE] apply auto using all by meson subgoal for i using mk_v_agree[of I ODE "((\<chi> i. if i \<in> FVO ODE then sol 0 $ i else ab $ i),bb)" "(\<chi> i. if i \<in> FVO ODE then sol x $ i else ab $ i)"] using mk_v_agree[of I ODE "(ab,bb)" "(sol x)"] ODE_vars_lr[of i I ODE] unfolding Vagree_def apply (auto) apply(erule allE[where x=i])+ apply(cases " i \<in> FVO ODE") apply(auto) (* 32 subgoals *) apply(cases " i \<in> FVO ODE") apply(auto) using ODE_vars_lr[of i I ODE] ode_to_fvo[of i I ODE] apply(auto) using alt_sem_lemma osafe by (metis (no_types) alt_sem_lemma good_interp osafe)+ done assume good:"is_interp I" show "mk_v I ODE (\<chi> i. if i \<in> FVO ODE then sol 0 $ i else ab $ i, bb) (\<chi> i. if i \<in> FVO ODE then sol x $ i else ab $ i) \<in> fml_sem I \<phi>" using mk_v_agree[of I ODE "(\<chi> i. if i \<in> FVO ODE then sol 0 $ i else ab $ i, bb)" "(\<chi> i. if i \<in> FVO ODE then sol x $ i else ab $ i)"] mk_v_agree[of I ODE "(ab, bb)" "sol x"] using sem[of "mk_v I ODE (\<chi> i. if i \<in> FVO ODE then sol 0 $ i else ab $ i, bb) (\<chi> i. if i \<in> FVO ODE then sol x $ i else ab $ i)" "mk_v I ODE (ab, bb) (sol x)"] VA1 VA2 allT[of x] allT[of 0] unfolding Vagree_def apply auto using atLeastAtMost_iff mem_Collect_eq mkV t x apply(auto) using eqP VA sem good by auto qed proof - fix x i assume assms:"osafe ODE" "fsafe \<phi>" "0 \<le> t" "(aa, ba) = mk_v I ODE (ab, bb) (sol t)" "VSagree (sol 0) ab {x. \<^cancel>\<open>Inl x \<in> BVO ODE \<or> \<close>Inl x \<in> Inl ` FVO ODE \<or> Inl x \<in> FVF \<phi>}" and deriv:"\<forall>x\<in>{0..t}. (sol has_derivative (\<lambda>xa. xa *\<^sub>R ODE_sem I ODE (sol x))) (at x within {0..t})" and sol:"sol \<in> {0..t} \<rightarrow> {x. mk_v I ODE (ab, bb) x \<in> fml_sem I \<phi>}" and mem:"x \<in> {0..t}" and good_interp:"is_interp I" from deriv have xDeriv:"(sol has_derivative (\<lambda>xa. xa *\<^sub>R ODE_sem I ODE (sol x))) (at x within {0..t})" using mem by blast have silly1:"(\<lambda>x. \<chi> i. sol x $ i) = sol" by (auto simp add: vec_eq_iff) have silly2:"(\<lambda>h. \<chi> i. h * ODE_sem I ODE (sol x) $ i) = (\<lambda>xa. xa *\<^sub>R ODE_sem I ODE (sol x))" by (auto simp add: vec_eq_iff) from xDeriv have xDeriv':"((\<lambda>x. \<chi> i. sol x $ i) has_derivative (\<lambda>h. \<chi> i. h * ODE_sem I ODE (sol x) $ i)) (at x within {0..t})" using silly1 silly2 apply auto done from xDeriv have xDerivs:"\<And>j. ((\<lambda>t. sol t $ j) has_derivative (\<lambda>xa. (xa *\<^sub>R ODE_sem I ODE (sol x)) $ j)) (at x within {0..t})" subgoal for j using silly1 silly2 has_derivative_proj[of "(\<lambda>i. \<lambda>t. sol t $ i)" "(\<lambda> i. \<lambda>xa. (xa *\<^sub>R ODE_sem I ODE (sol x)) $ i)" "(at x within {0..t})" j] apply auto done done have neato:"\<And>\<nu>. i \<notin> FVO ODE \<Longrightarrow> ODE_sem I ODE \<nu> $ i = 0" proof (induction "ODE") case (OVar x1 x2) then show ?case by(cases x2,auto) next case (OSing x1 x2) then show ?case by auto next case (OProd ODE1 ODE2) then show ?case by auto qed show "((\<lambda>t. if i \<in> FVO ODE then sol t $ i else ab $ i) has_derivative (\<lambda>h. h *\<^sub>R ODE_sem I ODE (\<chi> i. if i \<in> FVO ODE then sol x $ i else ab $ i) $ i)) (at x within {0..t})" using assms sol mem apply auto apply (rule has_derivative_eq_rhs) unfolding VSagree_def apply auto apply(cases " i \<in> FVO ODE") using xDerivs[of i] apply auto using alt_sem_lemma neato[of "(\<chi> i. if i \<in> FVO ODE then sol x $ i else ab $ i)"] apply auto proof - assume a1: "((\<lambda>t. sol t $ i) has_derivative (\<lambda>xa. xa * ODE_sem I ODE (sol x) $ i)) (at x within {0..t})" have "\<And> r. ODE_sem (I::interp) ODE (\<chi> c. if c \<in> FVO ODE then sol r $ c else ab $ c) = ODE_sem I ODE (sol r)" by (metis (no_types) alt_sem_lemma good_interp assms(1)) then show "((\<lambda>r. sol r $ i) has_derivative (\<lambda>r. r * ODE_sem I ODE (\<chi> c. if c \<in> FVO ODE then sol x $ c else ab $ c) $ i)) (at x within {0..t})" using a1 by presburger qed qed proof - fix aa ba bb sol t assume osafe:"osafe ODE" and fsafe:"fsafe \<phi>" and t:"0 \<le> t" and aaba:"(aa, ba) = mk_v I ODE (sol 0, bb) (sol t)" and sol:"(sol solves_ode (\<lambda>a. ODE_sem I ODE)) {0..t} {x. mk_v I ODE (sol 0, bb) x \<in> fml_sem I \<phi>}" show"\<exists>sola ta. mk_v I ODE (sol 0, bb) (sol t) = mk_v I ODE (sol 0, bb) (sola ta) \<and> 0 \<le> ta \<and> (sola solves_ode (\<lambda>a. ODE_sem I ODE)) {0..ta} {x. mk_v I ODE (sol 0, bb) x \<in> fml_sem I \<phi>} \<and> VSagree (sola 0) (sol 0) {x. Inl x \<in> Inl ` FVO ODE \<or> Inl x \<in> FVF \<phi>}" apply(rule exI[where x=sol]) apply(rule exI[where x=t]) using fsafe t aaba sol apply auto unfolding VSagree_def by auto qed done done show "\<forall>I J. is_interp I \<longrightarrow> is_interp J \<longrightarrow> coincide_hp (EvolveODE ODE P) I J \<and> ode_sem_equiv (EvolveODE ODE P) I" proof (rule allI | rule impI)+ fix I J::"interp" assume goodI:"is_interp I" assume goodJ:"is_interp J" from equiv[of I] have equivI:" {(\<nu>, mk_v I ODE \<nu> (sol t)) | \<nu> sol t. t \<ge> 0 \<and> (sol solves_ode (\<lambda>_. ODE_sem I ODE)) {0..t} {x. mk_v I ODE \<nu> x \<in> fml_sem I P} \<and> VSagree (sol 0) (fst \<nu>) {x | x. Inl x \<in> FVP (EvolveODE ODE P)}} = {(\<nu>, mk_v I ODE \<nu> (sol t)) | \<nu> sol t. t \<ge> 0 \<and> (sol solves_ode (\<lambda>_. ODE_sem I ODE)) {0..t} {x. mk_v I ODE \<nu> x \<in> fml_sem I P} \<and> (sol 0) = (fst \<nu>)}" unfolding ode_sem_equiv_def using osafe fsafe goodI goodJ by blast from equiv[of J] have equivJ:" {(\<nu>, mk_v J ODE \<nu> (sol t)) | \<nu> sol t. t \<ge> 0 \<and> (sol solves_ode (\<lambda>_. ODE_sem J ODE)) {0..t} {x. mk_v J ODE \<nu> x \<in> fml_sem J P} \<and> VSagree (sol 0) (fst \<nu>) {x | x. Inl x \<in> FVP (EvolveODE ODE P)}} = {(\<nu>, mk_v J ODE \<nu> (sol t)) | \<nu> sol t. t \<ge> 0 \<and> (sol solves_ode (\<lambda>_. ODE_sem J ODE)) {0..t} {x. mk_v J ODE \<nu> x \<in> fml_sem J P} \<and> (sol 0) = (fst \<nu>)}" unfolding ode_sem_equiv_def using osafe fsafe goodI goodJ by blast from equivI have alt_ode_semI:"prog_sem I (EvolveODE ODE P) = {(\<nu>, mk_v I ODE \<nu> (sol t)) | \<nu> sol t. t \<ge> 0 \<and> (sol solves_ode (\<lambda>_. ODE_sem I ODE)) {0..t} {x. mk_v I ODE \<nu> x \<in> fml_sem I P} \<and> VSagree (sol 0) (fst \<nu>) {x | x. Inl x \<in> FVP (EvolveODE ODE P)}}" by auto from equivJ have alt_ode_semJ:"prog_sem J (EvolveODE ODE P) = {(\<nu>, mk_v J ODE \<nu> (sol t)) | \<nu> sol t. t \<ge> 0 \<and> (sol solves_ode (\<lambda>_. ODE_sem J ODE)) {0..t} {x. mk_v J ODE \<nu> x \<in> fml_sem J P} \<and> VSagree (sol 0) (fst \<nu>) {x | x. Inl x \<in> FVP (EvolveODE ODE P)}}" by auto have co_hp:"coincide_hp (EvolveODE ODE P) I J" apply(unfold coincide_hp_def) apply (auto simp del: prog_sem.simps(9) simp add: alt_ode_semI alt_ode_semJ) proof - fix a b aa ba ab bb V sol t from IH have IHF:"\<forall>a b aa ba . is_interp I \<longrightarrow> is_interp J \<longrightarrow> Iagree I J (SIGF P) \<longrightarrow> Vagree (a, b) (aa, ba) (FVF P) \<longrightarrow> ((a, b) \<in> fml_sem I P) = ((aa, ba) \<in> fml_sem J P)" unfolding coincide_fml_def by blast assume IA:"Iagree I J (SIGF P \<union> {Inl x |x. Inl x \<in> SIGO ODE} \<union> {Inr (Inr x) |x. Inr x \<in> SIGO ODE})" and VA:"Vagree (a, b) (aa, ba) V" and Osub:"Inl ` FVO ODE \<subseteq> V" and Fsub:"FVF P \<subseteq> V" and veq:"(ab, bb) = mk_v I ODE (a, b) (sol t)" and t:"0 \<le> t" and sol:"(sol solves_ode (\<lambda>a. ODE_sem I ODE)) {0..t} {x. mk_v I ODE (a, b) x \<in> fml_sem I P}" and VSA:"VSagree (sol 0) a {uu. \<^cancel>\<open>Inl uu \<in> BVO ODE \<or> \<close>Inl uu \<in> Inl ` FVO ODE \<or> Inl uu \<in> FVF P}" have semBVsub:"(semBV I ODE) \<subseteq> BVO ODE" proof (induction ODE) case (OVar x1 x2) then show ?case apply(cases x2,auto) using goodI goodJ unfolding is_interp_def by auto next case (OSing x1 x2) then show ?case by auto next case (OProd ODE1 ODE2) then show ?case by auto qed have MBVBVsub:"(Inl ` ODE_dom ODE \<union> Inr ` ODE_dom ODE) \<subseteq> BVO ODE" apply(induction ODE) by auto from sol have solSem:"\<And>x. 0 \<le> x \<Longrightarrow> x \<le> t \<Longrightarrow> mk_v I ODE (a, b) (sol x) \<in> fml_sem I P" and solDeriv:"\<And>x. 0 \<le> x \<Longrightarrow> x \<le> t \<Longrightarrow> (sol has_vector_derivative ODE_sem I ODE (sol x)) (at x within {0..t})" unfolding solves_ode_def has_vderiv_on_def by auto have SIGFsub:"(SIGF P) \<subseteq> (SIGF P \<union> {Inl x |x. Inl x \<in> SIGO ODE} \<union> {Inr (Inr x) |x. Inr x \<in> SIGO ODE})" by auto from IA have IAP:"Iagree I J (SIGF P)" using Iagree_sub[OF SIGFsub] by auto from IHF have IH': "\<forall>a b aa ba. Vagree (a, b) (aa, ba) (FVF P) \<longrightarrow> ((a, b) \<in> fml_sem I P) = ((aa, ba) \<in> fml_sem J P)" using IAP goodI goodJ by blast from VA have VAOV:"Vagree (a,b) (aa,ba) (Inl ` FVO ODE)" using agree_sub[OF Osub] by auto have ag:"\<And>s. Vagree (mk_v I ODE (a, b) (sol s)) (a, b) (- semBV I ODE)" "\<And>s. Vagree (mk_v I ODE (a, b) (sol s)) (mk_xode I ODE (sol s)) (semBV I ODE)" "\<And>s. Vagree (mk_v J ODE (aa, ba) (sol s)) (aa, ba) (- semBV J ODE)" "\<And>s. Vagree (mk_v J ODE (aa, ba) (sol s)) (mk_xode J ODE (sol s)) (semBV J ODE)" subgoal for s using mk_v_agree[of I ODE "(a,b)" "sol s"] by auto subgoal for s using mk_v_agree[of I ODE "(a,b)" "sol s"] by auto subgoal for s using mk_v_agree[of J ODE "(aa,ba)" "sol s"] by auto subgoal for s using mk_v_agree[of J ODE "(aa,ba)" "sol s"] by auto done have sem_sub_BVO:"\<And>I::interp. is_interp I \<Longrightarrow> semBV I ODE \<subseteq> BVO ODE" proof (induction ODE) case (OVar x1 x2) then show ?case apply(cases x2,auto) using goodI goodJ unfolding is_interp_def by auto next case (OSing x1 x2) then show ?case by auto next case (OProd ODE1 ODE2) assume IH1:"\<And>I::interp. is_interp I \<Longrightarrow> semBV I ODE1 \<subseteq> BVO ODE1" assume IH2:"\<And>I::interp. is_interp I \<Longrightarrow> semBV I ODE2 \<subseteq> BVO ODE2" assume good:"is_interp I" then show ?case using IH1[OF good] IH2[OF good] by auto qed have MBV_sub_sem:"\<And>I. (Inl ` ODE_dom ODE \<union> Inr ` ODE_dom ODE) \<subseteq> semBV I ODE" subgoal for I by (induction ODE, auto) done have ag_BVO: "\<And>s. Vagree (mk_v I ODE (a, b) (sol s)) (a, b) (- BVO ODE)" "\<And>s. Vagree (mk_v J ODE (aa, ba) (sol s)) (aa, ba) (- BVO ODE)" using ag(1) ag(3) sem_sub_BVO[of I] sem_sub_BVO[of J] agree_sub goodI goodJ by blast+ have ag_semBV: "\<And>s. Vagree (mk_v I ODE (a, b) (sol s)) (mk_xode I ODE (sol s)) (Inl ` ODE_dom ODE \<union> Inr ` ODE_dom ODE)" "\<And>s. Vagree (mk_v J ODE (aa, ba) (sol s)) (mk_xode J ODE (sol s)) (Inl ` ODE_dom ODE \<union> Inr ` ODE_dom ODE)" using ag(2) ag(4) MBV_sub_sem[of I] MBV_sub_sem[of J] by (simp add: agree_sub)+ have IOsub:"({Inl x |x. Inl x \<in> SIGO ODE} \<union> {Inr (Inr x) |x. Inr x \<in> SIGO ODE}) \<subseteq> (SIGF P \<union> {Inl x |x. Inl x \<in> SIGO ODE} \<union> {Inr (Inr x) |x. Inr x \<in> SIGO ODE})" by auto from IA have IAO:"Iagree I J ({Inl x |x. Inl x \<in> SIGO ODE} \<union> {Inr (Inr x) |x. Inr x \<in> SIGO ODE})" using Iagree_sub[OF IOsub] by auto have IOsub':"({Inr (Inr x) |x. Inr x \<in> SIGO ODE}) \<subseteq> ({Inl x |x. Inl x \<in> SIGO ODE} \<union> {Inr (Inr x) |x. Inr x \<in> SIGO ODE})" by auto from IAO have IAO':"Iagree I J ({Inr (Inr x) |x. Inr x \<in> SIGO ODE})" using Iagree_sub[OF IOsub'] by auto have VAsol:"\<And>s \<nu>'. Vagree ((sol s), \<nu>') ((sol s), \<nu>') (Inl `FVO ODE)" unfolding Vagree_def by auto have Osem:"\<And>s. 0 \<le> s \<Longrightarrow> s \<le> t \<Longrightarrow> ODE_sem I ODE (sol s) = ODE_sem J ODE (sol s)" subgoal for s using coincidence_ode[OF goodI goodJ osafe VAsol[of s] IAO] by auto done from Osem have Oag:"\<And>s. 0 \<le> s \<Longrightarrow> s \<le> t \<Longrightarrow> VSagree (ODE_sem I ODE (sol s)) (ODE_sem J ODE (sol s)) {x. Inr x \<in> BVO ODE}" unfolding VSagree_def by auto from Osem have Oagsem:"\<And>s. 0 \<le> s \<Longrightarrow> s \<le> t \<Longrightarrow> VSagree (ODE_sem I ODE (sol s)) (ODE_sem J ODE (sol s)) {x. Inr x \<in> (semBV I ODE)}" unfolding VSagree_def by auto from Osem have halp:"\<And>s. 0 \<le> s \<Longrightarrow> s \<le> t \<Longrightarrow> Vagree (mk_xode I ODE (sol s)) (mk_xode J ODE (sol s)) (semBV I ODE)" apply(auto) using Oag unfolding Vagree_def VSagree_def by blast then have halpp:"\<And>s. 0 \<le> s \<Longrightarrow> s \<le> t \<Longrightarrow> Vagree (sol s, ODE_sem I ODE (sol s)) (sol s, ODE_sem J ODE (sol s)) (semBV I ODE)" by auto have neat:"\<And>ODE. Iagree I J ({Inr (Inr x) |x. Inr x \<in> SIGO ODE}) \<Longrightarrow> semBV I ODE = semBV J ODE" subgoal for ODE proof (induction ODE) case (OVar x) then show ?case unfolding Iagree_def by auto next case (OSing x1a x2) then show ?case by auto next case (OProd ODE1 ODE2) assume IH1:"Iagree I J {Inr (Inr x) |x. Inr x \<in> SIGO ODE1} \<Longrightarrow> semBV I ODE1 = semBV J ODE1" assume IH2:"Iagree I J {Inr (Inr x) |x. Inr x \<in> SIGO ODE2} \<Longrightarrow> semBV I ODE2 = semBV J ODE2" assume agree:"Iagree I J {Inr (Inr x) |x. Inr x \<in> SIGO (OProd ODE1 ODE2)}" from agree have agree1:"Iagree I J {Inr (Inr x) |x. Inr x \<in> SIGO ( ODE1 )}" and agree2:"Iagree I J {Inr (Inr x) |x. Inr x \<in> SIGO ( ODE2)}" unfolding Iagree_def by auto show ?case using IH1[OF agree1] IH2[OF agree2] by auto qed done note semBVeq = neat[OF IAO'] then have halpp':"\<And>s. 0 \<le> s \<Longrightarrow> s \<le> t \<Longrightarrow> Vagree (mk_v I ODE (a, b) (sol s)) (mk_v J ODE (aa, ba) (sol s)) (semBV I ODE)" subgoal for s using ag[of s] ag_semBV[of s] Oagsem agree_trans semBVeq unfolding Vagree_def using Osem by force done have VAbar:"\<And>s. 0 \<le> s \<Longrightarrow> s \<le> t \<Longrightarrow> Vagree (mk_v I ODE (a, b) (sol s)) (mk_v J ODE (aa, ba) (sol s)) (V \<inter> (-(semBV I ODE)))" subgoal for s apply(unfold Vagree_def) apply(rule conjI | rule allI)+ subgoal for i apply auto using VA ag[of s] semBVeq unfolding Vagree_def apply auto by (metis Un_iff) apply(rule allI)+ subgoal for i using VA ag[of s] semBVeq unfolding Vagree_def by auto done done have VAfoo:"\<And>s. 0 \<le> s \<Longrightarrow> s \<le> t \<Longrightarrow> Vagree (mk_v I ODE (a, b) (sol s)) (mk_v J ODE (aa, ba) (sol s)) V" using agree_union[OF halpp' VAbar] apply (auto simp add: Vagree_def) by blast have duhSub:"FVF P \<subseteq> UNIV" by auto from VAfoo have VA'foo:"\<And>s. 0 \<le> s \<Longrightarrow> s \<le> t \<Longrightarrow> Vagree (mk_v I ODE (a, b) (sol s)) (mk_v J ODE (aa, ba) (sol s)) V" using agree_sub[OF duhSub] by auto then have VA''foo:"\<And>s. 0 \<le> s \<Longrightarrow> s \<le> t \<Longrightarrow> Vagree (mk_v I ODE (a, b) (sol s)) (mk_v J ODE (aa, ba) (sol s)) (FVF P)" using agree_sub[OF Fsub] by auto from VA''foo IH' have fmlSem:"\<And>s. 0 \<le> s \<Longrightarrow> s \<le> t \<Longrightarrow> (mk_v I ODE (a, b) (sol s)) \<in> fml_sem I P \<longleftrightarrow> (mk_v J ODE (aa, ba) (sol s)) \<in> fml_sem J P" using IAP coincide_fml_def hpsafe_Evolve.IH goodI goodJ by blast from VA have VAO:"Vagree (a, b) (aa, ba) (Inl `FVO ODE)" using agree_sub[OF Osub] by auto have sol':"(sol solves_ode (\<lambda>_. ODE_sem J ODE)) {0..t} {x. mk_v J ODE (aa, ba) x \<in> fml_sem J P}" apply(auto simp add: solves_ode_def has_vderiv_on_def) subgoal for s using solDeriv[of s] Osem[of s] by auto subgoal for s using solSem[of s] fmlSem[of s] by auto done have VSA':"VSagree (a) aa {uu. Inl uu \<in> Inl `FVO ODE \<or> Inl uu \<in> FVF P}" using VSA VA Osub unfolding VSagree_def Vagree_def (*ovsub *) apply auto using Osub Fsub Osem by blast show " \<exists>ab bb. (\<exists>sol t. (ab, bb) = mk_v J ODE (aa, ba) (sol t) \<and> 0 \<le> t \<and> (sol solves_ode (\<lambda>a. ODE_sem J ODE)) {0..t} {x. mk_v J ODE (aa, ba) x \<in> fml_sem J P} \<and> VSagree (sol 0) aa {uu. Inl uu \<in> Inl ` FVO ODE \<or> Inl uu \<in> FVF P}) \<and> Vagree (mk_v I ODE (a, b) (sol t)) (ab, bb) (Inl ` ODE_dom ODE \<union> Inr ` ODE_dom ODE \<union> V)" apply(rule exI[where x="fst (mk_v J ODE (aa, ba) (sol t))"]) apply(rule exI[where x="snd (mk_v J ODE (aa, ba) (sol t))"]) apply(rule conjI) subgoal apply(rule exI[where x="sol"]) subgoal using VSA' unfolding VSagree_def by (smt Collect_cong VSA VSagree_def image_iff prod.collapse sol' sum.inject(1) t) done using mk_v_agree[of I ODE "(sol 0,b)" "(sol t)"] mk_v_agree[of J ODE "(aa,ba)" "(sol t)"] using agree_refl t VA'foo Osub Un_absorb1 MBV_sub_sem agree_sub agree_union halpp' by (smt prod.collapse) qed show "coincide_hp (EvolveODE ODE P) I J \<and> ode_sem_equiv (EvolveODE ODE P) I" using co_hp equiv[of I] using goodI goodJ by auto qed qed next case (hpsafe_Choice a b) then show "?case" proof (auto simp only: coincide_hp'_def coincide_hp_def) fix I J::"interp" and \<nu>1 \<nu>1' \<nu>2 \<nu>2' \<mu> \<mu>' V assume safe:"hpsafe a" "hpsafe b" and preIH1:"\<forall>I J. is_interp I \<longrightarrow> is_interp J \<longrightarrow> (\<forall>\<nu> \<nu>' \<mu> V. Iagree I J (SIGP a) \<longrightarrow> Vagree \<nu> \<nu>' V \<longrightarrow> FVP a \<subseteq> V \<longrightarrow> (\<nu>, \<mu>) \<in> prog_sem I a \<longrightarrow> (\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J a \<and> Vagree \<mu> \<mu>' (MBV a \<union> V))) \<and> ode_sem_equiv a I" and preIH2:"\<forall>I J. is_interp I \<longrightarrow> is_interp J \<longrightarrow> (\<forall>\<nu> \<nu>' \<mu> V. Iagree I J (SIGP b) \<longrightarrow> Vagree \<nu> \<nu>' V \<longrightarrow> FVP b \<subseteq> V \<longrightarrow> (\<nu>, \<mu>) \<in> prog_sem I b \<longrightarrow> (\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J b \<and> Vagree \<mu> \<mu>' (MBV b \<union> V))) \<and> ode_sem_equiv b I" and IA:"Iagree I J (SIGP (a \<union>\<union> b))" and VA:"Vagree (\<nu>1, \<nu>1') (\<nu>2, \<nu>2') V" and sub:"FVP (a \<union>\<union> b) \<subseteq> V" and sem:"((\<nu>1, \<nu>1'), (\<mu>, \<mu>')) \<in> prog_sem I (a \<union>\<union> b)" and goodI:"is_interp I" and goodJ:"is_interp J" hence eitherSem:"((\<nu>1, \<nu>1'), (\<mu>, \<mu>')) \<in> prog_sem I a \<or> ((\<nu>1, \<nu>1'), (\<mu>, \<mu>')) \<in> prog_sem I b" by auto from preIH1 have IH1: "(\<forall>\<nu> \<nu>' \<mu> V. Iagree I J (SIGP a) \<longrightarrow> Vagree \<nu> \<nu>' V \<longrightarrow> FVP a \<subseteq> V \<longrightarrow> (\<nu>, \<mu>) \<in> prog_sem I a \<longrightarrow> (\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J a \<and> Vagree \<mu> \<mu>' (MBV a \<union> V))) \<and> ode_sem_equiv a I" using goodI goodJ by(auto) from preIH2 have IH2:" (\<forall>\<nu> \<nu>' \<mu> V. Iagree I J (SIGP b) \<longrightarrow> Vagree \<nu> \<nu>' V \<longrightarrow> FVP b \<subseteq> V \<longrightarrow> (\<nu>, \<mu>) \<in> prog_sem I b \<longrightarrow> (\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J b \<and> Vagree \<mu> \<mu>' (MBV b \<union> V))) \<and> ode_sem_equiv b I" using goodI goodJ by(auto) have Ssub:"(SIGP a) \<subseteq> SIGP (a \<union>\<union> b)" "(SIGP b) \<subseteq> SIGP (a \<union>\<union> b)" unfolding SIGP.simps by auto have IA1:"Iagree I J (SIGP a)" and IA2:"Iagree I J (SIGP b)" using IA Iagree_sub[OF Ssub(1)] Iagree_sub[OF Ssub(2)] by auto from sub have sub1:"FVP a \<subseteq> V" and sub2:"FVP b \<subseteq> V" by auto then show "\<exists>\<mu>''. ((\<nu>2, \<nu>2'), \<mu>'') \<in> prog_sem J (a \<union>\<union> b) \<and> Vagree (\<mu>, \<mu>') \<mu>'' (MBV (a \<union>\<union> b) \<union> V)" proof (cases "((\<nu>1, \<nu>1'), (\<mu>, \<mu>')) \<in> prog_sem I a") case True then obtain \<mu>'' where prog_sem:"((\<nu>2,\<nu>2'), \<mu>'') \<in> prog_sem J a" and agree:"Vagree (\<mu>, \<mu>') \<mu>'' (MBV a \<union> V)" using IH1 VA sub1 IA1 by blast from agree have agree':"Vagree (\<mu>, \<mu>') \<mu>'' (MBV (a \<union>\<union> b) \<union> V)" unfolding Vagree_def MBV.simps by auto from prog_sem have prog_sem':"((\<nu>2,\<nu>2'), \<mu>'') \<in> prog_sem J (a \<union>\<union> b)" unfolding prog_sem.simps by blast from agree' and prog_sem' show ?thesis by blast next case False then have sem2:"((\<nu>1, \<nu>1'), (\<mu>, \<mu>')) \<in> prog_sem I b" using eitherSem by blast then obtain \<mu>'' where prog_sem:"((\<nu>2,\<nu>2'), \<mu>'') \<in> prog_sem J b" and agree:"Vagree (\<mu>, \<mu>') \<mu>'' (MBV b \<union> V)" using IH2 VA sub2 IA2 by blast from agree have agree':"Vagree (\<mu>, \<mu>') \<mu>'' (MBV (a \<union>\<union> b) \<union> V)" unfolding Vagree_def MBV.simps by auto from prog_sem have prog_sem':"((\<nu>2,\<nu>2'), \<mu>'') \<in> prog_sem J (a \<union>\<union> b)" unfolding prog_sem.simps by blast from agree' and prog_sem' show ?thesis by blast qed next fix I J::"interp" assume preIHs:"\<forall>I J. is_interp I \<longrightarrow> is_interp J \<longrightarrow> (\<forall>\<nu> \<nu>' \<mu> V. Iagree I J (SIGP a) \<longrightarrow> Vagree \<nu> \<nu>' V \<longrightarrow> FVP a \<subseteq> V \<longrightarrow> (\<nu>, \<mu>) \<in> prog_sem I a \<longrightarrow> (\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J a \<and> Vagree \<mu> \<mu>' (MBV a \<union> V))) \<and> ode_sem_equiv a I" "\<forall>I J. is_interp I \<longrightarrow> is_interp J \<longrightarrow> (\<forall>\<nu> \<nu>' \<mu> V. Iagree I J (SIGP b) \<longrightarrow> Vagree \<nu> \<nu>' V \<longrightarrow> FVP b \<subseteq> V \<longrightarrow> (\<nu>, \<mu>) \<in> prog_sem I b \<longrightarrow> (\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J b \<and> Vagree \<mu> \<mu>' (MBV b \<union> V))) \<and> ode_sem_equiv b I" and goodI:"is_interp I" and goodJ:"is_interp J" then show "ode_sem_equiv (a \<union>\<union> b) I" unfolding ode_sem_equiv_def by auto qed next case (hpsafe_Sequence a b) then show "?case" apply (unfold coincide_hp'_def coincide_hp_def) apply (rule allI | rule impI)+ apply (rule conjI) prefer 2 subgoal unfolding ode_sem_equiv_def by auto apply(unfold prog_sem.simps SIGP.simps FVP.simps ) apply(rule allI)+ apply(auto) subgoal for I J \<nu>2 \<nu>2' V \<nu>1 \<nu>1' \<mu> \<mu>' \<omega> \<omega>' proof - assume goodI:"is_interp I" assume goodJ:"is_interp J" assume safe:"hpsafe a" "hpsafe b" assume "\<forall>I. is_interp I \<longrightarrow> (\<forall>J. is_interp J \<longrightarrow> (Iagree I J (SIGP a) \<longrightarrow> (\<forall>aa b ab ba ac bb V. Vagree (aa, b) (ab, ba) V \<longrightarrow> FVP a \<subseteq> V \<longrightarrow> ((aa, b), ac, bb) \<in> prog_sem I a \<longrightarrow> (\<exists>aa b. ((ab, ba), aa, b) \<in> prog_sem J a \<and> Vagree (ac, bb) (aa, b) (MBV a \<union> V)))) \<and> ode_sem_equiv a I)" hence IH1':"\<And>aa b ab ba ac bb V. Iagree I J (SIGP a) \<Longrightarrow> Vagree (aa, b) (ab, ba) V \<Longrightarrow> FVP a \<subseteq> V \<Longrightarrow> ((aa, b), ac, bb) \<in> prog_sem I a \<Longrightarrow> (\<exists>aa b. ((ab, ba), aa, b) \<in> prog_sem J a \<and> Vagree (ac, bb) (aa, b) (MBV a \<union> V))" using goodI goodJ by auto note IH1 = IH1'[of \<nu>1 \<nu>1' \<nu>2 \<nu>2' V \<mu> \<mu>'] assume IH2''':"\<forall>I. is_interp I \<longrightarrow> (\<forall>J. is_interp J \<longrightarrow> (Iagree I J (SIGP b) \<longrightarrow> (\<forall>a ba aa bb ab bc V. Vagree (a, ba) (aa, bb) V \<longrightarrow> FVP b \<subseteq> V \<longrightarrow> ((a, ba), ab, bc) \<in> prog_sem I b \<longrightarrow> (\<exists>a ba. ((aa, bb), a, ba) \<in> prog_sem J b \<and> Vagree (ab, bc) (a, ba) (MBV b \<union> V)))) \<and> ode_sem_equiv b I) " then have IH2'':" (Iagree I J (SIGP b) \<longrightarrow> (\<forall>a ba aa bb ab bc V. Vagree (a, ba) (aa, bb) V \<longrightarrow> FVP b \<subseteq> V \<longrightarrow> ((a, ba), ab, bc) \<in> prog_sem I b \<longrightarrow> (\<exists>a ba. ((aa, bb), a, ba) \<in> prog_sem J b \<and> Vagree (ab, bc) (a, ba) (MBV b \<union> V)))) \<and> ode_sem_equiv b I" using goodI goodJ by auto assume IAab:"Iagree I J (SIGP a \<union> SIGP b)" have IAsubs:"SIGP a \<subseteq> (SIGP a \<union> SIGP b)" "SIGP b \<subseteq> (SIGP a \<union> SIGP b)" by auto from IAab have IA:"Iagree I J (SIGP a)" "Iagree I J (SIGP b)" using Iagree_sub[OF IAsubs(1)] Iagree_sub[OF IAsubs(2)] by auto from IH2'' have IH2':"\<And>a ba aa bb ab bc V . Iagree I J (SIGP b) \<Longrightarrow> Vagree (a, ba) (aa, bb) V \<Longrightarrow> FVP b \<subseteq> V \<Longrightarrow> ((a, ba), ab, bc) \<in> prog_sem I b \<Longrightarrow> (\<exists>a ba. ((aa, bb), a, ba) \<in> prog_sem J b \<and> Vagree (ab, bc) (a, ba) (MBV b \<union> V))" using IA by auto assume VA:"Vagree (\<nu>1, \<nu>1') (\<nu>2, \<nu>2') V" assume sub:"FVP a \<subseteq> V" "FVP b - MBV a \<subseteq> V" hence sub':"FVP a \<subseteq> V" by auto assume sem:"((\<nu>1, \<nu>1'), (\<mu>, \<mu>')) \<in> prog_sem I a" "((\<mu>, \<mu>'), (\<omega>, \<omega>')) \<in> prog_sem I b" obtain \<omega>1 \<omega>1' where sem1:"((\<nu>2, \<nu>2'), (\<omega>1, \<omega>1')) \<in> prog_sem J a" and VA1:"Vagree (\<mu>, \<mu>') (\<omega>1, \<omega>1') (MBV a \<union> V)" using IH1[OF IA(1) VA sub' sem(1)] by auto note IH2 = IH2'[of \<mu> \<mu>' \<omega>1 \<omega>1' " MBV a \<union> V" \<omega> \<omega>'] have sub2:"FVP b \<subseteq> MBV a \<union> V" using sub by auto obtain \<omega>2 \<omega>2' where sem2:"((\<omega>1, \<omega>1'), (\<omega>2, \<omega>2')) \<in> prog_sem J b" and VA2:"Vagree (\<omega>, \<omega>') (\<omega>2, \<omega>2') (MBV b \<union> (MBV a \<union> V))" using IH2[OF IA(2) VA1 sub2 sem(2)] by auto show "\<exists>ab bb. ((\<nu>2, \<nu>2'), (ab, bb)) \<in> prog_sem J a O prog_sem J b \<and> Vagree (\<omega>, \<omega>') (ab, bb) (MBV a \<union> MBV b \<union> V)" using sem1 sem2 VA1 VA2 by (metis (no_types, lifting) Un_assoc Un_left_commute relcomp.relcompI) qed done next case (hpsafe_Loop a) then show "?case" apply(unfold coincide_hp'_def coincide_hp_def) apply(rule allI | rule impI)+ apply(rule conjI) prefer 2 subgoal unfolding ode_sem_equiv_def by auto apply(rule allI | rule impI)+ apply(unfold prog_sem.simps FVP.simps MBV.simps SIGP.simps) subgoal for I J \<nu> \<nu>' \<mu> V proof - assume safe:"hpsafe a" assume goodI:"is_interp I" and goodJ:"is_interp J" assume IH':" \<forall>I J. is_interp I \<longrightarrow> is_interp J \<longrightarrow> (\<forall>\<nu> \<nu>' \<mu> V. Iagree I J (SIGP a) \<longrightarrow> Vagree \<nu> \<nu>' V \<longrightarrow> FVP a \<subseteq> V \<longrightarrow> (\<nu>, \<mu>) \<in> prog_sem I a \<longrightarrow> (\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J a \<and> Vagree \<mu> \<mu>' (MBV a \<union> V))) \<and> ode_sem_equiv a I" then have IH:"(\<forall>\<nu> \<nu>' \<mu> V. Iagree I J (SIGP a) \<longrightarrow> Vagree \<nu> \<nu>' V \<longrightarrow> FVP a \<subseteq> V \<longrightarrow> (\<nu>, \<mu>) \<in> prog_sem I a \<longrightarrow> (\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J a \<and> Vagree \<mu> \<mu>' (MBV a \<union> V))) \<and> ode_sem_equiv a I" using goodI goodJ by auto assume agree:"Iagree I J (SIGP a)" assume VA:"Vagree \<nu> \<nu>' V" assume sub:"FVP a \<subseteq> V" have "(\<nu>, \<mu>) \<in> (prog_sem I a)\<^sup>* \<Longrightarrow> (\<And>\<nu>'. Vagree \<nu> \<nu>' V \<Longrightarrow> \<exists>\<mu>'. (\<nu>', \<mu>') \<in> (prog_sem J a)\<^sup>* \<and> Vagree \<mu> \<mu>' ({} \<union> V))" apply(induction rule: converse_rtrancl_induct) apply(auto) subgoal for \<omega> \<omega>' s s' v v' proof - assume sem1:"((\<omega>, \<omega>'), (s, s')) \<in> prog_sem I a" and sem2:"((s, s'), \<mu>) \<in> (prog_sem I a)\<^sup>*" and IH2:"\<And>v v'. (Vagree (s, s') (v,v') V \<Longrightarrow> \<exists>ab ba. ((v,v'), (ab, ba)) \<in> (prog_sem J a)\<^sup>* \<and> Vagree \<mu> (ab, ba) V)" and VA:"Vagree (\<omega>, \<omega>') (v,v') V" obtain s'' where sem'':"((v, v'), s'') \<in> prog_sem J a" and VA'':"Vagree (s,s') s'' (MBV a \<union> V)" using IH agree VA sub sem1 agree_refl by blast then obtain s'1 and s'2 where sem'':"((v, v'), (s'1, s'2)) \<in> prog_sem J a" and VA'':"Vagree (s,s') (s'1, s'2) (MBV a \<union> V)" using IH agree VA sub sem1 agree_refl by (cases "s''", blast) from VA'' have VA''V:"Vagree (s,s') (s'1, s'2) V" using agree_sub by blast note IH2' = IH2[of s'1 s'2] note IH2'' = IH2'[OF VA''V] then obtain ab and ba where sem''':"((s'1, s'2), (ab, ba)) \<in> (prog_sem J a)\<^sup>*" and VA''':"Vagree \<mu> (ab, ba) V" using IH2'' by auto from sem'' sem''' have sem:"((v, v'), (ab, ba)) \<in> (prog_sem J a)\<^sup>*" by auto show "\<exists>\<mu>'1 \<mu>'2. ((v, v'), (\<mu>'1, \<mu>'2)) \<in> (prog_sem J a)\<^sup>* \<and> Vagree \<mu> (\<mu>'1, \<mu>'2) V" using sem VA''' by blast qed done then show "(\<nu>, \<mu>) \<in> (prog_sem I a)\<^sup>* \<Longrightarrow> Vagree \<nu> \<nu>' V \<Longrightarrow> \<exists>\<mu>'. (\<nu>', \<mu>') \<in> (prog_sem J a)\<^sup>* \<and> Vagree \<mu> \<mu>' ({} \<union> V)" by auto qed done next case (fsafe_Geq t1 t2) then have safe:"dsafe t1" "dsafe t2" by auto have almost:"\<And>\<nu> \<nu>'. \<And> I J :: interp. Iagree I J (SIGF (Geq t1 t2)) \<Longrightarrow> Vagree \<nu> \<nu>' (FVF (Geq t1 t2)) \<Longrightarrow> (\<nu> \<in> fml_sem I (Geq t1 t2)) = (\<nu>' \<in> fml_sem J (Geq t1 t2))" proof - fix \<nu> \<nu>' and I J :: "interp" assume IA:"Iagree I J (SIGF (Geq t1 t2))" hence IAs:"Iagree I J {Inl x | x. x \<in> (SIGT t1)}" "Iagree I J {Inl x | x. x \<in> (SIGT t2)}" unfolding SIGF.simps Iagree_def by auto assume VA:"Vagree \<nu> \<nu>' (FVF (Geq t1 t2))" hence VAs:"Vagree \<nu> \<nu>' (FVT t1)" "Vagree \<nu> \<nu>' (FVT t2)" unfolding FVF.simps Vagree_def by auto have sem1:"dterm_sem I t1 \<nu> = dterm_sem J t1 \<nu>'" by (auto simp add: coincidence_dterm'[OF safe(1) VAs(1) IAs(1)]) have sem2:"dterm_sem I t2 \<nu> = dterm_sem J t2 \<nu>'" by (auto simp add: coincidence_dterm'[OF safe(2) VAs(2) IAs(2)]) show "(\<nu> \<in> fml_sem I (Geq t1 t2)) = (\<nu>' \<in> fml_sem J (Geq t1 t2))" by (simp add: sem1 sem2) qed show "?case" using almost unfolding coincide_fml_def by blast next case (fsafe_Prop p args) then have safes:"\<And>arg. arg \<in> range args \<Longrightarrow> dsafe arg" using dfree_is_dsafe by auto have almost:"\<And>\<nu> \<nu>'. \<And> I J::interp. Iagree I J (SIGF (Prop p args)) \<Longrightarrow> Vagree \<nu> \<nu>' (FVF (Prop p args)) \<Longrightarrow> (\<nu> \<in> fml_sem I (Prop p args)) = (\<nu>' \<in> fml_sem J (Prop p args))" proof - fix \<nu> \<nu>' and I J :: "interp" assume IA:"Iagree I J (SIGF (Prop p args))" have subs:"\<And>i. {Inl x | x. x \<in> SIGT (args i)} \<subseteq> (SIGF (Prop p args))" by auto have IAs:"\<And>i. Iagree I J {Inl x | x. x \<in> SIGT (args i)}" using IA apply(unfold SIGF.simps) subgoal for i using Iagree_sub[OF subs[of i]] by auto done have mem:"Inr (Inr p) \<in> {Inr (Inr p)} \<union> {Inl x |x. x \<in> (\<Union>i. SIGT (args i))}" by auto from IA have pSame:"Predicates I p = Predicates J p" by (auto simp add: Iagree_Pred IA mem) assume VA:"Vagree \<nu> \<nu>' (FVF (Prop p args))" hence VAs:"\<And>i. Vagree \<nu> \<nu>' (FVT (args i))" unfolding FVF.simps Vagree_def by auto have sems:"\<And>i. dterm_sem I (args i) \<nu> = dterm_sem J (args i) \<nu>'" using IAs VAs coincidence_dterm' rangeI safes by (simp add: coincidence_dterm') hence vecSem:"(\<chi> i. dterm_sem I (args i) \<nu>) = (\<chi> i. dterm_sem J (args i) \<nu>')" by auto show "(\<nu> \<in> fml_sem I (Prop p args)) = (\<nu>' \<in> fml_sem J (Prop p args))" apply(unfold fml_sem.simps mem_Collect_eq) using IA vecSem pSame by (auto) qed then show "?case" unfolding coincide_fml_def by blast next case fsafe_Not then show "?case" by auto next case (fsafe_And p1 p2) then have safes:"fsafe p1" "fsafe p2" and IH1:"\<forall> \<nu> \<nu>' I J. is_interp I \<longrightarrow> is_interp J \<longrightarrow> Iagree I J (SIGF p1) \<longrightarrow> Vagree \<nu> \<nu>' (FVF p1) \<longrightarrow> (\<nu> \<in> fml_sem I p1) = (\<nu>' \<in> fml_sem J p1)" and IH2:"\<forall> \<nu> \<nu>' I J. is_interp I \<longrightarrow> is_interp J \<longrightarrow> Iagree I J (SIGF p2) \<longrightarrow> Vagree \<nu> \<nu>' (FVF p2) \<longrightarrow> (\<nu> \<in> fml_sem I p2) = (\<nu>' \<in> fml_sem J p2)" by auto have almost:"\<And>\<nu> \<nu>' I J. is_interp I \<Longrightarrow> is_interp J \<Longrightarrow> Iagree I J (SIGF (And p1 p2)) \<Longrightarrow> Vagree \<nu> \<nu>' (FVF (And p1 p2)) \<Longrightarrow> (\<nu> \<in> fml_sem I (And p1 p2)) = (\<nu>' \<in> fml_sem J (And p1 p2))" proof - fix \<nu> \<nu>' and I J::"interp" assume goodI:"is_interp I" and goodJ:"is_interp J" assume IA:"Iagree I J (SIGF (And p1 p2))" have IAsubs:"(SIGF p1) \<subseteq> (SIGF (And p1 p2))" "(SIGF p2) \<subseteq> (SIGF (And p1 p2))" by auto from IA have IAs:"Iagree I J (SIGF p1)" "Iagree I J (SIGF p2)" using Iagree_sub[OF IAsubs(1)] Iagree_sub[OF IAsubs(2)] goodI goodJ by auto assume VA:"Vagree \<nu> \<nu>' (FVF (And p1 p2))" hence VAs:"Vagree \<nu> \<nu>' (FVF p1)" "Vagree \<nu> \<nu>' (FVF p2)" unfolding FVF.simps Vagree_def by auto have eq1:"(\<nu> \<in> fml_sem I p1) = (\<nu>' \<in> fml_sem J p1)" using IH1 IAs VAs goodI goodJ by blast have eq2:"(\<nu> \<in> fml_sem I p2) = (\<nu>' \<in> fml_sem J p2)" using IH2 IAs VAs goodI goodJ by blast show "(\<nu> \<in> fml_sem I (And p1 p2)) = (\<nu>' \<in> fml_sem J (And p1 p2))" using eq1 eq2 by auto qed then show "?case" unfolding coincide_fml_def by blast next case (fsafe_Exists p x) then have safe:"fsafe p" and IH:"\<forall> \<nu> \<nu>' I J. is_interp I \<longrightarrow> is_interp J \<longrightarrow> Iagree I J (SIGF p) \<longrightarrow> Vagree \<nu> \<nu>' (FVF p) \<longrightarrow> (\<nu> \<in> fml_sem I p) = (\<nu>' \<in> fml_sem J p)" by auto have almost:"\<And>\<nu> \<nu>' I J. is_interp I \<Longrightarrow> is_interp J \<Longrightarrow> Iagree I J (SIGF (Exists x p)) \<Longrightarrow> Vagree \<nu> \<nu>' (FVF (Exists x p)) \<Longrightarrow> (\<nu> \<in> fml_sem I (Exists x p)) = (\<nu>' \<in> fml_sem J (Exists x p))" proof - fix \<nu> \<nu>' and I J::"interp" assume goodI:"is_interp I" and goodJ:"is_interp J" assume IA:"Iagree I J (SIGF (Exists x p))" hence IA':"Iagree I J (SIGF p)" unfolding SIGF.simps Iagree_def by auto assume VA:"Vagree \<nu> \<nu>' (FVF (Exists x p))" hence VA':"Vagree \<nu> \<nu>' (FVF p - {Inl x})" by auto hence VA'':"\<And>r. Vagree (repv \<nu> x r) (repv \<nu>' x r) (FVF p)" subgoal for r unfolding Vagree_def FVF.simps repv.simps by auto done have IH': "\<And>r. Iagree I J (SIGF p) \<Longrightarrow> Vagree (repv \<nu> x r) (repv \<nu>' x r) (FVF p) \<Longrightarrow> ((repv \<nu> x r) \<in> fml_sem I p) = ((repv \<nu>' x r) \<in> fml_sem J p)" subgoal for r using IH apply(rule allE[where x = "repv \<nu> x r"]) apply(erule allE[where x = "repv \<nu>' x r"]) using goodI goodJ by (auto) done hence IH'':"\<And>r. ((repv \<nu> x r) \<in> fml_sem I p) = ((repv \<nu>' x r) \<in> fml_sem J p)" subgoal for r using IA' VA'' by auto done have fact:"\<And>r. (repv \<nu> x r \<in> fml_sem I p) = (repv \<nu>' x r \<in> fml_sem J p)" subgoal for r using IH'[OF IA' VA''] by auto done show "(\<nu> \<in> fml_sem I (Exists x p)) = (\<nu>' \<in> fml_sem J (Exists x p))" apply(simp only: fml_sem.simps mem_Collect_eq) using IH'' by auto qed then show "?case" unfolding coincide_fml_def by blast next case (fsafe_Diamond a p) then have hsafe:"hpsafe a" and psafe:"fsafe p" and IH1':"\<forall>I J \<nu> \<nu>' \<mu> V. is_interp I \<longrightarrow> is_interp J \<longrightarrow> Iagree I J (SIGP a) \<longrightarrow> Vagree \<nu> \<nu>' V \<longrightarrow> FVP a \<subseteq> V \<longrightarrow> (\<nu>, \<mu>) \<in> prog_sem I a \<longrightarrow> (\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J a \<and> Vagree \<mu> \<mu>' (MBV a \<union> V))" and IH2:"\<forall>\<nu> \<nu>' I J. is_interp I \<longrightarrow> is_interp J \<longrightarrow>Iagree I J (SIGF p) \<longrightarrow> Vagree \<nu> \<nu>' (FVF p) \<longrightarrow> (\<nu> \<in> fml_sem I p) = (\<nu>' \<in> fml_sem J p)" unfolding coincide_hp'_def coincide_hp_def coincide_fml_def apply auto done have almost:"\<And>\<nu> \<nu>' I J. is_interp I \<Longrightarrow> is_interp J \<Longrightarrow> Iagree I J (SIGF (Diamond a p)) \<Longrightarrow> Vagree \<nu> \<nu>' (FVF (Diamond a p)) \<Longrightarrow> (\<nu> \<in> fml_sem I (Diamond a p)) = (\<nu>' \<in> fml_sem J (Diamond a p))" proof - fix \<nu> \<nu>' and I J::"interp" assume goodI:"is_interp I" assume goodJ:"is_interp J" have IH1:"\<forall> \<nu> \<nu>' \<mu> V. is_interp I \<longrightarrow> is_interp J \<longrightarrow> Iagree I J (SIGP a) \<longrightarrow> Vagree \<nu> \<nu>' V \<longrightarrow> FVP a \<subseteq> V \<longrightarrow> (\<nu>, \<mu>) \<in> prog_sem I a \<longrightarrow> (\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J a \<and> Vagree \<mu> \<mu>' (MBV a \<union> V))" using goodI goodJ IH1' by auto assume IA:"Iagree I J (SIGF (Diamond a p))" have IAsubs:"(SIGP a) \<subseteq> (SIGF (Diamond a p))" "(SIGF p) \<subseteq> (SIGF (Diamond a p))" by auto from IA have IAP:"Iagree I J (SIGP a)" and IAF:"Iagree I J (SIGF p)" using Iagree_sub[OF IAsubs(1)] Iagree_sub[OF IAsubs(2)] by auto from IAP have IAP':"Iagree J I (SIGP a)" by (rule Iagree_comm) from IAF have IAF':"Iagree J I (SIGF p)" by (rule Iagree_comm) assume VA:"Vagree \<nu> \<nu>' (FVF (Diamond a p))" hence VA':"Vagree \<nu>' \<nu> (FVF (Diamond a p))" by (rule agree_comm) have dir1:"\<nu> \<in> fml_sem I (Diamond a p) \<Longrightarrow> \<nu>' \<in> fml_sem J (Diamond a p)" proof - assume sem:"\<nu> \<in> fml_sem I (Diamond a p)" let ?V = "FVF (Diamond a p)" have Vsup:"FVP a \<subseteq> ?V" by auto obtain \<mu> where prog:"(\<nu>, \<mu>) \<in> prog_sem I a" and fml:"\<mu> \<in> fml_sem I p" using sem by auto from IH1 have IH1': "Iagree I J (SIGP a) \<Longrightarrow> Vagree \<nu> \<nu>' ?V \<Longrightarrow> FVP a \<subseteq> ?V \<Longrightarrow> (\<nu>, \<mu>) \<in> prog_sem I a \<Longrightarrow> (\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J a \<and> Vagree \<mu> \<mu>' (MBV a \<union> ?V))" using goodI goodJ by blast obtain \<mu>' where prog':"(\<nu>', \<mu>') \<in> prog_sem J a" and agree:"Vagree \<mu> \<mu>' (MBV a \<union> ?V)" using IH1'[OF IAP VA Vsup prog] by blast from IH2 have IH2':"Iagree I J (SIGF p) \<Longrightarrow> Vagree \<mu> \<mu>' (FVF p) \<Longrightarrow> (\<mu> \<in> fml_sem I p) = (\<mu>' \<in> fml_sem J p)" using goodI goodJ by blast have VAF:"Vagree \<mu> \<mu>' (FVF p)" using agree VA by (auto simp only: Vagree_def FVF.simps) hence IH2'':"(\<mu> \<in> fml_sem I p) = (\<mu>' \<in> fml_sem J p)" using IH2'[OF IAF VAF] by auto have fml':"\<mu>' \<in> fml_sem J p" using IH2'' fml by auto have "\<exists> \<mu>'. (\<nu>', \<mu>') \<in> prog_sem J a \<and> \<mu>' \<in> fml_sem J p" using fml' prog' by blast then show "\<nu>' \<in> fml_sem J (Diamond a p)" unfolding fml_sem.simps by (auto simp only: mem_Collect_eq) qed have dir2:"\<nu>' \<in> fml_sem J (Diamond a p) \<Longrightarrow> \<nu> \<in> fml_sem I (Diamond a p)" proof - assume sem:"\<nu>' \<in> fml_sem J (Diamond a p)" let ?V = "FVF (Diamond a p)" have Vsup:"FVP a \<subseteq> ?V" by auto obtain \<mu> where prog:"(\<nu>', \<mu>) \<in> prog_sem J a" and fml:"\<mu> \<in> fml_sem J p" using sem by auto from IH1 have IH1': "Iagree J I (SIGP a) \<Longrightarrow> Vagree \<nu>' \<nu> ?V \<Longrightarrow> FVP a \<subseteq> ?V \<Longrightarrow> (\<nu>', \<mu>) \<in> prog_sem J a \<Longrightarrow> (\<exists>\<mu>'. (\<nu>, \<mu>') \<in> prog_sem I a \<and> Vagree \<mu> \<mu>' (MBV a \<union> ?V))" using goodI goodJ IH1' by blast obtain \<mu>' where prog':"(\<nu>, \<mu>') \<in> prog_sem I a" and agree:"Vagree \<mu> \<mu>' (MBV a \<union> ?V)" using IH1'[OF IAP' VA' Vsup prog] by blast from IH2 have IH2':"Iagree J I (SIGF p) \<Longrightarrow> Vagree \<mu> \<mu>' (FVF p) \<Longrightarrow> (\<mu> \<in> fml_sem J p) = (\<mu>' \<in> fml_sem I p)" using goodI goodJ by blast have VAF:"Vagree \<mu> \<mu>' (FVF p)" using agree VA by (auto simp only: Vagree_def FVF.simps) hence IH2'':"(\<mu> \<in> fml_sem J p) = (\<mu>' \<in> fml_sem I p)" using IH2'[OF IAF' VAF] by auto have fml':"\<mu>' \<in> fml_sem I p" using IH2'' fml by auto have "\<exists> \<mu>'. (\<nu>, \<mu>') \<in> prog_sem I a \<and> \<mu>' \<in> fml_sem I p" using fml' prog' by blast then show "\<nu> \<in> fml_sem I (Diamond a p)" unfolding fml_sem.simps by (auto simp only: mem_Collect_eq) qed show "(\<nu> \<in> fml_sem I (Diamond a p)) = (\<nu>' \<in> fml_sem J (Diamond a p))" using dir1 dir2 by auto qed then show "?case" unfolding coincide_fml_def by blast next case (fsafe_InContext C \<phi>) then have safe:"fsafe \<phi>" and IH:"(\<forall> \<nu> \<nu>' I J. is_interp I \<longrightarrow> is_interp J \<longrightarrow> Iagree I J (SIGF \<phi>) \<longrightarrow> Vagree \<nu> \<nu>' (FVF \<phi>) \<longrightarrow> \<nu> \<in> fml_sem I \<phi> \<longleftrightarrow> \<nu>' \<in> fml_sem J \<phi>)" by (unfold coincide_fml_def) hence IH':"\<And>\<nu> \<nu>' I J. is_interp I \<Longrightarrow> is_interp J \<Longrightarrow> Iagree I J (SIGF \<phi>) \<Longrightarrow> Vagree \<nu> \<nu>' (FVF \<phi>) \<Longrightarrow> \<nu> \<in> fml_sem I \<phi> \<longleftrightarrow> \<nu>' \<in> fml_sem J \<phi>" by auto hence sem_eq:"\<And>I J. is_interp I \<Longrightarrow> is_interp J \<Longrightarrow> Iagree I J (SIGF \<phi>) \<Longrightarrow> fml_sem I \<phi> = fml_sem J \<phi>" apply (auto simp: Collect_cong Collect_mem_eq agree_refl) using agree_refl by blast+ have "(\<And> \<nu> \<nu>' I J C . is_interp I \<Longrightarrow> is_interp J \<Longrightarrow> Iagree I J (SIGF (InContext C \<phi>)) \<Longrightarrow> Vagree \<nu> \<nu>' (FVF (InContext C \<phi>)) \<Longrightarrow> \<nu> \<in> fml_sem I (InContext C \<phi>) \<longleftrightarrow> \<nu>' \<in> fml_sem J (InContext C \<phi>))" proof - fix \<nu> \<nu>' and I J::"interp" and C assume goodI:"is_interp I" and goodJ:"is_interp J" assume IA:"Iagree I J (SIGF (InContext C \<phi>))" then have IA':"Iagree I J (SIGF \<phi>)" unfolding SIGF.simps Iagree_def by auto assume VA:"Vagree \<nu> \<nu>' (FVF (InContext C \<phi>))" then have VAU:"Vagree \<nu> \<nu>' UNIV" unfolding FVF.simps Vagree_def by auto then have VA':"Vagree \<nu> \<nu>' (FVF \<phi>)" unfolding FVF.simps Vagree_def by auto from VAU have eq:"\<nu> = \<nu>'" by (cases "\<nu>", cases "\<nu>'", auto simp add: vec_eq_iff Vagree_def) from IA have Cmem:"Inr (Inl C) \<in> SIGF (InContext C \<phi>)" by simp have Cagree:"Contexts I C = Contexts J C" by (rule Iagree_Contexts[OF IA Cmem]) show "\<nu> \<in> fml_sem I (InContext C \<phi>) \<longleftrightarrow> \<nu>' \<in> fml_sem J (InContext C \<phi>)" using Cagree eq sem_eq IA' goodI goodJ by (auto) qed then show "?case" by simp qed lemma coincidence_formula:"\<And>\<nu> \<nu>' I J. fsafe (\<phi>:: formula) \<Longrightarrow> is_interp I \<Longrightarrow> is_interp J \<Longrightarrow> Iagree I J (SIGF \<phi>) \<Longrightarrow> Vagree \<nu> \<nu>' (FVF \<phi>) \<Longrightarrow> (\<nu> \<in> fml_sem I \<phi> \<longleftrightarrow> \<nu>' \<in> fml_sem J \<phi>)" using coincidence_hp_fml unfolding coincide_fml_def by blast lemma coincidence_hp: fixes \<nu> \<nu>' \<mu> V I J assumes safe:"hpsafe (\<alpha>:: hp)" assumes goodI:"is_interp I" assumes goodJ:"is_interp J" assumes IA:"Iagree I J (SIGP \<alpha>)" assumes VA:"Vagree \<nu> \<nu>' V" assumes sub:"V \<supseteq> (FVP \<alpha>)" assumes sem:"(\<nu>, \<mu>) \<in> prog_sem I \<alpha>" shows "(\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J \<alpha> \<and> Vagree \<mu> \<mu>' (MBV \<alpha> \<union> V))" proof - have thing:"(\<forall>I J. is_interp I \<longrightarrow> is_interp J \<longrightarrow> (\<forall>\<nu> \<nu>' \<mu> V. Iagree I J (SIGP \<alpha>) \<longrightarrow> Vagree \<nu> \<nu>' V \<longrightarrow> FVP \<alpha> \<subseteq> V \<longrightarrow> (\<nu>, \<mu>) \<in> prog_sem I \<alpha> \<longrightarrow> (\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J \<alpha> \<and> Vagree \<mu> \<mu>' (MBV \<alpha> \<union> V))) \<and> ode_sem_equiv \<alpha> I)" using coincidence_hp_fml unfolding coincide_hp_def coincide_hp'_def using safe by blast then have "(Iagree I J (SIGP \<alpha>) \<Longrightarrow> Vagree \<nu> \<nu>' V \<Longrightarrow> FVP \<alpha> \<subseteq> V \<Longrightarrow> (\<nu>, \<mu>) \<in> prog_sem I \<alpha> \<Longrightarrow> (\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J \<alpha> \<and> Vagree \<mu> \<mu>' (MBV \<alpha> \<union> V)))" using IA VA sub sem thing goodI goodJ by blast then show "(\<exists>\<mu>'. (\<nu>', \<mu>') \<in> prog_sem J \<alpha> \<and> Vagree \<mu> \<mu>' (MBV \<alpha> \<union> V))" using IA VA sub sem by auto qed subsection \<open>Corollaries: Alternate ODE semantics definition\<close> lemma ode_sem_eq: fixes I::"interp" and ODE::"ODE" and \<phi>::"formula" assumes goodI:"is_interp I" assumes goodJ:"is_interp J" assumes osafe:"osafe ODE" assumes fsafe:"fsafe \<phi>" shows "({(\<nu>, mk_v I ODE \<nu> (sol t)) | \<nu> sol t. t \<ge> 0 \<and> (sol solves_ode (\<lambda>_. ODE_sem I ODE)) {0..t} {x. mk_v I ODE \<nu> x \<in> fml_sem I \<phi>} \<and> VSagree (sol 0) (fst \<nu>) {x | x. Inl x \<in> FVP (EvolveODE ODE \<phi>)}}) = ({(\<nu>, mk_v I ODE \<nu> (sol t)) | \<nu> sol t. t \<ge> 0 \<and> (sol solves_ode (\<lambda>_. ODE_sem I ODE)) {0..t} {x. mk_v I ODE \<nu> x \<in> fml_sem I \<phi>} \<and> (sol 0) = (fst \<nu>)})" proof - have hpsafe:"hpsafe (EvolveODE ODE \<phi>)" using osafe fsafe by (auto intro: hpsafe_fsafe.intros) have "coincide_hp'(EvolveODE ODE \<phi>)" using coincidence_hp_fml hpsafe goodI goodJ by blast hence "ode_sem_equiv (EvolveODE ODE \<phi>) I" unfolding coincide_hp'_def using goodI goodJ by auto then show "?thesis" unfolding ode_sem_equiv_def using osafe fsafe by auto qed lemma ode_alt_sem:"\<And>I ::interp. \<And>ODE::ODE. \<And>\<phi>::formula. is_interp I \<Longrightarrow> osafe ODE \<Longrightarrow> fsafe \<phi> \<Longrightarrow> prog_sem I (EvolveODE ODE \<phi>) = {(\<nu>, mk_v I ODE \<nu> (sol t)) | \<nu> sol t. t \<ge> 0 \<and> (sol solves_ode (\<lambda>_. ODE_sem I ODE)) {0..t} {x. mk_v I ODE \<nu> x \<in> fml_sem I \<phi>} \<and> VSagree (sol 0) (fst \<nu>) {x | x. Inl x \<in> FVP (EvolveODE ODE \<phi>)}}" subgoal for I ODE \<phi> using ode_sem_eq[of I I ODE \<phi> ] by auto done end
using JuMP import Ipopt function P1(z) model = Model(Ipopt.Optimizer) @variable(model, x1) @variable(model, x2) @objective(model, Min, z[1] * x1 + z[2] * x2) @NLconstraint(model, c1, (x1 - 1)^2 + (x2 - 1)^2 <= 1) optimize!(model) return value.([x1, x2]), objective_value(model) end function P2(v) model = Model(Ipopt.Optimizer) @variable(model, z) @variable(model, x1) @variable(model, x2) @objective(model, Min, z) @NLconstraint(model, c1, (x1 - 1)^2 + (x2 - 1)^2 <= 1) @constraint(model, c2, x1 - z - v[1] <= 0) @constraint(model, c3, x2 - z - v[2] <= 0) optimize!(model) return (value.([x1, x2]), value(z)) end function D2(v) model = Model(Ipopt.Optimizer) @variable(model, u >= 0) @variable(model, w1 >= 0) @variable(model, w2 >= 0) @NLobjective( model, Max, (-(w1^2 + w2^2) / (4 * u) - u) + w1 * (1 - v[1]) + w2 * (1 - v[2]) ) @constraint(model, c1, w1 + w2 == 1) optimize!(model) return (value.([w1, w2]), value(u)) end function Γ(x) x end
Jonathan Fenton-Harvey is a journalist and researcher, who focuses on political issues and humanitarian crises in the Middle East and North Africa. Showing 3 results related to "Jonathan Fenton-Harvey". The UAE is Saudi Arabia's—and Saudi Crown Prince Mohammad bin Salman's—strongest backers. Why then, does the UAE not face any scrutiny for its whitewashing of MBS, and its own egregious human rights violations? As the international community drags its feet and consistently fails to find diplomatic solutions to Yemen's conflict, its population is dragged deeper into a humanitarian crisis with no end in sight.
""" struct DemoSection <: Any DemoSection(root::String) Constructs a demo section that holds either nested subsections or demo cards. # Fields Besides the root path to the demo section folder `root`, this struct has some other fields: * `cards`: demo cards found in `root` * `subsections`: nested subsections found in `root` # Configuration You can manage an extra `config.json` file to customize rendering of a demo section. Supported items are: * `order`: specify the cards order or subsections order. By default, it's case-insensitive alphabetic order. * `title`: specify the title of this demo section. By default, it's the folder name of `root`. The following is an example of `config.json`: ```json { "title": "learn by examples" "order": [ "quickstart.md", "array.md" ] } ``` !!! warning You can't specify files or foldernames in other folders. # Examples The following is the simplest folder structure of a `DemoSection`: ```text section ├── demo_1.md ├── demo_2.md ├── demo_3.md ├── demo_4.md ├── demo_5.md ├── demo_6.md ├── demo_7.md └── demo_8.md ``` The following is a typical folder structure of a `DemoSection`: ```text section ├── config.json ├── part1 │ ├── demo_21.md │ └── demo_22.md └── part2 ├── config.json ├── demo_23.md └── demo_24.md ``` !!! warning A section should only hold either subsections or demo files. A folder that has both subfolders and demo files (e.g., `*.md`) is invalid. See also: [`MarkdownDemoCard`](@ref DemoCards.MarkdownDemoCard), [`DemoPage`](@ref DemoCards.DemoPage) """ struct DemoSection root::String cards::Vector # Why would `Vector{<:AbstractDemoCard}` fail here? subsections::Vector{DemoSection} title::String end basename(sec::DemoSection) = basename(sec.root) function DemoSection(root::String)::DemoSection root = replace(root, r"[/\\]" => Base.Filesystem.path_separator) # windows compatibility isdir(root) || throw(ArgumentError("section root should be a valid dir, instead it's $(root)")) path = joinpath.(root, filter(x->!startswith(x, "."), readdir(root))) # filter out hidden files card_paths = filter(x->isfile(x) && !endswith(x, config_filename), path) section_paths = filter(x->isdir(x)&&!(basename(x) in ignored_dirnames), path) if isempty(card_paths) && isempty(section_paths) throw(ArgumentError("emtpy section folder $(root)")) elseif !xor(isempty(card_paths), isempty(section_paths)) throw(ArgumentError("section folder $(root) should only hold either cards or subsections")) end # first consturct an incomplete section # then load the config and reconstruct a new one section = DemoSection(root, map(democard, card_paths), map(DemoSection, section_paths), "") ordered_paths = joinpath.(root, load_config(section, "order")) if !isempty(section.cards) cards = map(democard, ordered_paths) subsections = [] else cards = [] subsections = map(DemoSection, ordered_paths) end title = load_config(section, "title") DemoSection(root, cards, subsections, title) end function load_config(sec::DemoSection, key) path = joinpath(sec.root, config_filename) config = isfile(path) ? JSON.parsefile(path) : Dict() if key == "order" haskey(config, key) || return get_default_order(sec) order = config[key] validate_order(order, sec) return order elseif key == "title" get(config, key, basename(sec)) else throw(ArgumentError("Unrecognized key $(key) for DemoSection")) end end """return case-insensitive alphabetic order""" function get_default_order(sec::DemoSection) order = isempty(sec.cards) ? basename.(sec.subsections) : basename.(sec.cards) sort(order, by = x->lowercase(x)) end
\subsection*{How many runs of randomized contraction do we need to be 99\% sure that a minimum cut is found?} In RA section 1.1, the probability of finding a minimum cut is found to be larger than $$ \frac{2}{n(n-1)} $$ We wish to find the number, $x$, of runs of the minimum cut algorithm, such that we are 99\% sure that a minimum cut is found. We can express, that the probability of finding a minimum cut, after $x$ repetitions of the algorithm, is at least 99\%, by $$ \left(\frac{2}{n(n-1)}\right)^x \geq 0.99 $$ So we just need to isolate $x$. $$ \begin{aligned} \left(\frac{2}{n(n-1)}\right) ^x & \geq 0.99 \\ x\ln\left(\frac{2}{n(n-1)}\right) & \geq \ln(0.99) \\ x & \geq \frac{\ln(0.99)}{\ln\left(\frac{2}{n(n-1)}\right)} \end{aligned} $$
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2005-2006 Dan Marsden Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_FUSION_ARRAY_ITERATOR_26122005_2250) #define BOOST_FUSION_ARRAY_ITERATOR_26122005_2250 #include <boost/config.hpp> #include <boost/fusion/iterator/iterator_facade.hpp> #include <boost/fusion/support/config.hpp> #include <boost/mpl/assert.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/int.hpp> #include <boost/mpl/minus.hpp> #include <boost/type_traits/is_const.hpp> #include <cstddef> namespace boost { namespace fusion { struct random_access_traversal_tag; template <typename Array, int Pos> struct array_iterator : iterator_facade<array_iterator<Array, Pos>, random_access_traversal_tag> { BOOST_MPL_ASSERT_RELATION(Pos, >=, 0); BOOST_MPL_ASSERT_RELATION(Pos, <=, static_cast<int>(Array::static_size)); typedef mpl::int_<Pos> index; typedef Array array_type; BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED array_iterator(Array &a) : array(a) {} Array &array; template <typename Iterator> struct value_of { typedef typename Iterator::array_type array_type; typedef typename array_type::value_type type; }; template <typename Iterator> struct deref { typedef typename Iterator::array_type array_type; typedef typename mpl::if_<is_const<array_type>, typename array_type::const_reference, typename array_type::reference>::type type; BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static type call(Iterator const &it) { return it.array[Iterator::index::value]; } }; template <typename Iterator, typename N> struct advance { typedef typename Iterator::index index; typedef typename Iterator::array_type array_type; typedef array_iterator<array_type, index::value + N::value> type; BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static type call(Iterator const &i) { return type(i.array); } }; template <typename Iterator> struct next : advance<Iterator, mpl::int_<1>> {}; template <typename Iterator> struct prior : advance<Iterator, mpl::int_<-1>> {}; template <typename I1, typename I2> struct distance : mpl::minus<typename I2::index, typename I1::index> { typedef typename mpl::minus<typename I2::index, typename I1::index>::type type; BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static type call(I1 const &, I2 const &) { return type(); } }; private: array_iterator<Array, Pos> &operator=(array_iterator<Array, Pos> const &); }; } // namespace fusion } // namespace boost #ifdef BOOST_FUSION_WORKAROUND_FOR_LWG_2408 namespace std { template <typename Array, int Pos> struct iterator_traits<::boost::fusion::array_iterator<Array, Pos>> {}; } // namespace std #endif #endif