Datasets:
AI4M
/

text
stringlengths
0
3.34M
Formal statement is: lemma adjoint_clauses: fixes f :: "'n::euclidean_space \<Rightarrow> 'm::euclidean_space" assumes lf: "linear f" shows "x \<bullet> adjoint f y = f x \<bullet> y" and "adjoint f y \<bullet> x = y \<bullet> f x" Informal statement is: If $f$ is a linear map from $\mathbb{R}^n$ to $\mathbb{R}^m$, then the adjoint of $f$ satisfies the following two properties: $x \cdot f^*(y) = f(x) \cdot y$ $f^*(y) \cdot x = y \cdot f(x)$
If $f$ is holomorphic on the open ball of radius $r$ centered at $0$ and $f(0) = 0$, then there exists a holomorphic function $h$ on the open ball of radius $r$ centered at $0$ such that for all $z$ with $|z| < r$, we have $f(z) = zh(z)$ and $f'(0) = h(0)$.
Formal statement is: lemma enn2real_plus:"a < top \<Longrightarrow> b < top \<Longrightarrow> enn2real (a + b) = enn2real a + enn2real b" Informal statement is: If $a$ and $b$ are positive real numbers, then $a + b$ is also a positive real number.
SUBROUTINE HSCOLR ( icolr, iret ) C************************************************************************ C* HSCOLR - GIF * C* * C* This subroutine sets the color on a graphics device. * C* * C* HSCOLR ( ICOLR, IRET ) * C* * C* Input parameters: * C* ICOLR INTEGER Color number * C* * C* Output parameters: * C* IRET INTEGER Return code * C** * C* Log: * C*J. Nielsen/SUNYA 3/91 Add colors * C* M. desJardins/NMC 12/91 Use symbolic command; check for NNCOLR * C* J. Nielsen-G/TAMU 12/97 Updated color range * C* T. Lee/GSC 7/00 Renamed gdr_* routines * C************************************************************************ INCLUDE 'GEMPRM.PRM' INCLUDE 'DEVCHR.CMN' INCLUDE 'ERROR.PRM' INCLUDE 'COLTBL.CMN' INCLUDE 'driver.cmn' C------------------------------------------------------------------------ C* Make sure plot file is open. C ltz = -1 IF ( .not. opnfil ) THEN CALL HOPEN ( iret ) IF ( iret .ne. NORMAL ) RETURN END IF C C* Set color 101 to background color. C IF ( icolr .eq. 101 ) THEN C C set current color index to BG color value C CALL WBCOLR ( ltz, ltz, ltz, iret ) resetc = .FALSE. RETURN END IF C C* Use only colors NNCOLR colors. C ic = icolr IF ( ( ic .lt. 1 ) .or. ( ic .gt. nncolr ) ) ic = nncolr C C* Write color components to plot file. C CALL WSCOLR ( icred (ic), icgrn (ic), icblue (ic), iret ) C C* Now that color has been set, reset flag. C resetc = .FALSE. C* RETURN END
{-# OPTIONS --sized-types --show-implicit #-} module WrongSizeAssignment2 where open import Common.Size renaming (↑_ to _^) data Empty : Set where data N : {_ : Size} -> Set where zero : N {∞} suc : forall {i} -> N {i ^} -> N {i} lift : forall {i} -> N {i} -> N {i ^} lift zero = zero lift (suc x) = suc (lift x) f : forall {i} -> N {i} -> Empty f x = f (suc (lift x))
[STATEMENT] lemma has_white_path_to_refl[iff]: "(x has_white_path_to x) s" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x has_white_path_to x) s [PROOF STEP] unfolding has_white_path_to_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<lambda>x y. (x points_to y) s \<and> white y s)\<^sup>*\<^sup>* x x [PROOF STEP] by simp
Formal statement is: lemma lmeasurable_closure: "bounded S \<Longrightarrow> closure S \<in> lmeasurable" Informal statement is: If $S$ is a bounded set, then the closure of $S$ is Lebesgue measurable.
lemma frontier_cbox: fixes a b :: "'a::euclidean_space" shows "frontier (cbox a b) = cbox a b - box a b"
""" A Julia package for the exploration of continuous and discrete dynamical systems. """ module DynamicalSystems """ DynamicalSystem Abstract type representing a dynamical system. Has the following concrete sub-types: * `DiscreteDS1D` * `DiscreteDS` * `ContinuousDS` """ abstract type DynamicalSystem end export DynamicalSystem, Systems include("discrete.jl") include("continuous.jl") include("lyapunovs.jl") include("famous_systems.jl") end # module
[STATEMENT] lemma sp_equiv_pair_comm: "sp_equiv_pair x y \<longleftrightarrow> sp_equiv_pair y x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. sp_equiv_pair x y = sp_equiv_pair y x [PROOF STEP] by (cases x; cases y) auto
-- @@stderr -- dtrace: failed to compile script test/unittest/types/err.D_OP_ARITH.badoperand.d: [D_OP_ARITH] line 21: operator - requires an operand of arithmetic type
// ---------------------------------------------------------------------------| // Test Harness includes // ---------------------------------------------------------------------------| #include "test/support/db-models/state-data-test-db.h" #include "test/support/misc-util/ptree-utils.h" // ---------------------------------------------------------------------------| // Standard includes // ---------------------------------------------------------------------------| #include <iostream> // ---------------------------------------------------------------------------| // Boost includes // ---------------------------------------------------------------------------| #include <boost/foreach.hpp> // ---------------------------------------------------------------------------| // Boost includes // ---------------------------------------------------------------------------| #include <boost/test/unit_test.hpp> // ---------------------------------------------------------------------------| // File wide namespace use // ---------------------------------------------------------------------------| using namespace std; using boost::property_tree::ptree; // ---------------------------------------------------------------------------| namespace YumaTest { // ===========================================================================| ToasterContainer::ToasterContainer() : toasterManufacturer_("") , toasterModelNumber_("") , toasterStatus_("") {} // ---------------------------------------------------------------------------| bool ToasterContainer::unpackItem( const ptree::value_type& v ) { bool res = true; if ( v.first == "toasterManufacturer" ) { toasterManufacturer_ = v.second.get_value<std::string>(); } else if ( v.first == "toasterModelNumber" ) { toasterModelNumber_ = v.second.get_value<std::string>(); } else if ( v.first == "toasterStatus" ) { toasterStatus_ = v.second.get_value<std::string>(); } else { res = false; } return res; } // ---------------------------------------------------------------------------| ToasterContainer::ToasterContainer( const boost::property_tree::ptree& pt ) : toasterManufacturer_("") , toasterModelNumber_("") , toasterStatus_("") { const ptree& toaster = pt.get_child( "data.toaster", ptree() ); BOOST_FOREACH( const ptree::value_type& v, toaster ) { if ( !unpackItem( v ) && v.first != "<xmlattr>") { BOOST_FAIL( "Unsupported child for Component: " << v.first ); } } } // ---------------------------------------------------------------------------| void checkEqual( const ToasterContainer& lhs, const ToasterContainer& rhs ) { BOOST_CHECK_EQUAL( lhs.toasterManufacturer_, rhs.toasterManufacturer_ ); BOOST_CHECK_EQUAL( lhs.toasterModelNumber_, rhs.toasterModelNumber_ ); BOOST_CHECK_EQUAL( lhs.toasterStatus_, rhs.toasterStatus_ ); } } // namespace ToasterNetconfIntegrationTest
lemma continuous_on_polymonial_function: fixes f :: "'a::real_normed_vector \<Rightarrow> 'b::euclidean_space" assumes "polynomial_function f" shows "continuous_on S f"
Formal statement is: lemma Cauchy_iff2: "Cauchy X \<longleftrightarrow> (\<forall>j. (\<exists>M. \<forall>m \<ge> M. \<forall>n \<ge> M. \<bar>X m - X n\<bar> < inverse (real (Suc j))))" Informal statement is: A sequence $X$ is Cauchy if and only if for every $j \in \mathbb{N}$, there exists $M \in \mathbb{N}$ such that for all $m, n \geq M$, we have $|X_m - X_n| < \frac{1}{j+1}$.
Require Export a_base Bool. Export ListNotations. Set Implicit Arguments. Module Type sound_mod (X: base_mod). Import X. (** * Definitions definition of Propositional Formulas*) Inductive PropF : Set := | Var : PropVars -> PropF | Bot : PropF | Conj : PropF -> PropF -> PropF | Disj : PropF -> PropF -> PropF | Impl : PropF -> PropF -> PropF . Notation "# P" := (Var P) (at level 1) : My_scope. Notation "A ∨ B" := (Disj A B) (at level 15, right associativity) : My_scope. Notation "A ∧ B" := (Conj A B) (at level 15, right associativity) : My_scope. Notation "A → B" := (Impl A B) (at level 16, right associativity) : My_scope. Notation "⊥" := Bot (at level 0) : My_scope. Definition Neg A := A → ⊥. Notation "¬ A" := (Neg A) (at level 5) : My_scope. Definition Top := ¬⊥. Notation "⊤" := Top (at level 0) : My_scope. Definition BiImpl A B := (A→B)∧(B→A). Notation "A ↔ B" := (BiImpl A B) (at level 17, right associativity) : My_scope. (** Validness *) (** Valuations are maps PropVars -> bool sending ⊥ to false*) Fixpoint TrueQ v A : bool := match A with | # P => v P | ⊥ => false | B ∨ C => (TrueQ v B) || (TrueQ v C) | B ∧ C => (TrueQ v B) && (TrueQ v C) | B → C => (negb (TrueQ v B)) || (TrueQ v C) end. Definition Satisfies v Γ := forall A, In A Γ -> Is_true (TrueQ v A). Definition Models Γ A := forall v,Satisfies v Γ->Is_true (TrueQ v A). Notation "Γ ⊨ A" := (Models Γ A) (at level 80). Definition Valid A := [] ⊨ A. (** Provability *) Reserved Notation "Γ ⊢ A" (at level 80). Inductive Nc : list PropF-> PropF->Prop := | Nax : forall Γ A , In A Γ -> Γ ⊢ A | ImpI : forall Γ A B, A::Γ ⊢ B -> Γ ⊢ A → B | ImpE : forall Γ A B, Γ ⊢ A → B -> Γ ⊢ A -> Γ ⊢ B | BotC : forall Γ A , ¬A::Γ ⊢ ⊥ -> Γ ⊢ A | AndI : forall Γ A B, Γ ⊢ A -> Γ ⊢ B -> Γ ⊢ A∧B | AndE1 : forall Γ A B, Γ ⊢ A∧B -> Γ ⊢ A | AndE2 : forall Γ A B, Γ ⊢ A∧B -> Γ ⊢ B | OrI1 : forall Γ A B, Γ ⊢ A -> Γ ⊢ A∨B | OrI2 : forall Γ A B, Γ ⊢ B -> Γ ⊢ A∨B | OrE : forall Γ A B C, Γ ⊢ A∨B -> A::Γ ⊢ C -> B::Γ ⊢ C -> Γ ⊢ C where "Γ ⊢ A" := (Nc Γ A) : My_scope. Definition Provable A := [] ⊢ A. (**The Theorems we are going to prove*) Definition Prop_Soundness := forall A,Provable A->Valid A. Definition Prop_Completeness := forall A,Valid A->Provable A. (** * Theorems *) Ltac mp := eapply ImpE. Ltac AddnilL := match goal with | |- _ ?Γ _ => change Γ with ([]++Γ) end. Ltac in_solve := intros;repeat (eassumption ||match goal with | H:In _ (_::_) |- _ => destruct H;[subst;try discriminate|] | H:In _ (_++_) |- _ => apply in_app_iff in H as [];subst | |- In _ (_++_) => apply in_app_iff;(left;in_solve;fail)||(right;in_solve;fail) end ||(once constructor;reflexivity) ||constructor 2). Ltac is_ass := once econstructor;in_solve. Ltac case_bool v A := let HA := fresh "H" in (case_eq (TrueQ v A);intro HA;try rewrite HA in *;simpl in *;try trivial;try contradiction). Local Ltac prove_satisfaction := intros ? K;destruct K;[subst;simpl; match goal with | [ H : TrueQ _ _ = _ |- _ ] => rewrite H end;exact I|auto]. Lemma PropFeq_dec : forall (x y : PropF), {x = y}+{x <> y}. induction x;destruct y;try (right;discriminate); try (destruct (IHx1 y1);[destruct (IHx2 y2);[left;f_equal;assumption|]|]; right;injection;intros;contradiction). destruct (Varseq_dec p p0). left;f_equal;assumption. right;injection;intro;contradiction. left;reflexivity. Qed. Lemma Excluded_Middle : forall Γ A, Γ ⊢ A∨¬A. intros;apply BotC;mp;[is_ass|apply OrI2;apply ImpI;mp;[is_ass|apply OrI1;is_ass]]. Qed. Lemma weakening2 : forall Γ A, Γ ⊢ A -> forall Δ, (forall B, In B Γ -> In B Δ) -> Δ ⊢ A. induction 1;[constructor|constructor 2|econstructor 3|constructor 4|constructor 5|econstructor 6 |econstructor 7|constructor 8|constructor 9|econstructor 10];try eauto; [apply IHNc..|apply IHNc2|try apply IHNc3];intros;in_solve;eauto. Qed. Lemma weakening : forall Γ Δ A, Γ ⊢ A -> Γ++Δ ⊢ A. intros;eapply weakening2;[eassumption|in_solve]. Qed. Lemma deduction : forall Γ A B, Γ ⊢ A → B -> A::Γ ⊢ B. intros;eapply ImpE with A;[eapply weakening2;[eassumption|in_solve]|is_ass]. Qed. Lemma prov_impl : forall A B, Provable (A → B)->forall Γ, Γ ⊢ A -> Γ ⊢ B. intros. mp. AddnilL;apply weakening. apply H. assumption. Qed. (* This tactic applies prov_impl in IH (apply prov_impl in IH doesn't work, because I want to keep the Γ quantified)*) Ltac prov_impl_in IH := let H := fresh "K" in try (remember (prov_impl IH) as H eqn:HeqH;clear IH HeqH). (** Soundness *) Theorem Soundness_general : forall A Γ, Γ ⊢ A -> Γ ⊨ A. intros A Γ H0 v;induction H0;simpl;intros;auto; try simpl in IHNc;try simpl in IHNc1;try simpl in IHNc2; case_bool v A;try (case_bool v B;fail); try (apply IHNc||apply IHNc2;prove_satisfaction); case_bool v B;apply IHNc3;prove_satisfaction. Qed. Theorem Soundness : Prop_Soundness. intros ? ? ? ?;eapply Soundness_general;eassumption. Qed. End sound_mod.
Formal statement is: lemma enum_mono: "i \<le> n \<Longrightarrow> j \<le> n \<Longrightarrow> enum i \<le> enum j \<longleftrightarrow> i \<le> j" Informal statement is: If $i \leq n$ and $j \leq n$, then $enum(i) \leq enum(j)$ if and only if $i \leq j$.
[STATEMENT] lemma point_index_distrib: "(B1 + B2) index ps = B1 index ps + B2 index ps" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (B1 + B2) index ps = B1 index ps + B2 index ps [PROOF STEP] by (simp add: points_index_def)
WASP @-@ 44 is a G @-@ type star ( the same class of star as the Sun ) that is located in the Cetus constellation . WASP @-@ 44 has a mass that is 0 @.@ 951 times that of the Sun . In terms of size , WASP @-@ 44 has a radius that is 0 @.@ 927 times that of the Sun . WASP @-@ 44 has an effective temperature of 5410 K , cooler than the Sun . However , the star is metal @-@ rich with relation to the Sun . Its measured metallicity is [ Fe / H ] = 0 @.@ 06 , or 1 @.@ 148 times that the amount of iron found in the Sun . WASP @-@ 44 's chromosphere ( outermost layer ) is not active . The star also does not rotate at a high velocity .
module Luau.TypeSaturation where open import Luau.Type using (Type; _⇒_; _∩_; _∪_) open import Luau.TypeNormalization using (_∪ⁿ_; _∩ⁿ_) -- So, there's a problem with overloaded functions -- (of the form (S_1 ⇒ T_1) ∩⋯∩ (S_n ⇒ T_n)) -- which is that it's not good enough to compare them -- for subtyping by comparing all of their overloads. -- For example (nil → nil) is a subtype of (number? → number?) ∩ (string? → string?) -- but not a subtype of any of its overloads. -- To fix this, we adapt the semantic subtyping algorithm for -- function types, given in -- https://www.irif.fr/~gc/papers/covcon-again.pdf and -- https://pnwamk.github.io/sst-tutorial/ -- A function type is *intersection-saturated* if for any overloads -- (S₁ ⇒ T₁) and (S₂ ⇒ T₂), there exists an overload which is a subtype -- of ((S₁ ∩ S₂) ⇒ (T₁ ∩ T₂)). -- A function type is *union-saturated* if for any overloads -- (S₁ ⇒ T₁) and (S₂ ⇒ T₂), there exists an overload which is a subtype -- of ((S₁ ∪ S₂) ⇒ (T₁ ∪ T₂)). -- A function type is *saturated* if it is both intersection- and -- union-saturated. -- For example (number? → number?) ∩ (string? → string?) -- is not saturated, but (number? → number?) ∩ (string? → string?) ∩ (nil → nil) ∩ ((number ∪ string)? → (number ∪ string)?) -- is. -- Saturated function types have the nice property that they can ber -- compared by just comparing their overloads: F <: G whenever for any -- overload of G, there is an overload os F which is a subtype of it. -- Forunately every function type can be saturated! _⋓_ : Type → Type → Type (S₁ ⇒ T₁) ⋓ (S₂ ⇒ T₂) = (S₁ ∪ⁿ S₂) ⇒ (T₁ ∪ⁿ T₂) (F₁ ∩ G₁) ⋓ F₂ = (F₁ ⋓ F₂) ∩ (G₁ ⋓ F₂) F₁ ⋓ (F₂ ∩ G₂) = (F₁ ⋓ F₂) ∩ (F₁ ⋓ G₂) F ⋓ G = F ∩ G _⋒_ : Type → Type → Type (S₁ ⇒ T₁) ⋒ (S₂ ⇒ T₂) = (S₁ ∩ⁿ S₂) ⇒ (T₁ ∩ⁿ T₂) (F₁ ∩ G₁) ⋒ F₂ = (F₁ ⋒ F₂) ∩ (G₁ ⋒ F₂) F₁ ⋒ (F₂ ∩ G₂) = (F₁ ⋒ F₂) ∩ (F₁ ⋒ G₂) F ⋒ G = F ∩ G _∩ᵘ_ : Type → Type → Type F ∩ᵘ G = (F ∩ G) ∩ (F ⋓ G) _∩ⁱ_ : Type → Type → Type F ∩ⁱ G = (F ∩ G) ∩ (F ⋒ G) ∪-saturate : Type → Type ∪-saturate (F ∩ G) = (∪-saturate F ∩ᵘ ∪-saturate G) ∪-saturate F = F ∩-saturate : Type → Type ∩-saturate (F ∩ G) = (∩-saturate F ∩ⁱ ∩-saturate G) ∩-saturate F = F saturate : Type → Type saturate F = ∪-saturate (∩-saturate F)
// This test covers ContinuousState (used directly by LeafContexts) and its // derived class DiagramContinuousState (for DiagramContexts). #include "drake/systems/framework/continuous_state.h" #include <memory> #include <Eigen/Dense> #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/systems/framework/basic_vector.h" #include "drake/systems/framework/diagram_continuous_state.h" #include "drake/systems/framework/test_utilities/my_vector.h" #include "drake/systems/framework/vector_base.h" using Eigen::Vector2d; using Eigen::Vector3d; using Eigen::Vector4d; using Eigen::VectorXd; namespace drake { namespace systems { namespace { typedef Eigen::Matrix<double, 5, 1> Vector5d; typedef Eigen::Matrix<double, 6, 1> Vector6d; constexpr int kPositionLength = 2; constexpr int kVelocityLength = 1; constexpr int kMiscLength = 1; constexpr int kLength = kPositionLength + kVelocityLength + kMiscLength; template <typename T> std::unique_ptr<VectorBase<T>> MakeSomeVector() { return BasicVector<T>::Make({1, 2, 3, 4}); } // Tests for ContinuousState. class ContinuousStateTest : public ::testing::Test { protected: void SetUp() override { continuous_state_ = MakeSomeState<double>(); } template <typename T> std::unique_ptr<ContinuousState<T>> MakeSomeState() { auto result = std::make_unique<ContinuousState<T>>( MakeSomeVector<T>(), kPositionLength, kVelocityLength, kMiscLength); result->set_system_id(system_id_); return result; } template <typename T> std::unique_ptr<ContinuousState<T>> MakeNanState() { auto result = std::make_unique<ContinuousState<T>>( std::make_unique<BasicVector<T>>(kLength), kPositionLength, kVelocityLength, kMiscLength); result->set_system_id(system_id_); return result; } const internal::SystemId system_id_ = internal::SystemId::get_new_id(); std::unique_ptr<ContinuousState<double>> continuous_state_; }; TEST_F(ContinuousStateTest, Access) { EXPECT_EQ(kLength, continuous_state_->size()); EXPECT_EQ(kPositionLength, continuous_state_->get_generalized_position().size()); EXPECT_EQ(1, continuous_state_->get_generalized_position()[0]); EXPECT_EQ(2, continuous_state_->get_generalized_position()[1]); EXPECT_EQ(kVelocityLength, continuous_state_->get_generalized_velocity().size()); EXPECT_EQ(3, continuous_state_->get_generalized_velocity()[0]); EXPECT_EQ(kMiscLength, continuous_state_->get_misc_continuous_state().size()); EXPECT_EQ(4, continuous_state_->get_misc_continuous_state()[0]); } TEST_F(ContinuousStateTest, Mutation) { continuous_state_->get_mutable_generalized_position()[0] = 5; continuous_state_->get_mutable_generalized_position()[1] = 6; continuous_state_->get_mutable_generalized_velocity()[0] = 7; continuous_state_->get_mutable_misc_continuous_state()[0] = 8; EXPECT_EQ(5, continuous_state_->get_vector()[0]); EXPECT_EQ(6, continuous_state_->get_vector()[1]); EXPECT_EQ(7, continuous_state_->get_vector()[2]); EXPECT_EQ(8, continuous_state_->get_vector()[3]); } // Tests that the continuous state can be indexed as an array. TEST_F(ContinuousStateTest, ArrayOperator) { (*continuous_state_)[1] = 42; EXPECT_EQ(42, continuous_state_->get_generalized_position()[1]); EXPECT_EQ(4, (*continuous_state_)[3]); } TEST_F(ContinuousStateTest, OutOfBoundsAccess) { EXPECT_THROW(continuous_state_->get_generalized_position().GetAtIndex(2), std::exception); EXPECT_THROW( continuous_state_->get_mutable_generalized_velocity().SetAtIndex(1, 42), std::exception); } // Tests that std::out_of_range is thrown if the component dimensions do not // sum to the state vector dimension. TEST_F(ContinuousStateTest, OutOfBoundsConstruction) { EXPECT_THROW( continuous_state_.reset(new ContinuousState<double>( MakeSomeVector<double>(), kPositionLength, kVelocityLength, kMiscLength + 1)), std::out_of_range); } // Tests that std::logic_error is thrown if there are more velocity than // position variables. TEST_F(ContinuousStateTest, MoreVelocityThanPositionVariables) { EXPECT_THROW( continuous_state_.reset(new ContinuousState<double>( MakeSomeVector<double>(), 1 /* num_q */, 2 /* num_v */, kMiscLength + 1)), std::out_of_range); } TEST_F(ContinuousStateTest, SetFrom) { const auto expected_double = MakeSomeState<double>(); const auto expected_autodiff = MakeSomeState<AutoDiffXd>(); const auto expected_symbolic = MakeSomeState<symbolic::Expression>(); // Check ContinuousState<T>::SetFrom<T> for all T's. auto actual_double = MakeNanState<double>(); auto actual_autodiff = MakeNanState<AutoDiffXd>(); auto actual_symbolic = MakeNanState<symbolic::Expression>(); actual_double->SetFrom(*expected_double); actual_autodiff->SetFrom(*expected_autodiff); actual_symbolic->SetFrom(*expected_symbolic); EXPECT_EQ(actual_double->CopyToVector(), expected_double->CopyToVector()); EXPECT_EQ(actual_autodiff->CopyToVector(), expected_autodiff->CopyToVector()); EXPECT_EQ(actual_symbolic->CopyToVector(), expected_symbolic->CopyToVector()); // Check ContinuousState<double>::SetFrom<U> for U=AutoDiff and U=Expression. actual_double = MakeNanState<double>(); actual_double->SetFrom(*expected_autodiff); EXPECT_EQ(actual_double->CopyToVector(), expected_double->CopyToVector()); actual_double = MakeNanState<double>(); actual_double->SetFrom(*expected_symbolic); EXPECT_EQ(actual_double->CopyToVector(), expected_double->CopyToVector()); // If there was an unbound variable, we get an exception. auto unbound_symbolic = expected_symbolic->Clone(); unbound_symbolic->get_mutable_vector()[0] = symbolic::Variable("q"); DRAKE_EXPECT_THROWS_MESSAGE( actual_double->SetFrom(*unbound_symbolic), std::exception, ".*variable q.*\n*"); // Check ContinuousState<AutoDiff>::SetFrom<U> for U=double and U=Expression. actual_autodiff = MakeNanState<AutoDiffXd>(); actual_autodiff->SetFrom(*expected_double); EXPECT_EQ(actual_autodiff->CopyToVector(), expected_autodiff->CopyToVector()); actual_autodiff = MakeNanState<AutoDiffXd>(); actual_autodiff->SetFrom(*expected_symbolic); EXPECT_EQ(actual_autodiff->CopyToVector(), expected_autodiff->CopyToVector()); // Check ContinuousState<Expression>::SetFrom<U> for U=double and U=AutoDiff. actual_symbolic = MakeNanState<symbolic::Expression>(); actual_symbolic->SetFrom(*expected_double); EXPECT_EQ(actual_symbolic->CopyToVector(), expected_symbolic->CopyToVector()); actual_symbolic = MakeNanState<symbolic::Expression>(); actual_symbolic->SetFrom(*expected_autodiff); EXPECT_EQ(actual_symbolic->CopyToVector(), expected_symbolic->CopyToVector()); // Check ContinuousState<AutoDiff>::SetFrom<AutoDiff> preserves derivatives. auto fancy_autodiff = MakeSomeState<AutoDiffXd>(); auto& fancy_vector = fancy_autodiff->get_mutable_vector(); fancy_vector[0].derivatives() = Eigen::VectorXd::Constant(4, -1.0); fancy_vector[1].derivatives() = Eigen::VectorXd::Constant(4, -2.0); fancy_vector[2].derivatives() = Eigen::VectorXd::Constant(4, -3.0); fancy_vector[3].derivatives() = Eigen::VectorXd::Constant(4, -4.0); actual_autodiff = MakeNanState<AutoDiffXd>(); actual_autodiff->SetFrom(*fancy_autodiff); EXPECT_EQ(actual_autodiff->CopyToVector(), expected_autodiff->CopyToVector()); const auto& actual_vector = actual_autodiff->get_vector(); EXPECT_EQ(actual_vector[0].derivatives(), fancy_vector[0].derivatives()); EXPECT_EQ(actual_vector[1].derivatives(), fancy_vector[1].derivatives()); EXPECT_EQ(actual_vector[2].derivatives(), fancy_vector[2].derivatives()); EXPECT_EQ(actual_vector[3].derivatives(), fancy_vector[3].derivatives()); } TEST_F(ContinuousStateTest, SetFromException) { const auto dut = MakeSomeState<double>(); const auto wrong = std::make_unique<ContinuousState<double>>( MakeSomeVector<double>(), kPositionLength - 1, kVelocityLength, kMiscLength + 1); EXPECT_THROW(dut->SetFrom(*wrong), std::exception); } // This is testing the default implementation of Clone() for when a // ContinuousState is used as a concrete object. A DiagramContinuousState has // to do more but that is not tested here. TEST_F(ContinuousStateTest, Clone) { auto clone_ptr = continuous_state_->Clone(); const ContinuousState<double>& clone = *clone_ptr; EXPECT_EQ(clone.get_system_id(), system_id_); EXPECT_EQ(1, clone[0]); EXPECT_EQ(2, clone[1]); EXPECT_EQ(3, clone[2]); EXPECT_EQ(4, clone[3]); // Make sure underlying BasicVector type, and 2nd-order structure, // is preserved in the clone. ContinuousState<double> state(MyVector3d::Make(1.25, 1.5, 1.75), 2, 1, 0); clone_ptr = state.Clone(); const ContinuousState<double>& clone2 = *clone_ptr; EXPECT_EQ(clone2[0], 1.25); EXPECT_EQ(clone2[1], 1.5); EXPECT_EQ(clone2[2], 1.75); EXPECT_EQ(clone2.num_q(), 2); EXPECT_EQ(clone2.num_v(), 1); EXPECT_EQ(clone2.num_z(), 0); EXPECT_EQ(clone2.get_generalized_position()[0], 1.25); EXPECT_EQ(clone2.get_generalized_position()[1], 1.5); EXPECT_EQ(clone2.get_generalized_velocity()[0], 1.75); auto vector = dynamic_cast<const MyVector3d*>(&clone2.get_vector()); ASSERT_NE(vector, nullptr); EXPECT_EQ((*vector)[0], 1.25); EXPECT_EQ((*vector)[1], 1.5); EXPECT_EQ((*vector)[2], 1.75); } // Tests ability to stream a ContinuousState vector into a string. TEST_F(ContinuousStateTest, StringStream) { std::stringstream s; s << "hello " << continuous_state_->get_vector() << " world"; std::stringstream s_expected; VectorXd eigen_vector = continuous_state_->CopyToVector(); s_expected << "hello " << eigen_vector.transpose() << " world"; EXPECT_EQ(s.str(), s_expected.str()); } // Tests for DiagramContinousState. class DiagramContinuousStateTest : public ::testing::Test { protected: void SetUp() override { state0_.reset( new ContinuousState<double>(MyVector3d::Make(1, 2, 3), 1, 1, 1)); state1_.reset(new ContinuousState<double>( BasicVector<double>::Make(4, 5, 6, 7, 8), 2, 1, 2)); state2_.reset(new ContinuousState<double>( BasicVector<double>::Make(10, 11), 0, 0, 2)); state3_.reset(new ContinuousState<double>( BasicVector<double>::Make(-1, -2, -3, -4), 2, 1, 1)); state0_->set_system_id(internal::SystemId::get_new_id()); state1_->set_system_id(internal::SystemId::get_new_id()); state2_->set_system_id(internal::SystemId::get_new_id()); state3_->set_system_id(internal::SystemId::get_new_id()); // Expected contents, with expected number of q/v/z variables. // unowned 3q 2v 5z // state0 q v z 1 2 3 // state1 2q v 2z 4,5 6 7,8 // state2 2z 10,11 unowned_.reset(new DiagramContinuousState<double>( {&*state0_, &*state1_, &*state2_})); unowned_->set_system_id(internal::SystemId::get_new_id()); // root_unowned 5q 3v 6z // state3 2q v z -1,-2 -3 -4 // unowned 3q 2v 5z 1,4,5 2,6 3,7,8,10,11 // state0 // state1 // state2 root_unowned_.reset( new DiagramContinuousState<double>({&*state3_, &*unowned_})); root_unowned_->set_system_id(internal::SystemId::get_new_id()); std::vector<std::unique_ptr<ContinuousState<double>>> copies; copies.emplace_back(state3_->Clone()); copies.emplace_back(unowned_->Clone()); copies.emplace_back(state1_->Clone()); // root_owned 7q 4v 8z // state3 (copy) 2q v z -1,-2 -3 -4 // unowned (copy) 3q 2v 5z 1,4,5 2,6 3,7,8,10,11 // state0 (copy) // state1 (copy) // state2 (copy) // state1 (copy) 2q v 2z 4,5 6 7,8 root_owned_.reset(new DiagramContinuousState<double>(std::move(copies))); root_owned_->set_system_id(internal::SystemId::get_new_id()); } std::unique_ptr<ContinuousState<double>> state0_, state1_, state2_, state3_; // These are created using the "unowned" constructor. std::unique_ptr<DiagramContinuousState<double>> unowned_, root_unowned_; // This is created using the "owned" constructor. std::unique_ptr<DiagramContinuousState<double>> root_owned_; }; // See above for number of substates and their identities. TEST_F(DiagramContinuousStateTest, Substates) { EXPECT_EQ(unowned_->num_substates(), 3); EXPECT_EQ(root_unowned_->num_substates(), 2); EXPECT_EQ(root_owned_->num_substates(), 3); EXPECT_EQ(&unowned_->get_substate(0), &*state0_); EXPECT_EQ(&unowned_->get_substate(1), &*state1_); EXPECT_EQ(&unowned_->get_substate(2), &*state2_); EXPECT_EQ(&root_unowned_->get_substate(0), &*state3_); EXPECT_EQ(&root_unowned_->get_substate(1), &*unowned_); // The root_owned substates must be copies. EXPECT_NE(&root_owned_->get_substate(0), &*state3_); EXPECT_NE(&root_owned_->get_substate(1), &*unowned_); EXPECT_NE(&root_owned_->get_substate(2), &*state1_); // Just make sure get_mutable_substate() exists and works. EXPECT_EQ(&unowned_->get_mutable_substate(1), &*state1_); } // See above for expected dimensions. TEST_F(DiagramContinuousStateTest, Counts) { EXPECT_EQ(unowned_->size(), 10); EXPECT_EQ(unowned_->num_q(), 3); EXPECT_EQ(unowned_->num_v(), 2); EXPECT_EQ(unowned_->num_z(), 5); EXPECT_EQ(root_unowned_->size(), 14); EXPECT_EQ(root_unowned_->num_q(), 5); EXPECT_EQ(root_unowned_->num_v(), 3); EXPECT_EQ(root_unowned_->num_z(), 6); EXPECT_EQ(root_owned_->size(), 19); EXPECT_EQ(root_owned_->num_q(), 7); EXPECT_EQ(root_owned_->num_v(), 4); EXPECT_EQ(root_owned_->num_z(), 8); } // See above for expected values. TEST_F(DiagramContinuousStateTest, Values) { // Asking for the whole value x treats all substates as whole values xi // so the ordering is x={x0,x1,x2, ...} which means the q's v's and z's // are all mixed together rather than grouped. const VectorXd unowned_value = unowned_->CopyToVector(); VectorXd unowned_expected(10); unowned_expected << 1, 2, 3, // state0 4, 5, 6, 7, 8, // state1 10, 11; // state2 EXPECT_EQ(unowned_value, unowned_expected); // Asking for individual partitions groups like variables together. const VectorXd unowned_q = unowned_->get_generalized_position().CopyToVector(); const VectorXd unowned_v = unowned_->get_generalized_velocity().CopyToVector(); const VectorXd unowned_z = unowned_->get_misc_continuous_state().CopyToVector(); EXPECT_EQ(unowned_q, Vector3d(1, 4, 5)); EXPECT_EQ(unowned_v, Vector2d(2, 6)); Vector5d unowned_z_expected; unowned_z_expected << 3, 7, 8, 10, 11; EXPECT_EQ(unowned_z, unowned_z_expected); const VectorXd root_unowned_value = root_unowned_->CopyToVector(); VectorXd root_unowned_expected(14); root_unowned_expected << -1, -2, -3, -4, // state3 1, 2, 3, 4, 5, 6, 7, 8, 10, 11; // unowned EXPECT_EQ(root_unowned_value, root_unowned_expected); const VectorXd root_unowned_q = root_unowned_->get_generalized_position().CopyToVector(); const VectorXd root_unowned_v = root_unowned_->get_generalized_velocity().CopyToVector(); const VectorXd root_unowned_z = root_unowned_->get_misc_continuous_state().CopyToVector(); Vector5d root_unowned_q_expected; root_unowned_q_expected << -1, -2, 1, 4, 5; EXPECT_EQ(root_unowned_q, root_unowned_q_expected); EXPECT_EQ(root_unowned_v, Vector3d(-3, 2, 6)); Vector6d root_unowned_z_expected; root_unowned_z_expected << -4, 3, 7, 8, 10, 11; EXPECT_EQ(root_unowned_z, root_unowned_z_expected); const VectorXd root_owned_value = root_owned_->CopyToVector(); VectorXd root_owned_expected(19); root_owned_expected << -1, -2, -3, -4, // state3 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, // unowned 4, 5, 6, 7, 8; // state1 EXPECT_EQ(root_owned_value, root_owned_expected); const VectorXd root_owned_q = root_owned_->get_generalized_position().CopyToVector(); const VectorXd root_owned_v = root_owned_->get_generalized_velocity().CopyToVector(); const VectorXd root_owned_z = root_owned_->get_misc_continuous_state().CopyToVector(); VectorXd root_owned_q_expected(7); root_owned_q_expected << -1, -2, 1, 4, 5, 4, 5; EXPECT_EQ(root_owned_q, root_owned_q_expected); EXPECT_EQ(root_owned_v, Vector4d(-3, 2, 6, 6)); VectorXd root_owned_z_expected(8); root_owned_z_expected << -4, 3, 7, 8, 10, 11, 7, 8; EXPECT_EQ(root_owned_z, root_owned_z_expected); } // Check that Clone() results in new memory being allocated by modifying that // memory and observing that it doesn't change the original. We'll assume that // means the new DiagramContinuousState has ownership. (We're not checking for // memory leaks here -- that's for Valgrind.) TEST_F(DiagramContinuousStateTest, Clone) { // unowned is singly-nested, root_unowned is doubly-nested. auto clone_of_unowned = unowned_->Clone(); auto clone_of_root_unowned = root_unowned_->Clone(); // Show that values got copied. for (int i=0; i < unowned_->size(); ++i) EXPECT_EQ((*clone_of_unowned)[i], (*unowned_)[i]); for (int i=0; i < root_unowned_->size(); ++i) EXPECT_EQ((*clone_of_root_unowned)[i], (*root_unowned_)[i]); (*state0_)[1] = 99; // Should affect unowned but not the clones (was 2). EXPECT_EQ((*unowned_)[1], 99); EXPECT_EQ((*clone_of_unowned)[1], 2); EXPECT_EQ((*root_unowned_)[5], 99); EXPECT_EQ((*clone_of_root_unowned)[5], 2); } // Check that Clone() preserves the system_id markers. TEST_F(DiagramContinuousStateTest, CloneSystemId) { auto clone_of_unowned = unowned_->Clone(); auto clone_of_root_unowned = root_unowned_->Clone(); EXPECT_EQ(clone_of_unowned->get_system_id(), unowned_->get_system_id()); for (int i = 0; i < unowned_->num_substates(); ++i) { EXPECT_EQ(clone_of_unowned->get_substate(i).get_system_id(), unowned_->get_substate(i).get_system_id()); } EXPECT_EQ(clone_of_root_unowned->get_system_id(), root_unowned_->get_system_id()); for (int i = 0; i < root_unowned_->num_substates(); ++i) { EXPECT_EQ(clone_of_root_unowned->get_substate(i).get_system_id(), root_unowned_->get_substate(i).get_system_id()); } } } // namespace } // namespace systems } // namespace drake
% book : Signals and Systems Laboratory with MATLAB % authors : Alex Palamides & Anastasia Veloni % % % % Unit step sequence % u[n] n1=-3:-1; n2=0:5; n=[n1 n2]; u1=zeros(size(n1)); u2=ones(size(n2)); u=[u1 u2]; stem(n,u) % second way figure n=-3:5 n0=0; u=(n>=n0) stem(n,u) %u[n-n0] figure n1=-3:1; n2=2:5; n=[n1 n2]; u1=zeros(size(n1)); u2=ones(size(n2)); u2=ones(size(n2)); u=[u1 u2]; stem(n,u) % second way figure n=-3:5 n0=2; u=((n-n0)>=0) stem(n,u)
proposition separate_compact_closed: fixes s t :: "'a::heine_borel set" assumes "compact s" and t: "closed t" "s \<inter> t = {}" shows "\<exists>d>0. \<forall>x\<in>s. \<forall>y\<in>t. d \<le> dist x y"
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes, Johannes Hölzl, Yury Kudryashov -/ import algebra.hom.group import algebra.group.commute /-! # Multiplicative homomorphisms respect semiconjugation and commutation. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ section commute variables {F M N : Type*} [has_mul M] [has_mul N] {a x y : M} @[simp, to_additive] protected lemma semiconj_by.map [mul_hom_class F M N] (h : semiconj_by a x y) (f : F) : semiconj_by (f a) (f x) (f y) := by simpa only [semiconj_by, map_mul] using congr_arg f h @[simp, to_additive] protected lemma commute.map [mul_hom_class F M N] (h : commute x y) (f : F) : commute (f x) (f y) := h.map f end commute
-- Andreas, 2019-06-17, LAIM 2019, issue #3855 -- Only allow erased definitions in erased context. open import Common.IO open import Common.Unit open import Common.String open import Common.Bool @0 noWorld : String noWorld = "Hallo, Welt!" -- Illegal definition, should raise a type error. world : Bool → String world true = "Hello world!" world false = noWorld main = putStrLn (world false)
# Cardano Formula ```python print("I'm going to solve a cubic equation for you") ``` I'm going to solve a cubic equation for you ```python def discriminant(): print("Ensure the coefficient of x^3 is 1") a = int(input("The coefficient of x^2 ")) b = int(input("The coefficient of x ")) c = int(input("The constant term ")) discriminant = ((a**2)*(b**2)) + (18*a*b*c) - (4*(b**3)) - (4*(a**2)*c) - (27*(c**2)) if discriminant > 0: print("The roots are real and distinct") elif discriminant == 0: print("The roots are real and equal") else: print("There is 1 real root and 2 imaginary roots") return discriminant; discriminant() ``` Ensure the coefficient of x^3 is 1 The coefficient of x^2 1 The coefficient of x 2 The constant term 3 There is 1 real root and 2 imaginary roots -175 ```python import math def Cardano(): print("Ensure the coefficient of x^3 is 1") a = float(input("The coefficient of x^3 ")) b = float(input("The coefficient of x^2 ")) c = float(input("The coefficient of x ")) d = float(input("The constant term ")) if a !=1: print("Please let a be equal to a by dividing the equation by a") else: while a ==1: discriminant = ((b**2)*(c**2)) + (18*b*c*d) - (4*(c**3)) - (4*(b**2)*d) - (27*(d**2)) Q = (3*c - b)/9 R = ((9*b*c)-(27*d) - (2 * pow(b,3)))/54 S = ((R + math.sqrt((Q**3)+ (R**2))))**(1/3) T = ((R - math.sqrt((Q**3)+ (R**2))))**(1/3) if discriminant < 0: print (Q,R,S,T) else: print("Can't use cardano") return Cardano() ``` ```python # importing library sympy from sympy import symbols, Eq, solve # defining symbols used in equations # or unknown variables x, y = symbols('x,y') # defining equations eq1 = Eq((x+y), 1) print("Equation 1:") print(eq1) eq2 = Eq((x-y), 1) print("Equation 2") print(eq2) # solving the equation print("Values of 2 unknown variable are as follows:") print(solve((eq1, eq2), (x, y))) ``` Equation 1: Eq(x + y, 1) Equation 2 Eq(x - y, 1) Values of 2 unknown variable are as follows: {x: 1, y: 0} ```python import math def cuberoot(x): if x < 0: x = abs(x) cube_root = x**(1/3)*(-1) else: cube_root = x**(1/3) return cube_root def Cardano(): print("Ensure the coefficient of x^3 is 1") a = float(input("The coefficient of x^3 ")) b = float(input("The coefficient of x^2 ")) c = float(input("The coefficient of x ")) d = float(input("The constant term ")) if a !=1: print("Please let a be equal to a by dividing the equation by a") else: if a ==1: discriminant = ((b**2)*(c**2)) + (18*b*c*d) - (4*(c**3)) - (4*(b**2)*d) - (27*(d**2)) Q = (3*c - pow(b,2))/9 R = ((9*b*c)-(27*d) - (2 * pow(b,3)))/54 u = (Q**3)+ (R**2) u = math.sqrt(u) x = R+u y = R-u if R < 0: S = cuberoot(x) T = cuberoot(y) print (S) else: print('Tired') #S = (R + math.sqrt(u))**(1/3) #u = (Q**3)+ (R**2) #S = (abs(R) + math.sqrt(u))**(1/3) #T = (R - u)**(0.33) if discriminant < 0: print (Q,R) else: print("Can't use cardano") return Cardano() ``` Ensure the coefficient of x^3 is 1 The coefficient of x^3 1 The coefficient of x^2 3 The coefficient of x 0 The constant term 0.5 -0.7937005259840998 -1.0 -1.25 ```python ```
-- different versions of one proof in tactic mode -- proofs with the or connective example (p q : Prop) : p ∨ q → q ∨ p := by intro h apply Or.elim h intro hp exact Or.intro_right q hp intro hq exact Or.intro_left p hq example (p q : Prop) : p ∨ q → q ∨ p := by intro h cases h apply Or.intro_right assumption apply Or.intro_left assumption example (p q : Prop) : p ∨ q → q ∨ p := by intro h cases h with | inl hp => apply Or.intro_right exact hp | inr hq => apply Or.intro_left exact hq example (p q : Prop) : p ∨ q → q ∨ p := by intro h cases h with | inl => apply Or.intro_right assumption | inr => apply Or.intro_left assumption -- proofs with the and connective example (p q : Prop) : p ∧ q → q ∧ p := by intro h apply And.intro exact h.right exact h.left example (p q : Prop) : p ∧ q → q ∧ p := by intro h cases h apply And.intro repeat assumption example (p q : Prop) : p ∧ q → q ∧ p := by intro h cases h with | intro hp hq => exact (And.intro hq hp) example (p q : Prop) : p ∧ q → q ∧ p := by intro h cases h with | intro => apply And.intro repeat assumption example (p q : Prop) : p ∧ q → q ∧ p := fun h => And.intro h.right h.left
using Random: AbstractRNG using Distributions: Univariate, Sampleable using HDF5: h5open using ComponentArrays: ComponentVector """ DynamicalDistribution(velocity, position, size) Sampleable that provides positions and velocities sampled from a variety of distributions. # Arguments **`velocity`** and **`position`** provide the velocities and positions and can be any type for which `select_item` has been implemented. **`size`** denotes to the size of the samples that should be produced. # Keywords # Example ```jldoctest; setup = :(using Random; Random.seed!(1)) using NQCDynamics.InitialConditions using Distributions d = DynamicalDistribution(5.0, Normal(), (1, 1)) rand(d) # output ComponentVector{Float64}(v = [5.0;;], r = [0.5314767537831963;;]) ``` """ struct DynamicalDistribution{V,R,S} <: NuclearDistribution velocity::V position::R size::NTuple{S,Int} end Base.size(s::DynamicalDistribution) = s.size Base.length(s::DynamicalDistribution) = lastindex(s) function Base.rand(rng::AbstractRNG, s::DynamicalDistribution) i = rand(rng, 1:lastindex(s)) return getindex(s, i) end Base.firstindex(s::DynamicalDistribution) = 1 function Base.lastindex(s::DynamicalDistribution)::Int if s.velocity isa Vector return length(s.velocity) elseif s.position isa Vector return length(s.position) elseif s.velocity isa String h5open(s.velocity, "r") do fid return length(fid) end elseif s.position isa String h5open(s.position, "r") do fid return length(fid) end else return 1 end end function Base.getindex(s::DynamicalDistribution, i::Integer) return ComponentVector( v=select_item(s.velocity, i, s.size), r=select_item(s.position, i, s.size) ) end Base.getindex(s::DynamicalDistribution, I) = [s[i] for i in I] # Indexed selections select_item(x::Vector{<:AbstractArray}, i::Integer, ::NTuple) = x[i] select_item(x::Vector{<:Number}, i::Integer, size::NTuple) = fill(x[i], size) function select_item(x::AbstractString, i::Integer, ::NTuple) h5open(x, "r") do fid return read(fid, string(i)) end end # Sampled selection select_item(x::Sampleable{Univariate}, ::Integer, size::NTuple) = rand(x, size) function select_item(x::Vector{<:Sampleable{Univariate}}, ::Integer, size::NTuple) if length(x) == size[2] if length(size) == 3 tmpsize = (size[1], 1, size[3]) elseif length(size) == 2 tmpsize = (size[1], 1) end a = rand.(x, Ref(tmpsize)) return cat(a...; dims=2) else return throw(ErrorException( "Distribution size does not match sample size. natoms != length(distribution)" )) end end # Deterministic selections select_item(x::Real, ::Integer, size::NTuple) = fill(x, size) select_item(x::Matrix, ::Integer, ::NTuple) = x select_item(x::AbstractArray{T,3}, ::Integer, ::NTuple) where T = x function Base.show(io::IO, s::DynamicalDistribution) print(io, "DynamicalDistribution with size: ", size(s)) end function Base.show(io::IO, ::MIME"text/plain", s::DynamicalDistribution) print(io, "DynamicalDistribution:\n ", "size: ", size(s)) end function write_hdf5(filename, data) h5open(filename, "w") do fid for (i,d) in enumerate(data) fid[string(i)] = d end end end function Base.iterate(s::DynamicalDistribution, state=1) state > lastindex(s) ? nothing : (s[state], state+1) end
If $f(x)$ and $g(x)$ both tend to infinity as $x$ tends to infinity, then $f(x)g(x)$ tends to infinity as $x$ tends to infinity.
To instruct new Pakistani students in the methods of archaeology , in early 1950 Wheeler ran a training excavation at Mohenjo @-@ daro ; there , he was joined by the British student Leslie Alcock , who spoke both Punjabi and Urdu and who was appointed a site supervisor by Wheeler . This excavation proved to be the only one for which Wheeler would not write and publish a full excavation report . Instead , he made reference to its findings in his book The Indus Civilization , published as part of the series The Cambridge History of India . His relationship with the Pakistani government had become strained , and so he declined to return to work for them for a third year .
{-# OPTIONS --cubical --no-import-sorts --safe #-} open import Cubical.Core.Everything open import Cubical.Foundations.HLevels module Cubical.Algebra.Monoid.Construct.Free {ℓ} (Aˢ : hSet ℓ) where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Univalence open import Cubical.Foundations.Path open import Cubical.Algebra.Monoid open import Cubical.Data.Empty.Polymorphic open import Cubical.Data.Prod open import Cubical.Relation.Binary.Reasoning.Equality private A = ⟨ Aˢ ⟩ isSetA = Aˢ .snd ------------------------------------------------------------------------ -- The direct free monoid type data FreeM : Type ℓ where inj : A → FreeM _•_ : Op₂ FreeM ε : FreeM •-assoc : Associative _•_ ε-identityˡ : LeftIdentity ε _•_ ε-identityʳ : RightIdentity ε _•_ squash : isSet FreeM ε-identity : Identity ε _•_ ε-identity = ε-identityˡ , ε-identityʳ elim : ∀ {ℓ′} {B : FreeM → Type ℓ′} → (∀ x → isSet (B x)) → (∀ x → B (inj x)) → (op : ∀ {x y} → B x → B y → B (x • y)) → (e : B ε) → (∀ {x y z} (a : B x) (b : B y) (c : B z) → PathP (λ i → B (•-assoc x y z i)) (op (op a b) c) (op a (op b c))) → (∀ {x} (a : B x) → PathP (λ i → B (ε-identityˡ x i)) (op e a) a) → (∀ {x} (a : B x) → PathP (λ i → B (ε-identityʳ x i)) (op a e) a) → (x : FreeM) → B x elim isSetB f op e assc idˡ idʳ (inj x) = f x elim isSetB f op e assc idˡ idʳ (x • y) = op (elim isSetB f op e assc idˡ idʳ x) (elim isSetB f op e assc idˡ idʳ y) elim isSetB f op e assc idˡ idʳ ε = e elim isSetB f op e assc idˡ idʳ (•-assoc x y z i) = assc (elim isSetB f op e assc idˡ idʳ x) (elim isSetB f op e assc idˡ idʳ y) (elim isSetB f op e assc idˡ idʳ z) i elim isSetB f op e assc idˡ idʳ (ε-identityˡ x i) = idˡ (elim isSetB f op e assc idˡ idʳ x) i elim isSetB f op e assc idˡ idʳ (ε-identityʳ x i) = idʳ (elim isSetB f op e assc idˡ idʳ x) i elim isSetB f op e assc idˡ idʳ (squash x y p q i j) = isOfHLevel→isOfHLevelDep 2 isSetB (elim isSetB f op e assc idˡ idʳ x) (elim isSetB f op e assc idˡ idʳ y) (cong (elim isSetB f op e assc idˡ idʳ) p) (cong (elim isSetB f op e assc idˡ idʳ) q) (squash x y p q) i j ------------------------------------------------------------------------ -- The simplified free monoid type -- Defined in Cubical.Data.List open import Cubical.Data.List open Structures isSetA public ------------------------------------------------------------------------ -- Proving the two types are equivalent List→FreeM : List A → FreeM List→FreeM [] = ε List→FreeM (x ∷ xs) = inj x • List→FreeM xs FreeM→List : FreeM → List A FreeM→List = elim (λ _ → isOfHLevelList 0 isSetA) [_] _++_ [] ++-assoc ++-identityˡ ++-identityʳ ++-hom : Homomorphic₂ List→FreeM _++_ _•_ ++-hom [] ys = sym (ε-identityˡ _) ++-hom (x ∷ xs) ys = cong (inj x •_) (++-hom xs ys) ∙ sym (•-assoc (inj x) (List→FreeM xs) (List→FreeM ys)) List→FreeM→List : retract List→FreeM FreeM→List List→FreeM→List [] = refl List→FreeM→List (x ∷ xs) = cong (x ∷_) (List→FreeM→List xs) FreeM→List→FreeM : section List→FreeM FreeM→List FreeM→List→FreeM = elim (λ _ → isSet→isGroupoid squash _ _) (λ _ → ε-identityʳ _) sectionOp refl (λ _ _ _ → isOfHLevelPathP' 0 (squash _ _) _ _ .fst) (λ _ → isOfHLevelPathP' 0 (squash _ _) _ _ .fst) (λ _ → isOfHLevelPathP' 0 (squash _ _) _ _ .fst) where sectionOp : ∀ {x y} → List→FreeM (FreeM→List x) ≡ x → List→FreeM (FreeM→List y) ≡ y → List→FreeM (FreeM→List (x • y)) ≡ (x • y) sectionOp {x} {y} p q = List→FreeM (FreeM→List (x • y)) ≡⟨⟩ List→FreeM (FreeM→List x ++ FreeM→List y) ≡⟨ ++-hom (FreeM→List x) (FreeM→List y) ⟩ List→FreeM (FreeM→List x) • List→FreeM (FreeM→List y) ≡⟨ cong₂ _•_ p q ⟩ x • y ∎ List≃FreeM : List A ≃ FreeM List≃FreeM = isoToEquiv (iso List→FreeM FreeM→List FreeM→List→FreeM List→FreeM→List) List≡FreeM : List A ≡ FreeM List≡FreeM = ua List≃FreeM ------------------------------------------------------------------------ -- Monoid structure FreeM-isMonoid : IsMonoid FreeM _•_ ε FreeM-isMonoid = record { isSemigroup = record { isMagma = record { is-set = squash } ; assoc = •-assoc } ; identity = ε-identity } FreeMonoid : Monoid ℓ FreeMonoid = record { isMonoid = FreeM-isMonoid } EquivFreeM : MonoidEquiv ListMonoid FreeMonoid EquivFreeM = record { eq = List≃FreeM ; isHom = record { preservesOp = ++-hom ; preservesId = refl } } FreeMonoid≡ : ListMonoid ≡ FreeMonoid FreeMonoid≡ = uaMonoid EquivFreeM
Require Import List Arith Ascii String. Import ListNotations. Open Scope string_scope. Inductive prim := PtrIncr | PtrDecr | Incr | Decr | Get. Inductive stmt := | SNil : stmt | Prim : prim -> stmt -> stmt | Put : stmt -> stmt | Loop : stmt -> stmt -> stmt. Fixpoint parse' (str : string) := match str with | "" => (SNil, nil) | String x xs => let (body, rest) := parse' xs in match x with | ">"%char => (Prim PtrIncr body, rest) | "<"%char => (Prim PtrDecr body, rest) | "+"%char => (Prim Incr body, rest) | "-"%char => (Prim Decr body, rest) | ","%char => (Prim Get body, rest) | "."%char => (Put body, rest) | "["%char => match rest with | nil => (Loop body SNil, nil) | cons s rest' => (Loop body s, rest') end | "]"%char => (SNil, cons body rest) | _ => (SNil, nil) end end. Definition parse str := fst (parse' str). Definition run_prim (env : (nat -> nat) * nat * list nat) p := let '(data, ptr, input) := env in match p with | PtrIncr => (data, S ptr, input) | PtrDecr => (data, pred ptr, input) | Incr => (fun i => if Nat.eq_dec i ptr then S (data ptr) else data i, ptr, input) | Decr => (fun i => if Nat.eq_dec i ptr then pred (data ptr) else data i, ptr, input) | Get => match input with | [] => env | x::rest => (fun i => if Nat.eq_dec i ptr then x else data i, ptr, rest) end end. Fixpoint append (s1 s2 : stmt) := match s1 with | SNil => s2 | Prim p s => Prim p (append s s2) | Put s => Put (append s s2) | Loop b s => Loop b (append s s2) end. Ltac run env c' := let c := eval compute in c' in match env with | (?data, ?ptr, ?input) => match c with | SNil => idtac | Prim ?p ?c' => let env' := eval compute in (run_prim (data,ptr,input) p) in run env' c' | Put ?c' => let x := eval compute in (data ptr) in idtac x; run env c' | Loop ?c1 ?c2 => let x := eval compute in (Nat.eq_dec (data ptr) 0) in match x with | left _ => run env c2 | right _ => run env (append c1 (Loop c1 c2)) end end end. Goal True. run ((fun _:nat=>0), 0, [4;3]) (parse ",>,<[-<+>]<."). run ((fun _:nat=>0), 0, [3;3]) (parse ",>,<[->[->>+<<]>>[-<+<+>>]<<<]>>."). run ((fun _:nat=>0), 0, @nil nat) (parse "+[>.+<]"). Abort.
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import tactic.basic /-- `ℕ+` is the type of positive natural numbers. It is defined as a subtype, and the VM representation of `ℕ+` is the same as `ℕ` because the proof is not stored. -/ def pnat := {n : ℕ // n > 0} notation `ℕ+` := pnat instance coe_pnat_nat : has_coe ℕ+ ℕ := ⟨subtype.val⟩ namespace nat /-- Convert a natural number to a positive natural number. The positivity assumption is inferred by `dec_trivial`. -/ def to_pnat (n : ℕ) (h : n > 0 . tactic.exact_dec_trivial) : ℕ+ := ⟨n, h⟩ /-- Write a successor as an element of `ℕ+`. -/ def succ_pnat (n : ℕ) : ℕ+ := ⟨succ n, succ_pos n⟩ @[simp] theorem succ_pnat_coe (n : ℕ) : (succ_pnat n : ℕ) = succ n := rfl /-- Convert a natural number to a pnat. `n+1` is mapped to itself, and `0` becomes `1`. -/ def to_pnat' (n : ℕ) : ℕ+ := succ_pnat (pred n) end nat namespace pnat open nat @[simp] theorem pos (n : ℕ+) : (n : ℕ) > 0 := n.2 theorem eq {m n : ℕ+} : (m : ℕ) = n → m = n := subtype.eq @[simp] theorem mk_coe (n h) : ((⟨n, h⟩ : ℕ+) : ℕ) = n := rfl instance : has_add ℕ+ := ⟨λ m n, ⟨m + n, add_pos m.2 n.2⟩⟩ @[simp] theorem add_coe (m n : ℕ+) : ((m + n : ℕ+) : ℕ) = m + n := rfl @[simp] theorem ne_zero (n : ℕ+) : (n : ℕ) ≠ 0 := ne_of_gt n.2 @[simp] theorem to_pnat'_coe {n : ℕ} : n > 0 → (n.to_pnat' : ℕ) = n := succ_pred_eq_of_pos @[simp] theorem coe_to_pnat' (n : ℕ+) : (n : ℕ).to_pnat' = n := eq (to_pnat'_coe n.pos) instance : comm_monoid ℕ+ := { mul := λ m n, ⟨m.1 * n.1, mul_pos m.2 n.2⟩, mul_assoc := λ a b c, subtype.eq (mul_assoc _ _ _), one := succ_pnat 0, one_mul := λ a, subtype.eq (one_mul _), mul_one := λ a, subtype.eq (mul_one _), mul_comm := λ a b, subtype.eq (mul_comm _ _) } @[simp] theorem one_coe : ((1 : ℕ+) : ℕ) = 1 := rfl @[simp] theorem mul_coe (m n : ℕ+) : ((m * n : ℕ+) : ℕ) = m * n := rfl /-- The power of a pnat and a nat is a pnat. -/ def pow (m : ℕ+) (n : ℕ) : ℕ+ := ⟨m ^ n, nat.pos_pow_of_pos _ m.pos⟩ instance : has_pow ℕ+ ℕ := ⟨pow⟩ @[simp] theorem pow_coe (m : ℕ+) (n : ℕ) : (↑(m ^ n) : ℕ) = m ^ n := rfl instance : has_repr ℕ+ := ⟨λ n, repr n.1⟩ end pnat
lemma linear_continuous_on: "bounded_linear f \<Longrightarrow> continuous_on s f"
Require Import CodeProofDeps. Require Import Ident. Require Import Constants. Require Import RData. Require Import EventReplay. Require Import MoverTypes. Require Import CommonLib. Require Import AbsAccessor.Spec. Require Import RmiAux2.Spec. Require Import RmiAux2.Layer. Require Import RmiOps.Code.rec_create_ops. Require Import RmiOps.LowSpecs.rec_create_ops. Local Open Scope Z_scope. Section CodeProof. Context `{real_params: RealParams}. Context {memb} `{Hmemx: Mem.MemoryModelX memb}. Context `{Hmwd: UseMemWithData memb}. Let mem := mwd (cdata RData). Context `{Hstencil: Stencil}. Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}. Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}. Let L : compatlayer (cdata RData) := _granule_set_state ↦ gensem granule_set_state_spec ⊕ _realm_set_rec_entry ↦ gensem realm_set_rec_entry_spec ⊕ _init_rec_read_only ↦ gensem init_rec_read_only_spec ⊕ _init_rec_regs ↦ gensem init_rec_regs_spec ⊕ _init_rec_rvic_state ↦ gensem init_rec_rvic_state_spec ⊕ _get_rec_rvic ↦ gensem get_rec_rvic_spec ⊕ _get_rd_par_base ↦ gensem get_rd_par_base_spec ⊕ _set_rec_par_base ↦ gensem set_rec_par_base_spec ⊕ _get_rd_par_end ↦ gensem get_rd_par_end_spec ⊕ _set_rec_par_end ↦ gensem set_rec_par_end_spec ⊕ _set_rec_g_rd ↦ gensem set_rec_g_rd_spec ⊕ _get_rd_g_rec_list ↦ gensem get_rd_g_rec_list_spec ⊕ _set_rec_g_rec_list ↦ gensem set_rec_g_rec_list_spec ⊕ _rec_granule_measure ↦ gensem rec_granule_measure_spec ⊕ _set_g_rec_rd ↦ gensem set_g_rec_rd_spec ⊕ _granule_get ↦ gensem granule_get_spec ⊕ _atomic_granule_get ↦ gensem atomic_granule_get_spec ⊕ _get_rec_params_flags ↦ gensem get_rec_params_flags_spec ⊕ _set_rec_runnable ↦ gensem set_rec_runnable_spec . Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L. Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L. Section BodyProof. Context `{Hwb: WritableBlockOps}. Variable (sc: stencil). Variables (ge: genv) (STENCIL_MATCHES: stencil_matches sc ge). Variable b_granule_set_state: block. Hypothesis h_granule_set_state_s : Genv.find_symbol ge _granule_set_state = Some b_granule_set_state. Hypothesis h_granule_set_state_p : Genv.find_funct_ptr ge b_granule_set_state = Some (External (EF_external _granule_set_state (signature_of_type (Tcons Tptr (Tcons tuint Tnil)) tvoid cc_default)) (Tcons Tptr (Tcons tuint Tnil)) tvoid cc_default). Local Opaque granule_set_state_spec. Variable b_realm_set_rec_entry: block. Hypothesis h_realm_set_rec_entry_s : Genv.find_symbol ge _realm_set_rec_entry = Some b_realm_set_rec_entry. Hypothesis h_realm_set_rec_entry_p : Genv.find_funct_ptr ge b_realm_set_rec_entry = Some (External (EF_external _realm_set_rec_entry (signature_of_type (Tcons tulong (Tcons Tptr (Tcons Tptr Tnil))) tvoid cc_default)) (Tcons tulong (Tcons Tptr (Tcons Tptr Tnil))) tvoid cc_default). Local Opaque realm_set_rec_entry_spec. Variable b_init_rec_read_only: block. Hypothesis h_init_rec_read_only_s : Genv.find_symbol ge _init_rec_read_only = Some b_init_rec_read_only. Hypothesis h_init_rec_read_only_p : Genv.find_funct_ptr ge b_init_rec_read_only = Some (External (EF_external _init_rec_read_only (signature_of_type (Tcons Tptr (Tcons Tptr (Tcons tulong Tnil))) tvoid cc_default)) (Tcons Tptr (Tcons Tptr (Tcons tulong Tnil))) tvoid cc_default). Local Opaque init_rec_read_only_spec. Variable b_init_rec_regs: block. Hypothesis h_init_rec_regs_s : Genv.find_symbol ge _init_rec_regs = Some b_init_rec_regs. Hypothesis h_init_rec_regs_p : Genv.find_funct_ptr ge b_init_rec_regs = Some (External (EF_external _init_rec_regs (signature_of_type (Tcons Tptr (Tcons tulong (Tcons Tptr Tnil))) tvoid cc_default)) (Tcons Tptr (Tcons tulong (Tcons Tptr Tnil))) tvoid cc_default). Local Opaque init_rec_regs_spec. Variable b_init_rec_rvic_state: block. Hypothesis h_init_rec_rvic_state_s : Genv.find_symbol ge _init_rec_rvic_state = Some b_init_rec_rvic_state. Hypothesis h_init_rec_rvic_state_p : Genv.find_funct_ptr ge b_init_rec_rvic_state = Some (External (EF_external _init_rec_rvic_state (signature_of_type (Tcons Tptr Tnil) tvoid cc_default)) (Tcons Tptr Tnil) tvoid cc_default). Local Opaque init_rec_rvic_state_spec. Variable b_get_rec_rvic: block. Hypothesis h_get_rec_rvic_s : Genv.find_symbol ge _get_rec_rvic = Some b_get_rec_rvic. Hypothesis h_get_rec_rvic_p : Genv.find_funct_ptr ge b_get_rec_rvic = Some (External (EF_external _get_rec_rvic (signature_of_type (Tcons Tptr Tnil) Tptr cc_default)) (Tcons Tptr Tnil) Tptr cc_default). Local Opaque get_rec_rvic_spec. Variable b_get_rd_par_base: block. Hypothesis h_get_rd_par_base_s : Genv.find_symbol ge _get_rd_par_base = Some b_get_rd_par_base. Hypothesis h_get_rd_par_base_p : Genv.find_funct_ptr ge b_get_rd_par_base = Some (External (EF_external _get_rd_par_base (signature_of_type (Tcons Tptr Tnil) tulong cc_default)) (Tcons Tptr Tnil) tulong cc_default). Local Opaque get_rd_par_base_spec. Variable b_set_rec_par_base: block. Hypothesis h_set_rec_par_base_s : Genv.find_symbol ge _set_rec_par_base = Some b_set_rec_par_base. Hypothesis h_set_rec_par_base_p : Genv.find_funct_ptr ge b_set_rec_par_base = Some (External (EF_external _set_rec_par_base (signature_of_type (Tcons Tptr (Tcons tulong Tnil)) tvoid cc_default)) (Tcons Tptr (Tcons tulong Tnil)) tvoid cc_default). Local Opaque set_rec_par_base_spec. Variable b_get_rd_par_end: block. Hypothesis h_get_rd_par_end_s : Genv.find_symbol ge _get_rd_par_end = Some b_get_rd_par_end. Hypothesis h_get_rd_par_end_p : Genv.find_funct_ptr ge b_get_rd_par_end = Some (External (EF_external _get_rd_par_end (signature_of_type (Tcons Tptr Tnil) tulong cc_default)) (Tcons Tptr Tnil) tulong cc_default). Local Opaque get_rd_par_end_spec. Variable b_set_rec_par_end: block. Hypothesis h_set_rec_par_end_s : Genv.find_symbol ge _set_rec_par_end = Some b_set_rec_par_end. Hypothesis h_set_rec_par_end_p : Genv.find_funct_ptr ge b_set_rec_par_end = Some (External (EF_external _set_rec_par_end (signature_of_type (Tcons Tptr (Tcons tulong Tnil)) tvoid cc_default)) (Tcons Tptr (Tcons tulong Tnil)) tvoid cc_default). Local Opaque set_rec_par_end_spec. Variable b_set_rec_g_rd: block. Hypothesis h_set_rec_g_rd_s : Genv.find_symbol ge _set_rec_g_rd = Some b_set_rec_g_rd. Hypothesis h_set_rec_g_rd_p : Genv.find_funct_ptr ge b_set_rec_g_rd = Some (External (EF_external _set_rec_g_rd (signature_of_type (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default)) (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default). Local Opaque set_rec_g_rd_spec. Variable b_get_rd_g_rec_list: block. Hypothesis h_get_rd_g_rec_list_s : Genv.find_symbol ge _get_rd_g_rec_list = Some b_get_rd_g_rec_list. Hypothesis h_get_rd_g_rec_list_p : Genv.find_funct_ptr ge b_get_rd_g_rec_list = Some (External (EF_external _get_rd_g_rec_list (signature_of_type (Tcons Tptr Tnil) Tptr cc_default)) (Tcons Tptr Tnil) Tptr cc_default). Local Opaque get_rd_g_rec_list_spec. Variable b_set_rec_g_rec_list: block. Hypothesis h_set_rec_g_rec_list_s : Genv.find_symbol ge _set_rec_g_rec_list = Some b_set_rec_g_rec_list. Hypothesis h_set_rec_g_rec_list_p : Genv.find_funct_ptr ge b_set_rec_g_rec_list = Some (External (EF_external _set_rec_g_rec_list (signature_of_type (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default)) (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default). Local Opaque set_rec_g_rec_list_spec. Variable b_rec_granule_measure: block. Hypothesis h_rec_granule_measure_s : Genv.find_symbol ge _rec_granule_measure = Some b_rec_granule_measure. Hypothesis h_rec_granule_measure_p : Genv.find_funct_ptr ge b_rec_granule_measure = Some (External (EF_external _rec_granule_measure (signature_of_type (Tcons Tptr (Tcons Tptr (Tcons tulong Tnil))) tvoid cc_default)) (Tcons Tptr (Tcons Tptr (Tcons tulong Tnil))) tvoid cc_default). Local Opaque rec_granule_measure_spec. Variable b_set_g_rec_rd: block. Hypothesis h_set_g_rec_rd_s : Genv.find_symbol ge _set_g_rec_rd = Some b_set_g_rec_rd. Hypothesis h_set_g_rec_rd_p : Genv.find_funct_ptr ge b_set_g_rec_rd = Some (External (EF_external _set_g_rec_rd (signature_of_type (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default)) (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default). Local Opaque set_g_rec_rd_spec. Variable b_granule_get: block. Hypothesis h_granule_get_s : Genv.find_symbol ge _granule_get = Some b_granule_get. Hypothesis h_granule_get_p : Genv.find_funct_ptr ge b_granule_get = Some (External (EF_external _granule_get (signature_of_type (Tcons Tptr Tnil) tvoid cc_default)) (Tcons Tptr Tnil) tvoid cc_default). Local Opaque granule_get_spec. Variable b_atomic_granule_get: block. Hypothesis h_atomic_granule_get_s : Genv.find_symbol ge _atomic_granule_get = Some b_atomic_granule_get. Hypothesis h_atomic_granule_get_p : Genv.find_funct_ptr ge b_atomic_granule_get = Some (External (EF_external _atomic_granule_get (signature_of_type (Tcons Tptr Tnil) tvoid cc_default)) (Tcons Tptr Tnil) tvoid cc_default). Local Opaque atomic_granule_get_spec. Variable b_get_rec_params_flags: block. Hypothesis h_get_rec_params_flags_s : Genv.find_symbol ge _get_rec_params_flags = Some b_get_rec_params_flags. Hypothesis h_get_rec_params_flags_p : Genv.find_funct_ptr ge b_get_rec_params_flags = Some (External (EF_external _get_rec_params_flags (signature_of_type Tnil tulong cc_default)) Tnil tulong cc_default). Local Opaque get_rec_params_flags_spec. Variable b_set_rec_runnable: block. Hypothesis h_set_rec_runnable_s : Genv.find_symbol ge _set_rec_runnable = Some b_set_rec_runnable. Hypothesis h_set_rec_runnable_p : Genv.find_funct_ptr ge b_set_rec_runnable = Some (External (EF_external _set_rec_runnable (signature_of_type (Tcons Tptr (Tcons tuint Tnil)) tvoid cc_default)) (Tcons Tptr (Tcons tuint Tnil)) tvoid cc_default). Local Opaque set_rec_runnable_spec. (* Lemma rec_create_ops_body_correct: forall m d d' env le g_rd_base g_rd_offset g_rec_base g_rec_offset rd_base rd_offset rec_list_base rec_list_offset rec_base rec_offset mpidr rec_idx (Henv: env = PTree.empty _) (Hinv: high_level_invariant d) (HPTg_rd: PTree.get _g_rd le = Some (Vptr g_rd_base (Int.repr g_rd_offset))) (HPTg_rec: PTree.get _g_rec le = Some (Vptr g_rec_base (Int.repr g_rec_offset))) (HPTrd: PTree.get _rd le = Some (Vptr rd_base (Int.repr rd_offset))) (HPTrec_list: PTree.get _rec_list le = Some (Vptr rec_list_base (Int.repr rec_list_offset))) (HPTrec: PTree.get _rec le = Some (Vptr rec_base (Int.repr rec_offset))) (HPTmpidr: PTree.get _mpidr le = Some (Vlong mpidr)) (HPTrec_idx: PTree.get _rec_idx le = Some (Vlong rec_idx)) (Hspec: rec_create_ops_spec0 (g_rd_base, g_rd_offset) (g_rec_base, g_rec_offset) (rd_base, rd_offset) (rec_list_base, rec_list_offset) (rec_base, rec_offset) (VZ64 (Int64.unsigned mpidr)) (VZ64 (Int64.unsigned rec_idx)) d = Some d'), exists le', (exec_stmt ge env le ((m, d): mem) rec_create_ops_body E0 le' (m, d') Out_normal). Proof. solve_code_proof Hspec rec_create_ops_body; eexists; solve_proof_low. Qed. *) End BodyProof. End CodeProof.
/*============================================================================== Copyright (c) 2016, 2017, 2018 Matt Calabrese 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) ==============================================================================*/ #ifndef ARGOT_RECEIVER_GRAPHVIZ_GRAPH_KIND_HPP_ #define ARGOT_RECEIVER_GRAPHVIZ_GRAPH_KIND_HPP_ #include <graphviz/cgraph.h> #include <boost/graph/graph_traits.hpp> #include <type_traits> namespace argot { namespace receiver { namespace graphviz { enum class graph_kind { directed, strict_directed, undirected, strict_undirected }; namespace graph_kind_detail { template< graph_kind kind > struct graph_kind_traits_impl { using is_valid = std::false_type; }; template<> struct graph_kind_traits_impl< graph_kind::directed > { using is_valid = std::true_type; using directed_category = boost::directed_tag; using edge_parallel_category = boost::allow_parallel_edge_tag; // TODO(mattcalabrese) construct instead of returning the constant. static Agdesc_t description() { return Agdirected; } }; template<> struct graph_kind_traits_impl< graph_kind::strict_directed > { using is_valid = std::true_type; using directed_category = boost::directed_tag; using edge_parallel_category = boost::disallow_parallel_edge_tag; // TODO(mattcalabrese) construct instead of returning the constant. static Agdesc_t description() { return Agstrictdirected; } }; template<> struct graph_kind_traits_impl< graph_kind::undirected > { using is_valid = std::true_type; using directed_category = boost::undirected_tag; using edge_parallel_category = boost::allow_parallel_edge_tag; // TODO(mattcalabrese) construct instead of returning the constant. static Agdesc_t description() { return Agundirected; } }; template<> struct graph_kind_traits_impl< graph_kind::strict_undirected > { using is_valid = std::true_type; using directed_category = boost::undirected_tag; using edge_parallel_category = boost::disallow_parallel_edge_tag; // TODO(mattcalabrese) construct instead of returning the constant. static Agdesc_t description() { return Agstrictundirected; } }; } // namespace argot::receiver::graphviz::graph_kind_detail template< graph_kind kind > struct is_valid_graph_kind : graph_kind_detail::graph_kind_traits_impl< kind >::is_valid{}; template< graph_kind kind > inline bool constexpr is_valid_graph_kind_v = is_valid_graph_kind< kind >::value; } // namespace argot::receiver::graphviz } // namespace argot::receiver } // namespace argot #endif // ARGOT_RECEIVER_GRAPHVIZ_GRAPH_KIND_HPP_
library(rrBLUP) library(data.table) args = commandArgs(trailingOnly=TRUE) X_file <- args[1] # geno matrix Y_file <- args[2] # pheno matrix test_file <- args[3] # individuals in test set geno <- fread(X_file) test <- scan(test_file, what='character') training <- geno[geno$ID %in% setdiff(geno$ID,test),] write.csv(training,'geno_training.csv',quote=F,row.names=F) Y <- read.csv(Y_file, row.names=1) Y <- Y[!rownames(Y) %in% test,] write.csv(Y,'pheno_training.csv',row.names=T,quote=F)
The Anne B. Kingsley Ovarian Cancer Foundation was founded in 2005 by Anne Kingsleys son, Robert Kingsley, to support research that helps in the early detection of ovarian cancer. The Davis Davisbased NonProfit Organizations nonprofit also supports graduate students working in gynecological oncology. Family and friends help with fundraising and managing the small foundation, in order to limit overhead costs. Mention of the foundation in the wiki:sacramento:Sacramento Business Journal: http://sacramento.bizjournals.com/sacramento/stories/2006/03/06/story6.html
represents EGEA externally and acts as the executive body of the association. Do you have any feedback for the Board of EGEA? Then click here. Do you have any feedback for Swen? Then click here. Do you have any feedback for Valentina? Then click here. Do you have any feedback for Milan? Then click here. Do you have any feedback for Frederike? Then click here. Do you have any feedback for Anna? Then click here. For more details about the teams and the country responsibilities, check out the information below. of support for the Board of EGEA and the Regional Teams. )* until 2012 Annual Congress Organiser, then until 2015 Annual Congress Coordinator. If you know the names of the officials before 1992, please write to webadmin[at]egea.eu.
-- Andreas, 2017-07-26 -- Better error message when constructor not fully applied. open import Agda.Builtin.Nat test : (Nat → Nat) → Nat test suc = suc zero -- WAS: Type mismatch -- NOW: Cannot pattern match on functions -- when checking that the pattern suc has type Nat → Nat
Formal statement is: lemma offset_poly_eq_0_iff: "offset_poly p h = 0 \<longleftrightarrow> p = 0" Informal statement is: The offset polynomial of a polynomial $p$ is zero if and only if $p$ is zero.
Formal statement is: lemma limitin_sequentially: "limitin X S l sequentially \<longleftrightarrow> l \<in> topspace X \<and> (\<forall>U. openin X U \<and> l \<in> U \<longrightarrow> (\<exists>N. \<forall>n. N \<le> n \<longrightarrow> S n \<in> U))" Informal statement is: A sequence $S$ converges to a point $l$ in a topological space $X$ if and only if $l$ is a point of $X$ and for every open set $U$ containing $l$, there exists an integer $N$ such that for all $n \geq N$, $S(n)$ is in $U$.
[STATEMENT] lemma codomain_unique: assumes "b \<in> codomains f" and "b' \<in> codomains f" shows "b = b'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. b = b' [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. b = b' [PROOF STEP] have "ide b \<and> seq b f \<and> ide b' \<and> seq b' f" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ide b \<and> seq b f \<and> ide b' \<and> seq b' f [PROOF STEP] using assms codomains_def ext [PROOF STATE] proof (prove) using this: b \<in> codomains f b' \<in> codomains f codomains ?f \<equiv> {b. ide b \<and> b \<cdot> ?f \<noteq> null} ?g \<cdot> ?f \<noteq> null \<Longrightarrow> seq ?g ?f goal (1 subgoal): 1. ide b \<and> seq b f \<and> ide b' \<and> seq b' f [PROOF STEP] by force [PROOF STATE] proof (state) this: ide b \<and> seq b f \<and> ide b' \<and> seq b' f goal (1 subgoal): 1. b = b' [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: ide b \<and> seq b f \<and> ide b' \<and> seq b' f goal (1 subgoal): 1. b = b' [PROOF STEP] using match_2 ide_def not_arr_null [PROOF STATE] proof (prove) using this: ide b \<and> seq b f \<and> ide b' \<and> seq b' f \<lbrakk>seq ?h (?g \<cdot> ?f); seq ?g ?f\<rbrakk> \<Longrightarrow> seq ?h ?g ide ?a \<equiv> ?a \<cdot> ?a \<noteq> null \<and> (\<forall>f. (f \<cdot> ?a \<noteq> null \<longrightarrow> f \<cdot> ?a = f) \<and> (?a \<cdot> f \<noteq> null \<longrightarrow> ?a \<cdot> f = f)) \<not> arr null goal (1 subgoal): 1. b = b' [PROOF STEP] by metis [PROOF STATE] proof (state) this: b = b' goal: No subgoals! [PROOF STEP] qed
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro ! This file was ported from Lean 3 source module data.multiset.basic ! leanprover-community/mathlib commit 2ec920d35348cb2d13ac0e1a2ad9df0fdf1a76b4 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Data.Set.List import Mathlib.Data.List.Perm import Mathlib.Init.Quot -- Porting note: added import /-! # Multisets These are implemented as the quotient of a list by permutations. ## Notation We define the global infix notation `::ₘ` for `Multiset.cons`. -/ open List Subtype Nat Function variable {α : Type _} {β : Type _} {γ : Type _} /-- `Multiset α` is the quotient of `List α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def Multiset.{u} (α : Type u) : Type u := Quotient (List.isSetoid α) #align multiset Multiset namespace Multiset -- Porting note: new /-- The quotient map from `List α` to `Multiset α`. -/ @[coe] def ofList : List α → Multiset α := Quot.mk _ instance : Coe (List α) (Multiset α) := ⟨ofList⟩ @[simp] theorem quot_mk_to_coe (l : List α) : @Eq (Multiset α) ⟦l⟧ l := rfl #align multiset.quot_mk_to_coe Multiset.quot_mk_to_coe @[simp] theorem quot_mk_to_coe' (l : List α) : @Eq (Multiset α) (Quot.mk (· ≈ ·) l) l := rfl #align multiset.quot_mk_to_coe' Multiset.quot_mk_to_coe' @[simp] theorem quot_mk_to_coe'' (l : List α) : @Eq (Multiset α) (Quot.mk Setoid.r l) l := rfl #align multiset.quot_mk_to_coe'' Multiset.quot_mk_to_coe'' @[simp] theorem coe_eq_coe {l₁ l₂ : List α} : (l₁ : Multiset α) = l₂ ↔ l₁ ~ l₂ := Quotient.eq #align multiset.coe_eq_coe Multiset.coe_eq_coe -- Porting note: new, TODO move to better place instance [DecidableEq α] (l₁ l₂ : List α) : Decidable (l₁ ≈ l₂) := inferInstanceAs (Decidable (l₁ ~ l₂)) -- Porting note: `Quotient.recOnSubsingleton₂ s₁ s₂` was in parens which broke elaboration instance decidableEq [DecidableEq α] : DecidableEq (Multiset α) | s₁, s₂ => Quotient.recOnSubsingleton₂ s₁ s₂ fun _ _ => decidable_of_iff' _ Quotient.eq #align multiset.has_decidable_eq Multiset.decidableEq /-- defines a size for a multiset by referring to the size of the underlying list -/ protected def sizeOf [SizeOf α] (s : Multiset α) : ℕ := (Quot.liftOn s SizeOf.sizeOf) fun _ _ => Perm.sizeOf_eq_sizeOf #align multiset.sizeof Multiset.sizeOf instance [SizeOf α] : SizeOf (Multiset α) := ⟨Multiset.sizeOf⟩ /-! ### Empty multiset -/ /-- `0 : Multiset α` is the empty set -/ protected def zero : Multiset α := @nil α #align multiset.zero Multiset.zero instance : Zero (Multiset α) := ⟨Multiset.zero⟩ instance : EmptyCollection (Multiset α) := ⟨0⟩ instance inhabitedMultiset : Inhabited (Multiset α) := ⟨0⟩ #align multiset.inhabited_multiset Multiset.inhabitedMultiset @[simp] theorem coe_nil : (@nil α : Multiset α) = 0 := rfl #align multiset.coe_nil Multiset.coe_nil @[simp] theorem empty_eq_zero : (∅ : Multiset α) = 0 := rfl #align multiset.empty_eq_zero Multiset.empty_eq_zero @[simp] theorem coe_eq_zero (l : List α) : (l : Multiset α) = 0 ↔ l = [] := Iff.trans coe_eq_coe perm_nil #align multiset.coe_eq_zero Multiset.coe_eq_zero theorem coe_eq_zero_iff_isEmpty (l : List α) : (l : Multiset α) = 0 ↔ l.isEmpty := Iff.trans (coe_eq_zero l) isEmpty_iff_eq_nil.symm #align multiset.coe_eq_zero_iff_empty Multiset.coe_eq_zero_iff_isEmpty /-! ### `Multiset.cons` -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : Multiset α) : Multiset α := Quot.liftOn s (fun l => (a :: l : Multiset α)) fun _ _ p => Quot.sound (p.cons a) #align multiset.cons Multiset.cons @[inherit_doc Multiset.cons] infixr:67 " ::ₘ " => Multiset.cons instance : Insert α (Multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : Multiset α) : insert a s = a ::ₘ s := rfl #align multiset.insert_eq_cons Multiset.insert_eq_cons @[simp] theorem cons_coe (a : α) (l : List α) : (a ::ₘ l : Multiset α) = (a :: l : List α) := rfl #align multiset.cons_coe Multiset.cons_coe @[simp] theorem cons_inj_left {a b : α} (s : Multiset α) : a ::ₘ s = b ::ₘ s ↔ a = b := ⟨Quot.inductionOn s fun l e => have : [a] ++ l ~ [b] ++ l := Quotient.exact e singleton_perm_singleton.1 <| (perm_append_right_iff _).1 this, congr_arg (· ::ₘ _)⟩ #align multiset.cons_inj_left Multiset.cons_inj_left @[simp] theorem cons_inj_right (a : α) : ∀ {s t : Multiset α}, a ::ₘ s = a ::ₘ t ↔ s = t := by rintro ⟨l₁⟩ ⟨l₂⟩; simp #align multiset.cons_inj_right Multiset.cons_inj_right @[recursor 5] protected theorem induction {p : Multiset α → Prop} (empty : p 0) (cons : ∀ ⦃a : α⦄ {s : Multiset α}, p s → p (a ::ₘ s)) : ∀ s, p s := by rintro ⟨l⟩; induction' l with _ _ ih <;> [exact empty, exact cons ih] #align multiset.induction Multiset.induction @[elab_as_elim] protected theorem induction_on {p : Multiset α → Prop} (s : Multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : Multiset α}, p s → p (a ::ₘ s)) : p s := Multiset.induction h₁ h₂ s #align multiset.induction_on Multiset.induction_on theorem cons_swap (a b : α) (s : Multiset α) : a ::ₘ b ::ₘ s = b ::ₘ a ::ₘ s := Quot.inductionOn s fun _ => Quotient.sound <| Perm.swap _ _ _ #align multiset.cons_swap Multiset.cons_swap section Rec variable {C : Multiset α → Sort _} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `Multiset.pi` fails with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : ∀ a m, C m → C (a ::ₘ m)) (C_cons_heq : ∀ a a' m b, HEq (C_cons a (a' ::ₘ m) (C_cons a' m b)) (C_cons a' (a ::ₘ m) (C_cons a m b))) (m : Multiset α) : C m := Quotient.hrecOn m (@List.rec α (fun l => C ⟦l⟧) C_0 fun a l b => C_cons a ⟦l⟧ b) fun l l' h => h.rec_heq (fun hl _ ↦ by congr 1; exact Quot.sound hl) (C_cons_heq _ _ ⟦_⟧ _) #align multiset.rec Multiset.rec /-- Companion to `Multiset.rec` with more convenient argument order. -/ @[elab_as_elim] protected def recOn (m : Multiset α) (C_0 : C 0) (C_cons : ∀ a m, C m → C (a ::ₘ m)) (C_cons_heq : ∀ a a' m b, HEq (C_cons a (a' ::ₘ m) (C_cons a' m b)) (C_cons a' (a ::ₘ m) (C_cons a m b))) : C m := Multiset.rec C_0 C_cons C_cons_heq m #align multiset.rec_on Multiset.recOn variable {C_0 : C 0} {C_cons : ∀ a m, C m → C (a ::ₘ m)} {C_cons_heq : ∀ a a' m b, HEq (C_cons a (a' ::ₘ m) (C_cons a' m b)) (C_cons a' (a ::ₘ m) (C_cons a m b))} @[simp] theorem recOn_0 : @Multiset.recOn α C (0 : Multiset α) C_0 C_cons C_cons_heq = C_0 := rfl #align multiset.rec_on_0 Multiset.recOn_0 @[simp] theorem recOn_cons (a : α) (m : Multiset α) : (a ::ₘ m).recOn C_0 C_cons C_cons_heq = C_cons a m (m.recOn C_0 C_cons C_cons_heq) := Quotient.inductionOn m fun _ => rfl #align multiset.rec_on_cons Multiset.recOn_cons end Rec section Mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def Mem (a : α) (s : Multiset α) : Prop := Quot.liftOn s (fun l => a ∈ l) fun l₁ l₂ (e : l₁ ~ l₂) => propext <| e.mem_iff #align multiset.mem Multiset.Mem instance : Membership α (Multiset α) := ⟨Mem⟩ @[simp] theorem mem_coe {a : α} {l : List α} : a ∈ (l : Multiset α) ↔ a ∈ l := Iff.rfl #align multiset.mem_coe Multiset.mem_coe instance decidableMem [DecidableEq α] (a : α) (s : Multiset α) : Decidable (a ∈ s) := Quot.recOnSubsingleton' s <| fun l ↦ inferInstanceAs (Decidable (a ∈ l)) #align multiset.decidable_mem Multiset.decidableMem @[simp] theorem mem_cons {a b : α} {s : Multiset α} : a ∈ b ::ₘ s ↔ a = b ∨ a ∈ s := Quot.inductionOn s fun _ => List.mem_cons #align multiset.mem_cons Multiset.mem_cons theorem mem_cons_of_mem {a b : α} {s : Multiset α} (h : a ∈ s) : a ∈ b ::ₘ s := mem_cons.2 <| Or.inr h #align multiset.mem_cons_of_mem Multiset.mem_cons_of_mem -- @[simp] -- Porting note: simp can prove this theorem mem_cons_self (a : α) (s : Multiset α) : a ∈ a ::ₘ s := mem_cons.2 (Or.inl rfl) #align multiset.mem_cons_self Multiset.mem_cons_self theorem forall_mem_cons {p : α → Prop} {a : α} {s : Multiset α} : (∀ x ∈ a ::ₘ s, p x) ↔ p a ∧ ∀ x ∈ s, p x := Quotient.inductionOn' s fun _ => List.forall_mem_cons #align multiset.forall_mem_cons Multiset.forall_mem_cons theorem exists_cons_of_mem {s : Multiset α} {a : α} : a ∈ s → ∃ t, s = a ::ₘ t := Quot.inductionOn s fun l (h : a ∈ l) => let ⟨l₁, l₂, e⟩ := mem_split h e.symm ▸ ⟨(l₁ ++ l₂ : List α), Quot.sound perm_middle⟩ #align multiset.exists_cons_of_mem Multiset.exists_cons_of_mem @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : Multiset α) := List.not_mem_nil _ #align multiset.not_mem_zero Multiset.not_mem_zero theorem eq_zero_of_forall_not_mem {s : Multiset α} : (∀ x, x ∉ s) → s = 0 := Quot.inductionOn s fun l H => by rw [eq_nil_iff_forall_not_mem.mpr H]; rfl #align multiset.eq_zero_of_forall_not_mem Multiset.eq_zero_of_forall_not_mem theorem eq_zero_iff_forall_not_mem {s : Multiset α} : s = 0 ↔ ∀ a, a ∉ s := ⟨fun h => h.symm ▸ fun _ => not_mem_zero _, eq_zero_of_forall_not_mem⟩ #align multiset.eq_zero_iff_forall_not_mem Multiset.eq_zero_iff_forall_not_mem theorem exists_mem_of_ne_zero {s : Multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := Quot.inductionOn s fun l hl => match l, hl with | [], h => False.elim <| h rfl | a :: l, _ => ⟨a, by simp⟩ #align multiset.exists_mem_of_ne_zero Multiset.exists_mem_of_ne_zero theorem empty_or_exists_mem (s : Multiset α) : s = 0 ∨ ∃ a, a ∈ s := or_iff_not_imp_left.mpr Multiset.exists_mem_of_ne_zero #align multiset.empty_or_exists_mem Multiset.empty_or_exists_mem @[simp] theorem zero_ne_cons {a : α} {m : Multiset α} : 0 ≠ a ::ₘ m := fun h => have : a ∈ (0 : Multiset α) := h.symm ▸ mem_cons_self _ _ not_mem_zero _ this #align multiset.zero_ne_cons Multiset.zero_ne_cons @[simp] theorem cons_ne_zero {a : α} {m : Multiset α} : a ::ₘ m ≠ 0 := zero_ne_cons.symm #align multiset.cons_ne_zero Multiset.cons_ne_zero theorem cons_eq_cons {a b : α} {as bs : Multiset α} : a ::ₘ as = b ::ₘ bs ↔ a = b ∧ as = bs ∨ a ≠ b ∧ ∃ cs, as = b ::ₘ cs ∧ bs = a ::ₘ cs := by haveI : DecidableEq α := Classical.decEq α constructor · intro eq by_cases h : a = b · subst h simp_all · have : a ∈ b ::ₘ bs := eq ▸ mem_cons_self _ _ have : a ∈ bs := by simpa [h] rcases exists_cons_of_mem this with ⟨cs, hcs⟩ simp [h, hcs] have : a ::ₘ as = b ::ₘ a ::ₘ cs := by simp [eq, hcs] have : a ::ₘ as = a ::ₘ b ::ₘ cs := by rwa [cons_swap] simpa using this · intro h rcases h with (⟨eq₁, eq₂⟩ | ⟨_, cs, eq₁, eq₂⟩) · simp [*] · simp [*, cons_swap a b] #align multiset.cons_eq_cons Multiset.cons_eq_cons end Mem /-! ### Singleton -/ instance : Singleton α (Multiset α) := ⟨fun a => a ::ₘ 0⟩ instance : IsLawfulSingleton α (Multiset α) := ⟨fun _ => rfl⟩ @[simp] theorem cons_zero (a : α) : a ::ₘ 0 = {a} := rfl #align multiset.cons_zero Multiset.cons_zero @[simp, norm_cast] theorem coe_singleton (a : α) : ([a] : Multiset α) = {a} := rfl #align multiset.coe_singleton Multiset.coe_singleton @[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : Multiset α) ↔ b = a := by simp only [← cons_zero, mem_cons, iff_self_iff, or_false_iff, not_mem_zero] #align multiset.mem_singleton Multiset.mem_singleton theorem mem_singleton_self (a : α) : a ∈ ({a} : Multiset α) := by rw [← cons_zero] exact mem_cons_self _ _ #align multiset.mem_singleton_self Multiset.mem_singleton_self @[simp] theorem singleton_inj {a b : α} : ({a} : Multiset α) = {b} ↔ a = b := by simp_rw [← cons_zero] exact cons_inj_left _ #align multiset.singleton_inj Multiset.singleton_inj @[simp, norm_cast] theorem coe_eq_singleton {l : List α} {a : α} : (l : Multiset α) = {a} ↔ l = [a] := by rw [← coe_singleton, coe_eq_coe, List.perm_singleton] #align multiset.coe_eq_singleton Multiset.coe_eq_singleton @[simp] theorem singleton_eq_cons_iff {a b : α} (m : Multiset α) : {a} = b ::ₘ m ↔ a = b ∧ m = 0 := by rw [← cons_zero, cons_eq_cons] simp [eq_comm] #align multiset.singleton_eq_cons_iff Multiset.singleton_eq_cons_iff theorem pair_comm (x y : α) : ({x, y} : Multiset α) = {y, x} := cons_swap x y 0 #align multiset.pair_comm Multiset.pair_comm /-! ### `Multiset.Subset` -/ section Subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def Subset (s t : Multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t #align multiset.subset Multiset.Subset instance : HasSubset (Multiset α) := ⟨Multiset.Subset⟩ instance : HasSSubset (Multiset α) := ⟨fun s t => s ⊆ t ∧ ¬t ⊆ s⟩ @[simp] theorem coe_subset {l₁ l₂ : List α} : (l₁ : Multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := Iff.rfl #align multiset.coe_subset Multiset.coe_subset @[simp] theorem Subset.refl (s : Multiset α) : s ⊆ s := fun _ h => h #align multiset.subset.refl Multiset.Subset.refl theorem Subset.trans {s t u : Multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := fun h₁ h₂ _ m => h₂ (h₁ m) #align multiset.subset.trans Multiset.Subset.trans theorem subset_iff {s t : Multiset α} : s ⊆ t ↔ ∀ ⦃x⦄, x ∈ s → x ∈ t := Iff.rfl #align multiset.subset_iff Multiset.subset_iff theorem mem_of_subset {s t : Multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ #align multiset.mem_of_subset Multiset.mem_of_subset @[simp] theorem zero_subset (s : Multiset α) : 0 ⊆ s := fun a => (not_mem_nil a).elim #align multiset.zero_subset Multiset.zero_subset theorem subset_cons (s : Multiset α) (a : α) : s ⊆ a ::ₘ s := fun _ => mem_cons_of_mem #align multiset.subset_cons Multiset.subset_cons theorem ssubset_cons {s : Multiset α} {a : α} (ha : a ∉ s) : s ⊂ a ::ₘ s := ⟨subset_cons _ _, fun h => ha <| h <| mem_cons_self _ _⟩ #align multiset.ssubset_cons Multiset.ssubset_cons @[simp] theorem cons_subset {a : α} {s t : Multiset α} : a ::ₘ s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp, forall_and] #align multiset.cons_subset Multiset.cons_subset theorem cons_subset_cons {a : α} {s t : Multiset α} : s ⊆ t → a ::ₘ s ⊆ a ::ₘ t := Quotient.inductionOn₂ s t fun _ _ => List.cons_subset_cons _ #align multiset.cons_subset_cons Multiset.cons_subset_cons theorem eq_zero_of_subset_zero {s : Multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem $ fun _ hx ↦ not_mem_zero _ (h hx) #align multiset.eq_zero_of_subset_zero Multiset.eq_zero_of_subset_zero theorem subset_zero {s : Multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, fun xeq => xeq.symm ▸ Subset.refl 0⟩ #align multiset.subset_zero Multiset.subset_zero theorem induction_on' {p : Multiset α → Prop} (S : Multiset α) (h₁ : p 0) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → p s → p (insert a s)) : p S := @Multiset.induction_on α (fun T => T ⊆ S → p T) S (fun _ => h₁) (fun _ _ hps hs => let ⟨hS, sS⟩ := cons_subset.1 hs h₂ hS sS (hps sS)) (Subset.refl S) #align multiset.induction_on' Multiset.induction_on' end Subset /-! ### `Multiset.toList` -/ section ToList /-- Produces a list of the elements in the multiset using choice. -/ noncomputable def toList (s : Multiset α) := s.out' #align multiset.to_list Multiset.toList @[simp, norm_cast] theorem coe_toList (s : Multiset α) : (s.toList : Multiset α) = s := s.out_eq' #align multiset.coe_to_list Multiset.coe_toList @[simp] theorem toList_eq_nil {s : Multiset α} : s.toList = [] ↔ s = 0 := by rw [← coe_eq_zero, coe_toList] #align multiset.to_list_eq_nil Multiset.toList_eq_nil @[simp] theorem empty_toList {s : Multiset α} : s.toList.isEmpty ↔ s = 0 := isEmpty_iff_eq_nil.trans toList_eq_nil #align multiset.empty_to_list Multiset.empty_toList @[simp] theorem toList_zero : (Multiset.toList 0 : List α) = [] := toList_eq_nil.mpr rfl #align multiset.to_list_zero Multiset.toList_zero @[simp] theorem mem_toList {a : α} {s : Multiset α} : a ∈ s.toList ↔ a ∈ s := by rw [← mem_coe, coe_toList] #align multiset.mem_to_list Multiset.mem_toList @[simp] theorem toList_eq_singleton_iff {a : α} {m : Multiset α} : m.toList = [a] ↔ m = {a} := by rw [← perm_singleton, ← coe_eq_coe, coe_toList, coe_singleton] #align multiset.to_list_eq_singleton_iff Multiset.toList_eq_singleton_iff @[simp] theorem toList_singleton (a : α) : ({a} : Multiset α).toList = [a] := Multiset.toList_eq_singleton_iff.2 rfl #align multiset.to_list_singleton Multiset.toList_singleton end ToList /-! ### Partial order on `Multiset`s -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def Le (s t : Multiset α) : Prop := (Quotient.liftOn₂ s t (· <+~ ·)) fun _ _ _ _ p₁ p₂ => propext (p₂.subperm_left.trans p₁.subperm_right) #align multiset.le Multiset.Le instance : PartialOrder (Multiset α) where le := Multiset.Le le_refl := by rintro ⟨l⟩; exact Subperm.refl _ le_trans := by rintro ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @Subperm.trans _ _ _ _ le_antisymm := by rintro ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact Quot.sound (Subperm.antisymm h₁ h₂) instance decidableLE [DecidableEq α] : DecidableRel ((· ≤ ·) : Multiset α → Multiset α → Prop) := fun s t => Quotient.recOnSubsingleton₂ s t List.decidableSubperm #align multiset.decidable_le Multiset.decidableLE section variable {s t : Multiset α} {a : α} theorem subset_of_le : s ≤ t → s ⊆ t := Quotient.inductionOn₂ s t fun _ _ => Subperm.subset #align multiset.subset_of_le Multiset.subset_of_le alias subset_of_le ← Le.subset #align multiset.le.subset Multiset.Le.subset theorem mem_of_le (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) #align multiset.mem_of_le Multiset.mem_of_le theorem not_mem_mono (h : s ⊆ t) : a ∉ t → a ∉ s := mt <| @h _ #align multiset.not_mem_mono Multiset.not_mem_mono @[simp] theorem coe_le {l₁ l₂ : List α} : (l₁ : Multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := Iff.rfl #align multiset.coe_le Multiset.coe_le @[elab_as_elim] theorem leInductionOn {C : Multiset α → Multiset α → Prop} {s t : Multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : List α}, l₁ <+ l₂ → C l₁ l₂) : C s t := Quotient.inductionOn₂ s t (fun l₁ _ ⟨l, p, s⟩ => (show ⟦l⟧ = ⟦l₁⟧ from Quot.sound p) ▸ H s) h #align multiset.le_induction_on Multiset.leInductionOn theorem zero_le (s : Multiset α) : 0 ≤ s := Quot.inductionOn s fun l => (nil_sublist l).subperm #align multiset.zero_le Multiset.zero_le instance : OrderBot (Multiset α) where bot := 0 bot_le := zero_le /-- This is a `rfl` and `simp` version of `bot_eq_zero`. -/ @[simp] theorem bot_eq_zero : (⊥ : Multiset α) = 0 := rfl #align multiset.bot_eq_zero Multiset.bot_eq_zero theorem le_zero : s ≤ 0 ↔ s = 0 := le_bot_iff #align multiset.le_zero Multiset.le_zero theorem lt_cons_self (s : Multiset α) (a : α) : s < a ::ₘ s := Quot.inductionOn s fun l => suffices l <+~ a :: l ∧ ¬l ~ a :: l by simpa [lt_iff_le_and_ne] ⟨(sublist_cons _ _).subperm, fun p => _root_.ne_of_lt (lt_succ_self (length l)) p.length_eq⟩ #align multiset.lt_cons_self Multiset.lt_cons_self theorem le_cons_self (s : Multiset α) (a : α) : s ≤ a ::ₘ s := le_of_lt <| lt_cons_self _ _ #align multiset.le_cons_self Multiset.le_cons_self theorem cons_le_cons_iff (a : α) : a ::ₘ s ≤ a ::ₘ t ↔ s ≤ t := Quotient.inductionOn₂ s t fun _ _ => subperm_cons a #align multiset.cons_le_cons_iff Multiset.cons_le_cons_iff theorem cons_le_cons (a : α) : s ≤ t → a ::ₘ s ≤ a ::ₘ t := (cons_le_cons_iff a).2 #align multiset.cons_le_cons Multiset.cons_le_cons theorem le_cons_of_not_mem (m : a ∉ s) : s ≤ a ::ₘ t ↔ s ≤ t := by refine' ⟨_, fun h => le_trans h <| le_cons_self _ _⟩ suffices ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a ::ₘ s ≤ t' by exact fun h => (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) introv h revert m refine' leInductionOn h _ introv s m₁ m₂ rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩ exact perm_middle.subperm_left.2 ((subperm_cons _).2 <| ((sublist_or_mem_of_sublist s).resolve_right m₁).subperm) #align multiset.le_cons_of_not_mem Multiset.le_cons_of_not_mem @[simp] theorem singleton_ne_zero (a : α) : ({a} : Multiset α) ≠ 0 := ne_of_gt (lt_cons_self _ _) #align multiset.singleton_ne_zero Multiset.singleton_ne_zero @[simp] theorem singleton_le {a : α} {s : Multiset α} : {a} ≤ s ↔ a ∈ s := ⟨fun h => mem_of_le h (mem_singleton_self _), fun h => let ⟨_t, e⟩ := exists_cons_of_mem h e.symm ▸ cons_le_cons _ (zero_le _)⟩ #align multiset.singleton_le Multiset.singleton_le end /-! ### Additive monoid -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : Multiset α) : Multiset α := (Quotient.liftOn₂ s₁ s₂ fun l₁ l₂ => ((l₁ ++ l₂ : List α) : Multiset α)) fun _ _ _ _ p₁ p₂ => Quot.sound <| p₁.append p₂ #align multiset.add Multiset.add instance : Add (Multiset α) := ⟨Multiset.add⟩ @[simp] theorem coe_add (s t : List α) : (s + t : Multiset α) = (s ++ t : List α) := rfl #align multiset.coe_add Multiset.coe_add @[simp] theorem singleton_add (a : α) (s : Multiset α) : {a} + s = a ::ₘ s := rfl #align multiset.singleton_add Multiset.singleton_add private theorem add_le_add_iff_left' {s t u : Multiset α} : s + t ≤ s + u ↔ t ≤ u := Quotient.inductionOn₃ s t u fun _ _ _ => subperm_append_left _ instance : CovariantClass (Multiset α) (Multiset α) (· + ·) (· ≤ ·) := ⟨fun _s _t _u => add_le_add_iff_left'.2⟩ instance : ContravariantClass (Multiset α) (Multiset α) (· + ·) (· ≤ ·) := ⟨fun _s _t _u => add_le_add_iff_left'.1⟩ instance : OrderedCancelAddCommMonoid (Multiset α) where zero := 0 add := (· + ·) add_comm := fun s t => Quotient.inductionOn₂ s t fun l₁ l₂ => Quot.sound perm_append_comm add_assoc := fun s₁ s₂ s₃ => Quotient.inductionOn₃ s₁ s₂ s₃ fun l₁ l₂ l₃ => congr_arg _ <| append_assoc l₁ l₂ l₃ zero_add := fun s => Quot.inductionOn s fun l => rfl add_zero := fun s => Quotient.inductionOn s fun l => congr_arg _ <| append_nil l add_le_add_left := fun s₁ s₂ => add_le_add_left le_of_add_le_add_left := fun s₁ s₂ s₃ => le_of_add_le_add_left theorem le_add_right (s t : Multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s #align multiset.le_add_right Multiset.le_add_right theorem le_add_left (s t : Multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s #align multiset.le_add_left Multiset.le_add_left theorem le_iff_exists_add {s t : Multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨fun h => leInductionOn h fun s => let ⟨l, p⟩ := s.exists_perm_append ⟨l, Quot.sound p⟩, fun ⟨_u, e⟩ => e.symm ▸ le_add_right _ _⟩ #align multiset.le_iff_exists_add Multiset.le_iff_exists_add instance : CanonicallyOrderedAddMonoid (Multiset α) where __ := inferInstanceAs (OrderBot (Multiset α)) le_self_add := le_add_right exists_add_of_le h := leInductionOn h fun s => let ⟨l, p⟩ := s.exists_perm_append ⟨l, Quot.sound p⟩ @[simp] theorem cons_add (a : α) (s t : Multiset α) : a ::ₘ s + t = a ::ₘ (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] #align multiset.cons_add Multiset.cons_add @[simp] theorem add_cons (a : α) (s t : Multiset α) : s + a ::ₘ t = a ::ₘ (s + t) := by rw [add_comm, cons_add, add_comm] #align multiset.add_cons Multiset.add_cons @[simp] theorem mem_add {a : α} {s t : Multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := Quotient.inductionOn₂ s t fun _l₁ _l₂ => mem_append #align multiset.mem_add Multiset.mem_add theorem mem_of_mem_nsmul {a : α} {s : Multiset α} {n : ℕ} (h : a ∈ n • s) : a ∈ s := by induction' n with n ih · rw [zero_nsmul] at h exact absurd h (not_mem_zero _) · rw [succ_nsmul, mem_add] at h exact h.elim id ih #align multiset.mem_of_mem_nsmul Multiset.mem_of_mem_nsmul @[simp] theorem mem_nsmul {a : α} {s : Multiset α} {n : ℕ} (h0 : n ≠ 0) : a ∈ n • s ↔ a ∈ s := by refine' ⟨mem_of_mem_nsmul, fun h => _⟩ obtain ⟨n, rfl⟩ := exists_eq_succ_of_ne_zero h0 rw [succ_nsmul, mem_add] exact Or.inl h #align multiset.mem_nsmul Multiset.mem_nsmul theorem nsmul_cons {s : Multiset α} (n : ℕ) (a : α) : n • (a ::ₘ s) = n • ({a} : Multiset α) + n • s := by rw [← singleton_add, nsmul_add] #align multiset.nsmul_cons Multiset.nsmul_cons /-! ### Cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card : Multiset α →+ ℕ where toFun s := (Quot.liftOn s length) fun _l₁ _l₂ => Perm.length_eq map_zero' := rfl map_add' s t := Quotient.inductionOn₂ s t length_append #align multiset.card Multiset.card @[simp] theorem coe_card (l : List α) : card (l : Multiset α) = length l := rfl #align multiset.coe_card Multiset.coe_card @[simp] theorem length_toList (s : Multiset α) : s.toList.length = card s := by rw [← coe_card, coe_toList] #align multiset.length_to_list Multiset.length_toList @[simp, nolint simpNF] -- Porting note: `dsimp` can not prove this, yet linter complains theorem card_zero : @card α 0 = 0 := rfl #align multiset.card_zero Multiset.card_zero theorem card_add (s t : Multiset α) : card (s + t) = card s + card t := card.map_add s t #align multiset.card_add Multiset.card_add theorem card_nsmul (s : Multiset α) (n : ℕ) : card (n • s) = n * card s := by rw [card.map_nsmul s n, Nat.nsmul_eq_mul] #align multiset.card_nsmul Multiset.card_nsmul @[simp] theorem card_cons (a : α) (s : Multiset α) : card (a ::ₘ s) = card s + 1 := Quot.inductionOn s fun _l => rfl #align multiset.card_cons Multiset.card_cons @[simp] theorem card_singleton (a : α) : card ({a} : Multiset α) = 1 := by simp only [← cons_zero, card_zero, eq_self_iff_true, zero_add, card_cons] #align multiset.card_singleton Multiset.card_singleton theorem card_pair (a b : α) : card {a, b} = 2 := by rw [insert_eq_cons, card_cons, card_singleton] #align multiset.card_pair Multiset.card_pair theorem card_eq_one {s : Multiset α} : card s = 1 ↔ ∃ a, s = {a} := ⟨Quot.inductionOn s fun _l h => (List.length_eq_one.1 h).imp fun _a => congr_arg _, fun ⟨_a, e⟩ => e.symm ▸ rfl⟩ #align multiset.card_eq_one Multiset.card_eq_one theorem card_le_of_le {s t : Multiset α} (h : s ≤ t) : card s ≤ card t := leInductionOn h Sublist.length_le #align multiset.card_le_of_le Multiset.card_le_of_le @[mono] theorem card_mono : Monotone (@card α) := fun _a _b => card_le_of_le #align multiset.card_mono Multiset.card_mono theorem eq_of_le_of_card_le {s t : Multiset α} (h : s ≤ t) : card t ≤ card s → s = t := leInductionOn h fun s h₂ => congr_arg _ <| s.eq_of_length_le h₂ #align multiset.eq_of_le_of_card_le Multiset.eq_of_le_of_card_le theorem card_lt_of_lt {s t : Multiset α} (h : s < t) : card s < card t := lt_of_not_ge fun h₂ => _root_.ne_of_lt h <| eq_of_le_of_card_le (le_of_lt h) h₂ #align multiset.card_lt_of_lt Multiset.card_lt_of_lt theorem lt_iff_cons_le {s t : Multiset α} : s < t ↔ ∃ a, a ::ₘ s ≤ t := ⟨Quotient.inductionOn₂ s t fun _l₁ _l₂ h => Subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), fun ⟨_a, h⟩ => lt_of_lt_of_le (lt_cons_self _ _) h⟩ #align multiset.lt_iff_cons_le Multiset.lt_iff_cons_le @[simp] theorem card_eq_zero {s : Multiset α} : card s = 0 ↔ s = 0 := ⟨fun h => (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, fun e => by simp [e]⟩ #align multiset.card_eq_zero Multiset.card_eq_zero theorem card_pos {s : Multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans <| not_congr card_eq_zero #align multiset.card_pos Multiset.card_pos theorem card_pos_iff_exists_mem {s : Multiset α} : 0 < card s ↔ ∃ a, a ∈ s := Quot.inductionOn s fun _l => length_pos_iff_exists_mem #align multiset.card_pos_iff_exists_mem Multiset.card_pos_iff_exists_mem theorem card_eq_two {s : Multiset α} : card s = 2 ↔ ∃ x y, s = {x, y} := ⟨Quot.inductionOn s fun _l h => (List.length_eq_two.mp h).imp fun _a => Exists.imp fun _b => congr_arg _, fun ⟨_a, _b, e⟩ => e.symm ▸ rfl⟩ #align multiset.card_eq_two Multiset.card_eq_two theorem card_eq_three {s : Multiset α} : card s = 3 ↔ ∃ x y z, s = {x, y, z} := ⟨Quot.inductionOn s fun _l h => (List.length_eq_three.mp h).imp fun _a => Exists.imp fun _b => Exists.imp fun _c => congr_arg _, fun ⟨_a, _b, _c, e⟩ => e.symm ▸ rfl⟩ #align multiset.card_eq_three Multiset.card_eq_three /-! ### Induction principles -/ /-- The strong induction principle for multisets. -/ @[elab_as_elim] def strongInductionOn {p : Multiset α → Sort _} (s : Multiset α) (ih : ∀ s, (∀ t < s, p t) → p s) : p s := (ih s) fun t _h => strongInductionOn t ih termination_by _ => card s decreasing_by exact card_lt_of_lt _h #align multiset.strong_induction_on Multiset.strongInductionOnₓ -- Porting note: reorderd universes theorem strongInductionOn_eq {p : Multiset α → Sort _} (s : Multiset α) (H) : @strongInductionOn _ p s H = H s fun t _h => @strongInductionOn _ p t H := by rw [strongInductionOn] #align multiset.strong_induction_eq Multiset.strongInductionOn_eq @[elab_as_elim] theorem case_strongInductionOn {p : Multiset α → Prop} (s : Multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀ t ≤ s, p t) → p (a ::ₘ s)) : p s := Multiset.strongInductionOn s fun s => Multiset.induction_on s (fun _ => h₀) fun _a _s _ ih => (h₁ _ _) fun _t h => ih _ <| lt_of_le_of_lt h <| lt_cons_self _ _ #align multiset.case_strong_induction_on Multiset.case_strongInductionOn /-- Suppose that, given that `p t` can be defined on all supersets of `s` of cardinality less than `n`, one knows how to define `p s`. Then one can inductively define `p s` for all multisets `s` of cardinality less than `n`, starting from multisets of card `n` and iterating. This can be used either to define data, or to prove properties. -/ def strongDownwardInduction {p : Multiset α → Sort _} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : Multiset α}, card t₂ ≤ n → t₁ < t₂ → p t₂) → card t₁ ≤ n → p t₁) (s : Multiset α) : card s ≤ n → p s := H s fun {t} ht _h => strongDownwardInduction H t ht termination_by _ => n - card s decreasing_by exact (tsub_lt_tsub_iff_left_of_le ht).2 (card_lt_of_lt _h) -- Porting note: reorderd universes #align multiset.strong_downward_induction Multiset.strongDownwardInductionₓ theorem strongDownwardInduction_eq {p : Multiset α → Sort _} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : Multiset α}, card t₂ ≤ n → t₁ < t₂ → p t₂) → card t₁ ≤ n → p t₁) (s : Multiset α) : strongDownwardInduction H s = H s fun ht _hst => strongDownwardInduction H _ ht := by rw [strongDownwardInduction] #align multiset.strong_downward_induction_eq Multiset.strongDownwardInduction_eq /-- Analogue of `strongDownwardInduction` with order of arguments swapped. -/ @[elab_as_elim] def strongDownwardInductionOn {p : Multiset α → Sort _} {n : ℕ} : ∀ s : Multiset α, (∀ t₁, (∀ {t₂ : Multiset α}, card t₂ ≤ n → t₁ < t₂ → p t₂) → card t₁ ≤ n → p t₁) → card s ≤ n → p s := fun s H => strongDownwardInduction H s #align multiset.strong_downward_induction_on Multiset.strongDownwardInductionOn theorem strongDownwardInductionOn_eq {p : Multiset α → Sort _} (s : Multiset α) {n : ℕ} (H : ∀ t₁, (∀ {t₂ : Multiset α}, card t₂ ≤ n → t₁ < t₂ → p t₂) → card t₁ ≤ n → p t₁) : s.strongDownwardInductionOn H = H s fun {t} ht _h => t.strongDownwardInductionOn H ht := by dsimp only [strongDownwardInductionOn] rw [strongDownwardInduction] #align multiset.strong_downward_induction_on_eq Multiset.strongDownwardInductionOn_eq /-- Another way of expressing `strongInductionOn`: the `(<)` relation is well-founded. -/ theorem wellFounded_lt : WellFounded ((· < ·) : Multiset α → Multiset α → Prop) := Subrelation.wf Multiset.card_lt_of_lt (measure Multiset.card).2 #align multiset.well_founded_lt Multiset.wellFounded_lt instance is_wellFounded_lt : WellFoundedLT (Multiset α) := ⟨wellFounded_lt⟩ #align multiset.is_well_founded_lt Multiset.is_wellFounded_lt /-! ### `Multiset.replicate` -/ /-- `replicate n a` is the multiset containing only `a` with multiplicity `n`. -/ def replicate (n : ℕ) (a : α) : Multiset α := List.replicate n a #align multiset.replicate Multiset.replicate theorem coe_replicate (n : ℕ) (a : α) : (List.replicate n a : Multiset α) = replicate n a := rfl #align multiset.coe_replicate Multiset.coe_replicate @[simp] theorem replicate_zero (a : α) : replicate 0 a = 0 := rfl #align multiset.replicate_zero Multiset.replicate_zero @[simp] theorem replicate_succ (a : α) (n) : replicate (n + 1) a = a ::ₘ replicate n a := rfl #align multiset.replicate_succ Multiset.replicate_succ theorem replicate_add (m n : ℕ) (a : α) : replicate (m + n) a = replicate m a + replicate n a := congr_arg _ <| List.replicate_add .. #align multiset.replicate_add Multiset.replicate_add /-- `Multiset.replicate` as an `AddMonoidHom`. -/ @[simps] def replicateAddMonoidHom (a : α) : ℕ →+ Multiset α where toFun := fun n => replicate n a map_zero' := replicate_zero a map_add' := fun _ _ => replicate_add _ _ a #align multiset.replicate_add_monoid_hom Multiset.replicateAddMonoidHom #align multiset.replicate_add_monoid_hom_apply Multiset.replicateAddMonoidHom_apply theorem replicate_one (a : α) : replicate 1 a = {a} := rfl #align multiset.replicate_one Multiset.replicate_one @[simp] theorem card_replicate (n) (a : α) : card (replicate n a) = n := length_replicate n a #align multiset.card_replicate Multiset.card_replicate theorem mem_replicate {a b : α} {n : ℕ} : b ∈ replicate n a ↔ n ≠ 0 ∧ b = a := List.mem_replicate #align multiset.mem_replicate Multiset.mem_replicate theorem eq_of_mem_replicate {a b : α} {n} : b ∈ replicate n a → b = a := List.eq_of_mem_replicate #align multiset.eq_of_mem_replicate Multiset.eq_of_mem_replicate theorem eq_replicate_card {a : α} {s : Multiset α} : s = replicate (card s) a ↔ ∀ b ∈ s, b = a := Quot.inductionOn s fun _l => coe_eq_coe.trans <| perm_replicate.trans eq_replicate_length #align multiset.eq_replicate_card Multiset.eq_replicate_card alias eq_replicate_card ↔ _ eq_replicate_of_mem #align multiset.eq_replicate_of_mem Multiset.eq_replicate_of_mem theorem eq_replicate {a : α} {n} {s : Multiset α} : s = replicate n a ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨fun h => h.symm ▸ ⟨card_replicate _ _, fun _b => eq_of_mem_replicate⟩, fun ⟨e, al⟩ => e ▸ eq_replicate_of_mem al⟩ #align multiset.eq_replicate Multiset.eq_replicate theorem replicate_right_injective {n : ℕ} (hn : n ≠ 0) : Injective (@replicate α n) := fun _ _ h => (eq_replicate.1 h).2 _ <| mem_replicate.2 ⟨hn, rfl⟩ #align multiset.replicate_right_injective Multiset.replicate_right_injective @[simp] theorem replicate_right_inj {a b : α} {n : ℕ} (h : n ≠ 0) : replicate n a = replicate n b ↔ a = b := (replicate_right_injective h).eq_iff #align multiset.replicate_right_inj Multiset.replicate_right_inj theorem replicate_left_injective (a : α) : Injective (replicate · a) := -- Porting note: was `fun m n h => by rw [← (eq_replicate.1 h).1, card_replicate]` LeftInverse.injective (card_replicate · a) #align multiset.replicate_left_injective Multiset.replicate_left_injective theorem replicate_subset_singleton (n : ℕ) (a : α) : replicate n a ⊆ {a} := List.replicate_subset_singleton n a #align multiset.replicate_subset_singleton Multiset.replicate_subset_singleton theorem replicate_le_coe {a : α} {n} {l : List α} : replicate n a ≤ l ↔ List.replicate n a <+ l := ⟨fun ⟨_l', p, s⟩ => perm_replicate.1 p ▸ s, Sublist.subperm⟩ #align multiset.replicate_le_coe Multiset.replicate_le_coe theorem nsmul_replicate {a : α} (n m : ℕ) : n • replicate m a = replicate (n * m) a := ((replicateAddMonoidHom a).map_nsmul _ _).symm #align multiset.nsmul_replicate Multiset.nsmul_replicate theorem nsmul_singleton (a : α) (n) : n • ({a} : Multiset α) = replicate n a := by rw [← replicate_one, nsmul_replicate, mul_one] #align multiset.nsmul_singleton Multiset.nsmul_singleton theorem replicate_le_replicate (a : α) {k n : ℕ} : replicate k a ≤ replicate n a ↔ k ≤ n := _root_.trans (by rw [← replicate_le_coe, coe_replicate]) (List.replicate_sublist_replicate a) #align multiset.replicate_le_replicate Multiset.replicate_le_replicate theorem le_replicate_iff {m : Multiset α} {a : α} {n : ℕ} : m ≤ replicate n a ↔ ∃ k ≤ n, m = replicate k a := ⟨fun h => ⟨card m, (card_mono h).trans_eq (card_replicate _ _), eq_replicate_card.2 <| fun _ hb => eq_of_mem_replicate <| subset_of_le h hb⟩, fun ⟨_, hkn, hm⟩ => hm.symm ▸ (replicate_le_replicate _).2 hkn⟩ #align multiset.le_replicate_iff Multiset.le_replicate_iff theorem lt_replicate_succ {m : Multiset α} {x : α} {n : ℕ} : m < replicate (n + 1) x ↔ m ≤ replicate n x := by rw [lt_iff_cons_le] constructor · rintro ⟨x', hx'⟩ have := eq_of_mem_replicate (mem_of_le hx' (mem_cons_self _ _)) rwa [this, replicate_succ, cons_le_cons_iff] at hx' · intro h rw [replicate_succ] exact ⟨x, cons_le_cons _ h⟩ #align multiset.lt_replicate_succ Multiset.lt_replicate_succ /-! ### Erasing one copy of an element -/ section Erase variable [DecidableEq α] {s t : Multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : Multiset α) (a : α) : Multiset α := Quot.liftOn s (fun l => (l.erase a : Multiset α)) fun _l₁ _l₂ p => Quot.sound (p.erase a) #align multiset.erase Multiset.erase @[simp] theorem coe_erase (l : List α) (a : α) : erase (l : Multiset α) a = l.erase a := rfl #align multiset.coe_erase Multiset.coe_erase @[simp, nolint simpNF] -- Porting note: `dsimp` can not prove this, yet linter complains theorem erase_zero (a : α) : (0 : Multiset α).erase a = 0 := rfl #align multiset.erase_zero Multiset.erase_zero @[simp] theorem erase_cons_head (a : α) (s : Multiset α) : (a ::ₘ s).erase a = s := Quot.inductionOn s fun l => congr_arg _ <| List.erase_cons_head a l #align multiset.erase_cons_head Multiset.erase_cons_head @[simp] theorem erase_cons_tail {a b : α} (s : Multiset α) (h : b ≠ a) : (b ::ₘ s).erase a = b ::ₘ s.erase a := Quot.inductionOn s fun l => congr_arg _ <| List.erase_cons_tail l h #align multiset.erase_cons_tail Multiset.erase_cons_tail @[simp] theorem erase_singleton (a : α) : ({a} : Multiset α).erase a = 0 := erase_cons_head a 0 #align multiset.erase_singleton Multiset.erase_singleton @[simp] theorem erase_of_not_mem {a : α} {s : Multiset α} : a ∉ s → s.erase a = s := Quot.inductionOn s fun _l h => congr_arg _ <| List.erase_of_not_mem h #align multiset.erase_of_not_mem Multiset.erase_of_not_mem @[simp] theorem cons_erase {s : Multiset α} {a : α} : a ∈ s → a ::ₘ s.erase a = s := Quot.inductionOn s fun _l h => Quot.sound (perm_cons_erase h).symm #align multiset.cons_erase Multiset.cons_erase theorem le_cons_erase (s : Multiset α) (a : α) : s ≤ a ::ₘ s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw [erase_of_not_mem h]; apply le_cons_self #align multiset.le_cons_erase Multiset.le_cons_erase theorem add_singleton_eq_iff {s t : Multiset α} {a : α} : s + {a} = t ↔ a ∈ t ∧ s = t.erase a := by rw [add_comm, singleton_add]; constructor · rintro rfl exact ⟨s.mem_cons_self a, (s.erase_cons_head a).symm⟩ · rintro ⟨h, rfl⟩ exact cons_erase h #align multiset.add_singleton_eq_iff Multiset.add_singleton_eq_iff theorem erase_add_left_pos {a : α} {s : Multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := Quotient.inductionOn₂ s t fun _l₁ l₂ h => congr_arg _ <| erase_append_left l₂ h #align multiset.erase_add_left_pos Multiset.erase_add_left_pos theorem erase_add_right_pos {a : α} (s) {t : Multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] #align multiset.erase_add_right_pos Multiset.erase_add_right_pos theorem erase_add_right_neg {a : α} {s : Multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := Quotient.inductionOn₂ s t fun _l₁ l₂ h => congr_arg _ <| erase_append_right l₂ h #align multiset.erase_add_right_neg Multiset.erase_add_right_neg theorem erase_add_left_neg {a : α} (s) {t : Multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] #align multiset.erase_add_left_neg Multiset.erase_add_left_neg theorem erase_le (a : α) (s : Multiset α) : s.erase a ≤ s := Quot.inductionOn s fun l => (erase_sublist a l).subperm #align multiset.erase_le Multiset.erase_le @[simp] theorem erase_lt {a : α} {s : Multiset α} : s.erase a < s ↔ a ∈ s := ⟨fun h => not_imp_comm.1 erase_of_not_mem (ne_of_lt h), fun h => by simpa [h] using lt_cons_self (s.erase a) a⟩ #align multiset.erase_lt Multiset.erase_lt theorem erase_subset (a : α) (s : Multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) #align multiset.erase_subset Multiset.erase_subset theorem mem_erase_of_ne {a b : α} {s : Multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := Quot.inductionOn s fun _l => List.mem_erase_of_ne ab #align multiset.mem_erase_of_ne Multiset.mem_erase_of_ne theorem mem_of_mem_erase {a b : α} {s : Multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) #align multiset.mem_of_mem_erase Multiset.mem_of_mem_erase theorem erase_comm (s : Multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := Quot.inductionOn s fun l => congr_arg _ <| l.erase_comm a b #align multiset.erase_comm Multiset.erase_comm theorem erase_le_erase {s t : Multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := leInductionOn h fun h => (h.erase _).subperm #align multiset.erase_le_erase Multiset.erase_le_erase @[simp] theorem card_erase_of_mem {a : α} {s : Multiset α} : a ∈ s → card (s.erase a) = pred (card s) := Quot.inductionOn s fun _l => length_erase_of_mem #align multiset.card_erase_of_mem Multiset.card_erase_of_mem @[simp] theorem card_erase_add_one {a : α} {s : Multiset α} : a ∈ s → card (s.erase a) + 1 = card s := Quot.inductionOn s fun _l => length_erase_add_one #align multiset.card_erase_add_one Multiset.card_erase_add_one theorem card_erase_lt_of_mem {a : α} {s : Multiset α} : a ∈ s → card (s.erase a) < card s := fun h => card_lt_of_lt (erase_lt.mpr h) #align multiset.card_erase_lt_of_mem Multiset.card_erase_lt_of_mem theorem card_erase_le {a : α} {s : Multiset α} : card (s.erase a) ≤ card s := card_le_of_le (erase_le a s) #align multiset.card_erase_le Multiset.card_erase_le theorem card_erase_eq_ite {a : α} {s : Multiset α} : card (s.erase a) = if a ∈ s then pred (card s) else card s := by by_cases h : a ∈ s · rwa [card_erase_of_mem h, if_pos] · rwa [erase_of_not_mem h, if_neg] #align multiset.card_erase_eq_ite Multiset.card_erase_eq_ite end Erase @[simp] theorem coe_reverse (l : List α) : (reverse l : Multiset α) = l := Quot.sound <| reverse_perm _ #align multiset.coe_reverse Multiset.coe_reverse /-! ### `Multiset.map` -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : Multiset α) : Multiset β := Quot.liftOn s (fun l : List α => (l.map f : Multiset β)) fun _l₁ _l₂ p => Quot.sound (p.map f) #align multiset.map Multiset.map @[congr] theorem map_congr {f g : α → β} {s t : Multiset α} : s = t → (∀ x ∈ t, f x = g x) → map f s = map g t := by rintro rfl h induction s using Quot.inductionOn exact congr_arg _ (List.map_congr h) #align multiset.map_congr Multiset.map_congr theorem map_hcongr {β' : Type _} {m : Multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀ a ∈ m, HEq (f a) (f' a)) : HEq (map f m) (map f' m) := by subst h; simp at hf simp [map_congr rfl hf] #align multiset.map_hcongr Multiset.map_hcongr theorem forall_mem_map_iff {f : α → β} {p : β → Prop} {s : Multiset α} : (∀ y ∈ s.map f, p y) ↔ ∀ x ∈ s, p (f x) := Quotient.inductionOn' s fun _L => List.forall_mem_map_iff #align multiset.forall_mem_map_iff Multiset.forall_mem_map_iff @[simp] theorem coe_map (f : α → β) (l : List α) : map f ↑l = l.map f := rfl #align multiset.coe_map Multiset.coe_map @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl #align multiset.map_zero Multiset.map_zero @[simp] theorem map_cons (f : α → β) (a s) : map f (a ::ₘ s) = f a ::ₘ map f s := Quot.inductionOn s fun _l => rfl #align multiset.map_cons Multiset.map_cons theorem map_comp_cons (f : α → β) (t) : map f ∘ cons t = cons (f t) ∘ map f := by ext simp #align multiset.map_comp_cons Multiset.map_comp_cons @[simp] theorem map_singleton (f : α → β) (a : α) : ({a} : Multiset α).map f = {f a} := rfl #align multiset.map_singleton Multiset.map_singleton @[simp] theorem map_replicate (f : α → β) (k : ℕ) (a : α) : (replicate k a).map f = replicate k (f a) := by simp only [← coe_replicate, coe_map, List.map_replicate] #align multiset.map_replicate Multiset.map_replicate @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := Quotient.inductionOn₂ s t fun _l₁ _l₂ => congr_arg _ <| map_append _ _ _ #align multiset.map_add Multiset.map_add /-- If each element of `s : Multiset α` can be lifted to `β`, then `s` can be lifted to `Multiset β`. -/ instance canLift (c) (p) [CanLift α β c p] : CanLift (Multiset α) (Multiset β) (map c) fun s => ∀ x ∈ s, p x where prf := by rintro ⟨l⟩ hl lift l to List β using hl exact ⟨l, coe_map _ _⟩ #align multiset.can_lift Multiset.canLift /-- `Multiset.map` as an `AddMonoidHom`. -/ def mapAddMonoidHom (f : α → β) : Multiset α →+ Multiset β where toFun := map f map_zero' := map_zero _ map_add' := map_add _ #align multiset.map_add_monoid_hom Multiset.mapAddMonoidHom @[simp] theorem coe_mapAddMonoidHom (f : α → β) : (mapAddMonoidHom f : Multiset α → Multiset β) = map f := rfl #align multiset.coe_map_add_monoid_hom Multiset.coe_mapAddMonoidHom theorem map_nsmul (f : α → β) (n : ℕ) (s) : map f (n • s) = n • map f s := (mapAddMonoidHom f).map_nsmul _ _ #align multiset.map_nsmul Multiset.map_nsmul @[simp] theorem mem_map {f : α → β} {b : β} {s : Multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := Quot.inductionOn s fun _l => List.mem_map #align multiset.mem_map Multiset.mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := Quot.inductionOn s fun _l => length_map _ _ #align multiset.card_map Multiset.card_map @[simp] theorem map_eq_zero {s : Multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 := by rw [← Multiset.card_eq_zero, Multiset.card_map, Multiset.card_eq_zero] #align multiset.map_eq_zero Multiset.map_eq_zero theorem mem_map_of_mem (f : α → β) {a : α} {s : Multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ #align multiset.mem_map_of_mem Multiset.mem_map_of_mem theorem map_eq_singleton {f : α → β} {s : Multiset α} {b : β} : map f s = {b} ↔ ∃ a : α, s = {a} ∧ f a = b := by constructor · intro h obtain ⟨a, ha⟩ : ∃ a, s = {a} := by rw [← card_eq_one, ← card_map, h, card_singleton] refine' ⟨a, ha, _⟩ rw [← mem_singleton, ← h, ha, map_singleton, mem_singleton] · rintro ⟨a, rfl, rfl⟩ simp #align multiset.map_eq_singleton Multiset.map_eq_singleton theorem map_eq_cons [DecidableEq α] (f : α → β) (s : Multiset α) (t : Multiset β) (b : β) : (∃ a ∈ s, f a = b ∧ (s.erase a).map f = t) ↔ s.map f = b ::ₘ t := by constructor · rintro ⟨a, ha, rfl, rfl⟩ rw [← map_cons, Multiset.cons_erase ha] · intro h have : b ∈ s.map f := by rw [h] exact mem_cons_self _ _ obtain ⟨a, h1, rfl⟩ := mem_map.mp this obtain ⟨u, rfl⟩ := exists_cons_of_mem h1 rw [map_cons, cons_inj_right] at h refine' ⟨a, mem_cons_self _ _, rfl, _⟩ rw [Multiset.erase_cons_head, h] #align multiset.map_eq_cons Multiset.map_eq_cons theorem mem_map_of_injective {f : α → β} (H : Function.Injective f) {a : α} {s : Multiset α} : f a ∈ map f s ↔ a ∈ s := Quot.inductionOn s fun _l => List.mem_map_of_injective H #align multiset.mem_map_of_injective Multiset.mem_map_of_injective @[simp] theorem map_map (g : β → γ) (f : α → β) (s : Multiset α) : map g (map f s) = map (g ∘ f) s := Quot.inductionOn s fun _l => congr_arg _ <| List.map_map _ _ _ #align multiset.map_map Multiset.map_map theorem map_id (s : Multiset α) : map id s = s := Quot.inductionOn s fun _l => congr_arg _ <| List.map_id _ #align multiset.map_id Multiset.map_id @[simp] theorem map_id' (s : Multiset α) : map (fun x => x) s = s := map_id s #align multiset.map_id' Multiset.map_id' -- Porting note: was a `simp` lemma in mathlib3 theorem map_const (s : Multiset α) (b : β) : map (const α b) s = replicate (card s) b := Quot.inductionOn s fun _ => congr_arg _ <| List.map_const' _ _ #align multiset.map_const Multiset.map_const -- Porting note: was not a `simp` lemma in mathlib3 because `function.const` was reducible @[simp] theorem map_const' (s : Multiset α) (b : β) : map (fun _ ↦ b) s = replicate (card s) b := map_const _ _ #align multiset.map_const' Multiset.map_const' theorem eq_of_mem_map_const {b₁ b₂ : β} {l : List α} (h : b₁ ∈ map (Function.const α b₂) l) : b₁ = b₂ := eq_of_mem_replicate <| by rwa [map_const] at h #align multiset.eq_of_mem_map_const Multiset.eq_of_mem_map_const @[simp] theorem map_le_map {f : α → β} {s t : Multiset α} (h : s ≤ t) : map f s ≤ map f t := leInductionOn h fun h => (h.map f).subperm #align multiset.map_le_map Multiset.map_le_map @[simp] theorem map_lt_map {f : α → β} {s t : Multiset α} (h : s < t) : s.map f < t.map f := by refine' (map_le_map h.le).lt_of_not_le fun H => h.ne <| eq_of_le_of_card_le h.le _ rw [← s.card_map f, ← t.card_map f] exact card_le_of_le H #align multiset.map_lt_map Multiset.map_lt_map theorem map_mono (f : α → β) : Monotone (map f) := fun _ _ => map_le_map #align multiset.map_mono Multiset.map_mono theorem map_strictMono (f : α → β) : StrictMono (map f) := fun _ _ => map_lt_map #align multiset.map_strict_mono Multiset.map_strictMono @[simp] theorem map_subset_map {f : α → β} {s t : Multiset α} (H : s ⊆ t) : map f s ⊆ map f t := fun _b m => let ⟨a, h, e⟩ := mem_map.1 m mem_map.2 ⟨a, H h, e⟩ #align multiset.map_subset_map Multiset.map_subset_map theorem map_erase [DecidableEq α] [DecidableEq β] (f : α → β) (hf : Function.Injective f) (x : α) (s : Multiset α) : (s.erase x).map f = (s.map f).erase (f x) := by induction' s using Multiset.induction_on with y s ih · simp by_cases hxy : y = x · cases hxy simp · rw [s.erase_cons_tail hxy, map_cons, map_cons, (s.map f).erase_cons_tail (hf.ne hxy), ih] #align multiset.map_erase Multiset.map_erase theorem map_surjective_of_surjective {f : α → β} (hf : Function.Surjective f) : Function.Surjective (map f) := by intro s induction' s using Multiset.induction_on with x s ih · exact ⟨0, map_zero _⟩ · obtain ⟨y, rfl⟩ := hf x obtain ⟨t, rfl⟩ := ih exact ⟨y ::ₘ t, map_cons _ _ _⟩ #align multiset.map_surjective_of_surjective Multiset.map_surjective_of_surjective /-! ### `Multiset.fold` -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : RightCommutative f) (b : β) (s : Multiset α) : β := Quot.liftOn s (fun l => List.foldl f b l) fun _l₁ _l₂ p => p.foldl_eq H b #align multiset.foldl Multiset.foldl @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl #align multiset.foldl_zero Multiset.foldl_zero @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a ::ₘ s) = foldl f H (f b a) s := Quot.inductionOn s fun _l => rfl #align multiset.foldl_cons Multiset.foldl_cons @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := Quotient.inductionOn₂ s t fun _l₁ _l₂ => foldl_append _ _ _ _ #align multiset.foldl_add Multiset.foldl_add /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : LeftCommutative f) (b : β) (s : Multiset α) : β := Quot.liftOn s (fun l => List.foldr f b l) fun _l₁ _l₂ p => p.foldr_eq H b #align multiset.foldr Multiset.foldr @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl #align multiset.foldr_zero Multiset.foldr_zero @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a ::ₘ s) = f a (foldr f H b s) := Quot.inductionOn s fun _l => rfl #align multiset.foldr_cons Multiset.foldr_cons @[simp] theorem foldr_singleton (f : α → β → β) (H b a) : foldr f H b ({a} : Multiset α) = f a b := rfl #align multiset.foldr_singleton Multiset.foldr_singleton @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := Quotient.inductionOn₂ s t fun _l₁ _l₂ => foldr_append _ _ _ _ #align multiset.foldr_add Multiset.foldr_add @[simp] theorem coe_foldr (f : α → β → β) (H : LeftCommutative f) (b : β) (l : List α) : foldr f H b l = l.foldr f b := rfl #align multiset.coe_foldr Multiset.coe_foldr @[simp] theorem coe_foldl (f : β → α → β) (H : RightCommutative f) (b : β) (l : List α) : foldl f H b l = l.foldl f b := rfl #align multiset.coe_foldl Multiset.coe_foldl theorem coe_foldr_swap (f : α → β → β) (H : LeftCommutative f) (b : β) (l : List α) : foldr f H b l = l.foldl (fun x y => f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans <| foldr_reverse _ _ _ #align multiset.coe_foldr_swap Multiset.coe_foldr_swap theorem foldr_swap (f : α → β → β) (H : LeftCommutative f) (b : β) (s : Multiset α) : foldr f H b s = foldl (fun x y => f y x) (fun _x _y _z => (H _ _ _).symm) b s := Quot.inductionOn s fun _l => coe_foldr_swap _ _ _ _ #align multiset.foldr_swap Multiset.foldr_swap theorem foldl_swap (f : β → α → β) (H : RightCommutative f) (b : β) (s : Multiset α) : foldl f H b s = foldr (fun x y => f y x) (fun _x _y _z => (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm #align multiset.foldl_swap Multiset.foldl_swap theorem foldr_induction' (f : α → β → β) (H : LeftCommutative f) (x : β) (q : α → Prop) (p : β → Prop) (s : Multiset α) (hpqf : ∀ a b, q a → p b → p (f a b)) (px : p x) (q_s : ∀ a ∈ s, q a) : p (foldr f H x s) := by revert s refine' Multiset.induction (by simp [px]) _ intro a s hs hsa rw [foldr_cons] have hps : ∀ x : α, x ∈ s → q x := fun x hxs => hsa x (mem_cons_of_mem hxs) exact hpqf a (foldr f H x s) (hsa a (mem_cons_self a s)) (hs hps) #align multiset.foldr_induction' Multiset.foldr_induction' theorem foldr_induction (f : α → α → α) (H : LeftCommutative f) (x : α) (p : α → Prop) (s : Multiset α) (p_f : ∀ a b, p a → p b → p (f a b)) (px : p x) (p_s : ∀ a ∈ s, p a) : p (foldr f H x s) := foldr_induction' f H x p p s p_f px p_s #align multiset.foldr_induction Multiset.foldr_induction theorem foldl_induction' (f : β → α → β) (H : RightCommutative f) (x : β) (q : α → Prop) (p : β → Prop) (s : Multiset α) (hpqf : ∀ a b, q a → p b → p (f b a)) (px : p x) (q_s : ∀ a ∈ s, q a) : p (foldl f H x s) := by rw [foldl_swap] exact foldr_induction' (fun x y => f y x) (fun x y z => (H _ _ _).symm) x q p s hpqf px q_s #align multiset.foldl_induction' Multiset.foldl_induction' theorem foldl_induction (f : α → α → α) (H : RightCommutative f) (x : α) (p : α → Prop) (s : Multiset α) (p_f : ∀ a b, p a → p b → p (f b a)) (px : p x) (p_s : ∀ a ∈ s, p a) : p (foldl f H x s) := foldl_induction' f H x p p s p_f px p_s #align multiset.foldl_induction Multiset.foldl_induction /-! ### Map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ nonrec def pmap {p : α → Prop} (f : ∀ a, p a → β) (s : Multiset α) : (∀ a ∈ s, p a) → Multiset β := Quot.recOn' s (fun l H => ↑(pmap f l H)) fun l₁ l₂ (pp : l₁ ~ l₂) => funext fun H₂ : ∀ a ∈ l₂, p a => have H₁ : ∀ a ∈ l₁, p a := fun a h => H₂ a (pp.subset h) have : ∀ {s₂ e H}, @Eq.ndrec (Multiset α) l₁ (fun s => (∀ a ∈ s, p a) → Multiset β) (fun _ => ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁) := by intro s₂ e _ ; subst e; rfl this.trans <| Quot.sound <| pp.pmap f #align multiset.pmap Multiset.pmap @[simp] theorem coe_pmap {p : α → Prop} (f : ∀ a, p a → β) (l : List α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl #align multiset.coe_pmap Multiset.coe_pmap @[simp] theorem pmap_zero {p : α → Prop} (f : ∀ a, p a → β) (h : ∀ a ∈ (0 : Multiset α), p a) : pmap f 0 h = 0 := rfl #align multiset.pmap_zero Multiset.pmap_zero @[simp] theorem pmap_cons {p : α → Prop} (f : ∀ a, p a → β) (a : α) (m : Multiset α) : ∀ h : ∀ b ∈ a ::ₘ m, p b, pmap f (a ::ₘ m) h = f a (h a (mem_cons_self a m)) ::ₘ pmap f m fun a ha => h a <| mem_cons_of_mem ha := Quotient.inductionOn m fun _l _h => rfl #align multiset.pmap_cons Multiset.pmap_cons /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : Multiset α) : Multiset { x // x ∈ s } := pmap Subtype.mk s fun _a => id #align multiset.attach Multiset.attach @[simp] theorem coe_attach (l : List α) : @Eq (Multiset { x // x ∈ l }) (@attach α l) l.attach := rfl #align multiset.coe_attach Multiset.coe_attach theorem sizeOf_lt_sizeOf_of_mem [SizeOf α] {x : α} {s : Multiset α} (hx : x ∈ s) : SizeOf.sizeOf x < SizeOf.sizeOf s := by induction' s using Quot.inductionOn with l a b exact List.sizeOf_lt_sizeOf_of_mem hx #align multiset.sizeof_lt_sizeof_of_mem Multiset.sizeOf_lt_sizeOf_of_mem theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : Multiset α) : ∀ H, @pmap _ _ p (fun a _ => f a) s H = map f s := Quot.inductionOn s fun l H => congr_arg _ <| List.pmap_eq_map p f l H #align multiset.pmap_eq_map Multiset.pmap_eq_map theorem pmap_congr {p q : α → Prop} {f : ∀ a, p a → β} {g : ∀ a, q a → β} (s : Multiset α) : ∀ {H₁ H₂}, (∀ a ∈ s, ∀ (h₁ h₂), f a h₁ = g a h₂) → pmap f s H₁ = pmap g s H₂ := @(Quot.inductionOn s (fun l _H₁ _H₂ h => congr_arg _ <| List.pmap_congr l h)) #align multiset.pmap_congr Multiset.pmap_congr theorem map_pmap {p : α → Prop} (g : β → γ) (f : ∀ a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (fun a h => g (f a h)) s H := Quot.inductionOn s fun l H => congr_arg _ <| List.map_pmap g f l H #align multiset.map_pmap Multiset.map_pmap theorem pmap_eq_map_attach {p : α → Prop} (f : ∀ a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map fun x => f x.1 (H _ x.2) := Quot.inductionOn s fun l H => congr_arg _ <| List.pmap_eq_map_attach f l H #align multiset.pmap_eq_map_attach Multiset.pmap_eq_map_attach -- @[simp] -- Porting note: Left hand does not simplify theorem attach_map_val' (s : Multiset α) (f : α → β) : (s.attach.map fun i => f i.val) = s.map f := Quot.inductionOn s fun l => congr_arg _ <| List.attach_map_coe' l f #align multiset.attach_map_coe' Multiset.attach_map_val' #align multiset.attach_map_val' Multiset.attach_map_val' @[simp] theorem attach_map_val (s : Multiset α) : s.attach.map Subtype.val = s := (attach_map_val' _ _).trans s.map_id #align multiset.attach_map_coe Multiset.attach_map_val #align multiset.attach_map_val Multiset.attach_map_val @[simp] theorem mem_attach (s : Multiset α) : ∀ x, x ∈ s.attach := Quot.inductionOn s fun _l => List.mem_attach _ #align multiset.mem_attach Multiset.mem_attach @[simp] theorem mem_pmap {p : α → Prop} {f : ∀ a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ (a : _)(h : a ∈ s), f a (H a h) = b := Quot.inductionOn s (fun _l _H => List.mem_pmap) H #align multiset.mem_pmap Multiset.mem_pmap @[simp] theorem card_pmap {p : α → Prop} (f : ∀ a, p a → β) (s H) : card (pmap f s H) = card s := Quot.inductionOn s (fun _l _H => length_pmap) H #align multiset.card_pmap Multiset.card_pmap @[simp] theorem card_attach {m : Multiset α} : card (attach m) = card m := card_pmap _ _ _ #align multiset.card_attach Multiset.card_attach @[simp] theorem attach_zero : (0 : Multiset α).attach = 0 := rfl #align multiset.attach_zero Multiset.attach_zero theorem attach_cons (a : α) (m : Multiset α) : (a ::ₘ m).attach = ⟨a, mem_cons_self a m⟩ ::ₘ m.attach.map fun p => ⟨p.1, mem_cons_of_mem p.2⟩ := Quotient.inductionOn m fun l => congr_arg _ <| congr_arg (List.cons _) <| by rw [List.map_pmap]; exact List.pmap_congr _ fun _ _ _ _ => Subtype.eq rfl #align multiset.attach_cons Multiset.attach_cons section DecidablePiExists variable {m : Multiset α} /-- If `p` is a decidable predicate, so is the predicate that all elements of a multiset satisfy `p`. -/ protected def decidableForallMultiset {p : α → Prop} [hp : ∀ a, Decidable (p a)] : Decidable (∀ a ∈ m, p a) := Quotient.recOnSubsingleton m fun l => decidable_of_iff (∀ a ∈ l, p a) <| by simp #align multiset.decidable_forall_multiset Multiset.decidableForallMultiset instance decidableDforallMultiset {p : ∀ a ∈ m, Prop} [_hp : ∀ (a) (h : a ∈ m), Decidable (p a h)] : Decidable (∀ (a) (h : a ∈ m), p a h) := @decidable_of_iff _ _ (Iff.intro (fun h a ha => h ⟨a, ha⟩ (mem_attach _ _)) fun h ⟨_a, _ha⟩ _ => h _ _) (@Multiset.decidableForallMultiset _ m.attach (fun a => p a.1 a.2) _) #align multiset.decidable_dforall_multiset Multiset.decidableDforallMultiset /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidableEqPiMultiset {β : α → Type _} [h : ∀ a, DecidableEq (β a)] : DecidableEq (∀ a ∈ m, β a) := fun f g => decidable_of_iff (∀ (a) (h : a ∈ m), f a h = g a h) (by simp [Function.funext_iff]) #align multiset.decidable_eq_pi_multiset Multiset.decidableEqPiMultiset /-- If `p` is a decidable predicate, so is the existence of an element in a multiset satisfying `p`. -/ protected def decidableExistsMultiset {p : α → Prop} [DecidablePred p] : Decidable (∃ x ∈ m, p x) := Quotient.recOnSubsingleton m fun l => decidable_of_iff (∃ a ∈ l, p a) <| by simp #align multiset.decidable_exists_multiset Multiset.decidableExistsMultiset instance decidableDexistsMultiset {p : ∀ a ∈ m, Prop} [_hp : ∀ (a) (h : a ∈ m), Decidable (p a h)] : Decidable (∃ (a : _)(h : a ∈ m), p a h) := @decidable_of_iff _ _ (Iff.intro (fun ⟨⟨a, ha₁⟩, _, ha₂⟩ => ⟨a, ha₁, ha₂⟩) fun ⟨a, ha₁, ha₂⟩ => ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩) (@Multiset.decidableExistsMultiset { a // a ∈ m } m.attach (fun a => p a.1 a.2) _) #align multiset.decidable_dexists_multiset Multiset.decidableDexistsMultiset end DecidablePiExists /-! ### Subtraction -/ section variable [DecidableEq α] {s t u : Multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a` (note that it is truncated subtraction, so it is `0` if `count a t ≥ count a s`). -/ protected def sub (s t : Multiset α) : Multiset α := (Quotient.liftOn₂ s t fun l₁ l₂ => (l₁.diff l₂ : Multiset α)) fun _v₁ _v₂ _w₁ _w₂ p₁ p₂ => Quot.sound <| p₁.diff p₂ #align multiset.sub Multiset.sub instance : Sub (Multiset α) := ⟨Multiset.sub⟩ @[simp] theorem coe_sub (s t : List α) : (s - t : Multiset α) = (s.diff t : List α) := rfl #align multiset.coe_sub Multiset.coe_sub /-- This is a special case of `tsub_zero`, which should be used instead of this. This is needed to prove `OrderedSub (Multiset α)`. -/ protected theorem sub_zero (s : Multiset α) : s - 0 = s := Quot.inductionOn s fun _l => rfl #align multiset.sub_zero Multiset.sub_zero @[simp] theorem sub_cons (a : α) (s t : Multiset α) : s - a ::ₘ t = s.erase a - t := Quotient.inductionOn₂ s t fun _l₁ _l₂ => congr_arg _ <| diff_cons _ _ _ #align multiset.sub_cons Multiset.sub_cons /-- This is a special case of `tsub_le_iff_right`, which should be used instead of this. This is needed to prove `OrderedSub (Multiset α)`. -/ protected theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s exact @(Multiset.induction_on t (by simp [Multiset.sub_zero]) fun a t IH s => by simp [IH, erase_le_iff_le_cons]) #align multiset.sub_le_iff_le_add Multiset.sub_le_iff_le_add instance : OrderedSub (Multiset α) := ⟨fun _n _m _k => Multiset.sub_le_iff_le_add⟩ theorem cons_sub_of_le (a : α) {s t : Multiset α} (h : t ≤ s) : a ::ₘ s - t = a ::ₘ (s - t) := by rw [← singleton_add, ← singleton_add, add_tsub_assoc_of_le h] #align multiset.cons_sub_of_le Multiset.cons_sub_of_le theorem sub_eq_fold_erase (s t : Multiset α) : s - t = foldl erase erase_comm s t := Quotient.inductionOn₂ s t fun l₁ l₂ => by show ofList (l₁.diff l₂) = foldl erase erase_comm l₁ l₂ rw [diff_eq_foldl l₁ l₂] symm exact foldl_hom _ _ _ _ _ fun x y => rfl #align multiset.sub_eq_fold_erase Multiset.sub_eq_fold_erase @[simp] theorem card_sub {s t : Multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (tsub_eq_of_eq_add_rev <| by rw [add_comm, ← card_add, tsub_add_cancel_of_le h]).symm #align multiset.card_sub Multiset.card_sub /-! ### Union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : Multiset α) : Multiset α := s - t + t #align multiset.union Multiset.union instance : Union (Multiset α) := ⟨union⟩ theorem union_def (s t : Multiset α) : s ∪ t = s - t + t := rfl #align multiset.union_def Multiset.union_def theorem le_union_left (s t : Multiset α) : s ≤ s ∪ t := le_tsub_add #align multiset.le_union_left Multiset.le_union_left theorem le_union_right (s t : Multiset α) : t ≤ s ∪ t := le_add_left _ _ #align multiset.le_union_right Multiset.le_union_right theorem eq_union_left : t ≤ s → s ∪ t = s := tsub_add_cancel_of_le #align multiset.eq_union_left Multiset.eq_union_left theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (tsub_le_tsub_right h _) u #align multiset.union_le_union_right Multiset.union_le_union_right theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw [← eq_union_left h₂]; exact union_le_union_right h₁ t #align multiset.union_le Multiset.union_le @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨fun h => (mem_add.1 h).imp_left (mem_of_le tsub_le_self), (Or.elim · (mem_of_le <| le_union_left _ _) (mem_of_le <| le_union_right _ _))⟩ #align multiset.mem_union Multiset.mem_union @[simp] theorem map_union [DecidableEq β] {f : α → β} (finj : Function.Injective f) {s t : Multiset α} : map f (s ∪ t) = map f s ∪ map f t := Quotient.inductionOn₂ s t fun l₁ l₂ => congr_arg ofList (by rw [List.map_append f, List.map_diff finj]) #align multiset.map_union Multiset.map_union --Porting note: new theorem @[simp] theorem zero_union : 0 ∪ s = s := by simp [union_def] --Porting note: new theorem @[simp] theorem union_zero : s ∪ 0 = s := by simp [union_def] /-! ### Intersection -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : Multiset α) : Multiset α := Quotient.liftOn₂ s t (fun l₁ l₂ => (l₁.bagInter l₂ : Multiset α)) fun _v₁ _v₂ _w₁ _w₂ p₁ p₂ => Quot.sound <| p₁.bagInter p₂ #align multiset.inter Multiset.inter instance : Inter (Multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : Multiset α) : s ∩ 0 = 0 := Quot.inductionOn s fun l => congr_arg ofList l.bagInter_nil #align multiset.inter_zero Multiset.inter_zero @[simp] theorem zero_inter (s : Multiset α) : 0 ∩ s = 0 := Quot.inductionOn s fun l => congr_arg ofList l.nil_bagInter #align multiset.zero_inter Multiset.zero_inter @[simp] theorem cons_inter_of_pos {a} (s : Multiset α) {t} : a ∈ t → (a ::ₘ s) ∩ t = a ::ₘ s ∩ t.erase a := Quotient.inductionOn₂ s t fun _l₁ _l₂ h => congr_arg ofList <| cons_bagInter_of_pos _ h #align multiset.cons_inter_of_pos Multiset.cons_inter_of_pos @[simp] theorem cons_inter_of_neg {a} (s : Multiset α) {t} : a ∉ t → (a ::ₘ s) ∩ t = s ∩ t := Quotient.inductionOn₂ s t fun _l₁ _l₂ h => congr_arg ofList <| cons_bagInter_of_neg _ h #align multiset.cons_inter_of_neg Multiset.cons_inter_of_neg theorem inter_le_left (s t : Multiset α) : s ∩ t ≤ s := Quotient.inductionOn₂ s t fun _l₁ _l₂ => (bagInter_sublist_left _ _).subperm #align multiset.inter_le_left Multiset.inter_le_left theorem inter_le_right (s : Multiset α) : ∀ t, s ∩ t ≤ t := Multiset.induction_on s (fun t => (zero_inter t).symm ▸ zero_le _) fun a s IH t => if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] #align multiset.inter_le_right Multiset.inter_le_right theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := by revert s u; refine @(Multiset.induction_on t ?_ fun a t IH => ?_) <;> intros s u h₁ h₂ · simpa only [zero_inter, nonpos_iff_eq_zero] using h₁ by_cases h : a ∈ u · rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons] exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) · rw [cons_inter_of_neg _ h] exact IH ((le_cons_of_not_mem <| mt (mem_of_le h₂) h).1 h₁) h₂ #align multiset.le_inter Multiset.le_inter @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨fun h => ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, fun ⟨h₁, h₂⟩ => by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ #align multiset.mem_inter Multiset.mem_inter instance : Lattice (Multiset α) := { sup := (· ∪ ·) sup_le := @union_le _ _ le_sup_left := le_union_left le_sup_right := le_union_right inf := (· ∩ ·) le_inf := @le_inter _ _ inf_le_left := inter_le_left inf_le_right := inter_le_right } @[simp] theorem sup_eq_union (s t : Multiset α) : s ⊔ t = s ∪ t := rfl #align multiset.sup_eq_union Multiset.sup_eq_union @[simp] theorem inf_eq_inter (s t : Multiset α) : s ⊓ t = s ∩ t := rfl #align multiset.inf_eq_inter Multiset.inf_eq_inter @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff #align multiset.le_inter_iff Multiset.le_inter_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff #align multiset.union_le_iff Multiset.union_le_iff theorem union_comm (s t : Multiset α) : s ∪ t = t ∪ s := sup_comm #align multiset.union_comm Multiset.union_comm theorem inter_comm (s t : Multiset α) : s ∩ t = t ∩ s := inf_comm #align multiset.inter_comm Multiset.inter_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] #align multiset.eq_union_right Multiset.eq_union_right theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ #align multiset.union_le_union_left Multiset.union_le_union_left theorem union_le_add (s t : Multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) #align multiset.union_le_add Multiset.union_le_add theorem union_add_distrib (s t u : Multiset α) : s ∪ t + u = s + u ∪ (t + u) := by simpa [(· ∪ ·), union, eq_comm, add_assoc] using show s + u - (t + u) = s - t by rw [add_comm t, tsub_add_eq_tsub_tsub, add_tsub_cancel_right] #align multiset.union_add_distrib Multiset.union_add_distrib theorem add_union_distrib (s t u : Multiset α) : s + (t ∪ u) = s + t ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] #align multiset.add_union_distrib Multiset.add_union_distrib theorem cons_union_distrib (a : α) (s t : Multiset α) : a ::ₘ (s ∪ t) = a ::ₘ s ∪ a ::ₘ t := by simpa using add_union_distrib (a ::ₘ 0) s t #align multiset.cons_union_distrib Multiset.cons_union_distrib theorem inter_add_distrib (s t u : Multiset α) : s ∩ t + u = (s + u) ∩ (t + u) := by by_contra h cases' lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl rw [← cons_add] at hl exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) #align multiset.inter_add_distrib Multiset.inter_add_distrib theorem add_inter_distrib (s t u : Multiset α) : s + t ∩ u = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] #align multiset.add_inter_distrib Multiset.add_inter_distrib theorem cons_inter_distrib (a : α) (s t : Multiset α) : a ::ₘ s ∩ t = (a ::ₘ s) ∩ (a ::ₘ t) := by simp #align multiset.cons_inter_distrib Multiset.cons_inter_distrib theorem union_add_inter (s t : Multiset α) : s ∪ t + s ∩ t = s + t := by apply _root_.le_antisymm · rw [union_add_distrib] refine' union_le (add_le_add_left (inter_le_right _ _) _) _ rw [add_comm] exact add_le_add_right (inter_le_left _ _) _ · rw [add_comm, add_inter_distrib] refine' le_inter (add_le_add_right (le_union_right _ _) _) _ rw [add_comm] exact add_le_add_right (le_union_left _ _) _ #align multiset.union_add_inter Multiset.union_add_inter theorem sub_add_inter (s t : Multiset α) : s - t + s ∩ t = s := by rw [inter_comm] revert s; refine' Multiset.induction_on t (by simp) fun a t IH s => _ by_cases h : a ∈ s · rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] · rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] #align multiset.sub_add_inter Multiset.sub_add_inter theorem sub_inter (s t : Multiset α) : s - s ∩ t = s - t := add_right_cancel <| by rw [sub_add_inter s t, tsub_add_cancel_of_le (inter_le_left s t)] #align multiset.sub_inter Multiset.sub_inter end /-! ### `Multiset.filter` -/ section variable (p : α → Prop) [DecidablePred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (s : Multiset α) : Multiset α := Quot.liftOn s (fun l => (List.filter p l : Multiset α)) fun _l₁ _l₂ h => Quot.sound <| h.filter p #align multiset.filter Multiset.filter @[simp] theorem coe_filter (l : List α) : filter p ↑l = l.filter p := rfl #align multiset.coe_filter Multiset.coe_filter @[simp] theorem filter_zero : filter p 0 = 0 := rfl #align multiset.filter_zero Multiset.filter_zero theorem filter_congr {p q : α → Prop} [DecidablePred p] [DecidablePred q] {s : Multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := Quot.inductionOn s fun _l h => congr_arg ofList <| filter_congr' $ by simpa using h #align multiset.filter_congr Multiset.filter_congr @[simp] theorem filter_add (s t : Multiset α) : filter p (s + t) = filter p s + filter p t := Quotient.inductionOn₂ s t fun _l₁ _l₂ => congr_arg ofList <| filter_append _ _ #align multiset.filter_add Multiset.filter_add @[simp] theorem filter_le (s : Multiset α) : filter p s ≤ s := Quot.inductionOn s fun _l => (filter_sublist _).subperm #align multiset.filter_le Multiset.filter_le @[simp] theorem filter_subset (s : Multiset α) : filter p s ⊆ s := subset_of_le <| filter_le _ _ #align multiset.filter_subset Multiset.filter_subset theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := leInductionOn h fun h => (h.filter (p ·)).subperm #align multiset.filter_le_filter Multiset.filter_le_filter theorem monotone_filter_left : Monotone (filter p) := fun _s _t => filter_le_filter p #align multiset.monotone_filter_left Multiset.monotone_filter_left theorem monotone_filter_right (s : Multiset α) ⦃p q : α → Prop⦄ [DecidablePred p] [DecidablePred q] (h : ∀ b, p b → q b) : s.filter p ≤ s.filter q := Quotient.inductionOn s fun l => (l.monotone_filter_right $ by simpa using h).subperm #align multiset.monotone_filter_right Multiset.monotone_filter_right variable {p} @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a ::ₘ s) = a ::ₘ filter p s := Quot.inductionOn s fun l h => congr_arg ofList <| List.filter_cons_of_pos l $ by simpa using h #align multiset.filter_cons_of_pos Multiset.filter_cons_of_pos @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬p a → filter p (a ::ₘ s) = filter p s := Quot.inductionOn s fun l h => congr_arg ofList <| List.filter_cons_of_neg l $ by simpa using h #align multiset.filter_cons_of_neg Multiset.filter_cons_of_neg @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := Quot.inductionOn s fun _l => by simpa using List.mem_filter (p := (p ·)) #align multiset.mem_filter Multiset.mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 #align multiset.of_mem_filter Multiset.of_mem_filter theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 #align multiset.mem_of_mem_filter Multiset.mem_of_mem_filter theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ #align multiset.mem_filter_of_mem Multiset.mem_filter_of_mem theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := Quot.inductionOn s fun _l => Iff.trans ⟨fun h => (filter_sublist _).eq_of_length (@congr_arg _ _ _ _ card h), congr_arg ofList⟩ $ by simpa using List.filter_eq_self (p := (p ·)) #align multiset.filter_eq_self Multiset.filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := Quot.inductionOn s fun _l => Iff.trans ⟨fun h => eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg ofList⟩ $ by simpa using List.filter_eq_nil (p := (p ·)) #align multiset.filter_eq_nil Multiset.filter_eq_nil theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨fun h => ⟨le_trans h (filter_le _ _), fun _a m => of_mem_filter (mem_of_le h m)⟩, fun ⟨h, al⟩ => filter_eq_self.2 al ▸ filter_le_filter p h⟩ #align multiset.le_filter Multiset.le_filter theorem filter_cons {a : α} (s : Multiset α) : filter p (a ::ₘ s) = (if p a then {a} else 0) + filter p s := by split_ifs with h · rw [filter_cons_of_pos _ h, singleton_add] · rw [filter_cons_of_neg _ h, zero_add] #align multiset.filter_cons Multiset.filter_cons theorem filter_singleton {a : α} (p : α → Prop) [DecidablePred p] : filter p {a} = if p a then {a} else ∅ := by simp only [singleton, filter_cons, filter_zero, add_zero, empty_eq_zero] #align multiset.filter_singleton Multiset.filter_singleton theorem filter_nsmul (s : Multiset α) (n : ℕ) : filter p (n • s) = n • filter p s := by refine' s.induction_on _ _ · simp only [filter_zero, nsmul_zero] · intro a ha ih rw [nsmul_cons, filter_add, ih, filter_cons, nsmul_add] congr split_ifs with hp <;> · simp only [filter_eq_self, nsmul_zero, filter_eq_nil] intro b hb rwa [mem_singleton.mp (mem_of_mem_nsmul hb)] #align multiset.filter_nsmul Multiset.filter_nsmul variable (p) @[simp] theorem filter_sub [DecidableEq α] (s t : Multiset α) : filter p (s - t) = filter p s - filter p t := by revert s; refine' Multiset.induction_on t (by simp) fun a t IH s => _ rw [sub_cons, IH] by_cases h : p a · rw [filter_cons_of_pos _ h, sub_cons] congr by_cases m : a ∈ s · rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] · rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] · rw [filter_cons_of_neg _ h] by_cases m : a ∈ s · rw [(by rw [filter_cons_of_neg _ h] : filter p (erase s a) = filter p (a ::ₘ erase s a)), cons_erase m] · rw [erase_of_not_mem m] #align multiset.filter_sub Multiset.filter_sub @[simp] theorem filter_union [DecidableEq α] (s t : Multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(· ∪ ·), union] #align multiset.filter_union Multiset.filter_union @[simp] theorem filter_inter [DecidableEq α] (s t : Multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter _ <| inter_le_left _ _) (filter_le_filter _ <| inter_le_right _ _)) <| le_filter.2 ⟨inf_le_inf (filter_le _ _) (filter_le _ _), fun _a h => of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ #align multiset.filter_inter Multiset.filter_inter @[simp] theorem filter_filter (q) [DecidablePred q] (s : Multiset α) : filter p (filter q s) = filter (fun a => p a ∧ q a) s := Quot.inductionOn s fun l => by simp #align multiset.filter_filter Multiset.filter_filter theorem filter_add_filter (q) [DecidablePred q] (s : Multiset α) : filter p s + filter q s = filter (fun a => p a ∨ q a) s + filter (fun a => p a ∧ q a) s := Multiset.induction_on s rfl fun a s IH => by by_cases p a <;> by_cases q a <;> simp [*] #align multiset.filter_add_filter Multiset.filter_add_filter theorem filter_add_not (s : Multiset α) : filter p s + filter (fun a => ¬p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2] · simp only [add_zero] · simp [Decidable.em, -Bool.not_eq_true, -not_and, not_and_or, or_comm] · simp only [Bool.not_eq_true, decide_eq_true_eq, Bool.eq_false_or_eq_true, decide_True, implies_true, Decidable.em] #align multiset.filter_add_not Multiset.filter_add_not theorem map_filter (f : β → α) (s : Multiset β) : filter p (map f s) = map f (filter (p ∘ f) s) := Quot.inductionOn s fun l => by simp [List.map_filter]; rfl #align multiset.map_filter Multiset.map_filter /-! ### Simultaneously filter and map elements of a multiset -/ /-- `filterMap f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filterMap (f : α → Option β) (s : Multiset α) : Multiset β := Quot.liftOn s (fun l => (List.filterMap f l : Multiset β)) fun _l₁ _l₂ h => Quot.sound <| h.filterMap f #align multiset.filter_map Multiset.filterMap @[simp] theorem coe_filterMap (f : α → Option β) (l : List α) : filterMap f l = l.filterMap f := rfl #align multiset.coe_filter_map Multiset.coe_filterMap @[simp] theorem filterMap_zero (f : α → Option β) : filterMap f 0 = 0 := rfl #align multiset.filter_map_zero Multiset.filterMap_zero @[simp] theorem filterMap_cons_none {f : α → Option β} (a : α) (s : Multiset α) (h : f a = none) : filterMap f (a ::ₘ s) = filterMap f s := Quot.inductionOn s fun l => congr_arg ofList <| List.filterMap_cons_none a l h #align multiset.filter_map_cons_none Multiset.filterMap_cons_none @[simp] theorem filterMap_cons_some (f : α → Option β) (a : α) (s : Multiset α) {b : β} (h : f a = some b) : filterMap f (a ::ₘ s) = b ::ₘ filterMap f s := Quot.inductionOn s fun l => congr_arg ofList <| List.filterMap_cons_some f a l h #align multiset.filter_map_cons_some Multiset.filterMap_cons_some theorem filterMap_eq_map (f : α → β) : filterMap (some ∘ f) = map f := funext fun s => Quot.inductionOn s fun l => congr_arg ofList <| congr_fun (List.filterMap_eq_map f) l #align multiset.filter_map_eq_map Multiset.filterMap_eq_map theorem filterMap_eq_filter : filterMap (Option.guard p) = filter p := funext fun s => Quot.inductionOn s fun l => congr_arg ofList <| by rw [← List.filterMap_eq_filter] congr; funext a; simp #align multiset.filter_map_eq_filter Multiset.filterMap_eq_filter theorem filterMap_filterMap (f : α → Option β) (g : β → Option γ) (s : Multiset α) : filterMap g (filterMap f s) = filterMap (fun x => (f x).bind g) s := Quot.inductionOn s fun l => congr_arg ofList <| List.filterMap_filterMap f g l #align multiset.filter_map_filter_map Multiset.filterMap_filterMap theorem map_filterMap (f : α → Option β) (g : β → γ) (s : Multiset α) : map g (filterMap f s) = filterMap (fun x => (f x).map g) s := Quot.inductionOn s fun l => congr_arg ofList <| List.map_filterMap f g l #align multiset.map_filter_map Multiset.map_filterMap theorem filterMap_map (f : α → β) (g : β → Option γ) (s : Multiset α) : filterMap g (map f s) = filterMap (g ∘ f) s := Quot.inductionOn s fun l => congr_arg ofList <| List.filterMap_map f g l #align multiset.filter_map_map Multiset.filterMap_map theorem filter_filterMap (f : α → Option β) (p : β → Prop) [DecidablePred p] (s : Multiset α) : filter p (filterMap f s) = filterMap (fun x => (f x).filter p) s := Quot.inductionOn s fun l => congr_arg ofList <| List.filter_filterMap f p l #align multiset.filter_filter_map Multiset.filter_filterMap theorem filterMap_filter (f : α → Option β) (s : Multiset α) : filterMap f (filter p s) = filterMap (fun x => if p x then f x else none) s := Quot.inductionOn s fun l => congr_arg ofList <| by simpa using List.filterMap_filter p f l #align multiset.filter_map_filter Multiset.filterMap_filter @[simp] theorem filterMap_some (s : Multiset α) : filterMap some s = s := Quot.inductionOn s fun l => congr_arg ofList <| List.filterMap_some l #align multiset.filter_map_some Multiset.filterMap_some @[simp] theorem mem_filterMap (f : α → Option β) (s : Multiset α) {b : β} : b ∈ filterMap f s ↔ ∃ a, a ∈ s ∧ f a = some b := Quot.inductionOn s fun l => List.mem_filterMap f l #align multiset.mem_filter_map Multiset.mem_filterMap theorem map_filterMap_of_inv (f : α → Option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : Multiset α) : map g (filterMap f s) = s := Quot.inductionOn s fun l => congr_arg ofList <| List.map_filterMap_of_inv f g H l #align multiset.map_filter_map_of_inv Multiset.map_filterMap_of_inv theorem filterMap_le_filterMap (f : α → Option β) {s t : Multiset α} (h : s ≤ t) : filterMap f s ≤ filterMap f t := leInductionOn h fun h => (h.filterMap _).subperm #align multiset.filter_map_le_filter_map Multiset.filterMap_le_filterMap /-! ### countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (s : Multiset α) : ℕ := Quot.liftOn s (List.countp p) fun _l₁ _l₂ => Perm.countp_eq (p ·) #align multiset.countp Multiset.countp @[simp] theorem coe_countp (l : List α) : countp p l = l.countp p := rfl #align multiset.coe_countp Multiset.coe_countp @[simp] theorem countp_zero : countp p 0 = 0 := rfl #align multiset.countp_zero Multiset.countp_zero variable {p} @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a ::ₘ s) = countp p s + 1 := Quot.inductionOn s <| by simpa using List.countp_cons_of_pos (p ·) #align multiset.countp_cons_of_pos Multiset.countp_cons_of_pos @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬p a → countp p (a ::ₘ s) = countp p s := Quot.inductionOn s <| by simpa using List.countp_cons_of_neg (p ·) #align multiset.countp_cons_of_neg Multiset.countp_cons_of_neg variable (p) theorem countp_cons (b : α) (s) : countp p (b ::ₘ s) = countp p s + if p b then 1 else 0 := Quot.inductionOn s <| by simp [List.countp_cons] #align multiset.countp_cons Multiset.countp_cons theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := Quot.inductionOn s fun l => l.countp_eq_length_filter (p ·) #align multiset.countp_eq_card_filter Multiset.countp_eq_card_filter theorem countp_le_card (s) : countp p s ≤ card s := Quot.inductionOn s fun _l => countp_le_length (p ·) #align multiset.countp_le_card Multiset.countp_le_card @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] #align multiset.countp_add Multiset.countp_add @[simp] theorem countp_nsmul (s) (n : ℕ) : countp p (n • s) = n * countp p s := by induction n <;> simp [*, succ_nsmul', succ_mul, zero_nsmul] #align multiset.countp_nsmul Multiset.countp_nsmul theorem card_eq_countp_add_countp (s) : card s = countp p s + countp (fun x => ¬p x) s := Quot.inductionOn s fun l => by simp [l.length_eq_countp_add_countp p] #align multiset.card_eq_countp_add_countp Multiset.card_eq_countp_add_countp /-- `countp p`, the number of elements of a multiset satisfying `p`, promoted to an `AddMonoidHom`. -/ def countpAddMonoidHom : Multiset α →+ ℕ where toFun := countp p map_zero' := countp_zero _ map_add' := countp_add _ #align multiset.countp_add_monoid_hom Multiset.countpAddMonoidHom @[simp] theorem coe_countpAddMonoidHom : (countpAddMonoidHom p : Multiset α → ℕ) = countp p := rfl #align multiset.coe_countp_add_monoid_hom Multiset.coe_countpAddMonoidHom @[simp] theorem countp_sub [DecidableEq α] {s t : Multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] #align multiset.countp_sub Multiset.countp_sub theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter p h) #align multiset.countp_le_of_le Multiset.countp_le_of_le @[simp] theorem countp_filter (q) [DecidablePred q] (s : Multiset α) : countp p (filter q s) = countp (fun a => p a ∧ q a) s := by simp [countp_eq_card_filter] #align multiset.countp_filter Multiset.countp_filter theorem countp_eq_countp_filter_add (s) (p q : α → Prop) [DecidablePred p] [DecidablePred q] : countp p s = (filter q s).countp p + (filter (fun a => ¬q a) s).countp p := Quot.inductionOn s fun l => by convert l.countp_eq_countp_filter_add (p ·) (q ·); simp #align multiset.countp_eq_countp_filter_add Multiset.countp_eq_countp_filter_add @[simp] theorem countp_True {s : Multiset α} : countp (fun _ => True) s = card s := Quot.inductionOn s fun _l => List.countp_true #align multiset.countp_true Multiset.countp_True @[simp] theorem countp_False {s : Multiset α} : countp (fun _ => False) s = 0 := Quot.inductionOn s fun _l => List.countp_false #align multiset.countp_false Multiset.countp_False theorem countp_map (f : α → β) (s : Multiset α) (p : β → Prop) [DecidablePred p] : countp p (map f s) = card (s.filter fun a => p (f a)) := by refine' Multiset.induction_on s _ fun a t IH => _ · rw [map_zero, countp_zero, filter_zero, card_zero] · rw [map_cons, countp_cons, IH, filter_cons, card_add, apply_ite card, card_zero, card_singleton, add_comm] #align multiset.countp_map Multiset.countp_map variable {p} theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := Quot.inductionOn s fun _l => by simpa using List.countp_pos (p ·) #align multiset.countp_pos Multiset.countp_pos theorem countp_eq_zero {s} : countp p s = 0 ↔ ∀ a ∈ s, ¬p a := Quot.inductionOn s fun _l => by simp #align multiset.countp_eq_zero Multiset.countp_eq_zero theorem countp_eq_card {s} : countp p s = card s ↔ ∀ a ∈ s, p a := Quot.inductionOn s fun _l => by simp #align multiset.countp_eq_card Multiset.countp_eq_card theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ #align multiset.countp_pos_of_mem Multiset.countp_pos_of_mem theorem countp_congr {s s' : Multiset α} (hs : s = s') {p p' : α → Prop} [DecidablePred p] [DecidablePred p'] (hp : ∀ x ∈ s, p x = p' x) : s.countp p = s'.countp p' := by revert hs hp exact Quot.induction_on₂ s s' (fun l l' hs hp => by simp only [quot_mk_to_coe'', coe_eq_coe] at hs apply hs.countp_congr simpa using hp) #align multiset.countp_congr Multiset.countp_congr end /-! ### Multiplicity of an element -/ section variable [DecidableEq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : Multiset α → ℕ := countp (a = ·) #align multiset.count Multiset.count @[simp] theorem coe_count (a : α) (l : List α) : count a (ofList l) = l.count a := by simp_rw [count, List.count, coe_countp (a = ·) l, @eq_comm _ a] rfl #align multiset.coe_count Multiset.coe_count @[simp, nolint simpNF] -- Porting note: simp can prove this at EOF, but not right now theorem count_zero (a : α) : count a 0 = 0 := rfl #align multiset.count_zero Multiset.count_zero @[simp] theorem count_cons_self (a : α) (s : Multiset α) : count a (a ::ₘ s) = count a s + 1 := countp_cons_of_pos _ $ rfl #align multiset.count_cons_self Multiset.count_cons_self @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : Multiset α) : count a (b ::ₘ s) = count a s := countp_cons_of_neg _ $ h #align multiset.count_cons_of_ne Multiset.count_cons_of_ne theorem count_le_card (a : α) (s) : count a s ≤ card s := countp_le_card _ _ #align multiset.count_le_card Multiset.count_le_card theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le _ #align multiset.count_le_of_le Multiset.count_le_of_le theorem count_le_count_cons (a b : α) (s : Multiset α) : count a s ≤ count a (b ::ₘ s) := count_le_of_le _ (le_cons_self _ _) #align multiset.count_le_count_cons Multiset.count_le_count_cons theorem count_cons (a b : α) (s : Multiset α) : count a (b ::ₘ s) = count a s + if a = b then 1 else 0 := countp_cons (a = ·) _ _ #align multiset.count_cons Multiset.count_cons theorem count_singleton_self (a : α) : count a ({a} : Multiset α) = 1 := count_eq_one_of_mem (nodup_singleton a) <| mem_singleton_self a #align multiset.count_singleton_self Multiset.count_singleton_self theorem count_singleton (a b : α) : count a ({b} : Multiset α) = if a = b then 1 else 0 := by simp only [count_cons, ← cons_zero, count_zero, zero_add] #align multiset.count_singleton Multiset.count_singleton @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add _ #align multiset.count_add Multiset.count_add /-- `count a`, the multiplicity of `a` in a multiset, promoted to an `AddMonoidHom`. -/ def countAddMonoidHom (a : α) : Multiset α →+ ℕ := countpAddMonoidHom (a = ·) #align multiset.count_add_monoid_hom Multiset.countAddMonoidHom @[simp] theorem coe_countAddMonoidHom {a : α} : (countAddMonoidHom a : Multiset α → ℕ) = count a := rfl #align multiset.coe_count_add_monoid_hom Multiset.coe_countAddMonoidHom @[simp] theorem count_nsmul (a : α) (n s) : count a (n • s) = n * count a s := by induction n <;> simp [*, succ_nsmul', succ_mul, zero_nsmul] #align multiset.count_nsmul Multiset.count_nsmul theorem count_pos {a : α} {s : Multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] #align multiset.count_pos Multiset.count_pos theorem one_le_count_iff_mem {a : α} {s : Multiset α} : 1 ≤ count a s ↔ a ∈ s := by rw [succ_le_iff, count_pos] #align multiset.one_le_count_iff_mem Multiset.one_le_count_iff_mem @[simp] theorem count_eq_zero_of_not_mem {a : α} {s : Multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction fun h' => h <| count_pos.1 (Nat.pos_of_ne_zero h') #align multiset.count_eq_zero_of_not_mem Multiset.count_eq_zero_of_not_mem @[simp] theorem count_eq_zero {a : α} {s : Multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 <| count_pos.symm.trans pos_iff_ne_zero #align multiset.count_eq_zero Multiset.count_eq_zero theorem count_ne_zero {a : α} {s : Multiset α} : count a s ≠ 0 ↔ a ∈ s := by simp [Ne.def, count_eq_zero] #align multiset.count_ne_zero Multiset.count_ne_zero theorem count_eq_card {a : α} {s} : count a s = card s ↔ ∀ x ∈ s, a = x := by simp [countp_eq_card, count, @eq_comm _ a] #align multiset.count_eq_card Multiset.count_eq_card @[simp] theorem count_replicate_self (a : α) (n : ℕ) : count a (replicate n a) = n := by convert List.count_replicate_self a n rw [←coe_count, coe_replicate] #align multiset.count_replicate_self Multiset.count_replicate_self theorem count_replicate (a b : α) (n : ℕ) : count a (replicate n b) = if a = b then n else 0 := by convert List.count_replicate a b n rw [←coe_count, coe_replicate] #align multiset.count_replicate Multiset.count_replicate @[simp] theorem count_erase_self (a : α) (s : Multiset α) : count a (erase s a) = count a s - 1 := Quotient.inductionOn s <| fun l => by convert List.count_erase_self a l <;> rw [←coe_count] <;> simp #align multiset.count_erase_self Multiset.count_erase_self @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : Multiset α) : count a (erase s b) = count a s := Quotient.inductionOn s <| fun l => by convert List.count_erase_of_ne ab l <;> rw [←coe_count] <;> simp #align multiset.count_erase_of_ne Multiset.count_erase_of_ne @[simp] theorem count_sub (a : α) (s t : Multiset α) : count a (s - t) = count a s - count a t := by revert s; refine' Multiset.induction_on t (by simp) fun b t IH s => _ rw [sub_cons, IH] rcases Decidable.eq_or_ne a b with rfl | ab · rw [count_erase_self, count_cons_self, Nat.sub_sub, add_comm] · rw [count_erase_of_ne ab, count_cons_of_ne ab] #align multiset.count_sub Multiset.count_sub @[simp] theorem count_union (a : α) (s t : Multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(· ∪ ·), union, tsub_add_eq_max] #align multiset.count_union Multiset.count_union @[simp] theorem count_inter (a : α) (s t : Multiset α) : count a (s ∩ t) = min (count a s) (count a t) := by apply @Nat.add_left_cancel (count a (s - t)) rw [← count_add, sub_add_inter, count_sub, tsub_add_min] #align multiset.count_inter Multiset.count_inter theorem le_count_iff_replicate_le {a : α} {s : Multiset α} {n : ℕ} : n ≤ count a s ↔ replicate n a ≤ s := Quot.inductionOn s fun _l => by simp only [quot_mk_to_coe'', mem_coe, coe_count] exact le_count_iff_replicate_sublist.trans replicate_le_coe.symm #align multiset.le_count_iff_replicate_le Multiset.le_count_iff_replicate_le @[simp] theorem count_filter_of_pos {p} [DecidablePred p] {a} {s : Multiset α} (h : p a) : count a (filter p s) = count a s := Quot.inductionOn s fun _l => by simp only [quot_mk_to_coe'', coe_filter, mem_coe, coe_count, decide_eq_true_eq] apply count_filter simpa using h #align multiset.count_filter_of_pos Multiset.count_filter_of_pos @[simp] theorem count_filter_of_neg {p} [DecidablePred p] {a} {s : Multiset α} (h : ¬p a) : count a (filter p s) = 0 := Multiset.count_eq_zero_of_not_mem fun t => h (of_mem_filter t) #align multiset.count_filter_of_neg Multiset.count_filter_of_neg theorem count_filter {p} [DecidablePred p] {a} {s : Multiset α} : count a (filter p s) = if p a then count a s else 0 := by split_ifs with h · exact count_filter_of_pos h · exact count_filter_of_neg h #align multiset.count_filter Multiset.count_filter theorem ext {s t : Multiset α} : s = t ↔ ∀ a, count a s = count a t := Quotient.inductionOn₂ s t fun _l₁ _l₂ => Quotient.eq.trans <| by simp only [quot_mk_to_coe, coe_filter, mem_coe, coe_count, decide_eq_true_eq] apply perm_iff_count #align multiset.ext Multiset.ext @[ext] theorem ext' {s t : Multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 #align multiset.ext' Multiset.ext' @[simp] theorem coe_inter (s t : List α) : (s ∩ t : Multiset α) = (s.bagInter t : List α) := by ext; simp #align multiset.coe_inter Multiset.coe_inter theorem le_iff_count {s t : Multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨fun h a => count_le_of_le a h, fun al => by rw [← (ext.2 fun a => by simp [max_eq_right (al a)] : s ∪ t = t)]; apply le_union_left⟩ #align multiset.le_iff_count Multiset.le_iff_count instance : DistribLattice (Multiset α) := { le_sup_inf := fun s t u => le_of_eq <| Eq.symm <| ext.2 fun a => by simp only [max_min_distrib_left, Multiset.count_inter, Multiset.sup_eq_union, Multiset.count_union, Multiset.inf_eq_inter] } theorem count_map {α β : Type _} (f : α → β) (s : Multiset α) [DecidableEq β] (b : β) : count b (map f s) = card (s.filter fun a => b = f a) := by simp [Bool.beq_eq_decide_eq, eq_comm, count, countp_map] #align multiset.count_map Multiset.count_map /- ./././Mathport/Syntax/Translate/Basic.lean:632:2: warning: expanding binder collection (x «expr ∈ » s) -/ /-- `Multiset.map f` preserves `count` if `f` is injective on the set of elements contained in the multiset -/ theorem count_map_eq_count [DecidableEq β] (f : α → β) (s : Multiset α) (hf : Set.InjOn f { x : α | x ∈ s }) (x) (H : x ∈ s) : (s.map f).count (f x) = s.count x := by suffices (filter (fun a : α => f x = f a) s).count x = card (filter (fun a : α => f x = f a) s) by rw [count, countp_map, ← this] exact count_filter_of_pos $ rfl · rw [eq_replicate_card.2 fun b hb => (hf H (mem_filter.1 hb).left _).symm] · simp only [count_replicate, eq_self_iff_true, if_true, card_replicate] · simp only [mem_filter, beq_iff_eq, and_imp, @eq_comm _ (f x), imp_self, implies_true] #align multiset.count_map_eq_count Multiset.count_map_eq_count /-- `Multiset.map f` preserves `count` if `f` is injective -/ theorem count_map_eq_count' [DecidableEq β] (f : α → β) (s : Multiset α) (hf : Function.Injective f) (x : α) : (s.map f).count (f x) = s.count x := by by_cases H : x ∈ s · exact count_map_eq_count f _ (Set.injOn_of_injective hf _) _ H · rw [count_eq_zero_of_not_mem H, count_eq_zero, mem_map] rintro ⟨k, hks, hkx⟩ rw [hf hkx] at hks contradiction #align multiset.count_map_eq_count' Multiset.count_map_eq_count' @[simp] theorem attach_count_eq_count_coe (m : Multiset α) (a) : m.attach.count a = m.count (a : α) := calc m.attach.count a = (m.attach.map (Subtype.val : _ → α)).count (a : α) := (Multiset.count_map_eq_count' _ _ Subtype.coe_injective _).symm _ = m.count (a : α) := congr_arg _ m.attach_map_val #align multiset.attach_count_eq_count_coe Multiset.attach_count_eq_count_coe theorem filter_eq' (s : Multiset α) (b : α) : s.filter (· = b) = replicate (count b s) b := Quotient.inductionOn s <| fun l => by simp only [quot_mk_to_coe, coe_filter, mem_coe, coe_count] rw [List.filter_eq' l b, coe_replicate] #align multiset.filter_eq' Multiset.filter_eq' theorem filter_eq (s : Multiset α) (b : α) : s.filter (Eq b) = replicate (count b s) b := by simp_rw [← filter_eq', eq_comm] #align multiset.filter_eq Multiset.filter_eq @[simp] theorem replicate_inter (n : ℕ) (x : α) (s : Multiset α) : replicate n x ∩ s = replicate (min n (s.count x)) x := by ext y rw [count_inter, count_replicate, count_replicate] by_cases h : y = x · simp only [h, if_true] · simp only [h, if_false, zero_min] #align multiset.replicate_inter Multiset.replicate_inter @[simp] theorem inter_replicate (s : Multiset α) (n : ℕ) (x : α) : s ∩ replicate n x = replicate (min (s.count x) n) x := by rw [inter_comm, replicate_inter, min_comm] #align multiset.inter_replicate Multiset.inter_replicate end @[ext] theorem addHom_ext [AddZeroClass β] ⦃f g : Multiset α →+ β⦄ (h : ∀ x, f {x} = g {x}) : f = g := by ext s induction' s using Multiset.induction_on with a s ih · simp only [_root_.map_zero] · simp only [← singleton_add, _root_.map_add, ih, h] #align multiset.add_hom_ext Multiset.addHom_ext section Embedding @[simp] theorem map_le_map_iff {f : α → β} (hf : Function.Injective f) {s t : Multiset α} : s.map f ≤ t.map f ↔ s ≤ t := by classical refine' ⟨fun h => le_iff_count.mpr fun a => _, map_le_map⟩ simpa [count_map_eq_count' f _ hf] using le_iff_count.mp h (f a) #align multiset.map_le_map_iff Multiset.map_le_map_iff /-- Associate to an embedding `f` from `α` to `β` the order embedding that maps a multiset to its image under `f`. -/ @[simps!] def mapEmbedding (f : α ↪ β) : Multiset α ↪o Multiset β := OrderEmbedding.ofMapLEIff (map f) fun _ _ => map_le_map_iff f.inj' #align multiset.map_embedding Multiset.mapEmbedding #align multiset.map_embedding_apply Multiset.mapEmbedding_apply end Embedding theorem count_eq_card_filter_eq [DecidableEq α] (s : Multiset α) (a : α) : s.count a = card (s.filter (a = ·)) := by rw [count, countp_eq_card_filter] #align multiset.count_eq_card_filter_eq Multiset.count_eq_card_filter_eq /-- Mapping a multiset through a predicate and counting the `True`s yields the cardinality of the set filtered by the predicate. Note that this uses the notion of a multiset of `Prop`s - due to the decidability requirements of `count`, the decidability instance on the LHS is different from the RHS. In particular, the decidability instance on the left leaks `Classical.decEq`. See [here](https://github.com/leanprover-community/mathlib/pull/11306#discussion_r782286812) for more discussion. -/ @[simp] theorem map_count_True_eq_filter_card (s : Multiset α) (p : α → Prop) [DecidablePred p] : (s.map p).count True = card (s.filter p) := by simp only [count_eq_card_filter_eq, map_filter, card_map, Function.comp.left_id, eq_true_eq_id, Function.comp] congr; funext _ simp only [eq_iff_iff, true_iff] #align multiset.map_count_true_eq_filter_card Multiset.map_count_True_eq_filter_card /-! ### Lift a relation to `Multiset`s -/ section Rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ @[mk_iff] inductive Rel (r : α → β → Prop) : Multiset α → Multiset β → Prop | zero : Rel r 0 0 | cons {a b as bs} : r a b → Rel r as bs → Rel r (a ::ₘ as) (b ::ₘ bs) #align multiset.rel Multiset.Rel #align multiset.rel_iff Multiset.Rel_iff variable {δ : Type _} {r : α → β → Prop} {p : γ → δ → Prop} private theorem rel_flip_aux {s t} (h : Rel r s t) : Rel (flip r) t s := Rel.recOn h Rel.zero fun h₀ _h₁ ih => Rel.cons h₀ ih theorem rel_flip {s t} : Rel (flip r) s t ↔ Rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ #align multiset.rel_flip Multiset.rel_flip theorem rel_refl_of_refl_on {m : Multiset α} {r : α → α → Prop} : (∀ x ∈ m, r x x) → Rel r m m := by refine' m.induction_on _ _ · intros apply Rel.zero · intro a m ih h exact Rel.cons (h _ (mem_cons_self _ _)) (ih fun _ ha => h _ (mem_cons_of_mem ha)) #align multiset.rel_refl_of_refl_on Multiset.rel_refl_of_refl_on theorem rel_eq_refl {s : Multiset α} : Rel (· = ·) s s := rel_refl_of_refl_on fun _x _hx => rfl #align multiset.rel_eq_refl Multiset.rel_eq_refl theorem rel_eq {s t : Multiset α} : Rel (· = ·) s t ↔ s = t := by constructor · intro h induction h <;> simp [*] · intro h subst h exact rel_eq_refl #align multiset.rel_eq Multiset.rel_eq theorem Rel.mono {r p : α → β → Prop} {s t} (hst : Rel r s t) (h : ∀ a ∈ s, ∀ b ∈ t, r a b → p a b) : Rel p s t := by induction hst case zero => exact Rel.zero case cons a b s t hab _hst ih => apply Rel.cons (h a (mem_cons_self _ _) b (mem_cons_self _ _) hab) exact ih fun a' ha' b' hb' h' => h a' (mem_cons_of_mem ha') b' (mem_cons_of_mem hb') h' #align multiset.rel.mono Multiset.Rel.mono theorem Rel.add {s t u v} (hst : Rel r s t) (huv : Rel r u v) : Rel r (s + u) (t + v) := by induction hst case zero => simpa using huv case cons a b s t hab hst ih => simpa using ih.cons hab #align multiset.rel.add Multiset.Rel.add theorem rel_flip_eq {s t : Multiset α} : Rel (fun a b => b = a) s t ↔ s = t := show Rel (flip (· = ·)) s t ↔ s = t by rw [rel_flip, rel_eq, eq_comm] #align multiset.rel_flip_eq Multiset.rel_flip_eq @[simp] theorem rel_zero_left {b : Multiset β} : Rel r 0 b ↔ b = 0 := by rw [Rel_iff]; simp #align multiset.rel_zero_left Multiset.rel_zero_left @[simp] theorem rel_zero_right {a : Multiset α} : Rel r a 0 ↔ a = 0 := by rw [Rel_iff]; simp #align multiset.rel_zero_right Multiset.rel_zero_right theorem rel_cons_left {a as bs} : Rel r (a ::ₘ as) bs ↔ ∃ b bs', r a b ∧ Rel r as bs' ∧ bs = b ::ₘ bs' := by constructor · generalize hm : a ::ₘ as = m intro h induction h generalizing as case zero => simp at hm case cons a' b as' bs ha'b h ih => rcases cons_eq_cons.1 hm with (⟨eq₁, eq₂⟩ | ⟨_h, cs, eq₁, eq₂⟩) · subst eq₁ subst eq₂ exact ⟨b, bs, ha'b, h, rfl⟩ · rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩ exact ⟨b', b ::ₘ bs', h₁, eq₁.symm ▸ Rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ · exact fun ⟨b, bs', hab, h, Eq⟩ => Eq.symm ▸ Rel.cons hab h #align multiset.rel_cons_left Multiset.rel_cons_left theorem rel_cons_right {as b bs} : Rel r as (b ::ₘ bs) ↔ ∃ a as', r a b ∧ Rel r as' bs ∧ as = a ::ₘ as' := by rw [← rel_flip, rel_cons_left] refine' exists₂_congr fun a as' => _ rw [rel_flip, flip] #align multiset.rel_cons_right Multiset.rel_cons_right theorem rel_add_left {as₀ as₁} : ∀ {bs}, Rel r (as₀ + as₁) bs ↔ ∃ bs₀ bs₁, Rel r as₀ bs₀ ∧ Rel r as₁ bs₁ ∧ bs = bs₀ + bs₁ := @(Multiset.induction_on as₀ (by simp) fun a s ih bs ↦ by simp only [ih, cons_add, rel_cons_left] constructor · intro h rcases h with ⟨b, bs', hab, h, rfl⟩ rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩ exact ⟨b ::ₘ bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ · intro h rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩ rcases h with ⟨b, bs, hab, h₀, rfl⟩ exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩) #align multiset.rel_add_left Multiset.rel_add_left theorem rel_add_right {as bs₀ bs₁} : Rel r as (bs₀ + bs₁) ↔ ∃ as₀ as₁, Rel r as₀ bs₀ ∧ Rel r as₁ bs₁ ∧ as = as₀ + as₁ := by rw [← rel_flip, rel_add_left]; simp [rel_flip] #align multiset.rel_add_right Multiset.rel_add_right theorem rel_map_left {s : Multiset γ} {f : γ → α} : ∀ {t}, Rel r (s.map f) t ↔ Rel (fun a b => r (f a) b) s t := @(Multiset.induction_on s (by simp) (by simp (config := { contextual := true }) [rel_cons_left])) #align multiset.rel_map_left Multiset.rel_map_left theorem rel_map_right {s : Multiset α} {t : Multiset γ} {f : γ → β} : Rel r s (t.map f) ↔ Rel (fun a b => r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; rfl #align multiset.rel_map_right Multiset.rel_map_right theorem rel_map {s : Multiset α} {t : Multiset β} {f : α → γ} {g : β → δ} : Rel p (s.map f) (t.map g) ↔ Rel (fun a b => p (f a) (g b)) s t := rel_map_left.trans rel_map_right #align multiset.rel_map Multiset.rel_map theorem card_eq_card_of_rel {r : α → β → Prop} {s : Multiset α} {t : Multiset β} (h : Rel r s t) : card s = card t := by induction h <;> simp [*] #align multiset.card_eq_card_of_rel Multiset.card_eq_card_of_rel theorem exists_mem_of_rel_of_mem {r : α → β → Prop} {s : Multiset α} {t : Multiset β} (h : Rel r s t) : ∀ {a : α} (_ha : a ∈ s), ∃ b ∈ t, r a b := by induction' h with x y s t hxy _hst ih · simp · intro a ha cases' mem_cons.1 ha with ha ha · exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ · rcases ih ha with ⟨b, hbt, hab⟩ exact ⟨b, mem_cons.2 (Or.inr hbt), hab⟩ #align multiset.exists_mem_of_rel_of_mem Multiset.exists_mem_of_rel_of_mem theorem rel_of_forall {m1 m2 : Multiset α} {r : α → α → Prop} (h : ∀ a b, a ∈ m1 → b ∈ m2 → r a b) (hc : card m1 = card m2) : m1.Rel r m2 := by revert m1 refine' @(m2.induction_on _ _) · intro m _h hc rw [rel_zero_right, ← card_eq_zero, hc, card_zero] · intro a t ih m h hc rw [card_cons] at hc obtain ⟨b, hb⟩ := card_pos_iff_exists_mem.1 (show 0 < card m from hc.symm ▸ Nat.succ_pos _) obtain ⟨m', rfl⟩ := exists_cons_of_mem hb refine' rel_cons_right.mpr ⟨b, m', h _ _ hb (mem_cons_self _ _), ih _ _, rfl⟩ · exact fun _ _ ha hb => h _ _ (mem_cons_of_mem ha) (mem_cons_of_mem hb) · simpa using hc #align multiset.rel_of_forall Multiset.rel_of_forall theorem rel_replicate_left {m : Multiset α} {a : α} {r : α → α → Prop} {n : ℕ} : (replicate n a).Rel r m ↔ card m = n ∧ ∀ x, x ∈ m → r a x := ⟨fun h => ⟨(card_eq_card_of_rel h).symm.trans (card_replicate _ _), fun x hx => by obtain ⟨b, hb1, hb2⟩ := exists_mem_of_rel_of_mem (rel_flip.2 h) hx rwa [eq_of_mem_replicate hb1] at hb2⟩, fun h => rel_of_forall (fun x y hx hy => (eq_of_mem_replicate hx).symm ▸ h.2 _ hy) (Eq.trans (card_replicate _ _) h.1.symm)⟩ #align multiset.rel_replicate_left Multiset.rel_replicate_left theorem rel_replicate_right {m : Multiset α} {a : α} {r : α → α → Prop} {n : ℕ} : m.Rel r (replicate n a) ↔ card m = n ∧ ∀ x, x ∈ m → r x a := rel_flip.trans rel_replicate_left #align multiset.rel_replicate_right Multiset.rel_replicate_right protected nonrec -- Porting note: added theorem Rel.trans (r : α → α → Prop) [IsTrans α r] {s t u : Multiset α} (r1 : Rel r s t) (r2 : Rel r t u) : Rel r s u := by induction' t using Multiset.induction_on with x t ih generalizing s u · rw [rel_zero_right.mp r1, rel_zero_left.mp r2, rel_zero_left] · obtain ⟨a, as, ha1, ha2, rfl⟩ := rel_cons_right.mp r1 obtain ⟨b, bs, hb1, hb2, rfl⟩ := rel_cons_left.mp r2 exact Multiset.Rel.cons (_root_.trans ha1 hb1) (ih ha2 hb2) #align multiset.rel.trans Multiset.Rel.trans theorem Rel.countp_eq (r : α → α → Prop) [IsTrans α r] [IsSymm α r] {s t : Multiset α} (x : α) [DecidablePred (r x)] (h : Rel r s t) : countp (r x) s = countp (r x) t := by induction' s using Multiset.induction_on with y s ih generalizing t · rw [rel_zero_left.mp h] · obtain ⟨b, bs, hb1, hb2, rfl⟩ := rel_cons_left.mp h rw [countp_cons, countp_cons, ih hb2] simp only [decide_eq_true_eq, add_right_inj] refine' (if_congr ⟨fun h => _root_.trans h hb1, fun h => _root_.trans h (symm hb1)⟩ rfl rfl) #align multiset.rel.countp_eq Multiset.Rel.countp_eq end Rel section Map theorem map_eq_map {f : α → β} (hf : Function.Injective f) {s t : Multiset α} : s.map f = t.map f ↔ s = t := by rw [← rel_eq, ← rel_eq, rel_map] simp only [hf.eq_iff] #align multiset.map_eq_map Multiset.map_eq_map theorem map_injective {f : α → β} (hf : Function.Injective f) : Function.Injective (Multiset.map f) := fun _x _y => (map_eq_map hf).1 #align multiset.map_injective Multiset.map_injective end Map section Quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : Multiset α} (hst : s.Rel r t) : s.map (Quot.mk r) = t.map (Quot.mk r) := Rel.recOn hst rfl fun hab _hst ih => by simp [ih, Quot.sound hab] #align multiset.map_mk_eq_map_mk_of_rel Multiset.map_mk_eq_map_mk_of_rel theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : Multiset (Quot r)) : ∃ t : Multiset α, s = t.map (Quot.mk r) := Multiset.induction_on s ⟨0, rfl⟩ fun a _s ⟨t, ht⟩ => Quot.inductionOn a fun a => ht.symm ▸ ⟨a ::ₘ t, (map_cons _ _ _).symm⟩ #align multiset.exists_multiset_eq_map_quot_mk Multiset.exists_multiset_eq_map_quot_mk theorem induction_on_multiset_quot {r : α → α → Prop} {p : Multiset (Quot r) → Prop} (s : Multiset (Quot r)) : (∀ s : Multiset α, p (s.map (Quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with | _, ⟨_t, rfl⟩ => fun h => h _ #align multiset.induction_on_multiset_quot Multiset.induction_on_multiset_quot end Quot /-! ### Disjoint multisets -/ /-- `Disjoint s t` means that `s` and `t` have no elements in common. -/ def Disjoint (s t : Multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → False #align multiset.disjoint Multiset.Disjoint @[simp] theorem coe_disjoint (l₁ l₂ : List α) : @Disjoint α l₁ l₂ ↔ l₁.Disjoint l₂ := Iff.rfl #align multiset.coe_disjoint Multiset.coe_disjoint theorem Disjoint.symm {s t : Multiset α} (d : Disjoint s t) : Disjoint t s | _a, i₂, i₁ => d i₁ i₂ #align multiset.disjoint.symm Multiset.Disjoint.symm theorem disjoint_comm {s t : Multiset α} : Disjoint s t ↔ Disjoint t s := ⟨Disjoint.symm, Disjoint.symm⟩ #align multiset.disjoint_comm Multiset.disjoint_comm theorem disjoint_left {s t : Multiset α} : Disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := Iff.rfl #align multiset.disjoint_left Multiset.disjoint_left theorem disjoint_right {s t : Multiset α} : Disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm #align multiset.disjoint_right Multiset.disjoint_right theorem disjoint_iff_ne {s t : Multiset α} : Disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] #align multiset.disjoint_iff_ne Multiset.disjoint_iff_ne theorem disjoint_of_subset_left {s t u : Multiset α} (h : s ⊆ u) (d : Disjoint u t) : Disjoint s t | _x, m₁ => d (h m₁) #align multiset.disjoint_of_subset_left Multiset.disjoint_of_subset_left theorem disjoint_of_subset_right {s t u : Multiset α} (h : t ⊆ u) (d : Disjoint s u) : Disjoint s t | _x, m, m₁ => d m (h m₁) #align multiset.disjoint_of_subset_right Multiset.disjoint_of_subset_right theorem disjoint_of_le_left {s t u : Multiset α} (h : s ≤ u) : Disjoint u t → Disjoint s t := disjoint_of_subset_left (subset_of_le h) #align multiset.disjoint_of_le_left Multiset.disjoint_of_le_left theorem disjoint_of_le_right {s t u : Multiset α} (h : t ≤ u) : Disjoint s u → Disjoint s t := disjoint_of_subset_right (subset_of_le h) #align multiset.disjoint_of_le_right Multiset.disjoint_of_le_right @[simp] theorem zero_disjoint (l : Multiset α) : Disjoint 0 l | a => (not_mem_nil a).elim #align multiset.zero_disjoint Multiset.zero_disjoint @[simp] theorem singleton_disjoint {l : Multiset α} {a : α} : Disjoint {a} l ↔ a ∉ l := by simp [Disjoint] #align multiset.singleton_disjoint Multiset.singleton_disjoint @[simp] theorem disjoint_singleton {l : Multiset α} {a : α} : Disjoint l {a} ↔ a ∉ l := by rw [disjoint_comm, singleton_disjoint] #align multiset.disjoint_singleton Multiset.disjoint_singleton @[simp] theorem disjoint_add_left {s t u : Multiset α} : Disjoint (s + t) u ↔ Disjoint s u ∧ Disjoint t u := by simp [Disjoint, or_imp, forall_and] #align multiset.disjoint_add_left Multiset.disjoint_add_left @[simp] theorem disjoint_add_right {s t u : Multiset α} : Disjoint s (t + u) ↔ Disjoint s t ∧ Disjoint s u := by rw [disjoint_comm, disjoint_add_left]; tauto #align multiset.disjoint_add_right Multiset.disjoint_add_right @[simp] theorem disjoint_cons_left {a : α} {s t : Multiset α} : Disjoint (a ::ₘ s) t ↔ a ∉ t ∧ Disjoint s t := (@disjoint_add_left _ {a} s t).trans <| by rw [singleton_disjoint] #align multiset.disjoint_cons_left Multiset.disjoint_cons_left @[simp] theorem disjoint_cons_right {a : α} {s t : Multiset α} : Disjoint s (a ::ₘ t) ↔ a ∉ s ∧ Disjoint s t := by rw [disjoint_comm, disjoint_cons_left]; tauto #align multiset.disjoint_cons_right Multiset.disjoint_cons_right theorem inter_eq_zero_iff_disjoint [DecidableEq α] {s t : Multiset α} : s ∩ t = 0 ↔ Disjoint s t := by rw [← subset_zero]; simp [subset_iff, Disjoint] #align multiset.inter_eq_zero_iff_disjoint Multiset.inter_eq_zero_iff_disjoint @[simp] theorem disjoint_union_left [DecidableEq α] {s t u : Multiset α} : Disjoint (s ∪ t) u ↔ Disjoint s u ∧ Disjoint t u := by simp [Disjoint, or_imp, forall_and] #align multiset.disjoint_union_left Multiset.disjoint_union_left @[simp] theorem disjoint_union_right [DecidableEq α] {s t u : Multiset α} : Disjoint s (t ∪ u) ↔ Disjoint s t ∧ Disjoint s u := by simp [Disjoint, or_imp, forall_and] #align multiset.disjoint_union_right Multiset.disjoint_union_right theorem add_eq_union_iff_disjoint [DecidableEq α] {s t : Multiset α} : s + t = s ∪ t ↔ Disjoint s t := by simp_rw [← inter_eq_zero_iff_disjoint, ext, count_add, count_union, count_inter, count_zero, Nat.min_eq_zero_iff, Nat.add_eq_max_iff] #align multiset.add_eq_union_iff_disjoint Multiset.add_eq_union_iff_disjoint theorem disjoint_map_map {f : α → γ} {g : β → γ} {s : Multiset α} {t : Multiset β} : Disjoint (s.map f) (t.map g) ↔ ∀ a ∈ s, ∀ b ∈ t, f a ≠ g b := by simp [Disjoint, @eq_comm _ (f _) (g _)] #align multiset.disjoint_map_map Multiset.disjoint_map_map /-- `Pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def Pairwise (r : α → α → Prop) (m : Multiset α) : Prop := ∃ l : List α, m = l ∧ l.Pairwise r #align multiset.pairwise Multiset.Pairwise @[simp] theorem pairwise_nil (r : α → α → Prop) : Multiset.Pairwise r 0 := ⟨[], rfl, List.Pairwise.nil⟩ #align multiset.pairwise_nil Multiset.pairwise_nil theorem pairwise_coe_iff {r : α → α → Prop} {l : List α} : Multiset.Pairwise r l ↔ ∃ l' : List α, l ~ l' ∧ l'.Pairwise r := exists_congr <| by simp #align multiset.pairwise_coe_iff Multiset.pairwise_coe_iff theorem pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : Symmetric r) {l : List α} : Multiset.Pairwise r l ↔ l.Pairwise r := Iff.intro (fun ⟨_l', Eq, h⟩ => ((Quotient.exact Eq).pairwise_iff hr).2 h) fun h => ⟨l, rfl, h⟩ #align multiset.pairwise_coe_iff_pairwise Multiset.pairwise_coe_iff_pairwise theorem map_set_pairwise {f : α → β} {r : β → β → Prop} {m : Multiset α} (h : { a | a ∈ m }.Pairwise fun a₁ a₂ => r (f a₁) (f a₂)) : { b | b ∈ m.map f }.Pairwise r := fun b₁ h₁ b₂ h₂ hn => by obtain ⟨⟨a₁, H₁, rfl⟩, a₂, H₂, rfl⟩ := Multiset.mem_map.1 h₁, Multiset.mem_map.1 h₂ exact h H₁ H₂ (mt (congr_arg f) hn) #align multiset.map_set_pairwise Multiset.map_set_pairwise end Multiset namespace Multiset section Choose variable (p : α → Prop) [DecidablePred p] (l : Multiset α) /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `chooseX p l hp` returns that `a` together with proofs of `a ∈ l` and `p a`. -/ def chooseX : ∀ _hp : ∃! a, a ∈ l ∧ p a, { a // a ∈ l ∧ p a } := Quotient.recOn l (fun l' ex_unique => List.chooseX p l' (ExistsUnique.exists ex_unique)) (by intros a b _ funext hp suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y · apply all_equal · rintro ⟨x, px⟩ ⟨y, py⟩ rcases hp with ⟨z, ⟨_z_mem_l, _pz⟩, z_unique⟩ congr calc x = z := z_unique x px _ = y := (z_unique y py).symm ) #align multiset.choose_x Multiset.chooseX /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns that `a`. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := chooseX p l hp #align multiset.choose Multiset.choose theorem choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (chooseX p l hp).property #align multiset.choose_spec Multiset.choose_spec theorem choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 #align multiset.choose_mem Multiset.choose_mem theorem choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 #align multiset.choose_property Multiset.choose_property end Choose variable (α) set_option linter.deprecated false in /-- The equivalence between lists and multisets of a subsingleton type. -/ def subsingletonEquiv [Subsingleton α] : List α ≃ Multiset α where toFun := ofList invFun := (Quot.lift id) fun (a b : List α) (h : a ~ b) => (List.ext_nthLe h.length_eq) fun _ _ _ => Subsingleton.elim _ _ left_inv _ := rfl right_inv m := Quot.inductionOn m fun _ => rfl #align multiset.subsingleton_equiv Multiset.subsingletonEquiv variable {α} @[simp] theorem coe_subsingletonEquiv [Subsingleton α] : (subsingletonEquiv α : List α → Multiset α) = ofList := rfl #align multiset.coe_subsingleton_equiv Multiset.coe_subsingletonEquiv end Multiset
module Network.DefaultHttpEngine import Network.Wai import Control.ST import Network.ST.TcpSockets import Network.ST.IOUtils import Network.Socket.Data import Data.Bool.BoolTheorems import Data.String.StringUtils record DefaultHttpEngineState where constructor MkDefaultHttpEngineState enginePendingRequestVar : Var engineBufferedSocket : BufferedSocket DefaultHttpPendingRequest : Type DefaultHttpPendingRequest = State () %error_reduce defaultHttpEngineActions : {tcpSockets: TcpSockets m} -> DefaultHttpEngineState -> (ty : Type) -> List (Action ty) defaultHttpEngineActions {tcpSockets} st ty = [ioBuffer (engineBufferedSocket st) ::: State (IOBuffer $ ioSocket (engineBufferedSocket st)), ioSocket (engineBufferedSocket st) ::: CFSock tcpSockets] data DefaultHttpApplication : (m : Type -> Type) -> (tcpSockets: TcpSockets m) -> Type where MkDefaultHttpApplication : ((engineState : DefaultHttpEngineState) -> HttpRequest -> ST m () ((remove (enginePendingRequestVar engineState) DefaultHttpPendingRequest)::(defaultHttpEngineActions {tcpSockets} engineState ()))) -> DefaultHttpApplication m tcpSockets joinByCRLF : List String -> String joinByCRLF args = go "" args where go : String -> List String -> String go pfx [] = pfx go pfx (h::t) = go (pfx ++ h ++ "\n") t httpHeaderToString : HttpHeader -> String httpHeaderToString (MkHttpHeader n v) = n ++ ": " ++ v httpResponseToString : HttpResponse -> String httpResponseToString resp = joinByCRLF $ ("HTTP/1.1 " ++ (show . responseNumber . code $ resp) ++ " " ++ (show . responseText . code $ resp)):: ((map httpHeaderToString ((MkHttpHeader "Content-Length" (show . Strings.length . body $ resp)) :: (headers resp))) ++ ["", body resp]) defaultHttpEngineSendResponse : (m : Type -> Type) -> (tcpSockets: TcpSockets m) -> (engineState: DefaultHttpEngineState) -> HttpResponse -> ST m () ((remove (enginePendingRequestVar engineState) DefaultHttpPendingRequest):: (defaultHttpEngineActions {m} {tcpSockets} engineState ())) defaultHttpEngineSendResponse m tcpSockets st resp = with ST do delete (enginePendingRequestVar st) True <- call $ fromCFSock tcpSockets (ioSocket (engineBufferedSocket st)) | False => with ST do call $ toCFSock tcpSockets Failed Refl (ioSocket (engineBufferedSocket st)) pure () True <- call $ writeSocketFully {m} {tcpSocketInstance = tcpSockets} (httpResponseToString resp) (ioSocket (engineBufferedSocket st)) | False => with ST do call $ toCFSock tcpSockets Failed Refl (ioSocket (engineBufferedSocket st)) pure () call $ toCFSock tcpSockets Connected Refl (ioSocket (engineBufferedSocket st)) defaultHttpEngineRunApplication : {m : Type -> Type} -> {tcpSockets: TcpSockets m} -> (bindTo: Maybe SocketAddress) -> (port: Int) -> (app: DefaultHttpApplication m tcpSockets) -> ST m String [] defaultHttpEngineRunApplication {m} {tcpSockets} bindTo port app = do Right listenerSocket <- socket tcpSockets | Left code => pure ("Can't create listener socket on address " ++ (show bindTo) ++ ", error code: " ++ (show code)) True <- bind tcpSockets bindTo port listenerSocket | False => do close tcpSockets listenerSocket pure "Can't bind listener to port" True <- listen tcpSockets listenerSocket | False => do close tcpSockets listenerSocket pure "Can't listen on listener socket" err <- applicationAcceptLoop listenerSocket close tcpSockets listenerSocket pure err where rtrim : String -> String rtrim = reverse . ltrim . reverse readHTTPHeaders : (sock : BufferedSocket) -> List HttpHeader -> ST m (Maybe (InvalidRequestOr (List HttpHeader))) (maybeBufferedSocketFails {tcpSocketInstance = tcpSockets} {ty = (InvalidRequestOr (List HttpHeader))} sock) readHTTPHeaders sock otherHeaders = do Just line <- readLineFromSocket sock | Nothing => pure Nothing if rtrim line == "" then pure $ Just $ ValidRequest otherHeaders else do let (headerNameUntrimmed, headerValueWithPfx) = break (==':') line ifWithProofs (headerValueWithPfx == "") (\_ => pure $ Just $ InvalidRequest) (\prfNonEmpty => do let headerName = rtrim headerNameUntrimmed let headerValue = trim (strTail' headerValueWithPfx prfNonEmpty) readHTTPHeaders sock (MkHttpHeader headerName headerValue :: otherHeaders) ) readHTTPHead : (sock : BufferedSocket) -> ST m (Maybe (InvalidRequestOr HttpRequest)) (maybeBufferedSocketFails {tcpSocketInstance = tcpSockets} {ty = (InvalidRequestOr HttpRequest)} sock) readHTTPHead sock = with ST do Just result <- readLineFromSocket sock | Nothing => pure Nothing let (method, afterMethod) = break (==' ') (trim result) let (path, versionAndSpace) = break (==' ') (ltrim afterMethod) let version = ltrim versionAndSpace Just (ValidRequest httpHeaders) <- readHTTPHeaders sock [] | Nothing => pure Nothing | Just InvalidRequest => pure (Just InvalidRequest) -- TODO: HTTP/2 if (version == "HTTP/1.1" || version == "HTTP/1.0") then pure $ Just $ ValidRequest $ MkHttpRequest method httpHeaders "" else pure (Just InvalidRequest) withContentLength : HttpRequest -> Maybe Nat withContentLength req = do contentLengthStr <- getHttpHeader "Content-Length" req cast (headerValue contentLengthStr) readHTTPBody : (sock : BufferedSocket) -> (req : HttpRequest) -> ST m (Maybe String) (maybeBufferedSocketFails {tcpSocketInstance = tcpSockets} {ty = String} sock) readHTTPBody sock req = case withContentLength req of Nothing => pure $ Just "" Just contentLength => readFullyFromSocket {tcpSocketInstance = tcpSockets} contentLength sock e400Content : String e400Content = "Your browser sent a request the server couldn't understand." e400Msg : String e400Msg = "HTTP/1.1 400 Bad Request\r\nContent-Length: " ++ (show . length $ e400Content) ++ "\r\n\r\n" ++ e400Content send400 : (sock : BufferedSocket) -> ST m (Maybe ()) (maybeBufferedSocketFails {tcpSocketInstance = tcpSockets} {ty = ()} sock) send400 sock = do True <- call (writeSocketFully {m} {tcpSocketInstance = tcpSockets} e400Msg (ioSocket sock)) | False => pure Nothing pure $ Just () runAppCall : (sock : BufferedSocket) -> HttpRequest -> DefaultHttpApplication m tcpSockets -> ST m (Maybe ()) (maybeBufferedSocketFails {tcpSocketInstance = tcpSockets} {ty = ()} sock) runAppCall sock req (MkDefaultHttpApplication appFn) = with ST do call $ toCFSock tcpSockets Connected Refl (ioSocket sock) pendingRequest <- new () let engineState : DefaultHttpEngineState = MkDefaultHttpEngineState pendingRequest sock appFn engineState req let engineBufferedSocketPrf : (engineBufferedSocket engineState = sock) = Refl doFromCFSock where doFromCFSock : ST m (Maybe ()) [ (ioBuffer sock) ::: State (IOBuffer (ioSocket sock)) , ioSocket sock ::: (CFSock tcpSockets) :-> wrappedMaybeCaseOnly (Sock tcpSockets) Failed Connected ] doFromCFSock = with ST do True <- call $ fromCFSock tcpSockets (ioSocket sock) | False => pure Nothing pure (Just ()) incomingConnectionLoop : (sourceAddr : SocketAddress) -> (rawSock : Var) -> ST m () [remove rawSock (Sock tcpSockets Connected)] incomingConnectionLoop sourceAddr rawSock = do (sock ** prfSockEquiv) <- initBufferedSocket rawSock (rewrite prfSockEquiv in go sock) closeBufferedSocket sock where go : (sock : BufferedSocket) -> ST m (Maybe ()) (maybeBufferedSocketFails {tcpSocketInstance = tcpSockets} {ty = ()} sock) go sock = with ST do -- TODO: Consider some kind of timeout on incoming connections Just (ValidRequest headers) <- readHTTPHead sock | Nothing => pure Nothing | Just InvalidRequest => send400 sock Just body <- readHTTPBody sock headers | Nothing => pure Nothing let req = record { body = body } headers Just _ <- runAppCall sock req app | Nothing => pure Nothing go sock applicationAcceptLoop : (listener: Var) -> ST m String [listener ::: Sock tcpSockets Listening :-> Sock tcpSockets Failed] applicationAcceptLoop listener = do -- TODO: Consider some kind of limit on the number of open connections to -- avoid a DoS Just _ <- accept tcpSockets listener incomingConnectionLoop | Nothing => pure "Failed to accept" applicationAcceptLoop listener export defaultHttpEngine : (m : Type -> Type) -> (tcpSockets : TcpSockets m) -> HttpEngine m defaultHttpEngine m tcpSockets = MkHttpEngine {- Application -} (DefaultHttpApplication m tcpSockets) {- EngineState -} DefaultHttpEngineState {- httpEngineActions -} defaultHttpEngineActions {- pendingRequestVar -} enginePendingRequestVar {- PendingRequest -} DefaultHttpPendingRequest {- sendResponse -} (defaultHttpEngineSendResponse m tcpSockets) {- mkApplication -} MkDefaultHttpApplication {- runApplication -} (defaultHttpEngineRunApplication {m} {tcpSockets})
-- ---------------------------------------------------------- [ Predicates.idr ] -- Module : Predicates.idr -- Copyright : (c) Jan de Muijnck-Hughes -- License : see LICENSE -- --------------------------------------------------------------------- [ EOH ] ||| More Quantifiers for Lists, but keeping them out of the prelude so ||| need a new module name. module Data.List.Predicates import public Data.List import public Data.List.Predicates.Unique import public Data.List.Predicates.Interleaving import public Data.List.Predicates.Pairs import public Data.List.Predicates.Thinning %default total %access public export -- --------------------------------------------------------------------- [ EOF ]
function M = unroll_dbn_topology(intra, inter, T, intra1) % UNROLL_DBN_TOPOLOGY Make the block diagonal adjacency matrix for a DBN consisting of T slices % M = unroll_dbn_topology(intra, inter, T, intra1) % % intra is the connectivity within a slice, inter between two slices. % M will have intra along the diagonal, and inter one above the diagonal. % intra1 is an optional argumnet, in case the intra is different for the first slice. if nargin < 4, intra1 = intra; end ss = length(intra); % slice size M = sparse(ss*T, ss*T); b = 1:ss; M(b,b) = intra1; M(b,b+ss) = inter; for t=2:T-1 b = (1:ss) + (t-1)*ss; M(b,b) = intra; M(b,b+ss) = inter; end t = T; b = (1:ss) + (t-1)*ss; M(b,b) = intra;
import .basic import combinatorics.pigeonhole namespace simple_graph open finset universes u v w variables {V : Type u} open_locale classical structure edge_coloring (G : simple_graph V) (α : Type w):= (f : sym2 V → α) -- first we want to prove that K_3 is subgraph of K_6 def complete_le_subgraph_complete (n k : ℕ) (h : k ≤ n) : (complete_graph (fin k)) ↪g (complete_graph (fin n)) := { to_fun := sorry, inj' := sorry, map_rel_iff' := sorry } variables (α : Type w) (colors : edge_coloring (⊤ : simple_graph (fin 6)) (fin 2)) -- grab arbitrary vertex and use pigeonhole to say it has at least 3 red or 3 blue edges lemma edge_red_or_blue (v : fin 6) : ∃ y : (fin 2), 3 ≤ (((⊤ : simple_graph (fin 6)).incidence_finset v).filter $ λ e, colors.f e = y).card := begin sorry, end end simple_graph
module plfa.working.Induction where import Relation.Binary.PropositionalEquality as Eq open Eq using (_≡_; refl; cong; sym) open Eq.≡-Reasoning using (begin_; _≡⟨⟩_; step-≡; _∎) open import Data.Nat using (ℕ; zero; suc; _+_; _*_; _∸_) +-assoc : ∀ (m n p : ℕ) → (m + n) + p ≡ m + (n + p) +-assoc zero n p = begin (zero + n) + p ≡⟨⟩ n + p ≡⟨⟩ zero + (n + p) ∎ +-assoc (suc m) n p = begin (suc m + n) + p ≡⟨⟩ suc (m + n) + p ≡⟨⟩ suc ((m + n) + p) ≡⟨ cong suc (+-assoc m n p) ⟩ suc (m + (n + p)) ≡⟨⟩ suc m + (n + p) ∎ +-identity : ∀ (m : ℕ) → m + zero ≡ m +-identity zero = begin zero + zero ≡⟨⟩ zero ∎ +-identity (suc m) = begin (suc m) + zero ≡⟨⟩ suc (m + zero) ≡⟨ cong suc (+-identity m) ⟩ suc m ∎ +-suc : ∀ (m n : ℕ) → m + suc n ≡ suc (m + n) +-suc zero n = begin zero + suc n ≡⟨⟩ suc n ≡⟨⟩ suc (zero + n) ∎ +-suc (suc m) n = begin suc m + suc n ≡⟨⟩ (suc m) + suc n ≡⟨ cong suc (+-suc m n) ⟩ suc (suc m + n) ∎ +-comm : ∀ (m n : ℕ) → m + n ≡ n + m +-comm m zero = begin m + zero ≡⟨ +-identity m ⟩ m ≡⟨⟩ zero + m ∎ +-comm m (suc n) = begin m + suc n ≡⟨ +-suc m n ⟩ suc (m + n) ≡⟨ cong suc (+-comm m n) ⟩ suc (n + m) ≡⟨⟩ suc n + m ∎
State Before: R : Type u inst✝¹ : CommSemiring R S : Type v inst✝ : CommSemiring S f g : R[X] h : Separable (f * g) ⊢ IsCoprime f g State After: R : Type u inst✝¹ : CommSemiring R S : Type v inst✝ : CommSemiring S f g : R[X] h : Separable (f * g) this : IsCoprime f (↑derivative (f * g)) ⊢ IsCoprime f g Tactic: have := h.of_mul_left_left State Before: R : Type u inst✝¹ : CommSemiring R S : Type v inst✝ : CommSemiring S f g : R[X] h : Separable (f * g) this : IsCoprime f (↑derivative (f * g)) ⊢ IsCoprime f g State After: R : Type u inst✝¹ : CommSemiring R S : Type v inst✝ : CommSemiring S f g : R[X] h : Separable (f * g) this : IsCoprime f (↑derivative f * g + f * ↑derivative g) ⊢ IsCoprime f g Tactic: rw [derivative_mul] at this State Before: R : Type u inst✝¹ : CommSemiring R S : Type v inst✝ : CommSemiring S f g : R[X] h : Separable (f * g) this : IsCoprime f (↑derivative f * g + f * ↑derivative g) ⊢ IsCoprime f g State After: no goals Tactic: exact IsCoprime.of_mul_right_right (IsCoprime.of_add_mul_left_right this)
The interval $[0,1]$ is the union of the intervals $[0,1/2]$ and $[1/2,1]$.
The interval $[0,1]$ is the union of the intervals $[0,1/2]$ and $[1/2,1]$.
[STATEMENT] lemma nest_mono[mono_set]: "x \<subseteq> y \<Longrightarrow> (a,b) \<in> nest r x \<longrightarrow> (a,b) \<in> nest r y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<subseteq> y \<Longrightarrow> (a, b) \<in> nest r x \<longrightarrow> (a, b) \<in> nest r y [PROOF STEP] using mono_nest[unfolded mono_def, rule_format, of x y r] [PROOF STATE] proof (prove) using this: x \<subseteq> y \<Longrightarrow> nest r x \<subseteq> nest r y goal (1 subgoal): 1. x \<subseteq> y \<Longrightarrow> (a, b) \<in> nest r x \<longrightarrow> (a, b) \<in> nest r y [PROOF STEP] by blast
(** * Opposite natural transformations *) Require Category.Dual Functor.Dual. Import Category.Dual.CategoryDualNotations Functor.Dual.FunctorDualNotations. Require Import Category.Core Functor.Core NaturalTransformation.Core. Set Universe Polymorphism. Set Implicit Arguments. Generalizable All Variables. Set Asymmetric Patterns. Local Open Scope category_scope. (** ** Definition of [Tᵒᵖ] *) Definition opposite C D (F G : Functor C D) (T : NaturalTransformation F G) : NaturalTransformation G^op F^op := Build_NaturalTransformation' (G^op) (F^op) (components_of T) (fun s d => commutes_sym T d s) (fun s d => commutes T d s). Local Notation "T ^op" := (opposite T) : natural_transformation_scope. (** ** [ᵒᵖ] is judgmentally involutive *) Local Open Scope natural_transformation_scope. Definition opposite_involutive C D (F G : Functor C D) (T : NaturalTransformation F G) : (T^op)^op = T := idpath. Module Export NaturalTransformationDualNotations. Notation "T ^op" := (opposite T) : natural_transformation_scope. End NaturalTransformationDualNotations.
[STATEMENT] lemma no_Private_override: "\<lbrakk>G\<turnstile>new overrides old\<rbrakk> \<Longrightarrow> accmodi old \<noteq> Private" [PROOF STATE] proof (prove) goal (1 subgoal): 1. G \<turnstile> new overrides old \<Longrightarrow> accmodi old \<noteq> Private [PROOF STEP] by (induct set: overridesR) (auto simp add: inheritable_in_def)
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import set_theory.cardinal /-! # Denumerability of ℚ This file proves that ℚ is infinite, denumerable, and deduces that it has cardinality `omega`. -/ namespace rat open denumerable instance : infinite ℚ := infinite.of_injective (coe : ℕ → ℚ) nat.cast_injective private def denumerable_aux : ℚ ≃ { x : ℤ × ℕ // 0 < x.2 ∧ x.1.nat_abs.coprime x.2 } := { to_fun := λ x, ⟨⟨x.1, x.2⟩, x.3, x.4⟩, inv_fun := λ x, ⟨x.1.1, x.1.2, x.2.1, x.2.2⟩, left_inv := λ ⟨_, _, _, _⟩, rfl, right_inv := λ ⟨⟨_, _⟩, _, _⟩, rfl } /-- **Denumerability of the Rational Numbers** -/ instance : denumerable ℚ := begin let T := { x : ℤ × ℕ // 0 < x.2 ∧ x.1.nat_abs.coprime x.2 }, letI : infinite T := infinite.of_injective _ denumerable_aux.injective, letI : encodable T := encodable.subtype, letI : denumerable T := of_encodable_of_infinite T, exact denumerable.of_equiv T denumerable_aux end end rat namespace cardinal open_locale cardinal @[simp] lemma mk_rat : #ℚ = ω := mk_denumerable ℚ end cardinal
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.nat.parity import order.filter.at_top_bot /-! # Numbers are frequently modeq to fixed numbers In this file we prove that `m ≡ d [MOD n]` frequently as `m → ∞`. -/ open filter namespace nat /-- Infinitely many natural numbers are equal to `d` mod `n`. -/ lemma frequently_modeq {n : ℕ} (h : n ≠ 0) (d : ℕ) : ∃ᶠ m in at_top, m ≡ d [MOD n] := ((tendsto_add_at_top_nat d).comp (tendsto_id.nsmul_at_top h.bot_lt)).frequently $ frequently_of_forall $ λ m, by { simp [nat.modeq_iff_dvd, ← sub_sub] } lemma frequently_mod_eq {d n : ℕ} (h : d < n) : ∃ᶠ m in at_top, m % n = d := by simpa only [nat.modeq, mod_eq_of_lt h] using frequently_modeq h.ne_bot d lemma frequently_even : ∃ᶠ m : ℕ in at_top, even m := by simpa only [even_iff] using frequently_mod_eq zero_lt_two lemma frequently_odd : ∃ᶠ m : ℕ in at_top, odd m := by simpa only [odd_iff] using frequently_mod_eq one_lt_two end nat
(* Property from Case-Analysis for Rippling and Inductive Proof, Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010. This Isabelle theory is produced using the TIP tool offered at the following website: https://github.com/tip-org/tools This file was originally provided as part of TIP benchmark at the following website: https://github.com/tip-org/benchmarks Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly to make it compatible with Isabelle2017.*) theory TIP_prop_15 imports "../../Test_Base" begin datatype 'a list = nil2 | cons2 "'a" "'a list" datatype Nat = Z | S "Nat" fun len :: "'a list => Nat" where "len (nil2) = Z" | "len (cons2 y xs) = S (len xs)" fun t2 :: "Nat => Nat => bool" where "t2 x (Z) = False" | "t2 (Z) (S z) = True" | "t2 (S x2) (S z) = t2 x2 z" fun ins :: "Nat => Nat list => Nat list" where "ins x (nil2) = cons2 x (nil2)" | "ins x (cons2 z xs) = (if t2 x z then cons2 x (cons2 z xs) else cons2 z (ins x xs))" theorem property0 : "((len (ins x xs)) = (S (len xs)))" oops end
-- Case-typed argument is defined in `TTImp` as an intermediate function applied to *all* previous arguments -- (disregarding whether there exists an actual dependency of not). -- The follolwing check ensures that those types being applied to different count of arguments mean the same type. x : {a : Type} -> (xs : List a) -> (v : List a) -> (0 _ : case v of [] => Unit; (x::xs) => Void) -> Nat y : {a : Type} -> (v : List a) -> (0 _ : case v of [] => Unit; (x::xs) => Void) -> Nat xy : {a : Type} -> (xs : List a) -> (v : List a) -> (0 c : case v of [] => Unit; (x::xs) => Void) -> x {a} xs v c = y {a} v c
variables A B C D : Prop example : A ∧ (A → B) → B := assume h: A ∧ (A -> B), show B, from (and.right h) (and.left h) example : A → ¬(¬A ∧ B) := assume h1: A, assume h2: ¬A ∧B, show false, from (and.left h2) h1 example : ¬(A ∧ B) → (A → ¬B) := assume h: ¬ (A ∧ B), assume h₁ : A, assume h₂ : B, show false, from h (and.intro h₁ h₂) example (h₁ : A ∨ B) (h₂ : A → C) (h₃ : B → D) : C ∨ D := /- lots of haves/shows -/ show C ∨ D, from or.elim h₁ (assume optionOne: A, show C ∨ D, from or.inl(h₂ optionOne) ) (assume optionTwo: B, show C ∨ D, from or.inr (h₃ optionTwo) ) example (h : ¬A ∧ ¬B) : ¬(A ∨ B) := /-demorgan's Law-/ assume h2 : A∨B, show false, from or.elim h2 (assume optionOne: A, show false, from (and.left h) optionOne) (assume optionTwo: B, show false, from (and.right h) optionTwo) example : ¬(A ↔ ¬A) := assume h: A ↔ ¬A, show false, from (assume h1: A,((iff.mp h h1)h1))(iff.mpr h (assume h1: A, ((iff.mp h h1)h1)))
[STATEMENT] lemma isContD: "isCont f x \<Longrightarrow> f \<midarrow>x\<rightarrow> f x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. isCont f x \<Longrightarrow> f \<midarrow>x\<rightarrow> f x [PROOF STEP] by (simp add: isCont_def)
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.finsupp.basic /-! # The pointwise product on `finsupp`. For the convolution product on `finsupp` when the domain has a binary operation, see the type synonyms `add_monoid_algebra` (which is in turn used to define `polynomial` and `mv_polynomial`) and `monoid_algebra`. -/ noncomputable theory open finset universes u₁ u₂ u₃ u₄ u₅ variables {α : Type u₁} {β : Type u₂} {γ : Type u₃} {δ : Type u₄} {ι : Type u₅} namespace finsupp /-! ### Declarations about the pointwise product on `finsupp`s -/ section variables [mul_zero_class β] /-- The product of `f g : α →₀ β` is the finitely supported function whose value at `a` is `f a * g a`. -/ instance : has_mul (α →₀ β) := ⟨zip_with (*) (mul_zero 0)⟩ lemma coe_mul (g₁ g₂ : α →₀ β) : ⇑(g₁ * g₂) = g₁ * g₂ := rfl @[simp] lemma mul_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ * g₂) a = g₁ a * g₂ a := rfl lemma support_mul [decidable_eq α] {g₁ g₂ : α →₀ β} : (g₁ * g₂).support ⊆ g₁.support ∩ g₂.support := begin intros a h, simp only [mul_apply, mem_support_iff] at h, simp only [mem_support_iff, mem_inter, ne.def], rw ←not_or_distrib, intro w, apply h, cases w; { rw w, simp }, end instance : mul_zero_class (α →₀ β) := finsupp.coe_fn_injective.mul_zero_class _ coe_zero coe_mul end instance [semigroup_with_zero β] : semigroup_with_zero (α →₀ β) := finsupp.coe_fn_injective.semigroup_with_zero _ coe_zero coe_mul instance [non_unital_non_assoc_semiring β] : non_unital_non_assoc_semiring (α →₀ β) := finsupp.coe_fn_injective.non_unital_non_assoc_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_semiring β] : non_unital_semiring (α →₀ β) := finsupp.coe_fn_injective.non_unital_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_comm_semiring β] : non_unital_comm_semiring (α →₀ β) := finsupp.coe_fn_injective.non_unital_comm_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_non_assoc_ring β] : non_unital_non_assoc_ring (α →₀ β) := finsupp.coe_fn_injective.non_unital_non_assoc_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [non_unital_ring β] : non_unital_ring (α →₀ β) := finsupp.coe_fn_injective.non_unital_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [non_unital_comm_ring β] : non_unital_comm_ring (α →₀ β) := finsupp.coe_fn_injective.non_unital_comm_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) -- TODO can this be generalized in the direction of `pi.has_scalar'` -- (i.e. dependent functions and finsupps) -- TODO in theory this could be generalised, we only really need `smul_zero` for the definition instance pointwise_scalar [semiring β] : has_scalar (α → β) (α →₀ β) := { smul := λ f g, finsupp.of_support_finite (λ a, f a • g a) begin apply set.finite.subset g.finite_support, simp only [function.support_subset_iff, finsupp.mem_support_iff, ne.def, finsupp.fun_support_eq, finset.mem_coe], intros x hx h, apply hx, rw [h, smul_zero], end } @[simp] lemma coe_pointwise_smul [semiring β] (f : α → β) (g : α →₀ β) : ⇑(f • g) = f • g := rfl /-- The pointwise multiplicative action of functions on finitely supported functions -/ instance pointwise_module [semiring β] : module (α → β) (α →₀ β) := function.injective.module _ coe_fn_add_hom coe_fn_injective coe_pointwise_smul end finsupp
[GOAL] B : Type u inst✝ : Bicategory B a b c d e : B f g h : a ⟶ b η : f ⟶ g θ : g ⟶ h ⊢ η ⊗≫ θ = η ≫ θ [PROOFSTEP] dsimp [bicategoricalComp] [GOAL] B : Type u inst✝ : Bicategory B a b c d e : B f g h : a ⟶ b η : f ⟶ g θ : g ⟶ h ⊢ η ≫ 𝟙 g ≫ θ = η ≫ θ [PROOFSTEP] simp
State Before: R : Type u_1 inst✝¹ : Ring R S : Submonoid R inst✝ : OreSet S hS : S ≤ R⁰ r₁ r₂ : R h : ↑numeratorHom r₁ = ↑numeratorHom r₂ ⊢ r₁ = r₂ State After: R : Type u_1 inst✝¹ : Ring R S : Submonoid R inst✝ : OreSet S hS : S ≤ R⁰ r₁ r₂ : R h : ∃ u v, r₂ * ↑u = r₁ * v ∧ ↑1 * ↑u = ↑1 * v ⊢ r₁ = r₂ Tactic: rw [numeratorHom_apply, numeratorHom_apply, oreDiv_eq_iff] at h State Before: R : Type u_1 inst✝¹ : Ring R S : Submonoid R inst✝ : OreSet S hS : S ≤ R⁰ r₁ r₂ : R h : ∃ u v, r₂ * ↑u = r₁ * v ∧ ↑1 * ↑u = ↑1 * v ⊢ r₁ = r₂ State After: case intro.intro.intro R : Type u_1 inst✝¹ : Ring R S : Submonoid R inst✝ : OreSet S hS : S ≤ R⁰ r₁ r₂ : R u : { x // x ∈ S } v : R h₁ : r₂ * ↑u = r₁ * v h₂ : ↑1 * ↑u = ↑1 * v ⊢ r₁ = r₂ Tactic: rcases h with ⟨u, v, h₁, h₂⟩ State Before: case intro.intro.intro R : Type u_1 inst✝¹ : Ring R S : Submonoid R inst✝ : OreSet S hS : S ≤ R⁰ r₁ r₂ : R u : { x // x ∈ S } v : R h₁ : r₂ * ↑u = r₁ * v h₂ : ↑1 * ↑u = ↑1 * v ⊢ r₁ = r₂ State After: case intro.intro.intro R : Type u_1 inst✝¹ : Ring R S : Submonoid R inst✝ : OreSet S hS : S ≤ R⁰ r₁ r₂ : R u : { x // x ∈ S } v : R h₁ : r₂ * ↑u = r₁ * v h₂ : ↑u = v ⊢ r₁ = r₂ Tactic: simp only [S.coe_one, one_mul] at h₂ State Before: case intro.intro.intro R : Type u_1 inst✝¹ : Ring R S : Submonoid R inst✝ : OreSet S hS : S ≤ R⁰ r₁ r₂ : R u : { x // x ∈ S } v : R h₁ : r₂ * ↑u = r₁ * v h₂ : ↑u = v ⊢ r₁ = r₂ State After: no goals Tactic: rwa [← h₂, mul_cancel_right_mem_nonZeroDivisors (hS (SetLike.coe_mem u)), eq_comm] at h₁
#pragma once #include "macros.h" #include <gsl/span> #include <array> #include <optional> #include <string> namespace linkollector::win { enum class activity { url, text }; constexpr std::string_view activity_delimiter = "\uedfd"; constexpr std::array<std::byte, activity_delimiter.size()> activity_delimiter_bin = []() { std::array<std::byte, activity_delimiter.size()> delim = {}; for (std::size_t i = 0; i < activity_delimiter.size(); ++i) { delim.at(i) = static_cast<std::byte>(activity_delimiter[i]); } return delim; }(); [[nodiscard]] std::string activity_to_string(activity activity_) noexcept; [[nodiscard]] std::wstring activity_to_wstring(activity activity_) noexcept; [[nodiscard]] std::optional<activity> activity_from_string(std::string_view activity_) noexcept; std::optional<std::pair<activity, std::string>> deserialize(gsl::span<std::byte> msg) noexcept; } // namespace linkollector::win
\documentclass[12pt]{report} \usepackage[utf8]{inputenc} \usepackage{amsmath,mathtools} \usepackage{tcolorbox} \newcommand{\mbf}[1]{\mathbf{#1}} \newcommand{\tbf}[1]{\textbf{#1}} \newcommand{\dsum}[3]{$\sum^{#1}_{#2}{#3}$} \newcommand{\dint}[3]{$\int^{#1}_{#2}{#3}$} \newcommand{\tit}[1]{\textit{#1}} \newcommand{\fn}[1]{\footnote{#1}} \newcommand{\de}[2]{\frac{d{#1}}{d{#2}}} \newcommand{\ch}[2]{\Gamma^{#1}_{#2}} \newcommand{\f}[1]{${#1}$} \newcommand{\chris}{\ch{\mu}{\alpha \beta}=\frac{1}{2}g^{\mu \lambda}(\p_{\alpha} g_{\beta \lambda}+\p_\beta g_{\alpha \lambda} - \p_\lambda g_{\alpha \beta})} \newcommand{\p}{\partial} \newcommand{\pe}[2]{\frac{\partial{#1}}{\partial{#2}}} \newcommand{\n}{\nonumber} \newcommand{\bra}[1]{\ensuremath{\left\langle#1\right|}} \newcommand{\ket}[1]{\ensuremath{\left|#1\right\rangle}} \newcommand{\cbox}{tcolorbox} \newcommand{\cc}[1]{\left({#1}\right)} \newcommand{\rr}[1]{\left[{#1}\right]} \begin{document} \title{Cosmology} \author{Divesh Jain} \maketitle \newpage \tableofcontents \newpage \chapter{Prequel} The most k \chapter{Introduction} This is a document which tells the history of 13.8 billion years ago. At early times, the universe was hot an dense. Matter was in form of free electrons and atomic nuclei and light bounced between them. As primordial plasma cooled, light elements like Hyrdogen, Helium and Lithium formed. At some point ,the energy had dropped enough for the first stable atoms to exist and this was when photons started to stream freely. After 13.8 billion years later, we see this afterglow of the Bigbang as Microwave radiation. This radiation is almost uniform throughout and has a temperature of $T=2.73K$ in all directions, there are small fluctuations of order $\sim10^{-4}$, making parts of sky slightly hotter and other parts slightly colder. What does this fluctuation in CMB represent? It represents tiny variations in primordial density of matter \footnote{what is this primordial density composed off(free electrons and radiation?)?}. Overtime and under influence of gravity, these fluctuations grew. Dense regions grew to form stars, galaxies and planets.(insert picture 1) Today majority of universe is composed of Dark matter(required to explain stability of galaxies and rate of formation of large scale structures) and Dark Energy(required to rationalise that expansion of universe started recently). It has been evident that the primordial density fluctuation were of quantum origin and streched to microscopic size during a peiod of inflationary expansion. Modern cosmology is based on Einstein's GR, according to which the space-time structure of the universe is determined by the matter distribution within it. This perspective on space-time is very different from that in classical physics, where space-time is considered eternal absolute. The maths of GR is so simplified for cosmology because of two cosmological principles are followed: Homogeneity and Isotropy \fn{Although on relatively small scales the present day universe deviates strongly from homogeneity and isotropy, which we will later see that the cause of these structures arise from small perturbations.} \begin{\cbox} Although, homogeneity and isotropy are well accepted theory, but \textbf{because Einstein's equations are non linear, the following subtlety must be stressed : there is no guarantee that the solution for a distribution of a source which was averaged over some region will be the same as that we obtain by first solving the Einstein's equations exactly and then averaging the solutions. In fact, it is possible to construct counterexamples in which the operations of averaging and solving do not commute.} \end{\cbox} Note: In this text natural units for $c,\bar{h}=1$ is used. Length and Time are treated in same units. Metric signature used here is $(+---)$. Space-Time four vectors would be denoted by capital letters. \chapter{Geometry and Dynamics} \textbf{For now, This section is left for future as a written note for the same is already worked out.Only some new points would add which is understood in a better form.} \begin{\cbox} The assumption of homogeneity and isotropy of the 3-space is true only for preferred class of observers. Another observer moving with a uniform velocity with respect to these fundamental class of observers will find the universe anisotropic \end{\cbox} In special relativity the metric is same everywhere in space and time i.e. $g_{\mu\nu}=diag(1,-1,-1,-1)$ but in G.R. this metric is dependent on space and time i.e. $g_{\mu\nu}(t,\mbf{x})$ which basically incorporates the effects of gravity. During expansion of universe, the comoving distance between points on suppose an imaginary grid remains constant even though the universe expands and the physical distance is $d_{phy}=a(t)d_{comoving}$. Expansion through scale factor is something that influences physical distances but has nothing to do with time. In order to define a metric which is influenced by the scale factor as a whole, we define \tit{conformal time} which is defined as $d\tau=\frac{dt}{a(t)}$ which helps us to define a static Minkowski metric multiplied by a time dependent conformal factor $a(\tau)$. since light travels on null geodesics $ds^2=0$, propagation of light in FRW metric is same as in the minkowski metric if we transform to conformal time. Along the path, as factorising scale factor leads to equal footing to both space and time, therefore $\nabla\tau=\nabla\chi$ \section{Kinematics} \subsection{Geodesics} What is a Geodesic and why is it important?\\ Ans: Geodesics are path followed by free falling particles in curved space-time in absence of gravity. Mathematicaly, it is the path that extremises the proper time, $\Delta s/c$ between two points in spacetime.\fn{enter the proof for geodesic equation path}. $\de{U^\mu}{s}+\ch{\mu}{\alpha\beta}U^{\alpha}U^{\beta}=0$ where %formula for christoffel symbol \begin{equation*} \ch{\mu}{\alpha \beta}=\frac{1}{2}g^{\mu \lambda}(\p_{\alpha} g_{\beta \lambda}+\p_\beta g_{\alpha \lambda} - \p_\lambda g_{\alpha \beta}) \end{equation*} and $\p_\mu = \p/\p {X}^\mu$. Now we would try to find covariant derevative with respect to the path, i.e. find $\nabla_\alpha U^\mu$.\\ Now, the first term of geodesic equation can be written as, $\de{U^\mu (X^\alpha(s))}{s}=\de{X^\alpha}{s}\de{U^\mu}{X^\alpha}=U^\alpha \de{U^\mu}{X^\alpha}$, substituing in the geodesic equation we get, $U^\alpha(\de{U^\mu}{X^\alpha}+\ch{\mu}{\alpha\beta}U^{\beta})=0$. The term in bracket is called the covariant derevative i.e. $\nabla_\alpha U^\mu = \de{U^\mu}{X^\alpha}+\ch{\mu}{\alpha\beta}U^{\beta}$ and the equation of geodesic can be reduced to $U^\alpha \nabla_\alpha U^\mu=0$. In terms of four momentum of the particle which is defined as $P^\alpha=mU^\alpha$, the equation of geodesic can be modified as %four momentum tensor equation \begin{equation}\label{Pgeo} P^\alpha \de{P^\mu}{X^\alpha}= - \ch{\mu}{\alpha \beta} P^\alpha P^\beta \end{equation} For masslessparticles lagrangian vanishes and hence, all equations from our derivation breaks down and hence \fn{check out paul townsend part 3 black hole lecture notes} has to be done in a different way. For now, let us accept that the equation of geodesic is given in terms of four momentum for both massive and massless particles, therefore now we will see how is it applied to FRW universe. \subsection{Geodesic Motion in FRW} In order to compute $- \ch{\mu}{\alpha \beta} P^\alpha P^\beta$, we first need to compute the Christoffel symbols for FRW metric: \begin{\cbox} The general space-time interval is given as : \begin{equation} ds^2=g_{\alpha\beta}dx^\alpha dx^\beta=g_{00}dt^2+2g_{0i}dt dx^i + g_{ik}dx^idx^k \end{equation} Isotropy of space implies the $g_{0\alpha}$ must vanish; if not, they would identify a particular three vector $v_i$ with components $g_{0i}$. Further \textbf{we use the proper time of clocks carried by these observers to label spacelike surfaces. This choice for time coordinate implies that $g_{00}=1$.} \end{\cbox} The assumption of isotropy implies spherical symmetry, therefore, line interval can be written as \begin{equation} dl^2=a^2\rr{\lambda^2(r)dr^2+r^2(d\theta^2 + \sin^2 \theta d\phi^2)} \end{equation} where, $a=a(t)$ can depend only on time. Computing the scalar curvature ${}^3R$ for which we use the formula: \begin{equation} {}^3R=\frac{3}{2 a^2 r^3}\frac{d}{dr}\rr{r^2\cc{1-\frac{1}{\lambda^2}}} \end{equation} Now, \textbf{Homogeneity implies that all geometrical property are independent of $r$; hence ${}^3R$ must be constant.} \\ We integrate the above scalar radius equation: \begin{eqnarray*} {}^3R=\frac{3}{2 a^2 r^3}\frac{d}{dr}\rr{r^2\cc{1-\frac{1}{\lambda^2}}}\\ \implies k=\frac{3}{2 a^2 r^3}\frac{d}{dr}\rr{r^2\cc{1-\frac{1}{\lambda^2}}}\\ \implies k \frac{2 a^2 r^3}{3}=\frac{d}{dr}\rr{r^2\cc{1-\frac{1}{\lambda^2}}}\\ \implies k \frac{2 a^2 r^3}{3}dr=d\rr{r^2\cc{1-\frac{1}{\lambda^2}}}\\ \implies k \frac{a^2 r^4}{6}=\rr{r^2\cc{1-\frac{1}{\lambda^2}}}+c_2\\ \implies r^2\cc{1-\frac{1}{\lambda^2}}= c_1r^4+c_2 \end{eqnarray*} \textbf{To avoid cingularity at $r=0$, we need $c_2=0$. Therefore we get $\lambda^2=\cc{1-c_1r^2}^{-1}$. When $c_1 \neq 0$, we can rescale $r$ to make $c_1=1 \text{ or } -1$. Therefore the space-time metric can finally be written as:} \begin{equation*} ds^2=dt^2- a^2(t)\gamma_{ij}dx^i dx^j=c^2dt^2 - a^2(t)\left[\frac{dr^2}{1-kr^2}+r^2(d\theta^2+ \sin^2 \theta d\phi^2)\right] \end{equation*} Here where we have set $x^0=ct \; , \; x^1=r \; , \;x^2 = \theta \; ,\;x^3 = \phi \;$. \begin{\cbox} Here, the form of metric was derived purely on symmetrical considerations, without any reference to the source $T_{ik}$ or Einstein's eqautions. These geometrical considerations, however will not allow us to determine the value of $k$ and the form of a(t). They have to be determined \textbf{by the Einstein's equation once the matter distribution is specified.} \end{\cbox} Following which the non zero components of $g^{ik} \: \mathtt{and} \: g_{ik}$ are: %elements of g for frw metric \begin{eqnarray*} g_{00}=1 \; , \; g_{11}=-\frac{a^2}{1-kr^2} \; , \; g_{22}= -a^2r^2 \; , \; g_{33}=-a^2r^2 \sin^2 \theta \\ g^{00}=1 \; , \; g^{11}= - \frac{1-kr^2}{a^2} \; , \; g^{22}= - \frac{1}{a^2r^2} \; , \; g^{33}= - \frac{1}{a^2r^2 \sin^2 \theta} \\ \end{eqnarray*} Computing $\ch{\mu}{0 0}$ \begin{eqnarray*} \ch{\mu}{00}=\frac{1}{2}g^{\mu \lambda}(\p_{0} g_{0 \lambda}+\p_0 g_{0 \lambda} - \p_\lambda g_{0 0})\\ \implies \ch{\mu}{00}=\frac{1}{2}a^2\gamma^{\mu \lambda}(\p_{0} a^2\gamma_{0 \lambda}+\p_0 a^2\gamma_{0 \lambda} - \p_\lambda a^2\gamma_{0 0}) = 0\\ \end{eqnarray*} Computing $\ch{0}{0 \beta}$ \begin{eqnarray*} \ch{0}{0 \beta}=\frac{1}{2}g^{0 \lambda}(\p_{0} g_{\beta \lambda}+\p_\beta g_{0 \lambda} - \p_\lambda g_{0 \beta})=0 \end{eqnarray*} Computing $\ch{0}{ij}$ \begin{eqnarray*} \ch{0}{ij}=\frac{1}{2}g^{0 \lambda}(\p_{i} g_{j \lambda}+\p_j g_{i \lambda} - \p_\lambda g_{ij})\\ \implies \ch{0}{ij}=\frac{1}{2}g^{0 0}(\p_{i} g_{j 0}+\p_j g_{i 0} - \p_0 g_{ij})\\ \implies \ch{0}{ij}=a \dot{a} \gamma_{ij}\\ \end{eqnarray*} Computing $\ch{i}{0j}$ \begin{eqnarray*} \ch{i}{0 j}=\frac{1}{2}g^{i \lambda}(\p_{0} g_{j \lambda}+\p_j g_{0 \lambda} - \p_\lambda g_{0j})\\ \implies \ch{i}{0 j}=\frac{1}{2}g^{i \lambda}(\p_{0} g_{j \lambda})\\ \implies \ch{i}{0 j}=\frac{1}{2} \frac{1}{a^2 \gamma_{i \lambda}}(\p_{0} a^2 \gamma_{j \lambda})\\ \implies \ch{i}{0 j}=\frac{1}{2} \frac{1}{a^2 \gamma_{i \lambda}} 2a \dot{a} \gamma_{j \lambda}\\ \implies \ch{i}{0 j}=\frac{1}{2} \frac{2 \dot{a}}{a } \gamma^{i \lambda} \gamma_{j \lambda}\\ \implies \ch{i}{0 j}= \frac{\dot{a}}{a } \delta^i_j \end{eqnarray*} Computing $\ch{i}{jk}$ \begin{eqnarray*} \ch{i}{j k}=\frac{1}{2}g^{i \lambda}(\p_{j} g_{k \lambda}+\p_k g_{j \lambda} - \p_\lambda g_{jk})\\ =\frac{1}{2}( - \frac{1}{a^2} \gamma^{i \lambda})(\p_{j} ( - {a^2} \gamma_{k \lambda})+\p_k ( - {a^2} \gamma_{j \lambda}) - \p_\lambda ( - {a^2} \gamma_{j k})\\ =\frac{1}{2} \gamma^{i \lambda}(\p_{j} \gamma_{k \lambda}+\p_k \gamma_{j \lambda} - \p_\lambda \gamma_{j k}) \end{eqnarray*} Now homogeneity would imply that spatial change in four momentum tensor($P^{\alpha}$) is zero i.e. $\p_i P^\alpha=0$. Therefore equation of geodesic (\ref{Pgeo}) reduces to \begin{eqnarray} P^0 \de{P^\mu}{t}=-\ch{\mu}{\alpha \beta}P^{\alpha}P^{\beta}\\ = - (2 \ch{\mu}{0 j} P^0 + \ch{\mu}{i j}P^{i})P^j \label{FRWgeo} \end{eqnarray} using values of $\ch{\mu}{\alpha \beta}$ obtained for the FRW metric \fn{the factor 2 in the first term(second line) got there because of symmetric property of christoffel sympbol by changing position of zero and then applying change of index from i to j } . Let us understand the final result for homogeneous FRW universe: \begin{itemize} \item For massive particles at rest in comoving frame, $P^{j}=0$, and will stay at rest, \begin{eqnarray*} P^0 \de{P^f}{t}= - (2 \ch{f}{0 j} P^0 + \ch{f}{i j}P^{i})P^j\\ \implies P^0 \de{P^f}{t}=0\\ \implies \de{P^f}{t}=0 \end{eqnarray*} \item Now if we consider $\mu=0$, for a particle massive or massless without prescribing anything regarding state of motion of the particle. The first term in \eqref{FRWgeo} goes to zero as we know $\ch{0}{0j}=0$ and the second term is given by $\ch{0}{ij}=a \dot{a} \gamma_{ij}$ therefore \eqref{FRWgeo} becomes: \begin{equation} E \de{E}{t}= - \ch{0}{ij} P^i P^j \end{equation} using $P^0=E$ and if we define three momentum as $p^2 \equiv -g_{ij}P^iP^j = a^2 \gamma_{ij}$ then \begin{equation}\label{Egeo} E\de{E}{t}= - \frac{\dot{a}}{a}p^2 \end{equation} The four momentum tensor satisfies the equation $g_{\mu \nu}P^{\mu} P^{\nu}=m^2$ or $E^2-p^2=m^2$. Now for massless particle $EdE=pdp$. Therefore \eqref{Egeo} can be written as, \begin{equation*} \frac{\dot{p}}{p}=-\frac{\dot{a}}{a} \implies \log p= -\log a \implies \log p= -\log \frac{1}{a} \implies p \propto \frac{1}{a} \end{equation*} \textbf{Note that, the physical three momentum for any type of particle decays with the expansion of the universe.} \begin{itemize} \item For massless particles $p=E \propto \frac{1}{a}$. \item For massive particles \begin{eqnarray} P^i=mU^i = m \de{X^i}{s}= m\de{t}{s} \de{X^i}{dt}= m \de{t}{s} v^i =m\frac{v^i}{\sqrt{1-v^2}}\\ p=\frac{mv}{\sqrt{1-v^2}}\propto \frac{1}{a} \label{pa} \end{eqnarray} Here $v^i=dx^i/dt$ called \tit{comoving peculiar velocity}. \fn{check out page 12 which tells how \eqref{pa} represents freely falling bodies which when left on their own will converge onto the hubble flow. What is Hubble flow?} \end{itemize} \end{itemize} \subsection{Redshift} For now, I am not repeating the same notes again and again. May be I will repeat this work when I have time in future. For now, two very important formulas to take away are, \begin{equation} 1+z=\frac{1}{a(t_1)} \end{equation} and This means that at redshift z, the universe was $1/(z+1)^{th}$ of its present size. We can also calculate the redshift for the matter and cosmological constant equality, i.e. , $\rho_m= \rho_\Lambda$ or $\Omega_m/a^3= \Omega_\Lambda$, Using the known values for $\Omega_m=0.31$ and $\Omega_\Lambda=0.69$ we get ${\left(\frac{\Omega_m}{\Omega_\Lambda}\right)}^{1/3}=\frac{1}{a}$ and substituting it in redshift relation we get $z=0.3$. We can similarly calculate matter-radiation equality, $\frac{\Omega_m}{a^3}=\frac{\Omega_r}{a^4}$. This was the time when neutrinos transited from relativistic to non relativistic regime, and if we use the current day neutrino radiation energy density $\Omega_r \sim 8.4 \times 10^{-4}$ we get $z=3700$. Therefore the universe was matter dominated for most of the time $z=3400$, (which is a more accurate number), with the cosmological constant becoming important only recently. \begin{equation} H_0 \equiv \frac{\dot{a}{(t_0)}}{a(t_1)} \end{equation} and for very small distances $z \simeq H_0d$. \subsection{Distances} For distant objects, we \section{Dynamics} In order to study the dynamics of the universe, we need to first solve the Einstein's equation: \begin{equation}\label{Enseq} G_{\mu \nu}= 8 \pi G T_{\mu \nu} \end{equation} $G_{\mu \nu}$ is the Einstein tensor which measures the \tit{spacetime curvature} of the FRW universe to the stress-energy tensor $T_{\mu \nu}$ which measures \tit{the matter content} in the universe. Our methodology will be to first discuss possible form of $T_{\mu \nu}$ and then compute the Einstein tensor $G_{\mu \nu}$ for FRW background and then using the above for the evolution of a(t) as a function of matter content. \subsection{Matter Sources} The condition of isotropy and homogeneity constraints a coarse grained universe to be perfect fluid. \subsection*{Number Density} First we will talk about Number current four vector $N^\mu$. The $\mu=0$ component, $N^0$ meaures the number density of particles,(here, even an entire galaxy may constitute a particle). The $\mu=0$ component, $N^i$ meaures the flux of particles in the direction $x^i$. For the current of galaxies, as measured by comoving observer, Isotropy requires that mean value of any 3-vector such as $N^i$ must vanish and the condition for homogeneity would require the value of any 3-scalar \fn{A 3-scalar is quantity that is invariant under purely spatial coordinate transformation.}, $N^0=n(t)$ be only dependent on time. Here $n(t)$ is the number of galaxies per proper volume as measured by comoving observer. A general observer , one who is in motion relative to the rest frame of the particles would measure the number current as $N^\mu=n U^\mu$ where $U^\mu \equiv \de{X}{s}$ is the relative four velocity between particles and observer. As the number density has to be conserved, Minkowski space would imply that equation of continuity would imply $\dot{N^0}=-\p_i N^i$. This equation can be written as $\p_\mu N^\mu=0$ and when accounting for space time curvature we have $\nabla_\mu N^\mu=0$. Expanding on that \begin{eqnarray*} \nabla_\mu N^\mu=\p_\mu N^\mu + \ch{\mu}{\mu \lambda}N^\lambda=0 \\ \implies \de{n}{t}+ \ch{i}{i0}n=0\\ \implies \de{n}{t}+ \ch{1}{10}n+ \ch{2}{20}n+ \ch{3}{30}n=0\\ \implies \frac{\dot{n}}{n}=-3\frac{\dot{a}}{a} \implies n(t) \propto a^{-3} \end{eqnarray*} In the above case we have used the christoffel symbols calculated for the FRW universe. \subsection*{Energy-Momentum Tensor} Now building on the same concept of isotropy and homogeneity we will try to form the stress-energy tensor $T_{\mu\nu}$. Tensor object $T_{\mu\nu}$ can be decomposed as 3-scalar, $T_{00}$, 3-vectors, $T_{i0},T_{0j}$ and a 3-tensor, $T_{ij}$. Isotropy would require 3-vectors to vanish as $T_{i0},T_{j0}=0$ and the isotropy around the point $x=0$ requires the mean value of $T_{ij}$ at that point to be proportional to \begin{equation} T_{ij} \propto \delta_{ij} \propto g_{ij}(x=0) \propto -a^2\delta_{ij} \end{equation} Homogeneity requires the proportionality coefficient to be only a function of time. Since this is a proportionality between two 3-tensor object, $T_{ij}$ and $g_{ij}$ it must remain unaffected by an arbitary transformation of spatial coordinates, \textbf{including those transformations that preserve the form of $g_{ij}$ while taking the origin into any other point}. Hence, considering everything above stress-energy tensor is given as $T_{00}=\rho(t), \; \; \pi_i=T_{i0}=0 \; \; T_{ij}= -P(t)g_{ij}(t,\mbf{x})$. This is the stress-energy tensor of a perfect fluid as seen by a comoving observer. \begin{equation}\label{step} T^\mu_\nu=(\rho+P)U^\mu U_\lambda - P \delta^\mu _\nu \end{equation} Now, we again have energy and momentum conserved in Minkowski space. The energy density therefore satisfies the continuity equation $\dot{\rho}=\p_i \pi^i$,i.e. the rate of change of the density equals the divergence equals the divergence of the energy flux. Similarly, $\dot{\pi_i}=\p_i P$, this is Euler equation. These conservation can be combined into a four component conservation equation given as $\p_\mu T^\mu _\nu=0$. The conservation equation can be expanded as \begin{equation*} \nabla_\mu {T^\mu}_\nu = \p_\mu {T^\mu} _\nu + \ch{\mu}{\mu \lambda} {T^\lambda} _\nu - \ch{\lambda}{\mu \nu} {T^\mu} _\lambda=0 \end{equation*} The evolution of energy density is determined by the $\nu=0$ equation \begin{eqnarray*} \nabla_\mu T^\mu _0 = \p_\mu T^\mu _0 + \ch{\mu}{\mu \lambda} T^\lambda _0 - \ch{\lambda}{\mu 0} T^\mu _\lambda=0 \\ \implies \de{\rho}{t} + \ch{\mu}{\mu 0} \rho - \ch{\lambda}{\mu 0} T^\mu _\lambda=0 \; \; \tit{ ;where $T^i_0$ vanishes by isotropy}\\ \dot{\rho}+ 3 \frac{\dot{a}}{a}(\rho + P) = 0 \tit{;This is the continuity equation} \end{eqnarray*} In the above equation we have used the christoffel symbols calculated for FRW universe. \subsection*{Cosmic Inventory} Let's look up the cosmic inventory, and classify different sources by their contribution to the pressure. \begin{itemize} \item \textbf{Matter} \\ This represents all forms of non relativistic particles for which, pressure is much smaller than the energy density, $|P|<< \rho $. Now we know the continuity equation to be $\dot{\rho}+ 3 \frac{\dot{a}}{a}(\rho + P) = 0$. Setting $P=0$ in \begin{equation*} \rho \propto a^{-3} \end{equation*} This dilution of the energy density simply reflects the expansion of the volume $V \propto a^3$. \begin{itemize} \item \textbf{Dark Matter}: Most of the matter in the universe is Dark matter which is predicted to be new heavy particle species. The 'cold' in the cold dark matter theory refers to the fact that it is non relativistic today, and moreover has been so for a very long time.\\ \item \textbf{Baryons}: All ordinary matter is considered Baryons. \end{itemize} \item \textbf{Radiation}:\\ Anything for which the pressure is about a third of energy density $P=\frac{1}{3}\rho$. It constitutes of all the relativistic particle, for which energy density is dominated by kinetic energy(momentum term in energy equation is greater than the mass). \begin{eqnarray*} \dot{\rho}+3\frac{\dot{a}}{a}(\rho +P)=0\\ \tit{for P=$1/3\rho$}\\ \implies \frac{\dot{\rho}}{\rho}=-4\frac{\dot{a}}{a}\\ \implies \log \rho \propto \log a^{-4}\\ \implies \rho \propto a^{-4} \end{eqnarray*} This can be thought as combined effect of dilution due to expansion of real space($\propto a^{-3}$) and expansion of wavelength of the photon travelling ($\propto a^{-1}$) \begin{itemize} \item \tbf{Photons}: Early universe was dominated by photons. Being massless, they are always relativistic. We detect these photons as CMB. \item \tbf{Neutrinos}: They were treated like radiation earlier but they have turned out to be matter. sighs! \item \tbf{Gravitons}: Early universe might have produced a background of Gravitational waves. We are now trying to detect them. \end{itemize} \item \tbf{Dark energy}:The Universe today appears to be dominated by a negative pressure content $P=-\rho$. \begin{eqnarray*} \dot{\rho}+3\frac{\dot{a}}{a}(P+\rho)=0\\ \tit{For $P=-\rho$}\\ \implies \rho= \tit{constant} \propto a^0 \end{eqnarray*} Since the energy density does not dilute as the spatial volume increases, energy has to be created.\\ \tbf{Is Dark energy, vaccum energy?} The groundstate energy of the stress energy tensor corresponds to the following stress energy tensor \begin{equation*} T_{\mu \nu}^{vac}=\rho_{vac}g_{\mu \nu} \end{equation*} Even though when we compare the above equation, with \eqref{step} , we get $P_{vac}= -\rho_{vac}$ which is a perfect match but, it is found that \begin{equation*} \frac{\rho_{vac}}{\rho_{obs}} \sim 10^{120} \end{equation*} \end{itemize} \tbf{*Drumrolls!* }\\ \tbf{Introducing Cosmological Constant} The dynamics of universe is given by \eqref{Enseq} , but the left hand side is not uniquely defined. Adding $\Lambda g_{\mu \nu}$ on both sides we get, \begin{equation}\label{ccp} G_{\mu \nu} - \Lambda g_{\mu \nu}= 8 \pi G T_{\mu \nu}- \Lambda g_{\mu \nu} \end{equation} But we know, conservation equation is \begin{eqnarray*} \nabla^{\mu}T_{\mu \nu}=0\\ \tit{introducing $\Lambda g_{\mu \nu} $ knowing that $\nabla^\mu g_{\mu \nu}=0$}\\ \implies \nabla^{\mu}(T_{\mu \nu}+\Lambda g_{\mu \nu})=0\\ \implies \nabla^{\mu}(T^\prime{\mu \nu})=0\\ \end{eqnarray*} Therefore, \eqref{ccp} is modified to be \begin{equation} G_{\mu \nu} - \Lambda g_{\mu \nu}= 8 \pi G T_{\mu \nu} \end{equation} Moving the term to r.h.s. and treating it as contribution to the stress energy tensor \begin{equation} T_{\mu \nu}^{\Lambda}=\frac{\Lambda}{8 \pi G}g_{\mu \nu}\equiv \rho_{\Lambda}g_{\mu \nu} \end{equation} which is of the same form as the stress energy tensor from vaccum energy. \\ \subsection*{Summary} Now if we parametrised in terms of a constant equation of state $w=P/\rho$. The solution to $\dot{\rho}+3\frac{\dot{a}}{a}(P+\rho)=0$ is \begin{equation*} \rho \propto a^{-3(1+w)} \end{equation*} Finaly, \begin{itemize} \item vaccum energy - $w=0$ and $\rho \propto a^0$ \item radiation - $w=1/3$ and $\rho \propto a^{-4}$ \item matter - $w=0$ and $\rho \propto a^{-3}$ \end{itemize} \subsection*{A method to determine the mass of galaxies or clusters of galaxies} \tbf{Galaxy Rotation Curves} At galactic scale, this method helps us to measure mass. We will go a little fast paced with this method. For this method we will assume that the galaxy has a spherical symmetry. Now the stars at a distance $r$ from the galactic center would experience a centrifugal force given as \begin{eqnarray*} \frac{v^2}{r}=\frac{GM(r)}{r^2}\tit{\; ; \; where M(r) is the mass enclosed inside the sphere of radius r}\\ \implies v(r)=\sqrt{\frac{GM(r)}{r}} \end{eqnarray*} Now, we would expect that as we cross the periphery of the galaxy, the $M(r)$ stays constant and the velocity drops as $\sqrt{1/r}$. This is not what is observed rather the velocity remains constant , indicating that the mass $M(r)$ increases and continues to grow as $M(r) \sim r$ far from the observable galaxy. This extended source of mass is called the dark matter halo. We measure the rotation speeds from the edge of the galaxy by studying the interstekkar gas, particularly 21 cm line of hydrogen. \subsection*{Spacetime Curvature} Now all this, what we want now is to use all the above information to understand the evolution of the scale factor $a(t)$ in the FRW metric which is given by \begin{equation*} ds^2=dt^2- a^2(t)\gamma_{ij}dx^i dx^j=c^2dt^2 - a^2(t)\left[\frac{dr^2}{1-kr^2}+r^2(d\theta^2+ \sin^2 \theta d\phi^2)\right] \end{equation*} To do this, first we need to calculate the Einstein tensor in the equation, \begin{equation*} G_{\mu \nu}=8 \pi G T_{\mu \nu} \end{equation*} and in order to do this we need the equation \begin{equation} G_{\mu \nu}= R_{\mu \nu} - \frac{1}{2}R g_{\mu \nu} \end{equation} For which we first need to find the following terms \begin{eqnarray} R_{\mu \nu} \equiv \p_{\lambda}\ch{\lambda}{\mu \nu} - \p_{\nu}\ch{\lambda}{\mu \lambda} + \ch{\lambda}{\lambda \rho}\ch{\rho}{\mu \nu} - \ch{\rho}{\mu \lambda}\ch{\lambda}{\nu \rho} \\ R = {R^\mu }_\mu = g^{\mu \nu} R_{\mu \nu} \end{eqnarray} Calculating the components of Ricci tensor. For which we need, \begin{eqnarray*} \ch{\mu}{00}= 0\\ \ch{0}{0 \beta}=0\\ \ch{0}{ij}=a \dot{a} \gamma_{ij}\\ \ch{i}{0 j}= \frac{\dot{a}}{a } \delta^i_j\\ \ch{i}{j k}=\frac{1}{2} \gamma^{i \lambda}(\p_{j} \gamma_{k \lambda}+\p_k \gamma_{j \lambda} - \p_\lambda \gamma_{j k}) \end{eqnarray*} Calculating the components of Ricci tensor. \begin{eqnarray*} R_{00}=\p_{\lambda}\ch{\lambda}{00} - \p_{0}\ch{\lambda}{0 \lambda} + \ch{\lambda}{\lambda \rho}\ch{\rho}{00} - \ch{\rho}{0 \lambda}\ch{\lambda}{0 \rho} \\ \implies R_{00}=-\de{(3\frac{\dot{a}}{a})}{t}-3\left({\frac{\dot{a}}{a}}\right)^2= -3 \frac{\ddot{a}}{a} \end{eqnarray*} Calculating $R_{i0}$ \begin{eqnarray*} R_{i0} \equiv \p_{\lambda}\ch{\lambda}{i0} - \p_{0}\ch{\lambda}{i \lambda} + \ch{\lambda}{\lambda \rho}\ch{\rho}{i0} - \ch{\rho}{i \lambda}\ch{\lambda}{0 \rho}\\ =\sum_\lambda \p_{\lambda}\ch{\lambda}{i0} - \sum_\lambda \p_{0}\ch{\lambda}{i \lambda} + \sum_{\lambda,\rho} \ch{\lambda}{\lambda \rho}\ch{\rho}{i0} -\sum_{\lambda,\rho} \ch{\rho}{i \lambda}\ch{\lambda}{0 \rho}\\ =\sum_\lambda \p_{\lambda}\ch{\lambda}{i0} - \sum_\lambda \p_{0}\ch{\lambda}{i \lambda} + \sum_{\lambda,\rho} \ch{\lambda}{\lambda \rho}\ch{\rho}{i0} -\sum_{\lambda,\rho} \ch{\rho}{i \lambda}\ch{\lambda}{0 \rho}\\ =( \p_{1}\ch{1}{i0}+\p_{2}\ch{2}{i0}+\p_{3}\ch{3}{i0}+\p_{0}\ch{0}{i0}) - (\p_{0}\ch{0}{i 0}+\p_{0}\ch{1}{i 1}+ \p_{0}\ch{2}{i 2} + \p_{0}\ch{3}{i 3}) + \sum_{\lambda,\rho} \ch{\lambda}{\lambda \rho} \frac{\dot{a}}{a } \delta^i_\rho -\sum_{\lambda,\rho} \ch{\rho}{i \lambda} \frac{\dot{a}}{a } \delta^\lambda_\rho\\ =( \p_{1}\ch{1}{i0}+\p_{2}\ch{2}{i0}+\p_{3}\ch{3}{i0}) - (\p_{0}\ch{1}{i 1}+ \p_{0}\ch{2}{i 2} + \p_{0}\ch{3}{i 3}) + \sum_{\lambda,\rho} \ch{\lambda}{\lambda \rho} \frac{\dot{a}}{a } \delta^i_\rho -\sum_{\lambda,\rho} \ch{\rho}{i \lambda} \frac{\dot{a}}{a } \delta^\lambda_\rho\\ =( \p_{i} (\frac{1}{2} \gamma^{i \lambda}(\p_{0} \gamma_{i \lambda}+\p_i \gamma_{0 \lambda} - \p_\lambda \gamma_{0i}))) - (\p_{0}\ch{1}{i 1}+ \p_{0}\ch{2}{i 2} + \p_{0}\ch{3}{i 3}) + \sum_{\lambda,\rho} \ch{\lambda}{\lambda \rho} \frac{\dot{a}}{a } \delta^i_\rho -\sum_{\lambda,\rho} \ch{\rho}{i \lambda} \frac{\dot{a}}{a } \delta^\lambda_\rho\\ =( \p_{i} (\frac{1}{2} \gamma^{i \lambda}(\p_i \gamma_{0 \lambda} - \p_\lambda \gamma_{0i}))) - (\p_{0}\ch{1}{i 1}+ \p_{0}\ch{2}{i 2} + \p_{0}\ch{3}{i 3}) + \sum_{\lambda,\rho} \ch{\lambda}{\lambda \rho} \frac{\dot{a}}{a } \delta^i_\rho -\sum_{\lambda,\rho} \ch{\rho}{i \lambda} \frac{\dot{a}}{a } \delta^\lambda_\rho\\ = - (\p_{0}\ch{1}{i 1}+ \p_{0}\ch{2}{i 2} + \p_{0}\ch{3}{i 3}) + \sum_{\lambda,\rho} \ch{\lambda}{\lambda \rho} \frac{\dot{a}}{a } \delta^i_\rho -\sum_{\lambda,\rho} \ch{\rho}{i \lambda} \frac{\dot{a}}{a } \delta^\lambda_\rho\\ = - (\p_{0}(\frac{1}{2} \gamma^{i \lambda}(\p_{1} \gamma_{i \lambda}+\p_i \gamma_{1 \lambda} - \p_\lambda \gamma_{1i}))+ \p_{0}\ch{2}{i 2} + \p_{0}\ch{3}{i 3}) + \sum_{\lambda,\rho} \ch{\lambda}{\lambda \rho} \frac{\dot{a}}{a } \delta^i_\rho -\sum_{\lambda,\rho} \ch{\rho}{i \lambda} \frac{\dot{a}}{a } \delta^\lambda_\rho\\ = - (\p_{0}(\frac{1}{2} \gamma^{i i}(\p_{1} \gamma_{i i}+\p_i \gamma_{1 1} - \p_\lambda \gamma_{11}))+ \p_{0}\ch{2}{i 2} + \p_{0}\ch{3}{i 3}) + \sum_{\lambda,\rho} \ch{\lambda}{\lambda \rho} \frac{\dot{a}}{a } \delta^i_\rho -\sum_{\lambda,\rho} \ch{\rho}{i \lambda} \frac{\dot{a}}{a } \delta^\lambda_\rho\\ = - (\p_{0}(\frac{1}{2} \gamma^{i i}(\p_{1} \gamma_{i i}+\p_i \gamma_{1 1} - \p_i \gamma_{11}))+ \p_{0}\ch{2}{i 2} + \p_{0}\ch{3}{i 3}) + \sum_{\lambda,\rho} \ch{\lambda}{\lambda \rho} \frac{\dot{a}}{a } \delta^i_\rho -\sum_{\lambda,\rho} \ch{\rho}{i \lambda} \frac{\dot{a}}{a } \delta^\lambda_\rho\\ = - (\p_{0}(\frac{1}{2} \gamma^{i i}(\p_{1} \gamma_{i i}))+ \p_{0}\ch{2}{i 2} + \p_{0}\ch{3}{i 3}) + \sum_{\lambda,\rho} \ch{\lambda}{\lambda \rho} \frac{\dot{a}}{a } \delta^i_\rho -\sum_{\lambda,\rho} \ch{\rho}{i \lambda} \frac{\dot{a}}{a } \delta^\lambda_\rho\\ = - (\p_{0}(\frac{1}{2} \gamma^{i i}(\p_{1} \gamma_{i i}))+ \p_{0}\ch{2}{i 2} + \p_{0}\ch{3}{i 3}) + \sum_{\lambda} \ch{\lambda}{\lambda i} \frac{\dot{a}}{a } -\sum_{\lambda} \ch{\lambda}{i \lambda} \frac{\dot{a}}{a } \\ = - (\p_{0}(\frac{1}{2} \gamma^{i i}(\p_{1} \gamma_{i i}))+ \p_{0}(\frac{1}{2} \gamma^{i i}(\p_{2} \gamma_{i i})) + \p_{0}(\frac{1}{2} \gamma^{i i}(\p_{3} \gamma_{i i})))\\ =0 \end{eqnarray*} Calculating $R_{ij}$ \begin{eqnarray*} R_{ij} \equiv \p_{\lambda}\ch{\lambda}{ij} - \p_{j}\ch{\lambda}{i \lambda} + \ch{\lambda}{\lambda \rho}\ch{\rho}{ij} - \ch{\rho}{i \lambda}\ch{\lambda}{j \rho}\\ =\p_{\lambda}\ch{\lambda}{ij} - \p_{j}\ch{\lambda}{i \lambda} + \ch{\lambda}{\lambda \rho}\ch{\rho}{ij} - \ch{\rho}{i \lambda}\ch{\lambda}{j \rho}\\ \end{eqnarray*} What we will do is compute $R_{ij}(\mbf{x}=0) \propto \delta_{ij} \propto g_{ij}(\mbf{x}=0)$ and then transform the resulting relation between 3-tensors to general $\mbf{x}$. The spatial metric is written as \begin{equation}\label{frwgamma} \gamma_{ij}=\delta_{ij}+\frac{kx_i x_j}{1-k(x_k x^k)} \end{equation} It is very important to note that even though we are obtaining the value of $R_{ij}$ for $\mbf{x=0}$, we should not use $\Gamma_{ij}=\delta_{ij}$ because there are contributions while calculating christoffel symbol and riemman tensor for which we need to calculate the derivative of the metric. We can drop the denominator of the second term in \eqref{frwgamma}, because when we calculate the derevative of \eqref{frwgamma} and substitute in the equation of christoffel symbol, the pertaining terms(scalar product terms) would cancel out. First, let us calculate the derevative of $\gamma_{ij}$. \begin{eqnarray*} \gamma_{ij}=\delta_{ij}+ kx_i x_j\\ \implies \p_l \gamma_{ij}=k (\delta_{li}x_j + x_i\delta_{lj}) \end{eqnarray*} Now, we try to evaluate the christoffel symbol, for which we need $\gamma^{ij}=\delta^{ij} - second term$, but as we are calculating for $\mbf{x=0}$, this term can just be reduced to $\gamma^{ij}=\delta^{ij}$ \begin{eqnarray*} \ch{i}{jk}=\frac{1}{2}\gamma^{il}(\p_j \gamma_{kl}+ \p_k \gamma_{jl} - \p_l \gamma_{jk})\\ \ch{i}{jk}=\frac{1}{2}\gamma^{il}(k (\delta_{jk}x_l + x_k\delta_{jl})+ k (\delta_{kj}x_l + x_j\delta_{kl}) - k (\delta_{lj}x_k + x_j\delta_{lk}))\\ \ch{i}{jk}=\frac{1}{2}\gamma^{il}k(\delta_{jk}x_l + \delta_{kj}x_l)\\ \ch{i}{jk}=\gamma^{il}k \delta_{jk}x_l \\ \ch{i}{jk}=\delta^{il}k \delta_{jk}x_l \\ \ch{i}{jk}=k \delta_{jk}x^i \\ \end{eqnarray*} Now, we need to calculate the Ricci tensor, \begin{eqnarray*} R_{\mu \nu} \equiv \p_{\lambda}\ch{\lambda}{\mu \nu} - \p_{\nu}\ch{\lambda}{\mu \lambda} + \ch{\lambda}{\lambda \rho}\ch{\rho}{\mu \nu} - \ch{\rho}{\mu \lambda}\ch{\lambda}{\nu \rho} \end{eqnarray*} From calculated christoffel symbol, we note that, $\ch{i}{jk}(\mbf{x=0})=0$ and $\p_l \ch{i}{jk}=k\delta^i_l \delta_jk$. Now, we calculate \begin{eqnarray*} R_{ij}(\mbf{x}=0) \equiv \p_{\lambda}\ch{\lambda}{ij} - \p_{j}\ch{\lambda}{i \lambda} + \ch{\lambda}{\lambda \rho}\ch{\rho}{ij} - \ch{\rho}{i \lambda}\ch{\lambda}{j \rho} \end{eqnarray*} Let us calculate the first two terms: \begin{eqnarray*} A=\p_{\lambda}\ch{\lambda}{ij} - \p_{j}\ch{\lambda}{i \lambda}\\ \implies A= \p_0 \ch{0}{ij} + \p_l \ch{l}{ij} - \p_j \ch{0}{i0} - \p_j \ch{l}{il} \\ \implies A= \p_0 \ch{0}{ij} + \p_l \ch{l}{ij} - \p_j \ch{l}{il} \\ \implies A= \p_0 (a\dot{a})\delta_{ij} + k \delta^l_l \delta_{ij} - k \delta^l_j \delta_{il} \\ \implies A= (a\dot{a}+\dot{a}^2+2k)\delta_{ij}\\ \tit{in the above statement did we get the 2 factor, is it because of the delta function?} \end{eqnarray*} Let us look at the last the last two terms: \begin{eqnarray*} B=\ch{\lambda}{\lambda \rho}\ch{\rho}{ij} - \ch{\rho}{i \lambda}\ch{\lambda}{j \rho}\\ \implies B=\ch{l}{l0}\ch{0}{ij}+\ch{0}{0l}\ch{l}{ij}-\ch{l}{i0}\ch{0}{jl}-\ch{0}{il}\ch{l}{i0}\\ \implies B=\ch{l}{l0}\ch{0}{ij}-\ch{l}{i0}\ch{0}{jl}-\ch{0}{il}\ch{l}{i0}\\ \implies B=3\frac{\dot{a}}{a}a\dot{a}\delta_{ij} - a\dot{a}\delta_{ij}\frac{\dot{a}}{a}\delta^l_j-\frac{\dot{a}}{a}\delta^l_j a\dot{a}\delta_{jl}\\ \implies B= \dot{a}^2 \delta_{ij} \end{eqnarray*} Adding, the two terms, \begin{eqnarray*} R_{ij}(\mbf{x=0})=A+B\\ =\left[a\ddot{a} + 2\dot{a}^2 +2k\right]\delta_{ij}\\ R_{ij}(\mbf{x=0})=-\left[\frac{\ddot{a}}{a} + 2\left(\frac{\dot{a}}{a}\right)^2 +2\frac{k}{a^2}\right]g_{ij}(\mbf{x=0})\\ \end{eqnarray*} \tbf{As this is a relation between tensors, this holds for any general $\mbf{x}=0$} Now, let us find the Ricci scalar, \begin{eqnarray*} R=R^\mu_\mu=g^{\mu \nu}R_{\mu \nu}\\ R=-g^{ij}\left[\frac{\ddot{a}}{a} + 2\left(\frac{\dot{a}}{a}\right)^2 +2\frac{k}{a^2}\right]g_{ij} - 3\frac{\ddot{a}}{a}g^{00} g_{00}\\ R=-3\left[\frac{\ddot{a}}{a} + 2\left(\frac{\dot{a}}{a}\right)^2 +2\frac{k}{a^2}\right] - 3\frac{\ddot{a}}{a}\\ R=-6\left[\frac{\ddot{a}}{a} + \left(\frac{\dot{a}}{a}\right)^2 +\frac{k}{a^2}\right] \\ \end{eqnarray*} Now, we finally are in a position to find the Einstein tensor, \begin{equation*} G_{\mu \nu}= R_{\mu \nu} - \frac{1}{2}R g_{\mu \nu} \end{equation*} The $G_{00}$ component is: \begin{eqnarray*} G_{00}=R_{00}- \frac{1}{2}R g_{\mu \nu}\\ G_{00}=3\left[ \left(\frac{\dot{a}}{a}\right)^2 +\frac{k}{a^2}\right]g_{00}\\ \end{eqnarray*} The $G_{ij}$ component is: \begin{eqnarray*} G_{ij}= R_{ij} - \frac{1}{2}R g_{ij}\\ G_{ij}=-\left[\frac{\ddot{a}}{a} + 2\left(\frac{\dot{a}}{a}\right)^2 +2\frac{k}{a^2}\right]g_{ij} - \frac{1}{2}(-6\left[\frac{\ddot{a}}{a} + \left(\frac{\dot{a}}{a}\right)^2 +\frac{k}{a^2}\right] g_{ij})\\ G_{ij}=\left[2\frac{\ddot{a}}{a} + \left(\frac{\dot{a}}{a}\right)^2 +\frac{k}{a^2}\right] g_{ij} \end{eqnarray*} The non zero components of the Einstein tensor $G^{\mu \nu} \equiv g^{\mu \lambda}G_{\lambda \nu}$ are \begin{eqnarray*} G^0_0=3\left[\left(\frac{\dot{a}}{a}\right)^2 +\frac{k}{a^2}\right]\\ G^i_j=\left[2\frac{\ddot{a}}{a} + \left(\frac{\dot{a}}{a}\right)^2 +\frac{k}{a^2}\right] g_{jm} g^{i m}\\ G^i_j=\left[2\frac{\ddot{a}}{a} + \left(\frac{\dot{a}}{a}\right)^2 +\frac{k}{a^2}\right] \delta^i_j\\ \end{eqnarray*} \subsection{Friedmann Equations} Now, we know everything to substitute in, \begin{equation*} G_{\mu \nu}=8 \pi G T_{\mu \nu} \end{equation*} From, $\mu=\nu=0$, and substituting $G_{00}$ and $T_{00}$, we get \begin{eqnarray*} 3\left[\left(\frac{\dot{a}}{a}\right)^2 +\frac{k}{a^2}\right]=8\pi G \rho\\ \end{eqnarray*} \begin{equation}\label{continuityeq} \left(\frac{\dot{a}}{a}\right)^2= \frac{8 \pi G \rho}{3} - \frac{k}{a^2} \end{equation} From, $\mu=i \; , \;\nu=j$, and substituting $G^i_{j}$ and $T^i_{j}$, we get \begin{eqnarray*} \left[2\frac{\ddot{a}}{a} + \left(\frac{\dot{a}}{a}\right)^2 +\frac{k}{a^2}\right] \delta^i_j=8 \pi G (-P)\delta^i_j\\ \implies 2\frac{\ddot{a}}{a}=8 \pi G (-P) - \left[\left(\frac{\dot{a}}{a}\right)^2 +\frac{k}{a^2}\right]\\ \tit{But we know from the calculation using $\mu=\nu=0$ we get that $\left(\frac{\dot{a}}{a}\right)^2= \frac{8 \pi G \rho}{3} - \frac{k}{a^2}$}\\ \implies 2\frac{\ddot{a}}{a}=8 \pi G (-P) - \left[\frac{8 \pi G \rho}{3} - \frac{k}{a^2} +\frac{k}{a^2}\right]\\ \implies 2\frac{\ddot{a}}{a}= - \frac{8\pi G (3P+ \rho)}{3}\\ \end{eqnarray*} \begin{equation}\label{Raychaudharieq} \implies \frac{\ddot{a}}{a}= - \frac{4\pi G (3P+ \rho)}{3} \end{equation} This is known as the \tit{Raychaudhuri Equation}. \textbf{Claim:} If matter obeys the strong energy condition, \begin{equation} \rho + 3P \geq 0 \end{equation} then there was a singularity at a time $t_{BB}$ in the past where $a(t_{BB}=0$. Furthermore, $t_0 - t_{BB} \leq H_0^{-1}$. \textbf{Proof:} The strong condition immediately tells us from \eqref{Raychaudharieq} that $\ddot{a}/a \leq 0$. This is the statement that the universe is decelerating. In other words we can claim that the universe was expanding faster in the past. Now suppose the $\ddot{a}=0$, then by integrating with respect to time we get \begin{eqnarray*} \dot{a}=Constant\\ \tit{But, we know $H_0=\dot{a}_0$ as $a_0=1$}\\ \implies a=H_0 t + const \end{eqnarray*} We see that for $a=0$, we have $t=\frac{c}{H_0}$. And for $\ddot{a}<0$, the zero for a occurs at $t^{\prime}>t$. Therefore, the universe with $\ddot{a}$ sets a lower time limit for big bang singularity $t_{BB}$ and an upper limit for the scale factor. \fn{check out page 36 of David tong notes on cosmology}. as we know $t_0= H_0^{-1}$ therefore , $t_0- t_{BB} \leq H_0^{-1}$. \tbf{It is important to note that here we had assumed a universe which is isotropic and homogeneous FRW universe, that is why the proof turned out to be simple}. This proof was made in the Hawking's singularity theorem without any of the above assumptions. Coming back to the Friedman Equations \eqref{continuityeq} and \eqref{Raychaudharieq}, Here it is understood that $\rho$ and $P$ are the result of contribution of all components in the universe. \tbf{$\rho_b$ - contribution from baryon , $\rho_\nu$ - neutrino , $\rho_c$ - cold dark matter , $\rho_r$ - radiation , $\rho_\gamma$ - photons , $\rho_\Lambda$ from vaccum energy distribution}. Equation \eqref{continuityeq} in terms of Hubble parameters $H \equiv \dot{a}/a$ is written as \begin{equation}\label{Firstfriedeq} H^2=\frac{8 \pi G \rho}{3} - \frac{k}{a^2} \end{equation} Now let us assume a flat universe $k=0$, that would lead to at a time today to \tit{critical density} given as \begin{equation} \rho_{crit,0}=\frac{3H_0^2}{8 \pi G}= 1.9 \times 10^{-29} \; h^2 \; grams \; \; cm^{-3} \end{equation} We can continue to define dimensionless density parameters given as \begin{equation} \Omega_{I,0}= \frac{\rho_{I,0}}{\rho_{crit,0}} \end{equation} and hence \eqref{Firstfriedeq} is written as \begin{equation} H^2= H_0^2 \left[\Omega_{r,0}\left(\frac{a_0}{a}\right)^4+\Omega_{m,0}\left(\frac{a_0}{a}\right)^3+\Omega_{k,0}\left(\frac{a_0}{a}\right)^2+\Omega_{\Lambda,0}\right] \end{equation} where we have defined $\Omega_{k,0} \equiv -k/(a_0 H_0)^2$ as curvature density. Or normalizing for the scale factor and using $\Omega_I$ to represent density content in today's time by dropping the zero subscript '0' and using $a_0 \equiv 1$, we get \begin{equation} H^2= H_0^2 \left[\Omega_{r}\left(\frac{1}{a}\right)^4+\Omega_{m}\left(\frac{1}{a}\right)^3+\Omega_{k}\left(\frac{1}{a}\right)^2+\Omega_{\Lambda}\right] \end{equation} \tbf{Add a summary to Friedman from page 26 to 28 of Daniel's lecture} \newpage \chapter{Inflation} \tbf{Standard cosmology predicts that the early universe was made up of many causally disconnected regions of space.} But we see that these disconnected patches of space have nearly the same densities and temperatures, this is called the \tit{Horizon Problem}. In this section we will study how an early period of accelerated expansion would resulted out an isotropic and homogeneous universe. \tbf{Here we have considered $M_{pl} \equiv \sqrt{\frac{\bar{h}c}{8 \pi G}}= 2.4 \times 10^{18} GeV$ (trading Newton's constant for reduced Planck's mass)}, so that the Friedman equation can be written as $H^2= \rho/ (3 M^2_{pl})$. \section{The Horizon Problem} \subsection{Light and Horizons} The size of the causal patch is determined by how far can light travel in a certain amount of time. For this we would utilize the advantage of working under the premise of conformal time (\tbf{in an expanding universe, the propagation of photons is best studied in conformal time}). For now, let us take the advantage of isotropy of space and consider that the light is travelling only along the radial direction. (i.e. $\theta$ and $\phi$ are constant). The evolution of path of propagation is given by the two dimensional line element \begin{eqnarray*} ds^2= a^2(\tau) \left(d \tau^2 - d \chi^2\right)\\ \tit{for propagation of photons, we know $ds^2=0$. Therefore:}\\ \end{eqnarray*} \begin{equation}\label{comoving distance} \implies d \chi = \pm d \tau \end{equation} The positive sign in the above equation represents outgoing photons while the minus sign refers to the incoming photons. \\ \tbf{Did you note the advantage of working with, conformal time?} The propagation of light rays correspond to $45^\circ$ straight lines in the $\chi- \tau$ coordinate system. If we had worked instead with physical time, the light cones in the curved space-time would had been curved. \newpage Done, with parameterisation of the problem, now we introduce two cosmological horizons \begin{itemize} \item \tbf{One which limits the distance at which past events can be observed} \tit{Particle Horizon}(The maximal distance from which we can receive signals): From, \eqref{comoving distance} we know that the maximal comoving distance that light can travel between $\tau_1$ and $\tau_2$ ($\tau_2 > \tau_1$), is $\Delta \tau = \tau_2 -\tau_1$. Now, if the big bang started at $t_i \equiv 0$\fn{the big bang singularity is a moment in time and not a point in space. The singularity can be described by extended space like hypersurface.}. Therefore, the greatest comoving distance from which an observer at time $t$ will be able to receive light or light like signals is given by \begin{equation}\label{particlehorizoneq} \chi_{ph} (\tau)=\tau - \tau_i = \int^{t}_{t_i}{\frac{dt}{a(t)}} \end{equation} This is called the comoving particle horizon. The size of the particle horizon is given by the intersection of past light cone of the observer at position p with the space like hypersurface at $\tau=\tau_i$. \tbf{All causal influences has to come within this region} \tbf{Only comoving particles with worldlines that intersect the past light cone of observer p can send a signal to the observer at p. The boundary of the region containing such worldlines is the particle horizon at p. To Note: every observer has his own particle horizon} \item \tbf{One which limits the distance it will ever be possible to obeserve future events.} \tit{Event Horizon}(The maximal distance to which we can send light signals): \tbf{here seeing the future events must be understood as ability to send light signal to a future time}. In comoving coordinates, the greatest distance from which an observer at time $t_f$ can receive signal emitted at any later time than $t$ is given by \begin{equation} \chi_{eh} (\tau)=\tau_f - \tau = \int^{t_f}_{t}{\frac{dt}{a(t)}} \end{equation} This is called the comoving event horizon. \tbf{To note: that this time may be finite even if the physical time is infinite.} Whether this is true or not depends on the form of $a(t)$. \end{itemize} \subsection*{Growing Hubble Sphere} It is the particle horizon that is relevant for the horizons problem of the standard Big Bang cosmology. Starting with the \eqref{particlehorizoneq} \begin{eqnarray*} \chi_{ph} (\tau)=\tau - \tau_i = \int^{t}_{t_i}{\frac{dt}{a(t)}}\\ \tit{let us introduce a change in variable, from t to a}\\ \de{a}{t}=\dot{a}\\ \frac{da}{\dot{a}}=dt\\ \tit{introducing this change in variable}\\ \implies \chi_{ph} (\tau)= \int^{a}_{a_i}{\frac{da}{\dot{a}a(t)}}\\ \implies \chi_{ph} (\tau)= \int^{\log a}_{\log a_i}{\frac{d \log a}{\dot{a}}}\\ \end{eqnarray*} \begin{equation}\label{Hubbleradiuseq} \implies \chi_{ph} (\tau)= \int^{\log a}_{\log a_i}{(aH)^{-1} d \log a} \end{equation} Here, $a_i \equiv 0$ corresponds to Big Bang singularity. Therefore we related the causal structure of universe of the \tit{comoving Hubble radius $(aH)^{-1}$}. For a universe dominated by a fluid with constant equation of state $w \equiv P/\rho$ we have, $(aH)^{-1}=(a H_0 a^{-\frac{3}{2}(1+w)})^{-1}=(H_0 a^{-\frac{3}{2}(1+w)+1})^{-1}=(H_0 a^{-\frac{1}{2}-\frac{3}{2}w)})^{-1}$\\\\ Finally, we get \begin{equation}\label{comovingHubbleradius} (aH)^{-1}=H_0^{-1} a^{\frac{1}{2}(1+3w)} \end{equation} Note, the dependence on $(1+3w)$. For \tbf{all familiar matter sources} satisfy the Strong Energy condition $\rho+3P >0$ or $(1+3w) >0$. This leads to a standard assumption that as the universe expands, the Hubble radius increases. On this basis the integral in \eqref{Hubbleradiuseq} is dominated by the upper limit and receives vanishing contributions form the early times. Now if we substitute \eqref{comovingHubbleradius} in \ref{Hubbleradiuseq} we get \begin{eqnarray*} \implies \chi_{ph} (\tau)= \int^{\log a}_{\log a_i}{H_0^{-1} a^{\frac{1}{2}(1+3w)} d \log a}\\ \implies \chi_{ph} (\tau)= \int^{\log a}_{\log a_i}{H_0^{-1} \frac{a^{\frac{1}{2}(1+3w)}}{a} da}\\ \implies \chi_{ph} (\tau)= \int^{\log a}_{\log a_i}{H_0^{-1} a^{({\frac{-1}{2}+\frac{3}{2}w)}} da}\\ \implies \chi_{ph} (\tau)= {H_0^{-1} \left[\frac{a^{({\frac{1}{2}+\frac{3}{2}w)}}}{({\frac{1}{2}+\frac{3}{2}w)}}\right]^{\log a}_{\log a_i} da}\\ \implies \chi_{ph} (\tau)= {H_0^{-1} \left[\frac{a^{({\frac{1}{2}+\frac{3}{2}w)}}}{({\frac{1}{2}+\frac{3}{2}w)}}\right]^{\log a}_{\log a_i} da}\\ \implies \chi_{ph} (\tau)=\frac{2H_0^{-1}}{(1+3w)} { \left[a^{({\frac{1}{2}+\frac{3}{2}w)}} - a_i^{({\frac{1}{2}+\frac{3}{2}w)}}\right] }\equiv \tau - \tau_i\\ \end{eqnarray*} The fact that the comoving horizon receives its largest contribution from late times can be made manifest by defining that the second term goes to zero vanishes for $a_i \rightarrow 0 , w>\frac{-1}{3}$. The comoving horizon is finite, \begin{equation} \chi_{ph} (\tau)=\frac{2H_0^{-1}}{(1+3w)} { \left[a^{({\frac{1}{2}+\frac{3}{2}w)}} \right] } = \tau = \frac{2H_0^{-1}}{(1+3w)} (aH)^{-1} \end{equation} \tbf{What is significance of Hubble Radius?}\\ In an ever-accelerating universe, if two particles are separated by a distance greater than the Hubble radius, they cannot talk to each other from now on (as they are now, not as they have been in the past), However, if they are outside of each other's particle horizon, they could have never communicated. \subsection{Why is the CMB so uniform?} About 380000 years after the big bang, the universe had cooled enough to allow the formation of hydrogen atom and decoupling of photons from the primordial plasma. We observe this event as CMB, and afterglow of hot bigbang. \tbf{This radiation is perfectly isotropic, with anisotropies in the CMB temperature of order $\sim 10^{-4}$}. This indicates a serious problem that,the time elapsed between $t_i=0$ and the formation of CMB ,$t_{rec}$, was finite it implies that most spots in the CMB have non overlapping past light cones and hence never were in causal contact. So how do the photons coming from p and q "know" that they should be at almos exactly the same temperature? \textbf{This applies to any two points in the sky separated by $1^{\circ}$}\fn{check out the derivation for this.} . In standard cosmology it is known that the sky is made up of $10^4$ such disconnected patches and still they look similar. \tit{This is the horizon problem.} \section{A Shrinking Hubble Sphere} Our description of the horizon problem has highlighted the fundamental role played by the growing hubble sphere. So if we want our spaces which are currently causally disconnected to have a causal connection, we would want a phase of \tbf{decreasing Hubble Radius} in the early universe. It is important to note that from \eqref{comovingHubbleradius} we would require \begin{eqnarray} \de{(aH)^{-1}}{t} = positive \times (1+3w) \times \dot{a} <0 \implies (1+3w)<0 \end{eqnarray} Therefore, for an expanding universe, physically shrinking hubble radius would require a SEC-violating fluid. \subsection{Solution to the Horizon Problem} For a shrinking hubble sphere \eqref{Hubbleradiuseq} is dominated by the lower limit. The decreasing hubble sphere also causes the Big bang singularity to be pushed in the negative conformal time as can be seen from the equation below \begin{equation} \tau_i=\frac{2H_0^{-1}}{(1+3w)} { \left[a_i^{({\frac{1}{2}+\frac{3}{2}w)}} \right] } \xrightarrow{{a_i \rightarrow 0, w<-1/3}} -\infty \end{equation} That implies that there was \tbf{"much more conformal time between the singularity and decoupling than we thought"!}. The past light cones of widely separated points in the CMB now had enough time to intersect before the time $\tau_i$. The uniformity of the CMB is not a mystery anymore. In inflationary cosmology, $\tau = 0$ isn't the initial singularity and the standard Big Bang evolution. There is time both before and after $\tau=0$. \subsection{Hubble Radius vs. Particle Horizon} Even if, in standard literature both particle horizon and Hubble radius is referred as horizon. But \tbf{the whole point of inflation is to make the particle horizon much larger than the Hubble radius.} \tbf{Finally, what is Hubble radius and particle horizon?} The Hubble radius is the comoving distance over which particles can travel in the course of expansion time. It is therefore another way of measuring whether particles are causally connected with each other. So, the end line would be that we can determine that if two particles are connected at \tit{a given moment of time}, if we compare the comoving distance between two particles $\lambda$ with Hubble radius $(aH)^{-1}$. Therefore $(aH)^{-1}$ and $\chi_{ph}$ are conceptually very different. \begin{itemize} \item if $\lambda>\chi_{ph}$ then the particles could \tbf{never} have communicated. \item if $\lambda>(aH)^{-1}$, then the particle cannot talk to each other \tit{now}. \end{itemize} \tbf{Inflation is a mechanism to achieve $\chi_{ph}>>(aH)^{-1}$. This means that particle cannot communicate now (or when the CMB was created), but were in causal contact early on. In particular, the shrinking Hubble sphere means that the particles were initially in causal contact with another - i.e. separated by a distance $\lambda<(a_I H_I)^{-1}$ can no longer communicate after a sufficiently long period of inflation. $\lambda>(a_I H_I)^{-1}$. However, at any moment before exit of the Hubble radius, the particles could still talk to each other and establish similar conditions. Everything within the Hubble sphere at the beginning of inflation $(a_I H_I)^{-1}$ was causally connected.} To note: If the entire observable universe was within the comoving Hubble radius at the beginning of the inflation i.e. $(aH)^{-1}$ was larger than the comoving radius of the observable universe $(a_0H_0)^{-1}$ then there is no horizon problem. \tbf{So, how much inflation do we need to solve the horizon problem?} Ans. At least we require that the observable universe today fits in the comoving hubble radius at the beginning of the inflation. \begin{equation} (a_0H_0)^{-1}<(a_IH_I)^{-1} \end{equation} \tbf{Answer this question , page 34} \subsection{Condition for Inflation} Let us look at how our definiton of inflation is equivalent to other popular way to describe it: \begin{itemize} \item \tit{Accelerated expansion:} We will see why inflation is also called period of accelerated expansion. \begin{equation} \de{(aH)^{-1}}{t}=\de{\dot{a}^{-1}}{t}=-\frac{\ddot{a}}{\dot{a}^2} \end{equation} and we know for shrinking hubble sphere the first term is less than zero. Therefore $\ddot{a}>0$. Therefore inflation can also be called period of accelerated expansion. \item \tit{Slowly varying Hubble parameter}: Or alternatively we would also start with \begin{eqnarray*} \de{(aH)^{-1}}{t}= -\frac{\dot{a}H+a\dot{H}}{(aH)^2}\\ \implies \de{(aH)^{-1}}{t}= -\frac{1}{a}(1-\epsilon)\\ \tit{where $\epsilon \equiv -\frac{\dot{H}}{H^2}$}\\ \tit{and as } \de{(aH)^{-1}}{t}<0 \implies \epsilon = -\frac{\dot{H}}{H^2} < 1\\ \end{eqnarray*} \item \tit{Quasi de-sitter expansion}: For inflation $\epsilon=0$, th space times becomes the de-sitter space. \begin{equation}\label{desitter} ds^2=dt^2-\exp^{2Ht}d\mbf{x}^2 \end{equation} where $H=\p_t ln a = constant$. Inflation has to end, so it should not correspond to perfect de-sitter but for very small values of $\epsilon$, the line element \eqref{desitter} is a good approximation to the inflationary background. Therefore inflation can be referred to as Quasi de-sitter space. \item \tit{Negative Pressure} \item \tit{Constant Density} \tbf{Add the last two points later. pg 36} \end{itemize} \newpage \section{The Physics of Inflation} \chapter{The Hot Universe} As we go back in time towards the Big Bang, the energy density in the universe increases. \tbf{As this happens, particles interact more and more frequently and the state of the uniform can hence be approximated by a hot fluid in equilibrium.} \tbf{As we go back in time, the Universe becomes hotter and hotter and things fall apart. Running the movie forward, the universe cools and various objects form.} A small jump in time: Let us go back to a time around 300,000 years after the Big bang when the atoms formed for the first time. Prior to this, temperature was higher than 13.6eV binding energy of hydrogen, and the elctrons were stripped from the protons. This moment is called \tbf{Recombination}. (On a side note, calling it "Combination" is more sensible as this was the time when electrons and protons combined for the first time). This is a key moment, \tbf{because prior to this time, space was filled with a charged plasma through which light is unable to propagate. But when electrons and protons form to make neutral hydrogen, the universe becomes transparent.} Before this period, the universe was so hot that nuclei would fail to cling together and they fall apart into their constituent protons and neutrons. This process which running forward in time as \tbf{Nucleosynthesis} happens around 3 minutes after the Big bang. To even earlier times, the universe was much more hotter and at energies probed by the particle accelerators. At some point as we look further back in time, the QCD phase transition takes place, protons and neutrons melt and dissolve into a hot soup of quark gluon plasma. Earlier still, at the electroweak phase transition, the condensate of Higgs Boson melts. \section{The Hot Big Bang} The key to underdstand thermal equilibroum in universe is to understand two time scales: \tit{time scale of particle interaction} and \tit{characteristic expansion time}. Thermal equilibrium will be reached when interaction time of particles is much less than characteristic expansion time of universe \begin{equation*} t_c \equiv \frac{1}{\Gamma} << t_H \equiv \frac{1}{H} \end{equation*} where $\Gamma$ is the rate of interaction of particles and $H$ is the rate of expansion of Universe. As the universe cools down the rate of interaction decreases faster than the rate of expansion and hence at one time $t_c \sim t_H$, at this time the particles decouple from thermal bath, they are no longer in equilibrium because they no longer interact. At this time particle is said to be decoupled. Different species have different interaction rates and hence decouple at different times. \section{The CMB} The universe is in this bath tub if thermal radiation called the Cosmic Microwave Background or CMB. This is was the first piece of evidence for the hot big bang. \section*{Some Statistical Mechanics} In this section we will build the mechanics that will allow us describe the hot stuff.\\ It is important to note that, there is no such thing, for example, the temperature of a single electron and instead these properties are the result of what we call as \tbf{The Emergent Phenomena}, which arises only when a sufficiently large number of particles are thrown together. While we are acquainted to use the number of particles $N \sim 10^{23}$; in cosmological setting this magnitude can be substantially larger. I can \tbf{to be studied} \subsection{The Boltzmann Constant} We will focus on states in thermal equilibrium. For a system with discreete energy eigen states $\ket{n}$, each with energy Eigen values $E_m$. In thermal equilibrium, the probability that the system sits in thermal equilibrium at temperature T, is given by the \tit{Boltzmann Distribution} \begin{equation} p(n)=\frac{e^{-E_n/K_BT}}{Z} \end{equation} Where $Z$ is the partition function. It is important to note that for the states with $E_n<<K_BT$ each state has more or less equlal chances of getting occupied. While for $E_n>>K_BT$ has vanishingly small chance of being occupied. Therefore, $K_bT$ sets the characteristic energy scale of the system. \fn{More parts can be added} \subsection{The Ideal Gas} So, even though we have said that interactions are necessary to drive the system in equilibrium, but while studying equilibrium mechanics we are going to dump it by arguing that, \tbf{Interactions are strong enough to drive the system in equilibrium but can we neglected when describing the mechanics.} It is still important to remember that interactions will be necessary, when we describe the phenomena of decoupling. If the momentum is continuous we should talk about the probability lies in a volume $d^3\mbf{v}$ centered around $\mbf{v}$, given that the particle is of mass m, momenta $\mbf{p}$ and velocity $\mbf{v}=\mbf{p}/m$. So if the corresponding probability distribution is given by $f(\mbf{v})d^3\mbf{v}$ which is given by \begin{equation}\label{probabilitydisteq} f(\mbf{v})d^3v=\frac{e^{-\beta m v^2/2}}{Z}d^3v \end{equation} Now, let the our velocity of interest is $v=|\mbf{v}|$ and hence the probability distribution is $f(v)dv=f(\mbf{v})d^3v$ then from \eqref{probabilitydisteq} is given as, \begin{eqnarray} f(\mbf{v})d^3v=\frac{e^{-\beta m v^2/2}}{Z}d^3v \implies f(v)dv=\frac{4 \pi v^2 e^{-\beta m v^2/2}}{Z}dv \end{eqnarray} Therefore, as opposed to $\mbf{v}$ we have $4 \pi v^2$ factor associated when we consider the distribution for $v$. Now, we require that \dint{\infty}{0}{f(v)dv}=1. Therefore, \begin{eqnarray} \int^\infty_0 f(v) dv =1 \implies \int^\infty_0 \frac{4 \pi v^2 e^{-\beta m v^2/2}}{Z}dv =1 \\ \implies Z=\left(\frac{2 \pi K_B T}{m}\right)^{3/2} \end{eqnarray} and hence \begin{equation} f(v)dv=\frac{4 \pi v^2 e^{-\beta m v^2/2}}{\left(\frac{2 \pi K_B T}{m}\right)^{3/2}}dv \end{equation} This is MB distribution and tells us the distribution of the speed of gas molecules in this room. \subsection*{Pressure and Equation of State} \section{The CMB} \subsection{Black Body Radiation} We want to derive the properties of a thermal gas of photons, Such a gas is known as $Blackbody radiation$ Now, the state of a single photon is given by its momentum, $\mbf{p}= \bar{h}\mbf{k}$ where $\mbf{k}$ is the wavevector. The energy of this photon is given by \begin{equation} E=pc=\hbar\omega \end{equation} where $\omega = ck$ is the angular frequency of photon. Because the photon number is not conserved, we state the number of photons in one state $N(\mbf{p})$ sit in the state $\mbf{p}.$ In thermal equilibrium, we will not have a definite number of photons N($\mbf{p}$) In thermal equlibrium, we will not have a definite number of photons $N(p)$, but rather some probability distribution over the number of photons, focusing on a fixed state $\mbf{p}=\hbar \mbf{k}$, the average number of particles is dictated by Boltzman distribution \begin{equation} \left\langle N(p)\right\rangle=\frac{1}{Z}\sum^\infty_{n=0} n e^{-\beta n \hbar \omega} \end{equation} \tbf{Not derived. Derive this} We learn the average number of particles with momentum$\mbf{p}$ is \begin{equation} \label{Averagenoeq} \left\langle N(p)\right\rangle = \frac{1}{e^{\beta \hbar \omega} - 1} \end{equation} \subsection*{Density of States} Let us count the number of states $\mbf{p}$ which have energy $\hbar \omega$ after which we an calculate the average number of photons with given energy $\hbar \omega$. It is easier to count objects that are discrete rather than continuous. For this reason, we will put our system in a square boz with sides of length L. At the end of the calculation, we will send $L \rightarrow \infty$. In such a boz, the wavevector is quantised: it takes the values \begin{equation} k_i=\frac{2 \pi q_i}{L} \;\;\; q_i \epsilon \mbf{Z} \end{equation} This is true for both a classical wave or a quantum particle; in both cases, an integer number of wavelengths must fit in the box. Different states are labelled by the integers $q_i$. When counting, or summing over such the states, we should therefore sum over the $q_i$. However, for very large boxes, so that L is mych bigger than any other length scale in the game, we can approximate this sum by an integral \begin{eqnarray} \sum_q \approx \frac{L^3}{(2 \pi)^3} \int d^3k= \frac{4 \pi V}{(2 \pi)^3}\int^\infty _0 dk k^2 \\ \tit{or, we can use the relation that $\omega=ck$}\\ =\frac{4 \pi V}{(2 \pi c)^3}\int^\infty_0 d \omega \omega^2 \end{eqnarray} where $V=L^3$ is the volume of the box. The final form means that the number of states with the magnitude of the waveform between k and k+dk is $4 \pi V k^2/(2 \pi)^3$. It is also important to note that the photon comes in two polarisation states. This means that the total number of states is twice the number above and from \eqref{Averagenoeq} \begin{equation} \left\langle N(p)\right\rangle d\omega = 2 \times \frac{4 \pi V}{(2 \pi c)^3} d \omega \omega^2 \frac{1}{e^{\beta \hbar \omega} - 1} \end{equation} Now we have number density $n=N/V$ given as \begin{equation} n=(\left\langle N(p)\right\rangle)/V = 2 \times \frac{4 \pi }{(2 \pi c)^3} d \omega \omega^2 \frac{1}{e^{\beta \hbar \omega} - 1}= \frac{1}{\pi^2 c^3}\frac{\omega^2}{e^{\beta \hbar \omega}-1} \end{equation} This is the Planck blackbody distribution. For a fixed temperatur, $\beta = 1/K_BT$, the distribution tells us how many photons of a given frequency. \subsection*{The Equation of State} Now, let us find, the equation of state. First the energy density, we integrate \begin{eqnarray*} \rho = \int^\infty_0 d\omega \hbar \omega n(\omega)\\ \implies \rho = \int^\infty_0 d\omega \hbar \omega \frac{1}{\pi^2 c^3}\frac{\omega^2}{e^{\beta \hbar \omega}-1}\\ \implies \rho = \hbar \frac{1}{\pi^2 c^3} \int^\infty_0 d\omega \frac{\omega^3}{e^{\beta \hbar \omega}-1} \end{eqnarray*} Now, let us look at pressure, for maxwell distribution of particles the pressure on the wall is \begin{equation} P=\frac{1}{3} \int dv n \mbf{v.p}f(v) \end{equation} Now with $\mbf{v.p}=\hbar ck=\hbar\omega$ we get \begin{equation} P=\frac{1}{3} \int dv n \hbar\omega f(v) \end{equation} This expression is same as that of the energy density with an extra factor of $1/3$. \begin{equation} P=\frac{1}{3}\rho \end{equation} This is the equation of state, which we had also used to describe the expanding universe. We return back to the integral \begin{eqnarray*} \rho = \hbar \frac{1}{\pi^2 c^3} \int^\infty_0 d\omega \frac{\omega^3}{e^{\beta \hbar \omega}-1}\\ \implies \rho = \frac{K_BT^4}{\hbar^3 \pi^2 c^3} \int^\infty_0 dy \frac{\omega^3}{e^y-1}\\ \end{eqnarray*} Here we have to use the integral \begin{eqnarray*} I_n=\int^\infty_0 dy \frac{y^{s-1}}{e^y-1}\\ =\sum_{n\leq 1} \int^{+\infty}_0 x^{s-1} e^{-nx} dx =^{x \rightarrow z/n} \sum_{n\leq 1} \frac{1}{n^s} \int^{+\infty}_0 z^{s-1} e^{-z} dz\\ =\Gamma(s) \sum_{n \leq 1} \frac{1}{n^s}\\ =\Gamma(s) \zeta(s) \end{eqnarray*} It turns out that $\zeta(4)= \pi^4/15$ and $I_3=\pi^4/15$ and $\zeta(3) \approx 1.20$ Therefore, the energy density is \begin{equation} \rho = \frac{K_BT^4}{\hbar^3 c^3} \frac{\pi^2}{15} \end{equation} Meanwhile, the total number density \begin{equation} n=\int^\infty_0 d\omega n(\omega)=\frac{1}{\pi^2 c^3} \int^\infty_0 d\omega \frac{\omega^2}{e^{\beta \hbar \omega}-1} = \frac{(K_BT)^3}{\pi^2 \hbar^3 c^3} \int^\infty_0 dy \frac{y^2}{e^y-1}=\frac{2 \zeta(3)}{\pi^2 \hbar^3 c^3}(K_BT)^3 \end{equation} \subsection{The CMB today} The universe is filled with a background of photons which is a perfect fit to the blackbody spectrum, with atemperature \begin{equation} T_{CMB}= 2.726 \pm 0.0006 K \end{equation} In observations we have seen the deviations of order \begin{equation} \frac{\Delta T}{T_{CMB}} \sim 10^{-5} \end{equation} From the temperature we can determine $T_{CMB}$ we can insert it in the energy density equation \begin{eqnarray*} \rho = \frac{\pi^2}{15\bar{h}^3 c^3}(K_B T)^4\\ \implies \rho = \frac{9.86}{15 (3.16 \times 10^{-26} m^3 Kg/s^2)^3}(1.38 \times 10^{-23} \times 2.73)^4\\ \implies \rho = \frac{0.02}{(10^{-26} m^3 Kg/s^2)^3}199.87 \times (10^{-23})^4\\ \implies \rho = 0.02 \times 199.87 \times (10^{-14})\\ \implies \rho = 3.99 \times (10^{-14}) \sim 4 \times 10^{-14} Kg \; m^{-1} s^{-2} \end{eqnarray*} When we compare this to the the $\rho_{crit,0}= 8.5 \times 10^{-10} Kg m^{-1} s^{-2}$ to find, \begin{equation} \Omega_{\gamma}=\frac{\rho_{\gamma}}{\rho_{crit,0}}= \frac{4 \times 10^{-14}}{8.5 \times 10^{-10}} \approx 5 \times 10^{-5} \end{equation} We can find the number density from the equation \begin{equation} n=\frac{2\zeta(3)}{\pi^2 \bar{h}^3 c^3}(K_BT)^3 \end{equation} where $\zeta(3) \approx 1.20$. Therefore,\fn{check out this calculation the answer possibly is $4 \times 10^8 m^{-3}$} \begin{eqnarray*} n=\frac{2\zeta(3)}{\pi^2 \bar{h}^3 c^3}(K_BT)^3\\ \implies n=\frac{2.40}{9.86 \times (3.16 \times 10^{-26} m^3 Kg/s^2)^3}(1.38 \times 10^{-23} \times 2.73)^3\\ \implies n=\frac{2.40}{9.86 \times 31.55 \times( 10^{-26} m^3 Kg/s^2)^3}(1.38 \times 10^{-23} \times 2.73)^3\\ \implies n=\frac{2.40}{311.083 \times( 10^{-26} m^3 Kg/s^2)^3} 201.45 \times (10^{-23} )^3\\ \implies n=\frac{2}{( 10^{-26} m^3 Kg/s^2)^3}\times (10^{-23} )^3\\ \implies n=2 \times 10^{9}\\ \end{eqnarray*} \subsection{The Saha Equation} Let us consider a gas of electrons and protons in equilibrium at some temperature. They have the possibility to combine and form hydrogen. Now we have this equation given by \begin{equation} e^{-}+p^{+} \xleftrightarrow \; H+\gamma \end{equation} The question we ask is what proportion of the particles are hydrogen, and what proportions are electron-proton pairs? To simplify life, we assume that the hydrogen is in ground state with binding energy \begin{equation} E_{bind} \sim 13.6 eV \end{equation} This is a bad idea! Naively, we would expect hydrogen to ionize when we reach temperatures of $K_BT >> E_{bind}$, the electrons can no longer cling on to the protons, and any hydrogen atom is surely ripped apart. When we check out the maths, it will ultimately turn out that hydrogen only forms at temperatures significantly lower than the $E_{bind}$. We will treat each of the massive particles - the electron, proton and hydrogen atom as non relativistic gas. Each particle has energy \begin{equation} E_{p}= mc^2 + \frac{p^2}{2m} \end{equation} Now we can write the binding energy equation \begin{equation}\label{bindingenergyeq} (m_e+m_p-m_H)c^2=E_{bind} = 13.6eV \end{equation} Now each of the particle comes with g number of internal states. The electron and proton each have $g_p=g_e=2$ corresponding to the two spin states,"spin up" and "spin down". For hydrogen has $g_H=4$,electron and proton spin can either be aligned, to give a spin 0 particle, or anti-aligned to give 3 different spin 1 states. The number density of the different species of particles is given by \begin{equation}\label{numberdensity} n_i=g_i\left(\frac{m_iK_BT}{2 \pi \bar{h}^2}\right)^{3/2} \exp^{-\beta (m_i c^2-\mu_i)} \end{equation} It is to take note that the rest mass energy $mc^2$ in the energy can be absorbed by a constant shift of the chemical potential. We require that the particles are in chemical equilibrium, this means that there is no rapid change from the $e^- + p^+$ pairs into hydrogen. The number of electrons, protons and hydrogen are balanced. For chemical equilibrium, the chemical potentials are related as \begin{equation}\label{chemicaleq} \mu_e + \mu_p = \mu_H \end{equation} If two systems are in thermal equilibrium, when brought together, there is no net flux of energy from one to another. \tbf{Do we require chemical potential for phtotons?} Ans. A reaction can result in two photons and the number is not conserved. Let us use the condition for chemical potential in \eqref{numberdensity} for our reaction. \begin{eqnarray*} \frac{n_H}{n_e n_p}=\frac{g_H\left(\frac{m_HK_BT}{2 \pi \bar{h}^2}\right)^{3/2} \exp^{-\beta (m_H c^2-\mu_H)}}{g_e\left(\frac{m_eK_BT}{2 \pi \bar{h}^2}\right)^{3/2} \exp^{-\beta (m_e c^2-\mu_e)} g_p\left(\frac{m_pK_BT}{2 \pi \bar{h}^2}\right)^{3/2} \exp^{-\beta (m_p c^2-\mu_p)}}\\ \implies \frac{n_H}{n_e n_p}=\frac{g_H}{g_e g_p}\left(\frac{m_H}{m_p m_e}\frac{2 \pi \bar{h}^2}{K_BT}\right)^{3/2}\exp^{-\beta (m_H c^2 -m_e c^2 -m_p c^2+\mu_p +\mu_e -\mu_H)}\\ \tit{Using the condition \eqref{chemicaleq} we get}\\ \implies \frac{n_H}{n_e n_p}=\frac{g_H}{g_e g_p}\left(\frac{m_H}{m_p m_e}\frac{2 \pi \bar{h}^2}{K_BT}\right)^{3/2}\exp^{-\beta (m_H -m_e -m_p)c^2}\\ \end{eqnarray*} In the pre-factor, it makes sense to approximate $m_H \sim m_p$. However in the exponent the difference between these masses is crucial; it is the binding energy of Hydrogen \eqref{bindingenergyeq}. \tbf{Now we use the observed fact that the universe is electrically neutral, so} \begin{equation} n_e=n_p\\ \end{equation} We then have \begin{equation}\label{sahaeq} \frac{n_H}{n_e^2}=\left(\frac{2 \pi \bar{h}^2}{m_e K_BT}\right)^{3/2}\exp^{\beta E_{bind}} \end{equation} This is the \tbf{The Saha Equation}. We started with the problem to understand the fraction of electron and Hydrogen pair that have combined to form Hydrogen. To this end, we define \tit{the ionisation fraction}. \begin{equation*} X_e= \frac{n_e}{n_B} \sim \frac{n_e}{n_p + n_H} \end{equation*} In the second equality we are ignoring neutrons and higher elements (\tbf{This is a good approximation!}). Since $n_e=n_p$, if $X_e=1$ it means that all electrons are free. If $X_e=0.1$ it means that only $10 \%$ of the electrons are free, the remainder bound inside Hydrogen. Using $n_e=n_p$, \begin{eqnarray*} 1 - X_e= 1- \frac{n_e}{n_p + n_H}\\ =\frac{n_p +n_H - n_e}{n_p+n_H}\\ =\frac{n_H}{n_p+n_H}\\ \implies 1 - X_e=\frac{n_H}{n_B} \end{eqnarray*} Therefore, now we try to find: \begin{eqnarray*} \frac{1-X_e}{X_e^2}=\frac{\frac{n_H}{n_B}}{\left(\frac{n_e}{n_B}\right)^2}\\ \implies \frac{1-X_e}{X_e^2}=\frac{n_H}{\left(n_e\right)^2}n_B \end{eqnarray*} Even though the Saha Equation gives us an expression for $\frac{n_H}{\left(n_e\right)^2}$. But to translate this into the fraction $X_e$, we also need to know the number of Baryons. We take from observation, we convert the number of baryons into the number of photons \fn{calculate this one!} \begin{equation} \eta=\frac{n_B}{n_\gamma}\sim 10^{-9} \end{equation} We will use the fact that $\eta \sim 10^{-9}$ has remained constant since recombination. Now we use the fact that photons sit at the temperature as the electrons, protons and hydrogen because they are all in equilibrium. This fact will allow us to utilize the expression \begin{equation}\label{photonno} n_\gamma=\frac{2\zeta(3)}{\pi^2 \bar{h}^3 c^3}(K_BT)^3 \end{equation} for the number of photons. \begin{eqnarray*} \frac{1-X_e}{X_e^2}=\left(\frac{2 \pi \bar{h}^2}{m_e K_BT}\right)^{3/2}\exp^{\beta E_{bind}} n_B\\ \tit{using the equation \eqref{photonno}}\\ \implies \frac{1-X_e}{X_e^2}=\left(\frac{2 \pi \bar{h}^2}{m_e K_BT}\right)^{3/2}\exp^{\beta E_{bind}} \eta n_\gamma\\ \implies \frac{1-X_e}{X_e^2}=\eta \left(\frac{2 \pi \bar{h}^2}{m_e K_BT}\right)^{3/2}\exp^{\beta E_{bind}} \frac{2\zeta(3)}{\pi^2 \bar{h}^3 c^3}(K_BT)^3\\ \end{eqnarray*} \begin{equation}\label{fractionelectroneq} \frac{1-X_e}{X_e^2}=\eta \left(\frac{2 \pi K_BT}{m_e c^2}\right)^{3/2} \frac{2\zeta(3)}{\pi^2 } \exp^{\beta E_{bind}} \end{equation} Let us run some analysis. First, $K_BT \sim E_{bind}$, we thought to be the temperature when recombination takes place. When we look closely in the above expression, we see that there are two very small numbers in the game: factor of $\eta \sim 10^{-9}$ and $K_BT/m_ec^2$ where the electron mass is $m_ec^2 \sim 0.5MeV$. This ensure that the $K_BT \sim E_{bind}$, this makes $X_e$ is very close to unity. Or we can say that , all electrons remain free and unbound. \tbf{In large part this is of the enormous number of photons, which mean that whenever a proton and electron bind, one can still find a sufficient high energy photons in the tail of the blackbody distribution to knock them apart.} Recombination only takes place when the $\exp{\beta E_{bind}}$ factor is sufficient to compensate both the $\eta$ and $K_BT/m_ec^2$ factors. Recombination is not a one of process, it happens continuously as the temperature varies. We will calculate the temperature when $X_e=0.1$, so $90\%$ of the electrons are sitting happily in their hydrogen homes. \begin{eqnarray} \frac{1-X_e}{X_e^2}=\eta \left(\frac{2 \pi K_BT}{m_e c^2}\right)^{3/2} \frac{2\zeta(3)}{\pi^2 } \exp^{\beta E_{bind}}\; \; \tit{use $X_e=0.1$}\\ \frac{0.9}{0.01}=\eta \left(\frac{2 \pi K_BT}{m_e c^2}\right)^{3/2} \frac{2\zeta(3)}{\pi^2 } \exp^{\beta E_{bind}}\\ 90=\eta \left(\frac{2 \pi K_BT}{m_e c^2}\right)^{3/2} \frac{2\zeta(3)}{\pi^2 } \exp^{\beta E_{bind}}\\ \end{eqnarray} \tbf{I dont understand this calculation. pg 101} From the above calculations, we find $\beta E_{bind} \sim 45$ or $K_BT_{rec} \sim 0.3 eV \implies T_{rec}\sim 3600K$. This correspond to a redshift of \begin{equation} z_{rec}=\frac{T_{rec}}{T_0} \sim 1300 \end{equation} Now, this is significantly later than matter- radiation equality $z_{eq} \sim 3400$. This means that during recombination universe is matter dominated, with $a(t) \sim (t/t_0)^{2/3}$. We can therefore date the time recombination to, \begin{equation} t_{rec} \sim \frac{t_0}{(1+z_{rec})^{3/2}} \sim 300,000 \tit{years} \end{equation} After recombination, the constituents of the universe have been mostly neutral atoms. Roughly speaking this means that the \tbf{universe is transparent and photons can propagate freely.} Let us look at the story more closely. \section*{Mea Culpa} Things are more complicated compared to the story we have seen above. At the time of recombination the temperature is much lower than the $13.6eV$ binding energy of the $1s$ state of hydrogen. This means that whenever a 1s state forms, it emits a photon which has significantly higher energy than the photons in thermal bath. The most likely outcome is that this high energy photon hits a different hydrogen atom, splitting into constituent proton and electron, this results in no net change in the number of atoms! \tbf{Instead, recombination must proceed through a rather more tortuous route.} The hydrogen atom does not just have a ground state: there a whole tower of excited states. These can form without emitting a high energy photon, and indeed at low thermal bath temperatures, these excited states of hydrogen atom are in equilibrium with the thermal bath. There are then two inefficient processes that populate the 1s state. A transition from 2s to 1s by emission of two photons (to preserve angular momentum) may happen, but the photon in released in this process does not have the energy to ionize other atoms. Alternatively, the 2p states can decay to 1s but still does not have enough energy to ionize other atoms. Moreover, if this photon experiences a redshift, it can no longer do the job and we can still continue to increase the number of atoms in the ground state. \subsection{Freeze out and last scattering} Photons interact with electric charge. After electrons and protons combine to form neutral hydrogen, the photon scatter much less frequently and the universe becomes transparent. After this time , the photons are essentially decoupled. These kind of scenarios have occured a number of times in the universe when a set of particles which once interacted frequently, stop interating eventually and evolve without care of what environment they are in. \tbf{An expanding universe is a time dependent background in which the concept of equilibrium does not apply. } For a system to be in equilibrium, the constituent particles must frequently interact, exchanging energy and momentum. So let us assign a certain interaction rate $\Gamma$ to a particle. A particle on average would interact with another particle in a time $t=1/\Gamma$. But, remember, it makes sense to talk about equilibrium provided the universe has not changed significantly over the course of interaction time $t_{int}$. The expanding universe is governed by the Hubble parameter, so if we have to talk about equilibrium then we would require that \begin{equation} \Gamma >> H \tit{ or } t_{int}<<t_{expansion} \end{equation} While for a system not in equilibrium we would require \begin{equation} \Gamma << H \tit{ or } t_{int}>>t_{expansion} \end{equation} For all processes, interaction is necessary to maintain equilibrium. \tbf{For many processes, both the interaction rate and temperature scale with T, but in different ways. The result is that particles retain equilibrium at certain times, but decouple from the thermal bath at late time. } This decoupling occurs when $\Gamma \sim H$ and is known as \tbf{Freeze Out!} We now apply the same idea, to the freeze out which goes by the name \tit{The Last scattering}. In the early universe , the scattering of photon was primarily due to electrons in a process called Thomson scattering.. In this case, the scattering is elastic therefore the energy and hence the frequency of photon is unchanged in this process. \begin{equation} e+\gamma \rightarrow e+\gamma \end{equation} For this scattering, the interaction rate is \begin{equation} \Gamma=n_e \sigma_Tc \end{equation} where $\sigma_T$ is the cross-section, a quantity that characterises the strength of scattering. Now, from elctromagnetism, \begin{equation} \sigma_T=\frac{\mu_0^@ e^4}{6 \pi m_e^2 c^2} \sim 6 \times 10^{-30} \tit{ } m^2 \end{equation} We note that the scattering crossection for electrons depends on mass of the electron and hence the scattering crossection of protons would had been a lot smaller. Now, coming to the last scattering, the temperature $T_{last}$ such that $\Gamma(T_{last}) \approx H_{last}$. We can express the interaction rate by replacing the number density of electrons with the number density of photons, \begin{equation} \Gamma(T_{last})=n_B X_e(T_{last})\sigma_Tc=\eta\frac{2\zeta(3)}{\pi^2 \bar{h}^3 c^3}(K_BT)^3 X_e(T_{last})\sigma_Tc \end{equation} And, to compute $H(T_{last})$, we use: \begin{equation} \left(\frac{H}{H_0}\right)^2= \frac{\Omega_r}{a^4}+\frac{\Omega_m}{a^3}+\frac{\Omega_k}{a^2}+\Omega_k \end{equation} At recombination, only matter term is important and hence \begin{eqnarray*} \left(\frac{H}{H_0}\right)^2 \approx \frac{\Omega_m}{a^3}\\ \tit{Or knowing the fact that temperature scales as $T \sim 1/a$}\\ \implies H(T_{last})=H_0 \sqrt{\Omega_m}\left(\frac{T_0}{T}\right)^{3/2} \end{eqnarray*} Now we equate the final expression with $\Gamma(T _{last})$ to solve for $X_e$ \begin{eqnarray*} H_0 \sqrt{\Omega_m}\left(\frac{T_0}{T}\right)^{3/2}=\eta\frac{2\zeta(3)}{\pi^2 \bar{h}^3 c^3}(K_BT)^3 X_e(T_{last})\sigma_Tc\\ \implies X_e(T_{last})=\frac{H_0 \sqrt{\Omega_m}\left(\frac{T_0}{T}\right)^{3/2}}{\eta\frac{2\zeta(3)}{\pi^2 \bar{h}^3 c^3}(K_BT)^3 \sigma_Tc}\\ \end{eqnarray*} Now using the \eqref{fractionelectroneq} we can calculate $X_e(T_{last})$, we will find that\fn{do the calculation} photons stop interacting with matter only when \begin{equation} X_e(T_{last})\approx 0.01 \end{equation} We see that the vast majority of electrobs must be housed in neutral hydrogen, with only $ 1\% $ of free electrons remaining, before light can travel freely. This corresponds to a temperature \begin{equation} K_{B}T_{last} \approx 0.27 eV \implies T_{last} \approx 3100 K \end{equation} and, correspondingly, a time somewhat after recombination, \begin{equation} z_{last}=\frac{T_{last}}{T_0} \approx 1100 \implies t_{last}=\frac{t_0}{(a+z)^{3/2}}\approx 350000 years \end{equation} Here, $t_0 = 13.7 \tit{billion years}$ and $T_0=2.73 K$\\ So, after this time the universe becomes transparent, the universe becomes transparent. \tbf{The CMB is a snapshot of the universe from this time.} \section{Bosons and Fermions} \tbf{The introduction to Fermion and Boson from the notes to be added.} There is one of the most fundamental properties of boson and fermions that can be depicted as The particles are called bosons if the wavefunction is symmetric under exchange of particles. \begin{equation} \psi(\mbf{x1,x2})=\psi(\mbf{x2,x1}) \end{equation} while the particles are called fermions if the wavefunction is asymmetric under exchange of particles. \begin{equation} \psi(\mbf{x1,x2})=- \psi(\mbf{x2,x1}) \end{equation} Importantly, if we try to put two fermions on top of each other than the wavefunction vanishes: $\psi(\mbf{x,x})=0$. The particle also has an intrinsic angular momentum carried by elementary particles called spin. Particles that have integer spin are bosons; particles that have half-integer spin are fermions. Other than photons, W and Z-bosons (which are responsible for the weak nuclear force) and gluons (responsible for the strong nuclear force). The only elementary spin 0 particle is the Higgs boson. Finally the graviton has spin 2. To determine whether the atoms are boson or fermion, now while the number of electron and proton are equal, the number of neutrons determine whether the atoms are boson or fermion. \section{Bose Einstein and Fermi Dirac Distribution } Here while describing the probability distribution function we will restrict our attention to non interacting species. In order to describe this particle we will describe the state of a single particle by its momentum $\mbf{p=\hbar k}$. \fn{we will take into account the spin and polarisation degrees of freedom later.}. Now the single particle state is described by state \ket{\mbf{p}} and for a relativistic particle the eneergy of state \ket{\mbf{p}} is given by \begin{equation} E_{\mbf{p}}= \sqrt{m^2c^4+p^2c^2} \end{equation} and to specify the full state, the full multi particle state is given by \ket{n}, we need to specify the number of particles $n_p$ occupying each state $\mbf{p}$. The number of particles for boson and fermions is given by \begin{eqnarray*} Bosons: \; \ ; n_p=0,1,2 \cdots\\ Fermions \; \; n_p=0,1 \end{eqnarray*} Previously done counting through M-B distribution is appropriate for bosons in non relativistic case. Now, let's do some counting for Bosons. For a given momentum $\mbf{p}$, the average number of photons is \begin{equation}\label{countingbsoneq} \left\langle N(\mbf{p}) \right\rangle = \frac{1}{\mbf{Z_p}}\sum^{\infty}_{n_p=0}n_pe^{\beta(n_pE_p-\mu n_p)}=\frac{1}{\beta}\frac{\p}{\p \mu} \log \mbf{Z_p} \end{equation} where \begin{equation}\label{bsonparteq} \mbf{Z_p}=\sum^\infty_{n=0}e^{-\beta n_p(E_p-\mu)}=\frac{e^{\beta(E_p-\mu)}}{e^{\beta(E_p-\mu)} - 1} \end{equation} Hence using \eqref{bsonparteq} in \eqref{bsonparteq} we have: \begin{eqnarray*} \left\langle N(\mbf{p}) \right\rangle =\frac{1}{\beta}\frac{\p}{\p \mu} \log \mbf{Z_p}\\ \implies \left\langle N(\mbf{p}) \right\rangle = \frac{1}{\beta}\frac{\p}{\p \mu} \log \frac{e^{\beta(E_p-\mu)}}{e^{\beta(E_p-\mu)} - 1}\\ \implies \left\langle N(\mbf{p}) \right\rangle = \frac{1}{\beta} \frac{1}{\frac{e^{\beta(E_p-\mu)}}{e^{\beta(E_p-\mu)} - 1}}\frac{- \beta e^{\beta(E_p-\mu)} (e^{\beta(E_p-\mu)} - 1) + \beta e^{-\beta(E_p-\mu)} (e^{\beta(E_p-\mu) })}{(e^{\beta(E_p-\mu)} - 1)^2}\\ \implies \left\langle N(\mbf{p}) \right\rangle = \frac{1}{\beta} \frac{-\beta (e^{\beta(E_p-\mu)} - 1) + \beta e^{\beta(E_p-\mu)}}{(e^{\beta(E_p-\mu)} - 1)}\\ \end{eqnarray*} \begin{equation} \implies \left\langle N(\mbf{p}) \right\rangle = \frac{ 1}{(e^{\beta(E_p-\mu)} - 1)} \end{equation} This is Bose-Einstein distribution. For fermions, We have \begin{eqnarray*} N(\mbf{p})= \frac{1}{\mbf{Z_p}}\sum_{n_p=0,1}n_pe^{-\beta(n_pE_p-\mu n_p)} \\ \implies N(\mbf{p})= \frac{1}{\mbf{Z_p}} e^{-\beta(E_p-\mu)} \\ \implies N(\mbf{p})= \frac{e^{-\beta(E_p-\mu)}}{1 + e^{-\beta(E_p-\mu)}} \\ \end{eqnarray*} \begin{equation} \implies N(\mbf{p})= \frac{1}{1 + e^{\beta(E_p-\mu)}} \end{equation} This is the fermi-dirac distribution.\\ where, \begin{eqnarray*} \mbf{Z_p}= \sum_{n_p=0,1}e^{-\beta(n_pE_p-\mu n_p)}\\ \implies \mbf{Z_p}= 1 + e^{-\beta(E_p-\mu)} \end{eqnarray*} All calculations now would require density of states calculation which will give us the number of internal states by integrating over all momenta states and multiplying with number of states and state degeneracy factor $g$. \begin{eqnarray*} n=N/V\\ N=\frac{V}{(2 \pi \hbar)^3} \int d^3p N(\mbf{p})\\ \implies n= \frac{\frac{g V}{(2 \pi \hbar)^3} \int d^3p N(\mbf{p})}{V}\\ \tit{the $g$ does the job of giving the number of internal states}\\ \tit{ in momenta $\mbf{p}$ } \end{eqnarray*} \begin{equation} n= \frac{g }{(2 \pi \hbar)^3} \int d^3p N(\mbf{p}) \end{equation} \\ Similarly the energy density is given by \begin{equation} \rho=\frac{g }{(2 \pi \hbar)^3} \int d^3p N(\mbf{p}) E_{\mbf{p}} \end{equation} and the pressure is \begin{equation} P=\frac{g }{(2 \pi \hbar)^3} \int d^3p N(\mbf{p}) \frac{\mbf{v.p}}{3} \end{equation} \subsection{case of ultra-relativistic gases} \tbf{When are particles considered in ultra relativistic limit?}\\ As we go back in time, the universe gets hotter and hotter. Now, in case if the thermal energy is greater than mass energy \begin{equation*} K_BT >> 2mc^2 \end{equation*} In this regime, particle-antiparticle pairse can be created in the fireball. At this stage, both the mass and the chemical potential are negligible. At this point particles can be said to be in \tbf{ultra-relativistic} and then their energies are given by \begin{equation*} E_\mbf{p} \approx pc \end{equation*} just as for massless particles. \tbf{Now it is important that we have equal number of particles and anti-particles. What do we do to ensure that?} In order to ensure equal number of particle and anti particle occupying a particular energy state, we use the condition $\mbf{\mu}=0$. Now, let us calculate the parameters for bosons and fermions. \tbf{Calculating parameters for bosons first} Number density for bosons: \begin{eqnarray*} n= \frac{g }{(2 \pi \hbar)^3} \int d^3p N(\mbf{p})\\ \implies n_{b}= \frac{g }{(2 \pi \hbar)^3} \int d^3p \frac{ 1}{(e^{\beta(E_p)} - 1)}\\ \implies n_{b}= \frac{ 4 \pi g}{(2 \pi \hbar)^3} \int dp \frac{ p^2}{(e^{\beta(pc)} - 1)}\\ \tit{Let $\beta pc = y$, therefore $p^2=\frac{y^2}{\beta^2 c^2}$ and $dp=\frac{dy}{\beta c}$}\\ \implies n_{b}= \frac{ 4 \pi g}{(2 \pi \hbar \beta c)^3 } \int dy \frac{ y^2}{(e^{y} - 1)}\\ \implies n_{b}= \frac{ 4 \pi g}{(2 \pi \hbar \beta c)^3 } I_2\\ \end{eqnarray*} energy density for bosons: \begin{eqnarray*} \rho = \frac{g}{(2 \pi \hbar)^3} \int d^3p N(\mbf{p})E_{\mbf{p}}\\ \implies \rho_b = \frac{g 4 \pi}{(2 \pi \hbar)^3} \int dp \frac{ p^2}{(e^{\beta(E_p)} - 1)} E_{\mbf{p}}\\ \implies \rho_b = \frac{g 4 \pi}{(2 \pi \hbar)^3} \int dp \frac{ p^2}{(e^{\beta(pc)} - 1)} pc\\ \tit{Let $\beta pc = y$, therefore $p^3=\frac{y^3}{\beta^3 c^3}$ and $dp=\frac{dy}{\beta c}$}\\ \implies \rho_b = \frac{g 4 \pi}{(2 \pi \hbar \beta c)^3} \int dy \frac{ y^3}{(e^{y} - 1)} \frac{1}{\beta}\\ \implies \rho_b = \frac{g 4 \pi}{(2 \pi \hbar c)^3} I_3 (K_B T)^4\\ \end{eqnarray*} Where we again use \begin{equation} I_n=\int^\infty_0 dy \frac{y^n}{e^y - 1}= \Gamma(n+1)\zeta(n+1) \end{equation} \tbf{Now for fermions} The number density: \begin{eqnarray*} n= \frac{g }{(2 \pi \hbar)^3} \int d^3p N(\mbf{p})\\ \implies n_{f}= \frac{g }{(2 \pi \hbar)^3} \int d^3p \frac{1}{1 + e^{\beta(E_p)}}\\ \implies n_{f}= \frac{ 4 \pi g}{(2 \pi \hbar)^3} \int dp \frac{ p^2}{(e^{\beta(pc)} + 1)}\\ \tit{Let $\beta pc = y$, therefore $p^2=\frac{y^2}{\beta^2 c^2}$ and $dp=\frac{dy}{\beta c}$}\\ \implies n_{f}= \frac{ 4 \pi g}{(2 \pi \hbar \beta c)^3 } \int dy \frac{ y^2}{(e^{y} + 1)}\\ \implies n_{f}= \frac{ 4 \pi g}{(2 \pi \hbar \beta c)^3 } J_2\\ \end{eqnarray*} energy density for fermions: \begin{eqnarray*} \rho = \frac{g}{(2 \pi \hbar)^3} \int d^3p N(\mbf{p})E_{\mbf{p}}\\ \implies \rho_b = \frac{g 4 \pi}{(2 \pi \hbar)^3} \int dp \frac{ p^2}{(e^{\beta(E_p)} + 1)} E_{\mbf{p}}\\ \implies \rho_b = \frac{g 4 \pi}{(2 \pi \hbar)^3} \int dp \frac{ p^2}{(e^{\beta(pc)} + 1)} pc\\ \tit{Let $\beta pc = y$, therefore $p^3=\frac{y^3}{\beta^3 c^3}$ and $dp=\frac{dy}{\beta c}$}\\ \implies \rho_b = \frac{g 4 \pi}{(2 \pi \hbar \beta c)^3} \int dy \frac{ y^3}{(e^{y} + 1)} \frac{1}{\beta}\\ \implies \rho_b = \frac{g 4 \pi}{(2 \pi \hbar c)^3} J_3 (K_B T)^4\\ \end{eqnarray*} where this time \begin{equation} J_n=\int^\infty_0 dy \frac{y^n}{e^y + 1}= \int^\infty_0 dy \left[\frac{y^n}{e^y-1} - \frac{2y^n}{e^{2y}-1} \right] = \left(1-\frac{1}{2^n}\right)I_n \end{equation} This results in the number density to be \begin{equation} n=\frac{g \zeta(3)}{\pi^2 \hbar^3 c^3} (K_BT)^3\times \begin{cases} 1 \text{ for bosons}\\ \frac{3}{4} \text{ for fermions} \end{cases} \end{equation} and the energy density is : \begin{equation} \rho=\frac{g \pi^2}{30 \hbar^3 c^3} (K_BT)^4\times \begin{cases} 1 \text{ for bosons}\\ \frac{7}{8} \text{ for fermions} \end{cases} \end{equation} Now as the gases we are interested can be formed of many particle species, therefore we define effective number of relativistic species in thermal equilibrium is: \begin{equation} g_\star =\sum _{bosons} g_i + \frac{7}{8} \sum _{fermions} g_i \end{equation} Here, $g_\star$ is the \tit{effective number of relativistic degrees of freedom} at the temperature T. \tbf{As the temperature drops below a particle's mass threshold, $K_BT<m_ic^2$, it becomes non-relativistic and this particle is removed from this sum. Therefore the number of relativistic species is both time and temperature dependent.} Therefore, the energy density from all relativistic species is then \begin{equation} \rho = g_\star \frac{\pi^2}{30 \hbar^2 c^3} (K_BT)^4 \end{equation} So, what we are left with is analysing $g_\star$ in different epochs, we need to calculate the matter content of the standard model. This is true for relativistic species in thermal equilibrium,$T_i=T>>m_i$. But for relativistic species that are not in thermal equilibrium with the photons, $T_i \neq T >> m_i$, these particles are already decoupled and hence \begin{equation} g^{dec}_\star(T)= \sum_{bosons} g_i \left(\frac{T_i}{T}\right)^4 +\frac{7}{8}\sum_{fermions} g_i \left(\frac{T_i}{T}\right)^4 \end{equation} We will see this case being relevant for the case of neutrinos after \f{e^+e^-} annihilation. \subsection*{Internal degrees of freedom vs temperatures} \begin{itemize} \item At $T \geq 100 GeV$, all particles are relativistic and hence the internal degrees of freedom is given as \begin{eqnarray*} g_{bosons}=28 \; \; \; \text{photons(2 polarisation)},W^{\pm} and Z^0 (3.3), gluons (8.2) and Higgs(1)\\ g_{fermions}=90 \; \ ; \; quarks(6.12),\text{charged leptons }(3.4), \text{ and neutrinos } (3.2) \end{eqnarray*} and hence, \begin{equation} g_\star=g_{boson} + \frac{7}{8}g_{fermion}=106.75 \end{equation} As we go to lower temperature, various particle species become non relativistic and annihilate. \item Being heaviest the top quark annihilate first. \fn{how is annihilation related to change of particle state from relativistic to non relativistic. Is transition from relativistic to non relativistic is instantaneous.} At $T \sim \frac{1}{6}m_t \sim 30 GeV$, the effective number of relativistic species is reduced to $g_\star = 106.75 - \frac{7}{8} \times 12 = 96.25$ \end{itemize} \subsection*{Equation of state of relativistic gas} The following equations would be derived later. We use them as a matter of fact and try to derive the equation of state of relativistic gas(radiation). We know the following equations: \begin{eqnarray} \tit{The number density is given as: } n=\frac{g}{(2 \pi)^3} \int d^3p f(p)\\ \tit{The energy density is given as: } \rho=\frac{g}{(2 \pi)^3} \int d^3p f(p) p\\ \tit{The Pressure is given as: } P=\frac{g}{(2 \pi)^3} \int d^3p f(p) \frac{p^2}{3E} \end{eqnarray} From the latter two equations we can derive the following limit for the relativistic limit where the kinetic energy term is greater than the mass term and hence : $E \sim p$. Now starting from the pressure equation and substituting the Energy for the relativistic gas we get \begin{eqnarray*} P=\frac{g}{(2 \pi)^3} \int d^3p f(p) \frac{p^2}{3p}\\ \implies P=\frac{g}{(2 \pi)^3} \int d^3p f(p) \frac{p}{3}\\ \implies P=\frac{g}{(2 \pi)^3} \int d^3p f(p) \frac{E}{3}\\ \implies P=\frac{\rho}{3}\\ \end{eqnarray*} \section{The Hot Big Bang} \subsection{Electron - Positron Annihilation} Prior to nucleosynthesis, the big bang fireball included Both electrons and positrons. At around $K_BT \sim 1 MeV$ these annihilate, injecting energy into the thermal bath of photons and slightly raising their temperature. \newpage \chapter{The Boltzmann Equations} \begin{figure}[h!] \includegraphics[width=\linewidth]{intm.png} \end{figure} \chapter{A critical overview of Cosmology} Cosmology is an attempt to describe the universe as a whole and hence transcends the realms of all other branches of science. Any conclusion about the universe are bound to be profound and hence must be drawn with utmost caution. \chapter{The non linear Evolution} \tbf{Q. Problem with linear peturbation theory:} \begin{itemize} \item It fails when the density contrast $\delta_k \approx 1$. \end{itemize} \tbf{Q. Why do we require a non linear evolution?}\\ \begin{itemize} \item Most of the structures in the universe like galaxies, clusters have density contrast far less than 1. Hence, structurew can be best understood by a non linear theory. \end{itemize} \section{Spherical Model for the nonlinear collapse} Our final verdict on the linear peturbation theory: \begin{itemize} \item From linear theory we where successfully able to arrive at the expression for processed power spectrum $P(k)$ at $t\geq t_{dec}$. \item Our observation of the micro wave background radiation, guarantees that the density contrast had a value of $\delta_k \leq 10^{-4}$ or so at this epoch(this value of the density contrast is quite small).This small value implies that the peturbation can be studied as a linear theory and this contrast evolves as $\propto \;\; a(t)$. \item As the $\delta_k$ evolves as $\propto \;\; a(t) $, its value goes upto unity. Let this time be $t_{nl}$. Now this $t_{nl}$ is the time when non linear evolution kicks in and the linear peturbation theory fails for this particular mode of density contrast$\delta_k$. \end{itemize} \tbf{Why where we using the fourier analysis in case of linear evolution of density?}\\ It is so because in linear evolution of $\delta(\mbf{x},t)$ under fourier transform, each mode $\delta_k(t)$ was evolving independently. Non this was true for linear evolution, and we don't have the same specific advantage from Fourier in nonlinear regime. Hence we will study the same in $\mbf{x}$ space as $\delta(\mbf{x},t)$.\\ \tbf{Q. Describe the formation of gravitationally bound system.}\\ \tit{Refer this to the paragraph 1 of Page 274 to Paddy's structure formation books.}\\ \medskip While the simplest model for non linear evolution of density contrast is when we assume that the overdense region is a spherically symmetric one. Let us assume that the overdense region we are interested has an initial density distribution of \begin{equation} \rho(r,t_i)=\rho_{b}(t_i)+\delta \rho(r,t_i)=\rho_b(t_i)\rr{1+\delta_i(r)} \end{equation} Here $\delta_i(r)=\delta(r,t_i)$ is the initial density contrast which is some specified, non increasing function of $\tau$.\\ \tbf{Can we use Newtonian approximation to probe the evolution of such peturbation?}\\ Here we are interested in scales $\lambda<<d_H$, the size R of the overdense region can be takes to be very less than the hubble radius.\\ The dynamics of the overdense region is determined by the gravitational potential \begin{equation*} \Phi_{total}(r,t)=\Phi_{b}(r,t)+\delta \Phi_{b}(r,t)=-\frac{1}{2}\cc{\frac{\ddot{a}}{a}}r^2+\delta \Phi_{b}(r,t) \end{equation*} \begin{equation} =\frac{2\pi}{3}G \rho_b r^2+\delta \Phi(r,t) \end{equation} where $\Phi_b(r,t)$ is the equivalent newtonian potential of the friedman metric and $\delta \Phi$ is the potential generated due to the excess density.\\ The motion of a thin shell of particles located at a distance r is governed by the equation \begin{equation}\label{eq:sppetur} \frac{d^2 r}{d t^2}=-\nabla \Phi_{total}=-\frac{4 \pi G \rho_b(t)}{3}\mbf{r}-\nabla(\delta \Phi)=-\frac{GM_b}{r^3}\mbf{r}-\frac{G\delta M(r,t)}{r^3}\mbf{r} \end{equation} \begin{\cbox} It is important to note that fir the spherically symmetric density distribution, the gravitational force only depend on the mass $\delta M$ contained inside the shell. \end{\cbox} Here, $M_b$ and $\delta M(r,t)$ stands for \begin{equation} M_b=\frac{4\pi}{3}\rho_b(t)r^3=\frac{4\pi}{3}a^3(t)x^3=constant \end{equation} and \begin{equation} \delta M(r,t)=4\pi \int^r_0 \delta\rho(q,t)q^2dq=4 \pi \int^r_0 q^2 \delta (q,t) dq \end{equation} \begin{\cbox} One more thing, to simplify our analysis, we assume that the spherical shell do not cross each other during the evolution. In such a case the mass contained within a shell of radius r does not change with time $\delta M(r,t)=\delta M(r_i,t_i)=$constant. \end{\cbox} We can now combine the two terms in \eqref{eq:sppetur} and get \begin{equation}\label{eq:sppeturbmo} \frac{d^2 r}{dt^2}=-\frac{GM }{r^2} \end{equation} where, \begin{equation} M=M_b+\delta M=\rho_b\cc{\frac{4\pi}{3}r_i^3}(1+\bar{\delta_i}) \end{equation} where \begin{equation*} \bar{\delta_i}=\cc{\frac{3}{4\pi r^3_i}}\int^{r_i}_0\delta_i(r) 4 \pi r^2 \end{equation*} Here, \begin{itemize} \item $r_i$ is the initial radius of the mass M \item $\bar{\delta_i}$ is the average value of $\delta$ within $r_i$ at time $t_i$. \end{itemize} Integrating \eqref{eq:sppeturbmo} we get \begin{equation}\label{eq:sppeturbsol} \frac{1}{2}\cc{\frac{dr}{dt}}^2-\frac{GM}{r}=E \end{equation} Here, E is the constant of integration. \begin{itemize} \item If $E>0$, $\frac{dr}{dt}>0$ and hence the shell is in an ever expanding phase. \item If $ E<0$, then as r increases, $\dot{r}$ will eventually become zero and later negative , implying a contraction and collapse. \end{itemize} In a more convenient form , let us express the equation \eqref{eq:sppeturbsol} at an initial time $t_i$. \begin{itemize} \item $t_i$ should be such that, $\delta$ is quite small such that we can claim that overdense region is expanding along with the background. \item or we can assume that peculiar velocities are negligible at time $t=t_i$. \item $\dot{r}_i=\frac{\dot{a}}{a}r_i=H(t_i)r_i\equiv H_ir_i$ at time $t_i$ \item the initial kinetic energy will be then defined as \begin{equation} K_i\equiv\cc{\frac{\dot{r_i}^2}{2}}_{t=t_i}=\frac{H_i^2r_i}{2} \end{equation} \item and the initial potential energy at $t=t_i$ is $U=-|U|$ and is defined as \begin{equation*} |U|=\cc{\frac{GM}{r}}_{t=t_i}=\cc{\frac{G\rho_b\cc{\frac{4\pi}{3}r_i^3}(1+\bar{\delta_i})}{r_i}}=\cc{G\rho_b\cc{\frac{4\pi}{3}r_i^2}(1+\bar{\delta_i})} \end{equation*} \begin{equation} \implies |U|=\frac{1}{2}(1+\bar{\delta_i})H_i^2r_i^2=K_i\Omega_i(1+\bar{\delta_i}) \end{equation} Here, $\Omega_i=\cc{\frac{\rho_b(t_i)}{\rho_c(t_i)}}$ which denotes the initial value of the density parameter $\Omega$ of the smoothed background of universe. \item And the total energy is given as \begin{equation} E=K_i-K_i\Omega_i(1+\bar{\delta_i})=K_i\Omega_i[\Omega_i^{-1}-(1+\bar{\delta_i})] \end{equation} \tbf{So, the condition $E<0$ for the shell to collapse (eventually), becomes $(1+\bar{\delta_i})>\Omega_i^{-1}$} or \begin{equation} \bar{\delta_i}>[\Omega_i^{-1}-1] \end{equation} \item For a closed or a flat universe with $\cc{[\Omega_i^{-1}\leq 1]}$ this condition is satisfied . (Note even though overdesities will always collapse but the smaller overdensities will take more than the bigger overdensities to collapse.)For an open universe $\Omega_i<1$, the overdensity has to be above a critical radius to collapse such that $\bar{\delta_i}(r_{cr})=\Omega_i^{-1}$ to collapse. \item \end{itemize} \section{N body simulation} A universe constituted will collisionaless particles evolves only through gravity. This is how we study non linear evolution of density peturbations through N body simulation.\\ \tbf{Q. What does an N body simulation do?}\\ \begin{enumerate} \item Here, the matter distribution is described as a collection of N particles interacting via gravity. \item The state of the system at any time t is given by the position and velocity of the particles which are evolved through a sequence of small time steps. \item The force on one particle by the rest N-1 particles is calculated when we have information of the particle position. \item When we know force, we can update the particle positions again and go back to step 2. \end{enumerate} \tbf{Q. Is there any limitation to this stupendo-fantabulous method?}\\ Yes! the only limitation of the problem arises from the value of N which increases the time required for computation of forces.\\ After a brief introduction to N body simulation let us move to the next step that is the technique of the calculation.\\ Three different schemes have been popularly studied in the literature. \begin{itemize} \item P-P scheme (Particle Particle scheme) \item The P-M scheme (Particle -Mesh scheme) \end{itemize} \subsection{The P-P method of N-body simulation} This is the simplest of the algorithm where the force on each particle is calculated as a sum of inverse square law forces due to all other particles.\\ \begin{\cbox} In general we don't calculate force all upto $\mbf{r}=0$, as the force $1/r^2$ blows up at zero; \tbf{what we do instead is smooth the law at small distances at small r and modifying } \begin{equation} \frac{1}{r^2}\rightarrow \frac{1}{r^2+a^2} \end{equation} \tit{although this smoothening would result in loss of spatial resolution, the computation becomes efficient.} \end{\cbox} \medskip \tbf{Q. How does smoothening the scale makes calculation computationally efficient?}\\ Ans. As $r \rightarrow 0$ then, the velocities increase rapidly as $\frac{1}{r^2}\rightarrow \infty$. In order to keep track of such steep rise in velocities one has to use smaller time steps to follow the particle trajectory.\\ \tbf{Q. What are the disadvantages of PP scheme?}\\ Ans. In PP method, in order to calculate force on N particles due to (N-1) particles one has to do $N^2$ number of operations. Therefore, \tbf{PP scheme is employed for $N\leq 10^4$}. \subsection{The PM scheme of N-body simulation} Instead of making $N^2$ calculations through brute force by calculating force on each particle, one can instead \tbf{calculate force on each particle by first calculating potential (obtained from solving the Poisson equation on a mesh)}. \subsubsection{Steps to apply PM algorithm} \begin{itemize} \item All the continuous variables in space e.g. density, potential are approximated by their values on a regular array of mesh points. \fn{ I think instead of the continuous function is space potential or density fields are approximated to a value for a given size of mesh and for the whole mesh one value is used for that variable. Therefore the implication being \tbf{the smaller the mesh the better?} } . \item Differential operators are replaced with finite difference approximations on the mesh. \end{itemize} \chapter{MUSIC} \end{document}
State Before: R : Type u S : Type v T : Type w a b : R n : ℕ inst✝¹ : CommRing R inst✝ : IsDomain R p q : R[X] ⊢ a ∈ roots p ↔ p ≠ 0 ∧ IsRoot p a State After: no goals Tactic: rw [← count_pos, count_roots p, rootMultiplicity_pos']
lemma frontier_straddle: fixes a :: "'a::metric_space" shows "a \<in> frontier S \<longleftrightarrow> (\<forall>e>0. (\<exists>x\<in>S. dist a x < e) \<and> (\<exists>x. x \<notin> S \<and> dist a x < e))"
theorem Janiszewski: fixes a b :: complex assumes "compact S" "closed T" and conST: "connected (S \<inter> T)" and ccS: "connected_component (- S) a b" and ccT: "connected_component (- T) a b" shows "connected_component (- (S \<union> T)) a b"
theory T93 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) " nitpick[card nat=4,timeout=86400] oops end
Formal statement is: lemma locally_path_connected_components: "\<lbrakk>locally path_connected S; c \<in> components S\<rbrakk> \<Longrightarrow> locally path_connected c" Informal statement is: If $S$ is locally path-connected and $c$ is a component of $S$, then $c$ is locally path-connected.
In the early evening hours of March 1st, 2008 the Mt. Morris Fire District was called mutual aid to Forreston for a working barn fire. Mt. Morris was asked to respond with a Heavy Rescue and a Chief on a Second Alarm. Shortly after arriving on scene command was given to Chief Hough by Forreston Fire Command. Mt. Morris also sent a Tender Company to the scene on a Third Alarm as well. The barn was a total loss, however area firefighters were able to save all the other buildings on the property. A large excavator was brought in to safely complete overhaul. Mt. Morris Firefighters were on scene about six hours.
------------------------------------------------------------------------ -- Convenient syntax for "equational reasoning" using a strict partial -- order ------------------------------------------------------------------------ open import Relation.Binary module Relation.Binary.StrictPartialOrderReasoning (p : StrictPartialOrder) where import Relation.Binary.PreorderReasoning as PreR import Relation.Binary.Props.StrictPartialOrder as SPO open PreR (SPO.preorder p) public renaming (_∼⟨_⟩_ to _<⟨_⟩_)
module SfBlackHole using Unitful import PhysicalConstants.CODATA2018: G, ħ, c_0, k_B export spaghettification_tensile_force, schwarzschild_radius, hawking_temperature, bekenstein_hawking_luminosity, hawking_evaporation spaghettification_tensile_force(m_parent::Unitful.Mass, m::Unitful.Mass, l::Unitful.Length, r::Unitful.Length) = (G*m_parent*l*m)/4r^3 |> u"N" """ schwarzschild_radius(m::Unitful.Mass) Radius of a Schwarzschild black hole of mass `m`. """ schwarzschild_radius(m::Unitful.Mass) = 2G*m / c_0^2 |> u"m" """ hawking_temperature(m::Unitful.Mass) Black body temperature of a Schwarzschild black hole of mass `m`. """ hawking_temperature(m::Unitful.Mass) = (ħ * c_0^3)/(8π * G * m * k_B) |> u"K" """ bekenstein_hawking_luminosity(m::Unitful.Mass) Pure photon luminosity of a Schwarzschild black hole of mass `m`. This approximation will break down as the temperature of the hole increases to the point where particle emission is possible. """ bekenstein_hawking_luminosity(m::Unitful.Mass) = upreferred((ħ * c_0^6)/(15360π * G^2 * m^2)) """ hawking_evaporation(m::Unitful.Mass) Time for a Schwarzschild black hole of initial mass `m` to evaporate via Hawking radiation. """ hawking_evaporation(m::Unitful.Mass) = upreferred((5120π * G^2 * m^3)/(ħ * c_0^4)) end
Amazing of High Ceiling Living Room Designs Ceiling Design For Living Room - Producing a home design plan could be a technological matter and also calls for research study and also preparation. The designer of a home plan will certainly take all facets of the home when preparing the plan consisting of the lifestyle of the individuals that would certainly be living in the home and also the readily available room. Picking a home design is everything about establishing how much room you need. You could locate contemporary home strategies in a selection of forms and also dimensions. This indicates that you could get the room that you need while additionally obtaining the design that you take pleasure in, no matter what that may be. The goal of constructing your home, besides, is to get the desire home that you constantly desired. The following is a photo high ceiling living room designs that will certainly give you the idea of home decor yet still provides the impression of glamorous. The Amazing of High Ceiling Living Room Designs Ceiling Design For Living Room above is a image with the size 600 x 399 and the section of high ceiling living room designs, we all selects the best libraries having best resolution exclusively for you all, and this images is one among graphics libraries inside our best graphics gallery about Elegant High Ceiling Living Room Designs. I'm hoping you may as it. As you already know, The Elegant Living Room has been a popular home design ideas for this years and it has so many benefits. Hopefully, the can help you create a neat interior design for your house.
[STATEMENT] lemma filter_bool_list_not_elem: "x \<notin> set xs \<Longrightarrow> x \<notin> set (filter_bool_list bs xs)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<notin> set xs \<Longrightarrow> x \<notin> set (filter_bool_list bs xs) [PROOF STEP] by(induct bs xs rule: filter_bool_list.induct) auto
lemma Bseq_cmult_iff: fixes c :: "'a::real_normed_field" assumes "c \<noteq> 0" shows "Bseq (\<lambda>x. c * f x) \<longleftrightarrow> Bseq f"
-- Andreas, 2016-07-29 issue #707 -- {-# OPTIONS -v tc.ip:20 #-} postulate A B : {!!} -- Should not create two interaction points! -- Also not two sort metas!
//=====================================================================// /*! @file @brief collada DAE ファイルの入出力 @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "dae_io.hpp" #include <boost/format.hpp> #include <boost/foreach.hpp> namespace collada { using namespace boost::property_tree; using namespace std; void dae_io::setup_material_(const std::string& name, material& mate) { const dae_effects::optional_effect_cref& cref = effects_.get_effect(name); if(cref) { const dae_effects::effect& eff = cref.get(); const dae_effects::profile_COM& com = eff.profile_com_; BOOST_FOREACH(const dae_effects::newparam& param, com.newparams_) { if(param.surface_.enable_) { mate.surface_ = param.surface_; } else if(param.sampler_.enable_) { mate.sampler_ = param.sampler_; } } } } void dae_io::parse_geometry_(const ptree::value_type& element, geometry& gt) { const std::string& s = element.first.data(); if(s != "geometry") return; const ptree& pt = element.second; if(boost::optional<string> id = pt.get_optional<string>("<xmlattr>.id")) { gt.id_ = id.get(); } if(boost::optional<string> name = pt.get_optional<string>("<xmlattr>.name")) { gt.name_ = name.get(); } if(verbose_()) { verbose_.nest_out(); cout << boost::format("id: '%s', name: '%s'") % gt.id_ % gt.name_ << endl; } verbose_.nest_down(); BOOST_FOREACH(const ptree::value_type& child, pt) { gt.mesh_.parse(verbose_, child); } verbose_.nest_up(); } void dae_io::parse_geometries_(const ptree::value_type& element) { const std::string& s = element.first.data(); if(s != "library_geometries") return; if(verbose_()) { cout << s << ":" << endl; } verbose_.nest_down(); BOOST_FOREACH(const ptree::value_type& child, element.second) { geometry gt; parse_geometry_(child, gt); geometries_.push_back(gt); } verbose_.nest_up(); } //-----------------------------------------------------------------// /*! @brief パース @param[in] filename ファイル名 @return 成功なら「true」 */ //-----------------------------------------------------------------// bool dae_io::parse(const std::string& filename) { read_xml(filename, pt_); // version の確認 if(boost::optional<string> ver = pt_.get_optional<string>("COLLADA.<xmlattr>.version")) { filename_ = filename; version_ = ver.get(); if(verbose_()) { std::cout << boost::format("Collada: file: '%s', version: '%s'") % filename % version_ << endl; } // 全エントリーを展開 int error = 0; BOOST_FOREACH(const ptree::value_type& child, pt_.get_child("COLLADA")) { error += asset_.parse(verbose_, child); error += lights_.parse(verbose_, child); error += images_.parse(verbose_, child); error += materials_.parse(verbose_, child); error += effects_.parse(verbose_, child); parse_geometries_(child); error += controllers_.parse(verbose_, child); error += visual_scenes_.parse(verbose_, child); error += scene_.parse(verbose_, child); if(error) { return false; } } return true; } else { return false; } } //-----------------------------------------------------------------// /*! @brief 三角形メッシュを作成する @param[out] tms 三角メッシュ構造体 @param[in] scale スケール */ //-----------------------------------------------------------------// void dae_io::create_triangle_mesh(triangle_meshes& tms, const vtx::fvtx& scale) { if(geometries_.empty()) return; float vsc[4]; vsc[0] = scale.x; vsc[1] = scale.y; vsc[2] = scale.z; vsc[3] = 1.0f; BOOST_FOREACH(const geometry& g, geometries_) { const dae_mesh& mesh = g.mesh_; BOOST_FOREACH(const dae_mesh::triangle& tri, mesh.get_triangles()) { triangle_mesh tm; tm.matrix_ = tri.matrix_; utils::optional_str_ref ref = materials_.get_from(tri.material_); if(ref) { setup_material_(ref.get(), tm.material_); } size_t p_stride = tri.inputs_.size(); BOOST_FOREACH(const dae_mesh::input& inp, tri.inputs_) { if(inp.semantic_ == dae_mesh::input::semantic::VERTEX) { boost::optional<const dae_mesh::source&> srcopt = mesh.get_vertex_source(inp.source_); if(!srcopt) continue; const dae_mesh::source& src = *srcopt; tm.vertex_stride_ = src.stride_; for(size_t i = inp.offset_; i < tri.pointer_.size(); i += p_stride) { int idx = tri.pointer_[i] * src.stride_; for(int j = 0; j < tm.vertex_stride_; ++j) { tm.vertex_.push_back(src.array_[idx + j] * vsc[j]); } } // 頂点集合から、min、max をスキャン dae_mesh::scan_min_max(src, tm.min_, tm.max_); } else if(inp.semantic_ == dae_mesh::input::semantic::NORMAL) { boost::optional<const dae_mesh::source&> srcopt = mesh.get_source(inp.source_); if(!srcopt) continue; const dae_mesh::source& src = *srcopt; tm.normal_stride_ = src.stride_; for(size_t i = inp.offset_; i < tri.pointer_.size(); i += p_stride) { int idx = tri.pointer_[i] * src.stride_; for(int j = 0; j < tm.normal_stride_; ++j) { tm.normal_.push_back(src.array_[idx + j]); } } } else if(inp.semantic_ == dae_mesh::input::semantic::TEXCOORD) { boost::optional<const dae_mesh::source&> srcopt = mesh.get_source(inp.source_); if(!srcopt) continue; const dae_mesh::source& src = *srcopt; tm.texcoord_stride_ = src.stride_; for(size_t i = inp.offset_; i < tri.pointer_.size(); i += p_stride) { int idx = tri.pointer_[i] * src.stride_; for(int j = 0; j < tm.texcoord_stride_; ++j) { tm.texcoord_.push_back(src.array_[idx + j]); } } } else if(inp.semantic_ == dae_mesh::input::semantic::COLOR) { boost::optional<const dae_mesh::source&> srcopt = mesh.get_source(inp.source_); if(!srcopt) continue; const dae_mesh::source& src = *srcopt; tm.color_stride_ = src.stride_; for(size_t i = inp.offset_; i < tri.pointer_.size(); i += p_stride) { int idx = tri.pointer_[i] * src.stride_; for(int j = 0; j < tm.color_stride_; ++j) { tm.color_.push_back(src.array_[idx + j]); } } } } tms.push_back(tm); } } } }
\section{Conclusion and Future Work} \label{sec:conclusion} Completing automatically playlists with tracks contained in the MPD dataset is a particularly difficult task due to the dataset dimension and the variety of playlists generated by numerous users having different likes and behaviors bringing great diversity. In this paper, we present the D2KLab recommender system that implements an ensemble approach of multiple learning models differently optimized combined with a Borda count strategy. Each model runs an RNN that exploits a wide range of playlist features such as artist, album, track, lyrics (used for the creative track), title and a so-called Title2Rec that takes as input the title and that is used, as fall-back strategy, when playlists do not contain any track. The approach showed to be robust in such a complex setting demonstrating the effectiveness of learning models for automatic playlist completion. The experimental analysis brought to further attention three points, namely the generation strategy, complementarity of the learning models, and computing time. The generation strategy has a great impact on the results and it pointed out that a recurrent decoding stage is less performing than using a ranking strategy that weighs the output of each RNN of the encoding stage. The ensemble strategy aggregates different outputs of the learning model runs by pivoting the generated ranking. This has granted a sensible increment in performance, so we plan to study further the complementarity of the runs and to build a learning model to automatically select the best candidates. Finally, the computing time has been a crucial experimental setup element due to the generation of the RNN learning model; we addressed it by creating different sizes of the MPD dataset randomly selected and by optimizing the learning models on the hardware a disposal, becoming another factor of differentiation for shaping a performing submission. %In this paper we presented a novel approach for music recommendation built on top of the Million Playlist Dataset. The strategy involves 3 types of vectors -- Sequential embeddings, Titles embeddings and Lyrics embeddings -- that are used for train a RNN based on LSTM. The final recommendation comes from an ensemble architecture the combine the results of an RNN and the ones of Title2Rec, a playlist generation algorithm that relies on the sole title of the playlist.
#include <boost/test/unit_test.hpp> #include "algorithms/data_structures/string/valid_parentheses.hpp" BOOST_AUTO_TEST_SUITE(TestValidParentheses) BOOST_AUTO_TEST_CASE(empty_string) { BOOST_CHECK(Algo::DS::String::ValidParentheses::IsValid(std::string())); } BOOST_AUTO_TEST_CASE(valid_strings) { BOOST_CHECK(Algo::DS::String::ValidParentheses::IsValid("()")); BOOST_CHECK(Algo::DS::String::ValidParentheses::IsValid("()[]{}")); BOOST_CHECK(Algo::DS::String::ValidParentheses::IsValid("()()")); BOOST_CHECK(Algo::DS::String::ValidParentheses::IsValid("(([{}]))")); BOOST_CHECK(Algo::DS::String::ValidParentheses::IsValid("([({[]})])")); } BOOST_AUTO_TEST_CASE(invalid_strings) { BOOST_CHECK(!Algo::DS::String::ValidParentheses::IsValid(")(")); BOOST_CHECK(!Algo::DS::String::ValidParentheses::IsValid("()(")); BOOST_CHECK(!Algo::DS::String::ValidParentheses::IsValid("]{")); BOOST_CHECK(!Algo::DS::String::ValidParentheses::IsValid("([)]")); } BOOST_AUTO_TEST_SUITE_END()
from csv import writer from tabnanny import check import cv2 import numpy as np import imutils import argparse HOGCV=cv2.HOGDescriptor() HOGCV.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) def detect(frame): bounding_boxes_coordinates, weights = HOGCV.detectMultiScale(frame, winStride=(4,4), padding=(8,8), scale=1.05) person = 1 for (x,y,w,h) in bounding_boxes_coordinates: cv2.rectangle(frame, (x,y), (x+w,y+h), (0,0,255), 2) cv2.putText(frame, "Person {}".format(person), (x,y-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 2) person += 1 cv2.putText(frame, 'Status: Detecting', (10,20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 2) cv2.putText(frame, "Total People: {}".format(person-1), (10,30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 2) cv2.imshow("Frame", frame) return frame def human_detection(args): image_path = args["image"] video_path = args["video"] if str(args["camera"])=='true':camera=True else:camera=False writer = None if args["output"] is not None and image_path is None: writer=cv2.VideoWriter(args['output'],cv2.VideoWriter_fourcc(*'MJPG'),30,(640,480)) if camera: print("[INFO] opening camera...") detectByCamera(writer) elif video_path is not None: print("[INFO] opening video file (path)...") detectByPathVideo(video_path,writer) elif image_path is not None: print("[INFO] opening image file (path)...") detectByPathImage(image_path,args["output"]) def detectByCamera(writer): video=cv2.VideoCapture(0) print('Detecting by camera...') while True: check,frame=video.read() if writer is not None: writer.write(frame) key=cv2.waitKey(1) if key==ord('q'): break video_release() cv2.destroyAllWindows() def detectByPathVideo(video_path,writer): video=cv2.VideoCapture(video_path) check,frame=video.read() if check==False: print('[ERROR] Video not found') return print('Detecting by video...') while video.isOpened(): check,frame=video.read() if check: frame=imutils.resize(frame,width=min(800,frame.shape[1])) frame=detect(frame) if writer is not None: writer.write(frame) key=cv2.waitKey(1) if key==ord('q'): break else: break video.realease() cv2.destroyAllWindows() def detectByCamera(writer): video=cv2.VideoCapture(0) print('Detecting by camera...') while True: check,frame=video.read() if writer is not None: writer.write(frame) key=cv2.waitKey(1) if key==ord('q'): break video.realease() cv2.destroyAllWindows() def detectByPathImage(image_path,writer): image=cv2.imread(image_path) if image is None: print('[ERROR] Image not found') return print('Detecting by image...') frame=imutils.resize(image,width=min(800,image.shape[1])) frame=detect(frame) if writer is not None: writer.write(frame) cv2.imshow("Frame",frame) cv2.waitKey(0) cv2.destroyAllWindows() def argsParser(): ap=argparse.ArgumentParser() ap.add_argument('-i','--image',default=None,help='Path to image') ap.add_argument('-v','--video',default=None,help='Path to video') ap.add_argument('-c','--camera',default=None,help='Detect by camera') ap.add_argument('-o','--output',default=None,help='Path to output video') args=vars(ap.parse_args()) return args if __name__=="__main__": HOGCV=cv2.HOGDescriptor() HOGCV.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) args=argsParser() human_detection(args)
It's been three years since the filing of a suit against the FBI after agents put several Muslims on the No Fly list to retaliate against their refusal to be conscripted as a confidential informants spying on other Muslims; the FBI's illegal retaliation cost their victims their jobs, subjected them to harassment, and cut them off from visits to family overseas. The FBI and Department of Justice don't dispute the fundamentals in this case: that FBI officers placed Muslims on the No Fly list in retaliation for their refusal to cooperate (and not because they were believed to be a security risk), and that this was illegal. However, they do object to their victims ability to sue individual FBI officials for their illegal actions; the government's lawyers asked the Second Circuit Court of Appeals to find that the Religious Freedom Restoration Act (RFRA) immunizes corrupt officials from legal consequences of lawbreaking, limiting victims to suing agencies, rather than agents. The court disagreed. The FBI's victims' suit against the officers who wronged them can proceed to the next step. Having decided the lawsuit can continue, the Appeals Court decides it doesn't need to reach a finding on the agents' qualified immunity assertions. This will be handled on remand by the lower court, which will first have to make this decision before deciding what (if any) damages the plaintiffs are entitled to. This is far from a victory for the plaintiffs but it does open the door for similar lawsuits against federal officers for harassment and intimidation tactics deployed in hopes of turning lawful residents and visitors into government informants. Raising the possibility of a successful lawsuit above the previously-presumed zero percent should hopefully act as a minor deterrent against future abuses of power.
import pandas as pd import numpy as np import joblib from sklearn.preprocessing import OneHotEncoder, StandardScaler from sklearn.model_selection import train_test_split from imblearn.over_sampling import SMOTE from sklearn.svm import SVC df = pd.read_csv('titanic_dataset.csv') X = df.drop(['survived', 'name', 'ticket', 'pclass', 'sex'], axis=1).values x_cat = df[['pclass', 'sex']] encoder = OneHotEncoder() x_ohe = encoder.fit_transform(x_cat).toarray() joblib.dump(encoder, 'encoder.pkl') X = np.hstack((X, x_ohe)) y = df['survived'].values x_train, x_test, y_train, y_test = train_test_split(X, y, random_state=42) scaler = StandardScaler() x_train = scaler.fit_transform(x_train) x_test = scaler.transform(x_test) joblib.dump(scaler, 'scaler.pkl') sm = SMOTE(random_state=42) x_train, y_train = sm.fit_sample(x_train, y_train) model = SVC() model.fit(x_train, y_train) joblib.dump(model, 'model.pkl') score_train = model.score(x_train, y_train) score_test = model.score(x_test, y_test) print(f'Training accuracy: {score_train}') print(f'Testing accuracy: {score_test}')
First @-@ line treatment of AML consists primarily of chemotherapy , and is divided into two phases : induction and postremission ( or consolidation ) therapy . The goal of induction therapy is to achieve a complete remission by reducing the number of leukemic cells to an undetectable level ; the goal of consolidation therapy is to eliminate any residual undetectable disease and achieve a cure . <unk> stem cell transplantation is usually considered if induction chemotherapy fails or after a person relapses , although transplantation is also sometimes used as front @-@ line therapy for people with high @-@ risk disease . Efforts to use tyrosine kinase inhibitors in AML continue .
[STATEMENT] lemma Exp_Gen_inj: "Exp Gen X = Exp Gen Y \<Longrightarrow> X = Y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Exp Gen X = Exp Gen Y \<Longrightarrow> X = Y [PROOF STEP] by (transfer, auto dest: eq_expgen)
State Before: α : Type u_1 β : Type u_2 γ : Type ?u.23811 r : Rel α β ⊢ ∀ (x : α), x ∈ core r Set.univ ↔ x ∈ Set.univ State After: no goals Tactic: simp [mem_core]
[STATEMENT] lemma strictly_subsumes_irrefl: "\<not> strictly_subsumes C C" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<not> strictly_subsumes C C [PROOF STEP] unfolding strictly_subsumes_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<not> (subsumes C C \<and> \<not> subsumes C C) [PROOF STEP] by blast
<unk> also agrees with Alekhine 's criticism of <unk> e5 2.Nf3 , a reversed Alekhine 's Defense , in Réti – Alekhine , Baden @-@ Baden 1925 , writing that Alekhine " understood the difference in opening philosophies for White and Black , and realized they just can 't be the same ! White is supposed to try for more than just obtaining a comfortable game in reversed colour opening set @-@ ups , and , as the statistics show — surprisingly for a lot of people , but not for me — White doesn 't even score as well as Black does in the same positions with his extra tempo and all . " Howard Staunton , generally considered to have been the strongest player in the world from 1843 to 1851 , made a similar point over 160 years ago , writing that Owen 's Defense ( 1.e4 b6 ) is playable for Black , but that <unk> is inferior to " the more customary [ first ] moves , from its being essentially defensive " . The current view is that Owen 's Defense is slightly better for White , while <unk> is playable but less likely to yield an opening advantage than 1.e4 or 1.d4.
theory T121 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) " nitpick[card nat=7,timeout=86400] oops end
The numerator and denominator of a fraction are coprime.
Formal statement is: corollary\<^marker>\<open>tag unimportant\<close> Jordan_disconnected: fixes c :: "real \<Rightarrow> complex" assumes "simple_path c" "pathfinish c = pathstart c" shows "\<not> connected(- path_image c)" Informal statement is: If $c$ is a simple closed curve, then the complement of the image of $c$ is not connected.
Formal statement is: corollary isometry_subspaces: fixes S :: "'a::euclidean_space set" and T :: "'b::euclidean_space set" assumes S: "subspace S" and T: "subspace T" and d: "dim S = dim T" obtains f where "linear f" "f ` S = T" "\<And>x. x \<in> S \<Longrightarrow> norm(f x) = norm x" Informal statement is: If $S$ and $T$ are subspaces of Euclidean spaces of the same dimension, then there exists a linear isometry from $S$ to $T$.
[STATEMENT] lemma length_sort[simp]: "length (sort_key f xs) = length xs" [PROOF STATE] proof (prove) goal (1 subgoal): 1. length (sort_key f xs) = length xs [PROOF STEP] by (induct xs, auto)
-- Andreas, 2015-06-28 -- {-# OPTIONS -v tc.polarity:20 #-} open import Common.Size -- List should be monotone in both arguments -- (even as phantom type). data List (i : Size) (A : Set) : Set where [] : List i A castL : ∀{i A} → List i A → List ∞ A castL x = x castLL : ∀{i A} → List i (List i A) → List ∞ (List ∞ A) castLL x = x -- Stream should be antitone in the first and monotone in the second argument -- (even with field `tail' missing). record Stream (i : Size) (A : Set) : Set where coinductive field head : A castS : ∀{i A} → Stream ∞ A → Stream i A castS x = x castSS : ∀{i A} → Stream ∞ (Stream ∞ A) → Stream i (Stream i A) castSS x = x
expand.weights = function (x, w){ # expand a list of values and weights to allow brute force # calculation of means, frequency distributions, etc. weights = sort(unique(w)) out = NULL for (i in weights) { a = x[ which(w == i) ] b = rep.int(a, i) out = c(out, b) } return(out) }
function [GHz] = kHz2GHz(kHz) % Convert frequency from kilohertz to gigahertz. % Chad A. Greene 2012 GHz = kHz*1e-6;
Andrew McCoy Photography consider the companies below as close associates and recommend their services and products. Doodle Print are an innovative photo booth hiring company in Warwickshire, whose next generation of photo booth is one of those extraordinary touches that makes your special event even more special. Their hiring package comes with unlimited prints, digital props, social sharing, online gallery, onsite attendants and travel within 50 miles radius from their office as standard. Exquisite Couture & "Ready to wear" bridal gowns. A range of sizes available to try, tiaras, veils and shoes; bridesmaid and flower girl dresses; designer service available for individual commisions. The Bridal Gallery stock designers such as Romantica of Devon, Tiffany, Sacha James, Estes, Margaret Lee, Hilary Morgan amd AnuPam. If you're looking for something a little different why not let their designers create a stunning wedding gown especially for you. Photobooth hire for parties, proms, corporate events and weddings in and around the Midlands region. Capture the fun at any event, whether that is a wedding, party, prom, product launch or corporate event. Their photo booths can be personalised to entertain guests or to promote brand awareness. With a range of packages to choose from: 2, 3 or 4 hour hire plus a range of additional goodies to create your own package. Established over fourteen years ago and is located in Medieval Spon Street, Coventry. Mark Andrew offers an extensive range of outfits in many different styles and colours to suit the discerning groom. The most contemporary range of wedding rings in the midlands. Ace Star Limousines, UK's finest limo hire company, offer fast, friendly and professional service. Specialists in limo hire and wedding car hire covering surrounding area of Midlands, Yorkshire and the Home Counties. Belle Fleur are passionate about weddings and special celebrations & provide a bespoke personal service to enhance the enjoyment of your special day. Whether a wedding for a large gathering or an intimate celebration for a select few, Belle Fleur can provide beautiful cakes & flowers to suit your specific needs. Unique & delicious Belle Fleur cakes can be complimented with the creation of fresh beautiful flower arrangements designed to co-ordinate with colour schemes and themes to enhance your perfect celebration. Lorraine is a highly skilled professional with similar packages and styles as our own.
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import group_theory.free_abelian_group import data.finsupp.basic /-! # Isomorphism between `free_abelian_group X` and `X →₀ ℤ` In this file we construct the canonical isomorphism between `free_abelian_group X` and `X →₀ ℤ`. We use this to transport the notion of `support` from `finsupp` to `free_abelian_group`. ## Main declarations - `free_abelian_group.equiv_finsupp`: group isomorphism between `free_abelian_group X` and `X →₀ ℤ` - `free_abelian_group.coeff`: the multiplicity of `x : X` in `a : free_abelian_group X` - `free_abelian_group.support`: the finset of `x : X` that occur in `a : free_abelian_group X` -/ noncomputable theory open_locale big_operators variables {X : Type*} /-- The group homomorphism `free_abelian_group X →+ (X →₀ ℤ)`. -/ def free_abelian_group.to_finsupp : free_abelian_group X →+ (X →₀ ℤ) := free_abelian_group.lift $ λ x, finsupp.single x (1 : ℤ) /-- The group homomorphism `(X →₀ ℤ) →+ free_abelian_group X`. -/ def finsupp.to_free_abelian_group : (X →₀ ℤ) →+ free_abelian_group X := finsupp.lift_add_hom $ λ x, (smul_add_hom ℤ (free_abelian_group X)).flip (free_abelian_group.of x) open finsupp free_abelian_group @[simp] lemma finsupp.to_free_abelian_group_comp_single_add_hom (x : X) : finsupp.to_free_abelian_group.comp (finsupp.single_add_hom x) = (smul_add_hom ℤ (free_abelian_group X)).flip (of x) := begin ext, simp only [add_monoid_hom.coe_comp, finsupp.single_add_hom_apply, function.comp_app, one_smul, to_free_abelian_group, finsupp.lift_add_hom_apply_single] end @[simp] lemma free_abelian_group.to_finsupp_comp_to_free_abelian_group : to_finsupp.comp to_free_abelian_group = add_monoid_hom.id (X →₀ ℤ) := begin ext x y, simp only [add_monoid_hom.id_comp], rw [add_monoid_hom.comp_assoc, finsupp.to_free_abelian_group_comp_single_add_hom], simp only [to_finsupp, add_monoid_hom.coe_comp, finsupp.single_add_hom_apply, function.comp_app, one_smul, lift.of, add_monoid_hom.flip_apply, smul_add_hom_apply, add_monoid_hom.id_apply], end @[simp] lemma finsupp.to_free_abelian_group_comp_to_finsupp : to_free_abelian_group.comp to_finsupp = add_monoid_hom.id (free_abelian_group X) := begin ext, rw [to_free_abelian_group, to_finsupp, add_monoid_hom.comp_apply, lift.of, lift_add_hom_apply_single, add_monoid_hom.flip_apply, smul_add_hom_apply, one_smul, add_monoid_hom.id_apply], end @[simp] lemma finsupp.to_free_abelian_group_to_finsupp {X} (x : free_abelian_group X) : x.to_finsupp.to_free_abelian_group = x := by rw [← add_monoid_hom.comp_apply, finsupp.to_free_abelian_group_comp_to_finsupp, add_monoid_hom.id_apply] namespace free_abelian_group open finsupp variable {X} @[simp] @[simp] lemma to_finsupp_to_free_abelian_group (f : X →₀ ℤ) : f.to_free_abelian_group.to_finsupp = f := by rw [← add_monoid_hom.comp_apply, to_finsupp_comp_to_free_abelian_group, add_monoid_hom.id_apply] variable (X) /-- The additive equivalence between `free_abelian_group X` and `(X →₀ ℤ)`. -/ @[simps] def equiv_finsupp : free_abelian_group X ≃+ (X →₀ ℤ) := { to_fun := to_finsupp, inv_fun := to_free_abelian_group, left_inv := to_free_abelian_group_to_finsupp, right_inv := to_finsupp_to_free_abelian_group, map_add' := to_finsupp.map_add } variable {X} /-- `coeff x` is the additive group homomorphism `free_abelian_group X →+ ℤ` that sends `a` to the multiplicity of `x : X` in `a`. -/ def coeff (x : X) : free_abelian_group X →+ ℤ := (finsupp.apply_add_hom x).comp to_finsupp /-- `support a` for `a : free_abelian_group X` is the finite set of `x : X` that occur in the formal sum `a`. -/ def support (a : free_abelian_group X) : finset X := a.to_finsupp.support lemma mem_support_iff (x : X) (a : free_abelian_group X) : x ∈ a.support ↔ coeff x a ≠ 0 := by { rw [support, finsupp.mem_support_iff], exact iff.rfl } lemma not_mem_support_iff (x : X) (a : free_abelian_group X) : x ∉ a.support ↔ coeff x a = 0 := by { rw [support, finsupp.not_mem_support_iff], exact iff.rfl } @[simp] lemma support_zero : support (0 : free_abelian_group X) = ∅ := by simp only [support, finsupp.support_zero, add_monoid_hom.map_zero] @[simp] lemma support_of (x : X) : support (of x) = {x} := by simp only [support, to_finsupp_of, finsupp.support_single_ne_zero (one_ne_zero)] @[simp] lemma support_neg (a : free_abelian_group X) : support (-a) = support a := by simp only [support, add_monoid_hom.map_neg, finsupp.support_neg] @[simp] lemma support_zsmul (k : ℤ) (h : k ≠ 0) (a : free_abelian_group X) : support (k • a) = support a := begin ext x, simp only [mem_support_iff, add_monoid_hom.map_zsmul], simp only [h, zsmul_int_int, false_or, ne.def, mul_eq_zero] end @[simp] lemma support_nsmul (k : ℕ) (h : k ≠ 0) (a : free_abelian_group X) : support (k • a) = support a := by { apply support_zsmul k _ a, exact_mod_cast h } open_locale classical lemma support_add (a b : free_abelian_group X) : (support (a + b)) ⊆ a.support ∪ b.support := begin simp only [support, add_monoid_hom.map_add], apply finsupp.support_add end end free_abelian_group
[STATEMENT] lemma butlast_zip[simp] : assumes "length xs = length ys" shows "butlast (xs || ys) = (butlast xs || butlast ys)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. butlast (xs || ys) = butlast xs || butlast ys [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: length xs = length ys goal (1 subgoal): 1. butlast (xs || ys) = butlast xs || butlast ys [PROOF STEP] by (metis (no_types, lifting) map_butlast map_fst_zip map_snd_zip zip_map_fst_snd)
{- Agda can check termination of Stream transducer operations. (Created: Andreas Abel, 2008-12-01 at Agda Intensive Meeting 9 in Sendai, Japan. I acknowledge the support by AIST and JST.) Stream transducers have been described in: N. Ghani, P. Hancock, and D. Pattinson, Continuous functions on final coalgebras. In Proc. CMCS 2006, Electr. Notes in Theoret. Comp. Sci., 2006. They have been modelled by mixed equi-(co)inductive sized types in A. Abel, Mixed Inductive/Coinductive Types and Strong Normalization. In APLAS 2007, LNCS 4807. Here we model them by mutual data/codata and mutual recursion/corecursion. -} module StreamProcEat where open import Common.Coinduction data Stream (A : Set) : Set where cons : A -> ∞ (Stream A) -> Stream A -- Stream Transducer: Trans A B -- intended semantics: Stream A -> Stream B mutual data Trans (A B : Set) : Set where 〈_〉 : ∞ (Trans' A B) -> Trans A B data Trans' (A B : Set) : Set where get : (A -> Trans' A B) -> Trans' A B put : B -> Trans A B -> Trans' A B out : forall {A B} -> Trans A B -> Trans' A B out 〈 p 〉 = ♭ p -- evaluating a stream transducer ("stream eating") mutual -- eat is defined by corecursion into Stream B eat : forall {A B} -> Trans A B -> Stream A -> Stream B eat 〈 sp 〉 as = eat' (♭ sp) as -- eat' is defined by a local recursion on Trans' A B eat' : forall {A B} -> Trans' A B -> Stream A -> Stream B eat' (get f) (cons a as) = eat' (f a) (♭ as) eat' (put b sp) as = cons b (♯ eat sp as) -- composing two stream transducers mutual -- comb is defined by corecursion into Trans A B comb : forall {A B C} -> Trans A B -> Trans B C -> Trans A C comb 〈 p1 〉 〈 p2 〉 = 〈 ♯ comb' (♭ p1) (♭ p2) 〉 -- comb' preforms a local lexicographic recursion on (Trans' B C, Trans' A B) comb' : forall {A B C} -> Trans' A B -> Trans' B C -> Trans' A C comb' (put b p1) (get f) = comb' (out p1) (f b) comb' (put b p1) (put c p2) = put c (comb p1 p2) comb' (get f) p2 = get (\ a -> comb' (f a) p2)